commit 8bd8fa7a0be2331778f2a2842f39e40784ea8f67 Author: litruv Date: Tue Nov 3 18:20:25 2026 +1100 Snapshot of the Umamo working tree as it is Uploaded as-is from /home/litruv/dev/vtsmaker/umamo on 2026-11-03. 1347 files. Includes the uncommitted work in progress in :edit, :runtime, and :ui, and the untracked files under module/edit/src/jvmAndroidMain/. History is not carried over. The source repo is https://github.com/umamoorg/umamo. diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 0000000..c950c54 --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,340 @@ +# CLAUDE.md — Umamo + +## What This Is? + +Umamo is an open-source cross-platform rigging editor for 2D puppet animation, with first class pen and touch support, built as a drop-in replacement for the Live2D Cubism Editor. + +- **Language:** Kotlin, Kotlin Multiplatform (shared core across desktop + Android). +- **Package root:** `org.umamo` (reverse-DNS of the `umamo.org` domain). Shared library modules are flat — `org.umamo.format`, `org.umamo.runtime`, `org.umamo.interop`, `org.umamo.render`, `org.umamo.ui`, `org.umamo.reimport`. App code carries product + platform — `org.umamo.editor.desktop`, `org.umamo.editor.android` (a future viewer takes `org.umamo.viewer.*`); the headless diagnostic tool is `org.umamo.cli` (JVM-only). The editor's Android `applicationId` is `org.umamo.editor`, keeping bare `org.umamo` a clean umbrella. +- **Platforms:** Windows, macOS, Linux (keyboard/mouse/pen) **and Android tablets** (pen/touch — e.g. Wacom MovinkPad). Rigging is a first-class workflow on **all** of these, not desktop-only. +- **Headline workflow:** draw in Clip Studio Paint (or Photoshop), save/export, switch to Umamo, and the rig **refreshes against the updated art** without losing rigging work. +- **Compatibility is the product:** read and write the existing Cubism source format so riggers can adopt incrementally and interoperate with the official editor. + +## The Thesis (do not let this drift) + +v1's win condition is **a CMO3-native rigging editor that interoperates with the official Cubism Editor**: + +1. **Read and write `.cmo3`** (editor source) → a rigger can bounce the same project between Umamo and the official Cubism Editor without burning bridges. This bidirectional interop is the primary adoption wedge. +2. **Ingest source art** (PSD, CLIP, KRA with robust layer ID matching — see Re-import) and keep the rig live against art changes. +3. **GPU-accelerated, trustworthy preview** — the viewport deformation must match what a rigger would see in Cubism so they can trust what they're authoring. + +Runtime concerns (MOC3 emit, SDK/Core replacement) are a work in progress — see Format Support. If a proposed change trades away source-format compatibility or the refresh workflow for internal elegance, it is wrong by definition. Raise it, don't silently take it. + +## Format Support (priority order) + +- **UMA — read AND write, and the app's Open/Save.** Native Umamo format: a ZIP of per-domain JSON entries (the puppet graph with its bulk arrays in a buffer entry, the atlas with its pixel entries, the linked source art) under a manifest whose compatibility rules open a newer file read-only or carry what this reader cannot interpret byte for byte. `object Uma : FormatCodec` lives in `:format` `uma/`; `UmaDocumentBridge` in `:interop` `uma/` maps a document to and from `PuppetModel`; `UmaDocument` (`:ui` jvmAndroidMain `document/`) is what File > Open loads and `writeUmaDocument` is what Save writes, laid over the file as opened so unknown keys and held tiles survive; the save target lives in a `DocumentFile` beside the session, not on the document. Editor state (`editor/state.json`, never an input to the model) rides each save as a merge patch: per-area view state and cameras through `AreaViewStates` (`:ui` `workspace/`), keyed by the layout's area ids, and the session's pose, selection, mode, cursors, and tool settings through `SessionViewState` (`:edit`), laid into the session's first snapshot so nothing restored is an undo step. Spec: `docs/format/UMA.md`; decisions and roadmap: `docs/plan/uma-format.md`. +- **CMO3 — read AND write, with edit-to-CMO3 lowering.** A CMO3 is the native format for the Cubism editor, and an interop boundary for Umamo: the UI offers it as Import/Export (Open/Save is reserved for UMA). `Cmo3.write` round-trips an unedited file's **decompressed `main.xml` byte-for-byte** — not the whole file; see the Fidelity contract. Export is a **state-based reconcile**: `Cmo3Export.apply` (`:interop` jvmAndroidMain) re-imports the retained graph as a baseline, diffs the session's model against it, and patches only what changed — flat fields, base geometry/UVs, the keyform grid web (re-bundled via `refinedToUnion`), blend shapes, and structural create/delete for every entity category. A MOC3-origin document (no retained graph) exports through **fresh-graph synthesis**: `Cmo3Conversion.freshCmo3` builds a blank BareMinimum-shaped skeleton plus a per-page image chain and runs the SAME reconcile against the empty baseline. Anything unrepresentable surfaces as an `ExportNotice`, never a silent drop. See `docs/format/CMO3.md` § Export. +- **PSD — read.** Layered-art ingestion. Re-import join key is the lyid layer id when present (Photoshop-written, stable across rename/reorder), else layer name/path + order (lossy; some exporters omit lyid, so CLIP/KRA with always-present stable ids stay more robust). See `docs/format/PSD.md`. +- **CLIP (Clip Studio Paint) — read.** Layered-art ingestion, proprietary (SQLite-based container). Implemented: layer tree + raster decode, registered in `FormatRegistry` with corpus-backed tests. See `docs/format/CLIP.md`. +- **KRA (Krita) — read.** Layered-art ingestion, open source format. See `docs/format/KRA.md`. +- **MOC3 — read AND write.** Serialized C structs (memory-cast, so byte-exact layout). See `docs/format/MOC3.md`. +- **JSON family**: `model3` (manifest), `physics3`, `cdi3`, `pose3`, `exp3`, `motion3`, `userdata3`, texture atlas. + +PSD/CLIP/KRA (and flat rasters, wrapped as one layer) come in through **File > Import > Artwork…** (or the Sources space's button — one command, `file.importArtwork`), which ADDS the file's layers to the OPEN document as one undo step, Blender-style, rather than replacing it: the editor always has a document, starting with the empty one it opens into. `SourceArtImport` (`:interop` `org.umamo.interop.art`) is the source-art → `PuppetModel` bridge — one drawable per raster layer over a quad birth mesh, one part per folder, the source-layer binding persisted on the tile (`AtlasTile.source`) with the file and its layer inventory on `PuppetModel.sources`. A rig's FIRST artwork also gives it the file's canvas, the world origin at that canvas's center, and the parameters of the `import.parameterTemplate` setting (Humanoid by default); a later file is placed on that canvas by the import's Align anchor and Offset rows on the operation strip (its record keeps the offset as `ArtSource.offsetX/Z`, x right and z up like the viewport, and every later read of the file is placed by it before the model sees the art), packed into the gaps with existing art held fixed, and redefines neither. A CMO3 export of such a document runs the fresh-graph synthesis with the document's own rasters, so the CMO3 carries the real layers and folders and reopens keyed by lyid (Phase H1); a CMO3-origin document's reloaded and added art is written into its retained graph the same way (H2); a MOC3-origin export still slices its layers out of the pages. See `docs/plan/art-sourcing-pipeline.md` Phase E. + +**Unified codec contract.** Every binary container format presents the same face to the rest of the project: a `FormatCodec` in `:format` (`kind`/`matches`/`read(ByteArray)`/`write(TModel)`, tied to `FileKind`), with `FormatRegistry` doing detect-by-magic and resolve-by-kind. CMO3 (`object Cmo3`, in `jvmAndroidMain` — JDOM/reflection are JVM-only) and MOC3 (`object Moc3`, `commonMain`) both implement it; the in-memory model type differs per format and shares no supertype (hence the generic). The **JSON sidecars are `String`-shaped, not bytes**, so they deliberately sit *outside* the codec contract as plain helpers on `Moc3` (`readModel3`/`writeModel3`/…). Add a format by implementing the interface and registering it — never by growing a bespoke read/write facade. + +## Architecture + +### UI: Compose Multiplatform + Embedded GPU Viewport + +The editor UI is **Compose Multiplatform** — Jetpack Compose on Android, Compose Desktop (Skiko) on Win/Mac/Linux. One UI codebase, idiomatic pen/touch/gesture input. **Not ImGui** (desktop/mouse-only, no Android pen story). **Not Swing/JavaFX** as UI. + +The puppet canvas is a **GPU surface composited into Compose**: +- Desktop (shipped): LWJGL renders offscreen through a hidden GLFW context; the frame is copied into a Compose `Image` — there is no Swing/AWT interop in this path. See `OffscreenPuppetService` / `:desktop` in the module graph. +- Android (not yet implemented): the target is a GLES surface composited the same way; today `:android` mounts the shared shell with a null viewport factory, so viewport areas render placeholders. See `:android` in the module graph. + +**Pen input (design target, not yet implemented):** no stylus/pressure/tilt code exists anywhere in the repo yet. The intended split is Android stylus (`MotionEvent` pressure/tilt/hover) as the easier target, desktop JVM pen as the harder one (plan for JPen or Wintab/Windows Ink). + +### Panels & docking + +**One interface, desktop and tablet.** The same edge-docked UI runs everywhere, modeled on Krita and Clip Studio Paint's desktop mode — both run their full desktop UI on Android tablets, and that is sufficient. There is **no separate slim tablet UI to maintain.** The tablet gets a touch-tuned _skin_ of the same interface, not a second front-end: larger hit targets, more panels collapsed-to-rail by default, the pen radial menu carrying tool switching, and the menubar folded into an overflow rather than a top strip. + +**Blender-style area tree, not free-floating**: +- The window content is a **recursive binary-split tree of areas**. Each area hosts exactly one **editor space** — the ten `SpaceKind`s are 2D viewport, UV editor, sources (the source-art linking table), outliner, parameters, keyform sheet, properties, tool details, history (undo stack, click an entry to jump to that state; deformers live in the outliner/parameters, not a separate space), and logs — and the space is **agnostic and switchable at runtime** via a dropdown in the area's top-left header — any area can become any space (turn the outliner into a tiny viewport if you like, exactly like Blender). +- Areas split along any edge into nested areas and merge/close; **splitters are draggable** with a min-size clamp; a Blender-style **corner-drag gesture joins two adjacent areas** back into one. +- A window holds **multiple named workspaces as tabs** (create/duplicate/rename/reorder/reset), each with its own area tree; a single workspace or the whole layout can be exported/imported as text. +- Each area also has a **right-click context menu** mirroring its header actions plus "Change Editor Type." +- **Free-floating / tear-off windows remain out of scope** — everything is tiled inside the window; this keeps the layout engine small. +- An area's shape does not restrict which space it may host (no "tall panels left/right, wide panels top/bottom" rail constraint). + +Concretely the shell is `org.umamo.ui.workspace`: a sealed `AreaNode` (split/leaf) tree per `Workspace`, rendered by a recursive Compose layout (`AreaTree`/`SplitContainer` + a draggable `Splitter`) — a tractable custom layout, not an IDE-grade free-float dock manager. Row drag-and-drop inside a space (the outliner, the parameters panel, the Sources table) is one shared kit in `org.umamo.ui.workspace.rowdrag`: the drag controller and hit-test, the Escape cancel seam, the long-press pickup, the cursor chip, and the drop-target ring; a space adds only its payload type and its drop rule. The 2D GL viewport stays platform code in the app, injected into a leaf via a `ViewportHost` seam (per-area surface kept alive across tree mutations with `movableContentOf`). + +**Defaults carry the opinion.** Each workspace ships a curated default area tree (Modelling = parameters, a viewport over the keyform sheet, and outliner over properties; Texture = stacked UV editors, a viewport, and a sources/outliner/properties column); user rearrangement is the customization layer on top, persisted to settings `interface.layout`; "reset layout" reseeds the defaults. This is how the tool stays focused while configurable — the workspaces own the good arrangements, so configurability is the escape hatch, not the primary interaction. + +### The tool surface is small and bounded + +2D rigging is not a tool-complex process. So the panel inventory is knowable up front: + +- **Canvas / viewport** — the GPU work surface. +- **Parts** — drawable + deformer hierarchy (with a Project view: source-image → model-image binding). +- **Parameters** — the rigging cockpit (sliders, multi-key 2D pad, keyform binding). +- **Properties** — a tabbed mega-panel over the document and the selected item: Document (canvas, runtime targets), Object (transform, relations), Data (type-specific — mesh/texture/blend, deformer, part), with a header search that filters to matching rows. Tabs come from an extensible `PropertyTabRegistry`, so a section is registered, never wired into a render switch. +- **Keyform sheet** — per-(item, channel) tracks over the parameter targeted in the Parameters panel. Its track widgets live in `org.umamo.ui.tracks` and are **domain-agnostic on purpose** (`TrackAxis` is the only place a domain appears), so the later time-based animation dope sheet reuses them; nothing about parameters, keyform grids, or `PuppetModel` may appear in that package. The `dopesheet` serialization key is deliberately left free for that editor. +- **Tool details** — context for the active tool. +- **History** — undo-history stack; click an entry to jump to that state. +- **Sources** — the source-art linking table: artwork file → layer (inventory as of the last read) → tile → drawables, each row tinted by status (present/missing file, bound/bound-by-name/unbound, placed/unplaced) with a filter. Dragging a layer row onto a tile row (or the reverse) rebinds it; Import Artwork…, Reload, Replace Artwork…, and Match Automatically each land as one undo step, with a Match Threshold row on the operation strip where matching applies. An unbound layer's chip can ignore it (a reload then never re-mints it). See § Re-import below for the reconcile/matcher mechanics. +- **Logs** — the diagnostic console. + +Animation later adds wide, bottom-docked panels (timeline, keyframe/graph editors). Because the set is small and known, the dock shell can be defined early without churn — but get the core rigging working in the default layout first; freeform rearrangement is a fast follow, not a prerequisite. + +### Commands, key bindings & input + +A central **action registry** is the spine of input: every operation is a named command (`mesh.subdivide`, `param.addKeyform`, `view.fit`, …). Menus, the toolbar, the pen radial menu, and keyboard shortcuts **all dispatch through it** — nothing hardcodes a handler. Design this in early; it's cheap up front and painful to retrofit after handlers are wired directly. + +- **Editable, persisted keymaps** with presets — default, a **Cubism-like** preset (so migrants keep their muscle memory), and a **Blender-like** one (matches the editing model we're borrowing). Detect conflicts; scope bindings per mode/context where a key's meaning differs. +- **Bindable inputs are not just the keyboard, in principle:** the design allows stylus barrel buttons, tablet express keys, and mouse buttons to bind to actions too, so a keyboardless tablet can still reach every command. Not yet wired — today only keyboard chords resolve through the keymap. +- Store a logical **primary modifier** (→ Cmd on macOS, Ctrl elsewhere), not a literal "Ctrl"; bind by **key position**, not character, so shortcuts survive non-QWERTY layouts. +- A searchable **command palette** falls out almost free from the registry — a strong discoverability / onboarding aid for rigging's harder abstractions. +- **Pie/radial menus** (`PieMenuKind` — pivot mode, snap, merge-target, …) are a second dispatch mechanism alongside the palette, built for pen/touch reach rather than search. + +Implemented (`:ui`'s `org.umamo.ui.action`): `Command`/`CommandHandler`/`CommandRegistry` (as `LocalCommands`), chords via `KeyChord`/`parseKeyChord` resolved through a `Keymap` (key position + a logical primary modifier). `org.umamo.ui.workspace.commands` holds every command table, one file per domain, each a builder returning `List` registered through `registerAll` (which returns the matching cleanup, so registration and unregistration can't drift apart). A `Command` also declares the spaces it belongs to (`spaces: CommandSpaces`, read off what its handler's routing really does, never narrower) and an optional short status-bar `hint`; both filter the palette and the status bar only — dispatch and the keymap never read them. A `Command(...)` built anywhere else is a bug — the table is the declaration, the handler just a lambda; that split is why the app's `file.*` tables stay in this commonMain package while the document loader behind them lives in `jvmAndroidMain` (`org.umamo.ui.app`'s controllers); `logs.export` and the `workspace.*` file commands need only a picker, so the settings-backed shell registers them. + +`commands/CommandRouting.kt` is the one place a command resolves "which area does the pointer mean," backed by a single hovered-surface resolver (`Modifier.stampsHoveredSurface`, installed once by `AreaLeaf` so every space kind is covered automatically). There is no viewport-only fallback: a command needing a viewport that finds none does nothing rather than reaching back to one the pointer has left (Blender's hovered-area rule). A request that must execute in one specific area carries that area in its payload instead (`SnapRequest`, `SelectLinkedRequest`, `UvSnapRequest`), so each overlay collector gates on its own id. + +`handleShellKey` is the live dispatch path (`KeyChord` → `Keymap.commandFor` → `registry.invoke`); `CommandPalette` lists `registry.all()`. New operations register a `Command` and bind a chord — never wire a handler into a widget. The keymap itself is editable and persisted via `KeymapPersistence` (`default`/`cubism`/`blender` presets plus per-command overrides, reactive), with a keybindings editor in Settings. + +### Localization (EN/JA/KO) + +The audience is heavily Japanese and the primary developer is bilingual — so **EN + JA are first-class from day one**, not retrofitted. Compose Multiplatform's resources system (`stringResource`, per-locale resources) is the mechanism. + +- **Externalize every UI string** from the start; no hardcoded literals. Build the pipeline for *N* locales, not just two. +- **Localize chrome and display names — never format-level identifiers.** Parameter IDs like `ParamAngleX` are part of the CMO3/Cubism data model and stay verbatim for interop; `cdi3.json` display names and the user's own part names are user data, not ours to translate. Two layers: Umamo's UI (we localize) vs the document's names/IDs (we don't). +- **CJK gotchas to test deliberately:** Skiko font fallback must cover JA glyphs on desktop *and* Android (bundle a CJK-capable font). Don't assume EN string widths in the dock/panel layout. +- RTL is out of scope for v1, but don't structurally preclude it. + +### Settings, storage & the app shell + +The **settings/storage foundation is built first** — it backs keymaps, layout, theme, and recent files, so nothing hardcodes config that has to be ripped out later. Two modules: + +- **`:storage`** — per-OS config/data directories + file IO over **okio** (Kotlin's stdlib has no common `File`; `java.io.File` is JVM-only), and a `FilePicker` open/save-dialog contract backed by **FileKit** — one commonMain `FileKitFilePicker` over each OS's native dialog (Win32 `IFileDialog`, Cocoa, GTK/portal) plus Android SAF, replacing the old desktop-only AWT `FileDialog`. Because FileKit already spans platforms there is no per-platform picker impl: desktop is done, and Android needs only `FileKit.init(activity)` in its `Activity` (it owns the result registry) — no separate SAF implementation. The contract returns FileKit's `PlatformFile`, not an okio `Path`: Android SAF hands back a `content://` URI with no real filesystem path that a `Path` cannot model. Platform factories `desktopAppStorage` / `androidAppStorage` resolve the dirs. +- **`:settings`** — a JSON tree of **bundled defaults ← user overrides** (← vendor extension defaults, later), addressed by **dotted keys** (`getString("interface.theme")`). No caller passes a default — `defaultSettings.json` (a Compose-MP resource in `:ui`, shared cross-platform) is the single baseline. Writes hit the *user* layer only, persist via `:storage`, and emit the changed key on a `changes: SharedFlow` (the reactive spine the UI / keymap / undo-History collect). Held as a dynamic `JsonObject`, not typed `@Serializable` classes (settings are open-ended + merged); typed per-domain views layer on later. Namespaces in use today: `interface.*` (theme, the undo-step cap pushed into `EditorSession.historyLimit`, the workspace area-tree layout, window geometry, viewport toolbar/sidebar visibility), `input.keybinding.*` (the keymap preset + overrides), `viewport.*` (zoom steps, selection/warning/pinned colors, grid, the `meshEdit.*` mesh-edit colors), `localization.locale`, and `import.*` (`parameterTemplate`, `alignment`, `watchMode`, `deleteArtIgnoresLayer`, `layerPositionsFromWorldAxes` — see § Re-import). See `defaultSettings.json` for the exact key list; `app.launchCount` and `input.pen.backend` are reserved there but genuinely unread/unwritten today. + +Apps load settings at startup and provide the instance through a `LocalSettings` composition local — the desktop loads **synchronously** so the saved window state is ready before the (unconditional) window opens; `application {}` exits if it ever has zero windows, so an async settings gate would close it. The **app shell is shared in `:ui`** (`org.umamo.ui.app`, jvmAndroidMain - `EditorApp` is wiring only, over one controller per responsibility: save, open, export, artwork, the source watcher): the File / Edit / Workspace / Help menu bar, a Preferences window (`edit.preferences`, holds the keybindings editor and other settings sections), Help Credits/About, the `Document` layer (CMO3/MOC3 import and CMO3 export via FileKit — Open/Save is reserved for UMA — recent files, the dirty-replace confirm, the export report alert), live locale switching, live keymap reload on preset/rebind, and the per-document session wiring. `:desktop` owns the window (geometry persisted to settings, title dirty-marker, the LWJGL offscreen render service); `:android` owns the Activity and mounts the same shell with a null viewport factory until the GLES renderer lands — Android does have renderer groundwork (`GpuRenderer.android.kt`: GLES20/30 grid + axis shaders), just not a puppet-deformation renderer or the Compose-image bridge yet. + +**Use the foundation, don't reinvent it:** new config (a keymap preset, a panel layout, a pen binding) is a settings key under its namespace via `Settings`; file open/save goes through `FilePicker`; app-data paths come from `AppStorage`. + +### Deformation (the core math) + +Parameter-driven morph blending, **not** skeletal: `p = base + Σ wᵢ·Δᵢ`, multilinear interpolation across an N-dimensional grid of keyforms. Warp deformers are FFD lattices; rotation deformers are a nesting pivot-transform hierarchy. Weights are computed CPU-side per frame (cheap; depend only on parameters); the per-vertex weighted delta-sum runs in a vertex shader. None of this maps onto any engine's built-in rig — it is ours. + +### Mesh-editing interaction model + +Mesh and keyform-deformation editing should feel like **sculpting, not CAD**, adopting Blender's UV-editor interactions. + +- **Proportional editing — shipped.** Moving one vertex drags its neighbours within an adjustable radius, with six selectable **falloff curves** (smooth / sphere / root / sharp / linear / constant) plus a geodesic "connected only" mode that follows mesh edges instead of screen-space distance (`module/edit/.../ProportionalEditing.kt`). +- **Brush radius for grab / smooth / relax — not yet implemented.** The only existing brush-radius tool today is circle-select, a selection brush, not a vertex-manipulation one; there are no grab/smooth/relax sculpt operators yet. +- **Pen-pressure-driven brush radius / falloff strength — not yet implemented.** No pressure/tilt input is wired anywhere in the codebase yet (see the Pen input note above); this stays the target pen-first advantage over Cubism's click-drag-per-vertex model once it lands. + +### Project format & source model + +CMO3 does **not** store the original `.psd`. On import Cubism **decomposes** the PSD into an editable, equivalent representation: a `CLayeredImage` tree of `CLayerGroup`/`CLayer` nodes, each layer's pixels stored as a separate embedded PNG (`CImageResource` → `imageFileBuf*.png`), positionally mapped. PSD is still the privileged *source* throughout the Cubism pipeline (mesh and model-image derive from it). That privilege is incompatible with first-class **CLIP** and **Krita (.kra)** support, so: + +- Umamo's **native project format is source-agnostic.** PSD, CLIP, and KRA are peer sources, each retaining its own **stable layer identity** (CLIP / Krita layer IDs; PSD's lyid layer id when present, else name + order). +- **CMO3 is an interop boundary, not the native format.** A shim unwraps CMO3's decomposed layer images (the `CLayeredImage` tree + per-layer PNGs) on import and synthesizes that decomposed, PSD-derived shape on export, so CMO3 round-trip still works. +- **Do not shim CLIP/Krita down to PSD on import.** That discards the stable layer IDs that make non-destructive re-import reliable — i.e. it throws away the exact reason CLIP support is worth having. The source-agnostic native model is what preserves them. + +This refines the thesis: CMO3 read/write stays primary (Cubism interop), but it is a *conversion at the boundary* layered over a custom native format — not the format you work in. The container is specified in `docs/format/UMA.md`, and File > Open/Save read and write it — see Format Support. + +### Re-import / source-art binding (the headline feature's hard problem) + +"File refreshes" = **non-destructive re-import keyed on stable layer identity**. Each drawable is bound to a source layer by a stable key (CLIP/Krita layer ID, or PSD's lyid when present; else PSD name/path + heuristics). On a watched-file change, reconcile: +- **Matched layer:** update its atlas region; preserve mesh/deformers/keyforms where topology still fits. +- **Moved/resized art:** adjust extents/UVs if possible; otherwise flag for re-mesh. +- **Added layer:** new unbound drawable. +- **Removed/renamed layer:** **never silently delete rig work** — flag, fuzzy-match, and make reconciliation reviewable (a diff/merge step). + +This is where Live2D's own reimport is lossy; doing it well is a competitive feature. + +**Status: Phase F is complete** — the binding is persisted and editable, and the reconcile by key (F1), the watcher (F2), and the fuzzy matcher with its review states (F3) are all built. The identity is ONE representation: the reader's `LayerId.raw` is the key and the reader says how strong it is (`SourceLayer.idIsStable`); it persists on the tile as `AtlasTile.source: SourceLayerRef`, and the document lists its artwork files with their pixel-free layer inventories as `PuppetModel.sources: List` (the baseline a reconcile diffs against). `:reimport` holds the pipeline: `KeyReconciler` classifies bindings by key and `ArtworkReloadPlanner` turns the matched/added layers into an `ArtworkReload` the session applies and the UI packs and commits — a changed layer's tile is superseded by a new tile rather than mutated (pixels are immutable per tile id, so undo and the CMO3 export both follow the lineage root), and a removed layer is left alone, flagged for review, never dropped. `PollingSourceWatcher` + `SourceWatchCoordinator` (F2) settle a save, hash the file so an unchanged save costs nothing, and dispatch a reload under the `import.watchMode` setting (auto/notify/off); a file edited while the document was closed is reported at open, never auto-reloaded. `InventoryLayerMatcher` (F3) ranks a lost binding's candidates over the inventory (name, folder, bounds, size, content hash, and pixel similarity when the file was read) to drive the Sources space's review chips and Match Automatically. Still absent: a reader and watcher for Android's SAF uris. See `docs/plan/art-sourcing-pipeline.md` § Phase F for the full mechanics. + +### Module graph (Gradle, Kotlin DSL; KMP) + +``` +:format commonMain — Cubism file family + art I/O. CMO3 (read/write), PSD (read), + CLIP (read), KRA (read), MOC3, JSON family. +:reimport commonMain — non-destructive reconcile over the model's source bindings: the + key reconciler, the reload planner (a changed layer's tile is + superseded, never mutated), the okio polling file watcher, the watch + coordinator (settle, hash, idle gate), and the inventory matcher with its + suggestions (names, folders, bounds, hashes, pixels). All commonMain - + nothing JVM-bound. + → :format, :interop, :storage, :runtime (api), kotlinx-coroutines (api) +:storage commonMain — app config/data dirs + file IO (okio) + native open/save dialogs + (FileKit, one commonMain FilePicker impl); platform factories in + jvmMain/androidMain (no expect/actual). → okio, FileKit +:settings commonMain — JSON settings engine: bundled defaults ← user overrides, dotted-key + get/set, persistence, change-event Flow. → :storage, kotlinx-serialization +:runtime commonMain — the pure puppet runtime: the immutable PuppetModel + typed ids, the + keyform grid algebra, the sampling eval, and the atlas domain (PuppetAtlas: + pages + tiles, each tile's AtlasPlacement, plus the uv-affine algebra that + maps between the art's frame and a page's). The placement lives here, not + in :render, because it is authored state every consumer needs — including + the CMO3 export lowering, whose module deliberately cannot see :render. + Zero format knowledge and zero project deps — CMO3/MOC3 conversion lives + in :interop. +:interop commonMain — format↔runtime conversion: CMO3/MOC3 ingest (Cmo3Import / Moc3Import → + PuppetModel), the model diff (diffPuppetModels), export notices, and the + RuntimeTarget↔format-version mapping; jvmAndroidMain hosts the CMO3 + export reconcile (Cmo3Export: diff-driven lowering onto the retained + graph) and the fresh-graph synthesis (Cmo3Conversion: blank skeleton + + image chain for MOC3-origin export). Future import/export formats and + format↔format conversions (each pivoting through PuppetModel) land + here too — including each format's atlas-page walk (`cmo3AtlasPages` / + `moc3AtlasPages` → a neutral `AtlasPageSet`), so :render never sees a + container format. `art/` is the source-art → PuppetModel bridge + (`SourceArtImport`: an UNPACKED model the app packs at open, the blend + table, the import notices; it seeds the parameter list it is handed and + knows no template). + → :format (api), :runtime (api) +:edit commonMain — the editing session over the immutable PuppetModel: EditorSession + (snapshot-based undo History, selection + mode state, tool latches, + request buses), the sealed Change hierarchy, the pure edit ops + (mesh topology/transforms, parameter edits, proportional editing), and + the seed catalogs a new model starts from (`seed/`: ParameterTemplate + + the humanoid standard set). + → :runtime (api), kotlinx-coroutines (api) +:render commonMain — deformation eval (CPU) + the puppet renderer + morph-blend shaders, + + GL impl over a `RenderDevice` backend seam. → :runtime (api), :format (api). + The whole renderer is backend-neutral commonMain now: the eval, the pure + render logic (`puppet/`: glue layout, pose resolve, model diff, delta + texels, bounds), the GL-family GLSL (`glsl/`, shared by GL 3.3 + GLES 3.0 + via a `GlslDialect`), the `RenderDevice` API (`device/`: handles, specs, + uniform structs, frame/pass encoders), and `PuppetRenderer` itself, which + makes ZERO GL calls — every GPU op goes through `RenderDevice`. A backend + is one `RenderDevice` impl: `GlRenderDevice` (jvmMain, LWJGL/GL 3.3 core) + ships; GLES 3.0 (android) + Metal (iOS) are ports of it, stubbed. `:render` + is zero `expect`/`actual` AND has no jvmAndroidMain — outside the backend + impls it is all commonMain. PNG decode goes through :format's `PngCodec` + (the old `decodePngToRgba` expect/actual is retired). :format is a + direct commonMain api dep — but for the NEUTRAL raster layer only + (RasterImage in the RenderDevice upload surface, PngCodec behind the atlas + decode). :render knows no CONTAINER format: the CMO3/MOC3 walks that + produce a document's atlas pages live in :interop and hand back a neutral + `AtlasPageSet` (page bytes + a drawable→page map), which the document + loader feeds to `buildPuppetTextures` here with its format's + `UndecodablePagePolicy` — CMO3 skips a bad page, MOC3 fails the import. + LWJGL is DESKTOP-ONLY. + The CPU eval (`eval/`) depends on nothing in :render and would move to + :runtime cleanly — it stays here ON PURPOSE, paired with the GPU deform + shaders it mirrors and that the differential oracle diffs it against. + That is why :ui, not :edit, owns the world-space transform helpers + (`org.umamo.ui.transform`): :edit and :render are siblings over :runtime. +:ui commonMain — Compose Multiplatform editor UI (panels, tree, timeline, parameter + grid) AND the shared app shell: the viewport composables + gizmo overlay + (`org.umamo.ui.viewport`, over the `PuppetViewportService` seam) in + commonMain, and a jvmAndroidMain (same pattern as :format) hosting the + document/file layer + shared `org.umamo.ui.app.EditorApp` — the + JDOM-backed CMO3 codec forces those off commonMain. + EDITING LOGIC OVER `EditorSession` DOES NOT LIVE HERE — an `EditorSession` + extension belongs in `:edit` (that is what the module is), and :ui keeps only + the pointer/composition bookkeeping that feeds it plain data. The ONE + exception is `org.umamo.ui.transform`, which needs :render's eval and so + cannot sit in :edit (see the :render note above). Reference split: + `KeyformCommands.kt` (:ui, resolves the hover) over `KeyformAimEdits.kt` + (:edit, decides what the edit means). + → :render (api), :runtime, :interop, :edit, :settings, :storage, :format (jvmAndroid). +:desktop jvm — thin desktop entrypoint over the shared EditorApp: the window, settings + gate, and the LWJGL offscreen `PuppetViewportService` (GLFW hidden + context → Compose Image; no SwingPanel/AWTGLCanvas interop remains). +:android android — thin Android entrypoint (Activity) over the same shared EditorApp; + the GLES `PuppetViewportService` implementation is pending — viewport + areas render placeholders until it lands. +:cli jvm — headless diagnostic tool: dump / extract / atlas / convert / diff over + cmo3, moc3, and source artwork files. An operator's tool, not a + shipping app target, so it skips :ui and :edit entirely. + → :interop (api brings :format, :runtime), :render +``` + +**On disk:** library modules live under `module/`, application targets under `app/` (e.g. `module/format`, `app/desktop`); everything else at the repo root is intentionally non-module. A module's Gradle path (`:format`, `:desktop`) is kept **flat and decoupled from its folder** via `projectDir` in `settings.gradle.kts`, so dependency declarations stay terse (`project(":format")`) and *path ≠ directory ≠ package*. Stretch-phase modules follow the same scheme. + +Keep `:format`, `:reimport`, `:runtime`, `:interop`, `:edit`, `:ui` in `commonMain` so Android and desktop share them verbatim. Platform-specific code (GPU contexts, FFI, pen, windowing) lives in `jvmMain` / `androidMain`. + +**Build logic that more than one module needs is a convention plugin, not a copied block.** `gradle/build-logic` is an included build (not `buildSrc` — the configuration cache is on, and a `buildSrc` edit invalidates the whole build) exposing three plugins a module opts into by id: + +- **`umamo.kmp-jvmandroid`** — creates the `jvmAndroidMain` source-set group shared by the desktop-JVM and Android targets, and wires `androidMain` onto it explicitly (the hierarchy template's `withAndroidTarget()` matches the LEGACY android target, not AGP 9's KMP android-library target, so without the edge Android silently cannot see the group). Applied by `:format`, `:interop`, and `:ui`. +- **`umamo.kmp-ios-gate`** — makes `check` depend on `compileKotlinIosArm64` AND `compileTestKotlinIosArm64`. A device target has no runnable test task, so neither compile joins `check` on its own and the commonMain-purity guarantee silently stops firing. Applied by every module with an `iosArm64()` target. +- **`umamo.test-corpus`** — the golden-corpus / `-D` forwarding for sample-gated tests, declared per module in a `umamoTestCorpus { }` block. Explicit `-D` wins (resolved against the REPO ROOT, and a path that does not exist fails the build); the local gitignored corpus is the default; absent both, the test self-skips and CI stays green. The shared default table lives in `org.umamo.buildlogic.sharedCorpusDefault` — add a property there only when it means the same thing in every module. + +The failure mode these guard against is the same one throughout: a gated test that cannot find its input prints and returns, so it reports PASSED while covering nothing. Never let a module hand a Test task a sample path by hand. + +## Fidelity contract + +Two tiers — conflating them is the classic mistake. + +- **Semantic validity — CMO3 (v1 primary).** Emit a valid CAFF container whose `main.xml` encodes the same object graph; the official editor's XML deserializer rebuilds it. Whole-file byte-identity is **not** the bar and is not achieved: re-emitting an unedited corpus model differs from the original (one 4-byte field per CAFF entry), and an edit would change the bytes by construction anyway. What IS asserted, and what the tests actually check, is **decompressed-content identity**: `main.xml` inflated out of a re-emitted file is byte-for-byte the `main.xml` inflated out of the original (`Cmo3FacadeTest`, `ModelDocumentTest`, `AllVersionsGateTest`), with zero unmodeled tags (`CoverageGateTest`). Do not "restore" a whole-file byte-identity claim here — it was checked against the corpus and is false. Neither writer is byte-reproducible, ours included, and that is on purpose: the editor stamps a local wall clock into each compressed blob's zip timestamp (the corpus sample reads 2022-06-06 17:03:30) and **we stamp one too**. Pinning that field to a constant would buy us determinism, but the official editor's reader is fragile and does a lot for cross-version compatibility — **when in doubt, write what the editor writes**; a convenience of ours never outranks matching its bytes. See `docs/format/CMO3.md` §1. **Round-trip is the bar:** open a corpus model, re-save, reopen in the official Cubism Editor, assert no semantic loss (mangled physics or a dropped deformer subtree kills the migration promise). +- **Preview parity — geometry (v1 primary).** The viewport deformation must visually match the Cubism Editor's own preview within tolerance. Computed geometry is **bounded ULP / visually identical**, never bit-identical (scalar vs SIMD vs GPU diverge by construction). + +Maintain a **golden corpus** of real `.cmo3` (and later `.moc3`) models. Never add a format version to the supported set without a corpus sample exercising it. + +## Tech stack (and why) + +- **Kotlin + Kotlin Multiplatform + Gradle (Kotlin DSL).** Android reuse; large accessible contributor pool; JVM reflection + JDOM make the CMO3 XML serializer (read *and* write) tractable on both desktop and Android. +- **Compose Multiplatform** for UI (Android + Desktop, pen/touch native). See Architecture. +- **FileKit** for native open/save dialogs — one Kotlin Multiplatform API over each OS's native picker (Win32 `IFileDialog`, Cocoa, GTK/portal) plus Android SAF, behind `:storage`'s `FilePicker` contract. +- **GPU:** LWJGL on desktop (GL/Vulkan + GLFW, behind interop); GLES/Vulkan on Android. **Baseline:** GL 3.3 core (desktop, `#version 330 core` shaders, GLFW core-profile context) / GLES 3.0 (Android, needed for VAOs). +- **CMO3:** CAFF container codec + reflection-driven XML serializer (JDOM 1.x, Kotlin reflection); JVM-and-Android (`jvmAndroidMain`) +- **C++ Core FFI (stretch):** `:core-bridge` behind one interface — Panama (`java.lang.foreign`) on desktop, **JNI/NDK on Android** (Android does NOT ship the FFM API). Never put `java.lang.foreign` in shared/Android code paths. + +## Build & run + +See README.md for build instructions. + +The official Cubism Core/SDK/Editor are **external dependencies of the harness only** — never committed, vendored, or linked into shipping artifacts. Never attempt to reverse engineer the official Cubism Core, SDK, or Editor. + +## Code style + +- **Indentation: tabs.** Set `.editorconfig` `indent_style = tab` and configure ktlint to match (overrides Kotlin's space default). +- **Naming:** `lowerCamelCase` functions/values, `PascalCase` types (matches Kotlin convention). Naming for functions and variables (including local variables, function parameters, and loop counters) is verbose and descriptive: `bitFlip`, never `bf` or `bFlip`. Single-letter names are NOT acceptable for loop counters (`i`/`j`/`k`) — use a name that reflects what's being iterated (`pageIndex`, `slotIndex`, `wordIndex`, `lineIndex`). Single-letter dimensions are NOT acceptable: `h` could be `height` or `hue`, so write `width`, `height`. Single-letter aliases for locals inside function bodies are NOT acceptable either (e.g. `b` for `backend`, `s` for `status`, `v` for a register value, `p` for a pointer) — give the local a descriptive name. Some abbreviation is okay as long as it is not ambiguous, such as `rect` for `rectangle`. Permitted short names: `x`, `y`, `z` for coordinates (universal graphics idiom); `r`, `g`, `b` for color channels ONLY when the enclosing function/struct name disambiguates (e.g. `paletteRgbToGrbi(uint8_t r, uint8_t g, uint8_t b, ...)` — the `Rgb` in the name makes the parameters self-documenting). Use US English for spelling, example: "Color", not "Colour". +- **World axis names:** the viewport convention is X right, Y forward, Z up, so a name that says it is world space calls its vertical axis Z (`worldOriginZ`, `Cursor2d.worldZ`, `screenToWorldZ`), never `worldY`. Space-agnostic math (`[x, y]` arrays, `MeshBounds`, GLSL `vec2`), canvas / screen / UV / NDC names, and the deform eval's pre-negation space keep y. See `PuppetModel.worldOriginX`. + +- **Comments:** English; about *why*, not *what*. +- **Format-citation discipline:** any code reading/writing a format field MUST cite the spec location, e.g. `// CMO3: field ` or `// MOC3 v4 §3.2 @ +0x18`. This is the format analogue of register-citation discipline — every byte traceable to docs, and it protects the clean-room story. +- Model format versions and deformer kinds as **sealed classes/enums**; match exhaustively so the compiler enforces coverage. No accidental nullability. +- Prefer `expect`/`actual` over `if (platform)` for desktop/Android splits. +- Braces are MANDATORY on EVERY `if`, `else if`, and `else` — including single-statement bodies. The body always goes on its own line inside `{ }`. The brace-less one-liner form is NOT allowed under any circumstances. + +### Comments & documentation + +- Public API doc comments and any non-obvious logic. +- Don't use Markdown bold and italic formating in comments and Docblocks. Purely visual formatting is fine such as spaces, line breaks, indentation, and lists. +- Oxford(Serial) comma, two spaces after a period at the end of a sentence. +- **Every function gets exactly one docblock**, PHP/PHPDoc-style. + - Open with `/**` (two stars) and close with ` */`; every interior line starts with ` * ` (leading space, star, space). This is what distinguishes a docblock from an ordinary `/* ... */` comment — reserve `/**` for documentation, use `/* */` for inline notes. + - Structure: a one-line summary sentence, then (optionally) a blank ` *` line and a longer prose description, then the tag block. Order of tags: `@param` (one per parameter, in signature order), `@return`, then any of `@note` / `@warning` / `@see` / `@pre` / `@post` as needed. Omit `@return` for `void` functions. Omit `@param` when there are no parameters (`void`). + - `@param type variable description` + - Indent with tabs, consistent with the rest of the file. + - Example 1: + ```kotlin + /** + * Clears the current GL framebuffer to the given color. Assumes a context is current. + * + * @param Float red Red Color + * @param Float green Green Color + * @param Float blue Blue Color + * @param ByteArray bytes Raw bytes from the file + * @return ReturnedVariable + */ + actual fun clear(red: Float, green: Float, blue: Float, alpha: Float) { } + ``` + +## Guardrails (hard rules — contributors and AI assistants) + +- **Re-import never destroys rig work.** Removals/renames are flagged and reviewable, never silently applied. +- **Docking is a Blender-style area tree:** the window is a recursive split tree of areas; each area hosts one editor space and is switchable to any space via its header dropdown; splitters are draggable. No free-floating windows. One shared desktop/tablet interface with a touch-tuned skin — never a second front-end. +- **All input dispatches through the action registry** — menus, toolbar, radial menu, and shortcuts never hardcode handlers, so a rebind takes effect everywhere. +- **All UI strings externalized; localize chrome/display, never format-level IDs** — `ParamAngleX` and the rest of the CMO3 identifiers stay verbatim for interop. +- **CMO3 round-trip must pass before any format-write change merges.** (Open → re-save → reopen in official editor → no semantic loss.) +- **Binary formats implement the shared `FormatCodec` contract** (`kind`/`matches`/`read`/`write`, dispatched via `FormatRegistry`); JSON sidecars stay text helpers. No bespoke per-format read/write facade. +- **Two fidelity tiers respected:** semantic-validity for CMO3, bounded-ULP for geometry, byte-exact only for MOC3 binary. Never relax format correctness; never chase bit-identical geometry. +- **No `java.lang.foreign` in shared/Android paths** (absent on Android). FFI only behind `:core-bridge`. +- **No Swing/JavaFX as UI** (Compose only). The desktop GL viewport is not Swing interop either — it renders offscreen via a hidden GLFW context into a Compose `Image`. +- **MOC3 version policy:** read v1–v6. + +## Glossary + +- **Drawable / art mesh** — textured triangle mesh with draw/render order, masks, blend mode, opacity, multiply/screen color. +- **Warp deformer** — FFD lattice; **Rotation deformer** — nesting pivot transform. +- **Parameter** — animation axis (e.g. `ParamAngleX`); **Keyform** — captured state at specific parameter values; runtime blends across the N-D keyform grid. +- **Source-art binding** — the stable-identity link from a rig drawable to a source layer; basis of non-destructive re-import. +- **File family** — `.cmo3` (editor source: CAFF container + XML-serialized object graph + embedded PNGs) · `.moc3` (runtime, C structs) · `model3/physics3/cdi3/pose3/exp3/motion3/userdata3.json` · texture atlas. \ No newline at end of file diff --git a/.claude/hooks/block-mnt.sh b/.claude/hooks/block-mnt.sh new file mode 100755 index 0000000..fbbbf80 --- /dev/null +++ b/.claude/hooks/block-mnt.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# Blocks any Claude Code tool call that touches /mnt + +input=$(cat) + +# Pull out the fields that might contain a path +file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty') +command=$(echo "$input" | jq -r '.tool_input.command // empty') +notebook_path=$(echo "$input" | jq -r '.tool_input.notebook_path // empty') + +# Check each for /mnt (with or without leading slash variants, and case just in case) +for candidate in "$file_path" "$command" "$notebook_path"; do + if echo "$candidate" | grep -qE '(^|[[:space:]/])/mnt(/|$| )'; then + echo "Blocked: this tool call references /mnt, which is off-limits in this project." >&2 + exit 2 + fi +done + +exit 0 \ No newline at end of file diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..92b743e --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Read|Write|Edit|Bash|NotebookEdit", + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-mnt.sh" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/.claude/skills/comment-cleanup/SKILL.md b/.claude/skills/comment-cleanup/SKILL.md new file mode 100644 index 0000000..a3d1ad9 --- /dev/null +++ b/.claude/skills/comment-cleanup/SKILL.md @@ -0,0 +1,185 @@ +--- +description: Sweep a branch's changed files against a base ref and fix comments/docblocks that no longer describe current code — stale claims, leftover planning/phase language, bug-narrative diary comments, irrelevant comparisons to unrelated tools/projects, wrong CMO3/MOC3 field citations, and incomplete docblocks. Batches large branches across parallel background agents. Use when asked to "clean up comments," "fix comments on this branch," or before merging a branch that accumulated debugging-session comment cruft. +argument-hint: [base-ref] +--- + +# Comment cleanup + +Reviews every comment and docblock touched by a branch (compared against `$1`, default `master`) +and fixes the ones that no longer tell the truth about the code below them. This is a text-only +pass: never change code logic. Suspected actual code bugs get flagged for the user, not silently +fixed — this skill's job is the comments, not the implementation, except where explicitly asked +to also apply a flagged fix. + +## 1. Scope the diff + +``` +git merge-base HEAD +git diff --name-status -M ...HEAD +``` + +Always pass `-M` (rename detection) — without it, a renamed-with-edits file shows as a spurious +delete+add pair, and pathspec-glob queries on the raw file list can double-count or miss renamed +paths. Cross-check any manually-assembled file list against `git diff --name-only` with a +set-difference (`comm -13`/`comm -23`) before trusting it's complete and non-overlapping. + +If the user says "second round" or references prior cleanup work on the same branch, scope to +`..HEAD` instead of the whole branch — that's usually a much smaller, more +targeted diff, and re-reviewing already-clean content wastes the pass. + +## 2. Decide solo vs. delegated + +- **Under ~30 changed files**: review directly, file by file, using `Read` and `git diff ...HEAD -- ` + per file. Keep a `TodoWrite` list per file cluster so progress survives context compaction. +- **Larger** (a big feature branch, a multi-week history sweep): batch by **module/directory + boundary**, not by commit range — a file's *final* state is what matters, not which commit last + touched it. Dispatch each batch as a background `Agent` (`subagent_type: general-purpose`, + `run_in_background: true`) so batches run in parallel. Aim for batches of roughly 5–20 files or + ~1000–2000 diff lines; split a single very large file (500+ lines) into its own batch if it's + dense. +- Before delegating, personally read and fix ONE representative example yourself first (see §5) — + it gives you a concrete before/after to paste into every agent prompt, which is what keeps + agent output consistent instead of six different interpretations of "stale." + +Every delegated agent prompt must include, verbatim or adapted: +- The exact file list for its batch (absolute repo-relative paths). +- The seven categories from §3, each with the concrete calibration example from §5. +- The explicit "what not to do" list from §4. +- An instruction to flag suspected real code bugs as `POSSIBLE CODE BUG: file:line — reason` + instead of fixing them. +- A word budget on the final report (400–700 words depending on batch size) so N parallel reports + don't blow the orchestrating session's context on consolidation. + +## 3. What counts as a fix (seven categories) + +**(A) Staleness.** A comment/docblock describes behavior, a signature, a nullability, a module +location, or a control-flow path that no longer matches the code beneath it. Includes dangling +cross-references (`[FormerName]`, a package that moved to another module, a docblock enumerating +fields that no longer match a `when` below it). Fix to describe the code as it stands now. + +**(B) Planning/phase language.** Leftover roadmap-numbering that reads like a project-plan label +rather than a description of what a step *does* — `Phase 1` / `Phase 2` inside a function that +runs both steps unconditionally every time, `(M2)`/`(M4)` milestone tags, `Slice A`, `Part 2 of`, +"placeholder pending a future step" for something that's actually wired, "dedicated follow-up" for +work already done in the same branch. Fix by renaming to what the step IS, not by deleting the +structure. Example fix applied in this project: + +``` +- // Phase 1 - set membership: identity shells for creations, source removal for deletions. ++ // Structural pass - set membership: identity shells for creations, source removal for deletions. +``` + +**Do not touch legitimate roadmap citations** — `docs/plan/art-sourcing-pipeline.md § Phase G` is a +real, still-open phase in a real design doc; a comment citing it accurately is not planning-language +cruft. The test is whether the *cited plan* still exists and is still pending, not whether the word +"Phase" appears. + +**(C) Bug-narrative / debugging-diary comments.** Rewrite comments that narrate a bug's discovery +story in a way that needs hidden context — "used to X, which caused Y, so now Z," "never showed the +bug," "one desync was observed (date) where..." — into either a direct atemporal statement of the +current invariant, or counterfactual "would" framing explaining what the guard prevents. Example: + +``` +- // one desync was observed (2026-08-03) where a second MOC3 exported the first model's rig +- // onto the second's atlas pages, which reads as a wall of drawable notices... ++ // a session from a stale composition pass would export the PREVIOUS document's rig onto this ++ // document's atlas pages, surfacing as a wall of drawable notices... +``` + +**Exception — test docblocks only:** a regression test MAY reference a historical bug if the +mechanism is fully and concretely spelled out in the comment itself (not left as an opaque "the +bug"). That's normal regression-test practice, not narrative cruft — don't over-correct it. + +**Exception — dated "KNOWN GAP" / investigative documentation:** a long, precise, dated note that +documents a real, currently-open limitation (what's broken, why, what's been ruled out, where the +real fix lives) is valuable "why" documentation, not diary cruft — even when it's long and reads +like it came out of a debugging session. Only fix it if a claim in it is factually wrong or has +been superseded by a later change; never trim it just for length. + +**(D) Format-citation discipline.** Any comment touching a binary/serialized format field must cite +it per the project convention (`// CMO3: field `, `// MOC3 §N ...`). Fix a +missing/wrong citation only if you can verify the correct one by reading the actual field/class +definition — never guess a citation. + +**(E) Docblock completeness.** Per the project's docblock style, an *existing* docblock needs one +`@param` per parameter (signature order) and `@return` for non-void functions. If a parameter was +added later without updating the docblock, add the tag. **Never add a docblock to a function that +never had one** — that's a different task, not this one. + +**(F) Formatting/whitespace artifacts.** Heavy debugging-session editing sometimes leaves stray +indentation (a nested function at 4 tabs instead of 1, relative to its scope) or a duplicate +comment block sitting next to the new one that replaced it. Cheap to spot with `cat -A` on the +touched region; fix as pure whitespace, zero semantic risk. + +**(G) Irrelevant tool/project comparisons.** A comment justifies a file's or function's existence +or design by contrasting it with what some unrelated tool or project does or doesn't do — "this is +the pipeline node Umamo owns and Blender does not," "unlike Photoshop," "which no other rigging +tool does" — where the comparison itself carries no technical information about this code's actual +behavior. A comment describes the purpose of the code in front of the reader, not a scorecard +against unrelated software. Fix by deleting the comparison and keeping only the real technical +rationale; if the comparison was the entire reason given, replace it with the actual reason (read +the surrounding code or the relevant `docs/plan/`/`docs/format/` doc to find it) rather than +leaving a bare, now-shorter claim. Example fix applied in this project: + +``` +- * This is the pipeline node Umamo owns and Blender does not - because the 2D source art hands us +- * each piece's opaque silhouette before packing, the atlas can be generated rather than authored +- * by hand and reconciled. ++ * Because the 2D source art hands us each piece's opaque silhouette before packing, the atlas can ++ * be generated rather than authored by hand and reconciled. +``` + +**Do not touch a comparison that names an actual compatibility or fidelity target** — "matches the +official Cubism Editor's export ordering," "unlike the CMO3 v3 schema, v4 adds a blend-shape +table" — those name a concrete constraint the code is built to satisfy (per the Fidelity contract +in CLAUDE.md), not a rhetorical aside about an unrelated project. The test is whether the named +project is the thing this code interoperates with or is bounded by (Cubism/CMO3/MOC3 for this +codebase), not whether a proper noun appears in the sentence. + +## 4. What not to do + +- No code-logic changes. Comment, docblock, and pure-whitespace text only. +- Don't add new comments/docblocks to undocumented functions. +- Don't "improve" already-accurate comments for style alone. +- Don't shorten legitimate dated investigative documentation just because it's long (see the (C) + exception above). +- Don't touch files outside the assigned scope/batch. +- Don't touch a project's own scratch/notes file above whatever heading marks it off-limits, if the + project's memory or CLAUDE.md says so (this repo: `TODO.md` above `# Claude Notes` is Alexia's + personal pad). + +## 5. Calibrate before delegating + +Read one file yourself, find one real instance of category (A) or (B), fix it, and keep the exact +before/after diff. Paste that verbatim into every batch's agent prompt as "here's a fix I already +made for calibration — read the file yourself since it won't show in `git diff` yet." This is what +keeps parallel agents from either being too aggressive (rewriting fine comments for style) or too +timid (leaving real staleness because it wasn't a 100% textual match to the example). + +## 6. Consolidate and verify + +- Every `POSSIBLE CODE BUG` an agent reports gets personally verified before it goes in the final + report — read the actual code, trace the call graph, confirm the claim with `grep`/`git log -L` + as needed. Never forward an unverified agent claim as a finding. +- Run a final repo-wide sweep for residual patterns the agents might have missed individually: + ``` + git diff --name-only ...HEAD -- '*.kt' | while read -r f; do + grep -noE 'Phase [A-Za-z0-9]+|\(M[0-9]+\)|Step [0-9]+|Slice [A-Z]|for now\b' "$f" + done + ``` +- Sanity-check the aggregate diff: `git diff --stat` should show a comment-sized insert/delete + ratio (roughly 1:1, small numbers) — a large net line-count change means something drifted into + code edits. +- If a fix touches control flow that a report only weakly implied should change (e.g. a stale + comment that was ALSO a real duplicate-notice bug), don't fix the logic unasked — report it, and + wait for explicit approval before removing/changing behavior (see the `Cmo3PropertyLowering` + redundant-notice example from this project's history: flagged first, fixed only after the user + said "go ahead"). + +## 7. Report format + +Group findings by theme, not by batch — the user doesn't care which agent found what. Lead with +the most consequential fixes (wrong logic implied by a comment, swapped comment blocks, a +misleading user-facing string), then the routine staleness/phase-language sweep, then any verified +`POSSIBLE CODE BUG` flags left for the user's own triage. Keep it scannable: file references, one +line of before → after gist each, no prose padding. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a410839 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,44 @@ +# EditorConfig — shared formatting rules across editors AND ktlint (which reads this file). +# CLAUDE.md mandates TAB indentation, overriding Kotlin's space default. +root = true + +[*] +charset = utf-8 +end_of_line = lf +# HOLY FUCKING SHIT THIS TOOK SO FUCKING LONG TO FIND. FUCK THIS NEWLINE AT THE END OF FILES SHIT. IT'S 2026! Stop doing lazy as fuck programming. +insert_final_newline = false +trim_trailing_whitespace = true +indent_style = tab + +[*.{kt,kts}] +indent_style = tab +# Tell ktlint to use the official ruleset but honour tab indentation above. +ktlint_code_style = ktlint_official +# Bilingual EN/JA comments push some lines long; relax the line-length rule rather than +# fight it (CLAUDE.md cares about *why*-comments, not column counts). +ktlint_standard_max-line-length = disabled +# Allow single-line call chains like `libs.versions.x.get().toInt()` (ubiquitous in Gradle +# Kotlin DSL + version-catalog access); the forced-newline form hurts more than it helps. +ktlint_standard_chain-method-continuation = disabled +# Same reasoning for constructor and function signatures: these wrapping rules key off +# max-line-length (disabled above), so with it off they over-wrap. Authors choose single- vs +# multi-line by readability. The valuable structural rules (imports, spacing, trailing commas, +# naming, no-wildcard-imports) remain enforced. +ktlint_standard_class-signature = disabled +ktlint_standard_function-signature = disabled +# @Composable functions are PascalCase by Compose convention; exempt them from the +# lowerCamelCase function-naming rule (the rule still applies to ordinary functions). +ktlint_function_naming_ignore_when_annotated_with = Composable +# Compose Resources generates ONE top-level extension property per UI string (Res.string.menu_file, +# …) in org.umamo.ui.resources, a set that grows unbounded with the catalog. Allow an on-demand +# (wildcard) import for that single generated package so consumers write `import …resources.*` +# instead of one line per string; no-wildcard-imports stays strict for every other package. This is +# the precise form of the gen/ subtree's blanket disable — exempt the generated package, not the file. +ij_kotlin_packages_to_use_import_on_demand = org.umamo.ui.resources.** + +[*.{yml,yaml,json,toml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..36eb7b9 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,15 @@ +# These are supported funding model platforms + +github: Alexia +patreon: c/Azxiana +open_collective: # Replace with a single Open Collective username +ko_fi: azxiana +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +polar: # Replace with a single Polar username +buy_me_a_coffee: # Replace with a single Buy Me a Coffee username +thanks_dev: # Replace with a single thanks.dev username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dd84ea7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f3c69b8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +# Continuous integration: runs the shared verification suite on every push/PR. +# The suite itself lives in verification.yml so release.yml can run the identical thing — see the +# comment at the top of that file for why it is factored out rather than inlined here. +name: CI + +on: + push: + branches: [master, develop] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +# Least-privilege default: checkout is all this workflow needs. GitHub reports each +# job's pass/fail as a PR status check natively, no extra `checks`/`statuses` scope required. +permissions: + contents: read + +# Cancel superseded runs on the same ref to save runner minutes. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + verify: + # Skip draft PRs to avoid burning runner minutes on WIP; ready_for_review re-triggers it. + # This guard lives here rather than in verification.yml because the release workflow calls the + # same suite with no pull-request context at all. + if: github.event_name != 'pull_request' || github.event.pull_request.draft == false + uses: ./.github/workflows/verification.yml + permissions: + contents: read diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..345e1fe --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,433 @@ +# Release: pushing a semver tag verifies the version, runs the full test suite, and publishes +# self-contained app images plus runnable uber jars for all five supported desktop targets. +# +# Deliberately out of scope until alpha: code signing, notarization, native installers +# (.msi/.dmg/.deb/.rpm) and auto-update. What ships here is an unzip-and-run app image with a +# bundled JRE, plus a jar for people who already have a JVM. See RELEASING.md. +name: Release + +on: + push: + # These are GitHub filter patterns, not regex: `+` means "one or more of the preceding + # character", so `[0-9]+` is one-or-more digits and `.` is a literal dot. Two patterns rather + # than one trailing `*` so it is obvious that prerelease tags are supported ON PURPOSE — + # ProjectInfo.kt declares 0.1.0-dev today, so `v0.1.0-dev` has to be a legal release tag, and + # gradle/project-version.gradle.kts already strips the suffix for jpackage. The verify job + # re-checks the tag against a strict semver regex, so these globs are only a coarse filter. + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-*" + # Dry run. Builds and tests everything and uploads all five targets as workflow artifacts, but + # publishes nothing — so the whole pipeline can be exercised from a branch before any tag exists. + workflow_dispatch: + +# Least privilege at the workflow level; only the `release` job widens it, and only to contents:write. +permissions: + contents: read + +# Serialise per ref, but NEVER cancel in progress: unlike CI, a cancelled run here can leave a +# half-uploaded release behind. A superseded release run is cheap; a torn one is not. +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + # ----------------------------------------------------------------------------------------------- + # 1. The version gate. ProjectInfo.kt IS the version (its docblock forbids a second definition), + # so this workflow VERIFIES the tag against it and never injects a version. Runs first and + # alone: a mismatch should cost ~30 seconds, not a five-way packaging matrix. + # ----------------------------------------------------------------------------------------------- + verify: + name: Verify version + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + version: ${{ steps.resolve.outputs.version }} + tag: ${{ steps.resolve.outputs.tag }} + prerelease: ${{ steps.resolve.outputs.prerelease }} + publish: ${{ steps.resolve.outputs.publish }} + steps: + - uses: actions/checkout@v7 + + - name: Resolve and cross-check the version + id: resolve + shell: bash + run: | + set -euo pipefail + + project_info="module/ui/src/commonMain/kotlin/org/umamo/ui/help/ProjectInfo.kt" + + # The same constant gradle/project-version.gradle.kts parses. POSIX sed with a + # bracket-expression for whitespace, so this needs nothing installed and behaves the same + # on every runner image. + declared="$(sed -n 's/.*VERSION[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "${project_info}" | head -n1)" + if [ -z "${declared}" ]; then + echo "::error file=${project_info}::VERSION constant not found — the build derives its version from it" + exit 1 + fi + echo "ProjectInfo.VERSION = ${declared}" + + if [ "${GITHUB_EVENT_NAME}" = "push" ]; then + tag="${GITHUB_REF_NAME}" + publish=true + else + # workflow_dispatch: no tag exists. Synthesise the one this commit WOULD ship under, so a + # dry run produces identically-named artifacts, and publish nothing. + tag="v${declared}" + publish=false + fi + echo "tag = ${tag} (publish=${publish})" + + case "${tag}" in + v*) version="${tag#v}" ;; + *) echo "::error::tag '${tag}' must start with 'v'"; exit 1 ;; + esac + + # Strict semver. The push filter above is a glob and would happily accept 'v1.2.3nonsense'. + if ! printf '%s' "${version}" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$'; then + echo "::error::tag '${tag}' is not a semantic version" + exit 1 + fi + + # THE gate. Fail loudly and say exactly what to do, because the fix is never "re-run". + if [ "${version}" != "${declared}" ]; then + echo "::error file=${project_info}::tag '${tag}' does not match ProjectInfo.VERSION '${declared}'. Bump the constant (and CHANGELOG.md), commit, delete the tag, and re-tag. This workflow never injects a version." + exit 1 + fi + + # A semver prerelease is anything with a '-' after MAJOR.MINOR.PATCH. 0.1.0-dev qualifies, + # which is correct: everything before alpha should be marked as such on the release page. + case "${version}" in + *-*) prerelease=true ;; + *) prerelease=false ;; + esac + + { + echo "version=${version}" + echo "tag=${tag}" + echo "prerelease=${prerelease}" + echo "publish=${publish}" + } >> "${GITHUB_OUTPUT}" + + # ----------------------------------------------------------------------------------------------- + # 2. The quality gate — literally the same suite every push and PR runs, called as a reusable + # workflow so the two cannot drift. Nothing is packaged until this is green. + # ----------------------------------------------------------------------------------------------- + test: + name: Verification suite + needs: verify + uses: ./.github/workflows/verification.yml + permissions: + contents: read + + # ----------------------------------------------------------------------------------------------- + # 3. Packaging, one leg per shipped target. Each leg produces exactly two files: + # umamo--.{tar.gz|zip} — self-contained app image (bundled JRE) + # umamo--.jar — uber jar, needs a JDK/JRE 21 on the machine + # Every leg builds ON its own OS/arch: an app image jlinks the HOST JDK into itself, so unlike + # the uber jar it genuinely cannot be cross-produced. + # ----------------------------------------------------------------------------------------------- + package: + name: Package ${{ matrix.target }} + needs: [verify, test] + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + strategy: + # One platform failing should not hide whether the other four work — on a release run that is + # the difference between one fix-and-retag and four. + fail-fast: false + # appImage gates createDistributable and the archive/assert steps that depend on it. It is + # false on macOS ONLY because of a jpackage bug, not anything about the app: + # jdk.jpackage.internal.CFBundleVersion rejects a CFBundleVersion whose first component is + # zero, so any 0.x version fails createDistributable on macOS alone. JDK-8380634 deleted that + # check on 2026-03-30, but it landed after JDK 26 forked — 21, 25 (LTS) and 26 (latest GA) all + # still carry it, so there is no released JDK to move to. Rather than mangle the version or + # ship an early-access runtime, the macOS legs publish the uber jar only until JDK 27 is GA + # (~September 2026). TO RESTORE: set these two back to true. Nothing else needs to change. + matrix: + include: + - { target: linux-x64, runner: ubuntu-latest, appImage: true } + - { target: linux-arm64, runner: ubuntu-24.04-arm, appImage: true } + - { target: windows-x64, runner: windows-latest, appImage: true } + - { target: macos-arm64, runner: macos-latest, appImage: false } + # macos-15-intel is the last x86-64 macOS image GitHub will offer; it retires in August + # 2027, after which this leg has to go and Intel Mac users fall back to the uber jar under + # an x64 JDK. (The older macos-13 label was retired in December 2025 — do not resurrect it.) + - { target: macos-x64, runner: macos-15-intel, appImage: false } + env: + UMAMO_VERSION: ${{ needs.verify.outputs.version }} + UMAMO_TARGET: ${{ matrix.target }} + UMAMO_APP_IMAGE: ${{ matrix.appImage }} + steps: + - uses: actions/checkout@v7 + + # jlink and jpackage come from the JVM the Gradle DAEMON runs on, not from jvmToolchain(21) — + # the Compose plugin defaults its javaHome to the `java.home` system property, and + # gradle/gradle-daemon-jvm.properties pins the daemon to 21. Temurin specifically: the plugin's + # checkRuntime task hard-errors on a Homebrew JDK, which is what a bare `brew install` leaves + # on PATH. + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" + + # No Android SDK step here, unlike the verification suite. Every KMP library module applies + # AGP's com.android.kotlin.multiplatform.library and Gradle configures all projects even for a + # :desktop-only task graph, so this looked like it would be required — but it measurably is + # not: `env -u ANDROID_HOME -u ANDROID_SDK_ROOT ./gradlew :desktop:createDistributable + # --dry-run --no-configuration-cache` configures all seven android targets and resolves the + # task graph cleanly. Skipping it saves ~40 s per leg and avoids the arm64-Linux problem that + # Google ships only x86-64 build-tools binaries. + + - name: Set up Gradle (with caching) + uses: gradle/actions/setup-gradle@v6 + with: + # A tag build is read-only by default (it is not the default branch), but say so + # explicitly: five legs racing to write one cache is pure waste, and a release must never + # be the run that poisons the cache every PR then reads. + cache-read-only: true + + # -Pumamo.target is passed EXPLICITLY rather than left to host detection, for two reasons: + # * the uber jar's name embeds it (see :desktop's archiveFileName override), so artifact + # names become a function of the matrix instead of a function of what the runner reported; + # * paired with -Pumamo.requireTargetIsHost it turns a runner-image surprise — an unexpected + # os.arch — into a build failure rather than a jar full of the wrong natives. + # + # Do NOT add `check` or `build` to this job. `check` pulls compileKotlinIosArm64 in :format, + # :runtime, and :render, and ubuntu-24.04-arm is not a supported Kotlin/Native host. The + # verification suite above is where testing happens. + # + # The heap overrides are not cosmetic: gradle.properties asks for a 4 GB Gradle daemon and the + # Kotlin daemon mirrors it, which is ~8 GB against the arm64 macOS runner's ~7 GB. 2 GB each + # fits every runner in the matrix and is ample for a :desktop-only task graph. + - name: Build the app image and the uber jar + shell: bash + run: | + set -euo pipefail + tasks=":desktop:packageUberJarForCurrentOS" + if [ "${UMAMO_APP_IMAGE}" = "true" ]; then + tasks=":desktop:createDistributable ${tasks}" + else + echo "::notice::${UMAMO_TARGET}: app image skipped, publishing the uber jar only (see the matrix comment in this workflow)" + fi + # shellcheck disable=SC2086 # tasks is a deliberate word-split list of Gradle task paths. + ./gradlew --stacktrace \ + -Dorg.gradle.jvmargs="-Xmx2g -Dfile.encoding=UTF-8" \ + -Pkotlin.daemon.jvmargs=-Xmx2g \ + -Pumamo.target="${UMAMO_TARGET}" \ + -Pumamo.requireTargetIsHost=true \ + ${tasks} + + # jlink writes a `release` descriptor listing MODULES into every runtime image and jpackage + # copies it into the app image verbatim, so this is a launch-free check that :desktop's + # modules(...) list still covers what the app actually uses. Without it a missing module is + # invisible until a user hits NoClassDefFoundError, because nothing in CI ever starts the + # packaged binary. The descriptor's depth differs per OS (macOS nests the runtime inside the + # .app bundle), so find it rather than hard-coding a path. + - name: Assert the bundled runtime carries the modules the app needs + if: matrix.appImage + shell: bash + run: | + set -euo pipefail + root="app/desktop/build/compose/binaries/main/app" + release_file="$(find "${root}" -maxdepth 8 -type f -name release | head -n1)" + if [ -z "${release_file}" ]; then + echo "::error::no jlink release descriptor under ${root} — did createDistributable actually run?" + exit 1 + fi + echo "runtime descriptor: ${release_file}" + modules_line="$(grep '^MODULES=' "${release_file}")" + echo "${modules_line}" + for module in java.base java.desktop java.instrument java.logging java.sql java.xml jdk.security.auth jdk.unsupported; do + case "${modules_line}" in + *"${module}"*) ;; + *) + echo "::error::bundled runtime is missing ${module} — add it to nativeDistributions.modules in app/desktop/build.gradle.kts" + exit 1 + ;; + esac + done + + # tar, not zip, on Linux: it is the only one of the three archivers here that preserves the + # execute bit on bin/umamo and the runtime's helper binaries. -C so the archive root is + # `umamo/` rather than the whole build path. + - name: Archive the app image (Linux) + if: matrix.appImage && runner.os == 'Linux' + shell: bash + run: | + set -euo pipefail + mkdir -p dist + tar -C "app/desktop/build/compose/binaries/main/app" \ + -czf "dist/umamo-${UMAMO_TARGET}-${UMAMO_VERSION}.tar.gz" umamo + + # Currently inert — matrix.appImage is false on both macOS legs (see the matrix comment). Kept + # rather than deleted so restoring macOS app images at JDK 27 GA is only a matrix flip. + # + # ditto, not zip: a .app is a bundle of symlinks, execute bits and extended attributes, and + # /usr/bin/zip flattens enough of that to produce something Finder refuses to open. + # `-c -k --keepParent` is Apple's own recipe and keeps `umamo.app` as the archive root. + - name: Archive the app image (macOS) + if: matrix.appImage && runner.os == 'macOS' + shell: bash + run: | + set -euo pipefail + mkdir -p dist + ditto -c -k --keepParent \ + "app/desktop/build/compose/binaries/main/app/umamo.app" \ + "dist/umamo-${UMAMO_TARGET}-${UMAMO_VERSION}.zip" + + # 7z, not Compress-Archive: the app image is ~230 MB spread over several thousand files, a + # shape Compress-Archive takes minutes on. 7z ships on the windows runner image. + # + # Push-Location into the app-image directory first and archive the bare "umamo" name — 7z's + # default is to preserve whatever relative path you hand it inside the archive, so pointing it + # at the full build path bakes app\desktop\build\compose\binaries\main\app\umamo\ into every + # entry, which is what a user then has to click through after unzipping. cd'ing there first + # keeps the archive root flat, matching the Linux (`tar -C`) and macOS (`ditto --keepParent`) + # legs, which already avoid this. + - name: Archive the app image (Windows) + if: matrix.appImage && runner.os == 'Windows' + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + New-Item -ItemType Directory -Force -Path dist | Out-Null + $distPath = (Resolve-Path dist).Path + Push-Location "app\desktop\build\compose\binaries\main\app" + try { + 7z a -tzip -mx=5 "$distPath\umamo-$env:UMAMO_TARGET-$env:UMAMO_VERSION.zip" umamo | Out-Null + } finally { + Pop-Location + } + + # An exact path, not a glob: the name is pinned by :desktop's archiveFileName override, so if + # that convention ever changes this fails here instead of shipping a release with a hole in it. + - name: Collect the uber jar + shell: bash + run: | + set -euo pipefail + mkdir -p dist + cp "app/desktop/build/compose/jars/umamo-${UMAMO_TARGET}-${UMAMO_VERSION}.jar" dist/ + ls -lh dist/ + + - name: Upload this target's artifacts + uses: actions/upload-artifact@v7 + with: + # Must be unique per matrix leg — the action errors rather than merging same-named uploads. + # The release job re-merges them with `pattern` + `merge-multiple`. + name: umamo-${{ matrix.target }} + path: dist/* + # A leg that produced nothing must fail here, not quietly ship a four-asset release. + if-no-files-found: error + # Everything in dist/ is already a compressed archive or a jar (itself a zip); re-deflating + # incompressible bytes would cost minutes per leg and save nothing. + compression-level: 0 + # These are intermediates — the release page is the durable copy. Long enough to debug a + # failed publish, short enough not to hoard ~1.4 GB per run. + retention-days: 7 + + # ----------------------------------------------------------------------------------------------- + # 4. Publish. Uses the gh CLI rather than a marketplace action on purpose: gh is preinstalled on + # every GitHub-hosted runner, so this — the only job holding contents:write — hands that token + # to no third-party code. It is also one less action version to pin and audit, and the + # behaviour on a re-run is ours to define rather than something to discover. + # ----------------------------------------------------------------------------------------------- + release: + name: Publish GitHub release + needs: [verify, package] + # Dry runs stop after `package`: the artifacts are on the run page, nothing is published, and + # there is nothing to clean up afterwards. + if: needs.verify.outputs.publish == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + # The only elevated permission anywhere in this workflow, scoped to the one job that needs it. + # Creating a release and uploading its assets is all contents:write buys; nothing here wants + # packages:, id-token: or actions:. + contents: write + steps: + - uses: actions/checkout@v7 + + - name: Download every target's artifacts + uses: actions/download-artifact@v8 + with: + pattern: umamo-* + merge-multiple: true + path: dist + + # Computed here, once, on one machine, in one format — rather than five per-OS variants of + # sha256sum/shasum/Get-FileHash that would then have to agree on output shape. The explicit + # `umamo-*` prefix keeps the checksum file from ever hashing itself. + - name: Generate SHA-256 checksums + working-directory: dist + run: | + set -euo pipefail + sha256sum umamo-* | tee SHA256SUMS.txt + ls -lh + + - name: Create the release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.verify.outputs.tag }} + VERSION: ${{ needs.verify.outputs.version }} + PRERELEASE: ${{ needs.verify.outputs.prerelease }} + run: | + set -euo pipefail + + # The unsigned-build warnings are not boilerplate: without them the first thing most users + # meet is an OS refusing to run the download. Unsigned is a deliberate pre-alpha choice, so + # the consequence belongs at the point of download. + notes="$(mktemp)" + cat > "${notes}" <<'NOTES' + ## Downloads + + | File | Note | + | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | + | `umamo--.zip` / `.tar.gz` | Java SDK not required, just run it directly. | + | `umamo--.jar` | You will need Java SDK 21 or higher to run. Either open through the file browser or through the command line. `java -jar umamo-...jar` | + + Targets: `linux-x64`, `linux-arm64`, `windows-x64`, `macos-arm64`, `macos-x64`. + Verify your download against `SHA256SUMS.txt`. + + **MacOS ships as the jar only for now.** A jpackage bug rejects any app version starting with `0`, and the fix is not in any released JDK yet, so there is no macOS app image until JDK 27 arrives. Install a JDK 21 or newer and run `java -jar umamo-….jar`. + + ## These builds are not signed + + Code signing and notarization arrive at alpha. Until then: + + * Windows: SmartScreen shows "Windows protected your PC". Choose *More info* → *Run anyway*. + * MacOS: The JAR is unaffected by Gatekeeper quarantine, so nothing extra is needed while MacOS ships as a JAR. + * Linux: No equivalent prompt. Extract `tar xzf umamo-*.tar.gz` and run `umamo/bin/umamo`. + + There are no installers yet and no auto-update: to upgrade, delete the old folder and unpack the new one. + + ## Status + + Umamo is early alpha. Keep backups of your project files and work on copies. + NOTES + + assets=(dist/*) + + # A re-run of a failed publish must converge, not collide. + if gh release view "${TAG}" > /dev/null 2>&1; then + echo "release ${TAG} already exists — replacing its assets" + gh release upload "${TAG}" "${assets[@]}" --clobber + else + args=( + --title "Umamo ${VERSION}" + --notes-file "${notes}" + # Appends the auto-generated commit/PR list after the hand-written notes above. + --generate-notes + # DRAFT on purpose. A draft is invisible to non-collaborators, notifies nobody, stays + # out of the releases Atom feed, and is never "latest" — so a bad build can be deleted + # as though it had never existed. Publishing is one click, or: + # gh release edit --draft=false + --draft + ) + if [ "${PRERELEASE}" = "true" ]; then + args+=(--prerelease) + fi + gh release create "${TAG}" "${args[@]}" "${assets[@]}" + fi + + gh release view "${TAG}" diff --git a/.github/workflows/verification.yml b/.github/workflows/verification.yml new file mode 100644 index 0000000..f2ad9dd --- /dev/null +++ b/.github/workflows/verification.yml @@ -0,0 +1,71 @@ +# The verification suite: lint + build + test on JDK 21 with a real headless GL context. +# +# This is a reusable workflow (`workflow_call`) rather than a job inside ci.yml, because two things +# need to run EXACTLY this and must not be allowed to drift apart: every push/PR (ci.yml) and every +# release (release.yml). A release that ran a subtly different suite than the branch gate is a +# release whose green tick means less than it looks like it does. +name: Verification + +on: + workflow_call: + +# Least-privilege default: checkout is all this workflow needs. GitHub reports each +# job's pass/fail as a PR status check natively, no extra `checks`/`statuses` scope required. +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v7 + + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" + + # Provides ANDROID_HOME + sdkmanager; needed for the :android app + android targets. + # `packages` is overridden because the action's default list includes the legacy `tools` + # package, which current cmdline-tools no longer resolve, and sdkmanager exits 1 on it. + - name: Set up Android SDK + uses: android-actions/setup-android@v4 + with: + packages: platform-tools + + - name: Install Android SDK packages + run: sdkmanager "platforms;android-36" "build-tools;36.0.0" + + - name: Set up Gradle (with caching) + uses: gradle/actions/setup-gradle@v6 + + # :render's GL tests drive a real GLFW / OpenGL 3.3 core context and assert on read-back pixels, + # so without a display they cover exactly nothing. Xvfb + Mesa's llvmpipe give the runner a real + # context. libgl1-mesa-dri is the load-bearing one — it carries swrast/llvmpipe, and Mesa cannot + # do software GL without it. The GLFW X11 libs are listed explicitly rather than trusted to the + # runner image, so an image change fails here instead of silently degrading the suite. + - name: Install headless OpenGL (Xvfb + Mesa software GL) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + xvfb libgl1 libgl1-mesa-dri libglx-mesa0 libegl1 \ + libxrandr2 libxinerama1 libxcursor1 libxi6 libxext6 + + # umamo.requireGl turns the GL tests' missing-context skip into a hard failure (HeadlessGlGate), + # so if this Xvfb setup ever stops yielding a context, CI says so instead of going green on a + # suite that ran nothing. That is the whole point of the step above — without this flag a broken + # Xvfb is indistinguishable from a pass. LIBGL_ALWAYS_SOFTWARE pins Mesa to llvmpipe, since the + # runner has no GPU. + # + # NOTE: the golden corpus (test/corpus/, gitignored) is absent here, so every corpus-gated test + # either skips or — for the ~76 print-and-return sites — reports PASSED while asserting nothing. + # This suite therefore proves markedly less than the same command does locally. See + # RELEASING.md § "What this gate does not prove". + - name: Build, test, and lint + env: + LIBGL_ALWAYS_SOFTWARE: "1" + run: > + xvfb-run -a --server-args="-screen 0 1280x1024x24" + ./gradlew build --stacktrace -Dumamo.requireGl=true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8b6be94 --- /dev/null +++ b/.gitignore @@ -0,0 +1,61 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +# Kotlin Gradle plugin data, see https://kotlinlang.org/docs/whatsnew20.html#new-directory-for-kotlin-data-in-gradle-projects +.kotlin/ + +# --- Gradle --- +.gradle/ +build/ +# The blanket `*.jar` rule above would also drop the committed Gradle wrapper jar. +# That jar MUST be tracked (it is how `./gradlew` bootstraps), so re-include it. +!gradle/wrapper/gradle-wrapper.jar + +# --- Android / machine-local --- +local.properties +.cxx/ +*.apk +*.aab +captures/ + +# --- IDE --- +.idea/ +*.iml +*.ipr +*.iws +.vscode/* +!.vscode/settings.json + +#Get fucked, Git. +/docs/formats +/docs/plans +/docs/format +/docs/plan + +#Don't commit my personal models. +/test/corpus +/test/relive +/test/tools +/test/work diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ab27daa --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,199 @@ +# Changelog + +All notable changes to Umamo will be documented in this file. + +Umamo is early alpha. + +(Unreleased changes) + +### Added +* Format: New native UMA file format! +* Format: A UMA document remembers each panel's open branches, filters, tab, and the UV Editor's texture choice, per area. +* Format: A UMA document reopens to the pose, selection, mode, cursors, pivot and proportional editing settings, and each viewport's pan and zoom it was saved with. +* Format: The `.uma` file type is now declared for desktop packages and Android along with freedesktop files in the Linux build to register it per user. +* UI: The unsaved-changes prompts when replacing a document or quitting now offer Save, Don’t Save, and Cancel. +* UI: Added save confirmation for dirty files when closing the application. +* UI: Opens to a new document by default with New and Open file menu operations available. +* UI: Can now drag and drop files on the window. Model files are opened and artworkd is added to the open document. +* UI: When a text entry box is active the mouse cursor now displays the text entry cursor everywhere to indicate that text entry is currently active. +* UI: Previous Workspace and Next Workspace added to Workspace menu. +* UI: Add hover tooltips to the Properties area and Operation Strip. +* Parameters: The parameters are now searchable. +* Source Artwork: The operation strip now offers to adjust the canvas placement of imported artwork to an existing document. The alignment and offset can be changed. +* Source Artwork: Hovering a layer, art, or drawable row in the Sources panel previews its art. +* Source Artwork: A new Import preference shows the Sources panel's layer positions measured from the world axes instead of the art file's top-left corner. +* Export: Image export of the current 2D Viewport with options for transparent, solid, and grid backgrounds. + +### Changed +* UI: The CTRL+O keybinding was changed to file open instead of import CMO3. +* UI: Add Artwork and Import Artwork have been standardized to just import and add artwork to the open document. +* UI: Confirmation dialogs now take arguments for button names and actions along with a new third button. +* UI: Clicking away from all text input fields should now commit the change. +* UI: Clicking away from all text input fields should now end text entry input preventing other inputs from being eaten. +* UI: The command palette now lists only the commands that apply to the editor area under the pointer. For example, Mirror UVs no longer shows while editing a mesh in the 2D viewport. +* UI: The status bar's shortcut suggestions now follow the editor area under the pointer. This is the first iteration of this feature and will be improved in the future. +* UI: The popup overlap picker now uses the drawable name with the part name in parenthesis. +* UI: Buttons now use the accent color when pressed. +* UI: Positions in the Properties panel are now measured from the world axes, and the Origin fields place those axes from the canvas's bottom-left corner. +* UI: Before the 2D cursor is placed, the 2D Cursor pivot now turns about the world origin, the same point the cursor snaps already used, instead of the selection's median. +* UV Editor: Clicking inside a UV island in Object mode now selects it even where its texture is transparent. Where islands overlap, the one with visible art under the cursor still wins. +* UV Editor: Switching to another page or layer for the first time refits the camera then remembers the camera position from there on. +* UV Editor: Fit View now also frames meshes that sit past the edge of the atlas page. +* Texture Atlas: Repack Atlas is now available on CMO3 models saved with "Show source artwork" turned on. + +### Fixed +* UI: Modal key ladder issue with escape closing the preferences window first instead of the confirmation dialog. +* UI: Dirty documents were obliterated when opening a new document since the dirty check was broken. +* UI: Panel state(open branches, filters, the UV Editor's texture choice) no longer resets when switching workspace tabs. +* UI: Pressing Escape while rebinding a key would close the preferences instead of just cancelling the rebind. +* UI: The keybindings editor's clear button no longer sits underneath the scrollbar. +* UI: Double-clicking a workspace tab after reordering the tabs now renames the tab that was clicked instead of the tab that used to be in that spot. +* Source Artwork: Removed the singleton that could be accidentally be shared across documents. +* Format: An artwork file whose magic bytes are missing now routes to its reader by extension. +* Format: Performance optimizations for the PNG CODEC resulting in up to 50% less memory usage and up to 50% faster loads. +* Viewport: Camera fitting now falls back to the canvas bounds when there are no drawables. +* Viewport: Changing an area between the UV Editor and the 2D Viewport no longer leaves the previous editor's contents and camera behind. +* Outliner: A CTRL+Left Click or Shift+Left Click followed quickly by a plain click on the same row no longer opens rename. +* Source Artwork: "Show source artwork" no longer draws layers misshaped, misplaced, and cut off on CMO3 models whose drawables use Cubism's reduced resolution texture copies. +* Source Artwork: Reloading or relinking a layer in a CMO3 whose drawables use Cubism's reduced resolution copies now points them at the new art on export, so Cubism shows the reloaded layer instead of the stale copy. +* Texture Atlas: Rebuilding the atlas after a reload, Replace Artwork, added artwork, or a repack no longer smears stretched pixels around art that touches the edge of its layer. +* Texture Atlas: CMO3 models saved in Cubism with "Show source artwork" turned on now load the texture atlas as the atlas pages instead of loading every individual layer as an atlas page. +* Viewport: Meshes that reach past the edge of their texture no longer smear the edge pixels across the overhang in the atlas display and clicking that overhang no longer selects the drawable. + + +## 0.3.0-dev - 2026-09-15 + +### Added +* Internationalization: Initial 한국어/Korean translation - Thank you to Nyaro for the translation. +* Export: Rework Cmo3AtlasUndedup to use the shared packer when exporting a fresh CMO3. +* Export: Generate layered art preview thumbnails for CMO3 export. +* Export: A document imported from source artwork(PSD, CLIP, or KRA) now writes its real layers and folders into the CMO3 instead of a synthesized stand-in, so the exported file reopens with every drawable's layer binding intact. +* Texture Authoring: The UV Editor now has object mode. Click an UV island to select the drawable it belongs to, box select multiple, and Alt+Left=Click through overlapping islands, mirroring how object selection already works in the 2D viewport. +* Texture Authoring: A Texture Page selector in the UV Editor header lets you pin the view to a specific atlas page(with its dimensions and mesh count shown) instead of always following the current selection, plus new Next/Previous/Follow Selection commands for stepping through pages from anywhere. +* Texture Authoring: The UV Editor can now show and edit a drawable's mapping directly over its original source layer artwork instead of only the packed atlas page, with a searchable "Find by Artwork" picker to jump straight to a layer's drawable. The cursor, pivot mode, snaps, and proportional editing all carry over to this view exactly as they work on the atlas page. +* Texture Authoring: A new "Show source artwork" document property switches the puppet between rendering from its packed texture atlas and rendering straight from each drawable's individual source layer, for checking the atlas mapping by eye before it's finalized. +* Texture Atlas: A new Repack Atlas command repacks every used piece of source artwork onto fresh atlas pages with Umamo's own packer. Art that can't be packed, too large for a page, empty, or unreadable, cancels the whole repack with a report naming each piece. +* Texture Atlas: Exporting a CMO3 that has been converted from a MOC3 and then had its atlass repacked should now write a fully consistent CMO3. Repacked layers should now properly target the renumbered pages. +* Texture Authoring: Turning on "Show source artwork" for a document whose artwork can't actually be displayed(nothing recoverable, or none of it decodes) now shows a notice instead of silently showing from the atlas instead. +* UI: A new Operation Strip modal will appear after the last operation in the focused 2D or UV viewport to make adjustments. +* Texture Atlas: Artwork placed on an atlas page can now be Grabbed, Rotated, and Scaled directly in the UV Editor's object mode, exactly like moving objects in the viewport. Moving a piece of art carries every drawable mapped to it along with it and the page recomposes around the new arrangement. Overlapping or off-page placements are flagged with an exact warning based on the art's actual painted pixels and mesh coverage, not just a bounding box. +* Texture Atlas: Placed artwork can now be pinned(P / Alt+P in the UV Editor's object mode, or the Data > Texture panel's checkbox) to protect it from being moved. Pinned art is left alone by a hand Grab/Rotate/Scale(which refuses with a clear message if every selected tile is pinned) and by Repack Atlas, whose settings strip has a Keep Pinned Tiles option to override that for a single run. Pinned-tile and warning highlight colors are now configurable in Settings > Colors. +* Texture Atlas: Repack Atlas's options(Max Page Size, rotation, gutter, extrusion, Alpha Threshold, and the square/power-of-two/shrink-to-fit flags) can now be adjusted after it runs from a small settings strip in the corner of the viewport or UV editor(or F9), which re-runs the repack instantly from where it started instead of asking for them in a dialog up front. Add Artwork, Reload, Match Automatically, and moving/rotating/scaling placed artwork get the same adjustable strip for their own settings(Alpha Threshold, Birth Mesh Margin, Match Threshold, and the move/rotate/scale amounts). +* Parameters: New default seed parameters are applied when import artwork for the first time. +* Source Artwork: A new Sources space lists every artwork file behind a document, each file's layers with a bound/bound-by-name/unbound status shown as a traffic-light colored icon, the tiles and drawables under each bound layer, and an Unbound Art group for anything left over, with a filter for Unbound, Missing, or Needs Review. +* Source Artwork: A new File > Import > Artwork… command opens a PSD, CLIP, or Krita(.kra)file, or a flat PNG/BMP/JPEG/WebP/TIFF, straight in as an editable rig. +* Source Artwork: An automatic birth mesh is created for every new drawable on a fresh import. +* Source Artwork: The Sources space's header Reload button re-reads every artwork file still present on disk and folds in whatever changed: a matched layer's tile gets the new pixels, an untouched area is simply re-cut from the new art, and a hand-edited mesh keeps its vertices and keeps sampling the same spot on the canvas. A layer that's gone missing or been renamed is never silently dropped from the rig, it's left alone and flagged for review instead. A CMO3-imported document can still relink and reload from its own original layers even when the source file isn't at its recorded path, or fails to read, by falling back to the layer images embedded in the CMO3 itself. +* Source Artwork: Artwork files can now be watched for changes for automatic reload or notify to reload(See: Setings -> Import). +* Source Artwork: A new Match Automatically command scores every layer that went missing from a reload against the rest of the file(by name, folder, position, size, and pixel content)and proposes a match right on its Sources row. + +### Changed +* Texture Atlas: Where each piece of source artwork sits on the atlas is now part of the document rather than something re-derived every time it's opened, so it can be edited, undone, and written back out. +* MOC3 to CMO3 conversion: The stand-in source document rebuilt from a MOC3's atlas pages now also opens and renders correctly in the official Cubism Editor, including switching between its layered-art and texture-atlas display modes. The export notice wording was updated to describe what's actually still lost this way(the layers are baked-atlas slices, not the original editable artwork) instead of claiming the file wouldn't render at all. +* Source Artwork: The Sources space's relink and file-action menus, and the UV Editor's "Find by Artwork" layer picker, were rebuilt on the app's standard menu component, gaining grouped section headings and a searchable filter for long lists. + +### Fixed +* UV Editor: Committing an edit could report vertices nobody moved as changed, because the display round trip wasn't bit-exact; this triggered spurious weld-divergence warnings on mappings that were never touched. +* MOC3 to CMO3 conversion: Reimported drawables were bound to a duplicate of the atlas page resource instead of the shared one the editor itself writes, which made every one of them look never packed and draw the wrong crop in the source layer view. +* Opening a document while another was already open could, for one frame, pair the new document with the previous document's editing session, so an export, the File menu, or the atlas page resolver could briefly act on stale data. +* Texture Atlas: Repack Atlas could apply a stale pack if a mesh was edited while the repack was still computing; it now cancels instead. +* Keyboard shortcuts could stop responding after using a dropdown chip, checkbox, number field, or section header that then disappeared from the screen while it still held focus; these now properly release focus back to the application. +* CMO3 Export: An artwork-imported document's parameters weren't placed in the export's parameter group hierarchy, and any part, drawable, or deformer with no authored keyforms at all exported with a missing keyform grid, both of which the official Cubism Editor refuses to open. Both are now written the way the editor expects. +* CMO3 Export: A CMO3-origin document's reloaded or newly added artwork kept the old pixels showing in the editor's layered-art view even after the texture atlas had already picked up the new art; it's now written into the document's own retained layer tree too, so both display modes match. + + +## 0.2.1-dev - 2026-08-11 + +### Added +* Diagnostic CLI: A new `:cli` module(`./gradlew :cli:run`) exposes headless `dump`, `convert`, `diff`, and `extract` for inspecting CMO3 and MOC3 files. +* MOC3 export: A new Export Options dialog for choosing MOC3 export granularity. +* History: The number of history steps is now configurable. +* Area Header Controls: Controls in area headers now overflow into a "...>" pop up instead of disappearing. + +### Changed +* CMO3 import and export are now at beta level status. Numerous bugs have been corrected especially on the export side. +* MOC3 import to CMO3 export conversion is now alpha level status. Texture atlases are now automatically cut up into source artwork layers and the produced CMO3 now displays properly in the Cubism editor. While a cut up texture atlas won't be original layered artwork quality this makes it easier to manually reconcile the source artwork layers and also get a functional CMO3. +* Deformers imported from a MOC, which never have a display name in the MOC3, are now labeled with the drawable they deform when that's unambiguous(e.g. "Warp40 (ArtMesh5)") instead of just the raw identifier. +* Export notices, the report shown after an import or export finishes, are now localized instead of always appearing in English. +* The pointer is now properly tracked across all hovered areas and the old "active area ID" was removed. This fixes a lot of hotkey fighting between areas. +* Outliner: After searching then selecting an item in a collapsed branch, the branch is expanded with `revealTarget()` when clearing the search term. +* Viewport/UV HUD Overlay: Now shows the part, drawable, and deformer name in the upper left. + +### Fixed +* Switch a part composite from isolated to anything else stops rendering composite effects. Originally for Umamo it was intended that opacity could be applied to have a part and have it cascade down to drawables to make it quick to change the opacity of all drawables in a part. However, reconciling Cubism behavior with Umamo desires would create too many problems. +* MOC3 export: Identifiers were being deduplicated before being truncated. This means the truncated identifier could then immediately become a duplicate again. Now they are truncated, deduplicated, and properly written into the MOC3 and sidecars. +* MOC3 export: Blend shape deltas under a deformer chain were computed in the wrong point space, looking up the entity's own space instead of its parent's, producing incorrect deltas for any blend shape nested under a deformer. +* MOC3 export no longer silently overwrites existing sidecar files(textures, model3.json, cdi3.json, and the rest) already present at the destination; it now warns and lists every file that would be overwritten before you confirm. +* Windows OS: Workaround for AWT not sending a resize event when cancelling a window resize on Windows causing the Compose around to be stuck at the wrong size until resizing without cancelling. +* Accessibility: Various semantics/contentDescription spots were fixed and visual tooltips added. + + +## 0.2.0-dev - 2026-08-03 + +### Added + +* CMO3 export: Alpha level support of writing Cubism 5.4 compliant CMO3 files. +* MOC3 to CMO3 conversion: Development level support of writing Cubism 5.4 complient CMO3 files converted from MOC3. Source artwork reconciliation is not implemented yet so converted files will not display textures in the official Cubism editor. +* New :interop module that serves as the import and exporting interoperability border between the :format and :runtime modules. +* Keyform Sheet: New editor area for editing key forms and blend shapes for all keyable properties. +* Document > Runtime Target selection: Can now select the runtime target for the puppet including Ayagami and Cubism 3.0 through 5.4. Selecting a target will automatically hide features in the UI that are not available for that runtime. +* Right-click context menu(Cut/Copy/Paste/Select All) on text input fields throughout the UI. This replaces the built-in Compose menu that was blocking some context menus. +* Viewport rendering settings: Super sampling options to toggle off for performance improvements. + +### Changed + +* Properties Panel: Expanded and updated for the Keyform Sheet. Missing properties implemented and the ability to hover over a property then press a shortcut to key it was added. + +### Fixed + +* Dragging a panel splitter gutter no longer lags out and fails to work on slow systems. This was due to an issue with how the movement input was accumulated. +* Dragging a panel splitter gutter only writes up the layout settings after a debounce period. + + +## 0.1.0-dev - 2026-07-27 + +### Added + +* Properties panel: A new editable, tabbed panel(Document/Object/Data) replacing the old read-only Inspector, with a header search that filters down to matching rows and switches tabs automatically. This brings in being able to edit many more puppet properties such as blend modes, alpha modes, compositing, and more. +* Logs panel: A new space showing the diagnostic output, color-coded by severity, with Copy to Clipboard and Export to File actions. +* Tagged releases: pushing a `vX.Y.Z` tag builds, tests, and publishes desktop artifacts for `linux-x64`, `linux-arm64`, `windows-x64`, `macos-arm64`, and `macos-x64` which are self contained application images with a bundled JRE plus a runnable uber jar per target. Unsigned, no installer, no auto-update yet. See [RELEASING.md](RELEASING.md). + +### Changed + +* Composite(part/group) rendering is faster: An isolated part whose blend is pose-identity Normal/Over over an all-Normal/Over subtree now draws inline instead of through its own offscreen layer, and each composite layer's clear/snapshot/draw is scissored to its subtree's posed bounds instead of the full viewport. +* Undo history entries for Grab/Scale/Rotate gestures are now labeled per domain and per operation(e.g. "Scale Vertices", "Rotate UVs", "Scale Objects") instead of collapsing to a generic "Move..." label regardless of what actually happened. +* The legacy "Add (Before 5.3)" / "Multiply (Before 5.3)" blend modes are relabeled "(Legacy)" and sorted to the bottom of the blend-mode picker; their properties no longer show the Alpha Blend field, which never applied to them. They might be renamed again in the future. + +### Fixed + +* Deformer opacity and multiply/screen color keyforms are now applied and cascade down the deformer hierarchy, so keying a deformer's opacity to show/hide a subtree, or its tint color to color a group animates correctly instead of being ignored. +* CMO3 artwork that wasn't packed into a texture atlas rendered enlarged with its outer margin clipped because its UVs weren't remapped through the image's logical frame transform. +* The legacy "Add"/"Multiply" blend modes rendered with incorrect, non-premultiplied math whenever Alpha Blend was set to anything other than "Over". +* The "Out" alpha blend mode cut a hole in the wrong layer(source instead of destination) inverting the intended silhouette effect. +* Extended blend modes(Multiply, Screen, Overlay, etc.) mis-blended under Conjoint/Disjoint alpha blending because the blend mix weight ignored the selected alpha mode; unpremultiplied colors are now also clamped to avoid out of range artifacts. +* MOC3-imported drawables' multiply/screen tint keyforms were silently dropped when rest mesh geometry was rebased to canvas space. + + +## 2026-07-14 – 2026-07-20 + +### Added + +* Source-art format support: readers for **BMP, JPEG, PNG, TIFF, and WebP**, alongside the existing PSD/CLIP/KRA support, broadening what art files Umamo can ingest. +* Alpha Shape Analysis: Pass that traces and simplifies the silhouette of a layer's alpha channel which is early groundwork toward automatic mesh generation from source art. +* MOC3 Import: Umamo can now load existing `.moc3` runtime files directly (not just `.cmo3` editor projects), converting them into an editable puppet. +* Blend Shape Support: Corrective blend shapes implemented end-to-end: decode/encode in the MOC3 format, CPU/GPU evaluation, and rendering, matching Cubism behavior. +* Offscreen/Composite Rendering: Parts can now render to an offscreen buffer and be composited with correct opacity and blend modes across nested groups, matching Cubism's part-level offscreen drawing feature in the viewport. +* Active/Selected object is now highlighted in a distinct color in the outliner and viewport. +* Snap radial(pie) menu for the UV Editor. + +### Changed + +* Rebuilt the renderer around a backend-neutral `RenderDevice` abstraction, splitting the previously monolithic GL renderer into focused pieces (shaders, frame encoding, GPU resource handles). This lays groundwork for future Android (GLES) and macOS/iOS (Metal) rendering backends. +* Outliner row striping now fills top-to-bottom consistently. +* CI now runs GL rendering tests in a headless environment. + +### Fixed + +* MOC3 import: incorrect rotation-deformer scaling. +* Several CMO3 read/write round-trip issues. +* MacOS crash/blank-viewport bug caused by an incorrect GLFW library binding (community contribution from Giodotblue). \ No newline at end of file diff --git a/CREDITS.md b/CREDITS.md new file mode 100644 index 0000000..48a81f2 --- /dev/null +++ b/CREDITS.md @@ -0,0 +1,110 @@ +# Credits & Third-Party Attributions + +Umamo is licensed under the GNU General Public License v3.0. +Project Lead: Azxiana - https://azxiana.com/ + +## Translations +한국어/Korean - Thank you to Nyaro for the translation. + +## Gylphs + +Tabler Icons - MIT License - https://github.com/tabler/tabler-icons/blob/main/LICENSE +Inter Font - SIL Open Font License 1.1 - https://raw.githubusercontent.com/rsms/inter/v4.1/LICENSE.txt +Noto Sans CJK - SIL Open Font License 1.1 - https://github.com/notofonts/noto-fonts/blob/main/LICENSE +Blender Icons - CC BY-SA 4.0 - https://creativecommons.org/licenses/by-sa/4.0/ - https://ui.blender.org/icons +Blender Cursors - GNU General Public License v3.0 - https://projects.blender.org/blender/blender/src/branch/main/doc/license/GPL3-license.txt - https://projects.blender.org/blender/blender/src/branch/main/release/datafiles/cursors + +## MOC3 File Format + +Umamo's MOC3 file format reader is based on Lina Hoshino's black box reverse engineering of the format. +https://www.youtube.com/@HoshinoLina +https://www.youtube.com/watch?v=eEa0-wt1SqE +https://www.youtube.com/watch?v=iT3A0AhK3YE +https://www.youtube.com/watch?v=5AiZTgUx_WM + +## Krita KRA File Format + +- Upstream: Krita - https://invent.kde.org/graphics/krita +- License: GNU Public License, Version 3 + +Umamo's KRA file format reader was ported directly from the official Krita repository. + +## Clip Studio Paint CLIP File Format + +Umamo's CLIP file format reader is based on research by rasensuihei. +https://github.com/rasensuihei/cliputils +MIT License: https://github.com/rasensuihei/cliputils/blob/master/LICENSE + +## TwelveMonkeys ImageIO - PSD, TIFF, and WEBP readers (BSD 3-Clause) + +- Upstream: TwelveMonkeys ImageIO, `imageio-psd` module - https://github.com/haraldk/TwelveMonkeys +- Copyright (c) 2008-2020 Harald Kuhr +- License: BSD 3-Clause + +- Upstream: TwelveMonkeys ImageIO, `imageio-tiff` (and `imageio-metadata`, `common-io`) modules - https://github.com/haraldk/TwelveMonkeys +- Copyright (c) 2012 Harald Kuhr, Oliver Schmidtmer +- License: BSD 3-Clause + + Covers the LZW, PackBits, horizontal-predictor, and CCITT (Modified Huffman RLE / T.4 / T.6) decoders. + The IFD parser, pixel assembly, and JPEG-in-TIFF handling are Umamo's own. + +- Upstream: TwelveMonkeys ImageIO, `imageio-webp` module - https://github.com/haraldk/TwelveMonkeys +- Copyright (c) 2017 Harald Kuhr, Simon Kammermeier +- License: BSD 3-Clause + +Per the BSD 3-Clause terms, the original copyright notice is retained here and in the header of the derived source file. The ported code is distributed as part of Umamo under GPLv3. + +``` +BSD 3-Clause License + +Copyright (c) 2008-2020, Harald Kuhr +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +## Baseline JPEG Decoder - Independent JPEG Group + +- Upstream: Independent JPEG Group's reference JPEG library (libjpeg) - https://www.ijg.org/ +- Copyright (c) 1991-2020, Thomas G. Lane, Guido Vollbeding +- License: IJG License (permissive, GPL-compatible) + +Umamo's JPEG decoder (`org.umamo.format.jpeg`) is an independent Kotlin implementation written from the public ITU-T T.81 specification. Accordingly, and per the IJG license's terms for distributing derived work: + +> This software is based in part on the work of the Independent JPEG Group. + +The decoder is distributed as part of Umamo under GPLv3. + +## poly2tri — constrained Delaunay triangulation (BSD) + +- Upstream: orbisgis/poly2tri - https://github.com/orbisgis/poly2tri +- License: New BSD License + +Used by Add Vertex Accept to triangulate closed draft rings with zigzag (Delaunay) diagonals. + +## Bundled Libraries +FileKit - https://github.com/vinceglb/FileKit/blob/main/LICENSE +poly2tri - https://github.com/orbisgis/poly2tri \ No newline at end of file diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..5384ff7 --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,9 @@ +This is purely for a marketing blitz later. + +* Modern UI that doesn't suck! +* CMO3 Import/Export! +* MOC3 Import/Export! +* Krita(KRA) and Photoshop(PSD) Import! +* Resolution independent scaling(Modern!) +* Pen and Touch Support! +* Android! (Tablets only though, you're crazy if you try to do this on your phone.) \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..deea74a --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + {{ project }} Copyright (C) {{ year }} {{ organization }} + 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 +. + + 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 +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..41f0731 --- /dev/null +++ b/README.md @@ -0,0 +1,261 @@ +# Umamo + +An open-source cross-platform modelling editor for 2D puppet animation, with first class pen and touch support, designed to interoperate with the Live2D Cubism source format (`.cmo3`). Runs on Windows, macOS, Linux, and Android tablets with pen/touch input. Supports importing and exporting both CMO3 and MOC3 formats. + +> **Status:** Early development. Prebuilt downloads are on the [Releases page](https://github.com/umamoorg/umamo/releases). Note, releases are not currently signed so Windows and MacOS will complain about it. APIs, formats, and scope are in flux. + +![Screenshot showing the main Umamo window with 2D puppet posed and smiling in a centered viewport. The left side shows an adjustable parameter panel while the right shows an object outliner, information, and history panel.](docs/screenshots/readme20260905.webp) + +## Quick Notes + +**Q:** Can I support the Umamo project financially? + +**A:** Umamo is completely open source and free, but if you would like to support the project you can [join the Patreon](https://patreon.com/Azxiana) or make a one time [donation through Ko-Fi](https://ko-fi.com/azxiana). All received funds go directly to paying hosting bills, hardware for testing, and platform developer fees. Excess funds will be banked for the future or distributed to other open source projects working with the Umamo Project. + +--- + +**Q:** Does Umamo do animations yet? + +**A:** Not yet. This is a long term stretch goal. Getting the modeling, UV editor, and physics interface perfected first will be important for animation later. + +--- + +**Q:** Umamo doesn't support a newer version of Cubism/Krita/Clip Studio Paint file formats yet. Can you add support? + +**A:** Yes, please [search if the issue has already been reported](https://github.com/umamoorg/umamo/issues) and if not, [open a new issue](https://github.com/umamoorg/umamo/issues/new) that describes the problem. + +--- + +**Q:** Umamo corrupted my project and I lost my work! HELP! + +**A:** Currently Umamo is alpha level software available for testing. Please make sure to **make regular backups** of your files. In fact, make second copies of your files explicitly for playing around with. Do not use the original copies. + +## Downloads + +Every tagged version publishes desktop builds on the [Releases page](https://github.com/umamoorg/umamo/releases). There are two different releases per platform: + +| File | Note | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `umamo--.zip`/`.tar.gz` | Java SDK not required, just run it directly. | +| `umamo--.jar` | You will need Java SDK 21 or higher to run. Either open through the file browser or through the command line. `java -jar umamo-...jar` | + +Targets: `linux-x64`, `linux-arm64`, `windows-x64`, `macos-arm64`, `macos-x64`. Check your download against the release's `SHA256SUMS.txt`. + +**These builds are not signed.** Code signing and notarization cost a lot of money so I will be waiting to do that until getting to a release candidate stage. Until then Windows and MacOS will complain about the applications being unsigned. + +- **MacOS:** Gatekeeper will quarantine the application and report it as *damaged*. It is not damaged. After unzipping run this in the Terminal, `xattr -dr com.apple.quarantine /path/to/umamo.app`, or allow the application through the settings. +- **Windows:** SmartScreen shows "Windows protected your PC". Choose *More info* -> *Run anyway*. +- **Linux:** Just run the application: `tar xzf umamo-*.tar.gz` and run `umamo/bin/umamo`. Linux doesn't restrict you from running any application that you wish to run on your computer. + +### Opening .uma files from the file manager + +Since the builds are plain archives without installers the `.uma` mimetype won't be registered automatically by the operating system. Linux has a manual mimetype registration option while Windows and MacOS will wait for their respective installers in the future. + +- **Linux:** The archives come with freedesktop.org files to register the mimetype manually. Put `umamo/bin/umamo` on your `PATH`(or edit the `Exec=` line in `umamo.desktop` to its full path), then register them for your user: +```bash +xdg-mime install --novendor umamo/lib/app/resources/umamo-uma.xml +xdg-desktop-menu install --novendor umamo/lib/app/resources/umamo.desktop +``` +`xdg-mime uninstall` and `xdg-desktop-menu uninstall` with the same files to undo it. + +## Building & Development + +Umamo is a Kotlin Multiplatform project (Gradle, Kotlin DSL) targeting desktop and Android from one shared codebase. + +| Platform | Note | +| -------- | --------------------------------------------------------------------------------------------------- | +| Windows | Regularly built and tested | +| Linux | Regularly built and tested | +| MacOS | Working, minimally tested. | +| Android | Not yet, incomplete graphics layer implementation is blocking it. | +| iPadOS | Application and UI loads, but there is no puppet renderer and JDOM is incompatible. | + +### Prerequisites + +- **JDK 21** (LTS). The build is pinned to a 21 toolchain. Point `JAVA_HOME` at a JDK 21 — e.g. `export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64`. (Newer JDKs run Gradle fine, but are ahead of the Android toolchain.) Use a distribution JDK, not Homebrew's: `:desktop:createDistributable` runs Compose's `checkRuntime`, which hard-errors on a Homebrew JDK unless you pass `-Pcompose.desktop.packaging.checkJdkVendor=false`. +- **Android SDK** with `platforms;android-36` and `build-tools;36.0.0`. Set `ANDROID_HOME` (or create `local.properties` with `sdk.dir=…`). Only needed for the Android target. + +The Gradle wrapper (`./gradlew`) pins the Gradle version so no system Gradle install required. + +### Common commands + +```bash +./gradlew :desktop:run #Launch the desktop editor +./gradlew :android:installDebug #Deploy to a connected Android tablet +./gradlew build #Everything +./gradlew test #Unit tests +./gradlew ktlintFormat #Format all files according to .editorconfig +./gradlew -q :cli:run --args="dump model.moc3" #Dump a CMO3/MOC3's contents to stdout +./gradlew -q :cli:run --args="convert model.cmo3 out.moc3" #Convert between formats(Overwrites WITHOUT confirmation) +./gradlew -q :cli:run --args="diff a.cmo3 b.moc3" #Compare two models semantically +# Cross-target the desktop build (default: host). -Pumamo.target swaps the bundled Skiko + LWJGL +# natives: linux-x64 | linux-arm64 | windows-x64 | macos-x64 | macos-arm64. +./gradlew :desktop:packageUberJarForCurrentOS -Pumamo.target=windows-x64 +# Self-contained app image with a bundled JRE (what the release workflow ships). +# → app/desktop/build/compose/binaries/main/app/ +./gradlew :desktop:createDistributable +``` + +`-Pumamo.target` is meaningless for `createDistributable` and must not be combined with it: an app image jlinks the *host* JDK into itself, so cross-resolving the natives would bundle one platform's Skiko/LWJGL inside another platform's runtime. Only the uber jar is portable that way. Pass `-Pumamo.requireTargetIsHost=true` (as CI does) to turn a mismatch into a build failure. + +### Running on WSL2 (WSLg) + +Two things differ from a native Linux box (neither applies on a real desktop/GPU): + +- **Use the system JDK 21, not Homebrew's.** Homebrew's `openjdk@21` has a few issues resolving libraries so it is easier to use the system installed JDK. Install `sudo apt install openjdk-21-jdk` and point `JAVA_HOME` at it: `export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64`. +- **Opt into the GPU.** Mesa defaults to the `llvmpipe` software rasteriser on WSL; select the hardware D3D12 path explicitly. Compose's own Skiko renderer can't make a hardware GL context under WSLg, so let it fall back to software. + +```bash +MESA_LOADER_DRIVER_OVERRIDE=d3d12 GALLIUM_DRIVER=d3d12 SKIKO_RENDER_API=SOFTWARE \ + ./gradlew :desktop:run +``` + +### Cross-building for another platform + +By default the desktop build bundles the natives for the machine running it. Pass `-Pumamo.target=-` to bundle a *different* platform's natives instead which is useful for testing a Windows build from a WSL2/Linux checkout. Recognized targets: `linux-x64`, `linux-arm64`, `windows-x64`, `macos-x64`, `macos-arm64`. + +```bash +# Produce a Windows-native runnable uber-jar from WSL2/Linux: +./gradlew :desktop:packageUberJarForCurrentOS -Pumamo.target=windows-x64 +# → app/desktop/build/compose/jars/ +``` + +This swaps both the Compose/Skiko renderer native and the LWJGL GL natives so the jar runs on the target. It is **not** a cross-compiler: the result is portable JVM bytecode plus the target's natives, so you still need a **matching JVM on the target** to launch it. + +Don't combine `-Pumamo.target` with `:desktop:run` — that would load the target's natives in your host JVM and fail. The override is for producing artifacts and not running locally. + +### Module layout + +Reusable library modules live under `module/`, runnable application targets under `app/`. Everything else at the repo root (`gradle/`, `docs/`, build files) is intentionally *not* a module. A module's Gradle path (`:format`) is kept flat and independent of its folder. See: [settings.gradle.kts](settings.gradle.kts) + +| Module | Directory | Targets | Role | +| ----------- | ----------------- | ------------- | ------------------------------------------------------------------------------------------------------ | +| `:format` | `module/format` | jvm + android | Cubism file family + art I/O (CMO3 read/write, …) | +| `:reimport` | `module/reimport` | jvm + android | Source-art binding + non-destructive reconcile | +| `:storage` | `module/storage` | jvm + android | App config/data dirs + file IO (okio) + native file dialogs (FileKit) | +| `:settings` | `module/settings` | jvm + android | JSON settings: defaults←user merge, dotted get/set, change Flow → `:storage` | +| `:runtime` | `module/runtime` | jvm + android | Puppet model + CMO3 ingest | +| `:render` | `module/render` | jvm + android | Deformation eval (CPU) + renderer + morph-blend shaders (`expect`/`actual`: LWJGL / GLES) → `:runtime` | +| `:ui` | `module/ui` | jvm + android | Compose Multiplatform editor shell | +| `:desktop` | `app/desktop` | jvm | Desktop entrypoint (Compose Desktop + LWJGL viewport) | +| `:android` | `app/android` | android | Android entrypoint (Activity + Compose + GLSurfaceView) | + +Shared logic lives in `commonMain`; platform code in `jvmMain`/`androidMain` via `expect`/`actual`. + +### Input, Commands, & Settings + +- **Action registry.** Every editor operation is a named `Command` in a central `CommandRegistry` (`:ui`, `org.umamo.ui.action`); menus, the command palette, and key bindings all dispatch through it, so handlers are never hardcoded in widgets. A command palette lists the registry with adaptive search. +- **Key bindings.** Chords are stored logically, by key *position* plus a platform "primary" modifier (CMD on macOS, CTRL elsewhere), so shortcuts survive non-QWERTY layouts and map per OS. They resolve through a `Keymap`; a built-in default (`defaultKeymap`) along with editable user-persisted keymaps and presets(settings `input.keybinding.preset`). +- **Settings.** A layered JSON tree: bundled defaults ← user overrides, addressed by dotted keys (`:settings`), persisted via `:storage` and emitting change events the UI reacts to. + +### File formats + +Editor-format knowledge for CMO3, MOC3, and CLIP are reverse-engineered by black box observation. KRA is ported directly from Krita's own open-source GPLv3 code which is license-compatible with Umamo. All are written up under [`docs/format/`](docs/format). + +#### File Format Support + +| Format | Read | Write | Note | +| ------ | ---- | ----- | ---------------------------------------------------------------------------------------- | +| PSD | 〇 | - | Photoshop (Read only) | +| CLIP | △ | - | Clip Studio Paint (Read only) - Implemented, not fully tested. Has some blending issues. | +| KRA | 〇 | - | Krita (Read only) - ZIP + maindoc.xml + tiled LZF rasters; ported from open source. | +| UMA | 〇 | 〇 | Umamo Model File | +| CMO3 | 〇 | 〇 | Cubism Editor Model File - Compatible up to Cubism 5.4 | +| MOC3 | 〇 | 〇 | Cubism Distribution Model File - Compatible up to Cubism 5.4 | + + +#### Format Documents + +Reverse engineered file formats have documentation in the [docs/format/](docs/format/) folder. + +#### Diagnostic CLI + +The `:cli` module (`app/cli`) is a headless dump, convert, diff, and atlas packing tool over the same CODEC and conversion stack the editor uses. Run it through Gradle; relative paths resolve against the repository root. Always pass `-q` so Gradle's own build output stays out of the tool's output. The tool writes data to stdout and diagnostics to stderr. The convert command will **overwrite WITHOUT confirmation**. + +```bash +./gradlew -q :cli:run --args="dump model.moc3" #Static-rig summary +./gradlew -q :cli:run --args="dump model.moc3 --sections" #Container tier: per-section presence + counts +./gradlew -q :cli:run --args="dump model.cmo3" #CAFF entry table + main.xml overview +./gradlew -q :cli:run --args="dump model.cmo3 --xml" #Decompressed main.xml, byte-for-byte (Redirectable) +./gradlew -q :cli:run --args="dump model.cmo3 --puppet" #Import to PuppetModel and summarize (Either format) +./gradlew -q :cli:run --args="dump art.psd" #Artwork canvas, folders, per-layer inventory + trimmed bounds +./gradlew -q :cli:run --args="extract model.cmo3 out/" #Unpack the archive (Plaintext main.xml + layer PNGs) into out/model/ +./gradlew -q :cli:run --args="atlas art.psd out/" #Pack the layers into out/art/page_NN.png + placements.txt +./gradlew -q :cli:run --args="atlas art.clip out/ --preview" #Also recomposite the canvas from the packed pages. +./gradlew -q :cli:run --args="convert in.cmo3 out.cmo3" #Resave (An unedited main.xml will reemit byte-identical.) +./gradlew -q :cli:run --args="convert in.moc3 out.moc3" #Rebake (Fresh synthesis, NOT byte-identical by design.) +./gradlew -q :cli:run --args="convert in.cmo3 out.moc3" #Full family: moc3 + model3.json + cdi3.json + textures +./gradlew -q :cli:run --args="convert in.moc3 out.cmo3" #Fresh-graph synthesis (Always reports MissingSourceArt) +./gradlew -q :cli:run --args="diff a.cmo3 b.moc3" #Semantic per-entity diff of two models +``` + +A moc3 input may also be given as its `.model3.json` manifest; textures and sidecars(cdi3/physics3/pose3/userdata3) are discovered through the manifest's file references. + +Both `dump` and `atlas` accept source layered artwork(`.psd`, `.clip`, `.kra`) or any flat raster read as a one-layer document. The `atlas` command takes `--page-size=N`, `--gutter=N`, `--extrude=N`, `--rotate`, `--visible-only`, and `--no-shrink`. It reads every packed tile back out of its page and exits non-zero if any byte differs and reports layers it could not pack(no opaque pixels, or larger than a page) rather than dropping them silently. + +#### Running Tests + +All tests can be run with `./gradlew test` or individual tests can be run like so: + +`./gradlew :interop:jvmTest --tests "org.umamo.interop.PuppetModelDiffTest"` + +#### Corpus Testing + +Each CODEC and reader have tests that run against real samples that you can supply. Note: The `/test/corpus` is intentionally gitignored to prevent accidentally committing private data. If you don't supply samples then the tests will automatically skip. + +Put your samples at `test/corpus/` and they are picked up automatically: + +``` +test/corpus/cmo3/ EricaTamamo.cmo3 (the model the CMO3 gate's exact counts are pinned to) +test/corpus/moc3/ Put each model's files in a separate subdirectory. + +Artwork: +test/corpus/clip/ test/corpus/psd/ test/corpus/krita/ test/corpus/tiff/ test/corpus/jpeg/ +``` + +```bash +./gradlew :format:jvmTest #Corpus automatic discovery. +./gradlew :format:jvmTest -Dcmo3.sample=/path/to/Model.cmo3 #Point at one explicitly. +./gradlew :format:jvmTest --tests "org.umamo.format.cmo3.tools.ModelGenerator" -Dcmo3.generate=true -Dcmo3.gensample=/path/to/Model.cmo3 --rerun #Generate new CMO3 model and registration. Make sure to run ktlintFormat afterwards to clean up. +``` + +## Legal & Trademark Notice + +Umamo is an independent, community-developed project. It is **not affiliated with, authorized by, endorsed by, or sponsored by Live2D Inc.** (formerly Cybernoids Co., Ltd.) or any of its affiliates. + +"Live2D®" and "Cubism" are trademarks of Live2D Inc. in Japan and/or other countries; all other trademarks are the property of their respective owners. These marks are used here only nominatively, to describe file-format compatibility, and **no endorsement, affiliation, or sponsorship is implied.** + +## Contributors + +WANTED: Human translations for various languages.(Japanese, Chinese, Korean, Spanish, French, German, etc.) +The English strings are located at: `module/ui/src/commonMain/composeResources/values/strings.xml` + +At the moment I'm not accepting large code contributions from outside contributers. Small fixes are accepted, but please keep in mind that at moment the development speed on this project is rapid. I'm might make your change obsolete by the time I get around to reviewing it. + +(Once large changes are accepted in the future.) +If you are planning a large change that touches many files then break it down into a stack of smaller pull requests that build on each other. For example, if you're adding a new export format: +* PR 1: Add the underlying data structures/parser with tests, no UI wiring yet. +* PR 2: Add the export logic that consumes those structures, merged on top of PR 1. +* PR 3: Wire up the UI/CLI flag that exposes the feature, merged on top of PR 2. + +Each PR should be reviewable and mergeable on its own instead of being submitted as one giant diff. This makes review faster and makes it easier to bisect regressions. + +### Provenance & Reverse Engineering + +Umamo's **editor-format layer** (`.cmo3`/`.moc3` read/write, `.clip` ingest) is a **clean-room reimplementation** built from black-box observation of file outputs and independently produced documentation. + +By contributing you affirm: + +1. No use of official Live2D/Cubism source or decompiled binaries as a basis, knowledge only from observing file outputs and public, independently authored documentation. +2. You are not bound by a Live2D agreement your contribution would breach, and will disclose any such license before contributing. +3. Are not a past or present employee of Live2D or Cybernoids. + +If you have been exposed to Live2D source code or decompiled binaries, please do not contribute. + +### AI Usage Disclaimer + +Large Language Models(LLM) are used to assist with [rubber ducking](https://en.wikipedia.org/wiki/Rubber_duck_debugging) and housekeeping tasks. Assisted tasks include planning development road maps, function documentation, and helping to keep the developer focused. AI has not been and will never be used to decompile or otherwise discover the source code of protected software. + +## License + +**GPLv3** See [LICENSE](LICENSE) diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..9d9fd1d --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,82 @@ +# Releasing Umamo + +Pushing a semantic version tag builds, tests, and publishes desktop artifacts for all five supported targets. + +## What ships + +Two files per target, ten in total, plus a `SHA256SUMS.txt`: + +| File | For | +| ------------------------------------------ | ---------------------------------------------------------------------------------------- | +| `umamo--.zip` / `.tar.gz` | Self-contained app image (`:desktop:createDistributable`). Bundles a jlinked JRE. | +| `umamo--.jar` | Uber jar (`:desktop:packageUberJarForCurrentOS`). Needs a JDK/JRE 21 on the machine. | + +Targets and the runner each is built on: + +| Target | Runner | +| ------------- | ------------------ | +| `linux-x64` | `ubuntu-latest` | +| `linux-arm64` | `ubuntu-24.04-arm` | +| `windows-x64` | `windows-latest` | +| `macos-arm64` | `macos-latest` | +| `macos-x64` | `macos-15-intel` | + +Every leg builds on its own OS and architecture. Unlike the uber jar, an application image cannot be cross-produced: jpackage jlinks the *host* JDK into the image, so cross-resolving natives would bundle one platform's Skiko/LWJGL inside another platform's runtime. The package job passes `-Pumamo.requireTargetIsHost=true` so an unexpected runner `os.arch` fails the build rather than shipping an artifact that runs nowhere. + +Out of scope until alpha: code signing, notarization, native installers, auto-update, and any Android artifact. See `TODO.md` § Build and Distribute. + +## File associations + +The `.uma` document type (`application/vnd.umamo.uma+zip`, `docs/format/UMA.md` § 2) is declared once per OS in `app/desktop/build.gradle.kts` (`fileAssociation`) and in the Android manifest. What that does depends on the artifact, because on Windows and Linux jpackage applies `--file-associations` to **installers only**: + +| Platform | Today's artifacts | With an installer | +| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | +| Linux | Not registered. The app image ships `lib/app/resources/umamo-uma.xml` and `umamo.desktop`; the README gives the two per-user `xdg-*` commands. | deb / rpm register the type. | +| Windows | Not registered. *Open with* only. | msi / exe register the type. | +| macOS | The app image's own `Info.plist` carries `CFBundleDocumentTypes`, so an unpacked `umamo.app` is the handler with no installer - but see below. | Same. | +| Android | The manifest's VIEW intent filters; no artifact ships yet. | n/a | + +The macOS legs publish the uber jar only until JDK 27 (the `appImage: false` note in `release.yml`), and a jar has no bundle to associate. Setting `appImage` back to `true` is therefore also what switches the macOS association on; the open-file handler in `Main.kt` is already in place for it and has not been exercised on a real bundle. + +`OsAssociationFilesTest` (`:desktop`) holds the build script, the manifest, and both freedesktop files to the codec's `Uma.MIME_TYPE`, and evaluates the freedesktop magic against a file the writer really produces. Those files are declared as inputs of `:desktop`'s test task - they are not on its classpath, so without that an edit to one leaves the test up to date and unrun. + +## Cutting a release + +1. Bump `VERSION` in `module/ui/src/commonMain/kotlin/org/umamo/ui/help/ProjectInfo.kt`. The workflow **verifies** the tag against it and never injects a version so a mismatch will fail with an annotation telling you what to fix. +2. Update the `CHANGELOG.md` with new changes under a `## [X.Y.Z] - YYYY-MM-DD` heading. +3. Run the pre-flight checks below. +4. Merge to `master`, then tag and push: + ```bash + git tag vX.Y.Z && git push origin vX.Y.Z + ``` +5. The workflow creates the release as a **draft**, marked prerelease when the version carries a suffix. Download the artifacts and launch at least one per OS before publishing. The CI does not test the packaged binaries. +6. Publish: `gh release edit vX.Y.Z --draft=false`, or discard and re-tag: + ```bash + gh release delete vX.Y.Z --yes + git push --delete origin vX.Y.Z && git tag -d vX.Y.Z + ``` + +Prerelease tags are supported as well, so having `-dev` or `-rc` is fine. However, jpackage rejects prerelease suffixes, so `project-version.gradle.kts` strips it for `packageVersion` while everything user visible keeps the full string. + +To rehearse the whole pipeline without a tag, run the workflow manually(`gh workflow run release.yml --ref `). With no tag, the version gate synthesizes `v`, sets `publish=false`, and the publish job is skipped. All of the artifacts will be visible on the action runner page and not published as a release. + +## Local Pre-flight Checks + +```bash +# Export a compatible Java SDK location other Compose's checkRuntime will error. +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 + +./gradlew :desktop:suggestRuntimeModules # after any dependency change +./gradlew :desktop:createDistributable :desktop:packageUberJarForCurrentOS +./gradlew build # what the release gate runs + +# The corpus suites specifically — see the caching caveat below. +./gradlew :format:jvmTest :runtime:jvmTest :render:jvmTest :ui:jvmTest --rerun +``` + +Then check the app image at `app/desktop/build/compose/binaries/main/app/`: + +* `umamo/lib/app/umamo.cfg` — the `[JavaOptions]` block must carry `-Xmx4g` and **must not** carry `-Dumamo.testCmo3`. Compose forwards `application.jvmArgs` to jpackage as `--java-options`, so anything added there ships; the corpus-preview override is deliberately set on the `run` task alone (see the comment at the bottom of `app/desktop/build.gradle.kts`). +* `umamo/lib/runtime/release` — the `MODULES=` line must list `java.instrument`, `java.sql`, `java.xml`, `jdk.security.auth`, and `jdk.unsupported`. The release workflow asserts this too. + +`suggestRuntimeModules` under-reports: it misses reflective and service-loaded edges, and does not name `java.xml` even though JDOM — and therefore all of CMO3 read/write — needs it. Treat its output as a lower bound and confirm with `jdeps --list-deps` when adding a dependency. \ No newline at end of file diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..52a6253 --- /dev/null +++ b/TODO.md @@ -0,0 +1,298 @@ +# TODO + +## Documentation +* Have a full model/ map made in docs/. (When everything is done.) + +## Deferred +* GPU glue: multi-pair seam vertices (deferred 2026-06-21) +* Android GLES renderer backend (deferred 2026-06-21) + +## WORK STEPS - 2026-09-14 +~~1.) Leftovers - Art Sourcing Pipeline Verification~~ +~~2.) Operation Strip - Make sure all application operations are using it.~~ +~~3.) Phase C - Art Sourcing Pipeline - Cmo3AtlasUndedup Refit~~ +~~4.) Phase H - Art Sourcing Pipeline - CMO3 Interop Hardening~~ +5.) Phase D - Art Sourcing Pipeline - Automatic Mesh from Art - This should become it's own planning document. +6.) (Everything required for glue, deformers, and so on.) +7.) UMA Format (Phase G - Art Sourcing Pipeline) - Mostly done, a few final pieces to go through. + +## VERY IMPORTANT +* Hire translators for localization. +* Final pass on keyboard shortcuts. +* Final pass on default settings. +* Final pass on default workspace layouts. +* Final pass on theme colors. + +## User Stories +* glTF export for easy import into game engines. (Requested; far future.) + * Shares buffer/accessor concepts with UMA's bulk-geometry encoding decision (docs/plan/uma-format.md U1), and would slot into the Document › Runtime export-targets model (§ Properties Panel). +* From CrystalorImLisa on Reddit: The ability to mirror deformers and drawables along with their key frames. + * Umamo solution: Select a deformer and the drawable -> Duplicate -> Mirror X (On the duplicate) -> Do some minor UV clean up -> Done! + * https://www.reddit.com/r/Live2D/comments/1uy0871/is_there_a_way_to_duplicate_a_warp_deformer/ +* From @thesillydarku on Twitter: "I had to manually add the "-Xmx4g" flag otherwise got java memory heap errors when trying to export to CMO3" + * https://fixupx.com/thesillydarku/status/2102974212952707294 + +## Artwork Import +* We need to properly handle different blending mode imports from artwork to setup the drawables automatically. +* Automatic visual matching of imported artwork layers to layers cut from a texture atlas after a MOC3 to CMO3 conversion. + +## Puppet Model, CMO3, MOC3 +* Parameter Repeat +* Glue +* CMO3 + * ACParameterControllableSource.isVisible was wired up so now the outliner needs this toggle as well. Deformer editing is not implemented yet so this is minor. + * Refactor interop/cmo3/ in the same way that interop/moc3/ was done. +* MOC3 + * (Check the bullshit the AI did without my permission.) CDI3 - Export mesh display names as a separate array. + * Reconcile isVisible/isEnabled from MOC3 for deformers. Maybe for CMO3 too. + +## Tools, Shortcuts, and Gizmos +* Improvements + * Unconnected proportional editing should edit all meshes when multiple meshes are selected for edit mode. I would like to merge the proportional button and falloff settings into one menu with the connected checkbox. + * ALT+H (Unhide All) and SHIFT+H (Hide everything that is not selected.) +* New Icons (For myself to get/make.) + * Replace magnet from the cursor/selection menu. + * The Tabler icons on the toolbar are probably fine, but I will check what is available from the Blender icons. + +## Overlays Toggle +* Overlay visibility toggles from viewport header. + * General Information - The spot in the AreaHeader showing the selected item will be moved here. It's too much in the AreaHeader. + * Wireframe (Object Mode) + * Grid - Ability to change scale and divisions. + * 2D Cursor + +## Object and Mesh Editing +* Improvements + * Mirror along X/Z axis, mirror with 2D cursor as the axis. Note: This is a small divergence to Blender's style. In Blender there is an origin for each object that can be moved to different places. Umamo still has the centroid origin calculated, but no way to move it or even if it was moved, a way to store it. + * Extrude(E) - Extrude an edge creates triangle cut quad automatically. + +## Texture Authoring/UV Editor +* Follow Selection Header Control - Split it into options and images. + * New custom image selection control. This will also be an entry point for adding artwork. + * Support renaming images. +* Improvements + * Long running atlas packing should have a progress visible in the status bar. We can also reuse this for other operations such as file open/import/export. +* Bugs + * When relinking EricaTamamo.psd in EricaTamamo.cmo3 it results in some layers getting fringe artifacts like what was experienced in the past. + +## UV Editor +* Bugs/Improvements + * Rip and Vertex Slide could be implemented for UV. + * Do a study to determine if rip functionality is really needed. It is definitely needed for 3D work, but for 2D work I think it is less useful. Though I'm curious what people would create with the functionality being available. + * Mirror UVs are shown in the command palette when editing a mesh in the 2D viewport. + * This is actually kind of useful, but technically breaks the border of the command palette only showing what is available per area. + * Pixels outside of the canvas still need to render. +* UV Snap Pie + * (Deferred) Selected to Adjacent Unselected - Moves selection to adjacent unselected element. + * Implementation difficulty: This moves the UV vertex that has been disconnected from its sibling, which is one vertex in the mesh, on top of each other. We will have to either walk the UV/mesh to find the sibling or store it. Selected to Adjacent Unselected is only needed if rip is supported in UVs. +* Relax/Pinch tools - deferred; needs brush machinery (radius cursor, per-stroke commits) that nothing else has yet. + +# Mesh and UV Editor Gizmos +* Improvements + * Hold CTRL to enable snapping for rotation and grid placement. + +## Shortcuts +https://hollisbrown.github.io/blendershortcuts/ - I should make a page like this demonstrating the shortcuts for Umamo. + +## Properties Panel +* The document-level **runtime-compatibility target data model** behind Document › Runtime — the enabled export targets (Cubism, Ayagami, …) + each target's options, how it persists on the document, and how it drives CMO3/MOC3 export. Scaffolded as a placeholder section now; its data design is a separate pass (depends on cataloguing each target runtime's capabilities). +* UMA serialization of the latent composite (the format work this unblocks). +* Improvements + * Deformers still have no editable Object-mode transform — needs the deformer → part → mesh cascade (parts already expand to their subtree meshes for G / S / R). + * Do another pass on the keyed parameter/property highlight colors. Why does off key filled color appear as grey over green? + * Transform Position and Size should update the render while scrubbing. + * Aspect locked properties(Size) should update the other control while one is being scrubbed. +* Single/multiple relation pickers. + * Improvements + * Persist list height.(Stored in UMA format, maybe?) + * Deformer pickAt(). + * Context Menus + +## Parameters +* Parameter templates: + * Need a way to apply these without having to do a fresh import. + +## Menus +* Clicking again should close instead of reopen the menu. + +## Tooltips +* Consider swapping to BasicTooltipBox in the future to get rip of the desktop and Android split of TooltipArea. BasicTooltipBox is more recent as of writing this, July 2026, is being actively iterated against. + +## Workspace Tabs +* Improvements + * Visual feedback of the tabs moving out of the way when reordering them. + +## Keymap +* Keymappings will need to become area contextual. For example: P is pin in the UV editor area. Once the Separate operation(Into multiple drawables) exist, if we want to match Blender's P shortcut for that then it has to become contextual per area. + +## Format + +### File +* Automatic Backup + +### UMA (Native File Format) +* Improvements + * Preview thumbnail should take a snapshot of the 2D space and not from the part thumbnailer. The part thumbnail does not respect visbility and so on. + * Format icon helper - Display thumbnail as the icon with the Umamo logo overlaid. Requires an installer. + +See the roadmap: docs/plan/art-sourcing-pipeline.md § Phase G — the source-agnostic container is designed there. +See format planning document: docs/plan/uma-format.md + +## Import +* MOC3 sidecar discovery on Android. MOC3 might be a desktop only feature. + +## Render +* GPU glue: multi-pair seam vertices — latent correctness gap; see Claude Notes § GPU glue: multi-pair seam vertices. + +## Glue +* Glue intensity is keyable but has no Properties home(glue is not selectable). See Claude Notes § Glue intensity has no editable home. + +## UI +* Viewport view styles - Top right, in the header area. +* Viewport loading overlay and mouse busy pointer. +* AreaHeader/Viewport2DHeaderControls + * Font size and icon sizes don't line up resulting in the font being 1px offset.(Lots of manual tweaking is required.) + +* Menu - New Items + * Edit + * Cut/Copy/Paste + +## Theme Colors +* Ability to edit ALL the theme colors (the UmamoColors palette) for a custom look through preferences. For example, in Blender I make my vertex colors as ff00ec(unselected), ff7a00(selected), and 7de400(active selection) since it is easier for me to see. + * The color-blind-assist first pass — vertex/edge/face gizmo colors plus the selection highlight — already exists in Settings > Colors. + +## Refactor +* module/render/src/commonMain/kotlin/org/umamo/render/puppet/PuppetRenderer.kt + +## DRY/Standardization +* Fields like PropertyFieldRow need to take a key use use that to get the correct resource key automatically instead of passing it. + * For Example: properties_field_base_angle - "base_angle" -> Expanded out to `properties_field_base_angle` and `properties_field_base_angle_description`. + * There are plenty of places in the code base that are passing the values around like this at the moment. Difficulty: .* import level maybe? I need to read up on the Kotlin compiler optimization to determine if this will be an issue. + * operatorParameterDescriptionRes also is the start of something of what I am thinking, but hardcoded. + +## Settings +* Keybinding - input.keybinding (Includes keyboard, mouse, and pen buttons.) +* Pen Binding (JPen, Wacom) - input.pen (Includes pen, pressure, and things related to the radial menu.) +* Quick Setup + * Versioned Settings + * Import from Previous +* The settings UI needs a design pass since it is basically just squares and whatever thrown together right now. +* New Settings + * Setting to make Left Click, instead of ALT+Left Click, the default to activate the popup overlap picker. + +## Keybindings +* Audit default keybinding maps for Blender and Cubism styles. + +## Future Feature Wishes +* Pose Reference - A poseable and adjustable 3D mannequin model for overlay reference. +* Really good edge detection for auto-mesh. +* Normal map, emission, metallic, and reflection shaders for texturing. +* Key/mouse/pen input overlay for recording/streaming. +* History playback for proof of work. The history system is there, but that is a lot of track over a long session. So capture a snapshot every time period or number of snapshots. +* A proper bone skeleton system with bendy bones. + +## Build and Distribute +* Eventually get installers, signing, and automatic updates setup. + +## MacOS +* Zoom with the touchpad on my 2014 Macbook Pro is glitchy. It will jump around and even go the wrong direction. +* Need to add back a light native menu so it does not say "MainKt" all the time. + +## Input + +### Pen backend + radial menu (sketch, deferred) + +Sketch: +- Settings: `input.pen.backend` ("auto"/"native"/"jpen"/"disabled"), later `input.pen.pressureCurve` etc. +- A `PenInput` seam (commonMain interface) producing pressure / tilt / barrel buttons, `expect`/`actual`: Android `actual` via `MotionEvent` (`getPressure`, `getAxisValue(AXIS_TILT/ORIENTATION)`) in the viewport pointer pipeline (Android pen is the easier, priority target per the thesis); desktop `actual` via JPen or Wintab / Windows Ink behind the seam (the risky part — no clean Compose-desktop pressure path). Barrel buttons bind to commands through the existing action registry. +- Radial menu: a commonMain Compose overlay whose entries come from the action registry, opened by a pen-bound action / long-press — the keyboardless-tablet entry point that carries tool switching and reaching Preferences (per CLAUDE.md). +- `PenSection`: backend dropdown now, pressure-curve editor later; replaces the stub. +- Why deferred: desktop pressure integration + the radial menu + a per-mode keymap context model is a feature of its own. Plan separately once Phase 3's keymap foundation lands (the radial menu and barrel-button binds reuse it). + +## Command Palette +* Icons for commands - Long tail feature, would need to add a lot of icons. We can reuse the existing icons for current commands such as editor/select modes. + +## Status Bar +* The first iteration to improve the status bar hints was a good success. Eventually: + * Hint icons (Mouse button indicator, etc.) + * Better contextual hints: Swap out anything that is irrelevant when selecting for example and just show selection relevant shortcuts. + +## Pose Palette/Library +* Cubism 5.4 added a "Model state set" which is just a pose library. The data is saved into the CMO3 file. This should be easy to implement and store in the native UMA format. + +## Color Space and Management +Right now the goal is to support sRGB from ingest to output with full correctness. Eventually we want to be able to add linear color space, HDR, and so on. While vtubers typically are 100% sRGB(art, edit, broadcast) some game developers may opt for different color spaces and require that flexibility. I'm tentatively planning this work for Q1 2027. + + +# Claude Notes + +## GPU glue: multi-pair seam vertices (deferred 2026-06-21) + +**What.** The GPU glue weld (`PuppetRenderer` two-pass; `module/render/src/commonMain/.../puppet/`) stores **one +partner per vertex** in its per-vertex glue attribute (partner global index, glue index, weld weight; built +in `buildGlueAttributes`, consumed by `GLUE_VERTEX_SHADER`). If a single mesh vertex participates in **more +than one** glue pair — e.g. a corner vertex shared by two seams — only the last-written pair survives, so the +GPU applies **one** weld where the CPU `applyGluesResolved` applies **both, sequentially**. That would diverge +from the CPU/oracle at such shared verts. + +**Why it's fine right now.** Erica's four glues have **disjoint** seam vertices (no vertex is in two pairs), +so the GPU render is pixel-perfect vs the CPU (maxDiff 3/255, 0 px >8). This is a **latent** gap that only a +model with shared seam verts would expose. + +**Detection.** Add a glue-aware per-vertex check: run the two-pass GPU glue, transform-feedback-capture the +**post-weld** positions, and diff against the CPU `applyCpuDeform` (which includes glue) on a model whose +glue pairs share vertices. (The existing `GpuDeformValidationTest` only validates the pre-glue deform.) + +**Fix options (when/if it bites).** +1. Per-vertex support for *N* partners: widen the glue attribute to a small fixed array (or an indexed side + buffer) and loop the welds in the shader **in the CPU's pair order** so the sequential result matches. +2. Detect shared seam verts at import and fall those specific glue meshes back to CPU glue (the hybrid path), + keeping the rest on the GPU. + +## Deformer keeps no rest geometry once its last axis is collapsed (found 2026-09-04) + +**What.** `withAxisCollapsed` returns null when the last axis goes, and `withParameterDeleted` stores that +null as a warp's or rotation's `geometryGrid` - so the deformer's lattice / pivot, which lived only in that +grid, is gone from the model. The CMO3 export then has nothing to write for it and removes the source's +`keyformGridSource`; the official editor refuses a source without a default keyform (`setKeyformGridSource` +rejects null, `getDefaultKeyForm` throws "no KeyForms" - the same refusal that crashed it on the first +artwork-origin export, fixed for drawables/parts/glue by writing one default cell in +`Cmo3KeyformLowering.buildBundle`). + +**Why it's fine right now.** Nothing in the editor deletes a parameter that keys a deformer's geometry +except the parameter-delete flow, and the structure round-trip gate only reaches the case by choosing a +victim parameter that keys deformer geometry. + +**Fix sketch.** Keep the rest cell: a last-axis collapse should yield an axis-less one-cell grid holding the +form at the kept key (the deformer's rest lattice / pivot), not null - for drawables too, since the export +then writes the same shape the corpus does. Once that holds, `writeGridWeb`'s empty-bundle branch becomes +unreachable and can go. + +## Glue intensity has no editable home (deferred 2026-07-29) + +**What.** `Glue.intensity` is a real keyable channel — `FormChannel.GLUE_INTENSITY`, with a static on +`Glue` and a track in `channelGrids` — and the keyform sheet already renders a row per glue and can move, +insert and delete its keys. What it has nowhere is a **Properties** home: there is no `SelectionTarget.Glue`, +no outliner entry, and no property section, so intensity cannot be typed, scrubbed, or keyed with `I` the +way every other channel now can. `:edit` also has no `withGlueIntensity` / `setGlueIntensity`; the only +writes are whole-object reconstructs inside the keyform and topology ops. + +**Why it's fine right now.** The channel is reachable where it matters most — the sheet — and intensity is +the least-touched of the keyable channels (a weld is usually 1.0 and left alone). Nothing is silently +broken: an unexposed channel simply cannot be edited, rather than being editable and wrong. + +**What giving it a home costs.** Four things, none of them local: +1. A new `SelectionTarget.Glue`, which touches selection, the outliner, the relation-pick system, and every + exhaustive `when` over selection targets. +2. A stable identity story. A glue has **no id** — `KeyformOwner.Glue` addresses it by the `(meshA, meshB)` + pair precisely because a list ordinal is not stable across edits (`KeyableTarget.kt`). +3. `Glue` is a plain `class`, not a `data class`, so it has no `copy()`; every rewrite reconstructs the full + constructor. A `withGlueIntensity` must do the same. +4. An outliner presence raises a design question that has never been answered: where does a glue *sit* in a + tree organised by parts and deformers, when it belongs to neither and welds two meshes that may be far + apart in it? + +**Fix sketch (when/if it bites).** The cheap half is `withGlueIntensity` / `setGlueIntensity` plus a +`GlueChange`, following the standard three-file property-op pattern — that alone would let the sheet's +context menu and `I` write the static. The expensive half is selectability, and is worth deferring until +there is a second reason to want it. \ No newline at end of file diff --git a/app/android/build.gradle.kts b/app/android/build.gradle.kts new file mode 100644 index 0000000..a08227d --- /dev/null +++ b/app/android/build.gradle.kts @@ -0,0 +1,82 @@ +// :android (app/android) — Android entrypoint (Activity + Compose + GLSurfaceView viewport). +// A plain Android application module (not KMP): it consumes the shared KMP libraries. +// :android — Android 起動点(Activity + Compose + GLSurfaceView ビューポート)。 + +plugins { + // AGP 9+ has built-in Kotlin support, so the org.jetbrains.kotlin.android plugin is gone — + // applying it now errors. AGP compiles Kotlin itself; the Compose compiler plugin hooks in. + alias(libs.plugins.androidApplication) + alias(libs.plugins.composeMultiplatform) + alias(libs.plugins.composeCompiler) +} + +// Resolve the application version from ProjectInfo.kt (see gradle/project-version.gradle.kts) so +// versionName never drifts from what the About dialog shows. +apply(from = rootProject.file("gradle/project-version.gradle.kts")) +val umamoVersion = extra["umamoVersion"] as String + +android { + namespace = "org.umamo.editor.android" + compileSdk = libs.versions.android.compileSdk.get().toInt() + + defaultConfig { + // applicationId is the permanent Play identity; it intentionally differs from `namespace` + // so org.umamo stays a clean umbrella for a future viewer app. + applicationId = "org.umamo.editor" + minSdk = libs.versions.android.minSdk.get().toInt() + targetSdk = libs.versions.android.targetSdk.get().toInt() + // versionCode is Play's monotonic release counter — bumped by hand on release; it cannot be + // derived from a semver string. + versionCode = 1 + versionName = umamoVersion + } + + buildTypes { + release { + isMinifyEnabled = false + } + } + + // Keep AGP's Java compilation in lockstep with Kotlin's JDK 21 target (otherwise the + // "inconsistent JVM target" error bites the moment any Java source appears). + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } + + packaging { + resources { + excludes += "/META-INF/LICENSE.md" + excludes += "/META-INF/LICENSE-notice.md" + } + } +} + +kotlin { + jvmToolchain(21) +} + +dependencies { + implementation(project(":ui")) + implementation(project(":runtime")) + // Editing core (EditorSession / Selection model): the Android host creates a per-document session + // the same way the desktop does; declared directly for parity with :runtime / :render. + implementation(project(":edit")) + implementation(project(":render")) + // androidAppStorage + the per-OS config/data dirs the settings live in; also pulls FileKit + // (api-exposed by :storage), whose Android pickers MainActivity initialises with FileKit.init. + implementation(project(":storage")) + // The Settings type returned by LocalSettings: :ui depends on :settings only via implementation, so + // MainActivity needs it on its own classpath to read settings.getString / observe settings.changes. + implementation(project(":settings")) + + // setContent { } lives in androidx.activity.compose. + implementation(libs.androidx.activity.compose) + // Direct Compose Multiplatform coordinates via the version catalog — the old `compose.runtime` + // plugin aliases were deprecated in CMP 1.10/1.11. The artifacts still redirect to + // androidx.compose on this Android target (Gradle metadata), so resolution is unchanged; see the + // catalog note on the `compose-*` entries and the matching :ui commonMain block. + implementation(libs.compose.runtime) + implementation(libs.compose.foundation) + implementation(libs.compose.ui) +} \ No newline at end of file diff --git a/app/android/src/main/AndroidManifest.xml b/app/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..f5b6257 --- /dev/null +++ b/app/android/src/main/AndroidManifest.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/android/src/main/kotlin/org/umamo/editor/android/MainActivity.kt b/app/android/src/main/kotlin/org/umamo/editor/android/MainActivity.kt new file mode 100644 index 0000000..3ec2f51 --- /dev/null +++ b/app/android/src/main/kotlin/org/umamo/editor/android/MainActivity.kt @@ -0,0 +1,118 @@ +package org.umamo.editor.android + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import io.github.vinceglb.filekit.FileKit +import io.github.vinceglb.filekit.dialogs.init +import org.umamo.storage.androidAppStorage +import org.umamo.ui.ProvideSettings +import org.umamo.ui.app.EditorApp +import org.umamo.ui.app.HostOpenRequests +import org.umamo.ui.app.rememberDocumentFileFor +import org.umamo.ui.app.rememberEditorSessionFor +import org.umamo.ui.app.rememberExitGuard +import org.umamo.ui.document.Document +import org.umamo.ui.document.newBlankDocument +import org.umamo.ui.theme.ProvideAppThemeFromSettings +import org.umamo.ui.theme.UmamoTheme + +/** + * Android entrypoint. Mounts the same shared [EditorApp] shell desktop runs - the full File / Edit / + * Workspace / Help menu bar, document open/save through the SAF picker, the per-document editing + * session, area tree, command palette, and the Preferences window - over the Android storage/settings + * foundation. The 2D GL viewport is the one piece still platform-deferred: viewport areas render + * placeholders (viewportServiceFactory = null) until the GLES sibling of the desktop render service + * lands; the platform split stays confined to the viewport, as intended. + */ +class MainActivity : ComponentActivity() { + /** + * Documents another app hands over - a `.uma` tapped in a file manager arrives as a VIEW intent - waiting for + * the shell to open them. Held by the activity so an intent delivered to the running editor (onNewIntent) + * reaches the same shell as the one that launched it. + */ + private val openRequests = HostOpenRequests() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Only a fresh launch reads the launching intent: a recreated activity (a rotation the manifest does not + // absorb, a process restore) would otherwise reopen the file over whatever the rigger has open by then. + if (savedInstanceState == null) { + openFrom(intent) + } + // FileKit owns the activity-result registry its open/save pickers dispatch through, so it must be + // initialised once with the Activity before any file dialog (or a .clip read) runs. + FileKit.init(this) + val storage = androidAppStorage(this) + setContent { + // ProvideSettings loads settings asynchronously and gates the tree until they are ready; Android + // has no zero-window hazard (that is desktop-only), so the async load is safe here. UmamoTheme + // wraps the whole content (matching desktop's Main) so LocalUmamoColors resolves to the active + // scheme for everything created here, including the future GLES viewport host. + ProvideSettings(storage) { + ProvideAppThemeFromSettings { + UmamoTheme { + // The editor always has a document: it starts in a new, empty one. + var document by remember { mutableStateOf(newBlankDocument()) } + val session = rememberEditorSessionFor(document) + val documentFile = rememberDocumentFileFor(document) + val exitGuard = rememberExitGuard() + // Back leaves the app (on Android 8 to 11 it destroys the root activity, edits and all), so + // while the document is dirty it asks through the same guard as File > Exit - and while a + // save is being written it goes through the guard too, which waits for the file to land. + // A clean, idle document keeps the platform's own back behavior. + val dirty = session?.dirty?.collectAsState()?.value == true + BackHandler(enabled = dirty || documentFile?.saving == true) { + exitGuard.request { finish() } + } + EditorApp( + document = document, + session = session, + documentFile = documentFile, + onOpen = { document = it }, + onExit = { finish() }, + exitGuard = exitGuard, + // The GLES puppet render service is the remaining platform work; until it lands the + // shared shell runs fully (menus, document, panels, thumbnails) with placeholder viewports. + viewportServiceFactory = null, + openRequests = openRequests, + ) + } + } + } + } + } + + /** + * A VIEW intent delivered while the editor is already running: the manifest makes the activity singleTask, so + * a second document opens here - through the shell's unsaved-changes check - instead of in a second activity. + * + * @param Intent intent The new intent. + */ + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + openFrom(intent) + } + + /** + * Forwards the document a VIEW intent names to the shell. The uri string is the same form the recent-files + * list stores, so the shell opens it the way it opens a recent file. The grant behind it is usually read-only + * and never persistable: a Save to it can fail into the save alert (Save As works), and the recent entry it + * leaves can fail later as the soft miss a stored uri already is. + * + * @param Intent? intent The intent to read. + */ + private fun openFrom(intent: Intent?) { + if (intent?.action == Intent.ACTION_VIEW) { + intent.data?.let { documentUri -> openRequests.request(documentUri.toString()) } + } + } +} \ No newline at end of file diff --git a/app/android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..cf2b4e9 --- /dev/null +++ b/app/android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/android/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/android/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..faf2905 --- /dev/null +++ b/app/android/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/app/android/src/main/res/mipmap-hdpi/ic_launcher.png b/app/android/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..44bff7c Binary files /dev/null and b/app/android/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/android/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/android/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..0b22e02 Binary files /dev/null and b/app/android/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/android/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/android/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..b8eb9c9 Binary files /dev/null and b/app/android/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/android/src/main/res/mipmap-mdpi/ic_launcher.png b/app/android/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..856265c Binary files /dev/null and b/app/android/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/android/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/android/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2c596c7 Binary files /dev/null and b/app/android/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/android/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/android/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..cdba213 Binary files /dev/null and b/app/android/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/android/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/android/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..2ec43c9 Binary files /dev/null and b/app/android/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/android/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/android/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..0c3b69b Binary files /dev/null and b/app/android/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/android/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/android/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..ca7d5e8 Binary files /dev/null and b/app/android/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/android/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/android/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..acd74ad Binary files /dev/null and b/app/android/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/android/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/android/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..6c5ae13 Binary files /dev/null and b/app/android/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/android/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/android/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..0dcc61d Binary files /dev/null and b/app/android/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..64a7d41 Binary files /dev/null and b/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..08f0f36 Binary files /dev/null and b/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..ba1b10f Binary files /dev/null and b/app/android/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/android/src/main/res/values/ic_launcher_background.xml b/app/android/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..8406673 --- /dev/null +++ b/app/android/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,7 @@ + + + + #FFFFFFFF + diff --git a/app/cli/build.gradle.kts b/app/cli/build.gradle.kts new file mode 100644 index 0000000..b84794c --- /dev/null +++ b/app/cli/build.gradle.kts @@ -0,0 +1,45 @@ +// :cli (app/cli) — the headless diagnostic tool: dump / extract / atlas / convert / diff over cmo3, +// moc3, and source artwork files. +// JVM-only on purpose: it is an operator's tool, not a shipping app target. It deliberately avoids +// :ui (whose document layer drags in Compose via LiveParams) and :edit — everything it needs is the +// :interop conversion surface plus :render's space/texture helpers. +plugins { + alias(libs.plugins.kotlinMultiplatform) +} + +kotlin { + jvmToolchain(21) + jvm() + + sourceSets { + jvmMain { + dependencies { + // :interop api-exposes :format and :runtime, so those come transitively. + implementation(project(":interop")) + // restMeshesToCanvasSpace / canvasToParentSpaceFor and the atlas texture helpers. + implementation(project(":render")) + } + } + } +} + +// A hand-registered JavaExec rather than the application plugin: the compose.desktop application +// block is the repo's only other runnable and is not wanted here. Only file collections are +// captured (never the Project), keeping the task configuration-cache safe; `--args` works through +// JavaExec's built-in @Option. +val cliMainCompilation = kotlin.jvm().compilations.getByName("main") +val repositoryRoot = rootDir + +tasks.register("run") { + group = "application" + description = "Runs the Umamo diagnostic CLI; pass arguments with --args=\"dump model.moc3\"." + mainClass.set("org.umamo.cli.MainKt") + classpath(cliMainCompilation.output.allOutputs, cliMainCompilation.runtimeDependencyFiles) + // Relative file arguments should resolve against the repo root the operator invoked from, not + // this subproject's directory (JavaExec's default). + workingDir = repositoryRoot + // The atlas packer holds every source layer's pixels plus the pages it composes, and a real + // document is hundreds of megabytes of raster before a single page is allocated. The JVM + // default (a quarter of RAM) is not something to leave to the operator's machine. + maxHeapSize = "6g" +} \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/AtlasCommand.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/AtlasCommand.kt new file mode 100644 index 0000000..e5f5b0c --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/AtlasCommand.kt @@ -0,0 +1,353 @@ +package org.umamo.cli + +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.art.isEffectivelyVisible +import org.umamo.format.atlas.AtlasPackItem +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.AtlasPackPlacement +import org.umamo.format.atlas.AtlasPackResult +import org.umamo.format.atlas.atlasPackItems +import org.umamo.format.atlas.packAtlas +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import java.io.File + +/* + * The atlas subcommand: pack a source artwork document's layers into texture atlas pages. + * + * The packer's standalone proof and inspection surface, beside the editor's own Repack Atlas command + * (document.repackAtlas): it writes the pages, reports every placement, and checks each packed tile + * back out of the page it landed on before claiming success. + */ + +/** Canvas pixels past which the preview composite is skipped rather than allocated. */ +private const val PREVIEW_PIXEL_CAP = 128_000_000 + +/** + * Runs `atlas [] [options]`. + * + * Output lands in a NEW subdirectory named after the input, created under the given directory + * (default: the input file's own directory), matching how `extract` keeps its output from mixing + * into a folder that already holds other files. + * + * @param List arguments The subcommand's arguments. + * @return Int The exit code; 1 when a packed tile fails to read back out of its page. + */ +internal fun runAtlas(arguments: List): Int { + val parsed = + parseArguments( + arguments, + knownFlags = setOf("--rotate", "--visible-only", "--no-shrink", "--preview"), + knownOptions = setOf("--page-size", "--gutter", "--extrude"), + ) + if (parsed.positionals.isEmpty() || parsed.positionals.size > 2) { + throw CliUsageException( + "Usage: atlas [] [--page-size=N] [--gutter=N] [--extrude=N] " + + "[--rotate] [--visible-only] [--no-shrink] [--preview]", + ) + } + val loaded = loadInput(parsed.positionals[0]) + if (loaded !is LoadedInput.SourceArtInput) { + throw CliUsageException("Atlas applies to source artwork only (psd, clip, kra, or a flat raster)") + } + + val gutter = parsed.intOption("--gutter", 2) + val options = + AtlasPackOptions( + maxPageSize = parsed.intOption("--page-size", 4096), + gutter = gutter, + extrude = parsed.intOption("--extrude", minOf(2, gutter)), + allowRotation = "--rotate" in parsed.flags, + shrinkPages = "--no-shrink" !in parsed.flags, + ) + + val art = loaded.art + val visibleOnly = "--visible-only" in parsed.flags + val include: (SourceLayer) -> Boolean = { layer -> + layer.kind == SourceLayerKind.Raster && (!visibleOnly || art.isEffectivelyVisible(layer)) + } + val includedLayers = art.layers.filter(include) + val items = art.atlasPackItems(include) + if (items.isEmpty()) { + throw CliUsageException("${loaded.file.name} has no raster layers to pack") + } + val nonRasterCount = art.layers.count { layer -> layer.kind != SourceLayerKind.Raster } + if (nonRasterCount > 0) { + System.err.println("Note: $nonRasterCount non-raster layer(s) carry no pixels and were not packed.") + } + + println("Packing ${items.size} layer(s) of ${loaded.file.name} (${art.widthPx}x${art.heightPx} canvas)") + val result = packAtlas(items, options) + + val outputDirectory = resolveOutputDirectory(loaded.file, parsed.positionals.getOrNull(1)) + outputDirectory.mkdirs() + writePages(result, outputDirectory) + writeReport(result, includedLayers, items, options, loaded.file, outputDirectory) + reportSkips(result) + if ("--preview" in parsed.flags) { + writePreview(art, includedLayers, items, result, outputDirectory) + } + + val mismatches = verifyTiles(items, result) + if (mismatches.isNotEmpty()) { + System.err.println("VERIFY FAILED: ${mismatches.size} tile(s) do not match their source pixels:") + mismatches.take(10).forEach { message -> System.err.println(" $message") } + return 1 + } + println("Verified ${result.placements.size}/${result.placements.size} tiles byte-exact") + return 0 +} + +/** + * Resolves the output subdirectory, named after the input file. + * + * @param File inputFile The source artwork file. + * @param String? parentDirectory The caller's directory argument, when given. + * @return File The directory the pages and report write into. + */ +private fun resolveOutputDirectory(inputFile: File, parentDirectory: String?): File { + val parent = if (parentDirectory != null) File(parentDirectory) else (inputFile.parentFile ?: File(".")) + val directory = File(parent, inputFile.nameWithoutExtension) + if (directory.exists()) { + System.err.println("Note: ${directory.path} already exists; its matching files will be overwritten.") + } + return directory +} + +/** + * Encodes and writes every packed page. + * + * @param AtlasPackResult result The packing outcome. + * @param File outputDirectory The directory to write into. + */ +private fun writePages(result: AtlasPackResult, outputDirectory: File) { + for ((pageIndex, page) in result.pages.withIndex()) { + val target = File(outputDirectory, "page_${pageIndex.toString().padStart(2, '0')}.png") + val bytes = PngCodec.write(page) + target.writeBytes(bytes) + val occupancy = (result.pageOccupancy(pageIndex) * 100f).toInt() + println("Wrote ${target.path} (${page.width}x${page.height}, $occupancy% occupancy, ${bytes.size} bytes)") + } +} + +/** + * Writes the placement report: the options the pack ran with, one line per placement, then the skips. + * + * @param AtlasPackResult result The packing outcome. + * @param List layers The layers that were offered to the packer, in the same order as [items]. + * @param List items The pack items, parallel to [layers]. + * @param AtlasPackOptions options The options the pack ran with. + * @param File inputFile The source artwork file. + * @param File outputDirectory The directory to write into. + */ +private fun writeReport( + result: AtlasPackResult, + layers: List, + items: List, + options: AtlasPackOptions, + inputFile: File, + outputDirectory: File, +) { + val layerNameByKey = items.indices.associate { itemIndex -> items[itemIndex].key to layers[itemIndex].name } + val target = File(outputDirectory, "placements.txt") + val report = StringBuilder() + report.appendLine("#atlas placements for ${inputFile.name}") + report.appendLine( + "#options pageSize=${options.maxPageSize} gutter=${options.gutter} extrude=${options.extrude} " + + "rotate=${options.allowRotation} shrink=${options.shrinkPages}", + ) + for ((pageIndex, page) in result.pages.withIndex()) { + report.appendLine( + "#page $pageIndex ${page.width}x${page.height} ${(result.pageOccupancy(pageIndex) * 100f).toInt()}% occupancy", + ) + } + report.appendLine("#page\tx\ty\twidth\theight\tturns\ttrimX\ttrimY\tkey\tname") + for (placement in result.placements) { + report.appendLine( + listOf( + placement.pageIndex, + placement.pageX, + placement.pageY, + placement.pageWidth, + placement.pageHeight, + placement.quarterTurns, + placement.trimLeft, + placement.trimTop, + placement.key, + layerNameByKey[placement.key].orEmpty(), + ).joinToString("\t"), + ) + } + for (skip in result.skipped) { + report.appendLine("#skipped\t${skip.reason}\t${skip.key}\t${layerNameByKey[skip.key].orEmpty()}") + } + target.writeText(report.toString()) + println("Wrote ${target.path} (${result.placements.size} placements, ${result.skipped.size} skipped)") +} + +/** + * Prints the skip tally to stderr, grouped by reason. + * + * A page that looks right while several layers quietly went missing is this stage's characteristic + * failure, so the skips are reported every run rather than only living in the written report. + * + * @param AtlasPackResult result The packing outcome. + */ +private fun reportSkips(result: AtlasPackResult) { + if (result.skipped.isEmpty()) { + return + } + for ((reason, skips) in result.skipped.groupBy { skip -> skip.reason }) { + System.err.println("Note: ${skips.size} layer(s) not packed - $reason") + } +} + +/** + * Reads every packed tile back out of its page and compares it to the source pixels. + * + * This is the command's reason to exist: the atlas is a repackable indirection over the source art, + * so a page that does not reproduce the art it was built from is worthless however good it looks. + * The page-coordinate mapping ([pagePixelOf]) is written out in this file rather than shared with the + * packer, so a wrong rotation convention cannot agree with itself. + * + * @param List items The tiles that were packed. + * @param AtlasPackResult result The packing outcome. + * @return List One message per mismatching tile, empty when every tile matched. + */ +private fun verifyTiles(items: List, result: AtlasPackResult): List { + val itemsByKey = items.associateBy { item -> item.key } + val mismatches = mutableListOf() + for (placement in result.placements) { + val item = itemsByKey.getValue(placement.key) + val page = result.pages[placement.pageIndex] + var mismatch: String? = null + for (tileY in 0 until placement.trimHeight) { + for (tileX in 0 until placement.trimWidth) { + val (pageX, pageY) = pagePixelOf(placement, tileX, tileY) + val sourceOffset = ((placement.trimTop + tileY) * item.width + placement.trimLeft + tileX) * 4 + val pageOffset = (pageY * page.width + pageX) * 4 + for (channelIndex in 0 until 4) { + if (item.rgba[sourceOffset + channelIndex] != page.rgba[pageOffset + channelIndex]) { + mismatch = "'${placement.key}' tile pixel ($tileX, $tileY) at page ($pageX, $pageY)" + break + } + } + if (mismatch != null) { + break + } + } + if (mismatch != null) { + break + } + } + mismatch?.let { message -> mismatches.add(message) } + } + return mismatches +} + +/** + * The page pixel a trimmed tile's pixel lands on under its placement, independent of the packer's + * own composition so the two can disagree; one copy serves both the byte check and the preview so + * those two cannot. + * + * @param AtlasPackPlacement placement Where the tile sits on its page. + * @param Int tileX The pixel's x within the trim. + * @param Int tileY The pixel's y within the trim. + * @return Pair The page (x, y). + */ +private fun pagePixelOf(placement: AtlasPackPlacement, tileX: Int, tileY: Int): Pair = + if (placement.quarterTurns == 0) { + (placement.pageX + tileX) to (placement.pageY + tileY) + } else { + (placement.pageX + tileY) to (placement.pageY + placement.trimWidth - 1 - tileX) + } + +/** + * Composites the packed layers back onto a canvas-sized image, sampling from the PAGES. + * + * The byte check proves the pages carry the right pixels; this is what a human looks at to see that + * the placements also mean the right thing. Blend modes and layer opacity are ignored - it is a + * source-over stack, not a compositor - so a document leaning on them will not match its own + * application's render, which is expected rather than a packing fault. + * + * @param SourceArt art The source document, for canvas size and layer positions. + * @param List layers The layers that were offered to the packer, parallel to [items]. + * @param List items The pack items, parallel to [layers]. + * @param AtlasPackResult result The packing outcome. + * @param File outputDirectory The directory to write into. + */ +private fun writePreview( + art: SourceArt, + layers: List, + items: List, + result: AtlasPackResult, + outputDirectory: File, +) { + if (art.widthPx.toLong() * art.heightPx.toLong() > PREVIEW_PIXEL_CAP) { + System.err.println("Note: ${art.widthPx}x${art.heightPx} canvas exceeds the preview cap; preview skipped.") + return + } + val placementByKey = result.placements.associateBy { placement -> placement.key } + val canvas = ByteArray(art.widthPx * art.heightPx * 4) + // Source-over from the bottom up: order is top-most first, so the highest order draws first. + for (layerIndex in layers.indices.sortedByDescending { layerIndex -> layers[layerIndex].order }) { + val placement = placementByKey[items[layerIndex].key] ?: continue + drawPlacementOntoCanvas(canvas, art.widthPx, art.heightPx, layers[layerIndex], placement, result) + } + val target = File(outputDirectory, "preview.png") + val bytes = PngCodec.write(RasterImage(art.widthPx, art.heightPx, canvas)) + target.writeBytes(bytes) + println("Wrote ${target.path} (${art.widthPx}x${art.heightPx} recomposite from the packed pages, ${bytes.size} bytes)") +} + +/** + * Draws one placed layer onto the preview canvas, reading its pixels out of the atlas page. + * + * @param ByteArray canvas The canvas buffer, RGBA8888 straight alpha. + * @param Int canvasWidth The canvas width in pixels. + * @param Int canvasHeight The canvas height in pixels. + * @param SourceLayer layer The layer being drawn, for its canvas position. + * @param AtlasPackPlacement placement Where its pixels sit on a page. + * @param AtlasPackResult result The packing outcome holding the pages. + */ +private fun drawPlacementOntoCanvas( + canvas: ByteArray, + canvasWidth: Int, + canvasHeight: Int, + layer: SourceLayer, + placement: AtlasPackPlacement, + result: AtlasPackResult, +) { + val page = result.pages[placement.pageIndex] + for (tileY in 0 until placement.trimHeight) { + val canvasY = layer.bounds.top + placement.trimTop + tileY + if (canvasY < 0 || canvasY >= canvasHeight) { + continue + } + for (tileX in 0 until placement.trimWidth) { + val canvasX = layer.bounds.left + placement.trimLeft + tileX + if (canvasX < 0 || canvasX >= canvasWidth) { + continue + } + val (pageX, pageY) = pagePixelOf(placement, tileX, tileY) + val pageOffset = (pageY * page.width + pageX) * 4 + val canvasOffset = (canvasY * canvasWidth + canvasX) * 4 + val sourceAlpha = (page.rgba[pageOffset + 3].toInt() and 0xFF) / 255f + if (sourceAlpha <= 0f) { + continue + } + val destinationAlpha = (canvas[canvasOffset + 3].toInt() and 0xFF) / 255f + val outAlpha = sourceAlpha + destinationAlpha * (1f - sourceAlpha) + for (channelIndex in 0 until 3) { + val sourceChannel = (page.rgba[pageOffset + channelIndex].toInt() and 0xFF) / 255f + val destinationChannel = (canvas[canvasOffset + channelIndex].toInt() and 0xFF) / 255f + val blended = + (sourceChannel * sourceAlpha + destinationChannel * destinationAlpha * (1f - sourceAlpha)) / outAlpha + canvas[canvasOffset + channelIndex] = (blended * 255f + 0.5f).toInt().coerceIn(0, 255).toByte() + } + canvas[canvasOffset + 3] = (outAlpha * 255f + 0.5f).toInt().coerceIn(0, 255).toByte() + } + } +} \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/CliInput.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/CliInput.kt new file mode 100644 index 0000000..747b108 --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/CliInput.kt @@ -0,0 +1,244 @@ +package org.umamo.cli + +import org.umamo.format.FormatRegistry +import org.umamo.format.art.ArtReader +import org.umamo.format.art.SourceArt +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.format.moc3.json.Model3Json +import org.umamo.format.raster.RasterCodec +import org.umamo.format.raster.rasterToSourceArt +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.PuppetModel +import java.io.File +import java.util.Locale + +/* + * Input routing shared by every subcommand: read a file, detect its format through the same + * FormatRegistry the app uses, and (for moc3) discover the sibling family files through the + * model3.json manifest. + */ + +/** A loaded input file, branched by detected format. */ +internal sealed interface LoadedInput { + /** A CMO3 editor document. */ + class Cmo3Input(val model: Cmo3Model, val bytes: ByteArray) : LoadedInput + + /** A MOC3 runtime document plus whatever family files sat beside it. */ + class Moc3Input(val document: MocDocument, val family: Moc3Family) : LoadedInput + + /** + * Layered or flat source artwork: PSD, CLIP, KRA, or any of the flat raster formats read as a + * single-layer document. It carries no rig - there is no source-art to PuppetModel bridge yet + * (pipeline Phase E) - so only artwork-side commands accept it. + */ + class SourceArtInput(val art: SourceArt, val file: File) : LoadedInput +} + +/** + * The MOC3 family files discovered around a moc: the manifest (when present), the display-info + * sidecar, the texture files the manifest references, and the pass-through sidecar texts. + * + * @property File mocFile The .moc3 file itself. + * @property Model3Json? manifest The parsed model3.json, or null when none was found. + * @property Cdi3Json? displayInfo The parsed cdi3.json, or null when absent. + * @property List textureFiles The manifest's texture files, resolved against its directory. + * @property List sidecars Physics/pose/userdata texts, carried through verbatim. + */ +internal class Moc3Family( + val mocFile: File, + val manifest: Model3Json?, + val displayInfo: Cdi3Json?, + val textureFiles: List, + val sidecars: List, +) + +/** + * Reads and format-detects one input file. A .model3.json path is accepted as a moc3 input, with + * the MOC3 resolved through the manifest's own file reference. + * + * @param String path The input file path. + * @return LoadedInput The loaded, format-branched input. + */ +internal fun loadInput(path: String): LoadedInput { + val inputFile = File(path) + if (!inputFile.isFile) { + throw CliUsageException("No such file: $path") + } + if (inputFile.name.lowercase(Locale.ROOT).endsWith(".model3.json")) { + val manifest = Moc3.readModel3(inputFile.readText()) + val mocFile = File(inputFile.parentFile, manifest.fileReferences.moc) + if (!mocFile.isFile) { + throw CliUsageException("Manifest references a missing MOC3: ${mocFile.path}") + } + return loadMoc3(mocFile, manifestFile = inputFile, manifest = manifest) + } + val bytes = inputFile.readBytes() + return when (val codec = FormatRegistry.detect(bytes, inputFile.name)) { + Cmo3 -> LoadedInput.Cmo3Input(Cmo3.read(bytes), bytes) + Moc3 -> loadMoc3(inputFile, manifestFile = null, manifest = null) + is ArtReader -> LoadedInput.SourceArtInput(codec.read(bytes), inputFile) + // A flat raster becomes a one-layer document, which is what makes `atlas cover.png` mean + // something rather than being rejected for lacking layers. + is RasterCodec -> LoadedInput.SourceArtInput(rasterToSourceArt(codec.read(bytes), inputFile.nameWithoutExtension), inputFile) + else -> throw CliUsageException("Unsupported input format: $path (expected cmo3, moc3, model3.json, or source artwork)") + } +} + +/** + * Loads a moc3 and discovers its family. Without an explicit manifest the sibling + * `.model3.json` is tried first, then any manifest in the directory whose moc reference + * names this file. + * + * @param File mocFile The .moc3 file. + * @param File? manifestFile The manifest file, when the caller already has it. + * @param Model3Json? manifest The parsed manifest, when the caller already has it. + * @return LoadedInput The moc3 input with its family. + */ +private fun loadMoc3(mocFile: File, manifestFile: File?, manifest: Model3Json?): LoadedInput.Moc3Input { + val document = Moc3.read(mocFile.readBytes()) + val resolvedManifestFile = + manifestFile + ?: File(mocFile.parentFile, Moc3Sidecars.basenameFor(mocFile.name) + ".model3.json").takeIf { candidate -> candidate.isFile } + ?: mocFile.parentFile + ?.listFiles { _, name -> name.lowercase(Locale.ROOT).endsWith(".model3.json") } + ?.firstOrNull { candidate -> + runCatching { Moc3.readModel3(candidate.readText()).fileReferences.moc == mocFile.name }.getOrDefault(false) + } + val resolvedManifest = manifest ?: resolvedManifestFile?.let { file -> Moc3.readModel3(file.readText()) } + if (resolvedManifest == null) { + return LoadedInput.Moc3Input(document, Moc3Family(mocFile, null, null, emptyList(), emptyList())) + } + val manifestDirectory = resolvedManifestFile!!.parentFile + val references = resolvedManifest.fileReferences + // Manifest reference first, then the sibling-by-basename fallback the app's document loader + // uses - a model3 without a DisplayInfo entry otherwise converts nameless, and the export then + // writes parameter ids where Cubism expects display names. + val displayInfo = + listOfNotNull(references.displayInfo, "${mocFile.nameWithoutExtension}.cdi3.json") + .distinct() + .firstNotNullOfOrNull { reference -> + File(manifestDirectory, reference) + .takeIf { file -> file.isFile } + ?.let { file -> runCatching { Moc3.readCdi3(file.readText()) }.getOrNull() } + } + val textureFiles = references.textures.map { reference -> File(manifestDirectory, reference) } + val sidecars = + buildList { + fun passThrough(kind: Moc3Sidecars.SidecarKind, reference: String?) { + val file = reference?.let { relative -> File(manifestDirectory, relative) } ?: return + if (file.isFile) { + add(Moc3Sidecars.PassThroughSidecar(kind, file.name, file.readText())) + } + } + passThrough(Moc3Sidecars.SidecarKind.Physics, references.physics) + passThrough(Moc3Sidecars.SidecarKind.Pose, references.pose) + passThrough(Moc3Sidecars.SidecarKind.UserData, references.userData) + } + return LoadedInput.Moc3Input(document, Moc3Family(mocFile, resolvedManifest, displayInfo, textureFiles, sidecars)) +} + +/** + * Imports a loaded input to the runtime PuppetModel - the exact import path the editor uses. + * + * A MOC3-origin puppet gets restMeshesToCanvasSpace (its rest meshes arrive in parent-deformer + * space); a CMO3-origin one authors directly in canvas pixels and must NOT be rebased. + * + * @param LoadedInput loaded The loaded input. + * @return PuppetModel The imported puppet, in canvas space. + */ +internal fun importPuppet(loaded: LoadedInput): PuppetModel = + when (loaded) { + is LoadedInput.Cmo3Input -> Cmo3Import.fromModelSource(loaded.model.root as CModelSource) + is LoadedInput.Moc3Input -> restMeshesToCanvasSpace(Moc3Import.fromMocDocument(loaded.document, loaded.family.displayInfo)) + is LoadedInput.SourceArtInput -> + throw CliUsageException( + "${loaded.file.name} is source artwork, which carries no rig; try `atlas` (a source-art to " + + "PuppetModel bridge is pipeline Phase E and does not exist yet)", + ) + } + +/** + * One command line split into positionals, boolean flags, and valued options. + * + * @property List positionals The non-flag arguments, in order. + * @property Set flags The boolean flags present, with their leading dashes. + * @property Map options The `--key=value` options, keyed with their leading dashes. + */ +internal class CliArguments( + val positionals: List, + val flags: Set, + val options: Map, +) { + /** + * Reads one valued option as an integer. + * + * @param String name The option name, with its leading dashes. + * @param Int defaultValue The value to use when the option is absent. + * @return Int The parsed value. + */ + fun intOption(name: String, defaultValue: Int): Int { + val raw = options[name] ?: return defaultValue + return raw.toIntOrNull() ?: throw CliUsageException("$name expects a whole number, got '$raw'") + } +} + +/** + * Splits a command line, rejecting anything the caller did not declare. + * + * Unknown flags are a usage error rather than being ignored, so a mistyped option cannot silently + * produce output the operator believes was generated some other way. + * + * @param List arguments The subcommand's raw arguments. + * @param Set knownFlags The boolean flags this subcommand accepts, with leading dashes. + * @param Set knownOptions The `--key=value` options this subcommand accepts, with leading dashes. + * @return CliArguments The split command line. + */ +internal fun parseArguments(arguments: List, knownFlags: Set, knownOptions: Set): CliArguments { + val positionals = mutableListOf() + val flags = mutableSetOf() + val options = mutableMapOf() + for (argument in arguments) { + if (!argument.startsWith("--")) { + positionals.add(argument) + continue + } + val separatorIndex = argument.indexOf('=') + if (separatorIndex < 0) { + if (argument !in knownFlags) { + throw CliUsageException("unknown flag '$argument'") + } + flags.add(argument) + continue + } + val name = argument.substring(0, separatorIndex) + if (name !in knownOptions) { + throw CliUsageException("unknown option '$name'") + } + options[name] = argument.substring(separatorIndex + 1) + } + return CliArguments(positionals, flags, options) +} + +/** + * Formats a float like C's printf %.6g (what dump_model.c prints), so dump output stays diffable + * against the relive harness. Java's %g keeps trailing zeros where C strips them, hence the trim. + * + * @param Float value The value to format. + * @return String The %.6g-formatted text with C's trailing-zero trimming. + */ +internal fun formatSixSignificant(value: Float): String { + val raw = String.format(Locale.ROOT, "%.6g", value.toDouble()) + val exponentIndex = raw.indexOfFirst { character -> character == 'e' || character == 'E' } + val mantissa = if (exponentIndex >= 0) raw.substring(0, exponentIndex) else raw + val exponent = if (exponentIndex >= 0) raw.substring(exponentIndex) else "" + val trimmed = if (mantissa.contains('.')) mantissa.trimEnd('0').trimEnd('.') else mantissa + return trimmed + exponent +} \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/ConvertCommand.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/ConvertCommand.kt new file mode 100644 index 0000000..15eb9fb --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/ConvertCommand.kt @@ -0,0 +1,172 @@ +package org.umamo.cli + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.moc3.Moc3 +import org.umamo.format.png.PngCodec +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3.Cmo3Conversion +import org.umamo.interop.cmo3.cmo3AtlasPages +import org.umamo.interop.describeExportNotice +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.render.PuppetTextures +import org.umamo.render.UndecodablePagePolicy +import org.umamo.render.buildPuppetTextures +import org.umamo.render.canvasToParentSpaceFor +import org.umamo.render.encodeAtlasPng +import org.umamo.render.withTexturePagesFrom +import java.io.File +import java.util.Locale +import kotlin.random.Random + +/* + * The convert subcommand: cmo3/moc3 resaves and cross-format conversions, replacing the old + * Cmo3ResaveDumpTest -Dcmo3.resave workflow. + */ + +/** + * Runs `convert `, picking the direction from the input's detected format and the output + * path's extension. + * + * @param List arguments The subcommand's arguments. + * @return Int The exit code. + */ +internal fun runConvert(arguments: List): Int { + if (arguments.size != 2) { + throw CliUsageException("Usage: convert ") + } + val loaded = loadInput(arguments[0]) + val outputFile = File(arguments[1]) + val outputExtension = outputFile.name.substringAfterLast('.', "").lowercase(Locale.ROOT) + outputFile.parentFile?.mkdirs() + when { + loaded is LoadedInput.Cmo3Input && outputExtension == "cmo3" -> { + // An unedited graph re-emits its main.xml byte-identically; only the CAFF wrapper differs. + Cmo3.write(loaded.model, outputFile) + println("Resaved cmo3 -> ${outputFile.path} (${outputFile.length()} bytes)") + } + + loaded is LoadedInput.Moc3Input && outputExtension == "moc3" -> { + outputFile.writeBytes(Moc3.write(loaded.document)) + println("Rebaked moc3 -> ${outputFile.path} (${outputFile.length()} bytes)") + println("Note: a rebake is a fresh synthesis, NOT byte-identical to the source by design") + } + + loaded is LoadedInput.Cmo3Input && outputExtension == "moc3" -> { + convertCmo3ToMoc3Family(loaded, outputFile) + } + + loaded is LoadedInput.Moc3Input && outputExtension == "cmo3" -> { + convertMoc3ToCmo3(loaded, outputFile) + } + + else -> throw CliUsageException("Unsupported conversion: ${arguments[0]} -> ${outputFile.name}") + } + return 0 +} + +/** + * Lowers a CMO3 document to the full MOC3 family (moc3 + model3.json + cdi3.json + atlas textures) + * next to [outputFile]. + * + * The two mandatory pre-steps mirror the app's own export path: the puppet's drawables arrive on + * the -1 texture-page sentinel (CMO3 binds textures through the layered-art web, not a page index), + * so withTexturePagesFrom must land real pages before the lowering can name them. + * + * @param LoadedInput.Cmo3Input loaded The cmo3 input. + * @param File outputFile The target .moc3 path; the family lands beside it. + */ +private fun convertCmo3ToMoc3Family(loaded: LoadedInput.Cmo3Input, outputFile: File) { + val basename = Moc3Sidecars.basenameFor(outputFile.name) + val importedPuppet = importPuppet(loaded) + val modelSource = (loaded.model.root as org.umamo.format.cmo3.model.custom.CModelSource) + val pageSet = cmo3AtlasPages(modelSource) { imageResource -> loaded.model.extractLayerPng(imageResource) } + // Skip matches the editor's CMO3 loader: a page that will not decode drops rather than failing the + // whole conversion, and Skip never returns null, so the fallback is unreachable. + val textures = + buildPuppetTextures( + pageSet.pageBytes, + pageSet.atlasIndexByDrawableId, + pageSet.premultipliedAlpha, + UndecodablePagePolicy.Skip, + ) ?: PuppetTextures(emptyList(), emptyMap(), pageSet.premultipliedAlpha) + val puppet = withTexturePagesFrom(importedPuppet, textures) + val pages = + textures.atlases.mapIndexed { pageIndex, atlas -> + Moc3Sidecars.AtlasPage( + fileName = String.format(Locale.ROOT, "%s.%d/texture_%02d.png", basename, atlas.width, pageIndex), + bytes = encodeAtlasPng(atlas), + ) + } + val bundle = + Moc3Sidecars.bundle( + puppet = puppet, + basename = basename, + pages = pages, + canvasToParentSpace = canvasToParentSpaceFor(puppet), + ) + + // Overwrites without confirmation. + val outputDirectory = outputFile.parentFile ?: File(".") + for (bundleFile in bundle.files) { + val target = File(outputDirectory, bundleFile.name) + target.parentFile?.mkdirs() + target.writeBytes(bundleFile.bytes) + println("Wrote ${target.path} (${bundleFile.bytes.size} bytes)") + } + reportNotices(bundle.report) +} + +/** + * Synthesizes a fresh CMO3 from a MOC3-origin document. The atlas pages come from the manifest's + * texture files; without a manifest the conversion proceeds textureless with a warning. A + * MissingSourceArt notice is always reported - the pages are atlas copies, not the original + * layered source art. + * + * @param LoadedInput.Moc3Input loaded The moc3 input with its discovered family. + * @param File outputFile The target .cmo3 path. + */ +private fun convertMoc3ToCmo3(loaded: LoadedInput.Moc3Input, outputFile: File) { + val puppet = importPuppet(loaded) + val presentTextureFiles = loaded.family.textureFiles.filter { textureFile -> textureFile.isFile } + if (loaded.family.manifest == null) { + System.err.println("Warning: no model3.json manifest found beside ${loaded.family.mocFile.name}; converting textureless") + } else if (presentTextureFiles.size < loaded.family.textureFiles.size) { + System.err.println("Warning: ${loaded.family.textureFiles.size - presentTextureFiles.size} manifest texture(s) missing on disk") + } + val pages = + presentTextureFiles.map { textureFile -> + val pngBytes = textureFile.readBytes() + val decoded = PngCodec.read(pngBytes) + Cmo3Conversion.AtlasPage(pngBytes = pngBytes, width = decoded.width, height = decoded.height) + } + val result = + Cmo3Conversion.freshCmo3( + puppet = puppet, + pages = pages, + pageIndexByDrawableId = loaded.document.artMeshes.associate { artMesh -> artMesh.id to artMesh.textureIndex }, + modelName = outputFile.name.removeSuffix(".cmo3"), + nowMillis = System.currentTimeMillis(), + obfuscateKey = Random.nextInt(), + ) + + // Overwrites without confirmation. + Cmo3.write(result.model, outputFile) + println("Wrote ${outputFile.path} (${outputFile.length()} bytes)") + reportNotices(result.report) +} + +/** + * Prints an export report's notices to stderr - advisory, never fatal. Each line is the same one the + * editor's log carries for that notice, so a report reads alike whichever tool wrote the file. + * + * @param ExportReport report The lowering's report. + */ +private fun reportNotices(report: ExportReport) { + if (report.isEmpty) { + return + } + System.err.println("Export notices (${report.notices.size}):") + for (notice in report.notices) { + System.err.println(" ${describeExportNotice(notice)}") + } +} \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/DiffCommand.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/DiffCommand.kt new file mode 100644 index 0000000..c49768b --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/DiffCommand.kt @@ -0,0 +1,94 @@ +package org.umamo.cli + +import org.umamo.interop.EntityDiff +import org.umamo.interop.GlueDiff +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId + +/* + * The diff subcommand: the semantic per-entity difference between two models, through the same + * diffPuppetModels the CMO3 export reconcile dispatches on. + */ + +/** + * Runs `diff `: imports both files (either format, both normalized to canvas space by the + * import path) and prints the per-category difference. Exit stays 0 either way - a diff is a + * report, not a failure. + * + * @param List arguments The subcommand's arguments. + * @return Int The exit code. + */ +internal fun runDiff(arguments: List): Int { + if (arguments.size != 2) { + throw CliUsageException("Usage: diff ") + } + val baseline = importPuppet(loadInput(arguments[0])) + val edited = importPuppet(loadInput(arguments[1])) + val diff = diffPuppetModels(baseline, edited) + if (diff.isEmpty) { + println("identical") + return 0 + } + printCategory("parameters", diff.parameters) + printCategory("parameterGroups", diff.parameterGroups) + printCategory("parts", diff.parts) + printCategory("deformers", diff.deformers) + printCategory("drawables", diff.drawables) + if (diff.glues.isNotEmpty()) { + println("[glues]") + for (glueDiff in diff.glues) { + val key = "${glueDiff.meshA.raw}~${glueDiff.meshB.raw}#${glueDiff.ordinal}" + when (glueDiff) { + is GlueDiff.Created -> println("+ $key") + is GlueDiff.Deleted -> println("- $key") + is GlueDiff.Changed -> println("~ $key ${glueDiff.fields.sorted()}") + } + } + } + if (diff.document.isNotEmpty()) { + println("[document]") + println("~ ${diff.document.sorted()}") + } + return 0 +} + +/** + * Prints one entity category's diffs: `+ id` created, `- id` deleted, `~ id [FIELDS]` changed. + * + * @param String label The category heading. + * @param List diffs The category's entries (skipped entirely when empty). + */ +private fun > printCategory(label: String, diffs: List>) { + if (diffs.isEmpty()) { + return + } + println("[$label]") + for (entityDiff in diffs) { + when (entityDiff) { + is EntityDiff.Created -> println("+ ${formatEntityId(entityDiff.id)}") + is EntityDiff.Deleted -> println("- ${formatEntityId(entityDiff.id)}") + is EntityDiff.Changed -> println("~ ${formatEntityId(entityDiff.id)} ${entityDiff.fields.sorted()}") + } + } +} + +/** + * The bare id string of a typed entity id - the value-class toString ("PartId(raw=...)") is noise + * in a report meant for humans and diff scripts. + * + * @param Any? id The typed entity id. + * @return String The raw id text. + */ +private fun formatEntityId(id: Any?): String = + when (id) { + is ParameterId -> id.raw + is ParameterGroupId -> id.raw + is PartId -> id.raw + is DeformerId -> id.raw + is DrawableId -> id.raw + else -> id.toString() + } \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/DumpCommand.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/DumpCommand.kt new file mode 100644 index 0000000..c512643 --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/DumpCommand.kt @@ -0,0 +1,249 @@ +package org.umamo.cli + +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.serialize.ModelDocument +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import org.umamo.runtime.model.PuppetModel + +/* + * The dump subcommand: human-readable (and, for MOC3, dump_model.c-diffable) file contents. + */ + +/** + * Runs `dump [--sections] [--xml] [--puppet]`. + * + * @param List arguments The subcommand's arguments. + * @return Int The exit code. + */ +internal fun runDump(arguments: List): Int { + val flags = arguments.filter { argument -> argument.startsWith("--") }.toSet() + val positionals = arguments.filterNot { argument -> argument.startsWith("--") } + val unknownFlags = flags - setOf("--sections", "--xml", "--puppet") + if (unknownFlags.isNotEmpty()) { + throw CliUsageException("unknown dump flag(s): ${unknownFlags.joinToString(", ")}") + } + if (positionals.size != 1) { + throw CliUsageException("usage: dump [--sections] [--xml] [--puppet]") + } + val loaded = loadInput(positionals[0]) + when (loaded) { + is LoadedInput.Moc3Input -> { + if ("--xml" in flags) { + throw CliUsageException("--xml applies to cmo3 input only") + } + if ("--sections" in flags) { + dumpMoc3Sections(loaded) + } else { + dumpMoc3Document(loaded.document) + } + } + + is LoadedInput.Cmo3Input -> { + if ("--sections" in flags) { + throw CliUsageException("--sections applies to moc3 input only") + } + if ("--xml" in flags) { + dumpCmo3Xml(loaded.model) + return 0 + } + dumpCmo3Overview(loaded.model) + } + + is LoadedInput.SourceArtInput -> { + if ("--sections" in flags || "--xml" in flags) { + throw CliUsageException("--sections and --xml do not apply to source artwork") + } + dumpSourceArt(loaded) + } + } + if ("--puppet" in flags) { + dumpPuppetSummary(importPuppet(loaded)) + } + return 0 +} + +/** + * The MOC3 semantic summary, mirroring dump_model.c's static line grammar (`P`/`T`/`D` records) so + * the relive harness's diff scripts can consume it. Runtime-evaluated columns (posed draw/render + * order, evaluated opacities, vertex-position hashes) are deliberately absent - this dumps the + * static rig, not a revived core. + * + * @param MocDocument document The decoded moc. + */ +private fun dumpMoc3Document(document: MocDocument) { + println("# MOC3 version=${document.version.byteValue}") + document.canvas?.let { canvas -> + val size = "${formatSixSignificant(canvas.width)},${formatSixSignificant(canvas.height)}" + val origin = "${formatSixSignificant(canvas.originX)},${formatSixSignificant(canvas.originY)}" + println("# canvas size=$size origin=$origin ppu=${formatSixSignificant(canvas.pixelsPerUnit)}") + } + println( + "# counts parameters=${document.parameters.size} parts=${document.parts.size} " + + "drawables=${document.artMeshes.size} deformers=${document.deformers.size} " + + "glues=${document.glues.size} groups=${document.renderOrderGroups.size} " + + "bindings=${document.bindings.size} blendShapes=${document.blendShapes.size} " + + "offscreens=${document.offscreens.size}", + ) + println("[parameters]") + document.parameters.forEachIndexed { parameterIndex, parameter -> + println( + "P $parameterIndex id=${parameter.id} type=${parameter.type?.number ?: -1} " + + "min=${formatSixSignificant(parameter.minimumValue)} max=${formatSixSignificant(parameter.maximumValue)} " + + "def=${formatSixSignificant(parameter.defaultValue)} repeat=${if (parameter.repeats) 1 else 0}", + ) + } + println("[parts]") + document.parts.forEachIndexed { partIndex, part -> + println("T $partIndex id=${part.id} parent=${part.parentPartIndex}") + } + println("[drawables]") + document.artMeshes.forEachIndexed { meshIndex, artMesh -> + println( + "D $meshIndex id=${artMesh.id} cflag=0x${(artMesh.constantFlags and 0xFF).toString(16).padStart(2, '0')} " + + "tex=${artMesh.textureIndex} part=${artMesh.parentPartIndex} vtx=${artMesh.vertexCount} " + + "idx=${artMesh.triangleIndices.size} masks=${artMesh.maskDrawableIndices.size}", + ) + } +} + +/** + * The MOC3 container tier: version, CountInfo, and per-section presence with element counts. + * + * @param LoadedInput.Moc3Input loaded The moc3 input (re-read at the container tier). + */ +private fun dumpMoc3Sections(loaded: LoadedInput.Moc3Input) { + val container = MocCodec.read(loaded.family.mocFile.readBytes()) + println("# MOC3 version=${container.versionByte} sections=${container.sectionCount} bigEndian=${container.isBigEndian}") + println("# countInfo ${container.countInfo.joinToString(",")}") + var presentCount = 0 + for (section in Section.entries) { + if (!container.sections.isPresent(section)) { + continue + } + presentCount++ + println("S ${section.name} count=${container.sections.elementCount(section)}") + } + println("# sections present=$presentCount modeled=${Section.entries.size}") +} + +/** + * The CMO3 overview: target version, the CAFF entry table, the embedded image resources, and the + * parsed main.xml prologue summary. + * + * @param Cmo3Model model The read model. + */ +private fun dumpCmo3Overview(model: Cmo3Model) { + val archive = model.archive + println("# CMO3 targetVersionNo=${model.targetVersionNo ?: "-"}") + println( + "# caff formatVersion=${archive.formatVersion.joinToString(".")} " + + "archiveVersion=${archive.archiveVersion.joinToString(".")} " + + "obfuscateKey=${archive.obfuscateKey}", + ) + println("[entries]") + archive.entries.forEachIndexed { entryIndex, entry -> + println( + "E $entryIndex path=${entry.path} tag=${entry.tag} size=${entry.content.size} " + + "compression=${entry.compression} obfuscated=${if (entry.obfuscated) 1 else 0}", + ) + } + println("[images]") + model.imageResources().forEachIndexed { imageIndex, resource -> + val pngSize = model.extractLayerPng(resource)?.size ?: 0 + println("I $imageIndex type=${resource.type} width=${resource.width} height=${resource.height} pngBytes=$pngSize") + } + val mainXml = archive.firstByTag(CaffArchive.TAG_MAIN_XML) + if (mainXml != null) { + // sharedElements/mainElements are JDOM-typed and JDOM stays :format-internal; the class-version + // table and import list are the useful prologue summary anyway. + val parsed = ModelDocument.parse(mainXml.content) + println("[xml]") + println("# versions ${parsed.versions.entries.joinToString(" ") { (className, versionNumber) -> "$className=$versionNumber" }}") + println("# imports ${parsed.imports.joinToString(" ")}") + } +} + +/** + * Writes the decompressed main.xml to stdout byte-for-byte, so a shell redirect round-trips it. + * CaffEntry.content is already inflated and deobfuscated by the CAFF read. + * + * @param Cmo3Model model The read model. + */ +private fun dumpCmo3Xml(model: Cmo3Model) { + val mainXml = + model.archive.firstByTag(CaffArchive.TAG_MAIN_XML) + ?: throw IllegalStateException("archive has no main_xml entry") + System.out.write(mainXml.content) + System.out.flush() +} + +/** + * The imported-puppet summary: entity counts and the parameter table - the exact import path the + * convert command lowers from, so a suspect conversion can be inspected at this tier first. + * + * @param PuppetModel puppet The imported puppet. + */ +private fun dumpPuppetSummary(puppet: PuppetModel) { + println("[puppet]") + println( + "# counts parameters=${puppet.parameters.size} parts=${puppet.parts.size} " + + "deformers=${puppet.deformers.size} drawables=${puppet.drawables.size} glues=${puppet.glues.size}", + ) + println( + "# canvas ${formatSixSignificant(puppet.canvasWidth)}x${formatSixSignificant(puppet.canvasHeight)} " + + "origin=${formatSixSignificant(puppet.worldOriginX)},${formatSixSignificant(puppet.worldOriginZ)} " + + "target=${puppet.runtimeTarget.name}", + ) + puppet.parameters.forEachIndexed { parameterIndex, parameter -> + println( + "P $parameterIndex id=${parameter.id.raw} min=${formatSixSignificant(parameter.min)} " + + "max=${formatSixSignificant(parameter.max)} def=${formatSixSignificant(parameter.default)}", + ) + } +} + +/** + * The source-artwork summary: canvas, folder attributes, and one line per layer. + * + * The layer inventory a PSD/CLIP/KRA reader produces has had no way to be seen until now, which is + * the same gap the atlas command closes on the packing side - this is what you read to judge whether + * a pack skipped the layers it should have. The alpha column is the packer's own view: the trimmed + * opaque bounds, or `empty` for a layer with no opaque pixel (which never reaches a page). + * + * @param LoadedInput.SourceArtInput loaded The loaded artwork document. + */ +private fun dumpSourceArt(loaded: LoadedInput.SourceArtInput) { + val art = loaded.art + val rasterLayerCount = art.layers.count { layer -> layer.kind == SourceLayerKind.Raster } + println("[artwork] ${loaded.file.name}") + println("# canvas ${art.widthPx}x${art.heightPx}") + println("# counts layers=${art.layers.size} raster=$rasterLayerCount groups=${art.groups.size}") + art.groups.forEach { group -> + println( + "G path=${group.path} name=${group.name} vis=${if (group.visible) 1 else 0} " + + "op=${formatSixSignificant(group.opacity)} blend=${group.blend} " + + "clip=${if (group.clipped) 1 else 0} through=${if (group.passThrough) 1 else 0}", + ) + } + art.layers.forEachIndexed { layerIndex, layer -> + val trimmed = layer.analyzeAlpha(contourEpsilon = 0f) + val alphaColumn = + if (trimmed == null) { + "empty" + } else { + "${trimmed.opaqueBounds.width}x${trimmed.opaqueBounds.height}" + + "+${trimmed.opaqueBounds.left}+${trimmed.opaqueBounds.top}" + } + println( + "L $layerIndex order=${layer.order} kind=${layer.kind} id=${layer.id.raw} name=${layer.name} " + + "at=${layer.bounds.left},${layer.bounds.top} size=${layer.bounds.width}x${layer.bounds.height} " + + "alpha=$alphaColumn op=${formatSixSignificant(layer.opacity)} blend=${layer.blend} " + + "vis=${if (layer.visible) 1 else 0} clip=${if (layer.clipped) 1 else 0} group=${layer.groupPath}", + ) + } +} \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/ExtractCommand.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/ExtractCommand.kt new file mode 100644 index 0000000..2856c02 --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/ExtractCommand.kt @@ -0,0 +1,69 @@ +package org.umamo.cli + +import java.io.File +import java.util.Locale + +/* + * The extract subcommand: unpack a cmo3's CAFF archive into loose files - the plaintext main.xml + * plus every embedded layer PNG. + */ + +/** + * Runs `extract []`. + * + * The entries land in a NEW subdirectory named after the model, created under the given directory + * (default: the input file's own directory) - `extract Model.cmo3 test/work/` writes into + * `test/work/Model/`. The subdirectory is deliberate accident insurance: extraction never mixes + * its output into a folder that already holds other files. + * + * @param List arguments The subcommand's arguments. + * @return Int The exit code. + */ +internal fun runExtract(arguments: List): Int { + val positionals = arguments.filterNot { argument -> argument.startsWith("--") } + if (arguments.size != positionals.size || positionals.isEmpty() || positionals.size > 2) { + throw CliUsageException("Usage: extract []") + } + val loaded = loadInput(positionals[0]) + if (loaded !is LoadedInput.Cmo3Input) { + throw CliUsageException("Extract applies to cmo3 input only") + } + val inputFile = File(positionals[0]) + val modelName = + inputFile.name.let { fileName -> + if (fileName.lowercase(Locale.ROOT).endsWith(".cmo3")) fileName.dropLast(".cmo3".length) else fileName + } + val parentDirectory = if (positionals.size == 2) File(positionals[1]) else (inputFile.parentFile ?: File(".")) + val extractionDirectory = File(parentDirectory, modelName) + if (extractionDirectory.exists()) { + System.err.println("Note: ${extractionDirectory.path} already exists; its matching files will be overwritten.") + } + extractionDirectory.mkdirs() + + val archive = loaded.model.archive + val writtenNames = HashSet() + archive.entries.forEachIndexed { entryIndex, entry -> + // Entry paths are archive data: guard against traversal and collisions rather than trusting them. + val safeName = entry.path.ifBlank { "entry_$entryIndex" } + val uniqueName = if (writtenNames.add(safeName)) safeName else "entry_${entryIndex}_$safeName" + val target = File(extractionDirectory, uniqueName) + if (!target.canonicalFile.toPath().startsWith(extractionDirectory.canonicalFile.toPath())) { + throw IllegalStateException("Archive entry escapes the extraction directory: ${entry.path}") + } + target.parentFile?.mkdirs() + // CaffEntry.content is already inflated and deobfuscated, so main.xml lands as plaintext. + target.writeBytes(entry.content) + println("Extracted ${target.path} (${entry.content.size} bytes)") + } + if (archive.preview.present) { + val previewTarget = File(extractionDirectory, "preview.png") + if (writtenNames.contains("preview.png")) { + System.err.println("Note: An archive entry already claimed preview.png; the CAFF preview image was skipped.") + } else { + previewTarget.writeBytes(archive.preview.png!!) + println("Extracted ${previewTarget.path} (${archive.preview.png!!.size} bytes, CAFF preview)") + } + } + println("Extracted ${archive.entries.size} entries into ${extractionDirectory.path}") + return 0 +} \ No newline at end of file diff --git a/app/cli/src/jvmMain/kotlin/org/umamo/cli/Main.kt b/app/cli/src/jvmMain/kotlin/org/umamo/cli/Main.kt new file mode 100644 index 0000000..7f6a3aa --- /dev/null +++ b/app/cli/src/jvmMain/kotlin/org/umamo/cli/Main.kt @@ -0,0 +1,113 @@ +package org.umamo.cli + +import kotlin.system.exitProcess + +/* + * The Umamo diagnostic CLI: dump / extract / atlas / convert / diff over cmo3, moc3, and source + * artwork files. + * + * Replaces the diagnostic-tests-in-disguise workflow (Cmo3ResaveDumpTest's -Dcmo3.resave, ad-hoc + * probe printlns) with a proper operator tool. Data goes to stdout, diagnostics to stderr; exit 0 + * on success, 1 on a command failure, 2 on a usage error. + */ + +private const val USAGE = """Umamo diagnostic CLI + +Usage (via Gradle; -q suppresses Gradle's own build output, leaving only this tool's): + ./gradlew -q :cli:run --args="dump [--sections] [--xml] [--puppet]" + ./gradlew -q :cli:run --args="extract []" + ./gradlew -q :cli:run --args="atlas [] [options]" + ./gradlew -q :cli:run --args="convert " + ./gradlew -q :cli:run --args="diff " + +Commands: + dump Print a cmo3/moc3/artwork file's contents. MOC3 defaults to printing + a static rig summary. CMO3 defaults to the archive entry table plus + the parsed main.xml overview. Source artwork(PSD, CLIP, KRA, or a + flat raster) prints its canvas, folders, and per-layer inventory with + each layer's trimmed opaque bounds. + --sections MOC3 container tier: per-section presence and counts. + --xml CMO3 only: the decompressed main.xml, byte-for-byte. + --puppet Either format: import to a PuppetModel and summarize. + extract [] + Unpack a cmo3's archive into loose files: The plaintext main.xml plus + every embedded layer PNG. Files write to a NEW subdirectory named + after the model, created under (Default: The file's own + directory) - `extract Model.cmo3 test/work/` writes test/work/Model/. + atlas [] + Pack a source artwork document(PSD, CLIP, KRA, or a flat raster) into + texture atlas pages. Writes page_NN.png plus placements.txt to a NEW + subdirectory named after the input, then reads every packed tile back + out of its page and fails if any byte differs. Layers with no opaque + pixels, or too large for a page, are reported rather than dropped. + --page-size=N Page side to pack against (Default: 4096). + --gutter=N Transparent spacing around every tile (Default: 2). + --extrude=N Edge pixels replicated into the gutter (Default: 2). + --rotate Allow quarter-turning tiles to pack tighter. + --visible-only Skip layers hidden by their own or a folder's eye. + --no-shrink Keep full --page-size pages instead of cropping. + --preview Also write preview.png: the canvas recomposited + from the packed pages (Source-over; blend modes + and layer opacity ignored). + convert + Direction by input format and output extension: + cmo3 -> cmo3 Resave (An unedited main.xml will reemit byte-identical.) + moc3 -> moc3 Rebake (Fresh synthesis, NOT byte-identical by design.) + cmo3 -> moc3 Full family: moc3 + model3.json + cdi3.json + textures + moc3 -> cmo3 Fresh-graph synthesis (Cubism can open it; the source + art pages are atlas copies, so a MissingSourceArt + notice is always reported.) + A moc3 input may also be given as its .model3.json manifest; sibling + sidecars (model3/cdi3/physics3/pose3/userdata3) are discovered by + the manifest's own file references. + diff Import both files (either format) and print the semantic per-entity + difference. + help This text.""" + +/** + * The CLI entry point: dispatches to a subcommand and converts its outcome to an exit code. + * + * @param Array args The raw command-line arguments (Gradle's --args, split). + */ +fun main(args: Array) { + val exitCode = runCli(args.toList()) + if (exitCode != 0) { + exitProcess(exitCode) + } +} + +/** + * Runs one CLI invocation. Split from main so the dispatch stays testable without exiting the JVM. + * + * @param List arguments The command line: a verb followed by its positionals and flags. + * @return Int The process exit code (0 success, 1 failure, 2 usage error). + */ +internal fun runCli(arguments: List): Int { + if (arguments.isEmpty() || arguments[0] == "help" || arguments[0] == "--help") { + println(USAGE) + return if (arguments.isEmpty()) 2 else 0 + } + return try { + when (arguments[0]) { + "dump" -> runDump(arguments.drop(1)) + "extract" -> runExtract(arguments.drop(1)) + "atlas" -> runAtlas(arguments.drop(1)) + "convert" -> runConvert(arguments.drop(1)) + "diff" -> runDiff(arguments.drop(1)) + else -> { + System.err.println("unknown command '${arguments[0]}'") + System.err.println(USAGE) + 2 + } + } + } catch (usageError: CliUsageException) { + System.err.println(usageError.message) + 2 + } catch (failure: Exception) { + System.err.println("error: ${failure.message ?: failure::class.simpleName}") + 1 + } +} + +/** A malformed invocation - reported as usage (exit 2) rather than a command failure (exit 1). */ +internal class CliUsageException(message: String) : Exception(message) \ No newline at end of file diff --git a/app/desktop/build.gradle.kts b/app/desktop/build.gradle.kts new file mode 100644 index 0000000..45b579e --- /dev/null +++ b/app/desktop/build.gradle.kts @@ -0,0 +1,223 @@ +// :desktop (app/desktop) — desktop entrypoint (Compose Desktop + LWJGL viewport interop). +// :desktop — デスクトップ起動点(Compose Desktop + LWJGL ビューポート連携)。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.composeMultiplatform) + alias(libs.plugins.composeCompiler) +} + +// EN: Resolve which platform's natives this build bundles (default: the host; override with +// -Pumamo.target=-, e.g. windows-x64 to cross-build from WSL2 Linux). The shared script +// also drives :render so both modules agree; it exposes its result via extra properties. See +// gradle/build-target.gradle.kts for the full rationale and the cross-build recipe. +// JA: 同梱するネイティブの対象プラットフォームを解決する(既定はホスト、-Pumamo.target で上書き)。 +apply(from = rootProject.file("gradle/build-target.gradle.kts")) +val buildTarget = extra["umamoBuildTarget"] as String +val lwjglNatives = extra["umamoLwjglNatives"] as String + +// Resolve the application version from ProjectInfo.kt (see gradle/project-version.gradle.kts) so +// the packaged artifacts never drift from what the About dialog shows. +apply(from = rootProject.file("gradle/project-version.gradle.kts")) +val umamoVersion = extra["umamoVersion"] as String +val umamoVersionNumeric = extra["umamoVersionNumeric"] as String + +// The .uma document type every OS registration names. OsAssociationFilesTest holds this script, the Android +// manifest, and the freedesktop files to the codec's own Uma.MIME_TYPE, so the four cannot drift apart. +val umaMimeType = "application/vnd.umamo.uma+zip" +val umaExtension = "uma" +val umaDescription = "Umamo Document" + +kotlin { + jvmToolchain(21) + + jvm() + + sourceSets { + jvmMain { + dependencies { + // EN: Compose Desktop's per-target artifact bundles the matching Skiko native (a + // .so/.dll/.dylib). buildTarget is exactly the artifact's "-" suffix, so + // `desktop-jvm-$buildTarget` selects the right one — on the host this is what + // `compose.desktop.currentOs` resolves to, so the default path is unchanged. Direct + // coordinate (not the `compose.desktop.` accessor) because those accessors are + // deprecated in CMP 1.11 — same migration the version catalog already made for the + // other compose.* artifacts (see libs.versions.toml). + // JA: 対象プラットフォームの Skiko ネイティブを含む Compose Desktop 依存を直接座標で選ぶ。 + implementation("org.jetbrains.compose.desktop:desktop-jvm-$buildTarget:${libs.versions.composeMultiplatform.get()}") + // Compose resources: the desktop menu bar localizes against :ui's EN/JA catalogs via + // stringResource(Res.string.*); :ui exposes it as implementation, so declare it here too. + implementation(libs.compose.components.resources) + implementation(project(":ui")) + implementation(project(":runtime")) + // Editing core: the per-document EditorSession the desktop host creates and the + // Selection / EditorMode model the viewport pick reads (used directly in jvmMain). + implementation(project(":edit")) + implementation(project(":render")) + implementation(project(":settings")) + implementation(project(":storage")) + // Explicit (also transitive via :runtime) — Document loading calls FormatRegistry/Cmo3 directly. + implementation(project(":format")) + + // JNA: a tiny Win32 FFI for desktop window chrome (the DWM title-bar caption tint). + // Already on the runtime classpath via FileKit; declared here so jvmMain compiles + // against com.sun.jna.* directly. No-op off Windows — the call is OS-guarded. + implementation(libs.jna) + + // LWJGL GL for the offscreen viewport renderer; BOM keeps module versions aligned. + implementation(project.dependencies.platform(libs.lwjgl.bom)) + implementation(libs.lwjgl.core) + implementation(libs.lwjgl.opengl) + // GLFW: a hidden-window GL context for the OFFSCREEN viewport renderer. The puppet is + // rendered to an FBO and shown as a lightweight Compose Image (not a heavyweight AWT + // canvas), so Compose menus/overlays/gizmos layer over it correctly on every platform. + implementation(libs.lwjgl.glfw) + runtimeOnly("org.lwjgl:lwjgl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives") + } + } + jvmTest { + dependencies { + implementation(kotlin("test")) + } + } + } +} + +// Compose Desktop's packaging/run DSL. `:desktop:run` launches the editor. +compose.desktop { + application { + mainClass = "org.umamo.editor.desktop.MainKt" + // Everything in this jvmArgs list is baked into the PACKAGED launcher too — the plugin + // hands application.jvmArgs straight to jpackage as --java-options, which end up in + // umamo.cfg. So only put things here that are true for a shipped build. The corpus-preview + // override, a developer affordance pointing at a gitignored absolute host path, is set on + // `:desktop:run` alone at the bottom of this file. + // + // Decoding the 8192² atlas to RGBA is transiently heavy (~0.5 GB); give the preview headroom. + jvmArgs.add("-Xmx16g") + nativeDistributions { + // packageName feeds the uber-jar base name (and any future jpackage installers); + // lowercase matches the project/domain and Linux package conventions. + packageName = "umamo" + // jpackage rejects prerelease suffixes, so installers get the numeric form; the uber jar + // keeps the full ProjectInfo string (below). + packageVersion = umamoVersionNumeric + + // Identity metadata. jpackage stamps vendor/description/copyright into the Windows exe + // version resource and the macOS Info.plist, and copies licenseFile into the app image + // — so even an unsigned build says who made it and under what terms. + vendor = "Umamo Project" + description = "Cross-platform 2D puppet modelling editor with Live2D Cubism .cmo3 interop." + copyright = "Copyright (C) Umamo Project contributors. Licensed under the GPL-3.0." + licenseFile.set(rootProject.file("LICENSE")) + + // The jlink module set for the bundled runtime. Compose's default is + // [java.base, java.desktop, java.logging, jdk.crypto.ec] and modules(...) APPENDS to + // it rather than replacing it, so these are purely additive. Each is load-bearing, + // and each was traced to the jar that needs it with `jdeps --list-deps`: + // java.instrument — kotlinx-coroutines' AgentPremain debug-probe transformer. + // java.sql — SQLDelight's JdbcSqliteDriver / sqlite-jdbc (CLIP ingest). + // java.xml — JDOM's SAX/JAXP path, i.e. all of CMO3 read/write. Already + // implied (java.desktop requires it transitively), but CMO3 is + // the product; it should not ride on someone else's implication. + // jdk.security.auth — dbus-java, under FileKit's XDG-portal open/save dialogs. + // jdk.unsupported — sun.misc.Unsafe, which LWJGL's MemoryBackendUnsafe* needs. + // Deliberately NOT includeAllModules: that adds ~50 MB per platform to paper over a + // class of bug the release workflow already catches by asserting on the MODULES= line + // of jlink's `release` descriptor. Re-run `:desktop:suggestRuntimeModules` after any + // dependency change and add whatever it names — but note it under-reports, since it + // misses reflective and service-loaded edges (it does not name java.xml). + modules("java.instrument", "java.sql", "java.xml", "jdk.security.auth", "jdk.unsupported") + + // App icon per OS. jpackage demands a different container per platform and reads only + // its own host's file, so all three are committed and each is consumed when packaging on + // that OS. These feed createDistributable / the native installers (not the uber jar, + // which carries no icon). Regenerate from the mascot with docs/design/appicon/generate.sh. + // + // The .uma document type (docs/format/UMA.md § 2), declared per OS because that is where the plugin + // puts it. What it does depends on what is being built: + // * macOS: the plugin writes CFBundleDocumentTypes into the app image's own Info.plist, so an + // unpacked Umamo.app is already the handler for .uma - no installer needed. + // * Windows and Linux: the plugin hands it to jpackage as --file-associations, which jpackage + // accepts for INSTALLERS only. It is inert for createDistributable, the only thing a release + // ships today, and takes effect the day an msi / deb is built. Until then Linux registers the + // type per user from the two files under resources/linux (see appResourcesRootDir below). + // The document reuses the application icon until it has one of its own. + windows { + iconFile.set(project.file("icons/umamo.ico")) + fileAssociation(umaMimeType, umaExtension, umaDescription, project.file("icons/umamo.ico")) + } + macOS { + iconFile.set(project.file("icons/umamo.icns")) + fileAssociation(umaMimeType, umaExtension, umaDescription, project.file("icons/umamo.icns")) + // CFBundleIdentifier. Matches :android's applicationId so one reverse-DNS identity + // covers the project on both platforms. Not required for an unsigned app image (the + // plugin only validates it when signing), but jpackage would otherwise derive one + // from the main-class package — and macOS keys preferences and TCC permission grants + // on this string, so changing it later orphans every user's saved state. + bundleID = "org.umamo.editor" + } + linux { + iconFile.set(project.file("icons/umamo.png")) + fileAssociation(umaMimeType, umaExtension, umaDescription, project.file("icons/umamo.png")) + } + + // Files copied into the app image beside the jars (lib/app/resources on Linux). resources/linux + // holds the freedesktop shared-mime-info entry and the desktop entry a rigger installs per user to + // make the file manager open .uma with an unpacked Umamo. + appResourcesRootDir.set(project.layout.projectDirectory.dir("resources")) + } + } +} + +// OsAssociationFilesTest reads the OS registration files straight from disk - this script, the Android manifest, +// and the two freedesktop files - and holds them to the codec's Uma.MIME_TYPE. None of them is on the test +// classpath, so Gradle does not know the test depends on them: left undeclared, an edit to any one leaves +// jvmTest UP-TO-DATE and the check silently never runs against the change it exists to catch. +val osAssociationFiles = + files( + "resources/linux/umamo-uma.xml", + "resources/linux/umamo.desktop", + "build.gradle.kts", + rootProject.file("app/android/src/main/AndroidManifest.xml"), + ) +tasks.withType().configureEach { + inputs.files(osAssociationFiles).withPropertyName("osAssociationFiles").withPathSensitivity(PathSensitivity.RELATIVE) +} + +// `umamo.testCmo3` opens the corpus CMO3 (gitignored; the puppet preview) on launch. It is a +// DEVELOPER affordance carrying an absolute host path, so it must never reach a packaged +// artifact where that path does not exist — hence the run task rather than +// application.jvmArgs, which the plugin forwards to jpackage as --java-options. +// +// Two deliberate choices: +// * withType/matching/configureEach, not tasks.named("run"): the Compose plugin registers its +// tasks inside its own afterEvaluate, so `run` does not exist while this script is being +// evaluated and named() would throw. Same lazy idiom as the uber-jar override below. +// * systemProperty(), not jvmArgs(): the plugin's own configuration action calls +// JavaExec.setJvmArgs() — a REPLACE, not an append. Gradle happens to run that action before +// this one so an appended jvmArg would survive today, but systemProperties is a separate +// collection setJvmArgs never touches, so this holds regardless of action ordering. +// The path is resolved to a val first so the lambda captures a String, not the Project +// (configuration cache). +val runPreviewCmo3Path = rootProject.file("test/corpus/cmo3/EricaTamamo.cmo3").absolutePath +tasks.withType().matching { execTask -> execTask.name == "run" } + .configureEach { + systemProperty("umamo.testCmo3", runPreviewCmo3Path) + } + +// The Compose plugin stamps the uber jar with the HOST os token (its own currentTarget +// detection), which lies when -Pumamo.target cross-resolves the bundled natives — the jar +// CONTENTS already honor buildTarget (Skiko artifact and LWJGL natives above). The plugin +// assigns the name PARTS (appendix/version) directly in its afterEvaluate, after any +// configureEach action, so part-level overrides lose; an explicit archiveFileName replaces the +// derived-from-parts convention outright and wins regardless of assignment order. +// +// Target before version — umamo---.. Keep that order: it is what the +// release assets are named and what downstream tooling matches on. +tasks.withType().matching { jarTask -> jarTask.name == "packageUberJarForCurrentOS" } + .configureEach { + archiveFileName.set("umamo-$buildTarget-$umamoVersion.jar") + } \ No newline at end of file diff --git a/app/desktop/icons/umamo.icns b/app/desktop/icons/umamo.icns new file mode 100644 index 0000000..c46d4ef Binary files /dev/null and b/app/desktop/icons/umamo.icns differ diff --git a/app/desktop/icons/umamo.ico b/app/desktop/icons/umamo.ico new file mode 100644 index 0000000..132cd3f Binary files /dev/null and b/app/desktop/icons/umamo.ico differ diff --git a/app/desktop/icons/umamo.png b/app/desktop/icons/umamo.png new file mode 100644 index 0000000..88acee3 Binary files /dev/null and b/app/desktop/icons/umamo.png differ diff --git a/app/desktop/resources/linux/umamo-uma.xml b/app/desktop/resources/linux/umamo-uma.xml new file mode 100644 index 0000000..d01ae2e --- /dev/null +++ b/app/desktop/resources/linux/umamo-uma.xml @@ -0,0 +1,29 @@ + + + + + Umamo Document + Umamo ドキュメント + + + + + + + + + + + + \ No newline at end of file diff --git a/app/desktop/resources/linux/umamo.desktop b/app/desktop/resources/linux/umamo.desktop new file mode 100644 index 0000000..22f173a --- /dev/null +++ b/app/desktop/resources/linux/umamo.desktop @@ -0,0 +1,16 @@ +[Desktop Entry] +Type=Application +Version=1.0 +Name=Umamo +GenericName=2D Puppet Modelling Editor +GenericName[ja]=2Dパペット モデリングエディター +Comment=Model 2D puppets in the Live2D Ecosystem +Comment[ja]=Live2Dエコシステムにおける2Dパペットのモデリング +# The launcher is named by PATH: an unpacked archive has no fixed location. Put bin/umamo on the PATH, or +# replace this with its absolute path, then: xdg-desktop-menu install --novendor umamo.desktop +Exec=umamo %f +TryExec=umamo +Icon=umamo +Terminal=false +Categories=Graphics;2DGraphics; +MimeType=application/vnd.umamo.uma+zip; \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/Main.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/Main.kt new file mode 100644 index 0000000..fd1a114 --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/Main.kt @@ -0,0 +1,274 @@ +package org.umamo.editor.desktop + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.window.Window +import androidx.compose.ui.window.application +import io.github.vinceglb.filekit.FileKit +import kotlinx.coroutines.runBlocking +import org.jetbrains.compose.resources.painterResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.editor.desktop.viewport.OffscreenPuppetService +import org.umamo.format.FileRole +import org.umamo.format.FormatRegistry +import org.umamo.runtime.model.ParameterId +import org.umamo.storage.UmamoLog +import org.umamo.storage.desktopAppStorage +import org.umamo.storage.platformFileFromSavedPath +import org.umamo.ui.LocalSettings +import org.umamo.ui.app.EditorApp +import org.umamo.ui.app.HostOpenRequests +import org.umamo.ui.app.rememberDocumentFileFor +import org.umamo.ui.app.rememberEditorSessionFor +import org.umamo.ui.app.rememberExitGuard +import org.umamo.ui.document.Document +import org.umamo.ui.document.DocumentLoad +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.addRecentFile +import org.umamo.ui.document.fileDisplayName +import org.umamo.ui.document.loadDocument +import org.umamo.ui.document.newBlankDocument +import org.umamo.ui.l10n.FALLBACK_LOCALE_TAG +import org.umamo.ui.l10n.LOCALE_SETTINGS_KEY +import org.umamo.ui.l10n.applyAppLocale +import org.umamo.ui.loadAppSettings +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.app_icon +import org.umamo.ui.resources.app_name +import org.umamo.ui.resources.title_read_only +import org.umamo.ui.resources.title_untitled_document +import org.umamo.ui.theme.ProvideAppThemeFromSettings +import org.umamo.ui.theme.UmamoTheme +import org.umamo.ui.viewport.LiveParams +import java.awt.Desktop +import java.util.concurrent.atomic.AtomicReference + +/** + * Applies the `UMAMO_DUMP_PARAMS` environment override (e.g. `ParamAngleX=30,ParamAngleY=-10`) to the + * given live params, so a deformed pose can be dumped headless. A desktop dev affordance - the shared + * initialLiveParams stays environment-free. + * + * @param LiveParams liveParams The initial document's parameter hand-off to rewrite. + */ +private fun applyDumpParamOverrides(liveParams: LiveParams) { + val spec = System.getenv("UMAMO_DUMP_PARAMS") ?: return + val values = liveParams.values.toMutableMap() + spec.split(",").forEach { pair -> + val parts = pair.split("=") + val value = parts.getOrNull(1)?.trim()?.toFloatOrNull() + if (parts.size == 2 && value != null) { + values[ParameterId(parts[0].trim())] = value + } + } + liveParams.values = values.toMap() +} + +/** + * Loads the initial document from a `.cmo3`/`.moc3` path and applies the dump-param overrides. + * + * A function rather than inline code in [main] on purpose: main's frame lives for the whole run + * (application {} blocks), and an interpreted frame keeps every local reachable - a document held + * in one would stay pinned, retained CMO3 graph and decoded atlas included, long after another + * file replaces it. Loading in a popped frame leaves the holder in [main] as the only reference. + * + * @param String? initialPath The argv / -Dumamo.testCmo3 path, or null for none. + * @return Document? The loaded document, or null when there is no path or the load fails. + */ +private fun loadInitialDocument(initialPath: String?): Document? { + val path = initialPath ?: return null + // A failed initial load falls back to an empty shell (the failure is in the log); the in-app + // alert only covers interactive opens, since the shell is not up yet to show it here. + val document = (runBlocking { loadDocument(platformFileFromSavedPath(path)) } as? DocumentLoad.Loaded)?.document + // The dump-params override applies only to the initially-opened document - it exists for the + // headless first-frame dump, which always opens via argv / -Dumamo.testCmo3. PuppetDocument + // covers both CMO3 and MOC3 documents, so a .moc3 argv dump poses correctly too. + (document as? PuppetDocument)?.let { applyDumpParamOverrides(it.liveParams) } + return document +} + +/** + * The window title: the app name, the open document's name, the unsaved marker, and the read-only marker. + * + * The name follows the `.uma` the document saves to once it has one, so a `Erica.cmo3` saved as `Erica.uma` + * reads as the latter. A document with no file is named here rather than by [Document.displayName], which + * is the plain-text name the log and an export's suggested file name need; the title is chrome, so it + * localizes. A read-only document says so, since Save is greyed for as long as it is open. + * + * @param Document? document The open document. + * @param String? savedPath The `.uma` the document saves to, or null before its first save. + * @param Boolean readOnly Whether the document opened read-only. + * @param Boolean dirty Whether the session has unsaved edits. + * @return String The title. + */ +@Composable +private fun windowTitleFor(document: Document?, savedPath: String?, readOnly: Boolean, dirty: Boolean): String { + val untitled = stringResource(Res.string.title_untitled_document) + val readOnlyMarker = stringResource(Res.string.title_read_only) + val name = savedPath?.let(::fileDisplayName) ?: document?.let { open -> if (open.path == null) untitled else open.displayName } + val markers = (if (dirty) " *" else "") + (if (readOnly) " $readOnlyMarker" else "") + return stringResource(Res.string.app_name) + (name?.let { " - $it$markers" }.orEmpty()) +} + +/** + * Whether [path] names a document the editor opens by itself - its own `.uma`, or a `.cmo3` / `.moc3` it imports. + * One test for the command line and the macOS open-file event, so a file the OS hands over is accepted the same + * way however it arrives. The extension only says the path is worth reading; the loader identifies the content. + * + * Artwork is deliberately not a document path: it is ADDED to whatever document is open, so a `.psd` argument + * would have nothing to be added to at this point in the launch. + * + * @param String path A path from the command line or the operating system. + * @return Boolean True when the path has a document extension. + */ +internal fun isOpenableDocumentPath(path: String): Boolean = FormatRegistry.kindForFileName(path)?.role == FileRole.Document + +/** + * Desktop entrypoint. Opens a single editor window over the storage/settings foundation: window state + * (size/position) and the recent-files list restore from `:settings`, and File → Open/Save-As use the + * native `:storage` dialogs. An initial document may come from a `.uma`, `.cmo3`, or `.moc3` argument or + * `-Dumamo.testCmo3`; otherwise the window opens into a new, empty document. + * `UMAMO_DUMP_PNG` still dumps the first frame headlessly (the WSL verification path). + * + * Settings load synchronously here (the bundled default is a Compose resource, read via `runBlocking`) + * so the window state is ready before the window opens and the window is unconditional - `application {}` + * exits if it ever has zero windows, which an async settings gate would briefly cause. + * + * @param Array args Optional: a `.uma`, `.cmo3`, or `.moc3` path. + */ +fun main(args: Array) { + // FileKit's native dialogs need a one-time init; `appId` names the per-OS data/cache dirs it uses. + FileKit.init(appId = "umamo") + // Pick the first document argument; loadDocument then does the real magic-byte detection once the file + // is actually read (a .moc3 routes to the sidecar-discovering loader). This is how Windows and Linux hand + // over a double-clicked file. + val initialPath = args.firstOrNull(::isOpenableDocumentPath) ?: System.getProperty("umamo.testCmo3") + // macOS hands a double-clicked file over as an open-file event instead, at launch and for as long as the + // app runs. Installed before the window exists: a cold launch's event can arrive before the first + // composition, and the requests wait in their buffer until the shell collects them. + val openRequests = HostOpenRequests() + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.APP_OPEN_FILE)) { + Desktop.getDesktop().setOpenFileHandler { event -> + event.files.map { file -> file.absolutePath }.firstOrNull(::isOpenableDocumentPath)?.let(openRequests::request) + } + } + // Synchronous load, like the settings below: the window opens with the document already in hand. + // The document reaches the first composition through a one-shot holder rather than a plain local: + // the application closure lives for the whole run, so a direct capture would keep the first + // document reachable after the user opens something else. remember empties the holder on first + // composition; only the path string stays behind for the recent-files record. + // A failed or absent argv load still opens a document - the new, empty one the editor starts in. + val initialDocumentHolder = AtomicReference(loadInitialDocument(initialPath) ?: newBlankDocument()) + val initialDocumentPath = initialDocumentHolder.get()?.path + val storage = desktopAppStorage("umamo") + // A first run also seeds the system's language here, so the window - and the Quick Setup modal it opens + // with - is already in that language. + val settings = runBlocking { loadAppSettings(storage) } + // Apply the UI language before the window opens so the menu bar (which lives outside the shell's + // own locale scope) and every other stringResource resolve to the configured locale from the start. + applyAppLocale(settings.getString(LOCALE_SETTINGS_KEY) ?: FALLBACK_LOCALE_TAG) + UmamoLog.info("config=${storage.configDirectory}") + + application { + var document by remember { mutableStateOf(initialDocumentHolder.getAndSet(null)) } + // The title's unsaved marker, mirrored from the session's dirty flag by the window content below, + // which is where the session lives. + var dirty by remember { mutableStateOf(false) } + // The title's file name and read-only marker, mirrored the same way from the document's save target, + // which is also derived inside the window content. + var savedPath by remember { mutableStateOf(null) } + var readOnly by remember { mutableStateOf(false) } + val windowState = remember { settings.savedWindowState() } + // A file opened from the command line is a real "open" - record it in recent files too. + LaunchedEffect(Unit) { initialDocumentPath?.let { settings.addRecentFile(it) } } + + fun closeApp() { + settings.saveWindowState(windowState) + exitApplication() + } + // Every way out passes through the shell's unsaved-changes guard: the window's close button here, File > + // Exit inside the shell, and the macOS Quit below. + val exitGuard = rememberExitGuard() + // macOS routes Cmd+Q and the Dock's Quit through the application's quit handler, not the window's + // close request. Cancelling the OS's quit and asking the guard keeps one path; the handler is + // unsupported, and nothing is installed, on Windows and Linux. + DisposableEffect(exitGuard) { + val quitHandlerSupported = Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.APP_QUIT_HANDLER) + if (quitHandlerSupported) { + Desktop.getDesktop().setQuitHandler { _, response -> + response.cancelQuit() + exitGuard.request { closeApp() } + } + } + onDispose { + if (quitHandlerSupported) { + Desktop.getDesktop().setQuitHandler(null) + } + } + } + Window( + onCloseRequest = { exitGuard.request { closeApp() } }, + state = windowState, + // Window + taskbar/dock icon. painterResource decodes the bundled app_icon PNG (the same + // mascot the packaged installer icons derive from); regenerate via docs/design/appicon/generate.sh. + icon = painterResource(Res.drawable.app_icon), + // A document that has never been saved has no file name to show, so the title localizes its own + // name for it rather than showing the plain-text one the log and export names use. + title = windowTitleFor(document, savedPath, readOnly, dirty), + ) { + // The session is derived HERE, in the composition that reads the document, and not in the + // application scope above. Window content is its own composition: it reads the document + // state directly, but sees a value from the outer scope only through the content lambda it + // was last handed. A session derived outside reaches EditorApp one frame late, so a newly + // opened document composes once with the previous document's session - and the export + // command, the File menu, and the page resolver registered in that frame keep the stale + // pair. Deriving both in one place keeps them consistent in every frame. + val session = rememberEditorSessionFor(document) + val documentFile = rememberDocumentFileFor(document) + LaunchedEffect(documentFile) { + readOnly = documentFile?.readOnly == true + snapshotFlow { documentFile?.umaPath }.collect { path -> savedPath = path } + } + LaunchedEffect(session) { + val activeSession = session + if (activeSession == null) { + dirty = false + } else { + activeSession.dirty.collect { dirty = it } + } + } + CompositionLocalProvider(LocalSettings provides settings) { + ProvideAppThemeFromSettings { + // Run the whole window content inside UmamoTheme so LocalUmamoColors resolves to the active + // scheme for everything created here - the Windows title-bar tint AND the GL viewport host, + // which reads the themed grid-backdrop colors at creation (it lives outside the shell's + // own UmamoTheme). The shell re-applies the same theme to its subtree, an idempotent, + // cheap re-provide. Without this wrap LocalUmamoColors falls back to its static dark default, + // so the viewport grid never tracked the theme. + UmamoTheme { + WindowsTitleBarTint(window) + WindowResizeHeal(window) + EditorApp( + document = document, + session = session, + documentFile = documentFile, + onOpen = { document = it }, + onExit = { closeApp() }, + exitGuard = exitGuard, + viewportServiceFactory = { puppet, textures, liveParams -> + OffscreenPuppetService(puppet, textures, liveParams).also { it.start() } + }, + openRequests = openRequests, + ) + } + } + } + } + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowChrome.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowChrome.kt new file mode 100644 index 0000000..6485a9e --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowChrome.kt @@ -0,0 +1,110 @@ +package org.umamo.editor.desktop + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import com.sun.jna.Library +import com.sun.jna.Native +import com.sun.jna.Pointer +import com.sun.jna.ptr.IntByReference +import org.umamo.ui.theme.LocalUmamoColors +import java.awt.Window + +/* + * Desktop window-chrome integration: tint the host-OS title bar to match the editor's own palette so the + * caption does not sit as a bright system-colored strip above a dark app. Only Windows 11's Desktop Window + * Manager exposes this (DWMWA_CAPTION_COLOR); every other platform is a no-op. The caption color is read + * from [LocalUmamoColors] so it tracks the active light/dark theme. + */ + +/** + * The DWM window attribute that sets the title-bar (caption) fill color. + * + * Win32: DWMWA_CAPTION_COLOR (dwmapi.h, value 35). Honored on Windows 11 build 22000 and later; older + * systems return a failure HRESULT, which we ignore so the call is harmless everywhere. + */ +private const val DWMWA_CAPTION_COLOR = 35 + +/** + * Minimal JNA binding to dwmapi.dll - only the single entry point we need. Loaded lazily and only on + * Windows (see [setWindowsCaptionColor]); the class is never touched on other platforms, so dwmapi.dll is + * never resolved there. + */ +private interface Dwmapi : Library { + /** + * Win32: DwmSetWindowAttribute. Sets a Desktop Window Manager attribute on a window. + * + * pvAttribute is passed by reference; for DWMWA_CAPTION_COLOR it points at a single COLORREF (DWORD), + * so [value] is an int-by-reference and [valueSize] is 4. + * + * @param Pointer windowHandle The target window's HWND. + * @param Int attribute The DWMWA_* attribute identifier. + * @param IntByReference value Pointer to the attribute value (a COLORREF here). + * @param Int valueSize Size of the value in bytes. + * @return Int The HRESULT; 0 (S_OK) on success. + * @note PascalCase is mandatory: JNA's interface mapper binds this method to the dwmapi.dll export of + * the same name, so it must match the Win32 symbol verbatim - hence the naming-rule suppression. + */ + @Suppress("ktlint:standard:function-naming") + fun DwmSetWindowAttribute(windowHandle: Pointer, attribute: Int, value: IntByReference, valueSize: Int): Int +} + +/** The dwmapi.dll binding, resolved on first use. Only ever forced on Windows. */ +private val dwmapi: Dwmapi by lazy { Native.load("dwmapi", Dwmapi::class.java) } + +/** + * Converts a Compose [Color] to a Win32 COLORREF. + * + * Win32 COLORREF packs the channels as 0x00BBGGRR (blue high, red low, top byte zero) - the reverse of + * ARGB's byte order - so the red and blue channels are swapped relative to [toArgb]. + * + * @return Int The COLORREF for this color. + */ +private fun Color.toColorRef(): Int { + val argb = toArgb() + val red = (argb shr 16) and 0xFF + val green = (argb shr 8) and 0xFF + val blue = argb and 0xFF + return (blue shl 16) or (green shl 8) or red +} + +/** + * Sets the Windows title-bar caption color to [color] via the Desktop Window Manager. A no-op on any + * non-Windows OS, before the window has a native peer (no HWND yet), or on a Windows build that predates + * DWMWA_CAPTION_COLOR - in the last case DWM returns a failure HRESULT, which is deliberately ignored so + * the call degrades to "system default caption" rather than throwing. + * + * @param Window window The window whose caption to tint. + * @param Color color The desired caption fill color. + */ +private fun setWindowsCaptionColor(window: Window, color: Color) { + // Gate on the OS before touching the JNA binding, so dwmapi.dll is only ever loaded on Windows. + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) { + return + } + if (!window.isDisplayable) { + return + } + val windowHandle = Native.getWindowPointer(window) ?: return + // HRESULT is ignored: a non-zero result (e.g. Windows 10, which lacks this attribute) just means the + // caption keeps its system color. + dwmapi.DwmSetWindowAttribute(windowHandle, DWMWA_CAPTION_COLOR, IntByReference(color.toColorRef()), Int.SIZE_BYTES) +} + +/** + * Tints [window]'s host-OS title bar to the theme's window-background color (Windows 11 only; a no-op + * elsewhere). Reads [LocalUmamoColors], so place it under the app theme; it re-applies whenever the + * resolved background changes (a light/dark theme switch), keeping the caption in step with the UI. + * + * This composable emits no UI - it is purely a window-chrome side effect. + * + * @param Window window The host window whose caption to tint. + */ +@Composable +fun WindowsTitleBarTint(window: Window) { + val captionColor = LocalUmamoColors.current.windowBackground + LaunchedEffect(window, captionColor) { + setWindowsCaptionColor(window, captionColor) + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowResizeHeal.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowResizeHeal.kt new file mode 100644 index 0000000..8e604fb --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowResizeHeal.kt @@ -0,0 +1,62 @@ +package org.umamo.editor.desktop + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import java.awt.event.ComponentEvent +import javax.swing.JFrame +import javax.swing.Timer + +/* + * On Windows, canceling an interactive resize with Escape restores the original window rect without + * a resize event: AWT silently syncs the frame's cached bounds (~750 ms later) but dispatches no + * componentResized and runs no layout. Compose derives its scene size, its layout, and + * WindowState.size from that missing event, so the content stays frozen at the dragged size inside + * the restored native window. This watchdog detects the desync and replays the pipeline the lost + * event would have driven. + */ + +/** How often the heal watchdog compares the frame's bounds against its laid-out root pane. */ +private const val HEAL_CHECK_INTERVAL_MILLIS = 250 + +/** + * Heals the window when the OS changes its bounds behind AWT's event stream (Escape-canceled + * resize). After every healthy resize the root pane is laid out to exactly the frame's bounds + * minus its insets, so a persistent mismatch is proof of a lost resize notification. On a + * mismatch this re-validates the component tree, which resizes the ComposeWindowPanel and with it + * the Compose scene, then dispatches a synthetic COMPONENT_RESIZED so Compose's own window + * listener refreshes WindowState.size. While bounds and layout agree - the permanent state on + * every platform outside this Windows quirk - each tick is two int comparisons on the EDT, so the + * watchdog runs unconditionally rather than behind an OS gate. + * + * This composable emits no UI - it only owns the watchdog timer's lifecycle. + * + * @param JFrame window The host window to watch and heal. + */ +@Composable +fun WindowResizeHeal(window: JFrame) { + DisposableEffect(window) { + val healTimer = + Timer(HEAL_CHECK_INTERVAL_MILLIS) { + if (!window.isShowing) { + return@Timer + } + val insets = window.insets + val expectedWidth = window.width - insets.left - insets.right + val expectedHeight = window.height - insets.top - insets.bottom + val rootPane = window.rootPane + if (expectedWidth > 0 && + expectedHeight > 0 && + (rootPane.width != expectedWidth || rootPane.height != expectedHeight) + ) { + // Replay what a real resize event does: layout first so the scene and every Swing + // child match the true bounds, then the window-level event so Compose's listener + // re-reads the (already correct) width/height into WindowState. + window.invalidate() + window.validate() + window.dispatchEvent(ComponentEvent(window, ComponentEvent.COMPONENT_RESIZED)) + } + } + healTimer.start() + onDispose { healTimer.stop() } + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowSettings.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowSettings.kt new file mode 100644 index 0000000..baa1e4b --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/WindowSettings.kt @@ -0,0 +1,59 @@ +package org.umamo.editor.desktop + +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.WindowPlacement +import androidx.compose.ui.window.WindowPosition +import androidx.compose.ui.window.WindowState +import org.umamo.settings.Settings + +/** + * The window size/position/placement to open with - restored from `interface.window.*`, or a sensible + * default (1280×800, platform-placed, floating) on first run. A window saved while maximized or fullscreen + * reopens that way; the persisted size/position are the floating restore geometry it returns to. + * + * @return WindowState The starting window state. + */ +fun Settings.savedWindowState(): WindowState { + val width = (getDouble("interface.window.width") ?: 1280.0).dp + val height = (getDouble("interface.window.height") ?: 800.0).dp + val x = getDouble("interface.window.x") + val y = getDouble("interface.window.y") + val position = if (x != null && y != null) WindowPosition(x.dp, y.dp) else WindowPosition.PlatformDefault + val placement = + when (getString("interface.window.placement")) { + "maximized" -> WindowPlacement.Maximized + "fullscreen" -> WindowPlacement.Fullscreen + else -> WindowPlacement.Floating + } + return WindowState(placement = placement, size = DpSize(width, height), position = position) +} + +/** + * Persists [state]'s current placement, plus its size + position, to `interface.window.*` so the next launch + * restores them. Call on close (the [WindowState] tracks live resizes/moves/maximize, so it holds the final + * state). Size and position are recorded only while floating: when maximized or fullscreen, [state]'s size + * and position are the screen-filling bounds, so saving them would clobber the restore geometry the window + * should return to on un-maximize - the last floating geometry is kept instead. + * + * @param WindowState state The window state to persist. + */ +fun Settings.saveWindowState(state: WindowState) { + setString( + "interface.window.placement", + when (state.placement) { + WindowPlacement.Maximized -> "maximized" + WindowPlacement.Fullscreen -> "fullscreen" + WindowPlacement.Floating -> "floating" + }, + ) + if (state.placement == WindowPlacement.Floating) { + setDouble("interface.window.width", state.size.width.value.toDouble()) + setDouble("interface.window.height", state.size.height.value.toDouble()) + val position = state.position + if (position is WindowPosition.Absolute) { + setDouble("interface.window.x", position.x.value.toDouble()) + setDouble("interface.window.y", position.y.value.toDouble()) + } + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/GlfwOffscreenGlContext.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/GlfwOffscreenGlContext.kt new file mode 100644 index 0000000..dc9cc92 --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/GlfwOffscreenGlContext.kt @@ -0,0 +1,60 @@ +package org.umamo.editor.desktop.viewport + +import org.lwjgl.glfw.GLFW +import org.lwjgl.opengl.GL +import org.lwjgl.system.MemoryUtil +import org.umamo.render.gl.GlRenderDevice + +/** + * The Windows / Linux offscreen GL context: a hidden GLFW window carrying a GL 3.3 core context, made + * current on the render thread. + */ +internal class GlfwOffscreenGlContext : OffscreenGlContext { + override val backendName: String = "GLFW" + + private var window: Long = MemoryUtil.NULL + + /** + * Creates the GLFW hidden-window GL 3.3 core context on this thread and makes it current. Returns false + * (degrading to a blank viewport) if GLFW init or window creation fails. + * + * @return Boolean True on success. + */ + override fun createAndMakeCurrent(): Boolean { + // On Linux Wayland sessions, LWJGL's GLFW often fails to create the hidden offscreen + // window, which leaves the puppet viewport blank. Prefer X11 (XWayland) when available. + val osName = System.getProperty("os.name").orEmpty().lowercase() + if (osName.contains("linux") && GLFW.glfwPlatformSupported(GLFW.GLFW_PLATFORM_X11)) { + GLFW.glfwInitHint(GLFW.GLFW_PLATFORM, GLFW.GLFW_PLATFORM_X11) + } + if (!GLFW.glfwInit()) { + return false + } + GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE) + GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3) + GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 3) + GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE) + GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_FORWARD_COMPAT, GLFW.GLFW_TRUE) + window = GLFW.glfwCreateWindow(1, 1, "umamo-offscreen", MemoryUtil.NULL, MemoryUtil.NULL) + if (window == MemoryUtil.NULL) { + return false + } + GLFW.glfwMakeContextCurrent(window) + GL.createCapabilities() + return true + } + + override fun describeContext(): String = GlRenderDevice().describeBackend() + + /** + * Releases the GLFW window and unbinds the context. Runs on the render thread, where the context is + * current, after the engine's glFinish barrier. + */ + override fun destroy() { + if (window != MemoryUtil.NULL) { + GLFW.glfwMakeContextCurrent(MemoryUtil.NULL) + GLFW.glfwDestroyWindow(window) + window = MemoryUtil.NULL + } + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenGlContext.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenGlContext.kt new file mode 100644 index 0000000..7bd7a1d --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenGlContext.kt @@ -0,0 +1,56 @@ +package org.umamo.editor.desktop.viewport + +import org.lwjgl.system.Configuration + +/** + * An off-screen GL 3.3+ core context owned by a single render thread. The offscreen viewport renderer + * ([OffscreenRenderEngine]) renders only to framebuffer objects, so a context needs no visible window and no + * presentable drawable - just a current GL context on the thread that issues the draw and read-back calls. + * + * Threading contract: [createAndMakeCurrent], [describeContext], and [destroy] all run on the one render + * thread, in that order across the context's life; the context is never migrated to another thread. + */ +internal interface OffscreenGlContext { + /** + * A short backend label for the startup log line (for example "GLFW" or "CGL GL4_Core"), so the log + * records which path the running OS actually took. + */ + val backendName: String + + /** + * Creates the context and makes it current on the calling (render) thread. On failure returns false so + * the caller degrades to a blank viewport rather than crashing - the same graceful fallback the engine + * already applies when GL is unavailable. + * + * @return Boolean True on success (a context is now current), false to degrade to a blank viewport. + */ + fun createAndMakeCurrent(): Boolean + + /** + * The renderer / version / vendor / GLSL of the current context, for the startup diagnostic. Valid only + * after a successful [createAndMakeCurrent]. + * + * @return String The context description. + */ + fun describeContext(): String + + /** + * Releases the context on the render thread. Must NOT call glFinish - the engine issues one glFinish + * barrier before disposing its GL resources, and this runs last, after that barrier. + */ + fun destroy() +} + +/** + * Selects the offscreen GL context implementation for the running OS. GLFW is used on all platforms. + * + * @return OffscreenGlContext The context backend for this OS. + */ +internal fun createOffscreenGlContext(): OffscreenGlContext { + val osName = System.getProperty("os.name").orEmpty().lowercase() + if (osName.contains("mac") || osName.contains("darwin")) { + // https://javadoc.lwjgl.org/org/lwjgl/glfw/package-summary.html#using-glfw-on-macos-heading + Configuration.GLFW_LIBRARY_NAME.set("glfw_async") + } + return GlfwOffscreenGlContext() +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenPuppetService.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenPuppetService.kt new file mode 100644 index 0000000..103c17f --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenPuppetService.kt @@ -0,0 +1,217 @@ +package org.umamo.editor.desktop.viewport + +import androidx.compose.ui.graphics.ImageBitmap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.withContext +import org.umamo.edit.GridConfig +import org.umamo.format.raster.RasterImage +import org.umamo.render.ContentBounds +import org.umamo.render.FrameBackdrop +import org.umamo.render.GridColors +import org.umamo.render.LayerDrawPlan +import org.umamo.render.LayerRasterBatch +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.capturedOver +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.model.DrawableThumbnailProvider +import org.umamo.ui.viewport.AreaCameraKey +import org.umamo.ui.viewport.AtlasPageBinding +import org.umamo.ui.viewport.ImageFrame +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.PuppetViewportService +import org.umamo.ui.viewport.RenderedFrame +import org.umamo.ui.viewport.UvSceneContent + +/** + * Renders the puppet OFF-SCREEN and publishes it as a Compose ImageBitmap per viewport area. + * Because the viewport is then lightweight Compose content, the UI layers over it correctly on every platform. + * + * This is the desktop implementation of [PuppetViewportService]. It is a thin facade that composes the + * pieces and forwards each call to the collaborator that owns it: + * + * - [ViewportAreaRegistry] - the registered areas + their cameras (register / resize / navigation), on the + * UI thread. + * - [OffscreenRenderEngine] - the render thread that owns the GL context, renderer, framebuffers, and + * async read-back, plus the render-input state (selection / shown / model / atlas pages / source + * artwork / grid / highlight colors). + * - [ViewportPicker] - CPU hit-testing and art thumbnails, on the UI thread (no GL). + * + * The GL context is chosen per OS behind [OffscreenGlContext], which is a hidden GLFW window on every + * desktop OS today (macOS only differs by loading the async GLFW library). + * + * Threading: every method here is called on the UI thread; the engine publishes frames from its render + * thread via the areas' StateFlows. Picking is CPU-side and synchronous. + * + * @property PuppetModel puppet The rig to render. + * @property PuppetTextures textures The atlas page(s). + * @property LiveParams liveParams The shared parameter hand-off (drives re-render on change). + */ +class OffscreenPuppetService( + puppet: PuppetModel, + textures: PuppetTextures, + liveParams: LiveParams, +) : PuppetViewportService { + private val registry = ViewportAreaRegistry() + private val engine = OffscreenRenderEngine(puppet, textures, liveParams, registry) + + // The picker shares the engine's renderer for its pure-CPU pickGeometry()/drawnOrder() snapshots (the + // same instance the render thread draws with - those reads are CPU-only and UI-thread-safe). + private val picker = ViewportPicker(engine.puppetRenderer, textures, puppet) + + /** Starts the render thread (call once, after construction). */ + fun start() { + engine.start() + } + + override var zoomStepPercent: Float + get() = registry.zoomStepPercent + set(value) { + registry.zoomStepPercent = value + } + + override var zoomStepCoarsePercent: Float + get() = registry.zoomStepCoarsePercent + set(value) { + registry.zoomStepCoarsePercent = value + } + + override var supersampleEnabled: Boolean + get() = engine.supersampleEnabled + set(value) { + engine.supersampleEnabled = value + } + + override var supersampleWhileResizing: Boolean + get() = engine.supersampleWhileResizing + set(value) { + engine.supersampleWhileResizing = value + } + + override var gridColors: GridColors + get() = engine.gridColors + set(value) { + engine.gridColors = value + } + + override var gridConfig: GridConfig + get() = engine.gridConfig + set(value) { + engine.gridConfig = value + } + + override fun register(areaId: String): StateFlow = registry.register(areaId) + + override fun registerUvScene(areaId: String, content: UvSceneContent, islandExtent: ContentBounds?): StateFlow = + registry.registerUvScene(areaId, content, islandExtent) + + override fun setUvSceneContent(areaId: String, content: UvSceneContent, islandExtent: ContentBounds?) = + registry.setUvSceneContent(areaId, content, islandExtent) + + override fun unregister(areaId: String) = registry.unregister(areaId) + + override fun cameraFlow(areaId: String): StateFlow = registry.cameraFlow(areaId) + + override fun cameras(): Map = registry.cameras() + + override fun seedCameras(cameras: Map) = registry.seedCameras(cameras) + + override fun resize(areaId: String, width: Int, height: Int) = registry.resize(areaId, width, height) + + override fun pan(areaId: String, deltaXpx: Float, deltaYpx: Float) = registry.pan(areaId, deltaXpx, deltaYpx) + + override fun zoomAtCursor(areaId: String, zoomIn: Boolean, coarse: Boolean, cursorXpx: Float, cursorYpx: Float) = + registry.zoomAtCursor(areaId, zoomIn, coarse, cursorXpx, cursorYpx) + + override fun zoomCentered(areaId: String, zoomIn: Boolean, coarse: Boolean) = + registry.zoomCentered(areaId, zoomIn, coarse) + + override fun zoomToRegion(areaId: String, leftPx: Float, topPx: Float, rightPx: Float, bottomPx: Float) = + registry.zoomToRegion(areaId, leftPx, topPx, rightPx, bottomPx) + + override fun actualSize(areaId: String) = registry.actualSize(areaId) + + override fun fit(areaId: String) = registry.fit(areaId) + + override fun fitWorldRect(areaId: String, minX: Float, minZ: Float, maxX: Float, maxZ: Float) = + registry.fitWorldRect(areaId, minX, minZ, maxX, maxZ) + + override fun setSelection(ids: Set) = engine.setSelection(ids) + + override fun setActiveSelection(id: DrawableId?) = engine.setActiveSelection(id) + + override fun setShownDrawables(ids: Set) = engine.setShownDrawables(ids) + + override fun setEditMeshFrozen(ids: Set) = engine.setEditMeshFrozen(ids) + + override fun setSourceLayerPlan(plan: LayerDrawPlan) = engine.setSourceLayerPlan(plan) + + override fun setAtlasPages(binding: AtlasPageBinding) { + engine.setAtlasPages(binding) + // The picker samples page alpha CPU-side, so its pixels must move with the GPU's - a stale set + // would reject clicks on visible art at the re-derived coordinates. + picker.setTextures(binding.textures) + } + + override fun deliverSourceLayerRasters(batch: LayerRasterBatch) = engine.deliverSourceLayerRasters(batch) + + /** + * Pushes the latest model to the render engine and, when it actually changed, rebuilds the picker's + * model-derived lookup maps so session-created drawables stay pickable / sampleable / labeled. + * + * @param PuppetModel model The current model. + */ + override fun setModel(model: PuppetModel) { + if (engine.setModel(model)) { + picker.updateModel(model) + } + } + + override fun setSelectionHighlightColor(red: Float, green: Float, blue: Float) = + engine.setSelectionHighlightColor(red, green, blue) + + override fun setActiveSelectionHighlightColor(red: Float, green: Float, blue: Float) = + engine.setActiveSelectionHighlightColor(red, green, blue) + + override fun pickAt(areaId: String, cursorXpx: Float, cursorYpx: Float): DrawableId? { + val view = registry.viewFor(areaId) ?: return null + return picker.pickAt(view.camera, view.width, view.height, cursorXpx, cursorYpx) + } + + override fun pickAllAt(areaId: String, cursorXpx: Float, cursorYpx: Float): List { + val view = registry.viewFor(areaId) ?: return emptyList() + return picker.pickAllAt(view.camera, view.width, view.height, cursorXpx, cursorYpx) + } + + override fun drawableWorldCentroids(): Map = picker.drawableWorldCentroids() + + /** + * Queues the capture on the render thread and, once its pixels arrive, converts them off the UI thread + * from the framebuffer's premultiplied color to the straight alpha an image file stores. + * + * @param ImageFrame frame The camera and pixel size to render. + * @param FrameBackdrop backdrop What the puppet is drawn over. + * @return RasterImage? The image, straight alpha, or null when the render thread could not serve it. + */ + override suspend fun renderImage(frame: ImageFrame, backdrop: FrameBackdrop): RasterImage? { + val premultiplied = engine.requestSnapshot(frame.camera, frame.width, frame.height, backdrop).await() ?: return null + return withContext(Dispatchers.Default) { premultiplied.capturedOver(backdrop) } + } + + override fun areaView(areaId: String): ImageFrame? = registry.viewFor(areaId)?.let { view -> ImageFrame(view.camera, view.width, view.height) } + + override fun visibleContentBounds(): ContentBounds? = engine.puppetRenderer.posedContentBounds(engine.shownDrawables) + + override fun thumbnailFor(id: DrawableId): ImageBitmap? = picker.thumbnailFor(id) + + override fun thumbnails(): DrawableThumbnailProvider = picker.thumbnails() + + override fun partNameFor(id: DrawableId): String? = picker.partNameFor(id) + + override fun drawableNameFor(id: DrawableId): String? = picker.drawableNameFor(id) + + override fun dispose() = engine.dispose() +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenRenderEngine.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenRenderEngine.kt new file mode 100644 index 0000000..6c278a3 --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/OffscreenRenderEngine.kt @@ -0,0 +1,976 @@ +package org.umamo.editor.desktop.viewport + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Deferred +import org.lwjgl.opengl.GL11 +import org.umamo.edit.GridConfig +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.render.ContentBounds +import org.umamo.render.DecodedImage +import org.umamo.render.FrameBackdrop +import org.umamo.render.GridColors +import org.umamo.render.LayerDrawPlan +import org.umamo.render.LayerRasterBatch +import org.umamo.render.PuppetTextures +import org.umamo.render.SupersampledSurface +import org.umamo.render.ViewportCamera +import org.umamo.render.device.ReadbackTicket +import org.umamo.render.gl.GlRenderDevice +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.visibleDrawableIds +import org.umamo.storage.UmamoLog +import org.umamo.ui.graphics.RgbaAlphaType +import org.umamo.ui.graphics.rgbaToImageBitmap +import org.umamo.ui.viewport.AtlasPageBinding +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.RenderedFrame +import org.umamo.ui.viewport.UvSceneContent +import java.io.File +import java.util.ArrayDeque +import java.util.concurrent.ConcurrentLinkedQueue + +/** + * Framebuffer pixels per display pixel while supersampling is on: the whole pipeline renders 2x and + * box-downscales on resolve. Supersampling off collapses the scale to 1. + */ +internal const val RENDER_SUPERSAMPLE = 2 + +/** Idle poll when nothing changed and no read-back is in flight (about 60 Hz wake to pick up new params). */ +private const val IDLE_MILLIS = 16L + +/** Short poll while a read-back is in flight, so its result is collected with low latency. */ +private const val BUSY_MILLIS = 1L + +/** + * Minimum interval between resize-driven re-renders while an area's size is actively changing (a + * gutter drag or a window-edge resize): about 10 Hz of live feedback, with the Compose side + * stretching the previous frame between them. Pose / camera / state changes are never throttled. + */ +private const val RESIZE_THROTTLE_NANOS = 50_000_000L + +/** How long a size must hold still before it counts as settled (the full-quality render then runs). */ +private const val RESIZE_SETTLE_NANOS = 25_000_000L + +/** + * The render engine: a dedicated daemon thread owns the GL context, the [PuppetRenderer], the supersample + * framebuffers, and the async read-back pool, and runs the render loop. It holds the render-input state the + * UI thread pushes (selection, shown set, model, atlas pages, source artwork, grid, highlight colors), renders + * each registered area whose pose / size / camera / backdrop changed, and publishes finished frames to the + * area's slot. + * + * The read-back is asynchronous (PBO + fence) so the thread never blocks on the GPU while a slider drags. + * Every 2D area of one document shows the same puppet at the same pose (the shared [liveParams]), so those + * areas differ only by size and camera; re-renders happen only when the pose or an area's + * size / camera / scene content / backdrop changes. + * + * @property PuppetModel puppet The rig to render. + * @property PuppetTextures textures The atlas page(s). + * @property LiveParams liveParams The shared parameter hand-off (drives re-render on change). + * @property ViewportAreaRegistry registry The area slots this engine renders and fits. + */ +internal class OffscreenRenderEngine( + private val puppet: PuppetModel, + private val textures: PuppetTextures, + private val liveParams: LiveParams, + private val registry: ViewportAreaRegistry, +) { + // The GL backend the renderer draws through; render-thread-owned, like every GL object here. + private val device = GlRenderDevice() + + // GL handles + async read-back state, all owned by the render thread. + private val renderer = + PuppetRenderer(puppet, textures, device).apply { + // The editor viewport shows the world-origin axes (red X / blue Z behind the puppet); the + // renderer default is off so headless render-diff tests stay line-free. + setWorldAxesVisible(true) + } + + /** The shared renderer, exposed so the facade can build the CPU picker over its pickGeometry()/drawnOrder(). */ + val puppetRenderer: PuppetRenderer + get() = renderer + + private val context = createOffscreenGlContext() + + // The supersampled draw + display-size resolve target pair, device-owned and backend-neutral. + private val surface = SupersampledSurface(device, RENDER_SUPERSAMPLE) + + /** An asynchronous read-back in flight: the device ticket plus what the pixels will mean on arrival. */ + private class PendingFrame( + val ticket: ReadbackTicket, + val areaId: String, + val camera: ViewportCamera, + val model: PuppetModel, + ) + + // In-flight read-backs in submission order; polled front-first each loop tick. Render-thread only. + private val pendingFrames = ArrayDeque() + + /** + * An image capture waiting for the render thread: what to draw, and where its pixels go. + * + * @property ViewportCamera camera The capture's camera. + * @property Int width The image width in pixels. + * @property Int height The image height in pixels. + * @property FrameBackdrop backdrop What the puppet is drawn over. + * @property CompletableDeferred result Completed with the premultiplied pixels, or null. + */ + private class PendingSnapshot( + val camera: ViewportCamera, + val width: Int, + val height: Int, + val backdrop: FrameBackdrop, + val result: CompletableDeferred, + ) + + // Captures queued by the UI thread and taken up by the render thread between frames. A queue for the same + // reason as the raster batches: two requests landing in one tick must both be served. + private val pendingSnapshots = ConcurrentLinkedQueue() + + // False once the render thread can no longer serve a capture (its context never came up, or it has shut + // down), so a request made after that is answered at once instead of waiting forever. + @Volatile + private var acceptingSnapshots = true + + @Volatile + private var running = true + + // Daemon so it can never block JVM exit; clean teardown still happens via dispose() -> join. + private val renderThread = Thread({ renderLoop() }, "umamo-offscreen-gl").apply { isDaemon = true } + + // --- Render inputs: written by the UI thread (volatile publishes of immutable values / scalars), read by + // the render thread each frame. A change bumps a render-version counter the loop folds into per-area + // freshness, so a state-only change (no resize / pose / camera change) still forces exactly one redraw. + + // The grid backdrop colors, fed from the editor theme; default to the neutral grey grid until the host + // pushes the themed colors. + @Volatile + private var gridColorsBacking: GridColors = GridColors.Classic + + // The per-document grid geometry (major spacing + subdivisions), fed from the session. + @Volatile + private var gridConfigBacking: GridConfig = GridConfig() + + // The currently selected drawables, read by the render thread to tint them. + @Volatile + private var selectionBacking: Set = emptySet() + + // The active (last-selected) drawable, tinted apart from the rest of a multi-selection; null when none. + @Volatile + private var activeSelectionBacking: DrawableId? = null + + // The drawables actually drawn (the resolved Parts-panel visibility cascade). Seeded from the open + // model's static cascade. + @Volatile + private var shownBacking: Set = puppet.visibleDrawableIds() + + // Edit-session drawable ids whose textured GPU mesh is frozen as the mesh-edit guide image. Empty + // outside Edit mode. Applied on the render thread before updateModel so topology edits keep the image. + @Volatile + private var editMeshFrozenBacking: Set = emptySet() + + // Which artwork the puppet's drawables map onto, published whole. EMPTY is the atlas, which is where + // every document starts until a plan is prepared for it. The pixels are NOT here: they arrive + // through the queue below, in answer to what the renderer asks for. + @Volatile + private var layerPlanBacking: LayerDrawPlan = LayerDrawPlan.EMPTY + + // Decoded artwork waiting to be uploaded, drained on the render thread. A queue rather than a + // volatile slot because deliveries are chunked - two batches landing between frames must both be + // taken up, where a slot would silently drop the first. + private val pendingRasterBatches = ConcurrentLinkedQueue() + + // The latest model, re-pushed on a structural edit (layer reorder / reparent, base-mesh move); seeded + // with the open model. + @Volatile + private var modelBacking: PuppetModel = puppet + + // The construction-time page pair: the pages initGl uploads, tagged with the atlas they render. + // Seeds both the published slot and the applied state, so the loop's first tick applies nothing + // unless a binding was pushed before the thread started. + private val initialAtlasBinding = AtlasPageBinding(puppet.atlas, textures) + + // The latest page set, published whole with the atlas value it was composed for. The loop applies + // it and an atlas-changing model as one pair - see the pairing note in renderLoop. + @Volatile + private var atlasBindingBacking: AtlasPageBinding = initialAtlasBinding + + // The pair the render thread has actually applied. Render-thread-owned after start(); read by the + // UV fit path (pageContentBounds), which also runs on the render thread. + private var appliedAtlasBinding: AtlasPageBinding = initialAtlasBinding + + @Volatile + private var puppetRenderBump: Long = 0 + + // The UV editor's flat scenes (atlas page, source layer) bump separately from the puppet, so a puppet + // update does not needlessly re-render them. + @Volatile + private var atlasRenderBump: Long = 0 + + // The color selected drawables are tinted toward; RGB, each 0..1, defaults to the classic blue accent. + @Volatile + private var highlightRed: Float = 0.20f + + @Volatile + private var highlightGreen: Float = 0.55f + + @Volatile + private var highlightBlue: Float = 1.0f + + // The color the active drawable is tinted toward; RGB, each 0..1, defaults to the edit-mode active green. + @Volatile + private var activeHighlightRed: Float = 0.49f + + @Volatile + private var activeHighlightGreen: Float = 0.89f + + @Volatile + private var activeHighlightBlue: Float = 0.0f + + // The performance settings (viewport.rendering.*): whether settled frames supersample at all, and + // whether frames rendered while a size is actively changing keep the supersample (false = drop to + // 1x for a quarter of the fill cost during gutter drags and window resizes). + @Volatile + private var supersampleBacking: Boolean = true + + @Volatile + private var supersampleWhileResizingBacking: Boolean = true + + private var dumped = false + + /** Starts the render thread (call once). */ + fun start() { + renderThread.start() + } + + /** Stops the render thread and releases the GL context. Blocks briefly to join. */ + fun dispose() { + running = false + renderThread.join(2000) + acceptingSnapshots = false + failPendingSnapshots() + } + + /** + * The drawables actually drawn (the resolved visibility cascade), as last pushed - what a capture's + * framing measures. + */ + val shownDrawables: Set + get() = shownBacking + + /** + * Queues an image capture of the current pose for the render thread, which takes it up between frames + * with the latest model, pages, artwork, shown set, and pose applied. + * + * Always completes: with the premultiplied pixels, or with null when the render thread cannot serve it. + * The check comes after the enqueue, so a shutdown racing the request still sweeps it up. + * + * @param ViewportCamera camera The capture's camera. + * @param Int width The image width in pixels. + * @param Int height The image height in pixels. + * @param FrameBackdrop backdrop What the puppet is drawn over. + * @return Deferred The premultiplied pixels, top row first, or null. + */ + fun requestSnapshot(camera: ViewportCamera, width: Int, height: Int, backdrop: FrameBackdrop): Deferred { + val snapshot = PendingSnapshot(camera, width, height, backdrop, CompletableDeferred()) + pendingSnapshots.add(snapshot) + if (!acceptingSnapshots) { + failPendingSnapshots() + } + return snapshot.result + } + + /** Answers every queued capture with null: the render thread will not serve them. */ + private fun failPendingSnapshots() { + while (true) { + val snapshot = pendingSnapshots.poll() ?: break + snapshot.result.complete(null) + } + } + + /** + * Renders every queued capture, on the render thread. A capture that fails logs and completes null; it + * never takes the render loop down with it. + * + * A shutdown stops the work at the next tile, so dispose() waits for one tile rather than a whole large + * image; what is left in the queue is answered by the loop's teardown. + */ + private fun serveSnapshots() { + while (running) { + val snapshot = pendingSnapshots.poll() ?: break + try { + if (snapshot.backdrop == FrameBackdrop.Grid) { + // The area renders apply the grid per render; a capture over it applies its own the same way. + val gridConfigApplied = gridConfigBacking + renderer.setGrid(gridColorsBacking, gridConfigApplied.scale, gridConfigApplied.subdivisions) + } + val image = renderer.renderSnapshot(snapshot.camera, snapshot.width, snapshot.height, snapshot.backdrop) { running } + if (image == null) { + UmamoLog.info("[GL] image capture (${snapshot.width}x${snapshot.height}) abandoned at shutdown") + } + snapshot.result.complete(image) + } catch (failure: Exception) { + UmamoLog.error("[GL] image capture (${snapshot.width}x${snapshot.height}) failed", failure) + snapshot.result.complete(null) + } catch (failure: OutOfMemoryError) { + // The stitched image is the one large allocation here, and running short of it costs this + // capture, not the viewport. + UmamoLog.error("[GL] image capture (${snapshot.width}x${snapshot.height}) ran out of memory", failure) + snapshot.result.complete(null) + } + } + } + + /** + * The grid backdrop colors (background / major / minor). A change bumps both render passes so a + * color-only change repaints without waiting for an unrelated render. + */ + var gridColors: GridColors + get() = gridColorsBacking + set(value) { + if (value != gridColorsBacking) { + gridColorsBacking = value + doPuppetRenderBump() + doAtlasRenderBump() + } + } + + /** + * The per-document grid geometry (major spacing + subdivisions). Like the grid colors, a change bumps + * both render passes so a grid-only change repaints without waiting for an unrelated render. + */ + var gridConfig: GridConfig + get() = gridConfigBacking + set(value) { + if (value != gridConfigBacking) { + gridConfigBacking = value + doPuppetRenderBump() + doAtlasRenderBump() + } + } + + /** + * Sets the highlighted drawables (object-mode selection). A change bumps the puppet render version so the + * loop re-renders every area once with the new tint; an identical set is a no-op. + * + * @param Set ids The selected drawable ids. + */ + fun setSelection(ids: Set) { + if (ids != selectionBacking) { + selectionBacking = ids + doPuppetRenderBump() + } + } + + /** + * Sets the active (last-selected) drawable, tinted apart from the rest of a multi-selection. A change + * bumps the puppet render version; an identical value is a no-op. + * + * @param DrawableId id The active drawable id, or null when none is active. + */ + fun setActiveSelection(id: DrawableId?) { + if (id != activeSelectionBacking) { + activeSelectionBacking = id + doPuppetRenderBump() + } + } + + /** + * Sets which drawables are drawn (the resolved Parts-panel visibility cascade). A change bumps the puppet + * render version so every area re-renders once; the geometry is unchanged, so only the draw filter moves. + * + * @param Set ids The drawable ids to draw. + */ + fun setShownDrawables(ids: Set) { + if (ids != shownBacking) { + shownBacking = ids + doPuppetRenderBump() + } + } + + /** + * Freezes Edit-session textured meshes as the mesh-edit guide image (see + * [PuppetRenderer.setEditMeshFrozen]). A change bumps the puppet render version. + * + * @param Set ids The Edit-session drawable ids to freeze, or empty to thaw. + */ + fun setEditMeshFrozen(ids: Set) { + if (ids != editMeshFrozenBacking) { + editMeshFrozenBacking = ids + doPuppetRenderBump() + } + } + + /** + * Sets which artwork the puppet's drawables map onto; an empty plan displays from the atlas. + * + * A volatile publish of one immutable value, like every other render input. The render loop hands + * it to the renderer, which is where the GPU work happens - this must not touch the device. + * + * @param LayerDrawPlan plan Each drawable's mapping into the document's artwork. + */ + fun setSourceLayerPlan(plan: LayerDrawPlan) { + if (plan !== layerPlanBacking) { + layerPlanBacking = plan + doPuppetRenderBump() + } + } + + /** + * Queues decoded artwork for upload on the render thread. + * + * @param LayerRasterBatch batch The decoded artwork. + */ + fun deliverSourceLayerRasters(batch: LayerRasterBatch) { + pendingRasterBatches.add(batch) + doPuppetRenderBump() + } + + /** + * Publishes the atlas page set the current model's placements render from. A pure volatile + * publish: the render loop bumps its own freshness when it APPLIES the binding, because applying + * can lag the publish by a tick while the matching model arrives - a bump here would let an area + * render back to freshness against the outgoing pair and never take the new one up. + * + * @param AtlasPageBinding binding The pages plus the atlas value they belong to. + */ + fun setAtlasPages(binding: AtlasPageBinding) { + if (binding !== atlasBindingBacking) { + atlasBindingBacking = binding + } + } + + /** + * Pushes the latest model so the render thread can reconcile it after an edit (a layer reorder + * re-derives the render order; a base-mesh move re-uploads the changed drawables' VBOs). A new (different) + * instance bumps the puppet render version so every area re-renders once. + * + * @param PuppetModel model The current model. + * @return Boolean True when the model actually changed (so the caller rebuilds model-derived state). + */ + fun setModel(model: PuppetModel): Boolean { + if (model !== modelBacking) { + modelBacking = model + doPuppetRenderBump() + return true + } + return false + } + + /** + * Sets the color selected drawables are tinted toward (the selection highlight). A change bumps the + * puppet render version; an identical color is a no-op. + * + * @param Float red The tint red, 0..1. + * @param Float green The tint green, 0..1. + * @param Float blue The tint blue, 0..1. + */ + fun setSelectionHighlightColor(red: Float, green: Float, blue: Float) { + if (red != highlightRed || green != highlightGreen || blue != highlightBlue) { + highlightRed = red + highlightGreen = green + highlightBlue = blue + doPuppetRenderBump() + } + } + + /** + * Sets the color the active drawable is tinted toward (the active-selection highlight). A change bumps the + * puppet render version; an identical color is a no-op. + * + * @param Float red The tint red, 0..1. + * @param Float green The tint green, 0..1. + * @param Float blue The tint blue, 0..1. + */ + fun setActiveSelectionHighlightColor(red: Float, green: Float, blue: Float) { + if (red != activeHighlightRed || green != activeHighlightGreen || blue != activeHighlightBlue) { + activeHighlightRed = red + activeHighlightGreen = green + activeHighlightBlue = blue + doPuppetRenderBump() + } + } + + /** + * Whether settled frames render supersampled at all (viewport.rendering.supersample). Off renders + * everything at 1x - the whole-session performance escape hatch for weak GPUs. A change bumps + * both render passes so every area repaints at the new quality. + */ + var supersampleEnabled: Boolean + get() = supersampleBacking + set(value) { + if (value != supersampleBacking) { + supersampleBacking = value + doPuppetRenderBump() + doAtlasRenderBump() + } + } + + /** + * Whether frames rendered while an area's size is actively changing keep the supersample + * (viewport.rendering.supersampleWhileResizing). False (the default) drops those frames to 1x; + * the settle render restores full quality within the settle window. No bump on change - the next + * resize simply picks up the new policy. + */ + var supersampleWhileResizing: Boolean + get() = supersampleWhileResizingBacking + set(value) { + supersampleWhileResizingBacking = value + } + + /** + * Bump the render version for puppets to increase the frame by one. + */ + fun doPuppetRenderBump() { + puppetRenderBump++ + } + + /** + * Bump the render version for atlases to increase the frame by one. + */ + fun doAtlasRenderBump() { + atlasRenderBump++ + } + + /** + * The render thread body: create the context, then loop - collect finished read-backs, issue new renders + * for changed areas, and idle when there is nothing to do. + */ + private fun renderLoop() { + if (!context.createAndMakeCurrent()) { + UmamoLog.warn("[GL] offscreen context unavailable (${context.backendName}); viewport will stay blank") + acceptingSnapshots = false + failPendingSnapshots() + return + } + UmamoLog.info("[GL] offscreen via ${context.backendName}: ${context.describeContext()}") + try { + renderer.initGl() + var lastParams: Map? = null + var lastOverrides: Map? = null + var lastShown: Set? = null + var lastModel: PuppetModel? = null + var lastLayerPlan: LayerDrawPlan? = null + var paramsVersion = 0L + while (running) { + collectCompleted() + val params = liveParams.values + val shown = shownBacking + // Pages and model apply as a consistent PAIR - the decision itself is pure and tested + // (resolveAtlasPairing); this block only carries it out. + val pairing = resolveAtlasPairing(modelBacking, atlasBindingBacking, appliedAtlasBinding, lastModel) + val orderModel = pairing.orderModel + pairing.applyBinding?.let { binding -> + // Pages first, then the model that samples them. The freshness bumps happen HERE, at + // apply, not at publish: paramsVersion re-renders the puppet areas, the atlas bump the + // UV page areas (whose AtlasPage content compares by index and cannot see same-index- + // new-pixels). A concurrent UI-thread bump can collapse into this one; both causes are + // covered by the single re-render that follows either way. + renderer.setAtlasPages(binding.textures) + appliedAtlasBinding = binding + paramsVersion++ + doAtlasRenderBump() + } + // The artwork hand-off, on the render thread where the uploads belong. The mapping is + // compared by identity: it is published whole, so a new reference IS the change. + val layerPlan = layerPlanBacking + if (layerPlan !== lastLayerPlan) { + renderer.setSourceLayerPlan(layerPlan) + lastLayerPlan = layerPlan + } + // Then any decoded pixels that arrived since the last frame. Drained rather than sampled: + // the producer chunks its deliveries so visible art lands first, and skipping a batch would + // strand whatever it carried on the atlas until the working set happened to move again. + while (true) { + val batch = pendingRasterBatches.poll() ?: break + renderer.deliverSourceLayerRasters(batch) + } + // Edit-mode guide freeze must land before updateModel so a topology delete in the same tick + // keeps the textured mesh. Applied every tick (cheap set-equality no-op when unchanged). + renderer.setEditMeshFrozen(editMeshFrozenBacking) + // Rebuild the pose - and thus the draw list, which setPose filters by the shown set and sorts by + // the render order - when the pose, the visibility cascade, OR the render order changes. A + // visibility toggle or a layer reorder leaves the params untouched, so without these checks the + // draw list would never refresh. setShownDrawables / updateModel run first so setPose uses them. + // The override map is compared by identity like the params map: both are swapped wholesale on + // the UI thread, so a reference change is exactly "something moved". + val overrides = liveParams.channelOverrides + if (params !== lastParams || overrides !== lastOverrides || shown !== lastShown || orderModel !== lastModel) { + renderer.setShownDrawables(shown) + if (orderModel !== lastModel) { + // Re-point the renderer at the edited model so the next setPose re-derives the draw order + // and (for a deformer reparent) the deform chain. + renderer.updateModel(orderModel) + lastModel = orderModel + } + renderer.setPose(params, overrides) + lastParams = params + lastOverrides = overrides + lastShown = shown + paramsVersion++ + } + // Captures run after the hand-offs above, so each one shows exactly the state the areas are about + // to render. A capture leaves the renderer's camera, scale, and selection as it found them, and + // every area render sets its own anyway. + serveSnapshots() + var pendingWork = pendingFrames.isNotEmpty() + val nowNanos = System.nanoTime() + val settleScale = if (supersampleBacking) RENDER_SUPERSAMPLE else 1 + // With supersampling off both scales collapse to 1, so supersampleWhileResizing is + // inert by construction (the preferences UI disables its checkbox to say so). + val interactiveScale = if (supersampleWhileResizingBacking) settleScale else 1 + for ((areaId, slot) in registry.areas) { + val width = slot.width + val height = slot.height + if (width <= 0 || height <= 0) { + continue + } + // Track size-change recency for the resize throttle. The FIRST observation (a fresh + // slot, observed 0x0) does not stamp, so a newly opened area counts as settled and its + // first frame renders at full quality immediately. + if (width != slot.observedWidth || height != slot.observedHeight) { + val firstObservation = slot.observedWidth == 0 && slot.observedHeight == 0 + slot.observedWidth = width + slot.observedHeight = height + if (!firstObservation) { + slot.sizeChangedNanos = nowNanos + } + } + if (slot.inFlight) { + pendingWork = true + continue // one read-back per area in flight; coalesces a flurry of slider moves + } + // Establish or refit the camera now that the size is known - the render thread owns the + // content bounds; the registry restores a remembered camera or fits fresh, and swaps a UV + // area's view when the page or layer it shows has changed. + val camera = registry.establishCamera(slot, areaId, width, height) { scene, content -> contentBoundsFor(scene, content) } + // Freshness splits into the size axis (throttled during an active resize) and the rest. + // A frame rendered below the settle scale stays size-stale on purpose, so the settle + // pass re-renders it at full quality once the size holds still. + // A UV scene is model-independent, so its freshness ignores the pose version and + // puppetRenderBump: it re-renders only on size / camera / the surface it shows (the page index + // or the layer raster), plus the grid colors and geometry it draws its backdrop with - tracked + // by atlasRenderBump. The puppet keeps the full freshness via puppetRenderBump. + val sizeFresh = slot.renderedWidth == width && slot.renderedHeight == height && slot.renderedScale == settleScale + val restFresh = + when (slot.scene) { + RenderScene.Puppet2D -> + slot.renderedParamsVersion == paramsVersion && + slot.renderedCamera === camera && + slot.puppetRenderBumpDone == puppetRenderBump + + // Kind and payload are read as ONE value, so a switch can never be observed half + // applied. Equality rather than identity: AtlasPage compares its index, and + // SourceLayer's image compares by reference, which is the freshness test either + // surface wants. + RenderScene.UvScene -> + slot.renderedUvContent == slot.uvContent && + slot.renderedCamera === camera && + slot.atlasRenderBumpDone == atlasRenderBump + } + if (sizeFresh && restFresh) { + continue + } + if (restFresh && shouldDeferResizeRender(slot, nowNanos)) { + // Deliberately NOT pendingWork: with no read-back in flight the loop then sleeps + // IDLE_MILLIS (16 ms) and revisits, which cannot oversleep the RESIZE_SETTLE_NANOS or the + // RESIZE_THROTTLE_NANOS window - flagging pendingWork with an empty pendingFrames queue + // would skip both sleeps and busy-spin instead. + continue + } + // A size still in motion renders at the interactive scale; pose / camera / state changes + // during that motion share the burst's quality rather than forcing a full-scale render. + val sizeInMotion = nowNanos - slot.sizeChangedNanos < RESIZE_SETTLE_NANOS + val renderScale = if (sizeInMotion) interactiveScale else settleScale + if (width != slot.renderedWidth || height != slot.renderedHeight) { + slot.resizeRenderNanos = nowNanos + } + issueRender(areaId, slot, width, height, paramsVersion, camera, orderModel, renderScale) + pendingWork = true + } + if (!pendingWork) { + Thread.sleep(IDLE_MILLIS) + } else if (pendingFrames.isNotEmpty()) { + Thread.sleep(BUSY_MILLIS) + } + } + } finally { + // Captures are answered before any GL teardown, which can itself throw: a caller awaiting one must + // hear back however this thread ends. + acceptingSnapshots = false + failPendingSnapshots() + // glFinish before any other GL call here, so the driver completes all pending GPU work BEFORE the + // disposers delete GL objects and the context is destroyed - otherwise a driver worker thread can be + // mid-copy on memory we free, which crashed (SIGSEGV in libc memcpy) on a clean window close. A + // single barrier here; the collaborators' dispose() must NOT call glFinish, and the context is + // destroyed last. + GL11.glFinish() + // Abandon in-flight read-backs (the fences/staging are freed through the device); the surface + // targets go the same way. The context is destroyed last. + while (pendingFrames.isNotEmpty()) { + device.cancelReadback(pendingFrames.removeFirst().ticket) + } + // The renderer's own device objects. Source artwork and underlay images are created and + // destroyed across its life rather than uploaded once, so they need releasing explicitly + // rather than being left to die with the context. + renderer.disposeGl() + pendingRasterBatches.clear() + surface.dispose() + context.destroy() + } + } + + /** + * The resize-throttle gate: whether a render whose ONLY staleness is its size should wait. A size + * that has held still for the settle window renders immediately (the full-quality settle pass); + * one still in motion renders at most once per throttle interval. + * + * @param AreaSlot slot The area being considered. + * @param Long nowNanos The loop pass's monotonic timestamp. + * @return Boolean True to skip this tick and let the idle sleep revisit. + */ + private fun shouldDeferResizeRender(slot: AreaSlot, nowNanos: Long): Boolean { + val settled = nowNanos - slot.sizeChangedNanos >= RESIZE_SETTLE_NANOS + val throttleElapsed = nowNanos - slot.resizeRenderNanos >= RESIZE_THROTTLE_NANOS + return !settled && !throttleElapsed + } + + /** + * Renders [slot] at [width] x [height] into the supersampled draw target, box-downscales it into the + * resolve framebuffer, then kicks off an asynchronous read-back gated by a fence. Marks the slot + * in-flight; the result is posted later by [collectCompleted]. + * + * @param String areaId The area's id. + * @param AreaSlot slot The area being rendered. + * @param Int width The render width in pixels. + * @param Int height The render height in pixels. + * @param Long paramsVersion The pose version this render reflects. + * @param ViewportCamera camera The view to project through. + * @param PuppetModel orderModel The model whose geometry this render reflects (stamped onto the frame). + * @param Int renderScale Framebuffer pixels per display pixel for THIS render: the settle scale for + * a still frame, the interactive scale while the size is in motion. + */ + private fun issueRender( + areaId: String, + slot: AreaSlot, + width: Int, + height: Int, + paramsVersion: Long, + camera: ViewportCamera, + orderModel: PuppetModel, + renderScale: Int, + ) { + val renderWidth = width * renderScale + val renderHeight = height * renderScale + + val drawTarget = surface.ensure(width, height, renderScale) + + // Supersample: render the whole pipeline (puppet, clip masks, grid) into the renderScale x draw + // buffer, then box-downscale to display size on resolve. The camera zoom and the grid line width scale + // by the same factor so framing and backdrop are unchanged after the downscale. The resolve target + // is display-size whatever the scale, so read-back consumers never see the quality switch. + renderer.setRenderScale(renderScale.toFloat()) + + // Capture the backdrop versions applied to this render so the freshness stamp below matches what was + // actually drawn; a change after this point bumps them again and re-renders next iteration. + val puppetRenderBumpDone = puppetRenderBump + val atlasRenderBumpDone = atlasRenderBump + + val gridConfigApplied = gridConfigBacking + renderer.setGrid(gridColorsBacking, gridConfigApplied.scale, gridConfigApplied.subdivisions) + renderer.setSelection(selectionBacking) + renderer.setActiveSelection(activeSelectionBacking) + + // The shown set is applied in the render-loop pose block (before setPose filters the draw list by it). + renderer.setSelectionHighlightColor(highlightRed, highlightGreen, highlightBlue) + renderer.setActiveSelectionHighlightColor(activeHighlightRed, activeHighlightGreen, activeHighlightBlue) + renderer.setCamera(camera.copy(zoom = camera.zoom * renderScale)) + + // Read once, drawn and stamped from the same value: re-reading slot.uvContent between the draw and + // the stamp below would let a switch land in between and mark the frame fresh for content it does + // not show. + val uvContent = slot.uvContent + when (slot.scene) { + RenderScene.Puppet2D -> renderer.render(drawTarget, renderWidth, renderHeight) + // A UV area draws its flat surface instead; the pose / selection / shown state pushed above are + // harmless no-ops for it (neither UV draw reads any of them - just the grid and the surface quad). + RenderScene.UvScene -> + when (uvContent) { + // An atlas page the engine already uploaded, addressed by index. + is UvSceneContent.AtlasPage -> renderer.renderAtlasPage(drawTarget, uvContent.pageIndex, renderWidth, renderHeight) + // Artwork the engine has never uploaded, so the renderer takes the pixels rather than an + // index and caches the texture it makes from them. + is UvSceneContent.SourceLayer -> renderer.renderUnderlayImage(drawTarget, uvContent.image, renderWidth, renderHeight) + null -> renderer.renderAtlasPage(drawTarget, null, renderWidth, renderHeight) + } + } + + surface.resolve() + + if (!dumped) { + System.getenv("UMAMO_DUMP_PNG")?.let { dumpPath -> + // A synchronous client read-back; safe here because no PBO is bound yet. Encoding and the + // file write live here rather than in :render - reading pixels is the renderer's business, + // turning them into a PNG on disk is not, and keeping the split means :render needs no + // image library at all. + File(dumpPath).writeBytes(PngCodec.write(device.readPixels(surface.resolveTarget, width, height))) + dumped = true + UmamoLog.info("[GL] puppet dumped to $dumpPath (${width}x$height)") + } + } + + // Bind the frame to the camera it was rendered at (the plain, non-supersampled camera) and to + // orderModel, the geometry this render reflects, so the overlay projects/poses against them - keeping + // the mesh glued to the raster along both the navigation and edit axes. The resolve target is + // capacity-sized (grow-only), so the read-back covers only the used region. + pendingFrames.addLast(PendingFrame(device.beginReadback(surface.resolveTarget, width, height), areaId, camera, orderModel)) + slot.inFlight = true + slot.renderedWidth = width + slot.renderedHeight = height + slot.renderedScale = renderScale + slot.renderedParamsVersion = paramsVersion + slot.renderedCamera = camera + slot.puppetRenderBumpDone = puppetRenderBumpDone + slot.atlasRenderBumpDone = atlasRenderBumpDone + slot.renderedUvContent = uvContent + } + + /** + * Collects every read-back whose fence signaled and publishes it to its area's slot, clearing the slot's + * in-flight flag. A read-back whose slot was unregistered while in flight is discarded (the slot is gone). + */ + private fun collectCompleted() { + // Front-first, stopping at the first still-in-flight ticket: reads complete in submission order on + // the GPU timeline, so a later one cannot be done before an earlier one. + while (pendingFrames.isNotEmpty()) { + val pending = pendingFrames.first() + val pixels = device.pollReadback(pending.ticket) ?: break + pendingFrames.removeFirst() + val slot = registry.areas[pending.areaId] ?: continue + slot.inFlight = false + // The device's read-back is TOP-first RGBA already; the preview background is composited into + // RGB, so it is opaque - the shared seam's Opaque path ignores the alpha bytes (no per-frame + // alpha pass) and gives the eventual Android viewport the same conversion for free. + val bitmap = rgbaToImageBitmap(pixels.rgba, pixels.width, pixels.height, RgbaAlphaType.Opaque) + slot.imageState.value = RenderedFrame(bitmap, pending.camera, pending.model) + } + } + + /** + * The content rectangle an area's camera fits: the puppet's rest-pose bounds for a 2D area, or the + * shown surface's rectangle for a UV-editor area (the atlas page, or the source layer's raster), which + * the registry widens to the shown meshes. Takes the kind and content the registry read rather than + * re-reading the slot, so the rectangle is of the surface the camera is filed under. Render thread only + * (reads the renderer's bounds). + * + * @param RenderScene scene The area's kind. + * @param UvSceneContent? uvContent What a UV-editor area shows; null for a puppet area. + * @return ContentBounds The rectangle to fit. + */ + private fun contentBoundsFor(scene: RenderScene, uvContent: UvSceneContent?): ContentBounds = + when (scene) { + RenderScene.Puppet2D -> renderer.contentBounds() + RenderScene.UvScene -> + when (uvContent) { + is UvSceneContent.AtlasPage -> pageContentBounds(uvContent.pageIndex) + is UvSceneContent.SourceLayer -> imageContentBounds(uvContent.image) + null -> pageContentBounds(null) + } + } + + /** + * The source-layer rectangle (0, 0, width, height) for the UV-editor fit, or a unit square when there + * is no layer, matching [pageContentBounds]' fallback so both UV scenes frame the same way. + * + * @param DecodedImage image The layer raster, or null for none. + * @return ContentBounds The layer rectangle, in texel/display units. + */ + private fun imageContentBounds(image: DecodedImage?): ContentBounds = + if (image != null) { + ContentBounds(0f, 0f, image.width.toFloat(), image.height.toFloat()) + } else { + ContentBounds(0f, 0f, 1f, 1f) + } + + /** + * The atlas page rectangle (0, 0, pageWidth, pageHeight) for the UV-editor fit, or a unit square when + * the page is missing (an untextured active drawable) so the fit stays sane and the grid still frames. + * + * @param Int pageIndex The atlas page, or null for none. + * @return ContentBounds The page rectangle, in texel/display units. + */ + private fun pageContentBounds(pageIndex: Int?): ContentBounds { + val page = pageIndex?.let { appliedAtlasBinding.textures.atlases.getOrNull(it) } + return if (page != null) { + ContentBounds(0f, 0f, page.width.toFloat(), page.height.toFloat()) + } else { + ContentBounds(0f, 0f, 1f, 1f) + } + } +} + +/** + * One render-loop tick's model/pages pairing decision. + * + * @property PuppetModel orderModel The model to render this tick (the published one, or the + * previous one while its pages are still in flight). + * @property AtlasPageBinding? applyBinding The binding to apply before the model, or null. + */ +internal class AtlasPairingDecision( + val orderModel: PuppetModel, + val applyBinding: AtlasPageBinding?, +) + +/** + * Decides how the render loop takes up a published model and a published page binding as one + * consistent pair. + * + * The two arrive on independent channels, and on an undo the baseline model would land frames before + * the baseline pages - repacked pixels under baseline coordinates - so an atlas-CHANGING model waits + * until the binding composed for its atlas has arrived, and the loop keeps rendering the previous + * pair. Non-atlas edits pass untouched: their atlas is the applied binding's own instance. Atlas + * comparison is identity first, then equality - the session's baseline short-circuit can publish the + * baseline pages under an equal-but-distinct atlas instance. + * + * Pure and render-thread-agnostic so the hold/apply matrix is testable without a GL context. + * + * @param PuppetModel publishedModel The latest model the UI published. + * @param AtlasPageBinding publishedBinding The latest page binding the UI published. + * @param AtlasPageBinding appliedBinding The binding the renderer currently holds. + * @param PuppetModel? lastModel The model the loop last applied, or null on the first tick. + * @return AtlasPairingDecision What to render and whether to swap pages first. + */ +internal fun resolveAtlasPairing( + publishedModel: PuppetModel, + publishedBinding: AtlasPageBinding, + appliedBinding: AtlasPageBinding, + lastModel: PuppetModel?, +): AtlasPairingDecision { + val bindingMatchesPublished = + publishedBinding.atlas === publishedModel.atlas || publishedBinding.atlas == publishedModel.atlas + val appliedMatchesPublished = + appliedBinding.atlas === publishedModel.atlas || appliedBinding.atlas == publishedModel.atlas + val orderModel = + if (!appliedMatchesPublished && !bindingMatchesPublished) { + // The pages for this model's atlas have not arrived; keep the previous pair. The first + // tick has no previous model to keep, and renders the published one against whatever pages + // exist rather than nothing at all. + lastModel ?: publishedModel + } else { + publishedModel + } + val applyBinding = + if (publishedBinding !== appliedBinding && + (publishedBinding.atlas === orderModel.atlas || publishedBinding.atlas == orderModel.atlas) + ) { + publishedBinding + } else { + null + } + return AtlasPairingDecision(orderModel, applyBinding) +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/ViewportAreaRegistry.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/ViewportAreaRegistry.kt new file mode 100644 index 0000000..4778247 --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/ViewportAreaRegistry.kt @@ -0,0 +1,659 @@ +package org.umamo.editor.desktop.viewport + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import org.umamo.render.ContentBounds +import org.umamo.render.ViewportCamera +import org.umamo.ui.viewport.AreaCameraKey +import org.umamo.ui.viewport.CameraSurface +import org.umamo.ui.viewport.RenderedFrame +import org.umamo.ui.viewport.UvSceneContent +import java.util.concurrent.ConcurrentHashMap + +/** + * Which content an area renders: the posed puppet (2D viewport), or the UV editor's flat surface. + * + * WHICH flat surface - a packed atlas page or a source layer's artwork - is not recorded here. That + * belongs to [AreaSlot.uvContent], which carries the kind together with its payload; splitting it + * across two fields is what let a switch be observed half applied. + */ +internal enum class RenderScene { + Puppet2D, + UvScene, +} + +/** The surface a scene's camera frames, which is what a remembered camera is keyed by beside its area. */ +internal val RenderScene.cameraSurface: CameraSurface + get() = + when (this) { + RenderScene.Puppet2D -> CameraSurface.Viewport + RenderScene.UvScene -> CameraSurface.Uv + } + +/** + * Which flat surface a UV-editor camera frames: one atlas page, or one source layer. A view of one means + * nothing over another - a page of thousands of texels and a layer of a few hundred share only their + * origin - so a UV-editor area keeps a view per surface. + */ +internal sealed interface UvSurfaceId { + /** + * An atlas page, by index. + * + * @property Int? pageIndex The page, or null for the untextured fallback's unit square. + */ + data class Page(val pageIndex: Int?) : UvSurfaceId + + /** + * A source layer, by its key in the document's source-art store. + * + * @property String layerKey The layer's key. + */ + data class Layer(val layerKey: String) : UvSurfaceId +} + +/** The surface this content shows: its identity, never its pixels, so a re-decoded layer is the same surface. */ +internal val UvSceneContent.surfaceId: UvSurfaceId + get() = + when (this) { + is UvSceneContent.AtlasPage -> UvSurfaceId.Page(pageIndex) + is UvSceneContent.SourceLayer -> UvSurfaceId.Layer(layerKey) + } + +/** + * A camera together with the UV surface it frames, published as ONE value so the two cannot tear: a pan on the + * UI thread racing a surface switch on the render thread can lose one update at worst, never file a view under + * the wrong surface. + * + * @property ViewportCamera camera The pan / zoom. + * @property UvSurfaceId? surface The UV surface it frames, or null for a puppet area's view of the world. + */ +internal data class FramedCamera(val camera: ViewportCamera, val surface: UvSurfaceId?) + +/** + * What a UV-editor view is remembered under for the session: one area showing one surface. + * + * @property String areaId The hosting leaf's area id. + * @property UvSurfaceId surface The page or layer the view frames. + */ +internal data class AreaUvSurfaceKey(val areaId: String, val surface: UvSurfaceId) + +/** + * The rectangle a UV-editor fit frames: the shown surface, widened to take in every shown mesh that reaches + * past it. A placement moved off the page carries its islands with it, and a fit that only knew the page + * would frame everything but the thing just moved. + * + * @param ContentBounds surfaceBounds The shown surface's rectangle. + * @param ContentBounds? islandExtent The shown meshes' bounds, or null for none. + * @return ContentBounds The union of the two. + */ +internal fun uvFitBounds(surfaceBounds: ContentBounds, islandExtent: ContentBounds?): ContentBounds { + if (islandExtent == null) { + return surfaceBounds + } + val minX = minOf(surfaceBounds.minX, islandExtent.minX) + val minY = minOf(surfaceBounds.minY, islandExtent.minY) + val maxX = maxOf(surfaceBounds.minX + surfaceBounds.width, islandExtent.minX + islandExtent.width) + val maxY = maxOf(surfaceBounds.minY + surfaceBounds.height, islandExtent.minY + islandExtent.height) + return ContentBounds(minX, minY, maxX - minX, maxY - minY) +} + +/** The camera and pixel size of a registered area, resolved for a CPU pick. Null-camera areas do not appear. */ +internal data class AreaView(val camera: ViewportCamera, val width: Int, val height: Int) + +/** + * Per-area render state, shared between the UI thread ([ViewportAreaRegistry]) and the render thread + * ([OffscreenRenderEngine]). Field-ownership contract: + * + * - The @Volatile fields are written by the UI thread and read by the render thread (a volatile publish of + * immutable values or plain scalars): scene, uvContent, uvIslandExtent, width, height, refitRequested. + * framing is written by both: the UI thread's pan / zoom and the render thread's establish, each + * replacing the whole value. + * - imageState / cameraState are thread-safe StateFlows; either thread may set them. + * - refCount is touched only on the UI thread (register/unregister run as composition effects). + * - The remaining plain fields (inFlight, rendered*, *RenderBumpDone) are render-thread-only bookkeeping. + */ +internal class AreaSlot { + // Whether this area renders the posed puppet or the UV editor's flat surface. Set by whichever + // registration claimed the slot last (register vs registerUvScene): switching an area's editor type in + // place registers the new space before the old one releases, so a live slot CAN change kind. WHICH + // flat surface is carried by uvContent below. UI thread writes, render thread reads - a volatile publish. + @Volatile + var scene: RenderScene = RenderScene.Puppet2D + + // What a UV-editor area draws, as ONE value: which kind and its payload inseparably. + // + // Publishing the kind and the payload as separate fields would let the render thread observe a + // half-applied switch - the old kind against the new payload - which reads as a legitimately stale + // frame, renders grid-only, and then stamps itself fresh against the payload that landed meanwhile. + // The area would sit on an empty grid until a pan or resize happened to dislodge it, and nothing + // would look wrong anywhere. A single reference cannot tear, so the switch is all-or-nothing. + // + // Null for a puppet area, which has no UV surface. + @Volatile + var uvContent: UvSceneContent? = null + + // The display-space bounds of the meshes a UV-editor area shows, which its fit widens the surface to take + // in. Read only when a fit runs, so an edit that moves an island re-renders nothing. Written BEFORE + // uvContent, and read after it: a render thread that sees new content also sees the extent measured over it. + @Volatile + var uvIslandExtent: ContentBounds? = null + + @Volatile + var width: Int = 0 + + @Volatile + var height: Int = 0 + val imageState = MutableStateFlow(null) + + // The per-area camera (pan/zoom) with the UV surface it frames. null until the render thread computes the + // initial fit (it needs the area size + content bounds); thereafter each pan / zoom swaps in a new immutable + // value (a volatile publish), and the render thread swaps it again when a UV area's shown surface is no + // longer the one it frames. cameraState mirrors the camera for the overlay readout. + @Volatile + var framing: FramedCamera? = null + + /** The area's current pan / zoom, or null before the first fit. */ + val camera: ViewportCamera? + get() = framing?.camera + + // Set by the Fit command (UI thread), cleared by the render thread, which then recomputes a fresh fit + // (ignoring any remembered camera). A flag rather than camera=null so the old view shows until the refit + // lands, and so refit beats the workspace-restore path. + @Volatile + var refitRequested: Boolean = false + val cameraState = MutableStateFlow(null) + + // How many live composables currently hold this area id. A leaf can be torn down and rebuilt for the SAME + // id during a tree collapse (closing a split sibling), so register(new) and unregister(old) briefly + // overlap; the slot is dropped only when this returns to 0. Touched only on the Compose UI thread. + var refCount: Int = 0 + + // Render-thread-only bookkeeping (no synchronization needed). + var inFlight: Boolean = false + var renderedWidth: Int = -1 + var renderedHeight: Int = -1 + var renderedParamsVersion: Long = -1 + var renderedCamera: ViewportCamera? = null + var puppetRenderBumpDone: Long = -1 + var atlasRenderBumpDone: Long = -1 + var renderedUvContent: UvSceneContent? = null + + // Render-thread-only resize-throttle bookkeeping: the last size the loop observed, when it last + // changed, when the last resize-driven render was issued (all System.nanoTime), and the + // supersample scale of the last issued render (a 1x interactive frame stays size-stale so the + // settle pass re-renders it at full quality). + var observedWidth: Int = 0 + var observedHeight: Int = 0 + var sizeChangedNanos: Long = 0L + var resizeRenderNanos: Long = 0L + var renderedScale: Int = -1 +} + +/** + * Owns the registered viewport areas and their cameras. The register/resize/camera-navigation surface runs + * on the UI thread; [OffscreenRenderEngine] iterates the same [areas] map on the render thread and calls + * [establishCamera] to fit newly-sized areas. The shared state is safe across the two threads: the slot map + * is a ConcurrentHashMap, per-area hand-off fields are @Volatile, and the camera flows are StateFlows. + */ +internal class ViewportAreaRegistry { + /** The registered areas, keyed by stable area id. Iterated by the render engine; mutated by the UI thread. */ + val areas = ConcurrentHashMap() + + // Cameras remembered by area AND surface beyond a slot's composable life, so switching workspaces (which + // disposes the inactive workspace's viewports -> drops their slots) and returning restores the pan/zoom + // instead of refitting. Keyed by the surface too because a view of the puppet's world means nothing over + // a texture's pixels: an area switched between the 2D viewport and the UV editor keeps one view of each. + // Area ids are minted once and never reused, so entries never collide; the map grows only by areas ever + // shown (a few floats each) and is not evicted (session-bounded, negligible cost). A UV editor's entry is + // the view of the page or layer it shows now - the one a save writes. + private val rememberedCameras = ConcurrentHashMap() + + // A UV-editor area's view of EACH page and layer it has shown, so switching to one it has left brings back + // that view and one it has never shown is fitted: a page's pan and zoom over a layer a fraction of its size + // lands the layer tiny and in a corner. Session state only - never in cameras(), so it never reaches a + // save - and dropped with the engine, so a new document starts over. Bounded the way rememberedCameras is. + private val uvSurfaceCameras = ConcurrentHashMap() + + // The areas that have shown a UV surface this session. Until an area has, its remembered UV view can only + // be the one the document was saved with, which belongs to whichever surface the area opens on. + private val uvShownAreaIds = ConcurrentHashMap.newKeySet() + + /** + * Every remembered camera, by area and surface - the areas shown now and the ones a workspace switch put away. + * + * @return Map A copy of the remembered cameras. + */ + fun cameras(): Map = HashMap(rememberedCameras) + + /** + * Remembers [cameras] as though each area had been shown with it, so an area registering for the first time + * opens on its saved view rather than a fit. Meant for the moment the engine is built, before any area + * registers; an area that already has a camera keeps it. + * + * @param Map cameras The saved cameras, by area and surface. + */ + fun seedCameras(cameras: Map) { + for ((cameraKey, camera) in cameras) { + rememberedCameras.putIfAbsent(cameraKey, camera) + } + } + + // Zoom increments in percentage points, fed from settings (viewport.zoomStep*Percent): the fine step is + // one wheel notch / keyboard press, the coarse step is the Shift-held variant. Defaults mirror + // defaultSettings.json. UI thread only. + @Volatile + var zoomStepPercent: Float = 1f + + @Volatile + var zoomStepCoarsePercent: Float = 5f + + /** + * Registers a viewport area and returns the flow of images to display for it. Re-registering an id that + * is still live (the same area's leaf rebuilt during a tree collapse - see [AreaSlot.refCount]) returns + * the existing slot and its last image, so the surviving viewport keeps rendering instead of being + * orphaned. + * + * @param String areaId The hosting area's stable id. + * @return StateFlow The area's image stream (null until the first render completes). + */ + fun register(areaId: String): StateFlow { + val slot = areas.getOrPut(areaId) { AreaSlot() } + claim(slot, RenderScene.Puppet2D, content = null, islandExtent = null) + slot.refCount++ + return slot.imageState + } + + /** + * Registers a UV-editor area (the flat image underlay) and returns its image flow. + * + * @param String areaId The hosting area's stable id. + * @param UvSceneContent content What the area draws. + * @param ContentBounds? islandExtent The shown meshes' display-space bounds, or null for none. + * @return StateFlow The area's image stream (null until the first render completes). + */ + fun registerUvScene(areaId: String, content: UvSceneContent, islandExtent: ContentBounds?): StateFlow { + val slot = areas.getOrPut(areaId) { AreaSlot() } + claim(slot, RenderScene.UvScene, content, islandExtent) + slot.refCount++ + return slot.imageState + } + + /** + * Makes [slot] an area of [scene], whatever it was. + * + * A slot outlives the space that registered it whenever the next space registers first - and switching an + * area's editor type in place does exactly that, the new space composing before the old one is disposed. The + * slot then holds the OLD kind, its surface, and its camera, so a registration has to claim all three or the + * engine keeps drawing the UV page under a 2D viewport's gizmos (and frames the puppet with a page's pan and + * zoom). A registration of the same kind - a leaf rebuilt during a tree collapse - changes nothing here, so + * the surviving viewport keeps its view. + * + * Order matters to the render thread, which walks the slot map and can see this slot mid-claim. Becoming a + * UV scene, the content goes first and the kind second; becoming a puppet, the kind goes first and the + * content is cleared second - either way the area never reads as a UV scene with nothing to draw. The camera + * goes LAST: dropped before the kind, the render thread could re-establish the old surface's view in the gap + * and keep it. Dropped after, the worst it can do is render one frame of the new surface through the old + * camera, which the fresh camera then makes stale. + * + * @param AreaSlot slot The slot to claim. + * @param RenderScene scene The kind of area registering. + * @param UvSceneContent? content What a UV area draws; null for a puppet area. + * @param ContentBounds? islandExtent The shown meshes' bounds a UV area's fit takes in; null for a puppet area. + */ + private fun claim(slot: AreaSlot, scene: RenderScene, content: UvSceneContent?, islandExtent: ContentBounds?) { + val kindChanged = slot.scene != scene + when (scene) { + RenderScene.UvScene -> { + slot.uvIslandExtent = islandExtent + slot.uvContent = content + slot.scene = scene + } + + RenderScene.Puppet2D -> { + slot.scene = scene + slot.uvContent = null + slot.uvIslandExtent = null + } + } + if (kindChanged) { + // The old surface's view stays remembered under its own key for the day the area switches back; this + // one is re-established from the new surface's remembered view, or a fit. The last frame goes too: + // it shows the old surface, and the new space's overlays would be drawn over it until the next lands. + slot.framing = null + slot.cameraState.value = null + slot.imageState.value = null + } + } + + /** + * Retargets what an already-registered UV-editor area draws, and the mesh extent its fit takes in. A no-op + * for an unregistered area or a puppet (2D) area - only a registration moves an area between the puppet and + * the UV family, and this moves the content within the UV one. + * + * A switch to another page or layer changes no camera here: the render thread sees that the surface shown is + * no longer the one the camera frames and swaps the view as it establishes the next frame, so the new + * surface's first frame already renders through its own view (see [establishCamera]). + * + * @param String areaId The UV-editor area to retarget. + * @param UvSceneContent content The new content to draw. + * @param ContentBounds? islandExtent The shown meshes' display-space bounds, or null for none. + */ + fun setUvSceneContent(areaId: String, content: UvSceneContent, islandExtent: ContentBounds?) { + val slot = areas[areaId] ?: return + if (slot.scene == RenderScene.Puppet2D) { + return + } + applyUvContent(slot, content, islandExtent) + } + + /** + * Publishes one UV content choice onto a slot, kind and payload inseparably, with the mesh extent measured + * over it. + * + * The content is one volatile store of one immutable value, which is what makes the switch atomic - see + * [AreaSlot.uvContent] for what publishing them separately would cost. The extent goes first, so a render + * thread that sees the new content also sees the extent that belongs to it. + * + * @param AreaSlot slot The slot to retarget. + * @param UvSceneContent content What the area draws. + * @param ContentBounds? islandExtent The shown meshes' display-space bounds, or null for none. + */ + private fun applyUvContent(slot: AreaSlot, content: UvSceneContent, islandExtent: ContentBounds?) { + slot.uvIslandExtent = islandExtent + slot.uvContent = content + } + + /** + * Releases one hold on an area; the slot is dropped only when the last holder leaves (ref-count to zero). + * This guards the tree-collapse case: closing one split sibling rebuilds the surviving area's leaf under a + * fresh composition node, so its [register] runs BEFORE the old leaf's unregister - a plain remove here + * would delete the slot the rebuilt viewport just bound to, freezing it at a stale (stretched) frame. Any + * read-back already in flight for a truly-dropped slot still completes and is discarded when collected. + * + * @param String areaId The area id to release. + */ + fun unregister(areaId: String) { + val slot = areas[areaId] ?: return + slot.refCount-- + if (slot.refCount <= 0) { + areas.remove(areaId) + } + } + + /** + * Returns the flow of the area's current camera, for the overlay zoom readout. The viewport composable + * registers the area before reading this, so it attaches to the existing slot. + * + * @param String areaId The area id. + * @return StateFlow The area's camera stream (null until the first fit). + */ + fun cameraFlow(areaId: String): StateFlow = + areas.getOrPut(areaId) { AreaSlot() }.cameraState + + /** + * Updates an area's requested pixel size; the render thread re-renders it at the new size. A no-op for an + * unregistered id - registration always precedes the size report, so resize must never resurrect a slot + * the ref-count has already dropped (that would leak a zero-ref slot the render loop renders forever). + * + * @param String areaId The area id. + * @param Int width The new width in pixels. + * @param Int height The new height in pixels. + */ + fun resize(areaId: String, width: Int, height: Int) { + val slot = areas[areaId] ?: return + slot.width = width + slot.height = height + } + + /** + * Pans the area's camera by a screen-pixel drag (grab style). No-op before the initial fit exists. + * + * @param String areaId The area id. + * @param Float deltaXpx Horizontal drag in pixels. + * @param Float deltaYpx Vertical drag in pixels. + */ + fun pan(areaId: String, deltaXpx: Float, deltaYpx: Float) { + updateCamera(areaId) { camera -> camera.panByScreen(deltaXpx, deltaYpx) } + } + + /** + * Zooms the area's camera about a cursor position (wheel zoom) by one configured step, pinning the world + * point under the cursor. The step (fine or coarse Shift step) comes from settings. + * + * @param String areaId The area id. + * @param Boolean zoomIn True to zoom in, false to zoom out. + * @param Boolean coarse Use the coarse (Shift) step. + * @param Float cursorXpx Cursor X in pixels. + * @param Float cursorYpx Cursor Y in pixels. + */ + fun zoomAtCursor(areaId: String, zoomIn: Boolean, coarse: Boolean, cursorXpx: Float, cursorYpx: Float) { + val slot = areas[areaId] ?: return + val width = slot.width + val height = slot.height + val step = stepFor(coarse) + val deltaPercent = if (zoomIn) step else -step + updateCamera(areaId) { camera -> + camera.zoomAtCursorByPercent( + deltaPercent, + step, + cursorXpx, + cursorYpx, + width, + height, + ) + } + } + + /** + * Frames a screen-pixel rectangle in the area's camera (Zoom Region / Shift+B): the box fills the + * viewport, letterboxed on the looser axis. A no-op before the first fit or when the area has no size yet. + * + * @param String areaId The area id. + * @param Float leftPx One horizontal box edge in viewport pixels. + * @param Float topPx One vertical box edge in viewport pixels. + * @param Float rightPx The other horizontal box edge in viewport pixels. + * @param Float bottomPx The other vertical box edge in viewport pixels. + */ + fun zoomToRegion(areaId: String, leftPx: Float, topPx: Float, rightPx: Float, bottomPx: Float) { + val slot = areas[areaId] ?: return + val width = slot.width + val height = slot.height + if (width <= 0 || height <= 0) { + return + } + updateCamera(areaId) { camera -> camera.framingScreenRect(leftPx, topPx, rightPx, bottomPx, width, height) } + } + + /** + * Zooms the area's camera about its center (keyboard zoom in/out) by one configured step. + * + * @param String areaId The area id. + * @param Boolean zoomIn True to zoom in, false to zoom out. + * @param Boolean coarse Use the coarse (Shift) step. + */ + fun zoomCentered(areaId: String, zoomIn: Boolean, coarse: Boolean) { + val step = stepFor(coarse) + val deltaPercent = if (zoomIn) step else -step + updateCamera(areaId) { camera -> camera.zoomedByPercent(deltaPercent, step) } + } + + /** + * Sets the area's camera to true 1:1 about its center (actual size / 100%). + * + * @param String areaId The area id. + */ + fun actualSize(areaId: String) { + updateCamera(areaId) { camera -> camera.withActualSize() } + } + + /** + * Refits the area's camera to the content on the next render tick by flagging it - the render thread, + * which owns the content bounds and the current size, recomputes the fit in [establishCamera]. + * + * @param String areaId The area id. + */ + fun fit(areaId: String) { + val slot = areas[areaId] ?: return + slot.refitRequested = true + } + + /** + * Fits a world-space rectangle inside the area, centerd (the Frame Selected camera move). A no-op before + * the first fit or when the area has no size yet. + * + * @param String areaId The area id. + * @param Float minX The rectangle's minimum world x. + * @param Float minZ The rectangle's minimum world z (up). + * @param Float maxX The rectangle's maximum world x. + * @param Float maxZ The rectangle's maximum world z (up). + */ + fun fitWorldRect(areaId: String, minX: Float, minZ: Float, maxX: Float, maxZ: Float) { + val slot = areas[areaId] ?: return + val width = slot.width + val height = slot.height + if (width <= 0 || height <= 0 || maxX < minX || maxZ < minZ) { + return + } + // A degenerate rect (a single vertex) still frames: ContentBounds spans are clamped to >= 1 world unit + // by the fit, so the camera centers on the point at a sane zoom. + updateCamera(areaId) { + ViewportCamera.fit(ContentBounds(minX, minZ, maxX - minX, maxZ - minZ), width, height) + } + } + + /** + * The camera and size of an area for a CPU pick, or null when the area is unregistered, unsized, or has + * no camera yet (before the first fit). + * + * @param String areaId The area id. + * @return AreaView The area's camera and pixel size, or null. + */ + fun viewFor(areaId: String): AreaView? { + val slot = areas[areaId] ?: return null + val camera = slot.camera ?: return null + return AreaView(camera, slot.width, slot.height) + } + + /** + * Render-thread: ensures the slot has a camera for what it shows, establishing or refitting it now that the + * size is known. A pending refit forces a fresh fit. Otherwise a freshly-(re)registered area restores its + * remembered camera (so workspace switches preserve pan/zoom), and a UV-editor area whose shown page or + * layer is no longer the one its camera frames swaps to the view it left that surface with - either falling + * back to a fit the first time that surface is shown. The content bounds are resolved lazily (only when a + * fit is actually needed) via [contentBounds]; a UV-editor fit is widened to the shown meshes' extent. + * + * The kind and the content are read once, up front: the fit, the recall, and the record all have to be about + * the same surface, and the UI thread can retarget the slot at any moment. A retarget that lands after the + * read leaves a camera framing a surface no longer shown, which the next call swaps in turn. + * + * @param AreaSlot slot The area being established. + * @param String areaId The area id. + * @param Int width The current area width. + * @param Int height The current area height. + * @param Function contentBounds Supplies the rectangle of the scene and content it is handed, evaluated only + * when a fit is needed. + * @return ViewportCamera The area's current camera. + */ + fun establishCamera( + slot: AreaSlot, + areaId: String, + width: Int, + height: Int, + contentBounds: (RenderScene, UvSceneContent?) -> ContentBounds, + ): ViewportCamera { + val scene = slot.scene + val content = slot.uvContent + val shownSurface = + when (scene) { + RenderScene.Puppet2D -> null + RenderScene.UvScene -> content?.surfaceId ?: UvSurfaceId.Page(null) + } + val framing = slot.framing + val refit = slot.refitRequested + if (framing != null && !refit && framing.surface == shownSurface) { + return framing.camera + } + val recalled = if (refit) null else recallCamera(areaId, scene, shownSurface) + val camera = + recalled ?: run { + val sceneBounds = contentBounds(scene, content) + // Read after the content: the UI thread writes the extent first, so it belongs to this content. + val fitBounds = + when (scene) { + RenderScene.Puppet2D -> sceneBounds + RenderScene.UvScene -> uvFitBounds(sceneBounds, slot.uvIslandExtent) + } + ViewportCamera.fit(fitBounds, width, height) + } + slot.refitRequested = false + publishCamera(slot, areaId, FramedCamera(camera, shownSurface)) + return camera + } + + /** + * The view an area had of a surface, for an area establishing one without a refit, or null when it has none + * and the surface is fitted. + * + * A UV-editor area takes its own view of that page or layer first. The area's whole-UV view - what a saved + * document seeds - stands in only while the area has shown no UV surface this session: until then it can only + * be the saved view, which belongs to whatever surface the area opens on. After that it is the last surface's + * view, and a different surface fits rather than inheriting it. + * + * @param String areaId The area id. + * @param RenderScene scene The area's kind. + * @param UvSurfaceId? surface The UV surface shown, or null for a puppet area. + * @return ViewportCamera? The view to restore, or null to fit. + */ + private fun recallCamera(areaId: String, scene: RenderScene, surface: UvSurfaceId?): ViewportCamera? { + if (surface == null) { + return rememberedCameras[AreaCameraKey(areaId, scene.cameraSurface)] + } + uvSurfaceCameras[AreaUvSurfaceKey(areaId, surface)]?.let { remembered -> + return remembered + } + if (areaId in uvShownAreaIds) { + return null + } + return rememberedCameras[AreaCameraKey(areaId, CameraSurface.Uv)] + } + + /** + * Makes [framing] the slot's camera and remembers it: under the area and its surface kind (what a save writes + * and a workspace switch restores) and, for a UV-editor view, under the page or layer it frames. Keyed off the + * framing's own surface rather than the slot's current content, so a view is always filed with the surface it + * was taken of. + * + * @param AreaSlot slot The area's slot. + * @param String areaId The area id. + * @param FramedCamera framing The camera and the surface it frames. + */ + private fun publishCamera(slot: AreaSlot, areaId: String, framing: FramedCamera) { + slot.framing = framing + slot.cameraState.value = framing.camera + val surface = framing.surface + if (surface == null) { + rememberedCameras[AreaCameraKey(areaId, CameraSurface.Viewport)] = framing.camera + } else { + rememberedCameras[AreaCameraKey(areaId, CameraSurface.Uv)] = framing.camera + uvSurfaceCameras[AreaUvSurfaceKey(areaId, surface)] = framing.camera + uvShownAreaIds.add(areaId) + } + } + + /** The zoom step in percentage points for this notch/press: the coarse (Shift) step or the fine step. */ + private fun stepFor(coarse: Boolean): Float = if (coarse) zoomStepCoarsePercent else zoomStepPercent + + /** + * Applies [transform] to the area's current camera and publishes the result, still framing the surface it + * framed. No-op before the initial fit (there is nothing to transform until the first frame establishes the + * view). + * + * @param String areaId The area id. + * @param Function transform Maps the current camera to its replacement. + */ + private fun updateCamera(areaId: String, transform: (ViewportCamera) -> ViewportCamera) { + val slot = areas[areaId] ?: return + val framing = slot.framing ?: return + publishCamera(slot, areaId, framing.copy(camera = transform(framing.camera))) + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/ViewportPicker.kt b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/ViewportPicker.kt new file mode 100644 index 0000000..635d22a --- /dev/null +++ b/app/desktop/src/jvmMain/kotlin/org/umamo/editor/desktop/viewport/ViewportPicker.kt @@ -0,0 +1,240 @@ +package org.umamo.editor.desktop.viewport + +import androidx.compose.ui.graphics.ImageBitmap +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.PickCandidate +import org.umamo.render.pick.drawableCentroids +import org.umamo.render.pick.pickAllDrawables +import org.umamo.render.pick.pickDrawable +import org.umamo.render.pick.screenToWorldX +import org.umamo.render.pick.screenToWorldZ +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.atlasKeyByDrawable +import org.umamo.runtime.model.drawableNameByDrawable +import org.umamo.runtime.model.partNameByDrawable +import org.umamo.runtime.model.pickableIndicesByDrawable +import org.umamo.runtime.model.pickableUvsByDrawable +import org.umamo.ui.model.DrawableThumbnailProvider +import org.umamo.ui.model.DrawableThumbnailer + +/** + * CPU-side hit-testing and art previews for the viewport, over the current deformed pose. Runs entirely on + * the UI thread and never touches GL: it reuses the renderer's pure-CPU pick geometry (a snapshot the render + * thread produces) and its resolved draw order, and the retained CPU atlas pixels for the alpha gate. The + * facade resolves each area's camera and size and forwards them here, so this class is area-agnostic. + * + * The model-derived lookup maps (pick indices / UVs, atlas keys, part labels) and the thumbnail provider are + * rebuilt by [updateModel] so session-created drawables (a duplicate's fresh ".001" id) and visibility edits + * stay pickable, sampleable, and labeled - maps frozen at construction would leave a duplicate unpickable. + * + * ビューポートの CPU ヒットテストとアートプレビュー。UI スレッドのみ、GL 不使用。 + * + * @property PuppetRenderer renderer The renderer, for its pure-CPU pickGeometry() and drawnOrder(). + * @property PuppetTextures textures The atlas pages, for the alpha gate and page sizes. + */ +internal class ViewportPicker( + private val renderer: PuppetRenderer, + // var: the session swaps the page set on a repack, and the alpha gate must sample the pixels the + // GPU is showing - see setTextures. + private var textures: PuppetTextures, + model: PuppetModel, +) { + // Per-drawable triangle indices for hit-testing, restricted to the drawables actually shown (the + // Parts-panel eyeball cascade) and to those carrying a triangle mesh. Picking iterates the pose's + // deformed positions and looks indices up here, so unshown / mesh-less drawables are never hit. + private var pickableIndices: Map = model.pickableIndicesByDrawable() + + // Per-drawable UVs (full-atlas [0,1]) for the same pickable set, so picking can interpolate the hit + // point's UV and sample the atlas alpha (rejecting clicks on a mesh's transparent triangle overhang). + private var pickableUvs: Map = model.pickableUvsByDrawable() + + // Drawable id -> owning part name, for the overlap-picker row labels. + private var partNameByDrawableId: Map = model.partNameByDrawable() + + // Drawable id -> its own name, the other half of an overlap-picker row label. + private var drawableNameByDrawableId: Map = model.drawableNameByDrawable() + + // Drawable id -> atlas lookup key: the source-format id the atlas map is keyed by, resolved through + // textureSourceId so a duplicate samples its SOURCE's texels for the pick alpha gate. + private var atlasKeyByDrawableId: Map = model.atlasKeyByDrawable() + + // Art-mesh previews for the overlap picker (the same provider the Outliner hover uses). Pure CPU over + // the immutable atlas bytes, so it is built once and shared - a single cache across both consumers. + private val thumbnailer = DrawableThumbnailer(model, textures) + + /** + * Swaps the atlas page set after a repack (or its undo), so the alpha gate and the thumbnails read + * the pixels the viewport is showing rather than the set the picker was built over. + * + * @param PuppetTextures next The new page set. + */ + fun setTextures(next: PuppetTextures) { + if (next === textures) { + return + } + textures = next + thumbnailer.setTextures(next) + } + + /** + * Rebuilds the model-derived lookup maps and the thumbnail provider after a committed edit or undo, so + * session-created drawables and visibility edits stay pickable, sampleable, and labeled. + * + * @param PuppetModel model The current model. + */ + fun updateModel(model: PuppetModel) { + pickableIndices = model.pickableIndicesByDrawable() + pickableUvs = model.pickableUvsByDrawable() + partNameByDrawableId = model.partNameByDrawable() + drawableNameByDrawableId = model.drawableNameByDrawable() + atlasKeyByDrawableId = model.atlasKeyByDrawable() + thumbnailer.updateModel(model) + } + + /** + * Hit-tests a viewport pixel against the current deformed pose and returns the FRONT-MOST opaque drawable + * under it, or null when the click misses or no pose is ready yet. Restricted to shown, meshed drawables; + * front/back uses the renderer's resolved draw order, and the transparent triangle overhang is rejected + * by the atlas-alpha gate. + * + * @param ViewportCamera camera The area's camera (screen-to-world inverse). + * @param Int width The area width in pixels. + * @param Int height The area height in pixels. + * @param Float cursorXpx Cursor X in pixels (top-left origin). + * @param Float cursorYpx Cursor Y in pixels (top-left origin). + * @return DrawableId The hit drawable, or null on a miss. + */ + fun pickAt(camera: ViewportCamera, width: Int, height: Int, cursorXpx: Float, cursorYpx: Float): DrawableId? { + if (width <= 0 || height <= 0) { + return null + } + val geometry = renderer.pickGeometry() ?: return null + // Screen (y-down) to world (y-up), the inverse of the camera's worldToNdc - see ScreenSpacePick. + val worldX = screenToWorldX(cursorXpx, camera, width) + val worldZ = screenToWorldZ(cursorYpx, camera, height) + return pickDrawable( + worldX, + worldZ, + geometry.worldPositions, + pickableIndices, + pickableUvs, + frontRankMap(), + ::sampleTexelAlpha, + ) + } + + /** + * All opaque drawables under a viewport pixel, FRONT-TO-BACK with each one's centrality - for the + * Alt-click overlap-picker popup. Same screen-to-world, hit, and alpha gate as [pickAt]. + * + * @param ViewportCamera camera The area's camera. + * @param Int width The area width in pixels. + * @param Int height The area height in pixels. + * @param Float cursorXpx Cursor X in pixels (top-left origin). + * @param Float cursorYpx Cursor Y in pixels (top-left origin). + * @return List The opaque candidates, front-to-back. + */ + fun pickAllAt( + camera: ViewportCamera, + width: Int, + height: Int, + cursorXpx: Float, + cursorYpx: Float, + ): List { + if (width <= 0 || height <= 0) { + return emptyList() + } + val geometry = renderer.pickGeometry() ?: return emptyList() + val worldX = screenToWorldX(cursorXpx, camera, width) + val worldZ = screenToWorldZ(cursorYpx, camera, height) + return pickAllDrawables( + worldX, + worldZ, + geometry.worldPositions, + pickableIndices, + pickableUvs, + frontRankMap(), + ::atlasSizeOf, + ::sampleTexelAlpha, + ) + } + + /** + * Every visible drawable's world-space centroid at the current pose, for Object-mode region select. Reads + * the same posed pick geometry as [pickAt] and reduces each drawable to its centroid; empty before the + * first frame's geometry lands. Area-independent - the caller projects with its camera. + * + * @return Map The per-drawable [x, y] world centroid. + */ + fun drawableWorldCentroids(): Map { + val geometry = renderer.pickGeometry() ?: return emptyMap() + return drawableCentroids(geometry.worldPositions) + } + + /** + * A small preview of a drawable's art for the overlap-picker popup, delegated to the shared thumbnailer + * (the same provider the Outliner hover uses). Returns null for an untextured or mesh-less drawable. + * + * @param DrawableId id The drawable to preview. + * @return ImageBitmap The cropped preview, or null when untextured or mesh-less. + */ + fun thumbnailFor(id: DrawableId): ImageBitmap? = thumbnailer.thumbnailFor(id) + + /** The shared art-mesh thumbnail provider, exposed so the host can wire it to the Outliner hover preview. */ + fun thumbnails(): DrawableThumbnailProvider = thumbnailer + + /** + * The name of the part a drawable belongs to, for the overlap-picker row labels, or null when the + * drawable sits at the root with no owning part. + * + * @param DrawableId id The drawable to look up. + * @return String The owning part's name, or null. + */ + fun partNameFor(id: DrawableId): String? = partNameByDrawableId[id] + + /** + * A drawable's own display name, for the overlap-picker row labels, or null when it is not pickable + * in the current model. + * + * @param DrawableId id The drawable to look up. + * @return String The drawable's name, or null. + */ + fun drawableNameFor(id: DrawableId): String? = drawableNameByDrawableId[id] + + /** The renderer's resolved back-to-front draw list as a front-rank map (higher index = more front). */ + private fun frontRankMap(): Map = + renderer.drawnOrder().withIndex().associate { (index, id) -> id to index.toFloat() } + + /** The drawable's atlas page size (width, height) in texels, or null when it is untextured. */ + private fun atlasSizeOf(id: DrawableId): Pair? = + textures.atlasIndexByDrawableId[atlasKeyByDrawableId[id] ?: id.raw]?.let { atlasIndex -> + textures.atlases.getOrNull(atlasIndex)?.let { image -> image.width to image.height } + } + + /** + * The atlas-texel alpha (0..1) for a drawable at a full-atlas (u, v), or 1f when the drawable is + * untextured (a flat draw color, treated as fully opaque). Reads the retained CPU atlas pixels; the + * alpha byte is the coverage whether or not the atlas is premultiplied, so no un-premultiply is needed. + * A point off the page is transparent, as the renderer draws it: a mesh overhangs its art, and when the + * page is a single model image that overhang runs past the page itself. + * + * @param DrawableId id The drawable. + * @param Float u The full-atlas U. + * @param Float v The full-atlas V. + * @return Float The texel alpha, 0..1. + */ + private fun sampleTexelAlpha(id: DrawableId, u: Float, v: Float): Float { + val atlasIndex = textures.atlasIndexByDrawableId[atlasKeyByDrawableId[id] ?: id.raw] ?: return 1f + val image = textures.atlases.getOrNull(atlasIndex) ?: return 1f + if (!(u >= 0f && u < 1f && v >= 0f && v < 1f)) { + return 0f + } + val px = (u * image.width).toInt().coerceAtMost(image.width - 1) + val py = (v * image.height).toInt().coerceAtMost(image.height - 1) + val alpha = image.rgba[(py * image.width + px) * 4 + 3].toInt() and 0xFF + return alpha / 255f + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/packaging/OsAssociationFilesTest.kt b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/packaging/OsAssociationFilesTest.kt new file mode 100644 index 0000000..aa5c8a3 --- /dev/null +++ b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/packaging/OsAssociationFilesTest.kt @@ -0,0 +1,181 @@ +package org.umamo.editor.desktop.packaging + +import org.umamo.editor.desktop.isOpenableDocumentPath +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriterInfo +import org.w3c.dom.Element +import java.io.ByteArrayOutputStream +import java.io.File +import java.util.zip.CRC32 +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import javax.xml.parsers.DocumentBuilderFactory +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Holds every operating-system registration of the `.uma` type to the codec. The type is declared in four places + * no compiler connects - the freedesktop MIME entry, the desktop entry, the desktop package's build script, and the + * Android manifest - and a registration that names another string, or a magic rule that reads another offset, + * fails silently: the file manager just stops recognising the file. The magic is not compared to a table here, + * it is EVALUATED against the bytes the writer really produces (docs/format/UMA.md § 2). + */ +class OsAssociationFilesTest { + /** Gradle runs a module's tests from the module directory, which is what these paths are relative to. */ + private val mimeEntry = File("resources/linux/umamo-uma.xml") + private val desktopEntry = File("resources/linux/umamo.desktop") + private val buildScript = File("build.gradle.kts") + private val androidManifest = File("../android/src/main/AndroidManifest.xml") + + /** One `match` rule of a shared-mime-info magic: a string expected at an offset, and the rules nested under it. */ + private class MagicRule(val offset: Int, val expected: ByteArray, val nested: List) + + /** + * The bytes a shared-mime-info `string` value denotes: C-style escapes, of which the entry uses the octal form. + * + * @param String value The attribute's text. + * @return ByteArray The bytes to find. + */ + private fun magicBytesOf(value: String): ByteArray { + val bytes = ByteArrayOutputStream() + var position = 0 + while (position < value.length) { + if (value[position] == '\\' && position + 3 < value.length && value.substring(position + 1, position + 4).all { digit -> digit in '0'..'7' }) { + bytes.write(value.substring(position + 1, position + 4).toInt(8)) + position += 4 + } else { + bytes.write(value[position].code) + position++ + } + } + return bytes.toByteArray() + } + + /** + * The `match` rules directly under [parent], each with its own nested rules. + * + * @param Element parent A `magic` or `match` element. + * @return List The rules. + */ + private fun rulesUnder(parent: Element): List { + val rules = ArrayList() + val children = parent.childNodes + for (childIndex in 0 until children.length) { + val child = children.item(childIndex) as? Element ?: continue + if (child.tagName == "match") { + assertEquals("string", child.getAttribute("type"), "the matcher below only evaluates string rules") + rules += MagicRule(child.getAttribute("offset").toInt(), magicBytesOf(child.getAttribute("value")), rulesUnder(child)) + } + } + return rules + } + + /** + * Whether [content] satisfies any of [rules]: a rule holds when its bytes sit at its offset AND, when it has + * nested rules, one of those holds too - the shared MIME database's own semantics. + * + * @param ByteArray content The file's bytes. + * @param List rules The alternatives. + * @return Boolean True when one matches. + */ + private fun matches(content: ByteArray, rules: List): Boolean = + rules.any { rule -> + val end = rule.offset + rule.expected.size + end <= content.size && + content.copyOfRange(rule.offset, end).contentEquals(rule.expected) && + (rule.nested.isEmpty() || matches(content, rule.nested)) + } + + /** The `mime-type` element of the committed entry. */ + private fun mimeTypeElement(): Element { + val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(mimeEntry) + return document.getElementsByTagName("mime-type").item(0) as Element + } + + /** + * A ZIP whose first entry is a stored `mimetype` holding [mimetype] - the shape KRA, EPUB, and OpenDocument + * share with UMA - or a plain ZIP when [mimetype] is null. + * + * @param String? mimetype The first entry's content, or null for none. + * @return ByteArray The archive. + */ + private fun zipAnnouncing(mimetype: String?): ByteArray { + val bytes = ByteArrayOutputStream() + ZipOutputStream(bytes).use { zip -> + if (mimetype != null) { + val content = mimetype.toByteArray(Charsets.US_ASCII) + val entry = ZipEntry("mimetype") + entry.method = ZipEntry.STORED + entry.size = content.size.toLong() + entry.compressedSize = content.size.toLong() + entry.crc = CRC32().also { crc -> crc.update(content) }.value + zip.putNextEntry(entry) + zip.write(content) + zip.closeEntry() + } + zip.putNextEntry(ZipEntry("content.txt")) + zip.write("not a puppet".toByteArray()) + zip.closeEntry() + } + return bytes.toByteArray() + } + + /** The magic recognises what the writer writes, and nothing that merely looks like it. */ + @Test + fun theFreedesktopMagicMatchesARealUmaAndNothingElse() { + val magic = mimeTypeElement().getElementsByTagName("magic").item(0) as Element + val rules = rulesUnder(magic) + val written = Uma.write(UmaModel.create(UmaWriterInfo("Umamo", "0.0.0-test"))) + + assertTrue(Uma.matches(written), "the codec's own probe accepts the file") + assertTrue(matches(written, rules), "and so does the freedesktop magic") + assertFalse(matches(zipAnnouncing(null), rules), "a plain ZIP is not a UMA") + assertFalse(matches(zipAnnouncing("application/x-krita"), rules), "nor is another format that announces itself the same way") + // The shared database gives application/zip's bare-signature magic 60 and its ZIP-based formats (EPUB, + // OpenDocument) 70. Above 60 so an extensionless .uma is not read as a plain ZIP; below 80, the level at + // which magic would outrank a file's NAME and a .uma renamed to .zip would stop opening as an archive. + val priority = magic.getAttribute("priority").toInt() + assertTrue(priority in 61..79, "priority $priority must sit above application/zip's 60 and below the name-outranking 80") + } + + /** The entry names the codec's type, as a ZIP subtype, with the `.uma` glob. */ + @Test + fun theFreedesktopEntryNamesTheCodecsType() { + val mimeType = mimeTypeElement() + + assertEquals(Uma.MIME_TYPE, mimeType.getAttribute("type")) + assertEquals("application/zip", (mimeType.getElementsByTagName("sub-class-of").item(0) as Element).getAttribute("type")) + assertEquals("*.${Uma.kind.extension}", (mimeType.getElementsByTagName("glob").item(0) as Element).getAttribute("pattern")) + } + + /** The desktop entry, the package's build script, and the Android manifest all name the same type and extension. */ + @Test + fun everyRegistrationNamesTheSameType() { + val desktopLines = desktopEntry.readLines() + assertTrue("MimeType=${Uma.MIME_TYPE};" in desktopLines, "the desktop entry handles the type") + assertTrue(desktopLines.any { line -> line.startsWith("Exec=") && line.endsWith("%f") }, "and takes the file as an argument, which Main reads") + + val script = buildScript.readText() + assertTrue("val umaMimeType = \"${Uma.MIME_TYPE}\"" in script, "the package's file association names the type") + assertTrue("val umaExtension = \"${Uma.kind.extension}\"" in script, "and the extension") + assertEquals(3, Regex("fileAssociation\\(umaMimeType, umaExtension,").findAll(script).count(), "declared for Windows, macOS, and Linux") + + val manifest = androidManifest.readText() + assertTrue("android:mimeType=\"${Uma.MIME_TYPE}\"" in manifest, "the Android intent filter names the type") + assertTrue("android:pathSuffix=\".${Uma.kind.extension}\"" in manifest, "and the extension, for providers that report a generic type") + } + + /** A path the OS hands over is accepted by extension alone, however it is cased; the loader checks the content. */ + @Test + fun aHandedOverPathIsAcceptedByItsExtension() { + assertTrue(isOpenableDocumentPath("/home/rigger/Erica.uma")) + assertTrue(isOpenableDocumentPath("C:\\Rigs\\ERICA.UMA")) + assertTrue(isOpenableDocumentPath("/home/rigger/Erica.cmo3")) + assertTrue(isOpenableDocumentPath("/home/rigger/Erica.moc3")) + assertFalse(isOpenableDocumentPath("/home/rigger/Erica.psd"), "artwork is imported into a document, never opened as one") + assertFalse(isOpenableDocumentPath("--some-flag")) + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/AtlasPairingTest.kt b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/AtlasPairingTest.kt new file mode 100644 index 0000000..f15da81 --- /dev/null +++ b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/AtlasPairingTest.kt @@ -0,0 +1,123 @@ +package org.umamo.editor.desktop.viewport + +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.viewport.AtlasPageBinding +import kotlin.test.Test +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * Pins the render loop's model/pages pairing: an atlas-changing model is held until the binding + * composed for its atlas arrives (undo must never render repacked pixels under baseline + * coordinates), non-atlas edits pass untouched, and the baseline's equal-but-distinct atlas + * instance still pairs. Pure - the decision is exactly what the loop carries out. + */ +class AtlasPairingTest { + private fun modelWith(atlas: PuppetAtlas): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 10f, + canvasHeight = 10f, + worldOriginX = 5f, + worldOriginZ = 5f, + atlas = atlas, + ) + + private fun bindingFor(atlas: PuppetAtlas): AtlasPageBinding = + AtlasPageBinding(atlas, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false)) + + private val baselineAtlas = PuppetAtlas(pages = listOf(AtlasPage(64, 64))) + private val repackedAtlas = PuppetAtlas(pages = listOf(AtlasPage(128, 128))) + + @Test + fun aNonAtlasEditPassesUntouched() { + val baseline = modelWith(baselineAtlas) + val applied = bindingFor(baselineAtlas) + val edited = baseline.copy(canvasWidth = 20f) + + val decision = resolveAtlasPairing(edited, applied, applied, baseline) + + assertSame(edited, decision.orderModel, "a same-atlas model renders immediately") + assertNull(decision.applyBinding, "and swaps nothing") + } + + @Test + fun anAtlasChangingModelWaitsForItsPages() { + val baseline = modelWith(baselineAtlas) + val applied = bindingFor(baselineAtlas) + val repacked = modelWith(repackedAtlas) + + val held = resolveAtlasPairing(repacked, applied, applied, baseline) + + assertSame(baseline, held.orderModel, "the previous pair keeps rendering while pages are in flight") + assertNull(held.applyBinding) + + val newBinding = bindingFor(repackedAtlas) + val released = resolveAtlasPairing(repacked, newBinding, applied, baseline) + assertSame(repacked, released.orderModel, "the matching binding releases the hold") + assertSame(newBinding, released.applyBinding, "and the pages swap first") + } + + @Test + fun undoHoldsUntilTheBaselinePagesComeBack() { + val baseline = modelWith(baselineAtlas) + val repacked = modelWith(repackedAtlas) + val repackedBinding = bindingFor(repackedAtlas) + + val held = resolveAtlasPairing(baseline, repackedBinding, repackedBinding, repacked) + assertSame(repacked, held.orderModel, "baseline coordinates must not render against repacked pixels") + assertNull(held.applyBinding) + + val baselineBinding = bindingFor(baselineAtlas) + val released = resolveAtlasPairing(baseline, baselineBinding, repackedBinding, repacked) + assertSame(baseline, released.orderModel) + assertSame(baselineBinding, released.applyBinding) + } + + @Test + fun anEqualButDistinctBaselineAtlasStillPairs() { + // The session's baseline short-circuit can publish the baseline pages under an atlas instance + // that is equal to - but not identical with - the model's own. + val modelAtlasTwin = PuppetAtlas(pages = listOf(AtlasPage(64, 64))) + val model = modelWith(modelAtlasTwin) + val applied = bindingFor(repackedAtlas) + val baselineBinding = bindingFor(baselineAtlas) + + val decision = resolveAtlasPairing(model, baselineBinding, applied, modelWith(repackedAtlas)) + + assertSame(model, decision.orderModel, "structural equality is enough to pair") + assertSame(baselineBinding, decision.applyBinding) + } + + @Test + fun aBindingRepublishUnderTheCurrentAtlasAppliesAlone() { + // The resolver's derive-failure fallback republishes pages under the model's own atlas. + val model = modelWith(repackedAtlas) + val applied = bindingFor(repackedAtlas) + val republished = bindingFor(repackedAtlas) + + val decision = resolveAtlasPairing(model, republished, applied, model) + + assertSame(model, decision.orderModel) + assertSame(republished, decision.applyBinding, "new pages under an unchanged atlas still swap") + } + + @Test + fun theFirstTickRendersThePublishedModelRegardless() { + val model = modelWith(repackedAtlas) + val applied = bindingFor(baselineAtlas) + + val decision = resolveAtlasPairing(model, applied, applied, lastModel = null) + + assertSame(model, decision.orderModel, "with no previous pair there is nothing to hold") + assertNull(decision.applyBinding) + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/AtlasSwapModelUpdateTest.kt b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/AtlasSwapModelUpdateTest.kt new file mode 100644 index 0000000..afc7e87 --- /dev/null +++ b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/AtlasSwapModelUpdateTest.kt @@ -0,0 +1,195 @@ +package org.umamo.editor.desktop.viewport + +import androidx.compose.ui.graphics.toPixelMap +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.visibleDrawableIds +import org.umamo.ui.viewport.AtlasPageBinding +import org.umamo.ui.viewport.LiveParams +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The live-repack integration gate, one level above the renderer: a real OffscreenPuppetService with + * its render thread and pairing loop, driven with the exact publish sequence the UI performs on a + * repack - setModel with a NEW atlas value, setAtlasPages with the binding composed for it - and + * then a plain UV edit. The UV edit is the point: after a page-count-changing repack, editing a + * mapping must still re-render (the modelG report: UV edits stopped updating the render after a + * 5-page document repacked to 2). + * + * Self-skips when no GL context can be created (no frame ever arrives). + */ +class AtlasSwapModelUpdateTest { + private val paramA = ParameterId("A") + private val probeId = DrawableId("SwapProbe") + + // A 120x120 quad centered at the origin, keyed with one zero-delta form. + private val quadPositions = floatArrayOf(-60f, -60f, 60f, -60f, -60f, 60f, 60f, 60f) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + private fun quadUvs(centerU: Float, centerV: Float, halfSpan: Float = 0.2f): FloatArray = + floatArrayOf( + centerU - halfSpan, + centerV + halfSpan, + centerU + halfSpan, + centerV + halfSpan, + centerU - halfSpan, + centerV - halfSpan, + centerU + halfSpan, + centerV - halfSpan, + ) + + private fun solidImage(red: Int, green: Int, blue: Int, size: Int = 16): DecodedImage { + val rgba = ByteArray(size * size * 4) + for (pixel in rgba.indices step 4) { + rgba[pixel] = red.toByte() + rgba[pixel + 1] = green.toByte() + rgba[pixel + 2] = blue.toByte() + rgba[pixel + 3] = 0xFF.toByte() + } + return DecodedImage(rgba, size, size) + } + + /** A 16x16 page whose left half is blue and right half is white. */ + private fun blueWhiteImage(): DecodedImage { + val size = 16 + val rgba = ByteArray(size * size * 4) + for (rowIndex in 0 until size) { + for (columnIndex in 0 until size) { + val pixel = (rowIndex * size + columnIndex) * 4 + val white = columnIndex >= size / 2 + rgba[pixel] = if (white) 0xFF.toByte() else 0x00 + rgba[pixel + 1] = if (white) 0xFF.toByte() else 0x00 + rgba[pixel + 2] = 0xFF.toByte() + rgba[pixel + 3] = 0xFF.toByte() + } + } + return DecodedImage(rgba, size, size) + } + + private fun modelWith(atlas: PuppetAtlas, uvs: FloatArray): PuppetModel { + val drawable = + Drawable( + id = probeId, + name = "SwapProbe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(quadPositions.copyOf(), uvs, quadIndices), + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(quadPositions.size)))), + ), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + atlas = atlas, + ) + } + + /** Waits until the area publishes a frame satisfying [accept], or returns null on timeout. */ + private fun awaitFrame( + frames: kotlinx.coroutines.flow.StateFlow, + deadlineMillis: Long = 5_000, + accept: (androidx.compose.ui.graphics.PixelMap) -> Boolean, + ): Boolean { + val start = System.currentTimeMillis() + while (System.currentTimeMillis() - start < deadlineMillis) { + val frame = frames.value + if (frame != null && accept(frame.bitmap.toPixelMap())) { + return true + } + Thread.sleep(20) + } + return false + } + + private fun centerChannelDominates(pixels: androidx.compose.ui.graphics.PixelMap, channel: String): Boolean { + val color = pixels[pixels.width / 2, pixels.height / 2] + val red = color.red + val green = color.green + val blue = color.blue + return when (channel) { + "red" -> red > green + 0.25f && red > blue + 0.25f + "blue" -> blue > red + 0.25f && blue > green + 0.25f + "white" -> red > 0.7f && green > 0.7f && blue > 0.7f + else -> false + } + } + + @Test + fun aUvEditAfterAPageCountChangingRepackStillRerenders() { + val baselineAtlas = PuppetAtlas(pages = listOf(AtlasPage(16, 16))) + val baselineModel = modelWith(baselineAtlas, quadUvs(0.5f, 0.5f)) + val baselineTextures = PuppetTextures(listOf(solidImage(0xFF, 0x00, 0x00)), mapOf(probeId.raw to 0), false) + val service = OffscreenPuppetService(baselineModel, baselineTextures, LiveParams(emptyMap())) + service.start() + try { + val frames = service.register("area") + service.resize("area", 100, 100) + val sawBaseline = awaitFrame(frames) { pixels -> centerChannelDominates(pixels, "red") } + if (!sawBaseline) { + println("[atlas-swap-live] no GL frame arrived; skipping (context unavailable, or baseline never rendered)") + return + } + + // The repack, in the UI's publish order: the committed model first (the session collector), + // then the binding composed for its atlas (the resolver). Page count changes 1 -> 2 and the + // probe moves to page 1, whose LEFT half is blue. + val repackedAtlas = PuppetAtlas(pages = listOf(AtlasPage(16, 16), AtlasPage(16, 16))) + val repackedModel = modelWith(repackedAtlas, quadUvs(0.25f, 0.5f)) + val repackedTextures = + PuppetTextures( + listOf(solidImage(0x00, 0xFF, 0x00), blueWhiteImage()), + mapOf(probeId.raw to 1), + false, + ) + service.setModel(repackedModel) + service.setShownDrawables(repackedModel.visibleDrawableIds()) + service.setAtlasPages(AtlasPageBinding(repackedAtlas, repackedTextures)) + assertTrue( + awaitFrame(frames) { pixels -> centerChannelDominates(pixels, "blue") }, + "the repacked pair must render (probe on page 1's blue half)", + ) + + // The UV edit: same atlas instance, the mapping moves to the WHITE half. This is the exact + // gesture the modelG report says stops updating the render. + val editedModel = + repackedModel.copy( + drawables = + listOf( + repackedModel.drawables.single().let { drawable -> + drawable.copy(mesh = DrawableMesh(drawable.mesh!!.positions, quadUvs(0.75f, 0.5f), drawable.mesh!!.indices)) + }, + ), + ) + service.setModel(editedModel) + assertTrue( + awaitFrame(frames) { pixels -> centerChannelDominates(pixels, "white") }, + "a UV edit after the repack must re-render (probe moved to page 1's white half)", + ) + } finally { + service.dispose() + } + } +} \ No newline at end of file diff --git a/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/ViewportAreaRegistryTest.kt b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/ViewportAreaRegistryTest.kt new file mode 100644 index 0000000..6e925aa --- /dev/null +++ b/app/desktop/src/jvmTest/kotlin/org/umamo/editor/desktop/viewport/ViewportAreaRegistryTest.kt @@ -0,0 +1,361 @@ +package org.umamo.editor.desktop.viewport + +import org.umamo.render.ContentBounds +import org.umamo.render.DecodedImage +import org.umamo.render.ViewportCamera +import org.umamo.ui.viewport.AreaCameraKey +import org.umamo.ui.viewport.CameraSurface +import org.umamo.ui.viewport.UvSceneContent +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins how an area's scene routing is published, which decides what the render loop draws it as and + * which content bounds its camera fits. + * + * These are pure state assertions - no GL, no render thread - because the routing is pure state. The + * engine reads exactly these fields to choose between drawing the posed puppet and drawing a flat UV + * surface, so a slot that reads as the wrong kind sends an area to the wrong renderer and fits it to + * the wrong bounds, which shows up as artwork that is simply in the wrong place. + */ +class ViewportAreaRegistryTest { + private fun image(width: Int = 4, height: Int = 4): DecodedImage = + DecodedImage(ByteArray(width * height * 4), width, height) + + /** + * A registered UV area reads as a UV scene, not as a puppet. + * + * The regression this exists for: the kind and the content were once published as separate fields, + * and collapsing them into one value dropped the kind write. Every UV area then still read as + * Puppet2D, so the engine fit each one to the PUPPET's rest bounds instead of the page rectangle and + * the atlas landed far off origin - while every existing test stayed green, because nothing covered + * this routing at all. + */ + @Test + fun registeringAUvSceneMarksTheAreaAsUv() { + val registry = ViewportAreaRegistry() + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), null) + val slot = registry.areas.getValue("uv") + assertEquals(RenderScene.UvScene, slot.scene, "a UV area must not read as a puppet area") + assertEquals(UvSceneContent.AtlasPage(0), slot.uvContent, "and it carries the content it registered with") + } + + /** A puppet area stays a puppet area, and carries no UV surface. */ + @Test + fun registeringAPuppetAreaLeavesItAPuppet() { + val registry = ViewportAreaRegistry() + registry.register("puppet") + val slot = registry.areas.getValue("puppet") + assertEquals(RenderScene.Puppet2D, slot.scene, "the puppet area keeps the puppet scene") + assertNull(slot.uvContent, "and has no UV surface to draw") + } + + /** + * Retargeting a UV area replaces its whole surface, kind and payload together. + * + * A page and a layer are addressed differently - one by index into the document's uploaded pages, + * one by pixels the engine has never seen - so a switch that carried over half of the old choice + * would draw one surface while the freshness test spoke for the other. + */ + @Test + fun retargetingReplacesTheWholeSurface() { + val registry = ViewportAreaRegistry() + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), null) + val slot = registry.areas.getValue("uv") + + val layer = image() + registry.setUvSceneContent("uv", UvSceneContent.SourceLayer("layer", layer), null) + assertEquals(UvSceneContent.SourceLayer("layer", layer), slot.uvContent, "the layer view replaces the page view whole") + assertEquals(RenderScene.UvScene, slot.scene, "and it is still a UV area") + + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(2), null) + assertEquals(UvSceneContent.AtlasPage(2), slot.uvContent, "and switching back replaces it whole again") + } + + /** + * Retargeting never turns a puppet area into a UV one. + * + * The puppet / UV split is fixed at registration; only the surface within the UV family moves. + */ + @Test + fun retargetingIgnoresAPuppetArea() { + val registry = ViewportAreaRegistry() + registry.register("puppet") + registry.setUvSceneContent("puppet", UvSceneContent.AtlasPage(1), null) + val slot = registry.areas.getValue("puppet") + assertEquals(RenderScene.Puppet2D, slot.scene, "a puppet area is not retargetable into a UV scene") + assertNull(slot.uvContent, "and takes on no UV surface") + } + + /** An unregistered area is a no-op rather than a crash, since requests can outlive their area. */ + @Test + fun retargetingAnUnknownAreaDoesNothing() { + val registry = ViewportAreaRegistry() + registry.setUvSceneContent("gone", UvSceneContent.AtlasPage(0), null) + assertTrue(registry.areas.isEmpty(), "no slot is conjured for an area that never registered") + } + + /** + * A UV area survives the register-before-unregister overlap a tree collapse produces. + * + * Closing a split sibling rebuilds the surviving area's leaf under a fresh composition node, so the + * new register runs BEFORE the old unregister. The slot must still be a UV area afterwards. + */ + @Test + fun aReRegisteredUvAreaSurvivesTheOverlap() { + val registry = ViewportAreaRegistry() + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), null) + registry.registerUvScene("uv", UvSceneContent.AtlasPage(1), null) + registry.unregister("uv") + val slot = registry.areas.getValue("uv") + assertEquals(RenderScene.UvScene, slot.scene, "the surviving hold keeps the area a UV scene") + assertEquals(UvSceneContent.AtlasPage(1), slot.uvContent, "with the content the rebuilt leaf registered") + } + + /** + * Switching an area's editor type in place - the UV editor to the 2D viewport - hands the slot to the new space. + * + * The new space registers BEFORE the old one releases (it composes first), so the slot never drops to zero and + * is reused as it stands: still a UV scene, still holding the page, still on the page's camera. Left that way + * the engine keeps drawing the atlas page under the 2D viewport's gizmos, framed by a pan and zoom that mean + * nothing in the puppet's world. A registration claims all three. + */ + @Test + fun switchingAUvEditorToAViewportInPlaceRetargetsTheSlot() { + val registry = ViewportAreaRegistry() + val pageBounds = ContentBounds(0f, 0f, 4096f, 4096f) + val puppetBounds = ContentBounds(-600f, -900f, 1200f, 1800f) + registry.registerUvScene("area", UvSceneContent.AtlasPage(0), null) + val slot = registry.areas.getValue("area") + val pageCamera = registry.establishCamera(slot, "area", 800, 600) { _, _ -> pageBounds } + + // The space switch: the viewport registers while the UV editor still holds the area, then the editor lets go. + registry.register("area") + registry.unregister("area") + + assertEquals(slot, registry.areas["area"], "the slot survives the switch - the area never went unheld") + assertEquals(RenderScene.Puppet2D, slot.scene, "and now reads as a puppet area") + assertNull(slot.uvContent, "with no UV surface left to draw") + assertNull(slot.camera, "and no camera, so the engine establishes the puppet's view") + assertNull(slot.imageState.value, "and no last frame of the page to show under the viewport's overlays") + val puppetCamera = registry.establishCamera(slot, "area", 800, 600) { _, _ -> puppetBounds } + assertEquals(ViewportCamera.fit(puppetBounds, 800, 600), puppetCamera, "the puppet is fitted, not framed by the page's camera") + + // And back: each surface kept its own view for the area. + registry.registerUvScene("area", UvSceneContent.AtlasPage(0), null) + registry.unregister("area") + assertEquals(RenderScene.UvScene, slot.scene) + assertEquals(pageCamera, registry.establishCamera(slot, "area", 800, 600) { _, _ -> error("the page's view is remembered, not refitted") }) + } + + /** + * A leaf rebuilt for the SAME space - a tree collapse registers the survivor again before its old leaf releases - + * keeps its camera and its frame: only a change of kind is a claim. + */ + @Test + fun reRegisteringTheSameSpaceKeepsTheView() { + val registry = ViewportAreaRegistry() + registry.register("area") + val slot = registry.areas.getValue("area") + val camera = registry.establishCamera(slot, "area", 800, 600) { _, _ -> ContentBounds(0f, -100f, 100f, 100f) } + + registry.register("area") + registry.unregister("area") + + assertEquals(camera, slot.camera) + assertEquals(camera, slot.cameraState.value) + } + + /** + * A camera seeded before an area registers is the one the area opens on, in place of a fit - how a saved + * document reopens each area on the view it was left with (docs/format/UMA.md § 7.3). A seed is for one + * surface: the same area showing the other surface fits instead. + */ + @Test + fun aSeededCameraIsWhatTheAreaOpensOn() { + val registry = ViewportAreaRegistry() + val saved = ViewportCamera(120f, -340f, 2.5f) + registry.seedCameras( + mapOf( + AreaCameraKey("viewport", CameraSurface.Viewport) to saved, + AreaCameraKey("never-shown", CameraSurface.Viewport) to ViewportCamera(1f, 1f, 1f), + AreaCameraKey("now-a-uv-editor", CameraSurface.Viewport) to ViewportCamera(2f, 2f, 2f), + ), + ) + registry.register("viewport") + registry.register("fresh") + registry.registerUvScene("now-a-uv-editor", UvSceneContent.AtlasPage(0), null) + val fitBounds = ContentBounds(0f, -100f, 100f, 100f) + + val restored = registry.establishCamera(registry.areas.getValue("viewport"), "viewport", 800, 600) { _, _ -> error("a seeded area must not fit") } + val fitted = registry.establishCamera(registry.areas.getValue("fresh"), "fresh", 800, 600) { _, _ -> fitBounds } + val otherSurface = registry.establishCamera(registry.areas.getValue("now-a-uv-editor"), "now-a-uv-editor", 800, 600) { _, _ -> fitBounds } + + assertEquals(saved, restored) + assertEquals(ViewportCamera.fit(fitBounds, 800, 600), fitted, "an area with nothing saved fits its content, as before") + assertEquals(ViewportCamera.fit(fitBounds, 800, 600), otherSurface, "a view saved for the puppet is not applied to a texture") + assertEquals(ViewportCamera(2f, 2f, 2f), registry.cameras()[AreaCameraKey("now-a-uv-editor", CameraSurface.Viewport)], "and stays remembered for the day the area shows a viewport again") + assertTrue(AreaCameraKey("never-shown", CameraSurface.Viewport) in registry.cameras(), "every remembered camera is readable for the next save") + } + + /** Seeding never moves an area that already has a camera: it is for the moment the engine is built. */ + @Test + fun seedingLeavesAnEstablishedCameraAlone() { + val registry = ViewportAreaRegistry() + registry.register("viewport") + val established = registry.establishCamera(registry.areas.getValue("viewport"), "viewport", 800, 600) { _, _ -> ContentBounds(0f, -100f, 100f, 100f) } + + registry.seedCameras(mapOf(AreaCameraKey("viewport", CameraSurface.Viewport) to ViewportCamera(9f, 9f, 9f))) + + assertEquals(established, registry.cameras()[AreaCameraKey("viewport", CameraSurface.Viewport)]) + } + + /** + * A UV editor keeps a view per page and layer. Switching to one it has never shown fits that surface rather + * than carrying the page's pan and zoom over it - a layer a fraction of the page's size would land tiny and in a + * corner - and switching back brings back the view the first one was left with. + */ + @Test + fun eachSurfaceKeepsItsOwnView() { + val registry = ViewportAreaRegistry() + val pageBounds = ContentBounds(0f, 0f, 4096f, 4096f) + val layerBounds = ContentBounds(0f, 0f, 300f, 200f) + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), null) + val slot = registry.areas.getValue("uv") + registry.establishCamera(slot, "uv", 800, 600) { _, _ -> pageBounds } + registry.pan("uv", 40f, -25f) + val pannedPage = slot.camera + + val layerContent = UvSceneContent.SourceLayer("layer-1", image(300, 200)) + registry.setUvSceneContent("uv", layerContent, null) + assertEquals(pannedPage, slot.camera, "a retarget moves no camera by itself - the render thread swaps it with the next frame") + val layerView = + registry.establishCamera(slot, "uv", 800, 600) { _, content -> + assertEquals(layerContent, content, "the fit is of the content the swap files the view under") + layerBounds + } + assertEquals(ViewportCamera.fit(layerBounds, 800, 600), layerView, "a layer the area has never shown is fitted") + + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(0), null) + assertEquals(pannedPage, registry.establishCamera(slot, "uv", 800, 600) { _, _ -> error("the page's view is remembered, not refitted") }) + + registry.setUvSceneContent("uv", UvSceneContent.SourceLayer("layer-1", image(300, 200)), null) + assertEquals(layerView, registry.establishCamera(slot, "uv", 800, 600) { _, _ -> error("a layer is known by its key, not its pixels") }) + } + + /** Two UV editors keep their own views: one's view of a page is not what the other opens that page on. */ + @Test + fun twoAreasKeepSeparateViewsOfOnePage() { + val registry = ViewportAreaRegistry() + val pageBounds = ContentBounds(0f, 0f, 1024f, 1024f) + registry.registerUvScene("top", UvSceneContent.AtlasPage(1), null) + registry.registerUvScene("bottom", UvSceneContent.AtlasPage(0), null) + val top = registry.areas.getValue("top") + val bottom = registry.areas.getValue("bottom") + registry.establishCamera(top, "top", 800, 300) { _, _ -> pageBounds } + registry.zoomCentered("top", zoomIn = true, coarse = true) + registry.establishCamera(bottom, "bottom", 800, 300) { _, _ -> pageBounds } + + registry.setUvSceneContent("bottom", UvSceneContent.AtlasPage(1), null) + + assertEquals(ViewportCamera.fit(pageBounds, 800, 300), registry.establishCamera(bottom, "bottom", 800, 300) { _, _ -> pageBounds }) + assertNotEquals(top.camera, bottom.camera, "and the top area's zoom stays its own") + } + + /** + * An area put away by a workspace tab switch and brought back showing another surface - its selection moved + * while it was away - opens on that surface's view, or a fit, never on the last view it had of the old one. + */ + @Test + fun aReturningAreaOnAnotherSurfaceTakesThatSurfacesView() { + val registry = ViewportAreaRegistry() + val pageBounds = ContentBounds(0f, 0f, 2048f, 2048f) + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), null) + registry.establishCamera(registry.areas.getValue("uv"), "uv", 800, 600) { _, _ -> pageBounds } + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(1), null) + registry.establishCamera(registry.areas.getValue("uv"), "uv", 800, 600) { _, _ -> pageBounds } + registry.zoomCentered("uv", zoomIn = true, coarse = true) + val secondPageView = registry.areas.getValue("uv").camera + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(0), null) + registry.establishCamera(registry.areas.getValue("uv"), "uv", 800, 600) { _, _ -> error("the first page's view is remembered") } + registry.pan("uv", 120f, 0f) + + // The tab switch drops the slot; the area comes back following a selection now on the second page. + registry.unregister("uv") + assertNull(registry.areas["uv"], "the slot is gone while its workspace is away") + registry.registerUvScene("uv", UvSceneContent.AtlasPage(1), null) + val returned = registry.establishCamera(registry.areas.getValue("uv"), "uv", 800, 600) { _, _ -> error("the second page's view is remembered") } + + assertEquals(secondPageView, returned) + assertEquals(secondPageView, registry.cameras()[AreaCameraKey("uv", CameraSurface.Uv)], "and it is the view a save now writes") + + registry.unregister("uv") + registry.registerUvScene("uv", UvSceneContent.SourceLayer("never-shown", image(64, 64)), null) + val layerBounds = ContentBounds(0f, 0f, 64f, 64f) + assertEquals(ViewportCamera.fit(layerBounds, 800, 600), registry.establishCamera(registry.areas.getValue("uv"), "uv", 800, 600) { _, _ -> layerBounds }) + } + + /** + * A saved document's UV view belongs to the surface the area opens on. Once the area has shown a surface this + * session, a surface it has not shown fits instead of inheriting the saved view. + */ + @Test + fun aSeededUvViewBelongsToTheFirstSurfaceShown() { + val registry = ViewportAreaRegistry() + val saved = ViewportCamera(300f, 200f, 0.5f) + val pageBounds = ContentBounds(0f, 0f, 1024f, 1024f) + registry.seedCameras(mapOf(AreaCameraKey("uv", CameraSurface.Uv) to saved)) + registry.registerUvScene("uv", UvSceneContent.AtlasPage(3), null) + val slot = registry.areas.getValue("uv") + + assertEquals(saved, registry.establishCamera(slot, "uv", 800, 600) { _, _ -> error("the saved view is what the area opens on") }) + + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(0), null) + assertEquals(ViewportCamera.fit(pageBounds, 800, 600), registry.establishCamera(slot, "uv", 800, 600) { _, _ -> pageBounds }) + + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(3), null) + assertEquals(saved, registry.establishCamera(slot, "uv", 800, 600) { _, _ -> error("and the opening page keeps it") }) + } + + /** A save sees one UV view per area, the shown surface's: the views kept for the other surfaces are session state. */ + @Test + fun aSaveSeesOnlyTheShownSurfacesView() { + val registry = ViewportAreaRegistry() + val layerBounds = ContentBounds(0f, 0f, 300f, 200f) + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), null) + val slot = registry.areas.getValue("uv") + registry.establishCamera(slot, "uv", 800, 600) { _, _ -> ContentBounds(0f, 0f, 4096f, 4096f) } + registry.pan("uv", 10f, 10f) + + registry.setUvSceneContent("uv", UvSceneContent.SourceLayer("layer-1", image(300, 200)), null) + val layerView = registry.establishCamera(slot, "uv", 800, 600) { _, _ -> layerBounds } + + assertEquals(mapOf(AreaCameraKey("uv", CameraSurface.Uv) to layerView), registry.cameras()) + } + + /** + * A UV editor's fit frames the page, widened to every shown mesh that reaches past it: a placement moved off the + * page carries its islands with it, and a fit of the page alone would frame everything but what was just moved. + */ + @Test + fun aFitTakesInMeshesPastThePageEdge() { + val pageBounds = ContentBounds(0f, 0f, 1024f, 1024f) + val spilled = ContentBounds(900f, -300f, 600f, 400f) + val widened = ContentBounds(0f, -300f, 1500f, 1324f) + assertEquals(widened, uvFitBounds(pageBounds, spilled)) + assertEquals(pageBounds, uvFitBounds(pageBounds, ContentBounds(10f, 10f, 20f, 20f)), "meshes inside the page leave the page fit alone") + assertEquals(pageBounds, uvFitBounds(pageBounds, null), "as does a surface with no meshes") + + val registry = ViewportAreaRegistry() + registry.registerUvScene("uv", UvSceneContent.AtlasPage(0), spilled) + val slot = registry.areas.getValue("uv") + assertEquals(ViewportCamera.fit(widened, 800, 600), registry.establishCamera(slot, "uv", 800, 600) { _, _ -> pageBounds }, "the first fit takes the spill in") + + registry.setUvSceneContent("uv", UvSceneContent.AtlasPage(0), ContentBounds(10f, 10f, 20f, 20f)) + registry.fit("uv") + assertEquals(ViewportCamera.fit(pageBounds, 800, 600), registry.establishCamera(slot, "uv", 800, 600) { _, _ -> pageBounds }, "and Fit View follows the meshes back inside") + } +} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..ccb1458 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,172 @@ +// Root build script. Plugins are declared here with `apply false` purely to pin their +// versions for the whole build; each module opts in by `alias(...)`-ing the ones it needs. +// This avoids every module repeating version numbers (the version catalog holds those). +// ルートビルドスクリプト。プラグインは `apply false` でバージョン固定のみを行い、各モジュールが +// 必要なものを `alias(...)` で取り込む。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) apply false + alias(libs.plugins.composeCompiler) apply false + alias(libs.plugins.composeMultiplatform) apply false + alias(libs.plugins.androidApplication) apply false + alias(libs.plugins.androidKmpLibrary) apply false + alias(libs.plugins.ktlint) +} + +// Apply ktlint to every subproject so tab-based style (see .editorconfig) is enforced +// uniformly. ktlint reads .editorconfig, so no rule config is needed here. +subprojects { + apply(plugin = "org.jlleitschuh.gradle.ktlint") + // Compose Multiplatform generates Kotlin under build/generated (JetBrains space-indent style); lint + // our own sources, not generated output (e.g. the resources `Res` collectors). + configure { + filter { + exclude { element -> element.file.path.contains("/generated/") } + } + } + + // Name every test as it runs, and print failures in full. + // + // Gradle's defaults report a passing run as a single count, which is the one shape this build must + // not have: the corpus- and GL-gated tests self-skip when their input is missing, and "239 tests + // completed" reads identically whether the GL suite rendered pixels or sat out the whole run. Naming + // passed AND skipped tests is what tells those two apart in a CI log. + // + // FULL rather than the default SHORT because SHORT prints only "AssertionError at File.kt:120" and + // drops the message - which is where a failure says what it actually was (HeadlessGlGate puts the + // GLFW error code and description there). Standard streams stay off: the tests print per-pixel + // diagnostics that would bury everything else. + tasks.withType().configureEach { + testLogging { + events("passed", "skipped", "failed") + exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL + } + } +} + +// Keeps the common source sets free of JVM-only APIs. +// +// This is NOT redundant with the compiler. Every target today is JVM-based (desktop JVM + +// Android/ART), so the common source set resolves `java.*` and the `kotlin.jvm.*` default import +// perfectly happily — a commonMain file can call java.util.zip and still compile. That only +// stops being true the day a non-JVM target (Kotlin/Native, for iPadOS) is added, at which point +// every accumulated leak surfaces at once, in code nobody has touched for months. This task +// turns that latent debt into an immediate failure instead. +// +// commonTest is in scope too, and deliberately: it has to compile for every target its commonMain +// does, so a JVM-only API there is the same latent break, and a test source set is exactly where one +// slips in unnoticed (a test that only ever runs on the JVM still has to *build* everywhere). It is +// also where the leaks were: `"ABCD".toByteArray(Charsets.US_ASCII)` in a shared test reads as +// harmless until the day it isn't. +// +// Three rules, each from a real leak found in this tree. Note that none of them is only about imports: +// the JVM's default imports (`java.lang.*`, `kotlin.jvm.*`, `kotlin.text.Charsets`) mean JVM-only APIs +// can appear with no import line to grep for, and even a non-default API can be written out in full at +// the use site — `catch (_: java.util.zip.DataFormatException)` needs no import and was exactly how the +// old ClipRaster reached zlib. +// 1. No `java.*` / `javax.*`, whether imported or spelled out at the use site — put the code in +// jvmAndroidMain, or hide the platform behind an expect/actual (see +// org.umamo.format.clip.useClipDatabase for the pattern). Reach for a common-code library +// before either: okio covers DEFLATE and buffers, which is how org.umamo.format.binary.Deflate +// retired the expect/actual it used to need. +// 2. `@Jvm*` annotations must be imported explicitly from `kotlin.jvm`. They are optional +// expectations, so non-JVM targets ignore them — but `kotlin.jvm.*` is a default import only +// on JVM, so an unimported `@JvmInline` is an unresolved reference off-JVM. +// 3. No `Charsets` — `kotlin.text.Charsets` is JVM-only, so `String(bytes, US_ASCII)` and +// `toByteArray(UTF_16BE)` do not exist off-JVM. Use org.umamo.format.binary.BinaryText, or +// `encodeToByteArray()` when the bytes really are meant to be UTF-8. +// (`decodeToString()` is NOT a general substitute: it is UTF-8 only.) +// +// This check is a net, not a proof: it catches the leak classes we have actually hit. The definitive +// check is compiling against a real non-JVM target — and `:format` now does exactly that: it carries +// an `iosArm64()` target, so its commonMain purity is a compiler guarantee and this task is only a +// faster pre-check there. (The two blockers this note used to name — CArrayList/CHashMap extending +// java.util collections — were resolved by delegating instead of inheriting.) Every other module is +// still JVM-only, and for those this task remains the only thing holding the line; the way to upgrade +// one is to copy :format's target, not to grow this regex. +val commonSources = + fileTree(rootDir) { + include( + "module/*/src/commonMain/**/*.kt", + "module/*/src/commonTest/**/*.kt", + "app/*/src/commonMain/**/*.kt", + "app/*/src/commonTest/**/*.kt", + ) + } + +val checkCommonSourcePurity = + tasks.register("checkCommonSourcePurity") { + group = "verification" + description = "Fails if any module's commonMain/commonTest uses a JVM-only API, which would break a future Kotlin/Native target." + inputs.files(commonSources).withPropertyName("commonSources") + // A marker output, so a green run stays UP-TO-DATE instead of re-reading every common source + // file on every `check`. The task's real product is the failure, not the file. + val report = layout.buildDirectory.file("reports/commonSourcePurity.txt") + outputs.file(report).withPropertyName("report") + val sourceFiles = commonSources + val repositoryRoot = rootDir + doLast { + val jvmImport = Regex("""^import (java|javax)\.""") + // Qualified use with no import: `catch (_: java.util.zip.DataFormatException)`. The + // lookbehind keeps `org.foo.java.Bar` and an identifier ending in "java" from matching. + val jvmQualifiedUse = Regex("""(?() + for (sourceFile in sourceFiles.files.sortedBy { it.path }) { + val lines = sourceFile.readLines() + val relativePath = sourceFile.relativeTo(repositoryRoot).path + val importedJvmAnnotations = + lines.mapNotNull { line -> + jvmAnnotationImport.find(line.trim())?.groupValues?.get(1) + }.toSet() + lines.forEachIndexed { lineIndex, line -> + val trimmed = line.trim() + if (jvmImport.containsMatchIn(trimmed)) { + violations += "$relativePath:${lineIndex + 1}: a common source set must not import a JVM-only API -> $trimmed" + return@forEachIndexed + } + // Only flag real code, not prose in comments or docblocks. + if (!trimmed.startsWith("*") && !trimmed.startsWith("//") && !trimmed.startsWith("/*")) { + if (jvmQualifiedUse.containsMatchIn(line)) { + violations += + "$relativePath:${lineIndex + 1}: a common source set must not reference a JVM-only API, even fully " + + "qualified (a qualified use needs no import, so rule 1 alone would miss it) -> $trimmed" + } + jvmAnnotationUse.findAll(line).forEach { match -> + val annotation = match.groupValues[1] + if (annotation !in importedJvmAnnotations) { + violations += + "$relativePath:${lineIndex + 1}: @$annotation needs an explicit `import kotlin.jvm.$annotation` " + + "(kotlin.jvm.* is a default import only on JVM targets)" + } + } + if (charsetsUse.containsMatchIn(line)) { + violations += + "$relativePath:${lineIndex + 1}: Charsets is JVM-only (kotlin.text.Charsets); use " + + "encodeToByteArray()/decodeToString() when the bytes are UTF-8, else " + + "org.umamo.format.binary.decodeAscii / encodeUtf16Be -> $trimmed" + } + } + } + } + if (violations.isNotEmpty()) { + throw GradleException( + "common-source purity check failed (${violations.size} violation(s)):\n" + + violations.joinToString("\n") { " $it" }, + ) + } + val reportFile = report.get().asFile + reportFile.parentFile.mkdirs() + reportFile.writeText("common-source purity: ${sourceFiles.files.size} file(s) checked, no violations.\n") + } + } + +// Wire into `check` so the guard runs with the normal verification lifecycle rather than needing to be +// remembered. Gradle runs the task once however many subprojects depend on it. +subprojects { + tasks.matching { task -> task.name == "check" }.configureEach { + dependsOn(checkCommonSourcePurity) + } +} \ No newline at end of file diff --git a/docs/design/appicon/generate.sh b/docs/design/appicon/generate.sh new file mode 100755 index 0000000..79b938b --- /dev/null +++ b/docs/design/appicon/generate.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +# +# Regenerate every Umamo application-icon asset from the pixel-art master. +# +# Run this by hand whenever the mascot art changes. It is deliberately NOT part +# of the Gradle build: the build references the committed outputs, and this +# script (re)produces them so contributors without image tooling still build. +# +# Pixel-art crispness: every size is nearest-neighbor scaled. Upscales use the +# largest integer multiple of the master edge that fits the target, then pad +# transparently to the exact dimension, so every source pixel keeps a uniform +# width (a non-integer scale would make some pixels one device-pixel wider). +# Targets smaller than the master fall back to point sampling. +# +# Requires ImageMagick 7 (`magick`). ImageMagick writes .ico and .icns itself, +# so no extra packers are needed; icotool (icoutils) / png2icns (libicns) / +# iconutil (macOS) are higher-fidelity alternatives if you prefer them. +# +# Usage: docs/design/appicon/generate.sh [path/to/master.png] +# (default master: docs/design/appicon/umamo-icon.png) + +set -euo pipefail + +scriptDir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repoRoot="$(cd "$scriptDir/../../.." && pwd)" +master="${1:-$scriptDir/umamo-icon.png}" + +if [[ ! -f "$master" ]]; then + echo "master art not found: $master" >&2 + echo "drop the mascot PNG there (or pass its path) and re-run." >&2 + exit 1 +fi + +magick="$(command -v magick || command -v convert)" +if [[ -z "$magick" ]]; then + echo "ImageMagick (magick/convert) not found on PATH." >&2 + exit 1 +fi + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT + +# Solid backdrop composited under the opaque outputs. The mascot is black line +# art on transparency, so a filled background keeps it visible on dark taskbars and +# launchers and matches the Android adaptive background. Keep this in sync with the +# ic_launcher_background color resource (values/ic_launcher_background.xml) so a +# re-skin changes both at once. +background="white" + +# Crisp nearest-neighbor render of the master at targetEdge x targetEdge, on a +# transparent canvas, filling the frame. -filter point is pure point sampling (no +# blending), so the pixel-art edges stay hard. When the target is an integer +# multiple of the master every source pixel keeps a uniform width; the 160px master +# does not integer-divide the standard icon sizes, so filling (minor per-pixel width +# variance at large sizes) is preferred over integer-scale-plus-margin, which would +# size the mascot inconsistently across the frame set. The master is square; a +# non-square master would fit within the box (letterboxed) rather than fill. +emitTransparent() { + local targetEdge="$1" outputPath="$2" + mkdir -p "$(dirname "$outputPath")" + "$magick" "$master" -filter point -resize "${targetEdge}x${targetEdge}" "$outputPath" +} + +# As emitTransparent, but flattened onto the solid backdrop (an opaque square). +emitSquare() { + local targetEdge="$1" outputPath="$2" + mkdir -p "$(dirname "$outputPath")" + "$magick" "$master" -filter point -resize "${targetEdge}x${targetEdge}" \ + -background "$background" -flatten "$outputPath" +} + +# Opaque backdrop disc + mascot, transparent outside the circle (legacy round +# launcher bitmap). round_src is already opaque (emitSquare flattened it), so +# CopyOpacity from the circle mask just carves the disc out of the square. +emitRound() { + local targetEdge="$1" outputPath="$2" + emitSquare "$targetEdge" "$scratch/round_src.png" + "$magick" -size "${targetEdge}x${targetEdge}" xc:none -fill white \ + -draw "circle $((targetEdge/2)),$((targetEdge/2)) $((targetEdge/2)),0" \ + "$scratch/round_mask.png" + "$magick" "$scratch/round_src.png" "$scratch/round_mask.png" \ + -alpha off -compose CopyOpacity -composite "$outputPath" +} + +### Desktop -- jpackage per-OS installer icons -------------------------------- +desktopIcons="$repoRoot/app/desktop/icons" +mkdir -p "$desktopIcons" + +# Windows .ico (multi-resolution frame set). +windowsSizes=(16 24 32 48 64 128 256) +windowsFrames=() +for size in "${windowsSizes[@]}"; do + emitSquare "$size" "$scratch/ico_${size}.png" + windowsFrames+=("$scratch/ico_${size}.png") +done +"$magick" "${windowsFrames[@]}" "$desktopIcons/umamo.ico" + +# macOS .icns -- assembled directly. ImageMagick's icns writer only emits a +# single frame, and png2icns/iconutil are not reliably present, so we build the +# container ourselves: an 'icns' magic + big-endian total length, then one typed +# chunk per size (each chunk is OSType + big-endian length-incl-header + a PNG +# payload, which modern macOS reads directly). The OSType/size table mirrors the +# standard iconutil .iconset mapping (non-retina icp4/icp5 plus retina ic07..ic14). +# Reference: Apple Icon Image format (icns); iconutil iconset type codes. +icnsSizes=(16 32 64 128 256 512 1024) +for size in "${icnsSizes[@]}"; do + emitSquare "$size" "$scratch/icns_${size}.png" +done +python3 - "$desktopIcons/umamo.icns" "$scratch" <<'PY' +import os, struct, sys + +outputPath, scratchDir = sys.argv[1], sys.argv[2] +# (OSType, pixel size) in the standard iconset order. Sizes recur across types +# on purpose (icp5/ic11 both 32px, ic08/ic13 both 256px, ic09/ic14 both 512px) +# so both the point-size and its @2x retina slot are populated. +entries = [ + (b"icp4", 16), (b"icp5", 32), (b"ic11", 32), (b"ic12", 64), + (b"ic07", 128), (b"ic13", 256), (b"ic08", 256), (b"ic14", 512), + (b"ic09", 512), (b"ic10", 1024), +] +chunks = b"" +for osType, size in entries: + with open(os.path.join(scratchDir, f"icns_{size}.png"), "rb") as pngFile: + pngBytes = pngFile.read() + chunks += osType + struct.pack(">I", 8 + len(pngBytes)) + pngBytes +container = b"icns" + struct.pack(">I", 8 + len(chunks)) + chunks +with open(outputPath, "wb") as icnsFile: + icnsFile.write(container) +PY + +# Linux single PNG. +emitSquare 512 "$desktopIcons/umamo.png" + +### Desktop -- live window / taskbar icon (Compose resource) ------------------ +emitSquare 512 "$repoRoot/module/ui/src/commonMain/composeResources/drawable/app_icon.png" + +### Android -- launcher icons ------------------------------------------------- +androidRes="$repoRoot/app/android/src/main/res" + +# Legacy square/round bitmaps are 48dp; adaptive foreground layers are 108dp. +declare -A legacyEdge=( [mdpi]=48 [hdpi]=72 [xhdpi]=96 [xxhdpi]=144 [xxxhdpi]=192 ) +declare -A foregroundEdge=( [mdpi]=108 [hdpi]=162 [xhdpi]=216 [xxhdpi]=324 [xxxhdpi]=432 ) + +for density in "${!legacyEdge[@]}"; do + emitSquare "${legacyEdge[$density]}" "$androidRes/mipmap-$density/ic_launcher.png" + emitRound "${legacyEdge[$density]}" "$androidRes/mipmap-$density/ic_launcher_round.png" + + # Adaptive foreground: render the mascot (on transparency, so the adaptive + # background color shows through) into the central ~66dp safe zone of the 108dp + # layer so the OS mask (circle/squircle/etc.) never clips it. + fgEdge="${foregroundEdge[$density]}" + safeEdge=$(( fgEdge * 66 / 108 )) + emitTransparent "$safeEdge" "$scratch/fg_${density}.png" + "$magick" "$scratch/fg_${density}.png" -background none -gravity center \ + -extent "${fgEdge}x${fgEdge}" \ + "$androidRes/mipmap-$density/ic_launcher_foreground.png" +done + +echo "regenerated Umamo icons from $master" diff --git a/docs/design/appicon/umamo-icon.png b/docs/design/appicon/umamo-icon.png new file mode 100644 index 0000000..daf0c69 Binary files /dev/null and b/docs/design/appicon/umamo-icon.png differ diff --git a/docs/design/cursors/2DCursor.afdesign b/docs/design/cursors/2DCursor.afdesign new file mode 100644 index 0000000..021971b Binary files /dev/null and b/docs/design/cursors/2DCursor.afdesign differ diff --git a/docs/design/cursors/2DCursor.svg b/docs/design/cursors/2DCursor.svg new file mode 100644 index 0000000..5049433 --- /dev/null +++ b/docs/design/cursors/2DCursor.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_blade.svg b/docs/design/cursors/cursor_blade.svg new file mode 100644 index 0000000..a2f6a9b --- /dev/null +++ b/docs/design/cursors/cursor_blade.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/docs/design/cursors/cursor_both_handles.svg b/docs/design/cursors/cursor_both_handles.svg new file mode 100644 index 0000000..bf80eca --- /dev/null +++ b/docs/design/cursors/cursor_both_handles.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_crossc.svg b/docs/design/cursors/cursor_crossc.svg new file mode 100644 index 0000000..bcad586 --- /dev/null +++ b/docs/design/cursors/cursor_crossc.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_crosshair.svg b/docs/design/cursors/cursor_crosshair.svg new file mode 100644 index 0000000..bbd9bfa --- /dev/null +++ b/docs/design/cursors/cursor_crosshair.svg @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_dot.svg b/docs/design/cursors/cursor_dot.svg new file mode 100644 index 0000000..b155f5e --- /dev/null +++ b/docs/design/cursors/cursor_dot.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_e_arrow.svg b/docs/design/cursors/cursor_e_arrow.svg new file mode 100644 index 0000000..8d571ae --- /dev/null +++ b/docs/design/cursors/cursor_e_arrow.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_eraser.svg b/docs/design/cursors/cursor_eraser.svg new file mode 100644 index 0000000..02b0517 --- /dev/null +++ b/docs/design/cursors/cursor_eraser.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/docs/design/cursors/cursor_ew_scroll.svg b/docs/design/cursors/cursor_ew_scroll.svg new file mode 100644 index 0000000..47bd0f3 --- /dev/null +++ b/docs/design/cursors/cursor_ew_scroll.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_eyedropper.svg b/docs/design/cursors/cursor_eyedropper.svg new file mode 100644 index 0000000..6459887 --- /dev/null +++ b/docs/design/cursors/cursor_eyedropper.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_h_split.svg b/docs/design/cursors/cursor_h_split.svg new file mode 100644 index 0000000..2d0a34b --- /dev/null +++ b/docs/design/cursors/cursor_h_split.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_hand.svg b/docs/design/cursors/cursor_hand.svg new file mode 100644 index 0000000..d95b5fd --- /dev/null +++ b/docs/design/cursors/cursor_hand.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/docs/design/cursors/cursor_hand_closed.svg b/docs/design/cursors/cursor_hand_closed.svg new file mode 100644 index 0000000..a9c5dd7 --- /dev/null +++ b/docs/design/cursors/cursor_hand_closed.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/docs/design/cursors/cursor_hand_point.svg b/docs/design/cursors/cursor_hand_point.svg new file mode 100644 index 0000000..d902880 --- /dev/null +++ b/docs/design/cursors/cursor_hand_point.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/docs/design/cursors/cursor_knife.svg b/docs/design/cursors/cursor_knife.svg new file mode 100644 index 0000000..653f7c6 --- /dev/null +++ b/docs/design/cursors/cursor_knife.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/docs/design/cursors/cursor_left_handle.svg b/docs/design/cursors/cursor_left_handle.svg new file mode 100644 index 0000000..7b2b7a8 --- /dev/null +++ b/docs/design/cursors/cursor_left_handle.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_mute.svg b/docs/design/cursors/cursor_mute.svg new file mode 100644 index 0000000..484f52e --- /dev/null +++ b/docs/design/cursors/cursor_mute.svg @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_n_arrow.svg b/docs/design/cursors/cursor_n_arrow.svg new file mode 100644 index 0000000..6c47108 --- /dev/null +++ b/docs/design/cursors/cursor_n_arrow.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_ns_scroll.svg b/docs/design/cursors/cursor_ns_scroll.svg new file mode 100644 index 0000000..6bdb3a1 --- /dev/null +++ b/docs/design/cursors/cursor_ns_scroll.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_nsew_scroll.svg b/docs/design/cursors/cursor_nsew_scroll.svg new file mode 100644 index 0000000..adaf50a --- /dev/null +++ b/docs/design/cursors/cursor_nsew_scroll.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_paint.svg b/docs/design/cursors/cursor_paint.svg new file mode 100644 index 0000000..a931c2a --- /dev/null +++ b/docs/design/cursors/cursor_paint.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_pencil.svg b/docs/design/cursors/cursor_pencil.svg new file mode 100644 index 0000000..65581c4 --- /dev/null +++ b/docs/design/cursors/cursor_pencil.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/docs/design/cursors/cursor_pick_area.svg b/docs/design/cursors/cursor_pick_area.svg new file mode 100644 index 0000000..3eda73c --- /dev/null +++ b/docs/design/cursors/cursor_pick_area.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/docs/design/cursors/cursor_pointer.svg b/docs/design/cursors/cursor_pointer.svg new file mode 100644 index 0000000..aac08df --- /dev/null +++ b/docs/design/cursors/cursor_pointer.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/docs/design/cursors/cursor_right_handle.svg b/docs/design/cursors/cursor_right_handle.svg new file mode 100644 index 0000000..b5f4113 --- /dev/null +++ b/docs/design/cursors/cursor_right_handle.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_s_arrow.svg b/docs/design/cursors/cursor_s_arrow.svg new file mode 100644 index 0000000..494eff8 --- /dev/null +++ b/docs/design/cursors/cursor_s_arrow.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_slip.svg b/docs/design/cursors/cursor_slip.svg new file mode 100644 index 0000000..ea81732 --- /dev/null +++ b/docs/design/cursors/cursor_slip.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_stop.svg b/docs/design/cursors/cursor_stop.svg new file mode 100644 index 0000000..6471a1d --- /dev/null +++ b/docs/design/cursors/cursor_stop.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/docs/design/cursors/cursor_swap_area.svg b/docs/design/cursors/cursor_swap_area.svg new file mode 100644 index 0000000..505ad48 --- /dev/null +++ b/docs/design/cursors/cursor_swap_area.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_text_edit.svg b/docs/design/cursors/cursor_text_edit.svg new file mode 100644 index 0000000..6ad8c67 --- /dev/null +++ b/docs/design/cursors/cursor_text_edit.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/docs/design/cursors/cursor_v_split.svg b/docs/design/cursors/cursor_v_split.svg new file mode 100644 index 0000000..6716a57 --- /dev/null +++ b/docs/design/cursors/cursor_v_split.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_vertex_loop.svg b/docs/design/cursors/cursor_vertex_loop.svg new file mode 100644 index 0000000..08c031c --- /dev/null +++ b/docs/design/cursors/cursor_vertex_loop.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_w_arrow.svg b/docs/design/cursors/cursor_w_arrow.svg new file mode 100644 index 0000000..5dd3d3f --- /dev/null +++ b/docs/design/cursors/cursor_w_arrow.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/cursors/cursor_wait.svg b/docs/design/cursors/cursor_wait.svg new file mode 100644 index 0000000..a4380a5 --- /dev/null +++ b/docs/design/cursors/cursor_wait.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/docs/design/cursors/cursor_x_move.svg b/docs/design/cursors/cursor_x_move.svg new file mode 100644 index 0000000..e759d3e --- /dev/null +++ b/docs/design/cursors/cursor_x_move.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/docs/design/cursors/cursor_y_move.svg b/docs/design/cursors/cursor_y_move.svg new file mode 100644 index 0000000..c503bc9 --- /dev/null +++ b/docs/design/cursors/cursor_y_move.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/docs/design/cursors/cursor_zoom_in.svg b/docs/design/cursors/cursor_zoom_in.svg new file mode 100644 index 0000000..4692f96 --- /dev/null +++ b/docs/design/cursors/cursor_zoom_in.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/docs/design/cursors/cursor_zoom_out.svg b/docs/design/cursors/cursor_zoom_out.svg new file mode 100644 index 0000000..c124fcb --- /dev/null +++ b/docs/design/cursors/cursor_zoom_out.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/docs/design/erodozer-logo.png b/docs/design/erodozer-logo.png new file mode 100755 index 0000000..3512729 Binary files /dev/null and b/docs/design/erodozer-logo.png differ diff --git a/docs/design/icons/blender_icon_edgesel.svg b/docs/design/icons/blender_icon_edgesel.svg new file mode 100644 index 0000000..972cbf8 --- /dev/null +++ b/docs/design/icons/blender_icon_edgesel.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_editmode_hlt.svg b/docs/design/icons/blender_icon_editmode_hlt.svg new file mode 100644 index 0000000..33aede2 --- /dev/null +++ b/docs/design/icons/blender_icon_editmode_hlt.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_facesel.svg b/docs/design/icons/blender_icon_facesel.svg new file mode 100644 index 0000000..6fb71b1 --- /dev/null +++ b/docs/design/icons/blender_icon_facesel.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_object_datamode.svg b/docs/design/icons/blender_icon_object_datamode.svg new file mode 100644 index 0000000..0373a61 --- /dev/null +++ b/docs/design/icons/blender_icon_object_datamode.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_uv_edgesel.svg b/docs/design/icons/blender_icon_uv_edgesel.svg new file mode 100644 index 0000000..e7ba0e6 --- /dev/null +++ b/docs/design/icons/blender_icon_uv_edgesel.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_uv_facesel.svg b/docs/design/icons/blender_icon_uv_facesel.svg new file mode 100644 index 0000000..89fa8d1 --- /dev/null +++ b/docs/design/icons/blender_icon_uv_facesel.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_uv_vertexsel.svg b/docs/design/icons/blender_icon_uv_vertexsel.svg new file mode 100644 index 0000000..44251dd --- /dev/null +++ b/docs/design/icons/blender_icon_uv_vertexsel.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/design/icons/blender_icon_vertexsel.svg b/docs/design/icons/blender_icon_vertexsel.svg new file mode 100644 index 0000000..f4d1cce --- /dev/null +++ b/docs/design/icons/blender_icon_vertexsel.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/screenshots/readme20260717.png b/docs/screenshots/readme20260717.png new file mode 100644 index 0000000..da1b156 Binary files /dev/null and b/docs/screenshots/readme20260717.png differ diff --git a/docs/screenshots/readme20260905.webp b/docs/screenshots/readme20260905.webp new file mode 100644 index 0000000..b4cae6a Binary files /dev/null and b/docs/screenshots/readme20260905.webp differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0cb607d --- /dev/null +++ b/gradle.properties @@ -0,0 +1,15 @@ +# Gradle daemon + project-wide flags. +# Gradle デーモンとプロジェクト全体のフラグ。 + +# Give the daemon enough heap for the Kotlin + Android toolchains; pin UTF-8 so format +# parsing/encoding is host-independent. +org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8 + +# Reuse build outputs across runs. +org.gradle.caching=true +org.gradle.configuration-cache=true + +# AndroidX is mandatory for modern AGP; non-transitive R classes keep per-module R +# namespaces tight (faster, fewer clashes). +android.useAndroidX=true +android.nonTransitiveRClass=true diff --git a/gradle/build-logic/build.gradle.kts b/gradle/build-logic/build.gradle.kts new file mode 100644 index 0000000..9cd0c9b --- /dev/null +++ b/gradle/build-logic/build.gradle.kts @@ -0,0 +1,27 @@ +// Build script for the convention plugins themselves. +// +// `kotlin-dsl` turns every *.gradle.kts under src/main/kotlin into a PRECOMPILED SCRIPT PLUGIN whose +// id is the file name minus the extension — umamo.kmp-jvmandroid.gradle.kts becomes the plugin id +// `umamo.kmp-jvmandroid`. Ordinary .kt files in the same source set compile alongside them, which is +// where the shared types (see org.umamo.buildlogic) live. + +plugins { + `kotlin-dsl` +} + +// The same JDK 21 (LTS) toolchain every module pins. Without it these scripts compile against whatever +// JVM happens to be running the daemon, which is how the Java and Kotlin compile tasks end up +// disagreeing about their target level. +kotlin { + jvmToolchain(21) +} + +dependencies { + // The KMP source-set hierarchy is configured through the Kotlin Gradle Plugin's own API + // (KotlinMultiplatformExtension, the hierarchy-template DSL), so the convention plugins compile + // against it. This is the LIBRARY coordinate, not the plugin marker — build-logic configures KGP, + // it never applies it; the modules still apply `alias(libs.plugins.kotlinMultiplatform)` + // themselves. Both read the same `kotlin` version from the catalog, so the API compiled against + // and the plugin applied can never drift. + implementation(libs.kotlinGradlePlugin) +} diff --git a/gradle/build-logic/settings.gradle.kts b/gradle/build-logic/settings.gradle.kts new file mode 100644 index 0000000..96041ad --- /dev/null +++ b/gradle/build-logic/settings.gradle.kts @@ -0,0 +1,29 @@ +// Settings for the build-logic INCLUDED BUILD — the home of Umamo's convention plugins. +// +// This is a build of its own, not a subproject: the root settings pulls it in with +// `pluginManagement { includeBuild("gradle/build-logic") }`, so its plugins are resolvable by id +// from every module's `plugins {}` block. That is what makes `id("umamo.kmp-jvmandroid")` read like +// any other plugin rather than an `apply(from = …)` script with no type-safe accessors. +// +// Being a separate build, it inherits NOTHING from the root — not the repositories, not the version +// catalog. Both are re-declared below, and the catalog is the SAME FILE the modules use so a +// convention plugin can never compile against a different Kotlin than the one the modules apply. + +rootProject.name = "build-logic" + +dependencyResolutionManagement { + repositories { + mavenCentral() + // The Kotlin Gradle Plugin publishes to both; the portal is what resolves plugin markers. + gradlePluginPortal() + } + + // The one catalog, reached by relative path (this file sits in gradle/build-logic, the catalog in + // gradle/). Gradle's automatic `gradle/libs.versions.toml` discovery is relative to THIS build's + // root, which would be gradle/build-logic/gradle/ — hence the explicit `from`. + versionCatalogs { + create("libs") { + from(files("../libs.versions.toml")) + } + } +} diff --git a/gradle/build-logic/src/main/kotlin/org/umamo/buildlogic/TestCorpus.kt b/gradle/build-logic/src/main/kotlin/org/umamo/buildlogic/TestCorpus.kt new file mode 100644 index 0000000..2633030 --- /dev/null +++ b/gradle/build-logic/src/main/kotlin/org/umamo/buildlogic/TestCorpus.kt @@ -0,0 +1,201 @@ +package org.umamo.buildlogic + +import java.io.File + +/** + * One path-valued system property a module forwards to its test JVMs. + * + * @param String name The system property name, e.g. "cmo3.sample". + * @param String? corpusRelativeDefault A module-specific default, relative to test/corpus, or null to + * take whatever [sharedCorpusDefault] has for this name (which may itself be nothing, + * leaving the property explicit-`-D`-only). + */ +data class CorpusSampleProperty( + val name: String, + val corpusRelativeDefault: String?, +) + +/** + * Declares which corpus-backed system properties a module's test JVMs receive. + * + * Registered by the `umamo.test-corpus` convention plugin as `umamoTestCorpus`; see that plugin for + * the resolution rules, and org.umamo.buildlogic.sharedCorpusDefault for the shared default table. + */ +abstract class TestCorpusExtension { + /** The declared path-valued properties, in declaration order. Read by the convention plugin. */ + val sampleProperties: MutableList = mutableListOf() + + /** The declared plain flags. Read by the convention plugin. */ + val flagProperties: MutableList = mutableListOf() + + /** The test JVM heap, or null to leave Gradle's default. Read by the convention plugin. */ + var testMaxHeap: String? = null + private set + + /** + * Forwards path-valued sample properties, defaulted from the shared corpus table. + * + * A name the shared table has no entry for is still forwarded — it simply has no default, so it + * only reaches the test JVM when an explicit `-D` is passed. + * + * @param String propertyNames The system property names. + */ + fun sample(vararg propertyNames: String) { + for (propertyName in propertyNames) { + sampleProperties += CorpusSampleProperty(propertyName, null) + } + } + + /** + * Forwards one path-valued sample property with a default this module alone wants. + * + * Use this when the shared table's answer is wrong HERE — :ui's moc3.sample is the case: the other + * modules deliberately leave it explicit-only, and giving it a table entry would silently switch + * their gated tests on. + * + * @param String propertyName The system property name. + * @param String corpusRelativePath The default, relative to test/corpus. File or directory; it is + * used only when it exists, so a partial corpus still self-skips. + */ + fun sampleWithCorpusDefault( + propertyName: String, + corpusRelativePath: String, + ) { + sampleProperties += CorpusSampleProperty(propertyName, corpusRelativePath) + } + + /** + * Forwards on/off flags verbatim — no path resolution, no existence check. + * + * A flag is a switch, not a location (`-Dcmo3.generate=true`, `-Dumamo.requireGl=true`), so putting + * one through the sample path would reject it for not naming a file that exists. Forwarding is + * still the part that matters: a flag the build forgets to pass through is a test that reads a + * property nobody set and returns immediately, reporting PASSED while doing nothing. + * + * @param String propertyNames The system property names. + */ + fun flag(vararg propertyNames: String) { + flagProperties += propertyNames + } + + /** + * Sets the heap for this module's test JVMs. + * + * @param String size A JVM heap size, e.g. "4g". + */ + fun maxHeap(size: String) { + testMaxHeap = size + } +} + +/** + * The shared corpus default for [propertyName], or null when the table has no entry for it. + * + * These are the defaults that mean the same thing in every module, so they live in one place rather + * than being re-derived per build script (which is how :interop and :render came to disagree with + * :format about whether an explicit `-D` gets checked at all). + * + * @param File corpusDirectory The local golden corpus root. Gitignored, so absent on CI and on a + * fresh clone — every lookup here is allowed to come back null. + * @param String propertyName The system property name. + * @return String? The default value, or null when there is none. + */ +fun sharedCorpusDefault( + corpusDirectory: File, + propertyName: String, +): String? { + if (!corpusDirectory.isDirectory) { + return null + } + return when (propertyName) { + // Pinned to one model on purpose, for two independent reasons: :format's facade/CAFF/document + // tests assert exact counts (180 image resources, 926 CAFF entries, 158 import PIs) that only + // this model satisfies, and it is the corpus model that actually carries glue affecters, which + // is what makes :render's glue gates meaningful rather than vacuously green. + "cmo3.sample" -> corpusDirectory.resolve("cmo3/EricaTamamo.cmo3").takeIf { it.isFile }?.absolutePath + + // Every .cmo3 in the corpus, spanning Cubism 3.x/4.x/5.3. The cross-version gate wants the + // whole set, and ModelGenerator wants it for the same reason its own docblock gives: the + // generated model is the UNION over every sample, so a field or enum constant that only one + // project exercises still gets covered. Generating from one sample would silently drop the rest. + "cmo3.probe", "cmo3.gensample" -> + corpusDirectory + .resolve("cmo3") + .listFiles { candidate -> candidate.isFile && candidate.extension == "cmo3" } + ?.sortedBy { it.name } + ?.joinToString(",") { it.absolutePath } + ?.takeIf { it.isNotEmpty() } + + // The whole moc3 tree — the decode/lowering/bake/probe gates walk it. + "moc3.samples" -> corpusDirectory.resolve("moc3").takeIf { it.isDirectory }?.absolutePath + + // Deliberately absent, and worth stating: `moc3.sample` (singular). :ui defaults it to the one + // corpus family that is complete on disk, while :interop and :render want it explicit-only — + // a table entry here would switch their gated tests on as a side effect. + else -> null + } +} + +/** + * Resolves [sampleProperty] to the value handed to the test JVM, or null to leave the test skipping. + * + * Two ways a path is found, in order: + * 1. An explicit `-D` on the Gradle command line. A RELATIVE value resolves against the REPO ROOT — + * not the test JVM's working directory, which is the module. That distinction is the whole point: + * a gated test that cannot find its sample does not fail, it prints and returns, so it reports + * PASSED while doing nothing. A relative path therefore used to disable the gate in total silence. + * An explicit path that resolves to nothing fails the build outright instead. + * 2. The local golden corpus, when present — the module-specific default if it declared one, else the + * shared table. This is what makes the mandatory CMO3 round-trip gate run BY DEFAULT for anyone + * who has the corpus, rather than only when they remember the flag. + * + * Absent entirely (a fresh clone, CI) → null, the tests self-skip, and the build stays green without a + * multi-gigabyte corpus in git. That is deliberate; CI passes no sample flags. + * + * @param File repositoryRoot The repo root, which relative `-D` values resolve against. + * @param File corpusDirectory The local golden corpus root (test/corpus). + * @param CorpusSampleProperty sampleProperty The property being resolved. + * @return String? The absolute path (or comma-separated paths), or null. + */ +fun resolveCorpusSample( + repositoryRoot: File, + corpusDirectory: File, + sampleProperty: CorpusSampleProperty, +): String? { + val explicitValue = + System.getProperty(sampleProperty.name) + ?: return moduleOrSharedDefault(corpusDirectory, sampleProperty) + + // Some properties (cmo3.probe) carry a comma-separated list; resolve each element. File.resolve + // returns an absolute argument unchanged, so this handles both forms. + val resolvedValue = + explicitValue + .split(',') + .filter { it.isNotBlank() } + .joinToString(",") { path -> repositoryRoot.resolve(path.trim()).absolutePath } + // Fail loudly rather than let the gated test skip-and-pass on a typo. + for (path in resolvedValue.split(',')) { + require(File(path).exists()) { + "-D${sampleProperty.name}=$explicitValue resolves to '$path', which does not exist. " + + "Relative values resolve against the repo root ($repositoryRoot)." + } + } + return resolvedValue +} + +/** + * The default for [sampleProperty]: its own corpus-relative path when it declared one, else the table. + * + * @param File corpusDirectory The local golden corpus root. + * @param CorpusSampleProperty sampleProperty The property being defaulted. + * @return String? The absolute path, or null when there is no default or no corpus. + */ +private fun moduleOrSharedDefault( + corpusDirectory: File, + sampleProperty: CorpusSampleProperty, +): String? { + val corpusRelativeDefault = + sampleProperty.corpusRelativeDefault + ?: return sharedCorpusDefault(corpusDirectory, sampleProperty.name) + return corpusDirectory.resolve(corpusRelativeDefault).takeIf { it.exists() }?.absolutePath +} diff --git a/gradle/build-logic/src/main/kotlin/umamo.kmp-ios-gate.gradle.kts b/gradle/build-logic/src/main/kotlin/umamo.kmp-ios-gate.gradle.kts new file mode 100644 index 0000000..562a16d --- /dev/null +++ b/gradle/build-logic/src/main/kotlin/umamo.kmp-ios-gate.gradle.kts @@ -0,0 +1,20 @@ +// Convention plugin: wire a module's iosArm64 compiles into `check`, main AND test. +// +// Neither task arrives on its own. `check` reaches a target's compile only by way of a runnable test +// task, and iosArm64 is a DEVICE target with none — so the commonMain-purity guarantee a module +// carries an Apple target FOR only fired when someone typed the task name, and `./gradlew check` +// passed straight over a commonMain `java.*` leak exactly as if the target did not exist. +// +// The test source set matters as much as main, and is the half that actually broke: KraReader sat in +// commonMain importing java.util.zip while a commonTest beside it referenced a symbol only it +// declared. compileKotlinIosArm64 was green throughout — main compiled fine — and CI failed on +// compileTestKotlinIosArm64, a task no local run touched. commonTest has to build for every target +// commonMain does, so it gets the same gate. + +// `withId` so the module's `plugins {}` block order does not matter — `check` comes from the base +// plugin that Kotlin Multiplatform brings with it, so it exists by the time this fires. +plugins.withId("org.jetbrains.kotlin.multiplatform") { + tasks.named("check") { + dependsOn("compileKotlinIosArm64", "compileTestKotlinIosArm64") + } +} diff --git a/gradle/build-logic/src/main/kotlin/umamo.kmp-jvmandroid.gradle.kts b/gradle/build-logic/src/main/kotlin/umamo.kmp-jvmandroid.gradle.kts new file mode 100644 index 0000000..a42b6b0 --- /dev/null +++ b/gradle/build-logic/src/main/kotlin/umamo.kmp-jvmandroid.gradle.kts @@ -0,0 +1,61 @@ +// Convention plugin: the `jvmAndroidMain` source-set group, shared by the two JVM-based targets +// (desktop JVM + Android/ART). +// +// Some code is JVM-API-bound but must reach BOTH those targets — the JDOM + Kotlin-reflection CMO3 +// serializer in :format above all, and everything layered on it (:interop's export lowering, :ui's +// document/file layer and app shell). commonMain cannot hold it and duplicating it into jvmMain + +// androidMain would be two copies of the same file, so it lives in src/jvmAndroidMain and is shared +// verbatim. +// +// This block was copy-pasted across four build scripts and marked "[kmp-jvmandroid] keep identical" — +// which is the shape of a convention plugin written out longhand. Applied as +// `id("umamo.kmp-jvmandroid")`, after the module applies the Kotlin Multiplatform plugin. + +// The hierarchy-template DSL (`applyDefaultHierarchyTemplate {}` with a describe block) is still +// marked experimental in KGP. The module build scripts opted in implicitly by living in a Gradle +// script; say it out loud here instead of emitting five warnings per compile. +@file:OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class) + +import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension + +// `withId` rather than a bare `configure`, so the order of the module's `plugins {}` block does not +// matter: whether Kotlin Multiplatform is applied before or after this plugin, the hierarchy is set up +// the moment it arrives. +plugins.withId("org.jetbrains.kotlin.multiplatform") { + extensions.configure { + // Using a template group (rather than raw `dependsOn`) keeps the auto-wired commonMain edges + // intact and avoids the "default hierarchy not applied" warning. + applyDefaultHierarchyTemplate { + common { + group("jvmAndroid") { + withJvm() + withAndroidTarget() + } + } + } + + // The group's withAndroidTarget() above matches the LEGACY android target, not AGP 9's new KMP + // android-library target (com.android.kotlin.multiplatform.library, which is what every module + // here applies) — so androidMain never inherits the jvmAndroid group and cannot see its + // declarations or its actuals. Wire the edge explicitly. (withJvm() does match, which is why the + // JVM target compiles fine and the breakage shows up as an Android-only failure.) + // + // Keyed on whichever of the two source sets is configured LAST, because their creation order is + // not ours to pick: androidMain arrives with the android target, jvmAndroidMain when the + // hierarchy template is applied over the registered targets. Checking both directions means the + // edge lands either way, and `dependsOn` is set-valued so arriving twice is harmless. + val kotlinSourceSets = sourceSets + kotlinSourceSets.configureEach { + val configuredSourceSet = this + when (configuredSourceSet.name) { + "jvmAndroidMain" -> + kotlinSourceSets.findByName("androidMain")?.dependsOn(configuredSourceSet) + + "androidMain" -> + kotlinSourceSets.findByName("jvmAndroidMain")?.let { jvmAndroidMain -> + configuredSourceSet.dependsOn(jvmAndroidMain) + } + } + } + } +} diff --git a/gradle/build-logic/src/main/kotlin/umamo.test-corpus.gradle.kts b/gradle/build-logic/src/main/kotlin/umamo.test-corpus.gradle.kts new file mode 100644 index 0000000..b11d36d --- /dev/null +++ b/gradle/build-logic/src/main/kotlin/umamo.test-corpus.gradle.kts @@ -0,0 +1,48 @@ +// Convention plugin: forward the golden corpus and its `-D` overrides to a module's test JVMs. +// +// Five build scripts each grew their own copy of this — the same corpusDefaultFor / sample-resolution +// pair, drifted three different ways (:interop and :edit forwarded an explicit `-D` verbatim while +// :format and :render resolved and existence-checked it; the corpus default table disagreed about +// which properties even had one). Since the failure mode of getting it wrong is a gated test that +// reports PASSED while doing nothing, one implementation is worth more here than in most places. +// +// A module declares what it wants and nothing else: +// +// umamoTestCorpus { +// maxHeap("4g") +// sample("cmo3.sample", "cmo3.probe") +// sampleWithCorpusDefault("moc3.sample", "moc3/modelA/modelA.moc3") +// flag("umamo.requireGl") +// } +// +// Resolution rules (explicit `-D` wins, corpus default second, else the test self-skips) are in +// org.umamo.buildlogic.resolveCorpusSample, and the shared default table in +// org.umamo.buildlogic.sharedCorpusDefault. Read those before adding a property. + +import org.umamo.buildlogic.TestCorpusExtension +import org.umamo.buildlogic.resolveCorpusSample + +val umamoTestCorpus = extensions.create("umamoTestCorpus") + +// Captured as plain Files so the configuration cache stores values, not a project reference. +val repositoryRoot = rootDir + +/** The local golden corpus root. Gitignored, so absent on CI and on a fresh clone. */ +val corpusDirectory = rootDir.resolve("test/corpus") + +tasks.withType().configureEach { + // Read at task-realization time, which is after the module's `umamoTestCorpus { }` block has run. + umamoTestCorpus.testMaxHeap?.let { heapSize -> + maxHeapSize = heapSize + } + for (sampleProperty in umamoTestCorpus.sampleProperties) { + resolveCorpusSample(repositoryRoot, corpusDirectory, sampleProperty)?.let { resolvedValue -> + systemProperty(sampleProperty.name, resolvedValue) + } + } + for (flagName in umamoTestCorpus.flagProperties) { + System.getProperty(flagName)?.let { flagValue -> + systemProperty(flagName, flagValue) + } + } +} diff --git a/gradle/build-target.gradle.kts b/gradle/build-target.gradle.kts new file mode 100644 index 0000000..26b6484 --- /dev/null +++ b/gradle/build-target.gradle.kts @@ -0,0 +1,85 @@ +// Shared build-target resolution. Applied via `apply(from = …)` by every module that bundles +// platform-specific LWJGL natives — :desktop and :render today. It works out the "-" +// token the build is targeting (defaulting to the host), honoring -Pumamo.target to cross-resolve +// so a Windows-native artifact can be produced from, say, WSL2 Linux: +// +// ./gradlew :desktop:packageUberJarForCurrentOS -Pumamo.target=windows-x64 +// +// then launched from the Windows side. This only swaps which prebuilt natives get bundled — JVM +// bytecode is platform-independent, so there is no real cross-compiler involved. (jpackage +// installers like .msi/.dmg must still be produced ON the target OS; only a runnable uber-jar is +// portable this way.) +// +// The result is handed back to the applying module through two extra properties: +// umamoBuildTarget — the resolved "-" string (e.g. "windows-x64") +// umamoLwjglNatives — the matching LWJGL natives classifier (e.g. "natives-windows") +// +// Why centralize: both :desktop and :render bundle LWJGL natives, and host-detection logic living in +// only one place means the two can never drift apart — otherwise a Windows build could bundle one +// module's Linux natives and silently fail to launch. The Compose/Skiko side stays in :desktop alone, +// because the `compose.desktop.` accessors only resolve inside a `dependencies {}` block — +// :desktop reads umamoBuildTarget from here and maps it there. + +val osName = System.getProperty("os.name").lowercase() +val osArch = System.getProperty("os.arch").lowercase() +val hostOs = + when { + osName.contains("linux") -> "linux" + osName.contains("mac") || osName.contains("darwin") -> "macos" + else -> "windows" + } +val hostArch = + when { + osArch.contains("aarch64") || osArch.contains("arm64") -> "arm64" + else -> "x64" + } +// EN: Skiko/Compose ships no windows-arm64 build; Windows-on-ARM runs the x64 artifact emulated. +val hostTarget = + if (hostOs == "windows" && hostArch == "arm64") { + "windows-x64" + } else { + "$hostOs-$hostArch" + } + +// EN: `findProperty` reads a Gradle project property (`-Pkey=value` on the command line, or a line in +// gradle.properties); it returns null when unset, so `?:` falls back to the host. The override wins. +val requestedTarget = (findProperty("umamo.target") as String?)?.lowercase()?.trim() +val resolvedTarget = requestedTarget ?: hostTarget + +val recognizedTargets = listOf("linux-x64", "linux-arm64", "windows-x64", "macos-x64", "macos-arm64") +require(resolvedTarget in recognizedTargets) { + "Unknown -Pumamo.target='$resolvedTarget'. Recognized: ${recognizedTargets.joinToString(", ")}." +} +if (requestedTarget != null) { + logger.lifecycle("[${project.path}] resolving natives for $resolvedTarget (build host is $hostTarget)") +} + +// Release packaging must never cross-resolve. Unlike the uber jar, a jpackage app image jlinks +// the HOST JDK into itself, so a mismatched -Pumamo.target bundles one platform's Skiko/LWJGL +// natives inside another platform's runtime — an artifact that runs nowhere, and one nothing +// downstream can detect. The release workflow passes -Pumamo.target explicitly (so artifact +// names are a function of the matrix rather than of what the runner reported) AND this flag, so +// an unexpected runner os.arch fails the build instead of shipping a broken download. Same +// shape as -Dumamo.requireGl in the GL tests: opt-in, and only CI opts in. +val requireTargetIsHost = (findProperty("umamo.requireTargetIsHost") as String?).toBoolean() +require(!requireTargetIsHost || resolvedTarget == hostTarget) { + "-Pumamo.requireTargetIsHost=true, but -Pumamo.target='$resolvedTarget' is not the build host " + + "'$hostTarget'. An app image jlinks the host JDK, so cross-resolving natives here produces " + + "an artifact that runs nowhere." +} + +// EN: LWJGL publishes its per-platform natives under these classifiers (org.lwjgl:lwjgl::natives-windows, …). +val lwjglNativesClassifier = + when (resolvedTarget) { + "linux-x64" -> "natives-linux" + "linux-arm64" -> "natives-linux-arm64" + "windows-x64" -> "natives-windows" + "macos-x64" -> "natives-macos" + "macos-arm64" -> "natives-macos-arm64" + else -> error("unreachable: resolvedTarget validated above") + } + +// EN: `extra` is Gradle's per-project untyped property bag; the applying module reads these back with +// `extra["umamoBuildTarget"] as String`. This is how an `apply(from =)` script returns values. +extra["umamoBuildTarget"] = resolvedTarget +extra["umamoLwjglNatives"] = lwjglNativesClassifier diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000..63e5bbd --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,2 @@ +#This file is generated by updateDaemonJvm +toolchainVersion=21 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..17da93b --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,113 @@ +# Version catalog — single source of truth for dependency + plugin versions. +# バージョンカタログ:依存とプラグインのバージョンを一元管理する。 +# Why: Gradle's typed `libs.*` accessors beat scattered string versions in each +# build script — one place to bump, compile-checked references. +[versions] +kotlin = "2.4.20" +agp = "9.3.0" +composeMultiplatform = "1.11.1" +ktlint = "14.2.0" +lwjgl = "3.4.2" +androidxActivity = "1.13.0" +# JDOM 1.x (package org.jdom) — the exact XML library the Cubism editor uses. Pinned to 1.1.x +# so XMLOutputter + Format.getPrettyFormat() reproduce main.xml byte-for-byte; JDOM2 (org.jdom2) +# would re-order/re-format and break the round-trip. See docs/formats/CMO3.md §3. +jdom = "1.1.3" +kotlinxSerialization = "1.11.0" +# okio — the de-facto multiplatform filesystem (Kotlin stdlib has no common File). Backs :storage's +# file IO on desktop + Android with one API, and FakeFileSystem makes :settings testable with no disk. +okio = "3.17.0" +# kotlinx-coroutines — for :settings' change-event SharedFlow (the reactive spine the UI/History want). +kotlinxCoroutines = "1.11.0" +# kotlinx-datetime — the local wall clock the CAFF zip timestamp needs. The Kotlin stdlib has a common +# Clock but no time ZONE, and a DOS timestamp is local time, so this is the smallest thing that closes +# the gap without reintroducing an expect/actual. See docs/formats/CMO3.md §1. +kotlinxDatetime = "0.8.0" +# FileKit — multiplatform native file pickers (desktop + Android one API). Replaces the AWT FileDialog +# in :storage so the picker is OS-native everywhere and Android SAF comes for free. See module/storage. +filekit = "0.14.2" +# JNA — desktop-only FFI for small Win32 calls (e.g. the DWM title-bar tint via dwmapi.dll). Already on +# the desktop runtime classpath transitively (FileKit's native dialogs use it); pinned to FileKit's +# version and declared explicitly so :desktop can compile against it without a resolution bump. +jna = "5.19.1" +# SQLDelight — typed access to the embedded SQLite layer table in a .clip file. +sqldelight = "2.3.2" +# poly2tri — constrained Delaunay triangulation (JVM/Android). Used by Add Vertex Accept so closed +# draft rings zigzag instead of cascading ears along the boundary. +poly2tri = "0.7.0" + +# Android SDK levels (referenced from each android target). +android-compileSdk = "37" +android-minSdk = "26" +android-targetSdk = "37" + +[libraries] +# --- LWJGL (desktop GPU): managed via the BOM so module versions stay aligned. --- +lwjgl-bom = { module = "org.lwjgl:lwjgl-bom", version.ref = "lwjgl" } +lwjgl-core = { module = "org.lwjgl:lwjgl" } +lwjgl-opengl = { module = "org.lwjgl:lwjgl-opengl" } +# GLFW: a hidden-window GL context — the desktop app's offscreen viewport renderer and the +# :render GPU-vs-CPU transform-feedback test both create their contexts through it. +lwjgl-glfw = { module = "org.lwjgl:lwjgl-glfw" } + +# AndroidX Activity + Compose interop: provides ComponentActivity.setContent { } for the +# Android app entrypoint (not covered by the Compose MP `compose.*` accessors). +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidxActivity" } + +# Compose Multiplatform artifacts as direct coordinates. The `compose.*` Gradle-plugin aliases +# (compose.runtime, compose.ui, …) were deprecated in CMP 1.10/1.11 — the warning literally says +# "Specify dependency directly". These org.jetbrains.compose artifacts still carry Gradle module +# metadata that redirects to androidx.compose.* on the Android target, so per-target resolution is +# unchanged; only the alias DSL went away. Kebab names map to nested accessors, so the call sites +# read identically: `libs.compose.runtime`, `libs.compose.components.resources`, etc. +compose-runtime = { module = "org.jetbrains.compose.runtime:runtime", version.ref = "composeMultiplatform" } +compose-foundation = { module = "org.jetbrains.compose.foundation:foundation", version.ref = "composeMultiplatform" } +compose-ui = { module = "org.jetbrains.compose.ui:ui", version.ref = "composeMultiplatform" } +# Compose UI testing. The keyform sheet's lane resolves tap-versus-drag from one raw pointer stream, which +# no unit test over pure functions can cover - only a real composition with real pointer input can. +compose-ui-test = { module = "org.jetbrains.compose.ui:ui-test", version.ref = "composeMultiplatform" } +compose-ui-test-junit4 = { module = "org.jetbrains.compose.ui:ui-test-junit4", version.ref = "composeMultiplatform" } +compose-components-resources = { module = "org.jetbrains.compose.components:components-resources", version.ref = "composeMultiplatform" } + +# JDOM 1.x — main.xml read/write for the CMO3 serializer (jvmAndroidMain; works on Android via JAXP). +jdom = { module = "org.jdom:jdom", version.ref = "jdom" } +kotlinxSerializationJson = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerialization" } +okio = { module = "com.squareup.okio:okio", version.ref = "okio" } +# okio's in-memory FileSystem for tests — :settings unit tests run with no real disk. +okio-fakefilesystem = { module = "com.squareup.okio:okio-fakefilesystem", version.ref = "okio" } +kotlinxCoroutinesCore = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } +kotlinxDatetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinxDatetime" } +kotlinxCoroutinesTest = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" } +# FileKit dialogs — open/save pickers (FileKit.openFilePicker/openFileSaver) plus the PlatformFile type +# the FilePicker contract returns. Pulls filekit-core transitively; multiplatform (jvm + android). +filekitDialogs = { module = "io.github.vinceglb:filekit-dialogs", version.ref = "filekit" } +# JNA — small Win32 FFI from :desktop (DWM caption-color tinting). See the version note above. +jna = { module = "net.java.dev.jna:jna", version.ref = "jna" } +# SQLDelight SQLite drivers: JVM JdbcSqliteDriver +sqldelightSqliteDriver = { module = "app.cash.sqldelight:sqlite-driver", version.ref = "sqldelight" } +sqldelightAndroidDriver = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" } +# SQLDelight's Kotlin/Native driver (SQLiter), for CLIP on iPadOS — Clip Studio Paint runs on iPad, +# so CLIP ingest is the native path that actually matters. Publishes iosArm64 alongside the rest. +sqldelightNativeDriver = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" } + +# The Kotlin Gradle Plugin as a LIBRARY coordinate, not a plugin marker: gradle/build-logic's +# convention plugins CONFIGURE KMP (KotlinMultiplatformExtension, the source-set hierarchy DSL) rather +# than applying it, so they need its API on their compile classpath. Same `kotlin` version ref the +# modules apply, so what build-logic compiles against and what the modules get can never drift. +kotlinGradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } +poly2tri = { module = "org.orbisgis:poly2tri", version.ref = "poly2tri" } + +[plugins] +kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +# Since Kotlin 2.0 the Compose compiler ships as a Kotlin Gradle plugin, version-locked +# to Kotlin itself (replaces the old standalone composeCompiler version matrix). +composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "composeMultiplatform" } +androidApplication = { id = "com.android.application", version.ref = "agp" } +# Modern KMP-aware Android library plugin (declare `android {}` inside `kotlin {}`), +# the AGP-recommended replacement for `com.android.library` + manual androidTarget(). +androidKmpLibrary = { id = "com.android.kotlin.multiplatform.library", version.ref = "agp" } +ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlint" } +kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +# SQLDelight code-gen plugin — generates the typed CLIP database from module/format .sq files. +sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" } diff --git a/gradle/project-version.gradle.kts b/gradle/project-version.gradle.kts new file mode 100644 index 0000000..4b32938 --- /dev/null +++ b/gradle/project-version.gradle.kts @@ -0,0 +1,28 @@ +// EN: Shared application-version resolution. Applied via `apply(from = …)` by the app modules that +// stamp a version onto an artifact — :desktop (uber-jar name, jpackage packageVersion) and +// :android (versionName). ProjectInfo.kt IS the version (its docblock forbids a second +// definition), so this script parses the constant out of the source at configuration time +// rather than declaring its own. providers.fileContents (not File.readText) so the +// configuration cache tracks the file as an input and invalidates when the version changes. +// +// The result is handed back to the applying module through two extra properties: +// umamoVersion — the full string, e.g. "0.1.0-dev" (jar names, Android versionName) +// umamoVersionNumeric — the prerelease-stripped MAJOR.MINOR.PATCH, e.g. "0.1.0" (jpackage +// rejects suffixes, so native installers get the numeric form) +// JA: 共有のアプリバージョン解決スクリプト。ProjectInfo.kt の VERSION 定数を設定時に読み取り、 +// umamoVersion(完全な文字列)と umamoVersionNumeric(数値のみ)を extra で返す。 + +val projectInfoFile = + rootProject.layout.projectDirectory.file("module/ui/src/commonMain/kotlin/org/umamo/ui/help/ProjectInfo.kt") +val projectInfoText = providers.fileContents(projectInfoFile).asText.get() +val versionMatch = + Regex("""VERSION\s*=\s*"([^"]+)"""").find(projectInfoText) + ?: error("ProjectInfo.kt: VERSION constant not found; the build derives its version from it") +val fullVersion = versionMatch.groupValues[1] +val numericVersion = fullVersion.substringBefore('-') +require(numericVersion.matches(Regex("""\d+\.\d+\.\d+"""))) { + "ProjectInfo.VERSION '$fullVersion' does not start with numeric MAJOR.MINOR.PATCH" +} + +extra["umamoVersion"] = fullVersion +extra["umamoVersionNumeric"] = numericVersion diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a9db115 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..b9bb139 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aa5f10b --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/module/edit/build.gradle.kts b/module/edit/build.gradle.kts new file mode 100644 index 0000000..b8c3c74 --- /dev/null +++ b/module/edit/build.gradle.kts @@ -0,0 +1,74 @@ +// :edit — editing session, undo/redo history, and the pure model-mutation transforms. Depends on +// :runtime (the immutable PuppetModel it snapshots and transforms). Holds no Compose: it is the +// platform-neutral editing core that both :ui and the apps drive, so it stays Android-sharable. +// :edit — 編集セッション・取り消し/やり直し履歴・純粋なモデル変換。:runtime に依存。Compose は持たない。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + // Shared jvmAndroidMain for poly2tri (CDT used by Add Vertex Accept). + id("umamo.kmp-jvmandroid") + // The corpus/-D forwarding for the export round-trip gate, configured by `umamoTestCorpus` below. + id("umamo.test-corpus") +} + +kotlin { + jvmToolchain(21) + + jvm() + + android { + namespace = "org.umamo.edit" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + // Created by umamo.kmp-jvmandroid; holds poly2tri actuals shared by desktop JVM + Android. + val jvmAndroidMain = getByName("jvmAndroidMain") + + commonMain { + dependencies { + // `api` (not `implementation`): PuppetModel and the typed ids appear in :edit's public + // surface (EditorSession exposes StateFlow, Change carries ids), so consumers + // (:ui, apps) see :runtime — and transitively :format — without re-declaring it. + api(project(":runtime")) + // `api`: StateFlow / SharedFlow are part of EditorSession's public surface, so a consumer + // that collects them needs the coroutines types visible transitively. + api(libs.kotlinxCoroutinesCore) + // Diagnostics (UmamoLog) for Accept / topology paths the Logs panel surfaces. + implementation(project(":storage")) + } + } + jvmAndroidMain.dependencies { + // Constrained Delaunay — zigzag diagonals on closed draft rings at Accept. + implementation(libs.poly2tri) + } + commonTest { + dependencies { + implementation(kotlin("test")) + } + } + jvmTest { + dependencies { + // The CMO3 export round-trip gate drives real :edit session ops over a corpus model, + // then re-reads the re-emitted file through the JVM-only codec. The conversion entry + // points (Cmo3Import / Cmo3Export) live in :interop, whose api(:format) also supplies + // the jvmAndroidMain codec surface transitively. + implementation(kotlin("test")) + implementation(project(":interop")) + // Lattice overlay mapping (warpLatticeLocalAt / warpLatticeSpaceMapping) for create-warp + // viewport diagnostics against corpus models. + implementation(project(":render")) + } + } + } +} + +// Corpus paths for the export round-trip gate (the `umamo.test-corpus` convention plugin): explicit -D +// wins, the local golden corpus is the default, and CI (no corpus, no flags) self-skips. +umamoTestCorpus { + // The round-trip gate inflates corpus CMO3s (multi-megabyte JDOM); match :format's test heap. + maxHeap("4g") + sample("cmo3.sample", "cmo3.probe") +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ActiveSelectTool.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ActiveSelectTool.kt new file mode 100644 index 0000000..71bfc08 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ActiveSelectTool.kt @@ -0,0 +1,124 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId + +/** The brush radius (viewport px) a freshly armed Circle-select tool starts at. */ +const val DEFAULT_CIRCLE_RADIUS_PX: Float = 40f + +/** The smallest Circle-select brush radius (viewport px); the wheel / numpad clamp to it. */ +const val MIN_CIRCLE_RADIUS_PX: Float = 5f + +/** The largest Circle-select brush radius (viewport px); the wheel / numpad clamp to it. */ +const val MAX_CIRCLE_RADIUS_PX: Float = 500f + +/** How much one wheel notch or numpad +/- press changes the Circle-select radius (viewport px). */ +const val CIRCLE_RADIUS_STEP_PX: Float = 8f + +/** + * One endpoint of a staged Add Vertex draft edge: either an existing mesh vertex or a draft vert index. + */ +sealed interface DraftEndpoint { + /** An existing mesh vertex that the draft chain touches. */ + data class Existing(val vertexIndex: Int) : DraftEndpoint + + /** A floating draft vertex (index into [ActiveSelectTool.AddVertex.verts]). */ + data class Draft(val index: Int) : DraftEndpoint +} + +/** + * An undirected draft edge between two [DraftEndpoint]s (canonicalized so [a] <= [b] by kind then index). + * + * @property DraftEndpoint a One endpoint. + * @property DraftEndpoint b The other endpoint. + */ +data class DraftEdge(val a: DraftEndpoint, val b: DraftEndpoint) { + companion object { + /** + * Builds a canonical undirected draft edge for two endpoints in either order. + * + * @return DraftEdge? The edge, or null when both ends are the same endpoint. + */ + fun of(endpointA: DraftEndpoint, endpointB: DraftEndpoint): DraftEdge? { + if (endpointA == endpointB) { + return null + } + return if (endpointRank(endpointA) <= endpointRank(endpointB)) { + DraftEdge(endpointA, endpointB) + } else { + DraftEdge(endpointB, endpointA) + } + } + + private fun endpointRank(endpoint: DraftEndpoint): Long = + when (endpoint) { + is DraftEndpoint.Existing -> endpoint.vertexIndex.toLong() + is DraftEndpoint.Draft -> (1L shl 32) or endpoint.index.toLong() + } + } +} + +/** + * One staged floating vertex in an Add Vertex draft: a free world point, or snapped to an existing edge. + * + * @property Float x World x. + * @property Float y World y. + * @property MeshElement.Edge? snapEdge The edge this vert snaps to, or null for a free float. + * @property Float snapT The parameter along [snapEdge] (ignored when free). + */ +data class DraftVert( + val x: Float, + val y: Float, + val snapEdge: MeshElement.Edge? = null, + val snapT: Float = 0.5f, +) + +/** + * A latched Edit-mode selection / geometry tool the gizmo overlay drives - the selection-gesture analog of + * [MeshOperatorKind]. Null when no tool is armed (a plain click selects and an empty drag rubber-bands a + * box); a command latches one and the overlay reads it to reinterpret pointer input. Transient editor + * state, never snapshotted and never on the change bus, exactly like [EditorSession.activeMeshOperator]. + */ +sealed interface ActiveSelectTool { + /** + * The viewport area that armed the tool (an opaque workspace-leaf id, the [ActiveOperator] + * currency): only the arming area's overlay drives the gesture, so an armed brush in one split + * viewport stays inert everywhere else. + */ + val areaId: String + + /** + * Blender's B box select: the overlay shows full-viewport crosshair guides and the next drag rubber-bands + * a box (ignoring element hit-tests), then the tool disarms (one-shot). + * + * @property String areaId The arming viewport's area id. + */ + data class BoxArmed(override val areaId: String) : ActiveSelectTool + + /** + * Blender's C circle select: a brush circle of [radiusPx] follows the cursor; a primary drag paints + * selection, a middle or Shift+primary drag erases, the wheel and numpad +/- resize it, and Esc / RMB / + * Enter leave the tool. + * + * @property Float radiusPx The brush radius in viewport pixels. + * @property String areaId The arming viewport's area id. + */ + data class Circle(val radiusPx: Float, override val areaId: String) : ActiveSelectTool + + /** + * Cubism-style Add Vertex draft: clicks place floating verts (auto-edged from the tip) without touching + * the document; Enter accepts into the mesh; Esc / empty RMB discards; RMB on a draft vert deletes it. + * + * @property String areaId The arming viewport's area id. + * @property DrawableId drawableId The session mesh the draft targets. + * @property List verts Staged floating verts (document-untouched). + * @property List edges Auto-chained draft edges between tips. + * @property DraftEndpoint? tip The chain tip for the next auto-edge, or null before the first click. + */ + data class AddVertex( + override val areaId: String, + val drawableId: DrawableId, + val verts: List = emptyList(), + val edges: List = emptyList(), + val tip: DraftEndpoint? = null, + ) : ActiveSelectTool +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/AtlasPlacementTransforms.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/AtlasPlacementTransforms.kt new file mode 100644 index 0000000..a4fc039 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/AtlasPlacementTransforms.kt @@ -0,0 +1,193 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.composeAffine +import org.umamo.runtime.model.placementAffine +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.hypot +import kotlin.math.sin + +/* + * The placement gizmo's model math: how a gesture affine measured on the page rewrites one tile's + * translation / rotation / scale, the page-space affines the three operators build, and which tiles + * a selection moves. Pure over :runtime, so the overlay that drives the gesture, the commit, and the + * tests all read one algebra - a placement written by one rule and previewed by another is exactly the + * drift the gizmo must not have. + * + * Every affine here is the runtime's 2x3 row-major form (m00, m01, m02, m10, m11, m12) over PAGE + * pixels, y down, the frame AtlasPlacement is expressed in. + */ + +/** + * How far from orthogonal a composed affine's axes may be (normalized) before it stops being a + * translation / rotation / scale and becomes a shear no placement can express. + */ +private const val PLACEMENT_SHEAR_TOLERANCE = 1e-4f + +/** + * This placement with [pageAffine] applied on top - the placement whose forward transform is + * `pageAffine . placementAffine(this)` - or null when that product is not a placement. + * + * A placement is translation / rotation / scale and nothing else, so only a similarity (translate, + * rotate, uniform scale) or a scale along the tile's own axes composes onto one exactly; a non-uniform + * scale along the page's axes shears a rotated tile, which no placement can carry. Refusing beats + * writing the closest placement, which would visibly re-point every mesh bound to the tile. + * + * The scale signs follow the receiver's, so a mirrored import stays mirrored through a move rather + * than flipping into a half-turn with positive scales (both describe the same pixels, but the export + * should write the file's own convention back). The rotation comes back normalized to (-180, 180]. + * + * @param FloatArray pageAffine The gesture's transform in page pixels, applied after the placement. + * @return AtlasPlacement? The composed placement, or null when the product is not TRS-expressible or + * degenerate. + */ +fun AtlasPlacement.composedWith(pageAffine: FloatArray): AtlasPlacement? { + val composed = composeAffine(pageAffine, placementAffine(this)) + val columnX0 = composed[0] + val columnX1 = composed[3] + val columnY0 = composed[1] + val columnY1 = composed[4] + val lengthX = hypot(columnX0, columnX1) + val lengthY = hypot(columnY0, columnY1) + if (lengthX == 0f || lengthY == 0f) { + return null + } + // The two columns are the rotated, scaled unit axes; a placement keeps them perpendicular. + val shear = abs(columnX0 * columnY0 + columnX1 * columnY1) / (lengthX * lengthY) + if (shear > PLACEMENT_SHEAR_TOLERANCE) { + return null + } + // The rotation is read off the x axis, negated back when that axis carries a mirror so the + // receiver's sign convention survives; the y scale is then the y axis projected onto the rotated + // y direction, which carries its own sign. + val signX = if (scaleX < 0f) -1f else 1f + val radians = atan2(columnX1 * signX, columnX0 * signX) + val cosine = cos(radians) + val sine = sin(radians) + val scaleYSigned = columnY1 * cosine - columnY0 * sine + return AtlasPlacement( + pageIndex = pageIndex, + positionX = composed[2], + positionY = composed[5], + scaleX = lengthX * signX, + scaleY = scaleYSigned, + rotationDegrees = (radians * 180.0 / PI).toFloat(), + ) +} + +/** + * The page-space translation by ([deltaX], [deltaY]). + * + * @param Float deltaX The horizontal move in page pixels. + * @param Float deltaY The vertical move in page pixels (positive is down). + * @return FloatArray The affine. + */ +fun translationAffine(deltaX: Float, deltaY: Float): FloatArray = floatArrayOf(1f, 0f, deltaX, 0f, 1f, deltaY) + +/** + * The page-space rotation by [radians] about ([pivotX], [pivotY]), in the same sense + * [AtlasPlacement.rotationDegrees] uses - composing this onto a placement adds the angle to it. + * + * @param Float pivotX The pivot's x in page pixels. + * @param Float pivotY The pivot's y in page pixels. + * @param Float radians The angle. + * @return FloatArray The affine. + */ +fun rotationAboutAffine(pivotX: Float, pivotY: Float, radians: Float): FloatArray { + val cosine = cos(radians) + val sine = sin(radians) + return floatArrayOf( + cosine, + -sine, + pivotX - cosine * pivotX + sine * pivotY, + sine, + cosine, + pivotY - sine * pivotX - cosine * pivotY, + ) +} + +/** + * The page-space scale by ([factorX], [factorY]) about ([pivotX], [pivotY]), along the PAGE axes. + * Only a uniform factor composes onto a rotated placement; the axis-locked form for a rotated tile is + * [localAxisScaleAboutAffine]. + * + * @param Float pivotX The pivot's x in page pixels. + * @param Float pivotY The pivot's y in page pixels. + * @param Float factorX The horizontal factor. + * @param Float factorY The vertical factor. + * @return FloatArray The affine. + */ +fun scaleAboutAffine(pivotX: Float, pivotY: Float, factorX: Float, factorY: Float): FloatArray = + floatArrayOf(factorX, 0f, pivotX - factorX * pivotX, 0f, factorY, pivotY - factorY * pivotY) + +/** + * The page-space scale by ([factorX], [factorY]) about ([pivotX], [pivotY]) along [placement]'s OWN + * axes: `T(P) . R(rotation) . diag(factorX, factorY) . R(-rotation) . T(-P)`. This is the one + * axis-locked scale a rotated placement can express - it multiplies the placement's own scale pair and + * leaves its rotation alone - and for an unrotated placement it is the page-axis scale exactly. + * + * @param AtlasPlacement placement The placement whose axes the factors follow. + * @param Float pivotX The pivot's x in page pixels. + * @param Float pivotY The pivot's y in page pixels. + * @param Float factorX The factor along the tile's x axis. + * @param Float factorY The factor along the tile's y axis. + * @return FloatArray The affine. + */ +fun localAxisScaleAboutAffine( + placement: AtlasPlacement, + pivotX: Float, + pivotY: Float, + factorX: Float, + factorY: Float, +): FloatArray { + val radians = (placement.rotationDegrees.toDouble() * PI / 180.0).toFloat() + val intoTileAxes = rotationAboutAffine(pivotX, pivotY, -radians) + val scaled = scaleAboutAffine(pivotX, pivotY, factorX, factorY) + val outOfTileAxes = rotationAboutAffine(pivotX, pivotY, radians) + return composeAffine(outOfTileAxes, composeAffine(scaled, intoTileAxes)) +} + +/** + * The placed tiles under [selection]: every selected drawable's tile that is packed onto a page, + * pinned or not, in document order. A drawable over unpacked art has nothing on a page, and a part + * or deformer in the selection contributes nothing. The pin commands' domain - Unpin must find the + * pinned tiles - where a gesture reads the narrower [placementDragTileIds]. + * + * @param Selection selection The session's object selection. + * @return Set The placed tiles the selection covers, empty when there are none. + */ +fun PuppetModel.placementSelectedTileIds(selection: Selection): Set { + val selectedIds = selection.targets.mapNotNullTo(HashSet()) { target -> (target as? SelectionTarget.Drawable)?.id } + if (selectedIds.isEmpty()) { + return emptySet() + } + val tileIds = LinkedHashSet() + for (drawable in drawables) { + if (drawable.id !in selectedIds) { + continue + } + val tileId = drawable.atlasTileId ?: continue + if (atlas.tileById[tileId]?.placement == null) { + continue + } + tileIds.add(tileId) + } + return tileIds +} + +/** + * The tiles a placement gesture over [selection] moves: the placed tiles under it + * ([placementSelectedTileIds]) minus the pinned ones. A pin means "keep this where it is", and a + * hand move is no exception - a pinned tile stays put until it is unpinned, and a gesture over a + * mixed selection moves the rest around it. + * + * @param Selection selection The session's object selection. + * @return Set The movable placed tiles the selection covers, empty when there are none. + */ +fun PuppetModel.placementDragTileIds(selection: Selection): Set = + placementSelectedTileIds(selection).filterTo(LinkedHashSet()) { tileId -> atlas.tileById[tileId]?.pinned != true } \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/Change.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/Change.kt new file mode 100644 index 0000000..1305a06 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/Change.kt @@ -0,0 +1,1121 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.RuntimeTarget + +/** + * How a [Change] participates in undo. Reconciles the two channels a mutation feeds: the change-event + * bus (everything emits) and the undo stack (only a subset are steps). A change declares one of these, + * so the [EditorSession] knows whether to push a history step without the call site hardcoding it. + */ +sealed interface Undoability { + /** Pushes its own history step. The common case (rename, reparent, visibility, a selection gesture). */ + object Undoable : Undoability + + /** + * Pushes a step, but a run that shares [key] within one gesture merges into a single step (a slider + * scrub, a continuous brush drag). Reserved for gestures like these; no call site produces a + * [Coalescing] change yet. + * + * @property String key The coalescing identity; consecutive changes sharing it merge. + */ + data class Coalescing(val key: String) : Undoability + + /** Emits on the change bus but is never a history step (a tool/brush switch, a live preview frame). */ + object Transient : Undoability +} + +/** + * A described edit. Carries the description of what changed — not how to undo it — because undo is by + * immutable snapshot, not by inverse op (see [History]). Every mutation emits a [Change] on the + * session's change bus; the [undoability] decides whether it also becomes a history step, and [labelKey] + * is a stable key the UI resolves to a localized history-panel label (kept here as a string so :edit + * stays free of Compose resources). + */ +sealed interface Change { + /** Whether this change is a history step, and how it coalesces. */ + val undoability: Undoability + + /** A stable key the UI maps to a localized history-panel / Edit-menu label. */ + val labelKey: String +} + +/** Changes to a part (the organizational tree node). */ +sealed interface PartChange : Change { + /** + * Toggles a part's Parts-panel eyeball. Cascades at render time (hiding a part hides its subtree), + * but the stored change is just this one part's flag. + * + * @property PartId id The part whose visibility changed. + * @property Boolean visible The new visibility. + */ + data class SetVisibility(val id: PartId, val visible: Boolean) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.visibility" + } + + /** + * Renames a part. + * + * @property PartId id The renamed part. + * @property String to The new name. + */ + data class Rename(val id: PartId, val to: String) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.rename" + } + + /** + * Toggles whether a part is viewport-selectable. + * + * @property PartId id The part whose selectability changed. + * @property Boolean selectable The new selectable state. + */ + data class SetSelectable(val id: PartId, val selectable: Boolean) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.selectable" + } + + /** + * Moves a part within the hierarchy (reparent and / or reorder among siblings). + * + * @property PartId id The moved part. + * @property PartId? toParentId The destination parent, or null for the top level. + * @property PartId? beforeId The sibling it was inserted before, or null when appended. + */ + data class Move(val id: PartId, val toParentId: PartId?, val beforeId: PartId?) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.move" + } + + /** + * Deletes a part. A cascade removes the whole subtree (the part, descendant parts, and their drawables); + * an ungroup removes only the folder and re-homes its contents up one level. + * + * @property PartId id The deleted part. + * @property Boolean cascade True for a subtree delete, false for an ungroup. + */ + data class Delete(val id: PartId, val cascade: Boolean) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.delete" + } + + /** + * Toggles a part's guide-image (sketch) flag - an editor-only reference overlay, excluded from + * runtime (MOC3) export. + * + * @property PartId id The part whose sketch flag changed. + * @property Boolean sketch The new sketch state. + */ + data class SetSketch(val id: PartId, val sketch: Boolean) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.sketch" + } + + /** + * Sets a part's own draw order (the sort key for its slot when it is grouped or isolated). + * + * @property PartId id The part whose draw order changed. + * @property Int order The new draw order. + */ + data class SetDrawOrder(val id: PartId, val order: Int) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.drawOrder" + } + + /** + * Sets a part's rendering group mode (PassThrough / Grouped / Isolated), carrying the whole mode + * value - an Isolated switch brings its full composite, so one change covers a mode swap and any + * composite sub-field edit alike. + * + * @property PartId id The part whose group mode changed. + * @property PartGroupMode mode The new group mode. + */ + data class SetGroupMode(val id: PartId, val mode: PartGroupMode) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.groupMode" + } + + /** + * Sets a part's compositing settings (opacity / blend / alpha / mask), stored latently regardless of + * group mode - so an isolated part's composite survives leaving and re-entering Isolated. Applied only + * while the part is Isolated. + * + * @property PartId id The part whose composite changed. + * @property PartComposite composite The new composite settings. + */ + data class SetComposite(val id: PartId, val composite: PartComposite) : PartChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.part.composite" + } +} + +/** Changes to a drawable (an art mesh). */ +sealed interface DrawableChange : Change { + /** + * Toggles a drawable's own Parts-panel eyeball. + * + * @property DrawableId id The drawable whose visibility changed. + * @property Boolean visible The new visibility. + */ + data class SetVisibility(val id: DrawableId, val visible: Boolean) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.visibility" + } + + /** + * Renames a drawable. + * + * @property DrawableId id The renamed drawable. + * @property String to The new name. + */ + data class Rename(val id: DrawableId, val to: String) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.rename" + } + + /** + * Toggles whether a drawable is viewport-selectable. + * + * @property DrawableId id The drawable whose selectability changed. + * @property Boolean selectable The new selectable state. + */ + data class SetSelectable(val id: DrawableId, val selectable: Boolean) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.selectable" + } + + /** + * Moves a drawable in the organizational tree: to a new owning part (null = the root level) and / or a + * new position among its siblings. Because the parts-panel order is also the draw-order tiebreak, this + * can change draw order, so the viewport follows. + * + * @property DrawableId id The moved drawable. + * @property PartId? toPartId The destination part, or null for the root level. + */ + data class Move(val id: DrawableId, val toPartId: PartId?) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.move" + } + + /** + * Duplicates whole drawables (Object-mode Shift+D): each copy gets a fresh id and name, sits after + * its source in the org tree, and carries no glue membership. + * + * @property List ids The created copies. + */ + data class Duplicate(val ids: List) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.duplicate" + } + + /** + * Deletes a drawable (and scrubs its mask / glue / render references). + * + * @property DrawableId id The deleted drawable. + */ + data class Delete(val id: DrawableId) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.delete" + } + + /** + * Sets a drawable's color blend mode. + * + * @property DrawableId id The drawable whose blend mode changed. + * @property BlendMode mode The new blend mode. + */ + data class SetBlendMode(val id: DrawableId, val mode: BlendMode) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.blendMode" + } + + /** + * Sets a drawable's alpha blend mode (Cubism 5.3's Porter-Duff-style alpha compositing). + * + * @property DrawableId id The drawable whose alpha blend mode changed. + * @property AlphaBlendMode mode The new alpha blend mode. + */ + data class SetAlphaBlendMode(val id: DrawableId, val mode: AlphaBlendMode) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.alphaBlendMode" + } + + /** + * Toggles a drawable's back-face culling (false = double-sided, Cubism's default). + * + * @property DrawableId id The drawable whose culling changed. + * @property Boolean culling The new culling state. + */ + data class SetCulling(val id: DrawableId, val culling: Boolean) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.culling" + } + + /** + * Toggles whether a drawable's clipping mask is inverted (the drawable shows outside the mask + * coverage instead of inside). + * + * @property DrawableId id The drawable whose mask inversion changed. + * @property Boolean invert The new inverted state. + */ + data class SetInvertMask(val id: DrawableId, val invert: Boolean) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.invertMask" + } + + /** + * Binds a drawable to the deformer that deforms it (or unbinds it). This is a cross-link, not a tree + * edge - a drawable is never a child of a deformer in the org tree - so it is a flat field write with + * no hierarchy surgery and no draw-order rederive. + * + * @property DrawableId id The drawable being rebound. + * @property DeformerId? parentDeformerId The deformer that now deforms it, or null to unbind. + */ + data class SetParentDeformer(val id: DrawableId, val parentDeformerId: DeformerId?) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.parentDeformer" + } + + /** + * Replaces the whole list of drawables whose alpha clips this one. The list flows as one value, so + * adding or removing a single mask is one undo step. + * + * @property DrawableId id The drawable whose mask list changed. + * @property List maskedBy The drawables that now clip it. + */ + data class SetMaskedBy(val id: DrawableId, val maskedBy: List) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.maskedBy" + } + + /** + * Sets a drawable's static opacity - the value its opacity channel falls back to when unkeyed. + * + * @property DrawableId id The retargeted drawable. + * @property Float opacity The new opacity, 0..1. + */ + data class SetOpacity(val id: DrawableId, val opacity: Float) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.opacity" + } + + /** + * Sets a drawable's static draw order - the value its draw-order channel falls back to when unkeyed. + * + * Does NOT re-derive the render root: unlike a part's draw order, a drawable's is resolved per pose at + * render time (DeformPrepare reads it as the channel's static), so the derived group tree is unaffected. + * + * @property DrawableId id The retargeted drawable. + * @property Float drawOrder The new draw order. + */ + data class SetDrawOrder(val id: DrawableId, val drawOrder: Float) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.drawOrder" + } + + /** + * Sets a drawable's per-art-mesh multiply color. Writes only the static value - a track + * keyed on this channel shadows it, exactly like [SetOpacity] (see PuppetModelEdits.withDrawableMultiplyColor). + * + * @property DrawableId id The drawable whose multiply color changed. + * @property ColorRgb color The new multiply color. + */ + data class SetMultiplyColor(val id: DrawableId, val color: ColorRgb) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.multiplyColor" + } + + /** + * Sets a drawable's per-art-mesh screen color; the static-value sibling of [SetMultiplyColor]. + * + * @property DrawableId id The drawable whose screen color changed. + * @property ColorRgb color The new screen color. + */ + data class SetScreenColor(val id: DrawableId, val color: ColorRgb) : DrawableChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.drawable.screenColor" + } +} + +/** Changes to a deformer (warp or rotation). */ +sealed interface DeformerChange : Change { + /** + * Creates a deformer (warp or rotation) and binds the intended children in the same undo step. + * + * @property DeformerId id The minted id of the new deformer. + */ + data class Create(val id: DeformerId) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.create" + } + + /** + * Renames a deformer. + * + * @property DeformerId id The renamed deformer. + * @property String to The new name. + */ + data class Rename(val id: DeformerId, val to: String) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.rename" + } + + /** + * Toggles whether a deformer is viewport-selectable. + * + * @property DeformerId id The deformer whose selectability changed. + * @property Boolean selectable The new selectable state. + */ + data class SetSelectable(val id: DeformerId, val selectable: Boolean) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.selectable" + } + + /** + * Moves a deformer within the nesting hierarchy (reparent, which changes deformation, and / or reorder). + * + * @property DeformerId id The moved deformer. + * @property DeformerId? toParentId The destination parent deformer, or null for an armature root. + * @property DeformerId? beforeId The sibling it was inserted before, or null when appended. + */ + data class Move(val id: DeformerId, val toParentId: DeformerId?, val beforeId: DeformerId?) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.move" + } + + /** + * Sets a deformer's static opacity - the value its opacity channel falls back to when unkeyed. + * + * A deformer's render channels CASCADE: this multiplies onto every drawable beneath it, so it is not + * the same lever as setting each of those drawables' own opacity. + * + * @property DeformerId id The retargeted deformer. + * @property Float opacity The new opacity, 0..1. + */ + data class SetOpacity(val id: DeformerId, val opacity: Float) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.opacity" + } + + /** + * Sets a deformer's static multiply color, which cascades onto every drawable beneath it. + * + * @property DeformerId id The retargeted deformer. + * @property ColorRgb color The new multiply color. + */ + data class SetMultiplyColor(val id: DeformerId, val color: ColorRgb) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.multiplyColor" + } + + /** + * Sets a deformer's static screen color, which cascades onto every drawable beneath it. + * + * @property DeformerId id The retargeted deformer. + * @property ColorRgb color The new screen color. + */ + data class SetScreenColor(val id: DeformerId, val color: ColorRgb) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.screenColor" + } + + /** + * Sets a ROTATION deformer's static horizontal reflection. + * + * A flag rather than a scalar, so it snaps to the floor cell instead of blending - which is why it + * lives on the channel side rather than on the pivot form. + * + * @property DeformerId id The retargeted deformer. + * @property Boolean flip The new reflection state. + */ + data class SetFlipX(val id: DeformerId, val flip: Boolean) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.flipX" + } + + /** + * Sets a ROTATION deformer's static vertical reflection. + * + * @property DeformerId id The retargeted deformer. + * @property Boolean flip The new reflection state. + */ + data class SetFlipY(val id: DeformerId, val flip: Boolean) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.flipY" + } + + /** + * Binds a deformer to the organizational part that owns it (or clears the binding). A loose reference + * into the org tree - no [org.umamo.runtime.model.Part.children] entry corresponds to it - so this is a + * flat field write, not tree surgery. + * + * @property DeformerId id The deformer being rebound. + * @property PartId? partId The part that now owns it, or null to clear. + */ + data class SetPart(val id: DeformerId, val partId: PartId?) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.part" + } + + /** + * Deletes a deformer by unwrapping it - its child deformers and bound drawables re-home to its parent. + * + * @property DeformerId id The deleted deformer. + */ + data class Delete(val id: DeformerId) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.delete" + } + + /** + * Sets a rotation deformer's static editor reference angle. A no-op on a warp deformer (it has no + * base angle), so the transform short-circuits. + * + * @property DeformerId id The rotation deformer whose base angle changed. + * @property Float angle The new base angle in degrees. + */ + data class SetBaseAngle(val id: DeformerId, val angle: Float) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.baseAngle" + } + + /** + * Sets a warp deformer's FFD interpolation mode (true = bilinear / quad, false = triangle split). + * A no-op on a rotation deformer (it has no lattice), so the transform short-circuits. + * + * @property DeformerId id The warp deformer whose interpolation mode changed. + * @property Boolean quad The new quad-transform state. + */ + data class SetQuadTransform(val id: DeformerId, val quad: Boolean) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.quadTransform" + } + + /** + * Sets a warp deformer's conversion-division grid (rows × columns) and resamples every lattice + * keyform through the old surface. A no-op on a rotation deformer (it has no lattice). + * + * @property DeformerId id The warp deformer whose grid changed. + * @property Int rows The new conversion divisions vertically. + * @property Int columns The new conversion divisions horizontally. + */ + data class SetGrid(val id: DeformerId, val rows: Int, val columns: Int) : DeformerChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.deformer.grid" + } +} + +/** Changes to a parameter (an animation axis). */ +sealed interface ParameterChange : Change { + /** + * Commits a parameter scrub: the live value (pose) of one or more parameters reached a new resting + * position. The pose is ephemeral editor state (not document content), snapshotted so the scrub is + * undoable. Coalescing is realized upstream, at the gesture boundary: a continuous slider / 2D-pad + * drag streams transient preview frames straight to the renderer and commits exactly one [SetValue] + * on release, so a whole drag is a single undo step while two separate drags are two. Hence this is a + * plain [Undoability.Undoable] step (one per commit), not a history-side merge. + * + * @property List ids The parameters whose live value this gesture moved. + */ + data class SetValue(val ids: List) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.value" + } + + /** + * Sets a parameter's range (minimum / maximum) and default. Document content - it changes the model + * and marks the document dirty. The default is clamped within the range, and the live pose value is + * re-clamped into the new range as part of the same undo step. + * + * @property ParameterId id The parameter whose range changed. + * @property Float min The new minimum (normalized so it does not exceed [max]). + * @property Float default The new default, clamped within [min]..[max]. + * @property Float max The new maximum. + */ + data class SetRange(val id: ParameterId, val min: Float, val default: Float, val max: Float) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.range" + } + + /** + * Links two adjacent parameters into one 2D pad, or removes that link. Document content - it + * changes the model and marks the document dirty. The live pose is untouched: both parameters + * keep their values, only the panel presentation folds into (or splits out of) a pad. + * + * @property ParameterId horizontal The X-axis (upper) parameter. + * @property ParameterId vertical The Y-axis parameter (the next parameter below in panel order). + * @property Boolean linked True to create the link, false to remove it. + */ + data class SetLink(val horizontal: ParameterId, val vertical: ParameterId, val linked: Boolean) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = if (linked) "change.parameter.link" else "change.parameter.unlink" + } + + /** + * Reorders a parameter row in the panel's group tree, or moves it into or out of a group. Layout only + * - the flat parameters list and the links are untouched. The subject is one or two adjacent parameter + * leaves (a slider or a linked pad) or a whole group. + * + * @property ParameterMoveSubject subject The leaves or group being moved. + * @property ParameterGroupId? toParentGroupId The destination group, or null for the root level. + */ + data class MoveNode(val subject: ParameterMoveSubject, val toParentGroupId: ParameterGroupId?) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.move" + } + + /** + * Creates a new empty parameter group. + * + * @property ParameterGroupId id The minted id of the new group. + */ + data class CreateGroup(val id: ParameterGroupId) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.groupCreate" + } + + /** + * Deletes a parameter group by unwrapping it - its child parameters splice into the parent in place, + * so no parameter is lost. + * + * @property ParameterGroupId id The dissolved group. + */ + data class DeleteGroup(val id: ParameterGroupId) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.groupDelete" + } + + /** + * Renames a parameter group. + * + * @property ParameterGroupId id The renamed group. + * @property String to The new display name. + */ + data class RenameGroup(val id: ParameterGroupId, val to: String) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.groupRename" + } + + /** + * Creates a new animatable parameter (a fresh axis). + * + * @property ParameterId id The minted id of the new parameter. + */ + data class Create(val id: ParameterId) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.create" + } + + /** + * Renames a parameter (its display name; the id is format-level and stays fixed). + * + * @property ParameterId id The renamed parameter. + * @property String to The new display name. + */ + data class Rename(val id: ParameterId, val to: String) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.rename" + } + + /** + * Deletes a parameter everywhere - the axis list, the panel tree, any link, the pose, and every + * object's keyform grid. Without [moveKeysTo] the axis collapses to the parameter's default slice; + * with it, matching axes retarget onto that destination instead. + * + * @property ParameterId id The deleted parameter. + * @property ParameterId? moveKeysTo Destination for retargeted keys, or null to discard them. + */ + data class Delete(val id: ParameterId, val moveKeysTo: ParameterId? = null) : ParameterChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = + if (moveKeysTo != null) "change.parameter.deleteMove" else "change.parameter.delete" + } +} + +/** Changes to document-wide properties that live on the model root rather than on any one entity. */ + +sealed interface DocumentChange : Change { + /** + * Sets the document canvas size in world units. Document content, so it marks the document dirty. + * + * @property Float width The new canvas width. + * @property Float height The new canvas height. + */ + data class SetCanvasSize(val width: Float, val height: Float) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.canvasSize" + } + + /** + * Sets the world origin (where the viewport axis lines cross, in world space). Document content, so + * it marks the document dirty. + * + * @property Float x The new world-origin x. + * @property Float z The new world-origin z (up). + */ + data class SetWorldOrigin(val x: Float, val z: Float) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.worldOrigin" + } + + /** + * Sets the document's runtime-compatibility target. Document content, so it marks the document + * dirty. + * + * @property RuntimeTarget target The new runtime target. + */ + data class SetRuntimeTarget(val target: RuntimeTarget) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.runtimeTarget" + } + + /** + * Switches the puppet between displaying from its source artwork and from the packed atlas. + * Document content - the source formats author it - so it marks the document dirty. + * + * @property Boolean fromSourceLayers True to display from the source artwork, false from the atlas. + */ + data class SetSourceLayerDisplay(val fromSourceLayers: Boolean) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.sourceLayerDisplay" + } + + /** + * Moves one or more pieces of source art to new spots on their pages, re-mapping every drawable + * over them - one step for a whole placement gesture, however many tiles it carried. Document + * content - a pack is authored - so it marks the document dirty. + * + * The label names the operator that ran, so the history panel and the operation settings strip + * read Rotate or Scale when that is what happened; a placement written by no gesture at all (a + * property edit, a test) reads as a move. + * + * @property List tileIds The tiles that moved. + * @property MeshOperatorKind? kind The placement operator that produced the move, or null. + */ + data class SetAtlasPlacement( + val tileIds: List, + val kind: MeshOperatorKind? = null, + ) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = + when (kind) { + MeshOperatorKind.Rotate -> "change.document.atlasPlacement.rotate" + MeshOperatorKind.Scale -> "change.document.atlasPlacement.scale" + // A placement has no slide; one arriving under that kind can only have moved. + MeshOperatorKind.Grab, MeshOperatorKind.VertexSlide, null -> "change.document.atlasPlacement" + } + } + + /** + * Pins or unpins one or more pieces of packed source art, so a repack keeps (or may move) their + * placements. Editor state on the model, undoable like any other edit; it marks the document + * dirty because the native format will carry it. + * + * @property List tileIds The tiles pinned or unpinned. + * @property Boolean pinned True to pin, false to unpin. + */ + data class SetAtlasPin( + val tileIds: List, + val pinned: Boolean, + ) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = if (pinned) "change.document.atlasPin" else "change.document.atlasUnpin" + } + + /** + * Repacks the whole atlas: a new page inventory, every tile placed anew, every bound drawable + * re-mapped over it. Document content - the pack is authored - so it marks the document dirty. + * + * @property Int tileCount The number of tiles placed onto the new pages. + * @property Int pageCount The number of pages the repack produced. + */ + data class RepackAtlas(val tileCount: Int, val pageCount: Int) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.atlasRepack" + } + + /** + * Rebinds one piece of source art to another layer of a listed artwork file, or unbinds it. + * Document content the native format carries, so it marks the document dirty. + * + * @property AtlasTileId tileId The tile rebound. + * @property Boolean bound True when a layer was bound, false when the tile was unbound. + */ + data class SetTileSource(val tileId: AtlasTileId, val bound: Boolean) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = if (bound) "change.document.tileSource" else "change.document.tileUnbind" + } + + /** + * Removes one piece of source art from the atlas: a tile no drawable samples (its drawables were + * deleted, or it never had any), so it stops taking a page slot and a Sources row. Its pixels stay + * in the document's raster store, so undo shows it again. Document content, so it marks the + * document dirty. With [ignoredLayer] the layer the tile was bound to is marked ignored in the same + * step, so a reload does not mint the art back (Settings > Import decides). + * + * @property AtlasTileId tileId The tile removed. + * @property Boolean ignoredLayer Whether the tile's layer was marked ignored with it. + */ + data class DeleteTile(val tileId: AtlasTileId, val ignoredLayer: Boolean = false) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = if (ignoredLayer) "change.document.deleteTileIgnore" else "change.document.deleteTile" + } + + /** + * Marks or clears the ignore on one layer of a listed artwork file: while marked, a reload leaves the + * layer out of the rig instead of minting a drawable for it. Document content the native format + * carries, so it marks the document dirty. + * + * @property ArtSourceId sourceId The file. + * @property String layerKey The layer's key within it. + * @property Boolean ignored True when the layer was marked, false when the mark was cleared. + */ + data class SetLayerIgnored(val sourceId: ArtSourceId, val layerKey: String, val ignored: Boolean) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = if (ignored) "change.document.layerIgnore" else "change.document.layerUnignore" + } + + /** + * Adds an artwork file to the document: its source record and layer inventory, one tile and one + * drawable per layer with art, one part per folder, packed onto the pages beside the existing art. + * Document content, so it marks the document dirty. + * + * @property String sourceName The file's display name. + * @property Int drawableCount How many drawables it added. + */ + data class AddArtwork(val sourceName: String, val drawableCount: Int) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.importArtwork" + } + + /** + * Reloads the document's artwork files: every changed layer's tile replaced with its new art, a lost + * layer's tile rebound to the layer that re-created it, the layers the files gained added, the untouched + * drawables following their layers' eye toggles, the inventories refreshed, and the changed tiles packed + * beside the existing art - one step for however many files were read. Document content, so it marks + * the document dirty. + * + * @property Int fileCount How many files were re-read. + * @property Int replacedCount How many tiles took new art (the rebound ones among them). + * @property Int addedCount How many drawables the files' new layers added. + * @property Int matchedCount How many tiles the matcher rebound to a re-created layer. + * @property Int missingCount How many bound layers the files no longer have (left for review). + * @property Int visibilityCount How many drawables followed their layer's eye toggle in the file. + */ + data class ReloadArtwork( + val fileCount: Int, + val replacedCount: Int, + val addedCount: Int, + val matchedCount: Int, + val missingCount: Int, + val visibilityCount: Int = 0, + ) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.reloadArtwork" + } + + /** + * Rebinds a tile to another source layer with that layer's art pulled in: the tile replaced, its + * drawables carried over it, the file's inventory refreshed. Document content, so it marks the + * document dirty. A rebinding that could not pull the art (the file missing) is a + * [SetTileSource] instead. + * + * @property AtlasTileId tileId The tile that was rebound (its id before the replacement). + */ + data class RelinkArtwork(val tileId: AtlasTileId) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.relinkArtwork" + } + + /** + * Matches the bindings the files no longer resolve to the layers the matcher is confident about: + * every accepted tile rebound with its layer's art pulled in and packed beside the existing art, + * the inventories refreshed - one step for however many files were scored. Document content, so it + * marks the document dirty. + * + * @property Int matchedCount How many tiles were rebound. + * @property Int remainingCount How many bindings are still left for review. + */ + data class MatchArtwork(val matchedCount: Int, val remainingCount: Int) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.matchArtwork" + } + + /** + * Repoints one artwork record at another file: the record's name, path, and format rewritten, every + * binding the new file resolves by key reloaded, the confident matches rebound, and the rest flagged + * for review with the file's layers left as their candidates. Document content, so it marks the + * document dirty. + * + * @property String sourceName The new file's display name. + * @property Int matchedCount How many bindings the new file resolved by key (changed or not). + * @property Int reboundCount How many bindings the matcher rebound to the new file's layers. + * @property Int missingCount How many bindings neither resolved, left for review. + */ + data class ReplaceArtwork(val sourceName: String, val matchedCount: Int, val reboundCount: Int, val missingCount: Int) : DocumentChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.document.replaceArtwork" + } +} + +/** + * A keyform authoring edit: binding a channel to a parameter, capturing a key, or removing one. + * + * Carries the CHANNEL rather than the whole target because that is what the history label needs to read + * usefully ("Insert Opacity Key"); the entity is already obvious from what the user was pointing at. + */ +sealed interface KeyformChange : Change { + /** + * The channel the edit was made on, or null for a GEOMETRY track. + * + * Nullable rather than a fourth "geometry" FormChannel constant: geometry is a separate typed field on + * every owner precisely so a scalar track can never reach the delta-texture builder, and giving it a + * FormChannel would undo that at the type level for the sake of a history label. + */ + val channel: FormChannel? + + /** + * A key captured at the current pose - which also BINDS the channel to the parameter when it was not + * keyed on it before, since a capture with nowhere to land seeds its own axis. + * + * @property FormChannel? channel The channel keyed, or null for geometry. + */ + data class InsertKey(override val channel: FormChannel?) : KeyformChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.keyform.insert" + } + + /** + * A key dragged to a new position on its parameter, carrying its stored value with it. + * + * @property FormChannel? channel The channel the key belongs to, or null for geometry. + */ + data class MoveKey(override val channel: FormChannel?) : KeyformChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.keyform.move" + } + + /** + * A key deleted, which also UNBINDS the channel when it was the last one holding the axis up, since + * removal collapses an axis rather than leaving a single key behind. + * + * @property FormChannel? channel The channel the key came off, or null for geometry. + */ + data class DeleteKey(override val channel: FormChannel?) : KeyformChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.keyform.delete" + } +} + +/** + * Changes to a drawable's art mesh (its interior geometry, edited in Edit mode). + * + * The three whole-gesture transforms ([TransformVertices], [TransformDrawables], [TransformUvs]) each carry + * the [MeshOperatorKind] they performed, so the history panel can name the operation rather than filing + * every Grab, Scale, and Rotate under one "Move" label. The kind names WHAT the transform was, not how it + * was driven: the Properties panel's typed Size row records Scale with no modal operator ever latching. + * + * Each label key is resolved by an exhaustive `when` over the kind rather than by interpolating a suffix + * into a namespace. Interpolation would happily mint a key like `change.object.slide` that no string + * resource answers, and an unmapped key degrades silently to the generic "Edit" label in the history panel. + */ +sealed interface MeshChange : Change { + /** + * Transforms a set of mesh vertices to new rest positions, per drawable - an Edit session spans several + * meshes, so one gesture can move vertices on each of them as a single undo step. The pose is + * unaffected; this edits the rest geometry, which is document content. + * + * @property Map> vertexIndicesByDrawable The vertices this gesture moved, per + * drawable (for the history-panel detail). + * @property MeshOperatorKind kind The operator this gesture ran, which selects the history label. + */ + data class TransformVertices( + val vertexIndicesByDrawable: Map>, + val kind: MeshOperatorKind, + ) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = + when (kind) { + MeshOperatorKind.Grab -> "change.mesh.move" + MeshOperatorKind.Scale -> "change.mesh.scale" + MeshOperatorKind.Rotate -> "change.mesh.rotate" + MeshOperatorKind.VertexSlide -> "change.mesh.slide" + } + } + + /** + * A topology edit of one mesh (duplicate / merge / rip / connect): the vertex count changes, every + * keyform cell's deltas are rebuilt, and the glue pairs remap. One change kind per operation so the + * history panel names what happened. + * + * @property DrawableId drawableId The drawable whose mesh's topology changed. + * @property String labelKey The operation's history label key (change.mesh.duplicate / merge / rip / connect). + */ + data class TopologyEdit(val drawableId: DrawableId, override val labelKey: String) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + } + + /** + * Transforms every vertex of one or more whole drawables to new rest positions - an Object-mode Grab / + * Scale / Rotate of the selected drawables, or the Properties panel's typed Position / Size rows. + * Recorded as one undo step for the whole gesture even though several drawables move. The pose is + * unaffected; this edits rest geometry, which is document content. + * + * @property List drawableIds The drawables this gesture moved (for the history-panel detail). + * @property MeshOperatorKind kind The operator this gesture ran, which selects the history label. + */ + data class TransformDrawables(val drawableIds: List, val kind: MeshOperatorKind) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = + when (kind) { + // Object mode cannot latch a Vertex Slide (the command is Edit-mode gated), so it can only + // arrive here through a future caller - where reading as a plain move is the honest label. + MeshOperatorKind.Grab, MeshOperatorKind.VertexSlide -> "change.object.move" + MeshOperatorKind.Scale -> "change.object.scale" + MeshOperatorKind.Rotate -> "change.object.rotate" + } + } + + /** + * Transforms a set of mesh vertices' texture coordinates to new atlas positions, per drawable - the UV + * editor's modal Grab / Scale / Rotate, the texture-mapping counterpart of [TransformVertices]. Rest + * geometry and the pose are unaffected; this edits which texels the mesh samples, which is + * document content. + * + * @property Map> vertexIndicesByDrawable The vertices whose UVs this gesture + * moved, per drawable (for the history-panel detail). + * @property MeshOperatorKind kind The operator this gesture ran, which selects the history label. + */ + data class TransformUvs( + val vertexIndicesByDrawable: Map>, + val kind: MeshOperatorKind, + ) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = + when (kind) { + // The UV editor has no Vertex Slide yet (see TODO § UV Editor); until it does, a slide can + // only reach here as a move. + MeshOperatorKind.Grab, MeshOperatorKind.VertexSlide -> "change.uv.move" + MeshOperatorKind.Scale -> "change.uv.scale" + MeshOperatorKind.Rotate -> "change.uv.rotate" + } + } + + /** + * Mirrors the selected vertices' texture coordinates about the transform pivot - the UV editor's + * explicit Mirror U / V commands, which serve the duplicated-and-flipped texture regions workflow + * (e.g. both eyes sampling one eye texture). Rest geometry and the pose are unaffected; document + * content like [TransformUvs]. + * + * @property List drawableIds The drawables whose UVs mirrored (for the history-panel detail). + * @property Boolean mirrorU True for a U (horizontal) mirror, false for a V (vertical) mirror. + */ + data class MirrorUvs(val drawableIds: List, val mirrorU: Boolean) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.uv.mirror" + } + + /** + * Mirrors selected Edit-mode mesh vertices about the transform pivot (world-space reflection written + * back to rest). One undo step for every drawable the gesture touched. + * + * @property Map> vertexIndicesByDrawable The mirrored vertices per drawable. + * @property Boolean mirrorHorizontal True for left↔right, false for top↔bottom. + */ + data class MirrorVertices( + val vertexIndicesByDrawable: Map>, + val mirrorHorizontal: Boolean, + ) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.mesh.mirror" + } + + /** + * Mirrors whole Object-mode drawables about the transform pivot (rest geometry). + * + * @property List drawableIds The mirrored drawables. + * @property Boolean mirrorHorizontal True for left↔right, false for top↔bottom. + */ + data class MirrorDrawables(val drawableIds: List, val mirrorHorizontal: Boolean) : MeshChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.object.mirror" + } +} + +/** + * Changes to ephemeral editor state — selection and mode — which ride alongside the document model in + * a history snapshot rather than inside [org.umamo.runtime.model.PuppetModel]. Selection gestures are + * full undo steps (the user's chosen Blender-faithful granularity); a mode toggle is transient. + */ +sealed interface EditorStateChange : Change { + /** A selection gesture (click, deselect, range). Its own undo step so a misclick is recoverable. */ + object SelectionChanged : EditorStateChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.selection" + } + + /** + * A parameter-target gesture (clicking a parameter row). Its own undo step, like the object and mesh + * selection gestures, so undoing back across a keyform edit restores the parameter it was made on. + */ + object ParameterSelectionChanged : EditorStateChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.parameter.select" + } + + /** + * An Edit-mode element-selection gesture (click, box, deselect). Its own undo step, like its + * object-mode counterpart [SelectionChanged], so a misclick that loses a selection is recoverable. + */ + object MeshSelectionChanged : EditorStateChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.mesh.select" + } + + /** + * The keyform sheet's key selection changed (a click, a shift-click, a marquee, or a clear). + * + * @see MeshSelectionChanged for the same granularity in Edit mode. + */ + object KeySelectionChanged : EditorStateChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.keyform.select" + } + + /** + * An Edit-mode select-mode switch (vertex / edge / face). Its own undo step, so undoing back across + * the switch restores both the prior mode and the selection it converted - the flush-down / derive-up + * conversion is lossy by design (Blender-faithful), so only the snapshot can bring the set back. + * + * @property MeshSelectMode selectMode The new select mode. + */ + data class MeshSelectModeChanged(val selectMode: MeshSelectMode) : EditorStateChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.mesh.selectMode" + } + + /** + * An Object/Edit mode toggle. Its own undo step (like a selection gesture), so undoing back across a + * mode change restores the prior mode together with the vertex selection it seeded - the editor never + * ends up in Edit mode showing a state that was captured in Object mode. + * + * @property EditorMode mode The new mode. + */ + data class ModeChanged(val mode: EditorMode) : EditorStateChange { + override val undoability: Undoability = Undoability.Undoable + override val labelKey: String = "change.mode" + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/DeformerCreateEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/DeformerCreateEdits.kt new file mode 100644 index 0000000..c8411e2 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/DeformerCreateEdits.kt @@ -0,0 +1,361 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.meshGridDefaultDeltas +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.runtime.model.partByDrawable +import kotlin.math.max + +/* + * Creating warp deformers for a selection: mint a lattice fitted to the selected meshes' parent-local + * bounds at the default pose, bind those drawables under it, and remap their rest positions (and keyed + * mesh deltas) into the lattice's normalized UV so the art does not jump. Cubism's Create Warp + * Deformer, reduced to the default size/parent choices (armature root, padded AABB, 2×2 conversion + * divisions). + * + * Parent-local (not raw rest mesh) matters for Cubism-imported art under an existing warp: rest + * positions stay in canvas units while keyform deltas place the drawable in the parent's UV, and the + * new lattice must be authored in that same parent-local space or the overlay / cascade maps it off + * into oblivion. + * + * 選択メッシュに合わせたワープデフォーマの作成。格子生成・親子付け・UV再マップを1操作で行う。 + */ + +/** Default conversion-division count Cubism-style create uses for a new warp (→ 3×3 control points). */ +private const val DEFAULT_WARP_DIVISIONS = 2 + +/** Padding around the selection AABB, as a fraction of each axis extent (so the lattice is not skin-tight). */ +private const val LATTICE_PADDING_FRACTION = 0.05f + +/** Floor for a degenerate (zero-size) selection axis so division by width / height stays defined. */ +private const val MIN_LATTICE_EXTENT = 1e-3f + +/** + * Mints a unused deformer id with [prefix] (then [prefix]2, [prefix]3, …), matching the parameter / + * parameter-group id minting style. + * + * @param String prefix The base id stem (e.g. "Warp"). + * @return DeformerId A free id. + */ +fun PuppetModel.freshDeformerId(prefix: String = "Warp"): DeformerId { + val existing = deformers.map { deformer -> deformer.id }.toSet() + if (DeformerId(prefix) !in existing) { + return DeformerId(prefix) + } + var suffix = 2 + while (DeformerId("$prefix$suffix") in existing) { + suffix++ + } + return DeformerId("$prefix$suffix") +} + +/** + * Builds a rectangular identity lattice covering [minX]..[maxX] × [minY]..[maxY] with + * ([rows]+1)×([columns]+1) control points, row-major (Y ascending), column-major within each row + * (X ascending) - the order [org.umamo.render.eval.warpInGrid] expects. + * + * @param Float minX Left edge. + * @param Float minY Bottom edge. + * @param Float maxX Right edge. + * @param Float maxY Top edge. + * @param Int rows Conversion divisions vertically. + * @param Int columns Conversion divisions horizontally. + * @return FloatArray Interleaved (x, y) control points. + */ +fun rectLatticeControlPoints(minX: Float, minY: Float, maxX: Float, maxY: Float, rows: Int, columns: Int): FloatArray { + val pointsPerRow = columns + 1 + val pointsPerCol = rows + 1 + val points = FloatArray(pointsPerRow * pointsPerCol * 2) + for (row in 0 until pointsPerCol) { + val y = minY + (maxY - minY) * (row.toFloat() / rows.coerceAtLeast(1)) + for (col in 0 until pointsPerRow) { + val x = minX + (maxX - minX) * (col.toFloat() / columns.coerceAtLeast(1)) + val index = (row * pointsPerRow + col) * 2 + points[index] = x + points[index + 1] = y + } + } + return points +} + +/** + * The drawable ids a warp-create gesture should wrap: mesh-carrying drawables reached from [selection] + * (a part expands to its outliner subtree). Already-parented meshes are included — create inserts the + * new warp under their shared parent (Cubism-style). When the selection spans more than one parent + * deformer, only the preferred parent's group is kept (the active drawable's parent when that is one + * of the candidates, otherwise the most common parent among candidates). Empty when nothing qualifies. + * + * @param Selection selection The object selection. + * @return List The drawable ids to wrap, in stable encounter order. + */ +fun PuppetModel.drawablesForWarpCreate(selection: Selection): List { + val ids = LinkedHashSet() + for (target in selection.targets) { + when (target) { + is SelectionTarget.Drawable -> ids.add(target.id) + is SelectionTarget.Part -> { + for (sub in subtreeTargets(target)) { + val drawable = sub as? SelectionTarget.Drawable ?: continue + ids.add(drawable.id) + } + } + is SelectionTarget.Deformer -> Unit + } + } + val candidates = + ids.mapNotNull { id -> + val drawable = drawables.firstOrNull { it.id == id } ?: return@mapNotNull null + if (drawable.mesh == null) { + null + } else { + drawable + } + } + if (candidates.isEmpty()) { + return emptyList() + } + val parentCounts = candidates.groupingBy { drawable -> drawable.parentDeformerId }.eachCount() + val activeParent = + (selection.active as? SelectionTarget.Drawable)?.let { active -> + candidates.firstOrNull { drawable -> drawable.id == active.id }?.parentDeformerId + } + val preferredParent = + if (activeParent != null && parentCounts.containsKey(activeParent)) { + activeParent + } else { + parentCounts.maxBy { entry -> entry.value }.key + } + return candidates.mapNotNull { drawable -> + if (drawable.parentDeformerId == preferredParent) drawable.id else null + } +} + +/** + * Returns a copy of [this] with a new warp deformer [newId] named [name] wrapping [drawableIds]: the + * lattice is fitted to their combined parent-local AABB at the default pose (padded), the warp is + * parented under that shared parent, each drawable is rebound to the warp, and its rest positions plus + * keyed mesh deltas are remapped into the lattice's normalized UV so the art stays put. Refuses + * (returns this) when [newId] collides, [drawableIds] is empty, any named drawable is missing / + * mesh-less, or the drawables do not share one parent deformer. + * + * @param DeformerId newId The minted deformer id. + * @param String name The initial display name. + * @param List drawableIds The mesh drawables to wrap (must share one parent deformer, which may be null). + * @param Int rows Conversion divisions vertically (default 2 → 3 control-point rows). + * @param Int columns Conversion divisions horizontally (default 2 → 3 control-point columns). + * @return PuppetModel The model with the warp and rebound drawables, or this if refused. + */ +fun PuppetModel.withWarpDeformerCreatedForDrawables( + newId: DeformerId, + name: String, + drawableIds: List, + rows: Int = DEFAULT_WARP_DIVISIONS, + columns: Int = DEFAULT_WARP_DIVISIONS, +): PuppetModel { + if (drawableIds.isEmpty() || deformers.any { it.id == newId }) { + return this + } + val targets = + drawableIds.mapNotNull { id -> + val drawable = drawables.firstOrNull { it.id == id } ?: return@mapNotNull null + val mesh = drawable.mesh ?: return@mapNotNull null + drawable to mesh + } + if (targets.size != drawableIds.size) { + return this + } + val sharedParent = targets.first().first.parentDeformerId + if (targets.any { (drawable, _) -> drawable.parentDeformerId != sharedParent }) { + return this + } + if (sharedParent != null && deformers.none { deformer -> deformer.id == sharedParent }) { + return this + } + val defaultValue: (ParameterId) -> Float = { id -> parameters.firstOrNull { it.id == id }?.default ?: 0f } + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + for ((drawable, mesh) in targets) { + val positions = parentLocalPositions(drawable, mesh.positions, defaultValue) + var index = 0 + while (index + 1 < positions.size) { + val x = positions[index] + val y = positions[index + 1] + if (x < minX) minX = x + if (y < minY) minY = y + if (x > maxX) maxX = x + if (y > maxY) maxY = y + index += 2 + } + } + if (!minX.isFinite() || !minY.isFinite() || !maxX.isFinite() || !maxY.isFinite()) { + return this + } + var width = max(maxX - minX, MIN_LATTICE_EXTENT) + var height = max(maxY - minY, MIN_LATTICE_EXTENT) + // Re-center a collapsed axis so a zero-extent selection still gets a real lattice around it. + if (maxX - minX < MIN_LATTICE_EXTENT) { + val mid = (minX + maxX) * 0.5f + minX = mid - width * 0.5f + maxX = mid + width * 0.5f + } + if (maxY - minY < MIN_LATTICE_EXTENT) { + val mid = (minY + maxY) * 0.5f + minY = mid - height * 0.5f + maxY = mid + height * 0.5f + } + val padX = width * LATTICE_PADDING_FRACTION + val padY = height * LATTICE_PADDING_FRACTION + minX -= padX + maxX += padX + minY -= padY + maxY += padY + width = maxX - minX + height = maxY - minY + val controlPoints = rectLatticeControlPoints(minX, minY, maxX, maxY, rows, columns) + val restGrid = + KeyformGrid( + emptyList(), + listOf(KeyformCell(IntArray(0), WarpLatticeForm(controlPoints))), + ) + val ownerByDrawable = partByDrawable() + val partId: PartId? = drawableIds.firstOrNull()?.let { id -> ownerByDrawable[id] } + val warp = + Deformer.Warp( + id = newId, + name = name, + parent = sharedParent, + partId = partId, + rows = rows, + columns = columns, + isQuadTransform = true, + geometryGrid = restGrid, + ) + val targetIds = drawableIds.toSet() + val newDrawables = + drawables.map { drawable -> + if (drawable.id !in targetIds) { + return@map drawable + } + val mesh = drawable.mesh ?: return@map drawable + val remappedPositions = remapPositionsToLatticeUv(mesh.positions, minX, minY, width, height) + val remappedGrid = drawable.geometryGrid?.let { grid -> remapMeshDeltaGrid(grid, width, height) } + drawable.copy( + parentDeformerId = newId, + mesh = DrawableMesh(remappedPositions, mesh.uvs, mesh.indices), + geometryGrid = remappedGrid, + ) + } + return copy(deformers = deformers + warp, drawables = newDrawables) +} + +/** + * Parent-local positions at the default pose: rest mesh plus the grid's default-pose deltas. Cubism + * art parented under a warp often keeps canvas units in the rest mesh and lands in parent UV only + * after those deltas - fitting / remapping must use this space, not the raw rest buffer. + * + * @param Drawable drawable The drawable (for its geometry grid). + * @param FloatArray rest Interleaved rest positions. + * @param Function defaultValue Default value per parameter id. + * @return FloatArray Parent-local interleaved positions (a copy when deltas apply). + */ +private fun parentLocalPositions( + drawable: Drawable, + rest: FloatArray, + defaultValue: (ParameterId) -> Float, +): FloatArray { + val deltas = meshGridDefaultDeltas(drawable, defaultValue) ?: return rest + val out = rest.copyOf() + val count = minOf(out.size, deltas.size) + for (index in 0 until count) { + out[index] += deltas[index] + } + return out +} + +/** + * Remaps interleaved model-space positions into the lattice's normalized UV ([0,1]² over the fitted rect). + * + * @param FloatArray positions Interleaved (x, y) rest positions. + * @param Float minX Lattice left. + * @param Float minY Lattice bottom. + * @param Float width Lattice width. + * @param Float height Lattice height. + * @return FloatArray Fresh remapped positions. + */ +private fun remapPositionsToLatticeUv(positions: FloatArray, minX: Float, minY: Float, width: Float, height: Float): FloatArray { + val out = FloatArray(positions.size) + var index = 0 + while (index + 1 < positions.size) { + out[index] = (positions[index] - minX) / width + out[index + 1] = (positions[index + 1] - minY) / height + index += 2 + } + return out +} + +/** + * Scales every cell's position deltas by the inverse lattice extent so keyed morphs stay correct after + * the rest mesh is remapped into UV. + * + * @param KeyformGrid grid The drawable's geometry grid. + * @param Float width Lattice width. + * @param Float height Lattice height. + * @return KeyformGrid The remapped grid. + */ +private fun remapMeshDeltaGrid(grid: KeyformGrid, width: Float, height: Float): KeyformGrid = + KeyformGrid( + grid.axes, + grid.cells.map { cell -> + val deltas = cell.form.positionDeltas + val remapped = FloatArray(deltas.size) + var index = 0 + while (index + 1 < deltas.size) { + remapped[index] = deltas[index] / width + remapped[index + 1] = deltas[index + 1] / height + index += 2 + } + KeyformCell(cell.coordinate.copyOf(), MeshDeltaForm(remapped)) + }, + ) + +/** + * Creates a warp deformer wrapping the mesh drawables in the current selection (parts expand to their + * subtree meshes; already-parented meshes insert the warp under their shared parent). One undo step; + * selects the new deformer and switches to Object mode on success so the lattice overlay is visible + * (it is Object-mode only). Emits a near-cursor notice and returns null when nothing in the selection + * can be wrapped. + * + * @param String name The initial display name. + * @return DeformerId? The new deformer's id, or null when the create was refused. + */ +fun EditorSession.createWarpDeformerForSelection(name: String): DeformerId? { + val drawableIds = model.value.drawablesForWarpCreate(selection.value) + if (drawableIds.isEmpty()) { + emitNotice("notice.deformer.createWarp.none", NoticePlacement.NearCursor) + return null + } + val id = model.value.freshDeformerId() + mutate(DeformerChange.Create(id)) { model -> + model.withWarpDeformerCreatedForDrawables(id, name, drawableIds) + } + if (model.value.deformers.none { it.id == id }) { + return null + } + // Lattice editing / drawing lives on the Object-mode overlay; stay there after create so the new + // warp is immediately visible and grab-able rather than only appearing in the outliner. + setMode(EditorMode.Object) + setSelection(Selection(setOf(SelectionTarget.Deformer(id)), SelectionTarget.Deformer(id))) + return id +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/DeformerSpaceEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/DeformerSpaceEdits.kt new file mode 100644 index 0000000..098d0c7 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/DeformerSpaceEdits.kt @@ -0,0 +1,224 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.invertPointsThroughWarpLattice +import org.umamo.runtime.eval.mapPointsThroughWarpLattice +import org.umamo.runtime.eval.rotationFormAt +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.sin + +/* + * Keeping a deformer's authored geometry put in world space when its parent nesting changes: control + * points (and rotation pivots) live in immediate-parent-local space, so a reparent without conversion + * sends lattices flying (canvas CPs under a UV parent, or UV CPs promoted to root). + */ + +/** Degrees → radians factor matching the renderer's PI_F-based conversion. */ +private const val DEG_TO_RAD = 3.1415927f / 180f + +/** + * Ancestor chain from [startParentId] up to the armature root (immediate parent first). + * + * @param DeformerId? startParentId The first ancestor, or null for an empty chain. + * @return List Deformers from near to far. + */ +private fun PuppetModel.ancestorChain(startParentId: DeformerId?): List { + if (startParentId == null) { + return emptyList() + } + val byId = deformers.associateBy { deformer -> deformer.id } + val chain = ArrayList() + val visited = HashSet() + var current: DeformerId? = startParentId + while (current != null && visited.add(current)) { + val deformer = byId[current] ?: break + chain.add(deformer) + current = deformer.parent + } + return chain +} + +/** + * Maps interleaved points from [startParentId]'s local space up to armature-root / canvas space by + * applying each ancestor's rest (default-pose) transform. + * + * @param DeformerId? startParentId Immediate parent (null = already root-local). + * @param FloatArray points Interleaved positions. + * @param Function defaultValue Default parameter sampler. + * @return FloatArray Root-local interleaved positions. + */ +private fun PuppetModel.mapToRootLocal( + startParentId: DeformerId?, + points: FloatArray, + defaultValue: (ParameterId) -> Float, +): FloatArray { + var current = points + for (ancestor in ancestorChain(startParentId)) { + current = + when (ancestor) { + is Deformer.Warp -> { + val cp = warpControlPointsAt(ancestor.geometryGrid, defaultValue) ?: continue + mapPointsThroughWarpLattice(current, cp, ancestor.columns, ancestor.rows, ancestor.isQuadTransform) + } + is Deformer.Rotation -> { + val form = rotationFormAt(ancestor.geometryGrid, defaultValue) ?: continue + mapPointsThroughRotation(current, form.originX, form.originY, form.angle, form.scale, ancestor.flipX, ancestor.flipY) + } + } + } + return current +} + +/** + * Inverse of [mapToRootLocal]: root-local points → [startParentId]'s local space. + * + * @param DeformerId? startParentId Immediate parent (null = already root-local). + * @param FloatArray points Root-local interleaved positions. + * @param Function defaultValue Default parameter sampler. + * @return FloatArray Parent-local interleaved positions. + */ +private fun PuppetModel.mapFromRootLocal( + startParentId: DeformerId?, + points: FloatArray, + defaultValue: (ParameterId) -> Float, +): FloatArray { + var current = points + for (ancestor in ancestorChain(startParentId).asReversed()) { + current = + when (ancestor) { + is Deformer.Warp -> { + val cp = warpControlPointsAt(ancestor.geometryGrid, defaultValue) ?: continue + invertPointsThroughWarpLattice(current, cp, ancestor.columns, ancestor.rows, ancestor.isQuadTransform) + } + is Deformer.Rotation -> { + val form = rotationFormAt(ancestor.geometryGrid, defaultValue) ?: continue + invertPointsThroughRotation(current, form.originX, form.originY, form.angle, form.scale, ancestor.flipX, ancestor.flipY) + } + } + } + return current +} + +/** + * Applies a rotation deformer's rest affine to interleaved points (same coefficient grouping as the + * renderer). + */ +private fun mapPointsThroughRotation( + points: FloatArray, + originX: Float, + originY: Float, + angleDegrees: Float, + scale: Float, + flipX: Boolean, + flipY: Boolean, +): FloatArray { + val radians = angleDegrees * DEG_TO_RAD + val sn = sin(radians.toDouble()).toFloat() + val cs = cos(radians.toDouble()).toFloat() + val fx = if (flipX) -1f else 1f + val fy = if (flipY) -1f else 1f + val c12 = cs * scale * fx + val c13 = fy * cs * scale + val c14 = fx * scale * sn + val c15 = -sn * scale * fy + val out = FloatArray(points.size) + var index = 0 + while (index + 1 < points.size) { + val x = points[index] + val y = points[index + 1] + out[index] = c15 * y + c12 * x + originX + out[index + 1] = y * c13 + x * c14 + originY + index += 2 + } + return out +} + +/** Closed-form inverse of [mapPointsThroughRotation]. Degenerate determinants leave points unchanged. */ +private fun invertPointsThroughRotation( + points: FloatArray, + originX: Float, + originY: Float, + angleDegrees: Float, + scale: Float, + flipX: Boolean, + flipY: Boolean, +): FloatArray { + val radians = angleDegrees * DEG_TO_RAD + val sn = sin(radians.toDouble()).toFloat() + val cs = cos(radians.toDouble()).toFloat() + val fx = if (flipX) -1f else 1f + val fy = if (flipY) -1f else 1f + val c12 = cs * scale * fx + val c13 = fy * cs * scale + val c14 = fx * scale * sn + val c15 = -sn * scale * fy + val determinant = c12 * c13 - c15 * c14 + if (abs(determinant) < 1e-12f) { + return points.copyOf() + } + val out = FloatArray(points.size) + var index = 0 + while (index + 1 < points.size) { + val relativeX = points[index] - originX + val relativeY = points[index + 1] - originY + out[index] = (relativeX * c13 - c15 * relativeY) / determinant + out[index + 1] = (c12 * relativeY - c14 * relativeX) / determinant + index += 2 + } + return out +} + +/** + * Rewrites [deformer]'s keyed geometry from [oldParentId]-local into [newParentId]-local so its world + * pose is unchanged by the reparent. Same-parent (reorder-only) returns [deformer] unchanged. + * + * @param Deformer deformer The deformer being moved (still carrying [oldParentId]). + * @param DeformerId? oldParentId Prior parent. + * @param DeformerId? newParentId Destination parent. + * @return Deformer Geometry-converted copy (parent field still the old one - caller sets the new parent). + */ +fun PuppetModel.withDeformerGeometryConvertedForReparent( + deformer: Deformer, + oldParentId: DeformerId?, + newParentId: DeformerId?, +): Deformer { + if (oldParentId == newParentId) { + return deformer + } + val defaultValue: (ParameterId) -> Float = { id -> parameters.firstOrNull { it.id == id }?.default ?: 0f } + return when (deformer) { + is Deformer.Warp -> { + val grid = deformer.geometryGrid ?: return deformer + val newCells = + grid.cells.map { cell -> + val rootLocal = mapToRootLocal(oldParentId, cell.form.controlPoints, defaultValue) + val newLocal = mapFromRootLocal(newParentId, rootLocal, defaultValue) + KeyformCell(cell.coordinate.copyOf(), WarpLatticeForm(newLocal)) + } + deformer.copy(geometryGrid = KeyformGrid(grid.axes, newCells)) + } + is Deformer.Rotation -> { + val grid = deformer.geometryGrid ?: return deformer + val newCells = + grid.cells.map { cell -> + val origin = floatArrayOf(cell.form.originX, cell.form.originY) + val rootLocal = mapToRootLocal(oldParentId, origin, defaultValue) + val newLocal = mapFromRootLocal(newParentId, rootLocal, defaultValue) + KeyformCell( + cell.coordinate.copyOf(), + RotationPivotForm(newLocal[0], newLocal[1], cell.form.angle, cell.form.scale), + ) + } + deformer.copy(geometryGrid = KeyformGrid(grid.axes, newCells)) + } + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/DeleteEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/DeleteEdits.kt new file mode 100644 index 0000000..dd2e710 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/DeleteEdits.kt @@ -0,0 +1,357 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.mapPointsThroughWarpLattice +import org.umamo.runtime.eval.meshGridDefaultDeltas +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.runtime.model.withDerivedRenderRoot + +/* + * Entity deletion over the org tree. Removing a drawable, a deformer, or a part scrubs every dangling + * reference so no later code dereferences a deleted id. Deleting an art mesh is the only inherently + * destructive case; deleting a deformer "unwraps" it (its sub-deformers and bound meshes re-home to its + * parent, with child coordinates baked through the deleted deformer's rest lattice so art stays put); + * deleting a part is either a cascade (the part and its whole subtree) or an ungroup (the folder only, + * contents spliced up into its parent). Org-tree edits re-derive the render order. + * + * Deformer delete never touches the organizational part tree - Cubism's "Apply deformer to child + * elements", not "Delete Deformer and its Content". + */ + +/** A copy of this deformer re-nested under [newParent] in the transform hierarchy (used to re-home orphans). */ +private fun Deformer.reparentedTo(newParent: DeformerId?): Deformer = + when (this) { + is Deformer.Warp -> copy(parent = newParent) + is Deformer.Rotation -> copy(parent = newParent) + } + +/** A copy of this deformer re-bound to the organizational part [newPart] (or null to clear a dangling ref). */ +private fun Deformer.reboundToPart(newPart: PartId?): Deformer = + when (this) { + is Deformer.Warp -> copy(partId = newPart) + is Deformer.Rotation -> copy(partId = newPart) + } + +/** + * Returns a copy of [this] with every drawable in [ids] removed and every reference to them scrubbed: the + * drawables list, the org tree (their [OrgChild.Drawable] entries), any other drawable's clip mask, and any + * glue whose either partner was deleted. The render order is NOT re-derived here - the caller does that once + * it has finished its structural changes. An empty set returns the same instance. + * + * @param Set ids The drawables to delete. + * @return PuppetModel The model with those drawables and their references gone. + */ +internal fun PuppetModel.removingDrawables(ids: Set): PuppetModel { + if (ids.isEmpty()) { + return this + } + val remaining = + drawables.filterNot { drawable -> drawable.id in ids } + .map { drawable -> + val cleanedMasks = drawable.maskedBy.filterNot { maskId -> maskId in ids } + if (cleanedMasks.size != drawable.maskedBy.size) drawable.copy(maskedBy = cleanedMasks) else drawable + } + val cleanedGlues = glues.filterNot { glue -> glue.meshA in ids || glue.meshB in ids } + val cleanedRoot = rootChildren.filterNot { child -> child is OrgChild.Drawable && child.id in ids } + val cleanedParts = + parts.map { part -> + val kids = part.children.filterNot { child -> child is OrgChild.Drawable && child.id in ids } + if (kids.size != part.children.size) part.copy(children = kids) else part + } + return copy(drawables = remaining, glues = cleanedGlues, rootChildren = cleanedRoot, parts = cleanedParts) +} + +/** + * Returns a copy of [this] with the single drawable [id] deleted (mask / glue / tree references scrubbed, + * render order re-derived). A no-op (no such drawable) returns the same instance. + * + * @param DrawableId id The drawable to delete. + * @return PuppetModel The model without that drawable, or [this] if it was absent. + */ +fun PuppetModel.withDrawableDeleted(id: DrawableId): PuppetModel { + if (drawables.none { it.id == id }) { + return this + } + return removingDrawables(setOf(id)).withDerivedRenderRoot() +} + +/** + * Bakes a drawable that lived under a deleted warp into the warp's parent space: rest + every keyform + * absolute is mapped through the warp's rest lattice, then re-expressed as rest + deltas so default-pose + * art stays put. Does not change [Drawable.parentDeformerId] - the caller rebinds. + * + * @param Drawable drawable The child drawable. + * @param FloatArray cp Deleted warp's rest control points. + * @param Int columns Warp columns. + * @param Int rows Warp rows. + * @param Boolean bilinear Warp blend mode. + * @param Function defaultValue Default parameter values (for choosing the new rest). + * @return Drawable The baked drawable (same instance when mesh-less). + */ +private fun bakeDrawableThroughWarp( + drawable: Drawable, + cp: FloatArray, + columns: Int, + rows: Int, + bilinear: Boolean, + defaultValue: (ParameterId) -> Float, +): Drawable { + val mesh = drawable.mesh ?: return drawable + val rest = mesh.positions + val grid = drawable.geometryGrid + if (grid == null) { + val bakedRest = mapPointsThroughWarpLattice(rest, cp, columns, rows, bilinear) + return drawable.copy(mesh = DrawableMesh(bakedRest, mesh.uvs, mesh.indices)) + } + val defaultDeltas = meshGridDefaultDeltas(drawable, defaultValue) + val defaultAbs = + if (defaultDeltas == null) { + rest + } else { + FloatArray(rest.size) { index -> rest[index] + (defaultDeltas.getOrNull(index) ?: 0f) } + } + val newRest = mapPointsThroughWarpLattice(defaultAbs, cp, columns, rows, bilinear) + val newCells = + grid.cells.map { cell -> + val deltas = cell.form.positionDeltas + val absolute = + FloatArray(rest.size) { index -> + rest[index] + (deltas.getOrNull(index) ?: 0f) + } + val warpedAbs = mapPointsThroughWarpLattice(absolute, cp, columns, rows, bilinear) + val newDeltas = + FloatArray(warpedAbs.size) { index -> + warpedAbs[index] - newRest[index] + } + KeyformCell(cell.coordinate.copyOf(), MeshDeltaForm(newDeltas)) + } + return drawable.copy( + mesh = DrawableMesh(newRest, mesh.uvs, mesh.indices), + geometryGrid = KeyformGrid(grid.axes, newCells), + ) +} + +/** + * Bakes a child warp's rest lattice control points through a deleted parent warp. + * + * @param Deformer.Warp child The child warp. + * @param FloatArray parentCp Deleted parent's rest control points. + * @param Int parentColumns Parent columns. + * @param Int parentRows Parent rows. + * @param Boolean parentBilinear Parent blend mode. + * @param Function defaultValue Default parameter values. + * @return Deformer.Warp The baked child (reparent not applied). + */ +private fun bakeChildWarpThroughWarp( + child: Deformer.Warp, + parentCp: FloatArray, + parentColumns: Int, + parentRows: Int, + parentBilinear: Boolean, + defaultValue: (ParameterId) -> Float, +): Deformer.Warp { + val grid = child.geometryGrid ?: return child + val newCells = + grid.cells.map { cell -> + val baked = + mapPointsThroughWarpLattice(cell.form.controlPoints, parentCp, parentColumns, parentRows, parentBilinear) + KeyformCell(cell.coordinate.copyOf(), WarpLatticeForm(baked)) + } + // Also ensure a 0-axis / default sample stays coherent when the grid is empty-axes rest-only. + val defaultCps = warpControlPointsAt(KeyformGrid(grid.axes, newCells), defaultValue) + if (defaultCps == null && newCells.isEmpty()) { + return child + } + return child.copy(geometryGrid = KeyformGrid(grid.axes, newCells)) +} + +/** + * Returns a copy of [this] with the deformer [id] deleted by unwrapping it: its child deformers and the + * drawables it deformed are baked through its rest transform into its own parent space (null = an + * armature root), then rebound there, so removing a transform wrapper never deletes art and never + * touches the organizational part tree. A no-op (no such deformer) returns the same instance. + * + * @param DeformerId id The deformer to delete. + * @return PuppetModel The model without that deformer, or [this] if it was absent. + */ +fun PuppetModel.withDeformerDeleted(id: DeformerId): PuppetModel { + val deformer = deformers.firstOrNull { it.id == id } ?: return this + val grandParent = deformer.parent + val defaultValue: (ParameterId) -> Float = { paramId -> parameters.firstOrNull { it.id == paramId }?.default ?: 0f } + val bakeWarp = + (deformer as? Deformer.Warp)?.let { warp -> + val cp = warpControlPointsAt(warp.geometryGrid, defaultValue) ?: return@let null + BakeWarp(cp, warp.columns, warp.rows, warp.isQuadTransform) + } + val updatedDeformers = + deformers.filter { it.id != id } + .map { other -> + val reparented = if (other.parent == id) other.reparentedTo(grandParent) else other + if (bakeWarp != null && other.parent == id && reparented is Deformer.Warp) { + bakeChildWarpThroughWarp( + reparented, + bakeWarp.cp, + bakeWarp.columns, + bakeWarp.rows, + bakeWarp.bilinear, + defaultValue, + ) + } else { + reparented + } + } + val updatedDrawables = + drawables.map { drawable -> + if (drawable.parentDeformerId != id) { + return@map drawable + } + val baked = + if (bakeWarp != null) { + bakeDrawableThroughWarp( + drawable, + bakeWarp.cp, + bakeWarp.columns, + bakeWarp.rows, + bakeWarp.bilinear, + defaultValue, + ) + } else { + drawable + } + baked.copy(parentDeformerId = grandParent) + } + return copy(deformers = updatedDeformers, drawables = updatedDrawables) +} + +/** Rest lattice used to bake children when unwrapping a deleted warp. */ +private data class BakeWarp( + val cp: FloatArray, + val columns: Int, + val rows: Int, + val bilinear: Boolean, +) + +/** The set of part ids in [id]'s org-tree subtree (the part itself plus every descendant part). */ +private fun PuppetModel.partSubtreeIds(id: PartId): Set { + val partById = parts.associateBy { it.id } + val subtree = LinkedHashSet() + val stack = ArrayDeque() + stack.add(id) + while (stack.isNotEmpty()) { + val next = stack.removeLast() + if (!subtree.add(next)) { + continue + } + partById[next]?.children?.forEach { child -> if (child is OrgChild.Part) stack.add(child.id) } + } + return subtree +} + +/** + * Returns a copy of [this] with the part [id] deleted. A [cascade] removes the whole subtree - the part, + * every descendant part, and every drawable under any of them (references scrubbed); an ungroup (cascade + * false) dissolves only the folder - its children (sub-parts and drawables) splice into its parent in + * place, so nothing is destroyed. The render order is re-derived. A no-op (no such part) returns the same + * instance. + * + * @param PartId id The part to delete. + * @param Boolean cascade True to delete the subtree, false to ungroup (keep contents, splice them up). + * @return PuppetModel The model with the part deleted, or [this] if it was absent. + */ +fun PuppetModel.withPartDeleted(id: PartId, cascade: Boolean): PuppetModel { + val part = parts.firstOrNull { it.id == id } ?: return this + val partRef = OrgChild.Part(id) + // The deleted part's parent (where ungrouped contents land / dangling deformer bindings fall back to). + val grandParentId = parts.firstOrNull { partRef in it.children }?.id + return if (cascade) { + val subtree = partSubtreeIds(id) + val doomedDrawables = + parts.filter { it.id in subtree } + .flatMap { it.children } + .filterIsInstance() + .map { it.id } + .toSet() + // Drop the subtree parts; detach the part ref from wherever it sits (root or its parent). + val remainingParts = + parts.filterNot { it.id in subtree } + .map { candidate -> if (partRef in candidate.children) candidate.copy(children = candidate.children - partRef) else candidate } + val cleanedRoot = rootChildren.filter { it != partRef } + // A deformer's organizational partId may point into the deleted subtree; clear it so nothing dangles. + val cleanedDeformers = + deformers.map { deformer -> + if (deformer.partId != null && deformer.partId in subtree) deformer.reboundToPart(null) else deformer + } + copy(parts = remainingParts, rootChildren = cleanedRoot, deformers = cleanedDeformers) + .removingDrawables(doomedDrawables) + .copy(rootPartId = if (rootPartId != null && rootPartId in subtree) null else rootPartId) + .withDerivedRenderRoot() + } else { + // Ungroup: replace the part ref with the part's own children, in place, wherever it sits. + fun splice(children: List): List = children.flatMap { if (it == partRef) part.children else listOf(it) } + val cleanedRoot = splice(rootChildren) + val remainingParts = parts.filterNot { it.id == id }.map { it.copy(children = splice(it.children)) } + val cleanedDeformers = deformers.map { deformer -> if (deformer.partId == id) deformer.reboundToPart(grandParentId) else deformer } + copy( + parts = remainingParts, + rootChildren = cleanedRoot, + deformers = cleanedDeformers, + rootPartId = if (rootPartId == id) grandParentId else rootPartId, + ).withDerivedRenderRoot() + } +} + +/** + * Deletes the drawable [id] as one undo step. A no-op records nothing. + * + * @param DrawableId id The drawable to delete. + */ +fun EditorSession.deleteDrawable(id: DrawableId) { + mutate(DrawableChange.Delete(id)) { model -> model.withDrawableDeleted(id) } +} + +/** + * Deletes the deformer [id] (unwrapping it - children re-home to its parent with coordinates baked + * through) as one undo step. Never removes parts or art meshes. + * + * @param DeformerId id The deformer to delete. + */ +fun EditorSession.deleteDeformer(id: DeformerId) { + mutate(DeformerChange.Delete(id)) { model -> model.withDeformerDeleted(id) } +} + +/** + * Deletes the part [id] as one undo step: a cascade (subtree) when [cascade], else an ungroup (contents spliced up). + * + * @param PartId id The part to delete. + * @param Boolean cascade True to delete the subtree, false to ungroup. + */ +fun EditorSession.deletePart(id: PartId, cascade: Boolean) { + mutate(PartChange.Delete(id, cascade)) { model -> model.withPartDeleted(id, cascade) } +} + +/** + * Deletes the entity named by [target] as one undo step. [cascade] applies only to a part (a drawable or a + * deformer ignores it - a deformer always unwraps without destroying children). + * + * @param SelectionTarget target The entity to delete. + * @param Boolean cascade For a part, true to delete the subtree, false to ungroup; ignored otherwise. + */ +fun EditorSession.deleteTarget(target: SelectionTarget, cascade: Boolean) { + when (target) { + is SelectionTarget.Part -> deletePart(target.id, cascade) + is SelectionTarget.Drawable -> deleteDrawable(target.id) + is SelectionTarget.Deformer -> deleteDeformer(target.id) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/DuplicateEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/DuplicateEdits.kt new file mode 100644 index 0000000..50964a4 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/DuplicateEdits.kt @@ -0,0 +1,104 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot + +/** + * Duplicates one whole drawable (Object-mode Shift+D): the copy takes a Blender-style ".001"-suffixed + * unique id and name, a fresh mesh instance (positions copied so the copy edits independently; + * uvs / indices shared - the copy-on-write discipline), a re-wrapped keyform grid sharing the form + * payloads by reference (immutable in practice; a later edit copy-on-writes them), and its source's + * mask references. It sits immediately after its source in the org tree (or appends at the root when + * the source was never placed - the import safety net's rule), and carries NO glue membership: glues + * reference meshes by id, so a fresh id naturally welds nothing. + * + * 描画オブジェクトの複製。".001" 形式の一意な id と名前を付け、元の直後にツリー挿入する。 + * グルーには参加しない。 + * + * @param DrawableId id The drawable to duplicate. + * @return Pair? The edited model and the copy's id, or null when the source + * is missing or carries no mesh. + */ +fun PuppetModel.withDrawableDuplicated(id: DrawableId): Pair? { + val source = drawables.firstOrNull { candidate -> candidate.id == id } ?: return null + val mesh = source.mesh ?: return null + val copyId = uniqueDuplicateId(id) + val copy = + source.copy( + id = copyId, + name = uniqueDuplicateName(source.name), + mesh = DrawableMesh(mesh.positions.copyOf(), mesh.uvs, mesh.indices), + geometryGrid = + source.geometryGrid?.let { grid -> + KeyformGrid(grid.axes, grid.cells.map { cell -> KeyformCell(cell.coordinate, cell.form) }) + }, + // The atlas mapping is keyed by the source format's ids, so the copy resolves its texture + // through its source (or the original, when duplicating a duplicate). + textureSourceId = source.textureSourceId ?: source.id, + ) + + // Insert the copy immediately after its source, in whichever child list holds it. + var placed = false + + fun insertAfterSource(children: List): List { + if (placed) { + return children + } + val sourceIndex = children.indexOfFirst { child -> child is OrgChild.Drawable && child.id == id } + if (sourceIndex < 0) { + return children + } + placed = true + return children.toMutableList().apply { add(sourceIndex + 1, OrgChild.Drawable(copyId)) } + } + val newRootChildren = insertAfterSource(rootChildren) + val newParts = parts.map { part -> if (placed) part else part.copy(children = insertAfterSource(part.children)) } + val finalRootChildren = if (placed) newRootChildren else newRootChildren + OrgChild.Drawable(copyId) + val edited = + copy( + drawables = drawables + copy, + parts = newParts, + rootChildren = finalRootChildren, + ) + return edited.withDerivedRenderRoot().let { derived -> derived to copyId } +} + +/** + * The first free ".NNN"-suffixed id derived from [id] (d -> d.001, d.002, ...), so repeated duplicates + * never collide. + * + * @param DrawableId id The source id. + * @return DrawableId The unique copy id. + */ +private fun PuppetModel.uniqueDuplicateId(id: DrawableId): DrawableId { + var counter = 1 + while (true) { + val candidate = DrawableId("${id.raw}.${counter.toString().padStart(3, '0')}") + if (drawables.none { drawable -> drawable.id == candidate }) { + return candidate + } + counter++ + } +} + +/** + * The first free ".NNN"-suffixed display name derived from [name], mirroring [uniqueDuplicateId]. + * + * @param String name The source display name. + * @return String The unique copy name. + */ +private fun PuppetModel.uniqueDuplicateName(name: String): String { + var counter = 1 + while (true) { + val candidate = "$name.${counter.toString().padStart(3, '0')}" + if (drawables.none { drawable -> drawable.name == candidate }) { + return candidate + } + counter++ + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/EditorMode.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/EditorMode.kt new file mode 100644 index 0000000..f7fb9fb --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/EditorMode.kt @@ -0,0 +1,17 @@ +package org.umamo.edit + +/** + * The editor's interaction mode, Blender-style. Object mode selects whole entities (parts, drawables, + * deformers) and shows the rendered puppet; Edit mode dives into the active entity's interior (mesh, + * warp lattice, or rotation pivot). The mode scopes hit-testing and tool behaviour. v1 implements + * Object fully and leaves Edit as a routed stub. + * + * エディタの操作モード(Blender 流)。オブジェクトモードは要素全体を選択し、編集モードは内部を編集する。 + */ +enum class EditorMode { + /** Whole-entity selection and posing — the default. */ + Object, + + /** Interior editing of the active entity (stubbed in v1). */ + Edit, +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/EditorSession.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/EditorSession.kt new file mode 100644 index 0000000..777795c --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/EditorSession.kt @@ -0,0 +1,2586 @@ +package org.umamo.edit + +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog + +/** + * Where the shell surfaces a [Notice]: the status-bar slot, or a transient label next to the pointer + * (Blender's near-cursor "can't do this because" style, for feedback about a blocked viewport gesture). + */ +enum class NoticePlacement { + StatusBar, + NearCursor, +} + +/** + * Posed-space snapshot for Add Vertex wipe-and-rebuild: rest, posed-local, and world arrays at the same + * vertex count, captured while the live mesh still had verts. + * + * @property FloatArray base Rest positions ([DrawableMesh.positions]). + * @property FloatArray displayed Posed local (base + keyform blend). + * @property FloatArray world [displayed] through the deformer chain. + */ +class AddVertexSpaceSeed( + val base: FloatArray, + val displayed: FloatArray, + val world: FloatArray, +) + +/** + * A transient user notice: a stable message key plus a monotonic [serial] that distinguishes it from an + * identical earlier message, so the UI can re-time its dismissal even when the same notice repeats. + * Carries a key rather than display text so this module stays presentation-free and the UI layer resolves + * the localized string (the same pattern as [Change.labelKey]). + * + * @property String messageKey The stable notice key the UI layer resolves to a localized message. + * @property Long serial The stamping order (see [EditorSession.emitNotice]); higher is newer. + * @property NoticePlacement placement Where the shell surfaces this notice. + * @property List arguments The values the localized message formats in, in its placeholder order + * (a count, a file name); empty for a message with none. Strings rather than typed values so this + * module stays presentation-free - the UI layer only substitutes. + */ +data class Notice( + val messageKey: String, + val serial: Long, + val placement: NoticePlacement, + val arguments: List = emptyList(), +) + +/** + * The single mutable owner of one open document: the live [model], the ephemeral editor state + * ([selection], [mode]), the undo [History], and the change-event bus. Every edit flows through here so + * undo, change events, and dirty-tracking stay consistent. + * + * Two channels, per the history design: [changes] emits on every mutation (the "everything emits a + * change event" completeness), while the history stack records only the undoable subset. A document + * mutation ([mutate]) and a selection gesture ([setSelection]) each push one step; a mode toggle + * ([setMode]) and future tool/brush switches are transient — they emit but never become steps. + * + * Undo is by immutable snapshot, never inverse op: [undo] / [redo] just republish a stored + * [EditorSnapshot]. Dirty is reference-equality of the model against the last-saved instance — because + * undo restores the exact prior model instance and selection-only steps reuse the same instance, + * `model !== savedModel` is correct across undo/redo and is never tripped by a bare selection change. + * + * Held on the UI thread (Compose drives it); the render host observes [model] / [selection] as flows. + * Compose-free by design (its module mandate), so it exposes coroutines flows, not Compose state. + * + * @param PuppetModel initialModel The document model at open. + * @param Pose initialPose The pose at open (the displayed scrub values); defaults to every parameter's + * default. The host passes the renderer's starting values so the session, the panel, and the viewport + * agree from frame one (e.g. a headless dump's overridden pose is not reset to defaults). + * @param Int initialHistoryLimit The retained-undo-step cap at open; [historyLimit] carries it and the + * host reassigns it when the preference changes. + * @param SessionViewState? initialViewState The session state the document was saved with, or null for a plain + * open. It is fitted to the model and laid into the FIRST snapshot and the tool latches, so what a rigger + * reopens to is where the history starts - never a run of undo steps, and never a dirty mark. + */ +class EditorSession( + initialModel: PuppetModel, + initialPose: Pose = initialModel.parameters.associate { parameter -> parameter.id to parameter.default }, + initialHistoryLimit: Int = DEFAULT_HISTORY_LIMIT, + initialViewState: SessionViewState? = null, +) { + // The saved session state with every reference the model cannot satisfy taken out, and the snapshot the + // session opens on. Declared first: the history and every snapshotted flow below start from it. + private val openingViewState: SessionViewState? = initialViewState?.fittedTo(initialModel) + private val openingSnapshot: EditorSnapshot = openingSnapshotOf(initialModel, initialPose, openingViewState) + + // The session's collaborators - the undo machinery (stack, saved baseline, derived flags), the + // area-request buses, the remembered-selection memory, and the tool latches; the members below + // delegate so the public API is unchanged, and every flow-write ordering stays in this facade. + private val history = HistoryCore(openingSnapshot, initialHistoryLimit) + private val requestBus = SessionRequestBus() + private val elementMemory = MeshElementMemory() + private val latches = ToolLatches(notify = ::emitNotice).also { created -> openingViewState?.let(created::seed) } + + /** + * Per-drawable mesh frozen at Edit enter only (never shrunk by deletes). Wipe-and-rebuild Accept + * bary/nearest-samples UVs from this original mesh onto the new floats. + */ + private val meshUvSeedByDrawable = HashMap() + + /** + * Posed space snapshots captured once at Edit enter. After a full wipe the live arrays and keyform + * deltas are empty, so Accept still needs this original snapshot to invert viewport clicks. + */ + private val meshSpaceSeedByDrawable = HashMap() + + /** + * Optional viewport world → mesh-base map for Add Vertex Accept. The Edit overlay installs the + * deformer inverse so draft floats can stay under the cursor in world space while the committed + * mesh stores rest positions. Null means draft coords are already mesh-base (UV editor). + */ + var addVertexWorldToBase: ((DrawableId, Float, Float) -> Pair)? = null + + /** + * The Edit-enter mesh kept for wipe-and-rebuild UV projection, or null. + * + * @param DrawableId drawableId The session drawable. + * @return DrawableMesh? The seed mesh. + */ + fun addVertexUvSeed(drawableId: DrawableId): DrawableMesh? = meshUvSeedByDrawable[drawableId] + + /** + * The Edit-enter posed-space snapshot for wipe-and-rebuild click inversion, or null. + * + * @param DrawableId drawableId The session drawable. + * @return AddVertexSpaceSeed? The base / displayed / world arrays. + */ + fun addVertexSpaceSeed(drawableId: DrawableId): AddVertexSpaceSeed? = meshSpaceSeedByDrawable[drawableId] + + /** + * Remembers posed space for [drawableId] once (Edit overlay at enter). Later calls no-op so deletes + * cannot replace the original with a shrunken scrap. + * + * @param DrawableId drawableId The session drawable. + * @param FloatArray base Rest positions. + * @param FloatArray displayed Posed local positions. + * @param FloatArray world World-projected positions. + */ + fun rememberAddVertexSpaceSeed(drawableId: DrawableId, base: FloatArray, displayed: FloatArray, world: FloatArray) { + if (meshSpaceSeedByDrawable.containsKey(drawableId)) { + return + } + if (base.size < 2 || displayed.size != base.size || world.size != base.size) { + return + } + meshSpaceSeedByDrawable[drawableId] = + AddVertexSpaceSeed(base.copyOf(), displayed.copyOf(), world.copyOf()) + } + + // The live step's predecessor as of the last push - the base an operation registering itself as + // adjustable ran from. Consumed by the registration and voided by a restore, so a registration can + // never pair an operation with some other step's base. + private var lastBaseSnapshot: EditorSnapshot? = null + + private val mutableAdjustableOperation = MutableStateFlow(null) + + /** + * The one operation that may still be adjusted (Blender's redo strip), or null. Set by + * [registerAdjustableOperation] right after an operation commits; cleared by any other history + * push, selection pushes included, and by every undo / redo / jump - the strip belongs to the newest + * step only. + */ + val adjustableOperation: StateFlow = mutableAdjustableOperation.asStateFlow() + + /** + * The model this session opened on - the document's own puppet, before any edit. + * + * Exposed so a host can verify that a session belongs to the document it is about to act on: + * a session outlives nothing, but a stale one paired with a fresh document would silently + * apply the PREVIOUS model's rig (see the export guard in EditorApp). + */ + val baselineModel: PuppetModel = initialModel + + private val mutableModel = MutableStateFlow(initialModel) + + /** The live document model; panels read it, the render host observes it. */ + val model: StateFlow = mutableModel.asStateFlow() + + private val mutableSelection = MutableStateFlow(openingSnapshot.selection) + + /** The live object-mode selection. */ + val selection: StateFlow = mutableSelection.asStateFlow() + + private val mutableParameterSelection = MutableStateFlow(openingSnapshot.parameterSelection) + + /** + * The parameters targeted for keyform authoring - which parameter an insert would write a key on. + * + * Independent of [selection]: the object selection says WHAT to key, this says on WHICH AXIS. + */ + val parameterSelection: StateFlow = mutableParameterSelection.asStateFlow() + + private val mutablePendingChannelEdits = MutableStateFlow>(emptyMap()) + + /** + * Channel values edited but NOT yet keyed - Blender's model, where changing a keyed property off a key + * takes effect now but is lost unless you key it. + * + * Deliberately NOT in the document: a pending edit never reaches [PuppetModel], so it costs nothing in + * document terms and a keyform insert can consume it without that being a document edit either. It IS in + * the undo history, one step per gesture end (see [commitPendingChannelEdit]) rather than per keystroke - + * a per-frame preview ([setPendingChannelEdit]) records nothing on its own. Every pending value is + * cleared whenever the pose moves, because a value chosen FOR one pose is meaningless at another; a + * history jump does not clear them, since [restore] lands on the very pose they were chosen for and + * restores them alongside it. + * + * The keyed-field tint reads this to show the edited-but-unkeyed state, and a keyform insert consumes + * it: the whole point is that `I` captures what you just typed rather than what is still stored. + */ + val pendingChannelEdits: StateFlow> = mutablePendingChannelEdits.asStateFlow() + + private val mutableKeySelection = MutableStateFlow>(emptySet()) + + /** + * The keyform sheet's selected keys - what its Delete and nudge commands act on. + * + * Shell-wide rather than per-sheet: it is snapshotted, and undo restores session state. Two open sheets + * therefore share one selection, which is the same call [parameterSelection] made and for the same + * reason - a second sheet showing a different answer to "what is selected" is worse than agreement. + */ + val keySelection: StateFlow> = mutableKeySelection.asStateFlow() + + private val mutablePose = MutableStateFlow(initialPose) + + /** The live pose (parameter scrub values); the render host mirrors it so undo / redo re-poses. */ + val pose: StateFlow = mutablePose.asStateFlow() + + private val mutableMode = MutableStateFlow(openingSnapshot.mode) + + /** + * The live interaction mode. Snapshotted (a mode change is its own undo step), and pose-neutral by + * contract: entering or leaving Edit mode NEVER writes the pose — Edit mode's rest view is a + * display-only override in the render host, so the Object-mode pose survives an Edit session + * untouched with no stashed state to juggle. + */ + val mode: StateFlow = mutableMode.asStateFlow() + + private val mutableMeshSelection = MutableStateFlow(openingSnapshot.meshSelection) + + /** The live Edit-mode element selection; snapshotted, so a selection gesture is undoable. */ + val meshSelection: StateFlow = mutableMeshSelection.asStateFlow() + + /** + * The modal mesh operator currently running (Grab / Scale / Rotate) with its initiating viewport area, + * or null. Transient UI coordination (not snapshotted, not on the bus): a registry command latches it, + * the initiating area's gizmo overlay observes it to drive the gesture (bystander viewports stay + * inert), and clears it on confirm / cancel. + */ + val activeMeshOperator: StateFlow = latches.activeMeshOperator + + /** + * The modal OBJECT operator currently running (Grab / Scale / Rotate over the selected drawables' whole + * geometry) with its initiating viewport area, or null. The Object-mode sibling of [activeMeshOperator]: + * a separate latch because the object overlay captures N drawables where the mesh overlay captures one, + * so the two must be distinguishable. Transient UI coordination like [activeMeshOperator] - not + * snapshotted, not on the bus - latched by a registry command, observed by the initiating area's object + * gizmo overlay, cleared on confirm / cancel / leaving Object mode. + */ + val activeObjectOperator: StateFlow = latches.activeObjectOperator + + /** + * The modal UV operator currently running (Grab / Scale / Rotate over the selected vertices' texture + * coordinates) with its initiating UV-editor area, or null. The UV-editor sibling of + * [activeMeshOperator]: a separate latch so the puppet viewport's gizmo overlays and the UV editor's + * overlay can never cross-capture one gesture (each overlay's capture effect keys on its own latch). + * Transient UI coordination like the others - not snapshotted, not on the bus - latched by a registry + * command, observed by the initiating area's UV overlay, cleared on confirm / cancel / leaving Edit mode. + */ + val activeUvOperator: StateFlow = latches.activeUvOperator + + /** + * The one modal transform operator running, from whichever of the three families latched it, or null. + * + * The families are mutually exclusive, so callers that only need to know whether SOME transform is in + * flight - the shell's modal key ladder, deciding who owns Escape / Enter / the axis keys - ask this + * instead of testing all three. An instantaneous read, not a flow: see [ToolLatches.activeOperator]. + */ + val activeOperator: ActiveOperator? + get() = latches.activeOperator + + /** + * Whether nothing is in flight that a model change would land under: no modal transform operator, + * no viewport gesture, no circle-select stroke, no armed select tool, and no open pie menu. The gate + * a watched-file reload waits behind, so the art never changes under a hand that is mid-drag. An + * instantaneous read, like [activeOperator]. + */ + val isQuiescent: Boolean + get() = + latches.activeOperator == null && + !latches.viewportGestureActive.value && + latches.previewSelection.value == null && + latches.activeSelectTool.value == null && + latches.activePieMenu.value == null + + /** + * Cancels whichever modal transform operator is running, if any - the family-agnostic counterpart to + * [clearMeshOperator] / [clearObjectOperator] / [clearUvOperator]. + */ + fun clearActiveOperator() { + latches.clearActiveOperator() + } + + /** + * The transient preview of which drawables an in-flight Object-mode circle stroke is painting, or null when + * no stroke is live. The GPU-tint bridge overlays this on top of the committed [selection] so painted + * drawables light up immediately without committing each frame (which would spam undo). Not snapshotted, + * not on the bus (transient UI coordination like [activeSelectTool]); the stroke commits once on release + * via [setSelection] and clears this back to null. + */ + val previewSelection: StateFlow?> = latches.previewSelection + + /** + * Publishes the transient circle-stroke preview selection (see [previewSelection]); pass null to clear it. + * + * @param Set? drawableIds The drawables currently painted by the stroke, or null to clear. + */ + fun setPreviewSelection(drawableIds: Set?) { + latches.setPreviewSelection(drawableIds) + } + + /** + * True while a viewport overlay is driving a non-armed pointer gesture (today: the Object-mode + * un-armed box drag), so the shell can route Escape to a gesture cancel instead of its next Escape + * behavior (clearing the object selection). Transient UI coordination like [previewSelection] - not + * snapshotted, not on the bus; the overlay sets it at press and clears it on release or cancel. + */ + val viewportGestureActive: StateFlow = latches.viewportGestureActive + + /** + * Publishes whether a non-armed viewport gesture is in flight (see [viewportGestureActive]). + * + * @param Boolean active True while the overlay's gesture owns the pointer. + */ + fun setViewportGestureActive(active: Boolean) { + latches.setViewportGestureActive(active) + } + + private val mutableNotice = MutableStateFlow(null) + + /** + * The current transient user notice, or null when none is showing. A short message the shell surfaces + * briefly (near the status bar) to explain why an action did nothing. Deliberately off the undo history and + * the change bus - a notice is momentary feedback, never document state. Used today when an Object-mode + * transform blocks because the selection holds a part, a deformer, or a mesh-less drawable. A StateFlow (not + * a one-shot event) so the shell reads it with the standard collectAsState path and a late subscriber still + * sees an in-flight notice; the [Notice.serial] lets the shell time its dismissal and re-trigger on a repeat + * of the same text. + */ + val notice: StateFlow = mutableNotice.asStateFlow() + + // Monotonic id stamped on each notice so an identical repeated message is still a distinct event the shell + // can re-time. Not a clock (unavailable here) - just a counter. + private var noticeSerial: Long = 0L + + /** + * Emits a transient user notice (see [notice]); it stays current until dismissed via [clearNotice] or + * replaced by a newer one. + * + * @param String messageKey The stable notice key the UI layer resolves to a localized message. + * @param NoticePlacement placement Where the shell surfaces the notice. + * @param List arguments The values the message formats in, in its placeholder order. + */ + fun emitNotice(messageKey: String, placement: NoticePlacement = NoticePlacement.StatusBar, arguments: List = emptyList()) { + noticeSerial += 1 + mutableNotice.value = Notice(messageKey, noticeSerial, placement, arguments) + } + + /** + * Dismisses the notice with the given [serial], but only if it is still the current one - so a dismissal + * timer for an older notice never clears a newer message that arrived in the meantime. + * + * @param Long serial The serial of the notice to dismiss (from [Notice.serial]). + */ + fun clearNotice(serial: Long) { + if (mutableNotice.value?.serial == serial) { + mutableNotice.value = null + } + } + + /** + * The Edit-mode selection tool currently armed (Box or Circle), or null. Transient UI coordination like + * [activeMeshOperator] (not snapshotted, not on the bus): a registry command latches it, the gizmo overlay + * observes it to reinterpret pointer input, and it clears on completion / cancel / leaving Edit mode. + */ + val activeSelectTool: StateFlow = latches.activeSelectTool + + /** + * The viewport area id whose Zoom Region gesture is armed (Blender's Shift+B), or null. Mode-agnostic - + * Zoom Region works in Object and Edit mode alike - so it is keyed by area rather than gated on the mode, + * and the top-level region overlay for that area reads it to capture the drag. Transient, not snapshotted. + */ + val zoomRegionArmedArea: StateFlow = latches.zoomRegionArmedArea + + private val mutableChanges = MutableSharedFlow(extraBufferCapacity = 64) + + /** The change-event bus: every mutation emits here, the undoable ones and the transient ones alike. */ + val changes: SharedFlow = mutableChanges.asSharedFlow() + + /** True when the document model differs from the last-saved state (drives the title/status marker). */ + val dirty: StateFlow = history.dirty + + /** True when there is a step to undo (drives the Edit-menu item's enabled state). */ + val canUndo: StateFlow = history.canUndo + + /** True when there is a step to redo. */ + val canRedo: StateFlow = history.canRedo + + /** The undo stack projected for the history panel; updates on every edit, undo, redo, jump, and save. */ + val historyView: StateFlow = history.historyView + + /** + * The retained-undo-step cap. The host writes it from the user preference - once when the document + * opens and again on every committed change - so the session never reads settings itself. + * + * Lowering it trims the stack at once rather than waiting for the next edit, but never past the live + * step, so the current state and its redo branch always survive; the excess sheds on subsequent + * pushes. The write republishes the derived flags, so the panel drops the same rows the stack did and + * [canUndo] stays honest when the trim lands the cursor on the oldest entry. + */ + var historyLimit: Int + get() = history.limit + set(value) { + history.limit = value + refreshFlags() + } + + /** + * Records one history step - the single path every push takes, so the adjustable-operation record + * cannot outlive the step it belongs to and the base of the next registration is always the step + * being left. + * + * @param EditorSnapshot snapshot The new live state. + * @param Change change The change that produced it. + */ + private fun pushStep(snapshot: EditorSnapshot, change: Change) { + mutableAdjustableOperation.value = null + lastBaseSnapshot = history.current + history.push(snapshot, change) + } + + /** + * Registers the operation that just committed [committedModel] as adjustable: the strip shows its + * [parameters], and editing one calls [rerun] with the updated record, which recomputes from the + * record's base and lands through [amendLastCommit]. + * + * Call it right after the operation's own commit. Refuses (null) when nothing was pushed since the + * last registration or restore, or when the live model is not [committedModel] - a client that + * committed nothing (a no-op edit) must not register against some other step's base. + * + * @param PuppetModel committedModel The model the operation's commit published. + * @param String? areaId The area the operation ran in, or null. + * @param List parameters The operation's settings as it ran. + * @param Function rerun Runs the operation again under the record it is given. + * @return AdjustableOperation? The record now live, or null when the registration was refused. + */ + fun registerAdjustableOperation( + committedModel: PuppetModel, + areaId: String?, + parameters: List, + rerun: (AdjustableOperation) -> Unit, + ): AdjustableOperation? { + val base = lastBaseSnapshot ?: return null + val change = history.currentChange ?: return null + if (mutableModel.value !== committedModel) { + return null + } + lastBaseSnapshot = null + val record = AdjustableOperation(change, areaId, parameters, base, rerun, identity = Any()) + mutableAdjustableOperation.value = record + return record + } + + /** + * Adjusts the live adjustable operation: publishes [parameters] as its settings and runs it again. + * A no-op while no operation is adjustable. + * + * @param List parameters The new settings, in the record's order. + */ + fun adjustLastOperation(parameters: List) { + val current = mutableAdjustableOperation.value ?: return + val updated = current.withParameters(parameters) + mutableAdjustableOperation.value = updated + updated.rerun(updated) + } + + /** + * Lands an adjustment: replaces the operation's own history step with [model] and publishes it, + * keeping the record live for the next adjustment. Nothing is undone and nothing is replayed - the + * step is rewritten in place ([History.amendTop]). + * + * Refuses when [operation] is not the live record (it was cleared by another push, an undo, or a + * document swap while an asynchronous rerun was in flight - the result is dropped, never committed + * over whatever the rigger did meanwhile) or when the stack refuses the amend. + * + * @param AdjustableOperation operation The record the rerun was given. + * @param PuppetModel model The recomputed document model. + * @return Boolean True when the step was replaced and published. + */ + fun amendLastCommit(operation: AdjustableOperation, model: PuppetModel): Boolean { + val current = mutableAdjustableOperation.value + if (current == null || current.identity !== operation.identity) { + return false + } + if (!history.amendTop(snapshot(model = model), operation.change)) { + return false + } + mutableModel.value = model + refreshFlags() + mutableChanges.tryEmit(operation.change) + return true + } + + /** + * Applies a document edit: computes the new model via [transform], records it as one undo step, and + * publishes it. The [change] describes the edit for the bus and the history-panel label. A transform + * that returns the same model instance (a no-op edit) records nothing, so callers need not pre-check. + * + * @param Change change The descriptor of this edit (its [Change.undoability] is assumed undoable here). + * @param Function transform Produces the new model from the current one. + */ + fun mutate(change: Change, transform: (PuppetModel) -> PuppetModel) { + commit(change, transform(mutableModel.value), mutablePose.value) + } + + /** + * Commits one undo step from an already-computed [model] and [pose], recording it and publishing both. + * The single choke point behind [mutate] (model edits), [commitPose] (scrubs), and [setParameterRange] + * (both at once). A commit that changes neither the model instance nor the pose records nothing, so + * callers need not pre-check. Dirty is measured against the model only, so a pose-only commit (a scrub) + * is an undo step without marking the document unsaved, exactly like a selection gesture. + * + * @param Change change The descriptor of this edit (for the bus and the history-panel label). + * @param PuppetModel model The new document model (same instance as now for a pose-only commit). + * @param Pose pose The new live pose (same value as now for a model-only commit). + */ + + private fun commit(change: Change, model: PuppetModel, pose: Pose) { + if (model === mutableModel.value && pose == mutablePose.value) { + return + } + // A pose move invalidates every pending edit: the value was chosen for the pose being left. + if (pose != mutablePose.value) { + clearPendingChannelEdits() + } + pushStep(snapshot(model = model, pose = pose), change) + mutableModel.value = model + mutablePose.value = pose + refreshFlags() + mutableChanges.tryEmit(change) + } + + /** + * A snapshot of the session's current state, with any field overridden. + * + * Every history push goes through this rather than calling [EditorSnapshot] directly. The constructor's + * own defaults are dangerous here: a field added later would default to its EMPTY value at every existing + * call site, which compiles cleanly but would silently record the wrong state - for example, undoing an + * unrelated edit would clear the parameter target instead of leaving it as it was. Defaulting to live + * state instead makes the omission harmless. + */ + private fun snapshot( + model: PuppetModel = mutableModel.value, + selection: Selection = mutableSelection.value, + pose: Pose = mutablePose.value, + meshSelection: MeshSelection = mutableMeshSelection.value, + mode: EditorMode = mutableMode.value, + parameterSelection: ParameterSelection = mutableParameterSelection.value, + pendingChannelEdits: Map = mutablePendingChannelEdits.value, + keySelection: Set = mutableKeySelection.value, + ): EditorSnapshot = + EditorSnapshot( + model, + selection, + pose, + meshSelection, + mode, + parameterSelection, + pendingChannelEdits, + keySelection, + ) + + /** + * Commits a parameter scrub as one undo step: the live [pose] reached a new resting position (a slider + * or 2D-pad gesture released, a value typed, a reset). Mid-gesture preview frames bypass this and reach + * the renderer directly, so a whole drag is a single step. The model is unchanged, so this does not + * mark the document dirty. A commit equal to the current pose records nothing. + * + * @param Change change The scrub descriptor (a [ParameterChange.SetValue]). + * @param Pose pose The pose to commit (the gesture's final parameter values). + */ + fun commitPose(change: Change, pose: Pose) { + commit(change, mutableModel.value, pose) + } + + /** + * Records [value] as an unkeyed edit of [target] - a value the user typed that is not stored anywhere yet. + * + * Transient by construction: no history step, no model change. The next pose move discards it, which is + * the behaviour rather than a limitation - the value was chosen FOR this pose, so carrying it to another + * would be applying an edit somewhere it was never meant. + * + * @param KeyableTarget target The property edited. + * @param ChannelValue value The value typed. + */ + fun setPendingChannelEdit(target: KeyableTarget, value: ChannelValue) { + mutablePendingChannelEdits.value = mutablePendingChannelEdits.value + (target to value) + } + + /** + * Records [value] as an unkeyed edit of [target] AND as one undo step, described by [change]. + * + * What a keyable property field calls when its gesture ends, where [setPendingChannelEdit] is what it + * calls per frame while the gesture is still running. A pending edit is still transient - the next pose + * move discards it - but discarding is not the same as never having happened: it is a deliberate edit + * the user can see take effect in the viewport, so it must be undoable independent of whether it ever + * reaches the document. + * + * Pushes its own snapshot rather than going through [mutate] / [commit], for the same reason + * [setSelection] and [setMeshSelection] do: neither the model nor the pose changes, so the commit choke + * point would short-circuit and record nothing. Not a document edit, so it leaves dirty untouched. + * + * [change] is the SAME descriptor the unkeyed path would have used, so the history entry reads "Set + * Opacity" whichever branch the edit took - which branch it took is an implementation detail of where + * the value could be stored, not something a rigger asked for. + * + * @param KeyableTarget target The property edited. + * @param ChannelValue value The value the user chose. + * @param Change change The descriptor of this edit (for the bus and the history-panel label). + */ + fun commitPendingChannelEdit(target: KeyableTarget, value: ChannelValue, change: Change) { + // Compared against what HISTORY holds, not against the live map: a scrub has already written its last + // preview frame there, so a live-map comparison makes the release of every drag look like a no-op and + // records nothing - the one case this exists for. + if (history.current.pendingChannelEdits[target] == value) { + // Still published: the guard says this step would record nothing new, not that the value is live. + // The two diverge whenever something retired the pending edit without recording that it did - a + // scrub previews through clearPendingChannelEdits and then ends where it began - and returning + // outright left the re-typed value out of the viewport and the field untinted. + setPendingChannelEdit(target, value) + return + } + val edits = mutablePendingChannelEdits.value + (target to value) + pushStep(snapshot(pendingChannelEdits = edits), change) + mutablePendingChannelEdits.value = edits + refreshFlags() + mutableChanges.tryEmit(change) + } + + /** + * Discards every pending unkeyed edit. + * + * Called on any pose move - the situation that invalidates ALL of them at once, since every pending value + * was chosen for the pose being left. A history jump does NOT call this: [restore] restores the + * snapshot's own [EditorSnapshot.pendingChannelEdits] instead, since the pose it lands on is exactly the + * pose those values were chosen for. A keyform insert that consumed one target's value uses + * [clearPendingChannelEdit] instead, because the other targets' values are still valid for the unchanged + * pose. + */ + fun clearPendingChannelEdits() { + if (mutablePendingChannelEdits.value.isNotEmpty()) { + mutablePendingChannelEdits.value = emptyMap() + } + } + + /** + * Discards the pending unkeyed edit of [target] alone. + * + * The keyform-insert path: the capture consumed this one value, and the pose did not move, so every + * other target's pending value is still the value its user chose for the current pose. + * + * @param KeyableTarget target The property whose pending edit was consumed. + */ + fun clearPendingChannelEdit(target: KeyableTarget) { + if (mutablePendingChannelEdits.value.containsKey(target)) { + mutablePendingChannelEdits.value = mutablePendingChannelEdits.value - target + } + } + + /** + * Sets parameter [id]'s range and default, and re-clamps its live pose value into the new range — all + * as one undo step. A model edit (the range is document content), so it marks the document dirty; the + * pose re-clamp rides the same step so undo restores both together. A no-op range records nothing. + * + * @param ParameterId id The parameter to retarget. + * @param Float min The requested minimum. + * @param Float default The requested default (clamped into the resulting range). + * @param Float max The requested maximum. + */ + fun setParameterRange(id: ParameterId, min: Float, default: Float, max: Float) { + val newModel = mutableModel.value.withParameterRange(id, min, default, max) + if (newModel === mutableModel.value) { + return + } + // Re-clamp the live value into the resulting (normalized) range so the pose stays valid. + val parameter = newModel.parameters.firstOrNull { it.id == id } + val newPose = + if (parameter != null) { + val current = mutablePose.value[id] + val clamped = current?.coerceIn(parameter.min, parameter.max) + if (clamped != null && clamped != current) { + mutablePose.value + (id to clamped) + } else { + mutablePose.value + } + } else { + mutablePose.value + } + val change = ParameterChange.SetRange(id, parameter?.min ?: min, parameter?.default ?: default, parameter?.max ?: max) + commit(change, newModel, newPose) + } + + /** + * Links parameter [horizontal] with [vertical] (the next parameter below it in panel order) into + * one 2D pad, or removes that link, as one undo step. A model edit (the link is document content), + * so it marks the document dirty. The pose needs no care here: a link only changes presentation, + * both parameters keep their live values by construction. An invalid request returns the same + * model instance from [withParameterLink], so the commit short-circuit records nothing. + * + * @param ParameterId horizontal The X-axis (upper) parameter. + * @param ParameterId vertical The Y-axis parameter. + * @param Boolean linked True to create the link, false to remove it. + */ + fun setParameterLink(horizontal: ParameterId, vertical: ParameterId, linked: Boolean) { + val newModel = mutableModel.value.withParameterLink(horizontal, vertical, linked) + if (newModel === mutableModel.value) { + return + } + if (!linked) { + // A pad targets BOTH its axes; once they are two separate sliders that reads as a multi-selection + // the panel cannot otherwise produce, so the target narrows to the one that was active. Narrowed + // BEFORE the commit, so the pushed snapshot carries the narrowed target and a later redo cannot + // restore the multi-selection. + val target = mutableParameterSelection.value + if (target.ids.size > 1) { + mutableParameterSelection.value = + target.active?.let { ParameterSelection.of(it) } ?: ParameterSelection() + } + } + commit(ParameterChange.SetLink(horizontal, vertical, linked), newModel, mutablePose.value) + } + + /** + * Deletes parameter [id] everywhere - the axis list, the panel tree, any link, every object's keyform + * grid / blend-shape binding, and the live pose - as one undo step. Without [moveKeysTo] each axis + * collapses to the default slice; with it, matching axes retarget onto that destination (key values + * and forms kept). A model edit, so it marks the document dirty; dropping the pose entry rides the + * same step so undo restores both. A member (not a mutate extension) because it commits a new model + * and a new pose together, like [setParameterRange]. A no-op (no such parameter, or an invalid move) + * records nothing. + * + * @param ParameterId id The parameter to delete. + * @param ParameterId? moveKeysTo Destination to retarget keys onto, or null to discard them. + */ + fun deleteParameter(id: ParameterId, moveKeysTo: ParameterId? = null) { + val newModel = mutableModel.value.withParameterDeleted(id, moveKeysTo) + if (newModel === mutableModel.value) { + return + } + // The target must never dangle on a parameter the model no longer has - pruned BEFORE the commit, + // so the pushed snapshot carries the pruned selection and a later redo (or a History jump to this + // entry) cannot restore the dangling id. + mutableParameterSelection.value = + mutableParameterSelection.value.prunedTo(newModel.parameters.mapTo(HashSet()) { parameter -> parameter.id }) + commit(ParameterChange.Delete(id, moveKeysTo), newModel, mutablePose.value - id) + } + + /** + * Records a selection gesture as its own undo step (the chosen Blender-faithful granularity), so a + * misclick that clears the selection is recoverable. A no-op (selecting the already-current + * selection) records nothing. + * + * @param Selection selection The new selection. + */ + + fun setSelection(selection: Selection) { + if (selection == mutableSelection.value) { + return + } + (selection.active as? SelectionTarget.Drawable)?.let { activeDrawable -> + elementMemory.lastActiveDrawableId = activeDrawable.id + } + pushStep( + snapshot(selection = selection), + EditorStateChange.SelectionChanged, + ) + mutableSelection.value = selection + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.SelectionChanged) + } + + /** + * Sets the parameters targeted for keyform authoring as its own undo step. + * + * Pushes its own snapshot rather than going through [mutate] / [commit], exactly like [setSelection]: + * neither the model nor the pose changes, so the commit choke point would short-circuit and record + * nothing. Shared session state rather than a panel's view state, so every area agrees on which + * parameter an insert would write to. + * + * @param ParameterSelection parameterSelection The new target set. + */ + fun setParameterSelection(parameterSelection: ParameterSelection) { + if (parameterSelection == mutableParameterSelection.value) { + return + } + pushStep(snapshot(parameterSelection = parameterSelection), EditorStateChange.ParameterSelectionChanged) + mutableParameterSelection.value = parameterSelection + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.ParameterSelectionChanged) + } + + /** + * Sets the interaction mode as its own undo step, so undo restores the mode (and the mesh selection + * it seeds) together - the editor never lands in Edit mode showing a state captured in Object mode. + * Entering Edit seeds the session with EVERY selected mesh-carrying drawable (multi-mesh edit; the + * object selection's active drawable becomes the session's active mesh), falling back to the last + * drawable that was active (Blender's remembered selection) when nothing is selected, and past that + * to the topmost editable drawable in Parts-panel order (so a fresh document lands on something to + * edit rather than an inert session); the remembered fallback is skipped if that drawable no longer + * exists in the model. When the model has nothing editable at all, entering Edit is refused - the + * mode stays Object and nothing is recorded - so Edit mode always holds meshes. Leaving Edit stashes the + * element selection and clears it; re-entering on the same drawable restores the stash when every + * element still fits the mesh (Blender's remembered mesh selection). Leaving also ends any in-flight + * operator. The mode is editor state, not document content, so it does not dirty the document. A no-op + * (already in [mode]) records nothing. + * + * @param EditorMode mode The new mode. + */ + fun setMode(mode: EditorMode) { + if (mode == mutableMode.value) { + return + } + val newMeshSelection = + when (mode) { + EditorMode.Edit -> { + val model = mutableModel.value + // The session spans EVERY selected mesh-carrying drawable (multi-mesh edit, needed for + // glue work); the object selection's active drawable becomes the session's active mesh. + // The model having nothing editable refuses Edit rather than opening an inert session + // (Blender needs an active object too): stay in Object, record nothing. + val editSeed = editSeedOf(model, mutableSelection.value, elementMemory.lastActiveDrawableId) ?: return + val seedDrawableIds = editSeed.drawableIds + val seedActiveId = editSeed.activeId + if (!editSeed.activeSelected) { + // Seeded from the remembered drawable or the topmost fallback: remember it so the next + // entry is stable. The object selection is left untouched - a soft seed, not a + // re-selection, matching the remembered-drawable behavior. + elementMemory.lastActiveDrawableId = seedActiveId + } + // Clear the transient tool state on entry too: the select tool is shared with Object mode, so + // an object tool armed before the switch must not leak in and drive the Edit overlay. + latches.clearTransient(clearViewportGesture = true) + meshUvSeedByDrawable.clear() + meshSpaceSeedByDrawable.clear() + for (drawableId in seedDrawableIds) { + val mesh = model.drawables.firstOrNull { candidate -> candidate.id == drawableId }?.mesh + if (mesh != null && mesh.vertexCount > 0) { + meshUvSeedByDrawable[drawableId] = mesh + } + } + // Restore each seeded drawable's remembered elements where they still fit its mesh; + // the rest start empty (a different mesh set no longer forgets the others' memory). + elementMemory.restore(MeshSelection.editing(seedDrawableIds, seedActiveId), model) + } + EditorMode.Object -> { + // Stash each mesh's element selection so re-entering Edit mode restores it per mesh. + elementMemory.stash(mutableMeshSelection.value) + latches.clearTransient(clearViewportGesture = true) + meshUvSeedByDrawable.clear() + meshSpaceSeedByDrawable.clear() + MeshSelection() + } + } + pushStep( + snapshot(meshSelection = newMeshSelection, mode = mode), + EditorStateChange.ModeChanged(mode), + ) + mutableMode.value = mode + mutableMeshSelection.value = newMeshSelection + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.ModeChanged(mode)) + } + + /** + * Records an Edit-mode element-selection gesture as its own undo step (the same Blender-faithful + * granularity as object selection), so a misclick that loses a selection is recoverable. A no-op + * (selecting the already-current selection) records nothing. Not a document edit — leaves dirty + * untouched. + * + * @param MeshSelection meshSelection The new element selection. + */ + fun setMeshSelection(meshSelection: MeshSelection) { + if (meshSelection == mutableMeshSelection.value) { + return + } + pushStep( + snapshot(meshSelection = meshSelection), + EditorStateChange.MeshSelectionChanged, + ) + mutableMeshSelection.value = meshSelection + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.MeshSelectionChanged) + } + + /** + * Records a keyform-sheet key-selection gesture as its own undo step, so a misclick that loses a + * carefully built multi-key selection is recoverable. A no-op records nothing. Not a document edit - + * leaves dirty untouched. + * + * Shared session state rather than a sheet's view state, for the same reason the parameter target is: a + * thing that undo restores has to live where undo can reach it, and two open sheets agreeing on one + * selection is the same trade [setParameterSelection] already made. + * + * Also the CONFIRM half of [stageKeySelection]: calling this with the staged selection after the + * gesture's edit records the selection exactly when the edit did not. + * + * @param Set keySelection The new key selection. + */ + fun setKeySelection(keySelection: Set) { + // Compared against what HISTORY holds, not against the live flow, because a stage has already moved + // the flow: comparing there makes a confirm look like a no-op in precisely the case it exists for - + // the one where the edit it followed recorded nothing and the staged selection reached no snapshot. + if (keySelection == history.current.keySelection) { + // Published rather than merely dropped: this step records nothing new, which is not the same as + // the live flow already holding it (a restore or an abandoned stage can leave it elsewhere). + mutableKeySelection.value = keySelection + return + } + pushStep(snapshot(keySelection = keySelection), EditorStateChange.KeySelectionChanged) + mutableKeySelection.value = keySelection + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.KeySelectionChanged) + } + + /** + * Publishes [keySelection] WITHOUT recording a step of its own, for a gesture whose own step is about to + * follow. + * + * A keyform-sheet gesture selects and edits at once - a drag re-points the selection at the ordinals its + * keys landed on, an empty-track press drops the selection and scrubs - and they are one gesture, so + * they are one entry. [snapshot] defaults every field it is not given to live state, so staging the + * selection BEFORE the edit folds it into that edit's own step. Recording both would make one drag take + * two presses of Ctrl+Z to reverse. + * + * STAGE, EDIT, CONFIRM - every caller runs all three. The edit may decline to record anything (a drag + * clamped to zero, a scrub that ended where it began, a move onto a key's own value), and a stage that + * reached no snapshot is a selection change undo cannot see. So the gesture ends by calling + * [setKeySelection] with the same selection: that compares against history rather than against the live + * flow, so it is a no-op when the edit's push already carried the selection and records a step of its + * own when it did not. Staging without confirming is a bug, not a shortcut. + * + * @param Set keySelection The new key selection. + */ + fun stageKeySelection(keySelection: Set) { + mutableKeySelection.value = keySelection + } + + /** + * Selects [keySelection] and moves the pose to [pose] as ONE undo step, named for the selection. + * + * Clicking a mark in the keyform sheet does both - it selects the key and lands the pose exactly on it - + * and they are one gesture, so they are one entry. Naming it for the selection rather than for the + * scrub is what makes the history read as what the user did: they clicked a keyframe, and the pose + * moving is the consequence. + * + * Recorded even when the pose does not move (clicking a key the pose already sits on), which is why this + * exists rather than staging the selection and letting a pose commit carry it: the pose commit + * short-circuits on an unchanged pose, and the selection would then vanish from history entirely. + * + * @param Set keySelection The keys the click selected. + * @param Pose pose The pose the click landed on. + */ + fun selectKeysAtPose(keySelection: Set, pose: Pose) { + // Against history rather than the live flow, for the reason [setKeySelection] spells out: a staged + // selection has already moved the flow, and a click that lands on the selection a stage left there + // must still record it. + if (keySelection == history.current.keySelection && pose == history.current.pose) { + mutableKeySelection.value = keySelection + mutablePose.value = pose + return + } + // A pose move invalidates every pending edit, exactly as it does through the ordinary commit path. + if (pose != mutablePose.value) { + clearPendingChannelEdits() + } + pushStep(snapshot(pose = pose, keySelection = keySelection), EditorStateChange.KeySelectionChanged) + mutableKeySelection.value = keySelection + mutablePose.value = pose + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.KeySelectionChanged) + } + + /** + * Commits a mesh-vertex edit (a finished modal G / S / R gesture) as ONE undo step: each session + * drawable's base art-mesh positions become its entry in [newPositionsByDrawable]. An Edit session + * spans several meshes, so the per-drawable copy-on-write [withMeshPositions] edits fold into a + * single model (one history step, like [commitObjectPositions]). Mid-gesture preview frames reach + * the renderer directly (transient), so a whole drag is a single step. A model edit (rest geometry + * is document content), so it marks the document dirty; a no-op (every array unchanged / mismatched) + * records nothing. + * + * @param MeshChange change The edit descriptor (a [MeshChange.TransformVertices]). + * @param Map newPositionsByDrawable Each edited drawable's committed rest positions. + */ + fun commitMeshPositions(change: MeshChange, newPositionsByDrawable: Map) { + val newModel = + newPositionsByDrawable.entries.fold(mutableModel.value) { model, (drawableId, newPositions) -> + model.withMeshPositions(drawableId, newPositions) + } + commit(change, newModel, mutablePose.value) + } + + /** + * Commits an Object-mode transform of several drawables (a finished modal G / S / R gesture) as ONE undo + * step: each drawable's base art-mesh positions become its entry in [newPositionsByDrawable]. Folds the + * per-drawable copy-on-write [withMeshPositions] edits into a single model, so N moved drawables are one + * history step (not N). Mid-gesture preview frames reach the renderer directly (transient), so a whole drag + * is a single step. A model edit (rest geometry is document content), so it marks the document dirty; a + * no-op (every array unchanged / mismatched, so the fold returns the same instance) records nothing. + * + * @param MeshChange change The edit descriptor (a [MeshChange.TransformDrawables]). + * @param Map newPositionsByDrawable Each moved drawable's committed rest positions. + */ + fun commitObjectPositions(change: MeshChange, newPositionsByDrawable: Map) { + val newModel = + newPositionsByDrawable.entries.fold(mutableModel.value) { model, (drawableId, newPositions) -> + model.withMeshPositions(drawableId, newPositions) + } + commit(change, newModel, mutablePose.value) + } + + /** + * Commits a UV edit (a finished modal G / S / R gesture in the UV editor, or a Mirror command) as + * ONE undo step: each edited drawable's texture coordinates become its entry in [newUvsByDrawable]. + * The texture-mapping twin of [commitMeshPositions] - the per-drawable copy-on-write [withMeshUvs] + * edits fold into a single model, so N edited meshes are one history step. Mid-gesture preview + * frames reach the renderer directly (transient), so a whole drag is a single step. A model edit + * (the sampled texels are document content), so it marks the document dirty; a no-op (every + * array unchanged / mismatched) records nothing. + * + * @param MeshChange change The edit descriptor (a [MeshChange.TransformUvs] or [MeshChange.MirrorUvs]). + * @param Map newUvsByDrawable Each edited drawable's committed atlas UVs. + */ + fun commitMeshUvs(change: MeshChange, newUvsByDrawable: Map) { + val newModel = + newUvsByDrawable.entries.fold(mutableModel.value) { model, (drawableId, newUvs) -> + model.withMeshUvs(drawableId, newUvs) + } + commit(change, newModel, mutablePose.value) + } + + /** + * Mirrors the selected vertices' texture coordinates about the transform pivot as ONE undo step - + * the UV editor's Mirror U / V commands, serving the duplicated-and-flipped texture regions + * workflow (both eyes sampling one eye texture). The pivot follows [pivotMode], resolved in UV + * space: Median Point mirrors about the covered vertices' combined median across every edited mesh, + * Individual Origins mirrors each connectivity island about its own median, Active Element anchors + * on the active element's median, and Cursor anchors on the UV cursor (each falling back to the + * combined median when unresolvable - a mirror should never silently do nothing because a pivot was + * never placed). Mirroring is axis-aligned, so operating directly in normalized UV space matches + * the on-screen result regardless of the shown surface's size. A no-op outside Edit mode or with an + * empty selection; a notice explains when no covered mesh carries an editable UV array. + * + * [frame] names the space the user is mirroring in, which for this operation is the whole question: + * an axis in the atlas page's frame is a different axis in a rotated or mirrored source layer's. + * With no frame the stored coordinates ARE the authoring space (the page view), and the whole + * conversion drops out. Untouched vertices keep their exact stored values either way, so a mirror + * never marks a vertex changed that it did not move. + * + * @param Boolean mirrorU True to mirror horizontally (u about the pivot), false vertically (v). + * @param UvFrame? frame The authoring frame, or null when the stored coordinates are the frame. + */ + fun mirrorSelectedUvs(mirrorU: Boolean, frame: UvFrame? = null) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val selection = mutableMeshSelection.value + if (selection.isEmpty) { + // Speaks up, unlike the mode guard above: reaching Mirror with an empty selection is an ordinary + // mistake a rigger makes, where a request arriving outside Edit mode is stale bus traffic the + // palette already gates. + emitNotice("notice.uv.noSelection", NoticePlacement.NearCursor) + return + } + val model = mutableModel.value + // Resolve each session mesh's covered vertices, skipping meshes without an editable UV array + // (imports may leave uvs empty; a malformed length is excluded by the same guard as withMeshUvs). + val coveredByDrawable = LinkedHashMap>() + val meshByDrawable = LinkedHashMap() + for (drawableId in selection.drawableIds) { + val mesh = model.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.mesh ?: continue + if (mesh.uvs.isEmpty() || mesh.uvs.size != mesh.positions.size) { + continue + } + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(drawableId), mesh.indices) + if (covered.isEmpty()) { + continue + } + coveredByDrawable[drawableId] = covered + meshByDrawable[drawableId] = mesh + } + if (coveredByDrawable.isEmpty()) { + emitNotice("notice.uv.noUvs", NoticePlacement.NearCursor) + return + } + // The whole operation runs in the authoring frame: pivots, island medians, and the reflection + // itself. With no frame these arrays are the stored ones and the conversions are absent. + val frameUvsByDrawable = + meshByDrawable.mapValues { (_, mesh) -> frame?.toFrame(mesh.uvs) ?: mesh.uvs } + val sharedPivot = + if (latches.pivotMode.value == TransformPivotMode.IndividualOrigins) { + null + } else { + resolveUvMirrorPivot(coveredByDrawable, meshByDrawable, frameUvsByDrawable, selection, frame) + } + val newUvsByDrawable = LinkedHashMap() + for ((drawableId, covered) in coveredByDrawable) { + val mesh = meshByDrawable.getValue(drawableId) + val frameUvs = frameUvsByDrawable.getValue(drawableId) + val groups = + if (sharedPivot == null) { + TransformPivots.islandGroups(frameUvs, covered, mesh.indices) + } else { + TransformPivots.sharedGroup(covered, sharedPivot.first, sharedPivot.second) + } + var mirroredUvs = frameUvs + for (group in groups) { + mirroredUvs = + MeshTransforms.scaleVerticesAxis( + mirroredUvs, + group.vertexIndices, + if (mirrorU) -1f else 1f, + if (mirrorU) 1f else -1f, + group.pivotX, + group.pivotY, + ) + } + // Back to the stored form, then overwrite ONLY the covered vertices onto the current stored + // array: a frame round trip is exact in the reals but not in floats, so rebuilding from the + // stored values is what keeps an untouched vertex bit-identical (and out of the export's + // changed-uv set). Without a frame the mirrored array is already stored-form and this is a + // straight copy of the moved components. + val storedMirrored = frame?.fromFrame(mirroredUvs) ?: mirroredUvs + val newUvs = mesh.uvs.copyOf() + for (vertexIndex in covered) { + newUvs[vertexIndex * 2] = storedMirrored[vertexIndex * 2] + newUvs[vertexIndex * 2 + 1] = storedMirrored[vertexIndex * 2 + 1] + } + newUvsByDrawable[drawableId] = newUvs + } + commitMeshUvs(MeshChange.MirrorUvs(newUvsByDrawable.keys.toList(), mirrorU), newUvsByDrawable) + } + + /** + * Reverse-swaps one UV axis pairwise by vertex index (0↔last, 1↔last-1, …) — the UV counterpart of + * viewport Reverse Positions H/V. Unlike [mirrorSelectedUvs], this exchanges components between + * verts rather than reflecting about a pivot. + * + * @param Boolean horizontal True to swap u only; false to swap v only. + * @param UvFrame? frame The authoring frame, or null when stored coordinates are the frame. + */ + fun reverseSwapSelectedUvs(horizontal: Boolean, frame: UvFrame? = null) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val selection = mutableMeshSelection.value + if (selection.isEmpty) { + emitNotice("notice.uv.noSelection", NoticePlacement.NearCursor) + return + } + val model = mutableModel.value + val newUvsByDrawable = LinkedHashMap() + for (drawableId in selection.drawableIds) { + val mesh = model.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.mesh ?: continue + if (mesh.uvs.isEmpty() || mesh.uvs.size != mesh.positions.size) { + continue + } + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(drawableId), mesh.indices) + if (covered.size < 2) { + continue + } + val ordered = covered.sorted() + val frameUvs = frame?.toFrame(mesh.uvs) ?: mesh.uvs + val swappedFrame = MeshTransforms.reverseSwapPositions(frameUvs, ordered, horizontal) + val storedSwapped = frame?.fromFrame(swappedFrame) ?: swappedFrame + val newUvs = mesh.uvs.copyOf() + for (vertexIndex in covered) { + newUvs[vertexIndex * 2] = storedSwapped[vertexIndex * 2] + newUvs[vertexIndex * 2 + 1] = storedSwapped[vertexIndex * 2 + 1] + } + newUvsByDrawable[drawableId] = newUvs + } + if (newUvsByDrawable.isEmpty()) { + emitNotice("notice.uv.noUvs", NoticePlacement.NearCursor) + return + } + commitMeshUvs(MeshChange.MirrorUvs(newUvsByDrawable.keys.toList(), mirrorU = horizontal), newUvsByDrawable) + } + + /** + * Resolves the shared UV mirror pivot for the single-anchor pivot modes: Cursor anchors on the UV + * cursor and Active Element on the active element's covered median, each falling back to the + * combined covered median across every edited mesh - which is also the Median Point result. + * + * Resolved in the AUTHORING frame throughout, so every anchor means the same thing the reflection + * does - including the UV cursor, which is stored in atlas coordinates and converts in like the + * meshes do. + * + * @param Map> coveredByDrawable Each edited mesh's covered vertex indices. + * @param Map meshByDrawable Each edited mesh, keyed like the covered map. + * @param Map frameUvsByDrawable Each edited mesh's uvs in the authoring frame. + * @param MeshSelection selection The live selection (for the active element). + * @param UvFrame? frame The authoring frame, or null when the stored coordinates are the frame. + * @return Pair The pivot's (u, v), in the authoring frame. + */ + private fun resolveUvMirrorPivot( + coveredByDrawable: Map>, + meshByDrawable: Map, + frameUvsByDrawable: Map, + selection: MeshSelection, + frame: UvFrame?, + ): Pair { + when (latches.pivotMode.value) { + TransformPivotMode.Cursor -> { + val cursor = latches.uvCursor.value + if (cursor != null) { + return frame?.pointToFrame(cursor.u, cursor.v) ?: (cursor.u to cursor.v) + } + } + + TransformPivotMode.ActiveElement -> { + val active = selection.activeElement + val activeMesh = active?.let { activeElement -> meshByDrawable[activeElement.drawableId] } + val activeFrameUvs = active?.let { activeElement -> frameUvsByDrawable[activeElement.drawableId] } + if (active != null && activeMesh != null && activeFrameUvs != null) { + val activeCovered = MeshTopology.coveredVertexIndices(setOf(active.element), activeMesh.indices) + if (activeCovered.isNotEmpty()) { + return MeshTransforms.medianPivot(activeFrameUvs, activeCovered) + } + } + } + + TransformPivotMode.MedianPoint, TransformPivotMode.IndividualOrigins -> {} + } + var sumU = 0f + var sumV = 0f + var coveredCount = 0 + for ((drawableId, covered) in coveredByDrawable) { + val uvs = frameUvsByDrawable.getValue(drawableId) + for (vertexIndex in covered) { + sumU += uvs[vertexIndex * 2] + sumV += uvs[vertexIndex * 2 + 1] + coveredCount += 1 + } + } + if (coveredCount == 0) { + // Unreachable today (callers pre-filter empty covered sets); the authoring frame's center is + // a safe anchor. + return 0.5f to 0.5f + } + return (sumU / coveredCount) to (sumV / coveredCount) + } + + /** + * Switches the Edit-mode select mode (vertex / edge / face) as its own undo step, converting the + * stored selection into the new domain with Blender's flush-down / derive-up rules (see + * [MeshSelectionOps.changeSelectMode]). The conversion is lossy by design, so the snapshot is what + * makes it recoverable. A no-op outside Edit mode — so the bound 1 / 2 / 3 commands need no context + * guard of their own and the keymap stays mode-agnostic — and a no-op when already in [selectMode]. + * Not a document edit — leaves dirty untouched. + * + * @param MeshSelectMode selectMode The new select mode. + */ + fun setMeshSelectMode(selectMode: MeshSelectMode) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val current = mutableMeshSelection.value + val model = mutableModel.value + val converted = + MeshSelectionOps.changeSelectMode(current, selectMode) { drawableId -> + model.drawables.firstOrNull { it.id == drawableId }?.mesh?.indices + } + if (converted == current) { + return + } + pushStep( + snapshot(meshSelection = converted), + EditorStateChange.MeshSelectModeChanged(selectMode), + ) + mutableMeshSelection.value = converted + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.MeshSelectModeChanged(selectMode)) + } + + /** + * Selects every element of every session mesh in the current select mode (Blender's Select All) as + * one undo step. A no-op outside Edit mode, or when the Edit session holds no meshes - so the bound + * command stays mode-agnostic (it dispatches to [selectAllObjects] in Object mode). Not a document edit. + */ + fun selectAllMeshElements() { + if (mutableMode.value != EditorMode.Edit) { + return + } + val current = mutableMeshSelection.value + val model = mutableModel.value + setMeshSelection(MeshSelectionOps.selectAll(current) { drawableId -> model.drawables.firstOrNull { it.id == drawableId }?.mesh }) + } + + /** + * Inverts every session mesh's element selection within the current select mode (Blender's Ctrl+I) as + * one undo step. A no-op outside Edit mode, or when the Edit session holds no meshes. Not a document + * edit. + */ + fun invertMeshSelection() { + if (mutableMode.value != EditorMode.Edit) { + return + } + val current = mutableMeshSelection.value + val model = mutableModel.value + setMeshSelection(MeshSelectionOps.invert(current) { drawableId -> model.drawables.firstOrNull { it.id == drawableId }?.mesh }) + } + + /** + * Selects every selectable entity in the model (Object mode's Select All) as one undo step. A no-op + * outside Object mode - so the bound command stays mode-agnostic (it dispatches to [selectAllMeshElements] + * in Edit mode). Not a document edit. + */ + fun selectAllObjects() { + if (mutableMode.value != EditorMode.Object) { + return + } + setSelection(SelectionOps.selectAll(mutableSelection.value, mutableModel.value)) + } + + /** + * Inverts the object selection over every selectable entity (Object mode's Ctrl+I) as one undo step. A + * no-op outside Object mode. Not a document edit. + */ + fun invertObjectSelection() { + if (mutableMode.value != EditorMode.Object) { + return + } + setSelection(SelectionOps.invert(mutableSelection.value, mutableModel.value)) + } + + /** + * True while the active mesh operator was latched with proportional editing suppressed - the + * duplicate / rip auto-grabs, which place fresh copies and must never drag bystander vertices. + * Transient latch state (never snapshotted), reset whenever the operator latches or clears. + */ + val activeMeshOperatorSuppressesProportional: Boolean + get() = latches.activeMeshOperatorSuppressesProportional + + /** + * Latches a modal mesh operator so the gizmo overlay begins the gesture. A no-op unless Edit mode is + * active with a drawable and a non-empty selection — so the bound G / S / R commands need no context + * guard of their own and the keymap stays mode-agnostic. For an edge or face selection the gesture + * moves the union of vertices the selected elements cover (resolved in the overlay). + * + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param String areaId The initiating viewport's area id (only its overlay drives the gesture). + * @param Boolean suppressProportional True to ignore proportional editing for this gesture (the + * duplicate / rip auto-grabs; treated like Vertex Slide at every proportional gate). + */ + fun beginMeshOperator(kind: MeshOperatorKind, areaId: String, suppressProportional: Boolean = false) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val selection = mutableMeshSelection.value + if (selection.drawableIds.isEmpty() || selection.isEmpty) { + return + } + latches.latchMeshOperator(kind, areaId, suppressProportional) + } + + /** Clears the active modal mesh operator (the overlay calls this on confirm or cancel). */ + fun clearMeshOperator() { + latches.clearMeshOperator() + } + + /** + * Begins an Object-mode modal transform (Grab / Scale / Rotate) over the selected drawables' whole + * geometry - the Object-mode counterpart to [beginMeshOperator]. A no-op unless Object mode is active + * with an eligible selection: at least one mesh-carrying drawable must be reachable from the selection + * (see [eligibleTransformDrawables] - a selected part expands to its subtree meshes; deformers and + * mesh-less drawables are silently ignored, so a Select All that swept them in never blocks the + * gesture). The gesture is BLOCKED with a near-cursor notice when the pose is not at parameter defaults: + * the object overlay captures at the live pose, and writing a deformed capture back through the warp + * inverse corrupts the rest meshes - the Blender-style guard tells the user to reset the parameters + * first. Clears any other latched tool / operator (mutual exclusion) before latching. + * + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param String areaId The initiating viewport's area id (only its overlay drives the gesture). + */ + fun beginObjectOperator(kind: MeshOperatorKind, areaId: String) { + if (mutableMode.value != EditorMode.Object) { + return + } + val drawables = eligibleTransformDrawables(mutableSelection.value, mutableModel.value) + if (drawables != null) { + if (!isPoseNeutral(mutableModel.value, mutablePose.value)) { + // Transforming rest geometry while the displayed pose is deformed would write garbage through + // the deformer inverse; refuse and tell the user how to proceed (see the docblock). + emitNotice("notice.transform.deformed", NoticePlacement.NearCursor) + return + } + latches.latchObjectOperator(kind, areaId) + return + } + // A selected warp with a lattice: G / S / R edits control points into the live Geometry key - allowed + // at any pose, unlike drawable rest-mesh transforms. + if (selectedWarpDeformerId(mutableSelection.value, mutableModel.value) != null) { + latches.latchObjectOperator(kind, areaId) + return + } + emitNotice("notice.transform.onlyDrawables", NoticePlacement.NearCursor) + } + + /** Clears the active modal object operator (the overlay calls this on confirm or cancel). */ + fun clearObjectOperator() { + latches.clearObjectOperator() + } + + /** + * Latches a modal UV operator so the UV editor's overlay begins the gesture - the UV-editor + * counterpart to [beginMeshOperator]. What the gesture moves follows the mode: in Edit mode the + * selected texture coordinates, in Object mode the selected drawables' atlas PLACEMENTS (the art + * itself on its page, with the coordinates over it re-derived on commit). Either way the bound + * G / S / R commands stay mode-agnostic. Vertex Slide is refused in both (it is rest-geometry math; + * Blender's UV editor has no slide either). + * + * Edit mode is a silent no-op on an empty selection and BLOCKED with a near-cursor notice when no + * covered mesh carries an editable UV array (imports may leave uvs empty), since latching would show + * a modal HUD that can never commit anything. Object mode is blocked with a notice when the stored + * coordinates address the art rather than the pages (a placement is meaningless there), when + * nothing selected is bound to packed art, and when every placed tile under the selection is + * pinned (a pin holds against a hand move too). Which page the overlay is showing - and whether it is + * showing a page at all rather than a source layer - is per-area state the session cannot see, so + * the overlay that owns the latch drops it with its own notice when its surface cannot serve the + * gesture. Clears any other latched tool / operator (mutual exclusion) before latching. + * + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param String areaId The initiating UV editor's area id (only its overlay drives the gesture). + */ + fun beginUvOperator(kind: MeshOperatorKind, areaId: String) { + if (kind == MeshOperatorKind.VertexSlide) { + return + } + val model = mutableModel.value + when (mutableMode.value) { + EditorMode.Object -> { + if (!model.atlas.storedUvsAddressPages) { + emitNotice("notice.uv.placement.layerAddressed", NoticePlacement.NearCursor) + return + } + if (model.placementDragTileIds(mutableSelection.value).isEmpty()) { + // Placed art under the selection that still cannot move is pinned art. + val messageKey = + if (model.placementSelectedTileIds(mutableSelection.value).isEmpty()) { + "notice.uv.placement.noPlacedArt" + } else { + "notice.uv.placement.pinned" + } + emitNotice(messageKey, NoticePlacement.NearCursor) + return + } + } + + EditorMode.Edit -> { + val selection = mutableMeshSelection.value + if (selection.drawableIds.isEmpty() || selection.isEmpty) { + return + } + val anyEditableUvs = + selection.drawableIds.any { drawableId -> + val mesh = model.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.mesh + mesh != null && + mesh.uvs.isNotEmpty() && + mesh.uvs.size == mesh.positions.size && + MeshTopology.coveredVertexIndices(selection.elementsOf(drawableId), mesh.indices).isNotEmpty() + } + if (!anyEditableUvs) { + emitNotice("notice.uv.noUvs", NoticePlacement.NearCursor) + return + } + } + } + latches.latchUvOperator(kind, areaId) + } + + /** Clears the active modal UV operator (the overlay calls this on confirm or cancel). */ + fun clearUvOperator() { + latches.clearUvOperator() + } + + /** + * Arms the Box-select tool (Blender's B): the gizmo overlay shows full-viewport crosshair guides and the + * next drag boxes. Mode-agnostic - in Edit mode it needs an active drawable (the box selects that mesh's + * elements); in Object mode it arms unconditionally (the box selects whole drawables). A no-op in Edit + * mode without a drawable. Clears any other latched tool / operator (mutual exclusion). + * + * @param String areaId The arming viewport's area id (only its overlay drives the drag). + */ + fun beginBoxSelect(areaId: String) { + if (mutableMode.value == EditorMode.Edit && mutableMeshSelection.value.drawableIds.isEmpty()) { + return + } + latches.armBoxSelect(areaId) + } + + /** + * Arms the Circle-select tool (Blender's C) at the remembered radius. Mode-agnostic like [beginBoxSelect]: + * needs an active drawable in Edit mode, arms unconditionally in Object mode. Clears any other latched + * tool / operator (mutual exclusion). + * + * @param String areaId The arming viewport's area id (only its overlay drives the brush). + */ + fun beginCircleSelect(areaId: String) { + if (mutableMode.value == EditorMode.Edit && mutableMeshSelection.value.drawableIds.isEmpty()) { + return + } + latches.armCircleSelect(areaId) + } + + /** + * Arms the Cubism-style Add Vertex draft on the active session mesh: clicks stage floating verts + * (document untouched) until [acceptAddVertexDraft]. Edit mode with a session mesh only. + * + * @param String areaId The arming viewport's area id (only its overlay drives the clicks). + */ + fun beginAddVertex(areaId: String) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val drawableId = mutableMeshSelection.value.activeDrawableId ?: return + if (drawableId !in mutableMeshSelection.value.drawableIds) { + return + } + latches.armAddVertex(areaId, drawableId) + } + + /** + * One LMB of the Add Vertex draft: places a floating vert (free or edge-snapped), or retargets the tip + * onto an existing mesh vert or a staged draft vert (to close a loop), auto-edging from the previous tip. + * Document untouched. + * + * @param Float worldX Click x in the overlay's world space. + * @param Float worldY Click y in the overlay's world space. + * @param Int? existingVertexIndex A hit mesh vertex on the draft drawable, or null. + * @param Int? draftVertIndex A hit staged draft vert index, or null. + * @param MeshElement.Edge? snapEdge A hit mesh edge on the draft drawable, or null. + * @param Float snapT Parameter along [snapEdge] when snapping. + */ + fun addVertexDraftClick( + worldX: Float, + worldY: Float, + existingVertexIndex: Int? = null, + draftVertIndex: Int? = null, + snapEdge: MeshElement.Edge? = null, + snapT: Float = 0.5f, + ) { + val tool = latches.activeSelectTool.value as? ActiveSelectTool.AddVertex ?: return + val tip = tool.tip + if (draftVertIndex != null && draftVertIndex in tool.verts.indices) { + val nextTip = DraftEndpoint.Draft(draftVertIndex) + val edges = + if (tip != null) { + val edge = DraftEdge.of(tip, nextTip) + if (edge != null && edge !in tool.edges) tool.edges + edge else tool.edges + } else { + tool.edges + } + latches.setAddVertexDraft(tool.copy(edges = edges, tip = nextTip)) + return + } + if (existingVertexIndex != null) { + val nextTip = DraftEndpoint.Existing(existingVertexIndex) + val edges = + if (tip != null) { + val edge = DraftEdge.of(tip, nextTip) + if (edge != null && edge !in tool.edges) tool.edges + edge else tool.edges + } else { + tool.edges + } + latches.setAddVertexDraft(tool.copy(edges = edges, tip = nextTip)) + return + } + val vert = + if (snapEdge != null) { + DraftVert(worldX, worldY, snapEdge = snapEdge, snapT = snapT) + } else { + DraftVert(worldX, worldY) + } + val draftIndex = tool.verts.size + val nextTip = DraftEndpoint.Draft(draftIndex) + val edges = + if (tip != null) { + val edge = DraftEdge.of(tip, nextTip) + if (edge != null) tool.edges + edge else tool.edges + } else { + tool.edges + } + latches.setAddVertexDraft(tool.copy(verts = tool.verts + vert, edges = edges, tip = nextTip)) + } + + /** + * Deletes one staged floating vert and its incident draft edges; retargets the tip. Document untouched. + * + * @param Int draftIndex Index into the draft vert list. + */ + fun deleteAddVertexDraftVert(draftIndex: Int) { + val tool = latches.activeSelectTool.value as? ActiveSelectTool.AddVertex ?: return + if (draftIndex !in tool.verts.indices) { + return + } + val newVerts = tool.verts.toMutableList().also { list -> list.removeAt(draftIndex) } + + fun remapEndpoint(endpoint: DraftEndpoint): DraftEndpoint? = + when (endpoint) { + is DraftEndpoint.Existing -> endpoint + is DraftEndpoint.Draft -> + when { + endpoint.index == draftIndex -> null + endpoint.index > draftIndex -> DraftEndpoint.Draft(endpoint.index - 1) + else -> endpoint + } + } + + val newEdges = ArrayList() + for (edge in tool.edges) { + val a = remapEndpoint(edge.a) ?: continue + val b = remapEndpoint(edge.b) ?: continue + DraftEdge.of(a, b)?.let { remapped -> + if (remapped !in newEdges) { + newEdges.add(remapped) + } + } + } + val newTip = + when (val tip = tool.tip) { + null -> null + is DraftEndpoint.Existing -> tip + is DraftEndpoint.Draft -> + when { + tip.index == draftIndex -> newVerts.indices.lastOrNull()?.let { index -> DraftEndpoint.Draft(index) } + tip.index > draftIndex -> DraftEndpoint.Draft(tip.index - 1) + else -> tip + } + } + latches.setAddVertexDraft(tool.copy(verts = newVerts, edges = newEdges, tip = newTip)) + } + + /** + * Deletes one existing mesh vertex from the Add Vertex tool's drawable (Cubism delete-vert): drops the + * vert and every incident triangle as one undo step, remaps the live draft's Existing tips / snaps, + * and keeps the tool armed. A no-op outside Add Vertex or when the index is missing. + * + * @param Int vertexIndex The mesh vertex to remove. + */ + fun deleteAddVertexExistingVert(vertexIndex: Int) { + val tool = latches.activeSelectTool.value as? ActiveSelectTool.AddVertex ?: return + if (mutableMode.value != EditorMode.Edit) { + return + } + val mesh = mutableModel.value.drawables.firstOrNull { it.id == tool.drawableId }?.mesh ?: return + if (vertexIndex !in 0 until mesh.vertexCount) { + return + } + val result = MeshTopologyOps.deleteVertices(mesh, listOf(vertexIndex)) ?: return + if (!commitMeshTopology("change.mesh.deleteVertex", tool.drawableId, result)) { + return + } + + fun remapExisting(index: Int): Int? = + when { + index == vertexIndex -> null + index > vertexIndex -> index - 1 + else -> index + } + + fun remapEndpoint(endpoint: DraftEndpoint): DraftEndpoint? = + when (endpoint) { + is DraftEndpoint.Draft -> endpoint + is DraftEndpoint.Existing -> remapExisting(endpoint.vertexIndex)?.let { DraftEndpoint.Existing(it) } + } + + val liveEdges = MeshTopology.uniqueEdges(result.edit.newMesh.indices).toSet() + val newVerts = + tool.verts.map { vert -> + val snap = vert.snapEdge + if (snap == null) { + vert + } else if (snap.endpointLow == vertexIndex || snap.endpointHigh == vertexIndex) { + vert.copy(snapEdge = null) + } else { + val low = remapExisting(snap.endpointLow) + val high = remapExisting(snap.endpointHigh) + if (low == null || high == null) { + vert.copy(snapEdge = null) + } else { + val remapped = MeshElement.Edge.of(low, high) + // Face-emptying deletes can leave the endpoints alive while the edge itself is gone. + if (remapped in liveEdges) vert.copy(snapEdge = remapped) else vert.copy(snapEdge = null) + } + } + } + val newEdges = ArrayList() + for (edge in tool.edges) { + val a = remapEndpoint(edge.a) ?: continue + val b = remapEndpoint(edge.b) ?: continue + DraftEdge.of(a, b)?.let { remapped -> + if (remapped !in newEdges) { + newEdges.add(remapped) + } + } + } + val newTip = tool.tip?.let { tip -> remapEndpoint(tip) } + latches.setAddVertexDraft(tool.copy(verts = newVerts, edges = newEdges, tip = newTip)) + } + + /** + * Commits the armed Add Vertex draft into the mesh as one undo step and clears the tool. An empty + * draft just clears. Enter routes here; Esc clears without committing. A refused Accept keeps the + * draft armed and logs why (Logs panel / stdout). + */ + fun acceptAddVertexDraft() { + val tool = latches.activeSelectTool.value as? ActiveSelectTool.AddVertex ?: return + UmamoLog.info( + "addVertex accept: drawable=${tool.drawableId.raw} draftVerts=${tool.verts.size} draftEdges=${tool.edges.size}", + ) + val mesh = mutableModel.value.drawables.firstOrNull { it.id == tool.drawableId }?.mesh + if (mesh == null) { + UmamoLog.warn("addVertex accept: drawable has no mesh — clearing tool") + latches.clearSelectTool() + return + } + UmamoLog.info("addVertex accept: base verts=${mesh.vertexCount} tris=${mesh.triangleCount}") + if (tool.verts.isEmpty() && tool.edges.isEmpty()) { + latches.clearSelectTool() + return + } + val uvSeed = meshUvSeedByDrawable[tool.drawableId] + val wiped = mesh.vertexCount == 0 + val worldToBase = addVertexWorldToBase + val draftVerts = + if (worldToBase == null) { + tool.verts + } else { + tool.verts.map { vert -> + val (baseX, baseY) = worldToBase(tool.drawableId, vert.x, vert.y) + vert.copy(x = baseX, y = baseY) + } + } + UmamoLog.info( + "addVertex accept: wiped=$wiped uvSeedVerts=${uvSeed?.vertexCount ?: 0} worldToBase=${worldToBase != null}", + ) + var result = + MeshTopologyOps.applyAddVertexDraft(mesh, draftVerts, tool.edges, uvSeedMesh = uvSeed) + if (result == null) { + UmamoLog.warn( + "addVertex accept: apply returned null (need a closed triangle of 3 edges; open polylines do not invent faces)", + ) + emitNotice("notice.addVertex.refused", NoticePlacement.NearCursor) + return + } + // Wipe-and-rebuild: force every new vert's UV through the Edit-enter field so the texture + // cannot depend on append order / leftover sampling paths. + if (wiped && uvSeed != null && uvSeed.vertexCount > 0) { + val projected = MeshUvField(uvSeed).projectAll(result.edit.newMesh) + result = + TopologyOpResult( + MeshTopologyEdit(projected, result.edit.vertexSources), + result.newElements, + ) + UmamoLog.info("addVertex accept: projected UVs from Edit-enter seed (${uvSeed.vertexCount} verts)") + } + val newMesh = result.edit.newMesh + val sampleUv = + if (newMesh.uvs.size >= 2) { + "(${newMesh.uvs[0]}, ${newMesh.uvs[1]})" + } else { + "n/a" + } + val samplePos = + if (newMesh.positions.size >= 2) { + "(${newMesh.positions[0]}, ${newMesh.positions[1]})" + } else { + "n/a" + } + UmamoLog.info( + "addVertex accept: result verts=${newMesh.vertexCount} tris=${newMesh.triangleCount} " + + "sources=${result.edit.vertexSources.size} selected=${result.newElements.size} " + + "firstPos=$samplePos firstUv=$sampleUv", + ) + if (!commitMeshTopology("change.mesh.addVertex", tool.drawableId, result)) { + UmamoLog.warn("addVertex accept: commit no-op (topology edit refused — check source/vert count)") + emitNotice("notice.addVertex.refused", NoticePlacement.NearCursor) + return + } + UmamoLog.info("addVertex accept: committed") + latches.clearSelectTool() + } + + /** + * Sets the Circle-select brush radius (clamped), remembering it for the next arm. When a Circle tool is + * live its radius updates in place so the overlay redraws; otherwise only the remembered value moves. + * + * @param Float radiusPx The requested radius in viewport pixels. + */ + fun setCircleRadius(radiusPx: Float) { + latches.setCircleRadius(radiusPx) + } + + /** Grows the Circle-select radius by one step (numpad +); a no-op unless a Circle tool is live. */ + fun growCircleRadius() { + latches.growCircleRadius() + } + + /** Shrinks the Circle-select radius by one step (numpad -); a no-op unless a Circle tool is live. */ + fun shrinkCircleRadius() { + latches.shrinkCircleRadius() + } + + /** Clears any armed select / geometry tool (the overlay calls this on completion, Esc, or RMB). */ + fun clearSelectTool() { + latches.clearSelectTool() + } + + /** + * Arms the Zoom Region gesture (Blender's Shift+B) for [areaId]. Mode-agnostic - valid in Object and + * Edit mode. Clears any latched Edit-mode tool so two overlays never capture at once. + * + * @param String areaId The viewport area the gesture will run in (the pointer's active area). + */ + fun armZoomRegion(areaId: String) { + latches.armZoomRegion(areaId) + } + + /** Disarms the Zoom Region gesture (the overlay calls this on completion, Esc, or RMB). */ + fun disarmZoomRegion() { + latches.disarmZoomRegion() + } + + /** + * The 2D cursor's world position, or null before any placement. Transient session state like the + * tool latches (deliberately NOT part of EditorSnapshot - see [Cursor2d]); placed by Shift+RightClick + * in the viewport, moved by the snap commands, and drawn by the HUD overlay only once placed. An + * operation that uses the cursor as a point reads [cursor2dOrWorldOrigin] instead. + */ + val cursor2d: StateFlow = latches.cursor2d + + /** + * Where the 2D cursor is: its placed point, or the world origin while it is unplaced. An unplaced + * cursor is not drawn, but everything that uses it as a point - the transform pivot in + * [TransformPivotMode.Cursor] and the snap commands - treats it as resting on the world axes, the way + * Blender's 3D cursor starts at the origin. Resolved on read, so the persisted cursor stays unplaced. + * + * @return Cursor2d The cursor's world position. + */ + fun cursor2dOrWorldOrigin(): Cursor2d = + cursor2d.value ?: model.value.let { current -> Cursor2d(current.worldOriginX, current.worldOriginZ) } + + /** + * Places (or moves) the 2D cursor. + * + * @param Float worldX The cursor's new world-space x. + * @param Float worldZ The cursor's new world-space z (up). + */ + fun setCursor2d(worldX: Float, worldZ: Float) { + latches.setCursor2d(worldX, worldZ) + } + + /** + * The UV editor's cursor in normalized atlas coordinates, or null before any placement. The + * texture-space sibling of [cursor2d] (see [UvCursor]): placed by Shift+RightClick in the UV editor, + * drawn by its overlay, and read as the UV transform pivot in [TransformPivotMode.Cursor]. + */ + val uvCursor: StateFlow = latches.uvCursor + + /** + * Places (or moves) the UV editor's cursor. + * + * @param Float u The cursor's new normalized atlas u coordinate. + * @param Float v The cursor's new normalized atlas v coordinate. + */ + fun setUvCursor(u: Float, v: Float) { + latches.setUvCursor(u, v) + } + + /** + * The viewport grid geometry (major spacing + subdivisions) driving both the drawn backdrop grid and + * the grid snap increment. Session state, deliberately NOT snapshotted - like the 2D cursor. Seeded from + * the global-default settings, or from the document's own value when it saved one + * ([gridFollowsApplication]). Read by the snap commands ([GridConfig.snapStep]) and pushed to the renderer + * by the viewport binding. + */ + val gridConfig: StateFlow = latches.gridConfig + + /** + * Whether the grid follows the application's default rather than a value the document brought with it. + * + * The viewport binding pushes the default grid setting into the session at open and on every change to it; a + * document that saved a grid of its own keeps it against that push, which is what makes it the document's. + */ + val gridFollowsApplication: Boolean = openingViewState?.gridConfig == null + + /** + * Sets the viewport grid geometry. Called by the viewport binding when the global-default settings + * change, while the grid follows them ([gridFollowsApplication]). + * + * @param GridConfig config The new grid scale and subdivisions. + */ + fun setGridConfig(config: GridConfig) { + latches.setGridConfig(config) + } + + /** + * The session state a saved document carries (docs/format/UMA.md § 7.4), as it stands now - the gather side of + * the constructor's initialViewState. The pose is not part of it; a save reads [pose] beside it. + * + * @return SessionViewState The state to save. + */ + fun viewState(): SessionViewState = + SessionViewState( + selection = mutableSelection.value, + parameterSelection = mutableParameterSelection.value, + mode = mutableMode.value, + selectMode = mutableMeshSelection.value.selectMode, + cursor2d = latches.cursor2d.value, + uvCursor = latches.uvCursor.value, + pivotMode = latches.pivotMode.value, + proportionalEnabled = latches.proportionalEdit.value != null, + proportionalSettings = latches.proportionalSettings, + gridConfig = latches.gridConfig.value.takeUnless { gridFollowsApplication }, + ) + + /** + * What a modal Scale / Rotate turns the selection about (the Period pie / the header dropdown). + * Transient editor state - it survives mode switches but is never snapshotted; the default is + * Blender's Median Point. + */ + val pivotMode: StateFlow = latches.pivotMode + + /** + * Selects the transform pivot mode. + * + * @param TransformPivotMode mode The pivot mode the next transforms anchor on. + */ + fun setPivotMode(mode: TransformPivotMode) { + latches.setPivotMode(mode) + } + + /** + * The axis the in-flight modal Grab / Scale is locked to, or null when unconstrained. Set by the + * shell's key ladder (X / Z during a modal gesture - the keymap cannot see those keys, the operator + * swallows them), read by the gizmo overlays' drive loops, cleared whenever an operator latches or + * clears. Transient coordination like [activeMeshOperator]. + */ + val axisConstraint: StateFlow = latches.axisConstraint + + /** + * Toggles the modal axis constraint (pressing a lock's own key again releases it; pressing the other + * axis switches). A no-op unless a Grab or Scale operator is in flight - Rotate has no axis to lock + * and idle keys must not arm a stale constraint. + * + * @param TransformAxisConstraint axis The axis whose lock to toggle. + */ + fun toggleAxisConstraint(axis: TransformAxisConstraint) { + latches.toggleAxisConstraint(axis) + } + + /** + * The radial pie menu currently open over the viewport, or null. Transient UI coordination: a + * command opens it (Period / Shift+S / the merge menu), the pie host composable renders it at the + * pointer, and picking an entry or Escape closes it. + */ + val activePieMenu: StateFlow = latches.activePieMenu + + /** + * Opens a pie menu over the viewport (closing any other transient latch is not needed - a pie is + * display-only and the key ladder swallows input while one is open). + * + * @param PieMenuKind kind The pie to open. + */ + fun openPieMenu(kind: PieMenuKind) { + latches.openPieMenu(kind) + } + + /** Closes the open pie menu (entry picked, Escape, or a click outside). */ + fun closePieMenu() { + latches.closePieMenu() + } + + /** + * The keyform edit waiting on an axis, or null. Transient UI coordination exactly like + * [activePieMenu]: an ambiguous `I` / `Alt+I` parks here, the shell lists the candidate parameters at + * the pointer, and picking one replays the edit through [resolveParameterChoice]. + */ + val pendingParameterChoice: StateFlow = latches.pendingParameterChoice + + /** + * Parks a keyform edit until the user picks the axis it writes on. + * + * @param ParameterChoiceRequest request The parked edit and the axes to choose between. + */ + fun requestParameterChoice(request: ParameterChoiceRequest) { + latches.openParameterChoice(request) + } + + /** Abandons the parked keyform edit (Escape, or a click outside the prompt). */ + fun cancelParameterChoice() { + latches.closeParameterChoice() + } + + /** + * Proportional editing (Blender's O): non-null while enabled, carrying the falloff curve and the + * influence radius. Transient editor state like [pivotMode] - it survives mode switches but is + * never snapshotted; the Edit overlay reads it when a modal operator latches (and on mid-gesture + * radius scrolls) to weight the unselected vertices near the selection. + */ + val proportionalEdit: StateFlow = latches.proportionalEdit + + /** + * Toggles proportional editing on or off (Blender's O), restoring the last falloff and radius on + * re-enable and confirming either way with a near-cursor notice (an idle toggle has no other + * visible effect - the influence circle only shows during a modal transform). + */ + fun toggleProportionalEdit() { + latches.toggleProportionalEdit() + } + + /** + * Toggles Connected Only for proportional editing (influence measured along mesh edges instead of + * straight-line, so the halo never leaps to unconnected geometry), enabling proportional editing + * if it was off - and then connected mode turns ON regardless of the remembered flag, since the + * command expresses the intent to use it. Confirms either way with a near-cursor notice. + */ + fun toggleProportionalConnected() { + latches.toggleProportionalConnected() + } + + /** + * Selects the proportional falloff curve, enabling proportional editing if it was off - picking a + * falloff from the palette or header expresses the intent to use it, and silently updating a + * disabled state would look like the command did nothing. + * + * @param ProportionalFalloff falloff The falloff curve the influence weights follow. + */ + fun setProportionalFalloff(falloff: ProportionalFalloff) { + latches.setProportionalFalloff(falloff) + } + + /** + * Sets the proportional influence radius, clamped to the allowed range. A no-op while proportional + * editing is off (the radius only changes from the mid-gesture scroll, which requires it on). + * + * @param Float radiusWorld The influence radius in world units (canvas px). + */ + fun setProportionalRadius(radiusWorld: Float) { + latches.setProportionalRadius(radiusWorld) + } + + /** + * Sets proportional editing outright - on with [state], or off with null - without a notice: the + * operation settings strip writes an adjusted transform's proportional rows back through here, so + * the next gesture starts from what the rigger last dialled in. + * + * @param ProportionalEditState? state The state to set, or null to turn proportional editing off. + */ + fun setProportionalEdit(state: ProportionalEditState?) { + latches.setProportionalEdit(state) + } + + /** + * Fires the geometry-dependent snap operations (Blender's Shift+S) for the active mode's overlay to + * execute: the posed world projections and the deformer-chain inverse those snaps need live with the + * overlays, not here (the same division as [meshConfirmRequests]). The purely arithmetical snaps + * (cursor to world origin / to grid) never pass through - their command handlers set the cursor + * directly. + * + * The payload carries the dispatch-time resolved area (see [SnapRequest]) purely to elect ONE of the + * open viewports; the handlers themselves ignore it. + */ + val snapRequests: SharedFlow = requestBus.snapRequests + + /** + * Requests a geometry-dependent snap (see [snapRequests]). + * + * @param SnapKind kind The snap to perform. + * @param String? areaId The executing overlay's area, resolved at command dispatch; null no-ops. + */ + fun requestSnap(kind: SnapKind, areaId: String?) { + requestBus.requestSnap(SnapRequest(kind, areaId)) + } + + /** + * Fires Select Linked (Blender's L / Ctrl+L) for one overlay to execute: a keymap command carries + * no pointer position, so the overlay (which tracks the pointer and owns the projected geometry) + * picks the seed and floods. The payload carries the flood variant AND the dispatch-time resolved + * area (see [SelectLinkedRequest]), so collectors gate deterministically on their own area id + * instead of re-reading a pointer-side volatile at collect time. + */ + val selectLinkedRequests: SharedFlow = requestBus.selectLinkedRequests + + /** + * Requests a Select Linked (see [selectLinkedRequests]). + * + * @param Boolean fromSelection True to flood from the whole selection (Ctrl+L), false from the cursor (L). + * @param String? areaId The executing overlay's area, resolved at command dispatch; null no-ops. + */ + fun requestSelectLinked(fromSelection: Boolean, areaId: String?) { + requestBus.requestSelectLinked(SelectLinkedRequest(fromSelection, areaId)) + } + + /** + * Fires a UV snap (the UV editor's Shift+S pie) for one UV editor overlay to execute: the shown + * surface's dimensions and display geometry live with the overlay, so it performs the snap over + * the texture coordinates (the texture-space sibling of [snapRequests]). The payload carries the + * operation AND the dispatch-time resolved area (see [UvSnapRequest]), so the collector gates + * deterministically on its own area id. + */ + val uvSnapRequests: SharedFlow = requestBus.uvSnapRequests + + /** + * Requests a UV snap (see [uvSnapRequests]). + * + * @param UvSnapRequest request The snap operation plus the executing overlay's area, resolved at + * command dispatch; a null area (the hovered surface was not a UV editor) no-ops. + */ + fun requestUvSnap(request: UvSnapRequest) { + requestBus.requestUvSnap(request) + } + + /** + * Fires a mirror (the uv.mirrorU / uv.mirrorV commands) for one UV editor overlay to execute: the + * axis a mirror reflects about depends on the surface being authored over - an atlas page or a + * source layer - and only the overlay knows which it is showing, so it supplies the frame and calls + * [mirrorSelectedUvs]. The payload carries the axis AND the dispatch-time resolved area (see + * [UvMirrorRequest]), so the collector gates deterministically on its own area id. + */ + val uvMirrorRequests: SharedFlow = requestBus.uvMirrorRequests + + /** + * Requests a mirror (see [uvMirrorRequests]). + * + * @param UvMirrorRequest request The mirror axis plus the executing overlay's area, resolved at + * command dispatch; a null area (the hovered surface was not a UV editor) no-ops. + */ + fun requestUvMirror(request: UvMirrorRequest) { + requestBus.requestUvMirror(request) + } + + /** + * Fires a viewport geometry mirror (mesh.mirrorH / mesh.mirrorV) for one viewport overlay to execute: + * Edit verts, Object drawables, and warp-lattice control points all need posed world geometry only + * the overlay has. The payload carries the axis and the dispatch-time resolved area. + */ + val viewportMirrorRequests: SharedFlow = requestBus.viewportMirrorRequests + + /** + * Requests a viewport geometry mirror (see [viewportMirrorRequests]). + * + * @param ViewportMirrorRequest request The axis plus the executing overlay's area. + */ + fun requestViewportMirror(request: ViewportMirrorRequest) { + requestBus.requestViewportMirror(request) + } + + /** + * Fires a page switch (the uv.page.* palette commands) for one UV editor area to execute: the + * per-area texture selection (the page pin) lives with the area's view state, not the session, so + * the space applies the transition itself. The payload carries the operation AND the + * dispatch-time resolved area (see [UvPageRequest]), so the collector gates deterministically on + * its own area id. + */ + val uvPageRequests: SharedFlow = requestBus.uvPageRequests + + /** + * Requests a page switch (see [uvPageRequests]). + * + * @param UvPageRequest request The page operation plus the executing area, resolved at command + * dispatch; a null area (the hovered surface was not a UV editor) no-ops. + */ + fun requestUvPage(request: UvPageRequest) { + requestBus.requestUvPage(request) + } + + /** + * Fires "switch the edited mesh to the drawable under the cursor" (Alt+Q) for the Edit overlay to + * execute - the pointer position and the pick live there (the same division as + * [selectLinkedRequests]). The payload IS the dispatch-time resolved area, so the collector gates on + * its own id rather than re-reading a pointer-side volatile at collect time. + */ + val switchObjectRequests: SharedFlow = requestBus.switchObjectRequests + + /** + * Requests an Alt+Q edited-mesh switch (see [switchObjectRequests]). + * + * @param String? areaId The executing overlay's area, resolved at command dispatch; null no-ops. + */ + fun requestSwitchObjectUnderCursor(areaId: String?) { + requestBus.requestSwitchObjectUnderCursor(areaId) + } + + /** + * Fires a rip (Blender's V) for the Edit overlay to execute: which side of the fan follows the + * ripped copies depends on the pointer, which lives with the overlay (the same division as + * [selectLinkedRequests]). The payload IS the dispatch-time resolved area, so the collector gates on + * its own id rather than re-reading a pointer-side volatile at collect time. + */ + val ripRequests: SharedFlow = requestBus.ripRequests + + /** + * Requests a rip at the pointer (see [ripRequests]). + * + * @param String? areaId The executing overlay's area, resolved at command dispatch; null no-ops. + */ + fun requestRip(areaId: String?) { + requestBus.requestRip(areaId) + } + + /** + * Commits a topology operation on one session mesh as ONE undo step: the model takes the edit (mesh + * swap, keyform-delta rebuild, glue remap - see [withMeshTopologyEdit]) and the mesh selection + * becomes the operation's result elements on that mesh, in the SAME history push - splitting them + * would let undo tear the selection from the topology it indexes into. The ops produce vertex + * results; they are re-derived into the CURRENT select mode (Blender keeps the mode across a + * topology op - a face-mode duplicate leaves the new faces selected in face mode), falling back to + * vertex mode only when nothing in the current domain covers them (e.g. a duplicated lone edge + * copies as loose vertices, which no edge or face contains - stranding them unselected would hide + * the copies and starve the follow-up auto-grab). A no-op edit records nothing. + * + * @param String labelKey The operation's history label key (change.mesh.duplicate / merge / rip / connect). + * @param DrawableId drawableId The edited mesh. + * @param TopologyOpResult result The op builder's outcome. + * @return Boolean True when a step was recorded; false for a no-op edit, after which a caller must + * not register the operation as adjustable (there is no step of its own to amend). + */ + fun commitMeshTopology(labelKey: String, drawableId: DrawableId, result: TopologyOpResult): Boolean { + val newModel = mutableModel.value.withMeshTopologyEdit(drawableId, result.edit) + if (newModel === mutableModel.value) { + return false + } + val current = mutableMeshSelection.value + val vertexResult = + MeshSelection( + drawableIds = current.drawableIds, + activeDrawableId = drawableId, + selectMode = MeshSelectMode.Vertex, + elementsByDrawable = if (result.newElements.isEmpty()) emptyMap() else mapOf(drawableId to result.newElements), + activeElement = result.newElements.firstOrNull()?.let { element -> ActiveMeshElement(drawableId, element) }, + ) + val newSelection = rederiveTopologyResult(vertexResult, current.selectMode, drawableId, newModel) + val change = MeshChange.TopologyEdit(drawableId, labelKey) + pushStep(snapshot(model = newModel, meshSelection = newSelection), change) + mutableModel.value = newModel + mutableMeshSelection.value = newSelection + refreshFlags() + mutableChanges.tryEmit(change) + return true + } + + /** + * Converts a topology op's vertex-mode result selection into [selectMode] against [newModel] (the + * post-edit topology, where the new elements exist), via the strict derive-up rules of + * [MeshSelectionOps.changeSelectMode]; the first derived element becomes active. Returns the + * vertex result unchanged when the session is already in vertex mode, when the op selected + * nothing, or when nothing in the target domain covers the new vertices (see + * [commitMeshTopology]'s docblock for that fallback's rationale). + * + * @param MeshSelection vertexResult The op's result selection, in vertex mode. + * @param MeshSelectMode selectMode The session's current select mode to re-derive into. + * @param DrawableId drawableId The edited mesh. + * @param PuppetModel newModel The model with the topology edit applied. + * @return MeshSelection The result selection in the kept mode, or the vertex fallback. + */ + private fun rederiveTopologyResult( + vertexResult: MeshSelection, + selectMode: MeshSelectMode, + drawableId: DrawableId, + newModel: PuppetModel, + ): MeshSelection { + if (selectMode == MeshSelectMode.Vertex || vertexResult.elementsOf(drawableId).isEmpty()) { + return vertexResult + } + val rederived = + MeshSelectionOps.changeSelectMode(vertexResult, selectMode) { candidateId -> + newModel.drawables.firstOrNull { drawable -> drawable.id == candidateId }?.mesh?.indices + } + val rederivedElements = rederived.elementsOf(drawableId) + if (rederivedElements.isEmpty()) { + return vertexResult + } + return rederived.copy(activeElement = ActiveMeshElement(drawableId, rederivedElements.first())) + } + + /** + * Duplicates the ACTIVE session mesh's covered elements in place (Edit-mode Shift+D) as one undo + * step, leaving the copies selected - the caller follows with a Grab so the copies pull away under + * the pointer, Blender-style. A no-op outside Edit mode or with nothing covered on the active mesh. + */ + fun duplicateSelectedElements() { + if (mutableMode.value != EditorMode.Edit) { + return + } + val selection = mutableMeshSelection.value + val drawableId = selection.activeDrawableId ?: return + val mesh = mutableModel.value.drawables.firstOrNull { it.id == drawableId }?.mesh ?: return + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(drawableId), mesh.indices) + val result = MeshTopologyOps.duplicateElements(mesh, covered) ?: return + commitMeshTopology("change.mesh.duplicate", drawableId, result) + } + + /** + * Merges the ACTIVE session mesh's selected vertices (Blender's M) as one undo step, leaving the + * survivor selected, and registers the step on the operation settings strip with its one row, Merge + * At - so a merge landed at the center can be re-landed at the first or last vertex without undoing. + * The rerun re-merges the SAME vertices from the record's base; every target keeps the survivor at + * the same index, so the survivor selection the step carries stays valid across an adjustment. + * Vertex mode only - the first / last targets read the selection order, which only vertex elements + * carry directly. Refusals explain themselves with a near-cursor notice. + * + * @param MergeTarget target Where the survivor lands (center / first / last). + * @param String? areaId The area the strip shows in (opaque here, like the operator latches), or null. + */ + fun mergeSelectedVertices(target: MergeTarget, areaId: String? = null) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val selection = mutableMeshSelection.value + val drawableId = selection.activeDrawableId ?: return + if (selection.selectMode != MeshSelectMode.Vertex) { + emitNotice("notice.merge.needsVertices", NoticePlacement.NearCursor) + return + } + // The element set is insertion-ordered (a LinkedHashSet built by the gestures), so "first" is + // the earliest-selected vertex; "last" prefers the active element (the most recent touch). + val orderedVertices = selection.elementsOf(drawableId).filterIsInstance().map { vertex -> vertex.index }.toMutableList() + (selection.activeElement?.element as? MeshElement.Vertex)?.let { activeVertex -> + if (orderedVertices.remove(activeVertex.index)) { + orderedVertices.add(activeVertex.index) + } + } + if (orderedVertices.size < 2) { + emitNotice("notice.merge.needsVertices", NoticePlacement.NearCursor) + return + } + val mesh = mutableModel.value.drawables.firstOrNull { it.id == drawableId }?.mesh ?: return + val result = MeshTopologyOps.mergeVertices(mesh, orderedVertices, target) ?: return + if (!commitMeshTopology("change.mesh.merge", drawableId, result)) { + return + } + val mergedVertices = orderedVertices.toList() + registerAdjustableOperation(mutableModel.value, areaId, mergeParameters(target)) { record -> + val adjustedTarget = mergeTargetOf(record.parameters, target) + val baseModel = record.baseSnapshot.model + val baseMesh = baseModel.drawables.firstOrNull { it.id == drawableId }?.mesh ?: return@registerAdjustableOperation + val rerun = MeshTopologyOps.mergeVertices(baseMesh, mergedVertices, adjustedTarget) ?: return@registerAdjustableOperation + amendLastCommit(record, baseModel.withMeshTopologyEdit(drawableId, rerun.edit)) + } + } + + /** + * Connects the ACTIVE session mesh's two selected vertices with a cut (Blender's J) as one undo + * step, leaving the cut path selected. Exactly two selected vertices in vertex mode; a refusal + * (already connected, nothing crossed, degenerate geometry) explains itself with a notice. + */ + fun connectSelectedVertices() { + if (mutableMode.value != EditorMode.Edit) { + return + } + val selection = mutableMeshSelection.value + val drawableId = selection.activeDrawableId ?: return + val vertices = selection.elementsOf(drawableId).filterIsInstance().map { vertex -> vertex.index } + if (selection.selectMode != MeshSelectMode.Vertex || vertices.size != 2) { + emitNotice("notice.connect.needsTwoVertices", NoticePlacement.NearCursor) + return + } + val mesh = mutableModel.value.drawables.firstOrNull { it.id == drawableId }?.mesh ?: return + val result = MeshTopologyOps.connectVertices(mesh, vertices[0], vertices[1]) + if (result == null) { + emitNotice("notice.connect.refused", NoticePlacement.NearCursor) + return + } + commitMeshTopology("change.mesh.connect", drawableId, result) + } + + /** + * Duplicates every eligible selected drawable (Object-mode Shift+D) as ONE undo step: each copy + * lands after its source in the org tree, and the selection becomes the copies - the caller follows + * with a Grab so they pull away under the pointer, Blender-style. + * + * @return List The created copies (empty when nothing was eligible). + */ + fun duplicateSelectedDrawables(): List { + if (mutableMode.value != EditorMode.Object) { + return emptyList() + } + val eligibleIds = eligibleTransformDrawables(mutableSelection.value, mutableModel.value) ?: return emptyList() + var newModel = mutableModel.value + val copies = ArrayList(eligibleIds.size) + for (drawableId in eligibleIds) { + val (edited, copyId) = newModel.withDrawableDuplicated(drawableId) ?: continue + newModel = edited + copies.add(copyId) + } + if (copies.isEmpty() || newModel === mutableModel.value) { + return emptyList() + } + val newSelection = + Selection( + copies.map { copyId -> SelectionTarget.Drawable(copyId) }.toSet(), + SelectionTarget.Drawable(copies.last()), + ) + val change = DrawableChange.Duplicate(copies) + pushStep(snapshot(model = newModel, selection = newSelection), change) + mutableModel.value = newModel + mutableSelection.value = newSelection + refreshFlags() + mutableChanges.tryEmit(change) + return copies + } + + /** + * Re-seeds the Edit session onto one drawable (Alt+Q's switch), as ONE undo step covering both + * selections: the session's meshes become just [drawableId] (with its remembered elements restored + * where they still fit), and the OBJECT selection moves onto the same drawable - so tabbing back to + * Object mode keeps the switched mesh instead of reviving the selection Edit mode was entered with. + * The outgoing meshes' element selections stash into the per-mesh memory first, and the + * remembered-drawable memory follows. A no-op outside Edit mode or when the drawable carries no + * mesh. + * + * Built as one combined snapshot push (never chained setSelection + setMeshSelection - each of + * those snapshots the OTHER selection's pre-change value, which would tear the pair across two + * undo steps). + * + * @param DrawableId drawableId The mesh to edit next. + */ + fun switchEditDrawable(drawableId: DrawableId) { + if (mutableMode.value != EditorMode.Edit) { + return + } + val model = mutableModel.value + if (model.drawables.none { drawable -> drawable.id == drawableId && drawable.mesh != null }) { + return + } + elementMemory.stash(mutableMeshSelection.value) + elementMemory.lastActiveDrawableId = drawableId + val newObjectSelection = SelectionOps.replace(SelectionTarget.Drawable(drawableId)) + val newMeshSelection = elementMemory.restore(MeshSelection.editing(listOf(drawableId)), model) + if (newObjectSelection == mutableSelection.value && newMeshSelection == mutableMeshSelection.value) { + return + } + pushStep( + snapshot(model = model, selection = newObjectSelection, meshSelection = newMeshSelection), + EditorStateChange.MeshSelectionChanged, + ) + mutableSelection.value = newObjectSelection + mutableMeshSelection.value = newMeshSelection + refreshFlags() + mutableChanges.tryEmit(EditorStateChange.MeshSelectionChanged) + } + + /** + * Fires when an in-flight modal mesh gesture should confirm. The working positions live in the desktop + * overlay, so the session cannot commit directly - it signals here and the overlay commits. This is the + * keyboard path (Enter); a primary click confirms in the overlay's own pointer loop. + */ + val meshConfirmRequests: SharedFlow = requestBus.meshConfirmRequests + + /** Requests that the gizmo overlay confirm the in-flight modal gesture (bound to Enter, like a click). */ + fun requestMeshConfirm() { + requestBus.requestMeshConfirm() + } + + /** + * Fires when an in-flight selection gesture should be abandoned (Escape). The box rubber-band and the + * circle stroke live in the overlay's local state, so the session cannot discard them directly - it + * signals here and the overlay clears them. Clearing a latched tool ([clearSelectTool]) already tells + * the overlay to abandon its gesture through the tool flow; this is the extra path for a non-armed box + * drag, which owns no tool state to change. + */ + val meshGestureCancelRequests: SharedFlow = requestBus.meshGestureCancelRequests + + /** Requests that the gizmo overlay abandon any in-flight box / circle selection gesture (bound to Escape). */ + fun requestMeshGestureCancel() { + requestBus.requestMeshGestureCancel() + } + + /** Steps back one undo level, republishing the model and selection. No-op when nothing to undo. */ + fun undo() { + restore(history.undo() ?: return) + } + + /** Steps forward one redo level, republishing the model and selection. No-op when nothing to redo. */ + fun redo() { + restore(history.redo() ?: return) + } + + /** + * Jumps the history cursor directly to [index], republishing the model and selection at that step. The + * history panel calls this when a row is clicked, so the user can leap across several undo levels at + * once. No-op when [index] is already the live step. + * + * @param Int index The target step index within [historyView]. + */ + fun jumpTo(index: Int) { + restore(history.jumpTo(index) ?: return) + } + + /** + * Marks the live model as the saved baseline, clearing the dirty marker - the form for a save that + * wrote the model that is current now. + */ + fun markSaved() { + markSaved(mutableModel.value) + } + + /** + * Marks [model] as the saved baseline: the instance a save snapshotted and wrote, which is the live + * model unless an edit landed while the file was being written. In that case the document stays + * dirty, since what is on screen is not what is on disk, and undoing back to [model] clears it. + * + * @param PuppetModel model The model instance just persisted. + */ + fun markSaved(model: PuppetModel) { + history.markSaved(model) + refreshFlags() + } + + /** + * Restores every session flow from [snapshot] - the history mechanism behind undo, redo, and jumpTo. + * Also updates the remembered active drawable and tears down all transient tool state (see the inline + * comment), then republishes the derived flags. + * + * @param EditorSnapshot snapshot The history snapshot to restore. + */ + private fun restore(snapshot: EditorSnapshot) { + // The strip belongs to the newest step only: moving the cursor ends the adjustable operation, + // and voids the base so nothing can register against the step just left. + mutableAdjustableOperation.value = null + lastBaseSnapshot = null + // The remembered drawable tracks whatever was most recently shown active, undo/redo included. + (snapshot.selection.active as? SelectionTarget.Drawable)?.let { activeDrawable -> + elementMemory.lastActiveDrawableId = activeDrawable.id + } + mutableModel.value = snapshot.model + mutableSelection.value = snapshot.selection + mutablePose.value = snapshot.pose + mutableMeshSelection.value = snapshot.meshSelection + mutableParameterSelection.value = snapshot.parameterSelection + // Restored, not cleared: the snapshot carries the pose these values were chosen for, so restoring the + // pair together keeps them coherent - an undo must land on the step's pose WITH the step's pending + // edits, not on the pose alone. + mutablePendingChannelEdits.value = snapshot.pendingChannelEdits + mutableKeySelection.value = snapshot.keySelection + // An undo / redo ends any in-flight gesture or armed tool, regardless of the restored mode: the select + // tool and its overlays are shared across modes, so a tool armed in one mode must not survive a restore + // into a snapshot of the other and drive the wrong overlay. + latches.clearTransient(clearAxisConstraint = true, clearViewportGesture = true) + latches.setPreviewSelection(null) + latches.closePieMenu() + mutableMode.value = snapshot.mode + refreshFlags() + } + + /** + * Republishes the flags derived from the model and the history stack - dirty, canUndo, canRedo, and + * the projected history view. Called after every mutation, restore, and saved-baseline move. + */ + private fun refreshFlags() { + history.refreshFlags(mutableModel.value) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/FreeTransform.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/FreeTransform.kt new file mode 100644 index 0000000..ddabf12 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/FreeTransform.kt @@ -0,0 +1,300 @@ +package org.umamo.edit + +import kotlin.math.abs + +/** + * One of the eight Photoshop-style scale handles on an axis-aligned bounds box: four corners and four + * edge midpoints. Corner handles resize both axes; edge handles resize only the axis they sit on. + * + * World y is up (the viewport's displayed Z). Screen drawing maps through the camera; hit-testing is + * done in screen pixels by the overlay. + */ +enum class BoundsHandle { + MinXMinY, + MidXMinY, + MaxXMinY, + MinXMidY, + MaxXMidY, + MinXMaxY, + MidXMaxY, + MaxXMaxY, + ; + + /** True when dragging this handle changes the x extent. */ + val affectsX: Boolean + get() = this != MidXMinY && this != MidXMaxY + + /** True when dragging this handle changes the y extent. */ + val affectsY: Boolean + get() = this != MinXMidY && this != MaxXMidY +} + +/** + * Axis-aligned bounds of a selection, with explicit min/max corners. Prefer this over [MeshBounds] + * when a free-transform handle needs the fixed opposite edge as a pivot - center+extent alone forces + * every caller to re-derive the corners and risk off-by-half errors. + * + * @property Float minX The left edge (smallest x). + * @property Float minY The bottom edge in world space (smallest y; world y is up). + * @property Float maxX The right edge (largest x). + * @property Float maxY The top edge in world space (largest y). + */ +data class AxisAlignedBounds( + val minX: Float, + val minY: Float, + val maxX: Float, + val maxY: Float, +) { + val width: Float get() = maxX - minX + + val height: Float get() = maxY - minY + + val centerX: Float get() = (minX + maxX) * 0.5f + + val centerY: Float get() = (minY + maxY) * 0.5f + + val isEmpty: Boolean get() = width <= 0f && height <= 0f + + /** + * The world-space position of [handle] on this box (corners and edge midpoints). + * + * @param BoundsHandle handle The handle. + * @return Pair The (x, y) world position. + */ + fun handleWorld(handle: BoundsHandle): Pair = + when (handle) { + BoundsHandle.MinXMinY -> minX to minY + BoundsHandle.MidXMinY -> centerX to minY + BoundsHandle.MaxXMinY -> maxX to minY + BoundsHandle.MinXMidY -> minX to centerY + BoundsHandle.MaxXMidY -> maxX to centerY + BoundsHandle.MinXMaxY -> minX to maxY + BoundsHandle.MidXMaxY -> centerX to maxY + BoundsHandle.MaxXMaxY -> maxX to maxY + } +} + +/** + * Axis-aligned bounds of the vertices in [indices] (or every vertex when [indices] is null / empty and + * [positions] is non-empty). Returns a zero box when there is nothing to measure. + * + * @param FloatArray positions Interleaved (x, y) positions. + * @param Set? indices Vertex indices to include, or null / empty for the whole array. + * @return AxisAlignedBounds The selection's AABB. + */ +fun selectionBounds(positions: FloatArray, indices: Set? = null): AxisAlignedBounds { + val pointCount = positions.size / 2 + if (pointCount == 0) { + return AxisAlignedBounds(0f, 0f, 0f, 0f) + } + val cover = + if (indices.isNullOrEmpty()) { + null + } else { + indices + } + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var found = false + if (cover == null) { + var slot = 0 + while (slot + 1 < positions.size) { + val x = positions[slot] + val y = positions[slot + 1] + if (x < minX) minX = x + if (x > maxX) maxX = x + if (y < minY) minY = y + if (y > maxY) maxY = y + found = true + slot += 2 + } + } else { + for (index in cover) { + if (index < 0 || index >= pointCount) { + continue + } + val x = positions[index * 2] + val y = positions[index * 2 + 1] + if (x < minX) minX = x + if (x > maxX) maxX = x + if (y < minY) minY = y + if (y > maxY) maxY = y + found = true + } + } + if (!found) { + return AxisAlignedBounds(0f, 0f, 0f, 0f) + } + return AxisAlignedBounds(minX, minY, maxX, maxY) +} + +/** + * Combined axis-aligned bounds of several interleaved position arrays (optionally restricted per array). + * Used when Object-mode Scale wraps multiple drawables in one marquee. + * + * @param List?>> sources Each (positions, indices-or-null-for-all) pair. + * @return AxisAlignedBounds The union AABB, or a zero box when every source is empty. + */ +fun unionSelectionBounds(sources: List?>>): AxisAlignedBounds { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var found = false + for ((positions, indices) in sources) { + if (positions.size < 2) { + continue + } + val box = selectionBounds(positions, indices) + if (box.minX < minX) minX = box.minX + if (box.minY < minY) minY = box.minY + if (box.maxX > maxX) maxX = box.maxX + if (box.maxY > maxY) maxY = box.maxY + found = true + } + if (!found) { + return AxisAlignedBounds(0f, 0f, 0f, 0f) + } + return AxisAlignedBounds(minX, minY, maxX, maxY) +} + +/** + * Per-axis scale factors and pivot for a Photoshop-style handle drag: the opposite edge/corner stays + * fixed (or the bounds center when [fromCenter] is set), and the dragged handle follows [targetX] / + * [targetY]. Degenerate axes (zero extent) yield factor 1 so a flat selection cannot explode. + * + * [uniform] (Shift) forces both factors to the dominant axis's factor on corner handles; edge handles + * stay single-axis. + * + * @param AxisAlignedBounds startBounds The selection AABB at gesture start. + * @param BoundsHandle handle The handle being dragged. + * @param Float targetX The pointer's world x (where the handle should land). + * @param Float targetY The pointer's world y. + * @param Boolean uniform Keep aspect ratio (corner drags). + * @param Boolean fromCenter Scale about the bounds center instead of the opposite side. + * @return Triple factorX, factorY, pivot (x, y). + */ +fun handleScaleFactors( + startBounds: AxisAlignedBounds, + handle: BoundsHandle, + targetX: Float, + targetY: Float, + uniform: Boolean, + fromCenter: Boolean, +): Triple> { + val width = startBounds.width + val height = startBounds.height + val pivotX: Float + val pivotY: Float + var factorX = 1f + var factorY = 1f + + if (fromCenter) { + pivotX = startBounds.centerX + pivotY = startBounds.centerY + if (handle.affectsX && width > 1e-6f) { + val startOffset = + when (handle) { + BoundsHandle.MinXMinY, BoundsHandle.MinXMidY, BoundsHandle.MinXMaxY -> -width * 0.5f + BoundsHandle.MaxXMinY, BoundsHandle.MaxXMidY, BoundsHandle.MaxXMaxY -> width * 0.5f + else -> width * 0.5f + } + factorX = (targetX - pivotX) / startOffset + } + if (handle.affectsY && height > 1e-6f) { + val startOffset = + when (handle) { + BoundsHandle.MinXMinY, BoundsHandle.MidXMinY, BoundsHandle.MaxXMinY -> -height * 0.5f + BoundsHandle.MinXMaxY, BoundsHandle.MidXMaxY, BoundsHandle.MaxXMaxY -> height * 0.5f + else -> height * 0.5f + } + factorY = (targetY - pivotY) / startOffset + } + } else { + pivotX = + when { + !handle.affectsX -> startBounds.centerX + handle == BoundsHandle.MinXMinY || handle == BoundsHandle.MinXMidY || handle == BoundsHandle.MinXMaxY -> + startBounds.maxX + else -> startBounds.minX + } + pivotY = + when { + !handle.affectsY -> startBounds.centerY + handle == BoundsHandle.MinXMinY || handle == BoundsHandle.MidXMinY || handle == BoundsHandle.MaxXMinY -> + startBounds.maxY + else -> startBounds.minY + } + if (handle.affectsX && width > 1e-6f) { + val startHandleX = + when (handle) { + BoundsHandle.MinXMinY, BoundsHandle.MinXMidY, BoundsHandle.MinXMaxY -> startBounds.minX + else -> startBounds.maxX + } + val startSpan = startHandleX - pivotX + if (abs(startSpan) > 1e-6f) { + factorX = (targetX - pivotX) / startSpan + } + } + if (handle.affectsY && height > 1e-6f) { + val startHandleY = + when (handle) { + BoundsHandle.MinXMinY, BoundsHandle.MidXMinY, BoundsHandle.MaxXMinY -> startBounds.minY + else -> startBounds.maxY + } + val startSpan = startHandleY - pivotY + if (abs(startSpan) > 1e-6f) { + factorY = (targetY - pivotY) / startSpan + } + } + } + + if (uniform && handle.affectsX && handle.affectsY) { + // Dominant axis by how far the pointer pulled that side, measured in world units of the start box. + val pullX = abs(factorX - 1f) * width + val pullY = abs(factorY - 1f) * height + val shared = if (pullX >= pullY) factorX else factorY + factorX = shared + factorY = shared + } + + return Triple(factorX, factorY, pivotX to pivotY) +} + +/** + * Scales [indices] in [positions] so the dragged [handle] of [startBounds] follows ([targetX], + * [targetY]) - Photoshop free-transform scale. Pure: returns a new array (or the same instance when + * nothing moves). + * + * @param FloatArray positions Interleaved (x, y) positions. + * @param Set indices Vertices to scale. + * @param AxisAlignedBounds startBounds The selection AABB frozen at gesture start. + * @param BoundsHandle handle The handle under the pointer. + * @param Float targetX Pointer world x. + * @param Float targetY Pointer world y. + * @param Boolean uniform Shift: keep aspect ratio on corner drags. + * @param Boolean fromCenter Alt: scale about the bounds center. + * @return FloatArray The scaled positions. + */ +fun scaledByHandleDrag( + positions: FloatArray, + indices: Set, + startBounds: AxisAlignedBounds, + handle: BoundsHandle, + targetX: Float, + targetY: Float, + uniform: Boolean = false, + fromCenter: Boolean = false, +): FloatArray { + if (indices.isEmpty() || positions.size < 2) { + return positions + } + val (factorX, factorY, pivot) = + handleScaleFactors(startBounds, handle, targetX, targetY, uniform, fromCenter) + if (factorX == 1f && factorY == 1f) { + return positions + } + return MeshTransforms.scaleVerticesAxis(positions, indices, factorX, factorY, pivot.first, pivot.second) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/History.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/History.kt new file mode 100644 index 0000000..b7b1396 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/History.kt @@ -0,0 +1,258 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel + +/** The default cap on retained undo steps; the oldest is dropped past this (a memory backstop). */ +const val DEFAULT_HISTORY_LIMIT: Int = 200 + +/** + * A pose: the live value of every parameter (the current scrub position the renderer deforms to). Held + * as ephemeral editor state outside [PuppetModel] - it is not document content (keyforms are), but it is + * snapshotted so a scrub is undoable. A small immutable map, so capturing one in a snapshot is cheap. + * + * ポーズ:各パラメータの現在値。ドキュメント内容ではない一時的な編集状態だが、スクラブを取り消せるよう保持。 + */ +typealias Pose = Map + +/** + * One undoable state: the document model plus the ephemeral editor state that rides with it. The + * interaction mode, the object-mode selection, the live pose, and the Edit-mode vertex selection are + * snapshotted here (not inside [PuppetModel]) so undo restores the mode (entering / leaving Edit is a + * real history step, not a guess), the prior selection after a misclick, the prior pose after a scrub, + * and the vertex selection after a mesh edit; a document edit also restores all of these as they were at + * that edit. Every field is an immutable value, so a snapshot is just a few references — cheap to keep + * and to restore. + * + * 取り消し可能な1状態:ドキュメントモデルと、それに付随するモード・選択・ポーズ・頂点選択。PuppetModel の外に持つ。 + * + * @property PuppetModel model The document model at this step. + * @property Selection selection The object-mode selection at this step. + * @property Pose pose The live parameter values (scrub position) at this step. + * @property MeshSelection meshSelection The Edit-mode vertex selection at this step. + * @property EditorMode mode The interaction mode (Object / Edit) at this step. + */ +data class EditorSnapshot( + val model: PuppetModel, + val selection: Selection, + val pose: Pose, + val meshSelection: MeshSelection = MeshSelection(), + val mode: EditorMode = EditorMode.Object, + /** + * The parameters targeted for keyform authoring. Restored like the other selections, so undoing back + * across a parameter click returns the target the edit was made against. + */ + val parameterSelection: ParameterSelection = ParameterSelection(), + /** + * The channel values edited but not yet keyed at this step. + * + * Snapshotted even though a pending edit never reaches the document: it is a deliberate user action + * that shows in the viewport, so Blender records one and so do we. The pose rides in the same + * snapshot, which is what makes restoring these coherent - a pending value was chosen FOR a pose, and + * undo returns to both together. + */ + val pendingChannelEdits: Map = emptyMap(), + /** + * The keyform-sheet keys selected at this step. + * + * The fourth selection to be snapshotted, and for the same reason as the other three: a misclick that + * loses a carefully built selection is otherwise unrecoverable, and the sheet's selection takes the most + * work to build of any of them. Ordinals renumber when keys cross, so a restored ref can name a key + * that no longer exists there - the sheet prunes at use, which is what makes that harmless. + */ + val keySelection: Set = emptySet(), +) + +/** + * One history entry: a [snapshot] and the [change] that produced it (null for the initial state). The + * change is metadata — the snapshot does the undoing — used for the history-panel label and coalescing. + * + * 履歴の1項目:スナップショットと、それを生んだ変更(初期状態は null)。 + * + * @property EditorSnapshot snapshot The state after [change] was applied. + * @property Change change The change that produced [snapshot], or null for the seed entry. + */ +data class HistoryEntry( + val snapshot: EditorSnapshot, + val change: Change?, +) + +/** + * A flattened, immutable projection of the undo stack for the history panel: each step's display + * [labelKey] and the [cursor] index of the live step. Rebuilt on every history change so a Compose + * panel renders it as plain state (clicking a row jumps the session there). Compose-free, so the label + * stays a key the UI resolves to a localized string. + * + * 履歴パネル用の取り消しスタックの平坦化ビュー。各段のラベルキーと現在位置を持つ。 + * + * @property List steps The stack oldest-first. + * @property Int cursor The index of the live step within [steps]. + */ +data class HistoryView( + val steps: List, + val cursor: Int, +) + +/** + * One row of a [HistoryView]. + * + * @property String? labelKey The label key of the change that produced this step, or null for the seed + * (the initial open) entry; the UI maps it to a localized label. + * @property Boolean saved Whether this exact step is the last-saved baseline (the panel marks it). + */ +data class HistoryStep( + val labelKey: String?, + val saved: Boolean, +) + +/** + * A linear undo/redo stack of immutable snapshots. The entry at [cursor] is the live state; [push] + * records a new step (discarding any redo branch, the chosen v1 behaviour), and [undo] / [redo] move the + * cursor and return the state to restore. Snapshots structurally share their unchanged sub-trees, so the + * stack's cost is bounded by what each step actually changed plus the [limit] cap on retained steps. + * + * Undo is a cursor move, never an inverse op — correctness is structural, since each entry holds the + * whole prior value. A future branching "undo tree" can replace the linear backing without touching the + * session API; v1 is deliberately linear. + * + * 不変スナップショットの線形な取り消し/やり直しスタック。やり直し枝は新規記録で破棄する(v1 の方針)。 + * + * @param EditorSnapshot initial The seed entry — the state the document opened on. + * @param Int initialLimit The starting cap; [limit] carries it and may be reassigned later. + * @property Int limit The maximum retained entries; the oldest is dropped past this. Settable at + * runtime, since the cap is a user preference. + */ +class History( + initial: EditorSnapshot, + initialLimit: Int = DEFAULT_HISTORY_LIMIT, +) { + private val entries: MutableList = mutableListOf(HistoryEntry(initial, null)) + private var cursor: Int = 0 + + /** + * The maximum retained entries, settable at runtime because the cap is a user preference. Assigning a + * lower value trims the stack at once (see [trimToLimit]), so lowering it frees memory without waiting + * for the next edit. Clamped to at least 1 so a degenerate cap never empties the stack. + */ + var limit: Int = initialLimit.coerceAtLeast(1) + set(value) { + field = value.coerceAtLeast(1) + trimToLimit() + } + + /** The live state — the snapshot at the current cursor. */ + val current: EditorSnapshot get() = entries[cursor].snapshot + + /** The change that produced the live state, or null at the seed entry (the label for "Undo X"). */ + val currentChange: Change? get() = entries[cursor].change + + /** The cursor's index into the stack — the position of the live step (the history panel highlights it). */ + val cursorIndex: Int get() = cursor + + /** A read-only copy of the stack, oldest-first — the source the history panel renders. */ + val steps: List get() = entries.toList() + + /** True when there is a prior step to undo to. */ + val canUndo: Boolean get() = cursor > 0 + + /** True when a redo step is available (an undo with no intervening [push]). */ + val canRedo: Boolean get() = cursor < entries.lastIndex + + /** + * Records [snapshot] as a new step produced by [change]. Any redo branch ahead of the cursor is + * discarded (linear history); once the stack exceeds [limit] the oldest entry is dropped so the + * cursor stays valid. The seed entry is never dropped below a single retained step. + * + * @param EditorSnapshot snapshot The new live state. + * @param Change change The change that produced it. + */ + fun push(snapshot: EditorSnapshot, change: Change) { + // Drop the redo branch: everything after the cursor is now an abandoned future. + while (entries.lastIndex > cursor) { + entries.removeAt(entries.lastIndex) + } + entries.add(HistoryEntry(snapshot, change)) + cursor = entries.lastIndex + trimToLimit() + } + + /** + * Replaces the live entry with [snapshot] and [change], keeping the cursor where it is - the + * mechanism behind adjusting the last operation: its result is recomputed from the state before + * it and lands over its own step, so the stack never grows and the base is never replayed. + * + * Refuses when a redo branch exists: an adjustment applies only to the newest step, and the caller + * clears its record on any undo anyway. Works at cursor 0 too, since a cap of one drops the base + * entry on push and the adjusting record holds that base itself. + * + * @param EditorSnapshot snapshot The recomputed live state. + * @param Change change The change that produced it (normally the entry's own). + * @return Boolean True when the entry was replaced, false when a redo branch made it refuse. + */ + fun amendTop(snapshot: EditorSnapshot, change: Change): Boolean { + if (canRedo) { + return false + } + entries[cursor] = HistoryEntry(snapshot, change) + return true + } + + /** + * Drops the oldest entries until the stack fits [limit], stopping at the live step so the current state + * and its redo branch are never discarded. That stop is what makes a lowered cap safe to apply to a + * stack whose cursor sits mid-history: it frees what it can at once and sheds the rest on subsequent + * pushes, and the cursor stays valid throughout. On the push path the cursor is the last entry, so the + * stop never engages and the stack lands exactly at the cap. + */ + private fun trimToLimit() { + while (entries.size > limit && cursor > 0) { + entries.removeAt(0) + cursor-- + } + } + + /** + * Moves back one step and returns the state to restore, or null when already at the oldest entry. + * + * @return EditorSnapshot? The prior state, or null if nothing to undo. + */ + fun undo(): EditorSnapshot? { + if (!canUndo) { + return null + } + cursor-- + return current + } + + /** + * Moves forward one step and returns the state to restore, or null when already at the newest entry. + * + * @return EditorSnapshot? The next state, or null if nothing to redo. + */ + fun redo(): EditorSnapshot? { + if (!canRedo) { + return null + } + cursor++ + return current + } + + /** + * Moves the cursor directly to [index] (clamped to the valid range) and returns the state to restore, + * or null when [index] is already the cursor (a no-op jump). This lets the history panel jump across + * several steps at once — multi-undo or multi-redo — rather than walking one level at a time. + * + * @param Int index The target step index within the stack. + * @return EditorSnapshot? The state at [index], or null when it is already the live step. + */ + fun jumpTo(index: Int): EditorSnapshot? { + val target = index.coerceIn(0, entries.lastIndex) + if (target == cursor) { + return null + } + cursor = target + return current + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/HistoryCore.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/HistoryCore.kt new file mode 100644 index 0000000..45a2412 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/HistoryCore.kt @@ -0,0 +1,154 @@ +package org.umamo.edit + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.umamo.runtime.model.PuppetModel + +/** + * The session's undo machinery: the snapshot [History] stack, the saved baseline (both the exact + * snapshot for the history panel's marker and the model instance for the reference-equality dirty + * flag), and the flags/view derived from them. [EditorSession] pushes snapshots and republishes + * flows from the ones this hands back; the derived flows here are exposed on the session unchanged. + * Dirty is measured against the model only, so pose-only and selection-only steps never trip it. + */ +internal class HistoryCore(initialSnapshot: EditorSnapshot, initialHistoryLimit: Int) { + private val history = History(initialSnapshot, initialHistoryLimit) + + /** + * The retained-undo-step cap. Assigning trims the stack immediately, never past the live step; the + * session republishes the derived flags afterwards so the panel and the undo/redo enabled states + * follow the trim. + */ + var limit: Int + get() = history.limit + set(value) { + history.limit = value + } + + /** + * The live step's snapshot - what the last push (or the last undo) recorded. + * + * Distinct from the session's live flows, which run ahead of it whenever an edit is being previewed + * without being recorded. A caller that must decide whether an edit would record anything new has to + * compare against THIS, not against the flows. + */ + val current: EditorSnapshot get() = history.current + + // The exact stack entry last persisted to disk, tracked by snapshot reference so the panel marks one + // row precisely (the dirty flag below tracks the model instead - see EditorSession's class doc). + private var savedSnapshot: EditorSnapshot = history.current + + // The model instance last persisted to disk; dirty is measured against it by reference. + private var savedModel: PuppetModel = initialSnapshot.model + + private val mutableDirty = MutableStateFlow(false) + + /** True when the document model differs from the last-saved state. */ + val dirty: StateFlow = mutableDirty.asStateFlow() + + private val mutableCanUndo = MutableStateFlow(false) + + /** True when there is a step to undo. */ + val canUndo: StateFlow = mutableCanUndo.asStateFlow() + + private val mutableCanRedo = MutableStateFlow(false) + + /** True when there is a step to redo. */ + val canRedo: StateFlow = mutableCanRedo.asStateFlow() + + private val mutableHistoryView = MutableStateFlow(buildHistoryView()) + + /** The undo stack projected for the history panel. */ + val historyView: StateFlow = mutableHistoryView.asStateFlow() + + /** + * Records one undo step. + * + * @param EditorSnapshot snapshot The complete post-edit state. + * @param Change change The descriptor for the bus and the history-panel label. + */ + fun push(snapshot: EditorSnapshot, change: Change) { + history.push(snapshot, change) + } + + /** The change that produced the live step, or null at the seed entry. */ + val currentChange: Change? get() = history.currentChange + + /** + * Replaces the live step in place (see [History.amendTop]). + * + * @param EditorSnapshot snapshot The recomputed live state. + * @param Change change The change that produced it. + * @return Boolean True when replaced, false when a redo branch made the stack refuse. + */ + fun amendTop(snapshot: EditorSnapshot, change: Change): Boolean = history.amendTop(snapshot, change) + + /** + * Steps the cursor back one level. + * + * @return EditorSnapshot? The snapshot to restore, or null with nothing to undo. + */ + fun undo(): EditorSnapshot? = history.undo() + + /** + * Steps the cursor forward one level. + * + * @return EditorSnapshot? The snapshot to restore, or null with nothing to redo. + */ + fun redo(): EditorSnapshot? = history.redo() + + /** + * Jumps the cursor directly to [index]. + * + * @param Int index The target step index. + * @return EditorSnapshot? The snapshot to restore, or null when [index] is already live. + */ + fun jumpTo(index: Int): EditorSnapshot? = history.jumpTo(index) + + /** + * Moves the saved baseline to [model]: it becomes the dirty reference, and the stack entry holding that + * instance becomes the panel's saved marker. + * + * The entry is found by the model's identity rather than taken to be the live one, because a save + * snapshots the model and writes off-thread: an edit landed while the file was being written makes a + * newer entry live, and that entry was never persisted. Dirty then stays true (the live model is not + * the saved instance) and the marker sits on the row that was. A model no entry holds any more (the + * step was trimmed) falls back to the live entry. + * + * @param PuppetModel model The model instance just persisted. + */ + fun markSaved(model: PuppetModel) { + savedModel = model + savedSnapshot = history.steps.lastOrNull { entry -> entry.snapshot.model === model }?.snapshot ?: history.current + } + + /** + * Republishes the derived flags - dirty, canUndo, canRedo, and the projected history view. The + * session calls this after every mutation, restore, and saved-baseline move. + * + * @param PuppetModel currentModel The live document model dirty is measured against. + */ + fun refreshFlags(currentModel: PuppetModel) { + mutableDirty.value = currentModel !== savedModel + mutableCanUndo.value = history.canUndo + mutableCanRedo.value = history.canRedo + mutableHistoryView.value = buildHistoryView() + } + + /** + * Builds the current [HistoryView] from the stack: one [HistoryStep] per entry (its label key and + * whether it is the saved baseline) plus the live cursor. The saved flag is by snapshot reference, so + * exactly one row is marked even when adjacent selection-only steps share a model instance. + * + * @return HistoryView The projected stack for the panel. + */ + private fun buildHistoryView(): HistoryView = + HistoryView( + steps = + history.steps.map { entry -> + HistoryStep(labelKey = entry.change?.labelKey, saved = entry.snapshot === savedSnapshot) + }, + cursor = history.cursorIndex, + ) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformAimEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformAimEdits.kt new file mode 100644 index 0000000..9004aa4 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformAimEdits.kt @@ -0,0 +1,360 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.channelGridsOf + +/* + * What "key this" and "unkey this" MEAN when the user asks for them - the intent layer over the concrete + * ops in KeyformTrackEdits / KeyformChannelEdits / KeyformGeometryEdits. + * + * Three questions live here: which parameter an edit writes on, whether it acts where the user pointed or + * where the pose stands, and whether a typed value becomes a pending edit or a static write. All three are + * editing SEMANTICS, so they belong in this module - a panel row, a keypress, and a lane context menu must + * answer them identically, and none of them is the right place to decide. + * + * This is also why these are not in :ui, where they started out: taking a Compose-side hover type put + * authoring rules in the UI module and made them untestable without a composition. A :ui caller now passes + * plain data - a track, an optional parameter id, and a KeyformAim - and keeps only the pointer bookkeeping + * that produced them. + */ + +/** + * Where a keyform edit is aimed: at a place the user named, or at the pose the rig is standing in. + * + * The distinction is not cosmetic. Pointing at a spot on a track is a statement about WHICH spot, so a key + * lands there rather than at the playhead; and pointing at a track but not at a key means "that key, of + * which there is none", which must remove nothing rather than falling back to the pose and destroying a key + * the user never pointed at. + */ +sealed interface KeyformAim { + /** No place was named, so the edit acts at the current pose - a property row, or a bare keypress. */ + data object Pose : KeyformAim + + /** + * A named place on the track's axis. + * + * @property Float position The parameter value pointed at. + * @property Int? keyIndex The ordinal of the key sitting there, or null when the pointer is between keys. + */ + data class Position(val position: Float, val keyIndex: Int?) : KeyformAim +} + +/** + * What a deferred keyform edit will do once the user picks the axis it writes on. + */ +enum class KeyformAction { + /** Insert a key ([captureKeyOnTrack]). */ + Capture, + + /** Remove a key ([removeKeyOnTrack]). */ + Remove, +} + +/** + * A keyform edit held back because more than one parameter is targeted and the user never named one. + * + * The linked-pad case: a 2D pad targets both its axes but reports only the HORIZONTAL one as active, so an + * unaimed edit would silently always write there and the vertical section would keep reading as unkeyed. + * Guessing is the one thing that must not happen - the wrong axis is authored work in the wrong place - so + * the edit parks here and the shell asks. + * + * Carries the whole edit rather than just the question, so answering it is a plain replay through the same + * entry point with the axis filled in; the UI decides nothing but which name was clicked. + * + * @property KeyformTrackRef track The track the edit was aimed at. + * @property KeyformAim aim Where on that track it lands. + * @property KeyformAction action Which edit is waiting. + * @property List candidates The targeted parameters to choose between, in model order. + * @property String? rowKey The keyform-sheet row the aim came from, carried so the replay can reconcile the + * key selection exactly as an unparked edit does; null when the aim came from somewhere with no sheet row. + */ +data class ParameterChoiceRequest( + val track: KeyformTrackRef, + val aim: KeyformAim, + val action: KeyformAction, + val candidates: List, + val rowKey: String? = null, +) + +/** + * The targeted parameters an unaimed edit would have to choose between, or null when there is no choice. + * + * Null - meaning "just proceed" - whenever the caller named a parameter (a sheet lane always does, and its + * lane is the answer), or fewer than two of the targeted ids still resolve in the model. + * + * @param ParameterId? parameterId The axis the caller named, or null. + * @return List? The candidates to ask about, or null to proceed without asking. + */ +private fun EditorSession.parameterChoiceFor(parameterId: ParameterId?): List? { + if (parameterId != null) { + return null + } + val targeted = parameterSelection.value.ids + if (targeted.size < 2) { + return null + } + // Model order, not set order: the prompt has to list the axes the way the panel does, and a Set's + // iteration order is an implementation detail the user would experience as the menu reshuffling. + val candidates = model.value.parameters.map { parameter -> parameter.id }.filter { id -> id in targeted } + return if (candidates.size < 2) null else candidates +} + +/** + * Answers the pending [ParameterChoiceRequest] by writing on [parameterId], replaying the parked edit. + * + * Replayed through the ordinary entry point with the axis now named, so the answered edit takes exactly the + * path an aimed one takes - there is no second implementation of what an insert or a removal means. + * + * @param ParameterId parameterId The axis the user picked. + */ +fun EditorSession.resolveParameterChoice(parameterId: ParameterId) { + val request = pendingParameterChoice.value ?: return + cancelParameterChoice() + when (request.action) { + KeyformAction.Capture -> captureKeyOnTrack(request.track, parameterId, request.aim, request.rowKey) + KeyformAction.Remove -> removeKeyOnTrack(request.track, parameterId, request.aim, request.rowKey) + } +} + +/** + * Captures a key on [track] at [aim], keyed on the parameter the edit writes on. + * + * An aimed capture inserts a shape-preserving key at that position, so it holds whatever the track already + * evaluates to there. A capture at the pose stores the PENDING unkeyed edit when there is one, else the + * channel's current evaluated value - so an insert after typing stores what was typed, and an insert with + * nothing edited pins what is already on screen (Blender's behaviour, and how a rigger anchors a pose before + * moving on). + * + * Refuses with a notice rather than silently doing nothing when no parameter resolves, since that is a thing + * the user can fix. + * + * When no parameter is named and more than one is targeted (a linked pad), the edit parks as a + * [ParameterChoiceRequest] instead of writing on whichever axis happens to be active. + * + * Reconciles the keyform sheet's key selection when [rowKey] names the row the aim came from, exactly as + * [removeKeyOnTrack] does: the new key renumbers every key at or above where it lands, so a selection on + * one of those keys must shift up by one to keep naming the same key. + * + * @param KeyformTrackRef track The track to key. + * @param ParameterId? parameterId The axis to key on, or null to use the session's targeted parameter. + * @param KeyformAim aim Where the key lands. + * @param String? rowKey The sheet row the aim came from, or null when it came from somewhere without one. + */ +fun EditorSession.captureKeyOnTrack( + track: KeyformTrackRef, + parameterId: ParameterId?, + aim: KeyformAim, + rowKey: String? = null, +) { + parameterChoiceFor(parameterId)?.let { candidates -> + requestParameterChoice(ParameterChoiceRequest(track, aim, KeyformAction.Capture, candidates, rowKey)) + return + } + val parameter = keyformParameterFor(parameterId) ?: return + // An aimed capture keys where it was pointed; every other kind keys at the pose. Resolved once, because + // it is both where the key goes and what the ordinal query has to be asked about. + val keyPosition = + when (aim) { + is KeyformAim.Position -> aim.position + is KeyformAim.Pose -> pose.value[parameter.id] ?: parameter.default + } + val inserted = insertedKeyRef(track, parameter, keyPosition, rowKey) + if (aim is KeyformAim.Position) { + insertingKey(inserted) { insertTrackKeyAt(track, parameter, aim.position) } + return + } + when (track) { + is KeyformTrackRef.Channel -> { + val target = track.target + // Resolved before the wrap, because a channel with no value to capture must leave the selection + // alone rather than reconcile it around an edit that never happens. + val value = pendingChannelEdits.value[target] ?: model.value.channelValueAt(target, pose.value) ?: return + insertingKey(inserted) { + // Retired BEFORE the capture records its step, exactly as the unkeyed branch of editKeyedChannel + // does below and for the same reason: a snapshot defaults every field to live state, so clearing + // afterwards leaves the consumed value inside the step that consumed it - and redo then re-shows + // the uncommitted-edit warning over the very key that now stores the value. + // + // Only THIS target's pending edit is consumed; the pose did not move, so any other target's typed + // value is still the value its user chose and must survive for its own capture. + clearPendingChannelEdit(target) + captureChannelKey(target, parameter, value) + } + } + + // Geometry: bind the targeted parameter when needed, then capture the form already on screen - + // the same loop channels use, so a warp / drawable / rotation can be keyed on ANY parameter. + is KeyformTrackRef.Geometry -> + insertingKey(inserted) { + captureGeometryKey(track.owner, parameter) + } + } +} + +/** + * The [TrackKeyRef] a key inserted at [position] would take, or null when nothing new is added. + * + * Null whenever the selection cannot be affected: the caller named no sheet row, or a key already sits at + * [position] so the capture overwrites a cell rather than renumbering the axis. + * + * @param KeyformTrackRef track The track the key goes on. + * @param Parameter parameter The parameter whose axis it goes on. + * @param Float position The new key's parameter value. + * @param String? rowKey The sheet row the aim came from, or null when it came from somewhere without one. + * @return TrackKeyRef? The new key's ref, or null when no ordinal renumbers. + */ +private fun EditorSession.insertedKeyRef( + track: KeyformTrackRef, + parameter: Parameter, + position: Float, + rowKey: String?, +): TrackKeyRef? { + if (rowKey == null) { + return null + } + val keyIndex = model.value.trackKeyIndexAfterInsert(track, parameter, position) + return if (keyIndex < 0) null else TrackKeyRef(parameter.id, rowKey, keyIndex) +} + +/** + * Removes the key [aim] names from [track], on the parameter the edit writes on. + * + * Either way the key is an ORDINAL, and either way aiming at nothing removes nothing: picking "the nearest + * key" would be a guess at which one the user meant, and a wrong guess silently destroys authored work. + * + * Parks as a [ParameterChoiceRequest] on an ambiguous target, exactly as [captureKeyOnTrack] does - a + * removal aimed at the wrong axis destroys authored work, so it is the LAST thing to guess at. + * + * Reconciles the keyform sheet's key selection when [rowKey] names the row the aim came from - the removal + * renumbers the keys above it, so a selection left alone would end up naming the neighbour. Done HERE + * rather than at each caller because this is where the ordinal is finally resolved, and the aim may not + * carry one at all (a pose aim resolves it against the track). + * + * @param KeyformTrackRef track The track to unkey. + * @param ParameterId? parameterId The axis to remove from, or null to use the session's targeted parameter. + * @param KeyformAim aim The key pointed at, or [KeyformAim.Pose] to take the key the pose stands on. + * @param String? rowKey The sheet row the aim came from, or null when it came from somewhere without one. + */ +fun EditorSession.removeKeyOnTrack( + track: KeyformTrackRef, + parameterId: ParameterId?, + aim: KeyformAim, + rowKey: String? = null, +) { + parameterChoiceFor(parameterId)?.let { candidates -> + requestParameterChoice(ParameterChoiceRequest(track, aim, KeyformAction.Remove, candidates, rowKey)) + return + } + val parameter = keyformParameterFor(parameterId) ?: return + val keyIndex = + when (aim) { + is KeyformAim.Position -> aim.keyIndex ?: -1 + is KeyformAim.Pose -> model.value.trackKeyIndexAtPose(track, parameter, pose.value) + } + if (keyIndex < 0) { + return + } + // An empty set when the caller has no row to name, which leaves the selection untouched. + val removed = rowKey?.let { row -> setOf(TrackKeyRef(parameter.id, row, keyIndex)) }.orEmpty() + removingKeys(removed) { + removeTrackKeys(listOf(Triple(track, parameter, keyIndex))) + } +} + +/** + * Routes a keyable property's typed or picked [value]: a KEYED channel records it as a pending unkeyed + * edit, an unkeyed channel writes the static through [writeStatic]. + * + * The one place the rule lives. Writing the static of a keyed channel is shadowed by the track, so the + * edit appears to be silently rejected (the field snaps back and a following `I` captures the old track + * value); a pending edit previews in the viewport and waits for `I`. An unkeyed channel has no track to + * shadow it, so the static is the real store. Reimplementing this branch at each property row instead of + * calling here would let the two halves drift: some rows would apply the guard and others would silently + * skip it. + * + * Both branches record exactly one undo step, and both record it under [change] - which of the two a given + * channel takes depends on whether it happens to carry a track, which is not a distinction the rigger made. + * + * @param KeyableTarget target The entity and channel being edited. + * @param ChannelValue value The value the user chose. + * @param Change change The descriptor of this edit, used by whichever branch runs. + * @param Function writeStatic Writes the owner's static (the unkeyed path); the caller supplies it because + * which setter that is depends on the owner and channel. + */ +fun EditorSession.editKeyedChannel( + target: KeyableTarget, + value: ChannelValue, + change: Change, + writeStatic: () -> Unit, +) { + val keyed = model.value.channelGridsOf(target.owner)?.get(target.channel) != null + if (keyed) { + commitPendingChannelEdit(target, value, change) + } else { + // A scrub previews through the pending buffer even on an unkeyed channel (see previewChannelEdit), + // so the static write has to retire that preview - otherwise the stale pending value keeps + // shadowing the very static just committed, and the field stays tinted as an uncommitted edit. + clearPendingChannelEdit(target) + writeStatic() + } +} + +/** + * Previews [value] on [target] without committing anything - what a field reports while being scrubbed. + * + * Always the pending buffer, whether or not the channel is keyed. For a keyed channel that is already + * where a committed edit lands, so preview and commit coincide; for an unkeyed one it is the difference + * between a live viewport and a history entry per pointer frame. [editKeyedChannel] retires the preview + * when the gesture ends. + * + * @param KeyableTarget target The entity and channel being scrubbed. + * @param ChannelValue value The in-flight value. + */ +fun EditorSession.previewChannelEdit(target: KeyableTarget, value: ChannelValue) { + setPendingChannelEdit(target, value) +} + +/** + * The parameter a keyform edit writes on: [parameterId] when the caller named one (a sheet lane belongs to + * one section's axis, which need not be the selection's active member), else the targeted parameter. + * + * Emits the no-parameter notice and returns null when the named parameter no longer resolves. + * + * @param ParameterId? parameterId The axis the caller named, or null to fall back to the target. + * @return Parameter? The parameter to write on, or null. + */ +private fun EditorSession.keyformParameterFor(parameterId: ParameterId?): Parameter? { + val namedId = parameterId ?: return targetedParameter() + val parameter = model.value.parameters.firstOrNull { candidate -> candidate.id == namedId } + if (parameter == null) { + emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor) + } + return parameter +} + +/** + * The parameter a keyform edit falls back to - the active member of the session's parameter selection. + * + * Emits a notice and returns null when nothing is targeted, since an edit with no axis to write on has no + * sensible default: guessing a parameter would key the rig somewhere the user never looked. + * + * @return Parameter? The targeted parameter, or null. + */ +private fun EditorSession.targetedParameter(): Parameter? { + val activeId = parameterSelection.value.active + if (activeId == null) { + emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor) + return null + } + val parameter = model.value.parameters.firstOrNull { candidate -> candidate.id == activeId } + if (parameter == null) { + // A dangling id (a stale snapshot's target for a parameter since deleted) is as unfixable-by-waiting + // as no target at all, so it gets the same notice rather than a silent no-op. + emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor) + } + return parameter +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformChannelEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformChannelEdits.kt new file mode 100644 index 0000000..ad8fe46 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformChannelEdits.kt @@ -0,0 +1,401 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.flagAt +import org.umamo.runtime.eval.gridCornersHolding +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.keyform.ChannelValueInterpolator +import org.umamo.runtime.keyform.axisIndexOf +import org.umamo.runtime.keyform.keyIndexAt +import org.umamo.runtime.keyform.withAxisSeeded +import org.umamo.runtime.keyform.withFormCaptured +import org.umamo.runtime.keyform.withKeyMoved +import org.umamo.runtime.keyform.withKeyRemoved +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ChannelValueKind +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.channelGridsOf +import org.umamo.runtime.model.withDerivedRenderRoot + +/* + * Keyform authoring for the SCALAR and COLOR channels - opacity, the multiply / screen tints, draw order, + * glue intensity. Geometry keyframing is deliberately not here: it needs the deformer-chain inverse under + * a pose, which is a separate problem, while these channels need no inverse at all. That is exactly why + * they come first - the whole authoring loop (bind, capture, remove, undo, and the sheet reflecting it) + * gets proven on the easy case before the hard one raises its own questions. + * + * Two rules from the grid algebra shape everything below, both forced by how the evaluator brackets a pose: + * a newly bound axis SPANS the parameter's range (an axis that does not reach the ends leaves the channel + * falling back to its static there), and removal COLLAPSES below two keys (a one-key axis resolves only + * within EPS_KEY of that key). + */ + +/** + * This owner's STATIC value for [channel] - what the channel reads when it has no track. + * + * The seed value for a first bind: binding replicates the entity's present look across the new axis, so + * that binding alone never changes the render, only the capture that follows does. + */ +private fun PuppetModel.staticValueOf(owner: KeyformOwner, channel: FormChannel): ChannelValue? = + when (owner) { + is KeyformOwner.Drawable -> + drawables.firstOrNull { it.id == owner.id }?.let { drawable -> + when (channel) { + FormChannel.DRAW_ORDER -> ChannelValue.Scalar(drawable.drawOrder) + FormChannel.OPACITY -> ChannelValue.Scalar(drawable.opacity) + FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(drawable.multiplyColor) + FormChannel.SCREEN_COLOR -> ChannelValue.Color(drawable.screenColor) + else -> null + } + } + + is KeyformOwner.Part -> + parts.firstOrNull { it.id == owner.id }?.let { part -> + when (channel) { + FormChannel.DRAW_ORDER -> ChannelValue.Scalar(part.drawOrder.toFloat()) + FormChannel.OPACITY -> ChannelValue.Scalar(part.composite.opacity) + FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(part.composite.multiplyColor) + FormChannel.SCREEN_COLOR -> ChannelValue.Color(part.composite.screenColor) + else -> null + } + } + + is KeyformOwner.Deformer -> + deformers.firstOrNull { it.id == owner.id }?.let { deformer -> + when (deformer) { + is Deformer.Warp -> + when (channel) { + FormChannel.OPACITY -> ChannelValue.Scalar(deformer.opacity) + FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(deformer.multiplyColor) + FormChannel.SCREEN_COLOR -> ChannelValue.Color(deformer.screenColor) + else -> null + } + + is Deformer.Rotation -> + when (channel) { + FormChannel.OPACITY -> ChannelValue.Scalar(deformer.opacity) + FormChannel.MULTIPLY_COLOR -> ChannelValue.Color(deformer.multiplyColor) + FormChannel.SCREEN_COLOR -> ChannelValue.Color(deformer.screenColor) + FormChannel.FLIP_X -> ChannelValue.Flag(deformer.flipX) + FormChannel.FLIP_Y -> ChannelValue.Flag(deformer.flipY) + else -> null + } + } + } + + is KeyformOwner.Glue -> + glues.firstOrNull { it.meshA == owner.meshA && it.meshB == owner.meshB }?.let { glue -> + if (channel == FormChannel.GLUE_INTENSITY) ChannelValue.Scalar(glue.intensity) else null + } + } + +/** + * This model with [owner]'s channel tracks replaced. + * + * A part edit re-derives the render root, because the render tree carries its own copy of each part's + * tracks and would otherwise keep evaluating the pre-edit ones. + */ +private fun PuppetModel.withChannelGrids(owner: KeyformOwner, channelGrids: ChannelGrids): PuppetModel = + when (owner) { + is KeyformOwner.Drawable -> + copy(drawables = drawables.map { if (it.id == owner.id) it.copy(channelGrids = channelGrids) else it }) + + is KeyformOwner.Part -> + copy(parts = parts.map { if (it.id == owner.id) it.copy(channelGrids = channelGrids) else it }) + .withDerivedRenderRoot() + + is KeyformOwner.Deformer -> + copy( + deformers = + deformers.map { deformer -> + if (deformer.id != owner.id) { + deformer + } else { + when (deformer) { + is Deformer.Warp -> deformer.copy(channelGrids = channelGrids) + is Deformer.Rotation -> deformer.copy(channelGrids = channelGrids) + } + } + }, + ) + + is KeyformOwner.Glue -> + copy( + glues = + glues.map { glue -> + if (glue.meshA == owner.meshA && glue.meshB == owner.meshB) { + glue.copy(channelGrids = channelGrids) + } else { + glue + } + }, + ) + } + +/** Whether [value] is the kind [channel] stores - a guard against writing a color into a scalar track. */ +private fun FormChannel.accepts(value: ChannelValue): Boolean = valueKind == value.valueKind + +/** + * This model with [value] captured on [target]'s channel at [pose], keyed on [parameter]. + * + * The whole authoring gesture in one op: + * + * - An UNBOUND channel is bound first - a new axis spanning the parameter's min / default / max holding + * the entity's current static value, so binding alone changes nothing on screen. + * - A channel already keyed on OTHER parameters gains this one as an additional axis, its existing cells + * replicated across it, so the motion it already had is preserved. + * - The capture then inserts a key at the pose if one is not already there (filling the new slice by + * interpolation, so every other pose is unchanged) and writes [value] into the single cell the pose now + * sits exactly on. + * + * Because the capture always lands on a key, the write is a plain assignment - there is never a blend to + * invert, which is why these channels need no math the geometry path is still missing. + * + * Returns the same instance when the entity is missing, the channel does not belong to it, [value] is the + * wrong kind for the channel, or the grid algebra refused the reshape (a degenerate parameter range). + * + * @param KeyableTarget target The entity and channel to key. + * @param Parameter parameter The parameter to key on. + * @param Pose pose The current pose; the capture lands at its value on [parameter]. + * @param ChannelValue value The value to store. + * @return PuppetModel The model with the key captured, or this on a refusal. + */ +fun PuppetModel.withChannelKeyCaptured( + target: KeyableTarget, + parameter: Parameter, + pose: Pose, + value: ChannelValue, +): PuppetModel { + if (!target.channel.accepts(value)) { + return this + } + val grids = channelGridsOf(target.owner) ?: return this + val staticValue = staticValueOf(target.owner, target.channel) ?: return this + val defaults = parameters.associate { it.id to it.default } + val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: defaults[id] ?: 0f } + + val existing = grids[target.channel] + val bound: KeyformGrid = + if (existing == null || existing.axisIndexOf(parameter.id) < 0) { + existing.withAxisSeeded(parameter, staticValue) ?: return this + } else { + existing + } + // Compared against BOUND, not existing: a capture that refuses after a fresh seed must refuse the whole + // op - committing the bare axis bind would discard the user's value while the channel reads as keyed. + val captured = bound.withFormCaptured(poseValue, value, ChannelValueInterpolator) + if (captured === bound) { + return this + } + return withChannelGrids(target.owner, ChannelGrids(grids.gridsByChannel + (target.channel to captured))) +} + +/** + * This model with the key at [pose] removed from [target]'s channel on [parameter]'s axis. + * + * Removing below two keys collapses the axis entirely - a one-key axis would resolve only within EPS_KEY of + * that key and leave the channel on its static everywhere else, which reads as the key having done + * something bizarre rather than having been removed. Collapsing the last axis drops the track, and the + * channel returns to its owner's static value. + * + * Returns the same instance when nothing is keyed there - in particular when the pose is not ON a key, + * since removing "the nearest key" to a pose between two of them is a guess, not an instruction. + * + * @param KeyableTarget target The entity and channel. + * @param Parameter parameter The parameter whose axis to remove from. + * @param Pose pose The current pose; the key at its value is the one removed. + * @return PuppetModel The model with the key removed, or this on a refusal. + */ +fun PuppetModel.withChannelKeyRemoved(target: KeyableTarget, parameter: Parameter, pose: Pose): PuppetModel { + val track = channelGridsOf(target.owner)?.get(target.channel) ?: return this + val scrubValue = pose[parameter.id] ?: parameters.firstOrNull { it.id == parameter.id }?.default ?: 0f + val keyIndex = track.keyIndexAt(parameter.id, scrubValue) + if (keyIndex < 0) { + return this + } + // One removal body: the pose-addressed remove is the ordinal-addressed one after resolving the key, + // so the collapse-below-two-keys rule cannot fork between the two paths. + return withChannelKeyRemovedAt(target, parameter, keyIndex) +} + +/** + * The value [target]'s channel currently evaluates to at [pose], or null when the entity or channel does + * not exist. + * + * What an insert captures when nothing is being edited: pinning the value already on screen, which is what + * Blender's `I` does and how a rigger anchors a pose before moving on. Reads through the same channel + * sampling the renderer uses, so the key lands on exactly what was displayed rather than on a value + * recomputed by a second code path. + * + * @param KeyableTarget target The entity and channel. + * @param Pose pose The pose to sample at. + * @return ChannelValue? The current value, or null when the target does not resolve. + */ +fun PuppetModel.channelValueAt(target: KeyableTarget, pose: Pose): ChannelValue? { + val grids = channelGridsOf(target.owner) ?: return null + val staticValue = staticValueOf(target.owner, target.channel) ?: return null + // No defaults map: this runs per keyable row per recomposition, a track has at most a few axes, and + // the pose usually answers - the per-miss linear scan beats an every-call full-map build. + val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: parameters.firstOrNull { it.id == id }?.default ?: 0f } + return when (staticValue) { + is ChannelValue.Scalar -> ChannelValue.Scalar(grids.scalarAt(target.channel, staticValue.value, poseValue)) + is ChannelValue.Color -> ChannelValue.Color(grids.colorAt(target.channel, staticValue.color, poseValue)) + is ChannelValue.Flag -> ChannelValue.Flag(grids.flagAt(target.channel, staticValue.flag, poseValue)) + } +} + +/** + * [channelValueAt] with out-of-span hold: past the track's first/last key the nearest end value is used + * instead of the owner's static. Insert uses this so a key after the last copies that last authored + * value; the property-panel read stays on [channelValueAt] so it still matches the renderer. + * + * @param KeyableTarget target The entity and channel. + * @param Pose pose The pose to sample at. + * @return ChannelValue? The held value, or null when the target does not resolve. + */ +fun PuppetModel.channelValueAtHolding(target: KeyableTarget, pose: Pose): ChannelValue? { + val grids = channelGridsOf(target.owner) ?: return null + val staticValue = staticValueOf(target.owner, target.channel) ?: return null + val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: parameters.firstOrNull { it.id == id }?.default ?: 0f } + val grid = grids[target.channel] ?: return staticValue + val corners = gridCornersHolding(grid, poseValue) ?: return staticValue + val cells = cellsByLinearIndex(grid) + return when (staticValue) { + is ChannelValue.Scalar -> { + var total = 0f + for (corner in corners) { + val value = (cells[corner.linearIndex]?.form as? ChannelValue.Scalar)?.value ?: continue + total += corner.weight * value + } + ChannelValue.Scalar(total) + } + is ChannelValue.Color -> { + var red = 0f + var green = 0f + var blue = 0f + for (corner in corners) { + val color = (cells[corner.linearIndex]?.form as? ChannelValue.Color)?.color ?: continue + red += corner.weight * color.red + green += corner.weight * color.green + blue += corner.weight * color.blue + } + ChannelValue.Color(ColorRgb(red, green, blue)) + } + is ChannelValue.Flag -> { + val floorCorner = corners.firstOrNull() ?: return staticValue + ChannelValue.Flag((cells[floorCorner.linearIndex]?.form as? ChannelValue.Flag)?.flag ?: staticValue.flag) + } + } +} + +/** + * This model with the key at [fromValue] on [target]'s channel moved to [toValue]. + * + * The sheet's drag gesture: the key keeps whatever it holds and only changes where on the parameter it + * applies. Identified by ORDINAL, not by its current value - keys a hair apart are legal, and resolving a + * value back to a key picks whichever is nearer, which silently moves the wrong one. + * + * @param KeyableTarget target The entity and channel. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's ordinal on that axis. + * @param Float toValue The requested new position. + * @return PuppetModel The model with the key moved, or this on a refusal. + */ +fun PuppetModel.withChannelKeyMoved( + target: KeyableTarget, + parameter: Parameter, + keyIndex: Int, + toValue: Float, +): PuppetModel { + val grids = channelGridsOf(target.owner) ?: return this + val track = grids[target.channel] ?: return this + val moved = track.withKeyMoved(parameter.id, keyIndex, toValue) + if (moved === track) { + return this + } + return withChannelGrids(target.owner, ChannelGrids(grids.gridsByChannel + (target.channel to moved))) +} + +/** + * This model with key [keyIndex] removed from [target]'s channel on [parameter]'s axis. + * + * By ordinal, for the same reason [withChannelKeyMoved] is: the sheet knows exactly which mark was + * clicked and must not re-derive it from a value two keys could answer to. + * + * @param KeyableTarget target The entity and channel. + * @param Parameter parameter The parameter whose axis to remove from. + * @param Int keyIndex The key's ordinal on that axis. + * @return PuppetModel The model with the key removed, or this on a refusal. + */ +fun PuppetModel.withChannelKeyRemovedAt(target: KeyableTarget, parameter: Parameter, keyIndex: Int): PuppetModel { + val grids = channelGridsOf(target.owner) ?: return this + val track = grids[target.channel] ?: return this + val reduced = track.withKeyRemoved(parameter.id, keyIndex) + if (reduced === track) { + return this + } + val remaining = + if (reduced == null) { + grids.gridsByChannel - target.channel + } else { + grids.gridsByChannel + (target.channel to reduced) + } + return withChannelGrids(target.owner, ChannelGrids(remaining)) +} + +/** + * Whether [target]'s channel is keyed on [parameter] at all - what the properties panel's keyed indicator + * and the `I` / `Alt+I` availability read. + * + * @param KeyableTarget target The entity and channel. + * @param ParameterId parameterId The parameter to look for. + * @return Boolean True when a track exists and keys on that parameter. + */ +fun PuppetModel.isChannelKeyedOn(target: KeyableTarget, parameterId: ParameterId): Boolean { + val track = channelGridsOf(target.owner)?.get(target.channel) ?: return false + return track.axisIndexOf(parameterId) >= 0 +} + +/** + * Captures [value] on [target] at the current pose, keyed on [parameter], as one undo step. + * + * @param KeyableTarget target The entity and channel to key. + * @param Parameter parameter The parameter to key on. + * @param ChannelValue value The value to store. + */ +fun EditorSession.captureChannelKey(target: KeyableTarget, parameter: Parameter, value: ChannelValue) { + mutate(KeyformChange.InsertKey(target.channel)) { model -> + model.withChannelKeyCaptured(target, parameter, pose.value, value) + } +} + +/** + * Removes the key at the current pose from [target]'s channel on [parameter], as one undo step. + * + * @param KeyableTarget target The entity and channel. + * @param Parameter parameter The parameter whose axis to remove from. + */ +fun EditorSession.removeChannelKey(target: KeyableTarget, parameter: Parameter) { + mutate(KeyformChange.DeleteKey(target.channel)) { model -> + model.withChannelKeyRemoved(target, parameter, pose.value) + } +} + +/** The kind guard's counterpart for callers building a value: the neutral value of [channel]'s kind. */ +internal fun FormChannel.neutralValue(): ChannelValue = + when (valueKind) { + ChannelValueKind.SCALAR -> ChannelValue.Scalar(0f) + ChannelValueKind.COLOR -> ChannelValue.Color(org.umamo.runtime.model.ColorRgb(0f, 0f, 0f)) + ChannelValueKind.FLAG -> ChannelValue.Flag(false) + } \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformGeometryEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformGeometryEdits.kt new file mode 100644 index 0000000..9c1ee70 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformGeometryEdits.kt @@ -0,0 +1,627 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.eval.gridCornersHolding +import org.umamo.runtime.keyform.FormInterpolator +import org.umamo.runtime.keyform.MeshDeltaInterpolator +import org.umamo.runtime.keyform.RotationPivotInterpolator +import org.umamo.runtime.keyform.WarpLatticeInterpolator +import org.umamo.runtime.keyform.axisIndexOf +import org.umamo.runtime.keyform.withAxisSeeded +import org.umamo.runtime.keyform.withFormCaptured +import org.umamo.runtime.keyform.withKeyInserted +import org.umamo.runtime.keyform.withKeyMoved +import org.umamo.runtime.keyform.withKeyRemoved +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm + +/* + * Geometry-track keyform authoring: bind an owner to a parameter, capture a form at a pose, and move / + * insert / remove key POSITIONS. + * + * Deliberately separate from KeyformChannelEdits: a channel is addressed by (owner, channel) and its cells + * hold a ChannelValue, while geometry is a privileged per-owner field whose cell type differs by owner + * (MeshDeltaForm / WarpLatticeForm / RotationPivotForm). One generic op cannot span both without erasing + * that distinction, and erasing it is exactly what would let a scalar track reach buildDeltaTexels. + * + * Binding and capturing a form mirror the channel path (seed the axis, then withFormCaptured). Interactive + * lattice / mesh sculpting that PRODUCES a new form still lives with the viewport; this file stores whatever + * form the caller (or the pose sample) already holds. + */ + +/** + * Whether [owner] has a geometry track keyed on [parameterId] at all. + * + * @param KeyformOwner owner The entity. + * @param ParameterId parameterId The parameter to look for. + * @return Boolean True when a geometry grid exists and keys on that parameter. + */ +fun PuppetModel.isGeometryKeyedOn(owner: KeyformOwner, parameterId: ParameterId): Boolean = + // Through geometryGridOf, the one owner dispatch - a second copy of the when let the keyed indicator + // and the actual edit ops disagree about a new owner kind. + (geometryGridOf(owner)?.axisIndexOf(parameterId) ?: -1) >= 0 + +/** + * [owner]'s geometry grid, or null when that kind of entity carries none. + * + * The grid rather than one axis, so callers can use the grid's own tolerance-aware lookups instead of + * re-deriving the evaluator's epsilon beside them. + * + * @param KeyformOwner owner The entity. + * @return KeyformGrid? Its geometry grid, or null. + */ +fun PuppetModel.geometryGridOf(owner: KeyformOwner): KeyformGrid<*>? = + when (owner) { + is KeyformOwner.Drawable -> drawableGeometry(owner) + is KeyformOwner.Deformer -> + when (val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id }) { + is Deformer.Warp -> deformer.geometryGrid + is Deformer.Rotation -> deformer.geometryGrid + null -> null + } + // A part is organizational and a glue welds two meshes; neither carries geometry of its own. + is KeyformOwner.Part, is KeyformOwner.Glue -> null + } + +/** + * This model with [owner]'s geometry captured at [pose] on [parameter] - bind the axis if needed, then + * write the form the owner currently evaluates to (or a rest-zero mesh delta for an unkeyed drawable). + * + * The geometry twin of [withChannelKeyCaptured]: seeding alone never changes the render, and a capture at + * the pose pins whatever is already on screen so a later sculpt (or a sheet insert at another value) has a + * handle to edit from. Refused when the owner cannot supply a form to seed with - an unkeyed warp has no + * rest lattice, so there is nothing to bind. + * + * @param KeyformOwner owner The entity whose geometry track to key. + * @param Parameter parameter The parameter to key on. + * @param Pose pose The pose the capture lands at. + * @return PuppetModel The model with the capture written, or this on a refusal. + */ +fun PuppetModel.withGeometryKeyCaptured(owner: KeyformOwner, parameter: Parameter, pose: Pose): PuppetModel { + val defaults = parameters.associate { it.id to it.default } + val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: defaults[id] ?: 0f } + return when (owner) { + is KeyformOwner.Drawable -> { + val drawable = drawables.firstOrNull { candidate -> candidate.id == owner.id } ?: return this + val form = + meshDeltasAt(drawable.geometryGrid, poseValue) + ?: drawable.mesh?.let { mesh -> MeshDeltaForm(FloatArray(mesh.positions.size)) } + ?: return this + captureDrawableGeometry(owner, parameter, poseValue, form) + } + + is KeyformOwner.Deformer -> + when (val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id }) { + is Deformer.Warp -> { + val points = warpControlPointsHolding(deformer.geometryGrid, poseValue) ?: return this + captureWarpGeometry(owner, parameter, poseValue, WarpLatticeForm(points.copyOf())) + } + + is Deformer.Rotation -> { + val form = rotationFormHolding(deformer.geometryGrid, poseValue) ?: return this + captureRotationGeometry(owner, parameter, poseValue, form) + } + + null -> this + } + + is KeyformOwner.Part, is KeyformOwner.Glue -> this + } +} + +/** + * Mesh-delta form sampled at [poseValue] with out-of-span hold (nearest end key), or null when the grid + * is absent. Authoring capture uses hold so a key past the last copies that last form, not rest-zero. + * + * @param KeyformGrid? grid The drawable's geometry grid. + * @param Function poseValue Value per parameter id. + * @return MeshDeltaForm? The blended deltas, or null. + */ +private fun meshDeltasAt(grid: KeyformGrid?, poseValue: (ParameterId) -> Float): MeshDeltaForm? { + if (grid == null) { + return null + } + val corners = gridCornersHolding(grid, poseValue) ?: return null + val byLinearIndex = cellsByLinearIndex(grid) + var blended: FloatArray? = null + for (corner in corners) { + val form = byLinearIndex[corner.linearIndex]?.form ?: continue + val target = blended ?: FloatArray(form.positionDeltas.size).also { blended = it } + for (componentIndex in target.indices) { + target[componentIndex] += corner.weight * form.positionDeltas[componentIndex] + } + } + return blended?.let(::MeshDeltaForm) +} + +/** + * Warp lattice sampled at [poseValue] with out-of-span hold, or null when the grid is absent. + * Authoring twin of [org.umamo.runtime.eval.warpControlPointsAt] - that one freezes out of range. + */ +private fun warpControlPointsHolding( + grid: KeyformGrid?, + poseValue: (ParameterId) -> Float, +): FloatArray? { + if (grid == null) { + return null + } + val corners = gridCornersHolding(grid, poseValue) ?: return null + val byLinearIndex = cellsByLinearIndex(grid) + var blended: FloatArray? = null + for (corner in corners) { + val form = byLinearIndex[corner.linearIndex]?.form ?: continue + val target = blended ?: FloatArray(form.controlPoints.size).also { blended = it } + for (componentIndex in target.indices) { + target[componentIndex] += corner.weight * form.controlPoints[componentIndex] + } + } + return blended +} + +/** + * Rotation form sampled at [poseValue] with out-of-span hold, or null when the grid is absent. + * Authoring twin of [org.umamo.runtime.eval.rotationFormAt] - that one freezes out of range. + */ +private fun rotationFormHolding( + grid: KeyformGrid?, + poseValue: (ParameterId) -> Float, +): RotationPivotForm? { + if (grid == null) { + return null + } + val corners = gridCornersHolding(grid, poseValue) ?: return null + val byLinearIndex = cellsByLinearIndex(grid) + var originX = 0f + var originY = 0f + var angle = 0f + var scale = 0f + var resolvedAnyCell = false + for (corner in corners) { + val form = byLinearIndex[corner.linearIndex]?.form ?: continue + resolvedAnyCell = true + originX += corner.weight * form.originX + originY += corner.weight * form.originY + angle += corner.weight * form.angle + scale += corner.weight * form.scale + } + if (!resolvedAnyCell) { + return null + } + return RotationPivotForm(originX, originY, angle, scale) +} + +/** + * Seeds / captures a drawable mesh-delta grid on [parameter] at [poseValue]. + * + * @param KeyformOwner.Drawable owner The drawable. + * @param Parameter parameter The parameter to key on. + * @param Function poseValue The pose sampler. + * @param MeshDeltaForm form The form to store at the pose. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.captureDrawableGeometry( + owner: KeyformOwner.Drawable, + parameter: Parameter, + poseValue: (ParameterId) -> Float, + form: MeshDeltaForm, +): PuppetModel { + val existing = drawableGeometry(owner) + val bound = existing.withAxisSeeded(parameter, form) ?: return this + val captured = bound.withFormCaptured(poseValue, form, MeshDeltaInterpolator) + if (captured === bound && existing != null && existing.axisIndexOf(parameter.id) >= 0) { + // Already keyed on this parameter and the cell already holds [form] - nothing to record. + return this + } + if (captured === existing) { + return this + } + return copy( + drawables = + drawables.map { candidate -> + if (candidate.id == owner.id) candidate.copy(geometryGrid = captured) else candidate + }, + ) +} + +/** + * This model with [owner]'s warp lattice written as [form] at [pose] on [parameter] - binds the axis when + * needed, then overwrites the cell the pose lands in. The viewport lattice drag commits through here so a + * sculpted form becomes a key on whatever parameter the rigger targeted. + * + * @param KeyformOwner.Deformer owner The warp. + * @param Parameter parameter The parameter to key on. + * @param Pose pose The pose the form is authored at. + * @param WarpLatticeForm form The lattice control points to store (parent-local, interleaved x,y). + * @return PuppetModel The model with the form written, or this on a refusal. + */ +fun PuppetModel.withWarpLatticeCaptured( + owner: KeyformOwner.Deformer, + parameter: Parameter, + pose: Pose, + form: WarpLatticeForm, +): PuppetModel { + val defaults = parameters.associate { it.id to it.default } + val poseValue: (ParameterId) -> Float = { id -> pose[id] ?: defaults[id] ?: 0f } + return captureWarpGeometry(owner, parameter, poseValue, form) +} + +/** + * Seeds / captures a warp lattice grid on [parameter] at [poseValue]. + * + * @param KeyformOwner.Deformer owner The deformer id wrapper. + * @param Parameter parameter The parameter to key on. + * @param Function poseValue The pose sampler. + * @param WarpLatticeForm form The lattice to store at the pose. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.captureWarpGeometry( + owner: KeyformOwner.Deformer, + parameter: Parameter, + poseValue: (ParameterId) -> Float, + form: WarpLatticeForm, +): PuppetModel { + val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id } as? Deformer.Warp ?: return this + val existing = deformer.geometryGrid + val bound = existing.withAxisSeeded(parameter, form) ?: return this + val captured = bound.withFormCaptured(poseValue, form, WarpLatticeInterpolator) + if (captured === bound && existing != null && existing.axisIndexOf(parameter.id) >= 0) { + return this + } + if (captured === existing) { + return this + } + return copy( + deformers = + deformers.map { candidate -> + if (candidate.id == owner.id && candidate is Deformer.Warp) { + candidate.copy(geometryGrid = captured) + } else { + candidate + } + }, + ) +} + +/** + * Seeds / captures a rotation pivot grid on [parameter] at [poseValue]. + * + * @param KeyformOwner.Deformer owner The deformer id wrapper. + * @param Parameter parameter The parameter to key on. + * @param Function poseValue The pose sampler. + * @param RotationPivotForm form The pivot to store at the pose. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.captureRotationGeometry( + owner: KeyformOwner.Deformer, + parameter: Parameter, + poseValue: (ParameterId) -> Float, + form: RotationPivotForm, +): PuppetModel { + val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id } as? Deformer.Rotation ?: return this + val existing = deformer.geometryGrid + val bound = existing.withAxisSeeded(parameter, form) ?: return this + val captured = bound.withFormCaptured(poseValue, form, RotationPivotInterpolator) + if (captured === bound && existing != null && existing.axisIndexOf(parameter.id) >= 0) { + return this + } + if (captured === existing) { + return this + } + return copy( + deformers = + deformers.map { candidate -> + if (candidate.id == owner.id && candidate is Deformer.Rotation) { + candidate.copy(geometryGrid = captured) + } else { + candidate + } + }, + ) +} + +/** + * This model with [owner]'s geometry key at [fromValue] moved to [toValue] on [parameter]'s axis. + * + * Moving a key changes only WHERE on the parameter its form applies - the cells are untouched - so it is + * safe for every owner, including a deformer with no rest lattice. The grid clamps at the neighbouring + * keys, so the stored destination can differ from the requested one. + * + * @param KeyformOwner owner The entity whose geometry track to edit. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's ordinal on that axis. + * @param Float toValue The requested new position. + * @return PuppetModel The model with the key moved, or this on a refusal. + */ +fun PuppetModel.withGeometryKeyMoved( + owner: KeyformOwner, + parameter: Parameter, + keyIndex: Int, + toValue: Float, +): PuppetModel = rewriteGeometry(owner) { grid -> grid.withKeyMoved(parameter.id, keyIndex, toValue) } + +/** + * This model with a key inserted at [position] on [owner]'s geometry track, holding the interpolated form. + * + * Shape-preserving: the new slice is the blend of its neighbours, the same operation the export refinement + * performs, so the deformation through the new key is the deformation that was already there. + * + * @param KeyformOwner owner The entity whose geometry track to edit. + * @param Parameter parameter The parameter whose axis to insert on. + * @param Float position The new key's parameter value. + * @return PuppetModel The model with the key inserted, or this on a refusal. + */ +fun PuppetModel.withGeometryKeyInserted(owner: KeyformOwner, parameter: Parameter, position: Float): PuppetModel = + rewriteGeometry(owner) { grid, interpolator -> grid.withKeyInserted(parameter.id, position, interpolator) } + +/** + * This model with [owner]'s geometry key at [position] removed from [parameter]'s axis. + * + * REFUSED for a deformer when the removal would collapse its last axis. A warp's control points live only + * in its keyform cells - there is no rest lattice - so an unkeyed deformer is hidden, and silently making a + * deformer and everything under it vanish is not an acceptable outcome of deleting one key. A drawable + * has a rest mesh, so the same removal there is safe and simply returns it to its rest shape. + * + * @param KeyformOwner owner The entity whose geometry track to edit. + * @param Parameter parameter The parameter whose axis to remove from. + * @param Int keyIndex The key's ordinal on that axis. + * @return PuppetModel The model with the key removed, or this on a refusal. + */ +fun PuppetModel.withGeometryKeyRemoved(owner: KeyformOwner, parameter: Parameter, keyIndex: Int): PuppetModel = + rewriteGeometryNullable(owner) { grid -> + val reduced = grid.withKeyRemoved(parameter.id, keyIndex) + if (reduced == null && owner is KeyformOwner.Deformer) grid else reduced + } + +/** + * Applies a same-shaped rewrite to whichever geometry grid [owner] has, keeping the form type. + * + * The generic form, for ops whose expression does not depend on what a cell holds. Returning the receiver + * means "no change", matching the algebra's own refusal convention. + * + * @param KeyformOwner owner The entity. + * @param Function rewrite Produces the new grid from the current one. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.rewriteGeometry( + owner: KeyformOwner, + rewrite: (KeyformGrid) -> KeyformGrid, +): PuppetModel = rewriteGeometryNullable(owner) { grid -> rewrite(grid) } + +/** + * Applies a rewrite that needs the grid's matching [FormInterpolator]. + * + * A second overload rather than a parameter on the first, because the interpolator's type is tied to the + * grid's and only the per-owner dispatch below knows both at once. + * + * @param KeyformOwner owner The entity. + * @param Function rewrite Produces the new grid from the current one and its interpolator. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.rewriteGeometry( + owner: KeyformOwner, + rewrite: (KeyformGrid, FormInterpolator) -> KeyformGrid, +): PuppetModel = + when (owner) { + is KeyformOwner.Drawable -> + replaceDrawableGeometry(owner) { grid -> rewrite(grid.asNothing(), MeshDeltaInterpolator.asNothing()) } + + is KeyformOwner.Deformer -> + replaceDeformerGeometry( + owner = owner, + onWarp = { grid -> rewrite(grid.asNothing(), WarpLatticeInterpolator.asNothing()) }, + onRotation = { grid -> rewrite(grid.asNothing(), RotationPivotInterpolator.asNothing()) }, + ) + + is KeyformOwner.Part, is KeyformOwner.Glue -> this + } + +/** + * The shared owner dispatch: reads [owner]'s geometry grid, asks [rewrite] for the new one, writes it back. + * + * One place that knows which entity kinds carry geometry, so adding one is a compile error here rather + * than a silently-ignored owner at three call sites. A null result drops the grid entirely (the entity + * becomes unkeyed); returning the receiver leaves the model untouched. + * + * @param KeyformOwner owner The entity. + * @param Function rewrite Produces the new grid, the same grid to refuse, or null to drop it. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.rewriteGeometryNullable( + owner: KeyformOwner, + rewrite: (KeyformGrid) -> KeyformGrid?, +): PuppetModel = + when (owner) { + is KeyformOwner.Drawable -> replaceDrawableGeometry(owner) { grid -> rewrite(grid.asNothing()) } + is KeyformOwner.Deformer -> + replaceDeformerGeometry( + owner = owner, + onWarp = { grid -> rewrite(grid.asNothing()) }, + onRotation = { grid -> rewrite(grid.asNothing()) }, + ) + + is KeyformOwner.Part, is KeyformOwner.Glue -> this + } + +/** This drawable's geometry grid, or null when the id is unknown or it has none. */ +private fun PuppetModel.drawableGeometry(owner: KeyformOwner.Drawable) = + drawables.firstOrNull { candidate -> candidate.id == owner.id }?.geometryGrid + +/** + * Runs [rewrite] over a drawable's mesh-delta grid and writes the result back. + * + * @param KeyformOwner.Drawable owner The drawable. + * @param Function rewrite Produces the new grid, the same one to refuse, or null to drop it. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.replaceDrawableGeometry( + owner: KeyformOwner.Drawable, + rewrite: (KeyformGrid) -> KeyformGrid?, +): PuppetModel { + @Suppress("UNCHECKED_CAST") + val grid = (drawableGeometry(owner) as KeyformGrid?) ?: return this + val rewritten = rewrite(grid) + if (rewritten === grid) { + return this + } + @Suppress("UNCHECKED_CAST") + return copy( + drawables = + drawables.map { candidate -> + if (candidate.id == owner.id) { + candidate.copy(geometryGrid = rewritten as KeyformGrid?) + } else { + candidate + } + }, + ) +} + +/** + * Runs the matching rewrite over a deformer's lattice or pivot grid and writes the result back. + * + * @param KeyformOwner.Deformer owner The deformer. + * @param Function onWarp The rewrite for a warp's lattice grid. + * @param Function onRotation The rewrite for a rotation's pivot grid. + * @return PuppetModel The rewritten model, or this. + */ +private fun PuppetModel.replaceDeformerGeometry( + owner: KeyformOwner.Deformer, + onWarp: (KeyformGrid) -> KeyformGrid?, + onRotation: (KeyformGrid) -> KeyformGrid?, +): PuppetModel { + val deformer = deformers.firstOrNull { candidate -> candidate.id == owner.id } ?: return this + + @Suppress("UNCHECKED_CAST") + val grid = + when (deformer) { + is Deformer.Warp -> deformer.geometryGrid as KeyformGrid? + is Deformer.Rotation -> deformer.geometryGrid as KeyformGrid? + } ?: return this + val rewritten = + when (deformer) { + is Deformer.Warp -> onWarp(grid) + is Deformer.Rotation -> onRotation(grid) + } + if (rewritten === grid) { + return this + } + @Suppress("UNCHECKED_CAST") + return copy( + deformers = + deformers.map { candidate -> + when { + candidate.id != owner.id -> candidate + candidate is Deformer.Warp -> + candidate.copy( + geometryGrid = rewritten as KeyformGrid?, + ) + + candidate is Deformer.Rotation -> + candidate.copy( + geometryGrid = rewritten as KeyformGrid?, + ) + + else -> candidate + } + }, + ) +} + +/** + * Views a grid as one over an unconstrained form type. + * + * The ops here move and remove KEYS and never touch a cell, so the form type is genuinely irrelevant to + * them - but Kotlin has no way to say "any grid" without a type argument. Confined to this file, and + * sound because [KeyformGrid] is immutable and no cell is ever read or written through the view. + */ +@Suppress("UNCHECKED_CAST") +private fun KeyformGrid.asNothing(): KeyformGrid = this as KeyformGrid + +/** The [asNothing] counterpart for an interpolator, for the same reason and with the same confinement. */ +@Suppress("UNCHECKED_CAST") +private fun FormInterpolator.asNothing(): FormInterpolator = this as FormInterpolator + +/** + * Moves [owner]'s geometry key at [fromValue] to [toValue], as one undo step. + * + * @param KeyformOwner owner The entity. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's ordinal on that axis. + * @param Float toValue The new position. + */ +fun EditorSession.moveGeometryKey(owner: KeyformOwner, parameter: Parameter, keyIndex: Int, toValue: Float) { + mutate(KeyformChange.MoveKey(null)) { model -> model.withGeometryKeyMoved(owner, parameter, keyIndex, toValue) } +} + +/** + * Inserts a shape-preserving key at [position] on [owner]'s geometry track, as one undo step. + * + * @param KeyformOwner owner The entity. + * @param Parameter parameter The parameter whose axis to insert on. + * @param Float position The new key's parameter value. + */ +fun EditorSession.insertGeometryKeyAt(owner: KeyformOwner, parameter: Parameter, position: Float) { + mutate(KeyformChange.InsertKey(null)) { model -> model.withGeometryKeyInserted(owner, parameter, position) } +} + +/** + * Captures [owner]'s current geometry at the live pose on [parameter], as one undo step - bind the axis + * when needed (any parameter, not a fixed set). + * + * @param KeyformOwner owner The entity. + * @param Parameter parameter The parameter to key on. + */ +fun EditorSession.captureGeometryKey(owner: KeyformOwner, parameter: Parameter) { + mutate(KeyformChange.InsertKey(null)) { model -> model.withGeometryKeyCaptured(owner, parameter, pose.value) } +} + +/** + * Writes [form] onto [owner]'s geometry at [pose], on the session's targeted parameter, as one undo + * step. Seeds the axis when the warp is not yet keyed on that parameter. + * + * Pass the LIVE scrub pose from the viewport ([LiveParams]) when committing from the lattice overlay - + * [EditorSession.pose] only moves when a scrub ends, so capturing against it mid-drag would land the + * form on the wrong key. + * + * Refuses (near-cursor notice) when nothing is targeted: guessing an axis would author work on a + * parameter the rigger never looked at. + * + * @param KeyformOwner.Deformer owner The warp. + * @param WarpLatticeForm form The lattice to store. + * @param Pose pose The pose the form is authored at (defaults to the session's committed pose). + */ +fun EditorSession.commitWarpLattice( + owner: KeyformOwner.Deformer, + form: WarpLatticeForm, + pose: Pose = this.pose.value, +) { + val activeId = parameterSelection.value.active + if (activeId == null) { + emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor) + return + } + val parameter = model.value.parameters.firstOrNull { candidate -> candidate.id == activeId } + if (parameter == null) { + emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor) + return + } + mutate(KeyformChange.InsertKey(null)) { model -> model.withWarpLatticeCaptured(owner, parameter, pose, form) } +} + +/** + * Removes [owner]'s geometry key at [position], as one undo step. + * + * @param KeyformOwner owner The entity. + * @param Parameter parameter The parameter whose axis to remove from. + * @param Int keyIndex The key's ordinal on that axis. + */ +fun EditorSession.removeGeometryKeyAt(owner: KeyformOwner, parameter: Parameter, keyIndex: Int) { + mutate(KeyformChange.DeleteKey(null)) { model -> model.withGeometryKeyRemoved(owner, parameter, keyIndex) } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformKeySelection.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformKeySelection.kt new file mode 100644 index 0000000..993a916 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformKeySelection.kt @@ -0,0 +1,119 @@ +package org.umamo.edit + +/* + * What a key REMOVAL does to the keyform sheet's key selection. + * + * Removing keys renumbers the ones above them: a [TrackKeyRef] names a row and an ordinal on that row's + * track, so a selection left untouched across a removal stops naming the key the user selected and instead + * names whichever key slides down onto the freed ordinal. + * + * The rule lives in :edit rather than in the sheet because it is a statement about what an edit MEANS, and + * three call sites need to agree on it - the aimed removal behind Alt+I and the lane menu, the selected-keys + * removal behind Delete, and the summary-mark removal. A [TrackKeyRef]'s row key is opaque here, which is + * all this needs: the algebra compares row keys, it never resolves one. + */ + +/** + * [current] with [removed] taken out and every ordinal that renumbers under them corrected. + * + * Only two kinds of ref are at risk from a removal: the removed keys themselves, and the LATER ordinals on + * the same row, which slide down one place per key removed below them. Everything else names exactly what + * it named before, so a mark the user had not selected must leave their selection untouched rather than + * clearing it wholesale. + * + * Matched on the parameter as well as the row because a linked pair renders one row under two sections, and + * a removal renumbers only the axis it happened on. + * + * @param Set current The selection before the removal. + * @param Set removed The keys the removal takes out. + * @return Set The selection that survives it. + */ +fun selectionAfterKeyRemoval(current: Set, removed: Set): Set { + if (removed.isEmpty()) { + return current + } + return current + .filterNot { key -> key in removed } + .map { key -> + val removedBelow = + removed.count { gone -> + gone.parameterId == key.parameterId && gone.rowKey == key.rowKey && gone.keyIndex < key.keyIndex + } + if (removedBelow == 0) key else key.copy(keyIndex = key.keyIndex - removedBelow) + }.toSet() +} + +/** + * [current] with every ordinal at or above [inserted] shifted up to make room for it. + * + * The mirror of [selectionAfterKeyRemoval]: an insert renumbers every key at or above where it lands, so a + * selection on one of those keys must shift up by one to keep naming the same key. A key below the + * insertion point already names the right key and is left untouched. + * + * @param Set current The selection before the insert. + * @param TrackKeyRef inserted The new key, at the ordinal it takes. + * @return Set The selection as it reads afterwards. + */ +fun selectionAfterKeyInsertion(current: Set, inserted: TrackKeyRef): Set = + current + .map { key -> + val renumbers = + key.parameterId == inserted.parameterId && + key.rowKey == inserted.rowKey && + key.keyIndex >= inserted.keyIndex + if (renumbers) key.copy(keyIndex = key.keyIndex + 1) else key + }.toSet() + +/** + * Runs [removeKeys] with the key selection re-pointed at what survives it, as ONE undo step. + * + * An empty [removed] is the caller saying it cannot name what it removed in sheet terms (a Properties row + * has no sheet row), and leaves the selection exactly as it was. + * + * @param Set removed The keys [removeKeys] takes out, in sheet-row terms. + * @param Function removeKeys The removal itself, which records its own step. + */ +fun EditorSession.removingKeys(removed: Set, removeKeys: () -> Unit) { + editingKeys({ current -> selectionAfterKeyRemoval(current, removed) }, removeKeys) +} + +/** + * Runs [insertKey] with the key selection re-pointed past the key it adds, as ONE undo step. + * + * A null [inserted] is the caller saying no key is added, or that it cannot name the new one in sheet terms, + * and leaves the selection exactly as it was. + * + * @param TrackKeyRef? inserted The new key at the ordinal it takes, or null when none is added. + * @param Function insertKey The insert itself, which records its own step. + */ +fun EditorSession.insertingKey(inserted: TrackKeyRef?, insertKey: () -> Unit) { + editingKeys({ current -> if (inserted == null) current else selectionAfterKeyInsertion(current, inserted) }, insertKey) +} + +/** + * Runs [edit] with the key selection put through [reconcile], as ONE undo step. + * + * STAGE, EDIT, CONFIRM (see [EditorSession.stageKeySelection]): the reconciled selection is staged first so + * the edit's own snapshot records it, and confirmed afterwards so it still reaches history when the edit + * declines to record anything. Staging it AFTER instead would leave every recorded step holding the + * pre-edit refs, so undoing back to one would point the selection at whichever keys had taken those ordinals. + * + * An edit that refuses is rolled back to the selection as it was, because nothing renumbered - the + * re-pointing would then be a shift with no edit under it. Measured by model identity, which the edit ops + * maintain: a refused edit hands back the instance it was given. + * + * @param Function reconcile The selection as it reads after [edit], given how it reads now. + * @param Function edit The edit itself, which records its own step. + */ +private fun EditorSession.editingKeys(reconcile: (Set) -> Set, edit: () -> Unit) { + val selectionBefore = keySelection.value + val reconciled = reconcile(selectionBefore) + val modelBeforeEdit = model.value + stageKeySelection(reconciled) + edit() + if (model.value === modelBeforeEdit) { + stageKeySelection(selectionBefore) + } else { + setKeySelection(reconciled) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformTrackEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformTrackEdits.kt new file mode 100644 index 0000000..fc9900e --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/KeyformTrackEdits.kt @@ -0,0 +1,520 @@ +package org.umamo.edit + +import org.umamo.runtime.keyform.keyDestinationFor +import org.umamo.runtime.keyform.keyIndexAfterInsert +import org.umamo.runtime.keyform.keyIndexAfterMove +import org.umamo.runtime.keyform.keyIndexAt +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.channelGridsOf + +/* + * The one dispatch from "a track the sheet is pointing at" to the channel or geometry implementation. + * + * The sheet applies the same three gestures - drag a key, insert one, remove one - to every row it draws, + * and which underlying op that becomes is not a decision the UI should be making twice per gesture. It is + * made once, here. + */ + +/** + * This model with [track]'s key at [fromValue] moved to [toValue] on [parameter]'s axis. + * + * @param KeyformTrackRef track The track to edit. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's ordinal on that axis. + * @param Float toValue The requested new position. + * @return PuppetModel The model with the key moved, or this on a refusal. + */ +fun PuppetModel.withTrackKeyMoved( + track: KeyformTrackRef, + parameter: Parameter, + keyIndex: Int, + toValue: Float, +): PuppetModel = + when (track) { + is KeyformTrackRef.Channel -> withChannelKeyMoved(track.target, parameter, keyIndex, toValue) + is KeyformTrackRef.Geometry -> withGeometryKeyMoved(track.owner, parameter, keyIndex, toValue) + } + +/** + * This model with a shape-preserving key inserted at [position] on [track]'s axis for [parameter]. + * + * @param KeyformTrackRef track The track to edit. + * @param Parameter parameter The parameter whose axis to insert on. + * @param Float position The new key's parameter value. + * @param Pose pose The current pose, which fixes the cell on every OTHER axis of a multi-keyed track. + * @return PuppetModel The model with the key inserted, or this on a refusal. + */ +fun PuppetModel.withTrackKeyInserted( + track: KeyformTrackRef, + parameter: Parameter, + position: Float, + pose: Pose, +): PuppetModel = + when (track) { + is KeyformTrackRef.Channel -> { + val posed = pose + (parameter.id to position) + // Hold-extrapolate past the track's key span so a key after the last copies that last value + // (render sampling falls back to the static out of range, which would author the wrong form). + val heldValue = channelValueAtHolding(track.target, posed) + if (heldValue == null) this else withChannelKeyCaptured(track.target, parameter, posed, heldValue) + } + + is KeyformTrackRef.Geometry -> { + // Same capture path as channels: seed the axis when the owner is not yet keyed on this + // parameter (any parameter the rigger targeted), then pin the form already on screen - + // withGeometryKeyCaptured hold-samples past the span so the new key copies the end form. + val posed = pose + (parameter.id to position) + withGeometryKeyCaptured(track.owner, parameter, posed) + } + } + +/** + * This model with [track]'s key at [position] removed from [parameter]'s axis. + * + * @param KeyformTrackRef track The track to edit. + * @param Parameter parameter The parameter whose axis to remove from. + * @param Int keyIndex The key's ordinal on that axis. + * @return PuppetModel The model with the key removed, or this on a refusal. + */ +fun PuppetModel.withTrackKeyRemoved(track: KeyformTrackRef, parameter: Parameter, keyIndex: Int): PuppetModel = + when (track) { + is KeyformTrackRef.Channel -> withChannelKeyRemovedAt(track.target, parameter, keyIndex) + is KeyformTrackRef.Geometry -> withGeometryKeyRemoved(track.owner, parameter, keyIndex) + } + +/** The history-label channel for [track] - null for geometry, which has no channel to name. */ +private fun channelOf(track: KeyformTrackRef) = + when (track) { + is KeyformTrackRef.Channel -> track.target.channel + is KeyformTrackRef.Geometry -> null + } + +/** + * [value] clamped into [parameter]'s range, tolerating a reversed (min > max) range from a malformed + * import. + * + * Centralized HERE rather than at each call site, so a pointer drag, a keyboard nudge, and a lane-edge + * insert cannot disagree about where the ends are. + * + * @param Float value The requested parameter value. + * @param Parameter parameter The parameter whose range bounds it. + * @return Float The clamped value. + */ +private fun clampToParameterRange(value: Float, parameter: Parameter): Float = + value.coerceIn(minOf(parameter.min, parameter.max), maxOf(parameter.min, parameter.max)) + +/** + * Moves [track]'s key at [fromValue] to [toValue], as one undo step. + * + * @param KeyformTrackRef track The track to edit. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's ordinal on that axis. + * @param Float toValue The new position. + * @return Int The ordinal the key holds AFTER the move, which a crossing changes. + */ +fun EditorSession.moveTrackKey( + track: KeyformTrackRef, + parameter: Parameter, + keyIndex: Int, + toValue: Float, +): Int { + // Within the parameter's range a key may cross its neighbours freely; the grid re-sorts and permutes + // its cells to match. Only the range itself is a wall - a key outside it can never be reached again. + val clamped = clampToParameterRange(toValue, parameter) + // Resolved BEFORE the mutate, against the grid this ordinal still refers to. A crossing renumbers the + // axis, so afterwards the ordinal names a different key - which is exactly why the caller has to be + // told the new one rather than left holding the old. + val landedIndex = model.value.trackKeyIndexAfterMove(track, parameter, keyIndex, toValue) + mutate(KeyformChange.MoveKey(channelOf(track))) { model -> + model.withTrackKeyMoved(track, parameter, keyIndex, clamped) + } + return landedIndex +} + +/** + * The ordinal a key inserted at [position] on [track] would take, or -1 when the insert adds none. + * + * The insert counterpart of [trackKeyIndexAfterMove], and needed for the same reason: an insert renumbers + * every key at or above it, so the keyform sheet has to correct its key selection to the ordinal the + * selected key lands on - and it has to do so before the insert records its step, since the selection rides + * that snapshot. + * + * Clamps [position] exactly as [insertTrackKeyAt] does, so the query cannot answer for a destination the + * insert would never use. + * + * @param KeyformTrackRef track The track to insert into. + * @param Parameter parameter The parameter whose axis the key goes on. + * @param Float position The new key's requested parameter value. + * @return Int The new key's ordinal, or -1 when the track does not resolve or a key already sits there. + */ +fun PuppetModel.trackKeyIndexAfterInsert(track: KeyformTrackRef, parameter: Parameter, position: Float): Int = + trackGridOf(this, track)?.keyIndexAfterInsert(parameter.id, clampToParameterRange(position, parameter)) ?: -1 + +/** + * The ordinal [keyIndex] on [track] would hold after being moved to [toValue] - pure, nothing recorded. + * + * Public for the same reason [limitedDragFraction] is: the keyform sheet has to know where a key will land + * BEFORE the move records its step, because the sheet's key selection rides that step's snapshot and a + * selection staged afterwards reaches no history entry at all. Preview, stage, and commit must agree about + * the landing, so they call one function rather than reimplementing the crossing rule. + * + * Clamps [toValue] exactly as [moveTrackKey] does, which is why the clamp lives here and not at either + * call site - a query that answered for an unclamped destination would disagree with the move it describes. + * + * @param KeyformTrackRef track The track the key sits on. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's current ordinal on that axis. + * @param Float toValue The requested destination. + * @return Int The ordinal after the move, or [keyIndex] when the track no longer resolves. + */ +fun PuppetModel.trackKeyIndexAfterMove( + track: KeyformTrackRef, + parameter: Parameter, + keyIndex: Int, + toValue: Float, +): Int = + trackGridOf(this, track) + ?.keyIndexAfterMove(parameter.id, keyIndex, clampToParameterRange(toValue, parameter)) + ?: keyIndex + +/** + * Inserts a shape-preserving key at [position] on [track], as one undo step. + * + * Shape-preserving means the new key holds whatever the track already evaluates to there, so the insert is + * a handle to edit from rather than an edit in itself. + * + * @param KeyformTrackRef track The track to edit. + * @param Parameter parameter The parameter whose axis to insert on. + * @param Float position The new key's parameter value. + */ +fun EditorSession.insertTrackKeyAt(track: KeyformTrackRef, parameter: Parameter, position: Float) { + // Clamped like a move: the lane's edge inset extrapolates a hit past the domain ends, and an unclamped + // insert would author a key outside the range that no scrub can ever reach. + val clamped = clampToParameterRange(position, parameter) + mutate(KeyformChange.InsertKey(channelOf(track))) { model -> + model.withTrackKeyInserted(track, parameter, clamped, pose.value) + } +} + +/** + * Moves every key in [keys] to [toValue] as ONE undo step - the summary-row drag. + * + * They go to the same place rather than by the same delta because that is what dragging a summary mark + * means: the marks were stacked at one value and stay stacked. Each still lands through its own track's + * `withKeyMoved`, so a key that would collide with a neighbour on ITS track is nudged the sub-pixel + * distance that keeps the span resolvable - the group can drift apart by at most EPS_SPAN, which is far + * below anything the sheet can draw. + * + * @param List keys The (track, parameter, key ordinal) triples to move. + * @param Float toValue The destination, in the parameter's units. + */ +fun EditorSession.moveTrackKeys(keys: List>, toValue: Float) { + if (keys.isEmpty()) { + return + } + mutate(KeyformChange.MoveKey(channelOf(keys.first().first))) { model -> + keys.fold(model) { current, (track, parameter, keyIndex) -> + current.withTrackKeyMoved(track, parameter, keyIndex, clampToParameterRange(toValue, parameter)) + } + } +} + +/** + * [fraction] reduced to what every key in [keys] can actually take without leaving its parameter's range. + * + * Public because the sheet PREVIEWS a group drag before committing it, and a preview drawn at the + * unclamped fraction would show the marks travelling past a wall they are about to stop at - which is the + * snap-back this exists to prevent. Preview and commit must be the same number, so they call the same + * function rather than reimplementing the bound. + * + * @param List keys The (track, parameter, key ordinal) triples being dragged. + * @param Float fraction The requested drag as a signed fraction of each parameter's range. + * @return Float The fraction the whole group can take - same sign, or zero when it cannot move. + */ +fun PuppetModel.limitedDragFraction(keys: List>, fraction: Float): Float = + keyDragsOf(keys).filterNotNull().fold(fraction) { limited, move -> move.limitedTo(limited) } + +/** + * One [KeyDrag] per entry of [keys], null where the ref no longer resolves. + * + * Aligned WITH keys rather than compacted: a caller gets one answer back per key it passed, so a stale ref + * must not shift every later answer by one. + * + * @param List keys The (track, parameter, key ordinal) triples. + * @return List The drags, position for position. + */ +private fun PuppetModel.keyDragsOf(keys: List>): List = + keys.map { (track, parameter, keyIndex) -> + trackKeyValue(track, parameter, keyIndex)?.let { fromValue -> KeyDrag(track, parameter, fromValue) } + } + +/** + * Drags every key in [keys] by [fraction] of its parameter's range, as ONE undo step - the multi-select + * mark drag. + * + * By a fraction rather than an absolute delta because a selection can span two parameters (a linked pad + * shows both axes at once) whose ranges differ by orders of magnitude. Within ONE parameter a fraction of + * its range IS the absolute delta, so the common case is exactly what the hand did; across two it is the + * only reading that keeps the group together on screen. + * + * Clamped to the MOST CONSTRAINED member rather than per key: clamping individually would let the keys + * nearest an end pile up while the rest kept travelling, silently destroying the spacing the rigger + * authored. Reducing the whole drag instead just stops the group at the wall. + * + * Each key is re-found BY VALUE inside the fold rather than trusted to keep its ordinal: a key that crosses + * an unselected neighbour renumbers the axis under the keys still to be moved. + * + * @param List keys The (track, parameter, key ordinal) triples to drag. + * @param Float fraction The drag as a signed fraction of each parameter's range. + * @return List Each key's ordinal AFTER the drag, in the order given - crossings renumber the axis, so + * a caller holding the old ordinals would be pointing at whichever keys took their place. + */ +fun EditorSession.dragTrackKeys(keys: List>, fraction: Float): List { + val plan = model.value.planTrackKeyDrag(keys, fraction) ?: return keys.map { (_, _, keyIndex) -> keyIndex } + // Computed before the mutate rather than inside it because the landing VALUES have to come back out, and + // mutate hands back only a model. It applies the transform exactly once against this same instance, so + // handing it the finished model is equivalent - including the reference-equality no-op check, which + // still fires when nothing moved. + mutate(KeyformChange.MoveKey(channelOf(keys.first().first))) { plan.model } + return plan.landedOrdinals +} + +/** + * Where every key in [keys] would land if dragged by [fraction] - pure, nothing recorded. + * + * The query half of [dragTrackKeys], public for the reason [trackKeyIndexAfterMove] spells out: the sheet + * has to re-point its key selection at the landed ordinals BEFORE the drag records its step, because the + * selection rides that step's snapshot. Both call the same planner, so the answer cannot drift from the + * drag it describes. + * + * @param List keys The (track, parameter, key ordinal) triples being dragged. + * @param Float fraction The drag as a signed fraction of each parameter's range. + * @return List Each key's ordinal after the drag, in the order given - the starting ordinals when the + * drag would move nothing. + */ +fun PuppetModel.trackKeyDragLandings(keys: List>, fraction: Float): List = + planTrackKeyDrag(keys, fraction)?.landedOrdinals ?: keys.map { (_, _, keyIndex) -> keyIndex } + +/** + * A planned group drag: the model it would produce, and the ordinal each key would hold in it. + * + * @property PuppetModel model The model with every drag applied. + * @property List landedOrdinals Each key's post-drag ordinal, aligned with the keys as given. + */ +private class KeyDragPlan(val model: PuppetModel, val landedOrdinals: List) + +/** + * Plans the group drag [dragTrackKeys] applies, or null when it would move nothing. + * + * Pure over this model, which is what lets the sheet ask for the landings and then commit the same drag. + * Null rather than a plan whose model is this one, so a caller cannot mistake "refused" for "applied". + * + * @param List keys The (track, parameter, key ordinal) triples to drag. + * @param Float fraction The drag as a signed fraction of each parameter's range. + * @return KeyDragPlan? The plan, or null when the drag is empty, unresolvable, or clamped to nothing. + */ +private fun PuppetModel.planTrackKeyDrag( + keys: List>, + fraction: Float, +): KeyDragPlan? { + if (keys.isEmpty() || fraction == 0f) { + return null + } + val moves = keyDragsOf(keys) + val live = moves.filterNotNull() + if (live.isEmpty()) { + return null + } + val effectiveFraction = live.fold(fraction) { limited, move -> move.limitedTo(limited) } + if (effectiveFraction == 0f) { + return null + } + val destinations = live.associateWith { move -> move.destinationAt(effectiveFraction) } + // Nearest the destination first, so a run of keys shuffling the same way cannot have an earlier one + // clamp against a neighbour that is about to move out of the way. + val ordered = if (effectiveFraction > 0f) live.sortedByDescending { it.fromValue } else live.sortedBy { it.fromValue } + val outcome = withKeyDragsApplied(ordered, destinations) + val landedOrdinals = + keys.mapIndexed { position, (track, parameter, keyIndex) -> + // Resolved by where the key ACTUALLY landed, not by where it was sent. A key dropped onto a + // neighbour is nudged EPS_SPAN aside, which is wider than the EPS_KEY tolerance this lookup uses - + // so asking for the requested value would find the key already sitting there and hand the caller + // ITS ordinal, silently moving the selection onto the wrong mark (and merging two of them into one). + val landed = moves[position]?.let { move -> outcome.landedValueByMove[move] } ?: return@mapIndexed keyIndex + outcome.model.trackKeyIndexAt(track, parameter, landed).takeIf { index -> index >= 0 } ?: keyIndex + } + return KeyDragPlan(outcome.model, landedOrdinals) +} + +/** + * The result of applying a batch of key drags: the new model, and where each key actually ended up. + * + * The landing values are not the requested destinations. A key dropped within EPS_SPAN of a neighbour is + * nudged aside, and one that cannot be nudged anywhere resolvable does not move at all - so the only + * description of a key that survives its own move is the value it truly holds afterwards. + * + * @property PuppetModel model The model with every drag applied. + * @property Map landedValueByMove Each drag's true landing value. + */ +private class KeyDragOutcome(val model: PuppetModel, val landedValueByMove: Map) + +/** + * This model with [ordered] applied in sequence, reporting where each key truly landed. + * + * Pure, and applied in the given order because each move reshapes the axis the next one is found on. + * + * @param List ordered The drags, already sorted into the direction of travel. + * @param Map destinations Each drag's requested destination. + * @return KeyDragOutcome The new model plus each drag's true landing value. + */ +private fun PuppetModel.withKeyDragsApplied(ordered: List, destinations: Map): KeyDragOutcome { + val landed = HashMap(ordered.size) + var working = this + for (move in ordered) { + // Re-found BY VALUE, not by the ordinal the caller passed: an earlier key crossing an unselected + // neighbour renumbers the axis under the keys still to be moved. + val liveIndex = working.trackKeyIndexAt(move.track, move.parameter, move.fromValue) + if (liveIndex < 0) { + continue + } + val requested = destinations.getValue(move) + // Asked BEFORE the move, off the same grid withTrackKeyMoved will consult, so the answer is the one + // that is about to be applied. Null is a refusal - the key stays exactly where it is. + landed[move] = working.trackKeyDestination(move.track, move.parameter, liveIndex, requested) ?: move.fromValue + working = working.withTrackKeyMoved(move.track, move.parameter, liveIndex, requested) + } + return KeyDragOutcome(working, landed) +} + +/** + * Where [track]'s key at [keyIndex] would land if moved toward [requested] - the collision nudge applied. + * + * @param KeyformTrackRef track The track to read. + * @param Parameter parameter The parameter whose axis the key sits on. + * @param Int keyIndex The key's ordinal on that axis. + * @param Float requested The requested destination. + * @return Float? The value it would take, or null when the move cannot apply. + */ +private fun PuppetModel.trackKeyDestination( + track: KeyformTrackRef, + parameter: Parameter, + keyIndex: Int, + requested: Float, +): Float? = trackGridOf(this, track)?.keyDestinationFor(parameter.id, keyIndex, requested) + +/** + * One key's in-flight drag: where it is now, and what bounds how far it may go. + * + * @property KeyformTrackRef track The track it sits on. + * @property Parameter parameter The parameter whose axis it sits on. + * @property Float fromValue Its position before the drag. + */ +private class KeyDrag(val track: KeyformTrackRef, val parameter: Parameter, val fromValue: Float) { + /** The parameter's span, floored so a degenerate (min == max) parameter cannot divide by zero. */ + private val span: Float get() = (maxOf(parameter.min, parameter.max) - minOf(parameter.min, parameter.max)).takeIf { it > 0f } ?: 1f + + /** + * [fraction] reduced, if needed, so this key stays inside its parameter's range. + * + * @param Float fraction The requested drag. + * @return Float The fraction this key can take, same sign or zero. + */ + fun limitedTo(fraction: Float): Float { + val low = minOf(parameter.min, parameter.max) + val high = maxOf(parameter.min, parameter.max) + return if (fraction > 0f) { + minOf(fraction, ((high - fromValue) / span).coerceAtLeast(0f)) + } else { + maxOf(fraction, ((low - fromValue) / span).coerceAtMost(0f)) + } + } + + /** + * Where this key lands at [fraction] of its parameter's range. + * + * @param Float fraction The (already limited) drag. + * @return Float The destination, clamped defensively to the range. + */ + fun destinationAt(fraction: Float): Float = + (fromValue + span * fraction).coerceIn(minOf(parameter.min, parameter.max), maxOf(parameter.min, parameter.max)) +} + +/** + * The parameter value key [keyIndex] currently sits at on [track], or null when there is no such key. + * + * @param KeyformTrackRef track The track to read. + * @param Parameter parameter The parameter whose axis to read. + * @param Int keyIndex The key's ordinal on that axis. + * @return Float? Its current position, or null. + */ +fun PuppetModel.trackKeyValue(track: KeyformTrackRef, parameter: Parameter, keyIndex: Int): Float? { + val axis = + trackGridOf(this, track)?.axes?.firstOrNull { candidate -> candidate.parameterId == parameter.id } + ?: return null + return axis.keys.getOrNull(keyIndex) +} + +/** + * The ordinal of [track]'s key at the current [pose] on [parameter]'s axis, or -1 when the pose is not on + * one. + * + * Within EPS_KEY, the same tolerance `bindBracket` snaps with - so "on a key" here means exactly what it + * means to the evaluator, and the field tint, the shortcut, and the rendered result cannot disagree about + * whether the pose is sitting on a key. + * + * @param KeyformTrackRef track The track to read. + * @param Parameter parameter The parameter whose axis to read. + * @param Pose pose The pose to resolve against. + * @return Int The key's ordinal, or -1. + */ +fun PuppetModel.trackKeyIndexAtPose(track: KeyformTrackRef, parameter: Parameter, pose: Pose): Int { + val grid = trackGridOf(this, track) ?: return -1 + return grid.keyIndexAt(parameter.id, pose[parameter.id] ?: parameter.default) +} + +/** + * The ordinal of [track]'s key sitting at [value] on [parameter]'s axis, or -1 when none does. + * + * Within EPS_KEY, the same tolerance the evaluator snaps with - so "the key at this value" means what it + * means everywhere else. The value-addressed sibling of [trackKeyIndexAtPose], for the one case where an + * ordinal cannot be trusted: after a move that may have crossed a neighbour and renumbered the axis. + * + * @param KeyformTrackRef track The track to read. + * @param Parameter parameter The parameter whose axis to read. + * @param Float value The parameter value to look at. + * @return Int The key's ordinal, or -1. + */ +fun PuppetModel.trackKeyIndexAt(track: KeyformTrackRef, parameter: Parameter, value: Float): Int = + trackGridOf(this, track)?.keyIndexAt(parameter.id, value) ?: -1 + +/** The grid behind [track] - its owner's channel track or its geometry - or null when there is none. */ +private fun trackGridOf(puppet: PuppetModel, track: KeyformTrackRef): KeyformGrid<*>? = + when (track) { + is KeyformTrackRef.Channel -> puppet.channelGridsOf(track.owner)?.get(track.target.channel) + is KeyformTrackRef.Geometry -> puppet.geometryGridOf(track.owner) + } + +/** + * Removes every key in [keys] as ONE undo step - the sheet's Delete over a multi-key selection. + * + * One step rather than one per key because the user made one gesture; a per-key step would make undoing a + * five-key delete take five presses. Applied in DESCENDING index order so each removal cannot renumber + * the keys the later ones still have to find. + * + * @param List keys The (track, parameter, key ordinal) triples to remove. + */ +fun EditorSession.removeTrackKeys(keys: List>) { + if (keys.isEmpty()) { + return + } + mutate(KeyformChange.DeleteKey(channelOf(keys.first().first))) { model -> + keys + .sortedByDescending { (_, _, keyIndex) -> keyIndex } + .fold(model) { current, (track, parameter, keyIndex) -> + current.withTrackKeyRemoved(track, parameter, keyIndex) + } + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MergeAdjust.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MergeAdjust.kt new file mode 100644 index 0000000..d7bbfd1 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MergeAdjust.kt @@ -0,0 +1,53 @@ +package org.umamo.edit + +/* + * The merge's face on the operation settings strip: its one setting, where the survivor lands, as a + * choice row the rigger can switch after the fact. The keys are declared here, in the module that + * runs the merge, so the UI's label table names constants rather than repeating strings. + */ + +/** The parameter key and the choice label-key prefix the merge's row carries. */ +object MergeParameterKeys { + /** The Merge At row: which vertex the survivor lands on. */ + const val TARGET = "merge.target" + + /** The label-key prefix of the row's choices; a target's [MergeTarget.parameterKey] follows it. */ + const val TARGET_CHOICE_PREFIX = "merge.target." +} + +/** The stable choice key of this target, as the strip's row stores it. */ +val MergeTarget.parameterKey: String + get() = + when (this) { + MergeTarget.AtCenter -> "center" + MergeTarget.AtFirst -> "first" + MergeTarget.AtLast -> "last" + } + +/** + * The strip's rows for a merge that landed at [target]: the Merge At choice over every target. + * + * @param MergeTarget target Where the survivor landed. + * @return List The one row. + */ +fun mergeParameters(target: MergeTarget): List = + listOf( + OperatorParameter.ChoiceParameter( + MergeParameterKeys.TARGET, + MergeParameterKeys.TARGET, + target.parameterKey, + MergeTarget.entries.map { candidate -> ParameterChoice(candidate.parameterKey, MergeParameterKeys.TARGET_CHOICE_PREFIX + candidate.parameterKey) }, + ), + ) + +/** + * The target the strip's rows name, or [fallback] when the row is absent or names no known target. + * + * @param List parameters The strip's rows. + * @param MergeTarget fallback The target the merge first ran with. + * @return MergeTarget The target to re-merge at. + */ +fun mergeTargetOf(parameters: List, fallback: MergeTarget): MergeTarget { + val key = parameters.choiceValue(MergeParameterKeys.TARGET, fallback.parameterKey) + return MergeTarget.entries.firstOrNull { candidate -> candidate.parameterKey == key } ?: fallback +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshElementMemory.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshElementMemory.kt new file mode 100644 index 0000000..5d4efc1 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshElementMemory.kt @@ -0,0 +1,83 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * The session's remembered-selection memory: which drawable was last active (so entering Edit mode + * with an empty selection lands somewhere sensible - Blender's remembered selection), and each + * mesh's stashed element selection (stashed when Edit mode is left or the session switches meshes, + * restored per drawable on re-entry when the elements still fit - Blender remembers the mesh + * selection across mode switches per mesh). Transient UI convenience, deliberately NOT part of + * [EditorSnapshot]: undo restores whatever the snapshot holds, this only seeds fresh entries. + * + * セッションの選択記憶。最後にアクティブだった描画対象と、メッシュごとの要素選択スタッシュを保持 + * する(Blender のモード切替をまたぐ選択記憶に相当)。スナップショットには含めない。 + */ +internal class MeshElementMemory { + /** The last drawable that was active, or null before any; Edit-mode entry falls back to it. */ + var lastActiveDrawableId: DrawableId? = null + + // Per-mesh element-selection memory, keyed by drawable, plus the select mode remembered alongside. + private val rememberedElementsByDrawable = HashMap>() + private val rememberedActiveElementByDrawable = HashMap() + private var rememberedSelectMode: MeshSelectMode? = null + + /** + * Stashes each session drawable's element selection into the per-mesh memory, so re-entering Edit + * mode - or switching back to the mesh with Alt+Q - restores it. An emptied mesh clears its slot; + * the select mode is remembered alongside. + * + * @param MeshSelection current The element selection to stash. + */ + fun stash(current: MeshSelection) { + if (current.drawableIds.isEmpty()) { + return + } + rememberedSelectMode = current.selectMode + for (drawableId in current.drawableIds) { + val elements = current.elementsOf(drawableId) + if (elements.isEmpty()) { + rememberedElementsByDrawable.remove(drawableId) + rememberedActiveElementByDrawable.remove(drawableId) + } else { + rememberedElementsByDrawable[drawableId] = elements + } + } + current.activeElement?.let { active -> rememberedActiveElementByDrawable[active.drawableId] = active.element } + } + + /** + * Restores the per-mesh remembered elements into [seeded]: each seeded drawable whose stored + * elements still fit its current mesh gets them back (validated per drawable, so one stale mesh + * never discards the others' memory); the remembered select mode returns when anything restored. + * + * @param MeshSelection seeded The freshly seeded session selection. + * @param PuppetModel model The current model (element fit is validated against its meshes). + * @return MeshSelection The seeded selection with the remembered elements folded in. + */ + fun restore(seeded: MeshSelection, model: PuppetModel): MeshSelection { + val restored = + seeded.drawableIds.mapNotNull { drawableId -> + val stored = rememberedElementsByDrawable[drawableId]?.takeIf { elements -> elements.isNotEmpty() } ?: return@mapNotNull null + val probe = seeded.copy(selectMode = rememberedSelectMode ?: seeded.selectMode, elementsByDrawable = mapOf(drawableId to stored)) + val fits = MeshSelectionOps.fitsWithinMeshes(probe) { candidateId -> model.drawables.firstOrNull { drawable -> drawable.id == candidateId }?.mesh } + if (fits) drawableId to stored else null + }.toMap() + if (restored.isEmpty()) { + return seeded + } + // The active mesh's remembered active element returns with it (when it is still selected there). + val restoredActive = + seeded.activeDrawableId?.let { activeId -> + rememberedActiveElementByDrawable[activeId] + ?.takeIf { element -> restored[activeId]?.contains(element) == true } + ?.let { element -> ActiveMeshElement(activeId, element) } + } + return seeded.copy( + selectMode = rememberedSelectMode ?: seeded.selectMode, + elementsByDrawable = restored, + activeElement = restoredActive, + ) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshSelection.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshSelection.kt new file mode 100644 index 0000000..a682b5a --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshSelection.kt @@ -0,0 +1,520 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh + +/** + * The Edit-mode selection domain, mirroring Blender's vertex / edge / face select modes: which kind of + * mesh element the pointer picks and the selection stores. Only the current mode's domain is stored in + * [MeshSelection.elementsByDrawable]; highlights in the other domains are derived for display, and + * switching modes converts the stored sets (see [MeshSelectionOps.changeSelectMode]). + * + * 編集モードの選択対象の種類。Blender の頂点・辺・面選択モードに対応する。 + */ +enum class MeshSelectMode { + Vertex, + Edge, + Face, +} + +/** + * One selectable mesh element: a vertex, an undirected edge, or a face. Element identity is LOCAL to + * its drawable's mesh (a vertex index means nothing without knowing which mesh), which is why + * [MeshSelection] stores elements per drawable and the active element carries its drawable alongside. + * The mesh topology is immutable while editing (copy-on-write replaces only positions), so vertex + * indices, canonical (low, high) edge pairs, and triangle indices are stable identities across every + * gesture. + * + * メッシュの選択可能要素。頂点・無向辺・面(三角形)のいずれか。要素の同一性はメッシュ内ローカル。 + */ +sealed interface MeshElement { + /** + * A single mesh vertex. + * + * @property Int index The vertex index (into the mesh's vertex list). + */ + data class Vertex(val index: Int) : MeshElement + + /** + * An undirected mesh edge, canonicalized so (a, b) and (b, a) are one identity. Construct via [of]. + * + * @property Int endpointLow The smaller endpoint vertex index. + * @property Int endpointHigh The larger endpoint vertex index. + */ + data class Edge(val endpointLow: Int, val endpointHigh: Int) : MeshElement { + companion object { + /** + * Builds the canonical undirected edge for two endpoint vertex indices, given in either order. + * + * @param Int vertexA One endpoint vertex index. + * @param Int vertexB The other endpoint vertex index. + * @return Edge The canonical (low, high) edge. + */ + fun of(vertexA: Int, vertexB: Int): Edge = + if (vertexA <= vertexB) { + Edge(vertexA, vertexB) + } else { + Edge(vertexB, vertexA) + } + } + } + + /** + * A single mesh face. The mesh is triangles-only, so a face is one triangle of the index list. + * + * @property Int triangleIndex The triangle ordinal (three consecutive entries of the index list). + */ + data class Face(val triangleIndex: Int) : MeshElement +} + +/** + * The active (primary) element of an Edit session: the last-touched element together with the drawable + * whose mesh it lives in - element indices are mesh-local, so the pair is the element's full identity. + * + * @property DrawableId drawableId The drawable whose mesh holds the element. + * @property MeshElement element The last-touched element. + */ +data class ActiveMeshElement(val drawableId: DrawableId, val element: MeshElement) + +/** + * An immutable Edit-mode sub-object selection over one or more drawables' meshes: which meshes are in + * the edit session, the select mode (vertex / edge / face), and the selected elements per mesh with the + * active (primary) one. This is the sub-object analog of [Selection] - where object-mode selects whole + * entities, Edit mode selects elements inside the session meshes - and the multi-mesh shape is what lets + * a rigger edit several art meshes at once (entering Edit with a multi-selection, and later the glue + * workflows that need two meshes live together). + * + * Only the current [selectMode]'s domain is ever stored in [elementsByDrawable] (a vertex-mode selection + * holds only [MeshElement.Vertex] members, and so on). Cross-domain highlights - an edge lighting up + * because both endpoints are selected in vertex mode - are derived for display via [MeshTopology], never + * stored, which is exactly Blender's model. + * + * [drawableIds] is empty when Edit mode is inert (entered without an editable drawable); the overlay + * then draws nothing and the transform operators no-op. [activeDrawableId] is Blender's active object + * within the session - the mesh a click last landed on, which anchors per-mesh actions (select-mode + * conversion display, the status bar's denominators). [activeElement] is the element analog of + * [Selection.active]: the last-touched element with its drawable; it is always a member of its + * drawable's element set, or null when nothing is selected. + * + * @property List drawableIds The meshes in the edit session, in selection order. + * @property DrawableId? activeDrawableId The session's active mesh, or null when the session is inert. + * @property MeshSelectMode selectMode The element domain clicks select (vertex / edge / face). + * @property Map> elementsByDrawable The selected elements per mesh, all of + * the current mode's domain; a drawable with no selection may be absent. + * @property ActiveMeshElement? activeElement The primary element (last touched), or null when none. + */ +data class MeshSelection( + val drawableIds: List = emptyList(), + val activeDrawableId: DrawableId? = null, + val selectMode: MeshSelectMode = MeshSelectMode.Vertex, + val elementsByDrawable: Map> = emptyMap(), + val activeElement: ActiveMeshElement? = null, +) { + /** True when no elements are selected on any mesh (the session may still hold drawables). */ + val isEmpty: Boolean get() = elementsByDrawable.values.all { elements -> elements.isEmpty() } + + /** The number of selected elements across every session mesh. */ + val size: Int get() = elementsByDrawable.values.sumOf { elements -> elements.size } + + /** + * The selected elements of one mesh (empty when the drawable has no selection or is not in the + * session). + * + * @param DrawableId drawableId The mesh to read. + * @return Set That mesh's selected elements. + */ + fun elementsOf(drawableId: DrawableId): Set = elementsByDrawable[drawableId] ?: emptySet() + + /** + * Reports whether the given element is selected on the given mesh. + * + * @param DrawableId drawableId The mesh the element lives in. + * @param MeshElement element The element to test. + * @return Boolean True when selected. + */ + fun contains(drawableId: DrawableId, element: MeshElement): Boolean = element in elementsOf(drawableId) + + companion object { + /** + * An empty Edit session over the given meshes: nothing selected, the first (or given) mesh active. + * + * @param List drawableIds The session meshes, in selection order. + * @param DrawableId? activeDrawableId The active mesh; defaults to the first. + * @return MeshSelection The seeded session selection. + */ + fun editing(drawableIds: List, activeDrawableId: DrawableId? = drawableIds.firstOrNull()): MeshSelection = + MeshSelection(drawableIds = drawableIds, activeDrawableId = activeDrawableId) + } +} + +/** + * Pure transformations over a [MeshSelection], one per selection gesture (mirroring [SelectionOps]). + * Element gestures name the drawable they land on (element identity is mesh-local); whole-session + * gestures (select all, invert, mode conversion) take a mesh provider so each session mesh converts + * against its own topology. Each function returns a new immutable [MeshSelection] over the same + * session and never mutates its input, so they are unit-testable without Compose. The active element + * is maintained per the [MeshSelection] invariant: always a member of its drawable's element set, or + * null when nothing remains. + */ +object MeshSelectionOps { + /** + * Rebuilds the per-drawable element map with one drawable's set replaced, dropping empty sets so the + * map never accumulates stale keys. + * + * @param MeshSelection selection The selection whose map to rebuild. + * @param DrawableId drawableId The drawable whose set changes. + * @param Set elements That drawable's new element set. + * @return Map> The rebuilt map. + */ + private fun withElements( + selection: MeshSelection, + drawableId: DrawableId, + elements: Set, + ): Map> = + if (elements.isEmpty()) { + selection.elementsByDrawable - drawableId + } else { + selection.elementsByDrawable + (drawableId to elements) + } + + /** + * Replaces the whole selection with a single element (a plain click): every session mesh clears and + * only [element] on [drawableId] remains, active, with its mesh becoming the session's active mesh. + * + * @param MeshSelection selection The selection to modify. + * @param DrawableId drawableId The mesh the click landed on. + * @param MeshElement element The sole element to select. + * @return MeshSelection A selection holding only [element], with it active. + */ + fun replace(selection: MeshSelection, drawableId: DrawableId, element: MeshElement): MeshSelection = + selection.copy( + activeDrawableId = drawableId, + elementsByDrawable = mapOf(drawableId to setOf(element)), + activeElement = ActiveMeshElement(drawableId, element), + ) + + /** + * Toggles an element's membership on its mesh (a Shift or Ctrl / Cmd click, Blender-style): removes + * it when present, adds it otherwise. When added it becomes active (and its mesh the active mesh); + * when removed the active element falls back to another member of the same mesh, or null. + * + * @param MeshSelection selection The selection to modify. + * @param DrawableId drawableId The mesh the click landed on. + * @param MeshElement element The element to toggle. + * @return MeshSelection The resulting selection. + */ + fun toggle(selection: MeshSelection, drawableId: DrawableId, element: MeshElement): MeshSelection { + val current = selection.elementsOf(drawableId) + return if (element in current) { + val remaining = current - element + val fallback = remaining.lastOrNull()?.let { survivor -> ActiveMeshElement(drawableId, survivor) } + selection.copy( + activeDrawableId = drawableId, + elementsByDrawable = withElements(selection, drawableId, remaining), + activeElement = if (selection.activeElement?.drawableId == drawableId && selection.activeElement.element == element) fallback else selection.activeElement, + ) + } else { + selection.copy( + activeDrawableId = drawableId, + elementsByDrawable = withElements(selection, drawableId, current + element), + activeElement = ActiveMeshElement(drawableId, element), + ) + } + } + + /** + * Adds an element without removing anything (an additive gesture), making it active and its mesh the + * session's active mesh. + * + * @param MeshSelection selection The selection to extend. + * @param DrawableId drawableId The mesh the element lives in. + * @param MeshElement element The element to add. + * @return MeshSelection The extended selection. + */ + fun add(selection: MeshSelection, drawableId: DrawableId, element: MeshElement): MeshSelection = + selection.copy( + activeDrawableId = drawableId, + elementsByDrawable = withElements(selection, drawableId, selection.elementsOf(drawableId) + element), + activeElement = ActiveMeshElement(drawableId, element), + ) + + /** + * Applies a box (rubber-band) selection across the session meshes: replaces every mesh's element set + * with its entry in [elementsByDrawable], or unions them in when [additive]. The active element is + * kept when it remains selected, otherwise it drops to null (a box has no single "last touched" + * element). + * + * @param MeshSelection selection The selection to modify. + * @param Map> elementsByDrawable The enclosed elements per session mesh. + * @param Boolean additive True to union with the current sets (Shift box), false to replace them. + * @return MeshSelection The resulting selection. + */ + fun box(selection: MeshSelection, elementsByDrawable: Map>, additive: Boolean): MeshSelection { + val resulting = HashMap>() + if (additive) { + selection.elementsByDrawable.forEach { (drawableId, elements) -> resulting[drawableId] = elements } + elementsByDrawable.forEach { (drawableId, elements) -> + resulting[drawableId] = (resulting[drawableId] ?: emptySet()) + elements + } + } else { + elementsByDrawable.forEach { (drawableId, elements) -> + if (elements.isNotEmpty()) { + resulting[drawableId] = elements + } + } + } + resulting.values.removeAll { elements -> elements.isEmpty() } + val active = selection.activeElement?.takeIf { active -> active.element in (resulting[active.drawableId] ?: emptySet()) } + return selection.copy(elementsByDrawable = resulting, activeElement = active) + } + + /** + * Removes elements per mesh (the erase half of a Circle-select stroke), keeping the active element + * only when it survives. The mirror of [box]'s additive union. + * + * @param MeshSelection selection The selection to shrink. + * @param Map> elementsByDrawable The elements to deselect per mesh. + * @return MeshSelection The selection with those elements removed. + */ + fun remove(selection: MeshSelection, elementsByDrawable: Map>): MeshSelection { + val resulting = HashMap>(selection.elementsByDrawable) + elementsByDrawable.forEach { (drawableId, elements) -> + val remaining = (resulting[drawableId] ?: emptySet()) - elements + if (remaining.isEmpty()) { + resulting.remove(drawableId) + } else { + resulting[drawableId] = remaining + } + } + val active = selection.activeElement?.takeIf { active -> active.element in (resulting[active.drawableId] ?: emptySet()) } + return selection.copy(elementsByDrawable = resulting, activeElement = active) + } + + /** + * Clears the selection, keeping the session meshes and mode (the Edit session stays open, nothing + * selected). + * + * @param MeshSelection selection The selection to clear. + * @return MeshSelection The selection with empty element sets. + */ + fun clear(selection: MeshSelection): MeshSelection = + selection.copy(elementsByDrawable = emptyMap(), activeElement = null) + + /** + * Switches the select mode, converting every session mesh's stored elements into the new domain with + * Blender's flush-down / derive-up rules. Flushing down (to vertex) expands every element to the + * vertices it covers, so selection is never lost. Deriving up is strict per Blender: an edge + * qualifies only when both endpoints were selected, and a face only when all of its own vertices + * (from vertex mode) or all three of its own edges (from edge mode) were selected. The active + * element drops to null on conversion (no single "last touched" element survives a domain change); + * a same-mode call returns the selection unchanged. A session mesh whose triangles the provider + * cannot resolve converts to empty. + * + * @param MeshSelection selection The selection to convert. + * @param MeshSelectMode newMode The target select mode. + * @param Function triangleIndicesOf Resolves a session mesh's triangle indices, or null when absent. + * @return MeshSelection The selection in [newMode] with the converted element sets. + */ + fun changeSelectMode( + selection: MeshSelection, + newMode: MeshSelectMode, + triangleIndicesOf: (DrawableId) -> IntArray?, + ): MeshSelection { + if (newMode == selection.selectMode) { + return selection + } + val converted = HashMap>() + for ((drawableId, elements) in selection.elementsByDrawable) { + val triangleIndices = triangleIndicesOf(drawableId) ?: continue + val convertedElements = convertElements(elements, selection.selectMode, newMode, triangleIndices) + if (convertedElements.isNotEmpty()) { + converted[drawableId] = convertedElements + } + } + return selection.copy(selectMode = newMode, elementsByDrawable = converted, activeElement = null) + } + + /** + * Converts one mesh's element set between select-mode domains (the single-mesh core of + * [changeSelectMode]; see its docblock for the flush / derive rules). + * + * @param Set elements The stored elements, all of [fromMode]'s domain. + * @param MeshSelectMode fromMode The current domain. + * @param MeshSelectMode newMode The target domain. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @return Set The converted set in [newMode]'s domain. + */ + private fun convertElements( + elements: Set, + fromMode: MeshSelectMode, + newMode: MeshSelectMode, + triangleIndices: IntArray, + ): Set = + when (newMode) { + MeshSelectMode.Vertex -> + MeshTopology.coveredVertexIndices(elements, triangleIndices) + .map { vertexIndex -> MeshElement.Vertex(vertexIndex) } + .toSet() + + MeshSelectMode.Edge -> + when (fromMode) { + MeshSelectMode.Vertex -> + MeshTopology.edgesWithBothEndpointsSelected( + triangleIndices, + MeshTopology.coveredVertexIndices(elements, triangleIndices), + ) + + MeshSelectMode.Face -> + elements + .filterIsInstance() + .flatMap { face -> MeshTopology.edgesOfTriangle(triangleIndices, face.triangleIndex) } + .toSet() + + // Unreachable: the same-mode case returned above; kept for exhaustiveness. + MeshSelectMode.Edge -> elements + } + + MeshSelectMode.Face -> + when (fromMode) { + MeshSelectMode.Vertex -> + MeshTopology.facesWithAllVerticesSelected( + triangleIndices, + MeshTopology.coveredVertexIndices(elements, triangleIndices), + ) + + MeshSelectMode.Edge -> + MeshTopology.facesWithAllEdgesSelected( + triangleIndices, + elements.filterIsInstance().toSet(), + ) + + // Unreachable: the same-mode case returned above; kept for exhaustiveness. + MeshSelectMode.Face -> elements + } + } + + /** + * Every element of a select mode's domain over a mesh: all vertices, all unique edges, or all faces. + * The full set [selectAll] fills and [invert] complements against. The vertex count comes from the + * mesh because an isolated vertex (one in no triangle) is still a valid element that the triangle + * indices alone would miss. + * + * @param MeshSelectMode mode The domain to enumerate. + * @param DrawableMesh mesh The mesh whose domain to enumerate. + * @return Set Every element of [mode]'s domain. + */ + private fun allElements(mode: MeshSelectMode, mesh: DrawableMesh): Set = + when (mode) { + MeshSelectMode.Vertex -> (0 until mesh.vertexCount).map { vertexIndex -> MeshElement.Vertex(vertexIndex) }.toSet() + MeshSelectMode.Edge -> MeshTopology.uniqueEdges(mesh.indices).toSet() + MeshSelectMode.Face -> (0 until mesh.triangleCount).map { triangleIndex -> MeshElement.Face(triangleIndex) }.toSet() + } + + /** + * Selects every element of the current select mode's domain on every session mesh (Blender's Select + * All). The active element is kept (it is necessarily still selected); from an empty selection it + * stays null. A session mesh the provider cannot resolve contributes nothing. + * + * @param MeshSelection selection The selection to fill. + * @param Function meshOf Resolves a session drawable's mesh, or null when absent. + * @return MeshSelection The selection holding every element of its domain on every session mesh. + */ + fun selectAll(selection: MeshSelection, meshOf: (DrawableId) -> DrawableMesh?): MeshSelection { + val filled = HashMap>() + for (drawableId in selection.drawableIds) { + val mesh = meshOf(drawableId) ?: continue + val all = allElements(selection.selectMode, mesh) + if (all.isNotEmpty()) { + filled[drawableId] = all + } + } + val active = selection.activeElement?.takeIf { active -> active.element in (filled[active.drawableId] ?: emptySet()) } + return selection.copy(elementsByDrawable = filled, activeElement = active) + } + + /** + * Inverts the selection within the current select mode's domain on every session mesh (Blender's + * Ctrl+I): every element not currently selected becomes selected and vice versa. The active element + * drops unless it happens to remain selected (in practice it drops - it was selected before). + * + * @param MeshSelection selection The selection to invert. + * @param Function meshOf Resolves a session drawable's mesh, or null when absent. + * @return MeshSelection The inverted selection. + */ + fun invert(selection: MeshSelection, meshOf: (DrawableId) -> DrawableMesh?): MeshSelection { + val inverted = HashMap>() + for (drawableId in selection.drawableIds) { + val mesh = meshOf(drawableId) ?: continue + val complement = allElements(selection.selectMode, mesh) - selection.elementsOf(drawableId) + if (complement.isNotEmpty()) { + inverted[drawableId] = complement + } + } + val active = selection.activeElement?.takeIf { active -> active.element in (inverted[active.drawableId] ?: emptySet()) } + return selection.copy(elementsByDrawable = inverted, activeElement = active) + } + + /** + * Unions a connectivity island's elements into one mesh's selection, in the CURRENT select mode's + * domain - Blender's Select Linked (L): every vertex of the island in vertex mode, every edge with + * both endpoints in the island in edge mode, every face with all vertices in the island in face + * mode. Additive by design (repeated L grows the selection island by island); the active element + * is left untouched (still a member - the union only adds). + * + * @param MeshSelection selection The selection to extend. + * @param DrawableId drawableId The mesh the island lives in. + * @param Set islandVertices The island's vertex indices (a [MeshTopology.connectedVertices] result). + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @return MeshSelection The selection with the island's elements added. + */ + fun selectLinked( + selection: MeshSelection, + drawableId: DrawableId, + islandVertices: Set, + triangleIndices: IntArray, + ): MeshSelection { + val islandElements: Set = + when (selection.selectMode) { + MeshSelectMode.Vertex -> islandVertices.map { vertexIndex -> MeshElement.Vertex(vertexIndex) }.toSet() + MeshSelectMode.Edge -> MeshTopology.edgesWithBothEndpointsSelected(triangleIndices, islandVertices) + MeshSelectMode.Face -> MeshTopology.facesWithAllVerticesSelected(triangleIndices, islandVertices) + } + if (islandElements.isEmpty()) { + return selection + } + return selection.copy( + elementsByDrawable = withElements(selection, drawableId, selection.elementsOf(drawableId) + islandElements), + ) + } + + /** + * Reports whether every selected element still exists in its mesh: vertex indices within the vertex + * count, edges present in the mesh's edge set, and face ordinals within the triangle count - across + * every session mesh. Used to decide whether a stashed selection may be restored (re-entering Edit + * mode) after the meshes may have changed underneath it. A session mesh the provider cannot resolve + * fails the check. + * + * @param MeshSelection selection The selection to validate. + * @param Function meshOf Resolves a session drawable's mesh, or null when absent. + * @return Boolean True when every element still fits its mesh. + */ + fun fitsWithinMeshes(selection: MeshSelection, meshOf: (DrawableId) -> DrawableMesh?): Boolean { + for ((drawableId, elements) in selection.elementsByDrawable) { + val mesh = meshOf(drawableId) ?: return false + // Built lazily: vertex- and face-only selections never pay for the edge scan. + val meshEdges by lazy { MeshTopology.uniqueEdges(mesh.indices).toSet() } + for (element in elements) { + val fits = + when (element) { + is MeshElement.Vertex -> element.index in 0 until mesh.vertexCount + is MeshElement.Edge -> element in meshEdges + is MeshElement.Face -> element.triangleIndex in 0 until mesh.triangleCount + } + if (!fits) { + return false + } + } + } + return true + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopology.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopology.kt new file mode 100644 index 0000000..c44f665 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopology.kt @@ -0,0 +1,231 @@ +package org.umamo.edit + +/** + * Pure topology queries over a triangle index list (three vertex indices per triangle). The single + * source of truth for Blender's select-mode rules: [MeshSelectionOps.changeSelectMode] uses these to + * convert a selection between domains, and the gizmo overlay uses the same derive-up functions for its + * cross-domain display highlights - so the flush / derive semantics live (and are tested) once. + * + * 三角形インデックス列に対する純粋なトポロジ照会。選択モード変換と表示ハイライトの共通基盤。 + */ +object MeshTopology { + /** + * The deduplicated undirected edges of a triangle index list. Each interior edge is shared by two + * triangles but must appear once, so edges are canonicalized to (low, high) before deduplication. + * + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @return List The unique edges, in first-encounter order. + */ + fun uniqueEdges(triangleIndices: IntArray): List { + val edges = LinkedHashSet() + val triangleCount = triangleIndices.size / 3 + for (triangleIndex in 0 until triangleCount) { + edges.addAll(edgesOfTriangle(triangleIndices, triangleIndex)) + } + return edges.toList() + } + + /** + * The three canonical edges of one triangle. + * + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Int triangleIndex The triangle ordinal. + * @return List The triangle's edges. + */ + fun edgesOfTriangle(triangleIndices: IntArray, triangleIndex: Int): List { + val cornerA = triangleIndices[triangleIndex * 3] + val cornerB = triangleIndices[triangleIndex * 3 + 1] + val cornerC = triangleIndices[triangleIndex * 3 + 2] + return listOf( + MeshElement.Edge.of(cornerA, cornerB), + MeshElement.Edge.of(cornerB, cornerC), + MeshElement.Edge.of(cornerC, cornerA), + ) + } + + /** + * The three vertex indices of one triangle. + * + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Int triangleIndex The triangle ordinal. + * @return Set The triangle's vertex indices. + */ + fun verticesOfTriangle(triangleIndices: IntArray, triangleIndex: Int): Set = + setOf( + triangleIndices[triangleIndex * 3], + triangleIndices[triangleIndex * 3 + 1], + triangleIndices[triangleIndex * 3 + 2], + ) + + /** + * The union of vertices covered by a set of elements: a vertex covers itself, an edge its two + * endpoints, a face its three corners. This is the flush-down rule (any mode to vertex mode), and + * what the G / S / R operators transform for an edge or face selection. + * + * @param Set elements The selected elements (any mix of domains). + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @return Set The covered vertex indices. + */ + fun coveredVertexIndices(elements: Set, triangleIndices: IntArray): Set { + val covered = HashSet() + for (element in elements) { + when (element) { + is MeshElement.Vertex -> covered.add(element.index) + + is MeshElement.Edge -> { + covered.add(element.endpointLow) + covered.add(element.endpointHigh) + } + + is MeshElement.Face -> covered.addAll(verticesOfTriangle(triangleIndices, element.triangleIndex)) + } + } + return covered + } + + /** + * The edges whose both endpoints are in the selected vertex set - the vertex-to-edge derive-up rule, + * also used to highlight edges while selecting vertices. + * + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Set selectedVertexIndices The selected vertex indices. + * @return Set The qualifying edges. + */ + fun edgesWithBothEndpointsSelected(triangleIndices: IntArray, selectedVertexIndices: Set): Set = + uniqueEdges(triangleIndices) + .filter { edge -> edge.endpointLow in selectedVertexIndices && edge.endpointHigh in selectedVertexIndices } + .toSet() + + /** + * The faces whose every vertex is in the selected vertex set - the vertex-to-face derive-up rule, + * also used to highlight faces while selecting vertices. + * + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Set selectedVertexIndices The selected vertex indices. + * @return Set The qualifying faces. + */ + fun facesWithAllVerticesSelected(triangleIndices: IntArray, selectedVertexIndices: Set): Set { + val faces = HashSet() + val triangleCount = triangleIndices.size / 3 + for (triangleIndex in 0 until triangleCount) { + if (verticesOfTriangle(triangleIndices, triangleIndex).all { vertexIndex -> vertexIndex in selectedVertexIndices }) { + faces.add(MeshElement.Face(triangleIndex)) + } + } + return faces + } + + /** + * The faces whose all three own edges are in the selected edge set - the edge-to-face derive-up rule, + * also used to highlight faces while selecting edges. Strict per Blender: a face whose vertices are + * merely covered by neighboring faces' selected edges does not qualify. + * + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Set selectedEdges The selected (canonical) edges. + * @return Set The qualifying faces. + */ + fun facesWithAllEdgesSelected(triangleIndices: IntArray, selectedEdges: Set): Set { + val faces = HashSet() + val triangleCount = triangleIndices.size / 3 + for (triangleIndex in 0 until triangleCount) { + if (edgesOfTriangle(triangleIndices, triangleIndex).all { edge -> edge in selectedEdges }) { + faces.add(MeshElement.Face(triangleIndex)) + } + } + return faces + } + + /** + * The per-vertex neighbor table of a triangle mesh: entry v lists the vertices sharing an edge with + * vertex v, deduplicated (an interior edge is shared by two triangles but yields one neighbor pair). + * Vertices outside every triangle (or an out-of-range index in a malformed list) get an empty entry. + * Build once per mesh and feed the connectivity walks below - Select Linked's flood fill and the + * Individual Origins island split. + * + * @param Int vertexCount The mesh's vertex count (the table's size). + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @return List The neighbor vertex indices per vertex. + */ + fun buildVertexAdjacency(vertexCount: Int, triangleIndices: IntArray): List { + val neighborSets = List(vertexCount) { HashSet() } + + fun connect(vertexA: Int, vertexB: Int) { + if (vertexA in 0 until vertexCount && vertexB in 0 until vertexCount && vertexA != vertexB) { + neighborSets[vertexA].add(vertexB) + neighborSets[vertexB].add(vertexA) + } + } + val triangleCount = triangleIndices.size / 3 + for (triangleIndex in 0 until triangleCount) { + val cornerA = triangleIndices[triangleIndex * 3] + val cornerB = triangleIndices[triangleIndex * 3 + 1] + val cornerC = triangleIndices[triangleIndex * 3 + 2] + connect(cornerA, cornerB) + connect(cornerB, cornerC) + connect(cornerC, cornerA) + } + return neighborSets.map { neighbors -> neighbors.toIntArray() } + } + + /** + * Every vertex connected to [seedVertexIndex] through the mesh's edges, the seed included - the flood + * fill behind Select Linked (Blender's L). An out-of-range seed yields an empty set. + * + * @param List adjacency The neighbor table from [buildVertexAdjacency]. + * @param Int seedVertexIndex The vertex to flood from. + * @return Set The seed's whole connected component. + */ + fun connectedVertices(adjacency: List, seedVertexIndex: Int): Set { + if (seedVertexIndex !in adjacency.indices) { + return emptySet() + } + val reached = HashSet() + val frontier = ArrayDeque() + reached.add(seedVertexIndex) + frontier.add(seedVertexIndex) + while (frontier.isNotEmpty()) { + val vertexIndex = frontier.removeFirst() + for (neighbor in adjacency[vertexIndex]) { + if (reached.add(neighbor)) { + frontier.add(neighbor) + } + } + } + return reached + } + + /** + * Splits a vertex subset into its connected islands: the components of the sub-graph induced on + * [vertexIndices] (two selected vertices join an island only when a mesh edge connects them within + * the subset). This is Blender's Individual Origins grouping - each island transforms about its own + * pivot. Out-of-range indices are dropped; the island order follows the subset's iteration order. + * + * @param List adjacency The neighbor table from [buildVertexAdjacency]. + * @param Set vertexIndices The vertex subset to split. + * @return List> The islands, each a disjoint subset of [vertexIndices]. + */ + fun selectionIslands(adjacency: List, vertexIndices: Set): List> { + val unvisited = vertexIndices.filterTo(LinkedHashSet()) { vertexIndex -> vertexIndex in adjacency.indices } + val islands = ArrayList>() + while (unvisited.isNotEmpty()) { + val seed = unvisited.first() + val island = HashSet() + val frontier = ArrayDeque() + island.add(seed) + unvisited.remove(seed) + frontier.add(seed) + while (frontier.isNotEmpty()) { + val vertexIndex = frontier.removeFirst() + for (neighbor in adjacency[vertexIndex]) { + if (neighbor in unvisited) { + unvisited.remove(neighbor) + island.add(neighbor) + frontier.add(neighbor) + } + } + } + islands.add(island) + } + return islands + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopologyEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopologyEdits.kt new file mode 100644 index 0000000..fe38448 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopologyEdits.kt @@ -0,0 +1,220 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.PuppetModel + +/** + * How one vertex of a topology-edited mesh derives its keyform deltas (and its glue identity) from the + * old mesh's vertices. A topology operation changes the vertex count, and every keyform cell's + * positionDeltas array is parallel to the positions (stride 2 * vertexCount) - so each NEW vertex must + * say where its per-cell deltas come from: + * + * - [FromOld] copies one old vertex's deltas verbatim (a kept or duplicated vertex). + * - [AverageOf] averages several old vertices' deltas (a merge's surviving vertex). + * - [LerpOf] interpolates two old vertices' deltas by t (a split point on an old edge). + * + * トポロジ編集後の各頂点が、旧頂点からどのようにキーフォームのデルタを引き継ぐかの指定。 + */ +sealed interface VertexSource { + /** + * The new vertex is old vertex [oldIndex], kept or duplicated: its deltas copy verbatim. + * + * @property Int oldIndex The old vertex the deltas copy from. + */ + data class FromOld(val oldIndex: Int) : VertexSource + + /** + * The new vertex merges several old vertices: its deltas are their per-cell mean. + * + * @property List oldIndices The merged old vertices. + */ + data class AverageOf(val oldIndices: List) : VertexSource + + /** + * The new vertex splits the old edge (oldA, oldB) at parameter [t]: its deltas lerp accordingly. + * + * @property Int oldA The edge's first old endpoint. + * @property Int oldB The edge's second old endpoint. + * @property Float t The split parameter (0 = at oldA, 1 = at oldB). + */ + data class LerpOf(val oldA: Int, val oldB: Int, val t: Float) : VertexSource +} + +/** + * One topology edit of one drawable's mesh, ready to commit: the complete replacement mesh (positions, + * uvs, and indices all sized to the new vertex count) plus one [VertexSource] per NEW vertex, from + * which [withMeshTopologyEdit] rebuilds every keyform cell's deltas and remaps the glue pairs. The op + * builders in MeshTopologyOps produce these; they never touch the model themselves. + * + * 1つの描画メッシュのトポロジ編集。置き換えメッシュと、新頂点ごとのデルタ導出指定を持つ。 + * + * @property DrawableMesh newMesh The replacement mesh (a freshly built instance). + * @property List vertexSources One source per new vertex, in vertex order. + */ +class MeshTopologyEdit( + val newMesh: DrawableMesh, + val vertexSources: List, +) + +/** + * Applies a topology edit to one drawable: swaps in the full replacement mesh, rebuilds EVERY keyform + * cell's positionDeltas to the new vertex count per the edit's [VertexSource]s (copy / average / lerp - + * so a parameter scrub after the edit still deforms sanely), and remaps the model's glue pairs through + * the old-to-new vertex mapping (a pair whose vertex was removed is dropped rather than left dangling). + * Everything else structurally shares with the receiver (the copy-on-write discipline). Returns the + * same instance when the drawable is missing, carries no mesh, or the edit's source list does not match + * its new mesh (a malformed edit must not corrupt the model). + * + * トポロジ編集の適用。メッシュ全体を差し替え、全キーフォームセルのデルタを新頂点数に再構築し、 + * グルー対も旧→新の対応で再マップする(消えた頂点の対は破棄)。 + * + * @param DrawableId id The drawable whose mesh the edit replaces. + * @param MeshTopologyEdit edit The edit to apply. + * @return PuppetModel The edited model, or this instance on a no-op. + */ +fun PuppetModel.withMeshTopologyEdit(id: DrawableId, edit: MeshTopologyEdit): PuppetModel { + val drawable = drawables.firstOrNull { candidate -> candidate.id == id } ?: return this + val oldMesh = drawable.mesh ?: return this + val newVertexCount = edit.newMesh.vertexCount + if (edit.vertexSources.size != newVertexCount) { + return this + } + + // Rebuild each geometry cell's deltas at the new stride, deriving per vertex from the old deltas. + // The channel tracks (multiply / screen tints, opacity, draw order, ...) carry no per-vertex data, so a + // topology edit leaves them untouched entirely - only the per-vertex geometry cells need this remap. + val newGeometry = + drawable.geometryGrid?.let { grid -> + KeyformGrid( + axes = grid.axes, + cells = + grid.cells.map { cell -> + KeyformCell(cell.coordinate, remapMeshDeltas(cell.form, edit.vertexSources, oldMesh.vertexCount)) + }, + ) + } + // Blend-shape forms are per-vertex too, so they need the same remap to the new vertex count; leaving + // them at the old count would silently zero every blend contribution after a topology edit. + val newBlendShapes = + drawable.blendShapes.map { binding -> + binding.copy( + forms = + binding.forms.map { form -> + form?.let { + MeshForm( + remapMeshDeltas(MeshDeltaForm(it.positionDeltas), edit.vertexSources, oldMesh.vertexCount).positionDeltas, + it.drawOrder, + it.opacity, + it.multiplyColor, + it.screenColor, + ) + } + }, + ) + } + + // The old-to-new vertex mapping glue remapping resolves through: a kept / duplicated / merged old + // vertex maps to the FIRST new vertex that claims it; an unclaimed old vertex maps to -1 (removed). + // First-claim is deliberate for duplicates: the kept originals (enumerated before the copies) claim + // their old indices, so a glue weld stays on the original and the copy floats free. + val oldToNewIndex = IntArray(oldMesh.vertexCount) { -1 } + edit.vertexSources.forEachIndexed { newIndex, source -> + when (source) { + is VertexSource.FromOld -> + if (source.oldIndex in 0 until oldMesh.vertexCount && oldToNewIndex[source.oldIndex] == -1) { + oldToNewIndex[source.oldIndex] = newIndex + } + + is VertexSource.AverageOf -> + for (oldIndex in source.oldIndices) { + if (oldIndex in 0 until oldMesh.vertexCount && oldToNewIndex[oldIndex] == -1) { + oldToNewIndex[oldIndex] = newIndex + } + } + + // A split point is a brand-new vertex; it claims no old identity. + is VertexSource.LerpOf -> {} + } + } + + val newDrawables = + drawables.map { candidate -> + if (candidate.id == id) { + candidate.copy(mesh = edit.newMesh, geometryGrid = newGeometry, blendShapes = newBlendShapes) + } else { + candidate + } + } + val newGlues = + glues.map { glue -> + if (glue.meshA != id && glue.meshB != id) { + glue + } else { + val remappedPairs = + glue.pairs.mapNotNull { pair -> + val newIndexA = if (glue.meshA == id) oldToNewIndex.getOrElse(pair.indexA) { -1 } else pair.indexA + val newIndexB = if (glue.meshB == id) oldToNewIndex.getOrElse(pair.indexB) { -1 } else pair.indexB + if (newIndexA < 0 || newIndexB < 0) { + // The welded vertex no longer exists: the pair is dropped, never left dangling. + null + } else { + GluePair(newIndexA, newIndexB, pair.weightA, pair.weightB) + } + } + glue.copy(pairs = remappedPairs) + } + } + return copy(drawables = newDrawables, glues = newGlues) +} + +/** + * Rebuilds one keyform cell's [MeshForm] at the new vertex count: each new vertex's delta pair copies, + * averages, or lerps from the old form's deltas per its [VertexSource]. An old index beyond the old + * form's array (a malformed grid) contributes zero, keeping the rebuild total. + * + * @param MeshForm form The old cell form (deltas at the old stride). + * @param List vertexSources One source per new vertex. + * @param Int oldVertexCount The old mesh's vertex count (bounds the old delta reads). + * @return MeshForm The rebuilt form (deltas at the new stride; drawOrder / opacity carried). + */ +private fun remapMeshDeltas(form: MeshDeltaForm, vertexSources: List, oldVertexCount: Int): MeshDeltaForm { + val oldDeltas = form.positionDeltas + + fun oldDeltaX(oldIndex: Int): Float = if (oldIndex in 0 until oldVertexCount && oldIndex * 2 < oldDeltas.size) oldDeltas[oldIndex * 2] else 0f + + fun oldDeltaY(oldIndex: Int): Float = if (oldIndex in 0 until oldVertexCount && oldIndex * 2 + 1 < oldDeltas.size) oldDeltas[oldIndex * 2 + 1] else 0f + val newDeltas = FloatArray(vertexSources.size * 2) + vertexSources.forEachIndexed { newIndex, source -> + when (source) { + is VertexSource.FromOld -> { + newDeltas[newIndex * 2] = oldDeltaX(source.oldIndex) + newDeltas[newIndex * 2 + 1] = oldDeltaY(source.oldIndex) + } + + is VertexSource.AverageOf -> { + if (source.oldIndices.isNotEmpty()) { + var sumX = 0f + var sumY = 0f + for (oldIndex in source.oldIndices) { + sumX += oldDeltaX(oldIndex) + sumY += oldDeltaY(oldIndex) + } + newDeltas[newIndex * 2] = sumX / source.oldIndices.size + newDeltas[newIndex * 2 + 1] = sumY / source.oldIndices.size + } + } + + is VertexSource.LerpOf -> { + newDeltas[newIndex * 2] = oldDeltaX(source.oldA) + (oldDeltaX(source.oldB) - oldDeltaX(source.oldA)) * source.t + newDeltas[newIndex * 2 + 1] = oldDeltaY(source.oldA) + (oldDeltaY(source.oldB) - oldDeltaY(source.oldA)) * source.t + } + } + } + return MeshDeltaForm(newDeltas) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopologyOps.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopologyOps.kt new file mode 100644 index 0000000..8d8c9da --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTopologyOps.kt @@ -0,0 +1,1232 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.storedToArtAffineForTile +import kotlin.math.abs + +/** + * How a free-placed Add Vertex samples atlas UVs when the live mesh has no faces (or no verts) left to + * lerp from — the wipe-and-rebuild path. Rest position → art UV via the tile's layer origin, then + * art → stored through the tile's affine. + * + * @property Float layerLeft Document-canvas x of the tile layer's top-left. + * @property Float layerTop Document-canvas y (down) of the tile layer's top-left. + * @property Float tileWidth Tile width in source pixels. + * @property Float tileHeight Tile height in source pixels. + * @property UvFrame? frame Stored↔art frame, or null when stored UVs already are art UVs. + */ +class FreeVertUvContext( + val layerLeft: Float, + val layerTop: Float, + val tileWidth: Float, + val tileHeight: Float, + val frame: UvFrame?, +) { + /** + * Stored UVs for a rest-space point on this drawable's art. + * + * @param Float x Rest x. + * @param Float y Rest y. + * @return Pair Stored (u, v). + */ + fun storedUvAt(x: Float, y: Float): Pair { + if (tileWidth <= 0f || tileHeight <= 0f) { + return 0f to 0f + } + val artU = (x - layerLeft) / tileWidth + val artV = (y - layerTop) / tileHeight + return frame?.pointFromFrame(artU, artV) ?: (artU to artV) + } +} + +/** + * Builds a [FreeVertUvContext] for [drawableId] from the model's atlas / source inventory, or null when + * the drawable has no recoverable tile. + * + * @param PuppetModel model The document model. + * @param DrawableId drawableId The drawable being rebuilt. + * @return FreeVertUvContext? The sampler, or null. + */ +fun freeVertUvContextOf(model: PuppetModel, drawableId: DrawableId): FreeVertUvContext? { + val drawable = model.drawables.firstOrNull { candidate -> candidate.id == drawableId } ?: return null + val tileId = drawable.atlasTileId ?: return null + val tile = model.atlas.tileById[tileId] ?: return null + val ref = tile.source + // Prefer the tile's bound layer; many retained tiles drop `source` on save, so fall back to a + // same-name / same-size inventory row (Bear_.uma's Jumper tile has no source but lyid:2 matches). + val layer = + ref?.let { sourceRef -> + model.sources + .firstOrNull { source -> source.id == sourceRef.sourceId } + ?.layers + ?.firstOrNull { row -> row.key == sourceRef.layerKey } + } + ?: model.sources + .asSequence() + .flatMap { source -> source.layers.asSequence() } + .firstOrNull { row -> + (row.name == tile.name || row.name == drawable.name) && + row.width == tile.width && + row.height == tile.height + } + val storedToArt = model.atlas.storedToArtAffineForTile(tileId) + val artToStored = storedToArt?.let { affine -> invertUvAffine(affine) } + val frame = + if (storedToArt != null && artToStored != null) { + UvFrame(storedToArt, artToStored) + } else { + null + } + return FreeVertUvContext( + layerLeft = layer?.left?.toFloat() ?: 0f, + layerTop = layer?.top?.toFloat() ?: 0f, + tileWidth = tile.width.toFloat(), + tileHeight = tile.height.toFloat(), + frame = frame, + ) +} + +/** + * Where a merge's surviving vertex lands (Blender's Merge menu): the merged vertices' centroid, or the + * first / last vertex of the selection order. + * + * マージ後の頂点の位置(中心・最初・最後)。 + */ +enum class MergeTarget { + AtCenter, + AtFirst, + AtLast, +} + +/** + * One topology operation's outcome, ready for the session to commit: the mesh edit plus the elements + * that should be selected afterwards (the duplicated copies, the merge survivor, the rip copies, the + * cut path). Null from a builder means the operation refused (nothing applicable, or a degenerate + * geometry it will not guess at). + * + * トポロジ操作の結果。適用する編集と、操作後に選択される要素。 + * + * @property MeshTopologyEdit edit The mesh edit to commit. + * @property Set newElements The elements selected after the edit (the new topology's ids). + */ +class TopologyOpResult( + val edit: MeshTopologyEdit, + val newElements: Set, +) + +/** + * Pure builders for the topology operations (Shift+D duplicate, M merge, V rip, J connect, insert on + * edge): each reads one mesh and produces a [TopologyOpResult] for [withMeshTopologyEdit] to commit, or + * null to refuse. + * They never touch the model - the session's commitMeshTopology is the single mutation path. + * + * トポロジ操作の純粋な構築関数。モデルには触れず、編集内容と新しい選択を返す。 + */ +object MeshTopologyOps { + /** + * Duplicates the covered vertices (and every face fully covered by them) in place: the copies append + * after the existing vertices, keyform deltas copy per vertex, and the new selection is the copies - + * ready for the auto-grab that follows a Blender Shift+D. Refuses (null) when nothing is covered. + * + * The induced subgraph is faces-only by data model: DrawableMesh is triangles-only, so a fully + * covered EDGE whose triangles have an uncovered third corner has no representation of its own and + * is deliberately not carried - duplicating two adjacent vertices yields two unconnected points + * (an accepted limitation; Blender would carry the edge because its meshes store edges as + * first-class elements). + * + * Glue note: a duplicated vertex's glue pair stays welded to the ORIGINAL vertex, never the copy - + * the old-to-new remap in withMeshTopologyEdit is first-claim, and the kept original (enumerated + * before the copies) claims its old index first. That matches Shift+D expectations (the copy is a + * free floating clone). + * + * @param DrawableMesh mesh The mesh to duplicate within. + * @param Set coveredVertices The vertices the selection covers. + * @return TopologyOpResult? The edit + the copies as the new selection, or null. + */ + fun duplicateElements(mesh: DrawableMesh, coveredVertices: Set): TopologyOpResult? { + val orderedCovered = coveredVertices.filter { vertexIndex -> vertexIndex in 0 until mesh.vertexCount }.sorted() + if (orderedCovered.isEmpty()) { + return null + } + val oldCount = mesh.vertexCount + val copyIndexByOld = HashMap(orderedCovered.size) + orderedCovered.forEachIndexed { copyOrdinal, oldIndex -> copyIndexByOld[oldIndex] = oldCount + copyOrdinal } + + val newCount = oldCount + orderedCovered.size + val newPositions = FloatArray(newCount * 2) + val newUvs = FloatArray(newCount * 2) + mesh.positions.copyInto(newPositions) + mesh.uvs.copyInto(newUvs, endIndex = minOf(mesh.uvs.size, newUvs.size)) + orderedCovered.forEachIndexed { copyOrdinal, oldIndex -> + val newIndex = oldCount + copyOrdinal + newPositions[newIndex * 2] = mesh.positions[oldIndex * 2] + newPositions[newIndex * 2 + 1] = mesh.positions[oldIndex * 2 + 1] + if (oldIndex * 2 + 1 < mesh.uvs.size) { + newUvs[newIndex * 2] = mesh.uvs[oldIndex * 2] + newUvs[newIndex * 2 + 1] = mesh.uvs[oldIndex * 2 + 1] + } + } + + // Faces whose three corners are all covered duplicate too, over the copied vertices. + val copiedTriangles = ArrayList() + val triangleCount = mesh.indices.size / 3 + for (triangleIndex in 0 until triangleCount) { + val cornerA = mesh.indices[triangleIndex * 3] + val cornerB = mesh.indices[triangleIndex * 3 + 1] + val cornerC = mesh.indices[triangleIndex * 3 + 2] + if (cornerA in copyIndexByOld && cornerB in copyIndexByOld && cornerC in copyIndexByOld) { + copiedTriangles.add(copyIndexByOld.getValue(cornerA)) + copiedTriangles.add(copyIndexByOld.getValue(cornerB)) + copiedTriangles.add(copyIndexByOld.getValue(cornerC)) + } + } + val newIndices = mesh.indices + copiedTriangles.toIntArray() + + val sources = ArrayList(newCount) + for (oldIndex in 0 until oldCount) { + sources.add(VertexSource.FromOld(oldIndex)) + } + for (oldIndex in orderedCovered) { + sources.add(VertexSource.FromOld(oldIndex)) + } + val newElements = copyIndexByOld.values.map { copyIndex -> MeshElement.Vertex(copyIndex) }.toSet() + return TopologyOpResult(MeshTopologyEdit(DrawableMesh(newPositions, newUvs, newIndices), sources), newElements) + } + + /** + * Merges the given vertices into one survivor (Blender's M): AtCenter lands on their centroid with + * averaged keyform deltas and UVs; AtFirst / AtLast keep the first / last vertex of the selection + * order verbatim. Unmerged vertices keep their order (so their indices only shift down); the + * survivor appends last. Triangles remap onto the survivor and degenerate ones (fewer than three + * distinct corners) drop. Refuses (null) with fewer than two vertices. + * + * @param DrawableMesh mesh The mesh to merge within. + * @param List orderedVertices The vertices to merge, in selection order (first / last matter). + * @param MergeTarget target Where the survivor lands. + * @return TopologyOpResult? The edit + the survivor as the new selection, or null. + */ + fun mergeVertices(mesh: DrawableMesh, orderedVertices: List, target: MergeTarget): TopologyOpResult? { + val merged = orderedVertices.filter { vertexIndex -> vertexIndex in 0 until mesh.vertexCount }.distinct() + if (merged.size < 2) { + return null + } + val mergedSet = merged.toSet() + val oldCount = mesh.vertexCount + val keptOld = (0 until oldCount).filter { oldIndex -> oldIndex !in mergedSet } + val survivorIndex = keptOld.size + val newCount = keptOld.size + 1 + + val oldToNew = IntArray(oldCount) { -1 } + keptOld.forEachIndexed { newIndex, oldIndex -> oldToNew[oldIndex] = newIndex } + for (oldIndex in merged) { + oldToNew[oldIndex] = survivorIndex + } + + val newPositions = FloatArray(newCount * 2) + val newUvs = FloatArray(newCount * 2) + + fun uvX(oldIndex: Int): Float = if (oldIndex * 2 < mesh.uvs.size) mesh.uvs[oldIndex * 2] else 0f + + fun uvY(oldIndex: Int): Float = if (oldIndex * 2 + 1 < mesh.uvs.size) mesh.uvs[oldIndex * 2 + 1] else 0f + keptOld.forEachIndexed { newIndex, oldIndex -> + newPositions[newIndex * 2] = mesh.positions[oldIndex * 2] + newPositions[newIndex * 2 + 1] = mesh.positions[oldIndex * 2 + 1] + newUvs[newIndex * 2] = uvX(oldIndex) + newUvs[newIndex * 2 + 1] = uvY(oldIndex) + } + val survivorSource: VertexSource + when (target) { + MergeTarget.AtCenter -> { + var sumX = 0f + var sumY = 0f + var sumU = 0f + var sumV = 0f + for (oldIndex in merged) { + sumX += mesh.positions[oldIndex * 2] + sumY += mesh.positions[oldIndex * 2 + 1] + sumU += uvX(oldIndex) + sumV += uvY(oldIndex) + } + newPositions[survivorIndex * 2] = sumX / merged.size + newPositions[survivorIndex * 2 + 1] = sumY / merged.size + newUvs[survivorIndex * 2] = sumU / merged.size + newUvs[survivorIndex * 2 + 1] = sumV / merged.size + survivorSource = VertexSource.AverageOf(merged) + } + + MergeTarget.AtFirst, MergeTarget.AtLast -> { + val keeper = if (target == MergeTarget.AtFirst) merged.first() else merged.last() + newPositions[survivorIndex * 2] = mesh.positions[keeper * 2] + newPositions[survivorIndex * 2 + 1] = mesh.positions[keeper * 2 + 1] + newUvs[survivorIndex * 2] = uvX(keeper) + newUvs[survivorIndex * 2 + 1] = uvY(keeper) + survivorSource = VertexSource.FromOld(keeper) + } + } + + // Remap the triangles onto the survivor, dropping the ones the merge degenerates. + val newIndices = ArrayList(mesh.indices.size) + val triangleCount = mesh.indices.size / 3 + for (triangleIndex in 0 until triangleCount) { + val cornerA = oldToNew[mesh.indices[triangleIndex * 3]] + val cornerB = oldToNew[mesh.indices[triangleIndex * 3 + 1]] + val cornerC = oldToNew[mesh.indices[triangleIndex * 3 + 2]] + if (cornerA != cornerB && cornerB != cornerC && cornerC != cornerA) { + newIndices.add(cornerA) + newIndices.add(cornerB) + newIndices.add(cornerC) + } + } + + val sources = ArrayList(newCount) + for (oldIndex in keptOld) { + sources.add(VertexSource.FromOld(oldIndex)) + } + sources.add(survivorSource) + return TopologyOpResult( + MeshTopologyEdit(DrawableMesh(newPositions, newUvs, newIndices.toIntArray()), sources), + setOf(MeshElement.Vertex(survivorIndex)), + ) + } + + /** + * Rips the covered vertices apart (Blender's V): each covered vertex that sits between triangle fans + * is duplicated, and the adjacent triangles the caller marks (the cursor's side) re-point at the + * copy - so the following grab pulls that side away, opening a seam. Refuses (null) when no + * triangle actually re-points (every covered vertex was surrounded by unmarked triangles or has no + * fan to split). + * + * @param DrawableMesh mesh The mesh to rip within. + * @param Set coveredVertices The vertices the selection covers. + * @param Function triangleTakesCopy True when the triangle ordinal should follow the ripped copies + * (the overlay marks the triangles on the pointer's side). + * @return TopologyOpResult? The edit + the copies as the new selection, or null. + */ + fun ripElements(mesh: DrawableMesh, coveredVertices: Set, triangleTakesCopy: (Int) -> Boolean): TopologyOpResult? { + val orderedCovered = coveredVertices.filter { vertexIndex -> vertexIndex in 0 until mesh.vertexCount }.sorted() + if (orderedCovered.isEmpty()) { + return null + } + val oldCount = mesh.vertexCount + val triangleCount = mesh.indices.size / 3 + // A vertex rips only when its fan splits: at least one adjacent triangle on each side. + val copyIndexByOld = LinkedHashMap() + for (oldIndex in orderedCovered) { + var marked = 0 + var unmarked = 0 + for (triangleIndex in 0 until triangleCount) { + val hasCorner = + mesh.indices[triangleIndex * 3] == oldIndex || + mesh.indices[triangleIndex * 3 + 1] == oldIndex || + mesh.indices[triangleIndex * 3 + 2] == oldIndex + if (hasCorner) { + if (triangleTakesCopy(triangleIndex)) { + marked++ + } else { + unmarked++ + } + } + } + if (marked > 0 && unmarked > 0) { + copyIndexByOld[oldIndex] = oldCount + copyIndexByOld.size + } + } + if (copyIndexByOld.isEmpty()) { + return null + } + + val newCount = oldCount + copyIndexByOld.size + val newPositions = FloatArray(newCount * 2) + val newUvs = FloatArray(newCount * 2) + mesh.positions.copyInto(newPositions) + mesh.uvs.copyInto(newUvs, endIndex = minOf(mesh.uvs.size, newUvs.size)) + for ((oldIndex, copyIndex) in copyIndexByOld) { + newPositions[copyIndex * 2] = mesh.positions[oldIndex * 2] + newPositions[copyIndex * 2 + 1] = mesh.positions[oldIndex * 2 + 1] + if (oldIndex * 2 + 1 < mesh.uvs.size) { + newUvs[copyIndex * 2] = mesh.uvs[oldIndex * 2] + newUvs[copyIndex * 2 + 1] = mesh.uvs[oldIndex * 2 + 1] + } + } + val newIndices = mesh.indices.copyOf() + for (triangleIndex in 0 until triangleCount) { + if (!triangleTakesCopy(triangleIndex)) { + continue + } + for (cornerSlot in 0 until 3) { + val copyIndex = copyIndexByOld[newIndices[triangleIndex * 3 + cornerSlot]] + if (copyIndex != null) { + newIndices[triangleIndex * 3 + cornerSlot] = copyIndex + } + } + } + + val sources = ArrayList(newCount) + for (oldIndex in 0 until oldCount) { + sources.add(VertexSource.FromOld(oldIndex)) + } + for (oldIndex in copyIndexByOld.keys) { + sources.add(VertexSource.FromOld(oldIndex)) + } + val newElements = copyIndexByOld.values.map { copyIndex -> MeshElement.Vertex(copyIndex) }.toSet() + return TopologyOpResult(MeshTopologyEdit(DrawableMesh(newPositions, newUvs, newIndices), sources), newElements) + } + + /** + * Connects two vertices with a cut (Blender's J): walks the straight segment between them, splits + * every edge it properly crosses (a new lerped vertex per crossing), and retriangulates the crossed + * triangles so the cut becomes real edges. Deliberately strict: refuses (null) when the vertices + * already share an edge, when the segment crosses nothing, or when any crossed triangle's crossing + * pattern is degenerate (a collinear graze, an on-vertex hit, more than two crossings) - a refusal + * with a notice always beats emitting a broken mesh. + * + * @param DrawableMesh mesh The mesh to cut within. + * @param Int vertexA The cut's first endpoint. + * @param Int vertexB The cut's second endpoint. + * @return TopologyOpResult? The edit + the cut path as the new selection, or null. + */ + fun connectVertices(mesh: DrawableMesh, vertexA: Int, vertexB: Int): TopologyOpResult? { + val vertexCount = mesh.vertexCount + if (vertexA == vertexB || vertexA !in 0 until vertexCount || vertexB !in 0 until vertexCount) { + return null + } + if (MeshTopology.uniqueEdges(mesh.indices).contains(MeshElement.Edge.of(vertexA, vertexB))) { + return null + } + val startX = mesh.positions[vertexA * 2] + val startY = mesh.positions[vertexA * 2 + 1] + val endX = mesh.positions[vertexB * 2] + val endY = mesh.positions[vertexB * 2 + 1] + + // One crossing per unique edge, shared by both triangles on that edge. + val crossingByEdge = LinkedHashMap() + val crossingSources = ArrayList() + val oldCount = vertexCount + for (edge in MeshTopology.uniqueEdges(mesh.indices)) { + if (edge.endpointLow == vertexA || edge.endpointLow == vertexB || edge.endpointHigh == vertexA || edge.endpointHigh == vertexB) { + continue + } + val crossing = + properSegmentCrossing( + startX, + startY, + endX, + endY, + mesh.positions[edge.endpointLow * 2], + mesh.positions[edge.endpointLow * 2 + 1], + mesh.positions[edge.endpointHigh * 2], + mesh.positions[edge.endpointHigh * 2 + 1], + ) ?: continue + crossingByEdge[edge] = oldCount + crossingSources.size + crossingSources.add(VertexSource.LerpOf(edge.endpointLow, edge.endpointHigh, crossing)) + } + if (crossingByEdge.isEmpty()) { + return null + } + + val newCount = oldCount + crossingSources.size + val newPositions = FloatArray(newCount * 2) + val newUvs = FloatArray(newCount * 2) + mesh.positions.copyInto(newPositions) + mesh.uvs.copyInto(newUvs, endIndex = minOf(mesh.uvs.size, newUvs.size)) + crossingSources.forEachIndexed { crossingOrdinal, source -> + val newIndex = oldCount + crossingOrdinal + val t = source.t + newPositions[newIndex * 2] = mesh.positions[source.oldA * 2] + (mesh.positions[source.oldB * 2] - mesh.positions[source.oldA * 2]) * t + newPositions[newIndex * 2 + 1] = + mesh.positions[source.oldA * 2 + 1] + (mesh.positions[source.oldB * 2 + 1] - mesh.positions[source.oldA * 2 + 1]) * t + if (source.oldA * 2 + 1 < mesh.uvs.size && source.oldB * 2 + 1 < mesh.uvs.size) { + newUvs[newIndex * 2] = mesh.uvs[source.oldA * 2] + (mesh.uvs[source.oldB * 2] - mesh.uvs[source.oldA * 2]) * t + newUvs[newIndex * 2 + 1] = mesh.uvs[source.oldA * 2 + 1] + (mesh.uvs[source.oldB * 2 + 1] - mesh.uvs[source.oldA * 2 + 1]) * t + } + } + + // Retriangulate the crossed triangles; refuse on any pattern the split rules do not cover. + val newIndices = ArrayList(mesh.indices.size + crossingSources.size * 6) + val triangleCount = mesh.indices.size / 3 + for (triangleIndex in 0 until triangleCount) { + val corners = intArrayOf(mesh.indices[triangleIndex * 3], mesh.indices[triangleIndex * 3 + 1], mesh.indices[triangleIndex * 3 + 2]) + val crossedSlots = ArrayList(2) + val crossingIndices = ArrayList(2) + for (cornerSlot in 0 until 3) { + val edge = MeshElement.Edge.of(corners[cornerSlot], corners[(cornerSlot + 1) % 3]) + val crossingIndex = crossingByEdge[edge] + if (crossingIndex != null) { + crossedSlots.add(cornerSlot) + crossingIndices.add(crossingIndex) + } + } + val hasEndpointCorner = corners.contains(vertexA) || corners.contains(vertexB) + when { + crossedSlots.isEmpty() -> { + newIndices.add(corners[0]) + newIndices.add(corners[1]) + newIndices.add(corners[2]) + } + + // The cut enters at an endpoint corner and exits through the opposite edge: a two-way fan. + crossedSlots.size == 1 && hasEndpointCorner -> { + val slot = crossedSlots[0] + val crossing = crossingIndices[0] + val apex = corners[(slot + 2) % 3] + if (apex != vertexA && apex != vertexB) { + // The crossing sits on an edge whose opposite corner is not the endpoint - a graze the + // split rules do not cover. + return null + } + newIndices.add(apex) + newIndices.add(corners[slot]) + newIndices.add(crossing) + newIndices.add(apex) + newIndices.add(crossing) + newIndices.add(corners[(slot + 1) % 3]) + } + + // The cut passes straight through: two crossed edges sharing a corner - one triangle at that + // corner plus a fan over the remaining quad. + crossedSlots.size == 2 -> { + val slotFirst = crossedSlots[0] + val slotSecond = crossedSlots[1] + val crossingFirst = crossingIndices[0] + val crossingSecond = crossingIndices[1] + // The corner both crossed edges share. + val sharedCorner = + when { + slotFirst == 0 && slotSecond == 1 -> 1 + slotFirst == 1 && slotSecond == 2 -> 2 + slotFirst == 0 && slotSecond == 2 -> 0 + else -> return null + } + val previousCorner = corners[(sharedCorner + 2) % 3] + val nextCorner = corners[(sharedCorner + 1) % 3] + // Crossing on the edge ENTERING the shared corner vs LEAVING it, in winding order. + val entering = + if (slotFirst == (sharedCorner + 2) % 3) { + crossingFirst + } else if (slotSecond == (sharedCorner + 2) % 3) { + crossingSecond + } else { + -1 + } + val leaving = + if (slotFirst == sharedCorner) { + crossingFirst + } else if (slotSecond == sharedCorner) { + crossingSecond + } else { + -1 + } + if (entering < 0 || leaving < 0) { + return null + } + newIndices.add(corners[sharedCorner]) + newIndices.add(leaving) + newIndices.add(entering) + newIndices.add(entering) + newIndices.add(leaving) + newIndices.add(nextCorner) + newIndices.add(entering) + newIndices.add(nextCorner) + newIndices.add(previousCorner) + } + + else -> return null + } + } + + val sources = ArrayList(newCount) + for (oldIndex in 0 until oldCount) { + sources.add(VertexSource.FromOld(oldIndex)) + } + sources.addAll(crossingSources) + val newElements = + buildSet { + add(MeshElement.Vertex(vertexA)) + add(MeshElement.Vertex(vertexB)) + for (crossingIndex in crossingByEdge.values) { + add(MeshElement.Vertex(crossingIndex)) + } + } + return TopologyOpResult(MeshTopologyEdit(DrawableMesh(newPositions, newUvs, newIndices.toIntArray()), sources), newElements) + } + + /** + * Inserts a vertex on each given edge at the supplied parameter and retriangulates every triangle + * that used that edge into two. Parameters clamp into `(ε, 1−ε)` so the new vertex never coincides + * with an endpoint. Refuses (null) when [splits] is empty or every edge is missing from the mesh. + * + * @param DrawableMesh mesh The mesh to split within. + * @param List splits Edges and split parameters (0 at endpointLow, 1 at endpointHigh). + * @return TopologyOpResult? The edit + the new vertices selected, or null. + */ + fun insertVerticesOnEdges(mesh: DrawableMesh, splits: List>): TopologyOpResult? { + if (splits.isEmpty()) { + return null + } + val existingEdges = MeshTopology.uniqueEdges(mesh.indices).toSet() + val uniqueSplits = LinkedHashMap() + for ((edge, rawT) in splits) { + if (edge !in existingEdges) { + continue + } + val t = rawT.coerceIn(1e-4f, 1f - 1e-4f) + uniqueSplits.putIfAbsent(edge, t) + } + if (uniqueSplits.isEmpty()) { + return null + } + val oldCount = mesh.vertexCount + val newIndexByEdge = LinkedHashMap(uniqueSplits.size) + val lerpSources = ArrayList(uniqueSplits.size) + uniqueSplits.entries.forEachIndexed { ordinal, (edge, t) -> + newIndexByEdge[edge] = oldCount + ordinal + lerpSources.add(VertexSource.LerpOf(edge.endpointLow, edge.endpointHigh, t)) + } + val newCount = oldCount + lerpSources.size + val newPositions = FloatArray(newCount * 2) + val newUvs = FloatArray(newCount * 2) + mesh.positions.copyInto(newPositions) + mesh.uvs.copyInto(newUvs, endIndex = minOf(mesh.uvs.size, newUvs.size)) + lerpSources.forEachIndexed { ordinal, source -> + val newIndex = oldCount + ordinal + val t = source.t + newPositions[newIndex * 2] = + mesh.positions[source.oldA * 2] + (mesh.positions[source.oldB * 2] - mesh.positions[source.oldA * 2]) * t + newPositions[newIndex * 2 + 1] = + mesh.positions[source.oldA * 2 + 1] + (mesh.positions[source.oldB * 2 + 1] - mesh.positions[source.oldA * 2 + 1]) * t + if (source.oldA * 2 + 1 < mesh.uvs.size && source.oldB * 2 + 1 < mesh.uvs.size) { + newUvs[newIndex * 2] = mesh.uvs[source.oldA * 2] + (mesh.uvs[source.oldB * 2] - mesh.uvs[source.oldA * 2]) * t + newUvs[newIndex * 2 + 1] = + mesh.uvs[source.oldA * 2 + 1] + (mesh.uvs[source.oldB * 2 + 1] - mesh.uvs[source.oldA * 2 + 1]) * t + } + } + val newIndices = ArrayList(mesh.indices.size + uniqueSplits.size * 3) + val triangleCount = mesh.indices.size / 3 + for (triangleIndex in 0 until triangleCount) { + val a = mesh.indices[triangleIndex * 3] + val b = mesh.indices[triangleIndex * 3 + 1] + val c = mesh.indices[triangleIndex * 3 + 2] + val edgeAb = MeshElement.Edge.of(a, b) + val edgeBc = MeshElement.Edge.of(b, c) + val edgeCa = MeshElement.Edge.of(c, a) + val splitAb = newIndexByEdge[edgeAb] + val splitBc = newIndexByEdge[edgeBc] + val splitCa = newIndexByEdge[edgeCa] + val splitCount = listOfNotNull(splitAb, splitBc, splitCa).size + when (splitCount) { + 0 -> { + newIndices.add(a) + newIndices.add(b) + newIndices.add(c) + } + 1 -> { + // One edge split: fan the opposite corner through the new vertex. + when { + splitAb != null -> { + newIndices.add(a) + newIndices.add(splitAb) + newIndices.add(c) + newIndices.add(splitAb) + newIndices.add(b) + newIndices.add(c) + } + splitBc != null -> { + newIndices.add(a) + newIndices.add(b) + newIndices.add(splitBc) + newIndices.add(a) + newIndices.add(splitBc) + newIndices.add(c) + } + else -> { + val split = splitCa!! + newIndices.add(a) + newIndices.add(b) + newIndices.add(split) + newIndices.add(split) + newIndices.add(b) + newIndices.add(c) + } + } + } + else -> { + // Two or three edges of one triangle split in one op: keep a watertight fan. + val midAb = splitAb ?: -1 + val midBc = splitBc ?: -1 + val midCa = splitCa ?: -1 + if (midAb >= 0 && midBc >= 0 && midCa >= 0) { + newIndices.addAll(listOf(a, midAb, midCa, midAb, b, midBc, midCa, midBc, c, midAb, midBc, midCa)) + } else if (midAb >= 0 && midBc >= 0) { + newIndices.addAll(listOf(a, midAb, c, midAb, b, midBc, midAb, midBc, c)) + } else if (midBc >= 0 && midCa >= 0) { + newIndices.addAll(listOf(a, b, midBc, a, midBc, midCa, midCa, midBc, c)) + } else { + newIndices.addAll(listOf(a, midAb, midCa, midAb, b, c, midAb, c, midCa)) + } + } + } + } + val sources = ArrayList(newCount) + for (oldIndex in 0 until oldCount) { + sources.add(VertexSource.FromOld(oldIndex)) + } + sources.addAll(lerpSources) + val newElements = newIndexByEdge.values.map { index -> MeshElement.Vertex(index) }.toSet() + return TopologyOpResult(MeshTopologyEdit(DrawableMesh(newPositions, newUvs, newIndices.toIntArray()), sources), newElements) + } + + /** + * Deletes the given vertices and every triangle that used them, compacting the survivors in place. + * Refuses (null) when [vertexIndices] is empty or none of them exist on the mesh. + * + * @param DrawableMesh mesh The mesh to delete within. + * @param Collection vertexIndices The vertex indices to remove. + * @return TopologyOpResult? The edit + an empty selection, or null. + */ + fun deleteVertices(mesh: DrawableMesh, vertexIndices: Collection): TopologyOpResult? { + val removed = vertexIndices.filter { index -> index in 0 until mesh.vertexCount }.toSet() + if (removed.isEmpty()) { + return null + } + val oldCount = mesh.vertexCount + val keptOld = (0 until oldCount).filter { oldIndex -> oldIndex !in removed } + val oldToNew = IntArray(oldCount) { -1 } + keptOld.forEachIndexed { newIndex, oldIndex -> oldToNew[oldIndex] = newIndex } + val newCount = keptOld.size + val newPositions = FloatArray(newCount * 2) + val newUvs = FloatArray(newCount * 2) + keptOld.forEachIndexed { newIndex, oldIndex -> + newPositions[newIndex * 2] = mesh.positions[oldIndex * 2] + newPositions[newIndex * 2 + 1] = mesh.positions[oldIndex * 2 + 1] + if (oldIndex * 2 + 1 < mesh.uvs.size) { + newUvs[newIndex * 2] = mesh.uvs[oldIndex * 2] + newUvs[newIndex * 2 + 1] = mesh.uvs[oldIndex * 2 + 1] + } + } + val newIndices = ArrayList(mesh.indices.size) + val triangleCount = mesh.indices.size / 3 + for (triangleIndex in 0 until triangleCount) { + val a = mesh.indices[triangleIndex * 3] + val b = mesh.indices[triangleIndex * 3 + 1] + val c = mesh.indices[triangleIndex * 3 + 2] + if (a in removed || b in removed || c in removed) { + continue + } + newIndices.add(oldToNew[a]) + newIndices.add(oldToNew[b]) + newIndices.add(oldToNew[c]) + } + val sources = keptOld.map { oldIndex -> VertexSource.FromOld(oldIndex) } + return TopologyOpResult( + MeshTopologyEdit(DrawableMesh(newPositions, newUvs, newIndices.toIntArray()), sources), + emptySet(), + ) + } + + /** + * Applies a Cubism-style Add Vertex draft against [mesh]: edge-snapped verts split edges, free floats + * append, closed draft triangles become faces, and remaining draft edges knife-connect. Sources on + * the final edit are relative to [mesh] (the pre-draft mesh). Refuses (null) when nothing changes. + * + * @param DrawableMesh mesh The pre-draft mesh. + * @param List draftVerts Staged floating verts. + * @param List draftEdges Staged edges between draft / existing endpoints. + * @param FreeVertUvContext? uvContext Legacy art→UV fallback when [mesh] is empty and no [uvSeedMesh] + * is available; wipe-and-rebuild prefers [uvSeedMesh] / [MeshUvField]. + * @param DrawableMesh? uvSeedMesh Edit-enter mesh projected via [MeshUvField] when [mesh] is empty. + * @return TopologyOpResult? The edit + new verts selected, or null. + */ + fun applyAddVertexDraft( + mesh: DrawableMesh, + draftVerts: List, + draftEdges: List, + uvContext: FreeVertUvContext? = null, + uvSeedMesh: DrawableMesh? = null, + ): TopologyOpResult? { + if (draftVerts.isEmpty() && draftEdges.isEmpty()) { + return null + } + // Three (or more) clicks in a chain only create n-1 edges; Cubism still fills on confirm when the + // path can close. Auto-close Draft(0)…Draft(n-1) so Enter after a drawn triangle makes a face. + val closedDraftEdges = autoCloseDraftPolyline(draftVerts, draftEdges) + val originalCount = mesh.vertexCount + var working = mesh + val draftToFinal = IntArray(draftVerts.size) { -1 } + val selected = LinkedHashSet() + // Sources for verts appended after [originalCount], keyed by final index, relative to [mesh]. + val appendedSources = HashMap() + + val snapByEdge = LinkedHashMap>() + for ((draftIndex, vert) in draftVerts.withIndex()) { + val edge = vert.snapEdge ?: continue + snapByEdge.putIfAbsent(edge, draftIndex to vert.snapT.coerceIn(1e-4f, 1f - 1e-4f)) + } + if (snapByEdge.isNotEmpty()) { + // Only split edges that still exist; stale snaps (faces deleted under them) demote to free + // floats below instead of aborting the whole Accept. + val liveEdges = MeshTopology.uniqueEdges(working.indices).toSet() + val validSnaps = snapByEdge.filter { (edge, _) -> edge in liveEdges } + if (validSnaps.isNotEmpty()) { + val splits = validSnaps.map { (edge, pair) -> edge to pair.second } + val countBefore = working.vertexCount + val inserted = insertVerticesOnEdges(working, splits) + if (inserted != null) { + working = inserted.edit.newMesh + validSnaps.entries.forEachIndexed { ordinal, (edge, pair) -> + val newIndex = countBefore + ordinal + draftToFinal[pair.first] = newIndex + selected.add(MeshElement.Vertex(newIndex)) + appendedSources[newIndex] = VertexSource.LerpOf(edge.endpointLow, edge.endpointHigh, pair.second) + } + } + } + } + + for ((draftIndex, vert) in draftVerts.withIndex()) { + if (draftToFinal[draftIndex] >= 0) { + continue + } + val (uvU, uvV, source) = sampleUvAndSource(mesh, vert.x, vert.y, uvContext, uvSeedMesh) + val newIndex = working.vertexCount + draftToFinal[draftIndex] = newIndex + selected.add(MeshElement.Vertex(newIndex)) + appendedSources[newIndex] = source + val newPositions = working.positions.copyOf(working.positions.size + 2) + val newUvs = working.uvs.copyOf(maxOf(working.uvs.size + 2, (newIndex + 1) * 2)) + newPositions[newIndex * 2] = vert.x + newPositions[newIndex * 2 + 1] = vert.y + newUvs[newIndex * 2] = uvU + newUvs[newIndex * 2 + 1] = uvV + working = DrawableMesh(newPositions, newUvs, working.indices.copyOf()) + } + + fun resolve(endpoint: DraftEndpoint): Int? = + when (endpoint) { + is DraftEndpoint.Existing -> + endpoint.vertexIndex.takeIf { index -> index in 0 until working.vertexCount } + is DraftEndpoint.Draft -> + draftToFinal.getOrNull(endpoint.index)?.takeIf { index -> index >= 0 } + } + + val resolvedEdges = LinkedHashSet() + for (edge in closedDraftEdges) { + val a = resolve(edge.a) ?: continue + val b = resolve(edge.b) ?: continue + if (a != b) { + resolvedEdges.add(MeshElement.Edge.of(a, b)) + } + } + + // Faces: only empty chordless triangles (three edges in mesh∪draft, positive area, no + // crossing of existing mesh edges, centroid not inside an existing face). No auto-close, + // no n-gon fan — those invented overlapping / exterior faces. + val meshEdges = MeshTopology.uniqueEdges(working.indices).toSet() + val coveredEdges = + HashSet(meshEdges.size + resolvedEdges.size).apply { + addAll(meshEdges) + addAll(resolvedEdges) + } + val neighbors = HashMap>() + for (edge in coveredEdges) { + neighbors.getOrPut(edge.endpointLow) { HashSet() }.add(edge.endpointHigh) + neighbors.getOrPut(edge.endpointHigh) { HashSet() }.add(edge.endpointLow) + } + val newIndices = working.indices.toMutableList() + val existingFaces = HashSet>() + for (tri in 0 until newIndices.size / 3) { + existingFaces.add(setOf(newIndices[tri * 3], newIndices[tri * 3 + 1], newIndices[tri * 3 + 2])) + } + + fun appendFace(a: Int, b: Int, c: Int) { + val ab = MeshElement.Edge.of(a, b) + val bc = MeshElement.Edge.of(b, c) + val ca = MeshElement.Edge.of(c, a) + val pureDraft = ab in resolvedEdges && bc in resolvedEdges && ca in resolvedEdges + if (!canFillTriangle(a, b, c, working.positions, newIndices, existingFaces, meshEdges, pureDraft)) { + return + } + existingFaces.add(setOf(a, b, c)) + val ax = working.positions[a * 2] + val ay = working.positions[a * 2 + 1] + val bx = working.positions[b * 2] + val by = working.positions[b * 2 + 1] + val cx = working.positions[c * 2] + val cy = working.positions[c * 2 + 1] + val area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) + if (area < 0f) { + newIndices.add(a) + newIndices.add(c) + newIndices.add(b) + } else { + newIndices.add(a) + newIndices.add(b) + newIndices.add(c) + } + } + for (edge in resolvedEdges) { + val a = edge.endpointLow + val b = edge.endpointHigh + val shared = neighbors[a].orEmpty().intersect(neighbors[b].orEmpty()) + for (c in shared) { + if (c != a && c != b) { + appendFace(a, b, c) + } + } + } + // Closed pure-draft ring with n≥3: constrained Delaunay (poly2tri) so diagonals zigzag instead + // of cascading ears along the boundary. n=3 may already be filled above; appendFace dedupes. + val draftRing = + (0 until draftVerts.size).map { draftIndex -> draftToFinal[draftIndex] }.takeIf { finals -> + finals.size >= 3 && finals.all { index -> index >= originalCount } + } + if (draftRing != null) { + val ringEdges = HashSet() + var ringClosed = true + for (i in draftRing.indices) { + val a = draftRing[i] + val b = draftRing[(i + 1) % draftRing.size] + val edge = MeshElement.Edge.of(a, b) + if (edge !in coveredEdges) { + ringClosed = false + break + } + ringEdges.add(edge) + } + if (ringClosed && ringEdges.size == draftRing.size) { + val xy = DoubleArray(draftRing.size * 2) + for (i in draftRing.indices) { + val vertex = draftRing[i] + xy[i * 2] = working.positions[vertex * 2].toDouble() + xy[i * 2 + 1] = working.positions[vertex * 2 + 1].toDouble() + } + val tris = PolygonTriangulator.triangulate(xy) + var t = 0 + while (t + 2 < tris.size) { + appendFace(draftRing[tris[t]], draftRing[tris[t + 1]], draftRing[tris[t + 2]]) + t += 3 + } + } + } + if (newIndices.size != working.indices.size) { + working = DrawableMesh(working.positions.copyOf(), working.uvs.copyOf(), newIndices.toIntArray()) + } + + // Knife-connect draft edges that still aren't mesh edges. + for (edge in resolvedEdges) { + if (MeshTopology.uniqueEdges(working.indices).contains(edge)) { + continue + } + val beforeCount = working.vertexCount + val connected = connectVertices(working, edge.endpointLow, edge.endpointHigh) ?: continue + working = connected.edit.newMesh + for (index in beforeCount until working.vertexCount) { + val src = connected.edit.vertexSources.getOrNull(index) + if (src is VertexSource.LerpOf) { + // Remap LerpOf endpoints through identity for verts that still live at original indices; + // crossings always lerp original-or-prior endpoints that remain valid on [mesh] when both + // ends were original - otherwise fall back to nearest on the original mesh. + appendedSources[index] = + if (src.oldA < originalCount && src.oldB < originalCount) { + src + } else { + sourceForAppended(mesh, working.positions[index * 2], working.positions[index * 2 + 1]) + } + } else { + appendedSources[index] = + sourceForAppended(mesh, working.positions[index * 2], working.positions[index * 2 + 1]) + } + } + selected.addAll(connected.newElements) + } + + if (working.vertexCount == mesh.vertexCount && + working.indices.contentEquals(mesh.indices) && + working.positions.contentEquals(mesh.positions) + ) { + return null + } + val sources = ArrayList(working.vertexCount) + for (index in 0 until working.vertexCount) { + if (index < originalCount) { + sources.add(VertexSource.FromOld(index)) + } else { + sources.add( + appendedSources[index] + ?: sourceForAppended(mesh, working.positions[index * 2], working.positions[index * 2 + 1]), + ) + } + } + val newElements = + selected.ifEmpty { + (originalCount until working.vertexCount).map { index -> MeshElement.Vertex(index) }.toSet() + } + return TopologyOpResult(MeshTopologyEdit(working, sources), newElements) + } + + /** + * Whether triangle (a,b,c) may be appended: missing, non-degenerate, new sides do not properly cross + * existing mesh edges. [pureDraft] triangles (all three sides from the draft) skip the centroid- + * inside-existing check so a closed drawn loop still fills when it sits over leftover art faces. + */ + private fun canFillTriangle( + a: Int, + b: Int, + c: Int, + positions: FloatArray, + indices: List, + existingFaces: Set>, + meshEdges: Set, + pureDraft: Boolean, + ): Boolean { + if (a == b || b == c || c == a) { + return false + } + if (setOf(a, b, c) in existingFaces) { + return false + } + val ax = positions[a * 2] + val ay = positions[a * 2 + 1] + val bx = positions[b * 2] + val by = positions[b * 2 + 1] + val cx = positions[c * 2] + val cy = positions[c * 2 + 1] + val area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) + if (kotlin.math.abs(area) < 1e-8f) { + return false + } + // Pure draft loops (all three sides drawn) always fill — they sit on top of leftover art by + // design. Hybrid closes still reject a new side that properly crosses a mesh edge (stacked / + // crossed diagonals on a filled quad). + if (pureDraft) { + return true + } + val sides = listOf(MeshElement.Edge.of(a, b), MeshElement.Edge.of(b, c), MeshElement.Edge.of(c, a)) + for (side in sides) { + if (side in meshEdges) { + continue + } + val sx0 = positions[side.endpointLow * 2] + val sy0 = positions[side.endpointLow * 2 + 1] + val sx1 = positions[side.endpointHigh * 2] + val sy1 = positions[side.endpointHigh * 2 + 1] + for (meshEdge in meshEdges) { + if (meshEdge.endpointLow == side.endpointLow || + meshEdge.endpointLow == side.endpointHigh || + meshEdge.endpointHigh == side.endpointLow || + meshEdge.endpointHigh == side.endpointHigh + ) { + continue + } + if (properSegmentCrossing( + sx0, + sy0, + sx1, + sy1, + positions[meshEdge.endpointLow * 2], + positions[meshEdge.endpointLow * 2 + 1], + positions[meshEdge.endpointHigh * 2], + positions[meshEdge.endpointHigh * 2 + 1], + ) != null + ) { + return false + } + } + } + val midX = (ax + bx + cx) / 3f + val midY = (ay + by + cy) / 3f + val probe = DrawableMesh(positions, FloatArray(positions.size), indices.toIntArray()) + return containingFace(probe, midX, midY) == null + } + + /** + * When draft verts 0…n-1 are chained by n-1 edges but the closing edge is missing, add it so Accept + * after three clicks (a drawn triangle) still fills a face without requiring a click-back on the first + * vert. + */ + private fun autoCloseDraftPolyline(draftVerts: List, draftEdges: List): List { + val count = draftVerts.size + if (count < 3) { + return draftEdges + } + for (index in 0 until count - 1) { + val step = DraftEdge.of(DraftEndpoint.Draft(index), DraftEndpoint.Draft(index + 1)) + if (step == null || step !in draftEdges) { + return draftEdges + } + } + val closer = DraftEdge.of(DraftEndpoint.Draft(count - 1), DraftEndpoint.Draft(0)) ?: return draftEdges + if (closer in draftEdges) { + return draftEdges + } + return draftEdges + closer + } + + /** UV + keyform source for a free draft point against the pre-draft [mesh]. */ + private fun sampleUvAndSource( + mesh: DrawableMesh, + x: Float, + y: Float, + uvContext: FreeVertUvContext?, + uvSeedMesh: DrawableMesh?, + ): Triple { + // Wipe-and-rebuild: project through the Edit-enter UV field (barycentric inside, affine outside). + if (mesh.vertexCount == 0) { + val field = uvSeedMesh?.takeIf { seed -> seed.vertexCount > 0 }?.let { seed -> MeshUvField(seed) } + if (field != null) { + val (u, v) = field.uvAt(x, y) + return Triple(u, v, VertexSource.AverageOf(emptyList())) + } + val (u, v) = uvContext?.storedUvAt(x, y) ?: (0f to 0f) + return Triple(u, v, VertexSource.AverageOf(emptyList())) + } + val face = containingFace(mesh, x, y) + if (face != null) { + val a = mesh.indices[face * 3] + val b = mesh.indices[face * 3 + 1] + val c = mesh.indices[face * 3 + 2] + val (wA, wB, wC) = + barycentric( + x, + y, + mesh.positions[a * 2], + mesh.positions[a * 2 + 1], + mesh.positions[b * 2], + mesh.positions[b * 2 + 1], + mesh.positions[c * 2], + mesh.positions[c * 2 + 1], + ) + val u = uvAt(mesh, a, 0) * wA + uvAt(mesh, b, 0) * wB + uvAt(mesh, c, 0) * wC + val v = uvAt(mesh, a, 1) * wA + uvAt(mesh, b, 1) * wB + uvAt(mesh, c, 1) * wC + return Triple(u, v, VertexSource.AverageOf(listOf(a, b, c))) + } + val nearest = nearestVertex(mesh, x, y) + return Triple(uvAt(mesh, nearest, 0), uvAt(mesh, nearest, 1), VertexSource.FromOld(nearest)) + } + + private fun sourceForAppended(mesh: DrawableMesh, x: Float, y: Float): VertexSource { + val face = containingFace(mesh, x, y) + if (face != null) { + return VertexSource.AverageOf( + listOf(mesh.indices[face * 3], mesh.indices[face * 3 + 1], mesh.indices[face * 3 + 2]), + ) + } + if (mesh.vertexCount == 0) { + return VertexSource.AverageOf(emptyList()) + } + return VertexSource.FromOld(nearestVertex(mesh, x, y)) + } + + private fun uvAt(mesh: DrawableMesh, vertexIndex: Int, component: Int): Float { + val index = vertexIndex * 2 + component + return if (index < mesh.uvs.size) mesh.uvs[index] else 0f + } + + private fun containingFace(mesh: DrawableMesh, x: Float, y: Float): Int? { + val triangleCount = mesh.indices.size / 3 + for (tri in 0 until triangleCount) { + val a = mesh.indices[tri * 3] + val b = mesh.indices[tri * 3 + 1] + val c = mesh.indices[tri * 3 + 2] + val (wA, wB, wC) = + barycentric( + x, + y, + mesh.positions[a * 2], + mesh.positions[a * 2 + 1], + mesh.positions[b * 2], + mesh.positions[b * 2 + 1], + mesh.positions[c * 2], + mesh.positions[c * 2 + 1], + ) + if (wA >= -1e-4f && wB >= -1e-4f && wC >= -1e-4f) { + return tri + } + } + return null + } + + private fun nearestVertex(mesh: DrawableMesh, x: Float, y: Float): Int { + var best = 0 + var bestDist = Float.MAX_VALUE + for (index in 0 until mesh.vertexCount) { + val dx = mesh.positions[index * 2] - x + val dy = mesh.positions[index * 2 + 1] - y + val dist = dx * dx + dy * dy + if (dist < bestDist) { + bestDist = dist + best = index + } + } + return best + } + + private fun barycentric( + px: Float, + py: Float, + ax: Float, + ay: Float, + bx: Float, + by: Float, + cx: Float, + cy: Float, + ): Triple { + val v0x = bx - ax + val v0y = by - ay + val v1x = cx - ax + val v1y = cy - ay + val v2x = px - ax + val v2y = py - ay + val dot00 = v0x * v0x + v0y * v0y + val dot01 = v0x * v1x + v0y * v1y + val dot02 = v0x * v2x + v0y * v2y + val dot11 = v1x * v1x + v1y * v1y + val dot12 = v1x * v2x + v1y * v2y + val denom = dot00 * dot11 - dot01 * dot01 + if (abs(denom) < 1e-12f) { + return Triple(1f, 0f, 0f) + } + val wB = (dot11 * dot02 - dot01 * dot12) / denom + val wC = (dot00 * dot12 - dot01 * dot02) / denom + val wA = 1f - wB - wC + return Triple(wA, wB, wC) + } + + /** + * The proper-crossing parameter of segment (a, b) against segment (p, q), or null: strictly interior + * on BOTH segments (an epsilon inside the endpoints) and non-parallel - the strictness is what lets + * [connectVertices] refuse grazes and on-vertex hits instead of guessing. + * + * @return Float? The parameter along (p, q) at the crossing, or null when there is no proper crossing. + */ + private fun properSegmentCrossing( + startX: Float, + startY: Float, + endX: Float, + endY: Float, + edgeStartX: Float, + edgeStartY: Float, + edgeEndX: Float, + edgeEndY: Float, + ): Float? { + val segmentX = endX - startX + val segmentY = endY - startY + val edgeX = edgeEndX - edgeStartX + val edgeY = edgeEndY - edgeStartY + val denominator = segmentX * edgeY - segmentY * edgeX + if (abs(denominator) < 1e-6f) { + return null + } + val betweenX = edgeStartX - startX + val betweenY = edgeStartY - startY + val segmentT = (betweenX * edgeY - betweenY * edgeX) / denominator + val edgeT = (betweenX * segmentY - betweenY * segmentX) / denominator + val epsilon = 1e-4f + if (segmentT <= epsilon || segmentT >= 1f - epsilon || edgeT <= epsilon || edgeT >= 1f - epsilon) { + return null + } + return edgeT + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTransforms.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTransforms.kt new file mode 100644 index 0000000..e273759 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshTransforms.kt @@ -0,0 +1,302 @@ +package org.umamo.edit + +import kotlin.math.cos +import kotlin.math.sin + +/** + * The active modal mesh operator: Blender-style Grab (translate), Scale, or Rotate. The session latches + * one of these while a gesture is in flight (the desktop overlay drives the pointer tracking and the + * corresponding [MeshTransforms] function); null means no operator is running. + * + * モーダルなメッシュ操作の種類(移動・拡縮・回転)。 + */ +enum class MeshOperatorKind { + Grab, + Scale, + Rotate, + + /** + * Slides the active vertex along one of its incident edges (Blender's Shift+V), clamped between the + * endpoints. Edit mode only, driven by the Edit overlay's own slide branch (the pointer projects + * onto the edge rather than through the shared operator math). + */ + VertexSlide, +} + +/** + * Pure transforms over an interleaved mesh-position array for the modal G / S / R operators. Positions + * are interleaved (x0, y0, x1, y1, ...), so vertex [index] occupies slots `2*index` and `2*index+1` + * (matching [org.umamo.runtime.model.DrawableMesh]). Each operator returns a NEW array, mutating only the + * coordinates of the selected vertices and copying the rest verbatim - it never touches its input, which + * keeps them trivially testable and upholds the copy-on-write discipline (the caller commits the returned + * array into a fresh DrawableMesh). + * + * The functions are coordinate-space agnostic: they operate on whatever values the array holds. The + * caller (the gizmo overlay) maps the pointer gesture into the same space the positions live in (model + * space) before computing the delta / factor / angle and the pivot. + * + * モーダルな移動・拡縮・回転の純粋変換。選択頂点のみを変更した新しい配列を返し、入力は変更しない。 + */ +object MeshTransforms { + /** + * The median pivot for scale / rotate: the mean (centroid) of the selected vertices' positions, in the + * array's coordinate space. Returns (0, 0) when nothing is selected (no operator runs in that case). + * + * @param FloatArray positions The interleaved mesh positions. + * @param Set indices The selected vertex indices. + * @return Pair The (x, y) centroid of the selected vertices. + */ + fun medianPivot(positions: FloatArray, indices: Set): Pair { + if (indices.isEmpty()) { + return 0f to 0f + } + var sumX = 0f + var sumY = 0f + for (vertexIndex in indices) { + sumX += positions[vertexIndex * 2] + sumY += positions[vertexIndex * 2 + 1] + } + val count = indices.size.toFloat() + return (sumX / count) to (sumY / count) + } + + /** + * The combined median pivot across several interleaved position arrays: the mean (centroid) of every + * vertex of every array, weighted by vertex count (so a denser mesh pulls the pivot toward itself, the + * same way [medianPivot] weights a single mesh by its vertices). This is the shared anchor an object-mode + * Scale / Rotate turns all selected drawables about. Returns (0, 0) when the collection is empty or holds + * only empty arrays (no gesture runs in that case). + * + * @param Collection positionsList The interleaved position arrays, one per selected drawable. + * @return Pair The (x, y) centroid across all arrays' vertices. + */ + fun combinedCentroid(positionsList: Collection): Pair { + var sumX = 0f + var sumY = 0f + var vertexCount = 0 + for (positions in positionsList) { + var slotIndex = 0 + while (slotIndex + 1 < positions.size) { + sumX += positions[slotIndex] + sumY += positions[slotIndex + 1] + vertexCount++ + slotIndex += 2 + } + } + if (vertexCount == 0) { + return 0f to 0f + } + val count = vertexCount.toFloat() + return (sumX / count) to (sumY / count) + } + + /** + * Translates the selected vertices by ([deltaX], [deltaY]). + * + * @param FloatArray positions The interleaved mesh positions. + * @param Set indices The selected vertex indices. + * @param Float deltaX The x offset. + * @param Float deltaY The y offset. + * @return FloatArray A new positions array with the selected vertices moved. + */ + fun translateVertices(positions: FloatArray, indices: Set, deltaX: Float, deltaY: Float): FloatArray { + val result = positions.copyOf() + for (vertexIndex in indices) { + result[vertexIndex * 2] += deltaX + result[vertexIndex * 2 + 1] += deltaY + } + return result + } + + /** + * Collapses the selected vertices onto one point ([targetX], [targetY]) - Blender's pile-up snap + * semantics (Selection to Cursor / Selection to Active). Unlike [translateVertices], the vertices + * do not keep their offsets from each other; every one lands exactly on the target. + * + * @param FloatArray positions The interleaved mesh positions. + * @param Set indices The selected vertex indices. + * @param Float targetX The x every selected vertex lands on. + * @param Float targetY The y every selected vertex lands on. + * @return FloatArray A new positions array with the selected vertices piled onto the target. + */ + fun collapseVertices(positions: FloatArray, indices: Set, targetX: Float, targetY: Float): FloatArray { + val result = positions.copyOf() + for (vertexIndex in indices) { + result[vertexIndex * 2] = targetX + result[vertexIndex * 2 + 1] = targetY + } + return result + } + + /** + * Scales the selected vertices about the pivot ([pivotX], [pivotY]) by [factor] (uniform on both axes). + * + * @param FloatArray positions The interleaved mesh positions. + * @param Set indices The selected vertex indices. + * @param Float factor The uniform scale factor (1 leaves them unchanged). + * @param Float pivotX The pivot x (the scale anchor). + * @param Float pivotY The pivot y. + * @return FloatArray A new positions array with the selected vertices scaled. + */ + fun scaleVertices(positions: FloatArray, indices: Set, factor: Float, pivotX: Float, pivotY: Float): FloatArray { + val result = positions.copyOf() + for (vertexIndex in indices) { + val x = result[vertexIndex * 2] + val y = result[vertexIndex * 2 + 1] + result[vertexIndex * 2] = pivotX + (x - pivotX) * factor + result[vertexIndex * 2 + 1] = pivotY + (y - pivotY) * factor + } + return result + } + + /** + * Scales the selected vertices about the pivot ([pivotX], [pivotY]) with independent per-axis + * factors - the axis-locked variant of [scaleVertices] (an X-locked scale passes factorY = 1 and + * vice versa). + * + * @param FloatArray positions The interleaved mesh positions. + * @param Set indices The selected vertex indices. + * @param Float factorX The scale factor along x (1 leaves x unchanged). + * @param Float factorY The scale factor along y (1 leaves y unchanged). + * @param Float pivotX The pivot x (the scale anchor). + * @param Float pivotY The pivot y. + * @return FloatArray A new positions array with the selected vertices scaled. + */ + fun scaleVerticesAxis(positions: FloatArray, indices: Set, factorX: Float, factorY: Float, pivotX: Float, pivotY: Float): FloatArray { + val result = positions.copyOf() + for (vertexIndex in indices) { + val x = result[vertexIndex * 2] + val y = result[vertexIndex * 2 + 1] + result[vertexIndex * 2] = pivotX + (x - pivotX) * factorX + result[vertexIndex * 2 + 1] = pivotY + (y - pivotY) * factorY + } + return result + } + + /** + * Pairwise swaps one axis among [orderedIndices]: index 0 with last, 1 with last-1, …. Odd count + * leaves the middle index alone. Horizontal swaps x (or u); vertical swaps y (or v); the other + * component stays on its vertex. + * + * @param FloatArray positions The interleaved positions (or UVs). + * @param List orderedIndices The selection in reverse-swap order (typically sorted indices). + * @param Boolean horizontal True to swap x/u only; false to swap y/v only. + * @return FloatArray A new array with pairs swapped; same instance when fewer than two indices. + */ + fun reverseSwapPositions( + positions: FloatArray, + orderedIndices: List, + horizontal: Boolean, + ): FloatArray { + if (orderedIndices.size < 2) { + return positions + } + val result = positions.copyOf() + val component = if (horizontal) 0 else 1 + var low = 0 + var high = orderedIndices.lastIndex + while (low < high) { + val a = orderedIndices[low] * 2 + component + val b = orderedIndices[high] * 2 + component + val tmp = result[a] + result[a] = result[b] + result[b] = tmp + low++ + high-- + } + return result + } + + /** + * Rotates the selected vertices about the pivot ([pivotX], [pivotY]) by [radians]. + * + * @param FloatArray positions The interleaved mesh positions. + * @param Set indices The selected vertex indices. + * @param Float radians The rotation angle in radians. + * @param Float pivotX The pivot x (the rotation center). + * @param Float pivotY The pivot y. + * @return FloatArray A new positions array with the selected vertices rotated. + */ + fun rotateVertices(positions: FloatArray, indices: Set, radians: Float, pivotX: Float, pivotY: Float): FloatArray { + val result = positions.copyOf() + val cosAngle = cos(radians) + val sinAngle = sin(radians) + for (vertexIndex in indices) { + val offsetX = result[vertexIndex * 2] - pivotX + val offsetY = result[vertexIndex * 2 + 1] - pivotY + result[vertexIndex * 2] = pivotX + offsetX * cosAngle - offsetY * sinAngle + result[vertexIndex * 2 + 1] = pivotY + offsetX * sinAngle + offsetY * cosAngle + } + return result + } + + /** + * Translates the weighted vertices by their share of ([deltaX], [deltaY]) - the proportional-editing + * companion of [translateVertices]: a weight of 1 moves fully, 0.5 half way. + * + * @param FloatArray positions The interleaved mesh positions. + * @param Map weights Vertex index to influence weight in [0, 1]. + * @param Float deltaX The full x offset (each vertex takes weight x this). + * @param Float deltaY The full y offset. + * @return FloatArray A new positions array with the weighted vertices moved. + */ + fun translateVerticesWeighted(positions: FloatArray, weights: Map, deltaX: Float, deltaY: Float): FloatArray { + val result = positions.copyOf() + for ((vertexIndex, weight) in weights) { + result[vertexIndex * 2] += deltaX * weight + result[vertexIndex * 2 + 1] += deltaY * weight + } + return result + } + + /** + * Scales the weighted vertices about the pivot by their share of the per-axis factors - the + * proportional-editing companion of [scaleVerticesAxis]: each vertex lerps from its current position + * toward its fully-scaled position by its weight (equivalently, its effective factor per axis is + * 1 + (factor - 1) x weight). + * + * @param FloatArray positions The interleaved mesh positions. + * @param Map weights Vertex index to influence weight in [0, 1]. + * @param Float factorX The full scale factor along x. + * @param Float factorY The full scale factor along y. + * @param Float pivotX The pivot x (the scale anchor). + * @param Float pivotY The pivot y. + * @return FloatArray A new positions array with the weighted vertices scaled. + */ + fun scaleVerticesWeighted(positions: FloatArray, weights: Map, factorX: Float, factorY: Float, pivotX: Float, pivotY: Float): FloatArray { + val result = positions.copyOf() + for ((vertexIndex, weight) in weights) { + val x = result[vertexIndex * 2] + val y = result[vertexIndex * 2 + 1] + result[vertexIndex * 2] = pivotX + (x - pivotX) * (1f + (factorX - 1f) * weight) + result[vertexIndex * 2 + 1] = pivotY + (y - pivotY) * (1f + (factorY - 1f) * weight) + } + return result + } + + /** + * Rotates the weighted vertices about the pivot by their share of [radians] - the + * proportional-editing companion of [rotateVertices]. The ANGLE is weighted (a half-weight vertex + * turns half the angle along the arc), not the endpoint position: lerping positions would cut the + * chord and collapse the falloff ring toward the pivot on large rotations. + * + * @param FloatArray positions The interleaved mesh positions. + * @param Map weights Vertex index to influence weight in [0, 1]. + * @param Float radians The full rotation angle in radians (each vertex turns weight x this). + * @param Float pivotX The pivot x (the rotation center). + * @param Float pivotY The pivot y. + * @return FloatArray A new positions array with the weighted vertices rotated. + */ + fun rotateVerticesWeighted(positions: FloatArray, weights: Map, radians: Float, pivotX: Float, pivotY: Float): FloatArray { + val result = positions.copyOf() + for ((vertexIndex, weight) in weights) { + val cosAngle = cos(radians * weight) + val sinAngle = sin(radians * weight) + val offsetX = result[vertexIndex * 2] - pivotX + val offsetY = result[vertexIndex * 2 + 1] - pivotY + result[vertexIndex * 2] = pivotX + offsetX * cosAngle - offsetY * sinAngle + result[vertexIndex * 2 + 1] = pivotY + offsetX * sinAngle + offsetY * cosAngle + } + return result + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshUvField.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshUvField.kt new file mode 100644 index 0000000..e341717 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/MeshUvField.kt @@ -0,0 +1,221 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableMesh +import kotlin.math.abs + +/** + * Projects rest-space positions onto the stored UVs of an Edit-enter reference mesh. + * + * Wipe-and-rebuild must not invent a new UV layout: every new vert samples this field so the texture + * stays locked to the original mapping no matter how the rigger retriangulates. + * + * Inside a reference face: barycentric (exact piecewise-linear field). Outside: a least-squares + * affine fit over all reference verts (smooth; no nearest-vert UV plateaus that stretch the art). + * + * @property DrawableMesh seed The mesh at Edit enter (positions + uvs + indices). + */ +class MeshUvField(private val seed: DrawableMesh) { + private val affine: FloatArray? = fitAffine(seed) + + /** + * Stored (u, v) at a rest-space point. + * + * @param Float x Rest x. + * @param Float y Rest y. + * @return Pair Stored UVs. + */ + fun uvAt(x: Float, y: Float): Pair { + if (seed.vertexCount == 0) { + return 0f to 0f + } + val face = containingFace(seed, x, y) + if (face != null) { + val a = seed.indices[face * 3] + val b = seed.indices[face * 3 + 1] + val c = seed.indices[face * 3 + 2] + val (wA, wB, wC) = + barycentric( + x, + y, + seed.positions[a * 2], + seed.positions[a * 2 + 1], + seed.positions[b * 2], + seed.positions[b * 2 + 1], + seed.positions[c * 2], + seed.positions[c * 2 + 1], + ) + val u = uvComponent(a, 0) * wA + uvComponent(b, 0) * wB + uvComponent(c, 0) * wC + val v = uvComponent(a, 1) * wA + uvComponent(b, 1) * wB + uvComponent(c, 1) * wC + return u to v + } + val fit = affine + if (fit != null) { + return (fit[0] * x + fit[1] * y + fit[2]) to (fit[3] * x + fit[4] * y + fit[5]) + } + val nearest = nearestVertex(seed, x, y) + return uvComponent(nearest, 0) to uvComponent(nearest, 1) + } + + /** + * Rewrites every vertex UV on [mesh] by projecting its rest position through this field. + * + * @param DrawableMesh mesh The mesh to re-UV. + * @return DrawableMesh A copy with projected uvs (positions / indices shared when unchanged). + */ + fun projectAll(mesh: DrawableMesh): DrawableMesh { + if (mesh.vertexCount == 0) { + return mesh + } + val uvs = FloatArray(mesh.vertexCount * 2) + for (index in 0 until mesh.vertexCount) { + val (u, v) = uvAt(mesh.positions[index * 2], mesh.positions[index * 2 + 1]) + uvs[index * 2] = u + uvs[index * 2 + 1] = v + } + return DrawableMesh(mesh.positions, uvs, mesh.indices) + } + + private fun uvComponent(vertexIndex: Int, component: Int): Float { + val index = vertexIndex * 2 + component + return if (index < seed.uvs.size) seed.uvs[index] else 0f + } + + companion object { + /** + * Least-squares affine [u,v] = M · [x, y, 1] over all seed verts with UVs. Null when fewer than + * three distinct positions or the system is degenerate. + */ + private fun fitAffine(seed: DrawableMesh): FloatArray? { + val count = seed.vertexCount + if (count < 3 || seed.uvs.size < count * 2) { + return null + } + // Normal equations for [x y 1; ...] → u and v separately (3x3 shared Gram matrix). + var sxx = 0.0 + var sxy = 0.0 + var sx = 0.0 + var syy = 0.0 + var sy = 0.0 + var n = 0.0 + var sxu = 0.0 + var syu = 0.0 + var su = 0.0 + var sxv = 0.0 + var syv = 0.0 + var sv = 0.0 + for (index in 0 until count) { + val x = seed.positions[index * 2].toDouble() + val y = seed.positions[index * 2 + 1].toDouble() + val u = seed.uvs[index * 2].toDouble() + val v = seed.uvs[index * 2 + 1].toDouble() + sxx += x * x + sxy += x * y + sx += x + syy += y * y + sy += y + n += 1.0 + sxu += x * u + syu += y * u + su += u + sxv += x * v + syv += y * v + sv += v + } + val det = + sxx * (syy * n - sy * sy) - sxy * (sxy * n - sx * sy) + sx * (sxy * sy - syy * sx) + if (abs(det) < 1e-18) { + return null + } + + fun solve(bx: Double, by: Double, b1: Double): Triple { + // Cramer's rule on the 3x3 Gram matrix. + val a0 = + ( + bx * (syy * n - sy * sy) - sxy * (by * n - b1 * sy) + sx * (by * sy - syy * b1) + ) / det + val a1 = + ( + sxx * (by * n - b1 * sy) - bx * (sxy * n - sx * sy) + sx * (sxy * b1 - by * sx) + ) / det + val a2 = + ( + sxx * (syy * b1 - sy * by) - sxy * (sxy * b1 - sx * by) + bx * (sxy * sy - syy * sx) + ) / det + return Triple(a0, a1, a2) + } + val (a, b, c) = solve(sxu, syu, su) + val (d, e, f) = solve(sxv, syv, sv) + return floatArrayOf(a.toFloat(), b.toFloat(), c.toFloat(), d.toFloat(), e.toFloat(), f.toFloat()) + } + + private fun containingFace(mesh: DrawableMesh, x: Float, y: Float): Int? { + val triangleCount = mesh.indices.size / 3 + for (tri in 0 until triangleCount) { + val a = mesh.indices[tri * 3] + val b = mesh.indices[tri * 3 + 1] + val c = mesh.indices[tri * 3 + 2] + val (wA, wB, wC) = + barycentric( + x, + y, + mesh.positions[a * 2], + mesh.positions[a * 2 + 1], + mesh.positions[b * 2], + mesh.positions[b * 2 + 1], + mesh.positions[c * 2], + mesh.positions[c * 2 + 1], + ) + if (wA >= -1e-4f && wB >= -1e-4f && wC >= -1e-4f) { + return tri + } + } + return null + } + + private fun nearestVertex(mesh: DrawableMesh, x: Float, y: Float): Int { + var best = 0 + var bestDist = Float.MAX_VALUE + for (index in 0 until mesh.vertexCount) { + val dx = mesh.positions[index * 2] - x + val dy = mesh.positions[index * 2 + 1] - y + val dist = dx * dx + dy * dy + if (dist < bestDist) { + bestDist = dist + best = index + } + } + return best + } + + private fun barycentric( + px: Float, + py: Float, + ax: Float, + ay: Float, + bx: Float, + by: Float, + cx: Float, + cy: Float, + ): Triple { + val v0x = bx - ax + val v0y = by - ay + val v1x = cx - ax + val v1y = cy - ay + val v2x = px - ax + val v2y = py - ay + val dot00 = v0x * v0x + v0y * v0y + val dot01 = v0x * v1x + v0y * v1y + val dot02 = v0x * v2x + v0y * v2y + val dot11 = v1x * v1x + v1y * v1y + val dot12 = v1x * v2x + v1y * v2y + val denom = dot00 * dot11 - dot01 * dot01 + if (abs(denom) < 1e-12f) { + return Triple(1f, 0f, 0f) + } + val wB = (dot11 * dot02 - dot01 * dot12) / denom + val wC = (dot00 * dot12 - dot01 * dot02) / denom + val wA = 1f - wB - wC + return Triple(wA, wB, wC) + } + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ModalTransformCapture.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ModalTransformCapture.kt new file mode 100644 index 0000000..25d0112 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ModalTransformCapture.kt @@ -0,0 +1,206 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId + +/** + * How Individual Origins ([TransformPivotMode.IndividualOrigins]) partitions one mesh into pivot groups. + * + * The two editing contexts read the same pivot mode differently, which the mode's own docblock already + * describes: in Edit and the UV editor a mesh's covered vertices split into connectivity islands, each + * turning about its own centroid; in Object mode a whole drawable turns about its single centroid. Making + * that an explicit parameter of [buildModalTransformCapture] keeps the one difference visible instead of + * hiding it in two copies of the group-derivation code. + */ +enum class IndividualOriginScope { + /** Split the covered set into connectivity islands (Edit mode, the UV editor). */ + ConnectivityIsland, + + /** One group for the whole covered set, about its centroid (Object mode). */ + WholeMesh, +} + +/** + * One mesh offered to [buildModalTransformCapture], before its pivots are resolved. + * + * The positions are frozen in whatever space the gesture runs in - world-posed for the viewport overlays, + * texel display for the UV editor - and the covered indices are the union of vertices the mesh's selected + * elements span (every vertex, for an Object-mode whole-drawable transform). A source whose covered set is + * empty contributes nothing and is dropped by the builder. + * + * @property DrawableId drawableId The drawable this mesh belongs to (the capture's per-mesh key). + * @property FloatArray positions The frozen interleaved positions the operator transforms and the pivots + * are measured in. The builder does not copy it - the caller freezes (copies) before handing it over. + * @property IntArray triangleIndices The mesh's triangle vertex indices (connectivity for islands and the + * geodesic proportional falloff). + * @property Set coveredIndices The vertices the selection covers on this mesh. + */ +class ModalCaptureSource( + val drawableId: DrawableId, + val positions: FloatArray, + val triangleIndices: IntArray, + val coveredIndices: Set, +) + +/** + * One mesh inside an in-flight modal transform: its frozen source geometry plus the pivot groups its + * covered vertices turn about, and the proportional-editing halo re-derived from the same frozen positions. + * + * [influence] and [movedIndices] are the only mutable state, because a mid-gesture radius or falloff change + * re-derives them - always from [positions], never from a live preview, so the influence ring can never + * feed back on its own output. + * + * @property DrawableId drawableId The drawable this entry belongs to. + * @property FloatArray positions The frozen positions the operator transforms (shared by reference from the + * source - never mutated). + * @property Set coveredIndices The vertices the selection covers on this mesh. + * @property IntArray triangleIndices The mesh's triangle vertex indices. + * @property List groups The pivot groups the covered vertices turn about. + */ +class ModalCaptureEntry internal constructor( + val drawableId: DrawableId, + val positions: FloatArray, + val coveredIndices: Set, + val triangleIndices: IntArray, + val groups: List, +) { + /** The proportional-editing halo: influenced unselected vertices to weight, empty when proportional is off. */ + var influence: Map = emptyMap() + private set + + /** Every vertex the gesture moves: the covered set, plus the influenced halo when proportional is on. */ + var movedIndices: Set = coveredIndices + private set + + /** + * Re-derives this mesh's influence halo and moved set from the FROZEN positions. + * + * @param ProportionalEditState? state The proportional configuration, or null to clear the halo. + * @param Float radius The influence radius in the positions' units (unused when [state] is null). + */ + internal fun deriveInfluence(state: ProportionalEditState?, radius: Float) { + influence = + when { + state == null -> emptyMap() + state.connectedOnly -> + proportionalInfluencesConnected(positions, coveredIndices, radius, state.falloff, triangleIndices) + else -> proportionalInfluences(positions, coveredIndices, radius, state.falloff) + } + movedIndices = + if (influence.isEmpty()) { + coveredIndices + } else { + coveredIndices + influence.keys + } + } +} + +/** + * The captured state of an in-flight modal transform, frozen when the operator latches so the whole drag is + * atomic across the meshes it moves. Shared by the Edit, Object, and UV gizmo overlays: each freezes its + * own-space geometry into [ModalCaptureSource]s, resolves its own active-element and cursor anchors, and + * hands both to [buildModalTransformCapture]; what comes back is identical in shape across all three. + * + * Overlays that need extra per-mesh data the shared capture does not carry (the Edit and Object overlays' + * deformer-chain mapping, the UV editor's page dimensions) hold it in a map keyed on + * [ModalCaptureEntry.drawableId] rather than a second index-aligned list. + * + * @property List entries The moving meshes, one per source that had covered vertices. + * @property Pair anchor The point in the gesture's space that factors and angles measure + * against (and the shared-pivot modes turn about); the HUD's pivot marker draws here. + * @property MeshOperatorKind operatorKind The operator that latched, frozen so the commit names the + * operation that actually ran rather than re-reading a latch that may already have cleared. + */ +class ModalTransformCapture internal constructor( + val entries: List, + val anchor: Pair, + val operatorKind: MeshOperatorKind, +) { + /** The Rotate gesture's angle accumulator (unwrapped per-move increments; see RotationAngleTracker). */ + val rotationTracker = RotationAngleTracker() + + /** The captured drawables, in capture order. */ + val drawableIds: List get() = entries.map { entry -> entry.drawableId } + + /** + * Re-derives every mesh's proportional halo from the frozen originals. Called on latch and again on a + * mid-gesture radius or falloff change; feeding the same inputs twice is idempotent. + * + * @param ProportionalEditState? state The proportional configuration, or null to clear the halos. + * @param Float radius The influence radius in the gesture space's units (unused when [state] is null). + */ + fun applyProportional(state: ProportionalEditState?, radius: Float) { + for (entry in entries) { + entry.deriveInfluence(state, radius) + } + } +} + +/** + * Builds a [ModalTransformCapture] from the meshes a gesture will move, resolving the shared anchor and each + * mesh's pivot groups per the active [pivotMode]. + * + * This owns exactly the part every overlay duplicated: the covered-vertex mean across the meshes, the + * fallback policy (Active Element and Cursor both fall back to the median when their anchor is absent), and + * the per-mesh group derivation. What differs between overlays stays with the caller and arrives + * pre-resolved: [activeAnchor] (each overlay finds its active element / drawable differently) and + * [cursorAnchor] (each reads a different cursor, in a different space). + * + * @param List sources The meshes offered; those with no covered vertices are dropped. + * @param TransformPivotMode pivotMode The active pivot mode (which anchor, and single vs per-island groups). + * @param IndividualOriginScope individualOriginScope How Individual Origins partitions a mesh. + * @param MeshOperatorKind operatorKind The operator that latched (frozen onto the capture). + * @param Pair? activeAnchor The Active-Element anchor the caller resolved, or null to fall + * back to the median. + * @param Pair? cursorAnchor The Cursor anchor the caller resolved, or null to fall back to + * the median. + * @return ModalTransformCapture? The capture, or null when no source had covered vertices (no gesture runs). + */ +fun buildModalTransformCapture( + sources: List, + pivotMode: TransformPivotMode, + individualOriginScope: IndividualOriginScope, + operatorKind: MeshOperatorKind, + activeAnchor: Pair?, + cursorAnchor: Pair?, +): ModalTransformCapture? { + val moving = sources.filter { source -> source.coveredIndices.isNotEmpty() } + if (moving.isEmpty()) { + return null + } + // The covered-vertex mean across every moving mesh - the shared median anchor, and the fallback for the + // Active-Element and Cursor modes. Object mode covers every vertex, so this equals its combined + // centroid (MeshTransforms.combinedCentroid) up to summation order. + var coveredSumX = 0f + var coveredSumY = 0f + var coveredCount = 0 + for (source in moving) { + for (vertexIndex in source.coveredIndices) { + coveredSumX += source.positions[vertexIndex * 2] + coveredSumY += source.positions[vertexIndex * 2 + 1] + coveredCount++ + } + } + val median = (coveredSumX / coveredCount) to (coveredSumY / coveredCount) + val anchor = + when (pivotMode) { + TransformPivotMode.MedianPoint, TransformPivotMode.IndividualOrigins -> median + TransformPivotMode.ActiveElement -> activeAnchor ?: median + TransformPivotMode.Cursor -> cursorAnchor ?: median + } + val entries = + moving.map { source -> + val groups = + when { + pivotMode == TransformPivotMode.IndividualOrigins && individualOriginScope == IndividualOriginScope.ConnectivityIsland -> + TransformPivots.islandGroups(source.positions, source.coveredIndices, source.triangleIndices) + pivotMode == TransformPivotMode.IndividualOrigins -> { + // WholeMesh: the drawable turns about its own centroid (the object-mode island). + val ownCentroid = MeshTransforms.medianPivot(source.positions, source.coveredIndices) + TransformPivots.sharedGroup(source.coveredIndices, ownCentroid.first, ownCentroid.second) + } + else -> TransformPivots.sharedGroup(source.coveredIndices, anchor.first, anchor.second) + } + ModalCaptureEntry(source.drawableId, source.positions, source.coveredIndices, source.triangleIndices, groups) + } + return ModalTransformCapture(entries, anchor, operatorKind) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ObjectTransforms.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ObjectTransforms.kt new file mode 100644 index 0000000..4d16ad7 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ObjectTransforms.kt @@ -0,0 +1,225 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * The drawables an object-mode Grab / Scale / Rotate may transform, or null when the gesture must be + * blocked. Object G / S / R writes only DrawableMesh.positions, so the transformable unit is always a + * mesh-carrying drawable: + * - a selected drawable contributes itself (when it has a mesh); + * - a selected part expands to every mesh-carrying drawable in its outliner subtree + * ([PuppetModel.subtreeTargets]), so Grab on a group moves the group's art together; + * - a deformer is still skipped (its shape lives in absolute per-keyform forms with no writer yet - the + * remaining Deformer → Part → Mesh cascade). + * Ineligible targets are silently ignored rather than blocking: a Select All that sweeps deformers in + * still lets G move the meshes. Only a selection with nothing transformable at all (empty, or holding + * only deformers / empty parts / mesh-less drawables) returns null, and the caller blocks with a note. + * + * オブジェクトモードの G / S / R が変形できる描画メッシュ。選択中のパーツはその配下のメッシュへ展開し、 + * デフォーマ・メッシュ無しは黙って除外する。1つも無ければ null(ジェスチャをブロック)。 + * + * @param Selection selection The object-mode selection to evaluate. + * @param PuppetModel model The rig the targets index into. + * @return List? The transformable drawable ids, or null when nothing is transformable. + */ +fun eligibleTransformDrawables(selection: Selection, model: PuppetModel): List? { + if (selection.isEmpty) { + return null + } + // LinkedHashSet: a part and one of its drawables in the same selection must not double-transform the mesh. + val drawableIds = LinkedHashSet() + for (target in selection.targets) { + when (target) { + is SelectionTarget.Drawable -> addMeshDrawable(drawableIds, model, target.id) + is SelectionTarget.Part -> { + for (sub in model.subtreeTargets(target)) { + val drawableTarget = sub as? SelectionTarget.Drawable ?: continue + addMeshDrawable(drawableIds, model, drawableTarget.id) + } + } + // Deformers cannot be transformed yet (no lattice / cascade writer for Object G / S / R here). + is SelectionTarget.Deformer -> Unit + } + } + return drawableIds.toList().ifEmpty { null } +} + +/** + * Adds [id] to [into] when the drawable exists and carries a mesh (positions to move). + * + * @param MutableSet into The accumulator. + * @param PuppetModel model The rig to look the drawable up in. + * @param DrawableId id The candidate drawable. + */ +private fun addMeshDrawable(into: MutableSet, model: PuppetModel, id: DrawableId) { + val drawable = model.drawables.firstOrNull { it.id == id } + if (drawable?.mesh != null) { + into.add(id) + } +} + +/** + * The active warp deformer when Object-mode G / S / R should edit its lattice, or null. + * + * Prefers the selection's active target when it is a keyed warp; otherwise the sole selected warp with a + * lattice. Drawables in the same selection do not block this - [eligibleTransformDrawables] already won + * if any mesh was transformable. + * + * @param Selection selection The object selection. + * @param PuppetModel model The rig. + * @return DeformerId? The warp to edit, or null. + */ +fun selectedWarpDeformerId(selection: Selection, model: PuppetModel): DeformerId? { + fun warpIdOf(target: SelectionTarget): DeformerId? { + val deformerTarget = target as? SelectionTarget.Deformer ?: return null + val warp = model.deformers.firstOrNull { candidate -> candidate.id == deformerTarget.id } as? Deformer.Warp + return if (warp?.geometryGrid != null) warp.id else null + } + selection.active?.let { active -> warpIdOf(active)?.let { return it } } + val warps = selection.targets.mapNotNull { target -> warpIdOf(target) } + return warps.singleOrNull() +} + +/** + * Reports whether the live pose sits at every parameter's default value. Object-mode transforms capture + * the displayed (posed) geometry and write it back through the deformer-chain inverse, which is only + * exact at the neutral pose - so [EditorSession.beginObjectOperator] refuses to start while any + * parameter is scrubbed away from its default. A parameter missing from the pose map counts as neutral + * (the renderer substitutes the default for it). + * + * @param PuppetModel model The rig whose parameter defaults define neutral. + * @param Pose pose The live parameter values to test. + * @return Boolean True when every posed value equals its parameter's default. + */ +fun isPoseNeutral(model: PuppetModel, pose: Pose): Boolean { + for (parameter in model.parameters) { + val value = pose[parameter.id] ?: continue + if (value != parameter.default) { + return false + } + } + return true +} + +/** + * The axis-aligned bounds of an interleaved position array: its center and its extents. A drawable has no + * scalar transform - its placement IS its geometry - so a "transform" for one is derived from these bounds, + * and an edit to the transform is an edit to the geometry that produced them. + * + * Space-agnostic: this measures whatever array it is handed. Which array that should be is the caller's + * decision and a consequential one - see the Properties panel's DrawableWorldTransform, which measures + * WORLD positions because a keyformed drawable's base array is nothing like its on-screen shape. + * + * @property Float centerX The bounds' center x. + * @property Float centerY The bounds' center y. + * @property Float width The x extent (0 for a degenerate or empty mesh). + * @property Float height The y extent (0 for a degenerate or empty mesh). + */ +class MeshBounds(val centerX: Float, val centerY: Float, val width: Float, val height: Float) + +/** + * Computes the axis-aligned bounds of an interleaved (x, y) position array. Shared by the Properties + * readout and the transform edits below, so what is displayed and what is written are the same measurement + * - a second definition would let the two drift and make a typed value land somewhere else. Both must be + * handed positions in the SAME space for that to hold. + * + * @param FloatArray positions Interleaved x, y vertex positions. + * @return MeshBounds The center and extents; a zero box when there are no vertices. + */ +fun meshBounds(positions: FloatArray): MeshBounds { + if (positions.size < 2) { + return MeshBounds(0f, 0f, 0f, 0f) + } + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var slotIndex = 0 + while (slotIndex + 1 < positions.size) { + val x = positions[slotIndex] + val y = positions[slotIndex + 1] + if (x < minX) { + minX = x + } + if (x > maxX) { + maxX = x + } + if (y < minY) { + minY = y + } + if (y > maxY) { + maxY = y + } + slotIndex += 2 + } + return MeshBounds((minX + maxX) / 2f, (minY + maxY) / 2f, maxX - minX, maxY - minY) +} + +/** Every vertex index of an interleaved position array - the whole-mesh index set the object edits move. */ +private fun allVertexIndices(positions: FloatArray): Set = (0 until positions.size / 2).toSet() + +/** + * Translates a whole mesh so its bounds center lands on ([newCenterX], [newCenterY]). This is the write + * side of the Properties Position row: the row reads [meshBounds]'s center, and typing a value moves the + * mesh rigidly by the difference, so the displayed number becomes exactly the value entered. + * + * Pure and space-agnostic - it moves the array it is given. The Properties panel applies it to WORLD + * positions and inverts the result back onto the base mesh; see DrawableWorldTransform. + * + * @param FloatArray positions The interleaved positions. + * @param Float newCenterX The x the bounds center should land on. + * @param Float newCenterY The y the bounds center should land on. + * @return FloatArray A new positions array, or the same instance when nothing moves. + */ +fun movedToBoundsCenter(positions: FloatArray, newCenterX: Float, newCenterY: Float): FloatArray { + if (positions.size < 2) { + return positions + } + val bounds = meshBounds(positions) + val deltaX = newCenterX - bounds.centerX + val deltaY = newCenterY - bounds.centerY + if (deltaX == 0f && deltaY == 0f) { + return positions + } + return MeshTransforms.translateVertices(positions, allVertexIndices(positions), deltaX, deltaY) +} + +/** + * Scales a whole mesh about its bounds center so its extents become ([newWidth], [newHeight]). The write + * side of the Properties Size row. Pure and space-agnostic like [movedToBoundsCenter]. + * + * The bounds center is the pivot precisely because it is a fixed point of the scale: the Position row reads + * that same center, so resizing never makes the position readout jump. (The vertex centroid - + * MeshTransforms.combinedCentroid, which the viewport gizmo pivots on - sits off the bounds center on an + * asymmetric mesh and would move it.) + * + * An axis whose current extent is zero has no defined factor - a degenerate mesh with every vertex on one + * line cannot be given a width - so that axis is left alone rather than multiplied by infinity. + * + * @param FloatArray positions The interleaved positions. + * @param Float newWidth The target x extent (ignored when the current x extent is 0). + * @param Float newHeight The target y extent (ignored when the current y extent is 0). + * @return FloatArray A new positions array, or the same instance when nothing changes. + */ +fun resizedAboutBoundsCenter(positions: FloatArray, newWidth: Float, newHeight: Float): FloatArray { + if (positions.size < 2) { + return positions + } + val bounds = meshBounds(positions) + val factorX = if (bounds.width > 0f) newWidth / bounds.width else 1f + val factorY = if (bounds.height > 0f) newHeight / bounds.height else 1f + if (factorX == 1f && factorY == 1f) { + return positions + } + return MeshTransforms.scaleVerticesAxis( + positions, + allVertexIndices(positions), + factorX, + factorY, + bounds.centerX, + bounds.centerY, + ) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/OperatorRecord.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/OperatorRecord.kt new file mode 100644 index 0000000..6fea27b --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/OperatorRecord.kt @@ -0,0 +1,205 @@ +package org.umamo.edit + +/* + * The record behind "adjust the last operation". + * + * An operation that has settings runs at once with its defaults and registers one of these. Editing + * a parameter re-runs the operation from the base snapshot the record holds and lands the result over + * the operation's own history step (History.amendTop), so an adjustment costs one run of the operation + * and nothing is replayed. Everything here is plain data the UI renders and the session owns; nothing + * about Compose or any one operation may appear in this file. + */ + +/** The unit a numeric parameter is shown in. */ +enum class ParameterUnit { + None, + Pixels, + Degrees, + Percent, +} + +/** + * One editable setting of an adjustable operation. + * + * Carries a stable [key] the operation reads its value back by and a [labelKey] the UI maps to a + * localized label (the [Change.labelKey] convention, so this module stays presentation-free). The + * value is typed per kind; the UI renders one row per kind and never needs to know the operation. + */ +sealed interface OperatorParameter { + /** The stable identity the operation reads the value back by. */ + val key: String + + /** The stable key the UI resolves to the row's localized label. */ + val labelKey: String + + /** + * A real-valued setting with a range, a scrub step, and a display unit. + * + * @property String key See [OperatorParameter.key]. + * @property String labelKey See [OperatorParameter.labelKey]. + * @property Float value The current value. + * @property Float min The smallest value the row accepts. + * @property Float max The largest value the row accepts. + * @property Float step The scrub / chevron increment. + * @property ParameterUnit unit The display unit. + */ + data class FloatParameter( + override val key: String, + override val labelKey: String, + val value: Float, + val min: Float, + val max: Float, + val step: Float = 1f, + val unit: ParameterUnit = ParameterUnit.None, + ) : OperatorParameter + + /** + * An integer setting with a range, a scrub step, and a display unit. + * + * @property String key See [OperatorParameter.key]. + * @property String labelKey See [OperatorParameter.labelKey]. + * @property Int value The current value. + * @property Int min The smallest value the row accepts. + * @property Int max The largest value the row accepts. + * @property Int step The scrub / chevron increment. + * @property ParameterUnit unit The display unit. + */ + data class IntParameter( + override val key: String, + override val labelKey: String, + val value: Int, + val min: Int, + val max: Int, + val step: Int = 1, + val unit: ParameterUnit = ParameterUnit.None, + ) : OperatorParameter + + /** + * An on / off setting. + * + * @property String key See [OperatorParameter.key]. + * @property String labelKey See [OperatorParameter.labelKey]. + * @property Boolean value The current value. + */ + data class BooleanParameter( + override val key: String, + override val labelKey: String, + val value: Boolean, + ) : OperatorParameter + + /** + * A pick from a closed list of choices. + * + * @property String key See [OperatorParameter.key]. + * @property String labelKey See [OperatorParameter.labelKey]. + * @property String value The key of the chosen entry of [choices]. + * @property List choices The entries, in display order. + */ + data class ChoiceParameter( + override val key: String, + override val labelKey: String, + val value: String, + val choices: List, + ) : OperatorParameter +} + +/** + * One entry of a [OperatorParameter.ChoiceParameter]. + * + * @property String key The stable value the operation reads back. + * @property String? labelKey The key the UI resolves to the entry's label, or null to show [key] verbatim + * (a page size, a number the rigger recognises). + */ +data class ParameterChoice( + val key: String, + val labelKey: String? = null, +) + +/** + * The parameter list with the entry at [key] replaced by [updated]. + * + * @param String key The entry to replace. + * @param OperatorParameter updated Its replacement (normally a copy with a new value). + * @return List The list with that one entry swapped; unchanged when no entry has the key. + */ +fun List.withParameter(key: String, updated: OperatorParameter): List = + map { parameter -> if (parameter.key == key) updated else parameter } + +/** + * The integer value of the parameter at [key], or [fallback] when absent or of another kind. + * + * @param String key The entry to read. + * @param Int fallback The value when the list carries no such integer. + * @return Int The value. + */ +fun List.intValue(key: String, fallback: Int): Int = + (firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.IntParameter)?.value ?: fallback + +/** + * The real value of the parameter at [key], or [fallback] when absent or of another kind. + * + * @param String key The entry to read. + * @param Float fallback The value when the list carries no such float. + * @return Float The value. + */ +fun List.floatValue(key: String, fallback: Float): Float = + (firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.FloatParameter)?.value ?: fallback + +/** + * The boolean value of the parameter at [key], or [fallback] when absent or of another kind. + * + * @param String key The entry to read. + * @param Boolean fallback The value when the list carries no such flag. + * @return Boolean The value. + */ +fun List.booleanValue(key: String, fallback: Boolean): Boolean = + (firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.BooleanParameter)?.value ?: fallback + +/** + * The chosen key of the choice parameter at [key], or [fallback] when absent or of another kind. + * + * @param String key The entry to read. + * @param String fallback The value when the list carries no such choice. + * @return String The chosen entry's key. + */ +fun List.choiceValue(key: String, fallback: String): String = + (firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.ChoiceParameter)?.value ?: fallback + +/** + * The one operation that may still be adjusted: what it committed, what it ran from, its current + * settings, and how to run it again. + * + * Immutable; an adjustment replaces the session's record with [withParameters], and the two share an + * [identity] so a rerun launched against the earlier value still lands (see + * [EditorSession.amendLastCommit]). The [baseSnapshot] is held here rather than looked up in the + * history because a cap of one drops it from the stack the moment the operation pushes. + * + * @property Change change The change the operation committed; its label titles the strip. + * @property String? areaId The area the operation ran in, or null for one that ran nowhere in + * particular (the strip then shows nowhere; the record stays adjustable through the F9 command). + * @property List parameters The current settings, in display order. + * @property EditorSnapshot baseSnapshot The state the operation ran from. + * @property Function rerun Runs the operation again from [baseSnapshot] under the record it is + * given (whose [parameters] are the new values) and lands through [EditorSession.amendLastCommit]. The + * client's closure, which owns whatever expensive inputs it retained and launches its own coroutine if + * it needs one. + * @property Any identity Shared by every value of one registration, so a stale value can be + * told from a cleared record. + */ +class AdjustableOperation internal constructor( + val change: Change, + val areaId: String?, + val parameters: List, + val baseSnapshot: EditorSnapshot, + val rerun: (AdjustableOperation) -> Unit, + internal val identity: Any, +) { + /** + * This record with new settings, keeping everything else including the identity. + * + * @param List parameters The new settings. + * @return AdjustableOperation The updated record. + */ + fun withParameters(parameters: List): AdjustableOperation = + AdjustableOperation(change, areaId, parameters, baseSnapshot, rerun, identity) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/OutlinerTreeEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/OutlinerTreeEdits.kt new file mode 100644 index 0000000..bf1d9ba --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/OutlinerTreeEdits.kt @@ -0,0 +1,295 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.deformerSelfAndDescendants +import org.umamo.runtime.model.partSelfAndDescendants + +/* + * Outliner drop resolution: the pure rules deciding what dropping one outliner row onto another does, + * over the organizational tree (parts / drawables) and the deformer armature. The UI reads the band + * for its indicator and resolves the drop for its dispatch through the SAME functions here, so the + * line / fill the user sees always matches the move that happens. The tree transforms themselves + * (withOrgChildMoved / withDeformerMoved) live in StructureEdits.kt; this file only routes a drop to + * them. Mirrors the parameter panel's split (ParametersDropRules in :ui feeds ParameterTreeEdits + * here) - except the outliner's rules mention no UI types, so the whole resolution lives in :edit. + * + * アウトライナーのドロップ解決。行ドロップの帯域判定と移動先の解決を一箇所で行い、指標と実際の + * 移動が常に一致する。ツリー変換自体は StructureEdits.kt にある。 + */ + +/** + * Where an outliner drop is aimed: a real entity row, the synthetic puppet root (org-tree top level), + * or the synthetic Armature row (deformer-hierarchy root). Synthetic rows carry no [SelectionTarget], + * so the UI names them explicitly rather than overloading a null target. + */ +sealed interface OutlinerDropTarget { + /** A selectable outliner row (part, drawable, or deformer). */ + data class Entity(val target: SelectionTarget) : OutlinerDropTarget + + /** The synthetic puppet-root row - org children drop here to sit at the top level. */ + data object PuppetRoot : OutlinerDropTarget + + /** The synthetic Armature row - deformers drop here to become armature roots. */ + data object Armature : OutlinerDropTarget +} + +/** + * A resolved outliner drop: the concrete move a drop dispatches, plus whether the UI should expand + * the target row afterwards (a nest-inside drop opens the destination so the user sees the moved + * item land, rather than fearing it vanished into a collapsed branch). + */ +sealed interface OutlinerDrop { + /** True when the UI should expand the drop-target row after applying the move. */ + val expandTarget: Boolean + + /** Re-home a deformer in the armature's nesting hierarchy. */ + data class MoveDeformer( + val id: DeformerId, + val newParentId: DeformerId?, + val beforeId: DeformerId?, + override val expandTarget: Boolean, + ) : OutlinerDrop + + /** Re-home an org child (a part or drawable) in the organizational tree. */ + data class MoveOrgChild( + val child: OrgChild, + val newParentId: PartId?, + val before: OrgChild?, + override val expandTarget: Boolean, + ) : OutlinerDrop +} + +/** + * The single source of truth for what a drag will do, given what is dragged, the row under the pointer, + * and the pointer's vertical band within that row - used by BOTH the drop dispatch and the row's indicator, + * so the line / fill the user sees always matches the move that happens. + * + * Rules of thumb: + * - org children (parts / drawables) only drop inside the org tree (including the puppet root); deformers + * only inside the armature (including the Armature row); + * - a part dropped on another part reorders beside it (before / after at the midline), matching the + * parameters panel's group-on-group behaviour - nesting a part into a part is done by dropping beside + * a child inside the destination (or via Properties); + * - a drawable dropped on a part nests in the middle band and reorders at the edges; + * - a drawable target is only before / after (no children to nest into); + * - a cycle (part into its own subtree, deformer into its own subtree) returns null so the indicator and + * the dispatch agree that nothing will happen. + * + * @param SelectionTarget dragged The entity being dragged. + * @param OutlinerDropTarget target The row under the pointer. + * @param Float fraction The pointer's 0..1 position down the target row. + * @return RowDropBand? The resolved band, or null when the drop is not allowed. + */ +fun PuppetModel.outlinerDropBandFor(dragged: SelectionTarget, target: OutlinerDropTarget, fraction: Float): RowDropBand? { + // Resolve first so cycles / illegal pairings yield null - the indicator must match the dispatch. + resolveOutlinerDrop(dragged, target, fraction) ?: return null + return when (target) { + OutlinerDropTarget.PuppetRoot -> beforeOrAfter(fraction) + OutlinerDropTarget.Armature -> RowDropBand.Into + is OutlinerDropTarget.Entity -> entityDropBand(dragged, target.target, fraction) + } +} + +/** + * The band an entity-row drop shows once the pairing is known to be legal. + * + * @param SelectionTarget dragged The entity being dragged. + * @param SelectionTarget target The entity under the pointer. + * @param Float fraction The pointer's 0..1 position down the target row. + * @return RowDropBand The indicator band. + */ +private fun entityDropBand(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): RowDropBand = + when (target) { + // A part dropped on a part only reorders / reparents as a sibling of the target (Parameters + // group-on-group parity): the whole row is before / after at the midline, so moving folders is + // not fighting a wide "into" band. Nesting a part into a part is dropping beside a child inside + // it (or via Properties). A drawable onto a part still gets Into. + is SelectionTarget.Part -> + if (dragged is SelectionTarget.Part) { + beforeOrAfter(fraction) + } else { + nestingContainerBand(fraction) + } + is SelectionTarget.Deformer -> nestingContainerBand(fraction) + is SelectionTarget.Drawable -> beforeOrAfter(fraction) + } + +/** Before above the row's midline, After below it. */ +private fun beforeOrAfter(fraction: Float): RowDropBand = + if (fraction >= 0.5f) RowDropBand.After else RowDropBand.Before + +/** Wider middle "into" band with before / after reorder at the edges (container rows that nest). */ +private fun nestingContainerBand(fraction: Float): RowDropBand = + when { + fraction < 0.33f -> RowDropBand.Before + fraction > 0.66f -> RowDropBand.After + else -> RowDropBand.Into + } + +/** + * This selection target as an [OrgChild] (a part or drawable), or null for a deformer (not in the org tree). + * + * @return OrgChild? The org-tree child, or null. + */ +fun SelectionTarget.asOrgChild(): OrgChild? = + when (this) { + is SelectionTarget.Part -> OrgChild.Part(id) + is SelectionTarget.Drawable -> OrgChild.Drawable(id) + is SelectionTarget.Deformer -> null + } + +/** The org child [child]'s sibling list - its owning part's children, or the root level when it is top-level. */ +private fun PuppetModel.orgSiblingsOf(child: OrgChild): List { + val parent = parts.firstOrNull { child in it.children } + return parent?.children ?: rootChildren +} + +/** The id of the part owning [child], or null when it is at the top level. */ +private fun PuppetModel.orgParentOf(child: OrgChild): PartId? = + parts.firstOrNull { child in it.children }?.id + +/** The org child immediately after [child] among its siblings, or null when it is last (append). */ +private fun PuppetModel.orgSiblingAfter(child: OrgChild): OrgChild? { + val siblings = orgSiblingsOf(child) + return siblings.getOrNull(siblings.indexOf(child) + 1) +} + +/** The deformer [id]'s parent in the nesting hierarchy, or null when it is an armature root. */ +private fun PuppetModel.deformerParentOf(id: DeformerId): DeformerId? = + deformers.firstOrNull { it.id == id }?.parent + +/** The deformer immediately after [id] among its same-parent siblings (list order), or null when last. */ +private fun PuppetModel.deformerSiblingAfter(id: DeformerId): DeformerId? { + val parent = deformerParentOf(id) + val siblings = deformers.filter { it.parent == parent }.map { it.id } + return siblings.getOrNull(siblings.indexOf(id) + 1) +} + +/** + * True when applying [drop] would nest a part / deformer inside its own subtree (a cycle the structure + * edit would refuse). Used so the band indicator stays blank rather than promising a no-op. + * + * @param OutlinerDrop drop The candidate move. + * @return Boolean True when the move is a cycle. + */ +private fun PuppetModel.outlinerDropIsCycle(drop: OutlinerDrop): Boolean = + when (drop) { + is OutlinerDrop.MoveOrgChild -> + drop.child is OrgChild.Part && + drop.newParentId != null && + drop.newParentId in partSelfAndDescendants(drop.child.id) + is OutlinerDrop.MoveDeformer -> + drop.newParentId != null && drop.newParentId in deformerSelfAndDescendants(drop.id) + } + +/** + * Resolves a drop of [dragged] onto [target] at [fraction] into the concrete move it performs, routed + * by the pointer's vertical band within the target row (the same [outlinerDropBandFor] the indicator + * drew): + * - before / after a sibling: re-home the dragged item next to the target in its parent (parts and + * drawables interleave, so a drawable can land between two parts) - which changes the panel order, + * hence the draw-order tiebreak, so the viewport follows when draw orders are equal; + * - into a part (or a deformer): nest the dragged item inside it, expanding the target; + * - onto the puppet root: move an org child to the top level (before = front, after = append); + * - onto the Armature row: make a deformer an armature root. + * Drops with no valid band or across the org / armature boundary resolve to null - no move. Cycles + * resolve to null here too (not only inside the move transforms), so a release on a descendant of the + * dragged folder does nothing visibly rather than looking like a failed drag. + * + * @param SelectionTarget dragged The entity being dragged. + * @param OutlinerDropTarget target The row under the pointer. + * @param Float fraction The pointer's 0..1 position down the target row. + * @return OutlinerDrop? The move to dispatch, or null when the drop does nothing. + */ +fun PuppetModel.resolveOutlinerDrop(dragged: SelectionTarget, target: OutlinerDropTarget, fraction: Float): OutlinerDrop? { + val drop = + when (target) { + OutlinerDropTarget.PuppetRoot -> resolvePuppetRootDrop(dragged, fraction) + OutlinerDropTarget.Armature -> resolveArmatureDrop(dragged) + is OutlinerDropTarget.Entity -> resolveEntityDrop(dragged, target.target, fraction) + } ?: return null + return if (outlinerDropIsCycle(drop)) null else drop +} + +/** + * Moves an org child to the puppet-root level: before = insert at the front of [PuppetModel.rootChildren], + * after (or into) = append. + * + * @param SelectionTarget dragged The entity being dragged. + * @param Float fraction The pointer's 0..1 position down the root row. + * @return OutlinerDrop? The move, or null when [dragged] is not an org child. + */ +private fun PuppetModel.resolvePuppetRootDrop(dragged: SelectionTarget, fraction: Float): OutlinerDrop? { + val child = dragged.asOrgChild() ?: return null + return if (fraction < 0.5f) { + OutlinerDrop.MoveOrgChild(child, newParentId = null, before = rootChildren.firstOrNull(), expandTarget = false) + } else { + OutlinerDrop.MoveOrgChild(child, newParentId = null, before = null, expandTarget = false) + } +} + +/** + * Makes a deformer an armature root (appended among the parentless deformers). + * + * @param SelectionTarget dragged The entity being dragged. + * @return OutlinerDrop? The move, or null when [dragged] is not a deformer. + */ +private fun resolveArmatureDrop(dragged: SelectionTarget): OutlinerDrop? { + val id = (dragged as? SelectionTarget.Deformer)?.id ?: return null + return OutlinerDrop.MoveDeformer(id, newParentId = null, beforeId = null, expandTarget = true) +} + +/** + * Resolves a drop onto a real entity row from the pointer band (without going through + * [outlinerDropBandFor], which itself calls resolve - that would recurse). + * + * @param SelectionTarget dragged The entity being dragged. + * @param SelectionTarget target The entity under the pointer. + * @param Float fraction The pointer's 0..1 position down the target row. + * @return OutlinerDrop? The move, or null when the pairing is illegal. + */ +private fun PuppetModel.resolveEntityDrop(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): OutlinerDrop? { + if ((dragged is SelectionTarget.Deformer) != (target is SelectionTarget.Deformer)) { + return null + } + val band = entityDropBand(dragged, target, fraction) + if (dragged is SelectionTarget.Deformer && target is SelectionTarget.Deformer) { + return when (band) { + RowDropBand.Before -> + OutlinerDrop.MoveDeformer(dragged.id, deformerParentOf(target.id), beforeId = target.id, expandTarget = false) + RowDropBand.After -> + OutlinerDrop.MoveDeformer(dragged.id, deformerParentOf(target.id), beforeId = deformerSiblingAfter(target.id), expandTarget = false) + RowDropBand.Into -> + OutlinerDrop.MoveDeformer(dragged.id, target.id, beforeId = null, expandTarget = true) + } + } + val draggedChild = dragged.asOrgChild() ?: return null + val targetChild = target.asOrgChild() ?: return null + return when (band) { + RowDropBand.Before -> + OutlinerDrop.MoveOrgChild(draggedChild, orgParentOf(targetChild), before = targetChild, expandTarget = false) + RowDropBand.After -> + OutlinerDrop.MoveOrgChild(draggedChild, orgParentOf(targetChild), before = orgSiblingAfter(targetChild), expandTarget = false) + RowDropBand.Into -> + if (target is SelectionTarget.Part) { + OutlinerDrop.MoveOrgChild(draggedChild, target.id, before = null, expandTarget = true) + } else { + null + } + } +} + +/** + * Applies a resolved outliner drop as one undo step, dispatching to the matching structure edit. + * + * @param OutlinerDrop drop The resolved move. + */ +fun EditorSession.applyOutlinerDrop(drop: OutlinerDrop) { + when (drop) { + is OutlinerDrop.MoveDeformer -> moveDeformer(drop.id, drop.newParentId, drop.beforeId) + is OutlinerDrop.MoveOrgChild -> moveOrgChild(drop.child, drop.newParentId, drop.before) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterCrudEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterCrudEdits.kt new file mode 100644 index 0000000..f9bc9a8 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterCrudEdits.kt @@ -0,0 +1,454 @@ +package org.umamo.edit + +import org.umamo.runtime.keyform.CollapsedChannels +import org.umamo.runtime.keyform.colorOr +import org.umamo.runtime.keyform.flagOr +import org.umamo.runtime.keyform.hasFractionalDrawOrder +import org.umamo.runtime.keyform.integralDrawOrderOrNull +import org.umamo.runtime.keyform.scalarOr +import org.umamo.runtime.keyform.withAxisCollapsed +import org.umamo.runtime.keyform.withAxisCollapsedLifting +import org.umamo.runtime.keyform.withAxisRetargeted +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot + +/* + * Parameter document edits: create a new axis, rename one (its display name), and delete one everywhere. + * Create and rename mirror the group edits (ParameterGroupEdits.kt) - pure PuppetModel.withX plus thin + * EditorSession wrappers through mutate. Delete is the heavier one: besides the flat parameters list, the + * panel tree, and any link, it must scrub the parameter out of every object's keyform grid and blend-shape + * binding, since each grid axis / binding references a parameter by id. The default path collapses each + * axis to the deleted parameter's default slice (discarding off-axis motion). An optional moveKeysTo + * destination retargets those axes onto another parameter instead, keeping key values and forms. + * The live pose entry is dropped in the session wrapper (pose lives on EditorSession). + * + * パラメータの作成・改名・削除。削除は各オブジェクトのキーフォーム格子から該当軸を取り除き、既定値の + * スライスへ畳み込む。moveKeysTo 指定時は軸を別パラメータへ付け替える。 + */ + +/** + * A fresh CParameterSource-style idstr ("Param", then "Param2", "Param3", ...) that collides with no + * existing parameter id. Deterministic from the model alone so the same edit replays identically under + * undo / redo - no clock, no random. + * + * // CMO3: CParameterSource id idstr - editor-minted sequential parameter identifiers. + * + * @return ParameterId A parameter id not already present in this model. + */ +fun PuppetModel.freshParameterId(): ParameterId { + val existing = parameters.map { parameter -> parameter.id }.toSet() + if (ParameterId("Param") !in existing) { + return ParameterId("Param") + } + var suffix = 2 + while (ParameterId("Param$suffix") in existing) { + suffix++ + } + return ParameterId("Param$suffix") +} + +/** + * A copy of this model with a new animatable parameter [newId] named [name] of [kind] appended to the axis + * list and its leaf prepended at the root top of the panel tree (so it lands on-screen for the immediate + * inline rename, like a new group). The default -1..1 / 0 range makes it animatable (min < max) so it + * renders as a slider; it is a neutral starting point the user retargets in the range editor. A + * BLEND_SHAPE kind renders with square knob / key marks (it carries no keys until authoring captures + * them). Materializes a flat tree first for a group-less model, so the existing rows keep their order + * beneath the new parameter. Refuses (returns this same instance) a colliding id. + * + * @param ParameterId newId The minted id of the new parameter. + * @param String name The initial display name. + * @param ParameterKind kind The parameter kind (NORMAL key-form or BLEND_SHAPE); defaults to NORMAL. + * @return PuppetModel The model with the parameter added, or this if the id already exists. + */ +fun PuppetModel.withParameterCreated( + newId: ParameterId, + name: String, + kind: ParameterKind = ParameterKind.NORMAL, +): PuppetModel { + if (parameters.any { parameter -> parameter.id == newId }) { + return this + } + val newParameter = Parameter(newId, name, min = -1f, max = 1f, default = 0f, kind = kind) + val newLeaf = ParameterNode.Param(newId) + return copy( + parameters = parameters + newParameter, + parameterTree = listOf(newLeaf) + materializedParameterTree(), + ) +} + +/** + * A copy of this model with parameter [id] renamed to [newName] (trimmed). The id is format-level and + * never changes - only the display name. A blank name is a no-op (returns this same instance), so an empty + * commit keeps the old label; an unchanged name likewise returns this. + * + * @param ParameterId id The parameter to rename. + * @param String newName The new display name (trimmed; blank is ignored). + * @return PuppetModel The model with the parameter renamed, or this if unchanged or blank. + */ +fun PuppetModel.withParameterRenamed(id: ParameterId, newName: String): PuppetModel { + val trimmed = newName.trim() + if (trimmed.isEmpty()) { + return this + } + var changed = false + val newParameters = + parameters.map { parameter -> + if (parameter.id == id && parameter.name != trimmed) { + changed = true + parameter.copy(name = trimmed) + } else { + parameter + } + } + return if (changed) { + copy(parameters = newParameters) + } else { + this + } +} + +/** + * A copy of this model with parameter [id] removed everywhere: the axis list, every panel-tree leaf, any + * link it belongs to (its partner reverts to a plain slider), and every keyform grid / blend-shape binding + * in the rig - drawables, both deformer kinds, parts, and glue intensities. + * + * Without [moveKeysTo], dropping the deleted axis collapses each grid to the slice at the parameter's + * default value (the neutral look), discarding that axis's motion. A channel track left with no axes is + * dropped, and the value of its kept slice is lifted into the owner's static so the neutral look survives + * the drop; a fractional part draw order stays behind as a constant track because the Int static slot + * cannot hold it without rounding. A geometry grid left with no axes becomes null (the drawable returns + * to its rest mesh - the base mesh is authored, never baked from a slice). Blend-shape bindings driven by + * [id] are dropped, and weight-limit curves that constrain on [id] are scrubbed. + * + * With [moveKeysTo], each matching axis is retargeted onto that destination instead (key values and forms + * kept absolute). When a grid already keys the destination, the destination axis collapses to its default + * slice first so the source's keys take over. Blend-shape bindings and weight-limit curves retarget the + * same way; a destination binding on the same owner is dropped in favour of the moved source. + * + * The render root is re-derived at the end so its per-group copies of the part tracks lose the deleted + * axis too. The live pose entry is dropped by the session wrapper. A no-op (no such parameter, or a + * missing / self [moveKeysTo]) returns this same instance. + * + * @param ParameterId id The parameter to delete. + * @param ParameterId? moveKeysTo Destination to retarget keys onto, or null to discard them. + * @return PuppetModel The model with the parameter removed, or this if it was absent / the move is invalid. + */ +fun PuppetModel.withParameterDeleted(id: ParameterId, moveKeysTo: ParameterId? = null): PuppetModel { + val deleted = parameters.firstOrNull { parameter -> parameter.id == id } ?: return this + val destination = + if (moveKeysTo != null) { + if (moveKeysTo == id) { + return this + } + parameters.firstOrNull { parameter -> parameter.id == moveKeysTo } ?: return this + } else { + null + } + val keepValue = deleted.default + val destinationKeepValue = destination?.default ?: 0f + // Both halves of a drawable key on parameters: the geometry grid and every channel track. + val newDrawables = + drawables.map { drawable -> + val geometry = + if (destination != null) { + drawable.geometryGrid?.withAxisRetargeted(id, destination.id, destinationKeepValue) + } else { + drawable.geometryGrid?.withAxisCollapsed(id, keepValue) + } + val scrubbed = + if (destination != null) { + CollapsedChannels( + drawable.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue), + emptyMap(), + ) + } else { + drawable.channelGrids.withAxisCollapsedLifting(id, keepValue) + } + val blendShapes = drawable.blendShapes.withParameterScrubbed(id, destination?.id) + if ( + geometry === drawable.geometryGrid && + scrubbed.channelGrids === drawable.channelGrids && + blendShapes === drawable.blendShapes + ) { + drawable + } else { + drawable.copy( + geometryGrid = geometry, + channelGrids = scrubbed.channelGrids, + drawOrder = scrubbed.lifted.scalarOr(FormChannel.DRAW_ORDER, drawable.drawOrder), + opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, drawable.opacity), + multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor), + screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, drawable.screenColor), + blendShapes = blendShapes, + ) + } + } + // Both halves of a deformer key on parameters: the geometry grid and every channel track. + val newDeformers = + deformers.map { deformer -> + val scrubbed = + if (destination != null) { + CollapsedChannels( + deformer.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue), + emptyMap(), + ) + } else { + deformer.channelGrids.withAxisCollapsedLifting(id, keepValue) + } + when (deformer) { + is Deformer.Warp -> { + val geometry = + if (destination != null) { + deformer.geometryGrid?.withAxisRetargeted(id, destination.id, destinationKeepValue) + } else { + deformer.geometryGrid?.withAxisCollapsed(id, keepValue) + } + val blendShapes = deformer.blendShapes.withParameterScrubbed(id, destination?.id) + if ( + geometry === deformer.geometryGrid && + scrubbed.channelGrids === deformer.channelGrids && + blendShapes === deformer.blendShapes + ) { + deformer + } else { + deformer.copy( + geometryGrid = geometry, + channelGrids = scrubbed.channelGrids, + opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, deformer.opacity), + multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, deformer.multiplyColor), + screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, deformer.screenColor), + blendShapes = blendShapes, + ) + } + } + + is Deformer.Rotation -> { + val geometry = + if (destination != null) { + deformer.geometryGrid?.withAxisRetargeted(id, destination.id, destinationKeepValue) + } else { + deformer.geometryGrid?.withAxisCollapsed(id, keepValue) + } + val blendShapes = deformer.blendShapes.withParameterScrubbed(id, destination?.id) + if ( + geometry === deformer.geometryGrid && + scrubbed.channelGrids === deformer.channelGrids && + blendShapes === deformer.blendShapes + ) { + deformer + } else { + deformer.copy( + geometryGrid = geometry, + channelGrids = scrubbed.channelGrids, + opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, deformer.opacity), + multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, deformer.multiplyColor), + screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, deformer.screenColor), + flipX = scrubbed.lifted.flagOr(FormChannel.FLIP_X, deformer.flipX), + flipY = scrubbed.lifted.flagOr(FormChannel.FLIP_Y, deformer.flipY), + blendShapes = blendShapes, + ) + } + } + } + } + val newParts = + parts.map { part -> + val scrubbed = + if (destination != null) { + CollapsedChannels( + part.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue), + emptyMap(), + ) + } else { + part.channelGrids.withAxisCollapsedLifting(id, keepValue) + } + val blendShapes = part.blendShapes.withParameterScrubbed(id, destination?.id) + if (scrubbed.channelGrids === part.channelGrids && blendShapes === part.blendShapes) { + part + } else { + val channels = + if (destination != null) { + scrubbed.channelGrids + } else { + scrubbed.withFractionalDrawOrderKept().channelGrids + } + part.copy( + channelGrids = channels, + drawOrder = scrubbed.lifted.integralDrawOrderOrNull() ?: part.drawOrder, + composite = + part.composite.copy( + opacity = scrubbed.lifted.scalarOr(FormChannel.OPACITY, part.composite.opacity), + multiplyColor = scrubbed.lifted.colorOr(FormChannel.MULTIPLY_COLOR, part.composite.multiplyColor), + screenColor = scrubbed.lifted.colorOr(FormChannel.SCREEN_COLOR, part.composite.screenColor), + ), + blendShapes = blendShapes, + ) + } + } + // Glue tracks key on parameters exactly like the rest, so they need the same scrub - without it a + // deleted parameter survives as a dangling KeyformAxis.parameterId that nothing can ever resolve. + val newGlues = + glues.map { glue -> + val scrubbed = + if (destination != null) { + CollapsedChannels( + glue.channelGrids.withAxisRetargeted(id, destination.id, destinationKeepValue), + emptyMap(), + ) + } else { + glue.channelGrids.withAxisCollapsedLifting(id, keepValue) + } + if (scrubbed.channelGrids === glue.channelGrids) { + glue + } else { + glue.copy( + channelGrids = scrubbed.channelGrids, + intensity = scrubbed.lifted.scalarOr(FormChannel.GLUE_INTENSITY, glue.intensity), + ) + } + } + return copy( + parameters = parameters.filterNot { parameter -> parameter.id == id }, + parameterLinks = parameterLinks.filterNot { link -> link.horizontal == id || link.vertical == id }, + parameterTree = removeParameterLeaf(parameterTree, id), + drawables = newDrawables, + deformers = newDeformers, + parts = newParts, + glues = newGlues, + ).withDerivedRenderRoot() +} + +/** + * These blend-shape bindings with [id] discarded or retargeted onto [moveKeysTo]. Destination bindings + * on the same owner yield to a moved source. Weight-limit curves that constrain on [id] follow the same + * rule. Returns this same list when nothing referenced [id]. + */ +private fun List>.withParameterScrubbed( + id: ParameterId, + moveKeysTo: ParameterId?, +): List> { + val hasSource = any { binding -> binding.parameterId == id } + val touchesId = + hasSource || any { binding -> binding.limits.any { limit -> limit.parameterId == id } } + if (!touchesId) { + return this + } + var changed = false + val result = ArrayList>(size) + for (binding in this) { + when { + binding.parameterId == id && moveKeysTo != null -> { + changed = true + result += + binding.copy( + parameterId = moveKeysTo, + limits = binding.limits.withConstraintScrubbed(id, moveKeysTo), + ) + } + binding.parameterId == id -> { + changed = true + } + binding.parameterId == moveKeysTo && hasSource -> { + changed = true + } + else -> { + val newLimits = binding.limits.withConstraintScrubbed(id, moveKeysTo) + if (newLimits !== binding.limits) { + changed = true + result += binding.copy(limits = newLimits) + } else { + result += binding + } + } + } + } + return if (changed) result else this +} + +/** These weight-limit curves with [id] discarded or retargeted onto [moveKeysTo]. */ +private fun List.withConstraintScrubbed( + id: ParameterId, + moveKeysTo: ParameterId?, +): List { + if (none { limit -> limit.parameterId == id }) { + return this + } + return if (moveKeysTo != null) { + mapNotNull { limit -> + when { + limit.parameterId == id -> limit.copy(parameterId = moveKeysTo) + limit.parameterId == moveKeysTo -> null + else -> limit + } + } + } else { + filterNot { limit -> limit.parameterId == id } + } +} + +/** + * These collapsed channels with a fractional lifted DRAW_ORDER kept as a zero-axis constant track. + * + * A part's static draw-order slot is an Int, so a fractional slice value cannot lift without rounding, + * and rounding could reorder two parts the track kept distinct. The deleted axis cannot stay either, so + * the value is kept as a single-cell track with no axes - the same degenerate shape MOC3 import already + * produces - which the evaluator reads as a constant. + * + * @return CollapsedChannels The channels with the fractional draw order retained as a constant track. + */ +private fun CollapsedChannels.withFractionalDrawOrderKept(): CollapsedChannels { + if (!lifted.hasFractionalDrawOrder()) { + return this + } + val constantTrack = KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), lifted[FormChannel.DRAW_ORDER]!!))) + return CollapsedChannels( + ChannelGrids(channelGrids.gridsByChannel + (FormChannel.DRAW_ORDER to constantTrack)), + lifted, + ) +} + +/** This node list with every [ParameterNode.Param] leaf for [id] spliced out, recursing into groups. */ +private fun removeParameterLeaf(nodes: List, id: ParameterId): List = + nodes.mapNotNull { node -> + when (node) { + is ParameterNode.Param -> if (node.id == id) null else node + is ParameterNode.Group -> node.copy(children = removeParameterLeaf(node.children, id)) + } + } + +/** + * Creates a new animatable parameter (a freshly minted id, default -1..1 range) named [name] of [kind] + * and returns its id, so the caller can immediately open inline rename on it. One undo step. + * + * @param String name The initial display name. + * @param ParameterKind kind The parameter kind (NORMAL key-form or BLEND_SHAPE); defaults to NORMAL. + * @return ParameterId The id of the created parameter. + */ +fun EditorSession.createParameter(name: String, kind: ParameterKind = ParameterKind.NORMAL): ParameterId { + val id = model.value.freshParameterId() + mutate(ParameterChange.Create(id)) { model -> model.withParameterCreated(id, name, kind) } + return id +} + +/** + * Renames parameter [id]'s display name to [newName] (trimmed) as one undo step. A blank or unchanged + * name records nothing. + * + * @param ParameterId id The parameter to rename. + * @param String newName The new display name. + */ +fun EditorSession.renameParameter(id: ParameterId, newName: String) { + mutate(ParameterChange.Rename(id, newName.trim())) { model -> model.withParameterRenamed(id, newName) } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterEdits.kt new file mode 100644 index 0000000..d4c8627 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterEdits.kt @@ -0,0 +1,87 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.PuppetModel + +/** + * A copy of this model with parameter [id]'s range set to [min]..[max] and its default clamped within + * it. The range is normalized so the stored minimum never exceeds the maximum regardless of entry order + * (typing a maximum below the current minimum still yields a valid range). The default is coerced into + * the resulting range. Returns this same instance unchanged when nothing actually differs (so the caller + * need not pre-check) or when [id] is not a parameter of this model. + * + * Pure over the model: it does not touch the live pose. Re-clamping the live value into a shrunk range + * is the session's concern, since the pose is editor state held outside the model. + * + * パラメータ [id] の範囲(最小・最大)と既定値を設定したモデルのコピー。範囲は最小≤最大に正規化し、 + * 既定値は範囲内に丸める。変化が無ければ同一インスタンスを返す。ライブのポーズには触れない。 + * + * @param ParameterId id The parameter to retarget. + * @param Float min The requested minimum. + * @param Float default The requested default (clamped into the resulting range). + * @param Float max The requested maximum. + * @return PuppetModel This model with the parameter's range and default updated, or this if unchanged. + */ +fun PuppetModel.withParameterRange(id: ParameterId, min: Float, default: Float, max: Float): PuppetModel { + val low = minOf(min, max) + val high = maxOf(min, max) + val clampedDefault = default.coerceIn(low, high) + val updated = + parameters.map { parameter -> + if (parameter.id == id) { + parameter.copy(min = low, max = high, default = clampedDefault) + } else { + parameter + } + } + if (updated == parameters) { + return this + } + return copy(parameters = updated) +} + +/** + * A copy of this model with the parameter link [horizontal]->[vertical] added ([linked] = true) or + * removed ([linked] = false). The model edit is the invariant keeper - any UI-side validity check is + * advisory only - so an invalid request returns this same instance unchanged (and the session's + * same-instance short-circuit then records no undo step): a link is refused when either id already + * belongs to any existing link, when the ids are equal, or when either id is not a parameter of this + * model; an unlink of a pair that is not present is a no-op. + * + * Pure over the model: values, ranges, and the live pose are untouched - a link only changes how the + * pair presents (one 2D pad instead of two sliders). + * + * // CMO3: CParameterSource.combined - the first member flags the pair, the partner is the next + * // parameter in document order (see Cmo3Import's link derivation). + * + * パラメータリンクを追加または削除したモデルのコピー。無効な要求(既にリンク済み・同一 ID・未知の + * ID・存在しないペアの解除)は同一インスタンスを返し、取り消し段も記録されない。値やポーズには + * 触れない。 + * + * @param ParameterId horizontal The X-axis (upper) parameter. + * @param ParameterId vertical The Y-axis parameter (the next parameter below in panel order). + * @param Boolean linked True to create the link, false to remove it. + * @return PuppetModel This model with the link added / removed, or this same instance when refused. + */ +fun PuppetModel.withParameterLink(horizontal: ParameterId, vertical: ParameterId, linked: Boolean): PuppetModel { + if (linked) { + if (horizontal == vertical) { + return this + } + val knownIds = parameters.map { parameter -> parameter.id }.toSet() + if (horizontal !in knownIds || vertical !in knownIds) { + return this + } + val linkedMembers = parameterLinks.flatMap { link -> listOf(link.horizontal, link.vertical) }.toSet() + if (horizontal in linkedMembers || vertical in linkedMembers) { + return this + } + return copy(parameterLinks = parameterLinks + ParameterLink(horizontal, vertical)) + } + val remaining = parameterLinks.filterNot { link -> link.horizontal == horizontal && link.vertical == vertical } + if (remaining.size == parameterLinks.size) { + return this + } + return copy(parameterLinks = remaining) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterGroupEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterGroupEdits.kt new file mode 100644 index 0000000..12e7b68 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterGroupEdits.kt @@ -0,0 +1,142 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel + +/* + * Parameter-group document edits: create an empty group, delete (unwrap) a group keeping its parameters, + * and rename a group. All operate on PuppetModel.parameterTree (layout) and never touch the flat + * parameters list or the links; each undoes for free through EditorSession.mutate's whole-model snapshot. + * Reuses materializedParameterTree / collectParameterGroupIds from ParameterTreeEdits. + * + * パラメータグループの編集:空グループ作成・グループ解除(子は残す)・改名。parameterTree のみを変更。 + */ + +/** + * A fresh CParameterGroup-style idstr ("ParamGroup", then "ParamGroup2", "ParamGroup3", ...) that + * collides with no existing group id anywhere in the tree. Deterministic from the model alone so the + * same edit replays identically under undo / redo - no clock, no random. + * + * // CMO3: CParameterGroupId.idstr - editor-minted sequential group identifiers. + * + * @return ParameterGroupId A group id not already present in this model. + */ +fun PuppetModel.freshParameterGroupId(): ParameterGroupId { + val existing = collectParameterGroupIds(parameterTree) + if (ParameterGroupId("ParamGroup") !in existing) { + return ParameterGroupId("ParamGroup") + } + var suffix = 2 + while (ParameterGroupId("ParamGroup$suffix") in existing) { + suffix++ + } + return ParameterGroupId("ParamGroup$suffix") +} + +/** + * A copy of this model with a new empty group [newGroupId] named [name] inserted at the top of the + * parameter root, expanded. Materializes a flat tree first for a group-less model, so the existing rows + * keep their order beneath the new group. An empty group has no visual anchor, so it lands at the top of + * the scroll region where the user is already looking and its immediate inline-rename is on screen - + * rather than below the fold. Refuses (returns this same instance) a colliding id. + * + * @param ParameterGroupId newGroupId The minted id of the new group. + * @param String name The initial display name. + * @return PuppetModel The model with the group added, or this if the id already exists. + */ +fun PuppetModel.withParameterGroupCreated(newGroupId: ParameterGroupId, name: String): PuppetModel { + if (newGroupId in collectParameterGroupIds(parameterTree)) { + return this + } + val newGroup = ParameterNode.Group(newGroupId, name, initiallyOpen = true, children = emptyList()) + return copy(parameterTree = listOf(newGroup) + materializedParameterTree()) +} + +/** + * A copy of this model with group [groupId] dissolved: its child nodes splice into the tree at the + * group's own position and the group node is dropped, so no parameter is lost. Never touches the flat + * parameters list or the links. A no-op (no such group) returns this same instance. + * + * @param ParameterGroupId groupId The group to unwrap. + * @return PuppetModel The model with the group unwrapped, or this if it was absent. + */ +fun PuppetModel.withParameterGroupDeleted(groupId: ParameterGroupId): PuppetModel { + if (groupId !in collectParameterGroupIds(parameterTree)) { + return this + } + + fun splice(nodes: List): List = + nodes.flatMap { node -> + when { + node is ParameterNode.Group && node.id == groupId -> node.children + node is ParameterNode.Group -> listOf(node.copy(children = splice(node.children))) + else -> listOf(node) + } + } + return copy(parameterTree = splice(parameterTree)) +} + +/** + * A copy of this model with group [groupId] renamed to [newName] (trimmed). A blank name is a no-op + * (returns this same instance), so an empty commit keeps the old label. Names are user data - never + * localized - and are not unique; identity is the group id, so only the matching node changes. + * + * @param ParameterGroupId groupId The group to rename. + * @param String newName The new display name (trimmed; blank is ignored). + * @return PuppetModel The model with the group renamed, or this if unchanged or blank. + */ +fun PuppetModel.withParameterGroupRenamed(groupId: ParameterGroupId, newName: String): PuppetModel { + val trimmed = newName.trim() + if (trimmed.isEmpty()) { + return this + } + + fun rename(nodes: List): List = + nodes.map { node -> + when { + node is ParameterNode.Group && node.id == groupId -> node.copy(name = trimmed) + node is ParameterNode.Group -> node.copy(children = rename(node.children)) + else -> node + } + } + val newTree = rename(parameterTree) + if (newTree == parameterTree) { + return this + } + return copy(parameterTree = newTree) +} + +/** + * Creates a new empty parameter group (a freshly minted id, expanded) and returns its id, so the caller + * can immediately open inline rename on it. One undo step. + * + * @param String name The initial display name. + * @return ParameterGroupId The id of the created group. + */ +fun EditorSession.createParameterGroup(name: String): ParameterGroupId { + val id = model.value.freshParameterGroupId() + mutate(ParameterChange.CreateGroup(id)) { model -> model.withParameterGroupCreated(id, name) } + return id +} + +/** + * Deletes (unwraps) parameter group [id], splicing its parameters into the parent, as one undo step. A + * no-op records nothing. + * + * @param ParameterGroupId id The group to unwrap. + */ +fun EditorSession.deleteParameterGroup(id: ParameterGroupId) { + mutate(ParameterChange.DeleteGroup(id)) { model -> model.withParameterGroupDeleted(id) } +} + +/** + * Renames parameter group [id] to [newName] (trimmed) as one undo step. A blank or unchanged name + * records nothing. + * + * @param ParameterGroupId id The group to rename. + * @param String newName The new display name. + */ +fun EditorSession.renameParameterGroup(id: ParameterGroupId, newName: String) { + mutate(ParameterChange.RenameGroup(id, newName.trim())) { model -> model.withParameterGroupRenamed(id, newName) } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterTreeEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterTreeEdits.kt new file mode 100644 index 0000000..cfe16e7 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ParameterTreeEdits.kt @@ -0,0 +1,257 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel + +/* + * Parameter-panel group-tree structure edits. PuppetModel.parameterTree is the canonical panel order + * (an ordered mix of parameter leaves and named groups); the flat parameters list stays the id-keyed + * authoritative axis list, whose ORDER nothing reads at runtime once a tree exists. So a reorder or a + * move into / out of a group rewrites ONLY parameterTree, leaving parameters and parameterLinks alone - + * the future CMO3 exporter flattens the tree for the _sources order. A model imported with no groups + * has an empty tree; the first real structure edit materializes a flat all-leaves-at-root tree so there + * is one code path afterward. Every edit snapshots the whole PuppetModel through EditorSession.mutate, + * so it undoes for free. + * + * パラメータパネルのグループツリー構造編集。parameterTree が表示順の正で、平坦な parameters は id 基準 + * の軸リスト。並べ替え・グループ出入りは parameterTree だけを書き換える。 + */ + +/** + * What a parameter-tree move relocates: a run of one or two adjacent parameter leaves (a slider is one + * leaf, a linked 2D pad is two, moved contiguously so they stay adjacent for combined CMO3 export), or a + * whole group. + */ +sealed interface ParameterMoveSubject { + /** One or two adjacent parameter leaves, in order (a pad is horizontal then vertical). */ + data class Leaves(val ids: List) : ParameterMoveSubject + + /** A whole group node, moved with its children intact. */ + data class Group(val id: ParameterGroupId) : ParameterMoveSubject +} + +/** + * A position anchor in the parameter tree - "insert before this node". Null anywhere a ref is expected + * means "append at the destination's end". + */ +sealed interface ParameterNodeRef { + /** Anchor on a parameter leaf. */ + data class Leaf(val id: ParameterId) : ParameterNodeRef + + /** Anchor on a group. */ + data class Group(val id: ParameterGroupId) : ParameterNodeRef +} + +/** + * This model's parameter tree, materializing a flat all-leaves-at-root tree when the model carries no + * groups. Gives structure edits one shape to operate on: a group-less model becomes a root list of + * [ParameterNode.Param] in the flat parameters order (which is what the panel already renders for an + * empty tree), so the first move / group edit has a tree to rewrite. + * + * @return List The existing tree, or a freshly materialized flat one. + */ +internal fun PuppetModel.materializedParameterTree(): List = + if (parameterTree.isEmpty()) { + parameters.map { parameter -> ParameterNode.Param(parameter.id) } + } else { + parameterTree + } + +/** + * Every group id anywhere in [nodes], recursing into nested groups. Used to mint collision-free ids and + * to validate a move destination. + * + * @param List nodes The tree (or subtree) to scan. + * @return Set Every group id present. + */ +internal fun collectParameterGroupIds(nodes: List): Set { + val ids = HashSet() + + fun walk(list: List) { + for (node in list) { + if (node is ParameterNode.Group) { + ids.add(node.id) + walk(node.children) + } + } + } + walk(nodes) + return ids +} + +/** The node ids removed by a detach for [subject] (leaf ids, or the single group id). */ +private fun ParameterMoveSubject.movedLeafIds(): Set = + when (this) { + is ParameterMoveSubject.Leaves -> ids.toSet() + is ParameterMoveSubject.Group -> emptySet() + } + +/** The group id removed by a detach for [subject], or null when it moves leaves. */ +private fun ParameterMoveSubject.movedGroupId(): ParameterGroupId? = + when (this) { + is ParameterMoveSubject.Leaves -> null + is ParameterMoveSubject.Group -> id + } + +/** + * Removes the moved node(s) from a node list (non-recursively at this level), returning the survivors and + * the detached group node when [subject] was a group found here. + */ +private fun List.detachSubject(subject: ParameterMoveSubject): List { + val movedLeaves = subject.movedLeafIds() + val movedGroup = subject.movedGroupId() + return filterNot { node -> + when (node) { + is ParameterNode.Param -> node.id in movedLeaves + is ParameterNode.Group -> node.id == movedGroup + } + } +} + +/** This node list with [inserted] placed before [before] (or appended when [before] is null or absent). */ +private fun List.withNodesInsertedBefore(inserted: List, before: ParameterNodeRef?): List { + val result = toMutableList() + val insertAt = + before?.let { ref -> + result.indexOfFirst { node -> node.matchesRef(ref) } + }?.takeIf { index -> index >= 0 } ?: result.size + result.addAll(insertAt, inserted) + return result +} + +/** True when this node is the one [ref] names. */ +private fun ParameterNode.matchesRef(ref: ParameterNodeRef): Boolean = + when { + this is ParameterNode.Param && ref is ParameterNodeRef.Leaf -> id == ref.id + this is ParameterNode.Group && ref is ParameterNodeRef.Group -> id == ref.id + else -> false + } + +/** + * A copy of this model with [subject] relocated in the parameter-panel group tree: under + * [newParentGroupId] (null = the root level) and inserted before [before] there (null / absent = + * appended). The flat parameters list and the links are untouched - this is layout only. Materializes a + * flat tree first when the model has no groups, so one code path serves grouped and group-less models. + * The moved leaves are always re-inserted contiguously in [subject] order, so a linked pad keeps its + * two members adjacent regardless of a slightly-off UI anchor. Refuses - returning this same instance, + * so the session records no undo step - a group moved under any group (groups do not nest one level + * deep), an unknown destination group, and any no-op move. + * + * @param ParameterMoveSubject subject The leaves or group to move. + * @param ParameterGroupId? newParentGroupId The destination group, or null for the root level. + * @param ParameterNodeRef? before The sibling to insert before, or null to append. + * @return PuppetModel The model with the move applied, or this if it was a no-op or illegal. + */ +fun PuppetModel.withParameterRowMoved( + subject: ParameterMoveSubject, + newParentGroupId: ParameterGroupId?, + before: ParameterNodeRef?, +): PuppetModel { + // One level only: a group can be reordered among root nodes but never dropped inside another group. + if (subject is ParameterMoveSubject.Group && newParentGroupId != null) { + return this + } + val workingTree = materializedParameterTree() + if (newParentGroupId != null && newParentGroupId !in collectParameterGroupIds(workingTree)) { + return this + } + // Detached-first snapshot of what is being moved, resolved before the tree loses it. + val insertedNodes = collectSubjectNodes(workingTree, subject) + if (insertedNodes.isEmpty()) { + return this + } + // Detach at the root and inside every group. + val detachedRoot = + workingTree.detachSubject(subject).map { node -> + if (node is ParameterNode.Group) { + node.copy(children = node.children.detachSubject(subject)) + } else { + node + } + } + val newTree: List = + if (newParentGroupId == null) { + detachedRoot.withNodesInsertedBefore(insertedNodes, before) + } else { + detachedRoot.map { node -> + if (node is ParameterNode.Group && node.id == newParentGroupId) { + node.copy(children = node.children.withNodesInsertedBefore(insertedNodes, before)) + } else { + node + } + } + } + if (newTree == workingTree) { + return this + } + return copy(parameterTree = newTree) +} + +/** + * The actual [ParameterNode]s named by [subject], found anywhere in [tree]. Leaves are returned as fresh + * [ParameterNode.Param]s in [subject] order (so a pad stays horizontal-then-vertical); a group is + * returned as its existing node with children intact. Empty when nothing matched. + */ +private fun collectSubjectNodes(tree: List, subject: ParameterMoveSubject): List = + when (subject) { + is ParameterMoveSubject.Leaves -> { + val present = collectLeafIds(tree) + subject.ids.filter { id -> id in present }.map { id -> ParameterNode.Param(id) } + } + is ParameterMoveSubject.Group -> { + val found = findGroupNode(tree, subject.id) + if (found == null) { + emptyList() + } else { + listOf(found) + } + } + } + +/** Every leaf id anywhere in [nodes]. */ +private fun collectLeafIds(nodes: List): Set { + val ids = HashSet() + + fun walk(list: List) { + for (node in list) { + when (node) { + is ParameterNode.Param -> ids.add(node.id) + is ParameterNode.Group -> walk(node.children) + } + } + } + walk(nodes) + return ids +} + +/** The group node with [groupId] anywhere in [nodes], or null. */ +private fun findGroupNode(nodes: List, groupId: ParameterGroupId): ParameterNode.Group? { + for (node in nodes) { + if (node is ParameterNode.Group) { + if (node.id == groupId) { + return node + } + val nested = findGroupNode(node.children, groupId) + if (nested != null) { + return nested + } + } + } + return null +} + +/** + * Moves a parameter row - one or two adjacent leaves, or a group - in the panel tree as one undo step. + * A refused or no-op move records nothing. + * + * @param ParameterMoveSubject subject The leaves or group to move. + * @param ParameterGroupId? newParentGroupId The destination group, or null for the root level. + * @param ParameterNodeRef? before The sibling to insert before, or null to append. + */ +fun EditorSession.moveParameterRow(subject: ParameterMoveSubject, newParentGroupId: ParameterGroupId?, before: ParameterNodeRef?) { + mutate(ParameterChange.MoveNode(subject, newParentGroupId)) { model -> + model.withParameterRowMoved(subject, newParentGroupId, before) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/PolygonTriangulator.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/PolygonTriangulator.kt new file mode 100644 index 0000000..7caa133 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/PolygonTriangulator.kt @@ -0,0 +1,17 @@ +package org.umamo.edit + +/** + * Platform polygon triangulation for Add Vertex Accept (closed draft rings). + * + * JVM/Android use poly2tri constrained Delaunay so diagonals zigzag (maximize min angle) instead of + * cascading ears along the boundary. + */ +internal expect object PolygonTriangulator { + /** + * Triangulates a simple polygon given as interleaved [x0,y0, x1,y1, …]. + * + * @param DoubleArray xy Flat vertex coordinates (length = 2 × vertex count). + * @return IntArray Flat triangle indices into the polygon (groups of three); empty on refusal. + */ + fun triangulate(xy: DoubleArray): IntArray +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ProportionalEditing.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ProportionalEditing.kt new file mode 100644 index 0000000..0130837 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ProportionalEditing.kt @@ -0,0 +1,260 @@ +package org.umamo.edit + +import kotlin.math.sqrt + +/* Proportional editing (Blender's O): a modal transform also pulls the UNSELECTED vertices within an + * influence radius, each weighted by a falloff curve over its distance to the nearest selected vertex, + * so mesh edits feel like sculpting instead of vertex-by-vertex CAD. This file holds the pure math + * (the falloff curves and the weight map); the session carries the on/off state and the gizmo overlay + * feeds the weights into the weighted MeshTransforms variants. */ + +/** The influence radius proportional editing starts with, in world units (canvas px). */ +const val DEFAULT_PROPORTIONAL_RADIUS_WORLD: Float = 200f + +/** The smallest allowed influence radius, in world units. */ +const val MIN_PROPORTIONAL_RADIUS_WORLD: Float = 1f + +/** The largest allowed influence radius, in world units. */ +const val MAX_PROPORTIONAL_RADIUS_WORLD: Float = 100_000f + +/** + * The geometric factor one scroll-wheel step multiplies (or divides) the influence radius by during a + * modal transform, so a step stays proportional at any scale (Blender resizes its proportional circle + * the same way). + */ +const val PROPORTIONAL_RADIUS_STEP_FACTOR: Float = 1.1f + +/** + * The falloff curve shaping how a vertex's influence fades from 1 (at the selection) to 0 (at the + * radius edge) - Blender's proportional-editing falloff set, minus the randomized ones. + * + * プロポーショナル編集の減衰カーブの種類(Blender と同じ)。 + */ +enum class ProportionalFalloff { + Smooth, + Sphere, + Root, + Sharp, + Linear, + Constant, +} + +/** + * The proportional-editing configuration while it is enabled: the falloff curve, the influence + * radius, and whether influence spreads only through CONNECTED geometry (Blender's Connected Only - + * distances measured along mesh edges instead of straight-line, so the halo never leaps a gap to + * nearby-but-unconnected geometry). Transient session state like the tool latches (deliberately NOT + * part of EditorSnapshot); the last configuration is remembered across off/on toggles, the + * circle-select radius pattern. + * + * プロポーショナル編集の設定(減衰カーブ、影響半径、接続のみ)。オン・オフをまたいで記憶される一時状態。 + * + * @property ProportionalFalloff falloff The falloff curve. + * @property Float radiusWorld The influence radius, in world units (canvas px). + * @property Boolean connectedOnly True to measure influence along mesh edges (geodesic) instead of + * straight-line distance. + */ +data class ProportionalEditState( + val falloff: ProportionalFalloff, + val radiusWorld: Float, + val connectedOnly: Boolean = false, +) + +/** The proportional configuration a session starts with: the smooth falloff at the default radius. */ +val DEFAULT_PROPORTIONAL_EDIT_STATE: ProportionalEditState = ProportionalEditState(ProportionalFalloff.Smooth, DEFAULT_PROPORTIONAL_RADIUS_WORLD) + +/** + * The falloff weight at a normalized distance: 1 at the selection (distance 0), 0 at and beyond the + * radius edge (distance >= 1), shaped in between by the curve. The formulas match Blender's + * proportional falloffs over fade = 1 - distance: Smooth is the smoothstep 3·fade² - 2·fade³, Sphere is + * the quarter-circle sqrt(1 - distance²), Root is sqrt(fade), Sharp is fade², Linear is fade, and + * Constant is 1 everywhere inside the radius. + * + * @param ProportionalFalloff falloff The falloff curve. + * @param Float normalizedDistance The vertex's distance to the nearest selected vertex, divided by the + * influence radius (values below 0 clamp to full weight). + * @return Float The weight in [0, 1]. + */ +fun proportionalWeight(falloff: ProportionalFalloff, normalizedDistance: Float): Float { + if (normalizedDistance >= 1f) { + return 0f + } + if (normalizedDistance <= 0f) { + return 1f + } + val fade = 1f - normalizedDistance + return when (falloff) { + ProportionalFalloff.Smooth -> fade * fade * (3f - 2f * fade) + ProportionalFalloff.Sphere -> sqrt(1f - normalizedDistance * normalizedDistance) + ProportionalFalloff.Root -> sqrt(fade) + ProportionalFalloff.Sharp -> fade * fade + ProportionalFalloff.Linear -> fade + ProportionalFalloff.Constant -> 1f + } +} + +/** + * One influenced vertex's proportional-editing sample: its falloff weight and the covered vertex it + * measured its distance against. The nearest-covered identity is what lets Individual Origins anchor + * the influenced halo on the OWNING island's pivot instead of the shared gesture anchor - the weight + * alone cannot say which island a bystander vertex belongs with. + * + * @property Float weight The falloff weight in (0, 1]. + * @property Int nearestCoveredIndex The covered vertex this vertex measured its distance to. + */ +data class ProportionalInfluence( + val weight: Float, + val nearestCoveredIndex: Int, +) + +/** + * The proportional influence map for one mesh: every vertex NOT in [coveredIndices] whose distance to + * the nearest covered vertex is inside [radiusWorld] maps to its falloff weight plus that nearest + * covered vertex; covered vertices (they move at full strength through the pivot groups) and vertices + * outside the radius are absent. The distances are measured in whatever space [positions] lives in - + * the overlay passes the frozen world-posed shape, matching the world-unit radius. + * + * The nearest-covered scan is O(covered x uncovered), fine at rigging mesh sizes (hundreds of + * vertices); an acceleration structure can slot in here later without changing the contract. + * + * @param FloatArray positions The interleaved vertex positions the distances are measured in. + * @param Set coveredIndices The vertices the selection covers (excluded from the map). + * @param Float radiusWorld The influence radius, in the positions' units. + * @param ProportionalFalloff falloff The falloff curve shaping the weights. + * @return Map Vertex index to influence, for every influenced vertex. + */ +fun proportionalInfluences( + positions: FloatArray, + coveredIndices: Set, + radiusWorld: Float, + falloff: ProportionalFalloff, +): Map { + if (coveredIndices.isEmpty() || radiusWorld <= 0f) { + return emptyMap() + } + val radiusSquared = radiusWorld * radiusWorld + val influences = LinkedHashMap() + val vertexCount = positions.size / 2 + for (vertexIndex in 0 until vertexCount) { + if (vertexIndex in coveredIndices) { + continue + } + val vertexX = positions[vertexIndex * 2] + val vertexY = positions[vertexIndex * 2 + 1] + var nearestSquared = Float.MAX_VALUE + var nearestCovered = -1 + for (coveredIndex in coveredIndices) { + val deltaX = positions[coveredIndex * 2] - vertexX + val deltaY = positions[coveredIndex * 2 + 1] - vertexY + val distanceSquared = deltaX * deltaX + deltaY * deltaY + if (distanceSquared < nearestSquared) { + nearestSquared = distanceSquared + nearestCovered = coveredIndex + } + } + if (nearestSquared < radiusSquared && nearestCovered >= 0) { + val weight = proportionalWeight(falloff, sqrt(nearestSquared) / radiusWorld) + if (weight > 0f) { + influences[vertexIndex] = ProportionalInfluence(weight, nearestCovered) + } + } + } + return influences +} + +/** + * The proportional weight map for one mesh - [proportionalInfluences] reduced to the weights, for + * callers that need no nearest-covered identity. + * + * @param FloatArray positions The interleaved vertex positions the distances are measured in. + * @param Set coveredIndices The vertices the selection covers (excluded from the map). + * @param Float radiusWorld The influence radius, in the positions' units. + * @param ProportionalFalloff falloff The falloff curve shaping the weights. + * @return Map Vertex index to weight, for every influenced unselected vertex. + */ +fun proportionalWeights( + positions: FloatArray, + coveredIndices: Set, + radiusWorld: Float, + falloff: ProportionalFalloff, +): Map = proportionalInfluences(positions, coveredIndices, radiusWorld, falloff).mapValues { entry -> entry.value.weight } + +/** + * The CONNECTED-ONLY proportional influence map for one mesh: like [proportionalInfluences], but + * distance is geodesic - the shortest path along mesh edges (euclidean edge lengths) from the covered + * set - so influence flows through the surface and never leaps a gap to nearby-but-unconnected + * geometry (Blender's Connected Only). A vertex unreachable within [radiusWorld] takes no weight, + * and each influenced vertex reports the covered vertex its shortest path started from (the island + * ownership key, exactly like the straight-line variant). + * + * Dijkstra over the vertex adjacency, seeded at every covered vertex, with an early stop past the + * radius. The frontier scan is O(V) per settled vertex (no priority queue in common Kotlin) - fine + * at rigging mesh sizes, and the radius bound keeps the settled set local in practice. + * + * @param FloatArray positions The interleaved vertex positions (edge lengths measured here). + * @param Set coveredIndices The vertices the selection covers (the geodesic sources). + * @param Float radiusWorld The influence radius, along edges, in the positions' units. + * @param ProportionalFalloff falloff The falloff curve shaping the weights. + * @param IntArray triangleIndices The mesh's triangle vertex indices (the edge graph). + * @return Map Vertex index to influence, for every reachable vertex. + */ +fun proportionalInfluencesConnected( + positions: FloatArray, + coveredIndices: Set, + radiusWorld: Float, + falloff: ProportionalFalloff, + triangleIndices: IntArray, +): Map { + if (coveredIndices.isEmpty() || radiusWorld <= 0f) { + return emptyMap() + } + val vertexCount = positions.size / 2 + val adjacency = MeshTopology.buildVertexAdjacency(vertexCount, triangleIndices) + val distance = FloatArray(vertexCount) { Float.MAX_VALUE } + val sourceCovered = IntArray(vertexCount) { -1 } + val settled = BooleanArray(vertexCount) + for (coveredIndex in coveredIndices) { + if (coveredIndex in 0 until vertexCount) { + distance[coveredIndex] = 0f + sourceCovered[coveredIndex] = coveredIndex + } + } + while (true) { + // The unsettled frontier vertex nearest the covered set; past the radius nothing can gain weight. + var frontier = -1 + var frontierDistance = Float.MAX_VALUE + for (vertexIndex in 0 until vertexCount) { + if (!settled[vertexIndex] && distance[vertexIndex] < frontierDistance) { + frontierDistance = distance[vertexIndex] + frontier = vertexIndex + } + } + if (frontier < 0 || frontierDistance >= radiusWorld) { + break + } + settled[frontier] = true + for (neighbor in adjacency[frontier]) { + if (settled[neighbor]) { + continue + } + val deltaX = positions[neighbor * 2] - positions[frontier * 2] + val deltaY = positions[neighbor * 2 + 1] - positions[frontier * 2 + 1] + val candidate = frontierDistance + sqrt(deltaX * deltaX + deltaY * deltaY) + if (candidate < distance[neighbor]) { + distance[neighbor] = candidate + sourceCovered[neighbor] = sourceCovered[frontier] + } + } + } + val influences = LinkedHashMap() + for (vertexIndex in 0 until vertexCount) { + if (vertexIndex in coveredIndices || sourceCovered[vertexIndex] < 0 || distance[vertexIndex] >= radiusWorld) { + continue + } + val weight = proportionalWeight(falloff, distance[vertexIndex] / radiusWorld) + if (weight > 0f) { + influences[vertexIndex] = ProportionalInfluence(weight, sourceCovered[vertexIndex]) + } + } + return influences +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/PuppetModelEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/PuppetModelEdits.kt new file mode 100644 index 0000000..c432db7 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/PuppetModelEdits.kt @@ -0,0 +1,1269 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtworkAdditions +import org.umamo.runtime.model.ArtworkReload +import org.umamo.runtime.model.AtlasComposition +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.OrgInsertion +import org.umamo.runtime.model.OrgSlot +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.multiplyColor +import org.umamo.runtime.model.opacity +import org.umamo.runtime.model.screenColor +import org.umamo.runtime.model.storedToArtAffineForTile +import org.umamo.runtime.model.withDerivedRenderRoot + +/* + * Pure transforms over the immutable PuppetModel: each returns a new model that structurally shares + * every unchanged entity with its input (a data class copy replaces only the touched list element), + * so producing a snapshot costs O(changed spine), not O(model). They never mutate their input, so they + * are trivially unit-testable and safe to use as undo snapshots. This is the model-mutation half of the + * editing core; the EditorSession wraps these with history and change events. + */ + +/** + * Returns a copy of [this] with the part [id]'s Parts-panel visibility set to [visible], sharing every + * other part and the rest of the model. A no-op id (no such part, or the flag already matches) returns + * the same instance, so callers can compare by reference to detect a real change. + * + * @param PartId id The part to retoggle. + * @param Boolean visible The new visibility. + * @return PuppetModel The model with that part's visibility updated, or [this] if nothing changed. + */ +fun PuppetModel.withPartVisibility(id: PartId, visible: Boolean): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].isVisible == visible) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(isVisible = visible) + return copy(parts = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s own Parts-panel visibility set to [visible], sharing + * every other drawable and the rest of the model. A no-op id (no such drawable, or the flag already + * matches) returns the same instance. + * + * @param DrawableId id The drawable to retoggle. + * @param Boolean visible The new visibility. + * @return PuppetModel The model with that drawable's visibility updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableVisibility(id: DrawableId, visible: Boolean): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].isVisible == visible) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(isVisible = visible) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the part [id]'s display name set to [name], sharing every other entity. + * A no-op id (no such part, or the name already matches) returns the same instance. + * + * @param PartId id The part to rename. + * @param String name The new display name. + * @return PuppetModel The model with that part renamed, or [this] if nothing changed. + */ +fun PuppetModel.withPartName(id: PartId, name: String): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].name == name) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(name = name) + return copy(parts = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s display name set to [name], sharing every other + * entity. A no-op id (no such drawable, or the name already matches) returns the same instance. + * + * @param DrawableId id The drawable to rename. + * @param String name The new display name. + * @return PuppetModel The model with that drawable renamed, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableName(id: DrawableId, name: String): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].name == name) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(name = name) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the deformer [id]'s display name set to [name], sharing every other + * entity. Handles both deformer kinds. A no-op id (no such deformer, or the name already matches) + * returns the same instance. + * + * @param DeformerId id The deformer to rename. + * @param String name The new display name. + * @return PuppetModel The model with that deformer renamed, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerName(id: DeformerId, name: String): PuppetModel { + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0 || deformers[index].name == name) { + return this + } + val updated = deformers.toMutableList() + updated[index] = + when (val deformer = updated[index]) { + is Deformer.Warp -> deformer.copy(name = name) + is Deformer.Rotation -> deformer.copy(name = name) + } + return copy(deformers = updated) +} + +/** + * Returns a copy of [this] with the part [id]'s selectable flag set to [selectable], sharing every other + * entity. A no-op id (no such part, or the flag already matches) returns the same instance. + * + * @param PartId id The part whose selectability to set. + * @param Boolean selectable The new selectable state. + * @return PuppetModel The model with that part's selectability updated, or [this] if nothing changed. + */ +fun PuppetModel.withPartSelectable(id: PartId, selectable: Boolean): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].isSelectable == selectable) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(isSelectable = selectable) + return copy(parts = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s selectable flag set to [selectable], sharing every + * other entity. A no-op id (no such drawable, or the flag already matches) returns the same instance. + * + * @param DrawableId id The drawable whose selectability to set. + * @param Boolean selectable The new selectable state. + * @return PuppetModel The model with that drawable's selectability updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableSelectable(id: DrawableId, selectable: Boolean): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].isSelectable == selectable) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(isSelectable = selectable) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the deformer [id]'s selectable flag set to [selectable], handling both + * deformer kinds and sharing every other entity. A no-op id returns the same instance. + * + * @param DeformerId id The deformer whose selectability to set. + * @param Boolean selectable The new selectable state. + * @return PuppetModel The model with that deformer's selectability updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerSelectable(id: DeformerId, selectable: Boolean): PuppetModel { + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0 || deformers[index].isSelectable == selectable) { + return this + } + val updated = deformers.toMutableList() + updated[index] = + when (val deformer = updated[index]) { + is Deformer.Warp -> deformer.copy(isSelectable = selectable) + is Deformer.Rotation -> deformer.copy(isSelectable = selectable) + } + return copy(deformers = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s base art-mesh positions replaced by [newPositions], + * sharing every other drawable and the rest of the model. Copy-on-write at the mesh leaf: it wraps + * [newPositions] in a NEW [DrawableMesh] and shares the unchanged uvs / indices arrays by reference, so a + * prior snapshot's positions array is never mutated. A no-op (no such drawable, no mesh, the same array + * instance, or a length mismatch - vertex count is fixed in this slice) returns the same instance so the + * session records nothing. + * + * The caller must pass a freshly built array (e.g. from [MeshTransforms]); never the live mesh array. + * + * @param DrawableId id The drawable whose mesh to retarget. + * @param FloatArray newPositions The new interleaved (x, y) rest positions, same length as the current. + * @return PuppetModel The model with that mesh updated, or [this] if nothing changed. + */ +fun PuppetModel.withMeshPositions(id: DrawableId, newPositions: FloatArray): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0) { + return this + } + val mesh = drawables[index].mesh + if (mesh == null || newPositions === mesh.positions || newPositions.size != mesh.positions.size) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(mesh = DrawableMesh(newPositions, mesh.uvs, mesh.indices)) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s texture UVs replaced by [newUvs], sharing every + * other drawable and the rest of the model. The mirror image of [withMeshPositions], copy-on-write at + * the mesh leaf: it wraps [newUvs] in a NEW [DrawableMesh] and shares the unchanged positions / indices + * arrays by reference, so retargeting which atlas texels a mesh samples never disturbs its rest + * geometry - the mesh/UV decoupling invariant seen from the UV side. A no-op (no such drawable, no + * mesh, the same array instance, or a length mismatch - vertex count never changes here) returns the + * same instance so the session records nothing. + * + * The caller must pass a freshly built array (e.g. from [MeshTransforms]); never the live mesh array. + * + * @param DrawableId id The drawable whose texture mapping to retarget. + * @param FloatArray newUvs The new interleaved (u, v) atlas coordinates, same length as the current. + * @return PuppetModel The model with that mesh's UVs updated, or [this] if nothing changed. + */ +fun PuppetModel.withMeshUvs(id: DrawableId, newUvs: FloatArray): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0) { + return this + } + val mesh = drawables[index].mesh + if (mesh == null || newUvs === mesh.uvs || newUvs.size != mesh.uvs.size) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(mesh = DrawableMesh(mesh.positions, newUvs, mesh.indices)) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s color blend mode set to [mode], sharing every other + * entity. A no-op id (no such drawable, or the mode already matches) returns the same instance. + * + * @param DrawableId id The drawable to retarget. + * @param BlendMode mode The new blend mode. + * @return PuppetModel The model with that drawable's blend mode updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableBlendMode(id: DrawableId, mode: BlendMode): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].blendMode == mode) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(blendMode = mode) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s alpha blend mode set to [mode], sharing every other + * entity. A no-op id (no such drawable, or the mode already matches) returns the same instance. + * + * @param DrawableId id The drawable to retarget. + * @param AlphaBlendMode mode The new alpha blend mode. + * @return PuppetModel The model with that drawable's alpha blend mode updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableAlphaBlendMode(id: DrawableId, mode: AlphaBlendMode): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].alphaBlendMode == mode) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(alphaBlendMode = mode) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s back-face culling set to [culling], sharing every + * other entity. A no-op id (no such drawable, or the flag already matches) returns the same instance. + * + * @param DrawableId id The drawable to retarget. + * @param Boolean culling The new culling state. + * @return PuppetModel The model with that drawable's culling updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableCulling(id: DrawableId, culling: Boolean): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].culling == culling) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(culling = culling) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s static opacity set to [opacity], sharing every other + * entity. A no-op id (no such drawable, or the value already matches) returns the same instance. + * + * Writes the STATIC only. When the drawable keys opacity, the track shadows this and the edit is invisible + * at any pose the track covers - which is why the Properties row routes a keyed channel's edit into the + * pending-edit buffer instead of here. + * + * @param DrawableId id The drawable to retarget. + * @param Float opacity The new opacity. + * @return PuppetModel The model with that drawable's opacity updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableOpacity(id: DrawableId, opacity: Float): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].opacity == opacity) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(opacity = opacity) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s static draw order set to [drawOrder], sharing every + * other entity. A no-op id (no such drawable, or the value already matches) returns the same instance. + * + * Deliberately does NOT re-derive the render root, unlike [withPartDrawOrder]. A part's draw order is + * baked into the derived group tree; a drawable's is resolved per POSE at render time as its draw-order + * channel's static, so the tree is unaffected and re-deriving would be wasted work on every edit. + * + * @param DrawableId id The drawable to retarget. + * @param Float drawOrder The new draw order. + * @return PuppetModel The model with that drawable's draw order updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableDrawOrder(id: DrawableId, drawOrder: Float): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].drawOrder == drawOrder) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(drawOrder = drawOrder) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with drawable [id]'s static [FormChannel.MULTIPLY_COLOR] set to [color]. + * A no-op (missing drawable, or the color already set) returns the same instance. + * + * A single-field copy: the tint is its own track with its own static, so this writes just that field + * rather than rewriting every keyform cell. Rewriting the whole grid instead would flatten any authored + * per-keyform color animation, and would trip diffModel's identity check into re-uploading the drawable's + * geometry for a mere color change. + * + * @param DrawableId id The drawable to retint. + * @param ColorRgb color The new multiply color. + * @return PuppetModel The model with that drawable's multiply color updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableMultiplyColor(id: DrawableId, color: ColorRgb): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].multiplyColor == color) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(multiplyColor = color) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with drawable [id]'s static [FormChannel.SCREEN_COLOR] set to [color]; see + * [withDrawableMultiplyColor]. + * + * @param DrawableId id The drawable to retint. + * @param ColorRgb color The new screen color. + * @return PuppetModel The model with that drawable's screen color updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableScreenColor(id: DrawableId, color: ColorRgb): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].screenColor == color) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(screenColor = color) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s mask-inversion flag set to [invert], sharing every + * other entity. A no-op id (no such drawable, or the flag already matches) returns the same instance. + * + * @param DrawableId id The drawable to retarget. + * @param Boolean invert The new inverted-mask state. + * @return PuppetModel The model with that drawable's mask inversion updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableInvertMask(id: DrawableId, invert: Boolean): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].invertMask == invert) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(invertMask = invert) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id] bound to the deformer [parentDeformerId] (null unbinds), + * sharing every other entity. A no-op id (no such drawable, or the binding already matches) returns the + * same instance. A drawable is deformed by, but never a child of, a deformer - so this is a flat field + * write with no tree surgery and no render-order rederive. + * + * @param DrawableId id The drawable to rebind. + * @param DeformerId? parentDeformerId The deformer that deforms it, or null to unbind. + * @return PuppetModel The model with that binding updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableParentDeformer(id: DrawableId, parentDeformerId: DeformerId?): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].parentDeformerId == parentDeformerId) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(parentDeformerId = parentDeformerId) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the drawable [id]'s clip-mask list replaced by [maskedBy], sharing every + * other entity. A no-op id (no such drawable, or the list already matches) returns the same instance. + * + * @param DrawableId id The drawable whose masks change. + * @param List maskedBy The drawables whose alpha now clips it. + * @return PuppetModel The model with that mask list updated, or [this] if nothing changed. + */ +fun PuppetModel.withDrawableMaskedBy(id: DrawableId, maskedBy: List): PuppetModel { + val index = drawables.indexOfFirst { drawable -> drawable.id == id } + if (index < 0 || drawables[index].maskedBy == maskedBy) { + return this + } + val updated = drawables.toMutableList() + updated[index] = updated[index].copy(maskedBy = maskedBy) + return copy(drawables = updated) +} + +/** + * Returns a copy of [this] with the deformer [id] bound to the organizational part [partId] (null clears + * it), sharing every other entity. A no-op id (no such deformer, or the binding already matches) returns + * the same instance. The part reference is loose - no Part.children entry corresponds to it - so this is a + * flat field write; the copy is per-subtype because Deformer is a sealed interface. + * + * @param DeformerId id The deformer to rebind. + * @param PartId? partId The part that owns it, or null to clear. + * @return PuppetModel The model with that binding updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerPart(id: DeformerId, partId: PartId?): PuppetModel { + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0 || deformers[index].partId == partId) { + return this + } + val updated = deformers.toMutableList() + updated[index] = + when (val deformer = updated[index]) { + is Deformer.Warp -> deformer.copy(partId = partId) + is Deformer.Rotation -> deformer.copy(partId = partId) + } + return copy(deformers = updated) +} + +/** + * Returns a copy of [this] with the deformer [id]'s static opacity set to [opacity], sharing every other + * entity. A no-op id (no such deformer, or the value already matches) returns the same instance. + * + * A deformer's render channels CASCADE onto every drawable beneath it - they compose by product at render + * time - so this is a different lever from setting each of those drawables' own opacity. + * + * @param DeformerId id The deformer to retarget. + * @param Float opacity The new opacity. + * @return PuppetModel The model with that deformer's opacity updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerOpacity(id: DeformerId, opacity: Float): PuppetModel = + withDeformerRewritten(id, { deformer -> deformer.opacity == opacity }) { deformer -> + when (deformer) { + is Deformer.Warp -> deformer.copy(opacity = opacity) + is Deformer.Rotation -> deformer.copy(opacity = opacity) + } + } + +/** + * Returns a copy of [this] with the deformer [id]'s static multiply color set to [color], sharing every + * other entity. A no-op id (no such deformer, or the value already matches) returns the same instance. + * + * @param DeformerId id The deformer to retarget. + * @param ColorRgb color The new multiply color. + * @return PuppetModel The model with that deformer's multiply color updated, or [this] if unchanged. + */ +fun PuppetModel.withDeformerMultiplyColor(id: DeformerId, color: ColorRgb): PuppetModel = + withDeformerRewritten(id, { deformer -> deformer.multiplyColor == color }) { deformer -> + when (deformer) { + is Deformer.Warp -> deformer.copy(multiplyColor = color) + is Deformer.Rotation -> deformer.copy(multiplyColor = color) + } + } + +/** + * Returns a copy of [this] with the deformer [id]'s static screen color set to [color], sharing every + * other entity. A no-op id (no such deformer, or the value already matches) returns the same instance. + * + * @param DeformerId id The deformer to retarget. + * @param ColorRgb color The new screen color. + * @return PuppetModel The model with that deformer's screen color updated, or [this] if unchanged. + */ +fun PuppetModel.withDeformerScreenColor(id: DeformerId, color: ColorRgb): PuppetModel = + withDeformerRewritten(id, { deformer -> deformer.screenColor == color }) { deformer -> + when (deformer) { + is Deformer.Warp -> deformer.copy(screenColor = color) + is Deformer.Rotation -> deformer.copy(screenColor = color) + } + } + +/** + * Returns a copy of [this] with the ROTATION deformer [id]'s static horizontal reflection set to [flip]. + * + * A no-op (no such deformer, a warp - which has no reflection - or the value already matches) returns the + * same instance. + * + * @param DeformerId id The deformer to retarget. + * @param Boolean flip The new reflection state. + * @return PuppetModel The model with that deformer's flip updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerFlipX(id: DeformerId, flip: Boolean): PuppetModel = + withDeformerRewritten(id, { deformer -> deformer !is Deformer.Rotation || deformer.flipX == flip }) { deformer -> + (deformer as Deformer.Rotation).copy(flipX = flip) + } + +/** + * Returns a copy of [this] with the ROTATION deformer [id]'s static vertical reflection set to [flip]. + * + * @param DeformerId id The deformer to retarget. + * @param Boolean flip The new reflection state. + * @return PuppetModel The model with that deformer's flip updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerFlipY(id: DeformerId, flip: Boolean): PuppetModel = + withDeformerRewritten(id, { deformer -> deformer !is Deformer.Rotation || deformer.flipY == flip }) { deformer -> + (deformer as Deformer.Rotation).copy(flipY = flip) + } + +/** + * The shared deformer-rewrite skeleton: find, refuse a no-op, copy-on-write. + * + * Deformer is a sealed interface with no shared copy, so every static setter would otherwise repeat the + * same find / guard / toMutableList dance around a two-branch when. Factored so adding a subtype is one + * compile error per op rather than a silently unhandled branch. + * + * @param DeformerId id The deformer to rewrite. + * @param Function isNoOp True when the edit would change nothing, or does not apply to this subtype. + * @param Function rewrite Produces the replacement deformer. + * @return PuppetModel The rewritten model, or [this] when the edit was a no-op. + */ +private inline fun PuppetModel.withDeformerRewritten( + id: DeformerId, + isNoOp: (Deformer) -> Boolean, + rewrite: (Deformer) -> Deformer, +): PuppetModel { + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0 || isNoOp(deformers[index])) { + return this + } + val updated = deformers.toMutableList() + updated[index] = rewrite(updated[index]) + return copy(deformers = updated) +} + +/** + * Returns a copy of [this] with the rotation deformer [id]'s base angle set to [angle], sharing every + * other entity. A no-op (no such deformer, a warp deformer - which has no base angle - or the angle + * already matches) returns the same instance. + * + * @param DeformerId id The deformer to retarget. + * @param Float angle The new base angle in degrees. + * @return PuppetModel The model with that deformer's base angle updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerBaseAngle(id: DeformerId, angle: Float): PuppetModel { + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0) { + return this + } + val deformer = deformers[index] + if (deformer !is Deformer.Rotation || deformer.baseAngle == angle) { + return this + } + val updated = deformers.toMutableList() + updated[index] = deformer.copy(baseAngle = angle) + return copy(deformers = updated) +} + +/** + * Returns a copy of [this] with the warp deformer [id]'s FFD interpolation mode set to [quad], sharing + * every other entity. A no-op (no such deformer, a rotation deformer - which has no lattice - or the + * flag already matches) returns the same instance. + * + * @param DeformerId id The deformer to retarget. + * @param Boolean quad The new quad-transform state. + * @return PuppetModel The model with that deformer's interpolation mode updated, or [this] if nothing changed. + */ +fun PuppetModel.withDeformerQuadTransform(id: DeformerId, quad: Boolean): PuppetModel { + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0) { + return this + } + val deformer = deformers[index] + if (deformer !is Deformer.Warp || deformer.isQuadTransform == quad) { + return this + } + val updated = deformers.toMutableList() + updated[index] = deformer.copy(isQuadTransform = quad) + return copy(deformers = updated) +} + +/** + * Returns a copy of [this] with the part [id]'s guide-image (sketch) flag set to [sketch], sharing every + * other entity. A no-op id (no such part, or the flag already matches) returns the same instance. + * + * @param PartId id The part to retarget. + * @param Boolean sketch The new sketch state. + * @return PuppetModel The model with that part's sketch flag updated, or [this] if nothing changed. + */ +fun PuppetModel.withPartSketch(id: PartId, sketch: Boolean): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].isSketch == sketch) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(isSketch = sketch) + return copy(parts = updated) +} + +/** + * Returns a copy of [this] with the part [id]'s own draw order set to [order], sharing every other + * entity. A no-op id (no such part, or the value already matches) returns the same instance. + * + * @param PartId id The part to retarget. + * @param Int order The new draw order. + * @return PuppetModel The model with that part's draw order updated, or [this] if nothing changed. + */ +fun PuppetModel.withPartDrawOrder(id: PartId, order: Int): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].drawOrder == order) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(drawOrder = order) + // Draw order feeds the derived render tree (a part's group slot), so re-derive renderRoot or the + // renderer keeps sorting by the pre-edit order - the same reason every structural edit re-derives. + return copy(parts = updated).withDerivedRenderRoot() +} + +/** + * Returns a copy of [this] with the part [id]'s rendering group mode set to [mode], sharing every other + * entity. Carries the whole mode value, so an Isolated switch and any composite sub-field edit go + * through here alike. A no-op id (no such part, or the mode already matches) returns the same instance. + * + * @param PartId id The part to retarget. + * @param PartGroupMode mode The new group mode. + * @return PuppetModel The model with that part's group mode updated, or [this] if nothing changed. + */ +fun PuppetModel.withPartGroupMode(id: PartId, mode: PartGroupMode): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].groupMode == mode) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(groupMode = mode) + // Group mode decides whether the part is a render-tree boundary (Isolated/Grouped) or transparent + // (PassThrough hoists its children), so re-derive renderRoot or the plan keeps the old structure. + return copy(parts = updated).withDerivedRenderRoot() +} + +/** + * Returns a copy of [this] with the part [id]'s latent compositing settings set to [composite], sharing + * every other entity. Stored independent of the part's group mode (so it survives a mode round-trip) and + * applied only while the part is Isolated. A no-op id (no such part, or the composite already matches) + * returns the same instance. + * + * @param PartId id The part to retarget. + * @param PartComposite composite The new composite settings. + * @return PuppetModel The model with that part's composite updated, or [this] if nothing changed. + */ +fun PuppetModel.withPartComposite(id: PartId, composite: PartComposite): PuppetModel { + val index = parts.indexOfFirst { part -> part.id == id } + if (index < 0 || parts[index].composite == composite) { + return this + } + val updated = parts.toMutableList() + updated[index] = updated[index].copy(composite = composite) + // resolvedComposite bakes the composite into RenderGroup.composite at derive time (masked-by parts + // expanded), so re-derive renderRoot or the renderer re-reads the pre-edit blend/opacity/colors/masks. + return copy(parts = updated).withDerivedRenderRoot() +} + +/** + * Returns a copy of [this] with the document canvas size set to [width] x [height] in world units, + * sharing the rest of the model. A no-op (both dimensions already match) returns the same instance. + * + * @param Float width The new canvas width. + * @param Float height The new canvas height. + * @return PuppetModel The model with the canvas resized, or [this] if nothing changed. + */ +fun PuppetModel.withCanvasSize(width: Float, height: Float): PuppetModel { + if (canvasWidth == width && canvasHeight == height) { + return this + } + return copy(canvasWidth = width, canvasHeight = height) +} + +/** + * Returns a copy of [this] with the world origin set to ([x], [z]) in world space, sharing the rest of + * the model. A no-op (both coordinates already match) returns the same instance. + * + * @param Float x The new world-origin x. + * @param Float z The new world-origin z (up). + * @return PuppetModel The model with the world origin moved, or [this] if nothing changed. + */ +fun PuppetModel.withWorldOrigin(x: Float, z: Float): PuppetModel { + if (worldOriginX == x && worldOriginZ == z) { + return this + } + return copy(worldOriginX = x, worldOriginZ = z) +} + +/** + * Returns a copy of [this] with the runtime-compatibility target set to [target], sharing the rest + * of the model. A no-op (the target already matches) returns the same instance. + * + * @param RuntimeTarget target The new runtime target. + * @return PuppetModel The model with the target set, or [this] if nothing changed. + */ +fun PuppetModel.withRuntimeTarget(target: RuntimeTarget): PuppetModel { + if (runtimeTarget == target) { + return this + } + return copy(runtimeTarget = target) +} + +/** + * This model displaying from its source artwork rather than from the packed atlas, or itself when the + * mode already matches. + * + * @param Boolean fromSourceLayers True to display from the source artwork, false from the atlas. + * @return PuppetModel The model with the display mode applied. + */ +fun PuppetModel.withSourceLayerDisplay(fromSourceLayers: Boolean): PuppetModel { + if (rendersFromSourceLayers == fromSourceLayers) { + return this + } + return copy(rendersFromSourceLayers = fromSourceLayers) +} + +/** + * This model with one atlas tile packed at [placement], every drawable over that art re-mapped so it + * keeps sampling the same pixels. + * + * Moving art around a page must not change what the art means. Stored texture coordinates address the + * PAGE, so a placement that moves without them moving with it silently re-points every mesh at whatever + * now occupies the old spot; that is why this rewrites both together, and why a repack is an edit on + * the tile rather than on each drawable. The re-mapping is the composition of the old mapping into the + * art's own frame with the inverse of the new one, so the vertex-to-art-pixel binding comes out + * bit-identical wherever the affines are exact. + * + * The mappings are built from the placements directly: stored coordinates mean the same thing whichever + * surface is being displayed, so a document whose coordinates address the packed pages re-maps here and + * one whose coordinates already address the art does not. + * + * PIXELS ARE NOT MOVED. A page's bytes belong to the document, not the model, so a caller that moves a + * placement must recompose the page for the result to render; the session's page resolver does that + * from the committed model, which is what lets the placement gizmo commit here and let the pixels + * follow. + * + * A no-op returns the same instance. So does an edit that cannot be expressed: an unknown tile, a + * placement naming a page the document does not have, or a mapping that will not invert (a zero scale, + * a zero-sized tile). Refusing beats writing a placement whose coordinates cannot follow it. + * + * @param AtlasTileId tileId The tile to place. + * @param AtlasPlacement? placement Where its art now sits, or null to mark it unpacked. + * @return PuppetModel The model with the placement and the re-derived coordinates, or [this]. + */ +fun PuppetModel.withAtlasPlacement(tileId: AtlasTileId, placement: AtlasPlacement?): PuppetModel = + withAtlasPlacements(mapOf(tileId to placement)) + +/** + * This model with several tiles placed anew in one pass - [withAtlasPlacement] over a whole gesture's + * worth of tiles, every drawable over each moved tile re-mapped so it keeps sampling the same pixels. + * + * One pass rather than a fold of single-tile edits so the result is one instance for one history + * push, and so the whole edit is refused together: an unknown tile, a placement naming a page the + * document does not have, or a mapping that will not invert anywhere in the map returns [this] + * untouched rather than moving the tiles that happened to precede the fault. The page inventory + * never changes here - that is the repack's op, [withAtlasRepack]. + * + * @param Map placementByTile Each tile's new placement, keyed by tile, null to mark it unpacked. + * @return PuppetModel The model with the placements and the re-derived coordinates, or [this] when + * nothing changes or the edit cannot be expressed. + */ +fun PuppetModel.withAtlasPlacements(placementByTile: Map): PuppetModel { + if (placementByTile.isEmpty()) { + return this + } + val movedTiles = atlas.tiles.toMutableList() + val changedTileIds = ArrayList() + for ((tileId, placement) in placementByTile) { + val tileIndex = movedTiles.indexOfFirst { tile -> tile.id == tileId } + if (tileIndex < 0) { + return this + } + if (placement != null && placement.pageIndex !in atlas.pages.indices) { + return this + } + val tile = movedTiles[tileIndex] + if (tile.placement == placement) { + continue + } + // An unpacked tile has no placement to keep, so packing one out drops its pin with it. + movedTiles[tileIndex] = tile.copy(placement = placement, pinned = tile.pinned && placement != null) + changedTileIds.add(tileId) + } + if (changedTileIds.isEmpty()) { + return this + } + val newAtlas = atlas.copy(tiles = movedTiles) + val remapByTile = HashMap() + for (tileId in changedTileIds) { + when (val outcome = tileRemap(atlas, newAtlas, tileId)) { + TileRemapOutcome.Unchanged -> Unit + TileRemapOutcome.Inexpressible -> return this + is TileRemapOutcome.Remap -> remapByTile[tileId] = outcome.remap + } + } + return copy(atlas = newAtlas, drawables = drawables.remappedOver(remapByTile)) +} + +/** + * This model with every tile in [tileIds] that has a placement pinned or unpinned - the flag a + * repack reads to keep a hand-placed tile where it is. + * + * A tile without a placement is skipped rather than refused: there is nothing on a page to keep, and + * a selection spanning packed and unpacked art should still pin what it can. An unknown tile is + * skipped the same way. No coordinates move - the flag says only what a LATER repack may do. + * + * @param Collection tileIds The tiles to pin or unpin. + * @param Boolean pinned True to pin, false to unpin. + * @return PuppetModel The model with the flags set, or [this] when nothing changes. + */ +fun PuppetModel.withAtlasPins(tileIds: Collection, pinned: Boolean): PuppetModel { + if (tileIds.isEmpty()) { + return this + } + val wanted = tileIds.toSet() + var changed = false + val tiles = + atlas.tiles.map { tile -> + if (tile.id in wanted && tile.placement != null && tile.pinned != pinned) { + changed = true + tile.copy(pinned = pinned) + } else { + tile + } + } + if (!changed) { + return this + } + return copy(atlas = atlas.copy(tiles = tiles)) +} + +/** + * This model with one tile's source binding replaced - rebound to another layer of a listed artwork + * file, or unbound when [source] is null. + * + * Refused (returns [this]) for an unknown tile or a ref naming a source the document does not list: + * a binding that points at nothing would be worse than no binding. Nothing else moves - the + * binding says which layer a re-import reads for this art, never where the art sits. + * + * @param AtlasTileId tileId The tile to rebind. + * @param SourceLayerRef? source The new binding, or null to unbind. + * @return PuppetModel The rebound model, or [this] when refused or unchanged. + */ +fun PuppetModel.withTileSource(tileId: AtlasTileId, source: SourceLayerRef?): PuppetModel { + val tileIndex = atlas.tiles.indexOfFirst { tile -> tile.id == tileId } + if (tileIndex < 0) { + return this + } + if (source != null && sources.none { candidate -> candidate.id == source.sourceId }) { + return this + } + val tile = atlas.tiles[tileIndex] + if (tile.source == source) { + return this + } + val tiles = atlas.tiles.toMutableList() + tiles[tileIndex] = tile.copy(source = source) + return copy(atlas = atlas.copy(tiles = tiles)) +} + +/** + * This model with an artwork file's additions appended: the source record, its tiles (unplaced), its + * drawables and parts, and the file's top-level order after the existing root children, with the + * render root re-derived. The pack that places the new tiles is a separate step over the result, + * exactly as it is for a fresh import. + * + * Refused (returns [this]) when any added id collides with one the model already has - the bridge + * mints past the existing ids, so a collision is a caller bug rather than document state to absorb. + * + * @param ArtworkAdditions additions The delta to append. + * @return PuppetModel The model with the artwork added, or [this] when refused. + */ +fun PuppetModel.withArtworkAdded(additions: ArtworkAdditions): PuppetModel { + if (sources.any { source -> source.id == additions.source.id }) { + return this + } + val existingTileIds = atlas.tiles.mapTo(HashSet()) { tile -> tile.id } + val existingDrawableIds = drawables.mapTo(HashSet()) { drawable -> drawable.id } + val existingPartIds = parts.mapTo(HashSet()) { part -> part.id } + if (additions.tiles.any { tile -> tile.id in existingTileIds } || + additions.drawables.any { drawable -> drawable.id in existingDrawableIds } || + additions.parts.any { part -> part.id in existingPartIds } || + additions.insertions.any { insertion -> insertion.container != null && insertion.container !in existingPartIds } + ) { + return this + } + val placed = placeInsertions(parts, rootChildren, additions.insertions) + return copy( + parts = placed.parts + additions.parts, + drawables = drawables + additions.drawables, + rootChildren = placed.rootChildren + additions.rootChildren, + atlas = atlas.copy(tiles = atlas.tiles + additions.tiles), + sources = sources + additions.source, + ).withDerivedRenderRoot() +} + +/** + * This model without the tile [tileId]: the tile and its placement gone from the atlas, its drawables + * untouched because there are none - a tile some drawable samples is refused, since removing it would + * strand the drawable's coordinates. The pages are derived state, so the page the tile sat on simply + * composes without it. Refused (returns [this]) for a tile the model lacks. + * + * @param AtlasTileId tileId The tile to remove. + * @return PuppetModel The model without the tile, or [this] when refused. + */ +fun PuppetModel.withTileDeleted(tileId: AtlasTileId): PuppetModel { + if (atlas.tileById[tileId] == null || drawables.any { drawable -> drawable.atlasTileId == tileId }) { + return this + } + return copy(atlas = atlas.copy(tiles = atlas.tiles.filter { tile -> tile.id != tileId })) +} + +/** + * This model with one inventory row's ignore mark set: a layer of a listed artwork file that a reload + * leaves out of the rig while [ignored] is true. The mark means something only for a layer no tile + * binds - a bound layer is matched by key, never minted - so a key some tile binds is refused, as is an + * unlisted file or key; a mark already as asked returns [this]. + * + * @param ArtSourceId sourceId The file. + * @param String key The layer's key within it. + * @param Boolean ignored True to keep the layer out of the rig, false to let a reload mint it again. + * @return PuppetModel The marked model, or [this] when refused or unchanged. + */ +fun PuppetModel.withLayerIgnored(sourceId: ArtSourceId, key: String, ignored: Boolean): PuppetModel { + val sourceIndex = sources.indexOfFirst { source -> source.id == sourceId } + if (sourceIndex < 0) { + return this + } + if (atlas.tiles.any { tile -> tile.source?.sourceId == sourceId && tile.source?.layerKey == key }) { + return this + } + val source = sources[sourceIndex] + val rowIndex = source.layers.indexOfFirst { row -> row.key == key } + if (rowIndex < 0 || source.layers[rowIndex].ignored == ignored) { + return this + } + val rows = source.layers.toMutableList() + rows[rowIndex] = rows[rowIndex].copy(ignored = ignored) + val updated = sources.toMutableList() + updated[sourceIndex] = source.copy(layers = rows) + return copy(sources = updated) +} + +/** + * The org tree after a delta's insertions: the parts and the root children. + * + * @property List parts The parts, the ones that took children rebuilt. + * @property List rootChildren The root's children. + */ +private class PlacedOrgTree( + val parts: List, + val rootChildren: List, +) + +/** + * [insertions] applied in order to [parts] and [rootChildren]: each child goes directly after or before + * its anchor among the container's children as they stand at that moment (an earlier insertion + * included), or at the end when the slot says so or the anchor is not there any more. + * + * @param List parts The parts as they stand. + * @param List rootChildren The root's children as they stand. + * @param List insertions The children to place, in order. + * @return PlacedOrgTree The placed tree; the same lists when there is nothing to place. + */ +private fun placeInsertions(parts: List, rootChildren: List, insertions: List): PlacedOrgTree { + if (insertions.isEmpty()) { + return PlacedOrgTree(parts, rootChildren) + } + var root = rootChildren + val childrenByPart = LinkedHashMap>() + for (part in parts) { + childrenByPart[part.id] = part.children + } + for (insertion in insertions) { + val container = insertion.container + if (container == null) { + root = root.withInserted(insertion.child, insertion.slot) + } else { + childrenByPart[container] = childrenByPart.getValue(container).withInserted(insertion.child, insertion.slot) + } + } + val placedParts = + parts.map { part -> + val children = childrenByPart.getValue(part.id) + if (children === part.children) part else part.copy(children = children) + } + return PlacedOrgTree(placedParts, root) +} + +/** + * This list with [child] at [slot]: after or before the anchor when the list holds it, else at the end. + * + * @param OrgChild child The child to place. + * @param OrgSlot slot Where it goes. + * @return List The grown list. + */ +private fun List.withInserted(child: OrgChild, slot: OrgSlot): List { + val index = + when (slot) { + is OrgSlot.After -> indexOf(slot.anchor).let { anchorIndex -> if (anchorIndex < 0) size else anchorIndex + 1 } + is OrgSlot.Before -> indexOf(slot.anchor).let { anchorIndex -> if (anchorIndex < 0) size else anchorIndex } + OrgSlot.End -> size + } + val grown = ArrayList(size + 1) + grown.addAll(this) + grown.add(index, child) + return grown +} + +/** + * This model with one artwork file re-read into it: the file's record replaced by [reload]'s (the + * inventory as just read), every superseded tile removed and its replacement appended unplaced, the + * drawables over a superseded tile moved onto its replacement with the meshes the plan decided, the + * drawables the file's eye toggle reached given the visibility the plan decided, and the layers the + * file gained appended under the same file (tiles, drawables, new parts, and each new + * child placed among the existing children where the file puts it, like [withArtworkAdded]). The + * render root is re-derived, so a layer added at the top of the file draws in front. The pack that places the new tiles is a + * separate step over the result, exactly as for an added file: an unplaced tile's coordinates address + * its own art, so the repack's re-derivation converts them. + * + * Nothing is deleted: a layer the file lost keeps its tile, its pixels, and its binding - the + * refreshed inventory carries its row flagged not present, which is what the Sources space shows as + * needing review. + * + * Refused (returns [this]) when the model does not list the file, a superseded or retired tile is + * unknown, a retired tile is also superseded, or any new id collides with one the model has - the + * planner mints past the model, so a collision is a caller bug rather than document state to absorb. + * + * @param ArtworkReload reload The delta to apply. + * @return PuppetModel The reloaded model, or [this] when refused. + */ +fun PuppetModel.withArtworkReloaded(reload: ArtworkReload): PuppetModel { + if (sources.none { source -> source.id == reload.source.id }) { + return this + } + val existingTileIds = atlas.tiles.mapTo(HashSet()) { tile -> tile.id } + val replacedIds = reload.replacedTiles.mapTo(HashSet()) { replaced -> replaced.oldId } + if (replacedIds.size != reload.replacedTiles.size || replacedIds.any { oldId -> oldId !in existingTileIds }) { + return this + } + val retiredIds = reload.retiredTiles.toSet() + if (retiredIds.any { tileId -> tileId !in existingTileIds || tileId in replacedIds }) { + return this + } + val additions = reload.additions + val newTiles = reload.replacedTiles.map { replaced -> replaced.tile } + additions?.tiles.orEmpty() + val existingDrawableIds = drawables.mapTo(HashSet()) { drawable -> drawable.id } + val existingPartIds = parts.mapTo(HashSet()) { part -> part.id } + if (newTiles.any { tile -> tile.id in existingTileIds } || + newTiles.mapTo(HashSet()) { tile -> tile.id }.size != newTiles.size || + additions?.drawables.orEmpty().any { drawable -> drawable.id in existingDrawableIds } || + additions?.parts.orEmpty().any { part -> part.id in existingPartIds } || + additions?.insertions.orEmpty().any { insertion -> insertion.container != null && insertion.container !in existingPartIds } + ) { + return this + } + val newTileByOldId = reload.replacedTiles.associate { replaced -> replaced.oldId to replaced.tile.id } + val movedDrawables = + drawables.map { drawable -> + val newTileId = drawable.atlasTileId?.let { tileId -> newTileByOldId[tileId] } + val mesh = reload.drawableMeshes[drawable.id] + val visible = reload.drawableVisibility[drawable.id] + if (newTileId == null && mesh == null && visible == null) { + drawable + } else { + drawable.copy(atlasTileId = newTileId ?: drawable.atlasTileId, mesh = mesh ?: drawable.mesh, isVisible = visible ?: drawable.isVisible) + } + } + val keptTiles = atlas.tiles.filter { tile -> tile.id !in replacedIds && tile.id !in retiredIds } + val placed = placeInsertions(parts, rootChildren, additions?.insertions.orEmpty()) + val reloaded = + copy( + parts = placed.parts + additions?.parts.orEmpty(), + drawables = movedDrawables + additions?.drawables.orEmpty(), + rootChildren = placed.rootChildren + additions?.rootChildren.orEmpty(), + atlas = atlas.copy(tiles = keptTiles + newTiles), + sources = sources.map { source -> if (source.id == reload.source.id) reload.source else source }, + ) + // A retired tile's drawables leave with it, every reference scrubbed the way a delete scrubs them. + val retiredDrawables = reloaded.drawables.filter { drawable -> drawable.atlasTileId in retiredIds }.mapTo(HashSet()) { drawable -> drawable.id } + return reloaded.removingDrawables(retiredDrawables).withDerivedRenderRoot() +} + +/** + * One tile's coordinate re-derivation across a placement change: out of the old mapping's frame, into + * the new. + * + * @property FloatArray storedToArt The old stored-to-art mapping. + * @property FloatArray artToStored The inverse of the new one. + */ +private class AtlasTileRemap( + val storedToArt: FloatArray, + val artToStored: FloatArray, +) + +/** What a tile's placement change means for the texture coordinates over it. */ +private sealed interface TileRemapOutcome { + /** The mapping is the same under both atlases, so the coordinates are left alone. */ + data object Unchanged : TileRemapOutcome + + /** One side has no mapping: a page the atlas lacks, a degenerate placement, or a zero-sized tile. */ + data object Inexpressible : TileRemapOutcome + + /** + * The coordinates move through [remap]. + * + * @property AtlasTileRemap remap The re-derivation to apply. + */ + class Remap(val remap: AtlasTileRemap) : TileRemapOutcome +} + +/** + * How [tileId]'s texture coordinates move between [oldAtlas] and [newAtlas] - the one resolution both + * the per-tile edit and the whole-atlas repack read. + * + * Each side reads its mapping against ITS OWN page inventory: the page a placement names supplies the + * mapping's normalization, so the two reads must not share pages. That is also why the repack is a + * distinct op from the per-tile edit - only it can change the inventory the new side reads. + * + * @param PuppetAtlas oldAtlas The atlas the coordinates currently address. + * @param PuppetAtlas newAtlas The atlas they will address, with the tile already moved. + * @param AtlasTileId tileId The tile whose mapping changed. + * @return TileRemapOutcome Unchanged, inexpressible, or the remap to apply. + */ +private fun tileRemap(oldAtlas: PuppetAtlas, newAtlas: PuppetAtlas, tileId: AtlasTileId): TileRemapOutcome { + val oldAffine = oldAtlas.storedToArtAffineForTile(tileId) + val newAffine = newAtlas.storedToArtAffineForTile(tileId) + if (oldAffine != null && newAffine != null && oldAffine.contentEquals(newAffine)) { + return TileRemapOutcome.Unchanged + } + val artToStored = newAffine?.let { affine -> invertUvAffine(affine) } + if (oldAffine == null || artToStored == null) { + return TileRemapOutcome.Inexpressible + } + return TileRemapOutcome.Remap(AtlasTileRemap(oldAffine, artToStored)) +} + +/** + * These drawables with every one over a tile in [remapByTile] carried through that tile's remap. Every + * other drawable, and every mesh's positions, passes through by reference: moving art on a page never + * moves the mesh, and an untouched coordinate array must not pick up float round-trip noise. + * + * @param Map remapByTile The re-derivation per moved tile. + * @return List The drawables, the same list when nothing moved. + */ +private fun List.remappedOver(remapByTile: Map): List { + if (remapByTile.isEmpty()) { + return this + } + return map { drawable -> + val remap = drawable.atlasTileId?.let { tileId -> remapByTile[tileId] } ?: return@map drawable + val mesh = drawable.mesh ?: return@map drawable + val artUvs = applyUvAffine(mesh.uvs, remap.storedToArt) + drawable.copy(mesh = DrawableMesh(mesh.positions, applyUvAffine(artUvs, remap.artToStored), mesh.indices)) + } +} + +/** + * This model repacked: the page inventory replaced by [pages], every tile's placement restated from + * [placementsByTile], and every bound drawable's texture coordinates re-derived, in one pass. + * + * The whole-atlas twin of [withAtlasPlacement], and a distinct op because the per-tile edit cannot + * change the page list: a tile's old mapping normalizes against the CURRENT pages and its new one + * against the REPLACEMENT pages, so folding per-tile edits would read the new mapping off a stale + * inventory. One call is also one history push - a repack is one gesture, not one step per tile. + * + * Input is validated up front instead of refused tile-by-tile: the placement map must restate every + * tile (an explicit null marks it unpacked), every placement must name one of [pages], and a tile + * with drawables bound must carry an expressible re-derivation. The orchestrating repack guarantees + * all three - it aborts before mutating when a bound tile cannot come along - so a violation here is + * a caller bug, not document state to absorb. A tile with NO drawables bound may have an + * inexpressible mapping (a degenerate imported placement); its placement still installs, and there + * are no coordinates to move. + * + * A tile whose mapping comes out unchanged is left alone entirely, so an untouched drawable's + * coordinate arrays pass through by reference rather than picking up float round-trip noise. + * + * PIXELS ARE NOT MOVED - [withAtlasPlacement]'s rule, unchanged: the caller must compose the new + * pages for the result to render. + * + * @param List pages The new page inventory. + * @param Map placementsByTile Every tile's new placement, keyed by tile, null for unpacked. + * @param AtlasComposition composition The trim and extrusion policy the pack composed under, recorded + * so the pages derive the same way; defaults to the atlas's current policy. + * @return PuppetModel The repacked model, or [this] when nothing changes. + */ +fun PuppetModel.withAtlasRepack( + pages: List, + placementsByTile: Map, + composition: AtlasComposition = atlas.composition, +): PuppetModel { + require(placementsByTile.keys == atlas.tiles.map { tile -> tile.id }.toSet()) { + "a repack must restate every tile's placement exactly once" + } + for ((tileId, placement) in placementsByTile) { + if (placement != null) { + require(placement.pageIndex in pages.indices) { + "tile '${tileId.raw}' names page ${placement.pageIndex} of ${pages.size}" + } + } + } + val movedTiles = atlas.tiles.map { tile -> tile.copy(placement = placementsByTile.getValue(tile.id)) } + val newAtlas = atlas.copy(pages = pages, tiles = movedTiles, composition = composition) + if (newAtlas == atlas) { + return this + } + + val boundTileIds = drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val remapByTile = HashMap() + for (tile in atlas.tiles) { + when (val outcome = tileRemap(atlas, newAtlas, tile.id)) { + TileRemapOutcome.Unchanged -> Unit + TileRemapOutcome.Inexpressible -> + require(tile.id !in boundTileIds) { + "tile '${tile.id.raw}' has drawables bound but no expressible re-derivation" + } + is TileRemapOutcome.Remap -> remapByTile[tile.id] = outcome.remap + } + } + return copy(atlas = newAtlas, drawables = drawables.remappedOver(remapByTile)) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/RowDropBand.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/RowDropBand.kt new file mode 100644 index 0000000..a606838 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/RowDropBand.kt @@ -0,0 +1,10 @@ +package org.umamo.edit + +/** + * Where a row drop lands relative to the target row: before it, into it (nesting inside a container + * row, when the panel's rules allow it), or after it. Shared by every row-dragging panel (outliner, + * parameters) so their drop rules and indicators speak one vocabulary. + * + * 行ドロップが対象行のどこに落ちるか(前・中・後)。行ドラッグを持つ各パネルで共有される。 + */ +enum class RowDropBand { Before, Into, After } \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/Selection.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/Selection.kt new file mode 100644 index 0000000..7f19c16 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/Selection.kt @@ -0,0 +1,241 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/** + * A selectable rig entity, addressed by its typed id. A closed taxonomy (part, drawable, or deformer) + * so a `when` over a selection is exhaustive; adding a fourth selectable kind becomes a compile error + * until handled everywhere. This is object-mode selection — whole entities, not their interior mesh + * vertices or deformer control points (those belong to Edit mode, see [EditorMode]). + */ +sealed interface SelectionTarget { + /** An organizational tree part. */ + data class Part(val id: PartId) : SelectionTarget + + /** A textured drawable mesh. */ + data class Drawable(val id: DrawableId) : SelectionTarget + + /** A warp or rotation deformer. */ + data class Deformer(val id: DeformerId) : SelectionTarget +} + +/** + * An immutable object-mode selection: the set of selected targets plus the active (primary) one — the + * last target the user added, which the Inspector features when several are selected and which anchors + * future range operations. The active target is always a member of [targets], or null when the + * selection is empty. + */ +data class Selection( + /** The selected targets, empty when nothing is selected. */ + val targets: Set = emptySet(), + /** The primary target (last added), or null when [targets] is empty. */ + val active: SelectionTarget? = null, +) { + /** True when nothing is selected. */ + val isEmpty: Boolean get() = targets.isEmpty() + + /** The number of selected targets. */ + val size: Int get() = targets.size + + /** + * Reports whether the given target is part of this selection. + * + * @param SelectionTarget target The target to test. + * @return Boolean True when [target] is selected. + */ + operator fun contains(target: SelectionTarget): Boolean = target in targets +} + +/** + * The parameters currently targeted for keyform authoring: the selected set plus the active (primary) one. + * + * Separate from [Selection] because it addresses a different axis of the document - you pick WHICH OBJECT + * to key from the object selection, and WHICH PARAMETER to key it on from here, and the two move + * independently. Held on the session rather than a panel's view state because it is shared: a keyform + * sheet in one area follows the parameter chosen in a parameters panel in another. + */ +data class ParameterSelection( + /** The selected parameters, empty when none is targeted. */ + val ids: Set = emptySet(), + /** The primary parameter (last added), or null when [ids] is empty. */ + val active: ParameterId? = null, +) { + /** True when no parameter is targeted. */ + val isEmpty: Boolean get() = ids.isEmpty() + + /** + * Reports whether the given parameter is selected. + * + * @param ParameterId id The parameter to test. + * @return Boolean True when [id] is selected. + */ + operator fun contains(id: ParameterId): Boolean = id in ids + + companion object { + /** + * A selection of just [id], the plain-click result. + * + * @param ParameterId id The sole parameter to select. + * @return ParameterSelection A selection holding only [id], with it active. + */ + fun of(id: ParameterId): ParameterSelection = ParameterSelection(setOf(id), id) + } + + /** + * This selection with [id] toggled (a Shift or primary-modifier click, matching [SelectionOps.toggle]). + * + * @param ParameterId id The parameter to toggle. + * @return ParameterSelection The resulting selection. + */ + fun toggled(id: ParameterId): ParameterSelection = + if (id in ids) { + val remaining = ids - id + ParameterSelection(remaining, remaining.lastOrNull()) + } else { + ParameterSelection(ids + id, id) + } + + /** + * This selection with every parameter not in [surviving] dropped - applied after a parameter is + * deleted, so the target can never dangle on an id the model no longer has. + * + * @param Set surviving The parameter ids still present in the model. + * @return ParameterSelection The pruned selection, or this when nothing was dropped. + */ + fun prunedTo(surviving: Set): ParameterSelection { + val kept = ids intersect surviving + return if (kept.size == ids.size) this else ParameterSelection(kept, active?.takeIf { it in kept } ?: kept.lastOrNull()) + } +} + +/** + * Pure transformations over a [Selection], one per selection gesture. Each returns a new immutable + * [Selection] and never mutates its input, so they are trivially unit-testable without Compose or a + * render context. The active target is maintained per the [Selection] invariant: it is always a member + * of the result's targets, or null when the result is empty. + */ +object SelectionOps { + /** + * Replaces the whole selection with a single target (a plain click). + * + * @param SelectionTarget target The sole target to select. + * @return Selection A selection holding only [target], with it active. + */ + fun replace(target: SelectionTarget): Selection = Selection(setOf(target), target) + + /** + * Toggles a target's membership (a Shift or Ctrl / Cmd click, Blender-style): removes it when + * present, adds it otherwise. When added it becomes active; when removed the active target falls + * back to another remaining member, or null if the selection became empty. + * + * @param Selection selection The selection to modify. + * @param SelectionTarget target The target to toggle. + * @return Selection The resulting selection. + */ + fun toggle(selection: Selection, target: SelectionTarget): Selection = + if (target in selection.targets) { + val remaining = selection.targets - target + Selection(remaining, remaining.lastOrNull()) + } else { + Selection(selection.targets + target, target) + } + + /** + * Adds a target without removing anything (an additive gesture with no current default binding), + * making it active. Adding a target already present simply promotes it to active. + * + * @param Selection selection The selection to extend. + * @param SelectionTarget target The target to add. + * @return Selection The extended selection. + */ + fun add(selection: Selection, target: SelectionTarget): Selection = Selection(selection.targets + target, target) + + /** + * Clears the selection. + * + * @return Selection An empty selection. + */ + fun clear(): Selection = Selection() + + /** + * Every selectable entity in the model as a target set, in parts-then-deformers-then-drawables order. + * A locked entity (isSelectable == false) is excluded, matching the pointer picker. The full set + * [selectAll] fills and [invert] complements against. + * + * @param PuppetModel model The rig to enumerate. + * @return Set Every selectable target. + */ + private fun allSelectableTargets(model: PuppetModel): Set { + val targets = LinkedHashSet() + for (part in model.parts) { + if (part.isSelectable) { + targets.add(SelectionTarget.Part(part.id)) + } + } + for (deformer in model.deformers) { + if (deformer.isSelectable) { + targets.add(SelectionTarget.Deformer(deformer.id)) + } + } + for (drawable in model.drawables) { + if (drawable.isSelectable) { + targets.add(SelectionTarget.Drawable(drawable.id)) + } + } + return targets + } + + /** + * Selects every selectable entity in the model (Blender's Select All in object mode). Keeps the current + * active target (it is necessarily still selected); with none, the last enumerated target becomes active. + * + * @param Selection selection The current selection (its active target is preserved when possible). + * @param PuppetModel model The rig whose entities to select. + * @return Selection The selection holding every selectable target. + */ + fun selectAll(selection: Selection, model: PuppetModel): Selection { + val allTargets = allSelectableTargets(model) + val active = selection.active?.takeIf { target -> target in allTargets } ?: allTargets.lastOrNull() + return Selection(allTargets, active) + } + + /** + * Inverts the object selection (Blender's Ctrl+I): every selectable entity not currently selected + * becomes selected and vice versa. The active target is kept only when it survives the inversion, which + * in practice drops it (a selected active target is deselected by the inversion). + * + * @param Selection selection The selection to invert. + * @param PuppetModel model The rig whose entities define the domain. + * @return Selection The inverted selection. + */ + fun invert(selection: Selection, model: PuppetModel): Selection { + val inverted = allSelectableTargets(model) - selection.targets + return Selection(inverted, selection.active?.takeIf { target -> target in inverted }) + } + + /** + * Expands every selected target to its outliner subtree (the Select Hierarchy context action): a + * part adds its descendant parts and their drawables, a deformer its descendant deformers, a + * drawable just itself - exactly the rows the outliner shows beneath each (see + * [PuppetModel.subtreeTargets]). The active target is kept (still selected); an empty selection + * stays empty. + * + * @param Selection selection The selection whose targets to expand. + * @param PuppetModel model The rig the subtrees are read from. + * @return Selection The selection with every subtree included. + */ + fun selectHierarchy(selection: Selection, model: PuppetModel): Selection { + if (selection.isEmpty) { + return selection + } + val expanded = LinkedHashSet() + for (target in selection.targets) { + expanded.addAll(model.subtreeTargets(target)) + } + return Selection(expanded, selection.active ?: expanded.lastOrNull()) + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionPropertyEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionPropertyEdits.kt new file mode 100644 index 0000000..ae75229 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionPropertyEdits.kt @@ -0,0 +1,524 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.AtlasComposition +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.SourceLayerRef + +/* + * Scalar property edits on an EditorSession, mostly driven by the Properties panel's editable controls + * (the atlas edits at the end of the file are not: commitAtlasRepack is driven by the atlas repack + * flow, setAtlasPlacements by the UV editor's placement gizmo, and setAtlasPins by its pin commands). Each + * applies one field change as a single undo step via mutate, dispatching the typed Change plus its + * PuppetModelEdits transform, and short-circuits to nothing on a no-op (the builder returns the same + * model instance). These are the write half of the Properties panel: a checkbox / dropdown / numeric + * field commit calls exactly one of these, and a registry command flipping the same document field + * (document.toggleSourceArtworkDisplay) goes through the same entry point rather than mutating in + * parallel, so both routes produce the one identical undo step. Continuous numeric scrubbing previews + * in the widget and commits one of these on release, so there is no per-frame mutation and no + * history-side coalescing (the same single-commit-per-gesture granularity the parameter scrub documents + * in ParameterChange.SetValue). + */ + +/** + * Sets drawable [id]'s color blend mode as one undo step. + * + * @param DrawableId id The drawable to retarget. + * @param BlendMode mode The new blend mode. + */ +fun EditorSession.setDrawableBlendMode(id: DrawableId, mode: BlendMode) { + mutate(DrawableChange.SetBlendMode(id, mode)) { model -> model.withDrawableBlendMode(id, mode) } +} + +/** + * Sets drawable [id]'s alpha blend mode as one undo step. + * + * @param DrawableId id The drawable to retarget. + * @param AlphaBlendMode mode The new alpha blend mode. + */ +fun EditorSession.setDrawableAlphaBlendMode(id: DrawableId, mode: AlphaBlendMode) { + mutate(DrawableChange.SetAlphaBlendMode(id, mode)) { model -> model.withDrawableAlphaBlendMode(id, mode) } +} + +/** + * Sets drawable [id]'s back-face culling as one undo step. + * + * @param DrawableId id The drawable to retarget. + * @param Boolean culling The new culling state. + */ +fun EditorSession.setDrawableCulling(id: DrawableId, culling: Boolean) { + mutate(DrawableChange.SetCulling(id, culling)) { model -> model.withDrawableCulling(id, culling) } +} + +/** + * Sets drawable [id]'s mask-inversion flag as one undo step. + * + * @param DrawableId id The drawable to retarget. + * @param Boolean invert The new inverted-mask state. + */ +fun EditorSession.setDrawableInvertMask(id: DrawableId, invert: Boolean) { + mutate(DrawableChange.SetInvertMask(id, invert)) { model -> model.withDrawableInvertMask(id, invert) } +} + +/** + * Sets drawable [id]'s static opacity as one undo step. + * + * @param DrawableId id The drawable to retarget. + * @param Float opacity The new opacity. + */ +fun EditorSession.setDrawableOpacity(id: DrawableId, opacity: Float) { + mutate(DrawableChange.SetOpacity(id, opacity)) { model -> model.withDrawableOpacity(id, opacity) } +} + +/** + * Sets drawable [id]'s static draw order as one undo step. + * + * @param DrawableId id The drawable to retarget. + * @param Float drawOrder The new draw order. + */ +fun EditorSession.setDrawableDrawOrder(id: DrawableId, drawOrder: Float) { + mutate(DrawableChange.SetDrawOrder(id, drawOrder)) { model -> model.withDrawableDrawOrder(id, drawOrder) } +} + +/** + * Sets deformer [id]'s static opacity as one undo step. Cascades onto every drawable beneath it. + * + * @param DeformerId id The deformer to retarget. + * @param Float opacity The new opacity. + */ +fun EditorSession.setDeformerOpacity(id: DeformerId, opacity: Float) { + mutate(DeformerChange.SetOpacity(id, opacity)) { model -> model.withDeformerOpacity(id, opacity) } +} + +/** + * Sets deformer [id]'s static multiply color as one undo step. Cascades onto every drawable beneath it. + * + * @param DeformerId id The deformer to retint. + * @param ColorRgb color The new multiply color. + */ +fun EditorSession.setDeformerMultiplyColor(id: DeformerId, color: ColorRgb) { + mutate(DeformerChange.SetMultiplyColor(id, color)) { model -> model.withDeformerMultiplyColor(id, color) } +} + +/** + * Sets deformer [id]'s static screen color as one undo step. Cascades onto every drawable beneath it. + * + * @param DeformerId id The deformer to retint. + * @param ColorRgb color The new screen color. + */ +fun EditorSession.setDeformerScreenColor(id: DeformerId, color: ColorRgb) { + mutate(DeformerChange.SetScreenColor(id, color)) { model -> model.withDeformerScreenColor(id, color) } +} + +/** + * Sets rotation deformer [id]'s static horizontal reflection as one undo step. + * + * @param DeformerId id The deformer to retarget. + * @param Boolean flip The new reflection state. + */ +fun EditorSession.setDeformerFlipX(id: DeformerId, flip: Boolean) { + mutate(DeformerChange.SetFlipX(id, flip)) { model -> model.withDeformerFlipX(id, flip) } +} + +/** + * Sets rotation deformer [id]'s static vertical reflection as one undo step. + * + * @param DeformerId id The deformer to retarget. + * @param Boolean flip The new reflection state. + */ +fun EditorSession.setDeformerFlipY(id: DeformerId, flip: Boolean) { + mutate(DeformerChange.SetFlipY(id, flip)) { model -> model.withDeformerFlipY(id, flip) } +} + +/** + * Sets drawable [id]'s multiply color (the static value) as one undo step. + * + * @param DrawableId id The drawable to retint. + * @param ColorRgb color The new multiply color. + */ +fun EditorSession.setDrawableMultiplyColor(id: DrawableId, color: ColorRgb) { + mutate(DrawableChange.SetMultiplyColor(id, color)) { model -> model.withDrawableMultiplyColor(id, color) } +} + +/** + * Sets drawable [id]'s screen color (the static value) as one undo step. + * + * @param DrawableId id The drawable to retint. + * @param ColorRgb color The new screen color. + */ +fun EditorSession.setDrawableScreenColor(id: DrawableId, color: ColorRgb) { + mutate(DrawableChange.SetScreenColor(id, color)) { model -> model.withDrawableScreenColor(id, color) } +} + +/** + * Binds drawable [id] to the deformer that deforms it (null unbinds) as one undo step. + * + * @param DrawableId id The drawable to rebind. + * @param DeformerId? parentDeformerId The deformer that deforms it, or null to unbind. + */ +fun EditorSession.setDrawableParentDeformer(id: DrawableId, parentDeformerId: DeformerId?) { + mutate(DrawableChange.SetParentDeformer(id, parentDeformerId)) { model -> + model.withDrawableParentDeformer(id, parentDeformerId) + } +} + +/** + * Replaces drawable [id]'s clip-mask list as one undo step, so adding or removing a single mask is one + * step. + * + * @param DrawableId id The drawable whose masks change. + * @param List maskedBy The drawables whose alpha now clips it. + */ +fun EditorSession.setDrawableMaskedBy(id: DrawableId, maskedBy: List) { + mutate(DrawableChange.SetMaskedBy(id, maskedBy)) { model -> model.withDrawableMaskedBy(id, maskedBy) } +} + +/** + * Binds deformer [id] to the organizational part that owns it (null clears it) as one undo step. + * + * @param DeformerId id The deformer to rebind. + * @param PartId? partId The part that owns it, or null to clear. + */ +fun EditorSession.setDeformerPart(id: DeformerId, partId: PartId?) { + mutate(DeformerChange.SetPart(id, partId)) { model -> model.withDeformerPart(id, partId) } +} + +/** + * Sets rotation deformer [id]'s base angle as one undo step. A no-op on a warp deformer (it has no base + * angle), so the commit short-circuits. + * + * @param DeformerId id The deformer to retarget. + * @param Float angle The new base angle in degrees. + */ +fun EditorSession.setDeformerBaseAngle(id: DeformerId, angle: Float) { + mutate(DeformerChange.SetBaseAngle(id, angle)) { model -> model.withDeformerBaseAngle(id, angle) } +} + +/** + * Sets warp deformer [id]'s FFD interpolation mode as one undo step. A no-op on a rotation deformer (it + * has no lattice), so the commit short-circuits. + * + * @param DeformerId id The deformer to retarget. + * @param Boolean quad The new quad-transform state. + */ +fun EditorSession.setDeformerQuadTransform(id: DeformerId, quad: Boolean) { + mutate(DeformerChange.SetQuadTransform(id, quad)) { model -> model.withDeformerQuadTransform(id, quad) } +} + +/** + * Sets warp deformer [id]'s conversion-division grid as one undo step, resampling every lattice keyform + * so the art stays put. A no-op on a rotation deformer / missing lattice (see [withWarpDeformerGrid]). + * + * @param DeformerId id The deformer to retarget. + * @param Int rows The new conversion divisions vertically. + * @param Int columns The new conversion divisions horizontally. + */ +fun EditorSession.setDeformerWarpGrid(id: DeformerId, rows: Int, columns: Int) { + mutate(DeformerChange.SetGrid(id, rows, columns)) { model -> model.withWarpDeformerGrid(id, rows, columns) } +} + +/** + * Sets part [id]'s guide-image (sketch) flag as one undo step. + * + * @param PartId id The part to retarget. + * @param Boolean sketch The new sketch state. + */ +fun EditorSession.setPartSketch(id: PartId, sketch: Boolean) { + mutate(PartChange.SetSketch(id, sketch)) { model -> model.withPartSketch(id, sketch) } +} + +/** + * Sets part [id]'s own draw order as one undo step. + * + * @param PartId id The part to retarget. + * @param Int order The new draw order. + */ +fun EditorSession.setPartDrawOrder(id: PartId, order: Int) { + mutate(PartChange.SetDrawOrder(id, order)) { model -> model.withPartDrawOrder(id, order) } +} + +/** + * Sets part [id]'s rendering group mode as one undo step. The [mode] carries the whole value, so a mode + * switch and any Isolated-composite sub-field edit both flow through here. + * + * @param PartId id The part to retarget. + * @param PartGroupMode mode The new group mode. + */ +fun EditorSession.setPartGroupMode(id: PartId, mode: PartGroupMode) { + mutate(PartChange.SetGroupMode(id, mode)) { model -> model.withPartGroupMode(id, mode) } +} + +/** + * Sets part [id]'s latent compositing settings as one undo step. Stored independent of the group mode, + * so an isolated part's composite survives leaving and re-entering Isolated; applied only while Isolated. + * + * @param PartId id The part to retarget. + * @param PartComposite composite The new composite settings. + */ +fun EditorSession.setPartComposite(id: PartId, composite: PartComposite) { + mutate(PartChange.SetComposite(id, composite)) { model -> model.withPartComposite(id, composite) } +} + +/** + * Sets the document canvas size (world units) as one undo step. + * + * @param Float width The new canvas width. + * @param Float height The new canvas height. + */ +fun EditorSession.setCanvasSize(width: Float, height: Float) { + mutate(DocumentChange.SetCanvasSize(width, height)) { model -> model.withCanvasSize(width, height) } +} + +/** + * Sets the world origin (world space) as one undo step. + * + * @param Float x The new world-origin x. + * @param Float z The new world-origin z (up). + */ +fun EditorSession.setWorldOrigin(x: Float, z: Float) { + mutate(DocumentChange.SetWorldOrigin(x, z)) { model -> model.withWorldOrigin(x, z) } +} + +/** + * Sets the document's runtime-compatibility target as one undo step. + * + * @param RuntimeTarget target The new runtime target. + */ +fun EditorSession.setRuntimeTarget(target: RuntimeTarget) { + mutate(DocumentChange.SetRuntimeTarget(target)) { model -> model.withRuntimeTarget(target) } +} + +/** + * Switches the puppet between displaying from its source artwork and from the packed atlas, as one + * undo step. + * + * A display choice that is document content rather than an app preference: the source formats author + * it, so it round-trips and it marks the document dirty like any other authored value. + * + * @param Boolean fromSourceLayers True to display from the source artwork, false from the atlas. + */ +fun EditorSession.setSourceLayerDisplay(fromSourceLayers: Boolean) { + mutate(DocumentChange.SetSourceLayerDisplay(fromSourceLayers)) { model -> model.withSourceLayerDisplay(fromSourceLayers) } +} + +/** + * Packs one piece of source art at [placement] as a single undo step, re-mapping every drawable over it + * so the art keeps meaning what it did - [setAtlasPlacements] over one tile. + * + * @param AtlasTileId tileId The tile to place. + * @param AtlasPlacement? placement Where its art now sits, or null to mark it unpacked. + */ +fun EditorSession.setAtlasPlacement(tileId: AtlasTileId, placement: AtlasPlacement?) { + setAtlasPlacements(mapOf(tileId to placement)) +} + +/** + * Packs several pieces of source art at once as ONE undo step - a placement gesture over a + * multi-tile selection is one edit, not one step per tile - re-mapping every drawable over them so + * the art keeps meaning what it did. + * + * The pages' PIXELS are session state derived from the model, not part of it: the session's page + * resolver composes the pages the new placements denote once this commit publishes (and re-composes + * them on undo), so nothing here touches a pixel and no snapshot ever carries one. + * + * @param Map placementByTile Each tile's new placement, keyed by tile, null to mark it unpacked. + * @param MeshOperatorKind? kind The placement operator that produced the move (it names the + * step), or null for a placement written by no gesture. + */ +fun EditorSession.setAtlasPlacements( + placementByTile: Map, + kind: MeshOperatorKind? = null, +) { + mutate(DocumentChange.SetAtlasPlacement(placementByTile.keys.toList(), kind)) { model -> model.withAtlasPlacements(placementByTile) } +} + +/** + * Pins or unpins the placed tiles among [tileIds] as one undo step, so a repack keeps (or may move) + * them - withAtlasPins under the one history push a pin command or checkbox should be. + * + * @param Collection tileIds The tiles to pin or unpin. + * @param Boolean pinned True to pin, false to unpin. + */ +fun EditorSession.setAtlasPins(tileIds: Collection, pinned: Boolean) { + mutate(DocumentChange.SetAtlasPin(tileIds.toList(), pinned)) { model -> model.withAtlasPins(tileIds, pinned) } +} + +/** + * Rebinds one tile to a layer of a listed artwork file, or unbinds it, as one undo step - + * withTileSource under the one history push a relink should be. + * + * @param AtlasTileId tileId The tile to rebind. + * @param SourceLayerRef? source The new binding, or null to unbind. + */ +fun EditorSession.setTileSource(tileId: AtlasTileId, source: SourceLayerRef?) { + setTileSources(listOf(tileId), source) +} + +/** + * Rebinds every tile in [tileIds] to one layer of a listed artwork file, or unbinds them all, as ONE + * undo step - what a review row's accepted proposal lands through when the layer's art cannot be + * pulled, so the tiles bound to a lost key move together. A tile the model refuses (unknown, or a + * binding to an unlisted file) is left as it is; a call that changes no tile pushes nothing. + * + * @param Collection tileIds The tiles to rebind, in any order; empty pushes nothing. + * @param SourceLayerRef? source The new binding, or null to unbind. + */ +fun EditorSession.setTileSources(tileIds: Collection, source: SourceLayerRef?) { + val first = tileIds.firstOrNull() ?: return + mutate(DocumentChange.SetTileSource(first, bound = source != null)) { model -> + tileIds.fold(model) { current, tileId -> current.withTileSource(tileId, source) } + } +} + +/** + * Removes the tile [tileId] from the atlas as one undo step, when no drawable samples it; a tile some + * drawable still samples, or one the model lacks, pushes nothing. With [ignoreLayer] the layer the tile + * was bound to is marked ignored in the same step (the import setting's choice), so the next reload + * does not mint the art back; an unbound tile has no layer to mark, and a layer another tile still binds + * is left unmarked, since the reload matches it by key. + * + * @param AtlasTileId tileId The tile to remove. + * @param Boolean ignoreLayer Whether to keep the tile's layer out of the rig from now on. + */ +fun EditorSession.deleteTile(tileId: AtlasTileId, ignoreLayer: Boolean = false) { + val current = model.value + val binding = current.atlas.tileById[tileId]?.source + val shared = + binding != null && + current.atlas.tiles.any { other -> other.id != tileId && other.source?.sourceId == binding.sourceId && other.source?.layerKey == binding.layerKey } + val marks = ignoreLayer && binding != null && !shared + mutate(DocumentChange.DeleteTile(tileId, ignoredLayer = marks)) { before -> + val deleted = before.withTileDeleted(tileId) + // marks already carries binding != null, and the compiler smart-casts through it. + if (marks && deleted !== before) { + deleted.withLayerIgnored(binding.sourceId, binding.layerKey, ignored = true) + } else { + deleted + } + } +} + +/** + * Marks or clears the ignore on one inventory row as one undo step - withLayerIgnored under the one + * history push the Sources row's toggle should be; a row the model refuses (unknown, or a key some tile + * binds) pushes nothing. + * + * @param SourceLayerRef ref The file and layer key. + * @param Boolean ignored True to keep the layer out of the rig, false to let a reload mint it again. + */ +fun EditorSession.setLayerIgnored(ref: SourceLayerRef, ignored: Boolean) { + mutate(DocumentChange.SetLayerIgnored(ref.sourceId, ref.layerKey, ignored)) { before -> before.withLayerIgnored(ref.sourceId, ref.layerKey, ignored) } +} + +/** + * Commits a model that already carries an artwork file's additions and their pack as ONE undo step. + * + * The orchestrator builds [added] off the UI thread (the bridge, the pack around the existing art, + * the re-derivation) from the model current when it started, checks nothing moved underneath it, and + * lands it here; the page pixels are session state it swaps in beside this commit, which is why the + * committed model comes back for the resolver's pre-warm. + * + * @param String sourceName The added file's display name, for the history label. + * @param Int drawableCount How many drawables it added. + * @param PuppetModel added The model with the additions and their pack applied. + * @return PuppetModel The committed model. + */ +fun EditorSession.commitArtworkAdded(sourceName: String, drawableCount: Int, added: PuppetModel): PuppetModel { + mutate(DocumentChange.AddArtwork(sourceName, drawableCount)) { added } + return added +} + +/** + * Commits a model that already carries a reload of the document's artwork files and its pack as ONE + * undo step - the same contract as [commitArtworkAdded]: built off the UI thread from the model + * current when the reload started, checked against it, landed here, the page pixels swapped in + * beside it and the committed model returned for the resolver's pre-warm. + * + * @param DocumentChange.ReloadArtwork change The step's counts, for the history label. + * @param PuppetModel reloaded The model with the reload and its pack applied. + * @return PuppetModel The committed model. + */ +fun EditorSession.commitArtworkReloaded(change: DocumentChange.ReloadArtwork, reloaded: PuppetModel): PuppetModel { + mutate(change) { reloaded } + return reloaded +} + +/** + * Commits a model that already carries one tile's rebinding with the layer's art pulled in, and its + * pack, as ONE undo step; see [commitArtworkAdded] for the contract. + * + * @param AtlasTileId tileId The rebound tile's id before the replacement. + * @param PuppetModel relinked The model with the relink and its pack applied. + * @return PuppetModel The committed model. + */ +fun EditorSession.commitArtworkRelinked(tileId: AtlasTileId, relinked: PuppetModel): PuppetModel { + mutate(DocumentChange.RelinkArtwork(tileId)) { relinked } + return relinked +} + +/** + * Commits a model that already carries the matcher's accepted rebindings and their pack as ONE undo + * step; see [commitArtworkAdded] for the contract. + * + * @param DocumentChange.MatchArtwork change The step's counts, for the history label. + * @param PuppetModel matched The model with the rebindings and their pack applied. + * @return PuppetModel The committed model. + */ +fun EditorSession.commitArtworkMatched(change: DocumentChange.MatchArtwork, matched: PuppetModel): PuppetModel { + mutate(change) { matched } + return matched +} + +/** + * Commits a model that already carries one record's replacement, the reload it resolved by key, and + * its pack as ONE undo step; see [commitArtworkAdded] for the contract. + * + * @param DocumentChange.ReplaceArtwork change The step's counts, for the history label. + * @param PuppetModel replaced The model with the replacement and its pack applied. + * @return PuppetModel The committed model. + */ +fun EditorSession.commitArtworkReplaced(change: DocumentChange.ReplaceArtwork, replaced: PuppetModel): PuppetModel { + mutate(change) { replaced } + return replaced +} + +/** + * Repacks the whole atlas as a single undo step: the new page inventory and every tile's placement + * land together, with every bound drawable's coordinates re-derived over them - withAtlasRepack's + * one-pass edit under the one history push a repack should be. + * + * The page PIXELS are session state the caller swaps in beside this commit, which is why the + * committed model comes back: the orchestrator pre-warms the session's page resolver with the SAME + * atlas instance this publishes (the resolver memoizes by identity), so the commit resolves its + * pages by cache hit - and undo re-resolves them the same way. + * + * @param List pages The new page inventory. + * @param Map placementsByTile Every tile's new placement, keyed by tile, null for unpacked. + * @param AtlasComposition composition The trim and extrusion policy the pack composed under. + * @return PuppetModel? The committed model, or null when the repack restated the atlas exactly. + */ +fun EditorSession.commitAtlasRepack( + pages: List, + placementsByTile: Map, + composition: AtlasComposition = model.value.atlas.composition, +): PuppetModel? { + val current = model.value + val repacked = current.withAtlasRepack(pages, placementsByTile, composition) + if (repacked === current) { + return null + } + val placedCount = placementsByTile.count { entry -> entry.value != null } + mutate(DocumentChange.RepackAtlas(placedCount, pages.size)) { repacked } + return repacked +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionRequestBus.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionRequestBus.kt new file mode 100644 index 0000000..ccd1c26 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionRequestBus.kt @@ -0,0 +1,237 @@ +package org.umamo.edit + +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow + +/** + * The session's request buses: fire-and-forget signals from command handlers to the area that + * executes them - a viewport or UV editor overlay, or the UV editor space itself. Every one exists + * for the same reason - the operation needs something only the receiving area has (the pointer + * position, the projected geometry, the in-flight working positions, the area's own view state), so + * the session cannot execute it directly; it signals here and the observing collector executes. + * Pure plumbing with no other session state involved, hence a separate collaborator; [EditorSession] + * exposes each flow and request method unchanged. + */ + +internal class SessionRequestBus { + private val mutableSnapRequests = MutableSharedFlow(extraBufferCapacity = 4) + + /** The geometry-dependent snap requests (see [EditorSession.snapRequests]). */ + val snapRequests: SharedFlow = mutableSnapRequests.asSharedFlow() + + private val mutableSelectLinkedRequests = MutableSharedFlow(extraBufferCapacity = 4) + + /** The Select Linked requests (see [EditorSession.selectLinkedRequests]). */ + val selectLinkedRequests: SharedFlow = mutableSelectLinkedRequests.asSharedFlow() + + private val mutableUvSnapRequests = MutableSharedFlow(extraBufferCapacity = 4) + + /** The UV editor snap requests (see [EditorSession.uvSnapRequests]). */ + val uvSnapRequests: SharedFlow = mutableUvSnapRequests.asSharedFlow() + + private val mutableUvMirrorRequests = MutableSharedFlow(extraBufferCapacity = 4) + + /** The UV editor mirror requests (see [EditorSession.uvMirrorRequests]). */ + val uvMirrorRequests: SharedFlow = mutableUvMirrorRequests.asSharedFlow() + + private val mutableViewportMirrorRequests = MutableSharedFlow(extraBufferCapacity = 4) + + /** The viewport geometry mirror requests (see [EditorSession.viewportMirrorRequests]). */ + val viewportMirrorRequests: SharedFlow = mutableViewportMirrorRequests.asSharedFlow() + + private val mutableUvPageRequests = MutableSharedFlow(extraBufferCapacity = 4) + + /** The UV editor page-switch requests (see [EditorSession.uvPageRequests]). */ + val uvPageRequests: SharedFlow = mutableUvPageRequests.asSharedFlow() + + private val mutableSwitchObjectRequests = MutableSharedFlow(extraBufferCapacity = 1) + + /** The Alt+Q edited-mesh switch requests, each carrying its executing area (see [EditorSession.switchObjectRequests]). */ + val switchObjectRequests: SharedFlow = mutableSwitchObjectRequests.asSharedFlow() + + private val mutableRipRequests = MutableSharedFlow(extraBufferCapacity = 1) + + /** The rip-at-pointer requests, each carrying its executing area (see [EditorSession.ripRequests]). */ + val ripRequests: SharedFlow = mutableRipRequests.asSharedFlow() + + private val mutableMeshConfirm = MutableSharedFlow(extraBufferCapacity = 1) + + /** The modal-gesture confirm requests (see [EditorSession.meshConfirmRequests]). */ + val meshConfirmRequests: SharedFlow = mutableMeshConfirm.asSharedFlow() + + private val mutableMeshGestureCancel = MutableSharedFlow(extraBufferCapacity = 1) + + /** The selection-gesture cancel requests (see [EditorSession.meshGestureCancelRequests]). */ + val meshGestureCancelRequests: SharedFlow = mutableMeshGestureCancel.asSharedFlow() + + /** + * Requests a geometry-dependent snap. + * + * @param SnapRequest request The snap to perform plus the dispatch-time resolved area. + */ + fun requestSnap(request: SnapRequest) { + mutableSnapRequests.tryEmit(request) + } + + /** + * Requests a Select Linked for one area's overlay to execute. + * + * @param SelectLinkedRequest request The flood variant plus the dispatch-time resolved area. + */ + fun requestSelectLinked(request: SelectLinkedRequest) { + mutableSelectLinkedRequests.tryEmit(request) + } + + /** + * Requests a UV snap for one UV editor area's overlay to execute. + * + * @param UvSnapRequest request The snap operation plus the dispatch-time resolved area. + */ + fun requestUvSnap(request: UvSnapRequest) { + mutableUvSnapRequests.tryEmit(request) + } + + /** + * Requests a mirror for one UV editor area's overlay to execute. + * + * @param UvMirrorRequest request The mirror axis plus the dispatch-time resolved area. + */ + fun requestUvMirror(request: UvMirrorRequest) { + mutableUvMirrorRequests.tryEmit(request) + } + + /** + * Requests a viewport geometry mirror for one area's overlay to execute. + * + * @param ViewportMirrorRequest request The axis plus the dispatch-time resolved area. + */ + fun requestViewportMirror(request: ViewportMirrorRequest) { + mutableViewportMirrorRequests.tryEmit(request) + } + + /** + * Requests a page switch for one UV editor area to execute. + * + * @param UvPageRequest request The page operation plus the dispatch-time resolved area. + */ + fun requestUvPage(request: UvPageRequest) { + mutableUvPageRequests.tryEmit(request) + } + + /** + * Requests an Alt+Q edited-mesh switch for one area's overlay to execute. + * + * @param String? areaId The dispatch-time resolved viewport area, or null when the pointer is elsewhere. + */ + fun requestSwitchObjectUnderCursor(areaId: String?) { + mutableSwitchObjectRequests.tryEmit(areaId) + } + + /** + * Requests a rip at the pointer for one area's overlay to execute. + * + * @param String? areaId The dispatch-time resolved viewport area, or null when the pointer is elsewhere. + */ + fun requestRip(areaId: String?) { + mutableRipRequests.tryEmit(areaId) + } + + /** Requests that the gizmo overlay confirm the in-flight modal gesture. */ + fun requestMeshConfirm() { + mutableMeshConfirm.tryEmit(Unit) + } + + /** Requests that the gizmo overlay abandon any in-flight box / circle selection gesture. */ + fun requestMeshGestureCancel() { + mutableMeshGestureCancel.tryEmit(Unit) + } +} + +/** + * One Select Linked request: which flood variant, and which area's overlay executes it. The area is + * resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload, + * so two collectors reading a volatile independently can never double- or zero-execute when the + * pointer crosses areas between resumptions. + * + * @property Boolean fromSelection True to flood from the whole selection (Ctrl+L), false from the cursor (L). + * @property String? areaId The area whose overlay executes, or null when no surface was ever touched + * (then no collector matches and the request is a clean no-op). + */ +data class SelectLinkedRequest(val fromSelection: Boolean, val areaId: String?) + +/** + * One UV snap request: which operation, and which UV editor area's overlay executes it. The area is + * resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload, + * exactly like [SelectLinkedRequest] - there is no area answer anywhere else for a collector to fall back + * on, so gating on this id is the whole mechanism. + * + * @property UvSnapKind kind The snap operation to perform. + * @property String? areaId The UV editor area whose overlay executes, or null when the hovered surface + * was not a UV editor (then no collector matches and the request is a clean no-op). + */ +data class UvSnapRequest(val kind: UvSnapKind, val areaId: String?) + +/** + * One UV mirror / reverse-swap request for a UV editor overlay. + * + * Geometric Mirror U/V reflects about a pivot ([reverseSwap] false). Toolbar Reverse Positions + * pairwise-swaps (u, v) among selected verts ([reverseSwap] true). + * + * @property Boolean mirrorU True to mirror horizontally, false vertically (ignored when [reverseSwap]). + * @property String? areaId The UV editor area whose overlay executes, or null when not over a UV editor. + * @property Boolean reverseSwap When true, pairwise-swap UV positions instead of reflecting about a pivot. + */ +data class UvMirrorRequest(val mirrorU: Boolean, val areaId: String?, val reverseSwap: Boolean = false) + +/** + * One viewport geometry mirror request: which axis, and which viewport area's overlay executes it. + * + * Edit-mode mesh verts, Object-mode drawables, and warp-lattice control points all need posed world + * geometry only the overlay has, so the command signals here the same way snaps do. + * + * @property Boolean mirrorHorizontal True to mirror left↔right (world X), false top↔bottom (world Y). + * @property String? areaId The viewport area whose overlay executes, or null when the pointer is not on a + * viewport (then no collector matches and the request is a clean no-op). + */ +data class ViewportMirrorRequest(val mirrorHorizontal: Boolean, val areaId: String?) + +/** + * The page operations a UV editor area's texture selection understands: cycling pins the next or + * previous atlas page with wrap-around from the currently shown page, and FollowSelection clears the + * pin back to the auto-follow default. These retarget a VIEW (the receiving area's per-area page + * pin), never the model, which is why they ride the request bus rather than the Change pipeline. + */ +enum class UvPageKind { + NextPage, + PreviousPage, + FollowSelection, +} + +/** + * One page-switch request: which operation, and which UV editor area executes it. The area is + * resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload, + * exactly like [UvSnapRequest] - there is no area answer anywhere else for a collector to fall back + * on, so gating on this id is the whole mechanism. + * + * @property UvPageKind kind The page operation to perform. + * @property String? areaId The UV editor area that executes, or null when the hovered surface was not + * a UV editor (then no collector matches and the request is a clean no-op). + */ +data class UvPageRequest(val kind: UvPageKind, val areaId: String?) + +/** + * One world-space snap request: which operation, and which viewport area's overlay executes it. The area + * is resolved ONCE at command dispatch (the hovered surface at that instant) and carried in the payload, + * exactly like [SelectLinkedRequest] and [UvSnapRequest]. + * + * The handlers ignore the area - a snap acts on the model, not on one viewport - so its only job here is + * ELECTION: every open viewport composes a collector, and without an id in the payload each would have to + * read a shared volatile to decide whether it is the one, which can double- or zero-execute when the + * pointer crosses areas between resumptions. + * + * @property SnapKind kind The snap operation to perform. + * @property String? areaId The viewport area whose overlay executes, or null when the pointer is not on a + * viewport (then no collector matches and the request is a clean no-op). + */ +data class SnapRequest(val kind: SnapKind, val areaId: String?) \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionTargetEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionTargetEdits.kt new file mode 100644 index 0000000..8f42a04 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionTargetEdits.kt @@ -0,0 +1,204 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/* + * Target-aware convenience edits on an EditorSession: a single selectable entity (part/drawable/deformer) + * is toggled or renamed as one undo step, and the subtree variants (a Blender-style Shift+Click on an + * outliner restriction icon) flip a whole outliner subtree in one step. These dispatch the right + * Change + transform per target kind so call sites (the outliner's per-row eye and inline rename) stay a + * thin one-liner. The selection-wide visibility toggle stays separate (see withSelectionVisibility) — + * that one flips the whole selection. + * + * 対象1件(パーツ/描画/デフォーマ)を1段の取り消し単位で切り替え・改名するセッション補助。サブツリー版 + * (Shift クリック)は配下全体を1段で切り替える。 + */ + +/** + * Toggles the visibility of one [target] as a single undo step, dispatching the part- or drawable-specific + * change and transform. A deformer has no visibility flag, so it is a no-op. + * + * @param SelectionTarget target The entity whose eyeball to flip. + */ +fun EditorSession.toggleVisibility(target: SelectionTarget) { + val newVisible = !model.value.visibilityOf(target) + when (target) { + is SelectionTarget.Part -> + mutate(PartChange.SetVisibility(target.id, newVisible)) { model -> model.withPartVisibility(target.id, newVisible) } + is SelectionTarget.Drawable -> + mutate(DrawableChange.SetVisibility(target.id, newVisible)) { model -> model.withDrawableVisibility(target.id, newVisible) } + is SelectionTarget.Deformer -> { + // Deformers have no visibility flag; nothing to toggle. + } + } +} + +/** + * Renames one [target] to [newName] as a single undo step, dispatching the per-kind change and transform. + * A blank name (after trimming) is ignored, so an empty commit keeps the old name. + * + * @param SelectionTarget target The entity to rename. + * @param String newName The requested new name. + */ +fun EditorSession.rename(target: SelectionTarget, newName: String) { + val trimmed = newName.trim() + if (trimmed.isEmpty()) { + return + } + when (target) { + is SelectionTarget.Part -> mutate(PartChange.Rename(target.id, trimmed)) { model -> model.withPartName(target.id, trimmed) } + is SelectionTarget.Drawable -> mutate(DrawableChange.Rename(target.id, trimmed)) { model -> model.withDrawableName(target.id, trimmed) } + is SelectionTarget.Deformer -> mutate(DeformerChange.Rename(target.id, trimmed)) { model -> model.withDeformerName(target.id, trimmed) } + } +} + +/** + * Whether [target] is viewport-selectable in [this] model. A missing entity reports true (selectable). + * + * @param SelectionTarget target The entity to query. + * @return Boolean The entity's selectable state. + */ +fun PuppetModel.selectableOf(target: SelectionTarget): Boolean = + when (target) { + is SelectionTarget.Part -> parts.firstOrNull { it.id == target.id }?.isSelectable ?: true + is SelectionTarget.Drawable -> drawables.firstOrNull { it.id == target.id }?.isSelectable ?: true + is SelectionTarget.Deformer -> deformers.firstOrNull { it.id == target.id }?.isSelectable ?: true + } + +/** + * Toggles the viewport selectability of one [target] as a single undo step, dispatching the per-kind + * change and transform. Unlike visibility, a deformer has a selectable flag too. + * + * @param SelectionTarget target The entity whose selectability to flip. + */ +fun EditorSession.toggleSelectable(target: SelectionTarget) { + val newSelectable = !model.value.selectableOf(target) + when (target) { + is SelectionTarget.Part -> + mutate(PartChange.SetSelectable(target.id, newSelectable)) { model -> model.withPartSelectable(target.id, newSelectable) } + is SelectionTarget.Drawable -> + mutate(DrawableChange.SetSelectable(target.id, newSelectable)) { model -> model.withDrawableSelectable(target.id, newSelectable) } + is SelectionTarget.Deformer -> + mutate(DeformerChange.SetSelectable(target.id, newSelectable)) { model -> model.withDeformerSelectable(target.id, newSelectable) } + } +} + +/** + * Enumerates the outliner subtree rooted at [target], the target itself first, in tree order. Matches + * exactly what the outliner shows as children: a part yields itself plus every descendant part and every + * drawable in those parts' org-tree children; a deformer yields itself plus its descendant deformers only + * (never the drawables bound to them via parentDeformerId — those rows live under their parts); a + * drawable is a leaf, so it yields just itself. An id that no longer resolves is still yielded (the + * transforms no-op on it) but never descended into, and a malformed cycle is visited once. Pure over the + * model, so it unit-tests without Compose. + * + * @param SelectionTarget target The subtree root. + * @return List The subtree's targets, [target] first. + */ +fun PuppetModel.subtreeTargets(target: SelectionTarget): List = + when (target) { + is SelectionTarget.Part -> { + val partsById = parts.associateBy { part -> part.id } + val visitedPartIds = HashSet() + val collected = mutableListOf() + + fun visitPart(partId: PartId) { + if (!visitedPartIds.add(partId)) { + return + } + collected += SelectionTarget.Part(partId) + val part = partsById[partId] ?: return + for (childEntry in part.children) { + when (childEntry) { + is OrgChild.Part -> visitPart(childEntry.id) + is OrgChild.Drawable -> collected += SelectionTarget.Drawable(childEntry.id) + } + } + } + visitPart(target.id) + collected + } + is SelectionTarget.Drawable -> listOf(target) + is SelectionTarget.Deformer -> { + val deformersByParent = deformers.groupBy { deformer -> deformer.parent } + val visitedDeformerIds = HashSet() + val collected = mutableListOf() + + fun visitDeformer(deformerId: DeformerId) { + if (!visitedDeformerIds.add(deformerId)) { + return + } + collected += SelectionTarget.Deformer(deformerId) + for (childDeformer in deformersByParent[deformerId].orEmpty()) { + visitDeformer(childDeformer.id) + } + } + visitDeformer(target.id) + collected + } + } + +/** + * Returns a copy of [this] with every entity in [targets] set to [selectable], structurally sharing + * untouched entities. Unlike the visibility counterpart (withSelectionVisibility) this covers deformers + * too — they carry the flag. Folding all targets into one model makes a whole subtree toggle a single + * undo step. + * + * @param Set targets The targets to retoggle. + * @param Boolean selectable The new selectable state. + * @return PuppetModel The model with those entities' selectability updated. + */ +fun PuppetModel.withSelectionSelectable(targets: Set, selectable: Boolean): PuppetModel { + var next = this + for (target in targets) { + next = + when (target) { + is SelectionTarget.Part -> next.withPartSelectable(target.id, selectable) + is SelectionTarget.Drawable -> next.withDrawableSelectable(target.id, selectable) + is SelectionTarget.Deformer -> next.withDeformerSelectable(target.id, selectable) + } + } + return next +} + +/** + * Toggles viewport selectability for [target] and its whole outliner subtree as one undo step: the new + * value is the flip of the clicked target's current state, applied uniformly to every subtree entity (a + * Blender-style Shift+Click), so a mixed subtree lands on one state. Reuses the clicked target's + * per-kind SetSelectable change, mirroring the selection-wide visibility command. + * + * @param SelectionTarget target The clicked subtree root. + */ +fun EditorSession.toggleSelectableSubtree(target: SelectionTarget) { + val newSelectable = !model.value.selectableOf(target) + val change: Change = + when (target) { + is SelectionTarget.Part -> PartChange.SetSelectable(target.id, newSelectable) + is SelectionTarget.Drawable -> DrawableChange.SetSelectable(target.id, newSelectable) + is SelectionTarget.Deformer -> DeformerChange.SetSelectable(target.id, newSelectable) + } + mutate(change) { model -> model.withSelectionSelectable(model.subtreeTargets(target).toSet(), newSelectable) } +} + +/** + * Toggles visibility for [target] and its whole outliner subtree as one undo step, applied uniformly like + * the selectable variant. Deformers have no visibility flag, so a deformer target is a no-op (the + * outliner shows no eye for one anyway) and any deformer inside a part subtree is skipped by + * withSelectionVisibility. + * + * @param SelectionTarget target The clicked subtree root. + */ +fun EditorSession.toggleVisibilitySubtree(target: SelectionTarget) { + val newVisible = !model.value.visibilityOf(target) + val change: Change = + when (target) { + is SelectionTarget.Part -> PartChange.SetVisibility(target.id, newVisible) + is SelectionTarget.Drawable -> DrawableChange.SetVisibility(target.id, newVisible) + // A deformer has no visibility flag; nothing to toggle. + is SelectionTarget.Deformer -> return + } + mutate(change) { model -> model.withSelectionVisibility(model.subtreeTargets(target).toSet(), newVisible) } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionViewState.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionViewState.kt new file mode 100644 index 0000000..ec8bd36 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/SessionViewState.kt @@ -0,0 +1,141 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.firstEditableDrawableInPanelOrder + +/** + * How a document was being worked on, as opposed to what it is: the session state a saved document carries so a + * rigger reopens it where they left off (docs/format/UMA.md § 7.4). None of it is document content - nothing here + * mints a model, so none of it marks a document dirty - and the pose rides beside it as the session's initial pose. + * + * Plain data with no format knowledge: whoever reads the file builds one, and the session validates it against + * the model it opens on ([fittedTo]), since a saved id can name an object the file no longer has. + * + * @property Selection selection The object selection. + * @property ParameterSelection parameterSelection The parameters targeted for keyform authoring. + * @property EditorMode mode The interaction mode; Edit holds only when it can be entered. + * @property MeshSelectMode selectMode The mesh select mode, meaningful in Edit mode. + * @property Cursor2d? cursor2d The 2D cursor, or null when never placed. + * @property UvCursor? uvCursor The UV cursor, or null when never placed. + * @property TransformPivotMode pivotMode What a modal Scale or Rotate turns about. + * @property Boolean proportionalEnabled Whether proportional editing is on. + * @property ProportionalEditState? proportionalSettings The proportional falloff, radius, and connected flag - kept + * while proportional editing is off, since a toggle brings them back - or null for the defaults. + * @property GridConfig? gridConfig The document's own grid, or null to follow the application's. + */ +data class SessionViewState( + val selection: Selection = Selection(), + val parameterSelection: ParameterSelection = ParameterSelection(), + val mode: EditorMode = EditorMode.Object, + val selectMode: MeshSelectMode = MeshSelectMode.Vertex, + val cursor2d: Cursor2d? = null, + val uvCursor: UvCursor? = null, + val pivotMode: TransformPivotMode = TransformPivotMode.MedianPoint, + val proportionalEnabled: Boolean = false, + val proportionalSettings: ProportionalEditState? = null, + val gridConfig: GridConfig? = null, +) + +/** + * This state with every reference [model] cannot satisfy taken out: a selected target the model lacks is dropped, + * and an active that did not survive falls to one that did. A saved file can name an object deleted by another + * writer or by a hand edit, and a selection holding a ghost would hand every command a target that is not there. + * + * @param PuppetModel model The model the session opens on. + * @return SessionViewState The state that fits the model. + */ +internal fun SessionViewState.fittedTo(model: PuppetModel): SessionViewState { + val partIds = model.parts.mapTo(HashSet()) { part -> part.id } + val drawableIds = model.drawables.mapTo(HashSet()) { drawable -> drawable.id } + val deformerIds = model.deformers.mapTo(HashSet()) { deformer -> deformer.id } + val targets = + selection.targets.filterTo(LinkedHashSet()) { target -> + when (target) { + is SelectionTarget.Part -> target.id in partIds + is SelectionTarget.Drawable -> target.id in drawableIds + is SelectionTarget.Deformer -> target.id in deformerIds + } + } + val parameterIds = model.parameters.mapTo(HashSet()) { parameter -> parameter.id } + val targetedParameters = parameterSelection.ids.filterTo(LinkedHashSet()) { parameterId -> parameterId in parameterIds } + return copy( + selection = Selection(targets, selection.active?.takeIf { active -> active in targets } ?: targets.lastOrNull()), + parameterSelection = + ParameterSelection( + targetedParameters, + parameterSelection.active?.takeIf { active -> active in targetedParameters } ?: targetedParameters.lastOrNull(), + ), + ) +} + +/** + * The meshes an Edit-mode session opens on, and which of them is active. + * + * @property List drawableIds The session's meshes. + * @property DrawableId activeId The active mesh. + * @property Boolean activeSelected Whether [activeId] is the object selection's own active drawable, as opposed + * to a fallback the entry chose. + */ +internal class EditSeed( + val drawableIds: List, + val activeId: DrawableId, + val activeSelected: Boolean, +) + +/** + * What entering Edit mode opens on: every selected mesh-carrying drawable (multi-mesh edit, the object selection's + * active drawable becoming the active mesh), else the remembered drawable, else the topmost editable drawable in + * Parts-panel order - or null when the model has nothing editable, which refuses the entry. + * + * @param PuppetModel model The session's model. + * @param Selection selection The object selection. + * @param DrawableId? rememberedDrawableId The last drawable that was active, or null. + * @return EditSeed? The meshes to open on, or null when Edit mode cannot be entered. + */ +internal fun editSeedOf(model: PuppetModel, selection: Selection, rememberedDrawableId: DrawableId?): EditSeed? { + val selectedMeshedIds = + selection.targets + .filterIsInstance() + .map { target -> target.id } + .filter { candidateId -> model.drawables.any { drawable -> drawable.id == candidateId && drawable.mesh != null } } + val activeSelectedId = (selection.active as? SelectionTarget.Drawable)?.id?.takeIf { activeId -> activeId in selectedMeshedIds } + val remembered = rememberedDrawableId?.takeIf { candidateId -> model.drawables.any { drawable -> drawable.id == candidateId && drawable.mesh != null } } + val seedDrawableIds = + when { + selectedMeshedIds.isNotEmpty() -> selectedMeshedIds + remembered != null -> listOf(remembered) + else -> listOfNotNull(model.firstEditableDrawableInPanelOrder()) + } + if (seedDrawableIds.isEmpty()) { + return null + } + return EditSeed(seedDrawableIds, activeSelectedId ?: seedDrawableIds.first(), activeSelectedId != null) +} + +/** + * The snapshot a session opens on: the model and pose as given, with [viewState] fitted to the model laid in, so + * the state a document was saved with is where its history STARTS rather than a run of undo steps on top of it. + * + * A saved Edit mode holds only when it can be entered over the restored selection; when the model has nothing + * editable the session opens in Object mode, the same refusal [EditorSession.setMode] makes. + * + * @param PuppetModel model The document model at open. + * @param Pose pose The pose at open. + * @param SessionViewState? viewState The saved session state, already fitted, or null for a plain open. + * @return EditorSnapshot The session's first snapshot. + */ +internal fun openingSnapshotOf(model: PuppetModel, pose: Pose, viewState: SessionViewState?): EditorSnapshot { + if (viewState == null) { + return EditorSnapshot(model, Selection(), pose) + } + val editSeed = if (viewState.mode == EditorMode.Edit) editSeedOf(model, viewState.selection, rememberedDrawableId = null) else null + return EditorSnapshot( + model = model, + selection = viewState.selection, + pose = pose, + meshSelection = editSeed?.let { seed -> MeshSelection.editing(seed.drawableIds, seed.activeId).copy(selectMode = viewState.selectMode) } ?: MeshSelection(), + mode = if (editSeed != null) EditorMode.Edit else EditorMode.Object, + parameterSelection = viewState.parameterSelection, + ) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/StructureEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/StructureEdits.kt new file mode 100644 index 0000000..c177701 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/StructureEdits.kt @@ -0,0 +1,144 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.deformerSelfAndDescendants +import org.umamo.runtime.model.partSelfAndDescendants +import org.umamo.runtime.model.withDerivedRenderRoot + +/* + * Organizational-tree structure edits. The org tree (PuppetModel.rootChildren + Part.children - an ordered + * mix of sub-parts and drawables) is the single source of truth for the hierarchy AND the parts-panel + * order, and that order is the draw-order tiebreak. So one move - withOrgChildMoved - covers reparenting a + * part, re-homing a drawable, reordering siblings, and interleaving a drawable between parts; every move + * re-derives the render order from the tree. Deformer moves are separate (deformers live in the Armature, + * not the org tree). + * + * 組織ツリーの構造編集。ツリーが階層とパネル順の唯一の真実で、描画順のタイブレークでもある。移動は1つに統合。 + */ + +/** True when [child] is present somewhere in the org tree (the root level or some part's children). */ +private fun PuppetModel.containsOrgChild(child: OrgChild): Boolean = + child in rootChildren || parts.any { child in it.children } + +/** This child list with [child] inserted before [before] (or appended when [before] is null or absent). */ +private fun List.withChildInsertedBefore(child: OrgChild, before: OrgChild?): List { + val result = toMutableList() + val insertAt = before?.let { result.indexOf(it) }?.takeIf { it >= 0 } ?: result.size + result.add(insertAt, child) + return result +} + +/** + * Returns a copy of [this] with the org child [child] (a sub-part or a drawable) moved under [newParentId] + * (null = the top level) and positioned before [before] there (null / absent = appended). This is the one + * organizational move: a part reparent / reorder, a drawable re-home, and a cross-kind interleave (a + * drawable dropped between two parts) are the same edit. Because the parts-panel order is the draw-order + * tiebreak, the render order is re-derived. A move that would drop a part inside its own subtree (a cycle), + * or that changes nothing, returns the same instance. + * + * @param OrgChild child The sub-part or drawable to move. + * @param PartId? newParentId The destination part, or null for the top level. + * @param OrgChild? before The sibling to insert before, or null to append at the destination's end. + * @return PuppetModel The model with the child moved, or [this] if the move was a no-op or illegal. + */ +fun PuppetModel.withOrgChildMoved(child: OrgChild, newParentId: PartId?, before: OrgChild?): PuppetModel { + if (!containsOrgChild(child)) { + return this + } + // The subtree set contains the part itself, so this rejects self-parenting and any deeper cycle at once. + // The Properties picker filters its candidates against the same query, so an illegal target is not + // offered there rather than being silently refused here. + if (child is OrgChild.Part && newParentId != null && newParentId in partSelfAndDescendants(child.id)) { + return this + } + // Detach from wherever it currently sits (the root level and / or some part's children). + val detachedRoot = rootChildren.filter { it != child } + val detachedParts = parts.map { part -> if (child in part.children) part.copy(children = part.children - child) else part } + val newRoot: List + val newParts: List + if (newParentId == null) { + newRoot = detachedRoot.withChildInsertedBefore(child, before) + newParts = detachedParts + } else { + newRoot = detachedRoot + newParts = + detachedParts.map { part -> + if (part.id == newParentId) part.copy(children = part.children.withChildInsertedBefore(child, before)) else part + } + } + if (newRoot == rootChildren && newParts == parts) { + return this + } + return copy(rootChildren = newRoot, parts = newParts).withDerivedRenderRoot() +} + +/** + * Moves the org child [child] under [newParentId] (null = top level), before [before] (null = append), as + * one undo step. A cycle-forming or no-op move records nothing. + * + * @param OrgChild child The sub-part or drawable to move. + * @param PartId? newParentId The destination part, or null for the top level. + * @param OrgChild? before The sibling to insert before, or null to append. + */ +fun EditorSession.moveOrgChild(child: OrgChild, newParentId: PartId?, before: OrgChild?) { + val change: Change = + when (child) { + is OrgChild.Part -> PartChange.Move(child.id, newParentId, (before as? OrgChild.Part)?.id) + is OrgChild.Drawable -> DrawableChange.Move(child.id, newParentId) + } + mutate(change) { model -> model.withOrgChildMoved(child, newParentId, before) } +} + +/** A copy of this deformer re-homed under [newParent] in the transform (nesting) hierarchy. */ +private fun Deformer.withParent(newParent: DeformerId?): Deformer = + when (this) { + is Deformer.Warp -> copy(parent = newParent) + is Deformer.Rotation -> copy(parent = newParent) + } + +/** + * Returns a copy of [this] with the deformer [id] re-nested under [newParentId] (null = an armature root) + * and re-positioned among the deformers list before [beforeId] (null = appended). Reparent and reorder are + * one move: [Deformer.parent] sets the transform nesting, and the deformers list order sets sibling order + * in the armature. When the parent actually changes, the deformer's keyed geometry is converted from the + * old parent-local space into the new one so the lattice keeps its world pose (otherwise canvas CPs under + * a UV parent - or the reverse - send it flying). A move that would nest the deformer inside its own + * subtree (a cycle) or that does nothing returns the same instance. + * + * @param DeformerId id The deformer to move. + * @param DeformerId? newParentId The destination parent deformer, or null for an armature root. + * @param DeformerId? beforeId The sibling to insert before, or null to append. + * @return PuppetModel The model with the deformer moved, or [this] if the move was a no-op or illegal. + */ +fun PuppetModel.withDeformerMoved(id: DeformerId, newParentId: DeformerId?, beforeId: DeformerId?): PuppetModel { + val deformer = deformers.firstOrNull { it.id == id } ?: return this + // The subtree set contains id itself, so this rejects self-parenting and any deeper cycle at once. The + // Properties picker filters its candidates against the same query, so an illegal target is not offered + // there rather than being silently refused here. + if (newParentId != null && newParentId in deformerSelfAndDescendants(id)) { + return this + } + val converted = withDeformerGeometryConvertedForReparent(deformer, deformer.parent, newParentId) + val moved = converted.withParent(newParentId) + val without = deformers.filter { it.id != id }.toMutableList() + val insertAt = beforeId?.let { target -> without.indexOfFirst { it.id == target } }?.takeIf { it >= 0 } ?: without.size + without.add(insertAt, moved) + return copy(deformers = without) +} + +/** + * Moves the deformer [id] under [newParentId] (null = armature root), before [beforeId] (null = append), + * as one undo step. A cycle-forming or no-op move records nothing. + * + * @param DeformerId id The deformer to move. + * @param DeformerId? newParentId The destination parent deformer, or null for a root. + * @param DeformerId? beforeId The sibling to insert before, or null to append. + */ +fun EditorSession.moveDeformer(id: DeformerId, newParentId: DeformerId?, beforeId: DeformerId?) { + mutate(DeformerChange.Move(id, newParentId, beforeId)) { model -> model.withDeformerMoved(id, newParentId, beforeId) } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/ToolLatches.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/ToolLatches.kt new file mode 100644 index 0000000..f44407d --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/ToolLatches.kt @@ -0,0 +1,537 @@ +package org.umamo.edit + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.umamo.runtime.model.DrawableId + +/** + * The session's transient tool state: the modal operator latches, the armed select tool, the zoom + * region, the axis constraint, the viewport-gesture flag, the stroke-preview selection, the pie + * menu, the 2D cursor, the pivot mode, and proportional editing - everything that coordinates the + * viewport overlays without ever being snapshotted or entering the change bus. The + * mutual-exclusion story (a transform operator owns the pointer, so arming anything drops the + * others) lives in [clearTransient]; [EditorSession] keeps the mode / selection / pose guards and + * delegates the state itself here, exposing every flow unchanged. + * + * セッションの一時的なツール状態(モーダル演算子・選択ツール・ズーム領域・軸拘束・パイメニュー・ + * 2D カーソル・ピボット・プロポーショナル編集)。スナップショットには入らないオーバーレイ調整用。 + * 相互排他の規則は clearTransient に集約する。 + * + * @param Function notify Emits a transient user notice (the proportional toggles confirm through it). + */ +internal class ToolLatches(private val notify: (String, NoticePlacement) -> Unit) { + private val mutableActiveMeshOperator = MutableStateFlow(null) + + /** The modal mesh operator currently running, or null (see [EditorSession.activeMeshOperator]). */ + val activeMeshOperator: StateFlow = mutableActiveMeshOperator.asStateFlow() + + private val mutableActiveObjectOperator = MutableStateFlow(null) + + /** The modal object operator currently running, or null (see [EditorSession.activeObjectOperator]). */ + val activeObjectOperator: StateFlow = mutableActiveObjectOperator.asStateFlow() + + private val mutableActiveUvOperator = MutableStateFlow(null) + + /** The modal UV operator currently running, or null (see [EditorSession.activeUvOperator]). */ + val activeUvOperator: StateFlow = mutableActiveUvOperator.asStateFlow() + + private val mutableActiveSelectTool = MutableStateFlow(null) + + /** The armed Box / Circle / Add Vertex tool, or null (see [EditorSession.activeSelectTool]). */ + val activeSelectTool: StateFlow = mutableActiveSelectTool.asStateFlow() + + private val mutableZoomRegionArmedArea = MutableStateFlow(null) + + /** The area id whose Zoom Region gesture is armed, or null (see [EditorSession.zoomRegionArmedArea]). */ + val zoomRegionArmedArea: StateFlow = mutableZoomRegionArmedArea.asStateFlow() + + private val mutableAxisConstraint = MutableStateFlow(null) + + /** The axis the in-flight modal transform is locked to, or null (see [EditorSession.axisConstraint]). */ + val axisConstraint: StateFlow = mutableAxisConstraint.asStateFlow() + + private val mutableViewportGestureActive = MutableStateFlow(false) + + /** True while a non-armed viewport gesture is in flight (see [EditorSession.viewportGestureActive]). */ + val viewportGestureActive: StateFlow = mutableViewportGestureActive.asStateFlow() + + private val mutablePreviewSelection = MutableStateFlow?>(null) + + /** The transient circle-stroke preview selection, or null (see [EditorSession.previewSelection]). */ + val previewSelection: StateFlow?> = mutablePreviewSelection.asStateFlow() + + private val mutableActivePieMenu = MutableStateFlow(null) + + /** The radial pie menu currently open, or null (see [EditorSession.activePieMenu]). */ + val activePieMenu: StateFlow = mutableActivePieMenu.asStateFlow() + + private val mutablePendingParameterChoice = MutableStateFlow(null) + + /** The keyform edit waiting on an axis, or null (see [EditorSession.pendingParameterChoice]). */ + val pendingParameterChoice: StateFlow = mutablePendingParameterChoice.asStateFlow() + + private val mutableCursor2d = MutableStateFlow(null) + + /** The 2D cursor's world position, or null before any placement (see [EditorSession.cursor2d]). */ + val cursor2d: StateFlow = mutableCursor2d.asStateFlow() + + private val mutableUvCursor = MutableStateFlow(null) + + /** The UV editor's cursor in atlas coordinates, or null before any placement (see [EditorSession.uvCursor]). */ + val uvCursor: StateFlow = mutableUvCursor.asStateFlow() + + private val mutablePivotMode = MutableStateFlow(TransformPivotMode.MedianPoint) + + /** What a modal Scale / Rotate turns the selection about (see [EditorSession.pivotMode]). */ + val pivotMode: StateFlow = mutablePivotMode.asStateFlow() + + private val mutableGridConfig = MutableStateFlow(GridConfig()) + + /** The viewport grid geometry driving the backdrop and grid snap (see [EditorSession.gridConfig]). */ + val gridConfig: StateFlow = mutableGridConfig.asStateFlow() + + /** + * Sets the viewport grid geometry. + * + * @param GridConfig config The new grid scale and subdivisions. + */ + fun setGridConfig(config: GridConfig) { + mutableGridConfig.value = config + } + + private val mutableProportionalEdit = MutableStateFlow(null) + + /** Proportional editing, non-null while enabled (see [EditorSession.proportionalEdit]). */ + val proportionalEdit: StateFlow = mutableProportionalEdit.asStateFlow() + + // The configuration proportional editing re-enables with: the last falloff and radius survive an + // off/on toggle (the circle-select radius pattern), so O comes back the way it was left. + private var lastProportionalEdit = DEFAULT_PROPORTIONAL_EDIT_STATE + + /** + * The proportional falloff, radius, and connected flag as they would apply now: the live state while + * proportional editing is on, else the configuration a toggle would bring back. + */ + val proportionalSettings: ProportionalEditState + get() = mutableProportionalEdit.value ?: lastProportionalEdit + + // The Circle-select brush radius carried across re-entry (Blender remembers it). Deliberately NOT + // part of EditorSnapshot - re-arming the tool restores the last size. + private var lastCircleRadiusPx: Float = DEFAULT_CIRCLE_RADIUS_PX + + /** + * True while the active mesh operator was latched with proportional editing suppressed - the + * duplicate / rip auto-grabs, which place fresh copies and must never drag bystander vertices. + * Reset whenever the operator latches or clears. + */ + var activeMeshOperatorSuppressesProportional: Boolean = false + private set + + /** + * Clears the mutually-exclusive transient tool latches - the modal mesh / object / UV operators and + * the armed select tool - plus the optional extras the caller names. Every site that latches a tool, + * switches mode, or restores a snapshot funnels through here so the mutual-exclusion story lives in + * one place; a caller about to latch one of the four simply overwrites its own slot right after. + * + * @param Boolean clearZoomRegion True to also disarm the zoom region (the tool-latch sites; a mode + * switch or restore leaves it armed - the gesture is mode-agnostic). + * @param Boolean clearAxisConstraint True to also drop the axis lock (the operator begins and + * restore; an axis lock is meaningless without a live operator). + * @param Boolean clearViewportGesture True to also end the viewport-gesture flag (mode switches and + * restore, which tear down any in-flight gesture). + */ + fun clearTransient( + clearZoomRegion: Boolean = false, + clearAxisConstraint: Boolean = false, + clearViewportGesture: Boolean = false, + ) { + mutableActiveMeshOperator.value = null + mutableActiveObjectOperator.value = null + mutableActiveUvOperator.value = null + mutableActiveSelectTool.value = null + if (clearZoomRegion) { + mutableZoomRegionArmedArea.value = null + } + if (clearAxisConstraint) { + mutableAxisConstraint.value = null + } + if (clearViewportGesture) { + mutableViewportGestureActive.value = false + } + } + + /** + * Latches a modal mesh operator (the caller has already checked the Edit-mode preconditions). + * Drops any armed select tool / zoom region first (mutual exclusion), and publishes the + * suppression BEFORE the operator itself: the overlay's latch effect keys on the operator flow and + * must read a consistent flag when it fires. + * + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param String areaId The initiating viewport's area id (only its overlay drives the gesture). + * @param Boolean suppressProportional True to ignore proportional editing for this gesture. + */ + fun latchMeshOperator(kind: MeshOperatorKind, areaId: String, suppressProportional: Boolean) { + clearTransient(clearZoomRegion = true, clearAxisConstraint = true) + activeMeshOperatorSuppressesProportional = suppressProportional + mutableActiveMeshOperator.value = ActiveOperator(kind, areaId) + } + + /** Clears the active modal mesh operator (confirm or cancel), dropping the axis lock with it. */ + fun clearMeshOperator() { + mutableActiveMeshOperator.value = null + mutableAxisConstraint.value = null + activeMeshOperatorSuppressesProportional = false + } + + /** + * Latches a modal object operator (the caller has already checked the Object-mode preconditions), + * dropping any other latched tool first (mutual exclusion). + * + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param String areaId The initiating viewport's area id (only its overlay drives the gesture). + */ + fun latchObjectOperator(kind: MeshOperatorKind, areaId: String) { + clearTransient(clearZoomRegion = true, clearAxisConstraint = true) + mutableActiveObjectOperator.value = ActiveOperator(kind, areaId) + } + + /** Clears the active modal object operator (confirm or cancel), dropping the axis lock with it. */ + fun clearObjectOperator() { + mutableActiveObjectOperator.value = null + mutableAxisConstraint.value = null + } + + /** + * Latches a modal UV operator (the caller has already checked the Edit-mode and UV-validity + * preconditions), dropping any other latched tool first (mutual exclusion). + * + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param String areaId The initiating UV editor's area id (only its overlay drives the gesture). + */ + fun latchUvOperator(kind: MeshOperatorKind, areaId: String) { + clearTransient(clearZoomRegion = true, clearAxisConstraint = true) + mutableActiveUvOperator.value = ActiveOperator(kind, areaId) + } + + /** Clears the active modal UV operator (confirm or cancel), dropping the axis lock with it. */ + fun clearUvOperator() { + mutableActiveUvOperator.value = null + mutableAxisConstraint.value = null + } + + /** + * The one modal transform operator currently running, whichever family latched it, or null. + * + * Safe to collapse the three into one answer because [clearTransient] runs at every latch site, so at + * most one is ever non-null. A plain getter rather than a combined StateFlow: the callers that want + * "is any transform running" read it at an instant (the shell's key ladder) and never observe it, so a + * combine would advertise a reactivity nobody consumes. + */ + val activeOperator: ActiveOperator? + get() = activeMeshOperator.value ?: activeObjectOperator.value ?: activeUvOperator.value + + /** + * Clears whichever operator family is running, if any. + * + * Dispatches to that family's own clear rather than blanking all three: only [clearMeshOperator] + * resets the proportional-suppression flag, so a three-way blank would quietly change the duplicate + * and rip auto-grab behavior. + */ + fun clearActiveOperator() { + when { + mutableActiveMeshOperator.value != null -> clearMeshOperator() + mutableActiveObjectOperator.value != null -> clearObjectOperator() + mutableActiveUvOperator.value != null -> clearUvOperator() + } + } + + /** + * Arms the Box-select tool (the caller has already checked the mode preconditions). + * + * @param String areaId The arming viewport's area id (only its overlay drives the drag). + */ + fun armBoxSelect(areaId: String) { + clearTransient(clearZoomRegion = true) + mutableActiveSelectTool.value = ActiveSelectTool.BoxArmed(areaId) + } + + /** + * Arms the Circle-select tool at the remembered radius (preconditions checked by the caller). + * + * @param String areaId The arming viewport's area id (only its overlay drives the brush). + */ + fun armCircleSelect(areaId: String) { + clearTransient(clearZoomRegion = true) + mutableActiveSelectTool.value = ActiveSelectTool.Circle(lastCircleRadiusPx, areaId) + } + + /** + * Sets the Circle-select brush radius (clamped), remembering it for the next arm. When a Circle + * tool is live its radius updates in place so the overlay redraws; otherwise only the remembered + * value moves. + * + * @param Float radiusPx The requested radius in viewport pixels. + */ + fun setCircleRadius(radiusPx: Float) { + val clamped = radiusPx.coerceIn(MIN_CIRCLE_RADIUS_PX, MAX_CIRCLE_RADIUS_PX) + lastCircleRadiusPx = clamped + val current = mutableActiveSelectTool.value + if (current is ActiveSelectTool.Circle) { + // A resize keeps the brush in its arming area - only re-arming moves the tool. + mutableActiveSelectTool.value = ActiveSelectTool.Circle(clamped, current.areaId) + } + } + + /** Grows the Circle-select radius by one step; a no-op unless a Circle tool is live. */ + fun growCircleRadius() { + val current = mutableActiveSelectTool.value + if (current is ActiveSelectTool.Circle) { + setCircleRadius(current.radiusPx + CIRCLE_RADIUS_STEP_PX) + } + } + + /** Shrinks the Circle-select radius by one step; a no-op unless a Circle tool is live. */ + fun shrinkCircleRadius() { + val current = mutableActiveSelectTool.value + if (current is ActiveSelectTool.Circle) { + setCircleRadius(current.radiusPx - CIRCLE_RADIUS_STEP_PX) + } + } + + /** + * Arms the Add Vertex draft tool on [drawableId]. Preconditions checked by the caller. + * + * @param String areaId The arming viewport's area id (only its overlay drives the clicks). + * @param DrawableId drawableId The session mesh the draft targets. + */ + fun armAddVertex(areaId: String, drawableId: DrawableId) { + clearTransient(clearZoomRegion = true) + mutableActiveSelectTool.value = ActiveSelectTool.AddVertex(areaId = areaId, drawableId = drawableId) + } + + /** + * Replaces the live Add Vertex draft in place. A no-op unless Add Vertex is armed. + * + * @param ActiveSelectTool.AddVertex draft The updated draft (same area / drawable). + */ + fun setAddVertexDraft(draft: ActiveSelectTool.AddVertex) { + val current = mutableActiveSelectTool.value + if (current is ActiveSelectTool.AddVertex && current.areaId == draft.areaId && current.drawableId == draft.drawableId) { + mutableActiveSelectTool.value = draft + } + } + + /** Clears any armed Box / Circle / Add Vertex tool. */ + fun clearSelectTool() { + mutableActiveSelectTool.value = null + } + + /** + * Arms the Zoom Region gesture for [areaId], clearing any latched tool so two overlays never + * capture at once. + * + * @param String areaId The viewport area the gesture will run in. + */ + fun armZoomRegion(areaId: String) { + clearTransient() + mutableZoomRegionArmedArea.value = areaId + } + + /** Disarms the Zoom Region gesture. */ + fun disarmZoomRegion() { + mutableZoomRegionArmedArea.value = null + } + + /** + * Toggles the modal axis constraint (pressing a lock's own key again releases it; pressing the + * other axis switches). A no-op unless a Grab or Scale operator is in flight - Rotate has no axis + * to lock and idle keys must not arm a stale constraint. + * + * @param TransformAxisConstraint axis The axis whose lock to toggle. + */ + fun toggleAxisConstraint(axis: TransformAxisConstraint) { + val operator = mutableActiveMeshOperator.value ?: mutableActiveObjectOperator.value ?: mutableActiveUvOperator.value ?: return + if (operator.kind == MeshOperatorKind.Rotate) { + return + } + mutableAxisConstraint.value = if (mutableAxisConstraint.value == axis) null else axis + } + + /** + * Publishes whether a non-armed viewport gesture is in flight. + * + * @param Boolean active True while the overlay's gesture owns the pointer. + */ + fun setViewportGestureActive(active: Boolean) { + mutableViewportGestureActive.value = active + } + + /** + * Publishes the transient circle-stroke preview selection; pass null to clear it. + * + * @param Set? drawableIds The drawables currently painted by the stroke, or null. + */ + fun setPreviewSelection(drawableIds: Set?) { + mutablePreviewSelection.value = drawableIds + } + + /** + * Opens a pie menu over the viewport. + * + * @param PieMenuKind kind The pie to open. + */ + fun openPieMenu(kind: PieMenuKind) { + mutableActivePieMenu.value = kind + } + + /** Closes the open pie menu. */ + fun closePieMenu() { + mutableActivePieMenu.value = null + } + + /** + * Parks a keyform edit until the user picks the axis it writes on. + * + * @param ParameterChoiceRequest request The parked edit and the axes to choose between. + */ + fun openParameterChoice(request: ParameterChoiceRequest) { + mutablePendingParameterChoice.value = request + } + + /** Discards the parked keyform edit (an axis was picked, or the prompt was dismissed). */ + fun closeParameterChoice() { + mutablePendingParameterChoice.value = null + } + + /** + * Places (or moves) the 2D cursor. + * + * @param Float worldX The cursor's new world-space x. + * @param Float worldZ The cursor's new world-space z (up). + */ + fun setCursor2d(worldX: Float, worldZ: Float) { + mutableCursor2d.value = Cursor2d(worldX, worldZ) + } + + /** + * Places (or moves) the UV editor's cursor. + * + * @param Float u The cursor's new normalized atlas u coordinate. + * @param Float v The cursor's new normalized atlas v coordinate. + */ + fun setUvCursor(u: Float, v: Float) { + mutableUvCursor.value = UvCursor(u, v) + } + + /** + * Selects the transform pivot mode. + * + * @param TransformPivotMode mode The pivot mode the next transforms anchor on. + */ + fun setPivotMode(mode: TransformPivotMode) { + mutablePivotMode.value = mode + } + + /** + * Toggles proportional editing on or off (Blender's O), restoring the last falloff and radius on + * re-enable and confirming either way with a near-cursor notice (an idle toggle has no other + * visible effect - the influence circle only shows during a modal transform). + */ + fun toggleProportionalEdit() { + val current = mutableProportionalEdit.value + if (current != null) { + lastProportionalEdit = current + mutableProportionalEdit.value = null + notify("notice.proportional.off", NoticePlacement.NearCursor) + } else { + mutableProportionalEdit.value = lastProportionalEdit + notify("notice.proportional.on", NoticePlacement.NearCursor) + } + } + + /** + * Toggles Connected Only for proportional editing (influence measured along mesh edges instead of + * straight-line, so the halo never leaps to unconnected geometry), enabling proportional editing + * if it was off - and then connected mode turns ON regardless of the remembered flag, since the + * command expresses the intent to use it. Confirms either way with a near-cursor notice. + */ + fun toggleProportionalConnected() { + val current = mutableProportionalEdit.value + val updated = + if (current == null) { + lastProportionalEdit.copy(connectedOnly = true) + } else { + current.copy(connectedOnly = !current.connectedOnly) + } + lastProportionalEdit = updated + mutableProportionalEdit.value = updated + notify( + if (updated.connectedOnly) "notice.proportional.connected.on" else "notice.proportional.connected.off", + NoticePlacement.NearCursor, + ) + } + + /** + * Selects the proportional falloff curve, enabling proportional editing if it was off - picking a + * falloff from the palette or header expresses the intent to use it, and silently updating a + * disabled state would look like the command did nothing. + * + * @param ProportionalFalloff falloff The falloff curve the influence weights follow. + */ + fun setProportionalFalloff(falloff: ProportionalFalloff) { + val updated = (mutableProportionalEdit.value ?: lastProportionalEdit).copy(falloff = falloff) + lastProportionalEdit = updated + mutableProportionalEdit.value = updated + } + + /** + * Sets the proportional influence radius, clamped to the allowed range. A no-op while proportional + * editing is off (the radius only changes from the mid-gesture scroll, which requires it on). + * + * @param Float radiusWorld The influence radius in world units (canvas px). + */ + fun setProportionalRadius(radiusWorld: Float) { + val current = mutableProportionalEdit.value ?: return + val updated = current.copy(radiusWorld = radiusWorld.coerceIn(MIN_PROPORTIONAL_RADIUS_WORLD, MAX_PROPORTIONAL_RADIUS_WORLD)) + lastProportionalEdit = updated + mutableProportionalEdit.value = updated + } + + /** + * Sets proportional editing outright - on with [state] (its radius clamped), or off with null - + * silently, and remembering the configuration a later toggle restores. The operation settings + * strip's write-back: the proportional rows of an adjusted transform become the state the next + * gesture starts from, and the strip's rows are their own confirmation, so no notice fires. + * + * @param ProportionalEditState? state The state to set, or null to turn proportional editing off. + */ + fun setProportionalEdit(state: ProportionalEditState?) { + if (state == null) { + mutableProportionalEdit.value?.let { current -> lastProportionalEdit = current } + mutableProportionalEdit.value = null + return + } + val clamped = state.copy(radiusWorld = state.radiusWorld.coerceIn(MIN_PROPORTIONAL_RADIUS_WORLD, MAX_PROPORTIONAL_RADIUS_WORLD)) + lastProportionalEdit = clamped + mutableProportionalEdit.value = clamped + } + + /** + * Lays a saved session's tool state in, silently: the cursors, the pivot mode, proportional editing with the + * configuration it would re-enable with, and the document's own grid when it saved one. Called once, as the + * session is built, so nothing here is a gesture and nothing here posts a notice. + * + * @param SessionViewState viewState The saved state, already fitted to the model. + */ + fun seed(viewState: SessionViewState) { + mutableCursor2d.value = viewState.cursor2d + mutableUvCursor.value = viewState.uvCursor + mutablePivotMode.value = viewState.pivotMode + viewState.proportionalSettings?.let { settings -> + lastProportionalEdit = settings.copy(radiusWorld = settings.radiusWorld.coerceIn(MIN_PROPORTIONAL_RADIUS_WORLD, MAX_PROPORTIONAL_RADIUS_WORLD)) + } + mutableProportionalEdit.value = lastProportionalEdit.takeIf { viewState.proportionalEnabled } + viewState.gridConfig?.let { config -> mutableGridConfig.value = config } + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/TrackKeyRef.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/TrackKeyRef.kt new file mode 100644 index 0000000..52fbdad --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/TrackKeyRef.kt @@ -0,0 +1,23 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ParameterId + +/** + * One selected keyform key: the parameter section, the row, and WHICH key on that row. + * + * By ordinal rather than by parameter value. Two keys a hair apart are legal and useful, and resolving a + * value back to a key would then pick whichever happens to be nearer - dragging one of a pair of + * near-coincident marks would silently move the other instead. The parameter is part of the identity + * because a linked pair renders two sections at once and one item's row key is the same string in both. + * + * [rowKey] is an opaque string to this module, and deliberately so. It is the keyform sheet's row identity, + * built from the OWNER plus what the row edits (a channel, the geometry, a blend binding) - model identity + * throughout, so it survives every edit that does not delete the thing it names. Resolving it back to a + * track is the sheet's job because only the sheet knows which rows it is currently projecting; a session + * that tried to would have to duplicate that projection to answer. + * + * @property ParameterId parameterId The parameter whose section the key sits in. + * @property String rowKey The owning row's stable key. + * @property Int keyIndex The key's ordinal on that row's track. + */ +data class TrackKeyRef(val parameterId: ParameterId, val rowKey: String, val keyIndex: Int) \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/TransformAdjust.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/TransformAdjust.kt new file mode 100644 index 0000000..a2392f7 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/TransformAdjust.kt @@ -0,0 +1,350 @@ +package org.umamo.edit + +import kotlin.math.PI + +/* + * The modal transforms' face on the operation settings strip - the half that knows no geometry: the + * numbers a Grab / Rotate / Scale (or a Vertex Slide) landed with as the strip's typed rows, the + * parameters those rows mean, and the proportional rows' state. The registrations that replay a + * frozen capture through the viewport's world geometry or the UV editor's frame live in :ui + * (viewport/TransformAdjustRegistration.kt) and cannot be here: :edit and :render are siblings over + * :runtime, and the world-to-base inverse needs :render's evaluator. + * + * There is no axis-constraint row, for the reason the placement gesture has none: a lock only zeroes + * one Grab component or pins one Scale factor at 1, so the per-component rows already say it. + */ + +/** + * The numbers one modal transform applies, in the positions' units: a Grab's translation, a Scale's + * factors, a Rotate's angle, the rest at identity. During a drag the UI resolves one from each pointer + * frame; after the commit the operation settings strip shows it as rows and builds one back from them, + * so the same transform runs from a pointer or a typed value. + * + * @property Float deltaX The Grab translation's x (identity 0 for the other operators). + * @property Float deltaY The Grab translation's y, in the positions' sense (y up for world space). + * @property Float factorX The Scale factor along x (identity 1 for the other operators). + * @property Float factorY The Scale factor along y. + * @property Float rotationRadians The Rotate angle in the positions' sense (identity 0 for the others). + */ +class TransformGestureParameters( + val deltaX: Float, + val deltaY: Float, + val factorX: Float, + val factorY: Float, + val rotationRadians: Float, +) { + companion object { + /** The parameters that move nothing. */ + val IDENTITY = TransformGestureParameters(0f, 0f, 1f, 1f, 0f) + } +} + +/** The parameter keys the transform gestures' rows carry (the strip maps them to labels). */ +object TransformParameterKeys { + const val MOVE_X = "transform.moveX" + const val MOVE_Y = "transform.moveY" + const val MOVE_Z = "transform.moveZ" + const val ANGLE = "transform.angle" + const val SCALE_X = "transform.scaleX" + const val SCALE_Y = "transform.scaleY" + const val SCALE_Z = "transform.scaleZ" + const val PROPORTIONAL = "transform.proportional" + const val FALLOFF = "transform.falloff" + const val PROPORTIONAL_SIZE = "transform.proportionalSize" + const val CONNECTED_ONLY = "transform.connectedOnly" + const val SLIDE_FACTOR = "transform.slideFactor" + + /** The label-key prefix of the Falloff row's choices; the curve's [ProportionalFalloff.choiceKey] follows it. */ + const val FALLOFF_CHOICE_PREFIX = "transform.falloff." +} + +/** The widest angle an Angle row accepts, in degrees either way. */ +const val TRANSFORM_ANGLE_LIMIT = 360f + +/** The smallest factor a Scale row accepts - a zero scale would collapse the geometry. */ +const val TRANSFORM_SCALE_MIN = 0.01f + +/** The largest factor a Scale row accepts. */ +const val TRANSFORM_SCALE_MAX = 100f + +/** The Scale rows' scrub step. */ +const val TRANSFORM_SCALE_STEP = 0.01f + +/** The farthest a Move row reaches either way, in the gesture space's units (world px or texels). */ +private const val TRANSFORM_MOVE_LIMIT = 100_000f + +/** The Proportional Size row's scrub step, in the gesture space's units. */ +private const val PROPORTIONAL_SIZE_STEP = 1f + +/** The Vertex Slide Factor row's scrub step. */ +private const val SLIDE_FACTOR_STEP = 0.01f + +/** + * The space a transform's rows read in - which decides the axis labels and the sign conventions. + */ +enum class TransformRowSpace { + /** + * World units in a 2D viewport: y up, shown as the Z axis (the project presents the 2D plane as X + * and Z per the Y+ forward, Z+ up convention, and the axis-lock badge says "along Z"). + */ + World, + + /** + * Display texels in the UV editor: the vertical row reads y DOWN, as the page and the placement + * strip's rows do, and the angle's sign flips with it (the flip mirrors a rotation's sense). + */ + UvDisplay, +} + +/** + * The proportional-editing rows' values: whether it applied, the curve, the radius in the gesture + * space's units, and Connected Only. Built from the session state at confirm and read back from the + * rows at each adjustment. + * + * @property Boolean enabled Whether the halo applies. + * @property ProportionalFalloff falloff The falloff curve. + * @property Float radius The influence radius, in the gesture space's units. + * @property Boolean connectedOnly Whether influence spreads only along mesh edges. + */ +class ProportionalRows( + val enabled: Boolean, + val falloff: ProportionalFalloff, + val radius: Float, + val connectedOnly: Boolean, +) { + /** + * The state the rows describe, or null while the flag is off - what the capture's halos re-derive + * from. The state's radius is [radius] in the gesture space's units; a caller writing it back to the + * session's WORLD radius from another space substitutes its own. + * + * @return ProportionalEditState? The state, or null. + */ + fun asState(): ProportionalEditState? = if (enabled) ProportionalEditState(falloff, radius, connectedOnly) else null + + companion object { + /** + * The rows for the session's live state at confirm, with [radius] the radius the gesture actually + * used (the session's world radius in the viewport, the editor's texel radius in the UV editor) + * and the defaults standing in for the curve and the flag while the state is off. + * + * @param ProportionalEditState? state The session's proportional state, or null while off. + * @param Float radius The radius the gesture ran with, in the gesture space's units. + * @return ProportionalRows The rows. + */ + fun of(state: ProportionalEditState?, radius: Float): ProportionalRows = + ProportionalRows( + enabled = state != null, + falloff = state?.falloff ?: ProportionalFalloff.Smooth, + radius = radius, + connectedOnly = state?.connectedOnly ?: false, + ) + } +} + +/** + * The strip's rows for a Grab / Rotate / Scale that landed with [parameters]: the move's two + * components, the angle in degrees, or the two factors, followed by the proportional rows when the + * gesture could take weights. A Vertex Slide has no rows here (see [slideParameters]). + * + * @param MeshOperatorKind kind The operator that ran. + * @param TransformGestureParameters parameters The numbers it landed with, in the gesture space's units. + * @param TransformRowSpace space The space the rows read in. + * @param ProportionalRows? proportional The proportional rows, or null when the gesture took no + * weights (Object mode, a suppressed auto-grab). + * @return List The rows, empty for an operator that has none. + */ +fun transformParameters( + kind: MeshOperatorKind, + parameters: TransformGestureParameters, + space: TransformRowSpace, + proportional: ProportionalRows?, +): List { + val rows = ArrayList() + when (kind) { + MeshOperatorKind.Grab -> { + rows.add(moveRow(TransformParameterKeys.MOVE_X, parameters.deltaX)) + rows.add(moveRow(space.verticalMoveKey, space.rowVertical(parameters.deltaY))) + } + + MeshOperatorKind.Rotate -> + rows.add( + OperatorParameter.FloatParameter( + TransformParameterKeys.ANGLE, + TransformParameterKeys.ANGLE, + space.rowDegrees(parameters.rotationRadians), + -TRANSFORM_ANGLE_LIMIT, + TRANSFORM_ANGLE_LIMIT, + unit = ParameterUnit.Degrees, + ), + ) + + MeshOperatorKind.Scale -> { + rows.add(scaleRow(TransformParameterKeys.SCALE_X, parameters.factorX)) + rows.add(scaleRow(space.verticalScaleKey, parameters.factorY)) + } + + MeshOperatorKind.VertexSlide -> return emptyList() + } + if (proportional != null) { + rows.addAll(proportionalParameters(proportional)) + } + return rows +} + +/** + * The gesture parameters the strip's rows mean - the inverse of [transformParameters], back into the + * gesture space's form the operator math takes. A missing row reads as identity, so the rows of one + * operator never move another. + * + * @param MeshOperatorKind kind The operator the rows belong to. + * @param TransformRowSpace space The space the rows read in. + * @param List parameters The rows, possibly edited. + * @return TransformGestureParameters The parameters to apply. + */ +fun transformGestureParametersOf( + kind: MeshOperatorKind, + space: TransformRowSpace, + parameters: List, +): TransformGestureParameters = + when (kind) { + MeshOperatorKind.Grab -> + TransformGestureParameters( + deltaX = parameters.floatValue(TransformParameterKeys.MOVE_X, 0f), + deltaY = space.rowVertical(parameters.floatValue(space.verticalMoveKey, 0f)), + factorX = 1f, + factorY = 1f, + rotationRadians = 0f, + ) + + MeshOperatorKind.Rotate -> + TransformGestureParameters( + deltaX = 0f, + deltaY = 0f, + factorX = 1f, + factorY = 1f, + rotationRadians = space.radiansOfRow(parameters.floatValue(TransformParameterKeys.ANGLE, 0f)), + ) + + MeshOperatorKind.Scale -> + TransformGestureParameters( + deltaX = 0f, + deltaY = 0f, + factorX = parameters.floatValue(TransformParameterKeys.SCALE_X, 1f), + factorY = parameters.floatValue(space.verticalScaleKey, 1f), + rotationRadians = 0f, + ) + + MeshOperatorKind.VertexSlide -> TransformGestureParameters.IDENTITY + } + +/** + * The proportional rows the strip's rows carry, or null when the gesture registered none. + * + * @param List parameters The rows, possibly edited. + * @return ProportionalRows? The rows' values, or null. + */ +fun proportionalRowsOf(parameters: List): ProportionalRows? { + if (parameters.none { parameter -> parameter.key == TransformParameterKeys.PROPORTIONAL }) { + return null + } + val falloffKey = parameters.choiceValue(TransformParameterKeys.FALLOFF, ProportionalFalloff.Smooth.choiceKey) + return ProportionalRows( + enabled = parameters.booleanValue(TransformParameterKeys.PROPORTIONAL, false), + falloff = ProportionalFalloff.entries.firstOrNull { falloff -> falloff.choiceKey == falloffKey } ?: ProportionalFalloff.Smooth, + radius = parameters.floatValue(TransformParameterKeys.PROPORTIONAL_SIZE, MIN_PROPORTIONAL_RADIUS_WORLD), + connectedOnly = parameters.booleanValue(TransformParameterKeys.CONNECTED_ONLY, false), + ) +} + +/** + * Re-derives [transform]'s proportional halos from its frozen positions under the rows' proportional + * settings, when the rows carry any: the entries' influence and moved sets change with the radius, + * curve, and flag. For a rerun over a RETAINED capture, which is no longer live, so rewriting its + * halos is safe. + * + * @param ModalTransformCapture transform The frozen capture. + * @param List parameters The rows, possibly edited. + * @return ProportionalRows? The rows the halos were derived under, or null when the rows carry none + * (the capture is left as it was). + */ +fun rederiveProportionalHalos(transform: ModalTransformCapture, parameters: List): ProportionalRows? { + val rows = proportionalRowsOf(parameters) ?: return null + val state = rows.asState() + transform.applyProportional(state, state?.radiusWorld ?: 0f) + return rows +} + +/** + * The strip's one row for a Vertex Slide: how far along its edge the vertex landed. + * + * @param Float factor The landed factor in [0, 1]. + * @return List The Factor row. + */ +fun slideParameters(factor: Float): List = + listOf(OperatorParameter.FloatParameter(TransformParameterKeys.SLIDE_FACTOR, TransformParameterKeys.SLIDE_FACTOR, factor, 0f, 1f, SLIDE_FACTOR_STEP)) + +/** The stable choice key of a falloff curve, as the Falloff row stores it. */ +val ProportionalFalloff.choiceKey: String + get() = name.lowercase() + +/** The proportional rows: the flag, the curve, the size, and Connected Only. */ +private fun proportionalParameters(proportional: ProportionalRows): List = + listOf( + OperatorParameter.BooleanParameter(TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.PROPORTIONAL, proportional.enabled), + OperatorParameter.ChoiceParameter( + TransformParameterKeys.FALLOFF, + TransformParameterKeys.FALLOFF, + proportional.falloff.choiceKey, + ProportionalFalloff.entries.map { falloff -> ParameterChoice(falloff.choiceKey, TransformParameterKeys.FALLOFF_CHOICE_PREFIX + falloff.choiceKey) }, + ), + OperatorParameter.FloatParameter( + TransformParameterKeys.PROPORTIONAL_SIZE, + TransformParameterKeys.PROPORTIONAL_SIZE, + proportional.radius, + MIN_PROPORTIONAL_RADIUS_WORLD, + MAX_PROPORTIONAL_RADIUS_WORLD, + PROPORTIONAL_SIZE_STEP, + ParameterUnit.Pixels, + ), + OperatorParameter.BooleanParameter(TransformParameterKeys.CONNECTED_ONLY, TransformParameterKeys.CONNECTED_ONLY, proportional.connectedOnly), + ) + +/** A Move row in the gesture space's pixel units. */ +private fun moveRow(key: String, value: Float): OperatorParameter = + OperatorParameter.FloatParameter(key, key, value, -TRANSFORM_MOVE_LIMIT, TRANSFORM_MOVE_LIMIT, unit = ParameterUnit.Pixels) + +/** A Scale row. */ +private fun scaleRow(key: String, value: Float): OperatorParameter = + OperatorParameter.FloatParameter(key, key, value, TRANSFORM_SCALE_MIN, TRANSFORM_SCALE_MAX, TRANSFORM_SCALE_STEP) + +/** The key of the vertical Move row: Z in world space, Y on the page. */ +private val TransformRowSpace.verticalMoveKey: String + get() = + when (this) { + TransformRowSpace.World -> TransformParameterKeys.MOVE_Z + TransformRowSpace.UvDisplay -> TransformParameterKeys.MOVE_Y + } + +/** The key of the vertical Scale row: Z in world space, Y on the page. */ +private val TransformRowSpace.verticalScaleKey: String + get() = + when (this) { + TransformRowSpace.World -> TransformParameterKeys.SCALE_Z + TransformRowSpace.UvDisplay -> TransformParameterKeys.SCALE_Y + } + +/** + * The vertical component as the row reads it - and, being its own inverse, as the gesture reads a + * row: world y is up and shown as-is; display y is flipped to read down like the page. + */ +private fun TransformRowSpace.rowVertical(value: Float): Float = + when (this) { + TransformRowSpace.World -> value + TransformRowSpace.UvDisplay -> -value + } + +/** The angle row for a gesture rotation: degrees, with the page space's sign flip. */ +private fun TransformRowSpace.rowDegrees(rotationRadians: Float): Float = rowVertical((rotationRadians * 180.0 / PI).toFloat()) + +/** The gesture rotation an angle row means: the inverse of [rowDegrees]. */ +private fun TransformRowSpace.radiansOfRow(degrees: Float): Float = (rowVertical(degrees) * PI / 180.0).toFloat() \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/TransformState.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/TransformState.kt new file mode 100644 index 0000000..7183b6f --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/TransformState.kt @@ -0,0 +1,325 @@ +package org.umamo.edit + +import org.umamo.runtime.model.PuppetModel +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.round +import kotlin.math.sin + +/** + * The default major grid spacing in world units (canvas px): the built-in fallback value for + * [GridConfig.scale] when neither a settings default (settings key viewport.grid.scale) nor a per-file + * value has been resolved. The grid snaps round to the finest subdivision, not to this spacing + * directly - see [GridConfig.snapStep]. + */ +const val SNAP_GRID_WORLD_UNITS = 100f + +/** + * The default number of minor subdivisions per major grid cell: the built-in fallback for + * [GridConfig.subdivisions] (settings key viewport.grid.subdivisions). + */ +const val DEFAULT_GRID_SUBDIVISIONS = 10 + +/** + * The viewport grid's geometry: the major line spacing in world units and how many minor + * (subdivision) lines divide each major cell. Drives both the drawn backdrop grid and the grid snap. + * Held per document: seeded from the global-default settings, or from the document's own value when a `.uma` + * saved one (docs/format/UMA.md § 7.4); CMO3 and MOC3 store no grid and keep the default. + * + * @property Float scale The major grid line spacing, in world units. + * @property Int subdivisions The minor lines per major cell (must be at least 1). + */ +data class GridConfig( + val scale: Float = SNAP_GRID_WORLD_UNITS, + val subdivisions: Int = DEFAULT_GRID_SUBDIVISIONS, +) { + /** + * The grid snap increment in world units: the finest visible spacing (major / subdivisions), so + * Selection- and Cursor-to-Grid round to the minor grid lines the backdrop draws. Subdivisions is + * clamped to at least 1 so the step is always a positive, finite value. + */ + val snapStep: Float + get() = scale / subdivisions.coerceAtLeast(1) +} + +/** + * Rounds a world coordinate to the nearest grid line, measured from [origin] (the world origin the grid + * is drawn around) rather than from world 0, so a snap lands on the same lines the backdrop grid draws. + * + * @param Float value The world coordinate to snap. + * @param Float origin The world origin the grid lattice is anchored on (a line passes through it). + * @param Float step The grid snap increment (see [GridConfig.snapStep]). + * @return Float The snapped world coordinate. + */ +fun snapToGrid(value: Float, origin: Float, step: Float): Float = round((value - origin) / step) * step + origin + +/** + * Rounds a world point to the nearest intersection of the model's world grid - the lattice the backdrop + * draws, anchored on the world origin. Both axes in one call, so a caller cannot anchor x on the origin's + * z or the reverse. + * + * @param Float worldX The world x to snap. + * @param Float worldZ The world z (up) to snap. + * @param Float step The grid snap increment (see [GridConfig.snapStep]). + * @return Pair The snapped world (x, z). + */ +fun PuppetModel.snapToWorldGrid(worldX: Float, worldZ: Float, step: Float): Pair = + snapToGrid(worldX, worldOriginX, step) to snapToGrid(worldZ, worldOriginZ, step) + +/** + * The 2D cursor: a placeable world-space anchor, the 2D analog of Blender's 3D cursor. Placed with + * Shift+RightClick in the viewport, drawn by the HUD overlay, usable as a transform pivot + * ([TransformPivotMode.Cursor]) and as the source / target of the Shift+S snap operations. Session + * state, transient by design: cursor moves are deliberately NOT undo steps (they ride outside + * [EditorSnapshot]), and the snap menu makes recovering a lost placement cheap. + * + * 2D カーソル。Blender の 3D カーソルの 2D 版。ピボットやスナップの基準点になるワールド座標の + * アンカー。取り消し履歴には乗らない一時状態。 + * + * @property Float worldX The cursor's world-space x. + * @property Float worldZ The cursor's world-space z (up). + */ +data class Cursor2d(val worldX: Float, val worldZ: Float) + +/** + * The UV editor's own 2D cursor: a placeable anchor in normalized atlas coordinates, the texture-space + * sibling of [Cursor2d] (Blender's UV editor likewise carries its own cursor, separate from the 3D + * one). Placed with Shift+RightClick in the UV editor, drawn by its overlay, and read as the UV + * transform pivot in [TransformPivotMode.Cursor]. Session state, transient by design like [Cursor2d]: + * cursor moves are deliberately NOT undo steps. + * + * UV エディタ専用の 2D カーソル。正規化アトラス座標のアンカーで、UV 変形のカーソルピボットになる。 + * 取り消し履歴には乗らない一時状態。 + * + * @property Float u The cursor's normalized atlas u coordinate. + * @property Float v The cursor's normalized atlas v coordinate. + */ +data class UvCursor(val u: Float, val v: Float) + +/** + * What a modal Scale / Rotate turns the selection about (Blender's pivot point selector, the Period + * pie). MedianPoint is the covered vertices' centroid (the default); IndividualOrigins splits the + * selection into connectivity islands (edit mode) or per drawable (object mode), each turning about + * its own centroid; ActiveElement anchors on the active element (or active drawable); Cursor anchors + * on the 2D cursor. + * + * 変形の基準点の種類(Blender のピボットポイント)。中点・各自の原点・アクティブ要素・2D カーソル。 + */ +enum class TransformPivotMode { + MedianPoint, + IndividualOrigins, + ActiveElement, + Cursor, +} + +/** + * The axis a modal Grab / Scale is locked to, toggled by pressing X or Z during the gesture (Blender's + * axis constraint; Rotate is excluded - there is only one 2D rotation axis). Named by the DISPLAYED + * axes: the project presents the 2D plane as X (horizontal) and Z (vertical, world +y) per the + * Y+ forward, Z+ up convention, so AxisZ constrains the position arrays' y coordinates. + * + * モーダル変形の軸ロック(X / Z キー)。表示規約は Y+ 前、Z+ 上なので、AxisZ は配列の y 成分に対応する。 + */ +enum class TransformAxisConstraint { + AxisX, + AxisZ, +} + +/** + * Which radial pie menu is open over the viewport, or none (null in the session flow). The pie + * entries dispatch through the command registry; the session only coordinates which pie is showing + * (a transient latch like the modal operators). + * + * 表示中のパイメニューの種類。エントリはコマンドレジストリ経由で実行される。 + */ +enum class PieMenuKind { + PivotMode, + Snap, + UvSnap, + MergeTarget, +} + +/** + * A latched modal transform operator together with the viewport area that initiated it. The area id + * is an opaque workspace-leaf id (the same currency as [EditorSession.zoomRegionArmedArea]): the + * session never interprets it, but the UI gates gesture capture, HUD drawing, and confirm delivery to + * the initiating area, so a gesture latched in one split viewport can never be driven or committed + * from another. Both fields publish atomically in one flow emission - a paired flow could tear. + * + * ラッチされたモーダル変形操作と、それを開始したビューポートエリア。エリア ID は不透明な文字列で、 + * UI 側がジェスチャの捕捉・HUD 描画・確定の配送を開始エリアに限定するために使う。 + * + * @property MeshOperatorKind kind The latched operator (Grab / Scale / Rotate / VertexSlide). + * @property String areaId The initiating viewport's area id. + */ +data class ActiveOperator( + val kind: MeshOperatorKind, + val areaId: String, +) + +/** + * The geometry-dependent snap operations (Blender's Shift+S) the viewport overlay executes: the + * cursor-to-geometry moves need the posed world projection and the selection-to-target moves edit the + * model through the deformer-chain inverse, both of which live with the overlay - so the session + * carries the request and the active mode's overlay performs it. The purely arithmetical snaps + * (cursor to world origin / to grid) are handled directly by their command handlers and never appear + * here. + * + * ジオメトリ依存のスナップ操作の種類。オーバーレイが実行する。 + */ +enum class SnapKind { + CursorToSelected, + CursorToActive, + SelectionToCursor, + SelectionToCursorOffset, + SelectionToGrid, + SelectionToActive, +} + +/** + * The UV editor's snap operations (its own Shift+S pie), the texture-space sibling of [SnapKind]. + * Every one edits or reads in the UV editor's texel display space, so the UV overlay - which owns the + * shown page's dimensions and display geometry - executes them, the same request-through-overlay split + * as [SnapKind]. The op set differs from the world snaps by design: UV has pixel-corner snaps (a + * texel boundary is a natural target for artwork-edge accuracy) and no Active-element snaps, while the + * world grid has no meaning here (the UV grid subdivides the atlas page instead - see the UV editor's + * display mapping). + * + * UV エディタのスナップ操作の種類。テクセル表示空間で動作し、UV オーバーレイが実行する。 + */ +enum class UvSnapKind { + SelectionToPixels, + SelectionToCursor, + SelectionToCursorOffset, + SelectionToGrid, + CursorToPixels, + CursorToSelected, + CursorToGrid, +} + +/** + * One pivot group of a modal transform: a set of vertices turning about one pivot. Median / Active / + * Cursor pivot modes produce a single group per mesh (every covered vertex about the one shared + * anchor); IndividualOrigins produces one group per connectivity island (edit mode) or per drawable + * (object mode), each about its own centroid. + * + * 変形のピボットグループ。1つのピボットを共有する頂点集合。各自の原点モードでは島ごとに分かれる。 + * + * @property Set vertexIndices The group's vertex indices (into the mesh's interleaved array). + * @property Float pivotX The group pivot's x, in the positions' coordinate space. + * @property Float pivotY The group pivot's y, in the positions' coordinate space. + */ +data class TransformPivotGroup( + val vertexIndices: Set, + val pivotX: Float, + val pivotY: Float, +) + +/** + * Pure pivot-group builders for the modal transforms (the [TransformPivotMode] machinery). + * + * ピボットグループの純粋な構築関数。 + */ +object TransformPivots { + /** + * One group turning every covered vertex about a shared anchor - the shape Median Point, Active + * Element, and Cursor pivots all reduce to (they differ only in where the anchor is). + * + * @param Set coveredIndices The vertices the gesture moves. + * @param Float pivotX The shared anchor's x. + * @param Float pivotY The shared anchor's y. + * @return List The single shared-pivot group. + */ + fun sharedGroup(coveredIndices: Set, pivotX: Float, pivotY: Float): List = + listOf(TransformPivotGroup(coveredIndices, pivotX, pivotY)) + + /** + * Per-island groups for Individual Origins in edit mode: the covered vertices split into + * connectivity islands (components of the sub-graph the selection induces), each turning about its + * own centroid. + * + * @param FloatArray positions The mesh's interleaved positions (the pivots' coordinate space). + * @param Set coveredIndices The vertices the gesture moves. + * @param IntArray triangleIndices The mesh triangle vertex indices (for connectivity). + * @return List One group per island. + */ + fun islandGroups( + positions: FloatArray, + coveredIndices: Set, + triangleIndices: IntArray, + ): List { + val vertexCount = positions.size / 2 + val adjacency = MeshTopology.buildVertexAdjacency(vertexCount, triangleIndices) + return MeshTopology.selectionIslands(adjacency, coveredIndices).map { island -> + val pivot = MeshTransforms.medianPivot(positions, island) + TransformPivotGroup(island, pivot.first, pivot.second) + } + } + + /** + * Splits a proportional influence map into per-group weight maps, index-parallel to [groups]: each + * influenced vertex follows the pivot group that OWNS its nearest covered vertex, so with Individual + * Origins the halo around an island turns about that island's pivot, not the shared gesture anchor. + * With a single shared group everything lands in it (whose pivot IS the gesture anchor), so the + * shared-pivot modes keep their behavior. An influence whose nearest covered vertex is in no group + * (impossible today - the groups partition the covered set) falls into the first group rather than + * dropping motion. + * + * @param Map influences The influenced vertices (weight + nearest covered). + * @param List groups The gesture's pivot groups. + * @return List> One weight map per group, parallel to [groups]. + */ + fun partitionInfluencesByGroup( + influences: Map, + groups: List, + ): List> { + if (groups.isEmpty()) { + return emptyList() + } + val partitions = List(groups.size) { LinkedHashMap() } + for ((vertexIndex, influence) in influences) { + val ownerIndex = groups.indexOfFirst { group -> influence.nearestCoveredIndex in group.vertexIndices } + partitions[if (ownerIndex >= 0) ownerIndex else 0][vertexIndex] = influence.weight + } + return partitions + } +} + +/** + * Accumulates a modal rotate gesture's angle from per-move increments, each wrapped into (-pi, pi], so + * the total walks smoothly through the atan2 branch cut at +-pi and supports multi-turn rotation. A + * raw start-to-current atan2 subtraction cannot: a far pivot (the 2D cursor off to the side) places the + * start angle right AT the cut, where the difference jumps by ~2*pi and the gesture's arc direction + * latches (it can never reverse past its start). One tracker lives per gesture capture; feeding the + * same pointer angle twice adds zero, so re-derives without pointer motion are safe. + */ +class RotationAngleTracker { + private var previousPointerAngle: Float? = null + + /** The accumulated gesture angle in radians (screen-space sign; the caller negates into world space). */ + var totalAngle: Float = 0f + private set + + /** + * Advances the accumulator to the pointer's current angle about the pivot and returns the total. + * + * @param Float pointerAngle The pointer's atan2 angle about the rotation pivot, radians. + * @return Float The accumulated gesture angle, radians. + */ + fun advance(pointerAngle: Float): Float { + val previous = previousPointerAngle + if (previous != null) { + totalAngle += wrapAngle(pointerAngle - previous) + } + previousPointerAngle = pointerAngle + return totalAngle + } +} + +/** + * Wraps an angle difference into (-pi, pi] - the shortest signed arc between two angles. + * + * @param Float delta The raw angle difference, radians. + * @return Float The wrapped difference. + */ +fun wrapAngle(delta: Float): Float = atan2(sin(delta), cos(delta)) \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/UvFrame.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/UvFrame.kt new file mode 100644 index 0000000..3ae1b09 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/UvFrame.kt @@ -0,0 +1,81 @@ +package org.umamo.edit + +/** + * A change of texture-coordinate frame: how the stored uvs relate to the space an edit is authored in. + * + * The UV editor shows a drawable's mapping over two different surfaces - the packed atlas page it is + * stored against, and the source artwork it was authored against - and an operation expressed in + * normalized coordinates (Mirror is the only one) means something different in each. Handing the + * operation this pair lets it work in whichever frame the user is looking at while still committing + * the stored form. + * + * Both members are 2x3 affines (m00, m01, m02, m10, m11, m12) over normalized coordinates, mutual + * inverses. A page-view edit passes no frame at all rather than an identity pair, so that path stays + * bit-identical to having no frame concept. + * + * A plain class, not a data class: the fields are arrays, whose identity-based equals would make a + * generated structural equals quietly wrong. Never use one as a snapshot or effect key - key on the + * scalars it was built from. + */ +class UvFrame(private val toFrameAffine: FloatArray, private val fromFrameAffine: FloatArray) { + /** + * Maps stored coordinates into the authoring frame. + * + * @param FloatArray uvs The stored coordinates, interleaved (u, v). + * @return FloatArray The frame coordinates, a fresh array. + */ + fun toFrame(uvs: FloatArray): FloatArray = applyAffine(uvs, toFrameAffine) + + /** + * Maps authoring-frame coordinates back to the stored form. + * + * @param FloatArray uvs The frame coordinates, interleaved (u, v). + * @return FloatArray The stored coordinates, a fresh array. + */ + fun fromFrame(uvs: FloatArray): FloatArray = applyAffine(uvs, fromFrameAffine) + + /** + * Maps one stored point into the authoring frame. + * + * @param Float u The stored u. + * @param Float v The stored v. + * @return Pair The point in frame coordinates. + */ + fun pointToFrame(u: Float, v: Float): Pair = + (toFrameAffine[0] * u + toFrameAffine[1] * v + toFrameAffine[2]) to + (toFrameAffine[3] * u + toFrameAffine[4] * v + toFrameAffine[5]) + + /** + * Maps one authoring-frame point back to the stored form. + * + * @param Float u The frame u. + * @param Float v The frame v. + * @return Pair The point in stored coordinates. + */ + fun pointFromFrame(u: Float, v: Float): Pair = + (fromFrameAffine[0] * u + fromFrameAffine[1] * v + fromFrameAffine[2]) to + (fromFrameAffine[3] * u + fromFrameAffine[4] * v + fromFrameAffine[5]) + + /** + * Maps a whole interleaved uv array through a 2x3 row-major affine, into a fresh array. + * + * A trailing odd component is left out rather than half-mapped: the arrays are interleaved pairs, so + * an odd length is malformed input, and the callers' own guards reject it upstream. + * + * @param FloatArray uvs The interleaved (u, v) pairs to map. + * @param FloatArray affine The 2x3 row-major affine (m00, m01, m02, m10, m11, m12). + * @return FloatArray The mapped pairs, in a new array of the same length. + */ + private fun applyAffine(uvs: FloatArray, affine: FloatArray): FloatArray { + val mapped = FloatArray(uvs.size) + var componentIndex = 0 + while (componentIndex + 1 < uvs.size) { + val u = uvs[componentIndex] + val v = uvs[componentIndex + 1] + mapped[componentIndex] = affine[0] * u + affine[1] * v + affine[2] + mapped[componentIndex + 1] = affine[3] * u + affine[4] * v + affine[5] + componentIndex += 2 + } + return mapped + } +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/VisibilityEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/VisibilityEdits.kt new file mode 100644 index 0000000..ae9b765 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/VisibilityEdits.kt @@ -0,0 +1,47 @@ +package org.umamo.edit + +import org.umamo.runtime.model.PuppetModel + +/* + * Selection-aware visibility helpers, bridging the object-mode Selection to the per-entity visibility + * transforms. Kept here (not in the UI) so the "toggle visibility of the selection" command is a thin + * dispatch and the model logic stays pure and testable. + * + * 選択に対する表示切り替えの補助。UI ではなくここに置き、コマンドは委譲だけにする。 + */ + +/** + * The current Parts-panel visibility of [target] in [this]. A deformer has no visibility flag, so it + * reports true (it is never "hidden"); a missing part/drawable also reports true. + * + * @param SelectionTarget target The entity to query. + * @return Boolean The entity's visibility (true when it has none). + */ +fun PuppetModel.visibilityOf(target: SelectionTarget): Boolean = + when (target) { + is SelectionTarget.Part -> parts.firstOrNull { it.id == target.id }?.isVisible ?: true + is SelectionTarget.Drawable -> drawables.firstOrNull { it.id == target.id }?.isVisible ?: true + is SelectionTarget.Deformer -> true + } + +/** + * Returns a copy of [this] with every part and drawable in [targets] set to [visible], structurally + * sharing untouched entities; deformer targets are skipped (they have no visibility flag). Folding all + * targets into one model makes the whole multi-selection toggle a single undo step. + * + * @param Set targets The selected targets to retoggle. + * @param Boolean visible The new visibility. + * @return PuppetModel The model with those entities' visibility updated. + */ +fun PuppetModel.withSelectionVisibility(targets: Set, visible: Boolean): PuppetModel { + var next = this + for (target in targets) { + next = + when (target) { + is SelectionTarget.Part -> next.withPartVisibility(target.id, visible) + is SelectionTarget.Drawable -> next.withDrawableVisibility(target.id, visible) + is SelectionTarget.Deformer -> next + } + } + return next +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/WarpLatticeGridEdits.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/WarpLatticeGridEdits.kt new file mode 100644 index 0000000..6cab399 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/WarpLatticeGridEdits.kt @@ -0,0 +1,243 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.math.min + +/* + * Resizing a warp deformer's conversion-division grid: every keyform lattice (and every blend-shape + * absolute lattice) is resampled through the old surface so the art does not jump. Child drawable UVs + * stay in the deformer's unit square, so they need no rewrite. + * + * ワープ格子の分割数変更。旧格子をサンプリングしてキーフォームを再標本化する。 + */ + +/** Smallest conversion-division count the properties slider / create path allow. */ +const val MIN_WARP_DIVISIONS = 2 + +/** Largest conversion-division count the properties slider allows (Cubism-style upper end). */ +const val MAX_WARP_DIVISIONS = 16 + +/** + * Clamps a conversion-division count into [[MIN_WARP_DIVISIONS], [MAX_WARP_DIVISIONS]]. + * + * @param Int divisions The requested count. + * @return Int The clamped count. + */ +fun clampWarpDivisions(divisions: Int): Int = divisions.coerceIn(MIN_WARP_DIVISIONS, MAX_WARP_DIVISIONS) + +/** + * Samples an absolute warp lattice at normalized UV ([0,1] inclusive) through the same bilinear / + * triangle-split blend the runtime uses for in-grid points. Boundary UVs land on the last row / + * column (inclusive), which [org.umamo.render.eval.warpInGrid]'s half-open `[0,1)` path would miss. + * + * @param FloatArray controlPoints Old lattice, `(columns+1)×(rows+1)` interleaved x,y. + * @param Int columns Old conversion divisions horizontally. + * @param Int rows Old conversion divisions vertically. + * @param Boolean bilinear Quad blend (true) vs triangle split (false). + * @param Float u Normalized horizontal coordinate in `[0,1]`. + * @param Float v Normalized vertical coordinate in `[0,1]`. + * @param FloatArray out Destination for the sampled point. + * @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`). + */ +fun sampleWarpLattice( + controlPoints: FloatArray, + columns: Int, + rows: Int, + bilinear: Boolean, + u: Float, + v: Float, + out: FloatArray, + outIndex: Int, +) { + val cols = columns.coerceAtLeast(1) + val rowCount = rows.coerceAtLeast(1) + val uu = u.coerceIn(0f, 1f) + val vv = v.coerceIn(0f, 1f) + val pointsPerRow = cols + 1 + val gridU = cols * uu + val gridV = rowCount * vv + val cellCol = min(gridU.toInt(), cols - 1) + val cellRow = min(gridV.toInt(), rowCount - 1) + val cellU = (gridU - cellCol).coerceIn(0f, 1f) + val cellV = (gridV - cellRow).coerceIn(0f, 1f) + val cellIndex = cellRow * pointsPerRow + cellCol + val p00 = cellIndex * 2 + val p10 = (cellIndex + 1) * 2 + val p01 = (cellIndex + pointsPerRow) * 2 + val p11 = (cellIndex + pointsPerRow + 1) * 2 + if (!bilinear) { + if (cellU + cellV <= 1f) { + out[outIndex] = controlPoints[p10] * cellU + controlPoints[p00] * (1 - cellU - cellV) + controlPoints[p01] * cellV + out[outIndex + 1] = + (1 - cellU - cellV) * controlPoints[p00 + 1] + controlPoints[p10 + 1] * cellU + controlPoints[p01 + 1] * cellV + } else { + val weight = (cellU - 1) + cellV + out[outIndex] = controlPoints[p01] * (1 - cellU) + controlPoints[p11] * weight + controlPoints[p10] * (1 - cellV) + out[outIndex + 1] = + weight * controlPoints[p11 + 1] + (1 - cellU) * controlPoints[p01 + 1] + (1 - cellV) * controlPoints[p10 + 1] + } + } else { + val invCellV = 1 - cellV + out[outIndex] = + controlPoints[p10] * cellU * invCellV + + controlPoints[p00] * (1 - cellU) * invCellV + + controlPoints[p01] * (1 - cellU) * cellV + + controlPoints[p11] * cellU * cellV + out[outIndex + 1] = + invCellV * controlPoints[p10 + 1] * cellU + + controlPoints[p00 + 1] * (1 - cellU) * invCellV + + (1 - cellU) * controlPoints[p01 + 1] * cellV + + cellU * controlPoints[p11 + 1] * cellV + } +} + +/** + * Builds a new lattice by sampling [controlPoints] at the UV of every new control point. + * + * @param FloatArray controlPoints Old lattice control points. + * @param Int oldRows Old conversion divisions vertically. + * @param Int oldColumns Old conversion divisions horizontally. + * @param Boolean bilinear The warp's interpolation mode. + * @param Int newRows New conversion divisions vertically. + * @param Int newColumns New conversion divisions horizontally. + * @return FloatArray Fresh interleaved control points for the new grid. + */ +fun resampleWarpLatticeControlPoints( + controlPoints: FloatArray, + oldRows: Int, + oldColumns: Int, + bilinear: Boolean, + newRows: Int, + newColumns: Int, +): FloatArray { + val pointsPerRow = newColumns + 1 + val pointsPerCol = newRows + 1 + val out = FloatArray(pointsPerRow * pointsPerCol * 2) + val scratch = FloatArray(2) + for (row in 0 until pointsPerCol) { + val v = row.toFloat() / newRows.coerceAtLeast(1) + for (col in 0 until pointsPerRow) { + val u = col.toFloat() / newColumns.coerceAtLeast(1) + sampleWarpLattice(controlPoints, oldColumns, oldRows, bilinear, u, v, scratch, 0) + val index = (row * pointsPerRow + col) * 2 + out[index] = scratch[0] + out[index + 1] = scratch[1] + } + } + return out +} + +/** + * Returns a copy of [this] with warp deformer [id]'s conversion divisions set to [rows]×[columns], + * resampling every geometry-grid cell and every blend-shape lattice through the old surface. A no-op + * (missing / non-warp deformer, unchanged size, missing lattice, or a cell whose point count does not + * match the old grid) returns the same instance. Counts are clamped to [[MIN_WARP_DIVISIONS], + * [MAX_WARP_DIVISIONS]]. + * + * @param DeformerId id The warp deformer to retarget. + * @param Int rows New conversion divisions vertically. + * @param Int columns New conversion divisions horizontally. + * @return PuppetModel The model with the resized warp, or [this] if nothing changed. + */ +fun PuppetModel.withWarpDeformerGrid( + id: DeformerId, + rows: Int, + columns: Int, +): PuppetModel { + val newRows = clampWarpDivisions(rows) + val newColumns = clampWarpDivisions(columns) + val index = deformers.indexOfFirst { deformer -> deformer.id == id } + if (index < 0) { + return this + } + val deformer = deformers[index] as? Deformer.Warp ?: return this + if (deformer.rows == newRows && deformer.columns == newColumns) { + return this + } + val grid = deformer.geometryGrid ?: return this + val expectedPoints = (deformer.columns + 1) * (deformer.rows + 1) * 2 + if (grid.cells.any { cell -> cell.form.controlPoints.size != expectedPoints }) { + return this + } + val resampledGrid = + KeyformGrid( + grid.axes, + grid.cells.map { cell -> + KeyformCell( + cell.coordinate.copyOf(), + WarpLatticeForm( + resampleWarpLatticeControlPoints( + cell.form.controlPoints, + deformer.rows, + deformer.columns, + deformer.isQuadTransform, + newRows, + newColumns, + ), + ), + ) + }, + ) + val resampledBlendShapes = + deformer.blendShapes.map { binding -> + resampleWarpBlendBinding(binding, deformer, newRows, newColumns, expectedPoints) + } + val updated = deformers.toMutableList() + updated[index] = + deformer.copy( + rows = newRows, + columns = newColumns, + geometryGrid = resampledGrid, + blendShapes = resampledBlendShapes, + ) + return copy(deformers = updated) +} + +/** + * Resamples one warp blend-shape binding's absolute lattices onto the new grid. Forms whose point + * count does not match the old grid are left untouched (same refuse rule as the geometry grid). + * + * @param BlendShapeBinding binding The binding to rewrite. + * @param Deformer.Warp deformer The warp before the resize (old dimensions / mode). + * @param Int newRows New conversion divisions vertically. + * @param Int newColumns New conversion divisions horizontally. + * @param Int expectedPoints Expected interleaved float count on the old grid. + * @return BlendShapeBinding The resampled binding. + */ +private fun resampleWarpBlendBinding( + binding: BlendShapeBinding, + deformer: Deformer.Warp, + newRows: Int, + newColumns: Int, + expectedPoints: Int, +): BlendShapeBinding = + binding.copy( + forms = + binding.forms.map { form -> + if (form == null || form.controlPoints.size != expectedPoints) { + form + } else { + WarpForm( + controlPoints = + resampleWarpLatticeControlPoints( + form.controlPoints, + deformer.rows, + deformer.columns, + deformer.isQuadTransform, + newRows, + newColumns, + ), + opacity = form.opacity, + multiplyColor = form.multiplyColor, + screenColor = form.screenColor, + ) + } + }, + ) \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/seed/HumanoidParameters.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/seed/HumanoidParameters.kt new file mode 100644 index 0000000..223239c --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/seed/HumanoidParameters.kt @@ -0,0 +1,69 @@ +package org.umamo.edit.seed + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId + +/** + * The humanoid parameter set: the ids, ranges, and defaults of Live2D's published Standard Parameter + * List, which every Live2D-compatible runtime, tracker, and application keys on. The ids are + * format-level identifiers and stay verbatim; the display names are English document data the + * rigger may rename. + */ +object HumanoidParameters { + /** + * One standard parameter. + * + * @param String id The format-level id, e.g. `ParamAngleX`. + * @param String name The English display name. + * @param Float min The axis minimum. + * @param Float max The axis maximum. + * @param Float default The rest value. + * @return Parameter The parameter. + */ + private fun standard(id: String, name: String, min: Float, max: Float, default: Float = 0f): Parameter = + Parameter(id = ParameterId(id), name = name, min = min, max = max, default = default) + + /** The set, in the order the official parameter palette lists it. */ + val list: List = + listOf( + standard("ParamAngleX", "Angle X", -30f, 30f), + standard("ParamAngleY", "Angle Y", -30f, 30f), + standard("ParamAngleZ", "Angle Z", -30f, 30f), + standard("ParamEyeLOpen", "Eye L Open", 0f, 1f, default = 1f), + standard("ParamEyeLSmile", "Eye L Smile", 0f, 1f), + standard("ParamEyeROpen", "Eye R Open", 0f, 1f, default = 1f), + standard("ParamEyeRSmile", "Eye R Smile", 0f, 1f), + standard("ParamEyeBallX", "Eyeball X", -1f, 1f), + standard("ParamEyeBallY", "Eyeball Y", -1f, 1f), + standard("ParamBrowLY", "Brow L Y", -1f, 1f), + standard("ParamBrowRY", "Brow R Y", -1f, 1f), + standard("ParamBrowLX", "Brow L X", -1f, 1f), + standard("ParamBrowRX", "Brow R X", -1f, 1f), + standard("ParamBrowLAngle", "Brow L Angle", -1f, 1f), + standard("ParamBrowRAngle", "Brow R Angle", -1f, 1f), + standard("ParamBrowLForm", "Brow L Form", -1f, 1f), + standard("ParamBrowRForm", "Brow R Form", -1f, 1f), + standard("ParamMouthForm", "Mouth Form", -1f, 1f), + standard("ParamMouthOpenY", "Mouth Open", 0f, 1f), + standard("ParamCheek", "Cheek", 0f, 1f), + standard("ParamBodyAngleX", "Body Rotation X", -10f, 10f), + standard("ParamBodyAngleY", "Body Rotation Y", -10f, 10f), + standard("ParamBodyAngleZ", "Body Rotation Z", -10f, 10f), + standard("ParamBreath", "Breath", 0f, 1f), + standard("ParamArmLA", "Arm L A", -10f, 10f), + standard("ParamArmRA", "Arm R A", -10f, 10f), + standard("ParamArmLB", "Arm L B", -10f, 10f), + standard("ParamArmRB", "Arm R B", -10f, 10f), + standard("ParamHandL", "Hand L", -10f, 10f), + standard("ParamHandR", "Hand R", -10f, 10f), + standard("ParamHairFront", "Hair Move Front", -1f, 1f), + standard("ParamHairSide", "Hair Move Side", -1f, 1f), + standard("ParamHairBack", "Hair Move Back", -1f, 1f), + standard("ParamHairFluffy", "Hair Fluffy", 0f, 1f), + standard("ParamShoulderY", "Shoulder Y", -10f, 10f), + standard("ParamBustX", "Bust X", -1f, 1f), + standard("ParamBustY", "Bust Y", -1f, 1f), + standard("ParamBaseX", "Base X", -30f, 30f), + standard("ParamBaseY", "Base Y", -30f, 30f), + ) +} \ No newline at end of file diff --git a/module/edit/src/commonMain/kotlin/org/umamo/edit/seed/ParameterTemplate.kt b/module/edit/src/commonMain/kotlin/org/umamo/edit/seed/ParameterTemplate.kt new file mode 100644 index 0000000..964bd23 --- /dev/null +++ b/module/edit/src/commonMain/kotlin/org/umamo/edit/seed/ParameterTemplate.kt @@ -0,0 +1,44 @@ +package org.umamo.edit.seed + +import org.umamo.runtime.model.Parameter + +/** + * The parameter set a new model is seeded with. + * + * An enum rather than a free list so the choice persists as one settings value and a later template + * (a quadruped, a prop) is one more entry. [key] is the stored value; the entry name is Umamo's, not + * a format's. The template is data only: whoever creates the model (an artwork import, a blank + * document) resolves it to [parameters] and seeds those. + * + * @property String key The value the settings key `import.parameterTemplate` stores. + */ +enum class ParameterTemplate(val key: String) { + /** No parameters; the rigger creates every axis by hand. */ + None("none"), + + /** The standard humanoid set every Live2D-compatible runtime and application expects. */ + Humanoid("humanoid"), + ; + + /** The parameters the template seeds, in the order the panel lists them. */ + val parameters: List + get() = + when (this) { + None -> emptyList() + Humanoid -> HumanoidParameters.list + } + + companion object { + /** The template that seeds a new model when nothing else is configured. */ + val Default: ParameterTemplate = Humanoid + + /** + * Resolves a stored key, falling back to [Default] for an unknown or absent one so a stale + * setting never leaves a new model without a template. + * + * @param String? key The stored settings value. + * @return ParameterTemplate The template. + */ + fun fromKey(key: String?): ParameterTemplate = entries.firstOrNull { template -> template.key == key } ?: Default + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/AdjustableOperationTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/AdjustableOperationTest.kt new file mode 100644 index 0000000..ce3b0bf --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/AdjustableOperationTest.kt @@ -0,0 +1,139 @@ +package org.umamo.edit + +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the session half of adjusting the last operation: a registration captures the base and the + * committed change, an adjustment re-runs from that base and rewrites the operation's own step, any + * other push or a restore clears the record, a stale amend after a clear is refused, an amended step + * dirties a saved document, and a registration against the wrong model or without a push is refused. + */ +class AdjustableOperationTest { + private val partId = PartId("a") + private val widthKey = "width" + + private fun model(name: String): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(Part(partId, name, children = emptyList())), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(partId)), + rootPartId = null, + ) + + private fun PuppetModel.renamed(name: String): PuppetModel = copy(parts = parts.map { part -> part.copy(name = name) }) + + private fun liveName(session: EditorSession): String = session.model.value.parts.first().name + + private fun parameters(width: Int): List = listOf(OperatorParameter.IntParameter(widthKey, "op.width", width, 0, 100)) + + /** + * Runs the test's stand-in operation: renames the part to "w" as one commit and registers it + * as adjustable, its rerun renaming from the BASE to the width it is given. + * + * @param EditorSession session The session to run in. + * @param Int width The operation's one setting. + * @return AdjustableOperation The live record. + */ + private fun runOperation(session: EditorSession, width: Int): AdjustableOperation { + session.mutate(PartChange.Rename(partId, "w$width")) { current -> current.renamed("w$width") } + val committed = session.model.value + return assertNotNull( + session.registerAdjustableOperation(committed, areaId = "area-1", parameters = parameters(width)) { record -> + val newWidth = record.parameters.intValue(widthKey, -1) + session.amendLastCommit(record, record.baseSnapshot.model.renamed("w$newWidth")) + }, + "a registration right after the commit succeeds", + ) + } + + @Test + fun aRegistrationCapturesTheBaseAndTheCommittedChange() { + val session = EditorSession(model("seed")) + + val record = runOperation(session, 1) + + assertEquals("seed", record.baseSnapshot.model.parts.first().name, "the base is the state the operation ran from") + assertEquals("change.part.rename", record.change.labelKey) + assertEquals("area-1", record.areaId) + assertSame(record, session.adjustableOperation.value) + } + + @Test + fun anAdjustmentRerunsFromTheBaseAndRewritesTheStepInPlace() { + val session = EditorSession(model("seed")) + runOperation(session, 1) + val stepsBefore = session.historyView.value.steps.size + + session.adjustLastOperation(parameters(7)) + + assertEquals("w7", liveName(session), "the rerun landed") + assertEquals(stepsBefore, session.historyView.value.steps.size, "the stack did not grow") + assertFalse(session.canRedo.value) + assertEquals(parameters(7), assertNotNull(session.adjustableOperation.value).parameters, "the record shows the new settings") + session.undo() + assertEquals("seed", liveName(session), "one undo returns to the base") + assertFalse(session.canUndo.value) + session.redo() + assertEquals("w7", liveName(session), "redo returns the adjusted result") + } + + @Test + fun anyOtherPushClearsTheRecord() { + val session = EditorSession(model("seed")) + runOperation(session, 1) + + session.mutate(PartChange.Rename(partId, "other")) { current -> current.renamed("other") } + + assertNull(session.adjustableOperation.value, "another commit ends the adjustable operation") + } + + @Test + fun aRestoreClearsTheRecordAndAStaleAmendIsRefused() { + val session = EditorSession(model("seed")) + val record = runOperation(session, 1) + + session.undo() + + assertNull(session.adjustableOperation.value, "undo ends the adjustable operation") + assertFalse(session.amendLastCommit(record, model("stale")), "a rerun completing after the clear is dropped") + assertEquals("seed", liveName(session), "nothing was published") + session.adjustLastOperation(parameters(9)) + assertEquals("seed", liveName(session), "adjusting with no record is a no-op") + } + + @Test + fun anAmendedStepDirtiesASavedDocument() { + val session = EditorSession(model("seed")) + runOperation(session, 1) + session.markSaved() + assertFalse(session.dirty.value) + + session.adjustLastOperation(parameters(2)) + + assertTrue(session.dirty.value, "the adjusted result is unsaved content") + } + + @Test + fun aRegistrationIsRefusedWithoutACommitOrAgainstAnotherModel() { + val fresh = EditorSession(model("seed")) + assertNull(fresh.registerAdjustableOperation(fresh.model.value, null, parameters(1)) {}, "nothing was pushed") + + val session = EditorSession(model("seed")) + session.mutate(PartChange.Rename(partId, "w1")) { current -> current.renamed("w1") } + assertNull(session.registerAdjustableOperation(model("elsewhere"), null, parameters(1)) {}, "the live model is not the one claimed") + assertNotNull(session.registerAdjustableOperation(session.model.value, null, parameters(1)) {}, "the right model registers") + assertNull(session.registerAdjustableOperation(session.model.value, null, parameters(1)) {}, "a second registration for the same push is refused") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ArtworkEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ArtworkEditsTest.kt new file mode 100644 index 0000000..40db044 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ArtworkEditsTest.kt @@ -0,0 +1,335 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.ArtworkAdditions +import org.umamo.runtime.model.ArtworkReload +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.OrgInsertion +import org.umamo.runtime.model.OrgSlot +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.ReplacedTile +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.deriveRenderRoot +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The three artwork edits: rebinding a tile to a source layer, appending an artwork file's + * additions, and applying a reload. All refuse rather than half-apply - a binding to an unlisted + * file, an addition or replacement whose ids collide, a reload naming a tile or file the model lacks - + * so the Sources space and the artwork flows can trust a returned model. + */ +class ArtworkEditsTest { + private val sourceA = ArtSource(ArtSourceId("art-0"), "a.psd", "/a.psd", "psd", listOf(ArtSourceLayer("lyid:1", "L1", "", 0, 0, 4, 4, true))) + private val refA1 = SourceLayerRef(ArtSourceId("art-0"), "lyid:1", stableKey = true) + + private fun quad(): DrawableMesh = DrawableMesh(floatArrayOf(0f, 0f, 4f, 0f, 4f, 4f, 0f, 4f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + + private fun drawable(id: String, tileId: String): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), quad(), null, atlasTileId = AtlasTileId(tileId)) + + private fun model(): PuppetModel { + val drawable = drawable("ArtMesh1", "art-0/lyid:1") + return PuppetModel( + parameters = emptyList(), + parts = listOf(Part(PartId("Part1"), "Folder", listOf(OrgChild.Drawable(drawable.id)))), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Part(PartId("Part1"))), + rootPartId = null, + atlas = PuppetAtlas(tiles = listOf(AtlasTile(AtlasTileId("art-0/lyid:1"), "L1", 4, 4, source = refA1))), + sources = listOf(sourceA), + ) + } + + @Test + fun aTileRebindsToAListedSourceAndUnbinds() { + val base = model() + val other = SourceLayerRef(ArtSourceId("art-0"), "lyid:2", stableKey = true) + + val rebound = base.withTileSource(AtlasTileId("art-0/lyid:1"), other) + assertEquals(other, rebound.atlas.tiles.single().source) + assertSame(base.drawables, rebound.drawables, "a rebind moves nothing else") + + val unbound = rebound.withTileSource(AtlasTileId("art-0/lyid:1"), null) + assertNull(unbound.atlas.tiles.single().source) + } + + @Test + fun tilesBoundToOneKeyRebindTogetherAsOneStep() { + // Two tiles under one lost key, the shape a review row's Accept acts on: they move as one edit, + // so one undo brings both back. + val second = AtlasTile(AtlasTileId("art-0/lyid:1~1"), "L1", 4, 4, source = refA1, replaces = AtlasTileId("art-0/lyid:1")) + val base = model().let { single -> single.copy(atlas = single.atlas.copy(tiles = single.atlas.tiles + second)) } + val session = EditorSession(base) + val both = base.atlas.tiles.map { tile -> tile.id } + + session.setTileSources(both, null) + assertTrue(session.model.value.atlas.tiles.all { tile -> tile.source == null }, "both tiles unbound") + assertTrue(session.canUndo.value) + + session.undo() + assertTrue(session.model.value.atlas.tiles.all { tile -> tile.source == refA1 }, "one undo restores both") + assertEquals(false, session.canUndo.value, "the two rebinds were one step") + + session.setTileSources(emptyList(), null) + assertEquals(false, session.canUndo.value, "an empty call pushes nothing") + } + + @Test + fun aRebindToAnUnlistedSourceOrAnUnknownTileIsRefused() { + val base = model() + assertSame(base, base.withTileSource(AtlasTileId("art-0/lyid:1"), SourceLayerRef(ArtSourceId("art-9"), "lyid:1", true)), "an unlisted file") + assertSame(base, base.withTileSource(AtlasTileId("nope"), refA1), "an unknown tile") + assertSame(base, base.withTileSource(AtlasTileId("art-0/lyid:1"), refA1), "the binding it already has") + } + + @Test + fun artworkAdditionsAppendAfterTheExistingRigWithADerivedRenderRoot() { + val base = model() + val added = drawable("ArtMesh2", "art-1/uuid-7") + val additions = + ArtworkAdditions( + source = ArtSource(ArtSourceId("art-1"), "b.clip", null, "clip", listOf(ArtSourceLayer("uuid-7", "Wing", "", 2, 2, 4, 4, true))), + tiles = listOf(AtlasTile(AtlasTileId("art-1/uuid-7"), "Wing", 4, 4, source = SourceLayerRef(ArtSourceId("art-1"), "uuid-7", true))), + drawables = listOf(added), + parts = listOf(Part(PartId("Part2"), "Wings", listOf(OrgChild.Drawable(added.id)))), + rootChildren = listOf(OrgChild.Part(PartId("Part2"))), + ) + + val grown = base.withArtworkAdded(additions) + assertEquals(listOf("art-0", "art-1"), grown.sources.map { source -> source.id.raw }) + assertEquals(listOf("ArtMesh1", "ArtMesh2"), grown.drawables.map { drawable -> drawable.id.raw }) + assertEquals(listOf("Part1", "Part2"), grown.parts.map { part -> part.id.raw }) + assertEquals(listOf(OrgChild.Part(PartId("Part1")), OrgChild.Part(PartId("Part2"))), grown.rootChildren, "the file's order follows the existing root children") + assertEquals(2, grown.atlas.tiles.size) + assertTrue(grown.renderRoot.children.isNotEmpty(), "the render root is re-derived over the grown tree") + assertEquals(base.atlas.pages, grown.atlas.pages, "the pages are untouched - the pack is a separate step") + } + + @Test + fun artworkAdditionsThatCollideAreRefused() { + val base = model() + val collidingDrawable = + ArtworkAdditions( + source = ArtSource(ArtSourceId("art-1"), "b.clip", null, "clip"), + tiles = emptyList(), + drawables = listOf(drawable("ArtMesh1", "art-1/x")), + parts = emptyList(), + rootChildren = emptyList(), + ) + assertSame(base, base.withArtworkAdded(collidingDrawable), "a drawable id the model already has") + val collidingSource = + ArtworkAdditions(source = sourceA, tiles = emptyList(), drawables = emptyList(), parts = emptyList(), rootChildren = emptyList()) + assertSame(base, base.withArtworkAdded(collidingSource), "a source id the model already lists") + } + + @Test + fun aReloadSwapsTheTileCarriesTheDrawablesAndAppendsTheAdditions() { + val base = model() + val newMesh = DrawableMesh(floatArrayOf(0f, 0f, 6f, 0f, 6f, 6f, 0f, 6f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + val replacement = AtlasTile(AtlasTileId("art-0/lyid:1~1"), "L1", 6, 6, source = refA1, pinned = true, replaces = AtlasTileId("art-0/lyid:1")) + val added = drawable("ArtMesh2", "art-0/lyid:2") + val refreshed = sourceA.copy(layers = listOf(ArtSourceLayer("lyid:1", "L1", "", 0, 0, 6, 6, true), ArtSourceLayer("lyid:2", "L2", "", 9, 9, 4, 4, true))) + val reload = + ArtworkReload( + source = refreshed, + replacedTiles = listOf(ReplacedTile(AtlasTileId("art-0/lyid:1"), replacement)), + drawableMeshes = mapOf(DrawableId("ArtMesh1") to newMesh), + additions = + ArtworkAdditions( + source = refreshed, + tiles = listOf(AtlasTile(AtlasTileId("art-0/lyid:2"), "L2", 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), "lyid:2", true))), + drawables = listOf(added), + parts = emptyList(), + rootChildren = listOf(OrgChild.Drawable(added.id)), + ), + outgrown = emptyList(), + ) + + val reloaded = base.withArtworkReloaded(reload) + assertEquals(listOf("art-0/lyid:1~1", "art-0/lyid:2"), reloaded.atlas.tiles.map { tile -> tile.id.raw }, "the old tile is gone, the replacement and the addition appended") + assertSame(replacement, reloaded.atlas.tiles.first()) + val carried = reloaded.drawables.first { drawable -> drawable.id.raw == "ArtMesh1" } + assertEquals(AtlasTileId("art-0/lyid:1~1"), carried.atlasTileId, "the drawable moved onto the replacement") + assertSame(newMesh, carried.mesh, "with the mesh the plan decided") + assertEquals(listOf("ArtMesh1", "ArtMesh2"), reloaded.drawables.map { drawable -> drawable.id.raw }) + assertEquals(listOf(OrgChild.Part(PartId("Part1")), OrgChild.Drawable(added.id)), reloaded.rootChildren) + assertEquals(refreshed, reloaded.sources.single(), "the file's record takes the new inventory") + assertEquals(reloaded.deriveRenderRoot(), reloaded.renderRoot, "the render root is re-derived") + } + + /** + * A delta's insertions place new children among the existing ones - before or after an anchor, at + * the end, and after a child the same delta placed just before - in the root and in a part the model + * already holds; an anchor the container lacks falls to the end; a container the model lacks refuses. + */ + @Test + fun insertionsPlaceNewChildrenAmongTheExistingOnes() { + val base = model() + val added = drawable("ArtMesh2", "art-0/lyid:2") + val second = drawable("ArtMesh3", "art-0/lyid:3") + val top = drawable("ArtMesh4", "art-0/lyid:4") + val kept = OrgChild.Drawable(DrawableId("ArtMesh1")) + val additions = + ArtworkAdditions( + source = sourceA, + tiles = listOf(added, second, top).map { drawable -> AtlasTile(drawable.atlasTileId!!, drawable.name, 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), drawable.atlasTileId!!.raw.substringAfter('/'), true)) }, + drawables = listOf(added, second, top), + parts = emptyList(), + rootChildren = emptyList(), + insertions = + listOf( + OrgInsertion(PartId("Part1"), OrgChild.Drawable(added.id), OrgSlot.Before(kept)), + OrgInsertion(PartId("Part1"), OrgChild.Drawable(second.id), OrgSlot.After(OrgChild.Drawable(added.id))), + OrgInsertion(null, OrgChild.Drawable(top.id), OrgSlot.Before(OrgChild.Part(PartId("Part1")))), + ), + ) + val reload = ArtworkReload(sourceA, replacedTiles = emptyList(), drawableMeshes = emptyMap(), additions = additions, outgrown = emptyList()) + val reloaded = base.withArtworkReloaded(reload) + assertEquals(listOf(OrgChild.Drawable(added.id), OrgChild.Drawable(second.id), kept), reloaded.parts.single().children, "before the kept child, then after the one just placed") + assertEquals(listOf(OrgChild.Drawable(top.id), OrgChild.Part(PartId("Part1"))), reloaded.rootChildren, "a top-of-file layer lands first at the root") + assertEquals(listOf("ArtMesh1", "ArtMesh2", "ArtMesh3", "ArtMesh4"), reloaded.drawables.map { drawable -> drawable.id.raw }) + assertEquals(RenderDrawable(DrawableId("ArtMesh4")), reloaded.renderRoot.children.last(), "and draws last of all, so in front (the render root runs back to front)") + + val fallbacks = additions.copy(insertions = listOf(OrgInsertion(PartId("Part1"), OrgChild.Drawable(added.id), OrgSlot.After(OrgChild.Drawable(DrawableId("gone")))), OrgInsertion(null, OrgChild.Drawable(top.id), OrgSlot.End))) + val fallen = base.withArtworkReloaded(reload.copy(additions = fallbacks)) + assertEquals(listOf(kept, OrgChild.Drawable(added.id)), fallen.parts.single().children, "a missing anchor falls to the end") + assertEquals(listOf(OrgChild.Part(PartId("Part1")), OrgChild.Drawable(top.id)), fallen.rootChildren) + + val unknownPart = additions.copy(insertions = listOf(OrgInsertion(PartId("Part9"), OrgChild.Drawable(added.id), OrgSlot.End))) + assertSame(base, base.withArtworkReloaded(reload.copy(additions = unknownPart)), "a part the model lacks refuses the reload") + assertSame(base, base.withArtworkAdded(unknownPart.copy(source = sourceA.copy(id = ArtSourceId("art-1")))), "and the addition") + } + + /** A tile no drawable samples can leave the atlas; one still sampled, or one the model lacks, cannot. */ + @Test + fun anUnsampledTileCanBeDeletedAndASampledOneCannot() { + val base = model() + val orphan = AtlasTile(AtlasTileId("art-0/lyid:2"), "L2", 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), "lyid:2", true)) + val withOrphan = base.copy(atlas = base.atlas.copy(tiles = base.atlas.tiles + orphan)) + val deleted = withOrphan.withTileDeleted(orphan.id) + assertEquals(listOf(AtlasTileId("art-0/lyid:1")), deleted.atlas.tiles.map { tile -> tile.id }, "the orphan is gone") + assertEquals(withOrphan.drawables, deleted.drawables, "and nothing else moved") + assertSame(withOrphan, withOrphan.withTileDeleted(AtlasTileId("art-0/lyid:1")), "a tile a drawable samples stays") + assertSame(withOrphan, withOrphan.withTileDeleted(AtlasTileId("nope")), "an unknown tile is a no-op") + } + + /** + * The ignore mark sits on an inventory row no tile binds: a bound key, an unlisted file or key, and a + * mark already as asked are refused; the session toggles it as one step; Delete Art marks the deleted + * tile's layer only when asked, and never a key another tile still binds. + */ + @Test + fun aLayerIsIgnoredOnlyWhileUnboundAndDeleteArtMarksItOnRequest() { + val base = model() + val fileId = ArtSourceId("art-0") + assertSame(base, base.withLayerIgnored(fileId, "lyid:1", ignored = true), "a bound key is refused") + assertSame(base, base.withLayerIgnored(ArtSourceId("art-9"), "lyid:1", ignored = true), "an unlisted file") + assertSame(base, base.withLayerIgnored(fileId, "lyid:9", ignored = true), "an unlisted key") + val unbound = base.withTileSource(AtlasTileId("art-0/lyid:1"), null) + val marked = unbound.withLayerIgnored(fileId, "lyid:1", ignored = true) + assertTrue(marked.sources.single().layers.single().ignored) + assertSame(marked, marked.withLayerIgnored(fileId, "lyid:1", ignored = true), "already as asked") + assertEquals(false, marked.withLayerIgnored(fileId, "lyid:1", ignored = false).sources.single().layers.single().ignored, "cleared again") + + val session = EditorSession(unbound) + session.setLayerIgnored(SourceLayerRef(fileId, "lyid:1", stableKey = true), ignored = true) + assertTrue(session.model.value.sources.single().layers.single().ignored) + assertTrue(session.canUndo.value) + session.undo() + assertSame(unbound, session.model.value) + session.setLayerIgnored(SourceLayerRef(fileId, "lyid:1", stableKey = true), ignored = false) + assertEquals(false, session.canUndo.value, "a mark already as asked pushes nothing") + + // Delete Art: the orphan tile leaves; under the setting its layer is marked in the same step. + val orphan = AtlasTile(AtlasTileId("art-0/lyid:2"), "L2", 4, 4, source = SourceLayerRef(fileId, "lyid:2", true)) + val withOrphan = + base.copy( + atlas = base.atlas.copy(tiles = base.atlas.tiles + orphan), + sources = listOf(sourceA.copy(layers = sourceA.layers + ArtSourceLayer("lyid:2", "L2", "", 0, 0, 4, 4, true))), + ) + val plain = EditorSession(withOrphan) + plain.deleteTile(orphan.id) + assertEquals(listOf(false, false), plain.model.value.sources.single().layers.map { layer -> layer.ignored }, "a plain Delete Art marks nothing") + val marking = EditorSession(withOrphan) + marking.deleteTile(orphan.id, ignoreLayer = true) + assertEquals(listOf(AtlasTileId("art-0/lyid:1")), marking.model.value.atlas.tiles.map { tile -> tile.id }) + assertEquals(listOf(false, true), marking.model.value.sources.single().layers.map { layer -> layer.ignored }, "the deleted tile's layer is marked in the same step") + marking.undo() + assertSame(withOrphan, marking.model.value, "one undo brings the tile and the unmarked row back") + // A key another tile still binds is left unmarked: the reload matches it by key. + val twin = AtlasTile(AtlasTileId("art-0/lyid:2~1"), "L2", 4, 4, source = SourceLayerRef(fileId, "lyid:2", true)) + val shared = EditorSession(withOrphan.copy(atlas = withOrphan.atlas.copy(tiles = withOrphan.atlas.tiles + twin))) + shared.deleteTile(orphan.id, ignoreLayer = true) + assertEquals(listOf(false, false), shared.model.value.sources.single().layers.map { layer -> layer.ignored }) + assertEquals(2, shared.model.value.atlas.tiles.size, "the tile still left") + } + + /** A reload's visibility map reaches the drawables it names and no other. */ + @Test + fun aReloadAppliesTheVisibilityItDecided() { + val base = model() + val reloaded = base.withArtworkReloaded(ArtworkReload(sourceA, emptyList(), emptyMap(), null, emptyList(), drawableVisibility = mapOf(DrawableId("ArtMesh1") to false))) + assertEquals(false, reloaded.drawables.single().isVisible) + assertEquals(base.atlas, reloaded.atlas, "nothing else moved") + assertEquals(true, base.withArtworkReloaded(ArtworkReload(sourceA, emptyList(), emptyMap(), null, emptyList())).drawables.single().isVisible, "an empty map changes nothing") + } + + @Test + fun aReloadThatCollidesOrNamesTheUnknownIsRefused() { + val base = model() + val unknownOld = + ArtworkReload(sourceA, listOf(ReplacedTile(AtlasTileId("nope"), AtlasTile(AtlasTileId("nope~1"), "x", 1, 1))), emptyMap(), null, emptyList()) + assertSame(base, base.withArtworkReloaded(unknownOld), "an unknown superseded tile") + val collidingNew = + ArtworkReload(sourceA, listOf(ReplacedTile(AtlasTileId("art-0/lyid:1"), AtlasTile(AtlasTileId("art-0/lyid:1"), "x", 1, 1))), emptyMap(), null, emptyList()) + assertSame(base, base.withArtworkReloaded(collidingNew), "a replacement reusing an existing id") + val unlisted = ArtworkReload(ArtSource(ArtSourceId("art-9"), "z", null, "psd"), emptyList(), emptyMap(), null, emptyList()) + assertSame(base, base.withArtworkReloaded(unlisted), "a file the model does not list") + } + + /** + * A reload's retired tiles leave with their drawables and every reference to them scrubbed, the way a + * delete scrubs them; a retired tile the model lacks, or one the same delta also supersedes, refuses + * the whole delta. + */ + @Test + fun aReloadRetiresTheTilesItNamesWithTheirDrawables() { + val base = model() + val fresh = drawable("ArtMesh3", "art-0/lyid:3") + val freshTile = AtlasTile(AtlasTileId("art-0/lyid:3"), "L3", 4, 4, source = SourceLayerRef(ArtSourceId("art-0"), "lyid:3", true)) + val withFresh = + base.copy( + drawables = listOf(base.drawables.single().copy(maskedBy = listOf(fresh.id)), fresh), + parts = listOf(base.parts.single().copy(children = base.parts.single().children + OrgChild.Drawable(fresh.id))), + atlas = base.atlas.copy(tiles = base.atlas.tiles + freshTile), + ).withDerivedRenderRoot() + val reload = ArtworkReload(sourceA, replacedTiles = emptyList(), drawableMeshes = emptyMap(), additions = null, outgrown = emptyList(), retiredTiles = listOf(freshTile.id)) + val retired = withFresh.withArtworkReloaded(reload) + assertEquals(listOf("ArtMesh1"), retired.drawables.map { drawable -> drawable.id.raw }, "the fresh drawable is gone") + assertEquals(listOf(AtlasTileId("art-0/lyid:1")), retired.atlas.tiles.map { tile -> tile.id }, "with its tile") + assertEquals(listOf(OrgChild.Drawable(DrawableId("ArtMesh1"))), retired.parts.single().children, "and its place in the part") + assertTrue(retired.drawables.single().maskedBy.isEmpty(), "and the mask that named it") + assertEquals(retired.deriveRenderRoot(), retired.renderRoot, "the render root is re-derived") + assertSame(withFresh, withFresh.withArtworkReloaded(reload.copy(retiredTiles = listOf(AtlasTileId("nope")))), "an unknown retired tile refuses") + val alsoReplaced = ArtworkReload(sourceA, listOf(ReplacedTile(freshTile.id, AtlasTile(AtlasTileId("art-0/lyid:3~1"), "L3", 4, 4))), emptyMap(), null, emptyList(), retiredTiles = listOf(freshTile.id)) + assertSame(withFresh, withFresh.withArtworkReloaded(alsoReplaced), "a tile both superseded and retired refuses") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasPlacementEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasPlacementEditsTest.kt new file mode 100644 index 0000000..55acaa8 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasPlacementEditsTest.kt @@ -0,0 +1,335 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableLayerBinding +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.layerUvAffineOf +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the multi-tile placement edit the gizmo commits through: every drawable over each moved tile + * re-maps in one pass (drawables sharing a tile move together), untouched drawables pass their arrays + * through by reference, one fault anywhere in the map refuses the whole edit, the session commit is + * ONE undo step, the step's label names the operator that ran, a pin lands only on a placed tile and + * leaves with its placement, and the Object-mode UV latch admits exactly the selections that have + * packed art to move. + */ +class AtlasPlacementEditsTest { + private val tileAId = AtlasTileId("tileA") + private val tileBId = AtlasTileId("tileB") + private val tileCId = AtlasTileId("tileC") + private val unpackedTileId = AtlasTileId("tileUnpacked") + private val page = AtlasPage(128, 128) + + private fun placement(x: Float, y: Float, pageIndex: Int = 0): AtlasPlacement = + AtlasPlacement(pageIndex, x, y, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f) + + private fun meshedDrawable(id: String, tileId: AtlasTileId?, uvs: FloatArray): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 1f), uvs, intArrayOf(0, 0, 0)), + geometryGrid = null, + atlasTileId = tileId, + ) + + private fun storedUvsAt(artUvs: FloatArray, tileId: AtlasTileId, placed: AtlasPlacement?): FloatArray { + val binding = DrawableLayerBinding(tileId.raw, placed, page.width, page.height) + val storedToArt = assertNotNull(layerUvAffineOf(binding, 16, 16)) + return applyUvAffine(artUvs, assertNotNull(invertUvAffine(storedToArt))) + } + + private fun assertUvsClose(expected: FloatArray, actual: FloatArray, message: String) { + assertEquals(expected.size, actual.size, message) + for (componentIndex in expected.indices) { + assertTrue( + abs(expected[componentIndex] - actual[componentIndex]) < 1e-5f, + "$message: component $componentIndex expected ${expected[componentIndex]}, was ${actual[componentIndex]}", + ) + } + } + + private val placedA = placement(4f, 4f) + private val placedB = placement(40f, 40f) + private val placedC = placement(80f, 80f) + private val artUvsA1 = floatArrayOf(0.25f, 0.5f, 0.75f, 0.125f) + private val artUvsA2 = floatArrayOf(0f, 1f, 1f, 0f) + private val artUvsB = floatArrayOf(0f, 0f, 1f, 1f) + private val artUvsC = floatArrayOf(0.5f, 0.5f, 0.5f, 0.5f) + + private fun baseModel(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = listOf(Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null)), + drawables = + listOf( + meshedDrawable("dA1", tileAId, storedUvsAt(artUvsA1, tileAId, placedA)), + meshedDrawable("dA2", tileAId, storedUvsAt(artUvsA2, tileAId, placedA)), + meshedDrawable("dB", tileBId, storedUvsAt(artUvsB, tileBId, placedB)), + meshedDrawable("dC", tileCId, storedUvsAt(artUvsC, tileCId, placedC)), + meshedDrawable("dUnpacked", unpackedTileId, artUvsB.copyOf()), + meshedDrawable("dLoose", null, artUvsB.copyOf()), + ), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 200f, + worldOriginX = 50f, + worldOriginZ = 100f, + atlas = + PuppetAtlas( + pages = listOf(page), + tiles = + listOf( + AtlasTile(tileAId, "A", 16, 16, placedA), + AtlasTile(tileBId, "B", 16, 16, placedB), + AtlasTile(tileCId, "C", 16, 16, placedC), + AtlasTile(unpackedTileId, "U", 16, 16, null), + ), + ), + ) + + private fun PuppetModel.uvsOf(id: String): FloatArray = drawables.first { drawable -> drawable.id.raw == id }.mesh!!.uvs + + private fun PuppetModel.placementOf(tileId: AtlasTileId): AtlasPlacement? = atlas.tileById.getValue(tileId).placement + + private fun target(id: String): SelectionTarget = SelectionTarget.Drawable(DrawableId(id)) + + @Test + fun aMultiTileMoveRemapsEveryDrawableOverEachMovedTileInOnePass() { + val base = baseModel() + val movedA = placement(20f, 8f) + val movedB = placement(60f, 44f) + + val moved = base.withAtlasPlacements(mapOf(tileAId to movedA, tileBId to movedB)) + + assertEquals(movedA, moved.placementOf(tileAId), "tile A moved") + assertEquals(movedB, moved.placementOf(tileBId), "tile B moved") + assertEquals(placedC, moved.placementOf(tileCId), "tile C stayed") + assertUvsClose(storedUvsAt(artUvsA1, tileAId, movedA), moved.uvsOf("dA1"), "the first drawable over A follows the art") + assertUvsClose(storedUvsAt(artUvsA2, tileAId, movedA), moved.uvsOf("dA2"), "the second drawable over A follows too - a tile moves every drawable sharing it") + assertUvsClose(storedUvsAt(artUvsB, tileBId, movedB), moved.uvsOf("dB"), "the drawable over B follows the art") + assertSame(base.uvsOf("dC"), moved.uvsOf("dC"), "an untouched tile's drawable keeps its array by reference") + assertSame(base.uvsOf("dLoose"), moved.uvsOf("dLoose"), "an unbound drawable is untouched") + assertEquals(placedA, base.placementOf(tileAId), "the original model is immutable") + } + + @Test + fun oneFaultAnywhereInTheMapRefusesTheWholeEdit() { + val base = baseModel() + + val missingPage = base.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f), tileBId to placement(0f, 0f, pageIndex = 3))) + assertSame(base, missingPage, "a placement naming a page the atlas lacks refuses the whole map, not just its tile") + + val collapsed = base.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f), tileBId to AtlasPlacement(0, 0f, 0f, 0f, 1f, 0f))) + assertSame(base, collapsed, "a placement that will not invert refuses the whole map") + + val unknown = base.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f), AtlasTileId("gone") to placement(1f, 1f))) + assertSame(base, unknown, "an unknown tile refuses the whole map") + } + + @Test + fun aNoOpMapReturnsTheSameInstance() { + val base = baseModel() + assertSame(base, base.withAtlasPlacements(emptyMap()), "an empty map changes nothing") + assertSame(base, base.withAtlasPlacements(mapOf(tileAId to placedA, tileBId to placedB)), "restating every placement changes nothing") + } + + @Test + fun theSessionCommitsAMultiTileMoveAsOneStep() { + val session = EditorSession(baseModel()) + val movedA = placement(20f, 8f) + val movedB = placement(60f, 44f) + + session.setAtlasPlacements(mapOf(tileAId to movedA, tileBId to movedB)) + assertEquals(movedA, session.model.value.placementOf(tileAId)) + assertEquals(movedB, session.model.value.placementOf(tileBId)) + assertTrue(session.dirty.value, "a pack is document content, so it dirties") + assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileAId, tileBId)).labelKey) + + session.undo() + assertEquals(placedA, session.model.value.placementOf(tileAId), "one undo restores both tiles") + assertEquals(placedB, session.model.value.placementOf(tileBId), "one undo restores both tiles") + assertFalse(session.canUndo.value, "the whole gesture was one step") + assertFalse(session.dirty.value, "undo restores the saved model instance") + + session.setAtlasPlacements(mapOf(tileAId to placedA)) + assertFalse(session.canUndo.value, "a no-op commit records nothing") + } + + @Test + fun thePlacementStepIsLabelledByTheOperatorThatRan() { + assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.Grab).labelKey) + assertEquals("change.document.atlasPlacement.rotate", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.Rotate).labelKey) + assertEquals("change.document.atlasPlacement.scale", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.Scale).labelKey) + assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileAId), MeshOperatorKind.VertexSlide).labelKey, "a placement cannot slide; it moved") + val session = EditorSession(baseModel()) + session.setAtlasPlacements(mapOf(tileAId to placement(20f, 8f)), MeshOperatorKind.Rotate) + assertEquals("change.document.atlasPlacement.rotate", session.historyView.value.steps.last().labelKey, "the session's step carries the kind") + } + + @Test + fun aPinLandsOnPlacedTilesOnlyAndLeavesWithThePlacement() { + val base = baseModel() + + val pinned = base.withAtlasPins(listOf(tileAId, unpackedTileId, AtlasTileId("gone")), pinned = true) + + assertTrue(pinned.atlas.tileById.getValue(tileAId).pinned, "a placed tile pins") + assertFalse(pinned.atlas.tileById.getValue(unpackedTileId).pinned, "an unpacked tile has nothing to keep") + assertFalse(pinned.atlas.tileById.getValue(tileBId).pinned, "an unnamed tile is untouched") + assertSame(base.drawables, pinned.drawables, "a pin moves no coordinates") + assertSame(pinned, pinned.withAtlasPins(listOf(tileAId), pinned = true), "restating a pin changes nothing") + assertSame(base, base.withAtlasPins(listOf(unpackedTileId), pinned = true), "pinning only unpacked art changes nothing") + assertSame(base, base.withAtlasPins(emptyList(), pinned = true)) + + val moved = pinned.withAtlasPlacements(mapOf(tileAId to placement(20f, 8f))) + assertTrue(moved.atlas.tileById.getValue(tileAId).pinned, "a hand move keeps the pin") + val unpacked = pinned.withAtlasPlacements(mapOf(tileAId to null)) + assertFalse(unpacked.atlas.tileById.getValue(tileAId).pinned, "packing a tile out drops its pin") + val repacked = + pinned.withAtlasRepack( + listOf(page), + pinned.atlas.tiles.associate { tile -> tile.id to (if (tile.id == tileBId) placement(60f, 44f) else tile.placement) }, + ) + assertTrue(repacked.atlas.tileById.getValue(tileAId).pinned, "a repack restating the placement keeps the pin") + } + + @Test + fun theSessionPinsAsOneUndoStep() { + val session = EditorSession(baseModel()) + + session.setAtlasPins(listOf(tileAId, tileBId), pinned = true) + assertTrue(session.model.value.atlas.tileById.getValue(tileAId).pinned) + assertTrue(session.model.value.atlas.tileById.getValue(tileBId).pinned) + assertEquals("change.document.atlasPin", session.historyView.value.steps.last().labelKey) + assertTrue(session.dirty.value, "a pin is document content") + + session.setAtlasPins(listOf(tileAId), pinned = false) + assertFalse(session.model.value.atlas.tileById.getValue(tileAId).pinned) + assertTrue(session.model.value.atlas.tileById.getValue(tileBId).pinned, "unpinning one leaves the other") + assertEquals("change.document.atlasUnpin", session.historyView.value.steps.last().labelKey) + + session.undo() + session.undo() + assertFalse(session.model.value.atlas.tileById.getValue(tileBId).pinned, "two undos return to the unpinned model") + assertFalse(session.canUndo.value) + + session.setAtlasPins(listOf(unpackedTileId), pinned = true) + assertFalse(session.canUndo.value, "a no-op pin records nothing") + } + + @Test + fun placementDragTileIdsCoversPlacedTilesOfSelectedDrawablesOnly() { + val model = baseModel() + val selection = + Selection( + setOf(target("dA1"), target("dA2"), target("dUnpacked"), target("dLoose"), SelectionTarget.Deformer(DeformerId("w"))), + target("dA1"), + ) + assertEquals(setOf(tileAId), model.placementDragTileIds(selection), "two drawables over one tile name it once; unpacked and unbound art contribute nothing") + assertEquals(emptySet(), model.placementDragTileIds(Selection()), "nothing selected, nothing to move") + assertEquals(setOf(tileAId, tileBId), model.placementDragTileIds(Selection(setOf(target("dB"), target("dA2")), target("dB"))).toSet()) + } + + @Test + fun objectModeLatchesAUvOperatorOverPackedArt() { + val session = EditorSession(baseModel()) + assertEquals(EditorMode.Object, session.mode.value) + session.setSelection(Selection(setOf(target("dA1")), target("dA1"))) + + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertEquals(ActiveOperator(MeshOperatorKind.Grab, "uv-area"), session.activeUvOperator.value, "a placed selection latches") + assertNull(session.notice.value, "no notice on success") + + session.clearUvOperator() + session.beginUvOperator(MeshOperatorKind.Rotate, "uv-area") + assertEquals(MeshOperatorKind.Rotate, session.activeUvOperator.value?.kind, "rotate latches too") + session.clearUvOperator() + session.beginUvOperator(MeshOperatorKind.Scale, "uv-area") + assertEquals(MeshOperatorKind.Scale, session.activeUvOperator.value?.kind, "scale latches too") + + session.clearUvOperator() + session.beginUvOperator(MeshOperatorKind.VertexSlide, "uv-area") + assertNull(session.activeUvOperator.value, "vertex slide is not a placement operation") + } + + @Test + fun objectModeRefusesWithANoticeWhenNothingSelectedIsPacked() { + val session = EditorSession(baseModel()) + + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertNull(session.activeUvOperator.value, "an empty selection has nothing to place") + assertEquals("notice.uv.placement.noPlacedArt", session.notice.value?.messageKey) + assertEquals(NoticePlacement.NearCursor, session.notice.value?.placement) + + session.setSelection(Selection(setOf(target("dUnpacked"), target("dLoose")), target("dUnpacked"))) + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertNull(session.activeUvOperator.value, "unpacked and unbound art has nothing on a page to move") + assertEquals("notice.uv.placement.noPlacedArt", session.notice.value?.messageKey) + } + + @Test + fun aPinHoldsAgainstTheGesture() { + val session = EditorSession(baseModel().withAtlasPins(listOf(tileAId), pinned = true)) + val pinnedOnly = Selection(setOf(target("dA1"), target("dA2")), target("dA1")) + val mixed = Selection(setOf(target("dA1"), target("dB")), target("dB")) + + assertEquals(emptySet(), session.model.value.placementDragTileIds(pinnedOnly), "a pinned tile is not a mover") + assertEquals(setOf(tileAId), session.model.value.placementSelectedTileIds(pinnedOnly), "but it is still the selection's placed tile - Unpin needs it") + assertEquals(setOf(tileBId), session.model.value.placementDragTileIds(mixed), "a mixed selection moves the unpinned tile alone") + + session.setSelection(pinnedOnly) + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertNull(session.activeUvOperator.value, "an all-pinned selection has nothing to move") + assertEquals("notice.uv.placement.pinned", session.notice.value?.messageKey, "and says why") + + session.setSelection(mixed) + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertEquals(MeshOperatorKind.Grab, session.activeUvOperator.value?.kind, "a mixed selection latches over its unpinned tile") + } + + @Test + fun objectModeRefusesALayerAddressedDocument() { + val base = baseModel() + val session = EditorSession(base.copy(atlas = base.atlas.copy(storedUvsAddressPages = false))) + session.setSelection(Selection(setOf(target("dA1")), target("dA1"))) + + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertNull(session.activeUvOperator.value, "coordinates that address the art have no page placement to move") + assertEquals("notice.uv.placement.layerAddressed", session.notice.value?.messageKey) + } + + @Test + fun editModeStillNeedsAMeshSelection() { + val session = EditorSession(baseModel()) + session.setSelection(Selection(setOf(target("dA1")), target("dA1"))) + session.setMode(EditorMode.Edit) + + session.beginUvOperator(MeshOperatorKind.Grab, "uv-area") + assertNull(session.activeUvOperator.value, "Edit mode moves texture coordinates and has none selected") + assertNull(session.notice.value, "an empty Edit selection stays a silent no-op") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasPlacementTransformsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasPlacementTransformsTest.kt new file mode 100644 index 0000000..b40e370 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasPlacementTransformsTest.kt @@ -0,0 +1,141 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.composeAffine +import org.umamo.runtime.model.placementAffine +import kotlin.math.PI +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the placement gizmo's algebra: composing a gesture affine onto a placement yields a placement + * whose forward transform IS the product (so the preview and the commit agree to float precision), + * each operator's page-space affine lands on the TRS component it means to, a mirrored placement keeps + * its mirror, and the two products no placement can express - a page-axis non-uniform scale on a + * rotated tile, and a collapsed axis - are refused rather than approximated. + */ +class AtlasPlacementTransformsTest { + private fun placement( + x: Float, + y: Float, + scaleX: Float = 1f, + scaleY: Float = 1f, + rotationDegrees: Float = 0f, + ): AtlasPlacement = AtlasPlacement(0, x, y, scaleX, scaleY, rotationDegrees) + + private fun radians(degrees: Float): Float = (degrees.toDouble() * PI / 180.0).toFloat() + + private fun assertClose(expected: Float, actual: Float, message: String) { + assertTrue(abs(expected - actual) < 1e-3f, "$message: expected $expected, was $actual") + } + + private fun assertAffineClose(expected: FloatArray, actual: FloatArray, message: String) { + for (componentIndex in expected.indices) { + assertClose(expected[componentIndex], actual[componentIndex], "$message (component $componentIndex)") + } + } + + /** + * Composes and asserts the load-bearing property: the result's forward affine is the product of the + * gesture and the original, so what the gizmo previewed is what the placement stores. + * + * @param AtlasPlacement original The placement before the gesture. + * @param FloatArray gesture The gesture's page-space affine. + * @return AtlasPlacement The composed placement. + */ + private fun assertComposesExactly(original: AtlasPlacement, gesture: FloatArray): AtlasPlacement { + val composed = assertNotNull(original.composedWith(gesture), "the product is a placement") + assertAffineClose( + composeAffine(gesture, placementAffine(original)), + placementAffine(composed), + "the composed placement's forward affine is the gesture applied after the original", + ) + return composed + } + + @Test + fun aTranslationMovesThePositionAndNothingElse() { + val moved = assertComposesExactly(placement(10f, 20f, rotationDegrees = 30f), translationAffine(5f, -3f)) + assertClose(15f, moved.positionX, "x moved by the delta") + assertClose(17f, moved.positionY, "y moved by the delta") + assertClose(1f, moved.scaleX, "scale x untouched") + assertClose(1f, moved.scaleY, "scale y untouched") + assertClose(30f, moved.rotationDegrees, "rotation untouched") + } + + @Test + fun aRotationAboutAPivotAddsToTheAngleAndOrbitsThePosition() { + val original = placement(10f, 20f, rotationDegrees = 30f) + val rotated = assertComposesExactly(original, rotationAboutAffine(50f, 60f, radians(90f))) + assertClose(120f, rotated.rotationDegrees, "the gesture angle adds to the placement's") + assertClose(1f, rotated.scaleX, "scale x untouched") + assertClose(1f, rotated.scaleY, "scale y untouched") + // The origin orbits the pivot: (10, 20) is (-40, -40) from it, a quarter turn lands at (40, -40). + assertClose(90f, rotated.positionX, "the origin orbited the pivot in x") + assertClose(20f, rotated.positionY, "the origin orbited the pivot in y") + } + + @Test + fun aUniformScaleAboutAPivotMultipliesBothScalesAndKeepsTheAngle() { + val original = placement(10f, 20f, rotationDegrees = 45f) + val scaled = assertComposesExactly(original, scaleAboutAffine(50f, 60f, 2f, 2f)) + assertClose(2f, scaled.scaleX, "scale x doubled") + assertClose(2f, scaled.scaleY, "scale y doubled") + assertClose(45f, scaled.rotationDegrees, "rotation untouched") + assertClose(-30f, scaled.positionX, "the origin moved away from the pivot in x") + assertClose(-20f, scaled.positionY, "the origin moved away from the pivot in y") + } + + @Test + fun aLocalAxisScaleOnARotatedPlacementStaysExpressible() { + val original = placement(10f, 20f, rotationDegrees = 30f) + val gesture = localAxisScaleAboutAffine(original, 50f, 60f, 2f, 1f) + val scaled = assertComposesExactly(original, gesture) + assertClose(2f, scaled.scaleX, "the tile's own x axis scaled") + assertClose(1f, scaled.scaleY, "the tile's own y axis untouched") + assertClose(30f, scaled.rotationDegrees, "rotation untouched") + } + + @Test + fun aLocalAxisScaleOnAnUnrotatedPlacementIsThePageAxisScale() { + val original = placement(10f, 20f) + assertAffineClose( + scaleAboutAffine(50f, 60f, 2f, 0.5f), + localAxisScaleAboutAffine(original, 50f, 60f, 2f, 0.5f), + "with no rotation the tile axes are the page axes", + ) + } + + @Test + fun aPageAxisNonUniformScaleOnARotatedPlacementIsRefused() { + val original = placement(10f, 20f, rotationDegrees = 30f) + assertNull(original.composedWith(scaleAboutAffine(50f, 60f, 2f, 1f)), "a shear is not a placement") + } + + @Test + fun aMirroredPlacementKeepsItsMirrorThroughAMove() { + val original = placement(10f, 20f, scaleX = -1f, rotationDegrees = 15f) + val moved = assertComposesExactly(original, translationAffine(4f, 4f)) + assertClose(-1f, moved.scaleX, "the mirror survives as a negative x scale, not as a half-turn") + assertClose(1f, moved.scaleY, "scale y untouched") + assertClose(15f, moved.rotationDegrees, "rotation untouched") + } + + @Test + fun aReducedImportedPlacementComposesAtItsOwnScale() { + // The corpus packs art reduced (modelC scales most of its tiles); a nudge must keep that scale. + val original = placement(100f, 200f, scaleX = 0.5f, scaleY = 0.5f, rotationDegrees = 270f) + val moved = assertComposesExactly(original, translationAffine(-10f, 6f)) + assertClose(0.5f, moved.scaleX, "scale x kept") + assertClose(0.5f, moved.scaleY, "scale y kept") + assertClose(-90f, moved.rotationDegrees, "the angle comes back normalized to (-180, 180]") + } + + @Test + fun aDegenerateProductIsRefused() { + assertNull(placement(10f, 20f, scaleX = 0f).composedWith(translationAffine(1f, 1f)), "a collapsed axis cannot be placed") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasRepackEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasRepackEditsTest.kt new file mode 100644 index 0000000..990885d --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/AtlasRepackEditsTest.kt @@ -0,0 +1,301 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AtlasComposition +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableLayerBinding +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.layerUvAffineOf +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the whole-atlas repack edit: pages and placements install atomically with every bound + * drawable's coordinates re-derived against the NEW page inventory (the exact read a per-tile fold + * gets wrong), unchanged mappings pass arrays through by reference, the session commit is one undo + * step under its own label, and malformed input throws instead of half-applying. + */ +class AtlasRepackEditsTest { + private val tileAId = AtlasTileId("tileA") + private val tileBId = AtlasTileId("tileB") + + private fun placement(pageIndex: Int, x: Float, y: Float): AtlasPlacement = + AtlasPlacement(pageIndex, x, y, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f) + + private fun meshedDrawable(id: String, tileId: AtlasTileId, uvs: FloatArray): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 1f), uvs, intArrayOf(0, 0, 0)), + geometryGrid = null, + atlasTileId = tileId, + ) + + private fun packedModel(atlas: PuppetAtlas, drawables: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 200f, + worldOriginX = 50f, + worldOriginZ = 100f, + atlas = atlas, + ) + + /** + * The stored coordinates a tile's art uvs take under one placement, built independently of the + * edit's internals from the same corpus-proven affine algebra. + * + * @param FloatArray artUvs Coordinates in the tile's own frame. + * @param AtlasTileId tileId The tile they belong to. + * @param AtlasPlacement? placed Where the tile sits. + * @param AtlasPage page The page the placement names. + * @param Int tileSide The square tile's side in pixels. + * @return FloatArray The page-addressed stored coordinates. + */ + private fun storedUvsAt( + artUvs: FloatArray, + tileId: AtlasTileId, + placed: AtlasPlacement?, + page: AtlasPage, + tileSide: Int, + ): FloatArray { + val binding = DrawableLayerBinding(tileId.raw, placed, page.width, page.height) + val storedToArt = assertNotNull(layerUvAffineOf(binding, tileSide, tileSide)) + return applyUvAffine(artUvs, assertNotNull(invertUvAffine(storedToArt))) + } + + private fun assertUvsClose(expected: FloatArray, actual: FloatArray, message: String) { + assertEquals(expected.size, actual.size, message) + for (componentIndex in expected.indices) { + assertTrue( + abs(expected[componentIndex] - actual[componentIndex]) < 1e-5f, + "$message: component $componentIndex expected ${expected[componentIndex]}, was ${actual[componentIndex]}", + ) + } + } + + @Test + fun repackInstallsPagesAndPlacementsAndKeepsEveryVertexOnItsArtPixel() { + val oldPage = AtlasPage(64, 64) + val newPage = AtlasPage(128, 128) + val oldA = placement(0, 4f, 4f) + val oldB = placement(0, 40f, 40f) + val atlas = + PuppetAtlas( + pages = listOf(oldPage), + tiles = listOf(AtlasTile(tileAId, "A", 16, 16, oldA), AtlasTile(tileBId, "B", 16, 16, oldB)), + ) + val artUvsA = floatArrayOf(0.25f, 0.5f, 0.75f, 0.125f) + val artUvsB = floatArrayOf(0f, 0f, 1f, 1f) + val base = + packedModel( + atlas, + listOf( + meshedDrawable("dA", tileAId, storedUvsAt(artUvsA, tileAId, oldA, oldPage, 16)), + meshedDrawable("dB", tileBId, storedUvsAt(artUvsB, tileBId, oldB, oldPage, 16)), + ), + ) + val newA = placement(0, 100f, 8f) + val newB = placement(0, 8f, 100f) + + val repacked = base.withAtlasRepack(listOf(newPage), mapOf(tileAId to newA, tileBId to newB)) + + assertEquals(listOf(newPage), repacked.atlas.pages, "the page inventory was replaced") + assertEquals(newA, repacked.atlas.tiles[0].placement) + assertEquals(newB, repacked.atlas.tiles[1].placement) + assertUvsClose( + storedUvsAt(artUvsA, tileAId, newA, newPage, 16), + repacked.drawables[0].mesh!!.uvs, + "tile A's drawable still addresses the same art pixels at the new spot", + ) + assertUvsClose( + storedUvsAt(artUvsB, tileBId, newB, newPage, 16), + repacked.drawables[1].mesh!!.uvs, + "tile B's drawable still addresses the same art pixels at the new spot", + ) + assertSame( + base.drawables[0].mesh!!.positions, + repacked.drawables[0].mesh!!.positions, + "moving art on a page never moves the mesh", + ) + } + + @Test + fun repackRederivesAgainstTheNewPageDimensionsNotTheOld() { + // The placement does not move at all; only the page grows. A fold through the per-tile edit + // would read the new mapping off the old 64px inventory and leave these coordinates untouched. + val samePlacement = placement(0, 4f, 4f) + val atlas = + PuppetAtlas( + pages = listOf(AtlasPage(64, 64)), + tiles = listOf(AtlasTile(tileAId, "A", 16, 16, samePlacement)), + ) + val artUvs = floatArrayOf(0.5f, 0.5f) + val base = + packedModel( + atlas, + listOf(meshedDrawable("dA", tileAId, storedUvsAt(artUvs, tileAId, samePlacement, AtlasPage(64, 64), 16))), + ) + + val repacked = base.withAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to samePlacement)) + + assertUvsClose( + storedUvsAt(artUvs, tileAId, samePlacement, AtlasPage(128, 128), 16), + repacked.drawables.single().mesh!!.uvs, + "the coordinates renormalized against the new page size", + ) + } + + @Test + fun anUnchangedMappingPassesItsCoordinateArraysThroughByReference() { + val oldPage = AtlasPage(64, 64) + val stayA = placement(0, 4f, 4f) + val oldB = placement(0, 40f, 40f) + val atlas = + PuppetAtlas( + pages = listOf(oldPage), + tiles = listOf(AtlasTile(tileAId, "A", 16, 16, stayA), AtlasTile(tileBId, "B", 16, 16, oldB)), + ) + val base = + packedModel( + atlas, + listOf( + meshedDrawable("dA", tileAId, floatArrayOf(0.1f, 0.1f)), + meshedDrawable("dB", tileBId, floatArrayOf(0.7f, 0.7f)), + ), + ) + + val repacked = base.withAtlasRepack(listOf(oldPage), mapOf(tileAId to stayA, tileBId to placement(0, 8f, 40f))) + + assertSame(base.drawables[0].mesh, repacked.drawables[0].mesh, "an unmoved tile's drawable is untouched") + assertFalse( + base.drawables[1].mesh!!.uvs.contentEquals(repacked.drawables[1].mesh!!.uvs), + "the moved tile's drawable re-derived", + ) + + val unchanged = base.withAtlasRepack(listOf(oldPage), mapOf(tileAId to stayA, tileBId to oldB)) + assertSame(base, unchanged, "restating the atlas exactly is a no-op") + } + + @Test + fun anUnpackedTileLowersItsArtFrameCoordinatesOntoThePage() { + val page = AtlasPage(64, 64) + val atlas = + PuppetAtlas( + pages = listOf(page), + tiles = listOf(AtlasTile(tileAId, "A", 16, 16, placement = null)), + ) + // Unpacked art stores its coordinates in the tile's own frame. + val artUvs = floatArrayOf(0.25f, 0.5f) + val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, artUvs.copyOf()))) + val placed = placement(0, 32f, 16f) + + val repacked = base.withAtlasRepack(listOf(page), mapOf(tileAId to placed)) + + assertUvsClose( + storedUvsAt(artUvs, tileAId, placed, page, 16), + repacked.drawables.single().mesh!!.uvs, + "packing never-packed art lowers its coordinates onto the page", + ) + } + + @Test + fun sessionCommitIsOneUndoStepUnderItsOwnLabel() { + val oldPage = AtlasPage(64, 64) + val oldA = placement(0, 4f, 4f) + val atlas = PuppetAtlas(pages = listOf(oldPage), tiles = listOf(AtlasTile(tileAId, "A", 16, 16, oldA))) + val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, floatArrayOf(0.2f, 0.3f)))) + val session = EditorSession(base) + val storedBefore = session.model.value.drawables.single().mesh!!.uvs.copyOf() + + session.commitAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to placement(0, 60f, 60f))) + assertEquals(listOf(AtlasPage(128, 128)), session.model.value.atlas.pages) + assertTrue(session.dirty.value, "a repack is document content, so it dirties") + assertEquals("change.document.atlasRepack", DocumentChange.RepackAtlas(1, 1).labelKey) + + session.undo() + assertEquals(listOf(oldPage), session.model.value.atlas.pages, "one undo restores the whole repack") + assertContentEquals(storedBefore, session.model.value.drawables.single().mesh!!.uvs) + assertFalse(session.dirty.value, "undo restores the saved model instance") + + // Restating the current state commits nothing. + session.commitAtlasRepack(listOf(oldPage), mapOf(tileAId to oldA)) + assertFalse(session.canUndo.value) + } + + @Test + fun theCompositionLandsOnTheAtlasAndRidesUndo() { + val oldPage = AtlasPage(64, 64) + val oldA = placement(0, 4f, 4f) + val atlas = PuppetAtlas(pages = listOf(oldPage), tiles = listOf(AtlasTile(tileAId, "A", 16, 16, oldA))) + val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, floatArrayOf(0.2f, 0.3f)))) + val session = EditorSession(base) + val policy = AtlasComposition(alphaThreshold = 64, extrude = 0) + + session.commitAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to placement(0, 60f, 60f)), policy) + assertEquals(policy, session.model.value.atlas.composition, "the pack's policy is recorded beside its placements") + + session.undo() + assertEquals(AtlasComposition.Default, session.model.value.atlas.composition, "undo restores the policy the earlier pages derive under") + + // A repack that names no policy keeps the atlas's current one, and a policy change alone is a change. + val repacked = session.model.value.withAtlasRepack(listOf(AtlasPage(128, 128)), mapOf(tileAId to placement(0, 60f, 60f))) + assertEquals(AtlasComposition.Default, repacked.atlas.composition) + val recomposed = repacked.withAtlasRepack(repacked.atlas.pages, mapOf(tileAId to placement(0, 60f, 60f)), policy) + assertEquals(policy, recomposed.atlas.composition, "the same placements under a new policy still produce a new atlas") + } + + @Test + fun malformedInputThrowsInsteadOfHalfApplying() { + val page = AtlasPage(64, 64) + val atlas = + PuppetAtlas( + pages = listOf(page), + tiles = listOf(AtlasTile(tileAId, "A", 16, 16, placement(0, 4f, 4f))), + ) + val base = packedModel(atlas, listOf(meshedDrawable("dA", tileAId, floatArrayOf(0.2f, 0.3f)))) + + assertFailsWith("a repack must restate every tile") { + base.withAtlasRepack(listOf(page), emptyMap()) + } + assertFailsWith("a placement must name a page the repack ships") { + base.withAtlasRepack(listOf(page), mapOf(tileAId to placement(3, 4f, 4f))) + } + + // A bound tile whose old mapping cannot invert has no expressible re-derivation. + val degenerate = + base.copy( + atlas = + atlas.copy( + tiles = listOf(AtlasTile(tileAId, "A", 16, 16, AtlasPlacement(0, 4f, 4f, 0f, 0f, 0f))), + ), + ) + assertFailsWith("a bound tile with a degenerate mapping is refused") { + degenerate.withAtlasRepack(listOf(page), mapOf(tileAId to placement(0, 8f, 8f))) + } + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ChannelPreviewEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ChannelPreviewEditsTest.kt new file mode 100644 index 0000000..de587b1 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ChannelPreviewEditsTest.kt @@ -0,0 +1,241 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The two-phase contract behind a property field's drag-scrub: preview is transient, commit is one step. + * + * A scrub that only reported its value on release moved the number and nothing else, so the viewport sat + * still for the whole gesture; one that committed per frame would bury the history under drag noise. + */ +class ChannelPreviewEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val drawableId = DrawableId("d") + private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY) + + /** The descriptor a real opacity row supplies - the same one whichever branch stores the value. */ + private fun opacityChange(opacity: Float): Change = DrawableChange.SetOpacity(drawableId, opacity) + + /** A drawable whose opacity channel is keyed when [keyed], and bare otherwise. */ + private fun model(keyed: Boolean): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(angleX, "ParamAngleX", min = -30f, max = 30f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + opacity = 1f, + channelGrids = + if (!keyed) { + ChannelGrids.Empty + } else { + ChannelGrids( + mapOf( + FormChannel.OPACITY to + KeyformGrid( + axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))), + cells = + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(1f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)), + KeyformCell(intArrayOf(2), ChannelValue.Scalar(1f)), + ), + ), + ), + ) + }, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** A preview reaches the renderer's override map without touching the document or the history. */ + @Test + fun previewIsTransientOnAnUnkeyedChannel() { + val session = EditorSession(model(keyed = false)) + session.previewChannelEdit(target, ChannelValue.Scalar(0.25f)) + + assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target]) + assertEquals(1f, session.model.value.drawables.first().opacity, "the document is untouched") + assertTrue(!session.canUndo.value, "a preview records no undo step") + } + + /** + * Committing an unkeyed channel writes the static AND retires the preview. + * + * Without the retire the stale pending value keeps shadowing the static just written, so the field + * stays tinted as an uncommitted edit even though the edit landed. + */ + @Test + fun commitOnAnUnkeyedChannelWritesTheStaticAndRetiresThePreview() { + val session = EditorSession(model(keyed = false)) + session.previewChannelEdit(target, ChannelValue.Scalar(0.25f)) + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + + assertEquals(0.25f, session.model.value.drawables.first().opacity) + assertEquals(null, session.pendingChannelEdits.value[target], "the preview is retired") + assertTrue(session.canUndo.value, "the commit is one undo step") + } + + /** A whole scrub is ONE undo step however many frames it previewed through. */ + @Test + fun aScrubIsOneUndoStep() { + val session = EditorSession(model(keyed = false)) + for (frame in 1..20) { + session.previewChannelEdit(target, ChannelValue.Scalar(frame / 20f)) + } + session.editKeyedChannel(target, ChannelValue.Scalar(1f), opacityChange(1f)) { + session.setDrawableOpacity(drawableId, 0.5f) + } + session.undo() + + assertEquals(1f, session.model.value.drawables.first().opacity, "one undo returns to the start") + assertTrue(!session.canUndo.value, "and there was only ever one step") + } + + /** + * On a KEYED channel a commit stays pending, because writing the static would be shadowed by the track. + */ + @Test + fun commitOnAKeyedChannelStaysPending() { + val session = EditorSession(model(keyed = true)) + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + + assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target]) + assertEquals(1f, session.model.value.drawables.first().opacity, "the static is not the store here") + } + + /** + * A pending edit is an undo step, and undoing it puts the previous pending value back. + * + * The value is transient - the next pose move discards it - but discarding is not the same as never + * having happened. It shows in the viewport the moment it is made, which is the whole test of whether + * something belongs in history; Blender records the equivalent edit and the panel promises the same. + */ + @Test + fun aPendingEditIsItsOwnUndoStep() { + val session = EditorSession(model(keyed = true)) + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + assertTrue(session.canUndo.value, "the commit is one undo step") + + session.editKeyedChannel(target, ChannelValue.Scalar(0.5f), opacityChange(0.5f)) { + session.setDrawableOpacity(drawableId, 0.5f) + } + session.undo() + + assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target], "back one edit") + session.undo() + assertEquals(null, session.pendingChannelEdits.value[target], "and back to none") + } + + /** Previewing per frame records nothing; only the gesture's end does. */ + @Test + fun aScrubOnAKeyedChannelIsAlsoOneUndoStep() { + val session = EditorSession(model(keyed = true)) + for (frame in 1..20) { + session.previewChannelEdit(target, ChannelValue.Scalar(frame / 20f)) + } + assertTrue(!session.canUndo.value, "twenty preview frames are not twenty steps") + + session.editKeyedChannel(target, ChannelValue.Scalar(1f), opacityChange(1f)) { + session.setDrawableOpacity(drawableId, 1f) + } + session.undo() + + assertEquals(null, session.pendingChannelEdits.value[target], "one undo clears the whole scrub") + assertTrue(!session.canUndo.value, "and there was only ever one step") + } + + /** A pose move still discards every pending value - undo restores them, a scrub does not. */ + @Test + fun aPoseMoveStillDiscardsAPendingEdit() { + val session = EditorSession(model(keyed = true)) + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + session.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f)) + + assertEquals(null, session.pendingChannelEdits.value[target], "the value was chosen for the old pose") + + session.undo() + assertEquals(ChannelValue.Scalar(0.25f), session.pendingChannelEdits.value[target], "undo brings it back") + } + + /** Retiring one target's preview leaves every other target's alone. */ + @Test + fun retiringOnePreviewLeavesTheOthers() { + val session = EditorSession(model(keyed = false)) + val other = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.DRAW_ORDER) + session.previewChannelEdit(target, ChannelValue.Scalar(0.25f)) + session.previewChannelEdit(other, ChannelValue.Scalar(720f)) + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + + assertEquals(null, session.pendingChannelEdits.value[target]) + assertEquals(ChannelValue.Scalar(720f), session.pendingChannelEdits.value[other], "the other survives") + } + + /** + * Re-typing a value the live step already records still puts it back in the viewport. + * + * The commit's no-op guard asks history, not the live map, and that is right - a scrub has already + * written its last preview frame there. But the two DO diverge: a pose scrub retires pending edits + * through the preview path, which records nothing, so a scrub that ends where it began leaves history + * holding a value the live map no longer has. Returning outright then dropped the re-typed value on the + * floor: no override reached the renderer and the field showed none of its uncommitted-edit tint. + */ + @Test + fun reTypingAValueHistoryStillHoldsRepublishesIt() { + val session = EditorSession(model(keyed = true)) + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + // What a scrub away and back does: the preview path retires the pending edit without recording that + // it did, and the commit then declines because the pose came home. + session.clearPendingChannelEdits() + session.commitPose(ParameterChange.SetValue(listOf(angleX)), session.pose.value) + assertEquals(null, session.pendingChannelEdits.value[target], "the scrub retired it") + + session.editKeyedChannel(target, ChannelValue.Scalar(0.25f), opacityChange(0.25f)) { + session.setDrawableOpacity(drawableId, 0.25f) + } + + assertEquals( + ChannelValue.Scalar(0.25f), + session.pendingChannelEdits.value[target], + "the re-typed value is live again even though the step records nothing new", + ) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/DeformerCreateEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/DeformerCreateEditsTest.kt new file mode 100644 index 0000000..4df8ee3 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/DeformerCreateEditsTest.kt @@ -0,0 +1,276 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies warp-deformer create: lattice fit, drawable bind + UV remap, and the session selection / + * refuse paths. + */ +class DeformerCreateEditsTest { + private val drawableA = DrawableId("a") + private val drawableB = DrawableId("b") + private val partId = PartId("p") + private val angleX = ParameterId("ParamAngleX") + + private fun mesh(positions: FloatArray): DrawableMesh = + DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2)) + + private fun drawable(id: DrawableId, positions: FloatArray, parent: DeformerId? = null, grid: KeyformGrid? = null): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = parent, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = mesh(positions), + geometryGrid = grid, + ) + + private fun model(drawables: List, deformers: List = emptyList()): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(angleX, "Angle X", -1f, 1f, 0f)), + parts = listOf(Part(partId, "P", drawables.map { OrgChild.Drawable(it.id) })), + deformers = deformers, + drawables = drawables, + rootChildren = listOf(OrgChild.Part(partId)), + rootPartId = null, + ) + + /** A 1×1 lattice is four corners of the rect, row-major with Y ascending. */ + @Test + fun rectLatticeIsRowMajorYAscending() { + val points = rectLatticeControlPoints(0f, 10f, 20f, 30f, rows = 1, columns = 1) + assertEquals(listOf(0f, 10f, 20f, 10f, 0f, 30f, 20f, 30f), points.toList()) + } + + /** Creating a warp wraps the drawable, remaps rest positions into UV, and keeps the art put. */ + @Test + fun createWarpBindsAndRemapsDrawable() { + val start = + model( + listOf( + drawable(drawableA, floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f)), + ), + ) + val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp Deformer", listOf(drawableA)) + val warp = after.deformers.filterIsInstance().single() + assertEquals(DeformerId("Warp"), warp.id) + assertEquals(partId, warp.partId) + assertNotNull(warp.geometryGrid) + val bound = after.drawables.single { it.id == drawableA } + assertEquals(DeformerId("Warp"), bound.parentDeformerId) + // With 5% padding on a 10×10 box from (0,0)-(10,10): lattice is (-0.5,-0.5)-(10.5,10.5). + // Corner (0,0) → ((0+0.5)/11, (0+0.5)/11). + val positions = assertNotNull(bound.mesh).positions + assertEquals((0.5f / 11f), positions[0], absoluteTolerance = 1e-5f) + assertEquals((0.5f / 11f), positions[1], absoluteTolerance = 1e-5f) + // The rest lattice samples at any pose (0-axis grid). + assertNotNull(warpControlPointsAt(warp.geometryGrid, { 0f })) + } + + /** Keyed mesh deltas scale with the lattice extent so morphs stay correct after the UV remap. */ + @Test + fun createWarpRemapsKeyedDeltas() { + val grid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(11f, 0f, 11f, 0f, 11f, 0f))), + ), + ) + val start = model(listOf(drawable(drawableA, floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f), grid = grid))) + val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA)) + val remapped = assertNotNull(after.drawables.single().geometryGrid) + val high = remapped.cells.single { it.coordinate.single() == 1 }.form.positionDeltas + // width = 11 after padding; 11 / 11 = 1. + assertEquals(1f, high[0], absoluteTolerance = 1e-5f) + } + + /** Already-parented drawables insert the new warp under their shared parent. */ + @Test + fun alreadyParentedDrawableInsertsUnderSharedParent() { + val existing = + Deformer.Warp( + DeformerId("Existing"), + "Existing", + parent = null, + partId = partId, + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = + KeyformGrid( + emptyList(), + listOf(KeyformCell(IntArray(0), WarpLatticeForm(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f)))), + ), + ) + val start = + model( + listOf(drawable(drawableA, floatArrayOf(0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f), parent = DeformerId("Existing"))), + listOf(existing), + ) + val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA)) + val warp = after.deformers.filterIsInstance().single { it.id == DeformerId("Warp") } + assertEquals(DeformerId("Existing"), warp.parent) + assertEquals(DeformerId("Warp"), after.drawables.single { it.id == drawableA }.parentDeformerId) + } + + /** + * Cubism-style parented meshes keep canvas units in the rest buffer and land in parent UV only + * after default-pose deltas — the new lattice must fit that UV AABB, not the canvas rest. + */ + @Test + fun parentedKeyedMeshFitsLatticeInParentUv() { + val existing = + Deformer.Warp( + DeformerId("Existing"), + "Existing", + parent = null, + partId = partId, + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = + KeyformGrid( + emptyList(), + listOf(KeyformCell(IntArray(0), WarpLatticeForm(floatArrayOf(0f, 0f, 100f, 0f, 0f, 100f, 100f, 100f)))), + ), + ) + // Rest in canvas-ish units; deltas pull the default pose into parent UV ≈ (0.2,0.2)-(0.8,0.8). + val rest = floatArrayOf(20f, 20f, 80f, 20f, 20f, 80f) + val deltas = floatArrayOf(-19.8f, -19.8f, -79.2f, -19.8f, -19.8f, -79.2f) + val grid = + KeyformGrid( + emptyList(), + listOf(KeyformCell(IntArray(0), MeshDeltaForm(deltas))), + ) + val start = + model( + listOf(drawable(drawableA, rest, parent = DeformerId("Existing"), grid = grid)), + listOf(existing), + ) + val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA)) + val warp = after.deformers.filterIsInstance().single { it.id == DeformerId("Warp") } + val cps = assertNotNull(warpControlPointsAt(warp.geometryGrid) { 0f }) + // UV fit of (0.2,0.2)-(0.8,0.8) with 5% pad → (0.17,0.17)-(0.83,0.83); all CPs stay in ~[0,1]. + for (index in cps.indices) { + assertTrue(cps[index] in -0.05f..1.05f, "cp[$index]=${cps[index]} should be parent-UV, not canvas") + } + assertTrue(cps[0] < 0.25f) + assertTrue(cps[cps.size - 2] > 0.75f) + } + + /** Mixed parent deformers among the create list refuse the whole op. */ + @Test + fun mixedParentsRefuse() { + val parentA = + Deformer.Warp( + DeformerId("A"), + "A", + null, + partId, + 1, + 1, + true, + KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(FloatArray(8))))), + ) + val parentB = + Deformer.Warp( + DeformerId("B"), + "B", + null, + partId, + 1, + 1, + true, + KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(FloatArray(8))))), + ) + val start = + model( + listOf( + drawable(drawableA, floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), parent = DeformerId("A")), + drawable(drawableB, floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), parent = DeformerId("B")), + ), + listOf(parentA, parentB), + ) + assertTrue(start === start.withWarpDeformerCreatedForDrawables(DeformerId("Warp"), "Warp", listOf(drawableA, drawableB))) + } + + /** Session create selects the new deformer; an empty selection notices and returns null. */ + @Test + fun sessionCreateSelectsWarpAndRefusesEmpty() { + val session = + EditorSession( + model( + listOf( + drawable(drawableA, floatArrayOf(0f, 0f, 4f, 0f, 0f, 4f)), + drawable(drawableB, floatArrayOf(10f, 10f, 14f, 10f, 10f, 14f)), + ), + ), + ) + assertNull(session.createWarpDeformerForSelection("Warp Deformer")) + assertEquals("notice.deformer.createWarp.none", session.notice.value?.messageKey) + + session.setMode(EditorMode.Edit) + session.setSelection(Selection(setOf(SelectionTarget.Drawable(drawableA)), SelectionTarget.Drawable(drawableA))) + val id = assertNotNull(session.createWarpDeformerForSelection("Warp Deformer")) + assertEquals(SelectionTarget.Deformer(id), session.selection.value.active) + assertEquals(EditorMode.Object, session.mode.value) + assertEquals(id, session.model.value.drawables.first { it.id == drawableA }.parentDeformerId) + } + + /** A part selection expands to its subtree meshes. */ + @Test + fun partSelectionExpandsToMeshes() { + val start = + model( + listOf( + drawable(drawableA, floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f)), + drawable(drawableB, floatArrayOf(4f, 4f, 6f, 4f, 4f, 6f)), + ), + ) + val ids = + start.drawablesForWarpCreate(Selection(setOf(SelectionTarget.Part(partId)), SelectionTarget.Part(partId))) + assertEquals(listOf(drawableA, drawableB), ids) + } + + /** freshDeformerId skips collisions. */ + @Test + fun freshIdAvoidsCollision() { + val existing = + Deformer.Warp( + DeformerId("Warp"), + "Warp", + null, + null, + 1, + 1, + true, + KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(FloatArray(8))))), + ) + assertEquals(DeformerId("Warp2"), model(emptyList(), listOf(existing)).freshDeformerId()) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/EditKeyedChannelTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/EditKeyedChannelTest.kt new file mode 100644 index 0000000..12a570e --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/EditKeyedChannelTest.kt @@ -0,0 +1,99 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins the ONE keyable-row edit-routing rule: a KEYED channel's typed value goes pending (writing the + * static would be shadowed by the track, so the edit would appear silently rejected), and an unkeyed + * channel writes the static. Centralized here rather than hand-copied per row, since a rule duplicated + * across every row is exactly the kind of thing that drifts - some rows carry it correctly and others + * silently do not. + */ +class EditKeyedChannelTest { + private val angleX = ParameterId("ParamAngleX") + private val drawableId = DrawableId("d") + private val keyedTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY) + private val unkeyedTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR) + + /** The descriptor a real opacity row supplies - the same one whichever branch stores the value. */ + private fun change(opacity: Float): Change = DrawableChange.SetOpacity(drawableId, opacity) + + private fun session(): EditorSession { + val opacityTrack = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf>( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(0.25f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)), + ), + ) + val drawable = + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack)), + ) + return EditorSession( + PuppetModel( + parameters = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + } + + /** A keyed channel's edit goes pending; the static write path must not run. */ + @Test + fun aKeyedChannelGoesPending() { + val editorSession = session() + var staticWrites = 0 + + editorSession.editKeyedChannel(keyedTarget, ChannelValue.Scalar(0.5f), change(0.5f)) { staticWrites++ } + + assertEquals(0, staticWrites, "the shadowed static must not be written") + assertEquals( + ChannelValue.Scalar(0.5f), + editorSession.pendingChannelEdits.value[keyedTarget], + "the typed value waits as a pending edit for `I`", + ) + assertTrue(editorSession.canUndo.value, "and it is still one undo step") + } + + /** An unkeyed channel has no track to shadow it, so the static is the real store. */ + @Test + fun anUnkeyedChannelWritesTheStatic() { + val editorSession = session() + var staticWrites = 0 + + editorSession.editKeyedChannel(unkeyedTarget, ChannelValue.Scalar(0.5f), change(0.5f)) { staticWrites++ } + + assertEquals(1, staticWrites, "the unkeyed path writes the static") + assertFalse(unkeyedTarget in editorSession.pendingChannelEdits.value, "nothing is left pending") + assertTrue(editorSession.pendingChannelEdits.value.isEmpty()) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/EditorSessionTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/EditorSessionTest.kt new file mode 100644 index 0000000..e93ef29 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/EditorSessionTest.kt @@ -0,0 +1,1431 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.partByDrawable +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Verifies the snapshot-history core: that a document mutation is one undoable step that restores by + * snapshot, that snapshots structurally share unchanged entities, that dirty-tracking is correct across + * undo/redo, and that a selection gesture is its own step without dirtying the document. + */ +class EditorSessionTest { + private val partA = Part(PartId("a"), "A", children = emptyList()) + private val partB = Part(PartId("b"), "B", children = emptyList()) + private val drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + private val warp = + Deformer.Warp( + id = DeformerId("w"), + name = "Warp", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = true, + geometryGrid = null, + ) + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + // Drawable d lives under part a; the top level holds both parts. + parts = listOf(partA.copy(children = listOf(OrgChild.Drawable(DrawableId("d")))), partB), + deformers = listOf(warp), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Part(PartId("a")), OrgChild.Part(PartId("b"))), + rootPartId = null, + ).withDerivedRenderRoot() + + /** + * A richer model for the delete tests: a part tree R > A > B plus a sibling T; three drawables (d1 under + * A bound to w2, d2 under B bound to w, d3 under T masked by d1); a w > w2 deformer chain; one glue + * pairing d1 and d2; and a flat render tree of d1, d2, d3 - so deletes can be checked against every kind + * of reference (part tree, render order, masks, glue, deformer binding). + * + * @return PuppetModel The fixture model. + */ + private fun deleteModel(): PuppetModel { + // Org tree: R > A > (B, d1); B > d2; T > d3. d1 deformed by w2, d2 by w; d3 masked by d1; glue(d1,d2). + val partB = Part(PartId("B"), "B", children = listOf(OrgChild.Drawable(DrawableId("d2")))) + val partA = Part(PartId("A"), "A", children = listOf(OrgChild.Part(PartId("B")), OrgChild.Drawable(DrawableId("d1")))) + val partR = Part(PartId("R"), "R", children = listOf(OrgChild.Part(PartId("A")))) + val partT = Part(PartId("T"), "T", children = listOf(OrgChild.Drawable(DrawableId("d3")))) + val warpW = Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null) + val warpW2 = + Deformer.Warp(DeformerId("w2"), "W2", parent = DeformerId("w"), partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null) + + fun mesh(rawId: String, deformer: DeformerId?, masks: List): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = deformer, + blendMode = BlendMode.Normal, + maskedBy = masks, + mesh = null, + geometryGrid = null, + ) + return PuppetModel( + parameters = emptyList(), + parts = listOf(partR, partA, partB, partT), + deformers = listOf(warpW, warpW2), + drawables = + listOf( + mesh("d1", DeformerId("w2"), emptyList()), + mesh("d2", DeformerId("w"), emptyList()), + mesh("d3", null, listOf(DrawableId("d1"))), + ), + rootChildren = listOf(OrgChild.Part(PartId("R")), OrgChild.Part(PartId("T"))), + rootPartId = PartId("R"), + glues = listOf(Glue(DrawableId("d1"), DrawableId("d2"), emptyList())), + ).withDerivedRenderRoot() + } + + /** + * withPartVisibility replaces only the touched part and structurally shares the rest of the model. + */ + @Test + fun mutationStructurallySharesUnchangedEntities() { + val before = model() + val after = before.withPartVisibility(PartId("a"), visible = false) + + assertFalse(after.parts.first { it.id == PartId("a") }.isVisible) + // The untouched part and drawable are the very same instances (structural sharing). + assertSame(before.parts.first { it.id == PartId("b") }, after.parts.first { it.id == PartId("b") }) + assertSame(before.drawables[0], after.drawables[0]) + } + + /** + * A no-op mutation returns the same model instance (so the session records nothing). + */ + @Test + fun noOpMutationReturnsSameInstance() { + val before = model() + assertSame(before, before.withPartVisibility(PartId("a"), visible = true)) + assertSame(before, before.withPartVisibility(PartId("missing"), visible = false)) + } + + /** + * A document edit is one undo step; undo restores the prior model by snapshot and clears dirty, + * redo re-applies it. Dirty is reference-equality against the saved instance. + */ + @Test + fun mutateThenUndoRedoTracksModelAndDirty() { + val initial = model() + val session = EditorSession(initial) + + assertFalse(session.dirty.value) + assertFalse(session.canUndo.value) + + session.mutate(PartChange.SetVisibility(PartId("a"), false)) { it.withPartVisibility(PartId("a"), false) } + + assertTrue(session.dirty.value) + assertTrue(session.canUndo.value) + assertFalse(session.canRedo.value) + assertFalse(session.model.value.parts.first { it.id == PartId("a") }.isVisible) + + session.undo() + + // Undo restored the exact prior instance, so dirty is false again. + assertSame(initial, session.model.value) + assertFalse(session.dirty.value) + assertTrue(session.canRedo.value) + + session.redo() + assertFalse(session.model.value.parts.first { it.id == PartId("a") }.isVisible) + assertTrue(session.dirty.value) + } + + /** + * A selection gesture is its own undo step, but it reuses the current model instance — so it never + * dirties the document, and undoing it restores the prior selection while leaving the model untouched. + */ + @Test + fun selectionGestureIsUndoableButNotDirtying() { + val session = EditorSession(model()) + val modelInstance = session.model.value + + session.setSelection(SelectionOps.replace(SelectionTarget.Part(PartId("a")))) + + assertTrue(session.canUndo.value) + assertFalse(session.dirty.value, "a selection change must not dirty the document") + assertSame(modelInstance, session.model.value) + assertEquals(setOf(SelectionTarget.Part(PartId("a"))), session.selection.value.targets) + + session.undo() + assertTrue(session.selection.value.isEmpty) + assertSame(modelInstance, session.model.value) + } + + /** + * A new edit after an undo discards the redo branch (linear history, the v1 choice). + */ + @Test + fun editAfterUndoDiscardsRedo() { + val session = EditorSession(model()) + session.mutate(PartChange.SetVisibility(PartId("a"), false)) { it.withPartVisibility(PartId("a"), false) } + session.undo() + assertTrue(session.canRedo.value) + + session.mutate(PartChange.SetVisibility(PartId("b"), false)) { it.withPartVisibility(PartId("b"), false) } + assertFalse(session.canRedo.value) + } + + /** + * markSaved moves the dirty baseline to the current model, so an edit re-dirties and undoing back to + * the saved instance clears it again. + */ + @Test + fun markSavedMovesDirtyBaseline() { + val session = EditorSession(model()) + session.mutate(PartChange.SetVisibility(PartId("a"), false)) { it.withPartVisibility(PartId("a"), false) } + assertTrue(session.dirty.value) + + session.markSaved() + assertFalse(session.dirty.value) + + session.undo() + // Undid past the saved point, so it is dirty again (the saved instance is no longer current). + assertTrue(session.dirty.value) + } + + /** + * A save snapshots the model and writes it off-thread, so the baseline moves to THAT instance: an edit + * landed meanwhile keeps the document dirty, undoing back to the saved instance clears it, and the + * history panel's saved marker sits on the row that was written rather than on the live one. + */ + @Test + fun markSavedOfASnapshotLeavesALaterEditDirty() { + val session = EditorSession(model()) + session.mutate(PartChange.SetVisibility(PartId("a"), false)) { it.withPartVisibility(PartId("a"), false) } + val snapshot = session.model.value + session.mutate(PartChange.Rename(PartId("b"), "B2")) { it.withPartName(PartId("b"), "B2") } + + session.markSaved(snapshot) + + assertTrue(session.dirty.value, "the edit after the snapshot is not on disk") + assertEquals(listOf(false, true, false), session.historyView.value.steps.map { step -> step.saved }, "the marker sits on the snapshot's row") + session.undo() + assertFalse(session.dirty.value, "undoing back to the saved instance is clean") + session.redo() + assertTrue(session.dirty.value) + } + + /** + * The history view projects the stack (seed plus each step's label key) with the live cursor, and + * jumpTo leaps directly to any step — restoring its model and selection — without walking one level at + * a time. The saved flag marks exactly the saved row. + */ + @Test + fun historyViewProjectsStackAndJumpToLeapsAcrossSteps() { + val session = EditorSession(model()) + session.mutate(PartChange.SetVisibility(PartId("a"), false)) { it.withPartVisibility(PartId("a"), false) } + session.mutate(PartChange.Rename(PartId("b"), "B2")) { it.withPartName(PartId("b"), "B2") } + session.markSaved() + session.mutate(PartChange.SetVisibility(PartId("b"), false)) { it.withPartVisibility(PartId("b"), false) } + + val view = session.historyView.value + // Seed (null label) plus three edits, cursor on the newest. + assertEquals(4, view.steps.size) + assertEquals(3, view.cursor) + assertNull(view.steps[0].labelKey) + assertEquals("change.part.visibility", view.steps[1].labelKey) + assertEquals("change.part.rename", view.steps[2].labelKey) + // Exactly one row is the saved baseline — the rename step that was current at markSaved. + assertEquals(listOf(2), view.steps.indices.filter { view.steps[it].saved }) + + // Jump back to the seed in one move: model and selection both restore, redo branch stays available. + session.jumpTo(0) + assertEquals(0, session.historyView.value.cursor) + assertTrue(session.model.value.parts.first { it.id == PartId("a") }.isVisible) + assertTrue(session.canRedo.value) + + // Jump forward past the saved point; the saved row no longer matches the live model, so it is dirty. + session.jumpTo(3) + assertEquals(3, session.historyView.value.cursor) + assertTrue(session.dirty.value) + assertNull(EditorSnapshotProbe.jumpResult(session, 3), "jumping to the current step is a no-op") + } + + /** + * undo / redo are safe no-ops at the ends of the stack. + */ + @Test + fun undoRedoAtBoundsAreNoOps() { + val session = EditorSession(model()) + assertNull(EditorSnapshotProbe.undoResult(session)) + session.redo() + assertFalse(session.canUndo.value) + assertFalse(session.canRedo.value) + } + + /** + * Renaming a target through the session is one undoable, dirtying step; undo restores the old name. + */ + @Test + fun renameTargetIsOneUndoStep() { + val session = EditorSession(model()) + + session.rename(SelectionTarget.Part(PartId("a")), "Head") + session.rename(SelectionTarget.Drawable(DrawableId("d")), "Eye") + session.rename(SelectionTarget.Deformer(DeformerId("w")), "JawWarp") + + assertEquals("Head", session.model.value.parts.first { it.id == PartId("a") }.name) + assertEquals("Eye", session.model.value.drawables.first { it.id == DrawableId("d") }.name) + assertEquals("JawWarp", session.model.value.deformers.first { it.id == DeformerId("w") }.name) + assertTrue(session.dirty.value) + + session.undo() + assertEquals("Warp", session.model.value.deformers.first { it.id == DeformerId("w") }.name) + } + + /** + * A blank rename is ignored (no step, no name change), and renaming to the current name is a no-op. + */ + @Test + fun blankOrNoOpRenameRecordsNothing() { + val session = EditorSession(model()) + + session.rename(SelectionTarget.Part(PartId("a")), " ") + session.rename(SelectionTarget.Part(PartId("a")), "A") + + assertFalse(session.canUndo.value) + assertEquals("A", session.model.value.parts.first { it.id == PartId("a") }.name) + } + + /** + * toggleVisibility flips one target's eyeball as one step; a deformer target is a no-op. + */ + @Test + fun toggleVisibilityTargetFlipsOneEntity() { + val session = EditorSession(model()) + + session.toggleVisibility(SelectionTarget.Drawable(DrawableId("d"))) + assertFalse(session.model.value.drawables.first { it.id == DrawableId("d") }.isVisible) + + session.toggleVisibility(SelectionTarget.Deformer(DeformerId("w"))) + // No visibility flag on a deformer, so the second toggle recorded nothing. + assertTrue(session.canUndo.value) + session.undo() + assertTrue(session.model.value.drawables.first { it.id == DrawableId("d") }.isVisible) + assertFalse(session.canUndo.value) + } + + /** + * toggleSelectable flips a part/drawable/deformer selectability as one step (deformers have the flag + * too, unlike visibility); undo restores it, and the model exposes the flag through selectableOf. + */ + @Test + fun toggleSelectableFlipsAnyTargetKind() { + val session = EditorSession(model()) + + session.toggleSelectable(SelectionTarget.Part(PartId("a"))) + session.toggleSelectable(SelectionTarget.Drawable(DrawableId("d"))) + session.toggleSelectable(SelectionTarget.Deformer(DeformerId("w"))) + + assertFalse(session.model.value.parts.first { it.id == PartId("a") }.isSelectable) + assertFalse(session.model.value.drawables.first { it.id == DrawableId("d") }.isSelectable) + assertFalse(session.model.value.deformers.first { it.id == DeformerId("w") }.isSelectable) + assertFalse(session.model.value.selectableOf(SelectionTarget.Deformer(DeformerId("w")))) + + session.undo() + assertTrue(session.model.value.deformers.first { it.id == DeformerId("w") }.isSelectable) + } + + /** + * subtreeTargets mirrors the outliner's tree: a part yields its descendant parts plus their drawables, + * a deformer yields nested deformers only (never the drawables bound via parentDeformerId), a drawable + * is a leaf, and a malformed parent cycle still terminates with each deformer yielded once. + */ + @Test + fun subtreeTargetsEnumeratesWhatTheOutlinerShows() { + val fixture = deleteModel() + + val partSubtree = fixture.subtreeTargets(SelectionTarget.Part(PartId("A"))) + assertEquals(SelectionTarget.Part(PartId("A")), partSubtree.first(), "the clicked target leads the list") + assertEquals( + setOf( + SelectionTarget.Part(PartId("A")), + SelectionTarget.Part(PartId("B")), + SelectionTarget.Drawable(DrawableId("d1")), + SelectionTarget.Drawable(DrawableId("d2")), + ), + partSubtree.toSet(), + "a part subtree is its descendant parts plus their drawables", + ) + + assertEquals( + setOf(SelectionTarget.Deformer(DeformerId("w")), SelectionTarget.Deformer(DeformerId("w2"))), + fixture.subtreeTargets(SelectionTarget.Deformer(DeformerId("w"))).toSet(), + "a deformer subtree is nested deformers only, never the drawables bound to them", + ) + + assertEquals( + listOf(SelectionTarget.Drawable(DrawableId("d3"))), + fixture.subtreeTargets(SelectionTarget.Drawable(DrawableId("d3"))), + "a drawable is a leaf", + ) + + // A malformed w <-> w2 parent cycle must terminate and yield each deformer once. + val cyclic = + fixture.copy( + deformers = + fixture.deformers.map { deformer -> + if (deformer is Deformer.Warp && deformer.id == DeformerId("w")) { + deformer.copy(parent = DeformerId("w2")) + } else { + deformer + } + }, + ) + assertEquals( + setOf(SelectionTarget.Deformer(DeformerId("w")), SelectionTarget.Deformer(DeformerId("w2"))), + cyclic.subtreeTargets(SelectionTarget.Deformer(DeformerId("w"))).toSet(), + "a parent cycle terminates", + ) + } + + /** + * A Shift+Click subtree selectable toggle covers the part, its descendant parts, and their drawables as + * ONE undo step - a single undo restores the whole cascade - while everything outside the subtree is + * untouched. + */ + @Test + fun toggleSelectableSubtreeIsOneUndoStepOverThePartSubtree() { + val session = EditorSession(deleteModel()) + + session.toggleSelectableSubtree(SelectionTarget.Part(PartId("A"))) + + val after = session.model.value + assertFalse(after.parts.first { it.id == PartId("A") }.isSelectable) + assertFalse(after.parts.first { it.id == PartId("B") }.isSelectable) + assertFalse(after.drawables.first { it.id == DrawableId("d1") }.isSelectable) + assertFalse(after.drawables.first { it.id == DrawableId("d2") }.isSelectable) + assertTrue(after.parts.first { it.id == PartId("R") }.isSelectable, "the parent is outside the subtree") + assertTrue(after.parts.first { it.id == PartId("T") }.isSelectable) + assertTrue(after.drawables.first { it.id == DrawableId("d3") }.isSelectable) + assertTrue(after.deformers.all { it.isSelectable }, "deformers are not part-subtree children") + assertTrue(session.dirty.value) + + session.undo() + val restored = session.model.value + assertTrue(restored.parts.first { it.id == PartId("A") }.isSelectable) + assertTrue(restored.parts.first { it.id == PartId("B") }.isSelectable) + assertTrue(restored.drawables.first { it.id == DrawableId("d1") }.isSelectable) + assertTrue(restored.drawables.first { it.id == DrawableId("d2") }.isSelectable) + assertFalse(session.canUndo.value, "the whole cascade was one step") + } + + /** + * The subtree toggle sets a uniform value (Blender parity), not a per-node flip: with d2 already + * unselectable, toggling on A drives ALL subtree entities to the clicked node's flipped state, and a + * second toggle brings them all back together. + */ + @Test + fun toggleSelectableSubtreeUnifiesMixedInitialStates() { + val session = EditorSession(deleteModel().withDrawableSelectable(DrawableId("d2"), false)) + + session.toggleSelectableSubtree(SelectionTarget.Part(PartId("A"))) + val allOff = session.model.value + assertFalse(allOff.parts.first { it.id == PartId("A") }.isSelectable) + assertFalse(allOff.parts.first { it.id == PartId("B") }.isSelectable) + assertFalse(allOff.drawables.first { it.id == DrawableId("d1") }.isSelectable) + assertFalse(allOff.drawables.first { it.id == DrawableId("d2") }.isSelectable, "already-off d2 is not flipped back on") + + session.toggleSelectableSubtree(SelectionTarget.Part(PartId("A"))) + val allOn = session.model.value + assertTrue(allOn.parts.first { it.id == PartId("A") }.isSelectable) + assertTrue(allOn.parts.first { it.id == PartId("B") }.isSelectable) + assertTrue(allOn.drawables.first { it.id == DrawableId("d1") }.isSelectable) + assertTrue(allOn.drawables.first { it.id == DrawableId("d2") }.isSelectable) + } + + /** + * A subtree toggle on a deformer covers its nested deformers only - the drawables bound to them via + * parentDeformerId live under their parts in the outliner and stay untouched. + */ + @Test + fun toggleSelectableSubtreeOnDeformerCoversNestedDeformersOnly() { + val session = EditorSession(deleteModel()) + + session.toggleSelectableSubtree(SelectionTarget.Deformer(DeformerId("w"))) + + val after = session.model.value + assertFalse(after.deformers.first { it.id == DeformerId("w") }.isSelectable) + assertFalse(after.deformers.first { it.id == DeformerId("w2") }.isSelectable) + assertTrue(after.drawables.first { it.id == DrawableId("d1") }.isSelectable, "bound drawables are not tree children") + assertTrue(after.drawables.first { it.id == DrawableId("d2") }.isSelectable) + + session.undo() + assertTrue(session.model.value.deformers.all { it.isSelectable }) + assertFalse(session.canUndo.value) + } + + /** + * The visibility subtree toggle hides the part subtree's parts and drawables as one step, and a + * deformer target records nothing at all (deformers have no visibility flag). + */ + @Test + fun toggleVisibilitySubtreeHidesPartSubtreeAndSkipsDeformers() { + val session = EditorSession(deleteModel()) + + session.toggleVisibilitySubtree(SelectionTarget.Part(PartId("A"))) + + val after = session.model.value + assertFalse(after.parts.first { it.id == PartId("A") }.isVisible) + assertFalse(after.parts.first { it.id == PartId("B") }.isVisible) + assertFalse(after.drawables.first { it.id == DrawableId("d1") }.isVisible) + assertFalse(after.drawables.first { it.id == DrawableId("d2") }.isVisible) + assertTrue(after.parts.first { it.id == PartId("T") }.isVisible) + assertTrue(after.drawables.first { it.id == DrawableId("d3") }.isVisible) + + session.undo() + assertTrue(session.model.value.parts.first { it.id == PartId("A") }.isVisible) + assertTrue(session.model.value.drawables.first { it.id == DrawableId("d2") }.isVisible) + assertFalse(session.canUndo.value, "the whole cascade was one step") + + // A deformer target is a no-op: no visibility flag, so no history step is recorded. + session.toggleVisibilitySubtree(SelectionTarget.Deformer(DeformerId("w"))) + assertFalse(session.canUndo.value) + } + + /** + * On a drawable (a leaf) the subtree toggles degenerate to plain single-entity toggles. + */ + @Test + fun toggleSubtreeOnDrawableIsAPlainSingleToggle() { + val session = EditorSession(deleteModel()) + + session.toggleVisibilitySubtree(SelectionTarget.Drawable(DrawableId("d3"))) + val afterVisibility = session.model.value + assertFalse(afterVisibility.drawables.first { it.id == DrawableId("d3") }.isVisible) + assertTrue(afterVisibility.drawables.first { it.id == DrawableId("d1") }.isVisible) + assertTrue(afterVisibility.parts.first { it.id == PartId("T") }.isVisible, "the owning part is not the leaf's subtree") + + session.toggleSelectableSubtree(SelectionTarget.Drawable(DrawableId("d3"))) + assertFalse(session.model.value.drawables.first { it.id == DrawableId("d3") }.isSelectable) + assertTrue(session.model.value.drawables.first { it.id == DrawableId("d1") }.isSelectable) + + session.undo() + session.undo() + assertTrue(session.model.value.drawables.first { it.id == DrawableId("d3") }.isVisible) + assertTrue(session.model.value.drawables.first { it.id == DrawableId("d3") }.isSelectable) + assertFalse(session.canUndo.value, "each leaf toggle was exactly one step") + } + + /** + * Moving a drawable re-homes it under another part; undo restores its old owner. + */ + @Test + fun moveOrgChildRehomesDrawableToAnotherPart() { + val session = EditorSession(model()) + + session.moveOrgChild(OrgChild.Drawable(DrawableId("d")), newParentId = PartId("b"), before = null) + assertEquals(PartId("b"), session.model.value.partByDrawable()[DrawableId("d")]) + + session.undo() + assertEquals(PartId("a"), session.model.value.partByDrawable()[DrawableId("d")]) + } + + /** + * Moving a drawable among its siblings reorders the org tree (the outliner) and the derived render + * order (the viewport, panel reversed back-to-front) consistently; undo restores both. + */ + @Test + fun moveOrgChildReordersTreeAndDerivesRenderOrder() { + val drawableE = + Drawable( + id = DrawableId("e"), + name = "e", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + val layered = + PuppetModel( + parameters = emptyList(), + parts = listOf(partA.copy(children = listOf(OrgChild.Drawable(DrawableId("d")), OrgChild.Drawable(DrawableId("e"))))), + deformers = emptyList(), + drawables = listOf(drawable, drawableE), + rootChildren = listOf(OrgChild.Part(PartId("a"))), + rootPartId = null, + ).withDerivedRenderRoot() + val session = EditorSession(layered) + + // d is above e in the panel; move d to after e (append). The panel order flips, and the derived + // render order (panel reversed) follows. + session.moveOrgChild(OrgChild.Drawable(DrawableId("d")), newParentId = PartId("a"), before = null) + assertEquals( + listOf(OrgChild.Drawable(DrawableId("e")), OrgChild.Drawable(DrawableId("d"))), + session.model.value.parts.first { it.id == PartId("a") }.children, + ) + assertEquals( + listOf(DrawableId("d"), DrawableId("e")), + session.model.value.renderRoot.children.filterIsInstance().map { it.id }, + ) + + session.undo() + assertEquals( + listOf(OrgChild.Drawable(DrawableId("d")), OrgChild.Drawable(DrawableId("e"))), + session.model.value.parts.first { it.id == PartId("a") }.children, + ) + } + + /** + * A drawable can be interleaved between two parts at the root (Cubism's cross-kind reorder), so a loose + * mesh sits between folders rather than only being parented into one. + */ + @Test + fun moveOrgChildInterleavesADrawableBetweenParts() { + val session = EditorSession(model()) + + // model()'s top level is [a, b] with d under a; move d to the root, between a and b. + session.moveOrgChild(OrgChild.Drawable(DrawableId("d")), newParentId = null, before = OrgChild.Part(PartId("b"))) + assertEquals( + listOf(OrgChild.Part(PartId("a")), OrgChild.Drawable(DrawableId("d")), OrgChild.Part(PartId("b"))), + session.model.value.rootChildren, + ) + assertNull(session.model.value.partByDrawable()[DrawableId("d")], "now a root-level drawable, owned by no part") + } + + /** + * Moving a part nests it under the new parent; a move that would form a cycle is refused. + */ + @Test + fun moveOrgChildReparentsPartAndRefusesCycles() { + val session = EditorSession(model()) + + session.moveOrgChild(OrgChild.Part(PartId("b")), newParentId = PartId("a"), before = null) + assertTrue(OrgChild.Part(PartId("b")) in session.model.value.parts.first { it.id == PartId("a") }.children) + + // a is now an ancestor of b, so moving a under b is a cycle and must be refused (no new step). + val before = session.model.value + session.moveOrgChild(OrgChild.Part(PartId("a")), newParentId = PartId("b"), before = null) + assertSame(before, session.model.value) + + session.undo() + assertFalse(OrgChild.Part(PartId("b")) in session.model.value.parts.first { it.id == PartId("a") }.children) + } + + /** + * Moving a deformer re-nests it under the new parent; a move that would form a cycle is refused. + */ + @Test + fun moveDeformerReparentsAndRefusesCycles() { + val warp2 = + Deformer.Warp( + id = DeformerId("w2"), + name = "Warp2", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = true, + geometryGrid = null, + ) + val nested = + PuppetModel( + parameters = emptyList(), + parts = listOf(partA, partB), + deformers = listOf(warp, warp2), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Part(PartId("a")), OrgChild.Part(PartId("b")), OrgChild.Drawable(DrawableId("d"))), + rootPartId = null, + ) + val session = EditorSession(nested) + + session.moveDeformer(DeformerId("w2"), newParentId = DeformerId("w"), beforeId = null) + assertEquals(DeformerId("w"), session.model.value.deformers.first { it.id == DeformerId("w2") }.parent) + + // w is now an ancestor of w2, so nesting w under w2 is a cycle and must be refused. + val before = session.model.value + session.moveDeformer(DeformerId("w"), newParentId = DeformerId("w2"), beforeId = null) + assertSame(before, session.model.value) + + session.undo() + assertNull(session.model.value.deformers.first { it.id == DeformerId("w2") }.parent) + } + + /** + * Deleting a drawable scrubs every reference to it: the drawables list, the render-order tree, another + * drawable's clip mask, and any glue it was half of. Undo restores them all. + */ + @Test + fun deleteDrawableScrubsAllReferences() { + val session = EditorSession(deleteModel()) + + session.deleteDrawable(DrawableId("d1")) + val after = session.model.value + assertFalse(after.drawables.any { it.id == DrawableId("d1") }) + assertFalse(after.renderRoot.children.filterIsInstance().any { it.id == DrawableId("d1") }) + assertTrue(after.drawables.first { it.id == DrawableId("d3") }.maskedBy.isEmpty(), "the mask reference to d1 is dropped") + assertTrue(after.glues.isEmpty(), "the glue that paired d1 with d2 is dropped") + + session.undo() + assertTrue(session.model.value.drawables.any { it.id == DrawableId("d1") }) + assertEquals(1, session.model.value.glues.size) + assertEquals(listOf(DrawableId("d1")), session.model.value.drawables.first { it.id == DrawableId("d3") }.maskedBy) + } + + /** + * Deleting a deformer unwraps it: its child deformers and the drawables it deformed re-home to its + * parent, so removing a transform wrapper never deletes art. + */ + @Test + fun deleteDeformerUnwrapsToParent() { + val session = EditorSession(deleteModel()) + + // w is a root; w2's parent is w, and d2 is deformed by w. Deleting w re-homes both to w's parent (null). + session.deleteDeformer(DeformerId("w")) + val after = session.model.value + assertFalse(after.deformers.any { it.id == DeformerId("w") }) + assertNull(after.deformers.first { it.id == DeformerId("w2") }.parent) + assertNull(after.drawables.first { it.id == DrawableId("d2") }.parentDeformerId) + // d1 was bound to w2 (not w), so it is untouched. + assertEquals(DeformerId("w2"), after.drawables.first { it.id == DrawableId("d1") }.parentDeformerId) + + session.undo() + assertEquals(DeformerId("w"), session.model.value.deformers.first { it.id == DeformerId("w2") }.parent) + } + + /** + * A cascade part delete removes the whole subtree - the part, its descendant parts, and every drawable + * under them (with references scrubbed) - while leaving unrelated parts and drawables intact. + */ + @Test + fun deletePartCascadeRemovesSubtree() { + val session = EditorSession(deleteModel()) + + // A holds B; d1 is under A and d2 under B. A cascade delete of A removes A, B, d1, and d2. + session.deletePart(PartId("A"), cascade = true) + val after = session.model.value + assertEquals(setOf(PartId("R"), PartId("T")), after.parts.map { it.id }.toSet()) + assertEquals(listOf(DrawableId("d3")), after.drawables.map { it.id }) + assertTrue(after.parts.first { it.id == PartId("R") }.children.isEmpty(), "A is detached from its parent R") + assertEquals(listOf(DrawableId("d3")), after.renderRoot.children.filterIsInstance().map { it.id }) + assertTrue(after.glues.isEmpty()) + + session.undo() + assertEquals(4, session.model.value.parts.size) + assertEquals(3, session.model.value.drawables.size) + } + + /** + * An ungroup part delete dissolves the folder only: its child parts and drawables rise one level to the + * deleted part's parent, and nothing is destroyed. + */ + @Test + fun deletePartUngroupKeepsContents() { + val session = EditorSession(deleteModel()) + + // Ungroup A (whose parent is R): B rises into R's children, and d1 (under A) re-homes to R. + session.deletePart(PartId("A"), cascade = false) + val after = session.model.value + assertFalse(after.parts.any { it.id == PartId("A") }) + assertEquals(3, after.drawables.size, "no drawable is deleted on an ungroup") + // A's own children (sub-part B and mesh d1) splice into A's parent R, in place. + assertEquals( + listOf(OrgChild.Part(PartId("B")), OrgChild.Drawable(DrawableId("d1"))), + after.parts.first { it.id == PartId("R") }.children, + ) + assertEquals(PartId("R"), after.partByDrawable()[DrawableId("d1")]) + + session.undo() + assertTrue(session.model.value.parts.any { it.id == PartId("A") }) + assertEquals(PartId("A"), session.model.value.partByDrawable()[DrawableId("d1")]) + } + + private val angleX = ParameterId("ParamAngleX") + + /** + * A one-parameter model for the pose / range tests: a single ParamAngleX over the given range. + * + * @param Float min The parameter minimum. + * @param Float max The parameter maximum. + * @param Float default The parameter default (the initial pose value). + * @return PuppetModel The fixture model. + */ + private fun paramModel(min: Float = -1f, max: Float = 1f, default: Float = 0f): PuppetModel = + model().copy(parameters = listOf(Parameter(angleX, "Angle X", min, max, default))) + + /** + * A scrub commit is one undo step over the pose: it moves the live value, does not dirty the document + * (the model is unchanged), and undo / redo restore the prior / next pose. The session pose starts at + * the parameter's default. + */ + @Test + fun scrubCommitIsUndoablePoseStepWithoutDirty() { + val session = EditorSession(paramModel()) + assertEquals(0f, session.pose.value[angleX]) + + session.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 0.6f)) + + assertEquals(0.6f, session.pose.value[angleX]) + assertFalse(session.dirty.value, "a pose-only scrub must not dirty the document") + assertTrue(session.canUndo.value) + + session.undo() + assertEquals(0f, session.pose.value[angleX]) + + session.redo() + assertEquals(0.6f, session.pose.value[angleX]) + } + + /** A scrub that commits the already-current pose records nothing. */ + @Test + fun scrubCommitOfUnchangedPoseIsNoOp() { + val session = EditorSession(paramModel()) + session.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 0f)) + assertFalse(session.canUndo.value) + } + + /** + * Editing a parameter's range is one undo step that edits the model (so it dirties the document), + * re-clamps the live pose into the shrunk range, and on undo restores both the range and the pose + * together. + */ + @Test + fun setRangeEditsModelReclampsPoseAndUndoesBoth() { + val session = EditorSession(paramModel(min = -1f, max = 1f, default = 0f)) + session.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 0.8f)) + + session.setParameterRange(angleX, min = -0.5f, default = 0f, max = 0.5f) + + val parameter = session.model.value.parameters.first() + assertEquals(-0.5f, parameter.min) + assertEquals(0.5f, parameter.max) + assertEquals(0.5f, session.pose.value[angleX], "the live value re-clamps into the shrunk range") + assertTrue(session.dirty.value, "a range edit changes the model and dirties the document") + + session.undo() + assertEquals(1f, session.model.value.parameters.first().max) + assertEquals(0.8f, session.pose.value[angleX], "undo restores the pre-clamp pose too") + assertFalse(session.dirty.value) + } + + /** withParameterRange normalizes inverted bounds and clamps the default into the resulting range. */ + @Test + fun withParameterRangeNormalizesBoundsAndClampsDefault() { + val base = paramModel(min = -1f, max = 1f, default = 0f) + val edited = base.withParameterRange(angleX, min = 5f, default = 10f, max = 1f) + + val parameter = edited.parameters.first() + assertEquals(1f, parameter.min, "min/max are normalized so min <= max") + assertEquals(5f, parameter.max) + assertEquals(5f, parameter.default, "the default is clamped into the normalized range") + assertSame(base, base.withParameterRange(angleX, min = -1f, default = 0f, max = 1f), "a no-op range is the same instance") + } + + private val angleY = ParameterId("ParamAngleY") + private val angleZ = ParameterId("ParamAngleZ") + + /** + * A three-parameter model for the link tests: ParamAngleX / Y / Z, all animatable, no links. + * + * @return PuppetModel The fixture model. + */ + private fun linkModel(): PuppetModel = + model().copy( + parameters = + listOf( + Parameter(angleX, "Angle X", -1f, 1f, 0f), + Parameter(angleY, "Angle Y", -1f, 1f, 0f), + Parameter(angleZ, "Angle Z", -1f, 1f, 0f), + ), + ) + + /** withParameterLink appends the pair, removes exactly that pair, and no-ops an absent unlink. */ + @Test + fun withParameterLinkAddsAndRemovesPairs() { + val base = linkModel() + val linked = base.withParameterLink(angleX, angleY, linked = true) + assertEquals(listOf(ParameterLink(angleX, angleY)), linked.parameterLinks) + + val unlinked = linked.withParameterLink(angleX, angleY, linked = false) + assertTrue(unlinked.parameterLinks.isEmpty()) + + assertSame(base, base.withParameterLink(angleX, angleY, linked = false), "unlinking an absent pair is the same instance") + } + + /** withParameterLink refuses equal ids, unknown ids, and members of an existing link - same instance. */ + @Test + fun withParameterLinkRefusesInvalidRequests() { + val base = linkModel() + assertSame(base, base.withParameterLink(angleX, angleX, linked = true), "equal ids are refused") + assertSame(base, base.withParameterLink(angleX, ParameterId("ParamUnknown"), linked = true), "an unknown id is refused") + + val linked = base.withParameterLink(angleX, angleY, linked = true) + assertSame(linked, linked.withParameterLink(angleY, angleZ, linked = true), "a vertical member cannot join a second link") + assertSame(linked, linked.withParameterLink(angleZ, angleX, linked = true), "a horizontal member cannot join a second link") + } + + /** + * Linking parameters is one undo step that edits the model (so it dirties the document), leaves the + * live pose untouched, and undoes / redoes the link list; a refused request records nothing. + */ + @Test + fun setParameterLinkIsOneDirtyStepLeavingPoseUntouched() { + val session = EditorSession(linkModel()) + session.commitPose(ParameterChange.SetValue(listOf(angleX)), session.pose.value + (angleX to 0.4f)) + + session.setParameterLink(angleX, angleY, linked = true) + + assertEquals(listOf(ParameterLink(angleX, angleY)), session.model.value.parameterLinks) + assertEquals(0.4f, session.pose.value[angleX], "a link edit never moves the live pose") + assertTrue(session.dirty.value, "a link edit changes the model and dirties the document") + + session.undo() + assertTrue(session.model.value.parameterLinks.isEmpty(), "undo restores the previous links") + assertEquals(0.4f, session.pose.value[angleX]) + + session.redo() + assertEquals(listOf(ParameterLink(angleX, angleY)), session.model.value.parameterLinks) + + // A refused request (angleY is already a link member) must not record an undo step. + val stepCountBefore = session.historyView.value.steps.size + session.setParameterLink(angleY, angleZ, linked = true) + assertEquals(stepCountBefore, session.historyView.value.steps.size, "a refused link records nothing") + } + + /** + * A model whose drawable d carries a base art-mesh (a single triangle), for the mesh-edit tests. + * + * @return PuppetModel The fixture model with an editable mesh on drawable d. + */ + private fun meshModel(): PuppetModel { + val mesh = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), + uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + indices = intArrayOf(0, 1, 2), + ) + return model().copy(drawables = listOf(drawable.copy(mesh = mesh))) + } + + /** A model with two meshed drawables, for the Alt+Q switch and the per-mesh selection memory. */ + private fun twoMeshModel(): PuppetModel { + val meshA = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), intArrayOf(0, 1, 2)) + val meshB = DrawableMesh(floatArrayOf(10f, 0f, 12f, 0f, 10f, 2f), FloatArray(6), intArrayOf(0, 1, 2)) + return model().copy( + parts = emptyList(), + drawables = + listOf( + drawable.copy(id = DrawableId("a"), name = "a", mesh = meshA), + drawable.copy(id = DrawableId("b"), name = "b", mesh = meshB), + ), + rootChildren = listOf(OrgChild.Drawable(DrawableId("a")), OrgChild.Drawable(DrawableId("b"))), + ).withDerivedRenderRoot() + } + + /** + * Alt+Q's switch moves the OBJECT selection with the edit session in ONE undo step, and the + * per-mesh element memory restores each mesh's selection when the session returns to it. + */ + @Test + fun switchEditDrawableSyncsObjectSelectionAndRemembersElementsPerMesh() { + val session = EditorSession(twoMeshModel()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("a")))) + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("a"), MeshElement.Vertex(1))) + + val stepsBefore = session.historyView.value.steps.size + session.switchEditDrawable(DrawableId("b")) + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "the switch is one undo step") + assertEquals(listOf(DrawableId("b")), session.meshSelection.value.drawableIds, "the edit session moved to b") + assertEquals( + SelectionTarget.Drawable(DrawableId("b")), + session.selection.value.active, + "the object selection follows the switch (tabbing out keeps b)", + ) + + // Switching back restores a's remembered element selection (the per-mesh memory). + session.switchEditDrawable(DrawableId("a")) + assertEquals(setOf(MeshElement.Vertex(1)), session.meshSelection.value.elementsOf(DrawableId("a")), "a's elements return") + + // One undo rewinds the whole switch - BOTH selections together, never torn across two steps. + session.undo() + assertEquals(listOf(DrawableId("b")), session.meshSelection.value.drawableIds, "undo returns the session to b") + assertEquals(SelectionTarget.Drawable(DrawableId("b")), session.selection.value.active, "undo returns the object selection with it") + } + + /** Leaving Edit mode stashes every session mesh's elements; re-entry restores them per mesh. */ + @Test + fun meshElementMemorySurvivesModeSwitchesPerMesh() { + val session = EditorSession(twoMeshModel()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("a")))) + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("a"), MeshElement.Vertex(0))) + session.setMode(EditorMode.Object) + + // Edit a DIFFERENT mesh in between: switching back to it later must not have forgotten a's memory. + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("b")))) + session.setMode(EditorMode.Edit) + assertEquals(listOf(DrawableId("b")), session.meshSelection.value.drawableIds) + session.setMode(EditorMode.Object) + + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("a")))) + session.setMode(EditorMode.Edit) + assertEquals( + setOf(MeshElement.Vertex(0)), + session.meshSelection.value.elementsOf(DrawableId("a")), + "a's element selection survives editing b in between", + ) + } + + /** withMeshPositions copy-on-writes the mesh: new positions, shared uvs/indices, input array untouched. */ + @Test + fun withMeshPositionsCowsAndSharesUnchangedArrays() { + val before = meshModel() + val beforeMesh = before.drawables.first().mesh!! + val newPositions = floatArrayOf(5f, 5f, 2f, 0f, 0f, 2f) + + val after = before.withMeshPositions(DrawableId("d"), newPositions) + val afterMesh = after.drawables.first().mesh!! + + assertSame(beforeMesh.uvs, afterMesh.uvs, "uvs shared by reference") + assertSame(beforeMesh.indices, afterMesh.indices, "indices shared by reference") + assertEquals(5f, afterMesh.positions[0], "new positions applied") + assertEquals(0f, beforeMesh.positions[0], "the prior mesh's array is unmutated (COW)") + assertSame(before, before.withMeshPositions(DrawableId("d"), beforeMesh.positions), "same array is a no-op") + assertSame(before, before.withMeshPositions(DrawableId("missing"), newPositions), "missing id is a no-op") + } + + /** A mesh edit is one undo step that marks dirty; undo restores the original array instance and clears dirty. */ + @Test + fun commitMeshPositionsIsOneUndoStepAndRestores() { + val initial = meshModel() + val session = EditorSession(initial) + val originalArray = initial.drawables.first().mesh!!.positions + val moved = floatArrayOf(9f, 9f, 2f, 0f, 0f, 2f) + + session.commitMeshPositions(MeshChange.TransformVertices(mapOf(DrawableId("d") to listOf(0)), MeshOperatorKind.Grab), mapOf(DrawableId("d") to moved)) + assertTrue(session.dirty.value, "a mesh edit dirties the document") + assertTrue(session.canUndo.value) + assertEquals(9f, session.model.value.drawables.first().mesh!!.positions[0]) + + session.undo() + assertSame(originalArray, session.model.value.drawables.first().mesh!!.positions, "undo restores the array instance") + assertFalse(session.dirty.value) + + session.redo() + assertEquals(9f, session.model.value.drawables.first().mesh!!.positions[0]) + } + + /** + * Vertex selection is undoable, and undoing a mesh move restores the vertex selection captured at that + * step (the snapshot carries it); a selection-only step does not dirty the document. + */ + @Test + fun vertexSelectionIsUndoableAndRidesTheMoveSnapshot() { + val session = EditorSession(meshModel()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("d"), session.meshSelection.value.activeDrawableId) + + session.setMeshSelection( + MeshSelectionOps.add(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0)), DrawableId("d"), MeshElement.Vertex(1)), + ) + assertEquals(setOf(MeshElement.Vertex(0), MeshElement.Vertex(1)), session.meshSelection.value.elementsOf(DrawableId("d"))) + assertFalse(session.dirty.value, "a vertex-selection gesture does not dirty the document") + + session.commitMeshPositions( + MeshChange.TransformVertices(mapOf(DrawableId("d") to listOf(0, 1)), MeshOperatorKind.Grab), + mapOf(DrawableId("d") to floatArrayOf(9f, 9f, 9f, 0f, 0f, 2f)), + ) + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(2))) + assertEquals(setOf(MeshElement.Vertex(2)), session.meshSelection.value.elementsOf(DrawableId("d"))) + + session.undo() // undo the {2} selection -> back to {0,1} + assertEquals(setOf(MeshElement.Vertex(0), MeshElement.Vertex(1)), session.meshSelection.value.elementsOf(DrawableId("d"))) + + session.undo() // undo the move -> geometry restored AND the selection it carried ({0,1}) + assertEquals(0f, session.model.value.drawables.first().mesh!!.positions[0]) + assertEquals(setOf(MeshElement.Vertex(0), MeshElement.Vertex(1)), session.meshSelection.value.elementsOf(DrawableId("d"))) + } + + /** + * Mode changes never write the pose (the contract that keeps Edit mode stash-free): entering and + * leaving Edit mode leave the scrubbed Object-mode pose untouched — the rest view Edit mode shows is + * a display-only override in the render host, not session state. + */ + @Test + fun modeChangesNeverTouchThePose() { + // A param plus an editable mesh on drawable d, so entering Edit actually engages (rather than being + // refused for want of something to edit). + val session = EditorSession(paramModel().copy(drawables = meshModel().drawables)) + session.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 0.6f)) + + session.setMode(EditorMode.Edit) + assertEquals(EditorMode.Edit, session.mode.value, "Edit engages when there is an editable drawable") + assertEquals(0.6f, session.pose.value[angleX], "entering Edit leaves the pose untouched") + + session.setMode(EditorMode.Object) + assertEquals(0.6f, session.pose.value[angleX], "leaving Edit leaves the pose untouched") + } + + /** Entering Edit auto-seeds the topmost editable drawable; a modal operator latches only with a non-empty selection. */ + @Test + fun editModeSeedAndOperatorGuards() { + val session = EditorSession(meshModel()) + + // No active drawable and nothing remembered: Edit auto-selects the topmost editable drawable (d) + // rather than opening an inert session, but the operator still no-ops with no elements selected. + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("d"), session.meshSelection.value.activeDrawableId) + session.beginMeshOperator(MeshOperatorKind.Grab, "area-test") + assertNull(session.activeMeshOperator.value, "operator no-ops with an empty element selection") + + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0))) + session.beginMeshOperator(MeshOperatorKind.Grab, "area-test") + assertEquals(MeshOperatorKind.Grab, session.activeMeshOperator.value?.kind) + session.clearMeshOperator() + assertNull(session.activeMeshOperator.value) + + // An edge selection latches too - G / S / R moves the vertices the selected elements cover. + session.setMeshSelectMode(MeshSelectMode.Edge) + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Edge.of(0, 1))) + session.beginMeshOperator(MeshOperatorKind.Grab, "area-test") + assertEquals(MeshOperatorKind.Grab, session.activeMeshOperator.value?.kind) + session.clearMeshOperator() + } + + /** + * Entering Edit mode after the selection was cleared falls back to the last drawable that was active + * (Blender's remembered selection), instead of landing in an inert Edit mode. + */ + @Test + fun editModeFallsBackToRememberedDrawableAfterDeselect() { + val session = EditorSession(meshModel()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setSelection(SelectionOps.clear()) + + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("d"), session.meshSelection.value.activeDrawableId, "remembered drawable seeds Edit mode") + } + + /** A currently-active drawable always wins over the remembered one when Edit mode seeds. */ + @Test + fun activeSelectionWinsOverRememberedDrawable() { + // Both drawables carry meshes: the seed filters to mesh-carrying drawables, so a mesh-less + // active target could never win (Edit refuses inert sessions). + val modelWithTwoDrawables = + meshModel().let { base -> + base.copy(drawables = base.drawables + base.drawables.first().copy(id = DrawableId("e"), name = "e")) + } + val session = EditorSession(modelWithTwoDrawables) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("e")))) + + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("e"), session.meshSelection.value.activeDrawableId, "the live active drawable wins") + } + + /** + * With the remembered drawable deleted and no other editable drawable left, entering Edit is refused - + * the mode stays Object rather than opening an inert session. + */ + @Test + fun editModeRefusedWhenNothingEditable() { + val session = EditorSession(meshModel()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setSelection(SelectionOps.clear()) + session.mutate(DrawableChange.Delete(DrawableId("d"))) { current -> + current.copy(drawables = current.drawables.filter { candidate -> candidate.id != DrawableId("d") }) + } + + session.setMode(EditorMode.Edit) + assertEquals(EditorMode.Object, session.mode.value, "Edit is refused when the model has nothing editable") + assertNull(session.meshSelection.value.activeDrawableId) + } + + /** + * A fresh document with nothing ever selected enters Edit on the topmost editable drawable (Parts-panel + * order, top = front), skipping mesh-less drawables ahead of it. + */ + @Test + fun editModeAutoSelectsTopmostDrawableOnFreshLoad() { + val mesh = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), + uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + indices = intArrayOf(0, 1, 2), + ) + val noMesh = drawable.copy(id = DrawableId("noMesh"), name = "noMesh", mesh = null) + val top = drawable.copy(id = DrawableId("top"), name = "top", mesh = mesh) + val bottom = drawable.copy(id = DrawableId("bottom"), name = "bottom", mesh = mesh) + val model = + model().copy( + parts = listOf(partA.copy(children = emptyList()), partB), + drawables = listOf(noMesh, top, bottom), + rootChildren = + listOf( + OrgChild.Drawable(DrawableId("noMesh")), + OrgChild.Drawable(DrawableId("top")), + OrgChild.Drawable(DrawableId("bottom")), + ), + ) + val session = EditorSession(model) + + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("top"), session.meshSelection.value.activeDrawableId, "front-most editable drawable seeds Edit") + } + + /** A model whose only drawables carry no mesh has nothing to edit, so Edit is refused. */ + @Test + fun editModeRefusedWhenModelHasNoEditableDrawable() { + val session = EditorSession(model()) // drawable d has mesh = null + + session.setMode(EditorMode.Edit) + assertEquals(EditorMode.Object, session.mode.value) + assertNull(session.meshSelection.value.activeDrawableId) + } + + /** + * A mode change is its own undo step, so undoing back across it restores the prior mode (and the vertex + * selection it seeded) - the editor never lands in Edit mode showing an Object-mode state. + */ + @Test + fun modeChangeIsUndoableAndRestoresPriorMode() { + val session = EditorSession(meshModel()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0))) + assertEquals(EditorMode.Edit, session.mode.value) + + session.undo() // undo the vertex selection -> still in Edit (that step was taken in Edit) + assertEquals(EditorMode.Edit, session.mode.value) + + session.undo() // undo the mode change -> back to Object, vertex selection gone + assertEquals(EditorMode.Object, session.mode.value) + assertNull(session.meshSelection.value.activeDrawableId) + + session.redo() // redo -> back into Edit with the drawable seeded + assertEquals(EditorMode.Edit, session.mode.value) + assertEquals(DrawableId("d"), session.meshSelection.value.activeDrawableId) + + assertFalse(session.dirty.value, "mode changes never dirty the document") + } + + /** + * A select-mode switch converts the selection (Blender's derive-up / flush-down), is one undo step + * labeled "change.mesh.selectMode", and no-ops outside Edit mode or when already in the requested mode. + */ + @Test + fun selectModeSwitchConvertsAndIsUndoable() { + val session = EditorSession(meshModel()) + session.setMeshSelectMode(MeshSelectMode.Edge) + assertEquals(MeshSelectMode.Vertex, session.meshSelection.value.selectMode, "no-op outside Edit mode") + + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelection( + MeshSelectionOps.add(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0)), DrawableId("d"), MeshElement.Vertex(1)), + ) + + val stepsBefore = session.historyView.value.steps.size + session.setMeshSelectMode(MeshSelectMode.Edge) + assertEquals(MeshSelectMode.Edge, session.meshSelection.value.selectMode) + assertEquals(setOf(MeshElement.Edge(0, 1)), session.meshSelection.value.elementsOf(DrawableId("d")), "both-endpoint edge derives") + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "the switch is exactly one undo step") + assertEquals("change.mesh.selectMode", session.historyView.value.steps.last().labelKey) + assertFalse(session.dirty.value, "a select-mode switch never dirties the document") + + session.setMeshSelectMode(MeshSelectMode.Edge) + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "a same-mode switch records nothing") + + session.undo() + assertEquals(MeshSelectMode.Vertex, session.meshSelection.value.selectMode) + assertEquals(setOf(MeshElement.Vertex(0), MeshElement.Vertex(1)), session.meshSelection.value.elementsOf(DrawableId("d"))) + + session.redo() + assertEquals(MeshSelectMode.Edge, session.meshSelection.value.selectMode) + assertEquals(setOf(MeshElement.Edge(0, 1)), session.meshSelection.value.elementsOf(DrawableId("d"))) + } + + /** + * Leaving Edit mode stashes the element selection and re-entering on the same drawable restores it + * (Blender's remembered mesh selection); landing on a different drawable starts empty instead. + */ + @Test + fun meshSelectionIsRememberedAcrossModeSwitches() { + // Two meshed drawables so the second entry can land somewhere else. + val model = + meshModel().let { base -> + base.copy(drawables = base.drawables + base.drawables.first().copy(id = DrawableId("d2"), name = "d2")) + } + val session = EditorSession(model) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(1))) + + session.setMode(EditorMode.Object) + assertNull(session.meshSelection.value.activeDrawableId, "leaving Edit clears the live selection") + + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("d"), session.meshSelection.value.activeDrawableId) + assertEquals(setOf(MeshElement.Vertex(1)), session.meshSelection.value.elementsOf(DrawableId("d")), "the stash restores on the same drawable") + assertEquals(ActiveMeshElement(DrawableId("d"), MeshElement.Vertex(1)), session.meshSelection.value.activeElement, "the active element restores too") + + // Leave again and land on the other drawable: the stash does not apply there. + session.setMode(EditorMode.Object) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d2")))) + session.setMode(EditorMode.Edit) + assertEquals(DrawableId("d2"), session.meshSelection.value.activeDrawableId) + assertTrue(session.meshSelection.value.isEmpty, "a different drawable starts empty") + } + + /** + * Entering Edit with several meshed drawables selected seeds them ALL into the session (multi-mesh + * edit), with the object selection's active drawable as the active mesh; a commit moving vertices + * on two meshes is ONE undo step that restores both. + */ + @Test + fun multiMeshEditSessionSeedsAndCommitsAcrossMeshes() { + val model = + meshModel().let { base -> + base.copy(drawables = base.drawables + base.drawables.first().copy(id = DrawableId("d2"), name = "d2")) + } + val session = EditorSession(model) + val targetD = SelectionTarget.Drawable(DrawableId("d")) + val targetD2 = SelectionTarget.Drawable(DrawableId("d2")) + session.setSelection(Selection(setOf(targetD, targetD2), targetD2)) + + session.setMode(EditorMode.Edit) + assertEquals(listOf(DrawableId("d"), DrawableId("d2")), session.meshSelection.value.drawableIds, "both meshes join the session") + assertEquals(DrawableId("d2"), session.meshSelection.value.activeDrawableId, "the object selection's active drawable is the active mesh") + + // One commit moving vertices on both meshes is a single undo step restoring both. + val stepsBefore = session.historyView.value.steps.size + session.commitMeshPositions( + MeshChange.TransformVertices(mapOf(DrawableId("d") to listOf(0), DrawableId("d2") to listOf(1)), MeshOperatorKind.Grab), + mapOf( + DrawableId("d") to floatArrayOf(9f, 9f, 2f, 0f, 0f, 2f), + DrawableId("d2") to floatArrayOf(0f, 0f, 7f, 7f, 0f, 2f), + ), + ) + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "two meshes, one undo step") + assertEquals(9f, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.positions[0]) + assertEquals(7f, session.model.value.drawables.first { it.id == DrawableId("d2") }.mesh!!.positions[2]) + + session.undo() + assertEquals(0f, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.positions[0]) + assertEquals(2f, session.model.value.drawables.first { it.id == DrawableId("d2") }.mesh!!.positions[2]) + } + + /** + * selectHierarchy expands a part to its outliner subtree (descendant parts + their drawables) and + * leaves a drawable-only selection unchanged (a leaf's subtree is itself). + */ + @Test + fun selectHierarchyExpandsPartSubtrees() { + val fixture = model() // part a holds drawable d; part b is empty. + val partTarget = SelectionTarget.Part(PartId("a")) + val expanded = SelectionOps.selectHierarchy(Selection(setOf(partTarget), partTarget), fixture) + assertEquals( + setOf(partTarget, SelectionTarget.Drawable(DrawableId("d"))), + expanded.targets, + "the part's subtree (itself + its drawable) is selected", + ) + assertEquals(partTarget, expanded.active, "the original active target is kept") + + val leaf = SelectionTarget.Drawable(DrawableId("d")) + val unchanged = SelectionOps.selectHierarchy(Selection(setOf(leaf), leaf), fixture) + assertEquals(setOf(leaf), unchanged.targets, "a drawable expands to just itself") + + assertTrue(SelectionOps.selectHierarchy(Selection(), fixture).isEmpty, "an empty selection stays empty") + } + + /** switchEditDrawable re-seeds the Edit session onto one mesh as an undoable selection step. */ + @Test + fun switchEditDrawableReseedsTheSession() { + val model = + meshModel().let { base -> + base.copy(drawables = base.drawables + base.drawables.first().copy(id = DrawableId("d2"), name = "d2")) + } + val session = EditorSession(model) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + assertEquals(listOf(DrawableId("d")), session.meshSelection.value.drawableIds) + + session.switchEditDrawable(DrawableId("d2")) + assertEquals(listOf(DrawableId("d2")), session.meshSelection.value.drawableIds, "the session re-seeds onto the target") + assertEquals(DrawableId("d2"), session.meshSelection.value.activeDrawableId) + + session.undo() + assertEquals(listOf(DrawableId("d")), session.meshSelection.value.drawableIds, "the switch is one undoable step") + + // A mesh-less or unknown drawable refuses the switch. + session.switchEditDrawable(DrawableId("missing")) + assertEquals(listOf(DrawableId("d")), session.meshSelection.value.drawableIds) + } + + /** Helper so the bounds test can assert the session's undo is a no-op without exposing internals. */ + private object EditorSnapshotProbe { + fun undoResult(session: EditorSession): Unit? { + val before = session.model.value + session.undo() + return if (session.model.value === before) null else Unit + } + + fun jumpResult(session: EditorSession, index: Int): Unit? { + val before = session.historyView.value.cursor + session.jumpTo(index) + return if (session.historyView.value.cursor == before) null else Unit + } + } + + /** + * The idle gate a watched-file reload waits behind: every latch that means a hand is mid-gesture + * closes it, and releasing the latch opens it again. + */ + @Test + fun quiescenceFollowsEveryLatch() { + val session = EditorSession(model()) + assertTrue(session.isQuiescent, "a fresh session is idle") + session.setViewportGestureActive(true) + assertFalse(session.isQuiescent, "a viewport drag") + session.setViewportGestureActive(false) + assertTrue(session.isQuiescent) + session.setPreviewSelection(emptySet()) + assertFalse(session.isQuiescent, "a circle stroke") + session.setPreviewSelection(null) + assertTrue(session.isQuiescent) + session.openPieMenu(PieMenuKind.Snap) + assertFalse(session.isQuiescent, "an open pie menu") + session.closePieMenu() + assertTrue(session.isQuiescent) + session.emitNotice("notice.test", NoticePlacement.StatusBar, listOf("7")) + assertEquals(listOf("7"), session.notice.value?.arguments, "a notice carries its arguments") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/FreeTransformTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/FreeTransformTest.kt new file mode 100644 index 0000000..1708821 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/FreeTransformTest.kt @@ -0,0 +1,135 @@ +package org.umamo.edit + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins Photoshop-style free-transform scale math: opposite-corner pivots, edge-only axes, Alt-from-center, + * and Shift-uniform on corners. + */ +class FreeTransformTest { + /** A 40 x 20 axis-aligned quad from (-10, -5) to (30, 15). */ + private val quad = + floatArrayOf( + -10f, + -5f, + 30f, + -5f, + 30f, + 15f, + -10f, + 15f, + ) + + private val all = setOf(0, 1, 2, 3) + + @Test + fun selectionBoundsReportsMinMax() { + val bounds = selectionBounds(quad, all) + assertEquals(-10f, bounds.minX) + assertEquals(-5f, bounds.minY) + assertEquals(30f, bounds.maxX) + assertEquals(15f, bounds.maxY) + assertEquals(40f, bounds.width) + assertEquals(20f, bounds.height) + } + + @Test + fun cornerDragScalesAboutOppositeCorner() { + val start = selectionBounds(quad, all) + // Drag the max-x / max-y corner to twice the width and height from the opposite corner. + val targetX = start.minX + start.width * 2f + val targetY = start.minY + start.height * 2f + val scaled = + scaledByHandleDrag( + quad, + all, + start, + BoundsHandle.MaxXMaxY, + targetX, + targetY, + ) + val bounds = selectionBounds(scaled, all) + assertEquals(start.minX, bounds.minX, 1e-4f) + assertEquals(start.minY, bounds.minY, 1e-4f) + assertEquals(start.width * 2f, bounds.width, 1e-4f) + assertEquals(start.height * 2f, bounds.height, 1e-4f) + } + + @Test + fun edgeDragScalesOnlyOneAxis() { + val start = selectionBounds(quad, all) + val scaled = + scaledByHandleDrag( + quad, + all, + start, + BoundsHandle.MaxXMidY, + start.minX + start.width * 1.5f, + start.centerY, + ) + val bounds = selectionBounds(scaled, all) + assertEquals(start.width * 1.5f, bounds.width, 1e-4f) + assertEquals(start.height, bounds.height, 1e-4f) + assertEquals(start.minX, bounds.minX, 1e-4f) + } + + @Test + fun fromCenterKeepsBoundsCenterFixed() { + val start = selectionBounds(quad, all) + val scaled = + scaledByHandleDrag( + quad, + all, + start, + BoundsHandle.MaxXMaxY, + start.centerX + start.width, + start.centerY + start.height, + fromCenter = true, + ) + val bounds = selectionBounds(scaled, all) + assertEquals(start.centerX, bounds.centerX, 1e-4f) + assertEquals(start.centerY, bounds.centerY, 1e-4f) + assertEquals(start.width * 2f, bounds.width, 1e-4f) + assertEquals(start.height * 2f, bounds.height, 1e-4f) + } + + @Test + fun uniformCornerUsesSharedFactor() { + val start = selectionBounds(quad, all) + // Pull mostly in x; with uniform, y should match the x factor. + val scaled = + scaledByHandleDrag( + quad, + all, + start, + BoundsHandle.MaxXMaxY, + start.minX + start.width * 2f, + start.minY + start.height * 1.1f, + uniform = true, + ) + val bounds = selectionBounds(scaled, all) + assertEquals(start.width * 2f, bounds.width, 1e-4f) + assertEquals(start.height * 2f, bounds.height, 1e-4f) + } + + @Test + fun degenerateAxisStaysFinite() { + val flat = floatArrayOf(0f, 7f, 10f, 7f, 20f, 7f) + val indices = setOf(0, 1, 2) + val start = selectionBounds(flat, indices) + val scaled = + scaledByHandleDrag( + flat, + indices, + start, + BoundsHandle.MaxXMaxY, + 40f, + 100f, + ) + assertTrue(scaled.all { it.isFinite() }) + val bounds = selectionBounds(scaled, indices) + assertEquals(0f, bounds.height, 1e-4f) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/HistoryAmendTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/HistoryAmendTest.kt new file mode 100644 index 0000000..1352a34 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/HistoryAmendTest.kt @@ -0,0 +1,83 @@ +package org.umamo.edit + +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins [History.amendTop], the primitive behind adjusting the last operation: it rewrites the live + * step in place without growing the stack or moving the cursor, refuses while a redo branch exists, + * and works at the oldest entry under a cap of one. + */ +class HistoryAmendTest { + private val part = Part(PartId("a"), "A", children = emptyList()) + + private fun model(name: String): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(part.copy(name = name)), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(PartId("a"))), + rootPartId = null, + ) + + private fun snapshot(name: String): EditorSnapshot = EditorSnapshot(model(name), Selection(), emptyMap()) + + private fun rename(name: String): PartChange.Rename = PartChange.Rename(PartId("a"), name) + + private fun liveName(history: History): String = history.current.model.parts.first().name + + @Test + fun amendingReplacesTheLiveStepWithoutGrowingTheStack() { + val history = History(snapshot("seed")) + history.push(snapshot("first"), rename("first")) + history.push(snapshot("second"), rename("second")) + val adjusted = rename("second-adjusted") + + assertTrue(history.amendTop(snapshot("second-adjusted"), adjusted)) + + assertEquals(3, history.steps.size, "the stack did not grow") + assertEquals(2, history.cursorIndex, "the cursor stayed on the live step") + assertEquals("second-adjusted", liveName(history)) + assertSame(adjusted, history.currentChange, "the entry carries the amended change") + history.undo() + assertEquals("first", liveName(history), "undo steps to the base the operation ran from") + history.redo() + assertEquals("second-adjusted", liveName(history), "redo returns to the amended result") + } + + @Test + fun anAmendRefusesWhileARedoBranchExists() { + val history = History(snapshot("seed")) + history.push(snapshot("first"), rename("first")) + history.push(snapshot("second"), rename("second")) + history.undo() + + assertFalse(history.amendTop(snapshot("first-adjusted"), rename("first-adjusted"))) + + assertEquals("first", liveName(history), "the refused amend changed nothing") + history.redo() + assertEquals("second", liveName(history), "the redo branch survived") + } + + @Test + fun anAmendAtTheOldestEntryWorksUnderACapOfOne() { + val history = History(snapshot("seed"), initialLimit = 1) + history.push(snapshot("first"), rename("first")) + assertEquals(1, history.steps.size, "the cap dropped the seed") + assertEquals(0, history.cursorIndex) + + assertTrue(history.amendTop(snapshot("first-adjusted"), rename("first-adjusted"))) + + assertEquals("first-adjusted", liveName(history)) + assertEquals(1, history.steps.size) + assertFalse(history.canUndo, "no base survives in the stack - the record holds it instead") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/HistoryLimitTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/HistoryLimitTest.kt new file mode 100644 index 0000000..113c2e8 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/HistoryLimitTest.kt @@ -0,0 +1,181 @@ +package org.umamo.edit + +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Verifies the retained-undo-step cap: that pushing past it drops the oldest steps while keeping the + * cursor on the live one, that a degenerate cap still retains a usable stack, and that reassigning the + * cap at runtime (what the History Steps preference does) trims immediately without ever discarding the + * live step or a reachable redo branch. + */ +class HistoryLimitTest { + private val part = Part(PartId("a"), "A", children = emptyList()) + + private fun model(name: String): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(part.copy(name = name)), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(PartId("a"))), + rootPartId = null, + ) + + private fun snapshot(name: String): EditorSnapshot = EditorSnapshot(model(name), Selection(), emptyMap()) + + /** + * Pushes [count] distinguishable steps, numbered from 1 so a step's name identifies its ordinal. + * + * @param History history The stack to push onto. + * @param Int count The number of steps to record. + */ + private fun pushSteps(history: History, count: Int) { + for (stepNumber in 1..count) { + history.push(snapshot("step$stepNumber"), PartChange.Rename(PartId("a"), "step$stepNumber")) + } + } + + /** + * The name carried by the live step, which identifies which push the cursor sits on. + * + * @param History history The stack to read. + * @return String The live snapshot's part name. + */ + private fun liveName(history: History): String = history.current.model.parts.first().name + + /** + * Pushing past the cap drops the oldest steps from the front, leaving the stack exactly at the cap with + * the cursor still on the newest push. + */ + @Test + fun pushingPastTheCapDropsTheOldestSteps() { + val history = History(snapshot("seed"), 5) + pushSteps(history, 12) + + assertEquals(5, history.steps.size) + assertEquals(4, history.cursorIndex) + assertEquals("step12", liveName(history)) + // The seed and steps 1-7 are gone; the retained window starts at step 8. + assertEquals("step8", history.steps.first().snapshot.model.parts.first().name) + } + + /** + * A cap below 1 clamps to a single retained step rather than emptying the stack, so the live state is + * always readable and the stack never indexes out of range. + */ + @Test + fun capBelowOneClampsToASingleRetainedStep() { + val history = History(snapshot("seed"), 0) + assertEquals(1, history.limit) + + pushSteps(history, 3) + assertEquals(1, history.steps.size) + assertEquals(0, history.cursorIndex) + assertEquals("step3", liveName(history)) + assertTrue(!history.canUndo && !history.canRedo, "a one-step stack has nothing to undo or redo") + + history.limit = -10 + assertEquals(1, history.limit) + assertEquals(1, history.steps.size) + } + + /** + * Lowering the cap trims the stack there and then - the preference frees memory without waiting for the + * next edit - while the live step itself is untouched. + */ + @Test + fun loweringTheCapTrimsImmediately() { + val history = History(snapshot("seed"), 100) + pushSteps(history, 20) + val liveSnapshot = history.current + + history.limit = 4 + + assertEquals(4, history.steps.size) + assertEquals(3, history.cursorIndex) + assertSame(liveSnapshot, history.current, "trimming must not move the live step") + assertEquals("step17", history.steps.first().snapshot.model.parts.first().name) + } + + /** + * With the cursor mid-history the trim stops at the live step: the current state and every reachable + * redo step survive, so the stack may legitimately still exceed the cap until later pushes shed it. + */ + @Test + fun loweringTheCapNeverTrimsPastTheLiveStep() { + val history = History(snapshot("seed"), 100) + pushSteps(history, 20) + // Walk back five steps, so the cursor sits at index 15 with a five-entry redo branch ahead of it. + repeat(5) { history.undo() } + val liveSnapshot = history.current + assertEquals("step15", liveName(history)) + + history.limit = 2 + + assertSame(liveSnapshot, history.current, "the live step must survive any trim") + assertEquals(0, history.cursorIndex, "the trim stops once the live step reaches the front") + // Six entries remain: the live step plus the five redo steps it can still reach. + assertEquals(6, history.steps.size) + assertTrue(history.canRedo, "a reachable redo branch is never discarded by a trim") + assertTrue(!history.canUndo, "everything before the live step was trimmed away") + + // The excess sheds on the next push, which discards the redo branch and applies the cap in full. + history.push(snapshot("after"), PartChange.Rename(PartId("a"), "after")) + assertEquals(2, history.steps.size) + assertEquals("after", liveName(history)) + } + + /** + * Raising the cap keeps every retained entry and simply allows the stack to grow further. + */ + @Test + fun raisingTheCapKeepsExistingSteps() { + val history = History(snapshot("seed"), 5) + pushSteps(history, 5) + assertEquals(5, history.steps.size) + + history.limit = 10 + assertEquals(5, history.steps.size, "raising the cap discards nothing") + assertEquals("step5", liveName(history)) + + pushSteps(history, 5) + assertEquals(10, history.steps.size) + } + + /** + * The session's cap - the property the preference writes - trims the stack and republishes the derived + * state, so the history panel drops the same rows and canUndo reflects the shortened stack. + */ + @Test + fun sessionCapTrimsAndRepublishesTheHistoryView() { + val session = EditorSession(model("A")) + for (stepNumber in 1..8) { + session.mutate(PartChange.Rename(PartId("a"), "A$stepNumber")) { it.withPartName(PartId("a"), "A$stepNumber") } + } + // Seed plus eight edits. + assertEquals(9, session.historyView.value.steps.size) + assertTrue(session.canUndo.value) + + session.historyLimit = 3 + + val view = session.historyView.value + assertEquals(3, view.steps.size) + assertEquals(2, view.cursor) + assertEquals("A8", session.model.value.parts.first().name, "trimming must not change the live model") + assertTrue(session.canUndo.value, "two older steps are still retained") + + // Down to a single step: nothing is left to undo, and the panel shows exactly the live row. + session.historyLimit = 1 + assertEquals(1, session.historyView.value.steps.size) + assertEquals(0, session.historyView.value.cursor) + assertTrue(!session.canUndo.value) + assertEquals("A8", session.model.value.parts.first().name) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/KeySelectionTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeySelectionTest.kt new file mode 100644 index 0000000..1f0b4e7 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeySelectionTest.kt @@ -0,0 +1,184 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The keyform sheet's key selection as session state, and the two ways of publishing one. + * + * The distinction under test is the whole reason [EditorSession.stageKeySelection] exists: a click on a mark + * both selects the key and scrubs the pose onto it, and recording those separately makes one click take two + * presses of Ctrl+Z to reverse. Staging folds the selection into the step the scrub is about to record. + */ +class KeySelectionTest { + private val angleX = ParameterId("ParamAngleX") + + private fun session(): EditorSession = + EditorSession( + PuppetModel( + parameters = listOf(Parameter(angleX, angleX.raw, min = -30f, max = 30f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + + private fun keyAt(keyIndex: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:d/OPACITY", keyIndex) + + /** A fresh document has nothing selected. */ + @Test + fun startsEmpty() { + assertTrue(session().keySelection.value.isEmpty()) + } + + /** Selecting keys is its own undo step, and undo brings the previous selection back. */ + @Test + fun selectingIsItsOwnUndoStep() { + val editorSession = session() + editorSession.setKeySelection(setOf(keyAt(0))) + editorSession.setKeySelection(setOf(keyAt(0), keyAt(1))) + + assertEquals(setOf(keyAt(0), keyAt(1)), editorSession.keySelection.value) + editorSession.undo() + assertEquals(setOf(keyAt(0)), editorSession.keySelection.value, "back to the first selection") + editorSession.undo() + assertTrue(editorSession.keySelection.value.isEmpty(), "and back to none") + } + + /** Selecting what is already selected records nothing - a re-click is not an edit. */ + @Test + fun reselectingTheSameKeysRecordsNothing() { + val editorSession = session() + editorSession.setKeySelection(setOf(keyAt(0))) + editorSession.setKeySelection(setOf(keyAt(0))) + + editorSession.undo() + assertTrue(editorSession.keySelection.value.isEmpty(), "one undo, not two") + } + + /** A selection is not a document change, so it must not mark the file unsaved. */ + @Test + fun selectingDoesNotDirtyTheDocument() { + val editorSession = session() + editorSession.setKeySelection(setOf(keyAt(0))) + + assertFalse(editorSession.dirty.value) + } + + /** + * A staged selection publishes immediately but records nothing on its own - the commit that follows + * carries it, so the pair is ONE undo step. + */ + @Test + fun aStagedSelectionRidesTheFollowingCommit() { + val editorSession = session() + editorSession.stageKeySelection(setOf(keyAt(2))) + assertEquals(setOf(keyAt(2)), editorSession.keySelection.value, "it publishes at once") + assertFalse(editorSession.canUndo.value, "but records nothing by itself") + + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f)) + editorSession.undo() + + assertTrue(editorSession.keySelection.value.isEmpty(), "one undo reverses the click's selection") + assertEquals(0f, editorSession.pose.value[angleX], "and its scrub, together") + assertFalse(editorSession.canUndo.value, "because they were one step") + } + + /** + * Clicking a mark selects it AND lands the pose on it, as one step named for the selection. + * + * The label matters: the entry used to read "Adjust Parameters", which described the consequence rather + * than the act - the rigger clicked a keyframe. + */ + @Test + fun selectingAtAPoseIsOneStepNamedForTheSelection() { + val editorSession = session() + editorSession.selectKeysAtPose(setOf(keyAt(1)), mapOf(angleX to 30f)) + + assertEquals(setOf(keyAt(1)), editorSession.keySelection.value) + assertEquals(30f, editorSession.pose.value[angleX]) + assertEquals("change.keyform.select", editorSession.liveStepLabelKey(), "named for the selection") + + editorSession.undo() + assertTrue(editorSession.keySelection.value.isEmpty(), "one undo reverses both") + assertEquals(0f, editorSession.pose.value[angleX]) + assertFalse(editorSession.canUndo.value) + } + + /** + * Clicking the key the pose ALREADY sits on still records the selection. + * + * The case that rules out staging the selection behind an ordinary pose commit: that commit + * short-circuits on an unchanged pose, so the selection would never reach history at all and the click + * would be silently unrecoverable. + */ + @Test + fun selectingWithoutMovingThePoseStillRecords() { + val editorSession = session() + editorSession.selectKeysAtPose(setOf(keyAt(0)), editorSession.pose.value) + + assertTrue(editorSession.canUndo.value, "the selection is the whole step here") + editorSession.undo() + assertTrue(editorSession.keySelection.value.isEmpty()) + } + + /** Re-clicking the same key at the same pose records nothing. */ + @Test + fun reselectingAtTheSamePoseRecordsNothing() { + val editorSession = session() + editorSession.selectKeysAtPose(setOf(keyAt(0)), editorSession.pose.value) + editorSession.selectKeysAtPose(setOf(keyAt(0)), editorSession.pose.value) + + editorSession.undo() + assertTrue(editorSession.keySelection.value.isEmpty(), "one undo, not two") + } + + /** + * A staged selection the following commit DECLINED to record is recorded by the confirming + * [EditorSession.setKeySelection] instead. + * + * The gesture is an empty-track press at the value the playhead already holds: it drops the selection and + * then scrubs nowhere, so the pose commit short-circuits. Staging alone left the selection changed with + * nothing in history to undo it - the one failure mode the stage / edit / confirm rule exists to close. + */ + @Test + fun aStagedSelectionTheCommitDroppedIsRecordedByTheConfirm() { + val editorSession = session() + editorSession.setKeySelection(setOf(keyAt(0), keyAt(1))) + + editorSession.stageKeySelection(emptySet()) + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), editorSession.pose.value) + editorSession.setKeySelection(editorSession.keySelection.value) + + assertTrue(editorSession.keySelection.value.isEmpty(), "the press dropped the selection") + editorSession.undo() + assertEquals(setOf(keyAt(0), keyAt(1)), editorSession.keySelection.value, "and undo brings it back") + } + + /** + * The confirm is a no-op when the edit it follows already carried the staged selection - one gesture + * stays one undo step. + */ + @Test + fun confirmingASelectionTheCommitAlreadyCarriedRecordsNothing() { + val editorSession = session() + editorSession.stageKeySelection(setOf(keyAt(2))) + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f)) + editorSession.setKeySelection(setOf(keyAt(2))) + + editorSession.undo() + assertTrue(editorSession.keySelection.value.isEmpty(), "one undo reverses the whole gesture") + assertEquals(0f, editorSession.pose.value[angleX], "selection and scrub together") + assertFalse(editorSession.canUndo.value, "so the confirm added no second step") + } + + /** The label key of the live history step - what the History panel would show for it. */ + private fun EditorSession.liveStepLabelKey(): String? = historyView.value.let { view -> view.steps[view.cursor].labelKey } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformAimEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformAimEditsTest.kt new file mode 100644 index 0000000..40a97a1 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformAimEditsTest.kt @@ -0,0 +1,257 @@ +package org.umamo.edit + +import org.umamo.runtime.keyform.axisIndexOf +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the keyform AIM semantics - which parameter an edit writes on, and whether it acts where the user + * pointed or where the pose stands. + * + * These rules used to live in the UI module taking a Compose hover type, where nothing could exercise them + * without a composition; both of the bugs they encode (an aimed edit landing on the targeted axis instead of + * the pointed-at one, and an aim at empty track space falling back to the pose) shipped because of that. + */ +class KeyformAimEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val drawableId = DrawableId("d") + private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY) + private val track = KeyformTrackRef.Channel(target) + + /** The sheet row the opacity track is drawn on - opaque to this module, and identity for a selected key. */ + private val row = "drawable:d/OPACITY" + + /** + * A session whose drawable has an opacity track keyed at the ends of [keyedOn]'s range, with both + * parameters present and [ParameterId] angleX targeted. + */ + private fun session(keyedOn: ParameterId = angleX): EditorSession { + val opacityTrack = + KeyformGrid( + listOf(KeyformAxis(keyedOn, floatArrayOf(-1f, 1f))), + listOf>( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(0.25f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)), + ), + ) + val drawable = + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack)), + ) + val editorSession = + EditorSession( + PuppetModel( + parameters = + listOf( + Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f), + Parameter(angleY, angleY.raw, min = -1f, max = 1f, default = 0f), + ), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + editorSession.setParameterSelection(ParameterSelection.of(angleX)) + return editorSession + } + + /** The opacity track's key positions on [parameterId]'s axis, or null when it is not keyed on it. */ + private fun EditorSession.keysOn(parameterId: ParameterId): List? { + val grid = model.value.drawables.single().channelGrids[FormChannel.OPACITY] ?: return null + val axisIndex = grid.axisIndexOf(parameterId) + return if (axisIndex < 0) null else grid.axes[axisIndex].keys.toList() + } + + /** An aimed capture keys WHERE it was aimed, not at the pose the rig happens to stand in. */ + @Test + fun anAimedCaptureKeysWhereItWasAimed() { + val editorSession = session() + + editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Position(0.5f, keyIndex = null)) + + assertEquals(listOf(-1f, 0.5f, 1f), editorSession.keysOn(angleX)) + } + + /** A capture at the pose stores the PENDING typed value and consumes it. */ + @Test + fun aPoseCaptureStoresThePendingEdit() { + val editorSession = session() + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + + editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Pose) + + assertEquals(listOf(-1f, 0f, 1f), editorSession.keysOn(angleX), "the pose's key was added") + assertEquals( + ChannelValue.Scalar(0.75f), + editorSession.model.value.channelValueAt(target, editorSession.pose.value), + "the key holds the value that was typed, not the value that was stored", + ) + assertTrue(editorSession.pendingChannelEdits.value.isEmpty(), "the captured pending edit was consumed") + } + + /** + * The capture's own history step records the pending edit as CONSUMED, so redo does not resurrect it. + * + * A snapshot defaults every field to live state, so clearing the pending edit after the capture pushed + * left the consumed value inside the step that consumed it: redoing the capture re-showed the + * uncommitted-edit warning over the very key that now stores the value, and left the session's live map + * disagreeing with its own history about what was still pending. + */ + @Test + fun redoingAPoseCaptureDoesNotResurrectTheConsumedEdit() { + val editorSession = session() + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + + editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Pose) + editorSession.undo() + editorSession.redo() + + assertTrue( + editorSession.pendingChannelEdits.value.isEmpty(), + "the capture step holds no pending edit, because the capture is what consumed it", + ) + assertEquals(listOf(-1f, 0f, 1f), editorSession.keysOn(angleX), "and the key it captured is back") + } + + /** + * An aimed edit keeps the sheet's key selection on the key it named, as ONE undo step. + * + * Both directions of the same renumbering rule. An insert shifts every key at or above it up one + * ordinal, so a selected mark to the right of the insertion point must shift with it to keep naming the + * same key; a removal shifts every key above it down one ordinal, so a selected mark above a removed key + * must shift the same way rather than staying on the ordinal the removal freed. + */ + @Test + fun anAimedEditCarriesTheKeySelectionWithIt() { + val editorSession = session() + // Keys at [-1, 1] with the one at 1 selected; the insert at 0 lands between them. + editorSession.setKeySelection(setOf(TrackKeyRef(angleX, row, 1))) + + editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Position(0f, keyIndex = null), row) + + assertEquals(listOf(-1f, 0f, 1f), editorSession.keysOn(angleX)) + assertEquals( + setOf(TrackKeyRef(angleX, row, 2)), + editorSession.keySelection.value, + "the selection follows its own key past the one just inserted below it", + ) + + // And back out again: the removal renumbers the other way. + editorSession.removeKeyOnTrack(track, angleX, KeyformAim.Position(0f, keyIndex = 1), row) + + assertEquals(listOf(-1f, 1f), editorSession.keysOn(angleX)) + assertEquals( + setOf(TrackKeyRef(angleX, row, 1)), + editorSession.keySelection.value, + "and back down again when the key below it goes", + ) + } + + /** An insert ABOVE the selection renumbers nothing, and the whole capture stays one undo step. */ + @Test + fun anInsertAboveTheSelectionLeavesItAloneAndRecordsOneStep() { + val editorSession = session() + editorSession.setKeySelection(setOf(TrackKeyRef(angleX, row, 0))) + + editorSession.captureKeyOnTrack(track, angleX, KeyformAim.Position(0f, keyIndex = null), row) + + assertEquals(setOf(TrackKeyRef(angleX, row, 0)), editorSession.keySelection.value, "nothing below it moved") + editorSession.undo() + assertEquals(listOf(-1f, 1f), editorSession.keysOn(angleX), "one undo reverses the whole capture") + assertEquals(setOf(TrackKeyRef(angleX, row, 0)), editorSession.keySelection.value) + } + + /** + * Aiming at track space with no key there removes NOTHING - it must not fall back to the pose, which + * would destroy a key the user never pointed at. + */ + @Test + fun anAimAtEmptyTrackSpaceRemovesNothing() { + val editorSession = session() + // The pose stands exactly on a key, so a pose-fallback would have something to delete. + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to -1f)) + val modelBefore = editorSession.model.value + + editorSession.removeKeyOnTrack(track, angleX, KeyformAim.Position(0.3f, keyIndex = null)) + + assertSame(modelBefore, editorSession.model.value, "aiming at nothing removed nothing") + assertEquals(listOf(-1f, 1f), editorSession.keysOn(angleX)) + } + + /** With no place aimed at, a removal takes the key the pose is standing on. */ + @Test + fun aPoseRemovalTakesTheKeyUnderThePose() { + val editorSession = session() + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to -1f)) + + editorSession.removeKeyOnTrack(track, angleX, KeyformAim.Pose) + + assertEquals(null, editorSession.keysOn(angleX), "the last key went, so the channel is unkeyed again") + } + + /** + * A named parameter beats the targeted one: a linked pad's second section is keyed on an axis that is + * not the selection's active member, and an edit aimed there must land on THAT axis. + */ + @Test + fun theNamedParameterBeatsTheTargetedOne() { + val editorSession = session(keyedOn = angleY) + assertEquals(angleX, editorSession.parameterSelection.value.active, "angleX is what is targeted") + + editorSession.captureKeyOnTrack(track, angleY, KeyformAim.Position(0.5f, keyIndex = null)) + + assertEquals(listOf(-1f, 0.5f, 1f), editorSession.keysOn(angleY), "the key landed on the named axis") + assertEquals(null, editorSession.keysOn(angleX), "the targeted axis was not touched") + } + + /** With no parameter named, the edit falls back to the targeted one. */ + @Test + fun anUnnamedParameterFallsBackToTheTarget() { + val editorSession = session() + + editorSession.captureKeyOnTrack(track, parameterId = null, aim = KeyformAim.Position(0.5f, keyIndex = null)) + + assertEquals(listOf(-1f, 0.5f, 1f), editorSession.keysOn(angleX)) + } + + /** With nothing named and nothing targeted there is no axis to write on, so the model is untouched. */ + @Test + fun noParameterAtAllRefuses() { + val editorSession = session() + editorSession.setParameterSelection(ParameterSelection()) + val modelBefore = editorSession.model.value + + editorSession.captureKeyOnTrack(track, parameterId = null, aim = KeyformAim.Position(0.5f, keyIndex = null)) + + assertSame(modelBefore, editorSession.model.value) + assertNotNull(editorSession.notice.value, "the refusal is announced rather than silent") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformChannelEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformChannelEditsTest.kt new file mode 100644 index 0000000..5f4d6b0 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformChannelEditsTest.kt @@ -0,0 +1,232 @@ +package org.umamo.edit + +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the scalar / color keyform authoring loop: bind, capture, remove, and undo. + * + * These channels come first precisely because they need no deformer-chain inverse - the capture always + * lands on a key, so the write is a plain assignment. What the tests below are really guarding is the two + * evaluator-forced invariants that make the difference between a key that works and one that makes art + * disappear: a seeded axis SPANS the parameter's range, and removal COLLAPSES below two keys. + */ +class KeyformChannelEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val drawableId = DrawableId("d") + private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY) + + private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -30f, max = 30f, default = 0f) + + private fun model(): PuppetModel = + PuppetModel( + parameters = listOf(parameter(angleX), parameter(angleY)), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + opacity = 0.25f, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** The opacity a model's drawable evaluates to at [value] on [parameterId]. */ + private fun opacityAt(puppet: PuppetModel, parameterId: ParameterId, value: Float): Float { + val drawable = puppet.drawables.single() + return drawable.channelGrids.scalarAt( + FormChannel.OPACITY, + drawable.opacity, + paramValue = { id -> if (id == parameterId) value else 0f }, + ) + } + + /** + * The first capture BINDS: it seeds an axis spanning min / default / max holding the entity's current + * static value, then writes the captured value at the pose. + * + * Spanning matters - an axis that stopped short would leave the channel falling back to its static at + * the ends of the slider, which reads as the key mysteriously not applying. + */ + @Test + fun theFirstCaptureBindsAnAxisSpanningTheRange() { + val captured = + model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + + val track = assertNotNull(captured.drawables.single().channelGrids[FormChannel.OPACITY]) + assertEquals(listOf(angleX), track.axes.map { it.parameterId }) + assertEquals(listOf(-30f, 0f, 15f, 30f), track.axes.single().keys.toList(), "seeded min/default/max plus the captured key") + assertEquals(1f, opacityAt(captured, angleX, 15f), "the captured value lands at the pose") + assertEquals(0.25f, opacityAt(captured, angleX, -30f), "the static holds at the ends - binding alone changed nothing") + assertEquals(0.25f, opacityAt(captured, angleX, 30f)) + } + + /** Capturing on a second parameter adds an axis and preserves the motion already authored. */ + @Test + fun capturingOnASecondParameterPreservesExistingMotion() { + val first = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 30f), ChannelValue.Scalar(1f)) + val second = first.withChannelKeyCaptured(target, parameter(angleY), mapOf(angleY to 30f), ChannelValue.Scalar(0.5f)) + + val track = assertNotNull(second.drawables.single().channelGrids[FormChannel.OPACITY]) + assertEquals(listOf(angleX, angleY), track.axes.map { it.parameterId }, "the new axis is appended") + // angleY sits at its default, so the angleX motion authored first must read back unchanged. + assertEquals(1f, opacityAt(second, angleX, 30f), "the first parameter's motion survives the second bind") + } + + /** A capture at a pose already on a key overwrites that cell without reshaping the axis. */ + @Test + fun capturingOnAnExistingKeyOverwrites() { + val first = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + val second = first.withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(0.5f)) + + val track = assertNotNull(second.drawables.single().channelGrids[FormChannel.OPACITY]) + assertEquals(4, track.axes.single().keys.size, "no new key was added") + assertEquals(0.5f, opacityAt(second, angleX, 15f)) + } + + /** + * A capture on a parameter whose range cannot seed an axis (min == max) is refused ENTIRELY. The old + * receiver-returning refusal let the capture proceed and write keys onto the channel's OTHER axes - + * mutating motion on a parameter the user never targeted. + */ + @Test + fun aCaptureOnADegenerateParameterIsRefusedEntirely() { + val degenerate = Parameter(angleY, angleY.raw, min = 5f, max = 5f, default = 5f) + val first = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + + val second = first.withChannelKeyCaptured(target, degenerate, mapOf(angleX to 30f, angleY to 5f), ChannelValue.Scalar(0.1f)) + + assertSame(first, second, "the refusal must not write onto the channel's other axes") + } + + /** + * A capture whose pose falls in the window between EPS_KEY (not on a key) and EPS_SPAN (too close to + * insert beside one) refuses the WHOLE op. The old guard compared against the pre-seed grid, so a + * fresh bind whose capture then refused still committed the bare axis - the channel read as keyed while + * the typed value was silently dropped. + */ + @Test + fun aCaptureInTheEpsilonWindowCommitsNoBareBind() { + val start = model() + val captured = start.withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 0.00125f), ChannelValue.Scalar(1f)) + assertSame(start, captured, "no bind-only commit: the channel must not read as keyed without the value") + } + + /** + * An insert aimed past the parameter's ends clamps to the range - the lane's edge inset extrapolates + * pixel hits past the domain, and an unclamped insert would author a key no scrub can ever reach. + */ + @Test + fun anInsertPastTheRangeClampsToTheEnd() { + val editorSession = + EditorSession(model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f))) + editorSession.insertTrackKeyAt(KeyformTrackRef.Channel(target), parameter(angleX), -31.7f) + + val axis = editorSession.model.value.drawables.single().channelGrids[FormChannel.OPACITY]!!.axes.single() + assertEquals(-30f, axis.keys.first(), "the clamped hit coincides with the min key, so nothing was added") + assertEquals(4, axis.keys.size, "no out-of-range key was authored") + } + + /** + * Inserting past the last authored key copies that last value, not the static (render's out-of-span + * fallback). Keys at -30/0/15 with last value 1; insert at 30 must land 1, not opacity 0.25. + */ + @Test + fun insertingPastTheLastKeyCopiesTheLastChannelValue() { + val keyed = + model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + // Drop the seeded max key so 30 sits past the authored span (keys become -30, 0, 15). + val shortened = keyed.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to 30f)) + val session = EditorSession(shortened) + session.insertTrackKeyAt(KeyformTrackRef.Channel(target), parameter(angleX), 30f) + + assertEquals(1f, opacityAt(session.model.value, angleX, 30f), "past-last insert holds the last authored value") + assertEquals( + listOf(-30f, 0f, 15f, 30f), + session.model.value.drawables.single().channelGrids[FormChannel.OPACITY]!!.axes.single().keys.toList(), + ) + } + + /** A value of the wrong kind for the channel is refused rather than silently stored. */ + @Test + fun aMismatchedValueKindIsRefused() { + val start = model() + val colorIntoScalar = + start.withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Color(ColorRgb(1f, 0f, 0f))) + assertSame(start, colorIntoScalar) + } + + /** Removing an interior key leaves the axis intact. */ + @Test + fun removingAnInteriorKeyKeepsTheAxis() { + val captured = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + val removed = captured.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to 15f)) + + val track = assertNotNull(removed.drawables.single().channelGrids[FormChannel.OPACITY]) + assertEquals(listOf(-30f, 0f, 30f), track.axes.single().keys.toList()) + } + + /** + * Removing down past two keys collapses the axis, and collapsing the only axis drops the track - the + * channel goes back to its static rather than being left on a one-key axis that resolves nowhere. + */ + @Test + fun removingPastTwoKeysUnbindsTheChannel() { + var puppet = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + for (keyValue in listOf(15f, 0f, -30f)) { + puppet = puppet.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to keyValue)) + } + assertTrue(puppet.drawables.single().channelGrids.isEmpty, "the track is gone") + assertFalse(puppet.isChannelKeyedOn(target, angleX)) + assertEquals(0.25f, opacityAt(puppet, angleX, 15f), "the channel reads its static again") + } + + /** A pose that is not ON a key removes nothing - picking "the nearest" would be a guess. */ + @Test + fun removingBetweenKeysIsARefusal() { + val captured = model().withChannelKeyCaptured(target, parameter(angleX), mapOf(angleX to 15f), ChannelValue.Scalar(1f)) + assertSame(captured, captured.withChannelKeyRemoved(target, parameter(angleX), mapOf(angleX to 7f))) + } + + /** Capture and removal are each one undo step, and undo restores the prior track exactly. */ + @Test + fun captureAndRemovalUndoAsSingleSteps() { + val session = EditorSession(model()) + session.captureChannelKey(target, parameter(angleX), ChannelValue.Scalar(1f)) + assertTrue(session.model.value.isChannelKeyedOn(target, angleX)) + + session.removeChannelKey(target, parameter(angleX)) + session.undo() + assertTrue(session.model.value.isChannelKeyedOn(target, angleX), "undo restores the removed key") + + session.undo() + assertFalse(session.model.value.isChannelKeyedOn(target, angleX), "undo again unbinds the channel") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformGeometryEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformGeometryEditsTest.kt new file mode 100644 index 0000000..2428c0b --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformGeometryEditsTest.kt @@ -0,0 +1,521 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The geometry-track key ops - the half of the keyform sheet that has no channel behind it. + * + * Worth its own suite because geometry is the majority of what a corpus rig puts on screen, and because + * its hide semantics differ per owner: a drawable falls back to its rest mesh when its grid goes away, a + * deformer has no rest lattice and would vanish. + */ +class KeyformGeometryEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val drawableId = DrawableId("d") + private val deformerId = DeformerId("w") + private val parameter = Parameter(angleX, "ParamAngleX", min = -30f, max = 30f, default = 0f) + + /** A three-key mesh-delta grid over ParamAngleX, one delta per key. */ + private fun meshGrid(): KeyformGrid = + KeyformGrid( + axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))), + cells = + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(-1f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(0f, 0f))), + KeyformCell(intArrayOf(2), MeshDeltaForm(floatArrayOf(1f, 0f))), + ), + ) + + private fun model(): PuppetModel = + PuppetModel( + parameters = listOf(parameter), + parts = emptyList(), + deformers = + listOf( + Deformer.Warp( + id = deformerId, + name = "w", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = true, + geometryGrid = + KeyformGrid( + axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))), + cells = + listOf( + KeyformCell(intArrayOf(0), WarpLatticeForm(FloatArray(8))), + KeyformCell(intArrayOf(1), WarpLatticeForm(FloatArray(8))), + KeyformCell(intArrayOf(2), WarpLatticeForm(FloatArray(8))), + ), + ), + ), + ), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = meshGrid(), + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** + * A two-parameter model whose drawable keys on the VERTICAL axis only - the linked-pad shape. + * + * A pad targets both its axes but reports only the horizontal one as active, so this is the model where + * "write on the active parameter" and "write on the one the rigger meant" give different answers. + */ + private fun padModel(): PuppetModel { + val vertical = Parameter(angleY, "ParamAngleY", min = -30f, max = 30f, default = 0f) + val onVertical = KeyformGrid(listOf(KeyformAxis(angleY, floatArrayOf(-30f, 0f, 30f))), meshGrid().cells) + val base = model() + return base.copy( + parameters = listOf(parameter, vertical), + drawables = listOf(base.drawables.single().copy(geometryGrid = onVertical)), + ) + } + + /** The drawable's geometry axis keys after an edit. */ + private fun keysOf(puppet: PuppetModel): List = + assertNotNull(puppet.drawables.single().geometryGrid).axes.single().keys.toList() + + /** Moving a geometry key repositions it without touching the cells it addresses. */ + @Test + fun movingAGeometryKeyRepositionsIt() { + val moved = model().withGeometryKeyMoved(KeyformOwner.Drawable(drawableId), parameter, keyIndex = 1, toValue = 12f) + assertEquals(listOf(-30f, 12f, 30f), keysOf(moved)) + assertEquals( + listOf(-1f, 0f, 1f), + assertNotNull(moved.drawables.single().geometryGrid) + .cells + .sortedBy { cell -> cell.coordinate[0] } + .map { cell -> cell.form.positionDeltas[0] }, + "a move changes key positions only - the cells stay where they were", + ) + } + + /** + * A key dragged past its neighbour CROSSES it, taking its own form along. + * + * The axis re-sorts and the cells permute to match, so the deformation the rigger authored stays with + * the key they dragged rather than staying at the ordinal it vacated. + */ + @Test + fun movingAGeometryKeyCrossesItsNeighbour() { + val moved = model().withGeometryKeyMoved(KeyformOwner.Drawable(drawableId), parameter, keyIndex = 1, toValue = 99f) + assertEquals(listOf(-30f, 30f, 99f), keysOf(moved), "the axis re-sorts") + assertEquals( + listOf(-1f, 1f, 0f), + assertNotNull(moved.drawables.single().geometryGrid) + .cells + .sortedBy { cell -> cell.coordinate[0] } + .map { cell -> cell.form.positionDeltas[0] }, + "the moved key's own form (0) travelled to the end; the key it passed (1) shifted down", + ) + } + + /** Inserting a geometry key holds the interpolated form, so the deformation through it is unchanged. */ + @Test + fun insertingAGeometryKeyHoldsTheInterpolatedForm() { + val inserted = model().withGeometryKeyInserted(KeyformOwner.Drawable(drawableId), parameter, 15f) + assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(inserted)) + val grid = assertNotNull(inserted.drawables.single().geometryGrid) + // Halfway between the deltas at 0 and 30, which hold 0 and 1. + val insertedCell = assertNotNull(grid.cells.firstOrNull { cell -> cell.coordinate[0] == 2 }) + assertEquals(0.5f, insertedCell.form.positionDeltas[0], 1e-5f) + } + + /** + * Sheet/lane insert past the last key copies that last keyform (hold), not the first. + * + * Capture samples out of the key span before writing; without hold-extrapolation that sample was the + * first cell (or rest-zero), so the new end key looked like the start of the axis. + */ + @Test + fun insertingPastTheLastKeyCopiesTheLastForm() { + val shortGrid = + KeyformGrid( + axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f))), + cells = + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(-1f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(7f, 0f))), + ), + ) + val shortWarp = + KeyformGrid( + axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f))), + cells = + listOf( + KeyformCell(intArrayOf(0), WarpLatticeForm(FloatArray(8) { -1f })), + KeyformCell(intArrayOf(1), WarpLatticeForm(FloatArray(8) { 7f })), + ), + ) + val base = model() + val session = + EditorSession( + base.copy( + drawables = listOf(base.drawables.single().copy(geometryGrid = shortGrid)), + deformers = + listOf( + (base.deformers.single() as Deformer.Warp).copy(geometryGrid = shortWarp), + ), + ), + ) + + session.insertTrackKeyAt(KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)), parameter, 30f) + val meshGrid = assertNotNull(session.model.value.drawables.single().geometryGrid) + assertEquals(listOf(-30f, 0f, 30f), meshGrid.axes.single().keys.toList()) + assertEquals( + 7f, + meshGrid.cells.first { cell -> cell.coordinate[0] == 2 }.form.positionDeltas[0], + "drawable past-last insert copies the last keyform", + ) + + session.insertTrackKeyAt(KeyformTrackRef.Geometry(KeyformOwner.Deformer(deformerId)), parameter, 30f) + val warpGrid = assertNotNull((session.model.value.deformers.single() as Deformer.Warp).geometryGrid) + assertEquals(listOf(-30f, 0f, 30f), warpGrid.axes.single().keys.toList()) + assertEquals( + 7f, + warpGrid.cells.first { cell -> cell.coordinate[0] == 2 }.form.controlPoints[0], + "warp past-last insert copies the last lattice, not the first", + ) + } + + /** Removing down past two keys collapses a drawable's axis - it falls back to its rest mesh. */ + @Test + fun removingCollapsesADrawablesAxis() { + val owner = KeyformOwner.Drawable(drawableId) + val once = model().withGeometryKeyRemoved(owner, parameter, keyIndex = 1) + assertEquals(listOf(-30f, 30f), keysOf(once)) + val twice = once.withGeometryKeyRemoved(owner, parameter, keyIndex = 1) + assertNull(twice.drawables.single().geometryGrid, "below two keys the axis collapses entirely") + } + + /** The same removal is REFUSED on a deformer, which has no rest lattice to fall back to. */ + @Test + fun removingRefusesToUnkeyADeformer() { + val owner = KeyformOwner.Deformer(deformerId) + val once = model().withGeometryKeyRemoved(owner, parameter, keyIndex = 1) + val warp = once.deformers.single() as Deformer.Warp + assertEquals(listOf(-30f, 30f), assertNotNull(warp.geometryGrid).axes.single().keys.toList()) + val refused = once.withGeometryKeyRemoved(owner, parameter, keyIndex = 1) + assertSame(once, refused, "collapsing a deformer's last axis would hide it, so it is refused") + } + + /** A part carries no geometry, so every op leaves the model alone rather than throwing. */ + @Test + fun ownersWithoutGeometryAreLeftAlone() { + val puppet = model() + val owner = KeyformOwner.Glue(drawableId, drawableId) + assertSame(puppet, puppet.withGeometryKeyMoved(owner, parameter, keyIndex = 0, toValue = 10f)) + assertSame(puppet, puppet.withGeometryKeyInserted(owner, parameter, 10f)) + assertSame(puppet, puppet.withGeometryKeyRemoved(owner, parameter, keyIndex = 0)) + } + + /** + * Two keys close enough to draw on the same pixel are still individually addressable. + * + * The case that made dragging one of a near-coincident pair move the other: a value-based lookup + * resolves to whichever key is nearer, and within EPS_KEY that is a coin toss. Nothing forbids keys + * this close - forbidding them would be the wrong cure - so the ordinal has to carry the identity. + */ + @Test + fun nearCoincidentKeysAreStillIndividuallyAddressable() { + val owner = KeyformOwner.Drawable(drawableId) + // Walk the middle key to within a hair of the last one, then move the LAST one and check the + // middle stayed put - a value-based lookup would have grabbed whichever it reached first. + val crowded = model().withGeometryKeyMoved(owner, parameter, keyIndex = 1, toValue = 30f) + val middle = keysOf(crowded)[1] + assertTrue(30f - middle < 0.01f, "the middle key should have clamped right up against the last (at $middle)") + val moved = crowded.withGeometryKeyMoved(owner, parameter, keyIndex = 2, toValue = 99f) + assertEquals(middle, keysOf(moved)[1], "moving the last key must not disturb the one beside it") + } + + /** + * A pose resolves to the ordinal of the key it is standing on, and to nothing between keys. + * + * What `Alt+I` acts on. Removing "the nearest key" instead would guess at which one the user meant, + * and a wrong guess silently destroys authored work. + */ + @Test + fun aPoseResolvesToTheKeyItStandsOn() { + val puppet = model() + val geometry = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + assertEquals(1, puppet.trackKeyIndexAtPose(geometry, parameter, mapOf(angleX to 0f))) + assertEquals(2, puppet.trackKeyIndexAtPose(geometry, parameter, mapOf(angleX to 30f))) + assertEquals(-1, puppet.trackKeyIndexAtPose(geometry, parameter, mapOf(angleX to 15f)), "between keys") + } + + /** An owner with no geometry resolves to nothing rather than throwing. */ + @Test + fun aTrackWithNoGridResolvesToNothing() { + val glue = KeyformTrackRef.Geometry(KeyformOwner.Glue(drawableId, drawableId)) + assertEquals(-1, model().trackKeyIndexAtPose(glue, parameter, mapOf(angleX to 0f))) + } + + /** + * Moving several keys to one destination is ONE undo step, and each lands on its own track. + * + * The summary-row drag: marks stacked at a value stay stacked, and one Ctrl+Z restores all of them. + */ + @Test + fun movingSeveralKeysToOneValueIsOneStep() { + val session = EditorSession(model()) + val drawableTrack = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + val deformerTrack = KeyformTrackRef.Geometry(KeyformOwner.Deformer(deformerId)) + session.moveTrackKeys( + listOf(Triple(drawableTrack, parameter, 1), Triple(deformerTrack, parameter, 1)), + toValue = 12f, + ) + + assertEquals(listOf(-30f, 12f, 30f), keysOf(session.model.value), "the drawable's key moved") + val warp = session.model.value.deformers.single() as Deformer.Warp + assertEquals( + listOf(-30f, 12f, 30f), + assertNotNull(warp.geometryGrid).axes.single().keys.toList(), + "and so did the deformer's, to the same place", + ) + + session.undo() + assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "one undo restores both") + assertTrue(!session.canUndo.value, "because there was only ever one step") + } + + /** + * A key dragged ONTO its neighbour reports its own new ordinal, not the neighbour's. + * + * Dragging a group into the axis end piles the leading key onto the key already sitting there, and the + * collision nudge pushes it EPS_SPAN aside. EPS_SPAN is WIDER than the EPS_KEY tolerance an + * ordinal lookup uses, so asking "which key is at the value I requested" found the key that was already + * there and handed back ITS ordinal - moving the sheet's selection onto the wrong mark, and collapsing + * two selected keys into one entry when both resolved to it. + */ + @Test + fun aKeyDraggedOntoItsNeighbourReportsItsOwnOrdinal() { + val session = EditorSession(model()) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + // Keys [-30, 0, 30] with 0 and 30 selected, dragged left until the key at 0 reaches the key at -30. + val landed = session.dragTrackKeys(listOf(Triple(track, parameter, 1), Triple(track, parameter, 2)), fraction = -0.5f) + + val keys = keysOf(session.model.value) + assertEquals(-30f, keys[0], "the key already at the end did not move") + assertTrue(keys[1] > -30f && keys[1] < -29.99f, "the dragged key was nudged clear of it, at ${keys[1]}") + assertEquals(0f, keys[2]) + assertEquals(listOf(1, 2), landed, "the dragged keys report THEIR ordinals, not the resident key's") + } + + /** + * With two parameters targeted and no axis named, an unaimed key edit PARKS instead of guessing. + * + * The linked-pad case: a 2D pad targets both its axes but reports only the horizontal one as active, so + * writing on the active one would silently always key the horizontal parameter and leave the vertical + * section reading as unkeyed. Answering the prompt replays the very same edit with the axis filled in. + */ + @Test + fun anAmbiguousTargetParksTheEditUntilAnAxisIsPicked() { + // The drawable keys on the VERTICAL axis only, while the pad reports the horizontal one as active - + // so writing on the active parameter would refuse outright and the pick has to be what decides. + val session = EditorSession(padModel()) + session.setParameterSelection(ParameterSelection(setOf(angleX, angleY), active = angleX)) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + + session.captureKeyOnTrack(track, parameterId = null, aim = KeyformAim.Position(15f, keyIndex = null)) + val parked = assertNotNull(session.pendingParameterChoice.value, "the edit parks rather than guessing") + assertEquals(KeyformAction.Capture, parked.action) + assertContentEquals(listOf(angleX, angleY), parked.candidates, "listed in model order") + assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "and nothing was written yet") + + session.resolveParameterChoice(angleY) + assertNull(session.pendingParameterChoice.value, "answering clears the prompt") + assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(session.model.value), "the key landed on the PICKED axis") + } + + /** A caller that names its axis - every sheet lane does - never sees the prompt. */ + @Test + fun aNamedAxisBypassesTheChoicePrompt() { + val session = EditorSession(padModel()) + session.setParameterSelection(ParameterSelection(setOf(angleX, angleY), active = angleX)) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + + session.captureKeyOnTrack(track, parameterId = angleY, aim = KeyformAim.Position(15f, keyIndex = null)) + assertNull(session.pendingParameterChoice.value, "a named axis is the answer, so nothing is asked") + assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(session.model.value)) + } + + /** + * Dragging a multi-key selection moves every member by the same distance, keeping their spacing. + * + * The whole point of a group drag: a delta applied per key preserves the shape the rigger authored, + * where the summary drag's send-them-all-to-one-value deliberately does not. + */ + @Test + fun draggingASelectionMovesEveryKeyByTheSameDistance() { + val session = EditorSession(model()) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + // -30 and 0, dragged a tenth of the 60-wide range: +6 each. + val landed = session.dragTrackKeys(listOf(Triple(track, parameter, 0), Triple(track, parameter, 1)), fraction = 0.1f) + + assertEquals(listOf(-24f, 6f, 30f), keysOf(session.model.value)) + assertEquals(listOf(0, 1), landed, "neither key crossed anything, so both keep their ordinals") + session.undo() + assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "one undo restores the whole drag") + assertTrue(!session.canUndo.value, "because it was one step") + } + + /** + * The drag stops at the MOST CONSTRAINED member rather than clamping each key on its own. + * + * Per-key clamping would let the keys nearest the end pile up while the rest kept travelling, silently + * destroying the spacing - which is exactly the thing a group drag exists to preserve. + */ + @Test + fun aGroupDragStopsAtItsMostConstrainedMember() { + val session = EditorSession(model()) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + // The key at 30 is already at the maximum, so the whole drag is refused rather than collapsing the pair. + session.dragTrackKeys(listOf(Triple(track, parameter, 1), Triple(track, parameter, 2)), fraction = 0.5f) + assertEquals(listOf(-30f, 0f, 30f), keysOf(session.model.value), "nothing moved, so nothing piled up") + + // Half of that is reachable: the key at 0 can take +15, the key at 30 cannot move at all. + session.dragTrackKeys(listOf(Triple(track, parameter, 0), Triple(track, parameter, 1)), fraction = 0.25f) + assertEquals(listOf(-15f, 15f, 30f), keysOf(session.model.value), "both moved the same 15, and the gap is intact") + } + + /** A key that crosses a neighbour reports its NEW ordinal, so the caller's selection can follow it. */ + @Test + fun aGroupDragReportsWhereEachKeyLanded() { + val session = EditorSession(model()) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + // Only the FIRST key is selected; dragging it +40 carries it past the key at 0. + val landed = session.dragTrackKeys(listOf(Triple(track, parameter, 0)), fraction = 40f / 60f) + assertEquals(listOf(0f, 10f, 30f), keysOf(session.model.value), "it crossed the key at 0 and the axis re-sorted") + assertEquals(listOf(1), landed, "and it now sits at ordinal 1") + } + + /** Each member is clamped to its OWN parameter's range, so a mixed batch cannot push one out of range. */ + @Test + fun aBatchMoveClampsPerParameter() { + val session = EditorSession(model()) + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + session.moveTrackKeys(listOf(Triple(track, parameter, 1)), toValue = 9999f) + assertEquals(30f, keysOf(session.model.value).last(), "clamped to the parameter's maximum") + } + + /** + * The landing QUERIES answer exactly what the edits they describe report. + * + * The sheet asks before the edit, because its key selection rides the edit's own snapshot and a selection + * re-pointed afterwards reaches no history entry at all. A query computed independently of the edit + * could disagree with what the edit actually produces, so both go through one planner: the landing a + * caller previews is guaranteed to be the landing the edit lands on. + */ + @Test + fun theLandingQueriesAgreeWithTheEditsTheyDescribe() { + val track = KeyformTrackRef.Geometry(KeyformOwner.Drawable(drawableId)) + + // A single key dragged past its neighbour: keys [-30, 0, 30], the first sent to +10. + val moveSession = EditorSession(model()) + val predictedMove = moveSession.model.value.trackKeyIndexAfterMove(track, parameter, keyIndex = 0, toValue = 10f) + assertEquals(1, predictedMove, "it crosses the key at 0") + assertEquals(predictedMove, moveSession.moveTrackKey(track, parameter, keyIndex = 0, toValue = 10f)) + + // The same crossing as a group drag, and a clamp the drag refuses outright. + val dragSession = EditorSession(model()) + val keys = listOf(Triple(track, parameter, 0)) + val predictedDrag = dragSession.model.value.trackKeyDragLandings(keys, fraction = 40f / 60f) + assertEquals(listOf(1), predictedDrag) + assertEquals(predictedDrag, dragSession.dragTrackKeys(keys, fraction = 40f / 60f)) + assertEquals( + listOf(1), + dragSession.model.value.trackKeyDragLandings(listOf(Triple(track, parameter, 1)), fraction = 0f), + "a drag that moves nothing reports the ordinals it was given", + ) + } + + /** + * Binding a warp's geometry to a parameter it did not yet key - any parameter, not a fixed set - seeds + * the axis and leaves the lattice looking the same at every pose until a later capture changes a cell. + */ + @Test + fun capturingInsertsOnADrawableMidPose() { + val owner = KeyformOwner.Drawable(drawableId) + val mid = model().withGeometryKeyCaptured(owner, parameter, mapOf(angleX to 15f)) + assertEquals(listOf(-30f, 0f, 15f, 30f), keysOf(mid)) + } + + @Test + fun capturingBindsAWarpToAnyParameter() { + val angleYParam = Parameter(angleY, "ParamAngleY", min = -30f, max = 30f, default = 0f) + val puppet = + model().copy(parameters = listOf(parameter, angleYParam)) + val owner = KeyformOwner.Deformer(deformerId) + assertFalse(puppet.isGeometryKeyedOn(owner, angleY), "precondition: not keyed on Angle Y") + + val bound = puppet.withGeometryKeyCaptured(owner, angleYParam, mapOf(angleY to 0f)) + assertTrue(bound.isGeometryKeyedOn(owner, angleY), "the warp is now keyed on Angle Y") + val warp = bound.deformers.single() as Deformer.Warp + val axis = assertNotNull(warp.geometryGrid).axes.first { it.parameterId == angleY } + assertEquals(listOf(-30f, 0f, 30f), axis.keys.toList(), "seeded across the parameter's range") + } + + /** A second capture on an already-bound parameter at a mid pose inserts a shape-preserving key there. */ + @Test + fun capturingOnAnExistingAxisInsertsAtThePose() { + val owner = KeyformOwner.Deformer(deformerId) + val mid = model().withGeometryKeyCaptured(owner, parameter, mapOf(angleX to 15f)) + val warp = mid.deformers.single() as Deformer.Warp + assertEquals( + listOf(-30f, 0f, 15f, 30f), + assertNotNull(warp.geometryGrid).axes.single { it.parameterId == angleX }.keys.toList(), + ) + } + + /** Dragging lattice points commits an authored form into the cell at the live pose. */ + @Test + fun writingAWarpLatticeFormOverwritesTheCellAtThePose() { + val owner = KeyformOwner.Deformer(deformerId) + val sculpted = WarpLatticeForm(FloatArray(8) { index -> index.toFloat() }) + val written = model().withWarpLatticeCaptured(owner, parameter, mapOf(angleX to 0f), sculpted) + val warp = written.deformers.single() as Deformer.Warp + val grid = assertNotNull(warp.geometryGrid) + val axis = grid.axes.single { it.parameterId == angleX } + val keyIndex = axis.keys.indexOfFirst { key -> key == 0f } + assertTrue(keyIndex >= 0, "default pose lands on the middle key") + val cell = grid.cells.first { candidate -> candidate.coordinate[0] == keyIndex } + assertContentEquals(sculpted.controlPoints, cell.form.controlPoints) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformKeySelectionTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformKeySelectionTest.kt new file mode 100644 index 0000000..569dd5d --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/KeyformKeySelectionTest.kt @@ -0,0 +1,101 @@ +package org.umamo.edit + +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * What a removal does to the keyform sheet's key selection. + * + * A removal renumbers every key above it, so the selection has to renumber the same way to keep naming what + * the user selected: dropping it wholesale loses a carefully built multi-key selection over one unrelated + * deletion, and leaving the refs untouched hands the freed ordinal to whichever key slides onto it. Three + * call sites need to agree on this - the aimed removal behind Alt+I and the lane menu, the selected-keys + * removal behind Delete, and the summary-mark removal - which is why the rule lives in one place. + */ +class KeyformKeySelectionTest { + private val angleX = ParameterId("ParamAngleX") + + /** A key on the geometry row at [ordinal]. */ + private fun key(ordinal: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:d/geometry", ordinal) + + /** A key on a different row at [ordinal] - something a removal here must not disturb. */ + private fun otherRowKey(ordinal: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:other/geometry", ordinal) + + /** Deleting a mark the user did not select leaves their selection completely alone. */ + @Test + fun removingAnUnselectedKeyLeavesTheSelectionAlone() { + val selection = setOf(key(0), key(1)) + assertEquals(selection, selectionAfterKeyRemoval(selection, setOf(otherRowKey(3)))) + assertEquals(selection, selectionAfterKeyRemoval(selection, emptySet()), "and so does removing nothing") + } + + /** The removed keys drop out, and the ones after them slide down to the ordinals they now hold. */ + @Test + fun theKeysAfterARemovalRenumber() { + assertEquals( + setOf(key(0), key(1), key(2), key(3)), + selectionAfterKeyRemoval(setOf(key(0), key(2), key(3), key(4)), setOf(key(1))), + "all four survive, and the three above the removal each slide down one place", + ) + assertEquals( + setOf(key(0)), + selectionAfterKeyRemoval(setOf(key(0), key(2)), setOf(key(2))), + "a selected key that IS removed simply goes", + ) + assertEquals( + setOf(key(1)), + selectionAfterKeyRemoval(setOf(key(0), key(3)), setOf(key(0), key(1))), + "two removed below it, and the removed one of its own", + ) + } + + /** + * A removal on one parameter's axis does not renumber another's. + * + * A linked pad renders the same row under two sections, so a row key alone does not identify the axis a + * key sits on - and shifting the other section's ordinals would move that selection onto the wrong marks. + */ + @Test + fun aRemovalOnlyRenumbersItsOwnAxis() { + val onAngleY = TrackKeyRef(ParameterId("ParamAngleY"), "drawable:d/geometry", 3) + assertEquals(setOf(onAngleY), selectionAfterKeyRemoval(setOf(onAngleY), setOf(key(0)))) + } + + /** + * An insert shifts the selection up from where it lands, and leaves everything below it alone. + * + * The asymmetry follows from the renumbering rule itself: an insert to the RIGHT of a selected mark + * renumbers nothing below it, so the selection already names the right key; an insert to the LEFT lands + * at or above the selected ordinal, so the selection must shift up by one to keep naming it. + */ + @Test + fun anInsertShiftsOnlyTheKeysAboveIt() { + assertEquals( + setOf(key(3)), + selectionAfterKeyInsertion(setOf(key(2)), key(0)), + "inserted below: the selected mark moves up one ordinal to stay on the same key", + ) + assertEquals( + setOf(key(2)), + selectionAfterKeyInsertion(setOf(key(2)), key(3)), + "inserted above: nothing renumbers", + ) + assertEquals( + setOf(key(3)), + selectionAfterKeyInsertion(setOf(key(2)), key(2)), + "inserted AT the selected ordinal: the new key takes it, so the selection moves up", + ) + } + + /** An insert on another row or another axis leaves the selection exactly as it was. */ + @Test + fun anInsertOnlyRenumbersItsOwnRowAndAxis() { + val selection = setOf(key(2)) + assertEquals(selection, selectionAfterKeyInsertion(selection, otherRowKey(0))) + assertEquals( + selection, + selectionAfterKeyInsertion(selection, TrackKeyRef(ParameterId("ParamAngleY"), "drawable:d/geometry", 0)), + ) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/MergeAdjustTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/MergeAdjustTest.kt new file mode 100644 index 0000000..b5064d5 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/MergeAdjustTest.kt @@ -0,0 +1,116 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Pins the merge's face on the operation settings strip: a merge registers with its Merge At row, + * switching the row re-merges the SAME vertices from the base at the new target over the same step + * (the survivor keeps its index, so the selection the step carries stays valid), and an unknown + * choice falls back to the target the merge ran with. + */ +class MergeAdjustTest { + private val drawableId = DrawableId("a") + + /** A quad: v0 (0,0), v1 (10,0), v2 (0,10), v3 (10,10), two triangles. */ + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "a", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 10f, 10f), FloatArray(8), intArrayOf(0, 1, 2, 1, 3, 2)), + geometryGrid = null, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** A session in Edit mode with v0 and v1 selected, v1 active (so First is v0 and Last is v1). */ + private fun session(): EditorSession { + val session = EditorSession(model()) + session.setMode(EditorMode.Edit) + session.setMeshSelection( + MeshSelection( + drawableIds = listOf(drawableId), + activeDrawableId = drawableId, + selectMode = MeshSelectMode.Vertex, + elementsByDrawable = mapOf(drawableId to setOf(MeshElement.Vertex(0), MeshElement.Vertex(1))), + activeElement = ActiveMeshElement(drawableId, MeshElement.Vertex(1)), + ), + ) + return session + } + + private fun survivor(session: EditorSession): Pair { + val positions = session.model.value.drawables.single().mesh!!.positions + // The survivor appends last: the two kept vertices come first. + return positions[4] to positions[5] + } + + private fun targetRow(key: String): OperatorParameter = + OperatorParameter.ChoiceParameter(MergeParameterKeys.TARGET, MergeParameterKeys.TARGET, key, emptyList()) + + @Test + fun aMergeRegistersAndItsTargetCanBeSwitchedInPlace() { + val session = session() + + session.mergeSelectedVertices(MergeTarget.AtCenter, areaId = "area-1") + + val record = assertNotNull(session.adjustableOperation.value, "the merge registered") + assertEquals("area-1", record.areaId) + assertEquals("change.mesh.merge", record.change.labelKey) + assertEquals("center", record.parameters.choiceValue(MergeParameterKeys.TARGET, "?")) + assertEquals(5f to 0f, survivor(session), "landed at the center of v0 and v1") + assertEquals(3, session.model.value.drawables.single().mesh!!.vertexCount) + val stepsBefore = session.historyView.value.steps.size + val selectionBefore = session.meshSelection.value + + session.adjustLastOperation(record.parameters.withParameter(MergeParameterKeys.TARGET, targetRow("first"))) + assertEquals(0f to 0f, survivor(session), "re-merged from the base at the first vertex") + assertEquals(stepsBefore, session.historyView.value.steps.size, "the step was amended in place") + assertEquals(selectionBefore, session.meshSelection.value, "the survivor selection still names the same index") + + session.adjustLastOperation(record.parameters.withParameter(MergeParameterKeys.TARGET, targetRow("last"))) + assertEquals(10f to 0f, survivor(session), "and at the last (active) vertex") + assertNotNull(session.adjustableOperation.value, "the record stays live for the next adjustment") + + session.undo() + assertEquals(4, session.model.value.drawables.single().mesh!!.vertexCount, "one undo returns to the unmerged quad") + assertNull(session.adjustableOperation.value) + } + + @Test + fun anUnknownChoiceFallsBackToTheTargetTheMergeRanWith() { + assertEquals(MergeTarget.AtLast, mergeTargetOf(listOf(targetRow("elsewhere")), MergeTarget.AtLast)) + assertEquals(MergeTarget.AtFirst, mergeTargetOf(emptyList(), MergeTarget.AtFirst)) + assertEquals(MergeTarget.AtCenter, mergeTargetOf(mergeParameters(MergeTarget.AtCenter), MergeTarget.AtLast)) + assertEquals(listOf("center", "first", "last"), mergeParameters(MergeTarget.AtCenter).filterIsInstance().single().choices.map { choice -> choice.key }) + } + + @Test + fun aRefusedMergeRegistersNothing() { + val session = EditorSession(model()) + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelection(drawableIds = listOf(drawableId), activeDrawableId = drawableId, elementsByDrawable = mapOf(drawableId to setOf(MeshElement.Vertex(0))))) + + session.mergeSelectedVertices(MergeTarget.AtCenter, areaId = "area-1") + + assertNull(session.adjustableOperation.value, "one vertex merges nothing, so nothing is adjustable") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshSelectionOpsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshSelectionOpsTest.kt new file mode 100644 index 0000000..ad0f5d6 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshSelectionOpsTest.kt @@ -0,0 +1,410 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Verifies the pure element-selection gestures maintain the [MeshSelection] invariant (the active element + * is a member of its drawable's selected set, or null when nothing remains), keep the session meshes and + * select mode across every op, span multiple meshes correctly (elements are mesh-local), and that + * select-mode switches follow Blender's flush-down / derive-up conversion rules per mesh. + */ +class MeshSelectionOpsTest { + private val drawableD = DrawableId("d") + private val drawableE = DrawableId("e") + + // A single-mesh session over d, and a two-mesh session over d + e. + private val base = MeshSelection.editing(listOf(drawableD)) + private val dual = MeshSelection.editing(listOf(drawableD, drawableE)) + + // The "spoke" fixture: center triangle T (face 0, vertices 0-1-2) shares each of its three edges with + // exactly one neighbor - A (face 1) across (0,1), B (face 2) across (1,2), C (face 3) across (0,2). + private val spokeIndices = intArrayOf(0, 1, 2, 0, 1, 3, 1, 2, 4, 2, 0, 5) + private val spokeMesh = DrawableMesh(FloatArray(12), FloatArray(12), spokeIndices) + + // Two triangles sharing the (1, 2) edge - the second session mesh's smaller topology. + private val stripIndices = intArrayOf(0, 1, 2, 1, 3, 2) + private val stripMesh = DrawableMesh(FloatArray(8), FloatArray(8), stripIndices) + + // The mesh provider the whole-session ops resolve topology through. + private fun meshOf(drawableId: DrawableId): DrawableMesh? = + when (drawableId) { + drawableD -> spokeMesh + drawableE -> stripMesh + else -> null + } + + /** + * Builds a vertex-domain element set from vertex indices, for terse assertions. + * + * @param IntArray vertexIndices The vertex indices. + * @return Set The corresponding vertex elements. + */ + private fun vertices(vararg vertexIndices: Int): Set = + vertexIndices.map { vertexIndex -> MeshElement.Vertex(vertexIndex) }.toSet() + + /** + * A single-mesh selection over d with the given elements (and optionally an active element). + * + * @param Set elements The selected elements on d. + * @param MeshElement? active The active element, or null. + * @param MeshSelectMode selectMode The select mode. + * @return MeshSelection The built selection. + */ + private fun selectionOnD( + elements: Set, + active: MeshElement? = null, + selectMode: MeshSelectMode = MeshSelectMode.Vertex, + ): MeshSelection = + base.copy( + selectMode = selectMode, + elementsByDrawable = if (elements.isEmpty()) emptyMap() else mapOf(drawableD to elements), + activeElement = active?.let { ActiveMeshElement(drawableD, it) }, + ) + + /** fitsWithinMeshes accepts elements that still exist in their mesh and rejects the rest, per domain. */ + @Test + fun fitsWithinMeshesValidatesEachDomain() { + // The spoke fixture has vertices 0..5, four faces, and no (3,4) edge. + assertTrue(MeshSelectionOps.fitsWithinMeshes(selectionOnD(vertices(0, 5)), ::meshOf), "in-range vertices fit") + assertTrue( + MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Edge.of(0, 1)), selectMode = MeshSelectMode.Edge), ::meshOf), + "an existing edge fits", + ) + assertTrue( + MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Face(3)), selectMode = MeshSelectMode.Face), ::meshOf), + "an existing face fits", + ) + assertTrue(MeshSelectionOps.fitsWithinMeshes(base, ::meshOf), "an empty selection always fits") + + assertFalse(MeshSelectionOps.fitsWithinMeshes(selectionOnD(vertices(0, 6)), ::meshOf), "an out-of-range vertex does not fit") + assertFalse( + MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Edge.of(3, 4)), selectMode = MeshSelectMode.Edge), ::meshOf), + "an edge absent from the mesh does not fit even with in-range endpoints", + ) + assertFalse( + MeshSelectionOps.fitsWithinMeshes(selectionOnD(setOf(MeshElement.Face(4)), selectMode = MeshSelectMode.Face), ::meshOf), + "an out-of-range face ordinal does not fit", + ) + assertFalse( + MeshSelectionOps.fitsWithinMeshes( + base.copy(elementsByDrawable = mapOf(DrawableId("gone") to vertices(0))), + ) { drawableId -> meshOf(drawableId) }, + "a selection on a mesh the provider cannot resolve does not fit", + ) + } + + /** replace selects a single element and makes it (and its mesh) active, keeping the session. */ + @Test + fun replaceSelectsSingleActive() { + val result = MeshSelectionOps.replace(base, drawableD, MeshElement.Vertex(3)) + assertEquals(vertices(3), result.elementsOf(drawableD)) + assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(3)), result.activeElement) + assertEquals(listOf(drawableD), result.drawableIds) + assertEquals(drawableD, result.activeDrawableId) + } + + /** replace on one session mesh clears the other meshes' selections (a plain click replaces everything). */ + @Test + fun replaceClearsOtherMeshes() { + val seeded = MeshSelectionOps.add(dual, drawableD, MeshElement.Vertex(1)) + val result = MeshSelectionOps.replace(seeded, drawableE, MeshElement.Vertex(0)) + assertTrue(result.elementsOf(drawableD).isEmpty(), "the other mesh's selection cleared") + assertEquals(vertices(0), result.elementsOf(drawableE)) + assertEquals(drawableE, result.activeDrawableId, "the clicked mesh becomes active") + } + + /** toggle adds a missing element (active) and removes a present one (active falls back or clears). */ + @Test + fun toggleAddsThenRemoves() { + val added = MeshSelectionOps.toggle(MeshSelectionOps.toggle(base, drawableD, MeshElement.Vertex(1)), drawableD, MeshElement.Vertex(2)) + assertEquals(vertices(1, 2), added.elementsOf(drawableD)) + assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(2)), added.activeElement) + + val removed = MeshSelectionOps.toggle(added, drawableD, MeshElement.Vertex(2)) + assertEquals(vertices(1), removed.elementsOf(drawableD)) + val removedActive = removed.activeElement + assertTrue( + removedActive != null && removed.contains(removedActive.drawableId, removedActive.element), + "active stays a member after removal", + ) + + val emptied = MeshSelectionOps.toggle(removed, drawableD, MeshElement.Vertex(1)) + assertTrue(emptied.isEmpty) + assertNull(emptied.activeElement, "active clears when the set empties") + } + + /** add extends the set and promotes the added element to active. */ + @Test + fun addExtendsAndActivates() { + val result = MeshSelectionOps.add(MeshSelectionOps.add(base, drawableD, MeshElement.Vertex(0)), drawableD, MeshElement.Vertex(5)) + assertEquals(vertices(0, 5), result.elementsOf(drawableD)) + assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(5)), result.activeElement) + } + + /** box replaces (or unions when additive) and keeps the active element only when it remains selected. */ + @Test + fun boxReplacesOrUnionsAndMaintainsActive() { + val seeded = MeshSelectionOps.replace(base, drawableD, MeshElement.Vertex(0)) + val replaced = MeshSelectionOps.box(seeded, mapOf(drawableD to vertices(2, 3)), additive = false) + assertEquals(vertices(2, 3), replaced.elementsOf(drawableD)) + assertNull(replaced.activeElement, "active drops when it is no longer selected") + + val additive = MeshSelectionOps.box(seeded, mapOf(drawableD to vertices(2, 3)), additive = true) + assertEquals(vertices(0, 2, 3), additive.elementsOf(drawableD)) + assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(0)), additive.activeElement, "active kept when it stays selected") + } + + /** A box spanning two session meshes selects on both; a non-additive box replaces both. */ + @Test + fun boxSpansSessionMeshes() { + val seeded = MeshSelectionOps.add(dual, drawableD, MeshElement.Vertex(5)) + val boxed = + MeshSelectionOps.box( + seeded, + mapOf(drawableD to vertices(0, 1), drawableE to vertices(2, 3)), + additive = false, + ) + assertEquals(vertices(0, 1), boxed.elementsOf(drawableD)) + assertEquals(vertices(2, 3), boxed.elementsOf(drawableE)) + assertEquals(4, boxed.size, "size sums across meshes") + + val additive = + MeshSelectionOps.box(seeded, mapOf(drawableE to vertices(0)), additive = true) + assertEquals(vertices(5), additive.elementsOf(drawableD), "the additive box keeps the other mesh's selection") + assertEquals(vertices(0), additive.elementsOf(drawableE)) + } + + /** clear empties every mesh's element set but keeps the session and mode (the Edit session stays open). */ + @Test + fun clearKeepsSessionAndMode() { + val edgeMode = dual.copy(selectMode = MeshSelectMode.Edge) + val result = MeshSelectionOps.clear(MeshSelectionOps.add(edgeMode, drawableD, MeshElement.Edge.of(1, 0))) + assertTrue(result.isEmpty) + assertNull(result.activeElement) + assertEquals(listOf(drawableD, drawableE), result.drawableIds) + assertEquals(MeshSelectMode.Edge, result.selectMode) + } + + /** The gestures work identically over edge and face elements, and Edge.of canonicalizes endpoint order. */ + @Test + fun gesturesAreDomainAgnosticAndEdgesCanonicalize() { + val edgeSelection = MeshSelectionOps.replace(base.copy(selectMode = MeshSelectMode.Edge), drawableD, MeshElement.Edge.of(2, 1)) + assertEquals(setOf(MeshElement.Edge(1, 2)), edgeSelection.elementsOf(drawableD), "(2,1) and (1,2) are one identity") + assertTrue(edgeSelection.contains(drawableD, MeshElement.Edge.of(1, 2))) + + val faceSelection = MeshSelectionOps.toggle(base.copy(selectMode = MeshSelectMode.Face), drawableD, MeshElement.Face(3)) + assertEquals(setOf(MeshElement.Face(3)), faceSelection.elementsOf(drawableD)) + assertEquals(ActiveMeshElement(drawableD, MeshElement.Face(3)), faceSelection.activeElement) + } + + /** A same-mode switch is a no-op returning the same instance; a converting switch nulls the active element. */ + @Test + fun changeSelectModeSameModeIsIdentityAndConversionDropsActive() { + val selection = MeshSelectionOps.add(base, drawableD, MeshElement.Vertex(0)) + assertSame(selection, MeshSelectionOps.changeSelectMode(selection, MeshSelectMode.Vertex) { spokeIndices }) + + val converted = MeshSelectionOps.changeSelectMode(selection, MeshSelectMode.Edge) { spokeIndices } + assertEquals(MeshSelectMode.Edge, converted.selectMode) + assertNull(converted.activeElement, "no single last-touched element survives a domain change") + assertEquals(listOf(drawableD), converted.drawableIds) + } + + /** A mode switch converts EVERY session mesh's elements against its own topology. */ + @Test + fun changeSelectModeConvertsPerMesh() { + val selection = + dual.copy( + elementsByDrawable = + mapOf( + // All of spoke face 0's vertices on d; all of strip face 0's vertices on e. + drawableD to vertices(0, 1, 2), + drawableE to vertices(0, 1, 2), + ), + ) + val converted = MeshSelectionOps.changeSelectMode(selection, MeshSelectMode.Face) { drawableId -> meshOf(drawableId)?.indices } + assertEquals(setOf(MeshElement.Face(0)), converted.elementsOf(drawableD), "the spoke's face 0 derives on d") + assertEquals(setOf(MeshElement.Face(0)), converted.elementsOf(drawableE), "the strip's face 0 derives on e") + } + + /** Vertex-to-edge derives only edges whose both endpoints were selected. */ + @Test + fun vertexToEdgeRequiresBothEndpoints() { + val converted = MeshSelectionOps.changeSelectMode(selectionOnD(vertices(0, 1, 3)), MeshSelectMode.Edge) { spokeIndices } + assertEquals( + setOf(MeshElement.Edge.of(0, 1), MeshElement.Edge.of(0, 3), MeshElement.Edge.of(1, 3)), + converted.elementsOf(drawableD), + ) + } + + /** Vertex-to-face derives only faces whose all three vertices were selected. */ + @Test + fun vertexToFaceRequiresAllVertices() { + val allOfT = MeshSelectionOps.changeSelectMode(selectionOnD(vertices(0, 1, 2)), MeshSelectMode.Face) { spokeIndices } + assertEquals(setOf(MeshElement.Face(0)), allOfT.elementsOf(drawableD)) + + val twoOfThree = MeshSelectionOps.changeSelectMode(selectionOnD(vertices(0, 1, 4)), MeshSelectMode.Face) { spokeIndices } + assertTrue(twoOfThree.isEmpty, "two of three vertices never derive a face") + } + + /** + * The headline Blender rule: edges of the neighbors can cover every vertex of the center triangle T + * without selecting T - a face derives only from all three of its OWN edges, never from vertex coverage. + */ + @Test + fun edgeToFaceRequiresOwnEdgesNotVertexCoverage() { + val neighborEdges = + setOf( + MeshElement.Edge.of(0, 3), + MeshElement.Edge.of(1, 3), + MeshElement.Edge.of(1, 4), + MeshElement.Edge.of(2, 4), + ) + // Sanity: these four edges cover all of T's vertices {0, 1, 2}. + assertTrue(MeshTopology.coveredVertexIndices(neighborEdges, spokeIndices).containsAll(setOf(0, 1, 2))) + val converted = + MeshSelectionOps.changeSelectMode( + selectionOnD(neighborEdges, selectMode = MeshSelectMode.Edge), + MeshSelectMode.Face, + ) { spokeIndices } + assertTrue(converted.isEmpty, "no face owns all three of its edges here (T owns none, A and B own two)") + + val ownEdges = + setOf( + MeshElement.Edge.of(0, 1), + MeshElement.Edge.of(1, 2), + MeshElement.Edge.of(0, 2), + ) + val face = + MeshSelectionOps.changeSelectMode( + selectionOnD(ownEdges, selectMode = MeshSelectMode.Edge), + MeshSelectMode.Face, + ) { spokeIndices } + assertEquals(setOf(MeshElement.Face(0)), face.elementsOf(drawableD), "all three own edges derive exactly T") + } + + /** Face-to-edge flushes down to the selected faces' own edges. */ + @Test + fun faceToEdgeFlushesToOwnEdges() { + val converted = + MeshSelectionOps.changeSelectMode( + selectionOnD(setOf(MeshElement.Face(1)), selectMode = MeshSelectMode.Face), + MeshSelectMode.Edge, + ) { spokeIndices } + assertEquals( + setOf(MeshElement.Edge.of(0, 1), MeshElement.Edge.of(1, 3), MeshElement.Edge.of(0, 3)), + converted.elementsOf(drawableD), + ) + } + + /** + * The documented lossy round-trip (Blender-faithful): selecting T's three neighbors, flushing down to + * vertices, then deriving back up to faces gains T - the flush covers all six vertices, and T's three + * vertices are among them. + */ + @Test + fun faceToVertexToFaceRoundTripGainsTheEnclosedFace() { + val neighbors = + selectionOnD( + setOf(MeshElement.Face(1), MeshElement.Face(2), MeshElement.Face(3)), + selectMode = MeshSelectMode.Face, + ) + val flushed = MeshSelectionOps.changeSelectMode(neighbors, MeshSelectMode.Vertex) { spokeIndices } + assertEquals(vertices(0, 1, 2, 3, 4, 5), flushed.elementsOf(drawableD), "flush-down covers every vertex of the selected faces") + + val derived = MeshSelectionOps.changeSelectMode(flushed, MeshSelectMode.Face) { spokeIndices } + assertEquals( + setOf(MeshElement.Face(0), MeshElement.Face(1), MeshElement.Face(2), MeshElement.Face(3)), + derived.elementsOf(drawableD), + "deriving back up now includes the enclosed face T", + ) + } + + /** Edge-to-vertex flushes down to the selected edges' endpoints. */ + @Test + fun edgeToVertexFlushesToEndpoints() { + val converted = + MeshSelectionOps.changeSelectMode( + selectionOnD(setOf(MeshElement.Edge.of(1, 3), MeshElement.Edge.of(2, 4)), selectMode = MeshSelectMode.Edge), + MeshSelectMode.Vertex, + ) { spokeIndices } + assertEquals(vertices(1, 2, 3, 4), converted.elementsOf(drawableD)) + } + + /** selectAll fills the current mode's whole domain on every session mesh, keeping the active element. */ + @Test + fun selectAllFillsDomainPerModeAcrossMeshes() { + val seeded = selectionOnD(vertices(2), active = MeshElement.Vertex(2)).copy(drawableIds = dual.drawableIds) + val allVertices = MeshSelectionOps.selectAll(seeded, ::meshOf) + assertEquals(vertices(0, 1, 2, 3, 4, 5), allVertices.elementsOf(drawableD), "the spoke's six vertices") + assertEquals(vertices(0, 1, 2, 3), allVertices.elementsOf(drawableE), "the strip's four vertices") + assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(2)), allVertices.activeElement, "active kept - it is still selected") + + val allFaces = MeshSelectionOps.selectAll(base.copy(selectMode = MeshSelectMode.Face), ::meshOf) + assertEquals( + setOf(MeshElement.Face(0), MeshElement.Face(1), MeshElement.Face(2), MeshElement.Face(3)), + allFaces.elementsOf(drawableD), + ) + + val allEdges = MeshSelectionOps.selectAll(base.copy(selectMode = MeshSelectMode.Edge), ::meshOf) + assertEquals(MeshTopology.uniqueEdges(spokeIndices).toSet(), allEdges.elementsOf(drawableD)) + } + + /** invert flips membership per session mesh and drops a now-deselected active element. */ + @Test + fun invertComplementsDomainAndDropsDeselectedActive() { + val selection = + dual.copy( + elementsByDrawable = mapOf(drawableD to vertices(0, 1)), + activeElement = ActiveMeshElement(drawableD, MeshElement.Vertex(0)), + ) + val inverted = MeshSelectionOps.invert(selection, ::meshOf) + assertEquals(vertices(2, 3, 4, 5), inverted.elementsOf(drawableD)) + assertEquals(vertices(0, 1, 2, 3), inverted.elementsOf(drawableE), "an untouched session mesh inverts from empty to all") + assertNull(inverted.activeElement, "the active element was deselected by the inversion") + } + + /** selectLinked unions a connectivity island's elements in the current domain, additively. */ + @Test + fun selectLinkedUnionsIslandPerDomain() { + // The strip mesh (vertices 0-3, faces 0-1) as one island; seed a selection elsewhere to prove union. + val stripSelection = MeshSelection.editing(listOf(drawableE)) + val island = setOf(0, 1, 2, 3) + + val vertexResult = MeshSelectionOps.selectLinked(stripSelection, drawableE, island, stripIndices) + assertEquals(vertices(0, 1, 2, 3), vertexResult.elementsOf(drawableE), "vertex mode adds every island vertex") + + val edgeResult = + MeshSelectionOps.selectLinked(stripSelection.copy(selectMode = MeshSelectMode.Edge), drawableE, island, stripIndices) + assertEquals(MeshTopology.uniqueEdges(stripIndices).toSet(), edgeResult.elementsOf(drawableE), "edge mode adds the island's edges") + + val faceResult = + MeshSelectionOps.selectLinked(stripSelection.copy(selectMode = MeshSelectMode.Face), drawableE, island, stripIndices) + assertEquals(setOf(MeshElement.Face(0), MeshElement.Face(1)), faceResult.elementsOf(drawableE)) + + // Additive: an existing selection on another vertex survives the union. + val seeded = MeshSelectionOps.add(stripSelection, drawableE, MeshElement.Vertex(3)) + val grown = MeshSelectionOps.selectLinked(seeded, drawableE, setOf(0, 1, 2), stripIndices) + assertEquals(vertices(0, 1, 2, 3), grown.elementsOf(drawableE), "the union keeps prior members") + assertEquals(ActiveMeshElement(drawableE, MeshElement.Vertex(3)), grown.activeElement, "the active element is untouched") + } + + /** remove deselects per mesh and keeps the active element only when it survives. */ + @Test + fun removeDropsElementsAndFixesActive() { + val selection = selectionOnD(vertices(0, 1, 2), active = MeshElement.Vertex(2)) + val afterActiveGone = MeshSelectionOps.remove(selection, mapOf(drawableD to vertices(2))) + assertEquals(vertices(0, 1), afterActiveGone.elementsOf(drawableD)) + assertNull(afterActiveGone.activeElement, "active drops when it is removed") + + val afterOtherGone = MeshSelectionOps.remove(selection, mapOf(drawableD to vertices(0))) + assertEquals(vertices(1, 2), afterOtherGone.elementsOf(drawableD)) + assertEquals(ActiveMeshElement(drawableD, MeshElement.Vertex(2)), afterOtherGone.activeElement, "active kept when it survives") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTopologyEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTopologyEditsTest.kt new file mode 100644 index 0000000..fd5c473 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTopologyEditsTest.kt @@ -0,0 +1,704 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Verifies the topology-edit infrastructure and the op builders: withMeshTopologyEdit rebuilds every + * keyform cell's deltas per VertexSource (copy / average / lerp) and remaps or drops glue pairs; + * duplicate appends copies with copied faces; merge collapses onto the survivor per target and drops + * degenerate triangles; rip splits a fan by the side predicate; connect cuts crossed triangles at + * lerped vertices and refuses degenerate requests; object-mode duplicate inserts after its source with + * a unique id; and the session commits model + selection as one undo step. + */ +class MeshTopologyEditsTest { + private val paramA = ParameterId("A") + + // The strip: a unit-ish quad of two triangles sharing edge (1, 2). + // v0 (0,0), v1 (2,0), v2 (0,2), v3 (2,2). + private val stripPositions = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f) + private val stripUvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f) + private val stripIndices = intArrayOf(0, 1, 2, 1, 3, 2) + private val stripMesh = DrawableMesh(stripPositions, stripUvs, stripIndices) + + // Per-vertex deltas 10*(index+1) on x, 0 on y - distinguishable per vertex. + private fun stripForm(): MeshDeltaForm = MeshDeltaForm(floatArrayOf(10f, 0f, 20f, 0f, 30f, 0f, 40f, 0f)) + + private fun stripDrawable(id: String): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = stripMesh, + geometryGrid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), stripForm()))), + ) + + private fun model(): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(stripDrawable("d"), stripDrawable("other")), + rootChildren = listOf(OrgChild.Drawable(DrawableId("d")), OrgChild.Drawable(DrawableId("other"))), + rootPartId = null, + glues = + listOf( + Glue( + meshA = DrawableId("d"), + meshB = DrawableId("other"), + pairs = listOf(GluePair(1, 1, 0.5f, 0.5f), GluePair(3, 3, 0.5f, 0.5f)), + ), + ), + ) + + /** withMeshTopologyEdit rebuilds keyform deltas per source kind and remaps / drops glue pairs. */ + @Test + fun topologyEditRemapsDeltasAndGlue() { + // New mesh: keep v0 and v1, average v2+v3 into a survivor, and add a lerp point on (0, 1). + val newMesh = + DrawableMesh( + floatArrayOf(0f, 0f, 2f, 0f, 1f, 2f, 1f, 0f), + FloatArray(8), + intArrayOf(0, 1, 2), + ) + val edit = + MeshTopologyEdit( + newMesh, + listOf( + VertexSource.FromOld(0), + VertexSource.FromOld(1), + VertexSource.AverageOf(listOf(2, 3)), + VertexSource.LerpOf(0, 1, 0.25f), + ), + ) + val edited = model().withMeshTopologyEdit(DrawableId("d"), edit) + val editedDrawable = edited.drawables.first { it.id == DrawableId("d") } + assertSame(newMesh, editedDrawable.mesh, "the replacement mesh swaps in") + val deltas = editedDrawable.geometryGrid!!.cells.single().form.positionDeltas + assertEquals(10f, deltas[0], "v0 copies its delta") + assertEquals(20f, deltas[2], "v1 copies its delta") + assertEquals(35f, deltas[4], "the merge survivor averages v2 and v3 (30 + 40) / 2") + assertEquals(12.5f, deltas[6], 1e-4f, "the split point lerps v0 and v1 by t = 0.25") + + // Glue: pair on old v1 remaps to new v1 (same slot); pair on old v3 collapses onto the survivor. + val glue = edited.glues.single() + assertEquals(listOf(1, 2), glue.pairs.map { pair -> pair.indexA }, "old v1 keeps its slot; old v3 remaps to the survivor") + assertEquals(listOf(1, 3), glue.pairs.map { pair -> pair.indexB }, "the other mesh's indices are untouched") + + // A malformed edit (source list size mismatch) is a no-op, never a corruption. + val malformed = MeshTopologyEdit(newMesh, listOf(VertexSource.FromOld(0))) + assertSame(model().let { it to it.withMeshTopologyEdit(DrawableId("d"), malformed) }.let { (before, after) -> before === after }, true) + } + + /** duplicateElements appends copies of the covered vertices plus every fully-covered face. */ + @Test + fun duplicateAppendsCopiesAndFaces() { + val result = MeshTopologyOps.duplicateElements(stripMesh, setOf(0, 1, 2))!! + val mesh = result.edit.newMesh + assertEquals(7, mesh.vertexCount, "three copies append after the four originals") + assertEquals(3, mesh.indices.size / 3, "only the fully-covered triangle duplicates") + assertEquals(listOf(4, 5, 6), mesh.indices.toList().subList(6, 9), "the copied face uses the copies") + assertEquals(0f, mesh.positions[8], "copy of v0 keeps its position x") + assertEquals(stripUvs[0], mesh.uvs[8], "copy of v0 keeps its uv") + assertEquals(VertexSource.FromOld(0), result.edit.vertexSources[4], "the copy's deltas copy from its source") + assertEquals( + setOf(MeshElement.Vertex(4), MeshElement.Vertex(5), MeshElement.Vertex(6)), + result.newElements, + "the copies are the new selection", + ) + assertNull(MeshTopologyOps.duplicateElements(stripMesh, emptySet()), "nothing covered refuses") + } + + /** mergeVertices collapses per target, drops degenerate triangles, and keeps the survivor selected. */ + @Test + fun mergeCollapsesPerTarget() { + // Merge v1 and v3 (the strip's right edge) at center: survivor at (2, 1). + val atCenter = MeshTopologyOps.mergeVertices(stripMesh, listOf(1, 3), MergeTarget.AtCenter)!! + val centerMesh = atCenter.edit.newMesh + assertEquals(3, centerMesh.vertexCount, "four vertices merge into three") + val survivor = 2 + assertEquals(2f, centerMesh.positions[survivor * 2], "survivor x is the midpoint") + assertEquals(1f, centerMesh.positions[survivor * 2 + 1], "survivor y is the midpoint") + // Triangle (1, 3, 2) held BOTH merged vertices, so it degenerates and drops; (0, 1, 2) survives. + assertEquals(1, centerMesh.indices.size / 3, "the triangle that held both merged vertices drops") + assertEquals(setOf(MeshElement.Vertex(survivor)), atCenter.newElements) + assertTrue(atCenter.edit.vertexSources[survivor] is VertexSource.AverageOf, "the survivor averages its members") + + // AtFirst keeps v1's position verbatim. + val atFirst = MeshTopologyOps.mergeVertices(stripMesh, listOf(1, 3), MergeTarget.AtFirst)!! + assertEquals(2f, atFirst.edit.newMesh.positions[4], "survivor x = v1.x") + assertEquals(0f, atFirst.edit.newMesh.positions[5], "survivor y = v1.y") + assertEquals(VertexSource.FromOld(1), atFirst.edit.vertexSources[2]) + + // AtLast keeps v3's position. + val atLast = MeshTopologyOps.mergeVertices(stripMesh, listOf(1, 3), MergeTarget.AtLast)!! + assertEquals(2f, atLast.edit.newMesh.positions[4]) + assertEquals(2f, atLast.edit.newMesh.positions[5]) + + // Merging two corners of ONE triangle degenerates it: only the other triangle survives. + val degenerate = MeshTopologyOps.mergeVertices(stripMesh, listOf(0, 1), MergeTarget.AtCenter)!! + assertEquals(1, degenerate.edit.newMesh.indices.size / 3, "the triangle that collapsed drops") + + assertNull(MeshTopologyOps.mergeVertices(stripMesh, listOf(1), MergeTarget.AtCenter), "one vertex refuses") + } + + /** ripElements duplicates only vertices whose fan splits, re-pointing the marked side. */ + @Test + fun ripSplitsFanBySidePredicate() { + // Rip the shared edge's vertices (1, 2), marking triangle 1 as the side that takes the copies. + val result = MeshTopologyOps.ripElements(stripMesh, setOf(1, 2)) { triangleIndex -> triangleIndex == 1 }!! + val mesh = result.edit.newMesh + assertEquals(6, mesh.vertexCount, "both shared vertices duplicate") + // Triangle 0 keeps the originals; triangle 1 re-points at the copies. + assertEquals(listOf(0, 1, 2), mesh.indices.toList().subList(0, 3)) + assertEquals(listOf(4, 3, 5), mesh.indices.toList().subList(3, 6), "the marked triangle uses the copies (v1 -> 4, v2 -> 5)") + assertEquals(setOf(MeshElement.Vertex(4), MeshElement.Vertex(5)), result.newElements) + + // Every adjacent triangle marked (or none): nothing to split, refused. + assertNull(MeshTopologyOps.ripElements(stripMesh, setOf(1, 2)) { true }, "a one-sided rip refuses") + } + + /** connectVertices cuts the crossed shared edge at a lerped vertex and retriangulates both sides. */ + @Test + fun connectCutsAcrossTheSharedEdge() { + // Connect v0 (0,0) and v3 (2,2): the diagonal crosses the shared edge (1,2) at its midpoint. + val result = MeshTopologyOps.connectVertices(stripMesh, 0, 3)!! + val mesh = result.edit.newMesh + assertEquals(5, mesh.vertexCount, "one crossing vertex appends") + assertEquals(1f, mesh.positions[8], 1e-4f, "the crossing sits at the shared edge's midpoint x") + assertEquals(1f, mesh.positions[9], 1e-4f, "and midpoint y") + assertEquals(4, mesh.indices.size / 3, "each crossed triangle splits in two") + val crossingSource = result.edit.vertexSources[4] + assertTrue(crossingSource is VertexSource.LerpOf && absDiff(crossingSource.t, 0.5f) < 1e-4f, "the crossing lerps at t = 0.5") + assertTrue(MeshElement.Vertex(4) in result.newElements, "the cut path is selected") + + // Already-connected vertices (an existing edge) refuse. + assertNull(MeshTopologyOps.connectVertices(stripMesh, 1, 2), "an existing edge refuses") + assertNull(MeshTopologyOps.connectVertices(stripMesh, 0, 0), "a self-connect refuses") + } + + /** Object-mode duplicate: a unique .001 id, org-tree insertion after the source, no glue membership. */ + @Test + fun withDrawableDuplicatedInsertsAfterSource() { + val (edited, copyId) = model().withDrawableDuplicated(DrawableId("d"))!! + assertEquals(DrawableId("d.001"), copyId) + assertEquals(3, edited.drawables.size) + assertEquals( + listOf(OrgChild.Drawable(DrawableId("d")), OrgChild.Drawable(copyId), OrgChild.Drawable(DrawableId("other"))), + edited.rootChildren, + "the copy sits immediately after its source", + ) + val copy = edited.drawables.first { it.id == copyId } + val source = edited.drawables.first { it.id == DrawableId("d") } + assertTrue(copy.mesh!!.positions !== source.mesh!!.positions, "positions are a fresh array") + assertSame(source.mesh!!.uvs, copy.mesh!!.uvs, "uvs share by reference (COW)") + assertTrue(edited.glues.single().meshA != copyId && edited.glues.single().meshB != copyId, "the copy joins no glue") + assertEquals(DrawableId("d"), copy.textureSourceId, "the copy resolves its atlas binding through its source") + + // A second duplicate of the same source lands at .002. + val (again, secondId) = edited.withDrawableDuplicated(DrawableId("d"))!! + assertEquals(DrawableId("d.002"), secondId) + assertEquals(4, again.drawables.size) + + // Duplicating the COPY still binds the texture through the ORIGINAL (the id the atlas map knows). + val (chained, chainedId) = again.withDrawableDuplicated(copyId)!! + val chainedCopy = chained.drawables.first { it.id == chainedId } + assertEquals(DrawableId("d"), chainedCopy.textureSourceId, "a copy of a copy inherits the original's atlas binding") + } + + /** The session commits a topology edit and its result selection as ONE undo step. */ + @Test + fun sessionCommitsTopologyAtomically() { + val session = EditorSession(model()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelection( + MeshSelectionOps.add(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0)), DrawableId("d"), MeshElement.Vertex(1)), + ) + + val stepsBefore = session.historyView.value.steps.size + session.duplicateSelectedElements() + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "duplicate is one undo step") + assertEquals(6, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, "two copies appended") + assertEquals( + setOf(MeshElement.Vertex(4), MeshElement.Vertex(5)), + session.meshSelection.value.elementsOf(DrawableId("d")), + "the copies are selected", + ) + assertTrue(session.dirty.value, "a topology edit dirties the document") + + session.undo() + assertEquals(4, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, "undo restores the topology") + assertEquals( + setOf(MeshElement.Vertex(0), MeshElement.Vertex(1)), + session.meshSelection.value.elementsOf(DrawableId("d")), + "undo restores the selection the edit replaced - never torn from the topology", + ) + } + + /** A face-mode duplicate keeps face mode, leaving the new face selected (Blender keeps the mode). */ + @Test + fun faceModeDuplicateKeepsFaceMode() { + val session = EditorSession(model()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelectMode(MeshSelectMode.Face) + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Face(0))) + + session.duplicateSelectedElements() + + // Face 0's three vertices copied to 4..6 plus one new triangle appended at index 2. + assertEquals(MeshSelectMode.Face, session.meshSelection.value.selectMode, "duplicate never switches the select mode") + assertEquals( + setOf(MeshElement.Face(2)), + session.meshSelection.value.elementsOf(DrawableId("d")), + "the copied face is selected in face mode", + ) + assertEquals( + ActiveMeshElement(DrawableId("d"), MeshElement.Face(2)), + session.meshSelection.value.activeElement, + "the copied face becomes active", + ) + } + + /** An edge-mode duplicate covering a whole face keeps edge mode with the copied edges selected. */ + @Test + fun edgeModeDuplicateKeepsEdgeMode() { + val session = EditorSession(model()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelectMode(MeshSelectMode.Edge) + // All three edges of face 0, so the whole triangle duplicates. + var withEdges = MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Edge(0, 1)) + withEdges = MeshSelectionOps.add(withEdges, DrawableId("d"), MeshElement.Edge(1, 2)) + withEdges = MeshSelectionOps.add(withEdges, DrawableId("d"), MeshElement.Edge(0, 2)) + session.setMeshSelection(withEdges) + + session.duplicateSelectedElements() + + assertEquals(MeshSelectMode.Edge, session.meshSelection.value.selectMode, "duplicate never switches the select mode") + assertEquals( + setOf(MeshElement.Edge(4, 5), MeshElement.Edge(5, 6), MeshElement.Edge(4, 6)), + session.meshSelection.value.elementsOf(DrawableId("d")), + "the copied triangle's edges are selected in edge mode", + ) + } + + /** + * An edge-mode duplicate of one lone edge copies two loose vertices no edge covers, so the result + * falls back to vertex mode - stranding the copies unselected would hide them and starve the + * follow-up auto-grab. + */ + @Test + fun looseEdgeDuplicateFallsBackToVertexMode() { + val session = EditorSession(model()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + session.setMeshSelectMode(MeshSelectMode.Edge) + session.setMeshSelection(MeshSelectionOps.replace(session.meshSelection.value, DrawableId("d"), MeshElement.Edge(0, 1))) + + session.duplicateSelectedElements() + + assertEquals(MeshSelectMode.Vertex, session.meshSelection.value.selectMode, "loose copies exist only in the vertex domain") + assertEquals( + setOf(MeshElement.Vertex(4), MeshElement.Vertex(5)), + session.meshSelection.value.elementsOf(DrawableId("d")), + "the loose vertex copies are selected", + ) + } + + /** Add Vertex stages floats without touching the model; Accept commits once; Esc discards. */ + @Test + fun addVertexDraftStagesThenAccepts() { + val session = EditorSession(model()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + session.setMode(EditorMode.Edit) + val before = session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount + + session.beginAddVertex("area-a") + assertTrue(session.activeSelectTool.value is ActiveSelectTool.AddVertex) + session.addVertexDraftClick(1f, 0f, snapEdge = MeshElement.Edge.of(0, 1), snapT = 0.5f) + session.addVertexDraftClick(1f, 1f) + val draft = session.activeSelectTool.value as ActiveSelectTool.AddVertex + assertEquals(2, draft.verts.size, "two floats staged") + assertEquals(1, draft.edges.size, "auto-edge from tip") + assertEquals(before, session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, "document untouched while staging") + + session.deleteAddVertexDraftVert(1) + assertEquals(1, (session.activeSelectTool.value as ActiveSelectTool.AddVertex).verts.size, "RMB delete removes a float") + + session.addVertexDraftClick(1f, 1f) + session.acceptAddVertexDraft() + assertNull(session.activeSelectTool.value, "accept clears the tool") + assertTrue( + session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount > before, + "accept appends staged verts", + ) + + val afterAccept = session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount + session.beginAddVertex("area-a") + session.addVertexDraftClick(0.5f, 0.5f) + session.clearSelectTool() + assertEquals( + afterAccept, + session.model.value.drawables.first { it.id == DrawableId("d") }.mesh!!.vertexCount, + "discard leaves the accepted mesh alone", + ) + } + + /** deleteVertices drops the vert and every incident triangle, compacting survivors. */ + @Test + fun deleteVerticesRemovesIncidentTriangles() { + val result = MeshTopologyOps.deleteVertices(stripMesh, listOf(1))!! + val mesh = result.edit.newMesh + assertEquals(3, mesh.vertexCount, "one vert removed") + assertEquals(0, mesh.indices.size / 3, "both triangles used v1 and drop") + assertNull(MeshTopologyOps.deleteVertices(stripMesh, emptyList()), "empty delete refuses") + assertNull(MeshTopologyOps.deleteVertices(stripMesh, listOf(99)), "missing index refuses") + } + + /** applyAddVertexDraft edge-snaps and appends free floats in one TopologyOpResult. */ + @Test + fun applyAddVertexDraftSnapsAndAppends() { + val result = + MeshTopologyOps.applyAddVertexDraft( + stripMesh, + listOf( + DraftVert(1f, 0f, snapEdge = MeshElement.Edge.of(0, 1), snapT = 0.5f), + DraftVert(1f, 1f), + ), + listOf(DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!), + )!! + assertEquals(6, result.edit.newMesh.vertexCount, "snap + free append") + assertTrue(MeshElement.Vertex(4) in result.newElements || MeshElement.Vertex(5) in result.newElements) + } + + /** + * Closing line on a triangular hole (mesh edge base + two draft sides to an orphan) fills exactly + * one face. + */ + @Test + fun applyAddVertexDraftClosingLineFillsHole() { + // Face (0,1,2) plus orphan v3; draft edges 1-3 and 2-3 close triangle (1,2,3). + val mesh = + DrawableMesh( + floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f), + FloatArray(8), + intArrayOf(0, 1, 2), + ) + val result = + MeshTopologyOps.applyAddVertexDraft( + mesh, + emptyList(), + listOf( + DraftEdge.of(DraftEndpoint.Existing(1), DraftEndpoint.Existing(3))!!, + DraftEdge.of(DraftEndpoint.Existing(2), DraftEndpoint.Existing(3))!!, + ), + ) + assertTrue(result != null, "closing lines must commit") + assertEquals(2, result!!.edit.newMesh.indices.size / 3, "exactly one new face fills the hole") + } + + /** Drawing the second diagonal of an already-filled quad must not stack overlapping faces. */ + @Test + fun applyAddVertexDraftRejectsCrossedQuadDiagonal() { + val mesh = + DrawableMesh( + floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f), + FloatArray(8), + intArrayOf(0, 1, 2, 0, 2, 3), + ) + val result = + MeshTopologyOps.applyAddVertexDraft( + mesh, + emptyList(), + listOf(DraftEdge.of(DraftEndpoint.Existing(1), DraftEndpoint.Existing(3))!!), + ) + // Knife may still run; faces must stay at the original two. + assertEquals(2, (result?.edit?.newMesh ?: mesh).indices.size / 3, "no stacked / crossed faces") + } + + /** A closed draft triangle over existing faces still fills (pure-draft skips centroid-inside reject). */ + @Test + fun applyAddVertexDraftPureDraftTriangleOverExistingFills() { + val result = + MeshTopologyOps.applyAddVertexDraft( + stripMesh, + listOf(DraftVert(0.5f, 0.5f), DraftVert(1.5f, 0.5f), DraftVert(1f, 1.5f)), + listOf( + DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!, + DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!, + DraftEdge.of(DraftEndpoint.Draft(2), DraftEndpoint.Draft(0))!!, + ), + ) + assertTrue(result != null, "closed draft triangle must commit") + assertEquals(7, result!!.edit.newMesh.vertexCount, "four originals + three floats") + assertEquals(3, result.edit.newMesh.indices.size / 3, "two original faces + one draft face") + } + + /** Three draft edges among orphan verts (no mesh faces) still form a triangle on Accept. */ + @Test + fun applyAddVertexDraftAllDraftTriangleFillsFace() { + val mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), IntArray(0)) + val edges = + listOf( + DraftEdge.of(DraftEndpoint.Existing(0), DraftEndpoint.Existing(1))!!, + DraftEdge.of(DraftEndpoint.Existing(1), DraftEndpoint.Existing(2))!!, + DraftEdge.of(DraftEndpoint.Existing(2), DraftEndpoint.Existing(0))!!, + ) + val result = MeshTopologyOps.applyAddVertexDraft(mesh, emptyList(), edges) + assertTrue(result != null, "all-draft triangle must commit") + assertEquals(1, result!!.edit.newMesh.indices.size / 3, "one face from three draft edges") + } + + /** + * Concave closed draft ring must CDT-fill (not fan from vert 0). A C-shaped notch would be covered + * by fan triangles from the first vertex; Delaunay keeps faces inside the polygon only. + */ + @Test + fun applyAddVertexDraftConcaveRingCdtsWithoutFan() { + val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0)) + // C outline, CCW: notch opens to the right around (2.5, 2). + val verts = + listOf( + DraftVert(0f, 0f), + DraftVert(4f, 0f), + DraftVert(4f, 1f), + DraftVert(1f, 1f), + DraftVert(1f, 3f), + DraftVert(4f, 3f), + DraftVert(4f, 4f), + DraftVert(0f, 4f), + ) + val edges = + verts.indices.map { index -> + DraftEdge.of(DraftEndpoint.Draft(index), DraftEndpoint.Draft((index + 1) % verts.size))!! + } + val result = MeshTopologyOps.applyAddVertexDraft(empty, verts, edges) + assertTrue(result != null, "concave ring must commit") + val mesh = result!!.edit.newMesh + assertEquals(8, mesh.vertexCount) + assertEquals(6, mesh.triangleCount, "CDT of 8-gon C yields 6 tris, not a fan covering the notch") + + // Notch probe (2.5, 2) must not land inside any accepted face. + fun pointInTri(px: Float, py: Float, a: Int, b: Int, c: Int): Boolean { + val ax = mesh.positions[a * 2] + val ay = mesh.positions[a * 2 + 1] + val bx = mesh.positions[b * 2] + val by = mesh.positions[b * 2 + 1] + val cx = mesh.positions[c * 2] + val cy = mesh.positions[c * 2 + 1] + val v0x = cx - ax + val v0y = cy - ay + val v1x = bx - ax + val v1y = by - ay + val v2x = px - ax + val v2y = py - ay + val dot00 = v0x * v0x + v0y * v0y + val dot01 = v0x * v1x + v0y * v1y + val dot02 = v0x * v2x + v0y * v2y + val dot11 = v1x * v1x + v1y * v1y + val dot12 = v1x * v2x + v1y * v2y + val denom = dot00 * dot11 - dot01 * dot01 + if (kotlin.math.abs(denom) < 1e-12f) { + return false + } + val u = (dot11 * dot02 - dot01 * dot12) / denom + val v = (dot00 * dot12 - dot01 * dot02) / denom + return u >= -1e-4f && v >= -1e-4f && u + v <= 1f + 1e-4f + } + for (tri in 0 until mesh.triangleCount) { + val a = mesh.indices[tri * 3] + val b = mesh.indices[tri * 3 + 1] + val c = mesh.indices[tri * 3 + 2] + assertTrue( + !pointInTri(2.5f, 2f, a, b, c), + "notch (2.5,2) must stay empty; fan-from-0 would cover it (tri $tri = $a,$b,$c)", + ) + } + } + + /** + * Convex octagon: CDT must not put every face on one apex (fan / cascading-ear). Incident face + * counts should be spread — a pure fan from vert 0 would hit all 6 triangles on that vert. + */ + @Test + fun applyAddVertexDraftConvexRingZigzagsNotAFan() { + val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0)) + val verts = + listOf( + DraftVert(2f, 0f), + DraftVert(3f, 1f), + DraftVert(3f, 3f), + DraftVert(2f, 4f), + DraftVert(0f, 4f), + DraftVert(-1f, 3f), + DraftVert(-1f, 1f), + DraftVert(0f, 0f), + ) + val edges = + verts.indices.map { index -> + DraftEdge.of(DraftEndpoint.Draft(index), DraftEndpoint.Draft((index + 1) % verts.size))!! + } + val result = MeshTopologyOps.applyAddVertexDraft(empty, verts, edges) + assertTrue(result != null) + val mesh = result!!.edit.newMesh + assertEquals(6, mesh.triangleCount) + val incident = IntArray(mesh.vertexCount) + for (tri in 0 until mesh.triangleCount) { + incident[mesh.indices[tri * 3]]++ + incident[mesh.indices[tri * 3 + 1]]++ + incident[mesh.indices[tri * 3 + 2]]++ + } + assertTrue( + incident.max() < mesh.triangleCount, + "no apex should own every face (fan); maxIncident=${incident.max()} tris=${mesh.triangleCount}", + ) + assertTrue(incident.count { count -> count >= 3 } >= 2, "at least two verts should share the load") + } + + /** + * Three chained clicks without click-back on the first vert still fill on Accept (auto-close). + */ + @Test + fun applyAddVertexDraftOpenPolylineAutoClosesOnAccept() { + val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0)) + val result = + MeshTopologyOps.applyAddVertexDraft( + empty, + listOf(DraftVert(0f, 0f), DraftVert(2f, 0f), DraftVert(1f, 2f)), + listOf( + DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!, + DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!, + ), + ) + assertTrue(result != null, "open drawn verts must still commit") + assertEquals(3, result!!.edit.newMesh.vertexCount, "three free floats append") + assertEquals(1, result.edit.newMesh.indices.size / 3, "Accept auto-closes a 3-click triangle") + } + + /** + * Legacy fallback: empty mesh + [FreeVertUvContext] (no UV seed) still samples art UVs so Accept + * cannot land UV(0,0) when the Edit-enter seed is missing. + */ + @Test + fun applyAddVertexDraftEmptyMeshSamplesArtUv() { + val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0)) + val uvContext = + FreeVertUvContext( + layerLeft = 100f, + layerTop = 200f, + tileWidth = 100f, + tileHeight = 100f, + frame = null, + ) + val result = + MeshTopologyOps.applyAddVertexDraft( + empty, + listOf(DraftVert(100f, 200f), DraftVert(200f, 200f), DraftVert(100f, 300f)), + listOf( + DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!, + DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!, + DraftEdge.of(DraftEndpoint.Draft(2), DraftEndpoint.Draft(0))!!, + ), + uvContext, + ) + assertTrue(result != null, "closed wipe rebuild must commit") + val mesh = result!!.edit.newMesh + assertEquals(1, mesh.triangleCount, "one face") + assertTrue(absDiff(mesh.uvs[0], 0f) < 1e-4f && absDiff(mesh.uvs[1], 0f) < 1e-4f, "top-left corner") + assertTrue(absDiff(mesh.uvs[2], 1f) < 1e-4f && absDiff(mesh.uvs[3], 0f) < 1e-4f, "top-right corner") + assertTrue(absDiff(mesh.uvs[4], 0f) < 1e-4f && absDiff(mesh.uvs[5], 1f) < 1e-4f, "bottom-left corner") + } + + /** + * Wipe-and-rebuild prefers a pre-wipe [uvSeedMesh] (Edit-enter snapshot) so stored atlas UVs stay + * correct even when the tile has no source binding for art projection. + */ + @Test + fun applyAddVertexDraftEmptyMeshSamplesUvSeed() { + val seed = + DrawableMesh( + floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), + floatArrayOf(0.25f, 0.5f, 0.75f, 0.5f, 0.25f, 0.9f), + intArrayOf(0, 1, 2), + ) + val empty = DrawableMesh(floatArrayOf(), floatArrayOf(), IntArray(0)) + val result = + MeshTopologyOps.applyAddVertexDraft( + empty, + listOf(DraftVert(0f, 0f), DraftVert(2f, 0f), DraftVert(0f, 2f)), + listOf( + DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!, + DraftEdge.of(DraftEndpoint.Draft(1), DraftEndpoint.Draft(2))!!, + DraftEdge.of(DraftEndpoint.Draft(2), DraftEndpoint.Draft(0))!!, + ), + uvSeedMesh = seed, + ) + assertTrue(result != null, "seeded wipe rebuild must commit") + val mesh = result!!.edit.newMesh + assertTrue(absDiff(mesh.uvs[0], 0.25f) < 1e-4f && absDiff(mesh.uvs[1], 0.5f) < 1e-4f) + assertTrue(absDiff(mesh.uvs[2], 0.75f) < 1e-4f && absDiff(mesh.uvs[3], 0.5f) < 1e-4f) + assertTrue(absDiff(mesh.uvs[4], 0.25f) < 1e-4f && absDiff(mesh.uvs[5], 0.9f) < 1e-4f) + } + + /** A stale edge-snap after faces were deleted demotes to a free float instead of aborting Accept. */ + @Test + fun applyAddVertexDraftStaleSnapDemotesToFree() { + val emptyFaces = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), IntArray(0)) + val result = + MeshTopologyOps.applyAddVertexDraft( + emptyFaces, + listOf(DraftVert(1f, 0f, snapEdge = MeshElement.Edge.of(0, 1), snapT = 0.5f), DraftVert(1f, 1f)), + listOf(DraftEdge.of(DraftEndpoint.Draft(0), DraftEndpoint.Draft(1))!!), + ) + assertTrue(result != null, "stale snap must not abort Accept") + assertEquals(5, result!!.edit.newMesh.vertexCount, "orphan verts kept + two free appends") + } + + /** Object-mode duplicateSelectedDrawables selects the copies as one undo step. */ + @Test + fun sessionDuplicatesDrawablesAndSelectsCopies() { + val session = EditorSession(model()) + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(DrawableId("d")))) + + val stepsBefore = session.historyView.value.steps.size + val copies = session.duplicateSelectedDrawables() + assertEquals(listOf(DrawableId("d.001")), copies) + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "one undo step") + assertEquals( + setOf(SelectionTarget.Drawable(DrawableId("d.001"))), + session.selection.value.targets, + "the copies become the selection", + ) + + session.undo() + assertEquals(2, session.model.value.drawables.size, "undo removes the copy") + assertEquals( + setOf(SelectionTarget.Drawable(DrawableId("d"))), + session.selection.value.targets, + "undo restores the prior selection", + ) + } + + private fun absDiff(left: Float, right: Float): Float = if (left > right) left - right else right - left +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTopologyTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTopologyTest.kt new file mode 100644 index 0000000..fc32c9d --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTopologyTest.kt @@ -0,0 +1,149 @@ +package org.umamo.edit + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Verifies the pure topology queries: edge deduplication and canonicalization, per-element vertex + * coverage, and the three derive-up rules the select-mode conversions and display highlights share. + */ +class MeshTopologyTest { + // Two triangles sharing the (1, 2) edge - the minimal mesh with an interior edge. + private val stripIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // The "spoke" fixture: center triangle T (face 0, vertices 0-1-2) shares each of its three edges with + // exactly one neighbor - A (face 1) across (0,1), B (face 2) across (1,2), C (face 3) across (0,2). + private val spokeIndices = intArrayOf(0, 1, 2, 0, 1, 3, 1, 2, 4, 2, 0, 5) + + /** uniqueEdges canonicalizes to (low, high) and emits a shared interior edge once. */ + @Test + fun uniqueEdgesDedupsAndCanonicalizes() { + val edges = MeshTopology.uniqueEdges(stripIndices) + assertEquals(5, edges.size, "two triangles sharing one edge have five unique edges") + assertEquals( + setOf( + MeshElement.Edge(0, 1), + MeshElement.Edge(1, 2), + MeshElement.Edge(0, 2), + MeshElement.Edge(1, 3), + MeshElement.Edge(2, 3), + ), + edges.toSet(), + ) + assertTrue(edges.all { edge -> edge.endpointLow <= edge.endpointHigh }, "every edge is canonical") + } + + /** edgesOfTriangle and verticesOfTriangle read one triangle's corners. */ + @Test + fun perTriangleAccessors() { + assertEquals(setOf(1, 2, 3), MeshTopology.verticesOfTriangle(stripIndices, 1)) + assertEquals( + setOf(MeshElement.Edge(1, 3), MeshElement.Edge(2, 3), MeshElement.Edge(1, 2)), + MeshTopology.edgesOfTriangle(stripIndices, 1).toSet(), + ) + } + + /** coveredVertexIndices resolves each element kind: a vertex itself, an edge its endpoints, a face its corners. */ + @Test + fun coveredVertexIndicesResolvesEachElementKind() { + val elements = + setOf( + MeshElement.Vertex(5), + MeshElement.Edge.of(3, 1), + MeshElement.Face(0), + ) + assertEquals(setOf(0, 1, 2, 3, 5), MeshTopology.coveredVertexIndices(elements, spokeIndices)) + } + + /** An edge derives from a vertex set only when both endpoints are selected. */ + @Test + fun edgesWithBothEndpointsSelectedIsStrict() { + val edges = MeshTopology.edgesWithBothEndpointsSelected(spokeIndices, setOf(0, 1, 3)) + assertEquals( + setOf(MeshElement.Edge(0, 1), MeshElement.Edge(0, 3), MeshElement.Edge(1, 3)), + edges, + ) + } + + /** A face derives from a vertex set only when all three of its vertices are selected. */ + @Test + fun facesWithAllVerticesSelectedIsStrict() { + assertEquals( + setOf(MeshElement.Face(0)), + MeshTopology.facesWithAllVerticesSelected(spokeIndices, setOf(0, 1, 2)), + ) + assertTrue( + MeshTopology.facesWithAllVerticesSelected(spokeIndices, setOf(0, 1, 4)).isEmpty(), + "two of three vertices never derive a face", + ) + } + + /** A face derives from an edge set only when all three of its OWN edges are selected, never by coverage. */ + @Test + fun facesWithAllEdgesSelectedIgnoresVertexCoverage() { + val neighborEdges = + setOf( + MeshElement.Edge.of(0, 3), + MeshElement.Edge.of(1, 3), + MeshElement.Edge.of(1, 4), + MeshElement.Edge.of(2, 4), + ) + assertTrue( + MeshTopology.facesWithAllEdgesSelected(spokeIndices, neighborEdges).isEmpty(), + "edges covering T's vertices do not select T", + ) + assertEquals( + setOf(MeshElement.Face(0)), + MeshTopology.facesWithAllEdgesSelected( + spokeIndices, + setOf(MeshElement.Edge.of(0, 1), MeshElement.Edge.of(1, 2), MeshElement.Edge.of(0, 2)), + ), + ) + } + + // Two disconnected components: the strip (vertices 0-3) plus a lone triangle (vertices 4-6). + private val twoIslandIndices = intArrayOf(0, 1, 2, 1, 3, 2, 4, 5, 6) + + /** buildVertexAdjacency lists each vertex's edge-sharing neighbors once, empty for unused vertices. */ + @Test + fun adjacencyListsEdgeNeighborsOnce() { + val adjacency = MeshTopology.buildVertexAdjacency(5, stripIndices) + assertEquals(setOf(1, 2), adjacency[0].toSet(), "vertex 0 neighbors") + assertEquals(setOf(0, 2, 3), adjacency[1].toSet(), "vertex 1 neighbors") + assertEquals(setOf(0, 1, 3), adjacency[2].toSet(), "vertex 2 neighbors; the shared (1,2) edge appears once") + assertEquals(setOf(1, 2), adjacency[3].toSet(), "vertex 3 neighbors") + assertEquals(emptySet(), adjacency[4].toSet(), "a vertex outside every triangle has no neighbors") + } + + /** connectedVertices floods a whole component and never crosses to a disconnected one. */ + @Test + fun connectedVerticesFloodsOneComponent() { + val adjacency = MeshTopology.buildVertexAdjacency(7, twoIslandIndices) + assertEquals(setOf(0, 1, 2, 3), MeshTopology.connectedVertices(adjacency, 0), "the strip floods from vertex 0") + assertEquals(setOf(4, 5, 6), MeshTopology.connectedVertices(adjacency, 5), "the lone triangle floods from vertex 5") + assertEquals(emptySet(), MeshTopology.connectedVertices(adjacency, 99), "an out-of-range seed yields nothing") + } + + /** selectionIslands splits by connectivity WITHIN the subset: an unselected bridge vertex separates islands. */ + @Test + fun selectionIslandsSplitOnUnselectedBridges() { + val adjacency = MeshTopology.buildVertexAdjacency(7, twoIslandIndices) + + // The whole strip selected is one island; adding the lone triangle's vertices makes a second. + val islands = MeshTopology.selectionIslands(adjacency, setOf(0, 1, 2, 3, 4, 5, 6)) + assertEquals(2, islands.size, "two mesh components make two islands") + assertEquals(setOf(setOf(0, 1, 2, 3), setOf(4, 5, 6)), islands.toSet()) + + // Selecting the strip's two ends WITHOUT the middle vertices splits them: 0 and 3 share no + // direct edge, so the sub-graph induced on {0, 3} is two singleton islands. + val split = MeshTopology.selectionIslands(adjacency, setOf(0, 3)) + assertEquals(setOf(setOf(0), setOf(3)), split.toSet(), "an unselected bridge separates the ends") + + // A connected sub-selection stays one island even when more of the mesh exists around it. + val joined = MeshTopology.selectionIslands(adjacency, setOf(0, 1, 3)) + assertEquals(setOf(setOf(0, 1, 3)), joined.toSet(), "0-1 and 1-3 edges join all three") + + assertEquals(emptyList(), MeshTopology.selectionIslands(adjacency, emptySet()), "an empty selection has no islands") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTransformsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTransformsTest.kt new file mode 100644 index 0000000..a14cbd5 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshTransformsTest.kt @@ -0,0 +1,185 @@ +package org.umamo.edit + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.sqrt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Verifies the pure modal-operator math: each operator moves only the selected vertices by the expected + * amount about the median pivot, leaves the unselected coordinates and the input array untouched + * (purity / copy-on-write), and the pivot is the centroid of the selection. + */ +class MeshTransformsTest { + // Four vertices of a 2x2 square: (0,0) (2,0) (0,2) (2,2), interleaved. + private fun square(): FloatArray = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f) + + private fun assertClose(expected: Float, actual: Float, message: String) { + assertTrue(abs(expected - actual) < 1e-4f, "$message (expected $expected, was $actual)") + } + + /** The median pivot is the centroid of the selected vertices. */ + @Test + fun medianPivotIsCentroidOfSelection() { + val (allX, allY) = MeshTransforms.medianPivot(square(), setOf(0, 1, 2, 3)) + assertClose(1f, allX, "median x of all four") + assertClose(1f, allY, "median y of all four") + + val (rightX, rightY) = MeshTransforms.medianPivot(square(), setOf(1, 3)) + assertClose(2f, rightX, "median x of the right edge") + assertClose(1f, rightY, "median y of the right edge") + } + + /** Translate moves only the selected vertices; the rest and the input array are untouched. */ + @Test + fun translateMovesOnlySelected() { + val input = square() + val result = MeshTransforms.translateVertices(input, setOf(1), deltaX = 1f, deltaY = -1f) + + assertEquals(3f, result[2], "vertex 1 x moved by +1") + assertEquals(-1f, result[3], "vertex 1 y moved by -1") + assertEquals(0f, result[0], "vertex 0 untouched") + assertEquals(2f, result[6], "vertex 3 untouched") + // Purity: the input array is unchanged. + assertEquals(2f, input[2], "input vertex 1 x unchanged") + assertEquals(0f, input[3], "input vertex 1 y unchanged") + } + + /** Collapse piles every selected vertex onto the target (no offsets kept); the rest are untouched. */ + @Test + fun collapsePilesSelectedOntoTarget() { + val input = square() + val result = MeshTransforms.collapseVertices(input, setOf(0, 1, 3), targetX = 5f, targetY = 7f) + + // Unlike translateVertices, the inter-vertex offsets are gone: all three land on (5,7). + for (vertexIndex in setOf(0, 1, 3)) { + assertEquals(5f, result[vertexIndex * 2], "vertex $vertexIndex x piled on the target") + assertEquals(7f, result[vertexIndex * 2 + 1], "vertex $vertexIndex y piled on the target") + } + assertEquals(0f, result[4], "vertex 2 x untouched") + assertEquals(2f, result[5], "vertex 2 y untouched") + // Purity: the input array is unchanged. + assertEquals(0f, input[0], "input vertex 0 x unchanged") + } + + /** Scale expands selected vertices about the pivot; unselected vertices stay put. */ + @Test + fun scaleAboutPivot() { + val input = square() + val result = MeshTransforms.scaleVertices(input, setOf(0, 3), factor = 2f, pivotX = 1f, pivotY = 1f) + + // (0,0) about (1,1) by 2 -> (-1,-1); (2,2) -> (3,3). + assertClose(-1f, result[0], "vertex 0 x scaled") + assertClose(-1f, result[1], "vertex 0 y scaled") + assertClose(3f, result[6], "vertex 3 x scaled") + assertClose(3f, result[7], "vertex 3 y scaled") + assertEquals(2f, result[2], "vertex 1 untouched") + assertEquals(0f, input[0], "input unchanged") + } + + /** Rotate turns selected vertices about the pivot; a 90 degree turn maps (2,0) about origin to (0,2). */ + @Test + fun rotateAboutPivot() { + val input = square() + val result = MeshTransforms.rotateVertices(input, setOf(1), radians = (PI / 2).toFloat(), pivotX = 0f, pivotY = 0f) + + assertClose(0f, result[2], "vertex 1 x after 90 degree turn") + assertClose(2f, result[3], "vertex 1 y after 90 degree turn") + assertEquals(0f, result[0], "vertex 0 untouched") + assertEquals(2f, input[2], "input unchanged") + } + + /** The combined centroid across arrays is the mean of every vertex, weighted by vertex count. */ + @Test + fun combinedCentroidIsVertexWeightedMean() { + // One array centerd at (1,1) with four vertices, plus a single-vertex array at (10,10). The mean of the + // five vertices is ((0+2+0+2+10)/5, (0+0+2+2+10)/5) = (2.8, 2.8), pulled toward the denser square. + val single = floatArrayOf(10f, 10f) + val (centroidX, centroidY) = MeshTransforms.combinedCentroid(listOf(square(), single)) + assertClose(2.8f, centroidX, "combined centroid x weighted by vertex count") + assertClose(2.8f, centroidY, "combined centroid y weighted by vertex count") + } + + /** The combined centroid of an empty collection (or only empty arrays) is the origin. */ + @Test + fun combinedCentroidEmptyIsOrigin() { + val (emptyX, emptyY) = MeshTransforms.combinedCentroid(emptyList()) + assertEquals(0f, emptyX, "empty collection centroid x") + assertEquals(0f, emptyY, "empty collection centroid y") + + val (blankX, blankY) = MeshTransforms.combinedCentroid(listOf(FloatArray(0), FloatArray(0))) + assertEquals(0f, blankX, "only-empty-arrays centroid x") + assertEquals(0f, blankY, "only-empty-arrays centroid y") + } + + /** Weighted translate moves each vertex by its share of the delta; unweighted vertices stay put. */ + @Test + fun weightedTranslateScalesTheDeltaPerVertex() { + val input = square() + val result = MeshTransforms.translateVerticesWeighted(input, mapOf(1 to 0.5f, 2 to 1f), deltaX = 4f, deltaY = -2f) + + assertClose(4f, result[2], "half-weight vertex 1 x moved by +2") + assertClose(-1f, result[3], "half-weight vertex 1 y moved by -1") + assertClose(4f, result[4], "full-weight vertex 2 x moved by +4") + assertClose(0f, result[5], "full-weight vertex 2 y moved by -2") + assertEquals(0f, result[0], "unweighted vertex 0 untouched") + assertEquals(2f, input[2], "input unchanged") + } + + /** Weighted scale lerps each vertex toward its fully-scaled position by its weight. */ + @Test + fun weightedScaleLerpsTowardTheScaledPosition() { + val input = square() + val result = MeshTransforms.scaleVerticesWeighted(input, mapOf(0 to 0.5f), factorX = 3f, factorY = 3f, pivotX = 1f, pivotY = 1f) + + // (0,0) fully scaled about (1,1) by 3 lands on (-2,-2); half weight stops halfway at (-1,-1) + // (the effective factor is 1 + (3-1) x 0.5 = 2). + assertClose(-1f, result[0], "half-weight vertex 0 x scaled by the effective factor") + assertClose(-1f, result[1], "half-weight vertex 0 y scaled by the effective factor") + assertEquals(2f, result[2], "unweighted vertex 1 untouched") + } + + /** Horizontal reverse-swap exchanges x only: 0↔last, 1↔last-1; y stays on each vert. */ + @Test + fun reverseSwapPositionsHorizontalSwapsXOnly() { + val input = floatArrayOf(0f, 10f, 1f, 11f, 2f, 12f, 3f, 13f, 4f, 14f, 5f, 15f) + val result = MeshTransforms.reverseSwapPositions(input, listOf(0, 1, 2, 3, 4, 5), horizontal = true) + assertEquals(5f, result[0]) + assertEquals(10f, result[1], "y0 stays") + assertEquals(4f, result[2]) + assertEquals(11f, result[3], "y1 stays") + assertEquals(0f, result[10]) + assertEquals(15f, result[11], "y5 stays") + assertEquals(0f, input[0], "input untouched") + } + + /** Vertical reverse-swap exchanges y only; x stays on each vert. */ + @Test + fun reverseSwapPositionsVerticalSwapsYOnly() { + val input = floatArrayOf(0f, 10f, 1f, 11f, 2f, 12f, 3f, 13f, 4f, 14f, 5f, 15f) + val result = MeshTransforms.reverseSwapPositions(input, listOf(0, 1, 2, 3, 4, 5), horizontal = false) + assertEquals(0f, result[0], "x0 stays") + assertEquals(15f, result[1]) + assertEquals(1f, result[2], "x1 stays") + assertEquals(14f, result[3]) + assertEquals(5f, result[10], "x5 stays") + assertEquals(10f, result[11]) + } + + /** Weighted rotate scales the ANGLE (arc), preserving each vertex's distance from the pivot. */ + @Test + fun weightedRotateScalesTheAngleNotTheChord() { + val input = square() + val result = MeshTransforms.rotateVerticesWeighted(input, mapOf(1 to 0.5f), radians = (PI / 2).toFloat(), pivotX = 0f, pivotY = 0f) + + // (2,0) with half the 90 degree turn lands at 45 degrees: (sqrt(2), sqrt(2)) - still 2 from the + // pivot, which a positional lerp (the chord midpoint (1,1)) would not be. + val expected = (2.0 / sqrt(2.0)).toFloat() + assertClose(expected, result[2], "half-weight vertex 1 x at 45 degrees") + assertClose(expected, result[3], "half-weight vertex 1 y at 45 degrees") + assertClose(2f, sqrt(result[2] * result[2] + result[3] * result[3]), "distance from the pivot preserved") + assertEquals(0f, result[0], "unweighted vertex 0 untouched") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshUvFieldTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshUvFieldTest.kt new file mode 100644 index 0000000..9858835 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/MeshUvFieldTest.kt @@ -0,0 +1,68 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableMesh +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Wipe-and-rebuild UV projection: barycentric inside seed faces, affine outside, projectAll rewrites. + */ +class MeshUvFieldTest { + private fun absDiff(a: Float, b: Float): Float = kotlin.math.abs(a - b) + + @Test + fun barycentricInsideFaceMatchesSeedVerts() { + val seed = + DrawableMesh( + floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), + floatArrayOf(0.1f, 0.2f, 0.9f, 0.2f, 0.1f, 0.8f), + intArrayOf(0, 1, 2), + ) + val field = MeshUvField(seed) + val (u0, v0) = field.uvAt(0f, 0f) + val (u1, v1) = field.uvAt(2f, 0f) + val (u2, v2) = field.uvAt(0f, 2f) + assertTrue(absDiff(u0, 0.1f) < 1e-4f && absDiff(v0, 0.2f) < 1e-4f) + assertTrue(absDiff(u1, 0.9f) < 1e-4f && absDiff(v1, 0.2f) < 1e-4f) + assertTrue(absDiff(u2, 0.1f) < 1e-4f && absDiff(v2, 0.8f) < 1e-4f) + val (uMid, vMid) = field.uvAt(2f / 3f, 2f / 3f) + assertTrue(absDiff(uMid, (0.1f + 0.9f + 0.1f) / 3f) < 1e-3f) + assertTrue(absDiff(vMid, (0.2f + 0.2f + 0.8f) / 3f) < 1e-3f) + } + + @Test + fun projectAllRewritesEveryUvFromRest() { + val seed = + DrawableMesh( + floatArrayOf(0f, 0f, 4f, 0f, 0f, 4f), + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + intArrayOf(0, 1, 2), + ) + val rebuilt = + DrawableMesh( + floatArrayOf(0f, 0f, 4f, 0f, 0f, 4f, 1f, 1f), + floatArrayOf(9f, 9f, 9f, 9f, 9f, 9f, 9f, 9f), + intArrayOf(0, 1, 2, 0, 1, 3), + ) + val projected = MeshUvField(seed).projectAll(rebuilt) + assertTrue(absDiff(projected.uvs[0], 0f) < 1e-4f && absDiff(projected.uvs[1], 0f) < 1e-4f) + assertTrue(absDiff(projected.uvs[2], 1f) < 1e-4f && absDiff(projected.uvs[3], 0f) < 1e-4f) + assertTrue(absDiff(projected.uvs[4], 0f) < 1e-4f && absDiff(projected.uvs[5], 1f) < 1e-4f) + val (u, v) = MeshUvField(seed).uvAt(1f, 1f) + assertTrue(absDiff(projected.uvs[6], u) < 1e-4f && absDiff(projected.uvs[7], v) < 1e-4f) + } + + @Test + fun affineOutsideFaceIsContinuousWithBoundary() { + val seed = + DrawableMesh( + floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + intArrayOf(0, 1, 2), + ) + val field = MeshUvField(seed) + // Just outside the hypotenuse should still be near the affine plane of the triangle. + val (u, v) = field.uvAt(1.2f, 1.2f) + assertTrue(u in -0.2f..1.2f && v in -0.2f..1.2f, "affine outside stays near atlas") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ModalTransformCaptureTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ModalTransformCaptureTest.kt new file mode 100644 index 0000000..a7b5d2a --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ModalTransformCaptureTest.kt @@ -0,0 +1,186 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the pure gesture-capture builder the three gizmo overlays share. This logic - the covered-vertex + * anchor, the pivot-mode fallback chain, the per-mesh pivot-group derivation, and the proportional halo - + * lived open-coded in three Compose overlays with no test coverage of its own; the overlays' own tests could + * not reach it. These assertions are that missing gate. + */ +class ModalTransformCaptureTest { + private val meshA = DrawableId("a") + private val meshB = DrawableId("b") + + /** A single square mesh (4 verts, 2 tris) whose vertices span (0,0)-(2,2), so its centroid is (1,1). */ + private fun square(id: DrawableId, offsetX: Float = 0f, offsetY: Float = 0f): ModalCaptureSource = + ModalCaptureSource( + drawableId = id, + positions = + floatArrayOf( + offsetX + 0f, + offsetY + 0f, + offsetX + 2f, + offsetY + 0f, + offsetX + 2f, + offsetY + 2f, + offsetX + 0f, + offsetY + 2f, + ), + triangleIndices = intArrayOf(0, 1, 2, 0, 2, 3), + coveredIndices = setOf(0, 1, 2, 3), + ) + + private fun build( + sources: List, + pivotMode: TransformPivotMode = TransformPivotMode.MedianPoint, + scope: IndividualOriginScope = IndividualOriginScope.ConnectivityIsland, + activeAnchor: Pair? = null, + cursorAnchor: Pair? = null, + ): ModalTransformCapture? = + buildModalTransformCapture(sources, pivotMode, scope, MeshOperatorKind.Grab, activeAnchor, cursorAnchor) + + /** The median anchor is the covered-vertex mean pooled across every moving mesh, not a per-mesh average. */ + @Test + fun medianAnchorIsTheCoveredMeanAcrossMeshes() { + // One square at origin (centroid 1,1) and one shifted to (10,10)-(12,12) (centroid 11,11); the pooled + // mean of all eight vertices is (6,6). A per-mesh average would give the midpoint (6,6) too, so make + // the mesh sizes differ to tell them apart. + val small = square(meshA) + val wide = + ModalCaptureSource( + drawableId = meshB, + positions = floatArrayOf(10f, 10f, 12f, 10f), // just two vertices -> pulls the pooled mean less + triangleIndices = intArrayOf(), + coveredIndices = setOf(0, 1), + ) + val capture = build(listOf(small, wide))!! + // Pooled: (0+2+2+0 + 10+12) / 6 = 26/6, (0+0+2+2 + 10+10) / 6 = 24/6 = 4. + assertEquals(26f / 6f, capture.anchor.first, 1e-4f) + assertEquals(24f / 6f, capture.anchor.second, 1e-4f) + } + + /** Active Element and Cursor each fall back to the median when the caller resolved no anchor. */ + @Test + fun activeAndCursorFallBackToMedian() { + val sources = listOf(square(meshA)) + assertEquals(1f to 1f, build(sources, TransformPivotMode.ActiveElement, activeAnchor = null)!!.anchor) + assertEquals(1f to 1f, build(sources, TransformPivotMode.Cursor, cursorAnchor = null)!!.anchor) + // A resolved anchor is used verbatim. + assertEquals(5f to 7f, build(sources, TransformPivotMode.ActiveElement, activeAnchor = 5f to 7f)!!.anchor) + assertEquals(9f to 3f, build(sources, TransformPivotMode.Cursor, cursorAnchor = 9f to 3f)!!.anchor) + } + + /** A shared-pivot mode makes one group per mesh, pivoted at the shared anchor. */ + @Test + fun sharedPivotModesMakeOneGroupAtTheAnchor() { + val capture = build(listOf(square(meshA), square(meshB, offsetX = 10f)), TransformPivotMode.MedianPoint)!! + assertEquals(2, capture.entries.size) + for (entry in capture.entries) { + assertEquals(1, entry.groups.size, "shared pivot is a single group") + assertEquals(capture.anchor.first, entry.groups.single().pivotX, 1e-4f) + assertEquals(capture.anchor.second, entry.groups.single().pivotY, 1e-4f) + assertEquals(setOf(0, 1, 2, 3), entry.groups.single().vertexIndices) + } + } + + /** WholeMesh Individual Origins pivots each mesh about its OWN centroid, not the shared anchor. */ + @Test + fun individualOriginsWholeMeshUsesEachMeshOwnCentroid() { + val capture = + build( + listOf(square(meshA), square(meshB, offsetX = 10f)), + TransformPivotMode.IndividualOrigins, + scope = IndividualOriginScope.WholeMesh, + )!! + val groupA = capture.entries.first { it.drawableId == meshA }.groups.single() + val groupB = capture.entries.first { it.drawableId == meshB }.groups.single() + assertEquals(1f, groupA.pivotX, 1e-4f) + assertEquals(11f, groupB.pivotX, 1e-4f) // shifted square's own centroid, not the shared (6,1) anchor + } + + /** ConnectivityIsland Individual Origins splits one mesh's disjoint islands into separate groups. */ + @Test + fun individualOriginsConnectivityIslandSplitsDisjointIslands() { + // Two disjoint triangles in one mesh (verts 0-2 and 3-5, no shared edge). + val twoIslands = + ModalCaptureSource( + drawableId = meshA, + positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 10f, 10f, 11f, 10f, 10f, 11f), + triangleIndices = intArrayOf(0, 1, 2, 3, 4, 5), + coveredIndices = setOf(0, 1, 2, 3, 4, 5), + ) + val groups = + build(listOf(twoIslands), TransformPivotMode.IndividualOrigins, scope = IndividualOriginScope.ConnectivityIsland)!! + .entries + .single() + .groups + assertEquals(2, groups.size, "two disjoint islands -> two pivot groups") + assertEquals(setOf(setOf(0, 1, 2), setOf(3, 4, 5)), groups.map { it.vertexIndices }.toSet()) + } + + /** A source with no covered vertices is dropped; an all-empty source list returns null (no gesture). */ + @Test + fun emptyCoveredSourcesAreDroppedAndAllEmptyReturnsNull() { + val empty = ModalCaptureSource(meshB, floatArrayOf(5f, 5f), intArrayOf(), emptySet()) + val capture = build(listOf(square(meshA), empty))!! + assertEquals(listOf(meshA), capture.drawableIds, "the empty source does not become an entry") + assertNull(build(listOf(empty)), "no covered vertices anywhere -> no capture") + assertNull(build(emptyList())) + } + + /** With proportional off, every mesh's moved set is exactly its covered set. */ + @Test + fun noProportionalLeavesMovedSetEqualToCovered() { + val capture = build(listOf(square(meshA)))!! + capture.applyProportional(null, 100f) + val entry = capture.entries.single() + assertTrue(entry.influence.isEmpty()) + assertEquals(entry.coveredIndices, entry.movedIndices) + } + + /** Proportional editing with a wide radius pulls unselected neighbours into the moved set. */ + @Test + fun proportionalHaloAddsInfluencedNeighboursToTheMovedSet() { + // One selected vertex at the origin, one unselected vertex a short hop away, on a shared edge. + val mesh = + ModalCaptureSource( + drawableId = meshA, + positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + triangleIndices = intArrayOf(0, 1, 2), + coveredIndices = setOf(0), + ) + val capture = build(listOf(mesh))!! + capture.applyProportional(ProportionalEditState(ProportionalFalloff.Linear, radiusWorld = 5f), 5f) + val entry = capture.entries.single() + assertTrue(entry.influence.isNotEmpty(), "neighbours within the radius take weight") + assertTrue(entry.movedIndices.containsAll(entry.coveredIndices)) + assertTrue(entry.movedIndices.size > entry.coveredIndices.size, "the halo grew the moved set") + // Re-deriving from the same frozen positions is idempotent, never compounding. + val movedOnce = entry.movedIndices + capture.applyProportional(ProportionalEditState(ProportionalFalloff.Linear, radiusWorld = 5f), 5f) + assertEquals(movedOnce, entry.movedIndices) + } + + /** Connected Only measures the halo geodesically, so it cannot leap to a disjoint island. */ + @Test + fun connectedOnlyHaloDoesNotLeapToADisjointIsland() { + // Selected vertex 0 on the first triangle; the second triangle (verts 3-5) sits close in space but + // shares no edge, so a geodesic halo must never reach it. + val mesh = + ModalCaptureSource( + drawableId = meshA, + positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 0.5f, 0.5f, 1.5f, 0.5f, 0.5f, 1.5f), + triangleIndices = intArrayOf(0, 1, 2, 3, 4, 5), + coveredIndices = setOf(0), + ) + val capture = build(listOf(mesh))!! + capture.applyProportional(ProportionalEditState(ProportionalFalloff.Linear, radiusWorld = 100f, connectedOnly = true), 100f) + val influenced = capture.entries.single().influence.keys + assertTrue(influenced.all { it in setOf(1, 2) }, "geodesic halo stays on the connected island: $influenced") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectBoundsEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectBoundsEditsTest.kt new file mode 100644 index 0000000..433e66f --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectBoundsEditsTest.kt @@ -0,0 +1,123 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the pure bounds geometry behind the Properties panel's Position and Size rows: the rows READ + * meshBounds and WRITE through these ops, so the invariant that matters is that asking for a value makes + * the measurement become exactly that value. Also pins the bounds center as the resize pivot (which is + * what keeps the Position row from jumping when Size changes) and the degenerate-axis guard. + * + * These are space-agnostic - the Properties panel feeds them WORLD positions, and the session-level round + * trip through the deformer chain is covered in :ui by DrawableWorldTransformTest. + */ +class ObjectBoundsEditsTest { + private val drawableId = DrawableId("d") + + /** A 40 x 20 quad centered on (10, 5), deliberately asymmetric in x so the vertex mean is NOT the bounds center. */ + private val quadPositions = + floatArrayOf( + -10f, + -5f, + 30f, + -5f, + 30f, + 15f, + -10f, + 15f, + // A fifth vertex clustered left, to pull the vertex centroid away from the bounds center. + -9f, + 14f, + ) + + private fun drawable(positions: FloatArray?): Drawable = + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = positions?.let { DrawableMesh(it, FloatArray(it.size), intArrayOf(0, 1, 2)) }, + geometryGrid = null, + ) + + private fun model(positions: FloatArray? = quadPositions.copyOf()): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable(positions)), + rootChildren = emptyList(), + rootPartId = null, + ) + + @Test + fun boundsReportsTheCenterAndExtents() { + val bounds = meshBounds(quadPositions) + assertEquals(10f, bounds.centerX) + assertEquals(5f, bounds.centerY) + assertEquals(40f, bounds.width) + assertEquals(20f, bounds.height) + + // An empty or single-coordinate array degrades to a zero box rather than throwing. + val empty = meshBounds(floatArrayOf()) + assertEquals(0f, empty.width) + assertEquals(0f, empty.height) + } + + @Test + fun movingLandsTheBoundsCenterExactlyOnTheRequestedPoint() { + val moved = movedToBoundsCenter(quadPositions, -100f, 250f) + val bounds = meshBounds(moved) + // The whole contract of the Position row: what you type is what the readout becomes. + assertEquals(-100f, bounds.centerX) + assertEquals(250f, bounds.centerY) + // Rigid: the extents are untouched. + assertEquals(40f, bounds.width) + assertEquals(20f, bounds.height) + } + + @Test + fun movingToTheCurrentCenterIsANoOp() { + assertSame(quadPositions, movedToBoundsCenter(quadPositions, 10f, 5f)) + // An empty mesh has no center to move, so it comes back untouched (the same instance it was given). + val empty = floatArrayOf() + assertSame(empty, movedToBoundsCenter(empty, 1f, 1f)) + } + + @Test + fun resizingLandsTheExtentsAndHoldsThePositionStill() { + val resized = resizedAboutBoundsCenter(quadPositions, 80f, 5f) + val bounds = meshBounds(resized) + assertEquals(80f, bounds.width) + assertEquals(5f, bounds.height) + // The bounds center is the pivot, so the Position row does not move when Size is edited. This is + // what a vertex-centroid pivot would break: the extra clustered vertex pulls that mean off-center. + assertEquals(10f, bounds.centerX) + assertEquals(5f, bounds.centerY) + } + + @Test + fun resizingToTheCurrentExtentsIsANoOp() { + assertSame(quadPositions, resizedAboutBoundsCenter(quadPositions, 40f, 20f)) + } + + @Test + fun aDegenerateAxisIsLeftAloneRatherThanScaledByInfinity() { + // Every vertex on one horizontal line: height is 0, so no factor exists for it. + val flat = floatArrayOf(0f, 7f, 10f, 7f, 20f, 7f) + val resized = resizedAboutBoundsCenter(flat, 40f, 100f) + val bounds = meshBounds(resized) + assertEquals(40f, bounds.width, "the well-defined axis still scales") + assertEquals(0f, bounds.height, "the degenerate axis stays degenerate, not NaN or infinite") + assertTrue(resized.all { coordinate -> coordinate.isFinite() }, "no infinity leaked into the geometry") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectOperatorSessionTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectOperatorSessionTest.kt new file mode 100644 index 0000000..0c4af93 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectOperatorSessionTest.kt @@ -0,0 +1,186 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the Object-mode session surface: the select-tool guards relaxed for Object mode, the object + * operator's eligibility guard and single-step commit, and the transient-tool clears that keep an armed + * object tool from leaking across a mode switch or an undo. + */ +class ObjectOperatorSessionTest { + private fun meshDrawable(id: String, positions: FloatArray): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2)), + geometryGrid = null, + ) + + private val warp = Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null) + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = listOf(warp), + drawables = listOf(meshDrawable("a", floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f)), meshDrawable("b", floatArrayOf(2f, 2f, 3f, 2f, 2f, 3f))), + rootChildren = emptyList(), + rootPartId = null, + ) + + private fun session(): EditorSession = EditorSession(model()) + + private val drawableA = SelectionTarget.Drawable(DrawableId("a")) + + /** Box / Circle select arm in Object mode with no drawable required (the box builds a whole-object selection). */ + @Test + fun selectToolsArmInObjectModeWithoutDrawable() { + val session = session() + assertEquals(EditorMode.Object, session.mode.value) + + session.beginBoxSelect("area-test") + assertTrue(session.activeSelectTool.value is ActiveSelectTool.BoxArmed, "box arms in Object mode") + + session.beginCircleSelect("area-test") + assertTrue(session.activeSelectTool.value is ActiveSelectTool.Circle, "circle arms in Object mode") + } + + /** An object operator latches on an eligible drawable selection. */ + @Test + fun objectOperatorArmsOnEligibleSelection() { + val session = session() + session.setSelection(Selection(setOf(drawableA), drawableA)) + + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind) + } + + /** An object operator blocks (stays null) when the selection holds nothing transformable at all. */ + @Test + fun objectOperatorBlocksOnIneligibleSelection() { + val session = session() + + // Empty selection. + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertNull(session.activeObjectOperator.value, "empty selection blocks") + assertEquals("notice.transform.onlyDrawables", session.notice.value?.messageKey, "the block explains itself") + assertEquals(NoticePlacement.NearCursor, session.notice.value?.placement, "the note shows near the pointer") + + // A selection of only a deformer blocks (nothing transformable). + session.setSelection(Selection(setOf(SelectionTarget.Deformer(DeformerId("w"))), null)) + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertNull(session.activeObjectOperator.value, "an only-deformer selection blocks") + } + + /** A deformer beside a drawable is silently skipped: the operator still arms for the drawable. */ + @Test + fun objectOperatorSkipsIneligibleTargetsBesideDrawables() { + val session = session() + session.setSelection(Selection(setOf(drawableA, SelectionTarget.Deformer(DeformerId("w"))), drawableA)) + + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind, "the drawable beside the deformer still transforms") + } + + /** An object operator refuses to start while any parameter is scrubbed away from its default. */ + @Test + fun objectOperatorBlocksWhilePoseIsDeformed() { + val angle = Parameter(ParameterId("angle"), "Angle", min = -1f, max = 1f, default = 0f) + val session = EditorSession(model().copy(parameters = listOf(angle))) + session.setSelection(Selection(setOf(drawableA), drawableA)) + + // Scrub the parameter away from its default, then try to transform. + session.commitPose(ParameterChange.SetValue(listOf(angle.id)), mapOf(angle.id to 0.5f)) + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertNull(session.activeObjectOperator.value, "a deformed pose blocks the transform") + assertEquals("notice.transform.deformed", session.notice.value?.messageKey, "the guard explains itself") + assertEquals(NoticePlacement.NearCursor, session.notice.value?.placement, "the note shows near the pointer") + + // Back at defaults the same gesture arms. + session.commitPose(ParameterChange.SetValue(listOf(angle.id)), mapOf(angle.id to 0f)) + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind, "a neutral pose arms") + } + + /** An object operator only arms in Object mode. */ + @Test + fun objectOperatorRequiresObjectMode() { + val session = session() + session.setSelection(Selection(setOf(drawableA), drawableA)) + session.setMode(EditorMode.Edit) + + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + assertNull(session.activeObjectOperator.value, "no object operator in Edit mode") + } + + /** commitObjectPositions writes the new base positions as exactly one undo step. */ + @Test + fun commitObjectPositionsIsOneUndoStep() { + val session = session() + assertFalse(session.canUndo.value) + + val moved = floatArrayOf(10f, 10f, 11f, 10f, 10f, 11f) + session.commitObjectPositions(MeshChange.TransformDrawables(listOf(DrawableId("a")), MeshOperatorKind.Grab), mapOf(DrawableId("a") to moved)) + + assertTrue(session.canUndo.value, "the commit is undoable") + assertTrue(session.dirty.value, "a rest-geometry edit dirties the document") + assertEquals(moved.toList(), session.model.value.drawables.first { it.id == DrawableId("a") }.mesh!!.positions.toList()) + + // Exactly one step: a single undo returns to the original geometry with nothing left to undo. + session.undo() + assertFalse(session.canUndo.value, "exactly one step was recorded") + assertEquals(listOf(0f, 0f, 1f, 0f, 0f, 1f), session.model.value.drawables.first { it.id == DrawableId("a") }.mesh!!.positions.toList()) + } + + /** commitObjectPositions with the drawable's existing positions is a no-op that records nothing. */ + @Test + fun commitObjectPositionsIdentityRecordsNothing() { + val session = session() + val current = session.model.value.drawables.first { it.id == DrawableId("a") }.mesh!!.positions + + session.commitObjectPositions(MeshChange.TransformDrawables(listOf(DrawableId("a")), MeshOperatorKind.Grab), mapOf(DrawableId("a") to current)) + assertFalse(session.canUndo.value, "committing the same positions records nothing") + } + + // (The object change's history label is pinned across every operator kind in TransformChangeLabelTest.) + + /** Switching to Edit mode clears an armed object select tool, so it cannot leak into the Edit overlay. */ + @Test + fun switchingToEditClearsArmedObjectTool() { + val session = session() + session.beginBoxSelect("area-test") + assertTrue(session.activeSelectTool.value is ActiveSelectTool.BoxArmed) + + session.setMode(EditorMode.Edit) + assertNull(session.activeSelectTool.value, "the armed object tool is cleared entering Edit mode") + } + + /** An undo (restore) ends any armed transient tool regardless of the restored mode. */ + @Test + fun undoClearsArmedObjectTool() { + val session = session() + // A committed step so there is something to undo. + session.commitObjectPositions(MeshChange.TransformDrawables(listOf(DrawableId("a")), MeshOperatorKind.Grab), mapOf(DrawableId("a") to floatArrayOf(9f, 9f, 9f, 9f, 9f, 9f))) + session.beginBoxSelect("area-test") + assertTrue(session.activeSelectTool.value is ActiveSelectTool.BoxArmed) + + session.undo() + assertNull(session.activeSelectTool.value, "restore clears the armed tool") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectTransformsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectTransformsTest.kt new file mode 100644 index 0000000..64762b4 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ObjectTransformsTest.kt @@ -0,0 +1,128 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies [eligibleTransformDrawables] - the gate that decides what an Object-mode G / S / R may run + * over: mesh-carrying drawables from the selection, with selected parts expanded to their subtree + * meshes, and deformers / mesh-less drawables silently skipped; null only when the selection holds + * nothing transformable at all (so the caller blocks the gesture with a note). Also verifies + * [isPoseNeutral], the guard that refuses an Object-mode transform while any parameter is scrubbed + * away from its default. + */ +class ObjectTransformsTest { + private fun mesh(): DrawableMesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2)) + + private fun drawable(id: String, withMesh: Boolean): Drawable = + Drawable( + DrawableId(id), + id.uppercase(), + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = if (withMesh) mesh() else null, + geometryGrid = null, + ) + + // A model with two mesh-carrying drawables, one mesh-less drawable, a part that owns drawable a, + // an empty part, and a deformer. + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + Part(PartId("p"), "P", children = listOf(OrgChild.Drawable(DrawableId("a")))), + Part(PartId("empty"), "Empty", children = emptyList()), + ), + deformers = listOf(Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null)), + drawables = listOf(drawable("a", withMesh = true), drawable("b", withMesh = true), drawable("empty", withMesh = false)), + rootChildren = listOf(OrgChild.Part(PartId("p")), OrgChild.Part(PartId("empty")), OrgChild.Drawable(DrawableId("b"))), + rootPartId = null, + ) + + private val drawableA = SelectionTarget.Drawable(DrawableId("a")) + private val drawableB = SelectionTarget.Drawable(DrawableId("b")) + + /** All targets are mesh-carrying drawables: the ids are returned (order-independent). */ + @Test + fun allMeshDrawablesAreEligible() { + val ids = eligibleTransformDrawables(Selection(setOf(drawableA, drawableB), drawableB), model()) + assertEquals(setOf(DrawableId("a"), DrawableId("b")), ids?.toSet(), "both drawable ids are eligible") + } + + /** An empty selection has nothing to transform. */ + @Test + fun emptySelectionIsIneligible() { + assertNull(eligibleTransformDrawables(Selection(), model())) + } + + /** A selected part expands to the mesh drawables in its outliner subtree. */ + @Test + fun partSelectionExpandsToSubtreeMeshes() { + val selection = Selection(setOf(SelectionTarget.Part(PartId("p"))), SelectionTarget.Part(PartId("p"))) + assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model())) + } + + /** A part and one of its drawables in the same selection do not double-list the mesh. */ + @Test + fun partAndOwnDrawableDedup() { + val selection = Selection(setOf(drawableA, SelectionTarget.Part(PartId("p"))), drawableA) + assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model())) + } + + /** A deformer in the selection is silently skipped; the drawable beside it still transforms. */ + @Test + fun deformerInSelectionIsSkipped() { + val selection = Selection(setOf(drawableA, SelectionTarget.Deformer(DeformerId("w"))), drawableA) + assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model())) + } + + /** A mesh-less drawable in the selection is silently skipped: it has no positions to move. */ + @Test + fun meshlessDrawableInSelectionIsSkipped() { + val selection = Selection(setOf(drawableA, SelectionTarget.Drawable(DrawableId("empty"))), drawableA) + assertEquals(listOf(DrawableId("a")), eligibleTransformDrawables(selection, model())) + } + + /** A selection holding nothing transformable at all (empty part + deformer) blocks. */ + @Test + fun onlyIneligibleTargetsBlock() { + val selection = Selection(setOf(SelectionTarget.Part(PartId("empty")), SelectionTarget.Deformer(DeformerId("w"))), null) + assertNull(eligibleTransformDrawables(selection, model())) + } + + private fun parameter(id: String, default: Float): Parameter = Parameter(ParameterId(id), id, min = -1f, max = 1f, default = default) + + private fun modelWithParameters(): PuppetModel = model().copy(parameters = listOf(parameter("angle", 0f), parameter("breath", 0.5f))) + + /** Every parameter at its default (explicitly or by omission) is neutral. */ + @Test + fun poseAtDefaultsIsNeutral() { + val model = modelWithParameters() + assertTrue(isPoseNeutral(model, mapOf(ParameterId("angle") to 0f, ParameterId("breath") to 0.5f)), "explicit defaults are neutral") + assertTrue(isPoseNeutral(model, emptyMap()), "an omitted parameter counts as neutral") + } + + /** Any parameter scrubbed away from its default makes the pose non-neutral. */ + @Test + fun scrubbedPoseIsNotNeutral() { + val model = modelWithParameters() + assertFalse(isPoseNeutral(model, mapOf(ParameterId("angle") to 0.25f))) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/OutlinerTreeEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/OutlinerTreeEditsTest.kt new file mode 100644 index 0000000..b53580b --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/OutlinerTreeEditsTest.kt @@ -0,0 +1,221 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class OutlinerTreeEditsTest { + private val partA = PartId("A") + private val partB = PartId("B") + private val drawable1 = DrawableId("d1") + private val drawable2 = DrawableId("d2") + private val drawable3 = DrawableId("d3") + private val warpRoot = DeformerId("w1") + private val warpSibling = DeformerId("w2") + private val warpNested = DeformerId("w3") + + /** + * A minimal tree model: part A holds drawables d1 + d2, part B is empty, d3 sits at the root; the + * armature has roots w1 + w2 with w3 nested under w1. Only the fields the drop resolution walks + * (parts, rootChildren, deformers) are populated. + * + * @return PuppetModel The fixture model. + */ + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + Part(partA, "A", children = listOf(OrgChild.Drawable(drawable1), OrgChild.Drawable(drawable2))), + Part(partB, "B", children = emptyList()), + ), + deformers = + listOf( + rotation(warpRoot, parent = null), + rotation(warpSibling, parent = null), + rotation(warpNested, parent = warpRoot), + ), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(partA), OrgChild.Part(partB), OrgChild.Drawable(drawable3)), + rootPartId = null, + ) + + /** + * A minimal rotation deformer for armature-shape tests (the kind is irrelevant to drop routing). + * + * @param DeformerId id The deformer's id. + * @param DeformerId? parent Its nesting parent, or null at the armature root. + * @return Deformer The deformer. + */ + private fun rotation(id: DeformerId, parent: DeformerId?): Deformer = + Deformer.Rotation(id, id.raw, parent = parent, partId = null, baseAngle = 0f, geometryGrid = null) + + private fun PuppetModel.band(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): RowDropBand? = + outlinerDropBandFor(dragged, OutlinerDropTarget.Entity(target), fraction) + + private fun PuppetModel.drop(dragged: SelectionTarget, target: SelectionTarget, fraction: Float): OutlinerDrop? = + resolveOutlinerDrop(dragged, OutlinerDropTarget.Entity(target), fraction) + + @Test + fun bandRefusesCrossDomainDrops() { + val model = model() + assertNull(model.band(SelectionTarget.Deformer(warpRoot), SelectionTarget.Drawable(drawable1), 0.5f)) + assertNull(model.band(SelectionTarget.Drawable(drawable1), SelectionTarget.Deformer(warpRoot), 0.5f)) + } + + @Test + fun drawableTargetSplitsAtMidlineAndNeverNests() { + val model = model() + val dragged = SelectionTarget.Drawable(drawable3) + val target = SelectionTarget.Drawable(drawable1) + assertEquals(RowDropBand.Before, model.band(dragged, target, 0.4f)) + assertEquals(RowDropBand.After, model.band(dragged, target, 0.6f)) + } + + @Test + fun partTargetHasWideIntoBandForDrawables() { + val model = model() + val dragged = SelectionTarget.Drawable(drawable3) + val target = SelectionTarget.Part(partB) + assertEquals(RowDropBand.Before, model.band(dragged, target, 0.2f)) + assertEquals(RowDropBand.Into, model.band(dragged, target, 0.5f)) + assertEquals(RowDropBand.After, model.band(dragged, target, 0.8f)) + } + + @Test + fun partOnPartOnlyReordersAtMidline() { + // Folders on folders match the parameters panel: before / after only, so sibling reorder is not + // fighting a middle "into" band. Nesting a part is dropping beside a child inside the destination. + val model = model() + val dragged = SelectionTarget.Part(partB) + val target = SelectionTarget.Part(partA) + assertEquals(RowDropBand.Before, model.band(dragged, target, 0.4f)) + assertEquals(RowDropBand.After, model.band(dragged, target, 0.6f)) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Part(partB), newParentId = null, before = OrgChild.Part(partA), expandTarget = false), + model.drop(dragged, target, 0.2f), + ) + // Midline is After (not Into): next root sibling after A is B itself, which the move treats as append. + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Part(partB), newParentId = null, before = OrgChild.Part(partB), expandTarget = false), + model.drop(dragged, target, 0.5f), + ) + } + + @Test + fun beforeDropAnchorsOnTargetInsideItsParent() { + val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Drawable(drawable1), 0.1f) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partA, before = OrgChild.Drawable(drawable1), expandTarget = false), + drop, + ) + } + + @Test + fun afterDropAnchorsOnNextSibling() { + val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Drawable(drawable1), 0.9f) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partA, before = OrgChild.Drawable(drawable2), expandTarget = false), + drop, + ) + } + + @Test + fun afterDropOnLastSiblingAppends() { + val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Drawable(drawable2), 0.9f) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partA, before = null, expandTarget = false), + drop, + ) + } + + @Test + fun intoPartNestsAndExpands() { + val drop = model().drop(SelectionTarget.Drawable(drawable3), SelectionTarget.Part(partB), 0.5f) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable3), partB, before = null, expandTarget = true), + drop, + ) + } + + @Test + fun rootLevelTargetResolvesRootSiblings() { + // Dropping d1 after part B at the root: the next root sibling is d3. + val drop = model().drop(SelectionTarget.Drawable(drawable1), SelectionTarget.Part(partB), 0.9f) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable1), newParentId = null, before = OrgChild.Drawable(drawable3), expandTarget = false), + drop, + ) + } + + @Test + fun puppetRootDropMovesOrgChildToTopLevel() { + val model = model() + val dragged = SelectionTarget.Drawable(drawable1) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable1), newParentId = null, before = OrgChild.Part(partA), expandTarget = false), + model.resolveOutlinerDrop(dragged, OutlinerDropTarget.PuppetRoot, 0.2f), + ) + assertEquals( + OutlinerDrop.MoveOrgChild(OrgChild.Drawable(drawable1), newParentId = null, before = null, expandTarget = false), + model.resolveOutlinerDrop(dragged, OutlinerDropTarget.PuppetRoot, 0.8f), + ) + assertNull(model.resolveOutlinerDrop(SelectionTarget.Deformer(warpRoot), OutlinerDropTarget.PuppetRoot, 0.5f)) + } + + @Test + fun armatureDropMakesDeformerARoot() { + val model = model() + assertEquals( + OutlinerDrop.MoveDeformer(warpNested, newParentId = null, beforeId = null, expandTarget = true), + model.resolveOutlinerDrop(SelectionTarget.Deformer(warpNested), OutlinerDropTarget.Armature, 0.5f), + ) + assertNull(model.resolveOutlinerDrop(SelectionTarget.Part(partA), OutlinerDropTarget.Armature, 0.5f)) + } + + @Test + fun cycleOntoOwnDescendantIsRefused() { + // Nest B under A, then dragging A onto B (or into B via a child) must not resolve. + val nested = + model().copy( + parts = + listOf( + Part(partA, "A", children = listOf(OrgChild.Part(partB), OrgChild.Drawable(drawable1))), + Part(partB, "B", children = emptyList()), + ), + rootChildren = listOf(OrgChild.Part(partA), OrgChild.Drawable(drawable3)), + ) + assertNull(nested.drop(SelectionTarget.Part(partA), SelectionTarget.Part(partB), 0.2f)) + assertNull(nested.drop(SelectionTarget.Part(partA), SelectionTarget.Drawable(drawable1), 0.9f)) + } + + @Test + fun deformerBeforeAndAfterAnchorWithinParent() { + val model = model() + // w2 dropped before w3 (nested under w1): parent w1, anchored on w3. + assertEquals( + OutlinerDrop.MoveDeformer(warpSibling, warpRoot, beforeId = warpNested, expandTarget = false), + model.drop(SelectionTarget.Deformer(warpSibling), SelectionTarget.Deformer(warpNested), 0.1f), + ) + // w2 dropped after w3, the last of w1's children: append (null anchor). + assertEquals( + OutlinerDrop.MoveDeformer(warpSibling, warpRoot, beforeId = null, expandTarget = false), + model.drop(SelectionTarget.Deformer(warpSibling), SelectionTarget.Deformer(warpNested), 0.9f), + ) + } + + @Test + fun deformerIntoNestsAndExpands() { + assertEquals( + OutlinerDrop.MoveDeformer(warpSibling, warpRoot, beforeId = null, expandTarget = true), + model().drop(SelectionTarget.Deformer(warpSibling), SelectionTarget.Deformer(warpRoot), 0.5f), + ) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterCrudEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterCrudEditsTest.kt new file mode 100644 index 0000000..8cf3ed9 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterCrudEditsTest.kt @@ -0,0 +1,423 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the parameter document edits: create mints a fresh animatable axis at the top and returns its id, + * rename changes the display name (id-stable) with blank / unchanged no-ops, and delete removes the axis + * from the parameters list, the panel tree, any link, and every keyform grid - collapsing a grid to the + * deleted parameter's default slice or to null when it was the last axis. Also pins the generic + * withAxisCollapsed coordinate math, and that each edit undoes. + */ +class ParameterCrudEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + /** An animatable parameter over -1..1 with the given [default]. */ + private fun parameter(id: ParameterId, default: Float = 0f): Parameter = + Parameter(id, id.raw, min = -1f, max = 1f, default = default) + + /** A drawable-less model holding [parameters], [links], [tree], and optional [drawables]. */ + private fun model( + parameters: List, + links: List = emptyList(), + tree: List = emptyList(), + drawables: List = emptyList(), + ): PuppetModel = + PuppetModel( + parameters = parameters, + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + parameterLinks = links, + parameterTree = tree, + ) + + /** + * A drawable keyed on angleX (keys -1, 0, 1) then angleY (keys 0, 1) - a 3x2 grid whose every cell's + * MeshForm carries a distinctive value (xIndex*10 + yIndex), so a collapse can be traced by payload. + */ + private fun keyedDrawable(): Drawable { + val axes = listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))) + val cells = + buildList { + for (xIndex in 0..2) { + for (yIndex in 0..1) { + add(KeyformCell(intArrayOf(xIndex, yIndex), MeshDeltaForm(floatArrayOf(xIndex * 10f + yIndex)))) + } + } + } + return Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = KeyformGrid(axes, cells), + ) + } + + /** Create appends the axis, prepends its leaf at the top, and returns the minted id. */ + @Test + fun createAppendsAxisAndPrependsLeaf() { + val session = EditorSession(model(listOf(parameter(angleX)))) + val id = session.createParameter("New Parameter") + + assertEquals(ParameterId("Param"), id, "the first minted id is Param") + val created = session.model.value.parameters.first { it.id == id } + assertEquals("New Parameter", created.name) + assertTrue(created.min < created.max, "the new parameter is animatable") + assertEquals(ParameterNode.Param(id), session.model.value.parameterTree.first(), "the leaf is at the top") + assertEquals(ParameterKind.NORMAL, created.kind, "the default kind is a key-form parameter") + + session.undo() + assertTrue(session.model.value.parameters.none { it.id == id }, "undo removes the new parameter") + } + + /** Create carries the requested kind (a blend-shape parameter authored with no keys yet). */ + @Test + fun createUsesRequestedKind() { + val session = EditorSession(model(listOf(parameter(angleX)))) + + val normalId = session.createParameter("A", ParameterKind.NORMAL) + val blendId = session.createParameter("B", ParameterKind.BLEND_SHAPE) + + assertEquals( + ParameterKind.NORMAL, + session.model.value.parameters.first { it.id == normalId }.kind, + "explicit NORMAL stays a key-form parameter", + ) + val blend = session.model.value.parameters.first { it.id == blendId } + assertEquals(ParameterKind.BLEND_SHAPE, blend.kind, "BLEND_SHAPE is carried through to the model") + assertTrue(session.model.value.drawables.all { it.blendShapes.isEmpty() }, "a fresh blend parameter keys nothing yet") + } + + /** The minted parameter id skips ids already present. */ + @Test + fun freshIdAvoidsCollision() { + val existing = model(listOf(parameter(ParameterId("Param")), parameter(ParameterId("Param2")))) + assertEquals(ParameterId("Param3"), existing.freshParameterId()) + } + + /** Rename changes the display name; blank and unchanged names are no-ops. */ + @Test + fun renameChangesNameBlankAndUnchangedAreNoOps() { + val start = model(listOf(parameter(angleX))) + val renamed = start.withParameterRenamed(angleX, " Eyes ") + assertEquals("Eyes", renamed.parameters.single().name) + + assertSame(start, start.withParameterRenamed(angleX, " "), "a blank rename is a no-op") + assertSame(renamed, renamed.withParameterRenamed(angleX, "Eyes"), "an unchanged rename is a no-op") + } + + /** Delete scrubs the parameters list, the tree leaf, and any link containing it. */ + @Test + fun deleteRemovesFromParametersTreeAndLink() { + val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY)) + val links = listOf(ParameterLink(angleX, angleY)) + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)), links, tree)) + session.deleteParameter(angleX) + + val after = session.model.value + assertTrue(after.parameters.none { it.id == angleX }, "the axis is gone") + assertTrue(after.parameterTree.none { it is ParameterNode.Param && it.id == angleX }, "the leaf is gone") + assertTrue(after.parameterLinks.isEmpty(), "the link that contained it is gone") + + session.undo() + assertTrue(session.model.value.parameters.any { it.id == angleX }, "undo restores the parameter") + assertEquals(1, session.model.value.parameterLinks.size, "undo restores the link") + } + + /** Delete collapses a multi-axis grid to the deleted axis's default slice, re-projecting coordinates. */ + @Test + fun deleteCollapsesGridToDefaultSlice() { + // default 0 on angleX -> keeps key index 1 (the value-0 key) of [-1, 0, 1]. + val session = EditorSession(model(listOf(parameter(angleX, default = 0f), parameter(angleY)), drawables = listOf(keyedDrawable()))) + session.deleteParameter(angleX) + + val grid = session.model.value.drawables.single().geometryGrid!! + assertEquals(listOf(angleY), grid.axes.map { it.parameterId }, "only angleY remains") + assertEquals(2, grid.cells.size, "the 3x2 grid collapsed to the 2 cells of the kept slice") + // The surviving forms are the angleX-index-1 slice: xIndex*10 + yIndex = 10 and 11. + val byCoordinate = grid.cells.associate { it.coordinate.single() to it.form.positionDeltas.single() } + assertEquals(10f, byCoordinate[0], "cell (angleY key 0) kept the default-slice form") + assertEquals(11f, byCoordinate[1], "cell (angleY key 1) kept the default-slice form") + } + + /** Deleting the sole axis of a grid leaves the entity unkeyed (null grid). */ + @Test + fun deleteSoleAxisGridBecomesNull() { + val singleAxis = + keyedDrawable().copy( + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(1f))), + KeyformCell(intArrayOf(2), MeshDeltaForm(floatArrayOf(2f))), + ), + ), + ) + val session = EditorSession(model(listOf(parameter(angleX)), drawables = listOf(singleAxis))) + session.deleteParameter(angleX) + assertNull(session.model.value.drawables.single().geometryGrid, "the last-axis grid becomes null") + } + + /** Deleting a parameter not present in a grid leaves that grid's entity untouched by identity. */ + @Test + fun deleteUnkeyedParamLeavesGridsUntouched() { + val drawable = keyedDrawable() + // angleZ exists as a parameter but is not an axis of the drawable's grid. + val angleZ = ParameterId("ParamAngleZ") + val start = model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)), drawables = listOf(drawable)) + val after = start.withParameterDeleted(angleZ) + assertSame(drawable.geometryGrid, after.drawables.single().geometryGrid, "an untouched grid keeps its instance") + } + + /** Deleting an unknown parameter is a no-op (same instance, no undo step). */ + @Test + fun deleteUnknownIsNoOp() { + val start = model(listOf(parameter(angleX))) + assertSame(start, start.withParameterDeleted(ParameterId("ParamNope"))) + } + + /** A single-axis channel track over angleX with one [ChannelValue.Scalar] per key of [-1, 0, 1]. */ + private fun scalarTrack(vararg values: Float): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f))), + values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), ChannelValue.Scalar(value)) }, + ) + + /** + * Dropping a channel track whose only axis is the deleted parameter lifts the kept slice's value into + * the owner's static, so the neutral look survives the drop instead of snapping back to the static. + */ + @Test + fun deleteLiftsCollapsedOpacityTrackIntoStatic() { + val drawable = + keyedDrawable().copy( + geometryGrid = null, + opacity = 1f, + channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0.5f, 0.3f, 0.9f))), + ) + // angleX's default is 0, whose key is index 1 - the neutral look renders opacity 0.3. + val start = model(listOf(parameter(angleX, default = 0f)), drawables = listOf(drawable)) + val after = start.withParameterDeleted(angleX) + + val scrubbed = after.drawables.single() + assertNull(scrubbed.channelGrids[FormChannel.OPACITY], "the sole-axis track is dropped") + assertEquals(0.3f, scrubbed.opacity, "the kept slice's value took over the static") + } + + /** The same lift for a glue: the kept slice's intensity replaces the full-weld static. */ + @Test + fun deleteLiftsGlueIntensityIntoStatic() { + val glue = + Glue( + meshA = DrawableId("a"), + meshB = DrawableId("b"), + pairs = emptyList(), + channelGrids = ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to scalarTrack(0.2f, 0.4f, 0.8f))), + ) + val start = model(listOf(parameter(angleX, default = 0f))).copy(glues = listOf(glue)) + val after = start.withParameterDeleted(angleX) + + val scrubbed = after.glues.single() + assertNull(scrubbed.channelGrids[FormChannel.GLUE_INTENSITY], "the sole-axis track is dropped") + assertEquals(0.4f, scrubbed.intensity, "the kept slice's intensity took over the static") + } + + /** + * A fractional part draw order cannot lift into the Int static slot, so it stays behind as a zero-axis + * constant track; an integral one lifts. + */ + @Test + fun deletePartDrawOrderLiftsIntegralKeepsFractionalAsConstant() { + val fractionalPart = + Part( + id = PartId("pFractional"), + name = "pFractional", + children = emptyList(), + groupMode = PartGroupMode.Grouped, + channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to scalarTrack(500f, 550.5f, 600f))), + ) + val integralPart = + Part( + id = PartId("pIntegral"), + name = "pIntegral", + children = emptyList(), + groupMode = PartGroupMode.Grouped, + channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to scalarTrack(500f, 600f, 700f))), + ) + val start = + model(listOf(parameter(angleX, default = 0f))) + .copy(parts = listOf(fractionalPart, integralPart)) + val after = start.withParameterDeleted(angleX) + + val fractional = after.parts.first { part -> part.id == PartId("pFractional") } + val constantTrack = fractional.channelGrids[FormChannel.DRAW_ORDER]!! + assertTrue(constantTrack.axes.isEmpty(), "the fractional value stays as a zero-axis constant track") + assertEquals(550.5f, (constantTrack.cells.single().form as ChannelValue.Scalar).value) + assertEquals(500, fractional.drawOrder, "the Int static keeps its value rather than rounding") + + val integral = after.parts.first { part -> part.id == PartId("pIntegral") } + assertNull(integral.channelGrids[FormChannel.DRAW_ORDER], "the integral track is dropped") + assertEquals(600, integral.drawOrder, "the kept slice's value lifted into the Int static") + } + + /** + * The render root's per-group copies of the part tracks are re-derived after the delete, so the + * evaluator (which samples renderRoot, not the parts list) cannot keep blending a ghost axis. + */ + @Test + fun deleteRederivesRenderRootPartTracks() { + val twoAxisTrack = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))), + buildList { + for (xIndex in 0..2) { + for (yIndex in 0..1) { + add(KeyformCell(intArrayOf(xIndex, yIndex), ChannelValue.Scalar(500f + xIndex * 10f + yIndex))) + } + } + }, + ) + val part = + Part( + id = PartId("p"), + name = "p", + children = emptyList(), + groupMode = PartGroupMode.Grouped, + channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to twoAxisTrack)), + ) + val start = + model(listOf(parameter(angleX, default = 0f), parameter(angleY))) + .copy(parts = listOf(part), rootChildren = listOf(OrgChild.Part(PartId("p")))) + .withDerivedRenderRoot() + val staleAxes = start.renderRoot.children.filterIsInstance().single().channelGrids[FormChannel.DRAW_ORDER]!!.axes + assertEquals(listOf(angleX, angleY), staleAxes.map { axis -> axis.parameterId }, "precondition: the group carries both axes") + + val after = start.withParameterDeleted(angleX) + val group = after.renderRoot.children.filterIsInstance().single() + val survivingAxes = group.channelGrids[FormChannel.DRAW_ORDER]!!.axes + assertEquals(listOf(angleY), survivingAxes.map { axis -> axis.parameterId }, "the render tree lost the deleted axis too") + } + + /** + * A glue's intensity TRACK is scrubbed too, so a deleted parameter leaves no dangling axis behind. + * Glue was the one owner the original scrub walk missed entirely. + */ + @Test + fun deleteScrubsGlueIntensityTrack() { + val intensityTrack = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))), + buildList { + for (xIndex in 0..2) { + for (yIndex in 0..1) { + add(KeyformCell(intArrayOf(xIndex, yIndex), ChannelValue.Scalar(xIndex * 10f + yIndex))) + } + } + }, + ) + val glue = + Glue( + meshA = DrawableId("a"), + meshB = DrawableId("b"), + pairs = emptyList(), + channelGrids = ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to intensityTrack)), + ) + val start = model(listOf(parameter(angleX), parameter(angleY))).copy(glues = listOf(glue)) + val after = start.withParameterDeleted(angleX) + val collapsed = after.glues.single().channelGrids[FormChannel.GLUE_INTENSITY]!! + assertEquals(listOf(angleY), collapsed.axes.map { axis -> axis.parameterId }, "the deleted axis is gone") + // angleX's default is 0, whose nearest key is index 1 - so the surviving intensities are 10 and 11. + assertEquals(listOf(10f, 11f), collapsed.cells.map { cell -> (cell.form as ChannelValue.Scalar).value }) + } + + /** Moving keys onto another parameter retargets grid axes instead of collapsing them. */ + @Test + fun deleteMoveKeysRetargetsGridOntoDestination() { + val session = + EditorSession(model(listOf(parameter(angleX), parameter(angleY)), drawables = listOf(keyedDrawable()))) + session.deleteParameter(angleX, moveKeysTo = angleY) + + val after = session.model.value + assertTrue(after.parameters.none { it.id == angleX }, "source parameter is gone") + assertTrue(after.parameters.any { it.id == angleY }, "destination parameter remains") + val grid = after.drawables.single().geometryGrid!! + assertEquals(listOf(angleY), grid.axes.map { it.parameterId }, "the source axis now keys the destination") + assertTrue(grid.axes.single().keys.contentEquals(floatArrayOf(-1f, 0f, 1f)), "key values are kept absolute") + assertEquals(3, grid.cells.size, "destination's prior axis collapsed; source's three keys remain") + + session.undo() + assertTrue(session.model.value.parameters.any { it.id == angleX }, "undo restores the source parameter") + assertEquals( + listOf(angleX, angleY), + session.model.value.drawables.single().geometryGrid!!.axes.map { it.parameterId }, + ) + } + + /** Discarding a blend-shape driver drops its binding; moving retargets it onto the destination. */ + @Test + fun deleteScrubsOrMovesBlendShapeBindings() { + val binding = + BlendShapeBinding( + parameterId = angleX, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, MeshForm(floatArrayOf(1f, 2f))), + ) + val drawable = keyedDrawable().copy(geometryGrid = null, blendShapes = listOf(binding)) + val start = model(listOf(parameter(angleX), parameter(angleY)), drawables = listOf(drawable)) + + val discarded = start.withParameterDeleted(angleX) + assertTrue(discarded.drawables.single().blendShapes.isEmpty(), "discard drops the binding") + + val moved = start.withParameterDeleted(angleX, moveKeysTo = angleY) + val movedBinding = moved.drawables.single().blendShapes.single() + assertEquals(angleY, movedBinding.parameterId, "move retargets the binding onto the destination") + assertTrue(movedBinding.keys.contentEquals(floatArrayOf(0f, 1f))) + } + + /** A missing or self moveKeysTo is a no-op (same instance). */ + @Test + fun deleteMoveKeysInvalidDestinationIsNoOp() { + val start = model(listOf(parameter(angleX), parameter(angleY)), drawables = listOf(keyedDrawable())) + assertSame(start, start.withParameterDeleted(angleX, moveKeysTo = ParameterId("ParamNope"))) + assertSame(start, start.withParameterDeleted(angleX, moveKeysTo = angleX)) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterGroupEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterGroupEditsTest.kt new file mode 100644 index 0000000..4a01514 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterGroupEditsTest.kt @@ -0,0 +1,106 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the parameter-group document edits: create mints a fresh expanded group at the top, delete + * unwraps (splicing children to the root, leaving parameters and links untouched), rename changes the + * label, a blank rename is a no-op, the id mint avoids collisions, and each undoes. + */ +class ParameterGroupEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + /** An animatable parameter over -1..1. */ + private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f) + + /** A drawable-less model holding [parameters], [links], and an optional group [tree]. */ + private fun model( + parameters: List, + links: List = emptyList(), + tree: List = emptyList(), + ): PuppetModel = + PuppetModel( + parameters = parameters, + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + parameterLinks = links, + parameterTree = tree, + ) + + /** A group node with the given children. */ + private fun group(id: ParameterGroupId, children: List): ParameterNode.Group = + ParameterNode.Group(id, id.raw, initiallyOpen = true, children = children) + + /** Create prepends a fresh expanded group and materializes the flat tree beneath it. */ + @Test + fun createPrependsFreshExpandedGroupAtTop() { + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)))) + val id = session.createParameterGroup("New Group") + + val tree = session.model.value.parameterTree + val head = tree.first() as ParameterNode.Group + assertEquals(id, head.id) + assertEquals("New Group", head.name) + assertTrue(head.initiallyOpen) + assertTrue(head.children.isEmpty()) + // The former flat parameters materialized as root leaves beneath the new group. + assertEquals(listOf(angleX, angleY), tree.filterIsInstance().map { it.id }) + + session.undo() + assertTrue(session.model.value.parameterTree.isEmpty(), "undo restores the group-less tree") + } + + /** The minted id skips ids already present. */ + @Test + fun freshIdAvoidsCollision() { + val existing = model(emptyList(), tree = listOf(group(ParameterGroupId("ParamGroup"), emptyList()), group(ParameterGroupId("ParamGroup2"), emptyList()))) + assertEquals(ParameterGroupId("ParamGroup3"), existing.freshParameterGroupId()) + } + + /** Delete unwraps: children splice to the root at the group's position; parameters and links untouched. */ + @Test + fun deleteSplicesChildrenToRootAtPosition() { + val links = listOf(ParameterLink(angleX, angleY)) + val tree = + listOf( + ParameterNode.Param(angleX), + group(ParameterGroupId("ParamGroup"), listOf(ParameterNode.Param(angleY))), + ) + val startModel = model(listOf(parameter(angleX), parameter(angleY)), links, tree) + val session = EditorSession(startModel) + session.deleteParameterGroup(ParameterGroupId("ParamGroup")) + + val newModel = session.model.value + assertEquals(listOf(angleX, angleY), newModel.parameterTree.filterIsInstance().map { it.id }) + assertTrue(newModel.parameterTree.none { it is ParameterNode.Group }, "the group node is gone") + assertSame(startModel.parameters, newModel.parameters, "the axis list is untouched") + assertSame(startModel.parameterLinks, newModel.parameterLinks, "the links are untouched") + + session.undo() + assertTrue(session.model.value.parameterTree.any { it is ParameterNode.Group }, "undo restores the group") + } + + /** Rename changes the name; a blank rename is a no-op. */ + @Test + fun renameChangesNameAndBlankIsNoOp() { + val groupId = ParameterGroupId("ParamGroup") + val startModel = model(emptyList(), tree = listOf(group(groupId, emptyList()))) + val renamed = startModel.withParameterGroupRenamed(groupId, " Eyes ") + assertEquals("Eyes", (renamed.parameterTree.single() as ParameterNode.Group).name) + + assertSame(startModel, startModel.withParameterGroupRenamed(groupId, " "), "a blank rename is a no-op") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterSelectionTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterSelectionTest.kt new file mode 100644 index 0000000..7034845 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterSelectionTest.kt @@ -0,0 +1,135 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the keyform-authoring target: which parameter an insert would write a key on. + * + * It lives on the session rather than a panel's view state because it is SHARED - a keyform sheet in one + * area has to follow the parameter picked in a parameters panel in another - and it rides the undo stack + * like the object and mesh selections, so undoing back across a keyform edit restores the target that edit + * was made against. + */ +class ParameterSelectionTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f) + + private fun session(ids: List): EditorSession = + EditorSession( + PuppetModel( + parameters = ids.map { id -> parameter(id) }, + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + + /** Nothing is targeted until the user picks something - a fresh document keys nowhere. */ + @Test + fun startsEmpty() { + assertTrue(session(listOf(angleX)).parameterSelection.value.isEmpty) + assertNull(session(listOf(angleX)).parameterSelection.value.active) + } + + /** Picking a parameter targets it, and the pick is its own undo step. */ + @Test + fun selectingIsItsOwnUndoStep() { + val editorSession = session(listOf(angleX, angleY)) + editorSession.setParameterSelection(ParameterSelection.of(angleX)) + assertEquals(angleX, editorSession.parameterSelection.value.active) + + editorSession.setParameterSelection(ParameterSelection.of(angleY)) + assertEquals(angleY, editorSession.parameterSelection.value.active) + + editorSession.undo() + assertEquals(angleX, editorSession.parameterSelection.value.active, "undo restores the previous target") + editorSession.redo() + assertEquals(angleY, editorSession.parameterSelection.value.active) + } + + /** Re-picking the same target records nothing, so repeated clicks do not pile up undo steps. */ + @Test + fun reselectingTheSameTargetIsANoOp() { + val editorSession = session(listOf(angleX)) + editorSession.setParameterSelection(ParameterSelection.of(angleX)) + val stepsAfterFirst = editorSession.historyView.value.steps.size + editorSession.setParameterSelection(ParameterSelection.of(angleX)) + assertEquals(stepsAfterFirst, editorSession.historyView.value.steps.size) + } + + /** Toggling extends and contracts the set, keeping the active member inside it. */ + @Test + fun togglingExtendsAndContracts() { + val both = ParameterSelection.of(angleX).toggled(angleY) + assertEquals(setOf(angleX, angleY), both.ids) + assertEquals(angleY, both.active, "the newly added member becomes active") + + val backToOne = both.toggled(angleY) + assertEquals(setOf(angleX), backToOne.ids) + assertEquals(angleX, backToOne.active, "the active target stays inside the set") + } + + /** + * Deleting a parameter drops it from the target, so an insert can never aim at an id the model no + * longer has. This is the one way the two could silently diverge - the target is session state, the + * parameter list is document state, and only the delete path touches both. + */ + @Test + fun deletingAParameterPrunesTheTarget() { + val editorSession = session(listOf(angleX, angleY)) + editorSession.setParameterSelection(ParameterSelection(setOf(angleX, angleY), angleY)) + + editorSession.deleteParameter(angleY) + + val target = editorSession.parameterSelection.value + assertFalse(angleY in target, "the deleted parameter is no longer targeted") + assertEquals(setOf(angleX), target.ids) + assertEquals(angleX, target.active, "the active target falls back to a surviving member") + } + + /** + * The prune rides INSIDE the delete's history entry: redo (or a History jump to the entry) restores + * the pruned target, never the dangling id the panel recorded before the delete. + */ + @Test + fun redoOfADeleteRestoresThePrunedTarget() { + val editorSession = session(listOf(angleX, angleY)) + editorSession.setParameterSelection(ParameterSelection(setOf(angleX, angleY), angleY)) + + editorSession.deleteParameter(angleY) + editorSession.undo() + assertTrue(editorSession.model.value.parameters.any { it.id == angleY }, "undo restores the parameter") + editorSession.redo() + + val target = editorSession.parameterSelection.value + assertFalse(angleY in target, "redo restores the pruned target, not the dangling id") + assertEquals(angleX, target.active) + } + + /** The unlink's narrowing rides its history entry the same way, so redo cannot restore the pad target. */ + @Test + fun redoOfAnUnlinkRestoresTheNarrowedTarget() { + val editorSession = session(listOf(angleX, angleY)) + editorSession.setParameterLink(angleX, angleY, true) + editorSession.setParameterSelection(ParameterSelection(setOf(angleX, angleY), angleX)) + + editorSession.setParameterLink(angleX, angleY, false) + assertEquals(setOf(angleX), editorSession.parameterSelection.value.ids, "the target narrows on unlink") + + editorSession.undo() + editorSession.redo() + assertEquals(setOf(angleX), editorSession.parameterSelection.value.ids, "redo restores the narrowed target") + assertEquals(angleX, editorSession.parameterSelection.value.active) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterTreeEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterTreeEditsTest.kt new file mode 100644 index 0000000..153bdb5 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ParameterTreeEditsTest.kt @@ -0,0 +1,186 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the pure parameter-tree move surgery: reorder within the root, move a parameter into / out of a + * group, reorder a group among root nodes, the atomic linked-pair move, materialize-on-empty, and the + * one-level and no-op refusals (which record no undo step). + */ +class ParameterTreeEditsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val angleZ = ParameterId("ParamAngleZ") + private val breath = ParameterId("ParamBreath") + private val groupA = ParameterGroupId("ParamGroup") + private val groupB = ParameterGroupId("ParamGroup2") + + /** An animatable parameter over -1..1. */ + private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f) + + /** + * A drawable-less model holding [parameters] and an optional group [tree]. + * + * @param List parameters The parameters (the id-keyed axis list). + * @param List tree The group tree (empty = the flat fallback). + * @return PuppetModel The fixture model. + */ + private fun model(parameters: List, tree: List = emptyList()): PuppetModel = + PuppetModel( + parameters = parameters, + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + parameterTree = tree, + ) + + /** The flat leaf-id sequence of a tree's root level (groups are not leaves). */ + private fun rootLeafIds(tree: List): List = + tree.filterIsInstance().map { leaf -> leaf.id } + + /** A group node with the given children. */ + private fun group(id: ParameterGroupId, children: List): ParameterNode.Group = + ParameterNode.Group(id, id.raw, initiallyOpen = true, children = children) + + /** Reordering within the root moves the leaf and leaves the others in place. */ + @Test + fun reorderWithinRoot() { + val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY), ParameterNode.Param(angleZ)) + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)), tree)) + session.moveParameterRow( + ParameterMoveSubject.Leaves(listOf(angleX)), + newParentGroupId = null, + before = ParameterNodeRef.Leaf(angleZ), + ) + assertEquals(listOf(angleY, angleX, angleZ), rootLeafIds(session.model.value.parameterTree)) + session.undo() + assertEquals(listOf(angleX, angleY, angleZ), rootLeafIds(session.model.value.parameterTree)) + } + + /** Moving a root leaf into a group re-homes it as that group's child and removes it from the root. */ + @Test + fun moveLeafIntoGroup() { + val tree = listOf(ParameterNode.Param(angleX), group(groupA, listOf(ParameterNode.Param(angleY)))) + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)), tree)) + session.moveParameterRow(ParameterMoveSubject.Leaves(listOf(angleX)), newParentGroupId = groupA, before = null) + val newTree = session.model.value.parameterTree + assertTrue(rootLeafIds(newTree).isEmpty(), "the leaf left the root") + val destination = newTree.filterIsInstance().single() + assertEquals(listOf(angleY, angleX), destination.children.filterIsInstance().map { it.id }) + } + + /** Moving a group child out to the root inserts it at the chosen root position. */ + @Test + fun moveLeafOutToRoot() { + val tree = listOf(group(groupA, listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY)))) + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY)), tree)) + session.moveParameterRow( + ParameterMoveSubject.Leaves(listOf(angleX)), + newParentGroupId = null, + before = ParameterNodeRef.Group(groupA), + ) + val newTree = session.model.value.parameterTree + assertEquals(listOf(angleX), rootLeafIds(newTree), "the leaf is now a root sibling before the group") + val remaining = newTree.filterIsInstance().single() + assertEquals(listOf(angleY), remaining.children.filterIsInstance().map { it.id }) + } + + /** A group reorders among root nodes, carrying its children. */ + @Test + fun reorderGroupAmongRootNodes() { + val tree = + listOf( + ParameterNode.Param(angleX), + group(groupA, listOf(ParameterNode.Param(angleY))), + ParameterNode.Param(angleZ), + ) + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ)), tree)) + session.moveParameterRow( + ParameterMoveSubject.Group(groupA), + newParentGroupId = null, + before = ParameterNodeRef.Leaf(angleX), + ) + val newTree = session.model.value.parameterTree + assertTrue(newTree.first() is ParameterNode.Group, "the group leads the root now") + assertEquals(groupA, (newTree.first() as ParameterNode.Group).id) + assertEquals(listOf(angleX, angleZ), rootLeafIds(newTree)) + } + + /** A linked pair moves as one contiguous run, keeping horizontal-then-vertical order. */ + @Test + fun pairMoveKeepsLeavesAdjacent() { + val tree = + listOf( + ParameterNode.Param(angleX), + ParameterNode.Param(angleY), + ParameterNode.Param(angleZ), + ParameterNode.Param(breath), + ) + val session = EditorSession(model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ), parameter(breath)), tree)) + // angleY (horizontal) + angleZ (vertical) are a linked pad; move them to the front. + session.moveParameterRow( + ParameterMoveSubject.Leaves(listOf(angleY, angleZ)), + newParentGroupId = null, + before = ParameterNodeRef.Leaf(angleX), + ) + assertEquals(listOf(angleY, angleZ, angleX, breath), rootLeafIds(session.model.value.parameterTree)) + } + + /** A group-less model materializes a flat tree on the first real move; a no-op leaves the tree empty. */ + @Test + fun materializeOnEmptyTreeThenMove() { + val base = model(listOf(parameter(angleX), parameter(angleY), parameter(angleZ))) + val moved = + base.withParameterRowMoved( + ParameterMoveSubject.Leaves(listOf(angleX)), + newParentGroupId = null, + before = ParameterNodeRef.Leaf(angleZ), + ) + assertEquals(listOf(angleY, angleX, angleZ), rootLeafIds(moved.parameterTree), "the flat tree materialized and the move applied") + + // A move that changes nothing must not materialize a tree - the model stays group-less. + val noOp = + base.withParameterRowMoved( + ParameterMoveSubject.Leaves(listOf(angleX)), + newParentGroupId = null, + before = ParameterNodeRef.Leaf(angleY), + ) + assertSame(base, noOp) + assertTrue(noOp.parameterTree.isEmpty()) + } + + /** A group cannot be dropped inside another group (one level only) - same instance, no step. */ + @Test + fun refusesGroupUnderGroup() { + val tree = listOf(group(groupA, emptyList()), group(groupB, emptyList())) + val session = EditorSession(model(emptyList(), tree)) + session.moveParameterRow(ParameterMoveSubject.Group(groupA), newParentGroupId = groupB, before = null) + assertFalse(session.canUndo.value, "a refused move records no undo step") + assertEquals(tree, session.model.value.parameterTree) + } + + /** A move that changes nothing returns the same instance. */ + @Test + fun noOpReturnsSameInstance() { + val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(angleY)) + val base = model(listOf(parameter(angleX), parameter(angleY)), tree) + val result = + base.withParameterRowMoved( + ParameterMoveSubject.Leaves(listOf(angleX)), + newParentGroupId = null, + before = ParameterNodeRef.Leaf(angleY), + ) + assertSame(base, result) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/PendingChannelEditTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/PendingChannelEditTest.kt new file mode 100644 index 0000000..e99aa4f --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/PendingChannelEditTest.kt @@ -0,0 +1,146 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the unkeyed-edit buffer: a value typed into a keyed property but not yet keyed. + * + * The behaviour it encodes is Blender's, and the discarding is the point rather than a shortcoming - a + * pending value was chosen FOR a pose, so carrying it to a different one would apply an edit somewhere it + * was never meant. What must never happen is a pending edit surviving into the undo history, which would + * bury the real edits under a step per keystroke. + */ +class PendingChannelEditTest { + private val angleX = ParameterId("ParamAngleX") + private val drawableId = DrawableId("d") + private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY) + + private fun session(): EditorSession = + EditorSession( + PuppetModel( + parameters = listOf(Parameter(angleX, angleX.raw, min = -30f, max = 30f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + opacity = 0.25f, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + + /** A pending edit is held for reading but records no history step and no model change. */ + @Test + fun aPendingEditIsTransient() { + val editorSession = session() + val stepsBefore = editorSession.historyView.value.steps.size + val modelBefore = editorSession.model.value + + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + + assertEquals(ChannelValue.Scalar(0.75f), editorSession.pendingChannelEdits.value[target]) + assertEquals(stepsBefore, editorSession.historyView.value.steps.size, "no undo step is recorded") + assertTrue(modelBefore === editorSession.model.value, "the document is untouched") + assertTrue(!editorSession.dirty.value, "an unkeyed edit does not dirty the document") + } + + /** Moving the pose discards it - the value was chosen for the pose being left. */ + @Test + fun aPoseMoveDiscardsIt() { + val editorSession = session() + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f)) + + assertTrue(editorSession.pendingChannelEdits.value.isEmpty(), "the pending edit did not survive the scrub") + } + + /** A history jump lands on a pose the pending value was never chosen for, so it goes too. */ + @Test + fun anUndoDiscardsIt() { + val editorSession = session() + editorSession.commitPose(ParameterChange.SetValue(listOf(angleX)), mapOf(angleX to 15f)) + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + + editorSession.undo() + + assertTrue(editorSession.pendingChannelEdits.value.isEmpty()) + } + + /** Capturing consumes it: the captured key holds the typed value, and nothing stays pending. */ + @Test + fun capturingConsumesIt() { + val editorSession = session() + val parameter = editorSession.model.value.parameters.single() + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + + val pending = editorSession.pendingChannelEdits.value.getValue(target) + editorSession.captureChannelKey(target, parameter, pending) + editorSession.clearPendingChannelEdits() + + assertTrue(editorSession.pendingChannelEdits.value.isEmpty()) + assertTrue(editorSession.model.value.isChannelKeyedOn(target, angleX), "the channel is now keyed") + assertEquals( + ChannelValue.Scalar(0.75f), + editorSession.model.value.channelValueAt(target, editorSession.pose.value), + "the key holds the value that was typed, not the value that was stored", + ) + } + + /** Several properties can be pending at once, each keyed independently. */ + @Test + fun severalTargetsCanBePendingAtOnce() { + val editorSession = session() + val multiplyTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR) + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + editorSession.setPendingChannelEdit(multiplyTarget, ChannelValue.Color(org.umamo.runtime.model.ColorRgb(1f, 0f, 0f))) + + assertEquals(2, editorSession.pendingChannelEdits.value.size) + } + + /** + * Capturing one target consumes only ITS pending edit: the pose did not move, so every other target's + * typed value is still the value its user chose and must survive for its own insert. + */ + @Test + fun capturingOneTargetKeepsOthersPending() { + val editorSession = session() + val parameter = editorSession.model.value.parameters.single() + val multiplyTarget = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR) + val multiplyValue = ChannelValue.Color(org.umamo.runtime.model.ColorRgb(1f, 0f, 0f)) + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.75f)) + editorSession.setPendingChannelEdit(multiplyTarget, multiplyValue) + + val pending = editorSession.pendingChannelEdits.value.getValue(target) + editorSession.captureChannelKey(target, parameter, pending) + editorSession.clearPendingChannelEdit(target) + + assertEquals( + mapOf(multiplyTarget to multiplyValue), + editorSession.pendingChannelEdits.value, + "the uncaptured target's typed value survives", + ) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/PropertyScalarEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/PropertyScalarEditsTest.kt new file mode 100644 index 0000000..df80ddf --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/PropertyScalarEditsTest.kt @@ -0,0 +1,496 @@ +package org.umamo.edit + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.multiplyColor +import org.umamo.runtime.model.opacity +import org.umamo.runtime.model.screenColor +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the scalar property edits behind the Properties panel: each PuppetModelEdits builder round-trips + * its field and returns the SAME instance on a no-op (unchanged value or a missing id), the deformer + * builders guard on kind (base angle only on Rotation, quad transform only on Warp), the part group-mode + * builder carries a whole Isolated composite, and a session setter commits exactly one undo step (or + * nothing when it is a no-op). + */ +class PropertyScalarEditsTest { + private val drawableId = DrawableId("d") + private val rotationId = DeformerId("rot") + private val warpId = DeformerId("warp") + private val partId = PartId("p") + + private val drawable = + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + private val rotation = + Deformer.Rotation(id = rotationId, name = "rot", parent = null, partId = null, baseAngle = 0f, geometryGrid = null) + + private val warp = + Deformer.Warp( + id = warpId, + name = "warp", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = false, + geometryGrid = null, + ) + + private val part = Part(partId, "p", children = emptyList()) + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(part), + deformers = listOf(rotation, warp), + drawables = listOf(drawable), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 200f, + worldOriginX = 50f, + worldOriginZ = 100f, + ) + + @Test + fun drawableScalarBuildersRoundTripAndNoOp() { + val base = model() + + assertEquals(BlendMode.Multiply, base.withDrawableBlendMode(drawableId, BlendMode.Multiply).drawables.first().blendMode) + assertEquals(AlphaBlendMode.Atop, base.withDrawableAlphaBlendMode(drawableId, AlphaBlendMode.Atop).drawables.first().alphaBlendMode) + assertTrue(base.withDrawableCulling(drawableId, true).drawables.first().culling) + assertTrue(base.withDrawableInvertMask(drawableId, true).drawables.first().invertMask) + + // Unchanged value and missing id are both no-ops (same instance). + assertSame(base, base.withDrawableBlendMode(drawableId, BlendMode.Normal)) + assertSame(base, base.withDrawableCulling(drawableId, false)) + assertSame(base, base.withDrawableInvertMask(DrawableId("missing"), true)) + } + + @Test + fun deformerBaseAngleOnlyAffectsRotation() { + val base = model() + + val edited = base.withDeformerBaseAngle(rotationId, 45f) + assertEquals(45f, (edited.deformers.first { it.id == rotationId } as Deformer.Rotation).baseAngle) + + // A warp has no base angle, and an unchanged angle is a no-op. + assertSame(base, base.withDeformerBaseAngle(warpId, 45f)) + assertSame(base, base.withDeformerBaseAngle(rotationId, 0f)) + } + + @Test + fun deformerQuadTransformOnlyAffectsWarp() { + val base = model() + + val edited = base.withDeformerQuadTransform(warpId, true) + assertTrue((edited.deformers.first { it.id == warpId } as Deformer.Warp).isQuadTransform) + + // A rotation has no lattice, and an unchanged flag is a no-op. + assertSame(base, base.withDeformerQuadTransform(rotationId, true)) + assertSame(base, base.withDeformerQuadTransform(warpId, false)) + } + + @Test + fun partScalarBuildersRoundTripAndNoOp() { + val base = model() + + assertTrue(base.withPartSketch(partId, true).parts.first().isSketch) + assertEquals(700, base.withPartDrawOrder(partId, 700).parts.first().drawOrder) + + assertSame(base, base.withPartSketch(partId, false)) + assertSame(base, base.withPartDrawOrder(partId, 500)) + } + + @Test + fun partCompositeIsStoredAndSurvivesModeRoundTrip() { + val base = model() + val custom = PartComposite(opacity = 0.5f) + + // The composite is stored on the part independent of the mode. + val withComposite = base.withPartComposite(partId, custom) + assertEquals(custom, withComposite.parts.first().composite) + // Only applied while Isolated: activeComposite is null until the mode is Isolated. + assertEquals(null, withComposite.parts.first().activeComposite) + + val isolated = withComposite.withPartGroupMode(partId, PartGroupMode.Isolated) + assertEquals(custom, isolated.parts.first().activeComposite) + + // Leaving and re-entering Isolated does NOT reset the composite (the whole point). + val roundTripped = + isolated + .withPartGroupMode(partId, PartGroupMode.PassThrough) + .withPartGroupMode(partId, PartGroupMode.Isolated) + assertEquals(custom, roundTripped.parts.first().composite) + assertEquals(custom, roundTripped.parts.first().activeComposite) + + // No-op composite / mode edits return the same instance. + assertSame(withComposite, withComposite.withPartComposite(partId, custom)) + assertSame(base, base.withPartGroupMode(partId, PartGroupMode.PassThrough)) + } + + /** + * The part in the org tree (so deriveRenderRoot emits a RenderGroup for it), Isolated by default so + * its composite resolves onto the group, with a freshly derived renderRoot. + */ + private fun modelWithPartInTree(groupMode: PartGroupMode = PartGroupMode.Isolated): PuppetModel = + model() + .copy(parts = listOf(part.copy(groupMode = groupMode)), rootChildren = listOf(OrgChild.Part(partId))) + .withDerivedRenderRoot() + + /** The derived render group owning [id], or null when the part is not a render-tree boundary. */ + private fun groupFor(model: PuppetModel, id: PartId): RenderGroup? { + fun search(node: RenderNode): RenderGroup? { + if (node !is RenderGroup) { + return null + } + if (node.partId == id) { + return node + } + for (child in node.children) { + search(child)?.let { return it } + } + return null + } + return search(model.renderRoot) + } + + @Test + fun partCompositeEditsReDeriveTheRenderRoot() { + // The renderer reads composite/draw-order/group structure from renderRoot, not from parts, so a + // composite property edit that does not re-derive renderRoot never reaches the viewport (the bug + // this pins): resolvedComposite bakes the composite into RenderGroup.composite at derive time. + val base = modelWithPartInTree() + assertEquals(PartComposite(), groupFor(base, partId)?.composite) + + val edited = base.withPartComposite(partId, PartComposite(opacity = 0.5f)) + assertEquals(0.5f, groupFor(edited, partId)?.composite?.opacity) + + // A part draw-order edit updates the group's sort key in the render tree. + assertEquals(700, groupFor(base.withPartDrawOrder(partId, 700), partId)?.drawOrder) + + // PassThrough removes the group boundary entirely (its children hoist into the enclosing group). + assertEquals(null, groupFor(base.withPartGroupMode(partId, PartGroupMode.PassThrough), partId)) + } + + /** + * The 5.3 per-art-mesh tint is now a STATIC channel value, so the builders write one field instead of + * rewriting every keyform cell. + * + * That is the point of the split: the old builder flattened any authored per-keyform color animation + * and, by replacing the grid, tripped the renderer's identity check into re-uploading geometry for a + * color change. Neither is possible now - the color never touches the geometry grid. + */ + @Test + fun drawableColorBuildersWriteTheStaticAndNoOp() { + val base = model().copy(drawables = listOf(drawable)) + val red = ColorRgb(1f, 0f, 0f) + + val tinted = base.withDrawableMultiplyColor(drawableId, red) + assertEquals(red, tinted.drawables.first().multiplyColor, "the static multiply color is set") + assertSame( + base.drawables.first().geometryGrid, + tinted.drawables.first().geometryGrid, + "a color edit leaves the geometry grid untouched by identity, so no re-upload is triggered", + ) + + // Already-set and missing-id are no-ops (same instance). + assertSame(tinted, tinted.withDrawableMultiplyColor(drawableId, red)) + assertSame(base, base.withDrawableMultiplyColor(drawableId, ColorRgb.MultiplyIdentity)) + assertSame(base, base.withDrawableScreenColor(DrawableId("missing"), ColorRgb.ScreenIdentity)) + } + + @Test + fun canvasAndOriginBuildersRoundTripAndNoOp() { + val base = model() + + assertEquals(300f, base.withCanvasSize(300f, 400f).canvasWidth) + assertEquals(400f, base.withCanvasSize(300f, 400f).canvasHeight) + assertEquals(7f, base.withWorldOrigin(7f, 8f).worldOriginX) + + assertSame(base, base.withCanvasSize(100f, 200f)) + assertSame(base, base.withWorldOrigin(50f, 100f)) + } + + @Test + fun sessionEditIsOneUndoStepThatDirtiesAndReverses() { + val session = EditorSession(model()) + assertFalse(session.canUndo.value) + + session.setDrawableCulling(drawableId, true) + + assertTrue(session.canUndo.value) + assertTrue(session.dirty.value) + assertTrue(session.model.value.drawables.first().culling) + + session.undo() + assertFalse(session.canUndo.value) + assertFalse(session.model.value.drawables.first().culling) + } + + @Test + fun sessionNoOpEditRecordsNothing() { + val session = EditorSession(model()) + + // The drawable is already Normal, so this edit changes nothing. + session.setDrawableBlendMode(drawableId, BlendMode.Normal) + + assertFalse(session.canUndo.value) + assertFalse(session.dirty.value) + } + + @Test + fun sessionGroupModeAndCanvasEditsCommit() { + val session = EditorSession(model()) + + session.setPartGroupMode(partId, PartGroupMode.Grouped) + assertEquals(PartGroupMode.Grouped, session.model.value.parts.first().groupMode) + + session.setCanvasSize(640f, 480f) + assertEquals(640f, session.model.value.canvasWidth) + + // Two distinct edits, so two undo steps back to the original. + session.undo() + session.undo() + assertEquals(PartGroupMode.PassThrough, session.model.value.parts.first().groupMode) + assertEquals(100f, session.model.value.canvasWidth) + } + + @Test + fun sessionRuntimeTargetEditCommitsUndoesAndNoOps() { + val session = EditorSession(model()) + + session.setRuntimeTarget(RuntimeTarget.Cubism50) + assertEquals(RuntimeTarget.Cubism50, session.model.value.runtimeTarget) + assertTrue(session.dirty.value, "a target change is document content, so it dirties") + assertEquals("change.document.runtimeTarget", DocumentChange.SetRuntimeTarget(RuntimeTarget.Cubism50).labelKey) + + session.undo() + assertEquals(RuntimeTarget.NoTarget, session.model.value.runtimeTarget) + assertFalse(session.dirty.value, "undo restores the saved model instance") + + // The target is already NoTarget, so this edit changes nothing. + session.setRuntimeTarget(RuntimeTarget.NoTarget) + assertFalse(session.canUndo.value) + assertFalse(session.dirty.value) + } + + /** The display mode is document content: one undo step, dirties, and a no-op change records nothing. */ + @Test + fun sessionSetSourceLayerDisplayCommitsOneStep() { + val session = EditorSession(model()) + assertFalse(session.model.value.rendersFromSourceLayers, "documents display from the atlas by default") + + session.setSourceLayerDisplay(true) + assertTrue(session.model.value.rendersFromSourceLayers) + assertTrue(session.dirty.value, "a display-mode change is document content, so it dirties") + assertEquals("change.document.sourceLayerDisplay", DocumentChange.SetSourceLayerDisplay(true).labelKey) + + session.undo() + assertFalse(session.model.value.rendersFromSourceLayers) + assertFalse(session.dirty.value, "undo restores the saved model instance") + + // Already displaying from the atlas, so this edit changes nothing. + session.setSourceLayerDisplay(false) + assertFalse(session.canUndo.value) + assertFalse(session.dirty.value) + } + + /** + * Packing art at a new spot is one undo step, and the coordinates over it follow. + * + * The mesh's uvs address the PAGE, so moving the art without moving them would silently re-point the + * mesh at whatever now sits at the old spot. Asserting the round trip - move, then move back - is + * what pins that: the coordinates must land where they started. + */ + @Test + fun sessionSetAtlasPlacementCommitsOneStepAndCarriesTheCoordinates() { + val tileId = AtlasTileId("tile0") + val original = AtlasPlacement(0, 0f, 0f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f) + val moved = AtlasPlacement(0, 32f, 16f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f) + val meshed = + drawable.copy( + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 1f), floatArrayOf(0f, 0f, 0.25f, 0.5f), intArrayOf(0, 0, 0)), + atlasTileId = tileId, + ) + val packed = + model().copy( + drawables = listOf(meshed), + atlas = + PuppetAtlas( + pages = listOf(AtlasPage(64, 64)), + tiles = listOf(AtlasTile(tileId, "Art", 16, 16, original)), + ), + ) + val session = EditorSession(packed) + val storedBefore = session.model.value.drawables.single().mesh!!.uvs.copyOf() + + session.setAtlasPlacement(tileId, moved) + assertEquals(moved, session.model.value.atlas.tiles.single().placement, "the tile moved") + assertTrue(session.dirty.value, "a pack is document content, so it dirties") + assertEquals("change.document.atlasPlacement", DocumentChange.SetAtlasPlacement(listOf(tileId)).labelKey) + assertFalse( + session.model.value.drawables.single().mesh!!.uvs.contentEquals(storedBefore), + "the stored coordinates followed the art rather than staying put", + ) + + session.setAtlasPlacement(tileId, original) + assertContentEquals( + storedBefore, + session.model.value.drawables.single().mesh!!.uvs, + "moving the art back restores the coordinates it started with", + ) + + session.undo() + session.undo() + assertEquals(original, session.model.value.atlas.tiles.single().placement) + assertFalse(session.dirty.value, "undo restores the saved model instance") + + // The tile is already there, so this edit changes nothing. + session.setAtlasPlacement(tileId, original) + assertFalse(session.canUndo.value) + + // An unknown tile is refused rather than half-applied. + session.setAtlasPlacement(AtlasTileId("gone"), moved) + assertFalse(session.canUndo.value) + } + + @Test + fun sessionSetPartCompositeCommitsOneStep() { + val session = EditorSession(model()) + val custom = PartComposite(opacity = 0.25f) + + session.setPartComposite(partId, custom) + assertEquals(custom, session.model.value.parts.first().composite) + + session.undo() + assertEquals(PartComposite(), session.model.value.parts.first().composite) + } + + /** The drawable's new scalar statics round-trip, and refuse a no-op the same way the others do. */ + @Test + fun drawableScalarChannelBuildersWriteTheStaticAndNoOp() { + val base = model() + val faded = base.withDrawableOpacity(drawableId, 0.25f) + assertEquals(0.25f, faded.drawables.first().opacity) + val reordered = base.withDrawableDrawOrder(drawableId, 720f) + assertEquals(720f, reordered.drawables.first().drawOrder) + + assertSame(base, base.withDrawableOpacity(drawableId, 1f), "the default opacity is already 1") + assertSame(base, base.withDrawableDrawOrder(DrawableId("missing"), 720f)) + assertSame( + base.drawables.first().geometryGrid, + faded.drawables.first().geometryGrid, + "a scalar-static edit leaves the geometry grid untouched by identity, so no re-upload is triggered", + ) + } + + /** + * A drawable's draw order does NOT re-derive the render root, unlike a part's. + * + * A part's draw order is baked into the derived group tree; a drawable's is resolved per pose at render + * time as its channel's static, so re-deriving would be work with no output. + */ + @Test + fun drawableDrawOrderLeavesTheRenderRootAlone() { + val base = model() + val reordered = base.withDrawableDrawOrder(drawableId, 720f) + assertSame(base.renderRoot, reordered.renderRoot) + } + + /** The deformer render statics round-trip on BOTH subtypes and refuse a no-op. */ + @Test + fun deformerRenderStaticBuildersCoverBothSubtypes() { + val base = model() + for (id in listOf(rotationId, warpId)) { + val faded = base.withDeformerOpacity(id, 0.5f) + assertEquals(0.5f, faded.deformerNamed(id).opacity, "opacity on $id") + val tinted = base.withDeformerMultiplyColor(id, ColorRgb(0.5f, 0.5f, 0.5f)) + assertEquals(ColorRgb(0.5f, 0.5f, 0.5f), tinted.deformerNamed(id).multiplyColor, "multiply on $id") + val screened = base.withDeformerScreenColor(id, ColorRgb(0.25f, 0f, 0f)) + assertEquals(ColorRgb(0.25f, 0f, 0f), screened.deformerNamed(id).screenColor, "screen on $id") + + assertSame(base, base.withDeformerOpacity(id, 1f), "the default opacity is already 1") + } + assertSame(base, base.withDeformerOpacity(DeformerId("missing"), 0.5f)) + } + + /** The flip flags exist only on a rotation deformer; a warp refuses them. */ + @Test + fun deformerFlipsOnlyAffectRotation() { + val base = model() + val flipped = base.withDeformerFlipX(rotationId, true) + assertEquals(true, (flipped.deformers.first { it.id == rotationId } as Deformer.Rotation).flipX) + val flippedY = base.withDeformerFlipY(rotationId, true) + assertEquals(true, (flippedY.deformers.first { it.id == rotationId } as Deformer.Rotation).flipY) + + assertSame(base, base.withDeformerFlipX(warpId, true), "a warp has no reflection") + assertSame(base, base.withDeformerFlipY(warpId, true), "a warp has no reflection") + assertSame(base, base.withDeformerFlipX(rotationId, false), "already false") + } + + /** Each new session setter is one undo step that reverses cleanly. */ + @Test + fun newSessionSettersAreOneUndoStepEach() { + val session = EditorSession(model()) + session.setDrawableOpacity(drawableId, 0.25f) + session.setDeformerOpacity(rotationId, 0.5f) + session.setDeformerFlipX(rotationId, true) + assertEquals(0.25f, session.model.value.drawables.first().opacity) + assertEquals(0.5f, session.model.value.deformerNamed(rotationId).opacity) + + session.undo() + session.undo() + session.undo() + assertEquals(1f, session.model.value.drawables.first().opacity) + assertEquals(1f, session.model.value.deformerNamed(rotationId).opacity) + } + + /** A no-op setter records nothing, so an unchanged value cannot pad the history. */ + @Test + fun newSessionNoOpSettersRecordNothing() { + val session = EditorSession(model()) + session.setDrawableOpacity(drawableId, 1f) + session.setDeformerFlipX(warpId, true) + assertEquals(false, session.canUndo.value) + } + + /** The deformer with [id], for reading a static through the sealed-type accessors. */ + private fun PuppetModel.deformerNamed(id: DeformerId): Deformer = deformers.first { candidate -> candidate.id == id } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/ProportionalEditingTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/ProportionalEditingTest.kt new file mode 100644 index 0000000..8cf9d98 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/ProportionalEditingTest.kt @@ -0,0 +1,120 @@ +package org.umamo.edit + +import kotlin.math.sqrt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +// Tests for the proportional-editing math: the falloff curves and the per-mesh weight map. + +class ProportionalEditingTest { + private val allFalloffs = ProportionalFalloff.entries + + @Test + fun everyFalloffIsFullAtZeroAndZeroAtRadiusEdge() { + for (falloff in allFalloffs) { + assertEquals(1f, proportionalWeight(falloff, 0f), "$falloff at distance 0") + assertEquals(0f, proportionalWeight(falloff, 1f), "$falloff at the radius edge") + assertEquals(0f, proportionalWeight(falloff, 1.5f), "$falloff beyond the radius") + assertEquals(1f, proportionalWeight(falloff, -0.5f), "$falloff clamps negative distances to full weight") + } + } + + @Test + fun falloffCurvesMatchTheirFormulasAtMidpoint() { + // fade = 0.5 at the midpoint; each curve's closed form evaluated by hand. + assertEquals(0.5f, proportionalWeight(ProportionalFalloff.Smooth, 0.5f), 1e-6f, "smoothstep is 0.5 at its midpoint") + assertEquals(sqrt(0.75f), proportionalWeight(ProportionalFalloff.Sphere, 0.5f), 1e-6f, "sphere is sqrt(1 - 0.25)") + assertEquals(sqrt(0.5f), proportionalWeight(ProportionalFalloff.Root, 0.5f), 1e-6f, "root is sqrt(fade)") + assertEquals(0.25f, proportionalWeight(ProportionalFalloff.Sharp, 0.5f), 1e-6f, "sharp is fade squared") + assertEquals(0.5f, proportionalWeight(ProportionalFalloff.Linear, 0.5f), 1e-6f, "linear is fade") + assertEquals(1f, proportionalWeight(ProportionalFalloff.Constant, 0.5f), "constant is full inside the radius") + } + + @Test + fun everyFalloffIsMonotonicallyNonIncreasing() { + val sampleCount = 20 + for (falloff in allFalloffs) { + var previousWeight = proportionalWeight(falloff, 0f) + for (sampleIndex in 1..sampleCount) { + val weight = proportionalWeight(falloff, sampleIndex / sampleCount.toFloat()) + assertTrue(weight <= previousWeight + 1e-6f, "$falloff must not increase with distance (sample $sampleIndex)") + previousWeight = weight + } + } + } + + // A horizontal strip of vertices spaced 10 units apart: (0,0), (10,0), (20,0), (30,0), (40,0). + private val stripPositions = floatArrayOf(0f, 0f, 10f, 0f, 20f, 0f, 30f, 0f, 40f, 0f) + + @Test + fun weightsExcludeCoveredVerticesAndThoseOutsideTheRadius() { + val weights = proportionalWeights(stripPositions, setOf(0), radiusWorld = 25f, falloff = ProportionalFalloff.Linear) + assertFalse(0 in weights, "the covered vertex moves at full strength through its pivot group, not the weight map") + assertEquals(setOf(1, 2), weights.keys, "only the vertices strictly inside the radius take a weight") + } + + @Test + fun weightsMeasureDistanceToTheNearestCoveredVertex() { + // Covering both ends, the middle vertex is 20 from either end; the second and fourth are 10 from + // their nearer end - the nearest covered vertex, not the first one iterated. + val weights = proportionalWeights(stripPositions, setOf(0, 4), radiusWorld = 25f, falloff = ProportionalFalloff.Linear) + assertEquals(1f - 10f / 25f, weights.getValue(1), 1e-6f, "vertex 1 is 10 from covered vertex 0") + assertEquals(1f - 20f / 25f, weights.getValue(2), 1e-6f, "vertex 2 is 20 from either covered end") + assertEquals(1f - 10f / 25f, weights.getValue(3), 1e-6f, "vertex 3 is 10 from covered vertex 4") + } + + @Test + fun weightsAreEmptyWithNoCoverageOrNoRadius() { + assertTrue(proportionalWeights(stripPositions, emptySet(), 25f, ProportionalFalloff.Smooth).isEmpty()) + assertTrue(proportionalWeights(stripPositions, setOf(0), 0f, ProportionalFalloff.Smooth).isEmpty()) + } + + @Test + fun influencesCarryTheNearestCoveredVertexIdentity() { + // The identity is the Individual Origins ownership key: vertex 1 belongs with covered end 0, + // vertex 3 with covered end 4 (each measured to its NEARER end). + val influences = proportionalInfluences(stripPositions, setOf(0, 4), radiusWorld = 25f, falloff = ProportionalFalloff.Linear) + assertEquals(0, influences.getValue(1).nearestCoveredIndex, "vertex 1's nearest covered vertex is 0") + assertEquals(4, influences.getValue(3).nearestCoveredIndex, "vertex 3's nearest covered vertex is 4") + assertEquals(1f - 10f / 25f, influences.getValue(1).weight, 1e-6f, "the weight rides along unchanged") + } + + @Test + fun connectedOnlyMeasuresAlongEdgesAndSkipsUnreachableIslands() { + // A bent sheet: 0=(0,0), 1=(0,4), 2=(3,0), 3=(3,4); triangles (0,1,2) and (1,2,3). Vertex 3 is + // 5 from vertex 0 straight-line but 7 along edges (0-1-3 or 0-2-3; there is no 0-3 edge). + val positions = floatArrayOf(0f, 0f, 0f, 4f, 3f, 0f, 3f, 4f) + val indices = intArrayOf(0, 1, 2, 1, 2, 3) + val straight = proportionalInfluences(positions, setOf(0), radiusWorld = 6f, falloff = ProportionalFalloff.Linear) + val connected = proportionalInfluencesConnected(positions, setOf(0), radiusWorld = 6f, falloff = ProportionalFalloff.Linear, triangleIndices = indices) + assertTrue(3 in straight, "straight-line influence reaches vertex 3 (distance 5, radius 6)") + assertFalse(3 in connected, "along edges vertex 3 is 7 away - outside the radius") + assertEquals(1f - 4f / 6f, connected.getValue(1).weight, 1e-6f, "a direct edge matches the straight-line distance") + assertEquals(0, connected.getValue(1).nearestCoveredIndex, "the geodesic source rides along") + + // A nearby-but-unconnected island takes no weight at ANY radius (the feature's point). + val twoIslands = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 5f, 0f, 7f, 0f, 5f, 2f) + val islandIndices = intArrayOf(0, 1, 2, 3, 4, 5) + val islandConnected = + proportionalInfluencesConnected(twoIslands, setOf(0), radiusWorld = 100f, falloff = ProportionalFalloff.Constant, triangleIndices = islandIndices) + assertEquals(setOf(1, 2), islandConnected.keys, "influence never leaps to the unconnected island") + } + + @Test + fun influencesPartitionByTheOwningPivotGroup() { + // Two single-vertex "islands" at the strip's ends: each influenced vertex must follow the group + // owning its nearest covered vertex, so the halos turn about their own island pivots. + val influences = proportionalInfluences(stripPositions, setOf(0, 4), radiusWorld = 25f, falloff = ProportionalFalloff.Linear) + val groups = + listOf( + TransformPivotGroup(setOf(0), pivotX = 0f, pivotY = 0f), + TransformPivotGroup(setOf(4), pivotX = 40f, pivotY = 0f), + ) + val partitions = TransformPivots.partitionInfluencesByGroup(influences, groups) + assertEquals(setOf(1, 2), partitions[0].keys, "vertices nearest end 0 follow the first island (2 ties to 0, iterated first)") + assertEquals(setOf(3), partitions[1].keys, "vertex 3 follows the second island") + assertEquals(influences.getValue(3).weight, partitions[1].getValue(3), "weights carry into the partitions") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/RelationEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/RelationEditsTest.kt new file mode 100644 index 0000000..c019d99 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/RelationEditsTest.kt @@ -0,0 +1,134 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the relation edits the Properties panel's pickers write through: each binds a flat cross-link field + * (no tree surgery), returns the SAME instance on a no-op (unchanged value or a missing id), works on both + * deformer subtypes, and commits exactly one undo step through its session op. + */ +class RelationEditsTest { + private val drawableId = DrawableId("d") + private val otherDrawableId = DrawableId("d2") + private val rotationId = DeformerId("rot") + private val warpId = DeformerId("warp") + private val partId = PartId("p") + + private fun drawable(id: DrawableId): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + private val rotation = + Deformer.Rotation(id = rotationId, name = "rot", parent = null, partId = null, baseAngle = 0f, geometryGrid = null) + + private val warp = + Deformer.Warp( + id = warpId, + name = "warp", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = false, + geometryGrid = null, + ) + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(Part(partId, "p", children = emptyList())), + deformers = listOf(rotation, warp), + drawables = listOf(drawable(drawableId), drawable(otherDrawableId)), + rootChildren = emptyList(), + rootPartId = null, + ) + + @Test + fun drawableParentDeformerRoundTripsAndNoOps() { + val base = model() + + val bound = base.withDrawableParentDeformer(drawableId, warpId) + assertEquals(warpId, bound.drawables.first { it.id == drawableId }.parentDeformerId) + // Unbinding is a real edit back to null. + assertNull(bound.withDrawableParentDeformer(drawableId, null).drawables.first { it.id == drawableId }.parentDeformerId) + + // Unchanged value and missing id are both no-ops (same instance). + assertSame(base, base.withDrawableParentDeformer(drawableId, null)) + assertSame(bound, bound.withDrawableParentDeformer(drawableId, warpId)) + assertSame(base, base.withDrawableParentDeformer(DrawableId("missing"), warpId)) + } + + @Test + fun drawableMaskedByRoundTripsAndNoOps() { + val base = model() + val masks = listOf(otherDrawableId) + + val masked = base.withDrawableMaskedBy(drawableId, masks) + assertEquals(masks, masked.drawables.first { it.id == drawableId }.maskedBy) + // Clearing back to empty is a real edit. + assertTrue(masked.withDrawableMaskedBy(drawableId, emptyList()).drawables.first { it.id == drawableId }.maskedBy.isEmpty()) + + assertSame(base, base.withDrawableMaskedBy(drawableId, emptyList())) + assertSame(masked, masked.withDrawableMaskedBy(drawableId, masks)) + assertSame(base, base.withDrawableMaskedBy(DrawableId("missing"), masks)) + } + + @Test + fun deformerPartRoundTripsOnBothSubtypes() { + val base = model() + + // The copy is per-subtype, so both a rotation and a warp must rebind. + val boundRotation = base.withDeformerPart(rotationId, partId) + assertEquals(partId, boundRotation.deformers.first { it.id == rotationId }.partId) + assertTrue(boundRotation.deformers.first { it.id == rotationId } is Deformer.Rotation, "subtype is preserved") + + val boundWarp = base.withDeformerPart(warpId, partId) + assertEquals(partId, boundWarp.deformers.first { it.id == warpId }.partId) + assertTrue(boundWarp.deformers.first { it.id == warpId } is Deformer.Warp, "subtype is preserved") + + assertSame(base, base.withDeformerPart(rotationId, null)) + assertSame(boundWarp, boundWarp.withDeformerPart(warpId, partId)) + assertSame(base, base.withDeformerPart(DeformerId("missing"), partId)) + } + + @Test + fun sessionRelationEditsAreOneUndoStepEach() { + val session = EditorSession(model()) + + session.setDrawableParentDeformer(drawableId, warpId) + assertEquals(warpId, session.model.value.drawables.first { it.id == drawableId }.parentDeformerId) + + session.setDrawableMaskedBy(drawableId, listOf(otherDrawableId)) + assertEquals(listOf(otherDrawableId), session.model.value.drawables.first { it.id == drawableId }.maskedBy) + + session.setDeformerPart(rotationId, partId) + assertEquals(partId, session.model.value.deformers.first { it.id == rotationId }.partId) + + // Three distinct edits, so three undo steps back to the original. + session.undo() + session.undo() + session.undo() + assertNull(session.model.value.drawables.first { it.id == drawableId }.parentDeformerId) + assertTrue(session.model.value.drawables.first { it.id == drawableId }.maskedBy.isEmpty()) + assertNull(session.model.value.deformers.first { it.id == rotationId }.partId) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/SelectionOpsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/SelectionOpsTest.kt new file mode 100644 index 0000000..ff66f19 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/SelectionOpsTest.kt @@ -0,0 +1,184 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the pure [SelectionOps] gesture transforms and the [Selection] invariant that the active + * target is always a member of the selection, or null when empty. + */ +class SelectionOpsTest { + private val partA = SelectionTarget.Part(PartId("a")) + private val drawableB = SelectionTarget.Drawable(DrawableId("b")) + private val drawableC = SelectionTarget.Drawable(DrawableId("c")) + + /** + * A fresh selection is empty with no active target. + */ + @Test + fun emptySelectionHasNoActive() { + val selection = Selection() + assertTrue(selection.isEmpty) + assertEquals(0, selection.size) + assertNull(selection.active) + } + + /** + * replace drops any prior selection and makes the new target the sole, active member. + */ + @Test + fun replaceSelectsOnlyTheTarget() { + val first = SelectionOps.replace(partA) + val second = SelectionOps.replace(drawableB) + + assertEquals(setOf(drawableB), second.targets) + assertEquals(drawableB, second.active) + assertFalse(partA in second) + // The original is untouched (immutability). + assertEquals(setOf(partA), first.targets) + } + + /** + * toggle adds an absent target (making it active) and removes a present one. + */ + @Test + fun toggleAddsThenRemoves() { + val added = SelectionOps.toggle(Selection(), partA) + assertEquals(setOf(partA), added.targets) + assertEquals(partA, added.active) + + val removed = SelectionOps.toggle(added, partA) + assertTrue(removed.isEmpty) + assertNull(removed.active) + } + + /** + * Removing the active target by toggle falls the active back to a remaining member, never dangling. + */ + @Test + fun toggleRemovingActiveFallsBackToRemaining() { + val twoSelected = SelectionOps.add(SelectionOps.replace(partA), drawableB) + assertEquals(drawableB, twoSelected.active) + + val afterRemove = SelectionOps.toggle(twoSelected, drawableB) + + assertEquals(setOf(partA), afterRemove.targets) + assertEquals(partA, afterRemove.active, "active must remain a member of the selection") + } + + /** + * add extends the selection without removing anything and promotes the added target to active. + */ + @Test + fun addExtendsAndActivates() { + val selection = SelectionOps.add(SelectionOps.add(SelectionOps.replace(partA), drawableB), drawableC) + + assertEquals(setOf(partA, drawableB, drawableC), selection.targets) + assertEquals(drawableC, selection.active) + assertEquals(3, selection.size) + } + + /** + * Adding an already-present target keeps the set unchanged but re-promotes it to active. + */ + @Test + fun addExistingPromotesToActive() { + val start = SelectionOps.add(SelectionOps.replace(partA), drawableB) + val reAdded = SelectionOps.add(start, partA) + + assertEquals(setOf(partA, drawableB), reAdded.targets) + assertEquals(partA, reAdded.active) + } + + /** + * clear returns an empty selection regardless of input. + */ + @Test + fun clearEmptiesSelection() { + assertTrue(SelectionOps.clear().isEmpty) + } + + /** + * contains reflects membership for the operator-in form used by panels and the highlight bridge. + */ + @Test + fun containsReflectsMembership() { + val selection = SelectionOps.add(SelectionOps.replace(partA), drawableB) + assertTrue(partA in selection) + assertTrue(drawableB in selection) + assertFalse(drawableC in selection) + } + + // A small model for the object Select All / Invert domain: one selectable part, one selectable deformer, + // one selectable drawable, and one LOCKED drawable that must be excluded. + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(Part(PartId("a"), "A", children = emptyList())), + deformers = + listOf( + Deformer.Warp(DeformerId("w"), "W", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null), + ), + drawables = + listOf( + Drawable(DrawableId("b"), "B", parentDeformerId = null, blendMode = BlendMode.Normal, maskedBy = emptyList(), mesh = null, geometryGrid = null), + Drawable( + DrawableId("c"), + "C", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + isSelectable = false, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** selectAll gathers every selectable entity (a locked one is excluded), with the active a member. */ + @Test + fun selectAllGathersSelectableEntities() { + val all = SelectionOps.selectAll(Selection(), model()) + assertEquals( + setOf( + SelectionTarget.Part(PartId("a")), + SelectionTarget.Deformer(DeformerId("w")), + SelectionTarget.Drawable(DrawableId("b")), + ), + all.targets, + "the locked drawable c is excluded", + ) + assertTrue(all.active in all.targets, "active is a member of the selection") + } + + /** selectAll keeps the current active target when it stays selected. */ + @Test + fun selectAllKeepsExistingActive() { + val all = SelectionOps.selectAll(SelectionOps.replace(SelectionTarget.Part(PartId("a"))), model()) + assertEquals(SelectionTarget.Part(PartId("a")), all.active) + } + + /** invert complements within the selectable domain and drops the now-deselected active target. */ + @Test + fun invertComplementsSelectableDomainAndDropsActive() { + val inverted = SelectionOps.invert(SelectionOps.replace(SelectionTarget.Part(PartId("a"))), model()) + assertEquals( + setOf(SelectionTarget.Deformer(DeformerId("w")), SelectionTarget.Drawable(DrawableId("b"))), + inverted.targets, + ) + assertNull(inverted.active, "the previously active (now deselected) target drops") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/SessionViewStateTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/SessionViewStateTest.kt new file mode 100644 index 0000000..a7ad75a --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/SessionViewStateTest.kt @@ -0,0 +1,170 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins how a session opens on the state a document was saved with (docs/format/UMA.md § 7.4): it is where the + * history STARTS - never an undo step, never a dirty mark - it is fitted to the model first, and what the session + * gathers for the next save is what it was opened with. + */ +class SessionViewStateTest { + /** + * A drawable with or without a mesh. + * + * @param String id The drawable id. + * @param Boolean meshed Whether it carries a one-triangle mesh. + * @return Drawable The drawable. + */ + private fun drawable(id: String, meshed: Boolean): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = if (meshed) DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), intArrayOf(0, 1, 2)) else null, + geometryGrid = null, + ) + + /** + * A model of one part, the given drawables at the root, and one parameter. + * + * @param List drawables The model's drawables. + * @return PuppetModel The model. + */ + private fun model(drawables: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(ParameterId("ParamAngleX"), "Angle X", -30f, 30f, 0f)), + parts = listOf(Part(PartId("face"), "Face", children = emptyList())), + deformers = emptyList(), + drawables = drawables, + rootChildren = listOf(OrgChild.Part(PartId("face"))) + drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + ).withDerivedRenderRoot() + + private val meshedModel = model(listOf(drawable("a", meshed = true), drawable("b", meshed = true))) + + /** A restored selection, parameter target, and tool state are the session's opening state, not steps on top of it. */ + @Test + fun aSavedStateIsWhereTheHistoryStarts() { + val saved = + SessionViewState( + selection = Selection(setOf(SelectionTarget.Drawable(DrawableId("a")), SelectionTarget.Part(PartId("face"))), SelectionTarget.Drawable(DrawableId("a"))), + parameterSelection = ParameterSelection(setOf(ParameterId("ParamAngleX")), ParameterId("ParamAngleX")), + cursor2d = Cursor2d(12f, -8f), + uvCursor = UvCursor(0.25f, 0.75f), + pivotMode = TransformPivotMode.Cursor, + proportionalEnabled = true, + proportionalSettings = ProportionalEditState(ProportionalFalloff.Sharp, 64f, connectedOnly = true), + ) + + val session = EditorSession(meshedModel, initialViewState = saved) + + assertEquals(saved.selection, session.selection.value) + assertEquals(saved.parameterSelection, session.parameterSelection.value) + assertEquals(Cursor2d(12f, -8f), session.cursor2d.value) + assertEquals(UvCursor(0.25f, 0.75f), session.uvCursor.value) + assertEquals(TransformPivotMode.Cursor, session.pivotMode.value) + assertEquals(ProportionalEditState(ProportionalFalloff.Sharp, 64f, connectedOnly = true), session.proportionalEdit.value) + assertFalse(session.canUndo.value, "nothing restored is an undo step") + assertFalse(session.dirty.value, "and nothing restored is a change to the document") + assertNull(session.notice.value, "and nothing restored posts a notice") + assertEquals(saved, session.viewState(), "what the session gathers is what it opened with") + } + + /** Proportional editing saved OFF keeps the configuration a toggle brings back. */ + @Test + fun aDisabledProportionalConfigurationComesBackOnToggle() { + val saved = SessionViewState(proportionalSettings = ProportionalEditState(ProportionalFalloff.Root, 48f)) + + val session = EditorSession(meshedModel, initialViewState = saved) + assertNull(session.proportionalEdit.value) + session.toggleProportionalEdit() + + assertEquals(ProportionalEditState(ProportionalFalloff.Root, 48f), session.proportionalEdit.value) + } + + /** A saved id the model no longer has is dropped, and the active falls to a target that survived. */ + @Test + fun referencesTheModelLacksAreDropped() { + val saved = + SessionViewState( + selection = Selection(setOf(SelectionTarget.Drawable(DrawableId("a")), SelectionTarget.Drawable(DrawableId("gone"))), SelectionTarget.Drawable(DrawableId("gone"))), + parameterSelection = ParameterSelection(setOf(ParameterId("ParamGone")), ParameterId("ParamGone")), + ) + + val session = EditorSession(meshedModel, initialViewState = saved) + + assertEquals(Selection(setOf(SelectionTarget.Drawable(DrawableId("a"))), SelectionTarget.Drawable(DrawableId("a"))), session.selection.value) + assertTrue(session.parameterSelection.value.isEmpty) + } + + /** A saved Edit mode opens the session in Edit over the restored selection, with the saved select mode. */ + @Test + fun aSavedEditModeOpensOverTheRestoredSelection() { + val saved = + SessionViewState( + selection = Selection(setOf(SelectionTarget.Drawable(DrawableId("b"))), SelectionTarget.Drawable(DrawableId("b"))), + mode = EditorMode.Edit, + selectMode = MeshSelectMode.Face, + ) + + val session = EditorSession(meshedModel, initialViewState = saved) + + assertEquals(EditorMode.Edit, session.mode.value) + assertEquals(listOf(DrawableId("b")), session.meshSelection.value.drawableIds) + assertEquals(DrawableId("b"), session.meshSelection.value.activeDrawableId) + assertEquals(MeshSelectMode.Face, session.meshSelection.value.selectMode) + assertFalse(session.canUndo.value, "opening in Edit is not a mode-change step") + + session.setMode(EditorMode.Object) + assertTrue(session.canUndo.value, "leaving it is an ordinary step") + session.undo() + assertEquals(EditorMode.Edit, session.mode.value, "and undo returns to the mode the document opened in") + } + + /** A saved Edit mode the model cannot satisfy opens in Object, the refusal setMode makes. */ + @Test + fun anEditModeWithNothingEditableOpensInObject() { + val session = EditorSession(model(listOf(drawable("flat", meshed = false))), initialViewState = SessionViewState(mode = EditorMode.Edit)) + + assertEquals(EditorMode.Object, session.mode.value) + assertTrue(session.meshSelection.value.drawableIds.isEmpty()) + } + + /** The grid follows the application unless the document brought its own, and only a document-owned grid is gathered. */ + @Test + fun aDocumentOwnedGridHoldsAgainstTheApplicationDefault() { + val plain = EditorSession(meshedModel) + assertTrue(plain.gridFollowsApplication) + assertNull(plain.viewState().gridConfig, "a grid that merely mirrors the setting is not the document's to save") + + val owned = EditorSession(meshedModel, initialViewState = SessionViewState(gridConfig = GridConfig(50f, 4))) + assertFalse(owned.gridFollowsApplication) + assertEquals(GridConfig(50f, 4), owned.gridConfig.value) + assertEquals(GridConfig(50f, 4), owned.viewState().gridConfig) + } + + /** A plain open is untouched: no saved state means the defaults the session always had. */ + @Test + fun aPlainOpenKeepsTheDefaults() { + val session = EditorSession(meshedModel) + + assertEquals(SessionViewState(proportionalSettings = DEFAULT_PROPORTIONAL_EDIT_STATE), session.viewState()) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformAdjustTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformAdjustTest.kt new file mode 100644 index 0000000..a1824c0 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformAdjustTest.kt @@ -0,0 +1,139 @@ +package org.umamo.edit + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the transform gestures' rows on the operation settings strip: they carry the gesture's numbers + * in each space's convention (world y up as Z, page y down with the angle's sense flipped), read back + * to the same parameters, the proportional rows appear only when the gesture could take weights and + * read back as a state, and the slide's one row carries its factor. + */ +class TransformAdjustTest { + private fun parameters(deltaX: Float = 0f, deltaY: Float = 0f, factorX: Float = 1f, factorY: Float = 1f, rotation: Float = 0f): TransformGestureParameters = + TransformGestureParameters(deltaX, deltaY, factorX, factorY, rotation) + + private fun List.float(key: String): Float = assertNotNull(firstOrNull { parameter -> parameter.key == key } as? OperatorParameter.FloatParameter, key).value + + private fun assertClose(expected: Float, actual: Float, message: String) { + assertTrue(abs(expected - actual) < 1e-4f, "$message: expected $expected, got $actual") + } + + @Test + fun grabRowsReadTheVerticalAxisPerSpace() { + val gesture = parameters(deltaX = 12f, deltaY = 5f) + + val worldRows = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, proportional = null) + assertEquals(listOf(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_Z), worldRows.map { row -> row.key }, "world space names the vertical axis Z") + assertEquals(5f, worldRows.float(TransformParameterKeys.MOVE_Z), "world y is shown as-is (up)") + + val pageRows = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.UvDisplay, proportional = null) + assertEquals(listOf(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_Y), pageRows.map { row -> row.key }, "the page names it Y") + assertEquals(-5f, pageRows.float(TransformParameterKeys.MOVE_Y), "page y reads down") + + for (space in TransformRowSpace.entries) { + val rows = transformParameters(MeshOperatorKind.Grab, gesture, space, proportional = null) + val back = transformGestureParametersOf(MeshOperatorKind.Grab, space, rows) + assertEquals(12f, back.deltaX, "$space round-trips x") + assertEquals(5f, back.deltaY, "$space round-trips y") + assertEquals(1f, back.factorX) + assertEquals(0f, back.rotationRadians) + } + } + + @Test + fun rotateRowsFlipTheirSenseWithThePage() { + val gesture = parameters(rotation = (PI / 2).toFloat()) + + val worldRows = transformParameters(MeshOperatorKind.Rotate, gesture, TransformRowSpace.World, proportional = null) + assertClose(90f, worldRows.float(TransformParameterKeys.ANGLE), "world degrees keep the gesture's sense") + val pageRows = transformParameters(MeshOperatorKind.Rotate, gesture, TransformRowSpace.UvDisplay, proportional = null) + assertClose(-90f, pageRows.float(TransformParameterKeys.ANGLE), "page degrees flip with the y axis") + + for (space in TransformRowSpace.entries) { + val rows = transformParameters(MeshOperatorKind.Rotate, gesture, space, proportional = null) + assertClose((PI / 2).toFloat(), transformGestureParametersOf(MeshOperatorKind.Rotate, space, rows).rotationRadians, "$space round-trips the angle") + } + } + + @Test + fun scaleRowsNameTheVerticalAxisPerSpaceAndRoundTrip() { + val gesture = parameters(factorX = 2f, factorY = 0.5f) + + val worldRows = transformParameters(MeshOperatorKind.Scale, gesture, TransformRowSpace.World, proportional = null) + assertEquals(listOf(TransformParameterKeys.SCALE_X, TransformParameterKeys.SCALE_Z), worldRows.map { row -> row.key }) + val pageRows = transformParameters(MeshOperatorKind.Scale, gesture, TransformRowSpace.UvDisplay, proportional = null) + assertEquals(listOf(TransformParameterKeys.SCALE_X, TransformParameterKeys.SCALE_Y), pageRows.map { row -> row.key }) + + for (space in TransformRowSpace.entries) { + val back = transformGestureParametersOf(MeshOperatorKind.Scale, space, transformParameters(MeshOperatorKind.Scale, gesture, space, proportional = null)) + assertEquals(2f, back.factorX, "$space round-trips x") + assertEquals(0.5f, back.factorY, "$space round-trips y") + } + assertTrue(transformParameters(MeshOperatorKind.VertexSlide, gesture, TransformRowSpace.World, proportional = null).isEmpty(), "a slide has rows of its own") + assertEquals(0.25f, slideParameters(0.25f).float(TransformParameterKeys.SLIDE_FACTOR)) + } + + @Test + fun proportionalRowsFollowTheGestureAndReadBackAsAState() { + val gesture = parameters(deltaX = 1f) + val without = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, proportional = null) + assertNull(proportionalRowsOf(without), "no proportional rows registered, none read back") + + val rows = ProportionalRows.of(ProportionalEditState(ProportionalFalloff.Sharp, 40f, connectedOnly = true), radius = 40f) + val with = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, rows) + assertEquals( + listOf(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_Z, TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.FALLOFF, TransformParameterKeys.PROPORTIONAL_SIZE, TransformParameterKeys.CONNECTED_ONLY), + with.map { row -> row.key }, + ) + val read = assertNotNull(proportionalRowsOf(with)) + assertEquals(ProportionalEditState(ProportionalFalloff.Sharp, 40f, connectedOnly = true), read.asState(), "the rows read back as the state") + + val off = ProportionalRows.of(state = null, radius = 200f) + val offRead = assertNotNull(proportionalRowsOf(transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, off))) + assertNull(offRead.asState(), "an off flag is no state") + assertEquals(ProportionalFalloff.Smooth, offRead.falloff, "the defaults stand in while off") + assertEquals(200f, offRead.radius, "the radius the gesture would have used is shown") + + val switchedOff = with.withParameter(TransformParameterKeys.PROPORTIONAL, OperatorParameter.BooleanParameter(TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.PROPORTIONAL, false)) + assertNull(assertNotNull(proportionalRowsOf(switchedOff)).asState(), "unticking the flag turns the halo off") + } + + /** The halos re-derive on the capture from the rows: a wider radius pulls the bystander in, an off flag drops it. */ + @Test + fun rederivingTheHalosFollowsTheRows() { + // Two vertices 10 apart, the first covered: at radius 5 the second is outside, at 20 it is inside. + val capture = + assertNotNull( + buildModalTransformCapture( + sources = listOf(ModalCaptureSource(org.umamo.runtime.model.DrawableId("a"), floatArrayOf(0f, 0f, 10f, 0f), intArrayOf(0, 1, 1), setOf(0))), + pivotMode = TransformPivotMode.MedianPoint, + individualOriginScope = IndividualOriginScope.ConnectivityIsland, + operatorKind = MeshOperatorKind.Grab, + activeAnchor = null, + cursorAnchor = null, + ), + ) + val entry = capture.entries.single() + val gesture = parameters(deltaX = 1f) + assertNull(rederiveProportionalHalos(capture, transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, proportional = null)), "no rows, no re-derivation") + + val narrow = transformParameters(MeshOperatorKind.Grab, gesture, TransformRowSpace.World, ProportionalRows(enabled = true, ProportionalFalloff.Linear, radius = 5f, connectedOnly = false)) + assertNotNull(rederiveProportionalHalos(capture, narrow)) + assertEquals(setOf(0), entry.movedIndices, "outside the radius nothing joins") + + val wide = narrow.withParameter(TransformParameterKeys.PROPORTIONAL_SIZE, OperatorParameter.FloatParameter(TransformParameterKeys.PROPORTIONAL_SIZE, TransformParameterKeys.PROPORTIONAL_SIZE, 20f, 1f, 100f)) + assertNotNull(rederiveProportionalHalos(capture, wide)) + assertEquals(setOf(0, 1), entry.movedIndices, "inside the radius the bystander joins") + assertClose(0.5f, assertNotNull(entry.influence[1]).weight, "linear falloff at half the radius") + + val off = wide.withParameter(TransformParameterKeys.PROPORTIONAL, OperatorParameter.BooleanParameter(TransformParameterKeys.PROPORTIONAL, TransformParameterKeys.PROPORTIONAL, false)) + assertNull(assertNotNull(rederiveProportionalHalos(capture, off)).asState()) + assertEquals(setOf(0), entry.movedIndices, "off clears the halo") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformChangeLabelTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformChangeLabelTest.kt new file mode 100644 index 0000000..8d9559c --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformChangeLabelTest.kt @@ -0,0 +1,91 @@ +package org.umamo.edit + +import org.umamo.runtime.model.DrawableId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the history label every whole-gesture transform reports, across all three domains and every + * [MeshOperatorKind]. + * + * Two things are being protected. First, the domain has to be readable at a glance in the history panel - + * an object transform, an Edit-mode mesh transform, and a UV transform must never share a label, which is + * why the keys sit in three separate namespaces rather than being distinguished only by the operator. + * Second, each key must have a matching arm in the history panel's resource lookup: an unmapped key does + * not fail anywhere, it silently renders as the generic "Edit" label, so the exhaustive table below is what + * makes a forgotten string visible. + */ +class TransformChangeLabelTest { + private val drawableIds = listOf(DrawableId("a")) + private val vertexIndices = mapOf(DrawableId("a") to listOf(0, 1)) + + /** Edit mode names all four of its operators, Vertex Slide included. */ + @Test + fun meshTransformLabelsPerOperator() { + assertEquals("change.mesh.move", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.Grab).labelKey) + assertEquals("change.mesh.scale", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.Scale).labelKey) + assertEquals("change.mesh.rotate", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.Rotate).labelKey) + assertEquals("change.mesh.slide", MeshChange.TransformVertices(vertexIndices, MeshOperatorKind.VertexSlide).labelKey) + } + + /** Object mode has no Vertex Slide of its own, so a slide reads as a plain move rather than an unmapped key. */ + @Test + fun objectTransformLabelsPerOperator() { + assertEquals("change.object.move", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.Grab).labelKey) + assertEquals("change.object.scale", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.Scale).labelKey) + assertEquals("change.object.rotate", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.Rotate).labelKey) + assertEquals("change.object.move", MeshChange.TransformDrawables(drawableIds, MeshOperatorKind.VertexSlide).labelKey) + } + + /** The UV editor's slide is unimplemented (see TODO § UV Editor); until it lands it degrades to the move label. */ + @Test + fun uvTransformLabelsPerOperator() { + assertEquals("change.uv.move", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.Grab).labelKey) + assertEquals("change.uv.scale", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.Scale).labelKey) + assertEquals("change.uv.rotate", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.Rotate).labelKey) + assertEquals("change.uv.move", MeshChange.TransformUvs(vertexIndices, MeshOperatorKind.VertexSlide).labelKey) + } + + /** + * No two domains share a key for the same operator. This is the requirement the labels exist for: a + * glance at the history panel has to say whether a step was an object, mesh, or UV operation, and three + * domains reusing one key would read identically no matter how the strings were worded. + */ + @Test + fun theThreeDomainsNeverShareALabelKey() { + for (kind in MeshOperatorKind.entries) { + val keys = + setOf( + MeshChange.TransformVertices(vertexIndices, kind).labelKey, + MeshChange.TransformDrawables(drawableIds, kind).labelKey, + MeshChange.TransformUvs(vertexIndices, kind).labelKey, + ) + assertEquals(3, keys.size, "$kind produced a shared label key across domains: $keys") + } + } + + /** Mirror keeps its own key in the UV namespace - it is not a G / S / R gesture. */ + @Test + fun mirrorKeepsItsOwnUvKey() { + assertEquals("change.uv.mirror", MeshChange.MirrorUvs(drawableIds, mirrorU = true).labelKey) + assertEquals("change.uv.mirror", MeshChange.MirrorUvs(drawableIds, mirrorU = false).labelKey) + } + + /** Viewport geometry mirrors keep mesh / object keys (not Scale). */ + @Test + fun viewportMirrorKeepsOwnKeys() { + assertEquals("change.mesh.mirror", MeshChange.MirrorVertices(vertexIndices, mirrorHorizontal = true).labelKey) + assertEquals("change.object.mirror", MeshChange.MirrorDrawables(drawableIds, mirrorHorizontal = false).labelKey) + } + + /** Every transform label is undoable - a gesture the user cannot step back over would be a trap. */ + @Test + fun everyTransformIsUndoable() { + for (kind in MeshOperatorKind.entries) { + assertTrue(MeshChange.TransformVertices(vertexIndices, kind).undoability == Undoability.Undoable, "$kind vertices") + assertTrue(MeshChange.TransformDrawables(drawableIds, kind).undoability == Undoability.Undoable, "$kind drawables") + assertTrue(MeshChange.TransformUvs(vertexIndices, kind).undoability == Undoability.Undoable, "$kind uvs") + } + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformStateTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformStateTest.kt new file mode 100644 index 0000000..2e57dc9 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/TransformStateTest.kt @@ -0,0 +1,327 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the modal-transform infrastructure: the axis-locked scale, the pivot-group builders + * (shared anchor vs per-island Individual Origins), and the session's axis-constraint / pivot / cursor + * / pie latches (toggle semantics, the Rotate exclusion, and the clear-on-latch discipline). + */ +class TransformStateTest { + /** scaleVerticesAxis scales each axis independently about the pivot. */ + @Test + fun scaleVerticesAxisScalesPerAxis() { + val positions = floatArrayOf(2f, 3f, 4f, 5f) + val scaled = MeshTransforms.scaleVerticesAxis(positions, setOf(0, 1), factorX = 2f, factorY = 1f, pivotX = 1f, pivotY = 1f) + assertEquals(listOf(3f, 3f, 7f, 5f), scaled.toList(), "x doubles about the pivot, y is untouched") + assertEquals(listOf(2f, 3f, 4f, 5f), positions.toList(), "the input array is never mutated") + } + + /** sharedGroup wraps every covered vertex about one anchor; islandGroups split by connectivity. */ + @Test + fun pivotGroupBuilders() { + val shared = TransformPivots.sharedGroup(setOf(0, 1, 2), pivotX = 5f, pivotY = 6f) + assertEquals(1, shared.size) + assertEquals(setOf(0, 1, 2), shared.single().vertexIndices) + assertEquals(5f, shared.single().pivotX) + + // Two disconnected triangles: vertices 0-2 at x=0..2, vertices 3-5 at x=10..12 (y = 0). + val positions = floatArrayOf(0f, 0f, 2f, 0f, 1f, 2f, 10f, 0f, 12f, 0f, 11f, 2f) + val triangles = intArrayOf(0, 1, 2, 3, 4, 5) + val islands = TransformPivots.islandGroups(positions, setOf(0, 1, 2, 3, 4, 5), triangles) + assertEquals(2, islands.size, "two components make two islands") + val leftIsland = islands.first { group -> 0 in group.vertexIndices } + assertEquals(setOf(0, 1, 2), leftIsland.vertexIndices) + assertEquals(1f, leftIsland.pivotX, 1e-4f, "each island pivots about its own centroid") + } + + private fun meshedSession(): EditorSession { + val mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), FloatArray(6), intArrayOf(0, 1, 2)) + val drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = mesh, + geometryGrid = null, + ) + val model = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = emptyList(), + rootPartId = null, + ) + return EditorSession(model) + } + + /** The axis constraint toggles only while a Grab / Scale is live, never for Rotate, and clears with the operator. */ + @Test + fun axisConstraintTogglesOnlyDuringGrabOrScale() { + val session = meshedSession() + val target = SelectionTarget.Drawable(DrawableId("d")) + session.setSelection(Selection(setOf(target), target)) + + // Idle: nothing to lock. + session.toggleAxisConstraint(TransformAxisConstraint.AxisX) + assertNull(session.axisConstraint.value, "no constraint arms while idle") + + session.beginObjectOperator(MeshOperatorKind.Grab, "area-test") + session.toggleAxisConstraint(TransformAxisConstraint.AxisX) + assertEquals(TransformAxisConstraint.AxisX, session.axisConstraint.value) + session.toggleAxisConstraint(TransformAxisConstraint.AxisZ) + assertEquals(TransformAxisConstraint.AxisZ, session.axisConstraint.value, "the other axis switches the lock") + session.toggleAxisConstraint(TransformAxisConstraint.AxisZ) + assertNull(session.axisConstraint.value, "the same axis releases the lock") + + session.toggleAxisConstraint(TransformAxisConstraint.AxisX) + session.clearObjectOperator() + assertNull(session.axisConstraint.value, "clearing the operator clears the lock") + + // Rotate has no 2D axis to lock. + session.beginObjectOperator(MeshOperatorKind.Rotate, "area-test") + session.toggleAxisConstraint(TransformAxisConstraint.AxisX) + assertNull(session.axisConstraint.value, "Rotate refuses the lock") + } + + /** The cursor, pivot mode, and pie latches hold their values; undo clears the transient pie latch. */ + @Test + fun cursorPivotAndPieState() { + val session = meshedSession() + assertNull(session.cursor2d.value, "no cursor before placement") + session.setCursor2d(12f, 34f) + assertEquals(Cursor2d(12f, 34f), session.cursor2d.value) + + assertEquals(TransformPivotMode.MedianPoint, session.pivotMode.value, "median is the default pivot") + session.setPivotMode(TransformPivotMode.Cursor) + assertEquals(TransformPivotMode.Cursor, session.pivotMode.value) + + session.openPieMenu(PieMenuKind.Snap) + assertEquals(PieMenuKind.Snap, session.activePieMenu.value) + session.closePieMenu() + assertNull(session.activePieMenu.value) + + // A restore (undo) drops the pie latch but keeps the cursor and pivot mode (persistent editor state). + val target = SelectionTarget.Drawable(DrawableId("d")) + session.setSelection(Selection(setOf(target), target)) + session.openPieMenu(PieMenuKind.PivotMode) + session.undo() + assertNull(session.activePieMenu.value, "restore closes an open pie") + assertEquals(Cursor2d(12f, 34f), session.cursor2d.value, "the cursor survives undo") + assertEquals(TransformPivotMode.Cursor, session.pivotMode.value, "the pivot mode survives undo") + assertTrue(session.canRedo.value) + } + + /** Proportional editing toggles off/on remembering its configuration; falloff selection enables it. */ + @Test + fun proportionalEditToggleAndConfiguration() { + val session = meshedSession() + assertNull(session.proportionalEdit.value, "proportional editing starts off") + + session.toggleProportionalEdit() + val enabled = session.proportionalEdit.value + assertEquals(ProportionalFalloff.Smooth, enabled?.falloff, "smooth is the default falloff") + assertEquals(DEFAULT_PROPORTIONAL_RADIUS_WORLD, enabled?.radiusWorld, "the default radius applies on first enable") + assertEquals("notice.proportional.on", session.notice.value?.messageKey, "the toggle confirms with a notice") + + // Reconfigure, toggle off, toggle back on: the configuration is remembered. + session.setProportionalFalloff(ProportionalFalloff.Sharp) + session.setProportionalRadius(500f) + session.toggleProportionalEdit() + assertNull(session.proportionalEdit.value, "the second toggle disables") + session.toggleProportionalEdit() + assertEquals(ProportionalEditState(ProportionalFalloff.Sharp, 500f), session.proportionalEdit.value, "the configuration survives an off/on cycle") + + // The radius clamps to its bounds; a falloff pick while off re-enables. + session.setProportionalRadius(0f) + assertEquals(MIN_PROPORTIONAL_RADIUS_WORLD, session.proportionalEdit.value?.radiusWorld, "the radius clamps at the minimum") + session.toggleProportionalEdit() + session.setProportionalFalloff(ProportionalFalloff.Linear) + assertEquals(ProportionalFalloff.Linear, session.proportionalEdit.value?.falloff, "picking a falloff while off enables proportional editing") + } + + /** The rotate accumulator crosses the atan2 branch cut, reverses through zero, and multi-turns. */ + @Test + fun rotationAngleTrackerUnwrapsAndAccumulates() { + val pi = kotlin.math.PI.toFloat() + + // Start right AT the branch cut (a far pivot's typical start) and sweep across it: the raw + // difference would jump ~2*pi, the tracker advances by the small increments actually travelled. + val tracker = RotationAngleTracker() + assertEquals(0f, tracker.advance(pi - 0.1f), 1e-5f, "the first sample anchors at zero") + assertEquals(0.15f, tracker.advance(-pi + 0.05f), 1e-5f, "crossing the cut adds the short arc, not ~2*pi") + assertEquals(-0.05f, tracker.advance(pi - 0.15f), 1e-5f, "reversing walks back through zero into the other sign") + assertEquals(-0.05f, tracker.advance(pi - 0.15f), 1e-5f, "the same sample twice adds nothing (re-derives are safe)") + + // A full circle in quarter steps accumulates ~2*pi (a raw subtraction could never exceed pi). + val multiTurn = RotationAngleTracker() + multiTurn.advance(0f) + multiTurn.advance(pi / 2) + multiTurn.advance(pi) + multiTurn.advance(-pi / 2) + assertEquals(2 * pi, multiTurn.advance(0f), 1e-4f, "a full sweep accumulates a whole turn") + + assertEquals(0f, wrapAngle(2 * pi), 1e-5f, "wrapAngle folds a whole turn to zero") + assertEquals(-pi + 0.2f, wrapAngle(pi + 0.2f), 1e-5f, "wrapAngle folds past +pi into the negative side") + } + + /** Connected Only toggles with a notice, enabling proportional editing when it was off. */ + @Test + fun proportionalConnectedOnlyToggle() { + val session = meshedSession() + session.toggleProportionalConnected() + assertEquals(true, session.proportionalEdit.value?.connectedOnly, "toggling while off enables proportional editing, connected on") + assertEquals("notice.proportional.connected.on", session.notice.value?.messageKey, "the toggle confirms with a notice") + session.toggleProportionalConnected() + assertEquals(false, session.proportionalEdit.value?.connectedOnly, "the second toggle turns connected off") + assertTrue(session.proportionalEdit.value != null, "proportional editing itself stays on") + + // Off/on cycles remember the flag with the rest of the configuration. + session.toggleProportionalConnected() + session.toggleProportionalEdit() + session.toggleProportionalEdit() + assertEquals(true, session.proportionalEdit.value?.connectedOnly, "connected only survives an off/on cycle") + } + + /** A suppressed latch (the duplicate / rip auto-grab) opts the gesture out of proportional editing. */ + @Test + fun suppressedMeshOperatorLatch() { + val session = meshedSession() + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0))) + + session.beginMeshOperator(MeshOperatorKind.Grab, "area-test", suppressProportional = true) + assertTrue(session.activeMeshOperatorSuppressesProportional, "the suppressed latch publishes its flag") + + // Clearing the operator resets the flag; a plain latch never inherits it. + session.clearMeshOperator() + assertTrue(!session.activeMeshOperatorSuppressesProportional, "clearing the operator resets the suppression") + session.beginMeshOperator(MeshOperatorKind.Grab, "area-test") + assertTrue(!session.activeMeshOperatorSuppressesProportional, "a plain latch is never suppressed") + } + + /** Operator latches record the initiating area; re-latching moves ownership atomically. */ + @Test + fun operatorLatchesCarryTheInitiatingArea() { + val session = meshedSession() + val target = SelectionTarget.Drawable(DrawableId("d")) + session.setSelection(Selection(setOf(target), target)) + + session.beginObjectOperator(MeshOperatorKind.Grab, "area-a") + assertEquals(ActiveOperator(MeshOperatorKind.Grab, "area-a"), session.activeObjectOperator.value) + session.beginObjectOperator(MeshOperatorKind.Scale, "area-b") + assertEquals(ActiveOperator(MeshOperatorKind.Scale, "area-b"), session.activeObjectOperator.value, "re-latching replaces both the kind and the owner") + session.clearObjectOperator() + + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("d"), MeshElement.Vertex(0))) + session.beginMeshOperator(MeshOperatorKind.Grab, "area-a") + assertEquals(ActiveOperator(MeshOperatorKind.Grab, "area-a"), session.activeMeshOperator.value) + } + + /** The armed select tools carry their arming area; a resize keeps it, a re-arm moves it. */ + @Test + fun selectToolsCarryTheArmingArea() { + val session = meshedSession() + session.beginBoxSelect("area-a") + assertEquals(ActiveSelectTool.BoxArmed("area-a"), session.activeSelectTool.value) + + session.beginCircleSelect("area-a") + val armed = session.activeSelectTool.value as ActiveSelectTool.Circle + assertEquals("area-a", armed.areaId) + + session.setCircleRadius(armed.radiusPx + 10f) + val resized = session.activeSelectTool.value as ActiveSelectTool.Circle + assertEquals("area-a", resized.areaId, "a resize keeps the brush in its arming area") + + // Re-arming from another viewport moves the tool there, restoring the remembered radius. + session.beginCircleSelect("area-b") + val rearmed = session.activeSelectTool.value as ActiveSelectTool.Circle + assertEquals("area-b", rearmed.areaId) + assertEquals(resized.radiusPx, rearmed.radiusPx, "the remembered radius survives the re-arm") + } + + /** Mutual exclusion crosses areas: a latch in one viewport drops a tool armed in another. */ + @Test + fun latchingDropsToolsArmedInOtherAreas() { + val session = meshedSession() + val target = SelectionTarget.Drawable(DrawableId("d")) + session.setSelection(Selection(setOf(target), target)) + + session.beginCircleSelect("area-a") + session.beginObjectOperator(MeshOperatorKind.Grab, "area-b") + assertNull(session.activeSelectTool.value, "latching an operator drops the other area's armed tool") + assertEquals("area-b", session.activeObjectOperator.value?.areaId) + + // A restore (undo) clears the area-carrying latch entirely, whoever owned it. + session.undo() + assertNull(session.activeObjectOperator.value, "restore clears the latched operator") + } + + /** snapToGrid rounds relative to the world origin, so a snap lands on the origin-anchored grid lines. */ + @Test + fun snapToGridRoundsRelativeToOrigin() { + // Origin 0: plain rounding to the nearest multiple of the step. + assertEquals(100f, snapToGrid(120f, origin = 0f, step = 100f), "120 -> nearest 100") + assertEquals(200f, snapToGrid(160f, origin = 0f, step = 100f), "160 -> nearest 200") + // Offset origin (the canvas-center case): the lattice shifts with it, so 120 snaps to origin + 100. + assertEquals(150f, snapToGrid(120f, origin = 50f, step = 100f), "grid at 50,150,... -> 120 snaps to 150") + assertEquals(50f, snapToGrid(60f, origin = 50f, step = 100f), "60 snaps to the origin line at 50") + } + + /** snapToWorldGrid anchors each axis on its own origin component, so both land on the drawn grid lines. */ + @Test + fun snapToWorldGridAnchorsEachAxisOnTheOrigin() { + // The origin a 1200 x 800 canvas derives: world (600, -400). + val model = meshedSession().model.value.copy(worldOriginX = 600f, worldOriginZ = -400f) + // x 630 is 30 right of the origin line, so it rounds back onto it; z -345 is 55 above, so up to -300. + assertEquals(600f to -300f, model.snapToWorldGrid(630f, -345f, step = 100f)) + // A point already on the lattice stays put. + assertEquals(700f to -500f, model.snapToWorldGrid(700f, -500f, step = 100f)) + } + + /** An unplaced cursor resolves to the world origin for every operation, without being placed. */ + @Test + fun unplacedCursorResolvesToTheWorldOrigin() { + val session = EditorSession(meshedSession().model.value.copy(worldOriginX = 600f, worldOriginZ = -600f)) + + assertEquals(Cursor2d(600f, -600f), session.cursor2dOrWorldOrigin(), "an unplaced cursor rests on the world axes") + assertNull(session.cursor2d.value, "resolving it does not place it, so it stays undrawn and unpersisted") + + session.setCursor2d(12f, 34f) + assertEquals(Cursor2d(12f, 34f), session.cursor2dOrWorldOrigin(), "a placed cursor is its own point") + } + + /** GridConfig.snapStep is the finest visible spacing: scale divided by the subdivision count. */ + @Test + fun gridConfigSnapStepIsScaleOverSubdivisions() { + assertEquals(10f, GridConfig(scale = 100f, subdivisions = 10).snapStep, "100 / 10 = 10") + assertEquals(25f, GridConfig(scale = 100f, subdivisions = 4).snapStep, "100 / 4 = 25") + // A defaulted config keeps the built-in fallbacks (SNAP_GRID_WORLD_UNITS / DEFAULT_GRID_SUBDIVISIONS). + assertEquals(SNAP_GRID_WORLD_UNITS / DEFAULT_GRID_SUBDIVISIONS, GridConfig().snapStep, "default step") + // subdivisions is clamped to at least 1, so a degenerate 0 never divides by zero. + assertEquals(100f, GridConfig(scale = 100f, subdivisions = 0).snapStep, "0 subdivisions clamps to 1") + } + + /** setGridConfig publishes the new geometry on the session's gridConfig flow (transient, not snapshotted). */ + @Test + fun setGridConfigPublishesAndIsNotUndoable() { + val session = meshedSession() + assertEquals(GridConfig(), session.gridConfig.value, "starts at the default grid") + session.setGridConfig(GridConfig(scale = 50f, subdivisions = 5)) + assertEquals(GridConfig(scale = 50f, subdivisions = 5), session.gridConfig.value, "the new config publishes") + assertTrue(!session.canUndo.value, "a grid-config change is transient, never an undo step") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/UvEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/UvEditsTest.kt new file mode 100644 index 0000000..8cc403e --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/UvEditsTest.kt @@ -0,0 +1,366 @@ +package org.umamo.edit + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Verifies the UV write path: the withMeshUvs copy-on-write op and its + * no-op guards, the commitMeshUvs undo integration, the activeUvOperator latch semantics (area + * ownership, mutual exclusion, the Vertex Slide and mode refusals, the axis-constraint hookup), the + * UV cursor, and the Mirror U / V command math. The load-bearing invariant throughout is the mesh/UV + * decoupling seen from the UV side: a UV edit shares the positions and indices arrays by reference + * and never disturbs rest geometry. + */ +class UvEditsTest { + private fun meshedDrawable(id: String, uvs: FloatArray): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), uvs, intArrayOf(0, 1, 2)), + geometryGrid = null, + ) + + private fun uvModel(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + meshedDrawable("a", floatArrayOf(0.2f, 0.1f, 0.4f, 0.1f, 0.6f, 0.4f)), + meshedDrawable("b", floatArrayOf(0.1f, 0.8f, 0.3f, 0.8f, 0.1f, 0.9f)), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** Asserts two interleaved uv arrays match element-wise within float tolerance. */ + private fun assertUvsEqual(expected: List, actual: FloatArray, message: String) { + assertEquals(expected.size, actual.size, message) + for (componentIndex in expected.indices) { + assertEquals(expected[componentIndex], actual[componentIndex], 1e-5f, "$message (component $componentIndex)") + } + } + + /** Enters Edit mode with every vertex of drawable "a" selected (and optionally "b" too). */ + private fun editSession(selectBothDrawables: Boolean = false): EditorSession { + val session = EditorSession(uvModel()) + session.setMode(EditorMode.Edit) + var selection = session.meshSelection.value + for (vertexIndex in 0..2) { + selection = MeshSelectionOps.add(selection, DrawableId("a"), MeshElement.Vertex(vertexIndex)) + } + if (selectBothDrawables) { + for (vertexIndex in 0..2) { + selection = MeshSelectionOps.add(selection, DrawableId("b"), MeshElement.Vertex(vertexIndex)) + } + } + session.setMeshSelection(selection) + return session + } + + /** withMeshUvs rebuilds only the touched mesh leaf, sharing positions / indices and every sibling. */ + @Test + fun withMeshUvsSharesEverythingButTheUvArray() { + val model = uvModel() + val originalMesh = model.drawables[0].mesh!! + val untouchedDrawable = model.drawables[1] + + val newUvs = floatArrayOf(0.5f, 0.5f, 0.6f, 0.5f, 0.5f, 0.6f) + val updated = model.withMeshUvs(DrawableId("a"), newUvs) + + assertNotSame(model, updated, "a real edit produces a new model instance") + val updatedMesh = updated.drawables[0].mesh!! + assertSame(newUvs, updatedMesh.uvs, "the new uv array is adopted as-is") + assertSame(originalMesh.positions, updatedMesh.positions, "positions are shared by reference (the decoupling invariant)") + assertSame(originalMesh.indices, updatedMesh.indices, "indices are shared by reference") + assertSame(untouchedDrawable, updated.drawables[1], "the other drawable is shared by reference") + assertSame(originalMesh, model.drawables[0].mesh, "the input model is never mutated") + } + + /** Every withMeshUvs no-op guard returns the same model instance so the session records nothing. */ + @Test + fun withMeshUvsNoOpGuards() { + val model = uvModel() + val mesh = model.drawables[0].mesh!! + + assertSame(model, model.withMeshUvs(DrawableId("missing"), FloatArray(6)), "an unknown drawable is a no-op") + assertSame(model, model.withMeshUvs(DrawableId("a"), mesh.uvs), "the live array instance is a no-op") + assertSame(model, model.withMeshUvs(DrawableId("a"), FloatArray(4)), "a length mismatch is a no-op") + + val meshless = + model.copy(drawables = listOf(model.drawables[0].copy(mesh = null))) + assertSame(meshless, meshless.withMeshUvs(DrawableId("a"), FloatArray(6)), "a mesh-less drawable is a no-op") + } + + /** commitMeshUvs folds several drawables into ONE undo step; undo restores the exact prior arrays. */ + @Test + fun commitMeshUvsIsOneUndoStepAndUndoRestoresTheArrayReferences() { + val session = editSession(selectBothDrawables = true) + val originalUvsA = session.model.value.drawables[0].mesh!!.uvs + val originalUvsB = session.model.value.drawables[1].mesh!!.uvs + val stepsBefore = session.historyView.value.steps.size + assertFalse(session.dirty.value, "selection setup never dirties the document") + + session.commitMeshUvs( + MeshChange.TransformUvs(mapOf(DrawableId("a") to listOf(0, 1, 2), DrawableId("b") to listOf(0, 1, 2)), MeshOperatorKind.Grab), + mapOf( + DrawableId("a") to floatArrayOf(0.3f, 0.2f, 0.5f, 0.2f, 0.7f, 0.5f), + DrawableId("b") to floatArrayOf(0.2f, 0.7f, 0.4f, 0.7f, 0.2f, 0.8f), + ), + ) + + assertEquals(stepsBefore + 1, session.historyView.value.steps.size, "both drawables commit as one step") + assertEquals("change.uv.move", session.historyView.value.steps.last().labelKey) + assertTrue(session.dirty.value, "a UV edit is document content") + assertNotSame(originalUvsA, session.model.value.drawables[0].mesh!!.uvs) + + session.undo() + assertSame(originalUvsA, session.model.value.drawables[0].mesh!!.uvs, "undo restores the exact prior uv array") + assertSame(originalUvsB, session.model.value.drawables[1].mesh!!.uvs) + assertFalse(session.dirty.value, "undo returns to the saved baseline") + } + + /** A commit whose every entry no-ops (mismatch / same instance / empty) records nothing. */ + @Test + fun commitMeshUvsNoOpRecordsNothing() { + val session = editSession() + val modelBefore = session.model.value + val stepsBefore = session.historyView.value.steps.size + + session.commitMeshUvs(MeshChange.TransformUvs(emptyMap(), MeshOperatorKind.Grab), emptyMap()) + session.commitMeshUvs(MeshChange.TransformUvs(mapOf(DrawableId("a") to emptyList()), MeshOperatorKind.Grab), mapOf(DrawableId("a") to FloatArray(4))) + session.commitMeshUvs( + MeshChange.TransformUvs(mapOf(DrawableId("a") to emptyList()), MeshOperatorKind.Grab), + mapOf(DrawableId("a") to modelBefore.drawables[0].mesh!!.uvs), + ) + + assertSame(modelBefore, session.model.value, "no-op commits leave the model instance untouched") + assertEquals(stepsBefore, session.historyView.value.steps.size, "no-op commits record no history step") + assertFalse(session.dirty.value) + } + + /** The UV latch records the initiating area, refuses Vertex Slide, and requires Edit mode. */ + @Test + fun uvOperatorLatchSemantics() { + val session = editSession() + + session.beginUvOperator(MeshOperatorKind.Grab, "area-uv") + assertEquals(ActiveOperator(MeshOperatorKind.Grab, "area-uv"), session.activeUvOperator.value) + session.beginUvOperator(MeshOperatorKind.Scale, "area-other") + assertEquals( + ActiveOperator(MeshOperatorKind.Scale, "area-other"), + session.activeUvOperator.value, + "re-latching replaces both the kind and the owner", + ) + session.clearUvOperator() + assertNull(session.activeUvOperator.value) + + session.beginUvOperator(MeshOperatorKind.VertexSlide, "area-uv") + assertNull(session.activeUvOperator.value, "Vertex Slide is rest-geometry math and is refused") + + session.setMode(EditorMode.Object) + session.beginUvOperator(MeshOperatorKind.Grab, "area-uv") + assertNull(session.activeUvOperator.value, "Object mode refuses the UV latch") + } + + /** The three operator latches are mutually exclusive, and a restore (undo) clears the UV latch. */ + @Test + fun uvOperatorMutualExclusionAndRestoreTeardown() { + val session = editSession() + + session.beginMeshOperator(MeshOperatorKind.Grab, "area-a") + session.beginUvOperator(MeshOperatorKind.Grab, "area-uv") + assertNull(session.activeMeshOperator.value, "latching UV drops the mesh operator") + assertEquals("area-uv", session.activeUvOperator.value?.areaId) + + session.beginMeshOperator(MeshOperatorKind.Grab, "area-a") + assertNull(session.activeUvOperator.value, "latching mesh drops the UV operator") + session.clearMeshOperator() + + session.beginBoxSelect("area-a") + session.beginUvOperator(MeshOperatorKind.Grab, "area-uv") + assertNull(session.activeSelectTool.value, "latching UV drops the armed select tool") + + session.undo() + assertNull(session.activeUvOperator.value, "restore clears the latched UV operator") + } + + /** The X / Z axis constraint toggles during a UV Grab / Scale, never for Rotate, and clears with the latch. */ + @Test + fun uvOperatorAxisConstraint() { + val session = editSession() + + session.beginUvOperator(MeshOperatorKind.Grab, "area-uv") + session.toggleAxisConstraint(TransformAxisConstraint.AxisX) + assertEquals(TransformAxisConstraint.AxisX, session.axisConstraint.value) + session.clearUvOperator() + assertNull(session.axisConstraint.value, "clearing the UV operator clears the lock") + + session.beginUvOperator(MeshOperatorKind.Rotate, "area-uv") + session.toggleAxisConstraint(TransformAxisConstraint.AxisX) + assertNull(session.axisConstraint.value, "Rotate refuses the lock") + } + + /** A selection whose meshes carry no editable UV array refuses the latch with an explanatory notice. */ + @Test + fun uvOperatorRefusesWithoutEditableUvs() { + val model = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(meshedDrawable("a", FloatArray(0))), + rootChildren = emptyList(), + rootPartId = null, + ) + val session = EditorSession(model) + session.setMode(EditorMode.Edit) + session.setMeshSelection(MeshSelectionOps.add(session.meshSelection.value, DrawableId("a"), MeshElement.Vertex(0))) + + session.beginUvOperator(MeshOperatorKind.Grab, "area-uv") + assertNull(session.activeUvOperator.value, "an empty uv array cannot be edited") + assertEquals("notice.uv.noUvs", session.notice.value?.messageKey, "the refusal explains itself") + + session.mirrorSelectedUvs(mirrorU = true) + assertFalse(session.dirty.value, "the mirror refuses for the same reason") + } + + /** The UV cursor latch holds its placement and survives undo (transient by design, like cursor2d). */ + @Test + fun uvCursorPlacement() { + val session = editSession() + assertNull(session.uvCursor.value, "no cursor before placement") + session.setUvCursor(0.25f, 0.75f) + assertEquals(UvCursor(0.25f, 0.75f), session.uvCursor.value) + session.undo() + assertEquals(UvCursor(0.25f, 0.75f), session.uvCursor.value, "the UV cursor survives undo") + } + + /** Mirror U flips u about the covered median leaving v (and rest geometry) untouched; Mirror V is the converse. */ + @Test + fun mirrorSelectedUvsAboutTheMedian() { + val session = editSession() + val originalPositions = session.model.value.drawables[0].mesh!!.positions + + // Covered u values are 0.2 / 0.4 / 0.6, so the median pivot's u is 0.4. + session.mirrorSelectedUvs(mirrorU = true) + val mirroredU = session.model.value.drawables[0].mesh!!.uvs + assertUvsEqual(listOf(0.6f, 0.1f, 0.4f, 0.1f, 0.2f, 0.4f), mirroredU, "u reflects about 0.4, v is untouched") + assertSame(originalPositions, session.model.value.drawables[0].mesh!!.positions, "rest geometry is untouched by reference") + assertEquals("change.uv.mirror", session.historyView.value.steps.last().labelKey) + + // Covered v values are now 0.1 / 0.1 / 0.4, so the median pivot's v is 0.2. + session.mirrorSelectedUvs(mirrorU = false) + val mirroredV = session.model.value.drawables[0].mesh!!.uvs + assertEquals(0.3f, mirroredV[1], 1e-5f, "v reflects about the median") + assertEquals(0.6f, mirroredV[0], 1e-5f, "u is untouched by a V mirror") + + session.undo() + session.undo() + assertEquals(listOf(0.2f, 0.1f, 0.4f, 0.1f, 0.6f, 0.4f), session.model.value.drawables[0].mesh!!.uvs.toList(), "two undos restore the original mapping") + } + + /** The Cursor pivot mode mirrors about the UV cursor, falling back to the median before any placement. */ + @Test + fun mirrorSelectedUvsAboutTheCursor() { + val session = editSession() + session.setPivotMode(TransformPivotMode.Cursor) + + // No cursor placed yet: the median fallback keeps the command effective. + session.mirrorSelectedUvs(mirrorU = true) + assertEquals(0.6f, session.model.value.drawables[0].mesh!!.uvs[0], 1e-5f, "an unplaced cursor falls back to the median") + session.undo() + + session.setUvCursor(0.5f, 0.5f) + session.mirrorSelectedUvs(mirrorU = true) + val mirrored = session.model.value.drawables[0].mesh!!.uvs + assertUvsEqual(listOf(0.8f, 0.1f, 0.6f, 0.1f, 0.4f, 0.4f), mirrored, "u reflects about the cursor's 0.5") + } + + /** + * A quarter-turn frame: stored (u, v) reads as (v, -u) in the authoring space. Enough to catch a + * mirror that reflects about the STORED axis while claiming to reflect about the shown one - under + * this frame the two are perpendicular, so the mistake cannot pass. + */ + private fun quarterTurnFrame(): UvFrame = + UvFrame(toFrameAffine = floatArrayOf(0f, 1f, 0f, -1f, 0f, 0f), fromFrameAffine = floatArrayOf(0f, -1f, 0f, 1f, 0f, 0f)) + + /** With no frame the mirror is exactly what it always was - the page view must not shift at all. */ + @Test + fun mirrorWithoutAFrameIsUnchanged() { + val withoutFrame = editSession() + withoutFrame.mirrorSelectedUvs(mirrorU = true) + val plain = withoutFrame.model.value.drawables[0].mesh!!.uvs + + val withIdentity = editSession() + withIdentity.mirrorSelectedUvs(mirrorU = true, frame = null) + assertUvsEqual(plain.toList(), withIdentity.model.value.drawables[0].mesh!!.uvs, "an absent frame changes nothing") + } + + /** + * Under a frame the mirror reflects about the AUTHORING axis, not the stored one. Mirroring + * horizontally through a quarter turn therefore moves v and leaves u alone - the opposite of what + * the same command does with no frame. + */ + @Test + fun mirrorReflectsAboutTheAuthoringAxis() { + val session = editSession() + val original = session.model.value.drawables[0].mesh!!.uvs.copyOf() + session.mirrorSelectedUvs(mirrorU = true, frame = quarterTurnFrame()) + val mirrored = session.model.value.drawables[0].mesh!!.uvs + + // Frame u is stored v, so a horizontal mirror in the frame reflects the stored v about its own + // covered median (0.1 / 0.1 / 0.4 -> 0.2) and leaves stored u untouched. + assertEquals(original[0], mirrored[0], 1e-5f, "stored u is untouched by a frame-horizontal mirror") + assertEquals(original[2], mirrored[2], 1e-5f, "stored u is untouched by a frame-horizontal mirror") + assertEquals(0.3f, mirrored[1], 1e-5f, "stored v reflects about the covered median") + assertEquals(0.3f, mirrored[3], 1e-5f, "stored v reflects about the covered median") + assertEquals(0.0f, mirrored[5], 1e-5f, "stored v reflects about the covered median") + } + + /** The Cursor pivot converts into the frame too, so the anchor means the same place in both spaces. */ + @Test + fun mirrorResolvesTheCursorPivotInTheFrame() { + val session = editSession() + session.setPivotMode(TransformPivotMode.Cursor) + session.setUvCursor(0.5f, 0.25f) + session.mirrorSelectedUvs(mirrorU = true, frame = quarterTurnFrame()) + val mirrored = session.model.value.drawables[0].mesh!!.uvs + // The cursor's stored (0.5, 0.25) is frame (0.25, -0.5); a frame-horizontal mirror reflects the + // frame u - stored v - about 0.25. + assertEquals(0.4f, mirrored[1], 1e-5f, "stored v reflects about the cursor's frame position") + assertEquals(0.1f, mirrored[5], 1e-5f, "stored v reflects about the cursor's frame position") + } + + /** A frame round trip must not disturb a vertex the mirror never moved. */ + @Test + fun mirrorLeavesUnselectedVerticesBitIdentical() { + val session = editSession() + // Select only vertex 0, so vertices 1 and 2 must survive the frame conversion untouched. + session.setMeshSelection(MeshSelectionOps.replace(MeshSelection(), DrawableId("a"), MeshElement.Vertex(0))) + val original = session.model.value.drawables[0].mesh!!.uvs.copyOf() + session.mirrorSelectedUvs(mirrorU = true, frame = quarterTurnFrame()) + val mirrored = session.model.value.drawables[0].mesh!!.uvs + for (componentIndex in 2 until original.size) { + assertEquals( + original[componentIndex].toRawBits(), + mirrored[componentIndex].toRawBits(), + "untouched component $componentIndex must keep its exact stored value", + ) + } + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/WarpCreateVisibilityTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/WarpCreateVisibilityTest.kt new file mode 100644 index 0000000..97ac23d --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/WarpCreateVisibilityTest.kt @@ -0,0 +1,71 @@ + +package org.umamo.edit + +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +class WarpCreateVisibilityTest { + private val partId = PartId("p") + private val drawableA = DrawableId("a") + + private fun parentWarp(): Deformer.Warp { + val points = rectLatticeControlPoints(0f, 0f, 1f, 1f, 1, 1) + return Deformer.Warp( + id = DeformerId("Parent"), + name = "Parent", + parent = null, + partId = partId, + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), WarpLatticeForm(points)))), + ) + } + + @Test + fun nestedCreateYieldsSampleableLattice() { + val parent = parentWarp() + val start = + PuppetModel( + parameters = emptyList(), + parts = listOf(Part(partId, "P", listOf(OrgChild.Drawable(drawableA)))), + deformers = listOf(parent), + drawables = + listOf( + Drawable( + id = drawableA, + name = "a", + parentDeformerId = DeformerId("Parent"), + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0.2f, 0.2f, 0.8f, 0.2f, 0.2f, 0.8f), FloatArray(6), intArrayOf(0, 1, 2)), + geometryGrid = null, + ), + ), + rootChildren = listOf(OrgChild.Part(partId)), + rootPartId = null, + ) + val after = start.withWarpDeformerCreatedForDrawables(DeformerId("Child"), "Child", listOf(drawableA)) + val child = after.deformers.filterIsInstance().single { it.id == DeformerId("Child") } + assertEquals(DeformerId("Parent"), child.parent) + val points = assertNotNull(warpControlPointsAt(child.geometryGrid) { 0f }) + assertTrue(points.size >= 8, "points=${points.size}") + assertTrue(points.max() > 0.1f, "max=${points.max()}") + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/WarpLatticeGridEditsTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/WarpLatticeGridEditsTest.kt new file mode 100644 index 0000000..40b03c2 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/WarpLatticeGridEditsTest.kt @@ -0,0 +1,97 @@ +package org.umamo.edit + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Warp lattice grid resize: resampling densifies the control points without moving the surface, and + * out-of-range counts clamp to the properties slider's 2–16 band. + */ +class WarpLatticeGridEditsTest { + private val partId = PartId("p") + + private fun identityWarp(rows: Int, columns: Int): Deformer.Warp { + val points = rectLatticeControlPoints(0f, 0f, 10f, 20f, rows, columns) + return Deformer.Warp( + id = DeformerId("Warp"), + name = "Warp", + parent = null, + partId = partId, + rows = rows, + columns = columns, + isQuadTransform = true, + geometryGrid = + KeyformGrid( + emptyList(), + listOf(KeyformCell(IntArray(0), WarpLatticeForm(points))), + ), + ) + } + + private fun modelWith(warp: Deformer.Warp): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = listOf(Part(partId, "P", emptyList())), + deformers = listOf(warp), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(partId)), + rootPartId = null, + ) + + @Test + fun resamplingIdentityLatticeKeepsCornersAndMidpoint() { + val start = identityWarp(rows = 2, columns = 2) + val old = assertNotNull(start.geometryGrid).cells.single().form.controlPoints + val resized = modelWith(start).withWarpDeformerGrid(start.id, rows = 5, columns = 5) + val warp = resized.deformers.single() as Deformer.Warp + assertEquals(5, warp.rows) + assertEquals(5, warp.columns) + val points = assertNotNull(warp.geometryGrid).cells.single().form.controlPoints + assertEquals((5 + 1) * (5 + 1) * 2, points.size) + assertEquals(old[0], points[0], absoluteTolerance = 1e-4f) + assertEquals(old[1], points[1], absoluteTolerance = 1e-4f) + val oldLast = old.size - 2 + val newLast = points.size - 2 + assertEquals(old[oldLast], points[newLast], absoluteTolerance = 1e-4f) + assertEquals(old[oldLast + 1], points[newLast + 1], absoluteTolerance = 1e-4f) + val expected = FloatArray(2) + // row 2, col 2 of a 6×6 point grid (5 divisions) sits at UV (2/5, 2/5). + sampleWarpLattice(old, columns = 2, rows = 2, bilinear = true, u = 2f / 5f, v = 2f / 5f, out = expected, outIndex = 0) + val midIndex = (2 * 6 + 2) * 2 + assertEquals(expected[0], points[midIndex], absoluteTolerance = 1e-4f) + assertEquals(expected[1], points[midIndex + 1], absoluteTolerance = 1e-4f) + } + + @Test + fun clampAndNoOp() { + val start = identityWarp(2, 2) + val model = modelWith(start) + assertTrue(model === model.withWarpDeformerGrid(start.id, 2, 2)) + val clamped = model.withWarpDeformerGrid(start.id, 99, 0) + val warp = clamped.deformers.single() as Deformer.Warp + assertEquals(MAX_WARP_DIVISIONS, warp.rows) + assertEquals(MIN_WARP_DIVISIONS, warp.columns) + } + + @Test + fun sessionCommitResizesSelectedWarp() { + val start = identityWarp(2, 2) + val session = EditorSession(modelWith(start)) + session.setDeformerWarpGrid(start.id, 8, 8) + val warp = session.model.value.deformers.single() as Deformer.Warp + assertEquals(8, warp.rows) + assertEquals(8, warp.columns) + assertEquals((8 + 1) * (8 + 1) * 2, assertNotNull(warp.geometryGrid).cells.single().form.controlPoints.size) + } +} \ No newline at end of file diff --git a/module/edit/src/commonTest/kotlin/org/umamo/edit/seed/ParameterTemplateTest.kt b/module/edit/src/commonTest/kotlin/org/umamo/edit/seed/ParameterTemplateTest.kt new file mode 100644 index 0000000..1d78c68 --- /dev/null +++ b/module/edit/src/commonTest/kotlin/org/umamo/edit/seed/ParameterTemplateTest.kt @@ -0,0 +1,39 @@ +package org.umamo.edit.seed + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the seed templates: the stored-key round trip and its stale-key fallback, and the humanoid + * dataset's shape - verbatim standard ids, no repeats - since every Live2D-compatible consumer keys + * on exactly those ids. + */ +class ParameterTemplateTest { + @Test + fun aStoredKeyResolvesAndAStaleOneFallsBackToTheDefault() { + assertEquals(ParameterTemplate.Humanoid, ParameterTemplate.fromKey("humanoid")) + assertEquals(ParameterTemplate.None, ParameterTemplate.fromKey("none")) + assertEquals(ParameterTemplate.Default, ParameterTemplate.fromKey("not-a-template"), "a stale setting falls back to the default") + assertEquals(ParameterTemplate.Default, ParameterTemplate.fromKey(null), "an absent setting falls back to the default") + for (template in ParameterTemplate.entries) { + assertEquals(template, ParameterTemplate.fromKey(template.key), "every entry's key round-trips") + } + } + + @Test + fun noneSeedsNothingAndHumanoidSeedsTheStandardSet() { + assertTrue(ParameterTemplate.None.parameters.isEmpty()) + assertEquals(HumanoidParameters.list, ParameterTemplate.Humanoid.parameters) + assertEquals("ParamAngleX", HumanoidParameters.list.first().id.raw, "the standard ids are verbatim") + assertEquals( + HumanoidParameters.list.size, + HumanoidParameters.list.map { parameter -> parameter.id }.toSet().size, + "no id repeats", + ) + for (parameter in HumanoidParameters.list) { + assertTrue(parameter.min < parameter.max, "${parameter.id.raw} is animatable") + assertTrue(parameter.default in parameter.min..parameter.max, "${parameter.id.raw} rests inside its range") + } + } +} \ No newline at end of file diff --git a/module/edit/src/jvmAndroidMain/kotlin/org/umamo/edit/PolygonTriangulator.jvmAndroid.kt b/module/edit/src/jvmAndroidMain/kotlin/org/umamo/edit/PolygonTriangulator.jvmAndroid.kt new file mode 100644 index 0000000..3ec49a2 --- /dev/null +++ b/module/edit/src/jvmAndroidMain/kotlin/org/umamo/edit/PolygonTriangulator.jvmAndroid.kt @@ -0,0 +1,64 @@ +package org.umamo.edit + +import org.poly2tri.Poly2Tri +import org.poly2tri.geometry.polygon.Polygon +import org.poly2tri.geometry.polygon.PolygonPoint +import org.poly2tri.triangulation.TriangulationPoint +import java.util.IdentityHashMap + +/** + * JVM/Android [PolygonTriangulator]: poly2tri constrained Delaunay (zigzag diagonals). + */ +internal actual object PolygonTriangulator { + actual fun triangulate(xy: DoubleArray): IntArray { + val count = xy.size / 2 + if (count < 3) { + return IntArray(0) + } + // poly2tri rejects duplicate coordinates; drop consecutive duplicates and a closing repeat. + val points = ArrayList(count) + val indexOf = IdentityHashMap() + var prevX = Double.NaN + var prevY = Double.NaN + for (i in 0 until count) { + val x = xy[i * 2] + val y = xy[i * 2 + 1] + if (i > 0 && x == prevX && y == prevY) { + continue + } + prevX = x + prevY = y + val point = PolygonPoint(x, y) + indexOf[point] = i + points.add(point) + } + if (points.size >= 2) { + val first = points.first() + val last = points.last() + if (first.x == last.x && first.y == last.y) { + points.removeAt(points.lastIndex) + } + } + if (points.size < 3) { + return IntArray(0) + } + return try { + val polygon = Polygon(points) + Poly2Tri.triangulate(polygon) + val triangles = polygon.triangles + val out = IntArray(triangles.size * 3) + var offset = 0 + for (triangle in triangles) { + val a = indexOf[triangle.points[0]] ?: return IntArray(0) + val b = indexOf[triangle.points[1]] ?: return IntArray(0) + val c = indexOf[triangle.points[2]] ?: return IntArray(0) + out[offset++] = a + out[offset++] = b + out[offset++] = c + } + out + } catch (_: RuntimeException) { + IntArray(0) + } + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpCreateViewportDiagTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpCreateViewportDiagTest.kt new file mode 100644 index 0000000..08a84a6 --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpCreateViewportDiagTest.kt @@ -0,0 +1,70 @@ +package org.umamo.edit + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.render.eval.warpLatticeLocalAt +import org.umamo.render.eval.warpLatticeSpaceMapping +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import java.io.File +import kotlin.math.max +import kotlin.math.min +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Corpus gate: creating a warp under an existing parent must keep the lattice mappable into a + * canvas-scale world AABB (not millions of units from treating canvas rest as parent UV). + */ +class WarpCreateViewportDiagTest { + private val sample: File? = + sequenceOf( + System.getProperty("cmo3.sample"), + "/home/litruv/dev/vtsmaker/Bear_.cmo3", + ).mapNotNull { path -> path?.let(::File)?.takeIf { file -> file.isFile } }.firstOrNull() + + private fun aabb(points: FloatArray): Pair { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var index = 0 + while (index + 1 < points.size) { + minX = min(minX, points[index]) + maxX = max(maxX, points[index]) + minY = min(minY, points[index + 1]) + maxY = max(maxY, points[index + 1]) + index += 2 + } + return (maxX - minX) to (maxY - minY) + } + + @Test + fun nestedCreateLatticeIsMappableOnBear() { + val file = sample ?: return + val root = Cmo3.read(file).root as? CModelSource ?: error("not CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + val pick = puppet.drawables.first { drawable -> drawable.parentDeformerId != null && drawable.mesh != null } + val after = + puppet.withWarpDeformerCreatedForDrawables( + DeformerId("DiagWarp"), + "DiagWarp", + listOf(pick.id), + ) + val created = after.deformers.filterIsInstance().single { it.id == DeformerId("DiagWarp") } + assertNotNull(created.parent) + val pose = after.parameters.associate { it.id to it.default } + val local = assertNotNull(warpLatticeLocalAt(after, pose, created.id)) + val mapping = assertNotNull(warpLatticeSpaceMapping(after, pose, created.id)) + val world = mapping.localToWorld(local) + val (spanX, spanY) = aabb(world) + // Parent warp covers ~canvas; a fitted child lattice must stay on that order of magnitude. + assertTrue(spanX in 1f..10_000f, "world spanX=$spanX") + assertTrue(spanY in 1f..10_000f, "world spanY=$spanY") + for (index in local.indices) { + assertTrue(local[index] in -0.5f..1.5f, "local[$index]=${local[index]} should be parent UV") + } + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpDeleteKeepsPartTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpDeleteKeepsPartTest.kt new file mode 100644 index 0000000..4cf8496 --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpDeleteKeepsPartTest.kt @@ -0,0 +1,76 @@ +package org.umamo.edit + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.render.eval.drawableLocalPosed +import org.umamo.render.eval.drawableSpaceMapping +import org.umamo.runtime.model.partByDrawable +import java.io.File +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Deformer delete must unwrap (bake) without removing parts or destroying the drawable's world pose. + */ +class WarpDeleteKeepsPartTest { + private fun span(points: FloatArray): Pair { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var index = 0 + while (index + 1 < points.size) { + minX = min(minX, points[index]) + maxX = max(maxX, points[index]) + minY = min(minY, points[index + 1]) + maxY = max(maxY, points[index + 1]) + index += 2 + } + return (maxX - minX) to (maxY - minY) + } + + @Test + fun createThenDeleteWarpKeepsPartAndWorldPose() { + val file = File("/home/litruv/dev/vtsmaker/Bear_.cmo3") + if (!file.isFile) { + return + } + val puppet = Cmo3Import.fromModelSource(Cmo3.read(file).root as CModelSource) + // A smaller mesh under Warp16 so an unbaked unwrap would stretch it across the parent lattice. + val pick = + puppet.drawables.first { drawable -> + drawable.parentDeformerId?.raw == "Warp16" && + drawable.mesh != null && + drawable.id.raw != "Jumper" + } + val owner = assertNotNull(puppet.partByDrawable()[pick.id]) + val partsBefore = puppet.parts.map { it.id }.toSet() + val pose = puppet.parameters.associate { it.id to it.default } + val beforeWorld = + drawableSpaceMapping(puppet, pose, pick.id)!!.localToWorld(drawableLocalPosed(puppet, pose, pick.id)!!) + val (beforeSpanX, beforeSpanY) = span(beforeWorld) + + val session = EditorSession(puppet) + session.setSelection(Selection(setOf(SelectionTarget.Drawable(pick.id)), SelectionTarget.Drawable(pick.id))) + val warpId = assertNotNull(session.createWarpDeformerForSelection("Warp Deformer")) + session.deleteDeformer(warpId) + + val after = session.model.value + assertEquals(partsBefore, after.parts.map { it.id }.toSet()) + assertTrue(after.parts.any { it.id == owner }) + assertTrue(after.deformers.none { it.id == warpId }) + assertEquals(pick.parentDeformerId, after.drawables.first { it.id == pick.id }.parentDeformerId) + + val afterWorld = + drawableSpaceMapping(after, pose, pick.id)!!.localToWorld(drawableLocalPosed(after, pose, pick.id)!!) + val (afterSpanX, afterSpanY) = span(afterWorld) + assertTrue(abs(afterSpanX - beforeSpanX) / beforeSpanX < 0.05f, "spanX before=$beforeSpanX after=$afterSpanX") + assertTrue(abs(afterSpanY - beforeSpanY) / beforeSpanY < 0.05f, "spanY before=$beforeSpanY after=$afterSpanY") + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpReparentKeepsPoseTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpReparentKeepsPoseTest.kt new file mode 100644 index 0000000..e8a33b1 --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/WarpReparentKeepsPoseTest.kt @@ -0,0 +1,94 @@ +package org.umamo.edit + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.render.eval.warpLatticeLocalAt +import org.umamo.render.eval.warpLatticeSpaceMapping +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import java.io.File +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Reparenting a warp must convert its lattice into the new parent space so the world pose stays put. + */ +class WarpReparentKeepsPoseTest { + private fun span(points: FloatArray): Pair { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var index = 0 + while (index + 1 < points.size) { + minX = min(minX, points[index]) + maxX = max(maxX, points[index]) + minY = min(minY, points[index + 1]) + maxY = max(maxY, points[index + 1]) + index += 2 + } + return (maxX - minX) to (maxY - minY) + } + + private fun worldLattice(model: org.umamo.runtime.model.PuppetModel, id: DeformerId): FloatArray { + val pose = model.parameters.associate { it.id to it.default } + val local = assertNotNull(warpLatticeLocalAt(model, pose, id)) + val mapping = assertNotNull(warpLatticeSpaceMapping(model, pose, id)) + return mapping.localToWorld(local) + } + + @Test + fun nestingRootWarpUnderAnotherKeepsWorldSpan() { + val file = File("/home/litruv/dev/vtsmaker/Bear_.cmo3") + if (!file.isFile) { + return + } + val puppet = Cmo3Import.fromModelSource(Cmo3.read(file).root as CModelSource) + val rootWarps = puppet.deformers.filterIsInstance().filter { it.parent == null } + assertTrue(rootWarps.size >= 2) + val moving = rootWarps.first { it.id.raw != "Warp16" } + val host = rootWarps.first { it.id.raw == "Warp16" } + val before = worldLattice(puppet, moving.id) + val (beforeX, beforeY) = span(before) + + val afterModel = puppet.withDeformerMoved(moving.id, host.id, beforeId = null) + assertTrue(afterModel.deformers.first { it.id == moving.id }.parent == host.id) + val after = worldLattice(afterModel, moving.id) + val (afterX, afterY) = span(after) + assertTrue(abs(afterX - beforeX) / max(beforeX, 1f) < 0.08f, "spanX before=$beforeX after=$afterX") + assertTrue(abs(afterY - beforeY) / max(beforeY, 1f) < 0.08f, "spanY before=$beforeY after=$afterY") + // Local CPs must now be parent-UV scale, not leftover canvas units. + val pose = afterModel.parameters.associate { it.id to it.default } + val local = assertNotNull(warpLatticeLocalAt(afterModel, pose, moving.id)) + for (value in local) { + assertTrue(value in -1f..2f, "local cp $value should be UV under Warp16") + } + } + + @Test + fun promotingChildWarpToRootKeepsWorldSpan() { + val file = File("/home/litruv/dev/vtsmaker/Bear_.cmo3") + if (!file.isFile) { + return + } + val puppet = Cmo3Import.fromModelSource(Cmo3.read(file).root as CModelSource) + val host = puppet.deformers.filterIsInstance().first { it.id.raw == "Warp16" } + val moving = puppet.deformers.filterIsInstance().first { it.parent == null && it.id != host.id } + val nested = puppet.withDeformerMoved(moving.id, host.id, beforeId = null) + val before = worldLattice(nested, moving.id) + val (beforeX, beforeY) = span(before) + + val promoted = nested.withDeformerMoved(moving.id, newParentId = null, beforeId = null) + assertNull(promoted.deformers.first { it.id == moving.id }.parent) + val after = worldLattice(promoted, moving.id) + val (afterX, afterY) = span(after) + assertTrue(abs(afterX - beforeX) / max(beforeX, 1f) < 0.08f, "spanX before=$beforeX after=$afterX") + assertTrue(abs(afterY - beforeY) / max(beforeY, 1f) < 0.08f, "spanY before=$beforeY after=$afterY") + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportCreationRoundTripTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportCreationRoundTripTest.kt new file mode 100644 index 0000000..cc8825a --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportCreationRoundTripTest.kt @@ -0,0 +1,181 @@ +package org.umamo.edit.export + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3.Cmo3Export +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The Created-path gate: session-created parts, deformers, and glues synthesize identity shells + * and lower through the ordinary Changed path, surviving an export/re-import with no notices and + * no residual diff. (Created parameters, groups, and duplicated drawables are covered by + * Cmo3ExportStructureRoundTripTest; the fresh-graph drawable binding path is covered by the + * MOC3-conversion round trip in :interop.) + */ +class Cmo3ExportCreationRoundTripTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private class RoundTrip( + val edited: PuppetModel, + val reimported: PuppetModel, + val report: ExportReport, + ) + + private fun roundTrip(file: File, edit: (PuppetModel) -> PuppetModel): RoundTrip { + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val edited = edit(Cmo3Import.fromModelSource(modelSource)) + val report = Cmo3Export.apply(edited, cmo3) + val reimportedSource = + Cmo3.read(Cmo3.write(cmo3)).root as? CModelSource ?: error("re-read root is not a CModelSource") + return RoundTrip(edited, Cmo3Import.fromModelSource(reimportedSource), report) + } + + private fun assertLossless(result: RoundTrip, label: String) { + assertTrue(result.report.isEmpty, "$label: expected no notices, got ${result.report.notices}") + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(residual.isEmpty, "$label: edits lost through export/import: $residual") + } + + private fun skipMessageOrNull(): File? { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping creation round-trip test") + } + return file + } + + @Test + fun createdPartRoundTrips() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val fresh = + Part( + id = PartId("UmamoCreatedPart"), + name = "Created Part", + children = emptyList(), + drawOrder = 480, + ) + puppet.copy( + parts = puppet.parts + fresh, + rootChildren = puppet.rootChildren + OrgChild.Part(fresh.id), + ) + } + assertLossless(result, "created part") + } + + @Test + fun createdWarpDeformerRoundTrips() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + // Clone the lattice shape from an existing warp so the control-point count matches + // the dimensions the official format expects for that grid size. + val template = puppet.deformers.filterIsInstance().first { it.geometryGrid != null } + val templateForm = template.geometryGrid!!.cells.first().form + val axisParameter = puppet.parameters.first { it.max - it.min >= 1f } + val nudged = templateForm.controlPoints.copyOf().also { points -> points[0] += 5f } + val fresh = + Deformer.Warp( + id = DeformerId("UmamoCreatedWarp"), + name = "Created Warp", + parent = null, + partId = puppet.parts.first().id, + rows = template.rows, + columns = template.columns, + isQuadTransform = template.isQuadTransform, + geometryGrid = + KeyformGrid( + listOf( + KeyformAxis( + axisParameter.id, + floatArrayOf(axisParameter.min, axisParameter.max), + ), + ), + listOf( + KeyformCell(intArrayOf(0), WarpLatticeForm(templateForm.controlPoints.copyOf())), + KeyformCell(intArrayOf(1), WarpLatticeForm(nudged)), + ), + ), + ) + puppet.copy(deformers = puppet.deformers + fresh) + } + assertLossless(result, "created warp deformer") + } + + @Test + fun createdRotationDeformerRoundTrips() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val axisParameter = puppet.parameters.first { it.max - it.min >= 1f } + val fresh = + Deformer.Rotation( + id = DeformerId("UmamoCreatedRotation"), + name = "Created Rotation", + parent = null, + partId = puppet.parts.first().id, + baseAngle = 15f, + geometryGrid = + KeyformGrid( + listOf( + KeyformAxis( + axisParameter.id, + floatArrayOf(axisParameter.min, axisParameter.max), + ), + ), + listOf( + KeyformCell(intArrayOf(0), RotationPivotForm(100f, 200f, 0f, 1f)), + KeyformCell(intArrayOf(1), RotationPivotForm(100f, 200f, 30f, 1.25f)), + ), + ), + ) + puppet.copy(deformers = puppet.deformers + fresh) + } + assertLossless(result, "created rotation deformer") + } + + @Test + fun createdGlueRoundTrips() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + // Weld the first two drawables that have enough vertices; the static intensity stays + // at the 1f default (the only static CMO3 can express without a form). + val candidates = puppet.drawables.filter { drawable -> (drawable.mesh?.positions?.size ?: 0) >= 6 } + val meshA = candidates[0] + val meshB = candidates[1] + val fresh = + Glue( + meshA = meshA.id, + meshB = meshB.id, + pairs = + listOf( + GluePair(indexA = 0, indexB = 0, weightA = 0.5f, weightB = 0.5f), + GluePair(indexA = 1, indexB = 1, weightA = 0.25f, weightB = 0.75f), + ), + ) + puppet.copy(glues = puppet.glues + fresh) + } + assertLossless(result, "created glue") + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportKeyformRoundTripTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportKeyformRoundTripTest.kt new file mode 100644 index 0000000..caca218 --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportKeyformRoundTripTest.kt @@ -0,0 +1,522 @@ +package org.umamo.edit.export + +import org.umamo.edit.withDrawableOpacity +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.DrawableField +import org.umamo.interop.EntityDiff +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3.Cmo3Export +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.keyform.MeshDeltaInterpolator +import org.umamo.runtime.keyform.OutOfSpanKeyPolicy +import org.umamo.runtime.keyform.withKeyInserted +import org.umamo.runtime.keyform.withKeyRemoved +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The keyform-lowering gate: keyform value edits, key inserts/deletes, channel-track edits, and + * statics reconcile onto the CMO3 grid web and survive an export/re-import. Channel values and + * key deletions round-trip bit-exact (values pass through unchanged; surviving forms keep their + * stored absolutes). Drawable GEOMETRY tolerates bounded ULP on edited/inserted cells only: CMO3 + * stores absolutes, Umamo deltas, and (base + delta) - base is not an IEEE identity - the same + * bounded-ULP tier the fidelity contract already assigns to geometry. + */ +class Cmo3ExportKeyformRoundTripTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private class RoundTrip( + val edited: PuppetModel, + val reimported: PuppetModel, + val report: ExportReport, + ) + + private fun roundTrip(file: File, edit: (PuppetModel) -> PuppetModel): RoundTrip { + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val edited = edit(Cmo3Import.fromModelSource(modelSource)) + val report = Cmo3Export.apply(edited, cmo3) + val reimportedSource = + Cmo3.read(Cmo3.write(cmo3)).root as? CModelSource ?: error("re-read root is not a CModelSource") + return RoundTrip(edited, Cmo3Import.fromModelSource(reimportedSource), report) + } + + private fun assertLossless(result: RoundTrip, label: String) { + assertTrue(result.report.isEmpty, "$label: expected no notices, got ${result.report.notices}") + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(residual.isEmpty, "$label: edits lost through export/import: $residual") + } + + /** + * Asserts the round trip is clean except, at most, a bounded-ULP GEOMETRY residue on the one + * edited drawable (the delta-vs-absolute conversion tier). + * + * @param RoundTrip result The edited/reimported model pair and export report under test. + * @param DrawableId drawableId The one drawable allowed to carry the tolerated residue. + * @param String label Test-scenario label used in assertion failure messages. + */ + private fun assertLosslessWithinGeometryUlp(result: RoundTrip, drawableId: DrawableId, label: String) { + assertTrue(result.report.isEmpty, "$label: expected no notices, got ${result.report.notices}") + val residual = diffPuppetModels(result.reimported, result.edited) + if (residual.isEmpty) { + return + } + val onlyExpectedResidue = + residual.parameters.isEmpty() && + residual.parameterGroups.isEmpty() && + residual.parts.isEmpty() && + residual.deformers.isEmpty() && + residual.glues.isEmpty() && + residual.document.isEmpty() && + residual.drawables.all { entityDiff -> + entityDiff is EntityDiff.Changed && + entityDiff.id == drawableId && + entityDiff.fields == setOf(DrawableField.GEOMETRY) + } + assertTrue(onlyExpectedResidue, "$label: unexpected residual $residual") + val editedGrid = result.edited.drawables.first { it.id == drawableId }.geometryGrid + val reimportedGrid = result.reimported.drawables.first { it.id == drawableId }.geometryGrid + assertTrue(editedGrid != null && reimportedGrid != null, "$label: geometry grid vanished") + val reimportedByCoordinate = + reimportedGrid.cells.associate { cell -> cell.coordinate.toList() to cell.form.positionDeltas } + var maxComponentDifference = 0f + for (cell in editedGrid.cells) { + val reimportedDeltas = reimportedByCoordinate[cell.coordinate.toList()] + assertTrue(reimportedDeltas != null, "$label: cell ${cell.coordinate.toList()} vanished") + for (component in cell.form.positionDeltas.indices) { + maxComponentDifference = + maxOf( + maxComponentDifference, + abs(cell.form.positionDeltas[component] - reimportedDeltas[component]), + ) + } + } + assertTrue(maxComponentDifference < 1e-3f, "$label: geometry drifted by $maxComponentDifference") + } + + private fun skipMessageOrNull(): File? { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping keyform round-trip test") + } + return file + } + + /** + * The first corpus file whose imported model satisfies [predicate] - the channel-track cases + * search the whole probe corpus because compaction leaves many models with statics only. + * + * @param Function predicate The feature the test needs. + * @return File? The matching file, or null (after a skip message) when no corpus model has it. + */ + private fun firstProbeFileWith(predicate: (PuppetModel) -> Boolean): File? { + val spec = System.getProperty("cmo3.probe") ?: System.getProperty("cmo3.sample") + if (spec == null) { + println("cmo3.probe not present; skipping") + return null + } + for (candidate in spec.split(',').map { File(it.trim()) }.filter { it.isFile }) { + val imported = + runCatching { + Cmo3Import.fromModelSource(Cmo3.read(candidate.readBytes()).root as CModelSource) + }.getOrNull() ?: continue + if (predicate(imported)) { + return candidate + } + } + println("no corpus model has the feature; skipping") + return null + } + + /** + * The first drawable with a multi-key geometry grid, for the grid-edit cases. + * + * @param PuppetModel puppet The model to search. + * @return Drawable The first matching drawable. + */ + private fun keyedDrawable(puppet: PuppetModel) = + puppet.drawables.first { drawable -> + val grid = drawable.geometryGrid + grid != null && grid.axes.isNotEmpty() && grid.axes.first().keys.size >= 3 && grid.cells.isNotEmpty() + } + + @Test + fun keyformGeometryNudgeSurvivesWithinUlp() { + val file = skipMessageOrNull() ?: return + var editedId: DrawableId? = null + val result = + roundTrip(file) { puppet -> + val drawable = keyedDrawable(puppet) + editedId = drawable.id + val grid = drawable.geometryGrid!! + val nudgedCells = + grid.cells.mapIndexed { cellIndex, cell -> + if (cellIndex == 0) { + val nudged = cell.form.positionDeltas.copyOf() + if (nudged.isNotEmpty()) { + nudged[0] += 2f + } + KeyformCell(cell.coordinate, MeshDeltaForm(nudged)) + } else { + cell + } + } + puppet.copy( + drawables = + puppet.drawables.map { candidate -> + if (candidate.id == drawable.id) { + candidate.copy(geometryGrid = KeyformGrid(grid.axes, nudgedCells)) + } else { + candidate + } + }, + ) + } + assertLosslessWithinGeometryUlp(result, editedId!!, "keyform nudge") + } + + @Test + fun geometryKeyInsertSurvivesWithinUlp() { + val file = skipMessageOrNull() ?: return + var editedId: DrawableId? = null + val result = + roundTrip(file) { puppet -> + val drawable = keyedDrawable(puppet) + editedId = drawable.id + val grid = drawable.geometryGrid!! + val axis = grid.axes.first() + val midValue = (axis.keys[0] + axis.keys[1]) / 2f + val inserted = + grid.withKeyInserted(axis.parameterId, midValue, MeshDeltaInterpolator, OutOfSpanKeyPolicy.Reject) + puppet.copy( + drawables = + puppet.drawables.map { candidate -> + if (candidate.id == drawable.id) candidate.copy(geometryGrid = inserted) else candidate + }, + ) + } + assertLosslessWithinGeometryUlp(result, editedId!!, "key insert") + } + + @Test + fun geometryKeyDeleteSurvivesExactly() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val drawable = keyedDrawable(puppet) + val grid = drawable.geometryGrid!! + val axis = grid.axes.first() + // A middle key: removal keeps the span, and every surviving cell keeps its stored + // form - the deletion round trip is bit-exact. + val removed = grid.withKeyRemoved(axis.parameterId, keyIndex = 1) + puppet.copy( + drawables = + puppet.drawables.map { candidate -> + if (candidate.id == drawable.id) candidate.copy(geometryGrid = removed) else candidate + }, + ) + } + assertLossless(result, "key delete") + } + + @Test + fun warpOpacityChannelEditSurvivesExactly() { + val file = + firstProbeFileWith { probe -> + probe.deformers.any { it is Deformer.Warp && it.channelGrids[FormChannel.OPACITY] != null } + } ?: return + val result = + roundTrip(file) { puppet -> + val warp = + puppet.deformers.first { it is Deformer.Warp && it.channelGrids[FormChannel.OPACITY] != null } + as Deformer.Warp + val track = warp.channelGrids[FormChannel.OPACITY]!! + val editedCells = + track.cells.mapIndexed { cellIndex, cell -> + if (cellIndex == 0) { + KeyformCell( + cell.coordinate, + ChannelValue.Scalar(0.37f) as ChannelValue, + ) + } else { + cell + } + } + val editedGrids = + ChannelGrids( + warp.channelGrids.gridsByChannel + ( + FormChannel.OPACITY to + KeyformGrid( + track.axes, + editedCells, + ) + ), + ) + puppet.copy( + deformers = + puppet.deformers.map { candidate -> + if (candidate.id == warp.id) warp.copy(channelGrids = editedGrids) else candidate + }, + ) + } + assertLossless(result, "warp opacity channel edit") + } + + @Test + fun drawableStaticOpacityEditSurvivesExactly() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + // A drawable with keyforms but no opacity track: the static's CMO3 home is every + // form cell, which the grid rebuild writes. + val drawable = + puppet.drawables.first { candidate -> + candidate.geometryGrid != null && + candidate.geometryGrid!!.cells.isNotEmpty() && + candidate.channelGrids[FormChannel.OPACITY] == null + } + puppet.withDrawableOpacity(drawable.id, 0.5f) + } + assertLossless(result, "drawable static opacity") + } + + @Test + fun partDrawOrderTrackSurvivesExactly() { + val file = skipMessageOrNull() ?: return + // No corpus model keeps a part draw-order track after compaction, so AUTHOR one: a fresh + // axis and varying values, exercising whole-web synthesis (new binding, fresh CPartForms). + val result = + roundTrip(file) { puppet -> + val part = puppet.parts.first { it.channelGrids.isEmpty } + val axisParameter = puppet.parameters.first { it.max - it.min >= 1f } + val track = + KeyformGrid( + listOf(KeyformAxis(axisParameter.id, floatArrayOf(axisParameter.min, axisParameter.max))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(part.drawOrder.toFloat()) as ChannelValue), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(part.drawOrder + 3f) as ChannelValue), + ), + ) + puppet.copy( + parts = + puppet.parts.map { candidate -> + if (candidate.id == part.id) { + part.copy(channelGrids = ChannelGrids(mapOf(FormChannel.DRAW_ORDER to track))) + } else { + candidate + } + }, + ) + } + assertLossless(result, "part draw-order track") + } + + @Test + fun glueIntensityTrackSurvivesExactly() { + val file = + firstProbeFileWith { probe -> probe.glues.isNotEmpty() } ?: return + // No corpus model keeps an intensity track after compaction, so AUTHOR one on an existing + // glue: a fresh axis with varying weld strength. + val result = + roundTrip(file) { puppet -> + val glueIndex = 0 + val glue = puppet.glues[glueIndex] + val axisParameter = puppet.parameters.first { it.max - it.min >= 1f } + val track = + KeyformGrid( + listOf(KeyformAxis(axisParameter.id, floatArrayOf(axisParameter.min, axisParameter.max))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(1f) as ChannelValue), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(0.5f) as ChannelValue), + ), + ) + val editedGlue = + org.umamo.runtime.model.Glue( + glue.meshA, + glue.meshB, + glue.pairs, + ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to track)), + glue.intensity, + ) + puppet.copy(glues = puppet.glues.mapIndexed { candidateIndex, candidate -> if (candidateIndex == glueIndex) editedGlue else candidate }) + } + assertLossless(result, "glue intensity track") + } + + @Test + fun blendShapeDeltaNudgeSurvivesWithinUlp() { + val file = + firstProbeFileWith { probe -> + probe.drawables.any { drawable -> drawable.blendShapes.any { binding -> binding.forms.any { it != null } } } + } ?: return + var editedId: DrawableId? = null + val result = + roundTrip(file) { puppet -> + val drawable = + puppet.drawables.first { candidate -> candidate.blendShapes.any { binding -> binding.forms.any { it != null } } } + editedId = drawable.id + val editedBindings = + drawable.blendShapes.mapIndexed { bindingIndex, binding -> + if (bindingIndex != 0) { + return@mapIndexed binding + } + val formIndex = binding.forms.indexOfFirst { it != null } + val editedForms = + binding.forms.mapIndexed { candidateIndex, form -> + if (candidateIndex == formIndex && form != null) { + val nudged = form.positionDeltas.copyOf() + if (nudged.isNotEmpty()) { + nudged[0] += 2f + } + org.umamo.runtime.model.MeshForm( + nudged, + form.drawOrder, + form.opacity, + form.multiplyColor, + form.screenColor, + ) + } else { + form + } + } + BlendShapeBinding( + binding.parameterId, + binding.keys, + binding.neutralIndex, + editedForms, + binding.limits, + ) + } + puppet.copy( + drawables = + puppet.drawables.map { candidate -> + if (candidate.id == drawable.id) candidate.copy(blendShapes = editedBindings) else candidate + }, + ) + } + // The morph rebuild reuses matched records/forms; the nudged form's absolute follows the + // delta-vs-absolute tier, so BLEND_SHAPES may carry bounded-ULP residue like GEOMETRY. + assertTrue(result.report.isEmpty, "blend shape nudge: expected no notices, got ${result.report.notices}") + val residual = diffPuppetModels(result.reimported, result.edited) + val acceptable = + residual.isEmpty || + ( + residual.parameters.isEmpty() && + residual.parameterGroups.isEmpty() && + residual.parts.isEmpty() && + residual.deformers.isEmpty() && + residual.glues.isEmpty() && + residual.document.isEmpty() && + residual.drawables.all { entityDiff -> + entityDiff is EntityDiff.Changed && + entityDiff.id == editedId && + entityDiff.fields.all { it == DrawableField.BLEND_SHAPES || it == DrawableField.GEOMETRY } + } + ) + assertTrue(acceptable, "blend shape nudge: unexpected residual $residual") + } + + @Test + fun baseMoveWithKeyformEditKeepsBlendShapeDeltas() { + // The combined base-move + keyform-edit path writes the base through the grid rebuild + // (alsoWriteBase) instead of lowerMeshPositions' pool-wide rebase, so the surviving + // morph-target forms must follow the base move on their own - a stale absolute shifts every + // re-imported blend-shape delta by the move distance. + val file = + firstProbeFileWith { probe -> + probe.drawables.any { drawable -> + drawable.mesh != null && + drawable.geometryGrid != null && + drawable.geometryGrid!!.cells.isNotEmpty() && + drawable.blendShapes.any { binding -> binding.forms.any { form -> form != null } } + } + } ?: return + var editedId: DrawableId? = null + val result = + roundTrip(file) { puppet -> + val drawable = + puppet.drawables.first { candidate -> + candidate.mesh != null && + candidate.geometryGrid != null && + candidate.geometryGrid!!.cells.isNotEmpty() && + candidate.blendShapes.any { binding -> binding.forms.any { form -> form != null } } + } + editedId = drawable.id + val mesh = drawable.mesh!! + val movedPositions = mesh.positions.copyOf() + movedPositions[0] += 5f + val grid = drawable.geometryGrid!! + val nudgedCells = + grid.cells.mapIndexed { cellIndex, cell -> + if (cellIndex == 0) { + val nudged = cell.form.positionDeltas.copyOf() + if (nudged.isNotEmpty()) { + nudged[0] += 2f + } + KeyformCell(cell.coordinate, MeshDeltaForm(nudged)) + } else { + cell + } + } + puppet.copy( + drawables = + puppet.drawables.map { candidate -> + if (candidate.id == drawable.id) { + candidate.copy( + mesh = DrawableMesh(movedPositions, mesh.uvs, mesh.indices), + geometryGrid = KeyformGrid(grid.axes, nudgedCells), + ) + } else { + candidate + } + }, + ) + } + // The base move leaves the imported weld by definition; nothing else may be reported. + assertTrue( + result.report.notices.all { notice -> notice is ExportNotice.WeldDivergence }, + "base move + keyform edit: unexpected notices ${result.report.notices}", + ) + val editedDrawable = result.edited.drawables.first { it.id == editedId } + val reimportedDrawable = result.reimported.drawables.first { it.id == editedId } + assertTrue( + reimportedDrawable.blendShapes.size == editedDrawable.blendShapes.size, + "base move + keyform edit: blend-shape binding count changed", + ) + var maxDeltaDrift = 0f + for (bindingIndex in editedDrawable.blendShapes.indices) { + val editedBinding = editedDrawable.blendShapes[bindingIndex] + val reimportedBinding = reimportedDrawable.blendShapes[bindingIndex] + for (formIndex in editedBinding.forms.indices) { + val editedForm = editedBinding.forms[formIndex] ?: continue + val reimportedForm = reimportedBinding.forms.getOrNull(formIndex) + assertTrue(reimportedForm != null, "base move + keyform edit: blend-shape form $formIndex vanished") + for (component in editedForm.positionDeltas.indices) { + maxDeltaDrift = + maxOf( + maxDeltaDrift, + abs(editedForm.positionDeltas[component] - reimportedForm.positionDeltas[component]), + ) + } + } + } + assertTrue(maxDeltaDrift < 1e-3f, "base move + keyform edit: blend-shape deltas drifted by $maxDeltaDrift") + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportRepackTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportRepackTest.kt new file mode 100644 index 0000000..054e477 --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportRepackTest.kt @@ -0,0 +1,507 @@ +package org.umamo.edit.export + +import org.umamo.edit.withAtlasPlacement +import org.umamo.edit.withAtlasPlacements +import org.umamo.edit.withAtlasRepack +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3.Cmo3Conversion +import org.umamo.interop.cmo3.Cmo3Export +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The recomposed-page export gate over the atlas-web reconcile: a repack's pages replace the file's + * stored page images (clearing the stale-page notice), a resize updates every dimension field + * including the cached-image manager's padding diagonal, a page-count growth mints an atlas and + * re-homes the moved entries with their drawables retargeted, an unbound pack-out removes its + * entry - while a page inventory disagreeing with the edited model, or a pack-out a drawable still + * binds, declines the WHOLE reconcile and keeps the honest notices. + */ +class Cmo3ExportRepackTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private fun skipMessageOrNull(): File? { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping export repack test") + } + return file + } + + /** A tiny valid PNG whose bytes are recognizably NOT any corpus page. */ + private fun markerPng(): ByteArray { + val rgba = ByteArray(2 * 2 * 4) { pixelByte -> (pixelByte * 17 + 3).toByte() } + return PngCodec.write(RasterImage(2, 2, rgba)) + } + + /** The page resources in _textureAtlases order - the model's own page numbering. */ + private fun pageResourcesOf(modelSource: CModelSource): List> { + val textureManager = modelSource.textureManager as? CTextureManager ?: return emptyList() + return elementsOf(textureManager._textureAtlases) + .filterIsInstance() + .mapNotNull { atlas -> (atlas.cachedAtlasImage as? CImageResource)?.let { resource -> atlas to resource } } + } + + private fun elementsOf(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun hasStalePageNotice(report: ExportReport): Boolean = + report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.AtlasPageNotRecomposed + } + + /** Opens the sample and applies a same-page placement nudge, or null when it packs nothing. */ + private fun nudgedSample(file: File): Triple? { + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val packed = imported.atlas.tiles.firstOrNull { tile -> tile.placement != null } + if (packed == null) { + println("${file.name} packs no artwork; skipping the repack export gate") + return null + } + val moved = packed.placement!!.copy(positionX = packed.placement!!.positionX + 8f) + return Triple(cmo3, imported.withAtlasPlacement(packed.id, moved), imported.atlas.pages.size) + } + + @Test + fun aSameMembershipPatchClearsTheNoticeAndLandsInTheArchive() { + val file = skipMessageOrNull() ?: return + val (cmo3, edited, _) = nudgedSample(file) ?: return + val modelSource = cmo3.root as CModelSource + val resources = pageResourcesOf(modelSource) + assertTrue(resources.isNotEmpty(), "the sample stores its pages") + val marker = markerPng() + // Same dimensions, so only the bytes move - the resize fields have their own gate below. + val pages = + resources.map { (_, resource) -> + Cmo3Conversion.AtlasPage(marker, resource.width, resource.height) + } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertFalse(hasStalePageNotice(report), "patched pages are not stale: ${report.notices}") + val rereadSource = Cmo3.read(Cmo3.write(cmo3)).root as? CModelSource ?: error("re-read root is not a CModelSource") + val rereadCmo3 = Cmo3.read(Cmo3.write(cmo3)) + for ((_, resource) in pageResourcesOf(rereadCmo3.root as CModelSource)) { + assertContentEquals(marker, rereadCmo3.extractLayerPng(resource), "the archive serves the recomposed bytes by name") + } + assertNotNull(rereadSource, "the patched file still parses") + } + + @Test + fun aResizedPatchUpdatesEveryDimensionField() { + val file = skipMessageOrNull() ?: return + val (cmo3, edited, _) = nudgedSample(file) ?: return + val modelSource = cmo3.root as CModelSource + val resources = pageResourcesOf(modelSource) + val marker = markerPng() + val pages = + resources.map { (_, resource) -> + Cmo3Conversion.AtlasPage(marker, resource.width / 2, resource.height / 2) + } + val expectedDims = pages.map { page -> page.width to page.height } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertFalse(hasStalePageNotice(report)) + val reread = pageResourcesOf(Cmo3.read(Cmo3.write(cmo3)).root as CModelSource) + for ((pageIndex, pair) in reread.withIndex()) { + val (atlas, resource) = pair + val (expectedWidth, expectedHeight) = expectedDims[pageIndex] + // CMO3: CImageResource fields width / height. + assertEquals(expectedWidth, resource.width, "resource width follows the recomposed page") + assertEquals(expectedHeight, resource.height) + // CMO3: CTextureAtlas fields width / height. + assertEquals(expectedWidth, atlas.width, "atlas width follows the recomposed page") + assertEquals(expectedHeight, atlas.height) + // CMO3: CCachedImage field transformRawImageToCachedImage - rawDim / ceil64(rawDim) per + // axis; identity here is the documented squished-art symptom, so this is the mutation gate. + val manager = assertNotNull(atlas.cachedImageManager as? CCachedImageManager) + val cached = assertNotNull(elementsOf(manager.cachedImages).filterIsInstance().firstOrNull()) + val diagonal = assertNotNull(cached.transformRawImageToCachedImage as? CAffine) + assertEquals(expectedWidth.toFloat() / ((expectedWidth + 63) / 64 * 64), diagonal.m00, 1e-6f) + assertEquals(expectedHeight.toFloat() / ((expectedHeight + 63) / 64 * 64), diagonal.m11, 1e-6f) + } + } + + @Test + fun pagesDisagreeingWithTheEditedModelsPageCountDeclineWhole() { + val file = skipMessageOrNull() ?: return + val (cmo3, edited, _) = nudgedSample(file) ?: return + val modelSource = cmo3.root as CModelSource + val resources = pageResourcesOf(modelSource) + val originalBytes = resources.map { (_, resource) -> assertNotNull(cmo3.extractLayerPng(resource)) } + val marker = markerPng() + // One page more than the EDITED model tracks: the pages are the repack's own output, so a + // count disagreeing with the model is caller inconsistency and declines whole. + val pages = + List(resources.size + 1) { Cmo3Conversion.AtlasPage(marker, 64, 64) } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertTrue(hasStalePageNotice(report), "an unpatchable page set keeps the honest notice") + val rereadCmo3 = Cmo3.read(Cmo3.write(cmo3)) + for ((pageIndex, pair) in pageResourcesOf(rereadCmo3.root as CModelSource).withIndex()) { + assertContentEquals( + originalBytes[pageIndex], + rereadCmo3.extractLayerPng(pair.second), + "a declined patch leaves the stored pages byte-identical", + ) + } + } + + /** One tile's entry inside [atlas], or null. */ + private fun entryIn(atlas: CTextureAtlas, tileId: String): ModelImageEntry? = + elementsOf(atlas.modelImages) + .filterIsInstance() + .firstOrNull { entry -> (entry.modelImageGuid as? Guid)?.uuid == tileId } + + /** The drawable source with [drawableId], or null. */ + private fun drawableSourceOf(modelSource: CModelSource, drawableId: String): CArtMeshSource? = + elementsOf((modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + .firstOrNull { source -> (source.id as? Id)?.idstr == drawableId } + + @Test + fun aPageCountGrowthMintsAnAtlasAndRehomesMovedEntries() { + val file = skipMessageOrNull() ?: return + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val boundTileIds = imported.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val movers = imported.atlas.tiles.filter { tile -> tile.placement != null && tile.id in boundTileIds }.take(2) + if (movers.size < 2) { + println("${file.name} packs too little bound artwork; skipping the growth gate") + return + } + val newPages = imported.atlas.pages + AtlasPage(512, 512) + val mintedPageIndex = newPages.size - 1 + val placements = + imported.atlas.tiles.associateTo(HashMap()) { tile -> tile.id to tile.placement } + placements[movers[0].id] = AtlasPlacement(mintedPageIndex, 16f, 16f, 1f, 1f, 0f) + placements[movers[1].id] = AtlasPlacement(mintedPageIndex, 260f, 260f, 1f, 1f, 0f) + val edited = imported.withAtlasRepack(newPages, placements) + val marker = markerPng() + val pages = + newPages.map { page -> Cmo3Conversion.AtlasPage(marker, page.width, page.height) } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertFalse(hasStalePageNotice(report), "a full reconcile owes no stale-page notice: ${report.notices}") + assertFalse( + report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.NoAtlasEntryToReconcile + }, + "every moved entry reconciled: ${report.notices}", + ) + val rereadCmo3 = Cmo3.read(Cmo3.write(cmo3)) + val rereadSource = rereadCmo3.root as CModelSource + val atlases = pageResourcesOf(rereadSource).map { (atlas, _) -> atlas } + assertEquals(newPages.size, atlases.size, "the page count grew") + val minted = atlases.last() + // CMO3: CTextureAtlas fields name / width / height / guid / cachedImageManager. + assertEquals("TextureAtlas${newPages.size}", minted.name) + assertEquals(512, minted.width) + assertEquals(512, minted.height) + assertNotNull(minted.guid, "the minted atlas carries a guid") + val mintedResource = assertNotNull(minted.cachedAtlasImage as? CImageResource) + assertContentEquals(marker, rereadCmo3.extractLayerPng(mintedResource), "the minted page PNG serves by name") + val manager = assertNotNull(minted.cachedImageManager as? CCachedImageManager) + val cached = assertNotNull(elementsOf(manager.cachedImages).filterIsInstance().firstOrNull()) + val diagonal = assertNotNull(cached.transformRawImageToCachedImage as? CAffine) + assertEquals(1f, diagonal.m00, 1e-6f, "512 is 64-aligned, so the padding diagonal is one") + + for (mover in movers) { + val entry = assertNotNull(entryIn(minted, mover.id.raw), "'${mover.name}' re-homed into the minted atlas") + assertSame(minted, entry.atlas, "and carries the owning-page back-reference") + val entryHalf = assertNotNull(entry.atlasLocalToCanvasTransform as? CAffine) + for (drawable in edited.drawables.filter { candidate -> candidate.atlasTileId == mover.id }) { + val source = assertNotNull(drawableSourceOf(rereadSource, drawable.id.raw)) + val texture = assertNotNull(source.texture as? GTexture2D, "the mover samples a texture") + assertSame( + mintedResource, + texture.srcImageResource, + "'${drawable.id.raw}' samples the minted page's own resource", + ) + val extension = + assertNotNull(elementsOf(source._extensions).filterIsInstance().firstOrNull()) + val region = + assertNotNull( + elementsOf(extension._textureInputs).filterIsInstance().firstOrNull(), + ) + assertEquals( + (minted.guid as? Guid)?.uuid, + (region.textureAtlasGuid as? Guid)?.uuid, + "the region input names the minted page", + ) + val input = assertNotNull(region.inputImageLocalToCanvasTransform as? CAffine) + assertEquals(entryHalf.m00, input.m00, 1e-3f) + assertEquals(entryHalf.m02, input.m02, 1e-1f) + assertEquals(entryHalf.m11, input.m11, 1e-3f) + assertEquals(entryHalf.m12, input.m12, 1e-1f) + } + } + + val reimported = Cmo3Import.fromModelSource(rereadSource) + assertEquals(newPages.size, reimported.atlas.pages.size, "the reimport sees the grown page set") + assertTrue(reimported.atlas.storedUvsAddressPages, "the document stays page-addressed") + for (mover in movers) { + assertEquals( + placements[mover.id], + reimported.atlas.tiles.first { tile -> tile.id == mover.id }.placement, + "'${mover.name}' reimports at its new placement", + ) + } + } + + @Test + fun aHandPlacedRotatedAndScaledTileExportsItsTrsAndKeepsItsMapping() { + val file = skipMessageOrNull() ?: return + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val boundTileIds = imported.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val tile = imported.atlas.tiles.firstOrNull { candidate -> candidate.placement != null && candidate.id in boundTileIds } + if (tile == null) { + println("${file.name} packs no bound artwork; skipping the hand-placement gate") + return + } + val original = assertNotNull(tile.placement) + // The gizmo's whole vocabulary on one tile: a fractional move, a turn, and a reduction. + val turned = + original.copy( + positionX = original.positionX + 5.5f, + positionY = original.positionY - 2.25f, + scaleX = 0.5f, + scaleY = 0.5f, + rotationDegrees = 30f, + ) + val edited = imported.withAtlasPlacements(mapOf(tile.id to turned)) + assertNotSame(imported, edited, "the placement moved") + val marker = markerPng() + val pages = + pageResourcesOf(modelSource).map { (_, resource) -> Cmo3Conversion.AtlasPage(marker, resource.width, resource.height) } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertFalse(hasStalePageNotice(report), "a same-membership hand placement patches the pages: ${report.notices}") + val reimported = Cmo3Import.fromModelSource(Cmo3.read(Cmo3.write(cmo3)).root as CModelSource) + val reread = assertNotNull(reimported.atlas.tileById[tile.id]?.placement, "'${tile.name}' reimports placed") + assertEquals(turned.pageIndex, reread.pageIndex, "page") + assertEquals(turned.positionX, reread.positionX, 1e-2f, "position x") + assertEquals(turned.positionY, reread.positionY, 1e-2f, "position y") + assertEquals(turned.scaleX, reread.scaleX, 1e-3f, "scale x") + assertEquals(turned.scaleY, reread.scaleY, 1e-3f, "scale y") + assertEquals(turned.rotationDegrees, reread.rotationDegrees, 1e-2f, "rotation") + val editedUvs = edited.drawables.associate { drawable -> drawable.id to drawable.mesh?.uvs } + for (drawable in reimported.drawables) { + if (drawable.atlasTileId != tile.id) { + continue + } + assertContentEquals(editedUvs[drawable.id], drawable.mesh?.uvs, "'${drawable.name}' exports the re-derived coordinates verbatim") + } + } + + @Test + fun aNeverPackedBoundTileGainsAnEntryAndARegionInput() { + val file = skipMessageOrNull() ?: return + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val boundTileIds = imported.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val packIn = imported.atlas.tiles.firstOrNull { tile -> tile.placement == null && tile.id in boundTileIds } + if (packIn == null) { + println("${file.name} has no bound never-packed art; skipping the pack-in gate") + return + } + val placements = + imported.atlas.tiles.associateTo(HashMap()) { tile -> tile.id to tile.placement } + placements[packIn.id] = AtlasPlacement(0, 100f, 100f, 1f, 1f, 0f) + val edited = imported.withAtlasRepack(imported.atlas.pages, placements) + val marker = markerPng() + val pages = + imported.atlas.pages.map { page -> + Cmo3Conversion.AtlasPage(marker, page.width, page.height) + } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertFalse(hasStalePageNotice(report), "the pack-in reconciled: ${report.notices}") + assertFalse( + report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.NoAtlasEntryToReconcile + }, + "the minted entry serves the placement diff: ${report.notices}", + ) + val rereadCmo3 = Cmo3.read(Cmo3.write(cmo3)) + val rereadSource = rereadCmo3.root as CModelSource + val atlasZero = pageResourcesOf(rereadSource).first().first + val entry = assertNotNull(entryIn(atlasZero, packIn.id.raw), "'${packIn.name}' gained an entry on page 0") + assertSame(atlasZero, entry.atlas, "with the owning-page back-reference") + val pageResource = assertNotNull(atlasZero.cachedAtlasImage as? CImageResource) + for (drawable in edited.drawables.filter { candidate -> candidate.atlasTileId == packIn.id }) { + val source = assertNotNull(drawableSourceOf(rereadSource, drawable.id.raw)) + val texture = assertNotNull(source.texture as? GTexture2D) + assertSame(pageResource, texture.srcImageResource, "'${drawable.id.raw}' now samples the page itself") + val extension = + assertNotNull(elementsOf(source._extensions).filterIsInstance().firstOrNull()) + val region = + assertNotNull( + elementsOf(extension._textureInputs).filterIsInstance().firstOrNull(), + "'${drawable.id.raw}' gained a region input", + ) + assertEquals( + ((atlasZero.guid as? Guid))?.uuid, + (region.textureAtlasGuid as? Guid)?.uuid, + "the region names page 0", + ) + assertSame(region, extension.currentTextureInputData, "the atlas-mode document samples the region") + } + val reimported = Cmo3Import.fromModelSource(rereadSource) + assertEquals( + placements[packIn.id], + reimported.atlas.tiles.first { tile -> tile.id == packIn.id }.placement, + "the reimport reads the minted placement", + ) + val editedUvs = edited.drawables.first { drawable -> drawable.atlasTileId == packIn.id }.mesh!!.uvs + val rereadUvs = + reimported.drawables.first { drawable -> drawable.atlasTileId == packIn.id }.mesh!!.uvs + assertEquals(editedUvs.size, rereadUvs.size) + for (componentIndex in editedUvs.indices) { + assertEquals( + editedUvs[componentIndex], + rereadUvs[componentIndex], + 1e-4f, + "page-frame coordinates round-trip verbatim (component $componentIndex)", + ) + } + } + + @Test + fun anUnboundTilePacksOutByRemovingItsEntry() { + val file = skipMessageOrNull() ?: return + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val boundTileIds = imported.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val packedTiles = imported.atlas.tiles.filter { tile -> tile.placement != null && tile.id in boundTileIds } + if (packedTiles.size < 2) { + println("${file.name} packs too little bound artwork; skipping the pack-out gate") + return + } + val packedOut = packedTiles[0] + val rebindTarget = packedTiles[1] + // Manufacture the unbound-placed shape the repack packs out: rebind the tile's drawables to a + // sibling tile (the rebinding itself is not lowered and takes its own notice, which this gate + // does not assert on), then pack the now-unbound tile out. + val edited = + imported + .copy( + drawables = + imported.drawables.map { drawable -> + if (drawable.atlasTileId == packedOut.id) drawable.copy(atlasTileId = rebindTarget.id) else drawable + }, + ).withAtlasPlacement(packedOut.id, null) + val resources = pageResourcesOf(modelSource) + val marker = markerPng() + val pages = + resources.map { (_, resource) -> + Cmo3Conversion.AtlasPage(marker, resource.width, resource.height) + } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + assertFalse(hasStalePageNotice(report), "the pack-out reconciled: ${report.notices}") + val rereadCmo3 = Cmo3.read(Cmo3.write(cmo3)) + val rereadSource = rereadCmo3.root as CModelSource + for (atlas in pageResourcesOf(rereadSource).map { (atlas, _) -> atlas }) { + assertEquals(null, entryIn(atlas, packedOut.id.raw), "the packed-out entry left every page") + } + val reimported = Cmo3Import.fromModelSource(rereadSource) + assertEquals( + null, + reimported.atlas.tiles.first { tile -> tile.id == packedOut.id }.placement, + "the reimport reads the tile as unplaced", + ) + } + + @Test + fun aBoundTilePackedOutDeclinesWhole() { + val file = skipMessageOrNull() ?: return + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val boundTileIds = imported.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val packed = imported.atlas.tiles.firstOrNull { tile -> tile.placement != null && tile.id in boundTileIds } + if (packed == null) { + println("${file.name} packs no bound artwork; skipping the bound pack-out gate") + return + } + val resources = pageResourcesOf(modelSource) + val originalBytes = resources.map { (_, resource) -> assertNotNull(cmo3.extractLayerPng(resource)) } + // Packing a BOUND tile out would strand its drawables' page sampling - the reconcile must + // decline whole rather than remove the entry from under them. + val edited = imported.withAtlasPlacement(packed.id, null) + val marker = markerPng() + val pages = + resources.map { (_, resource) -> + Cmo3Conversion.AtlasPage(marker, resource.width, resource.height) + } + + val report = Cmo3Export.apply(edited, cmo3, recomposedPages = pages) + + // The declined reconcile leaves the null placement to the ordinary lowering, whose honest + // notice for a placement without an entry to write is NoAtlasEntryToReconcile. + assertTrue( + report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.NoAtlasEntryToReconcile + }, + "a declined reconcile keeps the honest notice: ${report.notices}", + ) + val rereadCmo3 = Cmo3.read(Cmo3.write(cmo3)) + for ((pageIndex, pair) in pageResourcesOf(rereadCmo3.root as CModelSource).withIndex()) { + assertContentEquals( + originalBytes[pageIndex], + rereadCmo3.extractLayerPng(pair.second), + "a bound pack-out must not patch the pages", + ) + } + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportRoundTripTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportRoundTripTest.kt new file mode 100644 index 0000000..a4c3663 --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportRoundTripTest.kt @@ -0,0 +1,637 @@ +package org.umamo.edit.export + +import org.umamo.edit.withAtlasPlacement +import org.umamo.edit.withCanvasSize +import org.umamo.edit.withDeformerBaseAngle +import org.umamo.edit.withDeformerName +import org.umamo.edit.withDeformerPart +import org.umamo.edit.withDeformerSelectable +import org.umamo.edit.withDrawableAlphaBlendMode +import org.umamo.edit.withDrawableBlendMode +import org.umamo.edit.withDrawableCulling +import org.umamo.edit.withDrawableInvertMask +import org.umamo.edit.withDrawableMaskedBy +import org.umamo.edit.withDrawableName +import org.umamo.edit.withDrawableParentDeformer +import org.umamo.edit.withDrawableSelectable +import org.umamo.edit.withDrawableVisibility +import org.umamo.edit.withMeshPositions +import org.umamo.edit.withMeshUvs +import org.umamo.edit.withOrgChildMoved +import org.umamo.edit.withParameterGroupRenamed +import org.umamo.edit.withParameterLink +import org.umamo.edit.withParameterRange +import org.umamo.edit.withParameterRenamed +import org.umamo.edit.withPartGroupMode +import org.umamo.edit.withPartName +import org.umamo.edit.withPartSketch +import org.umamo.edit.withPartVisibility +import org.umamo.edit.withRuntimeTarget +import org.umamo.edit.withWorldOrigin +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.interop.DocumentField +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3.Cmo3Export +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.atlasPixelOf +import org.umamo.runtime.model.storedToArtAffineForTile +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The export-with-changes gate: apply real :edit ops to an imported corpus model, reconcile them + * onto the retained graph, re-emit the file, re-import it, and assert the edits are not lost - the + * re-imported model must diff empty against the edited one. Also pins the never-silent contract: + * an edit the lowering cannot express must surface as a notice AND remain visible in the residual + * diff, not vanish. + */ +class Cmo3ExportRoundTripTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private class RoundTrip( + val edited: PuppetModel, + val reimported: PuppetModel, + val report: ExportReport, + ) + + /** + * Imports the sample, applies [edit], exports through the reconcile, and re-imports the + * re-emitted bytes. + * + * @param File file The corpus sample. + * @param Function edit The model edit under test. + * @return RoundTrip The edited model, the re-imported model, and the export report. + */ + private fun roundTrip(file: File, edit: (PuppetModel) -> PuppetModel): RoundTrip { + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val edited = edit(Cmo3Import.fromModelSource(modelSource)) + val report = Cmo3Export.apply(edited, cmo3) + val reimportedSource = + Cmo3.read(Cmo3.write(cmo3)).root as? CModelSource ?: error("re-read root is not a CModelSource") + return RoundTrip(edited, Cmo3Import.fromModelSource(reimportedSource), report) + } + + private fun assertLossless(result: RoundTrip, label: String) { + assertTrue(result.report.isEmpty, "$label: expected no notices, got ${result.report.notices}") + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(residual.isEmpty, "$label: edits lost through export/import: $residual") + } + + private fun skipMessageOrNull(): File? { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping export round-trip test") + } + return file + } + + @Test + fun renamesSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + puppet + .withPartName(puppet.parts.first().id, "Renamed Part") + .withDrawableName(puppet.drawables.first().id, "Renamed Drawable") + .let { model -> + val deformer = model.deformers.firstOrNull() ?: return@let model + model.withDeformerName(deformer.id, "Renamed Deformer") + } + .let { model -> model.withParameterRenamed(model.parameters.first().id, "Renamed Parameter") } + } + assertLossless(result, "renames") + } + + @Test + fun visibilityAndSelectableFlagsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + puppet + .withPartVisibility(puppet.parts.first().id, visible = false) + .withDrawableVisibility(puppet.drawables.first().id, visible = false) + .withDrawableSelectable(puppet.drawables.first().id, selectable = false) + .let { model -> + val deformer = model.deformers.firstOrNull() ?: return@let model + model.withDeformerSelectable(deformer.id, selectable = false) + } + } + assertLossless(result, "visibility/selectable") + } + + @Test + fun blendCullingAndMaskEditsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val drawableId = puppet.drawables.first().id + val maskTarget = puppet.drawables.last().id + puppet + .withDrawableBlendMode(drawableId, BlendMode.Multiply) + .withDrawableAlphaBlendMode(drawableId, AlphaBlendMode.Atop) + .withDrawableCulling(drawableId, culling = true) + .withDrawableInvertMask(drawableId, invert = true) + .withDrawableMaskedBy(drawableId, listOf(maskTarget)) + } + assertLossless(result, "blend/culling/mask") + } + + @Test + fun reparentEditsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + // Detach a deformed drawable, and move a deformer to the tree root - both reference + // rewrites plus (for the deformer) the parts-panel _childGuids move. + val deformedDrawable = puppet.drawables.firstOrNull { it.parentDeformerId != null } + val partedDeformer = puppet.deformers.firstOrNull { it.partId != null } + var model = puppet + if (deformedDrawable != null) { + model = model.withDrawableParentDeformer(deformedDrawable.id, null) + } + if (partedDeformer != null) { + model = model.withDeformerPart(partedDeformer.id, null) + } + model + } + assertLossless(result, "reparent") + } + + @Test + fun partFieldEditsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val partId = puppet.parts.first().id + puppet + .withPartSketch(partId, sketch = true) + .withPartGroupMode(partId, PartGroupMode.Grouped) + } + assertLossless(result, "part fields") + } + + @Test + fun deformerFieldEditsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val rotation = + run { + val cmo3 = Cmo3.read(file.readBytes()) + Cmo3Import.fromModelSource(cmo3.root as CModelSource).deformers + .firstOrNull { it is org.umamo.runtime.model.Deformer.Rotation } + } + if (rotation == null) { + println("${file.name} has no rotation deformer; skipping base-angle round trip") + return + } + val result = roundTrip(file) { puppet -> puppet.withDeformerBaseAngle(rotation.id, 42.5f) } + assertLossless(result, "deformer fields") + } + + @Test + fun parameterRangeAndLinkEditsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + // Range edits change how a re-import COMPACTS channel tracks (axisSpansRange keys off the + // range), so a range edit on any axis-bearing parameter round-trips semantically equal but + // representationally different. Pick a parameter no axis references at all - collected from + // an UNCOMPACTED import, since a compacted-away track still resurfaces on re-import when the + // widened range stops its axis from spanning. + val uncompacted = + Cmo3Import.fromModelSource(Cmo3.read(file.readBytes()).root as CModelSource, compactChannels = false) + val referencedParameterIds = + buildSet { + for (drawable in uncompacted.drawables) { + drawable.geometryGrid?.axes?.forEach { axis -> add(axis.parameterId) } + drawable.channelGrids.gridsByChannel.values.forEach { grid -> grid.axes.forEach { add(it.parameterId) } } + drawable.blendShapes.forEach { binding -> add(binding.parameterId) } + } + for (deformer in uncompacted.deformers) { + deformer.channelGrids.gridsByChannel.values.forEach { grid -> grid.axes.forEach { add(it.parameterId) } } + } + for (part in uncompacted.parts) { + part.channelGrids.gridsByChannel.values.forEach { grid -> grid.axes.forEach { add(it.parameterId) } } + } + for (glue in uncompacted.glues) { + glue.channelGrids.gridsByChannel.values.forEach { grid -> grid.axes.forEach { add(it.parameterId) } } + } + } + val unreferenced = uncompacted.parameters.firstOrNull { it.id !in referencedParameterIds } + val result = + roundTrip(file) { puppet -> + var model = puppet + if (unreferenced != null) { + model = + model.withParameterRange( + unreferenced.id, + unreferenced.min - 5f, + unreferenced.default, + unreferenced.max + 5f, + ) + } + val existingLink = model.parameterLinks.firstOrNull() + if (existingLink != null) { + model = model.withParameterLink(existingLink.horizontal, existingLink.vertical, linked = false) + } + model + } + assertLossless(result, "parameter range/link") + } + + @Test + fun treeMovesSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + // Move the first part-owned drawable to the end of the root level - exercises both the + // old part's _childGuids rebuild and the root part's. + val ownedDrawable = + puppet.parts.asSequence() + .flatMap { part -> part.children.asSequence() } + .filterIsInstance() + .firstOrNull() ?: return@roundTrip puppet + puppet.withOrgChildMoved(ownedDrawable, newParentId = null, before = null) + } + assertLossless(result, "tree moves") + } + + @Test + fun parameterGroupEditsSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val hasGroup = + run { + val cmo3 = Cmo3.read(file.readBytes()) + Cmo3Import.fromModelSource(cmo3.root as CModelSource).parameterTree.any { it is ParameterNode.Group } + } + if (!hasGroup) { + println("${file.name} has no parameter groups; skipping group round trip") + return + } + val result = + roundTrip(file) { puppet -> + val group = puppet.parameterTree.filterIsInstance().first() + puppet.withParameterGroupRenamed(group.id, "Renamed Group") + } + assertLossless(result, "parameter group") + } + + @Test + fun canvasAndRuntimeTargetSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val newWidth = puppet.canvasWidth + 16f + val newHeight = puppet.canvasHeight + 16f + puppet + .withCanvasSize(newWidth, newHeight) + // CMO3 derives the origin as the canvas center, so a session exporting a resize + // moves its origin to the new center - the state the exported file will reopen at. + .withWorldOrigin(newWidth / 2f, -(newHeight / 2f)) + .withRuntimeTarget(RuntimeTarget.Cubism42) + } + assertLossless(result, "canvas/runtime target") + } + + /** + * Moving art on an atlas page rewrites BOTH halves of the entry's transform pair, and says the page + * image is now stale. + * + * The model round trip alone cannot gate this: the ingest reads only the packing transform, so a + * wrong atlasLocalToCanvasTransform would reimport perfectly and still be a broken file - the + * official editor composes the two, and the format's invariant is that they reproduce the art's + * CANVAS placement, which repacking does not move. So the written graph is checked directly. + */ + @Test + fun anAtlasPlacementMoveRewritesBothHalvesAndReportsTheStalePage() { + val file = skipMessageOrNull() ?: return + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(modelSource) + val packed = imported.atlas.tiles.firstOrNull { tile -> tile.placement != null } + if (packed == null) { + println("${file.name} packs no artwork; skipping the atlas placement round trip") + return + } + val canvasBefore = assertNotNull(canvasPlacementOf(modelSource, packed.id.raw), "the packed tile declares a canvas placement") + + val moved = packed.placement!!.copy(positionX = packed.placement!!.positionX + 8f) + val edited = imported.withAtlasPlacement(packed.id, moved) + assertEquals(moved, edited.atlas.tiles.first { tile -> tile.id == packed.id }.placement, "the edit applied") + + val report = Cmo3Export.apply(edited, cmo3) + assertTrue( + report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.AtlasPageNotRecomposed + }, + "a moved placement must say the page image was not redrawn: ${report.notices}", + ) + + val writtenSource = Cmo3.read(Cmo3.write(cmo3)).root as? CModelSource ?: error("re-read root is not a CModelSource") + assertEquals( + moved, + Cmo3Import.fromModelSource(writtenSource).atlas.tiles.first { tile -> tile.id == packed.id }.placement, + "the packing transform round-trips", + ) + // The pair must still compose to where the art sits on the canvas, which a repack never moves. + val entry = assertNotNull(atlasEntryOf(writtenSource, packed.id.raw), "the entry survives the export") + val atlasToCanvas = assertNotNull(entry.atlasLocalToCanvasTransform as? CAffine, "and keeps its atlas-to-canvas half") + val composed = + atlasPixelOf(moved, 0f, 0f).let { onPage -> + floatArrayOf( + atlasToCanvas.m00 * onPage[0] + atlasToCanvas.m01 * onPage[1] + atlasToCanvas.m02, + atlasToCanvas.m10 * onPage[0] + atlasToCanvas.m11 * onPage[1] + atlasToCanvas.m12, + ) + } + assertEquals(canvasBefore.first, composed[0], 1e-2f, "the art stayed put on the canvas in x") + assertEquals(canvasBefore.second, composed[1], 1e-2f, "the art stayed put on the canvas in y") + } + + /** The art's canvas placement, as the file declares it on its model image. */ + private fun canvasPlacementOf(modelSource: CModelSource, tileId: String): Pair? { + val textureManager = modelSource.textureManager as? CTextureManager ?: return null + for (group in elementsOf(textureManager._modelImageGroups).filterIsInstance()) { + for (image in elementsOf(group._modelImages).filterIsInstance()) { + if ((image.guid as? Guid)?.uuid != tileId) { + continue + } + val canvas = image._materialLocalToCanvasTransform as? CAffine ?: return null + return canvas.m02 to canvas.m12 + } + } + return null + } + + /** One tile's packed entry, wherever it sits. */ + private fun atlasEntryOf(modelSource: CModelSource, tileId: String): ModelImageEntry? { + val textureManager = modelSource.textureManager as? CTextureManager ?: return null + for (atlas in elementsOf(textureManager._textureAtlases).filterIsInstance()) { + for (entry in elementsOf(atlas.modelImages).filterIsInstance()) { + if ((entry.modelImageGuid as? Guid)?.uuid == tileId) { + return entry + } + } + } + return null + } + + /** Flattens a CMO3 collection field, held as `Any?` by the serializer. */ + private fun elementsOf(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + @Test + fun vertexNudgeSurvivesRoundTripWithAWeldNotice() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + val drawable = puppet.drawables.first { it.mesh != null } + val nudged = drawable.mesh!!.positions.copyOf() + nudged[0] += 3f + nudged[1] -= 2f + puppet.withMeshPositions(drawable.id, nudged) + } + // Exported geometry is written as authored rather than re-welded to Cubism's own topology, + // so the geometry survives exactly while the weld-divergence notice names the edited mesh. + val weld = result.report.notices.filterIsInstance().singleOrNull() + assertTrue(weld != null && weld.drawableNames.isNotEmpty(), "weld notice fires for a base-geometry edit") + assertTrue( + result.report.notices.none { it is ExportNotice.UnsupportedChange }, + "a base nudge lowers fully: ${result.report.notices}", + ) + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(residual.isEmpty, "vertex nudge lost through export/import: $residual") + } + + @Test + fun uvEditsSurviveRoundTripOnPackedAndUnpackedDrawables() { + val file = skipMessageOrNull() ?: return + // Exercise both UV frame conventions when the model has both: a packed (atlas-region) + // drawable writes verbatim, an unpacked one goes through the forward model-image affine. + val cmo3 = Cmo3.read(file.readBytes()) + val root = cmo3.root as CModelSource + val packedIds = + buildSet { + val sources = + (((root.drawableSourceSet as? CDrawableSourceSet)?._sources as? Iterable<*>) ?: emptyList()) + .filterIsInstance() + for (source in sources) { + val extensions = (source._extensions as? Iterable<*>) ?: emptyList() + val hasRegion = + extensions.filterIsInstance().any { extension -> + ( + (extension._textureInputs as? Iterable<*>) + ?: emptyList() + ).any { it is CTextureInput_TextureAtlasRegion } + } + if (hasRegion) { + (source.id as? Id)?.idstr?.let { idStr -> add(DrawableId(idStr)) } + } + } + } + val puppetProbe = Cmo3Import.fromModelSource(root) + val packed = puppetProbe.drawables.firstOrNull { it.mesh != null && it.id in packedIds } + val unpacked = puppetProbe.drawables.firstOrNull { it.mesh != null && it.id !in packedIds } + val result = + roundTrip(file) { puppet -> + var model = puppet + for (pick in listOfNotNull(packed, unpacked)) { + val mesh = model.drawables.first { it.id == pick.id }.mesh!! + val movedUvs = mesh.uvs.copyOf() + if (movedUvs.size >= 2) { + movedUvs[0] += 0.01f + movedUvs[1] += 0.01f + } + model = model.withMeshUvs(pick.id, movedUvs) + } + model + } + val weld = result.report.notices.filterIsInstance().singleOrNull() + assertTrue(weld != null, "weld notice fires for a UV edit") + assertTrue( + result.report.notices.none { it is ExportNotice.UnsupportedChange }, + "a UV edit lowers fully: ${result.report.notices}", + ) + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(residual.isEmpty, "UV edits lost through export/import: $residual") + } + + /** + * The first packed drawable over a reduced cache copy of its model image, classified straight off the + * file: its texture names one of the image's cached resources other than the raster. + * + * @param CModelSource root The CMO3's model source. + * @return CArtMeshSource? The drawable's source, or null when the file has none. + */ + private fun packedReducedCopyDrawable(root: CModelSource): CArtMeshSource? { + val textureManager = root.textureManager as? CTextureManager ?: return null + val copies = HashSet() + for (group in ((textureManager._modelImageGroups as? Iterable<*>) ?: emptyList()).filterIsInstance()) { + for (modelImage in ((group._modelImages as? Iterable<*>) ?: emptyList()).filterIsInstance()) { + val manager = modelImage.cachedImageManager as? CCachedImageManager ?: continue + for (cached in ((manager.cachedImages as? Iterable<*>) ?: emptyList()).filterIsInstance()) { + val resource = cached._cachedImageResource as? CImageResource ?: continue + if (resource !== modelImage._filteredImage) { + copies.add(resource) + } + } + } + } + val sources = (((root.drawableSourceSet as? CDrawableSourceSet)?._sources as? Iterable<*>) ?: emptyList()).filterIsInstance() + return sources.firstOrNull { source -> + val packed = + ((source._extensions as? Iterable<*>) ?: emptyList()).filterIsInstance().any { extension -> + ((extension._textureInputs as? Iterable<*>) ?: emptyList()).any { input -> input is CTextureInput_TextureAtlasRegion } + } + packed && ((source.texture as? GTexture2D)?.srcImageResource as? CImageResource) in copies && (source.uvs as? FloatArray)?.let { uvs -> uvs.size >= 4 } == true + } + } + + @Test + fun aUvEditOverAReducedCopyStoresTheEditorsCacheFrame() { + val spec = + System.getProperty("cmo3.probe") + ?: run { + println("cmo3.probe not present; skipping the reduced-copy UV round trip") + return + } + val files = spec.split(',').map { File(it.trim()) }.filter { it.isFile } + for (file in files) { + val cmo3 = Cmo3.read(file.readBytes()) + val root = cmo3.root as? CModelSource ?: continue + val source = packedReducedCopyDrawable(root) ?: continue + val drawableId = DrawableId((source.id as Id).idstr) + val storedBefore = (source.uvs as FloatArray).copyOf() + val scale = (source.texture as GTexture2D).transformImageResource01toLogical01 as CAffine + + val puppet = Cmo3Import.fromModelSource(root) + val movedUvs = puppet.drawables.first { drawable -> drawable.id == drawableId }.mesh!!.uvs.copyOf() + movedUvs[0] += 0.01f + movedUvs[1] += 0.01f + val edited = puppet.withMeshUvs(drawableId, movedUvs) + val report = Cmo3Export.apply(edited, cmo3) + assertTrue(report.notices.none { notice -> notice is ExportNotice.UnsupportedChange }, "${file.name}: a UV edit lowers fully: ${report.notices}") + + val reread = Cmo3.read(Cmo3.write(cmo3)) + val rereadRoot = reread.root as CModelSource + // Through the placement and the cache scale not every float has an exact preimage, so the edited + // pair comes back within a hair of a page texel; the untouched pairs, and the rest of the model, + // come back exactly. + val reimported = Cmo3Import.fromModelSource(rereadRoot) + val reimportedUvs = reimported.drawables.first { drawable -> drawable.id == drawableId }.mesh!!.uvs + for (componentIndex in 0 until 2) { + assertTrue( + kotlin.math.abs(reimportedUvs[componentIndex] - movedUvs[componentIndex]) <= 1e-6f, + "${file.name}: edited component $componentIndex re-imports as ${reimportedUvs[componentIndex]}, edited ${movedUvs[componentIndex]}", + ) + } + for (componentIndex in 2 until movedUvs.size) { + assertEquals(movedUvs[componentIndex].toRawBits(), reimportedUvs[componentIndex].toRawBits(), "${file.name}: untouched component $componentIndex re-imports exactly") + } + val residual = diffPuppetModels(reimported, edited.withMeshUvs(drawableId, reimportedUvs)) + assertTrue(residual.isEmpty, "${file.name}: the export changed more than the edited UVs: $residual") + val rereadSources = ((rereadRoot.drawableSourceSet as CDrawableSourceSet)._sources as Iterable<*>).filterIsInstance() + val storedAfter = rereadSources.first { candidate -> (candidate.id as? Id)?.idstr == drawableId.raw }.uvs as FloatArray + // The edited pair comes off the tile's page into its art's frame and is stored in the editor's cache + // frame; the untouched pairs byte for byte. + val storedToArt = assertNotNull(edited.drawables.first { drawable -> drawable.id == drawableId }.atlasTileId?.let { tileId -> edited.atlas.storedToArtAffineForTile(tileId) }) + val artU = storedToArt[0] * movedUvs[0] + storedToArt[1] * movedUvs[1] + storedToArt[2] + val artV = storedToArt[3] * movedUvs[0] + storedToArt[4] * movedUvs[1] + storedToArt[5] + assertEquals(scale.m00 * artU + scale.m01 * artV + scale.m02, storedAfter[0], 1e-5f, "${file.name}: the edited u is stored in the cache frame") + assertEquals(scale.m10 * artU + scale.m11 * artV + scale.m12, storedAfter[1], 1e-5f, "${file.name}: the edited v is stored in the cache frame") + for (componentIndex in 2 until storedBefore.size) { + assertEquals(storedBefore[componentIndex].toRawBits(), storedAfter[componentIndex].toRawBits(), "${file.name}: untouched component $componentIndex keeps its stored bits") + } + return + } + println("no cmo3.probe model draws over a reduced cache copy; skipping the reduced-copy UV round trip") + } + + @Test + fun worldOriginEditReportsInsteadOfSilentlyDropping() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> puppet.withWorldOrigin(puppet.worldOriginX + 10f, puppet.worldOriginZ) } + assertTrue( + result.report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && + notice.reason == ExportNoticeReason.NoAuthoredWorldOrigin + }, + "world origin edit must surface as a notice", + ) + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(DocumentField.WORLD_ORIGIN in residual.document, "the unlowered origin stays visible in the diff") + } + + @Test + fun renameSurvivesAcrossTheWholeCorpus() { + val spec = + System.getProperty("cmo3.probe") + ?: run { + println("cmo3.probe not present; skipping corpus rename smoke") + return + } + val files = spec.split(',').map { File(it.trim()) }.filter { it.isFile } + val failures = ArrayList() + for (file in files) { + val outcome = + runCatching { + val result = + roundTrip(file) { puppet -> + // Some synthetic corpus models (the offscreen probes) carry parts but no + // drawables; rename whichever entity the model has. + val drawable = puppet.drawables.firstOrNull() + val part = puppet.parts.firstOrNull() + when { + drawable != null -> puppet.withDrawableName(drawable.id, "Corpus Renamed") + part != null -> puppet.withPartName(part.id, "Corpus Renamed") + else -> puppet + } + } + if (!result.report.isEmpty) { + failures.add("${file.name}: notices ${result.report.notices}") + } else { + val residual = diffPuppetModels(result.reimported, result.edited) + if (!residual.isEmpty) { + failures.add("${file.name}: residual diff $residual") + } + } + } + outcome.exceptionOrNull()?.let { failure -> failures.add("${file.name}: threw $failure") } + } + assertTrue(failures.isEmpty(), "corpus rename smoke failed:\n" + failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportStructureRoundTripTest.kt b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportStructureRoundTripTest.kt new file mode 100644 index 0000000..1e3cd5a --- /dev/null +++ b/module/edit/src/jvmTest/kotlin/org/umamo/edit/export/Cmo3ExportStructureRoundTripTest.kt @@ -0,0 +1,239 @@ +package org.umamo.edit.export + +import org.umamo.edit.MergeTarget +import org.umamo.edit.MeshTopologyOps +import org.umamo.edit.withDeformerDeleted +import org.umamo.edit.withDrawableDeleted +import org.umamo.edit.withDrawableDuplicated +import org.umamo.edit.withMeshTopologyEdit +import org.umamo.edit.withParameterCreated +import org.umamo.edit.withParameterDeleted +import org.umamo.edit.withParameterGroupCreated +import org.umamo.edit.withPartDeleted +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.DrawableField +import org.umamo.interop.EntityDiff +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3.Cmo3Export +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The structural-synthesis gate: created and deleted parameters, created parameter groups, + * duplicated and deleted drawables, deleted parts/deformers, and mesh topology edits reconcile + * onto the CMO3 graph and survive an export/re-import. A duplicated drawable's textureSourceId is + * editor-only state (the re-imported file binds the atlas by the drawable's own id), and + * rebuilt/duplicated forms follow the delta-vs-absolute bounded-ULP tier, so those two residues + * are tolerated where noted. + */ +class Cmo3ExportStructureRoundTripTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private class RoundTrip( + val edited: PuppetModel, + val reimported: PuppetModel, + val report: ExportReport, + ) + + private fun roundTrip(file: File, edit: (PuppetModel) -> PuppetModel): RoundTrip { + val cmo3 = Cmo3.read(file.readBytes()) + val modelSource = cmo3.root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val edited = edit(Cmo3Import.fromModelSource(modelSource)) + val report = Cmo3Export.apply(edited, cmo3) + val reimportedSource = + Cmo3.read(Cmo3.write(cmo3)).root as? CModelSource ?: error("re-read root is not a CModelSource") + return RoundTrip(edited, Cmo3Import.fromModelSource(reimportedSource), report) + } + + private fun assertLossless(result: RoundTrip, label: String) { + assertTrue(result.report.isEmpty, "$label: expected no notices, got ${result.report.notices}") + val residual = diffPuppetModels(result.reimported, result.edited) + assertTrue(residual.isEmpty, "$label: edits lost through export/import: $residual") + } + + /** + * Asserts a clean round trip except the tolerated per-drawable residues: TEXTURE_SOURCE + * (editor-only state) and bounded-ULP GEOMETRY/BLEND_SHAPES drift on [drawableId]. The export + * report may carry WeldDivergence (a topology edit leaves the imported weld by definition) but + * nothing else; the geometry grid and every edited cell must survive - a vanished grid or cell + * is loss, not drift. + * + * @param RoundTrip result The edited/reimported model pair and export report under test. + * @param DrawableId drawableId The one drawable allowed to carry the tolerated residues. + * @param String label Test-scenario label used in assertion failure messages. + */ + private fun assertLosslessExceptDrawableResidue(result: RoundTrip, drawableId: DrawableId, label: String) { + assertTrue( + result.report.notices.all { notice -> notice is ExportNotice.WeldDivergence }, + "$label: unexpected notices ${result.report.notices}", + ) + val editedGrid = result.edited.drawables.first { it.id == drawableId }.geometryGrid + val reimportedGrid = result.reimported.drawables.first { it.id == drawableId }.geometryGrid + assertTrue( + (editedGrid == null) == (reimportedGrid == null), + "$label: geometry grid presence changed through the round trip", + ) + if (editedGrid != null && reimportedGrid != null) { + val reimportedByCoordinate = + reimportedGrid.cells.associate { cell -> cell.coordinate.toList() to cell.form.positionDeltas } + var maxComponentDifference = 0f + for (cell in editedGrid.cells) { + val reimportedDeltas = reimportedByCoordinate[cell.coordinate.toList()] + assertTrue(reimportedDeltas != null, "$label: cell ${cell.coordinate.toList()} vanished") + for (component in cell.form.positionDeltas.indices) { + maxComponentDifference = + maxOf( + maxComponentDifference, + abs(cell.form.positionDeltas[component] - reimportedDeltas[component]), + ) + } + } + assertTrue(maxComponentDifference < 1e-3f, "$label: geometry drifted by $maxComponentDifference") + } + val residual = diffPuppetModels(result.reimported, result.edited) + if (residual.isEmpty) { + return + } + val tolerated = setOf(DrawableField.TEXTURE_SOURCE, DrawableField.GEOMETRY, DrawableField.BLEND_SHAPES) + val onlyToleratedResidue = + residual.parameters.isEmpty() && + residual.parameterGroups.isEmpty() && + residual.parts.isEmpty() && + residual.deformers.isEmpty() && + residual.glues.isEmpty() && + residual.document.isEmpty() && + residual.drawables.all { entityDiff -> + entityDiff is EntityDiff.Changed && + entityDiff.id == drawableId && + tolerated.containsAll( + entityDiff.fields, + ) + } + assertTrue(onlyToleratedResidue, "$label: unexpected residual $residual") + } + + private fun skipMessageOrNull(): File? { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping structure round-trip test") + } + return file + } + + @Test + fun parameterCreateAndDeleteSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + var model = puppet.withParameterCreated(ParameterId("UmamoTestParam"), "Umamo Test Param") + // Delete a parameter nothing keys on, so the delete is a pure set-membership change. + val referenced = + buildSet { + for (drawable in model.drawables) { + drawable.geometryGrid?.axes?.forEach { add(it.parameterId) } + drawable.channelGrids.gridsByChannel.values.forEach { grid -> grid.axes.forEach { add(it.parameterId) } } + drawable.blendShapes.forEach { add(it.parameterId) } + } + for (deformer in model.deformers) { + deformer.channelGrids.gridsByChannel.values.forEach { grid -> grid.axes.forEach { add(it.parameterId) } } + } + model.parameterLinks.forEach { + add(it.horizontal) + add(it.vertical) + } + } + val victim = model.parameters.firstOrNull { it.id !in referenced && it.id.raw != "UmamoTestParam" } + if (victim != null) { + model = model.withParameterDeleted(victim.id) + } + model + } + assertLossless(result, "parameter create/delete") + } + + @Test + fun parameterGroupCreateSurvivesRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + puppet.withParameterGroupCreated(ParameterGroupId("UmamoTestGroup"), "Umamo Test Group") + } + assertLossless(result, "parameter group create") + } + + @Test + fun drawableDuplicateSurvivesRoundTrip() { + val file = skipMessageOrNull() ?: return + var duplicateId: DrawableId? = null + val result = + roundTrip(file) { puppet -> + val sourceDrawable = puppet.drawables.first { it.mesh != null } + val (duplicated, newId) = + puppet.withDrawableDuplicated(sourceDrawable.id) ?: error("duplicate refused") + duplicateId = newId + duplicated + } + assertLosslessExceptDrawableResidue(result, duplicateId!!, "drawable duplicate") + } + + @Test + fun drawableDeleteSurvivesRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + puppet.withDrawableDeleted(puppet.drawables.first().id) + } + assertLossless(result, "drawable delete") + } + + @Test + fun partAndDeformerDeleteSurviveRoundTrip() { + val file = skipMessageOrNull() ?: return + val result = + roundTrip(file) { puppet -> + // A leaf part (no sub-parts) keeps the cascade small; any deformer exercises the + // transform-tree removal. + val leafPart = + puppet.parts.firstOrNull { part -> part.children.none { it is OrgChild.Part } } + var model = puppet + if (leafPart != null) { + model = model.withPartDeleted(leafPart.id, cascade = true) + } + model.deformers.firstOrNull()?.let { deformer -> + model = model.withDeformerDeleted(deformer.id) + } + model + } + assertLossless(result, "part/deformer delete") + } + + @Test + fun topologyMergeSurvivesRoundTrip() { + val file = skipMessageOrNull() ?: return + var editedId: DrawableId? = null + val result = + roundTrip(file) { puppet -> + val drawable = + puppet.drawables.first { it.mesh != null && it.mesh!!.vertexCount >= 4 && it.mesh!!.indices.isNotEmpty() } + editedId = drawable.id + val mesh = drawable.mesh!! + // Merge the first triangle's first two vertices - a real topology reduction. + val topologyResult = + MeshTopologyOps.mergeVertices(mesh, listOf(mesh.indices[0], mesh.indices[1]), MergeTarget.AtCenter) + ?: error("merge refused") + puppet.withMeshTopologyEdit(drawable.id, topologyResult.edit) + } + assertLosslessExceptDrawableResidue(result, editedId!!, "topology merge") + } +} \ No newline at end of file diff --git a/module/format/build.gradle.kts b/module/format/build.gradle.kts new file mode 100644 index 0000000..1cdd986 --- /dev/null +++ b/module/format/build.gradle.kts @@ -0,0 +1,174 @@ +// :format — Cubism file family + art I/O. KMP library shared by desktop (JVM) and Android. +// :format — Cubism ファイル群とアート入出力。デスクトップ(JVM)と Android が共有する KMP ライブラリ。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + alias(libs.plugins.kotlinSerialization) + // Generates the typed CLIP database from module/format/src/commonMain/sqldelight/*.sq. + alias(libs.plugins.sqldelight) + // Umamo's own conventions (gradle/build-logic): the shared jvmAndroidMain source-set group, the + // iosArm64 → `check` wiring, and the corpus/-D forwarding configured by `umamoTestCorpus` below. + id("umamo.kmp-jvmandroid") + id("umamo.kmp-ios-gate") + id("umamo.test-corpus") +} + +kotlin { + // One toolchain for every target. Pinned to JDK 21 (LTS) — the build JVM and the + // bytecode level. `jvmToolchain` replaces hand-set sourceCompatibility/targetCompatibility. + jvmToolchain(21) + + // NOTE: `-Xexpect-actual-classes` used to live here, opting in to the Beta expect/actual CLASS + // feature (KT-61573) purely because CaffZip was an expect/actual object. It no longer is: the ZIP + // framing is plain commonMain code over the shared DEFLATE seam, and the module's only remaining + // expect is `useClipDatabase`, a top-level fun — which needs no opt-in. Do not add the flag back + // without a declaration that genuinely requires it. + + // The `jvmAndroidMain` group this module's CMO3 codec lives in comes from the + // `umamo.kmp-jvmandroid` convention plugin — CMO3 read/write is a JDOM + Kotlin-reflection XML + // serializer (NOT Java object serialization — see docs/format/CMO3.md), and those are JVM-only APIs. + // NOTE: commonMain purity is a COMPILER GUARANTEE in this module, not a convention — the iosArm64 + // target below is non-JVM, so `java.*` in commonMain is an unresolved reference rather than a + // latent surprise. (That is not true of a JVM-only module: there, commonMain resolves `java.*` + // happily and the root build's `checkCommonSourcePurity` regex task is the only net.) + + jvm() + + // The iPadOS target — and the reason commonMain purity is enforceable rather than merely intended. + // Windows, macOS, Linux and Android all run on the JVM (`:desktop` is jvm() packaged per-OS by + // jpackage), so iOS is the ONLY platform here that is not, and the only one that can catch a + // `java.*` leak or a `final`-on-native stdlib inheritance at compile time. It is not a proxy: no + // stand-in target is used, because a stand-in would prove "non-JVM" without proving Apple — and a + // dependency that publishes linuxX64 but not iosArm64 would sail straight through it. + // + // Compiles on Linux and on ubuntu CI: the Kotlin/Native Linux distribution bundles an iOS sysroot + // and the ios_arm64 platform klibs, and :format is a library with no binaries.framework {}, so + // nothing here needs Xcode's linker. Real iPadOS builds and native test runs happen on Apple + // hardware; this target is what makes the daily loop and CI fail fast instead of days later. + // + // iosArm64 is a DEVICE target, so it has no runnable test task — the gate is compile-time, and + // therefore nothing pulls it into `check` on its own; that is what `umamo.kmp-ios-gate` above fixes. + // Add iosSimulatorArm64() if native test EXECUTION on the Mac is wanted. + iosArm64() + + // New AGP KMP-aware Android target: declared inside `kotlin {}` (not a separate + // `com.android.library` module). namespace = R class package root. + android { + namespace = "org.umamo.format" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + // The `umamo.kmp-jvmandroid` convention plugin creates this group and wires androidMain onto it; + // it is not a well-known source-set name, so it has no generated accessor and is looked up here. + val jvmAndroidMain = getByName("jvmAndroidMain") + val androidMain = getByName("androidMain") + + commonMain.dependencies { + // `api`, not `implementation`: the UMA entry schemas (`uma/puppet/`) are public @Serializable + // classes whose generated companions return KSerializer, so the library is part of this + // module's public surface. + api(libs.kotlinxSerializationJson) + // okio: DEFLATE (its zlibMain source set reaches every target we build, iosArm64 included) + // and Buffer, the growable byte sink the codecs assemble output into. `implementation`, + // not `api`: no okio type appears in :format's public surface. + implementation(libs.okio) + // kotlinx-datetime: the local wall clock CaffZip stamps into the CAFF zip timestamp, to + // match what the official editor writes. The stdlib's common Clock has no time zone and a + // DOS timestamp is local, so this closes the gap without an expect/actual. + implementation(libs.kotlinxDatetime) + } + + // Shared by desktop JVM + Android: the CMO3 CAFF/XML codec. JDOM lives here (not jvmMain) + // because the editor's XML serializer must round-trip on both targets — CLAUDE.md keeps + // CMO3 read/write available on Android. JDOM 1.x works on Android via the platform's JAXP. + jvmAndroidMain.dependencies { + implementation(libs.jdom) + // The CMO3 serializer is reflection-driven (declaredMemberProperties, findAnnotation, + // javaField) — those kotlin.reflect.full/.jvm extensions live in kotlin-reflect, not + // the stdlib. Available on Android too, so it stays in the shared source set. + implementation(kotlin("reflect")) + } + jvmMain { + dependencies { + // Driver for CLIP's embedded SQLite database. + implementation(libs.sqldelightSqliteDriver) + } + } + androidMain.dependencies { + // Driver for CLIP's embedded SQLite database. + implementation(libs.sqldelightAndroidDriver) + } + // nativeMain, not iosArm64Main: the default hierarchy makes it the parent of appleMain, so the + // actual here already covers any further Apple target (a simulator, say) without moving. + nativeMain.dependencies { + // Driver for CLIP's embedded SQLite database (SQLiter under the hood). + implementation(libs.sqldelightNativeDriver) + // The native actual writes the extracted database to a temp file; okio is the only + // filesystem the common source sets have. + implementation(libs.okio) + } + commonTest { + dependencies { + implementation(kotlin("test")) + } + } + jvmTest { + dependencies { + // The synthetic CLIP fixture (ClipSyntheticReaderTest) drives the JDBC driver directly + // to generate its database. jvmMain already carries the driver, but the test's use is + // its own - declared here so it survives the driver ever moving out of jvmMain. + implementation(libs.sqldelightSqliteDriver) + } + } + } +} + +// SQLDelight: generate a typed ClipDatabase from src/commonMain/sqldelight/.../Clip.sq. +sqldelight { + databases { + create("ClipDatabase") { + packageName.set("org.umamo.format.clip.db") + } + } +} + +// Corpus wiring for the sample-gated tests (the `umamo.test-corpus` convention plugin). Explicit `-D` +// wins, the local golden corpus is the default, and absent both the test self-skips — see +// org.umamo.buildlogic.resolveCorpusSample in gradle/build-logic for the rules and why they are what +// they are. +// +// Most art readers (kra/clip/psd/tiff/jpeg/png/webp) additionally auto-discover test/corpus by walking +// up from the test working directory, so they need no default here — their entries exist only so an +// explicit `-D` can override. `bmp.sample` was dropped: nothing reads it. +umamoTestCorpus { + maxHeap("4g") + sample( + "cmo3.sample", + // Forwarded so AllVersionsGateTest can run at all — it was omitted here, so the + // cross-version parity gate could never see its property and always skipped. + "cmo3.probe", + // The MOC3 decode/lowering/bake/probe gates walk the whole moc3 corpus - without this they + // silently self-skipped on a plain `:format:jvmTest`. + "moc3.samples", + "kra.sample", + "clip.sample", + "psd.sample", + "png.sample", + "tiff.sample", + "webp.sample", + "jpeg.sample", + // ModelGenerator's input set. Defaults to the whole cmo3/ corpus so the generated model is the + // union across every sample (see sharedCorpusDefault). + "cmo3.gensample", + // Cmo3ResaveDumpTest's input list. Explicit-only (the shared table has no entry), so the resave + // dump never floods build/ on a plain test run. + "cmo3.resave", + ) + // ModelGenerator's on-switch — a boolean, not a path, so it goes through `flag` and skips the + // file-existence check. Without the forwarding the generator reads a property nobody set and + // returns immediately: a @Test reporting PASSED while generating nothing. + flag("cmo3.generate") +} \ No newline at end of file diff --git a/module/format/src/androidMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.android.kt b/module/format/src/androidMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.android.kt new file mode 100644 index 0000000..8ab7edb --- /dev/null +++ b/module/format/src/androidMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.android.kt @@ -0,0 +1,67 @@ +package org.umamo.format.clip + +import android.content.Context +import androidx.sqlite.db.SupportSQLiteDatabase +import app.cash.sqldelight.driver.android.AndroidSqliteDriver +import org.umamo.format.clip.db.ClipDatabase +import java.io.File + +/** + * Android app hook for the CLIP reader. Set [applicationContext] once at startup (from your + * Application or Activity, the same way the app calls FileKit.init): the Android SQLite driver needs + * a Context to locate a database file, but the format-neutral ArtReader.read(bytes) has none, so it + * is supplied here. Prefer the application context to avoid leaking an Activity. + * + * Android 用フック。起動時に applicationContext を一度設定する(Context が必要なため)。 + */ +object ClipAndroid { + // TODO(android-clip): currently assigned nowhere - the Android app has no file-open flow yet, so + // CLIP is unreachable there and this hook is inert. When Android gains an open path, set + // `ClipAndroid.applicationContext = applicationContext` in MainActivity.onCreate (where a future + // FileKit.init(this) will also go), or reading a .clip will fail the error() in useClipDatabase. + @Volatile + var applicationContext: Context? = null +} + +/** + * Android actual: write the database bytes into the app's databases dir and open the SQLDelight + * AndroidSqliteDriver over it. A no-op callback skips schema creation/migration - the embedded .clip + * database already has its tables (and carries user_version 0, which would otherwise trigger + * onCreate -> Schema.create and collide with the existing tables). + * + * @param ByteArray databaseBytes The raw "SQLite format 3" bytes. + * @param Function1 block Runs against the open database. + * @return T The block's result. + */ +internal actual fun useClipDatabase(databaseBytes: ByteArray, block: (ClipDatabase) -> T): T { + val context = + ClipAndroid.applicationContext + ?: error("ClipReader on Android requires ClipAndroid.applicationContext to be set at startup") + + // A short-lived DB under the app's databases dir; AndroidSqliteDriver(name) opens the same path. + val name = "umamo-clip-${System.nanoTime()}.sqlite3" + val databaseFile = context.getDatabasePath(name) + databaseFile.parentFile?.mkdirs() + databaseFile.writeBytes(databaseBytes) + try { + // Skip Schema.create/migrate: the file already is a complete CLIP database. + val callback = + object : AndroidSqliteDriver.Callback(ClipDatabase.Schema) { + override fun onCreate(db: SupportSQLiteDatabase) = Unit + + override fun onUpgrade(db: SupportSQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit + } + val driver = AndroidSqliteDriver(schema = ClipDatabase.Schema, context = context, name = name, callback = callback) + try { + return block(ClipDatabase(driver)) + } finally { + driver.close() + } + } finally { + databaseFile.delete() + // SQLite may create sidecar journal/WAL files next to the database; remove them too. + File("${databaseFile.path}-wal").delete() + File("${databaseFile.path}-shm").delete() + File("${databaseFile.path}-journal").delete() + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/FileKind.kt b/module/format/src/commonMain/kotlin/org/umamo/format/FileKind.kt new file mode 100644 index 0000000..1423c10 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/FileKind.kt @@ -0,0 +1,145 @@ +package org.umamo.format + +/** + * What the editor does with a file, as the file's kind declares it. + * + * The distinction is not about which codec reads the bytes - it is about which way in a file takes. A + * document REPLACES what is open (behind the unsaved-changes gate); artwork is ADDED to the document + * that is already open, the way importing an object into a Blender scene adds to it. A sidecar is + * neither: it is found beside a file the editor opened, never handed over on its own. + */ +enum class FileRole { + /** Opens as the whole document: the native `.uma`, and the CMO3 / MOC3 the editor imports. */ + Document, + + /** Ingested as source art into the open document: the layered formats and the flat rasters. */ + Artwork, + + /** Read beside a document, never opened as one: the MOC3 JSON family. */ + Sidecar, +} + +/** + * The file families Umamo understands, plus the art-source formats it ingests. + * + * Modelled as a `sealed interface` so a `when` over kinds is exhaustive (the compiler rejects an + * unhandled case) - the same enforcement applied to [Cmo3Version]. Each kind declares its + * capabilities ([readable]/[writable]/[role]), so dispatch and UI can reason about support without a + * scattered list of booleans, and its [extension] (with any [extensionAliases]), so nothing else + * spells the extension by hand. + */ +sealed interface FileKind { + /** Conventional file extension without the dot, e.g. `"cmo3"`. */ + val extension: String + + /** + * Other extensions the same format is written under, without the dot. + * + * Detection is by magic bytes, so an alias only matters where the name is the only signal - the + * extension fallback in [FormatRegistry.kindForFileName] and the picker filters built from it. + */ + val extensionAliases: List get() = emptyList() + val readable: Boolean + val writable: Boolean + + /** Which way into the editor a file of this kind takes. */ + val role: FileRole + + // --- Umamo UMA!~ --- + data object Uma : FileKind { + override val extension = "uma" + override val readable = true + override val writable = true + override val role = FileRole.Document + } + + // --- Live2D Cubism CMO3 Puppet Model --- + data object Cmo3 : FileKind { + override val extension = "cmo3" + override val readable = true + override val writable = true + override val role = FileRole.Document + } + + // --- Live2D Cubism MOC3 Puppet Model --- + data object Moc3 : FileKind { + override val extension = "moc3" + override val readable = true + override val writable = true + override val role = FileRole.Document + } + + // --- Live2D Cubism MOC3 Puppet Model Sidecar Files - model3/physics3/cdi3/pose3/exp3/motion3/userdata3. --- + data object Json : FileKind { + override val extension = "json" + override val readable = true + override val writable = true + override val role = FileRole.Sidecar + } + + // --- Adobe Photoshop PSD Layered Artwork --- + data object Psd : FileKind { + override val extension = "psd" + override val readable = true + override val writable = false + override val role = FileRole.Artwork + } + + // --- Clip Studio Paint CLIP Layered Artwork --- + data object Clip : FileKind { + override val extension = "clip" + override val readable = true + override val writable = false + override val role = FileRole.Artwork + } + + // --- Krita KRA Layered Artwork --- + data object Kra : FileKind { + override val extension = "kra" + override val readable = true + override val writable = false + override val role = FileRole.Artwork + } + + // --- PNG Raster Artwork --- + data object Png : FileKind { + override val extension = "png" + override val readable = true + override val writable = true + override val role = FileRole.Artwork + } + + // --- BMP Raster Artwork --- + data object Bmp : FileKind { + override val extension = "bmp" + override val readable = true + override val writable = true + override val role = FileRole.Artwork + } + + // --- JPEG Raster Artwork --- + data object Jpeg : FileKind { + override val extension = "jpg" + override val extensionAliases = listOf("jpeg") + override val readable = true + override val writable = false + override val role = FileRole.Artwork + } + + // --- WEBP Raster Artwork --- + data object WebP : FileKind { + override val extension = "webp" + override val readable = true + override val writable = false + override val role = FileRole.Artwork + } + + // --- TIFF Raster Artwork --- + data object Tiff : FileKind { + override val extension = "tiff" + override val extensionAliases = listOf("tif") + override val readable = true + override val writable = false + override val role = FileRole.Artwork + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/FormatCodec.kt b/module/format/src/commonMain/kotlin/org/umamo/format/FormatCodec.kt new file mode 100644 index 0000000..1c579e8 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/FormatCodec.kt @@ -0,0 +1,78 @@ +package org.umamo.format + +/** + * The shared read/write contract for one binary container format in the Cubism/Umamo file family. + * + * EN: Every format Umamo can both parse and emit as a self-contained byte stream (today `.cmo3` and + * `.moc3`; later `.uma`) exposes the same members, so callers and the [FormatRegistry] + * dispatcher treat formats uniformly instead of hardcoding one facade's method names. The + * in-memory model type differs per format ([org.umamo.format.cmo3.Cmo3Model] vs + * [org.umamo.format.moc3.moc.MocModel]) and the two share no supertype - hence the generic + * [TModel]; a heterogeneous registry holds `FormatCodec<*>` and callers branch on [kind]. The + * dependency runs codec → [FileKind] (a codec names its kind), never the reverse, so [FileKind] + * stays pure metadata. Text sidecars (`model3.json` and friends) are `String`-shaped, not + * `ByteArray`, so they deliberately fall outside this contract. + * JA: `.cmo3`/`.moc3` など「バイト列で完結する」形式の共通読み書き契約。モデル型は形式ごとに異なる。 + */ +public interface FormatCodec { + /** Which [FileKind] this codec reads and writes - the link to capability/tier metadata. */ + public val kind: FileKind + + /** + * Cheap magic-byte sniff: whether [candidateBytes] plausibly belongs to this format. + * + * Intended to be allocation-light (inspect only the leading magic), so [FormatRegistry] can try + * every codec against a file without fully parsing it. + * + * @param ByteArray candidateBytes The file contents to test. + * @return Boolean True if the leading bytes match this format's signature. + */ + public fun matches(candidateBytes: ByteArray): Boolean + + /** + * Cheap version probe: the format version carried by [bytes], without a full [read]. + * + * Implementations must stay lightweight next to [read] (decode only what the version requires) + * and must not throw on malformed or unknown input - null covers both "this codec exposes no + * version" (the default, kept by the layered-art readers) and "no version could be determined". + * + * @param ByteArray bytes The complete file contents. + * @return FormatVersion? The probed version, or null when unavailable. + */ + public fun getVersion(bytes: ByteArray): FormatVersion? = null + + /** + * Parses a complete file into this format's in-memory model. + * + * @param ByteArray bytes The complete file contents. + * @return TModel The parsed model. + */ + public fun read(bytes: ByteArray): TModel + + /** + * Serializes a model back to a complete file. + * + * @param TModel model The model to write. + * @return ByteArray The complete file bytes. + */ + public fun write(model: TModel): ByteArray +} + +/** + * A [FormatCodec] for a format Umamo reads but never emits - the layered-art ingestion sources + * (PSD, CLIP, KRA), whose [FileKind] already declares `writable = false`. Inherits a [write] that + * refuses, so the read-only nature is stated once in the type instead of copy-pasted throws in each + * reader; the [FormatRegistry] still holds these uniformly as `FormatCodec<*>`. + * + * 読み取り専用形式(PSD/CLIP/KRA などの画材取り込み元)用の FormatCodec。write は常に拒否する。 + */ +public interface ReadOnlyCodec : FormatCodec { + /** + * Always refuses: this format is ingestion-only. + * + * @param TModel model Ignored. + * @return ByteArray Never returns. + */ + override fun write(model: TModel): ByteArray = + throw UnsupportedOperationException("${kind.extension.uppercase()} is read-only") +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/FormatVersion.kt b/module/format/src/commonMain/kotlin/org/umamo/format/FormatVersion.kt new file mode 100644 index 0000000..654ffe1 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/FormatVersion.kt @@ -0,0 +1,22 @@ +package org.umamo.format + +/** + * A probed format version, the common face over each codec's own version type. + * + * [org.umamo.format.moc3.moc.MocVersion] (an enum) and [org.umamo.format.cmo3.Cmo3Version] (a + * sealed interface) share no other supertype - mirroring how the codec model types share none - + * so this marker is what lets [FormatCodec.getVersion] report a version uniformly. Not to be + * confused with the serialized CMO3 model enum `org.umamo.format.cmo3.model.gen.FormatVersion`, + * which is format data inside the document, not a probe result. + */ +public interface FormatVersion { + /** Short human-readable token naming the version (e.g. "cmo3 / Cubism 4.x"). */ + public val label: String + + /** + * A human-readable support summary for this version. + * + * @return String The summary sentence. + */ + public fun describe(): String +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/art/AlphaAnalysis.kt b/module/format/src/commonMain/kotlin/org/umamo/format/art/AlphaAnalysis.kt new file mode 100644 index 0000000..6698640 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/art/AlphaAnalysis.kt @@ -0,0 +1,230 @@ +package org.umamo.format.art + +/** + * Default alpha threshold: a pixel counts as opaque when its alpha byte is at least this value. + * + * 1 means any nonzero alpha counts, which keeps the trimmed bounds lossless for the atlas + * packer: no antialiased edge pixel (alpha 1..10) is ever cut away, so nothing visible can be + * clipped at an atlas tile boundary. Consumers wanting a stricter silhouette (the auto-mesh) + * pass a higher threshold instead of changing this default. + */ +public const val DEFAULT_ALPHA_THRESHOLD: Int = 1 + +/** + * Default Douglas-Peucker simplification tolerance for the alpha contour, in pixels. + * + * 1.0 collapses the unit staircase that a 45 degree antialiased edge traces (maximum deviation + * from the true diagonal is sqrt(2)/2, about 0.707 px) into single segments, while the + * Douglas-Peucker guarantee keeps the simplified polygon within one pixel of the exact mask + * boundary. 0 keeps the exact lattice ring. + */ +public const val DEFAULT_CONTOUR_EPSILON: Float = 1.0f + +/** + * The opaque-region description of one raster: pixel-tight trimmed bounds, an occupancy + * summary, and the boundary contour(s) of the thresholded alpha mask. This is the shared + * foundation the atlas packer (trimmed rects) and the auto-mesh (silhouette) both consume. + * + * A plain class, not a data class: it holds contour point arrays (via [contours]) for which + * generated structural equality would deep-compare arrays. Identity equality is the right + * default, matching [LayerRaster]. + */ +public class AlphaAnalysis( + /** + * Pixel-tight bounds of the opaque region, RASTER-LOCAL: left/top are relative to the + * raster's own origin, not the source canvas. Offset by the layer's canvas position via + * [opaqueBoundsOnCanvas] when canvas space is needed. + */ + public val opaqueBounds: LayerBounds, + /** Number of pixels whose alpha met the threshold. */ + public val opaquePixelCount: Int, + /** + * Boundary contours of the thresholded alpha mask, raster-local, one per opaque island + * plus one per enclosed hole ([AlphaContour.isHole]). Never empty on a non-null analysis, + * and always contains at least one non-hole contour. + */ + public val contours: List, +) { + /** Fraction of the trimmed bounds covered by opaque pixels, in 0.0..1.0. */ + public val boundsCoverage: Float + get() = opaquePixelCount.toFloat() / (opaqueBounds.width.toFloat() * opaqueBounds.height.toFloat()) +} + +/** + * One closed boundary loop of the thresholded alpha mask. + * + * Points are integer pixel-corner lattice coordinates (x in 0..width, y in 0..height, y down), + * raster-local: a contour point is a corner BETWEEN pixels, not a pixel center, so pixel + * (column, row) occupies the unit square [column, column+1] x [row, row+1] and the polygon is + * watertight and pixel-exact. Closure is implicit: the last point connects back to the first + * (they are never equal). Winding encodes the region side: walking the ring keeps opaque + * pixels on the right (y-down), so outer contours have positive shoelace area and holes have + * negative. [isHole] is derived from the exact ring and is the authoritative flag: the + * winding redundancy is guaranteed only for exact rings (contourEpsilon 0), because an + * adversarially self-intersecting simplified ring's shoelace sign may disagree (the known + * simplifier limitation) — do not re-derive hole-ness from a simplified ring's winding. + * + * A contour may touch itself at a saddle corner (a repeated non-consecutive vertex, "weakly + * simple"); it never crosses itself. + * + * A plain class, not a data class: it wraps a point array for which generated structural + * equality would deep-compare on every call. + */ +public class AlphaContour( + /** Flattened corner coordinates x0, y0, x1, y1, ...; the final point connects to the first. */ + public val points: IntArray, + /** True when this loop encloses a transparent hole inside an opaque island. */ + public val isHole: Boolean, +) + +/** + * Analyzes the opaque region of an RGBA8888 straight-alpha raster (top row first): pixel-tight + * trimmed bounds, opaque pixel count, and the traced boundary contours, optionally simplified. + * + * Despite the file's "alpha analysis" theme this is NOT an Edelsbrunner alpha shape (no + * Delaunay parameter); it is a threshold mask description: a scan for bounds and count, a + * marching-squares style boundary trace on the pixel-corner lattice, and Douglas-Peucker + * simplification. Output is fully deterministic for a given input, which downstream repacking + * relies on. + * + * Returns null if and only if no pixel meets [alphaThreshold] — including the 0x0 raster and + * the 1x1 transparent placeholders the CLIP/KRA readers emit for empty layers. Slivers with + * real opaque pixels (1 px wide or tall) are reported with their true bounds; excluding them + * is consumer policy, so a genuine hairline art layer is never dropped here. + * + * @param Int width Raster width in pixels; may be 0. + * @param Int height Raster height in pixels; may be 0. + * @param ByteArray rgba RGBA8888 pixels, straight alpha, row-major from the top row; exactly width * height * 4 bytes. + * @param Int alphaThreshold Minimum alpha byte value (1..255) for a pixel to count as opaque. + * @param Float contourEpsilon Douglas-Peucker tolerance in pixels; 0 keeps the exact lattice rings. + * @return AlphaAnalysis The RASTER-LOCAL opaque-region description (bounds and contours are + * relative to the raster's own origin, not the source canvas), or null when nothing + * meets the threshold. + */ +public fun analyzeAlpha( + width: Int, + height: Int, + rgba: ByteArray, + alphaThreshold: Int = DEFAULT_ALPHA_THRESHOLD, + contourEpsilon: Float = DEFAULT_CONTOUR_EPSILON, +): AlphaAnalysis? { + require(width >= 0 && height >= 0) { "raster dimensions must be non-negative: $width x $height" } + require(rgba.size.toLong() == width.toLong() * height.toLong() * 4L) { + "rgba size ${rgba.size} does not match $width x $height x 4" + } + require(alphaThreshold in 1..255) { + "alphaThreshold must be in 1..255 (0 marks everything opaque, 256 nothing): $alphaThreshold" + } + require(contourEpsilon >= 0f) { "contourEpsilon must be non-negative: $contourEpsilon" } + + // Pass 1: one row-major sweep folds the trimmed bounds and the count, and builds the + // bit-packed mask the tracer walks. Packed LongArray, not BooleanArray: an 8192^2 layer + // is 67M pixels — 8.4 MB packed versus 67 MB boolean, and the tracer needs a second + // same-geometry bitset (Android heap decides this). + val pixelCount = width * height + val maskWords = LongArray((pixelCount + 63) ushr 6) + var opaquePixelCount = 0 + var minRow = Int.MAX_VALUE + var maxRow = -1 + var minColumn = Int.MAX_VALUE + var maxColumn = -1 + var pixelIndex = 0 + for (rowIndex in 0 until height) { + for (columnIndex in 0 until width) { + // The `and 0xFF` is load-bearing: Kotlin Byte is signed, so alpha 128..255 reads + // negative without it and a >= threshold compare silently drops those pixels. + val alpha = rgba[pixelIndex * 4 + 3].toInt() and 0xFF + if (alpha >= alphaThreshold) { + opaquePixelCount++ + maskWords[pixelIndex ushr 6] = maskWords[pixelIndex ushr 6] or (1L shl (pixelIndex and 63)) + if (rowIndex < minRow) { + minRow = rowIndex + } + if (rowIndex > maxRow) { + maxRow = rowIndex + } + if (columnIndex < minColumn) { + minColumn = columnIndex + } + if (columnIndex > maxColumn) { + maxColumn = columnIndex + } + } + pixelIndex++ + } + } + if (opaquePixelCount == 0) { + return null + } + + val opaqueBounds = + LayerBounds( + left = minColumn, + top = minRow, + width = maxColumn - minColumn + 1, + height = maxRow - minRow + 1, + ) + val mask = AlphaMask(width, height, maskWords) + val exactContours = traceAlphaContours(mask, opaqueBounds) + val contours = + if (contourEpsilon > 0f) { + exactContours.map { contour -> + // simplifyClosedRing returns the input array itself when nothing can drop; + // reuse the contour object then instead of re-wrapping the same ring. + val simplifiedPoints = simplifyClosedRing(contour.points, contourEpsilon) + if (simplifiedPoints === contour.points) { + contour + } else { + AlphaContour(simplifiedPoints, contour.isHole) + } + } + } else { + exactContours + } + return AlphaAnalysis(opaqueBounds, opaquePixelCount, contours) +} + +/** + * Analyzes this layer raster's opaque region. See the positional [analyzeAlpha] for the full + * contract. + * + * @param Int alphaThreshold Minimum alpha byte value (1..255) for a pixel to count as opaque. + * @param Float contourEpsilon Douglas-Peucker tolerance in pixels; 0 keeps the exact lattice rings. + * @return AlphaAnalysis The opaque-region description, or null when nothing meets the threshold. + */ +public fun LayerRaster.analyzeAlpha( + alphaThreshold: Int = DEFAULT_ALPHA_THRESHOLD, + contourEpsilon: Float = DEFAULT_CONTOUR_EPSILON, +): AlphaAnalysis? = analyzeAlpha(width, height, rgba, alphaThreshold, contourEpsilon) + +/** + * Analyzes this layer's opaque region from its stored raster pixels. + * + * Deliberately ignores the layer's compositing properties — opacity, visible, blend, and + * channelMask describe how the pixels composite, not what is stored, and applying them is + * consumer policy. Results are raster-local; use [opaqueBoundsOnCanvas] with + * [SourceLayer.bounds] for canvas space. + * + * @param Int alphaThreshold Minimum alpha byte value (1..255) for a pixel to count as opaque. + * @param Float contourEpsilon Douglas-Peucker tolerance in pixels; 0 keeps the exact lattice rings. + * @return AlphaAnalysis The opaque-region description, or null when nothing meets the threshold. + */ +public fun SourceLayer.analyzeAlpha( + alphaThreshold: Int = DEFAULT_ALPHA_THRESHOLD, + contourEpsilon: Float = DEFAULT_CONTOUR_EPSILON, +): AlphaAnalysis? = raster.analyzeAlpha(alphaThreshold, contourEpsilon) + +/** + * Converts the raster-local trimmed bounds to source-canvas space by offsetting with the + * layer's canvas position ([SourceLayer.bounds] left/top). + * + * @param LayerBounds layerBounds The layer's position on the source canvas. + * @return LayerBounds The trimmed opaque bounds in source-canvas space. + */ +public fun AlphaAnalysis.opaqueBoundsOnCanvas(layerBounds: LayerBounds): LayerBounds = + LayerBounds( + left = layerBounds.left + opaqueBounds.left, + top = layerBounds.top + opaqueBounds.top, + width = opaqueBounds.width, + height = opaqueBounds.height, + ) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/art/AlphaContourTrace.kt b/module/format/src/commonMain/kotlin/org/umamo/format/art/AlphaContourTrace.kt new file mode 100644 index 0000000..f21347d --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/art/AlphaContourTrace.kt @@ -0,0 +1,236 @@ +package org.umamo.format.art + +/** + * A bit-packed boolean mask over a raster's pixels, one bit per pixel, row-major from the top. + * + * Out-of-range coordinates read as transparent so the boundary tracer needs no padding ring + * around the raster. Packed into a LongArray rather than a BooleanArray because the tracer's + * inputs can be large (an 8192^2 layer is 67M pixels) and two same-geometry bitsets are alive + * at once during tracing. + * + * @param Int width Mask width in pixels. + * @param Int height Mask height in pixels. + * @param LongArray words The packed bits, bit (rowIndex * width + columnIndex). + */ +internal class AlphaMask( + val width: Int, + val height: Int, + private val words: LongArray, +) { + /** + * Whether the pixel at the given coordinates is opaque; out-of-range is transparent. + * + * @param Int columnIndex Pixel column, any value. + * @param Int rowIndex Pixel row, any value. + * @return Boolean True when in range and the mask bit is set. + */ + fun isOpaque(columnIndex: Int, rowIndex: Int): Boolean { + if (columnIndex < 0 || columnIndex >= width || rowIndex < 0 || rowIndex >= height) { + return false + } + val pixelIndex = rowIndex * width + columnIndex + return (words[pixelIndex ushr 6] and (1L shl (pixelIndex and 63))) != 0L + } +} + +/** + * A growable flat (x, y) point accumulator for contour tracing, doubling on demand. + * + * Exists because commonMain has no java.util growable primitives and boxing every lattice + * corner into a List would swamp the trace loop on large contours. + */ +private class ContourPointBuffer { + private var storage = IntArray(INITIAL_CAPACITY) + private var size = 0 + + /** + * Appends one point. + * + * @param Int x Lattice corner x. + * @param Int y Lattice corner y. + */ + fun add(x: Int, y: Int) { + if (size + 2 > storage.size) { + storage = storage.copyOf(storage.size * 2) + } + storage[size] = x + storage[size + 1] = y + size += 2 + } + + /** The accumulated points as a right-sized flat array. */ + fun toArray(): IntArray = storage.copyOf(size) + + private companion object { + const val INITIAL_CAPACITY = 32 + } +} + +/** + * Twice the signed shoelace area of a closed flat-point ring (implicit closure, y-down). + * + * Under the tracer's opaque-on-the-right winding, outer contours are positive and holes are + * negative, and the signed areas of all contours of one mask sum to exactly twice the opaque + * pixel count — the tracer's core invariant, which tests assert. Long because a full-canvas + * ring at PSB scale overflows Int. + * + * @param IntArray points Flattened x0, y0, x1, y1, ... ring; last point connects to the first. + * @return Long Twice the signed area. + */ +internal fun signedAreaTwice(points: IntArray): Long { + var doubledArea = 0L + val pointCount = points.size / 2 + for (pointIndex in 0 until pointCount) { + val nextIndex = if (pointIndex + 1 == pointCount) 0 else pointIndex + 1 + val x = points[pointIndex * 2].toLong() + val y = points[pointIndex * 2 + 1].toLong() + val nextX = points[nextIndex * 2].toLong() + val nextY = points[nextIndex * 2 + 1].toLong() + doubledArea += x * nextY - nextX * y + } + return doubledArea +} + +/** + * Traces every closed boundary contour of the mask — outer island boundaries and enclosed + * holes — as exact pixel-corner lattice rings. + * + * This is boundary tracing on the pixel-corner lattice (the axis-aligned "outline of the + * union of pixel squares"), not the midpoint-interpolating marching-squares isoline, which + * would offset every polygon by half a pixel and cut corners. The walk keeps opaque pixels + * on the right of the travel direction (y-down), so outer contours come out with positive + * shoelace area and holes negative. Saddle corners (the two diagonal pixels opaque) take the + * tight right turn, i.e. 4-connected foreground / 8-connected background: a diagonal + * checkerboard traces as separate unit squares and loops never cross themselves (though one + * loop may touch itself at a saddle corner). Vertices are emitted only where the heading + * changes, so straight runs carry no interior points and the exact ring is already minimal. + * + * Discovery is a row-major scan restricted to the trimmed bounds: every loop, outer or hole, + * contains at least one "north edge" (transparent-or-border pixel above, opaque pixel below), + * which this winding always walks eastward, so marking traversed north edges in one extra + * bitset makes each loop discoverable exactly once. The scan order also pins determinism — + * each contour starts at its topmost-then-leftmost north edge and contours are listed in that + * discovery order — which downstream repacking relies on. Total cost is one bounds-restricted + * mask scan plus O(total boundary length). + * + * Worst case to know about: a 50 percent checkerboard-noise mask yields one unit-square + * contour per opaque pixel (millions of tiny rings on a large layer). Pathological input; no + * mitigation here. + * + * @param AlphaMask mask The thresholded pixel mask; must contain at least one opaque pixel. + * @param LayerBounds opaqueBounds The pixel-tight trimmed bounds of the mask's opaque pixels. + * @return List The traced contours; never empty, at least one non-hole. + */ +internal fun traceAlphaContours(mask: AlphaMask, opaqueBounds: LayerBounds): List { + val contours = mutableListOf() + // Bit per pixel: set when the north edge of that pixel (the edge to the pixel above) has + // been walked. Same geometry as the mask itself. + val northEdgeVisited = LongArray(((mask.width * mask.height) + 63) ushr 6) + for (rowIndex in opaqueBounds.top until opaqueBounds.top + opaqueBounds.height) { + for (columnIndex in opaqueBounds.left until opaqueBounds.left + opaqueBounds.width) { + if (!mask.isOpaque(columnIndex, rowIndex)) { + continue + } + if (mask.isOpaque(columnIndex, rowIndex - 1)) { + continue + } + val edgeIndex = rowIndex * mask.width + columnIndex + if ((northEdgeVisited[edgeIndex ushr 6] and (1L shl (edgeIndex and 63))) != 0L) { + continue + } + contours.add(traceLoop(mask, northEdgeVisited, columnIndex, rowIndex)) + } + } + return contours +} + +/** + * Walks one closed boundary loop starting from the north edge of the given opaque pixel, + * heading east, and returns its ring with the hole flag derived from the shoelace sign. + * + * Walk invariant: every traversed lattice edge has an opaque pixel on its right and a + * transparent one on its left (relative to the travel direction, y-down). At each corner the + * two pixels flanking the edge straight ahead pick the turn: + * + * left opaque, right opaque -> turn left (hug the corner) + * left clear, right opaque -> straight + * left clear, right clear -> turn right (round the corner) + * left opaque, right clear -> saddle -> tight right turn (4-connected foreground) + * + * The loop terminates when it is about to re-traverse the starting directed edge (same corner + * AND same heading — the corner alone is not enough, because a weakly simple loop may pass + * through the start corner again with a different heading). Every eastward edge walked is by + * construction the north edge of the opaque pixel below it, and is marked in the visited + * bitset so discovery never starts this loop twice. + * + * @param AlphaMask mask The thresholded pixel mask. + * @param LongArray northEdgeVisited Bit per pixel, set here for every eastward edge walked. + * @param Int startColumn Column of the opaque pixel whose north edge starts the loop. + * @param Int startRow Row of the opaque pixel whose north edge starts the loop. + * @return AlphaContour The traced ring. + */ +private fun traceLoop( + mask: AlphaMask, + northEdgeVisited: LongArray, + startColumn: Int, + startRow: Int, +): AlphaContour { + val points = ContourPointBuffer() + var cornerX = startColumn + var cornerY = startRow + var headingX = 1 + var headingY = 0 + // The start corner is always a genuine vertex: the walk can only enter it turning (the + // pixel to its west having a north edge on the same loop would have been discovered + // first), so emitting it up front never duplicates a straight-run point. + points.add(cornerX, cornerY) + while (true) { + if (headingX == 1) { + // An eastward edge always has its opaque pixel below (opaque-on-right), so the + // below pixel (cornerX, cornerY) is in range and this is its north edge. + val edgeIndex = cornerY * mask.width + cornerX + northEdgeVisited[edgeIndex ushr 6] = northEdgeVisited[edgeIndex ushr 6] or (1L shl (edgeIndex and 63)) + } + cornerX += headingX + cornerY += headingY + // The two pixels flanking the edge straight ahead. The quadrant offsets reduce to + // these closed forms; each division operand is always -2 or 0, so truncation is exact. + val leftOpaque = + mask.isOpaque( + cornerX + (headingX + headingY - 1) / 2, + cornerY + (headingY - headingX - 1) / 2, + ) + val rightOpaque = + mask.isOpaque( + cornerX + (headingX - headingY - 1) / 2, + cornerY + (headingY + headingX - 1) / 2, + ) + val newHeadingX: Int + val newHeadingY: Int + if (leftOpaque && rightOpaque) { + // Turn left. + newHeadingX = headingY + newHeadingY = -headingX + } else if (rightOpaque) { + // Straight on. + newHeadingX = headingX + newHeadingY = headingY + } else { + // Both clear, or the diagonal saddle (left opaque, right clear): turn right. The + // saddle right turn is the 4-connected-foreground policy — diagonal-only contact + // separates rather than merges. + newHeadingX = -headingY + newHeadingY = headingX + } + if (cornerX == startColumn && cornerY == startRow && newHeadingX == 1 && newHeadingY == 0) { + break + } + if (newHeadingX != headingX || newHeadingY != headingY) { + points.add(cornerX, cornerY) + } + headingX = newHeadingX + headingY = newHeadingY + } + val ring = points.toArray() + return AlphaContour(ring, isHole = signedAreaTwice(ring) < 0L) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/art/ContourSimplify.kt b/module/format/src/commonMain/kotlin/org/umamo/format/art/ContourSimplify.kt new file mode 100644 index 0000000..be39b94 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/art/ContourSimplify.kt @@ -0,0 +1,199 @@ +package org.umamo.format.art + +/** + * A growable Int stack for the iterative Douglas-Peucker range walk. + * + * Exists because contours can carry 100k+ vertices and a recursive formulation would gamble + * on Kotlin/Native stack depth in commonMain; java.util.ArrayDeque is unavailable here. + */ +private class IntStack { + private var storage = IntArray(INITIAL_CAPACITY) + private var size = 0 + + /** + * Pushes one value. + * + * @param Int value The value to push. + */ + fun push(value: Int) { + if (size == storage.size) { + storage = storage.copyOf(storage.size * 2) + } + storage[size] = value + size++ + } + + /** Removes and returns the top value; the caller guarantees non-emptiness. */ + fun pop(): Int { + size-- + return storage[size] + } + + /** Whether any values remain. */ + fun isNotEmpty(): Boolean = size > 0 + + private companion object { + const val INITIAL_CAPACITY = 64 + } +} + +/** + * Simplifies a closed lattice ring with Douglas-Peucker, returning a subset of its vertices. + * + * Closed rings get the standard two-anchor treatment: anchor A is ring index 0 (the tracer's + * deterministic topmost-then-leftmost start vertex) and anchor B is the vertex farthest from A + * (ties resolve to the lowest index); the two open halves A->B and B->A are simplified + * independently, so both anchors always survive. The walk is iterative over an explicit range + * stack. Distances are exact until the final comparison: Long integer dot and cross products, + * squared distance to the clamped segment (robust for halves that double back), and a strict + * greater-than against epsilon squared, so epsilon 0 drops exactly-collinear vertices and + * nothing else. + * + * Guarantees: every kept vertex is an original lattice vertex on the exact mask boundary, and + * every dropped vertex lies within epsilon pixels of a segment of the simplified ring (the + * Douglas-Peucker construction), so the result deviates from the exact boundary by at most + * epsilon. If simplification would leave fewer than 3 points (a 1xN sliver's rectangle at + * epsilon 1 collapses to its two anchors), the unsimplified ring is returned instead. Output + * is deterministic. + * + * Known limitation, accepted for v1: on adversarial shapes Douglas-Peucker can produce a + * self-intersecting simplified ring. Callers needing a guaranteed-simple polygon should pass + * a smaller epsilon (or 0) until a topology-preserving variant exists. + * + * @param IntArray points Flattened x0, y0, x1, y1, ... closed ring; last point connects to the first. + * @param Float epsilon Maximum allowed deviation from the input ring, in pixels; non-negative. + * @return IntArray The simplified ring, or the input array itself when nothing can be dropped. + */ +internal fun simplifyClosedRing(points: IntArray, epsilon: Float): IntArray { + val pointCount = points.size / 2 + if (pointCount < 4) { + // A triangle is already minimal: dropping any vertex would degenerate the ring. + return points + } + + var anchorB = 0 + var anchorBSquaredDistance = -1L + for (pointIndex in 1 until pointCount) { + val deltaX = (points[pointIndex * 2] - points[0]).toLong() + val deltaY = (points[pointIndex * 2 + 1] - points[1]).toLong() + val squaredDistance = deltaX * deltaX + deltaY * deltaY + if (squaredDistance > anchorBSquaredDistance) { + anchorBSquaredDistance = squaredDistance + anchorB = pointIndex + } + } + + val keep = BooleanArray(pointCount) + keep[0] = true + keep[anchorB] = true + val epsilonSquared = epsilon.toDouble() * epsilon.toDouble() + + // Ranges use virtual indices 0..pointCount so the wrap-around half (anchorB back to A) is + // a plain ascending range; a virtual index maps to ring index (virtual % pointCount). + val rangeStack = IntStack() + rangeStack.push(0) + rangeStack.push(anchorB) + rangeStack.push(anchorB) + rangeStack.push(pointCount) + while (rangeStack.isNotEmpty()) { + val lastVirtual = rangeStack.pop() + val firstVirtual = rangeStack.pop() + if (lastVirtual - firstVirtual < 2) { + continue + } + val segmentStartIndex = (firstVirtual % pointCount) * 2 + val segmentEndIndex = (lastVirtual % pointCount) * 2 + var farthestVirtual = -1 + var farthestSquaredDistance = -1.0 + for (interiorVirtual in firstVirtual + 1 until lastVirtual) { + val interiorIndex = (interiorVirtual % pointCount) * 2 + val squaredDistance = + squaredDistanceToSegment( + pointX = points[interiorIndex], + pointY = points[interiorIndex + 1], + segmentStartX = points[segmentStartIndex], + segmentStartY = points[segmentStartIndex + 1], + segmentEndX = points[segmentEndIndex], + segmentEndY = points[segmentEndIndex + 1], + ) + if (squaredDistance > farthestSquaredDistance) { + farthestSquaredDistance = squaredDistance + farthestVirtual = interiorVirtual + } + } + if (farthestSquaredDistance > epsilonSquared) { + keep[farthestVirtual % pointCount] = true + rangeStack.push(firstVirtual) + rangeStack.push(farthestVirtual) + rangeStack.push(farthestVirtual) + rangeStack.push(lastVirtual) + } + } + + var keptCount = 0 + for (pointIndex in 0 until pointCount) { + if (keep[pointIndex]) { + keptCount++ + } + } + if (keptCount < 3) { + return points + } + if (keptCount == pointCount) { + return points + } + val simplified = IntArray(keptCount * 2) + var writeIndex = 0 + for (pointIndex in 0 until pointCount) { + if (keep[pointIndex]) { + simplified[writeIndex] = points[pointIndex * 2] + simplified[writeIndex + 1] = points[pointIndex * 2 + 1] + writeIndex += 2 + } + } + return simplified +} + +/** + * Squared distance from a point to a segment, clamped to the segment's endpoints. + * + * Dot, cross, and length products are exact Longs from Int coordinates; only the final + * quotient goes through Double. A zero-length segment (possible between weakly simple ring + * vertices that coincide) degrades to point distance. + * + * @param Int pointX The point's x. + * @param Int pointY The point's y. + * @param Int segmentStartX Segment start x. + * @param Int segmentStartY Segment start y. + * @param Int segmentEndX Segment end x. + * @param Int segmentEndY Segment end y. + * @return Double The squared distance in pixels squared. + */ +private fun squaredDistanceToSegment( + pointX: Int, + pointY: Int, + segmentStartX: Int, + segmentStartY: Int, + segmentEndX: Int, + segmentEndY: Int, +): Double { + val segmentDeltaX = (segmentEndX - segmentStartX).toLong() + val segmentDeltaY = (segmentEndY - segmentStartY).toLong() + val toPointX = (pointX - segmentStartX).toLong() + val toPointY = (pointY - segmentStartY).toLong() + val segmentLengthSquared = segmentDeltaX * segmentDeltaX + segmentDeltaY * segmentDeltaY + if (segmentLengthSquared == 0L) { + return (toPointX * toPointX + toPointY * toPointY).toDouble() + } + val projection = toPointX * segmentDeltaX + toPointY * segmentDeltaY + if (projection <= 0L) { + return (toPointX * toPointX + toPointY * toPointY).toDouble() + } + if (projection >= segmentLengthSquared) { + val fromEndX = (pointX - segmentEndX).toLong() + val fromEndY = (pointY - segmentEndY).toLong() + return (fromEndX * fromEndX + fromEndY * fromEndY).toDouble() + } + val cross = toPointX * segmentDeltaY - toPointY * segmentDeltaX + return cross.toDouble() * cross.toDouble() / segmentLengthSquared.toDouble() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/art/SourceArt.kt b/module/format/src/commonMain/kotlin/org/umamo/format/art/SourceArt.kt new file mode 100644 index 0000000..9582a2c --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/art/SourceArt.kt @@ -0,0 +1,336 @@ +package org.umamo.format.art + +import org.umamo.format.FormatCodec +import org.umamo.format.ReadOnlyCodec +import kotlin.jvm.JvmInline + +/** + * Stable identity of a source-art layer, format-agnostic. + * + * `@JvmInline value class` wraps a String with zero runtime overhead (the compiler erases it + * to a bare String where it can) while making the type distinct - you can't accidentally pass a + * raw layer name where a layer id is expected. This replaces the "stringly-typed" anti-pattern + * (`Map` keyed by ambiguous strings). The meaning of the wrapped value depends on + * the source: CLIP supplies Celsys's rename-stable internal id; PSD can only offer a name/path. + * + * The `kotlin.jvm.JvmInline` import is load-bearing, not noise: `kotlin.jvm.*` is a default import + * only on JVM targets, so without it this file stops compiling the moment a non-JVM target + * (Kotlin/Native, for iPadOS) is added. The annotation is an optional expectation, so non-JVM + * targets simply ignore it. + * + * ソースレイヤーの安定 ID。value class で型安全かつゼロコスト。 + */ +@JvmInline +value class LayerId(val raw: String) + +/** + * Position and size of a layer on the source canvas, in pixels, with a top-left origin (the + * image/PSD convention). The renderer flips Y when mapping to GL's bottom-left origin. + * [AlphaAnalysis.opaqueBounds] reuses this shape raster-locally, with left/top relative to the + * raster's own origin instead of the canvas. + */ +data class LayerBounds( + val left: Int, + val top: Int, + val width: Int, + val height: Int, +) { + /** The rectangle's area in pixels; zero for an empty one. */ + val area: Long get() = if (width <= 0 || height <= 0) 0L else width.toLong() * height.toLong() + + /** + * How much of the union of this rectangle and [other] both cover: 1 for the same rectangle, 0 for + * disjoint ones - the overlap measure a layer matcher scores a candidate's placement on. + * + * @param LayerBounds other The other rectangle. + * @return Float The intersection over the union, 0 when either rectangle is empty. + */ + fun intersectionOverUnion(other: LayerBounds): Float { + if (area == 0L || other.area == 0L) { + return 0f + } + val overlapWidth = minOf(left + width, other.left + other.width) - maxOf(left, other.left) + val overlapHeight = minOf(top + height, other.top + other.height) - maxOf(top, other.top) + if (overlapWidth <= 0 || overlapHeight <= 0) { + return 0f + } + val intersection = overlapWidth.toLong() * overlapHeight.toLong() + return intersection.toFloat() / (area + other.area - intersection).toFloat() + } +} + +/** + * How a layer composites onto what's beneath it - the full PSD/Clip Studio/Krita blend-mode set. + * + * Source art (PSD, CLIP, KRA) shares essentially the same blend-mode vocabulary, so the neutral + * model carries it verbatim rather than collapsing it. A renderer that only supports a subset + * (Cubism drawables are Normal/Add/Multiply) maps the rest down at draw time - that is a render + * concern, not a reason to discard the source's intent here. Defaults to [Normal] (source-over). + * CSP-specific names noted: [GlowDodge] and [AddGlow] are CSP's clamped Color-Dodge/Add variants; + * [Luminosity] is CSP's "Brightness". + */ +enum class LayerBlend { + Normal, + Darken, + Multiply, + ColorBurn, + LinearBurn, + Subtract, + DarkerColor, + Lighten, + Screen, + ColorDodge, + GlowDodge, + Add, + AddGlow, + LighterColor, + Overlay, + SoftLight, + HardLight, + VividLight, + LinearLight, + PinLight, + HardMix, + Difference, + Exclusion, + Hue, + Saturation, + Color, + Luminosity, + Divide, +} + +/** + * What kind of source layer this is - chiefly, whether it carries ingestible raster pixels. + * + * EN: A raster-ingesting consumer cares most about [Raster] (has decodable pixels) versus everything + * else (no stored raster). The non-raster kinds are still surfaced so a consumer can report or + * skip them knowingly rather than treating them as empty raster layers: [Text] and [Vector] are + * object layers whose content is regenerated from object data on load (no persisted raster); + * [Adjustment] is a procedural correction/filter layer; [Fill] is a paper/solid-fill layer. + * JA: レイヤー種別。取り込み側はラスタの有無を知る必要がある。非ラスタ種別も識別して通知/スキップできる。 + */ +enum class SourceLayerKind { + Raster, + Text, + Vector, + Adjustment, + Fill, + Unknown, +} + +/** + * Which of the four output channels a layer writes when composited; a disabled channel passes + * through from the content below instead of being written by this layer. Defaults to all enabled, + * since most sources do not expose per-channel masking. Krita's channelflags populates this; a + * disabled alpha is the same underlying signal as inherit-alpha clipping (see SourceLayer.clipped). + * + * レイヤーが合成時に書き込むチャンネル。無効なチャンネルは下のレイヤーを通す。既定は全て有効。 + */ +data class ChannelMask( + val red: Boolean, + val green: Boolean, + val blue: Boolean, + val alpha: Boolean, +) { + companion object { + /** All channels enabled - the default when a source exposes no per-channel masking. */ + val ALL: ChannelMask = ChannelMask(red = true, green = true, blue = true, alpha = true) + } +} + +/** + * Decoded pixels for one layer: RGBA8888, straight (non-premultiplied) alpha, row-major from + * the top, sized to the layer's cropped [bounds][SourceLayer.bounds] (not the full canvas). + * + * A plain class, not a `data class`: it wraps a large [rgba] buffer for which generated structural + * equals/hashCode would be a footgun (a deep array compare on every call). Identity equality is the + * right default here. + * + * レイヤーの復号済みピクセル(RGBA8888・ストレートアルファ・上から行優先)。 + */ +class LayerRaster( + val width: Int, + val height: Int, + val rgba: ByteArray, +) + +/** + * Whether every pixel of this raster is fully transparent - a layer the artist erased to nothing, as + * opposed to one that merely fell under an import's alpha threshold. + * + * @return Boolean True when no pixel has any alpha. + */ +fun LayerRaster.isFullyTransparent(): Boolean { + var offset = 3 + while (offset < rgba.size) { + if (rgba[offset].toInt() != 0) { + return false + } + offset += 4 + } + return true +} + +/** + * One layer of ingested source art, neutral across PSD/CLIP/KRA. [id] is the re-import join key; + * [groupPath] is the slash-joined group hierarchy used as the PSD fallback key when [id] is weak. + */ +interface SourceLayer { + val id: LayerId + val name: String + val groupPath: String + + /** + * What kind of layer this is. Defaults to [SourceLayerKind.Raster] - the common case and the only + * kind the PSD/KRA readers emit - so only readers that surface non-raster layers (CLIP) override + * it. A raster-only consumer ingests [SourceLayerKind.Raster] and skips the rest. + */ + val kind: SourceLayerKind get() = SourceLayerKind.Raster + + /** + * Whether this layer is shown (the eye toggle). Defaults to true. A hidden layer is still read and + * surfaced so the consumer can decide whether to ingest or skip it; a layer can also be effectively + * hidden by an ancestor folder being hidden ([SourceGroup.visible]). + */ + val visible: Boolean get() = true + + /** + * Whether [id] is a format-minted identity that survives a rename or reorder in the art program (a + * CLIP or Krita layer uuid, a PSD lyid), as opposed to a name-and-order fallback that holds only as + * long as the artist's layer organization does. Defaults to true because every reader mints a + * stable id wherever the format offers one; a reader overrides it to false for the layers where it + * had to fall back. The re-import join trusts a stable key outright and routes the rest through + * review. + */ + val idIsStable: Boolean get() = true + + /** Draw order within the source document (top-most first), used to disambiguate fallbacks. */ + val order: Int + + /** Where this layer sits on the source canvas. */ + val bounds: LayerBounds + + /** Layer opacity, 0.0..1.0 (PSD stores 0..255). */ + val opacity: Float + + /** + * True if this is a clipping-mask layer: its output is clipped to the alpha of the first + * non-clipped ("base") layer below it in the same group (Photoshop "clip to layer below"). + */ + val clipped: Boolean + + /** Compositing mode against the layers beneath. */ + val blend: LayerBlend + + /** + * Which output channels this layer contributes; a disabled channel passes through from below. + * Defaults to all enabled, as most sources do not expose per-channel masking. + */ + val channelMask: ChannelMask get() = ChannelMask.ALL + + /** Decoded pixels, cropped to [bounds]. */ + val raster: LayerRaster +} + +/** + * A folder/group in the source-art hierarchy, identified by its slash-joined [path] (the same path + * the enclosed [SourceLayer]s carry in [SourceLayer.groupPath]). + * + * The flat model keys layers to their enclosing folders by path string rather than nesting; this + * carries the per-folder attributes that a flattened leaf list would otherwise lose - chiefly the + * folder [blend] and [opacity], which composite the whole group and are not equivalent to setting + * each child layer's blend. [passThrough] marks a folder that does not isolate (CSP "Through"): its + * children blend straight onto what is below the folder, so [blend] is moot. + * + * フォルダ属性(パスで識別)。フォルダのブレンド/不透明度は平坦化で失われるためここで保持する。 + */ +interface SourceGroup { + /** Slash-joined path identifying this folder, matching enclosed layers' [SourceLayer.groupPath]. */ + val path: String + val name: String + + /** Whether the folder is shown; a hidden folder hides its whole subtree. */ + val visible: Boolean + + /** Folder opacity, 0.0..1.0. */ + val opacity: Float + + /** True if the folder itself is a clipping layer (clips to the layer below it). */ + val clipped: Boolean + + /** How the folder composites onto what is beneath it (ignored when [passThrough] is true). */ + val blend: LayerBlend + + /** + * True for a non-isolating "pass-through" folder (Clip Studio's default folder mode): the group's + * children composite directly against the layers below the folder rather than within an isolated + * group buffer. When true, [blend] does not apply. + */ + val passThrough: Boolean +} + +/** + * A parsed source-art document: an ordered set of [SourceLayer]s, the [SourceGroup]s describing the + * folders that enclose them (keyed by path), plus the document pixel bounds. + * + * [groups] defaults to empty so readers that flatten without folder metadata (PSD, KRA) need no + * change; CLIP overrides it. + */ +interface SourceArt { + val layers: List + val groups: List get() = emptyList() + val widthPx: Int + val heightPx: Int +} + +/** + * Effective on-screen visibility of [layer]: its own eye toggle folded together with every ancestor + * folder's. A layer is shown only when it is itself visible and none of the folders enclosing it is + * hidden; the enclosing folders are found by walking [SourceLayer.groupPath] upward (a layer in + * "A/B/C" is hidden if any of "A", "A/B", or "A/B/C" is hidden). With no [groups] - the flat PSD/KRA + * case, or a document with no folders - this reduces to [SourceLayer.visible]. + * + * This is the pre-flattened answer for consumers that have no folder hierarchy of their own - the + * source-art preview compositor, which just draws a flat layer list. It is deliberately NOT what the + * eventual SourceArt to puppet-model ingest should use: that path keeps the two flags separate + * (each layer's own [SourceLayer.visible] seeds its drawable's eye toggle, each folder's + * [SourceGroup.visible] seeds the part the folder becomes) and lets the runtime's part-chain + * visibility cascade hide a still-"visible" layer whose ancestor part is hidden. Flattening here + * would discard the per-layer intent the artist may want back when they re-show a folder. Use this + * for "should I draw this now", not for "what is this layer's stored visibility". + * + * @param SourceLayer layer The layer to test; its [SourceLayer.groupPath] locates its folders. + * @return Boolean Whether the layer should be drawn by a flat (folderless) consumer. + */ +fun SourceArt.isEffectivelyVisible(layer: SourceLayer): Boolean { + if (!layer.visible) { + return false + } + if (groups.isEmpty() || layer.groupPath.isEmpty()) { + return true + } + val groupByPath = groups.associateBy { group -> group.path } + var ancestorPath = layer.groupPath + while (ancestorPath.isNotEmpty()) { + val ancestor = groupByPath[ancestorPath] + if (ancestor != null && !ancestor.visible) { + return false + } + val lastSlash = ancestorPath.lastIndexOf('/') + ancestorPath = if (lastSlash < 0) "" else ancestorPath.substring(0, lastSlash) + } + return true +} + +/** + * A [FormatCodec] whose in-memory model is the neutral [SourceArt] - one implementation per art + * format (PSD, CLIP, KRA). Folding the art readers into [FormatCodec] lets the format registry + * detect and resolve them exactly like the binary model codecs (CMO3/MOC3), rather than through a + * separate reader facade. These formats are ingestion-only, so [ReadOnlyCodec] supplies the + * refusing write - and every art FileKind has writable = false, which advertises that to callers + * before they try. + * + * ソースアートを読む FormatCodec。形式ごとに実装。読み取り専用なので write は常に拒否する。 + */ +interface ArtReader : ReadOnlyCodec \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/atlas/AtlasPack.kt b/module/format/src/commonMain/kotlin/org/umamo/format/atlas/AtlasPack.kt new file mode 100644 index 0000000..962b4c0 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/atlas/AtlasPack.kt @@ -0,0 +1,601 @@ +package org.umamo.format.atlas + +import org.umamo.format.art.DEFAULT_ALPHA_THRESHOLD +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.raster.RasterImage +import kotlin.math.ceil +import kotlin.math.floor + +/* + * The atlas packer: source-layer rasters in, packed pages plus a placement report out. + * + * Because the 2D source art hands us each piece's opaque silhouette before packing, the atlas can + * be generated rather than authored by hand and reconciled. The packing REPORT is deliberately + * not a placement transform: it records integer page rectangles, the trim each tile came from, and + * the quarter turn applied, which is what a packer knows. Lowering that onto a placement transform + * belongs with whoever owns the placement model. + * + * Its own package rather than sitting beside analyzeAlpha in `art`, because the packer reads layers + * and writes flat images: `art` deliberately does not depend on `raster` (see RasterImage's + * analyzeAlpha extension), and this is the node that legitimately spans both. + */ + +/** + * Extra area a tile's placement must keep clear, in raster-local pixels. + * + * The pixels alone do not bound what samples a tile: an art mesh rings OUTSIDE the opaque region + * (and routinely outside the raster itself), so a pack spaced by opaque bounds alone puts one + * tile's mesh footprint over its neighbor's art. A reserve carries that reach into the pack: the + * tile's reservation becomes the union of its opaque trim and this rect, so anything inside it + * lands on the tile's own transparent margin rather than on a neighbor. + * + * Coordinates are raster-local like a trim's, edges exclusive on the right and bottom, and MAY be + * negative or exceed the raster - a mesh's reach is not confined to its art. + * + * @property Int left The reserved rect's left edge. + * @property Int top The reserved rect's top edge. + * @property Int right The reserved rect's right edge, exclusive. + * @property Int bottom The reserved rect's bottom edge, exclusive. + */ +public data class AtlasPackReserve( + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, +) { + init { + require(right >= left && bottom >= top) { "reserve must not be inverted: $left..$right x $top..$bottom" } + } +} + +/** + * A place on a page decided BEFORE the pack: the tile stays exactly here, and the free tiles pack + * around it. This is what a pinned placement is to a repack. + * + * Expressed as the tile's full tile-to-page affine rather than a rect, because a hand placement may + * be rotated, scaled, or off the pixel grid - none of which an [AtlasPackPlacement] can hold - and + * the tile is painted through that same affine, by the same path a derivation paints it, so the + * packed page and a page derived from the kept placement cannot differ. + * + * @property Int pageIndex The page the tile stays on. + * @property FloatArray tileToPage The affine (m00, m01, m02, m10, m11, m12) mapping tile pixels to + * page pixels, both frames y-down - [AtlasTilePlacement]'s convention. + */ +public class AtlasPackFixed( + public val pageIndex: Int, + public val tileToPage: FloatArray, +) { + init { + require(pageIndex >= 0) { "fixed page index must not be negative: $pageIndex" } + require(tileToPage.size == 6) { "a fixed placement needs a 2x3 affine, got ${tileToPage.size} components" } + } +} + +/** + * One tile to pack: a stable key plus the straight-alpha pixels to place. + * + * Pixels are taken by reference and never mutated, matching how the flat-raster adapter hands a + * buffer through; the caller must not mutate [rgba] while a pack is running. + * + * A plain class, not a data class: it wraps a pixel buffer whose generated structural equality would + * deep-compare on every call, the same reason [LayerRaster] and [RasterImage] are plain classes. + * + * @property String key The tile's stable identity, unique within one pack. + * @property Int width The raster width in pixels. + * @property Int height The raster height in pixels. + * @property ByteArray rgba RGBA8888 pixels, straight alpha, row-major from the top row. + * @property AtlasPackReserve? reserve Extra area to keep clear around this tile (a mesh's reach), + * unioned with the opaque trim; null reserves the trim alone. + * @property AtlasPackFixed? fixed Where the tile already sits and stays, or null to let the + * packer place it. + */ +public class AtlasPackItem( + public val key: String, + public val width: Int, + public val height: Int, + public val rgba: ByteArray, + public val reserve: AtlasPackReserve? = null, + public val fixed: AtlasPackFixed? = null, +) { + init { + require(width >= 0 && height >= 0) { "tile '$key' has negative dimensions: $width x $height" } + require(rgba.size.toLong() == width.toLong() * height.toLong() * 4L) { + "tile '$key' rgba size ${rgba.size} does not match $width x $height x 4" + } + } +} + +/** + * How to pack. + * + * @property Int maxPageSize The square page side pages are packed against, in pixels. + * @property Int gutter Transparent spacing reserved around every tile and at the page border. + * @property Int extrude How many pixels of gutter around each tile carry its edge color, at zero alpha. + * @property Boolean allowRotation Whether a tile may be quarter-turned to pack tighter. + * @property Boolean powerOfTwoPages Whether final page dimensions round up to a power of two. + * @property Boolean squarePages Whether final pages are square, as every corpus atlas is. + * @property Boolean shrinkPages Whether pages size themselves to the document instead of staying at [maxPageSize]. + * @property Int alphaThreshold Minimum alpha byte (1..255) for a pixel to count as opaque when trimming. + * @property Int minimumOpaquePixels Tiles with fewer opaque pixels than this are reported rather than packed. + */ +public data class AtlasPackOptions( + val maxPageSize: Int = 4096, + val gutter: Int = 2, + val extrude: Int = 2, + val allowRotation: Boolean = false, + val powerOfTwoPages: Boolean = true, + val squarePages: Boolean = true, + val shrinkPages: Boolean = true, + val alphaThreshold: Int = DEFAULT_ALPHA_THRESHOLD, + val minimumOpaquePixels: Int = 1, +) + +/** + * Where one tile landed, in whole page pixels. + * + * [pageX] / [pageY] locate the tile itself, not its gutter footprint. The trim fields say which part + * of the source raster was packed: a tile is trimmed to its opaque bounds, so the source pixel + * (trimLeft + tileX, trimTop + tileY) is what sits at the placed position. A [quarterTurns] of 1 + * means the tile was rotated one counter-clockwise quarter turn in the page's y-down frame, which + * swaps its on-page width and height. + * + * @property String key The packed tile's key. + * @property Int pageIndex The page it landed on. + * @property Int pageX The tile's left edge on the page. + * @property Int pageY The tile's top edge on the page. + * @property Int trimLeft The opaque bounds' left edge within the source raster. + * @property Int trimTop The opaque bounds' top edge within the source raster. + * @property Int trimWidth The opaque bounds' width, before any rotation. + * @property Int trimHeight The opaque bounds' height, before any rotation. + * @property Int quarterTurns 0 for upright, 1 for one counter-clockwise quarter turn. + */ +public data class AtlasPackPlacement( + val key: String, + val pageIndex: Int, + val pageX: Int, + val pageY: Int, + val trimLeft: Int, + val trimTop: Int, + val trimWidth: Int, + val trimHeight: Int, + val quarterTurns: Int, +) { + /** The tile's width on the page, after any quarter turn. */ + public val pageWidth: Int + get() = if (quarterTurns == 0) trimWidth else trimHeight + + /** The tile's height on the page, after any quarter turn. */ + public val pageHeight: Int + get() = if (quarterTurns == 0) trimHeight else trimWidth +} + +/** Why a tile was not packed. */ +public enum class AtlasPackSkipReason { + /** Nothing in the raster met the alpha threshold - an empty layer, or a transparent placeholder. */ + NoOpaquePixels, + + /** The tile has opaque pixels but fewer than the configured minimum. */ + BelowMinimumCoverage, + + /** The trimmed tile plus its gutter does not fit a page even on its own. */ + LargerThanPage, + + /** + * The tile is fixed at a spot that does not fit inside the largest page the pack may use - its + * opaque art runs past the right or bottom edge. Reserve and gutter alone spilling past the edge + * do not refuse: they are clamped, the way a free pack's page-border gutter is. + */ + FixedOutsidePage, +} + +/** + * One tile that was not packed, and why. + * + * @property String key The tile's key. + * @property AtlasPackSkipReason reason Why it was left out. + */ +public data class AtlasPackSkip( + val key: String, + val reason: AtlasPackSkipReason, +) + +/** + * One fixed tile the pack kept where it was: the page it stayed on, the trim it painted there, and + * the affine it painted through. + * + * A plain class: [tileToPage] is an array. + * + * @property String key The tile's key. + * @property Int pageIndex The page it stayed on. + * @property Int trimLeft The opaque bounds' left edge within the source raster. + * @property Int trimTop The opaque bounds' top edge within the source raster. + * @property Int trimWidth The opaque bounds' width. + * @property Int trimHeight The opaque bounds' height. + * @property FloatArray tileToPage The affine it was painted through, as the caller gave it. + */ +public class AtlasPackFixedPlacement( + public val key: String, + public val pageIndex: Int, + public val trimLeft: Int, + public val trimTop: Int, + public val trimWidth: Int, + public val trimHeight: Int, + public val tileToPage: FloatArray, +) + +/** + * The packing outcome: the composed pages plus a full account of every tile that went in. + * + * [placements], [fixed], and [skipped] partition the input keys exactly - every tile handed to + * [packAtlas] appears in one of them. That is the contract that keeps a plausible-looking page from + * quietly having lost three layers, which is this stage's characteristic failure. + * + * A plain class, not a data class: [pages] holds pixel buffers. + * + * @property List pages The composed atlas pages, in page-index order. + * @property List placements Where each packed tile landed, in the caller's input order. + * @property List skipped The tiles left out, in the caller's input order. + * @property List fixed The tiles kept where they were, in the caller's input order. + */ +public class AtlasPackResult( + public val pages: List, + public val placements: List, + public val skipped: List, + public val fixed: List = emptyList(), +) { + /** + * The fraction of a page's area covered by tile pixels, ignoring gutters and extrusion. A packed + * tile covers its trim; a fixed tile covers its trim through its affine's area scale. + * + * @param Int pageIndex The page to measure. + * @return Float The covered fraction, in 0.0..1.0. + */ + public fun pageOccupancy(pageIndex: Int): Float { + val page = pages[pageIndex] + var covered = 0.0 + for (placement in placements) { + if (placement.pageIndex == pageIndex) { + covered += placement.trimWidth.toDouble() * placement.trimHeight.toDouble() + } + } + for (kept in fixed) { + if (kept.pageIndex == pageIndex) { + val affine = kept.tileToPage + val areaScale = kotlin.math.abs(affine[0] * affine[4] - affine[1] * affine[3]) + covered += kept.trimWidth.toDouble() * kept.trimHeight.toDouble() * areaScale + } + } + return (covered / (page.width.toDouble() * page.height.toDouble())).toFloat() + } +} + +/** + * A fixed tile's page footprint before the pack decides a page side: its trim widened by its reserve, + * through its affine, rounded out to pixels and grown by the gutter on every side. + * + * @property Int itemIndex The fixed item. + * @property Int pageIndex The page it stays on. + * @property Int left The footprint's left edge, gutter included, clamped to the page. + * @property Int top The footprint's top edge, gutter included, clamped to the page. + * @property Int right The footprint's right edge, exclusive, gutter included, clamped to the page. + * @property Int bottom The footprint's bottom edge, exclusive, gutter included, clamped to the page. + * @property Int artRight The opaque art's right edge, exclusive - what decides whether the tile fits. + * @property Int artBottom The opaque art's bottom edge, exclusive. + */ +private class FixedFootprint( + val itemIndex: Int, + val pageIndex: Int, + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, + val artRight: Int, + val artBottom: Int, +) { + /** The footprint as the rect packer's seed. */ + fun toSeed(): RectPackSeed = RectPackSeed(pageIndex, left, top, right - left, bottom - top) +} + +/** + * Packs tiles into atlas pages and composes the page pixels. + * + * Each tile is trimmed to its opaque bounds (lossless at the default threshold - no antialiased edge + * pixel is cut), reserved with a gutter on every side, placed by the MaxRects packer, blitted, and + * its edge color bled into its gutter at zero alpha. Pages are packed against [AtlasPackOptions.maxPageSize] and then cropped + * to what was used, so a document that needs a 512 page gets one rather than a mostly-empty 4096. + * + * The result is DETERMINISTIC: tiles are ordered by descending max side, then descending area, then + * key, so the caller's input order cannot change the packing. Repacking an unchanged set therefore + * reproduces it exactly, which is what makes a repack a safe operation rather than a churn source. + * + * A tile with an [AtlasPackItem.fixed] placement is not packed at all: its footprint (trim, reserve, + * and gutter, through its affine) seeds its page before any free tile is placed, so the free tiles + * pack around it, and it is painted through its own affine after them. Its page index is kept as + * given, so every page up to it exists even if nothing else lands there (an empty page crops to its + * used extent like any other). A fixed tile whose art does not fit inside [AtlasPackOptions.maxPageSize] + * is reported as [AtlasPackSkipReason.FixedOutsidePage] rather than moved - the caller decided to + * keep it, so the packer never second-guesses where; reserve and gutter that spill past the edge are + * clamped to it, not refused. + * + * @param List items The tiles to pack; keys must be unique. + * @param AtlasPackOptions options The packing policy. + * @return AtlasPackResult The composed pages, the placements, the tiles kept fixed, and the tiles left out. + */ +public fun packAtlas( + items: List, + options: AtlasPackOptions = AtlasPackOptions(), +): AtlasPackResult { + require(options.maxPageSize > 0) { "maxPageSize must be positive: ${options.maxPageSize}" } + require(options.gutter >= 0) { "gutter must be non-negative: ${options.gutter}" } + require(options.extrude in 0..options.gutter) { + "extrude must be in 0..gutter (${options.gutter}) so no tile's extrusion reaches another: ${options.extrude}" + } + require(options.alphaThreshold in 1..255) { "alphaThreshold must be in 1..255: ${options.alphaThreshold}" } + require(options.minimumOpaquePixels >= 0) { + "minimumOpaquePixels must be non-negative: ${options.minimumOpaquePixels}" + } + require(items.distinctBy { item -> item.key }.size == items.size) { + "atlas pack item keys must be unique; duplicates make the packing order ambiguous" + } + + // Trim first: a tile's footprint is its opaque bounds - widened to any caller reserve, since a + // mesh's reach must land on the tile's own margin - plus the gutter, and a tile with nothing + // opaque never reaches the packer at all. A fixed tile's footprint goes through its affine + // instead of into a request. + val trims = arrayOfNulls(items.size) + val reserves = arrayOfNulls(items.size) + val skipped = ArrayList() + val requests = ArrayList(items.size) + val fixedFootprints = ArrayList() + for ((itemIndex, item) in items.withIndex()) { + val analysis = analyzeAlpha(item.width, item.height, item.rgba, options.alphaThreshold) + if (analysis == null) { + skipped.add(AtlasPackSkip(item.key, AtlasPackSkipReason.NoOpaquePixels)) + continue + } + if (analysis.opaquePixelCount < options.minimumOpaquePixels) { + skipped.add(AtlasPackSkip(item.key, AtlasPackSkipReason.BelowMinimumCoverage)) + continue + } + val trim = analysis.opaqueBounds + val reserveLeft = minOf(trim.left, item.reserve?.left ?: trim.left) + val reserveTop = minOf(trim.top, item.reserve?.top ?: trim.top) + val reserveRight = maxOf(trim.left + trim.width, item.reserve?.right ?: (trim.left + trim.width)) + val reserveBottom = maxOf(trim.top + trim.height, item.reserve?.bottom ?: (trim.top + trim.height)) + trims[itemIndex] = trim + reserves[itemIndex] = LayerBounds(reserveLeft, reserveTop, reserveRight - reserveLeft, reserveBottom - reserveTop) + val fixed = item.fixed + if (fixed != null) { + val bounds = affineBounds(fixed.tileToPage, reserveLeft.toFloat(), reserveTop.toFloat(), reserveRight.toFloat(), reserveBottom.toFloat()) + val artBounds = + affineBounds(fixed.tileToPage, trim.left.toFloat(), trim.top.toFloat(), (trim.left + trim.width).toFloat(), (trim.top + trim.height).toFloat()) + // An overhang past the top or left is cropped by the composition, so the footprint starts at + // the page edge there. Past the right or bottom, only the ART decides whether the tile fits: + // a reserve or gutter spilling over the edge is clamped to it, exactly as a free pack's own + // page-border gutter is - a tile the free pack placed flush against the edge would otherwise + // be refused as fixed, since its mesh reach re-measured from page coordinates can round a + // pixel wider than the reach it was packed with. + fixedFootprints.add( + FixedFootprint( + itemIndex = itemIndex, + pageIndex = fixed.pageIndex, + left = floor(bounds[0] - options.gutter).toInt().coerceAtLeast(0), + top = floor(bounds[1] - options.gutter).toInt().coerceAtLeast(0), + right = ceil(bounds[2] + options.gutter).toInt().coerceIn(0, options.maxPageSize), + bottom = ceil(bounds[3] + options.gutter).toInt().coerceIn(0, options.maxPageSize), + artRight = ceil(artBounds[2]).toInt().coerceAtLeast(0), + artBottom = ceil(artBounds[3]).toInt().coerceAtLeast(0), + ), + ) + continue + } + requests.add( + RectPackRequest( + itemIndex = itemIndex, + width = reserveRight - reserveLeft + 2 * options.gutter, + height = reserveBottom - reserveTop + 2 * options.gutter, + ), + ) + } + + requests.sortWith( + compareByDescending { request -> maxOf(request.width, request.height) } + .thenByDescending { request -> request.width.toLong() * request.height.toLong() } + .thenBy { request -> items[request.itemIndex].key }, + ) + + // A fixed tile whose ART runs past the largest page can never be kept; every other one seeds each + // trial pack, so the side the pack settles on always holds them all. + val keptFootprints = ArrayList(fixedFootprints.size) + for (footprint in fixedFootprints) { + if (footprint.artRight > options.maxPageSize || footprint.artBottom > options.maxPageSize) { + skipped.add(AtlasPackSkip(items[footprint.itemIndex].key, AtlasPackSkipReason.FixedOutsidePage)) + } else { + keptFootprints.add(footprint) + } + } + val seeds = keptFootprints.map { footprint -> footprint.toSeed() } + val packingSide = choosePackingSide(requests, seeds, options) + val layout = packRects(requests, packingSide, options.allowRotation, seeds) + for (itemIndex in layout.oversizedItemIndices) { + skipped.add(AtlasPackSkip(items[itemIndex].key, AtlasPackSkipReason.LargerThanPage)) + } + + val pageWidths = IntArray(layout.usedWidths.size) + val pageHeights = IntArray(layout.usedHeights.size) + for (pageIndex in layout.usedWidths.indices) { + val sizes = finalPageSize(layout.usedWidths[pageIndex], layout.usedHeights[pageIndex], packingSide, options) + pageWidths[pageIndex] = sizes.first + pageHeights[pageIndex] = sizes.second + } + + val placementByItemIndex = arrayOfNulls(items.size) + for (slot in layout.slots) { + val item = items[slot.itemIndex] + val trim = checkNotNull(trims[slot.itemIndex]) { "packed tile '${item.key}' has no trim" } + val reserve = checkNotNull(reserves[slot.itemIndex]) { "packed tile '${item.key}' has no reserve" } + // The placement records the TRIM's page position, not the reservation's: the reservation only + // spaces neighbors further apart, so everything downstream of the placement (the lowering, the + // composition, the derivation) never sees it. A turned slot turns the reservation with the + // tile - the same counter-clockwise quarter turn the blit applies, reserve-local (u, v) landing + // at (v, reserveWidth - u) - so the trim's offset inside it turns too: what sat to the trim's + // LEFT in tile space sits BELOW it on the page. + val trimOffsetX = trim.left - reserve.left + val trimOffsetY = trim.top - reserve.top + val placedOffsetX = if (slot.rotated) trimOffsetY else trimOffsetX + val placedOffsetY = if (slot.rotated) reserve.width - trimOffsetX - trim.width else trimOffsetY + placementByItemIndex[slot.itemIndex] = + AtlasPackPlacement( + key = item.key, + pageIndex = slot.pageIndex, + pageX = slot.x + options.gutter + placedOffsetX, + pageY = slot.y + options.gutter + placedOffsetY, + trimLeft = trim.left, + trimTop = trim.top, + trimWidth = trim.width, + trimHeight = trim.height, + quarterTurns = if (slot.rotated) 1 else 0, + ) + } + val placements = placementByItemIndex.filterNotNull() + + // The free tiles compose through the packer's blit; the fixed tiles then paint over the same + // buffers in input order through the affine painter, exactly as a derivation paints them. + val pages = composeAtlasPages(pageWidths, pageHeights, items, placements, options.extrude) + val fixedPlacements = ArrayList(keptFootprints.size) + for (footprint in keptFootprints) { + val item = items[footprint.itemIndex] + val fixed = checkNotNull(item.fixed) { "fixed tile '${item.key}' lost its placement" } + val trim = checkNotNull(trims[footprint.itemIndex]) { "fixed tile '${item.key}' has no trim" } + val page = pages[footprint.pageIndex] + paintTilePlacement(page.rgba, page.width, page.height, item, trim, fixed.tileToPage, options.extrude) + fixedPlacements.add(AtlasPackFixedPlacement(item.key, footprint.pageIndex, trim.left, trim.top, trim.width, trim.height, fixed.tileToPage)) + } + + val inputOrderByKey = items.withIndex().associate { (itemIndex, item) -> item.key to itemIndex } + return AtlasPackResult( + pages = pages, + placements = placements, + skipped = skipped.sortedBy { skip -> inputOrderByKey.getValue(skip.key) }, + fixed = fixedPlacements, + ) +} + +/** + * Builds pack items from this document's layers, one per layer, keyed by its stable layer id. + * + * Layer kind, visibility, and sliver policy are deliberately the caller's: alpha-shape analysis never + * drops a real art layer and leaves the consumer to decide what to ingest, and the same rule applies + * here. Pass [include] to apply a policy; the default packs every layer. + * + * A duplicate layer id (possible from the PSD name-and-order fallback, where no lyid is written) is + * disambiguated with the layer's draw order rather than rejected, since the collision is an artifact + * of a weak source key and not a caller mistake. + * + * @param Function include Which layers to pack; defaults to all of them. + * @return List One pack item per included layer, in document draw order. + */ +public fun SourceArt.atlasPackItems(include: (SourceLayer) -> Boolean = { true }): List { + val usedKeys = HashSet() + return layers.filter(include).map { layer -> + var key = layer.id.raw + if (!usedKeys.add(key)) { + key = "${layer.id.raw}#${layer.order}" + usedKeys.add(key) + } + AtlasPackItem(key, layer.raster.width, layer.raster.height, layer.raster.rgba) + } +} + +/** + * Chooses the page side to pack against: the smallest one that still needs no extra page. + * + * Packing straight against [AtlasPackOptions.maxPageSize] and cropping afterwards is not enough, + * because best-short-side-fit spreads a small document along the top of a huge page - the crop then + * keeps a wide, shallow extent that squares up almost empty. Packing against a page the document + * roughly fills instead makes it stack, and the page count is the thing worth protecting: a smaller + * page that costs an extra texture bind is a worse trade than a slightly emptier one. + * + * Only the rectangle geometry runs here - no pixels are touched - so the handful of trial packs is + * cheap next to a single page composition. + * + * The seeds bound the side from below: a trial smaller than a seed's far edge could not keep it, so + * the first trial is already large enough for every seed, and each trial seeds the same footprints + * the final pack will. + * + * @param List requests The footprints to be packed. + * @param List seeds The fixed footprints every trial must keep. + * @param AtlasPackOptions options The packing policy. + * @return Int The page side to pack against. + */ +private fun choosePackingSide( + requests: List, + seeds: List, + options: AtlasPackOptions, +): Int { + if (!options.shrinkPages || (requests.isEmpty() && seeds.isEmpty())) { + return options.maxPageSize + } + val baseline = packRects(requests, options.maxPageSize, options.allowRotation, seeds) + val fitting = requests.filter { request -> request.width <= options.maxPageSize && request.height <= options.maxPageSize } + if (fitting.isEmpty() && seeds.isEmpty()) { + return options.maxPageSize + } + val largestRequest = fitting.maxOfOrNull { request -> maxOf(request.width, request.height) } ?: 1 + val farthestSeed = seeds.maxOfOrNull { seed -> maxOf(seed.x + seed.width, seed.y + seed.height) } ?: 1 + var side = roundUpToPowerOfTwo(maxOf(largestRequest, farthestSeed, 1)) + while (side < options.maxPageSize) { + val trial = packRects(requests, side, options.allowRotation, seeds) + if (trial.usedWidths.size <= baseline.usedWidths.size && + trial.oversizedItemIndices.size == baseline.oversizedItemIndices.size + ) { + return side + } + side = side shl 1 + } + return options.maxPageSize +} + +/** + * Resolves one page's final dimensions from the extent the packer actually used. + * + * @param Int usedWidth The rightmost footprint edge on the page, gutter included. + * @param Int usedHeight The lowest footprint edge on the page, gutter included. + * @param Int packingSide The page side the pack ran against. + * @param AtlasPackOptions options The packing policy. + * @return Pair The page width and height in pixels. + */ +private fun finalPageSize(usedWidth: Int, usedHeight: Int, packingSide: Int, options: AtlasPackOptions): Pair { + if (!options.shrinkPages) { + return packingSide to packingSide + } + var width = usedWidth + var height = usedHeight + if (options.squarePages) { + width = maxOf(width, height) + height = width + } + if (options.powerOfTwoPages) { + width = roundUpToPowerOfTwo(width) + height = roundUpToPowerOfTwo(height) + } + return minOf(width, packingSide) to minOf(height, packingSide) +} + +/** + * Rounds a positive extent up to the next power of two. + * + * @param Int extent The extent in pixels; at least 1. + * @return Int The smallest power of two that is at least [extent]. + */ +private fun roundUpToPowerOfTwo(extent: Int): Int { + var size = 1 + while (size < extent) { + size = size shl 1 + } + return size +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/atlas/AtlasPageCompose.kt b/module/format/src/commonMain/kotlin/org/umamo/format/atlas/AtlasPageCompose.kt new file mode 100644 index 0000000..08711fb --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/atlas/AtlasPageCompose.kt @@ -0,0 +1,811 @@ +package org.umamo.format.atlas + +import org.umamo.format.art.LayerBounds +import org.umamo.format.raster.RasterImage +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.roundToInt + +/* + * Pixel composition for the atlas packer: writing one trimmed tile into a page buffer, optionally + * quarter-turned, and bleeding its edge color outward into the surrounding gutter - plus the general + * affine blit a hand-authored placement needs, since a rigger may rotate or scale a tile on the page + * where the packer never would. + * + * The gutter band carries the edge's COLOR at zero alpha, never its coverage. A mesh reaches past the + * art it samples, so anything opaque painted around a tile shows as a fringe wherever its art meets the + * edge of its raster; the band's only job is to give a straight-alpha bilinear filter the edge's color to + * blend toward, so a transparent black neighbor does not darken the edge. Umamo's renderer filters + * premultiplied and never sees the band's color, but a page also leaves in an export, and Cubism's own + * pages carry the same band. Beyond the art the page is transparent, exactly as the source layer is. + * + * Every writer here goes through ONE rule, writeSample: a sample never erases content. A destination + * pixel nobody has painted (alpha 0) takes the sample verbatim, transparent or not - which is what keeps + * the packer's disjoint pages byte-identical, since every pixel it touches is untouched. Over painted + * content a transparent sample is skipped, an opaque one replaces (later placements win), a + * translucent one composites source-over, and a bleed band - synthetic pixels - never beats real + * ones. Hand-authored placements overlap; without the rule a later tile's transparent margin cut a + * box out of the tile beneath it. + * + * Kept apart from the packing geometry so the blit can be read and tested as pixels, which is where + * a packer's silent bugs live - an orientation flipped, an extrusion off by one, a stride computed + * from the wrong width. + */ + +/** + * Writes one straight-alpha sample into a page pixel under the content-preserving rule (see the file + * comment). + * + * @param ByteArray page The destination page, RGBA8888 row-major from the top. + * @param Int offset The destination pixel's byte offset. + * @param Int red The sample's red, 0..255. + * @param Int green The sample's green, 0..255. + * @param Int blue The sample's blue, 0..255. + * @param Int alpha The sample's alpha, 0..255. + * @param Boolean synthetic True for a bleed-band sample, which only ever fills untouched page. + */ +private fun writeSample( + page: ByteArray, + offset: Int, + red: Int, + green: Int, + blue: Int, + alpha: Int, + synthetic: Boolean, +) { + val destinationAlpha = page[offset + 3].toInt() and 0xFF + if (destinationAlpha == 0) { + // A bleed band holds no alpha, so an earlier tile's band is told apart from untouched page by its + // color: another band never recolors it, and the gutter keeps the color of the edge it borders. + if (synthetic && (page[offset].toInt() != 0 || page[offset + 1].toInt() != 0 || page[offset + 2].toInt() != 0)) { + return + } + page[offset] = red.toByte() + page[offset + 1] = green.toByte() + page[offset + 2] = blue.toByte() + page[offset + 3] = alpha.toByte() + return + } + if (synthetic || alpha == 0) { + return + } + if (alpha == 255) { + page[offset] = red.toByte() + page[offset + 1] = green.toByte() + page[offset + 2] = blue.toByte() + page[offset + 3] = alpha.toByte() + return + } + // Straight-alpha source-over: the sample sits over the earlier content. + val sourceCoverage = alpha / 255f + val destinationCoverage = destinationAlpha / 255f * (1f - sourceCoverage) + val outCoverage = sourceCoverage + destinationCoverage + page[offset] = compositeChannel(red, page[offset], sourceCoverage, destinationCoverage, outCoverage) + page[offset + 1] = compositeChannel(green, page[offset + 1], sourceCoverage, destinationCoverage, outCoverage) + page[offset + 2] = compositeChannel(blue, page[offset + 2], sourceCoverage, destinationCoverage, outCoverage) + page[offset + 3] = (outCoverage * 255f).roundToInt().coerceIn(0, 255).toByte() +} + +/** + * One color channel of a straight-alpha source-over composite. + * + * @param Int source The sample's channel, 0..255. + * @param Byte destination The page's channel byte. + * @param Float sourceCoverage The sample's alpha as coverage. + * @param Float destinationCoverage The page's alpha as coverage, already scaled by the sample's transparency. + * @param Float outCoverage The composite's coverage (the two summed). + * @return Byte The composited channel. + */ +private fun compositeChannel( + source: Int, + destination: Byte, + sourceCoverage: Float, + destinationCoverage: Float, + outCoverage: Float, +): Byte { + val destinationValue = destination.toInt() and 0xFF + val composite = (source * sourceCoverage + destinationValue * destinationCoverage) / outCoverage + return composite.roundToInt().coerceIn(0, 255).toByte() +} + +/** + * Writes one source raster pixel into a page pixel under the content-preserving rule. + * + * @param ByteArray page The destination page. + * @param Int destinationOffset The destination pixel's byte offset. + * @param ByteArray source The source raster, RGBA8888. + * @param Int sourceOffset The source pixel's byte offset. + */ +private fun writeSourcePixel( + page: ByteArray, + destinationOffset: Int, + source: ByteArray, + sourceOffset: Int, +) { + writeSample( + page, + destinationOffset, + source[sourceOffset].toInt() and 0xFF, + source[sourceOffset + 1].toInt() and 0xFF, + source[sourceOffset + 2].toInt() and 0xFF, + source[sourceOffset + 3].toInt() and 0xFF, + synthetic = false, + ) +} + +/** + * Bleeds one source raster pixel's color into a page pixel at zero alpha: a gutter pixel that gives + * filtering the edge's color without adding any coverage, filled only where nothing is painted. + * + * @param ByteArray page The destination page. + * @param Int destinationOffset The destination pixel's byte offset. + * @param ByteArray source The source raster, RGBA8888. + * @param Int sourceOffset The source pixel's byte offset. + */ +private fun bleedSourcePixel( + page: ByteArray, + destinationOffset: Int, + source: ByteArray, + sourceOffset: Int, +) { + writeSample( + page, + destinationOffset, + source[sourceOffset].toInt() and 0xFF, + source[sourceOffset + 1].toInt() and 0xFF, + source[sourceOffset + 2].toInt() and 0xFF, + 0, + synthetic = true, + ) +} + +/** + * The source raster byte offset of the pixel that lands at a placed tile's (column, row), under the + * tile's quarter turn - the reader half of [blitTile], shared with the extrusion so both read the + * same texel. + * + * @param Int sourceWidth The source raster's row stride in pixels. + * @param LayerBounds trim The trimmed sub-rectangle, raster-local. + * @param Int column The placed tile's column (post-rotation frame). + * @param Int row The placed tile's row (post-rotation frame). + * @param Int quarterTurns 0 for upright, 1 for one counter-clockwise quarter turn. + * @return Int The source pixel's byte offset. + */ +private fun sourceOffsetOfPlaced( + sourceWidth: Int, + trim: LayerBounds, + column: Int, + row: Int, + quarterTurns: Int, +): Int = + if (quarterTurns == 0) { + ((trim.top + row) * sourceWidth + trim.left + column) * 4 + } else { + // A quarter turn sends source (tileX, tileY) to placed (tileY, trimWidth - 1 - tileX). + ((trim.top + column) * sourceWidth + trim.left + trim.width - 1 - row) * 4 + } + +/** + * Copies one trimmed tile into a page buffer under the content-preserving rule. + * + * A quarter turn is COUNTER-CLOCKWISE in the page's y-down frame, matching how a placement records + * rotation: source pixel (tileX, tileY) lands at (destinationX + tileY, destinationY + trimWidth - 1 + * - tileX), so the destination footprint is trimHeight wide by trimWidth tall. + * + * @param ByteArray page The destination page, RGBA8888 row-major from the top. + * @param Int pageWidth The page width in pixels. + * @param ByteArray sourceRgba The source raster, RGBA8888 row-major from the top. + * @param Int sourceWidth The source raster's width in pixels (its row stride). + * @param LayerBounds trim The opaque sub-rectangle of the source to copy, raster-local. + * @param Int destinationX The tile's left edge on the page. + * @param Int destinationY The tile's top edge on the page. + * @param Int quarterTurns 0 for upright, 1 for one counter-clockwise quarter turn. + */ +internal fun blitTile( + page: ByteArray, + pageWidth: Int, + sourceRgba: ByteArray, + sourceWidth: Int, + trim: LayerBounds, + destinationX: Int, + destinationY: Int, + quarterTurns: Int, +) { + val placedWidth = if (quarterTurns == 0) trim.width else trim.height + val placedHeight = if (quarterTurns == 0) trim.height else trim.width + for (row in 0 until placedHeight) { + val destinationRowOffset = ((destinationY + row) * pageWidth + destinationX) * 4 + for (column in 0 until placedWidth) { + writeSourcePixel( + page, + destinationRowOffset + column * 4, + sourceRgba, + sourceOffsetOfPlaced(sourceWidth, trim, column, row, quarterTurns), + ) + } + } +} + +/** + * Bleeds a placed tile's edge colors outward into the surrounding gutter, at zero alpha. + * + * Bilinear sampling at a tile's border reads half a texel past it, and the renderer filters straight + * alpha, so the color it finds there tints the edge: transparent black would darken it. The band gives + * it the edge's own color with no coverage, so the page past the art stays as transparent as the layer + * is there - a mesh reaching past its art must not find an opaque copy of the edge. The edge is read + * from the SOURCE raster, not from the page: under the content-preserving rule a tile's transparent + * edge may not have landed on the page at all, and the band must carry the tile's own texel color, + * never whatever another tile left there. The caller guarantees room by reserving a gutter of at least + * [extrude] on every side, so no clamping against the page edge is needed here - and a silent clamp + * would hide exactly the arithmetic mistake this is most likely to make. Band pixels are synthetic: + * they fill unpainted pixels only. + * + * @param ByteArray page The destination page, RGBA8888 row-major from the top. + * @param Int pageWidth The page width in pixels. + * @param ByteArray sourceRgba The source raster, RGBA8888 row-major from the top. + * @param Int sourceWidth The source raster's row stride in pixels. + * @param LayerBounds trim The trimmed sub-rectangle, raster-local. + * @param Int tileX The placed tile's left edge on the page. + * @param Int tileY The placed tile's top edge on the page. + * @param Int quarterTurns 0 for upright, 1 for one counter-clockwise quarter turn. + * @param Int extrude How many pixels of edge color to replicate on every side. + */ +internal fun extrudeTileEdges( + page: ByteArray, + pageWidth: Int, + sourceRgba: ByteArray, + sourceWidth: Int, + trim: LayerBounds, + tileX: Int, + tileY: Int, + quarterTurns: Int, + extrude: Int, +) { + val tileWidth = if (quarterTurns == 0) trim.width else trim.height + val tileHeight = if (quarterTurns == 0) trim.height else trim.width + if (extrude <= 0 || tileWidth <= 0 || tileHeight <= 0) { + return + } + for (rowOffset in -extrude until tileHeight + extrude) { + val clampedRow = rowOffset.coerceIn(0, tileHeight - 1) + val insideVertically = rowOffset == clampedRow + for (columnOffset in -extrude until tileWidth + extrude) { + val clampedColumn = columnOffset.coerceIn(0, tileWidth - 1) + if (insideVertically && columnOffset == clampedColumn) { + continue + } + bleedSourcePixel( + page, + ((tileY + rowOffset) * pageWidth + tileX + columnOffset) * 4, + sourceRgba, + sourceOffsetOfPlaced(sourceWidth, trim, clampedColumn, clampedRow, quarterTurns), + ) + } + } +} + +/** + * Composes atlas pages from already-decided placements. + * + * This is the packer's own composition loop opened to callers that hold placements rather than a + * pack request: [packAtlas] composes through here, and a repack's undo re-derives an earlier page + * set through here, so the two can never drift apart. Placement footprints including their + * extrusion are pairwise disjoint (every placement reserves at least [extrude] of gutter on every + * side, which the bounds checks below enforce against the page and the packer enforced between + * tiles), so the composition is order-independent. + * + * @param IntArray pageWidths Page widths in pixels, indexed by [AtlasPackPlacement.pageIndex]. + * @param IntArray pageHeights Page heights in pixels, index-parallel to [pageWidths]. + * @param List items The tiles' pixels; every placement's key must resolve here. + * @param List placements Where each tile goes. + * @param Int extrude How many pixels of each tile's edge color are bled into the gutter, at zero alpha. + * @return List The composed pages, RGBA8888, in page-index order. + */ +public fun composeAtlasPages( + pageWidths: IntArray, + pageHeights: IntArray, + items: List, + placements: List, + extrude: Int, +): List { + require(pageWidths.size == pageHeights.size) { + "page width and height lists must be index-parallel: ${pageWidths.size} vs ${pageHeights.size}" + } + require(extrude >= 0) { "extrude must be non-negative: $extrude" } + val itemByKey = items.associateBy { item -> item.key } + require(itemByKey.size == items.size) { "atlas pack item keys must be unique" } + val pageBuffers = List(pageWidths.size) { pageIndex -> ByteArray(pageWidths[pageIndex] * pageHeights[pageIndex] * 4) } + for (placement in placements) { + val item = requireNotNull(itemByKey[placement.key]) { "placement '${placement.key}' has no item" } + require(placement.quarterTurns in 0..1) { + "placement '${placement.key}' has an unsupported rotation: ${placement.quarterTurns} quarter turns" + } + require( + placement.trimLeft >= 0 && + placement.trimTop >= 0 && + placement.trimLeft + placement.trimWidth <= item.width && + placement.trimTop + placement.trimHeight <= item.height, + ) { + "placement '${placement.key}' trims outside its ${item.width}x${item.height} raster" + } + val pageWidth = pageWidths.getOrNull(placement.pageIndex) + val pageHeight = pageHeights.getOrNull(placement.pageIndex) + require(pageWidth != null && pageHeight != null) { + "placement '${placement.key}' names page ${placement.pageIndex} of ${pageWidths.size}" + } + require( + placement.pageX - extrude >= 0 && + placement.pageY - extrude >= 0 && + placement.pageX + placement.pageWidth + extrude <= pageWidth && + placement.pageY + placement.pageHeight + extrude <= pageHeight, + ) { + "placement '${placement.key}' plus its $extrude px extrusion falls outside its ${pageWidth}x$pageHeight page" + } + val trim = LayerBounds(placement.trimLeft, placement.trimTop, placement.trimWidth, placement.trimHeight) + blitTile( + page = pageBuffers[placement.pageIndex], + pageWidth = pageWidth, + sourceRgba = item.rgba, + sourceWidth = item.width, + trim = trim, + destinationX = placement.pageX, + destinationY = placement.pageY, + quarterTurns = placement.quarterTurns, + ) + extrudeTileEdges( + page = pageBuffers[placement.pageIndex], + pageWidth = pageWidth, + sourceRgba = item.rgba, + sourceWidth = item.width, + trim = trim, + tileX = placement.pageX, + tileY = placement.pageY, + quarterTurns = placement.quarterTurns, + extrude = extrude, + ) + } + return pageBuffers.mapIndexed { pageIndex, buffer -> RasterImage(pageWidths[pageIndex], pageHeights[pageIndex], buffer) } +} + +/** + * One tile placed on a page by an arbitrary 2x3 affine over tile pixels - the shape a hand-authored + * placement takes once a rigger has rotated or scaled it, which [AtlasPackPlacement]'s integer rect + * plus quarter turn cannot hold. + * + * @property String key The tile's key into the items list. + * @property Int pageIndex The page the tile lands on. + * @property LayerBounds trim The opaque sub-rectangle of the tile's raster that is drawn, raster-local. + * @property FloatArray tileToPage The affine (m00, m01, m02, m10, m11, m12) mapping tile pixels to + * page pixels, both frames y-down with pixel (x, y) spanning [x, x + 1) by [y, y + 1). + */ +public class AtlasTilePlacement( + public val key: String, + public val pageIndex: Int, + public val trim: LayerBounds, + public val tileToPage: FloatArray, +) { + init { + require(tileToPage.size == 6) { "placement '$key' needs a 2x3 affine, got ${tileToPage.size} components" } + } +} + +/** + * Composes atlas pages from placements given as affines - [composeAtlasPages] for tiles that may sit + * rotated, scaled, off the pixel grid, or partly off the page. + * + * A placement that is an exact integer translation, or an exact counter-clockwise quarter turn on + * integer pixels, with room for its bleed band takes the packer's own blit and edge bleed, so a + * page composed here from a repack's placements is byte-identical to the page the packer composed, + * turned tiles included. Every other placement is resampled: each page pixel reads the tile + * bilinearly at its center's pre-image, against transparency beyond the trim, so an edge off the pixel + * grid lands with the partial coverage it has - the way the editor resamples its own pages. A page + * pixel the tile does not cover within [extrude] pixels of the footprint takes the nearest edge's color + * at zero alpha - the packer's bleed band, expressed so it holds under rotation. Pixels that fall off + * the page are dropped rather than refused: the placement is a rigger's authored choice, and clipping + * is what the page would show. + * + * Unlike the packer's placements, hand-authored footprints may overlap; they paint in list order + * under the content-preserving rule (a later transparent sample never erases an earlier tile, a later + * opaque one wins). + * + * @param IntArray pageWidths Page widths in pixels, indexed by [AtlasTilePlacement.pageIndex]. + * @param IntArray pageHeights Page heights in pixels, index-parallel to [pageWidths]. + * @param List items The tiles' pixels; every placement's key must resolve here. + * @param List placements Where each tile goes. + * @param Int extrude How many pixels of each tile's edge color are bled outward, at zero alpha. + * @return List The composed pages, RGBA8888 straight alpha, in page-index order. + */ +public fun composeAtlasPagesAffine( + pageWidths: IntArray, + pageHeights: IntArray, + items: List, + placements: List, + extrude: Int, +): List { + require(pageWidths.size == pageHeights.size) { + "page width and height lists must be index-parallel: ${pageWidths.size} vs ${pageHeights.size}" + } + require(extrude >= 0) { "extrude must be non-negative: $extrude" } + val itemByKey = items.associateBy { item -> item.key } + require(itemByKey.size == items.size) { "atlas pack item keys must be unique" } + val pageBuffers = List(pageWidths.size) { pageIndex -> ByteArray(pageWidths[pageIndex] * pageHeights[pageIndex] * 4) } + for (placement in placements) { + val item = requireNotNull(itemByKey[placement.key]) { "placement '${placement.key}' has no item" } + val trim = placement.trim + require( + trim.left >= 0 && + trim.top >= 0 && + trim.left + trim.width <= item.width && + trim.top + trim.height <= item.height, + ) { + "placement '${placement.key}' trims outside its ${item.width}x${item.height} raster" + } + val pageWidth = pageWidths.getOrNull(placement.pageIndex) + val pageHeight = pageHeights.getOrNull(placement.pageIndex) + require(pageWidth != null && pageHeight != null) { + "placement '${placement.key}' names page ${placement.pageIndex} of ${pageWidths.size}" + } + if (trim.width <= 0 || trim.height <= 0) { + continue + } + paintTilePlacement(pageBuffers[placement.pageIndex], pageWidth, pageHeight, item, trim, placement.tileToPage, extrude) + } + return pageBuffers.mapIndexed { pageIndex, buffer -> RasterImage(pageWidths[pageIndex], pageHeights[pageIndex], buffer) } +} + +/** + * Paints one tile onto a page through its affine: the packer's own blit and edge bleed when the + * affine is one of the packer's exact placements with room for the band, else the resampling blit. + * + * The ONE path a hand-authored placement takes, whether [composeAtlasPagesAffine] derives it from a + * model or [packAtlas] keeps it as a fixed tile beside the tiles it packed, so a page the packer + * composed and the page a derivation composes from the same placement cannot differ. + * + * @param ByteArray page The destination page, RGBA8888 row-major from the top. + * @param Int pageWidth The page width in pixels. + * @param Int pageHeight The page height in pixels. + * @param AtlasPackItem item The tile's pixels. + * @param LayerBounds trim The opaque sub-rectangle of the tile that is drawn, raster-local. + * @param FloatArray tileToPage The affine mapping tile pixels to page pixels. + * @param Int extrude How many pixels of edge color to bleed outward, at zero alpha. + */ +internal fun paintTilePlacement( + page: ByteArray, + pageWidth: Int, + pageHeight: Int, + item: AtlasPackItem, + trim: LayerBounds, + tileToPage: FloatArray, + extrude: Int, +) { + val exact = exactPlacement(tileToPage, trim) + if (exact != null && + exact.originX - extrude >= 0 && + exact.originY - extrude >= 0 && + exact.originX + exact.placedWidth(trim) + extrude <= pageWidth && + exact.originY + exact.placedHeight(trim) + extrude <= pageHeight + ) { + blitTile(page, pageWidth, item.rgba, item.width, trim, exact.originX, exact.originY, exact.quarterTurns) + extrudeTileEdges(page, pageWidth, item.rgba, item.width, trim, exact.originX, exact.originY, exact.quarterTurns, extrude) + } else { + blitTileAffine(page, pageWidth, pageHeight, item.rgba, item.width, trim, tileToPage, extrude) + } +} + +/** + * The page-space bounding box of a tile-local rectangle through an affine - its four corners mapped + * and their extremes taken, so a rotated rectangle's box is the box of its turned corners. + * + * @param FloatArray affine The affine (m00, m01, m02, m10, m11, m12) mapping tile pixels to page pixels. + * @param Float left The rectangle's left edge, tile-local. + * @param Float top The rectangle's top edge. + * @param Float right The rectangle's right edge, exclusive. + * @param Float bottom The rectangle's bottom edge, exclusive. + * @return FloatArray The box as (left, top, right, bottom) in continuous page pixels. + */ +internal fun affineBounds( + affine: FloatArray, + left: Float, + top: Float, + right: Float, + bottom: Float, +): FloatArray { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + for (cornerIndex in 0 until 4) { + val cornerX = if (cornerIndex and 1 == 0) left else right + val cornerY = if (cornerIndex and 2 == 0) top else bottom + val pageX = affine[0] * cornerX + affine[1] * cornerY + affine[2] + val pageY = affine[3] * cornerX + affine[4] * cornerY + affine[5] + minX = minOf(minX, pageX) + minY = minOf(minY, pageY) + maxX = maxOf(maxX, pageX) + maxY = maxOf(maxY, pageY) + } + return floatArrayOf(minX, minY, maxX, maxY) +} + +/** + * How far a rotation term may sit from zero and still read as one of the packer's quarter turns. + * + * A placement rotated by -90 degrees carries cos(-pi / 2) in its diagonal, which is near zero in + * float, not zero; the sine terms are exact. Anything a real hand rotation produces is orders of + * magnitude farther from a quarter turn than this. + */ +private const val EXACT_TURN_EPSILON = 1e-6f + +/** + * A placement the packer's own blit serves: the page pixel the placed tile's top-left lands on and + * how the tile is turned there. + * + * @property Int originX The placed tile's left edge on the page. + * @property Int originY The placed tile's top edge on the page. + * @property Int quarterTurns 0 for upright, 1 for one counter-clockwise quarter turn. + */ +private class ExactPlacement( + val originX: Int, + val originY: Int, + val quarterTurns: Int, +) { + /** + * The placed footprint's width for [trim]: a turn swaps the trim's sides. + * + * @param LayerBounds trim The tile's drawn sub-rectangle. + * @return Int The on-page width in pixels. + */ + fun placedWidth(trim: LayerBounds): Int = if (quarterTurns == 0) trim.width else trim.height + + /** + * The placed footprint's height for [trim]. + * + * @param LayerBounds trim The tile's drawn sub-rectangle. + * @return Int The on-page height in pixels. + */ + fun placedHeight(trim: LayerBounds): Int = if (quarterTurns == 0) trim.height else trim.width +} + +/** + * Classifies [placement] as one the packer's blit serves - an exact integer translation, or an exact + * counter-clockwise quarter turn landing on integer pixels - else null. + * + * The turned case is the affine the packer's own turn induces over the untrimmed tile frame: it sends + * trim-local (u, v) to (originX + v, originY + trimWidth - u), so the placed top-left sits at + * (m02 + trim.top, m12 - trim.left - trim.width). Recognising it here is what lets a repack that + * turned a tile derive byte-identical pages instead of resampling through the bilinear path, whose + * bleed band rounds corners differently from the packer's. + * + * @param FloatArray affine The tile-to-page affine to classify. + * @param LayerBounds trim The tile's drawn sub-rectangle, raster-local. + * @return ExactPlacement? The blit origin and turn, or null when the affine scales, rotates by + * anything but a packer turn, or lands between pixels. + */ +private fun exactPlacement(affine: FloatArray, trim: LayerBounds): ExactPlacement? { + val quarterTurns: Int + val originX: Float + val originY: Float + if (affine[0] == 1f && affine[1] == 0f && affine[3] == 0f && affine[4] == 1f) { + quarterTurns = 0 + originX = affine[2] + trim.left + originY = affine[5] + trim.top + } else if (abs(affine[0]) <= EXACT_TURN_EPSILON && affine[1] == 1f && affine[3] == -1f && abs(affine[4]) <= EXACT_TURN_EPSILON) { + quarterTurns = 1 + originX = affine[2] + trim.top + originY = affine[5] - trim.left - trim.width + } else { + return null + } + val pixelX = originX.roundToInt() + val pixelY = originY.roundToInt() + if (pixelX.toFloat() != originX || pixelY.toFloat() != originY) { + return null + } + return ExactPlacement(pixelX, pixelY, quarterTurns) +} + +/** + * Inverts a 2x3 affine, or null when it is singular. + * + * @param FloatArray affine The affine (m00, m01, m02, m10, m11, m12). + * @return FloatArray? The inverse. + */ +private fun invertAffine2x3(affine: FloatArray): FloatArray? { + val determinant = affine[0] * affine[4] - affine[1] * affine[3] + if (determinant == 0f) { + return null + } + val m00 = affine[4] / determinant + val m01 = -affine[1] / determinant + val m10 = -affine[3] / determinant + val m11 = affine[0] / determinant + return floatArrayOf( + m00, + m01, + -(m00 * affine[2] + m01 * affine[5]), + m10, + m11, + -(m10 * affine[2] + m11 * affine[5]), + ) +} + +/** + * Resamples one trimmed tile onto a page through an affine, clipping to the page. + * + * Runs over the footprint's bounding box grown by the bleed band plus the one texel a bilinear tap + * reaches past the trim, and inverse-maps each page pixel center into the tile. The tile is sampled + * bilinearly there against TRANSPARENCY beyond the trim ([sampleBilinearCovered]), so an edge that + * falls between page pixels paints the partial coverage it has, and nothing paints farther out than + * the art reaches. A pixel the tile does not cover at all takes the nearest edge's color at zero alpha + * when that edge, mapped back to the page, lies within [extrude] pixels - the packer's bleed band as a + * band of constant width around the footprint whatever its orientation - and is left untouched beyond + * it. Both go through the content-preserving rule; the band as synthetic. + * + * @param ByteArray page The destination page, RGBA8888 row-major from the top. + * @param Int pageWidth The page width in pixels. + * @param Int pageHeight The page height in pixels. + * @param ByteArray sourceRgba The source raster, RGBA8888 row-major from the top. + * @param Int sourceWidth The source raster's width in pixels (its row stride). + * @param LayerBounds trim The opaque sub-rectangle of the source to draw, raster-local. + * @param FloatArray tileToPage The affine mapping tile pixels to page pixels. + * @param Int extrude How many pixels of edge color to bleed outward, at zero alpha. + */ +internal fun blitTileAffine( + page: ByteArray, + pageWidth: Int, + pageHeight: Int, + sourceRgba: ByteArray, + sourceWidth: Int, + trim: LayerBounds, + tileToPage: FloatArray, + extrude: Int, +) { + val pageToTile = invertAffine2x3(tileToPage) ?: return + val trimLeft = trim.left.toFloat() + val trimTop = trim.top.toFloat() + val trimRight = (trim.left + trim.width).toFloat() + val trimBottom = (trim.top + trim.height).toFloat() + // The footprint's page-space bounding box: the four trim corners through the affine. A bilinear tap + // reaches half a texel past the trim, so coverage can land up to one page pixel past the box even + // with no band; the scan reaches whichever is farther. + val bounds = affineBounds(tileToPage, trimLeft, trimTop, trimRight, trimBottom) + val reach = maxOf(extrude, 1) + val startColumn = floor(bounds[0] - reach).toInt().coerceAtLeast(0) + val endColumn = ceil(bounds[2] + reach).toInt().coerceAtMost(pageWidth) + val startRow = floor(bounds[1] - reach).toInt().coerceAtLeast(0) + val endRow = ceil(bounds[3] + reach).toInt().coerceAtMost(pageHeight) + if (startColumn >= endColumn || startRow >= endRow) { + return + } + val extrudeSquared = extrude.toFloat() * extrude.toFloat() + val lastColumn = trim.left + trim.width - 1 + val lastRow = trim.top + trim.height - 1 + val sample = IntArray(4) + for (pageRow in startRow until endRow) { + val centerY = pageRow + 0.5f + for (pageColumn in startColumn until endColumn) { + val centerX = pageColumn + 0.5f + val tileX = pageToTile[0] * centerX + pageToTile[1] * centerY + pageToTile[2] + val tileY = pageToTile[3] * centerX + pageToTile[4] * centerY + pageToTile[5] + sampleBilinearCovered(sourceRgba, sourceWidth, trim.left, trim.top, lastColumn, lastRow, tileX, tileY, sample) + val pageOffset = (pageRow * pageWidth + pageColumn) * 4 + val clampedX = tileX.coerceIn(trimLeft, trimRight) + val clampedY = tileY.coerceIn(trimTop, trimBottom) + val insideTrim = clampedX == tileX && clampedY == tileY + if (sample[3] > 0 || insideTrim) { + // The tile's own pixels, a transparent one included, and the partial coverage of an edge. + writeSample(page, pageOffset, sample[0], sample[1], sample[2], sample[3], synthetic = false) + continue + } + if (extrude == 0) { + continue + } + val backX = tileToPage[0] * clampedX + tileToPage[1] * clampedY + tileToPage[2] + val backY = tileToPage[3] * clampedX + tileToPage[4] * clampedY + tileToPage[5] + val deltaX = backX - centerX + val deltaY = backY - centerY + if (deltaX * deltaX + deltaY * deltaY > extrudeSquared) { + continue + } + writeSample(page, pageOffset, sample[0], sample[1], sample[2], 0, synthetic = true) + } + } +} + +/** + * Samples the tile at a continuous tile-space point, bilinearly over the four surrounding texels, with + * every texel beyond the trim transparent. + * + * Transparent beyond the trim, not clamped to it: the art ends at the trim's edge, and a pixel center + * half a texel past an opaque edge must come out half covered - which is also how the editor resamples + * a tile it places between pixels. A tap beyond the trim still lends the nearest edge texel's color, so + * a point no texel covers carries the edge's color at zero alpha, and the covered texels' colors are + * averaged by their alpha: straight-alpha texels interpolate in premultiplied space and convert back, + * because averaging straight RGB across an alpha edge drags the matte color into the visible pixels. A + * point exactly on a texel center copies that texel verbatim, so an integer-aligned placement (a quarter + * turn, an exact translation the packer's blit could not take) stays byte-exact. + * + * @param ByteArray source The source raster, RGBA8888 row-major from the top. + * @param Int sourceWidth The source raster's row stride in pixels. + * @param Int firstColumn The trim's first column. + * @param Int firstRow The trim's first row. + * @param Int lastColumn The trim's last column, inclusive. + * @param Int lastRow The trim's last row, inclusive. + * @param Float sampleX The tile-space x to sample (texel (x, y) spans [x, x + 1)). + * @param Float sampleY The tile-space y to sample. + * @param IntArray out Receives the sample as (red, green, blue, alpha), 0..255. + */ +private fun sampleBilinearCovered( + source: ByteArray, + sourceWidth: Int, + firstColumn: Int, + firstRow: Int, + lastColumn: Int, + lastRow: Int, + sampleX: Float, + sampleY: Float, + out: IntArray, +) { + val x = sampleX - 0.5f + val y = sampleY - 0.5f + val floorX = floor(x) + val floorY = floor(y) + val fractionX = x - floorX + val fractionY = y - floorY + val baseColumn = floorX.toInt() + val baseRow = floorY.toInt() + var red = 0f + var green = 0f + var blue = 0f + var alpha = 0f + var straightRed = 0f + var straightGreen = 0f + var straightBlue = 0f + for (tapIndex in 0 until 4) { + val column = if (tapIndex and 1 == 0) baseColumn else baseColumn + 1 + val row = if (tapIndex and 2 == 0) baseRow else baseRow + 1 + val weight = + when (tapIndex) { + 0 -> (1f - fractionX) * (1f - fractionY) + 1 -> fractionX * (1f - fractionY) + 2 -> (1f - fractionX) * fractionY + else -> fractionX * fractionY + } + if (weight == 0f) { + continue + } + val inside = column in firstColumn..lastColumn && row in firstRow..lastRow + val offset = (row.coerceIn(firstRow, lastRow) * sourceWidth + column.coerceIn(firstColumn, lastColumn)) * 4 + val tapRed = (source[offset].toInt() and 0xFF).toFloat() + val tapGreen = (source[offset + 1].toInt() and 0xFF).toFloat() + val tapBlue = (source[offset + 2].toInt() and 0xFF).toFloat() + val tapAlpha = if (inside) (source[offset + 3].toInt() and 0xFF).toFloat() else 0f + if (weight == 1f) { + // Exactly on one texel's center: that texel, verbatim (at zero alpha when it lies beyond the trim). + out[0] = tapRed.toInt() + out[1] = tapGreen.toInt() + out[2] = tapBlue.toInt() + out[3] = tapAlpha.toInt() + return + } + red += weight * tapRed * tapAlpha + green += weight * tapGreen * tapAlpha + blue += weight * tapBlue * tapAlpha + alpha += weight * tapAlpha + straightRed += weight * tapRed + straightGreen += weight * tapGreen + straightBlue += weight * tapBlue + } + if (alpha > 0f) { + out[0] = (red / alpha).roundToInt().coerceIn(0, 255) + out[1] = (green / alpha).roundToInt().coerceIn(0, 255) + out[2] = (blue / alpha).roundToInt().coerceIn(0, 255) + } else { + // Nothing covered: keep the color the texels carry rather than inventing black. + out[0] = straightRed.roundToInt().coerceIn(0, 255) + out[1] = straightGreen.roundToInt().coerceIn(0, 255) + out[2] = straightBlue.roundToInt().coerceIn(0, 255) + } + out[3] = alpha.roundToInt().coerceIn(0, 255) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/atlas/RectPacker.kt b/module/format/src/commonMain/kotlin/org/umamo/format/atlas/RectPacker.kt new file mode 100644 index 0000000..121b633 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/atlas/RectPacker.kt @@ -0,0 +1,323 @@ +package org.umamo.format.atlas + +/* + * The rectangle bin packer behind the atlas packer: pure integer geometry with no art types and no + * pixels, so it is testable on its own and reusable by any other page-composition caller. + * + * MaxRects with best-short-side-fit (Jukka Jylanki, "A Thousand Ways to Pack the Bin"): each page + * keeps a list of maximal free rectangles; a request goes into the free rectangle that leaves the + * smallest short-side remainder, and every free rectangle the placement overlaps is then split and + * the contained ones pruned. Pages are tried in order and a new one opens only when none fits. + */ + +/** One rectangle to place: the caller's index plus the page footprint it needs, gutter included. */ +internal class RectPackRequest( + val itemIndex: Int, + val width: Int, + val height: Int, +) + +/** + * One rectangle decided before the pack runs: the page it holds and the footprint it keeps there, + * gutter included. A seed is occupied before any request is placed, so every free placement packs + * around it; it is never placed, reported, or turned. + */ +internal class RectPackSeed( + val pageIndex: Int, + val x: Int, + val y: Int, + val width: Int, + val height: Int, +) + +/** Where one request landed: its page, the footprint's top-left, and whether it was quarter-turned. */ +internal class RectPackSlot( + val itemIndex: Int, + val pageIndex: Int, + val x: Int, + val y: Int, + val rotated: Boolean, +) + +/** + * The packing outcome. + * + * [usedWidths] / [usedHeights] are the extent actually occupied on each page - the maximum right and + * bottom edge of any footprint - which is what a shrink-to-fit caller crops to. Because a footprint + * already carries its gutter on every side, that extent includes the trailing gutter margin. + */ +internal class RectPackLayout( + val slots: List, + val oversizedItemIndices: List, + val usedWidths: List, + val usedHeights: List, +) + +/** + * Packs footprints onto as many equally-sized pages as they need. + * + * Requests are packed in descending max-side order, which is what makes MaxRects behave: the large + * awkward pieces claim their space while the free list is still coarse, and the small ones fill the + * remainders. The caller is responsible for supplying a deterministic request order - this function + * preserves it exactly and adds no ordering of its own. + * + * Seeds go first: a seeded page exists whether or not a request lands on it (a seed on page 2 opens + * pages 0 and 1 too, so page indices keep their meaning), and its rectangle is taken before the first + * request is placed. The caller keeps every seed inside the page - a seed is a footprint the caller + * already decided to keep, so there is nothing sensible to do with one that does not fit. + * + * @param List requests The footprints to place, already in packing order. + * @param Int pageSize The square page side every page is packed against, in pixels. + * @param Boolean allowRotation Whether a request may be quarter-turned to fit. + * @param List seeds Footprints already decided, occupied before any request is placed. + * @return RectPackLayout The placements, the requests too large for any page, and the used extents. + */ +internal fun packRects( + requests: List, + pageSize: Int, + allowRotation: Boolean, + seeds: List = emptyList(), +): RectPackLayout { + require(pageSize > 0) { "pageSize must be positive: $pageSize" } + + val slots = ArrayList(requests.size) + val oversizedItemIndices = ArrayList() + val pages = ArrayList() + + for (seed in seeds) { + require(seed.pageIndex >= 0) { "seed page index must not be negative: ${seed.pageIndex}" } + while (pages.size <= seed.pageIndex) { + pages.add(MaxRectsPage(pageSize)) + } + pages[seed.pageIndex].seed(seed.x, seed.y, seed.width, seed.height) + } + + for (request in requests) { + // A square page cap means a quarter turn cannot rescue an oversized request: both sides + // have to fit either way. + if (request.width > pageSize || request.height > pageSize) { + oversizedItemIndices.add(request.itemIndex) + continue + } + var placed = false + for ((pageIndex, page) in pages.withIndex()) { + val placement = page.place(request.width, request.height, allowRotation) + if (placement != null) { + slots.add(RectPackSlot(request.itemIndex, pageIndex, placement.x, placement.y, placement.rotated)) + placed = true + break + } + } + if (!placed) { + val freshPage = MaxRectsPage(pageSize) + val placement = + checkNotNull(freshPage.place(request.width, request.height, allowRotation)) { + "request ${request.width}x${request.height} fits the page cap $pageSize but not an empty page" + } + pages.add(freshPage) + slots.add(RectPackSlot(request.itemIndex, pages.size - 1, placement.x, placement.y, placement.rotated)) + } + } + + return RectPackLayout( + slots = slots, + oversizedItemIndices = oversizedItemIndices, + usedWidths = pages.map { page -> page.usedWidth }, + usedHeights = pages.map { page -> page.usedHeight }, + ) +} + +/** A chosen position for one request, with the orientation it was accepted at. */ +private class MaxRectsPlacement(val x: Int, val y: Int, val rotated: Boolean) + +/** One free rectangle in the maximal-rectangles free list. */ +private class FreeRect(val x: Int, val y: Int, val width: Int, val height: Int) + +/** One page being packed: a square of [pageSize] plus its maximal free rectangles. */ +private class MaxRectsPage(private val pageSize: Int) { + private var freeRects = mutableListOf(FreeRect(0, 0, pageSize, pageSize)) + + /** The furthest right edge, in pixels, that any placement on this page has reached. */ + var usedWidth: Int = 0 + private set + + /** The furthest down edge, in pixels, that any placement on this page has reached. */ + var usedHeight: Int = 0 + private set + + /** + * Places one footprint if it fits, choosing the free rectangle with the smallest short-side + * remainder and breaking ties on the long side. + * + * @param Int width The footprint width. + * @param Int height The footprint height. + * @param Boolean allowRotation Whether the quarter-turned orientation may be considered. + * @return MaxRectsPlacement The accepted position, or null when nothing fits. + */ + fun place(width: Int, height: Int, allowRotation: Boolean): MaxRectsPlacement? { + var bestShortSide = Int.MAX_VALUE + var bestLongSide = Int.MAX_VALUE + var bestX = -1 + var bestY = -1 + var bestRotated = false + + for (freeRect in freeRects) { + val orientationCount = if (allowRotation) 2 else 1 + for (orientationIndex in 0 until orientationCount) { + val rotated = orientationIndex == 1 + val candidateWidth = if (rotated) height else width + val candidateHeight = if (rotated) width else height + if (candidateWidth > freeRect.width || candidateHeight > freeRect.height) { + continue + } + val leftoverHorizontal = freeRect.width - candidateWidth + val leftoverVertical = freeRect.height - candidateHeight + val shortSide = minOf(leftoverHorizontal, leftoverVertical) + val longSide = maxOf(leftoverHorizontal, leftoverVertical) + if (shortSide < bestShortSide || (shortSide == bestShortSide && longSide < bestLongSide)) { + bestShortSide = shortSide + bestLongSide = longSide + bestX = freeRect.x + bestY = freeRect.y + bestRotated = rotated + } + } + } + + if (bestX < 0) { + return null + } + val placedWidth = if (bestRotated) height else width + val placedHeight = if (bestRotated) width else height + occupy(bestX, bestY, placedWidth, placedHeight) + usedWidth = maxOf(usedWidth, bestX + placedWidth) + usedHeight = maxOf(usedHeight, bestY + placedHeight) + return MaxRectsPlacement(bestX, bestY, bestRotated) + } + + /** + * Takes a footprint decided before the pack: the free list loses it exactly as it loses a + * placement, and the used extent grows to cover it, so a page cropped to what it uses still + * holds the seed. + * + * @param Int seedX The footprint's left edge. + * @param Int seedY The footprint's top edge. + * @param Int seedWidth The footprint's width. + * @param Int seedHeight The footprint's height. + */ + fun seed(seedX: Int, seedY: Int, seedWidth: Int, seedHeight: Int) { + occupy(seedX, seedY, seedWidth, seedHeight) + usedWidth = maxOf(usedWidth, seedX + seedWidth) + usedHeight = maxOf(usedHeight, seedY + seedHeight) + } + + /** + * Splits every free rectangle the placement overlaps, then drops the ones now contained. + * + * @param Int placedX The footprint's left edge. + * @param Int placedY The footprint's top edge. + * @param Int placedWidth The footprint's width. + * @param Int placedHeight The footprint's height. + */ + private fun occupy(placedX: Int, placedY: Int, placedWidth: Int, placedHeight: Int) { + val next = ArrayList(freeRects.size + 4) + for (freeRect in freeRects) { + if (!splitFreeRect(freeRect, placedX, placedY, placedWidth, placedHeight, next)) { + next.add(freeRect) + } + } + freeRects = pruneContained(next) + } + + /** + * Splits one free rectangle around the placed footprint, appending the surviving strips. + * + * @param FreeRect freeRect The free rectangle to split. + * @param Int placedX The footprint's left edge. + * @param Int placedY The footprint's top edge. + * @param Int placedWidth The footprint's width. + * @param Int placedHeight The footprint's height. + * @param MutableList out Receives the strips left over after the split. + * @return Boolean True when the footprint overlapped and the rectangle was consumed. + */ + private fun splitFreeRect( + freeRect: FreeRect, + placedX: Int, + placedY: Int, + placedWidth: Int, + placedHeight: Int, + out: MutableList, + ): Boolean { + val placedRight = placedX + placedWidth + val placedBottom = placedY + placedHeight + val freeRight = freeRect.x + freeRect.width + val freeBottom = freeRect.y + freeRect.height + if (placedX >= freeRight || placedRight <= freeRect.x || placedY >= freeBottom || placedBottom <= freeRect.y) { + return false + } + if (placedX < freeRight && placedRight > freeRect.x) { + if (placedY > freeRect.y && placedY < freeBottom) { + out.add(FreeRect(freeRect.x, freeRect.y, freeRect.width, placedY - freeRect.y)) + } + if (placedBottom < freeBottom) { + out.add(FreeRect(freeRect.x, placedBottom, freeRect.width, freeBottom - placedBottom)) + } + } + if (placedY < freeBottom && placedBottom > freeRect.y) { + if (placedX > freeRect.x && placedX < freeRight) { + out.add(FreeRect(freeRect.x, freeRect.y, placedX - freeRect.x, freeRect.height)) + } + if (placedRight < freeRight) { + out.add(FreeRect(placedRight, freeRect.y, freeRight - placedRight, freeRect.height)) + } + } + return true + } + + /** + * Drops every free rectangle wholly contained in another, keeping the list maximal. + * + * The pairwise sweep is the canonical MaxRects prune. Duplicates contain each other, and the + * first check below fires for that case, so the EARLIER index is the one dropped; the survivors + * keep their relative order either way, and page layout is only deterministic if this is. + * + * @param MutableList candidates The free list after splitting, possibly with contained entries. + * @return MutableList The maximal free list. + */ + private fun pruneContained(candidates: MutableList): MutableList { + var candidateIndex = 0 + while (candidateIndex < candidates.size) { + var otherIndex = candidateIndex + 1 + var removedCandidate = false + while (otherIndex < candidates.size) { + if (contains(candidates[otherIndex], candidates[candidateIndex])) { + candidates.removeAt(candidateIndex) + removedCandidate = true + break + } + if (contains(candidates[candidateIndex], candidates[otherIndex])) { + candidates.removeAt(otherIndex) + continue + } + otherIndex++ + } + if (!removedCandidate) { + candidateIndex++ + } + } + return candidates + } + + /** + * Whether [outer] wholly covers [inner]. + * + * @param FreeRect outer The candidate containing rectangle. + * @param FreeRect inner The candidate contained rectangle. + * @return Boolean True when every corner of [inner] lies within or on the border of [outer]. + */ + private fun contains(outer: FreeRect, inner: FreeRect): Boolean = + inner.x >= outer.x && + inner.y >= outer.y && + inner.x + inner.width <= outer.x + outer.width && + inner.y + inner.height <= outer.y + outer.height +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/BinaryText.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/BinaryText.kt new file mode 100644 index 0000000..8d3ccc8 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/BinaryText.kt @@ -0,0 +1,58 @@ +package org.umamo.format.binary + +/* + * Text encodings the binary readers need, in common code. + * + * `kotlin.text.Charsets` is JVM-only despite being a default import, so `String(bytes, US_ASCII)` + * and `toByteArray(UTF_16BE)` cannot appear in commonMain. These are the two conversions the + * format readers actually use, implemented directly. Kotlin's stdlib offers no common Charset + * API, and `decodeToString()` is UTF-8 only — which is NOT a drop-in for either of these. + */ + +/** Byte values above this are not representable in ASCII. */ +private const val ASCII_MAX = 0x7F + +/** What a malformed byte decodes to, matching the JVM's US_ASCII decoder. */ +private const val REPLACEMENT_CHARACTER = '�' + +/** + * Decodes [length] bytes of [bytes] at [offset] as US-ASCII. + * + * Matches the JVM's `String(bytes, offset, length, Charsets.US_ASCII)` exactly, including mapping any + * byte outside 0x00..0x7F to U+FFFD. That fidelity matters: the naive alternative (`Byte.toChar()`) + * would silently decode high bytes as Latin-1, so a corrupt signature could compare equal to + * something it is not. Note `decodeToString()` is not a substitute — it decodes UTF-8. + * + * @param ByteArray bytes The buffer to read from. + * @param Int offset Offset of the first byte. + * @param Int length Number of bytes to decode. + * @return String The decoded text. + */ +internal fun decodeAscii(bytes: ByteArray, offset: Int, length: Int): String { + val characters = CharArray(length) + for (characterIndex in 0 until length) { + val byteValue = bytes[offset + characterIndex].toInt() and 0xFF + characters[characterIndex] = if (byteValue <= ASCII_MAX) byteValue.toChar() else REPLACEMENT_CHARACTER + } + return characters.concatToString() +} + +/** + * Encodes [text] as UTF-16 big-endian. + * + * Matches the JVM's `toByteArray(Charsets.UTF_16BE)`: a Kotlin `Char` is already a UTF-16 code unit, + * so writing each one big-endian is UTF-16BE by construction (surrogate pairs included, since they are + * simply two code units). No byte-order mark is emitted, which is what UTF_16BE means. + * + * @param String text The text to encode. + * @return ByteArray The UTF-16BE bytes, two per code unit. + */ +internal fun encodeUtf16Be(text: String): ByteArray { + val encoded = ByteArray(text.length * 2) + for (characterIndex in text.indices) { + val codeUnit = text[characterIndex].code + encoded[characterIndex * 2] = ((codeUnit ushr 8) and 0xFF).toByte() + encoded[characterIndex * 2 + 1] = (codeUnit and 0xFF).toByte() + } + return encoded +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/ByteReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ByteReader.kt new file mode 100644 index 0000000..fe50cc4 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ByteReader.kt @@ -0,0 +1,130 @@ +package org.umamo.format.binary + +/** + * A little-or-big-endian random-access reader over a [ByteArray], shared by the codecs that parse + * structured binary headers (TIFF's II/MM directories, WebP's little-endian RIFF chunks, PSD's + * big-endian records). + * + * Also the common-code replacement for `java.nio.ByteBuffer`, which is why it carries both a cursor + * and absolute reads: it defaults to big-endian and its [position] behaves like ByteBuffer's, so a + * big-endian ByteBuffer parser ports across without restructuring. Offsets are Int (files under + * 2 GiB); 32-bit fields are read as Long to stay unsigned-safe, with [u32AsInt] for the common + * in-range case. [position] advances on the sequential read* methods; the at-offset methods do not + * move it. + */ +internal class ByteReader( + val bytes: ByteArray, + var position: Int = 0, + var littleEndian: Boolean = false, +) { + /** + * Reads an unsigned byte at [at] without moving [position]. + * + * @param Int at Absolute offset. + * @return Int The value in 0..255. + */ + fun u8(at: Int): Int = bytes[at].toInt() and 0xFF + + /** + * Reads an unsigned 16-bit value at [at] in the current byte order, without moving [position]. + * + * @param Int at Absolute offset of the first byte. + * @return Int The value in 0..65535. + */ + fun u16(at: Int): Int = + if (littleEndian) { + u8(at) or (u8(at + 1) shl 8) + } else { + (u8(at) shl 8) or u8(at + 1) + } + + /** + * Reads an unsigned 32-bit value at [at] in the current byte order (as a Long), without moving + * [position]. + * + * @param Int at Absolute offset of the first byte. + * @return Long The value in 0..4294967295. + */ + fun u32(at: Int): Long = + if (littleEndian) { + (u8(at).toLong()) or (u8(at + 1).toLong() shl 8) or (u8(at + 2).toLong() shl 16) or (u8(at + 3).toLong() shl 24) + } else { + (u8(at).toLong() shl 24) or (u8(at + 1).toLong() shl 16) or (u8(at + 2).toLong() shl 8) or u8(at + 3).toLong() + } + + /** + * Reads an unsigned 32-bit value at [at] as an Int (for offsets/counts within the 2 GiB range). + * + * @param Int at Absolute offset of the first byte. + * @return Int The value truncated to Int. + */ + fun u32AsInt(at: Int): Int = u32(at).toInt() + + /** + * Reads an unsigned byte at [position], then advances by one. + * + * @return Int The value in 0..255. + */ + fun readU8(): Int = u8(position).also { position += 1 } + + /** + * Reads an unsigned 16-bit value at [position], then advances by two. + * + * @return Int The value in 0..65535. + */ + fun readU16(): Int = u16(position).also { position += 2 } + + /** + * Reads an unsigned 32-bit value at [position] (as a Long), then advances by four. + * + * @return Long The value in 0..4294967295. + */ + fun readU32(): Long = u32(position).also { position += 4 } + + /** + * Reads an unsigned 32-bit value at [position] as an Int, then advances by four. + * + * @return Int The value truncated to Int. + */ + fun readU32AsInt(): Int = u32AsInt(position).also { position += 4 } + + /** + * Reads a signed 16-bit value at [position], then advances by two. + * + * @return Int The sign-extended value in -32768..32767. + */ + fun readI16(): Int = readU16().toShort().toInt() + + /** + * Reads [count] bytes at [position], then advances by that many. + * + * @param Int count Number of bytes to copy. + * @return ByteArray The bytes read. + */ + fun readBytes(count: Int): ByteArray = bytes.copyOfRange(position, position + count).also { position += count } + + /** + * Reads [count] bytes at [at] and decodes them as US-ASCII, without moving [position]. + * + * For the fixed 4-character tags binary formats use as signatures and keys (PSD's `8BIM`/`lyid`, + * RIFF's `WEBP`). Strictly ASCII, via [decodeAscii]: any byte above 0x7F becomes U+FFFD rather + * than a Latin-1 character, so a corrupt tag cannot compare equal to something it is not. NOT for + * arbitrary text - a format's human-readable strings (a PSD layer name, say) carry a real encoding + * and must be decoded with it; see [readBytes] plus `decodeToString()` for UTF-8. + * + * @param Int at Absolute offset of the first byte. + * @param Int count Number of bytes to decode. + * @return String The decoded text. + */ + fun asciiAt(at: Int, count: Int): String = decodeAscii(bytes, at, count) + + /** + * Reads [count] bytes at [position] and decodes them as US-ASCII, then advances by that many. + * + * Carries [asciiAt]'s constraints: fixed tags only, never arbitrary text. + * + * @param Int count Number of bytes to decode. + * @return String The decoded text. + */ + fun readAscii(count: Int): String = asciiAt(position, count).also { position += count } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/ContentHash.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ContentHash.kt new file mode 100644 index 0000000..fe0a160 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ContentHash.kt @@ -0,0 +1,19 @@ +package org.umamo.format.binary + +import okio.ByteString.Companion.toByteString + +/* + * The content hash the document records for what it read - a file's bytes, a layer's pixels - and + * that the re-import compares against: the watcher to skip a save that changed nothing, the matcher to + * recognize a renamed layer whose pixels did not change. One algorithm, named here and nowhere else: + * SHA-256 as lowercase hex, which is what the native format persists (docs/format/UMA.md §6.4). + * :storage's contentHashOfFile is the streaming form of the same digest for a file on disk. + */ + +/** + * The content hash of [bytes]. + * + * @param ByteArray bytes The bytes. + * @return String The digest as lowercase hex. + */ +fun contentHashOf(bytes: ByteArray): String = bytes.toByteString().sha256().hex() \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/Crc32.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/Crc32.kt new file mode 100644 index 0000000..fb09151 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/Crc32.kt @@ -0,0 +1,102 @@ +package org.umamo.format.binary + +/** + * The CRC-32 lookup table for the reflected IEEE 802.3 polynomial (0xEDB88320), built once. + * + * Each entry is the CRC of a single byte value, so the update loop is one table lookup per byte. + */ +private val CRC32_TABLE: IntArray = + IntArray(256) { tableIndex -> + var remainder = tableIndex + repeat(8) { + remainder = + if ((remainder and 1) != 0) { + (remainder ushr 1) xor 0xEDB88320.toInt() + } else { + remainder ushr 1 + } + } + remainder + } + +/** + * Eight chained CRC-32 tables for slicing-by-8, 256 entries each, laid end to end: table 0 is + * [CRC32_TABLE], and entry i of table k is the CRC of byte i followed by k zero bytes. Looking up + * each of eight input bytes in its own table and XOR-ing the results advances the checksum by eight + * bytes at once, with the eight lookups independent of each other instead of each waiting on the last. + */ +private val CRC32_SLICE_TABLES: IntArray = + IntArray(8 * 256).also { tables -> + CRC32_TABLE.copyInto(tables) + for (tableIndex in 1 until 8) { + for (byteValue in 0 until 256) { + val shorter = tables[(tableIndex - 1) * 256 + byteValue] + tables[tableIndex * 256 + byteValue] = (shorter ushr 8) xor CRC32_TABLE[shorter and 0xFF] + } + } + } + +/** + * CRC-32 (IEEE 802.3), the checksum PNG stamps on every chunk (PNG spec §5.3) and ZIP on every entry + * (APPNOTE.TXT 4.3.9) — hence a shared utility here rather than something a single codec owns. + * + * A pure-Kotlin equivalent of `java.util.zip.CRC32`, mirroring its shape (accumulate with [update], + * read with [value]) so the codecs that use it stay in commonMain and compile for every target. + */ +internal class Crc32 { + // The running remainder, pre-conditioned to all-ones per the standard. + private var remainder = -1 + + /** + * Folds every byte of [bytes] into the running checksum. + * + * @param ByteArray bytes The bytes to accumulate. + */ + fun update(bytes: ByteArray) { + update(bytes, 0, bytes.size) + } + + /** + * Folds [length] bytes of [bytes] starting at [offset] into the running checksum, so a caller can + * checksum a slice of a larger buffer without copying it out. + * + * @param ByteArray bytes The buffer holding the bytes. + * @param Int offset Offset of the first byte to accumulate. + * @param Int length Number of bytes to accumulate. + */ + fun update(bytes: ByteArray, offset: Int, length: Int) { + val tables = CRC32_SLICE_TABLES + val end = offset + length + var running = remainder + var byteIndex = offset + while (end - byteIndex >= 8) { + // The reflected CRC consumes bytes least-significant first, so the first four fold into the + // running remainder as a little-endian word; the oldest byte takes the longest table. + val firstWord = + (bytes[byteIndex].toInt() and 0xFF) or + ((bytes[byteIndex + 1].toInt() and 0xFF) shl 8) or + ((bytes[byteIndex + 2].toInt() and 0xFF) shl 16) or + ((bytes[byteIndex + 3].toInt() and 0xFF) shl 24) + val first = running xor firstWord + running = + tables[7 * 256 + (first and 0xFF)] xor + tables[6 * 256 + ((first ushr 8) and 0xFF)] xor + tables[5 * 256 + ((first ushr 16) and 0xFF)] xor + tables[4 * 256 + (first ushr 24)] xor + tables[3 * 256 + (bytes[byteIndex + 4].toInt() and 0xFF)] xor + tables[2 * 256 + (bytes[byteIndex + 5].toInt() and 0xFF)] xor + tables[256 + (bytes[byteIndex + 6].toInt() and 0xFF)] xor + tables[bytes[byteIndex + 7].toInt() and 0xFF] + byteIndex += 8 + } + while (byteIndex < end) { + running = CRC32_TABLE[(running xor bytes[byteIndex].toInt()) and 0xFF] xor (running ushr 8) + byteIndex++ + } + remainder = running + } + + /** The checksum of everything accumulated so far, as an unsigned 32-bit value. */ + val value: Long + get() = remainder.inv().toLong() and 0xFFFFFFFFL +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/Deflate.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/Deflate.kt new file mode 100644 index 0000000..2eadacf --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/Deflate.kt @@ -0,0 +1,186 @@ +package org.umamo.format.binary + +import okio.Buffer +import okio.BufferedSource +import okio.Deflater +import okio.DeflaterSink +import okio.IOException +import okio.Inflater +import okio.InflaterSource +import okio.Source +import okio.buffer + +/* + * DEFLATE for the raster codecs and the CMO3 CAFF container. + * + * Two framings, because the callers need both: + * - zlib (RFC 1950: 2-byte header + deflate + Adler-32) — PNG IDAT, TIFF Deflate, PSD ZIP + * channels, CLIP tiles. + * - raw deflate (no wrapper; zlib's windowBits = -15) — the payload of a ZIP entry, which is what + * the CAFF codec frames for CMO3's compressed blobs. + */ + +/** Asks zlib for its default (level 6), matching java.util.zip's DEFAULT_COMPRESSION. */ +private const val DEFAULT_COMPRESSION_LEVEL = -1 + +/** + * Inflates the zlib stream at [sourceOffset] into its decompressed bytes. + * + * Best-effort by design: a truncated or corrupt stream yields the bytes recovered so far rather than + * throwing, matching the other readers and letting a partly damaged image still decode. + * + * @param ByteArray source The buffer holding the zlib stream. + * @param Int sourceOffset Offset of the stream's first byte. + * @param Int sourceLength Compressed byte count. + * @param Int maximumSize An upper bound on the output, so a malformed stream cannot inflate without + * limit; pass the decompressed size the container states. + * @return ByteArray The inflated bytes. + */ +internal fun inflateZlib(source: ByteArray, sourceOffset: Int, sourceLength: Int, maximumSize: Int): ByteArray = + inflate(source, sourceOffset, sourceLength, maximumSize, rawDeflate = false) + +/** + * Inflates a raw (unwrapped) deflate stream — the payload of a ZIP entry. + * + * @param ByteArray source The buffer holding the deflate stream. + * @param Int sourceOffset Offset of the stream's first byte. + * @param Int sourceLength Compressed byte count. + * @param Int maximumSize An upper bound on the output. + * @return ByteArray The inflated bytes. + */ +internal fun inflateRawDeflate(source: ByteArray, sourceOffset: Int, sourceLength: Int, maximumSize: Int): ByteArray = + inflate(source, sourceOffset, sourceLength, maximumSize, rawDeflate = true) + +/** + * Compresses [source] to a zlib stream at the default compression level. + * + * @param ByteArray source The raw bytes to compress. + * @return ByteArray The zlib-wrapped deflate stream. + */ +internal fun deflateZlib(source: ByteArray): ByteArray = deflate(source, DEFAULT_COMPRESSION_LEVEL, rawDeflate = false) + +/** + * Compresses [source] to a raw (unwrapped) deflate stream, for embedding as a ZIP entry's payload. + * + * @param ByteArray source The raw bytes to compress. + * @param Int level The DEFLATE level (0..9). + * @return ByteArray The raw deflate stream. + */ +internal fun deflateRawDeflate(source: ByteArray, level: Int): ByteArray = deflate(source, level, rawDeflate = true) + +/** + * The shared inflate path. + * + * @param ByteArray source The buffer holding the stream. + * @param Int sourceOffset Offset of the stream's first byte. + * @param Int sourceLength Compressed byte count. + * @param Int maximumSize Upper bound on the output. + * @param Boolean rawDeflate True for an unwrapped stream (windowBits -15), false for zlib framing. + * @return ByteArray The inflated bytes, up to [maximumSize]. + */ +private fun inflate(source: ByteArray, sourceOffset: Int, sourceLength: Int, maximumSize: Int, rawDeflate: Boolean): ByteArray { + if (sourceLength <= 0 || sourceOffset >= source.size || maximumSize <= 0) { + return ByteArray(0) + } + val available = minOf(sourceLength, source.size - sourceOffset) + val compressed = Buffer().write(source, sourceOffset, available) + // A raw stream has no trailer, and zlib wants a byte of lookahead past the final block to notice + // it is finished; without it the inflater asks for more input at the very end and okio raises EOF. + // java.util.zip documents the same "extra dummy byte" requirement for its nowrap mode. + if (rawDeflate) { + compressed.writeByte(0) + } + val inflated = Buffer() + val inflaterSource = InflaterSource(compressed, Inflater(rawDeflate)) + try { + while (inflated.size < maximumSize) { + if (inflaterSource.read(inflated, maximumSize - inflated.size) == -1L) { + break + } + } + } catch (_: IOException) { + // Best-effort: return what inflated so far rather than failing the whole decode. + } finally { + // Releases the inflater. On a truncated stream close() can itself raise, which must not mask + // the bytes already recovered. + try { + inflaterSource.close() + } catch (_: IOException) { + // Already best-effort. + } + } + return inflated.readByteArray() +} + +/** + * A zlib stream inflated on demand, for a caller that consumes the output a piece at a time (PNG's + * scanlines) rather than holding all of it at once. + * + * Best-effort like [inflateZlib]: a truncated or corrupt stream ends early instead of throwing, and + * every read after that point delivers nothing. The caller bounds the output by how much it asks + * for, so a stream that would inflate past what its container describes is never expanded further. + * + * @param Source compressed The zlib stream. + */ +internal class ZlibStreamReader(compressed: Source) { + private val inflated: BufferedSource = InflaterSource(compressed, Inflater(false)).buffer() + + // Set once the stream has ended or broken; no read is attempted after that. + private var ended = false + + /** + * Fills [destination] from [offset] with the next [count] inflated bytes, or with as many as the + * stream still holds. + * + * @param ByteArray destination The buffer to fill. + * @param Int offset Offset of the first byte to write. + * @param Int count Number of bytes wanted. + * @return Int The number of bytes written: [count] unless the stream ended or broke first. + */ + fun readFully(destination: ByteArray, offset: Int, count: Int): Int { + var filled = 0 + while (filled < count && !ended) { + val read = + try { + inflated.read(destination, offset + filled, count - filled) + } catch (_: IOException) { + -1 + } + if (read == -1) { + ended = true + } else { + filled += read + } + } + return filled + } + + /** + * Releases the inflater. On a truncated stream close() can itself raise, which must not mask the + * bytes already delivered. + */ + fun close() { + try { + inflated.close() + } catch (_: IOException) { + // Already best-effort. + } + } +} + +/** + * The shared deflate path. + * + * @param ByteArray source The raw bytes to compress. + * @param Int level The DEFLATE level. + * @param Boolean rawDeflate True to omit the zlib wrapper. + * @return ByteArray The compressed stream. + */ +private fun deflate(source: ByteArray, level: Int, rawDeflate: Boolean): ByteArray { + val deflated = Buffer() + val sink = DeflaterSink(deflated, Deflater(level, rawDeflate)).buffer() + sink.write(source) + // Finishes the stream and releases the deflater. + sink.close() + return deflated.readByteArray() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipArchive.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipArchive.kt new file mode 100644 index 0000000..7361aa2 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipArchive.kt @@ -0,0 +1,579 @@ +package org.umamo.format.binary + +/* + * A strict reader for ordinary multi-entry ZIP archives, in commonMain so every target reads the same + * bytes the same way: the UMA container and the KRA reader both stand on it. + * + * Strict where the shared DEFLATE seam is deliberately lenient. inflateRawDeflate recovers what it can + * from a damaged stream, which suits a half-readable image; an archive entry instead has a declared size + * and CRC-32, and this reader holds every entry to both, so a truncated, corrupt, or lying archive fails + * loudly (docs/format/UMA.md §1). + */ + +/** + * A malformed or unsupported ZIP archive, or an entry whose bytes do not match what the archive declares. + * + * @param String message What was wrong, naming the entry when there is one. + */ +internal class ZipFormatException(message: String) : RuntimeException(message) + +/** + * One entry as the central directory declares it. + * + * @property String name The entry name, decoded as UTF-8. + * @property Int method The compression method (APPNOTE.TXT 4.4.5). + * @property Int flags The general purpose bit flags (APPNOTE.TXT 4.4.4). + * @property Long crc32 The CRC-32 of the uncompressed bytes, unsigned. + * @property Int compressedSize The payload's size on disk. + * @property Int uncompressedSize The entry's size once inflated. + * @property Int dosDateTime The MS-DOS modification stamp: date in the high 16 bits, time in the low 16. + * @property Int payloadOffset Where the payload starts in the archive's bytes. + * @property Int versionNeeded The "version needed to extract" (APPNOTE.TXT 4.4.3). + */ +internal class ZipEntry( + val name: String, + val method: Int, + val flags: Int, + val crc32: Long, + val compressedSize: Int, + val uncompressedSize: Int, + val dosDateTime: Int, + val payloadOffset: Int, + val versionNeeded: Int, +) { + /** True for a directory entry, which ZIP marks with a trailing slash (APPNOTE.TXT 4.4.17.1). */ + val isDirectory: Boolean + get() = name.endsWith('/') + + /** True when the entry is encrypted, which this reader cannot inflate. */ + val isEncrypted: Boolean + get() = (flags and ZipRecords.FLAG_ENCRYPTED) != 0 +} + +/** + * A parsed ZIP archive over its bytes: the central directory read eagerly, each entry's payload only on + * request. + * + * Lazy payloads are what copy-through needs - a writer can carry an entry it never inflates + * ([rawPayload]) - and what lets a caller read two entries of a large archive without inflating the rest. + * + * @property List entries Every entry, in central-directory order. + */ +internal class ZipArchive private constructor( + /** The whole archive, which every entry's payload offset indexes into. */ + val bytes: ByteArray, + val entries: List, +) { + private val entryByName: Map = entries.associateBy { entry -> entry.name } + + /** + * The entry named [name], or null when the archive has none. + * + * @param String name The entry name. + * @return ZipEntry? The entry. + */ + fun entry(name: String): ZipEntry? = entryByName[name] + + /** + * The entry's uncompressed bytes, verified against the sizes and CRC-32 the archive declares. + * + * The inflate is bounded one byte past the declared size, so an entry that would inflate further + * stops there and fails rather than allocating what it claims not to hold. + * + * @param ZipEntry entry An entry of this archive. + * @return ByteArray The uncompressed bytes. + * @throws ZipFormatException When the entry is encrypted, uses a method other than stored or DEFLATE, + * or its bytes do not match its declared size or CRC-32. + */ + fun contents(entry: ZipEntry): ByteArray = decodeZipPayload(entry, bytes, entry.payloadOffset) + + /** + * The entry's payload exactly as stored - compressed, and encrypted if it is - for copying into another + * archive without inflating it. + * + * @param ZipEntry entry An entry of this archive. + * @return ByteArray The payload bytes. + */ + fun rawPayload(entry: ZipEntry): ByteArray = bytes.copyOfRange(entry.payloadOffset, entry.payloadOffset + entry.compressedSize) + + companion object { + /** The largest size a ByteArray can hold on every target, and so the largest entry or archive read. */ + private const val MAXIMUM_ARRAY_SIZE = Int.MAX_VALUE - 8 + + /** + * Parses [bytes] as a ZIP archive: finds the end record, follows Zip64 records where the classic + * fields overflow, walks the central directory, and validates every entry's local header. + * + * @param ByteArray bytes The whole archive. + * @return ZipArchive The parsed archive; payloads are read on request. + * @throws ZipFormatException When the archive is truncated, malformed, split across disks, or holds + * two entries with the same name. + */ + fun read(bytes: ByteArray): ZipArchive { + val reader = ByteReader(bytes, littleEndian = true) + val directory = locateCentralDirectory(reader) + val entries = ArrayList(directory.entryCount) + val names = HashSet(directory.entryCount) + var position = directory.offset + val directoryEnd = directory.offset + directory.size + repeat(directory.entryCount) { entryIndex -> + val entry = readCentralEntry(reader, position, directoryEnd, directory.offset, entryIndex) + if (!names.add(entry.first.name)) { + throw ZipFormatException("the archive holds two entries named '${entry.first.name}'") + } + entries += entry.first + position = entry.second + } + if (position != directoryEnd) { + throw ZipFormatException("the central directory declares ${directory.size} bytes but its ${directory.entryCount} entries span ${position - directory.offset}") + } + return ZipArchive(bytes, entries) + } + + /** + * Where the central directory is and how many entries it holds. + * + * @property Int offset The directory's first byte. + * @property Int size The directory's length in bytes. + * @property Int entryCount The number of entries. + */ + private class CentralDirectory( + val offset: Int, + val size: Int, + val entryCount: Int, + ) + + /** + * Finds the end of central directory record and, through it, the central directory. + * + * The record has a variable-length comment, so it is found by scanning the tail of the file. A + * candidate counts only when its comment ends exactly at the end of the file and the directory it + * describes is really there. A comment can hold bytes that look like an end record, and one at the + * very end even satisfies the comment rule, so the EARLIEST valid candidate wins: the genuine record + * precedes any look-alike its own comment contains. The scan runs upward and stops at the first + * candidate that describes a directory, so a look-alike after the genuine record is never examined and + * cannot fail the read. + * + * @param ByteReader reader The archive, little-endian. + * @return CentralDirectory The directory's extent and entry count. + */ + private fun locateCentralDirectory(reader: ByteReader): CentralDirectory { + val size = reader.bytes.size + if (size < ZipRecords.END_SIZE) { + throw ZipFormatException("$size bytes is too short to be a ZIP archive") + } + val lowestCandidate = maxOf(0, size - ZipRecords.END_SIZE - ZipRecords.MAXIMUM_COMMENT_LENGTH) + // A candidate that declares Zip64 records the archive lacks is remembered rather than thrown: a + // look-alike may still be followed by the genuine record, but if nothing qualifies, its reason + // names the actual damage instead of the generic one. + var zip64Failure: String? = null + for (candidate in lowestCandidate..size - ZipRecords.END_SIZE) { + if (reader.u32(candidate) == ZipRecords.END_SIGNATURE.toLong() && + // ZIP: end record @ +0x14 comment length (APPNOTE.TXT 4.3.16). + candidate + ZipRecords.END_SIZE + reader.u16(candidate + 20) == size + ) { + when (val match = centralDirectoryFromEnd(reader, candidate)) { + is EndRecordMatch.Found -> return match.directory + is EndRecordMatch.Zip64Missing -> zip64Failure = match.reason + EndRecordMatch.LookAlike -> Unit + } + } + } + throw ZipFormatException(zip64Failure ?: "no end of central directory record: the archive is truncated or not a ZIP") + } + + /** What examining one end record candidate found. */ + private sealed interface EndRecordMatch { + /** + * The candidate is the genuine record and describes [directory]. + * + * @property CentralDirectory directory The directory it describes. + */ + class Found(val directory: CentralDirectory) : EndRecordMatch + + /** + * The candidate carries Zip64 sentinels but no Zip64 locator precedes it, so it describes nothing + * this archive holds; [reason] is what to report if no other candidate qualifies. + * + * @property String reason The failure to report. + */ + class Zip64Missing(val reason: String) : EndRecordMatch + + /** The candidate describes no directory this archive holds: bytes inside a comment. */ + object LookAlike : EndRecordMatch + } + + /** + * The central directory an end record describes, or why the candidate describes none: a look-alike + * inside a comment, or a Zip64 record whose locator is missing. + * + * @param ByteReader reader The archive, little-endian. + * @param Int endOffset The candidate end record's offset. + * @return EndRecordMatch The directory, or the kind of false candidate this is. + */ + private fun centralDirectoryFromEnd(reader: ByteReader, endOffset: Int): EndRecordMatch { + // ZIP: end of central directory record (APPNOTE.TXT 4.3.16) - @ +0x04 this disk, @ +0x06 the + // directory's disk, @ +0x08 entries on this disk, @ +0x0A total entries, @ +0x0C directory + // size, @ +0x10 directory offset. + val diskNumber = reader.u16(endOffset + 4) + val directoryDisk = reader.u16(endOffset + 6) + val entriesOnDisk = reader.u16(endOffset + 8) + val totalEntries = reader.u16(endOffset + 10) + val directorySize = reader.u32(endOffset + 12) + val directoryOffset = reader.u32(endOffset + 16) + + val usesZip64 = + entriesOnDisk == ZipRecords.UINT16_SENTINEL || + totalEntries == ZipRecords.UINT16_SENTINEL || + directorySize == ZipRecords.UINT32_SENTINEL || + directoryOffset == ZipRecords.UINT32_SENTINEL + val locatorOffset = endOffset - ZipRecords.ZIP64_LOCATOR_SIZE + val hasLocator = locatorOffset >= 0 && reader.u32(locatorOffset) == ZipRecords.ZIP64_LOCATOR_SIGNATURE.toLong() + + if (usesZip64 && hasLocator) { + return EndRecordMatch.Found(zip64CentralDirectory(reader, locatorOffset)) + } + // A sentinel offset or size points at nothing, so the classic checks below cannot pass; what the + // record says is that Zip64 records should precede it and do not. The caller decides whether + // that is the archive's fault or a look-alike's. + if (directorySize == ZipRecords.UINT32_SENTINEL || directoryOffset == ZipRecords.UINT32_SENTINEL) { + return EndRecordMatch.Zip64Missing("the end record declares Zip64 records, but no Zip64 locator precedes it") + } + // A classic count of exactly 0xFFFF with no Zip64 records is a legal classic archive, read as is. + if (diskNumber != 0 || directoryDisk != 0 || entriesOnDisk != totalEntries) { + // Only a genuine end record can be declared multi-disk; a look-alike is skipped instead. + return if (plausibleDirectory(reader, directoryOffset, directorySize, totalEntries.toLong(), endOffset)) { + throw ZipFormatException("multi-disk (split) archives are not supported") + } else { + EndRecordMatch.LookAlike + } + } + if (!plausibleDirectory(reader, directoryOffset, directorySize, totalEntries.toLong(), endOffset)) { + return EndRecordMatch.LookAlike + } + return EndRecordMatch.Found(CentralDirectory(directoryOffset.toInt(), directorySize.toInt(), totalEntries)) + } + + /** + * The central directory a Zip64 end record describes. + * + * @param ByteReader reader The archive, little-endian. + * @param Int locatorOffset The Zip64 end of central directory locator's offset. + * @return CentralDirectory The directory. + */ + private fun zip64CentralDirectory(reader: ByteReader, locatorOffset: Int): CentralDirectory { + // ZIP: Zip64 end of central directory locator (APPNOTE.TXT 4.3.15) - @ +0x04 the disk holding the + // Zip64 end record, @ +0x08 its offset, @ +0x10 the total disk count. + val recordDisk = reader.u32(locatorOffset + 4) + val recordOffset = u64AsOffset(reader, locatorOffset + 8, "Zip64 end record offset") + val totalDisks = reader.u32(locatorOffset + 16) + if (recordDisk != 0L || totalDisks > 1L) { + throw ZipFormatException("multi-disk (split) archives are not supported") + } + if (recordOffset > locatorOffset - ZipRecords.ZIP64_END_SIZE || reader.u32(recordOffset) != ZipRecords.ZIP64_END_SIGNATURE.toLong()) { + throw ZipFormatException("the Zip64 locator points at no Zip64 end record") + } + // ZIP: Zip64 end of central directory record (APPNOTE.TXT 4.3.14) - @ +0x10 this disk, @ +0x14 the + // directory's disk, @ +0x18 entries on this disk, @ +0x20 total entries, @ +0x28 directory size, + // @ +0x30 directory offset. + val diskNumber = reader.u32(recordOffset + 16) + val directoryDisk = reader.u32(recordOffset + 20) + val entriesOnDisk = u64AsOffset(reader, recordOffset + 24, "Zip64 entries on disk") + val totalEntries = u64AsOffset(reader, recordOffset + 32, "Zip64 total entries") + val directorySize = u64AsOffset(reader, recordOffset + 40, "Zip64 central directory size") + val directoryOffset = u64AsOffset(reader, recordOffset + 48, "Zip64 central directory offset") + if (diskNumber != 0L || directoryDisk != 0L || entriesOnDisk != totalEntries) { + throw ZipFormatException("multi-disk (split) archives are not supported") + } + if (!plausibleDirectory(reader, directoryOffset.toLong(), directorySize.toLong(), totalEntries.toLong(), recordOffset)) { + throw ZipFormatException("the Zip64 end record describes a central directory the archive does not hold") + } + return CentralDirectory(directoryOffset, directorySize, totalEntries) + } + + /** + * Whether a declared central directory fits before its end record and starts where it should. + * + * @param ByteReader reader The archive, little-endian. + * @param Long offset The declared directory offset. + * @param Long size The declared directory size. + * @param Long entryCount The declared entry count. + * @param Int limit The offset the directory must end at or before (its end record). + * @return Boolean True when the declaration is consistent with the bytes. + */ + private fun plausibleDirectory(reader: ByteReader, offset: Long, size: Long, entryCount: Long, limit: Int): Boolean { + if (offset < 0 || size < 0 || offset + size > limit) { + return false + } + // An empty directory has no header to check, so it must sit exactly where its end record starts. + if (entryCount == 0L) { + return size == 0L && offset == limit.toLong() + } + return size >= ZipRecords.CENTRAL_HEADER_SIZE && + entryCount * ZipRecords.CENTRAL_HEADER_SIZE <= size && + reader.u32(offset.toInt()) == ZipRecords.CENTRAL_HEADER_SIGNATURE.toLong() + } + + /** + * Reads one central directory file header and validates the local header it points at. + * + * @param ByteReader reader The archive, little-endian. + * @param Int position The central header's offset. + * @param Int directoryEnd The central directory's end, which the header must not cross. + * @param Int directoryOffset The central directory's start, which every payload must end before. + * @param Int entryIndex The entry's index, for error messages. + * @return Pair The entry and the offset of the next central header. + */ + private fun readCentralEntry(reader: ByteReader, position: Int, directoryEnd: Int, directoryOffset: Int, entryIndex: Int): Pair { + if (position + ZipRecords.CENTRAL_HEADER_SIZE > directoryEnd || reader.u32(position) != ZipRecords.CENTRAL_HEADER_SIGNATURE.toLong()) { + throw ZipFormatException("central directory entry $entryIndex is truncated or missing its signature") + } + // ZIP: central directory file header (APPNOTE.TXT 4.3.12) - @ +0x06 version needed, @ +0x08 flags, @ +0x0A method, + // @ +0x0C time, @ +0x0E date, @ +0x10 crc-32, @ +0x14 compressed size, @ +0x18 uncompressed size, + // @ +0x1C name length, @ +0x1E extra length, @ +0x20 comment length, @ +0x22 disk number start, + // @ +0x2A local header offset, @ +0x2E the name. + val versionNeeded = reader.u16(position + 6) + val flags = reader.u16(position + 8) + val method = reader.u16(position + 10) + val time = reader.u16(position + 12) + val date = reader.u16(position + 14) + val crc32 = reader.u32(position + 16) + var compressedSize = reader.u32(position + 20) + var uncompressedSize = reader.u32(position + 24) + val nameLength = reader.u16(position + 28) + val extraLength = reader.u16(position + 30) + val commentLength = reader.u16(position + 32) + var diskStart = reader.u16(position + 34).toLong() + var localOffset = reader.u32(position + 42) + val nameStart = position + ZipRecords.CENTRAL_HEADER_SIZE + val extraStart = nameStart + nameLength + val nextPosition = extraStart + extraLength + commentLength + if (nextPosition > directoryEnd) { + throw ZipFormatException("central directory entry $entryIndex runs past the end of the directory") + } + val name = decodeName(reader.bytes, nameStart, nameLength, entryIndex) + + // ZIP: Zip64 extended information extra field (APPNOTE.TXT 4.5.3) - present values follow in this + // order, each only when its classic field holds the sentinel. + var extraPosition = extraStart + val extraEnd = extraStart + extraLength + while (extraPosition + 4 <= extraEnd) { + val headerId = reader.u16(extraPosition) + val dataSize = reader.u16(extraPosition + 2) + val dataStart = extraPosition + 4 + if (dataStart + dataSize > extraEnd) { + throw ZipFormatException("entry '$name' has a truncated extra field") + } + if (headerId == ZipRecords.ZIP64_EXTRA_ID) { + var fieldPosition = dataStart + val dataEnd = dataStart + dataSize + + /** + * Reads the next 64-bit value of the Zip64 extra field. + * + * @param String what The field, for error messages. + * @return Long The value. + */ + fun nextValue(what: String): Long { + if (fieldPosition + 8 > dataEnd) { + throw ZipFormatException("entry '$name' has a Zip64 extra field too short for its $what") + } + return u64AsOffset(reader, fieldPosition, "entry '$name' $what").toLong().also { fieldPosition += 8 } + } + if (uncompressedSize == ZipRecords.UINT32_SENTINEL) { + uncompressedSize = nextValue("uncompressed size") + } + if (compressedSize == ZipRecords.UINT32_SENTINEL) { + compressedSize = nextValue("compressed size") + } + if (localOffset == ZipRecords.UINT32_SENTINEL) { + localOffset = nextValue("local header offset") + } + if (diskStart == ZipRecords.UINT16_SENTINEL.toLong()) { + if (fieldPosition + 4 > dataEnd) { + throw ZipFormatException("entry '$name' has a Zip64 extra field too short for its disk number") + } + diskStart = reader.u32(fieldPosition) + } + } + extraPosition = dataStart + dataSize + } + if (diskStart != 0L) { + throw ZipFormatException("entry '$name' starts on another disk: multi-disk archives are not supported") + } + if (uncompressedSize > MAXIMUM_ARRAY_SIZE - 1 || compressedSize > MAXIMUM_ARRAY_SIZE) { + throw ZipFormatException("entry '$name' is larger than a byte array can hold") + } + val payloadOffset = validateLocalHeader(reader, localOffset, name, nameStart, nameLength, method, directoryOffset) + if (payloadOffset.toLong() + compressedSize > directoryOffset) { + throw ZipFormatException("entry '$name' is truncated: its payload runs past the start of the central directory") + } + val entry = + ZipEntry( + name = name, + method = method, + flags = flags, + crc32 = crc32, + compressedSize = compressedSize.toInt(), + uncompressedSize = uncompressedSize.toInt(), + dosDateTime = (date shl 16) or time, + payloadOffset = payloadOffset, + versionNeeded = versionNeeded, + ) + return entry to nextPosition + } + + /** + * Validates the local file header an entry points at and returns where its payload starts. + * + * The payload offset comes from the LOCAL header's own name and extra lengths, which may differ from + * the central directory's copy (writers put different extra fields in each). + * + * @param ByteReader reader The archive, little-endian. + * @param Long localOffset The local header's declared offset. + * @param String name The entry's name, for error messages. + * @param Int nameStart Where the central header's name bytes start. + * @param Int nameLength The central header's name length. + * @param Int method The central header's compression method. + * @param Int directoryOffset The central directory's start. + * @return Int The payload's offset. + */ + private fun validateLocalHeader( + reader: ByteReader, + localOffset: Long, + name: String, + nameStart: Int, + nameLength: Int, + method: Int, + directoryOffset: Int, + ): Int { + if (localOffset < 0 || localOffset + ZipRecords.LOCAL_HEADER_SIZE > directoryOffset) { + throw ZipFormatException("entry '$name' points at a local header outside the archive's entry data") + } + val headerOffset = localOffset.toInt() + if (reader.u32(headerOffset) != ZipRecords.LOCAL_HEADER_SIGNATURE.toLong()) { + throw ZipFormatException("entry '$name' points at bytes that are not a local file header") + } + // ZIP: local file header (APPNOTE.TXT 4.3.7) - @ +0x08 method, @ +0x1A name length, @ +0x1C extra + // length, @ +0x1E the name. + val localMethod = reader.u16(headerOffset + 8) + val localNameLength = reader.u16(headerOffset + 26) + val localExtraLength = reader.u16(headerOffset + 28) + val localNameStart = headerOffset + ZipRecords.LOCAL_HEADER_SIZE + if (localNameStart + localNameLength + localExtraLength > directoryOffset) { + throw ZipFormatException("entry '$name' has a local header that runs into the central directory") + } + if (localMethod != method) { + throw ZipFormatException("entry '$name' declares method $method centrally but $localMethod locally") + } + if (localNameLength != nameLength || !reader.bytes.rangeEquals(localNameStart, reader.bytes, nameStart, nameLength)) { + throw ZipFormatException("entry '$name' has a local header naming a different entry") + } + return localNameStart + localNameLength + localExtraLength + } + + /** + * Decodes an entry name as UTF-8, the encoding the writer flags and the one java.util.zip assumes. + * + * @param ByteArray bytes The archive. + * @param Int start The name's first byte. + * @param Int length The name's length in bytes. + * @param Int entryIndex The entry's index, for error messages. + * @return String The name. + */ + private fun decodeName(bytes: ByteArray, start: Int, length: Int, entryIndex: Int): String = + try { + bytes.decodeToString(start, start + length, throwOnInvalidSequence = true) + } catch (_: CharacterCodingException) { + throw ZipFormatException("central directory entry $entryIndex has a name that is not valid UTF-8") + } + + /** + * Reads an unsigned little-endian 64-bit field that must fit a byte-array offset. + * + * @param ByteReader reader The archive, little-endian. + * @param Int at The field's offset. + * @param String what The field, for error messages. + * @return Int The value. + */ + private fun u64AsOffset(reader: ByteReader, at: Int, what: String): Int { + val high = reader.u32(at + 4) + val low = reader.u32(at) + if (high != 0L || low > MAXIMUM_ARRAY_SIZE) { + throw ZipFormatException("$what exceeds what a byte array can address") + } + return low.toInt() + } + } +} + +/** + * Whether [length] bytes of this array starting at [offset] equal those of [other] starting at [otherOffset]. + * + * @param Int offset The first byte compared here. + * @param ByteArray other The array compared against. + * @param Int otherOffset The first byte compared there. + * @param Int length How many bytes to compare. + * @return Boolean True when every byte matches. + */ +internal fun ByteArray.rangeEquals(offset: Int, other: ByteArray, otherOffset: Int, length: Int): Boolean { + for (byteIndex in 0 until length) { + if (this[offset + byteIndex] != other[otherOffset + byteIndex]) { + return false + } + } + return true +} + +/** + * An entry's uncompressed bytes from its payload wherever the payload is held - inside the archive it came + * from, or copied out of it - verified against the sizes and CRC-32 the entry declares. + * + * The inflate is bounded one byte past the declared size, so a payload that would inflate further stops there + * and fails rather than allocating what it claims not to hold. + * + * @param ZipEntry entry The entry as its archive declared it. + * @param ByteArray source The bytes holding the payload. + * @param Int payloadOffset Where the payload starts in [source]. + * @return ByteArray The uncompressed bytes. + * @throws ZipFormatException When the entry is encrypted, uses a method other than stored or DEFLATE, its + * payload does not fit [source], or its bytes do not match its declared size or CRC-32. + */ +internal fun decodeZipPayload(entry: ZipEntry, source: ByteArray, payloadOffset: Int): ByteArray { + if (entry.isEncrypted) { + throw ZipFormatException("entry '${entry.name}' is encrypted") + } + if (payloadOffset < 0 || payloadOffset.toLong() + entry.compressedSize > source.size) { + throw ZipFormatException("entry '${entry.name}' has a payload that does not fit its bytes") + } + val uncompressed = + when (entry.method) { + ZipRecords.METHOD_STORED -> { + if (entry.compressedSize != entry.uncompressedSize) { + throw ZipFormatException( + "stored entry '${entry.name}' declares ${entry.compressedSize} bytes on disk but ${entry.uncompressedSize} uncompressed", + ) + } + source.copyOfRange(payloadOffset, payloadOffset + entry.compressedSize) + } + + ZipRecords.METHOD_DEFLATED -> { + // One byte of headroom is how an entry that inflates past its declared size is caught + // without inflating the rest of it. + inflateRawDeflate(source, payloadOffset, entry.compressedSize, entry.uncompressedSize + 1) + } + + else -> throw ZipFormatException("entry '${entry.name}' uses unsupported compression method ${entry.method}") + } + if (uncompressed.size != entry.uncompressedSize) { + throw ZipFormatException( + "entry '${entry.name}' inflates to ${if (uncompressed.size > entry.uncompressedSize) "more than" else "only"} " + + "${minOf(uncompressed.size, entry.uncompressedSize)} bytes, but declares ${entry.uncompressedSize}", + ) + } + val checksum = Crc32().also { crc -> crc.update(uncompressed) }.value + if (checksum != entry.crc32) { + throw ZipFormatException("entry '${entry.name}' fails its CRC-32 check") + } + return uncompressed +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipRecords.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipRecords.kt new file mode 100644 index 0000000..76bac8f --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipRecords.kt @@ -0,0 +1,114 @@ +package org.umamo.format.binary + +/* + * The ZIP record layout shared by the codecs that frame ZIP data: the CAFF container's single-entry + * blobs (CaffZip) and ordinary multi-entry archives (ZipArchive, ZipWriter). Constants only - each + * codec keeps its own policy (which flags it sets, whether it writes a data descriptor, which clock it + * stamps). + * + * Citations are to PKWARE's APPNOTE.TXT: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT + */ + +/** + * ZIP record signatures, sizes, and field values, as APPNOTE.TXT defines them. Every multi-byte field + * on disk is little-endian. + */ +internal object ZipRecords { + // ZIP: local file header signature (APPNOTE.TXT 4.3.7). + const val LOCAL_HEADER_SIGNATURE = 0x04034B50 + + // ZIP: data descriptor signature (APPNOTE.TXT 4.3.9.3; optional on disk, and what CAFF writes). + const val DATA_DESCRIPTOR_SIGNATURE = 0x08074B50 + + // ZIP: central directory file header signature (APPNOTE.TXT 4.3.12). + const val CENTRAL_HEADER_SIGNATURE = 0x02014B50 + + // ZIP: Zip64 end of central directory record signature (APPNOTE.TXT 4.3.14). + const val ZIP64_END_SIGNATURE = 0x06064B50 + + // ZIP: Zip64 end of central directory locator signature (APPNOTE.TXT 4.3.15). + const val ZIP64_LOCATOR_SIGNATURE = 0x07064B50 + + // ZIP: end of central directory record signature (APPNOTE.TXT 4.3.16). + const val END_SIGNATURE = 0x06054B50 + + // ZIP: fixed sizes before each record's variable-length fields (APPNOTE.TXT 4.3.7, 4.3.12, 4.3.14, + // 4.3.15, 4.3.16, 4.3.9.3). + const val LOCAL_HEADER_SIZE = 30 + const val CENTRAL_HEADER_SIZE = 46 + const val ZIP64_END_SIZE = 56 + const val ZIP64_LOCATOR_SIZE = 20 + const val END_SIZE = 22 + const val DATA_DESCRIPTOR_SIZE = 16 + + // ZIP: the Zip64 end record's "size of zip64 end of central directory record" excludes its own + // leading 12 bytes (APPNOTE.TXT 4.3.14.1). + const val ZIP64_END_RECORD_REMAINDER = ZIP64_END_SIZE - 12 + + // ZIP: the end record's comment length is a 16-bit field (APPNOTE.TXT 4.3.16), which bounds how far + // before the end of the file the record can start. + const val MAXIMUM_COMMENT_LENGTH = 0xFFFF + + // ZIP: compression methods (APPNOTE.TXT 4.4.5) - 0 stored, 8 DEFLATE. + const val METHOD_STORED = 0 + const val METHOD_DEFLATED = 8 + + // ZIP: "version needed to extract" (APPNOTE.TXT 4.4.3.2) - 1.0 for a stored entry, 2.0 for DEFLATE, + // 4.5 for Zip64 records. + const val VERSION_STORED = 10 + const val VERSION_DEFLATED = 20 + const val VERSION_ZIP64 = 45 + + // ZIP: general purpose bit flags (APPNOTE.TXT 4.4.4) - bit 0 encrypted, bit 3 sizes and CRC in a + // trailing data descriptor, bit 11 the name is UTF-8. + const val FLAG_ENCRYPTED = 0x0001 + const val FLAG_DATA_DESCRIPTOR = 0x0008 + const val FLAG_UTF8_NAME = 0x0800 + + // ZIP: the Zip64 extended information extra field's header id (APPNOTE.TXT 4.5.3). + const val ZIP64_EXTRA_ID = 0x0001 + + // ZIP: a 16-bit count or 32-bit size/offset holding all ones means "see the Zip64 record" + // (APPNOTE.TXT 4.4.1.4). + const val UINT16_SENTINEL = 0xFFFF + const val UINT32_SENTINEL = 0xFFFFFFFFL + + // MS-DOS timestamp bounds (APPNOTE.TXT 4.4.6). The date packs year-1980 into 7 bits, so the epoch is + // 1980 and the ceiling is 2107; a clock outside that range is clamped rather than allowed to wrap into + // a different year. + private const val DOS_EPOCH_YEAR = 1980 + private const val DOS_MAXIMUM_YEAR = 2107 + + // MS-DOS 1980-01-01 00:00 - the clamp floor, and what an out-of-range clock falls back to. + private const val DOS_EPOCH_DATE = 0x0021 + private const val DOS_EPOCH_TIME = 0x0000 + + /** MS-DOS 1980-01-01 00:00 as a packed stamp: the earliest instant a ZIP header can record. */ + const val DOS_EPOCH_DATE_TIME = (DOS_EPOCH_DATE shl 16) or DOS_EPOCH_TIME + + /** + * Packs a local date and time into the MS-DOS format ZIP headers use. + * + * Date: year-1980 in bits 15..9, month in 8..5, day in 4..0. Time: hour in 15..11, minute in + * 10..5, and seconds HALVED into 4..0 - which is why a DOS stamp has two-second resolution. + * + * A year outside 1980..2107 cannot be expressed in the 7 bits available, so it clamps to the epoch + * rather than wrapping into a wrong-but-plausible year. + * + * @param Int year Local year. + * @param Int month Local month, 1..12. + * @param Int day Local day of month, 1..31. + * @param Int hour Local hour, 0..23. + * @param Int minute Local minute, 0..59. + * @param Int second Local second, 0..59. + * @return Int The stamp: date in the high 16 bits, time in the low 16. + */ + fun dosDateTimeOf(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Int { + if (year < DOS_EPOCH_YEAR || year > DOS_MAXIMUM_YEAR) { + return DOS_EPOCH_DATE_TIME + } + val date = ((year - DOS_EPOCH_YEAR) shl 9) or (month shl 5) or day + val time = (hour shl 11) or (minute shl 5) or (second / 2) + return (date shl 16) or time + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipWriter.kt b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipWriter.kt new file mode 100644 index 0000000..ffc7105 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/binary/ZipWriter.kt @@ -0,0 +1,315 @@ +package org.umamo.format.binary + +import okio.Buffer + +/** + * Builds an ordinary multi-entry ZIP archive in memory, in insertion order. + * + * Every entry's sizes and CRC-32 are known before it is written, so each local header carries them and + * no data descriptor follows. No extra fields are written, which is what fixes a first stored entry's + * payload at offset 30 plus its name length - the UMA mimetype probe relies on it (docs/format/UMA.md §1). + * Output is a pure function of the entries added and [dosDateTime]: no wall clock, no host attributes. + * + * @param Int dosDateTime The MS-DOS modification stamp every entry carries: date in the high 16 bits, + * time in the low 16 (see ZipRecords.dosDateTimeOf). A parameter rather than a clock read, so the + * caller decides whether archives are byte-reproducible. + */ +internal class ZipWriter(private val dosDateTime: Int) { + /** + * What the central directory needs to repeat about one written entry. + * + * @property ByteArray nameBytes The UTF-8 name. + * @property Int versionNeeded The "version needed to extract". + * @property Int flags The general purpose bit flags. + * @property Int method The compression method. + * @property Long crc32 The CRC-32 of the uncompressed bytes. + * @property Int compressedSize The payload's size. + * @property Int uncompressedSize The uncompressed size. + * @property Int dosDateTime The MS-DOS modification stamp the entry carries. + * @property Long localHeaderOffset Where the entry's local header starts. + */ + private class WrittenEntry( + val nameBytes: ByteArray, + val versionNeeded: Int, + val flags: Int, + val method: Int, + val crc32: Long, + val compressedSize: Int, + val uncompressedSize: Int, + val dosDateTime: Int, + val localHeaderOffset: Long, + ) + + private val output = Buffer() + private val writtenEntries = ArrayList() + private val writtenNames = HashSet() + private var finished = false + + /** + * Adds an entry stored without compression. + * + * @param String name The entry name; a trailing slash makes it a directory entry. + * @param ByteArray contents The entry's bytes. + */ + fun addStored(name: String, contents: ByteArray) { + writeEntry( + name = name, + method = ZipRecords.METHOD_STORED, + flags = ZipRecords.FLAG_UTF8_NAME, + crc32 = crc32Of(contents), + uncompressedSize = contents.size, + payload = contents, + ) + } + + /** + * Adds an entry compressed with DEFLATE. + * + * @param String name The entry name. + * @param ByteArray contents The entry's uncompressed bytes. + * @param Int level The DEFLATE level, 0..9. + */ + fun addDeflated(name: String, contents: ByteArray, level: Int = DEFAULT_DEFLATE_LEVEL) { + require(level in 0..9) { "DEFLATE level must be in 0..9: $level" } + writeEntry( + name = name, + method = ZipRecords.METHOD_DEFLATED, + flags = ZipRecords.FLAG_UTF8_NAME, + crc32 = crc32Of(contents), + uncompressedSize = contents.size, + payload = deflateRawDeflate(contents, level), + ) + } + + /** + * Adds an entry copied from another archive without inflating or recompressing it: the method, CRC-32, + * sizes, encryption flag, version needed, and payload bytes carry over verbatim. The name and timestamp are + * this writer's, like every other entry, except where a decryption check depends on them (see below). + * + * An encrypted entry whose source used a data descriptor keeps it, and keeps its source's timestamp: traditional + * PKWARE decryption checks the last byte of the encryption header against the timestamp's high byte when flag + * bit 3 is set, and against the CRC-32's high byte otherwise (APPNOTE.TXT 6.1.6), so changing either would make + * the entry undecryptable. + * + * @param ZipEntry entry The source entry, as its archive declares it. + * @param ByteArray rawPayload The source entry's payload exactly as stored (ZipArchive.rawPayload). + */ + fun addRaw(entry: ZipEntry, rawPayload: ByteArray) { + require(rawPayload.size == entry.compressedSize) { + "entry '${entry.name}' declares ${entry.compressedSize} payload bytes but ${rawPayload.size} were given" + } + addRaw(entry, rawPayload, 0) + } + + /** + * Adds an entry copied from another archive, its payload read in place from [source] at [payloadOffset] rather + * than from a copy; see the overload taking the payload alone. + * + * @param ZipEntry entry The source entry, as its archive declares it. + * @param ByteArray source The bytes holding the payload: the source archive, or a copy of the payload. + * @param Int payloadOffset Where the payload starts in [source]. + */ + fun addRaw(entry: ZipEntry, source: ByteArray, payloadOffset: Int) { + require(payloadOffset >= 0 && payloadOffset.toLong() + entry.compressedSize <= source.size) { + "entry '${entry.name}' declares ${entry.compressedSize} payload bytes, which its source does not hold at $payloadOffset" + } + val keepsDescriptor = entry.isEncrypted && (entry.flags and ZipRecords.FLAG_DATA_DESCRIPTOR) != 0 + // Every other copied entry's sizes sit in its local header, so a data descriptor flag from its source would send + // a reader looking for a record that is not there. + val flags = if (keepsDescriptor) entry.flags or ZipRecords.FLAG_UTF8_NAME else (entry.flags and ZipRecords.FLAG_DATA_DESCRIPTOR.inv()) or ZipRecords.FLAG_UTF8_NAME + writeEntry( + name = entry.name, + method = entry.method, + flags = flags, + crc32 = entry.crc32, + uncompressedSize = entry.uncompressedSize, + payload = source, + payloadOffset = payloadOffset, + payloadSize = entry.compressedSize, + sourceVersionNeeded = entry.versionNeeded, + entryDosDateTime = if (keepsDescriptor) entry.dosDateTime else dosDateTime, + writesDescriptor = keepsDescriptor, + ) + } + + /** + * Writes the central directory and the end records and returns the archive. The writer takes no + * entries afterward. + * + * Zip64 end records are added only when the entry count reaches 0xFFFF, where the classic 16-bit count + * field runs out (its all-ones value is reserved to mean "see Zip64"). Sizes and offsets cannot + * overflow their 32-bit fields: the archive is a byte array, so it is under 2 GiB by construction. + * + * @return ByteArray The archive. + */ + fun finish(): ByteArray { + check(!finished) { "the archive has already been finished" } + finished = true + val directoryOffset = output.size + for (entry in writtenEntries) { + writeCentralHeader(entry) + } + val directorySize = output.size - directoryOffset + val entryCount = writtenEntries.size + val needsZip64 = entryCount >= ZipRecords.UINT16_SENTINEL + if (needsZip64) { + val zip64EndOffset = output.size + // ZIP: Zip64 end of central directory record (APPNOTE.TXT 4.3.14). + output.writeIntLe(ZipRecords.ZIP64_END_SIGNATURE) + output.writeLongLe(ZipRecords.ZIP64_END_RECORD_REMAINDER.toLong()) + output.writeShortLe(ZipRecords.VERSION_ZIP64) + output.writeShortLe(ZipRecords.VERSION_ZIP64) + output.writeIntLe(0) + output.writeIntLe(0) + output.writeLongLe(entryCount.toLong()) + output.writeLongLe(entryCount.toLong()) + output.writeLongLe(directorySize) + output.writeLongLe(directoryOffset) + // ZIP: Zip64 end of central directory locator (APPNOTE.TXT 4.3.15). + output.writeIntLe(ZipRecords.ZIP64_LOCATOR_SIGNATURE) + output.writeIntLe(0) + output.writeLongLe(zip64EndOffset) + output.writeIntLe(1) + } + val classicCount = if (needsZip64) ZipRecords.UINT16_SENTINEL else entryCount + // ZIP: end of central directory record (APPNOTE.TXT 4.3.16). + output.writeIntLe(ZipRecords.END_SIGNATURE) + output.writeShortLe(0) + output.writeShortLe(0) + output.writeShortLe(classicCount) + output.writeShortLe(classicCount) + output.writeIntLe(directorySize.toInt()) + output.writeIntLe(directoryOffset.toInt()) + output.writeShortLe(0) + check(output.size <= MAXIMUM_ARCHIVE_SIZE) { "the archive exceeds what a byte array can hold: ${output.size} bytes" } + return output.readByteArray() + } + + /** + * Writes one entry's local header and payload, and records what its central header will repeat. Every check runs + * before anything is written or the name is taken, so a refused entry leaves the writer as it was. + * + * @param String name The entry name. + * @param Int method The compression method. + * @param Int flags The general purpose bit flags. + * @param Long crc32 The CRC-32 of the uncompressed bytes. + * @param Int uncompressedSize The uncompressed size. + * @param ByteArray payload The bytes holding the payload. + * @param Int payloadOffset Where the payload starts in [payload]. + * @param Int payloadSize The payload's length. + * @param Int sourceVersionNeeded The version needed a copied entry's source declared, or 0. + * @param Int entryDosDateTime The MS-DOS stamp the entry carries. + * @param Boolean writesDescriptor Whether the local header leaves the CRC-32 and sizes zero for a data + * descriptor after the payload (flag bit 3). + */ + private fun writeEntry( + name: String, + method: Int, + flags: Int, + crc32: Long, + uncompressedSize: Int, + payload: ByteArray, + payloadOffset: Int = 0, + payloadSize: Int = payload.size, + sourceVersionNeeded: Int = 0, + entryDosDateTime: Int = dosDateTime, + writesDescriptor: Boolean = false, + ) { + check(!finished) { "the archive has already been finished" } + require(name.isNotEmpty()) { "an entry name cannot be empty" } + require(name !in writtenNames) { "the archive already holds an entry named '$name'" } + val nameBytes = name.encodeToByteArray() + require(nameBytes.size <= 0xFFFF) { "entry name '$name' is longer than a ZIP header can hold" } + val descriptorSize = if (writesDescriptor) ZipRecords.DATA_DESCRIPTOR_SIZE else 0 + val projectedSize = output.size + ZipRecords.LOCAL_HEADER_SIZE + nameBytes.size + payloadSize + descriptorSize + check(projectedSize <= MAXIMUM_ARCHIVE_SIZE) { "the archive would exceed what a byte array can hold: $projectedSize bytes" } + writtenNames += name + // ZIP: version needed to extract (APPNOTE.TXT 4.4.3) - what this entry's method needs, or what a copied entry's + // source declared when that is more (an AES or other entry this writer never produces itself). + val methodVersion = if (method == ZipRecords.METHOD_STORED) ZipRecords.VERSION_STORED else ZipRecords.VERSION_DEFLATED + val entry = + WrittenEntry( + nameBytes = nameBytes, + versionNeeded = maxOf(methodVersion, sourceVersionNeeded), + flags = flags, + method = method, + crc32 = crc32, + compressedSize = payloadSize, + uncompressedSize = uncompressedSize, + dosDateTime = entryDosDateTime, + localHeaderOffset = output.size, + ) + // ZIP: local file header (APPNOTE.TXT 4.3.7). + output.writeIntLe(ZipRecords.LOCAL_HEADER_SIGNATURE) + output.writeShortLe(entry.versionNeeded) + output.writeShortLe(entry.flags) + output.writeShortLe(entry.method) + // ZIP: @ +0x0A time, @ +0x0C date. + output.writeShortLe(entry.dosDateTime and 0xFFFF) + output.writeShortLe((entry.dosDateTime ushr 16) and 0xFFFF) + // ZIP: @ +0x0E crc-32, @ +0x12 compressed size, @ +0x16 uncompressed size - zero when a data descriptor carries + // them (APPNOTE.TXT 4.4.4). + output.writeIntLe(if (writesDescriptor) 0 else entry.crc32.toInt()) + output.writeIntLe(if (writesDescriptor) 0 else entry.compressedSize) + output.writeIntLe(if (writesDescriptor) 0 else entry.uncompressedSize) + output.writeShortLe(nameBytes.size) + output.writeShortLe(0) + output.write(nameBytes) + output.write(payload, payloadOffset, payloadSize) + if (writesDescriptor) { + // ZIP: data descriptor (APPNOTE.TXT 4.3.9), with its optional signature. + output.writeIntLe(ZipRecords.DATA_DESCRIPTOR_SIGNATURE) + output.writeIntLe(entry.crc32.toInt()) + output.writeIntLe(entry.compressedSize) + output.writeIntLe(entry.uncompressedSize) + } + writtenEntries += entry + } + + /** + * Writes one entry's central directory file header. + * + * @param WrittenEntry entry The entry. + */ + private fun writeCentralHeader(entry: WrittenEntry) { + // ZIP: central directory file header (APPNOTE.TXT 4.3.12). "Version made by" is 2.0 on an MS-DOS + // host with zero attributes, so nothing about the machine that wrote the archive leaks into it. + output.writeIntLe(ZipRecords.CENTRAL_HEADER_SIGNATURE) + output.writeShortLe(ZipRecords.VERSION_DEFLATED) + output.writeShortLe(entry.versionNeeded) + output.writeShortLe(entry.flags) + output.writeShortLe(entry.method) + output.writeShortLe(entry.dosDateTime and 0xFFFF) + output.writeShortLe((entry.dosDateTime ushr 16) and 0xFFFF) + output.writeIntLe(entry.crc32.toInt()) + output.writeIntLe(entry.compressedSize) + output.writeIntLe(entry.uncompressedSize) + output.writeShortLe(entry.nameBytes.size) + // ZIP: @ +0x1E extra length, @ +0x20 comment length, @ +0x22 disk number start, @ +0x24 internal + // attributes - all zero. + output.writeShortLe(0) + output.writeShortLe(0) + output.writeShortLe(0) + output.writeShortLe(0) + // ZIP: @ +0x26 external attributes, zero. + output.writeIntLe(0) + output.writeIntLe(entry.localHeaderOffset.toInt()) + output.write(entry.nameBytes) + } + + private companion object { + /** zlib's default level, spelled out so the writer's output never depends on a library default. */ + const val DEFAULT_DEFLATE_LEVEL = 6 + + /** The largest archive a ByteArray can hold on every target. */ + const val MAXIMUM_ARCHIVE_SIZE = Int.MAX_VALUE - 8L + + /** + * The CRC-32 of [bytes]. + * + * @param ByteArray bytes The bytes. + * @return Long The checksum, unsigned. + */ + fun crc32Of(bytes: ByteArray): Long = Crc32().also { crc -> crc.update(bytes) }.value + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/bmp/BmpCodec.kt b/module/format/src/commonMain/kotlin/org/umamo/format/bmp/BmpCodec.kt new file mode 100644 index 0000000..263b58f --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/bmp/BmpCodec.kt @@ -0,0 +1,262 @@ +package org.umamo.format.bmp + +import okio.Buffer +import org.umamo.format.FileKind +import org.umamo.format.raster.RasterCodec +import org.umamo.format.raster.RasterImage + +/** + * Pure-Kotlin BMP codec (desktop JVM and Android), read and write. + * + * Reads uncompressed Windows BMPs - 24-bit BGR and 32-bit BGRA (BI_RGB), and 16/32-bit + * BI_BITFIELDS with explicit channel masks - into the neutral straight-alpha RGBA8888 top-first + * [RasterImage]. Writes a 32-bit BITMAPV4HEADER file with explicit RGBA channel masks so straight + * alpha round-trips losslessly. Palette (<= 8-bit) and RLE BMPs are out of scope and rejected. + * Trivial and dependency-free, so it doubles as a debug-dump and round-trip test vehicle. + */ +public object BmpCodec : RasterCodec { + override val kind: FileKind = FileKind.Bmp + + // BMP: compression codes (wingdi.h BI_*). + private const val BI_RGB = 0 + private const val BI_BITFIELDS = 3 + private const val BI_ALPHABITFIELDS = 6 + + private const val FILE_HEADER_SIZE = 14 + private const val V4_HEADER_SIZE = 108 + + private const val OPAQUE = 0xFF.toByte() + + /** + * True if [candidateBytes] opens with the "BM" signature. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the BMP magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean = + // BMP: BITMAPFILEHEADER.bfType @ +0x00 = 'B','M'. + candidateBytes.size >= 2 && candidateBytes[0] == 0x42.toByte() && candidateBytes[1] == 0x4D.toByte() + + /** + * Decodes a `.bmp` into a straight-alpha RGBA8888 [RasterImage], top row first. + * + * @param ByteArray bytes The complete `.bmp` file. + * @return RasterImage The decoded image. + */ + override fun read(bytes: ByteArray): RasterImage { + require(matches(bytes)) { "Not a BMP (bad signature)" } + require(bytes.size >= FILE_HEADER_SIZE + 40) { "BMP too short for a DIB header" } + + // BMP: BITMAPFILEHEADER.bfOffBits @ +0x0A - offset of the pixel array. + val pixelOffset = readU32LE(bytes, 10).toInt() + // BMP: BITMAPINFOHEADER @ +0x0E - biSize, biWidth, biHeight, biPlanes, biBitCount, biCompression. + val dibStart = FILE_HEADER_SIZE + val dibSize = readU32LE(bytes, dibStart).toInt() + require(dibSize >= 40) { "Insupported BMP DIB header size $dibSize (Need BITMAPINFOHEADER or later)" } + + val width = readI32LE(bytes, dibStart + 4) + val rawHeight = readI32LE(bytes, dibStart + 8) + val bitCount = readU16LE(bytes, dibStart + 14) + val compression = readU32LE(bytes, dibStart + 16).toInt() + require(width > 0 && rawHeight != 0) { "BMP has non-positive width or zero height" } + val height = kotlin.math.abs(rawHeight) + val topDown = rawHeight < 0 // BMP: a negative biHeight means the rows are stored top-to-bottom. + require(bitCount == 16 || bitCount == 24 || bitCount == 32) { + "Unsupported BMP bit count $bitCount (only uncompressed 16/24/32-bit; palette/RLE rejected)" + } + require(compression == BI_RGB || compression == BI_BITFIELDS || compression == BI_ALPHABITFIELDS) { + "Unsupported BMP compression $compression (only BI_RGB / BI_BITFIELDS)" + } + + val masks = resolveMasks(bytes, dibStart, dibSize, bitCount, compression) + + val rowStride = ((bitCount * width + 31) / 32) * 4 + val rgba = ByteArray(width * height * 4) + for (fileRow in 0 until height) { + val rowStart = pixelOffset + fileRow * rowStride + // Bottom-up storage (positive height) puts file row 0 at the image bottom; flip to top-first. + val imageRow = if (topDown) fileRow else (height - 1 - fileRow) + for (column in 0 until width) { + val destination = (imageRow * width + column) * 4 + when (bitCount) { + 24 -> { + // BMP: 24-bit BI_RGB pixels are stored B, G, R (no alpha). + val pixel = rowStart + column * 3 + if (pixel + 2 < bytes.size) { + rgba[destination] = bytes[pixel + 2] + rgba[destination + 1] = bytes[pixel + 1] + rgba[destination + 2] = bytes[pixel] + } + rgba[destination + 3] = OPAQUE + } + + else -> { + val pixel = rowStart + column * (bitCount / 8) + val value = + if (bitCount == 32) { + if (pixel + 3 < bytes.size) readU32LE(bytes, pixel).toInt() else 0 + } else { + if (pixel + 1 < bytes.size) readU16LE(bytes, pixel) else 0 + } + rgba[destination] = extractChannel(value, masks.red).toByte() + rgba[destination + 1] = extractChannel(value, masks.green).toByte() + rgba[destination + 2] = extractChannel(value, masks.blue).toByte() + rgba[destination + 3] = if (masks.alpha == 0) OPAQUE else extractChannel(value, masks.alpha).toByte() + } + } + } + } + return RasterImage(width, height, rgba) + } + + /** + * Encodes a [RasterImage] as a 32-bit BGRA BMP with a BITMAPV4HEADER carrying explicit channel + * masks (including alpha), stored bottom-up. Straight alpha round-trips losslessly. + * + * @param RasterImage model The image to encode. + * @return ByteArray The complete `.bmp` file. + */ + override fun write(model: RasterImage): ByteArray { + val rowStride = model.width * 4 // 32-bit rows are already 4-byte aligned. + val pixelDataSize = rowStride * model.height + val pixelOffset = FILE_HEADER_SIZE + V4_HEADER_SIZE + val fileSize = pixelOffset + pixelDataSize + + val out = Buffer() + // BITMAPFILEHEADER. + out.writeByte(0x42) + out.writeByte(0x4D) + out.writeIntLe(fileSize) + out.writeShortLe(0) // bfReserved1 + out.writeShortLe(0) // bfReserved2 + out.writeIntLe(pixelOffset) // bfOffBits + + // BITMAPV4HEADER. + out.writeIntLe(V4_HEADER_SIZE) + out.writeIntLe(model.width) + out.writeIntLe(model.height) // positive: bottom-up + out.writeShortLe(1) // planes + out.writeShortLe(32) // bitCount + out.writeIntLe(BI_BITFIELDS) + out.writeIntLe(pixelDataSize) + out.writeIntLe(2835) // xPelsPerMeter (~72 DPI) + out.writeIntLe(2835) // yPelsPerMeter + out.writeIntLe(0) // clrUsed + out.writeIntLe(0) // clrImportant + out.writeIntLe(0x00FF0000) // redMask + out.writeIntLe(0x0000FF00) // greenMask + out.writeIntLe(0x000000FF) // blueMask + out.writeIntLe(-0x1000000) // alphaMask 0xFF000000 + out.writeIntLe(0x73524742) // CSType 'sRGB' + repeat(9) { out.writeIntLe(0) } // CIEXYZTRIPLE endpoints (ignored for BI_BITFIELDS) + out.writeIntLe(0) // gammaRed + out.writeIntLe(0) // gammaGreen + out.writeIntLe(0) // gammaBlue + + // Pixel array, bottom-up: file row 0 is the image's bottom row. Each pixel is B, G, R, A. + for (fileRow in 0 until model.height) { + val imageRow = model.height - 1 - fileRow + var source = imageRow * rowStride + for (column in 0 until model.width) { + out.writeByte(model.rgba[source + 2].toInt() and 0xFF) // B + out.writeByte(model.rgba[source + 1].toInt() and 0xFF) // G + out.writeByte(model.rgba[source].toInt() and 0xFF) // R + out.writeByte(model.rgba[source + 3].toInt() and 0xFF) // A + source += 4 + } + } + return out.readByteArray() + } + + /** The four channel bit-masks a BI_BITFIELDS (or defaulted BI_RGB) BMP uses. */ + private class ChannelMasks(val red: Int, val green: Int, val blue: Int, val alpha: Int) + + /** + * Resolves the per-channel bit masks: explicit ones for BI_BITFIELDS (from the V4+ header, or the + * DWORDs after a 40-byte BITMAPINFOHEADER), else the format defaults for BI_RGB. + * + * @param ByteArray bytes The complete file. + * @param Int dibStart Offset of the DIB header. + * @param Int dibSize DIB header size in bytes. + * @param Int bitCount Bits per pixel (16 or 32 here). + * @param Int compression The BMP compression code. + * @return ChannelMasks The resolved masks (alpha = 0 means "no alpha, treat as opaque"). + */ + private fun resolveMasks(bytes: ByteArray, dibStart: Int, dibSize: Int, bitCount: Int, compression: Int): ChannelMasks { + if (compression == BI_BITFIELDS || compression == BI_ALPHABITFIELDS) { + // The masks sit at the same place either way: inside a V4/V5 header at +40, or as the DWORDs + // immediately following a bare 40-byte BITMAPINFOHEADER (which bfOffBits skips past). + val maskBase = dibStart + 40 + val red = readU32LE(bytes, maskBase).toInt() + val green = readU32LE(bytes, maskBase + 4).toInt() + val blue = readU32LE(bytes, maskBase + 8).toInt() + val alpha = + if (compression == BI_ALPHABITFIELDS || dibSize >= 56) { + readU32LE(bytes, maskBase + 12).toInt() + } else { + 0 + } + return ChannelMasks(red, green, blue, alpha) + } + // BI_RGB defaults: 32-bit is X8R8G8B8 (alpha unused → opaque); 16-bit is X1R5G5B5. + return if (bitCount == 32) { + ChannelMasks(0x00FF0000, 0x0000FF00, 0x000000FF, 0) + } else { + ChannelMasks(0x7C00, 0x03E0, 0x001F, 0) + } + } + + /** + * Extracts one channel from a packed pixel value via its mask, scaled to 8 bits. + * + * @param Int value The packed little-endian pixel value. + * @param Int mask The channel bit mask (0 → returns 255, the opaque default for a missing channel). + * @return Int The channel value in 0..255. + */ + private fun extractChannel(value: Int, mask: Int): Int { + if (mask == 0) { + return 0xFF + } + val shift = mask.countTrailingZeroBits() + val bits = mask.countOneBits() + val raw = (value ushr shift) and ((1 shl bits) - 1) + val maxValue = (1 shl bits) - 1 + return if (bits == 8) raw else (raw * 255 + maxValue / 2) / maxValue + } + + /** + * Reads a little-endian unsigned 16-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the least-significant byte. + * @return Int The value in 0..65535. + */ + private fun readU16LE(bytes: ByteArray, at: Int): Int = + (bytes[at].toInt() and 0xFF) or ((bytes[at + 1].toInt() and 0xFF) shl 8) + + /** + * Reads a little-endian unsigned 32-bit value as a Long. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the least-significant byte. + * @return Long The value in 0..4294967295. + */ + private fun readU32LE(bytes: ByteArray, at: Int): Long = + (bytes[at].toLong() and 0xFF) or + ((bytes[at + 1].toLong() and 0xFF) shl 8) or + ((bytes[at + 2].toLong() and 0xFF) shl 16) or + ((bytes[at + 3].toLong() and 0xFF) shl 24) + + /** + * Reads a little-endian signed 32-bit value (BMP width/height are signed). + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the least-significant byte. + * @return Int The signed value. + */ + private fun readI32LE(bytes: ByteArray, at: Int): Int = + (bytes[at].toInt() and 0xFF) or + ((bytes[at + 1].toInt() and 0xFF) shl 8) or + ((bytes[at + 2].toInt() and 0xFF) shl 16) or + ((bytes[at + 3].toInt() and 0xFF) shl 24) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipBlend.kt b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipBlend.kt new file mode 100644 index 0000000..d313b64 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipBlend.kt @@ -0,0 +1,55 @@ +package org.umamo.format.clip + +import org.umamo.format.art.LayerBlend + +/** + * Maps a CLIP `Layer.LayerComposite` blend-mode code to the neutral [LayerBlend]. + * + * EN: The complete enum was reverse-engineered from LayerBlendModes.clip (one layer per mode, named + * after the Clip Studio Paint UI label). Codes are contiguous 0..26, then 36 for Divide; the + * 27..35 gap is unused for leaf layers. Code 30 was observed only on folders in one sample + * and is the folder pass-through composite, not a leaf blend mode - it is not represented here + * (folders are not emitted as layers). Truly unknown codes degrade to Normal. + * JA: LayerComposite コードを中立 LayerBlend へ写像する. LayerBlendModes.clip から全列挙を判明. + */ +object ClipBlend { + /** + * Returns the neutral blend mode for a LayerComposite code, defaulting unknown codes to Normal. + * + * @param Long compositeCode The raw Layer.LayerComposite value. + * @return LayerBlend The mapped blend mode (Normal for any unrecognized code). + */ + fun fromCompositeCode(compositeCode: Long): LayerBlend = + // CLIP: Layer.LayerComposite - verified code table (see LayerBlendModes.clip / docs/CLIP.md §3). + when (compositeCode) { + 0L -> LayerBlend.Normal + 1L -> LayerBlend.Darken + 2L -> LayerBlend.Multiply + 3L -> LayerBlend.ColorBurn + 4L -> LayerBlend.LinearBurn + 5L -> LayerBlend.Subtract + 6L -> LayerBlend.DarkerColor + 7L -> LayerBlend.Lighten + 8L -> LayerBlend.Screen + 9L -> LayerBlend.ColorDodge + 10L -> LayerBlend.GlowDodge + 11L -> LayerBlend.Add + 12L -> LayerBlend.AddGlow + 13L -> LayerBlend.LighterColor + 14L -> LayerBlend.Overlay + 15L -> LayerBlend.SoftLight + 16L -> LayerBlend.HardLight + 17L -> LayerBlend.VividLight + 18L -> LayerBlend.LinearLight + 19L -> LayerBlend.PinLight + 20L -> LayerBlend.HardMix + 21L -> LayerBlend.Difference + 22L -> LayerBlend.Exclusion + 23L -> LayerBlend.Hue + 24L -> LayerBlend.Saturation + 25L -> LayerBlend.Color + 26L -> LayerBlend.Luminosity // CLIP: CSP UI label "Brightness". + 36L -> LayerBlend.Divide + else -> LayerBlend.Normal // includes folder code 30 (pass-through) and the unused 27..35 gap. + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipContainer.kt b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipContainer.kt new file mode 100644 index 0000000..2c1e8fe --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipContainer.kt @@ -0,0 +1,133 @@ +package org.umamo.format.clip + +import org.umamo.format.binary.decodeAscii + +/** + * Parser for the outer CLIP (Clip Studio Paint) container: the CSFCHUNK wrapper. + * + * EN: A .clip file is a flat sequence of 8-byte-ASCII-tagged chunks with big-endian u64 sizes, + * verified against several samples(`>8sQ`). This object walks that sequence and hands back + * the embedded SQLite database (the CHNKSQLi payload), which carries the layer table the + * reader needs. The tiled raster in the CHNKExta chunks is left untouched. + * JA: CLIP コンテナ(CSFCHUNK)を解析し, 埋め込み SQLite(CHNKSQLi)を取り出す. + * + * Layout (all integers big-endian): + * // CLIP: @ +0x00 "CSFCHUNK" (8) container magic + * // CLIP: @ +0x08 fileSize u64 whole-file length + * // CLIP: @ +0x10 headOffset u64 offset of the first chunk (= 24) + * // CLIP: then [8-byte id][u64 size][size bytes payload] repeated: + * // "CHNKHead" header · "CHNKExta" external raster · "CHNKSQLi" db · "CHNKFoot" terminator + */ +object ClipContainer { + /** Container magic at offset 0. */ + internal const val MAGIC = "CSFCHUNK" + + private const val CHUNK_SQLITE = "CHNKSQLi" + private const val CHUNK_FOOTER = "CHNKFoot" + + // An 8-byte ASCII id + an 8-byte big-endian u64 size precede every chunk payload. + private const val CHUNK_HEADER_SIZE = 16 + + /** + * True if [candidateBytes] begins with the CSFCHUNK container magic. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the CLIP magic. + */ + fun isClip(candidateBytes: ByteArray): Boolean { + // CLIP: CSFCHUNK container magic @ +0x00. + val magic = MAGIC.encodeToByteArray() + if (candidateBytes.size < magic.size) { + return false + } + for (magicIndex in magic.indices) { + if (candidateBytes[magicIndex] != magic[magicIndex]) { + return false + } + } + return true + } + + /** + * Extracts the embedded SQLite database (the CHNKSQLi chunk payload) from a complete .clip file. + * + * Walks the chunk sequence from the header offset, returning the byte slice of the first + * CHNKSQLi payload. Stops at CHNKFoot. The returned array is a fresh copy, safe to write to a + * temp file for the SQLite driver. + * + * @param ByteArray bytes The complete .clip file contents. + * @return ByteArray The raw "SQLite format 3" database bytes. + * @throws IllegalArgumentException If the magic is missing or no CHNKSQLi chunk is present. + */ + fun extractSqliteDatabase(bytes: ByteArray): ByteArray { + require(isClip(bytes)) { "not a .clip file: missing CSFCHUNK magic @ +0x00" } + + // CLIP: @ +0x10 headOffset u64 - where the first chunk begins (24 in every observed file). + val headOffset = readUInt64(bytes, 16) + var offset = requireFits(headOffset, "headOffset") + + while (offset + CHUNK_HEADER_SIZE <= bytes.size) { + val chunkId = readAscii(bytes, offset, 8) + // CLIP: chunk size u64 immediately after the 8-byte id. + val payloadSize = requireFits(readUInt64(bytes, offset + 8), "chunk '$chunkId' size") + val payloadStart = offset + CHUNK_HEADER_SIZE + + if (chunkId == CHUNK_SQLITE) { + val payloadEnd = payloadStart + payloadSize + require(payloadEnd <= bytes.size) { + "CHNKSQLi payload runs past EOF (need $payloadEnd, have ${bytes.size})" + } + return bytes.copyOfRange(payloadStart, payloadEnd) + } + if (chunkId == CHUNK_FOOTER) { + break + } + + offset = payloadStart + payloadSize + } + + throw IllegalArgumentException("no CHNKSQLi chunk found in the CLIP container") + } + + /** + * Reads a big-endian unsigned 64-bit integer as a Long. + * + * @param ByteArray bytes The buffer to read from. + * @param Int at The offset of the most-significant byte. + * @return Long The decoded value (treated as non-negative; CLIP sizes never use the sign bit). + */ + private fun readUInt64(bytes: ByteArray, at: Int): Long { + require(at + 8 <= bytes.size) { "truncated u64 @ +$at" } + var value = 0L + for (byteIndex in 0 until 8) { + value = (value shl 8) or (bytes[at + byteIndex].toLong() and 0xFF) + } + return value + } + + /** + * Reads a fixed-length ASCII string (chunk ids are 8-byte ASCII tags). + * + * @param ByteArray bytes The buffer to read from. + * @param Int at The start offset. + * @param Int length The number of bytes to read. + * @return String The decoded ASCII string. + */ + private fun readAscii(bytes: ByteArray, at: Int, length: Int): String { + require(at + length <= bytes.size) { "truncated ascii @ +$at" } + return decodeAscii(bytes, at, length) + } + + /** + * Narrows a 64-bit file offset/size to an Int, since the whole file is held in one ByteArray + * (so any valid offset fits). Rejects values that would overflow rather than silently wrapping. + * + * @param Long value The 64-bit value to narrow. + * @param String label A description used in the error message. + * @return Int The value as a non-negative Int. + */ + private fun requireFits(value: Long, label: String): Int { + require(value in 0..Int.MAX_VALUE) { "$label out of addressable range: $value" } + return value.toInt() + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.kt b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.kt new file mode 100644 index 0000000..c28e8b8 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.kt @@ -0,0 +1,18 @@ +package org.umamo.format.clip + +import org.umamo.format.clip.db.ClipDatabase + +/** + * Opens a SQLDelight driver over the extracted .clip SQLite [databaseBytes], runs [block] against the + * resulting [ClipDatabase], and tears the driver (and any temp file) down afterward. + * + * The driver is the only platform-specific piece - JVM uses JdbcSqliteDriver, Android uses + * AndroidSqliteDriver - so it lives behind this expect/actual seam while the rest of the reader stays + * platform-neutral. The embedded database already has its tables, so the actuals must NOT run + * Schema.create. + * + * @param ByteArray databaseBytes The raw "SQLite format 3" bytes (the CHNKSQLi payload). + * @param Function1 block Runs against the open database and returns the parsed result. + * @return T The block's result. + */ +internal expect fun useClipDatabase(databaseBytes: ByteArray, block: (ClipDatabase) -> T): T \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipLayerTree.kt b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipLayerTree.kt new file mode 100644 index 0000000..933c0b5 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipLayerTree.kt @@ -0,0 +1,268 @@ +package org.umamo.format.clip + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind + +/** + * Document geometry plus the id of the root folder the layer walk descends from. + * + * Decoupled from the SQLDelight-generated row types so the tree logic is pure and testable; the + * reader maps the generated Canvas row into this. + */ +internal data class ClipCanvas( + val widthPx: Int, + val heightPx: Int, + val rootFolderId: Long, +) + +/** + * One CLIP Layer row, reduced to the fields the neutral model needs and with nulls already + * defaulted. The reader maps each SQLDelight-generated row into this shape. + */ +internal data class ClipLayerRow( + val mainId: Long, + val name: String, + val folder: Long, + val type: Long, + val visibility: Long, + val opacity: Long, + val composite: Long, + val clip: Long, + val offsetX: Long, + val offsetY: Long, + val firstChildIndex: Long, + val nextIndex: Long, + val uuid: String?, + // Tile-grid anchor = (offsetX + renderOffscrX, offsetY + renderOffscrY); canvas-aligned (0 in corpus). + val renderOffscrX: Long, + val renderOffscrY: Long, +) + +// CLIP: Layer.LayerFolder bit 0x10 marks a folder/group node. +private const val LAYER_FOLDER_BIT = 0x10L + +// CLIP: Layer.LayerOpacity is a 0..256 fixed-point scale (256 == fully opaque), not 0..255. +private const val OPACITY_FULL = 256f + +// CLIP: Layer.LayerVisibility is a bitfield; bit 0 is "shown" (values 1 and 3 are visible, 2 hidden - +// verified by several samples). The other bit is an unrelated sub-flag. +private const val VISIBILITY_SHOWN_BIT = 1L + +// CLIP: Layer.LayerComposite == 30 is the folder "Through" (pass-through, non-isolating) mode - the +// default for a new folder. Only meaningful on folder rows; observed in several samples. +private const val COMPOSITE_THROUGH = 30L + +// CLIP: Layer.LayerType - verified across the corpus (see docs/CLIP.md §5). 1 and 3 are raster +// layers (pixels persist); 0 is an object layer (vector/text, distinguished by TextLayerType); 1584 +// is the Paper/fill layer; 4098 is a procedural adjustment/correction layer. None of 0/1584/4098 +// carry a persisted raster. +private const val LAYER_TYPE_RASTER_PLAIN = 1L +private const val LAYER_TYPE_RASTER_VARIANT = 3L +private const val LAYER_TYPE_OBJECT = 0L +private const val LAYER_TYPE_FILL = 1584L +private const val LAYER_TYPE_ADJUSTMENT = 4098L + +/** + * Classifies a leaf layer row into a neutral [SourceLayerKind]. + * + * @param ClipLayerRow row The leaf layer row. + * @param Set textLayerIds MainIds of text object layers (empty on schemas without TextLayerType). + * @return SourceLayerKind The layer kind (Raster unless it is an object/fill/adjustment layer). + */ +private fun layerKindOf(row: ClipLayerRow, textLayerIds: Set): SourceLayerKind = + when (row.type) { + LAYER_TYPE_RASTER_PLAIN, LAYER_TYPE_RASTER_VARIANT -> SourceLayerKind.Raster + // CLIP: a text layer is in textLayerIds (TextLayerType set); other object layers are vector. + LAYER_TYPE_OBJECT -> if (row.mainId in textLayerIds) SourceLayerKind.Text else SourceLayerKind.Vector + LAYER_TYPE_FILL -> SourceLayerKind.Fill + LAYER_TYPE_ADJUSTMENT -> SourceLayerKind.Adjustment + else -> SourceLayerKind.Unknown + } + +/** + * Builds the neutral, ordered [SourceLayer] list from the CLIP layer table. + * + * EN: The layer tree is encoded as MainId links: a node's LayerFirstChildIndex points at its first + * child and LayerNextIndex at its next sibling (0 terminates each chain). We descend from + * Canvas.CanvasRootFolder (a synthetic root that is never emitted) and flatten depth-first. The + * firstChild/nextSibling walk visits the bottom-most layer first (verified: the root's first + * child in the corpus is "Paper", Clip Studio's default background), so the produced list is + * bottom-to-top - the painter's-algorithm order the compositor expects, matching the KRA reader. + * Folders contribute only their name to the slash-joined groupPath; only leaf layers are emitted. + * JA: MainId のリンク(FirstChild/NextSibling)でツリーを深さ優先に平坦化し, 下から上の順で葉のみ出力する. + * + * @param ClipCanvas canvas The document geometry and root-folder id. + * @param List rows All layer rows (in any order; indexed internally by MainId). + * @param Map rastersByMainId Decoded rasters keyed by layer MainId; absent => placeholder. + * @param Set textLayerIds MainIds of text object layers (for kind classification). + * @return ClipTree The leaf layers (bottom-to-top, order = top-most-first) and the folder groups. + */ +internal fun buildSourceTree( + canvas: ClipCanvas, + rows: List, + rastersByMainId: Map, + textLayerIds: Set, +): ClipTree { + val rowsByMainId = rows.associateBy { row -> row.mainId } + val leavesBottomToTop = ArrayList() + val groups = ArrayList() + + val rootRow = rowsByMainId[canvas.rootFolderId] + if (rootRow != null) { + collectTree(rootRow.firstChildIndex, rowsByMainId, parentPath = "", visited = HashSet(), outLeaves = leavesBottomToTop, outGroups = groups) + } + + // SourceLayer.order is top-most-first (0 == topmost); the list itself stays bottom-to-top, so the + // top-most leaf is the last collected. Convert the bottom-up index into a top-down order value. + val lastIndex = leavesBottomToTop.size - 1 + val layers = + leavesBottomToTop.mapIndexed { indexFromBottom, leaf -> + toSourceLayer( + row = leaf.row, + groupPath = leaf.groupPath, + order = lastIndex - indexFromBottom, + raster = rastersByMainId[leaf.row.mainId], + textLayerIds = textLayerIds, + ) + } + return ClipTree(layers = layers, groups = groups) +} + +/** The flattened result of a layer-tree walk: the leaf layers and the folders that enclose them. */ +internal class ClipTree(val layers: List, val groups: List) + +/** A leaf layer paired with the slash-joined path of the folders enclosing it. */ +private class ClipLeaf(val row: ClipLayerRow, val groupPath: String) + +/** + * Walks a sibling chain starting at [startMainId], descending into folders. Leaf layers are + * appended to [outLeaves] in document (bottom-to-top) order; each folder is recorded in [outGroups]. + * + * @param Long startMainId MainId of the first sibling (0 terminates immediately). + * @param Map rowsByMainId All rows indexed by MainId. + * @param String parentPath Slash-joined names of the enclosing folders (empty at root). + * @param MutableSet visited Guards against a malformed cyclic link list. + * @param MutableList outLeaves Accumulates leaves in walk order. + * @param MutableList outGroups Accumulates folder groups. + */ +private fun collectTree( + startMainId: Long, + rowsByMainId: Map, + parentPath: String, + visited: MutableSet, + outLeaves: MutableList, + outGroups: MutableList, +) { + var currentMainId = startMainId + while (currentMainId != 0L) { + if (!visited.add(currentMainId)) { + // A cyclic LayerNextIndex would otherwise loop forever; stop defensively. + break + } + val row = rowsByMainId[currentMainId] ?: break + // CLIP: a node is a group if the folder bit is set; treat "has children" as a group too, so a + // folder whose bit we misread still recurses rather than being emitted as a bogus drawable. + val isGroup = (row.folder and LAYER_FOLDER_BIT) != 0L || row.firstChildIndex != 0L + if (isGroup) { + val childPath = if (parentPath.isEmpty()) row.name else "$parentPath/${row.name}" + outGroups.add(toSourceGroup(row, childPath)) + collectTree(row.firstChildIndex, rowsByMainId, childPath, visited, outLeaves, outGroups) + } else { + outLeaves.add(ClipLeaf(row, parentPath)) + } + currentMainId = row.nextIndex + } +} + +/** + * Converts one folder row into a neutral [SourceGroup]. + * + * @param ClipLayerRow row The folder layer row. + * @param String path The slash-joined folder path (including this folder's name). + * @return SourceGroup The neutral folder descriptor. + */ +private fun toSourceGroup(row: ClipLayerRow, path: String): SourceGroup = + ClipSourceGroup( + path = path, + name = row.name, + visible = (row.visibility and VISIBILITY_SHOWN_BIT) != 0L, + opacity = (row.opacity.toFloat() / OPACITY_FULL).coerceIn(0f, 1f), + clipped = row.clip != 0L, + // CLIP: a folder's blend lives in LayerComposite, same codes as a layer; 30 is "Through". + blend = ClipBlend.fromCompositeCode(row.composite), + passThrough = row.composite == COMPOSITE_THROUGH, + ) + +/** + * Converts one leaf CLIP layer into a neutral [SourceLayer], using its decoded raster when present + * and a transparent 1x1 placeholder otherwise (adjustment/procedural layers carry no own pixels). + * + * @param ClipLayerRow row The leaf layer row. + * @param String groupPath The slash-joined enclosing-folder path. + * @param Int order Draw order, top-most == 0. + * @param ClipDecodedRaster? raster The decoded raster, or null for a transparent placeholder. + * @param Set textLayerIds MainIds of text object layers (for kind classification). + * @return SourceLayer The neutral layer. + */ +private fun toSourceLayer(row: ClipLayerRow, groupPath: String, order: Int, raster: ClipDecodedRaster?, textLayerIds: Set): SourceLayer { + // CLIP: LayerUuid is rename/reorder-stable - the strongest re-import key; fall back to the + // numeric MainId only if a layer somehow lacks a uuid. + val stableId = row.uuid?.takeIf { uuid -> uuid.isNotBlank() } ?: row.mainId.toString() + // Decoded raster supplies real bounds; otherwise a 1x1 transparent placeholder at the layer + // offset keeps downstream dimensions valid (mirrors the KRA reader's empty-layer placeholder). + val bounds = raster?.bounds ?: LayerBounds(left = row.offsetX.toInt(), top = row.offsetY.toInt(), width = 1, height = 1) + val pixels = raster?.raster ?: LayerRaster(width = 1, height = 1, rgba = ByteArray(4)) + return ClipSourceLayer( + id = LayerId(stableId), + name = row.name, + kind = layerKindOf(row, textLayerIds), + visible = (row.visibility and VISIBILITY_SHOWN_BIT) != 0L, + groupPath = groupPath, + order = order, + bounds = bounds, + opacity = (row.opacity.toFloat() / OPACITY_FULL).coerceIn(0f, 1f), + clipped = row.clip != 0L, // CLIP: Layer.LayerClip non-zero == clip to the layer below. + blend = ClipBlend.fromCompositeCode(row.composite), + raster = pixels, + ) +} + +/** Concrete [SourceLayer] backing a parsed CLIP layer. */ +private data class ClipSourceLayer( + override val id: LayerId, + override val name: String, + override val kind: SourceLayerKind, + override val visible: Boolean, + override val groupPath: String, + override val order: Int, + override val bounds: LayerBounds, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val raster: LayerRaster, +) : SourceLayer + +/** Concrete [SourceGroup] backing a parsed CLIP folder. */ +private data class ClipSourceGroup( + override val path: String, + override val name: String, + override val visible: Boolean, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val passThrough: Boolean, +) : SourceGroup + +/** Concrete [SourceArt] backing a parsed CLIP document. */ +data class ClipSourceArt( + override val widthPx: Int, + override val heightPx: Int, + override val layers: List, + override val groups: List, +) : SourceArt \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipRaster.kt b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipRaster.kt new file mode 100644 index 0000000..f5f84fc --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipRaster.kt @@ -0,0 +1,503 @@ +package org.umamo.format.clip + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.format.binary.encodeUtf16Be +import org.umamo.format.binary.inflateZlib + +/** + * Decodes a CLIP layer's tiled raster into a cropped RGBA8888 buffer. + * + * EN: A layer's pixels live in an external CHNKExta chunk as a grid of 256x256 tiles. Each tile is + * `[4-byte little-endian length][zlib stream]`; the inflated tile is `2562565` bytes laid out + * as a one-byte alpha plane followed by an interleaved BGRA color plane (the color plane's own + * alpha slot is unused). The tile grid (columns/rows and the padded image size) comes from the + * Offscreen.Attribute index. This object walks the block data, inflates each non-empty tile, + * converts planes to straight-alpha RGBA, and assembles the tiles cropped to their bounding box. + * JA: レイヤーのラスタは 256x256 タイル(4バイト長 + zlib, 展開後はアルファ面 + BGRA 面). 復号して結合する. + */ +internal object ClipRaster { + private const val TILE = 256 + private const val TILE_PIXELS = TILE * TILE // 65536 - the 8-bit alpha-plane byte count. + + // Every tile is an 8-bit/1-bit alpha plane FIRST, then a color plane. The inflated byte count + // identifies the canvas color mode (all corpus samples have CanvasChannelBytes = 1 / 8-bit): + // RGBA alpha(8b) + BGRA(4x8b) = 5 * TILE_PIXELS (ChannelOrder 33) + // Greyscale alpha(8b) + gray(8b) = 2 * TILE_PIXELS (ChannelOrder 17, ColorType 1) + // Monochrome alpha(1b) + value(1b) = TILE_PIXELS / 4 (ChannelOrder 17, ColorType 2) + private const val RGBA_TILE_BYTES = TILE_PIXELS * 5 // 327680 + private const val GREYSCALE_TILE_BYTES = TILE_PIXELS * 2 // 131072 + private const val MONOCHROME_TILE_BYTES = TILE_PIXELS / 4 // 16384 (two 1-bit planes, MSB-first) + + // One 1-bit plane is TILE_PIXELS/8 bytes; the monochrome value plane follows the alpha plane. + private const val MONOCHROME_PLANE_BYTES = TILE_PIXELS / 8 // 8192 + + // Generous inflate ceiling so a malformed/other-format tile can't overrun (8 bytes/pixel max). + private const val MAX_TILE_BYTES = TILE_PIXELS * 8 + + /** The pixel layout of a tile, identified by its inflated byte count. */ + private enum class TileFormat { Rgba, Greyscale, Monochrome } + + /** + * Maps an inflated tile byte count to its [TileFormat], or null for an unrecognized layout. + * + * @param Int inflatedLength The number of inflated tile bytes. + * @return TileFormat The pixel layout, or null if unsupported. + */ + private fun tileFormatFor(inflatedLength: Int): TileFormat? = + when (inflatedLength) { + RGBA_TILE_BYTES -> TileFormat.Rgba + GREYSCALE_TILE_BYTES -> TileFormat.Greyscale + MONOCHROME_TILE_BYTES -> TileFormat.Monochrome + else -> null + } + + // Block-data string tags (UTF-16BE) and the marker for "is the 2nd u32 the start of a tag". + private val BEGIN_TAG = encodeUtf16Be("BlockDataBeginChunk") + private val END_TAG = encodeUtf16Be("BlockDataEndChunk") + private val STATUS_TAG = encodeUtf16Be("BlockStatus") + private val CHECKSUM_TAG = encodeUtf16Be("BlockCheckSum") + + // "\x00B\x00l" - the first two UTF-16BE code units shared by every Block* tag; if the 2nd u32 + // equals this, the first u32 was the string length (no leading size word). + private const val TAG_PREFIX = 0x0042006CL + + private const val CHUNK_HEADER_SIZE = 16 // 8-byte id + u64 size + private const val EXTERNAL_HEADER_SIZE = 56 // CHNKExta payload header: u64 + 40-byte id + u64 + + /** + * Decodes one layer's raster (optionally baking in its grayscale mask), or returns null when + * there is no decodable content (no non-empty tiles, an unparseable Attribute, or an unexpected + * pixel format) so the caller can fall back to a placeholder. + * + * The mask, when present, modulates alpha: `outputAlpha = colorAlpha * mask / 255`. Mask tiles + * align with color tiles by `(col, row)` - both offscreens are canvas-anchored identically - so a + * color tile with no co-located mask tile is left fully visible (the mask InitColor is 255). + * + * @param ByteArray fileBytes The complete .clip file (chunks are read from it). + * @param Int colorChunkOffset Absolute file offset of the layer's color CHNKExta chunk. + * @param ByteArray colorAttribute The color Offscreen.Attribute tile index. + * @param Int maskChunkOffset Absolute file offset of the mask CHNKExta chunk, or -1 if none. + * @param ByteArray maskAttribute The mask Offscreen.Attribute, or null if the layer has no mask. + * @param Int anchorX Canvas X of tile column 0 (LayerOffsetX + LayerRenderOffscrOffsetX). + * @param Int anchorY Canvas Y of tile row 0. + * @return ClipDecodedRaster The placed, cropped RGBA raster, or null if nothing decodable. + */ + fun decodeLayer( + fileBytes: ByteArray, + colorChunkOffset: Int, + colorAttribute: ByteArray, + maskChunkOffset: Int, + maskAttribute: ByteArray?, + anchorX: Int, + anchorY: Int, + ): ClipDecodedRaster? { + val grid = parseAttributeGrid(colorAttribute) ?: return null + if (grid.columns <= 0 || grid.rows <= 0) { + return null + } + + val tiles = walkBlockData(fileBytes, colorChunkOffset) + val nonEmpty = tiles.filter { tile -> tile.bytes.isNotEmpty() } + if (nonEmpty.isEmpty()) { + return null + } + + // Mask tiles keyed by (col, row), aligned to color tiles (shared canvas-0,0 anchor). Absent + // for layers without a mask, and per-tile-absent where the mask InitColor (255) applies. + val maskTilesByColRow = + if (maskAttribute != null && maskChunkOffset >= 0) { + buildMaskTiles(fileBytes, maskChunkOffset, maskAttribute) + } else { + emptyMap() + } + + // Crop to the bounding box of non-empty tiles - bounds memory for large, mostly-empty layers + // and matches the KRA reader's union-of-tiles cropping. + var minColumn = Int.MAX_VALUE + var minRow = Int.MAX_VALUE + var maxColumn = Int.MIN_VALUE + var maxRow = Int.MIN_VALUE + for (tile in nonEmpty) { + val column = tile.index % grid.columns + val row = tile.index / grid.columns + if (column < minColumn) { + minColumn = column + } + if (row < minRow) { + minRow = row + } + if (column > maxColumn) { + maxColumn = column + } + if (row > maxRow) { + maxRow = row + } + } + + val widthPx = (maxColumn - minColumn + 1) * TILE + val heightPx = (maxRow - minRow + 1) * TILE + val rgba = ByteArray(widthPx * heightPx * 4) + + val inflateBuffer = ByteArray(MAX_TILE_BYTES) + for (tile in nonEmpty) { + val inflatedLength = inflateTile(tile.bytes, inflateBuffer) + // Identify the color mode from the tile size; skip an unrecognized layout rather than guess. + val format = tileFormatFor(inflatedLength) ?: continue + val column = tile.index % grid.columns + val row = tile.index / grid.columns + val maskTile = maskTilesByColRow[packColumnRow(column, row)] + blitTile( + tileBytes = inflateBuffer, + format = format, + rgba = rgba, + destXTile = (column - minColumn) * TILE, + destYTile = (row - minRow) * TILE, + rowStridePx = widthPx, + maskTile = maskTile, + ) + } + + val bounds = + LayerBounds( + left = anchorX + minColumn * TILE, + top = anchorY + minRow * TILE, + width = widthPx, + height = heightPx, + ) + return ClipDecodedRaster(bounds, LayerRaster(width = widthPx, height = heightPx, rgba = rgba)) + } + + /** + * Decodes a layer's mask offscreen into its non-empty grayscale tiles, keyed by `(col, row)`. + * + * Each mask tile inflates to a single-channel 256x256 plane (TILE_PIXELS bytes). Empty tiles are + * omitted: their absence signals the mask InitColor (255, fully visible) at decode time. + * + * @param ByteArray fileBytes The complete .clip file. + * @param Int maskChunkOffset Absolute file offset of the mask CHNKExta chunk. + * @param ByteArray maskAttribute The mask Offscreen.Attribute (gives the mask grid columns). + * @return Map Non-empty mask tiles (65536-byte planes) keyed by packed (col, row). + */ + private fun buildMaskTiles(fileBytes: ByteArray, maskChunkOffset: Int, maskAttribute: ByteArray): Map { + val grid = parseAttributeGrid(maskAttribute) ?: return emptyMap() + if (grid.columns <= 0) { + return emptyMap() + } + val tiles = walkBlockData(fileBytes, maskChunkOffset) + val result = HashMap() + val buffer = ByteArray(MAX_TILE_BYTES) + for (tile in tiles) { + if (tile.bytes.isEmpty()) { + continue + } + val inflatedLength = inflateTile(tile.bytes, buffer) + // A mask follows the layer's color mode: 8-bit grayscale (TILE_PIXELS bytes) on RGBA/greyscale + // layers, or 1-bit (TILE_PIXELS/8 bytes, MSB-first) on monochrome layers. Normalize both to a + // per-pixel 0..255 plane so blitTile's alpha multiply is uniform. Skip any other size. + val maskPlane = + when (inflatedLength) { + TILE_PIXELS -> buffer.copyOf(TILE_PIXELS) + MONOCHROME_PLANE_BYTES -> expandBitPlaneToBytes(buffer) + else -> continue + } + val column = tile.index % grid.columns + val row = tile.index / grid.columns + result[packColumnRow(column, row)] = maskPlane + } + return result + } + + /** + * Expands an MSB-first 1-bit plane (TILE_PIXELS/8 bytes) into a TILE_PIXELS-byte plane of 0/255, + * so a 1-bit mask multiplies alpha identically to an 8-bit mask (bit set => 255 reveals). + * + * @param ByteArray bits The inflated 1-bit plane (its first MONOCHROME_PLANE_BYTES bytes are used). + * @return ByteArray A TILE_PIXELS-byte plane, 255 where the bit is set and 0 otherwise. + */ + private fun expandBitPlaneToBytes(bits: ByteArray): ByteArray { + val plane = ByteArray(TILE_PIXELS) + for (pixelIndex in 0 until TILE_PIXELS) { + if (bitAt(bits, 0, pixelIndex)) { + plane[pixelIndex] = 0xFF.toByte() + } + } + return plane + } + + /** + * Packs a tile (column, row) into a single Long map key. + * + * @param Int column The tile column. + * @param Int row The tile row. + * @return Long The packed key. + */ + private fun packColumnRow(column: Int, row: Int): Long = (column.toLong() shl 32) or (row.toLong() and 0xFFFFFFFFL) + + /** + * Writes one inflated 256x256 tile into the assembled RGBA buffer at the given tile origin, + * expanding the tile's color mode to RGBA8888 and optionally baking in a grayscale mask tile. + * + * @param ByteArray tileBytes The inflated tile (alpha plane first, then the color plane). + * @param TileFormat format The tile's color mode (RGBA / greyscale / monochrome). + * @param ByteArray rgba The destination RGBA8888 buffer. + * @param Int destXTile Destination X of the tile's left edge, in pixels. + * @param Int destYTile Destination Y of the tile's top edge, in pixels. + * @param Int rowStridePx Destination buffer width in pixels. + * @param ByteArray? maskTile A 256x256 single-byte mask plane to bake into alpha, or null. + */ + private fun blitTile( + tileBytes: ByteArray, + format: TileFormat, + rgba: ByteArray, + destXTile: Int, + destYTile: Int, + rowStridePx: Int, + maskTile: ByteArray?, + ) { + for (y in 0 until TILE) { + val sourceRow = y * TILE + var destination = ((destYTile + y) * rowStridePx + destXTile) * 4 + for (x in 0 until TILE) { + val sourcePixel = sourceRow + x + val red: Int + val green: Int + val blue: Int + var alpha: Int + when (format) { + TileFormat.Rgba -> { + // CLIP: alpha plane [0, TILE_PIXELS), then interleaved B,G,R,(unused). + alpha = tileBytes[sourcePixel].toInt() and 0xFF + val colorBase = TILE_PIXELS + sourcePixel * 4 + red = tileBytes[colorBase + 2].toInt() and 0xFF + green = tileBytes[colorBase + 1].toInt() and 0xFF + blue = tileBytes[colorBase].toInt() and 0xFF + } + + TileFormat.Greyscale -> { + // CLIP: alpha plane [0, TILE_PIXELS), then an 8-bit gray plane. + alpha = tileBytes[sourcePixel].toInt() and 0xFF + val gray = tileBytes[TILE_PIXELS + sourcePixel].toInt() and 0xFF + red = gray + green = gray + blue = gray + } + + TileFormat.Monochrome -> { + // CLIP: 1-bit alpha plane, then a 1-bit value plane (MSB-first); value 0 = black. + alpha = if (bitAt(tileBytes, 0, sourcePixel)) 0xFF else 0 + val gray = if (bitAt(tileBytes, MONOCHROME_PLANE_BYTES, sourcePixel)) 0xFF else 0 + red = gray + green = gray + blue = gray + } + } + if (maskTile != null) { + // Bake the mask: outputAlpha = layerAlpha * mask / 255 (mask byte is grayscale 0..255). + alpha = alpha * (maskTile[sourcePixel].toInt() and 0xFF) / 255 + } + rgba[destination] = red.toByte() + rgba[destination + 1] = green.toByte() + rgba[destination + 2] = blue.toByte() + rgba[destination + 3] = alpha.toByte() + destination += 4 + } + } + } + + /** + * Reads one bit from an MSB-first 1-bit plane starting at [planeOffset]. + * + * @param ByteArray bytes The tile buffer. + * @param Int planeOffset Byte offset of the 1-bit plane. + * @param Int pixelIndex Pixel index within the 256x256 tile. + * @return Boolean Whether the bit is set. + */ + private fun bitAt(bytes: ByteArray, planeOffset: Int, pixelIndex: Int): Boolean { + val byte = bytes[planeOffset + (pixelIndex shr 3)].toInt() + return (byte shr (7 - (pixelIndex and 7))) and 1 != 0 + } + + /** + * Inflates a tile body (`[4-byte LE length][zlib stream]`) into [destination], returning the + * number of decompressed bytes (0 on failure). + * + * @param ByteArray tileBytes The tile body including its 4-byte length prefix. + * @param ByteArray destination The reusable inflate buffer (sized to MAX_TILE_BYTES). + * @return Int The number of bytes inflated, or 0 if the stream was invalid. + */ + private fun inflateTile(tileBytes: ByteArray, destination: ByteArray): Int { + // The 4-byte little-endian prefix is the zlib stream length; inflating from offset 4 is enough. + val inflated = inflateZlib(tileBytes, 4, tileBytes.size - 4, destination.size) + inflated.copyInto(destination, 0, 0, minOf(inflated.size, destination.size)) + return minOf(inflated.size, destination.size) + } + + /** Columns/rows of a layer's tile grid, read from Offscreen.Attribute. */ + private class AttributeGrid(val columns: Int, val rows: Int) + + /** + * Parses the tile-grid dimensions out of Offscreen.Attribute. + * + * The Attribute is a serialized property block; the "Parameter" entry is followed by four + * big-endian u32s: padded width, padded height, column count, row count. Only the grid shape is + * needed to place tiles by their block index. + * + * @param ByteArray attribute The Offscreen.Attribute bytes. + * @return AttributeGrid The columns/rows, or null if the "Parameter" entry was not found. + */ + private fun parseAttributeGrid(attribute: ByteArray): AttributeGrid? { + // CLIP: Offscreen.Attribute - UTF-16BE "Parameter", then width, height, cols, rows (u32 BE). + val parameterTag = encodeUtf16Be("Parameter") + val tagAt = indexOf(attribute, parameterTag, 0) + if (tagAt < 0) { + return null + } + val fieldsAt = tagAt + parameterTag.size + if (fieldsAt + 16 > attribute.size) { + return null + } + val columns = readUInt32BE(attribute, fieldsAt + 8) + val rows = readUInt32BE(attribute, fieldsAt + 12) + return AttributeGrid(columns = columns, rows = rows) + } + + /** One tile within a layer's external block data: its grid index and (possibly empty) body. */ + private class BlockTile(val index: Int, val bytes: ByteArray) + + /** + * Walks the external chunk's block data, returning each BlockDataBeginChunk's tile body (empty + * for tiles flagged as having no data). + * + * @param ByteArray fileBytes The complete .clip file. + * @param Int chunkOffset Absolute file offset of the CHNKExta chunk. + * @return List The tiles in encounter order. + */ + private fun walkBlockData(fileBytes: ByteArray, chunkOffset: Int): List { + val chunkSize = readUInt64(fileBytes, chunkOffset + 8) + val blockStart = chunkOffset + CHUNK_HEADER_SIZE + EXTERNAL_HEADER_SIZE + val blockEnd = minOf(chunkOffset + CHUNK_HEADER_SIZE + chunkSize, fileBytes.size) + + val tiles = ArrayList() + var position = blockStart + while (position + 8 <= blockEnd) { + val first = readUInt32BE(fileBytes, position) + val second = readUInt32BELong(fileBytes, position + 4) + position += 8 + val stringLength: Int + if (second == TAG_PREFIX) { + // No leading size word: the first u32 was the string length; rewind to the tag. + stringLength = first + position -= 4 + } else { + stringLength = readUInt32BE(fileBytes, position - 4) + } + val tagBytes = stringLength * 2 + if (position + tagBytes > blockEnd) { + break + } + val tag = fileBytes.copyOfRange(position, position + tagBytes) + position += tagBytes + + when { + tag.contentEquals(BEGIN_TAG) -> { + if (position + 20 > blockEnd) { + break + } + val blockIndex = readUInt32BE(fileBytes, position) + val notEmpty = readUInt32BE(fileBytes, position + 16) + position += 20 + if (notEmpty > 0) { + if (position + 4 > blockEnd) { + break + } + val tileLength = readUInt32BE(fileBytes, position) + position += 4 + val tileEnd = minOf(position + tileLength, blockEnd) + tiles.add(BlockTile(blockIndex, fileBytes.copyOfRange(position, tileEnd))) + position = tileEnd + } else { + tiles.add(BlockTile(blockIndex, ByteArray(0))) + } + } + + tag.contentEquals(END_TAG) -> Unit + tag.contentEquals(STATUS_TAG) -> position += 28 + tag.contentEquals(CHECKSUM_TAG) -> { + position += 28 + break + } + + else -> break + } + } + return tiles + } + + /** + * Returns the start index of needle within haystack at or after from, or -1. + * + * @param ByteArray haystack The buffer to search. + * @param ByteArray needle The byte sequence to find. + * @param Int from The first index to consider. + * @return Int The match start, or -1. + */ + private fun indexOf(haystack: ByteArray, needle: ByteArray, from: Int): Int { + if (needle.isEmpty() || haystack.size < needle.size) { + return -1 + } + var start = maxOf(from, 0) + val lastStart = haystack.size - needle.size + while (start <= lastStart) { + var matchIndex = 0 + while (matchIndex < needle.size && haystack[start + matchIndex] == needle[matchIndex]) { + matchIndex++ + } + if (matchIndex == needle.size) { + return start + } + start++ + } + return -1 + } + + /** + * Reads a big-endian unsigned 32-bit integer as an Int (CLIP block sizes fit comfortably). + * + * @param ByteArray bytes The buffer. + * @param Int at The offset of the most-significant byte. + * @return Int The decoded value. + */ + private fun readUInt32BE(bytes: ByteArray, at: Int): Int = + ((bytes[at].toInt() and 0xFF) shl 24) or + ((bytes[at + 1].toInt() and 0xFF) shl 16) or + ((bytes[at + 2].toInt() and 0xFF) shl 8) or + (bytes[at + 3].toInt() and 0xFF) + + /** + * Reads a big-endian unsigned 32-bit integer as a Long (for an unsigned tag-prefix compare). + * + * @param ByteArray bytes The buffer. + * @param Int at The offset of the most-significant byte. + * @return Long The decoded value in 0..0xFFFFFFFF. + */ + private fun readUInt32BELong(bytes: ByteArray, at: Int): Long = readUInt32BE(bytes, at).toLong() and 0xFFFFFFFFL + + /** + * Reads a big-endian unsigned 64-bit integer as an Int (the whole file fits one ByteArray). + * + * @param ByteArray bytes The buffer. + * @param Int at The offset of the most-significant byte. + * @return Int The decoded value. + */ + private fun readUInt64(bytes: ByteArray, at: Int): Int { + var value = 0L + for (byteIndex in 0 until 8) { + value = (value shl 8) or (bytes[at + byteIndex].toLong() and 0xFF) + } + return value.toInt() + } +} + +/** A decoded, placed layer raster: its canvas bounds and the cropped RGBA pixels. */ +internal class ClipDecodedRaster(val bounds: LayerBounds, val raster: LayerRaster) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipReader.kt new file mode 100644 index 0000000..d7d6e46 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/clip/ClipReader.kt @@ -0,0 +1,193 @@ +package org.umamo.format.clip + +import org.umamo.format.FileKind +import org.umamo.format.art.ArtReader +import org.umamo.format.art.SourceArt +import org.umamo.format.clip.db.ClipDatabase +import org.umamo.format.clip.db.SelectAllLayers +import kotlin.math.roundToInt + +/** + * Clip Studio Paint (.clip) reader (STRETCH, but the re-import-critical one). + * + * EN: `.clip` carries Celsys's rename/reorder-stable layer ids (Layer.MainId and Layer.LayerUuid), + * which give non-destructive re-import a reliable identity key PSD cannot. This reader parses the + * CSFCHUNK container down to the embedded SQLite database (CHNKSQLi) for the Canvas + Layer tables, + * and decodes the tiled raster from the CHNKExta chunks: ids, names, group hierarchy, order, + * opacity, blend, bounds, kind, visibility, RGBA/greyscale/monochrome pixels, masks (baked into + * alpha), and clipping. See docs/format/CLIP.md. + * JA: CLIP 読み込み。安定レイヤー ID が再取り込みの信頼性を生む。ラスタ(RGBA/グレースケール/モノクロ)も復号する。 + * + * Cross-platform (JVM + Android): the only platform-specific step - opening a SQLite driver over the + * extracted database bytes - sits behind the [useClipDatabase] expect/actual seam (JVM JdbcSqliteDriver, + * Android AndroidSqliteDriver). The container parse and tile decode are pure jvmAndroidMain Kotlin. + * On Android, ClipAndroid.applicationContext must be set once at startup (the driver needs a Context). + */ +object ClipReader : ArtReader { + override val kind: FileKind = FileKind.Clip + + /** + * True if [candidateBytes] starts with the CSFCHUNK container magic. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the CLIP magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean = ClipContainer.isClip(candidateBytes) + + /** + * Parses a complete .clip file into the neutral SourceArt model (layer tree only, this pass). + * + * @param ByteArray bytes The complete .clip file contents. + * @return SourceArt The canvas size and the ordered, bottom-to-top layer list. + */ + override fun read(bytes: ByteArray): SourceArt { + // CLIP: CSFCHUNK container -> CHNKSQLi payload holds the layer table; raster tiles live in the + // CHNKExta chunks of the same byte stream, located via ExternalChunk offsets. + val databaseBytes = ClipContainer.extractSqliteDatabase(bytes) + return readDatabase(bytes, databaseBytes) + } + + /** + * Reads the Canvas + Layer tables, decodes each layer's raster from [fileBytes], and assembles + * SourceArt. The driver lifecycle (write a temp DB, open the platform driver, close, clean up) + * lives in [useClipDatabase]; everything here is platform-neutral. The embedded database already + * has its tables, so the generated SELECTs run WITHOUT Schema.create. + * + * @param ByteArray fileBytes The complete .clip file (raster tiles are read from it). + * @param ByteArray databaseBytes The raw "SQLite format 3" bytes from the CHNKSQLi chunk. + * @return SourceArt The parsed document. + */ + private fun readDatabase(fileBytes: ByteArray, databaseBytes: ByteArray): SourceArt = + useClipDatabase(databaseBytes) { database -> + val canvasRow = + database.clipQueries.selectCanvas().executeAsOneOrNull() + ?: throw IllegalArgumentException("CLIP database has no Canvas row") + val canvas = + ClipCanvas( + // CLIP: Canvas dimensions are REAL pixels; round to the integer pixel grid. + widthPx = (canvasRow.CanvasWidth ?: 0.0).roundToInt(), + heightPx = (canvasRow.CanvasHeight ?: 0.0).roundToInt(), + rootFolderId = canvasRow.CanvasRootFolder ?: 0L, + ) + + val rows = database.clipQueries.selectAllLayers().executeAsList().map { row -> row.toClipLayerRow() } + val rastersByMainId = decodeRasters(fileBytes, database, rows) + val textLayerIds = readTextLayerIds(database) + val tree = buildSourceTree(canvas, rows, rastersByMainId, textLayerIds) + ClipSourceArt( + widthPx = canvas.widthPx, + heightPx = canvas.heightPx, + layers = tree.layers, + groups = tree.groups, + ) + } + + /** + * Decodes every layer's base-resolution raster, keyed by layer MainId. + * + * Resolves each layer's external-chunk reference (Offscreen.BlockData) to a file offset via the + * ExternalChunk table, then hands the Attribute tile-index and chunk offset to [ClipRaster]. + * Layers with no decodable content are simply omitted (the tree builder falls back to a + * placeholder for them). + * + * @param ByteArray fileBytes The complete .clip file. + * @param ClipDatabase database The open CLIP database. + * @param List rows The layer rows (for per-layer canvas offsets). + * @return Map Decoded rasters keyed by layer MainId. + */ + private fun decodeRasters( + fileBytes: ByteArray, + database: ClipDatabase, + rows: List, + ): Map { + // CLIP: ExternalChunk.ExternalID ("extrnlid"+GUID) -> absolute CHNKExta file offset. + val offsetByExternalId = HashMap() + for (external in database.clipQueries.selectExternalChunks().executeAsList()) { + val externalId = external.ExternalID ?: continue + val offset = external.Offset ?: continue + offsetByExternalId[externalId.decodeToString()] = offset.toInt() + } + + val layerOffsetsByMainId = rows.associateBy { row -> row.mainId } + + // Per-layer mask offscreen (Attribute + external chunk offset), keyed by layer MainId. + val maskByMainId = HashMap() + for (maskRow in database.clipQueries.selectLayerMaskRasters().executeAsList()) { + val mainId = maskRow.MainId ?: continue + val attribute = maskRow.Attribute ?: continue + // BlockData is non-null by construction: selectLayerMaskRasters filters `O.BlockData IS NOT NULL`, + // so SQLDelight types it non-nullable (unlike MainId/Attribute, which carry no such predicate). + val blockData = maskRow.BlockData + val chunkOffset = offsetByExternalId[blockData.decodeToString()] ?: continue + maskByMainId[mainId] = MaskSource(chunkOffset = chunkOffset, attribute = attribute) + } + + val rasters = HashMap() + for (rasterRow in database.clipQueries.selectLayerRasters().executeAsList()) { + val mainId = rasterRow.MainId ?: continue + val attribute = rasterRow.Attribute ?: continue + // BlockData is non-null by construction: selectLayerRasters filters `O.BlockData IS NOT NULL`, + // so SQLDelight types it non-nullable (unlike MainId/Attribute, which carry no such predicate). + val blockData = rasterRow.BlockData + val chunkOffset = offsetByExternalId[blockData.decodeToString()] ?: continue + val layerRow = layerOffsetsByMainId[mainId] ?: continue + val mask = maskByMainId[mainId] + val decoded = + ClipRaster.decodeLayer( + fileBytes = fileBytes, + colorChunkOffset = chunkOffset, + colorAttribute = attribute, + maskChunkOffset = mask?.chunkOffset ?: -1, + maskAttribute = mask?.attribute, + // CLIP: tile-grid anchor = LayerOffset + LayerRenderOffscrOffset (canvas-aligned). + anchorX = (layerRow.offsetX + layerRow.renderOffscrX).toInt(), + anchorY = (layerRow.offsetY + layerRow.renderOffscrY).toInt(), + ) + if (decoded != null) { + rasters[mainId] = decoded + } + } + return rasters + } +} + +/** + * Reads the set of text-layer MainIds, tolerating older CLIP schemas that lack the TextLayerType + * column. The CLIP SQLite schema gains columns across Clip Studio versions, so this version-specific + * lookup is isolated and its failure is swallowed - an absent column simply means "no text layers + * identified" (they fall back to Vector). + * + * @param ClipDatabase database The open CLIP database. + * @return Set The text-layer MainIds, or empty if the column is absent. + */ +private fun readTextLayerIds(database: ClipDatabase): Set = + runCatching { + database.clipQueries.selectTextLayerIds().executeAsList().mapNotNull { row -> row.MainId }.toSet() + }.getOrDefault(emptySet()) + +/** A layer's mask offscreen: the external chunk offset and the mask Attribute tile index. */ +private class MaskSource(val chunkOffset: Int, val attribute: ByteArray) + +/** + * Maps a SQLDelight-generated Layer row to the internal [ClipLayerRow], defaulting NULL columns. + * + * @return ClipLayerRow The reduced, null-defaulted row. + */ +private fun SelectAllLayers.toClipLayerRow(): ClipLayerRow = + ClipLayerRow( + mainId = MainId ?: 0L, + name = LayerName ?: "", + folder = LayerFolder ?: 0L, + type = LayerType ?: 0L, + visibility = LayerVisibility ?: 1L, + opacity = LayerOpacity ?: 256L, // CLIP: absent opacity defaults to fully opaque (256). + composite = LayerComposite ?: 0L, + clip = LayerClip ?: 0L, + offsetX = LayerOffsetX ?: 0L, + offsetY = LayerOffsetY ?: 0L, + firstChildIndex = LayerFirstChildIndex ?: 0L, + nextIndex = LayerNextIndex ?: 0L, + uuid = LayerUuid, + renderOffscrX = LayerRenderOffscrOffsetX ?: 0L, + renderOffscrY = LayerRenderOffscrOffsetY ?: 0L, + ) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/Cmo3TargetVersion.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/Cmo3TargetVersion.kt new file mode 100644 index 0000000..2f8fca2 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/Cmo3TargetVersion.kt @@ -0,0 +1,69 @@ +package org.umamo.format.cmo3 + +/** + * The Cubism SDK version ladder that `CModelSource.targetVersionNo` denotes - the "Model target + * version selection" the official editor stores per document. + * + * The on-disk value is an era-specific LITERAL per version, not one formula: the editor keeps + * the encoding scheme that was current when each SDK shipped (3.x = major*1000 + minor*10, + * 4.0 = major*100000, 4.2+ = major*1_000_000 + minor*10_000). A single formula is wrong by + * observation - it would predict 3030000 for 3.3 where the editor writes 3030. + * Corpus evidence: + * + * Cubism 3.0 -> 3000 (modelD - older editors) + * Cubism 3.3 -> 3030 (ModelWith[out]OffscreenSDK3.3) + * Cubism 4.0 -> 400000 (EricaTamamo, ModelWithoutOffscreenSDK4.0) + * Cubism 4.2 -> 4020000 (ModelWithoutOffscreenSDK4.2) + * Cubism 5.0 -> 5000000 (modelB, modelC) + * Cubism 5.3 -> 5030000 (modelA, ModelWithOffscreen family) + * SDK(N/A) -> 9000000 (ModelWithoutOffscreenSDKNA) - see [LATEST_VERSION_NO] + * + * This type is pure CMO3 format knowledge: it knows nothing about editor gating policy or any + * runtime target - that mapping lives above `:format`. + */ +enum class Cmo3TargetVersion(val major: Int, val minor: Int, val versionNo: Int) { + // CMO3: CModelSource field targetVersionNo - one entry per observed literal (table above). + V30(3, 0, 3_000), + V33(3, 3, 3_030), + V40(4, 0, 400_000), + V42(4, 2, 4_020_000), + V50(5, 0, 5_000_000), + V53(5, 3, 5_030_000), + ; + + /** + * The value this version would take under the modern 4.2+ scheme, accepted as a tolerant-read + * alias because a future editor revision normalizing old projects would most plausibly emit it. + */ + private val modernVersionNo: Int + get() = major * 1_000_000 + minor * 10_000 + + companion object { + /** + * The value the editor writes for the "SDK(N/A)/Latest Cubism" selection - no version + * ceiling at all. CMO3: CModelSource field targetVersionNo. Deliberately not an enum + * entry: it names the ABSENCE of a target version, so [fromVersionNo] returns null for it + * and callers persist it through this constant. + */ + const val LATEST_VERSION_NO: Int = 9_000_000 + + /** + * Decodes a raw `targetVersionNo` into a known Cubism SDK target version. + * + * Matches the observed per-era literals first, then the modern-scheme equivalents as a + * tolerant-read fallback. Everything else is null: the field being absent, unknown values, + * and [LATEST_VERSION_NO] (a target-less document has no target version). + * + * @param Int? versionNo The raw field value, or null when the document carries none. + * @return Cmo3TargetVersion? The matching version, or null for no/unknown version. + */ + fun fromVersionNo(versionNo: Int?): Cmo3TargetVersion? { + // CMO3: CModelSource field targetVersionNo. + if (versionNo == null) { + return null + } + return entries.firstOrNull { it.versionNo == versionNo } + ?: entries.firstOrNull { it.modernVersionNo == versionNo } + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/Cmo3Version.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/Cmo3Version.kt new file mode 100644 index 0000000..2b20d54 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/Cmo3Version.kt @@ -0,0 +1,60 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.FormatVersion + +/** + * Known CMO3 schema generations Umamo supports. + * + * Modelled as a `sealed interface` so the compiler forces every `when` over versions to be + * exhaustive: adding a generation without handling it everywhere becomes a compile error, not a + * silent runtime gap. + * + * 対応する CMO3 スキーマ世代。sealed interface により `when` の網羅性をコンパイラが強制する。 + */ +sealed interface Cmo3Version : FormatVersion { + // `data object` = a singleton with generated equals/hashCode/toString. There is exactly one + // of each version, so an object (not a class) is the right modelling. + data object V3 : Cmo3Version { + override val label = "cmo3 / Cubism 3.x" + } + + data object V4 : Cmo3Version { + override val label = "cmo3 / Cubism 4.x" + } + + data object V5 : Cmo3Version { + override val label = "cmo3 / Cubism 5.x" + } + + /** + * Human-readable summary. The `when` has no `else` branch on purpose - the sealed hierarchy makes + * it exhaustive, so a future `V6` won't compile until handled here. + * + * @return String The summary sentence. + */ + override fun describe(): String = + when (this) { + V3 -> "Supported: $label" + V4 -> "Supported: $label" + V5 -> "Supported: $label" + } + + companion object { + /** + * Maps a `` attribute value to a known generation, or null. + * + * The attribute is a packed decimal whose leading digit is the Cubism major generation + * (corpus: 401010001 and 400050002 are 4.x, 501030000 is 5.x) - CMO3.md §3 Document shape. + * + * @param String raw The attribute text. + * @return Cmo3Version? The matching generation, or null for garbage or an unknown generation. + */ + fun fromFileFormatVersion(raw: String): Cmo3Version? = + when (raw.trim().toLongOrNull()?.div(100_000_000L)) { + 3L -> V3 + 4L -> V4 + 5L -> V5 + else -> null + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffArchive.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffArchive.kt new file mode 100644 index 0000000..5923518 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffArchive.kt @@ -0,0 +1,85 @@ +package org.umamo.format.cmo3.caff + +/** + * One logical file inside a CAFF archive. [content] is the fully-decoded payload + * (de-obfuscated and decompressed); compression/obfuscation describe how it is stored on disk. + * + * EN: Holds decoded bytes rather than a file offset. + * JA: オフセットではなくデコード済みバイトを保持する。 + * + * @see CMO3.md §1 FILE TABLE + */ +public class CaffEntry( + public val path: String, + public val tag: String, + public val content: ByteArray, + public val compression: CompressOption = CompressOption.RAW, + public val obfuscated: Boolean = true, +) + +/** + * The CAFF preview thumbnail. Most cmo3 files carry [present] == false (NO_PREVIEW). + * + * @see CMO3.md §1 PREVIEW + */ +public class CaffPreview( + public val imageType: ImageType, + public val colorType: ColorType, + public val width: Int, + public val height: Int, + /** The preview PNG bytes, or null when [imageType] is NO_PREVIEW. */ + public val png: ByteArray?, +) { + public val present: Boolean get() = imageType == ImageType.PNG && png != null + + public companion object { + /** A NO_PREVIEW placeholder (what real cmo3 files contain). */ + public fun none(): CaffPreview = + CaffPreview(ImageType.NO_PREVIEW, ColorType.NO_PREVIEW, 0, 0, null) + } +} + +/** + * An in-memory CAFF archive: header metadata, optional preview, and the ordered file entries. + * + * EN: Entry order is significant - the model serializer assigns file paths positionally, and + * consumers map them by order (e.g. the i-th CImageResource ↔ the i-th imageFileBuf*). + * + * @see CMO3.md §1 Container: CAFF + */ +public class CaffArchive( + /** 4-char format identifier; "----" for cmo3. */ + public val formatIdentifier: String = DEFAULT_FORMAT_IDENTIFIER, + /** 3-element format version; {0,0,0} for the sample. */ + public val formatVersion: IntArray = intArrayOf(0, 0, 0), + /** 3-element archive version; {0,0,0} for the sample. */ + public val archiveVersion: IntArray = intArrayOf(0, 0, 0), + /** XOR key; 0 => not obfuscated. */ + public val obfuscateKey: Int = 0, + public val preview: CaffPreview = CaffPreview.none(), + public val entries: List = emptyList(), +) { + /** Returns the first entry carrying [tag], or null. */ + public fun firstByTag(tag: String): CaffEntry? = entries.firstOrNull { it.tag == tag } + + /** Returns all entries carrying [tag], in archive order. */ + public fun allByTag(tag: String): List = entries.filter { it.tag == tag } + + /** Returns the first entry with an exact [path], or null. */ + public fun byPath(path: String): CaffEntry? = entries.firstOrNull { it.path == path } + + /** Returns a copy of this archive with a different entry list (other metadata unchanged). */ + public fun withEntries(entries: List): CaffArchive = + CaffArchive(formatIdentifier, formatVersion, archiveVersion, obfuscateKey, preview, entries) + + public companion object { + public const val MAGIC: String = "CAFF" + public const val DEFAULT_FORMAT_IDENTIFIER: String = "----" + + /** Archive tag for the serialized model document (main.xml). */ + public const val TAG_MAIN_XML: String = "main_xml" + + /** Archive tag for the preview image entry. */ + public const val TAG_PREVIEW: String = "preview" + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffCodec.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffCodec.kt new file mode 100644 index 0000000..4f207b9 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffCodec.kt @@ -0,0 +1,294 @@ +package org.umamo.format.cmo3.caff + +import org.umamo.format.cmo3.io.BinaryReader +import org.umamo.format.cmo3.io.BinaryWriter + +/** + * Reads and writes the CAFF container. Stateless; operates on whole byte arrays. + * + * EN: Layout is header (unobfuscated) -> preview block (unobfuscated) -> file table (obfuscated) + * -> concatenated blobs -> guard bytes 'b''c'. See CMO3.md §1 for the exact byte map. + * JA: ヘッダ → プレビュー → ファイルテーブル → ブロブ群 → ガードバイト。詳細は CMO3.md §1。 + * + * @see CMO3.md §1 Container: CAFF + */ +public object CaffCodec { + private const val HEADER_AND_PREVIEW_BYTES = 54 // header(26) + preview(28); blobs/table follow + private const val GUARD_BYTE_0 = 0x62 // 'b' + private const val GUARD_BYTE_1 = 0x63 // 'c' + + private class EntryMeta( + val path: String, + val tag: String, + val offset: Int, + val storedSize: Int, + val obfuscated: Boolean, + val compression: CompressOption, + ) + + private class HeaderAndTable( + val archiveVersion: IntArray, + val formatIdentifier: String, + val formatVersion: IntArray, + val obfuscateKey: Int, + val previewImageType: ImageType, + val previewColorType: ColorType, + val previewWidth: Int, + val previewHeight: Int, + val previewStartPos: Long, + val previewFileSize: Int, + val metas: List, + ) + + /** + * True if [candidateBytes] starts with the unobfuscated `CAFF` magic. + * + * The magic sits at +0x00 and is read with XOR key 0 (cleartext), so a leading-bytes compare is + * a sound sniff without parsing the container - CMO3.md §1. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether this looks like a CAFF container (e.g. a `.cmo3`). + */ + public fun isCaff(candidateBytes: ByteArray): Boolean { + val magic = CaffArchive.MAGIC.encodeToByteArray() // CAFF: magic @ +0x00, unobfuscated + if (candidateBytes.size < magic.size) { + return false + } + for (magicIndex in magic.indices) { + if (candidateBytes[magicIndex] != magic[magicIndex]) { + return false + } + } + return true + } + + /** + * Parses the header, preview block, and file table, leaving every blob undecoded. + * + * @param BinaryReader reader A reader positioned at the start of the file. + * @return HeaderAndTable The parsed container metadata and entry table. + */ + private fun readHeaderAndTable(reader: BinaryReader): HeaderAndTable { + // --- HEADER (not obfuscated) - CMO3.md §1 --- + val magic = reader.readBytes(4, 0).decodeToString() + require(magic == CaffArchive.MAGIC) { "not a CAFF file (magic=$magic)" } + val archiveVersion = IntArray(3) { reader.readU8(0) } + val formatIdentifier = reader.readBytes(4, 0).decodeToString() + val formatVersion = IntArray(3) { reader.readU8(0) } + val obfuscateKey = reader.readInt32(0) + reader.skip(8) + + // --- PREVIEW (not obfuscated) - CMO3.md §1 --- + val previewImageType = ImageType.fromTypeNo(reader.readU8(0)) + val previewColorType = ColorType.fromTypeNo(reader.readU8(0)) + reader.skip(2) + val previewWidth = reader.readInt16(0).toInt() + val previewHeight = reader.readInt16(0).toInt() + val previewStartPos = reader.readInt64(0) and 0xFFFFFFFFL + val previewFileSize = reader.readInt32(0) + reader.skip(8) + + // --- FILE TABLE (obfuscated with obfuscateKey) - CMO3.md §1 --- + val count = reader.readInt32(obfuscateKey) + val metas = ArrayList(count) + for (entryIndex in 0 until count) { + val path = reader.readString(obfuscateKey) + val tag = reader.readString(obfuscateKey) + // CMO3: startPos high word is a writer artifact; the real offset is the low 32 bits. + val startPos = reader.readInt64(obfuscateKey) and 0xFFFFFFFFL + val fileSize = reader.readInt32(obfuscateKey) + val obfuscated = reader.readBool(obfuscateKey) + val compression = CompressOption.fromSerializeNo(reader.readU8(obfuscateKey)) + reader.skip(8) + metas.add(EntryMeta(path, tag, startPos.toInt(), fileSize, obfuscated, compression)) + } + + return HeaderAndTable( + archiveVersion, + formatIdentifier, + formatVersion, + obfuscateKey, + previewImageType, + previewColorType, + previewWidth, + previewHeight, + previewStartPos, + previewFileSize, + metas, + ) + } + + /** + * Slices, de-obfuscates, and decompresses one entry's blob. + * + * @param BinaryReader reader The reader over the full file bytes. + * @param EntryMeta meta The entry's file-table record. + * @param Int obfuscateKey The archive's XOR key. + * @return CaffEntry The decoded entry. + */ + private fun decodeEntry(reader: BinaryReader, meta: EntryMeta, obfuscateKey: Int): CaffEntry { + reader.seek(meta.offset) + val stored = reader.readBytes(meta.storedSize, if (meta.obfuscated) obfuscateKey else 0) + val content = if (meta.compression.isCompressed) CaffZip.unzipSingle(stored) else stored + return CaffEntry(meta.path, meta.tag, content, meta.compression, meta.obfuscated) + } + + /** + * Parses a CAFF archive from its raw bytes, decoding every entry's payload. + * + * @param ByteArray bytes The full .cmo3 (or other CAFF) file contents. + * @return CaffArchive The decoded archive. + */ + public fun read(bytes: ByteArray): CaffArchive { + val reader = BinaryReader(bytes) + val parsed = readHeaderAndTable(reader) + + // --- BLOBS: slice, de-obfuscate, decompress --- + val entries = parsed.metas.map { meta -> decodeEntry(reader, meta, parsed.obfuscateKey) } + + // Preview blob (RAW, not obfuscated) + val preview = + if (parsed.previewImageType == ImageType.PNG && parsed.previewFileSize > 0) { + reader.seek(parsed.previewStartPos.toInt()) + val png = reader.readBytes(parsed.previewFileSize, 0) + CaffPreview(parsed.previewImageType, parsed.previewColorType, parsed.previewWidth, parsed.previewHeight, png) + } else { + CaffPreview(parsed.previewImageType, parsed.previewColorType, parsed.previewWidth, parsed.previewHeight, null) + } + + return CaffArchive( + parsed.formatIdentifier, + parsed.formatVersion, + parsed.archiveVersion, + parsed.obfuscateKey, + preview, + entries, + ) + } + + /** + * Decodes only the first entry carrying [tag], leaving every other blob untouched. + * + * A cheap probe next to [read]: the header and file table are parsed (CMO3.md §1 FILE TABLE), but + * just the matching blob is de-obfuscated and decompressed - a version sniff over a `.cmo3` skips + * inflating the embedded layer PNGs this way. + * + * @param ByteArray bytes The full .cmo3 (or other CAFF) file contents. + * @param String tag The archive tag to look up (e.g. [CaffArchive.TAG_MAIN_XML]). + * @return CaffEntry? The decoded entry, or null when no entry carries the tag. + */ + public fun readFirstEntryByTag(bytes: ByteArray, tag: String): CaffEntry? { + val reader = BinaryReader(bytes) + val parsed = readHeaderAndTable(reader) + val meta = parsed.metas.firstOrNull { it.tag == tag } ?: return null + return decodeEntry(reader, meta, parsed.obfuscateKey) + } + + /** + * Serializes an archive back into CAFF bytes. Offsets are computed in one pass (no seek-back + * fixup) and written as clean 64-bit values (high word 0). + * + * @param CaffArchive archive The archive to encode. + * @return ByteArray The complete CAFF file bytes. + */ + public fun write(archive: CaffArchive): ByteArray { + val key = archive.obfuscateKey + + // Pre-encode each blob (compress, but XOR happens at write time via writeBytes). + val storedBlobs = + archive.entries.map { entry -> + if (entry.compression.isCompressed) { + CaffZip.zipSingle(entry.content, entry.compression.zipLevel) + } else { + entry.content + } + } + + // Compute the table size so we know where blobs start, then assign sequential offsets. + var tableBytes = 4 // count + for (entry in archive.entries) { + tableBytes += varIntSize(entry.path.encodeToByteArray().size) + entry.path.encodeToByteArray().size + tableBytes += varIntSize(entry.tag.encodeToByteArray().size) + entry.tag.encodeToByteArray().size + tableBytes += 8 + 4 + 1 + 1 + 8 // startPos, fileSize, isObfuscated, compress, skip(8) + } + val blobStart = HEADER_AND_PREVIEW_BYTES + tableBytes + val offsets = IntArray(archive.entries.size) + var cursor = blobStart + for (index in storedBlobs.indices) { + offsets[index] = cursor + cursor += storedBlobs[index].size + } + + val writer = BinaryWriter(cursor + 2) + + // --- HEADER --- + writer.writeBytes(CaffArchive.MAGIC.encodeToByteArray(), 0) + for (versionPart in 0 until 3) writer.writeU8(archive.archiveVersion[versionPart], 0) + writer.writeBytes(padFour(archive.formatIdentifier), 0) + for (versionPart in 0 until 3) writer.writeU8(archive.formatVersion[versionPart], 0) + writer.writeInt32(key, 0) + writer.skip(8) + + // --- PREVIEW --- + val previewEntryIndex = archive.entries.indexOfFirst { it.tag == CaffArchive.TAG_PREVIEW } + if (archive.preview.present && previewEntryIndex >= 0) { + writer.writeU8(ImageType.PNG.typeNo, 0) + writer.writeU8(archive.preview.colorType.typeNo, 0) + writer.skip(2) + writer.writeInt16(archive.preview.width, 0) + writer.writeInt16(archive.preview.height, 0) + writer.writeInt64(offsets[previewEntryIndex].toLong(), 0) + writer.writeInt32(storedBlobs[previewEntryIndex].size, 0) + writer.skip(8) + } else { + writer.writeU8(ImageType.NO_PREVIEW.typeNo, 0) + writer.writeU8(ColorType.NO_PREVIEW.typeNo, 0) + writer.skip(2) + writer.writeInt16(0, 0) + writer.writeInt16(0, 0) + writer.writeInt64(0, 0) + writer.writeInt32(0, 0) + writer.skip(8) + } + + // --- FILE TABLE --- + writer.writeInt32(archive.entries.size, key) + for (index in archive.entries.indices) { + val entry = archive.entries[index] + writer.writeString(entry.path, key) + writer.writeString(entry.tag, key) + writer.writeInt64(offsets[index].toLong(), key) + writer.writeInt32(storedBlobs[index].size, key) + writer.writeBool(entry.obfuscated, key) + writer.writeU8(entry.compression.serializeNo, key) + writer.skip(8) + } + + // --- BLOBS --- + for (index in archive.entries.indices) { + val entry = archive.entries[index] + writer.writeBytes(storedBlobs[index], if (entry.obfuscated) key else 0) + } + + // --- GUARD BYTES (not obfuscated) --- + writer.writeU8(GUARD_BYTE_0, 0) + writer.writeU8(GUARD_BYTE_1, 0) + + return writer.toByteArray() + } + + private fun varIntSize(value: Int): Int = + when { + value < 0x80 -> 1 + value < 0x4000 -> 2 + value < 0x200000 -> 3 + value < 0x10000000 -> 4 + else -> throw IllegalArgumentException("varint too large: $value") + } + + private fun padFour(identifier: String): ByteArray { + val bytes = identifier.encodeToByteArray() + require(bytes.size == 4) { "format identifier must be 4 bytes: '$identifier'" } + return bytes + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffEnums.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffEnums.kt new file mode 100644 index 0000000..2bb5f65 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffEnums.kt @@ -0,0 +1,84 @@ +package org.umamo.format.cmo3.caff + +/** + * Preview image encoding, as stored in the CAFF header preview block. + * + * EN: typeNo is the on-disk byte value. + * + * @see CMO3.md §1 PREVIEW + */ +public enum class ImageType(public val typeNo: Int) { + NOT_INIT(0), + PNG(1), + NO_PREVIEW(127), + ; + + public companion object { + /** + * Resolves a preview ImageType from its on-disk byte. + * + * @param Int typeNo The stored byte value. + * @return ImageType The matching constant. + */ + public fun fromTypeNo(typeNo: Int): ImageType = + entries.firstOrNull { it.typeNo == typeNo } + ?: throw IllegalArgumentException("unknown ImageType $typeNo") + } +} + +/** + * Preview pixel layout, as stored in the CAFF header preview block. + * + * EN: Preview pixel layout. + * + * @see CMO3.md §1 PREVIEW + */ +public enum class ColorType(public val typeNo: Int) { + NOT_INIT(0), + ARGB(1), + RGB(2), + NO_PREVIEW(127), + ; + + public companion object { + /** + * Resolves a preview ColorType from its on-disk byte. + * + * @param Int typeNo The stored byte value. + * @return ColorType The matching constant. + */ + public fun fromTypeNo(typeNo: Int): ColorType = + entries.firstOrNull { it.typeNo == typeNo } + ?: throw IllegalArgumentException("unknown ColorType $typeNo") + } +} + +/** + * Per-entry storage mode. serializeNo is the on-disk byte; zipLevel is the java.util.zip level + * used when (re)compressing FAST/SMALL entries. + * + * EN: RAW = stored as-is (already-compressed PNGs); + * FAST/SMALL = a single-entry ("contents") Java Zip stream. + * + * @see CMO3.md §1 Compression + */ +public enum class CompressOption(public val serializeNo: Int, public val zipLevel: Int) { + RAW(16, 0), + FAST(33, 1), + SMALL(37, 5), + ; + + public val isCompressed: Boolean get() = this != RAW + + public companion object { + /** + * Resolves a CompressOption from its on-disk serializeNo byte. + * + * @param Int serializeNo The stored byte value. + * @return CompressOption The matching constant. + */ + public fun fromSerializeNo(serializeNo: Int): CompressOption = + entries.firstOrNull { it.serializeNo == serializeNo } + ?: throw IllegalArgumentException("unknown CompressOption $serializeNo") + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffZip.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffZip.kt new file mode 100644 index 0000000..a6b9a46 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/caff/CaffZip.kt @@ -0,0 +1,152 @@ +package org.umamo.format.cmo3.caff + +import kotlinx.datetime.TimeZone +import kotlinx.datetime.number +import kotlinx.datetime.toLocalDateTime +import okio.Buffer +import org.umamo.format.binary.ByteReader +import org.umamo.format.binary.Crc32 +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.deflateRawDeflate +import org.umamo.format.binary.inflateRawDeflate +import kotlin.time.Clock + +/** + * The single-entry zip framing CAFF wraps FAST/SMALL blobs in. + * + * A CAFF compressed blob is a PARTIAL zip stream holding one entry named "contents": a local file + * header, a raw DEFLATE payload, a data descriptor, and then the end of the blob. It carries no + * central directory and no EOCD — measured on the corpus, not assumed (CMO3.md §1 has the byte + * layout and the evidence). So this is not `ZipOutputStream` output and cannot be produced by it: + * that class always appends both records on close. The framing is pure byte manipulation instead. + * + * @see CMO3.md §1 Compression + */ +internal object CaffZip { + // CMO3: the compressed blob is a single-entry zip stream; the entry is always named "contents". + private val ENTRY_NAME = "contents".encodeToByteArray() + + // ZIP: general-purpose flags. Bit 3 (0x08) says the CRC and sizes follow in a data descriptor + // rather than the local header; bit 11 (0x0800) declares the name UTF-8. The editor sets both + // (measured: 0x0808), so a real .cmo3 carries zeroed sizes up front — a reader that trusts them + // reads nothing. + private const val FLAGS = ZipRecords.FLAG_DATA_DESCRIPTOR or ZipRecords.FLAG_UTF8_NAME + + /** + * Inflates a single-entry CAFF zip stream back to the raw payload. + * + * Reads only what the framing guarantees: the local header's name/extra lengths locate the + * payload, and the DEFLATE stream ends itself. The sizes in the local header are ignored because + * the editor zeroes them (flag bit 3); the real ones are in the trailing data descriptor, which is + * data the inflater simply stops before. + * + * @param ByteArray zipStream The full zip stream bytes (already de-obfuscated). + * @return ByteArray The decompressed "contents" payload. + */ + fun unzipSingle(zipStream: ByteArray): ByteArray { + require(zipStream.size >= ZipRecords.LOCAL_HEADER_SIZE) { "Empty CAFF zip stream" } + val reader = ByteReader(zipStream, littleEndian = true) + require(reader.u32(0) == ZipRecords.LOCAL_HEADER_SIGNATURE.toLong()) { "CAFF blob is not a zip local file header" } + // ZIP: local header @ +0x1A name length, @ +0x1C extra length; the payload follows both. + val nameLength = reader.u16(26) + val extraLength = reader.u16(28) + val payloadStart = ZipRecords.LOCAL_HEADER_SIZE + nameLength + extraLength + require(payloadStart <= zipStream.size) { "Truncated CAFF zip local header" } + return inflateRawDeflate(zipStream, payloadStart, zipStream.size - payloadStart, declaredSize(reader)) + } + + /** + * The uncompressed size the blob's trailing data descriptor declares, else [Int.MAX_VALUE]. + * + * This is the only output bound the format offers. The CAFF file table's storedSize delimits the + * INPUT — compressed bytes — and says nothing about how far they inflate: the corpus blobs expand + * 3.5x to 6.7x, but DEFLATE reaches ~1000:1, so a crafted entry could otherwise balloon toward + * gigabytes in memory before anyone notices. A blob ends at its data descriptor (CMO3.md §1 has + * the measured layout and the per-sample numbers), and that record's usize field is exactly the + * bound wanted. + * + * Treated as a cap, never a promise: a descriptor that lies truncates only its own entry, and + * anything unrecognizable falls back to unbounded rather than corrupting an otherwise valid read. + * + * @param ByteReader reader The full blob, little-endian. + * @return Int The declared uncompressed size, or Int.MAX_VALUE when no usable descriptor is found. + */ + private fun declaredSize(reader: ByteReader): Int { + val blobSize = reader.bytes.size + if (blobSize < ZipRecords.LOCAL_HEADER_SIZE + ZipRecords.DATA_DESCRIPTOR_SIZE) { + return Int.MAX_VALUE + } + val descriptorStart = blobSize - ZipRecords.DATA_DESCRIPTOR_SIZE + if (reader.u32(descriptorStart) != ZipRecords.DATA_DESCRIPTOR_SIGNATURE.toLong()) { + return Int.MAX_VALUE + } + // ZIP: data descriptor @ +0x0C uncompressed size. Zero is what the LOCAL header carries, so a + // zero here reads as "not really a descriptor"; past Int range needs zip64 and cannot be a + // ByteArray length anyway. Both fall back rather than truncate. + val declared = reader.u32(descriptorStart + 12) + return if (declared in 1..Int.MAX_VALUE.toLong()) declared.toInt() else Int.MAX_VALUE + } + + /** + * Wraps [contents] in a single-entry ("contents") zip stream at the given level. + * + * @param ByteArray contents The raw payload to compress. + * @param Int level DEFLATE level (CompressOption.zipLevel). + * @param Int dosDateTime The MS-DOS modification stamp: date in the high 16 bits, time in the + * low 16. Defaults to the local wall clock, which is what the editor + * writes; injectable so tests can assert on the emitted bytes. + * @return ByteArray The zip stream bytes (before any obfuscation). + */ + fun zipSingle(contents: ByteArray, level: Int, dosDateTime: Int = currentDosDateTime()): ByteArray { + val deflated = deflateRawDeflate(contents, level) + val checksum = Crc32().also { it.update(contents) }.value.toInt() + val out = Buffer() + + // ZIP: local file header (APPNOTE.TXT 4.3.7). + // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT + out.writeIntLe(ZipRecords.LOCAL_HEADER_SIGNATURE) + // ZIP: version 2.0 — the minimum that understands DEFLATE, and what Java writes. + out.writeShortLe(ZipRecords.VERSION_DEFLATED) + out.writeShortLe(FLAGS) + out.writeShortLe(ZipRecords.METHOD_DEFLATED) + // ZIP: local header @ +0x0A time, @ +0x0C date. Both little-endian 16-bit, in LOCAL time. + out.writeShortLe(dosDateTime and 0xFFFF) + out.writeShortLe((dosDateTime ushr 16) and 0xFFFF) + // Zeroed here and carried in the data descriptor instead — that is what flag bit 3 means. + out.writeIntLe(0) + out.writeIntLe(0) + out.writeIntLe(0) + out.writeShortLe(ENTRY_NAME.size) + out.writeShortLe(0) + out.write(ENTRY_NAME) + + out.write(deflated) + + // ZIP: data descriptor (APPNOTE.TXT 4.3.9) — the real CRC and sizes. + out.writeIntLe(ZipRecords.DATA_DESCRIPTOR_SIGNATURE) + out.writeIntLe(checksum) + out.writeIntLe(deflated.size) + out.writeIntLe(contents.size) + + // Ends here — no central directory, no end-of-central-directory record. That is not an + // omission, it is what a CAFF blob measurably is: de-obfuscating the corpus sample finds one + // PK\x03\x04 and one PK\x07\x08, and zero of either record (CMO3.md §1). Re-emitting without + // them reproduces the original's exact file size, which is the same fact from the other side. + // Writing them would append 76 bytes the format does not carry, growing the file on each save + // — and is why this cannot be ZipOutputStream, which emits both unconditionally on close. + return out.readByteArray() + } + + /** + * The local wall clock now, as an MS-DOS date/time pair. + * + * Local, not UTC: a DOS timestamp has no zone, and the editor writes local time — matching it is + * the point of stamping a clock here at all. + * + * @return Int The stamp: date in the high 16 bits, time in the low 16. + */ + private fun currentDosDateTime(): Int { + val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) + return ZipRecords.dosDateTimeOf(now.year, now.month.number, now.day, now.hour, now.minute, now.second) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/io/BinaryReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/io/BinaryReader.kt new file mode 100644 index 0000000..d43dd1b --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/io/BinaryReader.kt @@ -0,0 +1,163 @@ +package org.umamo.format.cmo3.io + +/** + * Big-endian, XOR-deobfuscating reader over a byte array. + * + * EN: All multi-byte integers + * are big-endian; an obfuscation key XORs values by width (byte=key&0xFF, short=key&0xFFFF, + * int=key, long=(key<<32)|key). A key of 0 means "not obfuscated". + * JA: 多バイト整数はビッグエンディアン。難読化キーで幅ごとに XOR する。 + * + * @see CMO3.md §1 Container: CAFF + */ +public class BinaryReader(private val data: ByteArray) { + /** Current read cursor, in bytes from the start of [data]. */ + public var position: Int = 0 + private set + + /** Total length of the backing buffer. */ + public val size: Int get() = data.size + + /** + * Moves the cursor to an absolute byte offset. + * + * @param Int offset Absolute position to seek to. + */ + public fun seek(offset: Int) { + position = offset + } + + /** + * Advances the cursor by [count] bytes without interpreting them. + * + * EN: CAFF "skip(n)" is a literal reserved gap, NOT alignment padding. + * + * @param Int count Number of bytes to skip. + */ + public fun skip(count: Int) { + position += count + } + + /** + * Reads one unsigned byte (0..255), optionally XOR-deobfuscated. + * + * @param Int key Obfuscation key (0 = none). + * @return Int The byte value in 0..255. + */ + public fun readU8(key: Int): Int { + val raw = data[position].toInt() and 0xFF + position += 1 + return raw xor (key and 0xFF) + } + + /** + * Reads a big-endian signed 16-bit integer. + * + * @param Int key Obfuscation key (0 = none). + * @return Short The decoded value. + */ + public fun readInt16(key: Int): Short { + val high = data[position].toInt() and 0xFF + val low = data[position + 1].toInt() and 0xFF + position += 2 + val combined = (high shl 8) or low + return (combined xor (key and 0xFFFF)).toShort() + } + + /** + * Reads a big-endian signed 32-bit integer. + * + * @param Int key Obfuscation key (0 = none). + * @return Int The decoded value. + */ + public fun readInt32(key: Int): Int { + val byte0 = data[position].toInt() and 0xFF + val byte1 = data[position + 1].toInt() and 0xFF + val byte2 = data[position + 2].toInt() and 0xFF + val byte3 = data[position + 3].toInt() and 0xFF + position += 4 + val combined = (byte0 shl 24) or (byte1 shl 16) or (byte2 shl 8) or byte3 + return combined xor key + } + + /** + * Reads a big-endian signed 64-bit integer. + * + * @param Int key Obfuscation key (0 = none). + * @return Long The decoded value. + */ + public fun readInt64(key: Int): Long { + var combined = 0L + for (byteIndex in 0 until 8) { + combined = (combined shl 8) or (data[position + byteIndex].toLong() and 0xFFL) + } + position += 8 + // CMO3: the editor's 64-bit mask ORs the SIGN-EXTENDED key (see BinaryWriter.writeInt64); + // a negative key floods the high dword with ones. + val mask = (key.toLong() shl 32) or key.toLong() + return combined xor mask + } + + /** + * Reads a boolean stored as a single byte (non-zero = true). + * + * @param Int key Obfuscation key (0 = none). + * @return Boolean The decoded flag. + */ + public fun readBool(key: Int): Boolean = readU8(key) != 0 + + /** + * Reads a 7-bit, MSB-first variable-length unsigned integer. + * + * EN: A 7-bit variable-length integer: each byte carries 7 value bits; + * the high bit signals continuation. Used as the length prefix for strings. + * + * @param Int key Obfuscation key (0 = none). + * @return Int The decoded length/count. + */ + public fun readVarInt(key: Int): Int { + val byte0 = readU8(key) + if (byte0 and 0x80 == 0) return byte0 and 0xFF + val byte1 = readU8(key) + if (byte1 and 0x80 == 0) return ((byte0 and 0x7F) shl 7) or (byte1 and 0x7F) + val byte2 = readU8(key) + if (byte2 and 0x80 == 0) { + return ((byte0 and 0x7F) shl 14) or ((byte1 and 0x7F) shl 7) or (byte2 and 0xFF) + } + val byte3 = readU8(key) + if (byte3 and 0x80 == 0) { + return ((byte0 and 0x7F) shl 21) or ((byte1 and 0x7F) shl 14) or + ((byte2 and 0x7F) shl 7) or (byte3 and 0xFF) + } + throw IllegalStateException("varint exceeds 4 bytes at offset ${position - 4}") + } + + /** + * Reads a UTF-8 string: a [readVarInt] byte length followed by that many XOR'd UTF-8 bytes. + * + * @param Int key Obfuscation key (0 = none). + * @return String The decoded string. + */ + public fun readString(key: Int): String { + val length = readVarInt(key) + val raw = readBytes(length, key) + return raw.decodeToString() + } + + /** + * Reads [count] raw bytes, optionally XOR-deobfuscating each with key&0xFF. + * + * @param Int count Number of bytes to read. + * @param Int key Obfuscation key (0 = none). + * @return ByteArray A freshly allocated array of the (decoded) bytes. + */ + public fun readBytes(count: Int, key: Int): ByteArray { + val out = ByteArray(count) + val byteKey = (key and 0xFF).toByte() + for (index in 0 until count) { + out[index] = if (key == 0) data[position + index] else (data[position + index].toInt() xor byteKey.toInt()).toByte() + } + position += count + return out + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/io/BinaryWriter.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/io/BinaryWriter.kt new file mode 100644 index 0000000..f9ce20c --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/io/BinaryWriter.kt @@ -0,0 +1,184 @@ +package org.umamo.format.cmo3.io + +/** + * Big-endian, XOR-obfuscating writer into a growable byte buffer. + * + * EN: Inverse of [BinaryReader]; + * same big-endian + width-keyed XOR conventions. + * JA: [BinaryReader] の逆操作。 + * + * @see CMO3.md §1 Container: CAFF + */ +public class BinaryWriter(initialCapacity: Int = 64 * 1024) { + private var buffer = ByteArray(initialCapacity) + + /** Number of bytes written so far (also the current write cursor). */ + public var position: Int = 0 + private set + + private fun ensure(additional: Int) { + val needed = position + additional + if (needed > buffer.size) { + var newSize = buffer.size * 2 + if (newSize < needed) newSize = needed + buffer = buffer.copyOf(newSize) + } + } + + /** Returns a copy of the written bytes (length == [position]). */ + public fun toByteArray(): ByteArray = buffer.copyOf(position) + + /** + * Writes [count] zero bytes - a CAFF reserved "skip(n)" gap. + * + * @param Int count Number of zero bytes to emit. + */ + public fun skip(count: Int) { + ensure(count) + position += count + } + + /** + * Overwrites an already-written big-endian int32 at an absolute offset (used for back-patching + * file offsets without a second streaming pass). + * + * @param Int offset Absolute byte offset of the 4-byte slot. + * @param Int value Value to store (already XOR-encoded by the caller if needed). + */ + public fun patchInt32(offset: Int, value: Int) { + buffer[offset] = (value ushr 24).toByte() + buffer[offset + 1] = (value ushr 16).toByte() + buffer[offset + 2] = (value ushr 8).toByte() + buffer[offset + 3] = value.toByte() + } + + /** + * Writes one byte, XOR-obfuscated with key&0xFF. + * + * @param Int value Byte value (low 8 bits used). + * @param Int key Obfuscation key (0 = none). + */ + public fun writeU8(value: Int, key: Int) { + ensure(1) + buffer[position] = (value xor (key and 0xFF)).toByte() + position += 1 + } + + /** + * Writes a big-endian 16-bit integer, XOR-obfuscated with key&0xFFFF. + * + * @param Int value Value to write (low 16 bits used). + * @param Int key Obfuscation key (0 = none). + */ + public fun writeInt16(value: Int, key: Int) { + ensure(2) + val encoded = value xor (key and 0xFFFF) + buffer[position] = (encoded ushr 8).toByte() + buffer[position + 1] = encoded.toByte() + position += 2 + } + + /** + * Writes a big-endian 32-bit integer, XOR-obfuscated with the full key. + * + * @param Int value Value to write. + * @param Int key Obfuscation key (0 = none). + */ + public fun writeInt32(value: Int, key: Int) { + ensure(4) + val encoded = value xor key + buffer[position] = (encoded ushr 24).toByte() + buffer[position + 1] = (encoded ushr 16).toByte() + buffer[position + 2] = (encoded ushr 8).toByte() + buffer[position + 3] = encoded.toByte() + position += 4 + } + + /** + * Writes a big-endian 64-bit integer, XOR-obfuscated with ((long) key << 32) | key. + * + * CMO3: the editor's 64-bit mask ORs the SIGN-EXTENDED key, so a negative key floods the + * high dword to all-ones (corpus-pinned: every negative-key file stores 0xFFFFFFFF high + * dwords for sub-4GB offsets). A zero-extended mask matches only positive keys - the + * official reader then decodes garbage offsets and reports the file as empty. + * + * @param Long value Value to write. + * @param Int key Obfuscation key (0 = none). + */ + public fun writeInt64(value: Long, key: Int) { + ensure(8) + val mask = (key.toLong() shl 32) or key.toLong() + val encoded = value xor mask + for (byteIndex in 0 until 8) { + buffer[position + byteIndex] = (encoded ushr (56 - 8 * byteIndex)).toByte() + } + position += 8 + } + + /** + * Writes a boolean as a single XOR'd byte (1/0). + * + * @param Boolean value Flag to write. + * @param Int key Obfuscation key (0 = none). + */ + public fun writeBool(value: Boolean, key: Int): Unit = writeU8(if (value) 1 else 0, key) + + /** + * Writes a 7-bit, MSB-first variable-length unsigned integer (inverse of [BinaryReader.readVarInt]). + * + * @param Int value Non-negative value to encode. + * @param Int key Obfuscation key (0 = none). + */ + public fun writeVarInt(value: Int, key: Int) { + when { + value < 0x80 -> writeU8(value, key) + value < 0x4000 -> { + writeU8((value shr 7) and 0x7F or 0x80, key) + writeU8(value and 0x7F, key) + } + value < 0x200000 -> { + writeU8((value shr 14) and 0x7F or 0x80, key) + writeU8((value shr 7) and 0x7F or 0x80, key) + writeU8(value and 0x7F, key) + } + value < 0x10000000 -> { + writeU8((value shr 21) and 0x7F or 0x80, key) + writeU8((value shr 14) and 0x7F or 0x80, key) + writeU8((value shr 7) and 0x7F or 0x80, key) + writeU8(value and 0x7F, key) + } + else -> throw IllegalArgumentException("varint too large: $value") + } + } + + /** + * Writes a UTF-8 string: a [writeVarInt] length prefix followed by the XOR'd UTF-8 bytes. + * + * @param String value String to write. + * @param Int key Obfuscation key (0 = none). + */ + public fun writeString(value: String, key: Int) { + val utf8 = value.encodeToByteArray() + writeVarInt(utf8.size, key) + writeBytes(utf8, key) + } + + /** + * Writes raw bytes, optionally XOR-obfuscating each with key&0xFF. + * + * @param ByteArray bytes Bytes to write. + * @param Int key Obfuscation key (0 = none). + */ + public fun writeBytes(bytes: ByteArray, key: Int) { + ensure(bytes.size) + if (key == 0) { + bytes.copyInto(buffer, position) + } else { + val byteKey = key and 0xFF + for (index in bytes.indices) { + buffer[position + index] = (bytes[index].toInt() xor byteKey).toByte() + } + } + position += bytes.size + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/.editorconfig b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/.editorconfig new file mode 100644 index 0000000..c1f8cab --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/.editorconfig @@ -0,0 +1,11 @@ +# CMO3 model types mirror the Live2D on-disk schema VERBATIM. The reflection-based serializer +# derives each XML element/attribute name directly from the Kotlin class/property name, so +# identifiers like `imageFileBuf_size`, `CBlend_Normal`, `_modelImageGuid`, and `m00` are dictated +# by the format — renaming them to satisfy ktlint would break the CMO3 round-trip. This is the same +# "localize chrome/display, never format-level identifiers" rule from CLAUDE.md, applied to code. +# Scope is deliberately just this model/ subtree; the rest of the module stays strict. +# See docs/formats/CMO3.md §3 (Serializer mechanics). +[*.kt] +ktlint_standard_property-naming = disabled +ktlint_standard_backing-property-naming = disabled +ktlint_standard_class-naming = disabled diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/custom/CustomClasses.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/custom/CustomClasses.kt new file mode 100644 index 0000000..2185e17 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/custom/CustomClasses.kt @@ -0,0 +1,265 @@ +package org.umamo.format.cmo3.model.custom + +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.cmo3.serialize.annotations.DontSerializeIfDefault +import org.umamo.format.cmo3.serialize.annotations.SerialAttribute +import org.umamo.format.cmo3.serialize.annotations.SerialName +import org.umamo.format.cmo3.serialize.annotations.SerialTag + +/* + * Value/leaf classes whose scalar fields are written as attributes, modelled as reflective classes with + * @SerialAttribute for the fields the editor writes as attributes. Field order mirrors each class's + * serialize() method (verified by the byte-identity gate). Object fields are Any? - they reference + * already-typed or still-verbatim objects and round-trip by identity regardless. + */ + +/** A float RGBA color: `red`/`green`/`blue`/`alpha` float attributes. */ +@SerialTag("CFloatColor") +public class CFloatColor { + @SerialAttribute + public var red: Float = 0f + + @SerialAttribute + public var green: Float = 0f + + @SerialAttribute + public var blue: Float = 0f + + @SerialAttribute + public var alpha: Float = 0f +} + +/** A label color: `customizedColorInt` attribute + a `CLabelColorType` enum child. */ +@SerialTag("CLabelColor") +public class CLabelColor { + @SerialAttribute + public var customizedColorInt: Int = 0 + public var labelType: Any? = null +} + +/* + * Deformer original-shape snapshots. I believe that that official Cubism Editor's Java subclasses shadow + * the same field names declared on ACDeformerOriginalShape, re-emitting them at this level too; + * they are modelled as distinct Kotlin properties carrying the on-disk name via @SerialName so that + * both levels round-trip independently. + */ + +/** A warp-deformer original shape, extending the generated ACDeformerOriginalShape. */ +@SerialTag("WarpDeformerOriginalShape") +public class WarpDeformerOriginalShape : org.umamo.format.cmo3.model.gen.ACDeformerOriginalShape() { + @SerialName("lastUpdatedTimeString") + public var ownLastUpdatedTimeString: String? = null + + @SerialName("autoRefreshIsAvailable") + public var ownAutoRefreshIsAvailable: Boolean = false + + @SerialName("creationMethod") + public var ownCreationMethod: Any? = null + + @SerialName("col") + public var ownCol: Int = 0 + + @SerialName("row") + public var ownRow: Int = 0 +} + +/** A rotation-deformer original shape, extending the generated ACDeformerOriginalShape. */ +@SerialTag("RotationDeformerOriginalShape") +public class RotationDeformerOriginalShape : org.umamo.format.cmo3.model.gen.ACDeformerOriginalShape() { + @SerialName("lastUpdatedTimeString") + public var ownLastUpdatedTimeString: String? = null + + @SerialName("autoRefreshIsAvailable") + public var ownAutoRefreshIsAvailable: Boolean = false + + @SerialName("creationMethod") + public var ownCreationMethod: Any? = null + + @SerialName("col") + public var ownCol: Int = 0 + + @SerialName("row") + public var ownRow: Int = 0 +} + +/** A width/height size value: `width`, `height` attributes. */ +@SerialTag("CSize") +public class CSize { + @SerialAttribute + public var width: Int = 0 + + @SerialAttribute + public var height: Int = 0 +} + +/** + * A rotation-deformer keyform: 4 float + 2 bool attributes, + * extending ACDeformerForm (the engine nests its `` automatically). + */ +@SerialTag("CRotationDeformerForm") +public class CRotationDeformerForm : org.umamo.format.cmo3.model.gen.ACDeformerForm() { + @SerialAttribute + public var angle: Float = 0f + + @SerialAttribute + public var originX: Float = 0f + + @SerialAttribute + public var originY: Float = 0f + + @SerialAttribute + public var scale: Float = 0f + + @SerialAttribute + public var isReflectX: Boolean = false + + @SerialAttribute + public var isReflectY: Boolean = false +} + +/** A writable image: `width`/`height`/`type` attributes + an embedded image file. */ +@SerialTag("CWritableImage") +public class CWritableImage { + @SerialAttribute + public var width: Int = 0 + + @SerialAttribute + public var height: Int = 0 + + @SerialAttribute + public var type: String = "" + public var image: FileRef? = null +} + +/** A layer pixel resource: attributes + imageFileBuf/preview file children. */ +@SerialTag("CImageResource") +public class CImageResource { + @SerialAttribute + public var width: Int = 0 + + @SerialAttribute + public var height: Int = 0 + + @SerialAttribute + public var type: String = "" + public var imageFileBuf: FileRef? = null + + @SerialAttribute + public var imageFileBuf_size: Int = 0 + + @DontSerializeIfDefault + public var preview: FileRef? = null + + @SerialAttribute + public var previewFileBuf_size: Int = 0 +} + +/** A filter instance: `filterName` attribute + object children. */ +@SerialTag("FilterInstance") +public class FilterInstance { + @SerialAttribute + public var filterName: String = "" + public var filterDefGuid: Any? = null + public var filterDef: Any? = null + public var filterId: Any? = null + public var inputConnectors: Any? = null + public var outputConnectors: Any? = null + public var ownerFilterSet: Any? = null +} + +/** A model image: `modelImageVersion` attribute + object children. */ +@SerialTag("CModelImage") +public class CModelImage { + @SerialAttribute + public var modelImageVersion: Int = 0 + public var guid: Any? = null + public var name: Any? = null + public var inputFilter: Any? = null + public var inputFilterEnv: Any? = null + public var _filteredImage: Any? = null + public var icon16: Any? = null + public var _materialLocalToCanvasTransform: Any? = null + public var _group: Any? = null + public var linkedRawImageGuids: Any? = null + public var cachedImageManager: Any? = null + public var memo: Any? = null +} + +/** An editable mesh: `nextPointUid`/`useDelaunayTriangulation` attributes + object children. */ +@SerialTag("GEditableMesh2") +public class GEditableMesh2 { + @SerialAttribute + public var nextPointUid: Int = 0 + + @SerialAttribute + public var useDelaunayTriangulation: Boolean = false + public var point: Any? = null + public var pointPriority: Any? = null + public var edge: Any? = null + public var edgePriority: Any? = null + public var pointUid: Any? = null + public var meshGuid: Any? = null + public var coordType: Any? = null +} + +/** + * An image layer. Extends the generated ACImageLayer (whose + * ancestor ACLayerEntry carries the IOption `_optionOfIOption`); we override it here so the same value + * is written both in `` and directly, matching the editor. + */ +@SerialTag("CLayer") +public class CLayer : org.umamo.format.cmo3.model.gen.ACImageLayer() { + public var imageResource: Any? = null + public var boundsOnImageDoc: Any? = null + public var layerIdentifier: Any? = null + public var icon16: Any? = null + public var icon64: Any? = null + public var layerInfo: Any? = null + override var _optionOfIOption: Any? = null +} + +/** The model root: `isDefaultKeyformLocked` attribute + object children. */ +@SerialTag("CModelSource") +public class CModelSource { + public var guid: Any? = null + public var name: Any? = null + public var editorEdition: Any? = null + public var canvas: Any? = null + public var parameterSourceSet: Any? = null + public var textureManager: Any? = null + public var useLegacyDrawOrder__testImpl: Any? = null + public var drawableSourceSet: Any? = null + public var deformerSourceSet: Any? = null + public var affecterSourceSet: Any? = null + public var partSourceSet: Any? = null + public var physicsSettingsSourceSet: Any? = null + public var rootPart: Any? = null + public var parameterGroupSet: Any? = null + public var rootParameterGroup: Any? = null + public var modelInfo: Any? = null + public var modelOptions: Any? = null + public var _icon64: Any? = null + public var _icon32: Any? = null + public var _icon16: Any? = null + public var gameMotionSet: Any? = null + + @SerialAttribute + public var isDefaultKeyformLocked: Boolean = false + public var modelViewerSetting: Any? = null + public var guides: Any? = null + public var targetVersionNo: Any? = null + public var latestVersionOfLastModelerNo: Any? = null + public var artPathBrushesSetting: Any? = null + + // Newer fields absent in older files: omit when null so pre-existing models round-trip. + @DontSerializeIfDefault + public var randomPoseSetting: Any? = null + + @DontSerializeIfDefault + public var motionSyncSettingsSet: Any? = null + + // CMO3: CModelSource field modelStateSetSet - the 5.4 tail (BareMinimum writes an empty + // CModelStateSetSet as the root's last child). + @DontSerializeIfDefault + public var modelStateSetSet: Any? = null +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/drawable/MeshTypes.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/drawable/MeshTypes.kt new file mode 100644 index 0000000..c22c591 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/drawable/MeshTypes.kt @@ -0,0 +1,67 @@ +package org.umamo.format.cmo3.model.drawable + +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.type.GVector2 +import org.umamo.format.cmo3.serialize.annotations.SerialTag + +/** + * A named coordinate space. Fields derived from the serialized + * form: a single `coordName` string. + * + * @see CMO3.md §3 Serializer mechanics + */ +@SerialTag("CoordType") +public class CoordType { + public var coordName: String = "" +} + +/** + * A barycentric reference into an art-mesh triangle (3 point indices + weights). + * + * @see CMO3.md §3 Serializer mechanics + */ +@SerialTag("PointInTriangle") +public class PointInTriangle { + public var ptIndex1: Int = 0 + public var weight1: Float = 0f + public var ptIndex2: Int = 0 + public var weight2: Float = 0f + public var ptIndex3: Int = 0 + public var weight3: Float = 0f +} + +/** + * A point sampled along a controller curve. Mirrors the serialized form: a curve reference, the + * normalized/total parameter, distance, and a local position. + * + * EN: [curveId] references a CControllerCurveGuid (a [Guid]). + * + * @see CMO3.md §3 Serializer mechanics + */ +@SerialTag("PointOnCurve") +public class PointOnCurve { + public var curveId: Guid? = null + public var totalT: Float = 0f + public var distance: Float = 0f + public var _posOnLocal: GVector2? = null +} + +/** + * A reference from a deformer/affecter to a point on an art-mesh keyform. + * + * EN: Object fields reference shared objects; not-yet-typed targets (keyForm CArtMeshForm, + * _artMeshSource CArtMeshSource) are held as Any? and round-trip as references regardless. + * + * @see CMO3.md §3 Serializer mechanics + */ +@SerialTag("MeshPointRef") +public class MeshPointRef { + public var pointUid: Long = 0 + public var coordType: CoordType? = null + public var keyForm: Any? = null + public var positions: FloatArray? = null + public var step: Int = 0 + public var _artMeshSource: Any? = null + public var _index: Int = 0 + public var artMeshGuid: Guid? = null +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/gen/GeneratedModel.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/gen/GeneratedModel.kt new file mode 100644 index 0000000..f5df909 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/gen/GeneratedModel.kt @@ -0,0 +1,1253 @@ +// GENERATED by ModelGenerator from the corpus main.xml, merged over the previous output. +// Do not edit by hand; re-run with -Dcmo3.generate=true. Generation only ever ADDS. +package org.umamo.format.cmo3.model.gen + +import org.umamo.format.cmo3.serialize.annotations.DontSerializeIfDefault +import org.umamo.format.cmo3.serialize.annotations.SerialName +import org.umamo.format.cmo3.serialize.annotations.SerialTag + +@SerialTag("AlphaComposition") +public enum class AlphaComposition { ATOP, CONJOINT, DISJOINT, OUT, OVER } + +@SerialTag("Anisotropy") +public enum class Anisotropy { ON, } + +@SerialTag("AutoLayoutLock") +public enum class AutoLayoutLock { NONE, } + +@SerialTag("BindMethod") +public enum class BindMethod { LINE_AND_DIRECTION, } + +@SerialTag("CArtPathDrawingCurveType") +public enum class CArtPathDrawingCurveType { SPRITE, TIP_USE } + +@SerialTag("CLabelColorType") +public enum class CLabelColorType { BLUE, CUSTOM, GREEN, ORANGE, PURPLE, RED, UNDEFINED, YELLOW } + +@SerialTag("CMocExportType") +public enum class CMocExportType { SDK, } + +@SerialTag("CPhysicsSourceType") +public enum class CPhysicsSourceType { SRC_TO_G_ANGLE, SRC_TO_X } + +@SerialTag("CachedImageType") +public enum class CachedImageType { SCALE_1, SCALE_2 } + +@SerialTag("ColorComposition") +public enum class ColorComposition { ADD, ADD_R2, ADD_R2_TSL, COLORBURN_TSL, COLORDODGE_TSL, DARKEN, HARDLIGHT, HSL_COLOR, HSL_HUE, LIGHTEN, LINEARBURN_TSL, LINEARLIGHT_TSL, MULTIPLY, MULTIPLY_R2, NORMAL, OVERLAY, SCREEN, SOFTLIGHT } + +@SerialTag("CreationMethod") +public enum class CreationMethod { AFTER_KEY_ADDED, } + +@SerialTag("EffectParameterType") +public enum class EffectParameterType { EYE_BLINK, LIPSYNC } + +@SerialTag("ExtendedInterpolationType") +public enum class ExtendedInterpolationType { ELLIPSE, LINEAR, SNS_CURVE } + +@SerialTag("FormatVersion") +public enum class FormatVersion { VERSION_30, VERSION_40, VERSION_50, VERSION_53 } + +@SerialTag("GuideType") +public enum class GuideType { HORIZONTAL, VERTICAL } + +@SerialTag("InterpolationType") +public enum class InterpolationType { LINEAR, } + +@SerialTag("MagFilter") +public enum class MagFilter { LINEAR, } + +@SerialTag("MinFilter") +public enum class MinFilter { LINEAR_MIPMAP_LINEAR, } + +@SerialTag("SettingType") +public enum class SettingType { Shape, } + +@SerialTag("SyncType") +public enum class SyncType { CRI, } + +@SerialTag("TextureState") +public enum class TextureState { MODEL_IMAGE, TEXTURE_ATLAS } + +@SerialTag("TrackCursorSettingItemType") +public enum class TrackCursorSettingItemType { NONE, X, Y } + +@SerialTag("Type") +public enum class Type { MORPH_TARGET, NORMAL } + +@SerialTag("WrapMode") +public enum class WrapMode { CLAMP_TO_BORDER, } + +@SerialTag("YureRootDirection") +public enum class YureRootDirection { LEFT, TOP } + +@SerialTag("ACAffecterForm") +public open class ACAffecterForm : ACForm() + +@SerialTag("ACAffecterSource") +public open class ACAffecterSource : ACParameterControllableSource() { + public open var `guid`: Any? = null + public open var `id`: Any? = null + public open var `targetDeformerGuid`: Any? = null + public open var `editVersion`: Int = 0 +} + +@SerialTag("ACBlend") +public open class ACBlend + +@SerialTag("ACDeformerForm") +public open class ACDeformerForm : ACForm() { + public open var `opacity`: Float = 0f + + @DontSerializeIfDefault + public open var `multiplyColor`: Any? = null + + @DontSerializeIfDefault + public open var `screenColor`: Any? = null + public open var `coordType`: Any? = null +} + +@SerialTag("ACDeformerOriginalShape") +public open class ACDeformerOriginalShape { + public open var `positions`: Any? = null + public open var `lastUpdatedTimeString`: String? = null + public open var `autoRefreshIsAvailable`: Boolean = false + public open var `creationMethod`: Any? = null + + @DontSerializeIfDefault + public open var `baseAngle`: Float = 0f + + @DontSerializeIfDefault + public open var `globalAngle`: Float = 0f + + @DontSerializeIfDefault + public open var `globalScale`: Float = 0f + + @DontSerializeIfDefault + public open var `circleRadiusTimesScale`: Float = 0f + + @DontSerializeIfDefault + public open var `handleLength`: Float = 0f + + @DontSerializeIfDefault + public open var `isReflectX`: Boolean = false + + @DontSerializeIfDefault + public open var `isReflectY`: Boolean = false + + @DontSerializeIfDefault + public open var `col`: Int = 0 + + @DontSerializeIfDefault + public open var `row`: Int = 0 +} + +@SerialTag("ACDeformerSource") +public open class ACDeformerSource : ACParameterControllableSource() { + public open var `guid`: Any? = null + public open var `id`: Any? = null + public open var `targetDeformerGuid`: Any? = null +} + +@SerialTag("ACDrawableForm") +public open class ACDrawableForm : ACForm() { + public open var `drawOrder`: Int = 0 + public open var `opacity`: Float = 0f + + @DontSerializeIfDefault + public open var `multiplyColor`: Any? = null + + @DontSerializeIfDefault + public open var `screenColor`: Any? = null + public open var `coordType`: Any? = null +} + +@SerialTag("ACDrawableSource") +public open class ACDrawableSource : ACParameterControllableSource() { + public open var `id`: Any? = null + public open var `guid`: Any? = null + public open var `targetDeformerGuid`: Any? = null + public open var `clipGuidList`: Any? = null + public open var `invertClippingMask`: Boolean = false + public open var `icon32`: Any? = null + public open var `icon16`: Any? = null +} + +@SerialTag("ACExtension") +public open class ACExtension { + public open var `guid`: Any? = null + public open var `_owner`: Any? = null +} + +@SerialTag("ACForm") +public open class ACForm { + public open var `guid`: Any? = null + public open var `isAnimatedForm`: Boolean = false + public open var `isLocalAnimatedForm`: Boolean = false + public open var `_source`: Any? = null + public open var `name`: String? = null + public open var `notes`: String? = null +} + +@SerialTag("ACImageLayer") +public open class ACImageLayer : ACLayerEntry() + +@SerialTag("ACLayerEntry") +public open class ACLayerEntry { + public open var `name`: String? = null + public open var `memo`: String? = null + public open var `isVisible`: Boolean = false + public open var `isClipping`: Boolean = false + public open var `blend`: Any? = null + public open var `guid`: Any? = null + public open var `group`: Any? = null + public open var `opacity255`: Int = 0 + + // No @DontSerializeIfDefault: the editor always writes this field, and the official + // reader NPEs on its absence (docs/format/CMO3.md, Created-Entity Conventions). + public open var `isTransparencyShapesLayer`: Boolean = false + public open var `_optionOfIOption`: Any? = null + public open var `_layeredImage`: Any? = null +} + +@SerialTag("ACLayerGroup") +public open class ACLayerGroup : ACLayerEntry() { + public open var `_children`: Any? = null +} + +@SerialTag("ACParameterControllableSource") +public open class ACParameterControllableSource { + public open var `localName`: String? = null + public open var `isVisible`: Boolean = false + public open var `isLocked`: Boolean = false + public open var `parentGuid`: Any? = null + public open var `keyformGridSource`: Any? = null + + @DontSerializeIfDefault + public open var `keyformMorphTargetSet`: Any? = null + public open var `_extensions`: Any? = null + + // No @DontSerializeIfDefault: the editor always writes this field, as an explicit null, and the official + // reader NPEs on its absence (docs/format/CMO3.md, Created-Entity Conventions). + public open var `internalColor_direct_argb`: Any? = null + + @DontSerializeIfDefault + public open var `labelColor`: Any? = null + + @DontSerializeIfDefault + public open var `internalColor_indirect_argb`: Any? = null +} + +@SerialTag("ACTextureInput") +public open class ACTextureInput { + public open var `optionalTransformOnCanvas`: Any? = null + public open var `_owner`: Any? = null +} + +@SerialTag("AClip") +public open class AClip + +@SerialTag("AFilterDef") +public open class AFilterDef { + public open var `filterName`: String? = null + public open var `inputDefs`: Any? = null + public open var `outputDefs`: Any? = null +} + +@SerialTag("AMappingDetail") +public open class AMappingDetail { + public open var `_audioId`: String? = null +} + +@SerialTag("AValueConnector") +public open class AValueConnector + +@SerialTag("AutoYureConfig") +public class AutoYureConfig { + public var `leftYureConfig`: Any? = null + public var `rightYureConfig`: Any? = null + public var `syncLeftRight`: Boolean = false + public var `rootDirection`: Any? = null + public var `isFlip`: Boolean = false +} + +@SerialTag("CAffecterSourceSet") +public class CAffecterSourceSet { + public var `_sources`: Any? = null +} + +@SerialTag("CArtMeshForm") +public class CArtMeshForm : ACDrawableForm() { + public var `positions`: Any? = null +} + +@SerialTag("CArtMeshSource") +public class CArtMeshSource : ACDrawableSource() { + public var `indices`: Any? = null + public var `keyforms`: Any? = null + public var `positions`: Any? = null + public var `uvs`: Any? = null + public var `texture`: Any? = null + public var `colorComposition`: Any? = null + public var `culling`: Boolean = false + public var `textureState`: Any? = null + public var `userData`: String? = null + + @DontSerializeIfDefault + public var `alphaComposition`: Any? = null +} + +@SerialTag("CArtPathBrush") +public class CArtPathBrush { + public var `name`: String? = null + public var `guid`: Any? = null + public var `id`: Any? = null + public var `drawingCurveType`: Any? = null + public var `textureUvData`: Any? = null + public var `fixWidthData`: Any? = null + public var `spriteData`: Any? = null + public var `widthCoefficient`: Float = 0f + public var `textureInput`: Any? = null +} + +@SerialTag("CArtPathBrushSetting") +public class CArtPathBrushSetting { + public var `brushes`: Any? = null +} + +@SerialTag("CArtPathBrush_TextureInput") +public class CArtPathBrush_TextureInput { + public var `texture`: Any? = null + public var `positions`: Any? = null + public var `editableMesh`: Any? = null + public var `textureState`: Any? = null + public var `colorComposition`: Any? = null + public var `_textureInputs`: Any? = null + public var `currentTextureInputData`: Any? = null +} + +@SerialTag("CAutoYureConfigExtension") +public class CAutoYureConfigExtension : ACExtension() { + public var `paramToConfigMap`: Any? = null +} + +@SerialTag("CBlend_Color") +public class CBlend_Color : ACBlend() + +@SerialTag("CBlend_LinearDodge") +public class CBlend_LinearDodge : ACBlend() + +@SerialTag("CBlend_Multiply") +public class CBlend_Multiply : ACBlend() + +@SerialTag("CBlend_Normal") +public class CBlend_Normal : ACBlend() + +@SerialTag("CBlend_Normal_Original") +public class CBlend_Normal_Original : ACBlend() + +@SerialTag("CBlend_NotSupported") +public class CBlend_NotSupported : ACBlend() { + public var `blendKey`: String? = null +} + +@SerialTag("CCachedImage") +public class CCachedImage { + public var `_cachedImageResource`: Any? = null + public var `isSharedImage`: Boolean = false + public var `rawImageSize`: Any? = null + public var `reductionRatio`: Int = 0 + public var `mipmapLevel`: Int = 0 + public var `hasMargin`: Boolean = false + public var `isCleaned`: Boolean = false + public var `transformRawImageToCachedImage`: Any? = null +} + +@SerialTag("CCachedImageManager") +public class CCachedImageManager { + public var `defaultCacheType`: Any? = null + public var `rawImage`: Any? = null + public var `cachedImages`: Any? = null + public var `requiredMipmapLevel`: Int = 0 +} + +@SerialTag("CControllerCurve") +public class CControllerCurve { + public var `lineWidth`: Float = 0f + public var `lineHardnessPercent`: Float = 0f + public var `isOpen`: Boolean = false + public var `_curvePoints`: Any? = null + public var `curveId`: Any? = null +} + +@SerialTag("CControllerExtension") +public class CControllerExtension : ACExtension() { + public var `editLevel`: Int = 0 + public var `maxBindCount`: Int = 0 + public var `bindMethod`: Any? = null + public var `controlPoints`: Any? = null + public var `controlCurves`: Any? = null + public var `targetPoints`: Any? = null + public var `subArtMeshGuids`: Any? = null +} + +@SerialTag("CControllerPoint") +public class CControllerPoint { + public var `assignedCurve`: Any? = null + public var `isCorner`: Boolean = false + public var `coordType`: Any? = null + public var `pointInTriangle`: Any? = null + public var `pointOnCanvasForRecovery`: Any? = null + public var `totalEffectToPointInTriangle`: Float = 0f + public var `_owner`: Any? = null + public var `ctrlPtId`: Any? = null + public var `posOnLocalOfDefaultKeyform`: Any? = null +} + +@SerialTag("CCurveForRotationDeformerExtension") +public class CCurveForRotationDeformerExtension : ACExtension() { + public var `curveElements`: Any? = null +} + +@SerialTag("CDeformerOriginalShapeExtension") +public class CDeformerOriginalShapeExtension : ACExtension() { + public var `originalShape`: Any? = null +} + +@SerialTag("CDeformerSourceSet") +public class CDeformerSourceSet { + public var `_sources`: Any? = null +} + +@SerialTag("CDrawableSourceSet") +public class CDrawableSourceSet { + public var `_sources`: Any? = null +} + +@SerialTag("CEditableMeshExtension") +public class CEditableMeshExtension : ACExtension() { + public var `editableMesh`: Any? = null + public var `isLocked`: Boolean = false +} + +@SerialTag("CEffectParameterGroups") +public class CEffectParameterGroups { + public var `_parameterGroups`: Any? = null +} + +@SerialTag("CExtendedInterpolationExtension") +public class CExtendedInterpolationExtension : ACExtension() { + public var `extendedKeyformGridSource`: Any? = null + public var `normalExtendedKeyforms`: Any? = null + public var `_extendedKeyformMorphTargetSet`: Any? = null + public var `morphTargetExtendedKeyforms`: Any? = null +} + +@SerialTag("CGameMotionSet") +public class CGameMotionSet { + public var `gameMotions`: Any? = null + public var `gameMotionGroups`: Any? = null +} + +@SerialTag("CGlueForm") +public class CGlueForm : ACAffecterForm() { + public var `intensity`: Float = 0f +} + +@SerialTag("CGlueSource") +public class CGlueSource : ACAffecterSource() { + public var `weights`: Any? = null + public var `keyforms`: Any? = null + public var `targetArtMeshA_guid`: Any? = null + public var `targetArtMeshB_guid`: Any? = null + public var `bindVertexUids`: Any? = null + public var `tabPosOnCanvas`: Any? = null +} + +@SerialTag("CGuide_Modeling") +public class CGuide_Modeling { + public var `guid`: Any? = null + public var `type`: Any? = null + public var `position`: Float = 0f + public var `colorRed`: Float = 0f + public var `colorGreen`: Float = 0f + public var `colorBlue`: Float = 0f + public var `colorAlpha`: Float = 0f + public var `memo`: String? = null +} + +@SerialTag("CGuidesSetting") +public class CGuidesSetting { + public var `guidesModeling`: Any? = null +} + +@SerialTag("CImageCanvas") +public class CImageCanvas { + public var `pixelWidth`: Int = 0 + public var `pixelHeight`: Int = 0 + public var `background`: Any? = null +} + +@SerialTag("CImageIcon") +public class CImageIcon { + public var `image`: Any? = null +} + +@SerialTag("CLayerGroup") +public class CLayerGroup : ACLayerGroup() { + public var `layerIdentifier`: Any? = null +} + +@SerialTag("CLayerIdentifier") +public class CLayerIdentifier { + public var `layerName`: String? = null + public var `layerId`: String? = null + public var `layerIdValue_testImpl`: Int = 0 +} + +@SerialTag("CLayerInputData") +public class CLayerInputData { + public var `layer`: Any? = null + public var `affine`: Any? = null + public var `clippingOnTexturePx`: Any? = null +} + +@SerialTag("CLayerSelectorMap") +public class CLayerSelectorMap { + public var `_imageToLayerInput`: Any? = null +} + +@SerialTag("CLayeredImage") +public class CLayeredImage { + public var `name`: String? = null + public var `memo`: String? = null + public var `width`: Int = 0 + public var `height`: Int = 0 + public var `psdFile`: Any? = null + public var `description`: String? = null + public var `guid`: Any? = null + public var `psdBytes`: Any? = null + public var `psdFileLastModified`: Long = 0L + public var `_rootLayer`: Any? = null + public var `layerSet`: Any? = null + public var `icon16`: Any? = null + public var `icon64`: Any? = null +} + +@SerialTag("CMeshGeneratorExtension") +public class CMeshGeneratorExtension : ACExtension() { + public var `meshGenerateSetting`: Any? = null +} + +@SerialTag("CModelExportSettingDialogData") +public class CModelExportSettingDialogData { + public var `version`: Any? = null + public var `exportInvisiblePart`: Boolean = false + public var `exportSketchPart`: Boolean = false + public var `exportInvisibleArtMesh`: Boolean = false + public var `exportPhysicsJson`: Boolean = false + public var `exportUserDataJson`: Boolean = false + public var `exportDisplayInfoJson`: Boolean = false + + @DontSerializeIfDefault + public var `exportTrackCursorJson`: Boolean = false + public var `normalOriginX`: Float = 0f + public var `normalOriginY`: Float = 0f + public var `exportTextureScale`: Int = 0 + public var `pixelsPerUnit`: Float = 0f + public var `exportType`: Any? = null + public var `exportNizimaPreviewTextureScale`: Int = 0 + + @DontSerializeIfDefault + public var `enableExtendEdgeColor`: Boolean = false + + @DontSerializeIfDefault + public var `exportMotionSyncJson`: Boolean = false + + @DontSerializeIfDefault + public var `exportParamCtrlJson`: Boolean = false +} + +@SerialTag("CModelImageGroup") +public class CModelImageGroup { + public var `memo`: String? = null + public var `groupName`: String? = null + public var `_linkedRawImageGuids`: Any? = null + public var `_modelImages`: Any? = null +} + +@SerialTag("CModelInfo") +public class CModelInfo { + public var `pixelsPerUnit`: Float = 0f + public var `originInPixels`: Any? = null + public var `_effectParameterGroups`: Any? = null +} + +@SerialTag("CModelStateSetSet") +public class CModelStateSetSet { + public var `_modelStateSets`: Any? = null +} + +@SerialTag("CMotionSyncSettingSource") +public class CMotionSyncSettingSource { + public var `id`: Any? = null + public var `name`: String? = null + public var `guid`: Any? = null + public var `postProcessingSetting`: Any? = null + public var `mapping`: Any? = null +} + +@SerialTag("CMotionSyncSettingSourceSet") +public class CMotionSyncSettingSourceSet { + public var `_settingSourceSetMotionSync`: Any? = null +} + +@SerialTag("CParameterGroup") +public class CParameterGroup { + public var `name`: String? = null + public var `description`: String? = null + public var `folderIsOpened`: Boolean = false + public var `guid`: Any? = null + public var `parentGroupGuid`: Any? = null + public var `_childGuids`: Any? = null + public var `id`: Any? = null + + @DontSerializeIfDefault + public var `visibilityColorRed`: Float = 0f + + @DontSerializeIfDefault + public var `visibilityColorGreen`: Float = 0f + + @DontSerializeIfDefault + public var `visibilityColorBlue`: Float = 0f + + @DontSerializeIfDefault + public var `visibilityColorAlpha`: Float = 0f + + @DontSerializeIfDefault + public var `labelColor`: Any? = null +} + +@SerialTag("CParameterGroupSet") +public class CParameterGroupSet { + public var `_groups`: Any? = null +} + +// decimalPlaces AND snapEpsilon ARE HAND EDITED. IF YOU SEE THIS MESSAGE DISAPPEAR IN A DIFF, FIX IT. +@SerialTag("CParameterSource") +public class CParameterSource { + public var `decimalPlaces`: Int = 3 + public var `guid`: Any? = null + public var `snapEpsilon`: Float = 0.001f + public var `minValue`: Float = 0f + public var `maxValue`: Float = 0f + public var `defaultValue`: Float = 0f + public var `isRepeat`: Boolean = false + public var `id`: Any? = null + public var `paramType`: Any? = null + public var `name`: String? = null + public var `description`: String? = null + public var `combined`: Boolean = false + public var `parentGroupGuid`: Any? = null +} + +@SerialTag("CParameterSourceSet") +public class CParameterSourceSet { + public var `_sources`: Any? = null +} + +@SerialTag("CPartForm") +public class CPartForm : ACForm() { + public var `drawOrder`: Int = 0 + + @DontSerializeIfDefault + public var `opacity`: Float = 0f + + @DontSerializeIfDefault + public var `multiplyColor`: Any? = null + + @DontSerializeIfDefault + public var `screenColor`: Any? = null +} + +@SerialTag("CPartSource") +public class CPartSource : ACParameterControllableSource() { + public var `guid`: Any? = null + public var `id`: Any? = null + public var `keyforms`: Any? = null + public var `enableDrawOrderGroup`: Boolean = false + public var `defaultOrder_forEditor`: Int = 0 + public var `isSketch`: Boolean = false + public var `partsEditColor`: Any? = null + public var `_childGuids`: Any? = null + + // No @DontSerializeIfDefault: CPartSource.deserialize dereferences this unconditionally, and the official + // reader NPEs on its absence (docs/format/CMO3.md, Created-Entity Conventions). + public var `useOffscreen`: Boolean = false + + @DontSerializeIfDefault + public var `clipGuidList`: Any? = null + + // No @DontSerializeIfDefault: CPartSource.deserialize dereferences this unconditionally, and the official + // reader NPEs on its absence (docs/format/CMO3.md, Created-Entity Conventions). + public var `invertClippingMask`: Boolean = false + + @DontSerializeIfDefault + public var `colorComposition`: Any? = null + + @DontSerializeIfDefault + public var `alphaComposition`: Any? = null + + @DontSerializeIfDefault + public var `targetDeformerGuid`: Any? = null +} + +@SerialTag("CPartSourceSet") +public class CPartSourceSet { + public var `_sources`: Any? = null +} + +@SerialTag("CPhysicsInput") +public class CPhysicsInput { + public var `guid`: Any? = null + public var `source`: Any? = null + public var `angleScale`: Float = 0f + public var `translationScale`: Any? = null + public var `weight`: Float = 0f + public var `type`: Any? = null + public var `isReverse`: Boolean = false +} + +@SerialTag("CPhysicsOutput") +public class CPhysicsOutput { + public var `guid`: Any? = null + public var `destination`: Any? = null + public var `vertexIndex`: Int = 0 + public var `translationScale`: Any? = null + public var `angleScale`: Float = 0f + public var `weight`: Float = 0f + public var `type`: Any? = null + public var `isReverse`: Boolean = false +} + +@SerialTag("CPhysicsSettingsSource") +public class CPhysicsSettingsSource { + public var `name`: String? = null + public var `guid`: Any? = null + public var `id`: Any? = null + public var `inputs`: Any? = null + public var `outputs`: Any? = null + public var `vertices`: Any? = null + public var `normalizedPositionValueMax`: Float = 0f + public var `normalizedPositionValueMin`: Float = 0f + public var `normalizedPositionDefaultValue`: Float = 0f + public var `normalizedAngleValueMax`: Float = 0f + public var `normalizedAngleValueMin`: Float = 0f + public var `normalizedAngleDefaultValue`: Float = 0f +} + +@SerialTag("CPhysicsSettingsSourceSet") +public class CPhysicsSettingsSourceSet { + public var `_sourceCubismPhysics`: Any? = null + public var `selectedCubismPhysics`: Any? = null + + @DontSerializeIfDefault + public var `settingFPS`: Int? = null +} + +@SerialTag("CPhysicsVertex") +public class CPhysicsVertex { + public var `guid`: Any? = null + public var `position`: Any? = null + public var `mobility`: Float = 0f + public var `delay`: Float = 0f + public var `acceleration`: Float = 0f + public var `radius`: Float = 0f +} + +@SerialTag("CPoint") +public class CPoint { + public var `x`: Int = 0 + public var `y`: Int = 0 +} + +@SerialTag("CRandomPoseGroupData") +public class CRandomPoseGroupData { + public var `isExpand`: Boolean = false +} + +@SerialTag("CRandomPoseParamData") +public class CRandomPoseParamData { + public var `isEnable`: Boolean = false +} + +@SerialTag("CRandomPoseSetting") +public class CRandomPoseSetting { + @SerialName("parameters.keys") + public var `parameters_keys`: Any? = null + + @SerialName("parameters.values") + public var `parameters_values`: Any? = null + + @SerialName("groups.keys") + public var `groups_keys`: Any? = null + + @SerialName("groups.values") + public var `groups_values`: Any? = null +} + +@SerialTag("CRandomPoseSettingManager") +public class CRandomPoseSettingManager { + public var `_settings`: Any? = null + public var `currentIndex`: Int = 0 +} + +@SerialTag("CRotationDeformerSource") +public class CRotationDeformerSource : ACDeformerSource() { + public var `useBoneUi_testImpl`: Boolean = false + public var `keyforms`: Any? = null + public var `handleLengthOnCanvas`: Float = 0f + public var `circleRadiusOnCanvas`: Float = 0f + public var `baseAngle`: Float = 0f +} + +@SerialTag("CTextureAtlas") +public class CTextureAtlas { + public var `name`: String? = null + public var `width`: Int = 0 + public var `height`: Int = 0 + public var `cachedAtlasImage`: Any? = null + public var `lockCachedAtlasImage`: Boolean = false + public var `guid`: Any? = null + public var `modelImages`: Any? = null + public var `cachedImageManager`: Any? = null +} + +@SerialTag("CTextureImage") +public class CTextureImage { + public var `textureName`: String? = null + public var `imageResource`: Any? = null +} + +@SerialTag("CTextureInputExtension") +public class CTextureInputExtension : ACExtension() { + public var `_textureInputs`: Any? = null + public var `currentTextureInputData`: Any? = null +} + +@SerialTag("CTextureInput_ModelImage") +public class CTextureInput_ModelImage : ACTextureInput() { + public var `_modelImageGuid`: Any? = null +} + +@SerialTag("CTextureInput_TextureAtlasRegion") +public class CTextureInput_TextureAtlasRegion : ACTextureInput() { + public var `textureAtlasGuid`: Any? = null + public var `inputImageLocalToCanvasTransform`: Any? = null +} + +@SerialTag("CTextureManager") +public class CTextureManager { + public var `textureList`: Any? = null + public var `_rawImages`: Any? = null + public var `_modelImageGroups`: Any? = null + public var `_textureAtlases`: Any? = null + public var `isTextureInputModelImageMode`: Boolean = false + public var `previewReductionRatio`: Int = 0 + public var `artPathBrushUsingLayeredImageIds`: Any? = null +} + +@SerialTag("CTopologyObserverExtension") +public class CTopologyObserverExtension : ACExtension() { + public var `observers`: Any? = null +} + +@SerialTag("CWarpDeformerBezierExtension") +public class CWarpDeformerBezierExtension : ACExtension() { + public var `editLevel`: Int = 0 + public var `bezierCol`: Int = 0 + public var `bezierRow`: Int = 0 +} + +@SerialTag("CWarpDeformerForm") +public class CWarpDeformerForm : ACDeformerForm() { + public var `positions`: Any? = null +} + +@SerialTag("CWarpDeformerSource") +public class CWarpDeformerSource : ACDeformerSource() { + public var `col`: Int = 0 + public var `row`: Int = 0 + public var `isQuadTransform`: Boolean = false + public var `keyforms`: Any? = null +} + +@SerialTag("ClipByMesh") +public class ClipByMesh : AClip() { + public var `positions`: Any? = null + public var `indices`: Any? = null +} + +@SerialTag("CompatibilityOption_Cubism21to30") +public class CompatibilityOption_Cubism21to30 { + public var `idSets`: Any? = null +} + +@SerialTag("ConstValueConnector") +public class ConstValueConnector : AValueConnector() { + public var `_value`: Any? = null +} + +@SerialTag("CurveElement") +public class CurveElement { + public var `deformerGuid`: Any? = null + public var `t_onCurve`: Float = 0f + public var `isCtrlPt`: Boolean = false +} + +@SerialTag("EditorEdition") +public class EditorEdition { + public var `edition`: Int = 0 +} + +@SerialTag("Effect") +public class Effect { + public var `effectorPt`: Any? = null + public var `weight`: Float = 0f +} + +@SerialTag("EmptyFilter") +public class EmptyFilter : AFilterDef() + +@SerialTag("EnvConnection") +public class EnvConnection { + public var `_envValueDef`: Any? = null + public var `filter`: Any? = null + public var `filterValueDef`: Any? = null +} + +@SerialTag("EnvValueConnector") +public class EnvValueConnector : AValueConnector() { + public var `envValueId`: Any? = null +} + +@SerialTag("EnvValueSet") +public class EnvValueSet { + public var `id`: Any? = null + public var `value`: Any? = null + public var `updateTimeMs`: Long = 0L +} + +@SerialTag("ExtendedInterpolationSetting") +public class ExtendedInterpolationSetting { + public var `type`: Any? = null + public var `insertPointCount`: Int = 0 + public var `extendedInterpolationScale`: Float = 0f +} + +@SerialTag("ExtendedKeyFormMorphTarget") +public class ExtendedKeyFormMorphTarget { + public var `keyformGuid`: Any? = null + public var `parameterGuid`: Any? = null + public var `keyValue`: Float = 0f +} + +@SerialTag("ExtendedKeyFormMorphTargetSet") +public class ExtendedKeyFormMorphTargetSet { + public var `_morphTargets`: Any? = null + public var `extendedInterpolationSettings`: Any? = null +} + +@SerialTag("FilterEnv") +public open class FilterEnv { + public open var `parentEnv`: Any? = null + public open var `envValues`: Any? = null +} + +@SerialTag("FilterMode") +public class FilterMode { + public var `minFilter`: Any? = null + public var `magFilter`: Any? = null + public var `owner`: Any? = null +} + +@SerialTag("FilterOutputValueConnector") +public class FilterOutputValueConnector : AValueConnector() { + public var `instance`: Any? = null + public var `id`: Any? = null + public var `valueDef`: Any? = null +} + +@SerialTag("FilterSet") +public open class FilterSet { + public open var `filterMap`: Any? = null + public open var `_externalInputs`: Any? = null + public open var `_externalOutputs`: Any? = null +} + +@SerialTag("FilterValue") +public class FilterValue { + public var `name`: String? = null + public var `id`: Any? = null + public var `defaultValueInitializer`: Any? = null +} + +@SerialTag("FixWidthData") +public class FixWidthData { + public var `upFixedWidth`: Float = 0f + public var `downFixedWidth`: Float = 0f +} + +@SerialTag("GTexture") +public open class GTexture { + public open var `name`: String? = null + public open var `wrapMode`: Any? = null + public open var `filterMode`: Any? = null + public open var `guid`: Any? = null + public open var `anisotropy`: Any? = null +} + +@SerialTag("GTexture2D") +public class GTexture2D : GTexture() { + public var `srcImageResource`: Any? = null + public var `transformImageResource01toLogical01`: Any? = null + public var `mipmapLevel`: Int = 0 + public var `isPremultiplied`: Boolean = false +} + +@SerialTag("GTransform2") +public class GTransform2 { + public var `position`: Any? = null + public var `scale`: Any? = null + public var `eulerAngle`: Float = 0f +} + +@SerialTag("IdSet") +public class IdSet { + public var `idString21`: String? = null + public var `idType21`: String? = null + public var `guid30`: Any? = null + public var `id30`: Any? = null +} + +@SerialTag("KeyFormMorphTarget") +public class KeyFormMorphTarget { + public var `parameterGuid`: Any? = null + public var `keyValue`: Float = 0f + public var `keyformGuid`: Any? = null + public var `owner`: Any? = null + public var `editBaseParameterMap`: Any? = null +} + +@SerialTag("KeyFormMorphTargetSet") +public class KeyFormMorphTargetSet { + public var `_morphTargets`: Any? = null + public var `blendWeightConstraintSet`: Any? = null +} + +@SerialTag("KeyOnParameter") +public class KeyOnParameter { + public var `binding`: Any? = null + public var `keyIndex`: Int = 0 +} + +@SerialTag("KeyformBindingSource") +public class KeyformBindingSource { + public var `_gridSource`: Any? = null + public var `parameterGuid`: Any? = null + public var `keys`: Any? = null + public var `interpolationType`: Any? = null + public var `extendedInterpolationType`: Any? = null + public var `insertPointCount`: Int = 0 + public var `extendedInterpolationScale`: Float = 0f + public var `description`: String? = null +} + +@SerialTag("KeyformGridAccessKey") +public class KeyformGridAccessKey { + public var `_keyOnParameterList`: Any? = null +} + +@SerialTag("KeyformGridSource") +public class KeyformGridSource { + public var `keyformsOnGrid`: Any? = null + public var `keyformBindings`: Any? = null +} + +@SerialTag("KeyformOnGrid") +public class KeyformOnGrid { + public var `accessKey`: Any? = null + public var `keyformGuid`: Any? = null +} + +@SerialTag("LayerSet") +public class LayerSet { + public var `_layeredImage`: Any? = null + public var `_layerEntryList`: Any? = null +} + +@SerialTag("LayeredImageWrapper") +public class LayeredImageWrapper { + public var `image`: Any? = null + public var `importedTimeMSec`: Long = 0L + public var `lastModifiedTimeMSec`: Long = 0L + public var `isReplaced`: Boolean = false +} + +@SerialTag("MappingItem") +public class MappingItem { + public var `audioId`: String? = null + public var `type`: Any? = null + public var `details`: Any? = null +} + +@SerialTag("MeshGenerateSetting") +public class MeshGenerateSetting { + @DontSerializeIfDefault + public var `polygonOuterDensity`: Int = 0 + + @DontSerializeIfDefault + public var `polygonInnerDensity`: Int = 0 + + @DontSerializeIfDefault + public var `polygonDensity`: Int = 0 + public var `polygonMargin`: Int = 0 + public var `polygonInnerMargin`: Int = 0 + public var `polygonMinMargin`: Int = 0 + public var `polygonMinBoundsPt`: Int = 0 + public var `thresholdAlpha`: Int = 0 +} + +@SerialTag("MeshPointRefEx") +public class MeshPointRefEx + +@SerialTag("ModelImageEntry") +public class ModelImageEntry { + public var `atlas`: Any? = null + public var `modelImageGuid`: Any? = null + + @DontSerializeIfDefault + public var `autoLayoutLock`: Any? = null + public var `atlasLocalToCanvasTransform`: Any? = null + public var `materialLocalToAtlasTransform`: Any? = null +} + +@SerialTag("ModelImageFilterEnv") +public class ModelImageFilterEnv : FilterEnv() + +@SerialTag("ModelImageFilterSet") +public class ModelImageFilterSet : FilterSet() + +@SerialTag("ModelViewerSetting") +public class ModelViewerSetting { + public var `trackCursorSettings`: Any? = null +} + +@SerialTag("MorphTargetBlendWeightConstraint") +public class MorphTargetBlendWeightConstraint { + public var `morphTargetParameterGuid`: Any? = null + public var `constraintParameterGuid`: Any? = null + public var `constraintParameterValue`: Float = 0f + public var `blendWeight`: Float = 0f +} + +@SerialTag("MorphTargetBlendWeightConstraintSet") +public class MorphTargetBlendWeightConstraintSet { + public var `_constraints`: Any? = null +} + +@SerialTag("MorphTargetEditBaseParameterMap") +public class MorphTargetEditBaseParameterMap { + public var `baseParameterMap`: Any? = null +} + +@SerialTag("MotionSyncMappingSetting") +public class MotionSyncMappingSetting { + public var `syncType`: Any? = null + public var `cubismParameters`: Any? = null + public var `audioParameters`: Any? = null + public var `mappingMap`: Any? = null +} + +@SerialTag("MotionSyncPostProcSetting") +public class MotionSyncPostProcSetting { + public var `blendPercentage`: Float = 0f + public var `smoothAmount`: Int = 0 + public var `sampleRate`: Float = 0f +} + +@SerialTag("ShapeMappingDetail") +public class ShapeMappingDetail : AMappingDetail() { + public var `target`: Float = 0f +} + +@SerialTag("SpriteData") +public class SpriteData { + public var `density`: Float = 0f + public var `atlasSizeInfo`: Any? = null + public var `atlasUvInfo`: Any? = null + public var `useTextureMagnification`: Float = 0f +} + +@SerialTag("SyncAudioParam") +public class SyncAudioParam { + public var `guid`: Any? = null + public var `audioId`: String? = null + public var `name`: String? = null + public var `min`: Float = 0f + public var `max`: Float = 0f + public var `scale`: Float = 0f + public var `enabled`: Boolean = false +} + +@SerialTag("SyncCubismParam") +public class SyncCubismParam { + public var `guid`: Any? = null + public var `parameterId`: String? = null + public var `name`: String? = null + public var `min`: Float = 0f + public var `max`: Float = 0f + public var `damper`: Float = 0f + public var `smooth`: Int = 0 +} + +@SerialTag("TargetPoint") +public class TargetPoint { + public var `_point`: Any? = null + public var `effects`: Any? = null +} + +@SerialTag("TextureImageGroup") +public class TextureImageGroup { + public var `children`: Any? = null +} + +@SerialTag("TextureUvData") +public class TextureUvData { + public var `up`: Float = 0f + public var `upInter`: Float = 0f + public var `center`: Float = 0f + public var `downInter`: Float = 0f + public var `down`: Float = 0f + public var `inStart`: Float = 0f + public var `repeatStart`: Float = 0f + public var `repeatEnd`: Float = 0f + public var `outEnd`: Float = 0f +} + +@SerialTag("TrackCursorSetting") +public class TrackCursorSetting { + public var `guid`: Any? = null + public var `value`: Any? = null + + @DontSerializeIfDefault + public var `weight`: Float = 0f +} + +@SerialTag("YureDeformConfig") +public class YureDeformConfig { + public var `scalePercentX`: Float = 0f + public var `scalePercentY`: Float = 0f + public var `expandScale`: Float = 0f + public var `decayLevel`: Double = 0.0 +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/identity/Identity.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/identity/Identity.kt new file mode 100644 index 0000000..a02244d --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/identity/Identity.kt @@ -0,0 +1,30 @@ +package org.umamo.format.cmo3.model.identity + +/** + * A globally-unique entity reference (uuid) with a human-readable note: + * every entity (drawable, deformer, part, parameter, …) has a typed `*Guid`; on disk each is its own + * element tag carrying `uuid` + `note` attributes. [kind] holds that concrete tag. + * + * EN: One type covers all `*Guid` tags - they are opaque identity tokens with identical structure. + * JA: 全 `*Guid` を 1 型で表し、[kind] にタグ名を保持する。 + * + * @see CMO3.md §3 Serializer mechanics + */ +public class Guid(public val kind: String) { + /** The UUID string, e.g. "e9fe6eff-953b-4ce2-be7c-4a7c3913686b". */ + public var uuid: String = "" + + /** The editor's debug note, e.g. "Root Parameter Group" or "(no debug info)". */ + public var note: String = "" +} + +/** + * A string-keyed entity id: each `*Id` is its own element tag with an + * `idstr` attribute. [kind] holds that concrete tag. + * + * @see CMO3.md §3 Serializer mechanics + */ +public class Id(public val kind: String) { + /** The id string, e.g. "filter0" or "ilf_outputLayerData". */ + public var idstr: String = "" +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/type/FileRef.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/type/FileRef.kt new file mode 100644 index 0000000..1e07966 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/type/FileRef.kt @@ -0,0 +1,17 @@ +package org.umamo.format.cmo3.model.type + +/** + * A `` element, which the editor writes in two distinct shapes under the same tag: + * - `` - an embedded CAFF entry; [archivePath] set. + * - `C:\path\to.psd` - a java.io.File path as text content (the File serializer); + * [textPath] set. + * + * @see CMO3.md §1 Container / §3 Payload + */ +public class FileRef { + /** Set when the file is an embedded archive entry (the `path` attribute). */ + public var archivePath: String? = null + + /** Set when the file is a plain filesystem path stored as element text. */ + public var textPath: String? = null +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/type/ValueTypes.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/type/ValueTypes.kt new file mode 100644 index 0000000..65097f2 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/type/ValueTypes.kt @@ -0,0 +1,59 @@ +package org.umamo.format.cmo3.model.type + +import org.umamo.format.cmo3.serialize.annotations.DontSerialize +import org.umamo.format.cmo3.serialize.annotations.SerialTag + +/** + * A 2D vector, serialized reflectively as `` + * + `` children. + * + * @see CMO3.md §3 Primitive & collection tags + */ +@SerialTag("GVector2") +public class GVector2 { + public var x: Float = 0f + public var y: Float = 0f +} + +/** + * An integer rectangle: reflective `` children in x, y, width, + * height order. + * + * @see CMO3.md §3 Primitive & collection tags + */ +@SerialTag("CRect") +public class CRect { + public var x: Int = 0 + public var y: Int = 0 + public var width: Int = 0 + public var height: Int = 0 +} + +/** + * A color whose backing value is @DontSerialize (not persisted, matching the editor), so + * it serializes to an empty `` (the editor does not persist these UI colors). [argb] lets a + * caller hold a value, but it is never written, matching the editor. + * + * @see CMO3.md §3 Serializer mechanics + */ +@SerialTag("CColor") +public class CColor { + @DontSerialize + public var argb: Int = 0 +} + +/** + * A 2x3 affine matrix, custom-serialized as the + * attributes m00, m01, m02, m10, m11, m12. Defaults to the identity transform. + * + * @see CMO3.md §3 Serializer mechanics + */ +@SerialTag("CAffine") +public class CAffine { + public var m00: Float = 1f + public var m01: Float = 0f + public var m02: Float = 0f + public var m10: Float = 0f + public var m11: Float = 1f + public var m12: Float = 0f +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/serialize/annotations/Annotations.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/serialize/annotations/Annotations.kt new file mode 100644 index 0000000..c8d0ec2 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/serialize/annotations/Annotations.kt @@ -0,0 +1,66 @@ +package org.umamo.format.cmo3.serialize.annotations + +/** + * Marks a property as serialized. + * + * EN: The editor serializes a property unless told otherwise; this annotation makes intent explicit + * and carries [readOnly] (deserialized but treated as read-only by the editor UI). + * + * @see CMO3.md §3 Serializer mechanics + */ +@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +public annotation class Serialize(val readOnly: Boolean = false) + +/** Excludes a property from serialization. */ +@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +public annotation class DontSerialize + +/** + * Skips a property when its value equals the class's default-instance value. + */ +@Target(AnnotationTarget.CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +public annotation class DontSerializeIfDefault + +/** + * Suppresses serialization of the superclass as a nested `` element. + */ +@Target(AnnotationTarget.CLASS) +@Retention(AnnotationRetention.RUNTIME) +public annotation class SuppressSerializeSuperClass + +/** + * Pins the serialized element tag for a class (overrides the default simple-name mapping) and, + * optionally, the schema version emitted as a `` PI. + * + * EN: The editor derives the tag from the class (simple name, or an ``-qualified name). + * We make it explicit per class so the registry and version PIs are driven from the model. + * + * @see CMO3.md §3 Serializer mechanics + */ +@Target(AnnotationTarget.CLASS) +@Retention(AnnotationRetention.RUNTIME) +public annotation class SerialTag(val tag: String, val version: Int = -1) + +/** + * Serializes a property as an XML attribute on the owning element rather than a child element. + * For value classes whose scalar fields are written as attributes rather than child elements + * (e.g. CImageResource width/height, CModelSource isDefaultKeyformLocked). + * + * @see CMO3.md §3 Serializer mechanics + */ +@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +public annotation class SerialAttribute(val name: String = "") + +/** + * Overrides the serialized field name (xs.n) for a child-element property when it differs from the + * Kotlin property name - e.g. an on-disk name that is not a legal Kotlin identifier (`parameters.keys`). + * + * @see CMO3.md §3 Serializer mechanics + */ +@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +public annotation class SerialName(val name: String) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/type/CArrayList.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/type/CArrayList.kt new file mode 100644 index 0000000..cb68d39 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/type/CArrayList.kt @@ -0,0 +1,23 @@ +package org.umamo.format.cmo3.type + +/** + * A list type that serializes as `` (vs `` for a plain ArrayList). + * + * The editor uses a distinct list type for most model collections, and the tag + * distinguishes it on disk, so model fields that are carray_list must use this type to round-trip. + * + * @see CMO3.md §3 Primitive & collection tags + */ +public class CArrayList private constructor(private val backing: MutableList) : MutableList by backing { + public constructor() : this(mutableListOf()) + public constructor(initialCapacity: Int) : this(ArrayList(initialCapacity)) + public constructor(elements: Collection) : this(ArrayList(elements)) + + // Kotlin's `by` delegation forwards the interface, but NOT equals/hashCode/toString — they would + // silently fall back to identity, so two equal lists would compare unequal. Forward them by hand. + override fun equals(other: Any?): Boolean = backing == other + + override fun hashCode(): Int = backing.hashCode() + + override fun toString(): String = backing.toString() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/type/CHashMap.kt b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/type/CHashMap.kt new file mode 100644 index 0000000..5b750b2 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/cmo3/type/CHashMap.kt @@ -0,0 +1,25 @@ +package org.umamo.format.cmo3.type + +/** + * A map that serializes as `` but preserves insertion/read order. The editor writes + * hash_map entries in JVM-hash order; reading into a plain HashMap and re-emitting would reorder + * them (Enum/object keys hash by identity), breaking byte-identity. Reading into this order-keeping + * type re-emits entries in their original document order. + * + * Delegates to a backing LinkedHashMap rather than extending it, for the same reason as [CArrayList]: + * `kotlin.collections.LinkedHashMap` is a typealias to the open java.util class on JVM but is FINAL + * on Kotlin/Native. The backing map is still a LinkedHashMap, so the insertion-order guarantee this + * type exists for is unchanged. + * + * @see CMO3.md §3 Primitive & collection tags + */ +public class CHashMap private constructor(private val backing: MutableMap) : MutableMap by backing { + public constructor() : this(LinkedHashMap()) + + // As in CArrayList: `by` does not forward these, and identity equality would be a silent trap. + override fun equals(other: Any?): Boolean = backing == other + + override fun hashCode(): Int = backing.hashCode() + + override fun toString(): String = backing.toString() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegConstants.kt b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegConstants.kt new file mode 100644 index 0000000..ccb6d47 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegConstants.kt @@ -0,0 +1,168 @@ +// JPEG decoder, written from ITU-T T.81 (the JPEG specification). Section references in this package +// cite T.81; the fixed-point IDCT, upsampling filters, color-conversion constants, and progressive +// scan decoders follow the Independent JPEG Group's reference implementation (jidctint.c / jdsample.c +// / jdcolor.c / jdphuff.c) so output matches libjpeg exactly. + +package org.umamo.format.jpeg + +/** + * JPEG marker codes (T.81 Table B.1) and the zig-zag coefficient order (T.81 Figure A.6). + */ +internal object JpegConstants { + // Start Of Frame markers. SOF0/SOF1/SOF2 (sequential and progressive Huffman) are decodable; the + // rest are arithmetic-coded, differential, or lossless and are rejected. + const val MARKER_SOF0 = 0xC0 // Baseline DCT. + const val MARKER_SOF1 = 0xC1 // Extended sequential DCT, Huffman. + const val MARKER_SOF2 = 0xC2 // Progressive DCT, Huffman. + const val MARKER_SOF3 = 0xC3 // Lossless (sequential). + const val MARKER_SOF5 = 0xC5 // Differential sequential DCT. + const val MARKER_SOF6 = 0xC6 // Differential progressive DCT. + const val MARKER_SOF7 = 0xC7 // Differential lossless. + const val MARKER_SOF9 = 0xC9 // Extended sequential DCT, arithmetic. + const val MARKER_SOF10 = 0xCA // Progressive DCT, arithmetic. + const val MARKER_SOF11 = 0xCB // Lossless, arithmetic. + const val MARKER_SOF13 = 0xCD // Differential sequential DCT, arithmetic. + const val MARKER_SOF14 = 0xCE // Differential progressive DCT, arithmetic. + const val MARKER_SOF15 = 0xCF // Differential lossless, arithmetic. + + const val MARKER_DHT = 0xC4 // Define Huffman Table. + const val MARKER_DAC = 0xCC // Define Arithmetic Coding conditioning. + const val MARKER_SOI = 0xD8 // Start Of Image. + const val MARKER_EOI = 0xD9 // End Of Image. + const val MARKER_SOS = 0xDA // Start Of Scan. + const val MARKER_DQT = 0xDB // Define Quantization Table. + const val MARKER_DNL = 0xDC // Define Number of Lines. + const val MARKER_DRI = 0xDD // Define Restart Interval. + const val MARKER_APP0 = 0xE0 // JFIF lives here. + const val MARKER_APP14 = 0xEE // Adobe color-transform marker lives here. + const val MARKER_APP15 = 0xEF + const val MARKER_COM = 0xFE // Comment. + + const val MARKER_RST0 = 0xD0 // Restart markers RST0..RST7. + const val MARKER_RST7 = 0xD7 + + /** Samples per DCT block edge; the JPEG block is always 8x8 (T.81 A.3.3). */ + const val BLOCK_SIZE = 8 + + /** Coefficients per DCT block. */ + const val BLOCK_COEFFICIENTS = 64 + + /** + * Maps a zig-zag coefficient index to its natural (row-major) index within an 8x8 block. + * + * DQT tables and entropy-coded coefficients both arrive in zig-zag order; storing them through + * this table puts both in natural order, which is what the IDCT indexes. + */ + val NATURAL_ORDER = + intArrayOf( + 0, + 1, + 8, + 16, + 9, + 2, + 3, + 10, + 17, + 24, + 32, + 25, + 18, + 11, + 4, + 5, + 12, + 19, + 26, + 33, + 40, + 48, + 41, + 34, + 27, + 20, + 13, + 6, + 7, + 14, + 21, + 28, + 35, + 42, + 49, + 56, + 57, + 50, + 43, + 36, + 29, + 22, + 15, + 23, + 30, + 37, + 44, + 51, + 58, + 59, + 52, + 45, + 38, + 31, + 39, + 46, + 53, + 60, + 61, + 54, + 47, + 55, + 62, + 63, + ) + + /** + * True when [marker] is any Start Of Frame code (the SOFn range excluding DHT/DAC/RSTn). + * + * @param Int marker The marker code (the byte following 0xFF). + * @return Boolean Whether the marker starts a frame. + */ + fun isStartOfFrame(marker: Int): Boolean = + marker == MARKER_SOF0 || + marker == MARKER_SOF1 || + marker == MARKER_SOF2 || + marker == MARKER_SOF3 || + marker == MARKER_SOF5 || + marker == MARKER_SOF6 || + marker == MARKER_SOF7 || + marker == MARKER_SOF9 || + marker == MARKER_SOF10 || + marker == MARKER_SOF11 || + marker == MARKER_SOF13 || + marker == MARKER_SOF14 || + marker == MARKER_SOF15 + + /** + * Names an undecodable Start Of Frame, for the rejection message. + * + * Only reachable for frame types outside SOF0/SOF1/SOF2, so every case here is arithmetic-coded, + * differential, or lossless. + * + * @param Int marker The SOFn marker code. + * @return String The frame type's name. + */ + fun startOfFrameDescription(marker: Int): String = + when (marker) { + MARKER_SOF3 -> "lossless JPEG (SOF3)" + MARKER_SOF5 -> "differential sequential JPEG (SOF5)" + MARKER_SOF6 -> "differential progressive JPEG (SOF6)" + MARKER_SOF7 -> "differential lossless JPEG (SOF7)" + MARKER_SOF9 -> "arithmetic-coded sequential JPEG (SOF9)" + MARKER_SOF10 -> "arithmetic-coded progressive JPEG (SOF10)" + MARKER_SOF11 -> "arithmetic-coded lossless JPEG (SOF11)" + MARKER_SOF13 -> "arithmetic-coded differential sequential JPEG (SOF13)" + MARKER_SOF14 -> "arithmetic-coded differential progressive JPEG (SOF14)" + MARKER_SOF15 -> "arithmetic-coded differential lossless JPEG (SOF15)" + else -> "JPEG frame type 0x${marker.toString(16).uppercase()}" + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegDecoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegDecoder.kt new file mode 100644 index 0000000..6a2a663 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegDecoder.kt @@ -0,0 +1,1070 @@ +// JPEG decoder: marker/segment parsing (T.81 Annex B), the sequential and progressive Huffman scan +// decoders (T.81 Annex F and G), chroma upsampling, and color conversion. The upsampling filters and +// the YCbCr->RGB fixed-point constants follow the Independent JPEG Group's jdsample.c / jdcolor.c, and +// the progressive scan decoders follow jdphuff.c, so that output is byte-identical to libjpeg (and +// therefore to libjpeg-turbo, ImageIO, and PIL). + +package org.umamo.format.jpeg + +/** + * A decoded JPEG image: 8-bit samples, interleaved, top row first. + * + * @property width Image width in pixels. + * @property height Image height in pixels. + * @property componentCount 1 for grayscale, 3 for RGB (color conversion is already applied). + * @property samples width * height * componentCount interleaved samples. + */ +internal class JpegImage( + val width: Int, + val height: Int, + val componentCount: Int, + val samples: ByteArray, +) + +/** Color transform codes, matching the Adobe APP14 transform byte. */ +internal object JpegColorTransform { + const val NONE = 0 // Components are already RGB (or grayscale). + const val YCBCR = 1 // Components are YCbCr and need the inverse transform. +} + +/** + * One frame component (T.81 B.2.2): its sampling factors, quantization table, coefficient buffer, and + * decoded plane. + * + * Coefficients are held for the whole component rather than transformed block-by-block, because a + * progressive image refines the same coefficients across many scans and can only be transformed once + * every scan has been read. They are stored raw (still quantized), in natural order, exactly as + * libjpeg's JCOEF blocks are. + */ +private class JpegComponent( + val identifier: Int, + val horizontalSamplingFactor: Int, + val verticalSamplingFactor: Int, + val quantizationTableIndex: Int, +) { + var coefficients: ShortArray = ShortArray(0) + var plane: ByteArray = ByteArray(0) + var planeStride = 0 + + // The component's true sample dimensions, before padding out to whole MCUs. + var downsampledWidth = 0 + var downsampledHeight = 0 + + // Blocks covering the padded MCU grid; this is the coefficient buffer's shape. + var blocksPerLine = 0 + var blocksPerColumn = 0 + + var dcTableIndex = 0 + var acTableIndex = 0 + var dcPredictor = 0 +} + +/** + * Decodes a complete JPEG datastream. + * + * @param ByteArray bytes The JPEG datastream, starting at SOI. + * @param Int? forcedColorTransform JpegColorTransform.NONE / .YCBCR to override the stream's own + * color-space signalling (TIFF's PhotometricInterpretation is + * authoritative for JPEG-in-TIFF), or null to auto-detect. + * @return JpegImage The decoded image. + */ +internal fun decodeJpeg(bytes: ByteArray, forcedColorTransform: Int? = null): JpegImage = JpegDecoder(bytes, forcedColorTransform).decode() + +/** + * The JPEG decoder: baseline / extended sequential Huffman (SOF0 / SOF1) and progressive Huffman + * (SOF2). + * + * Lossless, arithmetic-coded, differential, and 12-bit frames are rejected with a clear message + * rather than decoded incorrectly. + */ +private class JpegDecoder(private val bytes: ByteArray, private val forcedColorTransform: Int?) { + private val quantizationTables = arrayOfNulls(4) + private val dcHuffmanTables = arrayOfNulls(4) + private val acHuffmanTables = arrayOfNulls(4) + + private var components: List = emptyList() + private var frameWidth = 0 + private var frameHeight = 0 + private var maxHorizontalSamplingFactor = 1 + private var maxVerticalSamplingFactor = 1 + private var mcusPerLine = 0 + private var mcusPerColumn = 0 + private var restartInterval = 0 + private var frameSeen = false + private var progressive = false + + private var adobeTransform: Int? = null + private var jfifSeen = false + + // Current scan parameters (T.81 B.2.3): the spectral band and successive-approximation bit positions. + private var spectralStart = 0 + private var spectralEnd = 63 + private var approximationHigh = 0 + private var approximationLow = 0 + + // Progressive end-of-band run: how many further blocks are entirely band-complete. + private var endOfBandRun = 0 + + private val idctBlock = IntArray(JpegConstants.BLOCK_COEFFICIENTS) + private val idctWorkspace = IntArray(JpegConstants.BLOCK_COEFFICIENTS) + + /** + * Parses the datastream and decodes its single frame. + * + * @return JpegImage The decoded image. + */ + fun decode(): JpegImage { + var position = 0 + require(bytes.size >= 2 && readMarkerAt(position) == JpegConstants.MARKER_SOI) { "Not a JPEG datastream (missing SOI)" } + position += 2 + + while (position + 1 < bytes.size) { + if ((bytes[position].toInt() and 0xFF) != 0xFF) { + // Resynchronize: stray bytes between segments are not legal but do occur. + position++ + continue + } + val marker = bytes[position + 1].toInt() and 0xFF + if (marker == 0xFF || marker == 0x00) { + position++ + continue + } + position += 2 + + when { + marker == JpegConstants.MARKER_EOI -> { + return assembleImage() + } + + marker == JpegConstants.MARKER_SOI -> { + // Nested SOI: nothing to do. + } + + marker in JpegConstants.MARKER_RST0..JpegConstants.MARKER_RST7 -> { + // A stray restart marker outside a scan; skip it. + } + + marker == 0x01 -> { + // TEM: standalone, no payload. + } + + else -> { + require(position + 1 < bytes.size) { "Truncated JPEG segment header" } + val segmentLength = readUnsigned16(position) + require(segmentLength >= 2) { "Invalid JPEG segment length $segmentLength" } + val payloadStart = position + 2 + val payloadEnd = minOf(position + segmentLength, bytes.size) + + when { + marker == JpegConstants.MARKER_DQT -> readQuantizationTables(payloadStart, payloadEnd) + marker == JpegConstants.MARKER_DHT -> readHuffmanTables(payloadStart, payloadEnd) + marker == JpegConstants.MARKER_DRI -> restartInterval = readUnsigned16(payloadStart) + marker == JpegConstants.MARKER_APP0 -> readJfif(payloadStart, payloadEnd) + marker == JpegConstants.MARKER_APP14 -> readAdobe(payloadStart, payloadEnd) + marker == JpegConstants.MARKER_DAC -> throw IllegalArgumentException("Unsupported JPEG: arithmetic-coded JPEG") + JpegConstants.isStartOfFrame(marker) -> readFrame(marker, payloadStart, payloadEnd) + + marker == JpegConstants.MARKER_SOS -> { + position = decodeScan(payloadStart, payloadEnd) + continue + } + + else -> { + // APPn / COM / DNL and other segments carry no data this decoder needs. + } + } + position += segmentLength + continue + } + } + } + + return assembleImage() + } + + /** + * Reads the 0xFFxx marker at [position]. + * + * @param Int position Offset of the marker's 0xFF byte. + * @return Int The marker code, or -1 when the bytes are not a marker. + */ + private fun readMarkerAt(position: Int): Int { + if (position + 1 >= bytes.size || (bytes[position].toInt() and 0xFF) != 0xFF) { + return -1 + } + return bytes[position + 1].toInt() and 0xFF + } + + /** + * Reads a big-endian unsigned 16-bit value (all JPEG multi-byte fields are big-endian). + * + * @param Int position The offset to read from. + * @return Int The value. + */ + private fun readUnsigned16(position: Int): Int { + require(position + 1 < bytes.size) { "Truncated JPEG data" } + return ((bytes[position].toInt() and 0xFF) shl 8) or (bytes[position + 1].toInt() and 0xFF) + } + + /** + * Reads one or more quantization tables from a DQT segment (T.81 B.2.4.1). + * + * @param Int start The payload start offset. + * @param Int end The payload end offset (exclusive). + */ + private fun readQuantizationTables(start: Int, end: Int) { + var position = start + while (position < end) { + val precisionAndIndex = bytes[position].toInt() and 0xFF + position++ + val precision = precisionAndIndex shr 4 + val tableIndex = precisionAndIndex and 0x0F + require(tableIndex < 4) { "Invalid JPEG quantization table index $tableIndex" } + require(precision == 0 || precision == 1) { "Invalid JPEG quantization table precision $precision" } + + // DQT values arrive in zig-zag order; store them in natural order for the IDCT. + val table = IntArray(JpegConstants.BLOCK_COEFFICIENTS) + for (zigZagIndex in 0 until JpegConstants.BLOCK_COEFFICIENTS) { + val value = + if (precision == 0) { + bytes[position].toInt() and 0xFF + } else { + readUnsigned16(position) + } + position += if (precision == 0) 1 else 2 + table[JpegConstants.NATURAL_ORDER[zigZagIndex]] = value + } + quantizationTables[tableIndex] = table + } + } + + /** + * Reads one or more Huffman tables from a DHT segment (T.81 B.2.4.2). + * + * @param Int start The payload start offset. + * @param Int end The payload end offset (exclusive). + */ + private fun readHuffmanTables(start: Int, end: Int) { + var position = start + while (position < end) { + val classAndIndex = bytes[position].toInt() and 0xFF + position++ + val tableClass = classAndIndex shr 4 + val tableIndex = classAndIndex and 0x0F + require(tableIndex < 4) { "Invalid JPEG Huffman table index $tableIndex" } + require(tableClass == 0 || tableClass == 1) { "Invalid JPEG Huffman table class $tableClass" } + + val codeCountsPerLength = IntArray(16) + var totalCodes = 0 + for (lengthIndex in 0 until 16) { + codeCountsPerLength[lengthIndex] = bytes[position + lengthIndex].toInt() and 0xFF + totalCodes += codeCountsPerLength[lengthIndex] + } + position += 16 + + require(position + totalCodes <= end) { "Truncated JPEG Huffman table" } + val values = IntArray(totalCodes) + for (valueIndex in 0 until totalCodes) { + values[valueIndex] = bytes[position + valueIndex].toInt() and 0xFF + } + position += totalCodes + + val table = JpegHuffmanTable(codeCountsPerLength, values) + if (tableClass == 0) { + dcHuffmanTables[tableIndex] = table + } else { + acHuffmanTables[tableIndex] = table + } + } + } + + /** + * Records whether an APP0 segment is a JFIF header (which implies YCbCr for 3-component frames). + * + * @param Int start The payload start offset. + * @param Int end The payload end offset (exclusive). + */ + private fun readJfif(start: Int, end: Int) { + if (end - start < 5) { + return + } + // APP0 identifier "JFIF\0". + if (bytes[start].toInt() == 0x4A && + bytes[start + 1].toInt() == 0x46 && + bytes[start + 2].toInt() == 0x49 && + bytes[start + 3].toInt() == 0x46 && + bytes[start + 4].toInt() == 0x00 + ) { + jfifSeen = true + } + } + + /** + * Reads the Adobe APP14 color-transform byte, which authoritatively names the frame's color space. + * + * @param Int start The payload start offset. + * @param Int end The payload end offset (exclusive). + */ + private fun readAdobe(start: Int, end: Int) { + if (end - start < 12) { + return + } + // APP14 identifier "Adobe"; the transform byte is the last of the 12-byte payload. + if (bytes[start].toInt() == 0x41 && + bytes[start + 1].toInt() == 0x64 && + bytes[start + 2].toInt() == 0x6F && + bytes[start + 3].toInt() == 0x62 && + bytes[start + 4].toInt() == 0x65 + ) { + adobeTransform = bytes[start + 11].toInt() and 0xFF + } + } + + /** + * Reads a Start Of Frame segment and allocates each component's coefficient buffer (T.81 B.2.2). + * + * @param Int marker The SOFn marker code. + * @param Int start The payload start offset. + * @param Int end The payload end offset (exclusive). + */ + private fun readFrame(marker: Int, start: Int, end: Int) { + require(marker == JpegConstants.MARKER_SOF0 || marker == JpegConstants.MARKER_SOF1 || marker == JpegConstants.MARKER_SOF2) { + "Unsupported JPEG: ${JpegConstants.startOfFrameDescription(marker)}" + } + require(!frameSeen) { "Unsupported JPEG: multiple frames" } + require(end - start >= 6) { "Truncated JPEG SOF segment" } + progressive = marker == JpegConstants.MARKER_SOF2 + + val samplePrecision = bytes[start].toInt() and 0xFF + require(samplePrecision == 8) { "Unsupported JPEG sample precision $samplePrecision (only 8-bit is supported)" } + frameHeight = readUnsigned16(start + 1) + frameWidth = readUnsigned16(start + 3) + val componentCount = bytes[start + 5].toInt() and 0xFF + require(frameWidth > 0 && frameHeight > 0) { "JPEG frame has non-positive dimensions ${frameWidth}x$frameHeight" } + require(componentCount == 1 || componentCount == 3) { + "Unsupported JPEG component count $componentCount (only grayscale and 3-component color are supported)" + } + require(end - start >= 6 + componentCount * 3) { "Truncated JPEG SOF component list" } + + val parsed = ArrayList(componentCount) + for (componentIndex in 0 until componentCount) { + val fieldStart = start + 6 + componentIndex * 3 + val samplingFactors = bytes[fieldStart + 1].toInt() and 0xFF + val horizontal = samplingFactors shr 4 + val vertical = samplingFactors and 0x0F + require(horizontal in 1..4 && vertical in 1..4) { "Invalid JPEG sampling factors ${horizontal}x$vertical" } + // Tq selects one of the four DQT slots; a larger value would index past quantizationTables + // in renderComponent, so reject it here where the message can still name the field. + val quantizationTableIndex = bytes[fieldStart + 2].toInt() and 0xFF + require(quantizationTableIndex < 4) { "Invalid JPEG quantization table index $quantizationTableIndex" } + parsed += + JpegComponent( + identifier = bytes[fieldStart].toInt() and 0xFF, + horizontalSamplingFactor = horizontal, + verticalSamplingFactor = vertical, + quantizationTableIndex = quantizationTableIndex, + ) + } + components = parsed + frameSeen = true + + maxHorizontalSamplingFactor = parsed.maxOf { it.horizontalSamplingFactor } + maxVerticalSamplingFactor = parsed.maxOf { it.verticalSamplingFactor } + // Every component must upsample by a whole number, which T.81 permits to be false (Hi/Vi are + // independent 1..4 fields) but no real encoder emits. libjpeg rejects these outright + // ("Fractional sampling not implemented yet", jdsample.c), and matching libjpeg's output is + // the whole point of this decoder, so decline them rather than invent a fractional filter + // whose results nothing else would agree with. + for (component in parsed) { + require( + maxHorizontalSamplingFactor % component.horizontalSamplingFactor == 0 && + maxVerticalSamplingFactor % component.verticalSamplingFactor == 0, + ) { + "Unsupported JPEG: fractional sampling (component ${component.identifier} is " + + "${component.horizontalSamplingFactor}x${component.verticalSamplingFactor} " + + "against a maximum of ${maxHorizontalSamplingFactor}x$maxVerticalSamplingFactor)" + } + } + mcusPerLine = ceilDivide(frameWidth, 8 * maxHorizontalSamplingFactor) + mcusPerColumn = ceilDivide(frameHeight, 8 * maxVerticalSamplingFactor) + + for (component in components) { + component.downsampledWidth = ceilDivide(frameWidth * component.horizontalSamplingFactor, maxHorizontalSamplingFactor) + component.downsampledHeight = ceilDivide(frameHeight * component.verticalSamplingFactor, maxVerticalSamplingFactor) + // Scans code whole MCUs, so the buffer is padded out to the MCU grid and cropped on render. + component.blocksPerLine = mcusPerLine * component.horizontalSamplingFactor + component.blocksPerColumn = mcusPerColumn * component.verticalSamplingFactor + component.coefficients = ShortArray(component.blocksPerLine * component.blocksPerColumn * JpegConstants.BLOCK_COEFFICIENTS) + } + } + + /** + * Decodes one entropy-coded scan (T.81 B.2.3, Annex F for sequential and Annex G for progressive). + * + * @param Int start The SOS payload start offset. + * @param Int end The SOS payload end offset (exclusive). + * @return Int The offset just past the scan's entropy-coded data. + */ + private fun decodeScan(start: Int, end: Int): Int { + require(frameSeen) { "JPEG scan before frame header" } + val scanComponentCount = bytes[start].toInt() and 0xFF + require(scanComponentCount in 1..components.size) { "Invalid JPEG scan component count $scanComponentCount" } + + val scanComponents = ArrayList(scanComponentCount) + for (scanIndex in 0 until scanComponentCount) { + val fieldStart = start + 1 + scanIndex * 2 + val componentIdentifier = bytes[fieldStart].toInt() and 0xFF + val component = + components.firstOrNull { it.identifier == componentIdentifier } + ?: throw IllegalArgumentException("JPEG scan names unknown component $componentIdentifier") + // Td/Ta are 4-bit fields but only four tables of each class exist; validate before they + // reach dcHuffmanTables/acHuffmanTables, which are sized 4 and would throw an index error + // over the "references undefined ... table" message dcTableFor/acTableFor exist to give. + val tableSelectors = bytes[fieldStart + 1].toInt() and 0xFF + val dcTableIndex = tableSelectors shr 4 + val acTableIndex = tableSelectors and 0x0F + require(dcTableIndex < 4) { "Invalid JPEG DC Huffman table index $dcTableIndex" } + require(acTableIndex < 4) { "Invalid JPEG AC Huffman table index $acTableIndex" } + component.dcTableIndex = dcTableIndex + component.acTableIndex = acTableIndex + component.dcPredictor = 0 + scanComponents += component + } + + spectralStart = bytes[start + 1 + scanComponentCount * 2].toInt() and 0xFF + spectralEnd = bytes[start + 2 + scanComponentCount * 2].toInt() and 0xFF + val approximation = bytes[start + 3 + scanComponentCount * 2].toInt() and 0xFF + approximationHigh = approximation shr 4 + approximationLow = approximation and 0x0F + + if (progressive) { + require(spectralStart <= spectralEnd && spectralEnd < JpegConstants.BLOCK_COEFFICIENTS) { + "Invalid progressive JPEG spectral band $spectralStart..$spectralEnd" + } + if (spectralStart == 0) { + require(spectralEnd == 0) { "A progressive JPEG DC scan must cover coefficient 0 alone (band $spectralStart..$spectralEnd)" } + } else { + // T.81 G.1.3.2: only DC scans may interleave components. + require(scanComponentCount == 1) { "A progressive JPEG AC scan must name exactly one component" } + } + } else { + require(spectralStart == 0 && spectralEnd == 63 && approximationHigh == 0 && approximationLow == 0) { + "Unsupported JPEG: progressive scan parameters in a sequential frame" + } + } + + endOfBandRun = 0 + val reader = JpegBitReader(bytes, end) + if (scanComponentCount == 1) { + decodeNonInterleavedScan(reader, scanComponents[0]) + } else { + decodeInterleavedScan(reader, scanComponents) + } + + // Skip past any trailing bytes to the next marker. + var position = reader.position + while (position + 1 < bytes.size) { + if ((bytes[position].toInt() and 0xFF) == 0xFF) { + val marker = bytes[position + 1].toInt() and 0xFF + if (marker != 0x00 && marker != 0xFF && marker !in JpegConstants.MARKER_RST0..JpegConstants.MARKER_RST7) { + break + } + } + position++ + } + return position + } + + /** + * Decodes an interleaved scan, walking the MCU grid. + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param List scanComponents The scan's components, in scan order. + */ + private fun decodeInterleavedScan(reader: JpegBitReader, scanComponents: List) { + val totalMcus = mcusPerLine * mcusPerColumn + var mcusSinceRestart = 0 + for (mcuIndex in 0 until totalMcus) { + if (restartInterval > 0 && mcusSinceRestart == restartInterval) { + if (!restart(reader, scanComponents)) { + return + } + mcusSinceRestart = 0 + } + val mcuRow = mcuIndex / mcusPerLine + val mcuColumn = mcuIndex % mcusPerLine + for (component in scanComponents) { + for (blockY in 0 until component.verticalSamplingFactor) { + for (blockX in 0 until component.horizontalSamplingFactor) { + decodeBlock( + reader, + component, + mcuRow * component.verticalSamplingFactor + blockY, + mcuColumn * component.horizontalSamplingFactor + blockX, + ) + } + } + } + mcusSinceRestart++ + } + } + + /** + * Decodes a single-component (non-interleaved) scan, walking that component's own block grid. + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The scan's only component. + */ + private fun decodeNonInterleavedScan(reader: JpegBitReader, component: JpegComponent) { + // A non-interleaved scan codes only the component's real blocks, not the padded MCU grid. + val blocksPerLine = ceilDivide(component.downsampledWidth, 8) + val blocksPerColumn = ceilDivide(component.downsampledHeight, 8) + val scanComponents = listOf(component) + var blocksSinceRestart = 0 + for (blockRow in 0 until blocksPerColumn) { + for (blockColumn in 0 until blocksPerLine) { + if (restartInterval > 0 && blocksSinceRestart == restartInterval) { + if (!restart(reader, scanComponents)) { + return + } + blocksSinceRestart = 0 + } + decodeBlock(reader, component, blockRow, blockColumn) + blocksSinceRestart++ + } + } + } + + /** + * Consumes a restart marker and resets the per-interval entropy state (T.81 F.2.1.3.1 / G.1.2.3). + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param List scanComponents The scan's components. + * @return Boolean False when no restart marker was found and decoding must stop. + */ + private fun restart(reader: JpegBitReader, scanComponents: List): Boolean { + if (!reader.restart()) { + return false + } + for (component in scanComponents) { + component.dcPredictor = 0 + } + // A restart interval is independently decodable, so any pending end-of-band run ends with it. + endOfBandRun = 0 + return true + } + + /** + * Decodes one 8x8 block's contribution to the coefficient buffer, dispatching on the scan type. + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int blockRow The block's row in the component's block grid. + * @param Int blockColumn The block's column in the component's block grid. + */ + private fun decodeBlock(reader: JpegBitReader, component: JpegComponent, blockRow: Int, blockColumn: Int) { + val blockOffset = (blockRow * component.blocksPerLine + blockColumn) * JpegConstants.BLOCK_COEFFICIENTS + if (blockOffset < 0 || blockOffset + JpegConstants.BLOCK_COEFFICIENTS > component.coefficients.size) { + return + } + when { + !progressive -> decodeBaselineBlock(reader, component, blockOffset) + spectralStart == 0 && approximationHigh == 0 -> decodeDcFirst(reader, component, blockOffset) + spectralStart == 0 -> decodeDcRefine(reader, component, blockOffset) + approximationHigh == 0 -> decodeAcFirst(reader, component, blockOffset) + else -> decodeAcRefine(reader, component, blockOffset) + } + } + + /** + * Resolves the scan's DC Huffman table. + * + * @param JpegComponent component The component being decoded. + * @return JpegHuffmanTable The table. + */ + private fun dcTableFor(component: JpegComponent): JpegHuffmanTable = + dcHuffmanTables[component.dcTableIndex] + ?: throw IllegalArgumentException("JPEG references undefined DC Huffman table ${component.dcTableIndex}") + + /** + * Resolves the scan's AC Huffman table. + * + * @param JpegComponent component The component being decoded. + * @return JpegHuffmanTable The table. + */ + private fun acTableFor(component: JpegComponent): JpegHuffmanTable = + acHuffmanTables[component.acTableIndex] + ?: throw IllegalArgumentException("JPEG references undefined AC Huffman table ${component.acTableIndex}") + + /** + * Decodes one sequential block: the DC difference then the AC run/size pairs (T.81 F.2.2). + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int blockOffset Index of the block's first coefficient. + */ + private fun decodeBaselineBlock(reader: JpegBitReader, component: JpegComponent, blockOffset: Int) { + val dcTable = dcTableFor(component) + val acTable = acTableFor(component) + component.coefficients.fill(0, blockOffset, blockOffset + JpegConstants.BLOCK_COEFFICIENTS) + + // DC coefficient: a Huffman-coded magnitude category, then that many bits of difference. + val dcCategory = dcTable.decode(reader) + val dcDifference = if (dcCategory == 0) 0 else extendJpegValue(reader.readBits(dcCategory), dcCategory) + component.dcPredictor += dcDifference + component.coefficients[blockOffset] = component.dcPredictor.toShort() + + // AC coefficients: run-length of zeros in the high nibble, magnitude category in the low. + var coefficientIndex = 1 + while (coefficientIndex < JpegConstants.BLOCK_COEFFICIENTS) { + val runAndSize = acTable.decode(reader) + val magnitudeCategory = runAndSize and 0x0F + val zeroRunLength = runAndSize shr 4 + if (magnitudeCategory == 0) { + if (zeroRunLength != 15) { + // End Of Block: the rest of the block is zero. + break + } + // ZRL: a run of 16 zeros. + coefficientIndex += 16 + continue + } + coefficientIndex += zeroRunLength + if (coefficientIndex >= JpegConstants.BLOCK_COEFFICIENTS) { + break + } + val value = extendJpegValue(reader.readBits(magnitudeCategory), magnitudeCategory) + component.coefficients[blockOffset + JpegConstants.NATURAL_ORDER[coefficientIndex]] = value.toShort() + coefficientIndex++ + } + } + + /** + * Decodes a progressive DC first scan: the DC difference, point-shifted left by Al (T.81 G.1.2.1). + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int blockOffset Index of the block's first coefficient. + */ + private fun decodeDcFirst(reader: JpegBitReader, component: JpegComponent, blockOffset: Int) { + val dcCategory = dcTableFor(component).decode(reader) + val dcDifference = if (dcCategory == 0) 0 else extendJpegValue(reader.readBits(dcCategory), dcCategory) + component.dcPredictor += dcDifference + component.coefficients[blockOffset] = (component.dcPredictor shl approximationLow).toShort() + } + + /** + * Decodes a progressive DC refinement scan: one bit per block, OR-ed in at Al (T.81 G.1.2.1). + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int blockOffset Index of the block's first coefficient. + */ + private fun decodeDcRefine(reader: JpegBitReader, component: JpegComponent, blockOffset: Int) { + if (reader.readBit() != 0) { + component.coefficients[blockOffset] = (component.coefficients[blockOffset].toInt() or (1 shl approximationLow)).toShort() + } + } + + /** + * Decodes a progressive AC first scan over the band Ss..Se (T.81 G.1.2.2). + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int blockOffset Index of the block's first coefficient. + */ + private fun decodeAcFirst(reader: JpegBitReader, component: JpegComponent, blockOffset: Int) { + if (endOfBandRun > 0) { + // This block's whole band is zero, accounted for by a previous EOBn code. + endOfBandRun-- + return + } + val acTable = acTableFor(component) + var coefficientIndex = spectralStart + while (coefficientIndex <= spectralEnd) { + val runAndSize = acTable.decode(reader) + val magnitudeCategory = runAndSize and 0x0F + var zeroRunLength = runAndSize shr 4 + if (magnitudeCategory == 0) { + if (zeroRunLength != 15) { + // EOBn: this block plus the next 2^n - 1 + extra blocks have an empty rest-of-band. + endOfBandRun = 1 shl zeroRunLength + if (zeroRunLength != 0) { + endOfBandRun += reader.readBits(zeroRunLength) + } + endOfBandRun-- + break + } + // ZRL: skip 16 zero coefficients. + coefficientIndex += 16 + continue + } + coefficientIndex += zeroRunLength + if (coefficientIndex > spectralEnd) { + break + } + val value = extendJpegValue(reader.readBits(magnitudeCategory), magnitudeCategory) + component.coefficients[blockOffset + JpegConstants.NATURAL_ORDER[coefficientIndex]] = (value shl approximationLow).toShort() + coefficientIndex++ + zeroRunLength = 0 + } + } + + /** + * Decodes a progressive AC refinement scan (T.81 G.1.2.3). + * + * The subtle scan type: newly nonzero coefficients arrive as run/size pairs whose size is always 1, + * while every already-nonzero coefficient passed over consumes one correction bit. A correction bit + * of 1 means the coefficient's magnitude gains the bit at Al. + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int blockOffset Index of the block's first coefficient. + */ + private fun decodeAcRefine(reader: JpegBitReader, component: JpegComponent, blockOffset: Int) { + val positiveBit = 1 shl approximationLow + val negativeBit = -1 shl approximationLow + var coefficientIndex = spectralStart + + if (endOfBandRun == 0) { + while (coefficientIndex <= spectralEnd) { + val runAndSize = acTableFor(component).decode(reader) + val magnitudeCategory = runAndSize and 0x0F + var zeroRunLength = runAndSize shr 4 + var newValue = 0 + + if (magnitudeCategory == 0) { + if (zeroRunLength != 15) { + // EOBn: the rest of this band, and of the next blocks, is handled as corrections only. + endOfBandRun = 1 shl zeroRunLength + if (zeroRunLength != 0) { + endOfBandRun += reader.readBits(zeroRunLength) + } + break + } + // ZRL: skip 16 zero-history coefficients (correcting nonzero ones on the way). + } else { + // A newly nonzero coefficient; its magnitude is always exactly 1 at this bit position. + newValue = if (reader.readBit() != 0) positiveBit else negativeBit + } + + // Walk forward over already-nonzero coefficients (appending correction bits) until + // zeroRunLength zero-history coefficients have been passed. + while (coefficientIndex <= spectralEnd) { + val position = blockOffset + JpegConstants.NATURAL_ORDER[coefficientIndex] + val existing = component.coefficients[position].toInt() + if (existing != 0) { + appendCorrectionBit(reader, component, position, existing, positiveBit, negativeBit) + } else { + if (zeroRunLength == 0) { + break + } + zeroRunLength-- + } + coefficientIndex++ + } + + if (newValue != 0 && coefficientIndex <= spectralEnd) { + component.coefficients[blockOffset + JpegConstants.NATURAL_ORDER[coefficientIndex]] = newValue.toShort() + } + coefficientIndex++ + } + } + + if (endOfBandRun > 0) { + // Inside an end-of-band run: no new coefficients, but existing ones still take correction bits. + while (coefficientIndex <= spectralEnd) { + val position = blockOffset + JpegConstants.NATURAL_ORDER[coefficientIndex] + val existing = component.coefficients[position].toInt() + if (existing != 0) { + appendCorrectionBit(reader, component, position, existing, positiveBit, negativeBit) + } + coefficientIndex++ + } + endOfBandRun-- + } + } + + /** + * Reads one correction bit and, when set, grows an already-nonzero coefficient's magnitude by the + * bit at Al. Re-applying an already-applied bit is a no-op, matching libjpeg. + * + * @param JpegBitReader reader The entropy-coded bit source. + * @param JpegComponent component The component being decoded. + * @param Int position Index of the coefficient in the component's buffer. + * @param Int existing The coefficient's current value. + * @param Int positiveBit 1 shifted to the bit position being coded. + * @param Int negativeBit -1 shifted to the bit position being coded. + */ + private fun appendCorrectionBit(reader: JpegBitReader, component: JpegComponent, position: Int, existing: Int, positiveBit: Int, negativeBit: Int) { + if (reader.readBit() == 0) { + return + } + if ((existing and positiveBit) != 0) { + return + } + val corrected = if (existing >= 0) existing + positiveBit else existing + negativeBit + component.coefficients[position] = corrected.toShort() + } + + /** + * Dequantizes and inverse-transforms every block of a component into its sample plane. + * + * @param JpegComponent component The component to render. + */ + private fun renderComponent(component: JpegComponent) { + val quantizationTable = + quantizationTables[component.quantizationTableIndex] + ?: throw IllegalArgumentException("JPEG references undefined quantization table ${component.quantizationTableIndex}") + component.planeStride = component.blocksPerLine * 8 + component.plane = ByteArray(component.planeStride * component.blocksPerColumn * 8) + + for (blockRow in 0 until component.blocksPerColumn) { + for (blockColumn in 0 until component.blocksPerLine) { + val blockOffset = (blockRow * component.blocksPerLine + blockColumn) * JpegConstants.BLOCK_COEFFICIENTS + for (coefficientIndex in 0 until JpegConstants.BLOCK_COEFFICIENTS) { + idctBlock[coefficientIndex] = component.coefficients[blockOffset + coefficientIndex] * quantizationTable[coefficientIndex] + } + JpegIdct.inverse(idctBlock, idctWorkspace, component.plane, blockRow * 8 * component.planeStride + blockColumn * 8, component.planeStride) + } + } + // The coefficients are spent; release them before the (larger) upsample buffers are allocated. + component.coefficients = ShortArray(0) + } + + /** + * Renders, upsamples, and color-converts every component into the finished image. + * + * @return JpegImage The finished image. + */ + private fun assembleImage(): JpegImage { + require(frameSeen) { "JPEG has no frame header" } + val colorTransform = forcedColorTransform ?: detectColorTransform() + for (component in components) { + renderComponent(component) + } + + if (components.size == 1) { + val luminance = upsampleComponent(components[0]) + return JpegImage(frameWidth, frameHeight, 1, luminance) + } + + val firstPlane = upsampleComponent(components[0]) + val secondPlane = upsampleComponent(components[1]) + val thirdPlane = upsampleComponent(components[2]) + val pixelCount = frameWidth * frameHeight + val rgb = ByteArray(pixelCount * 3) + + if (colorTransform == JpegColorTransform.NONE) { + for (pixelIndex in 0 until pixelCount) { + rgb[pixelIndex * 3] = firstPlane[pixelIndex] + rgb[pixelIndex * 3 + 1] = secondPlane[pixelIndex] + rgb[pixelIndex * 3 + 2] = thirdPlane[pixelIndex] + } + return JpegImage(frameWidth, frameHeight, 3, rgb) + } + + for (pixelIndex in 0 until pixelCount) { + val luminance = firstPlane[pixelIndex].toInt() and 0xFF + val blueChroma = secondPlane[pixelIndex].toInt() and 0xFF + val redChroma = thirdPlane[pixelIndex].toInt() and 0xFF + rgb[pixelIndex * 3] = clampToByte(luminance + JpegColorTables.redFromRedChroma[redChroma]) + rgb[pixelIndex * 3 + 1] = + clampToByte(luminance + ((JpegColorTables.greenFromBlueChroma[blueChroma] + JpegColorTables.greenFromRedChroma[redChroma]) shr JpegColorTables.SCALE_BITS)) + rgb[pixelIndex * 3 + 2] = clampToByte(luminance + JpegColorTables.blueFromBlueChroma[blueChroma]) + } + return JpegImage(frameWidth, frameHeight, 3, rgb) + } + + /** + * Determines the frame's color space the way libjpeg does: JFIF implies YCbCr, an Adobe marker + * names the transform outright, and otherwise the component ids are the only hint. + * + * @return Int The JpegColorTransform code. + */ + private fun detectColorTransform(): Int { + if (components.size == 1) { + return JpegColorTransform.NONE + } + if (jfifSeen) { + return JpegColorTransform.YCBCR + } + adobeTransform?.let { transform -> + return if (transform == 0) JpegColorTransform.NONE else JpegColorTransform.YCBCR + } + // No markers: component ids 'R','G','B' mean RGB, anything else is assumed YCbCr. + if (components[0].identifier == 'R'.code && components[1].identifier == 'G'.code && components[2].identifier == 'B'.code) { + return JpegColorTransform.NONE + } + return JpegColorTransform.YCBCR + } + + /** + * Expands one component's plane to the full image grid, cropping the MCU padding away. + * + * Uses the triangle ("fancy") filter for 2x horizontal expansion, matching libjpeg's default; other + * ratios replicate samples, which is also what libjpeg does for them. + * + * @param JpegComponent component The component to upsample. + * @return ByteArray frameWidth * frameHeight samples. + */ + private fun upsampleComponent(component: JpegComponent): ByteArray { + val horizontalExpansion = maxHorizontalSamplingFactor / component.horizontalSamplingFactor + val verticalExpansion = maxVerticalSamplingFactor / component.verticalSamplingFactor + val output = ByteArray(frameWidth * frameHeight) + + // Test the factors, not the ratio: integer division makes a 3:2 component's expansion 1, and + // copying whole rows out of a plane narrower than the frame would run off its end. readFrame + // rejects such frames outright, so this only has to not be the thing that discovers it. + if (component.horizontalSamplingFactor == maxHorizontalSamplingFactor && component.verticalSamplingFactor == maxVerticalSamplingFactor) { + for (row in 0 until frameHeight) { + component.plane.copyInto(output, row * frameWidth, row * component.planeStride, row * component.planeStride + frameWidth) + } + return output + } + + val fancyEligible = horizontalExpansion == 2 && component.downsampledWidth > 2 && component.horizontalSamplingFactor * 2 == maxHorizontalSamplingFactor + if (fancyEligible && verticalExpansion == 1) { + upsampleHorizontallyFancy(component, output) + return output + } + if (fancyEligible && verticalExpansion == 2) { + upsampleBothFancy(component, output) + return output + } + + // Replicate: the general power-of-two path. + for (row in 0 until frameHeight) { + val sourceRow = minOf(row / verticalExpansion, component.downsampledHeight - 1) + for (column in 0 until frameWidth) { + val sourceColumn = minOf(column / horizontalExpansion, component.downsampledWidth - 1) + output[row * frameWidth + column] = component.plane[sourceRow * component.planeStride + sourceColumn] + } + } + return output + } + + /** + * Doubles a component horizontally with libjpeg's triangle filter (h2v1_fancy_upsample). + * + * @param JpegComponent component The component to upsample. + * @param ByteArray output The full-resolution destination. + */ + private fun upsampleHorizontallyFancy(component: JpegComponent, output: ByteArray) { + val sourceWidth = component.downsampledWidth + val expanded = ByteArray(sourceWidth * 2) + for (row in 0 until frameHeight) { + val sourceRow = minOf(row, component.downsampledHeight - 1) + val rowBase = sourceRow * component.planeStride + + expanded[0] = component.plane[rowBase] + expanded[1] = (((component.plane[rowBase].toInt() and 0xFF) * 3 + (component.plane[rowBase + 1].toInt() and 0xFF) + 2) shr 2).toByte() + for (column in 1 until sourceWidth - 1) { + // 3/4 of the nearer sample plus 1/4 of the further one. + val nearer = (component.plane[rowBase + column].toInt() and 0xFF) * 3 + expanded[column * 2] = ((nearer + (component.plane[rowBase + column - 1].toInt() and 0xFF) + 1) shr 2).toByte() + expanded[column * 2 + 1] = ((nearer + (component.plane[rowBase + column + 1].toInt() and 0xFF) + 2) shr 2).toByte() + } + val lastValue = component.plane[rowBase + sourceWidth - 1].toInt() and 0xFF + expanded[(sourceWidth - 1) * 2] = ((lastValue * 3 + (component.plane[rowBase + sourceWidth - 2].toInt() and 0xFF) + 1) shr 2).toByte() + expanded[(sourceWidth - 1) * 2 + 1] = lastValue.toByte() + + expanded.copyInto(output, row * frameWidth, 0, minOf(frameWidth, expanded.size)) + } + } + + /** + * Doubles a component in both axes with libjpeg's triangle filter (h2v2_fancy_upsample). + * + * @param JpegComponent component The component to upsample. + * @param ByteArray output The full-resolution destination. + */ + private fun upsampleBothFancy(component: JpegComponent, output: ByteArray) { + val sourceWidth = component.downsampledWidth + val columnSums = IntArray(sourceWidth) + val expanded = ByteArray(sourceWidth * 2) + + for (row in 0 until frameHeight) { + // Each output row blends its source row 3:1 with the neighbour it sits nearer to. + val nearRow = minOf(row / 2, component.downsampledHeight - 1) + val farRow = + if (row % 2 == 0) { + maxOf(nearRow - 1, 0) + } else { + minOf(nearRow + 1, component.downsampledHeight - 1) + } + val nearBase = nearRow * component.planeStride + val farBase = farRow * component.planeStride + for (column in 0 until sourceWidth) { + columnSums[column] = (component.plane[nearBase + column].toInt() and 0xFF) * 3 + (component.plane[farBase + column].toInt() and 0xFF) + } + + expanded[0] = ((columnSums[0] * 4 + 8) shr 4).toByte() + expanded[1] = ((columnSums[0] * 3 + columnSums[1] + 7) shr 4).toByte() + for (column in 1 until sourceWidth - 1) { + expanded[column * 2] = ((columnSums[column] * 3 + columnSums[column - 1] + 8) shr 4).toByte() + expanded[column * 2 + 1] = ((columnSums[column] * 3 + columnSums[column + 1] + 7) shr 4).toByte() + } + expanded[(sourceWidth - 1) * 2] = ((columnSums[sourceWidth - 1] * 3 + columnSums[sourceWidth - 2] + 8) shr 4).toByte() + expanded[(sourceWidth - 1) * 2 + 1] = ((columnSums[sourceWidth - 1] * 4 + 7) shr 4).toByte() + + expanded.copyInto(output, row * frameWidth, 0, minOf(frameWidth, expanded.size)) + } + } +} + +/** + * The fixed-point YCbCr to RGB conversion tables from the Independent JPEG Group's jdcolor.c. + * + * Precomputing per chroma value keeps the conversion to one add (and one shift for green), and the + * exact rounding is what makes output match libjpeg. + */ +private object JpegColorTables { + const val SCALE_BITS = 16 + private const val ONE_HALF = 1 shl (SCALE_BITS - 1) + + // round(coefficient * 2^SCALE_BITS) for the standard JFIF conversion coefficients. + private const val FIX_1_40200 = 91881 + private const val FIX_1_77200 = 116130 + private const val FIX_0_71414 = 46802 + private const val FIX_0_34414 = 22554 + + val redFromRedChroma = IntArray(256) + val blueFromBlueChroma = IntArray(256) + val greenFromRedChroma = IntArray(256) + val greenFromBlueChroma = IntArray(256) + + init { + for (sampleValue in 0 until 256) { + // Chroma samples are stored biased by 128, so recenter before scaling. + val centered = sampleValue - 128 + redFromRedChroma[sampleValue] = (FIX_1_40200 * centered + ONE_HALF) shr SCALE_BITS + blueFromBlueChroma[sampleValue] = (FIX_1_77200 * centered + ONE_HALF) shr SCALE_BITS + // The green terms stay scaled; they are summed and shifted together by the caller. + greenFromRedChroma[sampleValue] = -FIX_0_71414 * centered + greenFromBlueChroma[sampleValue] = -FIX_0_34414 * centered + ONE_HALF + } + } +} + +/** + * Clamps a value to an 8-bit sample. + * + * @param Int value The value to clamp. + * @return Byte The 0..255 sample. + */ +private fun clampToByte(value: Int): Byte = + when { + value < 0 -> 0 + value > 255 -> 255.toByte() + else -> value.toByte() + } + +/** + * Divides rounding up, for non-negative operands. + * + * @param Int dividend The dividend. + * @param Int divisor The divisor. + * @return Int The rounded-up quotient. + */ +private fun ceilDivide(dividend: Int, divisor: Int): Int = (dividend + divisor - 1) / divisor \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegHuffman.kt b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegHuffman.kt new file mode 100644 index 0000000..108a290 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegHuffman.kt @@ -0,0 +1,191 @@ +// Baseline JPEG entropy decoding: the MSB-first bit reader with 0xFF00 byte de-stuffing (T.81 F.1.2.1) +// and the canonical Huffman DECODE procedure (T.81 Annex F, Figures F.12 / F.16). + +package org.umamo.format.jpeg + +/** + * A canonical JPEG Huffman table, built from a DHT segment's per-length code counts and value list. + * + * Decoding follows T.81 Figure F.16: walk one bit at a time, growing the code until it falls within + * the [minCode]/[maxCode] range recorded for the current code length. + */ +internal class JpegHuffmanTable(codeCountsPerLength: IntArray, private val values: IntArray) { + // Indexed by code length 1..16; index 0 is unused so the spec's 1-based lengths read directly. + private val minCode = IntArray(17) + private val maxCode = IntArray(17) + private val valuePointer = IntArray(17) + + init { + // T.81 Figure F.15: assign canonical codes in increasing length, then increasing value order. + var code = 0 + var valueIndex = 0 + for (codeLength in 1..16) { + val countAtLength = codeCountsPerLength[codeLength - 1] + if (countAtLength == 0) { + // No codes of this length; the sentinel makes the DECODE comparison always fall through. + maxCode[codeLength] = -1 + } else { + valuePointer[codeLength] = valueIndex + minCode[codeLength] = code + valueIndex += countAtLength + code += countAtLength + maxCode[codeLength] = code - 1 + } + code = code shl 1 + } + } + + /** + * Decodes one Huffman-coded symbol. + * + * @param JpegBitReader reader The entropy-coded bit source. + * @return Int The decoded symbol value. + */ + fun decode(reader: JpegBitReader): Int { + var code = reader.readBit() + var codeLength = 1 + while (code > maxCode[codeLength]) { + code = (code shl 1) or reader.readBit() + codeLength++ + require(codeLength <= 16) { "Invalid JPEG Huffman code (longer than 16 bits)" } + } + val index = valuePointer[codeLength] + code - minCode[codeLength] + require(index in values.indices) { "Invalid JPEG Huffman code (value index $index out of range)" } + return values[index] + } +} + +/** + * An MSB-first bit reader over JPEG entropy-coded data. + * + * Handles the 0xFF00 stuffed-zero convention (T.81 F.1.2.3). On reaching a real marker or the end of + * the buffer the reader pads with zero bits rather than failing, matching libjpeg's behavior for + * truncated scans; [markerReached] reports that the entropy segment has ended. + */ +internal class JpegBitReader(private val data: ByteArray, position: Int) { + /** The read cursor, left pointing at the 0xFF of a marker once one is reached. */ + var position: Int = position + private set + + /** True once a marker or the end of the buffer has been reached and bits are being zero-padded. */ + var markerReached: Boolean = false + private set + + private var bitBuffer = 0 + private var bitCount = 0 + + /** + * Reads the next entropy-coded bit, MSB first. + * + * @return Int The bit value (0 or 1); zero once the entropy segment has ended. + */ + fun readBit(): Int { + if (bitCount == 0) { + if (!fillBitBuffer()) { + return 0 + } + } + bitCount-- + return (bitBuffer shr bitCount) and 1 + } + + /** + * Reads [count] bits as an unsigned value, MSB first (the T.81 RECEIVE procedure, Figure F.17). + * + * @param Int count The number of bits to read (0..16). + * @return Int The bits as an unsigned integer. + */ + fun readBits(count: Int): Int { + var value = 0 + for (bitIndex in 0 until count) { + value = (value shl 1) or readBit() + } + return value + } + + /** + * Loads the next entropy-coded byte into the bit buffer, de-stuffing 0xFF00. + * + * @return Boolean False when a marker or the buffer end stopped the fill (bits are zero-padded). + */ + private fun fillBitBuffer(): Boolean { + if (position >= data.size) { + markerReached = true + return false + } + var nextByte = data[position].toInt() and 0xFF + if (nextByte == 0xFF) { + // Skip any fill bytes preceding a marker (T.81 B.1.1.2 permits 0xFF padding). + var lookahead = position + 1 + while (lookahead < data.size && (data[lookahead].toInt() and 0xFF) == 0xFF) { + lookahead++ + } + if (lookahead >= data.size) { + position = data.size + markerReached = true + return false + } + val following = data[lookahead].toInt() and 0xFF + if (following != 0x00) { + // A real marker: leave the cursor on its 0xFF so the caller can identify it. + position = lookahead - 1 + markerReached = true + return false + } + // A stuffed zero: the 0xFF is literal data and the 0x00 is dropped. + position = lookahead + 1 + nextByte = 0xFF + } else { + position++ + } + bitBuffer = nextByte + bitCount = 8 + return true + } + + /** + * Discards buffered bits and consumes the next restart marker, per T.81 F.2.1.3.1. + * + * @return Boolean Whether a restart marker was found and consumed. + */ + fun restart(): Boolean { + bitCount = 0 + markerReached = false + // The marker should sit at the cursor once bits are dropped, but tolerate stray fill bytes. + var scan = position + while (scan + 1 < data.size) { + if ((data[scan].toInt() and 0xFF) == 0xFF) { + val marker = data[scan + 1].toInt() and 0xFF + if (marker in JpegConstants.MARKER_RST0..JpegConstants.MARKER_RST7) { + position = scan + 2 + return true + } + if (marker != 0xFF && marker != 0x00) { + // Some other marker: the scan is over, leave the cursor for the caller. + position = scan + markerReached = true + return false + } + } + scan++ + } + position = data.size + markerReached = true + return false + } +} + +/** + * Sign-extends a [length]-bit Huffman-coded difference value (the T.81 EXTEND procedure, Figure F.12). + * + * @param Int value The raw magnitude bits from RECEIVE. + * @param Int length The number of bits read. + * @return Int The signed coefficient difference. + */ +internal fun extendJpegValue(value: Int, length: Int): Int { + if (length == 0) { + return 0 + } + // Values whose top bit is clear encode the negative half of the range. + return if (value < (1 shl (length - 1))) value - (1 shl length) + 1 else value +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegIdct.kt b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegIdct.kt new file mode 100644 index 0000000..09661be --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegIdct.kt @@ -0,0 +1,220 @@ +// Inverse DCT for baseline JPEG: the accurate integer ("islow") variant from the Independent JPEG +// Group's jidctint.c, a slow-but-exact 13-bit fixed-point implementation of the AAN-style separable +// IDCT described in T.81 Annex A.3.3. Implemented faithfully because the fixed-point rounding IS the +// output: libjpeg (and libjpeg-turbo, whose SIMD path is bit-exact with this C code) produce these +// exact samples, so a faithful port decodes byte-identically to every mainstream JPEG reader. + +package org.umamo.format.jpeg + +/** + * The 8x8 inverse DCT, integer "islow" variant. + * + * Pass 1 transforms columns into a workspace scaled up by 2^PASS1_BITS; pass 2 transforms rows and + * descales, level-shifts by +128, and clamps to 0..255. + */ +internal object JpegIdct { + // Fixed-point precision. CONST_BITS is the multiplier scale; PASS1_BITS the inter-pass headroom. + private const val CONST_BITS = 13 + private const val PASS1_BITS = 2 + + // Cosine multipliers, each round(value * 2^CONST_BITS). Names carry the value they approximate. + private const val FIX_0_298631336 = 2446 + private const val FIX_0_390180644 = 3196 + private const val FIX_0_541196100 = 4433 + private const val FIX_0_765366865 = 6270 + private const val FIX_0_899976223 = 7373 + private const val FIX_1_175875602 = 9633 + private const val FIX_1_501321110 = 12299 + private const val FIX_1_847759065 = 15137 + private const val FIX_1_961570560 = 16069 + private const val FIX_2_053119869 = 16819 + private const val FIX_2_562915447 = 20995 + private const val FIX_3_072711026 = 25172 + + /** + * Rounds a fixed-point value down by [shift] bits, rounding half away from zero-ward as libjpeg does. + * + * @param Int value The scaled value. + * @param Int shift The number of fractional bits to drop. + * @return Int The descaled value. + */ + private fun descale(value: Int, shift: Int): Int = (value + (1 shl (shift - 1))) shr shift + + /** + * Performs the inverse DCT of one block, writing level-shifted, clamped 8-bit samples. + * + * @param IntArray coefficients 64 dequantized coefficients in natural (row-major) order. + * @param IntArray workspace A scratch buffer of at least 64 ints, reused across calls. + * @param ByteArray output The destination plane. + * @param Int outputOffset Index in [output] of the block's top-left sample. + * @param Int outputStride Distance in [output] between vertically adjacent samples. + */ + fun inverse(coefficients: IntArray, workspace: IntArray, output: ByteArray, outputOffset: Int, outputStride: Int) { + // Pass 1: columns. Results are scaled up by sqrt(8) * 2^PASS1_BITS relative to a true IDCT. + for (column in 0 until 8) { + // Most blocks have all-zero AC terms in a column; that column is then a flat DC value. + if (coefficients[column + 8] == 0 && + coefficients[column + 16] == 0 && + coefficients[column + 24] == 0 && + coefficients[column + 32] == 0 && + coefficients[column + 40] == 0 && + coefficients[column + 48] == 0 && + coefficients[column + 56] == 0 + ) { + val dcValue = coefficients[column] shl PASS1_BITS + for (row in 0 until 8) { + workspace[column + row * 8] = dcValue + } + continue + } + + // Even part: the rotator is sqrt(2) * c(-6). + var z2 = coefficients[column + 16] + var z3 = coefficients[column + 48] + var z1 = (z2 + z3) * FIX_0_541196100 + var tmp2 = z1 + z3 * -FIX_1_847759065 + var tmp3 = z1 + z2 * FIX_0_765366865 + + z2 = coefficients[column] + z3 = coefficients[column + 32] + var tmp0 = (z2 + z3) shl CONST_BITS + var tmp1 = (z2 - z3) shl CONST_BITS + + val tmp10 = tmp0 + tmp3 + val tmp13 = tmp0 - tmp3 + val tmp11 = tmp1 + tmp2 + val tmp12 = tmp1 - tmp2 + + // Odd part: i0..i3 are coefficients 7, 5, 3, 1. + tmp0 = coefficients[column + 56] + tmp1 = coefficients[column + 40] + tmp2 = coefficients[column + 24] + tmp3 = coefficients[column + 8] + + z1 = tmp0 + tmp3 + z2 = tmp1 + tmp2 + z3 = tmp0 + tmp2 + var z4 = tmp1 + tmp3 + val z5 = (z3 + z4) * FIX_1_175875602 // sqrt(2) * c3 + + tmp0 *= FIX_0_298631336 // sqrt(2) * (-c1+c3+c5-c7) + tmp1 *= FIX_2_053119869 // sqrt(2) * ( c1+c3-c5+c7) + tmp2 *= FIX_3_072711026 // sqrt(2) * ( c1+c3+c5-c7) + tmp3 *= FIX_1_501321110 // sqrt(2) * ( c1+c3-c5-c7) + z1 *= -FIX_0_899976223 // sqrt(2) * (c7-c3) + z2 *= -FIX_2_562915447 // sqrt(2) * (-c1-c3) + z3 *= -FIX_1_961570560 // sqrt(2) * (-c3-c5) + z4 *= -FIX_0_390180644 // sqrt(2) * (c5-c3) + + z3 += z5 + z4 += z5 + + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + + workspace[column] = descale(tmp10 + tmp3, CONST_BITS - PASS1_BITS) + workspace[column + 56] = descale(tmp10 - tmp3, CONST_BITS - PASS1_BITS) + workspace[column + 8] = descale(tmp11 + tmp2, CONST_BITS - PASS1_BITS) + workspace[column + 48] = descale(tmp11 - tmp2, CONST_BITS - PASS1_BITS) + workspace[column + 16] = descale(tmp12 + tmp1, CONST_BITS - PASS1_BITS) + workspace[column + 40] = descale(tmp12 - tmp1, CONST_BITS - PASS1_BITS) + workspace[column + 24] = descale(tmp13 + tmp0, CONST_BITS - PASS1_BITS) + workspace[column + 32] = descale(tmp13 - tmp0, CONST_BITS - PASS1_BITS) + } + + // Pass 2: rows. Descale by the pass-1 scale plus the IDCT's own factor of 8 (2^3). + for (row in 0 until 8) { + val rowBase = row * 8 + val outputRow = outputOffset + row * outputStride + + // Pass 1 fills in AC terms, so the all-zero shortcut hits far less often here, but it is cheap. + if (workspace[rowBase + 1] == 0 && + workspace[rowBase + 2] == 0 && + workspace[rowBase + 3] == 0 && + workspace[rowBase + 4] == 0 && + workspace[rowBase + 5] == 0 && + workspace[rowBase + 6] == 0 && + workspace[rowBase + 7] == 0 + ) { + val dcSample = clampToSample(descale(workspace[rowBase], PASS1_BITS + 3)) + for (column in 0 until 8) { + output[outputRow + column] = dcSample + } + continue + } + + // Even part: the rotator is sqrt(2) * c(-6). + var z2 = workspace[rowBase + 2] + var z3 = workspace[rowBase + 6] + var z1 = (z2 + z3) * FIX_0_541196100 + var tmp2 = z1 + z3 * -FIX_1_847759065 + var tmp3 = z1 + z2 * FIX_0_765366865 + + var tmp0 = (workspace[rowBase] + workspace[rowBase + 4]) shl CONST_BITS + var tmp1 = (workspace[rowBase] - workspace[rowBase + 4]) shl CONST_BITS + + val tmp10 = tmp0 + tmp3 + val tmp13 = tmp0 - tmp3 + val tmp11 = tmp1 + tmp2 + val tmp12 = tmp1 - tmp2 + + // Odd part: i0..i3 are coefficients 7, 5, 3, 1. + tmp0 = workspace[rowBase + 7] + tmp1 = workspace[rowBase + 5] + tmp2 = workspace[rowBase + 3] + tmp3 = workspace[rowBase + 1] + + z1 = tmp0 + tmp3 + z2 = tmp1 + tmp2 + z3 = tmp0 + tmp2 + var z4 = tmp1 + tmp3 + val z5 = (z3 + z4) * FIX_1_175875602 // sqrt(2) * c3 + + tmp0 *= FIX_0_298631336 + tmp1 *= FIX_2_053119869 + tmp2 *= FIX_3_072711026 + tmp3 *= FIX_1_501321110 + z1 *= -FIX_0_899976223 + z2 *= -FIX_2_562915447 + z3 *= -FIX_1_961570560 + z4 *= -FIX_0_390180644 + + z3 += z5 + z4 += z5 + + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + + output[outputRow] = clampToSample(descale(tmp10 + tmp3, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 7] = clampToSample(descale(tmp10 - tmp3, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 1] = clampToSample(descale(tmp11 + tmp2, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 6] = clampToSample(descale(tmp11 - tmp2, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 2] = clampToSample(descale(tmp12 + tmp1, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 5] = clampToSample(descale(tmp12 - tmp1, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 3] = clampToSample(descale(tmp13 + tmp0, CONST_BITS + PASS1_BITS + 3)) + output[outputRow + 4] = clampToSample(descale(tmp13 - tmp0, CONST_BITS + PASS1_BITS + 3)) + } + } + + /** + * Applies the JPEG level shift (+128) and clamps to an 8-bit sample. + * + * libjpeg reads a precomputed range-limit table here; for in-range coefficients that table is + * exactly this clamp, and out-of-range values only arise from corrupt data. + * + * @param Int value The descaled, zero-centered IDCT output. + * @return Byte The 0..255 sample. + */ + private fun clampToSample(value: Int): Byte { + val shifted = value + 128 + return when { + shifted < 0 -> 0 + shifted > 255 -> 255.toByte() + else -> shifted.toByte() + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegReader.kt new file mode 100644 index 0000000..9637582 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/jpeg/JpegReader.kt @@ -0,0 +1,73 @@ +package org.umamo.format.jpeg + +import org.umamo.format.FileKind +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.ReadOnlyRasterCodec + +/** + * Pure-Kotlin JPEG reader (desktop JVM and Android), read only. + * + * Decodes sequential (SOF0 / SOF1) and progressive (SOF2) Huffman JPEG, 8-bit, grayscale or + * 3-component color, with restart intervals and any sampling factors, to the neutral straight-alpha + * RGBA8888 top-first [RasterImage] (alpha is always opaque — JPEG carries no alpha channel). + * Progressive support matters in practice, not as a nicety: it is what most of the web serves, so the + * common art sources (Twitter/X, Pixiv, Photoshop "Save for Web") emit it by default. + * + * Lossless, arithmetic-coded, differential, 12-bit, and CMYK/YCCK frames are rejected with a clear + * message. Uses no javax.imageio, so it decodes identically on both targets. + */ +public object JpegReader : ReadOnlyRasterCodec { + override val kind: FileKind = FileKind.Jpeg + + /** + * True if [candidateBytes] opens with the JPEG SOI + marker prefix. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the JPEG magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean = + // JPEG (JFIF/EXIF): SOI marker 0xFFD8 followed by a further 0xFF marker byte. + candidateBytes.size >= 3 && + candidateBytes[0] == 0xFF.toByte() && + candidateBytes[1] == 0xD8.toByte() && + candidateBytes[2] == 0xFF.toByte() + + /** + * Decodes a `.jpg` into an opaque straight-alpha RGBA8888 [RasterImage], top row first. + * + * @param ByteArray bytes The complete `.jpg` file. + * @return RasterImage The decoded image. + */ + override fun read(bytes: ByteArray): RasterImage { + require(matches(bytes)) { "Not a JPEG (bad signature)" } + val decoded = decodeJpeg(bytes) + return RasterImage(decoded.width, decoded.height, expandToRgba(decoded)) + } + + /** + * Expands decoded grayscale or RGB samples to opaque RGBA8888. + * + * @param JpegImage decoded The decoded JPEG. + * @return ByteArray The RGBA8888 pixels. + */ + private fun expandToRgba(decoded: JpegImage): ByteArray { + val pixelCount = decoded.width * decoded.height + val rgba = ByteArray(pixelCount * 4) + for (pixelIndex in 0 until pixelCount) { + val destination = pixelIndex * 4 + if (decoded.componentCount == 1) { + val gray = decoded.samples[pixelIndex] + rgba[destination] = gray + rgba[destination + 1] = gray + rgba[destination + 2] = gray + } else { + val source = pixelIndex * 3 + rgba[destination] = decoded.samples[source] + rgba[destination + 1] = decoded.samples[source + 1] + rgba[destination + 2] = decoded.samples[source + 2] + } + rgba[destination + 3] = 0xFF.toByte() + } + return rgba + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraChannelMask.kt b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraChannelMask.kt new file mode 100644 index 0000000..a7c4342 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraChannelMask.kt @@ -0,0 +1,48 @@ +package org.umamo.format.kra + +import org.umamo.format.art.ChannelMask + +/* + * The channelflags -> ChannelMask mapping, split out of KraReader so it can live in commonMain. + * + * KraReader itself cannot: it is a zip container plus a JDOM/SAX XML parse, both JVM-only, so it + * stays in jvmAndroidMain alongside the FormatRegistry that is its only non-test caller. This + * mapping is pure arithmetic over a string and belongs with the rest of KRA's platform-free logic + * (KraColorModel, KraLzf, KraTileData), where KraChannelMaskTest can reach it from commonTest and + * exercise it on every target. + */ + +/** + * Builds the neutral per-channel mask from Krita's channelflags attribute. + * + * channelflags is a per-channel enable mask in channel-index order ('0' disables a channel, + * anything else enables it; indices beyond the string default to enabled), or empty meaning all + * channels enabled. The channel-index order is the color space's own: for RGB it is Blue, Green, + * Red, Alpha (the addChannel sequence in RgbU8ColorSpace.cpp), and for GRAYA it is Gray, Alpha. + * Grayscale's single gray channel maps onto R, G, and B together, because the raster expands gray + * to RGB. + * + * A disabled alpha is Krita's "Inherit Alpha", which the caller maps onto the neutral clipped flag. + * That clipping is an approximation: PSD clips to the single base layer directly below, whereas + * Krita clips to the composite of everything below in the group. + * + * @param String? channelFlags The layer's channelflags attribute (null/empty means all enabled). + * @param KraPixelFormat format The resolved pixel format (gives channel family and order). + * @return ChannelMask the enabled state of the output red/green/blue/alpha channels. + */ +internal fun channelMaskFrom(channelFlags: String?, format: KraPixelFormat): ChannelMask { + // KRA: kis_kra_utils.cpp stringToFlags ('0' disables, default enabled); channel order from the + // color space addChannel sequence (RgbU8ColorSpace.cpp / GrayU8ColorSpace.cpp). + if (channelFlags.isNullOrEmpty()) { + return ChannelMask.ALL + } + + fun channelEnabled(channelIndex: Int): Boolean = + channelIndex !in channelFlags.indices || channelFlags[channelIndex] != '0' + return if (format.isRgb) { + ChannelMask(red = channelEnabled(2), green = channelEnabled(1), blue = channelEnabled(0), alpha = channelEnabled(3)) + } else { + val grayEnabled = channelEnabled(0) + ChannelMask(red = grayEnabled, green = grayEnabled, blue = grayEnabled, alpha = channelEnabled(1)) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraColorModel.kt b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraColorModel.kt new file mode 100644 index 0000000..d0b4197 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraColorModel.kt @@ -0,0 +1,171 @@ +package org.umamo.format.kra + +/** + * Maps a Krita layer's color space onto a converter that packs each source pixel into the neutral + * model's RGBA8888 straight-alpha format. + * + * Two things vary between Krita color spaces and must be handled here. First, channel byte order: + * Krita's integer RGB spaces store BGRA (KoBgrU8Traits / KoBgrU16Traits with blue at 0, green at 1, + * red at 2), while its float RGB space stores RGBA (KoRgbColorSpaceTraits with red at 0, green at 1, + * blue at 2). Grayscale is gray then alpha (KoGrayColorSpaceTraits). Second, bit depth: 8/16-bit + * integer and 32-bit float, down-converted to 8-bit (16-bit keeps the most-significant byte; float + * is clamped to 0..1 and scaled). The model is always RGBA8888, so high-depth precision cannot be + * preserved regardless - this is lossy by the model's contract. + * + * Scope: RGBA and GRAYA in U8, U16, and F32. Half-float (F16) and other models (CMYK, LAB, XYZ, + * YCbCr) raise a clear error rather than silently mis-decoding. + * + * Krita のカラースペースを RGBA8888 へ変換する。整数 RGB は BGRA、浮動小数 RGB は RGBA、グレースケールは + * gray, alpha の順。8/16/32 ビットに対応し 8 ビットへ縮約する。 + */ +internal enum class KraColorDepth { + UnsignedByte, // U8 + UnsignedShort, // U16 + Float32, // F32 +} + +/** + * A resolved per-layer pixel layout plus the logic to convert one source pixel to RGBA8888. + * + * @property Int channelCount Channels in the source pixel (RGBA is 4, GRAYA is 2). + * @property KraColorDepth depth Source bit depth. + * @property Boolean isRgb True for the RGBA family, false for GRAYA. + */ +internal class KraPixelFormat( + val channelCount: Int, + val depth: KraColorDepth, + val isRgb: Boolean, +) { + val bytesPerChannel: Int = + when (depth) { + KraColorDepth.UnsignedByte -> 1 + KraColorDepth.UnsignedShort -> 2 + KraColorDepth.Float32 -> 4 + } + + /** Bytes per source pixel - must equal the tile file's PIXELSIZE. */ + val pixelSize: Int = channelCount * bytesPerChannel + + /** + * Converts the source pixel at sourceOffset in source to four RGBA8888 bytes written at + * destinationOffset in destination. + * + * @param ByteArray source Interleaved native-order pixel bytes (one tile or row). + * @param Int sourceOffset Byte offset of the source pixel. + * @param ByteArray destination RGBA8888 output buffer. + * @param Int destinationOffset Byte offset of the destination pixel (4 bytes written). + */ + fun convertPixel( + source: ByteArray, + sourceOffset: Int, + destination: ByteArray, + destinationOffset: Int, + ) { + if (isRgb) { + when (depth) { + // KRA: KoBgrU8Traits - blue at 0, green at 1, red at 2, alpha at 3. + KraColorDepth.UnsignedByte -> { + destination[destinationOffset] = source[sourceOffset + 2] // red + destination[destinationOffset + 1] = source[sourceOffset + 1] // green + destination[destinationOffset + 2] = source[sourceOffset] // blue + destination[destinationOffset + 3] = source[sourceOffset + 3] // alpha + } + // KRA: KoBgrU16Traits - BGRA, little-endian; keep the MSB (offset+1 of each pair). + KraColorDepth.UnsignedShort -> { + destination[destinationOffset] = source[sourceOffset + 5] // red MSB + destination[destinationOffset + 1] = source[sourceOffset + 3] // green MSB + destination[destinationOffset + 2] = source[sourceOffset + 1] // blue MSB + destination[destinationOffset + 3] = source[sourceOffset + 7] // alpha MSB + } + // KRA: KoRgbColorSpaceTraits - float RGB is red-first (RGBA), 32-bit little-endian. + KraColorDepth.Float32 -> { + destination[destinationOffset] = floatByteToUnorm8(source, sourceOffset) // red + destination[destinationOffset + 1] = floatByteToUnorm8(source, sourceOffset + 4) // green + destination[destinationOffset + 2] = floatByteToUnorm8(source, sourceOffset + 8) // blue + destination[destinationOffset + 3] = floatByteToUnorm8(source, sourceOffset + 12) // alpha + } + } + } else { + // Grayscale: replicate the single grey channel into R/G/B. KRA: KoGrayColorSpaceTraits. + val grayByte: Byte + val alphaByte: Byte + when (depth) { + KraColorDepth.UnsignedByte -> { + grayByte = source[sourceOffset] + alphaByte = source[sourceOffset + 1] + } + + KraColorDepth.UnsignedShort -> { + grayByte = source[sourceOffset + 1] // gray MSB + alphaByte = source[sourceOffset + 3] // alpha MSB + } + + KraColorDepth.Float32 -> { + grayByte = floatByteToUnorm8(source, sourceOffset) + alphaByte = floatByteToUnorm8(source, sourceOffset + 4) + } + } + destination[destinationOffset] = grayByte + destination[destinationOffset + 1] = grayByte + destination[destinationOffset + 2] = grayByte + destination[destinationOffset + 3] = alphaByte + } + } +} + +/** + * Reads a 32-bit little-endian float at offset in source and quantises it to an 8-bit unorm byte + * (clamped to 0..1, scaled by 255, rounded). + * + * @param ByteArray source Buffer holding the float. + * @param Int offset Byte offset of the 4-byte little-endian float. + * @return Byte the quantised 0..255 channel value (as a signed Byte). + */ +private fun floatByteToUnorm8(source: ByteArray, offset: Int): Byte { + val bits = + (source[offset].toInt() and 0xFF) or + ((source[offset + 1].toInt() and 0xFF) shl 8) or + ((source[offset + 2].toInt() and 0xFF) shl 16) or + ((source[offset + 3].toInt() and 0xFF) shl 24) + val value = Float.fromBits(bits) + val clamped = value.coerceIn(0f, 1f) + return (clamped * 255f + 0.5f).toInt().toByte() +} + +/** + * Resolves a Krita colorspacename (such as RGBA, RGBA16, RGBAF32, or GRAYA) to a KraPixelFormat, + * cross-checking the implied pixel size against the tile file's authoritative PIXELSIZE. + * + * Family comes from the prefix (RGBA or GRAYA) and depth from a suffix scan (F32 means float, F16 + * is unsupported, any 16 means uint16, otherwise uint8) - robust across Krita's historically + * inconsistent names without enumerating every exact string. + * + * @param String colorspaceName The layer's colorspacename attribute. + * @param Int tilePixelSize Bytes per pixel from the tile header (PIXELSIZE). + * @return KraPixelFormat the resolved layout and converter. + * @throws IllegalArgumentException on an unsupported model/depth or a size mismatch. + */ +internal fun resolveKraPixelFormat(colorspaceName: String, tilePixelSize: Int): KraPixelFormat { + val normalized = colorspaceName.uppercase() + val isRgb = normalized.startsWith("RGBA") + val isGray = normalized.startsWith("GRAYA") + require(isRgb || isGray) { + "Unsupported KRA color model '$colorspaceName' - only RGBA and GRAYA are supported" + } + + val depth = + when { + normalized.contains("F32") -> KraColorDepth.Float32 + normalized.contains("F16") -> + error("Unsupported KRA color depth (half-float) '$colorspaceName'") + + normalized.contains("16") -> KraColorDepth.UnsignedShort + else -> KraColorDepth.UnsignedByte + } + + val format = KraPixelFormat(channelCount = if (isRgb) 4 else 2, depth = depth, isRgb = isRgb) + require(format.pixelSize == tilePixelSize) { + "KRA pixel-size mismatch: tile header says $tilePixelSize, '$colorspaceName' implies ${format.pixelSize}" + } + return format +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraLzf.kt b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraLzf.kt new file mode 100644 index 0000000..9f71b7f --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraLzf.kt @@ -0,0 +1,138 @@ +package org.umamo.format.kra + +/* + * Krita tile (de)serialisation primitives: the LZF decompressor and the color "delinearisation" + * that together reverse what Krita writes for each 64x64 tile. + * + * Krita compresses tile pixels with a fast LZF variant (a Lempel-Ziv byte coder), and - before + * compressing - reorders the interleaved pixel bytes into a planar layout (all of channel 0, then + * all of channel 1, and so on) because runs of one channel compress far better. Reading is the + * mirror: LZF-decompress, then de-interleave back to packed pixels. + * + * Pure Kotlin with no platform APIs, so it lives below the ZIP/XML orchestration and is unit + * testable on its own. Ported verbatim from Krita's GPL source. + * + * Krita タイルの復号プリミティブ。LZF 伸長と平面→インターリーブ変換。プラットフォーム非依存。 + */ + +// KRA: kis_tile_compressor_2.cpp - first payload byte selects raw vs LZF-compressed tile data. +internal const val KRA_RAW_DATA_FLAG: Int = 0 +internal const val KRA_COMPRESSED_DATA_FLAG: Int = 1 + +/** + * Decompresses one LZF stream into output, a direct port of Krita's lzff_decompress. + * + * The coder emits a stream of control bytes. A control byte whose value is below 32 starts a + * literal run of value-plus-one raw bytes; otherwise its top 3 bits are a back-reference length and + * its low 5 bits are the high bits of a back-reference distance (the next byte carries the low 8 + * bits, and a length of 7 means "read one more byte and add it"). Back-references copy + * already-decoded bytes, so output must be written strictly left to right. + * + * @param ByteArray input Buffer holding the compressed stream. + * @param Int inputOffset Index in input where the stream starts (skip the flag byte). + * @param Int inputLength Number of compressed bytes to read from inputOffset. + * @param ByteArray output Destination for the decoded bytes (sized to the exact tile size). + * @return Int the number of bytes written to output; 0 on a malformed or overrunning stream. + */ +internal fun lzfDecompress( + input: ByteArray, + inputOffset: Int, + inputLength: Int, + output: ByteArray, +): Int { + var inputPos = inputOffset + // KRA: kis_lzf_compression.cpp:176 - ip_limit = ip + length - 1 (last byte is never a header). + val inputLimit = inputOffset + inputLength - 1 + var outputPos = 0 + val outputLimit = output.size + + while (inputPos < inputLimit) { + // KRA: kis_lzf_compression.cpp:182-184 - control byte; all three values read the same byte. + val control = input[inputPos].toInt() and 0xFF + inputPos++ + val literalRunLength = control + 1 // The "ctrl" value: byte count when this is a literal run. + var backReferenceLength = control ushr 5 + + if (literalRunLength < 33) { + // Literal copy of literalRunLength raw bytes. KRA: kis_lzf_compression.cpp:186-208. + if (outputPos + literalRunLength > outputLimit) { + return 0 + } + var remaining = literalRunLength + while (remaining > 0) { + output[outputPos] = input[inputPos] + outputPos++ + inputPos++ + remaining-- + } + } else { + // Back reference. KRA: kis_lzf_compression.cpp:209-232. + backReferenceLength -= 1 + // ref = op - ofs; ref-- where ofs = (control & 31) << 8. + var referencePos = outputPos - ((control and 31) shl 8) - 1 + if (backReferenceLength == 6) { + backReferenceLength += input[inputPos].toInt() and 0xFF + inputPos++ + } + referencePos -= input[inputPos].toInt() and 0xFF + inputPos++ + if (outputPos + backReferenceLength + 3 > outputLimit) { + return 0 + } + if (referencePos < 0) { + return 0 + } + // 3 bytes always, then backReferenceLength more (the length is biased by 3). + output[outputPos] = output[referencePos] + outputPos++ + referencePos++ + output[outputPos] = output[referencePos] + outputPos++ + referencePos++ + output[outputPos] = output[referencePos] + outputPos++ + referencePos++ + while (backReferenceLength > 0) { + output[outputPos] = output[referencePos] + outputPos++ + referencePos++ + backReferenceLength-- + } + } + } + return outputPos +} + +/** + * Reverses Krita's color "linearisation": turns a planar buffer (channel 0 for every pixel, then + * channel 1, and so on) back into packed interleaved pixels (b,g,r,a,b,g,r,a and onward). + * + * Mirror of KisAbstractCompression::delinearizeColors: with stride equal to dataSize / pixelSize + * (the pixel count), output byte pixel * pixelSize + channel reads input byte channelstride + pixel. + * Only compressed tiles are linearised; raw tiles are already interleaved. + * + * @param ByteArray planarInput The de-compressed, planar tile bytes. + * @param ByteArray packedOutput Destination for interleaved pixels (same length as planarInput). + * @param Int dataSize Total byte count (pixelSize * tileWidth * tileHeight). + * @param Int pixelSize Bytes per pixel (channel count times bytes per channel). + */ +internal fun delinearizeColors( + planarInput: ByteArray, + packedOutput: ByteArray, + dataSize: Int, + pixelSize: Int, +) { + // KRA: kis_abstract_compression.cpp:38-66 - stride is the per-channel run length (pixel count). + val strideSize = dataSize / pixelSize + var outputPos = 0 + var pixelStartByte = 0 + while (outputPos < dataSize) { + var inputPos = pixelStartByte + for (channelIndex in 0 until pixelSize) { + packedOutput[outputPos] = planarInput[inputPos] + outputPos++ + inputPos += strideSize + } + pixelStartByte++ + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraTileData.kt b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraTileData.kt new file mode 100644 index 0000000..fb405c3 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/kra/KraTileData.kt @@ -0,0 +1,185 @@ +package org.umamo.format.kra + +import org.umamo.format.binary.decodeAscii + +/* + * Parser for one Krita layer's tiled pixel-data file (the imageName/layers/filename entry inside + * the ZIP). + * + * The file is a tiny ASCII header followed by a sequence of tiles. Each tile is a 64x64 block at a + * given paint-device coordinate; a tile is present only where the layer has content (Krita's canvas + * is unbounded), so the layer's extent is the union of its tile rectangles. + * + * The header is one KEY VALUE pair per newline-terminated line, in this order: VERSION 2, + * TILEWIDTH 64, TILEHEIGHT 64, PIXELSIZE bytesPerPixel, DATA tileCount. Each tile then has a line + * x,y,LZF,dataSize followed by dataSize bytes whose first byte flags raw vs LZF-compressed payload + * (see decodeTilePayload). + * + * KRA: header in kis_tiled_data_manager.cc:181-196; per-tile framing in kis_tile_compressor_2.cpp. + * + * Krita レイヤーのタイル化ピクセルデータの解析。ASCII ヘッダとタイル列。タイルは内容のある箇所のみ存在する。 + */ + +/** One decoded 64x64 tile: its top-left paint-device coordinate and interleaved native-order pixels. */ +internal class KraTile( + val left: Int, + val top: Int, + val pixels: ByteArray, +) + +/** A layer's full tile set plus the geometry needed to assemble it. */ +internal class KraLayerTiles( + val tileWidth: Int, + val tileHeight: Int, + val pixelSize: Int, + val tiles: List, +) + +/** + * Parses a layer data file into its decoded tiles (each tile's pixels are interleaved, native + * channel order - color conversion happens later, once the layer's KraPixelFormat is known). + * + * @param ByteArray data The complete layer data file bytes. + * @return KraLayerTiles the geometry and decoded tiles. + * @throws IllegalArgumentException on an unexpected version, header, or a tile that fails to decode. + */ +internal fun parseKraLayerTiles(data: ByteArray): KraLayerTiles { + val cursor = AsciiLineCursor(data) + + val version = headerValue(cursor.readLine(), "VERSION") + require(version == 2) { + "Unsupported KRA tile format version $version (expected 2)" + } + val tileWidth = headerValue(cursor.readLine(), "TILEWIDTH") + val tileHeight = headerValue(cursor.readLine(), "TILEHEIGHT") + val pixelSize = headerValue(cursor.readLine(), "PIXELSIZE") + val tileCount = headerValue(cursor.readLine(), "DATA") + + val tileDataSize = pixelSize * tileWidth * tileHeight + val tiles = ArrayList(tileCount) + + for (tileIndex in 0 until tileCount) { + // Tile header: x,y,LZF,dataSize. KRA: kis_tile_compressor_2.cpp:56-66. + val fields = cursor.readLine().split(',') + require(fields.size == 4) { + "Malformed KRA tile header at tile $tileIndex" + } + val left = fields[0].trim().toInt() + val top = fields[1].trim().toInt() + val compressionName = fields[2].trim() + val dataSize = fields[3].trim().toInt() + require(compressionName == "LZF") { + "Unsupported KRA tile compression '$compressionName' (expected LZF)" + } + + val payloadOffset = cursor.position + val decoded = decodeTilePayload(data, payloadOffset, dataSize, tileDataSize, pixelSize) + cursor.skip(dataSize) + + tiles.add(KraTile(left = left, top = top, pixels = decoded)) + } + + return KraLayerTiles(tileWidth = tileWidth, tileHeight = tileHeight, pixelSize = pixelSize, tiles = tiles) +} + +/** + * Decodes one tile payload into interleaved native-order pixels. + * + * The first payload byte is the flag: KRA_RAW_DATA_FLAG means the remaining tileDataSize bytes are + * the pixels verbatim; KRA_COMPRESSED_DATA_FLAG means an LZF stream that inflates to a planar + * buffer, which is then de-interleaved with delinearizeColors. + * + * @param ByteArray data Buffer holding the tile payload. + * @param Int payloadOffset Offset of the flag byte. + * @param Int dataSize Total payload length (flag byte plus data). + * @param Int tileDataSize Expected decoded size (pixelSize * tileWidth * tileHeight). + * @param Int pixelSize Bytes per pixel (needed to de-interleave). + * @return ByteArray the decoded, interleaved tile pixels (tileDataSize bytes). + */ +private fun decodeTilePayload( + data: ByteArray, + payloadOffset: Int, + dataSize: Int, + tileDataSize: Int, + pixelSize: Int, +): ByteArray { + val flag = data[payloadOffset].toInt() and 0xFF + val packed = ByteArray(tileDataSize) + when (flag) { + KRA_RAW_DATA_FLAG -> { + // Already interleaved; copy the tileDataSize bytes after the flag. + data.copyInto( + packed, + destinationOffset = 0, + startIndex = payloadOffset + 1, + endIndex = payloadOffset + 1 + tileDataSize, + ) + } + + KRA_COMPRESSED_DATA_FLAG -> { + val planar = ByteArray(tileDataSize) + val written = lzfDecompress(data, payloadOffset + 1, dataSize - 1, planar) + require(written == tileDataSize) { + "KRA tile LZF decode produced $written bytes, expected $tileDataSize" + } + delinearizeColors(planar, packed, tileDataSize, pixelSize) + } + + else -> error("Unknown KRA tile data flag $flag") + } + return packed +} + +/** + * Parses a KEY value header line and returns the integer value, asserting the key matches. + * + * @param String line The header line (already newline-stripped). + * @param String expectedKey The key this line must start with. + * @return Int the parsed value. + */ +private fun headerValue(line: String, expectedKey: String): Int { + val parts = line.trim().split(' ', limit = 2) + require(parts.size == 2 && parts[0] == expectedKey) { + "Expected KRA tile header '$expectedKey ', got '$line'" + } + return parts[1].trim().toInt() +} + +/** + * A tiny forward cursor that reads newline-terminated ASCII lines out of a mixed text/binary + * buffer, then hands off raw byte offsets for the binary tile payloads that follow each header line. + * + * @property ByteArray data The backing buffer. + */ +private class AsciiLineCursor(private val data: ByteArray) { + var position: Int = 0 + private set + + private val newline: Byte = '\n'.code.toByte() + + /** + * Reads from the current position up to and consuming the next newline, returning the text. + * + * @return String the line without its trailing newline. + */ + fun readLine(): String { + val start = position + while (position < data.size && data[position] != newline) { + position++ + } + val line = decodeAscii(data, start, position - start) + if (position < data.size) { + position++ // consume the newline + } + return line + } + + /** + * Advances the cursor past count bytes of binary payload. + * + * @param Int count The number of bytes to skip. + */ + fun skip(count: Int) { + position += count + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/Moc3.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/Moc3.kt new file mode 100644 index 0000000..778133f --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/Moc3.kt @@ -0,0 +1,170 @@ +package org.umamo.format.moc3 + +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString +import org.umamo.format.FileKind +import org.umamo.format.FormatCodec +import org.umamo.format.FormatVersion +import org.umamo.format.moc3.decode.MocDecoder +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.format.moc3.json.Model3Json +import org.umamo.format.moc3.json.Physics3Json +import org.umamo.format.moc3.json.SidecarJson +import org.umamo.format.moc3.json.UserData3Json +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocModel +import org.umamo.format.moc3.moc.MocVersion + +/** + * Reads and writes Live2D Cubism runtime assets: the `.moc3` binary model and its JSON sidecars. + * + * Implements [FormatCodec] at the SEMANTIC tier: [read] decodes a file all the way to [MocDocument], + * and [write] synthesizes every section back from one, so read - edit - write is a real cycle here + * rather than a byte copy. Byte-exact container fidelity lives one layer down in [MocCodec], whose + * own read/write reproduce an unedited file byte-for-byte; reach that tier through [decode] and + * [bake] when the raw sections are what a caller needs. This is the same split CMO3 has, where the + * codec re-emits the model graph and CaffCodec holds the container bytes. + * + * The JSON sidecar helpers handle `model3.json` and friends. Those sidecars are `String`-shaped + * (not `ByteArray`), so they sit alongside the [FormatCodec] members rather than within them. The + * `.moc3` and its sidecars are sibling files (the manifest references the rest by path), so they are + * decoupled here - pair them yourself. Pure Kotlin (JVM + Android); no JDOM/reflection. + * + * @see MOC3.md §8 + */ +public object Moc3 : FormatCodec { + /** This codec handles [FileKind.Moc3]. */ + override val kind: FileKind get() = FileKind.Moc3 + + /** + * True if [candidateBytes] starts with the `MOC3` magic and is at least header-sized. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether this looks like a `.moc3`. + */ + override fun matches(candidateBytes: ByteArray): Boolean = MocCodec.isMoc3(candidateBytes) + + /** + * Cheap version probe: reads the version byte without parsing the section table. + * + * @param ByteArray bytes The complete file contents. + * @return FormatVersion? The `.moc3` version, or null when the magic or byte is unrecognized. + */ + override fun getVersion(bytes: ByteArray): FormatVersion? { + if (!MocCodec.isMoc3(bytes)) { + return null + } + // MOC3.md §version gating: version byte @ +0x04. + val versionByte = bytes[4].toInt() and 0xFF + return MocVersion.entries.firstOrNull { it.byteValue == versionByte } + } + + /** + * Parses a `.moc3` and decodes it to the full semantic [MocDocument]. + * + * @param ByteArray bytes The file contents. + * @return MocDocument The decoded document. + */ + override fun read(bytes: ByteArray): MocDocument = MocDecoder.decode(MocCodec.read(bytes)) + + /** + * Bakes [model] to runtime-valid `.moc3` bytes, synthesizing every section from the object model + * with no reference container involved. + * + * The output is runtime-valid, not byte-identical to whatever file the document was read from: the + * section layout is ours rather than the editor's. Go through [MocCodec] when a byte-exact re-emit + * of an unedited container is the point. + * + * @param MocDocument model The document to bake. + * @return ByteArray The complete `.moc3` file bytes. + */ + override fun write(model: MocDocument): ByteArray = MocEncoder.bakeFresh(model.version, model) + + /** + * Decodes an already-parsed [MocModel] into the full semantic [MocDocument] - the container-tier + * entry, paired with [MocCodec.read] by a caller that wants the raw sections too. + * + * @param MocModel model The parsed model. + * @return MocDocument The decoded document. + */ + public fun decode(model: MocModel): MocDocument = MocDecoder.decode(model) + + /** + * Bakes a (possibly-edited) [doc] onto [reference], synthesizing every section the lowering covers + * and carrying anything it does not from the reference container. + * + * That carry-through is empty for every corpus model (`MocBakeFreshCoverageTest` pins the carried + * set at nothing), so it stands against a section some later format version adds rather than against + * one we cannot derive. [write] is the reference-free form, and what an export uses. + * + * @param MocModel reference The decoded source providing the carried sections and the version. + * @param MocDocument doc The document to bake. + * @return ByteArray The baked `.moc3` file bytes. + */ + public fun bake(reference: MocModel, doc: MocDocument): ByteArray = MocEncoder.bake(reference, doc) + + /** + * Parses a `model3.json` manifest. + * + * @param String text The file contents. + * @return Model3Json The parsed manifest. + */ + public fun readModel3(text: String): Model3Json = SidecarJson.decodeFromString(text) + + /** + * Serializes a `model3.json` manifest (matches the editor's formatting). + * + * @param Model3Json model The manifest to write. + * @return String The serialized JSON. + */ + public fun writeModel3(model: Model3Json): String = SidecarJson.encodeToString(model) + + /** + * Parses a `physics3.json` rig definition. + * + * @param String text The file contents. + * @return Physics3Json The parsed rig definition. + */ + public fun readPhysics3(text: String): Physics3Json = SidecarJson.decodeFromString(text) + + /** + * Serializes a `physics3.json` rig definition. + * + * @param Physics3Json physics The rig definition to write. + * @return String The serialized JSON. + */ + public fun writePhysics3(physics: Physics3Json): String = SidecarJson.encodeToString(physics) + + /** + * Parses a `cdi3.json` display-info file. + * + * @param String text The file contents. + * @return Cdi3Json The parsed display info. + */ + public fun readCdi3(text: String): Cdi3Json = SidecarJson.decodeFromString(text) + + /** + * Serializes a `cdi3.json` display-info file. + * + * @param Cdi3Json displayInfo The display info to write. + * @return String The serialized JSON. + */ + public fun writeCdi3(displayInfo: Cdi3Json): String = SidecarJson.encodeToString(displayInfo) + + /** + * Parses a `userdata3.json` file. + * + * @param String text The file contents. + * @return UserData3Json The parsed user data. + */ + public fun readUserData3(text: String): UserData3Json = SidecarJson.decodeFromString(text) + + /** + * Serializes a `userdata3.json` file. + * + * @param UserData3Json userData The user data to write. + * @return String The serialized JSON. + */ + public fun writeUserData3(userData: UserData3Json): String = SidecarJson.encodeToString(userData) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/MocDocument.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/MocDocument.kt new file mode 100644 index 0000000..1d0f105 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/MocDocument.kt @@ -0,0 +1,65 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.CanvasInfo +import org.umamo.format.moc3.moc.MocParameter +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.model.ArtMesh +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.Deformer +import org.umamo.format.moc3.model.Glue +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.format.moc3.model.Offscreen +import org.umamo.format.moc3.model.Part +import org.umamo.format.moc3.model.RenderOrderGroup + +/** + * The fully decoded semantic model of a `.moc3` - the agnostic intermediate for editor + * reconstruction and (later) the bake. + * + * Objects reference each other and parameters by index (their position in these lists). Each + * deformable object names a `keyformBindingIndex`; look the binding up with [keyformBinding] to + * learn the controlling parameters and key positions for its keyforms. The per-frame + * interpolation/deformation math is intentionally not modelled - this is the stored data. + * Blend shapes (moc 4+) and offscreens (moc 6) are assembled into [blendShapes]/[offscreens]; + * every section index is modeled in `Section`, though 149-151 (glue blend shapes) + * decode to nothing because no corpus sample carries one. + * + * @see MOC3.md §5 + */ +public class MocDocument( + public val version: MocVersion, + public val canvas: CanvasInfo?, + public val parameters: List, + private val keyformBindings: Map, + public val parts: List, + public val deformers: List, + public val artMeshes: List, + public val glues: List, + public val renderOrderGroups: List, + /** Blend-shape records (moc 4+); empty on older versions. */ + public val blendShapes: List = emptyList(), + /** Offscreen render targets (moc 6); empty on older versions. */ + public val offscreens: List = emptyList(), + /** + * Whether a blend-free file's KEY_POSITIONS (section 77) carries the trailing per-parameter + * sorted-union key region. This is an editor-version artifact: some Cubism editor builds append + * the union of each parameter's main-grid axis keys after the parameter-binding dedup region, + * others omit it, and no other section or header field distinguishes the two (probed across the + * v1/v3 corpus - the section tables and headers are byte-identical). Carried so the lowering can + * reproduce section 77 byte-exact; the runtime recomputes the same unions when the region is + * absent (a model with multi-keyset parameters loads correctly either way). A blend model always + * carries the region unconditionally, so this flag only disambiguates the blend-free path. + */ + public val keyPositionsHasParameterUnion: Boolean = false, +) { + /** All resolved keyform bindings referenced by objects, ascending by index. */ + public val bindings: List get() = keyformBindings.values.sortedBy { it.index } + + /** + * The keyform binding with the given index, or null if no object references it. + * + * @param Int index A `keyformBindingIndex` from an object. + * @return KeyformBinding? The resolved binding. + */ + public fun keyformBinding(index: Int): KeyformBinding? = keyformBindings[index] +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocArtMeshDecoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocArtMeshDecoder.kt new file mode 100644 index 0000000..773efcc --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocArtMeshDecoder.kt @@ -0,0 +1,126 @@ +package org.umamo.format.moc3.decode + +import org.umamo.format.moc3.moc.MocDrawable +import org.umamo.format.moc3.moc.MocSections +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.ArtMesh +import org.umamo.format.moc3.model.ArtMeshKeyform + +/** + * Decodes the drawables into [ArtMesh]es: their geometry slices and per-keyform values. + * + * A drawable's UVs, triangle indices, and mask indices are not addressed by any index table - + * they are CONCATENATED per drawable in drawable order, so the decode carries a running cursor + * per table and advances it by that drawable's own counts. The mask cursor is the one that does + * not start at zero: the offscreen mask entries are the block's prefix (MOC3 v6 §5.6 section 80). + */ +internal class MocArtMeshDecoder( + sections: MocSections, + private val bindings: MocBindingResolver, + private val colorTables: ColorTables, + private val keyformValues: KeyformValueTables, + private val maskData: IntArray, +) { + private val keyformBindingIndex = sections.intArray(Section.ARTMESH_KEYFORM_BINDING) + private val keyformBase = sections.intArray(Section.ARTMESH_KEYFORM_BASE) + private val parentDeformer = sections.intArray(Section.ARTMESH_PARENT_DEFORMER) + private val colorBase = + if (sections.isPresent(Section.ARTMESH_COLOR_BASE)) sections.intArray(Section.ARTMESH_COLOR_BASE) else null + + // MOC3 v6 §5.6 s153: per-drawable packed extended blend (0 = legacy constant-flags blend). + private val extendedBlend = + if (sections.isPresent(Section.ARTMESH_EXTENDED_BLEND)) sections.intArray(Section.ARTMESH_EXTENDED_BLEND) else null + + // s37 is the visibility toggle (pinned by joining miku_verycursed against its CMO3 twin); s38 is + // 1 on every drawable of every corpus sample and is carried only so a bake reproduces it. + private val isVisible = sections.intArray(Section.ARTMESH_IS_VISIBLE) + private val isEnabled = sections.intArray(Section.ARTMESH_IS_ENABLED) + + private val uvData = sections.floatArray(Section.ARTMESH_UV_DATA) + private val indexData = sections.shortArray(Section.ARTMESH_INDEX_DATA) + + /** + * Where the drawables' mask entries begin: the offscreen entries are the block's PREFIX and + * the drawables' masks follow (pinned on Model A against the CMO3 ground truth + the runtime's + * s158 addressing, which offsets from the block start). Pre-v6 there is no prefix. + */ + private val offscreenMaskTotal = + if (sections.isPresent(Section.OFFSCREEN_MASK_COUNT)) { + sections.intArray(Section.OFFSCREEN_MASK_COUNT).sum() + } else { + 0 + } + + /** + * Decodes every drawable, walking the concatenated geometry tables in drawable order. + * + * @param List drawables The model's drawables, whose counts drive the cursors. + * @return List The decoded art meshes, in drawable order. + */ + fun decodeAll(drawables: List): List { + var vertexBase = 0 + var indexBase = 0 + var maskBase = offscreenMaskTotal + return drawables.mapIndexed { drawableIndex, drawable -> + val vertexCount = drawable.vertexCount + val uvs = uvData.copyOfRange(vertexBase * 2, vertexBase * 2 + vertexCount * 2) + val triangleIndices = indexData.copyOfRange(indexBase, indexBase + drawable.indexCount) + val maskIndices = maskData.copyOfRange(maskBase, maskBase + drawable.maskCount) + vertexBase += vertexCount + indexBase += drawable.indexCount + maskBase += drawable.maskCount + artMesh(drawableIndex, drawable, uvs, triangleIndices, maskIndices) + } + } + + /** + * Builds one art mesh from its already-sliced geometry plus its per-keyform values. + * + * @param Int drawableIndex The drawable's index (every per-drawable table's row). + * @param MocDrawable drawable The drawable header (id, texture, flags, counts). + * @param FloatArray uvs This drawable's slice of the UV table. + * @param ShortArray triangleIndices This drawable's slice of the index table. + * @param IntArray maskIndices This drawable's slice of the mask table. + * @return ArtMesh The decoded art mesh. + */ + private fun artMesh( + drawableIndex: Int, + drawable: MocDrawable, + uvs: FloatArray, + triangleIndices: ShortArray, + maskIndices: IntArray, + ): ArtMesh { + val keyformBinding = keyformBindingIndex[drawableIndex] + val base = keyformBase[drawableIndex] + val keyforms = + (0 until bindings.binding(keyformBinding).gridSize).map { gridIndex -> + val positionOffset = keyformValues.positionIndex[base + gridIndex] + ArtMeshKeyform( + keyformValues.positionValues.copyOfRange( + positionOffset, + positionOffset + drawable.vertexCount * 2, + ), + keyformValues.artMeshOpacity[base + gridIndex], + keyformValues.artMeshDrawOrder[base + gridIndex], + colorTables.multiplyForKeyform(colorBase?.get(drawableIndex), gridIndex), + colorTables.screenForKeyform(colorBase?.get(drawableIndex), gridIndex), + ) + } + return ArtMesh( + drawable.id, + drawable.textureIndex, + drawable.constantFlags, + extendedBlend?.get(drawableIndex) ?: 0, + // Default to visible: a stripped file omitting the flags means "nothing is hidden". + isVisible.getOrElse(drawableIndex) { 1 } != 0, + isEnabled.getOrElse(drawableIndex) { 1 } != 0, + drawable.parentPartIndex, + parentDeformer[drawableIndex], + uvs, + triangleIndices, + maskIndices, + keyformBinding, + keyforms, + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocBindingResolver.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocBindingResolver.kt new file mode 100644 index 0000000..f521cee --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocBindingResolver.kt @@ -0,0 +1,128 @@ +package org.umamo.format.moc3.decode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.MocSections +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.KeyformAxis +import org.umamo.format.moc3.model.KeyformBinding + +/** + * Resolves keyform-binding indices into [KeyformBinding]s, and accumulates every one it resolves. + * + * This is deliberately an accumulator, not merely a cache: the set it has resolved BECOMES + * [MocDocument.keyformBindings], so registering a binding is how it reaches the document. Callers + * therefore resolve through [binding] even when they only want the grid size, and the glue pass + * resolves bindings purely to register them. Call [collected] and [hasParameterUnionRegion] only + * after every object kind has been decoded, or the tail of the binding table goes missing. + */ +internal class MocBindingResolver(sections: MocSections) { + /** + * Owning parameter per binding slot, expanded from the per-parameter slot counts (MOC3 §5.6 + * section 57): the slot table is a flat concatenation, so the parameter is positional. + */ + private val owningParameter: IntArray + + private val keyOffset: IntArray = sections.intArray(Section.BINDING_KEY_OFFSET) + private val keyCount: IntArray = sections.intArray(Section.BINDING_KEY_COUNT) + private val keyformBindingSlot: IntArray = sections.intArray(Section.KEYFORM_BINDING_SLOT) + private val keyformBindingStart: IntArray = sections.intArray(Section.KEYFORM_BINDING_START) + private val keyformBindingCount: IntArray = sections.intArray(Section.KEYFORM_BINDING_COUNT) + private val resolved = HashMap() + + /** The shared key-position table (MOC3 §5.6 section 77); the blend path reads it too. */ + val keyPositions: FloatArray = sections.floatArray(Section.KEY_POSITIONS) + + init { + val bindingCountPerParameter = sections.intArray(Section.PARAMETER_BINDING_COUNT) + owningParameter = IntArray(bindingCountPerParameter.sum()) + var bindingSlot = 0 + for (parameterIndex in bindingCountPerParameter.indices) { + repeat(bindingCountPerParameter[parameterIndex]) { owningParameter[bindingSlot++] = parameterIndex } + } + } + + /** Every binding resolved so far, which is what the document carries. */ + val collected: Map get() = resolved.toMap() + + /** + * Resolves the keyform binding at [keyformBindingIndex] into its parameter axes, registering it. + * + * @param Int keyformBindingIndex A keyform-binding index referenced by an object. + * @return KeyformBinding The resolved binding (its controlling parameter axes + key positions). + */ + fun binding(keyformBindingIndex: Int): KeyformBinding = + resolved.getOrPut(keyformBindingIndex) { + val start = keyformBindingStart[keyformBindingIndex] + val axes = + (0 until keyformBindingCount[keyformBindingIndex]).map { axisIndex -> + val bindingSlot = keyformBindingSlot[start + axisIndex] + KeyformAxis( + owningParameter[bindingSlot], + keyPositions.copyOfRange( + keyOffset[bindingSlot], + keyOffset[bindingSlot] + keyCount[bindingSlot], + ), + ) + } + KeyformBinding(keyformBindingIndex, axes) + } + + /** + * The grid size of a binding, treating a part's 0 as "static" rather than as binding 0. + * + * @param Int keyformBindingIndex A part's keyform-binding index, where 0 means no binding. + * @return Int The keyform grid size, 1 when static. + */ + fun staticAwareGridSize(keyformBindingIndex: Int): Int = + if (keyformBindingIndex <= 0) { + 1 + } else { + binding(keyformBindingIndex).gridSize + } + + /** + * Registers every binding record the file stores, not only those objects reference. + * + * The file allocates CountInfo[12] records, and a mesh-less model carries a single EMPTY + * binding (0 axes) that only static parts point at - lazy by-reference registration would drop + * it and shrink the re-synthesized binding sections + CountInfo (probed on the + * ModelWithOffscreen family). MOC3 §5.1 CountInfo field 12. + * + * @param Int storedBindingCount The stored record count, CountInfo field 12. + */ + fun registerStoredBindings(storedBindingCount: Int) { + repeat(storedBindingCount) { bindingIndex -> + binding(bindingIndex) + } + } + + /** + * Total keys the deduplicated main-grid region of KEY_POSITIONS holds, over the bindings + * registered so far. This is where the optional trailing union region begins. + * + * @return Int The main-grid key total. + */ + private fun mainGridKeyTotal(): Int { + val keySetsByParameter = HashMap>>() + for (resolvedBinding in resolved.values) { + for (axis in resolvedBinding.axes) { + keySetsByParameter.getOrPut(axis.parameterIndex) { LinkedHashSet() }.add(axis.keyPositions.toList()) + } + } + return keySetsByParameter.values.sumOf { keySets -> keySets.sumOf { it.size } } + } + + /** + * Whether KEY_POSITIONS (77) trails its dedup region with the per-parameter sorted-union of the + * main-grid axis keys, an editor-version artifact on some blend-free v1/v3 files (MOC3 §5.6). + * + * Detected as any nonzero key beyond the dedup (main-grid) region; zero padding beyond the + * region reads as absent. Only meaningful on a blend-free file - a blend model carries the + * region unconditionally, which the blend lowering path handles. + * + * @param Boolean isBlendFree Whether the model decoded no blend shapes. + * @return Boolean Whether the trailing union region is present. + */ + fun hasParameterUnionRegion(isBlendFree: Boolean): Boolean = + isBlendFree && (mainGridKeyTotal() until keyPositions.size).any { keyIndex -> keyPositions[keyIndex] != 0f } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocBlendDecoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocBlendDecoder.kt new file mode 100644 index 0000000..ea8f836 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocBlendDecoder.kt @@ -0,0 +1,504 @@ +package org.umamo.format.moc3.decode + +import org.umamo.format.moc3.moc.MocSections +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.ArtMeshKeyform +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.BlendShapeLimit +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.format.moc3.model.Part +import org.umamo.format.moc3.model.Rgb +import org.umamo.format.moc3.model.RotationKeyform +import org.umamo.format.moc3.model.WarpKeyform + +/** + * The per-object payload sizes and row anchor a blend-shape record's delta rows need, over the + * shared [KeyformValueTables]. Bundled so [BlendShapeDecoder] can lift the per-key delta payloads + * without a dozen loose parameters. + */ +internal class BlendDeltaTables( + val keyformValues: KeyformValueTables, + val colorTables: ColorTables, + val warpControlPointCounts: IntArray, + val drawableVertexCounts: IntArray, + /** + * First color-table row of the blend delta region: the moc-6 offscreen keyform prefix plus + * every object's base keyform rows. Computed from CONTENT, not from the table length - the + * raw element region is 64-byte zero-padded, so length-based anchoring drifts by the pad. + */ + val colorDeltaRowStart: Int, +) + +/** + * The deduplicated blend-weight limit pool (MOC3 v4+ §5.6 sections 123/124 + 131-136). + * + * A record ranges into SUB_INDEX, whose entries name a shared pool of (parameter, keys, weights) + * curves; records commonly point at the same pool entry, so the pool is stored once and expanded + * per record here. Absent tables decode as no limits, like any absent section. + */ +internal class BlendLimitPool(sections: MocSections) { + private val recordSubstart = sections.intArray(Section.BLENDSHAPE_RECORD_SUBSTART) + private val recordCornerCount = sections.intArray(Section.BLENDSHAPE_RECORD_CORNER_COUNT) + private val hasSubTables = sections.isPresent(Section.BLENDSHAPE_SUB_INDEX) + private val subIndex = if (hasSubTables) sections.intArray(Section.BLENDSHAPE_SUB_INDEX) else IntArray(0) + private val subParameter = if (hasSubTables) sections.intArray(Section.BLENDSHAPE_SUB_PARAMETER) else IntArray(0) + private val subKeyOffset = if (hasSubTables) sections.intArray(Section.BLENDSHAPE_SUB_KEY_OFFSET) else IntArray(0) + private val subKeyCount = if (hasSubTables) sections.intArray(Section.BLENDSHAPE_SUB_KEY_COUNT) else IntArray(0) + private val subKeys = if (hasSubTables) sections.floatArray(Section.BLENDSHAPE_SUB_KEYS) else FloatArray(0) + private val subWeights = if (hasSubTables) sections.floatArray(Section.BLENDSHAPE_SUB_WEIGHT_VALUES) else FloatArray(0) + + /** + * Expands one record's sub-binding refs into its limit curves (empty when uncapped). + * + * @param Int recordIndex The record's index in the record tables. + * @return List The record's limits, pool entries expanded per record. + */ + fun limitsFor(recordIndex: Int): List { + if (!hasSubTables || recordIndex >= recordCornerCount.size) { + return emptyList() + } + val cornerCount = recordCornerCount[recordIndex] + if (cornerCount == 0) { + return emptyList() + } + val cornerStart = recordSubstart[recordIndex] + return (cornerStart until cornerStart + cornerCount).map { cornerIndex -> + val subBinding = subIndex[cornerIndex] + val keyOffset = subKeyOffset[subBinding] + val keyCount = subKeyCount[subBinding] + BlendShapeLimit( + parameterIndex = subParameter[subBinding], + keyPositions = subKeys.copyOfRange(keyOffset, keyOffset + keyCount), + weights = subWeights.copyOfRange(keyOffset, keyOffset + keyCount), + ) + } + } +} + +/** + * Per-record addressing into the color tables' blend-delta region (MOC3 §5.6 sections 108-113). + * + * The delta region follows the base rows (and, on MOC3 v6, the offscreen keyform prefix), holding + * one row per (record, key) for warp, mesh, and rotation records in global record order - part + * records own no color rows. It anchors at the content-derived base-row total + * ([BlendDeltaTables.colorDeltaRowStart]); anchoring at table length minus the delta total drifts + * by the element region's 64-byte zero padding (2 rows on Model A, 10 on Model C - caught by + * their authored color morphs). + * + * The region is also a later format addition, so presence is probed rather than assumed: a + * 4.2-era bake with blend shapes carries the base rows only (corpus: Azxiana.moc3, V42 - CountInfo + * 23/24 there count base + prefix rows while fields 7-9 still include the deltas). When the + * tables do not cover the read extent, every record resolves to the absent sentinel and the deltas + * decode as null colors. + */ +internal class BlendColorDeltas( + sections: MocSections, + recordCount: Int, + recordBinding: IntArray, + bindingKeyCount: IntArray, + deltaTables: BlendDeltaTables, +) { + private val colorTables: ColorTables = deltaTables.colorTables + + /** Each record's first delta row, or -1 when it owns none (part-owned, or the region absent). */ + private val recordColorRow: IntArray + + init { + val partOwnedRecord = partOwnedRecords(sections, recordCount) + val colorReadRecord = colorReadRecords(sections, recordCount) + // Measure the read extent over exactly the rows that will be dereferenced: the record + // tables carry a few TRAILING records referenced by no group on every blend corpus model, + // and the stored region ends at the referenced records' rows (modelA: table 1808 = read + // extent 1806 + 2 rows padding; modelC: 2208 = 2198 + 10). + var requiredRowEnd = deltaTables.colorDeltaRowStart + var rowProbeCursor = deltaTables.colorDeltaRowStart + for (recordIndex in 0 until recordCount) { + if (!partOwnedRecord[recordIndex]) { + val rowEnd = rowProbeCursor + bindingKeyCount[recordBinding[recordIndex]] + if (colorReadRecord[recordIndex] && rowEnd > requiredRowEnd) { + requiredRowEnd = rowEnd + } + rowProbeCursor = rowEnd + } + } + val rows = IntArray(recordCount) { -1 } + if (colorTables.isPresent && requiredRowEnd <= colorTables.rowCount) { + var colorRowCursor = deltaTables.colorDeltaRowStart + for (recordIndex in 0 until recordCount) { + if (!partOwnedRecord[recordIndex]) { + rows[recordIndex] = colorRowCursor + colorRowCursor += bindingKeyCount[recordBinding[recordIndex]] + } + } + } + recordColorRow = rows + } + + /** + * Marks the records owned by a part object group, which carry no color rows. + * + * @param MocSections sections The model's typed sections. + * @param Int recordCount Total blend-shape records. + * @return BooleanArray One flag per record. + */ + private fun partOwnedRecords(sections: MocSections, recordCount: Int): BooleanArray { + val owned = BooleanArray(recordCount) + if (!sections.isPresent(Section.BLENDSHAPE_PART_OBJECT)) { + return owned + } + val partRecordStarts = sections.intArray(Section.BLENDSHAPE_PART_RECORD_START) + val partRecordCounts = sections.intArray(Section.BLENDSHAPE_PART_RECORD_COUNT) + for (groupIndex in partRecordStarts.indices) { + val partRecordEnd = partRecordStarts[groupIndex] + partRecordCounts[groupIndex] + for (recordIndex in partRecordStarts[groupIndex] until partRecordEnd) { + owned[recordIndex] = true + } + } + return owned + } + + /** + * Marks the records a warp, mesh, or rotation object group references - the only ones whose + * color rows are ever dereferenced. + * + * @param MocSections sections The model's typed sections. + * @param Int recordCount Total blend-shape records. + * @return BooleanArray One flag per record. + */ + private fun colorReadRecords(sections: MocSections, recordCount: Int): BooleanArray { + val referenced = BooleanArray(recordCount) + val groups = + listOf( + Triple( + Section.BLENDSHAPE_WARP_OBJECT, + Section.BLENDSHAPE_WARP_RECORD_START, + Section.BLENDSHAPE_WARP_RECORD_COUNT, + ), + Triple( + Section.BLENDSHAPE_MESH_OBJECT, + Section.BLENDSHAPE_MESH_RECORD_START, + Section.BLENDSHAPE_MESH_RECORD_COUNT, + ), + Triple( + Section.BLENDSHAPE_ROTATION_OBJECT, + Section.BLENDSHAPE_ROTATION_RECORD_START, + Section.BLENDSHAPE_ROTATION_RECORD_COUNT, + ), + ) + for ((objectSection, startSection, countSection) in groups) { + if (!sections.isPresent(objectSection)) { + continue + } + val recordStarts = sections.intArray(startSection) + val recordCounts = sections.intArray(countSection) + for (groupIndex in recordStarts.indices) { + for (recordIndex in recordStarts[groupIndex] until recordStarts[groupIndex] + recordCounts[groupIndex]) { + if (recordIndex in 0 until recordCount) { + referenced[recordIndex] = true + } + } + } + } + return referenced + } + + /** + * Multiply-color delta at key [keyIndex] of record [recordIndex]. + * + * @param Int recordIndex The record's index in the record tables. + * @param Int keyIndex The key's index within the record's binding. + * @return Rgb? The multiply-color delta row, or null when the record owns no color rows. + */ + fun multiplyDelta(recordIndex: Int, keyIndex: Int): Rgb? { + val colorRow = recordColorRow[recordIndex] + // Guarded here rather than folded into the row accessor: a negative row is the "no delta + // rows" sentinel, and offsetting it by keyIndex would land on a real row. + return if (colorRow < 0) { + null + } else { + colorTables.multiplyAtRow(colorRow + keyIndex) + } + } + + /** + * Screen-color delta at key [keyIndex] of record [recordIndex]. + * + * @param Int recordIndex The record's index in the record tables. + * @param Int keyIndex The key's index within the record's binding. + * @return Rgb? The screen-color delta row, or null when the record owns no color rows. + */ + fun screenDelta(recordIndex: Int, keyIndex: Int): Rgb? { + val colorRow = recordColorRow[recordIndex] + // Same sentinel guard as multiplyDelta above. + return if (colorRow < 0) { + null + } else { + colorTables.screenAtRow(colorRow + keyIndex) + } + } +} + +/** + * Decodes the blend-shape records: the binding structure, each record's blend-weight limits, and + * the typed per-key delta payloads. + * + * The records live in one flat table addressed by per-kind object groups (MOC3 v4+ §5.6 for + * meshes/warps, v5+ for rotations and parts). A group names its objects by KIND-LOCAL index, + * which is what sizes a delta payload, while the emitted [BlendShape] carries the deformer or + * drawable index instead - hence both travel together through the decode. + */ +internal class BlendShapeDecoder( + private val sections: MocSections, + parameterCount: Int, + private val keyPositions: FloatArray, + private val deltaTables: BlendDeltaTables, +) { + private val bindingKeyOffset = sections.intArray(Section.BLENDSHAPE_BINDING_KEY_OFFSET) + private val bindingKeyCount = sections.intArray(Section.BLENDSHAPE_BINDING_KEY_COUNT) + private val bindingNeutral = sections.intArray(Section.BLENDSHAPE_BINDING_NEUTRAL) + private val recordBinding = sections.intArray(Section.BLENDSHAPE_RECORD_BINDING) + private val recordBase = sections.intArray(Section.BLENDSHAPE_RECORD_BASE) + private val bindingOwner = resolveBindingOwners(sections, parameterCount) + private val limitPool = BlendLimitPool(sections) + private val colorDeltas = + BlendColorDeltas(sections, recordBinding.size, recordBinding, bindingKeyCount, deltaTables) + + /** The shared value tables the delta rows live in; aliased to keep the payload reads legible. */ + private val keyformValues = deltaTables.keyformValues + + /** + * Resolves the owning parameter of every blend-shape binding. + * + * Unlike the main keyform bindings, whose slot table is a flat concatenation, these carry + * explicit begin/count ranges per parameter (MOC3 §5.6). + * + * @param MocSections sections The model's typed sections. + * @param Int parameterCount Number of parameters. + * @return IntArray The owning parameter index per binding. + */ + private fun resolveBindingOwners(sections: MocSections, parameterCount: Int): IntArray { + val parameterBegin = sections.intArray(Section.BLENDSHAPE_PARAMETER_BEGIN) + val parameterBindingCount = sections.intArray(Section.BLENDSHAPE_PARAMETER_COUNT) + val owners = IntArray((0 until parameterCount).sumOf { parameterBindingCount[it] }) + for (parameterIndex in 0 until parameterCount) { + for (bindingIndex in 0 until parameterBindingCount[parameterIndex]) { + owners[parameterBegin[parameterIndex] + bindingIndex] = parameterIndex + } + } + return owners + } + + /** + * Decodes every object group's records, in warp, mesh, rotation, then part order. + * + * @param List warpToDeformer Maps a warp local index to its deformer index. + * @param List rotationToDeformer Maps a rotation local index to its deformer index. + * @return List The decoded records. + */ + fun decodeAll(warpToDeformer: List, rotationToDeformer: List): List { + val blendShapes = ArrayList() + blendShapes += + groupRecords( + Section.BLENDSHAPE_WARP_OBJECT, + Section.BLENDSHAPE_WARP_RECORD_START, + Section.BLENDSHAPE_WARP_RECORD_COUNT, + BlendShapeTarget.WARP, + warpToDeformer, + ) + blendShapes += + groupRecords( + Section.BLENDSHAPE_MESH_OBJECT, + Section.BLENDSHAPE_MESH_RECORD_START, + Section.BLENDSHAPE_MESH_RECORD_COUNT, + BlendShapeTarget.ART_MESH, + null, + ) + blendShapes += + groupRecords( + Section.BLENDSHAPE_ROTATION_OBJECT, + Section.BLENDSHAPE_ROTATION_RECORD_START, + Section.BLENDSHAPE_ROTATION_RECORD_COUNT, + BlendShapeTarget.ROTATION, + rotationToDeformer, + ) + // MOC3 v5+ §5.6 sections 143-145: part blend shapes (the object index is a part index). + blendShapes += + groupRecords( + Section.BLENDSHAPE_PART_OBJECT, + Section.BLENDSHAPE_PART_RECORD_START, + Section.BLENDSHAPE_PART_RECORD_COUNT, + BlendShapeTarget.PART, + null, + ) + return blendShapes + } + + /** + * Decodes the records of one target kind's object group. + * + * @param Section objectSection The per-object index section for this group. + * @param Section startSection The per-object record-start section. + * @param Section countSection The per-object record-count section. + * @param BlendShapeTarget target The target kind these records deform. + * @param List? toDeformer Local-index to deformer-index map, or null when the + * object index already names the target directly. + * @return List This group's records (empty when the section is absent). + */ + private fun groupRecords( + objectSection: Section, + startSection: Section, + countSection: Section, + target: BlendShapeTarget, + toDeformer: List?, + ): List { + if (!sections.isPresent(objectSection)) { + return emptyList() + } + val objectIndices = sections.intArray(objectSection) + val recordStarts = sections.intArray(startSection) + val recordCounts = sections.intArray(countSection) + val groupShapes = ArrayList() + for (groupIndex in objectIndices.indices) { + val localObjectIndex = objectIndices[groupIndex] + val objectIndex = toDeformer?.getOrElse(localObjectIndex) { localObjectIndex } ?: localObjectIndex + val recordStart = recordStarts[groupIndex] + for (recordIndex in recordStart until recordStart + recordCounts[groupIndex]) { + groupShapes.add(blendShape(target, localObjectIndex, objectIndex, recordIndex)) + } + } + return groupShapes + } + + /** + * Builds one record's [BlendShape], resolving its binding and lifting its delta payloads. + * + * @param BlendShapeTarget target Which kind of object this record deforms. + * @param Int localObjectIndex The target's kind-local index (sizes the payloads). + * @param Int objectIndex The deformer/drawable/part index the record targets. + * @param Int recordIndex The record's index in the record tables. + * @return BlendShape The decoded record. + */ + private fun blendShape( + target: BlendShapeTarget, + localObjectIndex: Int, + objectIndex: Int, + recordIndex: Int, + ): BlendShape { + val bindingIndex = recordBinding[recordIndex] + val keys = + keyPositions.copyOfRange( + bindingKeyOffset[bindingIndex], + bindingKeyOffset[bindingIndex] + bindingKeyCount[bindingIndex], + ) + return BlendShape( + target, + objectIndex, + bindingOwner[bindingIndex], + keys, + bindingNeutral[bindingIndex], + recordBase[recordIndex], + limitPool.limitsFor(recordIndex), + keyformsFor(target, localObjectIndex, recordIndex, bindingKeyCount[bindingIndex]), + ) + } + + /** + * Lifts one record's per-key delta payloads out of the shared value tables, at rows + * `recordBase + keyIndex` (MOC3 §5.6; the same tables the base keyforms use). + * + * @param BlendShapeTarget target The record's target kind. + * @param Int localObjectIndex The target's kind-local index (warp/rotation local, + * drawable, or part index) - sizes the payload. + * @param Int recordIndex The record's index in the record tables. + * @param Int keyCount The record's binding key count. + * @return List One delta payload per key, kind matching [target]. + */ + private fun keyformsFor( + target: BlendShapeTarget, + localObjectIndex: Int, + recordIndex: Int, + keyCount: Int, + ): List = + (0 until keyCount).map { keyIndex -> + val deltaRow = recordBase[recordIndex] + keyIndex + when (target) { + BlendShapeTarget.WARP -> warpDelta(localObjectIndex, recordIndex, keyIndex, deltaRow) + BlendShapeTarget.ART_MESH -> meshDelta(localObjectIndex, recordIndex, keyIndex, deltaRow) + BlendShapeTarget.ROTATION -> rotationDelta(recordIndex, keyIndex, deltaRow) + // MOC3 §5.6: part delta rows are draw-order floats in section 58. + BlendShapeTarget.PART -> BlendShapeKeyform.Part(keyformValues.partDrawOrder[deltaRow]) + } + } + + /** + * One warp control-point delta payload. + * + * @param Int localObjectIndex The warp's local index, which sizes the lattice. + * @param Int recordIndex The record's index in the record tables. + * @param Int keyIndex The key's index within the record's binding. + * @param Int deltaRow The record's row for this key. + * @return BlendShapeKeyform.Warp The delta payload. + */ + private fun warpDelta(localObjectIndex: Int, recordIndex: Int, keyIndex: Int, deltaRow: Int): BlendShapeKeyform.Warp { + // MOC3 §5.6: warp delta rows index packed position blocks via section 60 into 71. + val controlPointCount = deltaTables.warpControlPointCounts[localObjectIndex] + val positionOffset = keyformValues.warpPositionIndex[deltaRow] + return BlendShapeKeyform.Warp( + WarpKeyform( + keyformValues.positionValues.copyOfRange(positionOffset, positionOffset + controlPointCount * 2), + keyformValues.warpOpacity[deltaRow], + colorDeltas.multiplyDelta(recordIndex, keyIndex), + colorDeltas.screenDelta(recordIndex, keyIndex), + ), + ) + } + + /** + * One art-mesh vertex delta payload. + * + * @param Int localObjectIndex The drawable index, which sizes the vertex block. + * @param Int recordIndex The record's index in the record tables. + * @param Int keyIndex The key's index within the record's binding. + * @param Int deltaRow The record's row for this key. + * @return BlendShapeKeyform.Mesh The delta payload. + */ + private fun meshDelta(localObjectIndex: Int, recordIndex: Int, keyIndex: Int, deltaRow: Int): BlendShapeKeyform.Mesh { + // MOC3 §5.6: mesh delta rows index packed position blocks via section 70 into 71. + val vertexCount = deltaTables.drawableVertexCounts[localObjectIndex] + val positionOffset = keyformValues.positionIndex[deltaRow] + return BlendShapeKeyform.Mesh( + ArtMeshKeyform( + keyformValues.positionValues.copyOfRange(positionOffset, positionOffset + vertexCount * 2), + keyformValues.artMeshOpacity[deltaRow], + keyformValues.artMeshDrawOrder[deltaRow], + colorDeltas.multiplyDelta(recordIndex, keyIndex), + colorDeltas.screenDelta(recordIndex, keyIndex), + ), + ) + } + + /** + * One rotation affine delta payload. + * + * @param Int recordIndex The record's index in the record tables. + * @param Int keyIndex The key's index within the record's binding. + * @param Int deltaRow The record's row for this key. + * @return BlendShapeKeyform.Rotation The delta payload. + */ + private fun rotationDelta(recordIndex: Int, keyIndex: Int, deltaRow: Int): BlendShapeKeyform.Rotation = + // MOC3 §5.6: rotation delta rows sit directly in the affine tables 61-67. + BlendShapeKeyform.Rotation( + RotationKeyform( + keyformValues.rotationOriginX[deltaRow], + keyformValues.rotationOriginY[deltaRow], + keyformValues.rotationAngle[deltaRow], + keyformValues.rotationScale[deltaRow], + keyformValues.rotationReflectX[deltaRow] != 0, + keyformValues.rotationReflectY[deltaRow] != 0, + keyformValues.rotationOpacity[deltaRow], + colorDeltas.multiplyDelta(recordIndex, keyIndex), + colorDeltas.screenDelta(recordIndex, keyIndex), + ), + ) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDecodeTables.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDecodeTables.kt new file mode 100644 index 0000000..fefb542 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDecodeTables.kt @@ -0,0 +1,143 @@ +package org.umamo.format.moc3.decode + +import org.umamo.format.moc3.moc.MocSections +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.Rgb + +/** + * The shared per-keyform color tables (MOC3 §5.6 sections 108-113) and their row addressing. + * + * Every consumer reaches the same six tables by a different route - a base keyform as + * `colorBase + gridIndex`, an offscreen as one of the block's prefix rows, a blend-shape delta as + * a delta row - so the addressing is expressed once as [multiplyAtRow] / [screenAtRow] and the + * keyform form layers on top. An absent color section yields a null color from every accessor, + * which is what keeps the presence check off the call sites. + */ +internal class ColorTables(sections: MocSections) { + /** Whether the model carries color tables at all; absent on a model with no color animation. */ + val isPresent: Boolean = sections.isPresent(Section.COLOR_MULTIPLY_R) + + private val multiplyR: FloatArray = sections.floatArray(Section.COLOR_MULTIPLY_R) + private val multiplyG: FloatArray = sections.floatArray(Section.COLOR_MULTIPLY_G) + private val multiplyB: FloatArray = sections.floatArray(Section.COLOR_MULTIPLY_B) + private val screenR: FloatArray = sections.floatArray(Section.COLOR_SCREEN_R) + private val screenG: FloatArray = sections.floatArray(Section.COLOR_SCREEN_G) + private val screenB: FloatArray = sections.floatArray(Section.COLOR_SCREEN_B) + + /** + * Rows the tables hold, which the blend path probes against to decide whether the delta region + * was baked at all (a 4.2-era bake carries the base rows only). + */ + val rowCount: Int get() = multiplyR.size + + /** + * Multiply-color at absolute table row [row]. + * + * @param Int row The absolute row index; negative means "this object has no color row". + * @return Rgb? The multiply color, or null when the tables are absent or [row] is negative. + */ + fun multiplyAtRow(row: Int): Rgb? = + if (isPresent && row >= 0) { + Rgb(multiplyR[row], multiplyG[row], multiplyB[row]) + } else { + null + } + + /** + * Screen-color at absolute table row [row]. + * + * @param Int row The absolute row index; negative means "this object has no color row". + * @return Rgb? The screen color, or null when the tables are absent or [row] is negative. + */ + fun screenAtRow(row: Int): Rgb? = + if (isPresent && row >= 0) { + Rgb(screenR[row], screenG[row], screenB[row]) + } else { + null + } + + /** + * Multiply-color at keyform [gridIndex] of an object whose color table starts at [colorBase]. + * + * @param Int? colorBase The object's base row (null or -1 when the object is uncolored). + * @param Int gridIndex The keyform's grid index. + * @return Rgb? The multiply color, or null when color is absent. + */ + fun multiplyForKeyform(colorBase: Int?, gridIndex: Int): Rgb? = multiplyAtRow(keyformRow(colorBase, gridIndex)) + + /** + * Screen-color at keyform [gridIndex] of an object whose color table starts at [colorBase]. + * + * @param Int? colorBase The object's base row (null or -1 when the object is uncolored). + * @param Int gridIndex The keyform's grid index. + * @return Rgb? The screen color, or null when color is absent. + */ + fun screenForKeyform(colorBase: Int?, gridIndex: Int): Rgb? = screenAtRow(keyformRow(colorBase, gridIndex)) + + /** + * Resolves an object's keyform row, collapsing "uncolored" to the negative sentinel the + * row accessors already treat as absent. + * + * @param Int? colorBase The object's base row (null or -1 when the object is uncolored). + * @param Int gridIndex The keyform's grid index. + * @return Int The absolute row, or -1 when the object carries no color. + */ + private fun keyformRow(colorBase: Int?, gridIndex: Int): Int = + if (colorBase == null || colorBase < 0) { + -1 + } else { + colorBase + gridIndex + } +} + +/** + * The per-keyform value tables shared by the base keyforms and the blend-shape delta rows. + * + * MOC3 §5.6 appends a record's delta rows AFTER the base rows of these same tables, so a base + * keyform and a delta differ only in which row they address. That is why they are read once here + * and handed to both paths. Per-type structural tables (a warp's rows/columns, a drawable's UVs, + * any id or flag column) are NOT shared and stay with their own decoder. + */ +internal class KeyformValueTables(sections: MocSections) { + /** Art-mesh keyform -> packed-position offset (§5.6 section 70, indexing into 71). */ + val positionIndex: IntArray = sections.intArray(Section.KEYFORM_POSITION_INDEX) + + /** Warp keyform -> packed-position offset; a table distinct from [positionIndex] (section 60). */ + val warpPositionIndex: IntArray = sections.intArray(Section.WARP_KEYFORM_INDEX) + + /** The packed position blocks both index tables point into (section 71). */ + val positionValues: FloatArray = sections.floatArray(Section.KEYFORM_POSITION_VALUES) + + /** Part draw-order rows (section 58). */ + val partDrawOrder: FloatArray = sections.floatArray(Section.PART_DRAW_ORDER) + + /** Warp opacity rows (section 59). */ + val warpOpacity: FloatArray = sections.floatArray(Section.WARP_OPACITY) + + /** Art-mesh opacity rows (section 68). */ + val artMeshOpacity: FloatArray = sections.floatArray(Section.ARTMESH_OPACITY) + + /** Art-mesh draw-order rows (section 69). */ + val artMeshDrawOrder: FloatArray = sections.floatArray(Section.ARTMESH_DRAW_ORDER) + + /** Rotation opacity rows (section 61); a rotation delta indexes the affine tables directly. */ + val rotationOpacity: FloatArray = sections.floatArray(Section.ROTATION_OPACITY) + + /** Rotation angle rows (section 62). */ + val rotationAngle: FloatArray = sections.floatArray(Section.ROTATION_ANGLE) + + /** Rotation pivot X rows (section 63). */ + val rotationOriginX: FloatArray = sections.floatArray(Section.ROTATION_ORIGIN_X) + + /** Rotation pivot Y rows (section 64). */ + val rotationOriginY: FloatArray = sections.floatArray(Section.ROTATION_ORIGIN_Y) + + /** Rotation scale rows (section 65). */ + val rotationScale: FloatArray = sections.floatArray(Section.ROTATION_SCALE) + + /** Rotation X-reflection flags (section 66). */ + val rotationReflectX: IntArray = sections.intArray(Section.ROTATION_REFLECT_X) + + /** Rotation Y-reflection flags (section 67). */ + val rotationReflectY: IntArray = sections.intArray(Section.ROTATION_REFLECT_Y) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDecoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDecoder.kt new file mode 100644 index 0000000..735b0b0 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDecoder.kt @@ -0,0 +1,314 @@ +package org.umamo.format.moc3.decode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.MocModel +import org.umamo.format.moc3.moc.MocSections +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.Glue +import org.umamo.format.moc3.model.GlueVertexPair +import org.umamo.format.moc3.model.Offscreen +import org.umamo.format.moc3.model.OffscreenKeyform +import org.umamo.format.moc3.model.Part +import org.umamo.format.moc3.model.RenderOrderChild +import org.umamo.format.moc3.model.RenderOrderGroup +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer + +/** + * Resolves a parsed [MocModel] into the semantic [MocDocument]: the keyform-binding grid and each + * object's per-keyform values (vertex positions, opacity, draw-order, color, deformer transforms). + * + * Reads the typed Layer-1 sections and follows the base/index tables - it does not evaluate the + * model (no interpolation/cascade). Blend shapes (MOC3 v4+) and offscreens (MOC3 v6) are assembled + * too. Every section index is modeled in [Section], so nothing is left to raw access. + * + * @see MOC3.md §5.6 + */ +public object MocDecoder { + /** + * Decodes [model] into a [MocDocument]. + * + * @param MocModel model A parsed `.moc3` container. + * @return MocDocument The semantic model. + */ + public fun decode(model: MocModel): MocDocument { + val sections = model.sections + val deformerCount = model.deformerCount + val drawables = model.drawables() + + val bindings = MocBindingResolver(sections) + bindings.registerStoredBindings(model.countInfo.getOrElse(Sections.CI_KEYFORM_BINDINGS) { 0 }) + + // ---- value tables ---- + val colorTables = ColorTables(sections) + val keyformValues = KeyformValueTables(sections) + + // PARTS + val partKeyformBinding = sections.intArray(Section.PART_KEYFORM_BINDING) + val partKeyformBase = sections.intArray(Section.PART_KEYFORM_BASE) + // s7/s8 are a pair whose split is unpinned (both are 1 corpus-wide); take s7 and default to + // visible when a stripped file omits it. + val partVisible = sections.intArray(Section.PART_VISIBLE_ARTMESHES) + val partList = + model.parts().mapIndexed { partIndex, part -> + val keyformBinding = partKeyformBinding[partIndex] // for parts, 0 means static (no binding) + val gridSize = bindings.staticAwareGridSize(keyformBinding) + Part( + part.id, + part.parentPartIndex, + keyformBinding, + FloatArray(gridSize) { keyIndex -> keyformValues.partDrawOrder[partKeyformBase[partIndex] + keyIndex] }, + isVisible = partVisible.getOrElse(partIndex) { 1 } != 0, + ) + } + + // DEFORMERS + val decodedDeformers = DeformerDecoder(sections, bindings, colorTables, keyformValues).decodeAll(deformerCount) + val deformerList = decodedDeformers.deformers + + // ART MESHES + // MASK_INDEX_DATA is shared: the offscreen entries are its prefix and the drawables' masks + // follow, so both decoders read the one table (MOC3 v6 §5.6 section 80). + val maskData = sections.intArray(Section.MASK_INDEX_DATA) + val artMeshList = MocArtMeshDecoder(sections, bindings, colorTables, keyformValues, maskData).decodeAll(drawables) + + // GLUES + val glueList = decodeGlues(sections) + // Register glue bindings in the cache like every other object kind: a glue names a binding + // from the same shared table (MOC3.md §5.6), and without this a glue-exclusive binding would + // be missing from MocDocument.keyformBinding (dropping the glue's parameter-driven intensity + // downstream) AND from MocDocument.bindings (dropping its table rows from a re-bake). + for (glue in glueList) { + bindings.binding(glue.keyformBindingIndex) + } + + // RENDER-ORDER GROUPS + val groupList = + decodeRenderOrderGroups(sections, model.countInfo.getOrElse(Sections.CI_RENDER_ORDER_GROUPS) { 0 }) + + // BLEND SHAPES (MOC3 v4+) + // MOC3 §5.6: blend delta rows share the base keyforms' value tables (appended after the + // base rows at each record's RECORD_BASE), so the extraction needs the same tables plus + // each target object's payload size (warp control-point count, drawable vertex count). + val blendDeltaTables = + BlendDeltaTables( + keyformValues = keyformValues, + colorTables = colorTables, + warpControlPointCounts = decodedDeformers.warpControlPointCounts, + drawableVertexCounts = IntArray(drawables.size) { drawableIndex -> drawables[drawableIndex].vertexCount }, + colorDeltaRowStart = + model.countInfo.getOrElse(Sections.CI_OFFSCREEN_KEYFORMS) { 0 } + + deformerList.sumOf { deformer -> + when (deformer) { + is WarpDeformer -> deformer.keyforms.size + is RotationDeformer -> deformer.keyforms.size + } + } + + artMeshList.sumOf { it.keyforms.size }, + ) + val blendShapeList = + decodeBlendShapes( + sections, + model.parameterCount, + bindings.keyPositions, + decodedDeformers.warpToDeformer, + decodedDeformers.rotationToDeformer, + blendDeltaTables, + ) + + // OFFSCREENS (MOC3 v6) + // The offscreen mask entries are the PREFIX of MASK_INDEX_DATA, addressed per offscreen by + // s158 (the cumulative scan of s159, offset from the block start - MOC3 §5.6 section 80). + val offscreenList = + decodeOffscreens( + sections, + model.countInfo.getOrElse(Sections.CI_OFFSCREENS) { 0 }, + partList, + colorTables, + maskData, + ) + + // Probed last, and deliberately so: it measures the trailing region against the bindings + // registered by every object kind above, the glue pass included. + val keyPositionsHasParameterUnion = bindings.hasParameterUnionRegion(blendShapeList.isEmpty()) + + return MocDocument( + version = model.version, + canvas = model.canvasInfo, + parameters = model.parameters(), + keyformBindings = bindings.collected, + parts = partList, + deformers = deformerList, + artMeshes = artMeshList, + glues = glueList, + renderOrderGroups = groupList, + blendShapes = blendShapeList, + offscreens = offscreenList, + keyPositionsHasParameterUnion = keyPositionsHasParameterUnion, + ) + } + + /** + * Decodes the blend-shape records (MOC3 v4+ for meshes/warps, MOC3 v5+ for rotations and parts). + * + * @param MocSections sections The model's typed sections. + * @param Int parameterCount Number of parameters (sizes the per-parameter binding ranges). + * @param FloatArray keyPositions The shared key-position table. + * @param List warpToDeformer Maps a warp local index to its deformer index. + * @param List rotationToDeformer Maps a rotation local index to its deformer index. + * @param BlendDeltaTables deltaTables The shared value tables the delta rows live in. + * @return List The decoded blend-shape records (empty when absent). + */ + private fun decodeBlendShapes( + sections: MocSections, + parameterCount: Int, + keyPositions: FloatArray, + warpToDeformer: List, + rotationToDeformer: List, + deltaTables: BlendDeltaTables, + ): List { + if (!sections.isPresent(Section.BLENDSHAPE_PARAMETER_BEGIN)) { + return emptyList() + } + return BlendShapeDecoder(sections, parameterCount, keyPositions, deltaTables) + .decodeAll(warpToDeformer, rotationToDeformer) + } + + /** + * Decodes the offscreen render targets (moc 6), including their per-keyform opacity/color and + * mask indices. An offscreen's keyforms ride its owner part's keyform grid (no offscreen + * keyform-binding section exists; MOC3 §5.6, OffscreenKeyformProbeTest): opacity rows in + * section 161 and the color tables' PREFIX rows are laid out per offscreen in offscreen order. + * + * @param MocSections sections The model's typed sections. + * @param Int count Number of offscreens from CountInfo. + * @param List parts The decoded parts (their grids size the keyform runs). + * @param ColorTables colorTables The shared color tables (§5.6 sections 108-113); an offscreen's + * rows are the block's prefix, so they address it by row directly. + * @param IntArray maskData The full MASK_INDEX_DATA table (§5.6 section 80). + * @return List The decoded offscreens (empty when absent). + */ + private fun decodeOffscreens( + sections: MocSections, + count: Int, + parts: List, + colorTables: ColorTables, + maskData: IntArray, + ): List { + if (count == 0 || !sections.isPresent(Section.OFFSCREEN_OWNER_PART)) { + return emptyList() + } + val owner = sections.intArray(Section.OFFSCREEN_OWNER_PART) + val flags = sections.byteArray(Section.OFFSCREEN_CONSTANT_FLAGS) + val blendModes = sections.intArray(Section.OFFSCREEN_BLEND_MODE) // one packed value per offscreen + val maskCounts = sections.intArray(Section.OFFSCREEN_MASK_COUNT) + val maskBases = sections.intArray(Section.OFFSCREEN_MASK_BASE) + val opacity = sections.floatArray(Section.OFFSCREEN_OPACITY) + var keyformRowCursor = 0 + return (0 until count).map { offscreenIndex -> + val keyformCount = parts[owner[offscreenIndex]].drawOrderKeyforms.size + val keyforms = + (0 until keyformCount).map { keyIndex -> + val keyformRow = keyformRowCursor + keyIndex + OffscreenKeyform( + opacity[keyformRow], + colorTables.multiplyAtRow(keyformRow), + colorTables.screenAtRow(keyformRow), + ) + } + keyformRowCursor += keyformCount + // MOC3 v6 §5.6 s158: the offscreen's masks sit at the s158 offset from the BLOCK START - + // the offscreen entries are the block's prefix, before the drawables' masks (pinned on + // Model A: pupil offscreens clip the Whites masks, matching the CMO3 clipGuidList). + val maskIndices = maskData.copyOfRange(maskBases[offscreenIndex], maskBases[offscreenIndex] + maskCounts[offscreenIndex]) + Offscreen( + owner[offscreenIndex], + flags[offscreenIndex].toInt() and 0xFF, + blendModes[offscreenIndex], + maskCounts[offscreenIndex], + keyforms, + maskIndices, + ) + } + } + + /** + * Decodes the glues (seam-welds between art meshes). + * + * @param MocSections sections The model's typed sections. + * @return List The decoded glues (empty when absent). + */ + private fun decodeGlues(sections: MocSections): List { + val meshA = sections.intArray(Section.GLUE_MESH_A) + if (meshA.isEmpty()) { + return emptyList() + } + val meshB = sections.intArray(Section.GLUE_MESH_B) + val glueId = sections.idArray(Section.GLUE_ID) + val keyformBinding = sections.intArray(Section.GLUE_KEYFORM_BINDING) + val glueVertexStart = sections.intArray(Section.GLUE_VERTEX_START) + val glueVertexCount = sections.intArray(Section.GLUE_VERTEX_COUNT) + val keyOffset = sections.intArray(Section.GLUE_KEY_OFFSET) + val keyCount = sections.intArray(Section.GLUE_KEY_COUNT) + val weights = sections.floatArray(Section.GLUE_WEIGHTS) + val indices = sections.shortArray(Section.GLUE_VERTEX_INDICES) + val intensities = sections.floatArray(Section.GLUE_INTENSITIES) + return (meshA.indices).map { glueIndex -> + val vertexStartIndex = glueVertexStart[glueIndex] + val pairCount = glueVertexCount[glueIndex] / 2 + val pairs = + (0 until pairCount).map { pairIndex -> + GlueVertexPair( + indices[vertexStartIndex + 2 * pairIndex].toInt() and 0xFFFF, + indices[vertexStartIndex + 2 * pairIndex + 1].toInt() and 0xFFFF, + weights[vertexStartIndex + 2 * pairIndex], + weights[vertexStartIndex + 2 * pairIndex + 1], + ) + } + Glue( + // A stripped file without s90 leaves the id blank rather than failing the decode. + glueId.getOrElse(glueIndex) { "" }, + meshA[glueIndex], + meshB[glueIndex], + keyformBinding[glueIndex], + pairs, + intensities.copyOfRange(keyOffset[glueIndex], keyOffset[glueIndex] + keyCount[glueIndex]), + ) + } + } + + /** + * Decodes the render-order group tree (the draw-order hierarchy). + * + * @param MocSections sections The model's typed sections. + * @param Int groupCount Number of render-order groups from CountInfo. + * @return List The decoded groups (empty when absent). + */ + private fun decodeRenderOrderGroups( + sections: MocSections, + groupCount: Int, + ): List { + if (groupCount == 0) { + return emptyList() + } + val childCount = sections.intArray(Section.RENDER_ORDER_CHILD_COUNT) + val childKind = sections.intArray(Section.RENDER_ORDER_CHILD_KIND) + val childIndex = sections.intArray(Section.RENDER_ORDER_CHILD_INDEX) + val childGroupIndex = sections.intArray(Section.RENDER_ORDER_GROUP_INDEX) + var childBase = 0 + return (0 until groupCount).map { groupIndex -> + val children = + (0 until childCount[groupIndex]).map { childOrdinal -> + RenderOrderChild( + childKind[childBase + childOrdinal], + childIndex[childBase + childOrdinal], + childGroupIndex[childBase + childOrdinal], + ) + } + childBase += childCount[groupIndex] + RenderOrderGroup(children) + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDeformerDecoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDeformerDecoder.kt new file mode 100644 index 0000000..6812941 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/decode/MocDeformerDecoder.kt @@ -0,0 +1,166 @@ +package org.umamo.format.moc3.decode + +import org.umamo.format.moc3.moc.MocSections +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.Deformer +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.RotationKeyform +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.format.moc3.model.WarpKeyform + +/** The decoded deformer block, plus the index maps and payload sizes the blend path needs. */ +internal class DecodedDeformers( + val deformers: List, + /** Warp local index -> deformer index; blend-shape warp records are stored against the local one. */ + val warpToDeformer: List, + /** Rotation local index -> deformer index, for the same reason. */ + val rotationToDeformer: List, + /** Control points per warp, which sizes both a base warp keyform and a warp delta payload. */ + val warpControlPointCounts: IntArray, +) + +/** + * Decodes the deformer block into typed [WarpDeformer]s and [RotationDeformer]s. + * + * Both kinds share one deformer index space and one common head (MOC3 §5.6 sections 11-15), but + * each kind's own tables are densely packed over only its own members. So the walk advances the + * shared index while carrying a separate local cursor per kind, and every per-type read is by that + * local index, never the deformer index. Those local indices are also how blend-shape records + * name their target, which is what [DecodedDeformers] carries the maps for. + */ +internal class DeformerDecoder( + sections: MocSections, + private val bindings: MocBindingResolver, + private val colorTables: ColorTables, + private val keyformValues: KeyformValueTables, +) { + private val deformerType = sections.intArray(Section.DEFORMER_TYPE) + private val deformerParent = sections.intArray(Section.DEFORMER_PARENT) + + // The block's common head (MOC3 §5.6 S11-S15). + private val deformerId = sections.idArray(Section.DEFORMER_ID) + + // Section 12 is the same binding that the warp/rotation sections 19/25 have. + // Warp and Rotation have their own keyform binding which duplicates the deformer binding. + // We don't necessarily need it, but we read and write it since there is a chance it might cause a MOC3 + // validation error in the runtime. + private val deformerKeyformBinding = sections.intArray(Section.DEFORMER_KEYFORM_BINDING) + private val deformerIsVisible = sections.intArray(Section.DEFORMER_IS_VISIBLE) + private val deformerIsEnabled = sections.intArray(Section.DEFORMER_IS_ENABLED) + private val deformerParentPart = sections.intArray(Section.DEFORMER_PARENT_PART) + + private val warpKeyformBinding = sections.intArray(Section.WARP_KEYFORM_BINDING) + private val warpKeyformBase = sections.intArray(Section.WARP_KEYFORM_BASE) + private val warpRows = sections.intArray(Section.WARP_ROWS) + private val warpColumns = sections.intArray(Section.WARP_COLUMNS) + private val warpMode = if (sections.isPresent(Section.WARP_MODE)) sections.intArray(Section.WARP_MODE) else null + private val warpColorBase = + if (sections.isPresent(Section.WARP_COLOR_BASE)) sections.intArray(Section.WARP_COLOR_BASE) else null + + private val rotationKeyformBinding = sections.intArray(Section.ROTATION_KEYFORM_BINDING) + private val rotationKeyformBase = sections.intArray(Section.ROTATION_KEYFORM_BASE) + private val rotationBaseAngle = sections.floatArray(Section.ROTATION_BASE_ANGLE) + private val rotationColorBase = + if (sections.isPresent(Section.ROTATION_COLOR_BASE)) sections.intArray(Section.ROTATION_COLOR_BASE) else null + + /** Control points per warp: an (rows + 1) x (columns + 1) lattice of them. */ + private val warpControlPointCounts = + IntArray(warpRows.size) { warpLocalIndex -> + (warpRows[warpLocalIndex] + 1) * (warpColumns[warpLocalIndex] + 1) + } + + /** + * Decodes every deformer, dispatching on the section 11 type column. + * + * @param Int deformerCount The model's deformer count. + * @return DecodedDeformers The deformers in index order, with the per-kind index maps. + */ + fun decodeAll(deformerCount: Int): DecodedDeformers { + var nextWarpLocal = 0 + var nextRotationLocal = 0 + val warpToDeformer = ArrayList() + val rotationToDeformer = ArrayList() + val deformers = ArrayList(deformerCount) + for (deformerIndex in 0 until deformerCount) { + if (deformerType[deformerIndex] == 0) { + warpToDeformer.add(deformerIndex) + deformers.add(warpDeformer(deformerIndex, nextWarpLocal++)) + } else { + rotationToDeformer.add(deformerIndex) + deformers.add(rotationDeformer(deformerIndex, nextRotationLocal++)) + } + } + return DecodedDeformers(deformers, warpToDeformer, rotationToDeformer, warpControlPointCounts) + } + + /** + * Builds one warp deformer and its FFD lattice keyforms. + * + * @param Int deformerIndex Its index in the shared deformer space (the common head's row). + * @param Int warpLocalIndex Its index among warps (every per-warp table's row). + * @return WarpDeformer The decoded deformer. + */ + private fun warpDeformer(deformerIndex: Int, warpLocalIndex: Int): WarpDeformer { + val keyformBinding = warpKeyformBinding[warpLocalIndex] + val keyformBase = warpKeyformBase[warpLocalIndex] + val controlPointCount = warpControlPointCounts[warpLocalIndex] + val keyforms = + (0 until bindings.binding(keyformBinding).gridSize).map { gridIndex -> + val positionOffset = keyformValues.warpPositionIndex[keyformBase + gridIndex] + WarpKeyform( + keyformValues.positionValues.copyOfRange(positionOffset, positionOffset + controlPointCount * 2), + keyformValues.warpOpacity[keyformBase + gridIndex], + colorTables.multiplyForKeyform(warpColorBase?.get(warpLocalIndex), gridIndex), + colorTables.screenForKeyform(warpColorBase?.get(warpLocalIndex), gridIndex), + ) + } + return WarpDeformer( + id = deformerId.getOrElse(deformerIndex) { "" }, + keyformBindingIndex = keyformBinding, + isVisible = deformerIsVisible.getOrElse(deformerIndex) { 1 } != 0, + isEnabled = deformerIsEnabled.getOrElse(deformerIndex) { 1 } != 0, + parentPartIndex = deformerParentPart.getOrElse(deformerIndex) { -1 }, + parentDeformerIndex = deformerParent[deformerIndex], + rows = warpRows[warpLocalIndex], + columns = warpColumns[warpLocalIndex], + mode = warpMode?.get(warpLocalIndex) ?: 0, + keyforms = keyforms, + ) + } + + /** + * Builds one rotation deformer and its pivot-transform keyforms. + * + * @param Int deformerIndex Its index in the shared deformer space (the common head's row). + * @param Int rotationLocalIndex Its index among rotations (every per-rotation table's row). + * @return RotationDeformer The decoded deformer. + */ + private fun rotationDeformer(deformerIndex: Int, rotationLocalIndex: Int): RotationDeformer { + val keyformBinding = rotationKeyformBinding[rotationLocalIndex] + val keyformBase = rotationKeyformBase[rotationLocalIndex] + val keyforms = + (0 until bindings.binding(keyformBinding).gridSize).map { gridIndex -> + RotationKeyform( + keyformValues.rotationOriginX[keyformBase + gridIndex], + keyformValues.rotationOriginY[keyformBase + gridIndex], + keyformValues.rotationAngle[keyformBase + gridIndex], + keyformValues.rotationScale[keyformBase + gridIndex], + keyformValues.rotationReflectX[keyformBase + gridIndex] != 0, + keyformValues.rotationReflectY[keyformBase + gridIndex] != 0, + keyformValues.rotationOpacity[keyformBase + gridIndex], + colorTables.multiplyForKeyform(rotationColorBase?.get(rotationLocalIndex), gridIndex), + colorTables.screenForKeyform(rotationColorBase?.get(rotationLocalIndex), gridIndex), + ) + } + return RotationDeformer( + id = deformerId.getOrElse(deformerIndex) { "" }, + keyformBindingIndex = keyformBinding, + isVisible = deformerIsVisible.getOrElse(deformerIndex) { 1 } != 0, + isEnabled = deformerIsEnabled.getOrElse(deformerIndex) { 1 } != 0, + parentPartIndex = deformerParentPart.getOrElse(deformerIndex) { -1 }, + parentDeformerIndex = deformerParent[deformerIndex], + baseAngle = rotationBaseAngle[rotationLocalIndex], + keyforms = keyforms, + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocAuxLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocAuxLowering.kt new file mode 100644 index 0000000..472f383 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocAuxLowering.kt @@ -0,0 +1,168 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.RenderOrderChild + +/** + * Synthesizes the glue, render-order, and offscreen tables - the object kinds whose packing is + * deterministic but which own no keyform value tables of their own. + * + * @param MocLoweringContext context The shared lowering derivations. + * @return Map Section index → element-region bytes. + * @see MOC3.md §5.6 + */ +internal fun auxiliarySections(context: MocLoweringContext): Map { + val doc = context.doc + val sink = SectionSink(doc.version) + + // glue value tables + if (doc.glues.isNotEmpty()) { + val vertexStart = ArrayList() + val glueVertexCount = ArrayList() + val keyOffset = ArrayList() + val keyCount = ArrayList() + val weights = ArrayList() + val indices = ArrayList() + val intensities = ArrayList() + for (glue in doc.glues) { + vertexStart.add(weights.size) + glueVertexCount.add(glue.pairs.size * 2) + for (pair in glue.pairs) { + weights.add(pair.weightA) + weights.add(pair.weightB) + indices.add(pair.vertexA.toShort()) + indices.add(pair.vertexB.toShort()) + } + keyOffset.add(intensities.size) + keyCount.add(glue.intensityKeyforms.size) + glue.intensityKeyforms.forEach { intensities.add(it) } + } + sink.putInts(Section.GLUE_VERTEX_START, vertexStart) + sink.putInts(Section.GLUE_VERTEX_COUNT, glueVertexCount) + sink.putInts(Section.GLUE_KEY_OFFSET, keyOffset) + sink.putInts(Section.GLUE_KEY_COUNT, keyCount) + sink.putFloats(Section.GLUE_WEIGHTS, weights) + sink.putFloats(Section.GLUE_INTENSITIES, intensities) + sink.putShorts(Section.GLUE_VERTEX_INDICES, indices) + } + + // render-order group tree + if (doc.renderOrderGroups.isNotEmpty()) { + val groups = doc.renderOrderGroups + val childCount = ArrayList() + val childKind = ArrayList() + val childIndex = ArrayList() + val childGroupIndex = ArrayList() + for (group in groups) { + childCount.add(group.children.size) + for (child in group.children) { + childKind.add(child.kind) + childIndex.add(child.index) + childGroupIndex.add(child.groupIndex) + } + } + sink.putInts(Section.RENDER_ORDER_CHILD_COUNT, childCount) + sink.putInts(Section.RENDER_ORDER_CHILD_KIND, childKind) + sink.putInts(Section.RENDER_ORDER_CHILD_INDEX, childIndex) + sink.putInts(Section.RENDER_ORDER_GROUP_INDEX, childGroupIndex) + + // Per-group render count (83) and child draw-order extent (84/85), which the runtime reads. A kind-0 child's draw order is its + // mesh's; a kind-1 child's is its sub-group part's; the render count recurses into sub-groups and + // counts an extra slot for a sub-group part that owns an offscreen. Draw order = floor(0.001+value). + val ownerParts = doc.offscreens.map { it.ownerPartIndex }.toHashSet() + val renderCountMemo = HashMap() + + /** + * Total render-index count of group [groupIndex] (recursive, with offscreen-owner slots). + * + * @param Int groupIndex The render-order group index. + * @return Int The recursive render count. + */ + fun renderCount(groupIndex: Int): Int = + renderCountMemo.getOrPut(groupIndex) { + groups[groupIndex].children.sumOf { child -> + if (child.kind == 0) { + 1 + } else { + (if (child.index in ownerParts) 1 else 0) + renderCount(child.groupIndex) + } + } + } + + /** + * The integer draw order of one render-order [child] (its mesh's, or its sub-group part's). + * + * @param RenderOrderChild child A render-order child. + * @return Int The floored draw order (`floor(0.001 + value)`). + */ + fun childDrawOrder(child: RenderOrderChild): Int { + val drawOrderValue = + if (child.kind == 0) { + doc.artMeshes[child.index].keyforms.first().drawOrder + } else { + doc.parts[child.index].drawOrderKeyforms.first() + } + return (0.001f + drawOrderValue).toInt() + } + + val renderCounts = ArrayList() + val maxDraw = ArrayList() + val minDraw = ArrayList() + for (groupIndex in groups.indices) { + renderCounts.add(renderCount(groupIndex)) + val childOrders = groups[groupIndex].children.map(::childDrawOrder) + // MOC3 §5.6: an EMPTY group stores the max/min fold identities (-INT_MAX / INT_MAX), + // not a 500 default - probed on the ModelWithOffscreen family's childless groups. + maxDraw.add(childOrders.maxOrNull() ?: -Int.MAX_VALUE) + minDraw.add(childOrders.minOrNull() ?: Int.MAX_VALUE) + } + sink.putInts(Section.RENDER_ORDER_GROUP_RENDER_COUNT, renderCounts) + sink.putInts(Section.RENDER_ORDER_GROUP_MAX_DRAW_ORDER, maxDraw) + sink.putInts(Section.RENDER_ORDER_GROUP_MIN_DRAW_ORDER, minDraw) + } + + // offscreens: per-object scalar sections + keyform tables + if (doc.offscreens.isNotEmpty()) { + sink.putInts(Section.OFFSCREEN_OWNER_PART, doc.offscreens.map { it.ownerPartIndex }) + sink.putBytes(Section.OFFSCREEN_CONSTANT_FLAGS, ByteArray(doc.offscreens.size) { doc.offscreens[it].constantFlags.toByte() }) + sink.putInts(Section.OFFSCREEN_BLEND_MODE, doc.offscreens.map { it.blendMode }) + sink.putInts(Section.OFFSCREEN_MASK_COUNT, doc.offscreens.map { it.maskCount }) + // 152: the per-part inverse of OFFSCREEN_OWNER_PART (-1 for offscreen-less parts). + val offscreenByPart = IntArray(doc.parts.size) { -1 } + for ((offscreenIndex, offscreen) in doc.offscreens.withIndex()) { + if (offscreen.ownerPartIndex in offscreenByPart.indices) { + offscreenByPart[offscreen.ownerPartIndex] = offscreenIndex + } + } + sink.putInts(Section.OFFSCREEN_BY_PART, offscreenByPart.toList()) + // 160 gets the SAME inverse map, and it must be written: the runtime reads it as a per-part + // offscreen index, so leaving it empty makes it read the neighbouring section's bytes as part + // indices and take the core down (not a rejected file - a segfault inside it). + // + // The two columns are byte-identical in every corpus file but modelA, where 152 is the exact + // inverse of the offscreen owner column (155) and 160 names a different, larger set of parts + // that matches no owner. Which makes 152 the reconstructible one and 160 an editor-internal + // artifact, in the same class as the keyform-binding numbering: we write the consistent + // inverse in both rather than reproduce a divergence we cannot derive. + sink.putInts(Section.OFFSCREEN_BY_PART_ALIAS, offscreenByPart.toList()) + // 158: cumulative mask base (the scan of 159; MOC3 §5.6, OffscreenKeyformProbeTest). + val maskBases = ArrayList() + var maskBaseCursor = 0 + for (offscreen in doc.offscreens) { + maskBases.add(maskBaseCursor) + maskBaseCursor += offscreen.maskCount + } + sink.putInts(Section.OFFSCREEN_MASK_BASE, maskBases) + // Keyform tables only when the typed extraction populated them (else carried). + if (doc.offscreens.all { it.keyforms.isNotEmpty() }) { + val offscreenOpacities = doc.offscreens.flatMap { offscreen -> offscreen.keyforms.map { it.opacity } } + sink.putFloats(Section.OFFSCREEN_OPACITY, offscreenOpacities) + // 162/163: keyform → color-prefix row maps; identity because the offscreen keyform + // rows ARE the color tables' prefix, in offscreen order. + val identityRows = (0 until offscreenOpacities.size).toList() + sink.putInts(Section.OFFSCREEN_KEYFORM_MULTIPLY_ROW, identityRows) + sink.putInts(Section.OFFSCREEN_KEYFORM_SCREEN_ROW, identityRows) + } + } + return sink.toMap() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocBlendLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocBlendLowering.kt new file mode 100644 index 0000000..6e6ba25 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocBlendLowering.kt @@ -0,0 +1,179 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.BlendShapeTarget + +/** + * Synthesizes the blend-shape record/binding/limit sections from [context] (MOC3 v4+ §5.6: + * 115-136 plus the per-kind object trios 125-130/143-148). Bindings and the limit sub-binding + * pool are re-deduplicated from the per-record expansions (the decoder expands the pool per + * record); RECORD_BASE is recomputed as the per-kind running cursor after the base keyforms, + * which reproduces the decoded values for an unedited document. + * + * @param MocLoweringContext context The shared lowering derivations. + * @return Map Section index → element-region bytes. A document with no blend records still yields + * the per-parameter binding ranges 115/116, which a v4+ file carries either way; only a + * document with no parameters at all yields an empty map. + */ +internal fun blendShapeSections(context: MocLoweringContext): Map { + val doc = context.doc + val sink = SectionSink(doc.version) + val layout = context.blendLayout + + // 115/116: per-parameter binding ranges. A binding-less parameter stores begin = 0, NOT the + // running cumulative (probed on Model A/B/C - unlike SUBSTART's carry convention), unless the + // parameter is itself blend-shape-typed, which stores -1 instead. + // + // Written from the layout on EVERY document, blend records or not. A v4+ blend-free file still + // carries both columns, and an empty layout produces exactly what that file holds, so one path + // covers both kinds of document - the alternative is a second copy of the -1/0 filler rule that + // has to be kept in agreement with this one by hand. Below v4 the sink drops both sections. + // + // A document with NO parameters writes neither: the columns are per-parameter, and emitting + // them empty would override a section `MocEncoder.bake` would otherwise carry from its reference. + if (doc.parameters.isNotEmpty()) { + sink.putInts(Section.BLENDSHAPE_PARAMETER_BEGIN, layout.parameterBegin.toList()) + sink.putInts(Section.BLENDSHAPE_PARAMETER_COUNT, layout.parameterBindingCount.toList()) + } + if (!context.hasBlendShapes) { + return sink.toMap() + } + + // 117-119: per-binding key runs (absolute float offsets into KEY_POSITIONS' second region, + // after the main-grid keys) + neutral indices. + val mainGridKeyTotal = context.mainGridKeyTotal + val bindingKeyOffsets = ArrayList() + var bindingKeyCursor = mainGridKeyTotal + for (bindingKeys in layout.bindingKeys) { + bindingKeyOffsets.add(bindingKeyCursor) + bindingKeyCursor += bindingKeys.size + } + sink.putInts(Section.BLENDSHAPE_BINDING_KEY_OFFSET, bindingKeyOffsets) + sink.putInts(Section.BLENDSHAPE_BINDING_KEY_COUNT, layout.bindingKeys.map { it.size }) + sink.putInts(Section.BLENDSHAPE_BINDING_NEUTRAL, layout.bindingNeutral.toList()) + + // 120-122: per-record binding refs, value-table bases (per-kind running cursors after the + // base keyforms), and the redundant key-count copy. + sink.putInts(Section.BLENDSHAPE_RECORD_BINDING, layout.bindingIndexOfRecord.toList()) + val warps = context.warps + val rotations = context.rotations + val kindCursors = + hashMapOf( + BlendShapeTarget.WARP to warps.sumOf { it.keyforms.size }, + BlendShapeTarget.ART_MESH to doc.artMeshes.sumOf { it.keyforms.size }, + BlendShapeTarget.ROTATION to rotations.sumOf { it.keyforms.size }, + BlendShapeTarget.PART to doc.parts.sumOf { it.drawOrderKeyforms.size }, + ) + val recordBases = ArrayList() + for (record in layout.recordsInFileOrder) { + val cursor = kindCursors.getValue(record.target) + recordBases.add(cursor) + kindCursors[record.target] = cursor + record.keyPositions.size + } + sink.putInts(Section.BLENDSHAPE_RECORD_BASE, recordBases) + sink.putInts(Section.BLENDSHAPE_RECORD_KEY_COUNT, layout.recordsInFileOrder.map { it.keyPositions.size }) + + // 123/124 + 131-136: limit corner refs into the deduplicated sub-binding pool. SUBSTART is + // running-cumulative (cornerless records carry the running value). + val substarts = ArrayList() + val cornerCounts = ArrayList() + val subIndices = ArrayList() + var cornerCursor = 0 + for (record in layout.recordsInFileOrder) { + substarts.add(cornerCursor) + cornerCounts.add(record.limits.size) + cornerCursor += record.limits.size + for (limit in record.limits) { + subIndices.add(layout.poolIndexOf(limit)) + } + } + sink.putInts(Section.BLENDSHAPE_RECORD_SUBSTART, substarts) + sink.putInts(Section.BLENDSHAPE_RECORD_CORNER_COUNT, cornerCounts) + if (layout.pool.isNotEmpty()) { + val subKeyOffsets = ArrayList() + val subKeyCounts = ArrayList() + val subKeys = ArrayList() + val subWeights = ArrayList() + for (poolEntry in layout.pool) { + subKeyOffsets.add(subKeys.size) + subKeyCounts.add(poolEntry.keyPositions.size) + poolEntry.keyPositions.forEach { subKeys.add(it) } + poolEntry.weights.forEach { subWeights.add(it) } + } + sink.putInts(Section.BLENDSHAPE_SUB_INDEX, subIndices) + sink.putInts(Section.BLENDSHAPE_SUB_PARAMETER, layout.pool.map { it.parameterIndex }) + sink.putInts(Section.BLENDSHAPE_SUB_KEY_OFFSET, subKeyOffsets) + sink.putInts(Section.BLENDSHAPE_SUB_KEY_COUNT, subKeyCounts) + sink.putFloats(Section.BLENDSHAPE_SUB_KEYS, subKeys) + sink.putFloats(Section.BLENDSHAPE_SUB_WEIGHT_VALUES, subWeights) + } + + // Per-kind object trios: objects owning records (kind-local indices ascending), with each + // object's record range as GLOBAL record indices. + fun putTrio( + records: List, + recordOffset: Int, + localIndexOf: (Int) -> Int, + objectSection: Section, + startSection: Section, + countSection: Section, + ) { + if (records.isEmpty()) { + return + } + val objectIndices = ArrayList() + val recordStarts = ArrayList() + val recordCounts = ArrayList() + for ((recordOrdinal, record) in records.withIndex()) { + val localObjectIndex = localIndexOf(record.targetIndex) + if (objectIndices.isEmpty() || objectIndices.last() != localObjectIndex) { + objectIndices.add(localObjectIndex) + recordStarts.add(recordOffset + recordOrdinal) + recordCounts.add(1) + } else { + recordCounts[recordCounts.size - 1] = recordCounts.last() + 1 + } + } + sink.putInts(objectSection, objectIndices) + sink.putInts(startSection, recordStarts) + sink.putInts(countSection, recordCounts) + } + + val meshRecordOffset = layout.warpRecords.size + val partRecordOffset = meshRecordOffset + layout.meshRecords.size + val rotationRecordOffset = partRecordOffset + layout.partRecords.size + putTrio( + layout.warpRecords, + 0, + { deformerIndex -> layout.warpLocalByDeformer[deformerIndex] ?: deformerIndex }, + Section.BLENDSHAPE_WARP_OBJECT, + Section.BLENDSHAPE_WARP_RECORD_START, + Section.BLENDSHAPE_WARP_RECORD_COUNT, + ) + putTrio( + layout.meshRecords, + meshRecordOffset, + { drawableIndex -> drawableIndex }, + Section.BLENDSHAPE_MESH_OBJECT, + Section.BLENDSHAPE_MESH_RECORD_START, + Section.BLENDSHAPE_MESH_RECORD_COUNT, + ) + putTrio( + layout.partRecords, + partRecordOffset, + { partIndex -> partIndex }, + Section.BLENDSHAPE_PART_OBJECT, + Section.BLENDSHAPE_PART_RECORD_START, + Section.BLENDSHAPE_PART_RECORD_COUNT, + ) + putTrio( + layout.rotationRecords, + rotationRecordOffset, + { deformerIndex -> layout.rotationLocalByDeformer[deformerIndex] ?: deformerIndex }, + Section.BLENDSHAPE_ROTATION_OBJECT, + Section.BLENDSHAPE_ROTATION_RECORD_START, + Section.BLENDSHAPE_ROTATION_RECORD_COUNT, + ) + return sink.toMap() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocColorLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocColorLowering.kt new file mode 100644 index 0000000..338c373 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocColorLowering.kt @@ -0,0 +1,173 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.format.moc3.model.Rgb +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer + +/** + * Synthesizes the color tables and the per-form row references into them (MOC3 v4+). + * + * The encode-side counterpart of the decoder's ColorTables: one shared row pool that every kind of + * object indexes into, rather than a per-object table. Rows are laid out as a moc-6 offscreen keyform + * PREFIX, then the base rows (deformers in unified order, then art meshes), then the blend records' + * color delta rows - and sections 137-142 are what the runtime dereferences to reach a given form's + * row, so a kind whose reference table is short sends it reading past the pool. + * + * @param MocLoweringContext context The shared lowering derivations. + * @return Map Section index → element-region bytes (empty when the document carries no color data). + * @see MOC3.md §5.6 + */ +internal fun colorSections(context: MocLoweringContext): Map { + val doc = context.doc + val sink = SectionSink(doc.version) + + // Layout (MOC3 §5.6): a moc-6 offscreen keyform PREFIX, then the base rows (deformers in + // unified order, then meshes), then the blend records' color delta rows (global record + // order, part records excluded - parts own no color rows). Synthesized whenever any typed + // color data exists; a doc whose offscreens/blends predate the typed extraction (empty + // keyform lists) falls back to carrying via the size guard below. + val offscreenKeyformsTyped = doc.offscreens.all { it.keyforms.isNotEmpty() } + val hasColor = + (offscreenKeyformsTyped || doc.offscreens.isEmpty()) && + ( + doc.deformers.any { deformer -> + (deformer is WarpDeformer && deformer.keyforms.any { it.multiplyColor != null }) || + (deformer is RotationDeformer && deformer.keyforms.any { it.multiplyColor != null }) + } || + doc.artMeshes.any { mesh -> mesh.keyforms.any { it.multiplyColor != null } } || + doc.offscreens.any { offscreen -> offscreen.keyforms.any { it.multiplyColor != null } } + ) + if (hasColor) { + val multiplyRed = ArrayList() + val multiplyGreen = ArrayList() + val multiplyBlue = ArrayList() + val screenRed = ArrayList() + val screenGreen = ArrayList() + val screenBlue = ArrayList() + + /** + * Appends one keyform's multiply/screen colors, defaulting to white/black when absent. + * + * @param Rgb? multiplyColor The keyform's multiply color (null → white identity). + * @param Rgb? screenColor The keyform's screen color (null → black identity). + */ + fun appendColors(multiplyColor: Rgb?, screenColor: Rgb?) { + val multiply = multiplyColor ?: Rgb(1f, 1f, 1f) + val screen = screenColor ?: Rgb(0f, 0f, 0f) + multiplyRed.add(multiply.r) + multiplyGreen.add(multiply.g) + multiplyBlue.add(multiply.b) + screenRed.add(screen.r) + screenGreen.add(screen.g) + screenBlue.add(screen.b) + } + + /** + * Appends one blend delta row's colors; an unauthored delta channel is ZERO, not the + * channel's identity (MOC3 §5.6: delta rows are neutral-relative). + * + * @param Rgb? multiplyColor The delta row's multiply color (null → zero). + * @param Rgb? screenColor The delta row's screen color (null → zero). + */ + fun appendDeltaColors(multiplyColor: Rgb?, screenColor: Rgb?) { + appendColors(multiplyColor ?: Rgb(0f, 0f, 0f), screenColor ?: Rgb(0f, 0f, 0f)) + } + + // MOC3 v6: the offscreen keyform rows prefix the tables, shifting every base below. + for (offscreen in doc.offscreens) { + offscreen.keyforms.forEach { appendColors(it.multiplyColor, it.screenColor) } + } + // Per-FORM color-row references (137-142), one entry per form SLOT of each object kind, in + // that kind's own form order. They are what the runtime dereferences to reach a form's color + // row, so a kind whose table is short or absent sends it reading past the end - which is a + // segfault inside the official core, not a rejected file. + // + // The tail of each table covers that kind's BLEND-SHAPE record rows: the runtime reaches a + // record's color delta through the same indirection, at the record base rather than the + // object base, so the delta rows have to be addressable here too. + val warpColorRefs = ArrayList() + val rotationColorRefs = ArrayList() + val meshColorRefs = ArrayList() + val warpColorBase = ArrayList() + val rotationColorBase = ArrayList() + for (deformer in doc.deformers) { + when (deformer) { + is WarpDeformer -> { + warpColorBase.add(multiplyRed.size) + deformer.keyforms.forEach { + warpColorRefs.add(multiplyRed.size) + appendColors(it.multiplyColor, it.screenColor) + } + } + + is RotationDeformer -> { + rotationColorBase.add(multiplyRed.size) + deformer.keyforms.forEach { + rotationColorRefs.add(multiplyRed.size) + appendColors(it.multiplyColor, it.screenColor) + } + } + } + } + val meshColorBase = ArrayList() + for (mesh in doc.artMeshes) { + meshColorBase.add(multiplyRed.size) + mesh.keyforms.forEach { + meshColorRefs.add(multiplyRed.size) + appendColors(it.multiplyColor, it.screenColor) + } + } + // A 4.2-era bake carries no delta region (see hasColorDeltaRows) - mirror its absence so + // the re-synthesized tables end at the base rows and stay byte-exact both ways. + if (context.hasBlendShapes && context.hasColorDeltaRows) { + val blendLayout = context.blendLayout + for (record in blendLayout.recordsInFileOrder) { + if (record.target == BlendShapeTarget.PART) { + continue + } + for (keyform in record.keyforms) { + when (keyform) { + is BlendShapeKeyform.Warp -> { + warpColorRefs.add(multiplyRed.size) + appendDeltaColors(keyform.form.multiplyColor, keyform.form.screenColor) + } + + is BlendShapeKeyform.Mesh -> { + meshColorRefs.add(multiplyRed.size) + appendDeltaColors(keyform.form.multiplyColor, keyform.form.screenColor) + } + + is BlendShapeKeyform.Rotation -> { + rotationColorRefs.add(multiplyRed.size) + appendDeltaColors(keyform.form.multiplyColor, keyform.form.screenColor) + } + + // A part owns no color rows at all, so it contributes no reference either. + is BlendShapeKeyform.Part -> Unit + } + } + } + } + // The multiply and screen tables of each pair are bit-identical corpus-wide (the reference is to + // a ROW, and a row carries both colors), so one list feeds both. + sink.putInts(Section.WARP_FORM_MULTIPLY_ROW, warpColorRefs) + sink.putInts(Section.WARP_FORM_SCREEN_ROW, warpColorRefs) + sink.putInts(Section.ROTATION_FORM_MULTIPLY_ROW, rotationColorRefs) + sink.putInts(Section.ROTATION_FORM_SCREEN_ROW, rotationColorRefs) + sink.putInts(Section.ARTMESH_FORM_MULTIPLY_ROW, meshColorRefs) + sink.putInts(Section.ARTMESH_FORM_SCREEN_ROW, meshColorRefs) + sink.putInts(Section.WARP_COLOR_BASE, warpColorBase) + sink.putInts(Section.ROTATION_COLOR_BASE, rotationColorBase) + sink.putInts(Section.ARTMESH_COLOR_BASE, meshColorBase) + sink.putFloats(Section.COLOR_MULTIPLY_R, multiplyRed) + sink.putFloats(Section.COLOR_MULTIPLY_G, multiplyGreen) + sink.putFloats(Section.COLOR_MULTIPLY_B, multiplyBlue) + sink.putFloats(Section.COLOR_SCREEN_R, screenRed) + sink.putFloats(Section.COLOR_SCREEN_G, screenGreen) + sink.putFloats(Section.COLOR_SCREEN_B, screenBlue) + } + return sink.toMap() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocCountInfo.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocCountInfo.kt new file mode 100644 index 0000000..f45778c --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocCountInfo.kt @@ -0,0 +1,140 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.io.LittleEndianWriter +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.BlendShapeKeyform + +/** + * Synthesizes the CountInfo block (section 0) from [context]: the per-object-kind counts and the + * cumulative totals the runtime allocates its working buffers from. The per-kind keyform + * totals (6-10, 14) INCLUDE the blend-shape delta rows (MOC3 §5.6: CountInfo counts the full + * shared tables, base plus delta), and fields 23-36 carry the blend-shape and offscreen totals. + * + * Every total is taken from the shared context rather than recomputed, because CountInfo declares + * the extent of tables the other producers write - a second traversal here could disagree with them. + * + * @param MocLoweringContext context The shared lowering derivations (document, per-kind deformer + * lists, blend layout, and the keyform-grid totals). + * @return ByteArray The CountInfo element-region bytes (`u32[fieldCount]`). + */ +internal fun countInfoSection(context: MocLoweringContext): ByteArray { + val doc = context.doc + val warps = context.warps + val rotations = context.rotations + val blendLayout = context.blendLayout.takeIf { context.hasBlendShapes } + + fun padded(coordinateCount: Int): Int = (coordinateCount + 15) / 16 * 16 + + /** + * Sums the record keys of [records] (the per-kind delta-row total). + * + * @param List? records One kind's records, or null when the doc has no blends. + * @return Int The delta-row total. + */ + fun deltaRowsOf(records: List?): Int = records?.sumOf { it.keyPositions.size } ?: 0 + val positionFloatCount = + warps.sumOf { warp -> warp.keyforms.sumOf { padded(it.controlPoints.size) } } + + doc.artMeshes.sumOf { mesh -> mesh.keyforms.sumOf { padded(it.vertexPositions.size) } } + + ( + blendLayout?.let { layout -> + layout.warpRecords.sumOf { record -> + record.keyforms.filterIsInstance().sumOf { padded(it.form.controlPoints.size) } + } + + layout.meshRecords.sumOf { record -> + record.keyforms.filterIsInstance().sumOf { padded(it.form.vertexPositions.size) } + } + } ?: 0 + ) + // The block widens to 64 words at MOC3 v5, NOT at MOC3 v6: every v5 corpus file's section 0 is 256 + // bytes, and a v5 model with rotation blend shapes writes field 33 (LimeBirb). Capping v5 at 32 + // would silently drop that field, and the re-decode would then find zero blend-shape rotations. + val fieldCount = if (doc.version.byteValue >= 5) 64 else 32 + val countInfo = IntArray(fieldCount) + countInfo[0] = doc.parts.size + countInfo[1] = doc.deformers.size + countInfo[2] = warps.size + countInfo[3] = rotations.size + countInfo[4] = doc.artMeshes.size + countInfo[5] = doc.parameters.size + countInfo[6] = doc.parts.sumOf { it.drawOrderKeyforms.size } + deltaRowsOf(blendLayout?.partRecords) + countInfo[7] = warps.sumOf { it.keyforms.size } + deltaRowsOf(blendLayout?.warpRecords) + countInfo[8] = rotations.sumOf { it.keyforms.size } + deltaRowsOf(blendLayout?.rotationRecords) + countInfo[9] = doc.artMeshes.sumOf { it.keyforms.size } + deltaRowsOf(blendLayout?.meshRecords) + countInfo[10] = positionFloatCount + countInfo[11] = doc.bindings.sumOf { it.axes.size } // total keyform-binding slots + // 12 sizes the runtime's keyform-binding array, which it then indexes by an object's raw + // keyformBindingIndex - so the TABLE WIDTH, matching sections 73/74, not the entry count. + countInfo[12] = context.bindingCount + countInfo[13] = context.totalParamBindings + // 14 counts KEY_POSITIONS' full extent: the main-grid dedup keys, the blend binding key runs, + // and the per-parameter unions (whose counts are section 104). Each term is the same value the + // grid producer wrote, taken from the shared context rather than recomputed. + countInfo[14] = context.mainGridKeyTotal + context.blendLayout.bindingKeys.sumOf { it.size } + if (context.writesUnionRegion) { + countInfo[14] += context.unionKeysByParameter.sumOf { it.size } + } + countInfo[15] = 2 * doc.artMeshes.sumOf { it.vertexCount } + countInfo[16] = doc.artMeshes.sumOf { it.triangleIndices.size } + // 17 sizes MASK_INDEX_DATA, which on MOC3 v6 includes the offscreens' mask prefix (§5.6). + countInfo[17] = doc.artMeshes.sumOf { it.maskDrawableIndices.size } + doc.offscreens.sumOf { it.maskCount } + countInfo[18] = doc.renderOrderGroups.size + countInfo[19] = doc.renderOrderGroups.sumOf { it.children.size } + countInfo[20] = doc.glues.size + countInfo[21] = 2 * doc.glues.sumOf { it.pairs.size } + countInfo[22] = doc.glues.sumOf { it.intensityKeyforms.size } + + /** + * Writes CountInfo field [fieldIndex] when the version's block is wide enough. + * + * @param Int fieldIndex The CountInfo word index. + * @param Int value The field value. + */ + fun putField(fieldIndex: Int, value: Int) { + if (fieldIndex < fieldCount) { + countInfo[fieldIndex] = value + } + } + val offscreenKeyformTotal = doc.offscreens.sumOf { it.keyforms.size } + // 23/24: the color tables' actual row count - the moc-6 offscreen keyform prefix, the base + // keyform rows, and the blend delta rows only when the bake carries the delta region. A + // 4.2-era bake counts base + prefix here even though fields 7-9 still include the delta + // rows for the geometry/opacity tables (corpus: Azxiana.moc3, ci23 13957 vs ci7+8+9 13997). + val colorRowTotal = + if (blendLayout != null && !context.hasColorDeltaRows) { + warps.sumOf { it.keyforms.size } + rotations.sumOf { it.keyforms.size } + + doc.artMeshes.sumOf { it.keyforms.size } + offscreenKeyformTotal + } else { + countInfo[7] + countInfo[8] + countInfo[9] + offscreenKeyformTotal + } + if (blendLayout != null || doc.offscreens.isNotEmpty()) { + putField(23, colorRowTotal) + putField(24, colorRowTotal) + } + if (blendLayout != null) { + putField(25, blendLayout.bindingKeys.size) + putField(26, blendLayout.recordsInFileOrder.size) + putField(27, blendLayout.warpRecords.map { it.targetIndex }.distinct().size) + putField(28, blendLayout.meshRecords.map { it.targetIndex }.distinct().size) + putField(29, blendLayout.recordsInFileOrder.sumOf { it.limits.size }) + putField(30, blendLayout.pool.size) + putField(31, blendLayout.pool.sumOf { it.keyPositions.size }) + putField(32, blendLayout.partRecords.map { it.targetIndex }.distinct().size) + putField(33, blendLayout.rotationRecords.map { it.targetIndex }.distinct().size) + // 34: glue blend shapes - corpus-empty, unmodeled (stays zero). + } + putField(35, doc.offscreens.size) + putField(36, offscreenKeyformTotal) + return intList(countInfo.toList()) +} + +/** + * Encodes [values] as a packed little-endian `i32[]`. + * + * @param List values The integers to write. + * @return ByteArray The packed bytes. + */ +private fun intList(values: List): ByteArray { + val writer = LittleEndianWriter(values.size * 4) + values.forEach(writer::writeInt32) + return writer.toByteArray() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocDerivedIndexes.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocDerivedIndexes.kt new file mode 100644 index 0000000..9e46f35 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocDerivedIndexes.kt @@ -0,0 +1,83 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer + +/** + * Synthesizes the sections that are a pure function of the object lists: per-object form counts, the + * prefix-sum start columns into the shared static tables, the glue ids, and the constant snap type. + * + * Every value here is redundant with data the document already holds, which is why the decoder + * ignores most of them - but a file that omits or mis-sizes one is not loadable, so a writer has to + * produce them all. Each identity below is corpus-verified by `UnmodeledSectionIdentityProbeTest`. + * + * Only the sections needing NO intermediate from another producer live here. The rest - the + * per-form color refs (137-142), the offscreen-by-part alias (160), the parameter binding/key starts + * (56, 103) - are emitted beside the producer that already computes their inputs, so the two cannot + * drift apart. + * + * @see MOC3.md §5.6 + */ +public object MocDerivedIndexes { + /** + * Builds every self-contained derived section for [doc], keyed by section-table index. + * + * @param MocDocument doc The semantic model. + * @return Map Section index → element-region bytes. + */ + public fun derivedIndexSections(doc: MocDocument): Map { + val sink = SectionSink(doc.version) + + /** + * The running prefix sum of [counts]: entry i is the total of everything before it. + * + * @param List counts The per-object run lengths. + * @param Int base The value of entry 0. + * @return List The start column. + */ + fun prefixSum(counts: List, base: Int = 0): List { + var running = base + return counts.map { count -> + val start = running + running += count + start + } + } + + // Per-object keyform counts - the run length each object's keyform base points at. + sink.putInts(Section.PART_KEYFORM_COUNT, doc.parts.map { it.drawOrderKeyforms.size }) + sink.putInts(Section.WARP_KEYFORM_COUNT, doc.deformers.filterIsInstance().map { it.keyforms.size }) + sink.putInts( + Section.ROTATION_KEYFORM_COUNT, + doc.deformers.filterIsInstance().map { it.keyforms.size }, + ) + + // Start columns into the shared static tables. The UV column advances by TWO per vertex + // because section 78 is a flat float array, not a vertex array. + sink.putInts(Section.ARTMESH_UV_START, prefixSum(doc.artMeshes.map { it.vertexCount * 2 })) + sink.putInts(Section.ARTMESH_INDEX_START, prefixSum(doc.artMeshes.map { it.triangleIndices.size })) + // The offscreen masks occupy the PREFIX of section 80 and the drawable masks follow, so the + // drawable column starts past them rather than at zero. + sink.putInts( + Section.ARTMESH_MASK_START, + prefixSum( + doc.artMeshes.map { it.maskDrawableIndices.size }, + base = doc.offscreens.sumOf { it.maskIndices.size }, + ), + ) + + sink.putInts(Section.RENDER_ORDER_CHILD_START, prefixSum(doc.renderOrderGroups.map { it.children.size })) + + // The constant 3 on every parameter of every corpus sample, v1 through v6 - whatever it selects, + // no shipped model ever selects anything else, so there is no model field behind it. + sink.putInts(Section.PARAM_SNAP_TYPE, List(doc.parameters.size) { SNAP_TYPE }) + + sink.putIds(Section.GLUE_ID, doc.glues.map { it.id }) + return sink.toMap() + } + + /** The only snap type any corpus model uses; see [Section.PARAM_SNAP_TYPE]. */ + private const val SNAP_TYPE: Int = 3 +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocEncoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocEncoder.kt new file mode 100644 index 0000000..09a7a30 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocEncoder.kt @@ -0,0 +1,217 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.io.LittleEndianWriter +import org.umamo.format.moc3.moc.ElementType +import org.umamo.format.moc3.moc.MocModel +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section + +/** + * Frames an ordered set of section byte-arrays into a valid `.moc3` blob (header + offset table + + * sections), the serializer half of the bake. + * + * Section k is placed at `table[k]`, its start aligned to 64 bytes - or to 4 for an + * identifier-valued section, matching what the editor writes. [bake] carries whatever it cannot + * synthesize from a reference container; [bakeFresh] synthesizes everything and needs none. + * Neither reproduces the editor's byte layout exactly, which is not required for a runtime-valid + * file. The semantic lowering (model → section arrays) is the other half. + * + * @see MOC3.md §4, §7 + */ +public object MocEncoder { + private const val HEADER_SIZE: Int = 64 + private val MAGIC: ByteArray = byteArrayOf(0x4D, 0x4F, 0x43, 0x33) // "MOC3" + private const val SECTION_ALIGN: Int = 64 + + /** Identifier-valued sections align to 4 rather than 64; see [sectionAlignments]. */ + private const val ID_SECTION_ALIGN: Int = 4 + private const val BUFFER_ALIGN: Int = 64 + + /** + * Rounds [value] up to the next multiple of [alignment]. + * + * @param Int value The value to align. + * @param Int alignment The alignment boundary (e.g. 64). + * @return Int The smallest multiple of [alignment] that is `>= value`. + */ + private fun align(value: Int, alignment: Int): Int = (value + alignment - 1) / alignment * alignment + + /** + * Frames [sections] (in table-index order) into a `.moc3` for the given [versionByte]. + * + * @param Int versionByte The moc version byte (1..6). + * @param Boolean isBigEndian The endian flag (false for every shipped file). + * @param List sections Section payloads, in table order; section k lands at `table[k]`. + * @return ByteArray The complete `.moc3` bytes. + */ + public fun encode(versionByte: Int, isBigEndian: Boolean, sections: List): ByteArray { + val sectionTotal = sections.size + // The runtime reads a fixed-size offset table; reserve the editor's region for the version so + // it never reads past the live offsets into section data (0x7C0 for moc <=5, 0x16C0 for moc 6). + val headerRegion = if (versionByte >= 6) 0x16C0 else 0x7C0 + require(HEADER_SIZE + sectionTotal * 4 <= headerRegion) { + "offset table ($sectionTotal entries) overruns the $headerRegion-byte header region" + } + val firstOffset = headerRegion + val alignmentByIndex = sectionAlignments(versionByte, sectionTotal) + val offsets = IntArray(sectionTotal) + var cursor = firstOffset + for (sectionIndex in 0 until sectionTotal) { + // A section's START is aligned per ITS OWN rule, so the padding belongs to the section about to + // be placed rather than the one just written. Every section (even an empty one) takes the + // running cursor; the runtime indexes by table slot and tolerates equal offsets for empties. + cursor = align(cursor, alignmentByIndex[sectionIndex]) + offsets[sectionIndex] = cursor + cursor += sections[sectionIndex].size + } + val writer = LittleEndianWriter(align(cursor, BUFFER_ALIGN)) + writer.writeBytes(MAGIC) // MOC3 header: magic "MOC3" @ +0x00 + writer.writeU8(versionByte) // MOC3 header: version @ +0x04 + writer.writeU8(if (isBigEndian) 1 else 0) // MOC3 header: endian flag @ +0x05 + writer.zeroPad(HEADER_SIZE - writer.position) // reserved @ +0x06 + for (offset in offsets) writer.writeInt32(offset) // MOC3 offset table @ +0x40 + writer.zeroPad(firstOffset - writer.position) // pad the table region to the data region + for (sectionIndex in 0 until sectionTotal) { + // Pad up to the offset the table already promises for this section. + writer.zeroPad(offsets[sectionIndex] - writer.position) + writer.writeBytes(sections[sectionIndex]) + } + writer.alignTo(BUFFER_ALIGN) + return writer.toByteArray() + } + + /** + * The start alignment each section index requires, for a given moc version. + * + * Identifier-valued sections align to 4 bytes and everything else to 64. Over-aligning would be + * legal (64 satisfies 4), so this is not a correctness fix - it matches the shape the editor + * writes, which is the standing tie-breaker whenever our convenience and its bytes disagree. + * + * @param Int versionByte The moc version byte. + * @param Int sectionTotal How many table slots to describe. + * @return IntArray The per-index alignment. + */ + private fun sectionAlignments(versionByte: Int, sectionTotal: Int): IntArray { + val alignments = IntArray(sectionTotal) { SECTION_ALIGN } + // An unrecognized version gets the conservative all-64 layout rather than a wrong guess. + val version = MocVersion.entries.firstOrNull { it.byteValue == versionByte } ?: return alignments + for (section in Section.entries) { + if (section.element != ElementType.ID) { + continue + } + val index = section.indexIn(version) + if (index in 0 until sectionTotal) { + alignments[index] = ID_SECTION_ALIGN + } + } + return alignments + } + + /** + * Re-frames an existing [MocModel]'s sections into a compact valid `.moc3` (a "repack"). Useful to + * validate the serializer independent of the semantic lowering: the runtime accepts it and reads + * the same model, though the byte layout differs from the original (use + * [org.umamo.format.moc3.moc.MocCodec.write] for a byte-identical re-emit). + * + * @param MocModel model A parsed container. + * @return ByteArray The repacked `.moc3` bytes. + */ + public fun repack(model: MocModel): ByteArray = + encode(model.versionByte, model.isBigEndian, model.sectionBytesInOrder()) + + /** + * Bakes a (possibly-edited) [doc] to `.moc3` bytes, synthesizing every section [synthesize]'s + * producers cover and carrying anything they do not from [reference]. That carry-through is empty + * for every corpus model (`MocBakeFreshCoverageTest` pins the carried set at nothing), so it stands + * against a section some later format version adds rather than against one we cannot derive. The + * result is runtime-valid; for an unedited document the synthesized sections are byte-exact, so it + * matches the original data. + * + * @param MocModel reference The decoded source providing the carried sections + version. + * @param MocDocument doc The (editable) semantic model to bake. + * @return ByteArray The `.moc3` bytes. + */ + public fun bake(reference: MocModel, doc: MocDocument): ByteArray { + val synthesized = synthesize(doc) + // The reference's table can be SHORTER than the version defines (a stripped or hand-built + // container); pinning the output to it would silently drop synthesized sections past its end. + val tableSize = maxOf(reference.sectionCount, sectionCount(reference.version)) + val sections = + List(tableSize) { index -> + synthesized[index] ?: (reference.section(index) ?: ByteArray(0)) + } + return encode(reference.versionByte, reference.isBigEndian, sections) + } + + /** + * Bakes [doc] with NO reference container: every section is synthesized from the object model. + * + * This is what a document that did not come from a `.moc3` needs - there is nothing to carry from. + * Sections the version does not define are emitted empty. + * + * @param MocVersion version The moc version to emit; must match [doc]'s own. + * @param MocDocument doc The semantic model. + * @param Boolean isBigEndian The endian flag (false for every shipped file). + * @return ByteArray The `.moc3` bytes. + */ + public fun bakeFresh(version: MocVersion, doc: MocDocument, isBigEndian: Boolean = false): ByteArray { + // Loud rather than subtly wrong: lowering a document at a version other than its own would emit + // sections gated for one version with values shaped for another. + require(version == doc.version) { "bakeFresh version $version does not match the document's ${doc.version}" } + val synthesized = synthesize(doc) + val sections = List(sectionCount(version)) { index -> synthesized[index] ?: ByteArray(0) } + return encode(version.byteValue, isBigEndian, sections) + } + + /** + * The section indices [bakeFresh] can produce for [doc] - the coverage a completeness gate checks. + * + * An index missing here is one a bake could only carry from a reference container, which is exactly + * what makes a document un-bakeable from scratch. + * + * @param MocDocument doc The semantic model. + * @return Set The produced section indices. + */ + public fun bakeFreshCoverage(doc: MocDocument): Set = synthesize(doc).keys + + /** + * Every section the lowering can synthesize for [doc], keyed by section-table index. + * + * @param MocDocument doc The semantic model. + * @return Map Section index → element-region bytes. + */ + private fun synthesize(doc: MocDocument): Map = MocLowering.lower(doc) + + /** + * The number of section-table entries the editor emits for a moc [version]. The runtime indexes the + * table by fixed section index and never reads its length, so this only needs to be ≥ the highest + * index used; matching the editor keeps the file shape conventional. + * + * Confirmed against samples for v1 (101), v3 (102), v4 (137), v5 (152), and v6 (167); v2 (102) is + * the one unsampled version and follows the editor's version gates (+1 at 3.3, +35 at 4.2, +15 at 5.0). + * + * Matched exhaustively over [MocVersion] on purpose: with an `else` branch a newly added version + * would silently inherit the previous one's table length, which is a wrong file rather than a + * build error. + * + * @param MocVersion version The moc version. + * @return Int The section count. + */ + public fun sectionCount(version: MocVersion): Int = + when (version) { + MocVersion.V30 -> 101 + MocVersion.V33, MocVersion.V40 -> 102 + MocVersion.V42 -> 137 + MocVersion.V50 -> 152 + MocVersion.V53 -> 167 + } +} + +/** + * The section payloads in table-index order (internal accessor for the encoder). Absent sections + * become empty arrays so the list is dense and index-aligned with the offset table. + * + * @return List Each section's raw bytes, in table order. + */ +internal fun MocModel.sectionBytesInOrder(): List = List(sectionCount) { section(it) ?: ByteArray(0) } \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocGridLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocGridLowering.kt new file mode 100644 index 0000000..74698ca --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocGridLowering.kt @@ -0,0 +1,140 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.format.moc3.moc.Section + +/** + * Synthesizes the keyform-binding grid sections from [context] (byte-exact). Reproduces the + * editor's parameter-binding dedup: a parameter-binding is a unique `(parameter, key positions)` + * pair; they are grouped by owning parameter and, within a parameter, ordered by first occurrence + * scanning keyform-bindings in index order. + * + * @param MocLoweringContext context The shared lowering derivations. + * @return Map Section index → element-region bytes. + */ +internal fun keyformGridSections(context: MocLoweringContext): Map { + val doc = context.doc + val sink = SectionSink(doc.version) + val version = doc.version + + val parameterCount = doc.parameters.size + val bindingCount = context.bindingCount + val bindingAxes = context.bindingAxes + val keySetsByParameter = context.keySetsByParameter + // assign parameter-binding indices grouped by parameter + val parameterBindingIndex = HashMap>, Int>() + val parameterBindingOrder = ArrayList>() + val parameterBindingCount = IntArray(parameterCount) + for (parameterIndex in 0 until parameterCount) { + parameterBindingCount[parameterIndex] = keySetsByParameter[parameterIndex].size + for (keys in keySetsByParameter[parameterIndex]) { + parameterBindingIndex[parameterIndex to keys] = parameterBindingOrder.size + parameterBindingOrder.add(keys) + } + } + + val keyOffset = ArrayList() + val keyCount = ArrayList() + val keyPositions = ArrayList() + for (keys in parameterBindingOrder) { + keyOffset.add(keyPositions.size) + keyCount.add(keys.size) + keyPositions.addAll(keys) + } + val keyformBindingStart = ArrayList() + val keyformBindingCount = ArrayList() + val keyformBindingSlot = ArrayList() + for (bindingIndex in 0 until bindingCount) { + keyformBindingStart.add(keyformBindingSlot.size) + keyformBindingCount.add(bindingAxes[bindingIndex].size) + for ((parameterIndex, keys) in bindingAxes[bindingIndex]) { + keyformBindingSlot.add(parameterBindingIndex.getValue(parameterIndex to keys)) + } + } + + sink.putInts(Section.PARAMETER_BINDING_COUNT, parameterBindingCount.toList()) + // The matching START column, which the runtime uses to find each parameter's binding run. Written + // here rather than beside the other prefix sums because it needs the pool this function builds. + // + // The empty-slot filler is NOT arbitrary: a parameter with no bindings stores -1 when it is NORMAL + // and 0 when it is BLEND_SHAPE. Both values occur within one file (LimeBirb, modelF), so the + // parameter type is the only thing that tells the two fillers apart. + val parameterBindingStart = IntArray(parameterCount) + run { + var cursor = 0 + for (parameterIndex in 0 until parameterCount) { + parameterBindingStart[parameterIndex] = + if (parameterBindingCount[parameterIndex] > 0) { + val start = cursor + cursor += parameterBindingCount[parameterIndex] + start + } else if (doc.parameters.getOrNull(parameterIndex)?.type == ParameterType.BLEND_SHAPE) { + 0 + } else { + -1 + } + } + } + sink.putInts(Section.PARAM_BINDING_START, parameterBindingStart.toList()) + sink.putInts(Section.BINDING_KEY_OFFSET, keyOffset) + sink.putInts(Section.BINDING_KEY_COUNT, keyCount) + // KEY_POSITIONS is up to THREE regions (MOC3 §5.6): the main-grid dedup keys; then, on a blend + // model, the blend bindings' key runs (section 117 offsets point here); then the per-parameter + // sorted union of main-grid axis keys and blend-binding keys, whose counts are section 104. + // A blend-free document contributes nothing to the middle region and nothing but its main-grid + // keys to the union, so the same walk covers both kinds of document. + // + // Omitting 104 on a v4+ file is not a smaller file, it is an unloadable one: the runtime reads + // it unconditionally to SIZE its parameter key store, and an absent section still resolves to a + // pointer - so it sizes the arena from whatever bytes follow. + val allKeyPositions = ArrayList(keyPositions) + for (bindingKeys in context.blendLayout.bindingKeys) { + bindingKeys.forEach { allKeyPositions.add(it) } + } + val unionBase = allKeyPositions.size + val unionKeyCounts = ArrayList() + if (context.writesUnionRegion) { + for (unionKeys in context.unionKeysByParameter) { + unionKeyCounts.add(unionKeys.size) + allKeyPositions.addAll(unionKeys) + } + } + sink.putFloats(Section.KEY_POSITIONS, allKeyPositions) + putParameterKeyRuns(sink, version, unionKeyCounts, unionBase) + sink.putInts(Section.KEYFORM_BINDING_SLOT, keyformBindingSlot) + sink.putInts(Section.KEYFORM_BINDING_START, keyformBindingStart) + sink.putInts(Section.KEYFORM_BINDING_COUNT, keyformBindingCount) + return sink.toMap() +} + +/** + * Writes the per-parameter key run columns (103 start, 104 count) over the key-position union region. + * + * @param SectionSink sink The calling producer's section sink. + * @param MocVersion version The target version (the columns are MOC3 v4+). + * @param List counts Each parameter's union key count, in parameter order. + * @param Int regionStart Where the union region begins inside KEY_POSITIONS. + */ +private fun putParameterKeyRuns( + sink: SectionSink, + version: MocVersion, + counts: List, + regionStart: Int, +) { + if (version.byteValue < 4 || counts.isEmpty()) { + return + } + // The start column is an OFFSET INTO KEY_POSITIONS, not a running count from zero: the union + // region sits after the main-grid keys (and, on a blend model, the blend binding keys), so a + // prefix sum based at 0 would point every parameter at the wrong run. + var cursor = regionStart + val starts = + counts.map { count -> + val start = cursor + cursor += count + start + } + sink.putInts(Section.PARAM_KEY_START, starts) + sink.putInts(Section.PARAM_KEY_COUNT, counts) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocLowering.kt new file mode 100644 index 0000000..ad906c3 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocLowering.kt @@ -0,0 +1,68 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.Section + +/** + * Lowers a [MocDocument] back to section byte-arrays (the semantic half of the bake). + * + * The work is split across per-concern producers, each in its own file and each mirroring the decoder + * collaborator it has to round-trip against: structure ([structuralSections]), keyform value tables + * ([valueTableSections]), color tables ([colorSections]), the glue/render-order/offscreen tables + * ([auxiliarySections]), the parameter-binding grid ([keyformGridSections]), blend records + * ([blendShapeSections]), the self-contained derived columns ([MocDerivedIndexes]), the zero-filled + * runtime slots ([MocRuntimeSlots]), and section 0 ([countInfoSection]). Everything they share is + * derived once in [MocLoweringContext]; everything they write goes through a [SectionSink]. + * + * Every packing here is derived rather than carried, and deterministic, so one document always lowers + * to one set of bytes. + * + * @see MOC3.md §5, §7 + */ +public object MocLowering { + /** + * Lowers [doc] to every section it can produce, keyed by section-table index. + * + * The producers are merged STRICTLY: two of them claiming the same index fails here rather than + * resolving by merge order. That is not defensive - a `+` fold would resolve a double claim by + * silently keeping the later producer, leaving the shadowed copy editable with no effect on any + * output and no test to notice. Every index has exactly one owner, and this is what keeps it + * that way. + * + * @param MocDocument doc The semantic model. + * @return Map Section index → element-region bytes (no trailing padding). + */ + public fun lower(doc: MocDocument): Map { + val context = MocLoweringContext(doc) + val merged = LinkedHashMap() + val claimedBy = HashMap() + + /** + * Folds one producer's output in, failing when it claims an index another producer already owns. + * + * @param String producerName The producer's name, for the failure message. + * @param Map produced Its section index → element-region bytes. + */ + fun merge(producerName: String, produced: Map) { + for ((index, bytes) in produced) { + val previousProducer = claimedBy.put(index, producerName) + require(previousProducer == null) { + val sectionName = Section.entries.firstOrNull { it.indexIn(doc.version) == index }?.name ?: "unmodeled" + "section $index ($sectionName) claimed by both $previousProducer and $producerName" + } + merged[index] = bytes + } + } + + merge("structural", structuralSections(context)) + merge("valueTables", valueTableSections(context)) + merge("color", colorSections(context)) + merge("auxiliary", auxiliarySections(context)) + merge("keyformGrid", keyformGridSections(context)) + merge("blendShapes", blendShapeSections(context)) + merge("runtimeSlots", MocRuntimeSlots.runtimeSlotSections(doc)) + merge("derivedIndexes", MocDerivedIndexes.derivedIndexSections(doc)) + merge("countInfo", mapOf(Section.COUNT_INFO.indexIn(doc.version) to countInfoSection(context))) + return merged + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocLoweringContext.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocLoweringContext.kt new file mode 100644 index 0000000..2010a22 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocLoweringContext.kt @@ -0,0 +1,250 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.BlendShapeLimit +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer + +/** + * Everything the lowering producers derive from a [MocDocument] before any of them writes a byte. + * + * Each producer could rebuild what it needs on its own - the blend-shape file layout, the + * parameter-binding dedup grid, the per-parameter key union - and that would not be merely repeated + * work: CountInfo has to declare the exact extent of tables the other producers write, so two + * traversals drifting apart produces a file whose header disagrees with its own body. Deriving once + * and sharing is what makes them unable to disagree. + * + * @see MOC3.md §5.6 + */ +internal class MocLoweringContext(val doc: MocDocument) { + val version: MocVersion = doc.version + val warps: List = doc.deformers.filterIsInstance() + val rotations: List = doc.deformers.filterIsInstance() + + /** + * The blend-shape layout, built even when the document has no records. + * + * An empty layout is exactly what a blend-free document has to write (no bindings, no records, + * every per-parameter column at its empty-slot filler), so one code path covers both kinds of + * document instead of two that have to be kept in agreement. + */ + val blendLayout: BlendShapeLayout = BlendShapeLayout(doc) + + /** Whether the document carries any blend-shape record at all. */ + val hasBlendShapes: Boolean = doc.blendShapes.isNotEmpty() + + /** Whether the color tables carry the blend delta region, probed from the records' delta colors. */ + val hasColorDeltaRows: Boolean = hasColorDeltaRows(doc) + + /** + * The width of the keyform-binding table: one slot per index in `0 until bindingCount`. + * + * Taken from the highest binding index rather than the map's entry count. The two agree on every + * document any producer builds today, but sections 73/74 are written one row per slot while + * CountInfo field 12 sizes the runtime's array, and the runtime indexes that array by an object's + * raw `keyformBindingIndex` - which reaches the highest index, not the entry count. Deriving both + * from this one value is what stops a sparse map from producing a header that under-sizes its body. + */ + val bindingCount: Int = (doc.bindings.maxOfOrNull { it.index } ?: -1) + 1 + + /** Each keyform binding's axes as `(parameter, key positions)`, in binding-index order. */ + val bindingAxes: List>>> = + (0 until bindingCount).map { bindingIndex -> + doc.keyformBinding(bindingIndex)?.axes?.map { it.parameterIndex to it.keyPositions.toList() } + ?: emptyList() + } + + /** Per parameter, its distinct axis key-lists in first-occurrence order (the main-grid dedup). */ + val keySetsByParameter: Array>> = + Array>>(doc.parameters.size) { LinkedHashSet() }.also { keySets -> + for (axes in bindingAxes) { + for ((parameterIndex, keys) in axes) { + keySets[parameterIndex].add(keys) + } + } + } + + /** Total distinct parameter-bindings across every parameter (CountInfo field 13). */ + val totalParamBindings: Int = keySetsByParameter.sumOf { it.size } + + /** Float count of KEY_POSITIONS' main-grid region (the dedup keys, before any later region). */ + val mainGridKeyTotal: Int = keySetsByParameter.sumOf { keySet -> keySet.sumOf { it.size } } + + /** + * Per parameter, the sorted union of its main-grid axis keys and its blend bindings' keys. + * + * One computation for both kinds of document: on a blend-free one the layout contributes nothing, + * so the union collapses to the main-grid keys. + */ + val unionKeysByParameter: List> = + doc.parameters.indices.map { parameterIndex -> + val unionKeys = mutableSetOf() + for (keys in keySetsByParameter[parameterIndex]) { + unionKeys.addAll(keys) + } + for (bindingIndex in blendLayout.bindingKeys.indices) { + if (blendLayout.bindingOwnerParameter[bindingIndex] == parameterIndex) { + blendLayout.bindingKeys[bindingIndex].forEach { unionKeys.add(it) } + } + } + unionKeys.sorted() + } + + /** + * Whether KEY_POSITIONS carries the per-parameter union region. + * + * On MOC3 v4+ the region is always present and sections 103/104 address it; below v4 it appears + * only in the editor builds that wrote it, which the document records as + * `keyPositionsHasParameterUnion`. + * + * ONE predicate answers both "is the region written" and "does CountInfo field 14 count it", + * because those are the same question: field 14 declares section 77's extent and 103/104 address + * runs inside it, so a document that writes the region without counting it points the runtime past + * the buffer field 14 just sized. Splitting the two would let a v4+ blend-free export declare only + * its main-grid keys while carrying the union region as well. + */ + val writesUnionRegion: Boolean = + hasBlendShapes || doc.keyPositionsHasParameterUnion || version.byteValue >= 4 +} + +/** + * Whether [doc] carries the color tables' blend delta region. The region is a later format + * addition, absent on 4.2-era bakes whose tables end at the base rows (corpus: Azxiana.moc3, + * V42); the decoder marks absence by null colors on every non-part record keyform, and the + * region is all-or-nothing per file (a present region decodes zeros as non-null Rgb), so any + * non-null delta color means the source carried it. + * + * @param MocDocument doc The semantic model. + * @return Boolean True when the doc's blend keyforms carry color delta rows. + */ +internal fun hasColorDeltaRows(doc: MocDocument): Boolean = + doc.blendShapes.any { blend -> + blend.keyforms.any { keyform -> + when (keyform) { + is BlendShapeKeyform.Warp -> keyform.form.multiplyColor != null + is BlendShapeKeyform.Mesh -> keyform.form.multiplyColor != null + is BlendShapeKeyform.Rotation -> keyform.form.multiplyColor != null + is BlendShapeKeyform.Part -> false + } + } + } + +/** + * The blend-shape file layout derived from a document's records: the global record order + * (warp, mesh, part, then rotation records - objects ascending by kind-local index, verified + * on the corpus), the deduplicated binding list (grouped by parameter ascending, first + * occurrence within a parameter), and the deduplicated limit sub-binding pool (sorted by + * gating-parameter index; the within-parameter tie-break is first-occurrence order across + * recordsInFileOrder). + */ +internal class BlendShapeLayout(doc: MocDocument) { + val warpRecords: List + val meshRecords: List + val partRecords: List + val rotationRecords: List + val recordsInFileOrder: List + val warpLocalByDeformer: Map + val rotationLocalByDeformer: Map + val bindingKeys: List + val bindingNeutral: IntArray + val bindingOwnerParameter: IntArray + val parameterBegin: IntArray + val parameterBindingCount: IntArray + val bindingIndexOfRecord: IntArray + val pool: List + private val poolIndexByValue: Map, Int> + + init { + val warpLocal = HashMap() + val rotationLocal = HashMap() + var nextWarpLocal = 0 + var nextRotationLocal = 0 + for ((deformerIndex, deformer) in doc.deformers.withIndex()) { + if (deformer is WarpDeformer) { + warpLocal[deformerIndex] = nextWarpLocal++ + } else { + rotationLocal[deformerIndex] = nextRotationLocal++ + } + } + warpLocalByDeformer = warpLocal + rotationLocalByDeformer = rotationLocal + warpRecords = + doc.blendShapes.filter { it.target == BlendShapeTarget.WARP } + .sortedBy { warpLocal[it.targetIndex] ?: Int.MAX_VALUE } + meshRecords = doc.blendShapes.filter { it.target == BlendShapeTarget.ART_MESH }.sortedBy { it.targetIndex } + partRecords = doc.blendShapes.filter { it.target == BlendShapeTarget.PART }.sortedBy { it.targetIndex } + rotationRecords = + doc.blendShapes.filter { it.target == BlendShapeTarget.ROTATION } + .sortedBy { rotationLocal[it.targetIndex] ?: Int.MAX_VALUE } + recordsInFileOrder = warpRecords + meshRecords + partRecords + rotationRecords + + // Distinct bindings: (parameter, keys, neutral), first-occurrence order re-sorted by + // parameter (stable, so within-parameter order stays first-occurrence). + data class BindingIdentity(val parameterIndex: Int, val keys: List, val neutralKeyIndex: Int) + + val discoveredBindings = LinkedHashSet() + for (record in recordsInFileOrder) { + discoveredBindings.add( + BindingIdentity(record.parameterIndex, record.keyPositions.toList(), record.neutralKeyIndex), + ) + } + val orderedBindings = discoveredBindings.toList().sortedBy { it.parameterIndex } + bindingKeys = orderedBindings.map { it.keys.toFloatArray() } + bindingNeutral = IntArray(orderedBindings.size) { bindingIndex -> orderedBindings[bindingIndex].neutralKeyIndex } + bindingOwnerParameter = IntArray(orderedBindings.size) { bindingIndex -> orderedBindings[bindingIndex].parameterIndex } + val bindingIndexByIdentity = orderedBindings.withIndex().associate { (bindingIndex, identity) -> identity to bindingIndex } + bindingIndexOfRecord = + IntArray(recordsInFileOrder.size) { recordIndex -> + val record = recordsInFileOrder[recordIndex] + bindingIndexByIdentity.getValue( + BindingIdentity(record.parameterIndex, record.keyPositions.toList(), record.neutralKeyIndex), + ) + } + parameterBegin = IntArray(doc.parameters.size) + parameterBindingCount = IntArray(doc.parameters.size) + var bindingCursor = 0 + for (parameterIndex in doc.parameters.indices) { + parameterBindingCount[parameterIndex] = + orderedBindings.count { it.parameterIndex == parameterIndex } + // Binding-less parameters store 0, not the running cumulative - UNLESS the parameter is + // itself blend-shape-typed (a morph-target axis authored with no record bound to it), + // which stores -1 instead. + parameterBegin[parameterIndex] = + when { + parameterBindingCount[parameterIndex] > 0 -> bindingCursor + doc.parameters[parameterIndex].type == ParameterType.BLEND_SHAPE -> -1 + else -> 0 + } + bindingCursor += parameterBindingCount[parameterIndex] + } + + // The limit sub-binding pool, deduplicated by value. Sorted by gating-parameter index + // (corpus-observed); the within-parameter tie-break is first-occurrence order across + // recordsInFileOrder (Kotlin's sortedBy is stable). + fun identityOf(limit: BlendShapeLimit): List = + listOf(limit.parameterIndex, limit.keyPositions.toList(), limit.weights.toList()) + + val distinctLimits = LinkedHashMap, BlendShapeLimit>() + for (record in recordsInFileOrder) { + for (limit in record.limits) { + distinctLimits.getOrPut(identityOf(limit)) { limit } + } + } + pool = distinctLimits.values.sortedBy { it.parameterIndex } + poolIndexByValue = pool.withIndex().associate { (poolIndex, poolEntry) -> identityOf(poolEntry) to poolIndex } + } + + /** + * The pool index of [limit] (matched by value). + * + * @param BlendShapeLimit limit A per-record expanded limit curve. + * @return Int The deduplicated pool index. + */ + fun poolIndexOf(limit: BlendShapeLimit): Int = + poolIndexByValue.getValue(listOf(limit.parameterIndex, limit.keyPositions.toList(), limit.weights.toList())) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocRuntimeSlots.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocRuntimeSlots.kt new file mode 100644 index 0000000..d4ad78d --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocRuntimeSlots.kt @@ -0,0 +1,52 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.ElementType +import org.umamo.format.moc3.moc.Section + +/** + * Synthesizes the per-object runtime-slot sections: the 8-byte fields each object block opens with, + * which are all-zero on disk and filled by the runtime after its memory-cast. + * + * These carry no authored data, so a writer only has to SIZE them - but sizing them is not optional. + * The array must be exactly as long as its object list or the runtime reads past the end of the one + * it just allocated, which is why a bake cannot simply carry them from a reference file once the + * object count changes. That is the whole reason they are modeled at all. + * + * Corpus-verified all-zero across every sample by `UnmodeledSectionIdentityProbeTest`. + * + * @see MOC3.md §5.6 + */ +public object MocRuntimeSlots { + /** + * Builds every runtime-slot section for [doc], keyed by section-table index. + * + * @param MocDocument doc The semantic model. + * @return Map Section index → zero bytes, sized to the owning object list. + */ + public fun runtimeSlotSections(doc: MocDocument): Map { + val sink = SectionSink(doc.version) + + /** + * Emits one zero-filled slot array, sized to its owning object list. + * + * @param Section section The runtime-slot section. + * @param Int objectCount How many objects the array covers. + */ + fun put(section: Section, objectCount: Int) = sink.putZeros(section, objectCount * ElementType.U64.size) + + put(Section.PART_RUNTIME_SLOT, doc.parts.size) + put(Section.DEFORMER_RUNTIME_SLOT, doc.deformers.size) + // The art-mesh block opens with FOUR of them (Lina's research reads them as a header plus three + // unknowns); all four are zero, and all four must be sized. + put(Section.ARTMESH_RUNTIME_SLOT, doc.artMeshes.size) + put(Section.ARTMESH_RUNTIME_SLOT_A, doc.artMeshes.size) + put(Section.ARTMESH_RUNTIME_SLOT_B, doc.artMeshes.size) + put(Section.ARTMESH_RUNTIME_SLOT_C, doc.artMeshes.size) + put(Section.PARAM_RUNTIME_SLOT, doc.parameters.size) + put(Section.PARAM_RUNTIME_SLOT_A, doc.parameters.size) + put(Section.GLUE_RUNTIME_SLOT, doc.glues.size) + put(Section.OFFSCREEN_RUNTIME_SLOT, doc.offscreens.size) + return sink.toMap() + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocStructureLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocStructureLowering.kt new file mode 100644 index 0000000..3b8573c --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocStructureLowering.kt @@ -0,0 +1,112 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.WarpDeformer + +/** + * Synthesizes the structural/topology sections from [context], keyed by section-table index. + * + * @param MocLoweringContext context The shared lowering derivations. + * @return Map Section index → element-region bytes (no trailing padding). + */ +internal fun structuralSections(context: MocLoweringContext): Map { + val doc = context.doc + val sink = SectionSink(doc.version) + + doc.canvas?.let { canvas -> + sink.putFloats(Section.CANVAS, canvas.pixelsPerUnit, canvas.originX, canvas.originY, canvas.width, canvas.height, 0f) + } + + // parameters + sink.putIds(Section.PARAM_ID, doc.parameters.map { it.id }) + sink.putFloats(Section.PARAM_MAX, doc.parameters.map { it.maximumValue }) + sink.putFloats(Section.PARAM_MIN, doc.parameters.map { it.minimumValue }) + sink.putFloats(Section.PARAM_DEFAULT, doc.parameters.map { it.defaultValue }) + sink.putInts(Section.PARAM_REPEAT, doc.parameters.map { if (it.repeats) 1 else 0 }) + if (doc.parameters.any { it.type != null }) { + sink.putInts(Section.PARAM_TYPE, doc.parameters.map { it.type!!.number }) + } + + // parts + sink.putIds(Section.PART_ID, doc.parts.map { it.id }) + // MOC3 §5.6 s7/s8: a paired flag column, the same shape as the deformer (s13/s14) and art-mesh + // (s37/s38) pairs. The FIRST carries visibility; the SECOND is 1 on every part of every corpus + // sample and its meaning is unpinned, which `PairedVisibilityFlagProbeTest` pins as an invariant. + // Projecting isVisible into both would put a 0 in a column the editor has never been observed + // writing one into - a hidden part would make our bake the only file in existence that deviates. + sink.putInts(Section.PART_VISIBLE_ARTMESHES, doc.parts.map { if (it.isVisible) 1 else 0 }) + sink.putInts(Section.PART_VISIBLE_DEFORMERS, doc.parts.map { 1 }) + sink.putInts(Section.PART_PARENT, doc.parts.map { it.parentPartIndex }) + sink.putInts(Section.PART_KEYFORM_BINDING, doc.parts.map { it.keyformBindingIndex }) + + // drawables (art meshes) + topology + sink.putIds(Section.ARTMESH_ID, doc.artMeshes.map { it.id }) + sink.putInts(Section.ARTMESH_TEXTURE, doc.artMeshes.map { it.textureIndex }) + sink.putBytes(Section.ARTMESH_CONSTANT_FLAGS, ByteArray(doc.artMeshes.size) { doc.artMeshes[it].constantFlags.toByte() }) + // MOC3 v6 §5.6 s153: per-drawable packed extended blend (v6-only; the sink drops it below v6). + sink.putInts(Section.ARTMESH_EXTENDED_BLEND, doc.artMeshes.map { it.extendedBlend }) + // Hidden art meshes are CARRIED with the flag clear, never dropped - the official editor deletes + // them by default, but Umamo has no option to and doing it silently would be destructive. + sink.putInts(Section.ARTMESH_IS_VISIBLE, doc.artMeshes.map { if (it.isVisible) 1 else 0 }) + sink.putInts(Section.ARTMESH_IS_ENABLED, doc.artMeshes.map { if (it.isEnabled) 1 else 0 }) + sink.putInts(Section.ARTMESH_VERTEX_COUNT, doc.artMeshes.map { it.vertexCount }) + sink.putInts(Section.ARTMESH_INDEX_COUNT, doc.artMeshes.map { it.triangleIndices.size }) + sink.putInts(Section.ARTMESH_MASK_COUNT, doc.artMeshes.map { it.maskDrawableIndices.size }) + sink.putInts(Section.ARTMESH_PARENT_PART, doc.artMeshes.map { it.parentPartIndex }) + sink.putInts(Section.ARTMESH_PARENT_DEFORMER, doc.artMeshes.map { it.parentDeformerIndex }) + sink.putInts(Section.ARTMESH_KEYFORM_BINDING, doc.artMeshes.map { it.keyformBindingIndex }) + sink.putInts(Section.ARTMESH_KEYFORM_COUNT, doc.artMeshes.map { doc.keyformBinding(it.keyformBindingIndex)?.gridSize ?: 1 }) + sink.putFloatConcat(Section.ARTMESH_UV_DATA, doc.artMeshes) { it.vertexUvs } + sink.putShortConcat(Section.ARTMESH_INDEX_DATA, doc.artMeshes) { it.triangleIndices } + // The mask-index block holds (moc 6) the offscreens' mask lists as a PREFIX, then the + // drawables' mask lists (MOC3 §5.6 section 80; s158 offsets from the block start - pinned on + // Model A against the CMO3 clip lists). The prefix synthesizes from the typed + // Offscreen.maskIndices; a doc predating the typed extraction (index count != maskCount) + // carries the section instead. + if (doc.offscreens.all { it.maskIndices.size == it.maskCount }) { + val maskIndexValues = ArrayList() + for (offscreen in doc.offscreens) { + offscreen.maskIndices.forEach { maskIndexValues.add(it) } + } + for (mesh in doc.artMeshes) { + mesh.maskDrawableIndices.forEach { maskIndexValues.add(it) } + } + sink.putInts(Section.MASK_INDEX_DATA, maskIndexValues) + } + + // deformers (unified list + per-type). The block's leading runtime slot is sized by + // [MocRuntimeSlots] along with every other object block's, so it is not written here. + sink.putIds(Section.DEFORMER_ID, doc.deformers.map { it.id }) + sink.putInts(Section.DEFORMER_KEYFORM_BINDING, doc.deformers.map { it.keyformBindingIndex }) + sink.putInts(Section.DEFORMER_IS_VISIBLE, doc.deformers.map { if (it.isVisible) 1 else 0 }) + sink.putInts(Section.DEFORMER_IS_ENABLED, doc.deformers.map { if (it.isEnabled) 1 else 0 }) + sink.putInts(Section.DEFORMER_PARENT_PART, doc.deformers.map { it.parentPartIndex }) + sink.putInts(Section.DEFORMER_PARENT, doc.deformers.map { it.parentDeformerIndex }) + sink.putInts(Section.DEFORMER_TYPE, doc.deformers.map { if (it is WarpDeformer) 0 else 1 }) + // per-deformer index within its type group (warps vs rotations), in deformer-list order + val localIndex = IntArray(doc.deformers.size) + run { + var nextWarpLocal = 0 + var nextRotationLocal = 0 + for ((deformerIndex, deformer) in doc.deformers.withIndex()) { + localIndex[deformerIndex] = if (deformer is WarpDeformer) nextWarpLocal++ else nextRotationLocal++ + } + } + sink.putInts(Section.DEFORMER_LOCAL_INDEX, localIndex.toList()) + val warps = context.warps + val rotations = context.rotations + sink.putInts(Section.WARP_CONTROL_POINT_COUNT, warps.map { (it.rows + 1) * (it.columns + 1) }) + sink.putInts(Section.WARP_ROWS, warps.map { it.rows }) + sink.putInts(Section.WARP_COLUMNS, warps.map { it.columns }) + sink.putInts(Section.WARP_MODE, warps.map { it.mode }) + sink.putInts(Section.WARP_KEYFORM_BINDING, warps.map { it.keyformBindingIndex }) + sink.putFloats(Section.ROTATION_BASE_ANGLE, rotations.map { it.baseAngle }) + sink.putInts(Section.ROTATION_KEYFORM_BINDING, rotations.map { it.keyformBindingIndex }) + + // glue topology (mesh pair + binding) + sink.putInts(Section.GLUE_MESH_A, doc.glues.map { it.meshAIndex }) + sink.putInts(Section.GLUE_MESH_B, doc.glues.map { it.meshBIndex }) + sink.putInts(Section.GLUE_KEYFORM_BINDING, doc.glues.map { it.keyformBindingIndex }) + + return sink.toMap() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocValueLowering.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocValueLowering.kt new file mode 100644 index 0000000..4cd8530 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/MocValueLowering.kt @@ -0,0 +1,168 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.io.LittleEndianWriter +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.BlendShapeKeyform + +/** + * Synthesizes the keyform value tables from [context], keyed by section-table index. These are + * the layout-dependent geometry/scalar tables; the packing is deterministic (warp keyform blocks + * then mesh blocks in `POS_VALUES`, each padded to 16 floats; bases are cumulative), so they + * reconstruct byte-for-byte. The keyform-binding grid (param-binding dedup) is not synthesized + * here. + * + * @param MocLoweringContext context The shared lowering derivations. + * @return Map Section index → element-region bytes. + */ +internal fun valueTableSections(context: MocLoweringContext): Map { + val doc = context.doc + val sink = SectionSink(doc.version) + + val warps = context.warps + val rotations = context.rotations + + // POS_VALUES: warp control-point keyform blocks first, then art-mesh vertex keyform blocks, + // each padded to a 16-float (64-byte) boundary. Index tables record each block's float offset. + val positionValues = LittleEndianWriter(64 * 1024) + val warpPositionIndex = ArrayList() + val warpKeyformBase = IntArray(warps.size) + val warpOpacity = ArrayList() + for ((warpIndex, warp) in warps.withIndex()) { + warpKeyformBase[warpIndex] = warpPositionIndex.size + for (keyform in warp.keyforms) { + warpPositionIndex.add(positionValues.position / 4) + keyform.controlPoints.forEach(positionValues::writeFloat32) + padTo16Floats(positionValues, keyform.controlPoints.size) + warpOpacity.add(keyform.opacity) + } + } + val meshPositionIndex = ArrayList() + val meshKeyformBase = IntArray(doc.artMeshes.size) + val meshOpacity = ArrayList() + val meshDrawOrder = ArrayList() + for ((meshIndex, mesh) in doc.artMeshes.withIndex()) { + meshKeyformBase[meshIndex] = meshPositionIndex.size + for (keyform in mesh.keyforms) { + meshPositionIndex.add(positionValues.position / 4) + keyform.vertexPositions.forEach(positionValues::writeFloat32) + padTo16Floats(positionValues, keyform.vertexPositions.size) + meshOpacity.add(keyform.opacity) + meshDrawOrder.add(keyform.drawOrder) + } + } + + // Blend-shape delta rows append AFTER the base keyforms in the same tables (MOC3 §5.6): + // POS_VALUES gains warp-record then mesh-record delta blocks (16-float padded like the base + // blocks), the per-kind index/scalar tables gain one row per (record, key) in global record + // order, so the per-object bases above stay pure base-prefix indices. + val blendLayout = context.blendLayout.takeIf { context.hasBlendShapes } + if (blendLayout != null) { + for (record in blendLayout.warpRecords) { + for (keyform in record.keyforms) { + val warpDelta = (keyform as? BlendShapeKeyform.Warp)?.form ?: continue + warpPositionIndex.add(positionValues.position / 4) + warpDelta.controlPoints.forEach(positionValues::writeFloat32) + padTo16Floats(positionValues, warpDelta.controlPoints.size) + warpOpacity.add(warpDelta.opacity) + } + } + for (record in blendLayout.meshRecords) { + for (keyform in record.keyforms) { + val meshDelta = (keyform as? BlendShapeKeyform.Mesh)?.form ?: continue + meshPositionIndex.add(positionValues.position / 4) + meshDelta.vertexPositions.forEach(positionValues::writeFloat32) + padTo16Floats(positionValues, meshDelta.vertexPositions.size) + meshOpacity.add(meshDelta.opacity) + meshDrawOrder.add(meshDelta.drawOrder) + } + } + } + + sink.putInts(Section.WARP_KEYFORM_BASE, warpKeyformBase.toList()) + sink.putInts(Section.ARTMESH_KEYFORM_BASE, meshKeyformBase.toList()) + + // rotation deformers: per-keyform affine tables, base = cumulative rotation keyforms. + val rotationKeyformBase = IntArray(rotations.size) + val rotationAngle = ArrayList() + val rotationOriginX = ArrayList() + val rotationOriginY = ArrayList() + val rotationScale = ArrayList() + val rotationReflectX = ArrayList() + val rotationReflectY = ArrayList() + val rotationOpacity = ArrayList() + var rotationKeyformCounter = 0 + for ((rotationIndex, rotation) in rotations.withIndex()) { + rotationKeyformBase[rotationIndex] = rotationKeyformCounter + for (keyform in rotation.keyforms) { + rotationAngle.add(keyform.angle) + rotationOriginX.add(keyform.originX) + rotationOriginY.add(keyform.originY) + rotationScale.add(keyform.scale) + rotationReflectX.add(if (keyform.reflectX) 1 else 0) + rotationReflectY.add(if (keyform.reflectY) 1 else 0) + rotationOpacity.add(keyform.opacity) + rotationKeyformCounter++ + } + } + sink.putInts(Section.ROTATION_KEYFORM_BASE, rotationKeyformBase.toList()) + if (blendLayout != null) { + // MOC3 §5.6: rotation delta rows sit directly in the affine tables 61-67 after the base rows. + for (record in blendLayout.rotationRecords) { + for (keyform in record.keyforms) { + val rotationDelta = (keyform as? BlendShapeKeyform.Rotation)?.form ?: continue + rotationAngle.add(rotationDelta.angle) + rotationOriginX.add(rotationDelta.originX) + rotationOriginY.add(rotationDelta.originY) + rotationScale.add(rotationDelta.scale) + rotationReflectX.add(if (rotationDelta.reflectX) 1 else 0) + rotationReflectY.add(if (rotationDelta.reflectY) 1 else 0) + rotationOpacity.add(rotationDelta.opacity) + } + } + } + + sink.putBytes(Section.KEYFORM_POSITION_VALUES, positionValues.toByteArray()) + sink.putInts(Section.WARP_KEYFORM_INDEX, warpPositionIndex) + sink.putFloats(Section.WARP_OPACITY, warpOpacity) + sink.putInts(Section.KEYFORM_POSITION_INDEX, meshPositionIndex) + sink.putFloats(Section.ARTMESH_OPACITY, meshOpacity) + sink.putFloats(Section.ARTMESH_DRAW_ORDER, meshDrawOrder) + sink.putFloats(Section.ROTATION_ANGLE, rotationAngle) + sink.putFloats(Section.ROTATION_ORIGIN_X, rotationOriginX) + sink.putFloats(Section.ROTATION_ORIGIN_Y, rotationOriginY) + sink.putFloats(Section.ROTATION_SCALE, rotationScale) + sink.putInts(Section.ROTATION_REFLECT_X, rotationReflectX) + sink.putInts(Section.ROTATION_REFLECT_Y, rotationReflectY) + sink.putFloats(Section.ROTATION_OPACITY, rotationOpacity) + + // parts: per-part draw-order keyform table + cumulative base (a static part has a single value). + // MOC3 v5+ §5.6: part-owned blend-shape records append draw-order delta rows to section 58. + val partDrawOrder = ArrayList() + val partKeyformBase = IntArray(doc.parts.size) + for ((partIndex, part) in doc.parts.withIndex()) { + partKeyformBase[partIndex] = partDrawOrder.size + part.drawOrderKeyforms.forEach { partDrawOrder.add(it) } + } + if (blendLayout != null) { + for (record in blendLayout.partRecords) { + for (keyform in record.keyforms) { + val partDelta = keyform as? BlendShapeKeyform.Part ?: continue + partDrawOrder.add(partDelta.drawOrderDelta) + } + } + } + sink.putInts(Section.PART_KEYFORM_BASE, partKeyformBase.toList()) + sink.putFloats(Section.PART_DRAW_ORDER, partDrawOrder) + return sink.toMap() +} + +/** + * Zero-pads [writer] so a block of [count] floats reaches the next 16-float (64-byte) boundary. + * + * @param LittleEndianWriter writer The value-table writer to pad. + * @param Int count The number of floats just written in this block. + */ +private fun padTo16Floats(writer: LittleEndianWriter, count: Int) { + val padCount = ((count + 15) / 16 * 16) - count + repeat(padCount) { writer.writeFloat32(0f) } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/SectionSink.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/SectionSink.kt new file mode 100644 index 0000000..3590c11 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/encode/SectionSink.kt @@ -0,0 +1,180 @@ +package org.umamo.format.moc3.encode + +import org.umamo.format.moc3.io.LittleEndianWriter +import org.umamo.format.moc3.moc.ElementType +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections + +/** + * Collects a lowering producer's output as section index → element-region bytes. + * + * Owns the two things every producer would otherwise repeat: resolving a [Section] to its table index + * for the target version, and skipping a section the version does not define (a negative index). The + * typed putters encode as they store, so a call site names the section and the values and nothing else. + * + * Each typed putter checks the section's declared [ElementType], which is what stops an `i32[]` column + * from being written into an `f32[]` section - the section table is the only record of a section's + * element width, and a mismatch there produces a file the runtime reads at the wrong stride. + * + * @see MOC3.md §5.6 + */ +internal class SectionSink(private val version: MocVersion) { + private val sections = LinkedHashMap() + + /** + * The collected sections, keyed by section-table index. + * + * @return Map Section index → element-region bytes. + */ + fun toMap(): Map = sections + + /** + * Stores [bytes] verbatim under [section], if the version defines it. + * + * The unchecked escape hatch: it carries pre-packed blocks (the keyform position values are already + * a little-endian float run) as readily as genuine `u8[]` columns, so it deliberately does not + * check the element type. Prefer a typed putter wherever the values are still typed. + * + * @param Section section The section to write. + * @param ByteArray bytes The element-region bytes. + */ + fun putBytes(section: Section, bytes: ByteArray) { + val index = section.indexIn(version) + if (index >= 0) { + sections[index] = bytes + } + } + + /** + * Stores a zero-filled region of [byteCount] bytes under [section]. + * + * @param Section section The section to write. + * @param Int byteCount How many zero bytes the region spans. + */ + fun putZeros(section: Section, byteCount: Int): Unit = putBytes(section, ByteArray(byteCount)) + + /** + * Encodes [values] as a packed little-endian `i32[]` under [section]. + * + * @param Section section The section to write. + * @param List values The integers, in element order. + */ + fun putInts(section: Section, values: List) { + requireElement(section, ElementType.I32, ElementType.U32) + val writer = LittleEndianWriter(values.size * 4) + values.forEach(writer::writeInt32) + putBytes(section, writer.toByteArray()) + } + + /** + * Encodes [values] as a packed little-endian `i32[]` under [section]. + * + * @param Section section The section to write. + * @param IntArray values The integers, in element order. + */ + fun putInts(section: Section, values: IntArray) { + requireElement(section, ElementType.I32, ElementType.U32) + val writer = LittleEndianWriter(values.size * 4) + values.forEach(writer::writeInt32) + putBytes(section, writer.toByteArray()) + } + + /** + * Encodes [values] as a packed little-endian `f32[]` under [section]. + * + * @param Section section The section to write. + * @param List values The floats, in element order. + */ + fun putFloats(section: Section, values: List) { + requireElement(section, ElementType.F32) + val writer = LittleEndianWriter(values.size * 4) + values.forEach(writer::writeFloat32) + putBytes(section, writer.toByteArray()) + } + + /** + * Encodes [values] as a packed little-endian `f32[]` under [section]. + * + * @param Section section The section to write. + * @param Float values The floats, in element order. + */ + fun putFloats(section: Section, vararg values: Float) { + requireElement(section, ElementType.F32) + val writer = LittleEndianWriter(values.size * 4) + values.forEach(writer::writeFloat32) + putBytes(section, writer.toByteArray()) + } + + /** + * Encodes [values] as a packed little-endian `i16[]` under [section]. + * + * @param Section section The section to write. + * @param List values The shorts, in element order. + */ + fun putShorts(section: Section, values: List) { + requireElement(section, ElementType.I16) + val writer = LittleEndianWriter(values.size * 2) + values.forEach { shortValue -> writer.writeU16(shortValue.toInt()) } + putBytes(section, writer.toByteArray()) + } + + /** + * Encodes [identifiers] as fixed [Sections.ID_STRIDE]-byte NUL-terminated, zero-padded id records. + * + * @param Section section The section to write. + * @param List identifiers The identifiers, in element order. + */ + fun putIds(section: Section, identifiers: List) { + requireElement(section, ElementType.ID) + val writer = LittleEndianWriter(identifiers.size * Sections.ID_STRIDE) + for (identifier in identifiers) { + writer.writeFixedString(identifier, Sections.ID_STRIDE) + } + putBytes(section, writer.toByteArray()) + } + + /** + * Concatenates each item's selected `f32[]` into one packed block under [section]. + * + * @param Section section The section to write. + * @param List items The items to draw arrays from. + * @param (T) -> FloatArray select The per-item float array selector. + */ + fun putFloatConcat(section: Section, items: List, select: (T) -> FloatArray) { + requireElement(section, ElementType.F32) + val writer = LittleEndianWriter(items.sumOf { select(it).size } * 4) + for (item in items) { + select(item).forEach(writer::writeFloat32) + } + putBytes(section, writer.toByteArray()) + } + + /** + * Concatenates each item's selected `i16[]` into one packed block under [section]. + * + * @param Section section The section to write. + * @param List items The items to draw arrays from. + * @param (T) -> ShortArray select The per-item short array selector. + */ + fun putShortConcat(section: Section, items: List, select: (T) -> ShortArray) { + requireElement(section, ElementType.I16) + val writer = LittleEndianWriter(items.sumOf { select(it).size } * 2) + for (item in items) { + select(item).forEach { shortValue -> writer.writeU16(shortValue.toInt()) } + } + putBytes(section, writer.toByteArray()) + } + + /** + * Fails when [section] does not declare one of [allowed] as its element type. + * + * @param Section section The section being written. + * @param ElementType allowed The element types this putter encodes. + */ + private fun requireElement(section: Section, vararg allowed: ElementType) { + require(section.element in allowed) { + "$section is a ${section.element} section; cannot write it as ${allowed.joinToString("/")}" + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/io/LittleEndianReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/io/LittleEndianReader.kt new file mode 100644 index 0000000..a4ed028 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/io/LittleEndianReader.kt @@ -0,0 +1,118 @@ +package org.umamo.format.moc3.io + +/** + * Little-endian, non-obfuscated reader over a byte array. + * + * EN: MOC3 is a flat little-endian blob - no obfuscation, no compression (unlike CMO3's + * big-endian, XOR'd CAFF container). All multi-byte integers and floats are little-endian. + * JA: MOC3 はリトルエンディアンの素のバイナリ(難読化・圧縮なし)。 + * + * @see MOC3.md + */ +public class LittleEndianReader(private val data: ByteArray) { + /** Current read cursor, in bytes from the start of [data]. */ + public var position: Int = 0 + private set + + /** Total length of the backing buffer. */ + public val size: Int get() = data.size + + /** + * Moves the cursor to an absolute byte offset. + * + * @param Int offset Absolute position to seek to. + */ + public fun seek(offset: Int) { + position = offset + } + + /** + * Advances the cursor by [count] bytes without interpreting them. + * + * @param Int count Number of bytes to skip. + */ + public fun skip(count: Int) { + position += count + } + + /** + * Reads one unsigned byte (0..255). + * + * @return Int The byte value in 0..255. + */ + public fun readU8(): Int { + val value = data[position].toInt() and 0xFF + position += 1 + return value + } + + /** + * Reads a little-endian unsigned 16-bit integer (0..65535). + * + * @return Int The decoded value. + */ + public fun readU16(): Int { + val low = data[position].toInt() and 0xFF + val high = data[position + 1].toInt() and 0xFF + position += 2 + return (high shl 8) or low + } + + /** + * Reads a little-endian signed 32-bit integer. + * + * @return Int The decoded value. + */ + public fun readInt32(): Int { + val byte0 = data[position].toInt() and 0xFF + val byte1 = data[position + 1].toInt() and 0xFF + val byte2 = data[position + 2].toInt() and 0xFF + val byte3 = data[position + 3].toInt() and 0xFF + position += 4 + return byte0 or (byte1 shl 8) or (byte2 shl 16) or (byte3 shl 24) + } + + /** + * Reads a little-endian unsigned 32-bit integer as a [Long] (0..4294967295). + * + * EN: Section offsets and counts are stored as u32; in practice they fit in a signed Int (files + * are < 2 GiB), but this avoids surprises near the boundary. + * + * @return Long The decoded value. + */ + public fun readU32(): Long = readInt32().toLong() and 0xFFFFFFFFL + + /** + * Reads a little-endian 32-bit IEEE-754 float. + * + * @return Float The decoded value. + */ + public fun readFloat32(): Float = Float.fromBits(readInt32()) + + /** + * Reads [count] raw bytes. + * + * @param Int count Number of bytes to read. + * @return ByteArray A freshly allocated copy of the bytes. + */ + public fun readBytes(count: Int): ByteArray { + val out = data.copyOfRange(position, position + count) + position += count + return out + } + + /** + * Reads a fixed-width [width]-byte record as a NUL-terminated ASCII/UTF-8 string. + * + * EN: MOC3 IDs are 64-byte records: the identifier bytes, a NUL, then zero padding. + * + * @param Int width Record width in bytes (e.g. 64). + * @return String The string up to the first NUL. + */ + public fun readFixedString(width: Int): String { + val raw = readBytes(width) + var end = 0 + while (end < raw.size && raw[end].toInt() != 0) end++ + return raw.decodeToString(0, end) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/io/LittleEndianWriter.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/io/LittleEndianWriter.kt new file mode 100644 index 0000000..2159078 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/io/LittleEndianWriter.kt @@ -0,0 +1,152 @@ +package org.umamo.format.moc3.io + +/** + * Little-endian, non-obfuscated writer into a growable byte buffer. + * + * EN: Inverse of [LittleEndianReader]; same little-endian conventions, plus [alignTo] for the + * zero-padding MOC3 uses between sections / at end of file. + * JA: [LittleEndianReader] の逆操作。 + * + * @see MOC3.md + */ +public class LittleEndianWriter(initialCapacity: Int = 64 * 1024) { + private var buffer = ByteArray(initialCapacity) + + /** Number of bytes written so far (also the current write cursor). */ + public var position: Int = 0 + private set + + /** + * Grows the backing buffer if needed so that [additional] more bytes fit from [position]. + * + * Doubles capacity (amortised O(1) appends), but jumps straight to the required size when a single + * write exceeds a doubling. + * + * @param Int additional Number of bytes about to be written. + */ + private fun ensure(additional: Int) { + val needed = position + additional + if (needed > buffer.size) { + var newSize = buffer.size * 2 + if (newSize < needed) { + newSize = needed + } + buffer = buffer.copyOf(newSize) + } + } + + /** Returns a copy of the written bytes (length == [position]). */ + public fun toByteArray(): ByteArray = buffer.copyOf(position) + + /** + * Writes [count] zero bytes. + * + * @param Int count Number of zero bytes to emit. + */ + public fun zeroPad(count: Int) { + ensure(count) + position += count + } + + /** + * Zero-pads until [position] is a multiple of [alignment]. + * + * @param Int alignment Byte boundary to align to (e.g. 64). + */ + public fun alignTo(alignment: Int) { + val remainder = position % alignment + if (remainder != 0) { + zeroPad(alignment - remainder) + } + } + + /** + * Writes one byte (low 8 bits used). + * + * @param Int value Byte value. + */ + public fun writeU8(value: Int) { + ensure(1) + buffer[position] = value.toByte() + position += 1 + } + + /** + * Writes a little-endian 16-bit integer (low 16 bits used). + * + * Takes an [Int] and masks rather than taking a [Short] with a range precondition: callers pass + * `shortValue.toInt()`, which sign-extends above 32767, and a mesh with more than 32767 vertices + * writes exactly those values. A `require` here would reject a file the format permits. + * + * @param Int value Value to write; only the low 16 bits are used. + */ + public fun writeU16(value: Int) { + ensure(2) + buffer[position] = value.toByte() + buffer[position + 1] = (value ushr 8).toByte() + position += 2 + } + + /** + * Writes a little-endian 32-bit integer. + * + * @param Int value Value to write. + */ + public fun writeInt32(value: Int) { + ensure(4) + buffer[position] = value.toByte() + buffer[position + 1] = (value ushr 8).toByte() + buffer[position + 2] = (value ushr 16).toByte() + buffer[position + 3] = (value ushr 24).toByte() + position += 4 + } + + /** + * Writes a little-endian 32-bit IEEE-754 float. + * + * @param Float value Value to write. + */ + public fun writeFloat32(value: Float): Unit = writeInt32(value.toRawBits()) + + /** + * Writes raw bytes verbatim. + * + * @param ByteArray bytes Bytes to write. + */ + public fun writeBytes(bytes: ByteArray) { + ensure(bytes.size) + bytes.copyInto(buffer, position) + position += bytes.size + } + + /** + * Writes [value] as a fixed-width [width]-byte NUL-terminated record, zero-padded to width. + * + * Inverse of [LittleEndianReader.readFixedString]. MOC3 IDs are 64-byte records holding + * plain ASCII (MOC3 §5.4), so the encoded form must fit in `width - 1` bytes to leave room for + * the terminator; the corpus's longest id is well inside that. + * + * @param String value The identifier to write. + * @param Int width Record width in bytes (e.g. 64). + * @pre The UTF-8 encoding of [value] is shorter than [width]. + */ + public fun writeFixedString(value: String, width: Int) { + val encoded = value.encodeToByteArray() + require(encoded.size < width) { "id \"$value\" (${encoded.size} bytes) does not fit a $width-byte record" } + writeBytes(encoded) + zeroPad(width - encoded.size) + } + + /** + * Overwrites an already-written little-endian int32 at an absolute offset (back-patching). + * + * @param Int offset Absolute byte offset of the 4-byte slot. + * @param Int value Value to store. + */ + public fun patchInt32(offset: Int, value: Int) { + buffer[offset] = value.toByte() + buffer[offset + 1] = (value ushr 8).toByte() + buffer[offset + 2] = (value ushr 16).toByte() + buffer[offset + 3] = (value ushr 24).toByte() + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Cdi3Json.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Cdi3Json.kt new file mode 100644 index 0000000..f0b5de5 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Cdi3Json.kt @@ -0,0 +1,54 @@ +package org.umamo.format.moc3.json + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * `*.cdi3.json` - display info: human-readable names and grouping for parameters/parts, plus + * 2-axis "combined parameter" hints. Purely cosmetic (no runtime effect). + * + * Keys/order match the `cdi3.json` the editor exports, with one addition: `Drawables` is an Umamo + * extension (MOC3.md §6.3 documents no such key) carrying drawable display names, which the `.moc3` + * itself has no field for. `CombinedParameters` is an array-of-pairs (`[horizontal, vertical]`). + * + * @see MOC3.md §cdi3.json + */ +@Serializable +public data class Cdi3Json( + @SerialName("Version") val version: Int, + @SerialName("Parameters") val parameters: List, + @SerialName("ParameterGroups") val parameterGroups: List, + @SerialName("Parts") val parts: List, + @SerialName("CombinedParameters") val combinedParameters: List>? = null, + @SerialName("Drawables") val drawables: List? = null, +) + +/** A parameter's display name and owning group. */ +@Serializable +public data class DisplayParameter( + @SerialName("Id") val id: String, + @SerialName("GroupId") val groupId: String, + @SerialName("Name") val name: String, +) + +/** A parameter group's display name and (optional) parent group. */ +@Serializable +public data class DisplayParameterGroup( + @SerialName("Id") val id: String, + @SerialName("GroupId") val groupId: String, + @SerialName("Name") val name: String, +) + +/** A drawable's display name (the Umamo extension - see [Cdi3Json.drawables]). */ +@Serializable +public data class DisplayDrawable( + @SerialName("Id") val id: String, + @SerialName("Name") val name: String, +) + +/** A part's display name. */ +@Serializable +public data class DisplayPart( + @SerialName("Id") val id: String, + @SerialName("Name") val name: String, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Model3Json.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Model3Json.kt new file mode 100644 index 0000000..e0de40c --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Model3Json.kt @@ -0,0 +1,68 @@ +package org.umamo.format.moc3.json + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * `*.model3.json` - the model manifest referencing the `.moc3`, textures, and other sidecars. + * + * EN: Field order and names match the `model3.json` the editor exports (the SDK's documented + * manifest schema). Optional references are nullable and omitted when absent, so re-emission + * drops nothing. + * JA: モデルマニフェスト。 + * + * @see MOC3.md §model3.json + */ +@Serializable +public data class Model3Json( + @SerialName("Version") val version: Int, + @SerialName("FileReferences") val fileReferences: FileReferences, + @SerialName("Groups") val groups: List? = null, + @SerialName("HitAreas") val hitAreas: List? = null, +) + +/** File references within a [Model3Json]; all but [moc]/[textures] are optional. */ +@Serializable +public data class FileReferences( + @SerialName("Moc") val moc: String, + @SerialName("Textures") val textures: List, + @SerialName("Pose") val pose: String? = null, + @SerialName("Physics") val physics: String? = null, + @SerialName("UserData") val userData: String? = null, + @SerialName("DisplayInfo") val displayInfo: String? = null, + @SerialName("Expressions") val expressions: List? = null, + @SerialName("Motions") val motions: Map>? = null, +) + +/** An auto-wiring group (e.g. `EyeBlink`, `LipSync`) of parameter or part IDs. */ +@Serializable +public data class Model3Group( + @SerialName("Target") val target: String, + @SerialName("Name") val name: String, + @SerialName("Ids") val ids: List, +) + +/** A hit-test area mapping a display name to a drawable ID. */ +@Serializable +public data class Model3HitArea( + @SerialName("Name") val name: String, + @SerialName("Id") val id: String, +) + +/** An expression reference (`*.exp3.json`) with optional fade times. */ +@Serializable +public data class Model3Expression( + @SerialName("Name") val name: String, + @SerialName("File") val file: String, + @SerialName("FadeInTime") val fadeInTime: kotlinx.serialization.json.JsonPrimitive? = null, + @SerialName("FadeOutTime") val fadeOutTime: kotlinx.serialization.json.JsonPrimitive? = null, +) + +/** A motion reference (`*.motion3.json`) within a named group, with optional sound and fade times. */ +@Serializable +public data class Model3Motion( + @SerialName("File") val file: String, + @SerialName("Sound") val sound: String? = null, + @SerialName("FadeInTime") val fadeInTime: kotlinx.serialization.json.JsonPrimitive? = null, + @SerialName("FadeOutTime") val fadeOutTime: kotlinx.serialization.json.JsonPrimitive? = null, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Physics3Json.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Physics3Json.kt new file mode 100644 index 0000000..d488b30 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Physics3Json.kt @@ -0,0 +1,117 @@ +package org.umamo.format.moc3.json + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonPrimitive + +/** + * `*.physics3.json` - the physics rig definition (input/output bindings, particle chains). + * + * EN: Physical quantities (weights, scales, positions, forces, normalization bounds) are kept as + * [JsonPrimitive] so the editor's exact numeric tokens round-trip (it prints integral floats + * without a trailing `.0`). The physics math is out of scope here; this only models the file. + * JA: 物理演算リグ定義。数値はトークン保持。 + * + * @see MOC3.md §physics3.json + */ +@Serializable +public data class Physics3Json( + @SerialName("Version") val version: Int, + @SerialName("Meta") val meta: PhysicsMeta, + @SerialName("PhysicsSettings") val physicsSettings: List, +) + +/** Counts, effective forces, optional fps, and the names dictionary for a [Physics3Json]. */ +@Serializable +public data class PhysicsMeta( + @SerialName("PhysicsSettingCount") val physicsSettingCount: Int, + @SerialName("TotalInputCount") val totalInputCount: Int, + @SerialName("TotalOutputCount") val totalOutputCount: Int, + @SerialName("VertexCount") val vertexCount: Int, + @SerialName("Fps") val fps: JsonPrimitive? = null, + @SerialName("EffectiveForces") val effectiveForces: EffectiveForces, + @SerialName("PhysicsDictionary") val physicsDictionary: List, +) + +/** The constant gravity and wind vectors. */ +@Serializable +public data class EffectiveForces( + @SerialName("Gravity") val gravity: PhysicsVector2, + @SerialName("Wind") val wind: PhysicsVector2, +) + +/** A 2D vector with token-preserving components. */ +@Serializable +public data class PhysicsVector2( + @SerialName("X") val x: JsonPrimitive, + @SerialName("Y") val y: JsonPrimitive, +) + +/** A `(Id, Name)` pair naming a physics setting (parallel to [Physics3Json.physicsSettings] by index). */ +@Serializable +public data class PhysicsDictionaryEntry( + @SerialName("Id") val id: String, + @SerialName("Name") val name: String, +) + +/** One physics setting: its inputs, outputs, particle chain, and normalization. */ +@Serializable +public data class PhysicsSetting( + @SerialName("Id") val id: String, + @SerialName("Input") val input: List, + @SerialName("Output") val output: List, + @SerialName("Vertices") val vertices: List, + @SerialName("Normalization") val normalization: PhysicsNormalization, +) + +/** A parameter-driven input to the rig. */ +@Serializable +public data class PhysicsInput( + @SerialName("Source") val source: PhysicsTarget, + @SerialName("Weight") val weight: JsonPrimitive, + @SerialName("Type") val type: String, + @SerialName("Reflect") val reflect: Boolean, +) + +/** A particle-driven output to a parameter. */ +@Serializable +public data class PhysicsOutput( + @SerialName("Destination") val destination: PhysicsTarget, + @SerialName("VertexIndex") val vertexIndex: Int, + @SerialName("Scale") val scale: JsonPrimitive, + @SerialName("Weight") val weight: JsonPrimitive, + @SerialName("Type") val type: String, + @SerialName("Reflect") val reflect: Boolean, +) + +/** A target reference (`Target` kind + `Id`). */ +@Serializable +public data class PhysicsTarget( + @SerialName("Target") val target: String, + @SerialName("Id") val id: String, +) + +/** A particle in the chain (`[0]` is the anchor). */ +@Serializable +public data class PhysicsVertex( + @SerialName("Position") val position: PhysicsVector2, + @SerialName("Mobility") val mobility: JsonPrimitive, + @SerialName("Delay") val delay: JsonPrimitive, + @SerialName("Acceleration") val acceleration: JsonPrimitive, + @SerialName("Radius") val radius: JsonPrimitive, +) + +/** Input normalization ranges for position and angle. */ +@Serializable +public data class PhysicsNormalization( + @SerialName("Position") val position: PhysicsNormalizationRange, + @SerialName("Angle") val angle: PhysicsNormalizationRange, +) + +/** A `(Minimum, Default, Maximum)` normalization range. */ +@Serializable +public data class PhysicsNormalizationRange( + @SerialName("Minimum") val minimum: JsonPrimitive, + @SerialName("Default") val default: JsonPrimitive, + @SerialName("Maximum") val maximum: JsonPrimitive, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Sidecars.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Sidecars.kt new file mode 100644 index 0000000..0a9ed6d --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/Sidecars.kt @@ -0,0 +1,30 @@ +package org.umamo.format.moc3.json + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json + +/** + * The `Json` configuration that reproduces the Cubism editor's sidecar output. + * + * Tab-indented, pretty-printed, properties in declaration order; optional fields are omitted + * when absent (`explicitNulls = false`). Numeric leaves the editor prints without a trailing + * `.0` (e.g. `"Y": -1`, `"Weight": 60`) are modelled as + * [kotlinx.serialization.json.JsonPrimitive] so the original token round-trips exactly. + * Decoding tolerates unknown keys (`ignoreUnknownKeys`): newer Cubism exports add manifest + * fields the schema does not model yet (e.g. Cubism 5's FileReferences.MotionSync), and a + * reader that rejects them refuses valid real-world models. The flag affects decoding only, + * so encoded output is unchanged - but it means decode-then-encode DROPS unmodelled keys, so + * a future sidecar re-emit path must preserve unknown keys explicitly (raw JsonObject + * passthrough) rather than relying on the serializer. + * + * @see MOC3.md §JSON sidecars + */ +@OptIn(ExperimentalSerializationApi::class) +internal val SidecarJson: Json = + Json { + prettyPrint = true + prettyPrintIndent = "\t" + explicitNulls = false + encodeDefaults = true + ignoreUnknownKeys = true + } \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/UserData3Json.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/UserData3Json.kt new file mode 100644 index 0000000..a7f8f94 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/json/UserData3Json.kt @@ -0,0 +1,35 @@ +package org.umamo.format.moc3.json + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * `*.userdata3.json` - per-object user strings attached to drawables. + * + * EN: Keys/order match the `userdata3.json` the editor exports (`Meta` is `UserDataCount` + + * `TotalUserDataSize`; the SDK only consumes `Target == "ArtMesh"` entries). + * JA: ユーザーデータ。 + * + * @see MOC3.md §userdata3.json + */ +@Serializable +public data class UserData3Json( + @SerialName("Version") val version: Int, + @SerialName("Meta") val meta: UserDataMeta, + @SerialName("UserData") val userData: List, +) + +/** Counts for a [UserData3Json]: number of entries and total byte size of their values. */ +@Serializable +public data class UserDataMeta( + @SerialName("UserDataCount") val userDataCount: Int, + @SerialName("TotalUserDataSize") val totalUserDataSize: Int, +) + +/** A single user-data entry: target kind, target ID, and the user string. */ +@Serializable +public data class UserDataEntry( + @SerialName("Target") val target: String, + @SerialName("Id") val id: String, + @SerialName("Value") val value: String, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/Flags.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/Flags.kt new file mode 100644 index 0000000..10c2be3 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/Flags.kt @@ -0,0 +1,61 @@ +package org.umamo.format.moc3.moc + +/** + * Per-drawable constant flags (`SEC_DRAW_CFLAG`, section index 42), a `u8` bitmask. These match the + * public runtime API (`csmConstantDrawableFlags`); the low bits are blend mode, then masking. + * + * @see MOC3.md + */ +public object ConstantFlag { + /** Additive blending. */ + public const val BLEND_ADDITIVE: Int = 1 shl 0 + + /** Multiplicative blending. */ + public const val BLEND_MULTIPLICATIVE: Int = 1 shl 1 + + /** The mesh is double-sided. */ + public const val IS_DOUBLE_SIDED: Int = 1 shl 2 + + /** The clipping mask is inverted. */ + public const val IS_INVERTED_MASK: Int = 1 shl 3 +} + +/** + * Per-drawable dynamic flags (`csmDynamicDrawableFlags`), a `u8` bitmask of per-frame state. Not + * stored in the file (computed by the runtime), recorded here for completeness of the public model. + */ +public object DynamicFlag { + public const val IS_VISIBLE: Int = 1 shl 0 + public const val VISIBILITY_DID_CHANGE: Int = 1 shl 1 + public const val OPACITY_DID_CHANGE: Int = 1 shl 2 + public const val DRAW_ORDER_DID_CHANGE: Int = 1 shl 3 + public const val RENDER_ORDER_DID_CHANGE: Int = 1 shl 4 + public const val VERTEX_POSITIONS_DID_CHANGE: Int = 1 shl 5 + public const val BLEND_COLOR_DID_CHANGE: Int = 1 shl 6 +} + +/** + * Parameter kind (`SEC_PARAM_TYPE`, section index 114; present from MOC3 v4 / `Parameter.Types`). + * + * @see MOC3.md + */ +public enum class ParameterType(public val number: Int) { + /** A normal scalar parameter. */ + NORMAL(0), + + /** A blend-shape parameter (drives additive keyform deltas). */ + BLEND_SHAPE(1), + ; + + public companion object { + /** + * Resolves a stored type number to a [ParameterType]. + * + * @param Int number The i32 type code. + * @return ParameterType The matching kind. + */ + public fun fromNumber(number: Int): ParameterType = + entries.firstOrNull { it.number == number } + ?: throw IllegalArgumentException("unknown parameter type: $number") + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocCodec.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocCodec.kt new file mode 100644 index 0000000..799d8cc --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocCodec.kt @@ -0,0 +1,91 @@ +package org.umamo.format.moc3.moc + +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.io.LittleEndianWriter + +/** + * Reads and writes the `.moc3` binary container. + * + * A `.moc3` is a 64-byte header, a section-offset table at `0x40`, then the sections the table + * points at (each 16-byte-or-coarser aligned, the data region beginning at + * [Sections.DATA_SECTION_BEGIN]). The exporter appends sections sequentially and pads the file + * to a multiple of 64, so the sections partition `[firstOffset, EOF)` in table order. We keep + * every section verbatim, so [write] reproduces an unedited file byte-for-byte. + * + * @see MOC3.md + */ +public object MocCodec { + private const val HEADER_SIZE: Int = 64 + private val MAGIC: ByteArray = byteArrayOf(0x4D, 0x4F, 0x43, 0x33) // "MOC3" + + /** + * True if [bytes] starts with the `MOC3` magic and is at least header-sized. + * + * @param ByteArray bytes Candidate file contents. + * @return Boolean Whether this looks like a `.moc3`. + */ + public fun isMoc3(bytes: ByteArray): Boolean = + // MOC3 header: magic "MOC3" @ +0x00 + bytes.size >= HEADER_SIZE && bytes[0] == MAGIC[0] && bytes[1] == MAGIC[1] && bytes[2] == MAGIC[2] && bytes[3] == MAGIC[3] + + /** + * Parses a `.moc3` from raw bytes. + * + * @param ByteArray bytes The file contents. + * @return MocModel The parsed header, offset table, and section bytes. + * @throws IllegalArgumentException if the magic, version, or structure is invalid. + */ + public fun read(bytes: ByteArray): MocModel { + require(isMoc3(bytes)) { "Not a moc3: bad magic or too small" } + val versionByte = bytes[4].toInt() and 0xFF // MOC3 header: version @ +0x04 + require(versionByte in 1..MocVersion.LATEST) { "Unsupported moc3 version byte: $versionByte" } + + // MOC3 offset table @ +0x40: dense run of u32 file offsets, terminated by zero padding. + // (Editor output never has interior zero offsets; a 0 marks the start of the pad to the data + // region.) + val reader = LittleEndianReader(bytes) + reader.seek(0x40) + val offsets = ArrayList() + while (reader.position + 4 <= bytes.size) { + val value = reader.readU32() + if (value == 0L) { + break + } + offsets.add(value.toInt()) + } + require(offsets.isNotEmpty()) { "moc3 has no sections" } + + val sectionCount = offsets.size + val sections = + Array(sectionCount) { sectionIndex -> + val start = offsets[sectionIndex] + val end = if (sectionIndex + 1 < sectionCount) offsets[sectionIndex + 1] else bytes.size + require(start in HEADER_SIZE..bytes.size && end in start..bytes.size) { + "section $sectionIndex offset out of range: [$start, $end) in ${bytes.size}" + } + bytes.copyOfRange(start, end) + } + return MocModel(bytes.copyOfRange(0, HEADER_SIZE), offsets.toIntArray(), sections) + } + + /** + * Serializes a [MocModel] back to `.moc3` bytes. + * Byte-identical to the source for an unedited model. + * + * @param MocModel model The model to write. + * @return ByteArray The complete `.moc3` file bytes. + */ + public fun write(model: MocModel): ByteArray { + val firstOffset = model.offsets[0] + val tableEnd = HEADER_SIZE + model.offsets.size * 4 + require(firstOffset >= tableEnd) { "Offset table ($tableEnd B) overruns the first section ($firstOffset)" } + + val total = firstOffset + model.rawSections.sumOf { it.size } + val writer = LittleEndianWriter(total) + writer.writeBytes(model.header) // 64-byte header (magic, version, endian flag, reserved) + for (offset in model.offsets) writer.writeInt32(offset) + writer.zeroPad(firstOffset - writer.position) // pad header+table region up to the data region + for (section in model.rawSections) writer.writeBytes(section) + return writer.toByteArray() + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocModel.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocModel.kt new file mode 100644 index 0000000..4955fe3 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocModel.kt @@ -0,0 +1,232 @@ +package org.umamo.format.moc3.moc + +import org.umamo.format.moc3.io.LittleEndianReader + +/** Canvas dimensions and origin (section [Section.CANVAS], `f32[6]`). Pixel units. */ +public data class CanvasInfo( + val pixelsPerUnit: Float, + val originX: Float, + val originY: Float, + val width: Float, + val height: Float, +) + +/** + * A model parameter (slider). [type] is null on MOC3 versions without `Parameter.Types` (< 4). + * [repeats] is the Cubism 5.3+ "Parameter repeat flags" (section 54): true wraps the value into + * `[minimumValue, maximumValue)` instead of clamping. + */ +public data class MocParameter( + val id: String, + val minimumValue: Float, + val maximumValue: Float, + val defaultValue: Float, + val type: ParameterType?, + val repeats: Boolean = false, +) + +/** A part (visibility/draw-order group). [parentPartIndex] is -1 when the part is at the root. */ +public data class MocPart( + val id: String, + val parentPartIndex: Int, +) + +/** A drawable (ArtMesh). [constantFlags] is the [ConstantFlag] bitmask. */ +public data class MocDrawable( + val id: String, + val textureIndex: Int, + val constantFlags: Int, + val vertexCount: Int, + val indexCount: Int, + val maskCount: Int, + val parentPartIndex: Int, +) + +/** + * A parsed `.moc3`: the 64-byte header, the section-offset table, and each section's raw bytes. + * + * The model retains every section verbatim (the slice `[offset[k], offset[k+1])`, last → EOF, + * including padding) so [org.umamo.format.moc3.moc.MocCodec.write] reproduces an unedited file + * byte identical. A handful of structural sections (counts, canvas, IDs, parameters, parts, + * drawables) are exposed here as typed accessors for callers that need only the shape of a model; + * every section, deformation payload included, is reachable typed through [sections]. + * + * @see MOC3.md + */ +public class MocModel internal constructor( + /** The 64-byte file header `[0, 0x40)`, preserved verbatim. */ + public val header: ByteArray, + /** Absolute file offset of each section, in table order (length == section count). */ + public val offsets: IntArray, + /** Raw bytes of each section, in table order; section k == original `[offsets[k], offsets[k+1])`. */ + internal val rawSections: Array, +) { + /** Typed Layer-1 access to the deformation sections (deformers, keyforms, glue, colors, …). */ + public val sections: MocSections by lazy { MocSections(this) } + + /** The raw version byte at offset 0x04. */ + public val versionByte: Int get() = header[4].toInt() and 0xFF // MOC3 header: version @ +0x04 + + /** The typed format version. */ + public val version: MocVersion get() = MocVersion.fromByte(versionByte) + + /** Whether the file declares big-endian byte order (offset 0x05); false for every shipped file. */ + public val isBigEndian: Boolean get() = header[5].toInt() != 0 // MOC3 header: endian flag @ +0x05 + + /** Number of sections present in the offset table. */ + public val sectionCount: Int get() = offsets.size + + /** + * Returns the raw bytes of section [index] (including its trailing padding), or null if absent. + * + * @param Int index A section-table index (a [Section]'s [Section.indexIn] for this version). + * @return ByteArray? The section bytes, or null when the section is not present. + */ + public fun section(index: Int): ByteArray? = rawSections.getOrNull(index) + + /** + * The CountInfo block (section 0) decoded as a `u32[]` (indexable with `Sections.CI_*`). + * + * Read by raw index rather than through [sections], because every `PER_*` sizing rule in + * [MocSections] reads THIS - routing it back through the typed accessor would be circular. + */ + public val countInfo: IntArray by lazy { + val raw = section(Section.COUNT_INFO.indexIn(version)) ?: return@lazy IntArray(0) + val reader = LittleEndianReader(raw) + IntArray(raw.size / 4) { reader.readInt32() } + } + + /** + * Reads one count from the CountInfo block, defaulting to 0 when the index is absent. + * + * @param Int index A `Sections.CI_*` field index into [countInfo]. + * @return Int The count, or 0 when out of range. + */ + private fun count(index: Int): Int = countInfo.getOrElse(index) { 0 } + + /** Number of parts. */ + public val partCount: Int get() = count(Sections.CI_PARTS) + + /** Number of drawables (ArtMeshes). */ + public val drawableCount: Int get() = count(Sections.CI_DRAWABLES) + + /** Number of parameters. */ + public val parameterCount: Int get() = count(Sections.CI_PARAMETERS) + + /** Number of deformers (warp + rotation). */ + public val deformerCount: Int get() = count(Sections.CI_DEFORMERS) + + /** Number of glue (affecter) entries. */ + public val glueCount: Int get() = count(Sections.CI_GLUES) + + /** The canvas dimensions/origin, or null if the canvas section is absent. */ + public val canvasInfo: CanvasInfo? by lazy { + // The file stores f32[6]; the sixth is a trailing zero the model does not carry. + val values = sections.floatArray(Section.CANVAS) + if (values.size < 5) { + return@lazy null + } + CanvasInfo( + pixelsPerUnit = values[0], + originX = values[1], + originY = values[2], + width = values[3], + height = values[4], + ) + } + + // The three accessors below pad a short or absent section out to [elementCount] rather than + // returning what the file happens to hold. The callers index positionally by object, so a + // stripped or truncated section must read as zeros/blanks instead of throwing - the same + // defensive contract MocDecoder relies on for the object blocks' common heads. + + /** + * Reads [section] as a packed `i32[elementCount]`, zero-filling anything the file omits. + * + * @param Section section An I32 section. + * @param Int elementCount Number of 32-bit integers the caller will index. + * @return IntArray The decoded values (length == [elementCount]). + */ + private fun ints(section: Section, elementCount: Int): IntArray { + val decoded = sections.intArray(section) + return if (decoded.size == elementCount) decoded else decoded.copyOf(elementCount) + } + + /** + * Reads [section] as a packed `f32[elementCount]`, zero-filling anything the file omits. + * + * @param Section section An F32 section. + * @param Int elementCount Number of 32-bit floats the caller will index. + * @return FloatArray The decoded values (length == [elementCount]). + */ + private fun floats(section: Section, elementCount: Int): FloatArray { + val decoded = sections.floatArray(section) + return if (decoded.size == elementCount) decoded else decoded.copyOf(elementCount) + } + + /** + * Reads [section] as [elementCount] fixed-width ID records, blank-filling anything the file omits. + * + * @param Section section An ID section. + * @param Int elementCount Number of ID records the caller will index. + * @return List The decoded IDs (length == [elementCount]). + */ + private fun idStrings(section: Section, elementCount: Int): List { + val decoded = sections.idArray(section) + return if (decoded.size == elementCount) decoded else List(elementCount) { decoded.getOrElse(it) { "" } } + } + + /** The parameters, in file order. */ + public fun parameters(): List { + val parameterCount = parameterCount + val ids = idStrings(Section.PARAM_ID, parameterCount) + val maxima = floats(Section.PARAM_MAX, parameterCount) + val minima = floats(Section.PARAM_MIN, parameterCount) + val defaults = floats(Section.PARAM_DEFAULT, parameterCount) + val repeats = ints(Section.PARAM_REPEAT, parameterCount) + // Absent before moc 4, so a null types array means "every parameter is normal". + val types = if (sections.isPresent(Section.PARAM_TYPE)) ints(Section.PARAM_TYPE, parameterCount) else null + return List(parameterCount) { parameterIndex -> + MocParameter( + ids[parameterIndex], + minima[parameterIndex], + maxima[parameterIndex], + defaults[parameterIndex], + types?.let { ParameterType.fromNumber(it[parameterIndex]) }, + repeats[parameterIndex] != 0, + ) + } + } + + /** The parts, in file order. */ + public fun parts(): List { + val partCount = partCount + val ids = idStrings(Section.PART_ID, partCount) + val parents = ints(Section.PART_PARENT, partCount) + return List(partCount) { partIndex -> MocPart(ids[partIndex], parents[partIndex]) } + } + + /** The drawables (ArtMeshes), in file order. */ + public fun drawables(): List { + val drawableCount = drawableCount + val ids = idStrings(Section.ARTMESH_ID, drawableCount) + val textures = ints(Section.ARTMESH_TEXTURE, drawableCount) + val vertexCounts = ints(Section.ARTMESH_VERTEX_COUNT, drawableCount) + val indexCounts = ints(Section.ARTMESH_INDEX_COUNT, drawableCount) + val maskCounts = ints(Section.ARTMESH_MASK_COUNT, drawableCount) + val parents = ints(Section.ARTMESH_PARENT_PART, drawableCount) + // One byte per drawable, not an i32; byteArray already pads to the drawable count. + val flagsRaw = sections.byteArray(Section.ARTMESH_CONSTANT_FLAGS) + return List(drawableCount) { drawableIndex -> + MocDrawable( + id = ids[drawableIndex], + textureIndex = textures[drawableIndex], + constantFlags = (flagsRaw.getOrNull(drawableIndex)?.toInt() ?: 0) and 0xFF, + vertexCount = vertexCounts[drawableIndex], + indexCount = indexCounts[drawableIndex], + maskCount = maskCounts[drawableIndex], + parentPartIndex = parents[drawableIndex], + ) + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocSections.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocSections.kt new file mode 100644 index 0000000..07ee660 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocSections.kt @@ -0,0 +1,198 @@ +package org.umamo.format.moc3.moc + +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.io.LittleEndianWriter + +/** + * Typed read access to every [Section] of a [MocModel] (the "Layer-1" view): each section as a flat + * array of its element type, sized per its [Sizing] rule. + * + * Per-object sections (`PER_*`) are read for their CountInfo count, capped at what the slice holds + * (see [elementCount]); `TABLE` sections are read across the whole section slice (lossless - + * trailing padding becomes trailing zero elements the semantic layer never dereferences). Reading + * is non-destructive; the container's byte-identical write is unaffected. + * + * @see MOC3.md + */ +public class MocSections internal constructor(private val model: MocModel) { + private val version: MocVersion = model.version + + /** + * The element count for a section with the given [sizing] rule (its CountInfo field), or -1 for a + * [Sizing.TABLE] section (whose count comes from the slice size, not CountInfo). + * + * @param Sizing sizing The section's sizing rule. + * @return Int The per-object count, or -1 for table sections. + */ + private fun count(sizing: Sizing): Int = + when (sizing) { + Sizing.PER_PART -> ci(Sections.CI_PARTS) + Sizing.PER_DEFORMER -> ci(Sections.CI_DEFORMERS) + Sizing.PER_WARP -> ci(Sections.CI_WARPS) + Sizing.PER_ROTATION -> ci(Sections.CI_ROTATIONS) + Sizing.PER_DRAWABLE -> ci(Sections.CI_DRAWABLES) + Sizing.PER_PARAMETER -> ci(Sections.CI_PARAMETERS) + Sizing.PER_GLUE -> ci(Sections.CI_GLUES) + Sizing.PER_RENDER_ORDER_GROUP -> ci(Sections.CI_RENDER_ORDER_GROUPS) + Sizing.PER_RENDER_ORDER_CHILD -> ci(Sections.CI_RENDER_ORDER_CHILDREN) + Sizing.PER_OFFSCREEN -> ci(Sections.CI_OFFSCREENS) + Sizing.PER_BLENDSHAPE_WARP -> ci(Sections.CI_BLENDSHAPE_WARPS) + Sizing.PER_BLENDSHAPE_MESH -> ci(Sections.CI_BLENDSHAPE_MESHES) + Sizing.PER_BLENDSHAPE_ROTATION -> ci(Sections.CI_BLENDSHAPE_ROTATIONS) + Sizing.PER_BLENDSHAPE_PART -> ci(Sections.CI_BLENDSHAPE_PARTS) + Sizing.PER_BLENDSHAPE_GLUE -> ci(Sections.CI_BLENDSHAPE_GLUES) + Sizing.PER_PART_FORM -> ci(Sections.CI_PART_FORMS) + Sizing.PER_WARP_FORM -> ci(Sections.CI_WARP_FORMS) + Sizing.PER_ROTATION_FORM -> ci(Sections.CI_ROTATION_FORMS) + Sizing.PER_ARTMESH_FORM -> ci(Sections.CI_ARTMESH_FORMS) + Sizing.PER_OFFSCREEN_FORM -> ci(Sections.CI_OFFSCREEN_KEYFORMS) + Sizing.TABLE -> -1 + } + + /** + * Reads CountInfo field [index], defaulting to 0 when absent. + * + * @param Int index A `Sections.CI_*` CountInfo field index. + * @return Int The count, or 0 when out of range. + */ + private fun ci(index: Int): Int = model.countInfo.getOrElse(index) { 0 } + + /** + * The raw section slice backing [section] for this model's version, or null when the section is + * absent (version-gated out) or empty. + * + * @param Section section The section to locate. + * @return ByteArray? The section bytes, or null. + */ + private fun rawSlice(section: Section): ByteArray? { + val index = section.indexIn(version) + if (index < 0) { + return null + } + // A zero-length section carries no data; treat it as absent so PER_* reads don't run past it + // (a bake emits empty slots for sections it omits, e.g. blend shapes on a stripped model). + return model.section(index)?.takeIf { it.isNotEmpty() } + } + + /** Whether [section] is present in this model's version and has a section slice. */ + public fun isPresent(section: Section): Boolean = rawSlice(section) != null + + /** + * Number of elements [section] decodes to (CountInfo count, or whole-slice count for tables). + * + * A per-object count is clamped to what the slice can actually hold. CountInfo and the + * section bytes are independent on disk, so a stripped or truncated file can claim more + * objects than it stores; reading the claim would run off the end of the slice and fail the + * whole decode, which [org.umamo.format.moc3.decode.MocDecoder] promises not to do for an + * absent or partial id/flag section. Clamping yields a short array instead, which every + * caller already tolerates (they index through `getOrElse`). + * + * @param Section section The section to size. + * @return Int The element count, 0 when the section is absent. + */ + public fun elementCount(section: Section): Int { + val slice = rawSlice(section) ?: return 0 + val sliceCapacity = slice.size / section.element.size + return if (section.sizing == Sizing.TABLE) sliceCapacity else minOf(count(section.sizing), sliceCapacity) + } + + /** + * Reads [section] as an [IntArray] (for I32/U32 sections). + * + * @param Section section A section whose element type is I32 or U32. + * @return IntArray The decoded values (empty if the section is absent). + */ + public fun intArray(section: Section): IntArray { + require(section.element == ElementType.I32 || section.element == ElementType.U32) { "$section is not an int section" } + val slice = rawSlice(section) ?: return IntArray(0) + val reader = LittleEndianReader(slice) + return IntArray(elementCount(section)) { reader.readInt32() } + } + + /** + * Reads [section] as a [FloatArray] (for F32 sections). + * + * @param Section section A section whose element type is F32. + * @return FloatArray The decoded values (empty if the section is absent). + */ + public fun floatArray(section: Section): FloatArray { + require(section.element == ElementType.F32) { "$section is not a float section" } + val slice = rawSlice(section) ?: return FloatArray(0) + val reader = LittleEndianReader(slice) + return FloatArray(elementCount(section)) { reader.readFloat32() } + } + + /** + * Reads [section] as a [ShortArray] (for I16 sections, e.g. glue vertex indices). + * + * @param Section section A section whose element type is I16. + * @return ShortArray The decoded values (empty if the section is absent). + */ + public fun shortArray(section: Section): ShortArray { + require(section.element == ElementType.I16) { "$section is not an i16 section" } + val slice = rawSlice(section) ?: return ShortArray(0) + val reader = LittleEndianReader(slice) + return ShortArray(elementCount(section)) { reader.readU16().toShort() } + } + + /** + * Reads [section] as a [ByteArray] (for U8 sections, e.g. flag bytes). + * + * @param Section section A section whose element type is U8. + * @return ByteArray The decoded bytes (empty if the section is absent). + */ + public fun byteArray(section: Section): ByteArray { + require(section.element == ElementType.U8) { "$section is not a u8 section" } + val slice = rawSlice(section) ?: return ByteArray(0) + return slice.copyOf(elementCount(section)) + } + + /** + * Reads [section] as fixed-width ID records (for ID sections, e.g. deformer ids). + * + * @param Section section A section whose element type is ID. + * @return List The decoded identifiers (empty if the section is absent). + */ + public fun idArray(section: Section): List { + require(section.element == ElementType.ID) { "$section is not an id section" } + val slice = rawSlice(section) ?: return emptyList() + val reader = LittleEndianReader(slice) + // One source of truth for the record width: ElementType.ID.size IS the id stride, and sizing the + // walk from anything else lets the two drift and silently misread every id after the first. + return List(elementCount(section)) { reader.readFixedString(section.element.size) } + } + + /** + * Re-serializes [section]'s element region (the real elements, excluding trailing padding). + * Used to validate that the typed decode is lossless against the original bytes. + * + * @param Section section The section to re-encode. + * @return ByteArray The element-region bytes. + */ + public fun reencodeElementRegion(section: Section): ByteArray { + val elementCount = elementCount(section) + val writer = LittleEndianWriter(elementCount * section.element.size + 8) + when (section.element) { + ElementType.I32, ElementType.U32 -> intArray(section).forEach(writer::writeInt32) + ElementType.F32 -> floatArray(section).forEach(writer::writeFloat32) + ElementType.I16 -> shortArray(section).forEach { shortValue -> writer.writeU16(shortValue.toInt()) } + ElementType.U8 -> writer.writeBytes(byteArray(section)) + // Re-encoded from the decoded strings, so this genuinely exercises the id-record walk and the + // NUL-terminate-then-zero-pad convention rather than comparing raw bytes to themselves. Every + // id record in the corpus pads cleanly with zeros after its terminator, which is what makes the + // round trip byte-exact; a file that padded with garbage would fail here, and should. + ElementType.ID -> + idArray(section).forEach { identifier -> + writer.writeFixedString(identifier, section.element.size) + } + // A runtime slot is opaque (zero on disk, filled after the memory-cast), so there is no typed + // decode to re-serialize from and its element region round-trips as raw bytes. + ElementType.U64 -> writer.writeBytes(rawElementRegion(section)) + } + return writer.toByteArray() + } + + /** The element-region bytes straight from the file (first `elementCount × element.size` bytes). */ + public fun rawElementRegion(section: Section): ByteArray = + rawSlice(section)?.copyOf(elementCount(section) * section.element.size) ?: ByteArray(0) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocVersion.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocVersion.kt new file mode 100644 index 0000000..3a74c38 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/MocVersion.kt @@ -0,0 +1,59 @@ +package org.umamo.format.moc3.moc + +import org.umamo.format.FormatVersion + +/** + * The `.moc3` format version, stored as a single byte at file offset `0x04`. + * + * The byte (1..6) gates which sections are present; each value corresponds to a Cubism editor + * release. Newer versions only add sections at higher table indices, so a reader for a high + * version transparently reads lower ones. + * + * @see MOC3.md §version gating + */ +public enum class MocVersion(public val byteValue: Int, public val editorRange: String) : FormatVersion { + /** MOC3 v1 - Cubism 3.0-3.2 (base section set). */ + V30(1, "3.0-3.2"), + + /** MOC3 v2 - Cubism 3.3. */ + V33(2, "3.3"), + + /** MOC3 v3 - Cubism 4.0. */ + V40(3, "4.0"), + + /** MOC3 v4 - Cubism 4.2 (+ warp/rotation deformer color, `Parameter.Types`, art-mesh/warp blend shapes). */ + V42(4, "4.2"), + + /** MOC3 v5 - Cubism 5.0 (+ per-form color rows; blend shapes on parts and rotation deformers). */ + V50(5, "5.0"), + + /** MOC3 v6 - Cubism 5.3 (+ offscreen rendering). */ + V53(6, "5.3"), + ; + + /** Short token combining the version byte and the editor releases that write it. */ + override val label: String get() = "moc3 v$byteValue / Cubism $editorRange" + + /** + * Human-readable support summary. + * + * @return String The summary sentence. + */ + override fun describe(): String = "Supported: $label" + + public companion object { + /** The highest version byte understood here (matches the runtime core's latest). */ + public const val LATEST: Int = 6 + + /** + * Resolves a raw version byte to a [MocVersion]. + * + * @param Int byte The version byte from file offset 0x04. + * @return MocVersion The matching version. + * @throws IllegalArgumentException if the byte is outside 1..6. + */ + public fun fromByte(byte: Int): MocVersion = + entries.firstOrNull { it.byteValue == byte } + ?: throw IllegalArgumentException("unsupported moc3 version byte: $byte") + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/SectionLayout.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/SectionLayout.kt new file mode 100644 index 0000000..05f4d44 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/SectionLayout.kt @@ -0,0 +1,527 @@ +package org.umamo.format.moc3.moc + +/** Element width of a section's array. */ +public enum class ElementType(public val size: Int) { + /** unsigned 8-bit (flag bytes). */ + U8(1), + + /** signed 16-bit (glue vertex indices). */ + I16(2), + + /** signed 32-bit. */ + I32(4), + + /** unsigned 32-bit (CountInfo). */ + U32(4), + + /** unsigned 64-bit (the per-object runtime slots, zero on disk). */ + U64(8), + + /** IEEE-754 32-bit float. */ + F32(4), + + /** fixed 64-byte NUL-terminated ID record. */ + ID(64), +} + +/** + * How a section's element count is determined. + * + * Per-object arrays are sized by a CountInfo count; "table" arrays (keyform values, key + * positions, glue pairs, …) have no single count field and are read across the whole section + * slice (the runtime indexes them via base/offset tables, not a length). Reading the full slice + * is lossless - trailing zero padding becomes trailing zero elements that the semantic layer + * never dereferences. + */ +public enum class Sizing { + PER_PART, + PER_DEFORMER, + PER_WARP, + PER_ROTATION, + PER_DRAWABLE, + PER_PARAMETER, + PER_GLUE, + PER_RENDER_ORDER_GROUP, + PER_RENDER_ORDER_CHILD, + PER_OFFSCREEN, + PER_BLENDSHAPE_WARP, + PER_BLENDSHAPE_MESH, + PER_BLENDSHAPE_ROTATION, + PER_BLENDSHAPE_PART, + PER_BLENDSHAPE_GLUE, + + // One entry per KEYFORM of the object kind, not per object: the flat form arrays each object + // indexes into through its keyform base. Sized by CountInfo 6-9 and 36 respectively. + PER_PART_FORM, + PER_WARP_FORM, + PER_ROTATION_FORM, + PER_ARTMESH_FORM, + PER_OFFSCREEN_FORM, + + /** Read across the whole section slice (a table indexed elsewhere). */ + TABLE, +} + +/** + * EVERY section of a `.moc3`, with its element type, sizing rule, and section-table index per moc + * version - the single registry the decoder, the lowering, and the lossless gate all read. + * + * The per-version indices are on-disk facts (which table slot holds which data, recovered from the + * runtime). `index[version-1]` gives the slot; `-1` means the section is absent in that version. + * + * Completeness is enforced, not aspirational: `SectionRegistryTest` asserts that every slot each + * version's table defines has exactly one entry here, that no two entries claim a slot, and that an + * index never moves once introduced. That matters because a section modeled nowhere can only be + * carried verbatim from a reference container - which is precisely what stops a document being baked + * from scratch. + * + * @see MOC3.md §section map + */ +public enum class Section( + public val element: ElementType, + public val sizing: Sizing, + private vararg val indexByVersion: Int, // [v1,v2,v3,v4,v5,v6]; -1 = absent +) { + // --- global --- + + /** The object-count array itself (section 0); every `PER_*` sizing rule reads its fields. */ + COUNT_INFO(ElementType.U32, Sizing.TABLE, 0, 0, 0, 0, 0, 0), + + /** Canvas `f32[6]`: pixels-per-unit, origin x/y, width, height, and a trailing zero. */ + CANVAS(ElementType.F32, Sizing.TABLE, 1, 1, 1, 1, 1, 1), + + // --- deformers (unified list) --- + + /** + * Per-deformer 8-byte runtime slot, the block's leading field. Zero in every corpus file (the + * runtime fills it after the memory-cast), so it carries no authored data - it is modeled only so + * a bake sizes it to the deformer count instead of carrying a stale array from the source file. + * Every object block opens with the same slot: parts 2, art meshes 29, parameters 49, glues 89, + * offscreens 154. All are corpus-verified all-zero (UnmodeledSectionIdentityProbeTest). + */ + DEFORMER_RUNTIME_SLOT(ElementType.U64, Sizing.PER_DEFORMER, 10, 10, 10, 10, 10, 10), + + /** Per-deformer authored id (e.g. "Warp349", "B_LEG_01"), unique within the model. */ + DEFORMER_ID(ElementType.ID, Sizing.PER_DEFORMER, 11, 11, 11, 11, 11, 11), + + /** + * Per-deformer keyform-binding index, in unified deformer order. Duplicates the per-type + * [WARP_KEYFORM_BINDING] / [ROTATION_KEYFORM_BINDING] value for the same deformer (corpus-verified + * identical); both are written because the runtime addresses each by a different path. + */ + DEFORMER_KEYFORM_BINDING(ElementType.I32, Sizing.PER_DEFORMER, 12, 12, 12, 12, 12, 12), + + /** + * Per-deformer visibility flag (`0`/`1`), the editor's eye toggle. The only deformer flag that + * ever deviates from 1 on the corpus. See [DEFORMER_IS_ENABLED] for the pairing caveat. + */ + DEFORMER_IS_VISIBLE(ElementType.I32, Sizing.PER_DEFORMER, 13, 13, 13, 13, 13, 13), + + /** + * Per-deformer second flag, `1` on every deformer of every corpus model - so it is not the + * visibility toggle; [DEFORMER_IS_VISIBLE] is. + * + * That split is an inference rather than a join result. The art-mesh pair (37/38) has the same + * shape and WAS pinned by joining miku_verycursed against its CMO3 twin, and the only deformer + * deviation anywhere (Azxiana, 7 of 623) sits in the first column exactly as the art-mesh + * deviations do - but Azxiana has no twin, so nothing proves it directly. + */ + DEFORMER_IS_ENABLED(ElementType.I32, Sizing.PER_DEFORMER, 14, 14, 14, 14, 14, 14), + + /** Per-deformer owning part (the organizational tree), -1 at the root. */ + DEFORMER_PARENT_PART(ElementType.I32, Sizing.PER_DEFORMER, 15, 15, 15, 15, 15, 15), + DEFORMER_PARENT(ElementType.I32, Sizing.PER_DEFORMER, 16, 16, 16, 16, 16, 16), + DEFORMER_TYPE(ElementType.I32, Sizing.PER_DEFORMER, 17, 17, 17, 17, 17, 17), + + /** Per-deformer 0-based index within its type group (warps vs rotations), in deformer-list order. */ + DEFORMER_LOCAL_INDEX(ElementType.I32, Sizing.PER_DEFORMER, 18, 18, 18, 18, 18, 18), + + // --- warp deformers --- + WARP_KEYFORM_BINDING(ElementType.I32, Sizing.PER_WARP, 19, 19, 19, 19, 19, 19), + WARP_KEYFORM_BASE(ElementType.I32, Sizing.PER_WARP, 20, 20, 20, 20, 20, 20), + + /** Per-warp keyform count (its binding's grid size); the run length starting at [WARP_KEYFORM_BASE]. */ + WARP_KEYFORM_COUNT(ElementType.I32, Sizing.PER_WARP, 21, 21, 21, 21, 21, 21), + + /** Per-warp control-point count `(rows+1)·(columns+1)` (the runtime validates it against rows/cols). */ + WARP_CONTROL_POINT_COUNT(ElementType.I32, Sizing.PER_WARP, 22, 22, 22, 22, 22, 22), + WARP_ROWS(ElementType.I32, Sizing.PER_WARP, 23, 23, 23, 23, 23, 23), + WARP_COLUMNS(ElementType.I32, Sizing.PER_WARP, 24, 24, 24, 24, 24, 24), + + /** + * Warp interpolation mode (0 = triangle split, non-zero = bilinear quad). + * + * Gated from MOC3 v2 (Cubism 3.3), which is where slot 101 first exists at all - + * [org.umamo.format.moc3.encode.MocEncoder.sectionCount] gives v1 101 slots and v2 102. A v3 gate + * would leave v2's slot 101 modeled by nothing, which + * `SectionRegistryTest.everyTableSlotIsModeledForEveryVersion` rejects. UNVERIFIED against a + * sample: the corpus has no v2 file (v1, v3, v4, v5, v6 only), so this rests on the two agreeing + * sources rather than on bytes. Harmless if wrong - an absent section reads as absent. + */ + WARP_MODE(ElementType.I32, Sizing.PER_WARP, -1, 101, 101, 101, 101, 101), + WARP_COLOR_BASE(ElementType.I32, Sizing.PER_WARP, -1, -1, -1, 105, 105, 105), + WARP_OPACITY(ElementType.F32, Sizing.TABLE, 59, 59, 59, 59, 59, 59), + + /** Keyform → packed-position offset table for warps/rotations (distinct from art meshes' [KEYFORM_POSITION_INDEX]). */ + WARP_KEYFORM_INDEX(ElementType.I32, Sizing.TABLE, 60, 60, 60, 60, 60, 60), + + /** + * Per-warp-keyform multiply / screen color row refs (moc 5+), each `colorBase[warp] + gridIndex`. + * The two arrays are BIT-IDENTICAL on every corpus sample, the same shape the offscreen keyform + * rows (162/163) have - so both are derivable and neither carries independent data. + */ + WARP_FORM_MULTIPLY_ROW(ElementType.I32, Sizing.PER_WARP_FORM, -1, -1, -1, -1, 137, 137), + WARP_FORM_SCREEN_ROW(ElementType.I32, Sizing.PER_WARP_FORM, -1, -1, -1, -1, 138, 138), + + // --- rotation deformers --- + ROTATION_KEYFORM_BINDING(ElementType.I32, Sizing.PER_ROTATION, 25, 25, 25, 25, 25, 25), + ROTATION_KEYFORM_BASE(ElementType.I32, Sizing.PER_ROTATION, 26, 26, 26, 26, 26, 26), + + /** Per-rotation keyform count (its binding's grid size). */ + ROTATION_KEYFORM_COUNT(ElementType.I32, Sizing.PER_ROTATION, 27, 27, 27, 27, 27, 27), + + /** Per-rotation-keyform color row refs (moc 5+); see [WARP_FORM_MULTIPLY_ROW]. */ + ROTATION_FORM_MULTIPLY_ROW(ElementType.I32, Sizing.PER_ROTATION_FORM, -1, -1, -1, -1, 139, 139), + ROTATION_FORM_SCREEN_ROW(ElementType.I32, Sizing.PER_ROTATION_FORM, -1, -1, -1, -1, 140, 140), + ROTATION_COLOR_BASE(ElementType.I32, Sizing.PER_ROTATION, -1, -1, -1, 106, 106, 106), + ROTATION_BASE_ANGLE(ElementType.F32, Sizing.PER_ROTATION, 28, 28, 28, 28, 28, 28), + ROTATION_OPACITY(ElementType.F32, Sizing.TABLE, 61, 61, 61, 61, 61, 61), + ROTATION_ANGLE(ElementType.F32, Sizing.TABLE, 62, 62, 62, 62, 62, 62), + ROTATION_ORIGIN_X(ElementType.F32, Sizing.TABLE, 63, 63, 63, 63, 63, 63), + ROTATION_ORIGIN_Y(ElementType.F32, Sizing.TABLE, 64, 64, 64, 64, 64, 64), + ROTATION_SCALE(ElementType.F32, Sizing.TABLE, 65, 65, 65, 65, 65, 65), + ROTATION_REFLECT_X(ElementType.I32, Sizing.TABLE, 66, 66, 66, 66, 66, 66), + ROTATION_REFLECT_Y(ElementType.I32, Sizing.TABLE, 67, 67, 67, 67, 67, 67), + + // --- art meshes --- + + /** + * The art-mesh block's four leading 8-byte runtime slots (all-zero on disk, like every other + * object block's). Lina's research marks these header and unknown A, B, and C. + */ + ARTMESH_RUNTIME_SLOT(ElementType.U64, Sizing.PER_DRAWABLE, 29, 29, 29, 29, 29, 29), + ARTMESH_RUNTIME_SLOT_A(ElementType.U64, Sizing.PER_DRAWABLE, 30, 30, 30, 30, 30, 30), + ARTMESH_RUNTIME_SLOT_B(ElementType.U64, Sizing.PER_DRAWABLE, 31, 31, 31, 31, 31, 31), + ARTMESH_RUNTIME_SLOT_C(ElementType.U64, Sizing.PER_DRAWABLE, 32, 32, 32, 32, 32, 32), + + /** Per-drawable authored id, e.g. "ArtMesh42" or "D_HAIR_BACK_00". */ + ARTMESH_ID(ElementType.ID, Sizing.PER_DRAWABLE, 33, 33, 33, 33, 33, 33), + + /** + * Per-drawable visibility flag (`0`/`1`) - the editor's eye toggle, PROVEN by joining + * miku_verycursed against its CMO3 twin: it exports its hidden art meshes rather than dropping + * them, and exactly its 3 hidden meshes carry `0` here. See [ARTMESH_IS_ENABLED] for the pairing. + */ + ARTMESH_IS_VISIBLE(ElementType.I32, Sizing.PER_DRAWABLE, 37, 37, 37, 37, 37, 37), + + /** + * Per-drawable second flag, `1` on every drawable of every corpus sample - so whatever it means, it + * is not the visibility toggle ([ARTMESH_IS_VISIBLE] is). Lina's research indicates that this is + * the visibility flag, but probing indicates that it is not. + */ + ARTMESH_IS_ENABLED(ElementType.I32, Sizing.PER_DRAWABLE, 38, 38, 38, 38, 38, 38), + + /** Per-drawable owning part (the organizational tree), -1 at the root. */ + ARTMESH_PARENT_PART(ElementType.I32, Sizing.PER_DRAWABLE, 39, 39, 39, 39, 39, 39), + + /** Per-drawable texture (atlas page) index. */ + ARTMESH_TEXTURE(ElementType.I32, Sizing.PER_DRAWABLE, 41, 41, 41, 41, 41, 41), + + /** + * Per-drawable render-config bitmask - ONE BYTE per drawable, not an i32. Carries the legacy + * 2-bit blend mode, the double-sided bit, and the invert-mask bit; see + * [org.umamo.format.moc3.moc.ConstantFlag]. + */ + ARTMESH_CONSTANT_FLAGS(ElementType.U8, Sizing.PER_DRAWABLE, 42, 42, 42, 42, 42, 42), + ARTMESH_VERTEX_COUNT(ElementType.I32, Sizing.PER_DRAWABLE, 43, 43, 43, 43, 43, 43), + + /** Per-drawable start into the UV float table (section 78): the prefix sum of 2 x vertex count. */ + ARTMESH_UV_START(ElementType.I32, Sizing.PER_DRAWABLE, 44, 44, 44, 44, 44, 44), + ARTMESH_INDEX_COUNT(ElementType.I32, Sizing.PER_DRAWABLE, 46, 46, 46, 46, 46, 46), + ARTMESH_MASK_COUNT(ElementType.I32, Sizing.PER_DRAWABLE, 48, 48, 48, 48, 48, 48), + + /** Per-drawable start into the triangle-index table (section 79): the prefix sum of index count. */ + ARTMESH_INDEX_START(ElementType.I32, Sizing.PER_DRAWABLE, 45, 45, 45, 45, 45, 45), + + /** + * Per-drawable start into the mask-index table (section 80): the prefix sum of mask count, BASED at + * the offscreen mask block that precedes the drawable masks, so entry 0 is not generally zero. + */ + ARTMESH_MASK_START(ElementType.I32, Sizing.PER_DRAWABLE, 47, 47, 47, 47, 47, 47), + + /** Per-art-mesh-keyform color row refs (moc 5+); see [WARP_FORM_MULTIPLY_ROW]. */ + ARTMESH_FORM_MULTIPLY_ROW(ElementType.I32, Sizing.PER_ARTMESH_FORM, -1, -1, -1, -1, 141, 141), + ARTMESH_FORM_SCREEN_ROW(ElementType.I32, Sizing.PER_ARTMESH_FORM, -1, -1, -1, -1, 142, 142), + + // --- art-mesh deformation refs --- + ARTMESH_KEYFORM_BINDING(ElementType.I32, Sizing.PER_DRAWABLE, 34, 34, 34, 34, 34, 34), + ARTMESH_KEYFORM_BASE(ElementType.I32, Sizing.PER_DRAWABLE, 35, 35, 35, 35, 35, 35), + + /** Per-drawable keyform count (its keyform-binding grid size). */ + ARTMESH_KEYFORM_COUNT(ElementType.I32, Sizing.PER_DRAWABLE, 36, 36, 36, 36, 36, 36), + ARTMESH_COLOR_BASE(ElementType.I32, Sizing.PER_DRAWABLE, -1, -1, -1, 107, 107, 107), + ARTMESH_PARENT_DEFORMER(ElementType.I32, Sizing.PER_DRAWABLE, 40, 40, 40, 40, 40, 40), + ARTMESH_OPACITY(ElementType.F32, Sizing.TABLE, 68, 68, 68, 68, 68, 68), + ARTMESH_DRAW_ORDER(ElementType.F32, Sizing.TABLE, 69, 69, 69, 69, 69, 69), + + /** + * Per-drawable packed extended blend, colorMode | (alphaMode shl 8) - the 5.3 blend surface + * (color 0-17, alpha 0-4, same encoding as [OFFSCREEN_BLEND_MODE]). 0 = legacy blend, which + * stays in the constant-flags 2-bit field. MOC3 v6 §5.6 s153; pinned by the PartClipping bake + * (authored Screen/Out drawable stored 522 = 10 or (2 shl 8)). + */ + ARTMESH_EXTENDED_BLEND(ElementType.I32, Sizing.PER_DRAWABLE, -1, -1, -1, -1, -1, 153), + + // --- shared static geometry tables --- + + /** All drawables' UVs, concatenated as interleaved `u,v`; each indexes in at [ARTMESH_UV_START]. */ + ARTMESH_UV_DATA(ElementType.F32, Sizing.TABLE, 78, 78, 78, 78, 78, 78), + + /** All drawables' triangle indices (`u16`), concatenated; each starts at [ARTMESH_INDEX_START]. */ + ARTMESH_INDEX_DATA(ElementType.I16, Sizing.TABLE, 79, 79, 79, 79, 79, 79), + + /** + * Clipping mask references. The OFFSCREEN masks form the prefix of this table and the drawable + * masks follow, which is why [ARTMESH_MASK_START] is based rather than starting at zero. + */ + MASK_INDEX_DATA(ElementType.I32, Sizing.TABLE, 80, 80, 80, 80, 80, 80), + + // --- shared keyform value tables --- + KEYFORM_POSITION_INDEX(ElementType.I32, Sizing.TABLE, 70, 70, 70, 70, 70, 70), + KEYFORM_POSITION_VALUES(ElementType.F32, Sizing.TABLE, 71, 71, 71, 71, 71, 71), + + // --- parameters --- + + /** The parameter block's leading 8-byte runtime slot; all-zero on disk, sized only. */ + PARAM_RUNTIME_SLOT(ElementType.U64, Sizing.PER_PARAMETER, 49, 49, 49, 49, 49, 49), + + /** Per-parameter authored id, e.g. "ParamAngleX" - a format-level identifier, never localized. */ + PARAM_ID(ElementType.ID, Sizing.PER_PARAMETER, 50, 50, 50, 50, 50, 50), + + // NB: the file stores MAX before MIN. + PARAM_MAX(ElementType.F32, Sizing.PER_PARAMETER, 51, 51, 51, 51, 51, 51), + PARAM_MIN(ElementType.F32, Sizing.PER_PARAMETER, 52, 52, 52, 52, 52, 52), + PARAM_DEFAULT(ElementType.F32, Sizing.PER_PARAMETER, 53, 53, 53, 53, 53, 53), + + /** Per-parameter repeat flag: true wraps the value into `[min, max)` instead of clamping. */ + PARAM_REPEAT(ElementType.I32, Sizing.PER_PARAMETER, 54, 54, 54, 54, 54, 54), + + /** + * Per-parameter snap type. The constant `3` on every parameter of every corpus sample, v1 through + * v6, so it needs no model field - a writer emits 3. + */ + PARAM_SNAP_TYPE(ElementType.I32, Sizing.PER_PARAMETER, 55, 55, 55, 55, 55, 55), + + /** + * Per-parameter start into the binding-set pool: the running prefix sum of + * [PARAMETER_BINDING_COUNT] over parameters that HAVE bindings. A parameter with none stores + * `-1` when it is NORMAL and `0` when it is BLEND_SHAPE (`Parameter.Types`, section 114) - both + * values occur in one file, and only the parameter type separates them. + */ + PARAM_BINDING_START(ElementType.I32, Sizing.PER_PARAMETER, 56, 56, 56, 56, 56, 56), + + /** Per-parameter second 8-byte runtime slot (moc 4+); all-zero on disk, sized only. */ + PARAM_RUNTIME_SLOT_A(ElementType.U64, Sizing.PER_PARAMETER, -1, -1, -1, 102, 102, 102), + + /** + * Per-parameter start into the key-position table (moc 4+): the prefix sum of the per-parameter + * key count (section 104), BASED at the end of the preceding key region rather than at zero. + */ + PARAM_KEY_START(ElementType.I32, Sizing.PER_PARAMETER, -1, -1, -1, 103, 103, 103), + + /** Per-parameter key count, the run length starting at [PARAM_KEY_START] (moc 4+). */ + PARAM_KEY_COUNT(ElementType.I32, Sizing.PER_PARAMETER, -1, -1, -1, 104, 104, 104), + + /** Per-parameter kind (normal vs blend shape); see [ParameterType]. Absent before moc 4. */ + PARAM_TYPE(ElementType.I32, Sizing.PER_PARAMETER, -1, -1, -1, 114, 114, 114), + + // --- keyform-binding grid --- + PARAMETER_BINDING_COUNT(ElementType.I32, Sizing.PER_PARAMETER, 57, 57, 57, 57, 57, 57), + BINDING_KEY_OFFSET(ElementType.I32, Sizing.TABLE, 75, 75, 75, 75, 75, 75), + BINDING_KEY_COUNT(ElementType.I32, Sizing.TABLE, 76, 76, 76, 76, 76, 76), + KEYFORM_BINDING_SLOT(ElementType.I32, Sizing.TABLE, 72, 72, 72, 72, 72, 72), + KEYFORM_BINDING_START(ElementType.I32, Sizing.TABLE, 73, 73, 73, 73, 73, 73), + KEYFORM_BINDING_COUNT(ElementType.I32, Sizing.TABLE, 74, 74, 74, 74, 74, 74), + KEY_POSITIONS(ElementType.F32, Sizing.TABLE, 77, 77, 77, 77, 77, 77), + + // --- parts --- + + /** The part block's leading 8-byte runtime slot; all-zero on disk, sized only. */ + PART_RUNTIME_SLOT(ElementType.U64, Sizing.PER_PART, 2, 2, 2, 2, 2, 2), + + /** Per-part authored id, e.g. "PartHead". */ + PART_ID(ElementType.ID, Sizing.PER_PART, 3, 3, 3, 3, 3, 3), + PART_KEYFORM_BINDING(ElementType.I32, Sizing.PER_PART, 4, 4, 4, 4, 4, 4), + PART_KEYFORM_BASE(ElementType.I32, Sizing.PER_PART, 5, 5, 5, 5, 5, 5), + + /** Per-part keyform count (its binding's grid size). */ + PART_KEYFORM_COUNT(ElementType.I32, Sizing.PER_PART, 6, 6, 6, 6, 6, 6), + + /** + * The part's two visibility flags - read as "show my art meshes" and "show my deformers". + * Both are `1` on every part of every corpus sample and no CMO3 twin keeps a + * hidden part, so which is which is UNPINNED; nothing downstream needs the distinction, and a + * writer sets both from the part's single visibility. + */ + PART_VISIBLE_ARTMESHES(ElementType.I32, Sizing.PER_PART, 7, 7, 7, 7, 7, 7), + PART_VISIBLE_DEFORMERS(ElementType.I32, Sizing.PER_PART, 8, 8, 8, 8, 8, 8), + + /** Per-part parent in the organizational tree, -1 at the root. */ + PART_PARENT(ElementType.I32, Sizing.PER_PART, 9, 9, 9, 9, 9, 9), + PART_DRAW_ORDER(ElementType.F32, Sizing.TABLE, 58, 58, 58, 58, 58, 58), + + // --- color channel tables (v4+) --- + COLOR_MULTIPLY_R(ElementType.F32, Sizing.TABLE, -1, -1, -1, 108, 108, 108), + COLOR_MULTIPLY_G(ElementType.F32, Sizing.TABLE, -1, -1, -1, 109, 109, 109), + COLOR_MULTIPLY_B(ElementType.F32, Sizing.TABLE, -1, -1, -1, 110, 110, 110), + COLOR_SCREEN_R(ElementType.F32, Sizing.TABLE, -1, -1, -1, 111, 111, 111), + COLOR_SCREEN_G(ElementType.F32, Sizing.TABLE, -1, -1, -1, 112, 112, 112), + COLOR_SCREEN_B(ElementType.F32, Sizing.TABLE, -1, -1, -1, 113, 113, 113), + + // --- render-order group tree --- + RENDER_ORDER_CHILD_COUNT(ElementType.I32, Sizing.PER_RENDER_ORDER_GROUP, 82, 82, 82, 82, 82, 82), + + /** Per-group total render-index count (recursive: drawables + offscreen slots + sub-group totals). */ + RENDER_ORDER_GROUP_RENDER_COUNT(ElementType.I32, Sizing.PER_RENDER_ORDER_GROUP, 83, 83, 83, 83, 83, 83), + + /** Per-group maximum child draw order (drawable draw order, or a sub-group's part draw order). */ + RENDER_ORDER_GROUP_MAX_DRAW_ORDER(ElementType.I32, Sizing.PER_RENDER_ORDER_GROUP, 84, 84, 84, 84, 84, 84), + + /** Per-group minimum child draw order. */ + RENDER_ORDER_GROUP_MIN_DRAW_ORDER(ElementType.I32, Sizing.PER_RENDER_ORDER_GROUP, 85, 85, 85, 85, 85, 85), + RENDER_ORDER_CHILD_KIND(ElementType.I32, Sizing.TABLE, 86, 86, 86, 86, 86, 86), + RENDER_ORDER_CHILD_INDEX(ElementType.I32, Sizing.TABLE, 87, 87, 87, 87, 87, 87), + RENDER_ORDER_GROUP_INDEX(ElementType.I32, Sizing.TABLE, 88, 88, 88, 88, 88, 88), + + /** Per-group start into the child tables (86/87/88): the prefix sum of [RENDER_ORDER_CHILD_COUNT]. */ + RENDER_ORDER_CHILD_START(ElementType.I32, Sizing.PER_RENDER_ORDER_GROUP, 81, 81, 81, 81, 81, 81), + + // --- glue --- + + /** The glue block's leading 8-byte runtime slot; all-zero on disk, sized only. */ + GLUE_RUNTIME_SLOT(ElementType.U64, Sizing.PER_GLUE, 89, 89, 89, 89, 89, 89), + + /** Per-glue authored id, e.g. "Glue__ArtMesh48__ArtMesh49" (older bakes use "Glue_0_1_"). */ + GLUE_ID(ElementType.ID, Sizing.PER_GLUE, 90, 90, 90, 90, 90, 90), + GLUE_KEYFORM_BINDING(ElementType.I32, Sizing.PER_GLUE, 91, 91, 91, 91, 91, 91), + GLUE_KEY_OFFSET(ElementType.I32, Sizing.PER_GLUE, 92, 92, 92, 92, 92, 92), + GLUE_KEY_COUNT(ElementType.I32, Sizing.PER_GLUE, 93, 93, 93, 93, 93, 93), + GLUE_MESH_A(ElementType.I32, Sizing.PER_GLUE, 94, 94, 94, 94, 94, 94), + GLUE_MESH_B(ElementType.I32, Sizing.PER_GLUE, 95, 95, 95, 95, 95, 95), + GLUE_VERTEX_START(ElementType.I32, Sizing.PER_GLUE, 96, 96, 96, 96, 96, 96), + GLUE_VERTEX_COUNT(ElementType.I32, Sizing.PER_GLUE, 97, 97, 97, 97, 97, 97), + GLUE_WEIGHTS(ElementType.F32, Sizing.TABLE, 98, 98, 98, 98, 98, 98), + GLUE_VERTEX_INDICES(ElementType.I16, Sizing.TABLE, 99, 99, 99, 99, 99, 99), + GLUE_INTENSITIES(ElementType.F32, Sizing.TABLE, 100, 100, 100, 100, 100, 100), + + // --- blend shapes (moc 4+ positions / 5+ scalar fields) --- + BLENDSHAPE_WARP_OBJECT(ElementType.I32, Sizing.PER_BLENDSHAPE_WARP, -1, -1, -1, 125, 125, 125), + BLENDSHAPE_WARP_RECORD_START(ElementType.I32, Sizing.PER_BLENDSHAPE_WARP, -1, -1, -1, 126, 126, 126), + BLENDSHAPE_WARP_RECORD_COUNT(ElementType.I32, Sizing.PER_BLENDSHAPE_WARP, -1, -1, -1, 127, 127, 127), + BLENDSHAPE_MESH_OBJECT(ElementType.I32, Sizing.PER_BLENDSHAPE_MESH, -1, -1, -1, 128, 128, 128), + BLENDSHAPE_MESH_RECORD_START(ElementType.I32, Sizing.PER_BLENDSHAPE_MESH, -1, -1, -1, 129, 129, 129), + BLENDSHAPE_MESH_RECORD_COUNT(ElementType.I32, Sizing.PER_BLENDSHAPE_MESH, -1, -1, -1, 130, 130, 130), + + // v6 index is 146 (same as v5); the Umamo C++ Runtime's kSrcLayout maps it to the degenerate/empty slot 143. + BLENDSHAPE_ROTATION_OBJECT(ElementType.I32, Sizing.PER_BLENDSHAPE_ROTATION, -1, -1, -1, -1, 146, 146), + BLENDSHAPE_ROTATION_RECORD_START(ElementType.I32, Sizing.PER_BLENDSHAPE_ROTATION, -1, -1, -1, -1, 147, 147), + BLENDSHAPE_ROTATION_RECORD_COUNT(ElementType.I32, Sizing.PER_BLENDSHAPE_ROTATION, -1, -1, -1, -1, 148, 148), + BLENDSHAPE_RECORD_BINDING(ElementType.I32, Sizing.TABLE, -1, -1, -1, 120, 120, 120), + BLENDSHAPE_RECORD_BASE(ElementType.I32, Sizing.TABLE, -1, -1, -1, 121, 121, 121), + BLENDSHAPE_RECORD_SUBSTART(ElementType.I32, Sizing.TABLE, -1, -1, -1, 123, 123, 123), + BLENDSHAPE_RECORD_CORNER_COUNT(ElementType.I32, Sizing.TABLE, -1, -1, -1, 124, 124, 124), + + // MOC3 v4+ §5.6: redundant per-record copy of the record's binding key count (corpus-confirmed + // against Model A/Model B/Model C including v6 - see MorphTargetJoinProbeTest). + BLENDSHAPE_RECORD_KEY_COUNT(ElementType.I32, Sizing.TABLE, -1, -1, -1, 122, 122, 122), + + // MOC3 v4+ §5.6: blend-weight limit ("blend shape limit") sub-binding tables. A record's + // SUBSTART/CORNER_COUNT range into SUB_INDEX yields refs into a DEDUPLICATED sub-binding pool; + // each pool entry maps another parameter (SUB_PARAMETER) through an end-clamped piecewise-linear + // (SUB_KEYS, SUB_WEIGHT_VALUES) curve addressed by SUB_KEY_OFFSET/COUNT. The record's weight + // multiplier is the MINIMUM over its refs. v4/v5 indices confirmed against Model B/Model C (v5) and + // the C-runtime layout; the v6 column is assumed = v5 pending a v6 constraint bake (every confirmed + // blend section is index-identical v5 -> v6, incl. section 122 above). + BLENDSHAPE_SUB_INDEX(ElementType.I32, Sizing.TABLE, -1, -1, -1, 131, 131, 131), + BLENDSHAPE_SUB_PARAMETER(ElementType.I32, Sizing.TABLE, -1, -1, -1, 132, 132, 132), + BLENDSHAPE_SUB_KEY_OFFSET(ElementType.I32, Sizing.TABLE, -1, -1, -1, 133, 133, 133), + BLENDSHAPE_SUB_KEY_COUNT(ElementType.I32, Sizing.TABLE, -1, -1, -1, 134, 134, 134), + BLENDSHAPE_SUB_KEYS(ElementType.F32, Sizing.TABLE, -1, -1, -1, 135, 135, 135), + BLENDSHAPE_SUB_WEIGHT_VALUES(ElementType.F32, Sizing.TABLE, -1, -1, -1, 136, 136, 136), + + // MOC3 v5+ §5.6: part blend shapes (Model C carries one). v6 column assumed = v5 (same caveat). + BLENDSHAPE_PART_OBJECT(ElementType.I32, Sizing.PER_BLENDSHAPE_PART, -1, -1, -1, -1, 143, 143), + BLENDSHAPE_PART_RECORD_START(ElementType.I32, Sizing.PER_BLENDSHAPE_PART, -1, -1, -1, -1, 144, 144), + BLENDSHAPE_PART_RECORD_COUNT(ElementType.I32, Sizing.PER_BLENDSHAPE_PART, -1, -1, -1, -1, 145, 145), + BLENDSHAPE_BINDING_KEY_OFFSET(ElementType.I32, Sizing.TABLE, -1, -1, -1, 117, 117, 117), + BLENDSHAPE_BINDING_KEY_COUNT(ElementType.I32, Sizing.TABLE, -1, -1, -1, 118, 118, 118), + BLENDSHAPE_BINDING_NEUTRAL(ElementType.I32, Sizing.TABLE, -1, -1, -1, 119, 119, 119), + BLENDSHAPE_PARAMETER_BEGIN(ElementType.I32, Sizing.PER_PARAMETER, -1, -1, -1, 115, 115, 115), + BLENDSHAPE_PARAMETER_COUNT(ElementType.I32, Sizing.PER_PARAMETER, -1, -1, -1, 116, 116, 116), + + /** + * MOC3 v5+ §5.6: glue blend shapes, the fourth object kind alongside warp/mesh/rotation/part. + * CountInfo 34 is zero on every corpus sample, so these are modeled for completeness (and so a + * bake SIZES them) but no glue blend shape is decoded into the document - nothing exercises them. + */ + BLENDSHAPE_GLUE_OBJECT(ElementType.I32, Sizing.PER_BLENDSHAPE_GLUE, -1, -1, -1, -1, 149, 149), + BLENDSHAPE_GLUE_RECORD_START(ElementType.I32, Sizing.PER_BLENDSHAPE_GLUE, -1, -1, -1, -1, 150, 150), + BLENDSHAPE_GLUE_RECORD_COUNT(ElementType.I32, Sizing.PER_BLENDSHAPE_GLUE, -1, -1, -1, -1, 151, 151), + + // --- offscreen rendering (moc 6) --- + OFFSCREEN_OWNER_PART(ElementType.I32, Sizing.PER_OFFSCREEN, -1, -1, -1, -1, -1, 155), + OFFSCREEN_CONSTANT_FLAGS(ElementType.U8, Sizing.PER_OFFSCREEN, -1, -1, -1, -1, -1, 156), + OFFSCREEN_BLEND_MODE(ElementType.I32, Sizing.PER_OFFSCREEN, -1, -1, -1, -1, -1, 157), + OFFSCREEN_MASK_COUNT(ElementType.I32, Sizing.PER_OFFSCREEN, -1, -1, -1, -1, -1, 159), + OFFSCREEN_OPACITY(ElementType.F32, Sizing.TABLE, -1, -1, -1, -1, -1, 161), + + /** Per-part index of the offscreen it owns, -1 when none (the inverse of [OFFSCREEN_OWNER_PART]). */ + OFFSCREEN_BY_PART(ElementType.I32, Sizing.PER_PART, -1, -1, -1, -1, -1, 152), + + /** + * Per-offscreen cumulative base into the offscreen mask PREFIX of [MASK_INDEX_DATA], offset from + * the block start (successive diffs equal [OFFSCREEN_MASK_COUNT]; Model A probe, + * OffscreenKeyformProbeTest). + */ + OFFSCREEN_MASK_BASE(ElementType.I32, Sizing.PER_OFFSCREEN, -1, -1, -1, -1, -1, 158), + + /** + * Offscreen keyform → color-table row maps (multiply / screen). Observed identity on the corpus + * (the offscreen keyforms ARE the color tables' prefix rows, in offscreen order); the multiply + * vs screen split is assumed from the per-object color-base precedent, pending a discriminating + * sample. An offscreen's keyforms ride its owner part's keyform grid (Σ owner grid == CountInfo + * 36) - there is no offscreen keyform-binding section. + */ + OFFSCREEN_KEYFORM_MULTIPLY_ROW(ElementType.I32, Sizing.TABLE, -1, -1, -1, -1, -1, 162), + OFFSCREEN_KEYFORM_SCREEN_ROW(ElementType.I32, Sizing.TABLE, -1, -1, -1, -1, -1, 163), + + /** The offscreen block's 8-byte runtime slot; all-zero on disk, sized only. */ + OFFSCREEN_RUNTIME_SLOT(ElementType.U64, Sizing.PER_OFFSCREEN, -1, -1, -1, -1, -1, 154), + + /** + * A second per-part offscreen-index map, byte-identical to [OFFSCREEN_BY_PART] on every corpus + * sample BUT Model A, where 152 is the exact inverse of [OFFSCREEN_OWNER_PART] while 160 names a + * larger set of parts matching no owner - so 152 is the reconstructible column and 160 an + * editor-internal artifact whose rule is unknown (OffscreenSectionAliasProbeTest guards the + * divergence). A writer emits the derivable inverse in both. + */ + OFFSCREEN_BY_PART_ALIAS(ElementType.I32, Sizing.PER_PART, -1, -1, -1, -1, -1, 160), + + /** + * The v6 table's trailing slots. Zero-LENGTH in every corpus sample, so their element type and + * meaning are unknown; they are enumerated so the section map is complete and a coverage check can + * see them, and `U8`/`TABLE` is the neutral choice that asserts no stride. + */ + RESERVED_164(ElementType.U8, Sizing.TABLE, -1, -1, -1, -1, -1, 164), + RESERVED_165(ElementType.U8, Sizing.TABLE, -1, -1, -1, -1, -1, 165), + RESERVED_166(ElementType.U8, Sizing.TABLE, -1, -1, -1, -1, -1, 166), + ; + + /** + * Section-table index of this section for a moc [version], or -1 if absent. + * + * @param MocVersion version The moc version. + * @return Int The section index, or -1. + */ + public fun indexIn(version: MocVersion): Int = indexByVersion[version.byteValue - 1] +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/Sections.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/Sections.kt new file mode 100644 index 0000000..9a80d67 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/moc/Sections.kt @@ -0,0 +1,71 @@ +package org.umamo.format.moc3.moc + +/** + * `.moc3` container constants and the CountInfo field indices. + * + * Section-table INDICES do not live here - every one of them is a [Section] enum entry carrying + * its element type, sizing rule, and per-version index, so `MocSections` can decode it and the + * lossless gate can check it. A bare index constant sitting alongside that enum would name a + * section neither of them can see, so what remains here is the container geometry and the + * CountInfo field numbers, which are not sections at all. + * + * @see MOC3.md §section map + */ +public object Sections { + /** + * Where the data region (and section index 0, CountInfo) begins on a moc <= 5 file; the + * header+table region fills [0, this). A moc 6 file reserves a larger region and starts its data + * at 0x16C0 instead, so a reader takes the first section's offset from the table rather than this. + * MOC3 §4. + */ + public const val DATA_SECTION_BEGIN: Int = 1984 // 0x7C0 + + /** Fixed width, in bytes, of every ID record (ASCII, NUL-terminated, zero-padded). */ + public const val ID_STRIDE: Int = 64 + + // ---- CountInfo (section 0) u32 indices ---- + public const val CI_PARTS: Int = 0 + public const val CI_DEFORMERS: Int = 1 + public const val CI_WARPS: Int = 2 + public const val CI_ROTATIONS: Int = 3 + public const val CI_DRAWABLES: Int = 4 + public const val CI_PARAMETERS: Int = 5 + + // MOC3 §5.1 CountInfo fields 6-9: the flat per-KEYFORM array lengths, one entry per form rather + // than per object. Each object indexes its own run through its keyform base (sections 5/20/26/35). + public const val CI_PART_FORMS: Int = 6 + public const val CI_WARP_FORMS: Int = 7 + public const val CI_ROTATION_FORMS: Int = 8 + public const val CI_ARTMESH_FORMS: Int = 9 + + // MOC3 §5.1 CountInfo field 12: the stored keyform-binding record count. Authoritative over + // object references - a mesh-less model carries one EMPTY binding (0 axes) that only static + // parts point at (probed on the ModelWithOffscreen family). + public const val CI_KEYFORM_BINDINGS: Int = 12 + public const val CI_RENDER_ORDER_GROUPS: Int = 18 + public const val CI_RENDER_ORDER_CHILDREN: Int = 19 + public const val CI_GLUES: Int = 20 + public const val CI_BLENDSHAPE_WARPS: Int = 27 + public const val CI_BLENDSHAPE_MESHES: Int = 28 + + // MOC3 v4+ §5.6: total blend-shape sub-binding corner refs (Σ section 124) and the + // deduplicated sub-binding pool size (section 132's real element count). + public const val CI_BLENDSHAPE_SUB_CORNERS: Int = 29 + public const val CI_BLENDSHAPE_SUB_BINDINGS: Int = 30 + + // MOC3 v5+ §5.6: blend-shape part objects. Note CountInfo is NOT hard-capped at 32 words on + // v5 - Model C (v5) carries CI 32/33; the reader is slice-length-driven, so these decode fine. + public const val CI_BLENDSHAPE_PARTS: Int = 32 + public const val CI_BLENDSHAPE_ROTATIONS: Int = 33 + + // MOC3 v5+ §5.6: glue blend-shape objects (sections 149-151). Zero in every corpus sample, and + // the lowering deliberately writes zero here, so nothing downstream models a glue blend shape yet. + public const val CI_BLENDSHAPE_GLUES: Int = 34 + + // MOC3 v6 §5.1 CountInfo field 35: offscreen render targets (sections 152-163). + public const val CI_OFFSCREENS: Int = 35 + + // MOC3 v6 §5.6: total offscreen keyforms (Σ owner-part grid sizes; sizes section 161 and the + // color tables' offscreen prefix). + public const val CI_OFFSCREEN_KEYFORMS: Int = 36 +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Advanced.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Advanced.kt new file mode 100644 index 0000000..9c735d5 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Advanced.kt @@ -0,0 +1,170 @@ +package org.umamo.format.moc3.model + +/** + * One keyform of an [Offscreen]: its opacity plus multiply/screen color. Offscreen keyforms ride + * the owner part's keyform grid (there is no offscreen keyform-binding section; Σ owner-part grid + * sizes == CountInfo 36), and their rows form the PREFIX of the shared color tables on moc 6. + * + * @property opacity The offscreen's opacity at this keyform (MOC3 §5.6 section 161). + * @property multiplyColor The multiply color row, or null when color tables are absent. + * @property screenColor The screen color row, or null when color tables are absent. + */ +public data class OffscreenKeyform( + val opacity: Float, + val multiplyColor: Rgb? = null, + val screenColor: Rgb? = null, +) + +/** An offscreen render target (moc 6 / Cubism 5.3): composites its owner part's subtree. */ +public data class Offscreen( + val ownerPartIndex: Int, + /** [org.umamo.format.moc3.moc.ConstantFlag]-style bitmask (`u8`). */ + val constantFlags: Int, + /** Packed blend-mode value as stored in the file (the runtime unpacks it into color/alpha modes). */ + val blendMode: Int, + val maskCount: Int, + /** Per-keyform opacity/color, parallel to the owner part's keyform grid (empty pre-extraction). */ + val keyforms: List = emptyList(), + /** Masking drawable indices from the offscreen suffix of MASK_INDEX_DATA (§5.6 section 80). */ + val maskIndices: IntArray = IntArray(0), +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is Offscreen && + ownerPartIndex == other.ownerPartIndex && + constantFlags == other.constantFlags && + blendMode == other.blendMode && + maskCount == other.maskCount && + keyforms == other.keyforms && + maskIndices.contentEquals(other.maskIndices) + ) + + override fun hashCode(): Int { + var hash = ownerPartIndex + hash = 31 * hash + constantFlags + hash = 31 * hash + blendMode + hash = 31 * hash + maskCount + hash = 31 * hash + keyforms.hashCode() + hash = 31 * hash + maskIndices.contentHashCode() + return hash + } +} + +/** Which kind of object a [BlendShape] deltas (warps/meshes moc 4+; rotations/parts moc 5+). */ +public enum class BlendShapeTarget { WARP, ART_MESH, ROTATION, PART } + +/** + * One key's extracted delta payload of a [BlendShape] record, per target kind. + * + * Values are the raw per-key delta rows lifted from the shared keyform value tables (MOC3.md + * §5.6): relative to the object's grid form at the default pose, with the neutral key's row + * all-zero. Geometry stays in the space the base keyforms use (parent-relative); no coordinate + * conversion happens at the format layer. The reused keyform types carry the per-kind channels + * (positions/control points/affine plus opacity, draw order, and color), all as deltas - so an + * unauthored channel reads 0, not the channel's identity value. + */ +public sealed class BlendShapeKeyform { + /** An art-mesh record's per-key deltas (vertex positions, opacity, draw order, colors). */ + public data class Mesh(val form: ArtMeshKeyform) : BlendShapeKeyform() + + /** A warp record's per-key deltas (lattice control points, opacity, colors). */ + public data class Warp(val form: WarpKeyform) : BlendShapeKeyform() + + /** A rotation record's per-key deltas (origin/angle/scale, opacity, colors; reflects unused). */ + public data class Rotation(val form: RotationKeyform) : BlendShapeKeyform() + + /** A part record's per-key delta (draw order only - MOC3 §5.6 section 58 delta rows). */ + public data class Part(val drawOrderDelta: Float) : BlendShapeKeyform() +} + +/** + * A blend-weight limit ("blend shape limit") on a [BlendShape] record: an end-clamped + * piecewise-linear (key, weight) curve over ANOTHER parameter's value that caps the record's + * weight. A record's effective multiplier is the MINIMUM over its limits (1 when it has none). + * + * On disk (MOC3 v4+ §5.6, sections 123/124 + 131-136) records reference a DEDUPLICATED pool of + * sub-bindings; the decoder expands the pool per record, so identical curves shared by many + * records appear on each. A future lowering re-dedups by value when synthesizing the tables. + * + * @property parameterIndex The gating parameter (index into [org.umamo.format.moc3.MocDocument.parameters]). + * @property keyPositions The curve's parameter values, ascending. + * @property weights The weight cap at each key, parallel to [keyPositions]. + */ +public data class BlendShapeLimit( + val parameterIndex: Int, + val keyPositions: FloatArray, + val weights: FloatArray, +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is BlendShapeLimit && + parameterIndex == other.parameterIndex && + keyPositions.contentEquals(other.keyPositions) && + weights.contentEquals(other.weights) + ) + + override fun hashCode(): Int { + var hash = parameterIndex + hash = 31 * hash + keyPositions.contentHashCode() + hash = 31 * hash + weights.contentHashCode() + return hash + } +} + +/** + * A blend-shape record (moc 4+ for meshes/warps, moc 5+ for rotations): an additive deformation + * delta driven by one parameter. The deltas live in the shared keyform value tables at + * [recordBase] (per key) and are lifted into [keyforms]; each is relative to the object's grid + * form at the default pose, with the [neutralKeyIndex] row all-zero. + * + * @property target Kind of deformed object. + * @property targetIndex For [BlendShapeTarget.WARP]/[BlendShapeTarget.ROTATION], the deformer index + * in [org.umamo.format.moc3.MocDocument.deformers]; for + * [BlendShapeTarget.ART_MESH], the drawable index; for + * [BlendShapeTarget.PART], the part index. + * @property parameterIndex The driving parameter (index into [org.umamo.format.moc3.MocDocument.parameters]). + * @property keyPositions Parameter values at which deltas are keyed. + * @property neutralKeyIndex The key whose delta is zero (the rest shape). + * @property recordBase Base index into the keyform value tables for this record's per-key deltas. + * @property limits Blend-weight limits capping this record's weight (min-combined; empty = uncapped). + * @property keyforms Per-key delta payloads, parallel to [keyPositions] (one per key, kind + * matching [target]); see [BlendShapeKeyform] for the value conventions. + */ +public data class BlendShape( + val target: BlendShapeTarget, + val targetIndex: Int, + val parameterIndex: Int, + val keyPositions: FloatArray, + val neutralKeyIndex: Int, + val recordBase: Int, + val limits: List = emptyList(), + val keyforms: List = emptyList(), +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is BlendShape && + target == other.target && + targetIndex == other.targetIndex && + parameterIndex == other.parameterIndex && + keyPositions.contentEquals(other.keyPositions) && + neutralKeyIndex == other.neutralKeyIndex && + recordBase == other.recordBase && + limits == other.limits && + keyforms == other.keyforms + ) + + override fun hashCode(): Int { + var hash = target.hashCode() + hash = 31 * hash + targetIndex + hash = 31 * hash + parameterIndex + hash = 31 * hash + keyPositions.contentHashCode() + hash = 31 * hash + neutralKeyIndex + hash = 31 * hash + recordBase + hash = 31 * hash + limits.hashCode() + hash = 31 * hash + keyforms.hashCode() + return hash + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/ArtMesh.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/ArtMesh.kt new file mode 100644 index 0000000..388f479 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/ArtMesh.kt @@ -0,0 +1,91 @@ +package org.umamo.format.moc3.model + +/** One keyform of an [ArtMesh]: the deformed vertex positions plus opacity/draw-order/color. */ +public data class ArtMeshKeyform( + /** Vertex positions, `vertexCount` points as interleaved `x,y` (model space). */ + val vertexPositions: FloatArray, + val opacity: Float, + val drawOrder: Float, + val multiplyColor: Rgb?, + val screenColor: Rgb?, +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is ArtMeshKeyform && + vertexPositions.contentEquals(other.vertexPositions) && + opacity == other.opacity && + drawOrder == other.drawOrder && + multiplyColor == other.multiplyColor && + screenColor == other.screenColor + ) + + override fun hashCode(): Int { + var hash = vertexPositions.contentHashCode() + hash = 31 * hash + opacity.hashCode() + hash = 31 * hash + drawOrder.hashCode() + hash = 31 * hash + (multiplyColor?.hashCode() ?: 0) + hash = 31 * hash + (screenColor?.hashCode() ?: 0) + return hash + } +} + +/** + * An art mesh (drawable): static topology (UVs, triangles, mask list) plus per-keyform geometry. + * + * EN: [vertexUvs] (interleaved `u,v`) and [triangleIndices] are static; the vertex positions are + * keyed in [keyforms] over [keyformBindingIndex]'s grid. [parentDeformerIndex] is -1 for a mesh + * parented directly to its part. + */ +public data class ArtMesh( + val id: String, + val textureIndex: Int, + /** [org.umamo.format.moc3.moc.ConstantFlag] bitmask. */ + val constantFlags: Int, + /** + * Packed 5.3 extended blend, colorMode or (alphaMode shl 8); 0 = legacy (the constant-flags + * 2-bit blend field applies instead). MOC3 v6 §5.6 s153. + */ + val extendedBlend: Int = 0, + /** + * MOC3 §5.6 s37: whether the art mesh is visible (the editor's eye toggle). The official editor + * normally DELETES a hidden mesh at bake time and only carries it - flagged false here - when + * "export invisible drawable" is on, which is why almost every corpus file has this true + * throughout. An Umamo export carries hidden meshes this same way unless its own export options + * asked to omit them. + */ + val isVisible: Boolean = true, + /** MOC3 §5.6 s38: the drawable's second flag; 1 throughout the corpus (see `ARTMESH_IS_ENABLED`). */ + val isEnabled: Boolean = true, + val parentPartIndex: Int, + val parentDeformerIndex: Int, + val vertexUvs: FloatArray, + val triangleIndices: ShortArray, + val maskDrawableIndices: IntArray, + val keyformBindingIndex: Int, + val keyforms: List, +) { + /** Number of vertices (UVs / each keyform's positions hold this many `x,y` pairs). */ + val vertexCount: Int get() = vertexUvs.size / 2 + + override fun equals(other: Any?): Boolean = + this === other || + ( + other is ArtMesh && + id == other.id && + textureIndex == other.textureIndex && + constantFlags == other.constantFlags && + extendedBlend == other.extendedBlend && + isVisible == other.isVisible && + isEnabled == other.isEnabled && + parentPartIndex == other.parentPartIndex && + parentDeformerIndex == other.parentDeformerIndex && + vertexUvs.contentEquals(other.vertexUvs) && + triangleIndices.contentEquals(other.triangleIndices) && + maskDrawableIndices.contentEquals(other.maskDrawableIndices) && + keyformBindingIndex == other.keyformBindingIndex && + keyforms == other.keyforms + ) + + override fun hashCode(): Int = id.hashCode() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Deformers.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Deformers.kt new file mode 100644 index 0000000..81f91b8 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Deformers.kt @@ -0,0 +1,99 @@ +package org.umamo.format.moc3.model + +/** + * A deformer (warp or rotation), carrying the fields every deformer shares - the moc3 deformer + * block's common head (sections 11-16), in file order. + * + * Deformers reference each other by index (their position in + * [org.umamo.format.moc3.MocDocument.deformers]), and [id] is the authored identifier the editor + * wrote alongside that index. The two hierarchies are independent: [parentDeformerIndex] is the + * deformation nesting, [parentPartIndex] the organizational tree. + */ +public sealed class Deformer { + /** MOC3 §5.6 s11: the authored id, e.g. "Warp349" or "B_LEG_01". */ + public abstract val id: String + + /** MOC3 §5.6 s12: the deformer's keyform-binding (parameter grid) index. */ + public abstract val keyformBindingIndex: Int + + /** MOC3 §5.6 s13: whether the deformer is visible (the editor's eye toggle). */ + public abstract val isVisible: Boolean + + /** MOC3 §5.6 s14: the deformer's second flag; 1 throughout the corpus (see `DEFORMER_IS_ENABLED`). */ + public abstract val isEnabled: Boolean + + /** MOC3 §5.6 s15: the part this deformer belongs to, -1 at the root. */ + public abstract val parentPartIndex: Int + + /** MOC3 §5.6 s16: the parent in the deformation hierarchy, -1 for a root deformer. */ + public abstract val parentDeformerIndex: Int +} + +/** One keyform of a [WarpDeformer]: the deformed control-point grid plus opacity/color. */ +public data class WarpKeyform( + /** Control points, `(columns+1)·(rows+1)` points as interleaved `x,y`. */ + val controlPoints: FloatArray, + val opacity: Float, + val multiplyColor: Rgb?, + val screenColor: Rgb?, +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is WarpKeyform && + controlPoints.contentEquals(other.controlPoints) && + opacity == other.opacity && + multiplyColor == other.multiplyColor && + screenColor == other.screenColor + ) + + override fun hashCode(): Int { + var hash = controlPoints.contentHashCode() + hash = 31 * hash + opacity.hashCode() + hash = 31 * hash + (multiplyColor?.hashCode() ?: 0) + hash = 31 * hash + (screenColor?.hashCode() ?: 0) + return hash + } +} + +/** A warp (grid) deformer: a `(columns+1)·(rows+1)` control-point lattice keyed over parameters. */ +public data class WarpDeformer( + override val id: String, + override val keyformBindingIndex: Int, + override val isVisible: Boolean, + override val isEnabled: Boolean, + override val parentPartIndex: Int, + override val parentDeformerIndex: Int, + val rows: Int, + val columns: Int, + /** Interpolation mode (0 = triangle-split, non-zero = bilinear); 0 on moc < 3. */ + val mode: Int, + val keyforms: List, +) : Deformer() + +/** One keyform of a [RotationDeformer]: the local affine plus opacity/color. */ +public data class RotationKeyform( + val originX: Float, + val originY: Float, + /** Angle delta in degrees (added to [RotationDeformer.baseAngle]). */ + val angle: Float, + val scale: Float, + val reflectX: Boolean, + val reflectY: Boolean, + val opacity: Float, + val multiplyColor: Rgb?, + val screenColor: Rgb?, +) + +/** A rotation deformer: an origin/angle/scale affine keyed over parameters, plus a static base angle. */ +public data class RotationDeformer( + override val id: String, + override val keyformBindingIndex: Int, + override val isVisible: Boolean, + override val isEnabled: Boolean, + override val parentPartIndex: Int, + override val parentDeformerIndex: Int, + /** Static base angle in degrees, added to each keyform's [RotationKeyform.angle]. */ + val baseAngle: Float, + val keyforms: List, +) : Deformer() \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Keyforms.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Keyforms.kt new file mode 100644 index 0000000..c816dec --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Keyforms.kt @@ -0,0 +1,62 @@ +package org.umamo.format.moc3.model + +/** An RGB color (each channel typically 0..1); the alpha is always 1 in moc3 color tables. */ +public data class Rgb(val r: Float, val g: Float, val b: Float) + +/** + * One controlling axis of a [KeyformBinding]: a parameter and the key positions sampled along it. + * + * @property parameterIndex Index into [org.umamo.format.moc3.MocDocument.parameters] of the driving parameter. + * @property keyPositions The parameter values at which keyforms exist, ascending. + */ +public data class KeyformAxis( + val parameterIndex: Int, + val keyPositions: FloatArray, +) { + /** Number of keys on this axis. */ + val keyCount: Int get() = keyPositions.size + + override fun equals(other: Any?): Boolean = + this === other || + ( + other is KeyformAxis && + parameterIndex == other.parameterIndex && + keyPositions.contentEquals( + other.keyPositions, + ) + ) + + override fun hashCode(): Int = 31 * parameterIndex + keyPositions.contentHashCode() +} + +/** + * The interpolation grid an object's keyforms are laid out on: the controlling parameter [axes] + * (in stride order, the first the fastest-varying). The number of keyforms is [gridSize]; a grid + * index decomposes to per-axis key indices via [keyIndices]. + * + * EN: A static object (no controlling parameters) has no axes and a single keyform. + * + * @see MOC3.md §5.6 + */ +public data class KeyformBinding( + val index: Int, + val axes: List, +) { + /** Total number of keyforms = product of the axes' key counts (1 when there are no axes). */ + val gridSize: Int get() = axes.fold(1) { acc, axis -> acc * axis.keyCount } + + /** + * Decomposes a grid index into a per-axis key index (mixed-radix, first axis = stride 1). + * + * @param Int gridIndex A keyform index in `0 until gridSize`. + * @return IntArray The key index along each axis, in axis order. + */ + public fun keyIndices(gridIndex: Int): IntArray { + var stride = 1 + return IntArray(axes.size) { axisIndex -> + val keyIndex = (gridIndex / stride) % axes[axisIndex].keyCount + stride *= axes[axisIndex].keyCount + keyIndex + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Structure.kt b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Structure.kt new file mode 100644 index 0000000..b633b7a --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/moc3/model/Structure.kt @@ -0,0 +1,81 @@ +package org.umamo.format.moc3.model + +/** + * A part (visibility/draw-order group). [drawOrderKeyforms] holds the part's draw order per keyform + * of [keyformBindingIndex]'s grid (a single value when the part is static). + */ +public data class Part( + val id: String, + val parentPartIndex: Int, + val keyformBindingIndex: Int, + val drawOrderKeyforms: FloatArray, + /** + * MOC3 §5.6 s7/s8: the part's visibility. The file stores TWO flags here: Lina's research + * lists them as visible_artmeshes and visible_deformers, but without defining what they do. + * Both are 1 on every part of every corpus sample and no CMO3 twin keeps a hidden part, so + * which is which is unpinned. One field carries them: a decode takes s7, and a bake writes + * the same value to both. + */ + val isVisible: Boolean = true, +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is Part && + id == other.id && + parentPartIndex == other.parentPartIndex && + keyformBindingIndex == other.keyformBindingIndex && + isVisible == other.isVisible && + drawOrderKeyforms.contentEquals(other.drawOrderKeyforms) + ) + + override fun hashCode(): Int = id.hashCode() +} + +/** A glued vertex pair: a vertex in mesh A welded to one in mesh B with per-side weights. */ +public data class GlueVertexPair( + val vertexA: Int, + val vertexB: Int, + val weightA: Float, + val weightB: Float, +) + +/** + * A glue: seam-welds two art meshes' shared vertices. [intensityKeyforms] modulate the weld strength + * over [keyformBindingIndex]'s grid (a single value when static). + */ +public data class Glue( + /** MOC3 §5.6 s90: the authored id, e.g. "Glue__ArtMesh48__ArtMesh49" (older bakes: "Glue_0_1_"). */ + val id: String, + val meshAIndex: Int, + val meshBIndex: Int, + val keyformBindingIndex: Int, + val pairs: List, + val intensityKeyforms: FloatArray, +) { + override fun equals(other: Any?): Boolean = + this === other || + ( + other is Glue && + id == other.id && + meshAIndex == other.meshAIndex && + meshBIndex == other.meshBIndex && + keyformBindingIndex == other.keyformBindingIndex && + pairs == other.pairs && + intensityKeyforms.contentEquals(other.intensityKeyforms) + ) + + override fun hashCode(): Int = 31 * (31 * meshAIndex + meshBIndex) + keyformBindingIndex +} + +/** A child of a [RenderOrderGroup]: a drawable (kind 0) or a nested group (kind 1). */ +public data class RenderOrderChild( + val kind: Int, + /** Drawable index when [kind] is 0, else the part index used to look up the sub-group's order. */ + val index: Int, + /** The nested group's record index when [kind] is 1 (else unused). */ + val groupIndex: Int, +) + +/** A render-order group: an ordered list of drawable/sub-group children (the draw-order tree). */ +public data class RenderOrderGroup(val children: List) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/png/PngChunks.kt b/module/format/src/commonMain/kotlin/org/umamo/format/png/PngChunks.kt new file mode 100644 index 0000000..68bdbcf --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/png/PngChunks.kt @@ -0,0 +1,229 @@ +package org.umamo.format.png + +import okio.Buffer +import okio.Source +import okio.Timeout +import org.umamo.format.binary.Crc32 +import org.umamo.format.binary.deflateZlib + +/* + * PNG datastream plumbing: the 8-byte signature, the length/type/data/CRC chunk framing, the IDAT + * stream the decoder inflates, and the zlib compression the encoder writes it with. + * + * No host image library, so decode is byte-identical on every target; the only platform dependency is + * the zlib bridge in org.umamo.format.binary. Spec citations are to the PNG specification, second + * edition (ISO/IEC 15948:2003, W3C REC-PNG-20031110), whose section numbers differ from RFC 2083's. + */ + +/** PNG spec §5.2 Datastream signature: the fixed 8-byte file magic. */ +internal val PNG_SIGNATURE: ByteArray = + byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) + +/** + * One parsed PNG chunk: its 4-character type and where its (already CRC-verified) data sits in the + * file bytes. The data stays in place rather than being copied out, because the IDAT chunks of a + * large atlas page hold hundreds of megabytes that the decoder only needs to stream through once. + * + * @param String type The chunk type. + * @param ByteArray fileBytes The complete `.png` file the chunk was read from. + * @param Int dataOffset Offset of the chunk's first data byte in [fileBytes]. + * @param Int dataLength The chunk's data byte count. + */ +internal class PngChunk(val type: String, val fileBytes: ByteArray, val dataOffset: Int, val dataLength: Int) { + /** + * Copies the chunk's data out of the file bytes, for the small chunks (IHDR, PLTE, tRNS) the + * decoder reads as a whole. + * + * @return ByteArray The chunk data. + */ + fun copyData(): ByteArray = fileBytes.copyOfRange(dataOffset, dataOffset + dataLength) +} + +/** + * True if [bytes] opens with the PNG signature. + * + * @param ByteArray bytes Candidate file contents. + * @return Boolean Whether the leading 8 bytes are the PNG magic. + */ +internal fun matchesPngSignature(bytes: ByteArray): Boolean { + if (bytes.size < PNG_SIGNATURE.size) { + return false + } + for (signatureIndex in PNG_SIGNATURE.indices) { + if (bytes[signatureIndex] != PNG_SIGNATURE[signatureIndex]) { + return false + } + } + return true +} + +/** + * The width and height a PNG's header declares, read from the fixed offsets of its IHDR chunk without + * decoding anything else, or null when [bytes] do not open with the signature and an IHDR. + * + * PNG spec §11.2.2: IHDR is always the first chunk, 13 bytes of data, width then height as unsigned + * big-endian 32-bit integers. A dimension past what an Int holds reads as null too: no image this + * codec decodes can be that large. + * + * @param ByteArray bytes The complete `.png` file, or at least its first 24 bytes. + * @return Pair? The width and height, or null. + */ +internal fun pngDimensionsOf(bytes: ByteArray): Pair? { + val headerEnd = PNG_SIGNATURE.size + 16 + if (bytes.size < headerEnd || !matchesPngSignature(bytes)) { + return null + } + val chunkStart = PNG_SIGNATURE.size + if (readU32BE(bytes, chunkStart) != 13L || bytes.copyOfRange(chunkStart + 4, chunkStart + 8).decodeToString() != "IHDR") { + return null + } + val width = readU32BE(bytes, chunkStart + 8) + val height = readU32BE(bytes, chunkStart + 12) + if (width > Int.MAX_VALUE || height > Int.MAX_VALUE) { + return null + } + return width.toInt() to height.toInt() +} + +/** + * Reads an unsigned big-endian 32-bit integer as a Long (PNG stores lengths and CRCs this way). + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the most-significant byte. + * @return Long The value in 0..4294967295. + */ +internal fun readU32BE(bytes: ByteArray, at: Int): Long = + ((bytes[at].toLong() and 0xFF) shl 24) or + ((bytes[at + 1].toLong() and 0xFF) shl 16) or + ((bytes[at + 2].toLong() and 0xFF) shl 8) or + (bytes[at + 3].toLong() and 0xFF) + +/** + * Parses the chunk sequence after the signature, verifying each chunk's CRC-32, up to and including + * IEND. A truncated chunk or a CRC mismatch is a hard error - a valid PNG never has either. + * + * @param ByteArray bytes The complete `.png` file. + * @return List The chunks in file order. + */ +internal fun readChunks(bytes: ByteArray): List { + require(matchesPngSignature(bytes)) { "not a PNG (bad signature)" } + val chunks = ArrayList() + var cursor = PNG_SIGNATURE.size + // PNG spec §5.3 Chunk layout: length(4) | type(4) | data(length) | crc(4). + while (cursor + 8 <= bytes.size) { + val length = readU32BE(bytes, cursor).toInt() + val typeStart = cursor + 4 + val dataStart = cursor + 8 + // Checked in Long: a hostile length near Int.MAX_VALUE would otherwise wrap past the bound. + require(length >= 0 && dataStart.toLong() + length + 4 <= bytes.size) { "truncated PNG chunk at offset $cursor" } + val dataEnd = dataStart + length + + val type = bytes.decodeToString(typeStart, typeStart + 4) + val storedCrc = readU32BE(bytes, dataEnd) + // The CRC covers the type and data fields, which sit next to each other in the file. + val computedCrc = Crc32().also { crc -> crc.update(bytes, typeStart, 4 + length) }.value + require(storedCrc == computedCrc) { + "PNG chunk '$type' CRC mismatch (stored $storedCrc, computed $computedCrc)" + } + + chunks += PngChunk(type, bytes, dataStart, length) + cursor = dataEnd + 4 + if (type == "IEND") { + break + } + } + return chunks +} + +/** + * CRC-32 over a chunk's type bytes followed by its data bytes, per PNG spec §5.3. + * + * @param ByteArray type The 4 type bytes. + * @param ByteArray data The chunk data. + * @return Long The CRC-32 value. + */ +internal fun crc32Of(type: ByteArray, data: ByteArray): Long { + val crc = Crc32() + crc.update(type) + crc.update(data) + return crc.value +} + +/** + * Appends a complete chunk (length, type, data, CRC) to [out]. + * + * PNG's multi-byte fields are all big-endian, which is Buffer.writeInt's native order — hence no + * byte-order helper here. + * + * @param Buffer out The destination buffer. + * @param String type The 4-character chunk type (ASCII). + * @param ByteArray data The chunk data (may be empty, e.g. IEND). + */ +internal fun writeChunk(out: Buffer, type: String, data: ByteArray) { + val typeBytes = type.encodeToByteArray() + out.writeInt(data.size) + out.write(typeBytes) + out.write(data) + out.writeInt(crc32Of(typeBytes, data).toInt()) +} + +/** + * The data of the IDAT chunks, in file order, read as the one continuous zlib stream they form (PNG + * spec §10.2 and §11.2.4: the concatenated IDAT data is one zlib datastream, split at arbitrary + * boundaries). + * + * Reads straight out of the file bytes, a piece at a time, so the compressed stream is never + * concatenated into a copy of its own. + * + * @param List idatChunks The IDAT chunks in file order. + */ +internal class IdatSource(private val idatChunks: List) : Source { + private var chunkIndex = 0 + + // Bytes of the current chunk's data already delivered. + private var consumed = 0 + + /** + * Appends up to [byteCount] of the next stream bytes to [sink], never crossing into the next + * chunk in one call. + * + * @param Buffer sink The buffer to append to. + * @param Long byteCount The most bytes to deliver. + * @return Long The bytes delivered, or -1 once every chunk has been read. + */ + override fun read(sink: Buffer, byteCount: Long): Long { + while (chunkIndex < idatChunks.size && consumed == idatChunks[chunkIndex].dataLength) { + chunkIndex++ + consumed = 0 + } + if (chunkIndex == idatChunks.size) { + return -1L + } + val chunk = idatChunks[chunkIndex] + val count = minOf(byteCount, (chunk.dataLength - consumed).toLong()).toInt() + sink.write(chunk.fileBytes, chunk.dataOffset + consumed, count) + consumed += count + return count.toLong() + } + + /** + * No deadline: the bytes are already in memory. + * + * @return Timeout The no-op timeout. + */ + override fun timeout(): Timeout = Timeout.NONE + + /** + * Nothing to release: the file bytes belong to the caller. + */ + override fun close() { + } +} + +/** + * Compresses [data] to a zlib stream for an IDAT chunk (default deflate level). + * + * @param ByteArray data The raw, filtered scanline bytes. + * @return ByteArray The zlib-wrapped deflate stream. + */ +internal fun deflateIdat(data: ByteArray): ByteArray = deflateZlib(data) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/png/PngCodec.kt b/module/format/src/commonMain/kotlin/org/umamo/format/png/PngCodec.kt new file mode 100644 index 0000000..3db28aa --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/png/PngCodec.kt @@ -0,0 +1,567 @@ +package org.umamo.format.png + +import okio.Buffer +import org.umamo.format.FileKind +import org.umamo.format.binary.ZlibStreamReader +import org.umamo.format.raster.RasterCodec +import org.umamo.format.raster.RasterImage + +/** + * Pure-Kotlin PNG codec, read and write. + * + * Decodes every PNG color type (grayscale, RGB, palette, grayscale+alpha, RGBA) at bit depths + * 1/2/4/8/16, including tRNS transparency and Adam7 interlace, to the neutral straight-alpha + * RGBA8888 top-first [RasterImage]. 16-bit samples are reduced to 8 bits by the spec's most + * accurate rescaling, the linear equation of PNG spec §13.12, rather than by dropping the low byte. + * Encodes 8-bit RGBA (color type 6, non-interlaced) - the form the atlas / thumbnail pipeline + * needs. DEFLATE is the codec's only platform dependency, reached through the zlib bridge in + * org.umamo.format.binary, so it decodes byte-identically on every target (no javax.imageio / + * BitmapFactory, which is exactly what this replaces). + * + * Decoding streams: the IDAT data is inflated one scanline at a time straight out of the file + * bytes, so a decode holds the file and the output image and little else. Neither the compressed + * nor the decompressed stream is ever held whole, which is what lets a 16384-square atlas page + * decode in little more than the 1 GiB its pixels need. + * + * Spec citations are to the PNG specification, second edition (ISO/IEC 15948:2003, W3C + * REC-PNG-20031110). + */ +public object PngCodec : RasterCodec { + override val kind: FileKind = FileKind.Png + + // PNG spec §11.2.2 IHDR color types. + private const val COLOR_GRAYSCALE = 0 + private const val COLOR_RGB = 2 + private const val COLOR_PALETTE = 3 + private const val COLOR_GRAYSCALE_ALPHA = 4 + private const val COLOR_RGBA = 6 + + private const val OPAQUE = 0xFF.toByte() + + // A tRNS key no sample equals, for an image without one: raw samples are never negative. + private const val NO_KEY = -1 + + /** Adam7 per-pass origin and step (PNG spec §8.2): {startColumn, startRow, columnStep, rowStep}. */ + private val ADAM7_PASSES = + arrayOf( + intArrayOf(0, 0, 8, 8), + intArrayOf(4, 0, 8, 8), + intArrayOf(0, 4, 4, 8), + intArrayOf(2, 0, 4, 4), + intArrayOf(0, 2, 2, 4), + intArrayOf(1, 0, 2, 2), + intArrayOf(0, 1, 1, 2), + ) + + /** + * True if [candidateBytes] opens with the PNG signature. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the PNG magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean = matchesPngSignature(candidateBytes) + + /** + * Decodes a `.png` into a straight-alpha RGBA8888 [RasterImage], top row first. + * + * @param ByteArray bytes The complete `.png` file. + * @return RasterImage The decoded image. + */ + override fun read(bytes: ByteArray): RasterImage { + val chunks = readChunks(bytes) + val ihdrChunk = chunks.firstOrNull { it.type == "IHDR" } ?: throw IllegalArgumentException("PNG has no IHDR") + val header = parseHeader(ihdrChunk.copyData()) + + val palette = chunks.firstOrNull { it.type == "PLTE" }?.copyData() + val transparency = chunks.firstOrNull { it.type == "tRNS" }?.copyData() + // PNG spec §11.2.2 Table 11.1: an indexed-color image shall carry a PLTE chunk. + require(header.colorType != COLOR_PALETTE || palette != null) { "PNG color type 3 has no PLTE chunk" } + val expander = ScanlineExpander(header, palette, transparency) + + val rgba = ByteArray(header.width * header.height * 4) + // Only the scanlines IHDR describes are ever requested from the inflate, which is also its + // bound: a corrupt or hostile stream stops at the size the header promised instead of + // expanding until the process dies. A stream that ends early leaves the rows it never + // reached transparent black (best-effort, mirroring the PSD/CLIP readers). + val scanlines = ZlibStreamReader(IdatSource(chunks.filter { it.type == "IDAT" })) + try { + if (header.interlace == 1) { + for (pass in ADAM7_PASSES) { + val passWidth = passExtent(header.width, pass[0], pass[2]) + val passHeight = passExtent(header.height, pass[1], pass[3]) + if (passWidth == 0 || passHeight == 0) { + continue + } + decodePass(scanlines, rgba, header, expander, passWidth, passHeight, pass[0], pass[1], pass[2], pass[3]) + } + } else { + decodePass(scanlines, rgba, header, expander, header.width, header.height, 0, 0, 1, 1) + } + } finally { + scanlines.close() + } + return RasterImage(header.width, header.height, rgba) + } + + /** + * Encodes a [RasterImage] as an 8-bit RGBA (color type 6), non-interlaced PNG. + * + * Every scanline uses filter type 0 (None) - the simplest valid choice; DEFLATE still compresses + * it well. Round-trip is not byte-identical (zlib output varies), but decoding the result + * reproduces the input pixels exactly. + * + * @param RasterImage model The image to encode. + * @return ByteArray The complete `.png` file. + */ + override fun write(model: RasterImage): ByteArray { + val out = Buffer() + out.write(PNG_SIGNATURE) + + // PNG spec §11.2.2 IHDR: width, height, bitDepth=8, colourType=6 (RGBA), compression=0, filter=0, interlace=0. + val ihdr = Buffer() + ihdr.writeInt(model.width) + ihdr.writeInt(model.height) + ihdr.writeByte(8) + ihdr.writeByte(COLOR_RGBA) + ihdr.writeByte(0) + ihdr.writeByte(0) + ihdr.writeByte(0) + writeChunk(out, "IHDR", ihdr.readByteArray()) + + // Raw filtered scanlines: a leading filter byte (0=None) then width*4 RGBA bytes per row. + val rowBytes = model.width * 4 + val filtered = ByteArray(model.height * (1 + rowBytes)) + var destination = 0 + var source = 0 + for (rowIndex in 0 until model.height) { + filtered[destination++] = FILTER_NONE.toByte() + model.rgba.copyInto(filtered, destination, source, source + rowBytes) + destination += rowBytes + source += rowBytes + } + writeChunk(out, "IDAT", deflateIdat(filtered)) + writeChunk(out, "IEND", ByteArray(0)) + return out.readByteArray() + } + + /** + * The IHDR fields the decoder needs. + * + * @param Int width Image width in pixels. + * @param Int height Image height in pixels. + * @param Int bitDepth Bits per sample (per palette index for color type 3). + * @param Int colorType The PNG color type. + * @param Int interlace 0 for none, 1 for Adam7. + */ + private class PngHeader( + val width: Int, + val height: Int, + val bitDepth: Int, + val colorType: Int, + val interlace: Int, + ) { + /** Samples stored per pixel. */ + val channels: Int = channelCount(colorType) + + /** Bits one pixel occupies in a scanline. */ + val bitsPerPixel: Int = channels * bitDepth + } + + /** + * Parses the 13-byte IHDR data (PNG spec §11.2.2). + * + * @param ByteArray data The IHDR chunk data. + * @return PngHeader The parsed header, validated against the spec's allowed values. + */ + private fun parseHeader(data: ByteArray): PngHeader { + require(data.size >= 13) { "PNG IHDR too short" } + // PNG spec §11.2.2 IHDR: width(4) | height(4) | bit depth(1) | color type(1) | + // compression method(1) | filter method(1) | interlace method(1). + val width = readU32BE(data, 0).toInt() + val height = readU32BE(data, 4).toInt() + val bitDepth = data[8].toInt() and 0xFF + val colorType = data[9].toInt() and 0xFF + val compressionMethod = data[10].toInt() and 0xFF + val filterMethod = data[11].toInt() and 0xFF + val interlace = data[12].toInt() and 0xFF + require(width > 0 && height > 0) { "PNG has non-positive dimensions ${width}x$height" } + // IHDR allows dimensions up to 2^31-1 each, whose product overflows the Int sizing the RGBA + // buffer; reject rather than wrap to a negative (or plausible-but-wrong) allocation. + require(width.toLong() * height * 4 <= Int.MAX_VALUE) { "PNG is too large to decode: ${width}x$height" } + require(colorType == COLOR_GRAYSCALE || colorType == COLOR_RGB || colorType == COLOR_PALETTE || colorType == COLOR_GRAYSCALE_ALPHA || colorType == COLOR_RGBA) { + "unsupported PNG color type $colorType" + } + require(bitDepthAllowed(colorType, bitDepth)) { "PNG color type $colorType does not allow bit depth $bitDepth" } + // Method 0 is the only compression method and the only filter method the spec defines. + require(compressionMethod == 0) { "unsupported PNG compression method $compressionMethod" } + require(filterMethod == 0) { "unsupported PNG filter method $filterMethod" } + require(interlace == 0 || interlace == 1) { "unsupported PNG interlace method $interlace" } + // A 16-bit RGBA scanline is twice the width of its RGBA8888 row, so it can outgrow an array + // even when the image itself fits. + require((width.toLong() * channelCount(colorType) * bitDepth + 7) / 8 < Int.MAX_VALUE) { "PNG scanline is too long to decode: ${width}x$height" } + return PngHeader(width, height, bitDepth, colorType, interlace) + } + + /** + * Whether the spec allows [bitDepth] for [colorType] (PNG spec §11.2.2 Table 11.1). + * + * @param Int colorType A color type already checked to be one of the five defined ones. + * @param Int bitDepth The IHDR bit depth. + * @return Boolean True for an allowed pairing. + */ + private fun bitDepthAllowed(colorType: Int, bitDepth: Int): Boolean = + when (colorType) { + COLOR_GRAYSCALE -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8 || bitDepth == 16 + COLOR_PALETTE -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8 + else -> bitDepth == 8 || bitDepth == 16 + } + + /** Channels stored per pixel for a color type (palette and grayscale store one sample). */ + private fun channelCount(colorType: Int): Int = + when (colorType) { + COLOR_GRAYSCALE, COLOR_PALETTE -> 1 + COLOR_GRAYSCALE_ALPHA -> 2 + COLOR_RGB -> 3 + COLOR_RGBA -> 4 + else -> throw IllegalArgumentException("unsupported PNG color type $colorType") + } + + /** + * The number of pixels a reduced Adam7 pass spans along one axis (PNG spec §8.2). + * + * @param Int total The full image extent (width or height). + * @param Int start The pass origin on this axis. + * @param Int step The pass step on this axis. + * @return Int The count of samples this pass contributes on this axis (0 if the pass is empty). + */ + private fun passExtent(total: Int, start: Int, step: Int): Int = + if (total <= start) { + 0 + } else { + (total - start + step - 1) / step + } + + /** + * Decodes one filtered sub-image (the whole image when non-interlaced, one Adam7 pass otherwise), + * pulling its scanlines from [scanlines] and scattering its pixels into [rgba] at their + * interlaced positions. + * + * @param ZlibStreamReader scanlines The inflating IDAT stream, positioned at this sub-image. + * @param ByteArray rgba The destination full-image RGBA buffer. + * @param PngHeader header The IHDR parameters. + * @param ScanlineExpander expander Turns a reconstructed scanline into RGBA. + * @param Int passWidth Pixels per row in this sub-image. + * @param Int passHeight Rows in this sub-image. + * @param Int startColumn Adam7 column origin (0 for the full image). + * @param Int startRow Adam7 row origin (0 for the full image). + * @param Int columnStep Adam7 column step (1 for the full image). + * @param Int rowStep Adam7 row step (1 for the full image). + */ + private fun decodePass( + scanlines: ZlibStreamReader, + rgba: ByteArray, + header: PngHeader, + expander: ScanlineExpander, + passWidth: Int, + passHeight: Int, + startColumn: Int, + startRow: Int, + columnStep: Int, + rowStep: Int, + ) { + val bytesPerPixel = maxOf(1, (header.bitsPerPixel + 7) / 8) + val rowBytes = ((header.bitsPerPixel.toLong() * passWidth + 7) / 8).toInt() + val filterTypeByte = ByteArray(1) + // PNG spec §9.2: the first scanline of each reduced image filters against an all-zero row. + var previous = ByteArray(rowBytes) + var current = ByteArray(rowBytes) + for (rowIndex in 0 until passHeight) { + // PNG spec §9.2: each scanline opens with its filter-type byte. Past the end of a stream + // that stopped early, rows read as unfiltered zeros. + val filterType = + if (scanlines.readFully(filterTypeByte, 0, 1) == 1) { + filterTypeByte[0].toInt() and 0xFF + } else { + FILTER_NONE + } + val available = scanlines.readFully(current, 0, rowBytes) + if (available < rowBytes) { + current.fill(0, available, rowBytes) + } + + unfilterScanline(filterType, current, previous, bytesPerPixel) + + val imageY = startRow + rowIndex * rowStep + expander.expand(current, passWidth, rgba, (imageY * header.width + startColumn) * 4, columnStep * 4) + + val swap = previous + previous = current + current = swap + } + } + + /** + * Turns reconstructed scanlines into straight-alpha RGBA8888, with everything that depends only on + * IHDR, PLTE, and tRNS worked out once per image instead of once per sample. + * + * @param PngHeader header The IHDR parameters. + * @param ByteArray? palette The PLTE bytes (3 per entry), or null. + * @param ByteArray? transparency The tRNS bytes, or null. + */ + private class ScanlineExpander(private val header: PngHeader, palette: ByteArray?, transparency: ByteArray?) { + // PNG spec §11.3.2.1 tRNS for grayscale and truecolor: the single gray or RGB value, in the + // image's own sample range, that marks a pixel fully transparent. + private val keyGray = keySample(COLOR_GRAYSCALE, transparency, 0) + private val keyRed = keySample(COLOR_RGB, transparency, 0) + private val keyGreen = keySample(COLOR_RGB, transparency, 2) + private val keyBlue = keySample(COLOR_RGB, transparency, 4) + + /** + * RGBA for every possible sample value of the one-sample layouts at 8 bits or fewer (palette, + * and grayscale at 1/2/4/8 bits), where a table of at most 256 entries replaces all per-pixel + * work; null for every other layout. + */ + private val sampleColors: ByteArray? = buildSampleColors(palette, transparency) + + /** + * Reads one sample of a tRNS key, or [NO_KEY] when the image is not of [colorType] or its + * tRNS chunk is missing or too short to hold the key. + * + * @param Int colorType The color type the key belongs to. + * @param ByteArray? transparency The tRNS bytes, or null. + * @param Int offset Offset of the key sample's 2-byte big-endian value. + * @return Int The raw key sample, or [NO_KEY]. + */ + private fun keySample(colorType: Int, transparency: ByteArray?, offset: Int): Int { + val keyBytes = if (colorType == COLOR_RGB) 6 else 2 + if (header.colorType != colorType || transparency == null || transparency.size < keyBytes) { + return NO_KEY + } + return readU16(transparency, offset) + } + + /** + * Builds the per-sample RGBA table for palette and low-depth grayscale images. + * + * @param ByteArray? palette The PLTE bytes, or null. + * @param ByteArray? transparency The tRNS bytes, or null. + * @return ByteArray? Four RGBA bytes per sample value, or null when the layout has no table. + */ + private fun buildSampleColors(palette: ByteArray?, transparency: ByteArray?): ByteArray? { + if (header.bitDepth > 8) { + return null + } + val entries = 1 shl header.bitDepth + return when (header.colorType) { + COLOR_PALETTE -> { + val table = ByteArray(entries * 4) + for (index in 0 until entries) { + val paletteOffset = index * 3 + // An index past the palette's end stays black. + if (palette != null && paletteOffset + 2 < palette.size) { + table[index * 4] = palette[paletteOffset] + table[index * 4 + 1] = palette[paletteOffset + 1] + table[index * 4 + 2] = palette[paletteOffset + 2] + } + // PNG spec §11.3.2.1 tRNS for palette: one alpha byte per entry; unlisted entries are opaque. + table[index * 4 + 3] = if (transparency != null && index < transparency.size) transparency[index] else OPAQUE + } + table + } + + COLOR_GRAYSCALE -> { + val table = ByteArray(entries * 4) + val maximumSample = entries - 1 + for (sample in 0 until entries) { + // PNG spec §12.5 linear scaling up to 8 bits; 255 is a multiple of 1, 3, and 15, + // so the equation's rounding never comes into play. + val gray = (sample * 255 / maximumSample).toByte() + table[sample * 4] = gray + table[sample * 4 + 1] = gray + table[sample * 4 + 2] = gray + table[sample * 4 + 3] = if (sample == keyGray) 0 else OPAQUE + } + table + } + + else -> null + } + } + + /** + * Writes one reconstructed scanline's pixels into [rgba]. + * + * @param ByteArray scanline The reconstructed row bytes. + * @param Int pixelCount Pixels in the row. + * @param ByteArray rgba The destination full-image RGBA buffer. + * @param Int destinationStart Byte offset in [rgba] of the row's first pixel. + * @param Int destinationStep Bytes between the row's consecutive pixels in [rgba]: 4, or a + * multiple of it for an Adam7 pass. + */ + fun expand(scanline: ByteArray, pixelCount: Int, rgba: ByteArray, destinationStart: Int, destinationStep: Int) { + val table = sampleColors + if (table != null) { + expandFromTable(table, scanline, pixelCount, rgba, destinationStart, destinationStep) + } else if (header.colorType == COLOR_RGBA && header.bitDepth == 8) { + expandRgba8(scanline, pixelCount, rgba, destinationStart, destinationStep) + } else { + expandSamples(scanline, pixelCount, rgba, destinationStart, destinationStep) + } + } + + /** + * Expands a palette or low-depth grayscale scanline by table lookup. + * + * @param ByteArray table Four RGBA bytes per sample value. + * @param ByteArray scanline The reconstructed row bytes. + * @param Int pixelCount Pixels in the row. + * @param ByteArray rgba The destination full-image RGBA buffer. + * @param Int destinationStart Byte offset in [rgba] of the row's first pixel. + * @param Int destinationStep Bytes between the row's consecutive pixels in [rgba]. + */ + private fun expandFromTable(table: ByteArray, scanline: ByteArray, pixelCount: Int, rgba: ByteArray, destinationStart: Int, destinationStep: Int) { + val bitDepth = header.bitDepth + val sampleMask = (1 shl bitDepth) - 1 + var destination = destinationStart + for (pixelIndex in 0 until pixelCount) { + val sample = + if (bitDepth == 8) { + scanline[pixelIndex].toInt() and 0xFF + } else { + // PNG spec §7.2: samples under 8 bits pack leftmost-first from each byte's high-order bits. + val bitIndex = pixelIndex * bitDepth + (scanline[bitIndex ushr 3].toInt() ushr (8 - bitDepth - (bitIndex and 7))) and sampleMask + } + val tableOffset = sample * 4 + rgba[destination] = table[tableOffset] + rgba[destination + 1] = table[tableOffset + 1] + rgba[destination + 2] = table[tableOffset + 2] + rgba[destination + 3] = table[tableOffset + 3] + destination += destinationStep + } + } + + /** + * Expands an 8-bit RGBA scanline, which is already in the output layout: one copy for a full + * row, four bytes per pixel for an Adam7 pass. + * + * @param ByteArray scanline The reconstructed row bytes. + * @param Int pixelCount Pixels in the row. + * @param ByteArray rgba The destination full-image RGBA buffer. + * @param Int destinationStart Byte offset in [rgba] of the row's first pixel. + * @param Int destinationStep Bytes between the row's consecutive pixels in [rgba]. + */ + private fun expandRgba8(scanline: ByteArray, pixelCount: Int, rgba: ByteArray, destinationStart: Int, destinationStep: Int) { + if (destinationStep == 4) { + scanline.copyInto(rgba, destinationStart, 0, pixelCount * 4) + return + } + var source = 0 + var destination = destinationStart + for (pixelIndex in 0 until pixelCount) { + rgba[destination] = scanline[source] + rgba[destination + 1] = scanline[source + 1] + rgba[destination + 2] = scanline[source + 2] + rgba[destination + 3] = scanline[source + 3] + source += 4 + destination += destinationStep + } + } + + /** + * Expands the remaining layouts sample by sample: 8-bit grayscale+alpha and RGB, and every + * 16-bit layout. tRNS keys compare against the raw samples before any rescaling, as PNG spec + * §13.12 requires. + * + * @param ByteArray scanline The reconstructed row bytes. + * @param Int pixelCount Pixels in the row. + * @param ByteArray rgba The destination full-image RGBA buffer. + * @param Int destinationStart Byte offset in [rgba] of the row's first pixel. + * @param Int destinationStep Bytes between the row's consecutive pixels in [rgba]. + */ + private fun expandSamples(scanline: ByteArray, pixelCount: Int, rgba: ByteArray, destinationStart: Int, destinationStep: Int) { + val channels = header.channels + val sixteenBit = header.bitDepth == 16 + val sampleBytes = if (sixteenBit) 2 else 1 + val pixelBytes = channels * sampleBytes + var source = 0 + var destination = destinationStart + for (pixelIndex in 0 until pixelCount) { + val first = sampleAt(scanline, source, sixteenBit) + if (channels >= 3) { + val green = sampleAt(scanline, source + sampleBytes, sixteenBit) + val blue = sampleAt(scanline, source + 2 * sampleBytes, sixteenBit) + rgba[destination] = toEightBits(first, sixteenBit) + rgba[destination + 1] = toEightBits(green, sixteenBit) + rgba[destination + 2] = toEightBits(blue, sixteenBit) + rgba[destination + 3] = + if (channels == 4) { + toEightBits(sampleAt(scanline, source + 3 * sampleBytes, sixteenBit), sixteenBit) + } else if (first == keyRed && green == keyGreen && blue == keyBlue) { + 0 + } else { + OPAQUE + } + } else { + val gray = toEightBits(first, sixteenBit) + rgba[destination] = gray + rgba[destination + 1] = gray + rgba[destination + 2] = gray + rgba[destination + 3] = + if (channels == 2) { + toEightBits(sampleAt(scanline, source + sampleBytes, sixteenBit), sixteenBit) + } else if (first == keyGray) { + 0 + } else { + OPAQUE + } + } + source += pixelBytes + destination += destinationStep + } + } + } + + /** + * Reads one raw 8- or 16-bit sample from a reconstructed scanline. + * + * @param ByteArray scanline The reconstructed row bytes. + * @param Int offset Offset of the sample's first byte. + * @param Boolean sixteenBit Whether samples are 16-bit (big-endian, PNG spec §7.2) rather than 8-bit. + * @return Int The raw sample value. + */ + private fun sampleAt(scanline: ByteArray, offset: Int, sixteenBit: Boolean): Int = + if (sixteenBit) { + ((scanline[offset].toInt() and 0xFF) shl 8) or (scanline[offset + 1].toInt() and 0xFF) + } else { + scanline[offset].toInt() and 0xFF + } + + /** + * Converts a raw 8- or 16-bit sample to the 8-bit output value. + * + * A 16-bit sample is rescaled by PNG spec §13.12's linear equation, + * floor(sample * 255 / 65535 + 0.5). The multiply-and-shift form below equals it for every 16-bit + * input, and needs no division. + * + * @param Int sample The raw sample value. + * @param Boolean sixteenBit Whether [sample] is 16-bit. + * @return Byte The 8-bit value. + */ + private fun toEightBits(sample: Int, sixteenBit: Boolean): Byte = + if (sixteenBit) { + ((sample * 255 + 32895) ushr 16).toByte() + } else { + sample.toByte() + } + + /** + * Reads a big-endian unsigned 16-bit value (tRNS stores each key sample this way). + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the most-significant byte. + * @return Int The value in 0..65535. + */ + private fun readU16(bytes: ByteArray, at: Int): Int = + ((bytes[at].toInt() and 0xFF) shl 8) or (bytes[at + 1].toInt() and 0xFF) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/png/PngFilters.kt b/module/format/src/commonMain/kotlin/org/umamo/format/png/PngFilters.kt new file mode 100644 index 0000000..25d8058 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/png/PngFilters.kt @@ -0,0 +1,99 @@ +package org.umamo.format.png + +/* + * PNG scanline filtering (PNG spec §9 Filtering). Each decoded scanline is preceded by a filter-type + * byte; the filter predicts each byte from already-reconstructed neighbours and stores the residual, + * so decoding adds the prediction back. All arithmetic is modulo 256 (byte truncation). + */ + +// PNG spec §9.2 Filter types. +internal const val FILTER_NONE = 0 +internal const val FILTER_SUB = 1 +internal const val FILTER_UP = 2 +internal const val FILTER_AVERAGE = 3 +internal const val FILTER_PAETH = 4 + +/** + * Reconstructs one scanline in place, undoing the filter of type [filterType]. + * + * The bytes of the first pixel have no left neighbor (PNG spec §9.2 treats it as zero), so each + * filter handles them in a loop of their own and the main loop runs without a per-byte bounds test. + * + * @param Int filterType The filter byte (0=None, 1=Sub, 2=Up, 3=Average, 4=Paeth). + * @param ByteArray current The filtered bytes of this scanline; overwritten with the reconstruction. + * @param ByteArray previous The already-reconstructed previous scanline (all zero for the first row). + * @param Int bytesPerPixel The filter stride: bytes per complete pixel, rounded up to at least 1. + */ +internal fun unfilterScanline(filterType: Int, current: ByteArray, previous: ByteArray, bytesPerPixel: Int) { + val length = current.size + val firstPixelEnd = minOf(bytesPerPixel, length) + when (filterType) { + FILTER_NONE -> { + // Recon(x) = Filt(x). + } + + FILTER_SUB -> { + // Recon(x) = Filt(x) + Recon(a); the first pixel's left neighbor is zero. + for (index in bytesPerPixel until length) { + current[index] = (current[index] + current[index - bytesPerPixel]).toByte() + } + } + + FILTER_UP -> { + // Recon(x) = Filt(x) + Recon(b). + for (index in 0 until length) { + current[index] = (current[index] + previous[index]).toByte() + } + } + + FILTER_AVERAGE -> { + // Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2), over unsigned bytes. + for (index in 0 until firstPixelEnd) { + current[index] = (current[index] + ((previous[index].toInt() and 0xFF) ushr 1)).toByte() + } + for (index in bytesPerPixel until length) { + val left = current[index - bytesPerPixel].toInt() and 0xFF + val above = previous[index].toInt() and 0xFF + current[index] = (current[index] + ((left + above) ushr 1)).toByte() + } + } + + FILTER_PAETH -> { + // Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c)). With a and c both + // zero the predictor is always b, so the first pixel reduces to Up. + for (index in 0 until firstPixelEnd) { + current[index] = (current[index] + previous[index]).toByte() + } + for (index in bytesPerPixel until length) { + val left = current[index - bytesPerPixel].toInt() and 0xFF + val above = previous[index].toInt() and 0xFF + val aboveLeft = previous[index - bytesPerPixel].toInt() and 0xFF + current[index] = (current[index] + paethPredictor(left, above, aboveLeft)).toByte() + } + } + + else -> throw IllegalArgumentException("unknown PNG filter type $filterType") + } +} + +/** + * The Paeth predictor (PNG spec §9.4): picks the neighbour (left, above, or above-left) closest to + * the linear estimate left + above - aboveLeft. + * + * @param Int left The reconstructed byte to the left (a in the spec). + * @param Int above The reconstructed byte above (b in the spec). + * @param Int aboveLeft The reconstructed byte above-left (c in the spec). + * @return Int The predicted byte value (0..255). + */ +internal fun paethPredictor(left: Int, above: Int, aboveLeft: Int): Int { + // The spec's pa, pb, and pc with the estimate p = a + b - c substituted in: p - a = b - c, + // p - b = a - c, and p - c = a + b - 2c. + val distanceLeft = kotlin.math.abs(above - aboveLeft) + val distanceAbove = kotlin.math.abs(left - aboveLeft) + val distanceAboveLeft = kotlin.math.abs(left + above - aboveLeft - aboveLeft) + return when { + distanceLeft <= distanceAbove && distanceLeft <= distanceAboveLeft -> left + distanceAbove <= distanceAboveLeft -> above + else -> aboveLeft + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdLayerRecords.kt b/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdLayerRecords.kt new file mode 100644 index 0000000..31fa0c0 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdLayerRecords.kt @@ -0,0 +1,407 @@ +package org.umamo.format.psd + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.binary.ByteReader +import kotlin.math.abs + +/** + * The PSD file header plus the bits of the file structure the channel decoder needs. + * + * EN: Read from the 26-byte File Header. Canvas size and the per-layer pixel geometry both derive + * from depth and color mode, so they are surfaced here rather than guessed downstream. + * JA: PSD ファイルヘッダ(26 バイト)。キャンバスサイズと深度・カラーモードを公開する。 + * + * @see PSD.md §1 File Header + */ +internal data class PsdHeaderInfo( + val width: Int, + val height: Int, + // PSD: number of color channels including alpha (1..56). + val channels: Int, + // PSD: bits per channel - 1, 8, 16, or 32. + val depth: Int, + // PSD: color mode - 0=Bitmap, 1=Grayscale, 2=Indexed, 3=RGB, 4=CMYK, 7=Multichannel, 8=Duotone, 9=Lab. + val colorMode: Int, +) + +/** + * One entry of a layer's channel-info table: which channel it is and how many bytes its image-data + * block occupies (including the leading 2-byte compression code). + * + * PSD: channel id 0/1/2… are color channels (R/G/B for RGB, gray for grayscale, the palette index + * for indexed); -1 is the transparency (alpha) channel; -2/-3 are user/vector layer masks (no + * displayable color). + * + * @see PSD.md §4 Channel image data + */ +internal data class PsdChannelInfo( + val id: Int, + val length: Long, +) + +/** + * One raster layer mask's geometry, from the layer's mask data block: where its pixels sit, what + * value it takes outside them, and whether it applies at all. + * + * PSD: a mask channel's plane is sized to THIS rectangle, not the layer's, and the mask reads as + * [defaultColor] everywhere outside it. The rectangle is in canvas coordinates: Photoshop sets the + * "position relative to layer" flag on every mask in the corpus and writes canvas coordinates + * anyway, so the flag is recorded but never applied. + * + * @property LayerBounds bounds The mask's rectangle in canvas pixels (top-left origin, width and height). + * @property Int defaultColor The mask value (0 or 255) outside [bounds]. + * @property Boolean relativeToLayer The flags byte's bit 0, as stored; advisory only (see above). + * @property Boolean disabled Whether the mask is switched off (its channel is still stored). + */ +internal data class PsdLayerMask( + val bounds: LayerBounds, + val defaultColor: Int, + val relativeToLayer: Boolean, + val disabled: Boolean, +) + +/** + * Per-layer metadata read from a PSD's "Layer and Mask Information" section. + * + * We parse this ourselves rather than leaning on a library that keeps its layer structures private: + * the record headers that carry bounds/name/opacity/clipping/blend and the channel-info table are + * trivially and reliably walked here. [channelDataOffset] is the absolute file offset of this + * layer's channel image data, computed once all records are parsed (the channel data of every layer + * is stored sequentially after the records), so [PsdRaster] can seek straight to a layer's pixels. + * + * PSD のレイヤーレコードから取り出すメタデータ。チャンネルデータの絶対オフセットも保持する。 + * + * @see PSD.md §3 Layer records + */ +internal data class PsdLayerRecord( + val name: String, + val bounds: LayerBounds, + val opacity: Float, + val clipped: Boolean, + val blend: LayerBlend, + val visible: Boolean, + // PSD: section-divider kind from the lsct block - 0 = normal layer, 1 = open folder header, + // 2 = closed folder header, 3 = bounding divider (the hidden "" group end). + val dividerType: Int, + // PSD: true for a pass-through folder (blend mode key "pass"); only meaningful on folder records. + val passThrough: Boolean, + // PSD: the layer's Photoshop id from the lyid additional-layer-info block - stable across rename + // and reorder for the life of the layer; null when the writer omits lyid (some exporters do), in + // which case the reader falls back to a name+order identity. + val layerId: Int?, + // PSD: the raster layer mask stored in channel -2, or null when the layer has none. When a + // layer carries both a vector mask and a pixel mask, this describes the rasterized vector mask + // and [realUserMask] the pixel one. + val userMask: PsdLayerMask?, + // PSD: the pixel mask stored in channel -3 when the mask data block carries its "real" rectangle + // (a layer with both a vector and a pixel mask); null otherwise. + val realUserMask: PsdLayerMask?, + // PSD: this layer's channels, in storage order; their lengths drive the channel-data layout. + val channels: List, + // Absolute file offset of this layer's channel image data (assigned after all records are read). + val channelDataOffset: Int, +) + +/** + * The whole of a PSD relevant to art ingestion: the header, the (optional) indexed palette, and the + * per-layer records with their channel-data offsets. + * + * @see PSD.md + */ +internal data class PsdParse( + val header: PsdHeaderInfo, + // PSD: Color Mode Data section bytes - the 768-byte (256 x RGB) palette for indexed-color files, + // non-interleaved (all reds, then all greens, then all blues). Empty for every other color mode. + val colorModeData: ByteArray, + val records: List, +) + +internal object PsdLayerRecords { + /** + * Reads the header, color-mode data, and every layer record, then assigns each record the + * absolute offset of its channel image data. Records are returned in PSD storage order + * (bottom-most layer first), matching the order the channel data is stored in. + * + * @param ByteArray bytes The complete `.psd` file. + * @return PsdParse The header, palette, and per-layer records with channel-data offsets. + */ + fun parse(bytes: ByteArray): PsdParse { + // ByteReader defaults to big-endian, which is exactly PSD's byte order - no manual swaps. + val buffer = ByteReader(bytes) + + // PSD: File Header - signature '8BPS', version, reserved(6), channels, height, width, depth, mode. + val signature = buffer.readAscii(4) + require(signature == "8BPS") { "not a PSD file (signature='$signature')" } + val version = buffer.readU16() + // PSD: version 1 = PSD, version 2 = PSB (large document). PSB widens the channel-length and + // section-length fields to 64-bit, which this parser does not handle, so reject it cleanly. + require(version == 1) { "PSB (PSD version 2) is not supported; only version 1" } + buffer.position = 12 // skip the 6 reserved bytes after the version + val channels = buffer.readU16() + val height = buffer.readU32AsInt() + val width = buffer.readU32AsInt() + val depth = buffer.readU16() + val colorMode = buffer.readU16() + val header = PsdHeaderInfo(width = width, height = height, channels = channels, depth = depth, colorMode = colorMode) + + // PSD: Color Mode Data section (u32 length + data) - holds the indexed palette; empty otherwise. + val colorModeLength = buffer.readU32AsInt() + val colorModeData = buffer.readBytes(colorModeLength) + + skipLengthPrefixed(buffer) // PSD: Image Resources section (u32 length + data) - not needed here + + buffer.readU32AsInt() // PSD: Layer and Mask Information section length (unused here) + buffer.readU32AsInt() // PSD: Layer Info length (unused here) + + // PSD: layer count, signed i16; a negative value means the first alpha channel holds the + // merged transparency - irrelevant to record parsing, so take the magnitude. + val layerCount = abs(buffer.readI16()) + + val records = ArrayList(layerCount) + repeat(layerCount) { + // PSD: layer rectangle, top/left/bottom/right as i32 (top-left origin). + val top = buffer.readU32AsInt() + val left = buffer.readU32AsInt() + val bottom = buffer.readU32AsInt() + val right = buffer.readU32AsInt() + + // PSD: channel count (u16), then that many channel-info records of (id i16, length u32). + val channelCount = buffer.readU16() + val channelInfos = ArrayList(channelCount) + repeat(channelCount) { + val channelId = buffer.readI16() // signed: 0/1/2… color, -1 alpha, -2/-3 masks + val channelLength = buffer.readU32() // u32 byte length of the data block + channelInfos += PsdChannelInfo(id = channelId, length = channelLength) + } + + val blendSignature = buffer.readAscii(4) // PSD: must be '8BIM' + require(blendSignature == "8BIM") { "bad layer blend signature '$blendSignature'" } + val blendKey = buffer.readAscii(4) // PSD: 4-char blend mode key, e.g. 'norm' + val opacityByte = buffer.readU8() // PSD: opacity 0..255 + val clipping = buffer.readU8() // PSD: clipping, 0=base, 1=non-base (clipped) + // PSD: layer-record flags @ +0x0B; bit 1 (0x02) set means the layer is hidden (eye off). + val flags = buffer.readU8() + buffer.readU8() // PSD: filler (unused) + + // PSD: extra data length (u32) bounds the mask + ranges + name + any additional info. + val extraLength = buffer.readU32AsInt() + val extraDataStart = buffer.position + val extraDataEnd = extraDataStart + extraLength + // PSD: folder membership is carried by lsct (Section Divider Setting) in the additional + // layer info, scanned out of the whole extra region before we consume mask/ranges/name. + val dividerType = findAdditionalInfoInt(buffer, extraDataStart, extraDataEnd, "lsct") ?: 0 + // PSD: the lyid block carries Photoshop's stable per-layer id (absent when the writer omits it). + val layerId = findAdditionalInfoInt(buffer, extraDataStart, extraDataEnd, "lyid") + val (userMask, realUserMask) = readLayerMaskData(buffer) + skipLengthPrefixed(buffer) // PSD: layer blending ranges + val nameLength = buffer.readU8() // PSD: legacy Pascal-string name length + // The name is user text, not a tag: decode UTF-8, never readAscii (which is US-ASCII and + // would turn every byte of a Japanese layer name into U+FFFD). UTF-8 is what Photoshop + // writes here in practice; the strictly-correct source is the Unicode name in the luni + // additional-info block, which this parser does not read yet. + val name = buffer.readBytes(nameLength).decodeToString() + buffer.position = extraDataEnd // skip past any additional layer-info blocks we don't read + + records += + PsdLayerRecord( + name = name, + bounds = LayerBounds(left = left, top = top, width = right - left, height = bottom - top), + opacity = opacityByte / 255f, + clipped = clipping != 0, + blend = blendKeyToBlend(blendKey), + visible = (flags and 0x02) == 0, + dividerType = dividerType, + // PSD: a folder header's blend mode key is "pass" exactly when the folder is pass-through. + passThrough = blendKey == "pass", + layerId = layerId, + userMask = userMask, + realUserMask = realUserMask, + channels = channelInfos, + channelDataOffset = 0, // placeholder; filled in below once the data start is known + ) + } + + // PSD: the channel image data of every layer follows all the records, stored sequentially in + // the same order. The cursor now sits at the first layer's channel data, so walk the records + // accumulating channel-block lengths to give each layer its own absolute data offset. + var channelDataCursor = buffer.position.toLong() + val withOffsets = + records.map { record -> + val recordOffset = channelDataCursor.toInt() + channelDataCursor += record.channels.sumOf { channel -> channel.length } + record.copy(channelDataOffset = recordOffset) + } + + return PsdParse(header = header, colorModeData = colorModeData, records = withOffsets) + } + + /** + * Reads a layer record's Layer Mask / Adjustment Layer Data block, leaving the cursor just past it. + * + * PSD: u32 size (0 = no mask), then the mask rectangle (i32 top / left / bottom / right), a u8 + * default color (0 or 255), and a u8 flags byte - bit 0 = rectangle relative to the layer, bit 1 = + * mask disabled, bit 4 = mask parameters follow (a flags byte, then a u8 density and / or an f64 + * feather for the user and the vector mask as its bits say). A 20-byte block ends with 2 bytes of + * padding; a longer one carries the "real" user mask instead - u8 real flags, u8 real background, + * and the real rectangle - which describes the pixel mask (channel -3) when a vector mask (whose + * rasterization is channel -2) sits beside it. + * + * @param ByteReader buffer The reader, positioned at the block's size field. + * @return Pair The channel -2 mask and the channel -3 mask, either null when absent. + */ + private fun readLayerMaskData(buffer: ByteReader): Pair { + val size = buffer.readU32AsInt() + val end = buffer.position + size + if (size < 20) { + buffer.position = end + return null to null + } + val userMask = readMaskGeometry(buffer) + if ((userMask.flagsBits and 0x10) != 0) { + val parameterFlags = buffer.readU8() + if ((parameterFlags and 0x01) != 0) { + buffer.position += 1 + } + if ((parameterFlags and 0x02) != 0) { + buffer.position += 8 + } + if ((parameterFlags and 0x04) != 0) { + buffer.position += 1 + } + if ((parameterFlags and 0x08) != 0) { + buffer.position += 8 + } + } + var realUserMask: PsdLayerMask? = null + if (end - buffer.position >= 18) { + // PSD: real flags, real user mask background, real rectangle - the pixel mask's own geometry. + val realFlags = buffer.readU8() + val realBackground = buffer.readU8() + val realTop = buffer.readU32().toInt() + val realLeft = buffer.readU32().toInt() + val realBottom = buffer.readU32().toInt() + val realRight = buffer.readU32().toInt() + realUserMask = + PsdLayerMask( + bounds = LayerBounds(left = realLeft, top = realTop, width = realRight - realLeft, height = realBottom - realTop), + defaultColor = realBackground, + relativeToLayer = (realFlags and 0x01) != 0, + disabled = (realFlags and 0x02) != 0, + ) + } + buffer.position = end + return userMask.mask to realUserMask + } + + /** A parsed mask rectangle with the raw flags byte, so the caller can read the parameter bit. */ + private class MaskGeometry(val mask: PsdLayerMask, val flagsBits: Int) + + /** + * Reads one mask geometry: the rectangle, the default color, and the flags. + * + * @param ByteReader buffer The reader, positioned at the rectangle's top field. + * @return MaskGeometry The mask plus its raw flags. + */ + private fun readMaskGeometry(buffer: ByteReader): MaskGeometry { + // PSD: the rectangle is signed - a mask can sit partly off the canvas. + val top = buffer.readU32().toInt() + val left = buffer.readU32().toInt() + val bottom = buffer.readU32().toInt() + val right = buffer.readU32().toInt() + val defaultColor = buffer.readU8() + val flags = buffer.readU8() + return MaskGeometry( + PsdLayerMask( + bounds = LayerBounds(left = left, top = top, width = right - left, height = bottom - top), + defaultColor = defaultColor, + relativeToLayer = (flags and 0x01) != 0, + disabled = (flags and 0x02) != 0, + ), + flags, + ) + } + + /** + * Scans a layer record's extra-data region for an additional-layer-info block with the given + * 4-char [key] and returns the u32 right after the block's length field, or null when the key is + * absent. Used for both lsct (the Section Divider Setting / folder type) and lyid (the stable + * Photoshop layer id). + * + * The additional layer info is a run of blocks, each a 4-char signature ('8BIM' or '8B64'), a + * 4-char key, a u32 length, then that many data bytes - but the data padding varies by writer, so + * rather than walk block lengths we scan for the key behind a valid signature (the 8-byte + * signature+key prefix makes a false match in mask/range/name bytes effectively impossible). All + * reads here are absolute so the caller's cursor is left untouched. + * + * @param ByteReader buffer The whole-file reader. + * @param Int regionStart First byte of the extra-data region. + * @param Int regionEnd One past the last byte of the extra-data region. + * @param String key The 4-char block key to find (e.g. "lsct", "lyid"). + * @return Int the u32 after the matched block's length field, or null when [key] is absent. + */ + private fun findAdditionalInfoInt(buffer: ByteReader, regionStart: Int, regionEnd: Int, key: String): Int? { + var scanPosition = regionStart + // Need 16 bytes available: signature(4) + key(4) + length(4) + value(4). + while (scanPosition + 16 <= regionEnd) { + val signature = buffer.asciiAt(scanPosition, 4) + if ((signature == "8BIM" || signature == "8B64") && buffer.asciiAt(scanPosition + 4, 4) == key) { + return buffer.u32AsInt(scanPosition + 12) // the u32 right after the block's length field + } + scanPosition++ + } + return null + } + + /** + * Reads a u32-length-prefixed block and advances the cursor past its payload. + * + * @param ByteReader buffer Positioned at the 4-byte length field. + */ + private fun skipLengthPrefixed(buffer: ByteReader) { + val length = buffer.readU32AsInt() + buffer.position += length + } + + /** + * Maps a PSD 4-char blend-mode key to our [LayerBlend]. + * + * The keys are the space-padded 4-char codes Photoshop writes (PSD.java BLEND_*). Keys with no + * neutral-model equivalent (Dissolve) and any unknown key degrade to [LayerBlend.Normal]; "pass" + * (folder pass-through) is handled separately by the caller and also reads as Normal here. + * + * @param String key The 4-character blend mode key (e.g. `"norm"`, `"mul "`). + * @return LayerBlend the matching mode, or Normal. + */ + private fun blendKeyToBlend(key: String): LayerBlend = + // PSD: blend mode keys (Adobe Photoshop File Format, "Blend mode key"); see PSD.java BLEND_*. + when (key) { + "norm" -> LayerBlend.Normal + "dark" -> LayerBlend.Darken + "mul " -> LayerBlend.Multiply + "idiv" -> LayerBlend.ColorBurn // PSD "idiv" = Color Burn + "lbrn" -> LayerBlend.LinearBurn + "dkCl" -> LayerBlend.DarkerColor + "lite" -> LayerBlend.Lighten + "scrn" -> LayerBlend.Screen + "div " -> LayerBlend.ColorDodge + "lddg" -> LayerBlend.Add // linear dodge (add) + "lgCl" -> LayerBlend.LighterColor + "over" -> LayerBlend.Overlay + "sLit" -> LayerBlend.SoftLight + "hLit" -> LayerBlend.HardLight + "vLit" -> LayerBlend.VividLight + "lLit" -> LayerBlend.LinearLight + "pLit" -> LayerBlend.PinLight + "hMix" -> LayerBlend.HardMix + "diff" -> LayerBlend.Difference + "smud" -> LayerBlend.Exclusion // PSD "smud" = Exclusion + "fsub" -> LayerBlend.Subtract + "fdiv" -> LayerBlend.Divide + "hue " -> LayerBlend.Hue + "sat " -> LayerBlend.Saturation + "colr" -> LayerBlend.Color + "lum " -> LayerBlend.Luminosity + else -> LayerBlend.Normal + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdRaster.kt b/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdRaster.kt new file mode 100644 index 0000000..a37717f --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdRaster.kt @@ -0,0 +1,535 @@ +// Ported from TwelveMonkeys imageio-psd (BSD-3-Clause, Copyright (c) 2013-2020 Harald Kuhr). +// The channel decompression (PackBits RLE, ZIP, ZIP-with-prediction) and the per-depth/per-mode +// sample assembly follow PSDImageReader, PSDUtil, and HorizontalDeDifferencingStream. See CREDITS.md. + +package org.umamo.format.psd + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.format.binary.inflateZlib + +/** + * Decodes one PSD layer's channel image data into a straight-alpha RGBA8888 [LayerRaster]. + * + * A pure-Kotlin pixel decoder, needed because TwelveMonkeys / javax.imageio is absent on + * Android. A layer's pixels are stored as separate + * channel planes (R, G, B, alpha, …), each independently compressed; this object decompresses + * each plane, reduces it to 8 bits, and interleaves them to RGBA cropped to the layer bounds. + * A raster layer mask (channel -2, and -3 beside a vector mask) is decoded at its own rectangle + * and multiplied into the alpha, so the raster is the layer as the artist sees it - the same + * baking the CLIP reader applies. Supported: 8/16-bit RGB(A) and Grayscale, Indexed-color, and + * 1-bit Bitmap. CMYK, Lab, Multichannel, Duotone, and 32-bit float are rejected by + * [PsdReader] before reaching here. + * + * @see PSD.md §4 Channel image data + */ +internal object PsdRaster { + // PSD: channel image-data compression codes (PSD.java COMPRESSION_*). + private const val COMPRESSION_NONE = 0 + private const val COMPRESSION_RLE = 1 + private const val COMPRESSION_ZIP = 2 + private const val COMPRESSION_ZIP_PREDICTION = 3 + + // PSD: color modes (PSD.java COLOR_MODE_*). + private const val MODE_BITMAP = 0 + private const val MODE_GRAYSCALE = 1 + private const val MODE_INDEXED = 2 + private const val MODE_RGB = 3 + + // PSD: channel ids - color channels are 0/1/2…; -1 is the transparency (alpha) channel; -2 is the + // user layer mask (the rasterized vector mask when a pixel mask sits beside it), -3 that pixel mask. + private const val CHANNEL_RED = 0 + private const val CHANNEL_GREEN = 1 + private const val CHANNEL_BLUE = 2 + private const val CHANNEL_ALPHA = -1 + private const val CHANNEL_USER_MASK = -2 + private const val CHANNEL_REAL_USER_MASK = -3 + + private const val OPAQUE = 0xFF.toByte() + + /** + * Decodes [record]'s channels and assembles them into an RGBA8888 raster sized to the layer's + * bounds (top row first, straight alpha). + * + * @param ByteArray bytes The complete `.psd` file. + * @param PsdHeaderInfo header The file header (depth and color mode drive the decode). + * @param ByteArray colorModeData The Color Mode Data bytes (the indexed palette; empty otherwise). + * @param PsdLayerRecord record The layer to decode, carrying its channel-data offset. + * @return LayerRaster The cropped, straight-alpha RGBA pixels. + */ + fun decodeLayer(bytes: ByteArray, header: PsdHeaderInfo, colorModeData: ByteArray, record: PsdLayerRecord): LayerRaster { + val width = record.bounds.width + val height = record.bounds.height + if (width <= 0 || height <= 0) { + // A layer with no pixel area (an empty paint layer or a structural record): nothing to decode. + return LayerRaster(width = width.coerceAtLeast(0), height = height.coerceAtLeast(0), rgba = ByteArray(0)) + } + + val rowBytes = bytesPerRow(width, header.depth) + val decoded = decodePlanes(bytes, record, width, height, header.depth, rowBytes) + val planes = decoded.color + + val rgba = ByteArray(width * height * 4) + when (header.colorMode) { + MODE_RGB -> assembleRgb(planes, rgba, width * height) + MODE_GRAYSCALE -> assembleGrayscale(planes, rgba, width * height) + MODE_INDEXED -> assembleIndexed(planes, colorModeData, rgba, width * height) + MODE_BITMAP -> assembleBitmap(planes, rgba, width * height) + else -> error("PSD color mode ${header.colorMode} is not supported") + } + for (maskPlane in decoded.masks) { + applyMask(rgba, width, height, record.bounds, maskPlane) + } + return LayerRaster(width = width, height = height, rgba = rgba) + } + + /** + * One decoded mask: its geometry and its plane, sized to the mask's own rectangle. + * + * @property PsdLayerMask mask The mask's rectangle, default color, and flags. + * @property ByteArray plane The mask values, row-major over the mask rectangle. + */ + private class MaskPlane(val mask: PsdLayerMask, val plane: ByteArray) + + /** + * A layer's decoded planes: the displayable color channels by id, and every enabled mask. + * + * @property Map color The color and alpha planes by channel id, each width*height of the layer. + * @property List masks The enabled raster masks, each over its own rectangle. + */ + private class DecodedPlanes(val color: Map, val masks: List) + + /** + * Multiplies one mask into the raster's alpha: inside the mask rectangle the stored value, outside + * it the mask's default color, so a mask that hides everything beyond its rectangle does exactly + * that. The rectangle is always read as canvas-placed: Photoshop sets the "relative to layer" + * flag on every mask in the corpus while still writing canvas coordinates, and offsetting by the + * layer as the flag suggests throws the mask clear of its layer (every masked layer then decodes + * fully transparent). + * + * @param ByteArray rgba The layer's RGBA8888 pixels, modified in place. + * @param Int width The layer width in pixels. + * @param Int height The layer height in pixels. + * @param LayerBounds layerBounds The layer's canvas rectangle (locates the mask against it). + * @param MaskPlane maskPlane The mask to apply. + */ + private fun applyMask(rgba: ByteArray, width: Int, height: Int, layerBounds: LayerBounds, maskPlane: MaskPlane) { + val mask = maskPlane.mask + val plane = maskPlane.plane + val maskWidth = mask.bounds.width + val maskHeight = mask.bounds.height + // The mask rectangle's origin in LAYER pixel coordinates. + val originX = mask.bounds.left - layerBounds.left + val originY = mask.bounds.top - layerBounds.top + for (row in 0 until height) { + val maskRow = row - originY + val rowInside = maskRow in 0 until maskHeight + for (column in 0 until width) { + val maskColumn = column - originX + val value = + if (rowInside && maskColumn in 0 until maskWidth) { + plane[maskRow * maskWidth + maskColumn].toInt() and 0xFF + } else { + mask.defaultColor + } + if (value == 0xFF) { + continue + } + val alphaIndex = (row * width + column) * 4 + 3 + val alpha = rgba[alphaIndex].toInt() and 0xFF + rgba[alphaIndex] = ((alpha * value + 127) / 255).toByte() + } + } + } + + /** + * Decompresses every channel of [record] into an 8-bit-per-pixel plane: the displayable channels + * keyed by id at the layer's size, and each enabled mask channel at its own mask rectangle's size. + * A mask channel whose record describes no mask, or a disabled one, is skipped; the cursor advances + * by each channel's full block length regardless, keeping the channels sequential. + * + * @param ByteArray bytes The complete `.psd` file. + * @param PsdLayerRecord record The layer whose channels to decode. + * @param Int width Layer width in pixels. + * @param Int height Layer height in pixels. + * @param Int depth Bits per sample (1, 8, or 16). + * @param Int rowBytes Bytes per decoded channel row for this width and depth. + * @return DecodedPlanes The color planes and the enabled masks. + */ + private fun decodePlanes(bytes: ByteArray, record: PsdLayerRecord, width: Int, height: Int, depth: Int, rowBytes: Int): DecodedPlanes { + val planes = HashMap(record.channels.size) + val masks = ArrayList(2) + var cursor = record.channelDataOffset + for (channel in record.channels) { + val blockStart = cursor + val blockEnd = blockStart + channel.length.toInt() + cursor = blockEnd + // PSD: each channel block begins with a 2-byte compression code, then the (possibly + // compressed) sample bytes for that one channel. + if (channel.id < CHANNEL_ALPHA) { + // PSD: channel -2 is the user layer mask and -3 the real user mask; each is sized to the + // rectangle its mask geometry records, not to the layer. + val mask = + when (channel.id) { + CHANNEL_USER_MASK -> record.userMask + CHANNEL_REAL_USER_MASK -> record.realUserMask + else -> null + } + if (mask == null || mask.disabled || mask.bounds.width <= 0 || mask.bounds.height <= 0) { + continue + } + val maskRowBytes = bytesPerRow(mask.bounds.width, depth) + val compression = readU16BE(bytes, blockStart) + val samples = decodeChannel(bytes, blockStart + 2, blockEnd, compression, mask.bounds.width, mask.bounds.height, depth, maskRowBytes) + masks.add(MaskPlane(mask, samplesToPlane(samples, mask.bounds.width, mask.bounds.height, depth, maskRowBytes))) + continue + } + val compression = readU16BE(bytes, blockStart) + val samples = decodeChannel(bytes, blockStart + 2, blockEnd, compression, width, height, depth, rowBytes) + planes[channel.id] = samplesToPlane(samples, width, height, depth, rowBytes) + } + return DecodedPlanes(planes, masks) + } + + /** + * Decompresses one channel's sample bytes (size height*rowBytes), per its compression code. + * + * @param ByteArray bytes The complete `.psd` file. + * @param Int dataStart Offset of the channel's sample data (just past the compression code). + * @param Int blockEnd One past the last byte of this channel's block. + * @param Int compression The PSD compression code (0=raw, 1=RLE, 2=ZIP, 3=ZIP+prediction). + * @param Int width Layer width in pixels. + * @param Int height Layer height in pixels. + * @param Int depth Bits per sample (1, 8, or 16). + * @param Int rowBytes Bytes per decoded row. + * @return ByteArray The raw, row-major sample bytes for this channel. + */ + private fun decodeChannel(bytes: ByteArray, dataStart: Int, blockEnd: Int, compression: Int, width: Int, height: Int, depth: Int, rowBytes: Int): ByteArray { + val total = height * rowBytes + return when (compression) { + COMPRESSION_NONE -> { + // PSD: raw, uncompressed sample bytes, exactly height*rowBytes. + val out = ByteArray(total) + val available = minOf(total, blockEnd - dataStart, bytes.size - dataStart) + if (available > 0) { + bytes.copyInto(out, 0, dataStart, dataStart + available) + } + out + } + + COMPRESSION_RLE -> decodeRle(bytes, dataStart, height, rowBytes) + COMPRESSION_ZIP -> inflate(bytes, dataStart, blockEnd - dataStart, total) + COMPRESSION_ZIP_PREDICTION -> { + val inflated = inflate(bytes, dataStart, blockEnd - dataStart, total) + // PSD: ZIP-with-prediction stores horizontal differences; un-apply per row, per sample. + horizontalUnpredict(inflated, width, height, depth, rowBytes) + inflated + } + + else -> error("unknown PSD compression $compression") + } + } + + /** + * Decodes a PackBits-RLE channel: a table of per-row compressed byte counts, then the runs. + * + * PSD: for layer channels, the byte counts (one u16 per row, top-to-bottom) directly precede the + * PackBits-encoded rows of this single channel. Each row decodes to exactly rowBytes. + * + * @param ByteArray bytes The complete `.psd` file. + * @param Int dataStart Offset of the row-count table. + * @param Int height Number of rows. + * @param Int rowBytes Decoded bytes per row. + * @return ByteArray The decoded, row-major sample bytes (height*rowBytes). + */ + private fun decodeRle(bytes: ByteArray, dataStart: Int, height: Int, rowBytes: Int): ByteArray { + var countCursor = dataStart + val rowCounts = IntArray(height) + for (rowIndex in 0 until height) { + rowCounts[rowIndex] = readU16BE(bytes, countCursor) + countCursor += 2 + } + + val out = ByteArray(height * rowBytes) + var rowCursor = countCursor + for (rowIndex in 0 until height) { + unpackBits(bytes, rowCursor, rowCounts[rowIndex], out, rowIndex * rowBytes, rowBytes) + rowCursor += rowCounts[rowIndex] + } + return out + } + + /** + * Apple PackBits run-length decode of one row. + * + * A control byte n: 0..127 copies the next n+1 bytes verbatim; -127..-1 repeats the next byte + * 1-n times; -128 is a no-op. All reads and writes are bounded so a corrupt run cannot overrun. + * + * @param ByteArray source The buffer holding the compressed bytes. + * @param Int sourceOffset Offset of this row's compressed data. + * @param Int sourceLength Compressed byte count for this row. + * @param ByteArray destination The decoded-output buffer. + * @param Int destinationOffset Offset of this row in the output. + * @param Int destinationLength Decoded bytes expected for this row (rowBytes). + */ + private fun unpackBits(source: ByteArray, sourceOffset: Int, sourceLength: Int, destination: ByteArray, destinationOffset: Int, destinationLength: Int) { + var sourceIndex = sourceOffset + val sourceEnd = minOf(sourceOffset + sourceLength, source.size) + var destinationIndex = destinationOffset + val destinationEnd = destinationOffset + destinationLength + while (sourceIndex < sourceEnd && destinationIndex < destinationEnd) { + val control = source[sourceIndex++].toInt() // signed + if (control >= 0) { + val literalCount = control + 1 + var copied = 0 + while (copied < literalCount && sourceIndex < sourceEnd && destinationIndex < destinationEnd) { + destination[destinationIndex++] = source[sourceIndex++] + copied++ + } + } else if (control != -128) { + val runCount = 1 - control + if (sourceIndex >= sourceEnd) { + break + } + val runValue = source[sourceIndex++] + var written = 0 + while (written < runCount && destinationIndex < destinationEnd) { + destination[destinationIndex++] = runValue + written++ + } + } + } + } + + /** + * Inflates a zlib stream of [length] bytes at [offset] into a buffer of [expected] bytes. + * + * PSD ZIP channels are standard zlib streams (header + Adler-32), so the shared platform bridge + * decodes them. A short or malformed stream yields a partially filled (zero-padded) buffer rather + * than throwing, mirroring [org.umamo.format.clip.ClipRaster]. + * + * @param ByteArray bytes The buffer holding the compressed stream. + * @param Int offset Offset of the zlib stream. + * @param Int length Compressed byte count. + * @param Int expected Decompressed byte count (height*rowBytes). + * @return ByteArray The inflated bytes, sized [expected]. + */ + private fun inflate(bytes: ByteArray, offset: Int, length: Int, expected: Int): ByteArray { + val inflated = inflateZlib(bytes, offset, length, expected) + if (inflated.size == expected) { + return inflated + } + // A short stream leaves the rest zero-filled; the layer is best-effort rather than a hard failure. + val out = ByteArray(expected) + inflated.copyInto(out, 0, 0, minOf(inflated.size, expected)) + return out + } + + /** + * Reverses the horizontal differencing predictor in place: each sample is the running sum of the + * differences along its row (per the TIFF 6.0 predictor, with one sample per pixel for planar + * channels). Only 8- and 16-bit samples occur with prediction in the supported color modes. + * + * @param ByteArray data The inflated, differenced sample bytes (modified in place). + * @param Int width Samples per row. + * @param Int height Row count. + * @param Int depth Bits per sample (8 or 16). + * @param Int rowBytes Bytes per row. + */ + private fun horizontalUnpredict(data: ByteArray, width: Int, height: Int, depth: Int, rowBytes: Int) { + when (depth) { + 8 -> { + for (rowIndex in 0 until height) { + val base = rowIndex * rowBytes + for (column in 1 until width) { + val offset = base + column + if (offset < data.size) { + data[offset] = (data[offset] + data[offset - 1]).toByte() + } + } + } + } + + 16 -> { + for (rowIndex in 0 until height) { + val base = rowIndex * rowBytes + for (column in 1 until width) { + val offset = base + column * 2 + if (offset + 1 < data.size) { + val previous = ((data[offset - 2].toInt() and 0xFF) shl 8) or (data[offset - 1].toInt() and 0xFF) + val current = ((data[offset].toInt() and 0xFF) shl 8) or (data[offset + 1].toInt() and 0xFF) + val sum = (previous + current) and 0xFFFF + data[offset] = (sum ushr 8).toByte() + data[offset + 1] = sum.toByte() + } + } + } + } + + else -> error("PSD ZIP prediction unsupported for $depth-bit samples") + } + } + + /** + * Reduces a channel's raw sample bytes to an 8-bit-per-pixel plane. + * + * 8-bit samples pass through; 16-bit samples keep the high (big-endian first) byte; 1-bit samples + * (Bitmap mode) expand to an intensity where a set bit is black (PSD's bitmap convention) - the + * Bitmap assembler reads this plane directly as gray. + * + * @param ByteArray samples The raw, row-major sample bytes. + * @param Int width Layer width in pixels. + * @param Int height Layer height in pixels. + * @param Int depth Bits per sample (1, 8, or 16). + * @param Int rowBytes Bytes per sample row (gives the 1-bit row stride). + * @return ByteArray A width*height plane of 8-bit values. + */ + private fun samplesToPlane(samples: ByteArray, width: Int, height: Int, depth: Int, rowBytes: Int): ByteArray { + val plane = ByteArray(width * height) + when (depth) { + 8 -> { + // rowBytes == width, so the samples are already a contiguous per-pixel plane. + val count = minOf(plane.size, samples.size) + samples.copyInto(plane, 0, 0, count) + } + + 16 -> { + for (pixelIndex in 0 until width * height) { + val sampleOffset = pixelIndex * 2 + if (sampleOffset < samples.size) { + plane[pixelIndex] = samples[sampleOffset] // big-endian high byte + } + } + } + + 1 -> { + for (rowIndex in 0 until height) { + val rowBase = rowIndex * rowBytes + for (column in 0 until width) { + val byteIndex = rowBase + (column ushr 3) + if (byteIndex < samples.size) { + val bit = (samples[byteIndex].toInt() ushr (7 - (column and 7))) and 1 + // PSD: in Bitmap mode a set bit is black; clear is white. + plane[rowIndex * width + column] = if (bit == 1) 0 else OPAQUE + } + } + } + } + + else -> error("PSD $depth-bit depth is not supported") + } + return plane + } + + /** + * Interleaves R/G/B planes (and the alpha plane, or opaque if absent) into RGBA8888. + * + * @param Map planes The decoded channel planes by id. + * @param ByteArray rgba The destination RGBA buffer. + * @param Int pixelCount Number of pixels (width*height). + */ + private fun assembleRgb(planes: Map, rgba: ByteArray, pixelCount: Int) { + val red = planes[CHANNEL_RED] + val green = planes[CHANNEL_GREEN] + val blue = planes[CHANNEL_BLUE] + val alpha = planes[CHANNEL_ALPHA] + for (pixelIndex in 0 until pixelCount) { + val destination = pixelIndex * 4 + rgba[destination] = red?.get(pixelIndex) ?: 0 + rgba[destination + 1] = green?.get(pixelIndex) ?: 0 + rgba[destination + 2] = blue?.get(pixelIndex) ?: 0 + rgba[destination + 3] = alpha?.get(pixelIndex) ?: OPAQUE + } + } + + /** + * Expands a single gray plane to R=G=B, with the alpha plane (or opaque if absent). + * + * @param Map planes The decoded channel planes by id. + * @param ByteArray rgba The destination RGBA buffer. + * @param Int pixelCount Number of pixels (width*height). + */ + private fun assembleGrayscale(planes: Map, rgba: ByteArray, pixelCount: Int) { + val gray = planes[CHANNEL_RED] // PSD: grayscale's single channel has id 0 + val alpha = planes[CHANNEL_ALPHA] + for (pixelIndex in 0 until pixelCount) { + val destination = pixelIndex * 4 + val value = gray?.get(pixelIndex) ?: 0 + rgba[destination] = value + rgba[destination + 1] = value + rgba[destination + 2] = value + rgba[destination + 3] = alpha?.get(pixelIndex) ?: OPAQUE + } + } + + /** + * Maps each palette index through the Color Mode Data table to RGB, with alpha (or opaque). + * + * PSD: the indexed palette is non-interleaved - all red bytes, then all green, then all blue - + * with paletteSize = colorModeData.length / 3 entries (typically 256). + * + * @param Map planes The decoded channel planes by id. + * @param ByteArray colorModeData The palette bytes. + * @param ByteArray rgba The destination RGBA buffer. + * @param Int pixelCount Number of pixels (width*height). + */ + private fun assembleIndexed(planes: Map, colorModeData: ByteArray, rgba: ByteArray, pixelCount: Int) { + val indices = planes[CHANNEL_RED] // PSD: the index channel has id 0 + val alpha = planes[CHANNEL_ALPHA] + val paletteSize = colorModeData.size / 3 + for (pixelIndex in 0 until pixelCount) { + val destination = pixelIndex * 4 + val paletteIndex = (indices?.get(pixelIndex)?.toInt() ?: 0) and 0xFF + if (paletteSize > 0 && paletteIndex < paletteSize) { + rgba[destination] = colorModeData[paletteIndex] + rgba[destination + 1] = colorModeData[paletteSize + paletteIndex] + rgba[destination + 2] = colorModeData[2 * paletteSize + paletteIndex] + } + rgba[destination + 3] = alpha?.get(pixelIndex) ?: OPAQUE + } + } + + /** + * Writes a 1-bit Bitmap plane as opaque gray (the plane already encodes black/white intensity). + * + * @param Map planes The decoded channel planes by id. + * @param ByteArray rgba The destination RGBA buffer. + * @param Int pixelCount Number of pixels (width*height). + */ + private fun assembleBitmap(planes: Map, rgba: ByteArray, pixelCount: Int) { + val value = planes[CHANNEL_RED] // PSD: bitmap's single channel has id 0 + for (pixelIndex in 0 until pixelCount) { + val destination = pixelIndex * 4 + val gray = value?.get(pixelIndex) ?: 0 + rgba[destination] = gray + rgba[destination + 1] = gray + rgba[destination + 2] = gray + rgba[destination + 3] = OPAQUE + } + } + + /** + * Bytes per decoded channel row for a given width and sample depth. + * + * @param Int width The row width in pixels. + * @param Int depth Bits per sample (1, 8, or 16). + * @return Int The packed/contiguous byte count for one row. + */ + private fun bytesPerRow(width: Int, depth: Int): Int = + when (depth) { + 1 -> (width + 7) / 8 // PSD: 1-bit rows are byte-padded. + 8 -> width + 16 -> width * 2 + else -> error("PSD $depth-bit depth is not supported") + } + + /** + * Reads a big-endian unsigned 16-bit integer. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the most-significant byte. + * @return Int The value in 0..65535. + */ + private fun readU16BE(bytes: ByteArray, at: Int): Int = + ((bytes[at].toInt() and 0xFF) shl 8) or (bytes[at + 1].toInt() and 0xFF) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdReader.kt new file mode 100644 index 0000000..9fc4dab --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/psd/PsdReader.kt @@ -0,0 +1,181 @@ +package org.umamo.format.psd + +import org.umamo.format.FileKind +import org.umamo.format.art.ArtReader +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer + +/** + * Pure-Kotlin PSD reader (desktop JVM and Android). + * + * EN: [PsdLayerRecords] walks the "Layer and Mask Information" section for each layer's metadata + * (bounds/opacity/clipping/blend/name/folder structure) and channel layout; [PsdRaster] decodes + * each layer's channel pixels to straight-alpha RGBA. Both use only java.nio and java.util.zip, + * which Android ships (unlike javax.imageio, which is desktop-only) - so this lives in + * jvmAndroidMain and lights up tablets too. + * JA: 純 Kotlin の PSD 読み込み。メタデータは [PsdLayerRecords]、ピクセルは [PsdRaster]。Android でも動作。 + * + * Scope: read-only; 8/16-bit RGB(A) and Grayscale, Indexed-color, and 1-bit Bitmap. CMYK, Lab, + * Multichannel, Duotone, and 32-bit float are rejected with a clear error. + * + * @see PSD.md + */ +object PsdReader : ArtReader { + override val kind: FileKind = FileKind.Psd + + // PSD: color modes we ingest (PSD.java COLOR_MODE_*); everything else is rejected up front. + private const val MODE_BITMAP = 0 + private const val MODE_GRAYSCALE = 1 + private const val MODE_INDEXED = 2 + private const val MODE_RGB = 3 + + /** + * True if [candidateBytes] starts with the PSD file signature. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the PSD magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean = isPsd(candidateBytes) + + /** + * Decodes a `.psd` into the neutral [SourceArt] model: every layer with its placement, flags, + * and decoded RGBA pixels, ordered bottom-to-top. + * + * @param ByteArray bytes The complete `.psd` file. + * @return SourceArt the canvas size and the parsed layers. + */ + override fun read(bytes: ByteArray): SourceArt { + val parse = PsdLayerRecords.parse(bytes) + val header = parse.header + + // Fail fast on color modes / depths the channel decoder does not handle, with a clear message + // rather than producing garbled pixels (CMYK/Lab need ICC color management we deliberately omit). + require(header.colorMode == MODE_BITMAP || header.colorMode == MODE_GRAYSCALE || header.colorMode == MODE_INDEXED || header.colorMode == MODE_RGB) { + "PSD color mode ${header.colorMode} is not supported (only Bitmap/Grayscale/Indexed/RGB; CMYK/Lab/Multichannel/Duotone rejected)" + } + require(header.depth == 1 || header.depth == 8 || header.depth == 16) { + "PSD ${header.depth}-bit depth is not supported (only 1/8/16; 32-bit float rejected)" + } + + // Walk records top-to-bottom (the reverse of bottom-to-top PSD storage) so a folder's named + // header - which sits at the top of its run - opens the group before its children, and the + // hidden bounding divider at the bottom closes it. Real layers carry the current stack path; + // folder markers are structural and are not emitted as drawable layers. + val groups = ArrayList() + val folderStack = ArrayDeque() + val layersTopToBottom = ArrayList() + var emittedOrder = 0 + for (recordIndex in parse.records.indices.reversed()) { + val record = parse.records[recordIndex] + when (record.dividerType) { + 1, 2 -> { + // Folder header (open/closed): name the group and push it onto the path stack. + val parentPath = folderStack.joinToString("/") + val path = if (parentPath.isEmpty()) record.name else "$parentPath/${record.name}" + folderStack.addLast(record.name) + groups += + PsdSourceGroup( + path = path, + name = record.name, + visible = record.visible, + opacity = record.opacity, + clipped = record.clipped, + blend = record.blend, + passThrough = record.passThrough, + ) + } + + 3 -> { + // Bounding divider (""): closes the innermost open folder. + if (folderStack.isNotEmpty()) { + folderStack.removeLast() + } + } + + else -> { + layersTopToBottom += + PsdSourceLayer( + // Stable identity: Photoshop's lyid (stable across rename/reorder) when present, else name+order. See docs/format/PSD.md. + id = record.layerId?.let { layerId -> LayerId("lyid:$layerId") } ?: LayerId("${record.name}#$recordIndex"), + idIsStable = record.layerId != null, + name = record.name, + visible = record.visible, + groupPath = folderStack.joinToString("/"), + order = emittedOrder++, // top-most emitted layer = 0 + bounds = record.bounds, + opacity = record.opacity, + clipped = record.clipped, + blend = record.blend, + raster = PsdRaster.decodeLayer(bytes, header, parse.colorModeData, record), + ) + } + } + } + // The compositor and re-import expect layers bottom-to-top (painter's order), matching KRA. + return PsdSourceArt( + widthPx = header.width, + heightPx = header.height, + layers = layersTopToBottom.asReversed(), + groups = groups, + ) + } +} + +/** + * True if [bytes] begins with the PSD file signature. + * + * @param ByteArray bytes Candidate file contents. + * @return Boolean Whether the leading bytes are the PSD magic. + */ +private fun isPsd(bytes: ByteArray): Boolean { + // PSD: File Header signature '8BPS' @ +0x00. + val signature = byteArrayOf(0x38, 0x42, 0x50, 0x53) // "8BPS" + if (bytes.size < signature.size) { + return false + } + for (signatureIndex in signature.indices) { + if (bytes[signatureIndex] != signature[signatureIndex]) { + return false + } + } + return true +} + +/** Concrete [SourceLayer] backing a parsed PSD layer. */ +private data class PsdSourceLayer( + override val id: LayerId, + override val idIsStable: Boolean, + override val name: String, + override val visible: Boolean, + override val groupPath: String, + override val order: Int, + override val bounds: LayerBounds, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val raster: LayerRaster, +) : SourceLayer + +/** Concrete [SourceGroup] backing a parsed PSD folder (a section-divider header layer). */ +private data class PsdSourceGroup( + override val path: String, + override val name: String, + override val visible: Boolean, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val passThrough: Boolean, +) : SourceGroup + +/** Concrete [SourceArt] backing a parsed PSD document. */ +private data class PsdSourceArt( + override val widthPx: Int, + override val heightPx: Int, + override val layers: List, + override val groups: List, +) : SourceArt \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterAlpha.kt b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterAlpha.kt new file mode 100644 index 0000000..aebfc85 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterAlpha.kt @@ -0,0 +1,59 @@ +package org.umamo.format.raster + +/* + * Alpha conversions over the neutral raster, for pixels read back from a renderer: a GPU framebuffer + * holds premultiplied color, while [RasterImage] and every file format that carries it (PNG first) + * hold straight alpha. + */ + +/** + * Converts this raster's premultiplied RGBA to straight alpha in place. + * + * In place because the raster is a renderer's read-back, owned by whoever asked for it: a capture can be + * a gigabyte, and a converted copy beside it would double what it holds at its peak. + * + * Each color channel divides back out by the pixel's alpha, rounded to nearest and clamped at 255: a + * premultiplied pixel whose color exceeds its alpha (an additive contribution over nothing) has no + * straight form, and the clamp keeps its hue as close as the byte range allows. A pixel with zero + * alpha has no color at all, so it becomes transparent black. + */ +public fun RasterImage.unpremultiplyInPlace() { + var offset = 0 + while (offset < rgba.size) { + val alpha = rgba[offset + 3].toInt() and 0xFF + if (alpha == 0) { + rgba[offset] = 0 + rgba[offset + 1] = 0 + rgba[offset + 2] = 0 + } else if (alpha != 0xFF) { + rgba[offset] = unpremultiplied(rgba[offset].toInt() and 0xFF, alpha).toByte() + rgba[offset + 1] = unpremultiplied(rgba[offset + 1].toInt() and 0xFF, alpha).toByte() + rgba[offset + 2] = unpremultiplied(rgba[offset + 2].toInt() and 0xFF, alpha).toByte() + } + offset += 4 + } +} + +/** + * Sets every pixel's alpha to 255 in place, leaving its color as it is. + * + * For pixels rendered over an opaque background, where premultiplied and straight color coincide and + * any alpha short of 255 is only what a blend left in the channel, not coverage. In place for the same + * reason as [unpremultiplyInPlace]. + */ +public fun RasterImage.setOpaqueAlphaInPlace() { + var alphaOffset = 3 + while (alphaOffset < rgba.size) { + rgba[alphaOffset] = 0xFF.toByte() + alphaOffset += 4 + } +} + +/** + * One premultiplied channel divided back out by its alpha, rounded to nearest and clamped to a byte. + * + * @param Int component The premultiplied channel, 0..255. + * @param Int alpha The pixel's alpha, 1..255. + * @return Int The straight channel, 0..255. + */ +private fun unpremultiplied(component: Int, alpha: Int): Int = minOf(255, (component * 255 + alpha / 2) / alpha) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterCodec.kt b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterCodec.kt new file mode 100644 index 0000000..b27edf0 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterCodec.kt @@ -0,0 +1,27 @@ +package org.umamo.format.raster + +import org.umamo.format.FormatCodec +import org.umamo.format.ReadOnlyCodec + +/** + * A [FormatCodec] whose in-memory model is a single flat [RasterImage] - one implementation per flat + * image format (PNG, BMP, JPEG, WebP, TIFF). + * + * The flat-image analogue of [org.umamo.format.art.ArtReader] (which reads a layered layer tree + * into a SourceArt): a [RasterCodec] reads and, where the format supports it, writes one whole + * image. Folding the raster codecs into [FormatCodec] lets [org.umamo.format.FormatRegistry] + * detect and resolve them exactly like the layered readers and the binary model codecs, rather + * than through a separate facade (art-sourcing roadmap invariant #5). A caller that wants a flat + * decode does `FormatRegistry.detect(bytes) as? RasterCodec` to know the file yields a + * [RasterImage], then optionally wraps it as source art via [rasterToSourceArt]. + */ +public interface RasterCodec : FormatCodec + +/** + * A [RasterCodec] for a format Umamo decodes but does not encode (JPEG lossy, WebP, TIFF). Inherits + * a refusing [write] from [ReadOnlyCodec], so the read-only nature is stated once in the type; the + * corresponding [org.umamo.format.FileKind] declares writable = false to advertise it before a call. + * + * 読み取り専用のラスタコーデック(JPEG/WebP/TIFF)。write は常に拒否する。 + */ +public interface ReadOnlyRasterCodec : RasterCodec, ReadOnlyCodec \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterImage.kt b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterImage.kt new file mode 100644 index 0000000..a09a3b3 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterImage.kt @@ -0,0 +1,38 @@ +package org.umamo.format.raster + +import org.umamo.format.art.AlphaAnalysis +import org.umamo.format.art.DEFAULT_ALPHA_THRESHOLD +import org.umamo.format.art.DEFAULT_CONTOUR_EPSILON +import org.umamo.format.art.analyzeAlpha + +/** + * A whole decoded flat image: RGBA8888, straight (non-premultiplied) alpha, row-major from the top. + * + * The in-memory model of the flat-raster codec family (PNG, BMP, JPEG, WebP, TIFF), the neutral + * pixel form fixed by the art-sourcing roadmap invariant #6. It is field-compatible with the + * layered readers' [org.umamo.format.art.LayerRaster] and the renderer's DecodedImage, so the + * adapters between them are trivial copies (see [rasterToSourceArt]). + * + * A plain class, not a `data class`: it wraps a large [rgba] buffer for which a generated structural + * equals/hashCode would be a footgun (a deep array compare on every call). Identity equality is the + * right default - the same rationale as [org.umamo.format.art.LayerRaster]. + */ +public class RasterImage( + public val width: Int, + public val height: Int, + public val rgba: ByteArray, +) + +/** + * Analyzes this flat image's opaque region. See [org.umamo.format.art.analyzeAlpha] for the + * full contract; this extension lives here rather than in the art package to preserve the + * one-way raster -> art dependency direction. + * + * @param Int alphaThreshold Minimum alpha byte value (1..255) for a pixel to count as opaque. + * @param Float contourEpsilon Douglas-Peucker tolerance in pixels; 0 keeps the exact lattice rings. + * @return AlphaAnalysis The opaque-region description, or null when nothing meets the threshold. + */ +public fun RasterImage.analyzeAlpha( + alphaThreshold: Int = DEFAULT_ALPHA_THRESHOLD, + contourEpsilon: Float = DEFAULT_CONTOUR_EPSILON, +): AlphaAnalysis? = analyzeAlpha(width, height, rgba, alphaThreshold, contourEpsilon) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterSourceArt.kt b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterSourceArt.kt new file mode 100644 index 0000000..d0386ae --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterSourceArt.kt @@ -0,0 +1,65 @@ +package org.umamo.format.raster + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer + +/** + * Wraps a single decoded [RasterImage] as a one-layer [SourceArt], so a flat raster (PNG, BMP, …) + * rides the same source-art ingest path as the layered readers (PSD, CLIP, KRA) without a second + * import mechanism. + * + * The result is a root-level document with one raster layer covering the whole canvas: no groups, + * normal blend, full opacity, unclipped. A flat image carries no per-layer stable identity (the + * whole file is the layer), so [id] defaults to the file [name] and is marked unstable - a re-import + * can only ever match it by content. The pixels are handed through by reference - the caller must + * not mutate [RasterImage.rgba] afterwards. + * + * @param RasterImage image The decoded flat image (RGBA8888, straight alpha, top-first). + * @param String name A display name / provisional layer id for the single layer (e.g. the file name). + * @return SourceArt A one-layer document sized to the image. + */ +public fun rasterToSourceArt(image: RasterImage, name: String): SourceArt = + RasterSourceArtImpl( + widthPx = image.width, + heightPx = image.height, + layers = + listOf( + RasterSourceLayer( + id = LayerId(name), + idIsStable = false, + name = name, + groupPath = "", + order = 0, + bounds = LayerBounds(left = 0, top = 0, width = image.width, height = image.height), + opacity = 1f, + clipped = false, + blend = LayerBlend.Normal, + raster = LayerRaster(width = image.width, height = image.height, rgba = image.rgba), + ), + ), + ) + +/** Concrete [SourceLayer] backing a flat raster imported as a single layer. */ +private data class RasterSourceLayer( + override val id: LayerId, + override val idIsStable: Boolean, + override val name: String, + override val groupPath: String, + override val order: Int, + override val bounds: LayerBounds, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val raster: LayerRaster, +) : SourceLayer + +/** Concrete [SourceArt] backing a flat raster (one layer, no folders). */ +private data class RasterSourceArtImpl( + override val widthPx: Int, + override val heightPx: Int, + override val layers: List, +) : SourceArt \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterThumbnails.kt b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterThumbnails.kt new file mode 100644 index 0000000..86b530a --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/raster/RasterThumbnails.kt @@ -0,0 +1,131 @@ +package org.umamo.format.raster + +import org.umamo.format.art.LayerBounds +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.roundToInt + +/* + * Thumbnail rasterization over the neutral raster: the fit every CMO3 icon takes (the art scaled so + * its longer edge fills a square, centered, transparent elsewhere - the shape the official editor + * writes for layer, model-image, drawable, and model icons), and the rectangle crop a texture patch + * is cut with. Pure Kotlin, so the desktop and Android exports render identical icons. + */ + +/** + * Scales this raster so its longer edge equals [size] and centers it in a transparent + * [size] x [size] square, the aspect preserved. + * + * Each destination pixel is the area average of the source rectangle it covers, computed in + * premultiplied space and converted back: averaging straight RGB across an alpha edge drags the + * matte color into the visible pixels and darkens the fringe, the same reason the atlas composer + * samples premultiplied. A raster smaller than the square is scaled up by the same rule (a + * destination pixel then covers part of one source pixel and takes it whole). An empty raster + * yields the blank square. + * + * @param Int size The square's edge in pixels, at least 1. + * @return RasterImage The fitted square, straight alpha, top row first. + */ +public fun RasterImage.fittedInto(size: Int): RasterImage { + require(size > 0) { "a thumbnail needs a positive size, not $size" } + val square = ByteArray(size * size * 4) + if (width <= 0 || height <= 0) { + return RasterImage(size, size, square) + } + val scale = size.toDouble() / maxOf(width, height) + val fittedWidth = (width * scale).roundToInt().coerceIn(1, size) + val fittedHeight = (height * scale).roundToInt().coerceIn(1, size) + val offsetX = (size - fittedWidth) / 2 + val offsetY = (size - fittedHeight) / 2 + val columnSpans = axisSpans(width, fittedWidth) + val rowSpans = axisSpans(height, fittedHeight) + for (destinationRow in 0 until fittedHeight) { + val rowSpan = rowSpans[destinationRow] + for (destinationColumn in 0 until fittedWidth) { + val columnSpan = columnSpans[destinationColumn] + var red = 0.0 + var green = 0.0 + var blue = 0.0 + var alpha = 0.0 + var coverage = 0.0 + for (rowTap in 0 until rowSpan.count) { + val sourceRow = rowSpan.first + rowTap + val rowWeight = rowSpan.weights[rowTap] + for (columnTap in 0 until columnSpan.count) { + val sourceColumn = columnSpan.first + columnTap + val weight = rowWeight * columnSpan.weights[columnTap] + val offset = (sourceRow * width + sourceColumn) * 4 + val sourceAlpha = (rgba[offset + 3].toInt() and 0xFF).toDouble() + // Premultiplied taps: a transparent source pixel contributes coverage but no color. + red += (rgba[offset].toInt() and 0xFF) * sourceAlpha * weight + green += (rgba[offset + 1].toInt() and 0xFF) * sourceAlpha * weight + blue += (rgba[offset + 2].toInt() and 0xFF) * sourceAlpha * weight + alpha += sourceAlpha * weight + coverage += weight + } + } + if (coverage <= 0.0 || alpha <= 0.0) { + continue + } + val destinationOffset = ((offsetY + destinationRow) * size + offsetX + destinationColumn) * 4 + // Un-premultiply: the color sums carry an alpha factor the alpha sum divides back out. + square[destinationOffset] = (red / alpha).roundToInt().coerceIn(0, 255).toByte() + square[destinationOffset + 1] = (green / alpha).roundToInt().coerceIn(0, 255).toByte() + square[destinationOffset + 2] = (blue / alpha).roundToInt().coerceIn(0, 255).toByte() + square[destinationOffset + 3] = (alpha / coverage).roundToInt().coerceIn(0, 255).toByte() + } + } + return RasterImage(size, size, square) +} + +/** + * The source pixels one destination pixel covers along one axis, with the fraction of each it covers. + * + * @property Int first The first source index. + * @property Int count How many source indices, at least one. + * @property DoubleArray weights The covered fraction of each, in order. + */ +private class AxisSpan(val first: Int, val count: Int, val weights: DoubleArray) + +/** + * The per-destination source spans of one axis: destination index d covers the source interval + * [d * ratio, (d + 1) * ratio), where ratio is source over destination length. + * + * @param Int sourceLength The source extent in pixels. + * @param Int destinationLength The destination extent in pixels. + * @return Array One span per destination index. + */ +private fun axisSpans(sourceLength: Int, destinationLength: Int): Array { + val ratio = sourceLength.toDouble() / destinationLength + return Array(destinationLength) { destinationIndex -> + val start = destinationIndex * ratio + val end = ((destinationIndex + 1) * ratio).coerceAtMost(sourceLength.toDouble()) + val first = floor(start).toInt().coerceIn(0, sourceLength - 1) + val last = (ceil(end).toInt() - 1).coerceIn(first, sourceLength - 1) + val weights = + DoubleArray(last - first + 1) { tap -> + val sourceIndex = first + tap + // The overlap of [sourceIndex, sourceIndex + 1) with [start, end). + (minOf(end, sourceIndex + 1.0) - maxOf(start, sourceIndex.toDouble())).coerceAtLeast(0.0) + } + AxisSpan(first, weights.size, weights) + } +} + +/** + * Extracts [bounds] out of this raster, returning the raster itself when the bounds cover it. + * + * @param LayerBounds bounds The raster-local rect to keep, inside the raster. + * @return RasterImage The extracted pixels. + */ +public fun RasterImage.cropped(bounds: LayerBounds): RasterImage { + if (bounds.left == 0 && bounds.top == 0 && bounds.width == width && bounds.height == height) { + return this + } + val out = ByteArray(bounds.width * bounds.height * 4) + for (rowIndex in 0 until bounds.height) { + val sourceOffset = ((bounds.top + rowIndex) * width + bounds.left) * 4 + rgba.copyInto(out, rowIndex * bounds.width * 4, sourceOffset, sourceOffset + bounds.width * 4) + } + return RasterImage(bounds.width, bounds.height, out) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffCcitt.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffCcitt.kt new file mode 100644 index 0000000..981bca1 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffCcitt.kt @@ -0,0 +1,832 @@ +// CCITT fax decoder, ported from TwelveMonkeys imageio-tiff CCITTFaxDecoderStream (BSD-3-Clause, +// Copyright (c) 2012 Harald Kuhr, Oliver Schmidtmer). The Huffman code tables, the 1D/2D row +// decoders, and the changing-element bookkeeping follow that class; the stream plumbing is replaced +// by a whole-strip ByteArray decode. See CREDITS.md. + +package org.umamo.format.tiff + +/** + * Signals that the coded data ran out mid-row. Short strips are legal in the wild (encoders pad the + * declared row count), so the caller zero-fills the remaining rows rather than failing. + */ +private class CcittEndOfInput : RuntimeException("Unexpected end of CCITT stream") + +/** One node of a CCITT Huffman code tree; interior nodes carry children, leaves carry a run value. */ +private class CcittNode { + var left: CcittNode? = null + var right: CcittNode? = null + var value: Int = 0 + var isLeaf: Boolean = false + + /** + * Attaches [node] as the child selected by [bit]. + * + * @param Boolean bit The branch to set: false = left (0), true = right (1). + * @param CcittNode node The child to attach. + */ + fun set(bit: Boolean, node: CcittNode) { + if (!bit) { + left = node + } else { + right = node + } + } + + /** + * Follows the branch selected by [bit]. + * + * @param Boolean bit The branch to walk: false = left (0), true = right (1). + * @return CcittNode? The child, or null when the code is not in the tree. + */ + fun walk(bit: Boolean): CcittNode? = if (bit) right else left +} + +/** A CCITT Huffman code tree, built by inserting (bit-depth, code path) -> value entries. */ +private class CcittTree { + val root = CcittNode() + + /** + * Inserts a leaf carrying [value] at the code given by the low [depth] bits of [path]. + * + * @param Int depth The code length in bits. + * @param Int path The code bits, MSB first within [depth]. + * @param Int value The run length (or a VALUE_* sentinel) the code decodes to. + */ + fun fill(depth: Int, path: Int, value: Int) { + val leaf = CcittNode() + leaf.value = value + leaf.isLeaf = true + fill(depth, path, leaf) + } + + /** + * Inserts [node] at the code given by the low [depth] bits of [path], creating interior nodes. + * + * @param Int depth The code length in bits. + * @param Int path The code bits, MSB first within [depth]. + * @param CcittNode node The node to attach at the code's leaf position. + */ + fun fill(depth: Int, path: Int, node: CcittNode) { + var current = root + for (bitIndex in 0 until depth) { + val bitPosition = depth - 1 - bitIndex + val isSet = ((path shr bitPosition) and 1) == 1 + var next = current.walk(isSet) + if (next == null) { + next = if (bitIndex == depth - 1) node else CcittNode() + current.set(isSet, next) + } else { + require(!next.isLeaf) { "CCITT code table node is a leaf, no other code may follow" } + } + current = next + } + } +} + +/** + * The static CCITT code tables: terminating/makeup run codes for white and black, the EOL-only tree, + * and the T.4/T.6 2D mode tree. Tables are from ITU-T T.4 as tabulated by TwelveMonkeys. + */ +private object CcittTables { + // Sentinel leaf values; all negative so they never collide with a real run length. + const val VALUE_EOL = -2000 + const val VALUE_FILL = -1000 + const val VALUE_PASSMODE = -3000 + const val VALUE_HMODE = -4000 + + // T.4 black run codes, grouped by code length starting at 2 bits. + private val BLACK_CODES = + arrayOf( + shortArrayOf(0x2, 0x3), // 2 bits + shortArrayOf(0x2, 0x3), // 3 bits + shortArrayOf(0x2, 0x3), // 4 bits + shortArrayOf(0x3), // 5 bits + shortArrayOf(0x4, 0x5), // 6 bits + shortArrayOf(0x4, 0x5, 0x7), // 7 bits + shortArrayOf(0x4, 0x7), // 8 bits + shortArrayOf(0x18), // 9 bits + shortArrayOf(0x17, 0x18, 0x37, 0x8, 0xf), // 10 bits + shortArrayOf(0x17, 0x18, 0x28, 0x37, 0x67, 0x68, 0x6c, 0x8, 0xc, 0xd), // 11 bits + shortArrayOf( // 12 bits + 0x12, + 0x13, + 0x14, + 0x15, + 0x16, + 0x17, + 0x1c, + 0x1d, + 0x1e, + 0x1f, + 0x24, + 0x27, + 0x28, + 0x2b, + 0x2c, + 0x33, + 0x34, + 0x35, + 0x37, + 0x38, + 0x52, + 0x53, + 0x54, + 0x55, + 0x56, + 0x57, + 0x58, + 0x59, + 0x5a, + 0x5b, + 0x64, + 0x65, + 0x66, + 0x67, + 0x68, + 0x69, + 0x6a, + 0x6b, + 0x6c, + 0x6d, + 0xc8, + 0xc9, + 0xca, + 0xcb, + 0xcc, + 0xcd, + 0xd2, + 0xd3, + 0xd4, + 0xd5, + 0xd6, + 0xd7, + 0xda, + 0xdb, + ), + shortArrayOf( // 13 bits + 0x4a, + 0x4b, + 0x4c, + 0x4d, + 0x52, + 0x53, + 0x54, + 0x55, + 0x5a, + 0x5b, + 0x64, + 0x65, + 0x6c, + 0x6d, + 0x72, + 0x73, + 0x74, + 0x75, + 0x76, + 0x77, + ), + ) + + private val BLACK_RUN_LENGTHS = + arrayOf( + shortArrayOf(3, 2), // 2 bits + shortArrayOf(1, 4), // 3 bits + shortArrayOf(6, 5), // 4 bits + shortArrayOf(7), // 5 bits + shortArrayOf(9, 8), // 6 bits + shortArrayOf(10, 11, 12), // 7 bits + shortArrayOf(13, 14), // 8 bits + shortArrayOf(15), // 9 bits + shortArrayOf(16, 17, 0, 18, 64), // 10 bits + shortArrayOf(24, 25, 23, 22, 19, 20, 21, 1792, 1856, 1920), // 11 bits + shortArrayOf( // 12 bits + 1984, + 2048, + 2112, + 2176, + 2240, + 2304, + 2368, + 2432, + 2496, + 2560, + 52, + 55, + 56, + 59, + 60, + 320, + 384, + 448, + 53, + 54, + 50, + 51, + 44, + 45, + 46, + 47, + 57, + 58, + 61, + 256, + 48, + 49, + 62, + 63, + 30, + 31, + 32, + 33, + 40, + 41, + 128, + 192, + 26, + 27, + 28, + 29, + 34, + 35, + 36, + 37, + 38, + 39, + 42, + 43, + ), + shortArrayOf( // 13 bits + 640, + 704, + 768, + 832, + 1280, + 1344, + 1408, + 1472, + 1536, + 1600, + 1664, + 1728, + 512, + 576, + 896, + 960, + 1024, + 1088, + 1152, + 1216, + ), + ) + + // T.4 white run codes, grouped by code length starting at 4 bits. + private val WHITE_CODES = + arrayOf( + shortArrayOf(0x7, 0x8, 0xb, 0xc, 0xe, 0xf), // 4 bits + shortArrayOf(0x12, 0x13, 0x14, 0x1b, 0x7, 0x8), // 5 bits + shortArrayOf(0x17, 0x18, 0x2a, 0x2b, 0x3, 0x34, 0x35, 0x7, 0x8), // 6 bits + shortArrayOf(0x13, 0x17, 0x18, 0x24, 0x27, 0x28, 0x2b, 0x3, 0x37, 0x4, 0x8, 0xc), // 7 bits + shortArrayOf( // 8 bits + 0x12, + 0x13, + 0x14, + 0x15, + 0x16, + 0x17, + 0x1a, + 0x1b, + 0x2, + 0x24, + 0x25, + 0x28, + 0x29, + 0x2a, + 0x2b, + 0x2c, + 0x2d, + 0x3, + 0x32, + 0x33, + 0x34, + 0x35, + 0x36, + 0x37, + 0x4, + 0x4a, + 0x4b, + 0x5, + 0x52, + 0x53, + 0x54, + 0x55, + 0x58, + 0x59, + 0x5a, + 0x5b, + 0x64, + 0x65, + 0x67, + 0x68, + 0xa, + 0xb, + ), + shortArrayOf( // 9 bits + 0x98, + 0x99, + 0x9a, + 0x9b, + 0xcc, + 0xcd, + 0xd2, + 0xd3, + 0xd4, + 0xd5, + 0xd6, + 0xd7, + 0xd8, + 0xd9, + 0xda, + 0xdb, + ), + shortArrayOf(), // 10 bits + shortArrayOf(0x8, 0xc, 0xd), // 11 bits + shortArrayOf(0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x1c, 0x1d, 0x1e, 0x1f), // 12 bits + ) + + private val WHITE_RUN_LENGTHS = + arrayOf( + shortArrayOf(2, 3, 4, 5, 6, 7), // 4 bits + shortArrayOf(128, 8, 9, 64, 10, 11), // 5 bits + shortArrayOf(192, 1664, 16, 17, 13, 14, 15, 1, 12), // 6 bits + shortArrayOf(26, 21, 28, 27, 18, 24, 25, 22, 256, 23, 20, 19), // 7 bits + shortArrayOf( // 8 bits + 33, + 34, + 35, + 36, + 37, + 38, + 31, + 32, + 29, + 53, + 54, + 39, + 40, + 41, + 42, + 43, + 44, + 30, + 61, + 62, + 63, + 0, + 320, + 384, + 45, + 59, + 60, + 46, + 49, + 50, + 51, + 52, + 55, + 56, + 57, + 58, + 448, + 512, + 640, + 576, + 47, + 48, + ), + shortArrayOf( // 9 bits + 1472, + 1536, + 1600, + 1728, + 704, + 768, + 832, + 896, + 960, + 1024, + 1088, + 1152, + 1216, + 1280, + 1344, + 1408, + ), + shortArrayOf(), // 10 bits + shortArrayOf(1792, 1856, 1920), // 11 bits + shortArrayOf(1984, 2048, 2112, 2176, 2240, 2304, 2368, 2432, 2496, 2560), // 12 bits + ) + + val blackRunTree = CcittTree() + val whiteRunTree = CcittTree() + val eolOnlyTree = CcittTree() + val codeTree = CcittTree() + + init { + val endOfLine = CcittNode() + endOfLine.isLeaf = true + endOfLine.value = VALUE_EOL + + // A run of fill zeros loops back on itself until the terminating 1 bit completes the EOL code. + val fill = CcittNode() + fill.value = VALUE_FILL + fill.left = fill + fill.right = endOfLine + + eolOnlyTree.fill(12, 0, fill) + eolOnlyTree.fill(12, 1, endOfLine) + + for (lengthIndex in BLACK_CODES.indices) { + for (codeIndex in BLACK_CODES[lengthIndex].indices) { + blackRunTree.fill(lengthIndex + 2, BLACK_CODES[lengthIndex][codeIndex].toInt(), BLACK_RUN_LENGTHS[lengthIndex][codeIndex].toInt()) + } + } + blackRunTree.fill(12, 0, fill) + blackRunTree.fill(12, 1, endOfLine) + + for (lengthIndex in WHITE_CODES.indices) { + for (codeIndex in WHITE_CODES[lengthIndex].indices) { + whiteRunTree.fill(lengthIndex + 4, WHITE_CODES[lengthIndex][codeIndex].toInt(), WHITE_RUN_LENGTHS[lengthIndex][codeIndex].toInt()) + } + } + whiteRunTree.fill(12, 0, fill) + whiteRunTree.fill(12, 1, endOfLine) + + // T.4 table 4 / T.6 2D mode codes. + codeTree.fill(4, 1, VALUE_PASSMODE) + codeTree.fill(3, 1, VALUE_HMODE) + codeTree.fill(1, 1, 0) // V(0) + codeTree.fill(3, 3, 1) // V_R(1) + codeTree.fill(6, 3, 2) // V_R(2) + codeTree.fill(7, 3, 3) // V_R(3) + codeTree.fill(3, 2, -1) // V_L(1) + codeTree.fill(6, 2, -2) // V_L(2) + codeTree.fill(7, 2, -3) // V_L(3) + } +} + +/** + * Decodes one CCITT-coded strip into packed 1-bit-per-pixel rows where a set bit means black. + * + * The output bit sense (1 = black) matches TIFF PhotometricInterpretation WhiteIsZero, which is what + * fax-derived TIFFs declare; the caller's photometric handling inverts for BlackIsZero. + * + * @param ByteArray input The coded bytes for one strip. + * @param Int columns Pixels per row. + * @param Int rows Rows in this strip. + * @param Int type COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE, _CCITT_T4, or _CCITT_T6. + * @param Long options T4Options / T6Options, or 0 for Modified Huffman. + * @param Boolean byteAligned Whether each row restarts on a byte boundary (true for type 2). + * @return ByteArray The packed rows, ((columns + 7) / 8) bytes per row, zero-filled past any short strip. + */ +internal fun decodeCcitt(input: ByteArray, columns: Int, rows: Int, type: Int, options: Long, byteAligned: Boolean): ByteArray { + require(columns > 0) { "CCITT columns must be positive, was $columns" } + require(rows > 0) { "CCITT rows must be positive, was $rows" } + return CcittFaxDecoder(input, columns, rows, type, options, byteAligned).decode() +} + +/** + * Detects a Group 3 (T.4) stream that carries no EOL codes and is therefore really Modified Huffman + * RLE. Some encoders mislabel the compression tag; TwelveMonkeys applies the same probe. + * + * @param ByteArray input The coded bytes. + * @param Int encodedType The compression code from the TIFF tag. + * @return Int The compression code to actually decode with. + */ +internal fun findCcittCompressionType(input: ByteArray, encodedType: Int): Int { + if (encodedType != TiffConstants.COMPRESSION_CCITT_T4) { + return encodedType + } + if (input.size < 2) { + return encodedType + } + val first = input[0].toInt() and 0xFF + val second = input[1].toInt() and 0xFF + // A well-formed T.4 stream opens with an EOL (000000000001), possibly byte-aligned. + if (first == 0 && ((second shr 4) == 1 || second == 1)) { + return encodedType + } + + // Otherwise scan a bounded window for an EOL; absent one, treat the strip as Modified Huffman RLE. + val limitBytes = minOf(512, input.size) + var window = (((first shl 8) or second) shr 4) + var streamByte = second + for (bitIndex in 12 until limitBytes * 8) { + if (bitIndex % 8 == 0) { + streamByte = input[bitIndex / 8].toInt() and 0xFF + } + window = (window shl 1) + ((streamByte shr (7 - (bitIndex % 8))) and 0x01) + if ((window and 0xFFF) == 1) { + return TiffConstants.COMPRESSION_CCITT_T4 + } + } + return TiffConstants.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE +} + +/** + * The CCITT Modified Huffman RLE / Group 3 (T.4) / Group 4 (T.6) row decoder. + * + * Rows are decoded as runs of changing elements; 2D modes code the current row as deltas against the + * previous row's changing elements. Uncompressed mode (a rarely used T.4/T.6 option) is rejected. + */ +private class CcittFaxDecoder( + private val input: ByteArray, + private val columns: Int, + private val rows: Int, + private val type: Int, + options: Long, + private val byteAligned: Boolean, +) { + private val optionG32D: Boolean + private val optionUncompressed: Boolean + + private val decodedRow = ByteArray((columns + 7) / 8) + private var changesReferenceRow = IntArray(columns + 2) + private var changesCurrentRow = IntArray(columns + 2) + private var changesReferenceRowCount = 0 + private var changesCurrentRowCount = 0 + private var lastChangingElement = 0 + + private var bitPosition = 0 + + init { + when (type) { + TiffConstants.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE -> { + optionG32D = false + optionUncompressed = false + } + + TiffConstants.COMPRESSION_CCITT_T4 -> { + optionG32D = (options and TiffConstants.GROUP3OPT_2DENCODING.toLong()) != 0L + optionUncompressed = (options and TiffConstants.GROUP3OPT_UNCOMPRESSED.toLong()) != 0L + } + + TiffConstants.COMPRESSION_CCITT_T6 -> { + optionG32D = false + optionUncompressed = (options and TiffConstants.GROUP4OPT_UNCOMPRESSED.toLong()) != 0L + } + + else -> throw IllegalArgumentException("Unsupported CCITT compression $type (only Modified Huffman RLE / T.4 / T.6)") + } + require(!optionUncompressed) { "CCITT Group 3/4 uncompressed mode is not supported" } + } + + /** + * Decodes every row of the strip. + * + * @return ByteArray The packed 1-bit rows; rows past a truncated stream are left zero (white). + */ + fun decode(): ByteArray { + val rowBytes = decodedRow.size + val output = ByteArray(rowBytes * rows) + for (rowIndex in 0 until rows) { + try { + decodeRow() + } catch (_: CcittEndOfInput) { + // A short strip: the remaining rows stay white, matching TwelveMonkeys' padding behavior. + break + } + decodedRow.copyInto(output, rowIndex * rowBytes, 0, rowBytes) + } + return output + } + + /** + * Decodes a single row into [decodedRow], expanding the row's changing elements into packed bits. + */ + private fun decodeRow() { + when (type) { + TiffConstants.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE -> { + if (byteAligned) { + alignToByte() + } + decode1D() + } + + TiffConstants.COMPRESSION_CCITT_T4 -> { + if (byteAligned) { + alignToByte() + } + skipToEndOfLine() + if (!optionG32D || readBit()) { + decode1D() + } else { + decode2D() + } + } + + TiffConstants.COMPRESSION_CCITT_T6 -> { + if (byteAligned) { + alignToByte() + } + decode2D() + } + } + + var index = 0 + var white = true + lastChangingElement = 0 + + for (changeIndex in 0..changesCurrentRowCount) { + var nextChange = columns + if (changeIndex != changesCurrentRowCount) { + nextChange = changesCurrentRow[changeIndex] + } + if (nextChange > columns) { + nextChange = columns + } + + var byteIndex = index / 8 + + while (index % 8 != 0 && (nextChange - index) > 0) { + decodedRow[byteIndex] = (decodedRow[byteIndex].toInt() or (if (white) 0 else 1 shl (7 - (index % 8)))).toByte() + index++ + } + + if (index % 8 == 0) { + byteIndex = index / 8 + val wholeByte = (if (white) 0x00 else 0xFF).toByte() + while ((nextChange - index) > 7) { + decodedRow[byteIndex] = wholeByte + index += 8 + byteIndex++ + } + } + + while ((nextChange - index) > 0) { + if (index % 8 == 0) { + decodedRow[byteIndex] = 0 + } + decodedRow[byteIndex] = (decodedRow[byteIndex].toInt() or (if (white) 0 else 1 shl (7 - (index % 8)))).toByte() + index++ + } + + white = !white + } + + require(index == columns) { "CCITT run lengths do not sum to the scan line width: $index != $columns" } + } + + /** Decodes a 1D (Modified Huffman) row into the current changing-element list. */ + private fun decode1D() { + var index = 0 + var white = true + changesCurrentRowCount = 0 + + do { + val completeRun = decodeRun(if (white) CcittTables.whiteRunTree else CcittTables.blackRunTree) + index += completeRun + changesCurrentRow[changesCurrentRowCount++] = index + white = !white + } while (index < columns) + } + + /** Decodes a 2D (T.4 2D / T.6) row, coding changing elements against the reference row. */ + private fun decode2D() { + changesReferenceRowCount = changesCurrentRowCount + val swap = changesCurrentRow + changesCurrentRow = changesReferenceRow + changesReferenceRow = swap + + var white = true + var index = 0 + changesCurrentRowCount = 0 + + mode@ while (index < columns) { + var node = CcittTables.codeTree.root + while (true) { + node = node.walk(readBit()) ?: continue@mode + if (!node.isLeaf) { + continue + } + when (node.value) { + CcittTables.VALUE_HMODE -> { + // Horizontal mode: two runs coded with the 1D tables. + index += decodeRun(if (white) CcittTables.whiteRunTree else CcittTables.blackRunTree) + changesCurrentRow[changesCurrentRowCount++] = index + index += decodeRun(if (white) CcittTables.blackRunTree else CcittTables.whiteRunTree) + changesCurrentRow[changesCurrentRowCount++] = index + } + + CcittTables.VALUE_PASSMODE -> { + val passChangingElement = nextChangingElement(index, white) + 1 + index = + if (passChangingElement >= changesReferenceRowCount) { + columns + } else { + changesReferenceRow[passChangingElement] + } + } + + else -> { + // Vertical mode: the change sits within +/-3 of the reference row's change. + val verticalChangingElement = nextChangingElement(index, white) + index = + if (verticalChangingElement >= changesReferenceRowCount || verticalChangingElement == -1) { + columns + node.value + } else { + changesReferenceRow[verticalChangingElement] + node.value + } + changesCurrentRow[changesCurrentRowCount++] = index + white = !white + } + } + continue@mode + } + } + } + + /** + * Finds the reference row's next changing element to the right of [a0] with the opposite color. + * + * @param Int a0 The current position on the coding line. + * @param Boolean white Whether the current run is white. + * @return Int The index into the reference row, or -1 when none remains. + */ + private fun nextChangingElement(a0: Int, white: Boolean): Int { + // Changing elements alternate color, so the search starts on the matching parity. + var start = (lastChangingElement and 0xFFFFFFFE.toInt()) + (if (white) 0 else 1) + if (start > 2) { + start -= 2 + } + if (a0 == 0) { + return start + } + var elementIndex = start + while (elementIndex < changesReferenceRowCount) { + if (a0 < changesReferenceRow[elementIndex]) { + lastChangingElement = elementIndex + return elementIndex + } + elementIndex += 2 + } + return -1 + } + + /** + * Decodes one complete run: any number of makeup codes (>= 64) plus one terminating code. + * + * @param CcittTree tree The white or black run tree to decode with. + * @return Int The total run length in pixels. + */ + private fun decodeRun(tree: CcittTree): Int { + var total = 0 + var node = tree.root + while (true) { + node = node.walk(readBit()) ?: throw IllegalArgumentException("Unknown code in CCITT Huffman RLE stream") + if (!node.isLeaf) { + continue + } + total += node.value + when { + // Makeup code: another code follows to complete the run. + node.value >= 64 -> node = tree.root + node.value >= 0 -> return total + // EOL or fill encountered mid-run: end the line here. + else -> return columns + } + } + } + + /** Consumes coded bits up to and including the next EOL code (T.4 rows are EOL-prefixed). */ + private fun skipToEndOfLine() { + endOfLine@ while (true) { + var node = CcittTables.eolOnlyTree.root + while (true) { + node = node.walk(readBit()) ?: continue@endOfLine + if (node.isLeaf) { + return + } + } + } + } + + /** Advances the bit cursor to the next byte boundary (EncodedByteAlign / Modified Huffman rows). */ + private fun alignToByte() { + bitPosition = (bitPosition + 7) and 0xFFFFFFF8.toInt() + } + + /** + * Reads the next coded bit, MSB first. + * + * @return Boolean The bit value. + */ + private fun readBit(): Boolean { + val byteIndex = bitPosition ushr 3 + if (byteIndex >= input.size) { + throw CcittEndOfInput() + } + val bit = (input[byteIndex].toInt() shr (7 - (bitPosition and 7))) and 1 + bitPosition++ + return bit != 0 + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffConstants.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffConstants.kt new file mode 100644 index 0000000..06ff644 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffConstants.kt @@ -0,0 +1,106 @@ +// Constant values from TwelveMonkeys imageio-tiff TIFF / TIFFBaseline / TIFFExtension (BSD-3-Clause, +// Copyright (c) 2009-2013 Harald Kuhr). See CREDITS.md. + +package org.umamo.format.tiff + +/** + * TIFF tag ids, field type codes, and the enumerated values (compression, photometric, predictor, + * planar config, extra samples, sample format) the reader dispatches on. + */ +internal object TiffConstants { + const val TIFF_MAGIC = 42 + const val BIGTIFF_MAGIC = 43 + + // Field type codes and their byte lengths (index = type code; -1 = unused/variable). + const val TYPE_BYTE = 1 + const val TYPE_ASCII = 2 + const val TYPE_SHORT = 3 + const val TYPE_LONG = 4 + const val TYPE_SBYTE = 6 + const val TYPE_UNDEFINED = 7 + const val TYPE_SSHORT = 8 + const val TYPE_SLONG = 9 + val TYPE_LENGTHS = intArrayOf(-1, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4, -1, -1, 8, 8, 8) + + // Tags the baseline reader consumes. + const val TAG_IMAGE_WIDTH = 256 + const val TAG_IMAGE_HEIGHT = 257 + const val TAG_BITS_PER_SAMPLE = 258 + const val TAG_COMPRESSION = 259 + const val TAG_PHOTOMETRIC_INTERPRETATION = 262 + const val TAG_FILL_ORDER = 266 + const val TAG_STRIP_OFFSETS = 273 + const val TAG_SAMPLES_PER_PIXEL = 277 + const val TAG_ROWS_PER_STRIP = 278 + const val TAG_STRIP_BYTE_COUNTS = 279 + const val TAG_PLANAR_CONFIGURATION = 284 + const val TAG_GROUP3OPTIONS = 292 + const val TAG_GROUP4OPTIONS = 293 + const val TAG_PREDICTOR = 317 + const val TAG_COLOR_MAP = 320 + const val TAG_TILE_WIDTH = 322 + const val TAG_TILE_HEIGHT = 323 + const val TAG_TILE_OFFSETS = 324 + const val TAG_TILE_BYTE_COUNTS = 325 + const val TAG_EXTRA_SAMPLES = 338 + const val TAG_SAMPLE_FORMAT = 339 + const val TAG_JPEG_TABLES = 347 + const val TAG_YCBCR_SUB_SAMPLING = 530 + const val TAG_REFERENCE_BLACK_WHITE = 532 + + // Compression (TIFFBaseline / TIFFExtension). + const val COMPRESSION_NONE = 1 + const val COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE = 2 + const val COMPRESSION_CCITT_T4 = 3 // CCITT T.4/Group 3 Fax compression. + const val COMPRESSION_CCITT_T6 = 4 // CCITT T.6/Group 4 Fax compression. + const val COMPRESSION_LZW = 5 + const val COMPRESSION_OLD_JPEG = 6 // Deprecated. For backwards compatibility only ("Old-style" JPEG). + const val COMPRESSION_JPEG = 7 // JPEG Compression (lossy). + const val COMPRESSION_ZLIB = 8 // Adobe-style Deflate. + const val COMPRESSION_PACKBITS = 32773 + const val COMPRESSION_DEFLATE = 32946 // Custom: PKZIP-style Deflate. + + // T4Options (tag 292) / T6Options (tag 293) bit flags. TIFF 6.0 defines bits 0..2 of T4Options and + // bit 1 of T6Options; there is no byte-alignment flag in either. Row alignment is a property of the + // compression type (Modified Huffman RLE rows start on a byte boundary, T.4/T.6 rows do not), which + // is why TiffReader derives it from the type rather than from these options. FILLBITS needs no + // handling: the fill zeros precede an EOL, and the decoder's EOL search absorbs them. + const val GROUP3OPT_2DENCODING = 1 + const val GROUP3OPT_UNCOMPRESSED = 2 + const val GROUP3OPT_FILLBITS = 4 + const val GROUP4OPT_UNCOMPRESSED = 2 + + // Photometric interpretation. + const val PHOTOMETRIC_WHITE_IS_ZERO = 0 + const val PHOTOMETRIC_BLACK_IS_ZERO = 1 + const val PHOTOMETRIC_RGB = 2 + const val PHOTOMETRIC_PALETTE = 3 + const val PHOTOMETRIC_MASK = 4 + const val PHOTOMETRIC_YCBCR = 6 + + // Planar configuration. + const val PLANARCONFIG_CHUNKY = 1 + const val PLANARCONFIG_PLANAR = 2 + + // Predictor. + const val PREDICTOR_NONE = 1 + const val PREDICTOR_HORIZONTAL_DIFFERENCING = 2 + const val PREDICTOR_HORIZONTAL_FLOATINGPOINT = 3 + + // Extra samples (alpha kind). + const val EXTRASAMPLE_UNSPECIFIED = 0 + const val EXTRASAMPLE_ASSOCIATED_ALPHA = 1 // premultiplied + const val EXTRASAMPLE_UNASSOCIATED_ALPHA = 2 // straight + + // Sample format. + const val SAMPLEFORMAT_UINT = 1 + const val SAMPLEFORMAT_INT = 2 + const val SAMPLEFORMAT_FP = 3 + const val SAMPLEFORMAT_UNDEFINED = 4 + const val SAMPLEFORMAT_COMPLEXINT = 5 + const val SAMPLEFORMAT_COMPLEXIEEEFP = 6 + + // Fill order. + const val FILL_LEFT_TO_RIGHT = 1 + const val FILL_RIGHT_TO_LEFT = 2 +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffDirectory.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffDirectory.kt new file mode 100644 index 0000000..7c500ae --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffDirectory.kt @@ -0,0 +1,186 @@ +// TIFF header + IFD parsing, modelled on TwelveMonkeys imageio-metadata TIFFReader (BSD-3-Clause, +// Copyright (c) 2009 Harald Kuhr) but reimplemented over a ByteArray. See CREDITS.md. + +package org.umamo.format.tiff + +import org.umamo.format.binary.ByteReader + +/** + * The parsed fields of one TIFF image file directory (IFD): each numeric tag mapped to its values as + * a [LongArray], plus the raw bytes of UNDEFINED-typed tags (JPEGTables carries an abbreviated JPEG + * stream that way). Other non-numeric fields (ASCII, RATIONAL, …) the baseline reader does not need + * are dropped during parsing. + */ +internal class TiffDirectory( + private val values: Map, + private val rawValues: Map, + val littleEndian: Boolean, +) { + /** + * All values of [tag], or null when the tag is absent. + * + * @param Int tag The TIFF tag id. + * @return LongArray? The values, or null. + */ + fun longs(tag: Int): LongArray? = values[tag] + + /** + * The raw bytes of an UNDEFINED-typed [tag], or null when absent or otherwise typed. + * + * @param Int tag The TIFF tag id. + * @return ByteArray? The raw field bytes, or null. + */ + fun bytes(tag: Int): ByteArray? = rawValues[tag] + + /** + * All values of [tag] as an IntArray, or null when absent. + * + * @param Int tag The TIFF tag id. + * @return IntArray? The values, or null. + */ + fun ints(tag: Int): IntArray? = values[tag]?.let { source -> IntArray(source.size) { source[it].toInt() } } + + /** + * The first value of [tag] as an Int, or [default] when absent. + * + * @param Int tag The TIFF tag id. + * @param Int default The fallback value. + * @return Int The first value or the default. + */ + fun int(tag: Int, default: Int): Int = values[tag]?.firstOrNull()?.toInt() ?: default + + /** + * Whether [tag] is present. + * + * @param Int tag The TIFF tag id. + * @return Boolean True if the directory carries the tag. + */ + fun has(tag: Int): Boolean = values.containsKey(tag) || rawValues.containsKey(tag) +} + +/** + * Parses the TIFF header and the first IFD into a [TiffDirectory]. + * + * @param ByteArray bytes The complete `.tiff` file. + * @return TiffDirectory The first directory's numeric fields. + */ +internal fun parseFirstDirectory(bytes: ByteArray): TiffDirectory { + require(bytes.size >= 8) { "TIFF too short for a header" } + // TIFF: byte-order mark @ +0x00 - 'II' little-endian, 'MM' big-endian. + val littleEndian = + when { + bytes[0] == 0x49.toByte() && bytes[1] == 0x49.toByte() -> true + bytes[0] == 0x4D.toByte() && bytes[1] == 0x4D.toByte() -> false + else -> throw IllegalArgumentException("Not a TIFF (bad byte-order mark)") + } + val reader = ByteReader(bytes, littleEndian = littleEndian) + // TIFF: magic @ +0x02 - 42 (classic). 43 is BigTIFF, out of scope. + val magic = reader.u16(2) + require(magic == TiffConstants.TIFF_MAGIC) { + if (magic == TiffConstants.BIGTIFF_MAGIC) "BigTIFF is not supported" else "Unsupported TIFF magic $magic" + } + val firstIfdOffset = reader.u32AsInt(4) + return readDirectory(reader, firstIfdOffset) +} + +/** + * Reads the IFD at [offset]: an entry count then that many 12-byte entries. + * + * @param ByteReader reader The file reader (byte order already set). + * @param Int offset Offset of the directory. + * @return TiffDirectory The parsed directory. + */ +private fun readDirectory(reader: ByteReader, offset: Int): TiffDirectory { + require(offset in 0..reader.bytes.size - 2) { "TIFF IFD offset out of range" } + val entryCount = reader.u16(offset) + val values = HashMap(entryCount) + val rawValues = HashMap() + var entryOffset = offset + 2 + for (entryIndex in 0 until entryCount) { + if (entryOffset + 12 > reader.bytes.size) { + break + } + // TIFF: entry = tag(u16) | type(u16) | count(u32) | value-or-offset(4). + val tag = reader.u16(entryOffset) + val type = reader.u16(entryOffset + 2) + val valueCount = reader.u32AsInt(entryOffset + 4) + val numericValues = readNumericValues(reader, type, valueCount, entryOffset + 8) + if (numericValues != null) { + values[tag] = numericValues + } + val undefinedValues = readUndefinedValues(reader, type, valueCount, entryOffset + 8) + if (undefinedValues != null) { + rawValues[tag] = undefinedValues + } + entryOffset += 12 + } + return TiffDirectory(values, rawValues, reader.littleEndian) +} + +/** + * Reads the raw bytes of an UNDEFINED-typed field (TIFF type 7), which the spec defines as an opaque + * byte string. Returns null for every other type. + * + * @param ByteReader reader The file reader. + * @param Int type The TIFF field type code. + * @param Int count The value count (bytes, for UNDEFINED). + * @param Int valueFieldOffset Offset of the entry's 4-byte value/offset field. + * @return ByteArray? The field bytes, or null. + */ +private fun readUndefinedValues(reader: ByteReader, type: Int, count: Int, valueFieldOffset: Int): ByteArray? { + if (type != TiffConstants.TYPE_UNDEFINED || count <= 0) { + return null + } + // Up to four bytes are stored inline in the value field; longer strings live at the offset it holds. + val base = if (count <= 4) valueFieldOffset else reader.u32AsInt(valueFieldOffset) + if (base < 0 || base.toLong() + count > reader.bytes.size) { + return null + } + return reader.bytes.copyOfRange(base, base + count) +} + +/** + * Reads [count] values of a numeric TIFF [type] starting at the entry's value field (inline if the + * total fits in four bytes, else at the offset the value field points to). Returns null for + * non-numeric types (ASCII/RATIONAL/…), which the baseline reader ignores. + * + * @param ByteReader reader The file reader. + * @param Int type The TIFF field type code. + * @param Int count The value count. + * @param Int valueFieldOffset Offset of the entry's 4-byte value/offset field. + * @return LongArray? The values, or null when the type is not numeric. + */ +private fun readNumericValues(reader: ByteReader, type: Int, count: Int, valueFieldOffset: Int): LongArray? { + val typeLength = if (type in TiffConstants.TYPE_LENGTHS.indices) TiffConstants.TYPE_LENGTHS[type] else -1 + val numeric = + type == TiffConstants.TYPE_BYTE || + type == TiffConstants.TYPE_SHORT || + type == TiffConstants.TYPE_LONG || + type == TiffConstants.TYPE_SBYTE || + type == TiffConstants.TYPE_SSHORT || + type == TiffConstants.TYPE_SLONG + if (!numeric || typeLength <= 0 || count < 0) { + return null + } + val totalBytes = count.toLong() * typeLength + val base = if (totalBytes <= 4) valueFieldOffset else reader.u32AsInt(valueFieldOffset) + if (base < 0 || base + totalBytes > reader.bytes.size) { + return null + } + val out = LongArray(count) + var cursor = base + for (valueIndex in 0 until count) { + out[valueIndex] = + when (type) { + TiffConstants.TYPE_BYTE -> reader.u8(cursor).toLong() + TiffConstants.TYPE_SBYTE -> reader.bytes[cursor].toLong() + TiffConstants.TYPE_SHORT -> reader.u16(cursor).toLong() + TiffConstants.TYPE_SSHORT -> reader.u16(cursor).toShort().toLong() + TiffConstants.TYPE_LONG -> reader.u32(cursor) + TiffConstants.TYPE_SLONG -> reader.u32(cursor).toInt().toLong() + else -> 0L + } + cursor += typeLength + } + return out +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffLzw.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffLzw.kt new file mode 100644 index 0000000..efaef51 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffLzw.kt @@ -0,0 +1,256 @@ +// Ported from TwelveMonkeys imageio-tiff LZWDecoder (BSD-3-Clause, Copyright (c) 2012 Harald Kuhr). +// TIFF LZW (compression 5), including the old libTiff bit-reversed variant; see CREDITS.md. + +package org.umamo.format.tiff + +private const val CLEAR_CODE = 256 +private const val EOI_CODE = 257 +private const val MIN_BITS = 9 +private const val MAX_BITS = 12 +private const val TABLE_SIZE = 1 shl MAX_BITS + +/** + * A dictionary entry: a byte string built as a reverse linked list, so a new string is the previous + * string plus one trailing byte without copying. [firstChar] is cached for fast forward access. + */ +private class LzwString( + val value: Byte, + val firstChar: Byte, + val length: Int, + val previous: LzwString?, +) { + /** + * Builds the single-byte string for [code]. + * + * @param Byte code The byte value. + */ + constructor(code: Byte) : this(code, code, 1, null) + + /** + * Returns this string with [next] appended. + * + * @param Byte next The byte to append. + * @return LzwString The concatenated string. + */ + fun concatenate(next: Byte): LzwString = LzwString(next, this.firstChar, length + 1, this) + + /** + * Writes this string into [out] starting at [offset], back-filling from the tail (the linked list + * runs newest-to-oldest). + * + * @param ByteArray out The destination buffer. + * @param Int offset The write offset. + * @return Int The offset just past the written bytes (offset + length, clamped to out.size). + */ + fun writeTo(out: ByteArray, offset: Int): Int { + if (length == 0) { + return offset + } + var entry: LzwString? = this + var index = length - 1 + while (entry != null && index >= 0) { + val position = offset + index + if (position < out.size) { + out[position] = entry.value + } + entry = entry.previous + index-- + } + return minOf(offset + length, out.size) + } +} + +/** + * Decodes a TIFF LZW strip/tile into [expectedSize] bytes, auto-detecting the old libTiff + * bit-reversed stream variant from the leading bytes. + * + * @param ByteArray input The compressed strip/tile bytes. + * @param Int expectedSize The decompressed byte count. + * @return ByteArray The decompressed bytes (zero-padded if the stream ends early). + */ +internal fun decodeLzw(input: ByteArray, expectedSize: Int): ByteArray { + val oldBitReversed = isOldBitReversedStream(input) + val decoder = LzwDecoder(input, oldBitReversed) + return decoder.decode(expectedSize) +} + +/** + * True if [input] looks like an old libTiff bit-reversed LZW stream: the first CLEAR_CODE (256) is + * stored LSB-first, so the leading bytes are 0x00 then an odd byte. + * + * @param ByteArray input The compressed bytes. + * @return Boolean Whether the stream is the bit-reversed variant. + */ +private fun isOldBitReversedStream(input: ByteArray): Boolean { + if (input.size < 2) { + return false + } + val one = input[0].toInt() and 0xFF + val two = input[1].toInt() and 0xFF + return one == 0 && (two and 0x1) == 1 +} + +/** + * TIFF LZW decoder mirroring TwelveMonkeys' spec / compatibility bit-order variants and its + * early-change code-size growth. + */ +private class LzwDecoder( + private val input: ByteArray, + private val oldBitReversed: Boolean, +) { + private val table = arrayOfNulls(if (oldBitReversed) TABLE_SIZE + 1024 else TABLE_SIZE) + private var tableLength = 0 + private var bitsPerCode = 0 + private var oldCode = CLEAR_CODE + private var maxCode = 0 + private var bitMask = 0 + private var maxString = 0 + private var eofReached = false + private var nextData = 0 + private var nextBits = 0 + private var source = 0 + + init { + for (byteValue in 0..255) { + table[byteValue] = LzwString(byteValue.toByte()) + } + reset() + } + + /** + * Re-initializes the table to the 258 fixed entries and the minimum code size. + */ + private fun reset() { + tableLength = 258 + bitsPerCode = MIN_BITS + bitMask = (1 shl bitsPerCode) - 1 + maxCode = maxCode() + maxString = 1 + } + + /** + * The largest code before a code-size increase: spec uses early change (bitMask - 1), the old + * bit-reversed variant does not (bitMask). + * + * @return Int The threshold code. + */ + private fun maxCode(): Int = if (oldBitReversed) bitMask else bitMask - 1 + + /** + * Reads the next byte of [input], or -1 at end. + * + * @return Int The byte in 0..255, or -1. + */ + private fun readByte(): Int = if (source < input.size) input[source++].toInt() and 0xFF else -1 + + /** + * Reads the next LZW code in the active bit order, or [EOI_CODE] at end of input. + * + * @return Int The code. + */ + private fun getNextCode(): Int { + if (eofReached) { + return EOI_CODE + } + var read = readByte() + if (read < 0) { + eofReached = true + return EOI_CODE + } + if (oldBitReversed) { + nextData = nextData or (read shl nextBits) + nextBits += 8 + if (nextBits < bitsPerCode) { + read = readByte() + if (read < 0) { + eofReached = true + return EOI_CODE + } + nextData = nextData or (read shl nextBits) + nextBits += 8 + } + val code = nextData and bitMask + nextData = nextData ushr bitsPerCode + nextBits -= bitsPerCode + return code + } else { + nextData = (nextData shl 8) or read + nextBits += 8 + if (nextBits < bitsPerCode) { + read = readByte() + if (read < 0) { + eofReached = true + return EOI_CODE + } + nextData = (nextData shl 8) or read + nextBits += 8 + } + val code = (nextData shr (nextBits - bitsPerCode)) and bitMask + nextBits -= bitsPerCode + return code + } + } + + /** + * Adds [string] to the table, growing the code size when the table passes [maxCode]. + * + * @param LzwString string The new dictionary entry. + */ + private fun addStringToTable(string: LzwString) { + if (tableLength >= table.size) { + throw IllegalArgumentException("TIFF LZW table overflow (more than $MAX_BITS bits per code)") + } + table[tableLength++] = string + if (tableLength > maxCode) { + bitsPerCode++ + if (bitsPerCode > MAX_BITS) { + bitsPerCode = MAX_BITS + } + bitMask = (1 shl bitsPerCode) - 1 + maxCode = maxCode() + } + if (string.length > maxString) { + maxString = string.length + } + } + + /** + * Runs the decode loop into a buffer of [expectedSize] bytes. + * + * @param Int expectedSize The decompressed byte count. + * @return ByteArray The decompressed bytes. + */ + fun decode(expectedSize: Int): ByteArray { + val out = ByteArray(expectedSize) + var position = 0 + var code = getNextCode() + while (code != EOI_CODE) { + if (code == CLEAR_CODE) { + reset() + code = getNextCode() + if (code == EOI_CODE) { + break + } + val entry = table[code] ?: throw IllegalArgumentException("Corrupted TIFF LZW code $code") + position = entry.writeTo(out, position) + } else { + table[oldCode] ?: throw IllegalArgumentException("Corrupted TIFF LZW code $oldCode") + if (code < tableLength) { + val entry = table[code]!! + position = entry.writeTo(out, position) + addStringToTable(table[oldCode]!!.concatenate(entry.firstChar)) + } else { + val outString = table[oldCode]!!.concatenate(table[oldCode]!!.firstChar) + position = outString.writeTo(out, position) + addStringToTable(outString) + } + } + oldCode = code + if (position >= expectedSize) { + break + } + code = getNextCode() + } + return out + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffPackBits.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffPackBits.kt new file mode 100644 index 0000000..5863493 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffPackBits.kt @@ -0,0 +1,44 @@ +// Ported from TwelveMonkeys common-io PackBitsDecoder (BSD-3-Clause, Copyright (c) 2008 Harald Kuhr). +// Apple PackBits run-length decode; see CREDITS.md. + +package org.umamo.format.tiff + +/** + * Decodes an Apple PackBits (TIFF compression 32773) run-length stream into [expectedSize] bytes. + * + * A control byte n: 0..127 copies the next n+1 bytes literally; -1..-127 repeats the next byte 1-n + * times; -128 is a no-op. All reads and writes are bounded so a corrupt run cannot overrun. + * + * @param ByteArray input The compressed strip/tile bytes. + * @param Int expectedSize The decompressed byte count for this strip/tile. + * @return ByteArray The decompressed bytes (zero-padded if the input runs short). + */ +internal fun decodePackBits(input: ByteArray, expectedSize: Int): ByteArray { + val out = ByteArray(expectedSize) + var source = 0 + var destination = 0 + while (destination < expectedSize && source < input.size) { + val control = input[source++].toInt() // signed + if (control >= 0) { + val literalCount = control + 1 + var copied = 0 + while (copied < literalCount && destination < expectedSize && source < input.size) { + out[destination++] = input[source++] + copied++ + } + } else if (control != -128) { + val runCount = 1 - control + if (source >= input.size) { + break + } + val runValue = input[source++] + var written = 0 + while (written < runCount && destination < expectedSize) { + out[destination++] = runValue + written++ + } + } + // control == -128 is a no-op. + } + return out +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffPredictor.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffPredictor.kt new file mode 100644 index 0000000..bc5cab8 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffPredictor.kt @@ -0,0 +1,136 @@ +// Ported from TwelveMonkeys imageio-tiff HorizontalDeDifferencingStream (BSD-3-Clause, +// Copyright (c) 2013 Harald Kuhr). TIFF horizontal differencing predictor (2); see CREDITS.md. + +package org.umamo.format.tiff + +/** + * Un-applies the TIFF horizontal differencing predictor (Predictor 2) to one decompressed row in + * place, starting at [rowOffset] in [row]: each sample is the running sum of the stored deltas along + * its row (TIFF 6.0 §14). + * + * For planar data this is called with samplesPerPixel = 1. Sub-byte samples (1/2/4 bit) accumulate + * within each byte; 8/16-bit samples accumulate per sample using the file's byte order. + * + * @param ByteArray row The decompressed buffer (modified in place). + * @param Int rowOffset Byte offset of this row within [row]. + * @param Int columns Pixels in the row. + * @param Int samplesPerPixel Samples per pixel in this plane (1 for planar). + * @param Int bitsPerSample Bits per sample (1/2/4/8/16). + * @param Boolean littleEndian The TIFF byte order, for 16-bit samples. + */ +internal fun applyHorizontalPredictor(row: ByteArray, rowOffset: Int, columns: Int, samplesPerPixel: Int, bitsPerSample: Int, littleEndian: Boolean) { + when (bitsPerSample) { + 1 -> { + var accumulator = 0 + val byteCount = (columns + 7) / 8 + for (byteRelative in 0 until byteCount) { + val byteIndex = rowOffset + byteRelative + val original = row[byteIndex].toInt() + accumulator += (original shr 7) and 0x1 + var temp = (accumulator shl 7) and 0x80 + accumulator += (original shr 6) and 0x1 + temp = temp or ((accumulator shl 6) and 0x40) + accumulator += (original shr 5) and 0x1 + temp = temp or ((accumulator shl 5) and 0x20) + accumulator += (original shr 4) and 0x1 + temp = temp or ((accumulator shl 4) and 0x10) + accumulator += (original shr 3) and 0x1 + temp = temp or ((accumulator shl 3) and 0x08) + accumulator += (original shr 2) and 0x1 + temp = temp or ((accumulator shl 2) and 0x04) + accumulator += (original shr 1) and 0x1 + temp = temp or ((accumulator shl 1) and 0x02) + accumulator += original and 0x1 + row[byteIndex] = (temp or (accumulator and 0x1)).toByte() + } + } + + 2 -> { + var accumulator = 0 + val byteCount = (columns + 3) / 4 + for (byteRelative in 0 until byteCount) { + val byteIndex = rowOffset + byteRelative + val original = row[byteIndex].toInt() + accumulator += (original shr 6) and 0x3 + var temp = (accumulator shl 6) and 0xc0 + accumulator += (original shr 4) and 0x3 + temp = temp or ((accumulator shl 4) and 0x30) + accumulator += (original shr 2) and 0x3 + temp = temp or ((accumulator shl 2) and 0x0c) + accumulator += original and 0x3 + row[byteIndex] = (temp or (accumulator and 0x3)).toByte() + } + } + + 4 -> { + var accumulator = 0 + val byteCount = (columns + 1) / 2 + for (byteRelative in 0 until byteCount) { + val byteIndex = rowOffset + byteRelative + val original = row[byteIndex].toInt() + accumulator += (original shr 4) and 0xf + var temp = (accumulator shl 4) and 0xf0 + accumulator += original and 0x0f + row[byteIndex] = (temp or (accumulator and 0xf)).toByte() + } + } + + 8 -> { + for (column in 1 until columns) { + for (sampleIndex in 0 until samplesPerPixel) { + val offset = rowOffset + column * samplesPerPixel + sampleIndex + row[offset] = (row[offset - samplesPerPixel] + row[offset]).toByte() + } + } + } + + 16 -> { + for (column in 1 until columns) { + for (sampleIndex in 0 until samplesPerPixel) { + val offset = column * samplesPerPixel + sampleIndex + val previous = read16(row, rowOffset + 2 * (offset - samplesPerPixel), littleEndian) + val current = read16(row, rowOffset + 2 * offset, littleEndian) + write16(row, rowOffset + 2 * offset, (previous + current) and 0xFFFF, littleEndian) + } + } + } + + else -> throw IllegalArgumentException("Unsupported TIFF predictor bits per sample $bitsPerSample") + } +} + +/** + * Reads a 16-bit unsigned sample from [row] at [at] in the given byte order. + * + * @param ByteArray row The row bytes. + * @param Int at Byte offset. + * @param Boolean littleEndian The byte order. + * @return Int The value in 0..65535. + */ +private fun read16(row: ByteArray, at: Int, littleEndian: Boolean): Int { + val low = row[at].toInt() and 0xFF + val high = row[at + 1].toInt() and 0xFF + return if (littleEndian) { + low or (high shl 8) + } else { + (low shl 8) or high + } +} + +/** + * Writes a 16-bit sample [value] into [row] at [at] in the given byte order. + * + * @param ByteArray row The row bytes. + * @param Int at Byte offset. + * @param Int value The value to write. + * @param Boolean littleEndian The byte order. + */ +private fun write16(row: ByteArray, at: Int, value: Int, littleEndian: Boolean) { + if (littleEndian) { + row[at] = value.toByte() + row[at + 1] = (value ushr 8).toByte() + } else { + row[at] = (value ushr 8).toByte() + row[at + 1] = value.toByte() + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffReader.kt new file mode 100644 index 0000000..132384c --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/tiff/TiffReader.kt @@ -0,0 +1,644 @@ +// TIFF decoder, ported from TwelveMonkeys imageio-tiff (BSD-3-Clause, Copyright (c) 2012 Harald +// Kuhr). The container/IFD parse, codecs, and pixel assembly follow TIFFReader / TIFFImageReader / +// LZWDecoder / PackBitsDecoder / HorizontalDeDifferencingStream / CCITTFaxDecoderStream; see +// CREDITS.md. JPEG-in-TIFF strips are handed to org.umamo.format.jpeg, which is our own code. + +package org.umamo.format.tiff + +import org.umamo.format.FileKind +import org.umamo.format.binary.inflateZlib +import org.umamo.format.jpeg.JpegColorTransform +import org.umamo.format.jpeg.decodeJpeg +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.ReadOnlyRasterCodec + +/** + * Pure-Kotlin TIFF reader (desktop JVM and Android), read only. + * + * Decodes the first image of a classic (non-BigTIFF) TIFF to the neutral straight-alpha RGBA8888 + * top-first [RasterImage]. Scope: uncompressed / PackBits / LZW / Deflate / CCITT (Modified Huffman + * RLE, T.4, T.6) / baseline JPEG strips and tiles; WhiteIsZero / BlackIsZero grayscale, RGB, palette, + * and YCbCr (JPEG only); 1/2/4/8/16-bit unsigned samples (16 down-converts to 8, roadmap invariant + * #6); horizontal-differencing predictor; chunky and planar configurations; ExtraSamples alpha + * (associated -> un-premultiplied, unassociated -> straight). Anything else (old-style JPEG / + * float / CIELab / CMYK / BigTIFF / progressive JPEG) is rejected with a clear message. Uses only + * java.util.zip, so it decodes identically on both targets (no javax.imageio). + */ +public object TiffReader : ReadOnlyRasterCodec { + override val kind: FileKind = FileKind.Tiff + + /** + * True if [candidateBytes] opens with a little- or big-endian TIFF header. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the TIFF magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean { + if (candidateBytes.size < 4) { + return false + } + // TIFF: 'II' 0x2A00 (little-endian) or 'MM' 0x002A (big-endian) header @ +0x00. + val littleEndian = candidateBytes[0] == 0x49.toByte() && candidateBytes[1] == 0x49.toByte() && candidateBytes[2] == 0x2A.toByte() && candidateBytes[3] == 0x00.toByte() + val bigEndian = candidateBytes[0] == 0x4D.toByte() && candidateBytes[1] == 0x4D.toByte() && candidateBytes[2] == 0x00.toByte() && candidateBytes[3] == 0x2A.toByte() + return littleEndian || bigEndian + } + + /** + * Decodes the first image of a `.tiff` into a straight-alpha RGBA8888 [RasterImage], top row first. + * + * @param ByteArray bytes The complete `.tiff` file. + * @return RasterImage The decoded image. + */ + override fun read(bytes: ByteArray): RasterImage { + require(matches(bytes)) { "Not a TIFF (bad signature)" } + val directory = parseFirstDirectory(bytes) + val littleEndian = directory.littleEndian + + val width = directory.int(TiffConstants.TAG_IMAGE_WIDTH, -1) + val height = directory.int(TiffConstants.TAG_IMAGE_HEIGHT, -1) + require(width > 0 && height > 0) { "TIFF has non-positive dimensions ${width}x$height" } + + val samplesPerPixel = directory.int(TiffConstants.TAG_SAMPLES_PER_PIXEL, 1) + require(samplesPerPixel in 1..4) { "Unsupported TIFF samples-per-pixel $samplesPerPixel" } + + val bitsPerSampleValues = directory.ints(TiffConstants.TAG_BITS_PER_SAMPLE) ?: intArrayOf(1) + val bitsPerSample = bitsPerSampleValues[0] + for (sampleIndex in 1 until minOf(bitsPerSampleValues.size, samplesPerPixel)) { + require(bitsPerSampleValues[sampleIndex] == bitsPerSample) { "Mixed TIFF bits-per-sample not supported" } + } + require(bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 || bitsPerSample == 8 || bitsPerSample == 16) { + "Unsupported TIFF bits-per-sample $bitsPerSample" + } + + val sampleFormat = directory.ints(TiffConstants.TAG_SAMPLE_FORMAT)?.firstOrNull() ?: TiffConstants.SAMPLEFORMAT_UINT + require(sampleFormat == TiffConstants.SAMPLEFORMAT_UINT) { "Only unsigned-integer TIFF samples are supported (format $sampleFormat)" } + + val compression = directory.int(TiffConstants.TAG_COMPRESSION, TiffConstants.COMPRESSION_NONE) + require( + compression == TiffConstants.COMPRESSION_NONE || + compression == TiffConstants.COMPRESSION_PACKBITS || + compression == TiffConstants.COMPRESSION_LZW || + compression == TiffConstants.COMPRESSION_ZLIB || + compression == TiffConstants.COMPRESSION_DEFLATE || + compression == TiffConstants.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE || + compression == TiffConstants.COMPRESSION_CCITT_T4 || + compression == TiffConstants.COMPRESSION_CCITT_T6 || + compression == TiffConstants.COMPRESSION_JPEG, + ) { "Unsupported TIFF compression $compression (only none / PackBits / LZW / Deflate / CCITT / JPEG)" } + + val photometric = + if (directory.has(TiffConstants.TAG_PHOTOMETRIC_INTERPRETATION)) { + directory.int(TiffConstants.TAG_PHOTOMETRIC_INTERPRETATION, TiffConstants.PHOTOMETRIC_BLACK_IS_ZERO) + } else if (samplesPerPixel >= 3) { + TiffConstants.PHOTOMETRIC_RGB + } else { + TiffConstants.PHOTOMETRIC_BLACK_IS_ZERO + } + require( + photometric == TiffConstants.PHOTOMETRIC_WHITE_IS_ZERO || + photometric == TiffConstants.PHOTOMETRIC_BLACK_IS_ZERO || + photometric == TiffConstants.PHOTOMETRIC_RGB || + photometric == TiffConstants.PHOTOMETRIC_PALETTE || + (photometric == TiffConstants.PHOTOMETRIC_YCBCR && compression == TiffConstants.COMPRESSION_JPEG), + ) { "Unsupported TIFF photometric interpretation $photometric" } + // The two tags are validated independently above, so a file may still pair a color photometric + // with too few samples. assembleRgba reads three samples per pixel for those, which would run + // off the end of a one-sample buffer, so require the pairing to be coherent up front. + if (photometric == TiffConstants.PHOTOMETRIC_RGB || photometric == TiffConstants.PHOTOMETRIC_YCBCR) { + require(samplesPerPixel >= 3) { "TIFF declares photometric $photometric but only $samplesPerPixel sample(s) per pixel" } + } + + val planarConfig = directory.int(TiffConstants.TAG_PLANAR_CONFIGURATION, TiffConstants.PLANARCONFIG_CHUNKY) + require(planarConfig == TiffConstants.PLANARCONFIG_CHUNKY || planarConfig == TiffConstants.PLANARCONFIG_PLANAR) { + "Unsupported TIFF planar configuration $planarConfig" + } + + val predictor = directory.int(TiffConstants.TAG_PREDICTOR, TiffConstants.PREDICTOR_NONE) + require(predictor == TiffConstants.PREDICTOR_NONE || predictor == TiffConstants.PREDICTOR_HORIZONTAL_DIFFERENCING) { + "Unsupported TIFF predictor $predictor" + } + + val fillOrder = directory.int(TiffConstants.TAG_FILL_ORDER, TiffConstants.FILL_LEFT_TO_RIGHT) + require(fillOrder == TiffConstants.FILL_LEFT_TO_RIGHT) { "Reversed TIFF fill order is not supported" } + + val extraSamples = directory.ints(TiffConstants.TAG_EXTRA_SAMPLES) + val colorMap = directory.longs(TiffConstants.TAG_COLOR_MAP) + + val planeCount = if (planarConfig == TiffConstants.PLANARCONFIG_PLANAR) samplesPerPixel else 1 + val samplesInPlane = if (planarConfig == TiffConstants.PLANARCONFIG_PLANAR) 1 else samplesPerPixel + + // One raw sample value (native bit-depth range) per (pixel, channel), filled from every unit. + val samples = IntArray(width * height * samplesPerPixel) + val units = buildUnits(directory, width, height, samplesPerPixel, planeCount) + val coding = buildCoding(directory, bytes, units, compression, predictor, photometric, littleEndian) + for (unit in units) { + decodeUnit(bytes, unit, width, samplesInPlane, samplesPerPixel, bitsPerSample, coding, samples) + } + + // A JPEG-compressed YCbCr image is color-converted by the JPEG decoder, so it assembles as RGB. + val assemblyPhotometric = if (photometric == TiffConstants.PHOTOMETRIC_YCBCR) TiffConstants.PHOTOMETRIC_RGB else photometric + return RasterImage(width, height, assembleRgba(samples, width, height, samplesPerPixel, bitsPerSample, assemblyPhotometric, extraSamples, colorMap)) + } + + /** The per-image coding parameters every unit decode needs. */ + private class TiffCoding( + val compression: Int, + val predictor: Int, + val littleEndian: Boolean, + val ccittType: Int, + val ccittOptions: Long, + val ccittByteAligned: Boolean, + val jpegTables: ByteArray?, + val jpegColorTransform: Int?, + ) + + /** + * Gathers the compression-specific parameters for the image: the CCITT variant and options, and + * the JPEG tables and color transform. + * + * @param TiffDirectory directory The parsed directory. + * @param ByteArray bytes The complete file. + * @param List units The image's decode units. + * @param Int compression The TIFF compression code. + * @param Int predictor The TIFF predictor code. + * @param Int photometric The photometric interpretation. + * @param Boolean littleEndian The TIFF byte order. + * @return TiffCoding The coding parameters. + */ + private fun buildCoding( + directory: TiffDirectory, + bytes: ByteArray, + units: List, + compression: Int, + predictor: Int, + photometric: Int, + littleEndian: Boolean, + ): TiffCoding { + val ccittOptions = + when (compression) { + TiffConstants.COMPRESSION_CCITT_T4 -> directory.longs(TiffConstants.TAG_GROUP3OPTIONS)?.firstOrNull() ?: 0L + TiffConstants.COMPRESSION_CCITT_T6 -> directory.longs(TiffConstants.TAG_GROUP4OPTIONS)?.firstOrNull() ?: 0L + else -> 0L + } + // Some encoders tag a Modified Huffman RLE stream as T.4; probe the first unit once per image. + val ccittType = + if (compression == TiffConstants.COMPRESSION_CCITT_T4 && units.isNotEmpty()) { + val firstUnit = units.first() + val start = firstUnit.offset.coerceIn(0, bytes.size) + val available = if (firstUnit.byteCount > 0) minOf(firstUnit.byteCount, bytes.size - start) else bytes.size - start + findCcittCompressionType(bytes.copyOfRange(start, start + maxOf(available, 0)), compression) + } else { + compression + } + + // TIFF's photometric interpretation is authoritative for JPEG-in-TIFF, overriding the JPEG's + // own JFIF/Adobe color-space signalling (TIFF Technical Note 2). + val jpegColorTransform = + when { + compression != TiffConstants.COMPRESSION_JPEG -> null + photometric == TiffConstants.PHOTOMETRIC_YCBCR -> JpegColorTransform.YCBCR + photometric == TiffConstants.PHOTOMETRIC_RGB -> JpegColorTransform.NONE + else -> null + } + + return TiffCoding( + compression = compression, + predictor = predictor, + littleEndian = littleEndian, + ccittType = ccittType, + ccittOptions = ccittOptions, + // Follows the probed type, not the tag. TIFF 6.0 starts every Modified Huffman RLE row on + // a byte boundary, and that is as true of a stream the probe above unmasked as of one + // honestly tagged compression 2 - keying this off `compression` instead would decode the + // same bytes two different ways depending only on how the encoder labelled them. + ccittByteAligned = ccittType == TiffConstants.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE, + jpegTables = if (compression == TiffConstants.COMPRESSION_JPEG) directory.bytes(TiffConstants.TAG_JPEG_TABLES) else null, + jpegColorTransform = jpegColorTransform, + ) + } + + /** A decode unit: one strip or one tile, with its stored dimensions and in-image placement. */ + private class TiffUnit( + val offset: Int, + val byteCount: Int, + val imageX: Int, + val imageY: Int, + val unitWidth: Int, + val unitHeight: Int, + val copyWidth: Int, + val copyHeight: Int, + val plane: Int, + ) + + /** + * Builds the list of strips or tiles for the image, unifying strips as full-width tiles. + * + * @param TiffDirectory directory The parsed directory. + * @param Int width Image width. + * @param Int height Image height. + * @param Int samplesPerPixel Samples per pixel. + * @param Int planeCount 1 for chunky, samplesPerPixel for planar. + * @return List The decode units in tag order (matching offsets/byteCounts). + */ + private fun buildUnits(directory: TiffDirectory, width: Int, height: Int, samplesPerPixel: Int, planeCount: Int): List { + val units = ArrayList() + if (directory.has(TiffConstants.TAG_TILE_WIDTH)) { + val tileWidth = directory.int(TiffConstants.TAG_TILE_WIDTH, width) + val tileHeight = directory.int(TiffConstants.TAG_TILE_HEIGHT, height) + require(tileWidth > 0 && tileHeight > 0) { "Invalid TIFF tile dimensions" } + val offsets = directory.longs(TiffConstants.TAG_TILE_OFFSETS) ?: throw IllegalArgumentException("TIFF tiles without offsets") + val byteCounts = directory.longs(TiffConstants.TAG_TILE_BYTE_COUNTS) ?: throw IllegalArgumentException("TIFF tiles without byte counts") + val tilesAcross = (width + tileWidth - 1) / tileWidth + val tilesDown = (height + tileHeight - 1) / tileHeight + val tilesPerPlane = tilesAcross * tilesDown + for (plane in 0 until planeCount) { + for (tileY in 0 until tilesDown) { + for (tileX in 0 until tilesAcross) { + val unitIndex = plane * tilesPerPlane + tileY * tilesAcross + tileX + if (unitIndex >= offsets.size) { + continue + } + val imageX = tileX * tileWidth + val imageY = tileY * tileHeight + units += + TiffUnit( + offset = offsets[unitIndex].toInt(), + byteCount = byteCounts.getOrElse(unitIndex) { 0L }.toInt(), + imageX = imageX, + imageY = imageY, + unitWidth = tileWidth, + unitHeight = tileHeight, + copyWidth = minOf(tileWidth, width - imageX), + copyHeight = minOf(tileHeight, height - imageY), + plane = plane, + ) + } + } + } + } else { + val rowsPerStrip = directory.int(TiffConstants.TAG_ROWS_PER_STRIP, height).let { if (it <= 0) height else minOf(it, height) } + val offsets = directory.longs(TiffConstants.TAG_STRIP_OFFSETS) ?: throw IllegalArgumentException("TIFF without strip offsets") + val byteCounts = directory.longs(TiffConstants.TAG_STRIP_BYTE_COUNTS) + val stripsPerPlane = (height + rowsPerStrip - 1) / rowsPerStrip + for (plane in 0 until planeCount) { + for (stripY in 0 until stripsPerPlane) { + val unitIndex = plane * stripsPerPlane + stripY + if (unitIndex >= offsets.size) { + continue + } + val imageY = stripY * rowsPerStrip + val copyHeight = minOf(rowsPerStrip, height - imageY) + units += + TiffUnit( + offset = offsets[unitIndex].toInt(), + byteCount = byteCounts?.getOrElse(unitIndex) { 0L }?.toInt() ?: 0, + imageX = 0, + imageY = imageY, + unitWidth = width, + unitHeight = copyHeight, + copyWidth = width, + copyHeight = copyHeight, + plane = plane, + ) + } + } + } + return units + } + + /** + * Decompresses one unit, un-applies the predictor, and scatters its samples into [samples]. + * + * @param ByteArray bytes The complete file. + * @param TiffUnit unit The strip/tile to decode. + * @param Int width Image width. + * @param Int samplesInPlane Samples per pixel within a unit (1 for planar). + * @param Int samplesPerPixel Samples per pixel in the assembled image. + * @param Int bitsPerSample Bits per sample. + * @param TiffCoding coding The image's compression parameters. + * @param IntArray samples The destination raw-sample buffer (width*height*samplesPerPixel). + */ + private fun decodeUnit( + bytes: ByteArray, + unit: TiffUnit, + width: Int, + samplesInPlane: Int, + samplesPerPixel: Int, + bitsPerSample: Int, + coding: TiffCoding, + samples: IntArray, + ) { + val rowBytes = (unit.unitWidth * samplesInPlane * bitsPerSample + 7) / 8 + val expectedSize = rowBytes * unit.unitHeight + val decompressed = decompressUnit(bytes, unit, expectedSize, samplesInPlane, coding) + + for (row in 0 until unit.copyHeight) { + val rowBase = row * rowBytes + if (coding.predictor == TiffConstants.PREDICTOR_HORIZONTAL_DIFFERENCING) { + applyHorizontalPredictor(decompressed, rowBase, unit.unitWidth, samplesInPlane, bitsPerSample, coding.littleEndian) + } + val imageY = unit.imageY + row + for (column in 0 until unit.copyWidth) { + val imageX = unit.imageX + column + val pixelBase = (imageY * width + imageX) * samplesPerPixel + for (sampleWithinPlane in 0 until samplesInPlane) { + val linearSampleIndex = column * samplesInPlane + sampleWithinPlane + val channel = if (samplesInPlane == 1) unit.plane else sampleWithinPlane + samples[pixelBase + channel] = readSample(decompressed, rowBase, linearSampleIndex, bitsPerSample, coding.littleEndian) + } + } + } + } + + /** + * Reads one raw sample from a decompressed row, in the native bit-depth range. + * + * @param ByteArray row The decompressed buffer. + * @param Int rowBase Byte offset of the row. + * @param Int linearSampleIndex The sample's index within the row (pixel*samplesInPlane + sample). + * @param Int bitsPerSample Bits per sample. + * @param Boolean littleEndian The TIFF byte order (for 16-bit). + * @return Int The raw sample value. + */ + private fun readSample(row: ByteArray, rowBase: Int, linearSampleIndex: Int, bitsPerSample: Int, littleEndian: Boolean): Int { + return when (bitsPerSample) { + 8 -> { + val offset = rowBase + linearSampleIndex + if (offset < row.size) row[offset].toInt() and 0xFF else 0 + } + + 16 -> { + val offset = rowBase + linearSampleIndex * 2 + if (offset + 1 < row.size) { + val low = row[offset].toInt() and 0xFF + val high = row[offset + 1].toInt() and 0xFF + if (littleEndian) low or (high shl 8) else (low shl 8) or high + } else { + 0 + } + } + + else -> { + val bitIndex = linearSampleIndex * bitsPerSample + val byteIndex = rowBase + (bitIndex ushr 3) + if (byteIndex >= row.size) { + return 0 + } + val shift = 8 - bitsPerSample - (bitIndex and 7) + val mask = (1 shl bitsPerSample) - 1 + (row[byteIndex].toInt() ushr shift) and mask + } + } + } + + /** + * Decompresses one strip/tile into [expectedSize] bytes of packed samples. + * + * @param ByteArray bytes The complete file. + * @param TiffUnit unit The strip/tile to decompress. + * @param Int expectedSize Decompressed byte count. + * @param Int samplesInPlane Samples per pixel within the unit (1 for planar). + * @param TiffCoding coding The image's compression parameters. + * @return ByteArray The decompressed bytes. + */ + private fun decompressUnit(bytes: ByteArray, unit: TiffUnit, expectedSize: Int, samplesInPlane: Int, coding: TiffCoding): ByteArray { + val safeOffset = unit.offset.coerceIn(0, bytes.size) + val available = if (unit.byteCount > 0) minOf(unit.byteCount, bytes.size - safeOffset) else bytes.size - safeOffset + return when (coding.compression) { + TiffConstants.COMPRESSION_NONE -> { + val out = ByteArray(expectedSize) + val copy = minOf(available, expectedSize) + if (copy > 0) { + bytes.copyInto(out, 0, safeOffset, safeOffset + copy) + } + out + } + + TiffConstants.COMPRESSION_PACKBITS -> decodePackBits(bytes.copyOfRange(safeOffset, safeOffset + available), expectedSize) + TiffConstants.COMPRESSION_LZW -> decodeLzw(bytes.copyOfRange(safeOffset, safeOffset + available), expectedSize) + TiffConstants.COMPRESSION_ZLIB, TiffConstants.COMPRESSION_DEFLATE -> inflate(bytes, safeOffset, available, expectedSize) + + TiffConstants.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE, + TiffConstants.COMPRESSION_CCITT_T4, + TiffConstants.COMPRESSION_CCITT_T6, + -> + decodeCcitt( + bytes.copyOfRange(safeOffset, safeOffset + available), + unit.unitWidth, + unit.unitHeight, + coding.ccittType, + coding.ccittOptions, + coding.ccittByteAligned, + ) + + TiffConstants.COMPRESSION_JPEG -> + decodeJpegUnit(bytes.copyOfRange(safeOffset, safeOffset + available), unit, samplesInPlane, expectedSize, coding) + + else -> throw IllegalArgumentException("Unsupported TIFF compression ${coding.compression}") + } + } + + /** + * Decodes one JPEG-compressed strip/tile to interleaved 8-bit samples. + * + * TIFF Technical Note 2 ("new-style" JPEG, compression 7) stores each strip as its own abbreviated + * JPEG datastream, with the shared quantization and Huffman tables factored out into the JPEGTables + * tag; the two are spliced back together before decoding. + * + * @param ByteArray unitBytes The strip/tile's JPEG datastream. + * @param TiffUnit unit The strip/tile being decoded. + * @param Int samplesInPlane Samples per pixel expected within the unit. + * @param Int expectedSize The decompressed byte count the caller expects. + * @param TiffCoding coding The image's compression parameters. + * @return ByteArray The interleaved samples, padded to [expectedSize]. + */ + private fun decodeJpegUnit(unitBytes: ByteArray, unit: TiffUnit, samplesInPlane: Int, expectedSize: Int, coding: TiffCoding): ByteArray { + val datastream = spliceJpegTables(coding.jpegTables, unitBytes) + val decoded = decodeJpeg(datastream, coding.jpegColorTransform) + require(decoded.componentCount == samplesInPlane) { + "JPEG-in-TIFF strip has ${decoded.componentCount} components but the TIFF declares $samplesInPlane" + } + + val out = ByteArray(expectedSize) + val rowBytes = unit.unitWidth * samplesInPlane + val copyRows = minOf(unit.unitHeight, decoded.height) + val copyBytes = minOf(rowBytes, decoded.width * samplesInPlane) + for (row in 0 until copyRows) { + decoded.samples.copyInto(out, row * rowBytes, row * decoded.width * samplesInPlane, row * decoded.width * samplesInPlane + copyBytes) + } + return out + } + + /** + * Splices an abbreviated JPEGTables stream onto a strip's datastream: the tables' trailing EOI and + * the strip's leading SOI are dropped so the result is one well-formed datastream. + * + * @param ByteArray? tables The JPEGTables tag contents, or null when the strips are self-contained. + * @param ByteArray unitBytes The strip's datastream. + * @return ByteArray The complete JPEG datastream to decode. + */ + private fun spliceJpegTables(tables: ByteArray?, unitBytes: ByteArray): ByteArray { + if (tables == null || tables.size < 4) { + return unitBytes + } + // Drop the tables' EOI marker, keeping SOI + DQT/DHT segments. + var tablesEnd = tables.size + if (tables[tablesEnd - 2] == 0xFF.toByte() && tables[tablesEnd - 1] == 0xD9.toByte()) { + tablesEnd -= 2 + } + // Drop the strip's SOI marker, which the tables stream already supplied. + var unitStart = 0 + if (unitBytes.size >= 2 && unitBytes[0] == 0xFF.toByte() && unitBytes[1] == 0xD8.toByte()) { + unitStart = 2 + } + val spliced = ByteArray(tablesEnd + (unitBytes.size - unitStart)) + tables.copyInto(spliced, 0, 0, tablesEnd) + unitBytes.copyInto(spliced, tablesEnd, unitStart, unitBytes.size) + return spliced + } + + /** + * Inflates a zlib stream at [offset] into exactly [expectedSize] bytes (TIFF Deflate/ZIP are plain + * zlib). The strip's uncompressed size is known, so it bounds the inflate and any shortfall from a + * truncated stream is left zero-filled. + * + * @param ByteArray bytes The buffer holding the stream. + * @param Int offset Offset of the stream. + * @param Int length Compressed byte count. + * @param Int expectedSize Decompressed byte count. + * @return ByteArray The inflated bytes (zero-padded if the stream ends early). + */ + private fun inflate(bytes: ByteArray, offset: Int, length: Int, expectedSize: Int): ByteArray { + val inflated = inflateZlib(bytes, offset, length, expectedSize) + if (inflated.size == expectedSize) { + return inflated + } + val out = ByteArray(expectedSize) + inflated.copyInto(out, 0, 0, minOf(inflated.size, expectedSize)) + return out + } + + /** + * Maps the raw sample buffer to straight-alpha RGBA8888, applying photometric interpretation, + * palette lookup, 16-to-8 down-conversion, and ExtraSamples alpha (un-premultiplying associated + * alpha). + * + * @param IntArray samples The raw per-sample values. + * @param Int width Image width. + * @param Int height Image height. + * @param Int samplesPerPixel Samples per pixel. + * @param Int bitsPerSample Bits per sample. + * @param Int photometric The photometric interpretation. + * @param IntArray? extraSamples The ExtraSamples values, or null. + * @param LongArray? colorMap The palette (3 planes of 16-bit values), or null. + * @return ByteArray The RGBA8888 pixels. + */ + private fun assembleRgba( + samples: IntArray, + width: Int, + height: Int, + samplesPerPixel: Int, + bitsPerSample: Int, + photometric: Int, + extraSamples: IntArray?, + colorMap: LongArray?, + ): ByteArray { + val rgba = ByteArray(width * height * 4) + val maxValue = if (bitsPerSample >= 16) 65535 else (1 shl bitsPerSample) - 1 + val associatedAlpha = extraSamples != null && extraSamples.isNotEmpty() && extraSamples[0] == TiffConstants.EXTRASAMPLE_ASSOCIATED_ALPHA + + val opaqueSamples = if (photometric == TiffConstants.PHOTOMETRIC_RGB) 3 else 1 + val hasAlpha = samplesPerPixel > opaqueSamples + + val paletteSize = 1 shl bitsPerSample + val paletteAllLow = colorMap != null && colorMap.all { it < 256 } + + for (pixelIndex in 0 until width * height) { + val sampleBase = pixelIndex * samplesPerPixel + val destination = pixelIndex * 4 + var red: Int + var green: Int + var blue: Int + when (photometric) { + TiffConstants.PHOTOMETRIC_PALETTE -> { + val index = samples[sampleBase] + if (colorMap != null && index < paletteSize && 2 * paletteSize + index < colorMap.size) { + red = paletteComponent(colorMap[index], paletteAllLow) + green = paletteComponent(colorMap[paletteSize + index], paletteAllLow) + blue = paletteComponent(colorMap[2 * paletteSize + index], paletteAllLow) + } else { + red = 0 + green = 0 + blue = 0 + } + } + + TiffConstants.PHOTOMETRIC_RGB -> { + red = scaleToByte(samples[sampleBase], bitsPerSample, maxValue) + green = scaleToByte(samples[sampleBase + 1], bitsPerSample, maxValue) + blue = scaleToByte(samples[sampleBase + 2], bitsPerSample, maxValue) + } + + else -> { + var gray = scaleToByte(samples[sampleBase], bitsPerSample, maxValue) + if (photometric == TiffConstants.PHOTOMETRIC_WHITE_IS_ZERO) { + gray = 255 - gray + } + red = gray + green = gray + blue = gray + } + } + + var alpha = 255 + if (hasAlpha) { + alpha = scaleToByte(samples[sampleBase + opaqueSamples], bitsPerSample, maxValue) + if (associatedAlpha) { + red = unpremultiply(red, alpha) + green = unpremultiply(green, alpha) + blue = unpremultiply(blue, alpha) + } + } + + rgba[destination] = red.toByte() + rgba[destination + 1] = green.toByte() + rgba[destination + 2] = blue.toByte() + rgba[destination + 3] = alpha.toByte() + } + return rgba + } + + /** + * Scales a raw sample in [0, maxValue] to 8 bits (16-bit keeps the high byte; sub-8-bit scales up). + * + * @param Int sample The raw sample value. + * @param Int bitsPerSample Bits per sample. + * @param Int maxValue The maximum raw value for this depth. + * @return Int The 8-bit value. + */ + private fun scaleToByte(sample: Int, bitsPerSample: Int, maxValue: Int): Int = + when { + bitsPerSample >= 16 -> (sample ushr 8) and 0xFF + bitsPerSample == 8 -> sample and 0xFF + else -> (sample * 255 + maxValue / 2) / maxValue + } + + /** + * Converts one 16-bit ColorMap entry to an 8-bit component: normally value/256, but if the whole + * map fits in the low byte (a common exporter bug) the raw value is used. + * + * @param Long value The 16-bit palette component. + * @param Boolean allLow Whether every palette value is below 256. + * @return Int The 8-bit component. + */ + private fun paletteComponent(value: Long, allLow: Boolean): Int = if (allLow) (value and 0xFF).toInt() else ((value ushr 8) and 0xFF).toInt() + + /** + * Un-premultiplies an associated-alpha component: c = round(c * 255 / alpha), 0 when alpha is 0. + * + * @param Int component The premultiplied 8-bit component. + * @param Int alpha The 8-bit alpha. + * @return Int The straight-alpha component (0..255). + */ + private fun unpremultiply(component: Int, alpha: Int): Int = if (alpha == 0) 0 else minOf(255, (component * 255 + alpha / 2) / alpha) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/Uma.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/Uma.kt new file mode 100644 index 0000000..88c191f --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/Uma.kt @@ -0,0 +1,222 @@ +package org.umamo.format.uma + +import org.umamo.format.FileKind +import org.umamo.format.FormatCodec +import org.umamo.format.binary.ByteReader +import org.umamo.format.binary.ZipArchive +import org.umamo.format.binary.ZipEntry +import org.umamo.format.binary.ZipFormatException +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.ZipWriter +import org.umamo.format.binary.rangeEquals + +/** + * Umamo's native project format at the container level: identification, the manifest, the per-entry + * compatibility classification, and preservation of everything this reader does not own. + * + * The domain entries are carried as JSON trees; their schemas are layered on per entry kind. + * + * @see UMA.md §2 Identification, §3 Manifest + */ +public object Uma : FormatCodec { + /** + * The media type a UMA file announces itself with - the content of its `mimetype` entry (UMA §2) - and the one + * name every operating-system registration has to agree on: the freedesktop entry, the Android intent filter, + * and the desktop package's file association. + */ + public const val MIME_TYPE: String = UmaContainer.MIMETYPE + + // UMA §2: a stored first entry named "mimetype" puts its content right after the 30-byte local header + // and the 8-byte name. + private const val PROBE_OFFSET = ZipRecords.LOCAL_HEADER_SIZE + 8 + + private val MIMETYPE_NAME_BYTES = UmaContainer.MIMETYPE_PATH.encodeToByteArray() + + override val kind: FileKind = FileKind.Uma + + /** + * Whether [candidateBytes] start with the stored `mimetype` entry a UMA writer puts first. Probes fixed + * offsets without parsing the archive. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean True when the file announces itself as UMA. + */ + override fun matches(candidateBytes: ByteArray): Boolean { + val mimetype = UmaContainer.MIMETYPE_BYTES + if (candidateBytes.size < PROBE_OFFSET + mimetype.size) { + return false + } + val reader = ByteReader(candidateBytes, littleEndian = true) + // UMA §2 over ZIP's local file header (APPNOTE.TXT 4.3.7): @ +0x00 signature, @ +0x08 method, + // @ +0x16 uncompressed size, @ +0x1A name length, @ +0x1C extra length, @ +0x1E the name. + return reader.u32(0) == ZipRecords.LOCAL_HEADER_SIGNATURE.toLong() && + reader.u16(8) == ZipRecords.METHOD_STORED && + reader.u32(22) == mimetype.size.toLong() && + reader.u16(26) == MIMETYPE_NAME_BYTES.size && + reader.u16(28) == 0 && + candidateBytes.rangeEquals(ZipRecords.LOCAL_HEADER_SIZE, MIMETYPE_NAME_BYTES, 0, MIMETYPE_NAME_BYTES.size) && + candidateBytes.rangeEquals(PROBE_OFFSET, mimetype, 0, mimetype.size) + } + + /** + * Reads a UMA archive: validates the mimetype and the manifest, classifies every listed entry, and keeps + * everything this reader does not understand byte for byte. + * + * @param ByteArray bytes The whole file. + * @return UmaModel The document, possibly read-only. + * @throws UmaFormatException When the file cannot be opened as UMA at all. + */ + override fun read(bytes: ByteArray): UmaModel { + val archive = + try { + ZipArchive.read(bytes) + } catch (failure: ZipFormatException) { + throw UmaFormatException(UmaReadFailure.CorruptContainer(failure.message.orEmpty()), failure) + } + + // UMA §2: the mimetype entry identifies the file wherever a re-zipping tool left it; the writer puts + // it back first. + val mimetypeEntry = archive.entry(UmaContainer.MIMETYPE_PATH) ?: throw UmaFormatException(UmaReadFailure.NotUma("the archive has no mimetype entry")) + if (!contentsOf(archive, mimetypeEntry).contentEquals(UmaContainer.MIMETYPE_BYTES)) { + throw UmaFormatException(UmaReadFailure.NotUma("the mimetype entry does not hold ${UmaContainer.MIMETYPE}")) + } + val manifestEntry = + archive.entry(UmaContainer.MANIFEST_PATH) + ?: throw UmaFormatException(UmaReadFailure.MalformedManifest("the archive has no ${UmaContainer.MANIFEST_PATH}")) + val manifest = parseUmaManifest(contentsOf(archive, manifestEntry)) + + // UMA §3.3: classify every listed entry. + val entries = ArrayList(manifest.records.size) + val readOnlyReasons = ArrayList() + for (record in manifest.records) { + val zipEntry = archive.entry(record.path) ?: throw UmaFormatException(UmaReadFailure.MissingEntry(record.path)) + val knownKind = UmaEntryKind.ofWireName(record.kind) + val content = + if (knownKind != null && knownKind.version >= record.minVersion) { + val tree = parseJsonObject(contentsOf(archive, zipEntry)) { detail -> UmaReadFailure.MalformedEntry(record.path, detail) } + UmaEntryContent.Live(knownKind, tree) + } else { + if (record.required) { + val cause = + if (knownKind == null) { + UmaReadOnlyCause.UnknownKind + } else { + UmaReadOnlyCause.UnsupportedVersion(record.minVersion, knownKind.version) + } + readOnlyReasons += UmaReadOnlyReason(record.path, record.kind, cause) + } + UmaEntryContent.Preserved(UmaRawEntry(zipEntry, archive.bytes)) + } + entries += UmaEntry(record.path, record.kind, record.version, record.minVersion, record.required, record.record, content) + } + + // UMA §3.3: every other entry is a payload, kept exactly; nothing is garbage-collected. Each stays a slice of the + // file's bytes, which the document holds anyway, rather than a second copy. + val listedPaths = manifest.records.mapTo(HashSet()) { record -> record.path } + val archiveOrder = ArrayList(archive.entries.size) + val payloads = ArrayList() + for (zipEntry in archive.entries) { + if (UmaContainer.isReservedPath(zipEntry.name)) { + continue + } + archiveOrder += zipEntry.name + if (zipEntry.name !in listedPaths) { + payloads += UmaPayload(zipEntry.name, UmaRawEntry(zipEntry, archive.bytes)) + } + } + val model = UmaModel(manifest.writer, entries, payloads, readOnlyReasons, manifest.tree, archiveOrder) + // UMA §4.8, §5.8, §6.6: decoding the domain entries here makes a malformed one fail the read, not a later + // access. + model.puppet + model.textures + model.sources + return model + } + + /** + * Writes [model] as a UMA archive: the mimetype first and stored, the manifest second, then every other + * entry in the order the document holds them, all stamped with the fixed epoch. + * + * @param UmaModel model The document. + * @return ByteArray The archive. + * @throws IllegalStateException When the document is read-only. + */ + override fun write(model: UmaModel): ByteArray { + check(!model.isReadOnly) { + "a read-only UMA document cannot be written: " + + model.readOnlyReasons.joinToString { reason -> "'${reason.path}' (${reason.kind}): ${reason.cause}" } + } + // UMA §3.5: one fixed stamp on every entry, so the same document always writes the same bytes. + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + writer.addStored(UmaContainer.MIMETYPE_PATH, UmaContainer.MIMETYPE_BYTES) + writer.addDeflated(UmaContainer.MANIFEST_PATH, emitUmaManifest(model)) + + val entryByPath = model.entries.associateBy { entry -> entry.path } + val archivePaths = model.archiveOrder.toHashSet() + val payloadByPath = model.payloads.associateBy { payload -> payload.path } + val writtenPaths = HashSet() + + /** + * Writes the entry or payload at [path] once. + * + * @param String path The entry path. + */ + fun writePath(path: String) { + if (!writtenPaths.add(path)) { + return + } + // UMA §3.5: a payload an entry owns that a save rebuilt (a buffer, a pixel entry) is written stored in place + // of the payload read, or not at all when the entry no longer names it. + val owned = model.ownedPayloads[path] + if (owned != null) { + owned.bytes?.let { bytes -> writer.addStored(path, bytes) } + return + } + val entry = entryByPath[path] + if (entry != null) { + when (val content = entry.content) { + is UmaEntryContent.Live -> { + writer.addDeflated(path, encodeUmaJson(content.tree)) + // UMA §3.5: a payload new to this file follows the entry that owns it, in the order the save laid it out. + for ((ownedPath, ownedPayload) in model.ownedPayloads) { + if (ownedPayload.owner == content.kind && ownedPath !in archivePaths) { + writePath(ownedPath) + } + } + } + + is UmaEntryContent.Preserved -> writer.addRaw(content.raw.zipEntry, content.raw.archive, content.raw.zipEntry.payloadOffset) + } + return + } + payloadByPath[path]?.let { payload -> writer.addRaw(payload.raw.zipEntry, payload.raw.archive, payload.raw.zipEntry.payloadOffset) } + } + + // UMA §3.5: the archive's own order first, then entries new to this document in manifest order, then + // any payloads not yet written. + for (path in model.archiveOrder) { + writePath(path) + } + for (entry in model.entries) { + writePath(entry.path) + } + for (payload in model.payloads) { + writePath(payload.path) + } + return writer.finish() + } + + /** + * An entry's contents, with a ZIP-level failure reported as a corrupt container. + * + * @param ZipArchive archive The archive. + * @param ZipEntry entry The entry. + * @return ByteArray The entry's uncompressed bytes. + */ + private fun contentsOf(archive: ZipArchive, entry: ZipEntry): ByteArray = + try { + archive.contents(entry) + } catch (failure: ZipFormatException) { + throw UmaFormatException(UmaReadFailure.CorruptContainer(failure.message.orEmpty()), failure) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaBuffers.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaBuffers.kt new file mode 100644 index 0000000..be150ec --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaBuffers.kt @@ -0,0 +1,388 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package org.umamo.format.uma + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonEncoder +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.longOrNull +import kotlinx.serialization.modules.SerializersModule +import okio.Buffer +import org.umamo.format.binary.ByteReader + +/* + * Bulk arrays in buffer entries (docs/format/UMA.md §4.9). A domain entry's per-vertex arrays + * live in a little-endian buffer entry the domain owns, each named from the JSON by an accessor - an object + * holding exactly `buffer`, `byteOffset`, `byteLength`, `count`, and `componentType`. + * + * Accessors are recognized anywhere in a tree, under a known key or not, and every save lays the owned buffer + * out afresh from them in document order. That is what lets an accessor a newer writer put under a key this + * reader does not know keep its bytes, instead of pointing at an offset the rewritten buffer moved. + */ + +/** UMA §4.9: the alignment of an accessor whose component type this reader does not know, the largest a type may need. */ +private const val UNKNOWN_COMPONENT_ALIGNMENT = 8 + +/** UMA §4.9: the component types this reader interprets, each four bytes little-endian. */ +internal object UmaComponentType { + const val FLOAT32 = "float32" + const val INT32 = "int32" + + /** + * The size in bytes of one component of [componentType], or null for a type this reader does not know. + * + * @param String componentType The accessor's component type. + * @return Int? The component size. + */ + fun sizeOf(componentType: String): Int? = + when (componentType) { + FLOAT32, INT32 -> 4 + else -> null + } +} + +/** + * One accessor's fields. + * + * @property String buffer The buffer entry's path. + * @property Int byteOffset Where the array starts in the buffer. + * @property Int byteLength The array's length in bytes. + * @property Int count The number of components. + * @property String componentType The component type. + */ +internal class UmaAccessor( + val buffer: String, + val byteOffset: Int, + val byteLength: Int, + val count: Int, + val componentType: String, +) { + /** + * This accessor as the JSON object the file holds, keys in their written order. + * + * @return JsonObject The accessor. + */ + fun toJson(): JsonObject = + JsonObject( + linkedMapOf( + BUFFER_KEY to JsonPrimitive(buffer), + BYTE_OFFSET_KEY to JsonPrimitive(byteOffset), + BYTE_LENGTH_KEY to JsonPrimitive(byteLength), + COUNT_KEY to JsonPrimitive(count), + COMPONENT_TYPE_KEY to JsonPrimitive(componentType), + ), + ) + + companion object { + // UMA §4.9: an accessor's keys, all five required and nothing else. + private const val BUFFER_KEY = "buffer" + private const val BYTE_OFFSET_KEY = "byteOffset" + private const val BYTE_LENGTH_KEY = "byteLength" + private const val COUNT_KEY = "count" + private const val COMPONENT_TYPE_KEY = "componentType" + + /** The name a freshly encoded array's accessor gives its buffer until the layout places it. */ + const val SCRATCH_BUFFER = "umamo:scratch" + + /** + * [element] as an accessor, or null when it is not one: an object with exactly the five accessor + * keys, `buffer` and `componentType` strings, and the three sizes non-negative integers. + * + * @param JsonElement element The value. + * @return UmaAccessor? The accessor. + */ + fun of(element: JsonElement): UmaAccessor? { + val candidate = element as? JsonObject ?: return null + if (candidate.size != 5) { + return null + } + return UmaAccessor( + buffer = jsonStringOrNull(candidate[BUFFER_KEY]) ?: return null, + byteOffset = sizeOf(candidate[BYTE_OFFSET_KEY]) ?: return null, + byteLength = sizeOf(candidate[BYTE_LENGTH_KEY]) ?: return null, + count = sizeOf(candidate[COUNT_KEY]) ?: return null, + componentType = jsonStringOrNull(candidate[COMPONENT_TYPE_KEY]) ?: return null, + ) + } + + /** + * [element] as a non-negative integer within a byte array's range, or null. + * + * @param JsonElement? element The value. + * @return Int? The integer. + */ + private fun sizeOf(element: JsonElement?): Int? = + (element as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.longOrNull?.takeIf { value -> value in 0..Int.MAX_VALUE.toLong() }?.toInt() + } +} + +/** + * Where the first accessor in [tree] breaks a rule: a buffer that does not exist, a known component type + * whose length or alignment is wrong, or bytes past the buffer's end. + * + * @param JsonElement tree The entry's JSON. + * @param Function buffers Resolves a buffer path to its bytes, or null when there is no such buffer. + * @param String path The tree's position, for the report. + * @return String? A description of the first problem, or null when every accessor is sound. + */ +internal fun firstAccessorProblem(tree: JsonElement, buffers: (String) -> ByteArray?, path: String = ""): String? { + UmaAccessor.of(tree)?.let { accessor -> + val bytes = buffers(accessor.buffer) ?: return "$path names the buffer '${accessor.buffer}', which the archive does not hold" + val componentSize = UmaComponentType.sizeOf(accessor.componentType) + if (componentSize != null) { + if (accessor.byteLength.toLong() != accessor.count.toLong() * componentSize) { + return "$path declares ${accessor.count} ${accessor.componentType} components in ${accessor.byteLength} bytes" + } + if (accessor.byteOffset % componentSize != 0) { + return "$path starts at byte ${accessor.byteOffset}, which is not aligned to ${accessor.componentType}" + } + } + if (accessor.byteOffset.toLong() + accessor.byteLength > bytes.size) { + return "$path reaches byte ${accessor.byteOffset.toLong() + accessor.byteLength} of '${accessor.buffer}', which holds ${bytes.size}" + } + return null + } + when (tree) { + is JsonObject -> { + for ((key, value) in tree) { + firstAccessorProblem(value, buffers, if (path.isEmpty()) key else "$path.$key")?.let { problem -> return problem } + } + } + + is JsonArray -> { + for ((elementIndex, element) in tree.withIndex()) { + firstAccessorProblem(element, buffers, "$path[$elementIndex]")?.let { problem -> return problem } + } + } + + else -> {} + } + return null +} + +/** + * The growable little-endian buffer a save encodes its new arrays into, before the layout places them. + */ +internal class UmaScratchBuffer { + private val output = Buffer() + + /** + * Appends [values] as float32 and returns the accessor naming them. + * + * @param FloatArray values The array. + * @return UmaAccessor The accessor. + */ + fun appendFloats(values: FloatArray): UmaAccessor { + val offset = output.size.toInt() + for (value in values) { + output.writeIntLe(value.toRawBits()) + } + return UmaAccessor(UmaAccessor.SCRATCH_BUFFER, offset, values.size * 4, values.size, UmaComponentType.FLOAT32) + } + + /** + * Appends [values] as int32 and returns the accessor naming them. + * + * @param IntArray values The array. + * @return UmaAccessor The accessor. + */ + fun appendInts(values: IntArray): UmaAccessor { + val offset = output.size.toInt() + for (value in values) { + output.writeIntLe(value) + } + return UmaAccessor(UmaAccessor.SCRATCH_BUFFER, offset, values.size * 4, values.size, UmaComponentType.INT32) + } + + /** + * Everything appended so far. + * + * @return ByteArray The bytes. + */ + fun bytes(): ByteArray = output.copy().readByteArray() +} + +/** + * The result of laying an entry's accessors out into its owned buffer. + * + * @property JsonElement tree The tree with every accessor pointing into the owned buffer. + * @property ByteArray buffer The owned buffer's bytes. + * @property Boolean hasAccessors Whether the tree holds any accessor, so the buffer is referenced. + */ +internal class UmaBufferLayout( + val tree: JsonElement, + val buffer: ByteArray, + val hasAccessors: Boolean, +) + +/** + * Lays every accessor in [tree] out into one buffer at [ownedPath], in document order: each accessor's bytes + * are copied from the buffer it names, aligned to its component size (eight bytes for a type this reader does + * not know), and the accessor is rewritten to point into the new buffer. + * + * @param JsonElement tree The entry's JSON. + * @param String ownedPath The path of the buffer the entry owns. + * @param Function sources Resolves a buffer path, the scratch buffer included, to its bytes. + * @return UmaBufferLayout The rewritten tree and the owned buffer. + * @throws IllegalStateException When an accessor names bytes its source does not hold; a tree read from a + * file has already been validated, so this is a bug in the caller. + */ +internal fun layOutBuffer(tree: JsonElement, ownedPath: String, sources: (String) -> ByteArray?): UmaBufferLayout { + val output = Buffer() + var accessorCount = 0 + + /** + * Rewrites one subtree. + * + * @param JsonElement element The subtree. + * @return JsonElement The rewritten subtree. + */ + fun rewrite(element: JsonElement): JsonElement { + val accessor = UmaAccessor.of(element) + if (accessor != null) { + val source = checkNotNull(sources(accessor.buffer)) { "an accessor names the buffer '${accessor.buffer}', which is not available" } + check(accessor.byteOffset.toLong() + accessor.byteLength <= source.size) { "an accessor reaches past the end of '${accessor.buffer}'" } + // UMA §4.9: each array starts on a multiple of its component size. A type this reader does not know aligns to + // 8, a multiple of every component size a newer reader may check it against. + val alignment = UmaComponentType.sizeOf(accessor.componentType) ?: UNKNOWN_COMPONENT_ALIGNMENT + while (output.size % alignment != 0L) { + output.writeByte(0) + } + val offset = output.size.toInt() + output.write(source, accessor.byteOffset, accessor.byteLength) + accessorCount++ + return UmaAccessor(ownedPath, offset, accessor.byteLength, accessor.count, accessor.componentType).toJson() + } + return when (element) { + is JsonObject -> JsonObject(element.mapValuesTo(LinkedHashMap()) { (_, value) -> rewrite(value) }) + is JsonArray -> JsonArray(element.map(::rewrite)) + else -> element + } + } + val rewritten = rewrite(tree) + check(output.size <= Int.MAX_VALUE - 8L) { "the buffer '$ownedPath' exceeds what a byte array can hold" } + return UmaBufferLayout(rewritten, output.readByteArray(), accessorCount > 0) +} + +/** + * Reads accessors into float arrays while decoding, and writes float arrays out as accessors while encoding. + * + * @param Function buffers Resolves a buffer path to its bytes, for decoding. + * @param UmaScratchBuffer? scratch The buffer new arrays append to, for encoding. + */ +private class Float32AccessorSerializer( + private val buffers: (String) -> ByteArray?, + private val scratch: UmaScratchBuffer?, +) : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("org.umamo.format.uma.Float32Accessor") + + /** + * Writes [value] into the scratch buffer and its accessor into the tree. + * + * @param Encoder encoder The JSON encoder. + * @param FloatArray value The array. + */ + override fun serialize(encoder: Encoder, value: FloatArray) { + val sink = scratch ?: throw SerializationException("no buffer to write a float32 array into") + (encoder as JsonEncoder).encodeJsonElement(sink.appendFloats(value).toJson()) + } + + /** + * Reads the accessor at the decoder's position and slices its floats out of the buffer it names. + * + * @param Decoder decoder The JSON decoder. + * @return FloatArray The array. + */ + override fun deserialize(decoder: Decoder): FloatArray { + val (accessor, bytes) = resolveAccessor(decoder, UmaComponentType.FLOAT32, buffers) + val reader = ByteReader(bytes, littleEndian = true) + return FloatArray(accessor.count) { componentIndex -> Float.fromBits(reader.u32AsInt(accessor.byteOffset + componentIndex * 4)) } + } +} + +/** + * Reads accessors into int arrays while decoding, and writes int arrays out as accessors while encoding. + * + * @param Function buffers Resolves a buffer path to its bytes, for decoding. + * @param UmaScratchBuffer? scratch The buffer new arrays append to, for encoding. + */ +private class Int32AccessorSerializer( + private val buffers: (String) -> ByteArray?, + private val scratch: UmaScratchBuffer?, +) : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("org.umamo.format.uma.Int32Accessor") + + /** + * Writes [value] into the scratch buffer and its accessor into the tree. + * + * @param Encoder encoder The JSON encoder. + * @param IntArray value The array. + */ + override fun serialize(encoder: Encoder, value: IntArray) { + val sink = scratch ?: throw SerializationException("no buffer to write an int32 array into") + (encoder as JsonEncoder).encodeJsonElement(sink.appendInts(value).toJson()) + } + + /** + * Reads the accessor at the decoder's position and slices its ints out of the buffer it names. + * + * @param Decoder decoder The JSON decoder. + * @return IntArray The array. + */ + override fun deserialize(decoder: Decoder): IntArray { + val (accessor, bytes) = resolveAccessor(decoder, UmaComponentType.INT32, buffers) + val reader = ByteReader(bytes, littleEndian = true) + return IntArray(accessor.count) { componentIndex -> reader.u32AsInt(accessor.byteOffset + componentIndex * 4) } + } +} + +/** + * The accessor at [decoder]'s position and the bytes of the buffer it names, checked against the component + * type the field requires. + * + * @param Decoder decoder The JSON decoder. + * @param String componentType The component type the field requires. + * @param Function buffers Resolves a buffer path to its bytes. + * @return Pair The accessor and its buffer's bytes. + * @throws SerializationException When the value is not a sound accessor of that type. + */ +private fun resolveAccessor(decoder: Decoder, componentType: String, buffers: (String) -> ByteArray?): Pair { + val element = (decoder as JsonDecoder).decodeJsonElement() + val accessor = UmaAccessor.of(element) ?: throw SerializationException("expected a $componentType accessor, found $element") + if (accessor.componentType != componentType) { + throw SerializationException("expected a $componentType accessor, found ${accessor.componentType}") + } + val bytes = buffers(accessor.buffer) ?: throw SerializationException("the accessor names the buffer '${accessor.buffer}', which the archive does not hold") + if (accessor.byteLength.toLong() != accessor.count.toLong() * 4 || accessor.byteOffset.toLong() + accessor.byteLength > bytes.size) { + throw SerializationException("the $componentType accessor does not fit the buffer '${accessor.buffer}'") + } + return accessor to bytes +} + +/** + * The entry JSON with its bulk array fields bound to buffers: decoding slices them out of [buffers], and + * encoding appends them to [scratch]. + * + * @param Function buffers Resolves a buffer path to its bytes. + * @param UmaScratchBuffer? scratch The buffer new arrays append to, or null when only decoding. + * @return Json The configured instance. + */ +internal fun umaEntryJsonWithBuffers(buffers: (String) -> ByteArray?, scratch: UmaScratchBuffer?): Json = + Json(UmaEntryJson) { + serializersModule = + SerializersModule { + contextual(FloatArray::class, Float32AccessorSerializer(buffers, scratch)) + contextual(IntArray::class, Int32AccessorSerializer(buffers, scratch)) + } + } \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaEntryKind.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaEntryKind.kt new file mode 100644 index 0000000..075ae4d --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaEntryKind.kt @@ -0,0 +1,78 @@ +package org.umamo.format.uma + +/** + * The domain entry kinds this reader understands, each with the schema version it reads and writes + * (docs/format/UMA.md §3.2). + * + * The wire name is the stable identifier a manifest record's `kind` carries and the one thing a reader + * dispatches on; the enum constant's own name never reaches a file, so renaming one changes nothing on + * disk. An entry whose kind is not listed here, or whose `minVersion` is above [version], is preserved + * byte for byte rather than read. + * + * @property String wireName The manifest `kind` value. + * @property String defaultPath Where a writer puts a new entry of this kind. A read entry keeps the + * path its file gave it. + * @property Int version The schema version this reader understands and this writer emits. + * @property Int minVersion The `minVersion` this writer declares: the oldest schema version a reader + * may treat the entry as. + * @property Boolean required Whether understanding the entry is necessary to interpret or edit the + * document at all. + * @property String? bufferPath The buffer entry this kind owns for its bulk arrays, or null when it has none + * (UMA §4.9: an entry's accessors name only buffers it owns, and no two entries share one). + */ +public enum class UmaEntryKind( + public val wireName: String, + public val defaultPath: String, + public val version: Int, + public val minVersion: Int, + public val required: Boolean, + public val bufferPath: String? = null, +) { + // UMA §3.2: the base puppet graph. + Puppet("puppet", "model/puppet.json", 1, 1, true, "model/buffers.bin"), + + // UMA §3.2: the atlas and the pixel entries it names. + Textures("textures", "textures/index.json", 1, 1, true), + + // UMA §3.2: the linked source art and its layer inventories. + Sources("sources", "source/index.json", 1, 1, false), + + // UMA §3.2: document-scoped editor state, which is never load-bearing and so never required. + Editor("editor", "editor/state.json", 1, 1, false), + ; + + public companion object { + /** + * The kind a manifest record's `kind` names, or null when this reader does not know it. + * + * @param String wireName The manifest `kind` value. + * @return UmaEntryKind? The kind, or null. + */ + public fun ofWireName(wireName: String): UmaEntryKind? = entries.firstOrNull { kind -> kind.wireName == wireName } + } +} + +/** The container-level constants every UMA archive shares (docs/format/UMA.md §2, §3). */ +internal object UmaContainer { + // UMA §2: the mimetype entry's name and exact content. + const val MIMETYPE_PATH = "mimetype" + const val MIMETYPE = "application/vnd.umamo.uma+zip" + + // UMA §3: the manifest's path and the value its `format` key holds. + const val MANIFEST_PATH = "manifest.json" + const val FORMAT_NAME = "uma" + + // UMA §3.1: the one container version this reader understands and this writer emits. + const val CONTAINER_VERSION = 1 + + /** The mimetype entry's content as bytes. */ + val MIMETYPE_BYTES: ByteArray = MIMETYPE.encodeToByteArray() + + /** + * Whether [path] is one of the bootstrap entries no manifest record may name. + * + * @param String path An entry path. + * @return Boolean True for `mimetype` or `manifest.json`. + */ + fun isReservedPath(path: String): Boolean = path == MIMETYPE_PATH || path == MANIFEST_PATH +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaFormatException.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaFormatException.kt new file mode 100644 index 0000000..ed916a7 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaFormatException.kt @@ -0,0 +1,93 @@ +package org.umamo.format.uma + +/** + * Why a file could not be opened as UMA at all (docs/format/UMA.md §3.4). A file that opens but cannot + * be edited is not a failure; see [UmaModel.readOnlyReasons]. + */ +public sealed interface UmaReadFailure { + /** A human-readable account of the failure, for logs. */ + public val description: String + + /** + * The file is not a UMA document: it has no `mimetype` entry, the wrong one, or a manifest whose + * `format` is not `uma`. + * + * @property String detail What identified it as foreign. + */ + public data class NotUma(val detail: String) : UmaReadFailure { + override val description: String get() = "not a UMA document: $detail" + } + + /** + * The container version is newer than this reader understands, so nothing in the file can be trusted + * to mean what this reader thinks. + * + * @property Int found The file's container version. + * @property Int supported The newest container version this reader understands. + */ + public data class UnsupportedContainerVersion(val found: Int, val supported: Int) : UmaReadFailure { + override val description: String get() = "container version $found is newer than the supported version $supported" + } + + /** + * The ZIP archive itself is truncated, corrupt, or unsupported. + * + * @property String detail The ZIP reader's account. + */ + public data class CorruptContainer(val detail: String) : UmaReadFailure { + override val description: String get() = "corrupt container: $detail" + } + + /** + * The manifest is missing, is not valid JSON, or breaks one of its rules. + * + * @property String detail Which rule it breaks. + */ + public data class MalformedManifest(val detail: String) : UmaReadFailure { + override val description: String get() = "malformed manifest: $detail" + } + + /** + * The file names an entry the archive does not hold: a path the manifest lists, or a pixel entry an index + * record names. + * + * @property String path The named path. + */ + public data class MissingEntry(val path: String) : UmaReadFailure { + override val description: String get() = "the file names '$path', which the archive does not hold" + } + + /** + * A domain entry this reader understands is not what its kind requires. + * + * @property String path The entry's path. + * @property String detail What is wrong with it. + */ + public data class MalformedEntry(val path: String, val detail: String) : UmaReadFailure { + override val description: String get() = "malformed entry '$path': $detail" + } +} + +/** + * A file that cannot be opened as UMA, with the typed reason. + * + * @param UmaReadFailure failure Why the file could not be opened. + * @param Throwable? cause The underlying error, when there is one. + */ +public class UmaFormatException( + public val failure: UmaReadFailure, + cause: Throwable? = null, +) : RuntimeException(failure.description, cause) + +/** + * A document holds a value the UMA format cannot represent, so it cannot be saved. + * + * @param String path Where the value sits: an entry path, or a path within the entry. + * @param String detail What is wrong with it. + * @param Throwable? cause The underlying error, when there is one. + */ +public class UmaWriteException( + public val path: String, + public val detail: String, + cause: Throwable? = null, +) : RuntimeException("cannot write $path: $detail", cause) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaManifest.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaManifest.kt new file mode 100644 index 0000000..d57a366 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaManifest.kt @@ -0,0 +1,356 @@ +package org.umamo.format.uma + +import kotlinx.serialization.DeserializationStrategy +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.intOrNull + +/* + * The manifest's JSON: parsing it with every rule docs/format/UMA.md §3 sets, and emitting it back over the + * tree it was read from, so keys this writer does not own stay where they were. + */ + +/** + * The JSON every UMA entry this codec emits goes through: pretty-printed with tabs, keys in tree order. + * Parsing is plain JSON; unknown keys are kept by working on trees rather than decoding into classes. + */ +@OptIn(ExperimentalSerializationApi::class) +internal val UmaJson: Json = + Json { + prettyPrint = true + prettyPrintIndent = "\t" + } + +/** + * The JSON a domain entry's schema classes decode from and encode to, as trees. + * + * Unknown keys are ignored here because the retained tree keeps them (UMA §4.7); nulls are omitted, so an + * absent optional key and a null are one thing; special floats are refused, since JSON cannot carry them. + */ +internal val UmaEntryJson: Json = + Json { + ignoreUnknownKeys = true + explicitNulls = false + encodeDefaults = false + } + +/** + * A domain entry's tree decoded into its schema class, a tree the schema does not allow reported as the entry being + * malformed (UMA §3.4). + * + * @param Json json The JSON to decode with: [UmaEntryJson], or one with buffers bound. + * @param DeserializationStrategy serializer The schema class's deserializer. + * @param JsonObject tree The entry's JSON. + * @param String path The entry's path, for the failure. + * @return T The decoded content. + * @throws UmaFormatException When the tree breaks the schema. + */ +internal fun decodeUmaEntry(json: Json, serializer: DeserializationStrategy, tree: JsonObject, path: String): T = + try { + json.decodeFromJsonElement(serializer, tree) + } catch (failure: SerializationException) { + throw UmaFormatException(UmaReadFailure.MalformedEntry(path, failure.message.orEmpty()), failure) + } catch (failure: IllegalArgumentException) { + throw UmaFormatException(UmaReadFailure.MalformedEntry(path, failure.message.orEmpty()), failure) + } + +// UMA §3.3: the deepest the manifest or a live entry may nest, the root counting as one level. The JSON parser and +// every walk over a tree - the accessor check, the identity check, the merge, the buffer layout - recurse, so the bound +// keeps each one shallow on any thread whatever the file holds. +internal const val UMA_MAXIMUM_JSON_DEPTH = 256 + +/** + * Whether the JSON [text] nests deeper than [UMA_MAXIMUM_JSON_DEPTH] levels, read off its brackets before it is parsed: + * the parser itself recurses once per nested array, so a tree too deep to walk is too deep to parse. Brackets inside + * strings are not counted. + * + * @param String text The JSON text. + * @return Boolean True when an object or array opens deeper than the limit. + */ +internal fun jsonTextNestsTooDeep(text: String): Boolean { + var depth = 0 + var inString = false + var escaped = false + for (character in text) { + if (inString) { + when { + escaped -> escaped = false + character == '\\' -> escaped = true + character == '"' -> inString = false + } + continue + } + when (character) { + '"' -> inString = true + '{', '[' -> { + depth++ + if (depth > UMA_MAXIMUM_JSON_DEPTH) { + return true + } + } + + '}', ']' -> depth-- + } + } + return false +} + +/** + * Whether [tree] nests deeper than [UMA_MAXIMUM_JSON_DEPTH] levels, for a tree a save built rather than parsed. The + * walk stops as soon as it passes the limit, so its own recursion never goes deeper than the limit however deep the + * tree. + * + * @param JsonElement tree The tree. + * @param Int depth The level [tree] sits at, the root being 1. + * @return Boolean True when an object or array sits deeper than the limit. + */ +internal fun jsonNestsTooDeep(tree: JsonElement, depth: Int = 1): Boolean { + val children = + when (tree) { + is JsonObject -> tree.values + is JsonArray -> tree + else -> return false + } + if (depth > UMA_MAXIMUM_JSON_DEPTH) { + return true + } + for (child in children) { + if (child !is JsonPrimitive && jsonNestsTooDeep(child, depth + 1)) { + return true + } + } + return false +} + +// UMA §3.1: the manifest's own keys. +private const val FORMAT_KEY = "format" +private const val CONTAINER_VERSION_KEY = "containerVersion" +private const val WRITER_KEY = "writer" +private const val ENTRIES_KEY = "entries" + +// UMA §3.1: the writer record's keys. +private const val WRITER_APP_KEY = "app" +private const val WRITER_VERSION_KEY = "version" + +// UMA §3.1: an entry record's keys. +private const val PATH_KEY = "path" +private const val KIND_KEY = "kind" +private const val VERSION_KEY = "version" +private const val MIN_VERSION_KEY = "minVersion" +private const val REQUIRED_KEY = "required" + +/** + * One validated manifest entry record. + * + * @property String path The entry's path. + * @property String kind The entry's kind. + * @property Int version The declared schema version. + * @property Int minVersion The declared minimum schema version. + * @property Boolean required Whether the entry is declared required. + * @property JsonObject record The record as read. + */ +internal class UmaManifestRecord( + val path: String, + val kind: String, + val version: Int, + val minVersion: Int, + val required: Boolean, + val record: JsonObject, +) + +/** + * A validated manifest. + * + * @property UmaWriterInfo? writer The writer record, or null when the manifest has none. + * @property List records The entry records, in manifest order. + * @property JsonObject tree The manifest as read. + */ +internal class UmaParsedManifest( + val writer: UmaWriterInfo?, + val records: List, + val tree: JsonObject, +) + +/** + * Parses and validates a manifest. + * + * `format` is checked before anything else, so a foreign ZIP that happens to carry a `manifest.json` + * reads as not UMA rather than as a malformed UMA. + * + * @param ByteArray bytes The manifest entry's contents. + * @return UmaParsedManifest The validated manifest. + * @throws UmaFormatException When the manifest is not UMA's, too new, or breaks a rule. + */ +internal fun parseUmaManifest(bytes: ByteArray): UmaParsedManifest { + val tree = parseJsonObject(bytes) { detail -> UmaReadFailure.MalformedManifest(detail) } + + // UMA §3.1: `format` must be "uma". + val format = tree[FORMAT_KEY] + if (format !is JsonPrimitive || !format.isString || format.content != UmaContainer.FORMAT_NAME) { + throw UmaFormatException(UmaReadFailure.NotUma("the manifest's format is ${format ?: "absent"}, not \"${UmaContainer.FORMAT_NAME}\"")) + } + + // UMA §3.1: a container version this reader does not know refuses the whole file. + val containerVersion = jsonIntegerOrNull(tree[CONTAINER_VERSION_KEY]) ?: malformedManifest("containerVersion is missing or not an integer") + if (containerVersion > UmaContainer.CONTAINER_VERSION) { + throw UmaFormatException(UmaReadFailure.UnsupportedContainerVersion(containerVersion, UmaContainer.CONTAINER_VERSION)) + } + if (containerVersion < 1) { + malformedManifest("containerVersion $containerVersion is below 1") + } + + val writer = + tree[WRITER_KEY]?.let { element -> + val writerRecord = element as? JsonObject ?: malformedManifest("writer is not an object") + UmaWriterInfo( + app = jsonStringOrNull(writerRecord[WRITER_APP_KEY]) ?: malformedManifest("writer.app is missing or not a string"), + version = jsonStringOrNull(writerRecord[WRITER_VERSION_KEY]) ?: malformedManifest("writer.version is missing or not a string"), + ) + } + + val entriesArray = tree[ENTRIES_KEY] as? JsonArray ?: malformedManifest("entries is missing or not an array") + val records = ArrayList(entriesArray.size) + val seenPaths = HashSet() + val seenKnownKinds = HashSet() + for ((recordIndex, element) in entriesArray.withIndex()) { + val record = element as? JsonObject ?: malformedManifest("entries[$recordIndex] is not an object") + val path = jsonStringOrNull(record[PATH_KEY]) ?: malformedManifest("entries[$recordIndex].path is missing or not a string") + val kind = jsonStringOrNull(record[KIND_KEY]) ?: malformedManifest("entries[$recordIndex].kind is missing or not a string") + val version = jsonIntegerOrNull(record[VERSION_KEY]) ?: malformedManifest("entries[$recordIndex].version is missing or not an integer") + val minVersion = jsonIntegerOrNull(record[MIN_VERSION_KEY]) ?: malformedManifest("entries[$recordIndex].minVersion is missing or not an integer") + val required = jsonBooleanOrNull(record[REQUIRED_KEY]) ?: malformedManifest("entries[$recordIndex].required is missing or not a boolean") + // UMA §3.1: record rules. + if (path.isEmpty() || path.endsWith('/') || UmaContainer.isReservedPath(path)) { + malformedManifest("entries[$recordIndex] names '$path', which cannot hold a domain entry") + } + if (!seenPaths.add(path)) { + malformedManifest("'$path' is listed twice") + } + if (minVersion < 1 || minVersion > version) { + malformedManifest("'$path' declares minVersion $minVersion against version $version") + } + UmaEntryKind.ofWireName(kind)?.let { knownKind -> + if (!seenKnownKinds.add(knownKind)) { + malformedManifest("the ${knownKind.wireName} kind is listed twice") + } + } + records += UmaManifestRecord(path, kind, version, minVersion, required, record) + } + return UmaParsedManifest(writer, records, tree) +} + +/** + * The manifest [model] writes: its manifest as read with the keys this writer owns overwritten, so every + * other key keeps its place (UMA §3.5). + * + * Live entries are declared at this writer's schema version and requiredness (UMA §3.5, always write current); + * preserved entries keep their records exactly. + * + * @param UmaModel model The document being written. + * @return ByteArray The manifest's JSON. + */ +internal fun emitUmaManifest(model: UmaModel): ByteArray { + val manifest = LinkedHashMap(model.manifestTree ?: emptyMap()) + manifest[FORMAT_KEY] = JsonPrimitive(UmaContainer.FORMAT_NAME) + manifest[CONTAINER_VERSION_KEY] = JsonPrimitive(UmaContainer.CONTAINER_VERSION) + val writer = model.writer + if (writer == null) { + manifest.remove(WRITER_KEY) + } else { + val writerRecord = LinkedHashMap((manifest[WRITER_KEY] as? JsonObject) ?: emptyMap()) + writerRecord[WRITER_APP_KEY] = JsonPrimitive(writer.app) + writerRecord[WRITER_VERSION_KEY] = JsonPrimitive(writer.version) + manifest[WRITER_KEY] = JsonObject(writerRecord) + } + manifest[ENTRIES_KEY] = + JsonArray( + model.entries.map { entry -> + when (val content = entry.content) { + is UmaEntryContent.Preserved -> entry.record ?: error("a preserved entry always carries the record it was read with") + is UmaEntryContent.Live -> { + val record = LinkedHashMap(entry.record ?: emptyMap()) + record[PATH_KEY] = JsonPrimitive(entry.path) + record[KIND_KEY] = JsonPrimitive(content.kind.wireName) + record[VERSION_KEY] = JsonPrimitive(content.kind.version) + record[MIN_VERSION_KEY] = JsonPrimitive(content.kind.minVersion) + record[REQUIRED_KEY] = JsonPrimitive(content.kind.required) + JsonObject(record) + } + } + }, + ) + return encodeUmaJson(JsonObject(manifest)) +} + +/** + * Parses [bytes] as one JSON object, reporting any failure through [failureOf]. + * + * @param ByteArray bytes The JSON as UTF-8. + * @param Function failureOf Builds the failure for a detail message. + * @return JsonObject The object. + * @throws UmaFormatException When the bytes are not UTF-8, not JSON, or not an object. + */ +internal fun parseJsonObject(bytes: ByteArray, failureOf: (String) -> UmaReadFailure): JsonObject { + val text = + try { + bytes.decodeToString(throwOnInvalidSequence = true) + } catch (failure: CharacterCodingException) { + throw UmaFormatException(failureOf("not valid UTF-8"), failure) + } + if (jsonTextNestsTooDeep(text)) { + throw UmaFormatException(failureOf("nested deeper than $UMA_MAXIMUM_JSON_DEPTH levels")) + } + val element = + try { + UmaJson.parseToJsonElement(text) + } catch (failure: SerializationException) { + throw UmaFormatException(failureOf("not valid JSON: ${failure.message}"), failure) + } + return element as? JsonObject ?: throw UmaFormatException(failureOf("not a JSON object")) +} + +/** + * [tree] as the UTF-8 JSON this codec writes. + * + * @param JsonObject tree The JSON. + * @return ByteArray The encoded bytes. + */ +internal fun encodeUmaJson(tree: JsonObject): ByteArray = UmaJson.encodeToString(JsonElement.serializer(), tree).encodeToByteArray() + +/** + * Throws the malformed-manifest failure for [detail]. + * + * @param String detail Which rule the manifest breaks. + * @return Nothing Never returns. + */ +private fun malformedManifest(detail: String): Nothing = throw UmaFormatException(UmaReadFailure.MalformedManifest(detail)) + +/** + * [element] as a JSON string's content, or null when it is not a string. + * + * @param JsonElement? element The value. + * @return String? The string. + */ +internal fun jsonStringOrNull(element: JsonElement?): String? = (element as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.content + +/** + * [element] as a JSON integer, or null when it is not a number with an integer literal. + * + * @param JsonElement? element The value. + * @return Int? The integer. + */ +private fun jsonIntegerOrNull(element: JsonElement?): Int? = (element as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.intOrNull + +/** + * [element] as a JSON boolean, or null when it is not one. + * + * @param JsonElement? element The value. + * @return Boolean? The boolean. + */ +private fun jsonBooleanOrNull(element: JsonElement?): Boolean? = (element as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.booleanOrNull \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaModel.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaModel.kt new file mode 100644 index 0000000..4c16dea --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaModel.kt @@ -0,0 +1,560 @@ +package org.umamo.format.uma + +import kotlinx.serialization.json.JsonObject +import org.umamo.format.binary.ZipEntry +import org.umamo.format.binary.ZipFormatException +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.decodeZipPayload +import org.umamo.format.binary.inflateRawDeflate +import org.umamo.format.uma.puppet.UmaPuppet +import org.umamo.format.uma.puppet.UmaPuppetEntry +import org.umamo.format.uma.sources.UmaSources +import org.umamo.format.uma.sources.UmaSourcesEntry +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaTextures +import org.umamo.format.uma.textures.UmaTexturesEntry + +/** + * The application that last wrote a UMA file, as its manifest's `writer` record says. + * + * @property String app The application's name. + * @property String version The application's version. + */ +public data class UmaWriterInfo( + val app: String, + val version: String, +) + +/** Why a manifest-listed entry makes the document read-only (docs/format/UMA.md §3.3). */ +public sealed interface UmaReadOnlyCause { + /** The entry's kind is one this reader does not know. */ + public data object UnknownKind : UmaReadOnlyCause + + /** + * The entry's kind is known, but its `minVersion` says a reader of this version would misread it. + * + * @property Int minVersion The oldest schema version the file allows a reader to treat it as. + * @property Int supported The schema version this reader understands. + */ + public data class UnsupportedVersion(val minVersion: Int, val supported: Int) : UmaReadOnlyCause +} + +/** + * One required entry this reader cannot interpret, which keeps the document from being edited or saved. + * + * @property String path The entry's path. + * @property String kind The entry's manifest `kind`. + * @property UmaReadOnlyCause cause Why this reader cannot interpret it. + */ +public data class UmaReadOnlyReason( + val path: String, + val kind: String, + val cause: UmaReadOnlyCause, +) + +/** + * An archive entry kept exactly as it was read: its ZIP metadata and its payload as stored, for writing + * back without inflating or recompressing it. The payload stays where it is in the file's bytes rather than + * being copied out, so a document holds its file once. + * + * @property ZipEntry zipEntry The entry as the archive declared it; its payload offset locates the payload. + * @property ByteArray archive The whole file's bytes, which hold the payload. + */ +internal class UmaRawEntry( + val zipEntry: ZipEntry, + val archive: ByteArray, +) { + /** + * The first [length] bytes of the payload as stored, or all of them when it is shorter. + * + * @param Int length The most bytes to take. + * @return ByteArray The bytes. + */ + fun storedPrefix(length: Int): ByteArray = archive.copyOfRange(zipEntry.payloadOffset, zipEntry.payloadOffset + minOf(zipEntry.compressedSize, length)) +} + +/** What a manifest-listed entry holds in memory. */ +internal sealed interface UmaEntryContent { + /** + * An entry this reader understands, held as its parsed JSON tree so unknown keys ride along (UMA §4.7). + * + * @property UmaEntryKind kind The entry's kind. + * @property JsonObject tree The entry's JSON. + */ + class Live(val kind: UmaEntryKind, val tree: JsonObject) : UmaEntryContent + + /** + * An entry this reader does not understand, carried byte for byte. + * + * @property UmaRawEntry raw The entry as read. + */ + class Preserved(val raw: UmaRawEntry) : UmaEntryContent +} + +/** + * One manifest-listed domain entry. + * + * @property String path Where the entry lives in the archive. + * @property String kind The manifest `kind` value. + * @property Int version The schema version the file declares. + * @property Int minVersion The oldest schema version the file allows a reader to treat it as. + * @property Boolean required Whether the file declares the entry necessary to interpret the document. + */ +public class UmaEntry internal constructor( + public val path: String, + public val kind: String, + public val version: Int, + public val minVersion: Int, + public val required: Boolean, + /** The manifest record as read, whose unknown keys the writer keeps in place; null for a new entry. */ + internal val record: JsonObject?, + internal val content: UmaEntryContent, +) { + /** The kind this reader interprets the entry as, or null when the entry is carried byte for byte. */ + public val liveKind: UmaEntryKind? + get() = (content as? UmaEntryContent.Live)?.kind +} + +/** + * A payload an entry owns that a save rebuilt or dropped (UMA §3.3): a puppet's buffer (§4.9), a textures + * entry's pixel entries (§5.6). + * + * @property UmaEntryKind owner The entry kind that owns the payload, which a new payload is written after. + * @property ByteArray? bytes The bytes to write stored, or null when the payload leaves the file. + */ +internal class UmaOwnedPayload( + val owner: UmaEntryKind, + val bytes: ByteArray?, +) + +/** + * An archive entry no manifest record names - a texture, a buffer, a thumbnail, or anything a newer + * writer added - carried byte for byte. + * + * @property String path Where the entry lives in the archive. + */ +public class UmaPayload internal constructor( + public val path: String, + internal val raw: UmaRawEntry, +) + +/** + * A UMA document at the container level: the manifest's entries, each either understood or preserved, + * and every other archive entry preserved (docs/format/UMA.md §3). + * + * The domain contents stay raw JSON trees here; the typed schemas are layered on per entry kind. + * Nothing this model did not create is ever dropped: preserved entries and payloads are written back + * exactly as read, and an entry this reader cannot interpret that the file marks required makes the + * document read-only instead of editable. + * + * A document read from a file keeps that file's bytes for its life: its preserved entries and payloads are slices of + * them, never copies, so the file is held once rather than twice. + * + * @property UmaWriterInfo? writer The application that last wrote the file, or null. + * @property List entries The manifest-listed entries, in manifest order. + * @property List payloads Every other archive entry, in archive order. + * @property List readOnlyReasons Each required entry this reader cannot interpret. + */ +public class UmaModel internal constructor( + public val writer: UmaWriterInfo?, + public val entries: List, + public val payloads: List, + public val readOnlyReasons: List, + /** The manifest as read, whose unknown keys the writer keeps in place; null for a new document. */ + internal val manifestTree: JsonObject?, + /** Every non-bootstrap entry path in the order the archive held them; empty for a new document. */ + internal val archiveOrder: List, + /** + * The payloads an entry owns that a save rebuilt or dropped, by path, in write order (UMA §3.3): each written + * stored in place of the payload read, or left out of the file when its bytes are null. + */ + internal val ownedPayloads: Map = emptyMap(), + /** The puppet decode of the document this one derives from, when it is finished and still describes this one. */ + inheritedPuppet: Lazy? = null, + /** The textures decode of the document this one derives from, when it is finished and still describes this one. */ + inheritedTextures: Lazy? = null, + /** The sources decode of the document this one derives from, when it is finished and still describes this one. */ + inheritedSources: Lazy? = null, +) { + /** + * Each buffer payload's decompressed bytes by path, decompressed on first use to resolve accessors. Held as + * lazy values so a document read from several threads decompresses each buffer once and safely. Pixel + * entries never come through here: holding every tile's bytes a second time for the model's life would + * double an open's memory. + */ + private val decodedPayloads: Map> by lazy { + payloads.associate { payload -> + payload.path to + lazy { decodeVerified(payload) } + } + } + + /** Each payload by path, so a lookup per tile at open and at save stays constant-time however many payloads there are. */ + private val payloadByPath: Map by lazy { payloads.associateBy { payload -> payload.path } } + + /** The puppet entry's decode, run once per document; a document derived from this one reuses it while it holds. */ + private val puppetDecode: Lazy = + inheritedPuppet ?: lazy { + entries.firstOrNull { candidate -> candidate.liveKind == UmaEntryKind.Puppet }?.let { entry -> + UmaPuppetEntry.decode((entry.content as UmaEntryContent.Live).tree, entry.path, ::bufferBytes) + } + } + + /** The textures entry's decode, run once per document; a document derived from this one reuses it while it holds. */ + private val texturesDecode: Lazy = + inheritedTextures ?: lazy { + entries.firstOrNull { candidate -> candidate.liveKind == UmaEntryKind.Textures }?.let { entry -> + UmaTexturesEntry.decode((entry.content as UmaEntryContent.Live).tree, entry.path, ::payloadHeader) + } + } + + /** The sources entry's decode, run once per document; a document derived from this one reuses it while it holds. */ + private val sourcesDecode: Lazy = + inheritedSources ?: lazy { + entries.firstOrNull { candidate -> candidate.liveKind == UmaEntryKind.Sources }?.let { entry -> + UmaSourcesEntry.decode((entry.content as UmaEntryContent.Live).tree, entry.path) + } + } + + /** Whether the document holds a required entry this reader cannot interpret, which forbids saving it. */ + public val isReadOnly: Boolean + get() = readOnlyReasons.isNotEmpty() + + /** + * Whether the document's entry of [kind] is one this reader cannot interpret (UMA §3.3). Such an entry occupies + * its kind: a save carries it byte for byte and cannot set that kind's content, so an editor can hold back the + * edits that would need to. + * + * @param UmaEntryKind kind The entry kind. + * @return Boolean True when the kind's entry is carried rather than read. + */ + public fun holdsTooNewEntry(kind: UmaEntryKind): Boolean = entries.any { entry -> entry.liveKind == null && UmaEntryKind.ofWireName(entry.kind) == kind } + + /** + * The puppet entry's content (docs/format/UMA.md §4), or null when the document has no live puppet entry. + * + * Decoded once per model, and reused by a model derived from this one that keeps the entry; a model read from a file + * has already decoded it, so a malformed puppet entry fails the read rather than a later access. + */ + public val puppet: UmaPuppet? by puppetDecode + + /** + * The textures entry's content (docs/format/UMA.md §5), or null when the document has no live textures entry. + * + * Decoded once per model, and reused by a model derived from this one that keeps the entry; a model read from a file + * has already decoded it, so a malformed index, or one that names a pixel entry the archive does not hold, fails the + * read. + */ + public val textures: UmaTextures? by texturesDecode + + /** + * The sources entry's content (docs/format/UMA.md §6), or null when the document has no live sources entry. + * + * Decoded once per model, and reused by a model derived from this one that keeps the entry; a model read from a file + * has already decoded it. + */ + public val sources: UmaSources? by sourcesDecode + + /** + * The editor entry's tree (docs/format/UMA.md §7), or null when the document has no live editor entry. + * + * A dynamic tree rather than a typed decode: the entry is open-ended and read tolerantly by whoever owns each + * member, so there is no schema here to decode against and nothing in it can fail a read. It is never an input + * to the puppet, the atlas, or the sources (UMA §7). + */ + public val editorState: JsonObject? + get() = liveContent(UmaEntryKind.Editor) + + /** + * This document with its puppet entry set to [puppet], laid over the entry's tree as read so every key + * this writer does not own survives (UMA §4.7), or added when the document has no puppet entry. + * + * The puppet's buffer is rebuilt in the same step: every accessor in the merged tree - the new arrays and + * any a newer writer left under keys this one does not know - is laid out afresh in document order. + * + * @param UmaPuppet puppet The puppet. + * @return UmaModel The updated document. + * @throws UmaWriteException When the puppet holds a value the format cannot represent, or the document's puppet + * entry is too new to replace. + */ + public fun withPuppet(puppet: UmaPuppet): UmaModel { + val kind = UmaEntryKind.Puppet + val path = entryPathOf(kind) + val scratch = UmaScratchBuffer() + val encoded = UmaPuppetEntry.encode(puppet, path, scratch) + val merged = mergeRetainedTree(liveContent(kind), encoded, UmaPuppet.serializer().descriptor, UmaPuppetEntry.identities) + val ownedPath = checkNotNull(kind.bufferPath) + // The contract's exception, not check(): the caller's save flow catches UmaWriteException to report + // a document it cannot save, and a foreign writer's manifest can list this path. + if (entries.any { entry -> entry.path == ownedPath }) { + throw UmaWriteException(ownedPath, "is listed in the manifest as an entry, so the puppet cannot own it as its buffer") + } + val scratchBytes = scratch.bytes() + val layout = layOutBuffer(merged, ownedPath) { source -> if (source == UmaAccessor.SCRATCH_BUFFER) scratchBytes else bufferBytes(source) } + return withLiveContent(kind, layout.tree as JsonObject).withOwnedPayloads(kind, mapOf(ownedPath to UmaOwnedPayload(kind, layout.buffer.takeIf { layout.hasAccessors }))) + } + + /** + * This document with its textures entry set to [textures], laid over the entry's tree as read so every key + * this writer does not own survives (UMA §5.8), or added when the document has no textures entry. + * + * The pixel entries are laid out in the same step (UMA §5.7): a tile the file holds keeps its entry byte for + * byte and [pixels] is not asked for it, a new tile's PNG is written at a minted path, the render pages follow + * [pixels]'s mode, the thumbnail is written when given, and every pixel entry the index no longer names leaves + * the file (UMA §5.7). The paths and render pages [textures] carries are ignored. + * + * @param UmaTextures textures The index. + * @param UmaPixelSource pixels The pixels the save writes. + * @return UmaModel The updated document. + * @throws UmaWriteException When a new tile has no pixels, kept render pages are missing, the index breaks a rule + * a reader would refuse, or the document's textures entry is too new to replace. + */ + public fun withTextures(textures: UmaTextures, pixels: UmaPixelSource): UmaModel { + val kind = UmaEntryKind.Textures + val path = entryPathOf(kind) + val pathsInUse = HashSet(archiveOrder) + entries.mapTo(pathsInUse) { entry -> entry.path } + pathsInUse += ownedPayloads.keys + val layout = UmaTexturesEntry.layOut(textures, this.textures, pixels, path, pathsInUse, ::payloadHeader, ::payloadBytes) + val merged = mergeRetainedTree(liveContent(kind), UmaTexturesEntry.encode(layout.textures, path), UmaTextures.serializer().descriptor, UmaTexturesEntry.identities) + // UMA §5.7: pixel entries new to the file follow the index in index order - tiles, render pages, thumbnail - + // whichever save wrote them, so a document saved twice before it is written orders them as one save does. + val owned = LinkedHashMap() + for (namedPath in UmaTexturesEntry.namedPaths(layout.textures)) { + val bytes = layout.payloads[namedPath] + val payload = if (bytes != null) UmaOwnedPayload(kind, bytes) else ownedPayloads[namedPath]?.takeIf { earlier -> earlier.owner == kind } + payload?.let { laidOut -> owned[namedPath] = laidOut } + } + for ((droppedPath, bytes) in layout.payloads) { + if (bytes == null) { + owned[droppedPath] = UmaOwnedPayload(kind, null) + } + } + return withLiveContent(kind, merged as JsonObject).withOwnedPayloads(kind, owned) + } + + /** + * This document with its sources entry set to [sources], laid over the entry's tree as read so every key this + * writer does not own survives (UMA §6.5), or added when the document has no sources entry. + * + * @param UmaSources sources The sources. + * @return UmaModel The updated document. + * @throws UmaWriteException When the sources hold a value a reader would refuse, or the document's sources entry + * is too new to replace. + */ + public fun withSources(sources: UmaSources): UmaModel { + val kind = UmaEntryKind.Sources + val encoded = UmaSourcesEntry.encode(sources, entryPathOf(kind)) + val merged = mergeRetainedTree(liveContent(kind), encoded, UmaSources.serializer().descriptor, UmaSourcesEntry.identities) + return withLiveContent(kind, merged as JsonObject) + } + + /** + * This document with [patch] laid over its editor entry as a JSON Merge Patch (UMA §7.5): a member the patch + * names is set, one it names null is removed, and every other member of the tree as read survives. + * + * A document with no editor entry gains one only when the merge leaves something to write, and a merge that + * changes nothing returns this document, so a save of untouched editor state writes the same bytes. + * + * @param JsonObject patch The members to set, and the ones to remove as nulls. + * @return UmaModel The updated document. + * @throws UmaWriteException When the document's editor entry is too new to replace (check [holdsTooNewEntry] + * first: editor state is never worth refusing a save over), or the merged tree nests deeper than a reader accepts. + */ + public fun withEditorState(patch: JsonObject): UmaModel { + val kind = UmaEntryKind.Editor + val retained = liveContent(kind) + val merged = applyMergePatch(retained ?: JsonObject(emptyMap()), patch) + // UMA §7.5: no entry is added that would be empty, and an unchanged tree is not a new document. + if (merged == retained || (retained == null && merged.isEmpty())) { + return this + } + return withLiveContent(kind, merged) + } + + /** + * The bytes of the payload at [path] - a tile's or a page's PNG, say - as the next save would write them: + * the bytes a save laid out, else the archive's payload decompressed and verified afresh on every call. + * + * @param String path The payload's path. + * @return ByteArray? The bytes, or null when the document holds no such payload. + * @throws UmaFormatException When the payload's bytes fail their size or CRC-32 check. + */ + public fun payloadBytes(path: String): ByteArray? { + ownedPayloads[path]?.let { owned -> return owned.bytes } + val payload = payloadByPath[path] ?: return null + return decodeVerified(payload) + } + + /** + * The first bytes of the payload at [path], enough to read a PNG header, without decompressing more of it than + * that or keeping anything: a check of a pixel entry's size needs no more, and its bytes are verified whenever + * they are read. + * + * @param String path The payload's path. + * @return ByteArray? At most [PAYLOAD_HEADER_BYTES] bytes, or null when the document holds no such payload. + * @throws UmaFormatException When the payload is encrypted or compressed with a method this reader cannot inflate. + */ + internal fun payloadHeader(path: String): ByteArray? { + ownedPayloads[path]?.let { owned -> return owned.bytes?.let { bytes -> bytes.copyOf(minOf(bytes.size, PAYLOAD_HEADER_BYTES)) } } + val payload = payloadByPath[path] ?: return null + val raw = payload.raw + val zipEntry = raw.zipEntry + if (!zipEntry.isEncrypted && zipEntry.method == ZipRecords.METHOD_STORED) { + return raw.storedPrefix(PAYLOAD_HEADER_BYTES) + } + if (!zipEntry.isEncrypted && zipEntry.method == ZipRecords.METHOD_DEFLATED) { + // Only the stream's first bytes are inflated: a deflate block's Huffman tables and 64 bytes of + // output fit well inside the bound, and the inflater copies whatever it is handed before it starts, + // so handing it the whole payload would copy a page-sized PNG to read its header. A stream too + // sparse for the bound (a run of empty blocks) inflates short and takes the full path instead. + val bounded = inflateRawDeflate(raw.archive, zipEntry.payloadOffset, minOf(zipEntry.compressedSize, PAYLOAD_HEADER_SOURCE_BYTES), PAYLOAD_HEADER_BYTES) + if (bounded.size >= minOf(PAYLOAD_HEADER_BYTES, zipEntry.uncompressedSize)) { + return bounded + } + } + // An entry this reader cannot inflate at all fails as reading its bytes does. + val bytes = decodeVerified(payload) + return bytes.copyOf(minOf(bytes.size, PAYLOAD_HEADER_BYTES)) + } + + /** + * The bytes of the buffer at [path]: a buffer a save rebuilt, else an archive payload decompressed on first + * use and kept. + * + * @param String path The buffer's path. + * @return ByteArray? The bytes, or null when the document holds no such buffer. + * @throws UmaFormatException When the payload's bytes fail their size or CRC-32 check. + */ + internal fun bufferBytes(path: String): ByteArray? { + ownedPayloads[path]?.let { owned -> return owned.bytes } + return decodedPayloads[path]?.value + } + + /** + * A payload's bytes, decompressed and checked against the sizes and CRC-32 its entry declares. + * + * @param UmaPayload payload The payload. + * @return ByteArray The bytes. + * @throws UmaFormatException When they fail the check. + */ + private fun decodeVerified(payload: UmaPayload): ByteArray = + try { + decodeZipPayload(payload.raw.zipEntry, payload.raw.archive, payload.raw.zipEntry.payloadOffset) + } catch (failure: ZipFormatException) { + throw UmaFormatException(UmaReadFailure.CorruptContainer(failure.message.orEmpty()), failure) + } + + /** + * The path of this document's entry of [kind], or the kind's default path when it has none. + * + * @param UmaEntryKind kind The entry kind. + * @return String The path. + */ + private fun entryPathOf(kind: UmaEntryKind): String = entries.firstOrNull { entry -> UmaEntryKind.ofWireName(entry.kind) == kind }?.path ?: kind.defaultPath + + /** + * This document with [owned] laid over the payloads a save already owns, in [owned]'s order: the latest layout + * decides where a payload new to the file is written. + * + * @param UmaEntryKind kind The kind whose save laid the payloads out. + * @param Map owned The payloads, by path, in write order. + * @return UmaModel The updated document. + */ + private fun withOwnedPayloads(kind: UmaEntryKind, owned: Map): UmaModel = + derived(writer, entries, ownedPayloads.filterKeys { path -> path !in owned } + owned, kind) + + /** + * The live JSON tree of [kind], or null when the document has no live entry of that kind. + * + * @param UmaEntryKind kind The entry kind. + * @return JsonObject? The entry's tree. + */ + internal fun liveContent(kind: UmaEntryKind): JsonObject? = + entries.firstNotNullOfOrNull { entry -> (entry.content as? UmaEntryContent.Live)?.takeIf { live -> live.kind == kind }?.tree } + + /** + * This document with [kind]'s live content replaced by [tree], or added at the kind's default path when + * the document has none. + * + * @param UmaEntryKind kind The entry kind. + * @param JsonObject tree The entry's new JSON. + * @return UmaModel The updated document. + * @throws UmaWriteException When the kind is occupied by an entry too new to interpret, its default path is taken by + * another entry, or the tree nests deeper than a reader accepts. + */ + internal fun withLiveContent(kind: UmaEntryKind, tree: JsonObject): UmaModel { + // UMA §3.5: a reader refuses a tree nested past the limit, so a save that wrote one could never be reopened. + if (jsonNestsTooDeep(tree)) { + throw UmaWriteException(entryPathOf(kind), "the entry nests deeper than $UMA_MAXIMUM_JSON_DEPTH levels") + } + val existingIndex = entries.indexOfFirst { entry -> UmaEntryKind.ofWireName(entry.kind) == kind } + if (existingIndex >= 0) { + val existing = entries[existingIndex] + // UMA §3.3: an entry too new to interpret occupies its kind; writing a second one beside it would + // leave the file with two entries of one kind, and replacing it would lose what a newer writer put there. + if (existing.content !is UmaEntryContent.Live) { + throw UmaWriteException(existing.path, "the file's ${kind.wireName} entry is too new for this reader to replace") + } + val replaced = UmaEntry(existing.path, existing.kind, existing.version, existing.minVersion, existing.required, existing.record, UmaEntryContent.Live(kind, tree)) + return derived(writer, entries.toMutableList().also { list -> list[existingIndex] = replaced }, ownedPayloads, kind) + } + if (entries.any { entry -> entry.path == kind.defaultPath } || payloads.any { payload -> payload.path == kind.defaultPath }) { + throw UmaWriteException(kind.defaultPath, "the path is already taken, so a new ${kind.wireName} entry has nowhere to go") + } + val added = UmaEntry(kind.defaultPath, kind.wireName, kind.version, kind.minVersion, kind.required, null, UmaEntryContent.Live(kind, tree)) + return derived(writer, entries + added, ownedPayloads, kind) + } + + /** + * This document with its writer record replaced. + * + * @param UmaWriterInfo writer The application writing the file. + * @return UmaModel The updated document. + */ + public fun withWriter(writer: UmaWriterInfo): UmaModel = derived(writer, entries, ownedPayloads, null) + + /** + * A document over the given fields and this one's payloads, handed every finished decode of this one except the + * kind a save set afresh: an entry's decode depends only on its own tree and the payloads its kind owns, so every + * other kind's still describes the new document. + * + * @param UmaWriterInfo? writer The writer record. + * @param List entries The manifest-listed entries. + * @param Map ownedPayloads The payloads a save owns. + * @param UmaEntryKind? replaced The kind whose entry or payloads the new document sets, or null. + * @return UmaModel The document. + */ + private fun derived(writer: UmaWriterInfo?, entries: List, ownedPayloads: Map, replaced: UmaEntryKind?): UmaModel = + UmaModel( + writer, + entries, + payloads, + readOnlyReasons, + manifestTree, + archiveOrder, + ownedPayloads, + inheritedPuppet = puppetDecode.takeIf { decode -> replaced != UmaEntryKind.Puppet && decode.isInitialized() }, + inheritedTextures = texturesDecode.takeIf { decode -> replaced != UmaEntryKind.Textures && decode.isInitialized() }, + inheritedSources = sourcesDecode.takeIf { decode -> replaced != UmaEntryKind.Sources && decode.isInitialized() }, + ) + + public companion object { + /** How many leading bytes [payloadHeader] returns: a PNG signature and its IHDR chunk's header fields. */ + private const val PAYLOAD_HEADER_BYTES = 64 + + /** + * How much of a deflated payload the header probe hands the inflater: enough for a block's + * Huffman tables plus [PAYLOAD_HEADER_BYTES] of literals many times over, and nothing like a page. + */ + private const val PAYLOAD_HEADER_SOURCE_BYTES = 4096 + + /** + * An empty document with no entries, written by [writer]. + * + * @param UmaWriterInfo writer The application creating the document. + * @return UmaModel The document. + */ + public fun create(writer: UmaWriterInfo): UmaModel = UmaModel(writer, emptyList(), emptyList(), emptyList(), null, emptyList()) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaTreeMerge.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaTreeMerge.kt new file mode 100644 index 0000000..57c43f4 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/UmaTreeMerge.kt @@ -0,0 +1,303 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package org.umamo.format.uma + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject + +/* + * The retained-tree merge (docs/format/UMA.md §4.7): a domain entry is written by laying the freshly + * encoded schema object over the JSON tree the file was read with, so every key this reader does not know + * survives the save. The schema's own descriptors say which keys are known, so the merge never drifts from + * the classes; the one thing they cannot say - which array elements are the same object across an edit - + * comes from an identity table per entry kind. + */ + +/** How an array of one element class merges across a save (UMA §4.7). */ +internal sealed interface UmaListRule { + /** + * Elements are matched by an identity read from their JSON, so each keeps its unknown keys. + * + * @property Function identityIn Given the object holding the array, the reader of an element's identity, which + * yields null for an element that carries none. The holder is resolved once per array, so an identity that + * depends on it (a grid cell's key values, read through its grid's axes) costs nothing per element. + */ + class ByIdentity(val identityIn: (JsonObject) -> (JsonObject) -> String?) : UmaListRule + + /** The array is a value: the new array replaces the old one whole, unknown keys inside it included. */ + data object Whole : UmaListRule +} + +/** + * How an entry kind's arrays of objects merge, keyed by the element class's serial name. + * + * @param Map rules Each element class's serial name, mapped to its rule. + */ +internal class UmaIdentityTable(private val rules: Map) { + /** + * The rule for arrays of the class named [serialName], or null when there is none. + * + * @param String serialName The element class's serial name. + * @return UmaListRule? The rule. + */ + fun ruleFor(serialName: String): UmaListRule? = rules[serialName.removeSuffix("?")] +} + +/** The holder an array with no enclosing object resolves its identities in. */ +private val NO_HOLDER: JsonObject = JsonObject(emptyMap()) + +/** + * The rule matching elements by the JSON string at [key], the identity most arrays of objects carry (an `id`, a + * `parameter`, a layer `key`). + * + * @param String key The identifying key. + * @return UmaListRule The rule; an element whose value at [key] is absent or not a string has no identity. + */ +internal fun identityByStringKey(key: String): UmaListRule = UmaListRule.ByIdentity { _ -> { element -> jsonStringOrNull(element[key]) } } + +/** + * [updated] laid over [retained]: known keys from [updated] in schema order, each merged with the retained + * value it replaces, followed by [retained]'s unknown keys in their original order. + * + * A map merges value by value under the same key. Arrays of objects merge element by element through + * [identities]: the output follows [updated]'s order, + * each element merged with the retained element of the same identity, and a retained element with no + * counterpart - a deleted object - leaves with its unknown keys. Arrays of values are replaced whole. A + * known key [updated] omits, because its value is the default, is omitted from the output too - unless it + * holds an object that carries unknown keys, which keeps just those. + * + * @param JsonElement? retained The tree as read, or null for an object new to the file. + * @param JsonElement updated The freshly encoded tree. + * @param SerialDescriptor descriptor The schema of [updated]. + * @param UmaIdentityTable identities The element identities. + * @return JsonElement The merged tree. + * @throws IllegalStateException When the schema holds an array of objects with no identity rule. + */ +internal fun mergeRetainedTree(retained: JsonElement?, updated: JsonElement, descriptor: SerialDescriptor, identities: UmaIdentityTable): JsonElement = + when (descriptor.kind) { + StructureKind.CLASS -> mergeObject(retained as? JsonObject, updated, descriptor, identities) + StructureKind.LIST -> mergeArray(retained as? JsonArray, updated, descriptor.getElementDescriptor(0), identities, NO_HOLDER, NO_HOLDER) + StructureKind.MAP -> mergeMap(retained as? JsonObject, updated, descriptor.getElementDescriptor(1), identities) + else -> updated + } + +/** + * Where [tree] breaks the identity rules: an element of an identity-merged array with no identity, or two + * elements sharing one. + * + * @param JsonElement tree The tree as read. + * @param SerialDescriptor descriptor The schema of [tree]. + * @param UmaIdentityTable identities The element identities. + * @param String path The tree's position, for the report. + * @param JsonObject holder The object holding [tree], which an array's identities resolve in. + * @return String? A description of the first problem, or null when there is none. + */ +internal fun firstIdentityProblem(tree: JsonElement, descriptor: SerialDescriptor, identities: UmaIdentityTable, path: String, holder: JsonObject = NO_HOLDER): String? { + when (descriptor.kind) { + StructureKind.CLASS -> { + val treeObject = tree as? JsonObject ?: return null + for (elementIndex in 0 until descriptor.elementsCount) { + val child = treeObject[descriptor.getElementName(elementIndex)] ?: continue + val childPath = if (path.isEmpty()) descriptor.getElementName(elementIndex) else "$path.${descriptor.getElementName(elementIndex)}" + firstIdentityProblem(child, descriptor.getElementDescriptor(elementIndex), identities, childPath, treeObject)?.let { problem -> return problem } + } + } + + StructureKind.LIST -> { + val treeArray = tree as? JsonArray ?: return null + val elementDescriptor = descriptor.getElementDescriptor(0) + val identityOf = (identities.ruleFor(elementDescriptor.serialName) as? UmaListRule.ByIdentity)?.identityIn?.invoke(holder) + val seen = HashSet() + for ((elementIndex, element) in treeArray.withIndex()) { + if (identityOf != null && element is JsonObject) { + val identity = identityOf(element) ?: return "$path[$elementIndex] has no identity" + if (!seen.add(identity)) { + return "$path[$elementIndex] repeats the identity '${identity.replace(Char(0), ',')}'" + } + } + firstIdentityProblem(element, elementDescriptor, identities, "$path[$elementIndex]")?.let { problem -> return problem } + } + } + + StructureKind.MAP -> { + val treeObject = tree as? JsonObject ?: return null + val valueDescriptor = descriptor.getElementDescriptor(1) + for ((key, value) in treeObject) { + firstIdentityProblem(value, valueDescriptor, identities, "$path.$key")?.let { problem -> return problem } + } + } + + else -> {} + } + return null +} + +/** + * The object merge; see [mergeRetainedTree]. + * + * @param JsonObject? retained The object as read, or null. + * @param JsonElement updated The freshly encoded object. + * @param SerialDescriptor descriptor The object's schema. + * @param UmaIdentityTable identities The element identities. + * @return JsonElement The merged object. + */ +private fun mergeObject(retained: JsonObject?, updated: JsonElement, descriptor: SerialDescriptor, identities: UmaIdentityTable): JsonElement { + val updatedObject = updated as? JsonObject ?: return updated + val merged = LinkedHashMap() + val knownKeys = HashSet(descriptor.elementsCount) + for (elementIndex in 0 until descriptor.elementsCount) { + val key = descriptor.getElementName(elementIndex) + knownKeys += key + val elementDescriptor = descriptor.getElementDescriptor(elementIndex) + val value = updatedObject[key] + if (value != null) { + // UMA §4.7: an array's identities resolve in the object holding it - the retained elements in the object as + // read, the new ones in the object as written - so a grid's cells read their key values through their own axes. + merged[key] = + if (elementDescriptor.kind == StructureKind.LIST) { + mergeArray(retained?.get(key) as? JsonArray, value, elementDescriptor.getElementDescriptor(0), identities, retained ?: NO_HOLDER, updatedObject) + } else { + mergeRetainedTree(retained?.get(key), value, elementDescriptor, identities) + } + continue + } + // UMA §4.7: an object omitted because everything it knows is at its default (a part's composite) still + // carries the keys this reader did not know, so it keeps an object holding just those. An object with a + // required key (a tile's placement, a drawable's mesh) is omitted because it is gone, and its unknown keys + // leave with it, as a deleted array element's do; keeping them would write an object no reader accepts. + val retainedChild = retained?.get(key) as? JsonObject + if (retainedChild != null && elementDescriptor.kind == StructureKind.CLASS && everyElementIsOptional(elementDescriptor)) { + val unknownOnly = mergeObject(retainedChild, JsonObject(emptyMap()), elementDescriptor, identities) as JsonObject + if (unknownOnly.isNotEmpty()) { + merged[key] = unknownOnly + } + } + } + // UMA §4.7: unknown keys follow the known ones, so a document without them writes the same bytes + // whichever file it was last read from. + retained?.forEach { (key, value) -> + if (key !in knownKeys) { + merged[key] = value + } + } + return JsonObject(merged) +} + +/** + * Whether every key of the class [descriptor] describes may be absent, so an object holding none of them is + * still one a reader accepts. + * + * @param SerialDescriptor descriptor The class's schema. + * @return Boolean True when no key is required. + */ +private fun everyElementIsOptional(descriptor: SerialDescriptor): Boolean = (0 until descriptor.elementsCount).all { elementIndex -> descriptor.isElementOptional(elementIndex) } + +/** + * The array merge; see [mergeRetainedTree]. + * + * @param JsonArray? retained The array as read, or null. + * @param JsonElement updated The freshly encoded array. + * @param SerialDescriptor elementDescriptor The elements' schema. + * @param UmaIdentityTable identities The element identities. + * @param JsonObject retainedHolder The object holding [retained], as read. + * @param JsonObject updatedHolder The object holding [updated], as written. + * @return JsonElement The merged array. + */ +private fun mergeArray( + retained: JsonArray?, + updated: JsonElement, + elementDescriptor: SerialDescriptor, + identities: UmaIdentityTable, + retainedHolder: JsonObject, + updatedHolder: JsonObject, +): JsonElement { + val updatedArray = updated as? JsonArray ?: return updated + if (elementDescriptor.kind != StructureKind.CLASS) { + return updatedArray + } + val rule = + when ( + val listRule = + checkNotNull(identities.ruleFor(elementDescriptor.serialName)) { + "${elementDescriptor.serialName} has no list rule, so its unknown keys could not survive a save" + } + ) { + UmaListRule.Whole -> return updatedArray + is UmaListRule.ByIdentity -> listRule + } + val retainedIdentityOf = rule.identityIn(retainedHolder) + val updatedIdentityOf = rule.identityIn(updatedHolder) + val retainedByIdentity = HashMap() + retained?.forEach { element -> + val retainedElement = element as? JsonObject ?: return@forEach + val identity = retainedIdentityOf(retainedElement) ?: return@forEach + // Identities are unique in any tree that was read (firstIdentityProblem); the first wins regardless. + if (identity !in retainedByIdentity) { + retainedByIdentity[identity] = retainedElement + } + } + return JsonArray( + updatedArray.map { element -> + val twin = (element as? JsonObject)?.let(updatedIdentityOf)?.let(retainedByIdentity::get) + mergeRetainedTree(twin, element, elementDescriptor, identities) + }, + ) +} + +/** + * The map merge; see [mergeRetainedTree]. Keys follow [updated]; a key [updated] no longer holds leaves. + * + * @param JsonObject? retained The map as read, or null. + * @param JsonElement updated The freshly encoded map. + * @param SerialDescriptor valueDescriptor The values' schema. + * @param UmaIdentityTable identities The element identities. + * @return JsonElement The merged map. + */ +private fun mergeMap(retained: JsonObject?, updated: JsonElement, valueDescriptor: SerialDescriptor, identities: UmaIdentityTable): JsonElement { + val updatedObject = updated as? JsonObject ?: return updated + return JsonObject(updatedObject.mapValuesTo(LinkedHashMap()) { (key, value) -> mergeRetainedTree(retained?.get(key), value, valueDescriptor, identities) }) +} + +/** + * [patch] applied to [target] as a JSON Merge Patch (RFC 7386), which is how the editor entry is written over the + * tree as read (docs/format/UMA.md §7.5). + * + * The editor entry is a dynamic tree with no schema descriptor to say which keys a writer knows, so it cannot go + * through [mergeRetainedTree]. The patch says it instead: a member it names is set, a member it names `null` is + * removed, and a member it does not name survives - which is what keeps a newer writer's members in the file. + * Objects merge member by member; any other value replaces whole. An object the merge leaves with no members is + * removed in turn, so a deviation that returns to its default does not leave an empty block behind. + * + * Members keep the order [target] had them in, and new ones follow in [patch]'s order, so the same state always + * writes the same bytes. + * + * @param JsonObject target The tree as read. + * @param JsonObject patch The members to set, and the ones to remove as nulls. + * @return JsonObject The merged tree, holding no null this patch placed. + */ +internal fun applyMergePatch(target: JsonObject, patch: JsonObject): JsonObject { + val merged = LinkedHashMap(target) + for ((memberName, patchValue) in patch) { + when (patchValue) { + // UMA §7.5: null removes. + is JsonNull -> merged.remove(memberName) + + is JsonObject -> { + val mergedChild = applyMergePatch(merged[memberName] as? JsonObject ?: JsonObject(emptyMap()), patchValue) + if (mergedChild.isEmpty()) { + merged.remove(memberName) + } else { + merged[memberName] = mergedChild + } + } + + else -> merged[memberName] = patchValue + } + } + return JsonObject(merged) +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppet.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppet.kt new file mode 100644 index 0000000..6ee19fc --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppet.kt @@ -0,0 +1,274 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.Serializable + +/* + * The puppet entry's file-side shape (docs/format/UMA.md §4): `model/puppet.json` as it is written, one + * class per object the schema names, properties in the order the file lists them. + * + * Every optional property is nullable with a null default, so an absent key and a null are the same + * thing and neither is written. What counts as a default is decided by the bridge that fills these + * classes, not here: a value is left out only when it is bit-for-bit the model's own default, which a + * default value on these properties could not express (an IEEE comparison takes -0.0 for 0.0). + */ + +/** + * The root of `model/puppet.json`: the document fields and the puppet's object lists. + * + * @property Float? canvasWidth UMA §4.2: the canvas width in world units. + * @property Float? canvasHeight UMA §4.2: the canvas height in world units. + * @property Float? worldOriginX UMA §4.2: the world origin's x in world space. + * @property Float? worldOriginZ UMA §4.2: the world origin's z (up) in world space. + * @property Float? pixelsPerUnit UMA §4.2: the bake scale, absent when the document has none. + * @property UmaRuntimeTarget? runtimeTarget UMA §4.2: the runtime-compatibility target. + * @property Boolean? rendersFromSourceLayers UMA §4.2: whether the puppet displays its source art. + * @property List? parameters UMA §4.3: the parameter axes. + * @property List? parameterLinks UMA §4.3: the linked 2D parameter pairs. + * @property List? parameterTree UMA §4.3: the parameter panel's group tree. + * @property String? rootPart UMA §4.2: the organizational tree's root part id. + * @property List? rootChildren UMA §4.2: the organizational tree's top level. + * @property List? parts UMA §4.4: the parts. + * @property List? deformers UMA §4.5: the deformers. + * @property List? drawables UMA §4.6: the drawables. + * @property List? glues UMA §4.14: the glue affecters. + */ +@Serializable +public data class UmaPuppet( + val canvasWidth: Float? = null, + val canvasHeight: Float? = null, + val worldOriginX: Float? = null, + val worldOriginZ: Float? = null, + val pixelsPerUnit: Float? = null, + val runtimeTarget: UmaRuntimeTarget? = null, + val rendersFromSourceLayers: Boolean? = null, + val parameters: List? = null, + val parameterLinks: List? = null, + val parameterTree: List? = null, + val rootPart: String? = null, + val rootChildren: List? = null, + val parts: List? = null, + val deformers: List? = null, + val drawables: List? = null, + val glues: List? = null, +) + +/** + * UMA §4.3: one parameter axis. + * + * @property String id The format-level identifier, verbatim. + * @property String name The display name. + * @property Float min The lower limit. + * @property Float max The upper limit. + * @property Float default The resting value. + * @property UmaParameterKind? kind Absent for a normal parameter. + * @property Boolean? repeat Absent when the axis clamps. + */ +@Serializable +public data class UmaParameter( + val id: String, + val name: String, + val min: Float, + val max: Float, + val default: Float, + val kind: UmaParameterKind? = null, + val repeat: Boolean? = null, +) + +/** + * UMA §4.3: two parameters presented as one 2D pad. + * + * @property String horizontal The X-axis parameter id. + * @property String vertical The Y-axis parameter id. + */ +@Serializable +public data class UmaParameterLink( + val horizontal: String, + val vertical: String, +) + +/** + * UMA §4.3: one node of the parameter panel's tree - a leaf naming a parameter, or a group. Exactly one + * of [parameter] and [group] is set; a leaf carries nothing else. + * + * @property String? parameter A leaf's parameter id. + * @property String? group A group's id. + * @property String? name A group's display name (required for a group). + * @property Boolean? initiallyOpen A group's saved expanded state, absent when closed. + * @property List? children A group's children, absent when it has none. + */ +@Serializable +public data class UmaParameterNode( + val parameter: String? = null, + val group: String? = null, + val name: String? = null, + val initiallyOpen: Boolean? = null, + val children: List? = null, +) + +/** + * UMA §4.2: one entry of an ordered organizational child list - a part or a drawable. Exactly one of + * the two is set. + * + * @property String? part A sub-part's id. + * @property String? drawable A drawable's id. + */ +@Serializable +public data class UmaOrgRef( + val part: String? = null, + val drawable: String? = null, +) + +/** + * UMA §4.4: one part of the organizational tree. + * + * @property String id The part id. + * @property String name The display name. + * @property List? children The ordered children, absent when none. + * @property Boolean? isVisible Absent when visible. + * @property Boolean? isSketch Absent when not a guide-image part. + * @property Boolean? isSelectable Absent when selectable. + * @property UmaGroupMode? groupMode Absent for pass-through. + * @property Int? drawOrder Absent at the neutral 500. + * @property UmaPartComposite? composite Absent when every composite setting is at its default. + * @property Map? channels UMA §4.12: the keyed channels, absent when none. + * @property List? blendShapes UMA §4.13: the blend-shape bindings, absent when none. + */ +@Serializable +public data class UmaPart( + val id: String, + val name: String, + val children: List? = null, + val isVisible: Boolean? = null, + val isSketch: Boolean? = null, + val isSelectable: Boolean? = null, + val groupMode: UmaGroupMode? = null, + val drawOrder: Int? = null, + val composite: UmaPartComposite? = null, + val channels: Map? = null, + val blendShapes: List? = null, +) + +/** + * UMA §4.4: a part's latent compositing settings. + * + * @property UmaBlendMode? blendMode Absent for normal. + * @property UmaAlphaBlendMode? alphaBlendMode Absent for over. + * @property List? maskedBy The clipping drawables' ids, absent when none. + * @property List? maskedByParts The clipping parts' ids, absent when none. + * @property Boolean? invertMask Absent when the clip is not inverted. + * @property Float? opacity Absent at 1. + * @property List? multiplyColor Red, green, blue; absent at white. + * @property List? screenColor Red, green, blue; absent at black. + */ +@Serializable +public data class UmaPartComposite( + val blendMode: UmaBlendMode? = null, + val alphaBlendMode: UmaAlphaBlendMode? = null, + val maskedBy: List? = null, + val maskedByParts: List? = null, + val invertMask: Boolean? = null, + val opacity: Float? = null, + val multiplyColor: List? = null, + val screenColor: List? = null, +) + +/** + * UMA §4.5: one deformer. [kind] decides which of the kind-specific properties are required and which + * are not allowed: a warp carries [rows], [columns], and [isQuadTransform]; a rotation carries + * [baseAngle] and may carry [flipX] and [flipY]. + * + * @property String id The deformer id. + * @property UmaDeformerKind kind Warp or rotation. + * @property String name The display name. + * @property String? parent The parent deformer's id, absent at the root. + * @property String? part The owning part's id, absent at the root. + * @property Boolean? isVisible Absent when visible. + * @property Boolean? isEnabled Absent when enabled. + * @property Boolean? isSelectable Absent when selectable. + * @property Float? opacity Absent at 1. + * @property List? multiplyColor Red, green, blue; absent at white. + * @property List? screenColor Red, green, blue; absent at black. + * @property Int? rows A warp's lattice rows. + * @property Int? columns A warp's lattice columns. + * @property Boolean? isQuadTransform A warp's interpolation mode. + * @property Float? baseAngle A rotation's reference angle. + * @property Boolean? flipX A rotation's static horizontal reflection, absent when false. + * @property Boolean? flipY A rotation's static vertical reflection, absent when false. + * @property UmaDeformerGrid? geometry UMA §4.11: the geometry keyform grid, absent when unkeyed. + * @property Map? channels UMA §4.12: the keyed channels, absent when none. + * @property List? blendShapes UMA §4.13: the blend-shape bindings, absent when none. + */ +@Serializable +public data class UmaDeformer( + val id: String, + val kind: UmaDeformerKind, + val name: String, + val parent: String? = null, + val part: String? = null, + val isVisible: Boolean? = null, + val isEnabled: Boolean? = null, + val isSelectable: Boolean? = null, + val opacity: Float? = null, + val multiplyColor: List? = null, + val screenColor: List? = null, + val rows: Int? = null, + val columns: Int? = null, + val isQuadTransform: Boolean? = null, + val baseAngle: Float? = null, + val flipX: Boolean? = null, + val flipY: Boolean? = null, + val geometry: UmaDeformerGrid? = null, + val channels: Map? = null, + val blendShapes: List? = null, +) + +/** + * UMA §4.6: one drawable. Its mesh, keyforms, and blend shapes are the geometry half of the schema + * (§4.10-§4.13). + * + * @property String id The drawable id. + * @property String name The display name. + * @property String? parentDeformer The deforming parent's id, absent when undeformed. + * @property UmaBlendMode? blendMode Absent for normal. + * @property List? maskedBy The clipping drawables' ids, absent when none. + * @property Boolean? invertMask Absent when the clip is not inverted. + * @property Float? drawOrder Absent at the neutral 500. + * @property Float? opacity Absent at 1. + * @property List? multiplyColor Red, green, blue; absent at white. + * @property List? screenColor Red, green, blue; absent at black. + * @property UmaAlphaBlendMode? alphaBlendMode Absent for over. + * @property Boolean? culling Absent when double-sided. + * @property Boolean? isVisible Absent when visible. + * @property Boolean? isSelectable Absent when selectable. + * @property String? textureSource The drawable whose texture binding this one shares, absent when its own. + * @property Int? texturePage The page a MOC3-origin drawable samples, absent when none. + * @property String? atlasTile The atlas tile its art is, a reference into the textures entry. + * @property UmaMesh? mesh UMA §4.10: the rest-pose mesh, absent when none. + * @property UmaMeshGrid? geometry UMA §4.11: the geometry keyform grid, absent when unkeyed. + * @property Map? channels UMA §4.12: the keyed channels, absent when none. + * @property List? blendShapes UMA §4.13: the blend-shape bindings, absent when none. + */ +@Serializable +public data class UmaDrawable( + val id: String, + val name: String, + val parentDeformer: String? = null, + val blendMode: UmaBlendMode? = null, + val maskedBy: List? = null, + val invertMask: Boolean? = null, + val drawOrder: Float? = null, + val opacity: Float? = null, + val multiplyColor: List? = null, + val screenColor: List? = null, + val alphaBlendMode: UmaAlphaBlendMode? = null, + val culling: Boolean? = null, + val isVisible: Boolean? = null, + val isSelectable: Boolean? = null, + val textureSource: String? = null, + val texturePage: Int? = null, + val atlasTile: String? = null, + val mesh: UmaMesh? = null, + val geometry: UmaMeshGrid? = null, + val channels: Map? = null, + val blendShapes: List? = null, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetEntry.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetEntry.kt new file mode 100644 index 0000000..57b4940 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetEntry.kt @@ -0,0 +1,211 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.floatOrNull +import kotlinx.serialization.json.intOrNull +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaIdentityTable +import org.umamo.format.uma.UmaListRule +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaScratchBuffer +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.decodeUmaEntry +import org.umamo.format.uma.firstAccessorProblem +import org.umamo.format.uma.firstIdentityProblem +import org.umamo.format.uma.identityByStringKey +import org.umamo.format.uma.jsonStringOrNull +import org.umamo.format.uma.umaEntryJsonWithBuffers + +/** + * The puppet entry's codec over its JSON tree: decoding with every rule UMA §4 sets, encoding for a save, + * and the element identities its arrays merge by. + */ +internal object UmaPuppetEntry { + // Separates the two ids of a composite identity: the NUL character, which no id contains. Built with Char(0) + // rather than written as a character literal, so the source stays plain text. + private val IDENTITY_SEPARATOR: Char = Char(0) + + /** + * UMA §4.7: how each array of objects in the puppet entry matches elements across a save. A parameter, + * part, deformer, or drawable is its id; a link is its pair; a parameter-tree node and an org ref are + * their id qualified by which kind of id it is, so a part and a drawable that share a raw id stay apart. + * A grid axis, a blend shape, and a limit are their parameter; a cell is its key value on each axis; a glue is + * its ordered mesh pair. Blend forms and limit points are values, replaced whole. + */ + val identities: UmaIdentityTable = + UmaIdentityTable( + mapOf( + UmaParameter.serializer().descriptor.serialName to identityByStringKey("id"), + UmaPart.serializer().descriptor.serialName to identityByStringKey("id"), + UmaDeformer.serializer().descriptor.serialName to identityByStringKey("id"), + UmaDrawable.serializer().descriptor.serialName to identityByStringKey("id"), + UmaParameterLink.serializer().descriptor.serialName to byKeyPair("horizontal", "vertical"), + UmaParameterNode.serializer().descriptor.serialName to byOneOfKeys("parameter", "group"), + UmaOrgRef.serializer().descriptor.serialName to byOneOfKeys("part", "drawable"), + UmaAxis.serializer().descriptor.serialName to identityByStringKey("parameter"), + UmaMeshCell.serializer().descriptor.serialName to UmaListRule.ByIdentity(::cellIdentitiesIn), + UmaDeformerCell.serializer().descriptor.serialName to UmaListRule.ByIdentity(::cellIdentitiesIn), + UmaChannelCell.serializer().descriptor.serialName to UmaListRule.ByIdentity(::cellIdentitiesIn), + UmaMeshBlendShape.serializer().descriptor.serialName to identityByStringKey("parameter"), + UmaDeformerBlendShape.serializer().descriptor.serialName to identityByStringKey("parameter"), + UmaPartBlendShape.serializer().descriptor.serialName to identityByStringKey("parameter"), + UmaBlendLimit.serializer().descriptor.serialName to identityByStringKey("parameter"), + UmaGlue.serializer().descriptor.serialName to byKeyPair("meshA", "meshB"), + UmaMeshForm.serializer().descriptor.serialName to UmaListRule.Whole, + UmaDeformerForm.serializer().descriptor.serialName to UmaListRule.Whole, + UmaPartForm.serializer().descriptor.serialName to UmaListRule.Whole, + UmaBlendLimitPoint.serializer().descriptor.serialName to UmaListRule.Whole, + ), + ) + + /** + * Decodes a puppet entry's tree, failing loudly on anything the schema does not allow. + * + * @param JsonObject tree The entry's JSON. + * @param String path The entry's path, for the failure. + * @param Function buffers Resolves a buffer path to its bytes, or null when there is no such buffer. + * @return UmaPuppet The puppet. + * @throws UmaFormatException When the tree breaks the schema or a shape rule, names bytes a buffer does not hold, + * or repeats an identity. + */ + fun decode(tree: JsonObject, path: String, buffers: (String) -> ByteArray?): UmaPuppet { + // UMA §4.9: every accessor is checked, including those under keys this reader does not know, since a + // save copies their bytes too. + firstAccessorProblem(tree, buffers)?.let { problem -> + throw UmaFormatException(UmaReadFailure.MalformedEntry(path, problem)) + } + val puppet = decodeUmaEntry(umaEntryJsonWithBuffers(buffers, null), UmaPuppet.serializer(), tree, path) + // UMA §4.8: the shape rules come before identities, so a coordinate outside its axis is reported as that + // rather than as a cell with no identity. + val problem = UmaPuppetShape.firstProblem(puppet) ?: firstIdentityProblem(tree, UmaPuppet.serializer().descriptor, identities, "") + if (problem != null) { + throw UmaFormatException(UmaReadFailure.MalformedEntry(path, problem)) + } + return puppet + } + + /** + * Encodes a puppet for a save, its bulk arrays appended to [scratch] and named by accessors into it. + * + * @param UmaPuppet puppet The puppet. + * @param String path The entry's path, for the failure. + * @param UmaScratchBuffer scratch The buffer new arrays append to. + * @return JsonObject The entry's JSON, before any merge or buffer layout. + * @throws UmaWriteException When a value cannot be written, such as a non-finite inline float, or the puppet + * breaks a rule a reader would refuse. + */ + fun encode(puppet: UmaPuppet, path: String, scratch: UmaScratchBuffer): JsonObject { + // UMA §4.8: a reader refuses a puppet that breaks a shape rule or repeats an identity, so a save that wrote one + // could never be reopened. + UmaPuppetShape.firstProblem(puppet)?.let { problem -> throw UmaWriteException(path, problem) } + val tree = + try { + umaEntryJsonWithBuffers({ null }, scratch).encodeToJsonElement(UmaPuppet.serializer(), puppet) as JsonObject + } catch (failure: SerializationException) { + // UMA §4.1: JSON has no NaN or infinity, so a non-finite value refuses the save. + throw UmaWriteException(path, failure.message.orEmpty(), failure) + } + firstIdentityProblem(tree, UmaPuppet.serializer().descriptor, identities, "")?.let { problem -> throw UmaWriteException(path, problem) } + return tree + } + + /** + * The rule matching elements by the ordered pair of strings at [firstKey] and [secondKey]. + * + * @param String firstKey The first identifying key. + * @param String secondKey The second identifying key. + * @return UmaListRule The rule. + */ + private fun byKeyPair(firstKey: String, secondKey: String): UmaListRule = + UmaListRule.ByIdentity { _ -> + { element -> + val first = jsonStringOrNull(element[firstKey]) + val second = jsonStringOrNull(element[secondKey]) + if (first == null || second == null) null else "$first$IDENTITY_SEPARATOR$second" + } + } + + /** + * The rule matching elements that hold exactly one of two kinds of id by that id, qualified by its kind: the key + * it sits under. + * + * @param String firstKey The first kind's key. + * @param String secondKey The second kind's key. + * @return UmaListRule The rule; an element holding neither id or both has no identity. + */ + private fun byOneOfKeys(firstKey: String, secondKey: String): UmaListRule = + UmaListRule.ByIdentity { _ -> + { element -> + val firstId = jsonStringOrNull(element[firstKey]) + val secondId = jsonStringOrNull(element[secondKey]) + when { + firstId != null && secondId == null -> "$firstKey:$firstId" + secondId != null && firstId == null -> "$secondKey:$secondId" + else -> null + } + } + } + + /** + * One grid axis as a cell's identity reads it. + * + * @property String parameter The axis's parameter. + * @property List keys The axis's keys, a negative zero read as zero. + * @property IntArray occurrences Each key's count of the equal keys before it. + */ + private class IdentityAxis( + val parameter: String, + val keys: List, + val occurrences: IntArray, + ) + + /** + * The reader of a cell's identity in [grid] (UMA §4.7): the key value the cell sits at on each axis, named by the + * axis's parameter and in parameter order, so a key added before the cell or a reordering of the axes leaves it + * the same cell. A repeated key is told apart by its position among the keys equal to it. The axes are read once + * per grid; a cell whose coordinate does not resolve through them has no identity, which the shape rules report + * first. + * + * @param JsonObject grid The grid holding the cells. + * @return Function The identity reader. + */ + private fun cellIdentitiesIn(grid: JsonObject): (JsonObject) -> String? { + val axisTrees = grid["axes"] as? JsonArray ?: return { null } + val axes = ArrayList(axisTrees.size) + for (axisTree in axisTrees) { + val axis = axisTree as? JsonObject ?: return { null } + val parameter = jsonStringOrNull(axis["parameter"]) ?: return { null } + val keyTrees = axis["keys"] as? JsonArray ?: return { null } + val keys = + keyTrees.map { keyTree -> + val key = (keyTree as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.floatOrNull ?: return { null } + if (key == 0f) 0f else key + } + axes += IdentityAxis(parameter, keys, IntArray(keys.size) { keyIndex -> (0 until keyIndex).count { earlierIndex -> keys[earlierIndex] == keys[keyIndex] } }) + } + val axisOrder = axes.indices.sortedBy { axisIndex -> axes[axisIndex].parameter } + return identity@{ cell -> + val coordinate = cell["coordinate"] as? JsonArray ?: return@identity null + if (coordinate.size != axes.size) { + return@identity null + } + val keyIndices = IntArray(axes.size) + for ((axisIndex, component) in coordinate.withIndex()) { + val keyIndex = (component as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.intOrNull ?: return@identity null + if (keyIndex !in axes[axisIndex].keys.indices) { + return@identity null + } + keyIndices[axisIndex] = keyIndex + } + axisOrder.joinToString(IDENTITY_SEPARATOR.toString()) { axisIndex -> + val axis = axes[axisIndex] + val keyIndex = keyIndices[axisIndex] + val occurrence = axis.occurrences[keyIndex] + if (occurrence == 0) "${axis.parameter}=${axis.keys[keyIndex]}" else "${axis.parameter}=${axis.keys[keyIndex]}#$occurrence" + } + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetEnums.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetEnums.kt new file mode 100644 index 0000000..90e3349 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetEnums.kt @@ -0,0 +1,149 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/* + * The puppet entry's enum values, each spelled in the file by its @SerialName (docs/format/UMA.md §4.1). + * The serial names are the table: renaming a constant here or in the runtime model never changes a + * file. A value this reader does not know is a malformed entry, so a writer adding a value must raise the + * entry's minVersion. + */ + +/** UMA §4.1: a color blend mode, for drawables and part composites. */ +@Serializable +public enum class UmaBlendMode { + @SerialName("normal") + Normal, + + @SerialName("additivePremultiplied") + AdditivePremultiplied, + + @SerialName("multiplyPremultiplied") + MultiplyPremultiplied, + + @SerialName("additive") + Additive, + + @SerialName("additiveGlow") + AdditiveGlow, + + @SerialName("darken") + Darken, + + @SerialName("multiply") + Multiply, + + @SerialName("colorBurn") + ColorBurn, + + @SerialName("linearBurn") + LinearBurn, + + @SerialName("lighten") + Lighten, + + @SerialName("screen") + Screen, + + @SerialName("colorDodge") + ColorDodge, + + @SerialName("overlay") + Overlay, + + @SerialName("softLight") + SoftLight, + + @SerialName("hardLight") + HardLight, + + @SerialName("linearLight") + LinearLight, + + @SerialName("hue") + Hue, + + @SerialName("color") + Color, +} + +/** UMA §4.1: an alpha blend mode, for drawables and part composites. */ +@Serializable +public enum class UmaAlphaBlendMode { + @SerialName("over") + Over, + + @SerialName("atop") + Atop, + + @SerialName("out") + Out, + + @SerialName("conjoint") + Conjoint, + + @SerialName("disjoint") + Disjoint, +} + +/** UMA §4.3: what a parameter drives. */ +@Serializable +public enum class UmaParameterKind { + @SerialName("normal") + Normal, + + @SerialName("blendShape") + BlendShape, +} + +/** UMA §4.4: how a part groups its subtree for rendering. */ +@Serializable +public enum class UmaGroupMode { + @SerialName("passThrough") + PassThrough, + + @SerialName("grouped") + Grouped, + + @SerialName("isolated") + Isolated, +} + +/** UMA §4.2: the document's runtime-compatibility target. */ +@Serializable +public enum class UmaRuntimeTarget { + @SerialName("noTarget") + NoTarget, + + @SerialName("ayagami") + Ayagami, + + @SerialName("cubism30") + Cubism30, + + @SerialName("cubism33") + Cubism33, + + @SerialName("cubism40") + Cubism40, + + @SerialName("cubism42") + Cubism42, + + @SerialName("cubism50") + Cubism50, + + @SerialName("cubism53") + Cubism53, +} + +/** UMA §4.5: a deformer's kind. */ +@Serializable +public enum class UmaDeformerKind { + @SerialName("warp") + Warp, + + @SerialName("rotation") + Rotation, +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetGeometry.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetGeometry.kt new file mode 100644 index 0000000..7062948 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetGeometry.kt @@ -0,0 +1,323 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.Contextual +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement + +/* + * The puppet entry's geometry half (docs/format/UMA.md §4.10-§4.14): meshes, keyform grids, channel tracks, + * blend shapes, and glue. Per-vertex and per-control-point arrays are @Contextual so they travel as accessors + * into the entry's buffer (§4.9); everything else is inline JSON. + * + * Classes holding arrays are plain classes rather than data classes, since a generated equality would compare + * the arrays by reference and read as structural when it is not. + */ + +/** + * UMA §4.10: a drawable's rest-pose mesh. + * + * @property FloatArray positions x, y per vertex of the rest pose, before any deformer applies (an accessor). + * @property FloatArray uvs u, v per vertex (an accessor). + * @property IntArray indices Three per triangle (an accessor). + */ +@Serializable +public class UmaMesh( + @Contextual val positions: FloatArray, + @Contextual val uvs: FloatArray, + @Contextual val indices: IntArray, +) + +/** + * UMA §4.11: one axis of a keyform grid. + * + * @property String parameter The parameter the axis keys on. + * @property List keys The parameter values keyed, inline. + */ +@Serializable +public data class UmaAxis( + val parameter: String, + val keys: List, +) + +/** + * UMA §4.11: a drawable's geometry keyform grid. + * + * @property List axes The axes. + * @property List cells The keyed cells, in the model's order. + */ +@Serializable +public data class UmaMeshGrid( + val axes: List, + val cells: List, +) + +/** + * UMA §4.11: one cell of a drawable's geometry grid. + * + * @property List coordinate The key index per axis. + * @property FloatArray positionDeltas x, y per vertex, relative to the rest mesh (an accessor). + */ +@Serializable +public class UmaMeshCell( + val coordinate: List, + @Contextual val positionDeltas: FloatArray, +) + +/** + * UMA §4.11: a deformer's geometry keyform grid. + * + * @property List axes The axes. + * @property List cells The keyed cells, in the model's order. + */ +@Serializable +public data class UmaDeformerGrid( + val axes: List, + val cells: List, +) + +/** + * UMA §4.11: one cell of a deformer's geometry grid - a warp's lattice or a rotation's pivot, by the deformer's + * kind. + * + * @property List coordinate The key index per axis. + * @property FloatArray? controlPoints A warp's absolute lattice points, x, y per point (an accessor). + * @property Float? originX A rotation's pivot x. + * @property Float? originY A rotation's pivot y. + * @property Float? angle A rotation's angle. + * @property Float? scale A rotation's scale. + */ +@Serializable +public class UmaDeformerCell( + val coordinate: List, + @Contextual val controlPoints: FloatArray? = null, + val originX: Float? = null, + val originY: Float? = null, + val angle: Float? = null, + val scale: Float? = null, +) + +/** UMA §4.12: a keyed non-geometry channel. */ +@Serializable +public enum class UmaFormChannel { + @SerialName("drawOrder") + DrawOrder, + + @SerialName("opacity") + Opacity, + + @SerialName("multiplyColor") + MultiplyColor, + + @SerialName("screenColor") + ScreenColor, + + @SerialName("flipX") + FlipX, + + @SerialName("flipY") + FlipY, + + @SerialName("glueIntensity") + GlueIntensity, +} + +/** + * UMA §4.12: one channel's keyform track. + * + * @property List axes The axes. + * @property List cells The keyed cells, in the model's order. + */ +@Serializable +public data class UmaChannelGrid( + val axes: List, + val cells: List, +) + +/** + * UMA §4.12: one cell of a channel track. + * + * @property List coordinate The key index per axis. + * @property JsonElement value A number, a color `[r, g, b]`, or a boolean, by the channel's kind. + */ +@Serializable +public data class UmaChannelCell( + val coordinate: List, + val value: JsonElement, +) + +/** + * UMA §4.13: one point of a blend-weight limit curve. + * + * @property Float value The constraint parameter's value. + * @property Float weight The weight cap there. + */ +@Serializable +public data class UmaBlendLimitPoint( + val value: Float, + val weight: Float, +) + +/** + * UMA §4.13: a blend-weight limit curve over another parameter. + * + * @property String parameter The constraint parameter. + * @property List points The curve, ascending by value. + */ +@Serializable +public data class UmaBlendLimit( + val parameter: String, + val points: List, +) + +/** + * UMA §4.13: a drawable's blend-shape form. + * + * @property FloatArray positionDeltas x, y per vertex, relative to the rest mesh (an accessor). + * @property Float? drawOrder Absent at 500. + * @property Float? opacity Absent at 1. + * @property List? multiplyColor Absent at white. + * @property List? screenColor Absent at black. + */ +@Serializable +public class UmaMeshForm( + @Contextual val positionDeltas: FloatArray, + val drawOrder: Float? = null, + val opacity: Float? = null, + val multiplyColor: List? = null, + val screenColor: List? = null, +) + +/** + * UMA §4.13: a deformer's blend-shape form - a warp's lattice or a rotation's pivot, by the deformer's kind. + * + * @property FloatArray? controlPoints A warp's absolute lattice points (an accessor). + * @property Float? originX A rotation's pivot x. + * @property Float? originY A rotation's pivot y. + * @property Float? angle A rotation's angle. + * @property Float? scale A rotation's scale. + * @property Boolean? flipX A rotation's horizontal reflection, absent when false. + * @property Boolean? flipY A rotation's vertical reflection, absent when false. + * @property Float? opacity Absent at 1. + * @property List? multiplyColor Absent at white. + * @property List? screenColor Absent at black. + */ +@Serializable +public class UmaDeformerForm( + @Contextual val controlPoints: FloatArray? = null, + val originX: Float? = null, + val originY: Float? = null, + val angle: Float? = null, + val scale: Float? = null, + val flipX: Boolean? = null, + val flipY: Boolean? = null, + val opacity: Float? = null, + val multiplyColor: List? = null, + val screenColor: List? = null, +) + +/** + * UMA §4.13: a part's blend-shape form. + * + * @property Float drawOrder The part's draw order at this key. + * @property Float? opacity Absent at 1. + * @property List? multiplyColor Absent at white. + * @property List? screenColor Absent at black. + */ +@Serializable +public data class UmaPartForm( + val drawOrder: Float, + val opacity: Float? = null, + val multiplyColor: List? = null, + val screenColor: List? = null, +) + +/** + * UMA §4.13: a drawable's blend-shape binding. + * + * @property String parameter The driving parameter. + * @property List keys The keyed values, ascending, the neutral included. + * @property Int neutralIndex The neutral key's index. + * @property List forms One form per key; null where there is none. + * @property List? limits Weight limits, absent when none. + */ +@Serializable +public data class UmaMeshBlendShape( + val parameter: String, + val keys: List, + val neutralIndex: Int, + val forms: List, + val limits: List? = null, +) + +/** + * UMA §4.13: a deformer's blend-shape binding. + * + * @property String parameter The driving parameter. + * @property List keys The keyed values, ascending, the neutral included. + * @property Int neutralIndex The neutral key's index. + * @property List forms One form per key; null where there is none. + * @property List? limits Weight limits, absent when none. + */ +@Serializable +public data class UmaDeformerBlendShape( + val parameter: String, + val keys: List, + val neutralIndex: Int, + val forms: List, + val limits: List? = null, +) + +/** + * UMA §4.13: a part's blend-shape binding. + * + * @property String parameter The driving parameter. + * @property List keys The keyed values, ascending, the neutral included. + * @property Int neutralIndex The neutral key's index. + * @property List forms One form per key; null where there is none. + * @property List? limits Weight limits, absent when none. + */ +@Serializable +public data class UmaPartBlendShape( + val parameter: String, + val keys: List, + val neutralIndex: Int, + val forms: List, + val limits: List? = null, +) + +/** + * UMA §4.14: a glue's welded vertex pairs, as parallel arrays. + * + * @property IntArray indicesA Vertex indices into mesh A (an accessor). + * @property IntArray indicesB Vertex indices into mesh B (an accessor). + * @property FloatArray weightsA Mesh A's pull toward B per pair (an accessor). + * @property FloatArray weightsB Mesh B's pull toward A per pair (an accessor). + */ +@Serializable +public class UmaGluePairs( + @Contextual val indicesA: IntArray, + @Contextual val indicesB: IntArray, + @Contextual val weightsA: FloatArray, + @Contextual val weightsB: FloatArray, +) + +/** + * UMA §4.14: a glue affecter, identified by its ordered mesh pair. + * + * @property String meshA The first welded drawable. + * @property String meshB The second welded drawable. + * @property UmaGluePairs pairs The welded vertex pairs. + * @property Map? channels The keyed weld strength, absent when static. + * @property Float? intensity The static weld strength, absent at 1. + * @property String? id The authored name, absent when none. + */ +@Serializable +public data class UmaGlue( + val meshA: String, + val meshB: String, + val pairs: UmaGluePairs, + val channels: Map? = null, + val intensity: Float? = null, + val id: String? = null, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetShape.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetShape.kt new file mode 100644 index 0000000..135fc92 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/puppet/UmaPuppetShape.kt @@ -0,0 +1,504 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.floatOrNull + +/** UMA §4.12: what a channel track's cells hold. */ +internal enum class UmaChannelValueKind { + /** A finite float. */ + Number, + + /** Exactly three finite floats. */ + Color, + + /** A boolean. */ + Flag, +} + +/** UMA §4.12: the value kind each channel's cells hold. */ +internal val UmaFormChannel.valueKind: UmaChannelValueKind + get() = + when (this) { + UmaFormChannel.DrawOrder, UmaFormChannel.Opacity, UmaFormChannel.GlueIntensity -> UmaChannelValueKind.Number + UmaFormChannel.MultiplyColor, UmaFormChannel.ScreenColor -> UmaChannelValueKind.Color + UmaFormChannel.FlipX, UmaFormChannel.FlipY -> UmaChannelValueKind.Flag + } + +/** + * The puppet entry's shape rules the schema classes cannot enforce on their own (docs/format/UMA.md §4.8, §4.10-4.14): + * the fields that belong to one kind of object and not another, the arrays that must agree in size, and the indices + * and keys that must stay in range and in order. + * + * The reader refuses a file that breaks one, and the writer refuses to save one, so a document Umamo saves always + * reopens. Each problem names the value's path the way the reader reports it (`drawables[D].mesh.indices[2]`). + */ +internal object UmaPuppetShape { + /** + * Where [puppet] first breaks a shape rule. + * + * @param UmaPuppet puppet The puppet. + * @return String? A description of the first problem, or null when every rule holds. + */ + fun firstProblem(puppet: UmaPuppet): String? = + try { + checkPuppet(puppet) + null + } catch (problem: ShapeProblem) { + problem.detail + } + + /** + * The first problem found, carried out of the walk that found it. + * + * @property String detail What is wrong, and where. + */ + private class ShapeProblem(val detail: String) : RuntimeException(detail) + + /** + * Ends the walk with [detail] as the problem. + * + * @param String detail What is wrong, and where. + * @return Nothing Never returns. + */ + private fun problem(detail: String): Nothing = throw ShapeProblem(detail) + + /** + * Checks every rule over the whole puppet. + * + * @param UmaPuppet puppet The puppet. + */ + private fun checkPuppet(puppet: UmaPuppet) { + val drawables = puppet.drawables.orEmpty() + for (drawable in drawables) { + checkDrawable(drawable) + } + puppet.parameterTree.orEmpty().forEachIndexed { nodeIndex, node -> checkParameterNode(node, "parameterTree[$nodeIndex]") } + for (part in puppet.parts.orEmpty()) { + checkPart(part) + } + for (deformer in puppet.deformers.orEmpty()) { + checkDeformer(deformer) + } + // UMA §4.14: a glue's indices are checked against the meshes it welds, when those meshes are in the entry. + val vertexCountByDrawable = drawables.associate { drawable -> drawable.id to drawable.mesh?.let { mesh -> mesh.positions.size / 2 } } + for (glue in puppet.glues.orEmpty()) { + checkGlue(glue, vertexCountByDrawable) + } + puppet.rootChildren.orEmpty().forEachIndexed { childIndex, child -> checkOrgRef(child, "rootChildren[$childIndex]") } + } + + /** + * UMA §4.3: a parameter-tree node, which is exactly one of a leaf and a named group. + * + * @param UmaParameterNode node The node. + * @param String path The node's position. + */ + private fun checkParameterNode(node: UmaParameterNode, path: String) { + val isLeaf = node.parameter != null + val isGroup = node.group != null + if (isLeaf == isGroup) { + problem("$path must name exactly one of a parameter and a group") + } + if (isLeaf) { + if (node.name != null || node.initiallyOpen != null || node.children != null) { + problem("$path is a parameter leaf but carries group fields") + } + return + } + if (node.name == null) { + problem("$path is a group without a name") + } + node.children.orEmpty().forEachIndexed { childIndex, child -> checkParameterNode(child, "$path.children[$childIndex]") } + } + + /** + * UMA §4.2: an organizational child, which is exactly one of a part and a drawable. + * + * @param UmaOrgRef reference The reference. + * @param String path The reference's position. + */ + private fun checkOrgRef(reference: UmaOrgRef, path: String) { + if ((reference.part != null) == (reference.drawable != null)) { + problem("$path must name exactly one of a part and a drawable") + } + } + + /** + * UMA §4.4: a part, its children, composite, tracks, and blend shapes. + * + * @param UmaPart part The part. + */ + private fun checkPart(part: UmaPart) { + val path = "parts[${part.id}]" + part.children.orEmpty().forEachIndexed { childIndex, child -> checkOrgRef(child, "$path.children[$childIndex]") } + part.composite?.let { composite -> + checkColor(composite.multiplyColor, "$path.composite.multiplyColor") + checkColor(composite.screenColor, "$path.composite.screenColor") + } + checkChannels(part.channels, path) + part.blendShapes.orEmpty().forEachIndexed { bindingIndex, binding -> + val bindingPath = "$path.blendShapes[$bindingIndex]" + checkBinding(binding.keys, binding.forms.size, binding.neutralIndex, binding.limits, bindingPath) + binding.forms.forEachIndexed { formIndex, form -> + form?.let { + checkColor(form.multiplyColor, "$bindingPath.forms[$formIndex].multiplyColor") + checkColor(form.screenColor, "$bindingPath.forms[$formIndex].screenColor") + } + } + } + } + + /** + * UMA §4.5: a deformer, whose kind decides which fields it must and must not carry and what its forms hold. + * + * @param UmaDeformer deformer The deformer. + */ + private fun checkDeformer(deformer: UmaDeformer) { + val path = "deformers[${deformer.id}]" + checkColor(deformer.multiplyColor, "$path.multiplyColor") + checkColor(deformer.screenColor, "$path.screenColor") + when (deformer.kind) { + UmaDeformerKind.Warp -> { + if (deformer.baseAngle != null || deformer.flipX != null || deformer.flipY != null) { + problem("$path is a warp but carries rotation fields") + } + val rows = deformer.rows ?: problem("$path is a warp without rows") + val columns = deformer.columns ?: problem("$path is a warp without columns") + if (rows < 0 || columns < 0) { + problem("$path has a negative lattice size") + } + // UMA §4.11: a rows x columns lattice holds (rows + 1) x (columns + 1) control points, counted wide so a + // huge lattice cannot wrap to a small float count its arrays would then pass. + val pointFloatsWide = (rows + 1L) * (columns + 1L) * 2L + if (pointFloatsWide > Int.MAX_VALUE) { + problem("$path has a $rows x $columns lattice, too large to hold") + } + val pointFloats = pointFloatsWide.toInt() + if (deformer.isQuadTransform == null) { + problem("$path is a warp without isQuadTransform") + } + deformer.geometry?.let { grid -> + checkGrid(grid.axes, grid.cells.map { cell -> cell.coordinate }, "$path.geometry") + grid.cells.forEachIndexed { cellIndex, cell -> + val cellPath = "$path.geometry.cells[$cellIndex]" + if (cell.originX != null || cell.originY != null || cell.angle != null || cell.scale != null) { + problem("$cellPath belongs to a warp but carries rotation fields") + } + checkLattice(cell.controlPoints, pointFloats, cellPath) + } + } + checkChannels(deformer.channels, path) + deformer.blendShapes.orEmpty().forEachIndexed { bindingIndex, binding -> + val bindingPath = "$path.blendShapes[$bindingIndex]" + checkBinding(binding.keys, binding.forms.size, binding.neutralIndex, binding.limits, bindingPath) + binding.forms.forEachIndexed { formIndex, form -> + form?.let { + val formPath = "$bindingPath.forms[$formIndex]" + if (form.originX != null || form.originY != null || form.angle != null || form.scale != null || form.flipX != null || form.flipY != null) { + problem("$formPath belongs to a warp but carries rotation fields") + } + checkLattice(form.controlPoints, pointFloats, formPath) + checkColor(form.multiplyColor, "$formPath.multiplyColor") + checkColor(form.screenColor, "$formPath.screenColor") + } + } + } + } + + UmaDeformerKind.Rotation -> { + if (deformer.rows != null || deformer.columns != null || deformer.isQuadTransform != null) { + problem("$path is a rotation but carries warp fields") + } + if (deformer.baseAngle == null) { + problem("$path is a rotation without baseAngle") + } + deformer.geometry?.let { grid -> + checkGrid(grid.axes, grid.cells.map { cell -> cell.coordinate }, "$path.geometry") + grid.cells.forEachIndexed { cellIndex, cell -> + val cellPath = "$path.geometry.cells[$cellIndex]" + if (cell.controlPoints != null) { + problem("$cellPath belongs to a rotation but carries controlPoints") + } + checkPivot(cell.originX, cell.originY, cell.angle, cell.scale, cellPath) + } + } + checkChannels(deformer.channels, path) + deformer.blendShapes.orEmpty().forEachIndexed { bindingIndex, binding -> + val bindingPath = "$path.blendShapes[$bindingIndex]" + checkBinding(binding.keys, binding.forms.size, binding.neutralIndex, binding.limits, bindingPath) + binding.forms.forEachIndexed { formIndex, form -> + form?.let { + val formPath = "$bindingPath.forms[$formIndex]" + if (form.controlPoints != null) { + problem("$formPath belongs to a rotation but carries controlPoints") + } + checkPivot(form.originX, form.originY, form.angle, form.scale, formPath) + checkColor(form.multiplyColor, "$formPath.multiplyColor") + checkColor(form.screenColor, "$formPath.screenColor") + } + } + } + } + } + } + + /** + * UMA §4.6: a drawable, its mesh, and everything sized against the mesh. + * + * @param UmaDrawable drawable The drawable. + */ + private fun checkDrawable(drawable: UmaDrawable) { + val path = "drawables[${drawable.id}]" + val mesh = drawable.mesh + mesh?.let { checkMesh(mesh, "$path.mesh") } + drawable.geometry?.let { grid -> + checkGrid(grid.axes, grid.cells.map { cell -> cell.coordinate }, "$path.geometry") + grid.cells.forEachIndexed { cellIndex, cell -> checkDeltas(cell.positionDeltas, mesh, "$path.geometry.cells[$cellIndex].positionDeltas") } + } + checkChannels(drawable.channels, path) + checkColor(drawable.multiplyColor, "$path.multiplyColor") + checkColor(drawable.screenColor, "$path.screenColor") + drawable.blendShapes.orEmpty().forEachIndexed { bindingIndex, binding -> + val bindingPath = "$path.blendShapes[$bindingIndex]" + checkBinding(binding.keys, binding.forms.size, binding.neutralIndex, binding.limits, bindingPath) + binding.forms.forEachIndexed { formIndex, form -> + form?.let { + val formPath = "$bindingPath.forms[$formIndex]" + checkDeltas(form.positionDeltas, mesh, "$formPath.positionDeltas") + checkColor(form.multiplyColor, "$formPath.multiplyColor") + checkColor(form.screenColor, "$formPath.screenColor") + } + } + } + } + + /** + * UMA §4.10: a mesh's arrays, checked against each other. + * + * @param UmaMesh mesh The mesh. + * @param String path The mesh's position. + */ + private fun checkMesh(mesh: UmaMesh, path: String) { + if (mesh.positions.size % 2 != 0) { + problem("$path.positions holds ${mesh.positions.size} floats, not whole x, y pairs") + } + if (mesh.uvs.size != mesh.positions.size) { + problem("$path.uvs holds ${mesh.uvs.size} floats against ${mesh.positions.size} positions") + } + if (mesh.indices.size % 3 != 0) { + problem("$path.indices holds ${mesh.indices.size} indices, not whole triangles") + } + checkIndices(mesh.indices, mesh.positions.size / 2, "$path.indices") + } + + /** + * Checks every index names a vertex of a mesh with [vertexCount] vertices; nothing to check when the count is + * unknown (the mesh is absent). + * + * @param IntArray indices The indices. + * @param Int? vertexCount The mesh's vertex count, or null. + * @param String path Where the indices sit. + */ + private fun checkIndices(indices: IntArray, vertexCount: Int?, path: String) { + if (vertexCount == null) { + return + } + indices.forEachIndexed { indexIndex, index -> + if (index !in 0 until vertexCount) { + problem("$path[$indexIndex] is $index, outside the mesh's $vertexCount vertices") + } + } + } + + /** + * Checks position deltas hold one x, y pair per vertex of [mesh]; nothing to check without a mesh. + * + * @param FloatArray deltas The deltas. + * @param UmaMesh? mesh The drawable's mesh, if any. + * @param String path Where the deltas sit. + */ + private fun checkDeltas(deltas: FloatArray, mesh: UmaMesh?, path: String) { + if (mesh != null && deltas.size != mesh.positions.size) { + problem("$path holds ${deltas.size} floats against the mesh's ${mesh.positions.size} positions") + } + } + + /** + * Checks a warp form's lattice is there and whole. + * + * @param FloatArray? controlPoints The control points, or null. + * @param Int pointFloats The lattice's float count. + * @param String path The form's position. + */ + private fun checkLattice(controlPoints: FloatArray?, pointFloats: Int, path: String) { + if (controlPoints == null) { + problem("$path belongs to a warp but has no controlPoints") + } + if (controlPoints.size != pointFloats) { + problem("$path.controlPoints holds ${controlPoints.size} floats; the lattice needs $pointFloats") + } + } + + /** + * Checks a rotation form carries its whole pivot. + * + * @param Float? originX The pivot's x. + * @param Float? originY The pivot's y. + * @param Float? angle The angle. + * @param Float? scale The scale. + * @param String path The form's position. + */ + private fun checkPivot(originX: Float?, originY: Float?, angle: Float?, scale: Float?, path: String) { + when { + originX == null -> problem("$path has no originX") + originY == null -> problem("$path has no originY") + angle == null -> problem("$path has no angle") + scale == null -> problem("$path has no scale") + } + } + + /** + * UMA §4.11: a grid's axes, each one's keys ascending, and its cells' coordinates, each naming one key on every + * axis. + * + * @param List axes The axes. + * @param List> coordinates The cells' coordinates, in cell order. + * @param String path The grid's position. + */ + private fun checkGrid(axes: List, coordinates: List>, path: String) { + axes.forEachIndexed { axisIndex, axis -> checkAscending(axis.keys, "$path.axes[$axisIndex].keys") } + coordinates.forEachIndexed { cellIndex, coordinate -> + val cellPath = "$path.cells[$cellIndex]" + if (coordinate.size != axes.size) { + problem("$cellPath.coordinate has ${coordinate.size} components for ${axes.size} axes") + } + coordinate.forEachIndexed { axisIndex, keyIndex -> + if (keyIndex !in axes[axisIndex].keys.indices) { + problem("$cellPath.coordinate[$axisIndex] is $keyIndex, outside the axis's ${axes[axisIndex].keys.size} keys") + } + } + } + } + + /** + * Checks [values] never step down: the evaluator brackets a parameter value by scanning keys in order, so a key + * below its predecessor would place forms at the wrong values without any error. Equal neighbors are allowed; + * the evaluator treats their empty span as a snap. + * + * @param List values The values, in stored order. + * @param String path Where the list sits; a problem names the element under it. + */ + private fun checkAscending(values: List, path: String) { + for (valueIndex in 1 until values.size) { + if (values[valueIndex] < values[valueIndex - 1]) { + problem("$path[$valueIndex] is ${values[valueIndex]}, below the ${values[valueIndex - 1]} before it") + } + } + } + + /** + * UMA §4.12: an owner's channel tracks, each a grid whose values match their channel's kind. + * + * @param Map? channels The tracks, or null when the owner keys none. + * @param String path The owner's position. + */ + private fun checkChannels(channels: Map?, path: String) { + for ((channel, track) in channels.orEmpty()) { + val trackPath = "$path.channels.${UmaFormChannel.serializer().descriptor.getElementName(channel.ordinal)}" + checkGrid(track.axes, track.cells.map { cell -> cell.coordinate }, trackPath) + track.cells.forEachIndexed { cellIndex, cell -> checkChannelValue(cell.value, channel.valueKind, "$trackPath.cells[$cellIndex].value") } + } + } + + /** + * UMA §4.12: one channel value, which is a finite number, three of them, or a boolean, as its channel requires. + * + * @param JsonElement value The value. + * @param UmaChannelValueKind kind The channel's value kind. + * @param String path Where the value sits. + */ + private fun checkChannelValue(value: JsonElement, kind: UmaChannelValueKind, path: String) { + when (kind) { + UmaChannelValueKind.Number -> { + if (finiteNumberOf(value) == null) { + problem("$path must be a number") + } + } + + UmaChannelValueKind.Color -> { + val components = value as? JsonArray + if (components == null || components.size != 3 || components.any { component -> finiteNumberOf(component) == null }) { + problem("$path must be three numbers") + } + } + + UmaChannelValueKind.Flag -> { + if ((value as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.booleanOrNull == null) { + problem("$path must be a boolean") + } + } + } + } + + /** + * [value] as a finite float, or null when it is not a JSON number or does not fit a finite float. + * + * @param JsonElement value The value. + * @return Float? The number. + */ + private fun finiteNumberOf(value: JsonElement): Float? = (value as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.floatOrNull?.takeIf { number -> number.isFinite() } + + /** + * UMA §4.13: the rules every blend-shape binding shares - one form per key, a neutral key that exists, keys + * ascending, and each limit's points ascending by value. + * + * @param List keys The keys. + * @param Int formCount The number of forms. + * @param Int neutralIndex The neutral key's index. + * @param List? limits The limits, or null. + * @param String path The binding's position. + */ + private fun checkBinding(keys: List, formCount: Int, neutralIndex: Int, limits: List?, path: String) { + if (formCount != keys.size) { + problem("$path has ${keys.size} keys but $formCount forms") + } + if (neutralIndex !in keys.indices) { + problem("$path.neutralIndex is $neutralIndex, outside its ${keys.size} keys") + } + checkAscending(keys, "$path.keys") + limits.orEmpty().forEachIndexed { limitIndex, limit -> checkAscending(limit.points.map { point -> point.value }, "$path.limits[$limitIndex].points") } + } + + /** + * UMA §4.14: a glue's pairs, whose arrays agree in length and whose indices name vertices of the meshes it welds. + * + * @param UmaGlue glue The glue. + * @param Map vertexCountByDrawable Each drawable's vertex count, null for a drawable with no mesh. + */ + private fun checkGlue(glue: UmaGlue, vertexCountByDrawable: Map) { + val path = "glues[${glue.meshA},${glue.meshB}]" + val pairs = glue.pairs + val pairCount = pairs.indicesA.size + if (pairs.indicesB.size != pairCount || pairs.weightsA.size != pairCount || pairs.weightsB.size != pairCount) { + problem("$path.pairs holds arrays of different lengths") + } + checkIndices(pairs.indicesA, vertexCountByDrawable[glue.meshA], "$path.pairs.indicesA") + checkIndices(pairs.indicesB, vertexCountByDrawable[glue.meshB], "$path.pairs.indicesB") + checkChannels(glue.channels, path) + } + + /** + * UMA §4.1: an optional color, which is exactly three channels when present. + * + * @param List? channels The color's channels, or null. + * @param String path Where the color sits. + */ + private fun checkColor(channels: List?, path: String) { + if (channels != null && channels.size != 3) { + problem("$path has ${channels.size} channels instead of red, green, and blue") + } + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/sources/UmaSources.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/sources/UmaSources.kt new file mode 100644 index 0000000..ac1a211 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/sources/UmaSources.kt @@ -0,0 +1,89 @@ +package org.umamo.format.uma.sources + +import kotlinx.serialization.Serializable + +/* + * The sources entry's schema (docs/format/UMA.md §6): the artwork files the document was imported from, each + * with the layer inventory it had at its last read. The source bytes themselves are never stored (UMA §6). + */ + +/** UMA §6.4: the algorithm prefix every recorded hash carries in front of its lowercase hex digest. */ +public const val UMA_SHA256_PREFIX: String = "sha256:" + +/** + * UMA §6.1: the sources entry's root. + * + * @property List? sources The linked artwork files, in document order. + */ +@Serializable +public data class UmaSources( + val sources: List? = null, +) + +/** + * UMA §6.2: one linked artwork file. + * + * @property String id The document-local identity a tile's source reference names. + * @property String name The file's display name. + * @property String format The source format's file extension. + * @property String? path The advisory external path, absent when unknown. + * @property String? contentHash The whole-file hash as `sha256:`, absent when the document + * never read the file's bytes. + * @property Long? lastModified The file's modification time at the last read, in epoch + * milliseconds, absent when unknown. + * @property List? layers The layer inventory as of the last read, in the file's draw order. + * @property Int? offsetX How far right of the document canvas's top-left corner the file's + * own top-left corner sits, in pixels; absent means 0 (the file shares the document's frame). + * @property Int? offsetZ How far UP from the document canvas's top-left corner the file's + * top-left corner sits, in pixels - the viewport's world axes, so a file placed lower on the canvas carries a + * negative value; absent means 0. + */ +@Serializable +public data class UmaSource( + val id: String, + val name: String, + val format: String, + val path: String? = null, + val contentHash: String? = null, + val lastModified: Long? = null, + val layers: List? = null, + // UMA §6.2: offsetX / offsetZ - the file's canvas origin on the document canvas, x right and z up. + val offsetX: Int? = null, + val offsetZ: Int? = null, +) + +/** + * UMA §6.3: one layer of a source's inventory. + * + * @property String key The reader's layer key, the string a tile's source reference carries. + * @property String name The layer's name at the last read. + * @property String groupPath The slash-joined enclosing folder path, empty at the root. + * @property Int left The layer's x on the document canvas in source pixels (the file's own + * position plus the source's offsetX). + * @property Int top The layer's y on the document canvas in source pixels, y down (the file's + * own position minus the source's offsetZ, which is up). + * @property Int width The layer's raster width in source pixels. + * @property Int height The layer's raster height in source pixels. + * @property Boolean visible The layer's own eye toggle at the last read. + * @property Boolean? present Whether the file still had the layer at the last read; absent means true. + * @property String? contentHash The hash of the layer's pixels as `sha256:`, absent when never decoded. + * @property Boolean? empty Whether the layer had no pixel with any alpha; absent means false. + * @property Boolean? replaced Whether a missing row was lost to Replace Artwork; absent means false. + * @property Boolean? ignored Whether a reload leaves the layer out of the rig; absent means false. + */ +@Serializable +public data class UmaSourceLayer( + val key: String, + val name: String, + val groupPath: String, + val left: Int, + val top: Int, + val width: Int, + val height: Int, + val visible: Boolean, + val present: Boolean? = null, + val contentHash: String? = null, + val empty: Boolean? = null, + val replaced: Boolean? = null, + val ignored: Boolean? = null, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/sources/UmaSourcesEntry.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/sources/UmaSourcesEntry.kt new file mode 100644 index 0000000..672c890 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/sources/UmaSourcesEntry.kt @@ -0,0 +1,110 @@ +package org.umamo.format.uma.sources + +import kotlinx.serialization.json.JsonObject +import org.umamo.format.uma.UmaEntryJson +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaIdentityTable +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.decodeUmaEntry +import org.umamo.format.uma.firstIdentityProblem +import org.umamo.format.uma.identityByStringKey + +/** + * The sources entry's codec over its JSON tree: decoding with every rule UMA §6 sets, encoding for a save, + * and the identities its arrays merge by. + */ +internal object UmaSourcesEntry { + // UMA §6.4: a SHA-256 digest's length in hex digits. + private const val HASH_DIGITS = 64 + + /** UMA §6.5: sources match by id, and a source's layers by key. */ + val identities: UmaIdentityTable = + UmaIdentityTable( + mapOf( + UmaSource.serializer().descriptor.serialName to identityByStringKey("id"), + UmaSourceLayer.serializer().descriptor.serialName to identityByStringKey("key"), + ), + ) + + /** + * Decodes a sources entry's tree, failing loudly on anything the schema does not allow. + * + * @param JsonObject tree The entry's JSON. + * @param String path The entry's path, for the failure. + * @return UmaSources The sources. + * @throws UmaFormatException When the tree breaks the schema, repeats an identity, or holds a hash this + * reader does not know. + */ + fun decode(tree: JsonObject, path: String): UmaSources { + val sources = decodeUmaEntry(UmaEntryJson, UmaSources.serializer(), tree, path) + val problem = firstIdentityProblem(tree, UmaSources.serializer().descriptor, identities, "") ?: firstProblem(sources) + if (problem != null) { + throw UmaFormatException(UmaReadFailure.MalformedEntry(path, problem)) + } + return sources + } + + /** + * Encodes sources for a save, refusing what a reader would refuse. + * + * @param UmaSources sources The sources. + * @param String path The entry's path, for the failure. + * @return JsonObject The entry's JSON, before the merge. + * @throws UmaWriteException When a hash is not in the form the entry holds, a size is negative, or a source id or + * a layer key within a source repeats. + */ + fun encode(sources: UmaSources, path: String): JsonObject { + firstProblem(sources)?.let { problem -> throw UmaWriteException(path, problem) } + val tree = UmaEntryJson.encodeToJsonElement(UmaSources.serializer(), sources) as JsonObject + // UMA §6.6: a reader refuses a repeated identity, so a save that wrote one could never be reopened. + firstIdentityProblem(tree, UmaSources.serializer().descriptor, identities, "")?.let { problem -> throw UmaWriteException(path, problem) } + return tree + } + + /** + * Where [sources] first breaks a rule of UMA §6 that the schema classes cannot enforce on their own, apart + * from repeated identities. + * + * @param UmaSources sources The sources. + * @return String? A description of the first problem, or null when every rule holds. + */ + private fun firstProblem(sources: UmaSources): String? { + for ((sourceIndex, source) in sources.sources.orEmpty().withIndex()) { + val sourcePath = "sources[$sourceIndex]" + hashProblem(source.contentHash, "$sourcePath.contentHash")?.let { problem -> return problem } + for ((layerIndex, layer) in source.layers.orEmpty().withIndex()) { + val layerPath = "$sourcePath.layers[$layerIndex]" + if (layer.width < 0 || layer.height < 0) { + return "$layerPath has a negative size" + } + hashProblem(layer.contentHash, "$layerPath.contentHash")?.let { problem -> return problem } + } + } + return null + } + + /** + * What is wrong with a recorded hash, or null when it is absent or `sha256:` followed by 64 lowercase hex + * digits. + * + * @param String? hash The hash as written. + * @param String path Where it sits, for the report. + * @return String? The problem. + */ + private fun hashProblem(hash: String?, path: String): String? { + if (hash == null) { + return null + } + // UMA §6.4: a hash under another algorithm is unknown to this reader, like an unknown enum value; a writer + // that changes the algorithm raises the entry's minVersion. + if (!hash.startsWith(UMA_SHA256_PREFIX)) { + return "$path is '$hash', which is not a sha256 hash" + } + val digest = hash.substring(UMA_SHA256_PREFIX.length) + if (digest.length != HASH_DIGITS || digest.any { character -> character !in '0'..'9' && character !in 'a'..'f' }) { + return "$path is not 64 lowercase hexadecimal digits" + } + return null + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/textures/UmaTextures.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/textures/UmaTextures.kt new file mode 100644 index 0000000..5f25ced --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/textures/UmaTextures.kt @@ -0,0 +1,201 @@ +package org.umamo.format.uma.textures + +import kotlinx.serialization.Serializable + +/* + * The textures entry's schema (docs/format/UMA.md §5): the document's atlas - its pages, its tiles with + * their placements and source bindings - and the pixel entries those records name. Every optional value is + * a nullable with a null default, and the bridge writes a value only when it is not the model's default. + * + * Paths are the format layer's: a record a writer hands in carries no path, and the layout that precedes a + * save assigns one (§5.7). + */ + +/** + * UMA §5.2: the textures entry's root. + * + * @property Boolean? storedUvsAddressPages Whether the drawables' stored texture coordinates address the + * packed pages rather than the art; absent means true. + * @property UmaComposition? composition The trim and extrusion policy the pages derive under; absent + * means the packer's defaults. + * @property List? pages The atlas's pages, in page order: the sizes placements index. + * @property List? tiles Every piece of source art, in document order. + * @property UmaRenderPages? renderPages The imported page images the drawables sample, absent when the + * pages derive from the tiles (UMA §5.5). + * @property UmaThumbnail? thumbnail The document's thumbnail, absent when there is none. + */ +@Serializable +public data class UmaTextures( + val storedUvsAddressPages: Boolean? = null, + val composition: UmaComposition? = null, + val pages: List? = null, + val tiles: List? = null, + val renderPages: UmaRenderPages? = null, + val thumbnail: UmaThumbnail? = null, +) + +/** + * UMA §5.2: the policy the pages derive under. + * + * @property Int? alphaThreshold The minimum alpha (1 to 255) a pixel needs to count as opaque when a tile is + * trimmed; absent means 1. + * @property Int? extrude How many pixels of gutter around each tile carry its edge color, at alpha 0; + * absent means 2. + */ +@Serializable +public data class UmaComposition( + val alphaThreshold: Int? = null, + val extrude: Int? = null, +) + +/** + * UMA §5.3: one atlas page's size. + * + * @property Int width The page width in pixels. + * @property Int height The page height in pixels. + */ +@Serializable +public data class UmaPage( + val width: Int, + val height: Int, +) + +/** + * UMA §5.5: the page images a document's drawables sample while its pages are the ones it was imported with - a + * CMO3's embedded images, a MOC3's texture files - and which image each drawable samples. + * + * @property List pages The images, in the order the map indexes. + * @property Map? drawablePages Each sampling drawable's id, mapped to its image's index; absent when + * none samples one. + */ +@Serializable +public data class UmaRenderPages( + val pages: List, + val drawablePages: Map? = null, +) + +/** + * UMA §5.5: one render page image. + * + * @property Int width The image's width in pixels. + * @property Int height The image's height in pixels. + * @property String path The archive entry holding its pixels. + */ +@Serializable +public data class UmaRenderPage( + val width: Int, + val height: Int, + val path: String, +) + +/** + * UMA §5.4: one tile - a piece of source art the atlas packs. + * + * @property String id The tile's document-local identity. + * @property String name The tile's display name. + * @property Int width The art's width in pixels. + * @property Int height The art's height in pixels. + * @property String? path The archive entry holding the tile's pixels; required in a file, assigned + * by the layout before a save. + * @property UmaPlacement? placement Where the tile sits on its page, or absent when it was never packed. + * @property UmaSourceRef? source The source layer the art came from, or absent when the document retains + * no binding. + * @property Boolean? pinned Whether a repack keeps the placement where it is; absent means false. + * @property String? replaces The tile this one superseded when its layer was reloaded, or absent. + */ +@Serializable +public data class UmaTile( + val id: String, + val name: String, + val width: Int, + val height: Int, + val path: String? = null, + val placement: UmaPlacement? = null, + val source: UmaSourceRef? = null, + val pinned: Boolean? = null, + val replaces: String? = null, +) + +/** + * UMA §5.4: where a tile's upright art sits on a page - the packer's transform as translation, scale, and + * rotation, in page pixels with y down. + * + * @property Int page The page the art packs onto, indexing the entry's pages. + * @property Float positionX The packing origin's x on the page. + * @property Float positionY The packing origin's y on the page. + * @property Float scaleX The horizontal scale applied; negative mirrors. + * @property Float scaleY The vertical scale applied; negative mirrors. + * @property Float rotationDegrees The rotation applied, counter-clockwise degrees. + */ +@Serializable +public data class UmaPlacement( + val page: Int, + val positionX: Float, + val positionY: Float, + val scaleX: Float, + val scaleY: Float, + val rotationDegrees: Float, +) + +/** + * UMA §5.4: a tile's link to the source layer its art came from. + * + * @property String art The source's id in the sources entry. + * @property String layerKey The reader's key for the layer within that source. + * @property Boolean stableKey Whether the key is a format-minted id that survives a rename or a reorder. + */ +@Serializable +public data class UmaSourceRef( + val art: String, + val layerKey: String, + val stableKey: Boolean, +) + +/** + * UMA §5.6: the document's thumbnail. + * + * @property Int width The thumbnail's width in pixels. + * @property Int height The thumbnail's height in pixels. + * @property String path The archive entry holding its pixels. + */ +@Serializable +public data class UmaThumbnail( + val width: Int, + val height: Int, + val path: String, +) + +/** + * The pixels a save writes for the textures entry (UMA §5.7): a PNG per tile the file does not already hold, the + * render pages by mode, and the thumbnail. + * + * @property Function tile Yields a tile's PNG by tile id. Called only for a tile the file does + * not hold yet, since a tile's pixels never change; null refuses the save. + * @property UmaRenderPagePixels renderPages What the drawables sample. + * @property ByteArray? thumbnail The thumbnail's PNG, or null for no thumbnail. + */ +public class UmaPixelSource( + public val tile: (String) -> ByteArray?, + public val renderPages: UmaRenderPagePixels, + public val thumbnail: ByteArray?, +) + +/** What a save records about the images a document's drawables sample (UMA §5.5). */ +public sealed interface UmaRenderPagePixels { + /** The pages derive from the tiles placed on them, so nothing is stored. */ + public data object Derived : UmaRenderPagePixels + + /** + * The document samples these imported images, replacing whatever render pages the file held. + * + * @property List pages The PNG per image. + * @property Map drawablePages Each sampling drawable's id, mapped to its image's index in [pages]. + */ + public class Stored( + public val pages: List, + public val drawablePages: Map, + ) : UmaRenderPagePixels + + /** The file's own render pages are kept as they are, images and map both. */ + public data object Retained : UmaRenderPagePixels +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/uma/textures/UmaTexturesEntry.kt b/module/format/src/commonMain/kotlin/org/umamo/format/uma/textures/UmaTexturesEntry.kt new file mode 100644 index 0000000..69b0450 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/uma/textures/UmaTexturesEntry.kt @@ -0,0 +1,386 @@ +package org.umamo.format.uma.textures + +import kotlinx.serialization.json.JsonObject +import org.umamo.format.png.pngDimensionsOf +import org.umamo.format.uma.UmaEntryJson +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaIdentityTable +import org.umamo.format.uma.UmaListRule +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.decodeUmaEntry +import org.umamo.format.uma.firstIdentityProblem +import org.umamo.format.uma.identityByStringKey + +/** + * What laying the textures entry out for a save produced: the index with every path assigned, and the + * pixel entries the save writes or drops. + * + * @property UmaTextures textures The index, every record naming its pixel entry. + * @property Map payloads The pixel paths this save owns, in write order: bytes to write stored, or + * null for a path the index no longer names, which is dropped (UMA §5.7). + */ +internal class UmaTexturesLayout( + val textures: UmaTextures, + val payloads: Map, +) + +/** + * The textures entry's codec over its JSON tree: decoding with every rule UMA §5 sets, the layout that + * assigns pixel paths before a save, and the identities its arrays merge by. + */ +internal object UmaTexturesEntry { + // UMA §5.7: the pixel paths this entry mints. + private const val TILE_PATH_PREFIX = "textures/tile-" + private const val PAGE_PATH_PREFIX = "textures/page-" + private const val PNG_SUFFIX = ".png" + private const val THUMBNAIL_PATH = "thumbnail.png" + private const val THUMBNAIL_PATH_PREFIX = "thumbnail-" + + /** + * UMA §5.8: tiles match by id across a save; atlas pages have no identity and render pages are one + * imported set, so both are replaced whole. + */ + val identities: UmaIdentityTable = + UmaIdentityTable( + mapOf( + UmaTile.serializer().descriptor.serialName to identityByStringKey("id"), + UmaPage.serializer().descriptor.serialName to UmaListRule.Whole, + UmaRenderPage.serializer().descriptor.serialName to UmaListRule.Whole, + ), + ) + + /** + * Decodes a textures entry's tree, failing loudly on anything the schema or the pixel entries do not allow. + * + * @param JsonObject tree The entry's JSON. + * @param String path The entry's path, for the failure. + * @param Function payloadHeader Resolves an archive path to the first bytes of its payload (a PNG header's + * worth at least, when the payload is that long), or null when the archive holds no such payload. + * @return UmaTextures The index. + * @throws UmaFormatException When the tree breaks the schema, repeats a tile id, names a pixel entry the + * archive does not hold, or names one whose PNG header disagrees with its record. + */ + fun decode(tree: JsonObject, path: String, payloadHeader: (String) -> ByteArray?): UmaTextures { + val textures = decodeUmaEntry(UmaEntryJson, UmaTextures.serializer(), tree, path) + firstIdentityProblem(tree, UmaTextures.serializer().descriptor, identities, "")?.let { problem -> + throw UmaFormatException(UmaReadFailure.MalformedEntry(path, problem)) + } + firstProblem(textures, path, payloadHeader)?.let { failure -> throw UmaFormatException(failure) } + return textures + } + + /** + * Encodes a laid-out index for a save. + * + * @param UmaTextures textures The index, every record naming its pixel entry. + * @param String path The entry's path, for the failure. + * @return JsonObject The entry's JSON, before the merge. + * @throws UmaWriteException When a tile id repeats. + */ + fun encode(textures: UmaTextures, path: String): JsonObject { + val tree = UmaEntryJson.encodeToJsonElement(UmaTextures.serializer(), textures) as JsonObject + // UMA §5.9: a reader refuses a repeated tile id, so a save that wrote one could never be reopened. + firstIdentityProblem(tree, UmaTextures.serializer().descriptor, identities, "")?.let { problem -> throw UmaWriteException(path, problem) } + return tree + } + + /** + * Assigns every record its pixel entry for a save (UMA §5.7): a tile the file already holds keeps its path and + * its bytes, a new tile takes a minted path and its PNG from [pixels], the render pages follow [pixels]'s mode, + * and the thumbnail is recorded from its PNG's own header at the path the file's thumbnail already has, or at one + * nothing else holds. Paths and render pages the caller set on the index are ignored; the layout owns them. + * + * @param UmaTextures updated The index to save. + * @param UmaTextures? retained The index as read from the file, or null for a document without one. + * @param UmaPixelSource pixels The pixels to write. + * @param String entryPath The entry's path, for a failure. + * @param Set pathsInUse Every path the archive holds or a save already owns, so a minted path + * never collides with one, whoever named it. + * @param Function payloadHeader Resolves an archive path to its payload's first bytes, or null. + * @param Function payloadBytes Resolves an archive path to its payload's bytes, or null. + * @return UmaTexturesLayout The laid-out index and the pixel entries to write or drop. + * @throws UmaWriteException When a new tile has no pixels, kept render pages are missing, a PNG is not one, or + * the laid-out index breaks a rule a reader would refuse. + */ + fun layOut( + updated: UmaTextures, + retained: UmaTextures?, + pixels: UmaPixelSource, + entryPath: String, + pathsInUse: Set, + payloadHeader: (String) -> ByteArray?, + payloadBytes: (String) -> ByteArray?, + ): UmaTexturesLayout { + val written = LinkedHashMap() + val tiles = layOutTiles(updated.tiles.orEmpty(), retained?.tiles.orEmpty(), pixels.tile, entryPath, pathsInUse, written) + val renderPages = layOutRenderPages(retained?.renderPages, pixels.renderPages, entryPath, pathsInUse, written, payloadBytes) + val thumbnail = + pixels.thumbnail?.let { bytes -> + val (width, height) = pngDimensionsOf(bytes) ?: throw UmaWriteException("$entryPath: thumbnail", "the thumbnail is not a PNG") + // UMA §5.7: the thumbnail rewrites its own entry, and a new one never lands on a path something else holds. + val path = + retained?.thumbnail?.path + ?: THUMBNAIL_PATH.takeIf { candidate -> candidate !in pathsInUse } + ?: "$THUMBNAIL_PATH_PREFIX${nextNumberFor(THUMBNAIL_PATH_PREFIX, pathsInUse)}$PNG_SUFFIX" + written[path] = bytes + UmaThumbnail(width, height, path) + } + val laidOut = + updated.copy( + tiles = tiles.takeIf { list -> list.isNotEmpty() }, + renderPages = renderPages, + thumbnail = thumbnail, + ) + val payloads = LinkedHashMap(written) + val named = namedPaths(laidOut) + for (path in namedPaths(retained)) { + // UMA §5.7: a pixel entry the index no longer names leaves the file. + if (path !in named) { + payloads[path] = null + } + } + firstProblem(laidOut, entryPath) { path -> written[path] ?: payloadHeader(path) }?.let { failure -> + throw UmaWriteException(entryPath, failure.description) + } + return UmaTexturesLayout(laidOut, payloads) + } + + /** + * The render pages [mode] records. A stored image names an entry that already holds its bytes rather than a copy + * of it: a PNG this save writes (a tile a drawable samples directly), or a render page the file holds, so saving + * the same pages again writes the same file. + * + * @param UmaRenderPages? retained The render pages as read. + * @param UmaRenderPagePixels mode What the drawables sample. + * @param String entryPath The entry's path, for a failure. + * @param Set pathsInUse Every path in use. + * @param MutableMap written The pixel entries this save writes so far; receives the new ones. + * @param Function payloadBytes Resolves an archive path to its payload's bytes, or null. + * @return UmaRenderPages? The laid-out render pages, or null when the pages derive. + * @throws UmaWriteException When kept render pages are missing, or a stored image is not a PNG. + */ + private fun layOutRenderPages( + retained: UmaRenderPages?, + mode: UmaRenderPagePixels, + entryPath: String, + pathsInUse: Set, + written: MutableMap, + payloadBytes: (String) -> ByteArray?, + ): UmaRenderPages? = + when (mode) { + UmaRenderPagePixels.Derived -> null + + UmaRenderPagePixels.Retained -> retained ?: throw UmaWriteException("$entryPath: renderPages", "the file holds no render pages to keep") + + is UmaRenderPagePixels.Stored -> { + val pathByContent = HashMap>() + for ((path, bytes) in written) { + if (bytes != null) { + pathByContent.getOrPut(bytes.contentHashCode()) { ArrayList() } += path + } + } + val retainedPages = retained?.pages.orEmpty() + val retainedBytesByPath = HashMap() + + /** + * The path of a render page the file holds whose image is [bytes], the one at [pageIndex] tried first + * since an unchanged set keeps its order, or null. Only pages of the same size are read. + * + * @param ByteArray bytes The image. + * @param Int width Its width. + * @param Int height Its height. + * @param Int pageIndex Its index in the new set. + * @return String? The retained page's path. + */ + fun retainedPathOf(bytes: ByteArray, width: Int, height: Int, pageIndex: Int): String? { + val candidates = listOfNotNull(retainedPages.getOrNull(pageIndex)) + retainedPages + return candidates.firstOrNull { page -> + page.width == width && + page.height == height && + retainedBytesByPath.getOrPut(page.path) { payloadBytes(page.path) }?.contentEquals(bytes) == true + }?.path + } + var nextNumber = nextNumberFor(PAGE_PATH_PREFIX, pathsInUse) + val pages = + mode.pages.mapIndexed { pageIndex, bytes -> + val (width, height) = pngDimensionsOf(bytes) ?: throw UmaWriteException("$entryPath: renderPages.pages[$pageIndex]", "the image is not a PNG") + val shared = pathByContent[bytes.contentHashCode()]?.firstOrNull { path -> written[path]?.contentEquals(bytes) == true } ?: retainedPathOf(bytes, width, height, pageIndex) + val path = + shared ?: "$PAGE_PATH_PREFIX$nextNumber$PNG_SUFFIX".also { minted -> + nextNumber++ + written[minted] = bytes + pathByContent.getOrPut(bytes.contentHashCode()) { ArrayList() } += minted + } + UmaRenderPage(width, height, path) + } + UmaRenderPages(pages, mode.drawablePages.takeIf { map -> map.isNotEmpty() }) + } + } + + /** + * The tile records with their pixel entries assigned: a tile the file holds keeps its path, and a new one is + * minted a path and written from [tilePng]. + * + * @param List updated The tiles to save. + * @param List retained The tiles as read. + * @param Function tilePng Yields a new tile's PNG by id. + * @param String entryPath The entry's path, for a failure. + * @param Set pathsInUse Every path in use. + * @param MutableMap written Receives the pixel entries to write. + * @return List The laid-out tiles. + * @throws UmaWriteException When a new tile has no pixels. + */ + private fun layOutTiles( + updated: List, + retained: List, + tilePng: (String) -> ByteArray?, + entryPath: String, + pathsInUse: Set, + written: MutableMap, + ): List { + val retainedPathById = HashMap() + for (tile in retained) { + val path = tile.path ?: continue + if (tile.id !in retainedPathById) { + retainedPathById[tile.id] = path + } + } + var nextNumber = nextNumberFor(TILE_PATH_PREFIX, pathsInUse) + return updated.map { tile -> + // UMA §5.7: a tile's pixels never change, so a tile the file holds keeps its entry untouched. + val existing = retainedPathById[tile.id] + if (existing != null) { + tile.copy(path = existing) + } else { + val path = "$TILE_PATH_PREFIX$nextNumber$PNG_SUFFIX" + nextNumber++ + written[path] = tilePng(tile.id) ?: throw UmaWriteException("$entryPath: tiles[${tile.id}]", "no pixels for the tile") + tile.copy(path = path) + } + } + } + + /** + * The number after the highest one any path in [pathsInUse] carries under [prefix], so a minted path collides + * with nothing the archive holds, whoever named it. + * + * @param String prefix The path prefix before the number. + * @param Set pathsInUse Every path in use. + * @return Int The next free number. + */ + private fun nextNumberFor(prefix: String, pathsInUse: Set): Int { + var highest = -1 + for (path in pathsInUse) { + if (!path.startsWith(prefix) || !path.endsWith(PNG_SUFFIX)) { + continue + } + val number = path.substring(prefix.length, path.length - PNG_SUFFIX.length).toIntOrNull() ?: continue + if (number > highest) { + highest = number + } + } + return highest + 1 + } + + /** + * Every pixel path [textures]'s records name: the pixel entries the textures entry owns (UMA §5.7). + * + * @param UmaTextures? textures The index, or null. + * @return Set The paths, in index order. + */ + fun namedPaths(textures: UmaTextures?): Set { + if (textures == null) { + return emptySet() + } + val paths = LinkedHashSet() + textures.tiles?.forEach { tile -> tile.path?.let(paths::add) } + textures.renderPages?.pages?.forEach { page -> paths.add(page.path) } + textures.thumbnail?.let { thumbnail -> paths.add(thumbnail.path) } + return paths + } + + /** + * Where [textures] first breaks a rule of UMA §5 that the schema classes cannot enforce on their own. + * + * @param UmaTextures textures The index. + * @param String entryPath The entry's path, for the failure. + * @param Function payloadHeader Resolves an archive path to its payload's first bytes, or null. + * @return UmaReadFailure? The failure, or null when every rule holds. + */ + private fun firstProblem(textures: UmaTextures, entryPath: String, payloadHeader: (String) -> ByteArray?): UmaReadFailure? { + /** + * The malformed-entry failure for [detail]. + * + * @param String detail What is wrong, and where. + * @return UmaReadFailure The failure. + */ + fun malformed(detail: String): UmaReadFailure = UmaReadFailure.MalformedEntry(entryPath, detail) + + /** + * The failure a pixel entry earns when the archive does not hold it or its PNG header disagrees with its + * record's size, or null when it is sound. + * + * @param String path The pixel entry's path. + * @param Int width The record's width. + * @param Int height The record's height. + * @param String where The record's position, for the failure. + * @return UmaReadFailure? The failure. + */ + fun pixelProblem(path: String, width: Int, height: Int, where: String): UmaReadFailure? { + val header = payloadHeader(path) ?: return UmaReadFailure.MissingEntry(path) + // UMA §5.1: every pixel entry is a PNG exactly the size its record says. + val (pngWidth, pngHeight) = pngDimensionsOf(header) ?: return malformed("$where names '$path', which is not a PNG") + if (pngWidth != width || pngHeight != height) { + return malformed("$where is $width x $height but '$path' holds $pngWidth x $pngHeight") + } + return null + } + + textures.composition?.let { composition -> + composition.alphaThreshold?.let { threshold -> + if (threshold !in 1..255) { + return malformed("composition.alphaThreshold is $threshold, outside 1 to 255") + } + } + composition.extrude?.let { extrude -> + if (extrude < 0) { + return malformed("composition.extrude is $extrude, which is negative") + } + } + } + val pages = textures.pages.orEmpty() + for ((pageIndex, page) in pages.withIndex()) { + if (page.width < 0 || page.height < 0) { + return malformed("pages[$pageIndex] has a negative size") + } + } + for ((tileIndex, tile) in textures.tiles.orEmpty().withIndex()) { + val where = "tiles[$tileIndex]" + if (tile.width < 0 || tile.height < 0) { + return malformed("$where has a negative size") + } + val path = tile.path ?: return malformed("$where has no path") + pixelProblem(path, tile.width, tile.height, where)?.let { failure -> return failure } + tile.placement?.let { placement -> + if (placement.page !in pages.indices) { + return malformed("$where.placement.page is ${placement.page}, outside the ${pages.size} pages") + } + } + } + textures.renderPages?.let { renderPages -> + for ((pageIndex, page) in renderPages.pages.withIndex()) { + pixelProblem(page.path, page.width, page.height, "renderPages.pages[$pageIndex]")?.let { failure -> return failure } + } + for ((drawableId, pageIndex) in renderPages.drawablePages.orEmpty()) { + if (pageIndex !in renderPages.pages.indices) { + return malformed("renderPages.drawablePages.$drawableId is $pageIndex, outside the ${renderPages.pages.size} render pages") + } + } + } + textures.thumbnail?.let { thumbnail -> + pixelProblem(thumbnail.path, thumbnail.width, thumbnail.height, "thumbnail")?.let { failure -> return failure } + } + return null + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/Vp8lDecoder.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/Vp8lDecoder.kt new file mode 100644 index 0000000..20543ee --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/Vp8lDecoder.kt @@ -0,0 +1,445 @@ +// Ported from TwelveMonkeys imageio-webp lossless VP8LDecoder (BSD-3-Clause, Copyright (c) 2017 Harald +// Kuhr, Simon Kammermeier). VP8L transform chain, Huffman-code reading, and the LZ77 + literal + +// color-cache main loop, over a ByteArray/WebpRaster instead of ImageInputStream/WritableRaster; the +// ImageReadParam/subsampling plumbing is dropped. See CREDITS.md. + +package org.umamo.format.webp + +/** + * VP8L (lossless WebP) decoder. Fills a full-size [WebpRaster] with straight-alpha RGBA8888 pixels. + */ +internal class Vp8lDecoder(private val reader: WebpLsbBitReader) { + /** + * Decodes the top-level VP8L image into [raster]. + * + * @param WebpRaster raster The full-size output (width x height). + * @param Int width Image width. + * @param Int height Image height. + */ + fun decode(raster: WebpRaster, width: Int, height: Int) { + readVP8Lossless(raster, topLevel = true, width = width, height = height) + } + + /** + * Reads one (sub-)image: its transforms (top level only), color cache, Huffman codes, and pixels, + * then applies the transforms' inverses. + * + * @param WebpRaster raster The raster to fill (full image, or a transform/meta sub-image). + * @param Boolean topLevel Whether this is the top-level image (reads transforms + meta codes). + * @param Int width Raster width. + * @param Int height Raster height. + */ + private fun readVP8Lossless(raster: WebpRaster, topLevel: Boolean, width: Int, height: Int) { + var xSize = width + val transforms = ArrayList() + while (topLevel && reader.readBit() == 1) { + xSize = readTransform(xSize, height, transforms) + } + + var colorCacheBits = 0 + if (reader.readBit() == 1) { + colorCacheBits = reader.readBits(4).toInt() + require(colorCacheBits in 1..11) { "Corrupt WebP: color-cache bits $colorCacheBits out of range" } + } + + val huffmanInfo = readHuffmanCodes(xSize, height, colorCacheBits, topLevel) + val colorCache = if (colorCacheBits > 0) WebpColorCache(colorCacheBits) else null + + val decodeRaster = if (topLevel) raster.child(0, 0, xSize, height) else raster + + decodeImage(decodeRaster, huffmanInfo, colorCache) + + for (transform in transforms) { + transform.applyInverse(raster) + } + } + + /** + * Reads one transform header (and its sub-image data), prepends the inverse transform to + * [transforms], and returns the possibly-reduced logical width. + * + * @param Int xSize The current logical width. + * @param Int ySize The image height. + * @param MutableList transforms The transform list (newest inserted at index 0). + * @return Int The logical width after this transform. + */ + private fun readTransform(xSize: Int, ySize: Int, transforms: MutableList): Int { + var newXSize = xSize + when (val transformType = reader.readBits(2).toInt()) { + WebpTransformType.PREDICTOR, WebpTransformType.COLOR -> { + val sizeBits = (reader.readBits(3) + 2).toInt() + val blockWidth = subSampleSize(xSize, sizeBits) + val blockHeight = subSampleSize(ySize, sizeBits) + val block = WebpRaster.create(blockWidth, blockHeight) + readVP8Lossless(block, topLevel = false, width = blockWidth, height = blockHeight) + if (transformType == WebpTransformType.PREDICTOR) { + transforms.add(0, PredictorTransform(block, sizeBits)) + } else { + transforms.add(0, ColorTransform(block, sizeBits)) + } + } + + WebpTransformType.SUBTRACT_GREEN -> transforms.add(0, SubtractGreenTransform()) + + WebpTransformType.COLOR_INDEXING -> { + val colorTableSize = reader.readBits(8).toInt() + 1 // 1..256 + val safeColorTableSize = + when { + colorTableSize > 16 -> 256 + colorTableSize > 4 -> 16 + colorTableSize > 2 -> 4 + else -> 2 + } + val colorTable = ByteArray(safeColorTableSize * 4) + readVP8Lossless(WebpRaster.over(colorTable, colorTableSize, 1), topLevel = false, width = colorTableSize, height = 1) + // The color table is subtraction-coded to reduce entropy; resolve it. + for (byteIndex in 4 until colorTable.size) { + colorTable[byteIndex] = (colorTable[byteIndex] + colorTable[byteIndex - 4]).toByte() + } + val widthBits = + when { + colorTableSize > 16 -> 0 + colorTableSize > 4 -> 1 + colorTableSize > 2 -> 2 + else -> 3 + } + newXSize = subSampleSize(xSize, widthBits) + transforms.add(0, ColorIndexingTransform(colorTable, widthBits)) + } + + else -> throw IllegalArgumentException("Invalid WebP VP8L transform type $transformType") + } + return newXSize + } + + /** + * Reads the Huffman code groups (and the optional per-block meta-code raster). + * + * @param Int xSize The logical width. + * @param Int ySize The image height. + * @param Int colorCacheBits The color-cache size in bits (0 if none). + * @param Boolean readMetaCodes Whether to read the meta-code image (top level only). + * @return WebpHuffmanInfo The Huffman groups and meta-code selection. + */ + private fun readHuffmanCodes(xSize: Int, ySize: Int, colorCacheBits: Int, readMetaCodes: Boolean): WebpHuffmanInfo { + var huffmanGroupNum = 1 + var metaCodeBits = 0 + var huffmanMetaCodes: WebpRaster? = null + + if (readMetaCodes && reader.readBit() == 1) { + metaCodeBits = reader.readBits(3).toInt() + 2 + val huffmanXSize = subSampleSize(xSize, metaCodeBits) + val huffmanYSize = subSampleSize(ySize, metaCodeBits) + val metaRaster = WebpRaster.create(huffmanXSize, huffmanYSize) + readVP8Lossless(metaRaster, topLevel = false, width = huffmanXSize, height = huffmanYSize) + var maxCode = Int.MIN_VALUE + for (blockY in 0 until huffmanYSize) { + for (blockX in 0 until huffmanXSize) { + // The meta group index is (red << 8) | green of the decoded meta pixel. + val code = (metaRaster.getSample(blockX, blockY, 0) shl 8) or metaRaster.getSample(blockX, blockY, 1) + maxCode = maxOf(maxCode, code) + } + } + huffmanGroupNum = maxCode + 1 + huffmanMetaCodes = metaRaster + } + + val huffmanGroups = Array(huffmanGroupNum) { WebpHuffmanCodeGroup(reader, colorCacheBits) } + return WebpHuffmanInfo(huffmanMetaCodes, metaCodeBits, huffmanGroups) + } + + /** + * The LZ77 + literal + color-cache decode loop, filling [raster]. + * + * @param WebpRaster raster The raster to fill. + * @param WebpHuffmanInfo huffmanInfo The Huffman groups. + * @param WebpColorCache? colorCache The color cache, or null. + */ + private fun decodeImage(raster: WebpRaster, huffmanInfo: WebpHuffmanInfo, colorCache: WebpColorCache?) { + val width = raster.width + val height = raster.height + val huffmanMask = if (huffmanInfo.metaCodeBits == 0) -1 else (1 shl huffmanInfo.metaCodeBits) - 1 + var currentGroup = huffmanInfo.huffmanGroups[0] + val rgba = ByteArray(4) + + var x = 0 + var y = 0 + while (y < height) { + if ((x and huffmanMask) == 0 && huffmanInfo.huffmanMetaCodes != null) { + currentGroup = huffmanInfo.huffmanGroups[metaGroupIndex(huffmanInfo, x, y)] + } + + val code = currentGroup.mainCode.readSymbol(reader) + if (code < 256) { + decodeLiteral(raster, colorCache, currentGroup, rgba, x, y, code) + x++ + } else if (code < 256 + 24) { + val length = decodeBackwardReference(raster, colorCache, width, currentGroup, rgba, code, x, y) + val linear = y * width + x + length + x = linear % width + y = linear / width + if (y < height && huffmanInfo.huffmanMetaCodes != null) { + currentGroup = huffmanInfo.huffmanGroups[metaGroupIndex(huffmanInfo, x, y)] + } + continue + } else { + decodeCached(raster, colorCache!!, rgba, x, y, code) + x++ + } + + if (x >= width) { + x = 0 + y++ + } + } + } + + /** + * The meta group index for block containing pixel (x, y). + * + * @param WebpHuffmanInfo huffmanInfo The Huffman info (with the meta raster). + * @param Int x Pixel column. + * @param Int y Pixel row. + * @return Int The group index. + */ + private fun metaGroupIndex(huffmanInfo: WebpHuffmanInfo, x: Int, y: Int): Int { + val meta = huffmanInfo.huffmanMetaCodes!! + val blockX = x shr huffmanInfo.metaCodeBits + val blockY = y shr huffmanInfo.metaCodeBits + return (meta.getSample(blockX, blockY, 0) shl 8) or meta.getSample(blockX, blockY, 1) + } + + /** + * Decodes a literal pixel: green is the main code, red/blue/alpha come from their own trees. + */ + private fun decodeLiteral(raster: WebpRaster, colorCache: WebpColorCache?, group: WebpHuffmanCodeGroup, rgba: ByteArray, x: Int, y: Int, green: Int) { + val red = group.redCode.readSymbol(reader) + val blue = group.blueCode.readSymbol(reader) + val alpha = group.alphaCode.readSymbol(reader) + rgba[0] = red.toByte() + rgba[1] = green.toByte() + rgba[2] = blue.toByte() + rgba[3] = alpha.toByte() + raster.setPixel(x, y, rgba) + colorCache?.insert(((alpha and 0xff) shl 24) or ((red and 0xff) shl 16) or ((green and 0xff) shl 8) or (blue and 0xff)) + } + + /** + * Decodes a color-cache reference into pixel (x, y). + */ + private fun decodeCached(raster: WebpRaster, colorCache: WebpColorCache, rgba: ByteArray, x: Int, y: Int, code: Int) { + val argb = colorCache.lookup(code - 256 - 24) + rgba[0] = ((argb shr 16) and 0xff).toByte() + rgba[1] = ((argb shr 8) and 0xff).toByte() + rgba[2] = (argb and 0xff).toByte() + rgba[3] = (argb ushr 24).toByte() + raster.setPixel(x, y, rgba) + } + + /** + * Decodes an LZ77 backward reference starting at (x, y), copying `length` pixels from the resolved + * source position, and returns the copied length. + */ + private fun decodeBackwardReference(raster: WebpRaster, colorCache: WebpColorCache?, width: Int, group: WebpHuffmanCodeGroup, rgba: ByteArray, code: Int, x: Int, y: Int): Int { + val length = lz77decode(code - 256) + val remaining = width * raster.height - (y * width + x) + require(length <= remaining) { "Corrupt WebP: backward reference exceeds image bounds" } + + val distancePrefix = group.distanceCode.readSymbol(reader) + val distanceCode = lz77decode(distancePrefix) + + var sourceX: Int + var sourceY: Int + if (distanceCode > 120) { + val distance = distanceCode - 120 + sourceY = y - (distance / width) + sourceX = x - (distance % width) + } else { + val packed = DISTANCES[distanceCode - 1].toInt() + sourceX = x - (8 - (packed and 0xf)) + sourceY = y - (packed shr 4) + } + if (sourceX < 0) { + sourceY-- + sourceX += width + } else if (sourceX >= width) { + sourceX -= width + sourceY++ + } + require(sourceY >= 0 && sourceY < raster.height) { "Corrupt WebP: backward reference outside image" } + + var copyX = x + var copyY = y + var readX = sourceX + var readY = sourceY + var remainingLength = length + while (remainingLength > 0) { + if (copyX == width) { + copyX = 0 + copyY++ + } + raster.getPixel(readX, readY, rgba) + readX++ + raster.setPixel(copyX, copyY, rgba) + if (readX == width) { + readX = 0 + readY++ + } + colorCache?.insert(((rgba[3].toInt() and 0xff) shl 24) or ((rgba[0].toInt() and 0xff) shl 16) or ((rgba[1].toInt() and 0xff) shl 8) or (rgba[2].toInt() and 0xff)) + copyX++ + remainingLength-- + } + return length + } + + /** + * Decodes an LZ77 length/distance prefix code to its value (VP8L spec §4.2.2). + * + * @param Int prefixCode The prefix code. + * @return Int The decoded length or distance. + */ + private fun lz77decode(prefixCode: Int): Int { + if (prefixCode < 4) { + return prefixCode + 1 + } + val extraBits = (prefixCode - 2) shr 1 + val offset = (2 + (prefixCode and 1)) shl extraBits + return offset + reader.readBits(extraBits).toInt() + 1 + } + + companion object { + // Short backward-reference distances: high nibble is the y distance, low nibble is 8 minus the x distance. + private val DISTANCES = + byteArrayOf( + 0x18, + 0x07, + 0x17, + 0x19, + 0x28, + 0x06, + 0x27, + 0x29, + 0x16, + 0x1a, + 0x26, + 0x2a, + 0x38, + 0x05, + 0x37, + 0x39, + 0x15, + 0x1b, + 0x36, + 0x3a, + 0x25, + 0x2b, + 0x48, + 0x04, + 0x47, + 0x49, + 0x14, + 0x1c, + 0x35, + 0x3b, + 0x46, + 0x4a, + 0x24, + 0x2c, + 0x58, + 0x45, + 0x4b, + 0x34, + 0x3c, + 0x03, + 0x57, + 0x59, + 0x13, + 0x1d, + 0x56, + 0x5a, + 0x23, + 0x2d, + 0x44, + 0x4c, + 0x55, + 0x5b, + 0x33, + 0x3d, + 0x68, + 0x02, + 0x67, + 0x69, + 0x12, + 0x1e, + 0x66, + 0x6a, + 0x22, + 0x2e, + 0x54, + 0x5c, + 0x43, + 0x4d, + 0x65, + 0x6b, + 0x32, + 0x3e, + 0x78, + 0x01, + 0x77, + 0x79, + 0x53, + 0x5d, + 0x11, + 0x1f, + 0x64, + 0x6c, + 0x42, + 0x4e, + 0x76, + 0x7a, + 0x21, + 0x2f, + 0x75, + 0x7b, + 0x31, + 0x3f, + 0x63, + 0x6d, + 0x52, + 0x5e, + 0x00, + 0x74, + 0x7c, + 0x41, + 0x4f, + 0x10, + 0x20, + 0x62, + 0x6e, + 0x30, + 0x73, + 0x7d, + 0x51, + 0x5f, + 0x40, + 0x72, + 0x7e, + 0x61, + 0x6f, + 0x50, + 0x71, + 0x7f, + 0x60, + 0x70, + ) + + /** + * Sub-samples a size by [samplingBits] (ceil division by 2^bits). + * + * @param Int size The full size. + * @param Int samplingBits The sampling shift. + * @return Int The reduced size. + */ + private fun subSampleSize(size: Int, samplingBits: Int): Int = (size + (1 shl samplingBits) - 1) shr samplingBits + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/Vp8lHeader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/Vp8lHeader.kt new file mode 100644 index 0000000..faff181 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/Vp8lHeader.kt @@ -0,0 +1,83 @@ +// WebP RIFF container + VP8L header parsing, from TwelveMonkeys imageio-webp WebPImageReader.readHeader +// (BSD-3-Clause, Copyright (c) 2020 Harald Kuhr) reimplemented over a ByteArray; see CREDITS.md. + +package org.umamo.format.webp + +import org.umamo.format.binary.ByteReader + +/** + * The parsed VP8L header: image dimensions and the byte offset where the LSB-first VP8L bit stream + * begins (just past the 1-byte signature and 4-byte packed dimensions). + */ +internal class Vp8lHeader(val width: Int, val height: Int, val bitStreamStart: Int) + +// VP8L bitstream signature byte, per the WebP container spec. +private const val VP8L_SIGNATURE = 0x2f + +/** + * Locates the VP8L chunk (directly, or inside a VP8X extended container) and parses its header. + * Lossy VP8, animation, and other unsupported layouts throw a clear error. + * + * @param ByteArray bytes The complete `.webp` file. + * @return Vp8lHeader The dimensions and bit-stream start offset. + */ +internal fun parseVp8lHeader(bytes: ByteArray): Vp8lHeader { + require(bytes.size >= 12) { "WebP too short for a RIFF header" } + require(fourCC(bytes, 0) == "RIFF" && fourCC(bytes, 8) == "WEBP") { "Not a WebP (bad RIFF/WEBP magic)" } + val reader = ByteReader(bytes, littleEndian = true) + + var chunkOffset = 12 + val firstFourCC = fourCC(bytes, chunkOffset) + if (firstFourCC == "VP8X") { + // Extended container: skip the 10-byte VP8X chunk, then scan sub-chunks for VP8L. + val vp8xSize = reader.u32AsInt(chunkOffset + 4) + chunkOffset += 8 + vp8xSize + (vp8xSize and 1) + while (chunkOffset + 8 <= bytes.size) { + val subFourCC = fourCC(bytes, chunkOffset) + val subSize = reader.u32AsInt(chunkOffset + 4) + when (subFourCC) { + "VP8L" -> return readVp8lHeader(reader, chunkOffset + 8) + "VP8 " -> throw IllegalArgumentException("Lossy VP8 WebP is not supported (VP8L only)") + } + chunkOffset += 8 + subSize + (subSize and 1) + } + throw IllegalArgumentException("WebP VP8X container has no supported VP8L image") + } + + return when (firstFourCC) { + "VP8L" -> readVp8lHeader(reader, chunkOffset + 8) + "VP8 " -> throw IllegalArgumentException("Lossy VP8 WebP is not supported (VP8L only)") + else -> throw IllegalArgumentException("Unsupported WebP chunk '$firstFourCC'") + } +} + +/** + * Reads the VP8L signature and packed 14+14+1+3-bit dimensions at [dataStart]. + * + * @param ByteReader reader The little-endian file reader. + * @param Int dataStart Offset of the VP8L chunk data (the signature byte). + * @return Vp8lHeader The dimensions and bit-stream start. + */ +private fun readVp8lHeader(reader: ByteReader, dataStart: Int): Vp8lHeader { + require(dataStart + 5 <= reader.bytes.size) { "Truncated VP8L header" } + require(reader.u8(dataStart) == VP8L_SIGNATURE) { "Bad VP8L signature" } + // WebP VP8L: 1-byte signature, then 14 bits (width-1) | 14 bits (height-1) | 1 bit alpha | 3 bits version. + val packed = reader.u32(dataStart + 1) + val width = (packed and 0x3FFF).toInt() + 1 + val height = ((packed shr 14) and 0x3FFF).toInt() + 1 + return Vp8lHeader(width, height, dataStart + 5) +} + +/** + * Reads a 4-character chunk tag at [at]. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset. + * @return String The 4 ASCII characters. + */ +private fun fourCC(bytes: ByteArray, at: Int): String = + buildString { + for (index in 0 until 4) { + append((bytes[at + index].toInt() and 0xFF).toChar()) + } + } \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebPReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebPReader.kt new file mode 100644 index 0000000..ae6228d --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebPReader.kt @@ -0,0 +1,51 @@ +package org.umamo.format.webp + +import org.umamo.format.FileKind +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.ReadOnlyRasterCodec + +/** + * Pure-Kotlin WebP reader (desktop JVM and Android), read only. + * + * Decodes lossless VP8L WebP (directly or inside a VP8X extended container) to the neutral + * straight-alpha RGBA8888 top-first [RasterImage] - VP8L pixels are natively RGBA, so no + * conversion is needed. Lossy VP8, animation, and VP8L encode are out of scope and rejected with + * a clear message. Ported from TwelveMonkeys imageio-webp's lossless decoder over a ByteArray, so + * it decodes identically on desktop and Android (no javax.imageio). Stays read-only for now (a + * VP8L writer would make it a read+write codec, taking the bare name WebP like Cmo3 / Moc3). + */ +public object WebPReader : ReadOnlyRasterCodec { + override val kind: FileKind = FileKind.WebP + + /** + * True if [candidateBytes] is a RIFF container tagged "WEBP". + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the leading bytes are the WebP magic. + */ + override fun matches(candidateBytes: ByteArray): Boolean { + // WebP: 'RIFF' @ +0x00, 4-byte file size, then the 'WEBP' form type @ +0x08. + if (candidateBytes.size < 12) { + return false + } + val riff = + candidateBytes[0] == 0x52.toByte() && candidateBytes[1] == 0x49.toByte() && candidateBytes[2] == 0x46.toByte() && candidateBytes[3] == 0x46.toByte() + val webp = + candidateBytes[8] == 0x57.toByte() && candidateBytes[9] == 0x45.toByte() && candidateBytes[10] == 0x42.toByte() && candidateBytes[11] == 0x50.toByte() + return riff && webp + } + + /** + * Decodes a lossless VP8L `.webp` into a straight-alpha RGBA8888 [RasterImage], top row first. + * + * @param ByteArray bytes The complete `.webp` file. + * @return RasterImage The decoded image. + */ + override fun read(bytes: ByteArray): RasterImage { + require(matches(bytes)) { "Not a WebP (bad signature)" } + val header = parseVp8lHeader(bytes) + val raster = WebpRaster.create(header.width, header.height) + Vp8lDecoder(WebpLsbBitReader(bytes, header.bitStreamStart)).decode(raster, header.width, header.height) + return RasterImage(header.width, header.height, raster.data) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpColorCache.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpColorCache.kt new file mode 100644 index 0000000..8e8ae4a --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpColorCache.kt @@ -0,0 +1,40 @@ +// Ported from TwelveMonkeys imageio-webp lossless ColorCache (BSD-3-Clause, Copyright (c) 2017 Harald +// Kuhr). VP8L hash color cache; see CREDITS.md. + +package org.umamo.format.webp + +private const val HASH_MULTIPLIER = 0x1e35a7bdL + +/** + * The VP8L color cache: a small hash table of recently emitted ARGB pixels, indexed by a fixed + * multiplicative hash of the packed ARGB value. + */ +internal class WebpColorCache(hashBits: Int) { + private val colors = IntArray(1 shl hashBits) + private val hashShift = 32 - hashBits + + /** + * Returns the ARGB stored at cache slot [key]. + * + * @param Int key The cache index. + * @return Int The packed ARGB value. + */ + fun lookup(key: Int): Int = colors[key] + + /** + * Inserts a packed ARGB value at its hashed slot. + * + * @param Int argb The packed ARGB value. + */ + fun insert(argb: Int) { + colors[hashIndex(argb)] = argb + } + + /** + * The cache slot for a packed ARGB value. + * + * @param Int argb The packed ARGB value. + * @return Int The slot index. + */ + private fun hashIndex(argb: Int): Int = (((argb.toLong() and 0xFFFFFFFFL) * HASH_MULTIPLIER) and 0xFFFFFFFFL).ushr(hashShift).toInt() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpHuffman.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpHuffman.kt new file mode 100644 index 0000000..3aa9cae --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpHuffman.kt @@ -0,0 +1,304 @@ +// Ported from TwelveMonkeys imageio-webp lossless HuffmanTable / HuffmanCodeGroup / HuffmanInfo +// (BSD-3-Clause, Copyright (c) 2022 Harald Kuhr, Simon Kammermeier). Two-level canonical Huffman +// decode for VP8L; see CREDITS.md. + +package org.umamo.format.webp + +private const val LEVEL1_BITS = 8 + +// Symbols of the code-length (L) code, in the order their lengths are read. +private val L_CODE_ORDER = intArrayOf(17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) + +/** + * One VP8L Huffman tree as a two-level lookup table. The direct level-1 table (256 entries) resolves + * codes up to 8 bits; longer codes indirect into a level-2 table. Each entry packs code length in + * the high 16 bits and the symbol in the low 16 bits. Bits are consumed least-significant-first, so + * a code appears in the stream as the bit-reversed suffix of the lookup index. + */ +internal class WebpHuffmanTable { + private val level1 = IntArray(1 shl LEVEL1_BITS) + private val level2 = ArrayList() + + /** + * Builds the table by reading the encoded symbol lengths from [reader]. + * + * @param WebpLsbBitReader reader The VP8L bit reader. + * @param Int alphabetSize The number of symbols this tree decodes. + */ + constructor(reader: WebpLsbBitReader, alphabetSize: Int) { + val simpleLengthCode = reader.readBit() == 1 + if (simpleLengthCode) { + val symbolNum = reader.readBit() + 1 + val first8Bits = reader.readBit() == 1 + val symbol1 = reader.readBits(if (first8Bits) 8 else 1).toInt() + if (symbolNum == 2) { + val symbol2 = reader.readBits(8).toInt() + var index = 0 + while (index < (1 shl LEVEL1_BITS)) { + level1[index] = (1 shl 16) or symbol1 + level1[index + 1] = (1 shl 16) or symbol2 + index += 2 + } + } else { + level1.fill(symbol1) + } + } else { + val numLCodeLengths = (reader.readBits(4) + 4).toInt() + val lCodeLengths = ShortArray(L_CODE_ORDER.size) + var numPosCodeLens = 0 + for (lengthIndex in 0 until numLCodeLengths) { + val length = reader.readBits(3).toShort() + lCodeLengths[L_CODE_ORDER[lengthIndex]] = length + if (length > 0) { + numPosCodeLens++ + } + } + val codeLengths = readCodeLengths(reader, lCodeLengths, alphabetSize, numPosCodeLens) + buildFromLengths(codeLengths, positiveLengthCount(codeLengths)) + } + } + + /** + * Builds the table directly from explicit code lengths (used for the code-length sub-tree). + * + * @param ShortArray codeLengths The per-symbol bit lengths. + * @param Int numPosCodeLens The count of non-zero lengths. + */ + private constructor(codeLengths: ShortArray, numPosCodeLens: Int) { + buildFromLengths(codeLengths, numPosCodeLens) + } + + /** + * Reads and decodes the next symbol from [reader]. + * + * @param WebpLsbBitReader reader The bit reader. + * @return Int The decoded symbol. + */ + fun readSymbol(reader: WebpLsbBitReader): Int { + val index = reader.peekBits(LEVEL1_BITS).toInt() + var lengthAndSymbol = level1[index] + var length = lengthAndSymbol ushr 16 + if (length > LEVEL1_BITS) { + reader.readBits(LEVEL1_BITS) + val level2Index = reader.peekBits(length - LEVEL1_BITS).toInt() + lengthAndSymbol = level2[lengthAndSymbol and 0xffff][level2Index] + length = lengthAndSymbol ushr 16 + } + reader.readBits(length) + return lengthAndSymbol and 0xffff + } + + /** + * Populates the two-level lookup from per-symbol code lengths (canonical-code construction). + * + * @param ShortArray codeLengths The per-symbol bit lengths. + * @param Int numPosCodeLens The count of non-zero lengths. + */ + private fun buildFromLengths(codeLengths: ShortArray, numPosCodeLens: Int) { + val lengthsAndSymbols = IntArray(numPosCodeLens) + var index = 0 + for (symbol in codeLengths.indices) { + if (codeLengths[symbol].toInt() != 0) { + lengthsAndSymbols[index++] = (codeLengths[symbol].toInt() shl 16) or symbol + } + } + + // Special case: a single code decodes every index to the same symbol. + if (numPosCodeLens == 1) { + level1.fill(lengthsAndSymbols[0] and 0xffff) + return + } + + // Sorting the packed (length, symbol) pairs orders first by length, then symbol. + lengthsAndSymbols.sort() + + val count = IntArray(16) + for (lengthAndSymbol in lengthsAndSymbols) { + count[lengthAndSymbol ushr 16]++ + } + + // The next code, in the bit-reversed order it appears in the stream. + var code = 0 + var step = 2 + index = 0 + var length = 1 + while (length <= LEVEL1_BITS) { + while (count[length] > 0) { + val lengthAndSymbol = lengthsAndSymbols[index++] + var entry = code + while (entry < level1.size) { + level1[entry] = lengthAndSymbol + entry += step + } + code = nextCode(code, length) + count[length]-- + } + length++ + step = step shl 1 + } + + val rootMask = (1 shl LEVEL1_BITS) - 1 + var rootEntry = -1 + var currentTable: IntArray? = null + step = 2 + length = LEVEL1_BITS + 1 + while (length <= 15) { + while (count[length] > 0) { + val lengthAndSymbol = lengthsAndSymbols[index++] + if ((code and rootMask) != rootEntry) { + val level2Bits = nextTableBitSize(count, length, LEVEL1_BITS) + currentTable = IntArray(1 shl level2Bits) + rootEntry = code and rootMask + level2.add(currentTable) + level1[rootEntry] = ((LEVEL1_BITS + level2Bits) shl 16) or (level2.size - 1) + } + val value = ((length - LEVEL1_BITS) shl 16) or (lengthAndSymbol and 0xffff) + var entry = code ushr LEVEL1_BITS + val table = currentTable!! + while (entry < table.size) { + table[entry] = value + entry += step + } + code = nextCode(code, length) + count[length]-- + } + length++ + step = step shl 1 + } + } + + /** + * Reads the actual per-symbol code lengths, themselves Huffman-coded by the code-length tree, with + * the 16/17/18 repeat operators. + * + * @param WebpLsbBitReader reader The bit reader. + * @param ShortArray lCodeLengths The code-length tree's own lengths. + * @param Int alphabetSize The target alphabet size. + * @param Int numPosCodeLens The count of non-zero L-code lengths. + * @return ShortArray The decoded per-symbol lengths. + */ + private fun readCodeLengths(reader: WebpLsbBitReader, lCodeLengths: ShortArray, alphabetSize: Int, numPosCodeLens: Int): ShortArray { + val lengthTree = WebpHuffmanTable(lCodeLengths, numPosCodeLens) + + var codedSymbols = + if (reader.readBit() == 1) { + val maxSymbolBitLength = (2 + 2 * reader.readBits(3)).toInt() + (2 + reader.readBits(maxSymbolBitLength)).toInt() + } else { + alphabetSize + } + + val codeLengths = ShortArray(alphabetSize) + var previousLength: Short = 8 + var symbol = 0 + while (symbol < alphabetSize && codedSymbols > 0) { + val length = lengthTree.readSymbol(reader) + if (length < 16) { + codeLengths[symbol] = length.toShort() + if (length != 0) { + previousLength = length.toShort() + } + } else { + var repeatSymbol: Short = 0 + val extraBits: Int + val repeatOffset: Int + when (length) { + 16 -> { + repeatSymbol = previousLength + extraBits = 2 + repeatOffset = 3 + } + + 17 -> { + extraBits = 3 + repeatOffset = 3 + } + + 18 -> { + extraBits = 7 + repeatOffset = 11 + } + + else -> throw IllegalArgumentException("WebP Huffman: decoded code length > 18") + } + val repeatCount = (reader.readBits(extraBits) + repeatOffset).toInt() + require(symbol + repeatCount <= alphabetSize) { "WebP Huffman: code-length repeat overflows alphabet" } + codeLengths.fill(repeatSymbol, symbol, symbol + repeatCount) + symbol += repeatCount - 1 + } + symbol++ + codedSymbols-- + } + return codeLengths + } +} + +/** + * The count of non-zero entries in [codeLengths]. + * + * @param ShortArray codeLengths The lengths. + * @return Int The positive count. + */ +private fun positiveLengthCount(codeLengths: ShortArray): Int { + var count = 0 + for (length in codeLengths) { + if (length.toInt() != 0) { + count++ + } + } + return count +} + +/** + * Advances a bit-reversed canonical code by one for the given length: reverse(reverse(code) + 1). + * + * @param Int code The current bit-reversed code. + * @param Int length The code length in bits. + * @return Int The next bit-reversed code. + */ +private fun nextCode(code: Int, length: Int): Int { + val inverted = code.inv() and ((1 shl length) - 1) + val step = inverted.takeHighestOneBit() + return (code and (step - 1)) or step +} + +/** + * The number of bits a level-2 sub-table needs, given the remaining code counts. + * + * @param IntArray count The per-length code counts. + * @param Int length The current code length. + * @param Int rootBits The level-1 bit width. + * @return Int The level-2 bit width. + */ +private fun nextTableBitSize(count: IntArray, length: Int, rootBits: Int): Int { + var currentLength = length + var left = 1 shl (currentLength - rootBits) + while (currentLength < 15) { + left -= count[currentLength] + if (left <= 0) { + break + } + currentLength++ + left = left shl 1 + } + return currentLength - rootBits +} + +/** The five Huffman trees of one VP8L Huffman group. */ +internal class WebpHuffmanCodeGroup(reader: WebpLsbBitReader, colorCacheBits: Int) { + val mainCode = WebpHuffmanTable(reader, 256 + 24 + if (colorCacheBits > 0) 1 shl colorCacheBits else 0) + val redCode = WebpHuffmanTable(reader, 256) + val blueCode = WebpHuffmanTable(reader, 256) + val alphaCode = WebpHuffmanTable(reader, 256) + val distanceCode = WebpHuffmanTable(reader, 40) +} + +/** + * The Huffman-group selection for an image: the optional meta-code raster (per-block group index) and + * the groups it selects among. + */ +internal class WebpHuffmanInfo( + val huffmanMetaCodes: WebpRaster?, + val metaCodeBits: Int, + val huffmanGroups: Array, +) \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpLsbBitReader.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpLsbBitReader.kt new file mode 100644 index 0000000..2f809f4 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpLsbBitReader.kt @@ -0,0 +1,57 @@ +// Reimplements TwelveMonkeys imageio-webp LSBBitReader (BSD-3-Clause, Copyright (c) 2020 Harald Kuhr, +// Simon Kammermeier) over a ByteArray instead of an ImageInputStream; see CREDITS.md. + +package org.umamo.format.webp + +/** + * A least-significant-bit-first bit reader over a [ByteArray], as VP8L requires: within a byte the + * low bit is consumed first, and successive bytes fill higher result bits. Reading past the end + * yields zero bits (a truncated stream degrades rather than throwing). + */ +internal class WebpLsbBitReader(private val bytes: ByteArray, startByte: Int) { + private var bitPosition: Long = startByte.toLong() * 8 + + /** + * Reads [count] bits LSB-first and advances. + * + * @param Int count Number of bits (0..64). + * @return Long The bits, first-read bit in the least-significant position. + */ + fun readBits(count: Int): Long { + var result = 0L + var shift = 0 + var remaining = count + while (remaining > 0) { + val bytePosition = (bitPosition ushr 3).toInt() + val bitInByte = (bitPosition and 7L).toInt() + val take = minOf(8 - bitInByte, remaining) + val byteValue = if (bytePosition < bytes.size) (bytes[bytePosition].toInt() and 0xFF) ushr bitInByte else 0 + val mask = (1 shl take) - 1 + result = result or ((byteValue and mask).toLong() shl shift) + shift += take + remaining -= take + bitPosition += take + } + return result + } + + /** + * Reads [count] bits without advancing (VP8L peeks up to the level-1 Huffman index width). + * + * @param Int count Number of bits. + * @return Long The peeked bits. + */ + fun peekBits(count: Int): Long { + val saved = bitPosition + val value = readBits(count) + bitPosition = saved + return value + } + + /** + * Reads a single bit and advances. + * + * @return Int The bit (0 or 1). + */ + fun readBit(): Int = readBits(1).toInt() +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpRaster.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpRaster.kt new file mode 100644 index 0000000..f57db3a --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpRaster.kt @@ -0,0 +1,93 @@ +// Replaces java.awt.image.WritableRaster in the ported VP8L decoder (TwelveMonkeys imageio-webp, +// BSD-3-Clause). A plain RGBA8888 byte buffer with (x, y) access and child views; see CREDITS.md. + +package org.umamo.format.webp + +/** + * A 2D RGBA8888 pixel buffer with (x, y) get/set and sub-region child views, standing in for the AWT + * WritableRaster the TwelveMonkeys VP8L decoder threads throughout. Band order is R, G, B, A (bands + * 0..3); a child view shares the parent's backing [data] and row stride, so writes land in place. + */ +internal class WebpRaster private constructor( + val data: ByteArray, + private val offsetX: Int, + private val offsetY: Int, + val width: Int, + val height: Int, + private val rowStridePixels: Int, +) { + private fun base(x: Int, y: Int): Int = ((offsetY + y) * rowStridePixels + offsetX + x) * 4 + + /** + * Copies pixel (x, y)'s four bytes into [out]. + * + * @param Int x Column. + * @param Int y Row. + * @param ByteArray out A length-4 destination (R, G, B, A). + */ + fun getPixel(x: Int, y: Int, out: ByteArray) { + val index = base(x, y) + out[0] = data[index] + out[1] = data[index + 1] + out[2] = data[index + 2] + out[3] = data[index + 3] + } + + /** + * Writes [src]'s four bytes into pixel (x, y). + * + * @param Int x Column. + * @param Int y Row. + * @param ByteArray src A length-4 source (R, G, B, A). + */ + fun setPixel(x: Int, y: Int, src: ByteArray) { + val index = base(x, y) + data[index] = src[0] + data[index + 1] = src[1] + data[index + 2] = src[2] + data[index + 3] = src[3] + } + + /** + * Returns one band (0=R, 1=G, 2=B, 3=A) of pixel (x, y) as an unsigned int. + * + * @param Int x Column. + * @param Int y Row. + * @param Int band The band index. + * @return Int The band value in 0..255. + */ + fun getSample(x: Int, y: Int, band: Int): Int = data[base(x, y) + band].toInt() and 0xFF + + /** + * Returns a child view sharing this buffer, offset by (x, y) with its own logical size. + * + * @param Int x Child origin column within this raster. + * @param Int y Child origin row within this raster. + * @param Int childWidth Child width. + * @param Int childHeight Child height. + * @return WebpRaster The child view. + */ + fun child(x: Int, y: Int, childWidth: Int, childHeight: Int): WebpRaster = + WebpRaster(data, offsetX + x, offsetY + y, childWidth, childHeight, rowStridePixels) + + companion object { + /** + * Allocates a fresh RGBA raster of the given size. + * + * @param Int width Width. + * @param Int height Height. + * @return WebpRaster The new raster. + */ + fun create(width: Int, height: Int): WebpRaster = WebpRaster(ByteArray(width * height * 4), 0, 0, width, height, width) + + /** + * Wraps an existing RGBA byte buffer as a raster (used for the color-indexing color table). + * + * @param ByteArray data The RGBA bytes (row-major, tightly packed). + * @param Int width Width. + * @param Int height Height. + * @return WebpRaster The raster over [data]. + */ + fun over(data: ByteArray, width: Int, height: Int): WebpRaster = WebpRaster(data, 0, 0, width, height, width) + } +} \ No newline at end of file diff --git a/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpTransforms.kt b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpTransforms.kt new file mode 100644 index 0000000..2223584 --- /dev/null +++ b/module/format/src/commonMain/kotlin/org/umamo/format/webp/WebpTransforms.kt @@ -0,0 +1,369 @@ +// Ported from TwelveMonkeys imageio-webp lossless transforms (BSD-3-Clause, Copyright (c) 2022 Harald +// Kuhr, Simon Kammermeier): PredictorTransform / ColorTransform / SubtractGreenTransform / +// ColorIndexingTransform and their mode constants; see CREDITS.md. + +package org.umamo.format.webp + +import kotlin.math.abs + +// VP8L transform types (order of the 2-bit transform selector). +internal object WebpTransformType { + const val PREDICTOR = 0 + const val COLOR = 1 + const val SUBTRACT_GREEN = 2 + const val COLOR_INDEXING = 3 +} + +// VP8L spatial predictor modes. +private object PredictorMode { + const val BLACK = 0 + const val L = 1 + const val T = 2 + const val TR = 3 + const val TL = 4 + const val AVG_L_TR_T = 5 + const val AVG_L_TL = 6 + const val AVG_L_T = 7 + const val AVG_TL_T = 8 + const val AVG_T_TR = 9 + const val AVG_L_TL_T_TR = 10 + const val SELECT = 11 + const val CLAMP_ADD_SUB_FULL = 12 + const val CLAMP_ADD_SUB_HALF = 13 +} + +/** One inverse VP8L transform, applied to the decoded image in place. */ +internal interface WebpTransform { + /** + * Applies this transform's inverse to [raster] in place. + * + * @param WebpRaster raster The full-size decoded image. + */ + fun applyInverse(raster: WebpRaster) +} + +/** Inverse subtract-green: add the green sample back to red and blue. */ +internal class SubtractGreenTransform : WebpTransform { + override fun applyInverse(raster: WebpRaster) { + val rgba = ByteArray(4) + for (y in 0 until raster.height) { + for (x in 0 until raster.width) { + raster.getPixel(x, y, rgba) + rgba[0] = ((rgba[0] + rgba[1]) and 0xff).toByte() + rgba[2] = ((rgba[2] + rgba[1]) and 0xff).toByte() + raster.setPixel(x, y, rgba) + } + } + } +} + +/** Inverse color-indexing: expand each packed palette index back to its RGBA color. */ +internal class ColorIndexingTransform(private val colorTable: ByteArray, private val bits: Int) : WebpTransform { + override fun applyInverse(raster: WebpRaster) { + val rgba = ByteArray(4) + val componentSize = 8 shr bits + val packed = 1 shl bits + val componentMask = (1 shl componentSize) - 1 + for (y in 0 until raster.height) { + // Reversed so packed source samples are not overwritten before they are read. + for (x in raster.width - 1 downTo 0) { + val sourceColumn = x / packed + val componentOffset = componentSize * (x % packed) + val sample = raster.getSample(sourceColumn, y, 1) + val index = (sample shr componentOffset) and componentMask + colorTable.copyInto(rgba, 0, index * 4, index * 4 + 4) + raster.setPixel(x, y, rgba) + } + } + } +} + +/** Inverse cross-color transform: add the per-block color deltas back to red and blue. */ +internal class ColorTransform(private val data: WebpRaster, private val bits: Int) : WebpTransform { + override fun applyInverse(raster: WebpRaster) { + val transformPixel = ByteArray(4) + val rgba = ByteArray(4) + for (y in 0 until raster.height) { + for (x in 0 until raster.width) { + data.getPixel(x shr bits, y shr bits, transformPixel) + val greenToRed = transformPixel[2] + val greenToBlue = transformPixel[1] + val redToBlue = transformPixel[0] + + raster.getPixel(x, y, rgba) + var tmpRed = rgba[0].toInt() + var tmpBlue = rgba[2].toInt() + tmpRed += colorTransformDelta(greenToRed, rgba[1]) + tmpBlue += colorTransformDelta(greenToBlue, rgba[1]) + tmpBlue += colorTransformDelta(redToBlue, tmpRed.toByte()) + rgba[0] = (tmpRed and 0xff).toByte() + rgba[2] = (tmpBlue and 0xff).toByte() + raster.setPixel(x, y, rgba) + } + } + } +} + +/** + * A color-transform delta: (t * c) >> 5 in signed 8-bit arithmetic. + * + * @param Byte transform The transform coefficient. + * @param Byte channel The channel value. + * @return Int The signed delta. + */ +private fun colorTransformDelta(transform: Byte, channel: Byte): Int = (transform.toInt() * channel.toInt()) shr 5 + +/** Inverse spatial predictor transform: add each pixel's predicted value back. */ +internal class PredictorTransform(private val data: WebpRaster, private val bits: Int) : WebpTransform { + override fun applyInverse(raster: WebpRaster) { + val width = raster.width + val height = raster.height + val rgba = ByteArray(4) + val predictor = ByteArray(4) + val predictor2 = ByteArray(4) + val predictor3 = ByteArray(4) + + // (0,0) uses the BLACK predictor: add 0xff to alpha only. + raster.getPixel(0, 0, rgba) + rgba[3] = (rgba[3] + 0xff).toByte() + raster.setPixel(0, 0, rgba) + + // Top row (x,0) predicts from the left. + for (x in 1 until width) { + raster.getPixel(x, 0, rgba) + raster.getPixel(x - 1, 0, predictor) + addPixels(rgba, predictor) + raster.setPixel(x, 0, rgba) + } + + // Left column (0,y) predicts from above. + for (y in 1 until height) { + raster.getPixel(0, y, rgba) + raster.getPixel(0, y - 1, predictor) + addPixels(rgba, predictor) + raster.setPixel(0, y, rgba) + } + + for (y in 1 until height) { + for (x in 1 until width) { + val mode = data.getSample(x shr bits, y shr bits, 1) + raster.getPixel(x, y, rgba) + + val leftX = x - 1 + val topY = y - 1 + val topRightX = if (x == width - 1) 0 else x + 1 + val topRightY = if (x == width - 1) y else topY + + when (mode) { + PredictorMode.BLACK -> rgba[3] = (rgba[3] + 0xff).toByte() + PredictorMode.L -> { + raster.getPixel(leftX, y, predictor) + addPixels(rgba, predictor) + } + + PredictorMode.T -> { + raster.getPixel(x, topY, predictor) + addPixels(rgba, predictor) + } + + PredictorMode.TR -> { + raster.getPixel(topRightX, topRightY, predictor) + addPixels(rgba, predictor) + } + + PredictorMode.TL -> { + raster.getPixel(leftX, topY, predictor) + addPixels(rgba, predictor) + } + + PredictorMode.AVG_L_TR_T -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(topRightX, topRightY, predictor2) + average2(predictor, predictor2) + raster.getPixel(x, topY, predictor2) + average2(predictor, predictor2) + addPixels(rgba, predictor) + } + + PredictorMode.AVG_L_TL -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(leftX, topY, predictor2) + average2(predictor, predictor2) + addPixels(rgba, predictor) + } + + PredictorMode.AVG_L_T -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(x, topY, predictor2) + average2(predictor, predictor2) + addPixels(rgba, predictor) + } + + PredictorMode.AVG_TL_T -> { + raster.getPixel(leftX, topY, predictor) + raster.getPixel(x, topY, predictor2) + average2(predictor, predictor2) + addPixels(rgba, predictor) + } + + PredictorMode.AVG_T_TR -> { + raster.getPixel(x, topY, predictor) + raster.getPixel(topRightX, topRightY, predictor2) + average2(predictor, predictor2) + addPixels(rgba, predictor) + } + + PredictorMode.AVG_L_TL_T_TR -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(leftX, topY, predictor2) + average2(predictor, predictor2) + raster.getPixel(x, topY, predictor2) + raster.getPixel(topRightX, topRightY, predictor3) + average2(predictor2, predictor3) + average2(predictor, predictor2) + addPixels(rgba, predictor) + } + + PredictorMode.SELECT -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(x, topY, predictor2) + raster.getPixel(leftX, topY, predictor3) + addPixels(rgba, select(predictor, predictor2, predictor3)) + } + + PredictorMode.CLAMP_ADD_SUB_FULL -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(x, topY, predictor2) + raster.getPixel(leftX, topY, predictor3) + clampAddSubtractFull(predictor, predictor2, predictor3) + addPixels(rgba, predictor) + } + + PredictorMode.CLAMP_ADD_SUB_HALF -> { + raster.getPixel(leftX, y, predictor) + raster.getPixel(x, topY, predictor2) + average2(predictor, predictor2) + raster.getPixel(leftX, topY, predictor2) + clampAddSubtractHalf(predictor, predictor2) + addPixels(rgba, predictor) + } + } + raster.setPixel(x, y, rgba) + } + } + } +} + +/** + * Adds a predictor pixel into [rgba] component-wise (mod 256). + * + * @param ByteArray rgba The pixel to update. + * @param ByteArray predictor The predictor pixel. + */ +private fun addPixels(rgba: ByteArray, predictor: ByteArray) { + rgba[0] = (rgba[0] + predictor[0]).toByte() + rgba[1] = (rgba[1] + predictor[1]).toByte() + rgba[2] = (rgba[2] + predictor[2]).toByte() + rgba[3] = (rgba[3] + predictor[3]).toByte() +} + +/** + * Averages two pixels component-wise into [first]. + * + * @param ByteArray first The first pixel (overwritten with the average). + * @param ByteArray second The second pixel. + */ +private fun average2(first: ByteArray, second: ByteArray) { + first[0] = (((first[0].toInt() and 0xff) + (second[0].toInt() and 0xff)) / 2).toByte() + first[1] = (((first[1].toInt() and 0xff) + (second[1].toInt() and 0xff)) / 2).toByte() + first[2] = (((first[2].toInt() and 0xff) + (second[2].toInt() and 0xff)) / 2).toByte() + first[3] = (((first[3].toInt() and 0xff) + (second[3].toInt() and 0xff)) / 2).toByte() +} + +/** + * The Select predictor: returns whichever of the left/top pixels is closer (Manhattan) to the + * gradient estimate left + top - topLeft. + * + * @param ByteArray left The left pixel. + * @param ByteArray top The top pixel. + * @param ByteArray topLeft The top-left pixel. + * @return ByteArray Either [left] or [top]. + */ +private fun select(left: ByteArray, top: ByteArray, topLeft: ByteArray): ByteArray { + val predictedAlpha = addSubtractFull(left[3], top[3], topLeft[3]) + val predictedRed = addSubtractFull(left[0], top[0], topLeft[0]) + val predictedGreen = addSubtractFull(left[1], top[1], topLeft[1]) + val predictedBlue = addSubtractFull(left[2], top[2], topLeft[2]) + val distanceLeft = manhattanDistance(left, predictedAlpha, predictedRed, predictedGreen, predictedBlue) + val distanceTop = manhattanDistance(top, predictedAlpha, predictedRed, predictedGreen, predictedBlue) + return if (distanceLeft < distanceTop) left else top +} + +/** + * The Manhattan distance from a pixel to the predicted A/R/G/B estimate. + * + * @param ByteArray rgba The pixel to measure. + * @param Int predictedAlpha The estimate's alpha. + * @param Int predictedRed The estimate's red. + * @param Int predictedGreen The estimate's green. + * @param Int predictedBlue The estimate's blue. + * @return Int The summed absolute per-component difference. + */ +private fun manhattanDistance(rgba: ByteArray, predictedAlpha: Int, predictedRed: Int, predictedGreen: Int, predictedBlue: Int): Int = + abs(predictedAlpha - (rgba[3].toInt() and 0xff)) + abs(predictedRed - (rgba[0].toInt() and 0xff)) + + abs(predictedGreen - (rgba[1].toInt() and 0xff)) + abs(predictedBlue - (rgba[2].toInt() and 0xff)) + +/** + * Clamps a value to an 8-bit sample. + * + * @param Int value The value to clamp. + * @return Int The value in 0..255. + */ +private fun clamp(value: Int): Int = maxOf(0, minOf(value, 255)) + +/** + * The gradient estimate for one component: left + top - topLeft, unsigned. + * + * @param Byte left The left neighbour's component. + * @param Byte top The top neighbour's component. + * @param Byte topLeft The top-left neighbour's component. + * @return Int The estimate, which may fall outside 0..255. + */ +private fun addSubtractFull(left: Byte, top: Byte, topLeft: Byte): Int = (left.toInt() and 0xff) + (top.toInt() and 0xff) - (topLeft.toInt() and 0xff) + +/** + * The half-gradient estimate for one component: average + (average - topLeft) / 2, unsigned. + * + * @param Byte average The left/top average's component. + * @param Byte topLeft The top-left neighbour's component. + * @return Int The estimate, which may fall outside 0..255. + */ +private fun addSubtractHalf(average: Byte, topLeft: Byte): Int = + (average.toInt() and 0xff) + ((average.toInt() and 0xff) - (topLeft.toInt() and 0xff)) / 2 + +/** + * The clamped full add-subtract predictor, written back into [left]. + * + * @param ByteArray left The left neighbour; overwritten with the prediction. + * @param ByteArray top The top neighbour. + * @param ByteArray topLeft The top-left neighbour. + */ +private fun clampAddSubtractFull(left: ByteArray, top: ByteArray, topLeft: ByteArray) { + left[0] = clamp(addSubtractFull(left[0], top[0], topLeft[0])).toByte() + left[1] = clamp(addSubtractFull(left[1], top[1], topLeft[1])).toByte() + left[2] = clamp(addSubtractFull(left[2], top[2], topLeft[2])).toByte() + left[3] = clamp(addSubtractFull(left[3], top[3], topLeft[3])).toByte() +} + +/** + * The clamped half add-subtract predictor, written back into [average]. + * + * @param ByteArray average The left/top average; overwritten with the prediction. + * @param ByteArray topLeft The top-left neighbour. + */ +private fun clampAddSubtractHalf(average: ByteArray, topLeft: ByteArray) { + average[0] = clamp(addSubtractHalf(average[0], topLeft[0])).toByte() + average[1] = clamp(addSubtractHalf(average[1], topLeft[1])).toByte() + average[2] = clamp(addSubtractHalf(average[2], topLeft[2])).toByte() + average[3] = clamp(addSubtractHalf(average[3], topLeft[3])).toByte() +} \ No newline at end of file diff --git a/module/format/src/commonMain/sqldelight/org/umamo/format/clip/db/Clip.sq b/module/format/src/commonMain/sqldelight/org/umamo/format/clip/db/Clip.sq new file mode 100644 index 0000000..66d4161 --- /dev/null +++ b/module/format/src/commonMain/sqldelight/org/umamo/format/clip/db/Clip.sq @@ -0,0 +1,110 @@ +-- SQLDelight schema + queries for the embedded CLIP (Clip Studio Paint) database. +-- +-- These CREATE TABLE statements declare ONLY the subset of columns the reader consumes — the real +-- Canvas/Layer tables in a .clip carry dozens more (all `DEFAULT NULL`). They exist purely so +-- SQLDelight can type-check the SELECTs below and generate row classes; the reader NEVER runs +-- Schema.create (the embedded database already has its tables). Columns are left nullable to match +-- CLIP's `DEFAULT NULL` definitions. Citations: // CLIP: .. + +-- CLIP: Canvas — one row holding document geometry and the root-folder pointer. +CREATE TABLE Canvas ( + CanvasWidth REAL, -- CLIP: Canvas.CanvasWidth (pixels, stored as REAL) + CanvasHeight REAL, -- CLIP: Canvas.CanvasHeight (pixels, stored as REAL) + CanvasRootFolder INTEGER -- CLIP: Canvas.CanvasRootFolder (MainId of the root layer folder) +); + +-- CLIP: Layer — one row per layer/folder; the tree is encoded by MainId child/sibling links. +CREATE TABLE Layer ( + MainId INTEGER, -- CLIP: Layer.MainId (stable internal id; tree node key) + LayerName TEXT, -- CLIP: Layer.LayerName + LayerFolder INTEGER, -- CLIP: Layer.LayerFolder (bit 0x10 set => folder/group) + LayerType INTEGER, -- CLIP: Layer.LayerType (raster/adjustment/text/...; not yet mapped) + LayerVisibility INTEGER, -- CLIP: Layer.LayerVisibility (0/1) + LayerOpacity INTEGER, -- CLIP: Layer.LayerOpacity (0..256) + LayerComposite INTEGER, -- CLIP: Layer.LayerComposite (blend-mode code) + LayerClip INTEGER, -- CLIP: Layer.LayerClip (non-zero => clip to layer below) + LayerOffsetX INTEGER, -- CLIP: Layer.LayerOffsetX (canvas X, may be negative) + LayerOffsetY INTEGER, -- CLIP: Layer.LayerOffsetY (canvas Y, may be negative) + LayerFirstChildIndex INTEGER, -- CLIP: Layer.LayerFirstChildIndex (first child MainId, 0 => leaf) + LayerNextIndex INTEGER, -- CLIP: Layer.LayerNextIndex (next sibling MainId, 0 => end) + LayerUuid TEXT, -- CLIP: Layer.LayerUuid (rename/reorder-stable; preferred id) + LayerRenderMipmap INTEGER, -- CLIP: Layer.LayerRenderMipmap (MainId into Mipmap -> raster) + LayerRenderOffscrOffsetX INTEGER, -- CLIP: Layer.LayerRenderOffscrOffsetX (grid anchor = offset + this) + LayerRenderOffscrOffsetY INTEGER, -- CLIP: Layer.LayerRenderOffscrOffsetY + LayerLayerMaskMipmap INTEGER, -- CLIP: Layer.LayerLayerMaskMipmap (MainId into Mipmap -> mask) + TextLayerType INTEGER -- CLIP: Layer.TextLayerType (non-null => a text object layer) +); + +-- CLIP: Mipmap — a layer's pyramid; BaseMipmapInfo points at the full-resolution level. +CREATE TABLE Mipmap ( + MainId INTEGER, -- CLIP: Mipmap.MainId (== Layer.LayerRenderMipmap) + BaseMipmapInfo INTEGER -- CLIP: Mipmap.BaseMipmapInfo (MainId into MipmapInfo, full-res level) +); + +-- CLIP: MipmapInfo — one node per pyramid level; Offscreen points at that level's pixel store. +CREATE TABLE MipmapInfo ( + MainId INTEGER, -- CLIP: MipmapInfo.MainId + Offscreen INTEGER -- CLIP: MipmapInfo.Offscreen (MainId into Offscreen) +); + +-- CLIP: Offscreen — the tiled pixel store: Attribute is the tile index, BlockData the external ref. +CREATE TABLE Offscreen ( + MainId INTEGER, -- CLIP: Offscreen.MainId + Attribute BLOB, -- CLIP: Offscreen.Attribute (Parameter: width/height/cols/rows; BlockSize array) + BlockData BLOB -- CLIP: Offscreen.BlockData ("extrnlid"+GUID, keys ExternalChunk) +); + +-- CLIP: ExternalChunk — maps an "extrnlid"+GUID to the absolute file offset of its CHNKExta chunk. +CREATE TABLE ExternalChunk ( + ExternalID BLOB, -- CLIP: ExternalChunk.ExternalID ("extrnlid"+GUID; matches Offscreen.BlockData) + Offset INTEGER -- CLIP: ExternalChunk.Offset (byte offset of the CHNKExta chunk in the file) +); + +-- Document geometry + the id of the (never-emitted) root folder we descend from. +selectCanvas: +SELECT CanvasWidth, CanvasHeight, CanvasRootFolder +FROM Canvas +LIMIT 1; + +-- Every layer row; the reader maps these into the neutral model and walks the child/sibling links. +-- LayerRenderOffscrOffsetX/Y give the tile-grid anchor: anchor = LayerOffset + LayerRenderOffscrOffset +-- (canvas-aligned, observed to be 0 across the corpus). +selectAllLayers: +SELECT MainId, LayerName, LayerFolder, LayerType, LayerVisibility, LayerOpacity, LayerComposite, + LayerClip, LayerOffsetX, LayerOffsetY, LayerFirstChildIndex, LayerNextIndex, LayerUuid, + LayerRenderOffscrOffsetX, LayerRenderOffscrOffsetY +FROM Layer; + +-- MainIds of text object layers. TextLayerType only exists in newer CLIP schemas, so the reader +-- runs this defensively (a missing column => no text layers); keep it OUT of selectAllLayers, whose +-- columns must exist in every supported CLIP version. See docs/CLIP.md §5 on schema-version robustness. +selectTextLayerIds: +SELECT MainId +FROM Layer +WHERE TextLayerType IS NOT NULL; + +-- The "extrnlid"+GUID -> file-offset map used to locate each layer's external pixel chunk. +selectExternalChunks: +SELECT ExternalID, Offset +FROM ExternalChunk; + +-- Per-layer base-resolution raster: the tile-index Attribute and the external-chunk reference, +-- resolved through the Mipmap -> MipmapInfo -> Offscreen chain. Keyed by Layer.MainId. +selectLayerRasters: +SELECT L.MainId, O.Attribute, O.BlockData +FROM Layer L +JOIN Mipmap M ON M.MainId = L.LayerRenderMipmap +JOIN MipmapInfo MI ON MI.MainId = M.BaseMipmapInfo +JOIN Offscreen O ON O.MainId = MI.Offscreen +WHERE L.LayerRenderMipmap IS NOT NULL AND O.BlockData IS NOT NULL; + +-- Per-layer raster MASK (single-channel grayscale), via the LayerLayerMaskMipmap chain. The mask +-- offscreen is canvas-anchored identically to the render offscreen, so mask tile (col,row) aligns +-- with render tile (col,row). Keyed by Layer.MainId. +selectLayerMaskRasters: +SELECT L.MainId, O.Attribute, O.BlockData +FROM Layer L +JOIN Mipmap M ON M.MainId = L.LayerLayerMaskMipmap +JOIN MipmapInfo MI ON MI.MainId = M.BaseMipmapInfo +JOIN Offscreen O ON O.MainId = MI.Offscreen +WHERE L.LayerLayerMaskMipmap IS NOT NULL AND L.LayerLayerMaskMipmap <> 0 AND O.BlockData IS NOT NULL; diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/FileKindTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/FileKindTest.kt new file mode 100644 index 0000000..8a69940 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/FileKindTest.kt @@ -0,0 +1,43 @@ +package org.umamo.format + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the way in each file kind declares, because the answer decides what a file DOES to the editor: a + * document replaces the open one, artwork is added to it, and a sidecar is never handed over on its own. + * Getting a role wrong would make a dropped PSD discard a rig, or a dropped `.uma` land as source art. + * + * Listed exhaustively rather than sampled: the table is the specification, so a kind added without a + * considered role fails here instead of quietly inheriting one. + */ +class FileKindTest { + @Test + fun everyKindDeclaresItsWayIn() { + assertEquals(FileRole.Document, FileKind.Uma.role, "the native document") + assertEquals(FileRole.Document, FileKind.Cmo3.role, "the Cubism source project, imported whole") + assertEquals(FileRole.Document, FileKind.Moc3.role, "the baked runtime, imported whole") + assertEquals(FileRole.Sidecar, FileKind.Json.role, "the MOC3 family, found beside a document") + assertEquals(FileRole.Artwork, FileKind.Psd.role) + assertEquals(FileRole.Artwork, FileKind.Clip.role) + assertEquals(FileRole.Artwork, FileKind.Kra.role) + assertEquals(FileRole.Artwork, FileKind.Png.role, "a flat raster is art, not an atlas page, when it arrives on its own") + assertEquals(FileRole.Artwork, FileKind.Bmp.role) + assertEquals(FileRole.Artwork, FileKind.Jpeg.role) + assertEquals(FileRole.Artwork, FileKind.WebP.role) + assertEquals(FileRole.Artwork, FileKind.Tiff.role) + } + + /** + * Only the two formats written under a second extension declare one, and an alias is never the same + * string as some kind's primary extension - one name must resolve to one format. + */ + @Test + fun onlyTheFormatsWithASecondNameDeclareAliases() { + assertEquals(listOf("jpeg"), FileKind.Jpeg.extensionAliases) + assertEquals(listOf("tif"), FileKind.Tiff.extensionAliases) + assertTrue(FileKind.Uma.extensionAliases.isEmpty(), "a kind declares none by default") + assertTrue(FileKind.Png.extensionAliases.isEmpty()) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaAnalysisTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaAnalysisTest.kt new file mode 100644 index 0000000..6571bfc --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaAnalysisTest.kt @@ -0,0 +1,182 @@ +package org.umamo.format.art + +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.analyzeAlpha +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Unit tests for the alpha-analysis entry points over synthetic pixels: trimmed bounds, the + * occupancy count, threshold semantics (including the signed-byte alpha trap), the + * null-when-empty contract, argument validation, and the convenience extensions. Contour + * geometry has its own suite in AlphaContourTest; simplification in ContourSimplifyTest. + */ +class AlphaAnalysisTest { + @Test + fun fullyTransparentYieldsNull() { + // Nonzero RGB with zero alpha must not count: only the alpha channel decides. + assertNull(rasterOfRows("...", "...").analyzeAlpha()) + } + + @Test + fun zeroSizedRasterYieldsNull() { + assertNull(analyzeAlpha(0, 0, ByteArray(0))) + assertNull(analyzeAlpha(3, 0, ByteArray(0))) + } + + @Test + fun singleOpaquePixelHasUnitBounds() { + val analysis = assertNotNull(rasterOfRows("....", "..#.", "....").analyzeAlpha()) + assertEquals(LayerBounds(left = 2, top = 1, width = 1, height = 1), analysis.opaqueBounds) + assertEquals(1, analysis.opaquePixelCount) + assertEquals(1f, analysis.boundsCoverage) + } + + @Test + fun fullyOpaqueRectCoversItsBounds() { + val analysis = assertNotNull(rasterOfRows("###", "###").analyzeAlpha()) + assertEquals(LayerBounds(left = 0, top = 0, width = 3, height = 2), analysis.opaqueBounds) + assertEquals(6, analysis.opaquePixelCount) + assertEquals(1f, analysis.boundsCoverage) + } + + @Test + fun offsetRectangleTrimsExactly() { + val raster = + rasterOfRows( + "......", + "..###.", + "..###.", + "..###.", + "......", + ) + val analysis = assertNotNull(raster.analyzeAlpha()) + assertEquals(LayerBounds(left = 2, top = 1, width = 3, height = 3), analysis.opaqueBounds) + assertEquals(9, analysis.opaquePixelCount) + assertNoOpaquePixelOutside(raster, analysis.opaqueBounds, DEFAULT_ALPHA_THRESHOLD) + } + + @Test + fun coverageReflectsPartialOccupancy() { + // L-shape: 3 opaque pixels in a 2x2 trimmed rect. + val analysis = assertNotNull(rasterOfRows("#.", "##").analyzeAlpha()) + assertEquals(LayerBounds(left = 0, top = 0, width = 2, height = 2), analysis.opaqueBounds) + assertEquals(3, analysis.opaquePixelCount) + assertEquals(0.75f, analysis.boundsCoverage) + } + + @Test + fun defaultThresholdCountsAnyNonzeroAlpha() { + val analysis = assertNotNull(rasterOfAlphas(0, 1).analyzeAlpha()) + assertEquals(LayerBounds(left = 1, top = 0, width = 1, height = 1), analysis.opaqueBounds) + assertEquals(1, analysis.opaquePixelCount) + } + + @Test + fun customThresholdIncludesExactValueAndExcludesBelow() { + val analysis = assertNotNull(rasterOfAlphas(127, 128, 200, 255).analyzeAlpha(alphaThreshold = 128)) + assertEquals(LayerBounds(left = 1, top = 0, width = 3, height = 1), analysis.opaqueBounds) + assertEquals(3, analysis.opaquePixelCount) + } + + @Test + fun highAlphaValuesSurviveSignedByteStorage() { + // 128..255 read negative from a Kotlin Byte without masking; all four must count. + val analysis = assertNotNull(rasterOfAlphas(127, 128, 200, 255).analyzeAlpha()) + assertEquals(4, analysis.opaquePixelCount) + } + + @Test + fun sliversKeepTheirTrueBounds() { + // A 1 px wide layer with real opaque pixels is reported, never excluded here — + // exclusion is consumer policy. + val column = assertNotNull(rasterOfRows("#", "#", "#", "#", "#").analyzeAlpha()) + assertEquals(LayerBounds(left = 0, top = 0, width = 1, height = 5), column.opaqueBounds) + assertEquals(1, column.contours.size) + assertTrue(column.contours[0].points.size >= 6, "sliver contour still has at least 3 points") + + val row = assertNotNull(rasterOfRows("#####").analyzeAlpha()) + assertEquals(LayerBounds(left = 0, top = 0, width = 5, height = 1), row.opaqueBounds) + assertEquals(5, row.opaquePixelCount) + } + + @Test + fun rejectsMalformedArguments() { + assertFailsWith { analyzeAlpha(-1, 1, ByteArray(0)) } + assertFailsWith { analyzeAlpha(2, 2, ByteArray(15)) } + assertFailsWith { analyzeAlpha(1, 1, ByteArray(4), alphaThreshold = 0) } + assertFailsWith { analyzeAlpha(1, 1, ByteArray(4), alphaThreshold = 256) } + assertFailsWith { analyzeAlpha(1, 1, ByteArray(4), contourEpsilon = -1f) } + } + + @Test + fun extensionsAgreeWithThePositionalCore() { + val raster = rasterOfRows("##.", ".#.") + val fromExtension = assertNotNull(raster.analyzeAlpha()) + val fromPositional = assertNotNull(analyzeAlpha(raster.width, raster.height, raster.rgba)) + assertEquals(fromPositional.opaqueBounds, fromExtension.opaqueBounds) + assertEquals(fromPositional.opaquePixelCount, fromExtension.opaquePixelCount) + assertEquals(fromPositional.contours.size, fromExtension.contours.size) + for (contourIndex in fromPositional.contours.indices) { + assertContentEquals( + fromPositional.contours[contourIndex].points, + fromExtension.contours[contourIndex].points, + ) + assertEquals( + fromPositional.contours[contourIndex].isHole, + fromExtension.contours[contourIndex].isHole, + ) + } + } + + @Test + fun rasterImageExtensionAgreesWithThePositionalCore() { + val layerRaster = rasterOfRows("#.", ".#") + val image = RasterImage(layerRaster.width, layerRaster.height, layerRaster.rgba) + val fromImage = assertNotNull(image.analyzeAlpha()) + val fromPositional = assertNotNull(analyzeAlpha(layerRaster.width, layerRaster.height, layerRaster.rgba)) + assertEquals(fromPositional.opaqueBounds, fromImage.opaqueBounds) + assertEquals(fromPositional.opaquePixelCount, fromImage.opaquePixelCount) + assertEquals(fromPositional.contours.size, fromImage.contours.size) + for (contourIndex in fromPositional.contours.indices) { + assertContentEquals( + fromPositional.contours[contourIndex].points, + fromImage.contours[contourIndex].points, + ) + } + } + + @Test + fun sourceLayerAnalysisIgnoresCompositingProperties() { + val raster = rasterOfRows(".#.", "###") + val opaqueVisible = FakeSourceLayer(raster = raster, opacity = 1f, visible = true) + val faintHidden = FakeSourceLayer(raster = raster, opacity = 0.1f, visible = false) + val first = assertNotNull(opaqueVisible.analyzeAlpha()) + val second = assertNotNull(faintHidden.analyzeAlpha()) + assertEquals(first.opaqueBounds, second.opaqueBounds) + assertEquals(first.opaquePixelCount, second.opaquePixelCount) + } + + @Test + fun opaqueBoundsOnCanvasOffsetsByLayerPosition() { + val analysis = + assertNotNull( + rasterOfRows( + "......", + "..###.", + "..###.", + "..###.", + "......", + ).analyzeAlpha(), + ) + assertEquals( + LayerBounds(left = 102, top = 51, width = 3, height = 3), + analysis.opaqueBoundsOnCanvas(LayerBounds(left = 100, top = 50, width = 6, height = 5)), + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaAnalysisTestSupport.kt b/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaAnalysisTestSupport.kt new file mode 100644 index 0000000..0f8b4e9 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaAnalysisTestSupport.kt @@ -0,0 +1,218 @@ +package org.umamo.format.art + +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Builds a LayerRaster from rows of character art: '#' is alpha 255, '.' is alpha 0, and a + * decimal digit is that literal alpha value (0..9). RGB bytes are filled with nonzero values + * so an alpha-offset bug that reads a color channel as coverage fails loudly. + * + * @param String rows One string per pixel row, top row first, all the same length. + * @return LayerRaster The synthetic raster. + */ +internal fun rasterOfRows(vararg rows: String): LayerRaster { + val height = rows.size + val width = if (height == 0) 0 else rows[0].length + val rgba = ByteArray(width * height * 4) + for (rowIndex in 0 until height) { + require(rows[rowIndex].length == width) { "all rows must share one width" } + for (columnIndex in 0 until width) { + val cell = rows[rowIndex][columnIndex] + val alpha = + when (cell) { + '#' -> 255 + '.' -> 0 + in '0'..'9' -> cell - '0' + else -> throw IllegalArgumentException("unknown cell '$cell'") + } + val byteIndex = (rowIndex * width + columnIndex) * 4 + rgba[byteIndex] = 0x11 + rgba[byteIndex + 1] = 0x22 + rgba[byteIndex + 2] = 0x33 + rgba[byteIndex + 3] = alpha.toByte() + } + } + return LayerRaster(width, height, rgba) +} + +/** + * Builds a one-row LayerRaster with the given alpha byte values, RGB filled nonzero. + * + * @param Int alphaValues One alpha (0..255) per pixel, left to right. + * @return LayerRaster The synthetic 1-row raster. + */ +internal fun rasterOfAlphas(vararg alphaValues: Int): LayerRaster { + val rgba = ByteArray(alphaValues.size * 4) + for (columnIndex in alphaValues.indices) { + rgba[columnIndex * 4] = 0x11 + rgba[columnIndex * 4 + 1] = 0x22 + rgba[columnIndex * 4 + 2] = 0x33 + rgba[columnIndex * 4 + 3] = alphaValues[columnIndex].toByte() + } + return LayerRaster(alphaValues.size, 1, rgba) +} + +/** + * Asserts by direct rescan that no pixel outside the given raster-local bounds meets the + * threshold — the definition of the trimmed rect being trim-lossless. + * + * @param LayerRaster raster The analyzed raster. + * @param LayerBounds bounds The raster-local trimmed bounds. + * @param Int alphaThreshold The threshold the analysis ran with. + */ +internal fun assertNoOpaquePixelOutside(raster: LayerRaster, bounds: LayerBounds, alphaThreshold: Int) { + for (rowIndex in 0 until raster.height) { + for (columnIndex in 0 until raster.width) { + val insideBounds = + columnIndex >= bounds.left && + columnIndex < bounds.left + bounds.width && + rowIndex >= bounds.top && + rowIndex < bounds.top + bounds.height + if (insideBounds) { + continue + } + val alpha = raster.rgba[(rowIndex * raster.width + columnIndex) * 4 + 3].toInt() and 0xFF + assertTrue( + alpha < alphaThreshold, + "opaque pixel ($columnIndex, $rowIndex) outside trimmed bounds $bounds", + ) + } + } +} + +/** + * Asserts the structural invariants every non-null analysis must satisfy: a positive count, + * at least one contour, at least one non-hole, and per contour an even flat size of at least + * 3 points with every corner inside the trimmed-bounds lattice. + * + * With exactRings (epsilon 0) it additionally asserts what only unsimplified rings guarantee: + * implicit closure (first point differs from last), distinct consecutive points, axis-aligned + * consecutive steps including the wrap-around pair, the hole flag matching the shoelace sign, + * and the signed contour areas summing to exactly the opaque pixel count. + * + * @param AlphaAnalysis analysis The analysis under test. + * @param Boolean exactRings True when the analysis ran with contourEpsilon 0. + */ +internal fun assertAnalysisInvariants(analysis: AlphaAnalysis, exactRings: Boolean) { + assertTrue(analysis.opaquePixelCount >= 1, "non-null analysis has at least one opaque pixel") + assertTrue(analysis.contours.isNotEmpty(), "non-null analysis has at least one contour") + assertTrue(analysis.contours.any { contour -> !contour.isHole }, "at least one non-hole contour") + val bounds = analysis.opaqueBounds + var signedAreaSum = 0L + for (contour in analysis.contours) { + val points = contour.points + assertTrue(points.size >= 6, "contour has at least 3 points, got ${points.size / 2}") + assertTrue(points.size % 2 == 0, "contour point array is flat (x, y) pairs") + val pointCount = points.size / 2 + for (pointIndex in 0 until pointCount) { + val x = points[pointIndex * 2] + val y = points[pointIndex * 2 + 1] + assertTrue( + x >= bounds.left && + x <= bounds.left + bounds.width && + y >= bounds.top && + y <= bounds.top + bounds.height, + "corner ($x, $y) within trimmed-bounds lattice $bounds", + ) + if (exactRings) { + val nextIndex = (pointIndex + 1) % pointCount + val nextX = points[nextIndex * 2] + val nextY = points[nextIndex * 2 + 1] + assertTrue(x != nextX || y != nextY, "consecutive contour points distinct") + assertTrue((x == nextX) != (y == nextY), "exact ring steps are axis-aligned") + } + } + if (exactRings) { + assertTrue( + points[0] != points[(pointCount - 1) * 2] || points[1] != points[(pointCount - 1) * 2 + 1], + "closure is implicit: first point differs from last", + ) + val signedArea = signedAreaTwice(points) + assertEquals(contour.isHole, signedArea < 0L, "hole flag matches winding sign") + signedAreaSum += signedArea + } + } + if (exactRings) { + assertEquals( + analysis.opaquePixelCount.toLong() * 2L, + signedAreaSum, + "signed contour areas sum to the opaque pixel count", + ) + } +} + +/** + * Packs a lattice corner into one Long for set membership checks. + * + * @param Int x Lattice corner x. + * @param Int y Lattice corner y. + * @return Long The packed key. + */ +internal fun pointKey(x: Int, y: Int): Long = (x.toLong() shl 32) or (y.toLong() and 0xFFFFFFFFL) + +/** + * Counts the pixels meeting the threshold by direct scan, independent of the analysis. + * + * @param LayerRaster raster The pixels to scan. + * @param Int alphaThreshold Minimum alpha byte value for a pixel to count. + * @return Int The opaque pixel count. + */ +internal fun countOpaquePixels(raster: LayerRaster, alphaThreshold: Int): Int { + var count = 0 + for (pixelIndex in 0 until raster.width * raster.height) { + if ((raster.rgba[pixelIndex * 4 + 3].toInt() and 0xFF) >= alphaThreshold) { + count++ + } + } + return count +} + +/** + * Asserts every simplified vertex exists in the exact ring — simplification only ever drops + * vertices, never synthesizes coordinates. + * + * @param IntArray exactPoints The exact ring's flat points. + * @param IntArray simplifiedPoints The simplified ring's flat points. + * @param String label Assertion context. + */ +internal fun assertSimplifiedIsVertexSubset(exactPoints: IntArray, simplifiedPoints: IntArray, label: String) { + val exactPointSet = mutableSetOf() + for (pointIndex in 0 until exactPoints.size / 2) { + exactPointSet.add(pointKey(exactPoints[pointIndex * 2], exactPoints[pointIndex * 2 + 1])) + } + for (pointIndex in 0 until simplifiedPoints.size / 2) { + val x = simplifiedPoints[pointIndex * 2] + val y = simplifiedPoints[pointIndex * 2 + 1] + assertTrue( + pointKey(x, y) in exactPointSet, + "$label: simplified vertex ($x, $y) is an exact-ring vertex", + ) + } +} + +/** + * A minimal SourceLayer fake shared by the art-package suites, every member defaulted so each + * test injects only what it exercises (visibility cascade: name/visible/groupPath; alpha + * analysis: raster/opacity/visible). + * + * @param String name Layer name, also used as the stable id. + * @param Boolean visible The eye toggle. + * @param String groupPath Slash-joined enclosing-folder path. + * @param Float opacity Layer opacity, 0.0..1.0. + * @param LayerRaster raster Decoded pixels. + * @param LayerBounds bounds Position on the source canvas. + */ +internal class FakeSourceLayer( + override val name: String = "fake-layer", + override val visible: Boolean = true, + override val groupPath: String = "", + override val opacity: Float = 1f, + override val raster: LayerRaster = LayerRaster(1, 1, ByteArray(4)), + override val bounds: LayerBounds = LayerBounds(0, 0, 1, 1), +) : SourceLayer { + override val id: LayerId = LayerId(name) + override val order: Int = 0 + override val clipped: Boolean = false + override val blend: LayerBlend = LayerBlend.Normal +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaContourTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaContourTest.kt new file mode 100644 index 0000000..e05c075 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/art/AlphaContourTest.kt @@ -0,0 +1,128 @@ +package org.umamo.format.art + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Geometry tests for the boundary tracer, run at contourEpsilon 0 so rings are exact: the + * lattice-corner convention, winding and the hole flag, the 4-connected saddle policy, + * multi-island discovery, and the signed-area-equals-pixel-count invariant. + */ +class AlphaContourTest { + @Test + fun singlePixelTracesItsUnitSquare() { + val analysis = assertNotNull(rasterOfRows("...", ".#.", "...").analyzeAlpha(contourEpsilon = 0f)) + assertEquals(1, analysis.contours.size) + val contour = analysis.contours[0] + // Corners of the unit square [1, 2] x [1, 2], clockwise on screen from the top-left. + assertContentEquals(intArrayOf(1, 1, 2, 1, 2, 2, 1, 2), contour.points) + assertEquals(2L, signedAreaTwice(contour.points)) + assertTrue(!contour.isHole, "single pixel is an outer contour") + assertAnalysisInvariants(analysis, exactRings = true) + } + + @Test + fun fullRectTracesFourCorners() { + val analysis = assertNotNull(rasterOfRows("###", "###").analyzeAlpha(contourEpsilon = 0f)) + assertEquals(1, analysis.contours.size) + // Straight runs emit no interior vertices, so the exact ring is already minimal. + assertContentEquals(intArrayOf(0, 0, 3, 0, 3, 2, 0, 2), analysis.contours[0].points) + assertEquals(12L, signedAreaTwice(analysis.contours[0].points)) + assertAnalysisInvariants(analysis, exactRings = true) + } + + @Test + fun lShapeTracesSixCorners() { + val analysis = assertNotNull(rasterOfRows("#.", "##").analyzeAlpha(contourEpsilon = 0f)) + assertEquals(1, analysis.contours.size) + assertContentEquals(intArrayOf(0, 0, 1, 0, 1, 1, 2, 1, 2, 2, 0, 2), analysis.contours[0].points) + assertEquals(analysis.opaquePixelCount.toLong() * 2L, signedAreaTwice(analysis.contours[0].points)) + assertAnalysisInvariants(analysis, exactRings = true) + } + + @Test + fun donutTracesOuterRingAndFlaggedHole() { + val analysis = assertNotNull(rasterOfRows("###", "#.#", "###").analyzeAlpha(contourEpsilon = 0f)) + assertEquals(8, analysis.opaquePixelCount) + assertEquals(2, analysis.contours.size) + val outer = analysis.contours[0] + val hole = analysis.contours[1] + assertContentEquals(intArrayOf(0, 0, 3, 0, 3, 3, 0, 3), outer.points) + assertEquals(18L, signedAreaTwice(outer.points)) + assertTrue(!outer.isHole, "outer ring is not a hole") + // The hole's north edge sits under the hole (transparent above, opaque below), so its + // walk starts at pixel (1, 2) and winds opposite to the outer ring. + assertContentEquals(intArrayOf(1, 2, 2, 2, 2, 1, 1, 1), hole.points) + assertEquals(-2L, signedAreaTwice(hole.points)) + assertTrue(hole.isHole, "inner ring is flagged as a hole") + assertAnalysisInvariants(analysis, exactRings = true) + } + + @Test + fun diagonalSaddleSeparatesIntoUnitSquares() { + // The 4-connected-foreground saddle policy: diagonal-only contact never merges, so + // the checkerboard is two unit squares, not one corner-crossing zigzag. + val analysis = assertNotNull(rasterOfRows("#.", ".#").analyzeAlpha(contourEpsilon = 0f)) + assertEquals(2, analysis.contours.size) + assertContentEquals(intArrayOf(0, 0, 1, 0, 1, 1, 0, 1), analysis.contours[0].points) + assertContentEquals(intArrayOf(1, 1, 2, 1, 2, 2, 1, 2), analysis.contours[1].points) + assertEquals(2L, signedAreaTwice(analysis.contours[0].points)) + assertEquals(2L, signedAreaTwice(analysis.contours[1].points)) + assertAnalysisInvariants(analysis, exactRings = true) + } + + @Test + fun separateIslandsGetSeparateContoursAndUnionBounds() { + val analysis = assertNotNull(rasterOfRows("#..#", "#..#").analyzeAlpha(contourEpsilon = 0f)) + assertEquals(2, analysis.contours.size) + assertEquals(LayerBounds(left = 0, top = 0, width = 4, height = 2), analysis.opaqueBounds) + assertEquals(4, analysis.opaquePixelCount) + assertAnalysisInvariants(analysis, exactRings = true) + } + + @Test + fun tracingIsDeterministic() { + val raster = rasterOfRows(".##.", "#..#", ".##.") + val first = assertNotNull(raster.analyzeAlpha(contourEpsilon = 0f)) + val second = assertNotNull(raster.analyzeAlpha(contourEpsilon = 0f)) + assertEquals(first.contours.size, second.contours.size) + for (contourIndex in first.contours.indices) { + assertContentEquals(first.contours[contourIndex].points, second.contours[contourIndex].points) + } + } + + @Test + fun complexSceneSatisfiesAllInvariants() { + // Donut, vertical sliver, second donut, and a checkerboard row in one raster: the + // invariant sweep is the real assertion; the shape mix exists to exercise saddles, + // holes, slivers, and multi-island discovery together. + val raster = + rasterOfRows( + ".##..#......", + "####.#..###.", + "#..#.#..#.#.", + "####.#..###.", + ".....#......", + "#.#.#.#.#.#.", + ) + val exact = assertNotNull(raster.analyzeAlpha(contourEpsilon = 0f)) + assertAnalysisInvariants(exact, exactRings = true) + assertNoOpaquePixelOutside(raster, exact.opaqueBounds, DEFAULT_ALPHA_THRESHOLD) + assertTrue(exact.contours.count { contour -> contour.isHole } == 2, "both donut holes found") + + // The simplified run keeps the structural invariants and only ever drops vertices. + val simplified = assertNotNull(raster.analyzeAlpha()) + assertAnalysisInvariants(simplified, exactRings = false) + assertEquals(exact.contours.size, simplified.contours.size) + for (contourIndex in exact.contours.indices) { + assertSimplifiedIsVertexSubset( + exact.contours[contourIndex].points, + simplified.contours[contourIndex].points, + "complex scene contour $contourIndex", + ) + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/art/ContourSimplifyTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/art/ContourSimplifyTest.kt new file mode 100644 index 0000000..b0887d2 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/art/ContourSimplifyTest.kt @@ -0,0 +1,140 @@ +package org.umamo.format.art + +import kotlin.math.sqrt +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Unit tests for the closed-ring Douglas-Peucker simplifier: epsilon-zero identity and + * collinear collapse, the staircase collapse the 1.0 px default exists for, the under-3-points + * fallback, the within-epsilon deviation guarantee, and determinism. + */ +class ContourSimplifyTest { + @Test + fun epsilonZeroKeepsAnExactRing() { + // Traced rings have no collinear vertices (turn-only emission), so nothing can drop. + val ring = intArrayOf(0, 0, 1, 0, 1, 1, 2, 1, 2, 2, 0, 2) + assertContentEquals(ring, simplifyClosedRing(ring, 0f)) + } + + @Test + fun rectangleSurvivesAnyEpsilon() { + val rectangle = intArrayOf(0, 0, 100, 0, 100, 100, 0, 100) + assertContentEquals(rectangle, simplifyClosedRing(rectangle, 5f)) + } + + @Test + fun collinearVerticesDropAtEpsilonZero() { + // Hand-built ring with an injected collinear midpoint — the tracer never emits one. + val ring = intArrayOf(0, 0, 5, 0, 10, 0, 10, 10, 0, 10) + assertContentEquals(intArrayOf(0, 0, 10, 0, 10, 10, 0, 10), simplifyClosedRing(ring, 0f)) + } + + @Test + fun staircaseCollapsesAtTheDefaultEpsilon() { + // A unit staircase from (0, 0) to (10, 10) deviates at most sqrt(2)/2 from the true + // diagonal, so the 1.0 px default collapses it to a single segment. + val ringValues = mutableListOf(0, 0) + for (stepIndex in 1..10) { + ringValues.add(stepIndex) + ringValues.add(stepIndex - 1) + ringValues.add(stepIndex) + ringValues.add(stepIndex) + } + ringValues.add(0) + ringValues.add(10) + val ring = ringValues.toIntArray() + + val simplified = simplifyClosedRing(ring, DEFAULT_CONTOUR_EPSILON) + assertContentEquals(intArrayOf(0, 0, 10, 10, 0, 10), simplified) + assertMaxDeviationWithin(ring, simplified, DEFAULT_CONTOUR_EPSILON.toDouble()) + } + + @Test + fun collapseBelowThreePointsFallsBackToTheInput() { + // A 1xN sliver rectangle at the default epsilon would keep only its two anchors. + val sliver = intArrayOf(0, 0, 5, 0, 5, 1, 0, 1) + assertContentEquals(sliver, simplifyClosedRing(sliver, DEFAULT_CONTOUR_EPSILON)) + } + + @Test + fun triangleIsAlreadyMinimal() { + val triangle = intArrayOf(0, 0, 8, 0, 0, 8) + assertContentEquals(triangle, simplifyClosedRing(triangle, 100f)) + } + + @Test + fun outputIsDeterministic() { + val ring = intArrayOf(0, 0, 3, 0, 5, 1, 8, 0, 8, 8, 4, 7, 0, 8) + val first = simplifyClosedRing(ring, 1.5f) + val second = simplifyClosedRing(ring, 1.5f) + assertContentEquals(first, second) + } + + /** + * Asserts the Douglas-Peucker deviation guarantee numerically: every input vertex lies + * within epsilon of the simplified ring (its nearest segment, closure included). + * + * @param IntArray original The input ring. + * @param IntArray simplified The simplified ring. + * @param Double epsilon The tolerance the simplification ran with. + */ + private fun assertMaxDeviationWithin(original: IntArray, simplified: IntArray, epsilon: Double) { + val originalCount = original.size / 2 + for (pointIndex in 0 until originalCount) { + val distance = + distanceToRing( + original[pointIndex * 2].toDouble(), + original[pointIndex * 2 + 1].toDouble(), + simplified, + ) + assertTrue( + distance <= epsilon + 1e-9, + "dropped vertex index $pointIndex deviates $distance > $epsilon", + ) + } + assertEquals(0, simplified.size % 2, "simplified ring stays flat pairs") + } + + /** + * Distance from a point to the nearest segment of a closed flat-point ring. + * + * @param Double pointX The point's x. + * @param Double pointY The point's y. + * @param IntArray ring The ring; the last point connects to the first. + * @return Double The minimum distance. + */ + private fun distanceToRing(pointX: Double, pointY: Double, ring: IntArray): Double { + val pointCount = ring.size / 2 + var best = Double.MAX_VALUE + for (pointIndex in 0 until pointCount) { + val nextIndex = (pointIndex + 1) % pointCount + val startX = ring[pointIndex * 2].toDouble() + val startY = ring[pointIndex * 2 + 1].toDouble() + val endX = ring[nextIndex * 2].toDouble() + val endY = ring[nextIndex * 2 + 1].toDouble() + val segmentDeltaX = endX - startX + val segmentDeltaY = endY - startY + val lengthSquared = segmentDeltaX * segmentDeltaX + segmentDeltaY * segmentDeltaY + val projection = + if (lengthSquared == 0.0) { + 0.0 + } else { + (((pointX - startX) * segmentDeltaX + (pointY - startY) * segmentDeltaY) / lengthSquared) + .coerceIn(0.0, 1.0) + } + val nearestX = startX + projection * segmentDeltaX + val nearestY = startY + projection * segmentDeltaY + val distance = + sqrt( + (pointX - nearestX) * (pointX - nearestX) + (pointY - nearestY) * (pointY - nearestY), + ) + if (distance < best) { + best = distance + } + } + return best + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/art/LayerBoundsTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/art/LayerBoundsTest.kt new file mode 100644 index 0000000..80343e3 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/art/LayerBoundsTest.kt @@ -0,0 +1,20 @@ +package org.umamo.format.art + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The overlap measure: same, nested, partial, disjoint, and empty rectangles. */ +class LayerBoundsTest { + @Test + fun intersectionOverUnionCoversEveryArrangement() { + val square = LayerBounds(10, 10, 10, 10) + assertEquals(1f, square.intersectionOverUnion(square)) + assertEquals(0.25f, square.intersectionOverUnion(LayerBounds(10, 10, 5, 5)), "a nested quarter") + assertEquals(0.25f, LayerBounds(10, 10, 5, 5).intersectionOverUnion(square), "symmetric") + // Half overlap: 50 shared of 150 covered. + assertEquals(50f / 150f, square.intersectionOverUnion(LayerBounds(15, 10, 10, 10)), 1e-6f) + assertEquals(0f, square.intersectionOverUnion(LayerBounds(30, 30, 10, 10)), "disjoint") + assertEquals(0f, square.intersectionOverUnion(LayerBounds(20, 10, 10, 10)), "touching edges do not overlap") + assertEquals(0f, square.intersectionOverUnion(LayerBounds(10, 10, 0, 5)), "an empty rectangle") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/art/SourceArtVisibilityTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/art/SourceArtVisibilityTest.kt new file mode 100644 index 0000000..902938c --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/art/SourceArtVisibilityTest.kt @@ -0,0 +1,87 @@ +package org.umamo.format.art + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Unit tests for the format-agnostic visibility cascade ([SourceArt.isEffectivelyVisible]) - the + * single rule every source-art renderer shares for deciding whether a layer is drawn. These exercise + * the cascade purely from the neutral model, so they need no corpus file and run on every platform. + */ +class SourceArtVisibilityTest { + /** A minimal SourceGroup carrying only path + visibility. */ + private class FakeGroup( + override val path: String, + override val visible: Boolean, + ) : SourceGroup { + override val name: String = path.substringAfterLast('/') + override val opacity: Float = 1f + override val clipped: Boolean = false + override val blend: LayerBlend = LayerBlend.Normal + override val passThrough: Boolean = false + } + + /** A SourceArt over the given layers and groups. */ + private class FakeArt( + override val layers: List, + override val groups: List, + ) : SourceArt { + override val widthPx: Int = 1 + override val heightPx: Int = 1 + } + + @Test + fun visibleLayerWithNoGroupsIsShown() { + val layer = FakeSourceLayer(name = "leaf", visible = true, groupPath = "") + val art = FakeArt(layers = listOf(layer), groups = emptyList()) + assertTrue(art.isEffectivelyVisible(layer)) + } + + @Test + fun hiddenLayerIsNotShownRegardlessOfGroups() { + val layer = FakeSourceLayer(name = "leaf", visible = false, groupPath = "Folder") + val art = FakeArt(layers = listOf(layer), groups = listOf(FakeGroup("Folder", visible = true))) + assertFalse(art.isEffectivelyVisible(layer)) + } + + @Test + fun layerInsideHiddenFolderIsNotShown() { + val layer = FakeSourceLayer(name = "leaf", visible = true, groupPath = "Folder") + val art = FakeArt(layers = listOf(layer), groups = listOf(FakeGroup("Folder", visible = false))) + assertFalse(art.isEffectivelyVisible(layer)) + } + + @Test + fun layerIsHiddenWhenAnyAncestorFolderIsHidden() { + // The immediate folder is visible, but its grandparent is hidden - the cascade must walk up. + val layer = FakeSourceLayer(name = "leaf", visible = true, groupPath = "A/B/C") + val art = + FakeArt( + layers = listOf(layer), + groups = + listOf( + FakeGroup("A", visible = false), + FakeGroup("A/B", visible = true), + FakeGroup("A/B/C", visible = true), + ), + ) + assertFalse(art.isEffectivelyVisible(layer)) + } + + @Test + fun layerInsideFullyVisibleNestedFoldersIsShown() { + val layer = FakeSourceLayer(name = "leaf", visible = true, groupPath = "A/B/C") + val art = + FakeArt( + layers = listOf(layer), + groups = + listOf( + FakeGroup("A", visible = true), + FakeGroup("A/B", visible = true), + FakeGroup("A/B/C", visible = true), + ), + ) + assertTrue(art.isEffectivelyVisible(layer)) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPackTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPackTest.kt new file mode 100644 index 0000000..1600afb --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPackTest.kt @@ -0,0 +1,603 @@ +package org.umamo.format.atlas + +import org.umamo.format.art.analyzeAlpha +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Covers the packer end to end: trimming, page composition, gutters and extrusion, page sizing, the + * placement/skip partition, fixed tiles, and determinism. The bin-packing geometry alone is + * [RectPackerTest]. + */ +class AtlasPackTest { + /** + * A fixed tile: [opaquePackItem]'s pixels kept at a place on the page. + * + * @param String key The item key. + * @param Int width The tile width. + * @param Int height The tile height. + * @param Int pageIndex The page it stays on. + * @param FloatArray tileToPage The affine it stays at. + * @return AtlasPackItem The fixed item. + */ + private fun fixedPackItem(key: String, width: Int, height: Int, pageIndex: Int, tileToPage: FloatArray): AtlasPackItem = + AtlasPackItem(key, width, height, opaquePackItem(key, width, height).rgba, reserve = null, fixed = AtlasPackFixed(pageIndex, tileToPage)) + + /** + * The page-space bounding box of a tile through an affine, written independently of the packer's. + * + * @param FloatArray affine The tile-to-page affine. + * @param Int width The tile width. + * @param Int height The tile height. + * @return FloatArray (left, top, right, bottom). + */ + private fun boxOf(affine: FloatArray, width: Int, height: Int): FloatArray { + val xs = FloatArray(4) + val ys = FloatArray(4) + var cornerIndex = 0 + for (cornerX in listOf(0f, width.toFloat())) { + for (cornerY in listOf(0f, height.toFloat())) { + xs[cornerIndex] = affine[0] * cornerX + affine[1] * cornerY + affine[2] + ys[cornerIndex] = affine[3] * cornerX + affine[4] * cornerY + affine[5] + cornerIndex++ + } + } + return floatArrayOf(xs.min(), ys.min(), xs.max(), ys.max()) + } + + /** + * Asserts every packed placement's trim stays at least [gutter] away from [box] on [pageIndex]. + * + * @param AtlasPackResult result The pack. + * @param Int pageIndex The page the box is on. + * @param FloatArray box The box (left, top, right, bottom) the free tiles must keep clear. + * @param Int gutter The clearance. + */ + private fun assertFreeTilesClearOf(result: AtlasPackResult, pageIndex: Int, box: FloatArray, gutter: Int) { + for (placement in result.placements.filter { placement -> placement.pageIndex == pageIndex }) { + val separated = + placement.pageX + placement.pageWidth + gutter <= box[0] || + box[2] + gutter <= placement.pageX || + placement.pageY + placement.pageHeight + gutter <= box[1] || + box[3] + gutter <= placement.pageY + assertTrue(separated, "'${placement.key}' at (${placement.pageX}, ${placement.pageY}) comes within $gutter px of the fixed tile") + } + } + + @Test + fun aFixedTileStaysPutAndTheFreeTilesPackAroundIt() { + val kept = fixedPackItem("kept", 6, 6, pageIndex = 0, tileToPage = floatArrayOf(1f, 0f, 10f, 0f, 1f, 10f)) + val items = listOf(kept) + (0 until 5).map { tileIndex -> opaquePackItem("free$tileIndex", 6, 6) } + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 32, gutter = 2, extrude = 1)) + + val fixed = result.fixed.single() + assertEquals("kept", fixed.key) + assertEquals(0, fixed.pageIndex) + assertEquals(listOf(0, 0, 6, 6), listOf(fixed.trimLeft, fixed.trimTop, fixed.trimWidth, fixed.trimHeight)) + assertEquals(5, result.placements.size, "every free tile packs") + assertTrue(result.skipped.isEmpty()) + assertEquals( + items.map { item -> item.key }.sorted(), + (result.placements.map { placement -> placement.key } + result.fixed.map { kept -> kept.key } + result.skipped.map { skip -> skip.key }).sorted(), + "placements, fixed, and skipped partition the input", + ) + for (tileY in 0 until 6) { + for (tileX in 0 until 6) { + assertEquals(itemPixel(kept, tileX, tileY), pagePixel(result.pages[0], 10 + tileX, 10 + tileY), "kept pixel ($tileX, $tileY) sits at its affine spot verbatim") + } + } + assertTilesRoundTripByteExact(items, result) + assertFreeTilesClearOf(result, 0, floatArrayOf(10f, 10f, 16f, 16f), gutter = 2) + assertTrue(result.pageOccupancy(0) > 0f) + } + + @Test + fun aFixedRotatedTileKeepsTheFreeTilesClearOfItsBox() { + // A 30 degree turn at 0.75 scale about the tile origin, moved to (20, 6): the box the packer must + // keep clear is the box of the turned corners, not the upright rect. + val radians = 30.0 * kotlin.math.PI / 180.0 + val cosine = (kotlin.math.cos(radians) * 0.75).toFloat() + val sine = (kotlin.math.sin(radians) * 0.75).toFloat() + val affine = floatArrayOf(cosine, -sine, 20f, sine, cosine, 6f) + val kept = fixedPackItem("kept", 8, 8, pageIndex = 0, tileToPage = affine) + val items = listOf(kept) + (0 until 6).map { tileIndex -> opaquePackItem("free$tileIndex", 5, 5) } + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64, gutter = 2, extrude = 2)) + + assertEquals("kept", result.fixed.single().key) + assertEquals(6, result.placements.size) + val box = boxOf(affine, 8, 8) + assertFreeTilesClearOf(result, 0, box, gutter = 2) + val centerX = (affine[0] * 4f + affine[1] * 4f + affine[2]).toInt() + val centerY = (affine[3] * 4f + affine[4] * 4f + affine[5]).toInt() + assertEquals(0xFF, pagePixel(result.pages[0], centerX, centerY) and 0xFF, "the turned tile's center is painted opaque") + assertNoTileOverlap(result, gutter = 2) + } + + @Test + fun aFixedTilePastTheLargestPageIsReportedNotMoved() { + val kept = fixedPackItem("kept", 6, 6, pageIndex = 0, tileToPage = floatArrayOf(1f, 0f, 200f, 0f, 1f, 200f)) + val items = listOf(kept, opaquePackItem("free", 6, 6)) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64)) + + assertEquals(listOf(AtlasPackSkip("kept", AtlasPackSkipReason.FixedOutsidePage)), result.skipped) + assertTrue(result.fixed.isEmpty()) + assertEquals(listOf("free"), result.placements.map { placement -> placement.key }) + } + + @Test + fun shrinkingKeepsAPageLargeEnoughForItsFixedTile() { + val free = opaquePackItem("free", 4, 4) + val kept = fixedPackItem("kept", 4, 4, pageIndex = 0, tileToPage = floatArrayOf(1f, 0f, 40f, 0f, 1f, 40f)) + + val alone = packAtlas(listOf(free), AtlasPackOptions(maxPageSize = 256)) + val withKept = packAtlas(listOf(free, kept), AtlasPackOptions(maxPageSize = 256)) + + assertEquals(8, alone.pages.single().width, "a lone 4x4 with its gutter crops to an 8 page") + // The kept tile's gutter footprint reaches 46; the page rounds up to 64 and the free tile packs + // on that page rather than opening another. + assertEquals(1, withKept.pages.size) + assertEquals(64, withKept.pages.single().width) + assertEquals(64, withKept.pages.single().height) + assertTilesRoundTripByteExact(listOf(free), withKept) + } + + @Test + fun aFixedTileOnALaterPageKeepsItsIndex() { + val kept = fixedPackItem("kept", 4, 4, pageIndex = 1, tileToPage = floatArrayOf(1f, 0f, 2f, 0f, 1f, 2f)) + val items = listOf(opaquePackItem("free", 4, 4), kept) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64)) + + assertEquals(2, result.pages.size, "the fixed tile's page exists") + assertEquals(1, result.fixed.single().pageIndex) + assertEquals(0, result.placements.single().pageIndex, "the free tile takes the first page") + assertEquals(itemPixel(kept, 0, 0), pagePixel(result.pages[1], 2, 2)) + } + + @Test + fun aFixedTileWithNothingOpaqueIsSkippedLikeAnyOther() { + val empty = AtlasPackItem("empty", 3, 3, ByteArray(3 * 3 * 4), fixed = AtlasPackFixed(0, floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f))) + + val result = packAtlas(listOf(empty, opaquePackItem("free", 4, 4)), AtlasPackOptions(maxPageSize = 32)) + + assertEquals(listOf(AtlasPackSkip("empty", AtlasPackSkipReason.NoOpaquePixels)), result.skipped) + assertTrue(result.fixed.isEmpty()) + } + + @Test + fun tilesAreTrimmedToTheirOpaqueBounds() { + val item = + packItemOfRows( + "a", + ".....", + "..##.", + "..##.", + ".....", + ) + + val result = packAtlas(listOf(item)) + + val placement = result.placements.single() + val expected = assertNotNull(analyzeAlpha(item.width, item.height, item.rgba)) + assertEquals(expected.opaqueBounds.left, placement.trimLeft) + assertEquals(expected.opaqueBounds.top, placement.trimTop) + assertEquals(expected.opaqueBounds.width, placement.trimWidth) + assertEquals(expected.opaqueBounds.height, placement.trimHeight) + } + + @Test + fun everyTileReadsBackOutOfItsPageByteForByte() { + val items = + listOf( + opaquePackItem("wide", 12, 4), + opaquePackItem("tall", 4, 12), + opaquePackItem("square", 7, 7), + packItemOfRows("holed", "###", "#.#", "###"), + ) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64)) + + assertEquals(items.size, result.placements.size) + assertTilesRoundTripByteExact(items, result) + assertNoTileOverlap(result, gutter = 2) + } + + @Test + fun aQuarterTurnedTileReadsBackOutOfItsPageByteForByte() { + // Sized so the second tile only fits the strip the first leaves behind when turned. + val items = listOf(opaquePackItem("a", 16, 8), opaquePackItem("b", 8, 16)) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 16, gutter = 0, extrude = 0, allowRotation = true)) + + assertEquals(1, result.pages.size, "both tiles must share one page") + assertEquals(1, result.placements.count { placement -> placement.quarterTurns == 1 }) + assertTilesRoundTripByteExact(items, result) + } + + @Test + fun composingFromPlacementsAloneReproducesThePackedPages() { + val items = + listOf( + opaquePackItem("wide", 12, 4), + opaquePackItem("tall", 4, 12), + opaquePackItem("square", 7, 7), + packItemOfRows("holed", "###", "#.#", "###"), + ) + val options = AtlasPackOptions(maxPageSize = 64) + + val result = packAtlas(items, options) + val composed = + composeAtlasPages( + pageWidths = IntArray(result.pages.size) { pageIndex -> result.pages[pageIndex].width }, + pageHeights = IntArray(result.pages.size) { pageIndex -> result.pages[pageIndex].height }, + items = items, + placements = result.placements, + extrude = options.extrude, + ) + + assertEquals(result.pages.size, composed.size) + for (pageIndex in result.pages.indices) { + assertContentEquals(result.pages[pageIndex].rgba, composed[pageIndex].rgba, "page $pageIndex pixels") + } + } + + @Test + fun composingFromPlacementsReproducesAQuarterTurnedPage() { + val items = listOf(opaquePackItem("a", 16, 8), opaquePackItem("b", 8, 16)) + val options = AtlasPackOptions(maxPageSize = 16, gutter = 0, extrude = 0, allowRotation = true) + + val result = packAtlas(items, options) + val composed = + composeAtlasPages( + pageWidths = intArrayOf(result.pages.single().width), + pageHeights = intArrayOf(result.pages.single().height), + items = items, + placements = result.placements, + extrude = options.extrude, + ) + + assertEquals(1, result.placements.count { placement -> placement.quarterTurns == 1 }) + assertContentEquals(result.pages.single().rgba, composed.single().rgba) + } + + @Test + fun aReserveSpacesNeighborsWhileThePlacementStaysOnTheTrim() { + // Two 4x4 opaque tiles; the first reserves a mesh reach of 20px on every side. Without the + // reserve they pack shoulder to shoulder (gutter apart); with it, nothing may sit inside the + // first tile's reserved rect - which extends 20px past its trim in page space. + val reach = 20 + val items = + listOf( + AtlasPackItem( + "reaching", + 4, + 4, + opaquePackItem("reaching", 4, 4).rgba, + AtlasPackReserve(-reach, -reach, 4 + reach, 4 + reach), + ), + opaquePackItem("plain", 4, 4), + ) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 256)) + + assertEquals(2, result.placements.size) + assertTilesRoundTripByteExact(items, result) + val reaching = result.placements.first { placement -> placement.key == "reaching" } + val plain = result.placements.first { placement -> placement.key == "plain" } + // The placement anchors the TRIM, so the reserved margin lies around it on the page. + val reservedLeft = reaching.pageX - reach + val reservedTop = reaching.pageY - reach + val reservedRight = reaching.pageX + reaching.trimWidth + reach + val reservedBottom = reaching.pageY + reaching.trimHeight + reach + assertTrue(reservedLeft >= 0 && reservedTop >= 0, "the reserve stays on the page") + val plainRight = plain.pageX + plain.trimWidth + val plainBottom = plain.pageY + plain.trimHeight + val outside = + plain.pageX >= reservedRight || + plainRight <= reservedLeft || + plain.pageY >= reservedBottom || + plainBottom <= reservedTop + assertTrue( + outside, + "the neighbor must sit outside the reserved rect: plain at (${plain.pageX},${plain.pageY})," + + " reserve $reservedLeft..$reservedRight x $reservedTop..$reservedBottom", + ) + } + + @Test + fun aReserveLargerThanThePageSkipsTheTile() { + val item = + AtlasPackItem("vast", 4, 4, opaquePackItem("vast", 4, 4).rgba, AtlasPackReserve(-300, -300, 300, 300)) + + val result = packAtlas(listOf(item), AtlasPackOptions(maxPageSize = 128)) + + assertEquals(AtlasPackSkipReason.LargerThanPage, result.skipped.single().reason) + } + + @Test + fun aReserveTurnsWithItsTile() { + // A 19x8 tile packs first and leaves a 19x11 strip; the 8x12 tile with a 2 px reserve to its RIGHT + // (a 10x12 reservation) fits that strip only turned. The turn sends the reservation's right-hand + // band ABOVE the placed trim, so the trim lands two rows below the strip's top, not on it. + val wide = opaquePackItem("wide", 19, 8) + val reaching = AtlasPackItem("reaching", 8, 12, opaquePackItem("reaching", 8, 12).rgba, AtlasPackReserve(0, 0, 10, 12)) + val items = listOf(wide, reaching) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 19, gutter = 0, extrude = 0, allowRotation = true)) + + assertEquals(1, result.pages.size, "both tiles share one page") + val turned = result.placements.first { placement -> placement.key == "reaching" } + val upright = result.placements.first { placement -> placement.key == "wide" } + assertEquals(0, upright.quarterTurns) + assertEquals(1, turned.quarterTurns, "the reaching tile only fits turned") + assertEquals(0, turned.pageX) + assertEquals(upright.pageY + upright.trimHeight + 2, turned.pageY, "the turned reservation's band sits above the trim") + assertTilesRoundTripByteExact(items, result) + assertNoTileOverlap(result, gutter = 0) + } + + @Test + fun composingRefusesAPlacementWhoseExtrusionLeavesThePage() { + val item = opaquePackItem("a", 4, 4) + val placement = AtlasPackPlacement("a", 0, 1, 1, 0, 0, 4, 4, quarterTurns = 0) + + assertFailsWith { + composeAtlasPages(intArrayOf(16), intArrayOf(16), listOf(item), listOf(placement), extrude = 2) + } + } + + @Test + fun aTurnedPlacementSwapsItsOnPageExtent() { + val placement = AtlasPackPlacement("a", 0, 0, 0, 0, 0, 12, 5, quarterTurns = 1) + + assertEquals(5, placement.pageWidth) + assertEquals(12, placement.pageHeight) + } + + @Test + fun extrusionBleedsTheEdgeColorAtZeroAlphaAndAddsNoCoverage() { + val item = opaquePackItem("a", 3, 2) + + val result = packAtlas(listOf(item), AtlasPackOptions(maxPageSize = 64, gutter = 2, extrude = 2)) + + val placement = result.placements.single() + val page = result.pages.single() + for (rowOffset in -2 until placement.trimHeight + 2) { + for (columnOffset in -2 until placement.trimWidth + 2) { + val clampedColumn = columnOffset.coerceIn(0, placement.trimWidth - 1) + val clampedRow = rowOffset.coerceIn(0, placement.trimHeight - 1) + val edge = itemPixel(item, placement.trimLeft + clampedColumn, placement.trimTop + clampedRow) + val inside = columnOffset == clampedColumn && rowOffset == clampedRow + // The tile's own pixels verbatim; the band carries the nearest edge's color with no alpha, so the + // page past the art stays as transparent as the layer is there. + assertEquals( + if (inside) edge else edge and 0xFF.inv(), + pagePixel(page, placement.pageX + columnOffset, placement.pageY + rowOffset), + if (inside) "tile pixel ($columnOffset, $rowOffset)" else "bled pixel ($columnOffset, $rowOffset)", + ) + } + } + } + + @Test + fun withoutExtrusionEveryPixelOutsideATileStaysTransparent() { + val items = listOf(opaquePackItem("a", 5, 3), opaquePackItem("b", 3, 5)) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64, gutter = 2, extrude = 0)) + + for ((pageIndex, page) in result.pages.withIndex()) { + val covered = HashSet() + for (placement in result.placements.filter { placement -> placement.pageIndex == pageIndex }) { + for (tileY in 0 until placement.pageHeight) { + for (tileX in 0 until placement.pageWidth) { + covered.add((placement.pageY + tileY) * page.width + placement.pageX + tileX) + } + } + } + for (pixelIndex in 0 until page.width * page.height) { + if (pixelIndex in covered) { + continue + } + assertEquals(0, pagePixel(page, pixelIndex % page.width, pixelIndex / page.width), "pixel $pixelIndex") + } + } + } + + @Test + fun placementsAndSkipsPartitionTheInputExactly() { + val items = + listOf( + opaquePackItem("packed", 4, 4), + packItemOfRows("empty", "...", "..."), + opaquePackItem("huge", 200, 4), + packItemOfRows("sliver", ".#."), + ) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 32)) + + assertEquals( + items.map { item -> item.key }.sorted(), + (result.placements.map { placement -> placement.key } + result.skipped.map { skip -> skip.key }).sorted(), + ) + assertEquals( + listOf( + AtlasPackSkip("empty", AtlasPackSkipReason.NoOpaquePixels), + AtlasPackSkip("huge", AtlasPackSkipReason.LargerThanPage), + ), + result.skipped, + ) + assertEquals(listOf("packed", "sliver"), result.placements.map { placement -> placement.key }) + } + + @Test + fun aTileBelowTheMinimumCoverageIsReportedRatherThanPacked() { + val items = listOf(opaquePackItem("solid", 4, 4), packItemOfRows("speck", ".#.", "...")) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 32, minimumOpaquePixels = 2)) + + assertEquals(listOf(AtlasPackSkip("speck", AtlasPackSkipReason.BelowMinimumCoverage)), result.skipped) + assertEquals(listOf("solid"), result.placements.map { placement -> placement.key }) + } + + @Test + fun skipsAndPlacementsComeBackInTheCallerSInputOrder() { + val items = + listOf( + packItemOfRows("first-empty", ".."), + opaquePackItem("zeta", 3, 3), + packItemOfRows("second-empty", ".."), + opaquePackItem("alpha", 9, 9), + ) + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64)) + + assertEquals(listOf("zeta", "alpha"), result.placements.map { placement -> placement.key }) + assertEquals(listOf("first-empty", "second-empty"), result.skipped.map { skip -> skip.key }) + } + + @Test + fun pagesShrinkToWhatTheyUseAndRoundUpToAPowerOfTwo() { + val result = packAtlas(listOf(opaquePackItem("a", 2, 2)), AtlasPackOptions(maxPageSize = 4096, gutter = 2)) + + // A 2x2 tile with a 2 px gutter on every side uses 6x6, which squares and rounds to 8. + val page = result.pages.single() + assertEquals(8, page.width) + assertEquals(8, page.height) + assertEquals(2, result.placements.single().pageX) + assertEquals(2, result.placements.single().pageY) + } + + @Test + fun shrinkingCanBeTurnedOffToKeepFullSizePages() { + val result = + packAtlas( + listOf(opaquePackItem("a", 2, 2)), + AtlasPackOptions(maxPageSize = 128, gutter = 2, shrinkPages = false), + ) + + assertEquals(128, result.pages.single().width) + assertEquals(128, result.pages.single().height) + } + + @Test + fun nonSquarePagesKeepTheirOwnAxes() { + val result = + packAtlas( + listOf(opaquePackItem("a", 30, 2)), + AtlasPackOptions(maxPageSize = 4096, gutter = 1, extrude = 1, squarePages = false), + ) + + val page = result.pages.single() + assertEquals(32, page.width) + assertEquals(4, page.height) + } + + @Test + fun occupancyMeasuresPackedTilePixelsAgainstThePage() { + val result = + packAtlas( + listOf(opaquePackItem("a", 4, 4)), + AtlasPackOptions(maxPageSize = 64, gutter = 0, extrude = 0), + ) + + // A 4x4 tile alone on a 4x4 page covers all of it. + assertEquals(4, result.pages.single().width) + assertEquals(1.0f, result.pageOccupancy(0)) + } + + @Test + fun theCallerSItemOrderDoesNotChangeThePacking() { + val items = + listOf( + opaquePackItem("a", 13, 7), + opaquePackItem("b", 7, 13), + opaquePackItem("c", 11, 11), + opaquePackItem("d", 5, 21), + opaquePackItem("e", 21, 5), + opaquePackItem("f", 3, 3), + ) + + val forward = packAtlas(items, AtlasPackOptions(maxPageSize = 32)) + val reversed = packAtlas(items.reversed(), AtlasPackOptions(maxPageSize = 32)) + + assertContentEquals( + forward.placements.sortedBy { placement -> placement.key }, + reversed.placements.sortedBy { placement -> placement.key }, + ) + assertEquals(forward.pages.size, reversed.pages.size) + for (pageIndex in forward.pages.indices) { + assertContentEquals(forward.pages[pageIndex].rgba, reversed.pages[pageIndex].rgba, "page $pageIndex pixels") + } + } + + @Test + fun packingSpillsToFurtherPagesAndKeepsEveryTileReadable() { + val items = (0 until 6).map { itemIndex -> opaquePackItem("tile$itemIndex", 20, 20) } + + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 32, gutter = 2, extrude = 2)) + + assertEquals(6, result.pages.size, "a 32 page holds one 24x24 footprint") + assertTrue(result.skipped.isEmpty()) + assertTilesRoundTripByteExact(items, result) + assertNoTileOverlap(result, gutter = 2) + } + + @Test + fun anEmptyItemListPacksToNothing() { + val result = packAtlas(emptyList()) + + assertTrue(result.pages.isEmpty()) + assertTrue(result.placements.isEmpty()) + assertTrue(result.skipped.isEmpty()) + } + + @Test + fun anExtrusionWiderThanTheGutterIsRejected() { + val failure = + assertFailsWith { + packAtlas(listOf(opaquePackItem("a", 2, 2)), AtlasPackOptions(gutter = 1, extrude = 2)) + } + + assertTrue(failure.message.orEmpty().contains("extrude"), "the message must name the offending option") + } + + @Test + fun duplicateKeysAreRejectedBecauseTheyMakeTheOrderAmbiguous() { + assertFailsWith { + packAtlas(listOf(opaquePackItem("a", 2, 2), opaquePackItem("a", 3, 3))) + } + } + + @Test + fun anItemWhosePixelsDoNotMatchItsDimensionsIsRejected() { + assertFailsWith { + AtlasPackItem("a", 4, 4, ByteArray(4 * 4 * 3)) + } + } + + /** + * A fixed tile flush against the page edge keeps its place: only its ART decides whether it fits, + * and a reserve or gutter spilling past the edge is clamped rather than refused. A free pack puts + * tiles exactly there, and a mesh reach re-measured from page coordinates can round a pixel wider + * than the reach it was packed with - refusing that would pack a document's own art out. + */ + @Test + fun aFixedTileWhoseGutterSpillsPastTheEdgeIsKept() { + // 6x6 art at (58, 58) on a 64 page: the art ends at 64 exactly; the gutter would end at 66. + val kept = fixedPackItem("kept", 6, 6, pageIndex = 0, tileToPage = floatArrayOf(1f, 0f, 58f, 0f, 1f, 58f)) + val result = packAtlas(listOf(kept), AtlasPackOptions(maxPageSize = 64, gutter = 2, extrude = 2)) + assertTrue(result.skipped.isEmpty(), "a spilled gutter does not refuse: ${result.skipped}") + assertEquals("kept", result.fixed.single().key) + + // One pixel further and the art itself leaves the page: that is still a refusal. + val over = fixedPackItem("over", 6, 6, pageIndex = 0, tileToPage = floatArrayOf(1f, 0f, 59f, 0f, 1f, 59f)) + assertEquals(listOf(AtlasPackSkip("over", AtlasPackSkipReason.FixedOutsidePage)), packAtlas(listOf(over), AtlasPackOptions(maxPageSize = 64)).skipped) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPackTestSupport.kt b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPackTestSupport.kt new file mode 100644 index 0000000..ef1676c --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPackTestSupport.kt @@ -0,0 +1,176 @@ +package org.umamo.format.atlas + +import org.umamo.format.raster.RasterImage +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/* + * Shared fixtures and assertions for the atlas packer suites. + * + * Deliberately not reusing the alpha-analysis support: its rasters fill every pixel with the same + * RGB, which is right for coverage tests and useless here - a transposed or mirrored blit would + * compare equal against itself. These fixtures make every pixel distinguishable instead. + */ + +/** + * Builds a pack item from rows of character art: '#' is alpha 255, '.' is alpha 0, and a decimal + * digit is that literal alpha value. + * + * RGB carries the pixel's own coordinates plus a per-item tint, so a blit that transposes, mirrors, + * or reads the wrong row stride produces mismatching bytes rather than accidentally-equal ones. + * + * @param String key The item key; its first character tints the blue channel. + * @param String rows One string per pixel row, top row first, all the same length. + * @return AtlasPackItem The synthetic tile. + */ +internal fun packItemOfRows(key: String, vararg rows: String): AtlasPackItem { + val height = rows.size + val width = if (height == 0) 0 else rows[0].length + val rgba = ByteArray(width * height * 4) + for (rowIndex in 0 until height) { + require(rows[rowIndex].length == width) { "all rows must share one width" } + for (columnIndex in 0 until width) { + val cell = rows[rowIndex][columnIndex] + val alpha = + when (cell) { + '#' -> 255 + '.' -> 0 + in '0'..'9' -> cell - '0' + else -> throw IllegalArgumentException("unknown cell '$cell'") + } + val byteIndex = (rowIndex * width + columnIndex) * 4 + rgba[byteIndex] = (columnIndex + 1).toByte() + rgba[byteIndex + 1] = (rowIndex + 1).toByte() + rgba[byteIndex + 2] = key[0].code.toByte() + rgba[byteIndex + 3] = alpha.toByte() + } + } + return AtlasPackItem(key, width, height, rgba) +} + +/** + * Builds a fully opaque pack item of the given size, with the same per-pixel RGB scheme. + * + * @param String key The item key. + * @param Int width The tile width. + * @param Int height The tile height. + * @return AtlasPackItem The synthetic tile. + */ +internal fun opaquePackItem(key: String, width: Int, height: Int): AtlasPackItem = + packItemOfRows(key, *Array(height) { "#".repeat(width) }) + +/** + * Reads one page pixel as a packed 0xRRGGBBAA integer. + * + * @param RasterImage page The page to read. + * @param Int x The pixel column. + * @param Int y The pixel row. + * @return Int The packed RGBA value. + */ +internal fun pagePixel(page: RasterImage, x: Int, y: Int): Int { + val byteIndex = (y * page.width + x) * 4 + return ((page.rgba[byteIndex].toInt() and 0xFF) shl 24) or + ((page.rgba[byteIndex + 1].toInt() and 0xFF) shl 16) or + ((page.rgba[byteIndex + 2].toInt() and 0xFF) shl 8) or + (page.rgba[byteIndex + 3].toInt() and 0xFF) +} + +/** + * Reads one source-tile pixel as a packed 0xRRGGBBAA integer. + * + * @param AtlasPackItem item The source tile. + * @param Int x The pixel column. + * @param Int y The pixel row. + * @return Int The packed RGBA value. + */ +internal fun itemPixel(item: AtlasPackItem, x: Int, y: Int): Int { + val byteIndex = (y * item.width + x) * 4 + return ((item.rgba[byteIndex].toInt() and 0xFF) shl 24) or + ((item.rgba[byteIndex + 1].toInt() and 0xFF) shl 16) or + ((item.rgba[byteIndex + 2].toInt() and 0xFF) shl 8) or + (item.rgba[byteIndex + 3].toInt() and 0xFF) +} + +/** + * Where a tile pixel lands on its page, applying the placement's quarter turn. + * + * This is the reader half of the packer's own blit, written independently so a wrong rotation + * convention cannot agree with itself. + * + * @param AtlasPackPlacement placement The placement to read through. + * @param Int tileX The pixel's column within the trimmed tile. + * @param Int tileY The pixel's row within the trimmed tile. + * @return Pair The page column and row. + */ +internal fun pageCoordinateOf(placement: AtlasPackPlacement, tileX: Int, tileY: Int): Pair = + if (placement.quarterTurns == 0) { + (placement.pageX + tileX) to (placement.pageY + tileY) + } else { + (placement.pageX + tileY) to (placement.pageY + placement.trimWidth - 1 - tileX) + } + +/** + * Asserts every packed tile reads back out of its page byte-for-byte against its source pixels. + * + * This is the packer's central correctness claim: the atlas is a repackable indirection over the + * source art, so every opaque source pixel must survive the trip into the page unchanged. + * + * @param List items The tiles that were packed, by key. + * @param AtlasPackResult result The packing outcome to verify. + */ +internal fun assertTilesRoundTripByteExact(items: List, result: AtlasPackResult) { + val itemsByKey = items.associateBy { item -> item.key } + for (placement in result.placements) { + val item = itemsByKey.getValue(placement.key) + val page = result.pages[placement.pageIndex] + for (tileY in 0 until placement.trimHeight) { + for (tileX in 0 until placement.trimWidth) { + val (pageX, pageY) = pageCoordinateOf(placement, tileX, tileY) + assertEquals( + itemPixel(item, placement.trimLeft + tileX, placement.trimTop + tileY), + pagePixel(page, pageX, pageY), + "'${placement.key}' tile pixel ($tileX, $tileY) at page ($pageX, $pageY)", + ) + } + } + } +} + +/** + * Asserts no two tiles come within the gutter of each other, and every gutter footprint fits its page. + * + * Expanding each tile by the gutter reconstructs the footprint the packer reserved, so overlap here + * is exactly the failure that lets one tile's extrusion write over another's artwork. + * + * @param AtlasPackResult result The packing outcome to verify. + * @param Int gutter The gutter the pack ran with. + */ +internal fun assertNoTileOverlap(result: AtlasPackResult, gutter: Int) { + for (placement in result.placements) { + val page = result.pages[placement.pageIndex] + assertTrue( + placement.pageX - gutter >= 0 && placement.pageY - gutter >= 0, + "'${placement.key}' footprint starts outside its page at (${placement.pageX}, ${placement.pageY})", + ) + assertTrue( + placement.pageX + placement.pageWidth + gutter <= page.width && + placement.pageY + placement.pageHeight + gutter <= page.height, + "'${placement.key}' footprint runs past its ${page.width}x${page.height} page", + ) + } + for (firstIndex in result.placements.indices) { + for (secondIndex in firstIndex + 1 until result.placements.size) { + val first = result.placements[firstIndex] + val second = result.placements[secondIndex] + if (first.pageIndex != second.pageIndex) { + continue + } + val separated = + first.pageX + first.pageWidth + gutter <= second.pageX - gutter || + second.pageX + second.pageWidth + gutter <= first.pageX - gutter || + first.pageY + first.pageHeight + gutter <= second.pageY - gutter || + second.pageY + second.pageHeight + gutter <= first.pageY - gutter + assertTrue(separated, "'${first.key}' and '${second.key}' overlap within the gutter") + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPageComposeAffineTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPageComposeAffineTest.kt new file mode 100644 index 0000000..6c38844 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/AtlasPageComposeAffineTest.kt @@ -0,0 +1,318 @@ +package org.umamo.format.atlas + +import org.umamo.format.art.LayerBounds +import org.umamo.format.raster.RasterImage +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the affine page composer against the packer's own blit: an exact integer translation is + * byte-identical to [composeAtlasPages] (so a repack's pages derive unchanged), a quarter turn at an + * integer position reproduces the packer's turned blit texel for texel, a scale covers the scaled + * footprint, the bleed band surrounds a rotated tile on every side, an off-page footprint clips + * without throwing, and overlapping placements paint in list order. + */ +class AtlasPageComposeAffineTest { + private val pageSide = 16 + private val pageWidths = intArrayOf(pageSide) + private val pageHeights = intArrayOf(pageSide) + + /** A 5x5 tile whose opaque 3x3 block sits at (1, 1), with a translucent center texel. */ + private val item = + packItemOfRows( + "a", + ".....", + ".###.", + ".#4#.", + ".###.", + ".....", + ) + private val trim = LayerBounds(1, 1, 3, 3) + + private fun translation(deltaX: Float, deltaY: Float): FloatArray = floatArrayOf(1f, 0f, deltaX, 0f, 1f, deltaY) + + private fun alphaAt(page: RasterImage, x: Int, y: Int): Int = pagePixel(page, x, y) and 0xFF + + private fun composeOne(placement: AtlasTilePlacement, extrude: Int, items: List = listOf(item)): RasterImage = + composeAtlasPagesAffine(pageWidths, pageHeights, items, listOf(placement), extrude).single() + + @Test + fun anIntegerTranslationComposesByteIdenticallyToThePacker() { + val packed = + composeAtlasPages( + pageWidths, + pageHeights, + listOf(item), + listOf(AtlasPackPlacement("a", 0, pageX = 6, pageY = 7, trimLeft = 1, trimTop = 1, trimWidth = 3, trimHeight = 3, quarterTurns = 0)), + extrude = 2, + ).single() + // Tile pixel (x, y) lands at (x + 5, y + 6), so the trim origin (1, 1) lands at (6, 7). + val composed = composeOne(AtlasTilePlacement("a", 0, trim, translation(5f, 6f)), extrude = 2) + assertContentEquals(packed.rgba, composed.rgba, "the exact path is the packer's blit") + } + + @Test + fun aQuarterTurnAtAnIntegerPositionMatchesThePackersTurnedBlit() { + val destinationX = 4 + val destinationY = 5 + val packed = + composeAtlasPages( + pageWidths, + pageHeights, + listOf(item), + listOf(AtlasPackPlacement("a", 0, destinationX, destinationY, trimLeft = 1, trimTop = 1, trimWidth = 3, trimHeight = 3, quarterTurns = 1)), + extrude = 0, + ).single() + // The packer's turn sends tile pixel (tileX, tileY) to (destinationX + tileY - top, + // destinationY + trimWidth - 1 - (tileX - left)); over pixel centers that is the affine + // x' = y + (destinationX - top), y' = -x + (destinationY + trimWidth + left). + val turned = floatArrayOf(0f, 1f, (destinationX - trim.top).toFloat(), -1f, 0f, (destinationY + trim.width + trim.left).toFloat()) + val composed = composeOne(AtlasTilePlacement("a", 0, trim, turned), extrude = 0) + assertContentEquals(packed.rgba, composed.rgba, "centers that land on texel centers copy texels verbatim") + } + + @Test + fun aQuarterTurnFromARotationInDegreesTakesThePackersBlitBandIncluded() { + val destinationX = 4 + val destinationY = 5 + val packed = + composeAtlasPages( + pageWidths, + pageHeights, + listOf(item), + listOf(AtlasPackPlacement("a", 0, destinationX, destinationY, trimLeft = 1, trimTop = 1, trimWidth = 3, trimHeight = 3, quarterTurns = 1)), + extrude = 2, + ).single() + // The affine a placement rotated by -90 degrees produces: its diagonal is near zero, not zero, + // and with a band to extrude only the packer's own blit reproduces the packer's band. + val radians = -PI / 2 + val turned = + floatArrayOf( + cos(radians).toFloat(), + (-sin(radians)).toFloat(), + (destinationX - trim.top).toFloat(), + sin(radians).toFloat(), + cos(radians).toFloat(), + (destinationY + trim.width + trim.left).toFloat(), + ) + assertTrue(turned[0] != 0f, "the diagonal is near zero rather than zero - the case the recogniser must accept") + val composed = composeOne(AtlasTilePlacement("a", 0, trim, turned), extrude = 2) + assertContentEquals(packed.rgba, composed.rgba, "a degree-rotated quarter turn is the packer's turned blit, band included") + } + + @Test + fun aDoubledScaleCoversADoubledFootprintWithBilinearEdges() { + // Tile pixel (x, y) maps to (2x + 2, 2y + 2): the 3x3 trim at (1, 1) covers page [4, 10) squared. + // Beyond the trim the tile is transparent, so magnifying it bilinearly softens its edge by a + // pixel each way: page 4 reads a quarter of its taps outside the trim, page 3 three quarters. + val solid = opaquePackItem("s", 5, 5) + val composed = composeOne(AtlasTilePlacement("s", 0, trim, floatArrayOf(2f, 0f, 2f, 0f, 2f, 2f)), extrude = 0, items = listOf(solid)) + val coverageByPixel = mapOf(3 to 0.25f, 4 to 0.75f, 5 to 1f, 6 to 1f, 7 to 1f, 8 to 1f, 9 to 0.75f, 10 to 0.25f) + for (y in 0 until pageSide) { + for (x in 0 until pageSide) { + val expected = 255f * (coverageByPixel[x] ?: 0f) * (coverageByPixel[y] ?: 0f) + assertTrue(abs(alphaAt(composed, x, y) - expected) <= 1f, "alpha at ($x, $y) is ${alphaAt(composed, x, y)}, not $expected") + } + } + // A corner pixel sees one texel inside the trim: that texel's color, at the coverage it has. + assertEquals(itemPixel(solid, 1, 1) and 0xFF.inv(), pagePixel(composed, 4, 4) and 0xFF.inv(), "the scaled corner carries the trim's corner texel color") + // Between texels the samples blend: at twice the size no page center lands on the translucent + // center texel's own center, so it and its neighbors come out as mixtures rather than snapping + // to the nearest texel. + val blended = composeOne(AtlasTilePlacement("a", 0, trim, floatArrayOf(2f, 0f, 2f, 0f, 2f, 2f)), extrude = 0) + for ((x, y) in listOf(6 to 6, 5 to 5, 7 to 7)) { + val alpha = alphaAt(blended, x, y) + assertTrue(alpha in 5..254, "($x, $y) straddles the opaque and translucent texels and blends them, was $alpha") + } + } + + @Test + fun theBleedBandSurroundsARotatedTileWithoutAddingCoverage() { + val opaque = opaquePackItem("r", 3, 3) + val fullTrim = LayerBounds(0, 0, 3, 3) + // A 45 degree turn with the tile's center carried to the page center (8, 8). + val radians = (PI / 4).toFloat() + val cosine = cos(radians) + val sine = sin(radians) + val rotated = + floatArrayOf( + cosine, + -sine, + 8f - (cosine * 1.5f - sine * 1.5f), + sine, + cosine, + 8f - (sine * 1.5f + cosine * 1.5f), + ) + val bare = composeOne(AtlasTilePlacement("r", 0, fullTrim, rotated), extrude = 0, items = listOf(opaque)) + val extruded = composeOne(AtlasTilePlacement("r", 0, fullTrim, rotated), extrude = 2, items = listOf(opaque)) + + assertEquals(255, alphaAt(bare, 8, 8), "the center is inside the turned square") + // The band adds color, never coverage: every pixel's alpha is the same with and without it. + for (y in 0 until pageSide) { + for (x in 0 until pageSide) { + assertEquals(alphaAt(bare, x, y), alphaAt(extruded, x, y), "the band changes no coverage at ($x, $y)") + } + } + // The diamond's tips reach 2.12 px from the center, so these four pixels sit past its coverage on + // each side and inside the two-pixel band: untouched without it, the edge's color at zero alpha with it. + for ((x, y) in listOf(8 to 5, 8 to 10, 5 to 8, 10 to 8)) { + assertEquals(0, pagePixel(bare, x, y), "($x, $y) is untouched without a band") + assertEquals(0, alphaAt(extruded, x, y), "($x, $y) is transparent inside the band") + assertTrue(pagePixel(extruded, x, y) != 0, "($x, $y) carries the edge's color inside the band") + } + assertEquals(0, pagePixel(extruded, 8, 2), "three pixels past the tip is beyond the band") + } + + @Test + fun anOffPageFootprintClipsWithoutThrowing() { + // The trim origin lands at (-1, -1): tile pixel (2, 2) is the page's (0, 0). + val clipped = composeOne(AtlasTilePlacement("a", 0, trim, translation(-2f, -2f)), extrude = 2) + assertEquals(itemPixel(item, 2, 2), pagePixel(clipped, 0, 0), "the visible part composes at its clipped spot") + assertEquals(itemPixel(item, 3, 3), pagePixel(clipped, 1, 1)) + assertEquals(0, alphaAt(clipped, 5, 5), "nothing spills past the clipped footprint and band") + + val gone = composeOne(AtlasTilePlacement("a", 0, trim, translation(-40f, -40f)), extrude = 2) + assertTrue(gone.rgba.all { byte -> byte == 0.toByte() }, "a footprint wholly off the page leaves it empty") + } + + /** A 5x5 tile that is transparent except for one opaque texel at (0, 0) and a half-transparent one at (4, 4). */ + private val sparse = + packItemOfRows( + "b", + "#....", + ".....", + ".....", + ".....", + "....8", + ) + private val fullTrim = LayerBounds(0, 0, 5, 5) + + @Test + fun aLaterTransparentMarginNeverErasesEarlierContent() { + val solid = opaquePackItem("s", 3, 3) + val solidAt = translation(4f, 4f) + // The sparse tile's rectangle covers the solid tile entirely; only its (0, 0) texel is opaque and + // lands at (3, 3), outside the solid tile. + val exact = composeAtlasPagesAffine(pageWidths, pageHeights, listOf(solid, sparse), listOf(AtlasTilePlacement("s", 0, LayerBounds(0, 0, 3, 3), solidAt), AtlasTilePlacement("b", 0, fullTrim, translation(3f, 3f))), extrude = 0).single() + for (y in 4 until 7) { + for (x in 4 until 7) { + assertEquals(itemPixel(solid, x - 4, y - 4), pagePixel(exact, x, y), "the solid tile survives the transparent margin at ($x, $y) (exact path)") + } + } + assertEquals(itemPixel(sparse, 0, 0), pagePixel(exact, 3, 3), "the sparse tile's opaque texel lands") + + // The same through the resampling path (a fractional translation). + val resampled = composeAtlasPagesAffine(pageWidths, pageHeights, listOf(solid, sparse), listOf(AtlasTilePlacement("s", 0, LayerBounds(0, 0, 3, 3), solidAt), AtlasTilePlacement("b", 0, fullTrim, translation(3.5f, 3.5f))), extrude = 0).single() + for (y in 4 until 7) { + for (x in 4 until 7) { + assertEquals(255, alphaAt(resampled, x, y), "the solid tile stays opaque under the resampled margin at ($x, $y)") + } + } + + // And through the packer's quarter-turn path. + val turned = + composeAtlasPages( + pageWidths, + pageHeights, + listOf(solid, sparse), + listOf( + AtlasPackPlacement("s", 0, 4, 4, trimLeft = 0, trimTop = 0, trimWidth = 3, trimHeight = 3, quarterTurns = 0), + AtlasPackPlacement("b", 0, 3, 3, trimLeft = 0, trimTop = 0, trimWidth = 5, trimHeight = 5, quarterTurns = 1), + ), + extrude = 0, + ).single() + for (y in 4 until 7) { + for (x in 4 until 7) { + assertEquals(itemPixel(solid, x - 4, y - 4), pagePixel(turned, x, y), "the solid tile survives under the turned margin at ($x, $y)") + } + } + } + + @Test + fun aLaterOpaqueTexelReplacesAndATranslucentOneComposites() { + val solid = opaquePackItem("s", 3, 3) + // The sparse tile placed so its opaque (0, 0) covers the solid tile's (1, 1) and its + // half-transparent (4, 4) covers... nothing: place a second copy so (4, 4) lands on the solid. + val page = + composeAtlasPagesAffine( + pageWidths, + pageHeights, + listOf(solid, sparse), + listOf( + AtlasTilePlacement("s", 0, LayerBounds(0, 0, 3, 3), translation(4f, 4f)), + AtlasTilePlacement("b", 0, fullTrim, translation(5f, 5f)), + ), + extrude = 0, + ).single() + assertEquals(itemPixel(sparse, 0, 0), pagePixel(page, 5, 5), "an opaque texel replaces the earlier content") + assertEquals(itemPixel(solid, 0, 0), pagePixel(page, 4, 4), "beside it the earlier tile is untouched") + + val translucent = + composeAtlasPagesAffine( + pageWidths, + pageHeights, + listOf(solid, sparse), + listOf( + AtlasTilePlacement("s", 0, LayerBounds(0, 0, 3, 3), translation(4f, 4f)), + AtlasTilePlacement("b", 0, fullTrim, translation(1f, 1f)), + ), + extrude = 0, + ).single() + // The sparse (4, 4) texel, alpha 8, lands on the solid (1, 1) at page (5, 5): a source-over + // composite stays fully opaque and leans almost entirely on the tile beneath. + val composed = pagePixel(translucent, 5, 5) + assertEquals(255, composed and 0xFF, "compositing over opaque content stays opaque") + val beneathRed = (itemPixel(solid, 1, 1) ushr 24) and 0xFF + val overRed = (itemPixel(sparse, 4, 4) ushr 24) and 0xFF + val expectedRed = ((overRed * 8f + beneathRed * 247f) / 255f).toInt() + assertTrue(abs(((composed ushr 24) and 0xFF) - expectedRed) <= 1, "the red channel is the source-over blend") + } + + @Test + fun anExtrusionBandStopsAtContent() { + val first = opaquePackItem("s", 3, 3) + val second = opaquePackItem("t", 3, 3) + // Two opaque tiles two pixels apart: the first's band fills the gap, the second's band must not + // overwrite the first's pixels or recolor its band. Band pixels carry their edge's color at zero alpha. + val page = + composeAtlasPagesAffine( + pageWidths, + pageHeights, + listOf(first, second), + listOf( + AtlasTilePlacement("s", 0, LayerBounds(0, 0, 3, 3), translation(4f, 4f)), + AtlasTilePlacement("t", 0, LayerBounds(0, 0, 3, 3), translation(8f, 4f)), + ), + extrude = 2, + ).single() + assertEquals(itemPixel(first, 2, 1), pagePixel(page, 6, 5), "the first tile's edge pixel is not overwritten by the second's band") + assertEquals(itemPixel(first, 2, 1) and 0xFF.inv(), pagePixel(page, 7, 5), "the first tile's own band keeps the gap") + assertEquals(itemPixel(second, 0, 1), pagePixel(page, 8, 5), "the second tile's pixels land") + assertEquals(itemPixel(second, 2, 1) and 0xFF.inv(), pagePixel(page, 11, 5), "the second tile's outer band lands on empty page") + } + + @Test + fun overlappingPlacementsPaintInListOrder() { + val other = opaquePackItem("b", 3, 3) + val pages = + composeAtlasPagesAffine( + pageWidths, + pageHeights, + listOf(item, other), + listOf( + AtlasTilePlacement("a", 0, trim, translation(5f, 6f)), + AtlasTilePlacement("b", 0, LayerBounds(0, 0, 3, 3), translation(7f, 8f)), + ), + extrude = 0, + ) + val page = pages.single() + assertEquals(itemPixel(other, 0, 0), pagePixel(page, 7, 8), "the later placement wins the overlap") + assertEquals(itemPixel(item, 1, 1), pagePixel(page, 6, 7), "the earlier placement keeps its uncovered pixels") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/atlas/RectPackerTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/RectPackerTest.kt new file mode 100644 index 0000000..adda4ca --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/atlas/RectPackerTest.kt @@ -0,0 +1,160 @@ +package org.umamo.format.atlas + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Covers the rectangle bin packer on its own: placement geometry, page spill, rotation, seeded + * footprints, and the oversized report. Trimming, gutters, and pixels belong to [AtlasPackTest]. + */ +class RectPackerTest { + @Test + fun placementsNeverOverlapAndStayInsideThePage() { + val requests = + listOf( + RectPackRequest(0, 40, 30), + RectPackRequest(1, 30, 40), + RectPackRequest(2, 25, 25), + RectPackRequest(3, 60, 10), + RectPackRequest(4, 10, 60), + RectPackRequest(5, 5, 5), + ) + + val layout = packRects(requests, pageSize = 64, allowRotation = false) + + assertTrue(layout.oversizedItemIndices.isEmpty(), "nothing here exceeds a 64 page") + assertEquals(requests.size, layout.slots.size, "every request must be placed") + assertNoRectOverlap(requests, layout, pageSize = 64) + } + + @Test + fun aRequestTooLargeForAPageIsReportedNotDropped() { + val requests = listOf(RectPackRequest(0, 10, 10), RectPackRequest(1, 70, 10), RectPackRequest(2, 10, 70)) + + val layout = packRects(requests, pageSize = 64, allowRotation = true) + + assertEquals(listOf(1, 2), layout.oversizedItemIndices.sorted()) + assertEquals(listOf(0), layout.slots.map { slot -> slot.itemIndex }) + } + + @Test + fun requestsSpillOntoFurtherPagesWhenOneWillNotHold() { + val requests = (0 until 5).map { itemIndex -> RectPackRequest(itemIndex, 40, 40) } + + val layout = packRects(requests, pageSize = 64, allowRotation = false) + + // A 64 page holds exactly one 40x40, so five requests need five pages. + assertEquals(5, layout.slots.size) + assertEquals(listOf(0, 1, 2, 3, 4), layout.slots.map { slot -> slot.pageIndex }) + assertEquals(List(5) { 40 }, layout.usedWidths) + assertEquals(List(5) { 40 }, layout.usedHeights) + } + + @Test + fun rotationIsUsedOnlyWhenAllowed() { + // The 16x8 fills the top half of a 16 page, leaving one 16x8 free strip; the 8x16 fits it + // only quarter-turned. + val requests = listOf(RectPackRequest(0, 16, 8), RectPackRequest(1, 8, 16)) + + val turned = packRects(requests, pageSize = 16, allowRotation = true) + assertEquals(1, turned.slots.count { slot -> slot.rotated }, "the second request must turn to fit") + assertEquals(listOf(0, 0), turned.slots.map { slot -> slot.pageIndex }) + + val upright = packRects(requests, pageSize = 16, allowRotation = false) + assertTrue(upright.slots.none { slot -> slot.rotated }, "rotation must not appear when disallowed") + assertEquals(listOf(0, 1), upright.slots.map { slot -> slot.pageIndex }, "it needs its own page instead") + } + + @Test + fun theUsedExtentBoundsEveryPlacement() { + val requests = listOf(RectPackRequest(0, 30, 20), RectPackRequest(1, 20, 30), RectPackRequest(2, 10, 10)) + + val layout = packRects(requests, pageSize = 128, allowRotation = false) + + for (slot in layout.slots) { + val width = if (slot.rotated) requests[slot.itemIndex].height else requests[slot.itemIndex].width + val height = if (slot.rotated) requests[slot.itemIndex].width else requests[slot.itemIndex].height + assertTrue( + slot.x + width <= layout.usedWidths[slot.pageIndex] && slot.y + height <= layout.usedHeights[slot.pageIndex], + "item ${slot.itemIndex} runs past the reported used extent", + ) + } + } + + @Test + fun aSeedIsKeptClearAndCountsTowardTheUsedExtent() { + val seed = RectPackSeed(pageIndex = 0, x = 10, y = 10, width = 20, height = 20) + val requests = (0 until 6).map { itemIndex -> RectPackRequest(itemIndex, 15, 15) } + + val layout = packRects(requests, pageSize = 64, allowRotation = false, seeds = listOf(seed)) + + assertEquals(requests.size, layout.slots.size, "every request still finds room around the seed") + for (slot in layout.slots.filter { slot -> slot.pageIndex == 0 }) { + val separated = slot.x + 15 <= seed.x || seed.x + seed.width <= slot.x || slot.y + 15 <= seed.y || seed.y + seed.height <= slot.y + assertTrue(separated, "item ${slot.itemIndex} at (${slot.x}, ${slot.y}) overlaps the seed") + } + assertNoRectOverlap(requests, layout, pageSize = 64) + assertTrue(layout.usedWidths[0] >= seed.x + seed.width && layout.usedHeights[0] >= seed.y + seed.height, "the used extent covers the seed") + } + + @Test + fun seedingALaterPageOpensThePagesBeforeIt() { + val layout = packRects(emptyList(), pageSize = 32, allowRotation = false, seeds = listOf(RectPackSeed(2, 0, 0, 8, 8))) + + assertEquals(3, layout.usedWidths.size, "pages 0 and 1 exist so the seed keeps its index") + assertEquals(listOf(0, 0, 8), layout.usedWidths) + assertEquals(listOf(0, 0, 8), layout.usedHeights) + } + + @Test + fun packingIsAFunctionOfTheRequestOrderAlone() { + val requests = (0 until 12).map { itemIndex -> RectPackRequest(itemIndex, 10 + itemIndex, 40 - itemIndex) } + + val first = packRects(requests, pageSize = 64, allowRotation = true) + val second = packRects(requests, pageSize = 64, allowRotation = true) + + assertContentEquals( + first.slots.map { slot -> listOf(slot.itemIndex, slot.pageIndex, slot.x, slot.y, if (slot.rotated) 1 else 0) }, + second.slots.map { slot -> listOf(slot.itemIndex, slot.pageIndex, slot.x, slot.y, if (slot.rotated) 1 else 0) }, + ) + } + + /** + * Asserts no two placed rectangles intersect and every one fits the page. + * + * @param List requests The packed requests, indexed by item index. + * @param RectPackLayout layout The packing outcome. + * @param Int pageSize The page side the pack ran against. + */ + private fun assertNoRectOverlap(requests: List, layout: RectPackLayout, pageSize: Int) { + fun widthOf(slot: RectPackSlot): Int = + if (slot.rotated) requests[slot.itemIndex].height else requests[slot.itemIndex].width + + fun heightOf(slot: RectPackSlot): Int = + if (slot.rotated) requests[slot.itemIndex].width else requests[slot.itemIndex].height + + for (slot in layout.slots) { + assertTrue( + slot.x >= 0 && slot.y >= 0 && slot.x + widthOf(slot) <= pageSize && slot.y + heightOf(slot) <= pageSize, + "item ${slot.itemIndex} runs outside the page", + ) + } + for (firstIndex in layout.slots.indices) { + for (secondIndex in firstIndex + 1 until layout.slots.size) { + val first = layout.slots[firstIndex] + val second = layout.slots[secondIndex] + if (first.pageIndex != second.pageIndex) { + continue + } + val separated = + first.x + widthOf(first) <= second.x || + second.x + widthOf(second) <= first.x || + first.y + heightOf(first) <= second.y || + second.y + heightOf(second) <= first.y + assertTrue(separated, "items ${first.itemIndex} and ${second.itemIndex} overlap") + } + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/BinaryTextTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/BinaryTextTest.kt new file mode 100644 index 0000000..46b03e6 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/BinaryTextTest.kt @@ -0,0 +1,41 @@ +package org.umamo.format.binary + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Pins the common-code text conversions against the JVM charset behavior they replicate: US-ASCII + * decode with U+FFFD for high bytes (NOT Latin-1), and BOM-less UTF-16BE encode. + */ +class BinaryTextTest { + /** Bytes above 0x7F decode to the replacement character, matching the JVM's US_ASCII decoder. */ + @Test + fun decodeAsciiMapsHighBytesToReplacementCharacter() { + val bytes = byteArrayOf(0x41, 0xC3.toByte(), 0x42) + assertEquals("A�B", decodeAscii(bytes, 0, 3)) + } + + /** The offset/length window decodes exactly the requested slice. */ + @Test + fun decodeAsciiHonorsTheOffsetWindow() { + val bytes = "XhelloY".encodeToByteArray() + assertEquals("hello", decodeAscii(bytes, 1, 5)) + } + + /** Each code unit becomes two big-endian bytes with no byte-order mark. */ + @Test + fun encodeUtf16BeEmitsTwoBigEndianBytesPerCodeUnit() { + assertContentEquals(byteArrayOf(0x00, 0x41, 0x00, 0x42), encodeUtf16Be("AB")) + assertContentEquals(byteArrayOf(0x30, 0x42), encodeUtf16Be("あ"), "a non-ASCII code unit keeps its high byte first") + } + + /** An astral-plane character passes through as its two surrogate code units (four bytes). */ + @Test + fun encodeUtf16BePassesSurrogatePairsThrough() { + assertContentEquals( + byteArrayOf(0xD8.toByte(), 0x3D, 0xDE.toByte(), 0x00), + encodeUtf16Be("😀"), + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/ContentHashTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ContentHashTest.kt new file mode 100644 index 0000000..5b550e7 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ContentHashTest.kt @@ -0,0 +1,14 @@ +package org.umamo.format.binary + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The content hash is SHA-256 as lowercase hex. */ +class ContentHashTest { + @Test + fun theDigestIsSha256Hex() { + // The published vectors for "abc" and the empty input. + assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", contentHashOf("abc".encodeToByteArray())) + assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", contentHashOf(ByteArray(0))) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/Crc32Test.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/Crc32Test.kt new file mode 100644 index 0000000..2f3484e --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/Crc32Test.kt @@ -0,0 +1,77 @@ +package org.umamo.format.binary + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the pure-Kotlin CRC-32 against the standard check vector and the java.util.zip.CRC32 shape + * it mirrors (accumulate, then read) - the checksum PNG and ZIP both stamp, so a drift here corrupts + * every written container. + */ +class Crc32Test { + /** The IEEE 802.3 check value: CRC-32 of the ASCII digits "123456789" is 0xCBF43926. */ + @Test + fun standardCheckVectorMatches() { + val checksum = Crc32() + checksum.update("123456789".encodeToByteArray()) + assertEquals(0xCBF43926L, checksum.value) + } + + /** Chunked accumulation equals a one-shot update over the same bytes. */ + @Test + fun incrementalUpdateEqualsOneShot() { + val chunked = Crc32() + chunked.update("1234".encodeToByteArray()) + chunked.update("56789".encodeToByteArray()) + val oneShot = Crc32() + oneShot.update("123456789".encodeToByteArray()) + assertEquals(oneShot.value, chunked.value) + } + + /** No input yields the empty-message CRC of zero (the all-ones precondition inverted back). */ + @Test + fun emptyInputYieldsZero() { + assertEquals(0L, Crc32().value) + } + + /** + * Slices of every length at every alignment agree with a bit-at-a-time reference, covering the + * eight-byte fast path, its byte-wise tail, and a slice that starts mid-buffer. + */ + @Test + fun slicedUpdateMatchesBitwiseReference() { + val bytes = ByteArray(64) { byteIndex -> (byteIndex * 151 + 7).toByte() } + for (offset in 0 until 8) { + for (length in 0..(bytes.size - offset)) { + val checksum = Crc32() + checksum.update(bytes, offset, length) + assertEquals(bitwiseCrc32(bytes, offset, length), checksum.value, "offset $offset, length $length") + } + } + } + + /** + * The CRC-32 computed one bit at a time straight from the reflected polynomial, sharing no table + * with [Crc32]. + * + * @param ByteArray bytes The buffer. + * @param Int offset Offset of the first byte. + * @param Int length Number of bytes. + * @return Long The checksum, as an unsigned 32-bit value. + */ + private fun bitwiseCrc32(bytes: ByteArray, offset: Int, length: Int): Long { + var remainder = -1 + for (byteIndex in offset until offset + length) { + remainder = remainder xor (bytes[byteIndex].toInt() and 0xFF) + repeat(8) { + remainder = + if ((remainder and 1) != 0) { + (remainder ushr 1) xor 0xEDB88320.toInt() + } else { + remainder ushr 1 + } + } + } + return remainder.inv().toLong() and 0xFFFFFFFFL + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/DeflateContractTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/DeflateContractTest.kt new file mode 100644 index 0000000..3545287 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/DeflateContractTest.kt @@ -0,0 +1,93 @@ +package org.umamo.format.binary + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the DEFLATE seam's contract. In commonTest, so it also runs against Kotlin/Native. + * + * Nothing called [inflateZlib] directly before this, so its best-effort behaviour was untested even + * though every reader leans on it: a truncated or corrupt stream must yield the bytes recovered so + * far rather than throwing, which is what lets a partly damaged art file still decode. The + * `maximumSize` bound matters just as much — it is the only thing standing between a malicious or + * corrupt stream and an unbounded allocation. + */ +class DeflateContractTest { + // Compressible, PNG-scanline-ish data: a repeating ramp with enough structure to deflate well. + private val raw = ByteArray(40_000) { (it % 7).toByte() } + private val compressed = deflateZlib(raw) + + @Test + fun roundTripsZlib() { + assertTrue(compressed.size < raw.size, "must actually compress: ${compressed.size} vs ${raw.size}") + assertContentEquals(raw, inflateZlib(compressed, 0, compressed.size, raw.size), "zlib round-trip") + } + + @Test + fun truncatedStreamRecoversWhatItCan() { + // The load-bearing case: a half-supplied stream must not throw, and must not silently yield + // nothing either — the recovered prefix is what a damaged file still renders from. + val recovered = inflateZlib(compressed, 0, compressed.size / 2, raw.size) + assertTrue(recovered.isNotEmpty(), "a truncated stream must still recover its decodable prefix") + assertTrue(recovered.size < raw.size, "a truncated stream must not somehow produce everything") + assertContentEquals(raw.copyOfRange(0, recovered.size), recovered, "the recovered prefix must be correct, not garbage") + } + + @Test + fun corruptStreamYieldsEmptyRatherThanThrowing() { + val corrupt = compressed.copyOf() + for (index in 20 until minOf(60, corrupt.size)) { + corrupt[index] = 0x7F + } + assertEquals(0, inflateZlib(corrupt, 0, corrupt.size, raw.size).size, "corrupt stream decodes to nothing, without throwing") + assertEquals(0, inflateZlib(ByteArray(500) { 0x5A }, 0, 500, raw.size).size, "garbage decodes to nothing, without throwing") + } + + @Test + fun respectsTheMaximumSizeBound() { + // The guard against a decompression bomb: stop at the stated size, however much is available. + assertEquals(1_000, inflateZlib(compressed, 0, compressed.size, 1_000).size, "output is capped at maximumSize") + assertContentEquals(raw.copyOfRange(0, 1_000), inflateZlib(compressed, 0, compressed.size, 1_000), "the capped prefix is still correct") + } + + @Test + fun readsFromAnEmbeddedSubrange() { + val padded = ByteArray(11) + compressed + ByteArray(9) + assertContentEquals(raw, inflateZlib(padded, 11, compressed.size, raw.size), "offset/length select the stream") + } + + @Test + fun degenerateInputsYieldEmpty() { + assertEquals(0, inflateZlib(compressed, 0, 0, raw.size).size, "zero length") + assertEquals(0, inflateZlib(compressed, compressed.size + 5, 10, raw.size).size, "offset past end") + assertEquals(0, inflateZlib(compressed, 0, compressed.size, 0).size, "zero maximum") + assertEquals(0, inflateZlib(ByteArray(0), 0, 0, 16).size, "empty source") + } + + @Test + fun roundTripsRawDeflateAtEveryCaffLevel() { + // Raw (unwrapped) deflate is what a ZIP entry's payload is; CompressOption uses levels 0/1/5. + // The trailing-dummy-byte requirement of nowrap mode makes this worth pinning explicitly. + for (level in intArrayOf(0, 1, 5, 9)) { + val rawStream = deflateRawDeflate(raw, level) + assertContentEquals(raw, inflateRawDeflate(rawStream, 0, rawStream.size, raw.size), "raw deflate round-trip at level $level") + } + } + + @Test + fun rawDeflateIsExactlyTheZlibStreamWithoutItsFraming() { + // If the wrapper ever leaked back into the raw path, the CAFF codec's ZIP framing would be + // silently wrong — a ZIP reader does not expect zlib's 0x78 header or its Adler-32 trailer. + // Compare at the SAME level (6 == zlib's default), so only the framing differs. + val zlibStream = deflateZlib(raw) + val rawStream = deflateRawDeflate(raw, 6) + assertEquals(0x78, zlibStream[0].toInt() and 0xFF, "zlib framing starts with the 0x78 CMF byte") + assertContentEquals( + zlibStream.copyOfRange(2, zlibStream.size - 4), + rawStream, + "raw deflate must be exactly the zlib stream minus its 2-byte header and 4-byte Adler-32", + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipArchiveTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipArchiveTest.kt new file mode 100644 index 0000000..95f699e --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipArchiveTest.kt @@ -0,0 +1,395 @@ +package org.umamo.format.binary + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Pins the ZIP reader's contract: what it reads back from well-formed archives, and that every kind of + * damage or deceit fails loudly with a ZipFormatException rather than yielding wrong bytes. In + * commonTest, so the same contract compiles for Kotlin/Native. + */ +class ZipArchiveTest { + // Compressible enough that DEFLATE genuinely shrinks it. + private val compressible = ByteArray(40_000) { byteIndex -> (byteIndex % 13).toByte() } + + /** + * Every entry shape round-trips: stored, deflated, empty under both methods, a directory, and names + * outside ASCII - in insertion order, with the stamp and methods declared. + */ + @Test + fun roundTripsEveryEntryShape() { + val expected = + listOf( + Triple("mimetype", "application/vnd.umamo.uma+zip".encodeToByteArray(), false), + Triple("model/puppet.json", compressible, true), + Triple("empty-stored", ByteArray(0), false), + Triple("empty-deflated", ByteArray(0), true), + Triple("textures/", ByteArray(0), false), + Triple("テクスチャ/ページ.png", compressible.copyOf(1000), false), + Triple("émoji-😀.txt", "naïve".encodeToByteArray(), true), + ) + val archive = ZipArchive.read(archiveOf(*expected.toTypedArray())) + + assertEquals(expected.map { entry -> entry.first }, archive.entries.map { entry -> entry.name }, "entry order") + for ((name, contents, deflated) in expected) { + val entry = assertNotNull(archive.entry(name), "entry '$name' is listed") + assertContentEquals(contents, archive.contents(entry), "entry '$name' contents") + assertEquals(if (deflated) ZipRecords.METHOD_DEFLATED else ZipRecords.METHOD_STORED, entry.method, "entry '$name' method") + assertEquals(TEST_DOS_DATE_TIME, entry.dosDateTime, "entry '$name' stamp") + assertEquals(name.endsWith('/'), entry.isDirectory, "entry '$name' directory flag") + } + val deflatedEntry = assertNotNull(archive.entry("model/puppet.json")) + assertTrue(deflatedEntry.compressedSize < deflatedEntry.uncompressedSize, "the deflated entry actually compressed") + } + + /** + * An archive with no entries is just its end record, and reads as empty. + */ + @Test + fun readsAnEmptyArchive() { + val bytes = ZipWriter(TEST_DOS_DATE_TIME).finish() + assertEquals(ZipRecords.END_SIZE, bytes.size, "an empty archive is only its end record") + assertTrue(ZipArchive.read(bytes).entries.isEmpty(), "no entries") + } + + /** + * A raw payload is the compressed bytes exactly as stored. + */ + @Test + fun rawPayloadIsTheStoredBytes() { + val bytes = archiveOf(Triple("deflated", compressible, true)) + val archive = ZipArchive.read(bytes) + val entry = archive.entries.single() + val payload = archive.rawPayload(entry) + assertEquals(entry.compressedSize, payload.size, "payload size") + assertContentEquals(deflateRawDeflate(compressible, 6), payload, "payload is the raw DEFLATE stream") + } + + /** + * Cutting bytes off the end loses the end record, and a file too short for one is refused outright. + */ + @Test + fun truncatedArchiveFails() { + val bytes = archiveOf(Triple("a", compressible, true), Triple("b", compressible, false)) + assertFailsWith("one byte short") { ZipArchive.read(bytes.copyOf(bytes.size - 1)) } + assertFailsWith("half the archive") { ZipArchive.read(bytes.copyOf(bytes.size / 2)) } + assertFailsWith("shorter than an end record") { ZipArchive.read(ByteArray(10)) } + assertFailsWith("not a ZIP at all") { ZipArchive.read(compressible) } + } + + /** + * An end record whose central directory was cut short does not describe the bytes before it. + */ + @Test + fun truncatedCentralDirectoryFails() { + val bytes = archiveOf(Triple("first", compressible, true), Triple("second", compressible, true)) + val directoryOffset = centralDirectoryOffset(bytes) + val endRecord = bytes.copyOfRange(endRecordOffset(bytes), bytes.size) + val truncated = bytes.copyOf(directoryOffset + ZipRecords.CENTRAL_HEADER_SIZE + 3) + endRecord + assertFailsWith { ZipArchive.read(truncated) } + } + + /** + * A payload shorter than its stream - here the declared compressed size cut in half - cannot inflate + * to the declared size. + */ + @Test + fun truncatedPayloadFails() { + val bytes = archiveOf(Triple("entry", compressible, true)) + val header = centralHeaderOffset(bytes, 0) + writeU32Le(bytes, header + 20, readU32Le(bytes, header + 20) / 2) + val archive = ZipArchive.read(bytes) + assertFailsWith { archive.contents(archive.entries.single()) } + } + + /** + * A payload whose bytes changed after the CRC-32 was recorded is caught by the CRC-32. + */ + @Test + fun crcMismatchFails() { + val bytes = archiveOf(Triple("stored", compressible, false)) + val archive = ZipArchive.read(bytes) + val entry = archive.entries.single() + bytes[entry.payloadOffset + 100] = (bytes[entry.payloadOffset + 100] + 1).toByte() + assertFailsWith { archive.contents(entry) } + } + + /** + * An uncompressed size that lies in either direction fails, for a deflated and a stored entry alike. + */ + @Test + fun declaredSizeThatLiesFails() { + for (delta in listOf(-1L, 1L)) { + val bytes = archiveOf(Triple("deflated", compressible, true), Triple("stored", compressible, false)) + for (entryIndex in 0..1) { + val header = centralHeaderOffset(bytes, entryIndex) + writeU32Le(bytes, header + 24, readU32Le(bytes, header + 24) + delta) + } + val archive = ZipArchive.read(bytes) + for (entry in archive.entries) { + assertFailsWith("'${entry.name}' with its size off by $delta") { archive.contents(entry) } + } + } + } + + /** + * A stream that inflates far past its declared size stops one byte past it and fails, rather than + * inflating everything it holds. + */ + @Test + fun decompressionBombStopsAtItsDeclaredSize() { + val bomb = ByteArray(10 * 1024 * 1024) + val bytes = archiveOf(Triple("bomb", bomb, true)) + writeU32Le(bytes, centralHeaderOffset(bytes, 0) + 24, 100) + val archive = ZipArchive.read(bytes) + val entry = archive.entries.single() + assertTrue(entry.compressedSize < 64 * 1024, "the bomb is small on disk: ${entry.compressedSize}") + val failure = assertFailsWith { archive.contents(entry) } + assertTrue(failure.message.orEmpty().contains("more than 100"), "the failure names the bound: ${failure.message}") + } + + /** + * An encrypted entry cannot be inflated, but its raw payload still copies. + */ + @Test + fun encryptedEntryRefusesContentsButCopiesRaw() { + val bytes = archiveOf(Triple("secret", compressible, true)) + val header = centralHeaderOffset(bytes, 0) + writeU16Le(bytes, header + 8, readU16Le(bytes, header + 8) or ZipRecords.FLAG_ENCRYPTED) + val archive = ZipArchive.read(bytes) + val entry = archive.entries.single() + assertTrue(entry.isEncrypted, "the flag reads back") + assertFailsWith { archive.contents(entry) } + assertContentEquals(deflateRawDeflate(compressible, 6), archive.rawPayload(entry), "raw payload still copies") + } + + /** + * A method other than stored or DEFLATE lists but cannot be inflated. + */ + @Test + fun unsupportedMethodFailsOnContents() { + val bytes = archiveOf(Triple("bzip2", compressible, true)) + // ZIP: method 12 is BZIP2 (APPNOTE.TXT 4.4.5), patched into both headers so they agree. + writeU16Le(bytes, centralHeaderOffset(bytes, 0) + 10, 12) + writeU16Le(bytes, localHeaderOffset(bytes, 0) + 8, 12) + val archive = ZipArchive.read(bytes) + assertEquals(12, archive.entries.single().method, "the method reads back") + assertFailsWith { archive.contents(archive.entries.single()) } + } + + /** + * A local header that disagrees with its central header about the method or the name fails the read. + */ + @Test + fun localHeaderDisagreementFails() { + val methodMismatch = archiveOf(Triple("entry", compressible, true)) + writeU16Le(methodMismatch, centralHeaderOffset(methodMismatch, 0) + 10, ZipRecords.METHOD_STORED) + assertFailsWith("method mismatch") { ZipArchive.read(methodMismatch) } + + val nameMismatch = archiveOf(Triple("abc", compressible, true)) + nameMismatch[localHeaderOffset(nameMismatch, 0) + ZipRecords.LOCAL_HEADER_SIZE] = 'x'.code.toByte() + assertFailsWith("name mismatch") { ZipArchive.read(nameMismatch) } + + val outOfRange = archiveOf(Triple("entry", compressible, true)) + writeU32Le(outOfRange, centralHeaderOffset(outOfRange, 0) + 42, centralDirectoryOffset(outOfRange).toLong()) + assertFailsWith("local header offset inside the directory") { ZipArchive.read(outOfRange) } + } + + /** + * Two entries with the same name make every lookup ambiguous, so the read refuses them. + */ + @Test + fun duplicateNamesFail() { + val bytes = archiveOf(Triple("a1", compressible, false), Triple("a2", compressible, false)) + bytes[centralHeaderOffset(bytes, 1) + ZipRecords.CENTRAL_HEADER_SIZE + 1] = '1'.code.toByte() + bytes[localHeaderOffset(bytes, 1) + ZipRecords.LOCAL_HEADER_SIZE + 1] = '1'.code.toByte() + assertFailsWith { ZipArchive.read(bytes) } + } + + /** + * A name that is not valid UTF-8 fails rather than decoding to replacement characters. + */ + @Test + fun invalidUtf8NameFails() { + val bytes = archiveOf(Triple("ab", compressible, false)) + val invalid = 0xFF.toByte() + bytes[centralHeaderOffset(bytes, 0) + ZipRecords.CENTRAL_HEADER_SIZE] = invalid + bytes[localHeaderOffset(bytes, 0) + ZipRecords.LOCAL_HEADER_SIZE] = invalid + assertFailsWith { ZipArchive.read(bytes) } + } + + /** + * A comment holding an end-record look-alike - even one at the very end, which satisfies the comment + * rule - does not hijack the read. + */ + @Test + fun endRecordLookAlikeInCommentIsIgnored() { + val original = archiveOf(Triple("first", compressible, true), Triple("second", "two".encodeToByteArray(), false)) + val lookAlike = ByteArray(ZipRecords.END_SIZE) + writeU32Le(lookAlike, 0, ZipRecords.END_SIGNATURE.toLong()) + val commented = original + lookAlike + writeU16Le(commented, endRecordOffset(original) + 20, lookAlike.size) + val archive = ZipArchive.read(commented) + assertEquals(listOf("first", "second"), archive.entries.map { entry -> entry.name }, "the genuine directory is read") + assertContentEquals(compressible, archive.contents(archive.entries.first()), "and its entries inflate") + } + + /** + * A look-alike after the genuine end record that would fail the read if it were examined - one declaring another + * disk, one declaring Zip64 over a locator look-alike - is never reached, so the archive reads. + */ + @Test + fun failingLookAlikeInCommentIsNeverExamined() { + val original = archiveOf(Triple("first", compressible, true), Triple("second", "two".encodeToByteArray(), false)) + val genuineEnd = endRecordOffset(original) + + val multiDisk = original.copyOfRange(genuineEnd, original.size) + writeU16Le(multiDisk, 4, 1) + val withMultiDisk = original + multiDisk + writeU16Le(withMultiDisk, genuineEnd + 20, multiDisk.size) + assertEquals(listOf("first", "second"), ZipArchive.read(withMultiDisk).entries.map { entry -> entry.name }, "a multi-disk look-alike") + + val locator = ByteArray(ZipRecords.ZIP64_LOCATOR_SIZE) + writeU32Le(locator, 0, ZipRecords.ZIP64_LOCATOR_SIGNATURE.toLong()) + val zip64 = original.copyOfRange(genuineEnd, original.size) + writeU16Le(zip64, 8, ZipRecords.UINT16_SENTINEL) + writeU16Le(zip64, 10, ZipRecords.UINT16_SENTINEL) + val withZip64 = original + locator + zip64 + writeU16Le(withZip64, genuineEnd + 20, locator.size + zip64.size) + assertEquals(listOf("first", "second"), ZipArchive.read(withZip64).entries.map { entry -> entry.name }, "a Zip64 look-alike over a locator look-alike") + } + + /** + * A split archive is refused rather than read as if its first disk were the whole of it. + */ + @Test + fun multiDiskArchiveFails() { + val bytes = archiveOf(Triple("entry", compressible, false)) + writeU16Le(bytes, endRecordOffset(bytes) + 4, 1) + assertFailsWith { ZipArchive.read(bytes) } + } + + /** + * A central directory whose entry count disagrees with its byte size fails. + */ + @Test + fun entryCountThatLiesFails() { + val bytes = archiveOf(Triple("first", compressible, false), Triple("second", compressible, false)) + val endOffset = endRecordOffset(bytes) + writeU16Le(bytes, endOffset + 8, 1) + writeU16Le(bytes, endOffset + 10, 1) + assertFailsWith { ZipArchive.read(bytes) } + } + + /** + * An end record whose fields say "look in the Zip64 records" with no Zip64 locator before it fails by + * naming those records, not as "not a ZIP": the archive is a damaged Zip64 one, which is what a bug report + * needs to say. + */ + @Test + fun zip64SentinelsWithoutALocatorNameTheMissingRecords() { + val bytes = archiveOf(Triple("a", byteArrayOf(1, 2, 3), false)) + val endRecord = endRecordOffset(bytes) + // ZIP: end record @ +0x08 and +0x0A entry counts, @ +0x0C directory size, @ +0x10 directory offset + // (APPNOTE.TXT 4.3.16), each at its "see the Zip64 record" sentinel. + writeU16Le(bytes, endRecord + 8, ZipRecords.UINT16_SENTINEL) + writeU16Le(bytes, endRecord + 10, ZipRecords.UINT16_SENTINEL) + writeU32Le(bytes, endRecord + 12, ZipRecords.UINT32_SENTINEL) + writeU32Le(bytes, endRecord + 16, ZipRecords.UINT32_SENTINEL) + + val failure = assertFailsWith { ZipArchive.read(bytes) } + + assertTrue(failure.message.orEmpty().contains("Zip64"), "the failure names the missing records: ${failure.message}") + } + + /** + * The per-entry Zip64 extra field carries only the values whose classic fields hold the sentinel, in + * APPNOTE order, and a field it is too short for fails loudly. The writer never emits one, so each shape + * is patched into a classic archive by hand. + */ + @Test + fun zip64ExtraFieldsResolveTheSentinelledFields() { + val contents = byteArrayOf(9, 8, 7, 6, 5) + val original = archiveOf(Triple("a", contents, false)) + val localOffset = localHeaderOffset(original, 0).toLong() + + val allThree = ZipArchive.read(withZip64Extra(original, sentinelSizes = true, sentinelOffset = true, values = u64sLe(contents.size.toLong(), contents.size.toLong(), localOffset))) + val entry = assertNotNull(allThree.entry("a"), "the entry lists") + assertEquals(contents.size, entry.compressedSize, "the compressed size comes from the extra") + assertEquals(contents.size, entry.uncompressedSize, "the uncompressed size comes from the extra") + assertContentEquals(contents, allThree.contents(entry), "and the offset from the extra reaches the payload") + + val offsetOnly = ZipArchive.read(withZip64Extra(original, sentinelSizes = false, sentinelOffset = true, values = u64sLe(localOffset))) + val offsetEntry = assertNotNull(offsetOnly.entry("a")) + assertEquals(contents.size, offsetEntry.uncompressedSize, "an unflagged size stays classic") + assertContentEquals(contents, offsetOnly.contents(offsetEntry), "and only the flagged offset is read from the extra") + + val tooShort = withZip64Extra(original, sentinelSizes = false, sentinelOffset = true, values = ByteArray(4)) + val shortFailure = assertFailsWith { ZipArchive.read(tooShort) } + assertTrue(shortFailure.message.orEmpty().contains("too short"), shortFailure.message) + + val otherDisk = withZip64Extra(original, sentinelSizes = false, sentinelOffset = false, values = byteArrayOf(1, 0, 0, 0), sentinelDisk = true) + val diskFailure = assertFailsWith { ZipArchive.read(otherDisk) } + assertTrue(diskFailure.message.orEmpty().contains("disk"), diskFailure.message) + } + + /** + * [archive] (one entry, no comment) with a Zip64 extended-information extra field of [values] appended to + * its central entry, the flagged classic fields set to their sentinels, and the directory size grown to + * match. + * + * @param ByteArray archive The archive to patch. + * @param Boolean sentinelSizes Whether both size fields take the sentinel. + * @param Boolean sentinelOffset Whether the local header offset takes the sentinel. + * @param ByteArray values The extra field's data, as the parser should find it. + * @param Boolean sentinelDisk Whether the disk-number field takes the sentinel. + * @return ByteArray The patched archive. + */ + private fun withZip64Extra(archive: ByteArray, sentinelSizes: Boolean, sentinelOffset: Boolean, values: ByteArray, sentinelDisk: Boolean = false): ByteArray { + val headerStart = centralHeaderOffset(archive, 0) + // ZIP: central header @ +0x14 compressed size, @ +0x18 uncompressed size, @ +0x1C name length, + // @ +0x1E extra length, @ +0x22 disk number start, @ +0x2A local header offset (APPNOTE.TXT 4.3.12). + val nameLength = readU16Le(archive, headerStart + 28) + val extraLength = readU16Le(archive, headerStart + 30) + val insertAt = headerStart + ZipRecords.CENTRAL_HEADER_SIZE + nameLength + extraLength + // ZIP: extra field header - u16 id, u16 data size (APPNOTE.TXT 4.5.2). + val extra = ByteArray(4) + values + writeU16Le(extra, 0, ZipRecords.ZIP64_EXTRA_ID) + writeU16Le(extra, 2, values.size) + val patched = archive.copyOfRange(0, insertAt) + extra + archive.copyOfRange(insertAt, archive.size) + if (sentinelSizes) { + writeU32Le(patched, headerStart + 20, ZipRecords.UINT32_SENTINEL) + writeU32Le(patched, headerStart + 24, ZipRecords.UINT32_SENTINEL) + } + if (sentinelOffset) { + writeU32Le(patched, headerStart + 42, ZipRecords.UINT32_SENTINEL) + } + if (sentinelDisk) { + writeU16Le(patched, headerStart + 34, ZipRecords.UINT16_SENTINEL) + } + writeU16Le(patched, headerStart + 30, extraLength + extra.size) + val endRecord = endRecordOffset(patched) + writeU32Le(patched, endRecord + 12, readU32Le(patched, endRecord + 12) + extra.size) + return patched + } + + /** + * [values] as consecutive little-endian 64-bit fields, the Zip64 extra field's layout. + * + * @param LongArray values The values, in field order. + * @return ByteArray The encoded fields. + */ + private fun u64sLe(vararg values: Long): ByteArray { + val bytes = ByteArray(values.size * 8) + for ((valueIndex, value) in values.withIndex()) { + for (byteIndex in 0 until 8) { + bytes[valueIndex * 8 + byteIndex] = (value ushr (8 * byteIndex)).toByte() + } + } + return bytes + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipTestSupport.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipTestSupport.kt new file mode 100644 index 0000000..eb337a7 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipTestSupport.kt @@ -0,0 +1,112 @@ +package org.umamo.format.binary + +/* + * Byte-level helpers the ZIP tests use to read and corrupt archives in place, so each malformation is + * built from a valid archive rather than hand-assembled. + */ + +/** A fixed stamp for test archives: 2026-09-16 12:34:56 local. */ +internal val TEST_DOS_DATE_TIME: Int = ZipRecords.dosDateTimeOf(2026, 9, 16, 12, 34, 56) + +/** + * Reads a little-endian unsigned 16-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the low byte. + * @return Int The value. + */ +internal fun readU16Le(bytes: ByteArray, at: Int): Int = (bytes[at].toInt() and 0xFF) or ((bytes[at + 1].toInt() and 0xFF) shl 8) + +/** + * Reads a little-endian unsigned 32-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the low byte. + * @return Long The value. + */ +internal fun readU32Le(bytes: ByteArray, at: Int): Long = readU16Le(bytes, at).toLong() or (readU16Le(bytes, at + 2).toLong() shl 16) + +/** + * Overwrites a little-endian 16-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the low byte. + * @param Int value The value. + */ +internal fun writeU16Le(bytes: ByteArray, at: Int, value: Int) { + bytes[at] = value.toByte() + bytes[at + 1] = (value ushr 8).toByte() +} + +/** + * Overwrites a little-endian 32-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the low byte. + * @param Long value The value. + */ +internal fun writeU32Le(bytes: ByteArray, at: Int, value: Long) { + writeU16Le(bytes, at, (value and 0xFFFF).toInt()) + writeU16Le(bytes, at + 2, ((value ushr 16) and 0xFFFF).toInt()) +} + +/** + * The offset of the end of central directory record of an archive with no comment. + * + * @param ByteArray archive The archive. + * @return Int The record's offset. + */ +internal fun endRecordOffset(archive: ByteArray): Int = archive.size - ZipRecords.END_SIZE + +/** + * The offset of the central directory, read from an archive with no comment. + * + * @param ByteArray archive The archive. + * @return Int The directory's offset. + */ +internal fun centralDirectoryOffset(archive: ByteArray): Int = readU32Le(archive, endRecordOffset(archive) + 16).toInt() + +/** + * The offset of the central header of the entry at [entryIndex]. + * + * @param ByteArray archive The archive, with no comment. + * @param Int entryIndex The entry's position in the directory. + * @return Int The header's offset. + */ +internal fun centralHeaderOffset(archive: ByteArray, entryIndex: Int): Int { + var position = centralDirectoryOffset(archive) + repeat(entryIndex) { + val nameLength = readU16Le(archive, position + 28) + val extraLength = readU16Le(archive, position + 30) + val commentLength = readU16Le(archive, position + 32) + position += ZipRecords.CENTRAL_HEADER_SIZE + nameLength + extraLength + commentLength + } + return position +} + +/** + * The offset of the local header of the entry at [entryIndex]. + * + * @param ByteArray archive The archive, with no comment. + * @param Int entryIndex The entry's position in the directory. + * @return Int The header's offset. + */ +internal fun localHeaderOffset(archive: ByteArray, entryIndex: Int): Int = readU32Le(archive, centralHeaderOffset(archive, entryIndex) + 42).toInt() + +/** + * An archive of the given entries, each stored or deflated as its flag says, stamped [TEST_DOS_DATE_TIME]. + * + * @param List entries Entry name, contents, and whether to deflate. + * @return ByteArray The archive. + */ +internal fun archiveOf(vararg entries: Triple): ByteArray { + val writer = ZipWriter(TEST_DOS_DATE_TIME) + for ((name, contents, deflated) in entries) { + if (deflated) { + writer.addDeflated(name, contents) + } else { + writer.addStored(name, contents) + } + } + return writer.finish() +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipWriterTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipWriterTest.kt new file mode 100644 index 0000000..c25bc31 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/binary/ZipWriterTest.kt @@ -0,0 +1,223 @@ +package org.umamo.format.binary + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins the ZIP writer's byte layout - the parts other code relies on without reading the archive back: + * the fixed mimetype offset, byte-reproducible output, and when Zip64 records appear. In commonTest, so + * the layout compiles for Kotlin/Native. + */ +class ZipWriterTest { + private val mimetype = "application/vnd.umamo.uma+zip".encodeToByteArray() + + /** + * Whether [signature] occurs anywhere in [bytes]. + * + * @param ByteArray bytes The buffer to scan. + * @param Int signature The little-endian 32-bit signature. + * @return Boolean True when it occurs. + */ + private fun containsSignature(bytes: ByteArray, signature: Int): Boolean = + (0..bytes.size - 4).any { offset -> readU32Le(bytes, offset) == signature.toLong() } + + /** + * A stored first entry's payload starts at offset 30 plus its name length - 38 for "mimetype" - because + * the writer emits no extra field. The UMA identification probe reads it there without parsing the ZIP. + */ + @Test + fun storedMimetypeSitsAtOffset38() { + val writer = ZipWriter(TEST_DOS_DATE_TIME) + writer.addStored("mimetype", mimetype) + writer.addDeflated("manifest.json", "{}".encodeToByteArray()) + val bytes = writer.finish() + assertEquals(0, readU16Le(bytes, 28), "no extra field on the first local header") + assertContentEquals("mimetype".encodeToByteArray(), bytes.copyOfRange(30, 38), "the name follows the fixed header") + assertContentEquals(mimetype, bytes.copyOfRange(38, 38 + mimetype.size), "the payload sits at offset 38") + } + + /** + * The same entries and stamp always produce the same bytes, and the stamp is the only clock in them. + */ + @Test + fun outputIsAPureFunctionOfEntriesAndStamp() { + /** + * Writes the fixed test entries under a stamp. + * + * @param Int stamp The DOS date and time. + * @return ByteArray The archive. + */ + fun write(stamp: Int): ByteArray { + val writer = ZipWriter(stamp) + writer.addStored("mimetype", mimetype) + writer.addDeflated("model/puppet.json", ByteArray(5000) { byteIndex -> (byteIndex % 7).toByte() }) + writer.addStored("textures/", ByteArray(0)) + return writer.finish() + } + assertContentEquals(write(TEST_DOS_DATE_TIME), write(TEST_DOS_DATE_TIME), "identical inputs, identical bytes") + val epoch = write(ZipRecords.DOS_EPOCH_DATE_TIME) + assertFalse(write(TEST_DOS_DATE_TIME).contentEquals(epoch), "the stamp reaches the bytes") + // ZIP: local header @ +0x0A time, @ +0x0C date. + assertEquals(ZipRecords.DOS_EPOCH_DATE_TIME and 0xFFFF, readU16Le(epoch, 10), "local time field") + assertEquals(ZipRecords.DOS_EPOCH_DATE_TIME ushr 16, readU16Le(epoch, 12), "local date field") + } + + /** + * Every header declares a UTF-8 name and carries its sizes up front, with no data descriptor. + */ + @Test + fun headersDeclareUtf8NamesAndInlineSizes() { + val bytes = archiveOf(Triple("ページ", ByteArray(300) { 1 }, true)) + val localFlags = readU16Le(bytes, 6) + assertEquals(ZipRecords.FLAG_UTF8_NAME, localFlags, "local flags: UTF-8 name, no data descriptor") + assertEquals(ZipRecords.FLAG_UTF8_NAME, readU16Le(bytes, centralHeaderOffset(bytes, 0) + 8), "central flags") + assertTrue(readU32Le(bytes, 18) > 0, "the local header carries the compressed size") + assertEquals(300L, readU32Le(bytes, 22), "the local header carries the uncompressed size") + assertFalse(containsSignature(bytes, ZipRecords.DATA_DESCRIPTOR_SIGNATURE), "no data descriptor") + } + + /** + * Zip64 end records appear exactly when the entry count reaches the classic field's reserved all-ones + * value, and an archive on either side of that line reads back whole. + */ + @Test + fun zip64RecordsAppearOnlyWhenTheEntryCountNeedsThem() { + for (entryCount in listOf(0xFFFE, 0xFFFF)) { + val writer = ZipWriter(TEST_DOS_DATE_TIME) + repeat(entryCount) { entryIndex -> + writer.addStored("e$entryIndex", ByteArray(0)) + } + val bytes = writer.finish() + val needsZip64 = entryCount >= 0xFFFF + val endOffset = endRecordOffset(bytes) + assertEquals(if (needsZip64) 0xFFFF else entryCount, readU16Le(bytes, endOffset + 10), "$entryCount entries: classic count field") + assertEquals( + needsZip64, + readU32Le(bytes, endOffset - ZipRecords.ZIP64_LOCATOR_SIZE) == ZipRecords.ZIP64_LOCATOR_SIGNATURE.toLong(), + "$entryCount entries: Zip64 locator present", + ) + val archive = ZipArchive.read(bytes) + assertEquals(entryCount, archive.entries.size, "$entryCount entries read back") + assertEquals("e${entryCount - 1}", archive.entries.last().name, "$entryCount entries: the last one is intact") + } + } + + /** + * Copying every entry raw, under the same stamp, reproduces the archive byte for byte. + */ + @Test + fun rawCopyReproducesTheArchive() { + val original = + archiveOf( + Triple("mimetype", mimetype, false), + Triple("model/puppet.json", ByteArray(20_000) { byteIndex -> (byteIndex % 11).toByte() }, true), + Triple("textures/tile-0.png", ByteArray(700) { byteIndex -> byteIndex.toByte() }, false), + ) + val source = ZipArchive.read(original) + val copier = ZipWriter(TEST_DOS_DATE_TIME) + for (entry in source.entries) { + copier.addRaw(entry, source.rawPayload(entry)) + } + assertContentEquals(original, copier.finish(), "a raw copy is byte-identical") + } + + /** + * A raw copy's payload must match the size the entry declares. + */ + @Test + fun rawCopyRejectsAMismatchedPayload() { + val source = ZipArchive.read(archiveOf(Triple("entry", ByteArray(100) { 3 }, true))) + val entry = source.entries.single() + assertFailsWith { ZipWriter(TEST_DOS_DATE_TIME).addRaw(entry, source.rawPayload(entry).copyOf(1)) } + } + + /** + * A raw copy of an encrypted entry whose source used a data descriptor keeps the flag, its source's timestamp, and + * the descriptor, which traditional decryption checks against; an unencrypted one is written like any other entry. + */ + @Test + fun rawCopyKeepsWhatDecryptionChecks() { + val bytes = archiveOf(Triple("secret", ByteArray(300) { byteIndex -> (byteIndex % 7).toByte() }, true), Triple("plain", ByteArray(40) { 5 }, false)) + for (entryIndex in 0..1) { + val header = centralHeaderOffset(bytes, entryIndex) + val extraFlags = if (entryIndex == 0) ZipRecords.FLAG_ENCRYPTED or ZipRecords.FLAG_DATA_DESCRIPTOR else ZipRecords.FLAG_DATA_DESCRIPTOR + writeU16Le(bytes, header + 8, readU16Le(bytes, header + 8) or extraFlags) + } + val source = ZipArchive.read(bytes) + val copier = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + for (entry in source.entries) { + copier.addRaw(entry, source.rawPayload(entry)) + } + val copied = copier.finish() + val archive = ZipArchive.read(copied) + val secret = archive.entry("secret")!! + val plain = archive.entry("plain")!! + assertEquals(ZipRecords.FLAG_ENCRYPTED or ZipRecords.FLAG_DATA_DESCRIPTOR, secret.flags and (ZipRecords.FLAG_ENCRYPTED or ZipRecords.FLAG_DATA_DESCRIPTOR), "the encrypted entry keeps its descriptor flag") + assertEquals(TEST_DOS_DATE_TIME, secret.dosDateTime, "and its source's timestamp") + assertEquals(0, plain.flags and ZipRecords.FLAG_DATA_DESCRIPTOR, "an unencrypted entry drops the flag") + assertEquals(ZipRecords.DOS_EPOCH_DATE_TIME, plain.dosDateTime, "and takes this writer's timestamp") + + val local = localHeaderOffset(copied, 0) + assertEquals(0L, readU32Le(copied, local + 14), "the local header leaves the CRC-32 to the descriptor") + assertEquals(0L, readU32Le(copied, local + 18), "and the compressed size") + val descriptor = secret.payloadOffset + secret.compressedSize + assertEquals(ZipRecords.DATA_DESCRIPTOR_SIGNATURE.toLong(), readU32Le(copied, descriptor), "a descriptor follows the payload") + assertEquals(secret.crc32, readU32Le(copied, descriptor + 4)) + assertEquals(secret.compressedSize.toLong(), readU32Le(copied, descriptor + 8)) + assertEquals(secret.uncompressedSize.toLong(), readU32Le(copied, descriptor + 12)) + assertContentEquals(source.rawPayload(source.entry("secret")!!), archive.rawPayload(secret), "and the payload is unchanged") + } + + /** + * A raw copy keeps a version needed higher than its method's, as an entry this writer never produces declares. + */ + @Test + fun rawCopyKeepsTheVersionNeeded() { + val bytes = archiveOf(Triple("aes", ByteArray(50) { 9 }, false)) + // ZIP: method 99 is AES encryption, which needs version 5.1 (APPNOTE.TXT 4.4.3, 4.4.5); patched into both headers. + writeU16Le(bytes, centralHeaderOffset(bytes, 0) + 10, 99) + writeU16Le(bytes, localHeaderOffset(bytes, 0) + 8, 99) + writeU16Le(bytes, centralHeaderOffset(bytes, 0) + 6, 51) + val source = ZipArchive.read(bytes) + val copier = ZipWriter(TEST_DOS_DATE_TIME) + copier.addRaw(source.entries.single(), source.rawPayload(source.entries.single())) + val copied = copier.finish() + assertEquals(51, ZipArchive.read(copied).entries.single().versionNeeded, "the central header keeps it") + assertEquals(51, readU16Le(copied, localHeaderOffset(copied, 0) + 4), "and so does the local header") + } + + /** + * An entry the writer refuses leaves nothing behind: its name is still free, so the refusal a retry meets is the + * one it earned. + */ + @Test + fun aRefusedEntryLeavesTheNameFree() { + val writer = ZipWriter(TEST_DOS_DATE_TIME) + val tooLong = "n".repeat(70_000) + assertFailsWith { writer.addStored(tooLong, ByteArray(1)) } + val retry = assertFailsWith { writer.addStored(tooLong, ByteArray(1)) } + assertTrue(retry.message.orEmpty().contains("longer than a ZIP header can hold"), "the retry meets the length rule again: ${retry.message}") + writer.addStored("entry", ByteArray(1)) + assertEquals(listOf("entry"), ZipArchive.read(writer.finish()).entries.map { entry -> entry.name }, "and the archive holds only what was accepted") + } + + /** + * The writer refuses what would make an ambiguous or broken archive: a repeated or empty name, a DEFLATE + * level out of range, and anything added after finishing. + */ + @Test + fun rejectsInvalidUse() { + val writer = ZipWriter(TEST_DOS_DATE_TIME) + writer.addStored("entry", ByteArray(1)) + assertFailsWith("repeated name") { writer.addDeflated("entry", ByteArray(1)) } + assertFailsWith("empty name") { writer.addStored("", ByteArray(1)) } + assertFailsWith("level out of range") { writer.addDeflated("other", ByteArray(1), 10) } + writer.finish() + assertFailsWith("add after finish") { writer.addStored("late", ByteArray(1)) } + assertFailsWith("finish twice") { writer.finish() } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/bmp/BmpCodecTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/bmp/BmpCodecTest.kt new file mode 100644 index 0000000..a28d046 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/bmp/BmpCodecTest.kt @@ -0,0 +1,102 @@ +package org.umamo.format.bmp + +import okio.Buffer +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Exercises [BmpCodec] without a committed corpus: the 32-bit BITMAPV4HEADER writer round-trips + * straight alpha losslessly, a hand-built 24-bit BI_RGB file pins the read path (BGR order, bottom-up + * rows, 4-byte row padding), and a BMP -> PNG cross-check confirms both codecs share the neutral + * RGBA representation. + */ +class BmpCodecTest { + private fun bytes(vararg values: Int): ByteArray = ByteArray(values.size) { values[it].toByte() } + + /** + * Builds an uncompressed 24-bit BI_RGB BMP (bottom-up, 4-byte-padded rows) from top-first RGB. + * + * @param Int width Image width. + * @param Int height Image height. + * @param ByteArray rgbTopFirst Row-major R,G,B samples, top row first (width * height * 3). + * @return ByteArray The complete `.bmp` file. + */ + private fun buildBmp24(width: Int, height: Int, rgbTopFirst: ByteArray): ByteArray { + val rowStride = ((24 * width + 31) / 32) * 4 + val pixelData = ByteArray(rowStride * height) + for (imageRow in 0 until height) { + val fileRow = height - 1 - imageRow // bottom-up storage + var destination = fileRow * rowStride + for (column in 0 until width) { + val source = (imageRow * width + column) * 3 + pixelData[destination++] = rgbTopFirst[source + 2] // B + pixelData[destination++] = rgbTopFirst[source + 1] // G + pixelData[destination++] = rgbTopFirst[source] // R + } + } + val offBits = 14 + 40 + val out = Buffer() + out.writeByte(0x42) + out.writeByte(0x4D) + out.writeIntLe(offBits + pixelData.size) + out.writeShortLe(0) + out.writeShortLe(0) + out.writeIntLe(offBits) + out.writeIntLe(40) // BITMAPINFOHEADER + out.writeIntLe(width) + out.writeIntLe(height) + out.writeShortLe(1) + out.writeShortLe(24) + out.writeIntLe(0) // BI_RGB + out.writeIntLe(pixelData.size) + out.writeIntLe(2835) + out.writeIntLe(2835) + out.writeIntLe(0) + out.writeIntLe(0) + out.write(pixelData) + return out.readByteArray() + } + + @Test + fun writeThenReadRoundTripsRgbaWithAlpha() { + val source = + RasterImage( + width = 2, + height = 2, + rgba = bytes(10, 20, 30, 40, 50, 60, 70, 255, 80, 90, 100, 128, 200, 210, 220, 64), + ) + val decoded = BmpCodec.read(BmpCodec.write(source)) + assertEquals(2, decoded.width) + assertEquals(2, decoded.height) + assertContentEquals(source.rgba, decoded.rgba, "straight alpha survives the 32-bit V4 round-trip") + } + + @Test + fun readsHandBuilt24BitBmpAsOpaqueRgba() { + val rgb = bytes(255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0) + val decoded = BmpCodec.read(buildBmp24(width = 2, height = 2, rgbTopFirst = rgb)) + val expected = bytes(255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255) + assertContentEquals(expected, decoded.rgba) + } + + @Test + fun bmpAndPngShareTheNeutralRepresentation() { + val width = 6 + val height = 4 + val rgba = ByteArray(width * height * 4) { (it * 5 % 256).toByte() } + val throughBmp = BmpCodec.read(BmpCodec.write(RasterImage(width, height, rgba))) + val throughPng = PngCodec.read(PngCodec.write(throughBmp)) + assertContentEquals(rgba, throughPng.rgba, "RGBA -> BMP -> PNG -> RGBA is lossless") + } + + @Test + fun matchesOnlyTheBmSignature() { + val bmp = BmpCodec.write(RasterImage(1, 1, bytes(1, 2, 3, 4))) + assertTrue(BmpCodec.matches(bmp), "BM-prefixed bytes match") + assertTrue(!BmpCodec.matches(bytes(0x00, 0x4D, 1, 2)), "non-BM bytes do not match") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/clip/ClipContainerTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/clip/ClipContainerTest.kt new file mode 100644 index 0000000..05da705 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/clip/ClipContainerTest.kt @@ -0,0 +1,79 @@ +package org.umamo.format.clip + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins the CSFCHUNK container walk on hand-assembled bytes - the one CLIP layer that needs no + * SQLite, and therefore the coverage that survives a corpus-less run. Every failure path of + * extractSqliteDatabase is reachable synthetically. + */ +class ClipContainerTest { + private val databaseSentinel = byteArrayOf(0x53, 0x51, 0x4C, 0x69, 0x74, 0x65, 0x21) + + /** A well-formed container: header chunk, the database, and the footer terminator. */ + private fun wellFormedContainer(): ByteArray = + syntheticClipContainer( + listOf( + "CHNKHead" to byteArrayOf(1, 2, 3, 4), + "CHNKSQLi" to databaseSentinel, + "CHNKFoot" to byteArrayOf(), + ), + ) + + /** The magic sniff accepts a synthetic container and rejects anything else. */ + @Test + fun isClipMatchesOnlyTheContainerMagic() { + assertTrue(ClipContainer.isClip(wellFormedContainer())) + assertFalse(ClipContainer.isClip("NOTACLIP".encodeToByteArray())) + assertFalse(ClipContainer.isClip(byteArrayOf(0x43)), "a short buffer never matches") + } + + /** The extraction returns the CHNKSQLi payload as a fresh copy, not a view into the container. */ + @Test + fun extractReturnsTheSqlitePayloadAsACopy() { + val container = wellFormedContainer() + val extracted = ClipContainer.extractSqliteDatabase(container) + assertContentEquals(databaseSentinel, extracted) + extracted[0] = 0 + assertContentEquals(databaseSentinel, ClipContainer.extractSqliteDatabase(container), "mutating the result must not alias the container") + } + + /** A missing magic is rejected before any chunk walk. */ + @Test + fun extractFailsOnMissingMagic() { + assertFailsWith { + ClipContainer.extractSqliteDatabase("NOTACLIPatall".encodeToByteArray()) + } + } + + /** A database chunk whose declared size runs past EOF is rejected rather than truncated. */ + @Test + fun extractFailsWhenTheSqlitePayloadRunsPastEof() { + val container = wellFormedContainer() + // CLIP: chunk size u64 immediately after the 8-byte id; the CHNKSQLi header sits after the + // 24-byte preamble and the 20-byte CHNKHead chunk, so its size field starts at 24 + 20 + 8. + val sqliteSizeOffset = 24 + (16 + 4) + 8 + container[sqliteSizeOffset + 7] = 0x7F + assertFailsWith { ClipContainer.extractSqliteDatabase(container) } + } + + /** A container that ends (or hits the footer) without a database chunk is an error. */ + @Test + fun extractFailsWithoutASqliteChunk() { + val footerOnly = syntheticClipContainer(listOf("CHNKHead" to byteArrayOf(1), "CHNKFoot" to byteArrayOf())) + assertFailsWith { ClipContainer.extractSqliteDatabase(footerOnly) } + val sqliteAfterFooter = syntheticClipContainer(listOf("CHNKFoot" to byteArrayOf(), "CHNKSQLi" to databaseSentinel)) + assertFailsWith { ClipContainer.extractSqliteDatabase(sqliteAfterFooter) } + } + + /** A head offset outside the addressable range is rejected rather than wrapped. */ + @Test + fun extractFailsOnHeadOffsetOverflow() { + val container = syntheticClipContainer(listOf("CHNKSQLi" to databaseSentinel), headOffset = Long.MAX_VALUE) + assertFailsWith { ClipContainer.extractSqliteDatabase(container) } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/clip/ClipTestContainers.kt b/module/format/src/commonTest/kotlin/org/umamo/format/clip/ClipTestContainers.kt new file mode 100644 index 0000000..df10c24 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/clip/ClipTestContainers.kt @@ -0,0 +1,50 @@ +package org.umamo.format.clip + +/* + * Synthetic CSFCHUNK container assembly for tests. Lives in commonTest so the jvmTest synthetic + * ClipReader test (which additionally needs a real SQLite driver) can reuse the same builder via the + * test source-set hierarchy. + */ + +/** + * Assembles a synthetic .clip container around the given chunks. + * + * Layout per docs/format/CLIP.md (all integers big-endian): + * // CLIP: @ +0x00 "CSFCHUNK" (8) container magic + * // CLIP: @ +0x08 fileSize u64 whole-file length + * // CLIP: @ +0x10 headOffset u64 offset of the first chunk (= 24) + * // CLIP: then [8-byte ASCII id][u64 size][payload] repeated + * + * @param List chunks The chunk id (8 ASCII characters) to payload pairs, in file order. + * @param Long headOffset The first-chunk offset to stamp at +0x10 (24 in every real file). + * @return ByteArray The assembled container bytes. + */ +internal fun syntheticClipContainer(chunks: List>, headOffset: Long = 24): ByteArray { + val chunkBytes = chunks.sumOf { (_, payload) -> 16 + payload.size } + val container = ByteArray(24 + chunkBytes) + "CSFCHUNK".encodeToByteArray().copyInto(container, 0) + writeUInt64BigEndian(container, 8, container.size.toLong()) + writeUInt64BigEndian(container, 16, headOffset) + var offset = 24 + for ((chunkId, payload) in chunks) { + require(chunkId.length == 8) { "chunk id must be 8 ASCII characters: '$chunkId'" } + chunkId.encodeToByteArray().copyInto(container, offset) + writeUInt64BigEndian(container, offset + 8, payload.size.toLong()) + payload.copyInto(container, offset + 16) + offset += 16 + payload.size + } + return container +} + +/** + * Writes a big-endian unsigned 64-bit integer. + * + * @param ByteArray bytes The buffer to write into. + * @param Int at The offset of the most-significant byte. + * @param Long value The value to write. + */ +private fun writeUInt64BigEndian(bytes: ByteArray, at: Int, value: Long) { + for (byteIndex in 0 until 8) { + bytes[at + byteIndex] = ((value ushr ((7 - byteIndex) * 8)) and 0xFF).toByte() + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/Cmo3VersionTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/Cmo3VersionTest.kt new file mode 100644 index 0000000..947c2c1 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/Cmo3VersionTest.kt @@ -0,0 +1,35 @@ +package org.umamo.format.cmo3 + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class Cmo3VersionTest { + @Test + fun everyVersionDescribesItself() { + // If a new Cmo3Version is added, `describe()` won't compile until handled - this test just + // confirms the wired-up path produces a non-empty label for each known version. + val all = listOf(Cmo3Version.V3, Cmo3Version.V4, Cmo3Version.V5) + all.forEach { version -> + assertTrue(version.describe().isNotEmpty(), "describe() empty for $version") + } + } + + @Test + fun fileFormatVersionMapsByLeadingGenerationDigit() { + // Observed corpus values - CMO3.md §3 Document shape. + assertEquals(Cmo3Version.V4, Cmo3Version.fromFileFormatVersion("401010001"), "Cubism 4.x sample") + assertEquals(Cmo3Version.V4, Cmo3Version.fromFileFormatVersion("400050002"), "second Cubism 4.x sample") + assertEquals(Cmo3Version.V5, Cmo3Version.fromFileFormatVersion("501030000"), "Cubism 5.x sample") + assertEquals(Cmo3Version.V3, Cmo3Version.fromFileFormatVersion("300000000"), "Cubism 3.x generation") + } + + @Test + fun fileFormatVersionRejectsUnknownOrMalformedValues() { + assertNull(Cmo3Version.fromFileFormatVersion(""), "empty string") + assertNull(Cmo3Version.fromFileFormatVersion("not-a-number"), "garbage text") + assertNull(Cmo3Version.fromFileFormatVersion("601030000"), "unknown future generation") + assertNull(Cmo3Version.fromFileFormatVersion("42"), "too small to carry a generation digit") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/SanityTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/SanityTest.kt new file mode 100644 index 0000000..c021c84 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/SanityTest.kt @@ -0,0 +1,12 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.caff.CaffArchive +import kotlin.test.Test +import kotlin.test.assertEquals + +class SanityTest { + @Test + fun caffMagicIsStable() { + assertEquals("CAFF", CaffArchive.MAGIC) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/TargetVersionNoTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/TargetVersionNoTest.kt new file mode 100644 index 0000000..7d454d4 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/TargetVersionNoTest.kt @@ -0,0 +1,51 @@ +package org.umamo.format.cmo3 + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class TargetVersionNoTest { + @Test + fun decodesEveryObservedLiteral() { + // CMO3: CModelSource field targetVersionNo - the corpus-observed per-era literals. + assertEquals(Cmo3TargetVersion.V30, Cmo3TargetVersion.fromVersionNo(3_000), "Cubism 3.0") + assertEquals(Cmo3TargetVersion.V33, Cmo3TargetVersion.fromVersionNo(3_030), "Cubism 3.3") + assertEquals(Cmo3TargetVersion.V40, Cmo3TargetVersion.fromVersionNo(400_000), "Cubism 4.0") + assertEquals(Cmo3TargetVersion.V42, Cmo3TargetVersion.fromVersionNo(4_020_000), "Cubism 4.2") + assertEquals(Cmo3TargetVersion.V50, Cmo3TargetVersion.fromVersionNo(5_000_000), "Cubism 5.0") + assertEquals(Cmo3TargetVersion.V53, Cmo3TargetVersion.fromVersionNo(5_030_000), "Cubism 5.3") + } + + @Test + fun decodesModernSchemeAliasesForTheLegacyVersions() { + // The 4.2+ scheme applied to the older versions is accepted on read even though the editor + // has not been observed writing it - a tolerant-read fallback only. + assertEquals(Cmo3TargetVersion.V30, Cmo3TargetVersion.fromVersionNo(3_000_000), "modern 3.0 alias") + assertEquals(Cmo3TargetVersion.V33, Cmo3TargetVersion.fromVersionNo(3_030_000), "modern 3.3 alias") + assertEquals(Cmo3TargetVersion.V40, Cmo3TargetVersion.fromVersionNo(4_000_000), "modern 4.0 alias") + } + + @Test + fun versionLessValuesDecodeToNull() { + assertNull(Cmo3TargetVersion.fromVersionNo(null), "absent field") + assertNull(Cmo3TargetVersion.fromVersionNo(0), "zero") + assertNull(Cmo3TargetVersion.fromVersionNo(42), "garbage") + assertNull(Cmo3TargetVersion.fromVersionNo(6_000_000), "unknown future version") + assertNull(Cmo3TargetVersion.fromVersionNo(-3_000), "negative") + } + + @Test + fun latestSentinelIsVersionLess() { + // The SDK(N/A)/Latest selection names the absence of a target version, so the confirmed + // sentinel decodes to null while remaining a first-class write value via the constant. + assertEquals(9_000_000, Cmo3TargetVersion.LATEST_VERSION_NO) + assertNull(Cmo3TargetVersion.fromVersionNo(Cmo3TargetVersion.LATEST_VERSION_NO)) + } + + @Test + fun everyVersionRoundTripsThroughItsLiteral() { + Cmo3TargetVersion.entries.forEach { version -> + assertEquals(version, Cmo3TargetVersion.fromVersionNo(version.versionNo), "round trip for $version") + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/caff/CaffRoundTripTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/caff/CaffRoundTripTest.kt new file mode 100644 index 0000000..60220c7 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/caff/CaffRoundTripTest.kt @@ -0,0 +1,59 @@ +package org.umamo.format.cmo3.caff + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Platform-independent CAFF codec tests using synthetic archives (no sample/jar needed). + */ +class CaffRoundTripTest { + private fun assertEntriesEqual(expected: CaffEntry, actual: CaffEntry) { + assertEquals(expected.path, actual.path) + assertEquals(expected.tag, actual.tag) + assertEquals(expected.compression, actual.compression) + assertEquals(expected.obfuscated, actual.obfuscated) + assertContentEquals(expected.content, actual.content, "content of ${expected.path}") + } + + @Test + fun roundTripsObfuscatedMixedCompression() { + val entries = + listOf( + CaffEntry("raw.bin", "", byteArrayOf(0, 1, 2, 3, 0x7F, -1, -128), CompressOption.RAW, obfuscated = true), + CaffEntry("doc.xml", CaffArchive.TAG_MAIN_XML, "テスト".encodeToByteArray(), CompressOption.FAST, obfuscated = true), + CaffEntry("plain.txt", "", "no-xor".encodeToByteArray(), CompressOption.RAW, obfuscated = false), + ) + val archive = CaffArchive(obfuscateKey = 0xD7FC71B1.toInt(), entries = entries) + + val bytes = CaffCodec.write(archive) + assertEquals("CAFF", bytes.copyOfRange(0, 4).decodeToString()) + // Guard bytes 'b','c' terminate the blob region. + assertEquals(0x62, bytes[bytes.size - 2].toInt() and 0xFF) + assertEquals(0x63, bytes[bytes.size - 1].toInt() and 0xFF) + + val reparsed = CaffCodec.read(bytes) + assertEquals(archive.obfuscateKey, reparsed.obfuscateKey) + assertEquals(archive.formatIdentifier, reparsed.formatIdentifier) + assertEquals(entries.size, reparsed.entries.size) + for (index in entries.indices) assertEntriesEqual(entries[index], reparsed.entries[index]) + assertEquals(CaffArchive.TAG_MAIN_XML, reparsed.firstByTag(CaffArchive.TAG_MAIN_XML)?.tag) + } + + @Test + fun roundTripsUnobfuscatedArchive() { + val entries = listOf(CaffEntry("a.bin", "", byteArrayOf(10, 20, 30), CompressOption.RAW, obfuscated = false)) + val archive = CaffArchive(obfuscateKey = 0, entries = entries) + val reparsed = CaffCodec.read(CaffCodec.write(archive)) + assertEquals(0, reparsed.obfuscateKey) + assertEntriesEqual(entries[0], reparsed.entries[0]) + } + + @Test + fun emptyArchiveHasNoPreview() { + val reparsed = CaffCodec.read(CaffCodec.write(CaffArchive())) + assertEquals(0, reparsed.entries.size) + assertTrue(!reparsed.preview.present) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/caff/CaffZipFramingTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/caff/CaffZipFramingTest.kt new file mode 100644 index 0000000..27ffa98 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/caff/CaffZipFramingTest.kt @@ -0,0 +1,171 @@ +package org.umamo.format.cmo3.caff + +import org.umamo.format.binary.ZipRecords +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the byte layout of a CAFF compressed blob, measured from the corpus (see CMO3.md §1). + * + * [CaffRoundTripTest] cannot cover this: it round-trips through our own reader, which any + * self-consistent zip passes — including one carrying a central directory the format does not have. + * The layout is only observable by asserting on the bytes, so it is asserted here, corpus-free, so it + * runs on every target including Kotlin/Native. + */ +class CaffZipFramingTest { + // Compressible enough that the payload is unambiguously deflated rather than stored. + private val contents = ByteArray(20_000) { (it % 11).toByte() } + + /** + * Reads a little-endian unsigned 16-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the low byte. + * @return Int The value. + */ + private fun readU16(bytes: ByteArray, at: Int): Int = (bytes[at].toInt() and 0xFF) or ((bytes[at + 1].toInt() and 0xFF) shl 8) + + /** + * Reads a little-endian unsigned 32-bit value. + * + * @param ByteArray bytes The buffer. + * @param Int at Offset of the low byte. + * @return Long The value. + */ + private fun readU32(bytes: ByteArray, at: Int): Long = + (0 until 4).fold(0L) { accumulated, byteIndex -> + accumulated or ((bytes[at + byteIndex].toLong() and 0xFF) shl (8 * byteIndex)) + } + + /** + * Finds every offset at which [signature] occurs in [bytes]. + * + * @param ByteArray bytes The buffer to scan. + * @param Long signature The little-endian 32-bit signature. + * @return List The matching offsets. + */ + private fun occurrencesOf(bytes: ByteArray, signature: Long): List = + (0..bytes.size - 4).filter { offset -> readU32(bytes, offset) == signature } + + @Test + fun localHeaderMatchesWhatTheEditorWrites() { + val framed = CaffZip.zipSingle(contents, 1) + // Measured from Erica Tamamo.cmo3 after de-obfuscating (XOR 0xB1). + assertEquals(0x04034B50L, readU32(framed, 0), "local file header signature") + assertEquals(20, readU16(framed, 4), "version needed = 2.0, the minimum that understands DEFLATE") + assertEquals(0x0808, readU16(framed, 6), "flags: bit 3 (data descriptor) + bit 11 (UTF-8 name)") + assertEquals(8, readU16(framed, 8), "method 8 = DEFLATE") + // Flag bit 3's whole meaning: the real values live in the trailing descriptor, not here. + assertEquals(0L, readU32(framed, 14), "crc32 is zeroed in the local header") + assertEquals(0L, readU32(framed, 18), "compressed size is zeroed in the local header") + assertEquals(0L, readU32(framed, 22), "uncompressed size is zeroed in the local header") + assertEquals(8, readU16(framed, 26), "name length") + assertEquals(0, readU16(framed, 28), "extra length") + assertEquals("contents", framed.copyOfRange(30, 38).decodeToString(), "entry name") + } + + @Test + fun blobEndsAtItsDataDescriptorWithNoCentralDirectory() { + val framed = CaffZip.zipSingle(contents, 1) + // Sanity FIRST: an absence assertion is worthless if the scanner can never find anything, and + // a vacuously-empty occurrencesOf would pass both checks below while proving nothing. Pin that + // it locates the one signature we know is present before trusting it about the ones that are not. + assertEquals(listOf(0), occurrencesOf(framed, 0x04034B50L), "the scanner must find the local header at offset 0") + + // The load-bearing fact. A CAFF blob is a PARTIAL zip: ZipOutputStream would append both of + // these on close, adding 76 bytes per compressed entry to every save. The corpus sample has + // zero of either, and re-emitting without them reproduces its exact file size. + assertEquals(emptyList(), occurrencesOf(framed, 0x02014B50L), "there must be no central directory record") + assertEquals(emptyList(), occurrencesOf(framed, 0x06054B50L), "there must be no end-of-central-directory record") + + val descriptorStart = framed.size - 16 + assertEquals(0x08074B50L, readU32(framed, descriptorStart), "the blob ends with its data descriptor") + assertEquals(contents.size.toLong(), readU32(framed, descriptorStart + 12), "the descriptor declares the uncompressed size") + assertEquals((framed.size - 16 - 38).toLong(), readU32(framed, descriptorStart + 8), "the descriptor declares the compressed size") + } + + @Test + fun dosStampEncoderReproducesTheEditorsOwnBytes() { + // A free oracle: the corpus sample's local header reads DOS time 0x886F / date 0x54C6, which + // decodes to 2022-06-06 17:03:30. Feeding that date back through the encoder must reproduce + // those exact halves — so this pins the bit packing against real editor output rather than + // against my own reading of the spec. + val stamp = ZipRecords.dosDateTimeOf(2022, 6, 6, 17, 3, 30) + assertEquals(0x54C6, (stamp ushr 16) and 0xFFFF, "date: year-1980 in bits 15..9, month 8..5, day 4..0") + assertEquals(0x886F, stamp and 0xFFFF, "time: hour 15..11, minute 10..5, seconds HALVED into 4..0") + } + + @Test + fun theStampLandsInTheLocalHeaderLittleEndian() { + val stamp = ZipRecords.dosDateTimeOf(2022, 6, 6, 17, 3, 30) + val framed = CaffZip.zipSingle(contents, 1, stamp) + assertEquals(0x886F, readU16(framed, 10), "local header @ +0x0A is the DOS time") + assertEquals(0x54C6, readU16(framed, 12), "local header @ +0x0C is the DOS date") + } + + @Test + fun oddSecondsAndTheEpochBoundaryEncodeWithoutWrapping() { + // Two-second resolution: 31 and 30 are indistinguishable once halved. + assertEquals( + ZipRecords.dosDateTimeOf(2022, 6, 6, 17, 3, 30), + ZipRecords.dosDateTimeOf(2022, 6, 6, 17, 3, 31), + "an odd second truncates to the same stamp rather than rounding into the next minute", + ) + // A year outside 1980..2107 has no 7-bit representation. It must clamp, not wrap into a + // wrong-but-plausible year — a silently mangled date is worse than an obviously epochal one. + val epoch = (0x0021 shl 16) + assertEquals(epoch, ZipRecords.dosDateTimeOf(1979, 12, 31, 23, 59, 58), "a pre-epoch year clamps to 1980-01-01") + assertEquals(epoch, ZipRecords.dosDateTimeOf(2108, 1, 1, 0, 0, 0), "a past-ceiling year clamps to 1980-01-01") + assertEquals(0x0021, (ZipRecords.dosDateTimeOf(1980, 1, 1, 0, 0, 0) ushr 16) and 0xFFFF, "the epoch itself encodes exactly") + } + + @Test + fun aRealSaveStampsAPlausibleClockNotTheEpoch() { + // The default path is the wall clock, matching the editor. Guards the wiring: a stamp stuck at + // the epoch would mean currentDosDateTime() never reached the header. + val framed = CaffZip.zipSingle(contents, 1) + val year = ((readU16(framed, 12) ushr 9) and 0x7F) + 1980 + assertTrue(year >= 2020, "a real save must carry a current-looking year, not the DOS epoch; got $year") + } + + @Test + fun inflateIsBoundedByTheDeclaredUncompressedSize() { + // storedSize bounds the INPUT only; DEFLATE reaches ~1000:1, so the descriptor's usize is the + // only thing capping the output. A descriptor that lies must truncate its own entry, not + // allocate on the reader's behalf. + val framed = CaffZip.zipSingle(contents, 1) + val lying = framed.copyOf() + lying[lying.size - 4] = 100 + lying[lying.size - 3] = 0 + lying[lying.size - 2] = 0 + lying[lying.size - 1] = 0 + assertEquals(100, CaffZip.unzipSingle(lying).size, "a declared size of 100 caps the inflate at 100 bytes") + } + + @Test + fun unrecognizableDescriptorFallsBackToUnboundedRatherThanTruncating() { + // The fallback must not corrupt a valid read: better unbounded than silently short. + val framed = CaffZip.zipSingle(contents, 1) + val mangled = framed.copyOf() + mangled[mangled.size - 16] = 0x00 + assertContentEquals(contents, CaffZip.unzipSingle(mangled), "a blob with no usable descriptor still inflates fully") + + val zeroed = framed.copyOf() + for (offset in zeroed.size - 4 until zeroed.size) { + zeroed[offset] = 0 + } + assertContentEquals(contents, CaffZip.unzipSingle(zeroed), "a zero declared size reads as absent, not as an empty entry") + } + + @Test + fun roundTripsAtEveryCompressionLevelInUse() { + // CompressOption's levels; each must frame and unframe identically. + for (level in intArrayOf(0, 1, 5, 9)) { + val framed = CaffZip.zipSingle(contents, level) + assertTrue(framed.size > 38 + 16, "level $level must emit a header, payload, and descriptor") + assertContentEquals(contents, CaffZip.unzipSingle(framed), "round-trip at level $level") + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/io/BinaryInt64KeyingTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/io/BinaryInt64KeyingTest.kt new file mode 100644 index 0000000..2b7d3f5 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/io/BinaryInt64KeyingTest.kt @@ -0,0 +1,59 @@ +package org.umamo.format.cmo3.io + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the 64-bit obfuscation mask to the editor's semantics: ((long) key << 32) | key with a + * SIGN-EXTENDING OR operand, so a negative key floods the high dword with ones. + * + * Corpus proof: every negative-key official file stores 0xFFFFFFFF as the raw high dword of its + * sub-4GB entry offsets (miku.cmo3, modelB.cmo3, ...), which only the sign-extended mask + * produces. A zero-extended mask round-trips through Umamo's own symmetric reader while the + * official reader decodes garbage offsets and reports the file as "Premature end of file" - the + * failure is invisible to every decompressed-content gate, so this byte-level pin is the guard. + */ +class BinaryInt64KeyingTest { + /** + * Encodes [value] with [key] through BinaryWriter and returns the raw big-endian bytes. + * + * @param Long value The value to encode. + * @param Int key The obfuscation key. + * @return ByteArray The eight raw bytes. + */ + private fun rawBytes(value: Long, key: Int): ByteArray { + val writer = BinaryWriter() + writer.writeInt64(value, key) + return writer.toByteArray() + } + + @Test + fun negativeKeyFloodsTheHighDwordLikeTheEditor() { + // miku.cmo3's key; its entry table stores ffffffff high dwords for every offset. + val key = -1141606607 + val raw = rawBytes(0x12345678L, key) + val highDword = + (0 until 4).fold(0L) { accumulated, byteIndex -> (accumulated shl 8) or (raw[byteIndex].toLong() and 0xFF) } + // value high dword is 0, so the raw high dword IS the mask's high dword: all ones. + assertEquals(0xFFFFFFFFL, highDword, "negative key must sign-extend into the high dword") + } + + @Test + fun positiveKeyKeepsTheKeyInTheHighDword() { + val key = 0x49C74776 + val raw = rawBytes(0x12345678L, key) + val highDword = + (0 until 4).fold(0L) { accumulated, byteIndex -> (accumulated shl 8) or (raw[byteIndex].toLong() and 0xFF) } + assertEquals(key.toLong(), highDword, "positive key masks the high dword with the key itself") + } + + @Test + fun readerAndWriterStaySymmetricForBothSigns() { + for (key in intArrayOf(0, 0x49C74776, -1141606607, -1, Int.MIN_VALUE)) { + for (value in longArrayOf(0L, 455L, 23485317L, 0x1_0000_0000L)) { + val reader = BinaryReader(rawBytes(value, key)) + assertEquals(value, reader.readInt64(key), "round trip for key=$key value=$value") + } + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/type/CTypeEqualityTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/type/CTypeEqualityTest.kt new file mode 100644 index 0000000..e0ba671 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/cmo3/type/CTypeEqualityTest.kt @@ -0,0 +1,44 @@ +package org.umamo.format.cmo3.type + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals + +/** + * Pins the hand-forwarded equals/hashCode/toString on the CMO3 collection types. Kotlin's `by` + * delegation does NOT forward these three, so without the overrides two equal lists would compare + * by identity - the exact trap the classes document. This is the load-bearing behavior, not the + * delegated MutableList/MutableMap surface. + */ +class CTypeEqualityTest { + /** A CArrayList equals a plain list with the same elements, in both directions. */ + @Test + fun cArrayListEqualsAPlainListByValue() { + val cList = CArrayList(listOf(1, 2, 3)) + assertEquals(listOf(1, 2, 3), cList) + assertEquals(cList, listOf(1, 2, 3)) + assertEquals(listOf(1, 2, 3).hashCode(), cList.hashCode()) + assertEquals(listOf(1, 2, 3).toString(), cList.toString()) + assertNotEquals(listOf(1, 2), cList) + } + + /** A CHashMap equals a plain map with the same entries and keeps insertion order. */ + @Test + fun cHashMapEqualsAPlainMapAndPreservesInsertionOrder() { + val cMap = CHashMap() + cMap["zulu"] = 1 + cMap["alpha"] = 2 + cMap["mike"] = 3 + assertEquals(mapOf("zulu" to 1, "alpha" to 2, "mike" to 3), cMap) + assertEquals(mapOf("zulu" to 1, "alpha" to 2, "mike" to 3).hashCode(), cMap.hashCode()) + assertEquals(listOf("zulu", "alpha", "mike"), cMap.keys.toList(), "iteration follows insertion, not hash order") + assertNotEquals(mapOf("zulu" to 1), cMap) + } + + /** An empty-constructed instance still equals its plain empty counterpart. */ + @Test + fun emptyInstancesEqualTheirPlainCounterparts() { + assertEquals(emptyList(), CArrayList()) + assertEquals(emptyMap(), CHashMap()) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/jpeg/JpegDecodeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/jpeg/JpegDecodeTest.kt new file mode 100644 index 0000000..f88475e --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/jpeg/JpegDecodeTest.kt @@ -0,0 +1,367 @@ +package org.umamo.format.jpeg + +import kotlin.io.encoding.Base64 +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * Validates [JpegReader]'s decode against golden fixtures. Each fixture is a tiny JPEG encoded by + * libjpeg (via Pillow) plus the RGBA libjpeg itself decodes it to. JPEG is lossy, but decoding is + * deterministic: this decoder implements the same fixed-point IDCT, upsampling filters, and YCbCr + * conversion as the reference implementation, so the pixels must match exactly. The fixtures span + * baseline 4:4:4 / 4:2:0 / 4:2:2 (the triangle upsampling filters), grayscale, restart intervals, and + * progressive frames — whose default libjpeg scan script exercises spectral selection plus both DC and + * AC successive approximation (the refinement scans). Fixtures are embedded base64 so the test is + * self-contained. + */ +class JpegDecodeTest { + /** + * Decodes an embedded fixture and asserts it matches the embedded libjpeg-golden RGBA. + * + * @param Int width Expected width. + * @param Int height Expected height. + * @param String jpegBase64 Base64 of the `.jpg` bytes. + * @param String rgbaBase64 Base64 of the golden RGBA8888 (top-first, opaque). + */ + private fun assertDecodes(width: Int, height: Int, jpegBase64: String, rgbaBase64: String) { + val jpeg = Base64.decode(jpegBase64) + val expected = Base64.decode(rgbaBase64) + val decoded = JpegReader.read(jpeg) + assertEquals(width, decoded.width, "width") + assertEquals(height, decoded.height, "height") + assertContentEquals(expected, decoded.rgba, "JPEG decode must match libjpeg pixel-for-pixel") + } + + /** baseline, 4:4:4 (no chroma subsampling). */ + @Test + fun decodesChroma444() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wAARCAAQABADAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" + + "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW" + + "V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi" + + "4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC" + + "AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm" + + "Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq" + + "8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD4/wDBfwh/1f7j9KKNYOHuIfh94958F/CH/V/uP0r3KNY/p3h3iL4fePY/Bfwh/wBX+4/S" + + "vh6NY/zF4d4i+H3j3nwX8If9X+4/Svco1j+neHuIfh94/9k=", + rgbaBase64 = + "AAAA/w8AB/8iABD/MQAW/z0AH/9NASj/YQEx/3ABNv+AAD//jwBF/6IATv+yAFj/vwBf/84AZ//iAHD/8QB3/wAPCP8PDw//Iw8Y" + + "/zIQIf8/Dyf/Tw8x/2IPOf9wEED/gQ9K/48OT/+iDlj/sg9g/8APaf/OD2//4w56//EPf/8AIRH/DSEY/yEhIf8xISv/PSEw/00h" + + "Ov9hIUP/biJJ/38hU/+OIVj/oSBg/7Ehaf++IXL/ziF6/+Ahgf/vIIj/ADAa/w4wH/8hMSf/MDAw/z0wOf9NMUD/YTFJ/24xUP9+" + + "MFj/jDBf/6EwaP+xMHD/vjB4/80wgf/hMIr/7zCP/wI/IP8PPyf/Iz8w/zNAN/9AQED/Tz9J/2JAUf9xQFb/gUBi/5BAZ/+iP27/" + + "sj94/8A/gP/QQIj/4j+Q//E/l/8CTif/D08t/yNPNv8zT0D/P09F/09PT/9jT1j/cU9f/4BQaP+PUG//oU93/7JPfv/AT4f/0E+Q" + + "/+JOmP/xTp3/AGAw/w5hN/8hYT//MWFJ/z5gT/9NYVj/YWFh/3BhaP9+YnH/jWJ2/6BhgP+xYYj/vWGQ/85hmP/hYKD/8GCm/wBv" + + "Ov8Pbz//I29I/zNwUf8/cFr/TnBg/2Fwaf9wcHD/fnF6/41xgP+gcIj/sXCS/75wmP/OcKL/4W+q//BvsP8AgUD/DoBF/yKATv8y" + + "gFj/P4Be/09/Z/9jf3D/cn92/4CAgP+PgIf/ooCQ/7GAlv+9gJ//zYGo/+GBsf/vgLX/AJBK/w+QUP8ij1j/M49g/z+PaP9Qj3D/" + + "Y456/3KOf/+Aj4j/j4+P/6OPmP+xj6D/v4+n/8+Psf/ij7n/8JDA/wCiU/8Oolj/IKFg/zChaf8+oXL/T6F5/2Gggf9woIj/f6GR" + + "/42hmP+hoaH/sKCq/72hsP/Nobr/4aHD/+6iyf8AsVn/DbBf/yCwaP8wsXD/PrF4/02wgf9gsIn/b7CO/3+wmv+OsJ//obGn/7Cw" + + "sP+9sLn/zbHA/+Gxyf/usdD/AcBh/w/AZv8jwG//MsB4/z/AgP9PwIj/ZMCR/3G/l/+Cv6D/j7+n/6O/sP+zwLf/v7+//8+/yf/i" + + "wNH/8cDW/wHQaP8Qz2//Is92/zLPfv8/z4f/T9CQ/2LPmP9xz53/gs6n/4/Prf+jz7b/ss6//7/Pxf/Pz8//48/Y//HP3/8A4XH/" + + "DeJ2/yHggP8w4Yf/PuGQ/07imP9g4aD/b+Gm/4DgsP+O4bf/oeG//7DgyP++4M//zeHY/+Hh4f/w4ej/APF5/w7wgP8i8Yn/MfCR" + + "/z7wmP9O8aL/YfGr/2/wsP+A77r/j++//6PvyP+z8NH/vu/Z/87w4P/h8On/8PDw/w==", + ) + } + + /** baseline, 4:2:0 (2x2 chroma subsampling; exercises the triangle upsampling filter). */ + @Test + fun decodesChroma420() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wAARCAAQABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" + + "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW" + + "V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi" + + "4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC" + + "AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm" + + "Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq" + + "8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD4/wDBfwh/1f7j9K958F/CH/V/uP0r2PwX8If9X+4/SvefBfwh/wBX+4/SjB4zbUPDzxD+" + + "D3z/2Q==", + rgbaBase64 = + "AAAA/wkDB/8ZBRD/JwQY/zkCIf9KAij/WwMz/2oDOP95Az//iANF/5gETv+qBFj/uwJf/8oBZ//ZBHD/4wZ3/wYMCP8PDw//HhEa" + + "/y4SIf8/Dyn/UA4y/2EQO/9wD0L/gBBI/40PTv+eEFj/rxBg/8EOaf/QDm//3xB6/+gTf/8IHBH/Eh8W/yEhIf8xISv/QR4y/1Me" + + "Ov9jIEP/ch9J/4IgUf+RIFj/oSBg/7IgZ//EHnD/0x94/+Iggf/rIoj/CSwY/xIuH/8hMSf/MDAw/0IuOf9RL0D/ZC9L/3IvUP+B" + + "Llj/jy9d/6EwaP+yMHD/xC52/9Mtf//iL4r/6zKP/wY9IP8PPyX/H0Iu/y5CN/9AQED/UD9H/2JAUf9wQFb/gEFg/45BZf+gQG7/" + + "sEF2/8E/f//RP4b/30CQ/+lDl/8FTSf/Dk8t/x1SNv8tUz7/Pk9H/09PT/9hUFj/b1Bf/35RZv+NUW3/nlF1/65Rff/AT4f/0E+P" + + "/95QmP/nU53/Bl0w/w9gNf8fYj//LmNH/z9fUP9PYFj/YWFh/3BhaP+AYXD/jWJ2/55ifv+vYob/wV+Q/9FgmP/fYaD/6WSm/wZt" + + "OP8PcD3/H3JI/y9yT/9AcFr/T29g/2Fwaf9wcHD/gHF4/41xf/+ecYb/sHGO/8FumP/Rb6D/4HCo/+lzr/8HfUH/D39H/x+BUP8v" + + "glj/QH9i/1F+af9jf3H/cH94/4CAgP+PgIf/oYGQ/7CAlv/BfqH/0X6o/+GAs//pgrf/B4xK/xGPUP8fkFj/L5Fg/0GOav9SjnL/" + + "Y456/3CPgP+Aj4j/j4+P/6GQmP+wkJ//wo2p/9GOsf/hkLv/6pPA/wmdU/8SoFj/IKFh/zChaf9Cn3P/Up97/2Ofg/9yn4r/gaCR" + + "/4+gmP+hoaH/saCo/8Odsv/Tnrr/4qHD/+ujyf8HrVn/EK9f/x+xav8vsXH/QK96/0+vgf9ir4v/cK+Q/4Cwmv+OsJ//oLGp/7Cw" + + "sP/Crrn/0a7C/+Gxy//qs9D/Bb5h/w7BZv8dw3H/LMJ6/z7AgP9PwIj/YcGT/27Bl/9+waD/jMGl/5/BsP+uwrf/v7+//8+/yf/e" + + "wtH/58TY/wXOaP8O0G//HdF4/yzSgP8+0In/T9CQ/1/QmP9u0J//ftGn/43Qrf+d0rb/rtG9/7/Pxf/Pz8//3tHa/+jU3/8I3XH/" + + "EeB2/x/hgP8v4of/QeCQ/1LgmP9i4KH/cOCo/4Dhrv+P4LX/oOK+/7Dgxv/C3s//0t/W/+Hh4f/q5Oj/Dep5/xfsgP8m74n/Ne6R" + + "/0bsmP9Y7KL/aO2r/3bssP+G7bj/le29/6buyP+37s//yOvX/9fr4P/n7en/8PDw/w==", + ) + } + + /** baseline, 4:2:2 (2x1 chroma subsampling). */ + @Test + fun decodesChroma422() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wAARCAAQABADASEAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" + + "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW" + + "V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi" + + "4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC" + + "AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm" + + "Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq" + + "8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD4/wDBfwh/1f7j9K958F/CH/V/uP0ruwdbY/TvDziL4PePY/Bfwh/1f7j9K958F/CH/V/u" + + "P0rw8HW2P5j8POIvg94//9k=", + rgbaBase64 = + "BwAA/xAAB/8gARD/LgEY/0AAH/9RACj/YgAx/3EAOP+AAD//jwBF/58BTv+xAFj/wgBf/9EAZ//gAHD/6gN3/wcMCP8QDg//IBEY" + + "/zARIf9ADin/UQ0y/2IPOf9xD0L/gRBI/48OT/+gEFb/sRBg/8IOaf/RDXH/4RB4/+oSf/8GHhH/DyAY/x4iIf8uIyv/PyAw/1Ag" + + "Ov9hIUP/byFJ/38iUf+OIVj/niJg/68haf/BIHD/0SB6/98hgf/oJIj/Bi0Y/w8wH/8eMif/LTEw/z8vOf9QL0L/YTFJ/3AwUv9+" + + "MFf/jTBf/54yZv+vMXD/wS94/9Augf/fMYr/6DOQ/wc8IP8RPif/IEEw/zBBOf9BP0D/Uj5J/2JAUf9xP1j/gUBg/5BAZ/+gQG7/" + + "sUB4/8M+f//SPoj/4UCQ/+pCl/8ITCf/EU4t/yBQNv8wUUD/P05H/1BOUf9hUFj/cU9g/4BQZv+QT2//oFB1/7FPfv/BTof/0U6Q" + + "/+BQmP/pUp//BV4w/w5hN/8dYz//LWNJ/z5gUP9PYFr/YGJh/25haP9+YnD/jWJ2/55ifv+vYYj/wGCO/9BgmP/eYqD/52Sm/wZt" + + "OP8Pbz//H3JI/y9yUf8/cFr/T29i/2Bxaf9wcHL/fnF4/49wgP+ecYb/sHGQ/8BvmP/Qb6L/3nGq/+dzsP8JfUD/EX5F/yCBTv8w" + + "gVj/QH9g/1F+af9hgHD/cn94/4CAfv+Qf4f/oYGO/7GAlv/Bfp//0X6o/+GBsf/pgrf/CYxK/xKOUP8gkFj/MJBi/0GPaP9SjnL/" + + "Y456/3KOgP+Cj4j/kI6P/6GQlv+xj5//w42n/9ONsf/ij7n/65LA/weeUf8QoFj/H6Jg/y+iaf8/oXL/UKB7/2Chgf9woIr/f6GQ" + + "/4+gmP+gop//sKGo/8CfsP/QoLr/36LD/+ikyf8Grln/Dq9f/x6yaP8tsnH/P7B4/0+vgf9gsIn/b7CQ/3+xmP+OsJ//nrKn/6+x" + + "sP/Ar7f/0K/A/9+yyf/ptND/CL1g/xG/Zv8gwm//L8F4/0G/gP9Svor/Y8CR/3G/mP+AwJ7/j7+n/6DBrv+xwbf/wr6//9K+yf/h" + + "wNH/6sPY/wjMaP8Rz2//H9B2/y/QgP9Bz4f/Us6Q/2LPmP9xzp//gc+n/4/Prf+g0Lb/sM+//8LNxf/Szs//4dDY/+rS3/8G3nH/" + + "D+B4/x7ifv8u4of/P+CQ/1Dgmv9g4aD/b+Co/3/hrv+O4bf/n+O+/6/hxv/A38//0N/Y/+Di4f/p5Oj/Bu15/xDwgP8f8on/LvGR" + + "/z/wmP9R76L/YfGr/2/wsP9/8Lj/jvC//5/yyP+w8dH/we7X/9Dv4P/g8en/6fTw/w==", + ) + } + + /** baseline grayscale (single component). */ + @Test + fun decodesGrayscale() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/wAALCAAQABABAREA/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" + + "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW" + + "V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi" + + "4+Tl5ufo6erx8vP09fb3+Pn6/9oACAEBAAA/APj/AMF/CH/V/uP0r3nwX8If9X+4/SvY/Bfwh/1f7j9K958F/CH/AFf7j9K//9k=", + rgbaBase64 = + "AAAA/wUFBf8MDAz/ERER/xYWFv8cHBz/IyMj/ygoKP8tLS3/MjIy/zk5Of8/Pz//RERE/0lJSf9QUFD/VVVV/woKCv8PDw//FhYW" + + "/xwcHP8gICD/JiYm/y0tLf8yMjL/ODg4/zw8PP9DQ0P/SUlJ/05OTv9TU1P/Wlpa/19fX/8VFRX/Ghoa/yEhIf8nJyf/Kysr/zEx" + + "Mf84ODj/PT09/0NDQ/9ISEj/Tk5O/1RUVP9ZWVn/X19f/2VlZf9qamr/Hx8f/yQkJP8rKyv/MDAw/zU1Nf87Ozv/QkJC/0dHR/9M" + + "TEz/UVFR/1hYWP9eXl7/Y2Nj/2hoaP9vb2//dHR0/ykpKf8uLi7/NTU1/zs7O/9AQED/RUVF/0xMTP9RUVH/V1dX/1xcXP9iYmL/" + + "aGho/21tbf9zc3P/eXl5/35+fv8zMzP/ODg4/z8/P/9FRUX/SUlJ/09PT/9WVlb/W1tb/2FhYf9mZmb/bGxs/3Jycv93d3f/fX19" + + "/4ODg/+IiIj/Pj4+/0NDQ/9KSkr/UFBQ/1RUVP9aWlr/YWFh/2ZmZv9sbGz/cXFx/3d3d/99fX3/goKC/4iIiP+Ojo7/k5OT/0hI" + + "SP9NTU3/VFRU/1paWv9fX1//ZGRk/2tra/9wcHD/dnZ2/3t7e/+BgYH/h4eH/4yMjP+SkpL/mJiY/52dnf9TU1P/V1dX/15eXv9k" + + "ZGT/aWlp/25ubv91dXX/enp6/4CAgP+FhYX/jIyM/5GRkf+Wlpb/nJyc/6Ojo/+np6f/XV1d/2JiYv9oaGj/bm5u/3Nzc/95eXn/" + + "f39//4SEhP+Kior/j4+P/5aWlv+bm5v/oKCg/6ampv+tra3/srKy/2hoaP9tbW3/c3Nz/3l5ef9+fn7/hISE/4qKiv+Pj4//lZWV" + + "/5qamv+hoaH/pqam/6urq/+xsbH/uLi4/729vf9ycnL/dnZ2/319ff+Dg4P/iIiI/42Njf+UlJT/mZmZ/5+fn/+kpKT/q6ur/7Cw" + + "sP+1tbX/u7u7/8LCwv/Hx8f/fHx8/4GBgf+IiIj/jY2N/5KSkv+YmJj/n5+f/6Ojo/+pqan/rq6u/7W1tf+7u7v/v7+//8XFxf/M" + + "zMz/0dHR/4aGhv+Li4v/kZGR/5eXl/+cnJz/oqKi/6ioqP+tra3/s7Oz/7i4uP+/v7//xMTE/8nJyf/Pz8//1tbW/9vb2/+RkZH/" + + "lpaW/5ycnP+ioqL/p6en/62trf+zs7P/uLi4/76+vv/Dw8P/ysrK/8/Pz//U1NT/2tra/+Hh4f/m5ub/m5ub/6CgoP+np6f/rKys" + + "/7Gxsf+3t7f/vr6+/8LCwv/IyMj/zc3N/9TU1P/a2tr/3t7e/+Tk5P/r6+v/8PDw/w==", + ) + } + + /** baseline with restart intervals (DRI / RSTn markers). */ + @Test + fun decodesRestartIntervals() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wAARCAAQABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" + + "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW" + + "V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi" + + "4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC" + + "AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm" + + "Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq" + + "8vP09fb3+Pn6/90ABAAB/9oADAMBAAIRAxEAPwD4/wDBfwh/1f7j9K958F/CH/V/uP0r2PwX8If9X+4/SvefBfwh/wBX+4/SjB4z" + + "bUPDzxD+D3z/2Q==", + rgbaBase64 = + "AAAA/wkDB/8ZBRD/JwQY/zkCIf9KAij/WwMz/2oDOP95Az//iANF/5gETv+qBFj/uwJf/8oBZ//ZBHD/4wZ3/wYMCP8PDw//HhEa" + + "/y4SIf8/Dyn/UA4y/2EQO/9wD0L/gBBI/40PTv+eEFj/rxBg/8EOaf/QDm//3xB6/+gTf/8IHBH/Eh8W/yEhIf8xISv/QR4y/1Me" + + "Ov9jIEP/ch9J/4IgUf+RIFj/oSBg/7IgZ//EHnD/0x94/+Iggf/rIoj/CSwY/xIuH/8hMSf/MDAw/0IuOf9RL0D/ZC9L/3IvUP+B" + + "Llj/jy9d/6EwaP+yMHD/xC52/9Mtf//iL4r/6zKP/wY9IP8PPyX/H0Iu/y5CN/9AQED/UD9H/2JAUf9wQFb/gEFg/45BZf+gQG7/" + + "sEF2/8E/f//RP4b/30CQ/+lDl/8FTSf/Dk8t/x1SNv8tUz7/Pk9H/09PT/9hUFj/b1Bf/35RZv+NUW3/nlF1/65Rff/AT4f/0E+P" + + "/95QmP/nU53/Bl0w/w9gNf8fYj//LmNH/z9fUP9PYFj/YWFh/3BhaP+AYXD/jWJ2/55ifv+vYob/wV+Q/9FgmP/fYaD/6WSm/wZt" + + "OP8PcD3/H3JI/y9yT/9AcFr/T29g/2Fwaf9wcHD/gHF4/41xf/+ecYb/sHGO/8FumP/Rb6D/4HCo/+lzr/8HfUH/D39H/x+BUP8v" + + "glj/QH9i/1F+af9jf3H/cH94/4CAgP+PgIf/oYGQ/7CAlv/BfqH/0X6o/+GAs//pgrf/B4xK/xGPUP8fkFj/L5Fg/0GOav9SjnL/" + + "Y456/3CPgP+Aj4j/j4+P/6GQmP+wkJ//wo2p/9GOsf/hkLv/6pPA/wmdU/8SoFj/IKFh/zChaf9Cn3P/Up97/2Ofg/9yn4r/gaCR" + + "/4+gmP+hoaH/saCo/8Odsv/Tnrr/4qHD/+ujyf8HrVn/EK9f/x+xav8vsXH/QK96/0+vgf9ir4v/cK+Q/4Cwmv+OsJ//oLGp/7Cw" + + "sP/Crrn/0a7C/+Gxy//qs9D/Bb5h/w7BZv8dw3H/LMJ6/z7AgP9PwIj/YcGT/27Bl/9+waD/jMGl/5/BsP+uwrf/v7+//8+/yf/e" + + "wtH/58TY/wXOaP8O0G//HdF4/yzSgP8+0In/T9CQ/1/QmP9u0J//ftGn/43Qrf+d0rb/rtG9/7/Pxf/Pz8//3tHa/+jU3/8I3XH/" + + "EeB2/x/hgP8v4of/QeCQ/1LgmP9i4KH/cOCo/4Dhrv+P4LX/oOK+/7Dgxv/C3s//0t/W/+Hh4f/q5Oj/Dep5/xfsgP8m74n/Ne6R" + + "/0bsmP9Y7KL/aO2r/3bssP+G7bj/le29/6buyP+37s//yOvX/9fr4P/n7en/8PDw/w==", + ) + } + + /** progressive, 4:4:4 - spectral selection plus DC and AC successive approximation. */ + @Test + fun decodesProgressive444() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wgARCAAQABADAREAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAABgf/xAAYAQADAQEAAAAAAAAAAAAAAAAABAcF" + + "CP/aAAwDAQACEAMQAAABj4PHqcyw+Ynj1P8A/8QAFhAAAwAAAAAAAAAAAAAAAAAAAAQF/9oACAEBAAEFAkpAlIEpAlIP/8QAFxEB" + + "AAMAAAAAAAAAAAAAAAAABQAhMf/aAAgBAwEBPwE9DLhyOXDkcuHoZc//xAAVEQEBAAAAAAAAAAAAAAAAAAACAP/aAAgBAgEBPwEO" + + "Dg4O/8QAFhAAAwAAAAAAAAAAAAAAAAAAAAEh/9oACAEBAAY/AlBQUFD/xAAUEAEAAAAAAAAAAAAAAAAAAAAg/9oACAEBAAE/IQqq" + + "v//aAAwDAQACAAMAAAAQFM//xAAUEQEAAAAAAAAAAAAAAAAAAAAg/9oACAEDAQE/EBgBn//EABQRAQAAAAAAAAAAAAAAAAAAACD/" + + "2gAIAQIBAT8QAB//xAAVEAEBAAAAAAAAAAAAAAAAAAAA8f/aAAgBAQABPxCCgoKC/9k=", + rgbaBase64 = + "AAAA/w8AB/8iABD/MQAW/z0AH/9NASj/YQEx/3ABNv+AAD//jwBF/6IATv+yAFj/vwBf/84AZ//iAHD/8QB3/wAPCP8PDw//Iw8Y" + + "/zIQIf8/Dyf/Tw8x/2IPOf9wEED/gQ9K/48OT/+iDlj/sg9g/8APaf/OD2//4w56//EPf/8AIRH/DSEY/yEhIf8xISv/PSEw/00h" + + "Ov9hIUP/biJJ/38hU/+OIVj/oSBg/7Ehaf++IXL/ziF6/+Ahgf/vIIj/ADAa/w4wH/8hMSf/MDAw/z0wOf9NMUD/YTFJ/24xUP9+" + + "MFj/jDBf/6EwaP+xMHD/vjB4/80wgf/hMIr/7zCP/wI/IP8PPyf/Iz8w/zNAN/9AQED/Tz9J/2JAUf9xQFb/gUBi/5BAZ/+iP27/" + + "sj94/8A/gP/QQIj/4j+Q//E/l/8CTif/D08t/yNPNv8zT0D/P09F/09PT/9jT1j/cU9f/4BQaP+PUG//oU93/7JPfv/AT4f/0E+Q" + + "/+JOmP/xTp3/AGAw/w5hN/8hYT//MWFJ/z5gT/9NYVj/YWFh/3BhaP9+YnH/jWJ2/6BhgP+xYYj/vWGQ/85hmP/hYKD/8GCm/wBv" + + "Ov8Pbz//I29I/zNwUf8/cFr/TnBg/2Fwaf9wcHD/fnF6/41xgP+gcIj/sXCS/75wmP/OcKL/4W+q//BvsP8AgUD/DoBF/yKATv8y" + + "gFj/P4Be/09/Z/9jf3D/cn92/4CAgP+PgIf/ooCQ/7GAlv+9gJ//zYGo/+GBsf/vgLX/AJBK/w+QUP8ij1j/M49g/z+PaP9Qj3D/" + + "Y456/3KOf/+Aj4j/j4+P/6OPmP+xj6D/v4+n/8+Psf/ij7n/8JDA/wCiU/8Oolj/IKFg/zChaf8+oXL/T6F5/2Gggf9woIj/f6GR" + + "/42hmP+hoaH/sKCq/72hsP/Nobr/4aHD/+6iyf8AsVn/DbBf/yCwaP8wsXD/PrF4/02wgf9gsIn/b7CO/3+wmv+OsJ//obGn/7Cw" + + "sP+9sLn/zbHA/+Gxyf/usdD/AcBh/w/AZv8jwG//MsB4/z/AgP9PwIj/ZMCR/3G/l/+Cv6D/j7+n/6O/sP+zwLf/v7+//8+/yf/i" + + "wNH/8cDW/wHQaP8Qz2//Is92/zLPfv8/z4f/T9CQ/2LPmP9xz53/gs6n/4/Prf+jz7b/ss6//7/Pxf/Pz8//48/Y//HP3/8A4XH/" + + "DeJ2/yHggP8w4Yf/PuGQ/07imP9g4aD/b+Gm/4DgsP+O4bf/oeG//7DgyP++4M//zeHY/+Hh4f/w4ej/APF5/w7wgP8i8Yn/MfCR" + + "/z7wmP9O8aL/YfGr/2/wsP+A77r/j++//6PvyP+z8NH/vu/Z/87w4P/h8On/8PDw/w==", + ) + } + + /** progressive, 4:2:0 - progressive scans over subsampled chroma. */ + @Test + fun decodesProgressive420() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wgARCAAQABADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAABgf/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/9oA" + + "DAMBAAIQAxAAAAGPvGTw/8QAFhAAAwAAAAAAAAAAAAAAAAAAAAQF/9oACAEBAAEFAkpAlIEpAlIP/8QAFxEBAAMAAAAAAAAAAAAA" + + "AAAABgAhMf/aAAgBAwEBPwE8hy5//8QAFREBAQAAAAAAAAAAAAAAAAAAAwD/2gAIAQIBAT8BFr//xAAWEAADAAAAAAAAAAAAAAAA" + + "AAAAASH/2gAIAQEABj8CUFBQUP/EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8hCqq//9oADAMBAAIAAwAAABBT/8QAFBEB" + + "AAAAAAAAAAAAAAAAAAAAAP/aAAgBAwEBPxB//8QAFhEAAwAAAAAAAAAAAAAAAAAAACEx/9oACAECAQE/EIM//8QAFRABAQAAAAAA" + + "AAAAAAAAAAAAAPH/2gAIAQEAAT8QgoKCgv/Z", + rgbaBase64 = + "AAAA/wkDB/8ZBRD/JwQY/zkCIf9KAij/WwMz/2oDOP95Az//iANF/5gETv+qBFj/uwJf/8oBZ//ZBHD/4wZ3/wYMCP8PDw//HhEa" + + "/y4SIf8/Dyn/UA4y/2EQO/9wD0L/gBBI/40PTv+eEFj/rxBg/8EOaf/QDm//3xB6/+gTf/8IHBH/Eh8W/yEhIf8xISv/QR4y/1Me" + + "Ov9jIEP/ch9J/4IgUf+RIFj/oSBg/7IgZ//EHnD/0x94/+Iggf/rIoj/CSwY/xIuH/8hMSf/MDAw/0IuOf9RL0D/ZC9L/3IvUP+B" + + "Llj/jy9d/6EwaP+yMHD/xC52/9Mtf//iL4r/6zKP/wY9IP8PPyX/H0Iu/y5CN/9AQED/UD9H/2JAUf9wQFb/gEFg/45BZf+gQG7/" + + "sEF2/8E/f//RP4b/30CQ/+lDl/8FTSf/Dk8t/x1SNv8tUz7/Pk9H/09PT/9hUFj/b1Bf/35RZv+NUW3/nlF1/65Rff/AT4f/0E+P" + + "/95QmP/nU53/Bl0w/w9gNf8fYj//LmNH/z9fUP9PYFj/YWFh/3BhaP+AYXD/jWJ2/55ifv+vYob/wV+Q/9FgmP/fYaD/6WSm/wZt" + + "OP8PcD3/H3JI/y9yT/9AcFr/T29g/2Fwaf9wcHD/gHF4/41xf/+ecYb/sHGO/8FumP/Rb6D/4HCo/+lzr/8HfUH/D39H/x+BUP8v" + + "glj/QH9i/1F+af9jf3H/cH94/4CAgP+PgIf/oYGQ/7CAlv/BfqH/0X6o/+GAs//pgrf/B4xK/xGPUP8fkFj/L5Fg/0GOav9SjnL/" + + "Y456/3CPgP+Aj4j/j4+P/6GQmP+wkJ//wo2p/9GOsf/hkLv/6pPA/wmdU/8SoFj/IKFh/zChaf9Cn3P/Up97/2Ofg/9yn4r/gaCR" + + "/4+gmP+hoaH/saCo/8Odsv/Tnrr/4qHD/+ujyf8HrVn/EK9f/x+xav8vsXH/QK96/0+vgf9ir4v/cK+Q/4Cwmv+OsJ//oLGp/7Cw" + + "sP/Crrn/0a7C/+Gxy//qs9D/Bb5h/w7BZv8dw3H/LMJ6/z7AgP9PwIj/YcGT/27Bl/9+waD/jMGl/5/BsP+uwrf/v7+//8+/yf/e" + + "wtH/58TY/wXOaP8O0G//HdF4/yzSgP8+0In/T9CQ/1/QmP9u0J//ftGn/43Qrf+d0rb/rtG9/7/Pxf/Pz8//3tHa/+jU3/8I3XH/" + + "EeB2/x/hgP8v4of/QeCQ/1LgmP9i4KH/cOCo/4Dhrv+P4LX/oOK+/7Dgxv/C3s//0t/W/+Hh4f/q5Oj/Dep5/xfsgP8m74n/Ne6R" + + "/0bsmP9Y7KL/aO2r/3bssP+G7bj/le29/6buyP+37s//yOvX/9fr4P/n7en/8PDw/w==", + ) + } + + /** progressive grayscale (single component, 6-scan script). */ + @Test + fun decodesProgressiveGrayscale() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/wgALCAAQABABAREA/8QAFQABAQAAAAAAAAAAAAAAAAAABgf/2gAIAQEAAAABj7xk8//EABYQAAMAAAAA" + + "AAAAAAAAAAAAAAAEBf/aAAgBAQABBQJKQJSBKQJSD//EABYQAAMAAAAAAAAAAAAAAAAAAAABIf/aAAgBAQAGPwJQUFBQ/8QAFBAB" + + "AAAAAAAAAAAAAAAAAAAAIP/aAAgBAQABPyEKqr//2gAIAQEAAAAQX//EABUQAQEAAAAAAAAAAAAAAAAAAADx/9oACAEBAAE/EIKC" + + "goL/2Q==", + rgbaBase64 = + "AAAA/wUFBf8MDAz/ERER/xYWFv8cHBz/IyMj/ygoKP8tLS3/MjIy/zk5Of8/Pz//RERE/0lJSf9QUFD/VVVV/woKCv8PDw//FhYW" + + "/xwcHP8gICD/JiYm/y0tLf8yMjL/ODg4/zw8PP9DQ0P/SUlJ/05OTv9TU1P/Wlpa/19fX/8VFRX/Ghoa/yEhIf8nJyf/Kysr/zEx" + + "Mf84ODj/PT09/0NDQ/9ISEj/Tk5O/1RUVP9ZWVn/X19f/2VlZf9qamr/Hx8f/yQkJP8rKyv/MDAw/zU1Nf87Ozv/QkJC/0dHR/9M" + + "TEz/UVFR/1hYWP9eXl7/Y2Nj/2hoaP9vb2//dHR0/ykpKf8uLi7/NTU1/zs7O/9AQED/RUVF/0xMTP9RUVH/V1dX/1xcXP9iYmL/" + + "aGho/21tbf9zc3P/eXl5/35+fv8zMzP/ODg4/z8/P/9FRUX/SUlJ/09PT/9WVlb/W1tb/2FhYf9mZmb/bGxs/3Jycv93d3f/fX19" + + "/4ODg/+IiIj/Pj4+/0NDQ/9KSkr/UFBQ/1RUVP9aWlr/YWFh/2ZmZv9sbGz/cXFx/3d3d/99fX3/goKC/4iIiP+Ojo7/k5OT/0hI" + + "SP9NTU3/VFRU/1paWv9fX1//ZGRk/2tra/9wcHD/dnZ2/3t7e/+BgYH/h4eH/4yMjP+SkpL/mJiY/52dnf9TU1P/V1dX/15eXv9k" + + "ZGT/aWlp/25ubv91dXX/enp6/4CAgP+FhYX/jIyM/5GRkf+Wlpb/nJyc/6Ojo/+np6f/XV1d/2JiYv9oaGj/bm5u/3Nzc/95eXn/" + + "f39//4SEhP+Kior/j4+P/5aWlv+bm5v/oKCg/6ampv+tra3/srKy/2hoaP9tbW3/c3Nz/3l5ef9+fn7/hISE/4qKiv+Pj4//lZWV" + + "/5qamv+hoaH/pqam/6urq/+xsbH/uLi4/729vf9ycnL/dnZ2/319ff+Dg4P/iIiI/42Njf+UlJT/mZmZ/5+fn/+kpKT/q6ur/7Cw" + + "sP+1tbX/u7u7/8LCwv/Hx8f/fHx8/4GBgf+IiIj/jY2N/5KSkv+YmJj/n5+f/6Ojo/+pqan/rq6u/7W1tf+7u7v/v7+//8XFxf/M" + + "zMz/0dHR/4aGhv+Li4v/kZGR/5eXl/+cnJz/oqKi/6ioqP+tra3/s7Oz/7i4uP+/v7//xMTE/8nJyf/Pz8//1tbW/9vb2/+RkZH/" + + "lpaW/5ycnP+ioqL/p6en/62trf+zs7P/uLi4/76+vv/Dw8P/ysrK/8/Pz//U1NT/2tra/+Hh4f/m5ub/m5ub/6CgoP+np6f/rKys" + + "/7Gxsf+3t7f/vr6+/8LCwv/IyMj/zc3N/9TU1P/a2tr/3t7e/+Tk5P/r6+v/8PDw/w==", + ) + } + + /** progressive with restart intervals (EOB runs must reset per interval). */ + @Test + fun decodesProgressiveRestart() { + assertDecodes( + width = 16, + height = 16, + jpegBase64 = + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/wgARCAAQABADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAABgf/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/90A" + + "BAAB/9oADAMBAAIQAxAAAAGPvGTw/8QAFhAAAwAAAAAAAAAAAAAAAAAAAAQF/9oACAEBAAEFAkpB/9BKQf/RSkH/0kpB/8QAFxEB" + + "AAMAAAAAAAAAAAAAAAAABgAhMf/aAAgBAwEBPwE8hy5//8QAFREBAQAAAAAAAAAAAAAAAAAAAwD/2gAIAQIBAT8BFr//xAAWEAAD" + + "AAAAAAAAAAAAAAAAAAAAASH/2gAIAQEABj8CUP/QUP/RUP/SUP/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAT8hL//QL//R" + + "L//SL//aAAwDAQACAAMAAAAQU//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Qf//EABYRAAMAAAAAAAAAAAAAAAAAAAAh" + + "Mf/aAAgBAgEBPxCDP//EABUQAQEAAAAAAAAAAAAAAAAAAADx/9oACAEBAAE/EIL/0IL/0YL/0oL/2Q==", + rgbaBase64 = + "AAAA/wkDB/8ZBRD/JwQY/zkCIf9KAij/WwMz/2oDOP95Az//iANF/5gETv+qBFj/uwJf/8oBZ//ZBHD/4wZ3/wYMCP8PDw//HhEa" + + "/y4SIf8/Dyn/UA4y/2EQO/9wD0L/gBBI/40PTv+eEFj/rxBg/8EOaf/QDm//3xB6/+gTf/8IHBH/Eh8W/yEhIf8xISv/QR4y/1Me" + + "Ov9jIEP/ch9J/4IgUf+RIFj/oSBg/7IgZ//EHnD/0x94/+Iggf/rIoj/CSwY/xIuH/8hMSf/MDAw/0IuOf9RL0D/ZC9L/3IvUP+B" + + "Llj/jy9d/6EwaP+yMHD/xC52/9Mtf//iL4r/6zKP/wY9IP8PPyX/H0Iu/y5CN/9AQED/UD9H/2JAUf9wQFb/gEFg/45BZf+gQG7/" + + "sEF2/8E/f//RP4b/30CQ/+lDl/8FTSf/Dk8t/x1SNv8tUz7/Pk9H/09PT/9hUFj/b1Bf/35RZv+NUW3/nlF1/65Rff/AT4f/0E+P" + + "/95QmP/nU53/Bl0w/w9gNf8fYj//LmNH/z9fUP9PYFj/YWFh/3BhaP+AYXD/jWJ2/55ifv+vYob/wV+Q/9FgmP/fYaD/6WSm/wZt" + + "OP8PcD3/H3JI/y9yT/9AcFr/T29g/2Fwaf9wcHD/gHF4/41xf/+ecYb/sHGO/8FumP/Rb6D/4HCo/+lzr/8HfUH/D39H/x+BUP8v" + + "glj/QH9i/1F+af9jf3H/cH94/4CAgP+PgIf/oYGQ/7CAlv/BfqH/0X6o/+GAs//pgrf/B4xK/xGPUP8fkFj/L5Fg/0GOav9SjnL/" + + "Y456/3CPgP+Aj4j/j4+P/6GQmP+wkJ//wo2p/9GOsf/hkLv/6pPA/wmdU/8SoFj/IKFh/zChaf9Cn3P/Up97/2Ofg/9yn4r/gaCR" + + "/4+gmP+hoaH/saCo/8Odsv/Tnrr/4qHD/+ujyf8HrVn/EK9f/x+xav8vsXH/QK96/0+vgf9ir4v/cK+Q/4Cwmv+OsJ//oLGp/7Cw" + + "sP/Crrn/0a7C/+Gxy//qs9D/Bb5h/w7BZv8dw3H/LMJ6/z7AgP9PwIj/YcGT/27Bl/9+waD/jMGl/5/BsP+uwrf/v7+//8+/yf/e" + + "wtH/58TY/wXOaP8O0G//HdF4/yzSgP8+0In/T9CQ/1/QmP9u0J//ftGn/43Qrf+d0rb/rtG9/7/Pxf/Pz8//3tHa/+jU3/8I3XH/" + + "EeB2/x/hgP8v4of/QeCQ/1LgmP9i4KH/cOCo/4Dhrv+P4LX/oOK+/7Dgxv/C3s//0t/W/+Hh4f/q5Oj/Dep5/xfsgP8m74n/Ne6R" + + "/0bsmP9Y7KL/aO2r/3bssP+G7bj/le29/6buyP+37s//yOvX/9fr4P/n7en/8PDw/w==", + ) + } + + /** + * Arithmetic-coded JPEG is out of scope and must be refused by name rather than decoded to garbage. + * The fixture is a baseline JPEG whose SOF0 marker is patched to SOF9, which is how a decoder sees + * an arithmetic frame. + */ + @Test + fun rejectsArithmeticCoded() { + val arithmetic = + Base64.decode( + "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMU" + + "FRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU" + + "FBQUFBQUFBT/yQARCAAQABADAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" + + "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW" + + "V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi" + + "4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC" + + "AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm" + + "Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq" + + "8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD4/wDBfwh/1f7j9KKNYOHuIfh94958F/CH/V/uP0r3KNY/p3h3iL4fePY/Bfwh/wBX+4/S" + + "vh6NY/zF4d4i+H3j3nwX8If9X+4/Svco1j+neHuIfh94/9k=", + ) + assertTrue(JpegReader.matches(arithmetic), "an arithmetic-coded JPEG still carries the JPEG magic") + val failure = assertFailsWith { JpegReader.read(arithmetic) } + assertTrue(failure.message!!.contains("arithmetic"), "the rejection names the unsupported feature: ${failure.message}") + } + + /** A non-JPEG buffer is refused rather than misparsed. */ + @Test + fun rejectsNonJpeg() { + assertFailsWith { JpegReader.read(ByteArray(64)) } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/kra/KraChannelMaskTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/kra/KraChannelMaskTest.kt new file mode 100644 index 0000000..22221eb --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/kra/KraChannelMaskTest.kt @@ -0,0 +1,48 @@ +package org.umamo.format.kra + +import org.umamo.format.art.ChannelMask +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse + +/** + * Unit tests for the channelflags to ChannelMask mapping. channelflags is a per-channel enable mask + * ('0' disables, else enables) in channel-index order, which for RGB is Blue, Green, Red, Alpha and + * for GRAYA is Gray, Alpha. A disabled alpha is Krita's "Inherit Alpha" (the clipped signal). + * Values like "1110" are real Krita output - its comic templates ship inherit-alpha layers. + */ +class KraChannelMaskTest { + private val rgba = KraPixelFormat(channelCount = 4, depth = KraColorDepth.UnsignedByte, isRgb = true) + private val graya = KraPixelFormat(channelCount = 2, depth = KraColorDepth.UnsignedByte, isRgb = false) + + @Test + fun emptyOrFullMaskEnablesEverything() { + assertEquals(ChannelMask.ALL, channelMaskFrom("", rgba)) + assertEquals(ChannelMask.ALL, channelMaskFrom(null, rgba)) + assertEquals(ChannelMask.ALL, channelMaskFrom("1111", rgba)) + } + + @Test + fun rgbaAlphaOffIsInheritAlpha() { + // "1110": R,G,B enabled, alpha (index 3) disabled - real Krita comic-template value. + val mask = channelMaskFrom("1110", rgba) + assertEquals(ChannelMask(red = true, green = true, blue = true, alpha = false), mask) + assertFalse(mask.alpha) // the caller maps !alpha onto clipped + } + + @Test + fun rgbaColorChannelsFollowBgraIndexOrder() { + // Index order is Blue(0), Green(1), Red(2), Alpha(3). "0111" disables index 0 = blue. + assertEquals(ChannelMask(red = true, green = true, blue = false, alpha = true), channelMaskFrom("0111", rgba)) + // "1101" disables index 2 = red. + assertEquals(ChannelMask(red = false, green = true, blue = true, alpha = true), channelMaskFrom("1101", rgba)) + } + + @Test + fun grayaGrayChannelMapsToRgbTogether() { + // GRAYA index order is Gray(0), Alpha(1). "10" = gray on, alpha off. + assertEquals(ChannelMask(red = true, green = true, blue = true, alpha = false), channelMaskFrom("10", graya)) + // "01" = gray off (so R, G, B all off), alpha on. + assertEquals(ChannelMask(red = false, green = false, blue = false, alpha = true), channelMaskFrom("01", graya)) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/kra/KraLzfTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/kra/KraLzfTest.kt new file mode 100644 index 0000000..d937fea --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/kra/KraLzfTest.kt @@ -0,0 +1,45 @@ +package org.umamo.format.kra + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Unit tests for the pure KRA tile primitives - LZF decode and color delinearisation - using + * hand-built byte vectors, so they run with no external corpus. These verify the trickiest, + * citation-bound logic in isolation; the corpus-gated KraReaderTest exercises the same code on real + * Krita output (which is dense with back-references). + */ +class KraLzfTest { + @Test + fun lzfDecodesALiteralRun() { + // A literal run of N bytes is encoded as control byte (N-1) followed by the N raw bytes. + val stream = byteArrayOf(3, 'A'.code.toByte(), 'B'.code.toByte(), 'C'.code.toByte(), 'D'.code.toByte()) + val output = ByteArray(4) + val written = lzfDecompress(stream, inputOffset = 0, inputLength = stream.size, output = output) + assertEquals(4, written, "literal run length") + assertContentEquals("ABCD".encodeToByteArray(), output, "literal bytes copied verbatim") + } + + @Test + fun lzfDecodesAnOverlappingBackReference() { + // Literal AB, then a back-reference copying 3 bytes at distance 2, an overlapping ABA, + // yielding ABABA. Control 32 = (stored length 1 shifted left 5) or high distance bits 0; the + // next byte 1 is the low distance bits (stored distance = actual distance minus 1). + val stream = byteArrayOf(1, 'A'.code.toByte(), 'B'.code.toByte(), 32, 1) + val output = ByteArray(5) + val written = lzfDecompress(stream, inputOffset = 0, inputLength = stream.size, output = output) + assertEquals(5, written, "back-reference expands output") + assertContentEquals("ABABA".encodeToByteArray(), output, "overlapping copy expands run") + } + + @Test + fun delinearizeReinterleavesPlanarChannels() { + // 2 pixels times 4 channels: planar input is channel-major (stride = pixel count = 2); output + // is pixel-major (b,g,r,a,b,g,r,a). Distinct values per channel and pixel prove the mapping. + val planar = byteArrayOf(10, 11, 20, 21, 30, 31, 40, 41) + val packed = ByteArray(8) + delinearizeColors(planar, packed, dataSize = 8, pixelSize = 4) + assertContentEquals(byteArrayOf(10, 20, 30, 40, 11, 21, 31, 41), packed, "planar to interleaved") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/moc3/Moc3GetVersionTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/Moc3GetVersionTest.kt new file mode 100644 index 0000000..7e178dd --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/Moc3GetVersionTest.kt @@ -0,0 +1,42 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocVersion +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * The `.moc3` version probe: a synthetic 64-byte header (the same fixture style as + * FormatRegistryTest) carrying the magic plus a version byte at +0x04 is all `getVersion` reads. + */ +class Moc3GetVersionTest { + /** A 64-byte buffer with the MOC3 magic and [versionByte] at file offset 0x04. */ + private fun mocHeaderBytes(versionByte: Int): ByteArray = + ByteArray(64).also { bytes -> + "MOC3".encodeToByteArray().copyInto(bytes) + bytes[4] = versionByte.toByte() + } + + @Test + fun probesEveryKnownVersionByte() { + for (version in MocVersion.entries) { + assertEquals( + version, + Moc3.getVersion(mocHeaderBytes(version.byteValue)), + "version byte ${version.byteValue}", + ) + } + } + + @Test + fun unknownVersionByteProbesNull() { + assertNull(Moc3.getVersion(mocHeaderBytes(99)), "probe never throws on an unknown byte") + assertNull(Moc3.getVersion(mocHeaderBytes(0)), "zero is below the valid 1..6 range") + } + + @Test + fun nonMocBytesProbeNull() { + assertNull(Moc3.getVersion("NOPE".encodeToByteArray() + ByteArray(60)), "wrong magic") + assertNull(Moc3.getVersion(ByteArray(4)), "shorter than a header") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocDeformerBindingTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocDeformerBindingTest.kt new file mode 100644 index 0000000..0cb08d8 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocDeformerBindingTest.kt @@ -0,0 +1,161 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocLowering +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.moc.CanvasInfo +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.format.moc3.model.Part +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.RotationKeyform +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.format.moc3.model.WarpKeyform +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins that a lowered deformer's keyform binding is written identically to the unified column + * (MOC3 §5.6 s12) and to its per-type column (s19 for a warp, s25 for a rotation). + * + * The two columns are the same datum stored twice and the official runtime may raise a MOC3 + * validation error if they disagree. [org.umamo.format.moc3.model.Deformer] therefore carries ONE + * `keyformBindingIndex` and the lowering projects both columns from it, which makes divergence + * unrepresentable rather than merely unlikely. This test is what keeps it that way: a refactor that + * walked the unified list and the per-type lists separately would still compile and still pass every + * corpus gate, because the corpus never diverges - it would only break on a file we emitted. + * + * The deformers below deliberately interleave warps and rotations AND give each its own binding + * index, so a lowering that confused a type-local index for a unified one cannot pass by + * coincidence. Both halves are load-bearing: interleaving alone still leaves every column reading + * the same value if the deformers share a binding, and identical columns agree no matter which + * index was used to build them. + * + * @see MOC3.md §5.6 s12 + */ +class MocDeformerBindingTest { + /** + * Reads a lowered section back as an [IntArray]. + * + * @param Map sections The lowered section map, keyed by table index. + * @param Section section The section to read. + * @param MocVersion version The version whose table index applies. + * @return IntArray The decoded values. + */ + private fun intsOf(sections: Map, section: Section, version: MocVersion): IntArray { + val bytes = sections.getValue(section.indexIn(version)) + val reader = LittleEndianReader(bytes) + return IntArray(bytes.size / 4) { reader.readInt32() } + } + + @Test + fun unifiedAndPerTypeKeyformBindingColumnsAgree() { + val version = MocVersion.V50 + val warpKeyform = WarpKeyform(FloatArray(8), opacity = 1f, multiplyColor = null, screenColor = null) + val rotationKeyform = + RotationKeyform( + originX = 0f, + originY = 0f, + angle = 0f, + scale = 1f, + reflectX = false, + reflectY = false, + opacity = 1f, + multiplyColor = null, + screenColor = null, + ) + + /** + * Builds a static warp on the given binding. + * + * @param String id The deformer id. + * @param Int binding The keyform-binding index. + * @return WarpDeformer The deformer. + */ + fun warp(id: String, binding: Int) = + WarpDeformer( + id = id, + keyformBindingIndex = binding, + isVisible = true, + isEnabled = true, + parentPartIndex = -1, + parentDeformerIndex = -1, + rows = 1, + columns = 1, + mode = 0, + keyforms = listOf(warpKeyform), + ) + + /** + * Builds a static rotation on the given binding. + * + * @param String id The deformer id. + * @param Int binding The keyform-binding index. + * @return RotationDeformer The deformer. + */ + fun rotation(id: String, binding: Int) = + RotationDeformer( + id = id, + keyformBindingIndex = binding, + isVisible = true, + isEnabled = true, + parentPartIndex = -1, + parentDeformerIndex = -1, + baseAngle = 0f, + keyforms = listOf(rotationKeyform), + ) + + val document = + MocDocument( + version = version, + canvas = CanvasInfo(pixelsPerUnit = 1f, originX = 0f, originY = 0f, width = 10f, height = 10f), + parameters = emptyList(), + // One binding per deformer, so every value in the columns below is DISTINCT. Sharing one + // binding would make all three columns read as zeros, and a lowering that indexed the + // per-type column with the unified index would produce byte-identical output to a correct + // one - the assertions would hold while testing nothing. + keyformBindings = (0..4).associateWith { index -> KeyformBinding(index = index, axes = emptyList()) }, + parts = listOf(Part("Part0", -1, 0, floatArrayOf(0f))), + // Interleaved on purpose: type-local indices (0,0,1,1,2) diverge from file indices here. + deformers = + listOf( + warp("Warp0", binding = 0), + rotation("Rotation0", binding = 1), + warp("Warp1", binding = 2), + rotation("Rotation1", binding = 3), + warp("Warp2", binding = 4), + ), + artMeshes = emptyList(), + glues = emptyList(), + renderOrderGroups = emptyList(), + ) + + val sections = MocLowering.lower(document) + val unified = intsOf(sections, Section.DEFORMER_KEYFORM_BINDING, version) + val warpBindings = intsOf(sections, Section.WARP_KEYFORM_BINDING, version) + val rotationBindings = intsOf(sections, Section.ROTATION_KEYFORM_BINDING, version) + val types = intsOf(sections, Section.DEFORMER_TYPE, version) + val localIndices = intsOf(sections, Section.DEFORMER_LOCAL_INDEX, version) + + assertEquals(document.deformers.size, unified.size, "unified binding column covers every deformer") + for (deformerIndex in document.deformers.indices) { + // Type 0 is a warp, anything else a rotation; the per-type column is addressed by s18. + val perType = + if (types[deformerIndex] == 0) { + warpBindings[localIndices[deformerIndex]] + } else { + rotationBindings[localIndices[deformerIndex]] + } + assertEquals( + document.deformers[deformerIndex].keyformBindingIndex, + unified[deformerIndex], + "deformer $deformerIndex: s12 carries the document's binding", + ) + assertEquals( + unified[deformerIndex], + perType, + "deformer $deformerIndex: s12 agrees with its per-type column (runtime rejects a mismatch)", + ) + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocLoweringInvariantsTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocLoweringInvariantsTest.kt new file mode 100644 index 0000000..e942aa3 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocLoweringInvariantsTest.kt @@ -0,0 +1,222 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocLowering +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.moc.CanvasInfo +import org.umamo.format.moc3.moc.MocParameter +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.KeyformAxis +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.format.moc3.model.Part +import org.umamo.format.moc3.model.RenderOrderGroup +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Lowering invariants the golden corpus structurally cannot check. + * + * Every corpus model is dense in its keyform bindings and none carries a blend-shape-typed parameter + * that owns no record, so the choices those shapes would expose are invisible to the byte-exact gate: + * a lowering that traversed the binding map by entry rather than by index, or that wrote the wrong + * empty-slot filler, reproduces the corpus byte-for-byte and would only break on a file we emitted. + * These documents are hand-built to have exactly the shapes the corpus lacks, and run unconditionally. + * + * @see MOC3.md §5.6 + */ +class MocLoweringInvariantsTest { + /** + * Reads a lowered section back as an [IntArray]. + * + * @param Map sections The lowered section map, keyed by table index. + * @param Section section The section to read. + * @param MocVersion version The version whose table index applies. + * @return IntArray The decoded values. + */ + private fun intsOf(sections: Map, section: Section, version: MocVersion): IntArray { + val bytes = sections.getValue(section.indexIn(version)) + val reader = LittleEndianReader(bytes) + return IntArray(bytes.size / 4) { reader.readInt32() } + } + + /** + * Builds a parameter with one axis worth of range. + * + * @param String id The parameter id. + * @param ParameterType? type The parameter type, or null when the version stores none. + * @return MocParameter The parameter. + */ + private fun parameter(id: String, type: ParameterType?) = + MocParameter( + id = id, + minimumValue = -1f, + maximumValue = 1f, + defaultValue = 0f, + repeats = false, + type = type, + ) + + /** + * Builds a document around [keyformBindings], with no deformers, meshes, or blend records. + * + * @param Map keyformBindings The binding map, sparse or dense. + * @param List parameters The parameter list. + * @param List renderOrderGroups The render-order groups, empty by default. + * @return MocDocument The document. + */ + private fun documentWith( + keyformBindings: Map, + parameters: List, + renderOrderGroups: List = emptyList(), + ) = MocDocument( + version = MocVersion.V50, + canvas = CanvasInfo(pixelsPerUnit = 1f, originX = 0f, originY = 0f, width = 10f, height = 10f), + parameters = parameters, + keyformBindings = keyformBindings, + parts = listOf(Part("Part0", -1, 0, floatArrayOf(0f))), + deformers = emptyList(), + artMeshes = emptyList(), + glues = emptyList(), + renderOrderGroups = renderOrderGroups, + ) + + @Test + fun countInfoSizesTheBindingTableByWidthNotByEntryCount() { + val version = MocVersion.V50 + val parameters = listOf(parameter("ParamA", ParameterType.NORMAL)) + // A HOLE at index 1: three entries, but the table is four slots wide. The runtime allocates its + // keyform-binding array from CountInfo[12] and then indexes it by an object's raw + // keyformBindingIndex, which reaches 3 here - so a count of 3 sizes the array one slot short of + // the index that will be used against it, and the read runs off the end inside the official core. + val sparse = + mapOf( + 0 to KeyformBinding(index = 0, axes = listOf(KeyformAxis(0, floatArrayOf(-1f, 0f, 1f)))), + 2 to KeyformBinding(index = 2, axes = listOf(KeyformAxis(0, floatArrayOf(0f, 1f)))), + 3 to KeyformBinding(index = 3, axes = emptyList()), + ) + val document = documentWith(sparse, parameters) + val lowered = MocLowering.lower(document) + val countInfo = intsOf(lowered, Section.COUNT_INFO, version) + + val bindingStart = intsOf(lowered, Section.KEYFORM_BINDING_START, version) + val bindingCount = intsOf(lowered, Section.KEYFORM_BINDING_COUNT, version) + assertEquals(4, bindingStart.size, "s73 covers every table slot, including the hole") + assertEquals(4, bindingCount.size, "s74 covers every table slot, including the hole") + assertEquals( + bindingStart.size, + countInfo[12], + "CountInfo[12] sizes the runtime's binding array to the table width the sections actually carry", + ) + // The hole lowers to a zero-axis binding, which the decoder reads back as a static binding - + // degraded but loadable. It must not shift the rows after it. + assertEquals(0, bindingCount[1], "the hole contributes no axes") + } + + @Test + fun blendFreeParameterRunsCarryTheTypeSpecificEmptyFiller() { + val version = MocVersion.V50 + // A blend-shape-typed parameter that owns no record stores begin = -1; a normal one stores 0. + // Both fillers mean "no run", and no corpus model has the first shape on a blend-FREE document - + // every v4+ blend-free sample is all-normal - so nothing else can tell the two apart. + val parameters = + listOf( + parameter("ParamNormal", ParameterType.NORMAL), + parameter("ParamMorph", ParameterType.BLEND_SHAPE), + ) + val document = documentWith(emptyMap(), parameters) + val lowered = MocLowering.lower(document) + + val parameterBegin = intsOf(lowered, Section.BLENDSHAPE_PARAMETER_BEGIN, version) + val parameterCount = intsOf(lowered, Section.BLENDSHAPE_PARAMETER_COUNT, version) + assertEquals(listOf(0, -1), parameterBegin.toList(), "s115 fillers are type-specific on a blend-free document") + assertEquals(listOf(0, 0), parameterCount.toList(), "s116 counts no bindings for either parameter") + } + + @Test + fun parameterlessDocumentEmitsNoPerParameterBlendColumns() { + val version = MocVersion.V50 + // The columns are per-parameter. Emitting them zero-length would look harmless, but + // `MocEncoder.bake` overrides a reference file's section with whatever the lowering produced - + // so an empty section here erases one that was going to be carried. + val document = documentWith(emptyMap(), emptyList()) + val lowered = MocLowering.lower(document) + + assertEquals(null, lowered[Section.BLENDSHAPE_PARAMETER_BEGIN.indexIn(version)], "s115 stays absent") + assertEquals(null, lowered[Section.BLENDSHAPE_PARAMETER_COUNT.indexIn(version)], "s116 stays absent") + } + + @Test + fun everyProducerRunsThroughTheStrictMerge() { + // `lower` throws when two producers claim one section index, so reaching it at all is the pass + // condition - but only if every producer actually ran. A document that reaches none of them + // would return an empty map and "prove" disjointness vacuously, so this asserts a section OWNED + // BY EACH producer is present: whatever they wrote, they wrote it through the strict merge. + val parameters = listOf(parameter("ParamA", ParameterType.NORMAL), parameter("ParamB", ParameterType.BLEND_SHAPE)) + val bindings = + mapOf( + 0 to KeyformBinding(index = 0, axes = listOf(KeyformAxis(0, floatArrayOf(-1f, 0f, 1f)))), + 1 to KeyformBinding(index = 1, axes = emptyList()), + ) + // A childless render-order group is the cheapest thing that reaches the auxiliary producer - + // its glue, render-order, and offscreen blocks are each guarded on a non-empty list. + val document = documentWith(bindings, parameters, renderOrderGroups = listOf(RenderOrderGroup(emptyList()))) + val version = MocVersion.V50 + val lowered = MocLowering.lower(document) + + val ownedByProducer = + mapOf( + "structural" to Section.PARAM_ID, + "valueTables" to Section.PART_DRAW_ORDER, + "auxiliary" to Section.RENDER_ORDER_CHILD_COUNT, + "keyformGrid" to Section.KEY_POSITIONS, + "blendShapes" to Section.BLENDSHAPE_PARAMETER_BEGIN, + "runtimeSlots" to Section.PART_RUNTIME_SLOT, + "derivedIndexes" to Section.PARAM_SNAP_TYPE, + "countInfo" to Section.COUNT_INFO, + ) + for ((producerName, section) in ownedByProducer) { + assertTrue( + lowered.containsKey(section.indexIn(version)), + "$producerName ran: ${section.name} is present in the merged map", + ) + } + } + + @Test + fun countInfoCountsEveryFloatWrittenIntoKeyPositions() { + val version = MocVersion.V50 + val parameters = listOf(parameter("ParamA", ParameterType.NORMAL), parameter("ParamB", ParameterType.NORMAL)) + // Two parameters, each with two distinct key-lists, so the main-grid dedup region AND the + // per-parameter union region are both non-empty. Every v4+ blend-free corpus model has zero + // parameter bindings, so this shape is the one the corpus cannot produce. + val bindings = + mapOf( + 0 to KeyformBinding(index = 0, axes = listOf(KeyformAxis(0, floatArrayOf(-1f, 0f, 1f)))), + 1 to KeyformBinding(index = 1, axes = listOf(KeyformAxis(0, floatArrayOf(-1f, 1f)))), + 2 to KeyformBinding(index = 2, axes = listOf(KeyformAxis(1, floatArrayOf(0f, 0.5f, 1f)))), + ) + val document = documentWith(bindings, parameters) + val lowered = MocLowering.lower(document) + val countInfo = intsOf(lowered, Section.COUNT_INFO, version) + + val keyPositions = lowered.getValue(Section.KEY_POSITIONS.indexIn(version)) + val parameterKeyStart = intsOf(lowered, Section.PARAM_KEY_START, version) + val parameterKeyCount = intsOf(lowered, Section.PARAM_KEY_COUNT, version) + assertEquals( + keyPositions.size / 4, + countInfo[14], + "CountInfo[14] declares exactly the float count section 77 carries", + ) + // 103/104 address the union region; the runtime sizes its parameter key store from CountInfo[14] + // and then reads those runs out of it, so a run ending past the declared count reads past the + // buffer the runtime just allocated. + val lastRunEnd = parameterKeyStart.last() + parameterKeyCount.last() + assertEquals( + countInfo[14], + lastRunEnd, + "the last parameter key run ends exactly at the declared KEY_POSITIONS extent", + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocSanityTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocSanityTest.kt new file mode 100644 index 0000000..ca8f0be --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/MocSanityTest.kt @@ -0,0 +1,77 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.io.LittleEndianWriter +import org.umamo.format.moc3.moc.ConstantFlag +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocVersion +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Platform-independent moc3 tests using synthetic data (no sample/jar needed); mirrors the cmo3 + * module's CaffRoundTripTest so the public suite has coverage without the git-ignored samples. + */ +class MocSanityTest { + @Test + fun littleEndianRoundTrips() { + val writer = LittleEndianWriter() + writer.writeU8(0xAB) + writer.writeInt32(-123456) + writer.writeInt32(0x7FFFFFFF) + writer.writeFloat32(3.5f) + writer.writeBytes("ParamAngleX".encodeToByteArray()) + writer.zeroPad(64 - 11) // pad the "ID record" to 64 bytes + val bytes = writer.toByteArray() + + val reader = LittleEndianReader(bytes) + assertEquals(0xAB, reader.readU8()) + assertEquals(-123456, reader.readInt32()) + assertEquals(0x7FFFFFFF, reader.readInt32()) + assertEquals(3.5f, reader.readFloat32()) + assertEquals("ParamAngleX", reader.readFixedString(64)) + } + + @Test + fun versionByteMapping() { + assertEquals(MocVersion.V40, MocVersion.fromByte(3)) + assertEquals(MocVersion.V42, MocVersion.fromByte(4)) + assertEquals(MocVersion.V53, MocVersion.fromByte(6)) + assertEquals(6, MocVersion.LATEST) + } + + @Test + fun constantFlagBits() { + assertEquals(1, ConstantFlag.BLEND_ADDITIVE) + assertEquals(2, ConstantFlag.BLEND_MULTIPLICATIVE) + assertEquals(4, ConstantFlag.IS_DOUBLE_SIDED) + assertEquals(8, ConstantFlag.IS_INVERTED_MASK) + } + + @Test + fun syntheticMocRoundTrips() { + // Build a minimal valid moc3: 64-byte header, two section offsets, two 16-byte sections. + val writer = LittleEndianWriter() + writer.writeBytes(byteArrayOf(0x4D, 0x4F, 0x43, 0x33)) // "MOC3" + writer.writeU8(3) // version byte (4.0) + writer.writeU8(0) // little-endian flag + writer.zeroPad(64 - 6) // reserved up to the offset table at 0x40 + val firstOffset = 80 + writer.writeInt32(firstOffset) // section 0 offset + writer.writeInt32(firstOffset + 16) // section 1 offset + writer.zeroPad(firstOffset - writer.position) // pad table region to the data region + writer.writeBytes(ByteArray(16) { it.toByte() }) // section 0 data + writer.writeBytes(ByteArray(16) { (it + 100).toByte() }) // section 1 data + val original = writer.toByteArray() + + val model = MocCodec.read(original) + assertEquals(MocVersion.V40, model.version) + assertEquals(2, model.sectionCount) + assertContentEquals(intArrayOf(firstOffset, firstOffset + 16), model.offsets) + assertTrue(!model.isBigEndian) + + assertContentEquals(original, MocCodec.write(model), "synthetic moc3 round-trips byte-for-byte") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/moc3/SectionRegistryTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/SectionRegistryTest.kt new file mode 100644 index 0000000..81912df --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/moc3/SectionRegistryTest.kt @@ -0,0 +1,95 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Structural invariants of the [Section] registry itself, independent of any corpus file. + * + * The registry is the single source of truth for what a `.moc3` contains: one entry per section + * index, carrying its element type, sizing rule, and per-version slot. A second untyped registry of + * bare index constants used to sit beside it, and the sections named only there were invisible to + * both the typed decode and the lossless gate - so "is this index modeled?" had two answers. These + * tests keep it to one. + * + * @see MOC3.md §section map + */ +class SectionRegistryTest { + /** + * No two sections may claim the same table slot in the same version. + * + * A collision is silent otherwise: both entries decode, one lowering overwrites the other, and the + * bake emits whichever ran last. + */ + @Test + fun noTwoSectionsShareAnIndexInAnyVersion() { + for (version in MocVersion.entries) { + val owners = HashMap() + for (section in Section.entries) { + val index = section.indexIn(version) + if (index < 0) { + continue + } + val existing = owners.put(index, section) + assertEquals(null, existing, "${version.label}: index $index claimed by both $existing and $section") + } + } + } + + /** + * Every slot the version's table defines is modeled - the registry has no holes. + * + * [MocEncoder.sectionCount] is the editor's table length per version, so the indices a file can + * legitimately carry are exactly `0 until sectionCount`. Any gap here is a section a bake would + * have to carry verbatim from a reference container, which is precisely what makes a fresh + * synthesis impossible - so a gap is a real capability limit, not a cosmetic one. + */ + @Test + fun everyTableSlotIsModeledForEveryVersion() { + for (version in MocVersion.entries) { + val modeled = Section.entries.map { it.indexIn(version) }.filter { it >= 0 }.toSet() + val expected = (0 until MocEncoder.sectionCount(version)).toSet() + assertEquals( + emptySet(), + expected - modeled, + "${version.label}: unmodeled table slots", + ) + assertEquals( + emptySet(), + modeled - expected, + "${version.label}: sections claim slots past the version's table", + ) + } + } + + /** + * A section present in one version keeps the same index in every later version. + * + * MOC3 only ever APPENDS: a newer version adds higher indices rather than renumbering, which is + * what lets one index mean one thing across the whole family. A section that moved would break + * every version-agnostic reader, so the registry should never express one. + */ + @Test + fun sectionIndicesNeverMoveOnceIntroduced() { + val versions = MocVersion.entries.sortedBy { it.byteValue } + for (section in Section.entries) { + var introduced = -1 + for (version in versions) { + val index = section.indexIn(version) + if (index < 0) { + // Absent after being present would mean the format REMOVED a section; none does. + assertTrue(introduced < 0, "$section disappears again at ${version.label}") + continue + } + if (introduced < 0) { + introduced = index + } + assertEquals(introduced, index, "$section moves from $introduced to $index at ${version.label}") + } + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/png/PngCodecTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/png/PngCodecTest.kt new file mode 100644 index 0000000..06d9a11 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/png/PngCodecTest.kt @@ -0,0 +1,287 @@ +package org.umamo.format.png + +import okio.Buffer +import org.umamo.format.raster.RasterImage +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * Exercises [PngCodec] with hand-built PNGs (via the codec's own chunk writer), pinning every color + * type, bit depth, tRNS transparency, and sub-byte packing to a known-exact expected RGBA. + * + * Lives in commonTest so it runs on every target: the codec is pure Kotlin apart from the zlib bridge, + * and these cases are what prove a new platform decodes identically. The complementary strategy — + * decoding PNGs written by javax.imageio, an independent reference encoder — necessarily needs the + * JVM, and lives in PngImageIoParityTest. + */ +class PngCodecTest { + /** Builds a ByteArray from int literals (so values > 127 read cleanly). */ + private fun bytes(vararg values: Int): ByteArray = ByteArray(values.size) { values[it].toByte() } + + /** + * Assembles a minimal, non-interlaced PNG (filter type 0 on every row) from raw sample bytes, + * reusing the codec's own internal chunk framing so the test controls the exact bytes. + * + * @param Int width Image width. + * @param Int height Image height. + * @param Int bitDepth Bits per sample. + * @param Int colorType PNG color type. + * @param ByteArray samples The raw, row-major sample bytes (height * rowBytes). + * @param Int rowBytes Bytes per scanline (excluding the filter byte). + * @param ByteArray? palette The PLTE bytes, or null. + * @param ByteArray? trns The tRNS bytes, or null. + * @param Int compressionMethod The IHDR compression method byte. + * @param Function1 idatPieces Splits the zlib stream into the data of the IDAT chunks to write. + * @return ByteArray The complete `.png` file. + */ + private fun buildPng( + width: Int, + height: Int, + bitDepth: Int, + colorType: Int, + samples: ByteArray, + rowBytes: Int, + palette: ByteArray? = null, + trns: ByteArray? = null, + compressionMethod: Int = 0, + idatPieces: (ByteArray) -> List = { stream -> listOf(stream) }, + ): ByteArray { + val filtered = Buffer() + for (rowIndex in 0 until height) { + filtered.writeByte(0) // filter type None + filtered.write(samples, rowIndex * rowBytes, rowBytes) + } + val ihdr = Buffer() + ihdr.writeInt(width) + ihdr.writeInt(height) + ihdr.writeByte(bitDepth) + ihdr.writeByte(colorType) + ihdr.writeByte(compressionMethod) + ihdr.writeByte(0) // filter method + ihdr.writeByte(0) // interlace: none + + val out = Buffer() + out.write(PNG_SIGNATURE) + writeChunk(out, "IHDR", ihdr.readByteArray()) + if (palette != null) { + writeChunk(out, "PLTE", palette) + } + if (trns != null) { + writeChunk(out, "tRNS", trns) + } + for (piece in idatPieces(deflateIdat(filtered.readByteArray()))) { + writeChunk(out, "IDAT", piece) + } + writeChunk(out, "IEND", ByteArray(0)) + return out.readByteArray() + } + + @Test + fun writeThenReadRoundTripsRgba() { + val source = + RasterImage( + width = 2, + height = 2, + rgba = bytes(10, 20, 30, 40, 50, 60, 70, 255, 80, 90, 100, 128, 200, 210, 220, 64), + ) + val decoded = PngCodec.read(PngCodec.write(source)) + assertEquals(2, decoded.width) + assertEquals(2, decoded.height) + assertContentEquals(source.rgba, decoded.rgba, "RGBA survives write -> read") + } + + @Test + fun writeThenReadRoundTripsOddWidth() { + // A width that is not a power of two exercises the scanline byte math on both ends. + val width = 5 + val height = 3 + val rgba = ByteArray(width * height * 4) { (it * 7 % 256).toByte() } + val decoded = PngCodec.read(PngCodec.write(RasterImage(width, height, rgba))) + assertContentEquals(rgba, decoded.rgba, "odd-width RGBA survives write -> read") + } + + @Test + fun decodesGrayscale8WithTransparentKey() { + // tRNS gray key = 255, so the single 255-valued pixel decodes transparent; the rest opaque. + val png = buildPng(width = 3, height = 2, bitDepth = 8, colorType = 0, samples = bytes(10, 20, 200, 30, 255, 40), rowBytes = 3, trns = bytes(0, 255)) + val decoded = PngCodec.read(png) + val expected = bytes(10, 10, 10, 255, 20, 20, 20, 255, 200, 200, 200, 255, 30, 30, 30, 255, 255, 255, 255, 0, 40, 40, 40, 255) + assertContentEquals(expected, decoded.rgba) + } + + @Test + fun decodesPalette8WithTrns() { + val palette = bytes(255, 0, 0, 0, 255, 0, 0, 0, 255, 128, 128, 128) + val trns = bytes(255, 128) // idx0 opaque, idx1 half; idx2/idx3 default opaque + val png = buildPng(width = 2, height = 2, bitDepth = 8, colorType = 3, samples = bytes(0, 1, 2, 3), rowBytes = 2, palette = palette, trns = trns) + val decoded = PngCodec.read(png) + val expected = bytes(255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 255, 128, 128, 128, 255) + assertContentEquals(expected, decoded.rgba) + } + + @Test + fun decodesRgb8WithTransparentKey() { + val trns = bytes(0, 200, 0, 100, 0, 50) // key (200,100,50) as three 16-bit big-endian samples + val png = buildPng(width = 2, height = 1, bitDepth = 8, colorType = 2, samples = bytes(10, 20, 30, 200, 100, 50), rowBytes = 6, trns = trns) + val decoded = PngCodec.read(png) + assertContentEquals(bytes(10, 20, 30, 255, 200, 100, 50, 0), decoded.rgba) + } + + @Test + fun decodes16BitGrayscaleByTheSpecLinearEquation() { + // Every 16-bit value once, 256 per row, big-endian (PNG spec §7.2). + val samples = ByteArray(65536 * 2) + for (value in 0 until 65536) { + samples[value * 2] = (value ushr 8).toByte() + samples[value * 2 + 1] = value.toByte() + } + val png = buildPng(width = 256, height = 256, bitDepth = 16, colorType = 0, samples = samples, rowBytes = 512) + val decoded = PngCodec.read(png) + for (value in 0 until 65536) { + // PNG spec §13.12: floor(value * 255 / 65535 + 0.5), evaluated as one exact integer division. + val expected = ((2L * value * 255 + 65535) / (2L * 65535)).toInt() + assertEquals(expected, decoded.rgba[value * 4].toInt() and 0xFF, "16-bit sample $value") + } + } + + @Test + fun decodes16BitRgbaByTheSpecLinearEquation() { + // 0x00FF rounds up to 1 and 0xFF00 down to 254, where keeping the high byte would give 0 and 255. + val png = buildPng(width = 1, height = 1, bitDepth = 16, colorType = 6, samples = bytes(0x00, 0xFF, 0xFF, 0x00, 0x80, 0x80, 0xFF, 0xFF), rowBytes = 8) + assertContentEquals(bytes(1, 254, 128, 255), PngCodec.read(png).rgba) + } + + @Test + fun sixteenBitTransparentKeyMatchesBeforeRescaling() { + // PNG spec §13.12: the tRNS comparison is exact, on the raw samples. The second pixel's red + // differs from the key by one, so both pixels rescale to the same color but only the first is + // transparent. + val trns = bytes(0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC) + val samples = bytes(0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0x12, 0x35, 0x56, 0x78, 0x9A, 0xBC) + val png = buildPng(width = 2, height = 1, bitDepth = 16, colorType = 2, samples = samples, rowBytes = 12, trns = trns) + val decoded = PngCodec.read(png) + assertContentEquals(bytes(0x12, 0x56, 0x9A, 0, 0x12, 0x56, 0x9A, 255), decoded.rgba) + } + + @Test + fun decodesGrayscaleAlpha8() { + val png = buildPng(width = 2, height = 1, bitDepth = 8, colorType = 4, samples = bytes(10, 20, 200, 255), rowBytes = 4) + assertContentEquals(bytes(10, 10, 10, 20, 200, 200, 200, 255), PngCodec.read(png).rgba) + } + + @Test + fun decodesTwoBitPalette() { + // Indices 3,2,1,0 packed leftmost-first into one byte (PNG spec §7.2): 0b11_10_01_00. + val palette = bytes(255, 0, 0, 0, 255, 0, 0, 0, 255, 9, 9, 9) + val png = buildPng(width = 4, height = 1, bitDepth = 2, colorType = 3, samples = bytes(0xE4), rowBytes = 1, palette = palette) + assertContentEquals(bytes(9, 9, 9, 255, 0, 0, 255, 255, 0, 255, 0, 255, 255, 0, 0, 255), PngCodec.read(png).rgba) + } + + @Test + fun idatSplitAcrossChunksDecodesTheSame() { + // PNG spec §10.2: IDAT boundaries are arbitrary, including mid-scanline and empty chunks. + val width = 7 + val height = 5 + val samples = ByteArray(width * height * 4) { (it * 37 % 251).toByte() } + val whole = PngCodec.read(buildPng(width, height, bitDepth = 8, colorType = 6, samples = samples, rowBytes = width * 4)) + val split = + PngCodec.read( + buildPng(width, height, bitDepth = 8, colorType = 6, samples = samples, rowBytes = width * 4) { stream -> + listOf(stream.copyOfRange(0, 3), ByteArray(0), stream.copyOfRange(3, 11), stream.copyOfRange(11, stream.size)) + }, + ) + assertContentEquals(samples, whole.rgba) + assertContentEquals(whole.rgba, split.rgba) + } + + @Test + fun truncatedIdatStreamDecodesWhatItHolds() { + // Pseudo-random pixels keep the stream long, so half of it still reaches well past the first row. + val width = 256 + val height = 64 + var state = 12345 + val samples = + ByteArray(width * height * 4) { + state = state * 1103515245 + 12345 + (state ushr 16).toByte() + } + val png = buildPng(width, height, bitDepth = 8, colorType = 6, samples = samples, rowBytes = width * 4) { stream -> listOf(stream.copyOf(stream.size / 2)) } + val decoded = PngCodec.read(png) + val rowBytes = width * 4 + assertContentEquals(samples.copyOfRange(0, rowBytes), decoded.rgba.copyOfRange(0, rowBytes), "the first row survives") + assertTrue(decoded.rgba.copyOfRange((height - 1) * rowBytes, height * rowBytes).all { it == 0.toByte() }, "an unreached row is transparent black") + } + + @Test + fun rejectsBitDepthTheColorTypeDoesNotAllow() { + // PNG spec §11.2.2 Table 11.1: truecolor allows only 8 and 16 bits. + val png = buildPng(width = 2, height = 1, bitDepth = 4, colorType = 2, samples = bytes(0, 0, 0), rowBytes = 3) + assertFailsWith { PngCodec.read(png) } + } + + @Test + fun rejectsUnknownCompressionMethod() { + val png = buildPng(width = 1, height = 1, bitDepth = 8, colorType = 0, samples = bytes(0), rowBytes = 1, compressionMethod = 1) + assertFailsWith { PngCodec.read(png) } + } + + @Test + fun rejectsIndexedColorWithoutPalette() { + val png = buildPng(width = 1, height = 1, bitDepth = 8, colorType = 3, samples = bytes(0), rowBytes = 1) + assertFailsWith { PngCodec.read(png) } + } + + @Test + fun decodesOneBitGrayscaleScaledToFullRange() { + // 0b10110001 MSB-first: 1,0,1,1,0,0,0,1 -> 255,0,255,255,0,0,0,255. + val png = buildPng(width = 8, height = 1, bitDepth = 1, colorType = 0, samples = bytes(0xB1), rowBytes = 1) + val decoded = PngCodec.read(png) + val expected = + bytes( + 255, + 255, + 255, + 255, + 0, + 0, + 0, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 0, + 0, + 0, + 255, + 0, + 0, + 0, + 255, + 0, + 0, + 0, + 255, + 255, + 255, + 255, + 255, + ) + assertContentEquals(expected, decoded.rgba) + } + + @Test + fun decodedSignatureIsRejectedWhenCorrupt() { + val png = PngCodec.write(RasterImage(1, 1, bytes(1, 2, 3, 4))) + assertTrue(PngCodec.matches(png), "valid PNG matches") + png[1] = 0 + assertTrue(!PngCodec.matches(png), "corrupt signature does not match") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/psd/PsdSyntheticTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/psd/PsdSyntheticTest.kt new file mode 100644 index 0000000..bc11397 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/psd/PsdSyntheticTest.kt @@ -0,0 +1,326 @@ +package org.umamo.format.psd + +import okio.Buffer +import org.umamo.format.binary.deflateZlib +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Round-trips synthetic, hand-built PSD files through [PsdReader] to verify the channel decoder + * exactly, without needing a committed corpus or a reference reader for comparison. + * + * Each test constructs a single-layer RGBA PSD with known per-channel planes, encodes the channels + * with one of the three compressions a real `.psd` uses (raw, PackBits RLE, ZIP), and asserts the + * decoded RGBA is bit-exact and the geometry is correct. Together they cover the riskiest parts of + * the port: the channel-data offset math, every decompressor, the RGB+alpha assembly, and the + * lyid-or-name+order stable identity. + */ +class PsdSyntheticTest { + private val compressionRaw = 0 + private val compressionRle = 1 + private val compressionZip = 2 + + /** + * Compresses [data] to a zlib stream, matching the ZIP channel framing the reader inflates. + * + * @param ByteArray data The bytes to compress. + * @return ByteArray The zlib-wrapped deflate stream. + */ + private fun deflate(data: ByteArray): ByteArray = deflateZlib(data) + + /** + * PackBits-encodes one row as a single literal run (valid for rows up to 128 bytes). + * + * @param ByteArray row The raw row bytes. + * @return ByteArray The PackBits-encoded row (a 1-byte control of size-1, then the bytes). + */ + private fun packBitsRow(row: ByteArray): ByteArray { + val out = Buffer() + out.writeByte(row.size - 1) // control n: copy the next n+1 literal bytes + out.write(row) + return out.readByteArray() + } + + /** + * Encodes one channel's plane into its on-disk block: a 2-byte compression code then the + * (optionally compressed) sample bytes, with the per-row byte-count table for RLE. + * + * @param ByteArray plane The width*height raw 8-bit samples. + * @param Int width Row width in pixels. + * @param Int height Row count. + * @param Int compression The PSD compression code to apply. + * @return ByteArray The complete channel block. + */ + private fun encodeChannel(plane: ByteArray, width: Int, height: Int, compression: Int): ByteArray { + val out = Buffer() + out.writeShort(compression) + when (compression) { + compressionRaw -> out.write(plane) + compressionRle -> { + val encodedRows = (0 until height).map { rowIndex -> packBitsRow(plane.copyOfRange(rowIndex * width, rowIndex * width + width)) } + for (encoded in encodedRows) { + out.writeShort(encoded.size) // byte-count table entry + } + for (encoded in encodedRows) { + out.write(encoded) + } + } + + compressionZip -> out.write(deflate(plane)) + } + return out.readByteArray() + } + + /** + * Builds an additional-layer-info `lyid` block (8BIM signature, lyid key, u32 length 4, the id). + * + * @param Int layerId The Photoshop layer id to embed. + * @return ByteArray The 16-byte lyid block. + */ + private fun lyidBlock(layerId: Int): ByteArray { + val out = Buffer() + out.writeUtf8("8BIM") + out.writeUtf8("lyid") + out.writeInt(4) + out.writeInt(layerId) + return out.readByteArray() + } + + /** + * A raster layer mask for the synthetic layer: its plane over its own rectangle, and the mask + * data block's default color and disabled flag. + * + * @property ByteArray plane The mask values, row-major over the rectangle. + * @property Int left The rectangle's left edge in canvas pixels. + * @property Int top The rectangle's top edge in canvas pixels. + * @property Int width The rectangle's width. + * @property Int height The rectangle's height. + * @property Int defaultColor The mask value outside the rectangle (0 or 255). + * @property Boolean disabled Whether the mask is switched off. + */ + private class SyntheticMask( + val plane: ByteArray, + val left: Int, + val top: Int, + val width: Int, + val height: Int, + val defaultColor: Int, + val disabled: Boolean = false, + ) + + /** + * Builds a minimal valid version-1 RGB PSD with a single layer carrying the given channel planes, + * optionally embedding a `lyid` block so the stable-id path can be exercised, and optionally a + * raster layer mask (channel -2 plus its 20-byte mask data block). + * + * @param Int width Canvas/layer width. + * @param Int height Canvas/layer height. + * @param String name Layer name. + * @param ByteArray red Red plane (width*height). + * @param ByteArray green Green plane. + * @param ByteArray blue Blue plane. + * @param ByteArray alpha Alpha plane. + * @param Int compression The compression to apply to every channel. + * @param Int? layerId The lyid to embed, or null to omit the block. + * @param SyntheticMask? mask The raster layer mask to attach, or null for none. + * @return ByteArray The complete `.psd` bytes. + */ + private fun buildRgbPsd( + width: Int, + height: Int, + name: String, + red: ByteArray, + green: ByteArray, + blue: ByteArray, + alpha: ByteArray, + compression: Int, + layerId: Int? = null, + mask: SyntheticMask? = null, + ): ByteArray { + val channels = listOf(0 to red, 1 to green, 2 to blue, -1 to alpha) + val blocks = + channels.map { (id, plane) -> id to encodeChannel(plane, width, height, compression) } + + listOfNotNull(mask?.let { attached -> -2 to encodeChannel(attached.plane, attached.width, attached.height, compression) }) + + val out = Buffer() + + // File Header + out.writeUtf8("8BPS") + out.writeShort(1) // version 1 (PSD) + out.write(ByteArray(6)) // reserved + out.writeShort(3) // composite channel count + out.writeInt(height) + out.writeInt(width) + out.writeShort(8) // depth + out.writeShort(3) // mode = RGB + + out.writeInt(0) // Color Mode Data length + out.writeInt(0) // Image Resources length + out.writeInt(0) // Layer and Mask Information length (ignored by the reader) + out.writeInt(0) // Layer Info length (ignored by the reader) + out.writeShort(1) // layer count + + // Layer record + out.writeInt(0) // top + out.writeInt(0) // left + out.writeInt(height) // bottom + out.writeInt(width) // right + out.writeShort(blocks.size) + for ((id, block) in blocks) { + out.writeShort(id) + out.writeInt(block.size) + } + out.writeUtf8("8BIM") + out.writeUtf8("norm") + out.writeByte(255) // opacity + out.writeByte(0) // clipping + out.writeByte(0) // flags (visible) + out.writeByte(0) // filler + // UTF-8, which is what Photoshop writes into the legacy Pascal-string name and what the reader + // decodes. (Also keeps this out of kotlin.text.Charsets, which is JVM-only.) + val nameBytes = name.encodeToByteArray() + val additional = if (layerId != null) lyidBlock(layerId) else ByteArray(0) + val maskBlockLength = if (mask != null) 20 else 0 + out.writeInt(4 + maskBlockLength + 4 + 1 + nameBytes.size + additional.size) // extra data: mask + ranges + name + additional info + out.writeInt(maskBlockLength) // layer mask data length + if (mask != null) { + // PSD: rectangle (top, left, bottom, right), default color, flags (bit 1 = disabled), 2 padding. + out.writeInt(mask.top) + out.writeInt(mask.left) + out.writeInt(mask.top + mask.height) + out.writeInt(mask.left + mask.width) + out.writeByte(mask.defaultColor) + out.writeByte(if (mask.disabled) 0x02 else 0) + out.writeShort(0) + } + out.writeInt(0) // blending ranges length + out.writeByte(nameBytes.size) + out.write(nameBytes) + out.write(additional) + + // Channel image data, in channel-info order. + for ((_, block) in blocks) { + out.write(block) + } + return out.readByteArray() + } + + private val width = 2 + private val height = 2 + + // Distinct per-channel values (all <= 127 so they are valid Byte literals), row-major from top. + private val red = byteArrayOf(10, 50, 90, 120) + private val green = byteArrayOf(20, 60, 100, 121) + private val blue = byteArrayOf(30, 70, 110, 122) + private val alpha = byteArrayOf(40, 80, 115, 123) + private val expectedRgba = + byteArrayOf( + 10, + 20, + 30, + 40, + 50, + 60, + 70, + 80, + 90, + 100, + 110, + 115, + 120, + 121, + 122, + 123, + ) + + /** + * Decodes a synthetic PSD and asserts the single layer's geometry, pixels, and stable id. + * + * @param Int compression The compression the channels were encoded with. + * @param Int? layerId The lyid embedded in the file, or null for the name+order fallback. + */ + private fun assertDecodes(compression: Int, layerId: Int? = null) { + val bytes = buildRgbPsd(width, height, "Layer", red, green, blue, alpha, compression, layerId) + val art = PsdReader.read(bytes) + + assertEquals(width, art.widthPx, "canvas width") + assertEquals(height, art.heightPx, "canvas height") + assertEquals(1, art.layers.size, "one layer") + + val layer = art.layers.single() + assertEquals(width, layer.bounds.width, "layer width") + assertEquals(height, layer.bounds.height, "layer height") + assertEquals(width, layer.raster.width, "raster width") + assertEquals(height, layer.raster.height, "raster height") + assertContentEquals(expectedRgba, layer.raster.rgba, "decoded RGBA (compression $compression)") + + val expectedId = layerId?.let { "lyid:$it" } ?: "Layer#0" + assertEquals(expectedId, layer.id.raw, "stable layer id") + } + + @Test + fun decodesRawRgbaLayer() { + assertDecodes(compressionRaw) + } + + @Test + fun decodesRleRgbaLayer() { + assertDecodes(compressionRle) + } + + @Test + fun decodesZipRgbaLayer() { + assertDecodes(compressionZip) + } + + @Test + fun usesLyidAsStableIdWhenPresent() { + assertDecodes(compressionRaw, layerId = 42) + } + + /** + * A raster layer mask bakes into the alpha: inside its rectangle the stored value scales the + * alpha, outside it the default color does - so a black default hides everything beyond the + * rectangle, exactly as the artist sees the layer. The mask rectangle is the right column only, + * with one full and one half value, so both the placement and the multiply are pinned. + */ + @Test + fun aLayerMaskBakesIntoTheAlpha() { + val mask = SyntheticMask(plane = byteArrayOf(0xFF.toByte(), 0x80.toByte()), left = 1, top = 0, width = 1, height = 2, defaultColor = 0) + val bytes = buildRgbPsd(width, height, "Masked", red, green, blue, alpha, compressionRle, mask = mask) + val layer = PsdReader.read(bytes).layers.single() + + val alphas = (0 until 4).map { pixelIndex -> layer.raster.rgba[pixelIndex * 4 + 3].toInt() and 0xFF } + assertEquals(listOf(0, 80, 0, (123 * 0x80 + 127) / 255), alphas, "left column hidden by the default color, right column scaled by the mask") + assertEquals(listOf(10, 50, 90, 120), (0 until 4).map { pixelIndex -> layer.raster.rgba[pixelIndex * 4].toInt() and 0xFF }, "color channels are untouched") + } + + /** A disabled mask is stored but does not apply; a white default leaves the outside alone. */ + @Test + fun aDisabledMaskLeavesTheAlphaAlone() { + val mask = SyntheticMask(plane = byteArrayOf(0, 0), left = 1, top = 0, width = 1, height = 2, defaultColor = 0, disabled = true) + val bytes = buildRgbPsd(width, height, "Masked", red, green, blue, alpha, compressionRaw, mask = mask) + val layer = PsdReader.read(bytes).layers.single() + + assertContentEquals(expectedRgba, layer.raster.rgba, "a disabled mask changes nothing") + } + + /** + * A non-ASCII layer name survives the round trip. + * + * The audience is heavily Japanese, so this is the common case, not an exotic one. It is a + * regression test: the name was briefly decoded byte-per-character (Latin-1), which turned 顔 + * into three mojibake characters — and because a PSD without a lyid falls back to name+order for + * its stable id, that corruption reached the re-import join key too, not just the label. + */ + @Test + fun decodesNonAsciiLayerName() { + val japaneseName = "顔レイヤー" + val bytes = buildRgbPsd(width, height, japaneseName, red, green, blue, alpha, compressionRaw) + val layer = PsdReader.read(bytes).layers.single() + + assertEquals(japaneseName, layer.name, "layer name") + assertEquals("$japaneseName#0", layer.id.raw, "name+order stable id") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterAlphaTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterAlphaTest.kt new file mode 100644 index 0000000..2add37e --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterAlphaTest.kt @@ -0,0 +1,81 @@ +package org.umamo.format.raster + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** + * The read-back conversions: premultiplied framebuffer pixels to the straight alpha a PNG stores, and + * the forced-opaque alpha of a render over a solid background. + */ +class RasterAlphaTest { + /** + * Builds a one-row raster from RGBA quadruples. + * + * @param IntArray channels Four bytes per pixel, 0..255. + * @return RasterImage The raster. + */ + private fun row(vararg channels: Int): RasterImage = RasterImage(channels.size / 4, 1, ByteArray(channels.size) { index -> channels[index].toByte() }) + + /** + * One pixel's channels as ints. + * + * @param RasterImage image The raster. + * @param Int pixelIndex Which pixel of the row. + * @return List The four channels. + */ + private fun pixel(image: RasterImage, pixelIndex: Int): List = (0 until 4).map { channel -> image.rgba[pixelIndex * 4 + channel].toInt() and 0xFF } + + /** + * Converts a one-row raster in place and returns it, so a case reads as one expression. + * + * @param IntArray channels Four premultiplied bytes per pixel, 0..255. + * @return RasterImage The same raster, now straight alpha. + */ + private fun unpremultiplied(vararg channels: Int): RasterImage = row(*channels).also { image -> image.unpremultiplyInPlace() } + + /** A fully opaque pixel keeps its color: premultiplied and straight are the same there. */ + @Test + fun opaquePixelsKeepTheirColor() { + assertEquals(listOf(200, 100, 50, 255), pixel(unpremultiplied(200, 100, 50, 255), 0)) + } + + /** A pixel with no coverage becomes transparent black, whatever color was left in it. */ + @Test + fun transparentPixelsBecomeTransparentBlack() { + // Color with no coverage (an additive draw over nothing) has no straight form. + assertEquals(listOf(0, 0, 0, 0), pixel(unpremultiplied(40, 30, 20, 0), 0)) + } + + /** Partial coverage divides the color back out by the alpha, rounded to nearest. */ + @Test + fun partialAlphaDividesBackOutRoundedToNearest() { + // 64 / 128 * 255 = 127.5 rounds to 128; 32 / 128 * 255 = 63.75 rounds to 64; 1 / 128 * 255 = 1.99 rounds to 2. + assertEquals(listOf(128, 64, 2, 128), pixel(unpremultiplied(64, 32, 1, 128), 0)) + } + + /** A color brighter than its alpha allows clamps at full intensity instead of wrapping. */ + @Test + fun colorPastItsAlphaClampsAtFullIntensity() { + assertEquals(listOf(255, 26, 0, 100), pixel(unpremultiplied(200, 10, 0, 100), 0)) + } + + /** The conversion writes into the raster's own buffer rather than a copy. */ + @Test + fun theConversionWritesIntoTheSameBuffer() { + val image = row(64, 32, 16, 128) + val buffer = image.rgba + image.unpremultiplyInPlace() + assertSame(buffer, image.rgba) + assertEquals(listOf(128, 64, 32, 128), pixel(image, 0)) + } + + /** Forcing opaque alpha sets every alpha to 255 and leaves every color alone. */ + @Test + fun opaqueAlphaSetsEveryAlphaAndKeepsColor() { + val opaque = row(10, 20, 30, 0, 40, 50, 60, 128) + opaque.setOpaqueAlphaInPlace() + assertEquals(listOf(10, 20, 30, 255), pixel(opaque, 0)) + assertEquals(listOf(40, 50, 60, 255), pixel(opaque, 1)) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterSourceArtTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterSourceArtTest.kt new file mode 100644 index 0000000..cfe0b8a --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterSourceArtTest.kt @@ -0,0 +1,43 @@ +package org.umamo.format.raster + +import org.umamo.format.art.LayerBlend +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Confirms [rasterToSourceArt] wraps a flat [RasterImage] as a single full-canvas source layer, so a + * flat raster rides the same SourceArt ingest path as the layered readers. + */ +class RasterSourceArtTest { + @Test + fun wrapsRasterAsOneFullCanvasLayer() { + val rgba = ByteArray(3 * 2 * 4) { it.toByte() } + val image = RasterImage(width = 3, height = 2, rgba = rgba) + + val art = rasterToSourceArt(image, name = "hero.png") + + assertEquals(3, art.widthPx, "canvas width") + assertEquals(2, art.heightPx, "canvas height") + assertTrue(art.groups.isEmpty(), "a flat image has no folders") + assertEquals(1, art.layers.size, "exactly one layer") + + val layer = art.layers.single() + assertEquals("hero.png", layer.name, "layer name") + assertEquals("hero.png", layer.id.raw, "provisional layer id is the file name") + assertTrue(!layer.idIsStable, "a file name is not a layer identity, so the key is marked unstable") + assertEquals(0, layer.order, "single layer is top-most") + assertEquals("", layer.groupPath, "no enclosing folder") + assertEquals(LayerBlend.Normal, layer.blend, "normal blend") + assertEquals(1f, layer.opacity, "full opacity") + assertTrue(!layer.clipped, "not a clipping layer") + assertEquals(0, layer.bounds.left, "bounds origin x") + assertEquals(0, layer.bounds.top, "bounds origin y") + assertEquals(3, layer.bounds.width, "bounds width covers the canvas") + assertEquals(2, layer.bounds.height, "bounds height covers the canvas") + assertEquals(3, layer.raster.width, "raster width") + assertEquals(2, layer.raster.height, "raster height") + assertSame(rgba, layer.raster.rgba, "pixels are handed through by reference") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterThumbnailsTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterThumbnailsTest.kt new file mode 100644 index 0000000..40505b9 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/raster/RasterThumbnailsTest.kt @@ -0,0 +1,94 @@ +package org.umamo.format.raster + +import org.umamo.format.art.LayerBounds +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The thumbnail fit every CMO3 icon takes: the longer edge fills the square, the aspect holds, the + * art centers on the shorter axis, and the averaging runs in premultiplied space so an alpha edge + * keeps its color. + */ +class RasterThumbnailsTest { + private fun opaque(width: Int, height: Int, red: Int, green: Int, blue: Int): RasterImage = + RasterImage( + width, + height, + ByteArray(width * height * 4) { index -> + when (index % 4) { + 0 -> red.toByte() + 1 -> green.toByte() + 2 -> blue.toByte() + else -> 0xFF.toByte() + } + }, + ) + + private fun pixel(image: RasterImage, x: Int, y: Int): List { + val offset = (y * image.width + x) * 4 + return (0 until 4).map { channel -> image.rgba[offset + channel].toInt() and 0xFF } + } + + @Test + fun aWideRasterFillsTheWidthAndCentersVertically() { + val fitted = opaque(4, 2, 200, 100, 50).fittedInto(8) + assertEquals(8 to 8, fitted.width to fitted.height) + for (y in 0 until 8) { + for (x in 0 until 8) { + val expected = if (y in 2..5) listOf(200, 100, 50, 255) else listOf(0, 0, 0, 0) + assertEquals(expected, pixel(fitted, x, y), "pixel ($x, $y)") + } + } + } + + @Test + fun aTallRasterFillsTheHeightAndCentersHorizontally() { + val fitted = opaque(1, 3, 10, 20, 30).fittedInto(6) + for (y in 0 until 6) { + for (x in 0 until 6) { + val expected = if (x in 2..3) listOf(10, 20, 30, 255) else listOf(0, 0, 0, 0) + assertEquals(expected, pixel(fitted, x, y), "pixel ($x, $y)") + } + } + } + + @Test + fun averagingRunsInPremultipliedSpace() { + // One opaque red pixel and three transparent black ones average to quarter-alpha RED, not a + // quarter-alpha dark red: the transparent pixels contribute coverage, never color. + val rgba = ByteArray(2 * 2 * 4) + rgba[0] = 0xFF.toByte() + rgba[3] = 0xFF.toByte() + val fitted = RasterImage(2, 2, rgba).fittedInto(1) + assertEquals(listOf(255, 0, 0, 64), pixel(fitted, 0, 0)) + } + + @Test + fun aSmallRasterScalesUp() { + val fitted = opaque(1, 1, 5, 6, 7).fittedInto(4) + for (y in 0 until 4) { + for (x in 0 until 4) { + assertEquals(listOf(5, 6, 7, 255), pixel(fitted, x, y), "pixel ($x, $y)") + } + } + } + + @Test + fun anEmptyRasterYieldsTheBlankSquare() { + val fitted = RasterImage(0, 0, ByteArray(0)).fittedInto(3) + assertEquals(3 to 3, fitted.width to fitted.height) + assertTrue(fitted.rgba.all { byte -> byte == 0.toByte() }) + } + + @Test + fun croppingCoversAndCutsTheRect() { + val source = opaque(3, 2, 1, 2, 3) + assertSame(source, source.cropped(LayerBounds(0, 0, 3, 2)), "full bounds return the raster itself") + val corner = source.cropped(LayerBounds(2, 1, 1, 1)) + assertEquals(1 to 1, corner.width to corner.height) + assertContentEquals(byteArrayOf(1, 2, 3, 0xFF.toByte()), corner.rgba) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/tiff/TiffCcittDecodeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/tiff/TiffCcittDecodeTest.kt new file mode 100644 index 0000000..a0852be --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/tiff/TiffCcittDecodeTest.kt @@ -0,0 +1,130 @@ +package org.umamo.format.tiff + +import kotlin.io.encoding.Base64 +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Validates [TiffReader]'s CCITT fax decode against golden fixtures. Each fixture is a tiny bi-level + * TIFF encoded by libtiff (via Pillow) in one of the three CCITT variants the reader supports, and the + * expected pixels are the ones libtiff itself decodes them to. CCITT is lossless, so the decode must + * reproduce them exactly. The images are embedded base64 and the expected pixels are written as ASCII + * art ('#' black, '.' white) so a failure reads as a picture rather than a byte diff. + */ +class TiffCcittDecodeTest { + /** + * Decodes an embedded fixture and asserts its pixels match the expected ASCII art. + * + * @param String tiffBase64 Base64 of the `.tif` bytes. + * @param List expectedRows The expected image, one string per row, '#' black and '.' white. + */ + private fun assertDecodes(tiffBase64: String, expectedRows: List) { + val decoded = TiffReader.read(Base64.decode(tiffBase64)) + assertEquals(expectedRows[0].length, decoded.width, "width") + assertEquals(expectedRows.size, decoded.height, "height") + + val actualRows = + (0 until decoded.height).map { row -> + buildString { + for (column in 0 until decoded.width) { + val pixel = (row * decoded.width + column) * 4 + val red = decoded.rgba[pixel].toInt() and 0xFF + val alpha = decoded.rgba[pixel + 3].toInt() and 0xFF + assertEquals(255, alpha, "bi-level TIFF must decode opaque at ($column, $row)") + append(if (red == 0) '#' else '.') + } + } + } + assertEquals(expectedRows.joinToString("\n"), actualRows.joinToString("\n"), "CCITT decode must match libtiff pixel-for-pixel") + } + + /** Modified Huffman RLE (compression 2); PhotometricInterpretation 1. */ + @Test + fun decodesModifiedHuffmanRle() { + assertDecodes( + tiffBase64 = + "SUkqAE4AAADx+Ozx+Ozx+Ozx+Ow1n/H7NTHXj9g1h+Y/YDUfj9j0Of47sPx36HOw+HplYPY/47A1h7zHXsA1H7H/YDWHp497NR+n" + + "fsAACQAAAQMAAQAAACAAAAABAQMAAQAAABAAAAACAQMAAQAAAAEAAAADAQMAAQAAAAIAAAAGAQMAAQAAAAEAAAARAQQAAQAAAAgA" + + "AAAWAQMAAQAAABAAAAAXAQQAAQAAAEUAAAAcAQMAAQAAAAEAAAAAAAAA", + expectedRows = + listOf( + "#######.......#######.......####", + "#######.......#######.......####", + "#######.......#######.......####", + "#######.......#######.......####", + "...##..#######.......#######....", + ".....#.#######.......#######....", + "...#..########.......#######....", + ".......#######.......#######....", + "#######.#.....#######..#....####", + "#######..#....#######.#.....####", + "#######...#...########......####", + "#######....#..#######.......####", + "...#...#######.....#.#######....", + ".......#######....#..#######....", + "...#...########..#...#######....", + ".......#######.##....#######....", + ), + ) + } + + /** Group 3 / T.4 (compression 3); PhotometricInterpretation 1. */ + @Test + fun decodesGroup3() { + assertDecodes( + tiffBase64 = + "SUkqAGAAAAAAHx+OwAfH47AB8fjsAHx+OwATWf8fsAE1MdeP2ACaw/MfsAE1H4/YAPoc/x3YAP479DnYAPw9MrAB9j/jsAE1h7zH" + + "XsAE1H7H/YAJrD08e9gAmo/Tv2AACQAAAQMAAQAAACAAAAABAQMAAQAAABAAAAACAQMAAQAAAAEAAAADAQMAAQAAAAMAAAAGAQMA" + + "AQAAAAEAAAARAQQAAQAAAAgAAAAWAQMAAQAAABAAAAAXAQQAAQAAAFcAAAAcAQMAAQAAAAEAAAAAAAAA", + expectedRows = + listOf( + "#######.......#######.......####", + "#######.......#######.......####", + "#######.......#######.......####", + "#######.......#######.......####", + "...##..#######.......#######....", + ".....#.#######.......#######....", + "...#..########.......#######....", + ".......#######.......#######....", + "#######.#.....#######..#....####", + "#######..#....#######.#.....####", + "#######...#...########......####", + "#######....#..#######.......####", + "...#...#######.....#.#######....", + ".......#######....#..#######....", + "...#...########..#...#######....", + ".......#######.##....#######....", + ), + ) + } + + /** Group 4 / T.6 (compression 4); PhotometricInterpretation 1. */ + @Test + fun decodesGroup4() { + assertDecodes( + tiffBase64 = + "SUkqADoAAAA+M+P//yawR/I/wyOvhBP4vz6I5n8jvZHdLsjz7I+smsCN5Mcr8dLzD2l40EuACACAAAkAAAEDAAEAAAAgAAAAAQED" + + "AAEAAAAQAAAAAgEDAAEAAAABAAAAAwEDAAEAAAAEAAAABgEDAAEAAAABAAAAEQEEAAEAAAAIAAAAFgEDAAEAAAAQAAAAFwEEAAEA" + + "AAAxAAAAHAEDAAEAAAABAAAAAAAAAA==", + expectedRows = + listOf( + "#######.......#######.......####", + "#######.......#######.......####", + "#######.......#######.......####", + "#######.......#######.......####", + "...##..#######.......#######....", + ".....#.#######.......#######....", + "...#..########.......#######....", + ".......#######.......#######....", + "#######.#.....#######..#....####", + "#######..#....#######.#.....####", + "#######...#...########......####", + "#######....#..#######.......####", + "...#...#######.....#.#######....", + ".......#######....#..#######....", + "...#...########..#...#######....", + ".......#######.##....#######....", + ), + ) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/tiff/TiffDecodeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/tiff/TiffDecodeTest.kt new file mode 100644 index 0000000..4e2fa78 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/tiff/TiffDecodeTest.kt @@ -0,0 +1,404 @@ +package org.umamo.format.tiff + +import okio.Buffer +import org.umamo.format.binary.deflateZlib +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Exercises [TiffReader] with synthetic, hand-built single-strip TIFFs whose pixels are known exactly + * (mirroring PsdSyntheticTest), covering each compression (uncompressed, PackBits, LZW, Deflate), + * photometric (RGB, gray with WhiteIsZero, palette), the horizontal predictor, RGBA ExtraSamples + * alpha, 16-bit down-conversion, and both byte orders. In-test PackBits/LZW/Deflate encoders drive + * the compressed paths so no corpus is needed. + */ +class TiffDecodeTest { + private fun bytes(vararg values: Int): ByteArray = ByteArray(values.size) { values[it].toByte() } + + // --- Compression codes (mirrors TiffConstants). --- + private val none = 1 + private val lzw = 5 + private val zlib = 8 + private val packBits = 32773 + + // --- Field types. --- + private val typeShort = 3 + private val typeLong = 4 + + private class Field(val tag: Int, val type: Int, val values: IntArray) + + private fun typeLength(type: Int): Int = if (type == typeShort) 2 else 4 + + /** + * Encodes a field's values little-endian. + */ + private fun encodeValues(field: Field): ByteArray { + val out = Buffer() + for (value in field.values) { + if (field.type == typeShort) { + out.writeByte(value and 0xFF) + out.writeByte((value ushr 8) and 0xFF) + } else { + out.writeByte(value and 0xFF) + out.writeByte((value ushr 8) and 0xFF) + out.writeByte((value ushr 16) and 0xFF) + out.writeByte((value ushr 24) and 0xFF) + } + } + return out.readByteArray() + } + + /** + * Builds a little-endian single-strip TIFF from a fixed set of fields plus the strip data. + */ + private fun buildTiff( + width: Int, + height: Int, + bitsPerSample: IntArray, + samplesPerPixel: Int, + photometric: Int, + compression: Int, + stripData: ByteArray, + predictor: Int? = null, + colorMap: IntArray? = null, + extraSamples: IntArray? = null, + bigEndian: Boolean = false, + ): ByteArray { + val fields = ArrayList() + fields += Field(256, typeShort, intArrayOf(width)) + fields += Field(257, typeShort, intArrayOf(height)) + fields += Field(258, typeShort, bitsPerSample) + fields += Field(259, typeShort, intArrayOf(compression)) + fields += Field(262, typeShort, intArrayOf(photometric)) + val stripOffsetsField = Field(273, typeLong, intArrayOf(0)) + fields += stripOffsetsField + fields += Field(277, typeShort, intArrayOf(samplesPerPixel)) + fields += Field(278, typeLong, intArrayOf(height)) + fields += Field(279, typeLong, intArrayOf(stripData.size)) + if (predictor != null) { + fields += Field(317, typeShort, intArrayOf(predictor)) + } + if (colorMap != null) { + fields += Field(320, typeShort, colorMap) + } + if (extraSamples != null) { + fields += Field(338, typeShort, extraSamples) + } + fields.sortBy { it.tag } + + val ifdOffset = 8 + val ifdSize = 2 + 12 * fields.size + 4 + var externalCursor = ifdOffset + ifdSize + val externalBlocks = ArrayList>() + val valueField = HashMap() + for (field in fields) { + val encoded = encodeValues(field) + if (encoded.size <= 4) { + valueField[field] = 0 // inline; filled below from encoded bytes + } else { + valueField[field] = externalCursor + externalBlocks += externalCursor to encoded + externalCursor += encoded.size + } + } + val stripOffset = externalCursor + + val totalSize = stripOffset + stripData.size + val out = ByteArray(totalSize) + // Header. + if (bigEndian) { + out[0] = 0x4D + out[1] = 0x4D + out[2] = 0x00 + out[3] = 0x2A + } else { + out[0] = 0x49 + out[1] = 0x49 + out[2] = 0x2A + out[3] = 0x00 + } + putU32(out, 4, ifdOffset, bigEndian) + + // IFD. + putU16(out, ifdOffset, fields.size, bigEndian) + var entryOffset = ifdOffset + 2 + for (field in fields) { + putU16(out, entryOffset, field.tag, bigEndian) + putU16(out, entryOffset + 2, field.type, bigEndian) + putU32(out, entryOffset + 4, field.values.size, bigEndian) + val totalBytes = field.values.size * typeLength(field.type) + if (field === stripOffsetsField) { + putU32(out, entryOffset + 8, stripOffset, bigEndian) + } else if (totalBytes <= 4) { + // Inline: place the value(s) left-justified in the 4-byte field, in file byte order. + putInlineField(out, entryOffset + 8, field, bigEndian) + } else { + putU32(out, entryOffset + 8, valueField[field]!!, bigEndian) + } + entryOffset += 12 + } + putU32(out, entryOffset, 0, bigEndian) // next IFD = none + + // External data blocks (all SHORT arrays here). encodeValues wrote them little-endian; byte-swap + // each 16-bit value for a big-endian file. + for ((offset, block) in externalBlocks) { + val reordered = if (bigEndian) swapShorts(block) else block + reordered.copyInto(out, offset) + } + // Strip data. + stripData.copyInto(out, stripOffset) + return out + } + + /** Writes a field's short/long values inline into the 4-byte value slot, in file byte order. */ + private fun putInlineField(out: ByteArray, at: Int, field: Field, bigEndian: Boolean) { + var cursor = at + for (value in field.values) { + if (field.type == typeShort) { + putU16(out, cursor, value, bigEndian) + cursor += 2 + } else { + putU32(out, cursor, value, bigEndian) + cursor += 4 + } + } + } + + /** Byte-swaps each 16-bit value in [littleEndianBlock] (external SHORT arrays are always 16-bit). */ + private fun swapShorts(littleEndianBlock: ByteArray): ByteArray { + val out = ByteArray(littleEndianBlock.size) + var index = 0 + while (index + 1 < littleEndianBlock.size) { + out[index] = littleEndianBlock[index + 1] + out[index + 1] = littleEndianBlock[index] + index += 2 + } + return out + } + + private fun putU16(out: ByteArray, at: Int, value: Int, bigEndian: Boolean) { + if (bigEndian) { + out[at] = ((value ushr 8) and 0xFF).toByte() + out[at + 1] = (value and 0xFF).toByte() + } else { + out[at] = (value and 0xFF).toByte() + out[at + 1] = ((value ushr 8) and 0xFF).toByte() + } + } + + private fun putU32(out: ByteArray, at: Int, value: Int, bigEndian: Boolean) { + if (bigEndian) { + out[at] = ((value ushr 24) and 0xFF).toByte() + out[at + 1] = ((value ushr 16) and 0xFF).toByte() + out[at + 2] = ((value ushr 8) and 0xFF).toByte() + out[at + 3] = (value and 0xFF).toByte() + } else { + out[at] = (value and 0xFF).toByte() + out[at + 1] = ((value ushr 8) and 0xFF).toByte() + out[at + 2] = ((value ushr 16) and 0xFF).toByte() + out[at + 3] = ((value ushr 24) and 0xFF).toByte() + } + } + + // --- Strip-data encoders. --- + + /** PackBits-encodes [data] as one literal run per 128-byte chunk (valid; my decoder reads literals). */ + private fun packBitsEncode(data: ByteArray): ByteArray { + val out = Buffer() + var index = 0 + while (index < data.size) { + val runLength = minOf(128, data.size - index) + out.writeByte(runLength - 1) // control: copy next runLength literal bytes + out.write(data, index, runLength) + index += runLength + } + return out.readByteArray() + } + + /** + * zlib-compresses [data] for a TIFF Deflate/ZIP strip. + * + * Uses the shared bridge rather than a platform Deflater so this test runs on every target. That + * does mean the Deflate case round-trips through our own compressor, unlike the LZW and PackBits + * cases which have independent encoders below — acceptable because zlib framing is not ours to get + * wrong (the bridge delegates to the platform), and the assertions still pin the predictor, + * photometric, and assembly logic that this test actually exists to cover. + * + * @param ByteArray data The raw strip bytes. + * @return ByteArray The zlib stream. + */ + private fun deflate(data: ByteArray): ByteArray = deflateZlib(data) + + /** + * TIFF-spec LZW encode (MSB-first, 9-12 bit codes, early change) matching [decodeLzw]. + */ + private fun lzwEncode(data: ByteArray): ByteArray { + val out = Buffer() + var bitBuffer = 0 + var bitCount = 0 + var codeSize = 9 + + fun emit(code: Int) { + bitBuffer = (bitBuffer shl codeSize) or code + bitCount += codeSize + while (bitCount >= 8) { + out.writeByte((bitBuffer ushr (bitCount - 8)) and 0xFF) + bitCount -= 8 + } + } + + val dictionary = HashMap() + + fun reset() { + dictionary.clear() + for (value in 0..255) { + dictionary[value.toString()] = value + } + } + + val clearCode = 256 + val eoiCode = 257 + reset() + var next = 258 + codeSize = 9 + emit(clearCode) + var current = "" + for (rawByte in data) { + val symbol = (rawByte.toInt() and 0xFF).toString() + val combined = if (current.isEmpty()) symbol else "$current,$symbol" + if (dictionary.containsKey(combined)) { + current = combined + } else { + emit(dictionary[current]!!) + dictionary[combined] = next++ + if (next == (1 shl codeSize) - 1 && codeSize < 12) { + codeSize++ + } + current = symbol + } + } + if (current.isNotEmpty()) { + emit(dictionary[current]!!) + } + emit(eoiCode) + // Flush remaining bits. + if (bitCount > 0) { + out.writeByte((bitBuffer shl (8 - bitCount)) and 0xFF) + } + return out.readByteArray() + } + + /** Applies the horizontal-differencing predictor forward (encoder side) to 8-bit sample rows. */ + private fun predictHorizontal(data: ByteArray, width: Int, height: Int, samplesPerPixel: Int): ByteArray { + val out = data.copyOf() + val rowBytes = width * samplesPerPixel + for (row in 0 until height) { + val base = row * rowBytes + for (column in width - 1 downTo 1) { + for (sample in 0 until samplesPerPixel) { + val offset = base + column * samplesPerPixel + sample + out[offset] = (data[offset] - data[offset - samplesPerPixel]).toByte() + } + } + } + return out + } + + private fun compress(raw: ByteArray, compression: Int): ByteArray = + when (compression) { + packBits -> packBitsEncode(raw) + lzw -> lzwEncode(raw) + zlib -> deflate(raw) + else -> raw + } + + // --- Fixtures. --- + + private val rgb2x2 = bytes(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120) + private val rgb2x2Expected = + bytes(10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255) + + private fun assertRgbDecodes(compression: Int) { + val tiff = buildTiff(2, 2, intArrayOf(8, 8, 8), 3, 2, compression, compress(rgb2x2, compression)) + val decoded = TiffReader.read(tiff) + assertEquals(2, decoded.width) + assertEquals(2, decoded.height) + assertContentEquals(rgb2x2Expected, decoded.rgba, "RGB decode (compression $compression)") + } + + @Test fun decodesUncompressedRgb() = assertRgbDecodes(none) + + @Test fun decodesPackBitsRgb() = assertRgbDecodes(packBits) + + @Test fun decodesLzwRgb() = assertRgbDecodes(lzw) + + @Test fun decodesDeflateRgb() = assertRgbDecodes(zlib) + + @Test + fun decodesBigEndianRgb() { + val tiff = buildTiff(2, 2, intArrayOf(8, 8, 8), 3, 2, none, rgb2x2, bigEndian = true) + assertContentEquals(rgb2x2Expected, TiffReader.read(tiff).rgba, "big-endian RGB") + } + + @Test + fun decodesGrayBlackIsZero() { + val gray = bytes(0, 64, 128, 255) + val tiff = buildTiff(2, 2, intArrayOf(8), 1, 1, none, gray) + val expected = bytes(0, 0, 0, 255, 64, 64, 64, 255, 128, 128, 128, 255, 255, 255, 255, 255) + assertContentEquals(expected, TiffReader.read(tiff).rgba) + } + + @Test + fun decodesGrayWhiteIsZeroInverts() { + val gray = bytes(0, 64, 200, 255) + val tiff = buildTiff(2, 2, intArrayOf(8), 1, 0, none, gray) // photometric 0 = WhiteIsZero + val expected = bytes(255, 255, 255, 255, 191, 191, 191, 255, 55, 55, 55, 255, 0, 0, 0, 255) + assertContentEquals(expected, TiffReader.read(tiff).rgba) + } + + @Test + fun decodesPalette8Bit() { + // 8-bit palette needs 256 entries * 3 planes of 16-bit ColorMap; only the used indices matter. + val paletteSize = 256 + val colorMap = IntArray(paletteSize * 3) + + // Index 0 -> red, 1 -> green, 2 -> blue, 3 -> gray128 (ColorMap stores 16-bit; use value*257 to fill). + fun set(index: Int, red: Int, green: Int, blue: Int) { + colorMap[index] = red * 257 + colorMap[paletteSize + index] = green * 257 + colorMap[2 * paletteSize + index] = blue * 257 + } + set(0, 255, 0, 0) + set(1, 0, 255, 0) + set(2, 0, 0, 255) + set(3, 128, 128, 128) + val indices = bytes(0, 1, 2, 3) + val tiff = buildTiff(2, 2, intArrayOf(8), 1, 3, none, indices, colorMap = colorMap) + val expected = bytes(255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 128, 128, 128, 255) + assertContentEquals(expected, TiffReader.read(tiff).rgba) + } + + @Test + fun decodesRgbaWithUnassociatedAlpha() { + val rgba = bytes(10, 20, 30, 255, 40, 50, 60, 128, 70, 80, 90, 64, 100, 110, 120, 0) + val tiff = buildTiff(1, 4, intArrayOf(8, 8, 8, 8), 4, 2, none, rgba, extraSamples = intArrayOf(2)) + assertContentEquals(rgba, TiffReader.read(tiff).rgba, "straight alpha preserved") + } + + @Test + fun decodesPredictorHorizontalRgb() { + val predicted = predictHorizontal(rgb2x2, 2, 2, 3) + val tiff = buildTiff(2, 2, intArrayOf(8, 8, 8), 3, 2, none, predicted, predictor = 2) + assertContentEquals(rgb2x2Expected, TiffReader.read(tiff).rgba, "predictor 2 un-differenced") + } + + @Test + fun decodes16BitGrayKeepsHighByte() { + // Two pixels, 16-bit big-endian samples 0x1234 and 0xABCD -> high bytes 0x12, 0xAB. + val gray16 = bytes(0x12, 0x34, 0xAB, 0xCD) + val tiff = buildTiff(2, 1, intArrayOf(16), 1, 1, none, gray16, bigEndian = true) + val expected = bytes(0x12, 0x12, 0x12, 255, 0xAB, 0xAB, 0xAB, 255) + assertContentEquals(expected, TiffReader.read(tiff).rgba) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaCompatibilityTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaCompatibilityTest.kt new file mode 100644 index 0000000..a60f7b3 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaCompatibilityTest.kt @@ -0,0 +1,297 @@ +package org.umamo.format.uma + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.umamo.format.binary.ZipArchive +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.ZipWriter +import org.umamo.format.uma.sources.UmaSources +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the compatibility model against files a newer writer could produce (docs/format/UMA.md §3.3): + * what opens editable, what opens read-only, and that everything this reader does not own survives a + * save byte for byte (UMA §3.3). + */ +class UmaCompatibilityTest { + private val puppetRecord = recordJson("model/puppet.json", "puppet", required = true) + private val puppetEntry = TestEntry("model/puppet.json", """{ "marker": "puppet" }""".encodeToByteArray()) + + /** + * The manifest [bytes] holds, parsed. + * + * @param ByteArray bytes A UMA archive. + * @return JsonObject The manifest. + */ + private fun manifestOf(bytes: ByteArray): JsonObject { + val archive = ZipArchive.read(bytes) + return parseJsonObject(archive.contents(archive.entry(UmaContainer.MANIFEST_PATH)!!)) { detail -> UmaReadFailure.MalformedManifest(detail) } + } + + /** + * Each entry's raw payload in [bytes], by name. + * + * @param ByteArray bytes A UMA archive. + * @return Map The raw payloads. + */ + private fun rawPayloadsOf(bytes: ByteArray): Map { + val archive = ZipArchive.read(bytes) + return archive.entries.associate { entry -> entry.name to archive.rawPayload(entry) } + } + + /** + * A document the codec writes reads back and writes again to the same bytes, and to the same entries, + * when nothing was edited (UMA §3.5). + */ + @Test + fun unchangedDocumentRewritesByteForByte() { + val created = + UmaModel + .create(TEST_WRITER) + .withLiveContent(UmaEntryKind.Puppet, sampleTree("puppet")) + .withLiveContent(UmaEntryKind.Sources, sampleTree("sources")) + val first = Uma.write(created) + val second = Uma.write(Uma.read(first)) + assertContentEquals(first, second, "an unedited round trip reproduces the archive") + + // A file carrying everything a newer writer might add, normalized by one save, then saved again. + val future = + umaArchiveOf( + manifestJson( + listOf(puppetRecord, recordJson("model/physics.json", "physics", extraKeys = """, "driver": "wind"""")), + extraKeys = """, "savedBy": { "tool": "future" }""", + ), + listOf( + TestEntry("textures/tile-0.png", ByteArray(500) { byteIndex -> byteIndex.toByte() }, deflated = false), + puppetEntry, + TestEntry("model/physics.json", """{ "springs": [ 1, 2, 3 ] }""".encodeToByteArray()), + TestEntry("model/buffers.bin", ByteArray(4000) { byteIndex -> (byteIndex % 5).toByte() }), + ), + ) + val normalized = Uma.write(Uma.read(future)) + assertContentEquals(normalized, Uma.write(Uma.read(normalized)), "a saved file with unknown entries rewrites byte for byte") + } + + /** + * An unknown optional kind is preserved and the document stays editable: its record, its bytes, and its + * place in the archive all survive a save. + */ + @Test + fun unknownOptionalEntryIsPreservedAndEditable() { + val physicsBytes = """{ "springs": [ 1, 2, 3 ], "gravity": -9.8 }""".encodeToByteArray() + val source = + umaArchiveOf( + manifestJson(listOf(puppetRecord, recordJson("model/physics.json", "physics", version = 3, minVersion = 2, extraKeys = """, "driver": "wind""""))), + listOf(puppetEntry, TestEntry("model/physics.json", physicsBytes)), + ) + val model = Uma.read(source) + assertFalse(model.isReadOnly, "an optional unknown entry does not block editing") + val physics = model.entries.single { entry -> entry.kind == "physics" } + assertNull(physics.liveKind, "the unknown entry is carried, not read") + + val saved = Uma.write(model) + assertContentEquals(rawPayloadsOf(source)["model/physics.json"], rawPayloadsOf(saved)["model/physics.json"], "its payload is byte-identical") + val savedRecord = manifestOf(saved)["entries"]!!.jsonArray.map { element -> element.jsonObject }.single { record -> record["kind"] == JsonPrimitive("physics") } + val sourceRecord = manifestOf(source)["entries"]!!.jsonArray.map { element -> element.jsonObject }.single { record -> record["kind"] == JsonPrimitive("physics") } + assertEquals(sourceRecord, savedRecord, "its manifest record is verbatim, unknown keys and versions included") + assertEquals(listOf("mimetype", "manifest.json", "model/puppet.json", "model/physics.json"), ZipArchive.read(saved).entries.map { entry -> entry.name }, "archive order") + } + + /** + * An unknown kind the file marks required opens read-only with its reason, and cannot be written. + */ + @Test + fun unknownRequiredEntryMakesTheDocumentReadOnly() { + val source = + umaArchiveOf( + manifestJson(listOf(puppetRecord, recordJson("model/rig2.json", "rig2", required = true))), + listOf(puppetEntry, TestEntry("model/rig2.json", "{}".encodeToByteArray())), + ) + val model = Uma.read(source) + assertTrue(model.isReadOnly, "an unknown required entry blocks editing") + assertEquals(listOf(UmaReadOnlyReason("model/rig2.json", "rig2", UmaReadOnlyCause.UnknownKind)), model.readOnlyReasons, "the reason names the entry") + assertNotNull(model.liveContent(UmaEntryKind.Puppet), "what this reader understands still reads") + assertFailsWith { Uma.write(model) } + } + + /** + * A known kind whose minVersion is above this reader's version is treated as unknown: preserved, and + * read-only only when the file marks it required. + */ + @Test + fun knownKindTooNewIsTreatedAsUnknown() { + val tooNewRequired = + Uma.read( + umaArchiveOf( + manifestJson(listOf(recordJson("model/puppet.json", "puppet", version = 2, minVersion = 2, required = true))), + listOf(puppetEntry), + ), + ) + assertEquals( + listOf(UmaReadOnlyReason("model/puppet.json", "puppet", UmaReadOnlyCause.UnsupportedVersion(2, 1))), + tooNewRequired.readOnlyReasons, + "a required entry this reader would misread blocks editing", + ) + assertNull(tooNewRequired.liveContent(UmaEntryKind.Puppet), "and is not read") + + val sourcesBytes = """{ "sources": [] }""".encodeToByteArray() + val tooNewOptionalSource = + umaArchiveOf( + manifestJson(listOf(puppetRecord, recordJson("source/index.json", "sources", version = 2, minVersion = 2))), + listOf(puppetEntry, TestEntry("source/index.json", sourcesBytes)), + ) + val tooNewOptional = Uma.read(tooNewOptionalSource) + assertFalse(tooNewOptional.isReadOnly, "an optional entry this reader would misread does not block editing") + assertNull(tooNewOptional.liveContent(UmaEntryKind.Sources), "and is not read") + assertTrue(tooNewOptional.holdsTooNewEntry(UmaEntryKind.Sources), "the document reports the kind it cannot set") + assertFalse(tooNewOptional.holdsTooNewEntry(UmaEntryKind.Puppet), "and only that kind") + assertFailsWith("the too-new entry occupies its kind") { + tooNewOptional.withLiveContent(UmaEntryKind.Sources, sampleTree("mine")) + } + assertFailsWith("a typed save over it is refused the same way") { + tooNewOptional.withSources(UmaSources()) + } + assertContentEquals( + rawPayloadsOf(tooNewOptionalSource)["source/index.json"], + rawPayloadsOf(Uma.write(tooNewOptional))["source/index.json"], + "and survives a save byte for byte", + ) + } + + /** + * A known kind at a newer version that older readers may still read opens live, keeps the keys this + * reader does not know, and is written back at this writer's version (UMA §3.5). + */ + @Test + fun additiveNewerVersionReadsLiveAndWritesCurrent() { + val model = + Uma.read( + umaArchiveOf( + manifestJson(listOf(recordJson("model/puppet.json", "puppet", version = 2, minVersion = 1, required = true))), + listOf(TestEntry("model/puppet.json", """{ "marker": "puppet", "addedInV2": { "flag": true } }""".encodeToByteArray())), + ), + ) + assertFalse(model.isReadOnly, "an additive newer version stays editable") + val tree = assertNotNull(model.liveContent(UmaEntryKind.Puppet), "the entry reads live") + assertNotNull(tree["addedInV2"], "the newer key is in the tree") + + val saved = Uma.write(model) + val record = manifestOf(saved)["entries"]!!.jsonArray.single().jsonObject + assertEquals(1, record["version"]!!.jsonPrimitive.int, "written at this writer's version") + assertEquals(1, record["minVersion"]!!.jsonPrimitive.int, "with this writer's minVersion") + assertNotNull(Uma.read(saved).liveContent(UmaEntryKind.Puppet)!!["addedInV2"], "the newer key survives the save") + } + + /** + * A container version above this reader's refuses the whole file with the typed reason. + */ + @Test + fun newerContainerVersionIsRefused() { + val failure = + assertFailsWith { + Uma.read(umaArchiveOf(manifestJson(listOf(puppetRecord), containerVersion = 2), listOf(puppetEntry))) + } + assertEquals(UmaReadFailure.UnsupportedContainerVersion(2, 1), failure.failure) + } + + /** + * Keys this writer does not own, at the manifest's top level and inside its records, keep their values + * and their places. + */ + @Test + fun unknownManifestKeysSurviveInPlace() { + val record = recordJson("model/puppet.json", "puppet", required = true, extraKeys = """, "checksum": "abc"""") + val manifest = """{ "format": "uma", "note": "first", "containerVersion": 1, "writer": { "app": "Future", "build": 77, "version": "9" }, "entries": [ """ + record + """ ], "trailer": [ 1, 2 ] }""" + val source = umaArchiveOf(manifest, listOf(puppetEntry)) + val saved = manifestOf(Uma.write(Uma.read(source))) + assertEquals(listOf("format", "note", "containerVersion", "writer", "entries", "trailer"), saved.keys.toList(), "top-level keys keep their order") + assertEquals(JsonPrimitive(77), saved["writer"]!!.jsonObject["build"], "an unknown writer key survives") + assertEquals(JsonPrimitive("abc"), saved["entries"]!!.jsonArray.single().jsonObject["checksum"], "an unknown record key survives") + assertEquals(manifestOf(source)["trailer"], saved["trailer"], "an unknown top-level value survives") + } + + /** + * Entries no manifest record names keep their raw bytes, their compression, and their order. + */ + @Test + fun unlistedPayloadsArePreservedInOrder() { + val stored = ByteArray(700) { byteIndex -> (byteIndex * 7).toByte() } + val deflated = ByteArray(9000) { byteIndex -> (byteIndex % 9).toByte() } + val source = + umaArchiveOf( + manifestJson(listOf(puppetRecord)), + listOf( + TestEntry("thumbnail.png", stored, deflated = false), + puppetEntry, + TestEntry("model/buffers.bin", deflated), + TestEntry("textures/", ByteArray(0), deflated = false), + ), + ) + val model = Uma.read(source) + assertEquals(listOf("thumbnail.png", "model/buffers.bin", "textures/"), model.payloads.map { payload -> payload.path }, "payloads in archive order") + val saved = Uma.write(model) + val savedArchive = ZipArchive.read(saved) + assertEquals( + listOf("mimetype", "manifest.json", "thumbnail.png", "model/puppet.json", "model/buffers.bin", "textures/"), + savedArchive.entries.map { entry -> entry.name }, + "the archive keeps its order after the bootstrap entries", + ) + val sourcePayloads = rawPayloadsOf(source) + val savedPayloads = rawPayloadsOf(saved) + for (path in listOf("thumbnail.png", "model/buffers.bin", "textures/")) { + assertContentEquals(sourcePayloads[path], savedPayloads[path], "'$path' raw bytes") + assertEquals(ZipArchive.read(source).entry(path)!!.method, savedArchive.entry(path)!!.method, "'$path' compression") + } + assertContentEquals(deflated, savedArchive.contents(savedArchive.entry("model/buffers.bin")!!), "and still inflates") + } + + /** + * A mimetype a re-zipping tool moved away from the front still identifies the file, and the next save + * puts it back first. + */ + @Test + fun displacedMimetypeReadsAndIsRestoredFirst() { + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + writer.addDeflated(UmaContainer.MANIFEST_PATH, manifestJson(listOf(puppetRecord)).encodeToByteArray()) + writer.addDeflated(puppetEntry.path, puppetEntry.contents) + writer.addDeflated(UmaContainer.MIMETYPE_PATH, UmaContainer.MIMETYPE.encodeToByteArray()) + val displaced = writer.finish() + assertFalse(Uma.matches(displaced), "the probe needs the mimetype first") + val saved = Uma.write(Uma.read(displaced)) + assertTrue(Uma.matches(saved), "the save restores the identifying layout") + assertIs(Uma.read(saved).entries.single().content, "and the content survives") + } + + /** + * A manifest that lists the puppet's own buffer path as an entry - a foreign writer's doing - opens, but a + * puppet cannot be written over it, and the refusal is the write contract's exception: the app's save flow + * catches that one to report a document it cannot save, where a bare state error would crash it. + */ + @Test + fun aManifestListedBufferPathRefusesThePuppetWrite() { + val document = + Uma.read( + umaArchiveOf( + manifestJson(listOf(puppetRecord, recordJson("model/buffers.bin", "mystery"))), + listOf(puppetEntry, TestEntry("model/buffers.bin", byteArrayOf(1, 2, 3, 4), deflated = false)), + ), + ) + assertFalse(document.isReadOnly, "an optional unknown entry does not block editing") + + val failure = assertFailsWith { document.withPuppet(assertNotNull(document.puppet)) } + + assertEquals("model/buffers.bin", failure.path, "the refusal names the entry in the way") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaEditorEntryTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaEditorEntryTest.kt new file mode 100644 index 0000000..2bbe53c --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaEditorEntryTest.kt @@ -0,0 +1,216 @@ +package org.umamo.format.uma + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.umamo.format.binary.ZipArchive +import org.umamo.format.uma.puppet.samplePuppet +import org.umamo.format.uma.sources.UmaSource +import org.umamo.format.uma.sources.UmaSources +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * Pins the editor entry (docs/format/UMA.md §7): it is written as a JSON Merge Patch over the tree as read, it is + * never minted empty, and a file with it stripped loads the same puppet and sources (UMA §7). + */ +class UmaEditorEntryTest { + /** + * An outliner block with the given open branches, under one area id. + * + * @param String areaId The area the block belongs to. + * @param List expanded The open node ids. + * @return JsonObject The patch. + */ + private fun outlinerPatch(areaId: String, expanded: List): JsonObject = + buildJsonObject { + put( + "areas", + buildJsonObject { + put( + areaId, + buildJsonObject { + put("outliner", buildJsonObject { put("expanded", JsonArray(expanded.map(::JsonPrimitive))) }) + }, + ) + }, + ) + } + + /** + * A document holding a puppet and a source list, which is what a stripped editor entry must not disturb. + * + * @return UmaModel The document. + */ + private fun sampleDocument(): UmaModel = + UmaModel + .create(TEST_WRITER) + .withPuppet(samplePuppet()) + .withSources(UmaSources(listOf(UmaSource("guid-7", "Erica.psd", "psd")))) + + /** Objects merge, any other value replaces whole, and null removes (RFC 7386). */ + @Test + fun aPatchMergesObjectsReplacesValuesAndRemovesNulls() { + val target = + buildJsonObject { + put("kept", "as read") + put("replaced", buildJsonArray { add(JsonPrimitive("old")) }) + put("removed", 1) + put("nested", buildJsonObject { put("foreign", true) }) + } + val patch = + buildJsonObject { + put("replaced", buildJsonArray { add(JsonPrimitive("new")) }) + put("removed", JsonNull) + put("nested", buildJsonObject { put("mine", 2) }) + put("added", "last") + } + + val merged = applyMergePatch(target, patch) + + assertEquals(listOf("kept", "replaced", "nested", "added"), merged.keys.toList(), "members keep their order and new ones follow") + assertEquals("as read", merged["kept"]!!.jsonPrimitive.content) + assertEquals(listOf("new"), merged["replaced"]!!.jsonArray.map { element -> element.jsonPrimitive.content }, "an array replaces whole") + assertEquals(setOf("foreign", "mine"), merged["nested"]!!.jsonObject.keys, "an object merges member by member") + } + + /** A deviation that returns to its default takes its block with it, up to the root. */ + @Test + fun anObjectTheMergeEmptiesIsRemoved() { + val target = outlinerPatch("area-1", listOf("part:12")) + val patch = + buildJsonObject { + put("areas", buildJsonObject { put("area-1", buildJsonObject { put("outliner", buildJsonObject { put("expanded", JsonNull) }) }) }) + } + + assertEquals(JsonObject(emptyMap()), applyMergePatch(target, patch)) + } + + /** A member the patch does not name survives, which is what keeps a newer writer's state in the file. */ + @Test + fun membersThePatchDoesNotNameSurvive() { + val asRead = + buildJsonObject { + put("timeline", buildJsonObject { put("from", "future") }) + put("areas", buildJsonObject { put("area-1", buildJsonObject { put("dopesheet", buildJsonObject { put("from", "future") }) }) }) + } + val document = sampleDocument().withLiveContent(UmaEntryKind.Editor, asRead) + + val saved = document.withEditorState(outlinerPatch("area-1", listOf("part:12"))) + val tree = assertNotNull(Uma.read(Uma.write(saved)).editorState) + + assertEquals("future", tree["timeline"]!!.jsonObject["from"]!!.jsonPrimitive.content) + val area = tree["areas"]!!.jsonObject["area-1"]!!.jsonObject + assertEquals(setOf("dopesheet", "outliner"), area.keys, "the foreign block stays beside the one this writer set") + } + + /** A null for an area removes it: how a stale layout's ids leave the file (UMA §7.5). */ + @Test + fun aNullAreaLeavesTheFile() { + val document = sampleDocument().withEditorState(outlinerPatch("area-stale", listOf("part:1"))) + val patch = + buildJsonObject { + put( + "areas", + buildJsonObject { + put("area-stale", JsonNull) + put("area-mine", buildJsonObject { put("outliner", buildJsonObject { put("expanded", buildJsonArray { add(JsonPrimitive("part:2")) }) }) }) + }, + ) + } + + val areas = assertNotNull(document.withEditorState(patch).editorState)["areas"]!!.jsonObject + + assertEquals(setOf("area-mine"), areas.keys) + } + + /** Untouched editor state mints no entry, and an unchanged tree is the same document. */ + @Test + fun anEmptyPatchAddsNoEntryAndChangesNothing() { + val bare = sampleDocument() + assertSame(bare, bare.withEditorState(JsonObject(emptyMap())), "no entry for a tree with nothing in it") + assertNull(bare.editorState) + assertNull(bare.entries.firstOrNull { entry -> entry.kind == UmaEntryKind.Editor.wireName }) + + val patch = outlinerPatch("area-1", listOf("part:12")) + val withState = bare.withEditorState(patch) + assertSame(withState, withState.withEditorState(patch), "the same state again is not a new document") + assertContentEquals(Uma.write(withState), Uma.write(Uma.read(Uma.write(withState)).withEditorState(patch)), "and writes the same bytes") + } + + /** The entry is optional, at the kind's default path, and reads back as the tree that was written. */ + @Test + fun theEntryRoundTripsAsAnOptionalLiveTree() { + val patch = outlinerPatch("area-1", listOf("part:12", "deformer:4")) + + val reopened = Uma.read(Uma.write(sampleDocument().withEditorState(patch))) + + assertEquals(patch, reopened.editorState) + val entry = reopened.entries.single { candidate -> candidate.kind == UmaEntryKind.Editor.wireName } + assertEquals(UmaEntryKind.Editor.defaultPath, entry.path) + assertEquals(false, entry.required, "editor state is never load-bearing") + } + + /** An editor entry too new to interpret is carried, and a patch that would change it is refused. */ + @Test + fun aTooNewEditorEntryIsCarriedNotReplaced() { + val futureBytes = """{ "layout": "v2" }""".encodeToByteArray() + val archive = + umaArchiveOf( + manifestJson( + listOf( + recordJson("model/puppet.json", "puppet", required = true), + recordJson("editor/state.json", "editor", version = 2, minVersion = 2), + ), + ), + listOf(TestEntry("model/puppet.json", """{ "marker": "puppet" }""".encodeToByteArray()), TestEntry("editor/state.json", futureBytes)), + ) + val document = Uma.read(archive) + + assertNull(document.editorState, "a tree this reader would misread is not read") + assertEquals(true, document.holdsTooNewEntry(UmaEntryKind.Editor)) + assertEquals(false, document.isReadOnly, "and never blocks a save: the entry is optional") + assertSame(document, document.withEditorState(JsonObject(emptyMap())), "nothing to write is nothing to refuse") + assertFailsWith { document.withEditorState(outlinerPatch("area-1", listOf("part:1"))) } + } + + /** + * UMA §7: a file with its editor entry and that entry's manifest record stripped loads the same puppet and + * the same sources, because nothing in the model is read from the editor entry. + */ + @Test + fun aFileStrippedOfItsEditorEntryLoadsTheSameDocument() { + val full = Uma.write(sampleDocument().withEditorState(outlinerPatch("area-1", listOf("part:12")))) + val archive = ZipArchive.read(full) + val manifest = parseJsonObject(archive.contents(archive.entry(UmaContainer.MANIFEST_PATH)!!)) { detail -> UmaReadFailure.MalformedManifest(detail) } + val editorPath = UmaEntryKind.Editor.defaultPath + val strippedManifest = + JsonObject( + manifest + ("entries" to JsonArray(manifest["entries"]!!.jsonArray.filter { record -> record.jsonObject["path"]!!.jsonPrimitive.content != editorPath })), + ) + val keptEntries = + archive.entries + .filter { entry -> entry.name != editorPath && !UmaContainer.isReservedPath(entry.name) } + .map { entry -> TestEntry(entry.name, archive.contents(entry)) } + val stripped = Uma.read(umaArchiveOf(strippedManifest.toString(), keptEntries)) + + val whole = Uma.read(full) + assertNotNull(whole.editorState) + assertNull(stripped.editorState, "the entry is gone") + assertEquals(whole.puppet, stripped.puppet, "and the puppet is the same without it") + assertEquals(whole.sources, stripped.sources) + assertEquals(whole.textures, stripped.textures) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaEntrySchemaTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaEntrySchemaTest.kt new file mode 100644 index 0000000..dd522e9 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaEntrySchemaTest.kt @@ -0,0 +1,80 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package org.umamo.format.uma + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind +import org.umamo.format.uma.puppet.UmaPuppet +import org.umamo.format.uma.puppet.UmaPuppetEntry +import org.umamo.format.uma.sources.UmaSources +import org.umamo.format.uma.sources.UmaSourcesEntry +import org.umamo.format.uma.textures.UmaTextures +import org.umamo.format.uma.textures.UmaTexturesEntry +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Guards the retained-tree merge against schema drift: every array of objects a domain entry can hold must have a + * list rule - an identity, or replaced whole - or a save could not decide what its elements' unknown keys belong + * to (UMA §4.7). + */ +class UmaEntrySchemaTest { + /** + * The arrays of objects reachable from [root], through maps included, that [identities] has no rule for. + * + * @param SerialDescriptor root The entry's root schema. + * @param UmaIdentityTable identities The entry's list rules. + * @param String name The entry's name, for the report. + * @return List Each array without a rule, by path. + */ + private fun arraysWithoutARule(root: SerialDescriptor, identities: UmaIdentityTable, name: String): List { + val missing = ArrayList() + val visited = HashSet() + + /** + * Walks one descriptor, recording arrays of objects without a list rule. + * + * @param SerialDescriptor descriptor The schema node. + * @param String path Its position, for the report. + */ + fun walk(descriptor: SerialDescriptor, path: String) { + when (descriptor.kind) { + StructureKind.CLASS -> { + if (!visited.add(descriptor.serialName.removeSuffix("?"))) { + return + } + for (elementIndex in 0 until descriptor.elementsCount) { + walk(descriptor.getElementDescriptor(elementIndex), "$path.${descriptor.getElementName(elementIndex)}") + } + } + + StructureKind.LIST -> { + val element = descriptor.getElementDescriptor(0) + if (element.kind == StructureKind.CLASS && identities.ruleFor(element.serialName) == null) { + missing += "$path (${element.serialName})" + } + walk(element, "$path[]") + } + + StructureKind.MAP -> walk(descriptor.getElementDescriptor(1), "$path{}") + + else -> {} + } + } + walk(root, name) + return missing + } + + /** + * Every array of objects in the puppet, textures, and sources entries has a list rule. + */ + @Test + fun everyArrayOfObjectsHasARule() { + val missing = + arraysWithoutARule(UmaPuppet.serializer().descriptor, UmaPuppetEntry.identities, "puppet") + + arraysWithoutARule(UmaTextures.serializer().descriptor, UmaTexturesEntry.identities, "textures") + + arraysWithoutARule(UmaSources.serializer().descriptor, UmaSourcesEntry.identities, "sources") + assertTrue(missing.isEmpty(), "arrays of objects without a list rule: $missing") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaIdentificationTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaIdentificationTest.kt new file mode 100644 index 0000000..797b70d --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaIdentificationTest.kt @@ -0,0 +1,106 @@ +package org.umamo.format.uma + +import org.umamo.format.binary.ZipArchive +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.ZipWriter +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins how a UMA file identifies itself (docs/format/UMA.md §2) and the layout the writer gives it: the + * fixed-offset mimetype probe accepts exactly what the writer emits and nothing merely similar. + */ +class UmaIdentificationTest { + private val written = Uma.write(UmaModel.create(TEST_WRITER).withLiveContent(UmaEntryKind.Puppet, sampleTree("puppet"))) + + /** + * A mimetype-first archive with the given first entry. + * + * @param String name The first entry's name. + * @param ByteArray contents The first entry's contents. + * @param Boolean deflated Whether the first entry is compressed. + * @return ByteArray The archive. + */ + private fun archiveStartingWith(name: String, contents: ByteArray, deflated: Boolean = false): ByteArray { + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + if (deflated) { + writer.addDeflated(name, contents) + } else { + writer.addStored(name, contents) + } + writer.addDeflated("second.json", "{}".encodeToByteArray()) + return writer.finish() + } + + /** + * What the writer emits is what the probe accepts. + */ + @Test + fun probeAcceptsWriterOutput() { + assertTrue(Uma.matches(written), "a written UMA announces itself") + } + + /** + * The public media type is the string the writer stores at the probe offset, so an operating-system + * registration built from it (a freedesktop magic rule, an Android intent filter) describes real files. + */ + @Test + fun thePublicMediaTypeIsWhatTheWriterStores() { + val stored = written.copyOfRange(38, 38 + Uma.MIME_TYPE.length).decodeToString() + assertEquals(Uma.MIME_TYPE, stored, "UMA §2: the mimetype entry's content sits at offset 38") + } + + /** + * The probe rejects every near miss: another ZIP format's mimetype, a compressed or displaced mimetype, + * an extra field that moves the content, a wrong or longer string, and bytes that are not a ZIP. + */ + @Test + fun probeRejectsNearMisses() { + val mimetype = UmaContainer.MIMETYPE.encodeToByteArray() + assertFalse(Uma.matches(archiveStartingWith("mimetype", "application/x-krita".encodeToByteArray())), "a Krita mimetype") + assertFalse(Uma.matches(archiveStartingWith("mimetype", mimetype, deflated = true)), "a deflated mimetype") + assertFalse(Uma.matches(archiveStartingWith("manifest.json", mimetype)), "the right content under another name") + assertFalse(Uma.matches(archiveStartingWith("mimetype", "application/vnd.umamo.uma+zipx".encodeToByteArray())), "a longer string with the right prefix") + assertFalse(Uma.matches(archiveStartingWith("mimetype", "application/vnd.umamo.umb+zip".encodeToByteArray())), "a wrong string") + + val withExtraField = written.copyOf() + // ZIP: local header @ +0x1C extra length; a non-zero value moves the content off offset 38. + withExtraField[28] = 4 + assertFalse(Uma.matches(withExtraField), "an extra field on the mimetype entry") + + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + writer.addDeflated(UmaContainer.MANIFEST_PATH, "{}".encodeToByteArray()) + writer.addStored(UmaContainer.MIMETYPE_PATH, mimetype) + assertFalse(Uma.matches(writer.finish()), "a mimetype that is not the first entry") + + assertFalse(Uma.matches(ByteArray(200) { byteIndex -> byteIndex.toByte() }), "random bytes") + assertFalse(Uma.matches(written.copyOf(40)), "a file cut off inside the mimetype") + } + + /** + * The writer puts the mimetype first and stored at offset 38, the manifest second, and stamps every + * entry with the fixed epoch. + */ + @Test + fun writerLayoutIsFixed() { + val mimetype = UmaContainer.MIMETYPE.encodeToByteArray() + assertContentEquals(mimetype, written.copyOfRange(38, 38 + mimetype.size), "the mimetype content sits at offset 38") + val archive = ZipArchive.read(written) + assertEquals(listOf("mimetype", "manifest.json", "model/puppet.json"), archive.entries.map { entry -> entry.name }, "entry order") + assertEquals(ZipRecords.METHOD_STORED, archive.entries.first().method, "the mimetype is stored") + assertTrue(archive.entries.all { entry -> entry.dosDateTime == ZipRecords.DOS_EPOCH_DATE_TIME }, "every entry carries the fixed stamp") + } + + /** + * Written JSON is pretty-printed with tabs. + */ + @Test + fun writtenJsonIsTabIndented() { + val archive = ZipArchive.read(written) + val manifest = archive.contents(archive.entry(UmaContainer.MANIFEST_PATH)!!).decodeToString() + assertTrue(manifest.startsWith("{\n\t\"format\": \"uma\""), "the manifest opens tab-indented: ${manifest.take(40)}") + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaReadFailureTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaReadFailureTest.kt new file mode 100644 index 0000000..eb8dc26 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaReadFailureTest.kt @@ -0,0 +1,146 @@ +package org.umamo.format.uma + +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.ZipWriter +import org.umamo.format.uma.puppet.UmaParameterNode +import org.umamo.format.uma.puppet.UmaPuppet +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * Pins that every file that cannot open as UMA fails with its typed reason (docs/format/UMA.md §3.4), + * never with an untyped crash and never by opening something wrong. + */ +class UmaReadFailureTest { + private val puppetRecord = recordJson("model/puppet.json", "puppet", required = true) + private val puppetEntry = TestEntry("model/puppet.json", """{ "marker": "puppet" }""".encodeToByteArray()) + + /** + * The failure reading [bytes] raises. + * + * @param ByteArray bytes The file. + * @return UmaReadFailure The typed reason. + */ + private fun failureOf(bytes: ByteArray): UmaReadFailure = assertFailsWith { Uma.read(bytes) }.failure + + /** + * Bytes that are not a ZIP, or a ZIP that is damaged, are a corrupt container. + */ + @Test + fun corruptContainer() { + assertIs(failureOf(ByteArray(100) { byteIndex -> byteIndex.toByte() }), "not a ZIP") + val good = umaArchiveOf(manifestJson(listOf(puppetRecord)), listOf(puppetEntry)) + assertIs(failureOf(good.copyOf(good.size - 1)), "a truncated archive") + } + + /** + * A ZIP without the UMA mimetype, with a different one, or with a manifest naming another format is + * not UMA. + */ + @Test + fun notUma() { + assertIs(failureOf(umaArchiveOf(manifestJson(listOf(puppetRecord)), listOf(puppetEntry), mimetype = null)), "no mimetype") + assertIs(failureOf(umaArchiveOf(manifestJson(listOf(puppetRecord)), listOf(puppetEntry), mimetype = "application/x-krita")), "a Krita mimetype") + assertIs(failureOf(umaArchiveOf(manifestJson(listOf(puppetRecord), format = "kra"), listOf(puppetEntry))), "another format") + } + + /** + * A manifest that is missing, not JSON, not an object, or breaks a record rule is malformed. + */ + @Test + fun malformedManifest() { + /** + * Asserts the manifest text fails as malformed. + * + * @param String manifest The manifest text, or null for none. + * @param String label What is wrong with it. + */ + fun assertMalformed(manifest: String?, label: String) { + assertIs(failureOf(umaArchiveOf(manifest, listOf(puppetEntry))), label) + } + assertMalformed(null, "no manifest") + assertMalformed("{ \"format\": \"uma\", ", "not valid JSON") + assertMalformed("[ 1, 2 ]", "not an object") + assertMalformed("""{ "format": "uma", "entries": [] }""", "no container version") + assertMalformed(manifestJson(listOf(puppetRecord), containerVersion = 0), "a container version below 1") + assertMalformed("""{ "format": "uma", "containerVersion": "1", "entries": [] }""", "a container version that is a string") + assertMalformed("""{ "format": "uma", "containerVersion": 1 }""", "no entries") + assertMalformed("""{ "format": "uma", "containerVersion": 1, "writer": "me", "entries": [] }""", "a writer that is not an object") + assertMalformed(manifestJson(listOf(recordJson("model/puppet.json", "puppet", version = 1, minVersion = 2))), "minVersion above version") + assertMalformed(manifestJson(listOf(puppetRecord, puppetRecord)), "a path listed twice") + assertMalformed(manifestJson(listOf(puppetRecord, recordJson("model/other.json", "puppet"))), "a known kind listed twice") + assertMalformed(manifestJson(listOf(recordJson("manifest.json", "puppet"))), "a reserved path") + assertMalformed(manifestJson(listOf(recordJson("model/", "puppet"))), "a directory path") + assertMalformed(manifestJson(listOf("""{ "path": "model/puppet.json", "kind": "puppet", "version": 1, "minVersion": 1 }""")), "a record without required") + } + + /** + * A listed path the archive does not hold is a missing entry. + */ + @Test + fun missingEntry() { + assertEquals(UmaReadFailure.MissingEntry("model/puppet.json"), failureOf(umaArchiveOf(manifestJson(listOf(puppetRecord))))) + } + + /** + * A live entry that is not a JSON object fails loudly, even when the file marks it optional. + */ + @Test + fun malformedEntry() { + val notAnObject = failureOf(umaArchiveOf(manifestJson(listOf(puppetRecord)), listOf(TestEntry("model/puppet.json", "[]".encodeToByteArray())))) + assertIs(notAnObject, "a required entry that is not an object") + val optionalNotJson = + failureOf( + umaArchiveOf( + manifestJson(listOf(puppetRecord, recordJson("editor/state.json", "editor"))), + listOf(puppetEntry, TestEntry("editor/state.json", "not json".encodeToByteArray())), + ), + ) + assertEquals("editor/state.json", assertIs(optionalNotJson, "an optional entry that is not JSON").path) + } + + /** + * A mimetype whose bytes fail their CRC-32 is a corrupt container, not a foreign file. + */ + @Test + fun corruptMimetypeIsCorruptNotForeign() { + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + writer.addStored(UmaContainer.MIMETYPE_PATH, UmaContainer.MIMETYPE.encodeToByteArray()) + writer.addDeflated(UmaContainer.MANIFEST_PATH, manifestJson(listOf(puppetRecord)).encodeToByteArray()) + writer.addDeflated(puppetEntry.path, puppetEntry.contents) + val bytes = writer.finish() + // The mimetype's first content byte, at offset 38: changing it breaks the recorded CRC-32. + bytes[38] = 'A'.code.toByte() + assertIs(failureOf(bytes)) + } + + /** + * An entry nested past the limit fails as malformed instead of overflowing the stack of the walks over it, one at + * the limit reads, and a save that would nest past it is refused. + */ + @Test + fun nestingPastTheLimitIsRefused() { + /** + * A file whose puppet entry holds arrays under an unknown key, nested to [depth] levels with the root as one. + * + * @param Int depth The deepest level. + * @return ByteArray The file. + */ + fun puppetNestedTo(depth: Int): ByteArray { + val arrays = depth - 1 + val json = """{ "futureKey": ${"[".repeat(arrays)}${"]".repeat(arrays)} }""" + return umaArchiveOf(manifestJson(listOf(puppetRecord)), listOf(TestEntry("model/puppet.json", json.encodeToByteArray()))) + } + Uma.read(puppetNestedTo(UMA_MAXIMUM_JSON_DEPTH)) + assertIs(failureOf(puppetNestedTo(UMA_MAXIMUM_JSON_DEPTH + 1)), "one level past the limit") + val deep = assertIs(failureOf(puppetNestedTo(10_000)), "far past it") + assertTrue(deep.detail.contains("nested deeper"), deep.detail) + + var node = UmaParameterNode(parameter = "P") + repeat(200) { level -> node = UmaParameterNode(group = "G$level", name = "G", children = listOf(node)) } + assertFailsWith("a parameter tree nested past the limit") { UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(parameterTree = listOf(node))) } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaTestSupport.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaTestSupport.kt new file mode 100644 index 0000000..1e4ea40 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/UmaTestSupport.kt @@ -0,0 +1,89 @@ +package org.umamo.format.uma + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.ZipWriter + +/* + * Builders for the UMA tests: hand-made archives shaped like files a newer, older, or foreign writer + * could produce, so each compatibility rule is exercised from bytes rather than from the codec's own model. + */ + +/** The writer record the tests stamp on documents they create. */ +internal val TEST_WRITER: UmaWriterInfo = UmaWriterInfo("Umamo", "0.0.0-test") + +/** + * One archive entry a hand-built UMA file holds after its bootstrap entries. + * + * @property String path The entry path. + * @property ByteArray contents The entry's bytes. + * @property Boolean deflated Whether the entry is compressed. + */ +internal class TestEntry( + val path: String, + val contents: ByteArray, + val deflated: Boolean = true, +) + +/** + * A manifest entry record as JSON text, with any extra keys appended. + * + * @param String path The entry path. + * @param String kind The entry kind. + * @param Int version The declared schema version. + * @param Int minVersion The declared minimum schema version. + * @param Boolean required Whether the entry is declared required. + * @param String extraKeys Extra JSON members, including a leading comma, or empty. + * @return String The record. + */ +internal fun recordJson(path: String, kind: String, version: Int = 1, minVersion: Int = 1, required: Boolean = false, extraKeys: String = ""): String = + """{ "path": "$path", "kind": "$kind", "version": $version, "minVersion": $minVersion, "required": $required$extraKeys }""" + +/** + * A manifest as JSON text. + * + * @param List records The entry records' JSON. + * @param Int containerVersion The container version. + * @param String format The `format` value. + * @param String extraKeys Extra top-level JSON members, including a leading comma, or empty. + * @return String The manifest. + */ +internal fun manifestJson(records: List, containerVersion: Int = 1, format: String = "uma", extraKeys: String = ""): String = + """{ "format": "$format", "containerVersion": $containerVersion, "writer": { "app": "Future", "version": "9" }, "entries": [ ${records.joinToString(", ")} ]$extraKeys }""" + +/** + * A hand-built UMA archive: the stored mimetype first, the manifest second, then [entries] in order. + * + * @param String manifest The manifest's JSON text, or null to leave it out. + * @param List entries The entries after the bootstrap pair. + * @param String mimetype The mimetype entry's content, or null to leave it out. + * @return ByteArray The archive. + */ +internal fun umaArchiveOf(manifest: String?, entries: List = emptyList(), mimetype: String? = UmaContainer.MIMETYPE): ByteArray { + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + mimetype?.let { content -> writer.addStored(UmaContainer.MIMETYPE_PATH, content.encodeToByteArray()) } + manifest?.let { content -> writer.addDeflated(UmaContainer.MANIFEST_PATH, content.encodeToByteArray()) } + for (entry in entries) { + if (entry.deflated) { + writer.addDeflated(entry.path, entry.contents) + } else { + writer.addStored(entry.path, entry.contents) + } + } + return writer.finish() +} + +/** + * A small JSON object for a live entry's content. + * + * @param String marker A value that tells trees apart. + * @return JsonObject The tree. + */ +internal fun sampleTree(marker: String): JsonObject = + buildJsonObject { + put("marker", JsonPrimitive(marker)) + put("count", 3) + } \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaBufferTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaBufferTest.kt new file mode 100644 index 0000000..a65ea41 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaBufferTest.kt @@ -0,0 +1,251 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import okio.Buffer +import org.umamo.format.binary.ZipArchive +import org.umamo.format.binary.ZipRecords +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.TestEntry +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaAccessor +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.manifestJson +import org.umamo.format.uma.recordJson +import org.umamo.format.uma.umaArchiveOf +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the puppet entry's buffer (docs/format/UMA.md §4.9): what an accessor is, what a sound one + * must satisfy, how a save lays the owned buffer out, and that an accessor under a key this reader does not know + * keeps its bytes when the buffer is rebuilt around it. + */ +class UmaBufferTest { + private val bufferPath = "model/buffers.bin" + + /** + * Little-endian float32 bytes. + * + * @param Float values The values. + * @return ByteArray The bytes. + */ + private fun float32(vararg values: Float): ByteArray = Buffer().also { buffer -> values.forEach { value -> buffer.writeIntLe(value.toRawBits()) } }.readByteArray() + + /** + * Little-endian int32 bytes. + * + * @param Int values The values. + * @return ByteArray The bytes. + */ + private fun int32(vararg values: Int): ByteArray = Buffer().also { buffer -> values.forEach { value -> buffer.writeIntLe(value) } }.readByteArray() + + /** + * An accessor's JSON text. + * + * @param String buffer The buffer path. + * @param Int byteOffset The offset. + * @param Int count The component count. + * @param String componentType The component type. + * @param Int byteLength The byte length; four per component unless given. + * @return String The JSON. + */ + private fun accessor(buffer: String, byteOffset: Int, count: Int, componentType: String, byteLength: Int = count * 4): String = + """{ "buffer": "$buffer", "byteOffset": $byteOffset, "byteLength": $byteLength, "count": $count, "componentType": "$componentType" }""" + + /** + * A file holding a puppet entry and a buffer. + * + * @param String puppetJson The puppet entry's JSON text. + * @param ByteArray buffer The buffer's bytes, or null for no buffer. + * @param List extra Further entries. + * @return ByteArray The file. + */ + private fun fileWith(puppetJson: String, buffer: ByteArray?, extra: List = emptyList()): ByteArray = + umaArchiveOf( + manifestJson(listOf(recordJson("model/puppet.json", "puppet", required = true))), + listOfNotNull(TestEntry("model/puppet.json", puppetJson.encodeToByteArray()), buffer?.let { bytes -> TestEntry(bufferPath, bytes, deflated = false) }) + extra, + ) + + /** + * A one-triangle mesh whose arrays sit in the buffer after [prefixBytes] bytes of something else. + * + * @param Int prefixBytes Bytes before the mesh arrays. + * @return String The mesh's JSON text. + */ + private fun triangleMeshJson(prefixBytes: Int): String = + """{ "positions": ${accessor(bufferPath, prefixBytes, 6, "float32")}, "uvs": ${accessor(bufferPath, prefixBytes + 24, 6, "float32")}, "indices": ${accessor(bufferPath, prefixBytes + 48, 3, "int32")} }""" + + /** The triangle mesh's bytes, in the order [triangleMeshJson] names them. */ + private val triangleBytes: ByteArray = float32(0f, 0f, 10f, 0f, 0f, 10f) + float32(0f, 0f, 1f, 0f, 0f, 1f) + int32(0, 1, 2) + + /** + * An accessor is exactly five keys of the right types; anything else is ordinary data. + */ + @Test + fun accessorShapeIsExact() { + /** + * Parses JSON text as an object. + * + * @param String text The JSON. + * @return JsonObject The object. + */ + fun objectOf(text: String): JsonObject = kotlinx.serialization.json.Json.parseToJsonElement(text) as JsonObject + assertNotNull(UmaAccessor.of(objectOf(accessor(bufferPath, 0, 2, "float32"))), "the five keys") + assertNotNull(UmaAccessor.of(objectOf(accessor(bufferPath, 0, 2, "float64", byteLength = 16))), "an unknown component type is still an accessor") + assertNull(UmaAccessor.of(objectOf("""{ "buffer": "b", "byteOffset": 0, "byteLength": 8, "count": 2, "componentType": "float32", "stride": 4 }""")), "an extra key") + assertNull(UmaAccessor.of(objectOf("""{ "buffer": "b", "byteOffset": "0", "byteLength": 8, "count": 2, "componentType": "float32" }""")), "a quoted offset") + assertNull(UmaAccessor.of(objectOf("""{ "buffer": "b", "byteOffset": -4, "byteLength": 8, "count": 2, "componentType": "float32" }""")), "a negative offset") + assertNull(UmaAccessor.of(objectOf("""{ "buffer": "b", "byteOffset": 0, "byteLength": 8, "count": 2 }""")), "a missing key") + } + + /** + * A sound file reads its mesh straight out of the buffer. + */ + @Test + fun meshReadsFromTheBuffer() { + val model = Uma.read(fileWith("""{ "drawables": [ { "id": "D", "name": "D", "mesh": ${triangleMeshJson(0)} } ] }""", triangleBytes)) + val mesh = assertNotNull(model.puppet!!.drawables!!.single().mesh) + assertContentEquals(floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f), mesh.positions) + assertContentEquals(intArrayOf(0, 1, 2), mesh.indices) + } + + /** + * Each unsound accessor fails the read as a malformed entry, including one under a key this reader does not + * know, since a save would have to copy its bytes. + */ + @Test + fun unsoundAccessorsAreMalformed() { + /** + * Asserts that a puppet entry over [buffer] fails as malformed. + * + * @param String puppetJson The puppet entry's JSON text. + * @param ByteArray? buffer The buffer's bytes. + * @param String label What is wrong. + */ + fun assertMalformed(puppetJson: String, buffer: ByteArray?, label: String) { + val failure = assertFailsWith(label) { Uma.read(fileWith(puppetJson, buffer)) }.failure + assertIs(failure, label) + } + + /** + * A one-drawable puppet whose mesh positions use [positions]. + * + * @param String positions The positions accessor's JSON. + * @return String The puppet's JSON. + */ + fun withPositions(positions: String): String = + """{ "drawables": [ { "id": "D", "name": "D", "mesh": { "positions": $positions, "uvs": ${accessor(bufferPath, 24, 6, "float32")}, "indices": ${accessor(bufferPath, 48, 3, "int32")} } } ] }""" + + assertMalformed(withPositions(accessor(bufferPath, 0, 6, "float32")), null, "no buffer at all") + assertMalformed(withPositions(accessor("model/other.bin", 0, 6, "float32")), triangleBytes, "a buffer the archive does not hold") + assertMalformed(withPositions(accessor(bufferPath, 40, 6, "float32")), triangleBytes, "bytes past the buffer's end") + assertMalformed(withPositions(accessor(bufferPath, 0, 6, "float32", byteLength = 20)), triangleBytes, "a length that is not four per component") + assertMalformed(withPositions(accessor(bufferPath, 2, 5, "float32")), triangleBytes, "an offset off the component alignment") + assertMalformed(withPositions(accessor(bufferPath, 0, 6, "int32")), triangleBytes, "an int32 accessor on a float field") + assertMalformed( + """{ "drawables": [ { "id": "D", "name": "D", "mesh": ${triangleMeshJson(0)}, "futureWeights": ${accessor(bufferPath, 56, 4, "float32")} } ] }""", + triangleBytes, + "an unsound accessor under an unknown key", + ) + } + + /** + * A save writes the buffer stored, right after the puppet entry, with every array in document order on a + * four-byte boundary; with nothing unknown in it, the bytes do not depend on the file's history. + */ + @Test + fun saveLaysTheBufferOut() { + val first = UmaDrawable("A", "A", mesh = UmaMesh(floatArrayOf(1f, 2f, 3f, 4f), floatArrayOf(0f, 0f, 1f, 1f), intArrayOf(0, 1, 1))) + val second = UmaDrawable("B", "B", mesh = UmaMesh(floatArrayOf(5f, 6f), floatArrayOf(0.5f, 0.5f), intArrayOf(0, 0, 0))) + val puppet = UmaPuppet(drawables = listOf(first, second)) + val bytes = Uma.write(UmaModel.create(TEST_WRITER).withPuppet(puppet)) + + val archive = ZipArchive.read(bytes) + assertEquals(listOf("mimetype", "manifest.json", "model/puppet.json", bufferPath), archive.entries.map { entry -> entry.name }, "the buffer follows its entry") + assertEquals(ZipRecords.METHOD_STORED, archive.entry(bufferPath)!!.method, "the buffer is stored") + + val tree = Uma.read(bytes).liveContent(UmaEntryKind.Puppet)!! + val offsets = + (tree["drawables"] as JsonArray).flatMap { drawable -> + val mesh = (drawable as JsonObject)["mesh"] as JsonObject + listOf("positions", "uvs", "indices").map { key -> UmaAccessor.of(mesh[key]!!)!!.byteOffset } + } + assertEquals(listOf(0, 16, 32, 44, 52, 60), offsets, "document order, four bytes per component, no gaps") + + val otherHistory = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(drawables = listOf(second, first))))) + assertContentEquals(bytes, Uma.write(otherHistory.withPuppet(puppet)), "the same puppet writes the same bytes whatever came before") + assertContentEquals(bytes, Uma.write(Uma.read(bytes)), "an unedited reopen rewrites byte for byte") + } + + /** + * An accessor a newer writer put under a key this reader does not know keeps its bytes when a mesh edit + * rebuilds the buffer around it (UMA §4.9), and an accessor naming another buffer is copied into the + * owned one while that other buffer stays in the file. + */ + @Test + fun unknownAccessorsKeepTheirBytesThroughARebuild() { + val weights = int32(7, 8, 9) + val extraBytes = float32(0.25f, 0.5f) + val puppetJson = + """{ "drawables": [ { "id": "D", "name": "D", "mesh": ${triangleMeshJson(12)}, "futureWeights": ${accessor(bufferPath, 0, 3, "int32")}, "futureCurve": ${accessor("model/extra.bin", 0, 2, "float32")} } ] }""" + val document = Uma.read(fileWith(puppetJson, weights + triangleBytes, listOf(TestEntry("model/extra.bin", extraBytes, deflated = false)))) + + val edited = document.puppet!!.let { puppet -> puppet.copy(drawables = listOf(puppet.drawables!!.single().copy(mesh = UmaMesh(FloatArray(8) { value -> value.toFloat() }, FloatArray(8), intArrayOf(0, 1, 2, 0, 2, 3))))) } + val saved = Uma.read(Uma.write(document.withPuppet(edited))) + val drawable = ((saved.liveContent(UmaEntryKind.Puppet)!!["drawables"] as JsonArray).single() as JsonObject) + + val weightsAccessor = assertNotNull(UmaAccessor.of(drawable["futureWeights"]!!), "the unknown accessor survives") + assertEquals(bufferPath, weightsAccessor.buffer) + val buffer = saved.bufferBytes(bufferPath)!! + assertContentEquals(weights, buffer.copyOfRange(weightsAccessor.byteOffset, weightsAccessor.byteOffset + weightsAccessor.byteLength), "with its own bytes") + + val curveAccessor = assertNotNull(UmaAccessor.of(drawable["futureCurve"]!!)) + assertEquals(bufferPath, curveAccessor.buffer, "an accessor naming another buffer now names the owned one") + assertContentEquals(extraBytes, buffer.copyOfRange(curveAccessor.byteOffset, curveAccessor.byteOffset + curveAccessor.byteLength), "with the bytes it named") + assertTrue(saved.payloads.any { payload -> payload.path == "model/extra.bin" }, "and the other buffer stays in the file") + + assertContentEquals(FloatArray(8) { value -> value.toFloat() }, saved.puppet!!.drawables!!.single().mesh!!.positions, "the edit lands") + } + + /** + * An accessor of a component type this reader does not know is laid out on a multiple of 8, so a newer reader that + * knows the type finds it aligned however odd the run before it. + */ + @Test + fun unknownComponentTypesAlignToEight() { + val oddRun = byteArrayOf(1, 2, 3) + val doubleBytes = byteArrayOf(10, 11, 12, 13, 14, 15, 16, 17) + val puppetJson = + """{ "drawables": [ { "id": "D", "name": "D", "futureBytes": ${accessor(bufferPath, 0, 3, "uint8", byteLength = 3)}, "futureDouble": ${accessor(bufferPath, 3, 1, "float64", byteLength = 8)} } ] }""" + val document = Uma.read(fileWith(puppetJson, oddRun + doubleBytes)) + val saved = Uma.read(Uma.write(document.withPuppet(document.puppet!!))) + val drawable = ((saved.liveContent(UmaEntryKind.Puppet)!!["drawables"] as JsonArray).single() as JsonObject) + val doubleAccessor = assertNotNull(UmaAccessor.of(drawable["futureDouble"]!!)) + assertEquals(0, doubleAccessor.byteOffset % 8, "the run starts on a multiple of 8: ${doubleAccessor.byteOffset}") + val buffer = saved.bufferBytes(bufferPath)!! + assertContentEquals(doubleBytes, buffer.copyOfRange(doubleAccessor.byteOffset, doubleAccessor.byteOffset + doubleAccessor.byteLength), "with its own bytes") + } + + /** + * An owned buffer nothing references any more is not written. + */ + @Test + fun unreferencedOwnedBufferIsDropped() { + val document = Uma.read(fileWith("""{ "drawables": [ { "id": "D", "name": "D", "mesh": ${triangleMeshJson(0)} } ] }""", triangleBytes)) + val saved = Uma.write(document.withPuppet(UmaPuppet(drawables = listOf(UmaDrawable("D", "D"))))) + assertFalse(ZipArchive.read(saved).entries.any { entry -> entry.name == bufferPath }, "no buffer without an accessor") + assertEquals(JsonPrimitive("D"), ((Uma.read(saved).liveContent(UmaEntryKind.Puppet)!!["drawables"] as JsonArray).single() as JsonObject)["id"]) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaGeometryMergeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaGeometryMergeTest.kt new file mode 100644 index 0000000..68906ee --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaGeometryMergeTest.kt @@ -0,0 +1,244 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaModel +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Pins the retained-tree merge on the puppet entry's geometry half (docs/format/UMA.md §4.7): keys a + * newer writer puts in a mesh, a grid axis, a cell, a channel track, a blend shape, a limit, or a glue survive + * a rename, a mesh edit, and deletions that shift what follows; a cell keeps its keys at its key values; blend forms + * are values and are replaced whole; channel tracks merge by channel. + */ +class UmaGeometryMergeTest { + private val axis = UmaAxis("P0", listOf(-1f, 0f, 1f)) + + /** + * A one-axis channel track with the same value at every key. + * + * @param Float value The value. + * @return UmaChannelGrid The track. + */ + private fun track(value: Float): UmaChannelGrid = UmaChannelGrid(listOf(axis), (0 until 3).map { keyIndex -> UmaChannelCell(listOf(keyIndex), JsonPrimitive(value)) }) + + /** + * A triangle mesh. + * + * @return UmaMesh The mesh. + */ + private fun triangle(): UmaMesh = UmaMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), FloatArray(6), intArrayOf(0, 1, 2)) + + /** + * A puppet with one of every geometry object kind that carries keys of its own. + * + * @return UmaPuppet The puppet. + */ + private fun geometryPuppet(): UmaPuppet = + UmaPuppet( + parameters = listOf(UmaParameter("P0", "P0", -1f, 1f, 0f), UmaParameter("P1", "P1", 0f, 1f, 0f)), + drawables = + listOf( + UmaDrawable( + id = "A", + name = "A", + mesh = triangle(), + geometry = UmaMeshGrid(listOf(axis), (0 until 3).map { keyIndex -> UmaMeshCell(listOf(keyIndex), FloatArray(6) { keyIndex.toFloat() }) }), + channels = linkedMapOf(UmaFormChannel.DrawOrder to track(500f), UmaFormChannel.Opacity to track(0.5f)), + blendShapes = + listOf( + UmaMeshBlendShape( + parameter = "P1", + keys = listOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, UmaMeshForm(FloatArray(6) { 1f })), + limits = listOf(UmaBlendLimit("P0", listOf(UmaBlendLimitPoint(-1f, 0f), UmaBlendLimitPoint(1f, 1f)))), + ), + ), + ), + UmaDrawable("B", "B", mesh = triangle()), + ), + glues = + listOf( + UmaGlue("A", "B", UmaGluePairs(intArrayOf(0), intArrayOf(1), floatArrayOf(0.5f), floatArrayOf(0.5f))), + UmaGlue("B", "A", UmaGluePairs(intArrayOf(2), intArrayOf(0), floatArrayOf(0.25f), floatArrayOf(0.75f))), + ), + ) + + /** + * The saved geometry puppet with a newer writer's keys planted in every geometry object kind, read back. + * + * @return UmaModel The document as an older writer opens it. + */ + private fun plantedDocument(): UmaModel { + val saved = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(geometryPuppet()))) + var tree = saved.liveContent(UmaEntryKind.Puppet)!! + tree = + withArray(tree, "drawables") { _, drawable -> + if ((drawable["id"] as JsonPrimitive).content != "A") { + drawable + } else { + var planted = withKey(drawable, "mesh", withKey(drawable["mesh"] as JsonObject, "futureMesh", plantedValue("mesh"))) + var geometry = withArray(planted["geometry"] as JsonObject, "axes") { _, axisTree -> withKey(axisTree, "futureAxis", plantedValue("axis")) } + geometry = withArray(geometry, "cells") { cellIndex, cell -> if (cellIndex == 1) withKey(cell, "futureCell", plantedValue("cell 1")) else cell } + planted = withKey(planted, "geometry", geometry) + val channels = planted["channels"] as JsonObject + planted = withKey(planted, "channels", withKey(channels, "opacity", withKey(channels["opacity"] as JsonObject, "futureTrack", plantedValue("opacity")))) + withArray(planted, "blendShapes") { _, binding -> + val withLimit = withArray(withKey(binding, "futureBinding", plantedValue("binding")), "limits") { _, limit -> withKey(limit, "futureLimit", plantedValue("limit")) } + val forms = withLimit["forms"] as JsonArray + withKey(withLimit, "forms", JsonArray(listOf(forms[0], withKey(forms[1] as JsonObject, "futureForm", plantedValue("form"))))) + } + } + } + tree = withArray(tree, "glues") { glueIndex, glue -> if (glueIndex == 1) withKey(glue, "futureGlue", plantedValue("B,A")) else glue } + return Uma.read(Uma.write(saved.withLiveContent(UmaEntryKind.Puppet, tree))) + } + + /** + * Planted geometry keys ride through a rename, a mesh edit, a deleted cell, a deleted channel, and a deleted + * glue, each staying with its own object; a blend form's key does not, since forms are replaced whole. + */ + @Test + fun geometryKeysSurviveEditsByIdentity() { + val document = plantedDocument() + val puppet = assertNotNull(document.puppet) + val drawableA = puppet.drawables!!.first { drawable -> drawable.id == "A" } + val editedA = + drawableA.copy( + name = "A renamed", + mesh = UmaMesh(floatArrayOf(0f, 0f, 2f, 0f, 2f, 2f, 0f, 2f), FloatArray(8), intArrayOf(0, 1, 2, 0, 2, 3)), + geometry = drawableA.geometry!!.copy(cells = drawableA.geometry.cells.drop(1).map { cell -> UmaMeshCell(cell.coordinate, FloatArray(8) { 3f }) }), + channels = drawableA.channels!!.filterKeys { channel -> channel != UmaFormChannel.DrawOrder }, + blendShapes = drawableA.blendShapes!!.map { binding -> binding.copy(forms = listOf(null, UmaMeshForm(FloatArray(8) { 2f }))) }, + ) + val edited = puppet.copy(drawables = puppet.drawables.map { drawable -> if (drawable.id == "A") editedA else drawable }, glues = puppet.glues!!.drop(1)) + val saved = Uma.read(Uma.write(document.withPuppet(edited))) + val tree = saved.liveContent(UmaEntryKind.Puppet)!! + val drawable = assertNotNull(elementOf(tree, "drawables", "id", "A")) + + assertEquals(JsonPrimitive("A renamed"), drawable["name"], "the rename lands") + assertEquals(plantedValue("mesh"), (drawable["mesh"] as JsonObject)["futureMesh"], "a mesh keeps its key through a mesh edit") + assertContentEquals(floatArrayOf(0f, 0f, 2f, 0f, 2f, 2f, 0f, 2f), saved.puppet!!.drawables!!.first { candidate -> candidate.id == "A" }.mesh!!.positions, "and the edit lands") + + val geometry = drawable["geometry"] as JsonObject + assertEquals(plantedValue("axis"), ((geometry["axes"] as JsonArray).single() as JsonObject)["futureAxis"], "an axis keeps its key") + val cells = (geometry["cells"] as JsonArray).map { cell -> cell as JsonObject } + assertEquals(plantedValue("cell 1"), cells[0]["futureCell"], "the cell that shifted to the front keeps its own key") + assertNull(cells[1]["futureCell"], "and its old neighbor does not take it") + + val channels = drawable["channels"] as JsonObject + assertEquals(listOf("opacity"), channels.keys.toList(), "the deleted channel is gone") + assertEquals(plantedValue("opacity"), (channels["opacity"] as JsonObject)["futureTrack"], "the remaining track keeps its key") + + val binding = (drawable["blendShapes"] as JsonArray).single() as JsonObject + assertEquals(plantedValue("binding"), binding["futureBinding"], "a blend shape keeps its key") + assertEquals(plantedValue("limit"), ((binding["limits"] as JsonArray).single() as JsonObject)["futureLimit"], "a limit keeps its key") + assertNull(((binding["forms"] as JsonArray)[1] as JsonObject)["futureForm"], "a blend form is replaced whole") + + val glue = (tree["glues"] as JsonArray).single() as JsonObject + assertEquals(JsonPrimitive("B"), glue["meshA"], "the surviving glue shifted to the front") + assertEquals(plantedValue("B,A"), glue["futureGlue"], "and keeps its own key") + } + + /** + * A puppet with one drawable whose opacity track is [track] and whose mesh grid is [geometry]. + * + * @param UmaChannelGrid track The opacity track. + * @param UmaMeshGrid? geometry The mesh grid, if any. + * @return UmaPuppet The puppet. + */ + private fun trackPuppet(track: UmaChannelGrid, geometry: UmaMeshGrid? = null): UmaPuppet = + UmaPuppet( + parameters = listOf(UmaParameter("P0", "P0", -2f, 1f, 0f), UmaParameter("P1", "P1", 0f, 1f, 0f)), + drawables = listOf(UmaDrawable("A", "A", mesh = geometry?.let { triangle() }, geometry = geometry, channels = mapOf(UmaFormChannel.Opacity to track))), + ) + + /** + * [document] with a planted key on each cell of drawable A's opacity track, and on each cell of its mesh grid when + * it has one, marked by what [markerOf] names the cell. + * + * @param UmaModel document The saved document. + * @param Function markerOf Names a cell by its index. + * @return UmaModel The planted document, as an older writer reads it. + */ + private fun plantedCells(document: UmaModel, markerOf: (Int) -> String): UmaModel { + val tree = + withArray(document.liveContent(UmaEntryKind.Puppet)!!, "drawables") { _, drawable -> + val channels = drawable["channels"] as JsonObject + var planted = withKey(drawable, "channels", withKey(channels, "opacity", withArray(channels["opacity"] as JsonObject, "cells") { cellIndex, cell -> withKey(cell, "futureCell", plantedValue(markerOf(cellIndex))) })) + (planted["geometry"] as? JsonObject)?.let { geometry -> + planted = withKey(planted, "geometry", withArray(geometry, "cells") { cellIndex, cell -> withKey(cell, "futureCell", plantedValue(markerOf(cellIndex))) }) + } + planted + } + return Uma.read(Uma.write(document.withLiveContent(UmaEntryKind.Puppet, tree))) + } + + /** + * The planted marker of each cell under [key] of drawable A in [document], by coordinate. + * + * @param UmaModel document The document. + * @param String key `opacity` for the track, `geometry` for the mesh grid. + * @return Map Each cell's coordinate as text, mapped to its planted value or null. + */ + private fun markersOf(document: UmaModel, key: String): Map { + val drawable = assertNotNull(elementOf(document.liveContent(UmaEntryKind.Puppet)!!, "drawables", "id", "A")) + val grid = if (key == "geometry") drawable["geometry"] as JsonObject else (drawable["channels"] as JsonObject)[key] as JsonObject + return (grid["cells"] as JsonArray).associate { cell -> (cell as JsonObject)["coordinate"].toString() to cell["futureCell"] } + } + + /** + * A key a newer writer put in a grid cell stays with the cell for the same key values: through a key added before + * it, through a reordering of the axes, and through a repeated key; an axis the grid loses takes its cells' keys + * with it. + */ + @Test + fun cellKeysFollowTheirKeyValues() { + val oneAxis = UmaAxis("P0", listOf(-1f, 0f, 1f)) + val saved = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(trackPuppet(UmaChannelGrid(listOf(oneAxis), (0 until 3).map { keyIndex -> UmaChannelCell(listOf(keyIndex), JsonPrimitive(keyIndex)) }), UmaMeshGrid(listOf(oneAxis), (0 until 3).map { keyIndex -> UmaMeshCell(listOf(keyIndex), FloatArray(6)) }))))) + val planted = plantedCells(saved) { cellIndex -> "at ${oneAxis.keys[cellIndex]}" } + + // A key added below every other: each old cell's coordinate moves up by one. + val widened = UmaAxis("P0", listOf(-2f, -1f, 0f, 1f)) + val inserted = trackPuppet(UmaChannelGrid(listOf(widened), (0 until 4).map { keyIndex -> UmaChannelCell(listOf(keyIndex), JsonPrimitive(keyIndex)) }), UmaMeshGrid(listOf(widened), (0 until 4).map { keyIndex -> UmaMeshCell(listOf(keyIndex), FloatArray(6)) })) + val afterInsert = Uma.read(Uma.write(planted.withPuppet(inserted))) + val expected = mapOf("[0]" to null, "[1]" to plantedValue("at -1.0"), "[2]" to plantedValue("at 0.0"), "[3]" to plantedValue("at 1.0")) + assertEquals(expected, markersOf(afterInsert, "opacity"), "a channel cell keeps its key at its key value") + assertEquals(expected, markersOf(afterInsert, "geometry"), "and so does a mesh cell") + + // Two axes, then the same cells with the axes swapped. + val first = UmaAxis("P0", listOf(0f, 1f)) + val second = UmaAxis("P1", listOf(0f, 1f)) + val coordinates = listOf(listOf(0, 0), listOf(1, 0), listOf(0, 1), listOf(1, 1)) + val twoAxes = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(trackPuppet(UmaChannelGrid(listOf(first, second), coordinates.map { coordinate -> UmaChannelCell(coordinate, JsonPrimitive(0)) }))))) + val plantedTwoAxes = plantedCells(twoAxes) { cellIndex -> "P0=${coordinates[cellIndex][0]} P1=${coordinates[cellIndex][1]}" } + val swapped = trackPuppet(UmaChannelGrid(listOf(second, first), coordinates.map { coordinate -> UmaChannelCell(coordinate.reversed(), JsonPrimitive(0)) })) + assertEquals( + mapOf("[0,0]" to plantedValue("P0=0 P1=0"), "[0,1]" to plantedValue("P0=1 P1=0"), "[1,0]" to plantedValue("P0=0 P1=1"), "[1,1]" to plantedValue("P0=1 P1=1")), + markersOf(Uma.read(Uma.write(plantedTwoAxes.withPuppet(swapped))), "opacity"), + "a cell keeps its key when the axes swap", + ) + + // An axis the grid loses: its cells are different forms, so their keys leave. + val collapsed = trackPuppet(UmaChannelGrid(listOf(first), listOf(UmaChannelCell(listOf(0), JsonPrimitive(0)), UmaChannelCell(listOf(1), JsonPrimitive(0))))) + assertEquals(mapOf("[0]" to null, "[1]" to null), markersOf(Uma.read(Uma.write(plantedTwoAxes.withPuppet(collapsed))), "opacity"), "a lost axis takes its cells' keys") + + // A repeated key: the second of two equal keys stays the second through a key added before both. + val repeated = UmaAxis("P0", listOf(0f, 0f, 1f)) + val withRepeat = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(trackPuppet(UmaChannelGrid(listOf(repeated), (0 until 3).map { keyIndex -> UmaChannelCell(listOf(keyIndex), JsonPrimitive(keyIndex)) }))))) + val plantedRepeat = plantedCells(withRepeat) { cellIndex -> "cell $cellIndex" } + val repeatedWidened = UmaAxis("P0", listOf(-1f, 0f, 0f, 1f)) + val afterRepeat = Uma.read(Uma.write(plantedRepeat.withPuppet(trackPuppet(UmaChannelGrid(listOf(repeatedWidened), (0 until 4).map { keyIndex -> UmaChannelCell(listOf(keyIndex), JsonPrimitive(keyIndex)) }))))) + assertEquals(mapOf("[0]" to null, "[1]" to plantedValue("cell 0"), "[2]" to plantedValue("cell 1"), "[3]" to plantedValue("cell 2")), markersOf(afterRepeat, "opacity")) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetReadTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetReadTest.kt new file mode 100644 index 0000000..a942b58 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetReadTest.kt @@ -0,0 +1,108 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.TestEntry +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.manifestJson +import org.umamo.format.uma.recordJson +import org.umamo.format.uma.umaArchiveOf +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * Pins how the puppet entry decodes (docs/format/UMA.md §4.8): what the schema refuses fails the read with + * a malformed-entry reason, and what it does not know is ignored while the tree keeps it. + */ +class UmaPuppetReadTest { + /** + * A UMA file whose puppet entry is [puppetJson]. + * + * @param String puppetJson The puppet entry's JSON text. + * @return ByteArray The file. + */ + private fun fileWithPuppet(puppetJson: String): ByteArray = + umaArchiveOf( + manifestJson(listOf(recordJson("model/puppet.json", "puppet", required = true))), + listOf(TestEntry("model/puppet.json", puppetJson.encodeToByteArray())), + ) + + /** + * Asserts that reading a puppet entry fails as malformed, and returns the detail. + * + * @param String puppetJson The puppet entry's JSON text. + * @param String label What is wrong with it. + * @return String The failure's detail. + */ + private fun assertMalformed(puppetJson: String, label: String): String { + val failure = assertFailsWith(label) { Uma.read(fileWithPuppet(puppetJson)) }.failure + return assertIs(failure, label).detail + } + + /** + * Each thing the schema refuses fails the read. + */ + @Test + fun schemaViolationsAreMalformed() { + assertMalformed("""{ "parameters": [ { "id": "ParamA", "name": "A", "max": 1, "default": 0 } ] }""", "a missing required field") + assertMalformed("""{ "drawables": [ { "id": "D", "name": "D", "blendMode": "plusDarker" } ] }""", "an unknown enum value") + assertMalformed("""{ "parts": [ { "id": "P", "name": "P", "drawOrder": "high" } ] }""", "a wrong type") + assertMalformed("""{ "parts": [ { "id": "P", "name": "P", "drawOrder": 500.5 } ] }""", "a fraction where an integer belongs") + assertMalformed("""{ "canvasWidth": 1e400 }""", "a number beyond a float") + assertMalformed("""{ "drawables": [ { "id": "D", "name": 5 } ] }""", "a number where a string belongs") + val duplicate = assertMalformed("""{ "parts": [ { "id": "P", "name": "P" }, { "id": "P", "name": "Q" } ] }""", "a repeated id") + assertTrue(duplicate.contains("parts[1]"), "the failure names the repeat: $duplicate") + assertMalformed("""{ "rootChildren": [ {} ] }""", "an org reference naming nothing") + assertMalformed("""{ "rootChildren": [ { "part": "X" }, { "part": "X" } ] }""", "a repeated org reference") + } + + /** + * Keys the schema does not know decode without complaint, and the tree keeps them. + */ + @Test + fun unknownKeysAreIgnoredAndKept() { + val model = Uma.read(fileWithPuppet("""{ "canvasWidth": 800, "futureSetting": { "enabled": true }, "parts": [ { "id": "P", "name": "P", "futurePartKey": 3 } ] }""")) + assertEquals(800f, model.puppet!!.canvasWidth) + assertEquals(listOf(UmaPart("P", "P")), model.puppet!!.parts) + assertEquals(JsonPrimitive(3), elementOf(model.liveContent(UmaEntryKind.Puppet)!!, "parts", "id", "P")!!["futurePartKey"]) + } + + /** + * A part and a drawable may share a raw id, since org references are identified by kind. + */ + @Test + fun kindsKeepSharedRawIdsApart() { + val model = Uma.read(fileWithPuppet("""{ "rootChildren": [ { "part": "Head" }, { "drawable": "Head" } ] }""")) + assertEquals(listOf(UmaOrgRef(part = "Head"), UmaOrgRef(drawable = "Head")), model.puppet!!.rootChildren) + } + + /** + * A non-finite float refuses the save rather than writing something JSON cannot hold. + */ + @Test + fun nonFiniteValuesRefuseTheSave() { + assertFailsWith { UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(canvasWidth = Float.NaN)) } + assertFailsWith { UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(drawables = listOf(UmaDrawable("D", "D", opacity = Float.POSITIVE_INFINITY)))) } + } + + /** + * Floats survive a save bit for bit, including the ones a decimal round trip is most likely to bend. + */ + @Test + fun floatsRoundTripBitExact() { + val values = listOf(-0.0f, 0.0f, Float.MIN_VALUE, 1.4e-44f, 0.1f, 1f / 3f, 16777217f, Float.MAX_VALUE, -Float.MAX_VALUE) + val puppet = UmaPuppet(parameters = values.mapIndexed { valueIndex, value -> UmaParameter("P$valueIndex", "P", value, value, value) }) + val decoded = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(puppet))).puppet!!.parameters!! + for ((valueIndex, value) in values.withIndex()) { + assertEquals(value.toRawBits(), decoded[valueIndex].default.toRawBits(), "$value survives bit for bit") + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetShapeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetShapeTest.kt new file mode 100644 index 0000000..629490a --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetShapeTest.kt @@ -0,0 +1,216 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.TestEntry +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.manifestJson +import org.umamo.format.uma.recordJson +import org.umamo.format.uma.umaArchiveOf +import kotlin.test.Test +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the puppet entry's shape rules (docs/format/UMA.md §4.8): each shape the flat schema allows but the model does + * not is named by its path, refused by a save, and refused by a read, so a document Umamo saves always reopens. + */ +class UmaPuppetShapeTest { + private val positions = floatArrayOf(0f, 0f, 10f, 0f, 10f, 10f) + private val mesh = UmaMesh(positions, positions.copyOf(), intArrayOf(0, 1, 2)) + private val axis = UmaAxis("P0", listOf(0f, 1f)) + private val warp = UmaDeformer("W", UmaDeformerKind.Warp, "W", rows = 1, columns = 1, isQuadTransform = true) + private val rotation = UmaDeformer("R", UmaDeformerKind.Rotation, "R", baseAngle = 0f) + + /** + * Asserts that [puppet] breaks a shape rule the problem names at [where], and that a save refuses it. + * + * @param UmaPuppet puppet The puppet. + * @param String where A fragment of the path the problem must name. + */ + private fun assertRefused(puppet: UmaPuppet, where: String) { + val problem = assertNotNull(UmaPuppetShape.firstProblem(puppet), where) + assertTrue(problem.contains(where), "'$problem' names $where") + val failure = assertFailsWith(where) { UmaModel.create(TEST_WRITER).withPuppet(puppet) } + assertTrue(failure.detail.contains(where), "the save's refusal '${failure.detail}' names $where") + } + + /** + * A puppet holding one drawable. + * + * @param UmaDrawable drawable The drawable. + * @return UmaPuppet The puppet. + */ + private fun withDrawable(drawable: UmaDrawable): UmaPuppet = UmaPuppet(drawables = listOf(drawable)) + + /** + * The shapes a valid puppet holds pass, so the refusals below are the rules and not noise. + */ + @Test + fun soundShapesPass() { + assertNull(UmaPuppetShape.firstProblem(samplePuppet())) + val geometry = + UmaPuppet( + deformers = + listOf( + warp.copy(geometry = UmaDeformerGrid(listOf(axis), listOf(UmaDeformerCell(listOf(0), controlPoints = FloatArray(8))))), + rotation.copy(geometry = UmaDeformerGrid(listOf(axis), listOf(UmaDeformerCell(listOf(1), originX = 0f, originY = 0f, angle = 0f, scale = 1f)))), + ), + drawables = + listOf( + UmaDrawable( + "D", + "D", + mesh = mesh, + geometry = UmaMeshGrid(listOf(UmaAxis("P0", listOf(0f, 0f, 1f))), listOf(UmaMeshCell(listOf(2), FloatArray(6)))), + channels = mapOf(UmaFormChannel.MultiplyColor to UmaChannelGrid(emptyList(), listOf(UmaChannelCell(emptyList(), JsonArray(listOf(JsonPrimitive(1), JsonPrimitive(0.5), JsonPrimitive(0))))))), + ), + ), + ) + assertNull(UmaPuppetShape.firstProblem(geometry), "a repeated key, a zero-axis track, and whole forms") + } + + /** + * Each structural shape the model cannot hold is refused. + */ + @Test + fun impossibleStructureIsRefused() { + assertRefused(UmaPuppet(rootChildren = listOf(UmaOrgRef())), "rootChildren[0]") + assertRefused(UmaPuppet(rootChildren = listOf(UmaOrgRef(part = "P", drawable = "D"))), "rootChildren[0]") + assertRefused(UmaPuppet(parts = listOf(UmaPart("P", "P", children = listOf(UmaOrgRef())))), "parts[P].children[0]") + assertRefused(UmaPuppet(parameterTree = listOf(UmaParameterNode(parameter = "P", group = "G"))), "parameterTree[0]") + assertRefused(UmaPuppet(parameterTree = listOf(UmaParameterNode(group = "G"))), "parameterTree[0] is a group without a name") + assertRefused(UmaPuppet(parameterTree = listOf(UmaParameterNode(parameter = "P", name = "P"))), "parameterTree[0] is a parameter leaf") + assertRefused(UmaPuppet(parameterTree = listOf(UmaParameterNode(group = "G", name = "G", children = listOf(UmaParameterNode())))), "parameterTree[0].children[0]") + assertRefused(UmaPuppet(deformers = listOf(UmaDeformer("W", UmaDeformerKind.Warp, "W", columns = 2, isQuadTransform = true))), "deformers[W] is a warp without rows") + assertRefused(UmaPuppet(deformers = listOf(UmaDeformer("W", UmaDeformerKind.Warp, "W", rows = 2, columns = 2))), "deformers[W] is a warp without isQuadTransform") + assertRefused(UmaPuppet(deformers = listOf(warp.copy(baseAngle = 1f))), "deformers[W] is a warp but carries rotation fields") + assertRefused(UmaPuppet(deformers = listOf(warp.copy(rows = -1))), "deformers[W] has a negative lattice size") + assertRefused(UmaPuppet(deformers = listOf(UmaDeformer("R", UmaDeformerKind.Rotation, "R"))), "deformers[R] is a rotation without baseAngle") + assertRefused(UmaPuppet(deformers = listOf(rotation.copy(rows = 2))), "deformers[R] is a rotation but carries warp fields") + assertRefused(withDrawable(UmaDrawable("D", "D", multiplyColor = listOf(1f, 1f))), "drawables[D].multiplyColor") + assertRefused(UmaPuppet(parts = listOf(UmaPart("P", "P", composite = UmaPartComposite(screenColor = listOf(0f))))), "parts[P].composite.screenColor") + } + + /** + * Each geometry invariant the renderer relies on is refused. + */ + @Test + fun brokenGeometryIsRefused() { + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = UmaMesh(floatArrayOf(0f, 0f, 1f), floatArrayOf(0f, 0f, 1f), intArrayOf()))), "drawables[D].mesh.positions") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = UmaMesh(positions, floatArrayOf(0f, 0f), intArrayOf(0, 1, 2)))), "drawables[D].mesh.uvs") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = UmaMesh(positions, positions.copyOf(), intArrayOf(0, 1)))), "drawables[D].mesh.indices") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = UmaMesh(positions, positions.copyOf(), intArrayOf(0, 1, 3)))), "drawables[D].mesh.indices[2]") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, geometry = UmaMeshGrid(listOf(axis), listOf(UmaMeshCell(listOf(0), FloatArray(4)))))), "drawables[D].geometry.cells[0].positionDeltas") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, geometry = UmaMeshGrid(listOf(axis), listOf(UmaMeshCell(listOf(2), FloatArray(6)))))), "drawables[D].geometry.cells[0].coordinate[0]") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, geometry = UmaMeshGrid(listOf(axis), listOf(UmaMeshCell(listOf(0, 0), FloatArray(6)))))), "drawables[D].geometry.cells[0].coordinate") + assertRefused( + withDrawable(UmaDrawable("D", "D", channels = mapOf(UmaFormChannel.Opacity to UmaChannelGrid(listOf(axis), listOf(UmaChannelCell(listOf(0), JsonPrimitive(true))))))), + "drawables[D].channels.opacity.cells[0].value", + ) + assertRefused( + withDrawable(UmaDrawable("D", "D", channels = mapOf(UmaFormChannel.FlipX to UmaChannelGrid(listOf(axis), listOf(UmaChannelCell(listOf(0), JsonPrimitive(1))))))), + "drawables[D].channels.flipX.cells[0].value", + ) + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, blendShapes = listOf(UmaMeshBlendShape("P1", listOf(0f, 1f), 0, listOf(null))))), "drawables[D].blendShapes[0]") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, blendShapes = listOf(UmaMeshBlendShape("P1", listOf(0f, 1f), 2, listOf(null, UmaMeshForm(FloatArray(6))))))), "drawables[D].blendShapes[0].neutralIndex") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, geometry = UmaMeshGrid(listOf(UmaAxis("P0", listOf(1f, 0f))), listOf(UmaMeshCell(listOf(0), FloatArray(6)))))), "drawables[D].geometry.axes[0].keys[1]") + assertRefused(withDrawable(UmaDrawable("D", "D", mesh = mesh, blendShapes = listOf(UmaMeshBlendShape("P1", listOf(1f, 0f), 0, listOf(null, UmaMeshForm(FloatArray(6))))))), "drawables[D].blendShapes[0].keys[1]") + val descendingLimit = UmaBlendLimit("P0", listOf(UmaBlendLimitPoint(1f, 1f), UmaBlendLimitPoint(0f, 0f))) + assertRefused( + withDrawable(UmaDrawable("D", "D", mesh = mesh, blendShapes = listOf(UmaMeshBlendShape("P1", listOf(0f, 1f), 0, listOf(null, UmaMeshForm(FloatArray(6))), listOf(descendingLimit))))), + "drawables[D].blendShapes[0].limits[0].points[1]", + ) + + assertRefused(UmaPuppet(deformers = listOf(warp.copy(geometry = UmaDeformerGrid(listOf(axis), listOf(UmaDeformerCell(listOf(0), controlPoints = FloatArray(6))))))), "deformers[W].geometry.cells[0].controlPoints") + assertRefused(UmaPuppet(deformers = listOf(warp.copy(geometry = UmaDeformerGrid(listOf(axis), listOf(UmaDeformerCell(listOf(0), controlPoints = FloatArray(8), angle = 1f)))))), "deformers[W].geometry.cells[0]") + // 65536 x 65536 x 2 floats wraps to zero in 32 bits, which an empty lattice would then match. + val hugeWarp = warp.copy(rows = 65535, columns = 65535, geometry = UmaDeformerGrid(listOf(axis), listOf(UmaDeformerCell(listOf(0), controlPoints = FloatArray(0))))) + assertRefused(UmaPuppet(deformers = listOf(hugeWarp)), "deformers[W] has a 65535 x 65535 lattice") + assertRefused( + UmaPuppet(deformers = listOf(warp.copy(blendShapes = listOf(UmaDeformerBlendShape("P1", listOf(0f, 1f), 0, listOf(null, UmaDeformerForm(controlPoints = FloatArray(8), flipX = true))))))), + "deformers[W].blendShapes[0].forms[1]", + ) + assertRefused(UmaPuppet(deformers = listOf(rotation.copy(geometry = UmaDeformerGrid(listOf(axis), listOf(UmaDeformerCell(listOf(0), originX = 0f, originY = 0f, angle = 0f)))))), "deformers[R].geometry.cells[0]") + assertRefused( + UmaPuppet(deformers = listOf(rotation.copy(blendShapes = listOf(UmaDeformerBlendShape("P1", listOf(0f, 1f), 0, listOf(null, UmaDeformerForm(controlPoints = FloatArray(8)))))))), + "deformers[R].blendShapes[0].forms[1] belongs to a rotation but carries controlPoints", + ) + + val glueMeshes = listOf(UmaDrawable("A", "A", mesh = mesh), UmaDrawable("B", "B", mesh = mesh)) + assertRefused(UmaPuppet(drawables = glueMeshes, glues = listOf(UmaGlue("A", "B", UmaGluePairs(intArrayOf(0, 1), intArrayOf(0), FloatArray(2), FloatArray(2))))), "glues[A,B].pairs") + assertRefused(UmaPuppet(drawables = glueMeshes, glues = listOf(UmaGlue("A", "B", UmaGluePairs(intArrayOf(0), intArrayOf(5), FloatArray(1), FloatArray(1))))), "glues[A,B].pairs.indicesB[0]") + } + + /** + * A save refuses a puppet that repeats an identity a reader would refuse, not only a broken shape. + */ + @Test + fun repeatedIdentitiesRefuseTheSave() { + val glueMeshes = listOf(UmaDrawable("A", "A", mesh = mesh), UmaDrawable("B", "B", mesh = mesh)) + val pairs = UmaGluePairs(intArrayOf(0), intArrayOf(0), FloatArray(1), FloatArray(1)) + assertFailsWith("two glues on one mesh pair") { + UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(drawables = glueMeshes, glues = listOf(UmaGlue("A", "B", pairs), UmaGlue("A", "B", pairs)))) + } + assertFailsWith("a drawable listed twice in a part") { + UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(parts = listOf(UmaPart("P", "P", children = listOf(UmaOrgRef(drawable = "A"), UmaOrgRef(drawable = "A")))))) + } + assertFailsWith("two drawables with one id") { + UmaModel.create(TEST_WRITER).withPuppet(UmaPuppet(drawables = listOf(UmaDrawable("A", "A"), UmaDrawable("A", "Again")))) + } + } + + /** + * A file that breaks a shape rule fails the read with the rule's path, whether or not the rule involves a buffer. + */ + @Test + fun brokenShapesFailTheRead() { + /** + * The read failure of a file holding [puppetJson] and a buffer of [buffer]. + * + * @param String puppetJson The puppet entry's JSON text. + * @param ByteArray buffer The buffer entry's bytes. + * @return String The failure's detail. + */ + fun readFailure(puppetJson: String, buffer: ByteArray = ByteArray(0)): String { + val file = + umaArchiveOf( + manifestJson(listOf(recordJson("model/puppet.json", "puppet", required = true))), + listOf(TestEntry("model/puppet.json", puppetJson.encodeToByteArray()), TestEntry("model/buffers.bin", buffer, deflated = false)), + ) + val failure = assertFailsWith { Uma.read(file) }.failure + return assertIs(failure).detail + } + assertTrue(readFailure("""{ "rootChildren": [ {} ] }""").contains("rootChildren[0] must name exactly one")) + + // Six floats of positions and uvs, then the int32 indices 0, 1, and 3 of a three-vertex mesh. + val buffer = ByteArray(60) + for ((intIndex, value) in listOf(0, 1, 3).withIndex()) { + for (byteIndex in 0 until 4) { + buffer[48 + intIndex * 4 + byteIndex] = (value shr (8 * byteIndex)).toByte() + } + } + + /** + * An accessor into the test buffer. + * + * @param Int offset Where the run starts. + * @param Int count How many components. + * @param String componentType The component type. + * @return String The accessor's JSON text. + */ + fun accessor(offset: Int, count: Int, componentType: String): String = + """{ "buffer": "model/buffers.bin", "byteOffset": $offset, "byteLength": ${count * 4}, "count": $count, "componentType": "$componentType" }""" + val meshJson = """{ "positions": ${accessor(0, 6, "float32")}, "uvs": ${accessor(24, 6, "float32")}, "indices": ${accessor(48, 3, "int32")} }""" + val detail = readFailure("""{ "drawables": [ { "id": "D", "name": "D", "mesh": $meshJson } ] }""", buffer) + assertTrue(detail.contains("drawables[D].mesh.indices[2] is 3"), detail) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetTestSupport.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetTestSupport.kt new file mode 100644 index 0000000..7a2145d --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaPuppetTestSupport.kt @@ -0,0 +1,84 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/* + * Builders for the puppet entry tests: a small puppet that holds one of every object kind, and helpers that + * plant keys a newer writer might add into the JSON tree. + */ + +/** + * A puppet with at least one of every object kind the puppet entry holds, and a part and a drawable that + * share a raw id so kind-qualified identities are exercised. + * + * @return UmaPuppet The puppet. + */ +internal fun samplePuppet(): UmaPuppet = + UmaPuppet( + canvasWidth = 2400f, + canvasHeight = 3000f, + runtimeTarget = UmaRuntimeTarget.Cubism53, + parameters = + listOf( + UmaParameter("ParamA", "A", -30f, 30f, 0f), + UmaParameter("ParamB", "B", 0f, 1f, 0f, kind = UmaParameterKind.BlendShape), + ), + parameterLinks = listOf(UmaParameterLink("ParamA", "ParamB")), + parameterTree = + listOf( + UmaParameterNode(group = "Face", name = "Face", initiallyOpen = true, children = listOf(UmaParameterNode(parameter = "ParamA"), UmaParameterNode(parameter = "ParamB"))), + ), + rootPart = "Root", + rootChildren = listOf(UmaOrgRef(part = "Head"), UmaOrgRef(drawable = "Head")), + parts = + listOf( + UmaPart("Head", "Head", children = listOf(UmaOrgRef(drawable = "Eye")), isVisible = false, composite = UmaPartComposite(opacity = 0.5f)), + UmaPart("Body", "Body"), + ), + deformers = listOf(UmaDeformer("Warp1", UmaDeformerKind.Warp, "Warp", rows = 2, columns = 2, isQuadTransform = true)), + drawables = listOf(UmaDrawable("Eye", "Eye", maskedBy = listOf("Head")), UmaDrawable("Head", "Head face")), + ) + +/** + * [tree] with [key] set to [value], appended after its existing keys. + * + * @param JsonObject tree The object. + * @param String key The key. + * @param JsonElement value The value. + * @return JsonObject The object with the key. + */ +internal fun withKey(tree: JsonObject, key: String, value: JsonElement): JsonObject = JsonObject(LinkedHashMap(tree).also { map -> map[key] = value }) + +/** + * [tree] with the array at [key] rewritten element by element. + * + * @param JsonObject tree The object. + * @param String key The array's key. + * @param Function transform Rewrites one element given its index. + * @return JsonObject The object with the rewritten array. + */ +internal fun withArray(tree: JsonObject, key: String, transform: (Int, JsonObject) -> JsonObject): JsonObject = + withKey(tree, key, JsonArray((tree[key] as JsonArray).mapIndexed { elementIndex, element -> transform(elementIndex, element as JsonObject) })) + +/** + * A planted marker value, telling planted keys apart. + * + * @param String marker The marker. + * @return JsonObject The value. + */ +internal fun plantedValue(marker: String): JsonObject = JsonObject(mapOf("from" to JsonPrimitive("future"), "marker" to JsonPrimitive(marker))) + +/** + * The element of the array at [key] whose [identityKey] is [identityValue], or null. + * + * @param JsonObject tree The object holding the array. + * @param String key The array's key. + * @param String identityKey The key naming each element. + * @param String identityValue The element's value for it. + * @return JsonObject? The element. + */ +internal fun elementOf(tree: JsonObject, key: String, identityKey: String, identityValue: String): JsonObject? = + (tree[key] as? JsonArray)?.map { element -> element as JsonObject }?.firstOrNull { element -> (element[identityKey] as? JsonPrimitive)?.content == identityValue } \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaTreeMergeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaTreeMergeTest.kt new file mode 100644 index 0000000..f05acfc --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/puppet/UmaTreeMergeTest.kt @@ -0,0 +1,128 @@ +package org.umamo.format.uma.puppet + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaModel +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Pins the retained-tree merge on the puppet entry (docs/format/UMA.md §4.7): keys a newer writer adds + * to any object kind survive an older writer's edits and saves, travel with their object's identity rather + * than its position, and leave only with the object they belong to. + */ +class UmaTreeMergeTest { + /** + * A saved sample puppet whose tree has had a newer writer's keys planted in every object kind, read back. + * + * @return UmaModel The document as an older writer opens it. + */ + private fun plantedDocument(): UmaModel { + val saved = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(samplePuppet()))) + var tree = saved.liveContent(UmaEntryKind.Puppet)!! + tree = withKey(tree, "futureRoot", plantedValue("root")) + tree = withArray(tree, "parameters") { _, parameter -> withKey(parameter, "futureParameter", plantedValue((parameter["id"] as JsonPrimitive).content)) } + tree = withArray(tree, "parameterLinks") { _, link -> withKey(link, "futureLink", plantedValue("link")) } + tree = + withArray(tree, "parameterTree") { _, group -> + withArray(withKey(group, "futureGroup", plantedValue("group")), "children") { _, leaf -> + withKey(leaf, "futureLeaf", plantedValue((leaf["parameter"] as JsonPrimitive).content)) + } + } + tree = withArray(tree, "rootChildren") { childIndex, reference -> if (childIndex == 0) withKey(reference, "futureReference", plantedValue("part:Head")) else reference } + tree = + withArray(tree, "parts") { _, part -> + if ((part["id"] as JsonPrimitive).content != "Head") { + part + } else { + val composite = withKey(part["composite"] as JsonObject, "futureComposite", plantedValue("composite")) + withArray(withKey(withKey(part, "futurePart", plantedValue("Head")), "composite", composite), "children") { _, child -> withKey(child, "futureChild", plantedValue("Eye")) } + } + } + tree = withArray(tree, "deformers") { _, deformer -> withKey(deformer, "futureDeformer", plantedValue("Warp1")) } + tree = withArray(tree, "drawables") { _, drawable -> withKey(drawable, "futureDrawable", plantedValue((drawable["id"] as JsonPrimitive).content)) } + return Uma.read(Uma.write(saved.withLiveContent(UmaEntryKind.Puppet, tree))) + } + + /** + * Planted keys ride through a rename, a delete-and-shift, a reorder, and a reset to default: each stays + * with its object, leaves with a deleted one, and lands after the known keys. + */ + @Test + fun unknownKeysSurviveEditsByIdentity() { + val document = plantedDocument() + val puppet = assertNotNull(document.puppet, "planted keys do not stop the entry decoding") + val edited = + puppet.copy( + // Delete ParamA everywhere it appears, shifting ParamB to the front. + parameters = puppet.parameters!!.filter { parameter -> parameter.id != "ParamA" }, + parameterLinks = null, + parameterTree = puppet.parameterTree!!.map { group -> group.copy(children = group.children!!.filter { leaf -> leaf.parameter != "ParamA" }) }, + // Reorder the parts, and reset Head's visibility and composite to their defaults. + parts = puppet.parts!!.reversed().map { part -> if (part.id == "Head") part.copy(isVisible = null, composite = null) else part }, + // Rename a drawable. + drawables = puppet.drawables!!.map { drawable -> if (drawable.id == "Eye") drawable.copy(name = "Eye L") else drawable }, + ) + val tree = Uma.read(Uma.write(document.withPuppet(edited))).liveContent(UmaEntryKind.Puppet)!! + + assertEquals(plantedValue("root"), tree["futureRoot"], "a root key survives") + assertEquals("futureRoot", tree.keys.last(), "and follows the known keys") + + assertNull(elementOf(tree, "parameters", "id", "ParamA"), "the deleted parameter is gone") + val parameterB = assertNotNull(elementOf(tree, "parameters", "id", "ParamB")) + assertEquals(plantedValue("ParamB"), parameterB["futureParameter"], "the shifted parameter keeps its own key, not its old neighbor's") + assertNull(tree["parameterLinks"], "the deleted link leaves with its key") + + val group = (tree["parameterTree"] as JsonArray).single() as JsonObject + assertEquals(plantedValue("group"), group["futureGroup"], "a group keeps its key") + val leaf = (group["children"] as JsonArray).single() as JsonObject + assertEquals(plantedValue("ParamB"), leaf["futureLeaf"], "the surviving leaf keeps its key") + + assertEquals(listOf("Body", "Head"), (tree["parts"] as JsonArray).map { part -> ((part as JsonObject)["id"] as JsonPrimitive).content }, "parts in the new order") + val head = assertNotNull(elementOf(tree, "parts", "id", "Head")) + assertEquals(plantedValue("Head"), head["futurePart"], "the moved part keeps its key") + assertNull(head["isVisible"], "a value reset to its default drops its key") + assertEquals(JsonObject(mapOf("futureComposite" to plantedValue("composite"))), head["composite"], "a composite reset to defaults keeps only its unknown key") + assertEquals(plantedValue("Eye"), ((head["children"] as JsonArray).single() as JsonObject)["futureChild"], "an org reference keeps its key") + + val rootChildren = (tree["rootChildren"] as JsonArray).map { reference -> reference as JsonObject } + assertEquals(plantedValue("part:Head"), rootChildren.first { reference -> reference.containsKey("part") }["futureReference"], "the part reference keeps its key") + assertNull(rootChildren.first { reference -> reference.containsKey("drawable") }["futureReference"], "and the drawable sharing its raw id does not take it") + + assertEquals(plantedValue("Warp1"), assertNotNull(elementOf(tree, "deformers", "id", "Warp1"))["futureDeformer"], "a deformer keeps its key") + val eye = assertNotNull(elementOf(tree, "drawables", "id", "Eye")) + assertEquals(JsonPrimitive("Eye L"), eye["name"], "the rename lands") + assertEquals(plantedValue("Eye"), eye["futureDrawable"], "and the renamed drawable keeps its key") + assertEquals("futureDrawable", eye.keys.last(), "after its known keys") + } + + /** + * A document with no unknown keys writes the same bytes whether it was created fresh or edited from a + * file with a different history. + */ + @Test + fun outputDoesNotDependOnHistory() { + val target = samplePuppet().copy(canvasWidth = 1024f, parts = samplePuppet().parts!!.reversed()) + val fresh = Uma.write(UmaModel.create(TEST_WRITER).withPuppet(target)) + val fromHistory = Uma.write(Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(samplePuppet()))).withPuppet(target)) + assertContentEquals(fresh, fromHistory) + } + + /** + * Arrays of values are replaced whole, since their elements have no identity to carry keys by. + */ + @Test + fun valueArraysAreReplacedWhole() { + val saved = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withPuppet(samplePuppet()))) + val edited = saved.puppet!!.let { puppet -> puppet.copy(drawables = puppet.drawables!!.map { drawable -> if (drawable.id == "Eye") drawable.copy(maskedBy = listOf("Body", "Head")) else drawable }) } + val tree = Uma.read(Uma.write(saved.withPuppet(edited))).liveContent(UmaEntryKind.Puppet)!! + assertEquals(JsonArray(listOf(JsonPrimitive("Body"), JsonPrimitive("Head"))), elementOf(tree, "drawables", "id", "Eye")!!["maskedBy"]) + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/sources/UmaSourcesEntryTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/sources/UmaSourcesEntryTest.kt new file mode 100644 index 0000000..1e5554c --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/sources/UmaSourcesEntryTest.kt @@ -0,0 +1,141 @@ +package org.umamo.format.uma.sources + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.TestEntry +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.manifestJson +import org.umamo.format.uma.puppet.elementOf +import org.umamo.format.uma.puppet.plantedValue +import org.umamo.format.uma.puppet.withArray +import org.umamo.format.uma.puppet.withKey +import org.umamo.format.uma.recordJson +import org.umamo.format.uma.umaArchiveOf +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Pins the sources entry (docs/format/UMA.md §6): every inventory field and flag round-trips, a hash is the one + * form this reader knows (UMA §6.4), keys a newer writer planted follow their source and layer across edits, and + * each rule a reader enforces fails with its path. + */ +class UmaSourcesEntryTest { + private val indexPath = "source/index.json" + + private val hash = "sha256:" + "0123456789abcdef".repeat(4) + + /** + * Sources using every field: a read file with a hash, a time, and a placement offset, a layer with every flag + * set, a plain layer, and a source that was never read. + * + * @return UmaSources The sources. + */ + private fun sampleSources(): UmaSources = + UmaSources( + listOf( + UmaSource( + id = "art-0", + name = "character.clip", + format = "clip", + path = "C:/work/character.clip", + contentHash = hash, + lastModified = 1_757_894_400_123L, + layers = + listOf( + UmaSourceLayer("uuid-1", "Eye L", "Head/Face", -12, 180, 220, 140, visible = false, present = false, contentHash = hash, empty = true, replaced = true, ignored = true), + UmaSourceLayer("name:Sketch#2", "Sketch", "", 0, 0, 2048, 2048, visible = true), + ), + offsetX = 64, + offsetZ = -32, + ), + UmaSource("guid-7", "Erica.psd", "psd"), + ), + ) + + /** + * Every field and flag survives a save. + */ + @Test + fun everyFieldRoundTrips() { + val reopened = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withSources(sampleSources()))) + assertEquals(sampleSources(), reopened.sources) + val entry = reopened.entries.single { candidate -> candidate.liveKind == UmaEntryKind.Sources } + assertEquals(false, entry.required, "the sources entry is optional") + } + + /** + * A key a newer writer put in a source and in a layer stays with them through a layer rename and the deletion + * of the source before it. + */ + @Test + fun keysSurviveByIdentity() { + val sources = UmaSources(listOf(UmaSource("gone", "gone.psd", "psd")) + sampleSources().sources!!) + val document = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withSources(sources))) + val tree = + withArray(document.liveContent(UmaEntryKind.Sources)!!, "sources") { sourceIndex, source -> + val planted = withKey(source, "futureSource", plantedValue("source $sourceIndex")) + if (source["layers"] == null) planted else withArray(planted, "layers") { layerIndex, layer -> withKey(layer, "futureLayer", plantedValue("layer $layerIndex")) } + } + val planted = Uma.read(Uma.write(document.withLiveContent(UmaEntryKind.Sources, tree))) + val kept = planted.sources!!.sources!!.drop(1) + val renamed = kept[0].copy(layers = kept[0].layers!!.map { layer -> if (layer.key == "uuid-1") layer.copy(name = "Eye Left") else layer }) + val saved = Uma.read(Uma.write(planted.withSources(UmaSources(listOf(renamed, kept[1]))))) + val savedTree = saved.liveContent(UmaEntryKind.Sources)!! + val source = assertNotNull(elementOf(savedTree, "sources", "id", "art-0")) + assertEquals(plantedValue("source 1"), source["futureSource"], "the source keeps its own key after the shift") + val layer = assertNotNull(elementOf(source, "layers", "key", "uuid-1")) + assertEquals(plantedValue("layer 0"), layer["futureLayer"], "the renamed layer keeps its key") + assertEquals(2, (savedTree["sources"] as JsonArray).size) + assertEquals(plantedValue("source 2"), ((savedTree["sources"] as JsonArray)[1] as JsonObject)["futureSource"]) + } + + /** + * Each rule a reader enforces fails the open as malformed, naming where; the same values refuse a save. + */ + @Test + fun brokenSourcesFail() { + /** + * Asserts reading a file whose sources entry is [json] fails as malformed, naming [where]. + * + * @param String json The entry's JSON text. + * @param String where A fragment the detail must hold. + */ + fun assertMalformed(json: String, where: String) { + val file = umaArchiveOf(manifestJson(listOf(recordJson(indexPath, "sources"))), listOf(TestEntry(indexPath, json.encodeToByteArray()))) + val failure = assertFailsWith(where) { Uma.read(file) }.failure + val detail = assertIs(failure, where).detail + assertTrue(detail.contains(where), "'$detail' names $where") + } + val layer = """{ "key": "k", "name": "n", "groupPath": "", "left": 0, "top": 0, "width": 1, "height": 1, "visible": true }""" + val digest = "0123456789abcdef".repeat(4) + assertMalformed("""{ "sources": [ { "id": "a", "name": "a", "format": "psd", "contentHash": "md5:$digest" } ] }""", "sources[0].contentHash") + assertMalformed("""{ "sources": [ { "id": "a", "name": "a", "format": "psd", "contentHash": "sha256:${digest.uppercase()}" } ] }""", "sources[0].contentHash") + assertMalformed("""{ "sources": [ { "id": "a", "name": "a", "format": "psd", "contentHash": "sha256:abc" } ] }""", "sources[0].contentHash") + assertMalformed("""{ "sources": [ { "id": "a", "name": "a", "format": "psd", "layers": [ ${layer.replace("\"width\": 1", "\"width\": -1")} ] } ] }""", "sources[0].layers[0]") + assertMalformed("""{ "sources": [ { "id": "a", "name": "a", "format": "psd" }, { "id": "a", "name": "b", "format": "psd" } ] }""", "sources[1]") + assertMalformed("""{ "sources": [ { "id": "a", "name": "a", "format": "psd", "layers": [ $layer, $layer ] } ] }""", "sources[0].layers[1]") + val file = umaArchiveOf(manifestJson(listOf(recordJson(indexPath, "sources"))), listOf(TestEntry(indexPath, """{ "sources": [ { "id": "a", "name": "a", "format": "psd", "layers": [ ${layer.replace(", \"visible\": true", "")} ] } ] }""".encodeToByteArray()))) + assertIs(assertFailsWith("a layer without visible") { Uma.read(file) }.failure) + + assertFailsWith("a save with a foreign hash") { + UmaModel.create(TEST_WRITER).withSources(UmaSources(listOf(UmaSource("a", "a", "psd", contentHash = "md5:$digest")))) + } + assertFailsWith("a save repeating a source id") { + UmaModel.create(TEST_WRITER).withSources(UmaSources(listOf(UmaSource("a", "a", "psd"), UmaSource("a", "b", "psd")))) + } + val plainLayer = UmaSourceLayer("k", "n", "", 0, 0, 1, 1, visible = true) + assertFailsWith("a save repeating a layer key within a source") { + UmaModel.create(TEST_WRITER).withSources(UmaSources(listOf(UmaSource("a", "a", "psd", layers = listOf(plainLayer, plainLayer))))) + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/uma/textures/UmaTexturesEntryTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/uma/textures/UmaTexturesEntryTest.kt new file mode 100644 index 0000000..4cec4c8 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/uma/textures/UmaTexturesEntryTest.kt @@ -0,0 +1,455 @@ +package org.umamo.format.uma.textures + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.format.binary.Crc32 +import org.umamo.format.binary.ZipArchive +import org.umamo.format.binary.ZipEntry +import org.umamo.format.binary.ZipRecords +import org.umamo.format.binary.ZipWriter +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.TEST_WRITER +import org.umamo.format.uma.TestEntry +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaContainer +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.manifestJson +import org.umamo.format.uma.puppet.plantedValue +import org.umamo.format.uma.puppet.withArray +import org.umamo.format.uma.puppet.withKey +import org.umamo.format.uma.recordJson +import org.umamo.format.uma.umaArchiveOf +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * Pins the textures entry (docs/format/UMA.md §5): every field round-trips, the layout assigns and keeps pixel + * paths, pixel entries the index stops naming leave the file while ones it never named stay (UMA §5.7), the render + * pages follow their mode (UMA §5.5), and each rule a reader enforces fails with its path. + */ +class UmaTexturesEntryTest { + private val indexPath = "textures/index.json" + + /** + * A PNG of one flat color. + * + * @param Int width The width. + * @param Int height The height. + * @param Int value The byte every channel takes, so images tell apart. + * @return ByteArray The PNG. + */ + private fun png(width: Int, height: Int, value: Int): ByteArray = PngCodec.write(RasterImage(width, height, ByteArray(width * height * 4) { value.toByte() })) + + /** + * An index using every field: a composition off the defaults, layer-addressed coordinates, a page, a placed + * and pinned tile with a binding, an unplaced tile with a lineage, and a bare tile. + * + * @return UmaTextures The index, without paths. + */ + private fun sampleTextures(): UmaTextures = + UmaTextures( + storedUvsAddressPages = false, + composition = UmaComposition(alphaThreshold = 8, extrude = 0), + pages = listOf(UmaPage(16, 16)), + tiles = + listOf( + UmaTile("art-0/lyid:1", "Eye", 4, 3, placement = UmaPlacement(0, 1.5f, -0.0f, -1f, 2f, 90f), source = UmaSourceRef("art-0", "lyid:1", true), pinned = true), + UmaTile("art-0/name:Mouth#2~1", "Mouth", 2, 2, source = UmaSourceRef("art-0", "name:Mouth#2", false), replaces = "art-0/name:Mouth#2"), + UmaTile("guid-3", "Hair", 5, 1), + ), + ) + + /** The PNG per tile of [sampleTextures], by id. */ + private val samplePngs: Map = + mapOf("art-0/lyid:1" to png(4, 3, 10), "art-0/name:Mouth#2~1" to png(2, 2, 20), "guid-3" to png(5, 1, 30)) + + /** + * A pixel source over [pngs]. + * + * @param Map pngs The PNG per tile id. + * @param UmaRenderPagePixels renderPages The render pages' mode. + * @param ByteArray? thumbnail The thumbnail's PNG. + * @return UmaPixelSource The source. + */ + private fun pixelsOf(pngs: Map, renderPages: UmaRenderPagePixels, thumbnail: ByteArray? = null): UmaPixelSource = UmaPixelSource({ id -> pngs[id] }, renderPages, thumbnail) + + /** + * A document holding [textures] saved and read back. + * + * @param UmaTextures textures The index. + * @param UmaPixelSource pixels The pixels. + * @return UmaModel The reopened document. + */ + private fun savedDocument(textures: UmaTextures, pixels: UmaPixelSource): UmaModel = Uma.read(Uma.write(UmaModel.create(TEST_WRITER).withTextures(textures, pixels))) + + /** + * [textures] without what the layout assigns - tile paths, render pages, and the thumbnail - for comparing + * against what a writer handed in. + * + * @param UmaTextures textures The index. + * @return UmaTextures The index as a writer hands it in. + */ + private fun withoutLayout(textures: UmaTextures): UmaTextures = textures.copy(tiles = textures.tiles?.map { tile -> tile.copy(path = null) }, renderPages = null, thumbnail = null) + + /** + * Every field survives a save, each pixel entry is stored and holds the bytes it was given, and an unedited + * reopen writes the same bytes. + */ + @Test + fun everyFieldRoundTrips() { + val pagePng = png(16, 16, 40) + val thumbnailPng = png(8, 6, 50) + val renderPages = UmaRenderPagePixels.Stored(listOf(pagePng), mapOf("ArtMesh1" to 0, "ArtMesh2" to 0)) + val bytes = Uma.write(UmaModel.create(TEST_WRITER).withTextures(sampleTextures(), pixelsOf(samplePngs, renderPages, thumbnailPng))) + val reopened = Uma.read(bytes) + val textures = assertNotNull(reopened.textures) + assertEquals(sampleTextures(), withoutLayout(textures)) + assertEquals(UmaThumbnail(8, 6, "thumbnail.png"), textures.thumbnail, "the thumbnail's size comes from its PNG") + assertEquals(UmaRenderPages(listOf(UmaRenderPage(16, 16, "textures/page-0.png")), mapOf("ArtMesh1" to 0, "ArtMesh2" to 0)), textures.renderPages) + assertEquals(listOf("textures/tile-0.png", "textures/tile-1.png", "textures/tile-2.png"), textures.tiles!!.map { tile -> tile.path }) + for (tile in textures.tiles) { + assertContentEquals(samplePngs.getValue(tile.id), reopened.payloadBytes(tile.path!!), "${tile.id}'s pixels") + } + assertContentEquals(pagePng, reopened.payloadBytes("textures/page-0.png")) + assertContentEquals(thumbnailPng, reopened.payloadBytes("thumbnail.png")) + + val archive = ZipArchive.read(bytes) + assertEquals( + listOf("mimetype", "manifest.json", indexPath, "textures/tile-0.png", "textures/tile-1.png", "textures/tile-2.png", "textures/page-0.png", "thumbnail.png"), + archive.entries.map { entry -> entry.name }, + "new pixel entries follow the index: tiles, render pages, thumbnail", + ) + for (entry in archive.entries.filter { entry -> entry.name.endsWith(".png") }) { + assertEquals(ZipRecords.METHOD_STORED, entry.method, "${entry.name} is stored") + } + assertContentEquals(bytes, Uma.write(reopened), "an unedited reopen rewrites byte for byte") + } + + /** + * A tile the file holds keeps its entry and is never asked for pixels; a new tile is minted a path past every + * one in use; a tile the index drops leaves the file; a payload no record ever named stays, and a minted path + * never lands on it. + */ + @Test + fun theLayoutKeepsMintsAndDrops() { + val index = """{ "tiles": [ { "id": "A", "name": "A", "width": 4, "height": 3, "path": "textures/tile-0.png" }, { "id": "B", "name": "B", "width": 2, "height": 2, "path": "textures/tile-1.png" } ] }""" + val foreign = png(1, 1, 99) + val file = + umaArchiveOf( + manifestJson(listOf(recordJson(indexPath, "textures", required = true))), + listOf( + TestEntry(indexPath, index.encodeToByteArray()), + TestEntry("textures/tile-0.png", png(4, 3, 1), deflated = false), + TestEntry("textures/tile-1.png", png(2, 2, 2), deflated = false), + TestEntry("textures/tile-5.png", foreign, deflated = false), + ), + ) + val document = Uma.read(file) + val kept = document.textures!!.tiles!![1] + val newPng = png(3, 3, 3) + val pixels = + UmaPixelSource( + { id -> + if (id != "C") { + fail("the pixels of $id, which the file holds, were asked for") + } + newPng + }, + UmaRenderPagePixels.Derived, + null, + ) + val saved = Uma.read(Uma.write(document.withTextures(UmaTextures(tiles = listOf(kept, UmaTile("C", "C", 3, 3))), pixels))) + val tiles = saved.textures!!.tiles!! + assertEquals(listOf("textures/tile-1.png", "textures/tile-6.png"), tiles.map { tile -> tile.path }, "B keeps its path; C is minted past the unnamed tile-5") + assertContentEquals(png(2, 2, 2), saved.payloadBytes("textures/tile-1.png"), "B's bytes are copied") + assertContentEquals(newPng, saved.payloadBytes("textures/tile-6.png")) + assertNull(saved.payloadBytes("textures/tile-0.png"), "A left the index, so its entry left the file") + assertContentEquals(foreign, saved.payloadBytes("textures/tile-5.png"), "a payload no record named stays") + } + + /** + * The render pages follow their mode: stored images are written with their map, kept ones keep their entries, + * derived pages store nothing and drop the entries a stored set left, and an image that is a tile this save + * writes shares the tile's entry. + */ + @Test + fun renderPagesFollowTheirMode() { + val pagePng = png(16, 16, 40) + val stored = savedDocument(UmaTextures(pages = listOf(UmaPage(16, 16))), pixelsOf(emptyMap(), UmaRenderPagePixels.Stored(listOf(pagePng), mapOf("D" to 0)))) + assertEquals(UmaRenderPages(listOf(UmaRenderPage(16, 16, "textures/page-0.png")), mapOf("D" to 0)), stored.textures!!.renderPages) + + val retained = Uma.read(Uma.write(stored.withTextures(UmaTextures(pages = listOf(UmaPage(16, 16))), pixelsOf(emptyMap(), UmaRenderPagePixels.Retained)))) + assertEquals(stored.textures!!.renderPages, retained.textures!!.renderPages, "kept render pages keep their entries and map") + assertContentEquals(pagePng, retained.payloadBytes("textures/page-0.png")) + assertFailsWith("keeping render pages the file does not hold") { + UmaModel.create(TEST_WRITER).withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Retained)) + } + + val derived = Uma.read(Uma.write(stored.withTextures(UmaTextures(pages = listOf(UmaPage(32, 32))), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived)))) + assertNull(derived.textures!!.renderPages, "derived pages store nothing") + assertEquals(listOf(UmaPage(32, 32)), derived.textures!!.pages, "and the atlas's page sizes are still recorded") + assertNull(derived.payloadBytes("textures/page-0.png"), "and the stored image's entry left the file") + + val shared = savedDocument(sampleTextures(), pixelsOf(samplePngs, UmaRenderPagePixels.Stored(listOf(samplePngs.getValue("guid-3"), pagePng), mapOf("D" to 0, "E" to 1)))) + val renderPages = shared.textures!!.renderPages!! + assertEquals("textures/tile-2.png", renderPages.pages[0].path, "an image that is a tile's PNG shares the tile's entry") + assertEquals("textures/page-0.png", renderPages.pages[1].path) + } + + /** + * A thumbnail is written when given and leaves with its entry when not, and a key a newer writer planted in it + * leaves too rather than making the file unreadable. + */ + @Test + fun theThumbnailComesAndGoes() { + val withThumbnail = savedDocument(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived, png(8, 8, 1))) + assertEquals(UmaThumbnail(8, 8, "thumbnail.png"), withThumbnail.textures!!.thumbnail) + val tree = withThumbnail.liveContent(UmaEntryKind.Textures)!! + val planted = Uma.read(Uma.write(withThumbnail.withLiveContent(UmaEntryKind.Textures, withKey(tree, "thumbnail", withKey(tree["thumbnail"] as JsonObject, "futureKey", plantedValue("thumbnail")))))) + + val without = Uma.read(Uma.write(planted.withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived)))) + assertNull(without.textures!!.thumbnail) + assertNull(without.liveContent(UmaEntryKind.Textures)!!["thumbnail"], "the dropped thumbnail's unknown keys leave with it") + assertNull(without.payloadBytes("thumbnail.png")) + } + + /** + * A thumbnail rewrites the entry the file's thumbnail already has, and a new one never lands on a `thumbnail.png` + * something else holds. + */ + @Test + fun theThumbnailNeverTakesAnotherEntry() { + val foreign = png(2, 2, 77) + val file = + umaArchiveOf( + manifestJson(listOf(recordJson(indexPath, "textures", required = true))), + listOf(TestEntry(indexPath, "{}".encodeToByteArray()), TestEntry("thumbnail.png", foreign, deflated = false)), + ) + val saved = Uma.read(Uma.write(Uma.read(file).withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived, png(8, 8, 1))))) + assertEquals(UmaThumbnail(8, 8, "thumbnail-0.png"), saved.textures!!.thumbnail, "the new thumbnail takes a free path") + assertContentEquals(foreign, saved.payloadBytes("thumbnail.png"), "the payload already there is untouched") + + val newThumbnail = png(4, 4, 2) + val resaved = Uma.read(Uma.write(saved.withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived, newThumbnail)))) + assertEquals(UmaThumbnail(4, 4, "thumbnail-0.png"), resaved.textures!!.thumbnail, "a later thumbnail rewrites its own entry") + assertContentEquals(newThumbnail, resaved.payloadBytes("thumbnail-0.png")) + assertContentEquals(foreign, resaved.payloadBytes("thumbnail.png")) + } + + /** + * Stored render pages whose images the file already holds name those entries, so saving the same pages again writes + * the same file; a changed image takes a new entry and the one it replaced leaves. + */ + @Test + fun storedRenderPagesReuseTheirEntries() { + val pagePngs = listOf(png(16, 16, 40), png(8, 8, 41)) + val stored = UmaRenderPagePixels.Stored(pagePngs, mapOf("D" to 0, "E" to 1)) + val first = Uma.write(UmaModel.create(TEST_WRITER).withTextures(UmaTextures(), pixelsOf(emptyMap(), stored))) + val reopened = Uma.read(first) + assertContentEquals(first, Uma.write(reopened.withTextures(UmaTextures(), pixelsOf(emptyMap(), stored))), "the same pages write the same file") + + val swapped = UmaRenderPagePixels.Stored(pagePngs.reversed(), mapOf("D" to 1, "E" to 0)) + val swappedPages = Uma.read(Uma.write(reopened.withTextures(UmaTextures(), pixelsOf(emptyMap(), swapped)))).textures!!.renderPages!! + assertEquals(listOf("textures/page-1.png", "textures/page-0.png"), swappedPages.pages.map { page -> page.path }, "reordered images keep their entries") + + val changedPng = png(8, 8, 42) + val changed = Uma.read(Uma.write(reopened.withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Stored(listOf(pagePngs[0], changedPng), mapOf("D" to 0, "E" to 1)))))) + assertEquals(listOf("textures/page-0.png", "textures/page-2.png"), changed.textures!!.renderPages!!.pages.map { page -> page.path }) + assertContentEquals(changedPng, changed.payloadBytes("textures/page-2.png")) + assertNull(changed.payloadBytes("textures/page-1.png"), "the replaced image's entry left the file") + } + + /** + * A document saved twice before it is written lays its new pixel entries out in index order - tiles, render pages, + * thumbnail - exactly as one save of the second index does, not in the order the saves wrote them. + */ + @Test + fun chainedSavesKeepIndexOrder() { + val first = sampleTextures().copy(tiles = sampleTextures().tiles!!.take(2)) + val thumbnailPng = png(8, 6, 50) + val once = UmaModel.create(TEST_WRITER).withTextures(first, pixelsOf(samplePngs, UmaRenderPagePixels.Derived, thumbnailPng)) + val twice = once.withTextures(sampleTextures(), pixelsOf(samplePngs, UmaRenderPagePixels.Derived, thumbnailPng)) + val names = ZipArchive.read(Uma.write(twice)).entries.map { entry -> entry.name } + assertEquals(listOf("mimetype", "manifest.json", indexPath, "textures/tile-0.png", "textures/tile-1.png", "textures/tile-2.png", "thumbnail.png"), names) + } + + /** + * A key a newer writer put in a tile stays with that tile through a rename and through the deletion of the tile + * before it. + */ + @Test + fun tileKeysSurviveByIdentity() { + val document = savedDocument(sampleTextures(), pixelsOf(samplePngs, UmaRenderPagePixels.Derived)) + val tree = withArray(document.liveContent(UmaEntryKind.Textures)!!, "tiles") { tileIndex, tile -> withKey(tile, "futureTile", plantedValue("tile $tileIndex")) } + val planted = Uma.read(Uma.write(document.withLiveContent(UmaEntryKind.Textures, tree))) + val tiles = planted.textures!!.tiles!! + val edited = planted.textures!!.copy(tiles = listOf(tiles[1].copy(name = "Mouth renamed"), tiles[2])) + val saved = Uma.read(Uma.write(planted.withTextures(edited, pixelsOf(emptyMap(), UmaRenderPagePixels.Derived)))) + val savedTiles = (saved.liveContent(UmaEntryKind.Textures)!!["tiles"] as JsonArray).map { tile -> tile as JsonObject } + assertEquals(JsonPrimitive("Mouth renamed"), savedTiles[0]["name"]) + assertEquals(plantedValue("tile 1"), savedTiles[0]["futureTile"], "the renamed tile keeps its own key after the shift") + assertEquals(plantedValue("tile 2"), savedTiles[1]["futureTile"]) + } + + /** + * A pixel entry another writer deflated reads by its header alone at open, and its whole PNG comes back verified; a + * deflated one whose header disagrees with its record still fails the open. + */ + @Test + fun deflatedPixelEntriesRead() { + val tilePng = png(4, 3, 1) + val index = """{ "tiles": [ { "id": "A", "name": "A", "width": 4, "height": 3, "path": "textures/tile-0.png" } ] }""" + + /** + * A file whose one tile's PNG is [png], deflated. + * + * @param ByteArray png The PNG. + * @return ByteArray The file. + */ + fun fileWith(png: ByteArray): ByteArray = + umaArchiveOf( + manifestJson(listOf(recordJson(indexPath, "textures", required = true))), + listOf(TestEntry(indexPath, index.encodeToByteArray()), TestEntry("textures/tile-0.png", png, deflated = true)), + ) + val document = Uma.read(fileWith(tilePng)) + assertEquals(4, document.textures!!.tiles!!.single().width) + assertContentEquals(tilePng, document.payloadBytes("textures/tile-0.png")) + assertIs(assertFailsWith { Uma.read(fileWith(png(3, 4, 1))) }.failure) + } + + /** + * A deflated pixel entry is probed from its first bytes alone, so a page-sized PNG is not copied through + * the heap to read its header - and a stream too sparse for that probe still opens, through the full + * inflate the probe falls back to. + */ + @Test + fun aSparseDeflatedPixelEntryStillReads() { + val tilePng = png(4, 3, 1) + val index = """{ "tiles": [ { "id": "A", "name": "A", "width": 4, "height": 3, "path": "textures/tile-0.png" } ] }""" + // A raw deflate stream (RFC 1951 §3.2.4): a thousand empty stored blocks of five bytes each - well past + // any bound a header probe hands the inflater - then one final stored block holding the PNG. Legal, + // and nothing the stream's first bytes can yield. + val emptyBlock = byteArrayOf(0x00, 0x00, 0x00, 0xFF.toByte(), 0xFF.toByte()) + val length = tilePng.size + val lengthComplement = length xor 0xFFFF + val finalHeader = byteArrayOf(0x01, (length and 0xFF).toByte(), (length ushr 8).toByte(), (lengthComplement and 0xFF).toByte(), (lengthComplement ushr 8).toByte()) + val stream = ByteArray(1000 * emptyBlock.size) { byteIndex -> emptyBlock[byteIndex % emptyBlock.size] } + finalHeader + tilePng + val writer = ZipWriter(ZipRecords.DOS_EPOCH_DATE_TIME) + writer.addStored(UmaContainer.MIMETYPE_PATH, UmaContainer.MIMETYPE.encodeToByteArray()) + writer.addDeflated(UmaContainer.MANIFEST_PATH, manifestJson(listOf(recordJson(indexPath, "textures", required = true))).encodeToByteArray()) + writer.addDeflated(indexPath, index.encodeToByteArray()) + writer.addRaw( + ZipEntry( + name = "textures/tile-0.png", + method = ZipRecords.METHOD_DEFLATED, + flags = 0, + crc32 = Crc32().also { checksum -> checksum.update(tilePng) }.value, + compressedSize = stream.size, + uncompressedSize = tilePng.size, + dosDateTime = ZipRecords.DOS_EPOCH_DATE_TIME, + payloadOffset = 0, + versionNeeded = ZipRecords.VERSION_DEFLATED, + ), + stream, + ) + + val document = Uma.read(writer.finish()) + + assertEquals(4, document.textures!!.tiles!!.single().width, "the probe fell back to the full inflate and read the header") + assertContentEquals(tilePng, document.payloadBytes("textures/tile-0.png")) + } + + /** + * Each rule a reader enforces fails the open with a typed reason naming where. + */ + @Test + fun brokenIndexesFail() { + /** + * The failure reading a file with [index] and [pixels] produces. + * + * @param String index The index's JSON text. + * @param Map pixels The pixel entries by path. + * @return UmaReadFailure The failure. + */ + fun failureOf(index: String, pixels: Map): UmaReadFailure { + val file = + umaArchiveOf( + manifestJson(listOf(recordJson(indexPath, "textures", required = true))), + listOf(TestEntry(indexPath, index.encodeToByteArray())) + pixels.map { (path, bytes) -> TestEntry(path, bytes, deflated = false) }, + ) + return assertFailsWith { Uma.read(file) }.failure + } + + /** + * Asserts a malformed failure whose detail names [where]. + * + * @param UmaReadFailure failure The failure. + * @param String where A fragment the detail must hold. + */ + fun assertMalformedAt(failure: UmaReadFailure, where: String) { + val detail = assertIs(failure, where).detail + assertTrue(detail.contains(where), "'$detail' names $where") + } + val tile = png(4, 3, 1) + + /** + * A 4 x 3 tile record's JSON text. + * + * @param String extra Further members, including a leading comma, or empty. + * @param String path The pixel entry's path. + * @return String The record. + */ + fun tileJson(extra: String = "", path: String = "textures/tile-0.png"): String = """{ "id": "A", "name": "A", "width": 4, "height": 3, "path": "$path"$extra }""" + + assertMalformedAt(failureOf("""{ "tiles": [ ${tileJson(""", "placement": { "page": 0, "positionX": 0, "positionY": 0, "scaleX": 1, "scaleY": 1, "rotationDegrees": 0 }""")} ] }""", mapOf("textures/tile-0.png" to tile)), "tiles[0].placement.page") + assertMalformedAt(failureOf("""{ "tiles": [ ${tileJson()} ] }""", mapOf("textures/tile-0.png" to png(3, 4, 1))), "tiles[0]") + assertMalformedAt(failureOf("""{ "tiles": [ ${tileJson()} ] }""", mapOf("textures/tile-0.png" to ByteArray(40))), "tiles[0]") + assertEquals(UmaReadFailure.MissingEntry("textures/tile-9.png"), failureOf("""{ "tiles": [ ${tileJson(path = "textures/tile-9.png")} ] }""", emptyMap())) + assertMalformedAt(failureOf("""{ "tiles": [ { "id": "A", "name": "A", "width": 4, "height": 3 } ] }""", emptyMap()), "tiles[0]") + assertMalformedAt(failureOf("""{ "tiles": [ ${tileJson()}, ${tileJson()} ] }""", mapOf("textures/tile-0.png" to tile)), "tiles[1]") + assertMalformedAt(failureOf("""{ "composition": { "alphaThreshold": 0 } }""", emptyMap()), "composition.alphaThreshold") + assertMalformedAt(failureOf("""{ "composition": { "extrude": -1 } }""", emptyMap()), "composition.extrude") + val renderPage = """{ "width": 16, "height": 16, "path": "textures/page-0.png" }""" + assertMalformedAt(failureOf("""{ "renderPages": { "pages": [ $renderPage ], "drawablePages": { "D": 1 } } }""", mapOf("textures/page-0.png" to png(16, 16, 1))), "renderPages.drawablePages.D") + assertMalformedAt(failureOf("""{ "renderPages": { "pages": [ $renderPage ] } }""", mapOf("textures/page-0.png" to png(8, 16, 1))), "renderPages.pages[0]") + assertIs(failureOf("""{ "renderPages": { "pages": [ { "width": 16, "height": 16 } ] } }""", emptyMap()), "a render page without a path") + assertIs(failureOf("""{ "pages": [ { "width": 1.5, "height": 16 } ] }""", emptyMap()), "a fractional size") + assertIs(failureOf("""{ "tiles": [ { "id": "A", "width": 4, "height": 3, "path": "textures/tile-0.png" } ] }""", mapOf("textures/tile-0.png" to tile)), "a tile without a name") + } + + /** + * A save refuses a new tile it has no pixels for or whose PNG is another size, a thumbnail that is not a PNG, a + * render page that is not one, and a repeated tile id. + */ + @Test + fun unwritableIndexesAreRefused() { + assertFailsWith("a tile without pixels") { + UmaModel.create(TEST_WRITER).withTextures(UmaTextures(tiles = listOf(UmaTile("A", "A", 4, 3))), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived)) + } + assertFailsWith("a tile whose PNG is another size") { + UmaModel.create(TEST_WRITER).withTextures(UmaTextures(tiles = listOf(UmaTile("A", "A", 4, 3))), pixelsOf(mapOf("A" to png(3, 3, 1)), UmaRenderPagePixels.Derived)) + } + assertFailsWith("a thumbnail that is not a PNG") { + UmaModel.create(TEST_WRITER).withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Derived, ByteArray(10))) + } + assertFailsWith("a render page that is not a PNG") { + UmaModel.create(TEST_WRITER).withTextures(UmaTextures(), pixelsOf(emptyMap(), UmaRenderPagePixels.Stored(listOf(ByteArray(10)), emptyMap()))) + } + assertFailsWith("a repeated tile id") { + UmaModel.create(TEST_WRITER).withTextures(UmaTextures(tiles = listOf(UmaTile("A", "A", 4, 3), UmaTile("A", "Again", 4, 3))), pixelsOf(mapOf("A" to png(4, 3, 1)), UmaRenderPagePixels.Derived)) + } + } +} \ No newline at end of file diff --git a/module/format/src/commonTest/kotlin/org/umamo/format/webp/WebpVp8lDecodeTest.kt b/module/format/src/commonTest/kotlin/org/umamo/format/webp/WebpVp8lDecodeTest.kt new file mode 100644 index 0000000..11ced12 --- /dev/null +++ b/module/format/src/commonTest/kotlin/org/umamo/format/webp/WebpVp8lDecodeTest.kt @@ -0,0 +1,93 @@ +package org.umamo.format.webp + +import kotlin.io.encoding.Base64 +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Validates [WebPReader]'s VP8L lossless decode against golden fixtures. Each fixture is a tiny VP8L + * `.webp` (encoded by libwebp via Pillow) plus the RGBA libwebp itself decodes it to; since VP8L is + * lossless, our decoder must reproduce those exact pixels. The fixtures span solid color, an RGB + * gradient (predictor / subtract-green), an alpha gradient, a four-color image (color-indexing), a + * larger image (LZ77 backward references), and a 64x64 image with two dissimilar halves (multiple + * Huffman meta-groups / color cache). Fixtures are embedded base64 so the test is self-contained. + */ +class WebpVp8lDecodeTest { + /** + * Decodes an embedded VP8L fixture and asserts it matches the embedded libwebp-golden RGBA. + * + * @param Int width Expected width. + * @param Int height Expected height. + * @param String webpBase64 Base64 of the `.webp` bytes. + * @param String rgbaBase64 Base64 of the golden RGBA8888 (top-first, straight alpha). + */ + private fun assertDecodes(width: Int, height: Int, webpBase64: String, rgbaBase64: String) { + val webp = Base64.decode(webpBase64) + val expected = Base64.decode(rgbaBase64) + val decoded = WebPReader.read(webp) + assertEquals(width, decoded.width, "width") + assertEquals(height, decoded.height, "height") + assertContentEquals(expected, decoded.rgba, "VP8L decode must match libwebp pixel-for-pixel") + } + + @Test + fun decodesSolid() { + assertDecodes( + width = 4, + height = 4, + webpBase64 = "UklGRh4AAABXRUJQVlA4TBEAAAAvA8AAAAdQsiJXpv+BiOh/AAA=", + rgbaBase64 = "yGQy/8hkMv/IZDL/yGQy/8hkMv/IZDL/yGQy/8hkMv/IZDL/yGQy/8hkMv/IZDL/yGQy/8hkMv/IZDL/yGQy/w==", + ) + } + + @Test + fun decodesGradient() { + assertDecodes( + width = 8, + height = 8, + webpBase64 = "UklGRiwAAABXRUJQVlA4TCAAAAAvB8ABALmM6H/sClGIgvc/ICQgTPF/p+bAgERMANjeAA==", + rgbaBase64 = "AAAA/yAAEP9AACD/YAAw/4AAQP+gAFD/wABg/+AAcP8AIBD/ICAg/0AgMP9gIED/gCBQ/6AgYP/AIHD/4CCA/wBAIP8gQDD/QEBA/2BAUP+AQGD/oEBw/8BAgP/gQJD/AGAw/yBgQP9AYFD/YGBg/4BgcP+gYID/wGCQ/+BgoP8AgED/IIBQ/0CAYP9ggHD/gICA/6CAkP/AgKD/4ICw/wCgUP8goGD/QKBw/2CggP+AoJD/oKCg/8CgsP/goMD/AMBg/yDAcP9AwID/YMCQ/4DAoP+gwLD/wMDA/+DA0P8A4HD/IOCA/0DgkP9g4KD/gOCw/6DgwP/A4ND/4ODg/w==", + ) + } + + @Test + fun decodesAlpha() { + assertDecodes( + width = 8, + height = 8, + webpBase64 = "UklGRjgAAABXRUJQVlA4TCwAAAAvB8ABELkyRPQ/dhHR/wBhtlEhzp92ryMQCCT5s+7w4AkEUtgmT4An9wD9Bw==", + rgbaBase64 = "/wB4AOsAeCDXAHhAwwB4YK8AeICbAHighwB4wHMAeOD/FHgA6xR4INcUeEDDFHhgrxR4gJsUeKCHFHjAcxR44P8oeADrKHgg1yh4QMMoeGCvKHiAmyh4oIcoeMBzKHjg/zx4AOs8eCDXPHhAwzx4YK88eICbPHighzx4wHM8eOD/UHgA61B4INdQeEDDUHhgr1B4gJtQeKCHUHjAc1B44P9keADrZHgg12R4QMNkeGCvZHiAm2R4oIdkeMBzZHjg/3h4AOt4eCDXeHhAw3h4YK94eICbeHigh3h4wHN4eOD/jHgA64x4INeMeEDDjHhgr4x4gJuMeKCHjHjAc4x44A==", + ) + } + + @Test + fun decodesFewcolors() { + assertDecodes( + width = 16, + height = 16, + webpBase64 = "UklGRkAAAABXRUJQVlA4TDQAAAAvD8ADAB8gECD4n3VgQyCQ5G87wQIBgv9ZB+Y/8MlRAWG20SQnOcn7HUNE/yPZl/VZ/iUf", + rgbaBase64 = "/wAA//8AAP//AAD//wAA/wD/AP8A/wD/AP8A/wD/AP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8A/wD/AP8A/wD/AP8A/wD/AAD//wAA//8AAP//AAD///Dw8P/w8PD/8PDw//Dw8P//AAD//wAA//8AAP//AAD/AP8A/wD/AP8A/wD/AP8A/wAA//8AAP//AAD//wAA///w8PD/8PDw//Dw8P/w8PD//wAA//8AAP//AAD//wAA/wD/AP8A/wD/AP8A/wD/AP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw/wD/AP8A/wD/AP8A/wD/AP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8A/wD/AP8A/wD/AP8A/wD/AAD//wAA//8AAP//AAD///Dw8P/w8PD/8PDw//Dw8P//AAD//wAA//8AAP//AAD/AP8A/wD/AP8A/wD/AP8A/wAA//8AAP//AAD//wAA///w8PD/8PDw//Dw8P/w8PD//wAA//8AAP//AAD//wAA/wD/AP8A/wD/AP8A/wD/AP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8A/wD/AP8A/wD/AP8A/wD/AAD//wAA//8AAP//AAD///Dw8P/w8PD/8PDw//Dw8P//AAD//wAA//8AAP//AAD/AP8A/wD/AP8A/wD/AP8A/wAA//8AAP//AAD//wAA///w8PD/8PDw//Dw8P/w8PD//wAA//8AAP//AAD//wAA/wD/AP8A/wD/AP8A/wD/AP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8A/wD/AP8A/wD/AP8A/wD/8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8A/wD/AP8A/wD/AP8A/wD/AAD//wAA//8AAP//AAD///Dw8P/w8PD/8PDw//Dw8P//AAD//wAA//8AAP//AAD/AP8A/wD/AP8A/wD/AP8A/wAA//8AAP//AAD//wAA///w8PD/8PDw//Dw8P/w8PD//wAA//8AAP//AAD//wAA/wD/AP8A/wD/AP8A/wD/AP8AAP//AAD//wAA//8AAP//8PDw//Dw8P/w8PD/8PDw//8AAP//AAD//wAA//8AAP8A/wD/AP8A/wD/AP8A/wD/AAD//wAA//8AAP//AAD//w==", + ) + } + + @Test + fun decodesLarger() { + assertDecodes( + width = 20, + height = 20, + webpBase64 = "UklGRlIAAABXRUJQVlA4TEYAAAAvE8AEELkyRPQ/BmLBZP7Q3SHUP/ofwTOgadtIJnD8IX/GH6tZUNS2DRxU3m03BNfwT8BkeQjKL4AUNEbBW7E3Gi9AGGAb", + rgbaBase64 = "AAAA/wsAAPsWAAD3IQAA8ywAAO83AADrQgAA500AAONYAADfYwAA224AANd5AADThAAAz48AAMuaAADHpQAAw7AAAL+7AAC7xgAAt9EAALMADQD7Cw0B9xYNAvMhDQPvLA0E6zcNBedCDQbjTQ0H31gNCNtjDQnXbg0K03kNC8+EDQzLjw0Nx5oNDsOlDQ+/sA0Qu7sNEbfGDRKz0Q0TrwAaAPcLGgLzFhoE7yEaBussGgjnNxoK40IaDN9NGg7bWBoQ12MaEtNuGhTPeRoWy4QaGMePGhrDmhocv6UaHruwGiC3uxois8YaJK/RGiarACcA8wsnA+8WJwbrIScJ5ywnDOM3Jw/fQicS200nFddYJxjTYycbz24nHst5JyHHhCckw48nJ7+aJyq7pSctt7AnMLO7JzOvxic2q9EnOacANADvCzQE6xY0COchNAzjLDQQ3zc0FNtCNBjXTTQc01g0IM9jNCTLbjQox3k0LMOENDC/jzQ0u5o0OLelNDyzsDRAr7s0RKvGNEin0TRMowBBAOsLQQXnFkEK4yFBD98sQRTbN0EZ10JBHtNNQSPPWEEoy2NBLcduQTLDeUE3v4RBPLuPQUG3mkFGs6VBS6+wQVCru0FVp8ZBWqPRQV+fAE4A5wtOBuMWTgzfIU4S2yxOGNc3Th7TQk4kz01OKstYTjDHY042w25OPL95TkK7hE5It49OTrOaTlSvpU5aq7BOYKe7Tmajxk5sn9FOcpsAWwDjC1sH3xZbDtshWxXXLFsc0zdbI89CWyrLTVsxx1hbOMNjWz+/bltGu3lbTbeEW1Szj1tbr5pbYqulW2mnsFtwo7tbd5/GW36b0VuFlwBoAN8LaAjbFmgQ1yFoGNMsaCDPN2goy0JoMMdNaDjDWGhAv2NoSLtuaFC3eWhYs4RoYK+PaGirmmhwp6VoeKOwaICfu2iIm8ZokJfRaJiTAHUA2wt1CdcWdRLTIXUbzyx1JMs3dS3HQnU2w011P79YdUi7Y3VRt251WrN5dWOvhHVsq491daeadX6jpXWHn7B1kJu7dZmXxnWik9F1q48AggDXC4IK0xaCFM8hgh7LLIIoxzeCMsNCgjy/TYJGu1iCULdjglqzboJkr3mCbquEgninj4KCo5qCjJ+lgpabsIKgl7uCqpPGgrSP0YK+iwCPANMLjwvPFo8WyyGPIccsjyzDN483v0KPQrtNj023WI9Ys2OPY69uj26reY95p4SPhKOPj4+fmo+am6WPpZewj7CTu4+7j8aPxovRj9GHAJwAzwucDMsWnBjHIZwkwyycML83nDy7QpxIt02cVLNYnGCvY5xsq26ceKd5nISjhJyQn4+cnJuanKiXpZy0k7CcwI+7nMyLxpzYh9Gc5IMAqQDLC6kNxxapGsMhqSe/LKk0uzepQbdCqU6zTalbr1ipaKtjqXWnbqmCo3mpj5+EqZybj6mpl5qptpOlqcOPsKnQi7up3YfGqeqD0an3fwC2AMcLtg7DFrYcvyG2Krsstji3N7ZGs0K2VK9NtmKrWLZwp2O2fqNutoyfebaam4S2qJePtraTmrbEj6W20ouwtuCHu7bug8a2/H/Rtgp7AMMAwwvDD78Wwx67IcMttyzDPLM3w0uvQsNaq03DaadYw3ijY8OHn27Dlpt5w6WXhMO0k4/Dw4+aw9KLpcPhh7DD8IO7w/9/xsMOe9HDHXcA0AC/C9AQuxbQILch0DCzLNBArzfQUKtC0GCnTdBwo1jQgJ9j0JCbbtCgl3nQsJOE0MCPj9DQi5rQ4Iel0PCDsNAAf7vQEHvG0CB30dAwcwDdALsL3RG3Ft0isyHdM68s3USrN91Vp0LdZqNN3XefWN2Im2PdmZdu3aqTed27j4TdzIuP3d2Hmt3ug6Xd/3+w3RB7u90hd8bdMnPR3UNvAOoAtwvqErMW6iSvIeo2qyzqSKc36lqjQupsn03qfptY6pCXY+qik27qtI956saLhOrYh4/q6oOa6vx/peoOe7DqIHe76jJzxupEb9HqVmsA9wCzC/cTrxb3Jqsh9zmnLPdMozf3X59C93KbTfeFl1j3mJNj96uPbve+i3n30YeE9+SDj/f3f5r3Cnul9x13sPcwc7v3Q2/G91Zr0fdpZw==", + ) + } + + @Test + fun decodesComplex() { + assertDecodes( + width = 64, + height = 64, + webpBase64 = "UklGRgoJAABXRUJQVlA4TP4IAAAvP8APAJkViOh/6IBI26b+fS+HpwMx4P0nmKSptmOIZVG8d5KC2rZtGOn/s522ZY2ICeBcFXSW/4Aibf/iJqgyUQxlRvmdJLJTtbMqx+lElUnmED0DMzOjyqwsvAu+zICgbdsGt/8EzOFxGEm2adXW1gT23rdt27ai+YkG0bRN5qp2h6UFABRX0ljCahh5hGYIRRGaotZCr7vryd2aJoRm3XdPetKT746GJoTQ6/65n97p868ZLYomFEVYmsfIY/QxEvga8hPaXRrhRgGYMKLIzUWCc5HgfIhkLhKciwTnI4hzEfH9F0dwePA90w39vwpURMVUQqVURuVUQZVURdVUQ7VUR/XUQI3URM3UQq3URu3UQZ3URd3UQ73UR/1Cz1glXVKUNumaIrRNZfrfJItitE1lStAhWfR8TEH6+ghTjo4pSK9PLzn6jBC3zM2c4U3e5lWu5RxX8i7P82MjV/PbIv/8fdfz8yqv89vnjT9cN3rQCQPTKGAcOZSwiedJNKIXCRSwjDxKqEcRhzCxiE6MohJ5bKMLRbSDo//OX/yzf2L+PfSH/3ryL4K5DpxyjA94qAc/5EM/wKEd7MhLfAwOJ1wmg57qaZwWyaQneNg+NuTLzemGmf3m30Y0V5tVZmoOG8Ngc71ZMJaxeJZbOcgJPuUJXmTJnGraZtksGtNcaJrGhjz+wI/64R/5M2Ptwz5+MOO4WIaBr3qMYxEmvuDH9uHo2TnFk52+eZbohGc2OeN6rgOn2E+tZFW71T5jdQvsd5bZzLDYDqxgU2rvsxGy661lH7PESnZsoU24le1627UchbOgDQw4mCACAAhT2Ak1hg4EBPIiReC5Ewhi24eDbtmtcsztd03H3YoLmTvqWo67FSc4y2Utt+QazilPdsAtOT9PMuDqilPO4Sme6knP3jk60amd5tk/2QnPuQ4ctchCyyy3xGILrJ9Tm1dF5cS5j2zleI5v+3AKbIRzQIWt8AKMAMB3MIVHwAAMQ1iAZ4DCQ/AVIFgPu6EPBCT4AtpwH3DowcfQBY465KBjjjvisAMu9ys/DMKk8vM6TNIkt3045Rpe4qVe9Opdowtd2mVe/Ytd8JrrwFF/sV/lmd/v/+6xv9qv8swf9YbHPhK85R3DS77hI8sveuLjDPplH1aX+qbnFPwC26gixx6OEKCGU3wEGWIcoogyUnwCNyNCHU3sI0GItg9HQytIgYWtwQo4gFC5pRECTwhFmUsBBSEUPJAghRKGPImE0A0eyMhDzzz3xGMPvJtSnxZ5UYWpi3xROZVr+3AQD+LpyHA/rsEJruAqzA5jCzkexwW08Ciuw1+wgQLuxpMQ4BKeim1cxpOxg3uxiZwSxgEGNfAgBz2AoAUWaheHQQhSGtQQoaAHEh4LEQy2D0e/na/4ZV/H/KboC7/R5BsUcx04JX4apajGrfGZqEcQv4ssRkbEcRCF+Eyk8b74XURxfbTiY5FEKY4jjPdFHuW4PnYjR9NZqZ1Y4slMYgIJpmnamXKcOsklKU4jlCozTZLj2z6cQr+iVaTSfrqNdLqa3idGb5JBmP5EAj1DR+k++o4atJ4supUISfQWQXqFFkmm31CTPJDHEUY18ijHBEQtshjFM85qGtVYopiQ+FgsYbR9bMjr0jmJpa1pdxITSFKasZFmvJCsFG9P5ySUhLQ7zVhKMzbSjPNusiGPCZJKnGTSCZBGjKoa04C8mJJKASKdCD1GASTbh6N35xZvdlfmHaMb3sHk9rK5DhzMy3lVZnl/bmaeV3LC8tHcyjyvZCFbuWzlpdzIvntyBnkpN3KVlyB7zcwp/AW3WWXOPR4xYI2n/AgzxjxkkWWm/ARvZsQ6m9xnwpBtH46WVpEKK1uLVXABJS9Tozi1UKySGiVHJbMKL6TkKSxGCbysWzjlHt7ird707t2jG93abd79m93wnuvA0YwyzCzzTDLOIFcRzVEap7kXVSineZFXto8N+Xd8Oqu8n+/iEV/N7/OUX2WDMf+NF/gZPsoP8Vfc4PW8m29kwhK/x21+hRe5xz9xk23IqMDCCi+kOKCEJS2lUzteWoaoOF7ghbYPpzzDR3zUhz69Z/SgR3vMp/+wBz5zHThaW1WqrG6tVsUVVC9wjBqHQq2dykPVrXkl1XNgrfLU7VZOkS+kLapw6clIgGgylUeECZahiCILlSdksyDRxZS+EIFi+3CwLbdVjbX9rdl4W2lVfrS1Gm+F0Kzmt9pSa7Q0OrmBttQK2NyTG2hJzNGn84gPewrzidADH3/yOMlcB06p4wqrWnmVq15B1SqrfoDroMYFrWpNUdUrqY/VFFbbh6OyTs4RJltlt4gCRJKp7BRDsHRkQSwJtss5gkQQZyJEJDlL2mIIF1PirnBKGzfY1Mab3PQGmtZYy3LcBq3yaVObi1pB2mPNhc324eiv8xN/7JeZvwD94M+d/KporgOn6K90laq6X29TXa/W95Xpm2oo1j+poM/oUb1Pv9OGrldLb1Wikr6lUF/RRZX1N9pUjvazeruzzrvZxQ467NO+s0e4d3pOuuc7qKfJpOeV7cMp49MhDXVsHc8MfYDx3WAjMQYegyGMZwYd940QjfXDGo8NMqQxHnDcN/iQx/rRHR7IY4WqKldZdQWqKVPXwzrQMKOqaoxUV6KPaQzV9uFgP9hP76zv72v6pK/0VX3aD/dW5/14X+hWP9rX9V96owt9dz+pg77UT+3tvtxP7p2+tzc7RwcacLDBBxl4gOFldGRFXtRR5qFR1E7t2T6c8g5f8VVf+vbe0Yte7TXf/ste+M514OhsTWmyuXVaE08wK6cwpu8J05qFMSs0S2vySWZVwGnMOCy7k1PWF6u91MVXb40WWNqarkcWW3gNl7jkRdcTa/NCS1/m6i+y4LJ9OLov3qs22/v33zfeV+8sObqNnQfCtnbtSbuxQ39xkx2lcC9vv7x0N7cHMppwssknmXiCmTh0Or7nh4WToOmHcZjYPjbkjeucpa6t64U1WmB9t2ZsrBkvrGcWXQ+trxZa69fuNWNpzfi+NeOPV3fZkNGGm22+ycYbbCehO8nTvAwSB+28rEvn/z8p", + rgbaBase64 = "AAAA/wQAA/8IAAb/DAAJ/xAADP8UAA//GAAS/xwAFf8gABj/JAAb/ygAHv8sACH/MAAk/zQAJ/84ACr/PAAt/0AAMP9EADP/SAA2/0wAOf9QADz/VAA//1gAQv9cAEX/YABI/2QAS/9oAE7/bABR/3AAVP90AFf/eABa/3wAXf+goAD/xdVB/+oKhP8PP8n/NHQQ/1mpWf9+3qT/oxPx/8hIQP/tfZH/ErLk/zfnOf9cHJD/gVHp/6aGRP/Lu6H/8PAA/xUlYf86WsT/X48p/4TEkP+p+fn/zi5k//Nj0f8YmED/Pc2x/2ICJP+HN5n/rGwQ/9Ghif/21gT/GwuB/wAEA/8EBAb/CAQJ/wwEDP8QBA//FAQS/xgEFf8cBBj/IAQb/yQEHv8oBCH/LAQk/zAEJ/80BCr/OAQt/zwEMP9ABDP/RAQ2/0gEOf9MBDz/UAQ//1QEQv9YBEX/XARI/2AES/9kBE7/aARR/2wEVP9wBFf/dARa/3gEXf98BGD/sb0B/9bIQv/7F4X/ICLK/0VpEf9qtFr/j8Ol/7QO8v/ZVUH//mCS/yOv5f9I+jr/bQGR/5JM6v+3m0X/3Kai/wHtAf8mOGL/S0fF/3CSKv+V2ZH/uuT6/98zZf8EftL/KYVB/07Qsv9zHyX/mCqa/71xEf/ivIr/B8sF/ywWgv8ACAb/BAgJ/wgIDP8MCA//EAgS/xQIFf8YCBj/HAgb/yAIHv8kCCH/KAgk/ywIJ/8wCCr/NAgt/zgIMP88CDP/QAg2/0QIOf9ICDz/TAg//1AIQv9UCEX/WAhI/1wIS/9gCE7/ZAhR/2gIVP9sCFf/cAha/3QIXf94CGD/fAhj/8KaBP/n70X/DDCI/zEFzf9WThT/e5Nd/6DkqP/FKfX/6nJE/w9Hlf80iOj/Wd09/34mlP+ja+3/yLxI/+2Bpf8SygT/Nx9l/1xgyP+BtS3/pv6U/8vD/f/wFGj/FVnV/zqiRP9f97X/hDgo/6kNnf/OVhT/85uN/xjsCP89MYX/AAwJ/wQMDP8IDA//DAwS/xAMFf8UDBj/GAwb/xwMHv8gDCH/JAwk/ygMJ/8sDCr/MAwt/zQMMP84DDP/PAw2/0AMOf9EDDz/SAw//0wMQv9QDEX/VAxI/1gMS/9cDE7/YAxR/2QMVP9oDFf/bAxa/3AMXf90DGD/eAxj/3wMZv/T9wn/+IJK/x1djf9CaNL/ZyMZ/4z+Yv+xia3/1kT6//sfSf8gKpr/ReXt/2qwQv+PS5n/tAby/9nRTf/+7Kr/I6cJ/0hyav9tDc3/ktgy/7eTmf/crgL/AXlt/yY02v9Lz0n/cJq6/5VVLf+6YKL/3zsZ/wT2kv8pgQ3/TlyK/wAQDP8EEA//CBAS/wwQFf8QEBj/FBAb/xgQHv8cECH/IBAk/yQQJ/8oECr/LBAt/zAQMP80EDP/OBA2/zwQOf9AEDz/RBA//0gQQv9MEEX/UBBI/1QQS/9YEE7/XBBR/2AQVP9kEFf/aBBa/2wQXf9wEGD/dBBj/3gQZv98EGn/5NQQ/wmhUf8ufpT/U0vZ/3gAIP+d3Wn/wqq0/+dnAf8MPFD/MQmh/1bG9P97k0n/oGig/8Ul+f/q8lT/D8+x/zSEEP9ZUXH/fi7U/6P7Of/IsKD/7Y0J/xJadP83F+H/XOxQ/4G5wf+mdjT/y0Op//AYIP8V1Zn/OqIU/19/kf8AFA//BBQS/wgUFf8MFBj/EBQb/xQUHv8YFCH/HBQk/yAUJ/8kFCr/KBQt/ywUMP8wFDP/NBQ2/zgUOf88FDz/QBQ//0QUQv9IFEX/TBRI/1AUS/9UFE7/WBRR/1wUVP9gFFf/ZBRa/2gUXf9sFGD/cBRj/3QUZv94FGn/fBRs//UxGf8aRFr/P5ud/2Su4v+J5Sn/rjhy/9NPvf/4ggr/HdlZ/0Lsqv9nI/3/jHZS/7GNqf/WwAL/+xdd/yAquv9FYRn/arR6/4/L3f+0HkL/2VWp//5oEv8jv33/SPLq/20JWf+SXMr/t5M9/9ymsv8B/Sn/JjCi/0tHHf9wmpr/ABgS/wQYFf8IGBj/DBgb/xAYHv8UGCH/GBgk/xwYJ/8gGCr/JBgt/ygYMP8sGDP/MBg2/zQYOf84GDz/PBg//0AYQv9EGEX/SBhI/0wYS/9QGE7/VBhR/1gYVP9cGFf/YBha/2QYXf9oGGD/bBhj/3AYZv90GGn/eBhs/3wYb/8GDiT/K3tl/1CkqP91ke3/mto0/78Hff/kcMj/Cb0V/y7mZP9T07X/eBwI/51JXf/CsrT/5/8N/wwoaP8xFcX/Vl4k/3uLhf+g9Oj/xSFN/+pqtP8PVx3/NICI/1nN9f9+NmT/o2PV/8isSP/tmb3/EsI0/zcPrf9ceCj/gaWl/wAcFf8EHBj/CBwb/wwcHv8QHCH/FBwk/xgcJ/8cHCr/IBwt/yQcMP8oHDP/LBw2/zAcOf80HDz/OBw//zwcQv9AHEX/RBxI/0gcS/9MHE7/UBxR/1QcVP9YHFf/XBxa/2AcXf9kHGD/aBxj/2wcZv9wHGn/dBxs/3gcb/98HHL/F2sx/zwecv9hwbX/hvT6/6u/Qf/QYor/9RXV/xrYIv8/g3H/ZLbC/4l5Ff+uLGr/09fB//iaGv8dTXX/QnDS/2c7Mf+M7pL/sZH1/9ZEWv/7D8H/IDIq/0Xllf9qqAL/j1Nx/7QG4v/ZyVX//vzK/yOnQf9Iarr/bR01/5LAsv8AIBj/BCAb/wggHv8MICH/ECAk/xQgJ/8YICr/HCAt/yAgMP8kIDP/KCA2/ywgOf8wIDz/NCA//zggQv88IEX/QCBI/0QgS/9IIE7/TCBR/1AgVP9UIFf/WCBa/1wgXf9gIGD/ZCBj/2ggZv9sIGn/cCBs/3Qgb/94IHL/fCB1/yhIQP9NPYH/cuLE/5fXCf+8nFD/4UGZ/wY25P8r+zH/UKCA/3WV0f+aWiT/vw95/+T00P8JuSn/Lm6E/1NT4f94GED/nc2h/8KyBP/nZ2n/DCzQ/zEROf9WxqT/e4sR/6BwgP/FJfH/6upk/w/f2f80hFD/WUnJ/34+RP+j48H/ACQb/wQkHv8IJCH/DCQk/xAkJ/8UJCr/GCQt/xwkMP8gJDP/JCQ2/ygkOf8sJDz/MCQ//zQkQv84JEX/PCRI/0AkS/9EJE7/SCRR/0wkVP9QJFf/VCRa/1gkXf9cJGD/YCRj/2QkZv9oJGn/bCRs/3Akb/90JHL/eCR1/3wkeP85pVH/XtCS/4MP1f+oOhr/zXFh//Ksqv8X2/X/PBZC/2FNkf+GeOL/q7c1/9Diiv/1GeH/GlQ6/z+Dlf9kvvL/ifVR/64gsv/TXxX/+Ip6/x3B4f9C/Er/Zyu1/4xmIv+xnZH/1sgC//sHdf8gMur/RWlh/2qk2v+P01X/tA7S/wAoHv8EKCH/CCgk/wwoJ/8QKCr/FCgt/xgoMP8cKDP/ICg2/yQoOf8oKDz/LCg//zAoQv80KEX/OChI/zwoS/9AKE7/RChR/0goVP9MKFf/UCha/1QoXf9YKGD/XChj/2AoZv9kKGn/aChs/2wob/9wKHL/dCh1/3goeP98KHv/SoJk/2/3pf+UKOj/uR0t/95WdP8Di73/KPwI/00xVf9yaqT/l1/1/7yQSP/hxZ3/Bj70/ytzTf9QpKj/dZkF/5rSZP+/B8X/5Hgo/wmtjf8u5vT/U9td/3gMyP+dQTX/wrqk/+fvFf8MIIj/MRX9/1ZOdP97g+3/oPRo/8Up5f8ALCH/BCwk/wgsJ/8MLCr/ECwt/xQsMP8YLDP/HCw2/yAsOf8kLDz/KCw//ywsQv8wLEX/NCxI/zgsS/88LE7/QCxR/0QsVP9ILFf/TCxa/1AsXf9ULGD/WCxj/1wsZv9gLGn/ZCxs/2gsb/9sLHL/cCx1/3QseP94LHv/fCx+/1ufef+A6rr/pTX9/8oAQv/vS4n/FJbS/znhHf9eLGr/g3e5/6hCCv/NjV3/8tiy/xcjCf88bmL/Ybm9/4aEGv+rz3n/0Bra//VlPf8asKL/P/sJ/2TGcv+JEd3/rlxK/9Onuf/48ir/HT2d/0IIEv9nU4n/jJ4C/7Hpff/WNPr/ADAk/wQwJ/8IMCr/DDAt/xAwMP8UMDP/GDA2/xwwOf8gMDz/JDA//ygwQv8sMEX/MDBI/zQwS/84ME7/PDBR/0AwVP9EMFf/SDBa/0wwXf9QMGD/VDBj/1gwZv9cMGn/YDBs/2Qwb/9oMHL/bDB1/3AweP90MHv/eDB+/3wwgf9s/JD/kYnR/7ZWFP/bY1n/ACig/yX16f9KgjT/b0+B/5QU0P+5ISH/3u50/wO7yf8oQCD/TQ15/3La1P+X5zH/vKyQ/+F58f8GBlT/K9O5/1CYIP91pYn/mnL0/78/Yf/kxND/CZFB/y5etP9Tayn/eDCg/539Gf/CipT/51cR/wA0J/8ENCr/CDQt/ww0MP8QNDP/FDQ2/xg0Of8cNDz/IDQ//yQ0Qv8oNEX/LDRI/zA0S/80NE7/ODRR/zw0VP9ANFf/RDRa/0g0Xf9MNGD/UDRj/1Q0Zv9YNGn/XDRs/2A0b/9kNHL/aDR1/2w0eP9wNHv/dDR+/3g0gf98NIT/fdmp/6Ks6v/Hcy3/7EZy/xENuf820AL/W6dN/4Bqmv+lMen/ygQ6/+/Ljf8UnuL/OWU5/14okv+D/+3/qMJK/82Jqf/yXAr/FyNt/zz20v9hvTn/hoCi/6tXDf/QGnr/9eHp/xq0Wv8/e83/ZE5C/4kVuf+u2DL/06+t//hyKv8AOCr/BDgt/wg4MP8MODP/EDg2/xQ4Of8YODz/HDg//yA4Qv8kOEX/KDhI/yw4S/8wOE7/NDhR/zg4VP88OFf/QDha/0Q4Xf9IOGD/TDhj/1A4Zv9UOGn/WDhs/1w4b/9gOHL/ZDh1/2g4eP9sOHv/cDh+/3Q4gf94OIT/fDiH/442xP+zQwX/2JxI//2pjf8i4tT/Rz8d/2xIaP+RhbX/tt4E/9vrVf8AJKj/JXH9/0qKVP9vx63/lBAI/7ktZf/eZsT/A7Ml/yjMiP9NGe3/clJU/5dvvf+8uCj/4fWV/wYOBP8rW3X/UJTo/3WhXf+a+tT/vzdN/+RAyP8JnUX/ADwt/wQ8MP8IPDP/DDw2/xA8Of8UPDz/GDw//xw8Qv8gPEX/JDxI/yg8S/8sPE7/MDxR/zQ8VP84PFf/PDxa/0A8Xf9EPGD/SDxj/0w8Zv9QPGn/VDxs/1g8b/9cPHL/YDx1/2Q8eP9oPHv/bDx+/3A8gf90PIT/eDyH/3w8iv+fE+H/xGYi/+m5Zf8OjKr/M8fx/1gaOv99bYX/oqDS/8f7If/sznL/EQHF/zZUGv9br3H/gOLK/6U1Jf/KCIL/70Ph/xSWQv856aX/XjwK/4N3cf+oStr/zZ1F//LQsv8XKyH/PH6S/2GxBf+GhHr/q9/x/9ASav/1ZeX/Grhi/wBAMP8EQDP/CEA2/wxAOf8QQDz/FEA//xhAQv8cQEX/IEBI/yRAS/8oQE7/LEBR/zBAVP80QFf/OEBa/zxAXf9AQGD/REBj/0hAZv9MQGn/UEBs/1RAb/9YQHL/XEB1/2BAeP9kQHv/aEB+/2xAgf9wQIT/dECH/3hAiv98QI3/sHAA/9UFQf/62oT/H+/J/0SkEP9peVn/jg6k/7PD8f/YmED//a2R/yJi5P9HNzn/bMyQ/5GB6f+2VkT/22uh/wAgAP8l9WH/SorE/29fKf+UFJD/uSn5/97+ZP8Ds9H/KEhA/00dsf9y0iT/l+eZ/7y8EP/hcYn/BgYE/yvbgf8ARDP/BEQ2/whEOf8MRDz/EEQ//xREQv8YREX/HERI/yBES/8kRE7/KERR/yxEVP8wRFf/NERa/zhEXf88RGD/QERj/0REZv9IRGn/TERs/1BEb/9URHL/WER1/1xEeP9gRHv/ZER+/2hEgf9sRIT/cESH/3REiv94RI3/fESQ/8FNIf/mOGL/C+el/zDS6v9VmTH/ekR6/58zxf/E/hL/6aVh/w6Qsv8zXwX/WApa/33xsf+ivAr/x2tl/+xWwv8RHSH/NsiC/1u35f+AYkr/pSmx/8oUGv/vw4X/FI7y/zl1Yf9eINL/g+9F/6jauv/NgTH/8kyq/xc7Jf885qL/AEg2/wRIOf8ISDz/DEg//xBIQv8USEX/GEhI/xxIS/8gSE7/JEhR/yhIVP8sSFf/MEha/zRIXf84SGD/PEhj/0BIZv9ESGn/SEhs/0xIb/9QSHL/VEh1/1hIeP9cSHv/YEh+/2RIgf9oSIT/bEiH/3BIiv90SI3/eEiQ/3xIk//SqkT/99+F/xwAyP9BNQ3/Zn5U/4ujnf+w1Oj/1Rk1//pChP8fd9X/RLgo/2ntff+OFtT/s1st/9iMiP/9seX/IvpE/0cvpf9sUAj/kYVt/7bO1P/b8z3/ACSo/yVpFf9KkoT/b8f1/5QIaP+5Pd3/3mZU/wOrzf8o3Ej/TQHF/wBMOf8ETDz/CEw//wxMQv8QTEX/FExI/xhMS/8cTE7/IExR/yRMVP8oTFf/LExa/zBMXf80TGD/OExj/zxMZv9ATGn/RExs/0hMb/9MTHL/UEx1/1RMeP9YTHv/XEx+/2BMgf9kTIT/aEyH/2xMiv9wTI3/dEyQ/3hMk/98TJb/44dp/wjyqv8tLe3/Uhgy/3dTef+cjsL/wfkN/+Y0Wv8Lb6n/MFr6/1WVTf96wKL/nzv5/8R2Uv/poa3/DpwK/zPXaf9YAsr/fX0t/6Kokv/H4/n/7N5i/xEJzf82RDr/W7+p/4DqGv+lJY3/yhAC/+9Lef8UhvL/OfFt/14s6v8AUDz/BFA//whQQv8MUEX/EFBI/xRQS/8YUE7/HFBR/yBQVP8kUFf/KFBa/yxQXf8wUGD/NFBj/zhQZv88UGn/QFBs/0RQb/9IUHL/TFB1/1BQeP9UUHv/WFB+/1xQgf9gUIT/ZFCH/2hQiv9sUI3/cFCQ/3RQk/94UJb/fFCZ//TkkP8ZkdH/Pk4U/2N7Wf+IMKD/re3p/9KaNP/3V4H/HAzQ/0E5If9m9nT/i6PJ/7BYIP/VFXn/+sLU/x//Mf9EtJD/aWHx/44eVP+zy7n/2IAg//29if8iavT/Rydh/2zc0P+RiUH/tka0/9tzKf8AKKD/JeUZ/0qSlP9vTxH/AFQ//wRUQv8IVEX/DFRI/xBUS/8UVE7/GFRR/xxUVP8gVFf/JFRa/yhUXf8sVGD/MFRj/zRUZv84VGn/PFRs/0BUb/9EVHL/SFR1/0xUeP9QVHv/VFR+/1hUgf9cVIT/YFSH/2RUiv9oVI3/bFSQ/3BUk/90VJb/eFSZ/3xUnP8Fwbn/KrT6/09rPf90XoL/mRXJ/77IEv/jv13/CHKq/y0p+f9SHEr/d9Od/5yG8v/BfUn/5jCi/wvn/f8w2lr/VZG5/3pEGv+fO33/xO7i/+mlSf8OmLL/M08d/1gCiv99+fn/oqxq/8dj3f/sVlL/EQ3J/zbAQv9bt73/gGo6/wBYQv8EWEX/CFhI/wxYS/8QWE7/FFhR/xhYVP8cWFf/IFha/yRYXf8oWGD/LFhj/zBYZv80WGn/OFhs/zxYb/9AWHL/RFh1/0hYeP9MWHv/UFh+/1RYgf9YWIT/XFiH/2BYiv9kWI3/aFiQ/2xYk/9wWJb/dFiZ/3hYnP98WJ//Ft7k/zurJf9gdGj/hUGt/6oK9P/P1z3/9KCI/xlt1f8+NiT/YwN1/4jMyP+tmR3/0mJ0//cvzf8c+Cj/QcWF/2aO5P+LW0X/sCSo/9XxDf/6unT/H4fd/0RQSP9pHbX/juYk/7Ozlf/YfAj//Ul9/yIS9P9H323/bKjo/5F1Zf8AXEX/BFxI/whcS/8MXE7/EFxR/xRcVP8YXFf/HFxa/yBcXf8kXGD/KFxj/yxcZv8wXGn/NFxs/zhcb/88XHL/QFx1/0RceP9IXHv/TFx+/1Bcgf9UXIT/WFyH/1xciv9gXI3/ZFyQ/2hck/9sXJb/cFyZ/3RcnP94XJ//fFyi/yc7Ef9MTlL/cZGV/5ak2v+77yH/4DJq/wVFtf8qiAL/T9NR/3Tmov+ZKfX/vnxK/+OHof8Iyvr/LR1V/1Igsv93axH/nL5y/8HB1f/mFDr/C1+h/zBiCv9VtXX/evji/58DUf/EVsL/6Zk1/w6sqv8z9yH/WDqa/31NFf+ikJL/AGBI/wRgS/8IYE7/DGBR/xBgVP8UYFf/GGBa/xxgXf8gYGD/JGBj/yhgZv8sYGn/MGBs/zRgb/84YHL/PGB1/0BgeP9EYHv/SGB+/0xggf9QYIT/VGCH/1hgiv9cYI3/YGCQ/2Rgk/9oYJb/bGCZ/3BgnP90YJ//eGCi/3xgpf84GED/XW2B/4KyxP+nhwn/zMxQ//ERmf8WZuT/O6sx/2DwgP+FxdH/qgok/89fef/0pND/Gekp/z4+hP9jA+H/iEhA/62dof/S4gT/9zdp/xx80P9BQTn/Zpak/4vbEf+wIID/1XXx//q6ZP8fj9n/RNRQ/2kZyf+ObkT/s7PB/wBkS/8EZE7/CGRR/wxkVP8QZFf/FGRa/xhkXf8cZGD/IGRj/yRkZv8oZGn/LGRs/zBkb/80ZHL/OGR1/zxkeP9AZHv/RGR+/0hkgf9MZIT/UGSH/1Rkiv9YZI3/XGSQ/2Bkk/9kZJb/aGSZ/2xknP9wZJ//dGSi/3hkpf98ZKj/SXVx/24Asv+T3/X/uOo6/92hgf8CfMr/JwsV/0zGYv9xnbH/lqgC/7tnVf/gMqr/BckB/yqEWv9PU7X/dG4S/5klcf++8NL/4481/whamv8tEQH/Uixq/3f71f+ctkL/wU2x/+YYIv8L15X/MOIK/1W5gf96dPr/nwN1/8Te8v8AaE7/BGhR/whoVP8MaFf/EGha/xRoXf8YaGD/HGhj/yBoZv8kaGn/KGhs/yxob/8waHL/NGh1/zhoeP88aHv/QGh+/0Rogf9IaIT/TGiH/1Boiv9UaI3/WGiQ/1xok/9gaJb/ZGiZ/2honP9saJ//cGii/3Ropf94aKj/fGir/1pSpP9/J+X/pPgo/8nNbf/uhrT/E1v9/zgsSP9d4ZX/grrk/6ePNf/MQIj/8RXd/xbuNP87o43/YHTo/4VJRf+qAqT/z9cF//SoaP8Zfc3/PjY0/2MLnf+I3Aj/rZF1/9Jq5P/3P1X/HPDI/0HFPf9mnrT/i1Mt/7AkqP/V+SX/AGxR/wRsVP8IbFf/DGxa/xBsXf8UbGD/GGxj/xxsZv8gbGn/JGxs/yhsb/8sbHL/MGx1/zRseP84bHv/PGx+/0Bsgf9EbIT/SGyH/0xsiv9QbI3/VGyQ/1hsk/9cbJb/YGyZ/2RsnP9obJ//bGyi/3Bspf90bKj/eGyr/3xsrv9rr9n/kNoa/7UFXf/aMKL//3vp/ySmMv9J0X3/bhzK/5NHGf+4cmr/3b29/wLoEv8nE2n/TF7C/3GJHf+WtHr/u//Z/+AqOv8FVZ3/KoAC/0/Laf909tL/mSE9/75sqv/jlxn/CMKK/y0N/f9SOHL/d2Pp/5yuYv/B2d3/5gRa/wBwVP8EcFf/CHBa/wxwXf8QcGD/FHBj/xhwZv8ccGn/IHBs/yRwb/8ocHL/LHB1/zBweP80cHv/OHB+/zxwgf9AcIT/RHCH/0hwiv9McI3/UHCQ/1Rwk/9YcJb/XHCZ/2BwnP9kcJ//aHCi/2xwpf9wcKj/dHCr/3hwrv98cLH/fIwQ/6H5Uf/GJpT/6xPZ/xBYIP81hWn/WvK0/38/Af+kZFD/yVGh/+6e9P8Ty0n/ODCg/119+f+CqlT/p5ex/8zcEP/xCXH/FnbU/zujOf9g6KD/hdUJ/6oCdP/PT+H/9LRQ/xnhwf8+LjT/Yxup/4hAIP+tjZn/0voU//cnkf8AdFf/BHRa/wh0Xf8MdGD/EHRj/xR0Zv8YdGn/HHRs/yB0b/8kdHL/KHR1/yx0eP8wdHv/NHR+/zh0gf88dIT/QHSH/0R0iv9IdI3/THSQ/1B0k/9UdJb/WHSZ/1x0nP9gdJ//ZHSi/2h0pf9sdKj/cHSr/3R0rv94dLH/fHS0/43pSf+ynIr/10PN//x2Ev8hPVn/RuCi/2uX7f+QWjr/tQGJ/9o02v//+y3/JK6C/0lV2f9uGDL/k8+N/7jy6v/duUn/Amyq/ycTDf9MxnL/cY3Z/5awQv+7Z63/4Coa/wXRif8qhPr/T0tt/3R+4v+ZJVn/vujS/+OfTf8IQsr/AHha/wR4Xf8IeGD/DHhj/xB4Zv8UeGn/GHhs/xx4b/8geHL/JHh1/yh4eP8seHv/MHh+/zR4gf84eIT/PHiH/0B4iv9EeI3/SHiQ/0x4k/9QeJb/VHiZ/1h4nP9ceJ//YHii/2R4pf9oeKj/bHir/3B4rv90eLH/eHi0/3x4t/+exoT/w7PF/+hsCP8NWU3/MhKU/1fP3f98uCj/oXV1/8YuxP/rGxX/ENRo/zWBvf9aehT/fzdt/6TgyP/J3SX/7paE/xND5f84PEj/Xemt/4KiFP+nn33/zEjo//EFVf8W/sT/O6s1/2BkqP+FUR3/qgqU/8/HDf/0sIj/GW0F/wB8Xf8EfGD/CHxj/wx8Zv8QfGn/FHxs/xh8b/8cfHL/IHx1/yR8eP8ofHv/LHx+/zB8gf80fIT/OHyH/zx8iv9AfI3/RHyQ/0h8k/9MfJb/UHyZ/1R8nP9YfJ//XHyi/2B8pf9kfKj/aHyr/2x8rv9wfLH/dHy0/3h8t/98fLr/ryPB/9RWAv/5iUX/HryK/0P30f9oKhr/jV1l/7KQsv/XywH//P5S/yExpf9GZPr/a59R/5DSqv+1BQX/2jhi//9zwf8kpiL/SdmF/24M6v+TR1H/uHq6/92tJf8C4JL/JxsB/0xOcv9xgeX/lrRa/7vv0f/gIkr/BVXF/yqIQv8AgGD/BIBj/wiAZv8MgGn/EIBs/xSAb/8YgHL/HIB1/yCAeP8kgHv/KIB+/yyAgf8wgIT/NICH/ziAiv88gI3/QICQ/0SAk/9IgJb/TICZ/1CAnP9UgJ//WICi/1yApf9ggKj/ZICr/2iArv9sgLH/cIC0/3SAt/94gLr/fIC9/8AAAP/ldUH/CqqE/y+fyf9U1BD/eQlZ/55+pP/Ds/H/6OhA/w3dkf8yEuT/V0c5/3y8kP+h8en/xiZE/+sbof8QUAD/NYVh/1r6xP9/Lyn/pGSQ/8lZ+f/ujmT/E8PR/zg4QP9dbbH/gqIk/6eXmf/MzBD/8QGJ/xZ2BP87q4H/AIRj/wSEZv8IhGn/DIRs/xCEb/8UhHL/GIR1/xyEeP8ghHv/JIR+/yiEgf8shIT/MISH/zSEiv84hI3/PISQ/0CEk/9EhJb/SISZ/0yEnP9QhJ//VISi/1iEpf9chKj/YISr/2SErv9ohLH/bIS0/3CEt/90hLr/eIS9/3yEwP/RHUH/9miC/xu3xf9Aggr/ZclR/4oUmv+vY+X/1K4y//n1gf8ewNL/Qw8l/2haev+NodH/suwq/9c7hf/8BuL/IU1B/0aYov9r5wX/kDJq/7V50f/aRDr//5Ol/yTeEv9JJYH/bnDy/5O/Zf+4itr/3dFR/wIcyv8na0X/TLbC/wCIZv8EiGn/CIhs/wyIb/8QiHL/FIh1/xiIeP8ciHv/IIh+/ySIgf8oiIT/LIiH/zCIiv80iI3/OIiQ/zyIk/9AiJb/RIiZ/0iInP9MiJ//UIii/1SIpf9YiKj/XIir/2CIrv9kiLH/aIi0/2yIt/9wiLr/dIi9/3iIwP98iMP/4nqE/wcPxf8s0Aj/UeVN/3aulP+bc93/wAQo/+XJdf8KksT/L6cV/1RoaP95Pb3/nsYU/8OLbf/oXMj/DWEl/zIqhP9X/+X/fIBI/6FVrf/GHhT/6yN9/xD06P81uVX/WkLE/38XNf+k2Kj/ye0d/+62lP8Tew3/OAyI/13RBf8AjGn/BIxs/wiMb/8MjHL/EIx1/xSMeP8YjHv/HIx+/yCMgf8kjIT/KIyH/yyMiv8wjI3/NIyQ/ziMk/88jJb/QIyZ/0SMnP9IjJ//TIyi/1CMpf9UjKj/WIyr/1yMrv9gjLH/ZIy0/2iMt/9sjLr/cIy9/3SMwP94jMP/fIzG//NXyf8YIgr/Pf1N/2LIkv+Hg9n/rF4i/9Epbf/25Lr/G78J/0CKWv9lRa3/ihAC/6/rWf/UprL/+XEN/x5Mav9DB8n/aNIq/42tjf+yePL/1zNZ//wOwv8h2S3/RpSa/2tvCf+QOnr/tfXt/9rAYv//m9n/JFZS/0khzf9u/Er/AJBs/wSQb/8IkHL/DJB1/xCQeP8UkHv/GJB+/xyQgf8gkIT/JJCH/yiQiv8skI3/MJCQ/zSQk/84kJb/PJCZ/0CQnP9EkJ//SJCi/0yQpf9QkKj/VJCr/1iQrv9ckLH/YJC0/2SQt/9okLr/bJC9/3CQwP90kMP/eJDG/3yQyf8EtBD/KcFR/04elP9zK9n/mGAg/729af/iyrT/BwcB/yxcUP9RaaH/dqb0/5vzSf/ACKD/5UX5/wqSVP8vr7H/VOQQ/3kxcf+eTtT/w5s5/+jQoP8N7Qn/Mjp0/1d34f98jFD/odnB/8YWNP/rI6n/EHgg/zW1mf9awhT/fx+R/wCUb/8ElHL/CJR1/wyUeP8QlHv/FJR+/xiUgf8clIT/IJSH/ySUiv8olI3/LJSQ/zCUk/80lJb/OJSZ/zyUnP9AlJ//RJSi/0iUpf9MlKj/UJSr/1SUrv9YlLH/XJS0/2CUt/9klLr/aJS9/2yUwP9wlMP/dJTG/3iUyf98lMz/FZFZ/zrkmv9fO93/hA4i/6lFaf/OmLL/8+/9/xgiSv89eZn/Ykzq/4eDPf+s1pL/0S3p//ZgQv8bt53/QIr6/2XBWf+KFLr/r2sd/9S+gv/59en/HshS/0Mfvf9oUir/jamZ/7L8Cv/XM33//Aby/yFdaf9GkOL/a+dd/5A62v8AmHL/BJh1/wiYeP8MmHv/EJh+/xSYgf8YmIT/HJiH/yCYiv8kmI3/KJiQ/yyYk/8wmJb/NJiZ/ziYnP88mJ//QJii/0SYpf9ImKj/TJir/1CYrv9UmLH/WJi0/1yYt/9gmLr/ZJi9/2iYwP9smMP/cJjG/3SYyf94mMz/fJjP/ybupP9Lm+X/cEQo/5Vxbf+6OrT/3+f9/wSQSP8pXZX/Tgbk/3MzNf+Y/Ij/vand/+JSNP8HH43/LMjo/1H1Rf92vqT/m2sF/8AUaP/lwc3/Coo0/y+3nf9UYAj/eS11/57W5P/Dg1X/6EzI/w15Pf8yIrT/V+8t/3yYqP+hRSX/AJx1/wSceP8InHv/DJx+/xCcgf8UnIT/GJyH/xyciv8gnI3/JJyQ/yick/8snJb/MJyZ/zScnP84nJ//PJyi/0Ccpf9EnKj/SJyr/0ycrv9QnLH/VJy0/1ict/9cnLr/YJy9/2ScwP9onMP/bJzG/3Ccyf90nMz/eJzP/3yc0v83y/H/XL4y/4Fhdf+mVLr/yx8B//DCSv8VtZX/Onji/18jMf+EFoL/qdnV/86MKv/zd4H/GDra/z3tNf9i0JL/h5vx/6xOUv/RMbX/9uQa/xuvgf9Akur/ZUVV/4oIwv+v8zH/1Kai//lpFf8eXIr/QwcB/2jKev+NvfX/smBy/wCgeP8EoHv/CKB+/wyggf8QoIT/FKCH/xigiv8coI3/IKCQ/ySgk/8ooJb/LKCZ/zCgnP80oJ//OKCi/zygpf9AoKj/RKCr/0igrv9MoLH/UKC0/1Sgt/9YoLr/XKC9/2CgwP9koMP/aKDG/2ygyf9woMz/dKDP/3ig0v98oNX/SChA/21dgf+SgsT/t7cJ/9z8UP8BIZn/Jlbk/0ubMf9wwID/lfXR/7o6JP/fb3n/BJTQ/ynZKf9ODoT/czPh/5h4QP+9raH/4tIE/wcHaf8sTND/UXE5/3ampP+b6xH/wBCA/+VF8f8KimT/L7/Z/1TkUP95Kcn/nl5E/8ODwf8ApHv/BKR+/wikgf8MpIT/EKSH/xSkiv8YpI3/HKSQ/yCkk/8kpJb/KKSZ/yyknP8wpJ//NKSi/zikpf88pKj/QKSr/0Skrv9IpLH/TKS0/1Ckt/9UpLr/WKS9/1ykwP9gpMP/ZKTG/2ikyf9spMz/cKTP/3Sk0v94pNX/fKTY/1kFkf9+cNL/o68V/8iaWv/t0aH/Egzq/zd7Nf9ctoL/ge3R/6bYIv/LF3X/8ELK/xW5If869Hr/XyPV/4QeMv+pVZH/zoDy//P/Vf8YKrr/PWEh/2Jciv+Hi/X/rMZi/9E90f/2aEL/G6e1/0CSKv9lyaH/igQa/69zlf/UrhL/AKh+/wSogf8IqIT/DKiH/xCoiv8UqI3/GKiQ/xyok/8gqJb/JKiZ/yionP8sqJ//MKii/zSopf84qKj/PKir/0Corv9EqLH/SKi0/0yot/9QqLr/VKi9/1iowP9cqMP/YKjG/2Soyf9oqMz/bKjP/3Co0v90qNX/eKjY/3yo2/9qYuT/jxcl/7TIaP/Z/a3//rb0/yNrPf9IHIj/bdHV/5KKJP+3v3X/3HDI/wElHf8m3nT/S5PN/3BEKP+VeYX/ujLk/9/nRf8EmKj/KU0N/04GdP9zO93/mOxI/72htf/iWiT/Bw+V/yzACP9R9X3/dq70/5tjbf/AFOj/5cll/wCsgf8ErIT/CKyH/wysiv8QrI3/FKyQ/xisk/8crJb/IKyZ/ySsnP8orJ//LKyi/zCspf80rKj/OKyr/zysrv9ArLH/RKy0/0ist/9MrLr/UKy9/1SswP9YrMP/XKzG/2Csyf9krMz/aKzP/2ys0v9wrNX/dKzY/3is2/98rN7/e385/6AKev/F1b3/6uAC/w+rSf80dpL/WQHd/37MKv+jl3n/yKLK/+1tHf8SOHL/N8PJ/1yOIv+BWX3/pmTa/8svOf/w+pr/FYX9/zpQYv9fG8n/hCYy/6nxnf/OvAr/80d5/xgS6v893V3/YujS/4ezSf+sfsL/0Qk9//bUuv8AsIT/BLCH/wiwiv8MsI3/ELCQ/xSwk/8YsJb/HLCZ/yCwnP8ksJ//KLCi/yywpf8wsKj/NLCr/ziwrv88sLH/QLC0/0Swt/9IsLr/TLC9/1CwwP9UsMP/WLDG/1ywyf9gsMz/ZLDP/2iw0v9ssNX/cLDY/3Sw2/94sN7/fLDh/4xckP+xKdH/1vYU//vDWf8giKD/RVXp/2oiNP+P74H/tLTQ/9mBIf/+TnT/IxvJ/0jgIP9trXn/knrU/7dHMf/cDJD/Adnx/yamVP9Lc7n/cDgg/5UFif+60vT/359h/wRk0P8pMUH/Tv60/3PLKf+YkKD/vV0Z/+IqlP8H9xH/ALSH/wS0iv8ItI3/DLSQ/xC0k/8UtJb/GLSZ/xy0nP8gtJ//JLSi/yi0pf8stKj/MLSr/zS0rv84tLH/PLS0/0C0t/9EtLr/SLS9/0y0wP9QtMP/VLTG/1i0yf9ctMz/YLTP/2S00v9otNX/bLTY/3C02/90tN7/eLTh/3y05P+duen/wswq/+cTbf8MJrL/MW35/1awQv97x43/oAra/8VRKf/qZHr/D6vN/zT+Iv9ZBXn/fkjS/6OfLf/Ioor/7enp/xI8Sv83Q63/XJYS/4Hdef+m4OL/yzdN//B6uv8VgSn/OtSa/18bDf+ELoL/qXX5/864cv/zz+3/GBJq/wC4iv8EuI3/CLiQ/wy4k/8QuJb/FLiZ/xi4nP8cuJ//ILii/yS4pf8ouKj/LLir/zC4rv80uLH/OLi0/zy4t/9AuLr/RLi9/0i4wP9MuMP/ULjG/1S4yf9YuMz/XLjP/2C40v9kuNX/aLjY/2y42/9wuN7/dLjh/3i45P98uOf/rpZE/9Pjhf/4PMj/HQkN/0JCVP9nn53/jOjo/7ElNf/WfoT/+0vV/yCEKP9F0X3/airU/49nLf+0sIj/2Y3l//7GRP8jE6X/SGwI/225bf+S8tT/t889/9wYqP8BVRX/Jq6E/0v79f9wNGj/lQHd/7paVP/fl83/BOBI/yk9xf8AvI3/BLyQ/wi8k/8MvJb/ELyZ/xS8nP8YvJ//HLyi/yC8pf8kvKj/KLyr/yy8rv8wvLH/NLy0/zi8t/88vLr/QLy9/0S8wP9IvMP/TLzG/1C8yf9UvMz/WLzP/1y80v9gvNX/ZLzY/2i82/9svN7/cLzh/3S85P94vOf/fLzq/7/zof/khuL/CVkl/y5sav9TJ7H/ePr6/52NRf/CQJL/5xvh/wwuMv8x4YX/VrTa/3tPMf+gAor/xdXl/+roQv8Po6H/NHYC/1kJZf9+3Mr/o5cx/8iqmv/tfQX/EjBy/zfL4f9cnlL/gVHF/6ZkOv/LP7H/8PIq/xWFpf86WCL/AMCQ/wTAk/8IwJb/DMCZ/xDAnP8UwJ//GMCi/xzApf8gwKj/JMCr/yjArv8swLH/MMC0/zTAt/84wLr/PMC9/0DAwP9EwMP/SMDG/0zAyf9QwMz/VMDP/1jA0v9cwNX/YMDY/2TA2/9owN7/bMDh/3DA5P90wOf/eMDq/3zA7f/Q0AD/9aVB/xp6hP8/T8n/ZAQQ/4nZWf+urqT/02Px//g4QP8dDZH/QsLk/2eXOf+MbJD/sSHp/9b2RP/7y6H/IIAA/0VVYf9qKsT/j/8p/7S0kP/Zifn//l5k/yMT0f9I6ED/bb2x/5JyJP+3R5n/3BwQ/wHRif8mpgT/S3uB/wDEk/8ExJb/CMSZ/wzEnP8QxJ//FMSi/xjEpf8cxKj/IMSr/yTErv8oxLH/LMS0/zDEt/80xLr/OMS9/zzEwP9AxMP/RMTG/0jEyf9MxMz/UMTP/1TE0v9YxNX/XMTY/2DE2/9kxN7/aMTh/2zE5P9wxOf/dMTq/3jE7f98xPD/4S1h/wZYov8rh+X/ULIq/3X5cf+aJLr/v1MF/+SeUv8JxaH/LvDy/1M/Rf94apr/nZHx/8LcSv/nC6X/DDYC/zF9Yf9WqML/e9cl/6ACiv/FSfH/6nRa/w+jxf807jL/WRWh/35AEv+jj4X/yLr6/+3hcf8SLOr/N1tl/1yG4v8AyJb/BMiZ/wjInP8MyJ//EMii/xTIpf8YyKj/HMir/yDIrv8kyLH/KMi0/yzIt/8wyLr/NMi9/zjIwP88yMP/QMjG/0TIyf9IyMz/TMjP/1DI0v9UyNX/WMjY/1zI2/9gyN7/ZMjh/2jI5P9syOf/cMjq/3TI7f94yPD/fMjz//IKxP8XfwX/PKBI/2GVjf+G3tT/qwMd/9B0aP/1ubX/GuIE/z/XVf9kGKj/iU39/662VP/T+63/+CwI/x0RZf9CWsT/Z48l/4zwiP+xJe3/1m5U//tTvf8ghCj/RcmV/2oyBP+PZ3X/tKjo/9mdXf/+xtT/IwtN/0h8yP9toUX/AMyZ/wTMnP8IzJ//DMyi/xDMpf8UzKj/GMyr/xzMrv8gzLH/JMy0/yjMt/8szLr/MMy9/zTMwP84zMP/PMzG/0DMyf9EzMz/SMzP/0zM0v9QzNX/VMzY/1jM2/9czN7/YMzh/2TM5P9ozOf/bMzq/3DM7f90zPD/eMzz/3zM9v8DZyn/KBJq/03Nrf9y+PL/l7M5/7xugv/hGc3/BtQa/yuPaf9Qurr/dXUN/5ogYv+/27n/5JYS/wlBbf8ufMr/Uzcp/3jiiv+dne3/wkhS/+cDuf8MPiL/MemN/1ak+v97X2n/oAra/8XFTf/q8ML/D6s5/zRmsv9ZES3/fsyq/wDQnP8E0J//CNCi/wzQpf8Q0Kj/FNCr/xjQrv8c0LH/INC0/yTQt/8o0Lr/LNC9/zDQwP800MP/ONDG/zzQyf9A0Mz/RNDP/0jQ0v9M0NX/UNDY/1TQ2/9Y0N7/XNDh/2DQ5P9k0Of/aNDq/2zQ7f9w0PD/dNDz/3jQ9v980Pn/FESQ/zkx0f9e7hT/g9tZ/6iQoP/NTen/8jo0/xf3gf88rND/YZkh/4ZWdP+rA8n/0Pgg//W1ef8aYtT/P18x/2QUkP+JwfH/rr5U/9Nruf/4ICD/HR2J/0LK9P9nh2H/jHzQ/7EpQf/W5rT/+9Mp/yCIoP9FRRn/ajKU/4/vEf8A1J//BNSi/wjUpf8M1Kj/ENSr/xTUrv8Y1LH/HNS0/yDUt/8k1Lr/KNS9/yzUwP8w1MP/NNTG/zjUyf881Mz/QNTP/0TU0v9I1NX/TNTY/1DU2/9U1N7/WNTh/1zU5P9g1Of/ZNTq/2jU7f9s1PD/cNTz/3TU9v941Pn/fNT8/yWh+f9K1Dr/bwt9/5Q+wv+5dQn/3qhS/wPfnf8oEur/TUk5/3J8iv+Xs93/vOYy/+Edif8GUOL/K4c9/1C6mv918fn/miRa/79bvf/kjiL/CcWJ/y748v9TL13/eGLK/52ZOf/CzKr/5wMd/ww2kv8xbQn/VqCC/3vX/f+gCnr/ANii/wTYpf8I2Kj/DNir/xDYrv8U2LH/GNi0/xzYt/8g2Lr/JNi9/yjYwP8s2MP/MNjG/zTYyf842Mz/PNjP/0DY0v9E2NX/SNjY/0zY2/9Q2N7/VNjh/1jY5P9c2Of/YNjq/2TY7f9o2PD/bNjz/3DY9v902Pn/eNj8/3zY//82vmT/W8ul/4AU6P+lIS3/ymp0/++3vf8UwAj/OQ1V/15WpP+DY/X/qKxI/835nf/yAvT/F09N/zyYqP9hpQX/hu5k/6s7xf/QRCj/9ZGN/xra9P8/513/ZDDI/4l9Nf+uhqT/09MV//gciP8dKf3/QnJ0/2e/7f+MyGj/sRXl/wDcpf8E3Kj/CNyr/wzcrv8Q3LH/FNy0/xjct/8c3Lr/INy9/yTcwP8o3MP/LNzG/zDcyf803Mz/ONzP/zzc0v9A3NX/RNzY/0jc2/9M3N7/UNzh/1Tc5P9Y3Of/XNzq/2Dc7f9k3PD/aNzz/2zc9v9w3Pn/dNz8/3jc//983AL/R5vR/2zuEv+RMVX/tgSa/9tP4f8Akir/JeV1/0oowv9vcxH/lEZi/7mJtf/e3Ar/Aydh/yhquv9NvRX/coBy/5fL0f+8HjL/4WGV/wa0+v8r/2H/UMLK/3UVNf+aWKL/v6MR/+T2gv8JOfX/Lgxq/1NX4f94mlr/ne3V/8IwUv8A4Kj/BOCr/wjgrv8M4LH/EOC0/xTgt/8Y4Lr/HOC9/yDgwP8k4MP/KODG/yzgyf8w4Mz/NODP/zjg0v884NX/QODY/0Tg2/9I4N7/TODh/1Dg5P9U4Of/WODq/1zg7f9g4PD/ZODz/2jg9v9s4Pn/cOD8/3Tg//944AL/fOAF/1j4QP99jYH/olLE/8dnCf/sLFD/EfGZ/zaG5P9bSzH/gBCA/6Ul0f/K6iT/7795/xRE0P85CSn/Xt6E/4Pj4f+oqED/zX2h//ICBP8X12n/PJzQ/2GhOf+GdqT/qzsR/9DAgP/1lfH/Glpk/z9v2f9kNFD/ifnJ/66ORP/TU8H/AOSr/wTkrv8I5LH/DOS0/xDkt/8U5Lr/GOS9/xzkwP8g5MP/JOTG/yjkyf8s5Mz/MOTP/zTk0v845NX/POTY/0Dk2/9E5N7/SOTh/0zk5P9Q5Of/VOTq/1jk7f9c5PD/YOTz/2Tk9v9o5Pn/bOT8/3Dk//905AL/eOQF/3zkCP9p1bH/jqDy/7N/Nf/YSnr//QHB/yLcCv9Hq1X/bGai/5E98f+2CEL/28eV/wCS6v8laUH/SiSa/2/z9f+UzlL/uYWx/95QEv8DL3X/KPra/02xQf9yjKr/l1sV/7wWgv/h7fH/Brhi/yt31f9QQkr/dRnB/5rUOv+/o7X/5H4y/wDorv8E6LH/COi0/wzot/8Q6Lr/FOi9/xjowP8c6MP/IOjG/yToyf8o6Mz/LOjP/zDo0v806NX/OOjY/zzo2/9A6N7/ROjh/0jo5P9M6Of/UOjq/1To7f9Y6PD/XOjz/2Do9v9k6Pn/aOj8/2zo//9w6AL/dOgF/3joCP986Av/ejIk/59HZf/EmKj/6a3t/w7mNP8zO33/WEzI/32BFf+i2mT/x++1/+wgCP8RdV3/No60/1vDDf+AFGj/pSnF/8piJP/vt4X/FMjo/zkdTf9eVrT/g2sd/6i8iP/N8fX/8gpk/xdf1f88kEj/YaW9/4b+NP+rM63/0EQo//WZpf8A7LH/BOy0/wjst/8M7Lr/EOy9/xTswP8Y7MP/HOzG/yDsyf8k7Mz/KOzP/yzs0v8w7NX/NOzY/zjs2/887N7/QOzh/0Ts5P9I7Of/TOzq/1Ds7f9U7PD/WOzz/1zs9v9g7Pn/ZOz8/2js//9s7AL/cOwF/3TsCP947Av/fOwO/4sPmf+wetr/1aUd//qQYv8f26n/RAby/2lxPf+OvIr/s+fZ/9jSKv/9HX3/IkjS/0ezKf9s/oL/kSnd/7YUOv/bX5n/AIr6/yX1Xf9KIML/b2sp/5RWkv+5gf3/3sxq/wM32f8oYkr/Ta29/3KYMv+Xw6n/vA4i/+F5nf8GpBr/APC0/wTwt/8I8Lr/DPC9/xDwwP8U8MP/GPDG/xzwyf8g8Mz/JPDP/yjw0v8s8NX/MPDY/zTw2/848N7/PPDh/0Dw5P9E8Of/SPDq/0zw7f9Q8PD/VPDz/1jw9v9c8Pn/YPD8/2Tw//9o8AL/bPAF/3DwCP908Av/ePAO/3zwEf+cbBD/wRlR/+bGlP8L89n/MLgg/1Vlaf96ErT/n98B/8SEUP/psaH/Dn70/zMrSf9Y0KD/fZ35/6JKVP/Hd7H/7DwQ/xHpcf82ltT/W0M5/4AIoP+lNQn/yuJ0/++v4f8UVFD/OQHB/17ONP+D+6n/qKAg/81tmf/yGhT/F8eR/wD0t/8E9Lr/CPS9/wz0wP8Q9MP/FPTG/xj0yf8c9Mz/IPTP/yT00v8o9NX/LPTY/zD02/809N7/OPTh/zz05P9A9Of/RPTq/0j07f9M9PD/UPTz/1T09v9Y9Pn/XPT8/2D0//9k9AL/aPQF/2z0CP9w9Av/dPQO/3j0Ef989BT/rUmJ/9I8yv/34w3/HNZS/0Gdmf9mQOL/izct/7D6ev/Vocn/+pQa/x9bbf9EDsL/afUZ/464cv+zb83/2FIq//0Zif8izOr/R7NN/2xmsv+RLRn/thCC/9vH7f8Ailr/JXHJ/0okOv9v663/lN4i/7mFmf/eSBL/Az+N/yjiCv8A+Lr/BPi9/wj4wP8M+MP/EPjG/xT4yf8Y+Mz/HPjP/yD40v8k+NX/KPjY/yz42/8w+N7/NPjh/zj45P88+Of/QPjq/0T47f9I+PD/TPjz/1D49v9U+Pn/WPj8/1z4//9g+AL/ZPgF/2j4CP9s+Av/cPgO/3T4Ef94+BT/fPgX/76mBP/j00X/CAyI/y05zf9SchT/d69d/5zYqP/BFfX/5k5E/wt7lf8wtOj/VeE9/3oalP+fV+3/xIBI/+m9pf8O9gT/MyNl/1hcyP99iS3/osKU/8f//f/sKGj/EWXV/zaeRP9by7X/gAQo/6Uxnf/KahT/76eN/xTQCP85DYX/APy9/wT8wP8I/MP/DPzG/xD8yf8U/Mz/GPzP/xz80v8g/NX/JPzY/yj82/8s/N7/MPzh/zT85P84/Of/PPzq/0D87f9E/PD/SPzz/0z89v9Q/Pn/VPz8/1j8//9c/AL/YPwF/2T8CP9o/Av/bPwO/3D8Ef90/BT/ePwX/3z8Gv/Pg4H/9PbC/xkpBf8+HEr/Y1eR/4iK2v+t/SX/0jBy//drwf8cXhL/QZFl/2bEuv+LPxH/sHJq/9Wlxf/6mCL/H9OB/0QG4v9peUX/jqyq/7PnEf/Y2nr//Q3l/yJAUv9Hu8H/bO4y/5Ehpf+2FBr/20+R/wCCCv8l9YX/SigC/w==", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/FormatRegistry.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/FormatRegistry.kt new file mode 100644 index 0000000..d2f436a --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/FormatRegistry.kt @@ -0,0 +1,107 @@ +package org.umamo.format + +import org.umamo.format.bmp.BmpCodec +import org.umamo.format.clip.ClipReader +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.jpeg.JpegReader +import org.umamo.format.kra.KraReader +import org.umamo.format.moc3.Moc3 +import org.umamo.format.png.PngCodec +import org.umamo.format.psd.PsdReader +import org.umamo.format.tiff.TiffReader +import org.umamo.format.uma.Uma +import org.umamo.format.webp.WebPReader + +/** + * The registry of binary container codecs Umamo can read/write, and the entry point for dispatching + * an unknown file to the right one. + * + * Lives in `jvmAndroidMain` because it references [Cmo3], whose JDOM/reflection serializer is + * JVM-only (it still sees the commonMain [Moc3]). Holds heterogeneous `FormatCodec<*>` since the + * models share no supertype; a caller does `detect(bytes)?.read(bytes)` and then branches on the + * returned model type or the codec's [FormatCodec.kind]. Text sidecars (`model3.json` etc.) are + * not registered here - they are `String`-shaped and live as helpers on [Moc3]. + */ +public object FormatRegistry { + /** + * Every registered codec, in priority order (first magic match wins in [detect]): the native UMA + * container, the model codecs (CMO3, MOC3), the layered art readers (CLIP, KRA, PSD), and the flat raster + * codecs (PNG, BMP, JPEG, WebP, TIFF). The registry sits in jvmAndroidMain because the CMO3 codec does. + * The magics do not collide: UMA and KRA are both ZIPs announcing themselves through a mimetype entry, + * but each probe matches only its own mimetype string. The raster codecs sit last, so BMP's short + * 2-byte "BM" magic is checked after the longer signatures. + */ + private val codecs: List> = + listOf(Uma, Cmo3, Moc3, ClipReader, KraReader, PsdReader, PngCodec, BmpCodec, JpegReader, WebPReader, TiffReader) + + /** + * Identifies the codec for [bytes], preferring a reliable magic-byte match and falling back to the + * file extension when no codec recognises the leading bytes. + * + * Magic comes first because it is content-truthful - a mislabelled file still routes correctly. + * The extension fallback exists for container formats whose magic is not self-identifying (e.g. a + * ZIP-based .kra whose mimetype marker a third-party tool stripped), where the name is the only + * remaining signal. [fileName] may be a bare name or a full path; only its extension is read. + * + * @param ByteArray bytes The file contents to identify. + * @param String? fileName The file name or path, used only for the extension fallback. + * @return FormatCodec<*>? The matching codec, or null when unrecognised. + */ + public fun detect(bytes: ByteArray, fileName: String? = null): FormatCodec<*>? { + codecs.firstOrNull { codec -> codec.matches(bytes) }?.let { return it } + val kind = fileName?.let(::kindForFileName) ?: return null + return forKind(kind) + } + + /** + * Identifies a file kind from its name alone - the extension or one of its aliases, case-insensitively. + * + * Name-only, so it says nothing about whether the bytes are what the name claims: this answers "which + * way in does this path take" for a caller holding a path and no contents (a command-line argument, a + * file the OS hands over, a dropped file), and it is the extension fallback [detect] uses once the + * magic has not matched. The chosen route then reads the file and detects its content for real. + * + * @param String fileName The file name or path; only its extension is read. + * @return FileKind? The kind that claims that extension, or null when none does. + */ + public fun kindForFileName(fileName: String): FileKind? { + val extension = fileName.substringAfterLast('.', "").lowercase() + if (extension.isEmpty()) { + return null + } + return codecs.map { codec -> codec.kind } + .firstOrNull { kind -> kind.extension == extension || extension in kind.extensionAliases } + } + + /** + * Returns the registered codec for [kind], or null when no codec is wired for it yet (e.g. the + * JSON kind, which has no registered codec). + * + * @param FileKind kind The file kind to look up. + * @return FormatCodec<*>? The codec for that kind, or null. + */ + public fun forKind(kind: FileKind): FormatCodec<*>? = codecs.firstOrNull { codec -> codec.kind == kind } + + /** + * The file extensions Umamo can read, derived from the registered codecs - the single source of + * truth for an open-file picker's filter list (so it tracks the registry instead of a frozen list). + * + * @return List the distinct readable extensions, without the leading dot. + */ + public fun readableExtensions(): List = + codecs.filter { codec -> codec.kind.readable }.map { codec -> codec.kind.extension }.distinct() + + /** + * The file extensions of every registered kind that takes [role], aliases included - the single source + * of truth for a picker filter over one way in (e.g. Import Artwork's filter, which is every art format + * the registry reads and nothing else). + * + * @param FileRole role The way in to filter by. + * @return List the distinct extensions, without the leading dot, in registry order. + */ + public fun extensionsFor(role: FileRole): List = + codecs.map { codec -> codec.kind } + .filter { kind -> kind.role == role } + .flatMap { kind -> listOf(kind.extension) + kind.extensionAliases } + .distinct() +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3.kt new file mode 100644 index 0000000..0688287 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3.kt @@ -0,0 +1,358 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.FileKind +import org.umamo.format.FormatCodec +import org.umamo.format.FormatVersion +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.caff.CaffEntry +import org.umamo.format.cmo3.caff.CompressOption +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.serialize.ModelGraph +import org.umamo.format.cmo3.serialize.cubismEngine +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File + +/** + * A loaded CMO3: the CAFF container (all entries, incl. layer/atlas/icon PNGs) and the typed model + * graph (the CModelSource root plus the shared pool). Mutate the graph or layer images, then write. + * + * @see CMO3.md + */ +public class Cmo3Model internal constructor( + /** The container; replaced in place when layer images change. */ + public var archive: CaffArchive, + internal val graph: ModelGraph, +) { + /** The model root (a org.umamo.format.cmo3.model.custom.CModelSource), or null. */ + public val root: Any? get() = graph.root + + /** The model's raw authored SDK target version, or null when the document carries none. */ + public val targetVersionNo: Int? + // CMO3: CModelSource field targetVersionNo. + get() = (root as? CModelSource)?.targetVersionNo as? Int + + /** + * Sets the model's authored SDK target version so it survives a re-emit even when the source + * document carried no targetVersionNo element. The writer replays the child slots recorded at + * read time, so a bare field assignment on such a document would be dropped silently; this also + * records the missing slot, positioned where the editor writes the field (immediately before + * latestVersionOfLastModelerNo). + * + * @param Int versionNo The raw targetVersionNo value to persist. + */ + public fun setTargetVersionNo(versionNo: Int) { + // CMO3: CModelSource field targetVersionNo. + val modelSource = root as? CModelSource ?: error("model root is not a CModelSource") + modelSource.targetVersionNo = versionNo + graph.ensureKnownChildSlot( + owner = modelSource, + tag = "CModelSource", + propertyName = "targetVersionNo", + beforePropertyName = "latestVersionOfLastModelerNo", + ) + } + + /** All [CImageResource]s reachable in the model (shared pool + inline), each linking an embedded PNG. */ + public fun imageResources(): List { + val seen = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + val out = ArrayList() + val stack = ArrayDeque() + graph.root?.let(stack::addLast) + graph.sharedOrder.forEach(stack::addLast) + while (stack.isNotEmpty()) { + val obj = stack.removeLast() ?: continue + if (obj is CharSequence || obj is Number || obj is Boolean || obj is Char || obj is Enum<*>) continue + if (!seen.add(obj)) continue + if (obj is CImageResource) out.add(obj) + when (obj) { + is Iterable<*> -> obj.forEach(stack::addLast) + is Map<*, *> -> obj.values.forEach(stack::addLast) + is Array<*> -> obj.forEach(stack::addLast) + else -> + if (obj::class.java.name.startsWith(MODEL_PACKAGE)) { + var cls: Class<*>? = obj::class.java + while (cls != null && cls != Any::class.java) { + for (field in cls.declaredFields) { + if (java.lang.reflect.Modifier.isStatic(field.modifiers)) continue + field.isAccessible = true + stack.addLast(field.get(obj)) + } + cls = cls.superclass + } + } + } + } + return out + } + + private companion object { + const val MODEL_PACKAGE = "org.umamo.format.cmo3.model" + } + + /** + * Returns the decoded PNG bytes backing [resource], or null if it has no embedded file. + * + * @param CImageResource resource A model image resource. + * @return ByteArray? The PNG bytes, or null. + */ + public fun extractLayerPng(resource: CImageResource): ByteArray? { + val path = resource.imageFileBuf?.archivePath ?: return null + return archive.byPath(path)?.content + } + + /** + * Replaces [resource]'s embedded PNG with [png] (same dimensions expected) and updates its size. + * + * @param CImageResource resource The image resource to update. + * @param ByteArray png The new PNG bytes. + */ + public fun replaceLayerPng(resource: CImageResource, png: ByteArray) { + val path = resource.imageFileBuf?.archivePath ?: error("resource has no embedded imageFileBuf") + replacePng(path, png) + resource.imageFileBuf_size = png.size // keep main.xml's size attribute consistent + } + + /** + * Replaces the embedded PNG at [path] with [png], keeping the entry's place, tag, and options. + * + * The graph node that references the path is the caller's to keep consistent; an icon's + * CWritableImage carries no size field, a layer's CImageResource does ([replaceLayerPng]). + * + * @param String path The archive path of an existing entry. + * @param ByteArray png The new PNG bytes. + */ + public fun replacePng(path: String, png: ByteArray) { + require(archive.byPath(path) != null) { "archive holds no entry at '$path'" } + archive = + archive.withEntries( + archive.entries.map { entry -> + if (entry.path == path) CaffEntry(entry.path, entry.tag, png, entry.compression, entry.obfuscated) else entry + }, + ) + } + + /** + * Embeds a NEW PNG for [resource], whose `imageFileBuf` must already name an archive path no + * existing entry uses (mint one with [nextImageFileBufPath]). + * + * The entry takes the corpus conventions for pixel data - an empty tag, stored raw (a PNG is + * already compressed), and obfuscated like every corpus entry - and is inserted BEFORE the + * `main_xml` entry, which every corpus file keeps last in the table. + * + * @param CImageResource resource The image resource naming the new entry's path. + * @param ByteArray png The PNG bytes to embed. + */ + public fun addLayerPng(resource: CImageResource, png: ByteArray) { + val path = resource.imageFileBuf?.archivePath ?: error("resource has no imageFileBuf path to add under") + addPng(path, png) + resource.imageFileBuf_size = png.size // keep main.xml's size attribute consistent + } + + /** + * Embeds a NEW PNG at [path], which no existing entry may use (mint one with + * [nextImageFileBufPath] for a layer or page buffer, [nextImagePath] for an icon). + * + * The entry takes the corpus conventions for pixel data - an empty tag, stored raw (a PNG is + * already compressed), and obfuscated like every corpus entry - and is inserted BEFORE the + * `main_xml` entry, which every corpus file keeps last in the table. The graph node that + * references the path is the caller's to wire; an icon's CWritableImage carries no size field, so + * there is nothing here to keep consistent. + * + * @param String path The archive path the entry is stored under. + * @param ByteArray png The PNG bytes to embed. + */ + public fun addPng(path: String, png: ByteArray) { + require(archive.byPath(path) == null) { "archive already holds an entry at '$path'" } + val mainXmlIndex = archive.entries.indexOfFirst { entry -> entry.tag == CaffArchive.TAG_MAIN_XML } + val insertAt = if (mainXmlIndex >= 0) mainXmlIndex else archive.entries.size + val entries = archive.entries.toMutableList() + entries.add(insertAt, CaffEntry(path, "", png, CompressOption.RAW, obfuscated = true)) + archive = archive.withEntries(entries) + } + + /** + * Removes [resource]'s embedded PNG from the archive. + * + * The caller owns unlinking the graph: an archive entry a live resource still references is a + * load-time hazard, so remove the entry only together with dropping the resource itself. + * + * @param CImageResource resource The image resource whose entry to remove. + */ + public fun removeLayerPng(resource: CImageResource) { + val path = resource.imageFileBuf?.archivePath ?: error("resource has no embedded imageFileBuf") + archive = archive.withEntries(archive.entries.filterNot { entry -> entry.path == path }) + } + + /** + * Mints the next unused `imageFileBuf` archive path, continuing past the retained archive's + * highest suffix. + * + * The editor's convention is `imageFileBuf.png`, then `imageFileBuf_0.png` onward; resolution is + * by exact name, so continuing past the maximum is what keeps a minted page from colliding with + * any retained blob. + * + * @return String The unused archive path. + */ + public fun nextImageFileBufPath(): String = nextPathInSequence("imageFileBuf") + + /** + * Mints the next unused `image` archive path - the editor's icon-thumbnail sequence (`image.png`, + * then `image_0.png` onward), continuing past the retained archive's highest suffix, by the same + * rule as [nextImageFileBufPath]. + * + * @return String The unused archive path. + */ + public fun nextImagePath(): String = nextPathInSequence("image") + + /** + * The next unused path in one of the editor's de-dupe sequences: `.png`, then + * `_0.png` onward. Resolution is by exact name, so continuing past the maximum is what + * keeps a minted entry from colliding with any retained blob. + * + * @param String stem The sequence's stem. + * @return String The unused archive path. + */ + private fun nextPathInSequence(stem: String): String { + var highestUsed = -2 + for (entry in archive.entries) { + if (entry.path == "$stem.png") { + highestUsed = maxOf(highestUsed, -1) + } else { + val suffix = + entry.path + .removePrefix("${stem}_") + .removeSuffix(".png") + .takeIf { middle -> "${stem}_$middle.png" == entry.path } + ?.toIntOrNull() + if (suffix != null) { + highestUsed = maxOf(highestUsed, suffix) + } + } + } + val next = highestUsed + 1 + return if (next == -1) "$stem.png" else "${stem}_$next.png" + } +} + +/** + * Reads and writes Live2D Cubism `.cmo3` files (the CAFF container + the typed model graph). + * + * EN: `read` parses the container and deserializes main.xml into the typed model; `write` re-emits + * the model into main.xml and repacks the container. Round-trip is byte-identical for unedited + * files. Implements [FormatCodec] for `.cmo3`; the `File`-taking overloads are JVM-only + * conveniences on top of the byte-array contract. JVM/Android only (uses reflection + JDOM). + * + * @see CMO3.md + */ +public object Cmo3 : FormatCodec { + /** This codec handles [FileKind.Cmo3]. */ + override val kind: FileKind get() = FileKind.Cmo3 + + /** + * True if [candidateBytes] starts with the CAFF magic. Note that every CAFF container sniffs the + * same way; a `.cmo3` is distinguished from other CAFF files only on full [read] (the `main_xml` + * entry). Good enough for dispatch among the formats Umamo registers. + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether this looks like a CAFF container. + */ + override fun matches(candidateBytes: ByteArray): Boolean = CaffCodec.isCaff(candidateBytes) + + /** + * Cheap version probe: decodes only the `main_xml` entry and reads the `` + * attribute, skipping the embedded layer PNGs and the full XML/object-graph deserialization. + * + * @param ByteArray bytes The complete file contents. + * @return FormatVersion? The CMO3 generation, or null when this is not a readable `.cmo3`. + */ + override fun getVersion(bytes: ByteArray): FormatVersion? { + if (!CaffCodec.isCaff(bytes)) { + return null + } + // A probe never throws: a truncated or corrupt container reports null instead. + val mainXml = + runCatching { CaffCodec.readFirstEntryByTag(bytes, CaffArchive.TAG_MAIN_XML)?.content }.getOrNull() + ?: return null + val rawVersion = extractFileFormatVersion(mainXml) ?: return null + return Cmo3Version.fromFileFormatVersion(rawVersion) + } + + /** + * Scans decoded main.xml bytes for the ASCII `fileFormatVersion="..."` root attribute and returns + * its value, without decoding the multi-megabyte document to a String or parsing the XML. + * + * @param ByteArray mainXml The decoded main.xml bytes (UTF-8; the attribute is plain ASCII). + * @return String? The attribute text, or null when absent. + */ + private fun extractFileFormatVersion(mainXml: ByteArray): String? { + // CMO3.md §3 Document shape: . + val needle = "fileFormatVersion=\"".encodeToByteArray() + val quoteByte = '"'.code.toByte() + val lastNeedleStart = mainXml.size - needle.size + var scanIndex = 0 + scan@ while (scanIndex <= lastNeedleStart) { + for (needleIndex in needle.indices) { + if (mainXml[scanIndex + needleIndex] != needle[needleIndex]) { + scanIndex++ + continue@scan + } + } + val valueStart = scanIndex + needle.size + var valueEnd = valueStart + while (valueEnd < mainXml.size && mainXml[valueEnd] != quoteByte) { + valueEnd++ + } + if (valueEnd >= mainXml.size) { + return null + } + return mainXml.decodeToString(valueStart, valueEnd) + } + return null + } + + /** + * Parses a `.cmo3` from raw bytes. + * + * @param ByteArray bytes The file contents. + * @return Cmo3Model The loaded model. + */ + override fun read(bytes: ByteArray): Cmo3Model { + val archive = CaffCodec.read(bytes) + val mainXml = + archive.firstByTag(CaffArchive.TAG_MAIN_XML)?.content + ?: error("not a CMO3: no main_xml entry") + val graph = cubismEngine().readModel(XmlCodec.parse(mainXml)) + return Cmo3Model(archive, graph) + } + + /** Parses a `.cmo3` from a file. */ + public fun read(file: File): Cmo3Model = read(file.readBytes()) + + /** + * Serializes a model back to `.cmo3` bytes. + * + * @param Cmo3Model model The model to write. + * @return ByteArray The complete `.cmo3` file bytes. + */ + override fun write(model: Cmo3Model): ByteArray { + val document = cubismEngine().writeModel(model.graph) + // Classes first introduced after the read (created entities) are missing from the replayed + // / PIs, and the official reader cannot resolve their tags without them. + Cmo3Author.completePrologue(document) + val mainXml = XmlCodec.write(document) + val entries = + model.archive.entries.map { entry -> + if (entry.tag == CaffArchive.TAG_MAIN_XML) { + CaffEntry(entry.path, entry.tag, mainXml, entry.compression, entry.obfuscated) + } else { + entry + } + } + return CaffCodec.write(model.archive.withEntries(entries)) + } + + /** Writes a model to a `.cmo3` file. */ + public fun write(model: Cmo3Model, file: File): Unit = file.writeBytes(write(model)) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3Author.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3Author.kt new file mode 100644 index 0000000..b575d53 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3Author.kt @@ -0,0 +1,150 @@ +package org.umamo.format.cmo3 + +import org.jdom.Document +import org.jdom.Element +import org.jdom.ProcessingInstruction +import org.umamo.format.cmo3.serialize.cubismEngine +import org.umamo.format.cmo3.xml.XmlCodec + +/** + * Authors a main.xml for a NEVER-READ object graph, producing the full editor prologue that + * `SerializeEngine.writeRoot` alone cannot: the `fileFormatVersion` root attribute, the + * `` class-version PIs, and the `` tag-to-FQCN PIs (docs/format/CMO3.md §3 + * Document Shape). Read graphs never come through here - `Cmo3.write` replays their recorded + * prologue verbatim; this is the entry point for fresh-graph synthesis (a from-scratch CMO3 for a + * MOC3-origin document), whose bytes are then wrapped in a CAFF archive and fed back through + * `Cmo3.read` to obtain a reconcilable [Cmo3Model]. + */ +public object Cmo3Author { + /** + * The fileFormatVersion a fresh document writes. + * + * CMO3: root attribute fileFormatVersion (BareMinimum.cmo3, official editor 5.4 New -> Save + * As). Pinned to the 5.4 era because the prologue tables (Cmo3PiTables) are transcribed from + * the 504000000 corpus samples; changing one without the other would author a mismatched + * prologue. + */ + public const val FRESH_FILE_FORMAT_VERSION: String = "504000000" + + /** + * Serializes [root] as a complete main.xml document with the 5.4-era prologue. + * + * The `` list is derived from the document itself: one FQCN per distinct + * non-structural element tag actually emitted, sorted - exactly the rule every corpus file + * follows. An element tag with no FQCN table entry is a hard error: it means an unregistered + * or newly modeled class whose import the official editor's reader would miss. + * + * @param Any root The fresh model root (a CModelSource web built in memory, never read). + * @return ByteArray The UTF-8 main.xml bytes, CRLF-framed like the editor's writer. + */ + public fun writeFreshMainXml(root: Any): ByteArray { + val document = cubismEngine().writeRoot(root) + val tags = HashSet() + collectTags(document.rootElement, tags) + val modelTags = tags - CMO3_STRUCTURAL_TAGS + val imports = + modelTags + .map { tag -> + CMO3_TAG_TO_FQCN[tag] + ?: error("element tag <$tag> has no FQCN table entry; add it to Cmo3PiTables from a corpus sample") + } + .sorted() + // CMO3: PIs - the always-written pair, then per-tag entries in a + // deterministic (sorted-tag) order; the editor's own order is HashMap iteration and not + // reproducible, and readers key these by name. + val versions = ArrayList(CMO3_VERSIONS_ALWAYS_5_4) + for (tag in modelTags.sorted()) { + CMO3_VERSIONS_BY_TAG_5_4[tag]?.let { versionEntry -> versions.add(versionEntry) } + } + // CMO3: root attribute fileFormatVersion - the root's only attribute in every corpus file. + document.rootElement.setAttribute("fileFormatVersion", FRESH_FILE_FORMAT_VERSION) + var instructionIndex = 0 + for ((piName, versionNumber) in versions) { + document.addContent(instructionIndex++, ProcessingInstruction("version", "$piName:$versionNumber")) + } + for (fqcn in imports) { + document.addContent(instructionIndex++, ProcessingInstruction("import", fqcn)) + } + return XmlCodec.write(document) + } + + /** + * Reconciles a written document's prologue PIs with the tags it actually contains. + * + * `Cmo3.write` replays the prologue recorded at read time, which is complete for an unedited + * graph but misses any class first introduced AFTER the read - a session-created glue in a + * glue-less document, or the whole created population of a fresh-graph (MOC3-origin) export. + * The official reader resolves element tags through the `` list, so a missing import + * makes the file unreadable in the editor. This pass restores the corpus invariant: the + * import list is exactly one sorted FQCN per distinct non-structural tag (an import whose tag + * left the document is pruned; corpus files never carry stale imports). Version PIs are only + * ever APPENDED (5.4-era documents only - the per-tag numbers are era-specific), never pruned: + * corpus files do carry version PIs for classes with no matching element (BareMinimum's + * ModelStateSet:1), so pruning would break replay byte-identity. + * + * A document whose prologue is already complete is left untouched, keeping the unedited + * round trip byte-identical. + * + * @param Document document The written model document (mutated in place). + */ + public fun completePrologue(document: Document) { + val tags = HashSet() + collectTags(document.rootElement, tags) + val modelTags = tags - CMO3_STRUCTURAL_TAGS + + val instructions = document.content.filterIsInstance() + val versionInstructions = instructions.filter { it.target == "version" } + val importInstructions = instructions.filter { it.target == "import" } + val replayedImports = importInstructions.map { it.data.trim() } + val replayedFqcnByTag = replayedImports.associateBy { fqcn -> fqcn.substringAfterLast('.').substringAfterLast('$') } + val desiredImports = + modelTags + .map { tag -> + // The document's own spelling wins - the 5.4 table only fills tags the read + // never saw, so an older era's package layout is never rewritten. + replayedFqcnByTag[tag] + ?: CMO3_TAG_TO_FQCN[tag] + ?: error("element tag <$tag> has no FQCN table entry and no replayed import; add it to Cmo3PiTables from a corpus sample") + } + .sorted() + + val replayedVersionNames = versionInstructions.map { it.data.trim().substringBeforeLast(':') }.toHashSet() + val fileFormatVersion = document.rootElement.getAttributeValue("fileFormatVersion") + val appendedVersions = + if (fileFormatVersion == FRESH_FILE_FORMAT_VERSION) { + modelTags.sorted().mapNotNull { tag -> + CMO3_VERSIONS_BY_TAG_5_4[tag]?.takeIf { (piName, _) -> piName !in replayedVersionNames } + } + } else { + emptyList() + } + + if (desiredImports == replayedImports && appendedVersions.isEmpty()) { + return + } + for (instruction in importInstructions) { + document.removeContent(instruction) + } + var instructionIndex = + versionInstructions.lastOrNull()?.let { instruction -> document.indexOf(instruction) + 1 } ?: 0 + for ((piName, versionNumber) in appendedVersions) { + document.addContent(instructionIndex++, ProcessingInstruction("version", "$piName:$versionNumber")) + } + for (fqcn in desiredImports) { + document.addContent(instructionIndex++, ProcessingInstruction("import", fqcn)) + } + } + + /** + * Collects every element name in the subtree into [into]. + * + * @param Element element The subtree root. + * @param HashSet into The tag collector. + */ + private fun collectTags(element: Element, into: HashSet) { + into.add(element.name) + for (child in element.children) { + collectTags(child as Element, into) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3GraphEditor.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3GraphEditor.kt new file mode 100644 index 0000000..4204157 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3GraphEditor.kt @@ -0,0 +1,169 @@ +package org.umamo.format.cmo3 + +import org.jdom.Element +import org.umamo.format.cmo3.serialize.ATTR_REF +import org.umamo.format.cmo3.serialize.ChildSlot +import org.umamo.format.cmo3.serialize.ModelGraph +import org.umamo.format.cmo3.serialize.VerbatimNode + +/** + * Mutation support for a read [Cmo3Model]'s graph, for callers lowering editor state back onto it. + * + * The writer replays each read object's recorded child order and attribute presence, so a plain + * field assignment only reaches the re-emitted document when the source already carried that + * element/attribute. This facade exposes the bookkeeping a lowering needs on top of the bare + * assignments: recording missing slots/attributes, distinguishing read objects from fresh ones, + * and dropping shared-pool entries orphaned by structural deletes. + * + * @see Cmo3Model.setTargetVersionNo The original single-field precedent this generalizes. + */ +public class Cmo3GraphEditor internal constructor(private val graph: ModelGraph) { + /** + * Ensures the child element for [propertyName] of [owner] (at the [tag] serializer level) is + * emitted on write even when the source document carried no such element. Call after assigning + * a field the source omitted; without the slot the writer drops the assignment silently. No-op + * for fresh objects (they have no recorded order and already emit every declared field). + * + * @param Any owner The object whose recorded child order is amended. + * @param String tag The serializer tag level the order was recorded under. + * @param String propertyName The Kotlin property name of the assigned field. + * @param String? beforePropertyName The property to insert before (where the editor writes the + * field), or null to append. + */ + public fun ensureChildSlot(owner: Any, tag: String, propertyName: String, beforePropertyName: String? = null) { + graph.ensureKnownChildSlot(owner, tag, propertyName, beforePropertyName) + } + + /** + * Ensures the @SerialAttribute property [propertyName] of [owner] (at the [tag] serializer level) + * is emitted on write even when the source document omitted the attribute. The attribute twin of + * [ensureChildSlot]; attributes emit in declaration order, so no anchor is needed. No-op when no + * attribute record exists (the writer then already emits every non-default attribute value). + * + * @param Any owner The object whose attribute record is amended. + * @param String tag The serializer tag level the record was captured under. + * @param String propertyName The Kotlin property name of the assigned attribute. + */ + public fun ensurePresentAttr(owner: Any, tag: String, propertyName: String) { + graph.ensurePresentAttr(owner, tag, propertyName) + } + + /** + * True when [owner] has a recorded child order at the [tag] level, i.e. it was read from the + * source document. A fresh object has no record and emits super + every declared field in + * declaration order, honoring the serializer's default-skipping annotations. + * + * @param Any owner The object to query. + * @param String tag The serializer tag level. + * @return Boolean Whether a recorded order exists. + */ + public fun hasRecordedOrder(owner: Any, tag: String): Boolean = graph.childOrder[owner]?.get(tag) != null + + /** + * Drops shared-pool entries no longer reachable from the model root, after structural deletes + * removed the objects that referenced them. Survivors keep their preserved xs.id and xs.idx + * (the reader keys the pool by id, so index gaps are tolerated). Reachability follows typed + * fields, collections, and xs.ref attributes inside verbatim subtrees, so partially-typed + * documents never lose a pool entry their untyped content still references. + */ + public fun pruneUnreachableShared() { + val sharedById = HashMap() + for (instance in graph.sharedOrder) { + graph.sharedInfo[instance]?.let { sharedRef -> sharedById[sharedRef.id] = instance } + } + val reachable = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + val stack = ArrayDeque() + graph.root?.let(stack::addLast) + while (stack.isNotEmpty()) { + val obj = stack.removeLast() ?: continue + if (obj is CharSequence || obj is Number || obj is Boolean || obj is Char || obj is Enum<*>) { + continue + } + if (!reachable.add(obj)) { + continue + } + // xs.ref attributes inside this object's verbatim children target pool entries no typed + // field holds; those targets stay live. + graph.childOrder[obj]?.values?.forEach { slotsAtTag -> + for (slot in slotsAtTag) { + if (slot is ChildSlot.VerbatimChild) { + addVerbatimRefTargets(slot.element, sharedById, stack) + } + } + } + when (obj) { + is VerbatimNode -> addVerbatimRefTargets(obj.element, sharedById, stack) + is Iterable<*> -> obj.forEach(stack::addLast) + is Map<*, *> -> { + obj.keys.forEach(stack::addLast) + obj.values.forEach(stack::addLast) + } + + is Array<*> -> obj.forEach(stack::addLast) + else -> + if (shouldWalkFields(obj)) { + var currentClass: Class<*>? = obj::class.java + while (currentClass != null && currentClass != Any::class.java) { + for (field in currentClass.declaredFields) { + if (java.lang.reflect.Modifier.isStatic(field.modifiers)) { + continue + } + field.isAccessible = true + stack.addLast(field.get(obj)) + } + currentClass = currentClass.superclass + } + } + } + } + val unreachable = graph.sharedOrder.filter { instance -> instance !in reachable } + if (unreachable.isEmpty()) { + return + } + graph.sharedOrder.removeAll { instance -> instance !in reachable } + for (instance in unreachable) { + graph.sharedInfo.remove(instance) + } + } + + /** + * True when the reachability walk should descend into [obj]'s declared fields. Pruning must + * never drop an entry a live object still holds, so the walk descends into every graph-attached + * class rather than allow-listing packages; only platform and JDOM types (which cannot hold + * shared model references) are excluded. + * + * @param Any obj The object under consideration. + * @return Boolean Whether to walk its fields. + */ + private fun shouldWalkFields(obj: Any): Boolean { + val className = obj::class.java.name + return !className.startsWith("java.") && + !className.startsWith("javax.") && + !className.startsWith("kotlin.") && + !className.startsWith("org.jdom.") + } + + /** + * Pushes the shared objects targeted by xs.ref attributes anywhere in [element]'s subtree onto + * the reachability [stack]. + * + * @param Element element The verbatim subtree to scan. + * @param Map sharedById The pool keyed by preserved xs.id. + * @param ArrayDeque stack The walk stack to extend. + */ + private fun addVerbatimRefTargets(element: Element, sharedById: Map, stack: ArrayDeque) { + element.getAttributeValue(ATTR_REF)?.let { refId -> sharedById[refId]?.let(stack::addLast) } + @Suppress("UNCHECKED_CAST") + for (child in element.children as List) { + addVerbatimRefTargets(child, sharedById, stack) + } + } +} + +/** + * The mutation facade over this model's graph, for lowering editor state back onto it before a + * [Cmo3.write]. + * + * @return Cmo3GraphEditor The editor bound to this model's graph. + */ +public fun Cmo3Model.edit(): Cmo3GraphEditor = Cmo3GraphEditor(graph) \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3PiTables.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3PiTables.kt new file mode 100644 index 0000000..c795406 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/Cmo3PiTables.kt @@ -0,0 +1,321 @@ +package org.umamo.format.cmo3 + +/* + * The main.xml prologue tables a fresh document must author (docs/format/CMO3.md §3 Document + * Shape): every element tag's fully-qualified editor class name for the block, and the + * 5.4-era per-class schema versions for the block. Both are transcribed verbatim from + * the golden corpus (the union of all 32 samples' import PIs - zero tag collisions - and the + * fileFormatVersion=504000000 samples' version PIs); Cmo3AuthorTest re-derives every corpus file's + * prologue through these tables and compares verbatim, so any drift fails loudly. + */ + +// CMO3: - one per distinct non-primitive element tag, sorted by FQCN; nested +// classes use the 'dollar' spelling and the element tag is the segment after the last 'dollar' or '.'. +internal val CMO3_TAG_TO_FQCN: Map = + mapOf( + "ACAffecterForm" to "com.live2d.cubism.doc.model.affecter.ACAffecterForm", + "ACAffecterSource" to "com.live2d.cubism.doc.model.affecter.ACAffecterSource", + "ACBlend" to "com.live2d.graphics.psd.blend.ACBlend", + "ACDeformerForm" to "com.live2d.cubism.doc.model.deformer.ACDeformerForm", + "ACDeformerOriginalShape" to "com.live2d.cubism.doc.model.extension.deformerOriginalShape.ACDeformerOriginalShape", + "ACDeformerSource" to "com.live2d.cubism.doc.model.deformer.ACDeformerSource", + "ACDrawableForm" to "com.live2d.cubism.doc.model.drawable.ACDrawableForm", + "ACDrawableSource" to "com.live2d.cubism.doc.model.drawable.ACDrawableSource", + "ACExtension" to "com.live2d.cubism.doc.model.extension.ACExtension", + "ACForm" to "com.live2d.cubism.doc.model.ACForm", + "ACImageLayer" to "com.live2d.cubism.doc.resources.ACImageLayer", + "ACLayerEntry" to "com.live2d.cubism.doc.resources.ACLayerEntry", + "ACLayerGroup" to "com.live2d.cubism.doc.resources.ACLayerGroup", + "ACParameterControllableSource" to "com.live2d.cubism.doc.model.ACParameterControllableSource", + "ACTextureInput" to "com.live2d.cubism.doc.model.extension.textureInput.ACTextureInput", + "AClip" to "com.live2d.graphics.filter.concreteFilter.clip.AClip", + "AFilterDef" to "com.live2d.graphics.filter.AFilterDef", + "AMappingDetail" to "com.live2d.cubism.doc.model.motionSync.data.AMappingDetail", + "AValueConnector" to "com.live2d.graphics.filter.AValueConnector", + "AlphaComposition" to "com.live2d.cubism.doc.model.drawable.AlphaComposition", + "Anisotropy" to "com.live2d.graphics3d.texture.Anisotropy", + "AutoLayoutLock" to "com.live2d.cubism.doc.model.texture.textureAtlas.AutoLayoutLock", + "AutoYureConfig" to "com.live2d.cubism.doc.model.deformer.autoYure.AutoYureConfig", + "BindMethod" to "com.live2d.cubism.doc.model.extension.controller.CControllerExtension\$BindMethod", + "CAffecterGuid" to "com.live2d.type.CAffecterGuid", + "CAffecterId" to "com.live2d.cubism.doc.model.id.CAffecterId", + "CAffecterSourceSet" to "com.live2d.cubism.doc.model.affecter.CAffecterSourceSet", + "CAffine" to "com.live2d.type.CAffine", + "CArtMeshForm" to "com.live2d.cubism.doc.model.drawable.artMesh.CArtMeshForm", + "CArtMeshSource" to "com.live2d.cubism.doc.model.drawable.artMesh.CArtMeshSource", + "CArtPathBrush" to "com.live2d.cubism.doc.model.drawable.artPath.Line.CArtPathBrush", + "CArtPathBrushGuid" to "com.live2d.type.CArtPathBrushGuid", + "CArtPathBrushId" to "com.live2d.cubism.doc.model.id.CArtPathBrushId", + "CArtPathBrushSetting" to "com.live2d.cubism.doc.model.drawable.artPath.Line.CArtPathBrushSetting", + "CArtPathBrush_TextureInput" to "com.live2d.cubism.doc.model.drawable.artPath.Line.CArtPathBrush_TextureInput", + "CArtPathDrawingCurveType" to "com.live2d.cubism.doc.model.drawable.artPath.CArtPathDrawingCurveType", + "CAutoYureConfigExtension" to "com.live2d.cubism.doc.model.extension.autoYure.CAutoYureConfigExtension", + "CBlend_Color" to "com.live2d.graphics.psd.blend.CBlend_Color", + "CBlend_LinearDodge" to "com.live2d.graphics.psd.blend.CBlend_LinearDodge", + "CBlend_Multiply" to "com.live2d.graphics.psd.blend.CBlend_Multiply", + "CBlend_Normal" to "com.live2d.graphics.psd.blend.CBlend_Normal", + "CBlend_Normal_Original" to "com.live2d.graphics.psd.blend.CBlend_Normal_Original", + "CBlend_NotSupported" to "com.live2d.graphics.psd.blend.CBlend_NotSupported", + "CCachedImage" to "com.live2d.graphics.cachedImage.CCachedImage", + "CCachedImageManager" to "com.live2d.graphics.cachedImage.CCachedImageManager", + "CColor" to "com.live2d.type.CColor", + "CControllerCurve" to "com.live2d.cubism.doc.model.extension.controller.CControllerCurve", + "CControllerCurveGuid" to "com.live2d.type.CControllerCurveGuid", + "CControllerExtension" to "com.live2d.cubism.doc.model.extension.controller.CControllerExtension", + "CControllerPoint" to "com.live2d.cubism.doc.model.extension.controller.CControllerPoint", + "CControllerPointGuid" to "com.live2d.type.CControllerPointGuid", + "CCurveForRotationDeformerExtension" to "com.live2d.cubism.doc.model.affecter.glue.deformPathSkinning.CCurveForRotationDeformerExtension", + "CDeformerGuid" to "com.live2d.type.CDeformerGuid", + "CDeformerId" to "com.live2d.cubism.doc.model.id.CDeformerId", + "CDeformerOriginalShapeExtension" to "com.live2d.cubism.doc.model.extension.deformerOriginalShape.CDeformerOriginalShapeExtension", + "CDeformerSourceSet" to "com.live2d.cubism.doc.model.deformer.CDeformerSourceSet", + "CDrawableGuid" to "com.live2d.type.CDrawableGuid", + "CDrawableId" to "com.live2d.cubism.doc.model.id.CDrawableId", + "CDrawableSourceSet" to "com.live2d.cubism.doc.model.drawable.CDrawableSourceSet", + "CEditableMeshExtension" to "com.live2d.cubism.doc.model.extension.editableMesh.CEditableMeshExtension", + "CEffectParameterGroups" to "com.live2d.cubism.doc.model.CEffectParameterGroups", + "CExtendedInterpolationExtension" to "com.live2d.cubism.doc.model.interpolator.extendedInterpolation.CExtendedInterpolationExtension", + "CExtensionGuid" to "com.live2d.type.CExtensionGuid", + "CFloatColor" to "com.live2d.type.CFloatColor", + "CFormGuid" to "com.live2d.type.CFormGuid", + "CGameMotionSet" to "com.live2d.cubism.doc.gameData.motions.CGameMotionSet", + "CGlueForm" to "com.live2d.cubism.doc.model.affecter.glue.CGlueForm", + "CGlueSource" to "com.live2d.cubism.doc.model.affecter.glue.CGlueSource", + "CGuideGuid" to "com.live2d.type.CGuideGuid", + "CGuide_Modeling" to "com.live2d.cubism.doc.modeling.ui.guide.CGuide_Modeling", + "CGuidesSetting" to "com.live2d.cubism.doc.modeling.ui.guide.CGuidesSetting", + "CImageCanvas" to "com.live2d.graphics.CImageCanvas", + "CImageIcon" to "com.live2d.type.CImageIcon", + "CImageResource" to "com.live2d.graphics.CImageResource", + "CLabelColor" to "com.live2d.cubism.doc.model.CLabelColor", + "CLabelColorType" to "com.live2d.cubism.doc.model.CLabelColorType", + "CLayer" to "com.live2d.cubism.doc.resources.CLayer", + "CLayerGroup" to "com.live2d.cubism.doc.resources.CLayerGroup", + "CLayerGuid" to "com.live2d.type.CLayerGuid", + "CLayerIdentifier" to "com.live2d.cubism.doc.resources.CLayerIdentifier", + "CLayerInputData" to "com.live2d.cubism.doc.model.extension.textureInput.inputFilter.CLayerInputData", + "CLayerSelectorMap" to "com.live2d.cubism.doc.model.extension.textureInput.inputFilter.CLayerSelectorMap", + "CLayeredImage" to "com.live2d.cubism.doc.resources.CLayeredImage", + "CLayeredImageGuid" to "com.live2d.type.CLayeredImageGuid", + "CMeshGeneratorExtension" to "com.live2d.cubism.doc.model.extension.meshGenerator.CMeshGeneratorExtension", + "CMocExportType" to "com.live2d.cubism.doc.model.exporter.CMocExportType", + "CModelExportSettingDialogData" to "com.live2d.cubism.doc.model.exporter.CModelExportSettingDialogData", + "CModelGuid" to "com.live2d.type.CModelGuid", + "CModelImage" to "com.live2d.cubism.doc.model.texture.modelImage.CModelImage", + "CModelImageGroup" to "com.live2d.cubism.doc.model.texture.modelImage.CModelImageGroup", + "CModelImageGuid" to "com.live2d.type.CModelImageGuid", + "CModelInfo" to "com.live2d.cubism.doc.model.CModelInfo", + "CModelSource" to "com.live2d.cubism.doc.model.CModelSource", + "CModelStateSetSet" to "com.live2d.cubism.doc.model.modelStateSet.CModelStateSetSet", + "CMotionSyncSettingGuid" to "com.live2d.type.CMotionSyncSettingGuid", + "CMotionSyncSettingId" to "com.live2d.cubism.doc.model.id.CMotionSyncSettingId", + "CMotionSyncSettingSource" to "com.live2d.cubism.doc.model.motionSync.CMotionSyncSettingSource", + "CMotionSyncSettingSourceSet" to "com.live2d.cubism.doc.model.motionSync.CMotionSyncSettingSourceSet", + "CParameterGroup" to "com.live2d.cubism.doc.model.param.group.CParameterGroup", + "CParameterGroupGuid" to "com.live2d.type.CParameterGroupGuid", + "CParameterGroupId" to "com.live2d.cubism.doc.model.id.CParameterGroupId", + "CParameterGroupSet" to "com.live2d.cubism.doc.model.param.group.CParameterGroupSet", + "CParameterGuid" to "com.live2d.type.CParameterGuid", + "CParameterId" to "com.live2d.cubism.doc.model.id.CParameterId", + "CParameterSource" to "com.live2d.cubism.doc.model.param.CParameterSource", + "CParameterSourceSet" to "com.live2d.cubism.doc.model.param.CParameterSourceSet", + "CPartForm" to "com.live2d.cubism.doc.model.parts.CPartForm", + "CPartGuid" to "com.live2d.type.CPartGuid", + "CPartId" to "com.live2d.cubism.doc.model.id.CPartId", + "CPartSource" to "com.live2d.cubism.doc.model.parts.CPartSource", + "CPartSourceSet" to "com.live2d.cubism.doc.model.parts.CPartSourceSet", + "CPhysicsDataGuid" to "com.live2d.type.CPhysicsDataGuid", + "CPhysicsInput" to "com.live2d.cubism.doc.gameData.physics.CPhysicsInput", + "CPhysicsOutput" to "com.live2d.cubism.doc.gameData.physics.CPhysicsOutput", + "CPhysicsSettingId" to "com.live2d.cubism.doc.model.id.CPhysicsSettingId", + "CPhysicsSettingsGuid" to "com.live2d.type.CPhysicsSettingsGuid", + "CPhysicsSettingsSource" to "com.live2d.cubism.doc.gameData.physics.CPhysicsSettingsSource", + "CPhysicsSettingsSourceSet" to "com.live2d.cubism.doc.gameData.physics.CPhysicsSettingsSourceSet", + "CPhysicsSourceType" to "com.live2d.cubism.doc.gameData.physics.CPhysicsController\$CPhysicsSourceType", + "CPhysicsVertex" to "com.live2d.cubism.doc.gameData.physics.CPhysicsVertex", + "CPoint" to "com.live2d.type.CPoint", + "CRandomPoseGroupData" to "com.live2d.cubism.doc.model.randomPose.CRandomPoseSetting\$CRandomPoseGroupData", + "CRandomPoseParamData" to "com.live2d.cubism.doc.model.randomPose.CRandomPoseSetting\$CRandomPoseParamData", + "CRandomPoseSetting" to "com.live2d.cubism.doc.model.randomPose.CRandomPoseSetting", + "CRandomPoseSettingManager" to "com.live2d.cubism.doc.model.randomPose.CRandomPoseSettingManager", + "CRect" to "com.live2d.type.CRect", + "CRotationDeformerForm" to "com.live2d.cubism.doc.model.deformer.rotation.CRotationDeformerForm", + "CRotationDeformerSource" to "com.live2d.cubism.doc.model.deformer.rotation.CRotationDeformerSource", + "CSize" to "com.live2d.type.CSize", + "CTextureAtlas" to "com.live2d.cubism.doc.model.texture.textureAtlas.CTextureAtlas", + "CTextureAtlasGuid" to "com.live2d.type.CTextureAtlasGuid", + "CTextureImage" to "com.live2d.cubism.doc.model.texture.CTextureImage", + "CTextureInputExtension" to "com.live2d.cubism.doc.model.extension.textureInput.CTextureInputExtension", + "CTextureInput_ModelImage" to "com.live2d.cubism.doc.model.extension.textureInput.CTextureInput_ModelImage", + "CTextureInput_TextureAtlasRegion" to "com.live2d.cubism.doc.model.extension.textureInput.CTextureInput_TextureAtlasRegion", + "CTextureManager" to "com.live2d.cubism.doc.model.texture.CTextureManager", + "CTopologyObserverExtension" to "com.live2d.cubism.doc.model.extension.structureObserver.CTopologyObserverExtension", + "CWarpDeformerBezierExtension" to "com.live2d.cubism.doc.model.extension.warpBezier.CWarpDeformerBezierExtension", + "CWarpDeformerForm" to "com.live2d.cubism.doc.model.deformer.warp.CWarpDeformerForm", + "CWarpDeformerSource" to "com.live2d.cubism.doc.model.deformer.warp.CWarpDeformerSource", + "CWritableImage" to "com.live2d.graphics.CWritableImage", + "CachedImageType" to "com.live2d.graphics.cachedImage.CachedImageType", + "ClipByMesh" to "com.live2d.graphics.filter.concreteFilter.clip.ClipByMesh", + "ColorComposition" to "com.live2d.cubism.doc.model.drawable.ColorComposition", + "CompatibilityOption_Cubism21to30" to "com.live2d.cubism.doc.model.options.compatibility.CompatibilityOption_Cubism21to30", + "ConstValueConnector" to "com.live2d.graphics.filter.concreteConnector.ConstValueConnector", + "CoordType" to "com.live2d.doc.CoordType", + "CreationMethod" to "com.live2d.cubism.doc.model.extension.deformerOriginalShape.ACDeformerOriginalShape\$CreationMethod", + "CurveElement" to "com.live2d.cubism.doc.model.affecter.glue.deformPathSkinning.CCurveForRotationDeformerExtension\$CurveElement", + "EditorEdition" to "com.live2d.cubism.doc.model.options.edition.EditorEdition", + "Effect" to "com.live2d.cubism.doc.model.extension.controller.CControllerExtension\$Effect", + "EffectParameterType" to "com.live2d.cubism.doc.model.EffectParameterType", + "EmptyFilter" to "com.live2d.graphics.filter.concreteFilter.EmptyFilter", + "EnvConnection" to "com.live2d.graphics.filter.FilterSet\$EnvConnection", + "EnvValueConnector" to "com.live2d.graphics.filter.concreteConnector.EnvValueConnector", + "EnvValueSet" to "com.live2d.graphics.filter.FilterEnv\$EnvValueSet", + "ExtendedInterpolationSetting" to "com.live2d.cubism.doc.model.morphTarget.extendedInterpolation.ExtendedInterpolationSetting", + "ExtendedInterpolationType" to "com.live2d.cubism.doc.model.interpolator.extendedInterpolation.ExtendedInterpolationType", + "ExtendedKeyFormMorphTarget" to "com.live2d.cubism.doc.model.morphTarget.extendedInterpolation.ExtendedKeyFormMorphTarget", + "ExtendedKeyFormMorphTargetSet" to "com.live2d.cubism.doc.model.morphTarget.extendedInterpolation.ExtendedKeyFormMorphTargetSet", + "FilterDefGuid" to "com.live2d.type.FilterDefGuid", + "FilterEnv" to "com.live2d.graphics.filter.FilterEnv", + "FilterInstance" to "com.live2d.graphics.filter.filterInstance.FilterInstance", + "FilterInstanceId" to "com.live2d.graphics.filter.id.FilterInstanceId", + "FilterMode" to "com.live2d.graphics3d.texture.GTexture\$FilterMode", + "FilterOutputValueConnector" to "com.live2d.graphics.filter.concreteConnector.FilterOutputValueConnector", + "FilterSet" to "com.live2d.graphics.filter.FilterSet", + "FilterValue" to "com.live2d.graphics.filter.FilterValue", + "FilterValueId" to "com.live2d.graphics.filter.id.FilterValueId", + "FixWidthData" to "com.live2d.cubism.doc.model.drawable.artPath.Line.FixWidthData", + "FormatVersion" to "com.live2d.cubism.doc.model.exporter.CModelExportSettingDialogData\$FormatVersion", + "GEditableMesh2" to "com.live2d.graphics3d.editableMesh.GEditableMesh2", + "GEditableMeshGuid" to "com.live2d.type.GEditableMeshGuid", + "GTexture" to "com.live2d.graphics3d.texture.GTexture", + "GTexture2D" to "com.live2d.graphics3d.texture.GTexture2D", + "GTextureGuid" to "com.live2d.type.GTextureGuid", + "GTransform2" to "com.live2d.graphics3d.component.GTransform2", + "GVector2" to "com.live2d.graphics3d.type.GVector2", + "GuideType" to "com.live2d.cubism.doc.modeling.ui.guide.CGuide_Modeling\$GuideType", + "IdSet" to "com.live2d.cubism.doc.model.options.compatibility.CompatibilityOption_Cubism21to30\$IdSet", + "InterpolationType" to "com.live2d.cubism.doc.model.interpolator.InterpolationType", + "KeyFormMorphTarget" to "com.live2d.cubism.doc.model.morphTarget.KeyFormMorphTarget", + "KeyFormMorphTargetSet" to "com.live2d.cubism.doc.model.morphTarget.KeyFormMorphTargetSet", + "KeyOnParameter" to "com.live2d.cubism.doc.model.interpolator.KeyOnParameter", + "KeyformBindingSource" to "com.live2d.cubism.doc.model.interpolator.KeyformBindingSource", + "KeyformGridAccessKey" to "com.live2d.cubism.doc.model.interpolator.KeyformGridAccessKey", + "KeyformGridSource" to "com.live2d.cubism.doc.model.interpolator.KeyformGridSource", + "KeyformOnGrid" to "com.live2d.cubism.doc.model.interpolator.KeyformOnGrid", + "LayerSet" to "com.live2d.cubism.doc.resources.LayerSet", + "LayeredImageWrapper" to "com.live2d.cubism.doc.model.texture.LayeredImageWrapper", + "MagFilter" to "com.live2d.graphics3d.texture.MagFilter", + "MappingItem" to "com.live2d.cubism.doc.model.motionSync.data.MappingItem", + "MeshGenerateSetting" to "com.live2d.cubism.doc.model.extension.meshGenerator.MeshGenerateSetting", + "MeshPointRef" to "com.live2d.cubism.doc.model.drawable.artMesh.MeshPointRef", + "MeshPointRefEx" to "com.live2d.cubism.doc.model.drawable.artMesh.MeshPointRefEx", + "MinFilter" to "com.live2d.graphics3d.texture.MinFilter", + "ModelImageEntry" to "com.live2d.cubism.doc.model.texture.textureAtlas.CTextureAtlas\$ModelImageEntry", + "ModelImageFilterEnv" to "com.live2d.cubism.doc.model.extension.textureInput.inputFilter.ModelImageFilterEnv", + "ModelImageFilterSet" to "com.live2d.cubism.doc.model.extension.textureInput.inputFilter.ModelImageFilterSet", + "ModelViewerSetting" to "com.live2d.cubism.doc.modeling.ui.viewer.ModelViewerSetting", + "MorphTargetBlendWeightConstraint" to "com.live2d.cubism.doc.model.morphTarget.MorphTargetBlendWeightConstraint", + "MorphTargetBlendWeightConstraintSet" to "com.live2d.cubism.doc.model.morphTarget.MorphTargetBlendWeightConstraintSet", + "MorphTargetEditBaseParameterMap" to "com.live2d.cubism.doc.model.morphTarget.MorphTargetEditBaseParameterMap", + "MotionSyncMappingSetting" to "com.live2d.cubism.doc.model.motionSync.MotionSyncMappingSetting", + "MotionSyncPostProcSetting" to "com.live2d.cubism.doc.model.motionSync.MotionSyncPostProcSetting", + "PointInTriangle" to "com.live2d.cubism.doc.model.drawable.artMesh.PointInTriangle", + "PointOnCurve" to "com.live2d.cubism.doc.model.extension.controller.CControllerExtension\$PointOnCurve", + "RotationDeformerOriginalShape" to "com.live2d.cubism.doc.model.extension.deformerOriginalShape.RotationDeformerOriginalShape", + "SettingType" to "com.live2d.cubism.doc.model.motionSync.SettingType", + "ShapeMappingDetail" to "com.live2d.cubism.doc.model.motionSync.data.ShapeMappingDetail", + "SpriteData" to "com.live2d.cubism.doc.model.drawable.artPath.Line.SpriteData", + "StaticFilterDefGuid" to "com.live2d.type.StaticFilterDefGuid", + "SyncAudioParam" to "com.live2d.cubism.doc.model.motionSync.data.SyncAudioParam", + "SyncAudioParamGuid" to "com.live2d.type.SyncAudioParamGuid", + "SyncCubismParam" to "com.live2d.cubism.doc.model.motionSync.data.SyncCubismParam", + "SyncCubismParamGuid" to "com.live2d.type.SyncCubismParamGuid", + "SyncType" to "com.live2d.cubism.doc.model.motionSync.SyncType", + "TargetPoint" to "com.live2d.cubism.doc.model.extension.controller.CControllerExtension\$TargetPoint", + "TextureImageGroup" to "com.live2d.cubism.doc.model.texture.TextureImageGroup", + "TextureState" to "com.live2d.cubism.doc.model.drawable.TextureState", + "TextureUvData" to "com.live2d.cubism.doc.model.drawable.artPath.Line.TextureUvData", + "TrackCursorSetting" to "com.live2d.cubism.doc.modeling.ui.viewer.TrackCursorSetting", + "TrackCursorSettingItemType" to "com.live2d.cubism.doc.modeling.ui.viewer.TrackCursorSettingItemType", + "Type" to "com.live2d.cubism.doc.model.param.CParameterSource\$Type", + "WarpDeformerOriginalShape" to "com.live2d.cubism.doc.model.extension.deformerOriginalShape.WarpDeformerOriginalShape", + "WrapMode" to "com.live2d.graphics3d.texture.WrapMode", + "YureDeformConfig" to "com.live2d.cubism.doc.model.deformer.autoYure.YureDeformConfig", + "YureRootDirection" to "com.live2d.cubism.doc.model.deformer.autoYure.YureRootDirection", + ) + +// CMO3: - emitted regardless of document content in every corpus file +// (SerializeFormatVersion is never an element tag). +internal val CMO3_VERSIONS_ALWAYS_5_4: List> = + listOf( + "SerializeFormatVersion" to 2, + ) + +// CMO3: - emitted when the keyed element tag is present in the document. The +// PI name is the tag itself except for ModelImageEntry, whose version PI spells the dotted +// outer-class-less FQN while its import PI spells CTextureAtlas.ModelImageEntry with a dollar, +// and ModelStateSet, whose versioned item class rides on its (possibly empty) set's tag. +// The versions are the highest observed across the corpus (each class's current version at the +// eras our corpus spans); a versioned class MISSING from this table is load-bearing to get right: +// the editor's reader falls back to deserializing that class at version 0, and a v0 layout read +// over our current-version element NPEs field-by-field (CRotationDeformerForm was the proof - its +// PI rides only on corpus files that contain rotation deformers, so a table built from blank +// saves alone never sees it). +internal val CMO3_VERSIONS_BY_TAG_5_4: Map> = + mapOf( + "CModelStateSetSet" to ("ModelStateSet" to 1), + "ACDeformerOriginalShape" to ("ACDeformerOriginalShape" to 1), + "CArtMeshSource" to ("CArtMeshSource" to 5), + "CArtPathBrush" to ("CArtPathBrush" to 1), + "CArtPathBrush_TextureInput" to ("CArtPathBrush_TextureInput" to 1), + "CFloatColor" to ("CFloatColor" to 1), + "CGuide_Modeling" to ("CGuide_Modeling" to 1), + "CLabelColor" to ("CLabelColor" to 0), + "CModelImage" to ("CModelImage" to 3), + "CModelSource" to ("CModelSource" to 16), + "CParameterGroup" to ("CParameterGroup" to 4), + "CPartForm" to ("CPartForm" to 2), + "CPartSource" to ("CPartSource" to 2), + "CRotationDeformerForm" to ("CRotationDeformerForm" to 1), + "FixWidthData" to ("FixWidthData" to 1), + "KeyFormMorphTarget" to ("KeyFormMorphTarget" to 2), + "KeyformGridSource" to ("KeyformGridSource" to 1), + "ModelImageEntry" to ("com.live2d.cubism.doc.model.texture.textureAtlas.ModelImageEntry" to 2), + "RotationDeformerOriginalShape" to ("RotationDeformerOriginalShape" to 1), + "SpriteData" to ("SpriteData" to 1), + "TextureUvData" to ("TextureUvData" to 1), + "WarpDeformerOriginalShape" to ("WarpDeformerOriginalShape" to 1), + ) + +// Tags owned by the serializer itself (structural, primitive, collection, and array tags) - they +// deserialize without a class and therefore carry no import PI. +internal val CMO3_STRUCTURAL_TAGS: Set = + setOf( + "root", + "main", + "shared", + "entry", + "null", + "file", + "i", + "f", + "d", + "l", + "short", + "byte", + "char", + "b", + "s", + "array_list", + "carray_list", + "hash_map", + "linked_map", + "linked_set", + "float-array", + "int-array", + "long-array", + "short-array", + "double-array", + "byte-array", + "char-array", + "bool-array", + ) \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CollectionSerializers.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CollectionSerializers.kt new file mode 100644 index 0000000..aaa843f --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CollectionSerializers.kt @@ -0,0 +1,148 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element + +internal const val ATTR_ENUM_VALUE: String = "v" +internal const val ATTR_KEY_TYPE: String = "keyType" +internal const val TAG_ENTRY: String = "entry" +internal const val NAME_KEY: String = "key" +internal const val NAME_VALUE: String = "value" +private const val ARRAY_SEPARATOR: String = " " + +/** + * Serializer for a Kotlin enum class: ``. + * The enum constant name is stored in attribute `v`. + * + * @see CMO3.md §3 Primitive & collection tags + */ +internal class EnumSerializer(private val tag: String, private val enumClass: Class<*>) : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val element = Element(tag) + element.setFieldName(name) + element.setAttribute(ATTR_ENUM_VALUE, (value as Enum<*>).name) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any { + val constantName = element.getAttributeValue(ATTR_ENUM_VALUE) + // Class.getEnumConstants() is @Nullable in Java (null for non-enum classes), so Kotlin types it + // Array<...>?. This serializer is only ever constructed for an enum class, so the array is + // non-null by construction - assert it with !! rather than threading a spurious null path. + return enumClass.enumConstants!!.first { (it as Enum<*>).name == constantName } + } +} + +/** + * Serializer for a primitive typed array: `v0 v1 v2 ...` (space-joined text). + * Values are space-separated in the element text. + * + * @see CMO3.md §3 Primitive & collection tags + */ +internal class ArraySerializer( + private val tag: String, + private val size: (Any) -> Int, + private val encode: (Any) -> String, + private val decode: (List) -> Any, +) : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val element = Element(tag) + element.setFieldName(name) + element.setAttribute(ATTR_COUNT, size(value).toString()) + element.text = encode(value) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any { + val text = element.text.trim() + val tokens = if (text.isEmpty()) emptyList() else text.split(ARRAY_SEPARATOR) + return decode(tokens) + } + + internal companion object { + /** Joins a typed array's elements with the array separator. */ + fun join(values: Sequence): String = values.joinToString(ARRAY_SEPARATOR) + } +} + +/** + * Serializer for sets: `` with positional item children (no xs.n). + * Covers LinkedHashSet ("linked_set"). Reads into the [factory] type to preserve order. + * + * @see CMO3.md §3 Primitive & collection tags + */ +internal class SetSerializer(private val tag: String, private val factory: () -> MutableSet) : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val set = value as Set<*> + val element = Element(tag) + element.setFieldName(name) + element.setAttribute(ATTR_COUNT, set.size.toString()) + for (item in set) element.addContent(ctx.createElementFromObject(null, item)) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any { + val out = factory() + @Suppress("UNCHECKED_CAST") + for (child in element.children as List) out.add(ctx.createObjectFromElement(child)) + return out + } +} + +/** + * Serializer for maps: `` with `` children, each holding a + * `key` and `value` child. Covers HashMap ("hash_map") and LinkedHashMap ("linked_map"). + * + * EN: Reads into a LinkedHashMap so entry order is preserved for faithful re-emit. + * + * @see CMO3.md §3 Primitive & collection tags + */ +internal class MapSerializer( + private val tag: String, + private val factory: () -> MutableMap, +) : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val map = value as Map<*, *> + val element = Element(tag) + element.setFieldName(name) + element.setAttribute(ATTR_COUNT, map.size.toString()) + // CMO3: string-keyed maps carry keyType="string" and store each value as ; + // object-keyed maps omit keyType and wrap each pair in . + val stringKeyed = map.isEmpty() || map.keys.all { it is String } + if (stringKeyed) { + element.setAttribute(ATTR_KEY_TYPE, "string") + for ((key, mapValue) in map) element.addContent(ctx.createElementFromObject(key as String?, mapValue)) + } else { + for ((key, mapValue) in map) { + val entry = Element(TAG_ENTRY) + entry.addContent(ctx.createElementFromObject(NAME_KEY, key)) + entry.addContent(ctx.createElementFromObject(NAME_VALUE, mapValue)) + element.addContent(entry) + } + } + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any { + val out = factory() + + @Suppress("UNCHECKED_CAST") + val children = element.children as List + if (element.getAttributeValue(ATTR_KEY_TYPE) == "string") { + for (valueElement in children) { + val key = valueElement.getAttributeValue(ATTR_NAME) + out[key] = ctx.createObjectFromElement(valueElement) + } + } else { + for (entry in children) { + if (entry.name != TAG_ENTRY) continue + @Suppress("UNCHECKED_CAST") + val parts = entry.children as List + val keyElement = parts.firstOrNull { it.getAttributeValue(ATTR_NAME) == NAME_KEY } + val valueElement = parts.firstOrNull { it.getAttributeValue(ATTR_NAME) == NAME_VALUE } + out[keyElement?.let { ctx.createObjectFromElement(it) }] = + valueElement?.let { ctx.createObjectFromElement(it) } + } + } + return out + } +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CubismEngine.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CubismEngine.kt new file mode 100644 index 0000000..631f9e2 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CubismEngine.kt @@ -0,0 +1,22 @@ +package org.umamo.format.cmo3.serialize + +/** + * Builds a [SerializeEngine] wired with every typed Cubism subsystem implemented so far. Tags not + * yet modelled fall back to [VerbatimNode] (reported via [diagnostics]), so the result always reads + * and writes a complete model losslessly - coverage simply grows over time. + * + * @param SerializeDiagnostics diagnostics Sink for unmodeled-tag reports (default no-op). + * @return SerializeEngine The configured engine. + * + * @see CMO3.md §3 Payload: main.xml + */ +public fun cubismEngine(diagnostics: SerializeDiagnostics = SerializeDiagnostics.None): SerializeEngine { + val registry = SerializerRegistry() + // Subsystems are added here as they are typed; order is irrelevant (tag-keyed). + registerIdentitySubsystem(registry) // *Guid + *Id + registerValueTypeSubsystem(registry) // GVector2, CRect, CColor, CAffine + registerMeshSubsystem(registry) // CoordType, PointInTriangle, PointOnCurve, MeshPointRef + registerCustomSubsystem(registry) // + attribute-serialized leaves + CModelSource root + org.umamo.format.cmo3.serialize.gen.registerGeneratedSubsystem(registry) // bulk reflective (generated) + return SerializeEngine(registry, diagnostics) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CustomSubsystem.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CustomSubsystem.kt new file mode 100644 index 0000000..824a4dd --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/CustomSubsystem.kt @@ -0,0 +1,67 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element +import org.umamo.format.cmo3.model.custom.CFloatColor +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CLabelColor +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CRotationDeformerForm +import org.umamo.format.cmo3.model.custom.CSize +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.custom.FilterInstance +import org.umamo.format.cmo3.model.custom.GEditableMesh2 +import org.umamo.format.cmo3.model.custom.RotationDeformerOriginalShape +import org.umamo.format.cmo3.model.custom.WarpDeformerOriginalShape +import org.umamo.format.cmo3.model.type.FileRef + +/** + * Serializer for the `` element. Mirrors the editor's writeFile: the path + * names a de-duplicated CAFF entry; the bytes are managed by the container, not the XML. + * + * @see CMO3.md §1 Container / §3 Payload + */ +internal object FileSerializer : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val element = Element("file") + element.setFieldName(name) + val fileRef = value as FileRef + if (fileRef.archivePath != null) { + element.setAttribute("path", fileRef.archivePath) + } else { + element.text = fileRef.textPath ?: "" + } + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any { + val path = element.getAttributeValue("path") + return FileRef().apply { + if (path != null) archivePath = path else textPath = element.text + } + } +} + +/** + * Registers the hand-written custom subsystem: the `` element plus the attribute-serialized + * leaf/value classes (modelled reflectively with @SerialAttribute), including the CModelSource root. + * + * @param SerializerRegistry registry The registry to populate. + */ +internal fun registerCustomSubsystem(registry: SerializerRegistry) { + registry.registerCustomTag("file", FileRef::class, FileSerializer) + registry.register(CFloatColor::class) + registry.register(CLabelColor::class) + registry.register(WarpDeformerOriginalShape::class) + registry.register(RotationDeformerOriginalShape::class) + registry.register(CSize::class) + registry.register(CRotationDeformerForm::class) + registry.register(CWritableImage::class) + registry.register(CImageResource::class) + registry.register(FilterInstance::class) + registry.register(CModelImage::class) + registry.register(GEditableMesh2::class) + registry.register(CLayer::class) + registry.register(CModelSource::class) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/IdentitySerializers.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/IdentitySerializers.kt new file mode 100644 index 0000000..965e9e9 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/IdentitySerializers.kt @@ -0,0 +1,104 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id + +/** + * Custom serializer for all `*Guid` tags: `` (uuid then note attributes). + * + * @see CMO3.md §3 Serializer mechanics + */ +internal object GuidSerializer : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val guid = value as Guid + val element = Element(guid.kind) // tag is the concrete *Guid kind + element.setFieldName(name) + element.setAttribute("uuid", guid.uuid) + element.setAttribute("note", guid.note) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any = + Guid(element.name).apply { + uuid = element.getAttributeValue("uuid") ?: "" + note = element.getAttributeValue("note") ?: "" + } +} + +/** + * Custom serializer for all `*Id` tags: ``. + * + * @see CMO3.md §3 Serializer mechanics + */ +internal object IdSerializer : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val id = value as Id + val element = Element(id.kind) + element.setFieldName(name) + element.setAttribute("idstr", id.idstr) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any = + Id(element.name).apply { idstr = element.getAttributeValue("idstr") ?: "" } +} + +/** + * The `*Guid` tags emitted by the editor. One [Guid] type, many tags. + */ +internal val GUID_TAGS: List = + listOf( + "CAffecterGuid", + "CArtPathBrushGuid", + "CControllerCurveGuid", + "CControllerPointGuid", + "CDeformerGuid", + "CDrawableGuid", + "CExtensionGuid", + "CFormGuid", + "CGuideGuid", + "CLayeredImageGuid", + "CLayerGuid", + "CModelGuid", + "CModelImageGuid", + "CMotionSyncSettingGuid", + "CParameterGroupGuid", + "CParameterGuid", + "CPartGuid", + "CPhysicsDataGuid", + "CPhysicsSettingsGuid", + "CTextureAtlasGuid", + "FilterDefGuid", + "GEditableMeshGuid", + "GTextureGuid", + "StaticFilterDefGuid", + "SyncAudioParamGuid", + "SyncCubismParamGuid", + ) + +/** The `*Id` tags emitted by the editor. One [Id] type, many tags. */ +internal val ID_TAGS: List = + listOf( + "CAffecterId", + "CArtPathBrushId", + "CDeformerId", + "CDrawableId", + "CMotionSyncSettingId", + "CParameterGroupId", + "CParameterId", + "CPartId", + "CPhysicsSettingId", + "FilterInstanceId", + "FilterValueId", + ) + +/** + * Registers the identity subsystem (all `*Guid` and `*Id` tags) on a registry. + * + * @param SerializerRegistry registry The registry to populate. + */ +internal fun registerIdentitySubsystem(registry: SerializerRegistry) { + for (tag in GUID_TAGS) registry.registerCustomTag(tag, Guid::class, GuidSerializer) + for (tag in ID_TAGS) registry.registerCustomTag(tag, Id::class, IdSerializer) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/MeshSubsystem.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/MeshSubsystem.kt new file mode 100644 index 0000000..10a914b --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/MeshSubsystem.kt @@ -0,0 +1,19 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.model.drawable.CoordType +import org.umamo.format.cmo3.model.drawable.MeshPointRef +import org.umamo.format.cmo3.model.drawable.PointInTriangle +import org.umamo.format.cmo3.model.drawable.PointOnCurve + +/** + * Registers the mesh/geometry subsystem (all reflective). These are frequent shared-pool defs, so + * typing them is validated directly by the whole-file byte-identity gate. + * + * @param SerializerRegistry registry The registry to populate. + */ +internal fun registerMeshSubsystem(registry: SerializerRegistry) { + registry.register(CoordType::class) + registry.register(PointInTriangle::class) + registry.register(PointOnCurve::class) + registry.register(MeshPointRef::class) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/ModelDocument.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/ModelDocument.kt new file mode 100644 index 0000000..2d8e99a --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/ModelDocument.kt @@ -0,0 +1,105 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Document +import org.jdom.Element +import org.jdom.ProcessingInstruction +import org.umamo.format.cmo3.xml.XmlCodec + +/** + * The parsed model document (main.xml): the `` graph plus its ``/`` + * processing instructions, with navigable views over the shared pool and the main root. + * + * EN: This is the backbone the reflective serializer plugs into. It wraps the live JDOM + * [document], so [write] re-emits byte-identically (verbatim fallback) even before any class + * is typed; the parsed accessors (versions/imports/shared/main) drive the typed layer. + * The serializer model: `` holds a + * `` pool of referenceable objects (each `xs.id`/`xs.idx`) and a `
` root; uses + * reference each def via `xs.ref`. To keep byte-identity while only some classes are typed, the + * writer must REUSE the `xs.id`/`xs.idx` and `` ordering captured here rather than + * recompute the editor's global refId/writtenIndex counters. + * JA: main.xml を表すモデル文書。JDOM をそのまま保持するため、未対応クラスでも write はバイト一致する。 + * + * @see CMO3.md §3 Payload: main.xml + */ +public class ModelDocument private constructor( + /** The live JDOM document; mutating it changes what [write] emits. */ + public val document: Document, +) { + /** `` PIs as a className -> version map (e.g. "CModelSource" -> 13). */ + public val versions: Map + + /** `` PIs, in document order. */ + public val imports: List + + /** The document root, `` (carries the fileFormatVersion attribute). */ + public val rootElement: Element = document.rootElement + + /** Children of ``: the pool of cross-referenced objects (each has xs.id/xs.idx). */ + public val sharedElements: List + + /** Children of `
`: normally the single CModelSource root. */ + public val mainElements: List + + init { + require(rootElement.name == ROOT_ELEMENT) { "expected <$ROOT_ELEMENT>, got <${rootElement.name}>" } + + val parsedVersions = LinkedHashMap() + val parsedImports = ArrayList() + // PIs live as document content before the root element. + for (content in document.content) { + if (content !is ProcessingInstruction) continue + when (content.target) { + PI_VERSION -> { + // data is "ClassName:version" + val data = content.data + val separator = data.lastIndexOf(':') + if (separator > 0) { + val className = data.substring(0, separator) + data.substring(separator + 1).trim().toIntOrNull()?.let { parsedVersions[className] = it } + } + } + PI_IMPORT -> parsedImports.add(content.data.trim()) + } + } + versions = parsedVersions + imports = parsedImports + + @Suppress("UNCHECKED_CAST") + sharedElements = (rootElement.getChild(SHARED_ELEMENT)?.children as List?).orEmpty() + + @Suppress("UNCHECKED_CAST") + mainElements = (rootElement.getChild(MAIN_ELEMENT)?.children as List?).orEmpty() + } + + /** Schema version of [className] as declared by a `` PI, or null. */ + public fun versionOf(className: String): Int? = versions[className] + + /** + * Re-emits the document to bytes. Byte-identical to the source while the underlying JDOM is + * unmodified (verbatim fallback); reflects edits once the typed layer mutates [document]. + * + * @return ByteArray UTF-8 XML in the editor's exact format. + */ + public fun write(): ByteArray = XmlCodec.write(document) + + public companion object { + public const val ROOT_ELEMENT: String = "root" + public const val SHARED_ELEMENT: String = "shared" + public const val MAIN_ELEMENT: String = "main" + private const val PI_VERSION = "version" + private const val PI_IMPORT = "import" + + /** + * Parses model XML bytes (the decompressed main.xml) into a [ModelDocument]. + * + * @param ByteArray bytes The decompressed main.xml. + * @return ModelDocument The parsed document. + */ + public fun parse(bytes: ByteArray): ModelDocument = ModelDocument(XmlCodec.parse(bytes)) + } +} + +// TODO(diagnostics): when the reflective serializer materialises typed objects, route any element +// whose tag has no registered typed serializer through the verbatim fallback AND emit a diagnostic +// (configurable sink) naming the unimplemented tag + its stack path - so new Live2D format additions +// are visible rather than silently passed through. \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/SerializeEngine.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/SerializeEngine.kt new file mode 100644 index 0000000..d7d854d --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/SerializeEngine.kt @@ -0,0 +1,708 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Document +import org.jdom.Element +import org.jdom.ProcessingInstruction +import org.umamo.format.cmo3.serialize.annotations.SerialTag +import java.util.IdentityHashMap +import kotlin.reflect.KClass +import kotlin.reflect.full.findAnnotation + +/** + * Resolves element tags <-> classes and owns the serializer instances (primitives, collections, and + * lazily-built reflective class serializers). + */ +internal class SerializerRegistry { + private val tagToClass = HashMap>() + private val classToTag = HashMap, String>() + private val classSerializerCache = HashMap, ReflectiveClassSerializer>() + + private val intSerializer = PrimitiveSerializer("i") { it.toInt() } + private val floatSerializer = PrimitiveSerializer("f") { it.toFloat() } + private val doubleSerializer = PrimitiveSerializer("d") { it.toDouble() } + private val longSerializer = PrimitiveSerializer("l") { it.toLong() } + private val shortSerializer = PrimitiveSerializer("short") { it.toShort() } + private val byteSerializer = PrimitiveSerializer("byte") { it.toByte() } + private val charSerializer = PrimitiveSerializer("char") { it[0] } + private val boolSerializer = PrimitiveSerializer("b") { it == "true" } + private val stringSerializer = PrimitiveSerializer("s") { it } + private val arrayListSerializer = ListSerializer("array_list") { ArrayList() } + private val carrayListSerializer = ListSerializer("carray_list") { org.umamo.format.cmo3.type.CArrayList() } + + // hash_map reads into an order-preserving CHashMap so non-empty maps re-emit in document order. + private val hashMapSerializer = MapSerializer("hash_map") { org.umamo.format.cmo3.type.CHashMap() } + private val linkedMapSerializer = MapSerializer("linked_map") { LinkedHashMap() } + private val linkedSetSerializer = SetSerializer("linked_set") { LinkedHashSet() } + + private val floatArraySerializer = + ArraySerializer( + "float-array", + { (it as FloatArray).size }, + { (it as FloatArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> FloatArray(tokens.size) { tokens[it].toFloat() } }, + ) + private val intArraySerializer = + ArraySerializer( + "int-array", + { (it as IntArray).size }, + { (it as IntArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> IntArray(tokens.size) { tokens[it].toInt() } }, + ) + private val longArraySerializer = + ArraySerializer( + "long-array", + { (it as LongArray).size }, + { (it as LongArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> LongArray(tokens.size) { tokens[it].toLong() } }, + ) + private val shortArraySerializer = + ArraySerializer( + "short-array", + { (it as ShortArray).size }, + { (it as ShortArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> ShortArray(tokens.size) { tokens[it].toShort() } }, + ) + private val doubleArraySerializer = + ArraySerializer( + "double-array", + { (it as DoubleArray).size }, + { (it as DoubleArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> DoubleArray(tokens.size) { tokens[it].toDouble() } }, + ) + private val byteArraySerializer = + ArraySerializer( + "byte-array", + { (it as ByteArray).size }, + { (it as ByteArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> ByteArray(tokens.size) { tokens[it].toByte() } }, + ) + private val charArraySerializer = + ArraySerializer( + "char-array", + { (it as CharArray).size }, + { (it as CharArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> CharArray(tokens.size) { tokens[it][0] } }, + ) + private val boolArraySerializer = + ArraySerializer( + "bool-array", + { (it as BooleanArray).size }, + { (it as BooleanArray).joinToString(" ") { value -> value.toString() } }, + { tokens -> BooleanArray(tokens.size) { tokens[it] == "true" } }, + ) + + private val enumSerializerCache = HashMap, EnumSerializer>() + private val customByClass = HashMap, XmlSerializer>() + private val customByTag = HashMap() + + /** Registers a model class so its tag resolves on read and its version PI can be emitted. */ + fun register(kClass: KClass<*>) { + val tag = tagFor(kClass) + tagToClass[tag] = kClass + classToTag[kClass] = tag + } + + /** Registers a class with a hand-written (e.g. attribute-based) serializer, e.g. value-types. */ + fun registerCustom(kClass: KClass<*>, serializer: XmlSerializer) { + register(kClass) + customByClass[kClass] = serializer + customByTag[classToTag.getValue(kClass)] = serializer + } + + /** + * Registers a custom serializer for an explicit [tag] backed by [kClass]. Lets one class cover + * many tags (e.g. a single Guid type carrying its kind for all *Guid tags); the serializer must + * derive the element tag from the value on write. + * + * @param String tag The element tag to handle. + * @param KClass kClass The backing model class (shared across tags). + * @param XmlSerializer serializer The hand-written serializer. + */ + fun registerCustomTag(tag: String, kClass: KClass<*>, serializer: XmlSerializer) { + tagToClass[tag] = kClass + classToTag.putIfAbsent(kClass, tag) + customByClass[kClass] = serializer + customByTag[tag] = serializer + } + + private fun enumSerializerFor(enumClass: Class<*>): EnumSerializer { + val kClass = enumClass.kotlin + return enumSerializerCache.getOrPut(kClass) { EnumSerializer(tagFor(kClass), enumClass) } + } + + private fun enumClassOf(value: Enum<*>): Class<*> = + value.javaClass.let { if (it.isEnum) it else it.superclass } + + /** The element tag for [kClass]: its @SerialTag, else its simple name. */ + fun tagFor(kClass: KClass<*>): String = + classToTag[kClass] ?: ( + kClass.findAnnotation()?.tag ?: kClass.simpleName + ?: error("anonymous class cannot be serialized: $kClass") + ) + + /** The class registered under [tag], or null if unknown (caller may fall back to verbatim). */ + fun classForTag(tag: String): KClass<*>? = tagToClass[tag] + + /** Cached reflective serializer for [kClass]. */ + fun classSerializer(kClass: KClass<*>): ReflectiveClassSerializer = + classSerializerCache.getOrPut(kClass) { ReflectiveClassSerializer(kClass, this) } + + /** Serializer for a runtime value, dispatched by type (write path). */ + fun serializerForValue(value: Any): XmlSerializer { + customByClass[value::class]?.let { return it } + return when (value) { + is Enum<*> -> enumSerializerFor(enumClassOf(value)) + is Int -> intSerializer + is Float -> floatSerializer + is Double -> doubleSerializer + is Long -> longSerializer + is Short -> shortSerializer + is Byte -> byteSerializer + is Char -> charSerializer + is Boolean -> boolSerializer + is String -> stringSerializer + is FloatArray -> floatArraySerializer + is IntArray -> intArraySerializer + is LongArray -> longArraySerializer + is ShortArray -> shortArraySerializer + is DoubleArray -> doubleArraySerializer + is ByteArray -> byteArraySerializer + is CharArray -> charArraySerializer + is BooleanArray -> boolArraySerializer + // Order matters: subtypes before supertypes so the on-disk tag round-trips exactly. + is org.umamo.format.cmo3.type.CHashMap<*, *> -> hashMapSerializer + is LinkedHashMap<*, *> -> linkedMapSerializer + is Map<*, *> -> hashMapSerializer + is org.umamo.format.cmo3.type.CArrayList<*> -> carrayListSerializer + is List<*> -> arrayListSerializer + is Set<*> -> linkedSetSerializer + else -> classSerializer(value::class) + } + } + + /** Serializer for an element tag (read path), or null if the tag is unknown. */ + fun serializerForTag(tag: String): XmlSerializer? { + customByTag[tag]?.let { return it } + return when (tag) { + "i" -> intSerializer + "f" -> floatSerializer + "d" -> doubleSerializer + "l" -> longSerializer + "short" -> shortSerializer + "byte" -> byteSerializer + "char" -> charSerializer + "b" -> boolSerializer + "s" -> stringSerializer + "array_list" -> arrayListSerializer + "carray_list" -> carrayListSerializer + "hash_map" -> hashMapSerializer + "linked_map" -> linkedMapSerializer + "linked_set" -> linkedSetSerializer + "float-array" -> floatArraySerializer + "int-array" -> intArraySerializer + "long-array" -> longArraySerializer + "short-array" -> shortArraySerializer + "double-array" -> doubleArraySerializer + "byte-array" -> byteArraySerializer + "char-array" -> charArraySerializer + "bool-array" -> boolArraySerializer + else -> + classForTag(tag)?.let { kClass -> + if (kClass.java.isEnum) enumSerializerFor(kClass.java) else classSerializer(kClass) + } + } + } + + /** Serializer for the serializable superclass of [kClass], or null. Never instantiated directly. */ + fun superSerializerOf(kClass: KClass<*>, suppress: Boolean): ReflectiveClassSerializer? { + if (suppress) return null + val superJava = kClass.java.superclass ?: return null + if (superJava == Any::class.java || superJava.isInterface) return null + return classSerializer(superJava.kotlin) + } + + /** Registered (tag -> version) pairs for classes that declare a @SerialTag version. */ + fun versions(): List> = + classToTag.entries.mapNotNull { (kClass, tag) -> + kClass.findAnnotation()?.version?.takeIf { it >= 0 }?.let { tag to it } + } +} + +/** Identity record for an object already written, with its element and global write order. */ +internal class WrittenRecord(val element: Element, val index: Int) + +/** A shared (referenced >= 2x) object's definition element, its xs.id, and write order (xs.idx). */ +internal class SharedDef(val element: Element, val refId: String, val index: Int) + +/** + * A shared object's preserved identity (xs.id), pool index (xs.idx), and exact def tag, captured at + * read time. The [tag] is reused verbatim for references so it always matches the def - even where + * one class covers many tags (Guid/Id) or the tag differs from the class name (float-array, etc.). + */ +internal class SharedRef(val id: String, val index: Int, val tag: String) + +/** + * One child slot of a reflective object, captured on read so the exact child sequence can be replayed + * on write. This makes typed classes tolerant of format evolution (added, removed, or reordered + * fields) across schema versions while staying byte-identical: a known field is re-serialized from the + * typed value, an unrecognised one is re-emitted verbatim, and the superclass keeps its position. + */ +internal sealed interface ChildSlot { + /** A field the serializer recognised, replayed from the typed property [propertyName]. */ + class KnownField(val propertyName: String) : ChildSlot + + /** A child newer than (or unknown to) our schema, replayed verbatim. */ + class VerbatimChild(val element: Element) : ChildSlot + + /** The `` element (superclass fields), replayed via the super serializer. */ + object Super : ChildSlot +} + +/** + * The first fresh ref id not colliding with a preserved pool id ("#N" numeric ids only; the pool's + * non-numeric ids can never collide with the "#counter" form fresh ids take). + * + * @param IdentityHashMap? preassigned The preserved shared identities, or null outside reconcile mode. + * @return Int The starting counter value. + */ +private fun nextFreshRefId(preassigned: IdentityHashMap?): Int { + val maxPreserved = + preassigned?.values?.maxOfOrNull { sharedRef -> + sharedRef.id.removePrefix("#").toIntOrNull() ?: -1 + } ?: -1 + return maxPreserved + 1 +} + +/** + * Mutable write-side state: object-identity tracking and the shared pool (written-object map, + * shared list, ref-id and write-index counters). + * + * EN: In reconcile mode ([preassignedShared] != null) objects that were shared on read are emitted + * as xs.ref using their preserved id - so a round-trip stays byte-identical even when only some + * classes are typed. Any other object referenced more than once - fresh or newly-shared, in or + * out of reconcile mode - goes through the same hoist-on-second-use path, with fresh ids + * continuing past the preserved maximum so they never collide with one. + */ +internal class WriteContext( + private val registry: SerializerRegistry, + private val preassignedShared: IdentityHashMap? = null, + private val preservedChildOrder: IdentityHashMap>>? = null, + private val preservedPresentAttrs: IdentityHashMap>>? = null, +) { + private val written = IdentityHashMap() + val sharedDefs = ArrayList() + + // Fresh ids continue past the preserved pool's numeric ids: the reader keys references by id, + // so a new shared object reusing an id already bound by the source document would hijack every + // later xs.ref to that id. + private var refIdCounter = nextFreshRefId(preassignedShared) + private var writtenIndexCounter = 0 + + /** Records [value]'s element on first write (subsequent calls are no-ops, matching the editor). */ + fun setWritten(value: Any, element: Element) { + if (!written.containsKey(value)) written[value] = WrittenRecord(element, writtenIndexCounter++) + } + + /** + * The child sequence read for [owner] at the [tag] level, or null for a freshly constructed object. + * When non-null it is replayed verbatim (order, presence and unknown children all preserved), so a + * round-trip reproduces the source exactly - independent of schema version. + */ + fun childOrderFor(owner: Any, tag: String): List? = preservedChildOrder?.get(owner)?.get(tag) + + /** The attributes present when [owner] was read at the [tag] level, or null for a fresh object. */ + fun presentAttrsFor(owner: Any, tag: String): Set? = preservedPresentAttrs?.get(owner)?.get(tag) + + /** + * Builds the element for a field/item value: `` for null, an xs.ref for an already-written + * object (hoisting its def into the shared pool on first reuse), else delegates to the serializer. + * + * @param String? name The owning field name (xs.n), or null for collection items. + * @param Any? value The value to serialize. + * @return Element The element (def, reference, or null marker). + */ + fun createElementFromObject(name: String?, value: Any?): Element { + if (value == null) { + val nullElement = Element(TAG_NULL) + nullElement.setFieldName(name) + return nullElement + } + // Reconcile mode: a known-shared object is always emitted as a reference to its preserved id, + // reusing the def's exact tag captured at read time. + preassignedShared?.get(value)?.let { sharedRef -> + val reference = Element(sharedRef.tag) + reference.setFieldName(name) + reference.setAttribute(ATTR_REF, sharedRef.id) + return reference + } + if (value is VerbatimNode) { + // Re-emit the preserved subtree, re-stamping the owning field name (or dropping it for items). + val clone = value.element.clone() as Element + if (name != null) clone.setAttribute(ATTR_NAME, name) else clone.removeAttribute(ATTR_NAME) + return clone + } + written[value]?.let { record -> + var id = record.element.getAttributeValue(ATTR_ID) + if (id == null) { + id = "#${refIdCounter++}" + record.element.setAttribute(ATTR_ID, id) + sharedDefs.add(SharedDef(record.element, id, record.index)) + } + val reference = Element(record.element.name) + reference.setFieldName(name) + reference.setAttribute(ATTR_REF, id) + return reference + } + return registry.serializerForValue(value).createElement(name, value, this) + } +} + +/** Mutable read-side state: the xs.id -> instance map used to resolve xs.ref. */ +internal class ReadContext( + private val registry: SerializerRegistry, + private val diagnostics: SerializeDiagnostics, +) { + val references = HashMap() + + /** The ordered child sequence read for each object, keyed by owner then serializer tag (level). */ + val childOrder = IdentityHashMap>>() + + /** Names of the attributes actually present on read, keyed by owner then serializer tag. */ + val presentAttrs = IdentityHashMap>>() + + private fun slots(owner: Any, tag: String) = + childOrder.getOrPut(owner) { HashMap() }.getOrPut(tag) { ArrayList() } + + /** Records, in document order, a recognised child field of [owner] at the [tag] level. */ + fun recordKnownChild(owner: Any, tag: String, propertyName: String) = + slots(owner, tag).add(ChildSlot.KnownField(propertyName)) + + /** Records, in document order, a child of [owner] the [tag] serializer did not recognise. */ + fun recordVerbatimChild(owner: Any, tag: String, element: Element) = + slots(owner, tag).add(ChildSlot.VerbatimChild(element.clone() as Element)) + + /** Records, in document order, the position of the `` element of [owner] at the [tag] level. */ + fun recordSuperChild(owner: Any, tag: String) = slots(owner, tag).add(ChildSlot.Super) + + /** Records that attribute [attrName] of [owner] (at the [tag] level) was present in the source. */ + fun recordPresentAttr(owner: Any, tag: String, attrName: String) { + presentAttrs.getOrPut(owner) { HashMap() }.getOrPut(tag) { HashSet() }.add(attrName) + } + + /** + * Materialises the value for [element]: null marker, a resolved xs.ref, or a freshly + * created+populated value via the tag's serializer. + * + * @param Element element The source element. + * @return Any? The created value. + */ + fun createObjectFromElement(element: Element): Any? { + val tag = element.name + if (tag == TAG_NULL) return null + element.getAttributeValue(ATTR_REF)?.let { return references[it] } + val serializer = registry.serializerForTag(tag) + if (serializer == null) { + // Unmodeled tag: keep verbatim so the document still round-trips, and report it. + diagnostics.onUnmodeledTag(tag, element.getAttributeValue(ATTR_NAME) ?: "(item)") + return VerbatimNode(element.clone() as Element) + } + // A typed serializer may still fail on evolved/unknown content (e.g. a newer enum constant, + // an added field, a missing no-arg constructor). Fall back to verbatim + report, so format + // evolution never crashes or loses data - it just isn't typed yet. + return try { + val instance = serializer.createInstance(element, this) ?: return null + element.getAttributeValue(ATTR_ID)?.let { references[it] = instance } + serializer.setupInstance(element, instance, this) + instance + } catch (failure: Exception) { + diagnostics.onUnmodeledTag(tag, "deserialize-failed: ${failure.message}") + VerbatimNode(element.clone() as Element) + } + } +} + +/** + * A deserialized model with the metadata needed to re-emit it byte-identically: the main root + * object, the shared pool in document order (with preserved xs.id/xs.idx), the processing + * instructions, and the `` attributes. + * + * EN: [root] (and the shared objects) are typed where a serializer is registered, else [VerbatimNode]. + * + * @see CMO3.md §3 Payload: main.xml + */ +public class ModelGraph internal constructor( + /** The `
` root object (e.g. CModelSource), typed or verbatim. */ + public val root: Any?, + internal val sharedOrder: MutableList, + internal val sharedInfo: IdentityHashMap, + internal val processingInstructions: List, + internal val rootAttributes: List>, + internal val childOrder: IdentityHashMap>>, + internal val presentAttrs: IdentityHashMap>>, +) { + /** + * Ensures the replayed child order for [owner] at the [tag] level contains a KnownField slot for + * [propertyName], so a field assigned after read reaches the re-emitted document even when the + * source carried no such element (the writer replays recorded slots and would otherwise drop the + * assignment silently). Amends only an EXISTING recorded order: an owner without one already + * emits every declared field, and creating an order here would collapse its output to this + * single slot. The new slot lands immediately before [beforePropertyName]'s slot when that + * anchor exists (matching where the editor writes the field), else at the end. + * + * @param Any owner The object whose child order is amended. + * @param String tag The serializer tag level the order was recorded under. + * @param String propertyName The typed property the slot replays. + * @param String? beforePropertyName The anchor property to insert before, or null to append. + */ + internal fun ensureKnownChildSlot(owner: Any, tag: String, propertyName: String, beforePropertyName: String?) { + val slots = childOrder[owner]?.get(tag) ?: return + val alreadyRecorded = slots.any { slot -> slot is ChildSlot.KnownField && slot.propertyName == propertyName } + if (alreadyRecorded) { + return + } + val newSlot = ChildSlot.KnownField(propertyName) + val anchorIndex = + beforePropertyName?.let { anchor -> + slots.indexOfFirst { slot -> slot is ChildSlot.KnownField && slot.propertyName == anchor } + } ?: -1 + if (anchorIndex >= 0) { + slots.add(anchorIndex, newSlot) + } else { + slots.add(newSlot) + } + } + + /** + * Ensures the @SerialAttribute property [propertyName] of [owner] (at the [tag] level) is emitted + * on write even when the source document omitted the attribute. The writer emits exactly the + * attributes recorded as present at read time, so an attribute assigned after read would otherwise + * be dropped silently. Amends only an EXISTING record: an owner with no recorded attributes at + * [tag] already falls back to emitting every non-default attribute value, and a fresh object never + * has a record. Attributes emit in declaration order regardless of record order, so no anchor is + * needed. + * + * @param Any owner The object whose attribute record is amended. + * @param String tag The serializer tag level the record was captured under. + * @param String propertyName The Kotlin property name of the attribute to emit. + */ + internal fun ensurePresentAttr(owner: Any, tag: String, propertyName: String) { + presentAttrs[owner]?.get(tag)?.add(propertyName) + } +} + +/** + * Top-level model (de)serializer: turns a typed root object into a `
` + * JDOM document (and back), reproducing the editor's shared-pool hoisting and `` PIs. + * + * @see CMO3.md §3 Payload: main.xml + */ +public class SerializeEngine internal constructor( + private val registry: SerializerRegistry, + private val diagnostics: SerializeDiagnostics, +) { + /** + * Serializes [root] into a model document. + * + * @param Any root The model root object (e.g. CModelSource). + * @return Document The `` document with shared pool and version PIs. + */ + public fun writeRoot(root: Any): Document { + val context = WriteContext(registry) + val rootElement = Element(ModelDocument.ROOT_ELEMENT) + val sharedElement = Element(ModelDocument.SHARED_ELEMENT) + val mainElement = Element(ModelDocument.MAIN_ELEMENT) + rootElement.addContent(sharedElement) + rootElement.addContent(mainElement) + + mainElement.addContent(context.createElementFromObject(null, root)) + + // Hoist each shared def into and replace its first (inline) occurrence with a ref. + for (def in context.sharedDefs.sortedBy { it.index }) { + val defElement = def.element + val parent = defElement.parent as Element + val position = parent.indexOf(defElement) + val reference = Element(defElement.name) + defElement.getAttributeValue(ATTR_NAME)?.let { reference.setAttribute(ATTR_NAME, it) } + reference.setAttribute(ATTR_REF, def.refId) + parent.removeContent(defElement) + parent.addContent(position, reference) + defElement.removeAttribute(ATTR_NAME) + defElement.setAttribute(ATTR_INDEX, def.index.toString()) + sharedElement.addContent(defElement) + } + + val document = Document(rootElement) + registry.versions().forEachIndexed { piIndex, (tag, version) -> + document.addContent(piIndex, ProcessingInstruction("version", "$tag:$version")) + } + return document + } + + /** + * Deserializes a model document's `
` root object, resolving the shared pool first. + * + * @param Document document The model document. + * @return Any? The reconstructed root object. + */ + public fun readRoot(document: Document): Any? { + val rootElement = document.rootElement + val context = ReadContext(registry, diagnostics) + + @Suppress("UNCHECKED_CAST") + val sharedChildren = (rootElement.getChild(ModelDocument.SHARED_ELEMENT)?.children as List?).orEmpty() + val created = ArrayList>() + for (element in sharedChildren) { + val id = element.getAttributeValue(ATTR_ID) ?: continue + val serializer = registry.serializerForTag(element.name) ?: continue + val instance = serializer.createInstance(element, context) ?: continue + context.references[id] = instance + created.add(element to instance) + } + for ((element, instance) in created) { + registry.serializerForTag(element.name)?.setupInstance(element, instance, context) + } + + @Suppress("UNCHECKED_CAST") + val mainChild = + (rootElement.getChild(ModelDocument.MAIN_ELEMENT)?.children as List?) + ?.firstOrNull() ?: return null + return context.createObjectFromElement(mainChild) + } + + /** + * Reads a model document into a [ModelGraph]: the `
` root object plus the shared pool + * (preserving each shared object's xs.id/xs.idx and order), the processing instructions, and the + * `` attributes - everything needed to re-emit byte-identically. + * + * @param Document document The model document. + * @return ModelGraph The reconstructed graph with preserved identity metadata. + */ + public fun readModel(document: Document): ModelGraph { + val rootElement = document.rootElement + val context = ReadContext(registry, diagnostics) + val sharedOrder = ArrayList() + val sharedInfo = IdentityHashMap() + + @Suppress("UNCHECKED_CAST") + val sharedChildren = (rootElement.getChild(ModelDocument.SHARED_ELEMENT)?.children as List?).orEmpty() + val typedToSetup = ArrayList>() + for (element in sharedChildren) { + val id = element.getAttributeValue(ATTR_ID) ?: continue + val index = element.getAttributeValue(ATTR_INDEX)?.toIntOrNull() ?: -1 + val serializer = registry.serializerForTag(element.name) + val instance: Any = + if (serializer == null) { + diagnostics.onUnmodeledTag(element.name, "(shared)") + VerbatimNode(element.clone() as Element) + } else { + serializer.createInstance(element, context) ?: continue + } + context.references[id] = instance + sharedInfo[instance] = SharedRef(id, index, element.name) + sharedOrder.add(instance) + if (serializer != null) typedToSetup.add(element to instance) + } + for ((element, instance) in typedToSetup) { + registry.serializerForTag(element.name)?.setupInstance(element, instance, context) + } + + @Suppress("UNCHECKED_CAST") + val mainChild = (rootElement.getChild(ModelDocument.MAIN_ELEMENT)?.children as List?)?.firstOrNull() + val rootObject = mainChild?.let { context.createObjectFromElement(it) } + + val instructions = + document.content.filterIsInstance().map { it.clone() as ProcessingInstruction } + + @Suppress("UNCHECKED_CAST") + val rootAttributes = (rootElement.attributes as List).map { it.name to it.value } + return ModelGraph( + rootObject, + sharedOrder, + sharedInfo, + instructions, + rootAttributes, + context.childOrder, + context.presentAttrs, + ) + } + + /** + * Re-emits a [ModelGraph] to a document, reusing the preserved shared ids/order and PIs so an + * unedited graph round-trips byte-identical. Known-shared objects become xs.ref by identity. + * Fresh objects (added after read) referenced more than once are hoisted into the shared pool + * after the preserved entries, with ids and indexes continuing past the preserved maxima. + * + * @param ModelGraph graph The graph to serialize. + * @return Document The reconstructed model document. + */ + public fun writeModel(graph: ModelGraph): Document { + val rootElement = Element(ModelDocument.ROOT_ELEMENT) + for ((attrName, attrValue) in graph.rootAttributes) rootElement.setAttribute(attrName, attrValue) + val sharedElement = Element(ModelDocument.SHARED_ELEMENT) + val mainElement = Element(ModelDocument.MAIN_ELEMENT) + rootElement.addContent(sharedElement) + rootElement.addContent(mainElement) + + val context = WriteContext(registry, graph.sharedInfo, graph.childOrder, graph.presentAttrs) + graph.root?.let { mainElement.addContent(context.createElementFromObject(null, it)) } + + for (instance in graph.sharedOrder) { + val sharedRef = graph.sharedInfo.getValue(instance) + val defElement: Element = + if (instance is VerbatimNode) { + instance.element.clone() as Element + } else { + val element = registry.serializerForValue(instance).createElement(null, instance, context) + element.setAttribute(ATTR_ID, sharedRef.id) + element.setAttribute(ATTR_INDEX, sharedRef.index.toString()) + element + } + sharedElement.addContent(defElement) + } + + // Hoist fresh shared defs (objects added after read whose second use stamped an xs.id on the + // first inline def) into , the same replace-with-ref move writeRoot performs. This + // runs after both the main and the preserved-pool emission so defs nested inside preserved + // shared subtrees are caught too. xs.idx continues past the preserved maximum, keeping fresh + // entries clear of the source document's pool indexes. + var nextSharedIndex = (graph.sharedInfo.values.maxOfOrNull { sharedRef -> sharedRef.index } ?: -1) + 1 + for (def in context.sharedDefs.sortedBy { it.index }) { + val defElement = def.element + val parent = defElement.parent as Element + val position = parent.indexOf(defElement) + val reference = Element(defElement.name) + defElement.getAttributeValue(ATTR_NAME)?.let { reference.setAttribute(ATTR_NAME, it) } + reference.setAttribute(ATTR_REF, def.refId) + parent.removeContent(defElement) + parent.addContent(position, reference) + defElement.removeAttribute(ATTR_NAME) + defElement.setAttribute(ATTR_INDEX, nextSharedIndex.toString()) + sharedElement.addContent(defElement) + nextSharedIndex++ + } + + val document = Document(rootElement) + graph.processingInstructions.forEachIndexed { piIndex, instruction -> + document.addContent(piIndex, instruction.clone() as ProcessingInstruction) + } + return document + } + + public companion object { + /** + * Builds an engine for the given model classes (registered by their @SerialTag / simple name). + * + * @param Collection classes The model classes to register. + * @param SerializeDiagnostics diagnostics Sink for unmodeled-tag reports (default no-op). + * @return SerializeEngine A ready engine. + */ + public fun of( + classes: Collection>, + diagnostics: SerializeDiagnostics = SerializeDiagnostics.None, + ): SerializeEngine { + val registry = SerializerRegistry() + classes.forEach(registry::register) + return SerializeEngine(registry, diagnostics) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/Serializers.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/Serializers.kt new file mode 100644 index 0000000..f8f80b1 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/Serializers.kt @@ -0,0 +1,286 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element +import org.umamo.format.cmo3.serialize.annotations.DontSerialize +import org.umamo.format.cmo3.serialize.annotations.DontSerializeIfDefault +import org.umamo.format.cmo3.serialize.annotations.SerialAttribute +import org.umamo.format.cmo3.serialize.annotations.SerialName +import org.umamo.format.cmo3.serialize.annotations.SuppressSerializeSuperClass +import kotlin.reflect.KClass +import kotlin.reflect.KMutableProperty1 +import kotlin.reflect.full.declaredMemberProperties +import kotlin.reflect.full.findAnnotation +import kotlin.reflect.jvm.isAccessible +import kotlin.reflect.jvm.javaField + +// Serializer attribute/tag names (the on-disk xs.* attributes and primitive tags). +internal const val ATTR_NAME: String = "xs.n" +internal const val ATTR_ID: String = "xs.id" +internal const val ATTR_REF: String = "xs.ref" +internal const val ATTR_INDEX: String = "xs.idx" +internal const val ATTR_COUNT: String = "count" +internal const val TAG_NULL: String = "null" +internal const val NAME_SUPER: String = "super" + +/** + * Maps a model value to/from a JDOM element: + * objects are created empty ([createInstance]) then populated ([setupInstance]) so cyclic/shared + * references resolve; primitives ignore [setupInstance] and return their value from [createInstance]. + * + * @see CMO3.md §3 Serializer mechanics + */ +internal interface XmlSerializer { + /** + * Builds the element for [value] (already known non-null and not a back-reference). + * + * @param String? name The owning field name (becomes xs.n), or null for collection items. + * @param Any value The value to serialize. + * @param WriteContext ctx Shared write state (object identity, shared pool). + * @return Element The new element. + */ + fun createElement(name: String?, value: Any, ctx: WriteContext): Element + + /** + * Creates the value/instance for [element] (empty for class objects; the final value for leaves). + * + * @param Element element The source element. + * @param ReadContext ctx Shared read state (reference map). + * @return Any? The created value (null only for the `` tag, handled by the engine). + */ + fun createInstance(element: Element, ctx: ReadContext): Any? + + /** + * Populates a class instance's fields from [element]. No-op for leaf values. + * + * @param Element element The source element. + * @param Any instance The instance created by [createInstance]. + * @param ReadContext ctx Shared read state. + */ + fun setupInstance(element: Element, instance: Any, ctx: ReadContext) {} +} + +/** Sets the xs.n attribute when [name] is non-null (collection items omit it). */ +internal fun Element.setFieldName(name: String?) { + if (name != null) setAttribute(ATTR_NAME, name) +} + +/** + * Leaf serializer for a primitive/string: `value` (value = toString()). + * Scalars are written with their natural string form (e.g. 1.0, true). + */ +internal class PrimitiveSerializer( + private val tag: String, + private val parse: (String) -> Any, +) : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val element = Element(tag) + element.setFieldName(name) + element.text = value.toString() + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any = parse(element.text) +} + +/** + * Serializer for ordered collections: `` with positional item children + * (items carry no xs.n). Covers ArrayList ("array_list") and CArrayList ("carray_list"); [factory] + * builds the concrete list type so the tag round-trips (read tag -> type -> same tag on write). + */ +internal class ListSerializer( + private val tag: String, + private val factory: () -> MutableList, +) : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val list = value as List<*> + val element = Element(tag) + element.setFieldName(name) + element.setAttribute(ATTR_COUNT, list.size.toString()) + for (item in list) element.addContent(ctx.createElementFromObject(null, item)) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any { + val out = factory() + @Suppress("UNCHECKED_CAST") + for (child in element.children as List) out.add(ctx.createObjectFromElement(child)) + return out + } +} + +/** + * Reflective serializer for a model class, bound to one class in the hierarchy: writes this class's + * declared properties as child + * elements (xs.n = property name) in backing-field declaration order, and nests the superclass as a + * `` child unless @SuppressSerializeSuperClass. + * + * @see CMO3.md §3 Serializer mechanics + */ +internal class ReflectiveClassSerializer( + val kClass: KClass<*>, + private val registry: SerializerRegistry, +) : XmlSerializer { + private val tag: String = registry.tagFor(kClass) + private val suppressSuper: Boolean = kClass.findAnnotation() != null + + // Declared, mutable, serialized properties in backing-field declaration order. + private val properties: List> = buildProperties() + + // @SerialAttribute properties are written on the tag; the rest are child elements. + private val attributeProperties: List> = + properties.filter { it.findAnnotation() != null } + private val childProperties: List> = + properties.filter { it.findAnnotation() == null } + private val childPropertiesByName: Map> = + childProperties.associateBy { childNameOf(it) } + + // Keyed by Kotlin property name, for replaying a recorded child order on write. + private val childPropertiesByPropName: Map> = + childProperties.associateBy { it.name } + + private fun attributeNameOf(property: KMutableProperty1): String = + property.findAnnotation()!!.name.ifEmpty { property.name } + + /** The serialized child name (xs.n): an explicit @SerialName, else the Kotlin property name. */ + private fun childNameOf(property: KMutableProperty1): String = + property.findAnnotation()?.name ?: property.name + + // @DontSerializeIfDefault: skip a property whose value equals the default instance's value. + private val classDefaultIfDefault: Boolean = kClass.findAnnotation() != null + private val skipIfDefault: Set = + properties + .filter { classDefaultIfDefault || it.findAnnotation() != null } + .map { it.name }.toSet() + private val defaultInstance: Any? by lazy { + if (skipIfDefault.isEmpty()) null else runCatching { newInstance() }.getOrNull() + } + + // Serializer for the (serializable, non-Object) superclass, if any. + private val superSerializer: ReflectiveClassSerializer? by lazy { + registry.superSerializerOf( + kClass, + suppressSuper, + ) + } + + private fun newInstance(): Any { + val constructor = kClass.java.getDeclaredConstructor() + constructor.isAccessible = true + return constructor.newInstance() + } + + @Suppress("UNCHECKED_CAST") + private fun buildProperties(): List> { + val fieldOrder = kClass.java.declaredFields.map { it.name } + return kClass.declaredMemberProperties + .filterIsInstance>() + .filter { it.findAnnotation() == null } + .sortedBy { property -> + val fieldName = property.javaField?.name ?: property.name + fieldOrder.indexOf(fieldName).let { if (it < 0) Int.MAX_VALUE else it } + } + .onEach { it.isAccessible = true } + } + + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val element = Element(tag) + element.setFieldName(name) + ctx.setWritten(value, element) // before fields, so self/cyclic refs resolve + // Attributes (on the tag): when this object was read, keep exactly the attributes it had; for a + // freshly built object fall back to dropping @DontSerializeIfDefault defaults. + val presentAttrs = ctx.presentAttrsFor(value, tag) + for (property in attributeProperties) { + val propertyValue = property.get(value) + val omit = + if (presentAttrs != null) { + property.name !in presentAttrs + } else { + property.name in skipIfDefault && isDefaultValue(property, propertyValue) + } + if (omit) continue + if (propertyValue != null) element.setAttribute(attributeNameOf(property), propertyValue.toString()) + } + // Child elements: replay the exact sequence read (order, presence and unknown children all + // preserved across schema versions); otherwise emit super + own fields in declaration order. + val order = ctx.childOrderFor(value, tag) + if (order != null) { + for (slot in order) { + when (slot) { + is ChildSlot.Super -> + superSerializer?.let { + element.addContent( + it.createElement( + NAME_SUPER, + value, + ctx, + ), + ) + } + + is ChildSlot.VerbatimChild -> element.addContent(slot.element.clone() as Element) + is ChildSlot.KnownField -> + childPropertiesByPropName[slot.propertyName]?.let { property -> + element.addContent(ctx.createElementFromObject(childNameOf(property), property.get(value))) + } + } + } + } else { + superSerializer?.let { element.addContent(it.createElement(NAME_SUPER, value, ctx)) } + for (property in childProperties) { + val propertyValue = property.get(value) + if (property.name in skipIfDefault && isDefaultValue(property, propertyValue)) continue + element.addContent(ctx.createElementFromObject(childNameOf(property), propertyValue)) + } + } + return element + } + + private fun isDefaultValue(property: KMutableProperty1, propertyValue: Any?): Boolean { + val default = defaultInstance ?: return false + return propertyValue == property.get(default) + } + + override fun createInstance(element: Element, ctx: ReadContext): Any = newInstance() + + override fun setupInstance(element: Element, instance: Any, ctx: ReadContext) { + for (property in attributeProperties) { + val raw = element.getAttributeValue(attributeNameOf(property)) ?: continue + ctx.recordPresentAttr(instance, tag, property.name) + property.set(instance, parseScalar(raw, property)) + } + @Suppress("UNCHECKED_CAST") + for (child in element.children as List) { + val fieldName = child.getAttributeValue(ATTR_NAME) + if (fieldName == NAME_SUPER) { + val superSerializer = this.superSerializer + if (superSerializer != null) { + superSerializer.setupInstance(child, instance, ctx) + ctx.recordSuperChild(instance, tag) + } else { + ctx.recordVerbatimChild(instance, tag, child) // unmodeled superclass - keep verbatim + } + continue + } + val property = childPropertiesByName[fieldName] + if (property == null) { + ctx.recordVerbatimChild(instance, tag, child) // a field newer than our schema - keep it + continue + } + ctx.recordKnownChild(instance, tag, property.name) + property.set(instance, ctx.createObjectFromElement(child)) + } + } + + private fun parseScalar(raw: String, property: KMutableProperty1): Any = + when (property.returnType.classifier) { + Int::class -> raw.toInt() + Float::class -> raw.toFloat() + Double::class -> raw.toDouble() + Long::class -> raw.toLong() + Short::class -> raw.toShort() + Byte::class -> raw.toByte() + Boolean::class -> raw == "true" + Char::class -> raw[0] + else -> raw + } +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/ValueTypeSerializers.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/ValueTypeSerializers.kt new file mode 100644 index 0000000..9e0b16f --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/ValueTypeSerializers.kt @@ -0,0 +1,47 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element +import org.umamo.format.cmo3.model.type.CAffine + +/** + * Custom serializer for CAffine: ``. + * The six matrix floats are written/read as attributes. + * + * @see CMO3.md §3 Serializer mechanics + */ +internal object CAffineSerializer : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val affine = value as CAffine + val element = Element("CAffine") + element.setFieldName(name) + element.setAttribute("m00", affine.m00.toString()) + element.setAttribute("m01", affine.m01.toString()) + element.setAttribute("m02", affine.m02.toString()) + element.setAttribute("m10", affine.m10.toString()) + element.setAttribute("m11", affine.m11.toString()) + element.setAttribute("m12", affine.m12.toString()) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any = + CAffine().apply { + m00 = element.getAttributeValue("m00").toFloat() + m01 = element.getAttributeValue("m01").toFloat() + m02 = element.getAttributeValue("m02").toFloat() + m10 = element.getAttributeValue("m10").toFloat() + m11 = element.getAttributeValue("m11").toFloat() + m12 = element.getAttributeValue("m12").toFloat() + } +} + +/** + * Registers the value-type subsystem (GVector2, CRect, CColor reflective; CAffine custom). + * + * @param SerializerRegistry registry The registry to populate. + */ +internal fun registerValueTypeSubsystem(registry: SerializerRegistry) { + registry.register(org.umamo.format.cmo3.model.type.GVector2::class) + registry.register(org.umamo.format.cmo3.model.type.CRect::class) + registry.register(org.umamo.format.cmo3.model.type.CColor::class) + registry.registerCustom(CAffine::class, CAffineSerializer) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/Verbatim.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/Verbatim.kt new file mode 100644 index 0000000..da176f4 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/Verbatim.kt @@ -0,0 +1,47 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element + +/** + * A not-yet-typed subtree, held verbatim as its detached JDOM element so it round-trips unchanged. + * + * EN: When the engine meets a tag with no registered typed serializer it falls back to this, instead + * of failing - so newer Live2D format additions still load and save losslessly. As subsystems + * get typed, these are replaced by concrete classes. + * JA: 未対応タグはこのノードとして JDOM 要素のまま保持し、無損失で往復させる。 + * + * @see CMO3.md §3 Payload: main.xml + */ +public class VerbatimNode internal constructor( + /** The detached source element (a clone; safe to re-attach to a new tree). */ + internal val element: Element, +) { + /** The element tag this node stands in for (the unmodeled class name). */ + public val tag: String get() = element.name +} + +/** + * Receives notifications when the engine falls back to [VerbatimNode] for an unmodeled tag - so + * gaps in model coverage (or new Live2D additions) are visible rather than silent. + * + * EN: Functional interface; default is [None] (no-op). + * + * @see CMO3.md §3 Payload: main.xml + */ +public fun interface SerializeDiagnostics { + /** + * Called once per element whose tag has no registered typed serializer. + * + * @param String tag The unmodeled element tag (class name). + * @param String path The owning field path within the document (best-effort). + */ + fun onUnmodeledTag(tag: String, path: String) + + public companion object { + /** A diagnostics sink that ignores everything. */ + public val None: SerializeDiagnostics = SerializeDiagnostics { _, _ -> } + } +} + +// TODO(diagnostics): enrich `path` with the full owner stack (e.g. CModelSource.drawables[3].) +// by threading a name stack through ReadContext. Currently best-effort (immediate owner field name). \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/.editorconfig b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/.editorconfig new file mode 100644 index 0000000..699a464 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/.editorconfig @@ -0,0 +1,6 @@ +# GENERATED registration code (ModelGenerator, never hand-edited): it wildcard-imports the entire +# generated model package to register every class in one place. ktlint's no-wildcard-imports rule +# doesn't fit machine-generated code, so it's disabled for this gen/ subtree only. +# EN: generated code exemption. JA: 自動生成コードのためワイルドカードインポート規則を無効化。 +[*.kt] +ktlint_standard_no-wildcard-imports = disabled diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/GeneratedRegistration.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/GeneratedRegistration.kt new file mode 100644 index 0000000..026816b --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/GeneratedRegistration.kt @@ -0,0 +1,179 @@ +// GENERATED by ModelGenerator. Do not edit by hand. +package org.umamo.format.cmo3.serialize.gen + +import org.umamo.format.cmo3.model.gen.* +import org.umamo.format.cmo3.serialize.SerializerRegistry + +/** Registers every generated reflective class + enum. */ +internal fun registerGeneratedSubsystem(registry: SerializerRegistry) { + registry.register(ACAffecterForm::class) + registry.register(ACAffecterSource::class) + registry.register(ACBlend::class) + registry.register(ACDeformerForm::class) + registry.register(ACDeformerOriginalShape::class) + registry.register(ACDeformerSource::class) + registry.register(ACDrawableForm::class) + registry.register(ACDrawableSource::class) + registry.register(ACExtension::class) + registry.register(ACForm::class) + registry.register(ACImageLayer::class) + registry.register(ACLayerEntry::class) + registry.register(ACLayerGroup::class) + registry.register(ACParameterControllableSource::class) + registry.register(ACTextureInput::class) + registry.register(AClip::class) + registry.register(AFilterDef::class) + registry.register(AMappingDetail::class) + registry.register(AValueConnector::class) + registry.register(AlphaComposition::class) + registry.register(Anisotropy::class) + registry.register(AutoLayoutLock::class) + registry.register(AutoYureConfig::class) + registry.register(BindMethod::class) + registry.register(CAffecterSourceSet::class) + registry.register(CArtMeshForm::class) + registry.register(CArtMeshSource::class) + registry.register(CArtPathBrush::class) + registry.register(CArtPathBrushSetting::class) + registry.register(CArtPathBrush_TextureInput::class) + registry.register(CArtPathDrawingCurveType::class) + registry.register(CAutoYureConfigExtension::class) + registry.register(CBlend_Color::class) + registry.register(CBlend_LinearDodge::class) + registry.register(CBlend_Multiply::class) + registry.register(CBlend_Normal::class) + registry.register(CBlend_Normal_Original::class) + registry.register(CBlend_NotSupported::class) + registry.register(CCachedImage::class) + registry.register(CCachedImageManager::class) + registry.register(CControllerCurve::class) + registry.register(CControllerExtension::class) + registry.register(CControllerPoint::class) + registry.register(CCurveForRotationDeformerExtension::class) + registry.register(CDeformerOriginalShapeExtension::class) + registry.register(CDeformerSourceSet::class) + registry.register(CDrawableSourceSet::class) + registry.register(CEditableMeshExtension::class) + registry.register(CEffectParameterGroups::class) + registry.register(CExtendedInterpolationExtension::class) + registry.register(CGameMotionSet::class) + registry.register(CGlueForm::class) + registry.register(CGlueSource::class) + registry.register(CGuide_Modeling::class) + registry.register(CGuidesSetting::class) + registry.register(CImageCanvas::class) + registry.register(CImageIcon::class) + registry.register(CLabelColorType::class) + registry.register(CLayerGroup::class) + registry.register(CLayerIdentifier::class) + registry.register(CLayerInputData::class) + registry.register(CLayerSelectorMap::class) + registry.register(CLayeredImage::class) + registry.register(CMeshGeneratorExtension::class) + registry.register(CMocExportType::class) + registry.register(CModelExportSettingDialogData::class) + registry.register(CModelImageGroup::class) + registry.register(CModelInfo::class) + registry.register(CModelStateSetSet::class) + registry.register(CMotionSyncSettingSource::class) + registry.register(CMotionSyncSettingSourceSet::class) + registry.register(CParameterGroup::class) + registry.register(CParameterGroupSet::class) + registry.register(CParameterSource::class) + registry.register(CParameterSourceSet::class) + registry.register(CPartForm::class) + registry.register(CPartSource::class) + registry.register(CPartSourceSet::class) + registry.register(CPhysicsInput::class) + registry.register(CPhysicsOutput::class) + registry.register(CPhysicsSettingsSource::class) + registry.register(CPhysicsSettingsSourceSet::class) + registry.register(CPhysicsSourceType::class) + registry.register(CPhysicsVertex::class) + registry.register(CPoint::class) + registry.register(CRandomPoseGroupData::class) + registry.register(CRandomPoseParamData::class) + registry.register(CRandomPoseSetting::class) + registry.register(CRandomPoseSettingManager::class) + registry.register(CRotationDeformerSource::class) + registry.register(CTextureAtlas::class) + registry.register(CTextureImage::class) + registry.register(CTextureInputExtension::class) + registry.register(CTextureInput_ModelImage::class) + registry.register(CTextureInput_TextureAtlasRegion::class) + registry.register(CTextureManager::class) + registry.register(CTopologyObserverExtension::class) + registry.register(CWarpDeformerBezierExtension::class) + registry.register(CWarpDeformerForm::class) + registry.register(CWarpDeformerSource::class) + registry.register(CachedImageType::class) + registry.register(ClipByMesh::class) + registry.register(ColorComposition::class) + registry.register(CompatibilityOption_Cubism21to30::class) + registry.register(ConstValueConnector::class) + registry.register(CreationMethod::class) + registry.register(CurveElement::class) + registry.register(EditorEdition::class) + registry.register(Effect::class) + registry.register(EffectParameterType::class) + registry.register(EmptyFilter::class) + registry.register(EnvConnection::class) + registry.register(EnvValueConnector::class) + registry.register(EnvValueSet::class) + registry.register(ExtendedInterpolationSetting::class) + registry.register(ExtendedInterpolationType::class) + registry.register(ExtendedKeyFormMorphTarget::class) + registry.register(ExtendedKeyFormMorphTargetSet::class) + registry.register(FilterEnv::class) + registry.register(FilterMode::class) + registry.register(FilterOutputValueConnector::class) + registry.register(FilterSet::class) + registry.register(FilterValue::class) + registry.register(FixWidthData::class) + registry.register(FormatVersion::class) + registry.register(GTexture::class) + registry.register(GTexture2D::class) + registry.register(GTransform2::class) + registry.register(GuideType::class) + registry.register(IdSet::class) + registry.register(InterpolationType::class) + registry.register(KeyFormMorphTarget::class) + registry.register(KeyFormMorphTargetSet::class) + registry.register(KeyOnParameter::class) + registry.register(KeyformBindingSource::class) + registry.register(KeyformGridAccessKey::class) + registry.register(KeyformGridSource::class) + registry.register(KeyformOnGrid::class) + registry.register(LayerSet::class) + registry.register(LayeredImageWrapper::class) + registry.register(MagFilter::class) + registry.register(MappingItem::class) + registry.register(MeshGenerateSetting::class) + registry.register(MeshPointRefEx::class) + registry.register(MinFilter::class) + registry.register(ModelImageEntry::class) + registry.register(ModelImageFilterEnv::class) + registry.register(ModelImageFilterSet::class) + registry.register(ModelViewerSetting::class) + registry.register(MorphTargetBlendWeightConstraint::class) + registry.register(MorphTargetBlendWeightConstraintSet::class) + registry.register(MorphTargetEditBaseParameterMap::class) + registry.register(MotionSyncMappingSetting::class) + registry.register(MotionSyncPostProcSetting::class) + registry.register(SettingType::class) + registry.register(ShapeMappingDetail::class) + registry.register(SpriteData::class) + registry.register(SyncAudioParam::class) + registry.register(SyncCubismParam::class) + registry.register(SyncType::class) + registry.register(TargetPoint::class) + registry.register(TextureImageGroup::class) + registry.register(TextureState::class) + registry.register(TextureUvData::class) + registry.register(TrackCursorSetting::class) + registry.register(TrackCursorSettingItemType::class) + registry.register(Type::class) + registry.register(WrapMode::class) + registry.register(YureDeformConfig::class) + registry.register(YureRootDirection::class) +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/xml/XmlCodec.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/xml/XmlCodec.kt new file mode 100644 index 0000000..0019dc3 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/xml/XmlCodec.kt @@ -0,0 +1,52 @@ +package org.umamo.format.cmo3.xml + +import org.jdom.Document +import org.jdom.input.SAXBuilder +import org.jdom.output.Format +import org.jdom.output.XMLOutputter +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream + +/** + * Parses and emits the serialized model XML (main.xml) using the editor's exact JDOM backend. + * + * Matches the editor's writer: XMLOutputter + Format.getPrettyFormat() with indent "" and + * TextMode TRIM (line separator "\r\n", UTF-8). Using JDOM 1.1.3 with the same Format reproduces + * main.xml byte-for-byte across the whole corpus; this class centralises that contract so every + * emit path (generic round-trip and the typed model) shares one formatter. + * + * @see CMO3.md §3 Payload: main.xml + */ +public object XmlCodec { + /** + * The editor's output format: pretty layout, empty indent, TRIM text mode. + * + * @return Format A fresh Format instance (XMLOutputter mutates none of ours). + */ + private fun editorFormat(): Format = + Format.getPrettyFormat().apply { + setIndent("") + textMode = Format.TextMode.TRIM // Normalize would collapse spaces in user intended input so use trim instead. + } + + /** + * Parses model XML bytes into a JDOM document, preserving element/attribute/PI order. + * + * @param ByteArray bytes The decompressed main.xml bytes. + * @return Document The parsed JDOM document. + */ + public fun parse(bytes: ByteArray): Document = + SAXBuilder().build(ByteArrayInputStream(bytes)) + + /** + * Serializes a JDOM document back to bytes using the editor's exact format. + * + * @param Document document The document to emit. + * @return ByteArray The UTF-8 encoded XML, byte-compatible with the editor. + */ + public fun write(document: Document): ByteArray { + val sink = ByteArrayOutputStream() + XMLOutputter(editorFormat()).output(document, sink) + return sink.toByteArray() + } +} \ No newline at end of file diff --git a/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/kra/KraReader.kt b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/kra/KraReader.kt new file mode 100644 index 0000000..3ef3ec0 --- /dev/null +++ b/module/format/src/jvmAndroidMain/kotlin/org/umamo/format/kra/KraReader.kt @@ -0,0 +1,476 @@ +package org.umamo.format.kra + +import org.jdom.Element +import org.jdom.input.SAXBuilder +import org.umamo.format.FileKind +import org.umamo.format.art.ArtReader +import org.umamo.format.art.ChannelMask +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer +import org.umamo.format.binary.ZipArchive +import org.xml.sax.InputSource +import java.io.ByteArrayInputStream +import java.io.StringReader +import kotlin.math.max +import kotlin.math.min + +/** + * Krita .kra reader (desktop JVM and Android). + * + * A .kra is a ZIP holding maindoc.xml (the DOC/IMAGE layer tree) plus one tiled pixel-data file per + * raster layer under imageName/layers/. This reader unzips it, walks the layer tree, and decodes + * each paint layer into the neutral SourceArt model - the same shape the PSD reader produces, so it + * drops straight into the render and re-import paths. + * + * Scope: read-only; paint layers only (groups are traversed for hierarchy, all other node types + * skipped); RGBA and GRAYA color in 8/16/32-bit (see resolveKraPixelFormat). + * + * JDOM alone keeps this reader in jvmAndroidMain: the archive goes through the commonMain ZipArchive. + */ +object KraReader : ArtReader { + override val kind: FileKind = FileKind.Kra + + /** + * True if [candidateBytes] looks like a Krita archive (see isKra). + * + * @param ByteArray candidateBytes Candidate file contents. + * @return Boolean Whether the archive announces itself as a Krita document. + */ + override fun matches(candidateBytes: ByteArray): Boolean = isKra(candidateBytes) + + /** + * Decodes a .kra into the neutral SourceArt model: every paint layer with its placement, flags, + * stable uuid, and decoded RGBA pixels, ordered bottom-to-top (matching the PSD reader). + * + * @param ByteArray bytes The complete .kra file. + * @return SourceArt the canvas size and the parsed layers. + */ + override fun read(bytes: ByteArray): SourceArt { + val entries = unzipEntries(bytes) + val mainXml = + entries["maindoc.xml"] ?: entries["root"] + ?: error("not a .kra: no maindoc.xml in the archive") + + // JDOM finds elements by namespace-qualified name; KRA files carry a default namespace that + // also differs between schema versions (calligra.org vs koffice.org). So we match by local + // name throughout (see childrenNamed) and read attributes, which carry no namespace, directly. + val documentRoot = parseMainDocument(mainXml) + val imageElement = + documentRoot.childrenNamed("IMAGE").firstOrNull() + ?: error("malformed .kra: DOC has no IMAGE") + + // KRA: kis_kra_saver.cpp - IMAGE name/width/height/colorspacename attributes. + val imageName = imageElement.getAttributeValue("name") ?: "unnamed" + val canvasWidth = imageElement.getAttributeValue("width")?.toIntOrNull() ?: 0 + val canvasHeight = imageElement.getAttributeValue("height")?.toIntOrNull() ?: 0 + val imageColorSpace = imageElement.getAttributeValue("colorspacename") ?: "RGBA" + + // Depth-first, document order = top-to-bottom (the first layer element is the topmost). + val paintLayersTopToBottom = ArrayList() + val groupPaths = ArrayList() + val groups = ArrayList() + val topLayers = + imageElement.childrenNamed("layers").firstOrNull() // newer schema: lowercase layers + ?: imageElement.childrenNamed("LAYERS").firstOrNull() // legacy schema: uppercase LAYERS + if (topLayers != null) { + collectPaintLayers(topLayers, parentPath = "", paintLayersTopToBottom, groupPaths, groups) + } + + // Build in document order so order is top-most = 0, then reverse to bottom-to-top for the + // painter's-algorithm list the compositor expects (same contract as the PSD reader). + val layersTopToBottom = + paintLayersTopToBottom.mapIndexed { documentIndex, layerElement -> + buildLayer( + layerElement = layerElement, + groupPath = groupPaths[documentIndex], + order = documentIndex, + imageName = imageName, + imageColorSpace = imageColorSpace, + entries = entries, + ) + } + + return KraSourceArt( + widthPx = canvasWidth, + heightPx = canvasHeight, + layers = layersTopToBottom.reversed(), + groups = groups, + ) + } +} + +/** + * True if bytes is a Krita archive: a ZIP whose first, stored entry is the mimetype file holding + * application/x-krita. Krita writes that entry first and uncompressed (like ODF/EPUB), so the marker + * sits in the first few dozen bytes and a short prefix scan identifies the format without unzipping. + * A .kra re-saved by a tool that drops the mimetype entry will not match here, in which case the + * format registry's extension fallback covers it. + * + * @param ByteArray bytes Candidate file contents. + * @return Boolean Whether the archive announces itself as a Krita document. + */ +private fun isKra(bytes: ByteArray): Boolean { + // KRA: ZIP local-file-header magic @ +0x00, then the mimetype entry content (KoQuaZipStore.cpp:165 + // writes it first/uncompressed). A .kra carries TWO similar-looking Krita mime strings and they + // are not interchangeable: the mimetype entry holds "application/x-krita", while "application/x-kra" + // is the attribute inside maindoc.xml (see docs/format/KRA.md §1). Matching the + // latter here finds nothing — it is not even a prefix of the former, the two diverge at "kr|a" vs + // "kr|ita" — so scan for the real entry content. Both are accepted anyway: neither string can + // occur this early in a non-Krita ZIP, so allowing both only buys tolerance of writer variation. + val zipMagic = byteArrayOf(0x50, 0x4B, 0x03, 0x04) // "PK\x03\x04" + if (bytes.size < zipMagic.size) { + return false + } + for (magicIndex in zipMagic.indices) { + if (bytes[magicIndex] != zipMagic[magicIndex]) { + return false + } + } + val scanLimit = min(bytes.size, 128) + return KRA_MIMETYPE_MARKERS.any { marker -> indexOfBytes(bytes, marker.encodeToByteArray(), scanLimit) >= 0 } +} + +/** + * The mimetype-entry contents that identify a Krita archive. + * + * "application/x-krita" is what Krita actually writes; "application/x-kra" is accepted defensively + * (it is the maindoc.xml `` value, and is what an earlier version of this check looked + * for by mistake). + */ +private val KRA_MIMETYPE_MARKERS = listOf("application/x-krita", "application/x-kra") + +/** + * Returns the start index of the first occurrence of needle within haystack[0, scanLimit), or -1. + * + * @param ByteArray haystack The buffer to search. + * @param ByteArray needle The byte sequence to find. + * @param Int scanLimit Exclusive upper bound on where a match may start. + * @return Int the start index of the match, or -1 if absent. + */ +private fun indexOfBytes(haystack: ByteArray, needle: ByteArray, scanLimit: Int): Int { + if (needle.isEmpty()) { + return -1 + } + val lastStart = min(scanLimit, haystack.size - needle.size + 1) + var startIndex = 0 + while (startIndex < lastStart) { + var matchIndex = 0 + while (matchIndex < needle.size && haystack[startIndex + matchIndex] == needle[matchIndex]) { + matchIndex++ + } + if (matchIndex == needle.size) { + return startIndex + } + startIndex++ + } + return -1 +} + +/** + * Recursively gathers paint-layer elements in document order, building each one's slash-joined + * group path from its ancestor group names, and emits a neutral SourceGroup for every group layer + * encountered (so folder-level visibility and blend survive the flattening to a leaf list). + * + * @param Element container A layers/LAYERS element to walk. + * @param String parentPath Slash-joined names of the enclosing groups (empty at root). + * @param MutableList paintLayers Accumulates paint-layer elements in order. + * @param MutableList groupPaths Accumulates each paint layer's group path (parallel list). + * @param MutableList groups Accumulates a SourceGroup per group layer, by path. + */ +private fun collectPaintLayers( + container: Element, + parentPath: String, + paintLayers: MutableList, + groupPaths: MutableList, + groups: MutableList, +) { + for (layerElement in container.childrenNamed("layer")) { + // KRA: nodetype (newer) or layertype (legacy) names the node class. + val rawNodeType = + layerElement.getAttributeValue("nodetype") + ?: layerElement.getAttributeValue("layertype") + ?: "" + val nodeType = rawNodeType.lowercase() + val name = layerElement.getAttributeValue("name") ?: "" + when (nodeType) { + "grouplayer" -> { + val childPath = if (parentPath.isEmpty()) name else "$parentPath/$name" + groups.add(buildGroup(layerElement, childPath, name)) + val nested = + layerElement.childrenNamed("layers").firstOrNull() + ?: layerElement.childrenNamed("LAYERS").firstOrNull() + if (nested != null) { + collectPaintLayers(nested, childPath, paintLayers, groupPaths, groups) + } + } + + "paintlayer" -> { + paintLayers.add(layerElement) + groupPaths.add(parentPath) + } + // adjustment/generator/clone/shape/file layers and masks carry no plain raster - skip. + else -> Unit + } + } +} + +/** + * Builds a neutral SourceGroup from a Krita group-layer element. + * + * KRA group layers carry the same visibility/opacity/composite attributes as paint layers, plus a + * passthrough flag (a non-isolating folder). Krita has no per-folder "clip to below" concept that + * maps cleanly onto the neutral clipped flag (its inherit-alpha lives in channelflags and needs the + * resolved color space), so clipped is left false here; the source-art compositor only consumes + * group visibility today. + * + * @param Element groupElement The grouplayer element. + * @param String path The slash-joined folder path including this folder's name. + * @param String name The folder name. + * @return SourceGroup the neutral folder descriptor. + */ +private fun buildGroup(groupElement: Element, path: String, name: String): SourceGroup = + KraSourceGroup( + path = path, + name = name, + // KRA: a group layer's @visible "0" hides the whole subtree (kis_kra_loader sets node visible). + visible = groupElement.getAttributeValue("visible") != "0", + opacity = (groupElement.getAttributeValue("opacity")?.toIntOrNull() ?: 255) / 255f, + clipped = false, + blend = parseCompositeOp(groupElement.getAttributeValue("compositeop")), + // KRA: @passthrough "1" is a non-isolating folder; its blend then does not apply. + passThrough = groupElement.getAttributeValue("passthrough") == "1", + ) + +/** + * Decodes one paint layer into a SourceLayer: reads its tile file, resolves the color format, + * applies the default pixel, and assembles a cropped RGBA8888 raster placed on the canvas. + * + * @param Element layerElement The paintlayer element. + * @param String groupPath Slash-joined ancestor group names. + * @param Int order Draw order, top-most = 0. + * @param String imageName The IMAGE name (the layer-data directory prefix). + * @param String imageColorSpace Fallback color space if the layer omits its own. + * @param Map entries All decompressed ZIP entries by name. + * @return SourceLayer the decoded layer. + */ +private fun buildLayer( + layerElement: Element, + groupPath: String, + order: Int, + imageName: String, + imageColorSpace: String, + entries: Map, +): SourceLayer { + val name = layerElement.getAttributeValue("name") ?: "" + val filename = + layerElement.getAttributeValue("filename") + ?: error("KRA paint layer '$name' has no filename") + // KRA: layer uuid is rename/reorder-stable - the re-import key advantage over PSD name+order. + val uuid = layerElement.getAttributeValue("uuid") ?: "$groupPath/$name#$order" + // KRA: @visible "0" is the eye-off layer; absent or any other value means shown. + val visible = layerElement.getAttributeValue("visible") != "0" + val opacity = (layerElement.getAttributeValue("opacity")?.toIntOrNull() ?: 255) / 255f + val layerX = layerElement.getAttributeValue("x")?.toIntOrNull() ?: 0 + val layerY = layerElement.getAttributeValue("y")?.toIntOrNull() ?: 0 + val colorspaceName = layerElement.getAttributeValue("colorspacename") ?: imageColorSpace + val blend = parseCompositeOp(layerElement.getAttributeValue("compositeop")) + + val layerDataPath = "$imageName/layers/$filename" + val tileBytes = entries[layerDataPath] ?: error("KRA layer data missing: $layerDataPath") + val tiles = parseKraLayerTiles(tileBytes) + val format = resolveKraPixelFormat(colorspaceName, tiles.pixelSize) + val defaultPixelBytes = entries["$layerDataPath.defaultpixel"] + + // Per-channel enable mask (channelflags); its width is the channel count, so the format must be + // resolved first. A disabled alpha channel is Krita's "Inherit Alpha" - the clipping signal. + val channelMask = channelMaskFrom(layerElement.getAttributeValue("channelflags"), format) + + val assembled = assembleRaster(tiles, format, defaultPixelBytes, layerX, layerY) + + return KraSourceLayer( + id = LayerId(uuid), + name = name, + visible = visible, + groupPath = groupPath, + order = order, + bounds = assembled.bounds, + opacity = opacity, + clipped = !channelMask.alpha, // KRA: a disabled alpha channel is "Inherit Alpha" = clipping. + blend = blend, + channelMask = channelMask, + raster = assembled.raster, + ) +} + +private class AssembledRaster(val bounds: LayerBounds, val raster: LayerRaster) + +/** + * Composes a layer's tiles into one cropped RGBA8888 buffer sized to the union of its tile rects, + * pre-filled with the converted default pixel, and positioned on the canvas via the layer offset. + * + * @param KraLayerTiles tiles The decoded tiles and geometry. + * @param KraPixelFormat format The source pixel format and converter. + * @param ByteArray? defaultPixelBytes The defaultpixel bytes (native order), or null. + * @param Int layerX Layer canvas X offset (KRA: node->setX). + * @param Int layerY Layer canvas Y offset (KRA: node->setY). + * @return AssembledRaster the bounds (top-left origin) and packed pixels. + */ +private fun assembleRaster( + tiles: KraLayerTiles, + format: KraPixelFormat, + defaultPixelBytes: ByteArray?, + layerX: Int, + layerY: Int, +): AssembledRaster { + if (tiles.tiles.isEmpty()) { + // An empty paint layer: a 1x1 transparent placeholder keeps downstream dimensions valid. + return AssembledRaster(LayerBounds(layerX, layerY, 1, 1), LayerRaster(1, 1, ByteArray(4))) + } + + var minLeft = Int.MAX_VALUE + var minTop = Int.MAX_VALUE + var maxRight = Int.MIN_VALUE + var maxBottom = Int.MIN_VALUE + for (tile in tiles.tiles) { + minLeft = min(minLeft, tile.left) + minTop = min(minTop, tile.top) + maxRight = max(maxRight, tile.left + tiles.tileWidth) + maxBottom = max(maxBottom, tile.top + tiles.tileHeight) + } + val width = maxRight - minLeft + val height = maxBottom - minTop + val rgba = ByteArray(width * height * 4) + + // Pre-fill with the converted default pixel (the color Krita uses for untiled gaps). A + // transparent default leaves the zero-initialised buffer untouched. + val fillPixel = ByteArray(4) + if (defaultPixelBytes != null && defaultPixelBytes.size >= format.pixelSize) { + format.convertPixel(defaultPixelBytes, 0, fillPixel, 0) + } + if (fillPixel[0].toInt() != 0 || fillPixel[1].toInt() != 0 || fillPixel[2].toInt() != 0 || fillPixel[3].toInt() != 0) { + for (pixelIndex in 0 until width * height) { + fillPixel.copyInto(rgba, pixelIndex * 4, 0, 4) + } + } + + for (tile in tiles.tiles) { + for (rowIndex in 0 until tiles.tileHeight) { + val destinationY = tile.top - minTop + rowIndex + val rowBase = (destinationY * width + (tile.left - minLeft)) * 4 + val sourceRowBase = rowIndex * tiles.tileWidth * tiles.pixelSize + for (columnIndex in 0 until tiles.tileWidth) { + format.convertPixel( + tile.pixels, + sourceRowBase + columnIndex * tiles.pixelSize, + rgba, + rowBase + columnIndex * 4, + ) + } + } + } + + val bounds = LayerBounds(left = minLeft + layerX, top = minTop + layerY, width = width, height = height) + return AssembledRaster(bounds, LayerRaster(width = width, height = height, rgba = rgba)) +} + +/** + * Maps a Krita compositeop id to the neutral LayerBlend set; unknown ops degrade to Normal. + * + * @param String? compositeOp The compositeop attribute value. + * @return LayerBlend the closest supported blend mode. + */ +private fun parseCompositeOp(compositeOp: String?): LayerBlend = + // KRA: composite op ids (libs/pigment/compositeops). + when (compositeOp?.lowercase()) { + "multiply" -> LayerBlend.Multiply + "screen" -> LayerBlend.Screen + "add", "linear_dodge" -> LayerBlend.Add + else -> LayerBlend.Normal + } + +/** + * Returns this element's direct child elements whose local name equals localName (case-insensitive), + * ignoring XML namespaces - KRA's default namespace varies by schema version. + * + * @param String localName The unqualified element name to match. + * @return List the matching child elements (empty if none). + */ +@Suppress("UNCHECKED_CAST") +private fun Element.childrenNamed(localName: String): List = + (this.children as List).filter { it.name.equals(localName, ignoreCase = true) } + +/** + * Parses maindoc.xml into its root element with external-DTD loading disabled. + * + * KRA's maindoc.xml declares a DOCTYPE pointing at an external DTD (calligra.org or koffice.org) + * that we never need - we only read element/attribute structure. Left enabled, the parser tries to + * fetch that URL and fails (offline, or the URL no longer serves a valid DTD). So we turn off + * external-DTD loading and install a no-op entity resolver as a portable backstop. + * + * @param ByteArray xmlBytes The raw maindoc.xml bytes. + * @return Element the document root (DOC). + */ +private fun parseMainDocument(xmlBytes: ByteArray): Element { + val builder = SAXBuilder() + runCatching { + builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) + } + builder.setEntityResolver { _, _ -> InputSource(StringReader("")) } + return builder.build(ByteArrayInputStream(xmlBytes)).rootElement +} + +/** + * Decompresses every non-directory ZIP entry into memory, keyed by entry name. + * + * Every entry is read up front; a .kra's working set fits comfortably in memory (the PSD reader likewise + * takes the whole file as bytes). The shared ZIP reader verifies each entry's size and CRC-32, so a + * damaged archive fails here rather than decoding garbage layers. + * + * @param ByteArray bytes The complete ZIP archive. + * @return Map every entry's bytes by name. + */ +private fun unzipEntries(bytes: ByteArray): Map { + val archive = ZipArchive.read(bytes) + return archive.entries + .filterNot { entry -> entry.isDirectory } + .associate { entry -> entry.name to archive.contents(entry) } +} + +/** Concrete SourceLayer backing a parsed KRA paint layer. */ +private data class KraSourceLayer( + override val id: LayerId, + override val name: String, + override val visible: Boolean, + override val groupPath: String, + override val order: Int, + override val bounds: LayerBounds, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val channelMask: ChannelMask, + override val raster: LayerRaster, +) : SourceLayer + +/** Concrete SourceGroup backing a parsed KRA group layer. */ +private data class KraSourceGroup( + override val path: String, + override val name: String, + override val visible: Boolean, + override val opacity: Float, + override val clipped: Boolean, + override val blend: LayerBlend, + override val passThrough: Boolean, +) : SourceGroup + +/** Concrete SourceArt backing a parsed KRA document. */ +private data class KraSourceArt( + override val widthPx: Int, + override val heightPx: Int, + override val layers: List, + override val groups: List, +) : SourceArt \ No newline at end of file diff --git a/module/format/src/jvmMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.jvm.kt b/module/format/src/jvmMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.jvm.kt new file mode 100644 index 0000000..179d47f --- /dev/null +++ b/module/format/src/jvmMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.jvm.kt @@ -0,0 +1,29 @@ +package org.umamo.format.clip + +import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver +import org.umamo.format.clip.db.ClipDatabase +import java.nio.file.Files + +/** + * Desktop actual: write the database bytes to a temp file and open the JVM JdbcSqliteDriver over it. + * The driver and temp file are released in finally blocks. The embedded DB already has its tables, so + * we instantiate ClipDatabase(driver) and query WITHOUT calling Schema.create. + * + * @param ByteArray databaseBytes The raw "SQLite format 3" bytes. + * @param Function1 block Runs against the open database. + * @return T The block's result. + */ +internal actual fun useClipDatabase(databaseBytes: ByteArray, block: (ClipDatabase) -> T): T { + val tempDatabasePath = Files.createTempFile("umamo-clip", ".sqlite3") + try { + Files.write(tempDatabasePath, databaseBytes) + val driver = JdbcSqliteDriver("jdbc:sqlite:$tempDatabasePath") + try { + return block(ClipDatabase(driver)) + } finally { + driver.close() + } + } finally { + Files.deleteIfExists(tempDatabasePath) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/DeformerChannelProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/DeformerChannelProbeTest.kt new file mode 100644 index 0000000..1c84564 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/DeformerChannelProbeTest.kt @@ -0,0 +1,260 @@ +package org.umamo.format + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CFloatColor +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACDeformerForm +import org.umamo.format.cmo3.model.gen.ACDrawableForm +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CRotationDeformerSource +import org.umamo.format.cmo3.model.gen.CWarpDeformerSource +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CColor +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.model.Rgb +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import java.io.File +import kotlin.test.Test + +/** + * Print-only probe answering one question across the whole corpus: does any real model author a + * non-default opacity, multiply color, or screen color on a WARP or ROTATION DEFORMER keyform? + * + * Both format layers already decode those channels - CMO3 `ACDeformerForm.opacity`/`multiplyColor`/ + * `screenColor` (inherited by `CWarpDeformerForm` and `CRotationDeformerForm`), and MOC3 + * `WarpKeyform`/`RotationKeyform`. The runtime ingest is what drops them: `WarpForm` holds only + * control points and `RotationForm` only the pivot transform, so a deformer-level opacity is + * silently ignored at render time. This probe measures how much that costs on real art before the + * fix is scoped. + * + * Prints the drawable-side channels alongside as the control group - those ARE ingested + * (`MeshForm.opacity`/`multiplyColor`/`screenColor`), so a model showing deformer channels in the + * same range as its drawable channels is direct evidence the gap matters. + * + * Pins nothing; skips gracefully without a corpus. Feeds TODO § Puppet Model, CMO3, MOC3. + */ +class DeformerChannelProbeTest { + /** Cubism's identity values: fully opaque, white multiply, black screen. */ + private val opaque = 1f + private val multiplyIdentity = Rgb(1f, 1f, 1f) + private val screenIdentity = Rgb(0f, 0f, 0f) + + private fun cmo3Samples(): List = + System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { it.isFile }?.sortedBy { it.name } ?: emptyList() + + private fun moc3Samples(): List = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + // work/ holds OUR round-trip output (baked-*/docbaked-*), not authored art - scanning it + // would double-count every source model under a different name. + ?.filter { it.isFile && it.extension.equals("moc3", ignoreCase = true) && !it.path.contains("/work/") } + ?.sortedBy { it.name } + ?.toList() + ?: emptyList() + + /** + * Flattens a CMO3 collection field to a plain list (mirrors Cmo3Import.elementsOf). + * + * @param Any? collection The raw collection field, held as Any?. + * @return List The contained elements. + */ + private fun elementsOf(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun idOf(value: Any?): String? = (value as? Id)?.idstr + + /** + * Reads a CMO3 color field as float RGB, or null when absent (the @DontSerializeIfDefault identity). + * + * @param Any? value The raw multiplyColor / screenColor field. + * @return Rgb? The channels, or null when the field was omitted. + */ + private fun rgbOf(value: Any?): Rgb? = + when (value) { + is CFloatColor -> Rgb(value.red, value.green, value.blue) + // The older argb integer form; unobserved on 5.3 forms but decoded for completeness. + is CColor -> + Rgb( + ((value.argb shr 16) and 0xFF) / 255f, + ((value.argb shr 8) and 0xFF) / 255f, + (value.argb and 0xFF) / 255f, + ) + + else -> null + } + + /** Running tally of how many keyforms deviate from identity on each channel. */ + private class ChannelTally { + var keyformCount = 0 + var nonOpaque = 0 + var nonIdentityMultiply = 0 + var nonIdentityScreen = 0 + var minimumOpacity = Float.MAX_VALUE + + val hasAnything: Boolean get() = nonOpaque > 0 || nonIdentityMultiply > 0 || nonIdentityScreen > 0 + + override fun toString(): String = + "keyforms=$keyformCount nonOpaque=$nonOpaque" + + (if (nonOpaque > 0) " (min ${"%.3f".format(minimumOpacity)})" else "") + + " multiply!=identity=$nonIdentityMultiply screen!=identity=$nonIdentityScreen" + } + + /** + * Folds one keyform's three channels into [tally]. + * + * @param ChannelTally tally The running tally. + * @param Float opacity The keyform's opacity. + * @param Rgb? multiplyColor The keyform's multiply color, or null when absent. + * @param Rgb? screenColor The keyform's screen color, or null when absent. + */ + private fun record(tally: ChannelTally, opacity: Float, multiplyColor: Rgb?, screenColor: Rgb?) { + tally.keyformCount++ + if (opacity != opaque) { + tally.nonOpaque++ + tally.minimumOpacity = minOf(tally.minimumOpacity, opacity) + } + if (multiplyColor != null && multiplyColor != multiplyIdentity) { + tally.nonIdentityMultiply++ + } + if (screenColor != null && screenColor != screenIdentity) { + tally.nonIdentityScreen++ + } + } + + @Test + fun probeCmo3DeformerChannels() { + val files = cmo3Samples() + if (files.isEmpty()) { + println("cmo3.probe not present; skipping CMO3 deformer-channel probe") + return + } + println("=== CMO3 deformer channels (opacity / multiplyColor / screenColor on ACDeformerForm) ===") + val corpusWarp = ChannelTally() + val corpusRotation = ChannelTally() + val corpusDrawable = ChannelTally() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + val deformerSources = elementsOf((root.deformerSourceSet as? CDeformerSourceSet)?._sources) + val warp = ChannelTally() + val rotation = ChannelTally() + val drawable = ChannelTally() + // Per-deformer detail, collected so a hit can be named rather than just counted. + val offenders = mutableListOf() + + for (source in deformerSources) { + val isWarp = source is CWarpDeformerSource + if (!isWarp && source !is CRotationDeformerSource) { + continue + } + val tally = if (isWarp) warp else rotation + val before = tally.nonOpaque + tally.nonIdentityMultiply + tally.nonIdentityScreen + val forms = + when (source) { + is CWarpDeformerSource -> elementsOf(source.keyforms) + is CRotationDeformerSource -> elementsOf(source.keyforms) + else -> emptyList() + } + for (form in forms.filterIsInstance()) { + record(tally, form.opacity, rgbOf(form.multiplyColor), rgbOf(form.screenColor)) + record(if (isWarp) corpusWarp else corpusRotation, form.opacity, rgbOf(form.multiplyColor), rgbOf(form.screenColor)) + } + val after = tally.nonOpaque + tally.nonIdentityMultiply + tally.nonIdentityScreen + if (after > before) { + val name = + when (source) { + is CWarpDeformerSource -> source.localName ?: idOf(source.id) + is CRotationDeformerSource -> source.localName ?: idOf(source.id) + else -> null + } + offenders += "${if (isWarp) "warp" else "rotation"} '$name'" + } + } + + // Art meshes are the only drawable kind carrying keyforms; ACDrawableSource itself has no + // `keyforms` field, so match the concrete type rather than reaching for it reflectively. + for (source in elementsOf((root.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance()) { + for (form in elementsOf(source.keyforms).filterIsInstance()) { + record(drawable, form.opacity, rgbOf(form.multiplyColor), rgbOf(form.screenColor)) + record(corpusDrawable, form.opacity, rgbOf(form.multiplyColor), rgbOf(form.screenColor)) + } + } + + val flag = if (warp.hasAnything || rotation.hasAnything) " <<< DEFORMER CHANNELS IN USE" else "" + println("--- ${file.name}$flag") + println(" warp : $warp") + println(" rotation : $rotation") + println(" drawable : $drawable (control group - already ingested)") + if (offenders.isNotEmpty()) { + println(" deformers with non-identity channels: ${offenders.take(12)}${if (offenders.size > 12) " …+${offenders.size - 12}" else ""}") + } + } + println("=== CMO3 corpus totals ===") + println(" warp : $corpusWarp") + println(" rotation : $corpusRotation") + println(" drawable : $corpusDrawable") + } + + @Test + fun probeMoc3DeformerChannels() { + val files = moc3Samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping MOC3 deformer-channel probe") + return + } + println("=== MOC3 deformer channels (WarpKeyform / RotationKeyform opacity + colors) ===") + val corpusWarp = ChannelTally() + val corpusRotation = ChannelTally() + val corpusArtMesh = ChannelTally() + for (file in files) { + val decoded = + runCatching { Moc3.read(file.readBytes()) }.getOrElse { failure -> + println("--- ${file.name}: decode failed (${failure::class.simpleName}: ${failure.message})") + null + } + val document = decoded ?: continue + val warp = ChannelTally() + val rotation = ChannelTally() + val artMesh = ChannelTally() + for (deformer in document.deformers) { + when (deformer) { + is WarpDeformer -> + for (keyform in deformer.keyforms) { + record(warp, keyform.opacity, keyform.multiplyColor, keyform.screenColor) + record(corpusWarp, keyform.opacity, keyform.multiplyColor, keyform.screenColor) + } + + is RotationDeformer -> + for (keyform in deformer.keyforms) { + record(rotation, keyform.opacity, keyform.multiplyColor, keyform.screenColor) + record(corpusRotation, keyform.opacity, keyform.multiplyColor, keyform.screenColor) + } + } + } + for (mesh in document.artMeshes) { + for (keyform in mesh.keyforms) { + record(artMesh, keyform.opacity, keyform.multiplyColor, keyform.screenColor) + record(corpusArtMesh, keyform.opacity, keyform.multiplyColor, keyform.screenColor) + } + } + val flag = if (warp.hasAnything || rotation.hasAnything) " <<< DEFORMER CHANNELS IN USE" else "" + println("--- ${file.name} (v${document.version})$flag") + println(" warp : $warp") + println(" rotation : $rotation") + println(" artMesh : $artMesh (control group - already ingested)") + } + println("=== MOC3 corpus totals ===") + println(" warp : $corpusWarp") + println(" rotation : $corpusRotation") + println(" artMesh : $corpusArtMesh") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/FormatRegistryTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/FormatRegistryTest.kt new file mode 100644 index 0000000..fb4ca9b --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/FormatRegistryTest.kt @@ -0,0 +1,165 @@ +package org.umamo.format + +import kotlinx.serialization.json.JsonObject +import org.umamo.format.bmp.BmpCodec +import org.umamo.format.clip.ClipReader +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.jpeg.JpegReader +import org.umamo.format.kra.KraReader +import org.umamo.format.moc3.Moc3 +import org.umamo.format.png.PngCodec +import org.umamo.format.psd.PsdReader +import org.umamo.format.tiff.TiffReader +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.webp.WebPReader +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Confirms the format dispatcher routes a file to the right codec by leading magic, falls back to the + * file extension when the magic is unknown, and resolves a codec by [FileKind]. The fixtures are just + * correctly-magicked headers - no full container is needed to exercise `matches`. Every reader, + * PSD included, is registered on every target: PsdReader is pure Kotlin with no desktop-only + * dependency, so these JVM-target assertions hold on Android too. + */ +class FormatRegistryTest { + /** A 64-byte buffer whose first four bytes are the MOC3 magic (what `isMoc3` requires). */ + private fun mocHeaderBytes(): ByteArray = ByteArray(64).also { "MOC3".encodeToByteArray().copyInto(it) } + + /** A buffer whose first four bytes are the CAFF magic (what `isCaff` requires). */ + private fun caffHeaderBytes(): ByteArray = "CAFF".encodeToByteArray() + ByteArray(60) + + /** A buffer whose first four bytes are the PSD signature `8BPS`. */ + private fun psdHeaderBytes(): ByteArray = "8BPS".encodeToByteArray() + ByteArray(60) + + /** + * A ZIP header shaped like a real `.kra`: the local-file-header magic, then the stored `mimetype` + * entry whose content is `application/x-krita`. + * + * The exact string matters and is the reason this helper is spelled out rather than approximated. + * A `.kra` carries two similar Krita mime strings — `application/x-krita` in the mimetype entry and + * `application/x-kra` in maindoc.xml's `` — and they are not interchangeable (they + * diverge at `kr|a` vs `kr|ita`, so neither contains the other). This fixture previously used the + * wrong one, which made the test pass against a header no Krita ever writes while + * [org.umamo.format.kra.KraReader] rejected every real file; see docs/format/KRA.md §1. + */ + private fun kraHeaderBytes(): ByteArray = + byteArrayOf(0x50, 0x4B, 0x03, 0x04) + ByteArray(26) + "mimetype".encodeToByteArray() + + "application/x-krita".encodeToByteArray() + ByteArray(8) + + /** A buffer whose first eight bytes are the CLIP container magic `CSFCHUNK`. */ + private fun clipHeaderBytes(): ByteArray = "CSFCHUNK".encodeToByteArray() + ByteArray(56) + + /** A buffer whose first eight bytes are the PNG signature. */ + private fun pngHeaderBytes(): ByteArray = + byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) + ByteArray(16) + + /** A buffer whose first two bytes are the BMP `BM` signature. */ + private fun bmpHeaderBytes(): ByteArray = byteArrayOf(0x42, 0x4D) + ByteArray(60) + + /** A buffer whose first three bytes are the JPEG SOI + marker prefix. */ + private fun jpegHeaderBytes(): ByteArray = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte()) + ByteArray(16) + + /** A RIFF container tagged `WEBP` in the form-type slot. */ + private fun webpHeaderBytes(): ByteArray = + "RIFF".encodeToByteArray() + ByteArray(4) + "WEBP".encodeToByteArray() + ByteArray(16) + + /** A little-endian TIFF header (`II` 0x2A00). */ + private fun tiffHeaderBytes(): ByteArray = byteArrayOf(0x49, 0x49, 0x2A, 0x00) + ByteArray(16) + + @Test + fun detectRoutesByMagic() { + assertEquals(FileKind.Moc3, FormatRegistry.detect(mocHeaderBytes())?.kind, "MOC3 magic -> Moc3") + assertEquals(FileKind.Cmo3, FormatRegistry.detect(caffHeaderBytes())?.kind, "CAFF magic -> Cmo3") + assertEquals(FileKind.Psd, FormatRegistry.detect(psdHeaderBytes())?.kind, "8BPS magic -> Psd") + assertEquals(FileKind.Kra, FormatRegistry.detect(kraHeaderBytes())?.kind, "ZIP + x-kra marker -> Kra") + assertEquals(FileKind.Clip, FormatRegistry.detect(clipHeaderBytes())?.kind, "CSFCHUNK magic -> Clip") + assertEquals(FileKind.Png, FormatRegistry.detect(pngHeaderBytes())?.kind, "PNG signature -> Png") + assertEquals(FileKind.Bmp, FormatRegistry.detect(bmpHeaderBytes())?.kind, "BM magic -> Bmp") + assertEquals(FileKind.Jpeg, FormatRegistry.detect(jpegHeaderBytes())?.kind, "JPEG SOI -> Jpeg") + assertEquals(FileKind.WebP, FormatRegistry.detect(webpHeaderBytes())?.kind, "RIFF/WEBP -> WebP") + assertEquals(FileKind.Tiff, FormatRegistry.detect(tiffHeaderBytes())?.kind, "TIFF II* -> Tiff") + } + + @Test + fun detectFallsBackToExtensionWhenMagicUnknown() { + val unknown = byteArrayOf(0, 1, 2, 3) + assertEquals(FileKind.Kra, FormatRegistry.detect(unknown, "drawing.kra")?.kind, "unknown magic + .kra -> Kra") + assertEquals(FileKind.Psd, FormatRegistry.detect(unknown, "art.PSD")?.kind, "extension match is case-insensitive") + assertEquals(FileKind.Cmo3, FormatRegistry.detect(unknown, "/path/to/model.cmo3")?.kind, "full path -> extension") + assertEquals(FileKind.Png, FormatRegistry.detect(unknown, "atlas.png")?.kind, "unknown magic + .png -> Png") + assertEquals(FileKind.Bmp, FormatRegistry.detect(unknown, "dump.bmp")?.kind, "unknown magic + .bmp -> Bmp") + assertEquals(FileKind.Jpeg, FormatRegistry.detect(unknown, "photo.jpeg")?.kind, "an alias extension routes to its format too") + assertEquals(FileKind.Tiff, FormatRegistry.detect(unknown, "scan.TIF")?.kind, "and case-insensitively") + } + + /** + * A path with no contents in hand resolves by extension or alias, which is how a file the operating + * system hands over - an argument, a double-click, a drop - is routed before anything reads it. + */ + @Test + fun kindForFileNameResolvesByExtensionOrAlias() { + assertEquals(FileKind.Uma, FormatRegistry.kindForFileName("/home/rigger/Erica.uma")) + assertEquals(FileKind.Uma, FormatRegistry.kindForFileName("C:\\Rigs\\ERICA.UMA"), "case-insensitive, whatever the separator") + assertEquals(FileKind.Cmo3, FormatRegistry.kindForFileName("Erica.cmo3"), "a bare name works as well as a path") + assertEquals(FileKind.Jpeg, FormatRegistry.kindForFileName("photo.jpeg"), "an alias resolves to its format") + assertEquals(FileKind.Tiff, FormatRegistry.kindForFileName("scan.tif")) + assertNull(FormatRegistry.kindForFileName("notes.txt"), "an extension no kind claims") + assertNull(FormatRegistry.kindForFileName("--some-flag"), "and a command-line argument that is not a path at all") + assertNull(FormatRegistry.kindForFileName("Makefile"), "nor is a name with no extension") + } + + /** + * A picker filter for one way in lists that way's extensions and no others, so Import Artwork cannot + * offer a model file and Open cannot offer a PSD. + */ + @Test + fun extensionsForARoleCoverThatRoleAlone() { + val artwork = FormatRegistry.extensionsFor(FileRole.Artwork) + assertEquals(listOf("clip", "kra", "psd", "png", "bmp", "jpg", "jpeg", "webp", "tiff", "tif"), artwork, "every art format the registry reads, aliases included, in registry order") + assertEquals(listOf("uma", "cmo3", "moc3"), FormatRegistry.extensionsFor(FileRole.Document)) + assertTrue(FormatRegistry.extensionsFor(FileRole.Sidecar).isEmpty(), "the JSON family has no registered codec, so nothing lists it") + } + + @Test + fun detectReturnsNullForUnknownBytes() { + assertNull(FormatRegistry.detect(byteArrayOf(0, 1, 2, 3)), "unrecognised magic, no name -> null") + assertNull(FormatRegistry.detect(byteArrayOf(0, 1, 2, 3), "notes.txt"), "unrecognised magic + unknown ext -> null") + } + + @Test + fun forKindResolvesRegisteredCodecsOnly() { + assertSame(Cmo3, FormatRegistry.forKind(FileKind.Cmo3), "Cmo3 codec for FileKind.Cmo3") + assertSame(Moc3, FormatRegistry.forKind(FileKind.Moc3), "Moc3 codec for FileKind.Moc3") + assertSame(KraReader, FormatRegistry.forKind(FileKind.Kra), "KraReader codec for FileKind.Kra") + assertSame(PsdReader, FormatRegistry.forKind(FileKind.Psd), "PsdReader codec for FileKind.Psd") + assertSame(ClipReader, FormatRegistry.forKind(FileKind.Clip), "ClipReader codec for FileKind.Clip") + assertSame(PngCodec, FormatRegistry.forKind(FileKind.Png), "PngCodec codec for FileKind.Png") + assertSame(BmpCodec, FormatRegistry.forKind(FileKind.Bmp), "BmpCodec codec for FileKind.Bmp") + assertSame(JpegReader, FormatRegistry.forKind(FileKind.Jpeg), "JpegReader codec for FileKind.Jpeg") + assertSame(WebPReader, FormatRegistry.forKind(FileKind.WebP), "WebPReader codec for FileKind.WebP") + assertSame(TiffReader, FormatRegistry.forKind(FileKind.Tiff), "TiffReader codec for FileKind.Tiff") + assertSame(Uma, FormatRegistry.forKind(FileKind.Uma), "Uma codec for FileKind.Uma") + } + + /** + * A written UMA file detects as UMA by its mimetype probe and by its extension, and the two ZIP formats + * announcing themselves through a mimetype entry never detect as each other. + */ + @Test + fun umaAndKraDetectApart() { + val umaBytes = Uma.write(UmaModel.create(UmaWriterInfo("Umamo", "test")).withLiveContent(UmaEntryKind.Puppet, JsonObject(emptyMap()))) + assertEquals(FileKind.Uma, FormatRegistry.detect(umaBytes)?.kind, "UMA mimetype probe -> Uma") + assertEquals(FileKind.Uma, FormatRegistry.detect(byteArrayOf(0, 1, 2, 3), "rig.uma")?.kind, "unknown magic + .uma -> Uma") + assertFalse(KraReader.matches(umaBytes), "UMA bytes never match the KRA probe") + assertFalse(Uma.matches(kraHeaderBytes()), "KRA bytes never match the UMA probe") + assertEquals(FileKind.Kra, FormatRegistry.detect(kraHeaderBytes())?.kind, "the KRA header still detects as Kra") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/GetVersionCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/GetVersionCorpusTest.kt new file mode 100644 index 0000000..dc4acb5 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/GetVersionCorpusTest.kt @@ -0,0 +1,52 @@ +package org.umamo.format + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Version +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocVersion +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Corpus-gated `getVersion` probes: real files must report a known version without a full read. + * Skips (with a note) when the sample properties are absent, like the other corpus tests. + */ +class GetVersionCorpusTest { + private val cmo3Sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + private val mocSamplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + @Test + fun cmo3SampleProbesToAKnownGeneration() { + val file = + cmo3Sample ?: run { + println("cmo3.sample not present; skipping cmo3 getVersion corpus test") + return + } + val version = Cmo3.getVersion(file.readBytes()) + assertTrue(version is Cmo3Version, "cmo3 sample probes to a Cmo3Version, got $version") + } + + @Test + fun mocSamplesProbeToTheirVersionByte() { + val directory = + mocSamplesDir ?: run { + println("moc3.samples not present; skipping moc3 getVersion corpus test") + return + } + val samples = + directory.walkTopDown().filter { it.isFile && it.extension.equals("moc3", ignoreCase = true) }.toList() + if (samples.isEmpty()) { + println("moc3.samples contains no .moc3 files; skipping") + return + } + for (sample in samples) { + val bytes = sample.readBytes() + val version = Moc3.getVersion(bytes) + assertTrue(version is MocVersion, "${sample.name} probes to a MocVersion, got $version") + // MOC3.md §version gating: the probe must agree with the raw byte @ +0x04. + assertEquals(bytes[4].toInt() and 0xFF, version.byteValue, "${sample.name} version byte") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/art/AlphaAnalysisCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/art/AlphaAnalysisCorpusTest.kt new file mode 100644 index 0000000..1dd998e --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/art/AlphaAnalysisCorpusTest.kt @@ -0,0 +1,104 @@ +package org.umamo.format.art + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Alpha-analysis invariants over every raster layer of every layered corpus sample (PSD, CLIP, + * KRA). Corpus-gated: auto-discovers test/corpus by walking up from the working directory and + * self-skips when absent so CI stays green without a committed corpus. + * + * The exact-ring run (epsilon 0) asserts the full contract against independent rescans of the + * pixels: null exactly when nothing is opaque (the CLIP/KRA 1x1 transparent placeholders + * exercise this on real files), a matching recount, no opaque pixel outside the trimmed + * bounds, and the structural contour invariants including the signed-area sum. A second run + * at the default epsilon asserts the simplified structure and that simplification only ever + * drops vertices. + */ +class AlphaAnalysisCorpusTest { + @Test + fun analysisInvariantsHoldOnCorpusLayers() { + val samples = locateLayeredCorpusSamples() + if (samples.isEmpty()) { + println("no test/corpus directory; skipping alpha-analysis corpus test") + return + } + for ((sample, reader) in samples) { + checkSample(sample, reader) + } + } + + /** + * Runs the analysis over every raster layer of one sample and asserts the invariants. + * + * @param File sample The layered source file to read. + * @param ArtReader reader The reader that decodes it. + */ + private fun checkSample(sample: File, reader: ArtReader) { + val art = reader.read(sample.readBytes()) + var analyzedLayerCount = 0 + var emptyLayerCount = 0 + val startNanos = System.nanoTime() + for (layer in art.layers) { + if (layer.kind != SourceLayerKind.Raster) { + continue + } + val raster = layer.raster + val expectedCount = countOpaquePixels(raster, DEFAULT_ALPHA_THRESHOLD) + val exact = raster.analyzeAlpha(contourEpsilon = 0f) + if (exact == null) { + assertEquals( + 0, + expectedCount, + "${sample.name}: '${layer.name}' null analysis only for fully-transparent rasters", + ) + emptyLayerCount++ + continue + } + analyzedLayerCount++ + assertTrue(expectedCount > 0, "${sample.name}: '${layer.name}' non-null analysis has opaque pixels") + assertEquals( + expectedCount, + exact.opaquePixelCount, + "${sample.name}: '${layer.name}' count matches an independent recount", + ) + val bounds = exact.opaqueBounds + assertTrue( + bounds.left >= 0 && + bounds.top >= 0 && + bounds.left + bounds.width <= raster.width && + bounds.top + bounds.height <= raster.height, + "${sample.name}: '${layer.name}' trimmed bounds $bounds within raster ${raster.width}x${raster.height}", + ) + assertNoOpaquePixelOutside(raster, bounds, DEFAULT_ALPHA_THRESHOLD) + assertAnalysisInvariants(exact, exactRings = true) + + val simplified = + assertNotNull( + raster.analyzeAlpha(), + "${sample.name}: '${layer.name}' simplified run is non-null too", + ) + assertAnalysisInvariants(simplified, exactRings = false) + assertEquals( + exact.contours.size, + simplified.contours.size, + "${sample.name}: '${layer.name}' simplification never adds or drops contours", + ) + for (contourIndex in exact.contours.indices) { + assertSimplifiedIsVertexSubset( + exact.contours[contourIndex].points, + simplified.contours[contourIndex].points, + "${sample.name}: '${layer.name}' contour $contourIndex", + ) + } + } + val elapsedMillis = (System.nanoTime() - startNanos) / 1_000_000 + println( + "checked ${sample.name}: $analyzedLayerCount layers analyzed, " + + "$emptyLayerCount empty, $elapsedMillis ms", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/art/ArtVisibilityFixtureTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/art/ArtVisibilityFixtureTest.kt new file mode 100644 index 0000000..9e40015 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/art/ArtVisibilityFixtureTest.kt @@ -0,0 +1,141 @@ +package org.umamo.format.art + +import org.umamo.format.clip.ClipReader +import org.umamo.format.kra.KraReader +import org.umamo.format.psd.PsdReader +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Visibility regression tests against purpose-built fixtures whose hidden layers and folders are + * known up front. These are the only tests that prove the readers actually parse visibility with the + * right bit and the right sense from real files: the pure-model cascade test (SourceArtVisibilityTest) + * exercises the algorithm over fakes but never touches a reader, and the structural reader tests only + * assert that wiring is self-consistent - neither can catch a reader that reads the wrong flag, inverts + * hidden/shown, or drops folder visibility. A fixture with a layer the artist deliberately hid does. + * + * Corpus-gated: each fixture self-skips when absent, so CI stays green without the binaries committed. + */ +class ArtVisibilityFixtureTest { + /** + * Finds a fixture by file name anywhere under `test/corpus`. + * + * Deliberately searches by name rather than a fixed relative path: these tests are corpus-gated, so + * a path that stops resolving does not fail — it silently skips, and the fixture stops guarding + * anything. That is exactly what happened when the corpus was reorganized into per-format + * subdirectories and these three lookups still pointed at `test/corpus/`. Searching by name + * survives any further reshuffling. + * + * @param String fileName The fixture's file name, e.g. `EricaVisibilityTest.psd`. + * @return File? The fixture, or null when the corpus does not hold it. + */ + private fun corpusFile(fileName: String): File? { + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return corpus.walkTopDown().firstOrNull { candidate -> candidate.isFile && candidate.name == fileName } + } + directory = directory.parentFile + } + return null + } + + /** + * EricaVisibilityTest.psd has one folder ("Front hair") and one leaf ("Ear R/3") toggled off in + * Photoshop. It checks per-layer flag parsing, folder-header flag parsing, and the ancestor cascade + * in one shot. + */ + @Test + fun psdFixtureHasKnownHiddenFolderAndLayer() { + val file = corpusFile("EricaVisibilityTest.psd") + if (file == null) { + println("no EricaVisibilityTest.psd under test/corpus; skipping PSD visibility fixture test") + return + } + val art = PsdReader.read(file.readBytes()) + + // Folder-header flag: the "Front hair" folder was hidden, every other folder left shown. + val frontHair = art.groups.single { group -> group.path == "Front hair" } + assertFalse(frontHair.visible, "Front hair folder should be parsed as hidden") + val otherFolders = art.groups.filter { group -> group.path != "Front hair" } + assertTrue(otherFolders.all { group -> group.visible }, "no folder other than Front hair is hidden") + + // Cascade: the children keep their own eye on, but the hidden parent makes them not shown. + val frontHairChildren = art.layers.filter { layer -> layer.groupPath == "Front hair" } + assertTrue(frontHairChildren.isNotEmpty(), "Front hair should contain layers") + assertTrue(frontHairChildren.all { layer -> layer.visible }, "Front hair children keep their own eye on") + assertTrue( + frontHairChildren.none { layer -> art.isEffectivelyVisible(layer) }, + "layers under the hidden Front hair folder are not effectively visible", + ) + + // Per-layer flag (independent of folders): the "3" leaf in "Ear R" was hidden directly. + val hiddenLeaf = art.layers.single { layer -> layer.groupPath == "Ear R" && layer.name == "3" } + assertFalse(hiddenLeaf.visible, "Ear R/3 should be parsed as hidden") + assertFalse(art.isEffectivelyVisible(hiddenLeaf), "a hidden leaf is not effectively visible") + + // Positive control: a layer in a shown folder is both visible and effectively visible, so the + // reader is not simply returning false everywhere. + val shownLeaf = art.layers.first { layer -> layer.groupPath == "Tail" } + assertTrue(shownLeaf.visible && art.isEffectivelyVisible(shownLeaf), "Tail layers stay shown") + } + + /** + * KritaLayerVisibility.kra nests a shown folder ("Group 7") inside a hidden one ("Group 6"), so it + * exercises the multi-level cascade: a leaf whose own eye and whose immediate folder are both on is + * still not shown because a grandparent folder is hidden. It also carries a directly-hidden root leaf. + */ + @Test + fun kraFixtureCascadesThroughNestedGroups() { + val file = corpusFile("KritaLayerVisibility.kra") + if (file == null) { + println("no KritaLayerVisibility.kra under test/corpus; skipping KRA visibility fixture test") + return + } + val art = KraReader.read(file.readBytes()) + + // Folder flags: the outer "Group 6" is hidden, the inner "Group 6/Group 7" is shown. + assertFalse(art.groups.single { group -> group.path == "Group 6" }.visible, "Group 6 hidden") + assertTrue(art.groups.single { group -> group.path == "Group 6/Group 7" }.visible, "Group 7 shown") + + // The nested leaf keeps its own eye on and sits in a shown folder, yet the hidden grandparent + // folder makes it not shown - the cascade must walk all the way up, not just to the parent. + val nestedLeaf = art.layers.single { layer -> layer.groupPath == "Group 6/Group 7" } + assertTrue(nestedLeaf.visible, "the nested leaf keeps its own eye on") + assertFalse(art.isEffectivelyVisible(nestedLeaf), "hidden grandparent folder hides the nested leaf") + + // Leaves directly in the hidden folder are likewise not shown despite their own eye on. + val inHiddenFolder = art.layers.filter { layer -> layer.groupPath == "Group 6" } + assertTrue(inHiddenFolder.isNotEmpty() && inHiddenFolder.all { layer -> layer.visible }) + assertTrue(inHiddenFolder.none { layer -> art.isEffectivelyVisible(layer) }, "hidden folder hides its leaves") + + // A directly-hidden root leaf (own eye off, no folder involved). + val hiddenRootLeaf = art.layers.single { layer -> layer.groupPath.isEmpty() && !layer.visible } + assertFalse(art.isEffectivelyVisible(hiddenRootLeaf), "a directly-hidden root leaf is not shown") + + // Positive control: shown root leaves are visible and effectively visible. + val shownRootLeaves = art.layers.filter { layer -> layer.groupPath.isEmpty() && layer.visible } + assertTrue(shownRootLeaves.isNotEmpty() && shownRootLeaves.all { layer -> art.isEffectivelyVisible(layer) }) + } + + /** + * Greyscale.clip carries a hidden leaf ("Layer 2") alongside a shown one ("Layer 1") - a regression + * guard that CLIP's LayerVisibility bitfield is read with the right sense. + */ + @Test + fun clipFixtureHasKnownHiddenLayer() { + val file = corpusFile("Greyscale.clip") + if (file == null) { + println("no Greyscale.clip under test/corpus; skipping CLIP visibility fixture test") + return + } + val art = ClipReader.read(file.readBytes()) + + assertEquals(true, art.layers.single { layer -> layer.name == "Layer 1" }.visible, "Layer 1 shown") + assertEquals(false, art.layers.single { layer -> layer.name == "Layer 2" }.visible, "Layer 2 hidden") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/art/LayeredCorpus.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/art/LayeredCorpus.kt new file mode 100644 index 0000000..fedad4b --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/art/LayeredCorpus.kt @@ -0,0 +1,34 @@ +package org.umamo.format.art + +import org.umamo.format.clip.ClipReader +import org.umamo.format.kra.KraReader +import org.umamo.format.psd.PsdReader +import java.io.File + +/** + * Locates every layered corpus sample (PSD, CLIP, KRA) with the reader that decodes it, walking up + * from the working directory to find test/corpus. + * + * Shared by every corpus-gated layered-art test, so a new corpus subdirectory or a new reader reaches + * all of them at once: a private copy that missed the addition would keep its test printing "checked + * N samples" while never seeing the new format. + * + * @return List> The samples, empty when no corpus is present. + */ +internal fun locateLayeredCorpusSamples(): List> { + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + val samples = mutableListOf>() + for ((subdirectory, reader) in listOf("psd" to PsdReader, "clip" to ClipReader, "krita" to KraReader)) { + File(corpus, subdirectory).listFiles { file -> file.isFile } + ?.sortedBy { file -> file.name } + ?.forEach { file -> samples.add(file to reader) } + } + return samples + } + directory = directory.parentFile + } + return emptyList() +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/atlas/AtlasPackCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/atlas/AtlasPackCorpusTest.kt new file mode 100644 index 0000000..22848d3 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/atlas/AtlasPackCorpusTest.kt @@ -0,0 +1,104 @@ +package org.umamo.format.atlas + +import org.umamo.format.art.ArtReader +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.art.locateLayeredCorpusSamples +import org.umamo.format.png.PngCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Packs every layered corpus sample (PSD, CLIP, KRA) and asserts the packer's contract on real art. + * Corpus-gated: auto-discovers test/corpus by walking up from the working directory and self-skips + * when absent so CI stays green without a committed corpus. + * + * Four claims, all invariant rather than golden - a stored page image would pin this algorithm + * instead of the contract, and the contract is what a repack has to keep: + * + * - every packed tile reads back out of its page byte for byte, + * - no two tiles come within the gutter of each other, + * - each page survives a PNG encode/decode round trip unchanged, + * - and packing the same document twice produces the same pages. + */ +class AtlasPackCorpusTest { + @Test + fun packingInvariantsHoldOnCorpusDocuments() { + val samples = locateLayeredCorpusSamples() + if (samples.isEmpty()) { + println("no test/corpus directory; skipping atlas-pack corpus test") + return + } + for ((sample, reader) in samples) { + checkSample(sample, reader) + } + } + + /** + * Packs one sample's raster layers and asserts the invariants. + * + * @param File sample The layered source file to read. + * @param ArtReader reader The reader that decodes it. + */ + private fun checkSample(sample: File, reader: ArtReader) { + val options = AtlasPackOptions(maxPageSize = 4096) + val art = reader.read(sample.readBytes()) + val items = art.atlasPackItems { layer -> layer.kind == SourceLayerKind.Raster } + if (items.isEmpty()) { + println("checked ${sample.name}: no raster layers") + return + } + + val startNanos = System.nanoTime() + val result = packAtlas(items, options) + val packedNanos = System.nanoTime() + + assertEquals( + items.map { item -> item.key }.sorted(), + (result.placements.map { placement -> placement.key } + result.skipped.map { skip -> skip.key }).sorted(), + "${sample.name}: every layer must be placed or reported", + ) + assertTilesRoundTripByteExact(items, result) + assertNoTileOverlap(result, options.gutter) + for ((pageIndex, page) in result.pages.withIndex()) { + val decoded = PngCodec.read(PngCodec.write(page)) + assertEquals(page.width, decoded.width, "${sample.name}: page $pageIndex width survives PNG") + assertEquals(page.height, decoded.height, "${sample.name}: page $pageIndex height survives PNG") + assertContentEquals(page.rgba, decoded.rgba, "${sample.name}: page $pageIndex pixels survive PNG") + } + + val repacked = packAtlas(items, options) + assertContentEquals( + result.placements, + repacked.placements, + "${sample.name}: an unchanged document must repack identically", + ) + for (pageIndex in result.pages.indices) { + assertContentEquals( + result.pages[pageIndex].rgba, + repacked.pages[pageIndex].rgba, + "${sample.name}: page $pageIndex pixels must repack identically", + ) + } + val occupancy = + result.pages.indices.joinToString(", ") { pageIndex -> + val page = result.pages[pageIndex] + "${page.width}x${page.height} ${(result.pageOccupancy(pageIndex) * 100f).toInt()}%" + } + // Oversized layers are printed rather than asserted away: real source art does contain a + // layer wider than a 4096 page (ricardo_en.clip), and the packer reporting it is the + // contract - packing it would need downscaling, which the packer deliberately does not do. + val oversized = result.skipped.filter { skip -> skip.reason == AtlasPackSkipReason.LargerThanPage } + val oversizedNote = + if (oversized.isEmpty()) { + "" + } else { + ", oversized: ${oversized.joinToString(", ") { skip -> skip.key }}" + } + println( + "checked ${sample.name}: ${result.placements.size} packed, ${result.skipped.size} skipped, " + + "${result.pages.size} page(s) [$occupancy], ${(packedNanos - startNanos) / 1_000_000} ms$oversizedNote", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/binary/ZipJavaOracleTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/binary/ZipJavaOracleTest.kt new file mode 100644 index 0000000..a00d5df --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/binary/ZipJavaOracleTest.kt @@ -0,0 +1,244 @@ +package org.umamo.format.binary + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.util.zip.CRC32 +import java.util.zip.ZipFile +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import java.util.zip.ZipEntry as JavaZipEntry + +/** + * Differential test against java.util.zip in both directions, the way ImageIO stayed an oracle for the + * PNG codec: archives Java writes read identically through ZipArchive, archives ZipWriter writes read + * identically through ZipFile and ZipInputStream, and every corpus .kra lists and inflates the same + * through both readers. + */ +class ZipJavaOracleTest { + /** + * One entry as java.util.zip reads it. + * + * @property String name The entry name. + * @property ByteArray contents The uncompressed bytes. + */ + private class JavaReadEntry( + val name: String, + val contents: ByteArray, + ) + + /** + * Every entry of [bytes], read sequentially through ZipInputStream. + * + * @param ByteArray bytes The archive. + * @return List The entries in stream order. + */ + private fun readWithZipInputStream(bytes: ByteArray): List { + val entries = ArrayList() + ZipInputStream(ByteArrayInputStream(bytes)).use { zip -> + var entry = zip.nextEntry + while (entry != null) { + entries += JavaReadEntry(entry.name, zip.readBytes()) + zip.closeEntry() + entry = zip.nextEntry + } + } + return entries + } + + /** + * Every entry of [bytes], read through ZipFile's central directory. + * + * @param ByteArray bytes The archive. + * @return List The entries in directory order. + */ + private fun readWithZipFile(bytes: ByteArray): List { + val file = File.createTempFile("umamo-zip-oracle", ".zip") + try { + file.writeBytes(bytes) + ZipFile(file).use { zip -> + return zip.entries().toList().map { entry -> JavaReadEntry(entry.name, zip.getInputStream(entry).use { stream -> stream.readBytes() }) } + } + } finally { + file.delete() + } + } + + /** + * Asserts ZipArchive reads [bytes] as exactly [expected]: names in order and contents byte for byte. + * + * @param ByteArray bytes The archive. + * @param List expected The entries java.util.zip read. + * @param String label What is being compared, for failure messages. + */ + private fun assertArchiveReads(bytes: ByteArray, expected: List, label: String) { + val archive = ZipArchive.read(bytes) + assertEquals(expected.map { entry -> entry.name }, archive.entries.map { entry -> entry.name }, "$label: entry names and order") + for ((entryIndex, entry) in archive.entries.withIndex()) { + assertContentEquals(expected[entryIndex].contents, archive.contents(entry), "$label: '${entry.name}' contents") + } + } + + /** + * The entries the synthetic Java archives hold: stored and deflated, empty, a directory, and names + * outside ASCII. + * + * @return List The name, contents, and whether the entry is deflated. + */ + private fun syntheticEntries(): List> = + listOf( + Triple("mimetype", "application/vnd.umamo.uma+zip".encodeToByteArray(), false), + Triple("model/puppet.json", ByteArray(50_000) { byteIndex -> (byteIndex % 17).toByte() }, true), + Triple("empty-deflated", ByteArray(0), true), + Triple("textures/", ByteArray(0), false), + Triple("テクスチャ/ページ.bin", ByteArray(3000) { byteIndex -> (byteIndex * 31).toByte() }, false), + Triple("émoji-😀.txt", "naïve".encodeToByteArray(), true), + ) + + /** + * An archive Java writes with ZipOutputStream, whose deflated entries carry data descriptors. + * + * @param List entries The name, contents, and whether the entry is deflated. + * @return ByteArray The archive. + */ + private fun javaArchiveOf(entries: List>): ByteArray { + val sink = ByteArrayOutputStream() + ZipOutputStream(sink).use { zip -> + for ((name, contents, deflated) in entries) { + val entry = JavaZipEntry(name) + if (!deflated) { + val checksum = CRC32() + checksum.update(contents) + entry.method = JavaZipEntry.STORED + entry.size = contents.size.toLong() + entry.compressedSize = contents.size.toLong() + entry.crc = checksum.value + } + zip.putNextEntry(entry) + zip.write(contents) + zip.closeEntry() + } + } + return sink.toByteArray() + } + + /** + * Archives Java writes read identically through ZipArchive, data descriptors included. + */ + @Test + fun javaWrittenArchivesReadIdentically() { + val bytes = javaArchiveOf(syntheticEntries()) + val archive = ZipArchive.read(bytes) + assertTrue( + archive.entries.any { entry -> (entry.flags and ZipRecords.FLAG_DATA_DESCRIPTOR) != 0 }, + "the Java archive exercises data descriptors", + ) + assertArchiveReads(bytes, readWithZipInputStream(bytes), "Java-written archive") + } + + /** + * A Java archive with more entries than the classic count field holds - which Java writes with Zip64 + * end records - reads whole. + */ + @Test + fun javaZip64ArchiveReads() { + val entries = List(70_000) { entryIndex -> Triple("entry-$entryIndex", byteArrayOf(entryIndex.toByte()), false) } + val bytes = javaArchiveOf(entries) + assertArchiveReads(bytes, entries.map { (name, contents) -> JavaReadEntry(name, contents) }, "Java Zip64 archive") + } + + /** + * A raw copy of a Java entry that carried a data descriptor drops the flag, since the copy's sizes sit + * in its local header - and java.util.zip reads the copy back. + */ + @Test + fun rawCopyOfADataDescriptorEntryDropsTheFlag() { + val source = ZipArchive.read(javaArchiveOf(syntheticEntries())) + val copier = ZipWriter(TEST_DOS_DATE_TIME) + for (entry in source.entries) { + copier.addRaw(entry, source.rawPayload(entry)) + } + val copied = copier.finish() + assertTrue( + ZipArchive.read(copied).entries.none { entry -> (entry.flags and ZipRecords.FLAG_DATA_DESCRIPTOR) != 0 }, + "no copied entry claims a data descriptor", + ) + assertArchiveReads(copied, readWithZipInputStream(copied), "raw copy through ZipInputStream") + } + + /** + * Archives ZipWriter writes read identically through ZipInputStream and ZipFile. + */ + @Test + fun writerOutputReadsThroughJavaZip() { + val entries = syntheticEntries() + val bytes = archiveOf(*entries.toTypedArray()) + val expected = entries.map { (name, contents) -> JavaReadEntry(name, contents) } + for ((label, javaRead) in listOf("ZipInputStream" to readWithZipInputStream(bytes), "ZipFile" to readWithZipFile(bytes))) { + assertEquals(expected.map { entry -> entry.name }, javaRead.map { entry -> entry.name }, "$label: entry names and order") + for ((entryIndex, entry) in javaRead.withIndex()) { + assertContentEquals(expected[entryIndex].contents, entry.contents, "$label: '${entry.name}' contents") + } + } + } + + /** + * A ZipWriter archive with Zip64 end records reads whole through ZipFile, which follows them. + */ + @Test + fun writerZip64OutputReadsThroughZipFile() { + val writer = ZipWriter(TEST_DOS_DATE_TIME) + repeat(70_000) { entryIndex -> + writer.addStored("entry-$entryIndex", byteArrayOf(entryIndex.toByte())) + } + val javaRead = readWithZipFile(writer.finish()) + assertEquals(70_000, javaRead.size, "ZipFile sees every entry") + assertEquals("entry-69999", javaRead.last().name, "the last entry is intact") + assertContentEquals(byteArrayOf(69_999.toByte()), javaRead.last().contents, "and its contents") + } + + /** + * Every corpus .kra lists and inflates identically through ZipArchive and ZipInputStream. Corpus-gated: + * `-Dkra.sample` when set, else every .kra under test/corpus/krita found by walking up from the working + * directory; with neither it self-skips. + */ + @Test + fun corpusKraArchivesMatchZipInputStream() { + val samples = locateKraSamples() + if (samples.isEmpty()) { + println("no kra.sample and no test/corpus/krita samples; skipping the KRA ZIP oracle") + return + } + for (sample in samples) { + val bytes = sample.readBytes() + val expected = readWithZipInputStream(bytes) + assertTrue(expected.isNotEmpty(), "${sample.name}: java.util.zip found entries") + assertArchiveReads(bytes, expected, sample.name) + println("[Umamo][zip] ${sample.name}: ${expected.size} entries match java.util.zip") + } + } + + /** + * Locates the KRA samples: `-Dkra.sample` when set, else every .kra under test/corpus/krita. + * + * @return List The samples, empty when none are configured. + */ + private fun locateKraSamples(): List { + System.getProperty("kra.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus/krita") + if (corpus.isDirectory) { + return corpus.listFiles { file -> file.extension.equals("kra", ignoreCase = true) }?.sortedBy { it.name } ?: emptyList() + } + directory = directory.parentFile + } + return emptyList() + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/clip/ClipReaderTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/clip/ClipReaderTest.kt new file mode 100644 index 0000000..4d2a3ac --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/clip/ClipReaderTest.kt @@ -0,0 +1,108 @@ +package org.umamo.format.clip + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * End-to-end reader test against a real .clip. Corpus-gated: it uses -Dclip.sample= when given, + * else auto-discovers a sample under test/corpus/clip/ by walking up from the working directory; if + * neither is present it self-skips so CI stays green without a committed corpus. + * + * Asserts the structural invariants that matter to the render and re-import paths: a positive canvas + * size, at least one layer, stable non-blank ids, positive bounds, an RGBA buffer sized to each + * layer's dimensions, a top-most-first order permutation, and - when the document has decodable + * raster layers - at least one with real (non-transparent) pixels. + * + * The clipformat prototype repo holds the exhaustive feature-specific tests (blend modes, clipping, + * masks, grayscale/monochrome, layer kinds, visibility); here a single structural test guards the + * ported reader against any real .clip the developer points it at. + */ +class ClipReaderTest { + /** + * Locates every CLIP sample: `-Dclip.sample` when set, else every `.clip` under `test/corpus/clip`. + * + * @return List The samples, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("clip.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus/clip") + if (corpus.isDirectory) { + return corpus.listFiles { file -> file.extension.equals("clip", ignoreCase = true) } + ?.sortedBy { it.name } ?: emptyList() + } + directory = directory.parentFile + } + return emptyList() + } + + @Test + fun readsLayerTreeFromRealClip() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no clip.sample and no test/corpus/clip samples; skipping CLIP reader test") + return + } + for (sample in samples) { + checkSample(sample) + } + } + + /** + * Asserts the reader's structural invariants for one sample. + * + * @param File sample The `.clip` to read. + */ + private fun checkSample(sample: File) { + val bytes = sample.readBytes() + // Detection is asserted alongside the decode: reading directly would leave matches() untested, + // which is exactly how a broken magic check once reached the corpus unnoticed (see KraReader). + assertTrue(ClipReader.matches(bytes), "${sample.name}: detected as CLIP by magic") + val art = ClipReader.read(bytes) + + assertTrue(art.widthPx > 0 && art.heightPx > 0, "${sample.name}: positive canvas size") + assertTrue(art.layers.isNotEmpty(), "${sample.name}: at least one layer") + + for (layer in art.layers) { + assertTrue(layer.id.raw.isNotBlank(), "${sample.name}: layer '${layer.name}' has a stable id") + assertTrue( + layer.bounds.width > 0 && layer.bounds.height > 0, + "${sample.name}: layer '${layer.name}' has positive bounds", + ) + assertTrue( + layer.raster.rgba.size == layer.raster.width * layer.raster.height * 4, + "${sample.name}: layer '${layer.name}' raster sized to its dimensions", + ) + } + + val orderValues = art.layers.map { layer -> layer.order }.sorted() + assertTrue( + orderValues == (0 until art.layers.size).toList(), + "${sample.name}: layer order values form a 0..n-1 permutation", + ) + + // If any layer decoded to a real raster (not a 1x1 placeholder), at least one should carry pixels. + val decodedRasters = art.layers.filter { layer -> layer.raster.width > 1 && layer.raster.height > 1 } + if (decodedRasters.isNotEmpty()) { + val anyVisible = + decodedRasters.any { layer -> + var byteIndex = 3 + var hasAlpha = false + while (byteIndex < layer.raster.rgba.size) { + if (layer.raster.rgba[byteIndex].toInt() != 0) { + hasAlpha = true + break + } + byteIndex += 4 + } + hasAlpha + } + assertTrue(anyVisible, "${sample.name}: a decoded raster layer has non-transparent pixels") + } + println("checked ${sample.name}: ${art.widthPx}x${art.heightPx}, ${art.layers.size} layers, ${art.groups.size} groups") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/clip/ClipSyntheticReaderTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/clip/ClipSyntheticReaderTest.kt new file mode 100644 index 0000000..36e0b5e --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/clip/ClipSyntheticReaderTest.kt @@ -0,0 +1,156 @@ +package org.umamo.format.clip + +import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver +import org.umamo.format.art.SourceLayerKind +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Reads a fully synthetic .clip: a SQLite database generated through the SQLDelight schema, wrapped + * in a hand-assembled CSFCHUNK container. This is the corpus-free ClipReader coverage - the layer + * tree, canvas, folder metadata, and placeholder-raster fallback all assert without a real Clip + * Studio file. Raster tiles are deliberately absent (synthesizing valid tiled pixel data is a job + * of its own); layers fall back to the 1x1 transparent placeholder, which is the documented behavior + * for a layer with no decodable content. + */ +class ClipSyntheticReaderTest { + /** + * Generates a SQLite database with the ClipDatabase schema and the given rows. + * + * The real reader never runs Schema.create (an embedded database already has its tables); the + * FIXTURE runs it precisely because it is building that embedded database from nothing. + * + * @param List insertStatements Raw INSERT statements to run against the fresh schema. + * @return ByteArray The database file's bytes. + */ + private fun syntheticDatabaseBytes(insertStatements: List): ByteArray { + val temporaryDatabasePath = Files.createTempFile("umamo-clip-synthetic", ".sqlite3") + try { + val driver = JdbcSqliteDriver("jdbc:sqlite:$temporaryDatabasePath") + try { + org.umamo.format.clip.db.ClipDatabase.Schema.create(driver) + for (statement in insertStatements) { + driver.execute(null, statement, 0) + } + } finally { + driver.close() + } + return Files.readAllBytes(temporaryDatabasePath) + } finally { + Files.deleteIfExists(temporaryDatabasePath) + } + } + + /** + * One Layer INSERT. Tree links per docs/format/CLIP.md: LayerFirstChildIndex points at the first + * (bottom-most) child, LayerNextIndex at the next sibling, 0 terminates. LayerFolder bit 0x10 + * marks a folder. + * + * @param Long mainId The layer's MainId. + * @param String name The layer name. + * @param Boolean isFolder Whether the folder bit is set. + * @param Long visibility LayerVisibility (bit 0 = shown). + * @param Long opacity LayerOpacity (0..256). + * @param Long composite LayerComposite blend code (30 = folder Through). + * @param Long offsetX LayerOffsetX. + * @param Long offsetY LayerOffsetY. + * @param Long firstChild LayerFirstChildIndex. + * @param Long next LayerNextIndex. + * @param String? uuid LayerUuid, the stable re-import key. + * @return String The INSERT statement. + */ + private fun layerInsert( + mainId: Long, + name: String, + isFolder: Boolean = false, + visibility: Long = 1, + opacity: Long = 256, + composite: Long = 0, + offsetX: Long = 0, + offsetY: Long = 0, + firstChild: Long = 0, + next: Long = 0, + uuid: String? = null, + ): String { + val folderBits = if (isFolder) 0x10L else 0L + val layerType = if (isFolder) 0L else 1L + val uuidLiteral = if (uuid != null) "'$uuid'" else "NULL" + return "INSERT INTO Layer (MainId, LayerName, LayerFolder, LayerType, LayerVisibility, LayerOpacity, " + + "LayerComposite, LayerClip, LayerOffsetX, LayerOffsetY, LayerFirstChildIndex, LayerNextIndex, " + + "LayerUuid, LayerRenderMipmap, LayerRenderOffscrOffsetX, LayerRenderOffscrOffsetY, " + + "LayerLayerMaskMipmap, TextLayerType) " + + "VALUES ($mainId, '$name', $folderBits, $layerType, $visibility, $opacity, $composite, 0, " + + "$offsetX, $offsetY, $firstChild, $next, $uuidLiteral, NULL, 0, 0, NULL, NULL)" + } + + /** A canvas with a root folder holding a bottom Paper layer and a Through folder of two layers. */ + private fun syntheticClipBytes(): ByteArray { + val databaseBytes = + syntheticDatabaseBytes( + listOf( + "INSERT INTO Canvas (CanvasWidth, CanvasHeight, CanvasRootFolder) VALUES (640.0, 480.0, 1)", + layerInsert(mainId = 1, name = "Root", isFolder = true, firstChild = 2), + layerInsert(mainId = 2, name = "Paper", next = 3, uuid = "uuid-paper"), + layerInsert(mainId = 3, name = "Folder1", isFolder = true, composite = 30, firstChild = 4), + layerInsert(mainId = 4, name = "LayerA", opacity = 128, offsetX = 5, offsetY = 7, next = 5, uuid = "uuid-a"), + layerInsert(mainId = 5, name = "LayerB", visibility = 2, uuid = "uuid-b"), + ), + ) + return syntheticClipContainer( + listOf( + "CHNKHead" to byteArrayOf(0, 0, 0, 0), + "CHNKSQLi" to databaseBytes, + "CHNKFoot" to byteArrayOf(), + ), + ) + } + + /** The reader assembles canvas, bottom-to-top layer order, folder metadata, and stable ids. */ + @Test + fun readsTheSyntheticCanvasAndLayerTree() { + val art = ClipReader.read(syntheticClipBytes()) + assertEquals(640, art.widthPx) + assertEquals(480, art.heightPx) + + assertEquals(listOf("Paper", "LayerA", "LayerB"), art.layers.map { layer -> layer.name }, "bottom-to-top document order") + assertEquals(listOf("uuid-paper", "uuid-a", "uuid-b"), art.layers.map { layer -> layer.id.raw }, "LayerUuid is the stable id") + assertEquals(listOf(2, 1, 0), art.layers.map { layer -> layer.order }, "order counts from the topmost layer") + assertEquals(listOf("", "Folder1", "Folder1"), art.layers.map { layer -> layer.groupPath }) + assertTrue(art.layers.all { layer -> layer.kind == SourceLayerKind.Raster }) + + val layerA = art.layers.single { layer -> layer.name == "LayerA" } + assertEquals(0.5f, layerA.opacity, "opacity is the 0..256 CLIP scale normalized") + assertEquals(5, layerA.bounds.left, "a rasterless layer anchors its placeholder at the layer offset") + assertEquals(7, layerA.bounds.top) + assertEquals(1, layerA.bounds.width, "no decodable raster falls back to the 1x1 placeholder") + assertFalse(art.layers.single { layer -> layer.name == "LayerB" }.visible, "visibility bit 0 clear means hidden") + + val folder = art.groups.single { group -> group.path == "Folder1" } + assertTrue(folder.passThrough, "composite 30 is the folder Through mode") + assertTrue(folder.visible) + } + + /** A canvas whose root folder has no rows yields an empty tree rather than failing. */ + @Test + fun readsACanvasWithNoLayers() { + val databaseBytes = + syntheticDatabaseBytes( + listOf("INSERT INTO Canvas (CanvasWidth, CanvasHeight, CanvasRootFolder) VALUES (320.0, 200.0, 1)"), + ) + val container = + syntheticClipContainer( + listOf( + "CHNKSQLi" to databaseBytes, + "CHNKFoot" to byteArrayOf(), + ), + ) + val art = ClipReader.read(container) + assertEquals(320, art.widthPx) + assertEquals(200, art.heightPx) + assertTrue(art.layers.isEmpty()) + assertTrue(art.groups.isEmpty()) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/AlwaysSerializedFieldsTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/AlwaysSerializedFieldsTest.kt new file mode 100644 index 0000000..4839668 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/AlwaysSerializedFieldsTest.kt @@ -0,0 +1,61 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.model.gen.ACLayerEntry +import org.umamo.format.cmo3.model.gen.ACParameterControllableSource +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.serialize.annotations.DontSerializeIfDefault +import kotlin.reflect.KClass +import kotlin.reflect.full.declaredMemberProperties +import kotlin.reflect.full.findAnnotation +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Guards the four generated fields that must ALWAYS serialize. + * + * `@DontSerializeIfDefault` means "the corpus does not always carry this field", which is a fact + * about the SAMPLES. For these four the official editor's custom deserializers dereference the + * field unconditionally and NPE at load when it is absent - the corpus merely includes older-era + * samples that predate them. Marking any of these would emit a file Cubism cannot open, and the + * failure is a load-time NPE in the editor rather than anything a round-trip gate here would see. + * + * The rule that produces them lives in ModelGenerator.alwaysSerializedFields so a regeneration + * reproduces it; this test is the backstop that catches the annotation coming back by ANY route - + * a regeneration against a changed generator, a merge, or a hand-edit of the generated file. + */ +class AlwaysSerializedFieldsTest { + /** The generated properties the editor reads unconditionally, as (owner, property name). */ + private val alwaysSerialized: List, String>> = + listOf( + ACLayerEntry::class to "isTransparencyShapesLayer", + ACParameterControllableSource::class to "internalColor_direct_argb", + CPartSource::class to "useOffscreen", + CPartSource::class to "invertClippingMask", + ) + + @Test + fun theEditorsMandatoryFieldsAreNeverConditionallySerialized() { + val violations = ArrayList() + for ((owner, propertyName) in alwaysSerialized) { + val property = + owner.declaredMemberProperties.firstOrNull { candidate -> candidate.name == propertyName } + if (property == null) { + violations.add("${owner.simpleName}.$propertyName no longer exists") + continue + } + if (property.findAnnotation() != null) { + violations.add( + "${owner.simpleName}.$propertyName carries @DontSerializeIfDefault - the official editor " + + "NPEs when the field is absent (docs/format/CMO3.md, Created-Entity Conventions)", + ) + } + } + // The class-level annotation would suppress every property just as effectively. + for (owner in alwaysSerialized.map { (ownerClass, _) -> ownerClass }.distinct()) { + if (owner.findAnnotation() != null) { + violations.add("${owner.simpleName} carries a CLASS-level @DontSerializeIfDefault") + } + } + assertTrue(violations.isEmpty(), "mandatory fields became conditional:\n" + violations.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ArchivePngTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ArchivePngTest.kt new file mode 100644 index 0000000..8c86ae6 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ArchivePngTest.kt @@ -0,0 +1,108 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.type.FileRef +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the retained-archive PNG primitives a page mint/delete leans on: an added entry round-trips + * by name with `main_xml` still last and the corpus obfuscation convention, the path allocator + * continues past the retained maximum, and a removal leaves every other entry served. Skips + * without the sample. + */ +class Cmo3ArchivePngTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun anAddedPngRoundTripsAndKeepsMainXmlLast() { + val file = + sample ?: run { + println("cmo3.sample not present; skipping archive png test") + return + } + val model = Cmo3.read(file) + val donorPng = assertNotNull(model.extractLayerPng(model.imageResources().first())) + val mintedPath = model.nextImageFileBufPath() + // CMO3: CImageResource fields width, height, type, imageFileBuf, imageFileBuf_size. + val resource = + CImageResource().apply { + width = 16 + height = 16 + type = "INT_ARGB" + imageFileBuf = FileRef().apply { archivePath = mintedPath } + } + + model.addLayerPng(resource, donorPng) + + assertEquals(donorPng.size, resource.imageFileBuf_size, "the size attribute follows the bytes") + val rewritten = Cmo3.write(model) + val rereadArchive = CaffCodec.read(rewritten) + assertContentEquals(donorPng, rereadArchive.byPath(mintedPath)?.content, "the added entry serves by name") + assertEquals( + CaffArchive.TAG_MAIN_XML, + rereadArchive.entries.last().tag, + "main_xml stays the last entry in the table", + ) + val added = assertNotNull(rereadArchive.byPath(mintedPath)) + assertTrue(added.obfuscated, "pixel entries follow the corpus obfuscation convention") + + // A second add under the same path must refuse rather than shadow. + assertFailsWith { model.addLayerPng(resource, donorPng) } + } + + @Test + fun thePathAllocatorContinuesPastTheRetainedMax() { + val file = sample ?: return + val model = Cmo3.read(file) + val highestRetained = + model.archive.entries + .mapNotNull { entry -> + when { + entry.path == "imageFileBuf.png" -> -1 + else -> + entry.path + .removePrefix("imageFileBuf_") + .removeSuffix(".png") + .takeIf { middle -> "imageFileBuf_$middle.png" == entry.path } + ?.toIntOrNull() + } + }.maxOrNull() + + val minted = model.nextImageFileBufPath() + + assertNotNull(highestRetained, "the sample retains imageFileBuf entries") + assertEquals("imageFileBuf_${highestRetained + 1}.png", minted, "the allocator continues past the retained max") + assertNull(model.archive.byPath(minted), "the minted path is unused") + } + + @Test + fun aRemovedEntryLeavesTheOthersServed() { + val file = sample ?: return + val model = Cmo3.read(file) + val resources = model.imageResources() + val removed = resources.first() + val removedPath = assertNotNull(removed.imageFileBuf?.archivePath) + val keptResource = resources[1] + val keptBytes = assertNotNull(model.extractLayerPng(keptResource)) + + model.removeLayerPng(removed) + + assertNull(model.archive.byPath(removedPath), "the entry is gone") + val reread = CaffCodec.read(Cmo3.write(model)) + assertNull(reread.byPath(removedPath), "and stays gone through a write") + assertContentEquals( + keptBytes, + reread.byPath(assertNotNull(keptResource.imageFileBuf?.archivePath))?.content, + "every other entry still serves", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3AuthorTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3AuthorTest.kt new file mode 100644 index 0000000..3dcfdb3 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3AuthorTest.kt @@ -0,0 +1,138 @@ +package org.umamo.format.cmo3 + +import org.jdom.Element +import org.jdom.ProcessingInstruction +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.caff.CaffEntry +import org.umamo.format.cmo3.caff.CompressOption +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CImageCanvas +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Gates the fresh-document prologue authoring (Cmo3Author + Cmo3PiTables) two ways: the corpus + * sweep re-derives every sample's list through our tables and compares VERBATIM (plus + * the set for the 5.4-era files the tables target), and the synthetic case authors a + * minimal never-read CModelSource, wraps it in a CAFF archive, and proves the result reads back + * through Cmo3.read and re-emits its main.xml byte-identically (the prologue replays). + */ +class Cmo3AuthorTest { + @Test + fun tableDerivedPrologueMatchesTheCorpusVerbatim() { + val spec = + System.getProperty("cmo3.probe") + ?: run { + println("cmo3.probe not present; skipping prologue derivation sweep") + return + } + val files = spec.split(',').map { File(it.trim()) }.filter { it.isFile } + val failures = ArrayList() + for (file in files) { + val archive = CaffCodec.read(file.readBytes()) + val mainXml = archive.firstByTag(CaffArchive.TAG_MAIN_XML) ?: continue + val document = XmlCodec.parse(mainXml.content) + val instructions = document.content.filterIsInstance() + val actualImports = + instructions.filter { instruction -> instruction.target == "import" }.map { instruction -> instruction.data } + val tags = HashSet() + collectTags(document.rootElement, tags) + val modelTags = tags - CMO3_STRUCTURAL_TAGS + val unmapped = modelTags.filter { tag -> tag !in CMO3_TAG_TO_FQCN } + if (unmapped.isNotEmpty()) { + failures.add("${file.name}: tags missing from CMO3_TAG_TO_FQCN: $unmapped") + continue + } + val derivedImports = modelTags.map { tag -> CMO3_TAG_TO_FQCN.getValue(tag) }.sorted() + if (derivedImports != actualImports) { + val missing = actualImports.toSet() - derivedImports.toSet() + val extra = derivedImports.toSet() - actualImports.toSet() + failures.add("${file.name}: import derivation differs (missing=$missing extra=$extra)") + } + // The version tables target the 5.4 era only; compare as a set (the editor's own PI + // order is HashMap iteration and carries no meaning). + val fileFormatVersion = document.rootElement.getAttributeValue("fileFormatVersion") + if (fileFormatVersion == Cmo3Author.FRESH_FILE_FORMAT_VERSION) { + val actualVersions = + instructions + .filter { instruction -> instruction.target == "version" } + .map { instruction -> instruction.data } + .toSet() + val derivedVersions = HashSet() + CMO3_VERSIONS_ALWAYS_5_4.forEach { (piName, number) -> derivedVersions.add("$piName:$number") } + for (tag in modelTags) { + CMO3_VERSIONS_BY_TAG_5_4[tag]?.let { (piName, number) -> derivedVersions.add("$piName:$number") } + } + if (derivedVersions != actualVersions) { + failures.add( + "${file.name}: version derivation differs " + + "(missing=${actualVersions - derivedVersions} extra=${derivedVersions - actualVersions})", + ) + } + } + } + assertTrue(files.isNotEmpty(), "cmo3.probe matched no files") + assertTrue(failures.isEmpty(), "prologue derivation drift:\n" + failures.joinToString("\n")) + } + + @Test + fun freshDocumentReadsBackAndReEmitsByteIdentically() { + val root = + CModelSource().apply { + name = "Untitled Model" + canvas = + CImageCanvas().apply { + pixelWidth = 1000 + pixelHeight = 2000 + } + } + val mainXml = Cmo3Author.writeFreshMainXml(root) + + // The authored prologue is present and well-formed. + val document = XmlCodec.parse(mainXml) + assertEquals( + Cmo3Author.FRESH_FILE_FORMAT_VERSION, + document.rootElement.getAttributeValue("fileFormatVersion"), + "fileFormatVersion attribute", + ) + val instructions = document.content.filterIsInstance() + val imports = instructions.filter { instruction -> instruction.target == "import" }.map { instruction -> instruction.data } + assertTrue(imports.isNotEmpty(), "import PIs authored") + assertEquals(imports.sorted(), imports, "import PIs sorted") + assertTrue("com.live2d.graphics.CImageCanvas" in imports, "canvas class imported") + val versions = instructions.filter { instruction -> instruction.target == "version" }.map { instruction -> instruction.data } + assertTrue("SerializeFormatVersion:2" in versions, "SerializeFormatVersion authored") + assertTrue("CModelSource:16" in versions, "CModelSource version authored") + + // Wrapped in a CAFF archive, the fresh document round-trips through the normal codec and + // re-emits its main.xml byte-for-byte (the read graph replays the authored prologue). + val archive = + CaffArchive( + obfuscateKey = 0x49C74776.toInt(), + entries = listOf(CaffEntry("main.xml", CaffArchive.TAG_MAIN_XML, mainXml, CompressOption.FAST, obfuscated = true)), + ) + val model = Cmo3.read(CaffCodec.write(archive)) + val readRoot = model.root as? CModelSource ?: error("fresh root did not read back as CModelSource") + assertEquals("Untitled Model", readRoot.name, "name survives the round trip") + val reEmitted = CaffCodec.read(Cmo3.write(model)).firstByTag(CaffArchive.TAG_MAIN_XML) ?: error("no main_xml after write") + assertContentEquals(mainXml, reEmitted.content, "re-emitted main.xml is byte-identical") + } + + /** + * Collects every element name in the subtree into [into]. + * + * @param Element element The subtree root. + * @param HashSet into The tag collector. + */ + private fun collectTags(element: Element, into: HashSet) { + into.add(element.name) + for (child in element.children) { + collectTags(child as Element, into) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3FacadeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3FacadeTest.kt new file mode 100644 index 0000000..b704a58 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3FacadeTest.kt @@ -0,0 +1,64 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * End-to-end facade test: read a real .cmo3 into a typed model, inspect/replace layer images, and + * write it back losslessly. Self-contained (no editor jar). Skips without the sample. + */ +class Cmo3FacadeTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + private val pngMagic = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte()) + + private fun ByteArray.isPng() = size >= 4 && pngMagic.indices.all { this[it] == pngMagic[it] } + + @Test + fun readsModelExposesLayersAndReemitsMainXmlByteIdentical() { + val file = + sample ?: run { + println("cmo3.sample not present; skipping facade test") + return + } + val model = Cmo3.read(file) + + // Typed root + layer resources. + assertNotNull(model.root, "model root") + assertEquals("CModelSource", model.root!!::class.simpleName) + val resources = model.imageResources() + assertEquals(180, resources.size, "layer image resources") + for (resource in resources) { + val png = model.extractLayerPng(resource) + assertNotNull(png, "layer png for ${resource.imageFileBuf?.archivePath}") + assertTrue(png.isPng(), "valid PNG") + assertEquals(png.size, resource.imageFileBuf_size, "size attribute matches bytes") + } + + // Write back: the model's main.xml must round-trip byte-identical (re-read via our own codec). + val originalMainXml = CaffCodec.read(file.readBytes()).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + val rewritten = Cmo3.write(model) + val rewrittenMainXml = CaffCodec.read(rewritten).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + assertContentEquals(originalMainXml, rewrittenMainXml, "main.xml round-trips byte-identical via facade") + } + + @Test + fun replaceLayerPngPersists() { + val file = sample ?: return + val model = Cmo3.read(file) + val resources = model.imageResources() + val target = resources.first() + val donorPng = model.extractLayerPng(resources[1])!! // reuse another layer's PNG as the new pixels + + model.replaceLayerPng(target, donorPng) + val reread = Cmo3.read(Cmo3.write(model)) + val updated = reread.imageResources().first() + assertContentEquals(donorPng, reread.extractLayerPng(updated), "replaced PNG persisted") + assertEquals(donorPng.size, updated.imageFileBuf_size, "size attribute updated") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3PrologueProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3PrologueProbeTest.kt new file mode 100644 index 0000000..8ed2938 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3PrologueProbeTest.kt @@ -0,0 +1,164 @@ +package org.umamo.format.cmo3 + +import org.jdom.Element +import org.jdom.ProcessingInstruction +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Pins the main.xml prologue and CAFF-table invariants the fresh-graph writer builds against, + * corpus-wide (see docs/format/CMO3.md §2 invariants and §3 Document Shape): + * + * - the main_xml entry is the LAST entry in the file table, and every entry is obfuscated; + * - all processing instructions precede the root element, versions before imports, and no + * other PI target exists; + * - the root element carries exactly one attribute, fileFormatVersion; + * - no element tag anywhere is a fully-qualified name (no '.' or '$'); + * - the import PI set maps 1:1 onto the document's distinct non-primitive element tags (the + * FQCN's segment after the last '$' or '.' is the tag), and the import list is sorted; + * - SerializeFormatVersion:2 is present in every file's version PIs. + */ +class Cmo3PrologueProbeTest { + /** Tags owned by the serializer itself rather than a model class - excluded from the import mapping. */ + private val structuralTags = + setOf( + "root", + "main", + "shared", + "entry", + "null", + "file", + "i", + "f", + "d", + "l", + "short", + "byte", + "char", + "b", + "s", + "array_list", + "carray_list", + "hash_map", + "linked_map", + "linked_set", + "float-array", + "int-array", + "long-array", + "short-array", + "double-array", + "byte-array", + "char-array", + "bool-array", + ) + + @Test + fun prologueInvariantsHoldAcrossTheCorpus() { + val spec = + System.getProperty("cmo3.probe") + ?: run { + println("cmo3.probe not present; skipping prologue probe") + return + } + val files = spec.split(',').map { File(it.trim()) }.filter { it.isFile } + val failures = ArrayList() + for (file in files) { + probeFile(file, failures) + } + assertTrue(files.isNotEmpty(), "cmo3.probe matched no files") + assertTrue(failures.isEmpty(), "prologue invariants violated:\n" + failures.joinToString("\n")) + } + + /** + * Checks every invariant on one corpus file, appending human-readable violations. + * + * @param File file The corpus .cmo3 file. + * @param ArrayList failures The shared violation collector. + */ + private fun probeFile(file: File, failures: ArrayList) { + val archive = CaffCodec.read(file.readBytes()) + if (archive.entries.last().tag != CaffArchive.TAG_MAIN_XML) { + failures.add("${file.name}: main_xml is not the last CAFF entry") + } + if (archive.entries.count { entry -> entry.tag == CaffArchive.TAG_MAIN_XML } != 1) { + failures.add("${file.name}: expected exactly one main_xml entry") + } + archive.entries.filterNot { entry -> entry.obfuscated }.forEach { entry -> + failures.add("${file.name}: entry ${entry.path} is not obfuscated") + } + val mainXml = archive.firstByTag(CaffArchive.TAG_MAIN_XML) ?: return + val document = XmlCodec.parse(mainXml.content) + + // Prologue: version PIs, then import PIs, all before ; no other PI target. + val instructions = document.content.filterIsInstance() + val targets = instructions.map { instruction -> instruction.target } + targets.filterNot { target -> target == "version" || target == "import" }.forEach { target -> + failures.add("${file.name}: unexpected PI target ") + } + val lastVersionIndex = targets.lastIndexOf("version") + val firstImportIndex = targets.indexOf("import") + if (firstImportIndex >= 0 && lastVersionIndex > firstImportIndex) { + failures.add("${file.name}: a version PI follows an import PI") + } + val rootIndex = document.content.indexOf(document.rootElement) + if (instructions.isNotEmpty() && document.content.indexOf(instructions.last()) > rootIndex) { + failures.add("${file.name}: a PI appears after ") + } + + // Root attributes: exactly fileFormatVersion. + val attributeNames = document.rootElement.attributes.map { attribute -> (attribute as org.jdom.Attribute).name } + if (attributeNames != listOf("fileFormatVersion")) { + failures.add("${file.name}: root attributes are $attributeNames") + } + + // Version PIs parse as Name:Int and include SerializeFormatVersion:2. + val versions = + instructions.filter { instruction -> instruction.target == "version" }.map { instruction -> instruction.data } + versions.filterNot { data -> data.substringAfterLast(':').toIntOrNull() != null }.forEach { data -> + failures.add("${file.name}: unparseable version PI ") + } + if ("SerializeFormatVersion:2" !in versions) { + failures.add("${file.name}: SerializeFormatVersion:2 missing from version PIs") + } + + // Element tags: never fully qualified; import PIs map 1:1 onto the non-structural tag set. + val tags = HashSet() + collectTags(document.rootElement, tags) + tags.filter { tag -> '.' in tag || '$' in tag }.forEach { tag -> + failures.add("${file.name}: fully-qualified element tag <$tag>") + } + val modelTags = tags - structuralTags + val imports = + instructions.filter { instruction -> instruction.target == "import" }.map { instruction -> instruction.data } + if (imports != imports.sorted()) { + failures.add("${file.name}: import PIs are not sorted") + } + val importedTags = imports.map { fqcn -> fqcn.substringAfterLast('$').substringAfterLast('.') }.toSet() + if (importedTags.size != imports.size) { + failures.add("${file.name}: two import FQCNs map to one tag") + } + (modelTags - importedTags).forEach { tag -> + failures.add("${file.name}: tag <$tag> has no import PI") + } + (importedTags - modelTags).forEach { tag -> + failures.add("${file.name}: import for <$tag> matches no element tag") + } + } + + /** + * Collects every element name in the subtree into [into]. + * + * @param Element element The subtree root. + * @param HashSet into The tag collector. + */ + private fun collectTags(element: Element, into: HashSet) { + into.add(element.name) + for (child in element.children) { + collectTags(child as Element, into) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ResaveDumpTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ResaveDumpTest.kt new file mode 100644 index 0000000..a77b616 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ResaveDumpTest.kt @@ -0,0 +1,29 @@ +package org.umamo.format.cmo3 + +import java.io.File +import kotlin.test.Test + +/** + * Debugging aid: re-saves the -Dcmo3.resave files through Cmo3.read -> Cmo3.write and dumps the + * results to build/resave-.cmo3 for byte-level comparison against the originals and for + * manual official-editor acceptance runs. The property is explicit-only (no corpus default) so a + * plain test run does not dump the whole corpus into build/. + */ +class Cmo3ResaveDumpTest { + @Test + fun dumpResaves() { + val spec = + System.getProperty("cmo3.resave") + ?: run { + println("cmo3.resave not present; skipping resave dump") + return + } + for (file in spec.split(',').map { File(it.trim()) }.filter { it.isFile }) { + val resaved = Cmo3.write(Cmo3.read(file.readBytes())) + val target = File("build/resave-${file.name}") + target.parentFile.mkdirs() + target.writeBytes(resaved) + println("wrote ${target.absolutePath} (${resaved.size} bytes, original ${file.length()})") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ShapeGateTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ShapeGateTest.kt new file mode 100644 index 0000000..e0b72f5 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3ShapeGateTest.kt @@ -0,0 +1,96 @@ +package org.umamo.format.cmo3 + +import org.jdom.Element +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Element-SHAPE gate: every class element an Umamo-written CMO3 emits must carry a field set the + * official editor also writes somewhere in the corpus. + * + * The editor's custom deserializers dereference fields unconditionally, so a shape it has never + * produced is a shape it may not survive - and the failure is a load-time NPE, not a validation + * message. Two rounds of official-editor rejection were exactly this: a CPartForm carrying + * drawOrder + opacity but no multiply/screen colors (the corpus only ever has all five, or the + * pre-5.3 drawOrder-only shape), and forms missing the mandatory notes string. Presence audits + * per field miss these because each individual field IS legal - it is the COMBINATION that is + * novel. + * + * Corpus files whose name contains "ExportTest" are Umamo-written (promoted conversion outputs); + * every other corpus file is editor-written and defines the legal shape vocabulary. + */ +class Cmo3ShapeGateTest { + /** Serializer-owned tags whose children are elements rather than named fields. */ + private val collectionTags: Set = CMO3_STRUCTURAL_TAGS + + @Test + fun writtenElementShapesAllOccurInAnEditorWrittenFile() { + val probe = + System.getProperty("cmo3.probe") ?: run { + println("cmo3.probe not present; skipping shape gate") + return + } + val files = probe.split(',').map { path -> File(path.trim()) }.filter { file -> file.isFile } + val (ours, official) = files.partition { file -> file.name.contains("ExportTest") } + if (ours.isEmpty() || official.isEmpty()) { + println("shape gate needs both Umamo-written and editor-written corpus files; skipping") + return + } + val knownShapes = HashMap>>() + for (file in official) { + collectShapes(rootOf(file)) { tag, shape -> + knownShapes.getOrPut(tag) { HashSet() }.add(shape) + } + } + val violations = ArrayList() + for (file in ours) { + val seen = HashSet>>() + collectShapes(rootOf(file)) { tag, shape -> + // A tag absent from every editor-written file is not a shape question (the coverage + // and prologue gates own unknown tags); only novel shapes of KNOWN tags are reported. + val known = knownShapes[tag] ?: return@collectShapes + if (shape !in known && seen.add(tag to shape)) { + violations.add( + "${file.name}: <$tag> field set $shape occurs in no editor-written corpus file " + + "(closest known: ${known.minByOrNull { candidate -> candidate.size }})", + ) + } + } + } + assertTrue(violations.isEmpty(), "novel element shapes:\n" + violations.joinToString("\n")) + } + + /** + * Parses a CMO3's decompressed main.xml and returns its root element. + * + * @param File file The corpus file. + * @return Element The parsed root. + */ + private fun rootOf(file: File): Element { + val mainXml = + CaffCodec.read(file.readBytes()).firstByTag(CaffArchive.TAG_MAIN_XML) + ?: error("${file.name}: no main.xml entry") + return XmlCodec.parse(mainXml.content).rootElement + } + + /** + * Walks [element] depth-first, reporting each class element's direct-child field-name sequence. + * + * @param Element element The subtree root. + * @param Function report Receives (tag, field-name sequence) per class element. + */ + private fun collectShapes(element: Element, report: (String, List) -> Unit) { + @Suppress("UNCHECKED_CAST") + val children = element.children as List + if (element.name !in collectionTags) { + report(element.name, children.map { child -> child.getAttributeValue("xs.n") ?: child.name }) + } + for (child in children) { + collectShapes(child, report) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3TargetVersionWriteTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3TargetVersionWriteTest.kt new file mode 100644 index 0000000..071986b --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/Cmo3TargetVersionWriteTest.kt @@ -0,0 +1,71 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.serialize.ChildSlot +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the targetVersionNo write path: the facade persists the field through a re-emit, including on + * a document whose source XML carried no such element (where a bare field assignment is dropped by + * the slot-replaying writer), and a same-value set stays byte-identical. Skips without the sample. + */ +class Cmo3TargetVersionWriteTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun sameValueSetKeepsMainXmlByteIdentical() { + val file = + sample ?: run { + println("cmo3.sample not present; skipping targetVersionNo write test") + return + } + val model = Cmo3.read(file) + val existing = + model.targetVersionNo ?: run { + println("sample carries no targetVersionNo; skipping byte-identity pin") + return + } + model.setTargetVersionNo(existing) + val originalMainXml = CaffCodec.read(file.readBytes()).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + val rewrittenMainXml = CaffCodec.read(Cmo3.write(model)).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + assertContentEquals(originalMainXml, rewrittenMainXml, "same-value set keeps main.xml byte-identical") + } + + @Test + fun changedValuePersistsThroughReemit() { + val file = sample ?: return + val model = Cmo3.read(file) + model.setTargetVersionNo(Cmo3TargetVersion.V42.versionNo) + assertEquals(Cmo3TargetVersion.V42.versionNo, Cmo3.read(Cmo3.write(model)).targetVersionNo) + } + + @Test + fun missingElementIsRecreatedWhereTheEditorWritesIt() { + val file = sample ?: return + val model = Cmo3.read(file) + val modelSource = model.root as CModelSource + // Simulate a source document that never carried the element: null the field and drop its + // recorded slot, so the writer has nothing to replay. + modelSource.targetVersionNo = null + val slots = model.graph.childOrder[modelSource]!!.getValue("CModelSource") + slots.removeAll { slot -> slot is ChildSlot.KnownField && slot.propertyName == "targetVersionNo" } + // A bare field assignment is dropped - the failure mode the facade exists for. + modelSource.targetVersionNo = Cmo3TargetVersion.V42.versionNo + assertNull(Cmo3.read(Cmo3.write(model)).targetVersionNo, "a bare assignment has no slot to replay") + // The facade records the slot too, so the value survives, ordered before the modeler version. + model.setTargetVersionNo(Cmo3TargetVersion.V42.versionNo) + val rewritten = Cmo3.write(model) + assertEquals(Cmo3TargetVersion.V42.versionNo, Cmo3.read(rewritten).targetVersionNo) + val mainXml = CaffCodec.read(rewritten).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content.decodeToString() + val targetIndex = mainXml.indexOf("xs.n=\"targetVersionNo\"") + val modelerIndex = mainXml.indexOf("xs.n=\"latestVersionOfLastModelerNo\"") + assertTrue(targetIndex in 0 until modelerIndex, "recreated element sits before latestVersionOfLastModelerNo") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/GEditableMeshProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/GEditableMeshProbeTest.kt new file mode 100644 index 0000000..3fca22a --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/GEditableMeshProbeTest.kt @@ -0,0 +1,97 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.GEditableMesh2 +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CEditableMeshExtension +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Pins the corpus encodings of GEditableMesh2's untyped fields, which the CMO3 export's geometry + * sync and the topology rebuild both depend on: point is a float-array mirroring the art mesh's + * positions (a SEPARATE array object, never a shared ref to CArtMeshSource.positions), pointUid is + * an int-array of one uid per vertex, and edge is a SHORT-array of vertex-index pairs into the + * point array (vertex ordinals, not uids). Printed distributions feed docs/format/CMO3.md; the + * assertions are the invariants the export writes against. + */ +class GEditableMeshProbeTest { + @Test + fun editableMeshEncodingsHoldAcrossTheCorpus() { + val spec = + System.getProperty("cmo3.probe") + ?: run { + println("cmo3.probe not present; skipping editable-mesh probe") + return + } + val files = spec.split(',').map { File(it.trim()) }.filter { it.isFile } + val failures = ArrayList() + var meshCount = 0 + var sharedPointArrayCount = 0 + var edgeBearingCount = 0 + var delaunayCount = 0 + for (file in files) { + val root = Cmo3.read(file.readBytes()).root as? CModelSource ?: continue + val drawables = + (((root.drawableSourceSet as? CDrawableSourceSet)?._sources as? Iterable<*>) ?: emptyList()) + .filterIsInstance() + for (drawable in drawables) { + val extensions = (drawable._extensions as? Iterable<*>) ?: emptyList() + val editableMesh = + extensions.filterIsInstance().firstOrNull()?.editableMesh as? GEditableMesh2 + ?: continue + meshCount++ + val positions = drawable.positions as? FloatArray + val point = editableMesh.point + val pointUid = editableMesh.pointUid + val edge = editableMesh.edge + if (point != null && point !is FloatArray) { + failures.add("${file.name}: point is ${point::class.simpleName}") + continue + } + if (pointUid != null && pointUid !is IntArray) { + failures.add("${file.name}: pointUid is ${pointUid::class.simpleName}") + continue + } + if (edge != null && edge !is ShortArray) { + failures.add("${file.name}: edge is ${edge::class.simpleName}") + continue + } + val pointArray: FloatArray? = point + val uidArray: IntArray? = pointUid + val edgeArray: ShortArray? = edge + if (pointArray != null && positions != null) { + if (pointArray === positions) { + sharedPointArrayCount++ + } + if (pointArray.size != positions.size) { + failures.add("${file.name}: point size ${pointArray.size} != positions size ${positions.size}") + } + if (uidArray != null && uidArray.size * 2 != pointArray.size) { + failures.add("${file.name}: pointUid count ${uidArray.size} != vertex count ${pointArray.size / 2}") + } + } + if (edgeArray != null && edgeArray.isNotEmpty()) { + edgeBearingCount++ + if (edgeArray.size % 2 != 0) { + failures.add("${file.name}: edge array size ${edgeArray.size} is odd") + } + val vertexCount = (pointArray?.size ?: 0) / 2 + if (vertexCount > 0 && edgeArray.any { endpoint -> endpoint < 0 || endpoint >= vertexCount }) { + failures.add("${file.name}: edge endpoint out of vertex range") + } + } + if (editableMesh.useDelaunayTriangulation) { + delaunayCount++ + } + } + } + println( + "editable meshes: $meshCount, point===positions shares: $sharedPointArrayCount, " + + "edge-bearing: $edgeBearingCount, delaunay: $delaunayCount", + ) + assertTrue(failures.isEmpty(), "editable-mesh probe failed:\n" + failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/OffscreenProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/OffscreenProbeTest.kt new file mode 100644 index 0000000..7d8e7c5 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/OffscreenProbeTest.kt @@ -0,0 +1,171 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CFloatColor +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CParameterSource +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CPartForm +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CPartSourceSet +import org.umamo.format.cmo3.model.gen.KeyOnParameter +import org.umamo.format.cmo3.model.gen.KeyformBindingSource +import org.umamo.format.cmo3.model.gen.KeyformGridAccessKey +import org.umamo.format.cmo3.model.gen.KeyformGridSource +import org.umamo.format.cmo3.model.gen.KeyformOnGrid +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CColor +import java.io.File +import kotlin.test.Test + +/** + * Print-only probe for the CMO3 offscreen-drawing representation (Cubism 5.3 part feature): which + * parts carry useOffscreen, their color/alpha composition enums, clipping lists, and keyformed + * opacity/color payloads (CPartForm), plus the raw main.xml spellings. Feeds the offscreen support + * scratchpad (docs/plan/offscreen-support.md); pins nothing. Skips gracefully without samples. + */ +class OffscreenProbeTest { + private fun samples(): List = + System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { it.isFile } ?: emptyList() + + /** + * Flattens a CMO3 collection field to a plain list (mirrors Cmo3Import.elementsOf). + * + * @param Any? collection The raw collection field, held as Any?. + * @return List The contained elements. + */ + private fun elementsOf(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun uuidOf(value: Any?): String? = (value as? Guid)?.uuid?.takeIf { it.isNotEmpty() } + + private fun idOf(value: Any?): String? = (value as? Id)?.idstr + + private fun colorHex(value: Any?): String = + when (value) { + is CColor -> "#%08X".format(value.argb) + is CFloatColor -> "rgba(${value.red}, ${value.green}, ${value.blue}, ${value.alpha})" + null -> "null" + else -> value.toString() + } + + @Test + fun probeOffscreenParts() { + val files = samples() + if (files.isEmpty()) { + println("cmo3.probe not present; skipping offscreen probe") + return + } + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + val partSources = + elementsOf((root.partSourceSet as? CPartSourceSet)?._sources).filterIsInstance() + val drawableSources = + elementsOf((root.drawableSourceSet as? CDrawableSourceSet)?._sources) + val parameterSources = + elementsOf((root.parameterSourceSet as? CParameterSourceSet)?._sources).filterIsInstance() + val parameterNameByUuid = + parameterSources.associateBy(keySelector = { uuidOf(it.guid) }, valueTransform = { idOf(it.id) ?: it.name ?: "?" }) + // Both parts and drawables are legal clip targets; index them all by guid for resolution. + val nameByUuid = HashMap() + for (part in partSources) { + nameByUuid[uuidOf(part.guid)] = "part:" + (part.localName ?: idOf(part.id) ?: "?") + } + for (drawableSource in drawableSources) { + val mesh = drawableSource as? CArtMeshSource ?: continue + nameByUuid[uuidOf(mesh.guid)] = "mesh:" + (mesh.localName ?: idOf(mesh.id) ?: "?") + } + + val offscreenParts = partSources.filter { it.useOffscreen } + println("=== ${file.name}: parts=${partSources.size} offscreen=${offscreenParts.size} ===") + + for (part in offscreenParts) { + println(" part '${part.localName}' id=${idOf(part.id)}") + println(" enableDrawOrderGroup=${part.enableDrawOrderGroup} isSketch=${part.isSketch}") + println(" colorComposition=${part.colorComposition} alphaComposition=${part.alphaComposition}") + val clipNames = elementsOf(part.clipGuidList).map { nameByUuid[uuidOf(it)] ?: "unresolved" } + println(" invertClippingMask=${part.invertClippingMask} clip=$clipNames") + // The part's keyform grid: axes + each CPartForm cell's payload (the keyformed channels). + val grid = part.keyformGridSource as? KeyformGridSource + val bindings = elementsOf(grid?.keyformBindings).filterIsInstance() + val axisSummary = + bindings.joinToString { binding -> + val keys = elementsOf(binding.keys).map { (it as? Number)?.toFloat() } + "${parameterNameByUuid[uuidOf(binding.parameterGuid)]}=$keys" + } + println(" axes: [$axisSummary]") + val axisOfBinding = bindings.withIndex().associate { (index, binding) -> binding to index } + val formByUuid = elementsOf(part.keyforms).associateBy { form -> uuidOf((form as? CPartForm)?.guid) } + for (cell in elementsOf(grid?.keyformsOnGrid).filterIsInstance()) { + val form = formByUuid[uuidOf(cell.keyformGuid)] as? CPartForm ?: continue + val coordinate = IntArray(bindings.size) + val keyList = (cell.accessKey as? KeyformGridAccessKey)?._keyOnParameterList + for (keyOnParameter in elementsOf(keyList).filterIsInstance()) { + val axisIndex = axisOfBinding[keyOnParameter.binding] ?: continue + coordinate[axisIndex] = keyOnParameter.keyIndex + } + println( + " cell ${coordinate.toList()}: drawOrder=${form.drawOrder} opacity=${form.opacity}" + + " multiply=${colorHex(form.multiplyColor)} screen=${colorHex(form.screenColor)}", + ) + } + } + + // Enum tallies: every composition value observed, split by owner class, plus the same fields + // on NON-offscreen parts (do the fields ever appear when the checkbox is off?). + val partColor = partSources.groupingBy { "${it.useOffscreen}/${it.colorComposition}" }.eachCount() + val partAlpha = partSources.groupingBy { "${it.useOffscreen}/${it.alphaComposition}" }.eachCount() + println(" part colorComposition (useOffscreen/value -> count): $partColor") + println(" part alphaComposition (useOffscreen/value -> count): $partAlpha") + val meshes = drawableSources.filterIsInstance() + println(" mesh colorComposition values: ${meshes.groupingBy { it.colorComposition?.toString() }.eachCount()}") + println(" mesh alphaComposition values: ${meshes.groupingBy { it.alphaComposition?.toString() }.eachCount()}") + // Per-mesh detail wherever a drawable authors a non-default blend or culling - the + // drawable-level extended-blend / culling extraction evidence. + for (mesh in meshes) { + val colorValue = mesh.colorComposition?.toString() + val alphaValue = mesh.alphaComposition?.toString() + val nonDefault = + mesh.culling || (colorValue != null && colorValue != "NORMAL") || (alphaValue != null && alphaValue != "OVER") + if (nonDefault) { + println( + " mesh '${mesh.localName}' id=${idOf(mesh.id)} color=$colorValue alpha=$alphaValue" + + " culling=${mesh.culling} clip=${elementsOf(mesh.clipGuidList).map { nameByUuid[uuidOf(it)] ?: "unresolved" }}", + ) + } + } + + // Raw main.xml spellings for the offscreen-related fields (exact serialization shape). + val mainXml = CaffCodec.read(file.readBytes()).firstByTag(CaffArchive.TAG_MAIN_XML)?.content ?: continue + val keywords = + listOf( + "useOffscreen", + "clipGuidList", + "invertClippingMask", + "colorComposition", + "alphaComposition", + "multiplyColor", + "screenColor", + ) + val seenFragments = LinkedHashSet() + for (line in String(mainXml, Charsets.UTF_8).lineSequence()) { + if (keywords.any { keyword -> keyword in line }) { + seenFragments.add(line.trim()) + if (seenFragments.size >= 24) { + break + } + } + } + seenFragments.forEach { fragment -> println(" xml: $fragment") } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/TargetVersionNoCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/TargetVersionNoCorpusTest.kt new file mode 100644 index 0000000..6741deb --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/TargetVersionNoCorpusTest.kt @@ -0,0 +1,72 @@ +package org.umamo.format.cmo3 + +import org.umamo.format.cmo3.model.custom.CModelSource +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Corpus-gated targetVersionNo decode: known corpus documents must decode to their authored SDK + * target. Skips (with a note) when the probe property is absent, like the other corpus tests. + */ +class TargetVersionNoCorpusTest { + private val probeFiles: List = + System.getProperty("cmo3.probe") + ?.split(",") + ?.map(::File) + ?.filter { it.isFile } + .orEmpty() + + // CMO3: CModelSource field targetVersionNo - the authored target per corpus file. The + // SDK3.3/4.0/4.2/NA files were saved by the current official editor specifically to pin these + // literals; the SDKNA file carries the SDK(N/A)/Latest sentinel, which decodes to + // null (no target version). + private val expectedByFileName: Map = + mapOf( + "EricaTamamo.cmo3" to Cmo3TargetVersion.V40, + "ModelWithOffscreen.cmo3" to Cmo3TargetVersion.V53, + "ModelWithOffscreenSDK3.3.cmo3" to Cmo3TargetVersion.V33, + "ModelWithoutOffscreenSDK3.3.cmo3" to Cmo3TargetVersion.V33, + "ModelWithoutOffscreenSDK4.0.cmo3" to Cmo3TargetVersion.V40, + "ModelWithoutOffscreenSDK4.2.cmo3" to Cmo3TargetVersion.V42, + "ModelWithoutOffscreenSDKNA.cmo3" to null, + "modelA.cmo3" to Cmo3TargetVersion.V53, + "modelB.cmo3" to Cmo3TargetVersion.V50, + "modelD.cmo3" to Cmo3TargetVersion.V30, + ) + + @Test + fun corpusDocumentsDecodeToTheirAuthoredTarget() { + if (probeFiles.isEmpty()) { + println("cmo3.probe not present; skipping targetVersionNo corpus test") + return + } + var pinnedCount = 0 + for (file in probeFiles) { + val modelRoot = Cmo3.read(file).root as? CModelSource + assertNotNull(modelRoot, "${file.name} root is a CModelSource") + // EVERY probe file's value must deserialize as an Int (or be absent) - a VerbatimNode or + // other fallback type would silently coerce to null and land every import on NoTarget, so + // the type is asserted before the tolerant cast. The pinned subset must additionally + // decode to its known authored target. + val rawField = modelRoot.targetVersionNo + assertTrue( + rawField == null || rawField is Int, + "${file.name} targetVersionNo is an Int or absent, got ${rawField?.let { value -> value::class.simpleName }}", + ) + val rawVersionNo = rawField + val decoded = Cmo3TargetVersion.fromVersionNo(rawVersionNo) + if (expectedByFileName.containsKey(file.name)) { + assertEquals(expectedByFileName[file.name], decoded, "${file.name} targetVersionNo decode") + pinnedCount++ + } + if (file.name == "ModelWithoutOffscreenSDKNA.cmo3") { + // The freshly saved SDK(N/A)/Latest selection pins the sentinel value itself. + assertEquals(Cmo3TargetVersion.LATEST_VERSION_NO, rawVersionNo, "${file.name} raw sentinel") + } + } + assertTrue(pinnedCount > 0, "probe list contained none of the pinned corpus files") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/caff/CaffSampleTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/caff/CaffSampleTest.kt new file mode 100644 index 0000000..7e9adcd --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/caff/CaffSampleTest.kt @@ -0,0 +1,59 @@ +package org.umamo.format.cmo3.caff + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Validates the CAFF codec against the real sample, end to end: parse, inspect, and round-trip + * through our own writer/reader. Self-contained (no editor jar). Skips when the sample is absent. + */ +class CaffSampleTest { + private val sample: File? = + System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private val pngMagic = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte()) + + private fun ByteArray.startsWith(prefix: ByteArray): Boolean = + size >= prefix.size && prefix.indices.all { this[it] == prefix[it] } + + @Test + fun readsSampleAndRoundTrips() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping CAFF sample test") + return + } + val ours = CaffCodec.read(file.readBytes()) + assertEquals(926, ours.entries.size, "entry count") + assertEquals(0xD7FC71B1.toInt(), ours.obfuscateKey, "obfuscate key") + assertEquals("----", ours.formatIdentifier, "format identifier") + assertTrue(!ours.preview.present, "sample has NO_PREVIEW") + + val mainXml = ours.firstByTag(CaffArchive.TAG_MAIN_XML) ?: error("no main_xml entry") + assertTrue(mainXml.content.decodeToString().startsWith("() + val engine = cubismEngine { tag, _ -> unmodeled += tag } + val reemitted = XmlCodec.write(engine.writeModel(engine.readModel(XmlCodec.parse(mainXml)))) + + assertEquals(sortedSetOf(), unmodeled, "${file.name} has unmodeled tags") + + val limit = minOf(mainXml.size, reemitted.size) + val diff = (0 until limit).firstOrNull { mainXml[it] != reemitted[it] } ?: -1 + val identical = diff < 0 && mainXml.size == reemitted.size + assertTrue( + identical, + buildString { + append("${file.name} not byte-identical: sizes expected=${mainXml.size} actual=${reemitted.size}") + val at = if (diff < 0) limit else diff + append(", first diff @ $at\n") + val start = maxOf(0, at - 80) + + fun ByteArray.window() = decodeToString(start, minOf(size, at + 90)).replace("\r", "\\r").replace("\n", "\\n") + append(" expected: …${mainXml.window()}\n") + append(" actual: …${reemitted.window()}") + }, + ) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CTypeRoundTripTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CTypeRoundTripTest.kt new file mode 100644 index 0000000..afaaf9b --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CTypeRoundTripTest.kt @@ -0,0 +1,59 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.serialize.annotations.SerialTag +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.format.cmo3.type.CHashMap +import org.umamo.format.cmo3.xml.XmlCodec +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@SerialTag("Crate") +class Crate { + var items: List = emptyList() + var lookup: Map = emptyMap() +} + +/** + * Pins the on-disk contract of the two CMO3 collection types, corpus-free. + * + * These carry real weight: CArrayList must emit (not ) and CHashMap must + * emit preserving insertion order — SerializeEngine picks both by an `is` check ordered + * subtype-before-supertype, and CMO3 byte-identity depends on the tag and the entry order. Nothing + * else covers this without a corpus sample, so a change to how these types are declared could + * otherwise break round-trip with every gate still green. + */ +class CTypeRoundTripTest { + private fun engine(): SerializeEngine { + val registry = SerializerRegistry() + registry.register(Crate::class) + return SerializeEngine(registry, SerializeDiagnostics.None) + } + + @Test + fun cArrayListAndCHashMapRoundTripWithTagsAndOrder() { + val crate = + Crate().apply { + items = CArrayList(listOf("first", "second", "third")) + // Deliberately NOT alphabetical: proves order is preserved, not re-hashed. + lookup = + CHashMap().apply { + put("zulu", 26) + put("alpha", 1) + put("mike", 13) + } + } + + val engine = engine() + val xml = XmlCodec.write(engine.writeRoot(crate)).decodeToString() + assertTrue(", got: $xml") + assertTrue(", got: $xml") + + val restored = engine.readRoot(XmlCodec.parse(xml.encodeToByteArray())) as Crate + assertEquals(listOf("first", "second", "third"), restored.items, "list contents round-trip") + assertTrue(restored.items is CArrayList<*>, "carray_list must read back as CArrayList, got ${restored.items::class.simpleName}") + assertTrue(restored.lookup is CHashMap<*, *>, "hash_map must read back as CHashMap, got ${restored.lookup::class.simpleName}") + assertEquals(listOf("zulu", "alpha", "mike"), restored.lookup.keys.toList(), "hash_map entry ORDER must survive (CMO3 byte-identity depends on it)") + assertEquals(mapOf("zulu" to 26, "alpha" to 1, "mike" to 13), restored.lookup, "map contents round-trip") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CollectionSerializerTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CollectionSerializerTest.kt new file mode 100644 index 0000000..77e7fd5 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CollectionSerializerTest.kt @@ -0,0 +1,85 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element +import org.umamo.format.cmo3.serialize.annotations.SerialTag +import org.umamo.format.cmo3.xml.XmlCodec +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@SerialTag("Mode") +enum class Mode { ALPHA, BETA } + +@SerialTag("Point2") +class Point2 { + var x: Float = 0f + var y: Float = 0f +} + +@SerialTag("Bag") +class Bag { + var mode: Mode = Mode.ALPHA + var coords: FloatArray = FloatArray(0) + var labels: Map = emptyMap() + var point: Point2? = null +} + +/** A custom (attribute-based) serializer for a value-type. */ +private object Point2Serializer : XmlSerializer { + override fun createElement(name: String?, value: Any, ctx: WriteContext): Element { + val point = value as Point2 + val element = Element("Point2") + element.setFieldName(name) + element.setAttribute("x", point.x.toString()) + element.setAttribute("y", point.y.toString()) + return element + } + + override fun createInstance(element: Element, ctx: ReadContext): Any = + Point2().apply { + x = element.getAttributeValue("x").toFloat() + y = element.getAttributeValue("y").toFloat() + } +} + +/** Exercises enums, typed arrays, maps, and a custom attribute serializer through full XML round-trip. */ +class CollectionSerializerTest { + private fun engine(): SerializeEngine { + val registry = SerializerRegistry() + registry.register(Bag::class) + registry.register(Mode::class) + registry.registerCustom(Point2::class, Point2Serializer) + return SerializeEngine(registry, SerializeDiagnostics.None) + } + + @Test + fun roundTripsEnumArrayMapAndCustom() { + val bag = + Bag().apply { + mode = Mode.BETA + coords = floatArrayOf(1.5f, 2.0f, 3.25f) + labels = linkedMapOf("a" to 1, "b" to 2) + point = + Point2().apply { + x = 4f + y = 5f + } + } + + val engine = engine() + val xml = XmlCodec.write(engine.writeRoot(bag)).decodeToString() + assertTrue("" in xml, "enum stored as v attribute") + assertTrue("1.5 2.0 3.25" in xml, "float-array text") + // String-keyed maps store each value as (no wrapper). + assertTrue("1" in xml, "string-keyed map form") + assertTrue("" in xml, "custom attribute serializer") + + val restored = engine.readRoot(XmlCodec.parse(xml.toByteArray())) as Bag + assertEquals(Mode.BETA, restored.mode) + assertContentEquals(floatArrayOf(1.5f, 2.0f, 3.25f), restored.coords) + assertEquals(mapOf("a" to 1, "b" to 2), restored.labels) + assertEquals(4f, restored.point?.x) + assertEquals(5f, restored.point?.y) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CoverageGateTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CoverageGateTest.kt new file mode 100644 index 0000000..87010d2 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/CoverageGateTest.kt @@ -0,0 +1,31 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Documents and guards model coverage: with the full cubismEngine, exactly these tags remain + * verbatim (any tag without a registered typed serializer). Growing this set is a regression. + */ +class CoverageGateTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private val knownVerbatim = sortedSetOf() // every tag in the sample is now typed + + @Test + fun onlyKnownCustomTagsRemainVerbatim() { + val file = + sample ?: run { + println("cmo3.sample not present; skipping coverage gate") + return + } + val mainXml = CaffCodec.read(file.readBytes()).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + val unmodeled = sortedSetOf() + cubismEngine { tag, _ -> unmodeled += tag }.readModel(XmlCodec.parse(mainXml)) + assertEquals(knownVerbatim, unmodeled, "unmodeled tag set changed") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/FreshSharedObjectWriteTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/FreshSharedObjectWriteTest.kt new file mode 100644 index 0000000..472cf17 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/FreshSharedObjectWriteTest.kt @@ -0,0 +1,86 @@ +package org.umamo.format.cmo3.serialize + +import org.jdom.Element +import org.umamo.format.cmo3.xml.XmlCodec +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins reconcile-mode writing of FRESH shared objects (objects attached after read and referenced + * more than once): the def must hoist into the shared pool after the preserved entries, its id must + * not collide with any preserved id, and a re-read must resolve every reference to one instance. + * Also pins that an unedited graph still re-emits byte-identically (the hoist is a no-op for it). + */ +class FreshSharedObjectWriteTest { + private val engine = SerializeEngine.of(listOf(Node::class, Vec::class, Leaf::class)) + + private fun sourceXml(): ByteArray { + val sharedLeaf = Leaf().apply { id = 7 } + val node = + Node().apply { + label = "src" + sharedChild = sharedLeaf + sharedChildAgain = sharedLeaf // second use -> hoisted into with xs.id "#0" + } + return XmlCodec.write(engine.writeRoot(node)) + } + + @Test + fun uneditedGraphStaysByteIdentical() { + val source = sourceXml() + val reemitted = XmlCodec.write(engine.writeModel(engine.readModel(XmlCodec.parse(source)))) + assertContentEquals(source, reemitted, "unedited graph re-emits byte-identically") + } + + @Test + fun freshSharedObjectHoistsWithoutCollidingWithPreservedIds() { + val graph = engine.readModel(XmlCodec.parse(sourceXml())) + val root = graph.root as Node + + // A fresh object attached after read, referenced twice. + val freshLeaf = Leaf().apply { id = 42 } + root.sharedChild = freshLeaf + root.sharedChildAgain = freshLeaf + + val output = XmlCodec.write(engine.writeModel(graph)) + val document = XmlCodec.parse(output) + + @Suppress("UNCHECKED_CAST") + val defs = document.rootElement.getChild("shared").children as List + assertEquals(2, defs.size, "preserved def + hoisted fresh def") + val preservedDef = defs[0] + val freshDef = defs[1] + assertEquals("#0", preservedDef.getAttributeValue("xs.id"), "preserved def keeps its id") + assertEquals("#1", freshDef.getAttributeValue("xs.id"), "fresh id continues past the preserved maximum") + assertNotEquals( + preservedDef.getAttributeValue("xs.id"), + freshDef.getAttributeValue("xs.id"), + "fresh id never reuses a preserved id", + ) + val preservedIndex = preservedDef.getAttributeValue("xs.idx").toInt() + assertEquals(preservedIndex + 1, freshDef.getAttributeValue("xs.idx").toInt(), "xs.idx continues") + + // Both field uses in
are references; the inline def was replaced by the hoist. + @Suppress("UNCHECKED_CAST") + val mainNode = (document.rootElement.getChild("main").children as List).first() + + @Suppress("UNCHECKED_CAST") + val nodeChildren = mainNode.children as List + val childRef = nodeChildren.first { it.getAttributeValue("xs.n") == "sharedChild" } + val childAgainRef = nodeChildren.first { it.getAttributeValue("xs.n") == "sharedChildAgain" } + assertEquals("#1", childRef.getAttributeValue("xs.ref"), "first use replaced by a reference") + assertEquals("#1", childAgainRef.getAttributeValue("xs.ref"), "second use is a reference") + assertTrue(childRef.children.isEmpty(), "no inline def remains in
") + + // Re-read resolves both references to the one fresh instance. + val restored = engine.readRoot(XmlCodec.parse(output)) as Node + assertNotNull(restored.sharedChild) + assertSame(restored.sharedChild, restored.sharedChildAgain, "one instance behind both refs") + assertEquals(42, restored.sharedChild?.id) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/GraphEditorTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/GraphEditorTest.kt new file mode 100644 index 0000000..3fb7c2c --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/GraphEditorTest.kt @@ -0,0 +1,100 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.Cmo3GraphEditor +import org.umamo.format.cmo3.serialize.annotations.DontSerializeIfDefault +import org.umamo.format.cmo3.serialize.annotations.SerialAttribute +import org.umamo.format.cmo3.serialize.annotations.SerialTag +import org.umamo.format.cmo3.xml.XmlCodec +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@SerialTag("Badge") +@DontSerializeIfDefault +class Badge { + @SerialAttribute + var kind: String = "" + + @SerialAttribute + var level: Int = 0 +} + +/** + * Pins the Cmo3GraphEditor surface: the attribute-presence trap and its ensurePresentAttr escape + * hatch, hasRecordedOrder distinguishing read objects from fresh ones, and pruneUnreachableShared + * dropping only pool entries nothing references anymore - including keeping entries referenced + * solely from verbatim (untyped) subtrees. + */ +class GraphEditorTest { + private val nodeEngine = SerializeEngine.of(listOf(Node::class, Vec::class, Leaf::class)) + private val badgeEngine = SerializeEngine.of(listOf(Badge::class)) + + private fun sharedLeafSourceXml(): ByteArray { + val sharedLeaf = Leaf().apply { id = 7 } + val node = + Node().apply { + label = "src" + sharedChild = sharedLeaf + sharedChildAgain = sharedLeaf + } + return XmlCodec.write(nodeEngine.writeRoot(node)) + } + + @Test + fun attributeAssignedAfterReadIsDroppedWithoutEnsurePresentAttr() { + val source = XmlCodec.write(badgeEngine.writeRoot(Badge().apply { kind = "gold" })) + val graph = badgeEngine.readModel(XmlCodec.parse(source)) + val badge = graph.root as Badge + badge.level = 3 + + // The trap: the writer emits exactly the attributes recorded present at read, so the bare + // assignment does not reach the document. + val dropped = XmlCodec.write(badgeEngine.writeModel(graph)).decodeToString() + assertTrue("kind=\"gold\"" in dropped, "recorded attribute survives") + assertFalse("level" in dropped, "unrecorded attribute is dropped by the replay") + + Cmo3GraphEditor(graph).ensurePresentAttr(badge, "Badge", "level") + val kept = XmlCodec.write(badgeEngine.writeModel(graph)).decodeToString() + assertTrue("level=\"3\"" in kept, "ensurePresentAttr makes the assignment reach the document") + } + + @Test + fun hasRecordedOrderDistinguishesReadObjectsFromFreshOnes() { + val graph = nodeEngine.readModel(XmlCodec.parse(sharedLeafSourceXml())) + val editor = Cmo3GraphEditor(graph) + assertTrue(editor.hasRecordedOrder(graph.root as Node, "Node"), "read object has a recorded order") + assertFalse(editor.hasRecordedOrder(Leaf(), "Leaf"), "fresh object has none") + } + + @Test + fun pruneDropsOrphanedPoolEntriesAndKeepsReferencedOnes() { + val graph = nodeEngine.readModel(XmlCodec.parse(sharedLeafSourceXml())) + val editor = Cmo3GraphEditor(graph) + + // Still referenced: the pool entry stays. + editor.pruneUnreachableShared() + assertEquals(1, graph.sharedOrder.size, "referenced pool entry survives a prune") + + // Orphaned by a structural delete: the pool entry goes, and the document re-reads cleanly. + val root = graph.root as Node + root.sharedChild = null + root.sharedChildAgain = null + editor.pruneUnreachableShared() + assertEquals(0, graph.sharedOrder.size, "orphaned pool entry is dropped") + val output = XmlCodec.write(nodeEngine.writeModel(graph)) + val restored = nodeEngine.readRoot(XmlCodec.parse(output)) as Node + assertNull(restored.sharedChild, "re-read reflects the delete") + } + + @Test + fun pruneKeepsEntriesReferencedOnlyFromVerbatimSubtrees() { + // An empty registry reads everything verbatim: the root becomes a VerbatimNode whose xs.ref + // attributes are the only remaining links to the pool. + val verbatimEngine = SerializeEngine.of(emptyList()) + val graph = verbatimEngine.readModel(XmlCodec.parse(sharedLeafSourceXml())) + Cmo3GraphEditor(graph).pruneUnreachableShared() + assertEquals(1, graph.sharedOrder.size, "verbatim xs.ref keeps its pool entry alive") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/IdentitySubsystemTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/IdentitySubsystemTest.kt new file mode 100644 index 0000000..29eeee0 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/IdentitySubsystemTest.kt @@ -0,0 +1,73 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * Exercises the identity subsystem (*Guid / *Id). Confirms the reconciliation gate stays byte-identical + * with these typed, and that GUID/Id tags drop out of the unmodeled set (typing has real effect). + */ +class IdentitySubsystemTest { + private val sample: File? = + System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun identitySubsystemTypedAndStillByteIdentical() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping identity subsystem test") + return + } + val mainXml = + CaffCodec.read(file.readBytes()) + .firstByTag(CaffArchive.TAG_MAIN_XML)?.content ?: error("no main_xml") + + // Baseline: nothing typed -> count distinct unmodeled tags. + val baseline = sortedSetOf() + SerializeEngine.of(emptyList()) { tag, _ -> baseline += tag } + .readModel(XmlCodec.parse(mainXml)) + + // Typed identity subsystem. + val unmodeled = sortedSetOf() + val typedShared = mutableListOf() + val engine = cubismEngine { tag, _ -> unmodeled += tag } + val graph = engine.readModel(XmlCodec.parse(mainXml)) + + // GUID/Id shared defs are typed objects, so they don't appear in the unmodeled set. + assertTrue(unmodeled.none { it.endsWith("Guid") || it.endsWith("Id") }, "no GUID/Id left unmodeled: $unmodeled") + assertTrue(unmodeled.size < baseline.size, "typing reduced unmodeled tags (${unmodeled.size} < ${baseline.size})") + graph.sharedOrder.filterTo(typedShared) { it is Guid || it is Id } + assertTrue(typedShared.isNotEmpty(), "some shared defs deserialized into Guid/Id") + assertTrue(typedShared.any { it is Guid && it.uuid.isNotEmpty() }, "a Guid carries its uuid") + + // The gate: re-emit byte-identical. + val reemitted = XmlCodec.write(engine.writeModel(graph)) + assertByteIdentical(mainXml, reemitted) + } + + private fun assertByteIdentical(expected: ByteArray, actual: ByteArray) { + val limit = minOf(expected.size, actual.size) + var firstDiff = -1 + for (index in 0 until limit) { + if (expected[index] != actual[index]) { + firstDiff = index + break + } + } + if (firstDiff < 0 && expected.size == actual.size) return + val at = if (firstDiff < 0) limit else firstDiff + val start = maxOf(0, at - 60) + fail( + "not byte-identical: sizes expected=${expected.size} actual=${actual.size}, first diff @ $at\n" + + " expected: …${expected.decodeToString(start, minOf(expected.size, at + 80)).replace("\r", "\\r").replace("\n", "\\n")}…\n" + + " actual: …${actual.decodeToString(start, minOf(actual.size, at + 80)).replace("\r", "\\r").replace("\n", "\\n")}…", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/ModelDocumentTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/ModelDocumentTest.kt new file mode 100644 index 0000000..e7a1730 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/ModelDocumentTest.kt @@ -0,0 +1,53 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Verifies the ModelDocument backbone: parses the sample's main.xml into navigable parts (versions, + * imports, shared pool, main root) and re-emits byte-identically. Skips without the sample. + */ +class ModelDocumentTest { + private val sample: File? = + System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun parsesPartsAndReemitsByteIdentical() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping ModelDocument test") + return + } + val mainXml = + CaffCodec.read(file.readBytes()) + .firstByTag(CaffArchive.TAG_MAIN_XML)?.content ?: error("no main_xml") + + val doc = ModelDocument.parse(mainXml) + + // Version PIs (sample has 8, including the known CModelSource:13 / CArtMeshSource:4). + assertEquals(13, doc.versionOf("CModelSource"), "CModelSource version") + assertEquals(4, doc.versionOf("CArtMeshSource"), "CArtMeshSource version") + assertEquals(8, doc.versions.size, "version PI count") + + // Import PIs (sample has 158, all fully-qualified class names). + assertEquals(158, doc.imports.size, "import PI count") + assertTrue(doc.imports.all { '.' in it }, "imports are fully-qualified") + assertTrue( + doc.imports.any { it.endsWith("controller.CControllerExtension") }, + "imports include CControllerExtension", + ) + + // Structure: a non-empty shared pool and a single CModelSource main root. + assertTrue(doc.sharedElements.isNotEmpty(), "shared pool non-empty") + assertEquals(1, doc.mainElements.size, "single main root") + assertEquals("CModelSource", doc.mainElements.single().name, "main root is CModelSource") + + // Backbone must re-emit byte-identical (verbatim fallback intact). + assertContentEquals(mainXml, doc.write(), "ModelDocument round-trip byte-identical") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/ReconciliationTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/ReconciliationTest.kt new file mode 100644 index 0000000..1e8ce74 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/ReconciliationTest.kt @@ -0,0 +1,68 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.xml.XmlCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * The reconciliation gate: deconstruct the real main.xml into a ModelGraph (root object + shared + * pool + PIs + root attrs) and re-emit it byte-identical. With an empty registry everything is + * verbatim, proving the read/write reconstruction preserves shared ids/order, PIs, and structure. + * Skips when the sample is unavailable. + */ +class ReconciliationTest { + private val sample: File? = + System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun realMainXmlReconstructsByteIdentical() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping reconciliation test") + return + } + val mainXml = + CaffCodec.read(file.readBytes()) + .firstByTag(CaffArchive.TAG_MAIN_XML)?.content ?: error("no main_xml") + + var unmodeled = 0 + val engine = SerializeEngine.of(emptyList(), diagnostics = { _, _ -> unmodeled++ }) + + val graph = engine.readModel(XmlCodec.parse(mainXml)) + // Sanity: a verbatim CModelSource root and a populated shared pool were captured. + assertTrue(graph.root is VerbatimNode, "root captured verbatim") + assertEquals("CModelSource", (graph.root).tag) + assertTrue(graph.sharedOrder.isNotEmpty(), "shared pool captured") + assertTrue(unmodeled > 0, "unmodeled tags reported (nothing typed yet)") + + val reemitted = XmlCodec.write(engine.writeModel(graph)) + assertByteIdentical(mainXml, reemitted) + } + + /** Memory-safe byte comparison: reports the first divergence without building a 24 MB message. */ + private fun assertByteIdentical(expected: ByteArray, actual: ByteArray) { + val limit = minOf(expected.size, actual.size) + var firstDiff = -1 + for (index in 0 until limit) { + if (expected[index] != actual[index]) { + firstDiff = index + break + } + } + if (firstDiff < 0 && expected.size == actual.size) return + val at = if (firstDiff < 0) limit else firstDiff + val start = maxOf(0, at - 60) + val expectedWindow = expected.decodeToString(start, minOf(expected.size, at + 80)) + val actualWindow = actual.decodeToString(start, minOf(actual.size, at + 80)) + fail( + "not byte-identical: sizes expected=${expected.size} actual=${actual.size}, " + + "first diff @ $at\n expected: …${expectedWindow.replace("\r", "\\r").replace("\n", "\\n")}…" + + "\n actual: …${actualWindow.replace("\r", "\\r").replace("\n", "\\n")}…", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/SerializeEngineTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/SerializeEngineTest.kt new file mode 100644 index 0000000..d4ccf08 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/SerializeEngineTest.kt @@ -0,0 +1,81 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.serialize.annotations.SerialTag +import org.umamo.format.cmo3.xml.XmlCodec +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +@SerialTag("Leaf") +class Leaf { + var id: Int = 0 +} + +@SerialTag("Vec", version = 2) +class Vec { + var x: Int = 0 + var y: Float = 0f +} + +@SerialTag("Node") +class Node { + var label: String = "" + var flag: Boolean = false + var position: Vec? = null + var numbers: List = emptyList() + var sharedChild: Leaf? = null + var sharedChildAgain: Leaf? = null +} + +/** + * Validates the reflective engine core end-to-end: field discovery/order, primitives as + * `///` children, nested objects, an `array_list`, shared-object hoisting (xs.id/xs.ref/ + * xs.idx), version PIs, and full byte<->object<->byte round-trip through JDOM. + */ +class SerializeEngineTest { + private val engine = SerializeEngine.of(listOf(Node::class, Vec::class, Leaf::class)) + + @Test + fun roundTripsTypedGraphThroughXml() { + val leaf = Leaf().apply { id = 7 } + val node = + Node().apply { + label = "hi" + flag = true + position = + Vec().apply { + x = 1 + y = 2.5f + } + numbers = listOf(1, 2, 3) + sharedChild = leaf + sharedChildAgain = leaf // same instance -> must become a shared ref + } + + val xmlBytes = XmlCodec.write(engine.writeRoot(node)) + val xml = xmlBytes.decodeToString() + + // Shape checks against the editor's conventions. + assertTrue("" in xml, "version PI emitted") + assertTrue("" in xml || " { + val xml = XmlCodec.write(engine.writeRoot(value)).decodeToString() + val restored = engine.readRoot(XmlCodec.parse(xml.toByteArray())) + return xml to restored + } + + @Test + fun gvector2MatchesSampleForm() { + val (xml, restored) = + roundTrip( + GVector2().apply { + x = 6742.0273f + y = 6710.0273f + }, + ) + assertTrue("\r\n6742.0273\r\n6710.0273\r\n" in xml, xml) + restored as GVector2 + assertEquals(6742.0273f, restored.x) + assertEquals(6710.0273f, restored.y) + } + + @Test + fun crectMatchesSampleForm() { + val (xml, restored) = + roundTrip( + CRect().apply { + x = 2197 + y = 535 + width = 309 + height = 439 + }, + ) + assertTrue("2197" in xml && "439" in xml, xml) + restored as CRect + assertEquals(2197, restored.x) + assertEquals(439, restored.height) + } + + @Test + fun caffineMatchesSampleForm() { + val (xml, restored) = roundTrip(CAffine()) // identity + assertTrue("" in xml, xml) + restored as CAffine + assertEquals(1.0f, restored.m00) + assertEquals(1.0f, restored.m11) + } + + @Test + fun ccolorSerializesEmpty() { + val (xml, restored) = roundTrip(CColor().apply { argb = 0x11223344 }) + assertTrue("" in xml, "CColor serializes empty (argb is @DontSerialize): $xml") + assertTrue(restored is CColor) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/VerbatimFallbackTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/VerbatimFallbackTest.kt new file mode 100644 index 0000000..7b5efb6 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/serialize/VerbatimFallbackTest.kt @@ -0,0 +1,51 @@ +package org.umamo.format.cmo3.serialize + +import org.umamo.format.cmo3.serialize.annotations.SerialTag +import org.umamo.format.cmo3.xml.XmlCodec +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@SerialTag("Holder") +class Holder { + var name: String = "" + var payload: Any? = null +} + +/** + * Verifies the verbatim-JDOM fallback: an unmodeled tag inside a typed object is preserved + * losslessly on round-trip and reported via SerializeDiagnostics. + */ +class VerbatimFallbackTest { + @Test + fun unmodeledSubtreeRoundTripsAndReports() { + // A Holder (typed) whose `payload` is a class the engine does not know (). + val sourceXml = + """ +
+ hi5 +
+ """.trimIndent().toByteArray() + + val reported = mutableListOf() + val engine = + SerializeEngine.of( + listOf(Holder::class), + diagnostics = { tag, path -> reported += "$tag@$path" }, + ) + + val holder = engine.readRoot(XmlCodec.parse(sourceXml)) as Holder + assertEquals("hi", holder.name) + assertTrue(holder.payload is VerbatimNode, "unmodeled child kept verbatim") + assertEquals("Mystery", (holder.payload as VerbatimNode).tag) + + // Diagnostics fired once, naming the unmodeled tag and its owning field. + assertEquals(listOf("Mystery@payload"), reported) + + // Re-emit: the unmodeled subtree (attributes + nested element) survives intact. + val out = XmlCodec.write(engine.writeRoot(holder)).decodeToString() + assertTrue("5
" in out, "nested unmodeled content preserved") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/GeneratedModelSource.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/GeneratedModelSource.kt new file mode 100644 index 0000000..ed0c202 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/GeneratedModelSource.kt @@ -0,0 +1,182 @@ +package org.umamo.format.cmo3.tools + +import java.io.File + +/* + * A reader for the previously generated model, so ModelGenerator can ADD to it instead of replacing + * it. + * + * Why this exists: the generator only ever sees what the corpus exercises, so a regenerate from + * samples alone is destructive. Measured against the 4-sample corpus it dropped 31 enum constants, + * 7 whole enums, 29 classes, and 128 fields -- every one of them a real part of the format that + * simply had no sample. Worse, nothing would catch it: a constant no sample uses fails no test, and + * a dropped class falls back to verbatim and still round-trips byte-identical. So the previous + * output is an input, and generation is a union. + * + * The file is machine-written to a rigid shape, which is what makes parsing it reasonable rather + * than reckless. Both shapes it emits are handled: a class with a body, and the brace-less + * `class X : Y()` form used for an empty one. + */ + +/** One serialized field of a generated class, kept verbatim so re-emission is faithful. */ +internal class ModelField( + /** The on-disk `xs.n` name, which is what sample inference matches against. */ + val serialName: String, + /** The property lines exactly as previously emitted, annotations included. */ + val lines: List, +) { + /** True when the field already carries @DontSerializeIfDefault. */ + val dontSerializeIfDefault: Boolean get() = lines.any { it.trim() == "@DontSerializeIfDefault" } +} + +/** One generated class, with its fields in declaration order -- the order the serializer emits. */ +internal class ModelClass( + val tag: String, + val declaration: String, + val fields: MutableList = mutableListOf(), +) { + /** True for the brace-less `class X : Y()` form, which has no body to merge into. */ + val isBodyless: Boolean get() = !declaration.trimEnd().endsWith("{") +} + +/** The previously generated model: enum values and classes, both keyed by serial tag. */ +internal class GeneratedModelSource( + val enums: MutableMap> = linkedMapOf(), + val classes: MutableMap = linkedMapOf(), +) + +private val SERIAL_TAG = Regex("""^@SerialTag\("([^"]+)"\)$""") +private val ENUM_DECLARATION = Regex("""^public enum class \w+ \{([^}]*)}$""") +private val CLASS_DECLARATION = Regex("""^public (?:open )?class \w+""") +private val PROPERTY_DECLARATION = Regex("""^\tpublic (?:open )?var `([^`]+)`:""") +private val SERIAL_NAME = Regex("""^\t@SerialName\("([^"]+)"\)$""") + +/** + * Parses a previously generated model file, or returns an empty model when it does not exist. + * + * Splitting strictly on `@SerialTag` boundaries is deliberate: an earlier brace-matching attempt + * silently swallowed every declaration following a brace-less `class X : Y()`, and reported eleven + * classes as missing that were present all along. Anchoring on the tag line cannot drift that way. + * + * @param File file The generated model file. + * @return GeneratedModelSource The parsed model; empty when the file is absent. + */ +internal fun parseGeneratedModel(file: File): GeneratedModelSource { + val model = GeneratedModelSource() + if (!file.isFile) { + return model + } + val lines = file.readLines() + var index = 0 + while (index < lines.size) { + val tagMatch = SERIAL_TAG.find(lines[index].trim()) + if (tagMatch == null) { + index++ + continue + } + val tag = tagMatch.groupValues[1] + index++ + if (index >= lines.size) { + break + } + val declaration = lines[index] + val enumMatch = ENUM_DECLARATION.find(declaration.trim()) + if (enumMatch != null) { + model.enums[tag] = enumMatch.groupValues[1].split(',').map { it.trim() }.filter { it.isNotEmpty() }.toMutableSet() + index++ + continue + } + if (!CLASS_DECLARATION.containsMatchIn(declaration.trim())) { + continue + } + val modelClass = ModelClass(tag, declaration) + model.classes[tag] = modelClass + index++ + if (modelClass.isBodyless) { + continue + } + // Accumulate annotation lines until the property they decorate closes the field. + val pending = mutableListOf() + var serialNameOverride: String? = null + while (index < lines.size && lines[index] != "}") { + val line = lines[index] + SERIAL_NAME.find(line)?.let { serialNameOverride = it.groupValues[1] } + pending += line + val propertyMatch = PROPERTY_DECLARATION.find(line) + if (propertyMatch != null) { + // @SerialName carries the real on-disk name when it is not a legal Kotlin identifier. + val serialName = serialNameOverride ?: propertyMatch.groupValues[1] + modelClass.fields += ModelField(serialName, pending.toList()) + pending.clear() + serialNameOverride = null + } + index++ + } + } + return model +} + +/** + * Merges two field orders, preserving both, so a new field lands where the format actually puts it. + * + * Order is load-bearing: the serializer emits fields in `declaredFields` order (see + * Serializers.buildProperties), so appending a newly discovered field would move it in the XML and + * break byte-identity. A longest-common-subsequence merge keeps every field of both inputs in their + * relative positions, anchored on the fields the two agree about. + * + * @param List existing The order already generated. + * @param List inferred The order observed in the samples. + * @return List The merged order, containing the union of both. + */ +internal fun mergeFieldOrder(existing: List, inferred: List): List { + val lengths = Array(existing.size + 1) { IntArray(inferred.size + 1) } + for (existingIndex in existing.indices.reversed()) { + for (inferredIndex in inferred.indices.reversed()) { + lengths[existingIndex][inferredIndex] = + if (existing[existingIndex] == inferred[inferredIndex]) { + lengths[existingIndex + 1][inferredIndex + 1] + 1 + } else { + maxOf(lengths[existingIndex + 1][inferredIndex], lengths[existingIndex][inferredIndex + 1]) + } + } + } + val merged = mutableListOf() + var existingIndex = 0 + var inferredIndex = 0 + while (existingIndex < existing.size && inferredIndex < inferred.size) { + when { + existing[existingIndex] == inferred[inferredIndex] -> { + merged += existing[existingIndex] + existingIndex++ + inferredIndex++ + } + // Off the common subsequence: emit from whichever side the LCS says to advance, so both + // inputs' relative orders survive. + lengths[existingIndex + 1][inferredIndex] >= lengths[existingIndex][inferredIndex + 1] -> { + if (existing[existingIndex] !in merged) { + merged += existing[existingIndex] + } + existingIndex++ + } + else -> { + if (inferred[inferredIndex] !in merged) { + merged += inferred[inferredIndex] + } + inferredIndex++ + } + } + } + while (existingIndex < existing.size) { + if (existing[existingIndex] !in merged) { + merged += existing[existingIndex] + } + existingIndex++ + } + while (inferredIndex < inferred.size) { + if (inferred[inferredIndex] !in merged) { + merged += inferred[inferredIndex] + } + inferredIndex++ + } + return merged +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/GeneratedModelSourceTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/GeneratedModelSourceTest.kt new file mode 100644 index 0000000..3a63c76 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/GeneratedModelSourceTest.kt @@ -0,0 +1,109 @@ +package org.umamo.format.cmo3.tools + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the merge machinery ModelGenerator relies on to be additive. + * + * Worth its own test because a parser that quietly under-reports is the exact failure that makes a + * "merge" delete things: it cannot see what it is about to drop. An earlier brace-matching parser did + * precisely that -- a brace-less `class X : Y()` swallowed the declarations after it, and eleven + * present classes read as missing. These assertions run against the real generated file, so they + * fail if the emitted shape ever drifts away from what the parser understands. + */ +class GeneratedModelSourceTest { + private val generatedModel = + File("src/commonMain/kotlin/org/umamo/format/cmo3/model/gen/GeneratedModel.kt") + + @Test + fun parsesEveryDeclarationInTheRealGeneratedModel() { + if (!generatedModel.isFile) { + println("GeneratedModel.kt not found at ${generatedModel.absolutePath}; skipping") + return + } + val model = parseGeneratedModel(generatedModel) + // Cross-check against a source the parser cannot influence: the raw @SerialTag count. + val declaredTags = generatedModel.readLines().count { it.startsWith("@SerialTag(") } + assertEquals( + declaredTags, + model.enums.size + model.classes.size, + "every @SerialTag must parse into exactly one enum or class -- a shortfall means the parser " + + "is silently dropping declarations, which would make a merge delete them", + ) + assertTrue(model.enums.isNotEmpty(), "enums must parse") + assertTrue(model.classes.size > 100, "classes must parse; got ${model.classes.size}") + } + + @Test + fun parsesTheBracelessEmptyClassForm() { + if (!generatedModel.isFile) { + return + } + val model = parseGeneratedModel(generatedModel) + // `public class CBlend_Normal : ACBlend()` has no body -- the shape that broke the old parser. + val bodyless = model.classes.values.filter { it.isBodyless } + assertTrue(bodyless.isNotEmpty(), "the brace-less form must be recognized, not skipped") + assertTrue(bodyless.all { it.fields.isEmpty() }, "a brace-less class has no fields to collect") + } + + @Test + fun capturesFieldsInDeclarationOrderWithTheirAnnotations() { + if (!generatedModel.isFile) { + return + } + val model = parseGeneratedModel(generatedModel) + val withFields = model.classes.values.filter { it.fields.isNotEmpty() } + assertTrue(withFields.isNotEmpty(), "classes with fields must parse") + // Every field's captured lines must actually contain its own declaration. + for (modelClass in withFields) { + for (field in modelClass.fields) { + assertTrue( + field.lines.any { it.contains("var `") }, + "${modelClass.tag}.${field.serialName} captured no property line", + ) + } + } + assertTrue( + model.classes.values.any { modelClass -> modelClass.fields.any { it.dontSerializeIfDefault } }, + "@DontSerializeIfDefault must be carried through, or a merge would drop it", + ) + } + + @Test + fun mergeKeepsEveryFieldFromBothOrders() { + val existing = listOf("alpha", "bravo", "charlie") + val inferred = listOf("alpha", "delta", "charlie") + val merged = mergeFieldOrder(existing, inferred) + assertEquals(listOf("alpha", "bravo", "delta", "charlie"), merged, "the union, with both orders intact") + } + + @Test + fun mergeInsertsANewFieldInPositionRatherThanAppending() { + // The load-bearing case: the serializer emits fields in declaration order, so a new field + // appended to the end would move it in the XML and break byte-identity. + val existing = listOf("alpha", "charlie") + val inferred = listOf("alpha", "bravo", "charlie") + assertEquals(listOf("alpha", "bravo", "charlie"), mergeFieldOrder(existing, inferred)) + } + + @Test + fun mergeIsIdentityWhenNothingIsNew() { + val order = listOf("alpha", "bravo", "charlie") + assertEquals(order, mergeFieldOrder(order, order), "a re-run with no new samples must not churn the file") + assertEquals(order, mergeFieldOrder(order, emptyList()), "a class no sample exercises keeps its order") + assertEquals(order, mergeFieldOrder(emptyList(), order), "a brand-new class takes the inferred order") + } + + @Test + fun mergeNeverDropsAFieldEvenWhenTheOrdersDisagree() { + // Contradictory orders cannot both be honoured; what matters is that nothing vanishes. + val existing = listOf("alpha", "bravo", "charlie") + val inferred = listOf("charlie", "bravo", "alpha") + val merged = mergeFieldOrder(existing, inferred) + assertEquals(setOf("alpha", "bravo", "charlie"), merged.toSet(), "no field may be lost") + assertEquals(merged.size, merged.distinct().size, "no field may be duplicated") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/ModelGenerator.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/ModelGenerator.kt new file mode 100644 index 0000000..046bc84 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/tools/ModelGenerator.kt @@ -0,0 +1,453 @@ +package org.umamo.format.cmo3.tools + +import org.jdom.Element +import org.jdom.input.SAXBuilder +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.serialize.GUID_TAGS +import org.umamo.format.cmo3.serialize.ID_TAGS +import java.io.ByteArrayInputStream +import java.io.File +import kotlin.test.Test + +/** + * Sample-driven code generator for the reflective Cubism model classes. Reads each sample's main.xml, + * infers every tag's serialized field signature (name/type/order, inheritance, + * @DontSerializeIfDefault for sometimes-present fields), detects enums, and reports custom + * (attribute-bearing) tags for hand-writing. Emits model classes + a registration function. + * + * ADDITIVE, never destructive. The previously generated model is an INPUT: the output is the union of + * what is already there and what the corpus proves. This is not a nicety. The generator only ever sees + * what the samples happen to exercise, so a replace-everything run deletes every part of the format + * that no sample reaches -- measured against a 4-sample corpus, that was 31 enum constants, 7 whole + * enums, 29 classes, and 128 fields. And nothing would catch it: an unused enum constant fails no + * test, and a dropped class falls back to verbatim and still round-trips byte-identical. So the rule + * is: add what is newly proven, keep everything else exactly as it stands. + * + * Run with: -Dcmo3.generate=true. Input samples come from -Dcmo3.gensample (defaults to the whole + * cmo3/ corpus, so the union spans every version and feature available). The byte-identity gate over + * that same corpus validates the output. + */ +class ModelGenerator { + /** + * Fields that must ALWAYS serialize, overriding the sometimes-present inference. + * + * The `@DontSerializeIfDefault` rule is "the corpus does not always carry this field", which is + * a statement about the SAMPLES. For these four the official editor's custom deserializers + * dereference the field unconditionally and NPE at load when it is absent, so omitting it + * writes a file Cubism cannot open - the corpus merely happens to include older-era samples + * that predate the field. Corpus evidence cannot express that, so the exception lives here, + * in the generator, and NOT as a hand-edit of the output: a from-scratch regeneration (the + * output file deleted) has to reproduce it, and a hand-edit would not survive that. + * + * Keyed "Tag.field"; the value is the comment emitted above the property. + */ + private val alwaysSerializedFields = + mapOf( + "ACLayerEntry.isTransparencyShapesLayer" to "the editor always writes this field", + "ACParameterControllableSource.internalColor_direct_argb" to "the editor always writes this field, as an explicit null", + "CPartSource.useOffscreen" to "CPartSource.deserialize dereferences this unconditionally", + "CPartSource.invertClippingMask" to "CPartSource.deserialize dereferences this unconditionally", + ) + + private val primitiveTags = + mapOf( + "i" to ("Int" to "0"), + "f" to ("Float" to "0f"), + "d" to ("Double" to "0.0"), + "l" to ("Long" to "0L"), + "short" to ("Short" to "0"), + "byte" to ("Byte" to "0"), + "char" to ("Char" to "'\\u0000'"), + "b" to ("Boolean" to "false"), + "s" to ("String" to "\"\""), + ) + private val collectionTags = + setOf( + "array_list", + "carray_list", + "hash_map", + "linked_map", + "linked_set", + "entry", + "null", + "float", + "float-array", + "int-array", + "long-array", + "short-array", + "double-array", + "byte-array", + "char-array", + "bool-array", + ) + + // Already handled by hand (custom serializers or hand-written reflective classes). + private val handHandled = + buildSet { + addAll(GUID_TAGS) + addAll(ID_TAGS) + addAll( + listOf( + "CAffine", + "GVector2", + "CRect", + "CColor", + "CFloatColor", + "CLabelColor", + "CoordType", + "PointInTriangle", + "PointOnCurve", + "MeshPointRef", + "WarpDeformerOriginalShape", + "RotationDeformerOriginalShape", + ), + ) + add("root") + add("shared") + add("main") + add("file") + } + + private val neutralAttrs = setOf("xs.n", "xs.id", "xs.idx", "xs.ref", "count", "keyType") + + private class TagInfo { + var instances = 0 + var hasChildren = false + var superTag: String? = null + val customAttrs = sortedSetOf() + val enumValues = sortedSetOf() + val fieldTypeTags = LinkedHashMap>() // field -> observed child tags + val fieldPresence = HashMap() + val nullableFields = sortedSetOf() // fields observed as in some instance + var bestOrder: List = emptyList() // field order from the richest instance + var bestOrderSize = -1 + val isSuperOf = sortedSetOf() + } + + @Test + fun generate() { + if (System.getProperty("cmo3.generate") != "true") return + // Generate from cmo3.gensample if given (a comma-separated list unions several projects, e.g. the + // feature-complete so enum constants and fields from every version are covered), else the default single sample. + val sampleSpec = + System.getProperty("cmo3.gensample") ?: System.getProperty("cmo3.sample") + ?: error("cmo3.sample required") + val sampleFiles = sampleSpec.split(',').map { File(it.trim()) }.filter { it.isFile } + require(sampleFiles.isNotEmpty()) { "no readable sample in cmo3.gensample/cmo3.sample" } + val rootDir = repositoryRoot() + println("=== generating from ${sampleFiles.size} sample(s) into $rootDir ===") + + // Walk every sample into one accumulator: instances/enum-values/fields union across versions. + val tags = HashMap() + for (sampleFile in sampleFiles) { + val mainXml = + CaffCodec.read(sampleFile.readBytes()) + .firstByTag(CaffArchive.TAG_MAIN_XML)?.content ?: error("no main_xml in ${sampleFile.name}") + walk(SAXBuilder().build(ByteArrayInputStream(mainXml)).rootElement, tags) + } + + val reflective = sortedMapOf() + val enums = sortedMapOf() + val custom = sortedSetOf() + for ((tag, info) in tags) { + if (tag in handHandled || tag in primitiveTags || tag in collectionTags) continue + when { + info.customAttrs == sortedSetOf("v") && !info.hasChildren -> enums[tag] = info + info.customAttrs.isNotEmpty() -> custom += "$tag ${info.customAttrs}" + else -> reflective[tag] = info + } + } + + // Exclude classes that would redeclare an inherited field (e.g. the IOption mixin pattern): + // Kotlin forbids hiding a supertype member, and a safe override is risky to infer. Skip such + // classes (and anything extending them) - they stay verbatim and round-trip byte-identical. + fun ownFields(tag: String): Set = + reflective[tag]?.let { (it.bestOrder + it.fieldTypeTags.keys).toSet() } ?: emptySet() + + fun ancestorFields(tag: String): Set { + val out = HashSet() + var superTag = reflective[tag]?.superTag + while (superTag != null) { + out += ownFields(superTag) + superTag = reflective[superTag]?.superTag + } + return out + } + + val skip = sortedSetOf() + for (tag in reflective.keys) if ((ownFields(tag) intersect ancestorFields(tag)).isNotEmpty()) skip += tag + var changed = true + while (changed) { // cascade: drop anything extending a skipped class + changed = false + for ((tag, info) in reflective) { + val superTag = info.superTag + if (tag !in skip && superTag != null && superTag in skip) { + skip += tag + changed = true + } + } + } + val emit = reflective.filterKeys { it !in skip }.toSortedMap() + + writeModel(rootDir, emit, enums) + writeRegistration(rootDir, emit, enums) + + println("=== GENERATED ${emit.size} reflective classes, ${enums.size} enums ===") + println("=== SKIPPED (inherited-field collision; stay verbatim) ${skip.size}: $skip ===") + println("=== CUSTOM (hand-write these ${custom.size}): ===") + custom.forEach { println(" $it") } + } + + private fun walk(element: Element, tags: HashMap) { + // A reference (xs.ref) is not a definition: it has no fields and must not be counted as an + // instance (doing so made every field look "sometimes-present"). + if (element.getAttributeValue("xs.ref") != null) return + val tag = element.name + if (tag !in primitiveTags && tag !in collectionTags && tag != "entry") { + val info = tags.getOrPut(tag) { TagInfo() } + info.instances++ + @Suppress("UNCHECKED_CAST") + val attrs = element.attributes as List + for (attribute in attrs) { + if (attribute.name !in neutralAttrs) { + info.customAttrs += attribute.name + if (attribute.name == "v") info.enumValues += attribute.value + } + } + @Suppress("UNCHECKED_CAST") + val children = element.children as List + info.hasChildren = info.hasChildren || children.any { it.getAttributeValue("xs.n") != null } + val order = ArrayList() + for (child in children) { + val fieldName = child.getAttributeValue("xs.n") ?: continue + if (fieldName == "super") { + info.superTag = child.name + tags.getOrPut(child.name) { TagInfo() }.isSuperOf += tag + continue + } + if (child.name != "null") { + info.fieldTypeTags.getOrPut(fieldName) { sortedSetOf() } += child.name + } else { + info.fieldTypeTags.getOrPut(fieldName) { sortedSetOf() } + info.nullableFields += fieldName // a value means the field must be nullable + } + order += fieldName + info.fieldPresence[fieldName] = (info.fieldPresence[fieldName] ?: 0) + 1 + } + if (order.size > info.bestOrderSize) { + info.bestOrder = order + info.bestOrderSize = order.size + } + } + @Suppress("UNCHECKED_CAST") + for (child in element.children as List) walk(child, tags) + } + + private fun ktTypeAndDefault(typeTags: Set): Pair { + if (typeTags.size == 1) primitiveTags[typeTags.first()]?.let { return it } + return "Any?" to "null" + } + + /** + * The repository root, located by walking up for settings.gradle.kts. + * + * Not derived from the sample path, which is what it used to be: `sample.parentFile.parentFile` + * assumed the corpus sat exactly two levels below the root, so with samples at test/corpus/cmo3/ it + * resolved to test/corpus and wrote the "generated" model into the gitignored corpus, where nothing + * would ever compile it. + * + * @return File The repository root. + */ + private fun repositoryRoot(): File { + var candidate: File? = File(".").absoluteFile + while (candidate != null) { + if (File(candidate, "settings.gradle.kts").isFile) { + return candidate + } + candidate = candidate.parentFile + } + error("no settings.gradle.kts above ${File(".").absolutePath}; cannot locate the repository root") + } + + /** + * The property lines for a newly inferred field, annotations included. + * + * @param String tag The owning tag, for the @SerialName fallback. + * @param String field The on-disk `xs.n` field name. + * @param TagInfo info The inferred facts about the owning tag. + * @param String propertyModifier "open " for a class that is extended, else empty. + * @return List The lines to emit. + */ + private fun newFieldLines(tag: String, field: String, info: TagInfo, propertyModifier: String): List { + val lines = mutableListOf() + val (baseType, baseDefault) = ktTypeAndDefault(info.fieldTypeTags[field] ?: emptySet()) + // Nullable when observed as , or always for String (commonly null in the data). + val nullable = baseType != "Any?" && (field in info.nullableFields || baseType == "String") + val type = if (nullable) "$baseType?" else baseType + val default = if (nullable) "null" else baseDefault + val alwaysSerializedReason = alwaysSerializedFields["$tag.$field"] + if (alwaysSerializedReason != null) { + // The exception is emitted as a comment so the output explains itself; the rule that + // produces it lives in alwaysSerializedFields, so regeneration reproduces both. + lines += "\t// No @DontSerializeIfDefault: $alwaysSerializedReason, and the official" + lines += "\t// reader NPEs on its absence (docs/format/CMO3.md, Created-Entity Conventions)." + } else if ((info.fieldPresence[field] ?: 0) < info.instances) { + lines += "\t@DontSerializeIfDefault" + } + // Field names that are not legal Kotlin identifiers (e.g. "parameters.keys") get a + // sanitized property name + @SerialName carrying the real on-disk xs.n. + val legal = field.matches(Regex("[A-Za-z_][A-Za-z0-9_]*")) + val kotlinName = if (legal) field else field.replace(Regex("[^A-Za-z0-9_]"), "_") + if (!legal) { + lines += "\t@SerialName(\"$field\")" + } + lines += "\tpublic ${propertyModifier}var `$kotlinName`: $type = $default" + return lines + } + + /** + * Emits the model as the union of what was already generated and what the samples prove. + * + * Every existing declaration is carried through verbatim, including ones no sample exercises: the + * corpus is evidence of what the format DOES contain, never of what it does not. New tags, new + * enum constants, and new fields are added; nothing is removed or rewritten. + * + * @param File rootDir The repository root. + * @param Map reflective Inferred reflective classes. + * @param Map enums Inferred enums. + */ + private fun writeModel(rootDir: File, reflective: Map, enums: Map) { + val outFile = + File(rootDir, "module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/gen/GeneratedModel.kt") + val existing = parseGeneratedModel(outFile) + val added = mutableListOf() + + val builder = StringBuilder() + builder.appendLine("// GENERATED by ModelGenerator from the corpus main.xml, merged over the previous output.") + builder.appendLine("// Do not edit by hand; re-run with -Dcmo3.generate=true. Generation only ever ADDS.") + builder.appendLine("package org.umamo.format.cmo3.model.gen") + builder.appendLine() + builder.appendLine("import org.umamo.format.cmo3.serialize.annotations.DontSerializeIfDefault") + builder.appendLine("import org.umamo.format.cmo3.serialize.annotations.SerialName") + builder.appendLine("import org.umamo.format.cmo3.serialize.annotations.SerialTag") + builder.appendLine() + + for (tag in (existing.enums.keys + enums.keys).sorted()) { + val previous = existing.enums[tag] ?: emptySet() + val inferred = enums[tag]?.enumValues ?: emptySet() + (inferred - previous).forEach { added += "enum $tag.$it" } + if (tag !in existing.enums) { + added += "enum $tag (new)" + } + val values = (previous + inferred).sorted() + // A SINGLE-constant enum gets a trailing comma because that is what ktlintFormat writes; + // emitting it here keeps generate -> format idempotent. Without it every regeneration + // produced a spurious diff on exactly these enums that the next format run reversed. + val constants = values.joinToString(", ") + if (values.size == 1) "," else "" + builder.appendLine("@SerialTag(\"$tag\")") + builder.appendLine("public enum class $tag { $constants }") + builder.appendLine() + } + + for (tag in (existing.classes.keys + reflective.keys).sorted()) { + val previousClass = existing.classes[tag] + val info = reflective[tag] + if (previousClass != null) { + // Keep the declaration exactly: its `open` modifier and super clause encode decisions + // (including hand-written supers) that a fresh inference over a different corpus may not + // reproduce. + builder.appendLine("@SerialTag(\"$tag\")") + builder.appendLine(previousClass.declaration) + if (previousClass.isBodyless) { + builder.appendLine() + continue + } + val propertyModifier = if (previousClass.declaration.contains("open class")) "open " else "" + val byName = previousClass.fields.associateBy { it.serialName } + val inferredOrder = + if (info != null) { + LinkedHashSet(info.bestOrder).also { it += info.fieldTypeTags.keys }.toList() + } else { + emptyList() + } + for (field in mergeFieldOrder(previousClass.fields.map { it.serialName }, inferredOrder)) { + val known = byName[field] + if (known != null) { + known.lines.forEach { builder.appendLine(it) } + } else { + added += "$tag.$field" + newFieldLines(tag, field, info!!, propertyModifier).forEach { builder.appendLine(it) } + } + } + builder.appendLine("}") + builder.appendLine() + continue + } + + // A tag the previous output never had. + added += "class $tag (new)" + val openMod = if (info!!.isSuperOf.isNotEmpty()) "open " else "" + // Only extend a superclass that is itself generated; an external/hand-written super is left + // off (its element is preserved verbatim as an unmatched child at runtime). + val superClause = + info.superTag?.takeIf { reflective.containsKey(it) || existing.classes.containsKey(it) }?.let { " : $it()" } ?: "" + builder.appendLine("@SerialTag(\"$tag\")") + builder.appendLine("public ${openMod}class $tag$superClause {") + val fields = LinkedHashSet(info.bestOrder) + info.fieldTypeTags.keys.forEach { fields += it } // union, in case a field only appears outside the richest instance + // Open classes get open properties so hand-written subclasses can override (e.g. CLayer + // overriding the inherited _optionOfIOption); final classes keep plain properties. + for (field in fields) { + newFieldLines(tag, field, info, if (openMod.isNotEmpty()) "open " else "").forEach { builder.appendLine(it) } + } + builder.appendLine("}") + builder.appendLine() + } + + outFile.parentFile.mkdirs() + // trimEnd + one newline: the per-declaration blank-line separator leaves a trailing empty + // line that ktlintFormat strips, which made every generate -> format cycle churn one line. + outFile.writeText(builder.toString().trimEnd() + "\n") + println("=== ADDED ${added.size} declaration(s) ===") + added.sorted().forEach { println(" + $it") } + } + + /** + * Emits the registration function over the union of every generated declaration. + * + * Reads the model file back rather than registering only what this run inferred: the model is a + * union, so registering just the inferred subset would leave every carried-over class unregistered + * and silently drop it to verbatim -- the same deletion the merge exists to prevent, one file over. + * + * @param File rootDir The repository root. + * @param Map reflective Inferred reflective classes (already merged into the model). + * @param Map enums Inferred enums (already merged into the model). + */ + private fun writeRegistration(rootDir: File, reflective: Map, enums: Map) { + val model = + parseGeneratedModel( + File(rootDir, "module/format/src/commonMain/kotlin/org/umamo/format/cmo3/model/gen/GeneratedModel.kt"), + ) + val builder = StringBuilder() + builder.appendLine("// GENERATED by ModelGenerator. Do not edit by hand.") + builder.appendLine("package org.umamo.format.cmo3.serialize.gen") + builder.appendLine() + builder.appendLine("import org.umamo.format.cmo3.model.gen.*") + builder.appendLine("import org.umamo.format.cmo3.serialize.SerializerRegistry") + builder.appendLine() + builder.appendLine("/** Registers every generated reflective class + enum. */") + builder.appendLine("internal fun registerGeneratedSubsystem(registry: SerializerRegistry) {") + for (tag in (model.classes.keys + model.enums.keys + reflective.keys + enums.keys).sorted()) { + builder.appendLine("\tregistry.register($tag::class)") + } + builder.appendLine("}") + val outFile = + File( + rootDir, + "module/format/src/jvmAndroidMain/kotlin/org/umamo/format/cmo3/serialize/gen/GeneratedRegistration.kt", + ) + outFile.parentFile.mkdirs() + outFile.writeText(builder.toString().trimEnd() + "\n") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/xml/XmlRoundTripTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/xml/XmlRoundTripTest.kt new file mode 100644 index 0000000..d6c1506 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/cmo3/xml/XmlRoundTripTest.kt @@ -0,0 +1,36 @@ +package org.umamo.format.cmo3.xml + +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertTrue + +/** + * End-to-end XML fidelity: cmo3 -> CAFF -> main.xml bytes -> JDOM parse -> emit -> identical bytes. + * + * This locks the editor's XML formatting contract - re-emitted bytes must be byte-identical to the + * original. Skips when the sample is unavailable. + */ +class XmlRoundTripTest { + private val sample: File? = + System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun mainXmlRoundTripsByteIdentical() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping XML round-trip test") + return + } + val archive = CaffCodec.read(file.readBytes()) + val mainXml = + archive.firstByTag(CaffArchive.TAG_MAIN_XML)?.content + ?: error("no main_xml entry") + + val reemitted = XmlCodec.write(XmlCodec.parse(mainXml)) + assertTrue(reemitted.isNotEmpty(), "non-empty output") + assertContentEquals(mainXml, reemitted, "main.xml must round-trip byte-identical via JDOM") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/jpeg/JpegDecodeCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/jpeg/JpegDecodeCorpusTest.kt new file mode 100644 index 0000000..39dfe79 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/jpeg/JpegDecodeCorpusTest.kt @@ -0,0 +1,63 @@ +package org.umamo.format.jpeg + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Corpus-gated end-to-end JPEG decode: every `.jpg`/`.jpeg` under `test/corpus/` (or the single file + * named by `-Djpeg.sample=/path/to.jpg`) must decode to a correctly sized RGBA buffer. The corpus is + * not committed, so this self-skips when absent; the committed [JpegDecodeTest] fixtures carry the + * per-feature regression coverage. Progressive JPEGs are out of scope, so pick baseline samples. + */ +class JpegDecodeCorpusTest { + /** + * Locates every JPEG sample: `-Djpeg.sample` when set, else the `test/corpus` directory (and its + * `jpeg` subdirectory) found by walking up from the working directory. + * + * @return List The sample files, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("jpeg.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return listOf(corpus, File(corpus, "jpeg")) + .filter(File::isDirectory) + .flatMap { folder -> folder.listFiles { file -> file.isFile && isJpeg(file) }?.toList() ?: emptyList() } + .sortedBy { it.name } + } + directory = directory.parentFile + } + return emptyList() + } + + /** + * Whether [file] carries a JPEG extension. + * + * @param File file The candidate file. + * @return Boolean True for `.jpg` / `.jpeg`. + */ + private fun isJpeg(file: File): Boolean = file.extension.equals("jpg", ignoreCase = true) || file.extension.equals("jpeg", ignoreCase = true) + + @Test + fun decodesEveryCorpusJpeg() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no jpeg.sample and no test/corpus JPEGs; skipping JPEG corpus test") + return + } + for (sample in samples) { + val bytes = sample.readBytes() + assertTrue(JpegReader.matches(bytes), "${sample.name}: detected as JPEG by magic") + val decoded = JpegReader.read(bytes) + assertTrue(decoded.width > 0 && decoded.height > 0, "${sample.name}: positive dimensions") + assertEquals(decoded.width * decoded.height * 4, decoded.rgba.size, "${sample.name}: RGBA buffer sized to the image") + println("decoded ${sample.name}: ${decoded.width}x${decoded.height}") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/kra/KraReaderTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/kra/KraReaderTest.kt new file mode 100644 index 0000000..bbd2d54 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/kra/KraReaderTest.kt @@ -0,0 +1,113 @@ +package org.umamo.format.kra + +import org.umamo.format.art.isEffectivelyVisible +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * End-to-end reader test against a real .kra. Corpus-gated: it uses -Dkra.sample= when given, + * else auto-discovers a sample under test/corpus/krita/ by walking up from the working directory; if + * neither is present it self-skips so CI stays green without a committed corpus. + * + * Asserts the structural invariants that matter to the render and re-import paths: a positive canvas + * size, at least one decoded paint layer, every layer's RGBA buffer sized to its bounds, stable + * non-blank ids, and some actual pixel content. + */ +class KraReaderTest { + /** + * Locates every KRA sample: `-Dkra.sample` when set, else every `.kra` under `test/corpus/krita`. + * + * @return List The samples, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("kra.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus/krita") + if (corpus.isDirectory) { + return corpus.listFiles { file -> file.extension.equals("kra", ignoreCase = true) } + ?.sortedBy { it.name } ?: emptyList() + } + directory = directory.parentFile + } + return emptyList() + } + + @Test + fun readsLayersFromRealKra() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no kra.sample and no test/corpus/krita samples; skipping KRA reader test") + return + } + for (sample in samples) { + checkSample(sample) + } + } + + /** + * Asserts the reader's structural invariants for one sample. + * + * @param File sample The `.kra` to read. + */ + private fun checkSample(sample: File) { + val bytes = sample.readBytes() + // Asserting detection here is the regression guard for the magic check: KraReader once scanned + // for "application/x-kra" (the maindoc.xml value) instead of the mimetype entry's + // "application/x-krita", so it rejected every real .kra while the synthetic registry fixture, + // built from the same wrong string, still passed. + assertTrue(KraReader.matches(bytes), "${sample.name}: detected as KRA by magic") + val art = KraReader.read(bytes) + + assertTrue(art.widthPx > 0 && art.heightPx > 0, "${sample.name}: positive canvas size") + assertTrue(art.layers.isNotEmpty(), "${sample.name}: at least one paint layer") + + for (layer in art.layers) { + assertTrue(layer.id.raw.isNotBlank(), "${sample.name}: layer '${layer.name}' has a stable id") + assertTrue( + layer.bounds.width > 0 && layer.bounds.height > 0, + "${sample.name}: layer '${layer.name}' has positive bounds", + ) + assertTrue( + layer.raster.rgba.size == layer.raster.width * layer.raster.height * 4, + "${sample.name}: layer '${layer.name}' raster sized to its dimensions", + ) + } + + // At least one layer should carry visible pixels (a non-zero alpha somewhere) - proves the + // tile, LZF, and color pipeline actually produced content, not just transparent placeholders. + val anyVisible = + art.layers.any { layer -> + var hasAlpha = false + var byteIndex = 3 + while (byteIndex < layer.raster.rgba.size) { + if (layer.raster.rgba[byteIndex].toInt() != 0) { + hasAlpha = true + break + } + byteIndex += 4 + } + hasAlpha + } + assertTrue(anyVisible, "${sample.name}: at least one layer has non-transparent pixels") + + // Group surfacing: every emitted folder has a non-blank path, and every layer that claims an + // enclosing folder resolves to one - proving the group list and groupPath wiring stay aligned. + val groupPaths = art.groups.map { group -> group.path }.toSet() + for (group in art.groups) { + assertTrue(group.path.isNotBlank(), "${sample.name}: group '${group.name}' has a path") + } + for (layer in art.layers) { + assertTrue( + layer.groupPath.isEmpty() || layer.groupPath in groupPaths, + "${sample.name}: layer '${layer.name}' groupPath '${layer.groupPath}' resolves to a group", + ) + // The cascade helper must run cleanly over real data (no path/parse surprises). + art.isEffectivelyVisible(layer) + } + println("checked ${sample.name}: ${art.widthPx}x${art.heightPx}, ${art.layers.size} layers, ${art.groups.size} groups") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/BlendEncodeProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/BlendEncodeProbeTest.kt new file mode 100644 index 0000000..83b4de3 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/BlendEncodeProbeTest.kt @@ -0,0 +1,68 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import java.io.File +import kotlin.test.Test + +/** + * The BLENDSHAPE_PARAMETER_BEGIN value for binding-less parameters, and the ordering of the color + * tables' blend delta region (which carries authored nonzero color morphs on Model A/C). + */ +class BlendEncodeProbeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + @Test + fun probeParameterBeginAndColorDeltaOrder() { + val samples = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + .orEmpty() + .filter { file -> listOf("modelA", "modelB", "modelC").any { prefix -> file.name.startsWith(prefix) } } + if (samples.isEmpty()) { + println("moc3.samples not present; skipping encode probe") + return + } + for (file in samples) { + val model = MocCodec.read(file.readBytes()) + val document = Moc3.decode(model) + val sections = model.sections + val parameterBegin = sections.intArray(Section.BLENDSHAPE_PARAMETER_BEGIN) + val parameterCount = sections.intArray(Section.BLENDSHAPE_PARAMETER_COUNT) + println("[encode-probe] ${file.name} 115=${parameterBegin.toList()}") + println("[encode-probe] ${file.name} 116=${parameterCount.toList()}") + + // Nonzero color delta rows: row index (from the delta region start) -> channel values. + val multiplyRed = sections.floatArray(Section.COLOR_MULTIPLY_R) + val screenRed = sections.floatArray(Section.COLOR_SCREEN_R) + val recordKeyTotalNoParts = + document.blendShapes.filter { it.target != org.umamo.format.moc3.model.BlendShapeTarget.PART } + .sumOf { it.keyPositions.size } + val deltaStart = multiplyRed.size - recordKeyTotalNoParts + val nonZeroMultiply = + (deltaStart until multiplyRed.size).filter { rowIndex -> multiplyRed[rowIndex] != 0f } + .map { rowIndex -> rowIndex - deltaStart } + val nonZeroScreen = + (deltaStart until screenRed.size).filter { rowIndex -> screenRed[rowIndex] != 0f } + .map { rowIndex -> rowIndex - deltaStart } + println("[encode-probe] ${file.name} deltaStart=$deltaStart nonzeroMultiplyRows=$nonZeroMultiply nonzeroScreenRows=$nonZeroScreen") + + // My assumed order: warp records, mesh records, rotation records (parts excluded); print + // each record's delta-row span under that assumption with its kind + target + parameter. + val warpRecords = document.blendShapes.filter { it.target == org.umamo.format.moc3.model.BlendShapeTarget.WARP } + val meshRecords = document.blendShapes.filter { it.target == org.umamo.format.moc3.model.BlendShapeTarget.ART_MESH } + val rotationRecords = document.blendShapes.filter { it.target == org.umamo.format.moc3.model.BlendShapeTarget.ROTATION } + var rowCursor = 0 + for (record in warpRecords + meshRecords + rotationRecords) { + val span = rowCursor until rowCursor + record.keyPositions.size + val interesting = (nonZeroMultiply + nonZeroScreen).any { it in span } + if (interesting) { + println( + "[encode-probe] ${file.name} span=$span kind=${record.target} target=${record.targetIndex} " + + "param=${document.parameters[record.parameterIndex].id} recordBase=${record.recordBase}", + ) + } + rowCursor += record.keyPositions.size + } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/JsonRoundTripTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/JsonRoundTripTest.kt new file mode 100644 index 0000000..b010ca2 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/JsonRoundTripTest.kt @@ -0,0 +1,41 @@ +package org.umamo.format.moc3 + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Exact-string round-trip of the JSON sidecar fixtures(via the `moc3.samples` property). + * Equality covers key order, tab indentation, and numeric-token fidelity. Skips + * gracefully when a given sidecar type has no fixture. + */ +class JsonRoundTripTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun fixtures(suffix: String): List = + samplesDir?.listFiles()?.filter { it.isFile && it.name.endsWith(suffix) }?.sortedBy { it.name } ?: emptyList() + + private fun checkRoundTrip(suffix: String, roundTrip: (String) -> String) { + val files = fixtures(suffix) + if (files.isEmpty()) { + println("no *$suffix fixtures present; skipping") + return + } + for (file in files) { + val text = file.readText(Charsets.UTF_8) + assertEquals(text, roundTrip(text), "${file.name}: exact-string round-trip") + } + } + + @Test + fun model3RoundTrips(): Unit = checkRoundTrip(".model3.json") { Moc3.writeModel3(Moc3.readModel3(it)) } + + @Test + fun physics3RoundTrips(): Unit = checkRoundTrip(".physics3.json") { Moc3.writePhysics3(Moc3.readPhysics3(it)) } + + @Test + fun cdi3RoundTrips(): Unit = checkRoundTrip(".cdi3.json") { Moc3.writeCdi3(Moc3.readCdi3(it)) } + + @Test + fun userData3RoundTrips(): Unit = checkRoundTrip(".userdata3.json") { Moc3.writeUserData3(Moc3.readUserData3(it)) } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocBakeFreshCoverageTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocBakeFreshCoverageTest.kt new file mode 100644 index 0000000..2462756 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocBakeFreshCoverageTest.kt @@ -0,0 +1,82 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Measures how much of a real file a reference-free bake can actually reproduce. + * + * [MocEncoder.bake] hides an unproduced section by carrying it from the source container, so nothing + * else notices the gap; [MocEncoder.bakeFresh] has nothing to carry from, and every index it cannot + * produce is emitted EMPTY. That is the difference between "we can edit a moc" and "we can write + * one", so the gap is tracked as a number rather than discovered later by a runtime that will not + * load the result. + * + * The expectation below is a ratchet, not a target: it names the sections no producer covers, and it + * is empty, so the gate fails the moment a fresh bake stops producing a section a corpus model carries. + * + * @see MOC3.md §5.6 + */ +class MocBakeFreshCoverageTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + /** + * The sections still carried rather than synthesized, corpus-wide. + * + * Empty, and that is the point: every section any corpus model carries is now produced by a fresh + * bake. An entry added here is a claim that some index cannot be derived - state which model shows + * it and why, because the last four entries all turned out to be derivable, and two of them + * (the parameter key runs, the offscreen alias) were load-breaking while they sat here. + */ + private val knownUnproduced = emptySet
() + + @Test + fun freshBakeCoversEverySectionExceptTheKnownGaps() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping fresh bake coverage test") + return + } + val missingOverall = LinkedHashSet() + var totalProduced = 0 + var totalPresent = 0 + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val document = Moc3.decode(model) + val produced = MocEncoder.bakeFreshCoverage(document) + val nameByIndex = + Section.entries + .mapNotNull { section -> section.indexIn(document.version).takeIf { it >= 0 }?.to(section) } + .toMap() + // Only sections the FILE actually carries count as a gap: an index a given model leaves empty + // needs nothing produced for it. + val presentIndices = (0 until model.sectionCount).filter { (model.section(it)?.size ?: 0) > 0 } + totalPresent += presentIndices.size + totalProduced += presentIndices.count { it in produced } + for (index in presentIndices) { + if (index !in produced) { + missingOverall.add(nameByIndex[index]?.name ?: "index $index") + } + } + } + assertEquals( + knownUnproduced.map { it.name }.toSortedSet(), + missingOverall.toSortedSet(), + "the set of unproduced sections changed", + ) + assertTrue(totalPresent > 0, "no sections were examined") + println( + "[fresh-coverage] $totalProduced/$totalPresent present sections synthesized across ${files.size} " + + "models; ${missingOverall.size} distinct sections still carried", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocBakeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocBakeTest.kt new file mode 100644 index 0000000..7c8f6cf --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocBakeTest.kt @@ -0,0 +1,84 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.moc.MocCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Serializer (bake-framing) self-consistency: re-frame each decoded model with [MocEncoder] and + * confirm a re-decode yields the identical semantic model. This validates the offset table / section + * ordering / alignment independent of the semantic lowering. Covers all three framings - the raw + * repack, the reference-carrying [Moc3.bake], and the reference-free [Moc3.write] that is the + * registered codec's own write. Baked files are also written to `build/moc3-bake/` for a manual + * runtime check. Skips gracefully without samples. + */ +class MocBakeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + @Test + fun repackRoundTripsSemanticModel() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping bake test") + return + } + // Build output, never beside the corpus. A `work/` that lands inside the samples tree is picked + // up by this test's OWN walkTopDown on the next run - which is how `baked-baked-*.moc3` came to + // exist - and by every other gate that walks the corpus for models. + val workDir = File("build/moc3-bake").apply { mkdirs() } + for (file in files) { + val original = MocCodec.read(file.readBytes()) + val baked = MocEncoder.repack(original) + + // The repack is a valid container our codec reads back to the same semantic model. + val before = Moc3.decode(original) + val after = Moc3.decode(MocCodec.read(baked)) + assertEquals(before.version, after.version, "${file.name}: version") + assertEquals(before.parameters, after.parameters, "${file.name}: parameters") + assertEquals(before.parts, after.parts, "${file.name}: parts") + assertEquals(before.deformers, after.deformers, "${file.name}: deformers") + assertEquals(before.artMeshes, after.artMeshes, "${file.name}: art meshes") + assertEquals(before.glues, after.glues, "${file.name}: glues") + assertEquals(before.renderOrderGroups, after.renderOrderGroups, "${file.name}: render-order groups") + assertEquals(before.blendShapes, after.blendShapes, "${file.name}: blend shapes") + assertEquals(before.offscreens, after.offscreens, "${file.name}: offscreens") + assertEquals(0, baked.size % 64, "${file.name}: baked file 64-aligned") + + workDir.resolve("baked-${file.name}").writeBytes(baked) + + // Full bake: synthesize sections from the (editable) document, carry the rest. Re-decode + // must reproduce the same semantic model, and the synthesized sections come from `before`. + val viaDocument = Moc3.bake(original, before) + val rebaked = Moc3.decode(MocCodec.read(viaDocument)) + assertEquals(before.parameters, rebaked.parameters, "${file.name}: bake parameters") + assertEquals(before.artMeshes, rebaked.artMeshes, "${file.name}: bake art meshes") + assertEquals(before.deformers, rebaked.deformers, "${file.name}: bake deformers") + assertEquals(before.parts, rebaked.parts, "${file.name}: bake parts") + assertEquals(before.glues, rebaked.glues, "${file.name}: bake glues") + assertEquals(before.blendShapes, rebaked.blendShapes, "${file.name}: bake blend shapes") + assertEquals(before.offscreens, rebaked.offscreens, "${file.name}: bake offscreens") + + // The registered codec's own tier: read - write - read is a semantic fixed point. That is the + // cycle a FormatRegistry caller gets, and unlike the bake above it holds no reference + // container - Moc3.write synthesizes every section from the document alone. + val viaCodec = Moc3.read(Moc3.write(before)) + assertEquals(before.version, viaCodec.version, "${file.name}: codec version") + assertEquals(before.parameters, viaCodec.parameters, "${file.name}: codec parameters") + assertEquals(before.parts, viaCodec.parts, "${file.name}: codec parts") + assertEquals(before.deformers, viaCodec.deformers, "${file.name}: codec deformers") + assertEquals(before.artMeshes, viaCodec.artMeshes, "${file.name}: codec art meshes") + assertEquals(before.glues, viaCodec.glues, "${file.name}: codec glues") + assertEquals(before.blendShapes, viaCodec.blendShapes, "${file.name}: codec blend shapes") + assertEquals(before.offscreens, viaCodec.offscreens, "${file.name}: codec offscreens") + + workDir.resolve("docbaked-${file.name}").writeBytes(viaDocument) + println("${file.name}: repack ${file.length()} -> ${baked.size}; doc-bake -> ${viaDocument.size} bytes, semantic model preserved") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocCountInfoConsistencyTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocCountInfoConsistencyTest.kt new file mode 100644 index 0000000..b82df00 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocCountInfoConsistencyTest.kt @@ -0,0 +1,205 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocLowering +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import org.umamo.format.moc3.moc.Sizing +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * CountInfo ↔ section-length self-consistency for the lowering's own output. + * + * Every CountInfo field sizes one or more sections, and the official runtime allocates from the field + * and then indexes into the section. A field that over-counts its section sends the runtime reading + * past the end of the buffer it just allocated - inside the official core that is a segfault, not a + * rejected file - and a field that under-counts silently truncates whatever addresses the tail. Both + * halves are produced by [MocLowering], from separate traversals of the same document, so nothing but + * this check makes them agree. + * + * Asserted against the SYNTHESIZED bytes rather than the corpus file's raw slices: a raw slice runs to + * the next section's offset and so includes alignment padding, which makes an exact length comparison + * impossible. The synthesized map holds element regions with no padding, and the lowering is + * byte-exact against the corpus (`MocLoweringTest`), so an identity proven here holds of the real + * editor-written files too. Skips gracefully without samples. + * + * @see MOC3.md §5.6 + */ +class MocCountInfoConsistencyTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + /** + * The CountInfo field sizing each per-object [Sizing] rule. Mirrors `MocSections.count`, spelled + * out here on purpose: a test that derived its expectation from the code under test would agree + * with any change to it. + */ + private val countFieldBySizing: Map = + mapOf( + Sizing.PER_PART to Sections.CI_PARTS, + Sizing.PER_DEFORMER to Sections.CI_DEFORMERS, + Sizing.PER_WARP to Sections.CI_WARPS, + Sizing.PER_ROTATION to Sections.CI_ROTATIONS, + Sizing.PER_DRAWABLE to Sections.CI_DRAWABLES, + Sizing.PER_PARAMETER to Sections.CI_PARAMETERS, + Sizing.PER_GLUE to Sections.CI_GLUES, + Sizing.PER_RENDER_ORDER_GROUP to Sections.CI_RENDER_ORDER_GROUPS, + Sizing.PER_RENDER_ORDER_CHILD to Sections.CI_RENDER_ORDER_CHILDREN, + Sizing.PER_OFFSCREEN to Sections.CI_OFFSCREENS, + Sizing.PER_BLENDSHAPE_WARP to Sections.CI_BLENDSHAPE_WARPS, + Sizing.PER_BLENDSHAPE_MESH to Sections.CI_BLENDSHAPE_MESHES, + Sizing.PER_BLENDSHAPE_ROTATION to Sections.CI_BLENDSHAPE_ROTATIONS, + Sizing.PER_BLENDSHAPE_PART to Sections.CI_BLENDSHAPE_PARTS, + Sizing.PER_BLENDSHAPE_GLUE to Sections.CI_BLENDSHAPE_GLUES, + Sizing.PER_PART_FORM to Sections.CI_PART_FORMS, + Sizing.PER_WARP_FORM to Sections.CI_WARP_FORMS, + Sizing.PER_ROTATION_FORM to Sections.CI_ROTATION_FORMS, + Sizing.PER_ARTMESH_FORM to Sections.CI_ARTMESH_FORMS, + Sizing.PER_OFFSCREEN_FORM to Sections.CI_OFFSCREEN_KEYFORMS, + ) + + /** + * The CountInfo field sizing each [Sizing.TABLE] section. A table section's element count comes + * from a CountInfo field rather than from its own sizing rule, so the pairing has to be written + * out. Sections absent here are unchecked and reported as such. + */ + private val countFieldByTableSection: Map = + mapOf( + Section.PART_DRAW_ORDER to Sections.CI_PART_FORMS, + Section.WARP_OPACITY to Sections.CI_WARP_FORMS, + Section.WARP_KEYFORM_INDEX to Sections.CI_WARP_FORMS, + Section.ROTATION_OPACITY to Sections.CI_ROTATION_FORMS, + Section.ROTATION_ANGLE to Sections.CI_ROTATION_FORMS, + Section.ROTATION_ORIGIN_X to Sections.CI_ROTATION_FORMS, + Section.ROTATION_ORIGIN_Y to Sections.CI_ROTATION_FORMS, + Section.ROTATION_SCALE to Sections.CI_ROTATION_FORMS, + Section.ROTATION_REFLECT_X to Sections.CI_ROTATION_FORMS, + Section.ROTATION_REFLECT_Y to Sections.CI_ROTATION_FORMS, + Section.ARTMESH_OPACITY to Sections.CI_ARTMESH_FORMS, + Section.ARTMESH_DRAW_ORDER to Sections.CI_ARTMESH_FORMS, + Section.KEYFORM_POSITION_INDEX to Sections.CI_ARTMESH_FORMS, + Section.KEYFORM_POSITION_VALUES to CI_POSITION_FLOATS, + Section.KEYFORM_BINDING_SLOT to CI_KEYFORM_BINDING_SLOTS, + Section.KEYFORM_BINDING_START to Sections.CI_KEYFORM_BINDINGS, + Section.KEYFORM_BINDING_COUNT to Sections.CI_KEYFORM_BINDINGS, + Section.BINDING_KEY_OFFSET to CI_PARAMETER_BINDINGS, + Section.BINDING_KEY_COUNT to CI_PARAMETER_BINDINGS, + Section.KEY_POSITIONS to CI_KEY_POSITIONS, + Section.ARTMESH_UV_DATA to CI_UV_FLOATS, + Section.ARTMESH_INDEX_DATA to CI_TRIANGLE_INDICES, + Section.MASK_INDEX_DATA to CI_MASK_INDICES, + Section.RENDER_ORDER_CHILD_KIND to Sections.CI_RENDER_ORDER_CHILDREN, + Section.RENDER_ORDER_CHILD_INDEX to Sections.CI_RENDER_ORDER_CHILDREN, + Section.RENDER_ORDER_GROUP_INDEX to Sections.CI_RENDER_ORDER_CHILDREN, + Section.GLUE_WEIGHTS to CI_GLUE_VERTICES, + Section.GLUE_VERTEX_INDICES to CI_GLUE_VERTICES, + Section.GLUE_INTENSITIES to CI_GLUE_INTENSITIES, + Section.COLOR_MULTIPLY_R to CI_COLOR_MULTIPLY_ROWS, + Section.COLOR_MULTIPLY_G to CI_COLOR_MULTIPLY_ROWS, + Section.COLOR_MULTIPLY_B to CI_COLOR_MULTIPLY_ROWS, + Section.COLOR_SCREEN_R to CI_COLOR_SCREEN_ROWS, + Section.COLOR_SCREEN_G to CI_COLOR_SCREEN_ROWS, + Section.COLOR_SCREEN_B to CI_COLOR_SCREEN_ROWS, + Section.BLENDSHAPE_BINDING_KEY_OFFSET to CI_BLENDSHAPE_BINDINGS, + Section.BLENDSHAPE_BINDING_KEY_COUNT to CI_BLENDSHAPE_BINDINGS, + Section.BLENDSHAPE_BINDING_NEUTRAL to CI_BLENDSHAPE_BINDINGS, + Section.BLENDSHAPE_RECORD_BINDING to CI_BLENDSHAPE_RECORDS, + Section.BLENDSHAPE_RECORD_BASE to CI_BLENDSHAPE_RECORDS, + Section.BLENDSHAPE_RECORD_SUBSTART to CI_BLENDSHAPE_RECORDS, + Section.BLENDSHAPE_RECORD_CORNER_COUNT to CI_BLENDSHAPE_RECORDS, + Section.BLENDSHAPE_RECORD_KEY_COUNT to CI_BLENDSHAPE_RECORDS, + Section.BLENDSHAPE_SUB_INDEX to Sections.CI_BLENDSHAPE_SUB_CORNERS, + Section.BLENDSHAPE_SUB_PARAMETER to Sections.CI_BLENDSHAPE_SUB_BINDINGS, + Section.BLENDSHAPE_SUB_KEY_OFFSET to Sections.CI_BLENDSHAPE_SUB_BINDINGS, + Section.BLENDSHAPE_SUB_KEY_COUNT to Sections.CI_BLENDSHAPE_SUB_BINDINGS, + Section.BLENDSHAPE_SUB_KEYS to CI_BLENDSHAPE_SUB_KEYS, + Section.BLENDSHAPE_SUB_WEIGHT_VALUES to CI_BLENDSHAPE_SUB_KEYS, + Section.OFFSCREEN_OPACITY to Sections.CI_OFFSCREEN_KEYFORMS, + Section.OFFSCREEN_KEYFORM_MULTIPLY_ROW to Sections.CI_OFFSCREEN_KEYFORMS, + Section.OFFSCREEN_KEYFORM_SCREEN_ROW to Sections.CI_OFFSCREEN_KEYFORMS, + ) + + @Test + fun countInfoFieldsMatchTheSectionsTheySize() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping CountInfo consistency test") + return + } + val failures = ArrayList() + val uncheckedTableSections = sortedSetOf() + var checkedTotal = 0 + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val doc = Moc3.decode(model) + val version = doc.version + val lowered = MocLowering.lower(doc) + val countInfoBytes = lowered.getValue(Section.COUNT_INFO.indexIn(version)) + val countInfoReader = LittleEndianReader(countInfoBytes) + val countInfo = IntArray(countInfoBytes.size / 4) { countInfoReader.readInt32() } + + for (section in Section.entries) { + val index = section.indexIn(version) + if (index < 0) { + continue + } + val bytes = lowered[index] ?: continue + val countField = + if (section.sizing == Sizing.TABLE) { + countFieldByTableSection[section] + } else { + countFieldBySizing[section.sizing] + } + if (countField == null) { + uncheckedTableSections.add(section.name) + continue + } + val declaredCount = countInfo.getOrElse(countField) { 0 } + val expectedBytes = declaredCount * section.element.size + checkedTotal++ + if (bytes.size != expectedBytes) { + failures.add( + "${file.name}: ${section.name}@$index is ${bytes.size} bytes but CountInfo[$countField]" + + " declares $declaredCount × ${section.element.size} = $expectedBytes", + ) + } + } + } + if (uncheckedTableSections.isNotEmpty()) { + println("[countinfo] table sections with no CountInfo pairing (unchecked): $uncheckedTableSections") + } + println("[countinfo] ${files.size} models, $checkedTotal section/field identities checked") + failures.forEach { failureMessage -> println("[countinfo] FAIL $failureMessage") } + assertTrue(failures.isEmpty(), "CountInfo disagrees with the sections it sizes:\n" + failures.joinToString("\n")) + // A gate that checks nothing passes. The corpus produces ~100 sized sections per model, so a + // collapse to a handful means the lowering stopped producing, not that the identities improved. + assertTrue( + checkedTotal > 50 * files.size, + "CountInfo consistency covered only $checkedTotal identities across ${files.size} models", + ) + } + + private companion object { + // CountInfo fields with no `Sections.CI_*` constant yet; see MOC3.md §5.6 section 0. + const val CI_POSITION_FLOATS: Int = 10 + const val CI_KEYFORM_BINDING_SLOTS: Int = 11 + const val CI_PARAMETER_BINDINGS: Int = 13 + const val CI_KEY_POSITIONS: Int = 14 + const val CI_UV_FLOATS: Int = 15 + const val CI_TRIANGLE_INDICES: Int = 16 + const val CI_MASK_INDICES: Int = 17 + const val CI_GLUE_VERTICES: Int = 21 + const val CI_GLUE_INTENSITIES: Int = 22 + const val CI_COLOR_MULTIPLY_ROWS: Int = 23 + const val CI_COLOR_SCREEN_ROWS: Int = 24 + const val CI_BLENDSHAPE_BINDINGS: Int = 25 + const val CI_BLENDSHAPE_RECORDS: Int = 26 + const val CI_BLENDSHAPE_SUB_KEYS: Int = 31 + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocDecodeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocDecodeTest.kt new file mode 100644 index 0000000..b8d3757 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocDecodeTest.kt @@ -0,0 +1,347 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Decode (Layer-2) internal-consistency checks: decoding exercises every base/grid index path, so a + * clean run already proves the keyform-binding grid + value-table arithmetic stays in bounds; the + * assertions then tie object/keyform shapes together. Skips gracefully without samples. + */ +class MocDecodeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + /** + * Pins which blend-free v1/v3 samples carry the optional KEY_POSITIONS per-parameter union region + * (MOC3 §5.6 - an editor-version artifact the decoder records as `keyPositionsHasParameterUnion`). + * Catches a detector regression independently of MocLoweringTest's byte-exact reproduction. A + * blend model always carries the region unconditionally, so the flag is left false there (gated). + */ + @Test + fun keyPositionsUnionRegionFlagPinned() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping union-region flag test") + return + } + // The only corpus samples that append the union region; every other file (including all blend + // models) omits it. Probed across the corpus - byte-identical section tables split both ways. + val carriesUnion = setOf("modelD.moc3", "miku_verycursed.moc3") + for (file in files) { + val doc = Moc3.decode(MocCodec.read(file.readBytes())) + assertEquals( + file.name in carriesUnion, + doc.keyPositionsHasParameterUnion, + "${file.name}: keyPositionsHasParameterUnion", + ) + if (doc.blendShapes.isNotEmpty()) { + assertTrue(!doc.keyPositionsHasParameterUnion, "${file.name}: flag stays false on a blend model") + } + } + } + + @Test + fun decodesSamplesConsistently() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping decode test") + return + } + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val doc = Moc3.decode(model) + val v4plus = model.versionByte >= MocVersion.V42.byteValue + + // Counts line up with CountInfo / the structural layer. + assertEquals(model.parameterCount, doc.parameters.size, "${file.name}: parameters") + assertEquals(model.partCount, doc.parts.size, "${file.name}: parts") + assertEquals(model.deformerCount, doc.deformers.size, "${file.name}: deformers") + assertEquals(model.drawableCount, doc.artMeshes.size, "${file.name}: art meshes") + assertEquals( + model.countInfo[Sections.CI_WARPS], + doc.deformers.count { it is WarpDeformer }, + "${file.name}: warps", + ) + assertEquals( + model.countInfo[Sections.CI_ROTATIONS], + doc.deformers.count { it is RotationDeformer }, + "${file.name}: rotations", + ) + + // Keyform-binding axes are well-formed: parameters in range, keys ascending. + for (binding in doc.bindings) { + for (axis in binding.axes) { + assertTrue( + axis.parameterIndex in doc.parameters.indices, + "${file.name}: binding ${binding.index} param index", + ) + assertTrue(axis.keyCount > 0, "${file.name}: binding ${binding.index} has keys") + assertTrue( + (1 until axis.keyCount).all { axis.keyPositions[it - 1] <= axis.keyPositions[it] }, + "${file.name}: binding ${binding.index} keys ascending", + ) + } + } + + // Art meshes: keyform count == binding grid; each keyform's geometry matches the topology. + for (mesh in doc.artMeshes) { + val grid = doc.keyformBinding(mesh.keyformBindingIndex)?.gridSize ?: 1 + assertEquals(grid, mesh.keyforms.size, "${file.name}: ${mesh.id} keyform count == grid") + assertEquals(mesh.vertexCount * 2, mesh.vertexUvs.size, "${file.name}: ${mesh.id} uv size") + assertTrue( + mesh.triangleIndices.all { (it.toInt() and 0xFFFF) < mesh.vertexCount }, + "${file.name}: ${mesh.id} triangle indices in range", + ) + assertTrue( + mesh.parentDeformerIndex == -1 || mesh.parentDeformerIndex in doc.deformers.indices, + "${file.name}: ${mesh.id} parent deformer", + ) + for (keyform in mesh.keyforms) { + assertEquals( + mesh.vertexCount * 2, + keyform.vertexPositions.size, + "${file.name}: ${mesh.id} keyform vertex count", + ) + assertEquals( + v4plus, + keyform.multiplyColor != null, + "${file.name}: ${mesh.id} color present iff v4+", + ) + } + } + + // Warp keyforms have the right control-point lattice size, and the block's common head + // lands on the right deformer - the decode walks the unified list while the geometry comes + // from the per-type sections, so a head field is the place an index slip would show up. + val deformerIds = model.sections.idArray(Section.DEFORMER_ID) + val deformerParentParts = model.sections.intArray(Section.DEFORMER_PARENT_PART) + for ((deformerIndex, deformer) in doc.deformers.withIndex()) { + if (deformer is WarpDeformer) { + val cp = (deformer.rows + 1) * (deformer.columns + 1) * 2 + deformer.keyforms.forEach { assertEquals(cp, it.controlPoints.size, "${file.name}: warp cp size") } + } + assertTrue( + deformer.parentDeformerIndex == -1 || deformer.parentDeformerIndex in doc.deformers.indices, + "${file.name}: deformer parent", + ) + assertEquals(deformerIds[deformerIndex], deformer.id, "${file.name}: deformer $deformerIndex id") + assertEquals( + deformerParentParts[deformerIndex], + deformer.parentPartIndex, + "${file.name}: deformer ${deformer.id} parent part", + ) + assertTrue( + deformer.parentPartIndex == -1 || deformer.parentPartIndex in doc.parts.indices, + "${file.name}: deformer ${deformer.id} parent part in range", + ) + } + + // Glue pairs reference valid vertices of their meshes. + for (glue in doc.glues) { + val meshA = doc.artMeshes[glue.meshAIndex] + val meshB = doc.artMeshes[glue.meshBIndex] + for (pair in glue.pairs) { + assertTrue( + pair.vertexA < meshA.vertexCount && pair.vertexB < meshB.vertexCount, + "${file.name}: glue pair in range", + ) + } + // Every glue's binding resolves through the shared cache - the decoder registers glue + // bindings like every other object kind, so a glue-exclusive binding keeps its + // parameter-driven intensity downstream and its table rows in a re-bake. + assertTrue( + doc.keyformBinding(glue.keyformBindingIndex) != null, + "${file.name}: glue binding ${glue.keyformBindingIndex} registered", + ) + } + + val totalChildren = doc.renderOrderGroups.sumOf { it.children.size } + assertEquals( + model.countInfo[Sections.CI_RENDER_ORDER_CHILDREN], + totalChildren, + "${file.name}: render-order children", + ) + + // Offscreens (moc 6): owner part in range. + assertEquals( + model.countInfo.getOrElse(Sections.CI_OFFSCREENS) { 0 }, + doc.offscreens.size, + "${file.name}: offscreen count", + ) + doc.offscreens.forEach { + assertTrue( + it.ownerPartIndex in doc.parts.indices, + "${file.name}: offscreen owner part", + ) + } + + // Blend shapes (moc 4+): drivers and targets in range, keys ascending, neutral valid. + for (bs in doc.blendShapes) { + assertTrue(bs.parameterIndex in doc.parameters.indices, "${file.name}: blendshape parameter") + assertTrue( + bs.keyPositions.isNotEmpty() && bs.neutralKeyIndex in bs.keyPositions.indices, + "${file.name}: blendshape neutral", + ) + assertTrue( + (1 until bs.keyPositions.size).all { bs.keyPositions[it - 1] <= bs.keyPositions[it] }, + "${file.name}: blendshape keys ascending", + ) + val targetOk = + when (bs.target) { + org.umamo.format.moc3.model.BlendShapeTarget.ART_MESH -> bs.targetIndex in doc.artMeshes.indices + org.umamo.format.moc3.model.BlendShapeTarget.PART -> bs.targetIndex in doc.parts.indices + else -> bs.targetIndex in doc.deformers.indices + } + assertTrue(targetOk, "${file.name}: blendshape target ${bs.target} ${bs.targetIndex}") + for (limit in bs.limits) { + assertTrue(limit.parameterIndex in doc.parameters.indices, "${file.name}: limit parameter") + assertTrue( + limit.keyPositions.toList() == limit.keyPositions.toList().sorted(), + "${file.name}: limit keys ascending", + ) + assertEquals(limit.keyPositions.size, limit.weights.size, "${file.name}: limit weights parallel") + } + + // Typed delta payloads: one keyform per key, kind matching the target, and the + // neutral key's row all-zero (MOC3 §5.6: deltas are relative to the neutral). + assertEquals(bs.keyPositions.size, bs.keyforms.size, "${file.name}: blendshape keyforms parallel keys") + val kindMatches = + bs.keyforms.all { keyform -> + when (bs.target) { + org.umamo.format.moc3.model.BlendShapeTarget.WARP -> keyform is BlendShapeKeyform.Warp + org.umamo.format.moc3.model.BlendShapeTarget.ART_MESH -> keyform is BlendShapeKeyform.Mesh + org.umamo.format.moc3.model.BlendShapeTarget.ROTATION -> keyform is BlendShapeKeyform.Rotation + org.umamo.format.moc3.model.BlendShapeTarget.PART -> keyform is BlendShapeKeyform.Part + } + } + assertTrue(kindMatches, "${file.name}: blendshape keyform kinds match ${bs.target}") + when (val neutralKeyform = bs.keyforms[bs.neutralKeyIndex]) { + is BlendShapeKeyform.Mesh -> { + assertTrue( + neutralKeyform.form.vertexPositions.all { it == 0f }, + "${file.name}: neutral mesh delta zero", + ) + assertEquals(0f, neutralKeyform.form.opacity, "${file.name}: neutral mesh opacity delta") + assertEquals(0f, neutralKeyform.form.drawOrder, "${file.name}: neutral mesh draw-order delta") + // Color delta rows follow the same neutral-zero rule; this also pins the + // delta-region anchoring in the shared color tables (MOC3 §5.6). + neutralKeyform.form.multiplyColor?.let { neutralMultiply -> + assertTrue( + neutralMultiply.r == 0f && neutralMultiply.g == 0f && neutralMultiply.b == 0f, + "${file.name}: neutral mesh multiply-color delta zero (got $neutralMultiply)", + ) + } + neutralKeyform.form.screenColor?.let { neutralScreen -> + assertTrue( + neutralScreen.r == 0f && neutralScreen.g == 0f && neutralScreen.b == 0f, + "${file.name}: neutral mesh screen-color delta zero (got $neutralScreen)", + ) + } + } + is BlendShapeKeyform.Warp -> { + assertTrue( + neutralKeyform.form.controlPoints.all { it == 0f }, + "${file.name}: neutral warp delta zero", + ) + assertEquals(0f, neutralKeyform.form.opacity, "${file.name}: neutral warp opacity delta") + } + is BlendShapeKeyform.Rotation -> { + assertEquals(0f, neutralKeyform.form.originX, "${file.name}: neutral rotation origin-x delta") + assertEquals(0f, neutralKeyform.form.originY, "${file.name}: neutral rotation origin-y delta") + assertEquals(0f, neutralKeyform.form.angle, "${file.name}: neutral rotation angle delta") + assertEquals(0f, neutralKeyform.form.scale, "${file.name}: neutral rotation scale delta") + assertEquals(0f, neutralKeyform.form.opacity, "${file.name}: neutral rotation opacity delta") + } + is BlendShapeKeyform.Part -> { + assertEquals(0f, neutralKeyform.drawOrderDelta, "${file.name}: neutral part draw-order delta") + } + } + } + + val limitAttachments = doc.blendShapes.sumOf { it.limits.size } + val distinctLimits = doc.blendShapes.flatMap { it.limits }.distinct().size + println( + "${file.name}: v${model.versionByte} params=${doc.parameters.size} parts=${doc.parts.size} deformers=${doc.deformers.size} meshes=${doc.artMeshes.size} glues=${doc.glues.size} groups=${doc.renderOrderGroups.size} bindings=${doc.bindings.size} blendShapes=${doc.blendShapes.size} limits=$limitAttachments/$distinctLimits offscreens=${doc.offscreens.size}", + ) + + // Golden anchors for the blend-shape corpus models. + val deltaKeyformTotal = doc.blendShapes.sumOf { it.keyforms.size } + + /** + * Sums the delta keyforms of the records targeting [target]. + * + * @param org.umamo.format.moc3.model.BlendShapeTarget target The record kind to total. + * @return Int The delta-keyform count over that kind's records. + */ + fun deltaKeyformsOf(target: org.umamo.format.moc3.model.BlendShapeTarget): Int = + doc.blendShapes.filter { it.target == target }.sumOf { it.keyforms.size } + if (file.name.startsWith("modelA")) { + assertEquals(60, doc.blendShapes.size, "Model A: blend-shape records") + assertEquals(0, limitAttachments, "Model A: no blend-weight limits") + assertEquals(178, deltaKeyformTotal, "Model A: delta keyforms") + assertEquals(142, deltaKeyformsOf(org.umamo.format.moc3.model.BlendShapeTarget.WARP), "Model A: warp delta keyforms") + assertEquals(24, deltaKeyformsOf(org.umamo.format.moc3.model.BlendShapeTarget.ART_MESH), "Model A: mesh delta keyforms") + assertEquals(12, deltaKeyformsOf(org.umamo.format.moc3.model.BlendShapeTarget.ROTATION), "Model A: rotation delta keyforms") + } + if (file.name.startsWith("modelB")) { + assertEquals(45, doc.blendShapes.size, "Model B: blend-shape records") + assertEquals(44, limitAttachments, "Model B: limit attachments") + assertEquals(1, distinctLimits, "Model B: one deduplicated limit curve") + assertEquals(90, deltaKeyformTotal, "Model B: delta keyforms") + } + if (file.name.startsWith("Azxiana")) { + // A 4.2-era bake: blend shapes present, but the color tables carry NO blend delta + // region (its CountInfo 23/24 count base rows only), so every record keyform must + // decode null colors rather than read past the tables' end. + assertEquals(20, doc.blendShapes.size, "Azxiana: blend-shape records") + val hasDeltaColor = + doc.blendShapes.any { blend -> + blend.keyforms.any { keyform -> + when (keyform) { + is BlendShapeKeyform.Warp -> keyform.form.multiplyColor != null + is BlendShapeKeyform.Mesh -> keyform.form.multiplyColor != null + is BlendShapeKeyform.Rotation -> keyform.form.multiplyColor != null + is BlendShapeKeyform.Part -> false + } + } + } + assertEquals(false, hasDeltaColor, "Azxiana: V42 bake carries no color delta region") + } + if (file.name.startsWith("modelA")) { + // The delta region IS present on the 5.x bakes: keyform colors decode non-null + // (zeros where unauthored), the counterpart of the Azxiana absence anchor. + val meshKeyform = + doc.blendShapes.first { it.target == org.umamo.format.moc3.model.BlendShapeTarget.ART_MESH } + .keyforms.filterIsInstance().first() + assertEquals(true, meshKeyform.form.multiplyColor != null, "Model A: color delta region present") + } + if (file.name.startsWith("modelC")) { + assertEquals(124, doc.blendShapes.size, "Model C: blend-shape records (incl. 1 part-owned)") + assertEquals(1, doc.blendShapes.count { it.target == org.umamo.format.moc3.model.BlendShapeTarget.PART }, "Model C: part records") + assertEquals(234, limitAttachments, "Model C: limit attachments") + assertEquals(7, distinctLimits, "Model C: deduplicated limit curves") + assertEquals(270, deltaKeyformTotal, "Model C: delta keyforms") + // The single part-owned record's typed payload (MOC3 §5.6 section 58 delta rows). + val partRecord = doc.blendShapes.first { it.target == org.umamo.format.moc3.model.BlendShapeTarget.PART } + assertEquals( + listOf(BlendShapeKeyform.Part(-900f), BlendShapeKeyform.Part(0f)), + partRecord.keyforms, + "Model C: part record delta payload", + ) + } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocDeformerBindingCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocDeformerBindingCorpusTest.kt new file mode 100644 index 0000000..d4c174a --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocDeformerBindingCorpusTest.kt @@ -0,0 +1,119 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Corpus gates for the duplicated deformer keyform binding: MOC3 §5.6 s12 (unified) against s19/s25 + * (per type). The official runtime might raise a MOC3 validation error when the two disagree, so this + * covers both directions - what the decoder takes on the way in, and what a bake emits on the way out. + * + * MocSectionsTest already pins the two RAW sections against each other in the source file. These + * two go further: the first pins the DECODER'S CHOICE (it takes the per-type value from s19/s25, + * leaving s12 read but unused) against s12, and the second pins the emitted bytes after a bake, + * which is the direction that can actually produce an unloadable file. + * + * @see MOC3.md §5.6 s12 + */ +class MocDeformerBindingCorpusTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + /** + * The value the decoder puts on each [org.umamo.format.moc3.model.Deformer] comes from the per-type + * section, so this is the assertion the unused s12 read in `MocDecoder` is positioned to make: the + * column it reads and the column it keeps carry the same binding for every deformer in the corpus. + */ + @Test + fun decodedKeyformBindingMatchesTheUnifiedSection() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping decoded deformer binding test") + return + } + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val document = Moc3.decode(model) + val unified = model.sections.intArray(Section.DEFORMER_KEYFORM_BINDING) + assertEquals(document.deformers.size, unified.size, "${file.name}: s12 covers every deformer") + for ((deformerIndex, deformer) in document.deformers.withIndex()) { + assertEquals( + unified[deformerIndex], + deformer.keyformBindingIndex, + "${file.name}: deformer $deformerIndex decoded binding matches s12", + ) + } + } + } + + /** + * A baked file must keep the two columns in agreement, because that is what makes it loadable. + * + * Note this is NOT implied by the decode-side gate: it would still hold if the lowering wrote the + * unified and per-type columns from separate walks, right up until one of those walks changed. A + * structurally edited document is the case that would break first, which is why the deformer list + * is reversed here - it permutes both the file order and every type-local index without inventing + * geometry, so the two columns can only stay aligned if they share one source. + */ + @Test + fun bakedKeyformBindingColumnsAgree() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping baked deformer binding test") + return + } + for (file in files) { + val original = MocCodec.read(file.readBytes()) + val document = Moc3.decode(original) + if (document.deformers.isEmpty()) { + continue + } + val reordered = + MocDocument( + version = document.version, + canvas = document.canvas, + parameters = document.parameters, + keyformBindings = document.bindings.associateBy { binding -> binding.index }, + parts = document.parts, + deformers = document.deformers.reversed(), + artMeshes = document.artMeshes, + glues = document.glues, + renderOrderGroups = document.renderOrderGroups, + blendShapes = document.blendShapes, + offscreens = document.offscreens, + keyPositionsHasParameterUnion = document.keyPositionsHasParameterUnion, + ) + val baked = MocCodec.read(Moc3.bake(original, reordered)) + val unified = baked.sections.intArray(Section.DEFORMER_KEYFORM_BINDING) + val warpBindings = baked.sections.intArray(Section.WARP_KEYFORM_BINDING) + val rotationBindings = baked.sections.intArray(Section.ROTATION_KEYFORM_BINDING) + val types = baked.sections.intArray(Section.DEFORMER_TYPE) + val localIndices = baked.sections.intArray(Section.DEFORMER_LOCAL_INDEX) + for (deformerIndex in reordered.deformers.indices) { + // Type 0 is a warp, anything else a rotation; the per-type column is addressed by s18. + val perType = + if (types[deformerIndex] == 0) { + warpBindings[localIndices[deformerIndex]] + } else { + rotationBindings[localIndices[deformerIndex]] + } + assertEquals( + reordered.deformers[deformerIndex].keyformBindingIndex, + unified[deformerIndex], + "${file.name}: baked deformer $deformerIndex s12 carries the document's binding", + ) + assertEquals( + unified[deformerIndex], + perType, + "${file.name}: baked deformer $deformerIndex s12 disagrees with its per-type column", + ) + } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocLoweringTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocLoweringTest.kt new file mode 100644 index 0000000..bc612bf --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocLoweringTest.kt @@ -0,0 +1,95 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocLowering +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Lowering validation: synthesizing a decoded [MocDocument]'s sections - structural, value tables, + * auxiliary, keyform grid, blend shapes, runtime slots, and derived indexes - reproduces the original + * section bytes exactly (decode → lower → byte-compare). This proves the object→bytes direction for + * those sections without the runtime. The offscreen per-part alias is the one exception, skipped + * below because it is an editor artifact no producer can derive. Skips gracefully without samples. + */ +class MocLoweringTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + @Test + fun structuralSectionsLowerByteExact() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping lowering test") + return + } + // Failures collect per file instead of aborting the loop, so one model's regression cannot + // mask (or be masked by) the others - the whole corpus, v1 through v6, lowers byte-exact. + val failures = ArrayList() + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val doc = Moc3.decode(model) + // `MocLowering.lower` merges the producers strictly - a section claimed by two of them throws + // there rather than resolving by merge order - so this test consumes the merged map directly + // and leaves producer disjointness to that production check. + val merged = MocLowering.lower(doc) + assertTrue(merged.isNotEmpty(), "${file.name}: lowered some sections") + + for ((index, bytes) in merged) { + if (index == Section.COUNT_INFO.indexIn(doc.version)) { + // Compared separately below, at the ORIGINAL's width rather than the synthesized one. + continue + } + if (index == Section.OFFSCREEN_BY_PART_ALIAS.indexIn(doc.version)) { + // Not byte-exact by design, and only on modelA: 160 carries a per-part offscreen map + // that disagrees with 152 there and matches no offscreen owner, so it is an editor + // artifact we cannot derive - see OffscreenSectionAliasProbeTest. The lowering writes + // the owner-consistent inverse instead, which is what makes the file loadable. + continue + } + val original = model.section(index) + if (original == null || original.size < bytes.size) { + failures.add("${file.name}: section $index present & sized (need ${bytes.size}, have ${original?.size})") + continue + } + if (!original.copyOf(bytes.size).contentEquals(bytes)) { + val firstMismatch = bytes.indices.first { original[it] != bytes[it] } + failures.add("${file.name}: section $index not byte-exact (first mismatch at byte $firstMismatch of ${bytes.size})") + continue + } + // Guard against silently dropping data: anything in the original beyond our synthesized + // element region must be zero padding (a synthesized section shorter than the original + // with a nonzero tail - e.g. blend-shape deltas appended to a shared value table - would + // be a truncation bug; such sections must be carried, not synthesized). + val tail = original.copyOfRange(bytes.size, original.size) + if (!tail.all { it.toInt() == 0 }) { + failures.add("${file.name}: section $index synthesized too short (nonzero tail dropped: ${tail.size} bytes)") + } + } + // Full CountInfo synthesis, including the blend-shape/offscreen totals (fields 23-36). + // Compared at the ORIGINAL's width, not the synthesized one: comparing only the synthesized + // prefix would let a too-narrow block pass while dropping the fields past its end (v5 carries + // 64 words and a rotation-blend model writes field 33, which a 32-word cap would lose). + val ci = merged.getValue(Section.COUNT_INFO.indexIn(doc.version)) + val originalCi = model.section(0)!! + if (!originalCi.contentEquals(ci)) { + val firstMismatch = + (0 until maxOf(originalCi.size, ci.size)).first { + originalCi.getOrNull(it) != ci.getOrNull(it) + } + failures.add( + "${file.name}: CountInfo not byte-exact (${ci.size} bytes vs ${originalCi.size}; " + + "first mismatch at byte $firstMismatch, field ${firstMismatch / 4})", + ) + } + println("${file.name}: v${model.versionByte} ${merged.size} sections lowered") + } + failures.forEach { failureMessage -> println("[lowering] FAIL $failureMessage") } + assertTrue(failures.isEmpty(), "lowering not byte-exact:\n" + failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocRoundTripTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocRoundTripTest.kt new file mode 100644 index 0000000..9197458 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocRoundTripTest.kt @@ -0,0 +1,80 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Byte-identical round-trip + typed-accessor checks against the real `.moc3` samples (resolved + * from the `moc3.samples` system property). Skips gracefully when the samples are absent, so a + * public checkout still passes. + */ +class MocRoundTripTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + @Test + fun samplesRoundTripByteIdentical() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping moc3 round-trip test") + return + } + for (file in files) { + val bytes = file.readBytes() + val model = MocCodec.read(bytes) + + assertTrue(MocCodec.isMoc3(bytes), "${file.name}: MOC3 magic") + assertTrue(model.versionByte in 1..6, "${file.name}: version byte ${model.versionByte}") + assertTrue(!model.isBigEndian, "${file.name}: little-endian") + assertEquals(0, model.offsets[0] % 64, "${file.name}: first section is 64-byte aligned") + assertEquals(0, bytes.size % 64, "${file.name}: file is 64-byte aligned") + + assertContentEquals(bytes, MocCodec.write(model), "${file.name}: byte-identical round-trip") + println("${file.name}: v${model.versionByte} sections=${model.sectionCount} params=${model.parameterCount} parts=${model.partCount} drawables=${model.drawableCount}") + } + } + + @Test + fun typedAccessorsAreConsistent() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping moc3 typed-accessor test") + return + } + for (file in files) { + val model = MocCodec.read(file.readBytes()) + + val canvas = model.canvasInfo + assertTrue(canvas != null && canvas.pixelsPerUnit > 0f, "${file.name}: canvas ppu") + + val parameters = model.parameters() + assertEquals(model.parameterCount, parameters.size, "${file.name}: parameter count") + for (parameter in parameters) { + assertTrue(parameter.id.isNotEmpty(), "${file.name}: parameter id present") + assertTrue( + parameter.minimumValue <= parameter.defaultValue && parameter.defaultValue <= parameter.maximumValue, + "${file.name}: ${parameter.id} min<=def<=max", + ) + } + + assertEquals(model.partCount, model.parts().size, "${file.name}: part count") + model.parts().forEach { assertTrue(it.id.isNotEmpty(), "${file.name}: part id present") } + + val drawables = model.drawables() + assertEquals(model.drawableCount, drawables.size, "${file.name}: drawable count") + for (drawable in drawables) { + assertTrue(drawable.id.isNotEmpty(), "${file.name}: drawable id present") + assertTrue(drawable.vertexCount > 0, "${file.name}: ${drawable.id} has vertices") + assertEquals(0, drawable.indexCount % 3, "${file.name}: ${drawable.id} index count is whole triangles") + assertTrue(drawable.textureIndex >= 0, "${file.name}: ${drawable.id} texture index") + } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocSectionsTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocSectionsTest.kt new file mode 100644 index 0000000..0919690 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocSectionsTest.kt @@ -0,0 +1,155 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Layer-1 typed-section decode: every present section re-encodes to its exact on-disk element + * region (lossless decode), plus structural invariants that tie sections to CountInfo and to each + * other (the deformer head columns, and the unified keyform binding against its per-type columns). + * Skips gracefully without samples. + */ +class MocSectionsTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + @Test + fun everyPresentSectionDecodesLosslessly() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping section decode test") + return + } + for (file in files) { + val model = MocCodec.read(file.readBytes()) + var checked = 0 + for (section in Section.entries) { + if (!model.sections.isPresent(section)) { + continue + } + assertContentEquals( + model.sections.rawElementRegion(section), + model.sections.reencodeElementRegion(section), + "${file.name}: $section lossless typed decode", + ) + checked++ + } + println("${file.name}: v${model.versionByte} decoded $checked/${Section.entries.size} sections losslessly") + } + } + + @Test + fun structuralInvariants() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping structural test") + return + } + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val sections = model.sections + val warps = model.countInfo[Sections.CI_WARPS] + val rotations = model.countInfo[Sections.CI_ROTATIONS] + val deformers = model.countInfo[Sections.CI_DEFORMERS] + + // Deformer type column splits into the CountInfo warp/rotation counts. + val types = sections.intArray(Section.DEFORMER_TYPE) + assertEquals(deformers, types.size, "${file.name}: deformer type count") + assertEquals(warps, types.count { it == 0 }, "${file.name}: warp count") + assertEquals(rotations, types.count { it == 1 }, "${file.name}: rotation count") + + // Parallel per-object arrays are sized by their CountInfo counts. + assertEquals(warps, sections.intArray(Section.WARP_ROWS).size, "${file.name}: warp rows") + assertEquals(warps, sections.intArray(Section.WARP_COLUMNS).size, "${file.name}: warp cols") + assertEquals( + rotations, + sections.floatArray(Section.ROTATION_BASE_ANGLE).size, + "${file.name}: rotation base angle", + ) + assertEquals( + model.drawableCount, + sections.intArray(Section.ARTMESH_PARENT_DEFORMER).size, + "${file.name}: artmesh parent deformer", + ) + assertEquals( + model.partCount, + sections.intArray(Section.PART_KEYFORM_BINDING).size, + "${file.name}: part keyform binding", + ) + assertEquals( + model.parameterCount, + sections.intArray(Section.PARAMETER_BINDING_COUNT).size, + "${file.name}: parameter binding count", + ) + + // Deformer parents are -1 (root) or a valid deformer index. + val parents = sections.intArray(Section.DEFORMER_PARENT) + assertTrue(parents.all { it == -1 || it in 0 until deformers }, "${file.name}: deformer parent range") + + // The deformer block's common head: one id per deformer (unique, like every other id + // column), flags that are strictly 0/1, and a part index in range. + val deformerIds = sections.idArray(Section.DEFORMER_ID) + assertEquals(deformers, deformerIds.size, "${file.name}: deformer id count") + assertEquals(deformerIds.size, deformerIds.toSet().size, "${file.name}: deformer ids unique") + assertTrue(deformerIds.none { it.isEmpty() }, "${file.name}: deformer ids non-empty") + for (flagSection in listOf(Section.DEFORMER_IS_VISIBLE, Section.DEFORMER_IS_ENABLED)) { + val flags = sections.intArray(flagSection) + assertEquals(deformers, flags.size, "${file.name}: $flagSection count") + assertTrue(flags.all { it == 0 || it == 1 }, "${file.name}: $flagSection is boolean") + } + val deformerParts = sections.intArray(Section.DEFORMER_PARENT_PART) + assertTrue( + deformerParts.all { it == -1 || it in 0 until model.partCount }, + "${file.name}: deformer parent part range", + ) + + // Section 12 is the same keyform binding the per-type sections carry, addressed by the + // deformer's type-local index - a reader may take either, so they must not drift. + val unifiedBinding = sections.intArray(Section.DEFORMER_KEYFORM_BINDING) + val warpBinding = sections.intArray(Section.WARP_KEYFORM_BINDING) + val rotationBinding = sections.intArray(Section.ROTATION_KEYFORM_BINDING) + val localIndex = sections.intArray(Section.DEFORMER_LOCAL_INDEX) + assertEquals(deformers, unifiedBinding.size, "${file.name}: deformer keyform binding count") + for (deformerIndex in 0 until deformers) { + val perType = + if (types[deformerIndex] == 0) { + warpBinding[localIndex[deformerIndex]] + } else { + rotationBinding[localIndex[deformerIndex]] + } + assertEquals( + perType, + unifiedBinding[deformerIndex], + "${file.name}: deformer $deformerIndex keyform binding matches its per-type section", + ) + } + + // Art-mesh keyform position base is a non-decreasing cumulative table. + val posBase = sections.intArray(Section.ARTMESH_KEYFORM_BASE) + assertTrue( + (1 until posBase.size).all { posBase[it - 1] <= posBase[it] }, + "${file.name}: keyform base monotonic", + ) + + // Version gating: color-base sections are v4+ only. Per-mesh, so a mesh-less model + // (the offscreen extraction family) has an empty region even on v6 - the invariant is + // v4+ AND at least one drawable. + val v4plus = model.versionByte >= MocVersion.V42.byteValue + assertEquals( + v4plus && model.drawableCount > 0, + sections.isPresent(Section.ARTMESH_COLOR_BASE), + "${file.name}: color base present iff v4+ with drawables", + ) + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocStructuralEditBakeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocStructuralEditBakeTest.kt new file mode 100644 index 0000000..a301389 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MocStructuralEditBakeTest.kt @@ -0,0 +1,122 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * A bake must survive a change to an OBJECT COUNT, not just to values. + * + * This is the case that was broken until CountInfo was synthesized rather than carried from the + * reference container: adding an object grew the per-object arrays while section 0 still declared the + * old count, so the re-decode either dropped the new object or read past an array it had just sized. + * Nothing else exercises it - the other bake tests re-bake a document with the SAME object counts, + * where a stale CountInfo happens to be correct. + * + * Parts are the vehicle because a part is the cheapest object to synthesize honestly: an id, a parent, + * a keyform binding, and one draw-order value per grid cell. Adding one moves CountInfo fields 0 + * (parts) and 6 (part forms) plus nine per-part sections, which is enough to catch a stale count. + * + * @see MOC3.md §5.1 + */ +class MocStructuralEditBakeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + /** + * Rebuilds [document] with [parts] substituted, leaving everything else identical. + * + * @param MocDocument document The decoded source. + * @param List parts The replacement part list. + * @return MocDocument The edited document. + */ + private fun withParts(document: MocDocument, parts: List): MocDocument = + MocDocument( + version = document.version, + canvas = document.canvas, + parameters = document.parameters, + keyformBindings = document.bindings.associateBy { binding -> binding.index }, + parts = parts, + deformers = document.deformers, + artMeshes = document.artMeshes, + glues = document.glues, + renderOrderGroups = document.renderOrderGroups, + blendShapes = document.blendShapes, + offscreens = document.offscreens, + keyPositionsHasParameterUnion = document.keyPositionsHasParameterUnion, + ) + + @Test + fun addingAPartKeepsCountInfoAndTheDecodeConsistent() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping structural edit bake test") + return + } + var exercised = 0 + val skippedForPartBlends = ArrayList() + for (file in files) { + val original = MocCodec.read(file.readBytes()) + val document = Moc3.decode(original) + val lastPart = document.parts.lastOrNull() ?: continue + + // KNOWN LIMITATION, not a property of this edit: a part-target blend record's delta rows are + // appended to the SAME part draw-order table (section 58) the main grid uses, and the record + // carries a `recordBase` into it. Adding a part inserts a main-grid row ahead of those + // deltas, so every stored base past the insertion point is off by one - and the base is + // carried on the decoded model rather than recomputed at bake time. Editing a model with + // part blend shapes therefore needs the blend layout re-derived, which is export-phase work. + // modelC is the only corpus sample with such a record. + if (document.blendShapes.any { it.target == org.umamo.format.moc3.model.BlendShapeTarget.PART }) { + skippedForPartBlends.add(file.name) + continue + } + // An appended ROOT part with the same binding as one that already works: its draw-order run + // simply extends section 58, and nothing else in the file refers to it by index. + val addedPart = lastPart.copy(id = "UmamoAddedPart", parentPartIndex = -1) + val edited = withParts(document, document.parts + addedPart) + + val baked = MocCodec.read(MocEncoder.bake(original, edited)) + val redecoded = Moc3.decode(baked) + + assertEquals( + document.parts.size + 1, + redecoded.parts.size, + "${file.name}: the added part survived the bake", + ) + assertEquals( + document.parts.size + 1, + baked.countInfo.getOrElse(Sections.CI_PARTS) { 0 }, + "${file.name}: CountInfo part count tracks the edit", + ) + assertEquals(edited.parts, redecoded.parts, "${file.name}: parts round-trip through the edit") + // Every per-part column must have grown with the list, or the runtime reads past one of them. + for (section in listOf(Section.PART_ID, Section.PART_PARENT, Section.PART_KEYFORM_BINDING)) { + assertEquals( + document.parts.size + 1, + baked.sections.elementCount(section), + "${file.name}: $section resized with the part list", + ) + } + // The edit must not disturb anything else - a stale count elsewhere shows up here first. + assertEquals(document.deformers, redecoded.deformers, "${file.name}: deformers unchanged") + assertEquals(document.artMeshes, redecoded.artMeshes, "${file.name}: art meshes unchanged") + assertEquals(document.blendShapes, redecoded.blendShapes, "${file.name}: blend shapes unchanged") + assertEquals(document.glues, redecoded.glues, "${file.name}: glues unchanged") + exercised++ + } + assertTrue(exercised > 0, "no corpus model had a part to duplicate") + println("[structural-edit] added a part to $exercised models; CountInfo and every per-part column tracked it") + if (skippedForPartBlends.isNotEmpty()) { + println("[structural-edit] skipped (part-target blend records index the table this edit shifts): $skippedForPartBlends") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MorphTargetJoinProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MorphTargetJoinProbeTest.kt new file mode 100644 index 0000000..5b0d2d3 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/MorphTargetJoinProbeTest.kt @@ -0,0 +1,360 @@ +package org.umamo.format.moc3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACDeformerSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CParameterSource +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CRotationDeformerSource +import org.umamo.format.cmo3.model.gen.CWarpDeformerSource +import org.umamo.format.cmo3.model.gen.KeyFormMorphTarget +import org.umamo.format.cmo3.model.gen.KeyFormMorphTargetSet +import org.umamo.format.cmo3.model.gen.Type +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.format.moc3.model.BlendShapeTarget +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Joins a CMO3's MorphTarget sets against the same model's baked MOC3 blend-shape records to + * pin down the derivation rules the ingest needs - how morph targets group into records, where + * the neutral key comes from, and whether a NORMAL-typed parameter can drive a morph target. + * + * The join is by id for art meshes and by document-order index for deformers - the index + * correspondence is itself one of the hypotheses this probe checks. Keyed on Model A's pair from + * `cmo3.probe` + `moc3.samples`; skips gracefully when either is absent. + */ +class MorphTargetJoinProbeTest { + private val modelACmo3: File? = + System.getProperty("cmo3.probe")?.split(',')?.map(::File) + ?.firstOrNull { it.isFile && it.name.startsWith("modelA") } + private val modelAMoc3: File? = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + ?.walkTopDown()?.firstOrNull { it.isFile && it.name == "modelA.moc3" } + + /** One CMO3 morph-target group: everything on one source driven by one parameter. */ + private data class MorphGroup( + val sourceKind: String, + val sourceId: String, + val sourceOrderIndex: Int, + val parameterId: String, + val parameterType: String, + val parameterDefault: Float, + val keyValues: List, + ) + + @Test + fun joinModelAMorphTargetsAgainstBakedRecords() { + val cmo3File = modelACmo3 + val moc3File = modelAMoc3 + if (cmo3File == null || moc3File == null) { + println("Model A corpus pair not present; skipping morph-target join probe") + return + } + val root = Cmo3.read(cmo3File).root as? CModelSource ?: error("root is not a CModelSource") + + val parameterSources = + elements((root.parameterSourceSet as? CParameterSourceSet)?._sources) + .filterIsInstance() + val parameterByUuid = + parameterSources.mapNotNull { source -> + val uuid = (source.guid as? Guid)?.uuid ?: return@mapNotNull null + uuid to source + }.toMap() + + val drawableSources = + elements((root.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + val deformerSources = + elements((root.deformerSourceSet as? CDeformerSourceSet)?._sources) + .filterIsInstance() + + /** + * Collects the morph-target groups on one controllable source. + * + * @param String kind The source kind label (mesh / warp / rotation). + * @param Any? morphSet The source's keyformMorphTargetSet. + * @param Any? sourceId The source's id object. + * @param Int orderIndex The source's document-order index within its kind. + * @return List One group per driving parameter. + */ + fun groupsOf(kind: String, morphSet: Any?, sourceId: Any?, orderIndex: Int): List { + val set = morphSet as? KeyFormMorphTargetSet ?: return emptyList() + val targets = elements(set._morphTargets).filterIsInstance() + if (targets.isEmpty()) { + return emptyList() + } + return targets.groupBy { (it.parameterGuid as? Guid)?.uuid }.mapNotNull { (uuid, group) -> + val parameter = uuid?.let(parameterByUuid::get) ?: return@mapNotNull null + MorphGroup( + sourceKind = kind, + sourceId = (sourceId as? Id)?.idstr ?: "?", + sourceOrderIndex = orderIndex, + parameterId = (parameter.id as? Id)?.idstr ?: "?", + parameterType = (parameter.paramType as? Type)?.name ?: "null", + parameterDefault = parameter.defaultValue, + keyValues = group.map { it.keyValue }.sorted(), + ) + } + } + + val meshGroups = + drawableSources.flatMapIndexed { index, source -> + groupsOf("mesh", source.keyformMorphTargetSet, source.id, index) + } + val warpGroups = + deformerSources.filterIsInstance().let { warps -> + warps.flatMapIndexed { index, source -> + groupsOf("warp", source.keyformMorphTargetSet, source.id, index) + } + } + val rotationGroups = + deformerSources.filterIsInstance().let { rotations -> + rotations.flatMapIndexed { index, source -> + groupsOf("rotation", source.keyformMorphTargetSet, source.id, index) + } + } + val allGroups = meshGroups + warpGroups + rotationGroups + + println("[probe] CMO3 morph groups: total=${allGroups.size} mesh=${meshGroups.size} warp=${warpGroups.size} rotation=${rotationGroups.size}") + println("[probe] CMO3 morph target records: ${allGroups.sumOf { it.keyValues.size }}") + + // E4: driving-parameter typing. + val drivingParams = allGroups.map { it.parameterId to it.parameterType }.distinct().sortedBy { it.first } + val morphTypedParams = + parameterSources.filter { (it.paramType as? Type) == Type.MORPH_TARGET } + .mapNotNull { (it.id as? Id)?.idstr } + println("[probe] E4: distinct driving params=${drivingParams.size}, MORPH_TARGET-typed params=${morphTypedParams.size}") + for ((parameterId, parameterType) in drivingParams) { + if (parameterType != "MORPH_TARGET") { + println("[probe] E4: driving param $parameterId has paramType=$parameterType") + } + } + val unusedMorphParams = morphTypedParams.toSet() - drivingParams.map { it.first }.toSet() + if (unusedMorphParams.isNotEmpty()) { + println("[probe] E4: MORPH_TARGET params driving nothing: $unusedMorphParams") + } + + // MOC3 side. + val document = Moc3.read(moc3File.readBytes()) + val records = document.blendShapes + val warpIndexToDeformer = document.deformers.withIndex().filter { it.value is org.umamo.format.moc3.model.WarpDeformer }.map { it.index } + val rotationIndexToDeformer = document.deformers.withIndex().filter { it.value is org.umamo.format.moc3.model.RotationDeformer }.map { it.index } + println("[probe] MOC3 records=${records.size} (params typed BLEND_SHAPE=${document.parameters.count { it.type == ParameterType.BLEND_SHAPE }})") + + // E3 join: meshes by id, deformers by document-order index within their kind. + var matched = 0 + var neutralAtDefault = 0 + var neutralInCmo3Keys = 0 + var keySetMatchesWithNeutralAdded = 0 + for (record in records) { + val parameterId = document.parameters[record.parameterIndex].id + val group = + when (record.target) { + BlendShapeTarget.PART -> null // part morph targets are not collected CMO3-side yet + BlendShapeTarget.ART_MESH -> + meshGroups.firstOrNull { it.sourceId == document.artMeshes[record.targetIndex].id && it.parameterId == parameterId } + BlendShapeTarget.WARP -> + warpGroups.firstOrNull { warpIndexToDeformer.getOrNull(it.sourceOrderIndex) == record.targetIndex && it.parameterId == parameterId } + BlendShapeTarget.ROTATION -> + rotationGroups.firstOrNull { rotationIndexToDeformer.getOrNull(it.sourceOrderIndex) == record.targetIndex && it.parameterId == parameterId } + } + val mocKeys = record.keyPositions.toList() + val neutralValue = record.keyPositions.getOrNull(record.neutralKeyIndex) + val parameterDefault = document.parameters[record.parameterIndex].defaultValue + if (group == null) { + println("[probe] UNMATCHED moc record: ${record.target} target=${record.targetIndex} param=$parameterId keys=$mocKeys neutral=$neutralValue") + continue + } + matched++ + if (neutralValue == parameterDefault) { + neutralAtDefault++ + } + if (group.keyValues.any { it == neutralValue }) { + neutralInCmo3Keys++ + } + if ((group.keyValues + listOfNotNull(neutralValue)).distinct().sorted() == mocKeys.distinct().sorted()) { + keySetMatchesWithNeutralAdded++ + } + println( + "[probe] ${record.target} ${group.sourceId} param=$parameterId cmo3Keys=${group.keyValues} " + + "mocKeys=$mocKeys neutralIdx=${record.neutralKeyIndex} neutralVal=$neutralValue default=$parameterDefault", + ) + } + println( + "[probe] E3 summary: records=${records.size} matched=$matched groups=${allGroups.size} " + + "neutralAtDefault=$neutralAtDefault neutralInCmo3Keys=$neutralInCmo3Keys keySetMatchesWithNeutralAdded=$keySetMatchesWithNeutralAdded", + ) + assertTrue(records.isNotEmpty(), "Model A's moc3 should carry blend-shape records") + assertTrue(allGroups.isNotEmpty(), "Model A's cmo3 should carry morph-target groups") + + // E3 rule, asserted independent of deformer identity (the order-index join above shows CMO3 + // and MOC3 deformer orders differ): as MULTISETS over (target kind, driving parameter, key + // positions), the CMO3 groups with the parameter default inserted as the neutral key equal + // the MOC3 records exactly. + val kindByLabel = mapOf("mesh" to "ART_MESH", "warp" to "WARP", "rotation" to "ROTATION") + val cmo3Multiset = + allGroups.map { group -> + val keysWithNeutral = (group.keyValues + group.parameterDefault).distinct().sorted() + Triple(kindByLabel.getValue(group.sourceKind), group.parameterId, keysWithNeutral) + }.groupingBy { it }.eachCount() + val mocMultiset = + records.map { record -> + Triple( + record.target.name, + document.parameters[record.parameterIndex].id, + record.keyPositions.toList().sorted(), + ) + }.groupingBy { it }.eachCount() + kotlin.test.assertEquals( + cmo3Multiset, + mocMultiset, + "E3 rule: moc keys = cmo3 keys + neutral inserted at the parameter default", + ) + for (record in records) { + kotlin.test.assertEquals( + document.parameters[record.parameterIndex].defaultValue, + record.keyPositions[record.neutralKeyIndex], + "E3 rule: every record's neutral key sits at the driving parameter's default", + ) + } + } + + /** + * Flattens a serializer collection payload (list/map/array) into its elements. + * + * @param Any? collection The raw collection field value. + * @return List The contained elements, empty when absent. + */ + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + /** + * Verifies the section-122 identity: across every corpus moc3 with blend shapes, (1) each + * record's delta block at its NEUTRAL key is all zeros in the shared value tables - the + * interpolation includes the neutral key's stored block when bracketing across it, so the + * format must store zeros there - and (2) section 122 is a redundant per-record copy of the + * record's binding key count (confirmed on Model A v6 + Model B/Model C v5). + */ + @Test + fun neutralDeltaBlocksAreZeroAndSection122IsKeyCount() { + val samples = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + ?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + .orEmpty() + if (samples.isEmpty()) { + println("moc3.samples not present; skipping neutral-delta probe") + return + } + for (file in samples) { + val model = org.umamo.format.moc3.moc.MocCodec.read(file.readBytes()) + val document = Moc3.decode(model) + if (document.blendShapes.isEmpty()) { + continue + } + val sections = model.sections + val positionValues = sections.floatArray(org.umamo.format.moc3.moc.Section.KEYFORM_POSITION_VALUES) + val meshPositionIndex = sections.intArray(org.umamo.format.moc3.moc.Section.KEYFORM_POSITION_INDEX) + val warpPositionIndex = sections.intArray(org.umamo.format.moc3.moc.Section.WARP_KEYFORM_INDEX) + val rotationAngle = sections.floatArray(org.umamo.format.moc3.moc.Section.ROTATION_ANGLE) + val rotationOriginX = sections.floatArray(org.umamo.format.moc3.moc.Section.ROTATION_ORIGIN_X) + val rotationOriginY = sections.floatArray(org.umamo.format.moc3.moc.Section.ROTATION_ORIGIN_Y) + val rotationScale = sections.floatArray(org.umamo.format.moc3.moc.Section.ROTATION_SCALE) + + // (2) Table-level: sec122[record] == BINDING_KEY_COUNT[RECORD_BINDING[record]]. + val recordBinding = sections.intArray(org.umamo.format.moc3.moc.Section.BLENDSHAPE_RECORD_BINDING) + val bindingKeyCount = sections.intArray(org.umamo.format.moc3.moc.Section.BLENDSHAPE_BINDING_KEY_COUNT) + val recordKeyCount = sections.intArray(org.umamo.format.moc3.moc.Section.BLENDSHAPE_RECORD_KEY_COUNT) + for (recordIndex in document.blendShapes.indices) { + kotlin.test.assertEquals( + bindingKeyCount[recordBinding[recordIndex]], + recordKeyCount[recordIndex], + "${file.name}: section 122 record $recordIndex is the binding key count", + ) + } + + // (1) Neutral delta blocks are zero, per target kind - checked on the RAW tables, then + // cross-checked against the decoder's typed extraction (BlendShape.keyforms) so the two + // read paths can never drift apart. + var meshChecked = 0 + var warpChecked = 0 + var rotationChecked = 0 + for (record in document.blendShapes) { + val neutralRow = record.recordBase + record.neutralKeyIndex + when (record.target) { + BlendShapeTarget.ART_MESH -> { + val blockLength = document.artMeshes[record.targetIndex].keyforms.first().vertexPositions.size + val offset = meshPositionIndex[neutralRow] + for (valueIndex in offset until offset + blockLength) { + assertTrue(positionValues[valueIndex] == 0f, "${file.name}: mesh neutral delta zero at $valueIndex") + } + for (keyIndex in record.keyforms.indices) { + val typed = record.keyforms[keyIndex] as org.umamo.format.moc3.model.BlendShapeKeyform.Mesh + val rawOffset = meshPositionIndex[record.recordBase + keyIndex] + kotlin.test.assertEquals(blockLength, typed.form.vertexPositions.size, "${file.name}: typed mesh block length") + for (valueIndex in 0 until blockLength) { + assertTrue( + typed.form.vertexPositions[valueIndex] == positionValues[rawOffset + valueIndex], + "${file.name}: typed mesh delta equals raw at key $keyIndex value $valueIndex", + ) + } + } + meshChecked++ + } + BlendShapeTarget.WARP -> { + val warp = document.deformers[record.targetIndex] as org.umamo.format.moc3.model.WarpDeformer + val blockLength = warp.keyforms.first().controlPoints.size + val offset = warpPositionIndex[neutralRow] + for (valueIndex in offset until offset + blockLength) { + assertTrue(positionValues[valueIndex] == 0f, "${file.name}: warp neutral delta zero at $valueIndex") + } + for (keyIndex in record.keyforms.indices) { + val typed = record.keyforms[keyIndex] as org.umamo.format.moc3.model.BlendShapeKeyform.Warp + val rawOffset = warpPositionIndex[record.recordBase + keyIndex] + kotlin.test.assertEquals(blockLength, typed.form.controlPoints.size, "${file.name}: typed warp block length") + for (valueIndex in 0 until blockLength) { + assertTrue( + typed.form.controlPoints[valueIndex] == positionValues[rawOffset + valueIndex], + "${file.name}: typed warp delta equals raw at key $keyIndex value $valueIndex", + ) + } + } + warpChecked++ + } + BlendShapeTarget.ROTATION -> { + assertTrue(rotationAngle[neutralRow] == 0f, "${file.name}: rotation neutral angle zero") + assertTrue(rotationOriginX[neutralRow] == 0f, "${file.name}: rotation neutral originX zero") + assertTrue(rotationOriginY[neutralRow] == 0f, "${file.name}: rotation neutral originY zero") + assertTrue(rotationScale[neutralRow] == 0f, "${file.name}: rotation neutral scale zero") + for (keyIndex in record.keyforms.indices) { + val typed = record.keyforms[keyIndex] as org.umamo.format.moc3.model.BlendShapeKeyform.Rotation + val rawRow = record.recordBase + keyIndex + assertTrue(typed.form.angle == rotationAngle[rawRow], "${file.name}: typed rotation angle equals raw at key $keyIndex") + assertTrue(typed.form.originX == rotationOriginX[rawRow], "${file.name}: typed rotation originX equals raw at key $keyIndex") + assertTrue(typed.form.originY == rotationOriginY[rawRow], "${file.name}: typed rotation originY equals raw at key $keyIndex") + assertTrue(typed.form.scale == rotationScale[rawRow], "${file.name}: typed rotation scale equals raw at key $keyIndex") + } + rotationChecked++ + } + BlendShapeTarget.PART -> { + // MOC3 v5+ §5.6: part delta rows are draw-order floats in section 58 at + // recordBase (verified on Model C: [-900, 0], neutral zero) - the typed + // extraction is asserted by MocDecodeTest's Model C golden. + } + } + } + println("[probe] ${file.name}: neutral-zero + typed-extraction verified mesh=$meshChecked warp=$warpChecked rotation=$rotationChecked") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenKeyformProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenKeyformProbeTest.kt new file mode 100644 index 0000000..ca213ec --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenKeyformProbeTest.kt @@ -0,0 +1,137 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Verifies the v6 offscreen keyform layout on the Model A corpus sample (the only offscreen-carrying + * model). Confirmed structure (see MOC3.md §5.6): + * + * - An offscreen's keyforms ride its OWNER PART's keyform grid - there is no offscreen + * keyform-binding section; Σ owner-part grid sizes == CountInfo 36. + * - Section 161 (OFFSCREEN_OPACITY) holds one row per offscreen keyform, offscreen order. + * - The shared color tables (108-113) are PREFIXED by those same keyform rows; sections 162/163 + * map keyform → color row and read as identity. + * - Section 158 (OFFSCREEN_MASK_BASE) is the cumulative scan of 159 (OFFSCREEN_MASK_COUNT), + * offset from the START of MASK_INDEX_DATA (80): the offscreen mask indices are the block's + * PREFIX and the drawables' masks follow. (Originally misread as a suffix after the drawables' + * masks - refuted against the CMO3 clip lists and the runtime's s158 addressing: Model A's + * pupil offscreens clip the Whites masks, which live at block offsets 0-3.) + * - Section 152 (OFFSCREEN_BY_PART) is the inverse of 155 (OFFSCREEN_OWNER_PART). + * + * Refuted along the way: 158 is NOT a shared-binding index (Σ gridSize over its values far + * exceeds CountInfo 36). Sections 154 and 160 are both typed now, for different reasons: 154 is the + * per-offscreen runtime slot, all-zero on disk and only sized on write (UnmodeledSectionIdentityProbeTest), + * while 160 is a second per-part offscreen-index map whose meaning stays open - it coincides with 152 + * on the small samples and diverges on Model A (OffscreenSectionAliasProbeTest). + */ +class OffscreenKeyformProbeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + @Test + fun offscreenKeyformLayoutIsPinned() { + val sample = + samplesDir?.walkTopDown()?.firstOrNull { it.isFile && it.name.startsWith("modelA") && it.extension == "moc3" } + if (sample == null) { + println("moc3.samples/modelA not present; skipping offscreen probe") + return + } + val model = MocCodec.read(sample.readBytes()) + val document = Moc3.decode(model) + val sections = model.sections + val offscreenCount = model.countInfo.getOrElse(Sections.CI_OFFSCREENS) { 0 } + val offscreenKeyformTotal = model.countInfo.getOrElse(Sections.CI_OFFSCREEN_KEYFORMS) { 0 } + assertEquals(offscreenCount, document.offscreens.size, "offscreen count") + assertTrue(offscreenCount > 0, "Model A carries offscreens") + + // Keyforms ride the owner part's grid; the total matches CountInfo 36. + val ownerGridSizes = document.offscreens.map { document.parts[it.ownerPartIndex].drawOrderKeyforms.size } + assertEquals(offscreenKeyformTotal, ownerGridSizes.sum(), "Σ owner-part grid sizes == CI36") + assertEquals( + ownerGridSizes, + document.offscreens.map { it.keyforms.size }, + "typed keyform runs follow the owner grids", + ) + + // Section 161 rows equal the typed opacities, in offscreen order. + val opacityTable = sections.floatArray(Section.OFFSCREEN_OPACITY) + val typedOpacities = document.offscreens.flatMap { offscreen -> offscreen.keyforms.map { it.opacity } } + assertEquals( + typedOpacities, + opacityTable.toList().subList(0, offscreenKeyformTotal), + "typed opacities equal section 161 rows", + ) + + // The color tables' prefix rows equal the typed keyform colors (multiply channel spot). + val multiplyRed = sections.floatArray(Section.COLOR_MULTIPLY_R) + val typedMultiplyRed = document.offscreens.flatMap { offscreen -> offscreen.keyforms.map { it.multiplyColor!!.r } } + assertEquals( + typedMultiplyRed, + multiplyRed.toList().subList(0, offscreenKeyformTotal), + "typed multiply-color reds equal the color-table prefix", + ) + + // Sections 162/163: keyform → color-row maps, identity on the corpus. + for (rowMapSection in listOf(Section.OFFSCREEN_KEYFORM_MULTIPLY_ROW, Section.OFFSCREEN_KEYFORM_SCREEN_ROW)) { + val rowMap = sections.intArray(rowMapSection) + assertEquals( + (0 until offscreenKeyformTotal).toList(), + rowMap.toList().subList(0, offscreenKeyformTotal), + "$rowMapSection is the identity keyform → color-row map", + ) + } + + // Section 158 is the cumulative scan of 159, offset from the block start (the offscreen + // masks are the PREFIX of MASK_INDEX_DATA; the drawables' masks follow). + val maskBase = sections.intArray(Section.OFFSCREEN_MASK_BASE) + val maskCounts = sections.intArray(Section.OFFSCREEN_MASK_COUNT) + var runningMaskBase = 0 + for (offscreenIndex in 0 until offscreenCount) { + assertEquals(runningMaskBase, maskBase[offscreenIndex], "158 cumulative at offscreen $offscreenIndex") + runningMaskBase += maskCounts[offscreenIndex] + } + val drawableMaskTotal = model.drawables().sumOf { it.maskCount } + val maskBytes = model.section(Section.MASK_INDEX_DATA.indexIn(model.version))!! + val maskReader = org.umamo.format.moc3.io.LittleEndianReader(maskBytes) + val maskTable = IntArray(maskBytes.size / 4) { maskReader.readInt32() } + // The raw element region is 64-byte padded, so compare the meaningful rows and require + // anything beyond them to be zero padding. + assertTrue( + maskTable.size >= runningMaskBase + drawableMaskTotal, + "MASK_INDEX_DATA holds the offscreen prefix + drawable masks", + ) + val typedMaskIndices = document.offscreens.flatMap { it.maskIndices.toList() } + assertEquals( + maskTable.toList().subList(0, runningMaskBase), + typedMaskIndices, + "typed offscreen mask indices equal the section 80 prefix", + ) + val typedDrawableMasks = document.artMeshes.flatMap { it.maskDrawableIndices.toList() } + assertEquals( + maskTable.toList().subList(runningMaskBase, runningMaskBase + drawableMaskTotal), + typedDrawableMasks, + "typed drawable mask indices follow the offscreen prefix", + ) + assertTrue( + (runningMaskBase + drawableMaskTotal until maskTable.size).all { maskTable[it] == 0 }, + "nothing but zero padding follows the drawable masks", + ) + + // Section 152 is the inverse of 155. + val byPart = sections.intArray(Section.OFFSCREEN_BY_PART) + for (partIndex in document.parts.indices) { + val expected = document.offscreens.indexOfFirst { it.ownerPartIndex == partIndex } + assertEquals(expected, byPart[partIndex], "152 inverse-map at part $partIndex") + } + + println( + "[offscreen-probe] ${sample.name}: pinned - offscreens=$offscreenCount keyforms=$offscreenKeyformTotal " + + "masks=$runningMaskBase ownerGrids=$ownerGridSizes", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenSectionAliasProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenSectionAliasProbeTest.kt new file mode 100644 index 0000000..b57c14c --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenSectionAliasProbeTest.kt @@ -0,0 +1,91 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocModel +import org.umamo.format.moc3.moc.Section +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Section 160 is NOT a duplicate of section 152. + * + * Both are per-part `i32` arrays that carry an offscreen index (`-1` where a part owns none), and in + * every two-offscreen sample model they are byte-identical - which is where the "alias" reading came + * from. A model with a realistic number of offscreens refutes it: 152 names one slot per offscreen at + * the owner part's index, while 160 holds ONE MORE value at slots shifted off the owner parts. + * + * Its real meaning stays open. The extra value hints at the render-order rule that gives a sub-group + * part owning an offscreen its own render slot, but nothing in the corpus pins that, so a bake writes + * the derivable inverse map into 160 as well rather than reproducing a divergence it cannot derive + * (`MocLowering`, section 160) - and this test exists so the refuted identity is not re-derived from + * the small samples a third time. + */ +class OffscreenSectionAliasProbeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + /** + * Reads a per-part `i32` section as a list. + * + * @param MocModel model The parsed container. + * @param Section section The section to read. + * @param Int count The part count. + * @return List? The values, or null when the section is absent. + */ + private fun perPartInts(model: MocModel, section: Section, count: Int): List? { + val index = section.indexIn(model.version).takeIf { it >= 0 } ?: return null + val bytes = model.section(index) ?: return null + if (bytes.size < count * 4) { + return null + } + return (0 until count).map { slot -> + (bytes[slot * 4].toInt() and 0xFF) or + ((bytes[slot * 4 + 1].toInt() and 0xFF) shl 8) or + ((bytes[slot * 4 + 2].toInt() and 0xFF) shl 16) or + (bytes[slot * 4 + 3].toInt() shl 24) + } + } + + @Test + fun sections152And160DivergeOnAMultiOffscreenModel() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping offscreen alias probe") + return + } + var identical = 0 + var divergent = 0 + var largestDivergence: String? = null + for (file in files) { + val model = MocCodec.read(file.readBytes()) + if (model.version.byteValue < 6) { + continue + } + val partCount = model.countInfo.getOrElse(0) { 0 } + val byPart = perPartInts(model, Section.OFFSCREEN_BY_PART, partCount) ?: continue + val alias = perPartInts(model, Section.OFFSCREEN_BY_PART_ALIAS, partCount) ?: continue + if (byPart == alias) { + identical++ + } else { + divergent++ + val offscreens = byPart.count { it >= 0 } + val aliased = alias.count { it >= 0 } + largestDivergence = "${file.name}: 152 names $offscreens offscreens, 160 names $aliased" + } + } + println("[section-probe] s152 vs s160: $identical identical, $divergent divergent ($largestDivergence)") + assertTrue( + divergent > 0, + "no corpus model distinguishes s152 from s160 - the alias claim cannot be refuted from this corpus, " + + "so re-examine whether the fresh bake should synthesize it after all", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenSweepProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenSweepProbeTest.kt new file mode 100644 index 0000000..2c1167e --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/OffscreenSweepProbeTest.kt @@ -0,0 +1,112 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.encode.MocLowering +import org.umamo.format.moc3.moc.MocCodec +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.test.Test + +/** + * Print-only probe over the baked ModelWithOffscreen family: pairs each file's MOC3 offscreen + * scalar sections (152-163) with the CMO3-authored enum sweep to derive the blend-mode int + * mapping, and dumps the sections the lowering currently misses on these mesh-less models + * (83-85 render-order aggregates, CountInfo, color-table presence). Feeds + * docs/plan/offscreen-support.md; pins nothing. + */ +class OffscreenSweepProbeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun intsOf(bytes: ByteArray?): List { + if (bytes == null) { + return emptyList() + } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + return (0 until bytes.size / 4).map { buffer.getInt(it * 4) } + } + + @Test + fun probeOffscreenSweep() { + val dir = + samplesDir ?: run { + println("moc3.samples not present; skipping") + return + } + // modelA rides along as the organic 24-offscreen cross-check for the section-role hypotheses + // (160 == 152, 153 sizing) derived from the authored extraction family. + val files = + dir.walkTopDown() + .filter { + it.isFile && + it.extension == "moc3" && + ( + it.name.startsWith("ModelWithOffscreen") || + it.name.startsWith("MultiplyScreenColors") || + it.name == "modelA.moc3" + ) + } + .sortedBy { it.name } + .toList() + if (files.isEmpty()) { + println("no ModelWithOffscreen moc3 samples; skipping") + return + } + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val doc = Moc3.decode(model) + println("=== ${file.name} v${model.versionByte} ===") + println(" parts=${doc.parts.size} meshes=${doc.artMeshes.size} offscreens=${doc.offscreens.size}") + for ((offscreenIndex, offscreen) in doc.offscreens.withIndex()) { + val ownerPart = doc.parts.getOrNull(offscreen.ownerPartIndex) + println( + " offscreen[$offscreenIndex] owner=${ownerPart?.id} blendMode=${offscreen.blendMode}" + + " constantFlags=0b${offscreen.constantFlags.toString(2).padStart(8, '0')}" + + " maskCount=${offscreen.maskCount} maskIndices=${offscreen.maskIndices.toList()}" + + " keyforms=${offscreen.keyforms.map { "op=${it.opacity} mul=${it.multiplyColor} scr=${it.screenColor}" }}", + ) + } + // Raw v6 offscreen scalar sections, incl. the carried unknowns 153/154/160. + for (sectionIndex in 152..163) { + val raw = intsOf(model.section(sectionIndex)) + if (raw.isNotEmpty()) { + println(" s$sectionIndex=${raw.take(12)}") + } + } + // The lowering mismatches: real vs synthesized 83/84/85 and CountInfo. + val lowered = MocLowering.lower(doc) + for (sectionIndex in 83..85) { + println(" s$sectionIndex real=${intsOf(model.section(sectionIndex))} ours=${intsOf(lowered[sectionIndex])}") + } + val realCount = intsOf(model.section(0)) + val ourCount = intsOf(lowered[0]) + val diffs = + realCount.indices.filter { fieldIndex -> + fieldIndex < ourCount.size && realCount[fieldIndex] != ourCount[fieldIndex] + } + println(" CountInfo diffs at fields $diffs real=${diffs.map { realCount[it] }} ours=${diffs.map { ourCount[it] }}") + println(" countInfo[0..22]=${realCount.take(23)}") + // Color-table presence (the falsified MocSectionsTest invariant). + println(" colorSections present: ${(108..113).map { model.section(it)?.size ?: 0 }}") + // Render-order groups for the 84/85 analysis. + for ((groupIndex, group) in doc.renderOrderGroups.withIndex()) { + println(" group[$groupIndex] children=${group.children.map { child -> "k${child.kind}:i${child.index}:g${child.groupIndex}" }}") + } + // Drawable-level extraction for the PartClipping bake: constant flags (culling bit) and a + // full section-size map to locate where a drawable's EXTENDED blend (screen/out) lands - + // the legacy 2-bit flag field cannot express it. + if ("PartClipping" in file.name) { + for ((drawableIndex, mesh) in doc.artMeshes.withIndex()) { + println( + " drawable[$drawableIndex] ${mesh.id} flags=0b${mesh.constantFlags.toString(2).padStart(8, '0')}" + + " masks=${mesh.maskDrawableIndices.toList()}", + ) + } + val sectionSizes = + (0 until 256).mapNotNull { sectionIndex -> + model.section(sectionIndex)?.let { sectionIndex to it.size } + } + println(" sections: $sectionSizes") + } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/PairedVisibilityFlagProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/PairedVisibilityFlagProbeTest.kt new file mode 100644 index 0000000..231cf67 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/PairedVisibilityFlagProbeTest.kt @@ -0,0 +1,260 @@ +package org.umamo.format.moc3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACDeformerSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CPartSourceSet +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocModel +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins which half of each paired MOC3 boolean flag column carries the editor's visibility toggle, + * by joining every corpus CMO3 against its own baked MOC3 twin. + * + * Three object classes store two adjacent `Bool32` columns whose split has never been pinned: + * parts (s7, s8), deformers (s13, s14), and art meshes (s37, s38). + * + * Only the FIRST column of each pair ever deviates from 1 - Azxiana hides 7 of 623 deformers in + * s13, miku_verycursed hides 3 of 100 art meshes in s37 - while s14 and s38 are 1 on every object + * of every sample. A column that is never anything but 1 cannot be the toggle that hides things. + * + * The join is one-directional on purpose, because a bake normally DELETES what the editor hides: + * across the twins, a CMO3-hidden object is simply absent from the MOC3 (EricaTamamo drops 3 art + * meshes, modelD drops 4 plus 2 parts, miku drops 5 plus a part). Only miku_verycursed keeps + * them - the editor's "export invisible drawable" option - and there all 3 hidden meshes are + * present with s37 = 0 and nothing else is. So the provable direction is `s37 == 0` implies + * hidden, and that is what this asserts; "hidden implies s37 == 0" is NOT assertable, both + * because the object is usually gone and because the twins can drift (modelE hides ArtMesh153 in + * a CMO3 saved after its bake, so the MOC3 still has it visible). + * + * Two things stay deliberately unpinned. Deformers: Azxiana is the only sample with an s13 + * deviation and it has no CMO3 twin, so s13 = visible is an inference from the art-mesh pair's + * proven shape, not a join result. Parts: no twin keeps a hidden part, so s7 and s8 are both + * all-1 and nothing distinguishes which is `visible_artmeshes` and which is `visible_deformers`. + * + * NOTE for the export: the drop-on-bake behavior above is the official editor's default, NOT the + * one Umamo adopts. We have no "omit hidden objects" option, and deleting something the user can + * still see in the outliner would be a silent destructive edit, so an Umamo export writes a hidden + * art mesh, part, or deformer out with its first flag set to 0 rather than omitting it. TODO: when + * an export-options surface exists, add an "omit hidden objects" toggle there, defaulting to OFF. + * + * @see MOC3.md §5.6 + */ +class PairedVisibilityFlagProbeTest { + private val cmo3Probes: List = + System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { it.isFile }.orEmpty() + private val moc3SamplesDir: File? = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + /** One paired-flag column group: its id column, its two flag columns, and the object count. */ + private data class FlagPair( + val label: String, + val countInfoField: Int, + val idSection: Section, + val firstFlagSection: Section, + val secondFlagSection: Section, + ) + + private val flagPairs = + listOf( + FlagPair("part", Sections.CI_PARTS, Section.PART_ID, Section.PART_VISIBLE_ARTMESHES, Section.PART_VISIBLE_DEFORMERS), + FlagPair("deformer", Sections.CI_DEFORMERS, Section.DEFORMER_ID, Section.DEFORMER_IS_VISIBLE, Section.DEFORMER_IS_ENABLED), + FlagPair("artMesh", Sections.CI_DRAWABLES, Section.ARTMESH_ID, Section.ARTMESH_IS_VISIBLE, Section.ARTMESH_IS_ENABLED), + ) + + /** + * Reads a flag column, or null when the file does not carry it for this object kind. + * + * @param MocModel model The parsed container. + * @param Section section The flag column. + * @param Int count The object count the column should cover. + * @return IntArray? The values, or null when absent or short. + */ + private fun flagColumn(model: MocModel, section: Section, count: Int): IntArray? = + model.sections.intArray(section).takeIf { it.size == count } + + /** + * Flattens a serializer collection payload into its elements. + * + * @param Any? collection The raw collection field value. + * @return List The contained elements, empty when absent. + */ + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + @Test + fun firstFlagOfEachPairCarriesVisibility() { + if (cmo3Probes.isEmpty() || moc3SamplesDir == null) { + println("cmo3.probe / moc3.samples not both present; skipping paired visibility flag probe") + return + } + val mocByName = + moc3SamplesDir.walkTopDown().filter { it.isFile && it.extension == "moc3" } + .associateBy { it.nameWithoutExtension } + val twins = cmo3Probes.mapNotNull { cmo3 -> mocByName[cmo3.nameWithoutExtension]?.let { cmo3 to it } } + if (twins.isEmpty()) { + println("no CMO3/MOC3 twins in the corpus; skipping paired visibility flag probe") + return + } + + var joinedDeviations = 0 + for ((cmo3File, moc3File) in twins.sortedBy { it.first.name }) { + val root = Cmo3.read(cmo3File).root as? CModelSource ?: continue + val model = MocCodec.read(moc3File.readBytes()) + val counts = model.countInfo + + // Each CMO3 source kind keyed by its authored id, which is also what the moc's id section holds. + val hiddenIdsByKind = + mapOf( + "part" to + elements((root.partSourceSet as? CPartSourceSet)?._sources) + .filterIsInstance() + .filter { !it.isVisible } + .mapNotNull { (it.id as? Id)?.idstr } + .toSet(), + "deformer" to + elements((root.deformerSourceSet as? CDeformerSourceSet)?._sources) + .filterIsInstance() + .filter { !it.isVisible } + .mapNotNull { (it.id as? Id)?.idstr } + .toSet(), + "artMesh" to + elements((root.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + .filter { !it.isVisible } + .mapNotNull { (it.id as? Id)?.idstr } + .toSet(), + ) + + for (pair in flagPairs) { + val count = counts.getOrElse(pair.countInfoField) { 0 } + if (count == 0) { + continue + } + val ids = model.sections.idArray(pair.idSection).takeIf { it.size == count } ?: continue + val firstFlag = flagColumn(model, pair.firstFlagSection, count) ?: continue + val secondFlag = flagColumn(model, pair.secondFlagSection, count) ?: continue + + // The second column has never been observed carrying anything but 1, on any object of any + // sample. If a future sample breaks this, the split is genuinely more complex than + // "first = visible" and the docs must stop claiming otherwise. + val secondDeviations = secondFlag.count { it != 1 } + assertEquals( + 0, + secondDeviations, + "${moc3File.name}: ${pair.label} ${pair.secondFlagSection} is not constant 1", + ) + + val flaggedHidden = ids.filterIndexed { index, _ -> firstFlag[index] == 0 }.toSet() + val cmo3Hidden = hiddenIdsByKind.getValue(pair.label) + val mocIds = ids.toSet() + + // The provable direction: anything the moc flags zero is hidden in the editor. The + // converse does not hold - see the class docblock. + assertEquals( + emptySet(), + flaggedHidden - cmo3Hidden, + "${moc3File.name}: ${pair.label} ${pair.firstFlagSection} flags an object the CMO3 shows", + ) + joinedDeviations += flaggedHidden.size + if (flaggedHidden.isNotEmpty() || cmo3Hidden.isNotEmpty()) { + println( + "[flag-probe] ${moc3File.name} ${pair.label}: mocCount=$count " + + "${pair.firstFlagSection}Zero=${flaggedHidden.size} " + + "cmo3Hidden=${cmo3Hidden.size} " + + "keptInMoc=${cmo3Hidden.intersect(mocIds).size} " + + "droppedByBake=${(cmo3Hidden - mocIds).size}", + ) + } + } + } + + // A join that never saw a flagged object would pass vacuously and prove nothing about the split, + // which is the exact failure mode a corpus gate is prone to. miku_verycursed is the one sample + // that exports its hidden art meshes instead of dropping them, so the twins must reach 3 here. + assertEquals( + 3, + joinedDeviations, + "the paired-flag split was not exercised (expected miku_verycursed's 3 exported hidden meshes)", + ) + } + + /** + * Census over EVERY corpus moc, twin or not: the second column of each pair is constant 1, and the + * only deviations anywhere are in the first columns. + * + * This is what carries the deformer half of the claim. Azxiana is the sole sample with an s13 + * deviation and it has no CMO3 twin, so the join above cannot reach it; pinning the census keeps + * the observation from silently evaporating, and a future sample that puts a zero in s8, s14, or + * s38 fails here rather than quietly invalidating the docs. + */ + @Test + fun onlySecondFlagsAreConstantAcrossTheWholeCorpus() { + val samplesDir = moc3SamplesDir + if (samplesDir == null) { + println("moc3.samples not present; skipping paired flag census") + return + } + // work/ holds our own bake outputs, excluded like every other corpus walk does. This census + // pins what the EDITOR writes; including our bakes would let the export's own output vouch for + // the invariant it is supposed to be measured against. + val files = + samplesDir + .walkTopDown() + .filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + .sortedBy { it.name } + .toList() + if (files.isEmpty()) { + println("no corpus moc3 files; skipping paired flag census") + return + } + val firstColumnDeviations = HashMap() + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val counts = model.countInfo + for (pair in flagPairs) { + val count = counts.getOrElse(pair.countInfoField) { 0 } + if (count == 0) { + continue + } + val firstFlag = flagColumn(model, pair.firstFlagSection, count) ?: continue + val secondFlag = flagColumn(model, pair.secondFlagSection, count) ?: continue + assertEquals( + 0, + secondFlag.count { it != 1 }, + "${file.name}: ${pair.label} ${pair.secondFlagSection} is not constant 1", + ) + val zeros = firstFlag.count { it == 0 } + if (zeros > 0) { + firstColumnDeviations["${file.name} ${pair.label} ${pair.firstFlagSection}"] = zeros + println("[flag-census] ${file.name} ${pair.label}: ${pair.firstFlagSection} zero on $zeros/$count") + } + } + } + // Pinned: the two samples that carry a deviation at all, and how many. Azxiana's is the only + // evidence that the deformer pair splits the same way the art-mesh pair provably does. + assertEquals( + mapOf( + "Azxiana.moc3 deformer DEFORMER_IS_VISIBLE" to 7, + "miku_verycursed.moc3 artMesh ARTMESH_IS_VISIBLE" to 3, + ), + firstColumnDeviations, + "corpus flag deviations changed", + ) + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/UnmodeledSectionIdentityProbeTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/UnmodeledSectionIdentityProbeTest.kt new file mode 100644 index 0000000..7244ce2 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/moc3/UnmodeledSectionIdentityProbeTest.kt @@ -0,0 +1,299 @@ +package org.umamo.format.moc3 + +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocModel +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.moc.Sections +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the on-disk identity of the section indices a bake once had to carry verbatim from a + * reference container, so they can be folded into the typed `Section` enum knowing what they hold + * rather than guessing. + * + * Every index below is typed and synthesized now - `MocRuntimeSlots` sizes the runtime slots, + * `MocDerivedIndexes` rebuilds the drawable and render-order start columns, and `MocLowering` writes + * the part keyform base, the per-form color rows, and the parameter start columns - which is what + * makes `MocEncoder.bakeFresh` possible without a reference file. The identities pinned here are + * the evidence those writers are derived from, so the probe stays as the gate that catches a corpus + * sample contradicting one. + * + * Sections 137-142 are per-FORM color row references, not blend-shape sections, and their multiply + * and screen arrays are bit-identical, the same shape the offscreen keyform rows (162/163) already + * have. Section 56's empty-slot filler is not arbitrary either: it is -1 for a NORMAL parameter and + * 0 for a BLEND_SHAPE one, which is what makes the column reproducible. + * + * @see MOC3.md §5.6 + */ +class UnmodeledSectionIdentityProbeTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir?.walkTopDown()?.filter { it.isFile && it.extension == "moc3" }?.sortedBy { it.name }?.toList() + ?: emptyList() + + /** + * Reads a raw section as [count] little-endian `i32`s, or null when absent or too short. + * + * @param MocModel model The parsed container. + * @param Int index The section-table index. + * @param Int count How many entries to read. + * @return IntArray? The values, or null. + */ + private fun rawInts(model: MocModel, index: Int, count: Int): IntArray? { + val bytes = model.section(index) ?: return null + if (count == 0 || bytes.size < count * 4) { + return null + } + val reader = LittleEndianReader(bytes) + return IntArray(count) { reader.readInt32() } + } + + /** + * The running prefix sum of [counts], each entry scaled by [scale] and shifted by [base]. + * + * @param IntArray counts The per-object counts. + * @param Int base The value of entry 0. + * @param Int scale Multiplier applied to each count. + * @return IntArray The expected start column. + */ + private fun prefixSum(counts: IntArray, base: Int = 0, scale: Int = 1): IntArray { + var running = base + return IntArray(counts.size) { index -> + val start = running + running += counts[index] * scale + start + } + } + + /** + * Sections 2, 29-32, 49, 89, 102, and 154 are per-object `u64` runtime slots: the runtime fills + * them after the memory-cast, so they are all-zero on disk and only need to be SIZED on write. + */ + @Test + fun runtimeSlotSectionsAreAllZeroOnDisk() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping runtime slot probe") + return + } + // Section index → the CountInfo field sizing it, and how many u64 slots each object gets. + val slotSections = + listOf( + Triple(2, Sections.CI_PARTS, 1), + Triple(29, Sections.CI_DRAWABLES, 1), + Triple(30, Sections.CI_DRAWABLES, 1), + Triple(31, Sections.CI_DRAWABLES, 1), + Triple(32, Sections.CI_DRAWABLES, 1), + Triple(49, Sections.CI_PARAMETERS, 1), + Triple(89, Sections.CI_GLUES, 1), + Triple(102, Sections.CI_PARAMETERS, 1), + Triple(154, Sections.CI_OFFSCREENS, 1), + ) + var checked = 0 + for (file in files) { + val model = MocCodec.read(file.readBytes()) + for ((sectionIndex, countField, slotsPerObject) in slotSections) { + val count = model.countInfo.getOrElse(countField) { 0 } * slotsPerObject + val bytes = model.section(sectionIndex) ?: continue + if (count == 0) { + continue + } + val region = bytes.copyOf(minOf(bytes.size, count * 8)) + assertTrue(region.all { it.toInt() == 0 }, "${file.name}: s$sectionIndex is not all-zero") + checked++ + } + } + assertTrue(checked > 0, "no runtime slot sections were examined") + println("[section-probe] runtime slots: $checked all-zero regions across ${files.size} samples") + } + + /** + * Sections 44, 45, 47, 5, and 81 are start columns: the running prefix sum of a count column that + * IS modeled. Section 47's base is the offscreen mask block that precedes the drawable masks in + * section 80, so it is taken from entry 0 rather than assumed zero. + */ + @Test + fun startColumnsArePrefixSumsOfTheirCountColumns() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping start column probe") + return + } + var checked = 0 + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val drawables = model.countInfo.getOrElse(Sections.CI_DRAWABLES) { 0 } + val parts = model.countInfo.getOrElse(Sections.CI_PARTS) { 0 } + val groups = model.countInfo.getOrElse(Sections.CI_RENDER_ORDER_GROUPS) { 0 } + + // s44 indexes section 78 (UV floats), so it advances by TWO per vertex. + rawInts(model, 43, drawables)?.let { vertexCounts -> + rawInts(model, 44, drawables)?.let { starts -> + assertEquals(prefixSum(vertexCounts, scale = 2).toList(), starts.toList(), "${file.name}: s44") + checked++ + } + } + rawInts(model, 46, drawables)?.let { indexCounts -> + rawInts(model, 45, drawables)?.let { starts -> + assertEquals(prefixSum(indexCounts).toList(), starts.toList(), "${file.name}: s45") + checked++ + } + } + rawInts(model, 48, drawables)?.let { maskCounts -> + rawInts(model, 47, drawables)?.let { starts -> + assertEquals( + prefixSum(maskCounts, base = starts.first()).toList(), + starts.toList(), + "${file.name}: s47 (base = the offscreen mask prefix)", + ) + checked++ + } + } + rawInts(model, 6, parts)?.let { formCounts -> + rawInts(model, 5, parts)?.let { starts -> + assertEquals(prefixSum(formCounts).toList(), starts.toList(), "${file.name}: s5") + checked++ + } + } + rawInts(model, 82, groups)?.let { childCounts -> + rawInts(model, 81, groups)?.let { starts -> + assertEquals(prefixSum(childCounts).toList(), starts.toList(), "${file.name}: s81") + checked++ + } + } + } + assertTrue(checked > 0, "no start columns were examined") + println("[section-probe] start columns: $checked prefix-sum identities held") + } + + /** + * Sections 137-142 are per-FORM color row references, `colorBase[object] + gridIndex`, and each + * pair's multiply and screen arrays are bit-identical. + * + * An earlier revision of `MOC3.md` §5.6 lumped 115-148 together as blend-shape sections, which is + * wrong for these six: they belong to WarpForm / RotForm / ArtMeshForm and arrived in Cubism 5. + * Both halves of the claim are checked here, per form of every object of every v5+ sample, and the + * table now names the six individually. + */ + @Test + fun perFormColorReferencesAreBasePlusGridIndex() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping per-form color reference probe") + return + } + // (object count field, keyform-base section, form-count section, colorBase section, + // multiply-ref section, screen-ref section, form count field) + val groups = + listOf( + Triple(Sections.CI_WARPS, intArrayOf(20, 21, 105, 137, 138), 7), + Triple(Sections.CI_ROTATIONS, intArrayOf(26, 27, 106, 139, 140), 8), + Triple(Sections.CI_DRAWABLES, intArrayOf(35, 36, 107, 141, 142), 9), + ) + var checkedForms = 0 + for (file in files) { + val model = MocCodec.read(file.readBytes()) + if (model.version.byteValue < 5) { + continue + } + for ((objectCountField, sections, formCountField) in groups) { + val objectCount = model.countInfo.getOrElse(objectCountField) { 0 } + val formCount = model.countInfo.getOrElse(formCountField) { 0 } + val keyformBase = rawInts(model, sections[0], objectCount) ?: continue + val formCounts = rawInts(model, sections[1], objectCount) ?: continue + val colorBase = rawInts(model, sections[2], objectCount) ?: continue + val multiplyRefs = rawInts(model, sections[3], formCount) ?: continue + val screenRefs = rawInts(model, sections[4], formCount) ?: continue + + assertEquals( + multiplyRefs.toList(), + screenRefs.toList(), + "${file.name}: s${sections[3]} and s${sections[4]} are not identical", + ) + for (objectIndex in 0 until objectCount) { + for (gridIndex in 0 until formCounts[objectIndex]) { + val slot = keyformBase[objectIndex] + gridIndex + assertTrue(slot < formCount, "${file.name}: form slot $slot past the color ref table") + assertEquals( + colorBase[objectIndex] + gridIndex, + multiplyRefs[slot], + "${file.name}: s${sections[3]}[$slot] != colorBase[$objectIndex] + $gridIndex", + ) + checkedForms++ + } + } + } + } + assertTrue(checkedForms > 0, "no per-form color references were examined") + println("[section-probe] per-form color refs: $checkedForms forms matched base + gridIndex") + } + + /** + * Section 56 is the parameter's binding-set start: the prefix sum of section 57 over parameters + * that HAVE bindings, with the empty slots filled by -1 for a NORMAL parameter and 0 for a + * BLEND_SHAPE one. Section 103 is the same shape over section 104, based at the end of the + * preceding key region rather than at zero. + * + * The empty-slot filler is what made this column look arbitrary: both values occur in one file + * (LimeBirb, modelF), and only the parameter type separates them. + */ + @Test + fun parameterStartColumnsFollowTheTypedEmptySlotConvention() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping parameter start column probe") + return + } + var checkedEmpty = 0 + var checkedFilled = 0 + for (file in files) { + val model = MocCodec.read(file.readBytes()) + val parameters = model.countInfo.getOrElse(Sections.CI_PARAMETERS) { 0 } + val bindingCounts = rawInts(model, 57, parameters) ?: continue + val starts = rawInts(model, 56, parameters) ?: continue + // s114 (Parameter.Types) only exists from moc 4; before that every parameter is NORMAL. + val types = rawInts(model, Section.PARAM_TYPE.indexIn(model.version), parameters) + + var running = 0 + for (parameterIndex in 0 until parameters) { + if (bindingCounts[parameterIndex] > 0) { + assertEquals( + running, + starts[parameterIndex], + "${file.name}: s56[$parameterIndex] is not the running binding-set cursor", + ) + running += bindingCounts[parameterIndex] + checkedFilled++ + } else { + val isBlendShape = types?.getOrNull(parameterIndex) == ParameterType.BLEND_SHAPE.ordinal + assertEquals( + if (isBlendShape) 0 else -1, + starts[parameterIndex], + "${file.name}: s56[$parameterIndex] empty slot does not follow the parameter type", + ) + checkedEmpty++ + } + } + + if (model.version.byteValue >= 4) { + rawInts(model, 104, parameters)?.let { keyCounts -> + rawInts(model, 103, parameters)?.let { keyStarts -> + assertEquals( + prefixSum(keyCounts, base = keyStarts.first()).toList(), + keyStarts.toList(), + "${file.name}: s103 is not a based prefix sum of s104", + ) + } + } + } + } + assertTrue(checkedFilled > 0 && checkedEmpty > 0, "both filled and empty s56 slots must be exercised") + println("[section-probe] s56: $checkedFilled cursor slots, $checkedEmpty typed empty slots") + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/png/PngDecodeParityTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/png/PngDecodeParityTest.kt new file mode 100644 index 0000000..fd1bb54 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/png/PngDecodeParityTest.kt @@ -0,0 +1,148 @@ +package org.umamo.format.png + +import java.awt.image.BufferedImage +import java.io.ByteArrayInputStream +import java.io.File +import java.util.Arrays +import javax.imageio.ImageIO +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The art-sourcing roadmap's named Phase-A validation: decode a real PNG through the pure-Kotlin + * [PngCodec] and through javax.imageio (the decoder the retired `decodePngToRgba` used), and assert + * the straight-alpha RGBA byte streams are pixel-identical. This is the drop-in-replacement proof + * for the CMO3 atlas path. + * + * The one reference serves every bit depth: ImageIO's ColorModel reduces a 16-bit sample with the same + * linear equation PngCodec applies (PNG spec §13.12), so a 16-bit file is compared exactly too. + * + * Corpus-gated: point `-Dpng.sample=/path/to/atlas.png` at a real PNG, or drop `.png` files anywhere + * under `test/corpus/` — the atlas pages that ship beside a model's `.moc3` are exactly the intended + * sample. Absent → the test self-skips, so CI stays green without a committed corpus. + */ +class PngDecodeParityTest { + /** + * Locates every PNG sample: `-Dpng.sample` when set, else every `.png` anywhere under + * `test/corpus`. + * + * Searches the whole corpus rather than one `png/` directory because the PNGs worth this test are + * the atlas pages that sit beside the model they belong to, not loose files in a per-format folder. + * + * @return List The samples, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("png.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return corpus.walkTopDown() + .filter { candidate -> candidate.isFile && candidate.extension.equals("png", ignoreCase = true) } + .sortedBy { it.path } + .toList() + } + directory = directory.parentFile + } + return emptyList() + } + + @Test + fun pngCodecMatchesImageIoPixelForPixel() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no png.sample and no test/corpus PNGs; skipping PNG parity test") + return + } + val failures = samples.mapNotNull(::checkSample) + assertTrue(failures.isEmpty(), "PngCodec decode must match javax.imageio:\n" + failures.joinToString("\n")) + } + + /** + * Compares one PNG's decode through [PngCodec] against javax.imageio, one row at a time. + * + * The reference is built one row at a time, so a 16384-square atlas never holds more than the two + * decoded images at once (1 GiB each). A whole-image reference copy would add two more, past the + * test heap. + * + * @param File sample The `.png` to compare. + * @return String? The mismatch description, or null when the decodes agree or ImageIO cannot read the file. + */ + private fun checkSample(sample: File): String? { + val bytes = sample.readBytes() + val decoded = PngCodec.read(bytes) + val reference = ImageIO.read(ByteArrayInputStream(bytes)) + if (reference == null) { + println("${sample.name}: ImageIO could not decode; skipping parity test") + return null + } + if (reference.width != decoded.width || reference.height != decoded.height) { + return "${sample.path}: PngCodec decoded ${decoded.width}x${decoded.height}, javax.imageio ${reference.width}x${reference.height}" + } + + val width = decoded.width + val rowBytes = width * 4 + val expectedRow = ByteArray(rowBytes) + val argbRow = IntArray(width) + var mismatchedPixels = 0L + var firstMismatch: String? = null + for (rowIndex in 0 until decoded.height) { + referenceRow(reference, rowIndex, argbRow, expectedRow) + val rowStart = rowIndex * rowBytes + if (Arrays.equals(expectedRow, 0, rowBytes, decoded.rgba, rowStart, rowStart + rowBytes)) { + continue + } + for (columnIndex in 0 until width) { + val pixelOffset = columnIndex * 4 + if (Arrays.equals(expectedRow, pixelOffset, pixelOffset + 4, decoded.rgba, rowStart + pixelOffset, rowStart + pixelOffset + 4)) { + continue + } + mismatchedPixels++ + if (firstMismatch == null) { + val expectedPixel = rgbaHex(expectedRow, pixelOffset) + val decodedPixel = rgbaHex(decoded.rgba, rowStart + pixelOffset) + firstMismatch = "first at ($columnIndex, $rowIndex): expected $expectedPixel, decoded $decodedPixel" + } + } + } + if (firstMismatch != null) { + return "${sample.path}: $mismatchedPixels of ${width.toLong() * decoded.height} pixels differ, $firstMismatch" + } + println("parity ok ${sample.name}: ${width}x${decoded.height}, ${reference.sampleModel.getSampleSize(0)}-bit") + return null + } + + /** + * Builds one row of the reference through ImageIO's ColorModel, as the retired `decodePngToRgba` + * did, unpacking each packed ARGB pixel to straight-alpha RGBA. + * + * @param BufferedImage reference The ImageIO decode. + * @param Int rowIndex The image row to read. + * @param IntArray scratch At least `width` ints, overwritten with the row's packed ARGB. + * @param ByteArray expectedRow Receives the row's `width * 4` RGBA bytes. + */ + private fun referenceRow(reference: BufferedImage, rowIndex: Int, scratch: IntArray, expectedRow: ByteArray) { + val width = reference.width + reference.getRGB(0, rowIndex, width, 1, scratch, 0, width) + for (columnIndex in 0 until width) { + val packed = scratch[columnIndex] + val base = columnIndex * 4 + expectedRow[base] = (packed ushr 16).toByte() + expectedRow[base + 1] = (packed ushr 8).toByte() + expectedRow[base + 2] = packed.toByte() + expectedRow[base + 3] = (packed ushr 24).toByte() + } + } + + /** + * Formats the four RGBA bytes at [offset] as hex, for a mismatch report. + * + * @param ByteArray rgba The buffer. + * @param Int offset The pixel's first byte. + * @return String The pixel as `RRGGBBAA`. + */ + private fun rgbaHex(rgba: ByteArray, offset: Int): String = + (0 until 4).joinToString("") { channelIndex -> (rgba[offset + channelIndex].toInt() and 0xFF).toString(16).padStart(2, '0') } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/png/PngImageIoParityTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/png/PngImageIoParityTest.kt new file mode 100644 index 0000000..3e13e4e --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/png/PngImageIoParityTest.kt @@ -0,0 +1,180 @@ +package org.umamo.format.png + +import org.umamo.format.raster.RasterImage +import java.awt.image.BufferedImage +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import javax.imageio.IIOImage +import javax.imageio.ImageIO +import javax.imageio.ImageWriteParam +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Exercises [PngCodec] against javax.imageio as an independent reference encoder: PNGs ImageIO writes + * use whatever scanline filters it chooses, plus Adam7 interlace, so decoding them proves the + * unfilter and de-interlace paths against an encoder that is not ours. + * + * This is the half of the PNG suite that genuinely needs the JVM (ImageIO is desktop-only, absent on + * Android and Kotlin/Native), so it stays in jvmTest; the hand-built, target-independent cases live in + * commonTest's PngCodecTest. + */ +class PngImageIoParityTest { + @Test + fun decodesImageIoEncodedRgbaAcrossFilters() { + val image = gradientArgbImage(width = 17, height = 11) + val decoded = PngCodec.read(encodePng(image, interlaced = false)) + assertArgbImageMatches(image, decoded) + } + + @Test + fun decodesImageIoInterlacedRgba() { + val image = gradientArgbImage(width = 19, height = 13) + val png = encodePng(image, interlaced = true) + if ((png[28].toInt() and 0xFF) != 1) { + println("ImageIO did not produce an interlaced PNG on this JDK; skipping Adam7 assertion") + return + } + val decoded = PngCodec.read(png) + assertArgbImageMatches(image, decoded) + } + + @Test + fun decodesImageIoInterlacedGray8() { + // 8-bit grayscale decodes through the per-sample lookup table rather than the RGBA copy, so + // its Adam7 scatter is a separate path. + val image = BufferedImage(19, 13, BufferedImage.TYPE_BYTE_GRAY) + for (y in 0 until image.height) { + for (x in 0 until image.width) { + image.raster.setSample(x, y, 0, (x * 13 + y * 7) and 0xFF) + } + } + val png = encodePng(image, interlaced = true) + if ((png[28].toInt() and 0xFF) != 1) { + println("ImageIO did not produce an interlaced PNG on this JDK; skipping Adam7 assertion") + return + } + assertGraySamplesMatch(image, PngCodec.read(png)) { sample -> sample } + } + + @Test + fun decodesImageIoInterlacedGray16() { + // 16-bit grayscale decodes sample by sample and rescales by PNG spec §13.12's linear equation. + val image = BufferedImage(19, 13, BufferedImage.TYPE_USHORT_GRAY) + for (y in 0 until image.height) { + for (x in 0 until image.width) { + image.raster.setSample(x, y, 0, (x * 3001 + y * 1733) and 0xFFFF) + } + } + val png = encodePng(image, interlaced = true) + assertEquals(16, png[24].toInt() and 0xFF, "ImageIO writes TYPE_USHORT_GRAY as a 16-bit PNG") + if ((png[28].toInt() and 0xFF) != 1) { + println("ImageIO did not produce an interlaced PNG on this JDK; skipping Adam7 assertion") + return + } + assertGraySamplesMatch(image, PngCodec.read(png)) { sample -> ((2L * sample * 255 + 65535) / (2L * 65535)).toInt() } + } + + @Test + fun readsWidthAndHeightFromRealImageIoPng() { + // A quick guard that a standard single-IDAT ImageIO PNG decodes via the same public path. + val image = gradientArgbImage(4, 4) + val out = ByteArrayOutputStream() + ImageIO.write(image, "png", out) + val reread = ImageIO.read(ByteArrayInputStream(out.toByteArray())) + assertEquals(reread.width, PngCodec.read(out.toByteArray()).width) + } + + /** + * Builds a TYPE_INT_ARGB test image with a deterministic gradient; alpha stays in 64..255 so + * ImageIO reliably preserves the RGB of every pixel (a fully-transparent pixel is where encoders + * are free to drop color - covered separately by the hand-built tRNS tests). + * + * @param Int width Image width. + * @param Int height Image height. + * @return BufferedImage The gradient image. + */ + private fun gradientArgbImage(width: Int, height: Int): BufferedImage { + val image = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) + for (y in 0 until height) { + for (x in 0 until width) { + val red = (x * 13) and 0xFF + val green = (y * 17) and 0xFF + val blue = ((x + y) * 7) and 0xFF + val alpha = 64 + ((x * y) % 192) + image.setRGB(x, y, (alpha shl 24) or (red shl 16) or (green shl 8) or blue) + } + } + return image + } + + /** + * Encodes a BufferedImage to PNG bytes via javax.imageio, optionally requesting Adam7 interlace. + * + * @param BufferedImage image The image to encode. + * @param Boolean interlaced Whether to request progressive (interlaced) output. + * @return ByteArray The PNG bytes. + */ + private fun encodePng(image: BufferedImage, interlaced: Boolean): ByteArray { + val out = ByteArrayOutputStream() + if (!interlaced) { + ImageIO.write(image, "png", out) + return out.toByteArray() + } + val writer = ImageIO.getImageWritersByFormatName("png").next() + val param = writer.defaultWriteParam + if (param.canWriteProgressive()) { + param.progressiveMode = ImageWriteParam.MODE_DEFAULT + } + ImageIO.createImageOutputStream(out).use { stream -> + writer.output = stream + writer.write(null, IIOImage(image, null, null), param) + } + writer.dispose() + return out.toByteArray() + } + + /** + * Asserts a decoded [RasterImage] matches the reference image pixel-for-pixel (straight RGBA). + * + * @param BufferedImage reference The source TYPE_INT_ARGB image. + * @param RasterImage decoded The codec's decode. + */ + private fun assertArgbImageMatches(reference: BufferedImage, decoded: RasterImage) { + assertEquals(reference.width, decoded.width, "width") + assertEquals(reference.height, decoded.height, "height") + for (y in 0 until reference.height) { + for (x in 0 until reference.width) { + val packed = reference.getRGB(x, y) + val base = (y * reference.width + x) * 4 + assertEquals((packed ushr 16) and 0xFF, decoded.rgba[base].toInt() and 0xFF, "R @ ($x,$y)") + assertEquals((packed ushr 8) and 0xFF, decoded.rgba[base + 1].toInt() and 0xFF, "G @ ($x,$y)") + assertEquals(packed and 0xFF, decoded.rgba[base + 2].toInt() and 0xFF, "B @ ($x,$y)") + assertEquals((packed ushr 24) and 0xFF, decoded.rgba[base + 3].toInt() and 0xFF, "A @ ($x,$y)") + } + } + } + + /** + * Asserts a decoded [RasterImage] is the opaque gray a single-band reference image stores, compared + * against the reference's raster samples (the values written to the file) through [toEightBits]. + * + * @param BufferedImage reference The source single-band grayscale image. + * @param RasterImage decoded The codec's decode. + * @param Function1 toEightBits Maps a stored sample to the expected 8-bit gray. + */ + private fun assertGraySamplesMatch(reference: BufferedImage, decoded: RasterImage, toEightBits: (Int) -> Int) { + assertEquals(reference.width, decoded.width, "width") + assertEquals(reference.height, decoded.height, "height") + for (y in 0 until reference.height) { + for (x in 0 until reference.width) { + val expectedGray = toEightBits(reference.raster.getSample(x, y, 0)) + val base = (y * reference.width + x) * 4 + assertEquals(expectedGray, decoded.rgba[base].toInt() and 0xFF, "R @ ($x,$y)") + assertEquals(expectedGray, decoded.rgba[base + 1].toInt() and 0xFF, "G @ ($x,$y)") + assertEquals(expectedGray, decoded.rgba[base + 2].toInt() and 0xFF, "B @ ($x,$y)") + assertEquals(255, decoded.rgba[base + 3].toInt() and 0xFF, "A @ ($x,$y)") + } + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/psd/PsdReaderTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/psd/PsdReaderTest.kt new file mode 100644 index 0000000..c38844a --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/psd/PsdReaderTest.kt @@ -0,0 +1,228 @@ +package org.umamo.format.psd + +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.isEffectivelyVisible +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * End-to-end reader test against a real .psd. Corpus-gated: it uses -Dpsd.sample= when given, + * else auto-discovers a sample under test/corpus/ (or test/) by walking up from the working + * directory; if none is present it self-skips so CI stays green without a committed corpus. + * + * Asserts the structural invariants that matter to the render and re-import paths: a positive canvas + * size, at least one decoded layer, every layer's RGBA buffer sized to its bounds, non-blank ids, + * and - the visibility/folder work this guards - that every layer's groupPath resolves to an emitted + * group, the order values form a 0..n-1 permutation, and the visibility cascade runs cleanly. + */ +class PsdReaderTest { + /** + * Locates every PSD sample: `-Dpsd.sample` when set, else every `.psd` under `test/corpus/psd` + * (with `test/corpus` and `test` kept as fallbacks for a loose sample). + * + * @return List The samples, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("psd.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + for (subdirectory in listOf("test/corpus/psd", "test/corpus", "test")) { + val samples = + File(directory, subdirectory).takeIf(File::isDirectory) + ?.listFiles { file -> file.extension.equals("psd", ignoreCase = true) } + ?.sortedBy { it.name } + .orEmpty() + if (samples.isNotEmpty()) { + return samples + } + } + directory = directory.parentFile + } + return emptyList() + } + + @Test + fun readsLayersFromRealPsd() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no psd.sample and no test/corpus PSD samples; skipping PSD reader test") + return + } + for (sample in samples) { + checkSample(sample) + } + } + + /** + * Asserts the reader's structural invariants for one sample. + * + * @param File sample The `.psd` to read. + */ + private fun checkSample(sample: File) { + val bytes = sample.readBytes() + // Detection is asserted with the decode so matches() cannot rot untested (see KraReader). + assertTrue(PsdReader.matches(bytes), "${sample.name}: detected as PSD by magic") + val art = PsdReader.read(bytes) + + assertTrue(art.widthPx > 0 && art.heightPx > 0, "${sample.name}: positive canvas size") + assertTrue(art.layers.isNotEmpty(), "${sample.name}: at least one layer") + + for (layer in art.layers) { + assertTrue(layer.id.raw.isNotBlank(), "${sample.name}: layer '${layer.name}' has a stable id") + // The key's strength must say what the key IS: a lyid is stable, the name-and-order fallback is not. + assertEquals( + layer.id.raw.startsWith("lyid:"), + layer.idIsStable, + "${sample.name}: layer '${layer.name}' key '${layer.id.raw}' reports its own stability", + ) + assertTrue( + layer.raster.rgba.size == layer.raster.width * layer.raster.height * 4, + "${sample.name}: layer '${layer.name}' raster sized to its dimensions", + ) + } + + // Order must be a 0..n-1 permutation (folder markers are not emitted, so emitted layers renumber). + val orderValues = art.layers.map { layer -> layer.order }.sorted() + assertTrue( + orderValues == (0 until art.layers.size).toList(), + "${sample.name}: layer order values form a 0..n-1 permutation", + ) + + // Folder surfacing: every group has a non-blank path, and every layer that names an enclosing + // folder resolves to one - the section-divider stack and groupPath assignment must stay aligned. + val groupPaths = art.groups.map { group -> group.path }.toSet() + for (group in art.groups) { + assertTrue(group.path.isNotBlank(), "${sample.name}: group '${group.name}' has a path") + } + for (layer in art.layers) { + assertTrue( + layer.groupPath.isEmpty() || layer.groupPath in groupPaths, + "${sample.name}: layer '${layer.name}' groupPath '${layer.groupPath}' resolves to a group", + ) + art.isEffectivelyVisible(layer) + } + + // Raster layer masks are baked into the alpha, and both halves of that are checked against the + // unmasked decode of the same record: a masked layer keeps SOME of its art wherever its mask + // holds a non-zero value over the layer (an all-transparent result is the mask landing off its + // layer, which is what a mis-read rectangle looks like), and for a black-default mask every + // layer pixel outside the rectangle decodes transparent. + var maskedLayers = 0 + var checkedPixels = 0 + val parse = PsdLayerRecords.parse(bytes) + for (record in parse.records) { + val mask = record.userMask ?: continue + if (mask.disabled || mask.bounds.width <= 0 || mask.bounds.height <= 0) { + continue + } + maskedLayers++ + val layer = art.layers.firstOrNull { candidate -> candidate.name == record.name && candidate.bounds == record.bounds } ?: continue + val raster = layer.raster + val unmasked = PsdRaster.decodeLayer(bytes, parse.header, parse.colorModeData, record.copy(userMask = null, realUserMask = null)) + val unmaskedOpaque = opaquePixelCount(unmasked.rgba) + val maskedOpaque = opaquePixelCount(raster.rgba) + assertTrue(maskedOpaque <= unmaskedOpaque, "${sample.name}: layer '${layer.name}' mask can only hide pixels ($maskedOpaque vs $unmaskedOpaque)") + val originX = mask.bounds.left - record.bounds.left + val originY = mask.bounds.top - record.bounds.top + if (unmaskedOpaque > 0 && maskPlaneHasValueOverLayer(bytes, parse, record, mask, originX, originY, unmasked)) { + assertTrue(maskedOpaque > 0, "${sample.name}: layer '${layer.name}' lost every pixel to its mask - the mask rectangle is off its layer") + } + if (mask.defaultColor != 0) { + continue + } + for (row in 0 until raster.height) { + for (column in 0 until raster.width) { + val inside = (row - originY) in 0 until mask.bounds.height && (column - originX) in 0 until mask.bounds.width + if (inside) { + continue + } + checkedPixels++ + assertEquals( + 0, + raster.rgba[(row * raster.width + column) * 4 + 3].toInt() and 0xFF, + "${sample.name}: layer '${layer.name}' pixel ($column, $row) lies outside its black-default mask and must be transparent", + ) + } + } + } + println("checked ${sample.name}: ${art.widthPx}x${art.heightPx}, ${art.layers.size} layers, ${art.groups.size} groups, $maskedLayers masked layers ($checkedPixels outside-mask pixels checked)") + } + + /** + * How many pixels of an RGBA8888 raster have any alpha. + * + * @param ByteArray rgba The raster. + * @return Int The count. + */ + private fun opaquePixelCount(rgba: ByteArray): Int { + var count = 0 + var index = 3 + while (index < rgba.size) { + if (rgba[index].toInt() != 0) { + count++ + } + index += 4 + } + return count + } + + /** + * Whether the mask plane holds a non-zero value at some pixel where the unmasked layer has alpha - + * the condition under which the bake must keep at least one pixel. The plane is decoded through + * the reader's own channel path by presenting the mask channel as a color channel of a layer sized + * to the mask rectangle. + * + * @param ByteArray bytes The `.psd` bytes. + * @param PsdParse parse The parsed file. + * @param PsdLayerRecord record The masked layer's record. + * @param PsdLayerMask mask Its mask geometry. + * @param Int originX The mask rectangle's left edge in layer pixels. + * @param Int originY The mask rectangle's top edge in layer pixels. + * @param LayerRaster unmasked The layer decoded without its mask. + * @return Boolean True when the mask reveals at least one pixel that has alpha. + */ + private fun maskPlaneHasValueOverLayer( + bytes: ByteArray, + parse: PsdParse, + record: PsdLayerRecord, + mask: PsdLayerMask, + originX: Int, + originY: Int, + unmasked: LayerRaster, + ): Boolean { + var offset = record.channelDataOffset + var maskChannel: PsdChannelInfo? = null + for (channel in record.channels) { + if (channel.id == -2) { + maskChannel = channel + break + } + offset += channel.length.toInt() + } + val channel = maskChannel ?: return false + val asColor = record.copy(bounds = mask.bounds, channels = listOf(PsdChannelInfo(0, channel.length)), channelDataOffset = offset, userMask = null, realUserMask = null) + val plane = PsdRaster.decodeLayer(bytes, parse.header, parse.colorModeData, asColor) + for (row in 0 until unmasked.height) { + val maskRow = row - originY + if (maskRow !in 0 until plane.height) { + continue + } + for (column in 0 until unmasked.width) { + val maskColumn = column - originX + if (maskColumn !in 0 until plane.width) { + continue + } + val hasAlpha = unmasked.rgba[(row * unmasked.width + column) * 4 + 3].toInt() != 0 + val maskValue = plane.rgba[(maskRow * plane.width + maskColumn) * 4].toInt() and 0xFF + if (hasAlpha && maskValue != 0) { + return true + } + } + } + return false + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/tiff/TiffDecodeCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/tiff/TiffDecodeCorpusTest.kt new file mode 100644 index 0000000..c4cc435 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/tiff/TiffDecodeCorpusTest.kt @@ -0,0 +1,64 @@ +package org.umamo.format.tiff + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Corpus-gated end-to-end TIFF decode: every `.tif`/`.tiff` under `test/corpus/` (or the single file + * named by `-Dtiff.sample=/path/to.tiff`) must decode to a correctly sized RGBA buffer. The corpus is + * not committed (it holds multi-hundred-megabyte artwork exports), so this self-skips when absent and + * CI stays green; the committed [TiffDecodeTest] and [TiffCcittDecodeTest] fixtures carry the + * per-feature regression coverage. + */ +class TiffDecodeCorpusTest { + /** + * Locates every TIFF sample: `-Dtiff.sample` when set, else the `test/corpus` directory (and its + * `tiff` subdirectory) found by walking up from the working directory. + * + * @return List The sample files, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("tiff.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return listOf(corpus, File(corpus, "tiff")) + .filter(File::isDirectory) + .flatMap { folder -> folder.listFiles { file -> file.isFile && isTiff(file) }?.toList() ?: emptyList() } + .sortedBy { it.name } + } + directory = directory.parentFile + } + return emptyList() + } + + /** + * Whether [file] carries a TIFF extension. + * + * @param File file The candidate file. + * @return Boolean True for `.tif` / `.tiff`. + */ + private fun isTiff(file: File): Boolean = file.extension.equals("tiff", ignoreCase = true) || file.extension.equals("tif", ignoreCase = true) + + @Test + fun decodesEveryCorpusTiff() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no tiff.sample and no test/corpus TIFFs; skipping TIFF corpus test") + return + } + for (sample in samples) { + val bytes = sample.readBytes() + assertTrue(TiffReader.matches(bytes), "${sample.name}: detected as TIFF by magic") + val decoded = TiffReader.read(bytes) + assertTrue(decoded.width > 0 && decoded.height > 0, "${sample.name}: positive dimensions") + assertEquals(decoded.width * decoded.height * 4, decoded.rgba.size, "${sample.name}: RGBA buffer sized to the image") + println("decoded ${sample.name}: ${decoded.width}x${decoded.height}") + } + } +} \ No newline at end of file diff --git a/module/format/src/jvmTest/kotlin/org/umamo/format/webp/WebpDecodeCorpusTest.kt b/module/format/src/jvmTest/kotlin/org/umamo/format/webp/WebpDecodeCorpusTest.kt new file mode 100644 index 0000000..d86a339 --- /dev/null +++ b/module/format/src/jvmTest/kotlin/org/umamo/format/webp/WebpDecodeCorpusTest.kt @@ -0,0 +1,56 @@ +package org.umamo.format.webp + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Corpus-gated end-to-end WebP decode: every `.webp` under `test/corpus/` (or the single file named by + * `-Dwebp.sample=/path/to.webp`) must decode to a correctly sized RGBA buffer. The corpus is not + * committed, so this self-skips when absent; the committed [WebpVp8lDecodeTest] fixtures carry the + * per-feature regression coverage. Lossy VP8 files are out of scope and rejected, so pick lossless + * (VP8L) samples. + */ +class WebpDecodeCorpusTest { + /** + * Locates every WebP sample: `-Dwebp.sample` when set, else the `test/corpus` directory (and its + * `webp` subdirectory) found by walking up from the working directory. + * + * @return List The sample files, empty when none are configured. + */ + private fun locateSamples(): List { + System.getProperty("webp.sample")?.let { path -> + return listOfNotNull(File(path).takeIf(File::isFile)) + } + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return listOf(corpus, File(corpus, "webp")) + .filter(File::isDirectory) + .flatMap { folder -> folder.listFiles { file -> file.isFile && file.extension.equals("webp", ignoreCase = true) }?.toList() ?: emptyList() } + .sortedBy { it.name } + } + directory = directory.parentFile + } + return emptyList() + } + + @Test + fun decodesEveryCorpusWebp() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no webp.sample and no test/corpus WebPs; skipping WebP corpus test") + return + } + for (sample in samples) { + val bytes = sample.readBytes() + assertTrue(WebPReader.matches(bytes), "${sample.name}: detected as WebP by magic") + val decoded = WebPReader.read(bytes) + assertTrue(decoded.width > 0 && decoded.height > 0, "${sample.name}: positive dimensions") + assertEquals(decoded.width * decoded.height * 4, decoded.rgba.size, "${sample.name}: RGBA buffer sized to the image") + println("decoded ${sample.name}: ${decoded.width}x${decoded.height}") + } + } +} \ No newline at end of file diff --git a/module/format/src/nativeMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.native.kt b/module/format/src/nativeMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.native.kt new file mode 100644 index 0000000..6515395 --- /dev/null +++ b/module/format/src/nativeMain/kotlin/org/umamo/format/clip/ClipDatabaseAccess.native.kt @@ -0,0 +1,99 @@ +package org.umamo.format.clip + +import app.cash.sqldelight.driver.native.NativeSqliteDriver +import co.touchlab.sqliter.DatabaseConfiguration +import okio.FileSystem +import okio.IOException +import okio.Path +import okio.Path.Companion.toPath +import org.umamo.format.clip.db.ClipDatabase +import kotlin.random.Random + +/** + * Kotlin/Native actual: write the database bytes to a temp file and open SQLDelight's + * [NativeSqliteDriver] (SQLiter) over it. + * + * This is the iPadOS path, and it is the one native actual worth having: Clip Studio Paint runs on + * iPad, so ingesting a `.clip` is exactly what a tablet build is for. + * + * Two details are load-bearing: + * - SQLiter opens a database by NAME within a directory, not by arbitrary path, so the blob has to + * be written somewhere and the configuration pointed at that directory. + * - Schema creation must be defeated. The convenience `NativeSqliteDriver(schema, name)` constructor + * runs Schema.create when user_version is 0 — and an embedded .clip database carries user_version 0 + * while already having every table, so it would collide. The Android actual documents the same + * trap. Hence the DatabaseConfiguration overload with no-op create/upgrade. + * + * @param ByteArray databaseBytes The raw "SQLite format 3" bytes. + * @param Function1 block Runs against the open database. + * @return T The block's result. + */ +internal actual fun useClipDatabase(databaseBytes: ByteArray, block: (ClipDatabase) -> T): T { + val fileSystem = FileSystem.SYSTEM + val directory = FileSystem.SYSTEM_TEMPORARY_DIRECTORY + fileSystem.createDirectories(directory) + val databasePath = createTemporaryDatabase(fileSystem, directory, databaseBytes) + try { + val configuration = + DatabaseConfiguration( + // SQLiter addresses the file as (basePath, name), so the two are split rather than joined. + name = databasePath.name, + version = ClipDatabase.Schema.version.toInt(), + // Both no-ops, deliberately: the file already IS a complete CLIP database, so creating + // or migrating it would collide with the tables it arrived with. + create = {}, + upgrade = { _, _, _ -> }, + extendedConfig = DatabaseConfiguration.Extended(basePath = directory.toString()), + ) + val driver = NativeSqliteDriver(configuration) + try { + return block(ClipDatabase(driver)) + } finally { + driver.close() + } + } finally { + fileSystem.delete(databasePath, mustExist = false) + // SQLite may leave journal/WAL sidecars beside the database; take them with it. + for (suffix in listOf("-wal", "-shm", "-journal")) { + fileSystem.delete("$databasePath$suffix".toPath(), mustExist = false) + } + } +} + +/** + * Writes [databaseBytes] to a freshly created file in [directory] and returns its path. + * + * The name is random per call rather than derived from the content, which is what the sibling actuals + * guarantee too (JVM `Files.createTempFile`, Android `System.nanoTime()`). A content-derived name + * would not: two concurrent reads of the same `.clip` would resolve to one path, so each would + * truncate the database the other had open and then delete it mid-query. + * + * `mustCreate` claims the name atomically (O_EXCL), so the retry closes that race rather than merely + * narrowing it. + * + * @param FileSystem fileSystem The filesystem to create on. + * @param Path directory The directory to create in. + * @param ByteArray databaseBytes The bytes to write. + * @return Path The created file. + */ +private fun createTemporaryDatabase(fileSystem: FileSystem, directory: Path, databaseBytes: ByteArray): Path { + while (true) { + val candidate = directory / "umamo-clip-${Random.nextLong().toULong().toString(16)}.sqlite3" + // Only the claim retries. A failure to WRITE is a real error (a full or read-only temp dir) + // and propagates — looping on it would spin forever laying down files. + val handle = + try { + fileSystem.openReadWrite(candidate, mustCreate = true) + } catch (_: IOException) { + // The name is taken — vanishingly unlikely across 64 random bits, but draw again + // rather than clobber a file another reader is holding open. + continue + } + try { + handle.write(0L, databaseBytes, 0, databaseBytes.size) + } finally { + handle.close() + } + return candidate + } +} \ No newline at end of file diff --git a/module/interop/build.gradle.kts b/module/interop/build.gradle.kts new file mode 100644 index 0000000..6900bbe --- /dev/null +++ b/module/interop/build.gradle.kts @@ -0,0 +1,84 @@ +// :interop — format↔runtime conversion. CMO3/MOC3 ingest into the PuppetModel, the CMO3 export +// reconcile, the MOC3 export lowering, the model diff, and the RuntimeTarget↔format-version +// mapping. Depends on BOTH +// :format and :runtime so that neither has to know the other: :format stays a standalone codec +// library and :runtime stays a pure puppet runtime. + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + // Umamo's own conventions (gradle/build-logic): the shared jvmAndroidMain source-set group, the + // iosArm64 → `check` wiring, and the corpus/-D forwarding configured by `umamoTestCorpus` below. + id("umamo.kmp-jvmandroid") + id("umamo.kmp-ios-gate") + id("umamo.test-corpus") +} + +kotlin { + jvmToolchain(21) + + // The `jvmAndroidMain` group comes from the `umamo.kmp-jvmandroid` convention plugin. This module + // needs it because the CMO3 export lowering (Cmo3Export) mutates a Cmo3Model graph, which lives in + // :format's own jvmAndroidMain (the JDOM-backed codec) — so it can't sit in commonMain. + + jvm() + + // The iPadOS ship target, mirroring :format and :runtime (see :format's docblock for the full + // rationale). It keeps the commonMain conversions (MOC3 ingest for a future iOS viewer, the CMO3 + // ingest and model diff) a compiler-checked iOS citizen rather than the root regex gate's + // convention. Compiles on Linux/CI (klib only, no Xcode linker); a device target has no runnable + // test task, so `umamo.kmp-ios-gate` wires `check` to the compiles. + iosArm64() + + android { + namespace = "org.umamo.interop" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + commonMain { + dependencies { + // Both `api` (not `implementation`): the conversion surface exposes both sides — + // CModelSource/Cmo3Model/MocDocument parameters from :format, PuppetModel and the + // diff types from :runtime — so consumers (:ui, tests) see them transitively. + api(project(":format")) + api(project(":runtime")) + } + } + commonTest { + dependencies { + implementation(kotlin("test")) + } + } + jvmTest { + dependencies { + // The skeleton gate compares emitted XML structure against the corpus blank; JDOM is + // :format's own (implementation-scoped) backend, so the test declares it directly. + implementation(libs.jdom) + // TEST-ONLY: the MOC3 conversion round trip mirrors the app's document loader, which + // normalizes rest meshes to canvas space through :render's evaluator before export + // (production :interop code never depends on :render - siblings over :runtime). + implementation(project(":render")) + } + } + } +} + +// Corpus wiring for the gated tests (the `umamo.test-corpus` convention plugin): +// `./gradlew :interop:jvmTest -Dcmo3.sample=… -Dmoc3.sample=… -Dmoc3.samples=…`. +// +// cmo3.sample and cmo3.probe take the shared corpus defaults, so Cmo3ImportTest's probe loop exercises +// the whole corpus by default when the local (gitignored) corpus is present; moc3.samples points at the +// whole moc3 tree, which CompositeImportTest joins against ingested CMO3s and the MOC3 export/downgrade +// round-trip gates walk in full. moc3.sample (singular, read by Moc3ImportTest's golden-count test) has +// no default and only takes effect when passed as -D. +umamoTestCorpus { + // The probe loop inflates every corpus CMO3 (Model C's main.xml alone is ~10 MB of JDOM). Raised + // from 4g when modelF joined the corpus: at 57.8 MB and ~6.5 M keyform vertex positions its + // MOC3→CMO3 conversion in Cmo3ConversionRoundTripTest OOMs at 4g and passes at 8g, because the + // conversion holds the PuppetModel and the whole synthesized JDOM graph at once. Do not trim this + // back without re-running that test against modelF. + maxHeap("8g") + sample("cmo3.sample", "cmo3.probe", "moc3.sample", "moc3.samples") +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/AtlasPageSet.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/AtlasPageSet.kt new file mode 100644 index 0000000..2ae55be --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/AtlasPageSet.kt @@ -0,0 +1,30 @@ +package org.umamo.interop + +/** + * A document's atlas pages as its source format carries them: the encoded page bytes plus which page + * each drawable samples. + * + * The format-neutral half of texture ingest. Every container answers "which pages are there, and who + * samples which" its own way - a CMO3 walks its drawable sources to embedded image resources, a MOC3 + * reads a per-mesh index into the manifest's texture list - but the answer is the same shape, and + * decoding it is not a format concern. So the walk lives here with the rest of the format ingest and + * the decode stays in the renderer, which is what keeps container knowledge out of `:render`. + * + * Pages are referenced by position: a drawable's value in [atlasIndexByDrawableId] indexes [pageBytes]. + * + * @property List pageBytes The encoded pages, in the source's own page order. + * @property Map atlasIndexByDrawableId Raw drawable id to its page's index in [pageBytes]. + * @property Boolean premultipliedAlpha The source's texture-upload-convention flag, carried + * through for the renderer's own record; it is not a claim about the encoded bytes, which are always + * straight alpha. Only CMO3 sets it. + */ +public class AtlasPageSet( + public val pageBytes: List, + public val atlasIndexByDrawableId: Map, + public val premultipliedAlpha: Boolean = false, +) { + public companion object { + /** No pages and nothing bound - what a document with no atlas ingests to. */ + public val EMPTY: AtlasPageSet = AtlasPageSet(emptyList(), emptyMap()) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/BlendModeMapping.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/BlendModeMapping.kt new file mode 100644 index 0000000..bbc083a --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/BlendModeMapping.kt @@ -0,0 +1,261 @@ +package org.umamo.interop + +import org.umamo.format.cmo3.model.gen.AlphaComposition +import org.umamo.format.cmo3.model.gen.ColorComposition +import org.umamo.format.moc3.moc.ConstantFlag +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode + +/* + * The blend-mode bijections shared by both importers, per the extraction tables in + * docs/plan/offscreen-support.md: CMO3 serializes enum tokens (ColorComposition / + * AlphaComposition), MOC3 packs ints (sections 153/157, colorMode or (alphaMode shl 8)). + * The bare legacy tokens (NORMAL/ADD/MULTIPLY) are the pre-5.3 modes in every era; each + * 5.3 mode has its own token and int. + */ + +/** + * Maps a CMO3 ColorComposition token to the runtime color blend mode. + * + * @param String? name The serialized enum constant name (e.g. "MULTIPLY_R2"), or null when absent. + * @return BlendMode The runtime mode; Normal for null or an unknown token. + */ +internal fun colorBlendOfToken(name: String?): BlendMode = + // CMO3: ColorComposition constants, matched by name (the generated enum is observed-only). + when (name) { + "NORMAL" -> BlendMode.Normal + "ADD" -> BlendMode.AdditivePremultiplied + "MULTIPLY" -> BlendMode.MultiplyPremultiplied + "ADD_R2_TSL" -> BlendMode.Additive + "ADD_R2" -> BlendMode.AdditiveGlow + "DARKEN" -> BlendMode.Darken + "MULTIPLY_R2" -> BlendMode.Multiply + "COLORBURN_TSL" -> BlendMode.ColorBurn + "LINEARBURN_TSL" -> BlendMode.LinearBurn + "LIGHTEN" -> BlendMode.Lighten + "SCREEN" -> BlendMode.Screen + "COLORDODGE_TSL" -> BlendMode.ColorDodge + "OVERLAY" -> BlendMode.Overlay + "SOFTLIGHT" -> BlendMode.SoftLight + "HARDLIGHT" -> BlendMode.HardLight + "LINEARLIGHT_TSL" -> BlendMode.LinearLight + "HSL_HUE" -> BlendMode.Hue + "HSL_COLOR" -> BlendMode.Color + else -> BlendMode.Normal + } + +/** + * Maps a runtime color blend mode to its CMO3 ColorComposition constant - the export inverse of + * [colorBlendOfToken]. + * + * @param BlendMode mode The runtime mode. + * @return ColorComposition The serialized enum constant. + */ +internal fun colorCompositionOf(mode: BlendMode): ColorComposition = + // CMO3: ColorComposition constants (see colorBlendOfToken's forward table). + when (mode) { + BlendMode.Normal -> ColorComposition.NORMAL + BlendMode.AdditivePremultiplied -> ColorComposition.ADD + BlendMode.MultiplyPremultiplied -> ColorComposition.MULTIPLY + BlendMode.Additive -> ColorComposition.ADD_R2_TSL + BlendMode.AdditiveGlow -> ColorComposition.ADD_R2 + BlendMode.Darken -> ColorComposition.DARKEN + BlendMode.Multiply -> ColorComposition.MULTIPLY_R2 + BlendMode.ColorBurn -> ColorComposition.COLORBURN_TSL + BlendMode.LinearBurn -> ColorComposition.LINEARBURN_TSL + BlendMode.Lighten -> ColorComposition.LIGHTEN + BlendMode.Screen -> ColorComposition.SCREEN + BlendMode.ColorDodge -> ColorComposition.COLORDODGE_TSL + BlendMode.Overlay -> ColorComposition.OVERLAY + BlendMode.SoftLight -> ColorComposition.SOFTLIGHT + BlendMode.HardLight -> ColorComposition.HARDLIGHT + BlendMode.LinearLight -> ColorComposition.LINEARLIGHT_TSL + BlendMode.Hue -> ColorComposition.HSL_HUE + BlendMode.Color -> ColorComposition.HSL_COLOR + } + +/** + * Maps a CMO3 AlphaComposition token to the runtime alpha blend mode. + * + * @param String? name The serialized enum constant name (e.g. "DISJOINT"), or null when absent + * (pre-5.3 sources carry no alpha mode). + * @return AlphaBlendMode The runtime mode; Over for null or an unknown token. + */ +internal fun alphaBlendOfToken(name: String?): AlphaBlendMode = + // CMO3: AlphaComposition constants, matched by name. + when (name) { + "OVER" -> AlphaBlendMode.Over + "ATOP" -> AlphaBlendMode.Atop + "OUT" -> AlphaBlendMode.Out + "CONJOINT" -> AlphaBlendMode.Conjoint + "DISJOINT" -> AlphaBlendMode.Disjoint + else -> AlphaBlendMode.Over + } + +/** + * Maps a runtime alpha blend mode to its CMO3 AlphaComposition constant - the export inverse of + * [alphaBlendOfToken]. + * + * @param AlphaBlendMode mode The runtime mode. + * @return AlphaComposition The serialized enum constant. + */ +internal fun alphaCompositionOf(mode: AlphaBlendMode): AlphaComposition = + // CMO3: AlphaComposition constants (see alphaBlendOfToken's forward table). + when (mode) { + AlphaBlendMode.Over -> AlphaComposition.OVER + AlphaBlendMode.Atop -> AlphaComposition.ATOP + AlphaBlendMode.Out -> AlphaComposition.OUT + AlphaBlendMode.Conjoint -> AlphaComposition.CONJOINT + AlphaBlendMode.Disjoint -> AlphaComposition.DISJOINT + } + +/** + * Unpacks the color half of a MOC3 packed blend int (sections 153/157). + * + * @param Int packed The stored int, colorMode or (alphaMode shl 8). + * @return BlendMode The runtime mode; Normal for an unknown colorMode. + */ +internal fun colorBlendOfPacked(packed: Int): BlendMode = + // MOC3 v6 §5.6 s153/s157: colorMode 0-17 in editor-dropdown order (legacy first). + when (packed and 0xFF) { + 0 -> BlendMode.Normal + 1 -> BlendMode.AdditivePremultiplied + 2 -> BlendMode.MultiplyPremultiplied + 3 -> BlendMode.Additive + 4 -> BlendMode.AdditiveGlow + 5 -> BlendMode.Darken + 6 -> BlendMode.Multiply + 7 -> BlendMode.ColorBurn + 8 -> BlendMode.LinearBurn + 9 -> BlendMode.Lighten + 10 -> BlendMode.Screen + 11 -> BlendMode.ColorDodge + 12 -> BlendMode.Overlay + 13 -> BlendMode.SoftLight + 14 -> BlendMode.HardLight + 15 -> BlendMode.LinearLight + 16 -> BlendMode.Hue + 17 -> BlendMode.Color + else -> BlendMode.Normal + } + +/** + * Unpacks the alpha half of a MOC3 packed blend int (sections 153/157). + * + * @param Int packed The stored int, colorMode or (alphaMode shl 8). + * @return AlphaBlendMode The runtime mode; Over for an unknown alphaMode. + */ +internal fun alphaBlendOfPacked(packed: Int): AlphaBlendMode = + // MOC3 v6 §5.6 s153/s157: alphaMode 0-4 in editor-dropdown order. + when ((packed shr 8) and 0xFF) { + 0 -> AlphaBlendMode.Over + 1 -> AlphaBlendMode.Atop + 2 -> AlphaBlendMode.Out + 3 -> AlphaBlendMode.Conjoint + 4 -> AlphaBlendMode.Disjoint + else -> AlphaBlendMode.Over + } + +/** + * The LEGACY 2-bit constant-flag encoding of [mode] - the only blend a moc below v6 can express. + * + * The pre-5.3 fixed-function set is just Normal / Add / Multiply, so every 5.3+ mode has to fall back + * to its nearest premultiplied ancestor: the 5.3 additive family reads as Add and the multiply family + * as Multiply, and anything with no fixed-function equivalent reads as Normal. A v6 export writes the + * packed extended blend instead and leaves these bits at Normal, so this is only reached when the + * target version genuinely cannot carry the authored mode. + * + * @param BlendMode mode The runtime blend mode. + * @return Int The constant-flag bits (0 for Normal). + */ +internal fun legacyBlendFlagOf(mode: BlendMode): Int = + when (nearestLegacyBlendMode(mode)) { + BlendMode.AdditivePremultiplied -> ConstantFlag.BLEND_ADDITIVE + BlendMode.MultiplyPremultiplied -> ConstantFlag.BLEND_MULTIPLICATIVE + else -> 0 + } + +/** + * The pre-5.3 mode [mode] degrades to when the target version cannot carry it. + * + * The same nearest-ancestor rule [legacyBlendFlagOf] encodes, as a runtime mode rather than as flag + * bits, so a version downgrade rewrites the MODEL to what the file will actually say instead of + * leaving the two to disagree about what "additive" means. + * + * @param BlendMode mode The authored blend mode. + * @return BlendMode The nearest mode a pre-5.3 runtime understands. + */ +internal fun nearestLegacyBlendMode(mode: BlendMode): BlendMode = + when (mode) { + BlendMode.AdditivePremultiplied, BlendMode.Additive, BlendMode.AdditiveGlow -> + BlendMode.AdditivePremultiplied + BlendMode.MultiplyPremultiplied, BlendMode.Multiply -> BlendMode.MultiplyPremultiplied + else -> BlendMode.Normal + } + +/** + * The constant-flag bits of [mode] when the pair names the mode EXACTLY, else 0. + * + * Unlike [legacyBlendFlagOf] this never approximates: only the two premultiplied modes have a legacy + * bit that means the same thing, so Additive (non-premultiplied), AdditiveGlow, and Multiply all read + * as Normal here. That is what a moc 6 offscreen's flag byte contains - every corpus offscreen sets + * the bit for colorMode 1 or 2 and clears it for every other mode - because on v6 the packed section + * is authoritative and these bits merely restate the two modes an old reader could have understood. + * + * Approximating here would state a mode the file does not, which is the failure the two names exist to + * keep apart: [legacyBlendFlagOf] is for a DOWNGRADE (the packed section is gone and the nearest + * ancestor is the best available), this is for an ECHO (the packed section is right there). + * + * @param BlendMode mode The runtime blend mode. + * @return Int The constant-flag bits (0 unless the mode is exactly additive- or multiply-premultiplied). + */ +internal fun exactLegacyBlendFlagOf(mode: BlendMode): Int = + when (mode) { + BlendMode.AdditivePremultiplied -> ConstantFlag.BLEND_ADDITIVE + BlendMode.MultiplyPremultiplied -> ConstantFlag.BLEND_MULTIPLICATIVE + else -> 0 + } + +/** + * Packs [color] and [alpha] into the MOC3 v6 blend int (sections 153 / 157). + * + * The exact inverse of [colorBlendOfPacked] and [alphaBlendOfPacked], written as the same ordinal + * tables read backwards so a mode added to one direction is a compile error in the other rather than a + * silently unpackable value. + * + * @param BlendMode color The runtime color blend mode. + * @param AlphaBlendMode alpha The runtime alpha blend mode. + * @return Int The stored int, `colorMode or (alphaMode shl 8)`. + */ +internal fun packedBlendOf(color: BlendMode, alpha: AlphaBlendMode): Int { + val colorMode = + when (color) { + BlendMode.Normal -> 0 + BlendMode.AdditivePremultiplied -> 1 + BlendMode.MultiplyPremultiplied -> 2 + BlendMode.Additive -> 3 + BlendMode.AdditiveGlow -> 4 + BlendMode.Darken -> 5 + BlendMode.Multiply -> 6 + BlendMode.ColorBurn -> 7 + BlendMode.LinearBurn -> 8 + BlendMode.Lighten -> 9 + BlendMode.Screen -> 10 + BlendMode.ColorDodge -> 11 + BlendMode.Overlay -> 12 + BlendMode.SoftLight -> 13 + BlendMode.HardLight -> 14 + BlendMode.LinearLight -> 15 + BlendMode.Hue -> 16 + BlendMode.Color -> 17 + } + val alphaMode = + when (alpha) { + AlphaBlendMode.Over -> 0 + AlphaBlendMode.Atop -> 1 + AlphaBlendMode.Out -> 2 + AlphaBlendMode.Conjoint -> 3 + AlphaBlendMode.Disjoint -> 4 + } + return colorMode or (alphaMode shl 8) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/ExportNotice.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/ExportNotice.kt new file mode 100644 index 0000000..67a63a5 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/ExportNotice.kt @@ -0,0 +1,169 @@ +package org.umamo.interop + +import org.umamo.runtime.model.RuntimeFeature + +/** + * One advisory finding from an export, CMO3 or MOC3. + * + * An export ALWAYS writes; notices only tell the user what the written file does not carry or what + * a Cubism-side edit could do to it. Nothing is ever silently dropped: every edit a lowering cannot + * yet (or can never) express in the target format surfaces as an [UnsupportedChange], and every + * feature the chosen target version predates surfaces as a [FeatureStripped]. + */ +sealed interface ExportNotice { + /** + * An edit the export lowering did not persist into the written file. + * + * @property ExportEntityCategory category The kind of thing the finding is about. + * @property String? subject The affected entity's id, or null for a document-level + * finding, whose [reason] names the field itself. + * @property ExportNoticeReason reason Why the lowering could not carry the edit. + */ + data class UnsupportedChange( + val category: ExportEntityCategory, + val subject: String?, + val reason: ExportNoticeReason, + ) : ExportNotice + + /** + * Drawables whose base geometry or UVs diverged from the imported geometry/UV weld. The export + * writes them as authored (the official editor renders the same displaced result Umamo shows), + * but Cubism couples geometry and UVs at the neutral form, so its own mesh-edit / re-atlas + * operations may re-derive and corrupt the mapping. + * + * @property List drawableNames The affected drawables' display names. + */ + data class WeldDivergence(val drawableNames: List) : ExportNotice + + /** + * A feature the export target's runtime cannot load, removed from the written file. + * + * Distinct from [UnsupportedChange], which reports what the lowering could not express: this one + * reports what the lowering deliberately took OUT because the chosen version predates it. The + * document itself keeps the feature - the strip runs on a copy - so re-exporting at a higher + * version brings it back. + * + * @property RuntimeFeature feature The stripped feature. + * @property List subjects The affected entities' display names, in document order. + */ + data class FeatureStripped( + val feature: RuntimeFeature, + val subjects: List, + ) : ExportNotice + + /** + * Not every drawable's art came from a real source layer, so the CMO3 was built around a + * fabricated source document - the whole file, for a MOC3-origin document, which has no source + * artwork at all. + * + * A CMO3 is organised around the layered art it was imported from; a MOC3 carries only packed + * atlas pages, so the export reconstructs a stand-in source document by slicing each drawable's + * patch back out of the atlas. The result opens and renders in the official Cubism Editor, and + * switches between its layered-art and texture-atlas display modes - but every layer in it is a + * slice of a baked page, not the artwork the rig was drawn from. What that costs is editable + * art: the layers cannot be redrawn upstream and refreshed, and their quality is capped by the + * page they were cut from. Reconciling the ORIGINAL layered art (PSD/CLIP/KRA) into the + * document is what replaces them with the real thing. + * + * @property Int pageCount The number of atlas pages the stand-in source was built from. + */ + data class MissingSourceArt(val pageCount: Int) : ExportNotice + + /** + * Drawables that share one atlas slot with a twin at another canvas placement and could not be + * given a slot of their own because their patch is too large for a page even on its own. A CMO3 + * model image carries a single canvas placement, so the official editor shows such a drawable at + * the first twin's placement in its layered-art display mode; the texture-atlas mode and the + * runtime are unaffected. A transparent twin (a hit area's) is not reported: nothing shows at + * either placement. + * + * @property List drawableNames The affected drawables' display names, in document order. + */ + data class SharedAtlasSlotKept(val drawableNames: List) : ExportNotice +} + +/** + * One log line for an export notice: what the editor's log and the command-line tool's report both print, + * the headless-visible mirror of the editor's report alert. + * + * Deliberately English and deliberately structural: the log is a diagnostic surface, read off a bug + * report rather than by a rigger mid-edit, so it wants text that is stable across locales and greps + * straight back to a call site. Printing the reason itself gives that for free and, unlike a second + * hand-written copy of the alert's prose, cannot drift from the case list it describes. + * + * @param ExportNotice notice The notice to describe. + * @return String The log text. + */ +fun describeExportNotice(notice: ExportNotice): String = + when (notice) { + is ExportNotice.UnsupportedChange -> + if (notice.subject == null) { + "[${notice.category}] ${notice.reason}" + } else { + "[${notice.category}] ${notice.subject}: ${notice.reason}" + } + is ExportNotice.WeldDivergence -> "weld divergence on ${notice.drawableNames.joinToString()}" + is ExportNotice.FeatureStripped -> + "${notice.feature} is not in the exported moc version; removed from " + + notice.subjects.take(8).joinToString() + + if (notice.subjects.size > 8) " (+${notice.subjects.size - 8} more)" else "" + is ExportNotice.MissingSourceArt -> + "no source artwork: the CMO3 was built around a stand-in document rebuilt from ${notice.pageCount} atlas page(s), " + + "so its layers are atlas slices rather than the original artwork" + is ExportNotice.SharedAtlasSlotKept -> + "twins sharing one atlas slot could not be given their own: " + + notice.drawableNames.take(8).joinToString() + + (if (notice.drawableNames.size > 8) " (+${notice.drawableNames.size - 8} more)" else "") + + "; the editor's layered view shows them at the first twin's placement" + } + +/** + * The kind of thing an [ExportNotice.UnsupportedChange] is about, naming the panel a rigger would + * look in to find it. + * + * An enum rather than the free text it replaces: the vocabulary was previously documented in a + * comment and enforced by nothing, so a typo produced a category no reader recognized, and the label + * could not be localized. [Keyform] is the odd member - a keyform is not an entity in its own right - + * but the notice's subject there is the owning drawable or part, so the rendered line still reads as + * a place to look. + */ +enum class ExportEntityCategory { + Parameter, + ParameterGroup, + Part, + Deformer, + Drawable, + Glue, + Document, + Keyform, +} + +/** + * The format one export wrote, naming which file family a report's findings are about. + * + * Deliberately narrower than [org.umamo.format.FileKind], which spans every family Umamo reads + * (art sources, sidecars, raster pages) - only the ones an export path writes belong here, so a + * `when` over an [ExportReport]'s format stays exhaustive without an `else` that would silently + * swallow a new export target. + */ +enum class ExportFormat { + Cmo3, + Moc3, +} + +/** + * The advisory outcome of one export: what the written file does not carry. + * + * The notice kinds are format-neutral because the contract is: an export ALWAYS writes, and notices + * only say what the written file does not carry. That holds identically for CMO3 and MOC3, so both + * report through this rather than through parallel types the UI would have to handle twice. The + * [format] is what keeps the report attributable: a reader (the alert's header, a log line) has to + * name the file family the findings are about, and no notice carries that on its own. + * + * @property ExportFormat format The format the export wrote. + * @property List notices The findings, empty for a fully-lowered export. + */ +data class ExportReport(val format: ExportFormat, val notices: List) { + /** True when the export lowered everything with nothing to warn about. */ + val isEmpty: Boolean get() = notices.isEmpty() +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/ExportNoticeReason.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/ExportNoticeReason.kt new file mode 100644 index 0000000..ded7c9c --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/ExportNoticeReason.kt @@ -0,0 +1,275 @@ +package org.umamo.interop + +import org.umamo.runtime.model.FormChannel + +/** + * Why one [ExportNotice.UnsupportedChange] fired: the closed vocabulary of things an export lowering + * cannot carry into the written file. + * + * Closed rather than free text so the reason can be LOCALIZED. The prose a rigger reads lives in the + * UI's string catalog, keyed off the case; this module stays presentation-free and carries only the + * structured facts a sentence needs. That is the same split [ExportNotice.FeatureStripped] already + * uses for its [org.umamo.runtime.model.RuntimeFeature], generalized to every finding. + * + * Two rules hold across every case, and both are load-bearing: + * + * - Every case is a `data object` or `data class`, never a bare `object`. The log mirror in the app + * prints the reason with `toString()`, so a bare object would emit an identity hash instead of a + * name. ExportNoticeReasonTest pins this. + * - Ids are plain [String], not the typed `ParameterId`/`DrawableId` wrappers. A report is a display + * carrier rather than a model - [ExportNotice.UnsupportedChange.subject] and + * [ExportNotice.FeatureStripped.subjects] are already plain strings - and a value class would render + * as `ParameterId(raw=ParamAngleX)` in every log line. [FormChannel] is the one typed field, because + * it is a localizable enum rather than user data. + * + * The cases are declared here in commonMain even where only the CMO3 lowering produces them: :interop + * builds an iosArm64 target that never sees jvmAndroidMain, so a member declared there would break the + * exhaustive `when` the UI does over this hierarchy. + */ +sealed interface ExportNoticeReason { + // Shared - fired by both export paths. + + /** The drawable carries no mesh, so there is no geometry to write. */ + data object DrawableHasNoMesh : ExportNoticeReason + + // MOC3 lowering. + + /** + * A channel keyed over a narrower span than its object's grid, written as a constant instead. + * + * @property FormChannel channel The demoted channel. + */ + data class ChannelDemotedToStatic(val channel: FormChannel) : ExportNoticeReason + + /** A guide-image (sketch) part holds authoring aids, not runtime content. */ + data object SketchPartIsNotRuntimeContent : ExportNoticeReason + + /** A hidden part's subtree was left out because the export options omit hidden parts. */ + data object HiddenPartOmittedByExportOption : ExportNoticeReason + + /** A hidden art mesh was left out because the export options omit hidden drawables. */ + data object HiddenDrawableOmittedByExportOption : ExportNoticeReason + + /** An unkeyed drawable under a deformer has no parent-space geometry the moc could store. */ + data object UnkeyedDrawableUnderDeformerHasNoParentGeometry : ExportNoticeReason + + /** + * The canvas-to-parent conversion returned a different coordinate count than the mesh has. + * + * @property Int convertedCoordinateCount The count the conversion returned. + * @property Int expectedCoordinateCount The count the mesh carries. + */ + data class RestMeshConversionSizeMismatch( + val convertedCoordinateCount: Int, + val expectedCoordinateCount: Int, + ) : ExportNoticeReason + + /** No atlas page is bound to the drawable, so its texture index fell back to page 0. */ + data object NoAtlasPageBound : ExportNoticeReason + + /** + * A clipping mask names drawables this export does not contain. + * + * @property List maskDrawableIds The masking drawables that were left out. + */ + data class ClippingMaskNotInExport(val maskDrawableIds: List) : ExportNoticeReason + + /** An offscreen's clipping mask names a drawable that could not be written. */ + data object OffscreenMaskNotInExport : ExportNoticeReason + + /** A warp deformer carries no control-point grid, so it has no lattice to write. */ + data object WarpDeformerHasNoLattice : ExportNoticeReason + + /** A rotation deformer carries no pivot grid, so it has no transform to write. */ + data object RotationDeformerHasNoPivot : ExportNoticeReason + + /** A glue names a drawable that is not in this export. */ + data object GlueNamesAnUnknownDrawable : ExportNoticeReason + + /** + * An id too long for a moc's fixed-width id record, written shortened. + * + * @property Int recordByteWidth The record's width in bytes. + * @property String writtenId The id that was actually written. + */ + data class IdTruncated(val recordByteWidth: Int, val writtenId: String) : ExportNoticeReason + + /** + * An id too long for the record whose truncation ALSO collided with another object's id, so a + * disambiguating suffix was fitted into the same width. + * + * @property Int recordByteWidth The record's width in bytes. + * @property String writtenId The id that was actually written. + */ + data class IdTruncatedAndDisambiguated( + val recordByteWidth: Int, + val writtenId: String, + ) : ExportNoticeReason + + // CMO3 reconcile - an edit with no counterpart in the retained graph. + + /** The edited entity has no matching CMO3 source to reconcile the change onto. */ + data object NoMatchingSourceToReconcile : ExportNoticeReason + + /** A parameter changed between normal and blend-shape kind, which the lowering cannot express. */ + data object ParameterKindChangeNotLowered : ExportNoticeReason + + /** A deformer changed kind, which the lowering cannot express. */ + data object DeformerKindChangeNotLowered : ExportNoticeReason + + /** A warp-only edit (bilinear mode, lattice, keyforms) whose CMO3 source is not a warp deformer. */ + data object DeformerEditNeedsWarpSource : ExportNoticeReason + + /** A rotation-only edit (base angle, keyforms) whose CMO3 source is not a rotation deformer. */ + data object DeformerEditNeedsRotationSource : ExportNoticeReason + + /** Which texture a drawable samples is editor-only state that CMO3 does not carry. */ + data object TextureSourceRebindingIsEditorOnly : ExportNoticeReason + + /** The edited base geometry has a different vertex count than its CMO3 source. */ + data object BaseGeometryVertexCountMismatch : ExportNoticeReason + + /** The drawable has no UVs to reconcile. */ + data object NoUvsToReconcile : ExportNoticeReason + + /** The deformer was reparented to a part that has no CMO3 counterpart. */ + data object DeformerHasNoPartToMoveTo : ExportNoticeReason + + /** + * A static draw order that disagrees with its own keyform track. + * + * CMO3 re-derives the static from the track's head cell on import, so a disagreeing static has + * nowhere to live independently. + */ + data object StaticDrawOrderShadowedByKeyforms : ExportNoticeReason + + /** A composite's static values disagree with the part's keyform tracks, which shadow them. */ + data object CompositeStaticsShadowedByKeyforms : ExportNoticeReason + + /** Part-typed composite masks are an Umamo extension; CMO3 carries only drawable-typed masks. */ + data object PartMasksFlattenToDrawables : ExportNoticeReason + + // CMO3 structural creation - a new entity with nowhere to be created. + + /** The CMO3 model has no set of this kind to create the new entity into. */ + data object NoSourceSetToCreateInto : ExportNoticeReason + + /** The entity was created this session and has no CMO3 source yet, so panel order skipped it. */ + data object CreatedEntityHasNoSourceYet : ExportNoticeReason + + /** The created group is not in the edited parameter tree. */ + data object CreatedGroupIsNotInTheEditedTree : ExportNoticeReason + + /** The created drawable has no texture source to clone a CMO3 image chain from. */ + data object CreatedDrawableHasNoTextureSource : ExportNoticeReason + + /** A glued drawable has no CMO3 source, so the glue could not be synthesized. */ + data object GluedDrawableHasNoSource : ExportNoticeReason + + // CMO3 mesh topology and glue re-binding. + + /** + * A mesh with more vertices than the editable mesh's short-indexed edge table can address. + * + * @property Int vertexCount The mesh's vertex count. + * @property Int maximumVertexCount The most the edge table can index. + */ + data class VertexCountExceedsEdgeTable( + val vertexCount: Int, + val maximumVertexCount: Int, + ) : ExportNoticeReason + + /** A glued mesh has no editable-mesh vertex-id table to re-bind the glue against. */ + data object GluedMeshHasNoUidTable : ExportNoticeReason + + /** A glue pair indexes past its mesh's vertex-id table. */ + data object GluePairIndexesPastUidTable : ExportNoticeReason + + // CMO3 keyforms. + + /** + * A keyform set that will not bundle into the single grid CMO3 stores per object. + * + * @property KeyformBundleRejection rejection Which bundling rule the keyforms broke. + */ + data class KeyformCannotBundle(val rejection: KeyformBundleRejection) : ExportNoticeReason + + /** + * A grid axis whose parameter has no CMO3 source. + * + * @property String parameterId The axis parameter's id. + */ + data class AxisParameterHasNoSource(val parameterId: String) : ExportNoticeReason + + /** + * A blend shape whose parameter has no CMO3 source. + * + * @property String parameterId The blend-shape parameter's id. + */ + data class BlendShapeParameterHasNoSource(val parameterId: String) : ExportNoticeReason + + /** Keyforms with no base mesh to bundle against. */ + data object KeyformsWithoutBaseMesh : ExportNoticeReason + + /** A fractional draw order, where CMO3 stores a whole number. */ + data object FractionalDrawOrderNotStorable : ExportNoticeReason + + /** A static glue intensity with no keyforms, which CMO3 has nowhere to put. */ + data object StaticGlueIntensityWithoutKeyforms : ExportNoticeReason + + // CMO3 document fields. The notice's subject is null for these - the reason names its own field, + // because the field name is chrome and would otherwise be untranslated English in the subject. + + /** CMO3 stores no authored world origin; reopening derives it from the canvas center. */ + data object NoAuthoredWorldOrigin : ExportNoticeReason + + /** The model has no root parameter group to rebuild the parameter tree against. */ + data object NoRootParameterGroup : ExportNoticeReason + + /** The model has no root part to rebuild the parts panel order against. */ + data object NoRootPart : ExportNoticeReason + + /** The model has no parameter set to write a parameter order into. */ + data object NoParameterSourceSet : ExportNoticeReason + + /** + * The parameter order was adjusted to keep a combined pair adjacent, as CMO3 requires. + * + * @property String horizontalParameterId The pair's horizontal parameter id. + * @property String verticalParameterId The pair's vertical parameter id. + */ + data class CombinedPairReordered( + val horizontalParameterId: String, + val verticalParameterId: String, + ) : ExportNoticeReason + + /** The model has no canvas to reconcile a size against. */ + data object NoCanvasToReconcile : ExportNoticeReason + + /** The document carries no texture manager, so the source-artwork display mode has nowhere to go. */ + data object NoTextureManagerToReconcile : ExportNoticeReason + + /** The drawable lacks the texture input the chosen display mode samples, so its pointer was left as-is. */ + data object NoTextureInputForDisplayMode : ExportNoticeReason + + /** A fractional canvas size, where CMO3 stores whole pixels. */ + data object FractionalCanvasSizeNotStorable : ExportNoticeReason + + /** The tile has no packed entry on any atlas page, so there is no placement in the file to move. */ + data object NoAtlasEntryToReconcile : ExportNoticeReason + + /** + * A placement moved, but the page's stored pixels were not rebuilt to match. + * + * Where the art is RECORDED to sit is model state; the page image is the document's, and nothing + * here recomposes it. The written file is a faithful export of what was authored, and its atlas + * page still shows the art at its old spot until a repack redraws it. + */ + data object AtlasPageNotRecomposed : ExportNoticeReason + + /** The tile's own art changed - its name, size, or source layer - which a repack cannot express. */ + data object AtlasTileMetadataNotReconcilable : ExportNoticeReason + + /** The drawable was rebound to different source art, which needs the art re-imported, not repacked. */ + data object AtlasTileRebindingNotLowered : ExportNoticeReason +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/KeyformBundle.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/KeyformBundle.kt new file mode 100644 index 0000000..e099d68 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/KeyformBundle.kt @@ -0,0 +1,291 @@ +package org.umamo.interop + +import org.umamo.runtime.eval.EPS_KEY +import org.umamo.runtime.keyform.ChannelValueInterpolator +import org.umamo.runtime.keyform.FormInterpolator +import org.umamo.runtime.keyform.refinedToUnion +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId + +/* + * Re-bundles a runtime entity's SPLIT keyform representation - one geometry grid plus independent + * per-channel tracks - back into the single dense grid every source format stores. + * + * The runtime deliberately keeps geometry and each render channel on their own axes so a rigger + * can key opacity without touching the mesh. Both CMO3 and MOC3 store one grid per object + * instead, with every cell carrying every value, so an export has to union the axes and + * re-interpolate each part onto the result. That inversion is exactly `refinedToUnion`'s + * contract, and doing it identically for both formats is the point of this file: two + * independent copies would drift the moment one gained a clamp or a tolerance the other lacked, + * and only a differential oracle would ever notice. + * + * @see CMO3.md §6 Export + * @see MOC3.md §8 Export + */ + +/** What to do with a channel whose keyed span does not cover the bundled union axes. */ +enum class OutOfSpanPolicy { + /** + * Reject the whole owner: the export cannot represent it and says so. + * + * CMO3's choice - a partially-representable owner would silently change the rig's shape, and CMO3 + * can simply decline to write that object's grid. + */ + RejectOwner, + + /** + * Drop the offending channel to its static value and bundle the rest, naming what was demoted. + * + * MOC3's choice, and not a preference: every MOC3 object MUST carry at least one keyform, so + * rejecting the owner would mean emitting nothing for it and producing a file the runtime cannot + * load. Losing one channel's animation is the strictly smaller loss. + */ + DemoteChannel, +} + +/** One re-bundled cell: its coordinate, per-parameter key values, geometry, and channel values. */ +class KeyformBundleCell( + val coordinate: IntArray, + val values: Map, + val geometry: Any?, + val channels: Map, +) + +/** + * A dense bundled grid: the union axes and every cell of their cross product. + * + * @property List axes The union axes, geometry axes first. + * @property List cells Every cell, in first-axis-fastest order. + * @property List demotedChannels Channels dropped to their static under [OutOfSpanPolicy.DemoteChannel]. + */ +class KeyformBundle( + val axes: List, + val cells: List, + val demotedChannels: List = emptyList(), +) + +/** The outcome of a bundling attempt. */ +sealed interface KeyformBundleResult { + /** The entity bundled; [bundle] may still name demoted channels. */ + class Bundled(val bundle: KeyformBundle) : KeyformBundleResult + + /** + * The split state cannot be expressed as one grid, and the caller must report it. + * + * @property KeyformBundleRejection rejection Which bundling rule the keyforms broke. + */ + data class Unrepresentable(val rejection: KeyformBundleRejection) : KeyformBundleResult +} + +/** + * Why a bundling attempt failed, for the caller to lower into an export notice. + * + * The bundler owns this vocabulary rather than [ExportNoticeReason] because the rule that was broken + * is a fact about bundling, not about any one format - the CMO3 lowering wraps it in + * [ExportNoticeReason.KeyformCannotBundle], and a future format would wrap the same cases its own way. + * Format-neutral for the same reason: the "one grid per object" clause a reader sees is supplied by + * the wrapping notice, not baked in here. + */ +sealed interface KeyformBundleRejection { + /** Geometry keys fall outside the union span, and geometry is never demotable. */ + data object KeysOutsideGeometrySpan : KeyformBundleRejection + + /** Channels key but there is no geometry to hang them on, where the caller requires geometry. */ + data object ChannelKeysWithoutGeometry : KeyformBundleRejection + + /** + * A channel keys outside its track span, under a policy that rejects the owner rather than + * demoting the channel. + * + * @property FormChannel channel The offending channel. + */ + data class KeysOutsideChannelSpan(val channel: FormChannel) : KeyformBundleRejection +} + +/** + * Re-bundles a split representation onto union axes. + * + * The axis ORDER follows the geometry grid first, which is the order the import's fan-out preserved - + * so a round trip through split-then-bundled keeps the source's own axis order rather than inventing + * one. Cells are emitted first-axis-fastest, matching the mixed radix both formats index with. + * + * @param KeyformGrid? geometryGrid The geometry grid, or null for a channel-only owner. + * @param FormInterpolator geometryBlend The geometry interpolator (unused when there is no geometry). + * @param ChannelGrids channels The owner's channel tracks. + * @param Map statics Fallback value per relevant channel. + * @param Boolean requireGeometry Whether a geometry-less bundle is an error (warp/rotation). + * @param OutOfSpanPolicy outOfSpanPolicy What to do with a channel whose span misses the union. + * @return KeyformBundleResult The bundle - possibly with empty axes when fully unkeyed - or a rejection. + */ +fun buildKeyformBundle( + geometryGrid: KeyformGrid?, + geometryBlend: FormInterpolator, + channels: ChannelGrids, + statics: Map, + requireGeometry: Boolean, + outOfSpanPolicy: OutOfSpanPolicy, +): KeyformBundleResult { + // Union keys per parameter, geometry axes first so the bundled axis order follows the + // geometry grid (the order the import's fan-out preserved). + val unionKeys = LinkedHashMap() + + fun mergeAxis(axis: KeyformAxis) { + val existing = unionKeys[axis.parameterId] + unionKeys[axis.parameterId] = + if (existing == null) axis.keys.copyOf() else mergedKeys(existing, axis.keys) + } + geometryGrid?.axes?.forEach(::mergeAxis) + for (grid in channels.gridsByChannel.values) { + grid.axes.forEach(::mergeAxis) + } + if (unionKeys.isEmpty()) { + // No parameter keys anywhere. An axis-less grid (one static cell) is a real shape in both + // formats and keeps its single cell; a grid-less, channel-less owner is fully unkeyed (empty). + // + // AXIS-LESS IS NOT VALUE-LESS. A channel track can be a single cell with no axes - an authored + // constant that was never lifted into the owner's static - and that value must win over the + // static, which in that state still holds its untouched constructor default. Falling straight + // back to the statics here would silently replace every such value. + val channelValues = + buildMap { + for ((channel, staticValue) in statics) { + put(channel, channels.gridsByChannel[channel]?.cells?.firstOrNull()?.form ?: staticValue) + } + } + val staticCell = geometryGrid?.cells?.firstOrNull() + if (staticCell != null) { + return KeyformBundleResult.Bundled( + KeyformBundle( + emptyList(), + listOf(KeyformBundleCell(IntArray(0), emptyMap(), staticCell.form, channelValues)), + ), + ) + } + // A geometry-less owner whose channels are all axis-less still has one cell's worth of values; + // emitting nothing would make the caller fall back to the same statics this just corrected. + if (channels.gridsByChannel.isNotEmpty()) { + return KeyformBundleResult.Bundled( + KeyformBundle(emptyList(), listOf(KeyformBundleCell(IntArray(0), emptyMap(), null, channelValues))), + ) + } + return KeyformBundleResult.Bundled(KeyformBundle(emptyList(), emptyList())) + } + + // Refine geometry over its own axes only (an empty ranges map suppresses the append path); every + // axis must then carry exactly the union keys - a span that does not cover them means an + // out-of-span key the bundle cannot represent without inventing values. + var axes: List + var geometryByCoordinate: Map, TGeometry> + if (geometryGrid != null) { + val refined = geometryGrid.refinedToUnion(unionKeys, emptyMap(), geometryBlend) + for (axis in refined.axes) { + if (!axis.keys.contentEquals(unionKeys.getValue(axis.parameterId))) { + // Geometry is never demotable - it is the thing being exported. + return KeyformBundleResult.Unrepresentable(KeyformBundleRejection.KeysOutsideGeometrySpan) + } + } + axes = refined.axes + geometryByCoordinate = refined.cells.associate { cell -> cell.coordinate.toList() to cell.form } + // Replicate across parameters only channels key (the value is constant along them). + for ((parameterId, keys) in unionKeys) { + if (axes.none { it.parameterId == parameterId }) { + axes = axes + KeyformAxis(parameterId, keys) + geometryByCoordinate = + buildMap { + for (keyIndex in keys.indices) { + for ((coordinate, form) in geometryByCoordinate) { + put(coordinate + keyIndex, form) + } + } + } + } + } + } else { + if (requireGeometry) { + return KeyformBundleResult.Unrepresentable(KeyformBundleRejection.ChannelKeysWithoutGeometry) + } + axes = unionKeys.map { (parameterId, keys) -> KeyformAxis(parameterId, keys) } + geometryByCoordinate = emptyMap() + } + + // Refine each channel over its own axes; a final-coordinate lookup then projects onto the + // channel's axis subset (the channel is constant along axes it does not key). + val channelLookups = HashMap ChannelValue?>() + val demotedChannels = ArrayList() + val finalAxisPosition = axes.mapIndexed { position, axis -> axis.parameterId to position }.toMap() + for ((channel, track) in channels.gridsByChannel) { + val refined = track.refinedToUnion(unionKeys, emptyMap(), ChannelValueInterpolator) + val outOfSpan = + refined.axes.any { axis -> !axis.keys.contentEquals(unionKeys.getValue(axis.parameterId)) } + if (outOfSpan) { + if (outOfSpanPolicy == OutOfSpanPolicy.RejectOwner) { + return KeyformBundleResult.Unrepresentable( + KeyformBundleRejection.KeysOutsideChannelSpan(channel), + ) + } + // Demoted: no lookup is registered, so every cell falls back to the channel's static below. + demotedChannels.add(channel) + continue + } + val subPositions = + refined.axes.map { axis -> finalAxisPosition.getValue(axis.parameterId) }.toIntArray() + channelLookups[channel] = + { coordinate -> + val subCoordinate = IntArray(subPositions.size) { axisIndex -> coordinate[subPositions[axisIndex]] } + refined.cellsByLinearIndex[refined.linearIndexOf(subCoordinate)]?.form + } + } + + // Assemble every cell of the dense final grid. + val keyCounts = axes.map { it.keys.size } + val totalCells = keyCounts.fold(1) { product, count -> product * count } + val cells = ArrayList(totalCells) + val coordinate = IntArray(axes.size) + for (cellOrdinal in 0 until totalCells) { + var remainder = cellOrdinal + for (axisIndex in axes.indices) { + coordinate[axisIndex] = remainder % keyCounts[axisIndex] + remainder /= keyCounts[axisIndex] + } + val cellCoordinate = coordinate.copyOf() + val values = + buildMap { + for (axisIndex in axes.indices) { + put(axes[axisIndex].parameterId, axes[axisIndex].keys[cellCoordinate[axisIndex]]) + } + } + val channelValues = + buildMap { + for ((channel, staticValue) in statics) { + put(channel, channelLookups[channel]?.invoke(cellCoordinate) ?: staticValue) + } + } + cells.add( + KeyformBundleCell(cellCoordinate, values, geometryByCoordinate[cellCoordinate.toList()], channelValues), + ) + } + return KeyformBundleResult.Bundled(KeyformBundle(axes, cells, demotedChannels)) +} + +/** + * The two key arrays merged ascending with evaluator-tolerance duplicates dropped. + * + * @param FloatArray first One axis's keys. + * @param FloatArray second The other's. + * @return FloatArray The merged ascending keys. + */ +private fun mergedKeys(first: FloatArray, second: FloatArray): FloatArray { + val sorted = (first + second).sortedArray() + val kept = ArrayList(sorted.size) + for (candidate in sorted) { + // The evaluator's own key-snap tolerance: two keys it cannot tell apart stay one key. + if (kept.isEmpty() || candidate - kept.last() >= EPS_KEY) { + kept.add(candidate) + } + } + return kept.toFloatArray() +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/PuppetModelDiff.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/PuppetModelDiff.kt new file mode 100644 index 0000000..ae89f34 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/PuppetModelDiff.kt @@ -0,0 +1,855 @@ +package org.umamo.interop + +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.runtime.model.lineageRoot + +/* + * The semantic diff between two PuppetModels - the input the CMO3 export reconcile dispatches on. + * + * The exporter never consumes the editor's Change log: it compares the session's FINAL model against + * a baseline re-imported from the retained CMO3 graph, so deletion is "baseline entity absent from + * the edited model", creation is the reverse, and an empty diff proves the graph needs no touch at + * all (which is what makes the no-change byte-identity gate structural rather than accidental). + * + * Completeness is the load-bearing property: any semantic difference between the two models MUST + * surface in some field below, because an edit the diff misses is an edit the export silently drops. + * Comparisons are bit-exact (FloatArray.contentEquals semantics; raw bits for loose scalars) - the + * diff's job is to detect that anything changed, not to judge whether the change is significant. + */ + +/** The changed aspects of a [Parameter]. */ +enum class ParameterField { NAME, RANGE, KIND } + +/** The changed aspects of a [ParameterNode.Group]. */ +enum class ParameterGroupField { NAME, INITIALLY_OPEN, CHILDREN } + +/** The changed aspects of a [Part]. */ +enum class PartField { NAME, VISIBLE, SKETCH, SELECTABLE, GROUP_MODE, DRAW_ORDER, CHILDREN, CHANNELS, COMPOSITE } + +/** The changed aspects of a [Deformer]. */ +enum class DeformerField { + KIND, + NAME, + PARENT, + PART, + SELECTABLE, + LATTICE, + QUAD_TRANSFORM, + BASE_ANGLE, + GEOMETRY, + CHANNELS, + STATICS, + BLEND_SHAPES, +} + +/** The changed aspects of a [Drawable]. */ +enum class DrawableField { + NAME, + PARENT_DEFORMER, + BLEND_MODE, + ALPHA_BLEND_MODE, + MASKED_BY, + INVERT_MASK, + CULLING, + VISIBLE, + SELECTABLE, + TEXTURE_SOURCE, + ATLAS_TILE, + MESH_TOPOLOGY, + MESH_POSITIONS, + MESH_UVS, + GEOMETRY, + CHANNELS, + STATICS, + BLEND_SHAPES, +} + +/** The changed aspects of a [Glue]. */ +enum class GlueField { PAIRS, CHANNELS, INTENSITY } + +/** The changed aspects of an [AtlasTile]. */ +enum class AtlasTileField { + /** Where the tile's art sits on its page - the authored half, and the only one an edit produces. */ + PLACEMENT, + + /** Its name, pixel size, or source binding: what the art itself is, not where it was packed. */ + METADATA, +} + +/** The changed document-level aspects of a [PuppetModel]. */ +enum class DocumentField { + CANVAS_SIZE, + WORLD_ORIGIN, + RUNTIME_TARGET, + SOURCE_LAYER_DISPLAY, + PARAMETER_ORDER, + PARAMETER_LINKS, + PARAMETER_TREE, + ROOT_CHILDREN, + ATLAS_PAGES, + SOURCE_FILES, +} + +/** + * One entity's difference between the baseline and the edited model: present only in the edited + * model (Created), only in the baseline (Deleted), or in both with changed fields (Changed). + */ +sealed interface EntityDiff { + /** The entity's id in whichever model carries it. */ + val id: TId + + /** An entity the edited model has and the baseline does not - it needs CMO3-side synthesis. */ + data class Created(override val id: TId) : EntityDiff + + /** An entity the baseline has and the edited model does not - its CMO3 node must be removed. */ + data class Deleted(override val id: TId) : EntityDiff + + /** An entity present in both models whose [fields] differ. */ + data class Changed(override val id: TId, val fields: Set) : EntityDiff +} + +/** + * One glue's difference. A glue has no id (CGlueSource carries none), so it is keyed by its + * ordered mesh pair plus an ordinal among glues sharing that pair. + */ +sealed interface GlueDiff { + val meshA: DrawableId + val meshB: DrawableId + val ordinal: Int + + /** A glue only the edited model has. */ + data class Created( + override val meshA: DrawableId, + override val meshB: DrawableId, + override val ordinal: Int, + ) : GlueDiff + + /** A glue only the baseline has. */ + data class Deleted( + override val meshA: DrawableId, + override val meshB: DrawableId, + override val ordinal: Int, + ) : GlueDiff + + /** A glue present in both models whose [fields] differ. */ + data class Changed( + override val meshA: DrawableId, + override val meshB: DrawableId, + override val ordinal: Int, + val fields: Set, + ) : GlueDiff +} + +/** + * The complete semantic difference between a baseline and an edited [PuppetModel]. + * + * @property List parameters Per-parameter diffs. + * @property List parameterGroups Per-parameter-panel-group diffs (groups flattened out of the tree). + * @property List parts Per-part diffs. + * @property List deformers Per-deformer diffs. + * @property List drawables Per-drawable diffs. + * @property List glues Per-glue diffs. + * @property List atlasTiles Per-atlas-tile diffs. + * @property Set document Document-level field diffs. + */ +data class PuppetDiff( + val parameters: List>, + val parameterGroups: List>, + val parts: List>, + val deformers: List>, + val drawables: List>, + val glues: List, + val atlasTiles: List>, + val document: Set, +) { + /** True when the models are semantically identical and the export graph needs no touch. */ + val isEmpty: Boolean + get() = + parameters.isEmpty() && + parameterGroups.isEmpty() && + parts.isEmpty() && + deformers.isEmpty() && + drawables.isEmpty() && + glues.isEmpty() && + atlasTiles.isEmpty() && + document.isEmpty() +} + +/** + * Diffs [edited] against [baseline] (the model re-imported from the retained CMO3 graph). + * + * @param PuppetModel baseline The graph-derived baseline. + * @param PuppetModel edited The session's current model. + * @return PuppetDiff The complete semantic difference. + */ +fun diffPuppetModels(baseline: PuppetModel, edited: PuppetModel): PuppetDiff = + PuppetDiff( + parameters = diffEntities(baseline.parameters, edited.parameters, Parameter::id, ::parameterFields), + parameterGroups = + diffEntities( + flattenGroups(baseline.parameterTree), + flattenGroups(edited.parameterTree), + ParameterNode.Group::id, + ::parameterGroupFields, + ), + parts = diffEntities(baseline.parts, edited.parts, Part::id, ::partFields), + deformers = diffEntities(baseline.deformers, edited.deformers, Deformer::id, ::deformerFields), + drawables = diffEntities(baseline.drawables, edited.drawables, Drawable::id, ::drawableFields), + glues = diffGlues(baseline.glues, edited.glues), + atlasTiles = diffAtlasTiles(baseline.atlas.tiles, edited.atlas.tiles), + document = documentFields(baseline, edited), + ) + +/** + * Generic per-category entity diff: keys both lists by id, emits Created/Deleted for one-sided ids + * and Changed for shared ids whose [changedFields] set is non-empty. Baseline-order for stability. + * + * @param List baselineEntities The baseline's entities. + * @param List editedEntities The edited model's entities. + * @param Function idOf The entity's id accessor. + * @param Function changedFields The field comparator for a shared id. + * @return List The category's diffs, empty when nothing differs. + */ +private inline fun diffEntities( + baselineEntities: List, + editedEntities: List, + idOf: (TEntity) -> TId, + changedFields: (TEntity, TEntity) -> Set, +): List> { + val baselineById = baselineEntities.associateBy(idOf) + val editedById = editedEntities.associateBy(idOf) + val diffs = ArrayList>() + for (baselineEntity in baselineEntities) { + val entityId = idOf(baselineEntity) + val editedEntity = editedById[entityId] + if (editedEntity == null) { + diffs.add(EntityDiff.Deleted(entityId)) + continue + } + if (baselineEntity === editedEntity) { + continue + } + val fields = changedFields(baselineEntity, editedEntity) + if (fields.isNotEmpty()) { + diffs.add(EntityDiff.Changed(entityId, fields)) + } + } + for (editedEntity in editedEntities) { + val entityId = idOf(editedEntity) + if (entityId !in baselineById) { + diffs.add(EntityDiff.Created(entityId)) + } + } + return diffs +} + +private fun parameterFields(baseline: Parameter, edited: Parameter): Set = + buildSet { + if (baseline.name != edited.name) { + add(ParameterField.NAME) + } + if (!floatEq(baseline.min, edited.min) || !floatEq(baseline.max, edited.max) || !floatEq(baseline.default, edited.default)) { + add(ParameterField.RANGE) + } + if (baseline.kind != edited.kind) { + add(ParameterField.KIND) + } + } + +private fun parameterGroupFields(baseline: ParameterNode.Group, edited: ParameterNode.Group): Set = + buildSet { + if (baseline.name != edited.name) { + add(ParameterGroupField.NAME) + } + if (baseline.initiallyOpen != edited.initiallyOpen) { + add(ParameterGroupField.INITIALLY_OPEN) + } + if (nodeIdentities(baseline.children) != nodeIdentities(edited.children)) { + add(ParameterGroupField.CHILDREN) + } + } + +private fun partFields(baseline: Part, edited: Part): Set = + buildSet { + if (baseline.name != edited.name) { + add(PartField.NAME) + } + if (baseline.isVisible != edited.isVisible) { + add(PartField.VISIBLE) + } + if (baseline.isSketch != edited.isSketch) { + add(PartField.SKETCH) + } + if (baseline.isSelectable != edited.isSelectable) { + add(PartField.SELECTABLE) + } + if (baseline.groupMode != edited.groupMode) { + add(PartField.GROUP_MODE) + } + if (baseline.drawOrder != edited.drawOrder) { + add(PartField.DRAW_ORDER) + } + if (baseline.children != edited.children) { + add(PartField.CHILDREN) + } + if (!channelGridsEqual(baseline.channelGrids, edited.channelGrids)) { + add(PartField.CHANNELS) + } + if (baseline.composite != edited.composite) { + add(PartField.COMPOSITE) + } + } + +private fun deformerFields(baseline: Deformer, edited: Deformer): Set = + buildSet { + if (baseline::class != edited::class) { + // A kind swap under one id has no edit op; surfacing it beats mis-reading field diffs. + add(DeformerField.KIND) + return@buildSet + } + if (baseline.name != edited.name) { + add(DeformerField.NAME) + } + if (baseline.parent != edited.parent) { + add(DeformerField.PARENT) + } + if (baseline.partId != edited.partId) { + add(DeformerField.PART) + } + if (baseline.isSelectable != edited.isSelectable) { + add(DeformerField.SELECTABLE) + } + when (baseline) { + is Deformer.Warp -> { + val editedWarp = edited as Deformer.Warp + if (baseline.rows != editedWarp.rows || baseline.columns != editedWarp.columns) { + add(DeformerField.LATTICE) + } + if (baseline.isQuadTransform != editedWarp.isQuadTransform) { + add(DeformerField.QUAD_TRANSFORM) + } + if (!gridEquals(baseline.geometryGrid, editedWarp.geometryGrid, ::warpLatticeFormEqual)) { + add(DeformerField.GEOMETRY) + } + if ( + !floatEq(baseline.opacity, editedWarp.opacity) || + baseline.multiplyColor != editedWarp.multiplyColor || + baseline.screenColor != editedWarp.screenColor + ) { + add(DeformerField.STATICS) + } + if (!blendShapesEqual(baseline.blendShapes, editedWarp.blendShapes, ::warpFormEqual)) { + add(DeformerField.BLEND_SHAPES) + } + } + + is Deformer.Rotation -> { + val editedRotation = edited as Deformer.Rotation + if (!floatEq(baseline.baseAngle, editedRotation.baseAngle)) { + add(DeformerField.BASE_ANGLE) + } + if (!gridEquals(baseline.geometryGrid, editedRotation.geometryGrid, ::rotationPivotFormEqual)) { + add(DeformerField.GEOMETRY) + } + if ( + !floatEq(baseline.opacity, editedRotation.opacity) || + baseline.multiplyColor != editedRotation.multiplyColor || + baseline.screenColor != editedRotation.screenColor || + baseline.flipX != editedRotation.flipX || + baseline.flipY != editedRotation.flipY + ) { + add(DeformerField.STATICS) + } + if (!blendShapesEqual(baseline.blendShapes, editedRotation.blendShapes, ::rotationFormEqual)) { + add(DeformerField.BLEND_SHAPES) + } + } + } + if (!channelGridsEqual(baseline.channelGrids, edited.channelGrids)) { + add(DeformerField.CHANNELS) + } + } + +/** + * Diffs the atlas inventory, comparing only the tiles BOTH models carry. + * + * Set membership is deliberately not a difference here. A tile is the art the document holds, which + * arrives and leaves with an import rather than with an edit - and the two models being compared do not + * always track it the same way: a MOC3-origin conversion synthesizes model images into the graph that + * its puppet, which never had layered art, does not know about. Reporting those as deletions would + * describe an edit nobody made, on a path with nothing to reconcile. + * + * That is safe precisely because no edit can add or remove art today. When re-import can (it is the + * whole point of that phase), this grows the created/deleted arms together with the lowering that + * serves them, rather than reporting a difference nothing acts on. + * + * @param List baseline The graph-derived tiles. + * @param List edited The session's tiles. + * @return List One Changed entry per shared tile that differs. + */ +private fun diffAtlasTiles(baseline: List, edited: List): List> { + val editedById = edited.associateBy { tile -> tile.id } + // A reloaded tile is a new tile whose lineage root is the baseline's id; it is the same art to the + // graph, compared under the root so the reload reads as that tile changing. + val editedByRoot = edited.filter { tile -> tile.replaces != null }.associateBy { tile -> tile.id.lineageRoot } + return baseline.mapNotNull { baselineTile -> + val editedTile = editedById[baselineTile.id] ?: editedByRoot[baselineTile.id] ?: return@mapNotNull null + val fields = atlasTileFields(baselineTile, editedTile) + if (fields.isEmpty()) null else EntityDiff.Changed(baselineTile.id, fields) + } +} + +/** + * The changed aspects of one atlas tile. + * + * @param AtlasTile baseline The graph-derived tile. + * @param AtlasTile edited The session's tile. + * @return Set The fields that differ. + */ +private fun atlasTileFields(baseline: AtlasTile, edited: AtlasTile): Set = + buildSet { + if (baseline.placement != edited.placement) { + add(AtlasTileField.PLACEMENT) + } + if ( + baseline.name != edited.name || + baseline.width != edited.width || + baseline.height != edited.height || + baseline.source != edited.source + ) { + add(AtlasTileField.METADATA) + } + } + +private fun drawableFields(baseline: Drawable, edited: Drawable): Set = + buildSet { + if (baseline.name != edited.name) { + add(DrawableField.NAME) + } + if (baseline.parentDeformerId != edited.parentDeformerId) { + add(DrawableField.PARENT_DEFORMER) + } + if (baseline.blendMode != edited.blendMode) { + add(DrawableField.BLEND_MODE) + } + if (baseline.alphaBlendMode != edited.alphaBlendMode) { + add(DrawableField.ALPHA_BLEND_MODE) + } + if (baseline.maskedBy != edited.maskedBy) { + add(DrawableField.MASKED_BY) + } + if (baseline.invertMask != edited.invertMask) { + add(DrawableField.INVERT_MASK) + } + if (baseline.culling != edited.culling) { + add(DrawableField.CULLING) + } + if (baseline.isVisible != edited.isVisible) { + add(DrawableField.VISIBLE) + } + if (baseline.isSelectable != edited.isSelectable) { + add(DrawableField.SELECTABLE) + } + if (baseline.textureSourceId != edited.textureSourceId) { + add(DrawableField.TEXTURE_SOURCE) + } + // Absence is "not tracked", not "unbound", for the same reason the page list is only compared + // when there is an atlas: a drawable the model carries no art for says nothing about the art the + // graph carries for it. + // Compared under the lineage root: a drawable carried onto its tile's reload replacement still + // samples the same art as far as the graph knows. + val editedTileId = edited.atlasTileId + if (editedTileId != null && baseline.atlasTileId?.lineageRoot != editedTileId.lineageRoot) { + add(DrawableField.ATLAS_TILE) + } + addAll(meshFields(baseline.mesh, edited.mesh)) + if (!gridEquals(restOnlyAsUnkeyed(baseline.geometryGrid), restOnlyAsUnkeyed(edited.geometryGrid), ::meshDeltaFormEqual)) { + add(DrawableField.GEOMETRY) + } + if (!channelGridsEqual(baseline.channelGrids, edited.channelGrids)) { + add(DrawableField.CHANNELS) + } + if ( + !floatEq(baseline.drawOrder, edited.drawOrder) || + !floatEq(baseline.opacity, edited.opacity) || + baseline.multiplyColor != edited.multiplyColor || + baseline.screenColor != edited.screenColor + ) { + add(DrawableField.STATICS) + } + if (!blendShapesEqual(baseline.blendShapes, edited.blendShapes, ::meshFormEqual)) { + add(DrawableField.BLEND_SHAPES) + } + } + +/** + * The mesh aspect of a drawable diff. A vertex-count or triangulation change (or a mesh appearing/ + * disappearing) is MESH_TOPOLOGY; with topology intact, moved vertices are MESH_POSITIONS and + * remapped texels MESH_UVS - the split the lowering dispatches on, since topology forces a full + * GEditableMesh2 rebuild while the others patch arrays in place. + * + * @param DrawableMesh? baseline The baseline's mesh. + * @param DrawableMesh? edited The edited model's mesh. + * @return Set The changed mesh fields. + */ +private fun meshFields(baseline: DrawableMesh?, edited: DrawableMesh?): Set { + if (baseline === edited) { + return emptySet() + } + if (baseline == null || edited == null) { + return setOf(DrawableField.MESH_TOPOLOGY) + } + if (baseline.vertexCount != edited.vertexCount || !baseline.indices.contentEquals(edited.indices)) { + return setOf(DrawableField.MESH_TOPOLOGY) + } + return buildSet { + if (!baseline.positions.contentEquals(edited.positions)) { + add(DrawableField.MESH_POSITIONS) + } + if (!baseline.uvs.contentEquals(edited.uvs)) { + add(DrawableField.MESH_UVS) + } + } +} + +private fun diffGlues(baselineGlues: List, editedGlues: List): List { + if (baselineGlues === editedGlues) { + return emptyList() + } + // A glue has no id: key by the ordered mesh pair, with an ordinal among same-pair glues. + val baselineByPair = baselineGlues.groupBy { glue -> glue.meshA to glue.meshB } + val editedByPair = editedGlues.groupBy { glue -> glue.meshA to glue.meshB } + val diffs = ArrayList() + for ((pair, baselineList) in baselineByPair) { + val editedList = editedByPair[pair].orEmpty() + for (ordinal in baselineList.indices) { + val editedGlue = editedList.getOrNull(ordinal) + if (editedGlue == null) { + diffs.add(GlueDiff.Deleted(pair.first, pair.second, ordinal)) + continue + } + val fields = glueFields(baselineList[ordinal], editedGlue) + if (fields.isNotEmpty()) { + diffs.add(GlueDiff.Changed(pair.first, pair.second, ordinal, fields)) + } + } + } + for ((pair, editedList) in editedByPair) { + val baselineCount = baselineByPair[pair].orEmpty().size + for (ordinal in baselineCount until editedList.size) { + diffs.add(GlueDiff.Created(pair.first, pair.second, ordinal)) + } + } + return diffs +} + +private fun glueFields(baseline: Glue, edited: Glue): Set { + if (baseline === edited) { + return emptySet() + } + return buildSet { + val pairsEqual = + baseline.pairs.size == edited.pairs.size && + baseline.pairs.indices.all { pairIndex -> + val baselinePair = baseline.pairs[pairIndex] + val editedPair = edited.pairs[pairIndex] + baselinePair.indexA == editedPair.indexA && + baselinePair.indexB == editedPair.indexB && + floatEq(baselinePair.weightA, editedPair.weightA) && + floatEq(baselinePair.weightB, editedPair.weightB) + } + if (!pairsEqual) { + add(GlueField.PAIRS) + } + if (!channelGridsEqual(baseline.channelGrids, edited.channelGrids)) { + add(GlueField.CHANNELS) + } + if (!floatEq(baseline.intensity, edited.intensity)) { + add(GlueField.INTENSITY) + } + } +} + +private fun documentFields(baseline: PuppetModel, edited: PuppetModel): Set = + buildSet { + if (!floatEq(baseline.canvasWidth, edited.canvasWidth) || !floatEq(baseline.canvasHeight, edited.canvasHeight)) { + add(DocumentField.CANVAS_SIZE) + } + if (!floatEq(baseline.worldOriginX, edited.worldOriginX) || !floatEq(baseline.worldOriginZ, edited.worldOriginZ)) { + add(DocumentField.WORLD_ORIGIN) + } + if (baseline.runtimeTarget != edited.runtimeTarget) { + add(DocumentField.RUNTIME_TARGET) + } + if (baseline.rendersFromSourceLayers != edited.rendersFromSourceLayers) { + add(DocumentField.SOURCE_LAYER_DISPLAY) + } + // The page LIST, not the tiles on it: a page appearing, disappearing, or resizing changes what + // every placement on it means, and no per-tile diff would say so. + // + // Only when the edited model actually tracks an atlas. Carrying none is "this model has no + // source art" - a MOC3 origin never had any - and is not the same as an atlas that was emptied; + // comparing against a graph that does carry one would report a deletion nobody performed. + if (edited.atlas.tiles.isNotEmpty() && baseline.atlas.pages != edited.atlas.pages) { + add(DocumentField.ATLAS_PAGES) + } + // Document order of the flat parameter list is semantic in CMO3: combined (2D) pairs are + // encoded positionally (the Y axis is the next source after its combined X). + if (baseline.parameters.map(Parameter::id) != edited.parameters.map(Parameter::id)) { + add(DocumentField.PARAMETER_ORDER) + } + if (baseline.parameterLinks != edited.parameterLinks) { + add(DocumentField.PARAMETER_LINKS) + } + if (nodeIdentities(baseline.parameterTree) != nodeIdentities(edited.parameterTree)) { + add(DocumentField.PARAMETER_TREE) + } + if (baseline.rootChildren != edited.rootChildren) { + add(DocumentField.ROOT_CHILDREN) + } + // The file each source record points at - its name, path, and modification time - and nothing + // else about the record: the inventory and the hashes change on every reload and have no CMO3 + // home, so they must not turn a reload into a document change the export cannot lower. Only + // the records BOTH models list: a record one side lacks is art added this session, or a page + // slice a fresh synthesis minted under its own id, and has no layered image to repoint. + if (sourceFilesChanged(baseline, edited)) { + add(DocumentField.SOURCE_FILES) + } + } + +/** + * Whether any source record both models list points at a different file in [edited]: another name, + * path, or modification time. + * + * @param PuppetModel baseline The graph-derived baseline. + * @param PuppetModel edited The session's current model. + * @return Boolean True when a shared record was repointed. + */ +private fun sourceFilesChanged(baseline: PuppetModel, edited: PuppetModel): Boolean { + val baselineById = baseline.sources.associateBy { source -> source.id } + return edited.sources.any { source -> + val before = baselineById[source.id] ?: return@any false + before.name != source.name || before.path != source.path || before.lastModified != source.lastModified + } +} + +/** + * The identity sequence of one tree level - a Param's id or a Group's id, in order. Group content + * changes are reported per group (CHILDREN), so tree-level comparisons only look at this level's + * ordered identities. + * + * @param List nodes The level's nodes. + * @return List One identity token per node. + */ +private fun nodeIdentities(nodes: List): List = + nodes.map { node -> + when (node) { + is ParameterNode.Param -> "p:${node.id.raw}" + is ParameterNode.Group -> "g:${node.id.raw}" + } + } + +private fun flattenGroups(tree: List): List { + val groups = ArrayList() + + fun walk(nodes: List) { + for (node in nodes) { + if (node is ParameterNode.Group) { + groups.add(node) + walk(node.children) + } + } + } + walk(tree) + return groups +} + +/* + * Bit-exact equality helpers. Two independent imports of the same graph produce bit-identical + * floats, so raw-bits comparison never yields a false diff there - while an edit that flips only a + * sign bit (0.0 vs -0.0) still surfaces. Every helper takes the `===` fast path first: the common + * call compares a model against itself or against structurally shared sub-objects. + */ + +private fun floatEq(baseline: Float, edited: Float): Boolean = baseline.toRawBits() == edited.toRawBits() + +/** + * A drawable's geometry grid with the rest-only shape read as unkeyed: an axis-less grid holding one + * cell of zero deltas IS the unkeyed drawable, since both mean "the base mesh, nothing keyed". The + * two spellings arise from the formats - every CMO3 source carries a default form, so an unkeyed + * drawable exports as that one cell and re-imports as this grid - and neither is an edit of the + * other, so the diff must not call it one. + * + * @param KeyformGrid? grid The drawable's geometry grid. + * @return KeyformGrid? The grid, or null when it is the rest-only shape. + */ +private fun restOnlyAsUnkeyed(grid: KeyformGrid?): KeyformGrid? { + if (grid == null || grid.axes.isNotEmpty() || grid.cells.size != 1) { + return grid + } + val deltas = grid.cells.single().form.positionDeltas + return if (deltas.all { delta -> delta == 0f }) null else grid +} + +private fun gridEquals( + baseline: KeyformGrid?, + edited: KeyformGrid?, + formEqual: (TForm, TForm) -> Boolean, +): Boolean { + if (baseline === edited) { + return true + } + if (baseline == null || edited == null) { + return false + } + if (baseline.axes.size != edited.axes.size || baseline.cells.size != edited.cells.size) { + return false + } + for (axisIndex in baseline.axes.indices) { + val baselineAxis = baseline.axes[axisIndex] + val editedAxis = edited.axes[axisIndex] + if (baselineAxis.parameterId != editedAxis.parameterId || !baselineAxis.keys.contentEquals(editedAxis.keys)) { + return false + } + } + // Cells compare by coordinate, not list position: the import and the edit ops are both free to + // order cells differently without that being a semantic change. + val baselineByCoordinate = HashMap, TForm>(baseline.cells.size) + for (cell in baseline.cells) { + baselineByCoordinate[cell.coordinate.toList()] = cell.form + } + for (cell in edited.cells) { + val baselineForm = baselineByCoordinate[cell.coordinate.toList()] ?: return false + if (!formEqual(baselineForm, cell.form)) { + return false + } + } + return true +} + +private fun channelGridsEqual(baseline: ChannelGrids, edited: ChannelGrids): Boolean { + if (baseline === edited) { + return true + } + if (baseline.gridsByChannel.keys != edited.gridsByChannel.keys) { + return false + } + for ((channel, baselineGrid) in baseline.gridsByChannel) { + val editedGrid = edited.gridsByChannel.getValue(channel) + if (!gridEquals(baselineGrid, editedGrid) { baselineValue, editedValue -> baselineValue == editedValue }) { + return false + } + } + return true +} + +private fun blendShapesEqual( + baseline: List>, + edited: List>, + formEqual: (TForm, TForm) -> Boolean, +): Boolean { + if (baseline === edited) { + return true + } + if (baseline.size != edited.size) { + return false + } + for (bindingIndex in baseline.indices) { + val baselineBinding = baseline[bindingIndex] + val editedBinding = edited[bindingIndex] + if ( + baselineBinding.parameterId != editedBinding.parameterId || + !baselineBinding.keys.contentEquals(editedBinding.keys) || + baselineBinding.neutralIndex != editedBinding.neutralIndex || + baselineBinding.limits != editedBinding.limits || + baselineBinding.forms.size != editedBinding.forms.size + ) { + return false + } + for (formIndex in baselineBinding.forms.indices) { + val baselineForm = baselineBinding.forms[formIndex] + val editedForm = editedBinding.forms[formIndex] + if (baselineForm == null || editedForm == null) { + if (baselineForm !== editedForm) { + return false + } + continue + } + if (!formEqual(baselineForm, editedForm)) { + return false + } + } + } + return true +} + +private fun meshDeltaFormEqual(baseline: MeshDeltaForm, edited: MeshDeltaForm): Boolean = + baseline === edited || baseline.positionDeltas.contentEquals(edited.positionDeltas) + +private fun warpLatticeFormEqual(baseline: WarpLatticeForm, edited: WarpLatticeForm): Boolean = + baseline === edited || baseline.controlPoints.contentEquals(edited.controlPoints) + +private fun rotationPivotFormEqual(baseline: RotationPivotForm, edited: RotationPivotForm): Boolean = + baseline === edited || + ( + floatEq(baseline.originX, edited.originX) && + floatEq(baseline.originY, edited.originY) && + floatEq(baseline.angle, edited.angle) && + floatEq(baseline.scale, edited.scale) + ) + +private fun meshFormEqual(baseline: MeshForm, edited: MeshForm): Boolean = + baseline === edited || + ( + baseline.positionDeltas.contentEquals(edited.positionDeltas) && + floatEq(baseline.drawOrder, edited.drawOrder) && + floatEq(baseline.opacity, edited.opacity) && + baseline.multiplyColor == edited.multiplyColor && + baseline.screenColor == edited.screenColor + ) + +private fun warpFormEqual(baseline: WarpForm, edited: WarpForm): Boolean = + baseline === edited || + ( + baseline.controlPoints.contentEquals(edited.controlPoints) && + floatEq(baseline.opacity, edited.opacity) && + baseline.multiplyColor == edited.multiplyColor && + baseline.screenColor == edited.screenColor + ) + +private fun rotationFormEqual(baseline: RotationForm, edited: RotationForm): Boolean = + baseline === edited || + ( + floatEq(baseline.originX, edited.originX) && + floatEq(baseline.originY, edited.originY) && + floatEq(baseline.angle, edited.angle) && + floatEq(baseline.scale, edited.scale) && + baseline.flipX == edited.flipX && + baseline.flipY == edited.flipY && + floatEq(baseline.opacity, edited.opacity) && + baseline.multiplyColor == edited.multiplyColor && + baseline.screenColor == edited.screenColor + ) \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/RuntimeTargetMapping.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/RuntimeTargetMapping.kt new file mode 100644 index 0000000..4ee6e7c --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/RuntimeTargetMapping.kt @@ -0,0 +1,97 @@ +package org.umamo.interop + +import org.umamo.format.cmo3.Cmo3TargetVersion +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.runtime.model.RuntimeTarget + +/* + * The RuntimeTarget ↔ format-version mapping: which Cmo3TargetVersion / MocVersion each runtime + * target reads from and persists as. It lives here rather than on the enum so :runtime stays free + * of :format - the target's capability matrix (supports / restrictedFeatures) is runtime policy, + * while the version encodings are a format concern owned by the conversion layer. + */ + +/** + * The moc version a MOC3 export of this target bakes: the matching version for a Cubism target, + * the latest for NoTarget (nothing restricted), and V50 for Ayagami (its effective level). + * + * @return MocVersion The bake target. + */ +fun RuntimeTarget.mocVersion(): MocVersion = + when (this) { + RuntimeTarget.NoTarget -> MocVersion.V53 + RuntimeTarget.Ayagami -> MocVersion.V50 + RuntimeTarget.Cubism30 -> MocVersion.V30 + RuntimeTarget.Cubism33 -> MocVersion.V33 + RuntimeTarget.Cubism40 -> MocVersion.V40 + RuntimeTarget.Cubism42 -> MocVersion.V42 + RuntimeTarget.Cubism50 -> MocVersion.V50 + RuntimeTarget.Cubism53 -> MocVersion.V53 + } + +/** + * The CMO3 target version this target persists as, or null for NoTarget - a target-less document + * has no target VERSION and persists through the latest sentinel instead (see + * [cmo3TargetVersionNo]). Ayagami has no CMO3 encoding of its own, so it persists at its + * effective Cubism level: the gating level survives a CMO3 round-trip even though the Ayagami + * identity cannot (a reopen shows Cubism 5.0; UMA will carry the identity). + * + * @return Cmo3TargetVersion? The CMO3-side version, or null for NoTarget. + */ +fun RuntimeTarget.cmo3TargetVersion(): Cmo3TargetVersion? = + when (this) { + RuntimeTarget.NoTarget -> null + // Ayagami writes its effective Cubism level, in lockstep with cubismLevel and mocVersion. + RuntimeTarget.Ayagami -> Cmo3TargetVersion.V50 + RuntimeTarget.Cubism30 -> Cmo3TargetVersion.V30 + RuntimeTarget.Cubism33 -> Cmo3TargetVersion.V33 + RuntimeTarget.Cubism40 -> Cmo3TargetVersion.V40 + RuntimeTarget.Cubism42 -> Cmo3TargetVersion.V42 + RuntimeTarget.Cubism50 -> Cmo3TargetVersion.V50 + RuntimeTarget.Cubism53 -> Cmo3TargetVersion.V53 + } + +/** + * The raw `targetVersionNo` a CMO3 save persists for this target: the version's literal, or the + * "SDK(N/A)/Latest Cubism" sentinel for NoTarget. Every target persists something. + * + * @return Int The value to write. + */ +fun RuntimeTarget.cmo3TargetVersionNo(): Int = + // CMO3: CModelSource field targetVersionNo. + cmo3TargetVersion()?.versionNo ?: Cmo3TargetVersion.LATEST_VERSION_NO + +/** + * Maps a CMO3 document's decoded target version to the runtime target it selects, with unknown or + * absent values falling back to no restriction. + * + * @param Cmo3TargetVersion? version The decoded CMO3 target version, or null for unknown/absent. + * @return RuntimeTarget The matching target, or [RuntimeTarget.NoTarget] for null. + */ +fun runtimeTargetOfCmo3Target(version: Cmo3TargetVersion?): RuntimeTarget = + when (version) { + null -> RuntimeTarget.NoTarget + Cmo3TargetVersion.V30 -> RuntimeTarget.Cubism30 + Cmo3TargetVersion.V33 -> RuntimeTarget.Cubism33 + Cmo3TargetVersion.V40 -> RuntimeTarget.Cubism40 + Cmo3TargetVersion.V42 -> RuntimeTarget.Cubism42 + Cmo3TargetVersion.V50 -> RuntimeTarget.Cubism50 + Cmo3TargetVersion.V53 -> RuntimeTarget.Cubism53 + } + +/** + * Maps a baked moc's version byte to the runtime target it implies - the moc version is a hard + * fact of the file, so an imported .moc3 starts at the matching Cubism target. + * + * @param MocVersion version The moc version. + * @return RuntimeTarget The matching Cubism target. + */ +fun runtimeTargetOfMocVersion(version: MocVersion): RuntimeTarget = + when (version) { + MocVersion.V30 -> RuntimeTarget.Cubism30 + MocVersion.V33 -> RuntimeTarget.Cubism33 + MocVersion.V40 -> RuntimeTarget.Cubism40 + MocVersion.V42 -> RuntimeTarget.Cubism42 + MocVersion.V50 -> RuntimeTarget.Cubism50 + MocVersion.V53 -> RuntimeTarget.Cubism53 + } \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/art/ArtworkAnchor.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/ArtworkAnchor.kt new file mode 100644 index 0000000..ece2804 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/ArtworkAnchor.kt @@ -0,0 +1,37 @@ +package org.umamo.interop.art + +/** + * Where a later artwork file's canvas is anchored on the document canvas when it is added: the nine + * anchors the art programs' own Canvas Size dialogs offer, so a file whose canvas the artist resized + * around some anchor lands back where the art was drawn. A file the same size as the document canvas + * lands identically under every anchor. + * + * @property String key The stable setting and strip value. + * @property Float horizontal How far along the document's width the file's width is anchored (0 left, 0.5 center, 1 right). + * @property Float vertical How far along the document's height the file's height is anchored (0 top, 0.5 middle, 1 bottom). + */ +enum class ArtworkAnchor(val key: String, val horizontal: Float, val vertical: Float) { + TopLeft("topLeft", 0f, 0f), + Top("top", 0.5f, 0f), + TopRight("topRight", 1f, 0f), + Left("left", 0f, 0.5f), + Center("center", 0.5f, 0.5f), + Right("right", 1f, 0.5f), + BottomLeft("bottomLeft", 0f, 1f), + Bottom("bottom", 0.5f, 1f), + BottomRight("bottomRight", 1f, 1f), + ; + + companion object { + /** The anchor a fresh install adds with: the art programs' own default when a canvas is resized. */ + val Default: ArtworkAnchor = Center + + /** + * The anchor a setting or strip value names, or [Default] for a value no anchor carries. + * + * @param String? key The value. + * @return ArtworkAnchor The anchor. + */ + fun fromKey(key: String?): ArtworkAnchor = entries.firstOrNull { anchor -> anchor.key == key } ?: Default + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/art/LayerBlendMapping.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/LayerBlendMapping.kt new file mode 100644 index 0000000..c741a34 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/LayerBlendMapping.kt @@ -0,0 +1,72 @@ +package org.umamo.interop.art + +import org.umamo.format.art.LayerBlend +import org.umamo.runtime.model.BlendMode + +/** + * How one source-art blend lands on the model's blend modes. + * + * Three outcomes, kept distinct because the rigger's remedy differs: an exact mapping needs no word, + * an approximation is worth a notice so an artist who leaned on the exact formula knows, and an + * unsupported blend falls back to Normal with a notice so the change is never silent. + */ +sealed interface LayerBlendMapping { + /** The blend mode the model gets, Normal for an unsupported one. */ + val blendMode: BlendMode + + /** The model has this blend under the same formula. */ + data class Exact(override val blendMode: BlendMode) : LayerBlendMapping + + /** The model's nearest blend, not the same formula. */ + data class Approximate(override val blendMode: BlendMode) : LayerBlendMapping + + /** No model blend comes close; the drawable renders Normal. */ + data object Unsupported : LayerBlendMapping { + override val blendMode: BlendMode get() = BlendMode.Normal + } +} + +/** + * Maps a source-art blend onto the model's blend modes. + * + * The model's set is Cubism 5.3's (see [BlendMode]), which covers most of the PSD / Clip Studio / + * Krita vocabulary one to one. Glow Dodge is Clip Studio's clamped Color Dodge and lands there as an + * approximation; the HSL modes the model lacks (Saturation, Luminosity), the two comparison modes + * (Darker / Lighter Color), and the arithmetic ones (Subtract, Divide, Vivid / Pin Light, Hard Mix, + * Difference, Exclusion) have no model equivalent at all. + * + * @param LayerBlend blend The source layer's blend. + * @return LayerBlendMapping Where it lands. + */ +fun mapLayerBlend(blend: LayerBlend): LayerBlendMapping = + when (blend) { + LayerBlend.Normal -> LayerBlendMapping.Exact(BlendMode.Normal) + LayerBlend.Darken -> LayerBlendMapping.Exact(BlendMode.Darken) + LayerBlend.Multiply -> LayerBlendMapping.Exact(BlendMode.Multiply) + LayerBlend.ColorBurn -> LayerBlendMapping.Exact(BlendMode.ColorBurn) + LayerBlend.LinearBurn -> LayerBlendMapping.Exact(BlendMode.LinearBurn) + LayerBlend.Lighten -> LayerBlendMapping.Exact(BlendMode.Lighten) + LayerBlend.Screen -> LayerBlendMapping.Exact(BlendMode.Screen) + LayerBlend.ColorDodge -> LayerBlendMapping.Exact(BlendMode.ColorDodge) + LayerBlend.GlowDodge -> LayerBlendMapping.Approximate(BlendMode.ColorDodge) + LayerBlend.Add -> LayerBlendMapping.Exact(BlendMode.Additive) + LayerBlend.AddGlow -> LayerBlendMapping.Exact(BlendMode.AdditiveGlow) + LayerBlend.Overlay -> LayerBlendMapping.Exact(BlendMode.Overlay) + LayerBlend.SoftLight -> LayerBlendMapping.Exact(BlendMode.SoftLight) + LayerBlend.HardLight -> LayerBlendMapping.Exact(BlendMode.HardLight) + LayerBlend.LinearLight -> LayerBlendMapping.Exact(BlendMode.LinearLight) + LayerBlend.Hue -> LayerBlendMapping.Exact(BlendMode.Hue) + LayerBlend.Color -> LayerBlendMapping.Exact(BlendMode.Color) + LayerBlend.Subtract, + LayerBlend.DarkerColor, + LayerBlend.LighterColor, + LayerBlend.VividLight, + LayerBlend.PinLight, + LayerBlend.HardMix, + LayerBlend.Difference, + LayerBlend.Exclusion, + LayerBlend.Saturation, + LayerBlend.Luminosity, + LayerBlend.Divide, + -> LayerBlendMapping.Unsupported + } \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtImport.kt new file mode 100644 index 0000000..ea7a6b2 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtImport.kt @@ -0,0 +1,1048 @@ +package org.umamo.interop.art + +import org.umamo.format.art.ChannelMask +import org.umamo.format.art.DEFAULT_ALPHA_THRESHOLD +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.art.isFullyTransparent +import org.umamo.format.binary.contentHashOf +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.ArtworkAdditions +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.OrgInsertion +import org.umamo.runtime.model.OrgSlot +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.canvasCenterWorldOriginX +import org.umamo.runtime.model.canvasCenterWorldOriginZ +import org.umamo.runtime.model.deriveRenderRoot +import kotlin.math.floor +import kotlin.math.roundToInt + +/* + * The SourceArt -> PuppetModel bridge: the first point where a layered file (or a flat raster) + * becomes an editable rig. One drawable per raster layer over a quad birth mesh, one part per + * folder, one atlas tile per layer bound to its source layer by the reader's key. + * + * The model comes out UNPACKED - every tile unplaced, every drawable's coordinates addressing its own + * art - so this stays a pure conversion that the pack at open then moves onto pages through the same + * repack primitive the Repack Atlas command uses. Packing here would only duplicate that path. + * + * The art arrives already in the document canvas frame (SourceArtPlacement.kt): the bridge reads + * bounds as document positions and never shifts them itself. + */ + +/** + * What the importer records about the file the art came from. + * + * @property String name The file's display name (its file name). + * @property String? path The advisory external path, or null when the platform has none (a SAF uri). + * @property String format The source format's file extension ("psd", "clip", "kra", "png", ...). + * @property String? contentHash The whole-file content hash of the bytes read, or null when unknown. + * @property Long? lastModified The file's modification time (epoch milliseconds) when read, or null when unknown. + */ +class ArtSourceDescriptor( + val name: String, + val path: String?, + val format: String, + val contentHash: String? = null, + val lastModified: Long? = null, +) + +/** + * How an import shapes the model it builds. + * + * The bridge seeds whatever parameters it is handed and knows nothing about templates: the choice of + * set (and its default) is editor policy the caller resolves before the import runs, so the bridge's + * own default is to seed nothing. + * + * @property List parameters The parameters to seed, in panel order. + * @property Int alphaThreshold Minimum alpha byte (1..255) for a pixel to count as art + * when a layer is trimmed for its birth mesh; the pack at open trims under the same threshold. + * @property Int birthMeshMargin How far, in source pixels, the birth quad extends past + * the layer's opaque bounds on every side. + * @property ArtworkAnchor anchor Where a later file's canvas is anchored on the document + * canvas ([SourceArtImport.offsetFor]); moot for a rig's first artwork, which sets the canvas. + * @property Int nudgeX Pixels added to the anchor's placement along x. + * @property Int nudgeZ Pixels added to the anchor's placement along z - up, the + * viewport's world axis, so a negative nudge moves the art down the canvas. + */ +class SourceArtImportOptions( + val parameters: List = emptyList(), + val alphaThreshold: Int = DEFAULT_ALPHA_THRESHOLD, + val birthMeshMargin: Int = SourceArtImport.DEFAULT_BIRTH_MESH_MARGIN, + val anchor: ArtworkAnchor = ArtworkAnchor.Default, + val nudgeX: Int = 0, + val nudgeZ: Int = 0, +) { + init { + require(alphaThreshold in 1..255) { "alphaThreshold must be in 1..255: $alphaThreshold" } + require(birthMeshMargin >= 0) { "birthMeshMargin must be non-negative: $birthMeshMargin" } + } +} + +/** + * What an import produced. + * + * @property PuppetModel puppet The unpacked model. + * @property Map rasterByTile Each tile's pixels, by tile - the document's pixel supplier takes + * them from here, since the model itself carries none. + * @property List notices Everything the import could not carry as drawn, in document order. + */ +class SourceArtImportResult( + val puppet: PuppetModel, + val rasterByTile: Map, + val notices: List, +) + +/** + * What one artwork file adds to a model, with its pixels and its notes: the delta a fresh import + * assembles into a new model and an open document appends to itself. + * + * @property ArtworkAdditions additions The source record, tiles, drawables, parts, and root order. + * @property Map rasterByTile Each added tile's pixels, by tile. + * @property List notices Everything the import could not carry as drawn, in document order. + */ +class SourceArtAdditions( + val additions: ArtworkAdditions, + val rasterByTile: Map, + val notices: List, +) + +/** One raster layer that became a drawable, kept for the passes that run after the first. */ +private class ImportedLayer( + val layer: SourceLayer, + val drawableId: DrawableId, +) + +/** + * The next ids to mint, continuing past whatever the receiving model already has so an added file's + * drawables and parts read as the editor's own would (`ArtMesh`, `Part`). + * + * @property Int nextDrawable The suffix of the next drawable id. + * @property Int nextPart The suffix of the next part id. + */ +private class IdMinter(var nextDrawable: Int, var nextPart: Int) + +/** + * One folder of the source tree while the org tree is being built: its own attributes plus the + * children gathered under it, each tagged with the order it sorts by. + */ +private class FolderNode( + val path: String, + val name: String, + val visible: Boolean, + val opacity: Float, + val clipped: Boolean, + val blend: LayerBlend, + val passThrough: Boolean, +) { + val children = ArrayList() + + /** The top-most order under this folder, so it sorts among its siblings where its first layer is. */ + var firstOrder: Int = Int.MAX_VALUE +} + +/** One direct child of a folder as the FILE orders it: a layer by key, or a sub-folder by path. */ +private sealed interface FileSibling { + val order: Int + + class Layer(override val order: Int, val key: String) : FileSibling + + class Folder(override val order: Int, val path: String) : FileSibling +} + +/** One entry of a folder's children: a drawable, or a nested folder, with the order it sorts by. */ +private sealed interface FolderChild { + val order: Int + + class Layer(override val order: Int, val drawableId: DrawableId) : FolderChild + + class Folder(val node: FolderNode) : FolderChild { + override val order: Int get() = node.firstOrder + } +} + +/** + * Turns parsed source art into a puppet model - see the file comment for the shape it produces. + */ +object SourceArtImport { + /** How far the birth quad extends past a layer's opaque bounds, in source pixels. */ + const val DEFAULT_BIRTH_MESH_MARGIN: Int = 2 + + /** The id of the one source a first import records; later files continue the sequence. */ + const val FIRST_SOURCE_ID: String = "art-0" + + /** + * Builds an unpacked model from [art]. + * + * Layers are visited top-most first (the source's own draw order), and every id the model mints - + * `ArtMesh`, `Part`, the tile ids - is sequential in that order, so the same file imports to + * the same ids every time and a CMO3 export reads the way the official editor's own import would. + * The additions are the same ones [additionsFor] appends to an open document; this assembles them + * into a new model with the seeded parameters and the file's canvas. + * + * @param SourceArt art The parsed source art. + * @param ArtSourceDescriptor source What to record about the file it came from. + * @param SourceArtImportOptions options The seed parameters, threshold, and margin. + * @return SourceArtImportResult The model, its tiles' pixels, and the import notices. + */ + fun fromSourceArt( + art: SourceArt, + source: ArtSourceDescriptor, + options: SourceArtImportOptions = SourceArtImportOptions(), + ): SourceArtImportResult { + val blank = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ) + val added = additionsFor(art, source, options, blank) + val additions = added.additions + + val assembled = + PuppetModel( + parameters = emptyList(), + parts = additions.parts, + deformers = emptyList(), + drawables = additions.drawables, + rootChildren = additions.rootChildren, + rootPartId = null, + atlas = PuppetAtlas(pages = emptyList(), tiles = additions.tiles, storedUvsAddressPages = true), + sources = listOf(additions.source), + ) + // The same two seeds a rig gets when this file is its first artwork, applied through the same + // helpers the add path uses, so a document built by importing art and a new document that then + // imports the same art come out identical. + val model = withSeedParameters(withFirstArtworkState(assembled, art), options.parameters) + return SourceArtImportResult(model.copy(renderRoot = model.deriveRenderRoot()), added.rasterByTile, added.notices) + } + + /** + * [model] with the frame its FIRST artwork gives it: the file's canvas, the world origin at that + * canvas's center, and the fresh-import display state. + * + * Rest positions are canvas pixels with y down, the convention every import shares, so the world + * origin is the canvas center negated into world space like every vertex. Source-layer display is + * the official editor's own state after an import - the rigger sees the layers as drawn, and the + * pack that follows is what makes the document shippable. + * + * For the first artwork only: a document that already has art keeps the canvas it was authored + * against, since a second file is placed within that frame rather than redefining it. + * + * @param PuppetModel model The model to seed. + * @param SourceArt art The artwork the frame comes from. + * @return PuppetModel The seeded model. + */ + fun withFirstArtworkState(model: PuppetModel, art: SourceArt): PuppetModel { + val canvasWidth = art.widthPx.toFloat() + val canvasHeight = art.heightPx.toFloat() + return model.copy( + canvasWidth = canvasWidth, + canvasHeight = canvasHeight, + worldOriginX = canvasCenterWorldOriginX(canvasWidth), + worldOriginZ = canvasCenterWorldOriginZ(canvasHeight), + rendersFromSourceLayers = true, + ) + } + + /** + * [model] with [parameters] as its axes, materialized flat in the parameter tree. + * + * The tree is materialized (one leaf per parameter at the root) rather than left empty: the CMO3 + * export places parameters in the editor's group hierarchy from the tree alone, and the official + * editor logs a recovery for every parameter it finds outside it. Same shape the editor's own + * parameter-create materializes. + * + * For a rig with no axes yet: seeding over authored parameters would replace them, so the caller + * seeds only a model whose parameter list is empty. + * + * @param PuppetModel model The model to seed. + * @param List parameters The template's parameters; an empty list leaves the model alone. + * @return PuppetModel The seeded model. + */ + fun withSeedParameters(model: PuppetModel, parameters: List): PuppetModel { + if (parameters.isEmpty()) { + return model + } + return model.copy( + parameters = parameters, + parameterTree = parameters.map { parameter -> ParameterNode.Param(parameter.id) }, + ) + } + + /** + * Whether an artwork file added to [model] would be its FIRST: a rig with no drawable and no tile + * takes its frame from the file that arrives ([withFirstArtworkState]), so the file is never placed + * within a canvas - it defines the canvas. The one test the add's framing and its placement share. + * + * @param PuppetModel model The model the artwork would join. + * @return Boolean True when the model has no art of its own yet. + */ + fun isFirstArtwork(model: PuppetModel): Boolean = model.drawables.isEmpty() && model.atlas.tiles.isEmpty() + + /** + * Where [art]'s canvas lands on [model]'s: the anchor's placement of the file's size within the + * document's, plus the options' nudge, in the world axes (x right, z up). Zero for a rig's first + * artwork (the file sets the canvas) and for a document with no canvas to place within. Negative + * along x where the file is wider than the canvas (the art overhangs the way the anchor says), and + * along z whenever the file's top edge sits below the document's, which is every anchor but the top + * row for a file shorter than the canvas. + * + * @param PuppetModel model The model the artwork joins. + * @param SourceArt art The file, for its canvas size. + * @param SourceArtImportOptions options The anchor and nudge. + * @return CanvasOffset The translation to place the file's art by. + */ + fun offsetFor(model: PuppetModel, art: SourceArt, options: SourceArtImportOptions): CanvasOffset { + if (isFirstArtwork(model) || model.canvasWidth <= 0f || model.canvasHeight <= 0f) { + return CanvasOffset.Zero + } + return CanvasOffset( + x = anchoredOffset(model.canvasWidth.roundToInt() - art.widthPx, options.anchor.horizontal) + options.nudgeX, + z = -anchoredOffset(model.canvasHeight.roundToInt() - art.heightPx, options.anchor.vertical) + options.nudgeZ, + ) + } + + /** + * The canvas-frame offset an anchor places a file at along one axis: the spare room (the document's + * extent minus the file's, negative when the file is larger) split by the anchor's fraction, rounded + * down so a centered file with one odd pixel of room sits one pixel nearer the top-left. Canvas y + * runs down, so the caller negates the vertical result into z. + * + * @param Int room The document's extent minus the file's along the axis. + * @param Float fraction How far along the room the file is anchored (0, 0.5, or 1). + * @return Int The offset. + */ + private fun anchoredOffset(room: Int, fraction: Float): Int = floor(room * fraction).toInt() + + /** + * The additions [art] makes to [existing]: the delta an open document appends to itself, with every + * id minted past the ones the document already has. + * + * Ids continue the existing sequences (`ArtMesh` and `Part` past their highest suffix, the + * source past `art-`), and a tile key that collides with an existing tile is disambiguated the + * same way a duplicate layer key is. The additions carry no placements: the caller packs them + * around the document's art. + * + * The art is never placed here: [art] is expected in the DOCUMENT canvas frame already (a new file + * placed by [SourceArt.placedBy], a listed file's read placed by [SourceArt.placedFor]), and the + * birth meshes and inventory rows take its bounds as they are. + * + * @param SourceArt art The parsed source art, in the document canvas frame. + * @param ArtSourceDescriptor source What to record about the file it came from. + * @param SourceArtImportOptions options The threshold and margin (the seed parameters are a fresh import's). + * @param PuppetModel existing The model the additions will join. + * @param ArtSourceId? underSource The source the additions belong to when the file is one + * the model already lists (a reload adding the layers a file gained): the tiles bind to it and the + * returned record carries its id, so the caller merges rather than appends the record. Only the + * folders the added layers live in become parts; a folder the document already keeps as a part + * (the part holding the most drawables of that folder, found through the source's bindings) takes + * the new layers as children instead of being minted again; and every new child of the root or of + * such a part is placed among the existing children where the file puts it, anchored to its + * nearest sibling in the file. Null mints a new source with every folder of the file, the shape a + * fresh import and Add Artwork take. + * @param Set? layerKeys The keys of the layers to mint, or null for every layer. A + * reload names the layers the file gained while handing over the WHOLE file, so the placement can + * see the layers around them. + * @param List? inventory The inventory of [art] when the caller already computed it + * (it hashes every layer's pixels); computed here when null. + * @param CanvasOffset offset The translation [art] was placed by, recorded on a NEW + * source's record so every later read of the file is placed the same way. Ignored under + * [underSource], whose record keeps the offset it already carries. + * @return SourceArtAdditions The delta, its tiles' pixels, and the import notices. + */ + fun additionsFor( + art: SourceArt, + source: ArtSourceDescriptor, + options: SourceArtImportOptions, + existing: PuppetModel, + underSource: ArtSourceId? = null, + layerKeys: Set? = null, + inventory: List? = null, + offset: CanvasOffset = CanvasOffset.Zero, + ): SourceArtAdditions { + val sourceId = underSource ?: ArtSourceId("art-${nextSuffix(existing.sources.map { candidate -> candidate.id.raw }, "art-", first = 0)}") + // A listed file's record keeps the frame it was placed in; the reload that hands its layers here + // has already placed the art by it. + val recorded = underSource?.let { listed -> existing.sources.firstOrNull { candidate -> candidate.id == listed } } + val recordedOffset = if (recorded == null) offset else CanvasOffset(recorded.offsetX, recorded.offsetZ) + val minter = + IdMinter( + nextDrawable = nextSuffix(existing.drawables.map { drawable -> drawable.id.raw }, "ArtMesh", first = 1), + nextPart = nextSuffix(existing.parts.map { part -> part.id.raw }, "Part", first = 1), + ) + val layersTopFirst = art.layers.sortedBy { layer -> layer.order } + val notices = ArrayList() + + // Pass 1: one drawable and one tile per raster layer with art in it. + val imported = ArrayList() + val drawables = ArrayList() + val tiles = ArrayList() + val rasterByTile = LinkedHashMap() + val usedTileKeys = existing.atlas.tiles.mapTo(HashSet()) { tile -> tile.id.raw } + for (layer in layersTopFirst) { + if (layerKeys != null && layer.id.raw !in layerKeys) { + continue + } + if (layer.kind != SourceLayerKind.Raster) { + notices.add(SourceArtImportNotice.NonRasterLayer(layer.name, layer.kind)) + continue + } + val analysis = layer.analyzeAlpha(alphaThreshold = options.alphaThreshold) + if (analysis == null) { + notices.add(SourceArtImportNotice.EmptyLayer(layer.name)) + continue + } + // The reader's key is the tile's identity too, disambiguated by draw order when a weak source + // key (the PSD name-and-order fallback) collides - the same rule the packer's adapter applies. + var tileKey = "${sourceId.raw}/${layer.id.raw}" + if (!usedTileKeys.add(tileKey)) { + tileKey = "$tileKey#${layer.order}" + usedTileKeys.add(tileKey) + } + val tileId = AtlasTileId(tileKey) + tiles.add( + AtlasTile( + id = tileId, + name = layer.name, + width = layer.raster.width, + height = layer.raster.height, + source = SourceLayerRef(sourceId, layer.id.raw, stableKey = layer.idIsStable), + ), + ) + rasterByTile[tileId] = layer.raster + + val blendMapping = mapLayerBlend(layer.blend) + when (blendMapping) { + is LayerBlendMapping.Exact -> Unit + is LayerBlendMapping.Approximate -> notices.add(SourceArtImportNotice.BlendApproximated(layer.name, layer.blend, blendMapping.blendMode)) + LayerBlendMapping.Unsupported -> notices.add(SourceArtImportNotice.BlendUnsupported(layer.name, layer.blend)) + } + if (layer.channelMask != ChannelMask.ALL) { + notices.add(SourceArtImportNotice.ChannelMaskDropped(layer.name)) + } + + val drawableId = DrawableId("ArtMesh${minter.nextDrawable}") + minter.nextDrawable++ + drawables.add( + Drawable( + id = drawableId, + name = layer.name, + parentDeformerId = null, + blendMode = blendMapping.blendMode, + maskedBy = emptyList(), + mesh = birthQuad(layer, analysis.opaqueBounds.left, analysis.opaqueBounds.top, analysis.opaqueBounds.width, analysis.opaqueBounds.height, options.birthMeshMargin), + geometryGrid = null, + opacity = layer.opacity, + isVisible = layer.visible, + atlasTileId = tileId, + ), + ) + imported.add(ImportedLayer(layer, drawableId)) + } + + // Pass 2: a clipping layer clips to the nearest non-clipped layer BELOW it in its own folder - + // Photoshop's "clip to layer below", which CLIP and Krita share. Below is a greater order. + val drawableIndexById = drawables.withIndex().associate { (index, drawable) -> drawable.id to index } + for ((position, entry) in imported.withIndex()) { + if (!entry.layer.clipped) { + continue + } + val base = + imported.subList(position + 1, imported.size).firstOrNull { candidate -> + candidate.layer.groupPath == entry.layer.groupPath && !candidate.layer.clipped + } + if (base == null) { + notices.add(SourceArtImportNotice.ClipBaseMissing(entry.layer.name)) + continue + } + val index = drawableIndexById.getValue(entry.drawableId) + drawables[index] = drawables[index].copy(maskedBy = listOf(base.drawableId)) + } + + // Pass 3: the org tree. A fresh file mints every folder as a part, nested by path, and its whole + // tree lands after the model's root children. A file the document already lists mints only the + // folders its added layers live in, a folder the document already keeps as a part takes the + // layers as children instead, and every new child of the root or of such a part is placed among + // the existing children where the file puts it. Each folder sorts among its siblings where its + // top-most layer sits, so the panel reads in the file's own order. + val existingPartByPath = if (underSource == null) emptyMap() else existingPartsByFolder(existing, underSource) + val folderByPath = LinkedHashMap() + if (underSource == null) { + for (group in art.groups) { + folderByPath[group.path] = folderNodeOf(group) + } + } else { + val groupByPath = art.groups.associateBy { group -> group.path } + for (entry in imported) { + for (path in ancestorPathsOf(entry.layer.groupPath)) { + val group = groupByPath[path] + if (group != null && path !in folderByPath) { + folderByPath[path] = folderNodeOf(group) + } + } + } + } + for (entry in imported) { + ensureFolders(entry.layer.groupPath, folderByPath) + } + // Where a new child gathers: the root's list, an anchored part's list (placed among that part's + // existing children below), or a new folder's own node. + val rootGathered = ArrayList() + val gatheredByAnchor = LinkedHashMap>() + + fun gatheredFor(parentPath: String): MutableList = + when { + parentPath.isEmpty() -> rootGathered + parentPath in existingPartByPath -> gatheredByAnchor.getOrPut(parentPath) { ArrayList() } + else -> folderByPath.getValue(parentPath).children + } + for (folder in folderByPath.values) { + if (folder.path in existingPartByPath) { + // Anchored to a part the document has: its children lower into that part, and the folder + // itself is never a child of anything new. + continue + } + gatheredFor(folder.path.substringBeforeLast('/', missingDelimiterValue = "")).add(FolderChild.Folder(folder)) + } + for (entry in imported) { + gatheredFor(entry.layer.groupPath).add(FolderChild.Layer(entry.layer.order, entry.drawableId)) + var ancestorPath = entry.layer.groupPath + while (ancestorPath.isNotEmpty()) { + val ancestor = folderByPath.getValue(ancestorPath) + ancestor.firstOrder = minOf(ancestor.firstOrder, entry.layer.order) + ancestorPath = ancestorPath.substringBeforeLast('/', missingDelimiterValue = "") + } + } + val parts = ArrayList() + val orgRoot: List + val insertions: List + if (underSource == null) { + orgRoot = orgChildrenOf(rootGathered, parts, minter, notices) + insertions = emptyList() + } else { + orgRoot = emptyList() + val placer = InsertionPlacer(art, existing, underSource, existingPartByPath, imported) + val placed = ArrayList() + placer.place(container = null, containerPath = "", gathered = rootGathered, parts, minter, notices, placed) + for ((containerPath, gathered) in gatheredByAnchor) { + placer.place(existingPartByPath.getValue(containerPath), containerPath, gathered, parts, minter, notices, placed) + } + insertions = placed + } + + return SourceArtAdditions( + ArtworkAdditions( + source = + ArtSource( + sourceId, + source.name, + source.path, + source.format, + inventory ?: inventoryOf(art), + source.contentHash, + source.lastModified, + offsetX = recordedOffset.x, + offsetZ = recordedOffset.z, + ), + tiles = tiles, + drawables = drawables, + parts = parts, + rootChildren = orgRoot, + insertions = insertions, + ), + rasterByTile, + notices, + ) + } + + /** + * Places a listed file's new children among a container's existing ones by the file's order. + * + * The file's direct children of a folder - its layers and its sub-folders, each with the order it + * sorts by (a folder's is its top-most layer's) - are the siblings; a new child goes directly after + * its nearest sibling above that the container can show (an existing drawable bound to that layer, the + * part the document keeps for that folder, or a child this delta placed before it), else directly + * before its nearest such sibling below, else at the end. So a layer added at the top of the file + * lands first, and one added between two layers lands between their drawables. + * + * @property SourceArt art The whole file, for the siblings. + * @property PuppetModel existing The model, for what each container already holds. + * @property ArtSourceId sourceId The file's record, for the bindings that name existing drawables. + * @property Map existingPartByPath The part the document keeps per folder path. + * @property List imported The layers this delta minted, with their drawables. + */ + private class InsertionPlacer( + private val art: SourceArt, + private val existing: PuppetModel, + sourceId: ArtSourceId, + private val existingPartByPath: Map, + imported: List, + ) { + /** The drawables each layer key has: the delta's new one, else every existing drawable over the bound tile. */ + private val drawablesByKey: Map> = boundDrawablesByLayerKey(existing, sourceId) + imported.associate { entry -> entry.layer.id.raw to listOf(entry.drawableId) } + + /** Each folder's top-most layer order over the WHOLE file, so a sub-folder sorts among layers. */ + private val minOrderByPath: Map = minOrderByGroupPath(art) + + /** The parts this delta minted, by folder path, so a later child can anchor on a new folder. */ + private val newPartByPath = HashMap() + + /** + * Places [gathered]'s children into [container], appending one insertion per child to [into]. + * + * @param PartId? container The part, or null for the root. + * @param String containerPath The folder path the container stands for ("" at the root). + * @param List gathered The new children, in any order. + * @param MutableList parts Every part minted so far, appended to for a new folder. + * @param IdMinter minter The id sequence a new folder's part takes. + * @param MutableList notices Appended with a new folder's composite notes. + * @param MutableList into The insertions, appended in the file's order. + */ + fun place( + container: PartId?, + containerPath: String, + gathered: List, + parts: MutableList, + minter: IdMinter, + notices: MutableList, + into: MutableList, + ) { + val existingChildren = if (container == null) existing.rootChildren else existing.parts.first { part -> part.id == container }.children + val present = HashSet(existingChildren) + val siblings = fileSiblingsOf(containerPath) + for (child in gathered.sortedBy { candidate -> candidate.order }) { + val orgChild = + when (child) { + is FolderChild.Layer -> OrgChild.Drawable(child.drawableId) + is FolderChild.Folder -> { + val minted = orgChildrenOf(listOf(child), parts, minter, notices).single() + newPartByPath[child.node.path] = (minted as OrgChild.Part).id + minted + } + } + into.add(OrgInsertion(container, orgChild, slotFor(child.order, siblings, present, orgChild))) + present.add(orgChild) + } + } + + /** + * The file's direct children of [containerPath], sorted by the order they sit at. + * + * @param String containerPath The folder ("" at the root). + * @return List The layers and sub-folders, top-most first. + */ + private fun fileSiblingsOf(containerPath: String): List { + val siblings = ArrayList() + for (layer in art.layers) { + if (layer.groupPath == containerPath) { + siblings.add(FileSibling.Layer(layer.order, layer.id.raw)) + } + } + val folderPaths = LinkedHashSet(minOrderByPath.keys) + for (group in art.groups) { + folderPaths.add(group.path) + } + for (path in folderPaths) { + if (path.substringBeforeLast('/', missingDelimiterValue = "") == containerPath && path != containerPath) { + siblings.add(FileSibling.Folder(minOrderByPath[path] ?: Int.MAX_VALUE, path)) + } + } + return siblings.sortedBy { sibling -> sibling.order } + } + + /** + * Where a child at [order] goes among [siblings]: after the nearest one above the container can + * show, else before the nearest one below it can, else at the end. + * + * @param Int order The child's order in the file. + * @param List siblings The container's children as the file orders them. + * @param Set present What the container holds now, this delta's earlier placements included. + * @param OrgChild self The child being placed, never its own anchor. + * @return OrgSlot The slot. + */ + private fun slotFor(order: Int, siblings: List, present: Set, self: OrgChild): OrgSlot { + for (sibling in siblings.filter { candidate -> candidate.order < order }.asReversed()) { + val anchor = shownChildOf(sibling, present, self) + if (anchor != null) { + return OrgSlot.After(anchor) + } + } + for (sibling in siblings.filter { candidate -> candidate.order > order }) { + val anchor = shownChildOf(sibling, present, self) + if (anchor != null) { + return OrgSlot.Before(anchor) + } + } + return OrgSlot.End + } + + /** + * The child the container shows for [sibling], or null when it shows none: a skipped layer, a + * layer whose drawable the rigger moved elsewhere, a folder with no part. + * + * @param FileSibling sibling The layer or folder. + * @param Set present What the container holds. + * @param OrgChild self The child being placed. + * @return OrgChild? The shown child, or null. + */ + private fun shownChildOf(sibling: FileSibling, present: Set, self: OrgChild): OrgChild? { + val candidates = + when (sibling) { + is FileSibling.Layer -> drawablesByKey[sibling.key].orEmpty().map { drawableId -> OrgChild.Drawable(drawableId) } + is FileSibling.Folder -> listOfNotNull((existingPartByPath[sibling.path] ?: newPartByPath[sibling.path])?.let { partId -> OrgChild.Part(partId) }) + } + return candidates.firstOrNull { candidate -> candidate != self && candidate in present } + } + } + + /** + * Every existing drawable each layer of [sourceId]'s file has, by the layer's key: the tiles bound + * to the file and the drawables over them. + * + * @param PuppetModel existing The model. + * @param ArtSourceId sourceId The file. + * @return Map The drawable ids per bound layer key. + */ + private fun boundDrawablesByLayerKey(existing: PuppetModel, sourceId: ArtSourceId): Map> { + val drawablesByTile = existing.drawables.groupBy { drawable -> drawable.atlasTileId } + val result = HashMap>() + for (tile in existing.atlas.tiles) { + val ref = tile.source ?: continue + if (ref.sourceId != sourceId) { + continue + } + val drawables = drawablesByTile[tile.id].orEmpty().map { drawable -> drawable.id } + if (drawables.isNotEmpty()) { + result[ref.layerKey] = result[ref.layerKey].orEmpty() + drawables + } + } + return result + } + + /** + * The top-most layer order under every folder path of [art], the folder's own order among its siblings. + * + * @param SourceArt art The file. + * @return Map The minimum order per folder path; a folder with no layer under it is absent. + */ + private fun minOrderByGroupPath(art: SourceArt): Map { + val minOrder = HashMap() + for (layer in art.layers) { + for (path in ancestorPathsOf(layer.groupPath)) { + minOrder[path] = minOf(minOrder[path] ?: Int.MAX_VALUE, layer.order) + } + } + return minOrder + } + + /** + * Which of [existing]'s parts stands for each folder of [sourceId]'s file: for every drawable bound + * to the file, its layer's folder (from the recorded inventory) and the part holding the drawable + * directly; a folder maps to the part holding the most of its drawables, and a folder with no + * drawable of its own (one holding only sub-folders) to the part that holds a mapped sub-folder's + * part. A CMO3-origin document has no folder binding on its parts, so this is what says "Front + * hair" already exists. + * + * @param PuppetModel existing The model the additions will join. + * @param ArtSourceId sourceId The file whose folders are being placed. + * @return Map The part per folder path; a folder reached by neither rule is absent. + */ + private fun existingPartsByFolder(existing: PuppetModel, sourceId: ArtSourceId): Map { + val rowByKey = existing.sources.firstOrNull { source -> source.id == sourceId }?.layers?.associateBy { row -> row.key }.orEmpty() + val folderByDrawable = HashMap() + for (drawable in existing.drawables) { + val tile = drawable.atlasTileId?.let { tileId -> existing.atlas.tileById[tileId] } ?: continue + val ref = tile.source ?: continue + if (ref.sourceId != sourceId) { + continue + } + val folder = rowByKey[ref.layerKey]?.groupPath ?: continue + if (folder.isNotEmpty()) { + folderByDrawable[drawable.id] = folder + } + } + val countByFolderAndPart = LinkedHashMap>() + val parentByPart = HashMap() + for (part in existing.parts) { + for (child in part.children) { + when (child) { + is OrgChild.Part -> parentByPart[child.id] = part.id + is OrgChild.Drawable -> { + val folder = folderByDrawable[child.id] ?: continue + val counts = countByFolderAndPart.getOrPut(folder) { LinkedHashMap() } + counts[part.id] = (counts[part.id] ?: 0) + 1 + } + } + } + } + val partByFolder = LinkedHashMap() + for ((folder, counts) in countByFolderAndPart) { + partByFolder[folder] = counts.maxBy { (_, count) -> count }.key + } + // A folder no drawable sits in directly is reached through a mapped sub-folder: its part is the + // one holding that sub-folder's part. A direct mapping always wins over an inferred one. + for ((folder, partId) in countByFolderAndPart.keys.associateWith { folder -> partByFolder.getValue(folder) }) { + var ancestorFolder = folder.substringBeforeLast('/', missingDelimiterValue = "") + var ancestorPart = parentByPart[partId] + while (ancestorFolder.isNotEmpty() && ancestorPart != null && ancestorFolder !in partByFolder) { + partByFolder[ancestorFolder] = ancestorPart + ancestorFolder = ancestorFolder.substringBeforeLast('/', missingDelimiterValue = "") + ancestorPart = parentByPart[ancestorPart] + } + } + return partByFolder + } + + /** + * Every folder path along [groupPath], outermost first ("Head", "Head/Hair", ...); empty at the root. + * + * @param String groupPath The slash-joined path. + * @return List The ancestor paths, the path itself last. + */ + private fun ancestorPathsOf(groupPath: String): List { + if (groupPath.isEmpty()) { + return emptyList() + } + val paths = ArrayList() + var path = "" + for (segment in groupPath.split('/')) { + path = if (path.isEmpty()) segment else "$path/$segment" + paths.add(path) + } + return paths + } + + /** + * The pixel-free layer inventory of [art], top-most first: EVERY layer, skipped ones included, so a + * re-import can tell a layer that was there and unusable from one that is new. The record a fresh + * import stores and a reload replaces. Each raster layer carries the content hash of its pixels, + * the one thing about the pixels the inventory keeps, so a later read can recognize a renamed layer + * whose art did not change. + * + * @param SourceArt art The parsed source art. + * @return List The inventory rows, in the file's own draw order. + */ + fun inventoryOf(art: SourceArt): List = + art.layers.sortedBy { layer -> layer.order }.map { layer -> + ArtSourceLayer( + key = layer.id.raw, + name = layer.name, + groupPath = layer.groupPath, + left = layer.bounds.left, + top = layer.bounds.top, + width = layer.bounds.width, + height = layer.bounds.height, + visible = layer.visible, + contentHash = if (layer.kind == SourceLayerKind.Raster) contentHashOf(layer.raster.rgba) else null, + empty = layer.kind == SourceLayerKind.Raster && layer.raster.isFullyTransparent(), + ) + } + + /** + * The suffix the next id in a `` sequence takes: one past the highest suffix among + * [ids] that carry the prefix and a numeric tail, or [first] when none does. + * + * @param Iterable ids The ids already in use. + * @param String prefix The sequence's prefix. + * @param Int first The suffix a fresh sequence starts at. + * @return Int The next suffix. + */ + private fun nextSuffix(ids: Iterable, prefix: String, first: Int): Int { + var highest: Int? = null + for (id in ids) { + if (!id.startsWith(prefix)) { + continue + } + val suffix = id.substring(prefix.length).toIntOrNull() ?: continue + if (highest == null || suffix > highest) { + highest = suffix + } + } + return if (highest == null) first else highest + 1 + } + + /** + * The quad a layer is born with, over its opaque bounds as [analyzeAlpha] found them - the mesh an + * import gives every drawable, and the one a reload gives back to a drawable whose quad was never + * edited. Null when the layer has no opaque pixel under [alphaThreshold], which is the layer the + * import skips. + * + * @param SourceLayer layer The layer. + * @param Int alphaThreshold The minimum alpha byte (1..255) for a pixel to count as art. + * @param Int margin How far the quad extends past the opaque bounds on every side. + * @return DrawableMesh? The two-triangle quad, or null for a layer with no art. + */ + fun birthMeshFor(layer: SourceLayer, alphaThreshold: Int, margin: Int): DrawableMesh? { + val analysis = layer.analyzeAlpha(alphaThreshold = alphaThreshold) ?: return null + val bounds = analysis.opaqueBounds + return birthQuad(layer, bounds.left, bounds.top, bounds.width, bounds.height, margin) + } + + /** + * The quad a layer is born with: the layer's opaque bounds grown by [margin] on every side, as + * canvas-pixel positions and art-frame coordinates that are two views of the same rectangle. + * + * The quad may overhang the layer's raster (the margin is not clamped): the mesh's reach is what + * the pack reserves around the tile, and a coordinate past the raster's edge samples the gutter + * the pack keeps clear there. + * + * @param SourceLayer layer The layer. + * @param Int trimLeft The opaque bounds' left edge, raster-local. + * @param Int trimTop The opaque bounds' top edge, raster-local. + * @param Int trimWidth The opaque bounds' width. + * @param Int trimHeight The opaque bounds' height. + * @param Int margin How far the quad extends past the bounds. + * @return DrawableMesh The two-triangle quad. + */ + private fun birthQuad(layer: SourceLayer, trimLeft: Int, trimTop: Int, trimWidth: Int, trimHeight: Int, margin: Int): DrawableMesh { + val left = (trimLeft - margin).toFloat() + val top = (trimTop - margin).toFloat() + val right = (trimLeft + trimWidth + margin).toFloat() + val bottom = (trimTop + trimHeight + margin).toFloat() + val canvasLeft = layer.bounds.left.toFloat() + val canvasTop = layer.bounds.top.toFloat() + val tileWidth = layer.raster.width.toFloat() + val tileHeight = layer.raster.height.toFloat() + return DrawableMesh( + positions = + floatArrayOf( + canvasLeft + left, + canvasTop + top, + canvasLeft + right, + canvasTop + top, + canvasLeft + right, + canvasTop + bottom, + canvasLeft + left, + canvasTop + bottom, + ), + uvs = + floatArrayOf( + left / tileWidth, + top / tileHeight, + right / tileWidth, + top / tileHeight, + right / tileWidth, + bottom / tileHeight, + left / tileWidth, + bottom / tileHeight, + ), + indices = intArrayOf(0, 1, 2, 0, 2, 3), + ) + } + + /** + * A folder node carrying a source group's own attributes. + * + * @param SourceGroup group The parsed folder. + * @return FolderNode The node, with no children yet. + */ + private fun folderNodeOf(group: SourceGroup): FolderNode = + FolderNode( + path = group.path, + name = group.name, + visible = group.visible, + opacity = group.opacity, + clipped = group.clipped, + blend = group.blend, + passThrough = group.passThrough, + ) + + /** + * Makes sure every folder along [groupPath] has a node, synthesizing the ones the reader did not + * describe (a reader that flattens without folder metadata still names each layer's path). + * + * @param String groupPath The slash-joined path to ensure. + * @param MutableMap folderByPath The nodes so far, added to. + */ + private fun ensureFolders(groupPath: String, folderByPath: MutableMap) { + if (groupPath.isEmpty()) { + return + } + var path = "" + for (segment in groupPath.split('/')) { + path = if (path.isEmpty()) segment else "$path/$segment" + if (path !in folderByPath) { + folderByPath[path] = FolderNode(path, segment, visible = true, opacity = 1f, clipped = false, blend = LayerBlend.Normal, passThrough = true) + } + } + } + + /** + * Lowers one level of gathered children onto org children, minting a part per folder in pre-order + * so part ids follow the panel order. + * + * A folder composites like the art when it must: opacity under 1 or a non-Normal blend makes the + * part Isolated with that composite, since pass-through would draw its layers as if the folder were + * not there. A folder that isolates for no visible reason stays pass-through, the model's default. + * + * @param List children The gathered children of one folder (or the root). + * @param MutableList parts Every part minted so far, appended to. + * @param IdMinter minter The id sequences, advanced per part. + * @param MutableList notices The import notices, appended to. + * @return List The org children, top-most first. + */ + private fun orgChildrenOf( + children: List, + parts: MutableList, + minter: IdMinter, + notices: MutableList, + ): List = + children.sortedBy { child -> child.order }.map { child -> + when (child) { + is FolderChild.Layer -> OrgChild.Drawable(child.drawableId) + is FolderChild.Folder -> { + val node = child.node + val partId = PartId("Part${minter.nextPart}") + minter.nextPart++ + // Reserve the slot before descending so a parent's id precedes its children's. + val slot = parts.size + parts.add(Part(partId, node.name, emptyList())) + val nestedChildren = orgChildrenOf(node.children, parts, minter, notices) + val blendMapping = mapLayerBlend(node.blend) + if (blendMapping == LayerBlendMapping.Unsupported) { + notices.add(SourceArtImportNotice.FolderBlendUnsupported(node.path, node.blend)) + } + if (node.clipped) { + notices.add(SourceArtImportNotice.FolderClipDropped(node.path)) + } + val composites = node.opacity < 1f || blendMapping.blendMode != BlendMode.Normal + parts[slot] = + Part( + id = partId, + name = node.name, + children = nestedChildren, + isVisible = node.visible, + groupMode = if (composites) PartGroupMode.Isolated else PartGroupMode.PassThrough, + composite = if (composites) PartComposite(blendMode = blendMapping.blendMode, opacity = node.opacity) else PartComposite(), + ) + OrgChild.Part(partId) + } + } + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtImportNotice.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtImportNotice.kt new file mode 100644 index 0000000..f0b161a --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtImportNotice.kt @@ -0,0 +1,43 @@ +package org.umamo.interop.art + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.SourceLayerKind +import org.umamo.runtime.model.BlendMode + +/** + * One thing an artwork import could not carry onto the model as drawn, named so the rigger can act + * on it. Anything unrepresentable surfaces as a notice, never as a silent drop - the same rule the + * export notices follow. Presentation-free: the shell logs each one and raises a single status + * notice. + */ +sealed interface SourceArtImportNotice { + /** A text, vector, adjustment, or fill layer: no stored pixels, so no drawable. */ + data class NonRasterLayer(val layerName: String, val kind: SourceLayerKind) : SourceArtImportNotice + + /** A raster layer with no pixel over the alpha threshold: nothing to mesh, so no drawable. */ + data class EmptyLayer(val layerName: String) : SourceArtImportNotice + + /** A layer blend the model has no equivalent for; the drawable falls back to Normal. */ + data class BlendUnsupported(val layerName: String, val blend: LayerBlend) : SourceArtImportNotice + + /** A layer blend carried onto its nearest model equivalent, which is not the same formula. */ + data class BlendApproximated(val layerName: String, val blend: LayerBlend, val mappedTo: BlendMode) : SourceArtImportNotice + + /** A clipping layer with no non-clipped layer below it in its folder to clip to; imported unclipped. */ + data class ClipBaseMissing(val layerName: String) : SourceArtImportNotice + + /** A layer that writes only some of its channels; the model has no per-channel masking, so all four write. */ + data class ChannelMaskDropped(val layerName: String) : SourceArtImportNotice + + /** A folder blend the model has no equivalent for; the part composites with Normal. */ + data class FolderBlendUnsupported(val groupPath: String, val blend: LayerBlend) : SourceArtImportNotice + + /** A folder that is itself a clipping layer; the part imports unclipped. */ + data class FolderClipDropped(val groupPath: String) : SourceArtImportNotice + + /** Art whose trimmed footprint does not fit the largest page the import packs against; left unpacked. */ + data class LayerLargerThanPage(val layerName: String) : SourceArtImportNotice + + /** Art the packer could not place for any other reason; left unpacked, with the packer's reason. */ + data class LayerNotPacked(val layerName: String, val reason: String) : SourceArtImportNotice +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtPlacement.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtPlacement.kt new file mode 100644 index 0000000..aad9f7b --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/art/SourceArtPlacement.kt @@ -0,0 +1,87 @@ +package org.umamo.interop.art + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer +import org.umamo.runtime.model.ArtSource + +/* + * Placing a file's art on the document canvas. Every SourceArt the model sees - the bridge's, the + * reload planner's, the matcher's - is in the DOCUMENT canvas frame, and the placement happens ONCE, + * where the file is read: the add path places a new file by its Align and Offset rows, and every + * later read of a listed file is placed by the offset its record keeps. That keeps the inventory + * rows, the birth meshes, and the reload's frame comparisons in one frame with the drawables' + * positions, so nothing downstream knows a file's own canvas ever differed from the document's. + */ + +/** + * A translation from a file's own canvas to the document canvas, in pixels along the viewport's world + * axes: x to the right and z UP. A file whose top-left corner sits below the document's carries a + * negative z, and a layer's canvas top (y down) moves by -z. + * + * @property Int x How far right of the document canvas's top-left corner the file's top-left corner sits. + * @property Int z How far up from the document canvas's top-left corner the file's top-left corner sits. + */ +data class CanvasOffset(val x: Int, val z: Int) { + /** Whether this offset moves nothing. */ + val isZero: Boolean get() = x == 0 && z == 0 + + companion object { + /** The offset of a file that shares the document's frame. */ + val Zero: CanvasOffset = CanvasOffset(0, 0) + } +} + +/** + * This art with every layer's bounds shifted by [offset], the file's canvas placed on the document's. + * + * The layers delegate everything but their bounds to the originals, so each layer's raster is the + * SAME instance: the add path's decode memo and the renderer's texture cache both key on that + * identity. The file's own canvas size and its folders pass through unchanged. A zero offset + * returns this art itself. + * + * @param CanvasOffset offset The translation. + * @return SourceArt The placed art. + */ +fun SourceArt.placedBy(offset: CanvasOffset): SourceArt { + if (offset.isZero) { + return this + } + return PlacedSourceArt(this, offset) +} + +/** + * This art placed by [source]'s recorded offset - what every read of a listed file goes through + * before the model sees it. + * + * @param ArtSource source The file's record. + * @return SourceArt The placed art. + */ +fun SourceArt.placedFor(source: ArtSource): SourceArt = placedBy(CanvasOffset(source.offsetX, source.offsetZ)) + +/** A file's art shifted onto the document canvas; see [placedBy]. */ +private class PlacedSourceArt( + private val original: SourceArt, + offset: CanvasOffset, +) : SourceArt { + override val layers: List = original.layers.map { layer -> PlacedSourceLayer(layer, offset) } + override val groups: List get() = original.groups + override val widthPx: Int get() = original.widthPx + override val heightPx: Int get() = original.heightPx +} + +/** One layer shifted onto the document canvas: the original in every respect but where it sits. */ +private class PlacedSourceLayer( + private val original: SourceLayer, + offset: CanvasOffset, +) : SourceLayer by original { + override val bounds: LayerBounds = + LayerBounds( + left = original.bounds.left + offset.x, + // Canvas y runs down and z runs up, so a file placed higher has a smaller top. + top = original.bounds.top - offset.z, + width = original.bounds.width, + height = original.bounds.height, + ) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AffineValues.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AffineValues.kt new file mode 100644 index 0000000..1d43f38 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AffineValues.kt @@ -0,0 +1,47 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.type.CAffine + +/* + * The CMO3 2x3 affine as the runtime's six-float array (m00, m01, m02, m10, m11, m12), in both + * directions. Every atlas lowering reads and writes a CAffine through these, so a transposed index + * cannot be written in one site and not another - a wrong transform in the file is exactly the + * corruption the reconcile exists to prevent. + */ + +/** + * This affine's six components in the runtime's row-major order. + * + * @return FloatArray The components (m00, m01, m02, m10, m11, m12). + */ +internal fun CAffine.toAffineArray(): FloatArray = floatArrayOf(m00, m01, m02, m10, m11, m12) + +/** + * Overwrites this affine's six components from the runtime's row-major order. + * + * @param FloatArray values The components (m00, m01, m02, m10, m11, m12). + */ +internal fun CAffine.setFromAffineArray(values: FloatArray) { + m00 = values[0] + m01 = values[1] + m02 = values[2] + m10 = values[3] + m11 = values[4] + m12 = values[5] +} + +/** + * A fresh affine holding [values]. + * + * @param FloatArray values The components (m00, m01, m02, m10, m11, m12). + * @return CAffine The new affine. + */ +internal fun affineOf(values: FloatArray): CAffine = CAffine().apply { setFromAffineArray(values) } + +/** + * An independent copy of this affine. The writer must not hoist one shared instance across the + * entry, the region input, and the model image - the editor writes separate elements. + * + * @return CAffine The copy. + */ +internal fun CAffine.copyAffine(): CAffine = affineOf(toAffineArray()) \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasIngest.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasIngest.kt new file mode 100644 index 0000000..8b96082 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasIngest.kt @@ -0,0 +1,438 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACLayerEntry +import org.umamo.format.cmo3.model.gen.ACLayerGroup +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CLayerIdentifier +import org.umamo.format.cmo3.model.gen.CLayerInputData +import org.umamo.format.cmo3.model.gen.CLayerSelectorMap +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.EnvValueSet +import org.umamo.format.cmo3.model.gen.FilterEnv +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CRect +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.cmo3.model.type.GVector2 +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.SourceLayerRef + +/** + * A CMO3's layered-art web read as model state: the atlas itself, which tile each drawable samples, + * where each tile's pixels live in the graph, and the artwork files the editor decomposed to build it. + * + * @property PuppetAtlas atlas The document's pages and tiles, with each tile's placement. + * @property Map tileIdByDrawableId Raw drawable id to the tile it samples; absent when it has none. + * @property Map imageResourceByTile The graph resource holding each tile's pixels, for the + * document's pixel supplier - metadata ingest reads no bytes, so decoding stays the caller's. + * @property List sources The layered images the editor imported, as the model's + * source list: identity, name, the advisory PSD path, and the layer inventory walked from the + * editor's decomposed layer tree ([walkLayeredImage]) - the same walk that mints each tile's binding. + */ +public class Cmo3AtlasIngest( + public val atlas: PuppetAtlas, + public val tileIdByDrawableId: Map, + public val imageResourceByTile: Map, + public val sources: List = emptyList(), +) { + public companion object { + /** What a document with no texture manager, or no model images, ingests to. */ + public val EMPTY: Cmo3AtlasIngest = Cmo3AtlasIngest(PuppetAtlas.Empty, emptyMap(), emptyMap()) + } +} + +/** + * Reads a CMO3's layered-art web into the model's atlas. + * + * The web is three joined structures and this walks all three: the texture manager's atlas pages carry + * a `ModelImageEntry` per packed image (where the packer put it), the model-image groups carry the + * images themselves (the art, and its size), and each art mesh's texture-input extension names the + * image it samples. The join key throughout is the model image's guid, which becomes the tile id. + * + * Nothing is decoded here: an image's dimensions come off its resource record, so a model with hundreds + * of layers ingests without touching a pixel. [Cmo3AtlasIngest.imageResourceByTile] is what lets the + * caller decode later, on demand. + * + * A drawable's placement is deliberately NOT resolved here. Whether a drawable reads a packed page or + * its art directly follows from the document's display mode and whether its tile was packed at all - + * both of which are model state - so the model derives it (`PuppetModel.atlasBindingFor`) rather than + * this ingest freezing an answer that an edit would then have to keep in step. + * + * @param CModelSource modelSource The CMO3's root model source. + * @return Cmo3AtlasIngest The atlas, the per-drawable tile binding, and the pixel resources. + */ +public fun cmo3AtlasIngest(modelSource: CModelSource): Cmo3AtlasIngest { + // CMO3: CModelSource field textureManager - the root of the whole layered-art web. + val textureManager = modelSource.textureManager as? CTextureManager ?: return Cmo3AtlasIngest.EMPTY + + // CMO3: CTextureManager field _textureAtlases -> CTextureAtlas fields modelImages / width / height. + // This page order is the document's, and becomes AtlasPlacement.pageIndex; it is independent of the + // renderer's own page numbering, which is derived from drawable encounter order. + val atlases = Cmo3Import.elementsOf(textureManager._textureAtlases).filterIsInstance() + val pages = atlases.map { atlas -> AtlasPage(atlas.width, atlas.height) } + // CMO3: CTextureAtlas field cachedAtlasImage - the page's own pixels. A drawable whose texture points AT + // one stores page-space coordinates. Identity membership is the test, CImageResource being a plain class. + val atlasPageResources = atlases.mapNotNull { atlas -> atlas.cachedAtlasImage as? CImageResource }.toHashSet() + val placementByModelImageGuid = HashMap() + for ((pageIndex, atlas) in atlases.withIndex()) { + for (entry in Cmo3Import.elementsOf(atlas.modelImages).filterIsInstance()) { + // CMO3: ModelImageEntry field modelImageGuid - the join back to the pooled model image. + val modelImageGuid = Cmo3Import.uuidOf(entry.modelImageGuid) ?: continue + // CMO3: ModelImageEntry field materialLocalToAtlasTransform - the packer's work, as a + // GTransform2 (position, scale, eulerAngle in DEGREES). Absent scale defaults to 1: a + // GTransform2 with no scale child is the unscaled case, not a collapse to zero. + val transform = entry.materialLocalToAtlasTransform as? GTransform2 ?: continue + val position = transform.position as? GVector2 + val scale = transform.scale as? GVector2 + placementByModelImageGuid[modelImageGuid] = + AtlasPlacement( + pageIndex = pageIndex, + positionX = position?.x ?: 0f, + positionY = position?.y ?: 0f, + scaleX = scale?.x ?: 1f, + scaleY = scale?.y ?: 1f, + rotationDegrees = transform.eulerAngle, + ) + } + } + + // CMO3: CTextureManager field _rawImages -> LayeredImageWrapper field image -> CLayeredImage fields + // guid / name / psdFile - the artwork files the editor decomposed at import, each keyed by the guid + // the selector maps below reference. psdFile is the external-reference shape: its text is + // the absolute path on the importing machine (docs/format/CMO3.md section 4), advisory here. The + // field's legacy name notwithstanding, a flat raster import lands in the same structure, so the + // format is read off the name's extension rather than assumed. + val layeredImages = + Cmo3Import.elementsOf(textureManager._rawImages).mapNotNull { wrapper -> (wrapper as? LayeredImageWrapper)?.image as? CLayeredImage } + val sources = ArrayList(layeredImages.size) + val refByLayerGuidBySource = HashMap>() + for (image in layeredImages) { + val guid = Cmo3Import.uuidOf(image.guid) ?: continue + if (guid in refByLayerGuidBySource) { + continue + } + val name = image.name?.takeIf { candidate -> candidate.isNotEmpty() } ?: guid + val inventory = layeredImageInventory(image, ArtSourceId(guid)) + refByLayerGuidBySource[guid] = inventory.refByLayerGuid + sources.add( + ArtSource( + id = ArtSourceId(guid), + name = name, + path = (image.psdFile as? FileRef)?.textPath?.takeIf { path -> path.isNotEmpty() }, + format = name.substringAfterLast('.', missingDelimiterValue = "psd").lowercase(), + layers = inventory.rows, + // CMO3: CLayeredImage field psdFileLastModified - the source's modification time when the + // editor imported it (epoch milliseconds), zero when it never recorded one. + lastModified = image.psdFileLastModified.takeIf { millis -> millis > 0L }, + ), + ) + } + + // CMO3: CTextureManager field _modelImageGroups -> CModelImageGroup field _modelImages. + val modelImages = + Cmo3Import.elementsOf(textureManager._modelImageGroups) + .filterIsInstance() + .flatMap { group -> Cmo3Import.elementsOf(group._modelImages).filterIsInstance() } + val tiles = ArrayList(modelImages.size) + val imageResourceByTile = HashMap() + val knownTileIds = HashSet() + for (modelImage in modelImages) { + // CMO3: CModelImage field guid - the key every binding and placement references. + val key = Cmo3Import.uuidOf(modelImage.guid) ?: continue + // CMO3: CModelImage field _filteredImage - the baked composite raster, carrying its own + // dimensions, so the inventory needs no decode. An image with no resource has no art to show + // and no size to place, so it is not a tile at all. + val resource = modelImage._filteredImage as? CImageResource ?: continue + val tileId = AtlasTileId(key) + knownTileIds.add(key) + imageResourceByTile[tileId] = resource + tiles.add( + AtlasTile( + id = tileId, + // CMO3: CModelImage field name - the editor writes the drawable's own name here. + name = displayNameOf(modelImage.name) ?: key, + width = resource.width, + height = resource.height, + placement = placementByModelImageGuid[key], + source = soleSourceLayerRefOf(modelImage, refByLayerGuidBySource), + ), + ) + } + + // CMO3: CDrawableSourceSet field _sources -> CArtMeshSource field _extensions. + val artMeshes = + Cmo3Import.elementsOf((modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + val tileIdByDrawableId = HashMap() + // Whether the model's coordinates address pages: a drawable samples a page, or - the same thing once + // the import has read it (Cmo3TextureFrames) - its tile is placed, since a placed tile's drawable takes + // its coordinates on the page whatever its texture names. A model saved in source-layer display points + // every drawable at a model image, yet its placed tiles still sit on the page the file carries. + var anyDrawableAddressesAPage = false + for (mesh in artMeshes) { + val drawableId = Cmo3Import.idStrOf(mesh.id) ?: continue + // CMO3: CTextureInputExtension field _textureInputs -> CTextureInput_ModelImage field + // _modelImageGuid. A drawable carrying only an atlas-region input (no model image) has no + // source art and is simply absent from the map. + val extension = + Cmo3Import.elementsOf(mesh._extensions).filterIsInstance().firstOrNull() ?: continue + val modelImageInput = + Cmo3Import.elementsOf(extension._textureInputs).filterIsInstance().firstOrNull() + ?: continue + val key = Cmo3Import.uuidOf(modelImageInput._modelImageGuid) ?: continue + if (key !in knownTileIds) { + continue + } + // CMO3: CArtMeshSource field texture -> GTexture2D field srcImageResource. + val sampledResource = (mesh.texture as? GTexture2D)?.srcImageResource as? CImageResource + if ((sampledResource != null && sampledResource in atlasPageResources) || key in placementByModelImageGuid) { + anyDrawableAddressesAPage = true + } + tileIdByDrawableId[drawableId] = AtlasTileId(key) + } + + return Cmo3AtlasIngest( + PuppetAtlas(pages, tiles, storedUvsAddressPages = anyDrawableAddressesAPage), + tileIdByDrawableId, + imageResourceByTile, + sources, + ) +} + +/** + * One decomposed artwork file's layer table: the inventory rows in the editor's stored order, and the + * binding each layer's guid resolves to, so a tile's binding and the inventory row it names are minted + * by the same pass and cannot disagree. + * + * @property List rows The inventory rows. + * @property Map refByLayerGuid Each image layer's binding, keyed by the layer entry's guid. + */ +private class LayeredImageInventory(val rows: List, val refByLayerGuid: Map) + +/** + * One image layer of a decomposed artwork file as the walk found it: the entry, the key the walk + * minted for it, whether that key is stable, its folder path, and its place in the stored order. + * + * @property CLayer layer The layer entry. + * @property String key The binding key ("lyid:", or "name:" with an order suffix on a duplicate). + * @property Boolean stable Whether the key survives a rename (an unsuffixed Photoshop layer id). + * @property String groupPath The slash-joined enclosing-folder path ("" at the root). + * @property Int order The layer's index in the stored order, top-most first. + */ +internal class WalkedCmo3Layer( + val layer: CLayer, + val key: String, + val stable: Boolean, + val groupPath: String, + val order: Int, +) + +/** + * Walks one decomposed artwork file's layer tree: every image layer under its root group, in the + * editor's stored order, with its key. + * + * Keys are minted the way the PSD reader mints them, so a CMO3-origin document and a fresh read of + * the same file agree on a layer's identity: "lyid:" when the editor recorded Photoshop's layer + * id (a stable key, the reader's own), else "name:", which is unique within the image only by + * construction - a repeated name takes an order suffix ("name:1#2") on every duplicate after the + * first, and any suffixed key is unstable by definition, because the suffix depends on the tree order. + * + * @param CLayeredImage image The layered image to walk. + * @return List The image layers, empty when the image has no layer tree. + */ +internal fun walkLayeredImage(image: CLayeredImage): List { + // CMO3: CLayeredImage field _rootLayer -> CLayerGroup, whose ACLayerGroup field _children holds the + // image layers (CLayer) and nested folders (CLayerGroup) of the decomposed file. + val root = image._rootLayer as? ACLayerGroup ?: return emptyList() + val walked = ArrayList() + val duplicateCountByKey = HashMap() + + fun walk(group: ACLayerGroup, path: String) { + for (entry in Cmo3Import.elementsOf(group._children)) { + when (entry) { + is ACLayerGroup -> { + // CMO3: ACLayerEntry field name - the folder's own name, one segment of the path. + val name = entry.name.orEmpty() + walk(entry, if (path.isEmpty()) name else "$path/$name") + } + is CLayer -> { + // CMO3: ACLayerEntry field name. + val name = entry.name.orEmpty() + val photoshopLayerId = photoshopLayerIdOf(entry.layerIdentifier) + val baseKey = if (photoshopLayerId != null) "lyid:$photoshopLayerId" else "name:$name" + val duplicateOrdinal = (duplicateCountByKey[baseKey] ?: 0) + 1 + duplicateCountByKey[baseKey] = duplicateOrdinal + val key = if (duplicateOrdinal == 1) baseKey else "$baseKey#$duplicateOrdinal" + walked.add(WalkedCmo3Layer(entry, key, stable = photoshopLayerId != null && duplicateOrdinal == 1, groupPath = path, order = walked.size)) + } + } + } + } + walk(root, "") + return walked +} + +/** + * The layer inventory of one decomposed artwork file, over [walkLayeredImage]. + * + * @param CLayeredImage image The layered image to walk. + * @param ArtSourceId sourceId The source id the bindings carry. + * @return LayeredImageInventory The rows and the per-layer bindings, both empty when the image has no + * layer tree. + */ +private fun layeredImageInventory(image: CLayeredImage, sourceId: ArtSourceId): LayeredImageInventory { + val rows = ArrayList() + val refByLayerGuid = HashMap() + for (walked in walkLayeredImage(image)) { + val entry = walked.layer + // CMO3: ACLayerEntry fields isVisible / guid; CLayer field boundsOnImageDoc, a CRect (x / y / + // width / height) placing the layer on the source document. + val bounds = entry.boundsOnImageDoc as? CRect + Cmo3Import.uuidOf(entry.guid)?.let { layerGuid -> + refByLayerGuid[layerGuid] = SourceLayerRef(sourceId, layerKey = walked.key, stableKey = walked.stable) + } + rows.add( + ArtSourceLayer( + key = walked.key, + name = entry.name.orEmpty(), + groupPath = walked.groupPath, + left = bounds?.x ?: 0, + top = bounds?.y ?: 0, + width = bounds?.width ?: 0, + height = bounds?.height ?: 0, + visible = entry.isVisible, + ), + ) + } + return LayeredImageInventory(rows, refByLayerGuid) +} + +/** + * The Photoshop layer id the editor recorded for a decomposed layer, or null when it recorded none. + * + * @param Any? identifier The layer's CLayerIdentifier slot. + * @return Int? The id, as the PSD reader's lyid integer. + */ +private fun photoshopLayerIdOf(identifier: Any?): Int? { + // CMO3: CLayerIdentifier field layerId - Photoshop's lyid (the additional-layer-info block the PSD + // reader keys on, docs/format/PSD.md) written as up to four dash-separated hex bytes, big-endian + // ("00-00-06-28" is 1576); null when the import was not a PSD. layerIdValue_testImpl mirrors it in + // decimal (-1 when absent) and is not read: the byte string is the field the editor names as the id. + val text = (identifier as? CLayerIdentifier)?.layerId?.takeIf { candidate -> candidate.isNotEmpty() } ?: return null + val byteTexts = text.split('-') + if (byteTexts.size > 4) { + return null + } + var value = 0L + for (byteText in byteTexts) { + val byteValue = byteText.toIntOrNull(16) ?: return null + if (byteValue !in 0..255) { + return null + } + value = (value shl 8) or byteValue.toLong() + } + return value.toInt() +} + +/** + * The one layer input a model image composites, with the layered image it comes from. + * + * @property String imageGuid The layered image's guid (uuid text). + * @property CLayerInputData input The layer input, whose `layer` is the composited entry. + */ +internal class SoleLayerInput(val imageGuid: String, val input: CLayerInputData) + +/** + * The one layer input of a model image's selector map, when exactly one artwork layer composites + * into it - which is every model image across the corpus - else null. Shared by the ingest's binding + * walk and the export's retained-layer rewrite, so both agree on which layer a tile IS. + * + * @param CModelImage modelImage The model image to resolve. + * @return SoleLayerInput? The input, or null. + */ +internal fun soleLayerInputOf(modelImage: CModelImage): SoleLayerInput? { + // CMO3: CModelImage field inputFilterEnv -> ModelImageFilterEnv (a FilterEnv) field envValues, a map + // from filter-value ids to EnvValueSet; the set under mi_input_layerInputData holds the + // CLayerSelectorMap whose _imageToLayerInput maps each layered image's guid to the list of layer + // inputs composited from it. Found by the value's type rather than the id: the id is an Id node + // whose equality the deserializer does not promise, and only one set holds a selector map. + val filterEnv = modelImage.inputFilterEnv as? FilterEnv ?: return null + val selectorMap = + Cmo3Import.elementsOf(filterEnv.envValues).filterIsInstance() + .firstNotNullOfOrNull { valueSet -> valueSet.value as? CLayerSelectorMap } ?: return null + val imageToInputs = selectorMap._imageToLayerInput as? Map<*, *> ?: return null + var soleImageGuid: String? = null + var soleInput: CLayerInputData? = null + var inputCount = 0 + for ((imageGuid, inputs) in imageToInputs) { + for (input in Cmo3Import.elementsOf(inputs).filterIsInstance()) { + inputCount++ + soleImageGuid = Cmo3Import.uuidOf(imageGuid) + soleInput = input + } + } + if (inputCount != 1) { + return null + } + val imageGuid = soleImageGuid ?: return null + val input = soleInput ?: return null + return SoleLayerInput(imageGuid, input) +} + +/** + * The source-layer binding of a model image, when exactly one artwork layer composites into it - + * which is every model image across the corpus - else null. + * + * The binding is the one the inventory walk minted for that layer (looked up by the layer entry's + * guid), so it names an inventory row by construction. A layer the walk never listed - one outside + * its image's root tree - falls back to an unstable name key rather than losing the binding. + * + * @param CModelImage modelImage The model image to resolve. + * @param Map refByLayerGuidBySource Each listed layered image's per-layer bindings, keyed by + * the image guid; a map keyed by an unlisted image binds to nothing rather than to a source the + * document does not have. + * @return SourceLayerRef? The binding, or null. + */ +private fun soleSourceLayerRefOf(modelImage: CModelImage, refByLayerGuidBySource: Map>): SourceLayerRef? { + val sole = soleLayerInputOf(modelImage) ?: return null + val refByLayerGuid = refByLayerGuidBySource[sole.imageGuid] ?: return null + // CMO3: CLayerInputData field layer -> ACLayerEntry fields guid / name. + val layer = sole.input.layer as? ACLayerEntry ?: return null + Cmo3Import.uuidOf(layer.guid)?.let { layerGuid -> refByLayerGuid[layerGuid] }?.let { ref -> return ref } + val layerName = layer.name?.takeIf { name -> name.isNotEmpty() } ?: return null + return SourceLayerRef(ArtSourceId(sole.imageGuid), layerKey = "name:$layerName", stableKey = false) +} + +/** + * Resolves a CMO3 name slot, which the serializer holds as `Any?` and fills with either a plain string + * or an id-bearing node. + * + * @param Any? name The raw name field. + * @return String? The display name, or null when the slot holds neither shape. + */ +private fun displayNameOf(name: Any?): String? = + when (name) { + is String -> name.takeIf { candidate -> candidate.isNotEmpty() } + is Id -> name.idstr.takeIf { candidate -> candidate.isNotEmpty() } + else -> null + } \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPages.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPages.kt new file mode 100644 index 0000000..7844c03 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPages.kt @@ -0,0 +1,104 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.interop.AtlasPageSet + +/** + * Extracts the image(s) a CMO3 model's art meshes are shown from, the images their imported coordinates + * address: a drawable over a placed tile is shown from that tile's atlas page (`CTextureAtlas.cachedAtlasImage`) + * whatever its texture names - a model saved in source-layer display still carries the page - and any other + * drawable from the image its texture names, its model image's raster standing in for a reduced cache copy + * ([Cmo3TextureFrames.renderedImageOf]). Each distinct image's embedded PNG is collected once and keyed by + * the drawable id (matching `DrawableId` from [Cmo3Import]). + * + * The pixel lookup is injected rather than taken from a `Cmo3Model`, which is what keeps this in + * commonMain: the CMO3 graph node types are all commonMain, and only the JDOM-built container wrapper + * that owns the CAFF archive is JVM-bound. The caller passes `Cmo3Model::extractLayerPng` (see the + * document loader); a test passes a map lookup. + * + * A resource carrying no bytes at all is dropped here, leaving its drawables unmapped; one carrying + * bytes that will not decode is the decoder's call, and for a CMO3 that means dropping the page rather + * than refusing the document - its pixels are embedded in the model file, so one corrupt resource + * inside an otherwise editable rig must not cost the rigger everything else. + * + * @param CModelSource modelSource The CMO3's root model source. + * @param Function readPng Yields an image resource's embedded PNG bytes, or null when it has none. + * @return AtlasPageSet The encoded pages + per-drawable index. + */ +public fun cmo3AtlasPages(modelSource: CModelSource, readPng: (CImageResource) -> ByteArray?): AtlasPageSet = + cmo3AtlasPages(modelSource, cmo3AtlasIngest(modelSource), readPng) + +/** + * [cmo3AtlasPages] over an atlas ingest the caller already holds, so the document loader walks the web once. + * + * @param CModelSource modelSource The CMO3's root model source. + * @param Cmo3AtlasIngest atlasIngest The model's atlas ingest, for each drawable's tile and placement. + * @param Function readPng Yields an image resource's embedded PNG bytes, or null when it has none. + * @return AtlasPageSet The encoded pages + per-drawable index. + */ +public fun cmo3AtlasPages( + modelSource: CModelSource, + atlasIngest: Cmo3AtlasIngest, + readPng: (CImageResource) -> ByteArray?, +): AtlasPageSet { + val sources = (modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources + val artMeshes = Cmo3Import.elementsOf(sources).filterIsInstance() + val textureFrames = Cmo3TextureFrames(modelSource) + // CMO3: CModelSource field textureManager -> CTextureManager field _textureAtlases -> CTextureAtlas field + // cachedAtlasImage, in the order a placement's pageIndex counts. + val pageImages = + Cmo3Import.elementsOf((modelSource.textureManager as? CTextureManager)?._textureAtlases) + .filterIsInstance() + .map { atlas -> atlas.cachedAtlasImage as? CImageResource } + + // Resolved once per DISTINCT resource, not per drawable: art meshes overwhelmingly share one atlas + // page, so a per-drawable lookup would repeat the archive fetch hundreds of times on a real model. + // A null value is a remembered failure (no bytes), which is why this is not a getOrPut - getOrPut + // treats a stored null as absent and would recompute it every time. + val resolvedPageIndexByResource = HashMap() + val pageBytes = ArrayList() + val atlasIndexByDrawableId = HashMap() + var premultiplied = false + + for (mesh in artMeshes) { + val drawableId = Cmo3Import.idStrOf(mesh.id) ?: continue + val texture = mesh.texture as? GTexture2D ?: continue + // CMO3: GTexture2D.isPremultiplied is an editor texture-upload-convention flag (serialized true on + // nearly every model), NOT a claim the embedded PNG is premultiplied - PngCodec decodes straight + // alpha and the shader premultiplies. Aggregated here but deliberately unconsumed downstream; do + // not drive rendering off it (that would over-darken the corpus). The version-dependent + // premultiplied-vs-straight COMPOSITING axis rides BlendMode.isLegacy, not this flag. See + // PuppetTextures.premultipliedAlpha and docs/format/CMO3.md, "Premultiplied vs straight alpha". + premultiplied = premultiplied || texture.isPremultiplied + val placement = atlasIngest.tileIdByDrawableId[drawableId]?.let { tileId -> atlasIngest.atlas.tileById[tileId]?.placement } + val resource = + if (placement != null) { + // Its coordinates are on the page; without the page's image it has nothing to show from. + pageImages.getOrNull(placement.pageIndex) ?: continue + } else { + textureFrames.renderedImageOf(mesh) ?: continue + } + val pageIndex = + if (resolvedPageIndexByResource.containsKey(resource)) { + resolvedPageIndexByResource[resource] + } else { + val resolved = + readPng(resource)?.let { png -> + pageBytes.add(png) + pageBytes.size - 1 + } + resolvedPageIndexByResource[resource] = resolved + resolved + } + if (pageIndex != null) { + atlasIndexByDrawableId[drawableId] = pageIndex + } + } + return AtlasPageSet(pageBytes, atlasIndexByDrawableId, premultiplied) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3Import.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3Import.kt new file mode 100644 index 0000000..8295b22 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3Import.kt @@ -0,0 +1,1032 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3TargetVersion +import org.umamo.format.cmo3.model.custom.CFloatColor +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CRotationDeformerForm +import org.umamo.format.cmo3.model.custom.GEditableMesh2 +import org.umamo.format.cmo3.model.gen.ACDeformerSource +import org.umamo.format.cmo3.model.gen.ACForm +import org.umamo.format.cmo3.model.gen.AlphaComposition +import org.umamo.format.cmo3.model.gen.CAffecterSourceSet +import org.umamo.format.cmo3.model.gen.CArtMeshForm +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CEditableMeshExtension +import org.umamo.format.cmo3.model.gen.CGlueForm +import org.umamo.format.cmo3.model.gen.CGlueSource +import org.umamo.format.cmo3.model.gen.CImageCanvas +import org.umamo.format.cmo3.model.gen.CParameterGroup +import org.umamo.format.cmo3.model.gen.CParameterGroupSet +import org.umamo.format.cmo3.model.gen.CParameterSource +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CPartForm +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CPartSourceSet +import org.umamo.format.cmo3.model.gen.CRotationDeformerSource +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.CWarpDeformerForm +import org.umamo.format.cmo3.model.gen.CWarpDeformerSource +import org.umamo.format.cmo3.model.gen.ColorComposition +import org.umamo.format.cmo3.model.gen.KeyFormMorphTarget +import org.umamo.format.cmo3.model.gen.KeyFormMorphTargetSet +import org.umamo.format.cmo3.model.gen.KeyOnParameter +import org.umamo.format.cmo3.model.gen.KeyformBindingSource +import org.umamo.format.cmo3.model.gen.KeyformGridAccessKey +import org.umamo.format.cmo3.model.gen.KeyformGridSource +import org.umamo.format.cmo3.model.gen.KeyformOnGrid +import org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraint +import org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraintSet +import org.umamo.format.cmo3.model.gen.Type +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.interop.alphaBlendOfToken +import org.umamo.interop.colorBlendOfToken +import org.umamo.interop.runtimeTargetOfCmo3Target +import org.umamo.runtime.keyform.asChannelTrack +import org.umamo.runtime.keyform.channelGridsOf +import org.umamo.runtime.keyform.fanOutMesh +import org.umamo.runtime.keyform.fanOutRotation +import org.umamo.runtime.keyform.fanOutWarp +import org.umamo.runtime.keyform.withChannelsCompacted +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.BlendWeightLimitPoint +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GlueForm +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.canvasCenterWorldOriginX +import org.umamo.runtime.model.canvasCenterWorldOriginZ +import org.umamo.runtime.model.deriveRenderRoot +import org.umamo.runtime.model.storedToArtAffineForTile + +/** + * Maps a parsed CMO3 model graph (`:format`) into the concrete [PuppetModel] (`:runtime`). + * + * This is the boundary that keeps CMO3's serialization quirks out of the deformation core. The + * raw graph is loosely typed (object fields are `Any?` holding already-resolved instances) and its + * structure is encoded as GUID strings (`targetDeformerGuid`, `parentGuid`, `clipGuidList`), not + * object links. So mapping is two passes: (1) index every source by its GUID uuid → runtime id; + * (2) build the runtime entities, resolving each cross-reference through those indices. + * + * @see CMO3.md §3 Model object graph + */ +object Cmo3Import { + /** + * Builds a [PuppetModel] from a CMO3 `CModelSource` root (e.g. from `Cmo3.read(file).root`). + * + * @param CModelSource modelSource The parsed model root. + * @param Boolean compactChannels Whether to run the post-import channel compaction (on by default). + * Off imports the fanned-out tracks verbatim, which is the reference an equivalence test diffs + * against and the switch to flip when bisecting a suspected compaction fault. + * @return PuppetModel The concrete runtime puppet. + */ + fun fromModelSource(modelSource: CModelSource, compactChannels: Boolean = true): PuppetModel = + importModelSource(modelSource, compactChannels).puppet + + /** + * Builds a [PuppetModel] from a CMO3 `CModelSource` root together with the atlas ingest the model was + * read from, for a caller that also needs the ingest's per-tile pixel resources (the document loader's + * byte supplier). One walk of the layered-art web serves both, so the model's tile ids and the + * supplier's keys cannot come from two runs that disagree. + * + * @param CModelSource modelSource The parsed model root. + * @param Boolean compactChannels Whether to run the post-import channel compaction; see [fromModelSource]. + * @return Cmo3ImportedDocument The puppet plus the atlas ingest it carries. + */ + fun importModelSource(modelSource: CModelSource, compactChannels: Boolean = true): Cmo3ImportedDocument { + val parameterSources = + elementsOf((modelSource.parameterSourceSet as? CParameterSourceSet)?._sources) + .filterIsInstance() + val partSources = + elementsOf((modelSource.partSourceSet as? CPartSourceSet)?._sources) + .filterIsInstance() + val deformerSources = + elementsOf((modelSource.deformerSourceSet as? CDeformerSourceSet)?._sources) + .filterIsInstance() + val drawableSources = + elementsOf((modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + + // CMO3: rootPart is the synthetic __RootPart__ tree anchor - the editor excludes it from its + // part count, and entities directly under it are top-level (partId == null). Drop it from the + // user-facing parts so the model matches the editor and null cleanly means "at the root". + val rootPart = modelSource.rootPart + val rootPartUuid = + when (rootPart) { + is CPartSource -> uuidOf(rootPart.guid) + else -> uuidOf(rootPart) + } + val userPartSources = partSources.filter { uuidOf(it.guid) != rootPartUuid } + + // Pass 1 - GUID uuid → runtime id, per category. Cross-references resolve through these. + val partIdByUuid = + buildMap { + for (part in userPartSources) { + val uuid = uuidOf(part.guid) ?: continue + val id = idStrOf(part.id) ?: continue + put(uuid, PartId(id)) + } + } + val deformerIdByUuid = + buildMap { + for (deformer in deformerSources) { + val uuid = uuidOf(deformer.guid) ?: continue + val id = idStrOf(deformer.id) ?: continue + put(uuid, DeformerId(id)) + } + } + val drawableIdByUuid = + buildMap { + for (drawable in drawableSources) { + val uuid = uuidOf(drawable.guid) ?: continue + val id = idStrOf(drawable.id) ?: continue + put(uuid, DrawableId(id)) + } + } + val paramIdByUuid = + buildMap { + for (param in parameterSources) { + val uuid = uuidOf(param.guid) ?: continue + val id = idStrOf(param.id) ?: continue + put(uuid, ParameterId(id)) + } + } + // Pass 2 - build runtime entities, resolving references through the indices above. + val parameters = + parameterSources.map { source -> + Parameter( + id = ParameterId(idStrOf(source.id).orEmpty()), + // CMO3: CParameterSource.name is the display label; fall back to the id (ParamAngleX). + name = source.name ?: idStrOf(source.id).orEmpty(), + min = source.minValue, + max = source.maxValue, + default = source.defaultValue, + // CMO3: CParameterSource field paramType - MORPH_TARGET marks a blend-shape axis. + kind = if ((source.paramType as? Type) == Type.MORPH_TARGET) ParameterKind.BLEND_SHAPE else ParameterKind.NORMAL, + ) + } + + // CMO3: CParameterSource.combined is true ONLY on the first (horizontal/X) member of a LINKED + // ("combined") pair; the next parameter in document order is its vertical (Y) member. Walk the + // sources in order and, when a combined head has a following source, emit the (X, Y) link and skip + // the consumed partner so an adjacent second pair is not mis-read as starting on that partner. A + // trailing combined head with no following member is ignored - there is no Y axis to pair. + val parameterLinks = + buildList { + var sourceIndex = 0 + while (sourceIndex < parameterSources.size) { + val source = parameterSources[sourceIndex] + val nextSource = parameterSources.getOrNull(sourceIndex + 1) + if (source.combined && nextSource != null) { + val horizontalId = idStrOf(source.id) + val verticalId = idStrOf(nextSource.id) + if (horizontalId != null && verticalId != null) { + add(ParameterLink(ParameterId(horizontalId), ParameterId(verticalId))) + } + sourceIndex += 2 + } else { + sourceIndex += 1 + } + } + } + + // CMO3: CParameterGroup is the parameter-panel group (the editor's collapsible groups). + // CModelSource.rootParameterGroup is the hidden top group; its _childGuids interleaves parameter and + // subgroup GUIDs in panel order, and each subgroup nests the same way - mirroring the parts tree's + // _childGuids walk. Each CParameterSource also carries a redundant parentGroupGuid, but the + // rootParameterGroup walk is the authoritative panel order. See docs/format/CMO3.md §3. + val parameterGroupByUuid = + buildMap { + val groups = (modelSource.parameterGroupSet as? CParameterGroupSet)?._groups + for (group in elementsOf(groups).filterIsInstance()) { + val uuid = uuidOf(group.guid) ?: continue + put(uuid, group) + } + } + val parameterTree = + buildParameterTree(modelSource.rootParameterGroup as? CParameterGroup, parameterGroupByUuid, paramIdByUuid) + + // Parts-panel pre-order index over the part tree, used to order the flat drawables list back-to-front + // (the empty-renderRoot fallback / storage order; the derived renderRoot is the draw-order authority). + val renderIndexByUuid = partsTreeRenderOrder(modelSource, partSources) + + // CMO3: CPartSource._childGuids is the parts-panel order - sub-parts and drawables interleaved (plus + // deformers, which we route to the Armature instead). Resolve each child guid to a part or drawable + // org child, skipping anything else; this ordered list is the org tree's single source of truth. + fun orgChildrenOf(childGuids: Any?): List = + elementsOf(childGuids).mapNotNull { childGuid -> + val childUuid = uuidOf(childGuid) ?: return@mapNotNull null + drawableIdByUuid[childUuid]?.let { return@mapNotNull OrgChild.Drawable(it) } + partIdByUuid[childUuid]?.let { return@mapNotNull OrgChild.Part(it) } + null + } + + // CMO3: part draw order is CPartForm.drawOrder (a keyform); the static first-cell value (else + // defaultOrder_forEditor) is the fallback, the grid carries the per-pose blend for a group part. + fun partStaticDrawOrder(part: CPartSource): Int = + elementsOf(part.keyforms).filterIsInstance().firstOrNull()?.drawOrder ?: part.defaultOrder_forEditor + + // A 5.3-authored part is marked by a present colorComposition (the offscreen probe pins this on every + // corpus file); a pre-5.3 part has it null. + fun isPre53Part(part: CPartSource): Boolean = part.colorComposition == null + + // CMO3: CPartForm.opacity is @DontSerializeIfDefault with a 0f default, and pre-5.3 parts never author + // the float, so it parses as 0f meaning "unset -> fully opaque" (Cubism's semantic default is 100%), + // NOT 0%. A 5.3 part authors opacity explicitly, so a genuine 0 there (e.g. a draw-order crossfade + // keyform) is a real value and is left alone - only pre-5.3's unset 0f is remapped to opaque. Without + // this a pre-5.3 model's whole part subtree renders invisible under the part-opacity cascade. + fun resolvedPartOpacity(rawOpacity: Float, isPre53: Boolean): Float = + if (isPre53 && rawOpacity == 0f) { + 1f + } else { + rawOpacity + } + + fun partChannelsOf(part: CPartSource): ChannelGrids { + val bundled = + buildGrid(part.keyformGridSource, part.keyforms, paramIdByUuid) { form -> + // CMO3: CPartForm carries the part's keyformed channels - drawOrder always, and (5.3) + // opacity/multiplyColor/screenColor for the layer composite. + (form as? CPartForm)?.let { + PartForm( + drawOrder = it.drawOrder.toFloat(), + opacity = resolvedPartOpacity(it.opacity, isPre53Part(part)), + multiplyColor = colorRgbOf(it.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(it.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + } + // A grid with no parameter axes is a single static cell - it carries nothing the eval reads + // beyond Part.drawOrder (kept separately) and the opacity/color channels, which then fall back + // to the part's PartComposite. Dropping it means an isolated static part honors an edited + // composite opacity/color, and it matches Moc3Import, which yields no track for an unbound + // part. A part with real animation keeps its tracks (non-empty axes). + ?.takeIf { it.axes.isNotEmpty() } ?: return ChannelGrids.Empty + // Fan the one bundled grid out into per-channel tracks sharing its axes: a pure re-shape, so the + // blended values are bit-identical to what the bundled cell produced. + return channelGridsOf( + FormChannel.DRAW_ORDER to bundled.asChannelTrack { form -> ChannelValue.Scalar(form.drawOrder) }, + FormChannel.OPACITY to bundled.asChannelTrack { form -> ChannelValue.Scalar(form.opacity) }, + FormChannel.MULTIPLY_COLOR to bundled.asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) }, + FormChannel.SCREEN_COLOR to bundled.asChannelTrack { form -> ChannelValue.Color(form.screenColor) }, + ) + } + + // CMO3: the composition/clip fields are latent - they survive unchecking offscreen, so this is + // called for every part (not just offscreen ones) to capture the settings regardless of mode; the + // composite is only applied while the part is Isolated. Each field defaults gracefully when absent + // (colorComposition/alphaComposition -> Normal/Over via the token maps; pre-5.3 CPartForms carry no + // opacity/color elements, so firstForm's channels fall back to identity). + fun partCompositeOf(source: CPartSource): PartComposite { + val firstForm = elementsOf(source.keyforms).filterIsInstance().firstOrNull() + return PartComposite( + blendMode = colorBlendOfToken((source.colorComposition as? ColorComposition)?.name), + alphaBlendMode = alphaBlendOfToken((source.alphaComposition as? AlphaComposition)?.name), + // CMO3: CPartSource.clipGuidList - always drawable GUIDs (a part picked as Clipping ID is + // expanded to its drawables at authoring time). + maskedBy = resolveGuids(source.clipGuidList, drawableIdByUuid), + // CMO3: CPartSource.invertClippingMask - show outside the mask instead of inside. + invertMask = source.invertClippingMask, + // No form at all is already opaque; a pre-5.3 form's unset 0f is remapped to opaque too. + opacity = firstForm?.let { resolvedPartOpacity(it.opacity, isPre53Part(source)) } ?: 1f, + multiplyColor = colorRgbOf(firstForm?.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(firstForm?.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + + val parts = + userPartSources.map { source -> + Part( + id = PartId(idStrOf(source.id).orEmpty()), + // CMO3: localName is the user-facing part name; fall back to the id. + name = source.localName ?: idStrOf(source.id).orEmpty(), + children = orgChildrenOf(source._childGuids), + // CMO3: ACParameterControllableSource.isVisible = the Parts-panel eyeball (cascades to children); + // CPartSource.isSketch = the Inspector's "Guide Image" checkbox (reference-only, non-export). + isVisible = source.isVisible, + isSketch = source.isSketch, + // CMO3: ACParameterControllableSource.isLocked (inverted: Cubism lock = not selectable). + isSelectable = !source.isLocked, + // CMO3: CPartSource.useOffscreen = "offscreen drawing" (forces grouping on); + // enableDrawOrderGroup = "Group by Draw Order"; CPartForm.drawOrder = the slot. + groupMode = + when { + source.useOffscreen -> PartGroupMode.Isolated + source.enableDrawOrderGroup -> PartGroupMode.Grouped + else -> PartGroupMode.PassThrough + }, + drawOrder = partStaticDrawOrder(source), + channelGrids = partChannelsOf(source), + // The composite is stored latently on every part (not just offscreen ones): the CMO3 + // composition/clip fields survive unchecking offscreen, so we capture them regardless of the + // mode and apply them only while Isolated. partCompositeOf defaults gracefully when absent. + composite = partCompositeOf(source), + ) + } + + val deformers = + deformerSources.mapNotNull { source -> + val id = idStrOf(source.id)?.let(::DeformerId) ?: return@mapNotNull null + // CMO3: ACParameterControllableSource.localName is the user-facing deformer name; fall back to the id. + val name = source.localName ?: idStrOf(source.id).orEmpty() + // CMO3: targetDeformerGuid = parent deformer (transform tree); parentGuid = part (org tree). + val parent = deformerIdByUuid[uuidOf(source.targetDeformerGuid)] + val partId = partIdByUuid[uuidOf(source.parentGuid)] + when (source) { + is CWarpDeformerSource -> { + val fanned = buildGrid(source.keyformGridSource, source.keyforms, paramIdByUuid, ::warpForm)?.fanOutWarp() + Deformer.Warp( + id, + name, + parent, + partId, + rows = source.row, + columns = source.col, + isQuadTransform = source.isQuadTransform, + geometryGrid = fanned?.geometry, + channelGrids = fanned?.channels ?: ChannelGrids.Empty, + // CMO3: ACParameterControllableSource.isLocked (inverted: Cubism lock = not selectable). + isSelectable = !source.isLocked, + // CMO3: ACParameterControllableSource.isVisible - the deformer's own eyeball. CMO3 has + // no analogue of the MOC3's second flag, so isEnabled keeps its default. + isVisible = source.isVisible, + blendShapes = + blendShapeBindingsOf(source.keyformMorphTargetSet, source.keyforms, paramIdByUuid, ::warpForm), + ) + } + is CRotationDeformerSource -> { + val fanned = buildGrid(source.keyformGridSource, source.keyforms, paramIdByUuid, ::rotationForm)?.fanOutRotation() + Deformer.Rotation( + id, + name, + parent, + partId, + baseAngle = source.baseAngle, + geometryGrid = fanned?.geometry, + channelGrids = fanned?.channels ?: ChannelGrids.Empty, + // CMO3: ACParameterControllableSource.isLocked (inverted: Cubism lock = not selectable). + isSelectable = !source.isLocked, + // CMO3: ACParameterControllableSource.isVisible - the deformer's own eyeball. CMO3 has + // no analogue of the MOC3's second flag, so isEnabled keeps its default. + isVisible = source.isVisible, + blendShapes = + blendShapeBindingsOf(source.keyformMorphTargetSet, source.keyforms, paramIdByUuid, ::rotationForm), + ) + } + else -> null + } + } + + // Render order: drawables painted back-to-front. The parts-tree DFS (panel order, top = front) + // is front-to-back, so the drawable list is its reverse - the last panel entry is the backmost, + // drawn first. drawOrder (all 500 in the corpus) and its animation refine this later; the tree + // walk is the param-independent base. CMO3: CPartSource._childGuids holds child parts / deformers + // / meshes in panel order; the drawableSourceSet is creation order, not stacking order. The shared + // renderIndexByUuid (computed above for parts) is the source of both this order and panelOrder. + val orderedDrawableSources = drawableSources.sortedByDescending { renderIndexByUuid[uuidOf(it.guid)] ?: Int.MAX_VALUE } + + // The layered-art web, read once as model state: the atlas pages, the tiles, and which tile each + // drawable samples. Metadata only - no pixel is decoded here. + val atlasIngest = cmo3AtlasIngest(modelSource) + // Which image each drawable is shown from and which frame its stored coordinates are in. + val textureFrames = Cmo3TextureFrames(modelSource) + + val drawables = + orderedDrawableSources.map { source -> + // A placed tile's drawable takes its coordinates on the tile's page (Cmo3TextureFrames). + val storedToArt = atlasIngest.tileIdByDrawableId[idStrOf(source.id).orEmpty()]?.let { tileId -> atlasIngest.atlas.storedToArtAffineForTile(tileId) } + val mesh = meshOf(source, textureFrames, storedToArt) + // One bundled grid, then split into per-vertex deltas and the render channels. + val fannedMesh = + buildGrid(source.keyformGridSource, source.keyforms, paramIdByUuid) { form -> + meshForm(form, mesh?.positions) + }?.fanOutMesh() + Drawable( + id = DrawableId(idStrOf(source.id).orEmpty()), + // CMO3: ACParameterControllableSource.localName is the user-facing drawable name; fall back to the id. + name = source.localName ?: idStrOf(source.id).orEmpty(), + parentDeformerId = deformerIdByUuid[uuidOf(source.targetDeformerGuid)], + // CMO3: colorComposition/alphaComposition - the full 5.3 blend surface (bare legacy + // tokens on pre-5.3 meshes; every mode token maps, see BlendModeMapping). + blendMode = colorBlendOfToken((source.colorComposition as? ColorComposition)?.name), + alphaBlendMode = alphaBlendOfToken((source.alphaComposition as? AlphaComposition)?.name), + maskedBy = resolveGuids(source.clipGuidList, drawableIdByUuid), + // CMO3: ACDrawableSource.invertClippingMask - show outside the mask instead of inside. + invertMask = source.invertClippingMask, + // CMO3: CArtMeshSource.culling - back-face culling (default false = double-sided). + culling = source.culling, + // CMO3: ACParameterControllableSource.isVisible - the drawable's own eyeball (ANDed with parents). + isVisible = source.isVisible, + // CMO3: ACParameterControllableSource.isLocked (inverted: Cubism lock = not selectable). + isSelectable = !source.isLocked, + mesh = mesh, + geometryGrid = fannedMesh?.geometry, + channelGrids = fannedMesh?.channels ?: ChannelGrids.Empty, + blendShapes = + blendShapeBindingsOf(source.keyformMorphTargetSet, source.keyforms, paramIdByUuid) { form -> + meshForm(form, mesh?.positions) + }, + atlasTileId = atlasIngest.tileIdByDrawableId[idStrOf(source.id).orEmpty()], + ) + } + + // rootPartId records the synthetic root's id (for tree reconstruction / write-back) even though + // it is intentionally absent from [parts]; entities under it carry partId == null. + val rootPartId = + partSources.firstOrNull { uuidOf(it.guid) == rootPartUuid } + ?.let { idStrOf(it.id) } + ?.let(::PartId) + + // Glue affecters: seam-weld vertex pairs after deformation. CMO3 references vertices by stable UID; + // build uid→index per drawable from its editable mesh (positions[i] == editableMesh.point[i]). + val uidToIndexByDrawableId = + buildMap { + for (source in drawableSources) { + val id = idStrOf(source.id)?.let(::DrawableId) ?: continue + val pointUid = editableMeshOf(source)?.pointUid as? IntArray ?: continue + put(id, buildMap { pointUid.forEachIndexed { vertexIndex, uid -> put(uid, vertexIndex) } }) + } + } + val glues = + elementsOf((modelSource.affecterSourceSet as? CAffecterSourceSet)?._sources) + .filterIsInstance() + .mapNotNull { glue -> glueOf(glue, drawableIdByUuid, uidToIndexByDrawableId, paramIdByUuid) } + + // The org tree's top level: the synthetic root part's _childGuids (parts + drawables interleaved). + val rootChildrenFromTree = orgChildrenOf((rootPart as? CPartSource)?._childGuids) + // Safety net: any drawable the panel walk never placed (e.g. one reachable only under a deformer) is + // appended at the root, so no mesh is dropped from the outliner or the derived render order. + val placedDrawableIds = + buildSet { + rootChildrenFromTree.forEach { child -> if (child is OrgChild.Drawable) add(child.id) } + parts.forEach { part -> part.children.forEach { child -> if (child is OrgChild.Drawable) add(child.id) } } + } + val rootChildren = + rootChildrenFromTree + drawables.mapNotNull { drawable -> if (drawable.id in placedDrawableIds) null else OrgChild.Drawable(drawable.id) } + + // CMO3: CModelSource.canvas -> CImageCanvas fields pixelWidth / pixelHeight - the document canvas + // size. Drawable rest positions live in this canvas px space (Y down, the canvas rect spanning + // [0, width] x [0, height]; art may overhang it); the deform eval NEGATES Y into world space. + // A model without a canvas keeps the (0, 0) defaults. + val canvas = modelSource.canvas as? CImageCanvas + val canvasWidth = (canvas?.pixelWidth ?: 0).toFloat() + val canvasHeight = (canvas?.pixelHeight ?: 0).toFloat() + + // The world origin is the CANVAS CENTER - the same origin a MOC3 export computes for CanvasInfo + // (MOC3 §5.3 originX/originY = canvasWidth/2, canvasHeight/2 across the whole corpus). It is NOT + // CModelSource.modelInfo's CModelInfo.originInPixels: that CPoint sits at its (0, 0) default in + // every corpus model, so reading it collapses both axis lines onto the canvas corner. The center + // is canvas-space, so its y negates into world space like every vertex (a positive canvas y stored + // raw would float a full canvas above the art - the "X axis above the head" bug). The viewport + // axes cross here and snap.cursorToWorldOrigin lands here. canvasCenterWorldOriginX / Z are the one + // definition of that center, shared with the CMO3 export's check for an origin it cannot store. + + // Draw order is a pure derivation of the org tree + the parts' draw-order group flags / values, so + // the renderer's render-order tree is computed, never a parallel source of truth that can drift. + val model = + PuppetModel( + parameters = parameters, + parts = parts, + deformers = deformers, + drawables = drawables, + rootChildren = rootChildren, + rootPartId = rootPartId, + glues = glues, + parameterLinks = parameterLinks, + parameterTree = parameterTree, + canvasWidth = canvasWidth, + canvasHeight = canvasHeight, + worldOriginX = canvasCenterWorldOriginX(canvasWidth), + worldOriginZ = canvasCenterWorldOriginZ(canvasHeight), + // CMO3: CModelSource field targetVersionNo - the authored SDK target. The SDK(N/A)/Latest + // sentinel, unknown values, and an absent field all map to NoTarget, so nothing is + // restricted. + runtimeTarget = runtimeTargetOfCmo3Target(Cmo3TargetVersion.fromVersionNo(modelSource.targetVersionNo as? Int)), + // CMO3: CTextureManager field isTextureInputModelImageMode - true displays the combined + // layer images, false the packed atlas. The texture manager is mandatory even when empty + // (docs/format/CMO3.md §3), so an absent one falls back to the atlas default. + rendersFromSourceLayers = (modelSource.textureManager as? CTextureManager)?.isTextureInputModelImageMode ?: false, + atlas = atlasIngest.atlas, + sources = atlasIngest.sources, + ) + val withRenderRoot = model.copy(renderRoot = model.deriveRenderRoot()) + val puppet = if (compactChannels) withRenderRoot.withChannelsCompacted() else withRenderRoot + return Cmo3ImportedDocument(puppet, atlasIngest) + } + + /** + * Builds the parameter-panel group tree from the CMO3 root CParameterGroup, returning the root's + * children in panel order. Walks each group's `_childGuids`, resolving every entry to either a leaf + * parameter (uuid in [paramIdByUuid]) or a nested group (uuid in [groupByUuid]), recursing into the + * latter. A `visited` set guards against a malformed cyclic group reference, mirroring the parts-tree + * walk. Returns an empty list when there is no root group (a group-less model), so callers fall back + * to the flat parameter list. + * + * @param CParameterGroup? rootGroup The hidden top group (CModelSource.rootParameterGroup), or null. + * @param Map groupByUuid uuid → CParameterGroup, for resolving nested-group references. + * @param Map paramIdByUuid uuid → ParameterId, for resolving leaf parameters. + * @return List The root group's children in panel order (empty when no root group). + */ + private fun buildParameterTree( + rootGroup: CParameterGroup?, + groupByUuid: Map, + paramIdByUuid: Map, + ): List { + if (rootGroup == null) { + return emptyList() + } + val visited = HashSet() + + fun childrenOf(group: CParameterGroup): List = + buildList { + for (childGuid in elementsOf(group._childGuids)) { + val uuid = uuidOf(childGuid) ?: continue + val paramId = paramIdByUuid[uuid] + if (paramId != null) { + add(ParameterNode.Param(paramId)) + continue + } + val childGroup = groupByUuid[uuid] ?: continue + if (!visited.add(uuid)) { + continue + } + add( + ParameterNode.Group( + id = ParameterGroupId(idStrOf(childGroup.id).orEmpty()), + // CMO3: CParameterGroup.name is the group label; fall back to the id. Names are + // not unique (group names can repeat), so identity stays on the id. + name = childGroup.name ?: idStrOf(childGroup.id).orEmpty(), + // CMO3: CParameterGroup.folderIsOpened - the editor's saved expand/collapse state. + initiallyOpen = childGroup.folderIsOpened, + children = childrenOf(childGroup), + ), + ) + } + } + return childrenOf(rootGroup) + } + + /** + * The editable mesh holding a drawable's stable per-vertex UIDs (`pointUid[i]` is vertex `i`'s UID, + * since `editableMesh.point[i] == CArtMeshSource.positions[i]`). + * + * @param CArtMeshSource source The art-mesh source. + * @return GEditableMesh2? The editable mesh, or null if the extension is absent. + */ + internal fun editableMeshOf(source: CArtMeshSource): GEditableMesh2? = + elementsOf(source._extensions).filterIsInstance().firstOrNull()?.editableMesh as? GEditableMesh2 + + /** + * Maps a CMO3 `CGlueSource` to a runtime [Glue], resolving its target meshes and converting each + * UID-keyed vertex pair to mesh-local indices. CMO3: `weights`/`bindVertexUids` are `[A,B]`-interleaved + * per pair; `keyforms` (CGlueForm.intensity) drive the weld strength. + * + * @param CGlueSource glue The glue source. + * @param Map drawableIdByUuid uuid → DrawableId. + * @param Map uidToIndexByDrawableId DrawableId → (vertex uid → index). + * @param Map paramIdByUuid uuid → ParameterId (for the intensity grid). + * @return Glue? The runtime glue, or null when a target/extension is missing. + */ + private fun glueOf( + glue: CGlueSource, + drawableIdByUuid: Map, + uidToIndexByDrawableId: Map>, + paramIdByUuid: Map, + ): Glue? { + val meshA = drawableIdByUuid[uuidOf(glue.targetArtMeshA_guid)] ?: return null + val meshB = drawableIdByUuid[uuidOf(glue.targetArtMeshB_guid)] ?: return null + val weights = glue.weights as? FloatArray ?: return null + val uids = glue.bindVertexUids as? LongArray ?: return null + val uidToIndexA = uidToIndexByDrawableId[meshA] ?: return null + val uidToIndexB = uidToIndexByDrawableId[meshB] ?: return null + val pairCount = minOf(weights.size, uids.size) / 2 + val pairs = ArrayList(pairCount) + for (pairIndex in 0 until pairCount) { + val indexA = uidToIndexA[uids[pairIndex * 2].toInt()] ?: continue + val indexB = uidToIndexB[uids[pairIndex * 2 + 1].toInt()] ?: continue + pairs.add(GluePair(indexA, indexB, weights[pairIndex * 2], weights[pairIndex * 2 + 1])) + } + val intensityTrack = + buildGrid(glue.keyformGridSource, glue.keyforms, paramIdByUuid, ::glueForm) + ?.asChannelTrack { form -> ChannelValue.Scalar(form.intensity) } + // A glue with no keyed intensity welds fully, which is the runtime's long-standing fallback. + return Glue(meshA, meshB, pairs, channelGridsOf(FormChannel.GLUE_INTENSITY to intensityTrack), intensity = 1f) + } + + /** + * Glue cell payload: the weld intensity captured at one grid cell. + * + * @param Any form The form object (expected CGlueForm). + * @return GlueForm? The intensity form, or null if absent. + */ + private fun glueForm(form: Any): GlueForm? = (form as? CGlueForm)?.let { GlueForm(it.intensity) } + + /** + * Flattens a CMO3 collection field (a `CArrayList`/`ArrayList`, or a `CHashMap`) to a plain list. + * + * @param Any? collection The raw `_sources`/`_childGuids`/etc. field, held as `Any?`. + * @return List The contained elements, or empty when the field is null/unrecognised. + */ + internal fun elementsOf(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + /** + * Assigns each entity a pre-order index from a depth-first walk of the parts tree, following every + * part's ordered `_childGuids`. Drawables sorted by their index render in the editor's panel + * stacking order. Non-part children (deformers, meshes) are leaves and get an index without + * recursing; the gaps they leave do not matter since only relative order is used. + * + * @param CModelSource modelSource The model root (for `rootPart`). + * @param List partSources All part sources (including the synthetic root). + * @return Map uuid → render-order index. + */ + private fun partsTreeRenderOrder(modelSource: CModelSource, partSources: List): Map { + val partByUuid = partSources.mapNotNull { part -> uuidOf(part.guid)?.let { it to part } }.toMap() + val rootPart = modelSource.rootPart + val rootUuid = (rootPart as? CPartSource)?.let { uuidOf(it.guid) } ?: uuidOf(rootPart) + val order = HashMap() + val visited = HashSet() + var nextIndex = 0 + + fun walk(uuid: String) { + if (!visited.add(uuid)) { + return + } + order[uuid] = nextIndex++ + val part = partByUuid[uuid] ?: return + for (child in elementsOf(part._childGuids)) { + val childUuid = uuidOf(child) ?: continue + walk(childUuid) + } + } + + if (rootUuid != null) { + walk(rootUuid) + } + return order + } + + /** + * Resolves a CMO3 GUID list (e.g. `_childGuids`, `clipGuidList`) to runtime ids via [index]. + * + * @param Any? guidList A field holding a collection of `Guid` objects. + * @param Map index uuid → runtime id, from pass 1. + * @return List The resolved ids, skipping any that do not resolve. + */ + private fun resolveGuids(guidList: Any?, index: Map): List = + elementsOf(guidList).mapNotNull { index[uuidOf(it)] } + + /** + * Extracts the uuid string from a CMO3 `Guid` object, or null if absent/empty. + * + * @param Any? value A field expected to hold a `Guid`. + * @return String? The uuid, or null. + */ + internal fun uuidOf(value: Any?): String? = (value as? Guid)?.uuid?.takeIf { it.isNotEmpty() } + + /** + * Extracts the id string from a CMO3 `Id` object, or null if absent/empty. + * + * @param Any? value A field expected to hold an `Id`. + * @return String? The idstr (e.g. `ParamAngleX`, `ArtMesh82`), or null. + */ + internal fun idStrOf(value: Any?): String? = (value as? Id)?.idstr?.takeIf { it.isNotEmpty() } + + /** + * Converts a CMO3 `CFloatColor` field to the runtime [ColorRgb]. + * + * @param Any? value A field expected to hold a `CFloatColor` (channels = editor hex / 255). + * @return ColorRgb? The color, or null when absent (pre-5.3 forms carry no color elements). + */ + private fun colorRgbOf(value: Any?): ColorRgb? = + // CMO3: CFloatColor red/green/blue attributes; the alpha attribute is 1.0 in every observed + // sample and is not modeled. + (value as? CFloatColor)?.let { ColorRgb(it.red, it.green, it.blue) } + + /** + * Reads an art mesh's rest-pose geometry. CMO3: `CArtMeshSource.positions`/`uvs` are `float-array` + * (interleaved x,y), `indices` is an `int-array` (3 per triangle). + * + * The stored `uvs` reach the model through [Cmo3TextureFrames.modelUvsOf]: coordinates on an atlas page + * stay as they are, anything else is brought into its model image's raster frame (out of the editor's + * cache frame when unpacked or over a reduced copy), and a placed tile's then go on onto its page. + * + * @param CArtMeshSource source The art-mesh source. + * @param Cmo3TextureFrames textureFrames The document's texture frames. + * @param FloatArray? storedToArt The drawable's tile's model-to-art affine, or null without a tile. + * @return DrawableMesh? The base mesh, or null when the source carries no positions. + */ + private fun meshOf(source: CArtMeshSource, textureFrames: Cmo3TextureFrames, storedToArt: FloatArray?): DrawableMesh? { + val positions = source.positions as? FloatArray ?: return null + val storedUvs = source.uvs as? FloatArray ?: FloatArray(0) + val indices = source.indices as? IntArray ?: IntArray(0) + return DrawableMesh(positions, textureFrames.modelUvsOf(source, storedUvs, storedToArt), indices) + } + + /** + * Whether a drawable carries a `CTextureInput_TextureAtlasRegion` in its texture-input extension - i.e. + * it was packed into a texture atlas at some point. Packing rewrites a mesh's `uvs` into the frame of the + * image it samples, and they stay there even when the model is toggled back to combined-layer display; a + * never-packed drawable keeps its `uvs` in the editor's cache frame. A model with no atlas at all + * (MultiplyScreenColors) has only model-image inputs, so every drawable returns false. Which frame a + * drawable's coordinates are in is [Cmo3TextureFrames.storedFrameOf]'s call, of which this is one part. + * + * CMO3: CArtMeshSource _extensions -> CTextureInputExtension._textureInputs holds a + * CTextureInput_ModelImage and, once packed, a CTextureInput_TextureAtlasRegion. See docs/format/CMO3.md §4. + * + * @param CArtMeshSource source The art-mesh source. + * @return Boolean True when the drawable has an atlas-region texture input. + */ + internal fun hasAtlasRegion(source: CArtMeshSource): Boolean { + val extension = elementsOf(source._extensions).filterIsInstance().firstOrNull() ?: return false + return elementsOf(extension._textureInputs).any { it is CTextureInput_TextureAtlasRegion } + } + + /** + * Builds the keyform grid for a controllable source. CMO3: `keyformGridSource` holds the axes + * (`keyformBindings`: parameterGuid + key values) and the cells (`keyformsOnGrid`: an accessKey + * coordinate + a `keyformGuid` referencing one of the source's `keyforms` form objects). + * + * @param Any? gridSource The source's `keyformGridSource`. + * @param Any? forms The source's `keyforms` collection (the form objects). + * @param Map paramIdByUuid uuid → ParameterId, from pass 1. + * @param Function cellPayload Builds the typed form payload from a raw form object. + * @return KeyformGrid? The grid, or null when the source carries no grid. + */ + private fun buildGrid( + gridSource: Any?, + forms: Any?, + paramIdByUuid: Map, + cellPayload: (Any) -> TForm?, + ): KeyformGrid? { + val grid = gridSource as? KeyformGridSource ?: return null + val bindings = elementsOf(grid.keyformBindings).filterIsInstance() + val axes = + bindings.map { binding -> + KeyformAxis( + parameterId = paramIdByUuid[uuidOf(binding.parameterGuid)] ?: ParameterId(""), + keys = floatKeys(binding.keys), + ) + } + // accessKey entries point at a binding object (resolved by identity), giving each cell's coord. + val axisOfBinding = bindings.withIndex().associate { (index, binding) -> binding to index } + val formByUuid = formPool(forms) + val cells = + elementsOf(grid.keyformsOnGrid).filterIsInstance().mapNotNull { cell -> + val form = formByUuid[uuidOf(cell.keyformGuid)] ?: return@mapNotNull null + val payload = cellPayload(form) ?: return@mapNotNull null + val coordinate = IntArray(axes.size) + val keyList = (cell.accessKey as? KeyformGridAccessKey)?._keyOnParameterList + for (keyOnParameter in elementsOf(keyList).filterIsInstance()) { + val axisIndex = axisOfBinding[keyOnParameter.binding] ?: continue + coordinate[axisIndex] = keyOnParameter.keyIndex + } + KeyformCell(coordinate, payload) + } + return KeyformGrid(axes, cells) + } + + /** + * Decodes a binding's `keys` (an `ArrayList` of parameter values) to a FloatArray. + * + * @param Any? keys The binding's `keys` field. + * @return FloatArray The key parameter values (empty when absent). + */ + private fun floatKeys(keys: Any?): FloatArray { + val values = elementsOf(keys) + return FloatArray(values.size) { (values[it] as? Number)?.toFloat() ?: 0f } + } + + /** + * Reads a form's own guid (`ACForm.guid`), used to resolve a cell's `keyformGuid` reference. + * + * @param Any? form A form object (CArtMeshForm / CWarpDeformerForm / CRotationDeformerForm). + * @return Any? The form's `guid` (a `Guid`), or null. + */ + private fun formGuid(form: Any?): Any? = (form as? ACForm)?.guid + + /** + * Indexes a source's `keyforms` pool by each form's own guid uuid. Grid cells and morph + * targets both resolve their form references through this pool. + * + * @param Any? forms The source's `keyforms` collection (the form objects). + * @return Map The uuid → form object index. + */ + private fun formPool(forms: Any?): Map = elementsOf(forms).associateBy { uuidOf(formGuid(it)) } + + /** + * Builds a source's blend-shape bindings from its morph-target set: one binding per driving + * parameter, keys sorted with the neutral key inserted at value 0. + * + * CMO3: ACParameterControllableSource field keyformMorphTargetSet - a KeyFormMorphTargetSet + * whose _morphTargets each bind one form (keyformGuid, from the source's shared keyforms pool) + * at one keyValue on one driving parameter (parameterGuid). CMO3 stores no morph target at + * value 0 in the usual case; the baked MOC3 records carry sorted(keys + 0) with the neutral at + * value 0, so ingest inserts it here with a null form (corpus-verified rule - see + * MorphTargetJoinProbeTest). The editBaseParameterMap field is ignored: it is null in every + * corpus instance, its semantics unresolved. + * + * @param Any? morphTargetSet The source's `keyformMorphTargetSet`. + * @param Any? forms The source's `keyforms` collection (the form objects). + * @param Map paramIdByUuid uuid → ParameterId, from pass 1. + * @param Function formPayload Builds the typed form payload from a raw form object. + * @return List The bindings (empty when the source carries no morph targets). + */ + private fun blendShapeBindingsOf( + morphTargetSet: Any?, + forms: Any?, + paramIdByUuid: Map, + formPayload: (Any) -> TForm?, + ): List> { + val set = morphTargetSet as? KeyFormMorphTargetSet ?: return emptyList() + val targets = elementsOf(set._morphTargets).filterIsInstance() + if (targets.isEmpty()) { + return emptyList() + } + val formByUuid = formPool(forms) + val constraints = + elementsOf((set.blendWeightConstraintSet as? MorphTargetBlendWeightConstraintSet)?._constraints) + .filterIsInstance() + return targets.groupBy { uuidOf(it.parameterGuid) }.mapNotNull { (parameterUuid, group) -> + val parameterId = parameterUuid?.let(paramIdByUuid::get) ?: return@mapNotNull null + val neutralValue = 0f + val payloadByKey = + group.mapNotNull { target -> + val form = formByUuid[uuidOf(target.keyformGuid)] ?: return@mapNotNull null + val payload = formPayload(form) ?: return@mapNotNull null + target.keyValue to payload + }.toMap() + if (payloadByKey.isEmpty()) { + return@mapNotNull null + } + val keys = (payloadByKey.keys + neutralValue).sorted() + BlendShapeBinding( + parameterId = parameterId, + keys = keys.toFloatArray(), + neutralIndex = keys.indexOf(neutralValue), + forms = keys.map { key -> payloadByKey[key] }, + limits = blendWeightLimitsOf(constraints, parameterUuid, paramIdByUuid), + ) + } + } + + /** + * Groups a morph-target set's flat constraint records into per-parameter limit curves for one + * driving parameter. + * + * CMO3: MorphTargetBlendWeightConstraint - (morphTargetParameterGuid, constraintParameterGuid, + * constraintParameterValue, blendWeight); one curve point per record, grouped by the + * constraint parameter, sorted by its value. + * + * @param List collection The set's constraint records. + * @param String morphTargetParameterUuid The driving parameter whose limits are wanted. + * @param Map paramIdByUuid uuid → ParameterId, from pass 1. + * @return List The limit curves (empty when the set has none for this parameter). + */ + private fun blendWeightLimitsOf( + collection: List, + morphTargetParameterUuid: String, + paramIdByUuid: Map, + ): List = + collection + .filter { uuidOf(it.morphTargetParameterGuid) == morphTargetParameterUuid } + .groupBy { uuidOf(it.constraintParameterGuid) } + .mapNotNull { (constraintUuid, records) -> + val parameterId = constraintUuid?.let(paramIdByUuid::get) ?: return@mapNotNull null + BlendWeightLimit( + parameterId = parameterId, + points = + records + .sortedBy { it.constraintParameterValue } + .map { BlendWeightLimitPoint(it.constraintParameterValue, it.blendWeight) }, + ) + } + + /** + * Mesh cell payload: the form's absolute positions converted to deltas vs the mesh [base]. + * + * @param Any form The form object (expected CArtMeshForm). + * @param FloatArray? base The mesh base positions. + * @return MeshForm? The delta form, or null if the form has no positions. + */ + private fun meshForm(form: Any, base: FloatArray?): MeshForm? { + val artForm = form as? CArtMeshForm ?: return null + val positions = artForm.positions as? FloatArray ?: return null + // CMO3: ACDrawableForm.drawOrder (Cubism default 500) + opacity (0..1) + the 5.3 per-art-mesh + // multiply/screen color ride on the art-mesh keyform (pre-5.3 forms carry no color -> identity). + return MeshForm( + deltaVsBase(base, positions), + artForm.drawOrder.toFloat(), + artForm.opacity, + multiplyColor = colorRgbOf(artForm.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(artForm.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + + /** + * Warp cell payload: the form's absolute FFD control-point positions plus its render channels. + * + * The channels live on the shared `ACDeformerForm` base, so warp and rotation read them the same + * way. They cascade onto every drawable under the deformer - see `DeformerCascade`. + * + * @param Any form The form object (expected CWarpDeformerForm). + * @return WarpForm? The control points, or null if absent. + */ + private fun warpForm(form: Any): WarpForm? { + val warp = form as? CWarpDeformerForm ?: return null + val positions = warp.positions as? FloatArray ?: return null + // CMO3: ACDeformerForm opacity / multiplyColor / screenColor. + return WarpForm( + positions, + opacity = warp.opacity, + multiplyColor = colorRgbOf(warp.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(warp.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + + /** + * Rotation cell payload: the form's absolute pivot transform plus its render channels. + * + * @param Any form The form object (expected CRotationDeformerForm). + * @return RotationForm? The transform, or null if absent. + */ + private fun rotationForm(form: Any): RotationForm? { + val rotation = form as? CRotationDeformerForm ?: return null + // CMO3: ACDeformerForm opacity / multiplyColor / screenColor. + return RotationForm( + rotation.originX, + rotation.originY, + rotation.angle, + rotation.scale, + rotation.isReflectX, + rotation.isReflectY, + opacity = rotation.opacity, + multiplyColor = colorRgbOf(rotation.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(rotation.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + + /** + * Per-vertex deltas of [positions] vs [base] (`positions − base`), or a copy of positions when + * there is no size-matching base, so the form is kept absolute rather than dropped. + * + * @param FloatArray? base The mesh base positions. + * @param FloatArray positions The form's absolute positions. + * @return FloatArray The deltas, or a copy of positions. + */ + private fun deltaVsBase(base: FloatArray?, positions: FloatArray): FloatArray { + if (base == null || base.size != positions.size) { + return positions.copyOf() + } + return FloatArray(positions.size) { positions[it] - base[it] } + } +} + +/** + * A CMO3 import's two products: the runtime puppet and the atlas ingest it was built from. + * + * @property PuppetModel puppet The concrete runtime puppet. + * @property Cmo3AtlasIngest atlasIngest The layered-art web the puppet's atlas came from, carrying the + * per-tile pixel resources the model deliberately does not hold. + */ +class Cmo3ImportedDocument( + val puppet: PuppetModel, + val atlasIngest: Cmo3AtlasIngest, +) \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3LayeredArt.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3LayeredArt.kt new file mode 100644 index 0000000..9d9e380 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3LayeredArt.kt @@ -0,0 +1,120 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.type.CRect +import org.umamo.format.png.PngCodec +import org.umamo.runtime.model.ArtSourceId + +/* + * A CMO3's decomposed artwork as source art: the official editor stores every layer of an imported + * file as its own PNG at its canvas bounds (the CLayeredImage tree), so a CMO3-origin document can + * hand the reload planner a layer's pixels without the original file - what a relink reads when the + * file the document recorded is not on this machine. It is the art as the editor imported it, not + * as the artist last saved it, so a reload (which asks "what changed") reads the file, never this. + */ + +/** + * One decomposed layer as a source layer. The raster decodes on first use - a relink needs one + * layer's pixels, not the whole file's. + * + * @property WalkedCmo3Layer walked The layer as the walk found it (its key, folder, and order). + * @property Function extractPng The CMO3's PNG lookup for a resource. + */ +private class Cmo3SourceLayer( + private val walked: WalkedCmo3Layer, + private val extractPng: (CImageResource) -> ByteArray?, +) : SourceLayer { + // CMO3: CLayer field imageResource - the layer's own PNG, at the size of boundsOnImageDoc. + private val resource: CImageResource? = walked.layer.imageResource as? CImageResource + + override val id: LayerId = LayerId(walked.key) + override val name: String = walked.layer.name.orEmpty() + override val groupPath: String = walked.groupPath + override val kind: SourceLayerKind = if (resource?.imageFileBuf != null) SourceLayerKind.Raster else SourceLayerKind.Unknown + override val visible: Boolean = walked.layer.isVisible + override val idIsStable: Boolean = walked.stable + override val order: Int = walked.order + override val bounds: LayerBounds = + (walked.layer.boundsOnImageDoc as? CRect).let { rect -> + // CMO3: CLayer field boundsOnImageDoc (x / y / width / height on the source document). + LayerBounds(rect?.x ?: 0, rect?.y ?: 0, rect?.width ?: (resource?.width ?: 0), rect?.height ?: (resource?.height ?: 0)) + } + + // CMO3: ACLayerEntry fields opacity255 / isClipping / blend. + override val opacity: Float = walked.layer.opacity255 / 255f + override val clipped: Boolean = walked.layer.isClipping + override val blend: LayerBlend = layerBlendOf(walked.layer.blend) + override val raster: LayerRaster by lazy { + val decoded = resource?.let(extractPng)?.let { png -> runCatching { PngCodec.read(png) }.getOrNull() } + if (decoded != null) { + LayerRaster(decoded.width, decoded.height, decoded.rgba) + } else { + // A layer whose PNG is missing or undecodable reads as fully transparent at its bounds, which + // the planner treats as a layer with no art to give. + LayerRaster(bounds.width, bounds.height, ByteArray(bounds.width * bounds.height * 4)) + } + } +} + +/** + * The decomposed file as a source document. + * + * @property List layers The image layers, in the stored order. + * @property Int widthPx The source document's width. + * @property Int heightPx The source document's height. + */ +private class Cmo3LayeredArt( + override val layers: List, + override val widthPx: Int, + override val heightPx: Int, +) : SourceArt + +/** + * The blend a decomposed layer composites with, as the readers name it. + * + * @param Any? blend The layer's ACBlend node. + * @return LayerBlend The blend; Normal for a node the CMO3 marks unsupported or one this does not name. + */ +private fun layerBlendOf(blend: Any?): LayerBlend = + // CMO3: ACLayerEntry field blend - one of the CBlend_* classes; the editor keeps only the modes it + // composites itself and marks the rest CBlend_NotSupported. + when (blend?.let { node -> node::class.simpleName }) { + "CBlend_Multiply" -> LayerBlend.Multiply + "CBlend_LinearDodge" -> LayerBlend.Add + "CBlend_Color" -> LayerBlend.Color + else -> LayerBlend.Normal + } + +/** + * The artwork file [sourceId] names, as the CMO3 decomposed it at import: one source layer per image + * layer of the matching layered image, keyed exactly as the atlas ingest keys the document's + * bindings, with pixels read from the layer's own PNG. Null when the document lists no such image. + * + * @param CModelSource modelSource The parsed CMO3 root. + * @param ArtSourceId sourceId The source to read - the layered image's guid. + * @param Function extractPng The CMO3's PNG lookup for a resource (the codec's extractLayerPng). + * @return SourceArt? The decomposed file, or null. + */ +fun cmo3SourceArtOf(modelSource: CModelSource, sourceId: ArtSourceId, extractPng: (CImageResource) -> ByteArray?): SourceArt? { + // CMO3: CModelSource field textureManager -> CTextureManager field _rawImages -> LayeredImageWrapper + // field image -> CLayeredImage fields guid / width / height. + val textureManager = modelSource.textureManager as? CTextureManager ?: return null + val image = + Cmo3Import.elementsOf(textureManager._rawImages) + .mapNotNull { wrapper -> (wrapper as? LayeredImageWrapper)?.image as? CLayeredImage } + .firstOrNull { candidate -> Cmo3Import.uuidOf(candidate.guid) == sourceId.raw } + ?: return null + val layers = walkLayeredImage(image).map { walked -> Cmo3SourceLayer(walked, extractPng) } + return Cmo3LayeredArt(layers, image.width, image.height) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3TextureFrames.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3TextureFrames.kt new file mode 100644 index 0000000..f8d0b81 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/cmo3/Cmo3TextureFrames.kt @@ -0,0 +1,349 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.invertUvAffine + +/** + * The frame a drawable's stored texture coordinates are in, read off the image its texture names. + */ +internal enum class Cmo3StoredFrame { + /** An atlas page's own [0,1]: the drawable samples the page. */ + Page, + + /** Its model image's raster's own [0,1]: a packed drawable sampling the raster. */ + Raster, + + /** The editor's cache frame, the raster padded to a multiple of 64: unpacked, or over a reduced copy. */ + Cache, +} + +/** + * Which image each CMO3 drawable is shown from, and how its stored texture coordinates reach that image - + * the one place the CMO3 boundary decides a drawable's texture frame, on import and on export alike. + * + * The editor can point a drawable at three kinds of image: an atlas page, its model image's own raster + * (`_filteredImage`), or a reduced cache copy of that raster (a `CCachedImage` other than the raster itself, + * the raster padded to a multiple of 64 and scaled down). Stored coordinates live in one of two frames: + * the sampled image's own, or the cache frame - the padded raster, which is also the reduced copy's frame. + * A packed drawable over a page or the raster stores its sampled image's frame; an unpacked drawable, and + * any drawable over a reduced copy, stores the cache frame. `GTexture2D.transformImageResource01toLogical01` + * carries the raster-to-cache scale (raster size over its 64-aligned padding, per axis), so the cache frame + * reaches the raster through that affine's inverse. + * + * Umamo keeps no cache frame and no reduced copy, and reads every placed tile off its page. A drawable + * whose tile the editor packed (it has an atlas entry, so the tile has a placement) takes model coordinates + * in that PAGE's frame whatever its texture names: a model saved in source-layer display points its + * drawables at model images or their copies, yet its atlas page is in the file and is what the editor shows + * with the source artwork off. Any other drawable takes its model image's raster frame, and a drawable + * over a reduced copy is shown from the raster - the copy is the editor's display cache and has no meaning + * outside it. The export runs the same chain backward, so the file keeps the frame the editor reads. + * + * The tile's placement arrives as its stored-to-art affine ([org.umamo.runtime.model.storedToArtAffineForTile]): + * the import's atlas on the way in, the EDITED model's on the way out, so a repack's new placement converts + * correctly while the art frame - which a repack never moves - is what reaches the file. + * + * The set of reduced copies is taken once, from the graph as it was read. An export that rewrites a model + * image rebuilds its cache and would otherwise make its copy vanish in the middle of the pass; each query + * reads the drawable's CURRENT texture against that set, so only a deliberate retarget of the texture moves + * a drawable out of the cache frame. The atlas pages, by contrast, are read live: a pack-in points its + * drawable at a page the same export may have just minted, and that drawable stores the page's frame. + * + * @param CModelSource modelSource The CMO3's root model source, as read. + */ +internal class Cmo3TextureFrames(private val modelSource: CModelSource) { + /** Each reduced copy in the graph as read, to the model image it is a copy of; compared by identity. */ + private val ownerByReducedCopy: Map = reducedCopiesOf(modelSource) + + /** + * Whether a drawable's texture is a reduced cache copy of its model image. + * + * @param CArtMeshSource source The drawable's graph source. + * @return Boolean True when it samples a copy rather than a page or a raster. + */ + fun samplesReducedCopy(source: CArtMeshSource): Boolean = sampledResourceOf(source)?.let { resource -> resource in ownerByReducedCopy } == true + + /** + * The frame a drawable's stored coordinates are in. + * + * @param CArtMeshSource source The drawable's graph source. + * @return Cmo3StoredFrame Page over an atlas page; Cache when unpacked or over a reduced copy; else Raster. + */ + fun storedFrameOf(source: CArtMeshSource): Cmo3StoredFrame { + val sampled = sampledResourceOf(source) + return when { + sampled != null && isAtlasPage(sampled) -> Cmo3StoredFrame.Page + !Cmo3Import.hasAtlasRegion(source) || samplesReducedCopy(source) -> Cmo3StoredFrame.Cache + else -> Cmo3StoredFrame.Raster + } + } + + /** + * The image Umamo shows a drawable from: its model image's raster in place of a reduced copy, else the + * image its texture names. + * + * @param CArtMeshSource source The drawable's graph source. + * @return CImageResource? The image, or null when the drawable has no texture image. + */ + fun renderedImageOf(source: CArtMeshSource): CImageResource? { + val sampled = sampledResourceOf(source) ?: return null + // CMO3: CModelImage field _filteredImage - the raster the copy was reduced from. + return ownerByReducedCopy[sampled]?.let { owner -> owner._filteredImage as? CImageResource } ?: sampled + } + + /** + * The model coordinates of a drawable's stored ones. Page coordinates are taken verbatim. Otherwise + * the stored coordinates reach the raster frame - verbatim from Raster, through the inverse of the + * raster-to-cache affine from Cache - and a placed tile's then go on through its placement onto its page. + * + * @param CArtMeshSource source The drawable's graph source. + * @param FloatArray storedUvs The stored coordinates, interleaved (u, v). + * @param FloatArray? storedToArt The drawable's tile's model-to-art affine, or null (or the identity) + * when the tile is not placed. + * @return FloatArray The model coordinates; the same array when no remap applies. + */ + fun modelUvsOf(source: CArtMeshSource, storedUvs: FloatArray, storedToArt: FloatArray? = null): FloatArray { + val frame = storedFrameOf(source) + if (frame == Cmo3StoredFrame.Page) { + return storedUvs + } + val artUvs = if (frame == Cmo3StoredFrame.Cache) rasterUvsOfCache(source, storedUvs) else storedUvs + val artToModel = storedToArt?.takeUnless(::isIdentityAffine)?.let(::invertUvAffine) ?: return artUvs + return applyUvAffine(artUvs, artToModel) + } + + /** + * Cache-frame coordinates brought into the raster frame through the inverse of the raster-to-cache affine. + * + * @param CArtMeshSource source The drawable's graph source. + * @param FloatArray cacheUvs The coordinates in the cache frame. + * @return FloatArray The raster-frame coordinates; the same array when the affine is absent or degenerate. + */ + private fun rasterUvsOfCache(source: CArtMeshSource, cacheUvs: FloatArray): FloatArray { + val affine = cacheAffineOf(source) ?: return cacheUvs + val determinant = affine.m00 * affine.m11 - affine.m01 * affine.m10 + // A degenerate affine would invert to NaN or infinity; the coordinates stay as stored. + if (determinant == 0f) { + return cacheUvs + } + val rasterUvs = FloatArray(cacheUvs.size) + var componentIndex = 0 + while (componentIndex + 1 < cacheUvs.size) { + rasterUvs[componentIndex] = inverseU(affine, determinant, cacheUvs[componentIndex], cacheUvs[componentIndex + 1]) + rasterUvs[componentIndex + 1] = inverseV(affine, determinant, cacheUvs[componentIndex], cacheUvs[componentIndex + 1]) + componentIndex += 2 + } + return rasterUvs + } + + /** + * The stored coordinates of a drawable's model ones - [modelUvsOf] run backward. Page coordinates are + * stored verbatim. Otherwise a placed tile's model coordinates come off its page through the placement + * into the raster frame, which Raster stores verbatim and Cache through the raster-to-cache affine. + * + * A coordinate pair the edit left alone keeps its stored value, so the float round trip cannot drift a + * file the rigger did not touch there. That needs both the stored and the baseline model coordinates, + * and is only sound when the tile's placement is the one those were read under - the caller passes them + * only then. Without them every pair is converted, and a converted pair re-imports within a few ULPs of + * the model's value: through a scale, not every float has a float that maps onto it exactly. + * + * @param CArtMeshSource source The drawable's graph source. + * @param FloatArray modelUvs The model coordinates to store, interleaved (u, v). + * @param FloatArray? storedToArt The drawable's tile's model-to-art affine in the model being stored, + * or null (or the identity) when the tile is not placed. + * @param FloatArray? storedUvs The coordinates the graph stores now, or null. + * @param FloatArray? baselineUvs The model coordinates [storedUvs] import to, or null. + * @return FloatArray The coordinates to store, a fresh array. + */ + fun storedUvsOf( + source: CArtMeshSource, + modelUvs: FloatArray, + storedToArt: FloatArray? = null, + storedUvs: FloatArray? = null, + baselineUvs: FloatArray? = null, + ): FloatArray { + val frame = storedFrameOf(source) + if (frame == Cmo3StoredFrame.Page) { + return modelUvs.copyOf() + } + val artUvs = storedToArt?.takeUnless(::isIdentityAffine)?.let { affine -> applyUvAffine(modelUvs, affine) } ?: modelUvs + val cacheAffine = if (frame == Cmo3StoredFrame.Cache) cacheAffineOf(source) else null + val keptStored = storedUvs?.takeIf { stored -> stored.size == modelUvs.size && baselineUvs?.size == modelUvs.size } + val result = FloatArray(modelUvs.size) + var componentIndex = 0 + while (componentIndex + 1 < modelUvs.size) { + val unchangedPair = + baselineUvs != null && + modelUvs[componentIndex].toRawBits() == baselineUvs[componentIndex].toRawBits() && + modelUvs[componentIndex + 1].toRawBits() == baselineUvs[componentIndex + 1].toRawBits() + if (keptStored != null && unchangedPair) { + result[componentIndex] = keptStored[componentIndex] + result[componentIndex + 1] = keptStored[componentIndex + 1] + } else if (cacheAffine != null) { + val u = artUvs[componentIndex] + val v = artUvs[componentIndex + 1] + result[componentIndex] = cacheAffine.m00 * u + cacheAffine.m01 * v + cacheAffine.m02 + result[componentIndex + 1] = cacheAffine.m10 * u + cacheAffine.m11 * v + cacheAffine.m12 + } else { + result[componentIndex] = artUvs[componentIndex] + result[componentIndex + 1] = artUvs[componentIndex + 1] + } + componentIndex += 2 + } + return result + } + + /** + * Whether a resource is one of the graph's atlas pages right now. + * + * The page's own instance, or a twin naming the same archive entry: a graph built rather than read can + * hand a texture a second resource record for the page's pixels, and it samples the page all the same. + * + * @param CImageResource resource The resource. + * @return Boolean True when some texture atlas holds it, or its archive entry, as its page image. + */ + fun isAtlasPage(resource: CImageResource): Boolean { + // CMO3: CImageResource field imageFileBuf - the archive entry holding the pixels. + val archivePath = resource.imageFileBuf?.archivePath + // CMO3: CModelSource field textureManager -> CTextureManager field _textureAtlases -> CTextureAtlas + // field cachedAtlasImage. + return Cmo3Import.elementsOf((modelSource.textureManager as? CTextureManager)?._textureAtlases).any { atlas -> + val page = (atlas as? CTextureAtlas)?.cachedAtlasImage as? CImageResource + page != null && (page === resource || (archivePath != null && page.imageFileBuf?.archivePath == archivePath)) + } + } + + /** + * Whether a drawable is shown from a model image: it samples the image's raster, or a reduced copy of it + * as the graph was read. + * + * @param CArtMeshSource source The drawable's graph source. + * @param CModelImage modelImage The model image. + * @return Boolean True when the drawable's texture is the image's raster or one of its copies. + */ + fun isShownFrom(source: CArtMeshSource, modelImage: CModelImage): Boolean { + val sampled = sampledResourceOf(source) ?: return false + // CMO3: CModelImage field _filteredImage. + return sampled === modelImage._filteredImage || ownerByReducedCopy[sampled] === modelImage + } + + /** + * Whether a resource was a reduced copy when the graph was read. + * + * @param CImageResource resource The resource. + * @return Boolean True for a copy. + */ + fun isReducedCopy(resource: CImageResource): Boolean = resource in ownerByReducedCopy + + private companion object { + /** + * Whether a 2x3 uv affine changes nothing. + * + * @param FloatArray affine The affine (m00, m01, m02, m10, m11, m12). + * @return Boolean True for the identity. + */ + fun isIdentityAffine(affine: FloatArray): Boolean = + affine[0] == 1f && affine[1] == 0f && affine[2] == 0f && affine[3] == 0f && affine[4] == 1f && affine[5] == 0f + + /** + * The model u a stored pair imports to: the cache frame's inverse, the one expression import uses. + * + * @param CAffine affine The raster-to-cache affine. + * @param Float determinant Its linear part's determinant, nonzero. + * @param Float storedU The stored u. + * @param Float storedV The stored v. + * @return Float The model u. + */ + fun inverseU(affine: CAffine, determinant: Float, storedU: Float, storedV: Float): Float = + (affine.m11 * (storedU - affine.m02) - affine.m01 * (storedV - affine.m12)) / determinant + + /** + * The model v a stored pair imports to: the cache frame's inverse, the one expression import uses. + * + * @param CAffine affine The raster-to-cache affine. + * @param Float determinant Its linear part's determinant, nonzero. + * @param Float storedU The stored u. + * @param Float storedV The stored v. + * @return Float The model v. + */ + fun inverseV(affine: CAffine, determinant: Float, storedU: Float, storedV: Float): Float = + (-affine.m10 * (storedU - affine.m02) + affine.m00 * (storedV - affine.m12)) / determinant + + /** + * The image a drawable's texture names. + * + * @param CArtMeshSource source The drawable's graph source. + * @return CImageResource? The image, or null without one. + */ + fun sampledResourceOf(source: CArtMeshSource): CImageResource? = + // CMO3: CArtMeshSource field texture -> GTexture2D field srcImageResource. + (source.texture as? GTexture2D)?.srcImageResource as? CImageResource + + /** + * A drawable's raster-to-cache affine, or null when it has none or it is the identity. + * + * @param CArtMeshSource source The drawable's graph source. + * @return CAffine? The affine. + */ + fun cacheAffineOf(source: CArtMeshSource): CAffine? { + // CMO3: GTexture2D field transformImageResource01toLogical01 - a CAffine taking the raster's [0,1] + // into the cache frame's [0,1]. + val affine = (source.texture as? GTexture2D)?.transformImageResource01toLogical01 as? CAffine ?: return null + val isIdentity = + affine.m00 == 1f && + affine.m01 == 0f && + affine.m02 == 0f && + affine.m10 == 0f && + affine.m11 == 1f && + affine.m12 == 0f + return affine.takeUnless { isIdentity } + } + + /** + * Every reduced copy in the graph, to the model image it is a copy of. + * + * A copy is any cached image of a model image other than the raster itself; an atlas page is never + * one, even should a cache ever name it. + * + * @param CModelSource modelSource The CMO3's root model source. + * @return Map The copies and their owners. + */ + fun reducedCopiesOf(modelSource: CModelSource): Map { + // CMO3: CModelSource field textureManager. + val textureManager = modelSource.textureManager as? CTextureManager ?: return emptyMap() + // CMO3: CTextureManager field _textureAtlases -> CTextureAtlas field cachedAtlasImage. + val pages = + Cmo3Import.elementsOf(textureManager._textureAtlases).filterIsInstance() + .mapNotNull { atlas -> atlas.cachedAtlasImage as? CImageResource } + .toHashSet() + val ownerByCopy = HashMap() + // CMO3: CTextureManager field _modelImageGroups -> CModelImageGroup field _modelImages. + for (group in Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance()) { + for (modelImage in Cmo3Import.elementsOf(group._modelImages).filterIsInstance()) { + val raster = modelImage._filteredImage as? CImageResource + // CMO3: CModelImage field cachedImageManager -> CCachedImageManager field cachedImages -> + // CCachedImage field _cachedImageResource - the raster itself at SCALE_1, and a reduced + // copy beside it when the editor made one. + val manager = modelImage.cachedImageManager as? CCachedImageManager ?: continue + for (cached in Cmo3Import.elementsOf(manager.cachedImages).filterIsInstance()) { + val resource = cached._cachedImageResource as? CImageResource ?: continue + if (resource !== raster && resource !in pages) { + ownerByCopy[resource] = modelImage + } + } + } + } + return ownerByCopy + } + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3ExportOptions.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3ExportOptions.kt new file mode 100644 index 0000000..9148d04 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3ExportOptions.kt @@ -0,0 +1,42 @@ +package org.umamo.interop.moc3 + +/** + * What a MOC3 export includes, chosen at export time rather than stored on the document. + * + * The defaults here are the API's compatibility contract, not the export dialog's: an options-less + * call behaves exactly as the lowering always has - hidden objects carried with their flag clear, + * guide subtrees dropped, every sidecar emitted, and the canvas scale resolved by + * [org.umamo.interop.moc3.export.Moc3Export.mocPixelsPerUnitFor]. The dialog seeds its own + * first-launch defaults in the UI layer, and those match the official editor's bake instead + * (hidden objects dropped), so the two default sets are deliberately not the same thing. + * + * One class carries both the lowering's flags and the bundle's sidecar toggles, so an export + * handler threads a single value end to end. A future texture-resolution scale is one more + * defaulted property here. + * + * @property Boolean exportHiddenParts Write hidden part subtrees, flag clear, instead of + * dropping them the way the official bake does. + * @property Boolean exportHiddenDrawables Write drawables whose own flag is hidden, flag clear, + * instead of dropping them. + * @property Boolean exportGuideImageParts Write guide-image (sketch) subtrees instead of dropping + * them. + * @property Boolean includePhysics Carry a retained physics3.json through the bundle. + * @property Boolean includeUserData Carry a retained userdata3.json through the bundle. + * @property Boolean includeDisplayInfo Synthesize the cdi3.json display-info sidecar. + * @property Float? pixelsPerUnitOverride The bake scale to write, or null to resolve it from the + * model (the recorded scale, else the canvas width). + */ +data class Moc3ExportOptions( + val exportHiddenParts: Boolean = true, + val exportHiddenDrawables: Boolean = true, + val exportGuideImageParts: Boolean = false, + val includePhysics: Boolean = true, + val includeUserData: Boolean = true, + val includeDisplayInfo: Boolean = true, + val pixelsPerUnitOverride: Float? = null, +) { + companion object { + /** The options-less behavior: exactly what the lowering did before options existed. */ + val Default: Moc3ExportOptions = Moc3ExportOptions() + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3Sidecars.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3Sidecars.kt new file mode 100644 index 0000000..267494e --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3Sidecars.kt @@ -0,0 +1,267 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.FileKind +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.format.moc3.json.DisplayDrawable +import org.umamo.format.moc3.json.DisplayParameter +import org.umamo.format.moc3.json.DisplayParameterGroup +import org.umamo.format.moc3.json.DisplayPart +import org.umamo.format.moc3.json.FileReferences +import org.umamo.format.moc3.json.Model3Json +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.interop.ExportReport +import org.umamo.interop.moc3.export.CanvasToParentSpace +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.export.Moc3WrittenIds +import org.umamo.interop.mocVersion +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel + +/** + * Builds the whole `.moc3` FILE FAMILY - the moc, its `model3.json` manifest, a `cdi3.json` of + * display names, the atlas pages, and whatever sidecars the document was imported with. + * + * A baked model is a family, not a file: the runtime loads the manifest, and the manifest is what + * names the atlas pages a moc's texture indices point into. Writing the moc alone produces something + * no runtime can open, so the export's unit is this bundle. + * + * Everything here is pure - the caller supplies the atlas bytes and the retained sidecar texts, and + * receives named byte arrays to write wherever it likes. That keeps the family layout testable + * without a filesystem, and keeps the IO (and its per-platform limits) in the app layer. + * + * @see MOC3.md § Export + */ +object Moc3Sidecars { + /** The moc extension the family's base name is derived against, dotted for the name strip. */ + private val MOC3_EXTENSION: String = ".${FileKind.Moc3.extension}" + + /** + * The family base name for a moc file called [fileName] - every sibling is named off this. + * + * The strip ignores CASE. A file spelled `X.MOC3` would otherwise keep its extension in the base + * name, and every generated sibling - the manifest included - would be named after an `X.MOC3.moc3` + * that no write ever produces. Import and export both derive the name this way, so a re-export + * lands the family in the shape the model already used. + * + * @param String fileName The moc's own file name. + * @return String The base name the rest of the family hangs off. + */ + fun basenameFor(fileName: String): String = + if (fileName.endsWith(MOC3_EXTENSION, ignoreCase = true)) { + fileName.dropLast(MOC3_EXTENSION.length) + } else { + fileName + } + + /** The cdi3 schema version the editor writes. */ + private const val CDI3_VERSION: Int = 3 + + /** The model3 schema version the editor writes. */ + private const val MODEL3_VERSION: Int = 3 + + /** + * One file of the exported family. + * + * @property String name The file name, relative to the moc's own directory. + * @property ByteArray bytes The contents. + */ + class BundleFile(val name: String, val bytes: ByteArray) + + /** + * A retained sidecar carried through untouched. + * + * Pass-through, not synthesis: physics, poses, expressions, and user data are authored elsewhere + * and reference parameters and parts by id, which the export preserves - so re-emitting the + * original text is both lossless and the only honest option, since Umamo does not model them. + * + * @property SidecarKind kind Which sidecar this is, for the manifest wiring below. + * @property String fileName The name to write it under. + * @property String text The original file's text. + */ + class PassThroughSidecar(val kind: SidecarKind, val fileName: String, val text: String) + + /** The sidecar families a MOC3 export carries through from the imported document. */ + enum class SidecarKind { + Physics, + Pose, + UserData, + Expression, + Motion, + } + + /** + * One atlas page's bytes and the name to write them under. + * + * @property String fileName The page's file name, manifest-relative. + * @property ByteArray bytes The PNG bytes, verbatim from the source when there is one. + */ + class AtlasPage(val fileName: String, val bytes: ByteArray) + + /** + * The complete export: every file to write, plus the lowering's advisory report. + * + * @property List files The family, moc first. + * @property ExportReport report The notices from the moc lowering. + */ + class Bundle(val files: List, val mocFileName: String, val report: ExportReport) + + /** + * Builds the family for [puppet]. + * + * @param PuppetModel puppet The rig to export. + * @param String basename The family's base name (no extension). + * @param MocVersion version The moc version to bake; the document's runtime target by default. + * @param List pages The atlas pages, in the drawables' texture-page index order. + * @param List sidecars The retained sidecars to carry through. + * @param Model3Json? source The imported manifest, whose non-file sections carry through. + * @param CanvasToParentSpace? canvasToParentSpace The unkeyed-drawable space inverse, or null. + * @param Moc3ExportOptions options What the rigger chose to include; the default is the + * options-less behavior. + * @return Bundle The files to write, which of them is the moc, and the report. + */ + fun bundle( + puppet: PuppetModel, + basename: String, + version: MocVersion = puppet.runtimeTarget.mocVersion(), + pages: List, + sidecars: List = emptyList(), + source: Model3Json? = null, + canvasToParentSpace: CanvasToParentSpace? = null, + options: Moc3ExportOptions = Moc3ExportOptions.Default, + ): Bundle { + // Lowered rather than written outright, because the cdi3 below has to name the objects by the ids + // the MOC actually got: an id the record width forced short is not the id the model carries. + val lowered = Moc3Export.toMocDocument(puppet, version, canvasToParentSpace, options) + val mocBytes = Moc3.write(lowered.document) + val report = lowered.report + val mocFileName = "$basename$MOC3_EXTENSION" + // Null when the rigger opted the cdi3 out: the file and the manifest's reference to it must + // move together, or the manifest names a file the bundle does not contain. + val displayInfoName = "$basename.cdi3.json".takeIf { options.includeDisplayInfo } + val files = ArrayList(pages.size + sidecars.size + 3) + files.add(BundleFile(mocFileName, mocBytes)) + if (displayInfoName != null) { + files.add( + BundleFile(displayInfoName, Moc3.writeCdi3(displayInfo(puppet, lowered.writtenIds)).encodeToByteArray()), + ) + } + for (page in pages) { + files.add(BundleFile(page.fileName, page.bytes)) + } + for (sidecar in sidecars) { + files.add(BundleFile(sidecar.fileName, sidecar.text.encodeToByteArray())) + } + val manifest = + Model3Json( + version = MODEL3_VERSION, + fileReferences = + FileReferences( + moc = mocFileName, + textures = pages.map { page -> page.fileName }, + pose = sidecars.firstOrNull { it.kind == SidecarKind.Pose }?.fileName, + physics = sidecars.firstOrNull { it.kind == SidecarKind.Physics }?.fileName, + userData = sidecars.firstOrNull { it.kind == SidecarKind.UserData }?.fileName, + displayInfo = displayInfoName, + // Expression and motion entries carry their own fade times and group names, so the + // source's own entries are re-emitted rather than rebuilt from the file list - the + // files themselves ride along in `sidecars` under those same relative names. + expressions = source?.fileReferences?.expressions, + motions = source?.fileReferences?.motions, + ), + // Auto-wiring groups (EyeBlink / LipSync) and hit areas are USER DATA that lives only in + // the manifest. Nothing in PuppetModel holds them, so dropping them here would quietly + // delete a rigger's eye-blink wiring on the first MOC3 round trip. + groups = source?.groups, + hitAreas = source?.hitAreas, + ) + files.add(BundleFile("$basename.model3.json", Moc3.writeModel3(manifest).encodeToByteArray())) + return Bundle(files, mocFileName, report) + } + + /** + * The `cdi3.json` for [puppet]: parameter, group, part, and art-mesh display names. + * + * Written whenever [Moc3ExportOptions.includeDisplayInfo] allows it, even when every name equals + * its id. A cdi3 is what carries the ONE thing the MOC3 cannot - what the rigger called each + * object - and deciding it is "not worth writing" because this model happens to use default names + * would make the family's shape depend on the data in it. The rigger's explicit opt-out in the + * export options is the one sanctioned exception: a CHOICE may shape the family, the data may not. + * + * Every id here is the id the MOC was written with, taken from [writtenIds] rather than from the + * model: the runtime joins the two files on that string, so an id the record width forced short + * would leave its cdi3 entry naming an object the MOC3 does not contain - the display name, the + * parameter's group placement, and its combined-parameter pairing all quietly stranded. Parameter + * GROUP ids are the exception, and stay verbatim: they exist only in this file, so no MOC3 record + * bounds them. + * + * Parts and art meshes are also filtered to the ones the lowering actually WROTE - the export drops + * sketch subtrees, mesh-less drawables, and unkeyed drawables it cannot invert into parent space. + * Naming a dropped object is dead weight on its own, and worse than that alongside the shortening + * above: a dropped object claims no id, so an over-long id can shorten onto exactly its string and + * leave the file with two entries under one id for a reader's join to choose between. + * + * @param PuppetModel puppet The rig. + * @param Moc3WrittenIds writtenIds What the lowering wrote each object's id as. + * @return Cdi3Json The display info. + */ + fun displayInfo( + puppet: PuppetModel, + writtenIds: Moc3WrittenIds, + ): Cdi3Json { + val groupIdByParameter = HashMap() + val groups = ArrayList() + + /** + * Walks the parameter tree, recording each group and the group every parameter belongs to. + * + * @param List nodes The nodes at this level. + * @param String parentGroupId The enclosing group's id, empty at the root. + */ + fun walk(nodes: List, parentGroupId: String) { + for (node in nodes) { + when (node) { + is ParameterNode.Param -> groupIdByParameter[node.id.raw] = parentGroupId + is ParameterNode.Group -> { + groups.add(DisplayParameterGroup(id = node.id.raw, groupId = parentGroupId, name = node.name)) + walk(node.children, node.id.raw) + } + } + } + } + walk(puppet.parameterTree, "") + + return Cdi3Json( + version = CDI3_VERSION, + parameters = + puppet.parameters.map { parameter -> + DisplayParameter( + id = writtenIds.parameterId(parameter.id), + // Keyed by the MODEL id: the group walk above indexed the parameter tree, which + // holds model ids like everything else in the rig. + groupId = groupIdByParameter[parameter.id.raw] ?: "", + name = parameter.name, + ) + }, + parameterGroups = groups, + parts = + puppet.parts + .filter { part -> writtenIds.wrotePart(part.id) } + .map { part -> DisplayPart(id = writtenIds.partId(part.id), name = part.name) }, + // The pair order is the same one the import reads back: horizontal first, then vertical. + combinedParameters = + puppet.parameterLinks + .map { link -> + listOf(writtenIds.parameterId(link.horizontal), writtenIds.parameterId(link.vertical)) + } + .takeIf { links -> links.isNotEmpty() }, + drawables = + puppet.drawables + .filter { drawable -> writtenIds.wroteDrawable(drawable.id) } + .map { drawable -> + DisplayDrawable(id = writtenIds.drawableId(drawable.id), name = drawable.name) + } + .takeIf { meshes -> meshes.isNotEmpty() }, + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3SpaceSeam.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3SpaceSeam.kt new file mode 100644 index 0000000..6515b28 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/Moc3SpaceSeam.kt @@ -0,0 +1,231 @@ +package org.umamo.interop.moc3 + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId + +/* + * The coordinate seam between a `.moc3`'s stored values and the runtime's convention, in BOTH + * directions. + * + * MOC3 stores geometry in three different spaces depending on what an object hangs from, and only + * one of them differs from the runtime's - so an import converts a minority of values and an + * export has to invert exactly that same minority. There is also a unit seam on rotation scale + * that is easy to miss and impossible to see in a single object: the FIRST rotation on each root + * path carries the pixels-per-unit factor and every rotation below it does not. + * + * Import and export live in one file because the failure mode of two copies is invisible until it + * is catastrophic. Get the rotation-ancestor predicate subtly wrong in one of them and a whole + * subtree exports at the wrong scale, with nothing but a differential oracle to say so. + * + * @see MOC3.md §5.3 + */ + +/** The coordinate space an object's stored positions live in, selected by its parent deformer. */ +enum class PointSpace { + /** MOC3 model space (a root object): canvas = CanvasInfo origin + ppu·model, Y-down like the canvas. */ + ModelRoot, + + /** A warp parent's normalized lattice (u, v) - identical in both conventions. */ + WarpLattice, + + /** A rotation parent's pixel-scale local frame - identical in both conventions. */ + RotationLocal, +} + +/** + * The canvas mapping a `.moc3` stores, as the two numbers every conversion here needs. + * + * @property Float pixelsPerUnit Canvas pixels per model unit; 1 when the source carried no canvas. + * @property Float originX The canvas-space origin's x. + * @property Float originY The canvas-space origin's y, in CANVAS orientation (not negated). + */ +class MocCanvasMapping( + val pixelsPerUnit: Float, + val originX: Float, + val originY: Float, +) + +/** + * The scale every conversion in this file actually applies. + * + * A degenerate canvas (ppu 0) has no invertible scale: dividing by it is a division by zero, and + * multiplying by it collapses the whole rig onto the canvas origin. Both directions therefore + * substitute the identity, which is also how the import treats a canvas-less document. + * + * Shared rather than written out per direction because a guard applied on only one side is exactly + * how the two stop being inverses - the moc direction would map a degenerate canvas as the identity + * while the runtime direction flattened every point onto one spot, and nothing here would say so. + * + * @param MocCanvasMapping canvas The document's canvas mapping. + * @return Float The scale factor to apply. + */ +private fun effectiveScale(canvas: MocCanvasMapping): Float = + if (canvas.pixelsPerUnit != 0f) canvas.pixelsPerUnit else 1f + +/** + * Converts interleaved x,y [points] from the moc's stored [space] to the runtime's convention. + * + * Warp-lattice and rotation-local values are already in the runtime's convention (corpus-verified) and + * pass through untouched; only root-space values map through the canvas affine. + * + * @param PointSpace space The stored space. + * @param FloatArray points Interleaved x,y positions as stored in the moc. + * @param MocCanvasMapping canvas The document's canvas mapping. + * @return FloatArray The converted positions (always a fresh array). + */ +fun convertPointsToRuntime(space: PointSpace, points: FloatArray, canvas: MocCanvasMapping): FloatArray { + val converted = FloatArray(points.size) + val scale = effectiveScale(canvas) + var coordIndex = 0 + while (coordIndex + 1 < points.size) { + when (space) { + // MOC3 §5.3 CanvasInfo: canvas px = origin + ppu·model, same Y-down orientation. + PointSpace.ModelRoot -> { + converted[coordIndex] = canvas.originX + scale * points[coordIndex] + converted[coordIndex + 1] = canvas.originY + scale * points[coordIndex + 1] + } + // Warp-lattice (u, v) and pixel-scale rotation-local frames match the runtime verbatim. + PointSpace.WarpLattice, PointSpace.RotationLocal -> { + converted[coordIndex] = points[coordIndex] + converted[coordIndex + 1] = points[coordIndex + 1] + } + } + coordIndex += 2 + } + return converted +} + +/** + * The exact inverse of [convertPointsToRuntime]: runtime positions back to the moc's stored [space]. + * + * @param PointSpace space The space to store in. + * @param FloatArray points Interleaved x,y positions in the runtime's convention. + * @param MocCanvasMapping canvas The document's canvas mapping. + * @return FloatArray The values to store (always a fresh array). + */ +fun convertPointsToMoc(space: PointSpace, points: FloatArray, canvas: MocCanvasMapping): FloatArray { + val converted = FloatArray(points.size) + val scale = effectiveScale(canvas) + var coordIndex = 0 + while (coordIndex + 1 < points.size) { + when (space) { + PointSpace.ModelRoot -> { + converted[coordIndex] = (points[coordIndex] - canvas.originX) / scale + converted[coordIndex + 1] = (points[coordIndex + 1] - canvas.originY) / scale + } + PointSpace.WarpLattice, PointSpace.RotationLocal -> { + converted[coordIndex] = points[coordIndex] + converted[coordIndex + 1] = points[coordIndex + 1] + } + } + coordIndex += 2 + } + return converted +} + +/** + * Converts interleaved delta components from the moc's stored [space] to the runtime's convention. + * + * Unlike [convertPointsToRuntime] the canvas ORIGIN does not apply - it cancels out of a difference - + * so a root-space delta scales by ppu only; the other spaces pass through. + * + * @param PointSpace space The stored space. + * @param FloatArray deltas Interleaved x,y deltas as stored in the moc. + * @param MocCanvasMapping canvas The document's canvas mapping. + * @return FloatArray The converted deltas (always a fresh array). + */ +fun convertDeltasToRuntime(space: PointSpace, deltas: FloatArray, canvas: MocCanvasMapping): FloatArray = + when (space) { + PointSpace.ModelRoot -> { + val scale = effectiveScale(canvas) + FloatArray(deltas.size) { index -> scale * deltas[index] } + } + PointSpace.WarpLattice, PointSpace.RotationLocal -> deltas.copyOf() + } + +/** + * The exact inverse of [convertDeltasToRuntime]. + * + * @param PointSpace space The space to store in. + * @param FloatArray deltas Interleaved x,y deltas in the runtime's convention. + * @param MocCanvasMapping canvas The document's canvas mapping. + * @return FloatArray The values to store (always a fresh array). + */ +fun convertDeltasToMoc(space: PointSpace, deltas: FloatArray, canvas: MocCanvasMapping): FloatArray { + val scale = effectiveScale(canvas) + return when (space) { + PointSpace.ModelRoot -> FloatArray(deltas.size) { index -> deltas[index] / scale } + PointSpace.WarpLattice, PointSpace.RotationLocal -> deltas.copyOf() + } +} + +/** + * The px→model unit factor a rotation deformer's stored scale carries. + * + * Along every root path the FIRST rotation is where the accumulated scale chain converts pixel-scale + * local space into model units, so only that rotation's stored scale carries the factor. Every + * rotation below it - whatever its direct parent's kind - inherits it through the accumulator and + * stores its scale verbatim. + * + * @param Boolean hasRotationAncestor Whether a rotation sits anywhere above this deformer. + * @param MocCanvasMapping canvas The document's canvas mapping. + * @return Float The multiplier taking a stored scale to the runtime's, 1 when a rotation is above. + */ +fun rotationScaleFactor(hasRotationAncestor: Boolean, canvas: MocCanvasMapping): Float = + if (hasRotationAncestor) 1f else effectiveScale(canvas) + +/** + * Whether a rotation deformer sits anywhere on each deformer's ancestor chain, by FILE index. + * + * @param Int deformerCount How many deformers there are. + * @param Function parentIndexOf Each deformer's parent index (-1 at the root). + * @param Function isRotationAt Whether the deformer at an index is a rotation. + * @return BooleanArray Indexed like the deformer list. + */ +fun rotationAncestorFlags( + deformerCount: Int, + parentIndexOf: (Int) -> Int, + isRotationAt: (Int) -> Boolean, +): BooleanArray = + BooleanArray(deformerCount) { deformerIndex -> + var currentIndex = parentIndexOf(deformerIndex) + var found = false + // The step cap breaks a malformed cyclic parent chain rather than hanging on it. + var chainSteps = 0 + while (currentIndex in 0 until deformerCount && chainSteps <= deformerCount) { + if (isRotationAt(currentIndex)) { + found = true + break + } + currentIndex = parentIndexOf(currentIndex) + chainSteps++ + } + found + } + +/** + * [rotationAncestorFlags] over a RUNTIME deformer list, keyed by deformer id. + * + * The export walks ids rather than file indices, but the predicate must stay the one the import used - + * hence one implementation with two adapters rather than two walks. + * + * @param List deformers The runtime deformers. + * @return Map Whether a rotation sits above each deformer. + */ +fun rotationAncestorsById(deformers: List): Map { + val byId = deformers.associateBy { deformer -> deformer.id } + return deformers.associate { deformer -> + var current = deformer.parent?.let { byId[it] } + var found = false + var chainSteps = 0 + while (current != null && chainSteps <= deformers.size) { + if (current is Deformer.Rotation) { + found = true + break + } + current = current.parent?.let { byId[it] } + chainSteps++ + } + deformer.id to found + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ArtMeshLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ArtMeshLowering.kt new file mode 100644 index 0000000..8a9c37c --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ArtMeshLowering.kt @@ -0,0 +1,174 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.moc.ConstantFlag +import org.umamo.format.moc3.model.ArtMesh +import org.umamo.format.moc3.model.ArtMeshKeyform +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.legacyBlendFlagOf +import org.umamo.interop.moc3.convertPointsToMoc +import org.umamo.interop.packedBlendOf +import org.umamo.runtime.keyform.MeshDeltaInterpolator +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.MeshDeltaForm + +/** + * Lowers every exportable drawable into its MOC3 art-mesh record. + * + * @param Moc3ExportContext context The export's derived state. + * @param Moc3KeyformPool pool Interned into: every art mesh claims a binding index here. + * @param Moc3ExportIds ids Claimed from: each drawable's written id. + * @param Moc3ExportNotices noticeSink Appended to: demotions and unresolvable masks. + * @return List The records, in plan order. + */ +internal fun lowerArtMeshes( + context: Moc3ExportContext, + pool: Moc3KeyformPool, + ids: Moc3ExportIds, + noticeSink: Moc3ExportNotices, +): List { + val plan = context.plan + val canvasToParentSpace = context.canvasToParentSpace + return plan.drawables.map { drawable -> + val mesh = drawable.mesh!! + val space = context.spaceOfParent(drawable.parentDeformerId) + // An unkeyed drawable under a deformer has no deltas to recover parent-local from, so the + // injected seam must supply it. That seam inverts canvas-space rests (MOC3 import after + // restMeshesToCanvasSpace) and leaves already-parent-local rests alone (UMA / CMO3 / warp- + // create UV) - applying the inverse blindly would double-transform the latter. A keyed + // drawable already reconstructs parent-local as base + delta, so the seam is asked only + // where it is needed. + val basePositions = + if (drawable.geometryGrid == null && drawable.parentDeformerId != null) { + canvasToParentSpace?.invoke(drawable.id, mesh.positions)?.also { converted -> + if (converted.size != mesh.positions.size) { + noticeSink.unsupported( + ExportEntityCategory.Drawable, + drawable.id.raw, + ExportNoticeReason.RestMeshConversionSizeMismatch( + converted.size, + mesh.positions.size, + ), + ) + } + }?.takeIf { converted -> converted.size == mesh.positions.size } ?: mesh.positions + } else { + mesh.positions + } + val keyforms = + lowerObjectKeyforms( + pool, + drawable.geometryGrid, + MeshDeltaInterpolator, + drawable.channelGrids.onlyChannels( + *(renderChannels(context.colorsEnabled) + arrayOf(FormChannel.DRAW_ORDER)), + ), + renderStatics(drawable.opacity, drawable.multiplyColor, drawable.screenColor, context.colorsEnabled) + + mapOf(FormChannel.DRAW_ORDER to ChannelValue.Scalar(drawable.drawOrder)), + requireGeometry = false, + ) + noticeSink.reportDemotions(ExportEntityCategory.Drawable, drawable.id.raw, keyforms) + val bundle = keyforms?.bundle + val cellCount = maxOf(bundle?.cells?.size ?: 0, 1) + val triangleIndices = + ShortArray(mesh.indices.size) { index -> mesh.indices[index].toShort() } + // -1 is the "no atlas page bound" sentinel and a moc has no way to spell it, so the write + // clamps to page 0. On a multi-page rig that is the WRONG texture rather than a near miss, + // which is worth a notice even though the file it produces is structurally valid. + if (drawable.texturePage < 0) { + noticeSink.unsupported( + ExportEntityCategory.Drawable, + drawable.id.raw, + ExportNoticeReason.NoAtlasPageBound, + ) + } + // A mask naming a drawable this export dropped has no file index to reference. Filtering it + // is the only option, but doing so silently would leave the mesh rendering unclipped with + // nothing in the report to explain why. + val maskIndices = ArrayList(drawable.maskedBy.size) + val unresolvedMasks = ArrayList() + for (maskId in drawable.maskedBy) { + val maskIndex = plan.drawableIndex(maskId) + if (maskIndex >= 0) { + maskIndices.add(maskIndex) + } else { + unresolvedMasks.add(maskId.raw) + } + } + if (unresolvedMasks.isNotEmpty()) { + noticeSink.unsupported( + ExportEntityCategory.Drawable, + drawable.id.raw, + ExportNoticeReason.ClippingMaskNotInExport(unresolvedMasks.toList()), + ) + } + ArtMesh( + id = ids.drawableId(drawable.id), + textureIndex = maxOf(drawable.texturePage, 0), + constantFlags = constantFlagsOf(drawable, context.extendedBlendEnabled), + // The 5.3 blend surface; below v6 the mode falls back to the legacy constant-flag bits. + extendedBlend = + if (context.extendedBlendEnabled) packedBlendOf(drawable.blendMode, drawable.alphaBlendMode) else 0, + isVisible = drawable.isVisible, + isEnabled = true, + parentPartIndex = plan.partIndex(context.partByDrawable[drawable.id]), + parentDeformerIndex = plan.deformerIndex(drawable.parentDeformerId), + vertexUvs = mesh.uvs.copyOf(), + triangleIndices = triangleIndices, + maskDrawableIndices = maskIndices.toIntArray(), + keyformBindingIndex = keyforms?.bindingIndex ?: 0, + keyforms = + (0 until cellCount).map { cellIndex -> + // THE load-bearing invariant: base + delta is the absolute parent-space position. + val deltas = + (bundle?.cells?.getOrNull(cellIndex)?.geometry as? MeshDeltaForm) + ?.positionDeltas + val absolute = + FloatArray(basePositions.size) { coordinate -> + basePositions[coordinate] + (deltas?.getOrNull(coordinate) ?: 0f) + } + ArtMeshKeyform( + vertexPositions = convertPointsToMoc(space, absolute, context.canvas), + opacity = + bundle?.let { scalarOf(it, cellIndex, FormChannel.OPACITY, drawable.opacity) } + ?: drawable.opacity, + drawOrder = + bundle?.let { scalarOf(it, cellIndex, FormChannel.DRAW_ORDER, drawable.drawOrder) } + ?: drawable.drawOrder, + multiplyColor = + colorOf(bundle, cellIndex, FormChannel.MULTIPLY_COLOR, drawable.multiplyColor, context.colorsEnabled), + screenColor = + colorOf(bundle, cellIndex, FormChannel.SCREEN_COLOR, drawable.screenColor, context.colorsEnabled), + ) + }, + ) + } +} + +/** + * The drawable's constant-flag byte. + * + * Note bit 2 is the INVERSE of culling: the flag means "double sided", so a culled drawable clears + * it. Getting that backwards silently double-draws every back face. + * + * @param Drawable drawable The drawable. + * @param Boolean extendedBlendEnabled Whether the target version carries the 5.3 extended-blend + * section, which then states the blend mode instead of the + * legacy bits. + * @return Int The flag bits. + */ +private fun constantFlagsOf(drawable: Drawable, extendedBlendEnabled: Boolean): Int { + // On moc 6 the extended-blend section is authoritative and the editor leaves the legacy 2-bit pair + // CLEAR even for an additive or multiply mesh - writing both would state the mode twice, and the + // legacy pair cannot express the other sixteen modes anyway. + var flags = if (extendedBlendEnabled) 0 else legacyBlendFlagOf(drawable.blendMode) + if (!drawable.culling) { + flags = flags or ConstantFlag.IS_DOUBLE_SIDED + } + if (drawable.invertMask) { + flags = flags or ConstantFlag.IS_INVERTED_MASK + } + return flags +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3BlendShapeLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3BlendShapeLowering.kt new file mode 100644 index 0000000..9f9c009 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3BlendShapeLowering.kt @@ -0,0 +1,322 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.model.ArtMeshKeyform +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.BlendShapeLimit +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.format.moc3.model.Rgb +import org.umamo.format.moc3.model.RotationKeyform +import org.umamo.format.moc3.model.WarpKeyform +import org.umamo.interop.moc3.MocCanvasMapping +import org.umamo.interop.moc3.PointSpace +import org.umamo.interop.moc3.convertDeltasToMoc +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.meshGridDefaultDeltas +import org.umamo.runtime.eval.rotationFormAt +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm + +/* + * Lowers the runtime's blend-shape bindings back into MOC3 records. + * + * A stored MOC3 blend row is a pure DELTA; the runtime form is that delta plus the object's grid form + * interpolated at the DEFAULT pose, which the import added so the evaluator can subtract the same + * reference back out. Exporting therefore means subtracting that reference again - and it has to be + * the SAME reference, computed by the same `org.umamo.runtime.eval` samplers the evaluator calls, or + * the loop does not close. + * + * The reference comes from the SESSION grid, not from a refined copy. That is the fixed point: the + * evaluator subtracts whatever grid the model currently holds, a re-import of this export rebuilds + * exactly that grid, so sampling the session grid makes export → import → eval cancel. (Compaction's + * refinement is bit-exact, so the two sample identically anyway - but only one of them is the + * definition.) + * + * @see MOC3.md §5.6 + */ + +/** + * Builds every blend-shape record for the document. + * + * `recordBase` is left at 0 deliberately: `MocLowering.blendShapeSections` recomputes it as a running + * per-kind cursor over the value tables, so a value carried here would be ignored at best and stale at + * worst. + * + * @param List drawables The drawables in file order. + * @param List deformers The deformers in file order. + * @param List parts The parts in file order. + * @param List parameters The parameters in file order. + * @param Moc3IndexPlan plan The index plan. + * @param MocCanvasMapping canvas The canvas mapping, for un-converting positional deltas. + * @param Function spaceOfParent The space a child of the given parent deformer stores its positions in. + * @param Function scaleFactorOf The px→model factor for a rotation deformer. + * @param Boolean colorsEnabled Whether the target version carries color tables. + * @return List The records, in no particular order (the lowering orders them). + */ +internal fun lowerBlendShapes( + drawables: List, + deformers: List, + parts: List, + parameters: List, + plan: Moc3IndexPlan, + canvas: MocCanvasMapping, + spaceOfParent: (DeformerId?) -> PointSpace, + scaleFactorOf: (Deformer.Rotation) -> Float, + colorsEnabled: Boolean, +): List { + val defaultByParameter = parameters.associate { parameter -> parameter.id to parameter.default } + val defaultValue: (ParameterId) -> Float = { id -> defaultByParameter[id] ?: 0f } + val records = ArrayList() + + /** + * The delta of a color channel against its reference, or null when colors are not written. + * + * @param ColorRgb form The form's color (reference + delta). + * @param ColorRgb reference The channel's value at the default pose. + * @return Rgb? The stored delta row. + */ + fun colorDelta(form: ColorRgb, reference: ColorRgb): Rgb? = + if (colorsEnabled) { + Rgb(form.red - reference.red, form.green - reference.green, form.blue - reference.blue) + } else { + null + } + + /** + * Assembles one record from a binding, given a per-key payload builder. + * + * The NEUTRAL key's form is null in the runtime binding and its stored row is all zeros, which the + * builder produces naturally by receiving null. + * + * @param BlendShapeTarget target The owner kind. + * @param Int localIndex The owner's kind-local index. + * @param BlendShapeBinding binding The runtime binding. + * @param Function payloadOf Builds one key's delta payload (null form = the neutral row). + */ + fun addRecord( + target: BlendShapeTarget, + localIndex: Int, + binding: BlendShapeBinding, + payloadOf: (TForm?) -> BlendShapeKeyform, + ) { + val parameterIndex = plan.parameterIndex(binding.parameterId) + if (parameterIndex < 0) { + return + } + records.add( + BlendShape( + target = target, + targetIndex = localIndex, + parameterIndex = parameterIndex, + keyPositions = binding.keys.copyOf(), + neutralKeyIndex = binding.neutralIndex, + // Recomputed by the lowering; see this function's docblock. + recordBase = 0, + limits = + binding.limits.mapNotNull { limit -> + val limitParameter = plan.parameterIndex(limit.parameterId) + if (limitParameter < 0) { + return@mapNotNull null + } + BlendShapeLimit( + parameterIndex = limitParameter, + keyPositions = limit.points.map { point -> point.value }.toFloatArray(), + weights = limit.points.map { point -> point.weight }.toFloatArray(), + ) + }, + keyforms = binding.forms.map(payloadOf), + ), + ) + } + + // ---- drawables ---- + for (drawable in drawables) { + if (drawable.blendShapes.isEmpty()) { + continue + } + val localIndex = plan.drawableIndex(drawable.id) + val space = spaceOfParent(drawable.parentDeformerId) + val referenceDeltas = meshGridDefaultDeltas(drawable, defaultValue) ?: FloatArray(0) + val referenceDrawOrder = + drawable.channelGrids.scalarAt(FormChannel.DRAW_ORDER, drawable.drawOrder, defaultValue) + val referenceOpacity = drawable.channelGrids.scalarAt(FormChannel.OPACITY, drawable.opacity, defaultValue) + val referenceMultiply = + drawable.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor, defaultValue) + val referenceScreen = + drawable.channelGrids.colorAt(FormChannel.SCREEN_COLOR, drawable.screenColor, defaultValue) + val vertexCount = drawable.mesh?.positions?.size ?: 0 + for (binding in drawable.blendShapes) { + addRecord(BlendShapeTarget.ART_MESH, localIndex, binding) { form: MeshForm? -> + BlendShapeKeyform.Mesh( + ArtMeshKeyform( + vertexPositions = + if (form == null) { + FloatArray(vertexCount) + } else { + convertDeltasToMoc( + space, + FloatArray(vertexCount) { component -> + form.positionDeltas.getOrElse(component) { 0f } - + referenceDeltas.getOrElse(component) { 0f } + }, + canvas, + ) + }, + opacity = if (form == null) 0f else form.opacity - referenceOpacity, + drawOrder = if (form == null) 0f else form.drawOrder - referenceDrawOrder, + multiplyColor = + if (form == null) { + colorDelta(referenceMultiply, referenceMultiply) + } else { + colorDelta(form.multiplyColor, referenceMultiply) + }, + screenColor = + if (form == null) { + colorDelta(referenceScreen, referenceScreen) + } else { + colorDelta(form.screenColor, referenceScreen) + }, + ), + ) + } + } + } + + // ---- deformers ---- + for (deformer in deformers) { + when (deformer) { + is Deformer.Warp -> { + if (deformer.blendShapes.isEmpty()) { + continue + } + // Resolved only once the deformer is known to carry blend shapes: `spaceOfParent` is a + // lookup the caller supplies, and asking it for every deformer in the rig would pay for a + // result that is discarded on all of them in a model with no blend shapes. + val space = spaceOfParent(deformer.parent) + // The UNIFIED deformer index, not the kind-local one: `MocLowering` maps it through + // `warpLocalByDeformer` itself, so handing it a kind-local index would re-map an already + // -mapped value and name a different deformer. The decoder produces the same convention. + val localIndex = plan.deformerIndex(deformer.id) + val reference = warpControlPointsAt(deformer.geometryGrid, defaultValue) ?: FloatArray(0) + val referenceOpacity = + deformer.channelGrids.scalarAt(FormChannel.OPACITY, deformer.opacity, defaultValue) + val referenceMultiply = + deformer.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, deformer.multiplyColor, defaultValue) + val referenceScreen = + deformer.channelGrids.colorAt(FormChannel.SCREEN_COLOR, deformer.screenColor, defaultValue) + val pointCount = (deformer.rows + 1) * (deformer.columns + 1) * 2 + for (binding in deformer.blendShapes) { + addRecord(BlendShapeTarget.WARP, localIndex, binding) { form: WarpForm? -> + BlendShapeKeyform.Warp( + WarpKeyform( + controlPoints = + if (form == null) { + FloatArray(pointCount) + } else { + convertDeltasToMoc( + space, + FloatArray(pointCount) { component -> + form.controlPoints.getOrElse(component) { 0f } - + reference.getOrElse(component) { 0f } + }, + canvas, + ) + }, + opacity = if (form == null) 0f else form.opacity - referenceOpacity, + multiplyColor = + colorDelta(form?.multiplyColor ?: referenceMultiply, referenceMultiply), + screenColor = colorDelta(form?.screenColor ?: referenceScreen, referenceScreen), + ), + ) + } + } + } + is Deformer.Rotation -> { + if (deformer.blendShapes.isEmpty()) { + continue + } + // Resolved after the guard; see the warp branch. + val space = spaceOfParent(deformer.parent) + // Unified, not kind-local; see the warp branch. + val localIndex = plan.deformerIndex(deformer.id) + val reference = + rotationFormAt(deformer.geometryGrid, defaultValue) ?: RotationPivotForm(0f, 0f, 0f, 1f) + val referenceOpacity = + deformer.channelGrids.scalarAt(FormChannel.OPACITY, deformer.opacity, defaultValue) + val referenceMultiply = + deformer.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, deformer.multiplyColor, defaultValue) + val referenceScreen = + deformer.channelGrids.colorAt(FormChannel.SCREEN_COLOR, deformer.screenColor, defaultValue) + val scaleFactor = scaleFactorOf(deformer) + for (binding in deformer.blendShapes) { + addRecord(BlendShapeTarget.ROTATION, localIndex, binding) { form: RotationForm? -> + val originDelta = + if (form == null) { + floatArrayOf(0f, 0f) + } else { + convertDeltasToMoc( + space, + floatArrayOf( + form.originX - reference.originX, + form.originY - reference.originY, + ), + canvas, + ) + } + BlendShapeKeyform.Rotation( + RotationKeyform( + originX = originDelta[0], + originY = originDelta[1], + angle = if (form == null) 0f else form.angle - reference.angle, + scale = + if (form == null) { + 0f + } else { + (form.scale - reference.scale) / (if (scaleFactor != 0f) scaleFactor else 1f) + }, + // Reflections are not blendable: MOC3 stores no flip delta row, so the stored + // value is the record's own neutral rather than a difference. + reflectX = false, + reflectY = false, + opacity = if (form == null) 0f else form.opacity - referenceOpacity, + multiplyColor = + colorDelta(form?.multiplyColor ?: referenceMultiply, referenceMultiply), + screenColor = colorDelta(form?.screenColor ?: referenceScreen, referenceScreen), + ), + ) + } + } + } + } + } + + // ---- parts ---- + for (part in parts) { + if (part.blendShapes.isEmpty()) { + continue + } + val localIndex = plan.partIndex(part.id) + val referenceDrawOrder = + part.channelGrids.scalarAt(FormChannel.DRAW_ORDER, part.drawOrder.toFloat(), defaultValue) + for (binding in part.blendShapes) { + addRecord(BlendShapeTarget.PART, localIndex, binding) { form: PartForm? -> + BlendShapeKeyform.Part(if (form == null) 0f else form.drawOrder - referenceDrawOrder) + } + } + } + return records +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3DeformerLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3DeformerLowering.kt new file mode 100644 index 0000000..a941c8b --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3DeformerLowering.kt @@ -0,0 +1,182 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.RotationKeyform +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.format.moc3.model.WarpKeyform +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.moc3.convertPointsToMoc +import org.umamo.runtime.keyform.RotationPivotInterpolator +import org.umamo.runtime.keyform.WarpLatticeInterpolator +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.format.moc3.model.Deformer as MocDeformer + +/** + * Lowers every deformer in the plan into its MOC3 record, warps and rotations alike. + * + * Kept as one pass over `plan.deformers` rather than two per-kind passes: the file stores deformers in + * one unified list whose order is the addressing scheme, and the per-type columns are addressed through + * it - so splitting the walk would mean rebuilding that correspondence twice. + * + * @param Moc3ExportContext context The export's derived state. + * @param Moc3KeyformPool pool Interned into: every deformer claims a binding index here. + * @param Moc3ExportIds ids Claimed from: each deformer's written id. + * @param Moc3ExportNotices noticeSink Appended to: demotions and unrepresentable grids. + * @return List The records, in plan order. + */ +internal fun lowerDeformers( + context: Moc3ExportContext, + pool: Moc3KeyformPool, + ids: Moc3ExportIds, + noticeSink: Moc3ExportNotices, +): List { + val plan = context.plan + return plan.deformers.map { deformer -> + val parentPartIndex = plan.partIndex(deformer.partId) + val parentDeformerIndex = plan.deformerIndex(deformer.parent) + val space = context.spaceOfParent(deformer.parent) + when (deformer) { + is Deformer.Warp -> { + val keyforms = + lowerObjectKeyforms( + pool, + deformer.geometryGrid, + WarpLatticeInterpolator, + deformer.channelGrids.onlyChannels(*renderChannels(context.colorsEnabled)), + renderStatics( + deformer.opacity, + deformer.multiplyColor, + deformer.screenColor, + context.colorsEnabled, + ), + requireGeometry = true, + ) + noticeSink.reportDemotions(ExportEntityCategory.Deformer, deformer.id.raw, keyforms) + if (keyforms == null) { + noticeSink.unsupported( + ExportEntityCategory.Deformer, + deformer.id.raw, + ExportNoticeReason.WarpDeformerHasNoLattice, + ) + } + val bundle = keyforms?.bundle + // A MOC3 addresses an object's forms as `gridSize` rows from its own keyform base, and + // the static binding 0 still declares ONE row - so an object that writes zero rows puts + // its base on top of the next object's, and the last one sends the reader off the end of + // the table. Every object kind writes at least one form for that reason. + val cellCount = maxOf(bundle?.cells?.size ?: 0, 1) + // Unlike a drawable, which falls back to its rest mesh, a grid-less warp has no lattice + // anywhere in the model - so the form it is obliged to write is a correctly SIZED empty + // one. The reader slices (rows + 1) x (columns + 1) control points back out by that + // arithmetic, and a short array would desynchronize every warp block after it. + val controlPointFloats = (deformer.rows + 1) * (deformer.columns + 1) * 2 + WarpDeformer( + id = ids.deformerId(deformer.id), + keyformBindingIndex = keyforms?.bindingIndex ?: 0, + isVisible = deformer.isVisible, + isEnabled = deformer.isEnabled, + parentPartIndex = parentPartIndex, + parentDeformerIndex = parentDeformerIndex, + rows = deformer.rows, + columns = deformer.columns, + mode = if (deformer.isQuadTransform) 1 else 0, + keyforms = + (0 until cellCount).map { cellIndex -> + val lattice = + bundle?.cells?.getOrNull(cellIndex)?.geometry + as? WarpLatticeForm + WarpKeyform( + convertPointsToMoc( + space, + lattice?.controlPoints ?: FloatArray(controlPointFloats), + context.canvas, + ), + bundle?.let { scalarOf(it, cellIndex, FormChannel.OPACITY, deformer.opacity) } + ?: deformer.opacity, + colorOf(bundle, cellIndex, FormChannel.MULTIPLY_COLOR, deformer.multiplyColor, context.colorsEnabled), + colorOf(bundle, cellIndex, FormChannel.SCREEN_COLOR, deformer.screenColor, context.colorsEnabled), + ) + }, + ) + } + is Deformer.Rotation -> { + val keyforms = + lowerObjectKeyforms( + pool, + deformer.geometryGrid, + RotationPivotInterpolator, + deformer.channelGrids.onlyChannels( + *(renderChannels(context.colorsEnabled) + arrayOf(FormChannel.FLIP_X, FormChannel.FLIP_Y)), + ), + renderStatics(deformer.opacity, deformer.multiplyColor, deformer.screenColor, context.colorsEnabled) + + mapOf( + FormChannel.FLIP_X to ChannelValue.Flag(deformer.flipX), + FormChannel.FLIP_Y to ChannelValue.Flag(deformer.flipY), + ), + requireGeometry = true, + ) + noticeSink.reportDemotions(ExportEntityCategory.Deformer, deformer.id.raw, keyforms) + if (keyforms == null) { + noticeSink.unsupported( + ExportEntityCategory.Deformer, + deformer.id.raw, + ExportNoticeReason.RotationDeformerHasNoPivot, + ) + } + val bundle = keyforms?.bundle + // One form minimum, for the same base-collision reason as the warp branch above. A + // pivot-less rotation has a well-defined fallback the warp does not: the identity + // transform, which is what `pivot == null` already resolves to below. + val cellCount = maxOf(bundle?.cells?.size ?: 0, 1) + // Only the FIRST rotation on each root path carries the px->model factor. + val scaleFactor = + context.rotationScaleFactorFor(deformer) + RotationDeformer( + id = ids.deformerId(deformer.id), + keyformBindingIndex = keyforms?.bindingIndex ?: 0, + isVisible = deformer.isVisible, + isEnabled = deformer.isEnabled, + parentPartIndex = parentPartIndex, + parentDeformerIndex = parentDeformerIndex, + baseAngle = deformer.baseAngle, + keyforms = + (0 until cellCount).map { cellIndex -> + val pivot = + bundle?.cells?.getOrNull(cellIndex)?.geometry + as? RotationPivotForm + val origin = + convertPointsToMoc( + space, + floatArrayOf(pivot?.originX ?: 0f, pivot?.originY ?: 0f), + context.canvas, + ) + RotationKeyform( + originX = origin[0], + originY = origin[1], + angle = pivot?.angle ?: 0f, + scale = (pivot?.scale ?: 1f) / (if (scaleFactor != 0f) scaleFactor else 1f), + reflectX = + bundle?.let { flagOf(it, cellIndex, FormChannel.FLIP_X, deformer.flipX) } + ?: deformer.flipX, + reflectY = + bundle?.let { flagOf(it, cellIndex, FormChannel.FLIP_Y, deformer.flipY) } + ?: deformer.flipY, + opacity = + bundle?.let { scalarOf(it, cellIndex, FormChannel.OPACITY, deformer.opacity) } + ?: deformer.opacity, + multiplyColor = + colorOf(bundle, cellIndex, FormChannel.MULTIPLY_COLOR, deformer.multiplyColor, context.colorsEnabled), + screenColor = + colorOf(bundle, cellIndex, FormChannel.SCREEN_COLOR, deformer.screenColor, context.colorsEnabled), + ) + }, + ) + } + } + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3Export.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3Export.kt new file mode 100644 index 0000000..d99c757 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3Export.kt @@ -0,0 +1,230 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.CanvasInfo +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportReport +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.interop.mocVersion +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * Lowers a [PuppetModel] into a [MocDocument] - the semantic half of writing a `.moc3` from a rig + * that may never have been one. + * + * This is a FULL SYNTHESIS, deliberately unlike the CMO3 export's state-based reconcile. That + * reconcile exists to preserve unmodeled XML the writer does not understand; a MOC3 has no such + * payload once every section index is modeled, so there is nothing to carry and a reference + * container would only constrain the output. A CMO3-origin or future UMA-origin document + * therefore exports exactly like a MOC3-origin one. + * + * THE LOAD-BEARING INVARIANT, which every geometry path here depends on: + * `drawable.mesh.positions[i] + cell.positionDeltas[i]` is the drawable's ABSOLUTE position in its + * parent-deformer space, for every document origin. `restMeshesToCanvasSpace` rewrites the base + * and compensates the deltas so the sum is untouched, and CMO3 stores the same mixed-space + * convention natively - which is what lets one lowering serve both. + * + * An export ALWAYS writes. Anything it cannot express becomes an [ExportNotice] rather than a + * silent drop, including hidden objects, which by default are CARRIED with their flag clear rather + * than deleted the way the official editor's bake deletes them. [Moc3ExportOptions] is where the + * rigger changes that: its hidden/guide flags feed [resolveExportEligibility], and its scale + * override feeds the [Moc3ExportContext]; the options-less default stays the carrying behavior. + * + * This object is only the orchestrator. The work sits in per-concern producers beside it - + * [resolveExportEligibility] for what gets written at all, then [lowerParameters], [lowerRenderOrder], + * [lowerParts], [lowerDeformers], [lowerArtMeshes], [lowerGlues], [lowerOffscreens], and + * [lowerBlendShapes] - over one immutable [Moc3ExportContext] and three collaborators each producer + * takes explicitly: the [Moc3KeyformPool] it interns bindings into, the [Moc3ExportIds] it claims + * written ids from, and the [Moc3ExportNotices] it reports through. A producer's signature is + * therefore the statement of what it can change. + * + * @see MOC3.md §5.6 + */ +object Moc3Export { + /** + * The lowered document plus whatever the lowering could not express. + * + * @property MocDocument document The document to bake. + * @property ExportReport report The advisory findings; empty for a fully-lowered export. + * @property Moc3WrittenIds writtenIds What each object's id was written as, for the sidecars that + * have to name the same objects (see [Moc3WrittenIds]). + */ + class Lowered( + val document: MocDocument, + val report: ExportReport, + val writtenIds: Moc3WrittenIds, + ) + + /** + * Lowers [puppet] into a [MocDocument] at [version], stripping whatever that version cannot carry. + * + * The strip runs FIRST, on the model (see [Moc3VersionDowngrade]), so every producer works on a rig + * the target version can express completely - and the loss is reported against entities the rigger + * recognizes rather than against section indices. + * + * @param PuppetModel puppet The rig to export. + * @param MocVersion version The moc version to target; the document's own runtime target by default. + * @param CanvasToParentSpace? canvasToParentSpace Inverts the deformer chain for an unkeyed + * drawable; null drops those drawables with a notice instead (see [CanvasToParentSpace]). + * @param Moc3ExportOptions options What the rigger chose to include; the default is the + * options-less behavior. + * @return Lowered The document and its notices. + */ + fun toMocDocument( + puppet: PuppetModel, + version: MocVersion = puppet.runtimeTarget.mocVersion(), + canvasToParentSpace: CanvasToParentSpace? = null, + options: Moc3ExportOptions = Moc3ExportOptions.Default, + ): Lowered { + val noticeSink = Moc3ExportNotices() + val downgraded = Moc3VersionDowngrade.strip(puppet, version) + noticeSink.addStripNotices(downgraded.notices) + // Everything below works on the STRIPPED rig, never the parameter. The two are the same object + // whenever the target carries every feature the rig uses, which is every corpus export and every + // re-target upward - so reading the parameter by mistake is invisible on all of them. Naming + // them apart is what makes the mistake say so. + val downgradedPuppet = downgraded.puppet + val eligibility = resolveExportEligibility(downgradedPuppet, canvasToParentSpace, options) + val plan = Moc3IndexPlan.of(downgradedPuppet, eligibility.drawables, eligibility.parts) + val context = Moc3ExportContext(downgradedPuppet, version, eligibility, plan, canvasToParentSpace, options) + val pool = Moc3KeyformPool { parameterId -> plan.parameterIndex(parameterId) } + // Built from the plan, so every id the file will contain is claimed before the first record is + // written and an id too wide for the record can only be shortened INTO a free name. + val ids = Moc3ExportIds(plan, downgradedPuppet.glues, noticeSink) + + // Neither of these two interns: a parameter is an axis objects bind TO, and the render-order tree + // addresses objects that already exist. + val parameters = lowerParameters(context, ids) + val renderOrderGroups = lowerRenderOrder(downgradedPuppet, plan) + + // The four producers below intern into the shared pool IN THIS ORDER, and that order is the + // file's binding numbering. Reordering them is semantically harmless - the numbering is a + // permutation nothing downstream reads - but it is also the visible symptom of a producer moving + // relative to a data dependency it has, which is not harmless. Moc3ExportBindingOrderTest pins + // it so that second thing cannot happen quietly. + val loweredParts = lowerParts(context, pool, ids, noticeSink) + val parts = loweredParts.records + val deformers = lowerDeformers(context, pool, ids, noticeSink) + val artMeshes = lowerArtMeshes(context, pool, ids, noticeSink) + val glues = lowerGlues(downgradedPuppet, context, pool, ids, noticeSink) + + // LAST, so drop notices trail the per-object findings rather than leading them. The eligibility + // pass runs first, but a rigger reads its findings better after the rest. + noticeSink.reportDroppedDrawables(eligibility.droppedDrawables) + + val document = + MocDocument( + version = version, + canvas = + CanvasInfo( + pixelsPerUnit = context.pixelsPerUnit, + // MOC3 §5.3 CanvasInfo originX / originY: read off the same mapping every converted + // position went through, so the record and the geometry share one origin. + originX = context.canvas.originX, + originY = context.canvas.originY, + width = downgradedPuppet.canvasWidth, + height = downgradedPuppet.canvasHeight, + ), + parameters = parameters, + keyformBindings = pool.bindings().associateBy { binding -> binding.index }, + parts = parts, + deformers = deformers, + artMeshes = artMeshes, + glues = glues, + renderOrderGroups = renderOrderGroups, + offscreens = + if (context.offscreensEnabled) { + lowerOffscreens(downgradedPuppet, plan, loweredParts.keyformsByPartId, context.colorsEnabled, noticeSink) + } else { + emptyList() + }, + // Blend shapes arrived in Cubism 4.2; a lower target simply carries none. + blendShapes = + if (version.byteValue < 4) { + emptyList() + } else { + lowerBlendShapes( + plan.drawables, + plan.deformers, + plan.parts, + plan.parameters, + plan, + context.canvas, + { parentId -> context.spaceOfParent(parentId) }, + { rotation -> context.rotationScaleFactorFor(rotation) }, + context.colorsEnabled, + ) + }, + ) + return Lowered(document, noticeSink.report(), ids.writtenIds()) + } + + /** + * Lowers [puppet] and bakes it to `.moc3` bytes. + * + * @param PuppetModel puppet The rig to export. + * @param MocVersion version The moc version to target; the document's own runtime target by default. + * @param CanvasToParentSpace? canvasToParentSpace The unkeyed-drawable space inverse, or null. + * @param Moc3ExportOptions options What the rigger chose to include; the default is the + * options-less behavior. + * @return Pair The bytes and the advisory report. + */ + fun write( + puppet: PuppetModel, + version: MocVersion = puppet.runtimeTarget.mocVersion(), + canvasToParentSpace: CanvasToParentSpace? = null, + options: Moc3ExportOptions = Moc3ExportOptions.Default, + ): Pair { + val lowered = toMocDocument(puppet, version, canvasToParentSpace, options) + return Moc3.write(lowered.document) to lowered.report + } + + /** + * The pixels-per-unit a bake of [puppet] should carry. + * + * A moc's canvas scale is a BAKE parameter, not a project property: every corpus `.cmo3` stores + * `CModelInfo.pixelsPerUnit = 1` - a CMO3 works in canvas pixels - while the editor's bake of the + * same project writes a real scale, and the rigger picks it in the export dialog. Its default there + * is the canvas WIDTH, which 21 of the 25 corpus bakes use exactly (the four that do not chose their + * own: 9000 -> 5000, 9000 -> 3077, 4500 -> 3000, 5134 -> 5000). + * + * So a CMO3-origin export defaults to the canvas width, and a MOC3-origin one keeps the scale its + * file already had. Writing the project's literal 1 instead is not a smaller choice - it stores the + * whole rig at PIXEL scale, which every runtime then draws hundreds of times too large. A rigger + * who wants a different bake scale sets [Moc3ExportOptions.pixelsPerUnitOverride]; the export + * dialog seeds its scale field from this function, which is why it is public. + * + * The two cases are told apart by [PuppetModel.pixelsPerUnit] being NULL, never by the value's + * magnitude: 1 is a legitimate bake scale, so a `> 1` test would silently rescale a moc that baked + * at 1 - or at any scale below it - by the canvas width and shrink the rig by that whole factor. + * + * @param PuppetModel puppet The rig being exported. + * @return Float The canvas scale to write. + */ + fun mocPixelsPerUnitFor(puppet: PuppetModel): Float { + puppet.pixelsPerUnit?.let { recorded -> return recorded } + return puppet.canvasWidth.takeIf { width -> width > 0f } ?: 1f + } +} + +/** + * Ensures an unkeyed drawable's rest mesh is in its parent deformer's space for the MOC3 write. + * + * An injected seam rather than a call, because the inverse lives in `:render` (a closed-form rotation + * inverse and a damped-Newton warp inverse over the evaluated chain) and `:interop` is its sibling + * over `:runtime`, not its dependent - the same shape as the atlas decode's injected byte reader. + * + * Only reached for a drawable with no keyform grid under a deformer: everything else already stores + * parent-local values. The implementation must invert canvas-space rests and leave already-parent- + * local rests unchanged - see [org.umamo.render.canvasToParentSpaceFor]. Returning null (or a + * differently-sized array) leaves the rest mesh as authored and raises a notice, which is the honest + * outcome when the chain cannot be inverted at all. + * + * @param DrawableId drawable The drawable being written. + * @param FloatArray positions Its interleaved rest positions (canvas or already parent-local). + * @return FloatArray? The interleaved parent-space positions, or null when the chain cannot invert. + */ +typealias CanvasToParentSpace = (drawable: DrawableId, positions: FloatArray) -> FloatArray? \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportChannels.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportChannels.kt new file mode 100644 index 0000000..0159207 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportChannels.kt @@ -0,0 +1,79 @@ +package org.umamo.interop.moc3.export + +import org.umamo.runtime.keyform.FormInterpolator +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel + +/* + * The channel-set helpers every object lowering shares: which render channels an object's grid should + * bundle at the target version, the static fallbacks behind them, and the narrowing that keeps a + * bundle to exactly those channels. + */ + +/** + * The render channels an object's grid should bundle, gated on whether the version carries colors. + * + * @param Boolean colorsEnabled Whether the target version has color tables. + * @return Array The channels to bundle. + */ +internal fun renderChannels(colorsEnabled: Boolean): Array = + if (colorsEnabled) { + arrayOf(FormChannel.OPACITY, FormChannel.MULTIPLY_COLOR, FormChannel.SCREEN_COLOR) + } else { + arrayOf(FormChannel.OPACITY) + } + +/** + * The static fallbacks for [renderChannels]. + * + * Colors are omitted entirely below moc 4 rather than defaulted, so the bundle never manufactures a + * color cell the version has nowhere to store. + * + * @param Float opacity The owner's static opacity. + * @param ColorRgb multiplyColor The owner's static multiply color. + * @param ColorRgb screenColor The owner's static screen color. + * @param Boolean colorsEnabled Whether the target version has color tables. + * @return Map The statics per channel. + */ +internal fun renderStatics( + opacity: Float, + multiplyColor: ColorRgb, + screenColor: ColorRgb, + colorsEnabled: Boolean, +): Map = + if (colorsEnabled) { + mapOf( + FormChannel.OPACITY to ChannelValue.Scalar(opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(screenColor), + ) + } else { + mapOf(FormChannel.OPACITY to ChannelValue.Scalar(opacity)) + } + +/** A geometry interpolator for owners that have no geometry at all (parts, glues). */ +internal object UnitInterpolator : FormInterpolator { + override fun interpolate(lower: Unit, upper: Unit, fraction: Float) = Unit + + override fun isExactlyEqual(left: Unit, right: Unit): Boolean = true +} + +/** + * This channel set restricted to [channels] - the tracks the owner's moc block can actually store. + * + * A runtime entity may carry tracks a given moc version has no field for (a color track on a v3 + * export), and bundling those in would widen the grid with axes nothing reads. + * + * @param FormChannel channels The channels to keep. + * @return ChannelGrids The restricted set. + */ +internal fun ChannelGrids.onlyChannels( + vararg channels: FormChannel, +): ChannelGrids { + val keep = channels.toSet() + return ChannelGrids( + gridsByChannel.filterKeys { channel -> channel in keep }, + ) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportContext.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportContext.kt new file mode 100644 index 0000000..5d6946d --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportContext.kt @@ -0,0 +1,116 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.interop.moc3.MocCanvasMapping +import org.umamo.interop.moc3.PointSpace +import org.umamo.interop.moc3.rotationAncestorsById +import org.umamo.interop.moc3.rotationScaleFactor +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/** + * Everything the export producers derive from a rig before any of them writes a record. + * + * Immutable, and deliberately narrower than the encode side's `MocLoweringContext`: the two things a + * producer MUTATES - the keyform pool it interns bindings into and the notice sink it reports through - + * are passed alongside this rather than held here, so a producer's signature says what it changes. + * + * The rig here is the STRIPPED one. A producer that reached back to the caller's model would read + * features the target version cannot carry, and on every export at a model's own version the two are + * the same object - so nothing would notice. + * + * @see MOC3.md §5.6 + */ +internal class Moc3ExportContext( + val puppet: PuppetModel, + val version: MocVersion, + val eligibility: Moc3ExportEligibility, + val plan: Moc3IndexPlan, + val canvasToParentSpace: CanvasToParentSpace?, + options: Moc3ExportOptions = Moc3ExportOptions.Default, +) { + /** + * The bake scale written into the canvas record and used to convert every position. + * + * Resolved HERE, before [canvas] is built, because an override that only patched the canvas + * record afterward would leave every converted position at the old scale - the record and the + * geometry must come from the same number. + */ + val pixelsPerUnit: Float = + options.pixelsPerUnitOverride?.takeIf { override -> override > 0f } + ?: Moc3Export.mocPixelsPerUnitFor(puppet) + + /** + * The px↔model mapping every geometry conversion goes through, and the origin the canvas record + * writes. MOC3 §5.3 CanvasInfo counts its origin in canvas orientation (y down), so the world + * origin's z (up) is negated back. + */ + val canvas: MocCanvasMapping = MocCanvasMapping(pixelsPerUnit, puppet.worldOriginX, -puppet.worldOriginZ) + + /** + * Whether the target version carries the per-object color tables. + * + * Per-object multiply/screen color arrived in Cubism 4.2; below that the tables do not exist and + * every keyform must carry null rather than an identity, or the lowering would synthesize sections + * the version cannot address. + */ + val colorsEnabled: Boolean = version.byteValue >= 4 + + /** + * Whether the target version carries offscreen records. + * + * Offscreen rendering (an isolated part composited as one layer) arrived in Cubism 5.3, as did the + * extended blend surface. Two names for one number: they are separate features that happen to + * share a version, and a later version bump should be able to move one without the other - which is + * why this and [extendedBlendEnabled] stay separate fields rather than collapsing into one. + */ + val offscreensEnabled: Boolean = version.byteValue >= 6 + + /** Whether the target version carries the packed extended blend (MOC3 v6 §5.6 s153). */ + val extendedBlendEnabled: Boolean = version.byteValue >= 6 + + /** Per rotation deformer, whether a rotation ancestor already applied the px→model factor. */ + private val rotationAncestors: Map = rotationAncestorsById(plan.deformers) + + /** Each drawable's owning part, null when unparented. */ + val partByDrawable: Map get() = eligibility.partByDrawable + + /** The org tree's part→parent link. */ + val partParentById: Map get() = eligibility.partParentById + + /** + * The space a child of [parentId] stores its positions in. + * + * The export's mirror of the import's `pointSpaceOf`, resolved through the plan so an unknown parent + * normalizes to root exactly as the import normalizes an unresolvable index. Three callers - the + * deformer, art-mesh, and blend-shape lowerings - and they must all resolve identically, which is + * what makes this a context method rather than a local helper in one of them. + * + * @param DeformerId? parentId The owning object's parent deformer. + * @return PointSpace The space to store in. + */ + fun spaceOfParent(parentId: DeformerId?): PointSpace { + val index = plan.deformerIndex(parentId) + return when (plan.deformers.getOrNull(index)) { + is Deformer.Warp -> PointSpace.WarpLattice + is Deformer.Rotation -> PointSpace.RotationLocal + null -> PointSpace.ModelRoot + } + } + + /** + * The px→model factor a rotation deformer's pivot scale divides by. + * + * Routed through the context because the deformer lowering and the blend-shape pass both need it + * and must agree; deriving it twice is how the two would drift. + * + * @param Deformer.Rotation rotation The rotation deformer. + * @return Float The scale factor. + */ + fun rotationScaleFactorFor(rotation: Deformer.Rotation): Float = + rotationScaleFactor(rotationAncestors[rotation.id] ?: false, canvas) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportEligibility.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportEligibility.kt new file mode 100644 index 0000000..d844428 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportEligibility.kt @@ -0,0 +1,168 @@ +package org.umamo.interop.moc3.export + +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.partByDrawable + +/** + * Which of a rig's objects an export actually writes, and why the rest were left out. + * + * @property List drawables The drawables that survive, in model order. + * @property Set parts The part ids that survive. + * @property Map partByDrawable Each drawable's owning part, null when unparented. + * @property Map partParentById The org tree's part→parent link, inverted once. + * @property Map droppedDrawables Each omitted drawable and the reason, + * for notices. + */ +internal class Moc3ExportEligibility( + val drawables: List, + val parts: Set, + val partByDrawable: Map, + val partParentById: Map, + val droppedDrawables: Map, +) + +/** + * Decides which objects of [puppet] the export can write. + * + * Runs BEFORE the index plan, because the plan's indices are the file's addressing scheme: a drawable + * dropped after the plan was built would leave every later index - and every mask reference into them - + * naming the wrong object. + * + * Must also run AFTER the version strip, on the stripped rig. No strip currently touches the + * predicates below, so passing the un-stripped rig would be invisible today - which is exactly why the + * order is stated rather than left to be rediscovered. + * + * Structural drops (sketch subtree, no mesh, no parent-space inverse) are decided before the + * option-driven hidden drops, so the mask exemption below can never resurrect a drawable the file + * has no way to write. + * + * @param PuppetModel puppet The rig to export, already stripped to the target version. + * @param CanvasToParentSpace? canvasToParentSpace The unkeyed-drawable space inverse, or null. + * @param Moc3ExportOptions options What the rigger chose to include; the default is the + * options-less behavior (hidden objects carried, guides dropped). + * @return Moc3ExportEligibility The surviving objects and the drop reasons. + */ +internal fun resolveExportEligibility( + puppet: PuppetModel, + canvasToParentSpace: CanvasToParentSpace?, + options: Moc3ExportOptions = Moc3ExportOptions.Default, +): Moc3ExportEligibility { + // A SKETCH part is a guide overlay - a scan or a rough the rigger traces over - and the official + // bake leaves it out of the moc entirely. The whole subtree goes: a guide's drawables are the + // thing that would otherwise render in the runtime, sitting on top of the puppet. + val sketchParts = + if (options.exportGuideImageParts) { + emptySet() + } else { + partSubtree(puppet, puppet.parts.filter { part -> part.isSketch }) + } + // A hidden part cascades over its whole subtree, matching the parts panel's eyeball: a visible + // child of a hidden part does not show, so omitting hidden parts omits the child's contents too. + val hiddenParts = + if (options.exportHiddenParts) { + emptySet() + } else { + partSubtree(puppet, puppet.parts.filter { part -> !part.isVisible }) + } + val exportableParts = + puppet.parts.mapNotNullTo(LinkedHashSet()) { part -> + part.id.takeIf { it !in sketchParts && it !in hiddenParts } + } + val partByDrawable = puppet.partByDrawable() + // The org tree's part->parent link, inverted ONCE. Both of these are asked per object further + // down, and re-deriving either there turns its pass into a quadratic rescan of the whole tree. + val partParentById = HashMap() + for (part in puppet.parts) { + for (child in part.children) { + if (child is OrgChild.Part) { + partParentById[child.id] = part.id + } + } + } + val dropped = LinkedHashMap() + for (drawable in puppet.drawables) { + if (partByDrawable[drawable.id] in sketchParts) { + dropped[drawable.id] = ExportNoticeReason.SketchPartIsNotRuntimeContent + } else if (drawable.mesh == null) { + dropped[drawable.id] = ExportNoticeReason.DrawableHasNoMesh + } else if (drawable.geometryGrid == null && drawable.parentDeformerId != null && canvasToParentSpace == null) { + // With no grid there are no deltas to recover the parent-local form from. A canvas-space + // rest (MOC3 import) needs :render's chain inverse; an already-parent-local rest (UMA / + // CMO3) needs the same seam to confirm and pass through. Without it the drawable is + // dropped rather than written at the wrong scale. + dropped[drawable.id] = ExportNoticeReason.UnkeyedDrawableUnderDeformerHasNoParentGeometry + } else if (partByDrawable[drawable.id] in hiddenParts) { + dropped[drawable.id] = ExportNoticeReason.HiddenPartOmittedByExportOption + } else if (!options.exportHiddenDrawables && !drawable.isVisible) { + dropped[drawable.id] = ExportNoticeReason.HiddenDrawableOmittedByExportOption + } + } + // A hidden mask is routine in a Cubism rig - the mesh exists to clip, not to draw - so dropping + // it for being hidden would unclip everything it masks. A drawable dropped ONLY by the + // hidden-art-mesh option is therefore kept after all when a surviving drawable masks with it, + // written with its flag clear exactly as the options-less export writes it. One pass suffices: + // a mask's own mask list is not consulted by the runtime's mask render, so keeping it creates no + // further need. The exemption deliberately does not extend to hidden-PART drops - those take + // the part record itself, and a written drawable under an unwritten part is a state the index + // plan has no shape for - so there the mask reference is filtered with a notice instead (see + // the mask handling in the art-mesh lowering). + if (dropped.isNotEmpty()) { + val masksOfSurvivors = LinkedHashSet() + for (drawable in puppet.drawables) { + if (drawable.id !in dropped) { + masksOfSurvivors.addAll(drawable.maskedBy) + } + } + for (maskId in masksOfSurvivors) { + if (dropped[maskId] == ExportNoticeReason.HiddenDrawableOmittedByExportOption) { + dropped.remove(maskId) + } + } + } + return Moc3ExportEligibility( + drawables = puppet.drawables.filter { drawable -> drawable.id !in dropped }, + parts = exportableParts, + partByDrawable = partByDrawable, + partParentById = partParentById, + droppedDrawables = dropped, + ) +} + +/** + * Every part in the subtrees rooted at [roots], roots included. + * + * A guide image or a hidden group is usually one part, but nothing stops a rigger from grouping + * several under it - and a child of a guide is still a guide, a child of a hidden part still + * hidden. + * + * @param PuppetModel puppet The rig. + * @param List roots The subtree roots to close over. + * @return Set The part ids to omit. + */ +private fun partSubtree(puppet: PuppetModel, roots: List): Set { + if (roots.isEmpty()) { + return emptySet() + } + val partsById = puppet.parts.associateBy { part -> part.id } + val omitted = LinkedHashSet() + val pending = ArrayDeque(roots.map { part -> part.id }) + while (pending.isNotEmpty()) { + val partId = pending.removeFirst() + if (!omitted.add(partId)) { + continue + } + for (child in partsById[partId]?.children.orEmpty()) { + if (child is OrgChild.Part) { + pending.addLast(child.id) + } + } + } + return omitted +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportIds.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportIds.kt new file mode 100644 index 0000000..7c66e05 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportIds.kt @@ -0,0 +1,426 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.moc.Sections +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId + +/** + * The id each object is written under, one namespace per moc id space. + * + * MOC3 §5.4 makes every id a fixed 64-byte record, so an id whose UTF-8 form does not fit with room + * for the terminator cannot be written - the writer's own precondition rejects one, and an export that + * let that reach the caller would throw straight past the report and out of the file write. CMO3 + * places no width limit on these ids, and 22 CJK characters already exceed the record, so shortening + * is a reachable path rather than a theoretical one. + * + * Shortening is also what MINTS DUPLICATES: two names that differ only past the 63rd byte truncate to + * the same string. A MOC3 addresses nothing by id, so the file itself takes the duplicate without + * complaint and the loss surfaces only on the way back, where a re-import merges the two objects into + * one - one mesh's masks, part membership, and keyforms landing on the other. So a shortened id is + * disambiguated here rather than reported and left colliding. + * + * Every id the model can write VERBATIM is claimed up front, at construction, rather than as each + * object is lowered. Otherwise the outcome would depend on lowering order: a shortened id could take + * a name that a later object holds outright, and that object - whose id needed no shortening at all - + * would be the one renamed. Claiming first means shortening can only ever yield ground, never take it. + * + * Drawables are the exception: their moc ids are the sanitized display names (`[A-Za-z0-9_-]`), not + * the Cubism `ArtMeshN` model ids, so VTube Studio and other runtimes that list meshes by id show + * "TopTeeth" rather than "ArtMesh13". Collisions and empty names fall back / disambiguate the same + * way over-long ids do. + * + * Mutable (it accumulates claims), so it is passed to each producer explicitly alongside the keyform + * pool and the notice sink rather than held on the immutable [Moc3ExportContext]. + * + * @see MOC3.md §5.4 + */ +internal class Moc3ExportIds( + plan: Moc3IndexPlan, + glues: List, + noticeSink: Moc3ExportNotices, +) { + // One namespace per id space, because a moc's sections are separate id tables: a part and a + // drawable sharing a name collide nowhere, so disambiguating across the two would rename an object + // for no reason. + private val parameterSpace = Moc3IdSpace(ExportEntityCategory.Parameter, plan.parameters.map { parameter -> parameter.id.raw }, noticeSink) + private val partSpace = Moc3IdSpace(ExportEntityCategory.Part, plan.parts.map { part -> part.id.raw }, noticeSink) + private val deformerSpace = Moc3IdSpace(ExportEntityCategory.Deformer, plan.deformers.map { deformer -> deformer.id.raw }, noticeSink) + + // Model id → sanitized display-name id; claimed entirely up front (not via Moc3IdSpace) so the + // preferred names cannot be stolen by a later truncated claim. + private val drawableWrittenByModelId: Map = claimDrawableExportIds(plan.drawables, noticeSink) + + // A glue with no authored id gets one synthesized at lowering time, so only the authored ones can + // be claimed here. That is enough: a shortened id is at least ID_STRIDE - 4 bytes long (dropping + // one character sheds at most 4 UTF-8 bytes), and the synthesized "Glue_a_b_" form is far shorter + // than that, so the two can never name the same string. + private val glueSpace = Moc3IdSpace(ExportEntityCategory.Glue, glues.mapNotNull { glue -> glue.id }, noticeSink) + + /** + * The id a parameter is written under. + * + * @param ParameterId id The parameter's model id. + * @return String The id to write. + */ + fun parameterId(id: ParameterId): String = parameterSpace.writtenId(id.raw) + + /** + * The id a part is written under. + * + * @param PartId id The part's model id. + * @return String The id to write. + */ + fun partId(id: PartId): String = partSpace.writtenId(id.raw) + + /** + * The id a deformer is written under. + * + * @param DeformerId id The deformer's model id. + * @return String The id to write. + */ + fun deformerId(id: DeformerId): String = deformerSpace.writtenId(id.raw) + + /** + * The id a drawable is written under (sanitized display name). + * + * @param DrawableId id The drawable's model id. + * @return String The id to write. + */ + fun drawableId(id: DrawableId): String = drawableWrittenByModelId.getValue(id.raw) + + /** + * The id a glue is written under. + * + * Takes a plain [String] because a glue's id is one: nothing references a glue, so the model carries + * no typed id for it, and the caller has already resolved the synthesized fallback for a glue that + * was authored without one. + * + * @param String id The glue's id, authored or synthesized. + * @return String The id to write. + */ + fun glueId(id: String): String = glueSpace.writtenId(id) + + /** + * What every object asked about so far was written as, frozen for the sidecars to read. + * + * Called after the lowering, when each producer has asked once per record it wrote - so the result + * covers exactly the objects the file contains. Drawable ids are claimed entirely at construction + * (display-name export), so they are present even before [drawableId] is asked. + * + * @return Moc3WrittenIds The model-id → written-id mapping, by space. + */ + fun writtenIds(): Moc3WrittenIds = + Moc3WrittenIds( + parameters = parameterSpace.writtenIds(), + parts = partSpace.writtenIds(), + deformers = deformerSpace.writtenIds(), + drawables = drawableWrittenByModelId, + ) +} + +/** + * Claims a unique moc id for every exportable drawable from its display name, sanitized to + * `[A-Za-z0-9_-]`. Empty names fall back to the sanitized model id; collisions append `-2`, `-3`, …. + * + * @param List drawables The exportable drawables in plan order. + * @param Moc3ExportNotices noticeSink Notices when a name must be truncated to the id record. + * @return Map Model drawable id → written moc id. + */ +private fun claimDrawableExportIds( + drawables: List, + noticeSink: Moc3ExportNotices, +): Map { + val preferredByModelId = + drawables.associate { drawable -> + drawable.id.raw to sanitizeMocExportId(drawable.name, fallback = drawable.id.raw).ifEmpty { "drawable" } + } + // Pre-claim every unique preferred id that fits, so a later truncated name cannot steal an id + // another drawable holds outright (same rule as [Moc3IdSpace] for model ids). + val preferredCounts = preferredByModelId.values.groupingBy { preferred -> preferred }.eachCount() + val claimed = HashSet() + for (preferred in preferredByModelId.values) { + if (preferredCounts.getValue(preferred) == 1 && fitsIdRecord(preferred)) { + claimed.add(preferred) + } + } + val written = LinkedHashMap(drawables.size) + for (drawable in drawables) { + val base = preferredByModelId.getValue(drawable.id.raw) + val truncated = !fitsIdRecord(base) + val exclusiveFit = !truncated && preferredCounts.getValue(base) == 1 + if (exclusiveFit) { + written[drawable.id.raw] = base + continue + } + var candidate = if (truncated) fittedToIdRecord(base) else base + if (candidate.isEmpty()) { + candidate = "drawable" + } + var disambiguator = 2 + var chosen = candidate + var collided = false + while (!claimed.add(chosen)) { + collided = true + chosen = fittedToIdRecord(base, "-$disambiguator") + disambiguator++ + } + if (truncated || collided) { + noticeSink.unsupported( + ExportEntityCategory.Drawable, + drawable.id.raw, + if (collided) { + ExportNoticeReason.IdTruncatedAndDisambiguated(Sections.ID_STRIDE, chosen) + } else { + ExportNoticeReason.IdTruncated(Sections.ID_STRIDE, chosen) + }, + ) + } + written[drawable.id.raw] = chosen + } + return written +} + +/** + * Sanitizes [displayName] into a moc-safe id: ASCII `[A-Za-z0-9_-]` (case preserved). Whitespace + * becomes `_`; other characters are dropped. Runs of `_` collapse; edges strip. When that yields + * nothing, [fallback] is scrubbed the same way; when that is also empty (e.g. a CJK-only Cubism id), + * the raw [fallback] is kept so record-width fitting can still shorten it. + * + * @param String displayName The drawable's display name. + * @param String fallback The model id when the name sanitizes to empty. + * @return String A non-empty id stem (may still need record fitting / disambiguation). + */ +internal fun sanitizeMocExportId( + displayName: String, + fallback: String, +): String { + fun scrub(source: String): String { + val out = StringBuilder(source.length) + var lastWasUnderscore = false + for (ch in source) { + val mapped = + when { + ch in 'a'..'z' || ch in 'A'..'Z' || ch in '0'..'9' || ch == '-' -> ch + ch == '_' || ch.isWhitespace() -> '_' + else -> null + } ?: continue + if (mapped == '_') { + if (!lastWasUnderscore && out.isNotEmpty()) { + out.append('_') + lastWasUnderscore = true + } + } else { + out.append(mapped) + lastWasUnderscore = false + } + } + while (out.isNotEmpty() && out.last() == '_') { + out.deleteAt(out.lastIndex) + } + while (out.isNotEmpty() && out.first() == '_') { + out.deleteAt(0) + } + return out.toString() + } + val fromName = scrub(displayName) + if (fromName.isNotEmpty()) { + return fromName + } + val fromFallback = scrub(fallback) + if (fromFallback.isNotEmpty()) { + return fromFallback + } + return fallback.ifEmpty { "drawable" } +} + +/** + * What an export actually wrote each object's id as. + * + * The moc is not the only file in a bake: the `cdi3.json` beside it names parameters, parts, and art + * meshes BY ID to carry their display names, and the runtime joins the two on that string. So a + * sidecar built from the model's own ids silently unpairs itself from the moc for every id the record + * width forced short - the name, the parameter's group placement, and its combined-parameter pairing + * all address an object the moc does not contain under that name. Handing this back with the document + * is what lets the family agree with itself. + * + * An id the export never wrote (a dropped drawable) maps to itself, which is the only honest answer: + * there is no written form to report. Whether an object was written at all is a separate question, and + * one a sidecar has to ask before naming it - see [wrotePart] / [wroteDrawable]. + * + * @see MOC3.md §5.4 + */ +class Moc3WrittenIds internal constructor( + private val parameters: Map, + private val parts: Map, + private val deformers: Map, + private val drawables: Map, +) { + /** + * Whether the moc contains a record for [id]. + * + * A part in a sketch subtree is left out of the bake entirely, so a sidecar entry for it names + * nothing the file contains. + * + * @param PartId id The part's model id. + * @return Boolean True when the export wrote it. + */ + fun wrotePart(id: PartId): Boolean = id.raw in parts + + /** + * Whether the moc contains a record for [id]. + * + * A drawable can be dropped for several reasons (a sketch subtree, a missing mesh, an uninvertible + * deformer chain), and a dropped one holds no claim on its id - so an over-long id can be shortened + * onto exactly that string. A sidecar that named the dropped object anyway would then carry two + * entries under one id, and a join on that string would pick between them arbitrarily. + * + * @param DrawableId id The drawable's model id. + * @return Boolean True when the export wrote it. + */ + fun wroteDrawable(id: DrawableId): Boolean = id.raw in drawables + + /** + * The id [id] was written under. + * + * @param ParameterId id The parameter's model id. + * @return String The written id. + */ + fun parameterId(id: ParameterId): String = parameters[id.raw] ?: id.raw + + /** + * The id [id] was written under. + * + * @param PartId id The part's model id. + * @return String The written id. + */ + fun partId(id: PartId): String = parts[id.raw] ?: id.raw + + /** + * The id [id] was written under. + * + * Carried for completeness rather than for a reader that exists today: a moc names its deformers + * and nothing else does, since cdi3 has no deformer entries. + * + * @param DeformerId id The deformer's model id. + * @return String The written id. + */ + fun deformerId(id: DeformerId): String = deformers[id.raw] ?: id.raw + + /** + * The id [id] was written under. + * + * @param DrawableId id The drawable's model id. + * @return String The written id. + */ + fun drawableId(id: DrawableId): String = drawables[id.raw] ?: id.raw +} + +/** + * One moc id table: which names are spoken for, and what each model id ended up written as. + * + * @param List modelIds Every id the rig gives this space, claimed if it fits. + * @property ExportEntityCategory category The entity category, for the notices it raises. + * @property Moc3ExportNotices noticeSink Appended to when an id has to be shortened. + */ +private class Moc3IdSpace( + private val category: ExportEntityCategory, + modelIds: List, + private val noticeSink: Moc3ExportNotices, +) { + // Only the ids that FIT are claimed: an over-long one is not written under its own name, so + // reserving it would block a shortened id from a string the file never contains. + private val claimedIds: MutableSet = modelIds.filterTo(HashSet()) { modelId -> fitsIdRecord(modelId) } + + // Memoized so an object asked about twice gets one answer and one notice. The deformer lowering + // asks from each of its two type branches, and a second unmemoized call would "collide" the id + // with the claim its own first call made. + private val writtenIdByModelId = HashMap() + + /** + * The id [modelId] is written under, shortened and disambiguated if it cannot be written as-is. + * + * @param String modelId The id the model carries. + * @return String The id to write. + */ + fun writtenId(modelId: String): String = writtenIdByModelId.getOrPut(modelId) { claim(modelId) } + + /** + * A snapshot of what this space has written so far. + * + * @return Map Model id → written id. + */ + fun writtenIds(): Map = writtenIdByModelId.toMap() + + /** + * Resolves and claims the written form of [modelId], reporting whatever had to be cut. + * + * @param String modelId The id the model carries. + * @return String The id to write. + */ + private fun claim(modelId: String): String { + if (fitsIdRecord(modelId)) { + claimedIds.add(modelId) + return modelId + } + val truncated = fittedToIdRecord(modelId) + var written = truncated + var disambiguator = 2 + // The suffix has to be part of what gets fitted, not appended after it, or disambiguating would + // push the id back over the record width it was just trimmed to. + while (!claimedIds.add(written)) { + written = fittedToIdRecord(modelId, "-$disambiguator") + disambiguator++ + } + noticeSink.unsupported( + category, + modelId, + if (written == truncated) { + ExportNoticeReason.IdTruncated(Sections.ID_STRIDE, written) + } else { + ExportNoticeReason.IdTruncatedAndDisambiguated(Sections.ID_STRIDE, written) + }, + ) + return written + } +} + +/** + * Whether [id] can be written into a moc id record as-is. + * + * @param String id The id to measure. + * @return Boolean True when its UTF-8 form leaves room for the terminator. + */ +private fun fitsIdRecord(id: String): Boolean = id.encodeToByteArray().size < Sections.ID_STRIDE + +/** + * The longest leading run of [id] that fits a moc id record with [suffix] appended. + * + * @param String id The id to shorten. + * @param String suffix A disambiguating suffix to keep room for; empty for a plain truncation. + * @return String The shortened id, suffix included. + */ +private fun fittedToIdRecord( + id: String, + suffix: String = "", +): String { + val suffixBytes = suffix.encodeToByteArray().size + // Trimmed by CHARACTER so the result stays valid UTF-8; cutting at a byte offset could land + // mid-sequence and write a broken code point into the record. + var fitted = id + while (fitted.isNotEmpty() && fitted.encodeToByteArray().size + suffixBytes >= Sections.ID_STRIDE) { + fitted = fitted.dropLast(1) + } + // A Kotlin Char is a UTF-16 code unit, so an astral character (emoji, rarer CJK) is TWO of them: + // trimming can leave the leading half behind, which encodes as a replacement byte rather than as + // the character it was part of. Dropping it only shortens the result, so it cannot re-overflow. + if (fitted.isNotEmpty() && fitted.last().isHighSurrogate()) { + fitted = fitted.dropLast(1) + } + return fitted + suffix +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportNotices.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportNotices.kt new file mode 100644 index 0000000..3d4b880 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ExportNotices.kt @@ -0,0 +1,85 @@ +package org.umamo.interop.moc3.export + +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportFormat +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.ExportReport +import org.umamo.runtime.model.DrawableId + +/** + * The advisory findings a lowering accumulates, in the order a rigger will read them. + * + * An export ALWAYS writes; anything it cannot express lands here instead of being silently dropped. + * The order is user-visible - the editor logs the report as a list and shows it in the export panel - + * so the two positional decisions are stated rather than inherited from whatever order the producers + * happen to run in: the version strip's own notices come FIRST (they describe the rig the rest of the + * lowering then worked on), and the dropped-drawable flush comes LAST. + * + * Mutable on purpose, and passed to each producer explicitly rather than hidden inside the export + * context, so a producer's signature says whether it can report. + */ +internal class Moc3ExportNotices { + private val collected = ArrayList() + + /** Everything reported so far, in report order. */ + val notices: List get() = collected + + /** + * The report to hand back with the document. + * + * @return ExportReport The advisory findings; empty for a fully-lowered export. + */ + fun report(): ExportReport = ExportReport(ExportFormat.Moc3, collected.toList()) + + /** + * Adopts the version strip's notices, which describe losses taken before any lowering ran. + * + * @param List stripNotices The strip's findings. + */ + fun addStripNotices(stripNotices: List) { + collected.addAll(stripNotices) + } + + /** + * Records a notice for something the lowering could not express. + * + * @param ExportEntityCategory category The entity category. + * @param String subject The entity's id. + * @param ExportNoticeReason reason Why it was not lowered. + */ + fun unsupported(category: ExportEntityCategory, subject: String, reason: ExportNoticeReason) { + collected.add(ExportNotice.UnsupportedChange(category, subject, reason)) + } + + /** + * Reports every channel a bundle had to drop to its static. + * + * @param ExportEntityCategory category The entity category. + * @param String subject The entity's id. + * @param Moc3ObjectKeyforms? keyforms The lowered keyforms, or null when unrepresentable. + */ + fun reportDemotions( + category: ExportEntityCategory, + subject: String, + keyforms: Moc3ObjectKeyforms?, + ) { + for (channel in keyforms?.demotedChannels.orEmpty()) { + unsupported(category, subject, ExportNoticeReason.ChannelDemotedToStatic(channel)) + } + } + + /** + * Reports every drawable the eligibility pass left out, with the reason it gave. + * + * Called LAST by the orchestrator, so drop notices trail the per-object findings rather than + * leading them - the eligibility pass runs first, but its findings read better after the rest. + * + * @param Map droppedDrawables Each omitted drawable and why. + */ + fun reportDroppedDrawables(droppedDrawables: Map) { + for ((drawableId, reason) in droppedDrawables) { + unsupported(ExportEntityCategory.Drawable, drawableId.raw, reason) + } + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3GlueLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3GlueLowering.kt new file mode 100644 index 0000000..b109b23 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3GlueLowering.kt @@ -0,0 +1,77 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.model.GlueVertexPair +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.PuppetModel +import org.umamo.format.moc3.model.Glue as MocGlue + +/** + * Lowers every glue whose two meshes both survived into its MOC3 record. + * + * Interns LAST of the four object kinds, and a glue naming a dropped mesh returns before it would have + * interned - so restructuring the filter to intern first would shift every binding index after it. + * + * @param PuppetModel puppet The stripped rig, for its glue list. + * @param Moc3ExportContext context The export's derived state. + * @param Moc3KeyformPool pool Interned into: every surviving glue claims a binding index here. + * @param Moc3ExportIds ids Claimed from: each surviving glue's written id. + * @param Moc3ExportNotices noticeSink Appended to: demotions and unknown mesh references. + * @return List The records, in model order. + */ +internal fun lowerGlues( + puppet: PuppetModel, + context: Moc3ExportContext, + pool: Moc3KeyformPool, + ids: Moc3ExportIds, + noticeSink: Moc3ExportNotices, +): List { + val plan = context.plan + return puppet.glues.mapIndexedNotNull { glueIndex, glue -> + val meshA = plan.drawableIndex(glue.meshA) + val meshB = plan.drawableIndex(glue.meshB) + if (meshA < 0 || meshB < 0) { + noticeSink.unsupported( + ExportEntityCategory.Glue, + glue.id ?: "Glue$glueIndex", + ExportNoticeReason.GlueNamesAnUnknownDrawable, + ) + return@mapIndexedNotNull null + } + val keyforms = + lowerObjectKeyforms( + pool, + null as KeyformGrid?, + UnitInterpolator, + glue.channelGrids.onlyChannels(FormChannel.GLUE_INTENSITY), + mapOf(FormChannel.GLUE_INTENSITY to ChannelValue.Scalar(glue.intensity)), + requireGeometry = false, + ) + // ONE fallback, computed once: a notice naming a subject the file does not contain sends the + // reader searching the export for an object that was never written under that name. The + // drop notice above is the exception on purpose - a dropped glue has no written id to cite, + // so its ordinal is the only handle left. + val glueId = glue.id ?: "Glue_${meshA}_${meshB}_" + noticeSink.reportDemotions(ExportEntityCategory.Glue, glueId, keyforms) + val bundle = keyforms?.bundle + val cellCount = maxOf(bundle?.cells?.size ?: 0, 1) + MocGlue( + id = ids.glueId(glueId), + meshAIndex = meshA, + meshBIndex = meshB, + keyformBindingIndex = keyforms?.bindingIndex ?: 0, + pairs = + glue.pairs.map { pair -> + GlueVertexPair(pair.indexA, pair.indexB, pair.weightA, pair.weightB) + }, + intensityKeyforms = + FloatArray(cellCount) { cellIndex -> + bundle?.let { scalarOf(it, cellIndex, FormChannel.GLUE_INTENSITY, glue.intensity) } + ?: glue.intensity + }, + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3IndexPlan.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3IndexPlan.kt new file mode 100644 index 0000000..4b31bfa --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3IndexPlan.kt @@ -0,0 +1,167 @@ +package org.umamo.interop.moc3.export + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/** + * Every ordering and index decision an export makes, resolved ONCE. + * + * A `.moc3` is entirely index-addressed - a drawable names its part and its deformer by list + * position, a deformer names its parent, a render-order child names a drawable. So the file + * order of each object list is not a detail: it is the addressing scheme, and every lowering has + * to agree on it exactly. Resolving it here means a lowering can only ask "what index is this + * id?" and never invent an answer. + * + * Two orderings are load-bearing rather than arbitrary. Parts and deformers are emitted + * PARENT-BEFORE-CHILD because every corpus file is written that way (parent index < own index, + * universally, v1 through v6) and the runtime's own single forward pass over the deformer list + * depends on it - a child seen before its parent would read an unresolved transform. + * + * @see MOC3.md §5.6 + */ +class Moc3IndexPlan private constructor( + val parts: List, + val deformers: List, + val drawables: List, + val parameters: List, + private val partIndexById: Map, + private val deformerIndexById: Map, + private val drawableIndexById: Map, + private val parameterIndexById: Map, +) { + /** The file index of [id], or -1 when it names nothing (the moc's own "absent" encoding). */ + fun partIndex(id: PartId?): Int = id?.let { partIndexById[it] } ?: -1 + + /** The file index of [id], or -1 when it names nothing. */ + fun deformerIndex(id: DeformerId?): Int = id?.let { deformerIndexById[it] } ?: -1 + + /** The file index of [id], or -1 when it names nothing. */ + fun drawableIndex(id: DrawableId?): Int = id?.let { drawableIndexById[it] } ?: -1 + + /** The file index of [id], or -1 when it names nothing. */ + fun parameterIndex(id: ParameterId?): Int = id?.let { parameterIndexById[it] } ?: -1 + + companion object { + /** + * Resolves the file order of every object list in [puppet]. + * + * @param PuppetModel puppet The rig to export. + * @param List exportableDrawables The drawables that will actually be written. + * @param Set exportableParts The parts that will actually be written. + * @return Moc3IndexPlan The resolved plan. + */ + fun of( + puppet: PuppetModel, + exportableDrawables: List = puppet.drawables, + exportableParts: Set = puppet.parts.mapTo(HashSet()) { part -> part.id }, + ): Moc3IndexPlan { + // Same reason the drawable list is filtered: a part the export omits must not hold an index, + // or every part after it - and every drawable's owning-part reference - names the wrong one. + val orderedParts = partsParentFirst(puppet).filter { part -> part.id in exportableParts } + val orderedDeformers = deformersParentFirst(puppet.deformers) + return Moc3IndexPlan( + parts = orderedParts, + deformers = orderedDeformers, + // Drawables and parameters carry no intra-list dependency, so their runtime order is + // already a valid file order and keeping it makes the export's output stable. + // + // The list is the drawables that will ACTUALLY be written, not every drawable the rig has. + // A MOC3 addresses drawables by position, so if the export drops one - a mesh-less drawable, + // say - and the plan still counted it, every index after it would name the wrong drawable + // and every mask reference would silently shift. + drawables = exportableDrawables, + parameters = puppet.parameters, + partIndexById = orderedParts.withIndex().associate { (index, part) -> part.id to index }, + deformerIndexById = + orderedDeformers.withIndex().associate { (index, deformer) -> deformer.id to index }, + drawableIndexById = + exportableDrawables.withIndex().associate { (index, drawable) -> drawable.id to index }, + parameterIndexById = + puppet.parameters.withIndex().associate { (index, parameter) -> parameter.id to index }, + ) + } + + /** + * The parts in org-tree pre-order, so a parent always precedes its children. + * + * Walks the TREE rather than sorting the flat list, because the tree is the authoritative + * hierarchy - the flat [PuppetModel.parts] is a lookup list whose order carries no meaning. A + * part the tree never reaches (an orphan) is appended so the export cannot silently drop it. + * + * @param PuppetModel puppet The rig. + * @return List The parts in file order. + */ + private fun partsParentFirst(puppet: PuppetModel): List { + val partById = puppet.parts.associateBy { part -> part.id } + val ordered = ArrayList(puppet.parts.size) + val visited = HashSet() + + fun walk(children: List) { + for (child in children) { + if (child !is OrgChild.Part) { + continue + } + val part = partById[child.id] ?: continue + // The guard also breaks a malformed cycle rather than recursing forever. + if (!visited.add(part.id)) { + continue + } + ordered.add(part) + walk(part.children) + } + } + walk(puppet.rootChildren) + for (part in puppet.parts) { + if (visited.add(part.id)) { + ordered.add(part) + } + } + return ordered + } + + /** + * The deformers ordered so a parent always precedes its children. + * + * A stable depth-first emit rather than a general topological sort: it preserves the input's + * relative order among siblings, which keeps the output stable across runs and keeps a + * round-tripped file close to its source instead of arbitrarily permuted. + * + * @param List deformers The rig's deformers. + * @return List The deformers in file order. + */ + private fun deformersParentFirst(deformers: List): List { + val byId = deformers.associateBy { deformer -> deformer.id } + val childrenByParent = deformers.groupBy { deformer -> deformer.parent } + val ordered = ArrayList(deformers.size) + val visited = HashSet() + + fun walk(deformer: Deformer) { + if (!visited.add(deformer.id)) { + return + } + ordered.add(deformer) + childrenByParent[deformer.id]?.forEach(::walk) + } + // Roots are deformers with no parent, plus any whose parent id does not resolve - an + // unresolvable parent is treated as root exactly as the import treats it. + for (deformer in deformers) { + if (deformer.parent == null || byId[deformer.parent] == null) { + walk(deformer) + } + } + // Anything still unvisited sits in a parent cycle; emit it so nothing is dropped. + for (deformer in deformers) { + walk(deformer) + } + return ordered + } + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3KeyformLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3KeyformLowering.kt new file mode 100644 index 0000000..d03184b --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3KeyformLowering.kt @@ -0,0 +1,196 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.format.moc3.model.Rgb +import org.umamo.interop.KeyformBundle +import org.umamo.interop.KeyformBundleResult +import org.umamo.interop.OutOfSpanPolicy +import org.umamo.interop.buildKeyformBundle +import org.umamo.runtime.keyform.FormInterpolator +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformGrid +import org.umamo.format.moc3.model.KeyformAxis as MocKeyformAxis + +/** + * The keyform-binding pool a `.moc3` addresses every object's forms through, plus the per-object + * bundles that ride it. + * + * The runtime keeps geometry and each channel on their own axes; a MOC3 stores ONE dense grid per + * object and every object points at a shared, deduplicated binding record describing that grid's + * parameter axes. So an export has to re-bundle each object (shared with the CMO3 path - see + * [buildKeyformBundle]) and then intern the resulting axis signature into a pool. + * + * BINDING 0 IS RESERVED for the zero-axis (static) binding and emitted whether or not anything + * references it. That is not tidiness: it is corpus-universal across all 26 samples, and the + * mesh-less `ModelWithOffscreen` family proves the runtime expects the record to exist even when + * only static parts point at it. + * + * The pool's NUMBERING will not match the source file's on a round trip. A MOC3's binding indices + * are the editor's internal creation order - first-reference order over the object lists is + * non-ascending in 9 of 10 non-trivial corpus models - and [org.umamo.runtime.model.PuppetModel] + * deliberately does not carry them, since format indices in the runtime model would invert the + * module graph. The pool is therefore semantically equivalent, not byte-identical, and every + * round-trip gate canonicalizes before comparing. + * + * @see MOC3.md §5.6 + */ +class Moc3KeyformPool(private val parameterIndexOf: (org.umamo.runtime.model.ParameterId) -> Int) { + /** Signature → binding index, so two objects on the same axes share one record. */ + private val indexBySignature = LinkedHashMap>>, Int>() + private val bindings = ArrayList() + + init { + // Reserve index 0 for the static binding before anything else can claim it. + intern(emptyList()) + } + + /** Every interned binding, in index order - what `MocDocument.keyformBindings` is built from. */ + fun bindings(): List = bindings.toList() + + /** + * The binding index for [bundle]'s axes, interning it when new. + * + * @param KeyformBundle bundle The re-bundled grid. + * @return Int The pool index. + */ + fun indexOf(bundle: KeyformBundle): Int = + intern( + bundle.axes.map { axis -> parameterIndexOf(axis.parameterId) to axis.keys.toList() }, + ) + + /** + * Interns an axis signature, returning its stable index. + * + * @param List signature Per axis, its parameter index and key positions. + * @return Int The pool index. + */ + private fun intern(signature: List>>): Int = + indexBySignature.getOrPut(signature) { + val index = bindings.size + bindings.add( + KeyformBinding( + index, + signature.map { (parameterIndex, keys) -> MocKeyformAxis(parameterIndex, keys.toFloatArray()) }, + ), + ) + index + } +} + +/** + * One object's lowered keyforms: the binding it points at and its dense cell list. + * + * @property Int bindingIndex The pool index this object's grid uses. + * @property KeyformBundle bundle The bundled grid, whose cells are already in the moc's + * first-axis-fastest order. + */ +class Moc3ObjectKeyforms( + val bindingIndex: Int, + val bundle: KeyformBundle, +) { + /** + * Channels the bundling dropped to their static, which the caller turns into notices. + * + * Delegated rather than copied into a field of its own: two stores of one fact let a later change + * filter the demotions in one place and leave the other reading the unfiltered list, with nothing + * in the type system to catch the divergence. + */ + val demotedChannels: List get() = bundle.demotedChannels +} + +/** + * Re-bundles one object and interns its binding. + * + * MOC3 takes [OutOfSpanPolicy.DemoteChannel] rather than CMO3's reject: every moc object must carry at + * least one keyform, so declining an owner would mean writing nothing for it and producing a file the + * runtime cannot load. Losing one channel's animation is the strictly smaller loss, and the caller + * turns the demotion into a notice so it is never silent. + * + * @param Moc3KeyformPool pool The shared binding pool. + * @param KeyformGrid? geometryGrid The object's geometry grid, or null when it has none. + * @param FormInterpolator geometryBlend The geometry interpolator. + * @param ChannelGrids channels The object's channel tracks. + * @param Map statics Fallback value per channel the object owns. + * @param Boolean requireGeometry Whether a geometry-less object is an error. + * @return Moc3ObjectKeyforms? The lowered keyforms, or null when unrepresentable. + */ +fun lowerObjectKeyforms( + pool: Moc3KeyformPool, + geometryGrid: KeyformGrid?, + geometryBlend: FormInterpolator, + channels: ChannelGrids, + statics: Map, + requireGeometry: Boolean, +): Moc3ObjectKeyforms? { + val result = + buildKeyformBundle( + geometryGrid, + geometryBlend, + channels, + statics, + requireGeometry, + OutOfSpanPolicy.DemoteChannel, + ) + if (result !is KeyformBundleResult.Bundled) { + return null + } + val bundle = result.bundle + return Moc3ObjectKeyforms(pool.indexOf(bundle), bundle) +} + +/** + * The scalar value of [channel] in [cellIndex], falling back to [fallback]. + * + * @param KeyformBundle bundle The bundled grid. + * @param Int cellIndex The cell ordinal. + * @param FormChannel channel The channel to read. + * @param Float fallback The value when the channel is absent or not a scalar. + * @return Float The cell's value. + */ +fun scalarOf(bundle: KeyformBundle, cellIndex: Int, channel: FormChannel, fallback: Float): Float = + (bundle.cells.getOrNull(cellIndex)?.channels?.get(channel) as? ChannelValue.Scalar)?.value ?: fallback + +/** + * The flag value of [channel] in [cellIndex], falling back to [fallback]. + * + * @param KeyformBundle bundle The bundled grid. + * @param Int cellIndex The cell ordinal. + * @param FormChannel channel The channel to read. + * @param Boolean fallback The value when the channel is absent or not a flag. + * @return Boolean The cell's value. + */ +fun flagOf(bundle: KeyformBundle, cellIndex: Int, channel: FormChannel, fallback: Boolean): Boolean = + (bundle.cells.getOrNull(cellIndex)?.channels?.get(channel) as? ChannelValue.Flag)?.flag ?: fallback + +/** + * The color of [channel] in [cellIndex] as the format's [Rgb], or null when the target version has no + * color tables. + * + * A null return is meaningful rather than a failure: the lowering writes the color sections only when + * some object carries a color, so a pre-4.2 export must produce nulls throughout or it would + * synthesize tables the version cannot address. + * + * @param KeyformBundle? bundle The bundled grid, or null for an unkeyed owner. + * @param Int cellIndex The cell ordinal. + * @param FormChannel channel The color channel to read. + * @param ColorRgb fallback The owner's static color. + * @param Boolean enabled Whether the target version carries color tables. + * @return Rgb? The cell's color, or null when colors are not written. + */ +fun colorOf( + bundle: KeyformBundle?, + cellIndex: Int, + channel: FormChannel, + fallback: ColorRgb, + enabled: Boolean, +): Rgb? { + if (!enabled) { + return null + } + val value = + (bundle?.cells?.getOrNull(cellIndex)?.channels?.get(channel) as? ChannelValue.Color)?.color ?: fallback + return Rgb(value.red, value.green, value.blue) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3LoweredParts.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3LoweredParts.kt new file mode 100644 index 0000000..7a85c6e --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3LoweredParts.kt @@ -0,0 +1,92 @@ +package org.umamo.interop.moc3.export + +import org.umamo.interop.ExportEntityCategory +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.PartId +import org.umamo.format.moc3.model.Part as MocPart + +/** + * The lowered parts, plus the keyform bundles the offscreen lowering has to reuse. + * + * @property List records The part records, in file order. + * @property Map keyformsByPartId Each part's bundle, for the offscreen lowering. + */ +internal class Moc3LoweredParts( + val records: List, + val keyformsByPartId: Map, +) + +/** + * Lowers every exportable part into a MOC3 part record. + * + * An offscreen's keyforms ride its OWNER PART'S grid - Σ of the owner grid sizes is CountInfo 36 - so + * the part's bundle is built once here and handed back for the offscreen lowering to read. Building it + * twice would let the two disagree about the grid an offscreen is indexed against; RETURNING it rather + * than writing it into shared state is what makes lowering offscreens first a compile error instead of + * a silently empty map. + * + * @param Moc3ExportContext context The export's derived state. + * @param Moc3KeyformPool pool Interned into: every part claims a binding index here. + * @param Moc3ExportIds ids Claimed from: each part's written id. + * @param Moc3ExportNotices noticeSink Appended to: channel demotions. + * @return Moc3LoweredParts The records and their bundles. + */ +internal fun lowerParts( + context: Moc3ExportContext, + pool: Moc3KeyformPool, + ids: Moc3ExportIds, + noticeSink: Moc3ExportNotices, +): Moc3LoweredParts { + val plan = context.plan + val partKeyformsById = HashMap() + val records = + plan.parts.map { part -> + // An isolated part's composite channels ride the same cells as its draw order, so they are + // bundled together; a non-isolated part has no composite to key. + val compositeChannels = + if (context.offscreensEnabled && part.isIsolated) { + renderChannels(context.colorsEnabled) + } else { + emptyArray() + } + val compositeStatics = + if (context.offscreensEnabled && part.isIsolated) { + renderStatics( + part.composite.opacity, + part.composite.multiplyColor, + part.composite.screenColor, + context.colorsEnabled, + ) + } else { + emptyMap() + } + val keyforms = + lowerObjectKeyforms( + pool, + null as KeyformGrid?, + UnitInterpolator, + part.channelGrids.onlyChannels(*(compositeChannels + arrayOf(FormChannel.DRAW_ORDER))), + compositeStatics + mapOf(FormChannel.DRAW_ORDER to ChannelValue.Scalar(part.drawOrder.toFloat())), + requireGeometry = false, + ) + noticeSink.reportDemotions(ExportEntityCategory.Part, part.id.raw, keyforms) + partKeyformsById[part.id] = keyforms + val bundle = keyforms?.bundle + val cellCount = bundle?.cells?.size ?: 0 + MocPart( + id = ids.partId(part.id), + parentPartIndex = plan.partIndex(context.partParentById[part.id]), + // A static part points at binding 0, which is what the import's `> 0` static test expects. + keyformBindingIndex = if (cellCount > 1) keyforms!!.bindingIndex else 0, + drawOrderKeyforms = + FloatArray(maxOf(cellCount, 1)) { cellIndex -> + bundle?.let { scalarOf(it, cellIndex, FormChannel.DRAW_ORDER, part.drawOrder.toFloat()) } + ?: part.drawOrder.toFloat() + }, + isVisible = part.isVisible, + ) + } + return Moc3LoweredParts(records, partKeyformsById) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3OffscreenLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3OffscreenLowering.kt new file mode 100644 index 0000000..9e8d8a8 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3OffscreenLowering.kt @@ -0,0 +1,98 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.moc.ConstantFlag +import org.umamo.format.moc3.model.Offscreen +import org.umamo.format.moc3.model.OffscreenKeyform +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.exactLegacyBlendFlagOf +import org.umamo.interop.packedBlendOf +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.drawablesByPartSubtree +import org.umamo.runtime.model.flattenedMasks + +/** + * Lowers every isolated part into a MOC3 v6 offscreen record. + * + * An offscreen is a part rendered into its own buffer and composited back as one layer, which is what + * gives a part an opacity and a blend mode of its own. The MOC3 models it as a separate object list + * keyed by owner part index rather than as fields on the part, so this walks the parts once and emits a + * record per [org.umamo.runtime.model.PartGroupMode.Isolated] one, in ascending part-index order (the + * corpus-confirmed ordering invariant). + * + * @param PuppetModel puppet The rig being exported. + * @param Moc3IndexPlan plan The file's addressing scheme. + * @param Map keyformsByPartId The part bundles the part lowering already built. + * @param Boolean colorsEnabled Whether the target version has color tables. + * @param Moc3ExportNotices noticeSink Where anything unrepresentable is reported. + * @return List The records, owner-index ascending. + */ +internal fun lowerOffscreens( + puppet: PuppetModel, + plan: Moc3IndexPlan, + keyformsByPartId: Map, + colorsEnabled: Boolean, + noticeSink: Moc3ExportNotices, +): List { + val isolated = plan.parts.filter { part -> part.isIsolated } + if (isolated.isEmpty()) { + return emptyList() + } + + // One index for the whole batch - flattenedMasks' docblock requires it, and a per-composite rebuild + // would walk the whole part tree once per isolated part. + val subtrees = puppet.drawablesByPartSubtree() + return isolated + .map { part -> + val composite = part.composite + // The SHARED mask expansion: resolving part-masks a second way here would let the shipped + // file clip differently from the viewport that authored it. + val maskDrawables = flattenedMasks(composite, subtrees) + val maskIndices = + maskDrawables + .map { drawableId -> plan.drawableIndex(drawableId) } + .filter { index -> index >= 0 } + if (maskIndices.size < maskDrawables.size) { + noticeSink.unsupported( + ExportEntityCategory.Part, + part.id.raw, + ExportNoticeReason.OffscreenMaskNotInExport, + ) + } + val bundle = keyformsByPartId[part.id]?.bundle + // Exactly the owner part's grid size: Σ over the owner bindings is CountInfo 36, so a row count + // that disagrees with the part's own keyform count desynchronizes every later offscreen. + val cellCount = maxOf(bundle?.cells?.size ?: 0, 1) + Offscreen( + ownerPartIndex = plan.partIndex(part.id), + // MOC3 v6 §5.6 s156: the drawable flag byte's shape, reused. Bit 2 (double-sided) is set on + // every corpus offscreen - a composited layer is a quad with no back face to cull - and the + // legacy pair restates the mode when, and only when, it can name it exactly, which is the + // opposite of what the same version does for a drawable (there the pair stays clear). Both + // are what the editor writes. + constantFlags = + ConstantFlag.IS_DOUBLE_SIDED or + exactLegacyBlendFlagOf(composite.blendMode) or + (if (composite.invertMask) ConstantFlag.IS_INVERTED_MASK else 0), + // MOC3 v6 §5.6 s157: packed colorMode | (alphaMode shl 8). + blendMode = packedBlendOf(composite.blendMode, composite.alphaBlendMode), + maskCount = maskIndices.size, + keyforms = + List(cellCount) { cellIndex -> + OffscreenKeyform( + opacity = + bundle?.let { scalarOf(it, cellIndex, FormChannel.OPACITY, composite.opacity) } + ?: composite.opacity, + multiplyColor = + colorOf(bundle, cellIndex, FormChannel.MULTIPLY_COLOR, composite.multiplyColor, colorsEnabled), + screenColor = + colorOf(bundle, cellIndex, FormChannel.SCREEN_COLOR, composite.screenColor, colorsEnabled), + ) + }, + maskIndices = maskIndices.toIntArray(), + ) + } + .sortedBy { offscreen -> offscreen.ownerPartIndex } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ParameterLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ParameterLowering.kt new file mode 100644 index 0000000..ea16f75 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3ParameterLowering.kt @@ -0,0 +1,39 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.runtime.model.ParameterKind +import org.umamo.format.moc3.moc.MocParameter as MocParameter + +/** + * Lowers every parameter in the plan into its MOC3 record. + * + * Takes no keyform pool, which is the point of the signature: a parameter is an axis objects bind TO, + * so this pass cannot intern a binding and the type says so. + * + * @param Moc3ExportContext context The export's derived state. + * @param Moc3ExportIds ids Claimed from: each parameter's written id (over-long ones reported). + * @return List The records, in plan order. + */ +internal fun lowerParameters( + context: Moc3ExportContext, + ids: Moc3ExportIds, +): List { + val version = context.version + val plan = context.plan + return plan.parameters.map { parameter -> + MocParameter( + id = ids.parameterId(parameter.id), + minimumValue = parameter.min, + maximumValue = parameter.max, + defaultValue = parameter.default, + // Parameter.Types is moc 4+; below that every parameter is normal and the section is absent. + type = + when { + version.byteValue < 4 -> null + parameter.kind == ParameterKind.BLEND_SHAPE -> ParameterType.BLEND_SHAPE + else -> ParameterType.NORMAL + }, + repeats = parameter.repeat, + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3RenderOrderLowering.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3RenderOrderLowering.kt new file mode 100644 index 0000000..f39183d --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3RenderOrderLowering.kt @@ -0,0 +1,79 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.model.RenderOrderChild +import org.umamo.format.moc3.model.RenderOrderGroup +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode + +/** + * Lowers the runtime's render tree into the MOC3's draw-group records. + * + * The shapes already correspond: a MOC3 draw group holds an ordered child list where each child is + * either an art mesh or a nested group tagged with the part that supplies its depth, and + * `RenderGroup` is that same thing. Group 0 is the root by convention, and records are allocated + * in the order the tree is walked so a parent always precedes its children. + * + * The format has one hard rule worth stating: EVERY art mesh must appear exactly once across the + * whole tree. A runtime that finds a drawable referenced twice, or not at all, is documented as + * free to behave erratically - so the guarantee has to arrive with the tree rather than be checked + * here: the render tree the import builds supplies it through its own append-the-missing safety + * net, and this walk preserves that shape, skipping only a child whose drawable or part could not + * be written at all. + * + * @see MOC3.md §5.6 + */ +internal fun lowerRenderOrder(puppet: PuppetModel, plan: Moc3IndexPlan): List { + val groups = ArrayList() + + /** + * Allocates a record for [group] and recursively for its sub-groups, returning its index. + * + * The record is reserved BEFORE its children are walked, so a nested group's own index is already + * assigned when its parent's child entry needs to name it. + * + * @param RenderGroup group The subtree root. + * @return Int The allocated record index. + */ + fun allocate(group: RenderGroup): Int { + val recordIndex = groups.size + // Placeholder, replaced below: the slot must exist before the children can reference it. + groups.add(RenderOrderGroup(emptyList())) + val children = ArrayList(group.children.size) + for (child: RenderNode in group.children) { + when (child) { + is RenderDrawable -> { + val drawableIndex = plan.drawableIndex(child.id) + if (drawableIndex >= 0) { + // MOC3 §5.6 render-order child kind 0: an art-mesh leaf. groupIndex is unused for a leaf. + children.add(RenderOrderChild(kind = 0, index = drawableIndex, groupIndex = 0)) + } + } + is RenderGroup -> { + val partIndex = plan.partIndex(child.partId) + // The part check comes BEFORE the record is allocated. Allocating first and then + // declining to reference it leaves a group in the table that no child names - an + // unreachable record still counted by CI_RENDER_ORDER_GROUPS and still consuming a slot + // in the child-start prefix sum. + // + // Skipping the record takes its whole subtree with it, which is only sound because the + // sole reason a part is unwritable is that it is a sketch, and the export drops every + // drawable under a sketch part too. A future rule that drops a part while KEEPING its + // drawables would strand those art meshes outside the render tree, which the format + // says leaves the runtime free to behave erratically. + if (partIndex >= 0) { + val childRecord = allocate(child) + // Kind 1: a "group by draw order" part, whose members live in the named record. + children.add(RenderOrderChild(kind = 1, index = partIndex, groupIndex = childRecord)) + } + } + } + } + groups[recordIndex] = RenderOrderGroup(children) + return recordIndex + } + + allocate(puppet.renderRoot) + return groups +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3VersionDowngrade.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3VersionDowngrade.kt new file mode 100644 index 0000000..0535fbe --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/export/Moc3VersionDowngrade.kt @@ -0,0 +1,384 @@ +package org.umamo.interop.moc3.export + +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import org.umamo.interop.ExportNotice +import org.umamo.interop.nearestLegacyBlendMode +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.multiplyColor +import org.umamo.runtime.model.screenColor + +/** + * Removes from a copy of the rig everything the export target's runtime cannot load. + * + * A MOC3 version is a hard capability boundary: a Cubism 3.0 MOC3 has nowhere to put a blend shape, a color + * table, or an offscreen, and the sections that would carry them do not exist in its table. Dropping + * them at the SECTION level is not enough - the CountInfo would still count the keyforms a stripped + * section no longer holds - so the removal happens here, on the [PuppetModel], before any lowering + * runs. The lowering then sees one shape it can express completely. + * + * Reporting is the other half of the reason: a notice raised here names entities the rigger + * recognizes ("Warp40", "ParamAngleX"), while the same loss detected after lowering could only name + * section indices. + * + * What can be carried is asked of the SECTION TABLE, not of [RuntimeTarget.supports]. The two ladders + * are close but not the same, and where they differ the section table is the one that decides what a + * file can hold: [RuntimeTarget] follows the official editor's target dialog, which gates the reversed + * mask at Cubism 4.0 and the parameter repeat at Cubism 5.3 even though both are carried by every MOC3 version back + * to v1. Stripping on the editor's ladder would make a v5 file that uses either one round-trip + * LOSSILY through a v5 export - LimeBirb's repeating parameters are exactly that case in the corpus. + * RuntimeTarget's own docblock anticipates this and says so: edit gating is editor parity, the + * section-level nuances belong to export lowering. + * + * The consequence is that a pre-export confirmation built on + * [org.umamo.runtime.model.unsupportedFeaturesInUse] can name a feature this does not strip. That is + * the conservative direction (it over-warns, never under-warns), and the report returned here is what + * actually happened. + * + * @see MOC3.md § Export + */ +object Moc3VersionDowngrade { + /** + * A rig reduced to a target's capabilities, plus what that cost. + * + * @property PuppetModel puppet The stripped copy; the caller's model is untouched. + * @property List notices One [ExportNotice.FeatureStripped] per feature actually removed. + */ + class Stripped(val puppet: PuppetModel, val notices: List) + + /** + * Strips [puppet] down to what moc [version] can carry. + * + * @param PuppetModel puppet The rig to export. + * @param MocVersion version The moc version being written. + * @return Stripped The reduced rig and its notices; the input model when nothing had to go. + */ + fun strip(puppet: PuppetModel, version: MocVersion): Stripped { + val unsupported = RuntimeFeature.entries.filterNot { feature -> carries(feature, version) } + if (unsupported.isEmpty()) { + return Stripped(puppet, emptyList()) + } + val notices = ArrayList() + var stripped = puppet + + /** + * Records one feature's removal, skipping the notice when nothing carried it. + * + * @param RuntimeFeature feature The feature removed. + * @param List subjects The entities it was removed from. + */ + fun report(feature: RuntimeFeature, subjects: List) { + if (subjects.isNotEmpty()) { + notices.add(ExportNotice.FeatureStripped(feature, subjects)) + } + } + + for (feature in unsupported) { + stripped = + when (feature) { + RuntimeFeature.WarpQuadTransform -> stripQuadTransform(stripped, ::report) + RuntimeFeature.MeshWarpBlendShapes -> stripMeshWarpBlendShapes(stripped, ::report) + RuntimeFeature.BlendShapeParameters -> stripBlendShapeParameters(stripped, ::report) + RuntimeFeature.MultiplyColor -> + stripColorChannel(stripped, FormChannel.MULTIPLY_COLOR, ColorRgb.MultiplyIdentity, ::report) + + RuntimeFeature.ScreenColor -> + stripColorChannel(stripped, FormChannel.SCREEN_COLOR, ColorRgb.ScreenIdentity, ::report) + + RuntimeFeature.ExtendedBlendShapes -> stripExtendedBlendShapes(stripped, ::report) + RuntimeFeature.ExtendedBlendModes -> stripExtendedBlendModes(stripped, ::report) + RuntimeFeature.PartComposite -> stripPartComposites(stripped, ::report) + // Carried by EVERY moc version, so `carries` is unconditionally true for both and neither + // ever reaches this loop: the reversed mask is a bit in the constant-flag byte and + // parameter repeat is section 54, and both go back to v1. The arm exists to keep the + // `when` exhaustive, not because there is work to do. If a future version gate ever + // drops one of them, this has to grow a real strip - returning the model unchanged would + // write the feature into a file with nowhere to put it. + RuntimeFeature.ReversedMask, RuntimeFeature.ParameterRepeat -> stripped + // Neither is representable in PuppetModel, so there is nothing here to remove: motion + // sync is a sidecar family and an art path survives only as CMO3 round-trip payload. + RuntimeFeature.MotionSync, RuntimeFeature.ArtPath -> stripped + } + } + return Stripped(stripped, notices) + } + + /** + * Whether moc [version] has somewhere to put [feature]. + * + * Asked of the [Section] table itself rather than restated as version numbers, so a section whose + * introduction version is corrected in one place cannot leave this saying otherwise - and each + * branch doubles as the citation for why the feature has that floor. + * + * @param RuntimeFeature feature The feature to place. + * @param MocVersion version The version being written. + * @return Boolean True when the version can carry it. + */ + private fun carries(feature: RuntimeFeature, version: MocVersion): Boolean = + when (feature) { + RuntimeFeature.WarpQuadTransform -> Section.WARP_MODE.indexIn(version) >= 0 + RuntimeFeature.MeshWarpBlendShapes -> Section.BLENDSHAPE_MESH_OBJECT.indexIn(version) >= 0 + RuntimeFeature.BlendShapeParameters -> Section.PARAM_TYPE.indexIn(version) >= 0 + RuntimeFeature.MultiplyColor, RuntimeFeature.ScreenColor -> Section.COLOR_MULTIPLY_R.indexIn(version) >= 0 + RuntimeFeature.ExtendedBlendShapes -> Section.BLENDSHAPE_ROTATION_OBJECT.indexIn(version) >= 0 + RuntimeFeature.ExtendedBlendModes -> Section.ARTMESH_EXTENDED_BLEND.indexIn(version) >= 0 + RuntimeFeature.PartComposite -> Section.OFFSCREEN_OWNER_PART.indexIn(version) >= 0 + RuntimeFeature.ParameterRepeat -> Section.PARAM_REPEAT.indexIn(version) >= 0 + // The reversed mask is a BIT in the drawable/offscreen constant-flag byte, not a section of + // its own, and that byte is in every version - so no moc version has to give it up. + RuntimeFeature.ReversedMask -> true + // Neither is representable in PuppetModel, so no version can fail to carry what is not there. + RuntimeFeature.MotionSync, RuntimeFeature.ArtPath -> true + } + + /** The quad-transform flag (Cubism 3.3's warp method) cleared on every warp that set it. */ + private fun stripQuadTransform(puppet: PuppetModel, report: Reporter): PuppetModel { + val affected = ArrayList() + val deformers = + puppet.deformers.map { deformer -> + if (deformer is Deformer.Warp && deformer.isQuadTransform) { + affected.add(deformer.name) + deformer.copy(isQuadTransform = false) + } else { + deformer + } + } + report(RuntimeFeature.WarpQuadTransform, affected) + return if (affected.isEmpty()) puppet else puppet.copy(deformers = deformers) + } + + /** Every mesh and warp blend-shape binding dropped (moc 4.2 introduced them). */ + private fun stripMeshWarpBlendShapes(puppet: PuppetModel, report: Reporter): PuppetModel { + val affected = ArrayList() + val drawables = + puppet.drawables.map { drawable -> + if (drawable.blendShapes.isEmpty()) { + drawable + } else { + affected.add(drawable.name) + drawable.copy(blendShapes = emptyList()) + } + } + val deformers = + puppet.deformers.map { deformer -> + if (deformer is Deformer.Warp && deformer.blendShapes.isNotEmpty()) { + affected.add(deformer.name) + deformer.copy(blendShapes = emptyList()) + } else { + deformer + } + } + report(RuntimeFeature.MeshWarpBlendShapes, affected) + return if (affected.isEmpty()) puppet else puppet.copy(drawables = drawables, deformers = deformers) + } + + /** Rotation- and part-target blend records dropped (moc 5.0 introduced those two targets). */ + private fun stripExtendedBlendShapes(puppet: PuppetModel, report: Reporter): PuppetModel { + val affected = ArrayList() + val deformers = + puppet.deformers.map { deformer -> + if (deformer is Deformer.Rotation && deformer.blendShapes.isNotEmpty()) { + affected.add(deformer.name) + deformer.copy(blendShapes = emptyList()) + } else { + deformer + } + } + val parts = + puppet.parts.map { part -> + if (part.blendShapes.isEmpty()) { + part + } else { + affected.add(part.name) + part.copy(blendShapes = emptyList()) + } + } + report(RuntimeFeature.ExtendedBlendShapes, affected) + return if (affected.isEmpty()) puppet else puppet.copy(deformers = deformers, parts = parts) + } + + /** Blend-shape parameters demoted to normal axes; their records are already gone by this point. */ + private fun stripBlendShapeParameters(puppet: PuppetModel, report: Reporter): PuppetModel { + val affected = ArrayList() + val parameters = + puppet.parameters.map { parameter: Parameter -> + if (parameter.kind == ParameterKind.BLEND_SHAPE) { + affected.add(parameter.id.raw) + parameter.copy(kind = ParameterKind.NORMAL) + } else { + parameter + } + } + report(RuntimeFeature.BlendShapeParameters, affected) + return if (affected.isEmpty()) puppet else puppet.copy(parameters = parameters) + } + + /** One color channel reset to its identity everywhere - statics and tracks alike. */ + private fun stripColorChannel( + puppet: PuppetModel, + channel: FormChannel, + identity: ColorRgb, + report: Reporter, + ): PuppetModel { + val isMultiply = channel == FormChannel.MULTIPLY_COLOR + val identityValue = ChannelValue.Color(identity) + val affected = ArrayList() + + /** + * Whether an owner tints through this channel - a non-identity static or a track. + * + * @param ColorRgb staticColor The owner's static color. + * @param ChannelGrids grids The owner's tracks. + * @return Boolean True when the channel is in use. + */ + fun tints(staticColor: ColorRgb, grids: ChannelGrids): Boolean = + staticColor != identity || grids.varies(channel, identityValue) + + val drawables = + puppet.drawables.map { drawable: Drawable -> + val staticColor = if (isMultiply) drawable.multiplyColor else drawable.screenColor + if (!tints(staticColor, drawable.channelGrids)) { + drawable + } else { + affected.add(drawable.name) + drawable + .copy(channelGrids = drawable.channelGrids.without(channel)) + .let { if (isMultiply) it.copy(multiplyColor = identity) else it.copy(screenColor = identity) } + } + } + val deformers = + puppet.deformers.map { deformer -> + val staticColor = if (isMultiply) deformer.multiplyColor else deformer.screenColor + if (!tints(staticColor, deformer.channelGrids)) { + deformer + } else { + affected.add(deformer.name) + val grids = deformer.channelGrids.without(channel) + when (deformer) { + is Deformer.Warp -> + if (isMultiply) { + deformer.copy(channelGrids = grids, multiplyColor = identity) + } else { + deformer.copy(channelGrids = grids, screenColor = identity) + } + + is Deformer.Rotation -> + if (isMultiply) { + deformer.copy(channelGrids = grids, multiplyColor = identity) + } else { + deformer.copy(channelGrids = grids, screenColor = identity) + } + } + } + } + val parts = + puppet.parts.map { part: Part -> + val composite = part.activeComposite ?: return@map part + val staticColor = if (isMultiply) composite.multiplyColor else composite.screenColor + if (!tints(staticColor, part.channelGrids)) { + part + } else { + affected.add(part.name) + val reset: PartComposite = + if (isMultiply) { + composite.copy(multiplyColor = identity) + } else { + composite.copy(screenColor = identity) + } + part.copy(composite = reset, channelGrids = part.channelGrids.without(channel)) + } + } + report(if (isMultiply) RuntimeFeature.MultiplyColor else RuntimeFeature.ScreenColor, affected) + return if (affected.isEmpty()) { + puppet + } else { + puppet.copy(drawables = drawables, deformers = deformers, parts = parts) + } + } + + /** The 5.3 blend surface degraded to its nearest pre-5.3 ancestor, alpha back to Over. */ + private fun stripExtendedBlendModes(puppet: PuppetModel, report: Reporter): PuppetModel { + val affected = ArrayList() + val drawables = + puppet.drawables.map { drawable -> + if (drawable.blendMode.isLegacy && drawable.alphaBlendMode == AlphaBlendMode.Over) { + drawable + } else { + affected.add(drawable.name) + drawable.copy( + blendMode = nearestLegacyBlendMode(drawable.blendMode), + alphaBlendMode = AlphaBlendMode.Over, + ) + } + } + val parts = + puppet.parts.map { part -> + val composite = part.activeComposite ?: return@map part + if (composite.blendMode.isLegacy && composite.alphaBlendMode == AlphaBlendMode.Over) { + part + } else { + affected.add(part.name) + part.copy( + composite = + composite.copy( + blendMode = nearestLegacyBlendMode(composite.blendMode), + alphaBlendMode = AlphaBlendMode.Over, + ), + ) + } + } + report(RuntimeFeature.ExtendedBlendModes, affected) + return if (affected.isEmpty()) puppet else puppet.copy(drawables = drawables, parts = parts) + } + + /** + * Isolated parts demoted to grouped: the subtree keeps its single stacking slot but stops being + * composited as its own layer. The composite settings stay on the part - they are latent by + * design, and this strip runs on an export copy the rigger never sees. + */ + private fun stripPartComposites(puppet: PuppetModel, report: Reporter): PuppetModel { + val affected = ArrayList() + val parts = + puppet.parts.map { part -> + if (part.isIsolated) { + affected.add(part.name) + part.copy(groupMode = PartGroupMode.Grouped) + } else { + part + } + } + report(RuntimeFeature.PartComposite, affected) + return if (affected.isEmpty()) puppet else puppet.copy(parts = parts) + } +} + +/** How each strip hands its result back: the feature removed and who it was removed from. */ +private typealias Reporter = (RuntimeFeature, List) -> Unit + +/** + * This owner's tracks without [channel], sharing [ChannelGrids.Empty] when nothing is left. + * + * @param FormChannel channel The channel to drop. + * @return ChannelGrids The remaining tracks. + */ +private fun ChannelGrids.without(channel: FormChannel): ChannelGrids { + if (this[channel] == null) { + return this + } + val remaining = gridsByChannel - channel + return if (remaining.isEmpty()) ChannelGrids.Empty else ChannelGrids(remaining) +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3AtlasPages.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3AtlasPages.kt new file mode 100644 index 0000000..c24a6cd --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3AtlasPages.kt @@ -0,0 +1,34 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.MocDocument +import org.umamo.interop.AtlasPageSet + +/** + * Collects a MOC3-imported puppet's atlas pages from its sidecar page bytes. + * + * A `.moc3` embeds no pixels: the pages are external PNG files listed in model3.json's + * `FileReferences.Textures` (in order - a drawable's `textureIndex` indexes that list), so the caller + * reads those files and hands their bytes here in the same order. All this adds is the per-drawable + * index; the page list passes straight through. + * + * Unlike a CMO3, a page that will not decode should fail the whole import rather than be dropped - the + * pages are sibling files named by the manifest, so one that will not decode means the family on disk + * is incomplete or mismatched. That is the decoder's policy and the loader states it there. + * + * @param MocDocument mocDocument The decoded moc, whose art meshes carry the per-mesh textureIndex. + * @param List pageBytes The PNG bytes per manifest texture, in Textures order. + * @return AtlasPageSet The pages + per-drawable index. + */ +public fun moc3AtlasPages(mocDocument: MocDocument, pageBytes: List): AtlasPageSet = + AtlasPageSet( + pageBytes, + // MOC3: ArtMesh.textureIndex, decoded from section 41 (Section.ARTMESH_TEXTURE) - the mesh's page + // slot, indexing model3's Textures list. + mocDocument.artMeshes.associate { artMesh -> artMesh.id to artMesh.textureIndex }, + // Cubism texture files are straight-alpha PNGs (premultiplication is a runtime load option, not a + // property of the files), matching the straight-alpha stream PngCodec yields. The premultiplied- + // vs-straight COMPOSITING distinction (legacy vs 5.3+ blend modes) rides BlendMode.isLegacy, not + // this flag; see PuppetTextures.premultipliedAlpha and docs/format/CMO3.md, "Premultiplied vs + // straight alpha". + premultipliedAlpha = false, + ) \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3BlendShapeImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3BlendShapeImport.kt new file mode 100644 index 0000000..e0d1300 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3BlendShapeImport.kt @@ -0,0 +1,322 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.Rgb +import org.umamo.interop.moc3.PointSpace +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.flagAt +import org.umamo.runtime.eval.meshGridDefaultDeltas +import org.umamo.runtime.eval.rotationFormAt +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.BlendWeightLimitPoint +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm +import org.umamo.format.moc3.model.BlendShape as MocBlendShape + +/* + * Blend-shape ingest (MOC3 v4+ §5.6), one builder per target kind. + * + * A moc stores a blend key as a DELTA against the object's pose at the parameter defaults, while the + * runtime stores the referenced value itself. So every builder here does the same two things: sample + * the owner's grid at the default pose to recover that reference, then add each stored row onto it. + * The evaluator subtracts the same reference back out, which is why the reference has to be sampled the + * way it samples it - `BlendShapeChannelOracleTest` and `BlendShapeOracleTest` are what hold the two + * together, since a reference that is wrong by a constant still round-trips through our own export. + * + * Every builder runs on an object that is already CONSTRUCTED, because the object's own keyform grid is + * the reference source. + */ + +/** + * Maps [records] onto [drawable] as mesh blend bindings: each stored delta row plus the + * grid-at-default reference (positions, draw order, opacity), converted to runtime space. + * + * @param Moc3ImportContext context The import's derived state. + * @param Drawable drawable The constructed runtime drawable (its grid is the reference source). + * @param PointSpace space The drawable's stored point space. + * @param List records The drawable's records. + * @return List> The runtime bindings. + */ +internal fun meshBlendShapesOf( + context: Moc3ImportContext, + drawable: Drawable, + space: PointSpace, + records: List, +): List> { + val defaultValue: (ParameterId) -> Float = context::defaultValueOf + val referenceDeltas = meshGridDefaultDeltas(drawable, defaultValue) ?: FloatArray(0) + // The scalar reference is each channel's own value at the DEFAULT pose. An untracked or + // out-of-range channel falls back to the drawable's static, which for an imported drawable is + // Cubism's 500 / full opacity - the same fallback meshBlendState uses, so the evaluator's + // subtraction cancels exactly even for an ungridded drawable. + val referenceDrawOrder = + drawable.channelGrids.scalarAt(FormChannel.DRAW_ORDER, drawable.drawOrder, defaultValue) + val referenceOpacity = drawable.channelGrids.scalarAt(FormChannel.OPACITY, drawable.opacity, defaultValue) + val referenceMultiply = + drawable.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor, defaultValue) + val referenceScreen = + drawable.channelGrids.colorAt(FormChannel.SCREEN_COLOR, drawable.screenColor, defaultValue) + return records.mapNotNull { record -> + val payloads = + record.keyforms.map { keyform -> + (keyform as? BlendShapeKeyform.Mesh)?.form ?: return@mapNotNull null + } + if (payloads.size != record.keyPositions.size) { + return@mapNotNull null + } + bindingOfRecord(context, record) { keyIndex -> + MeshForm( + positionDeltas = + addReference( + referenceDeltas, + context.convertDeltas(space, payloads[keyIndex].vertexPositions), + ), + drawOrder = referenceDrawOrder + payloads[keyIndex].drawOrder, + opacity = referenceOpacity + payloads[keyIndex].opacity, + // Color delta rows are ADDITIVE like the scalars, so their identity is zero rather + // than Cubism's white multiply / black screen; a record without color tables has no + // row at all and contributes nothing. + multiplyColor = addColorDelta(referenceMultiply, payloads[keyIndex].multiplyColor), + screenColor = addColorDelta(referenceScreen, payloads[keyIndex].screenColor), + ) + } + } +} + +/** + * Maps [records] onto [warp] as lattice blend bindings: each stored control-point delta row + * plus the lattice's grid-at-default reference, and the same treatment for the deformer's own + * render channels (opacity, multiply / screen color), which CASCADE onto every drawable + * underneath. + * + * @param Moc3ImportContext context The import's derived state. + * @param Deformer.Warp warp The constructed runtime warp (its grid is the reference source). + * @param PointSpace space The warp's stored point space. + * @param List records The warp's records. + * @return List> The runtime bindings. + */ +internal fun warpBlendShapesOf( + context: Moc3ImportContext, + warp: Deformer.Warp, + space: PointSpace, + records: List, +): List> { + val defaultValue: (ParameterId) -> Float = context::defaultValueOf + val reference = warpControlPointsAt(warp.geometryGrid, defaultValue) ?: FloatArray(0) + val referenceOpacity = warp.channelGrids.scalarAt(FormChannel.OPACITY, warp.opacity, defaultValue) + val referenceMultiply = + warp.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, warp.multiplyColor, defaultValue) + val referenceScreen = warp.channelGrids.colorAt(FormChannel.SCREEN_COLOR, warp.screenColor, defaultValue) + return records.mapNotNull { record -> + val payloads = + record.keyforms.map { keyform -> + (keyform as? BlendShapeKeyform.Warp)?.form ?: return@mapNotNull null + } + if (payloads.size != record.keyPositions.size) { + return@mapNotNull null + } + bindingOfRecord(context, record) { keyIndex -> + WarpForm( + addReference(reference, context.convertDeltas(space, payloads[keyIndex].controlPoints)), + opacity = referenceOpacity + payloads[keyIndex].opacity, + multiplyColor = addColorDelta(referenceMultiply, payloads[keyIndex].multiplyColor), + screenColor = addColorDelta(referenceScreen, payloads[keyIndex].screenColor), + ) + } + } +} + +/** + * Maps [records] onto [rotation] as affine blend bindings: origin/angle/scale delta rows plus + * the grid-at-default reference. The scale delta carries the same px→model seam factor as + * the grid keyforms; flips are not blendable, so the FLIP tracks' value at the default pose + * fills the form. The deformer's own opacity/color rows get the same reference treatment as + * the geometry and CASCADE onto every drawable underneath (see `DeformerCascade`). + * + * @param Moc3ImportContext context The import's derived state. + * @param Deformer.Rotation rotation The constructed runtime rotation (reference source). + * @param PointSpace space The rotation's stored point space. + * @param Float scaleFactor The px→model seam factor (1 under a rotation ancestor, else ppu). + * @param List records The rotation's records. + * @return List> The runtime bindings. + */ +internal fun rotationBlendShapesOf( + context: Moc3ImportContext, + rotation: Deformer.Rotation, + space: PointSpace, + scaleFactor: Float, + records: List, +): List> { + val defaultValue: (ParameterId) -> Float = context::defaultValueOf + // The fallback mirrors rotationBlendDeltas' (identity transform, scale 1) so the + // evaluator's subtraction cancels exactly even for an unkeyed rotation. + val reference = + rotationFormAt(rotation.geometryGrid, defaultValue) + ?: RotationPivotForm(0f, 0f, 0f, 1f) + val referenceOpacity = rotation.channelGrids.scalarAt(FormChannel.OPACITY, rotation.opacity, defaultValue) + val referenceMultiply = + rotation.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, rotation.multiplyColor, defaultValue) + val referenceScreen = + rotation.channelGrids.colorAt(FormChannel.SCREEN_COLOR, rotation.screenColor, defaultValue) + return records.mapNotNull { record -> + val payloads = + record.keyforms.map { keyform -> + (keyform as? BlendShapeKeyform.Rotation)?.form ?: return@mapNotNull null + } + if (payloads.size != record.keyPositions.size) { + return@mapNotNull null + } + bindingOfRecord(context, record) { keyIndex -> + val originDelta = + context.convertDeltas(space, floatArrayOf(payloads[keyIndex].originX, payloads[keyIndex].originY)) + RotationForm( + originX = reference.originX + originDelta[0], + originY = reference.originY + originDelta[1], + angle = reference.angle + payloads[keyIndex].angle, + scale = reference.scale + payloads[keyIndex].scale * scaleFactor, + // The reference pivot carries no flips - reflections are FLAG channels on the deformer, + // and a blend shape never varies them (MOC3 stores no flip delta rows). Sampled from + // the FLIP tracks at the default pose: at this point in the import the statics are still + // their constructor defaults (compaction lifts constant flip tracks only at the end), + // so reading rotation.flipX here would be constant false and drop the reflection. + flipX = rotation.channelGrids.flagAt(FormChannel.FLIP_X, rotation.flipX, defaultValue), + flipY = rotation.channelGrids.flagAt(FormChannel.FLIP_Y, rotation.flipY, defaultValue), + opacity = referenceOpacity + payloads[keyIndex].opacity, + multiplyColor = addColorDelta(referenceMultiply, payloads[keyIndex].multiplyColor), + screenColor = addColorDelta(referenceScreen, payloads[keyIndex].screenColor), + ) + } + } +} + +/** + * Maps [records] onto a part as draw-order blend bindings. + * + * A part's only blendable channel is its draw order, so a record carries a single scalar delta + * per key. It gets the same reference treatment as every other blend payload - the stored delta + * plus the channel's value at the DEFAULT pose - so the evaluator's subtraction cancels exactly. + * + * @param Moc3ImportContext context The import's derived state. + * @param Float staticOrder The part's static draw order. + * @param ChannelGrids channelGrids The part's own keyform tracks (the reference source). + * @param List records The part's records. + * @return List> The runtime bindings. + */ +internal fun partBlendShapesOf( + context: Moc3ImportContext, + staticOrder: Float, + channelGrids: ChannelGrids, + records: List, +): List> { + val defaultValue: (ParameterId) -> Float = context::defaultValueOf + val referenceDrawOrder = channelGrids.scalarAt(FormChannel.DRAW_ORDER, staticOrder, defaultValue) + return records.mapNotNull { record -> + val payloads = + record.keyforms.map { keyform -> + (keyform as? BlendShapeKeyform.Part)?.drawOrderDelta ?: return@mapNotNull null + } + if (payloads.size != record.keyPositions.size) { + return@mapNotNull null + } + bindingOfRecord(context, record) { keyIndex -> + PartForm(drawOrder = referenceDrawOrder + payloads[keyIndex]) + } + } +} + +/** + * Assembles one runtime binding from a record: the moc keys already include the inserted + * neutral, whose form slot imports as null (the stored neutral delta row is all-zero). + * + * @param Moc3ImportContext context The import's derived state, for the parameter id table. + * @param MocBlendShape record The record to map. + * @param Function formAt Builds the synthesized runtime form for a non-neutral key. + * @return BlendShapeBinding The runtime binding. + */ +private fun bindingOfRecord( + context: Moc3ImportContext, + record: MocBlendShape, + formAt: (keyIndex: Int) -> TForm?, +): BlendShapeBinding = + BlendShapeBinding( + parameterId = context.parameterIds.getOrElse(record.parameterIndex) { ParameterId("") }, + keys = record.keyPositions.copyOf(), + neutralIndex = record.neutralKeyIndex, + forms = + record.keyPositions.indices.map { keyIndex -> + if (keyIndex == record.neutralKeyIndex) null else formAt(keyIndex) + }, + limits = blendLimitsOf(context, record), + ) + +/** + * Maps a record's limit curves to the runtime's min-combined [BlendWeightLimit] list. + * + * @param Moc3ImportContext context The import's derived state, for the parameter id table. + * @param MocBlendShape record The record whose limits to map. + * @return List The runtime limit curves. + */ +private fun blendLimitsOf( + context: Moc3ImportContext, + record: MocBlendShape, +): List = + record.limits.map { limit -> + BlendWeightLimit( + parameterId = context.parameterIds.getOrElse(limit.parameterIndex) { ParameterId("") }, + points = + limit.keyPositions.indices.map { pointIndex -> + BlendWeightLimitPoint(limit.keyPositions[pointIndex], limit.weights[pointIndex]) + }, + ) + } + +/** + * Elementwise sum of [reference] and [deltas] (sized like [deltas]; a size-mismatched + * reference contributes only its overlapping prefix, mirroring the evaluator's guards). + * + * @param FloatArray reference The grid-at-default reference components. + * @param FloatArray deltas The converted delta components. + * @return FloatArray The synthesized absolute/rest-relative components. + */ +private fun addReference( + reference: FloatArray, + deltas: FloatArray, +): FloatArray = + FloatArray(deltas.size) { componentIndex -> + deltas[componentIndex] + (reference.getOrNull(componentIndex) ?: 0f) + } + +/** + * Adds a color delta row onto its grid-at-default reference, the color analogue of + * [addReference]. + * + * A blend record's color rows are ADDITIVE, so a zero row is the identity and a null row (a + * model whose color tables are absent entirely, pre-4.2) contributes nothing. Not clamped + * here: the evaluator subtracts this same reference back out and clamps only after summing every + * contribution, so clamping now would bias a record whose neighbors pull the other way. + * + * @param ColorRgb reference The channel's value at the default pose. + * @param Rgb? delta The record's stored delta row, or null when the model has no colors. + * @return ColorRgb The referenced color this key blends toward. + */ +private fun addColorDelta( + reference: ColorRgb, + delta: Rgb?, +): ColorRgb = + if (delta == null) { + reference + } else { + ColorRgb(reference.red + delta.r, reference.green + delta.g, reference.blue + delta.b) + } \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3DeformerImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3DeformerImport.kt new file mode 100644 index 0000000..62da966 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3DeformerImport.kt @@ -0,0 +1,285 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.interop.moc3.rotationScaleFactor +import org.umamo.runtime.keyform.fanOutRotation +import org.umamo.runtime.keyform.fanOutWarp +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.WarpForm + +/** + * Imports every deformer, warps and rotations alike, in file order. + * + * File order is preserved because every cross-reference in a MOC3 - a parent link, an art mesh's owner, + * a blend record's target - is a position in this list, so reordering here would silently repoint all of + * them. + * + * Each deformer's keyform grid is built ONCE as a bundled form and then fanned into its geometry and its + * render tracks, rather than walked twice: the opacity and color tracks CASCADE onto every drawable + * underneath, so a second walk that disagreed with the first about a cell would shift a whole subtree. + * + * @param Moc3ImportContext context The import's derived state. + * @return List The runtime deformers, in file order. + */ +internal fun importDeformers(context: Moc3ImportContext): List { + val mocDocument = context.mocDocument + // A bake stores no deformer display name, so the label is the id - readable, but it says nothing + // about what the deformer moves. Where the answer is unambiguous, the drawable it deforms is + // appended as an anchor: "Warp40 (ArtMesh5)". See [soleDrawableByDeformer] for what counts. + val soleDrawable = soleDrawableByDeformer(mocDocument) + + /** + * The display name of the deformer at [deformerIndex]: its id, plus the drawable it deforms + * when exactly one is in reach. + * + * @param Int deformerIndex The deformer's file index. + * @param DeformerId id The deformer's resolved runtime id. + * @return String The display name. + */ + fun deformerNameOf( + deformerIndex: Int, + id: DeformerId, + ): String { + val anchorIndex = soleDrawable[deformerIndex] ?: return id.raw + val anchorName = mocDocument.artMeshes.getOrNull(anchorIndex)?.id ?: return id.raw + return "${id.raw} ($anchorName)" + } + + return mocDocument.deformers.mapIndexed { deformerIndex, source -> + val id = context.deformerIds[deformerIndex] + val parent = context.deformerIds.getOrNull(source.parentDeformerIndex) + val keyformSpace = context.pointSpaceOf(source.parentDeformerIndex) + val binding = context.bindingOf(source.keyformBindingIndex) + when (source) { + is WarpDeformer -> { + // One bundled grid, then split into lattice geometry and the render tracks that cascade + // down onto every drawable under this deformer. + val fannedWarp = + gridOf(context, binding) { gridIndex -> + source.keyforms.getOrNull(gridIndex)?.let { keyform -> + WarpForm( + context.convertPoints(keyformSpace, keyform.controlPoints), + opacity = keyform.opacity, + multiplyColor = colorRgbOf(keyform.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(keyform.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + }?.fanOutWarp() + val warp = + Deformer.Warp( + id = id, + name = deformerNameOf(deformerIndex, id), + parent = parent, + // MOC3 §5.6 s15: the deformer's own org-tree part; -1 (→ null) at the root. + partId = context.partIds.getOrNull(source.parentPartIndex), + // MOC3 §5.6 s13/s14: the editor's eye toggle and its unpinned partner. + isVisible = source.isVisible, + isEnabled = source.isEnabled, + rows = source.rows, + columns = source.columns, + // MOC3 §5.6 warp mode: 0 = triangle split, non-zero = bilinear (quad). + isQuadTransform = source.mode != 0, + geometryGrid = fannedWarp?.geometry, + channelGrids = fannedWarp?.channels ?: ChannelGrids.Empty, + ) + val warpRecords = context.blendRecordsByTarget[BlendShapeTarget.WARP to deformerIndex].orEmpty() + if (warpRecords.isEmpty()) { + warp + } else { + warp.copy(blendShapes = warpBlendShapesOf(context, warp, keyformSpace, warpRecords)) + } + } + + is RotationDeformer -> { + val scaleFactor = rotationScaleFactor(context.hasRotationAncestor[deformerIndex], context.canvasMapping) + // One bundled grid, then split into the pivot geometry, the render tracks that cascade + // down onto every drawable under this deformer, and the two reflection flags. + val fannedRotation = + gridOf(context, binding) { gridIndex -> + source.keyforms.getOrNull(gridIndex)?.let { keyform -> + val origin = + context.convertPoints(keyformSpace, floatArrayOf(keyform.originX, keyform.originY)) + RotationForm( + originX = origin[0], + originY = origin[1], + angle = keyform.angle, + scale = keyform.scale * scaleFactor, + flipX = keyform.reflectX, + flipY = keyform.reflectY, + opacity = keyform.opacity, + multiplyColor = colorRgbOf(keyform.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(keyform.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + }?.fanOutRotation() + val rotation = + Deformer.Rotation( + id = id, + name = deformerNameOf(deformerIndex, id), + parent = parent, + partId = context.partIds.getOrNull(source.parentPartIndex), + isVisible = source.isVisible, + isEnabled = source.isEnabled, + baseAngle = source.baseAngle, + geometryGrid = fannedRotation?.geometry, + channelGrids = fannedRotation?.channels ?: ChannelGrids.Empty, + ) + val rotationRecords = context.blendRecordsByTarget[BlendShapeTarget.ROTATION to deformerIndex].orEmpty() + if (rotationRecords.isEmpty()) { + rotation + } else { + rotation.copy( + blendShapes = + rotationBlendShapesOf( + context, + rotation, + keyformSpace, + scaleFactor, + rotationRecords, + ), + ) + } + } + } + } +} + +/** + * Infers each deformer's organizational part from the drawables it deforms. A FALLBACK only: MOC3 + * §5.6 s15 carries real deformer→part membership, and this runs solely when that section placed + * nothing at all. + * + * A MOC3 whose s15 is absent or entirely -1 - a stripped or synthesized file, or one that + * genuinely puts every deformer at the root - converts to a flat org tree with an unusable + * parts panel. The two cases are indistinguishable in a bake, and inference is the better + * outcome for both, so this reconstructs the grouping from the one signal that is still + * present: a deformer's drawables almost always live in the deformer's own part. The rule is + * the plurality part of the DIRECTLY deformed drawables, falling back to the whole descendant + * subtree for a deformer that only deforms other deformers. + * + * This is INFERENCE, not recovery. Measured against the corpus twins (each model's + * editor-written CMO3 against its own bake) it reproduced 81-93% of the original placements, + * and a deformer whose drawables span several parts can land in any of them - which is why it + * never overrides s15. A CMO3-origin document never reaches here: it carries the real + * membership on ACParameterControllableSource.parentGuid. + * + * @param List deformers The imported deformers, none of which resolved a part. + * @param List drawables The imported drawables. + * @param Map partByDrawable Each drawable's org-tree part (null at the root). + * @return List The deformers with inferred [Deformer.partId] values. + * @see MOC3.md §5.6 s15 + */ +internal fun inferDeformerParts( + deformers: List, + drawables: List, + partByDrawable: Map, +): List { + val parentById = deformers.associate { deformer -> deformer.id to deformer.parent } + val directParts = HashMap>() + val subtreeParts = HashMap>() + for (drawable in drawables) { + val partId = partByDrawable[drawable.id] ?: continue + val ownerId = drawable.parentDeformerId ?: continue + directParts.getOrPut(ownerId) { ArrayList() }.add(partId) + // Walk the deformer chain so an ancestor that deforms no drawable directly still sees the + // parts below it; the visited set guards a malformed cyclic chain. + var ancestorId: DeformerId? = ownerId + val visited = HashSet() + while (ancestorId != null && visited.add(ancestorId)) { + subtreeParts.getOrPut(ancestorId) { ArrayList() }.add(partId) + ancestorId = parentById[ancestorId] + } + } + + /** + * The plurality part id of a candidate list, or null when empty. + * + * @param List? candidates The observed part ids. + * @return PartId? The most frequent id. + */ + fun plurality(candidates: List?): PartId? = + candidates?.groupingBy { partId -> partId }?.eachCount()?.maxByOrNull { entry -> entry.value }?.key + + return deformers.map { deformer -> + val inferred = plurality(directParts[deformer.id]) ?: plurality(subtreeParts[deformer.id]) + if (inferred == null) { + deformer + } else { + when (deformer) { + is Deformer.Warp -> deformer.copy(partId = inferred) + is Deformer.Rotation -> deformer.copy(partId = inferred) + } + } + } +} + +/** + * The one drawable each deformer deforms, for the deformers where "the one" is unambiguous. + * + * Used only to label a deformer, whose authored name a bake drops. A deformer's own drawables + * decide it when it has any; otherwise its whole descendant subtree does, so a rotation that + * only drives a warp still names the mesh at the bottom of the chain. Either way the answer is + * a CARDINALITY, not a vote: a deformer over several drawables has no single answer and is left + * out, because drawables - unlike parts - are distinct entities rather than a category several + * of them can agree on, so picking a winner would just be naming the deformer after an arbitrary + * one of its meshes. Being an anchor rather than data, an absent entry costs a label, nothing more. + * + * @param MocDocument mocDocument The decoded document (file indices throughout). + * @return Map Deformer file index → its sole drawable's file index, for the unambiguous ones. + */ +private fun soleDrawableByDeformer(mocDocument: MocDocument): Map { + val deformerCount = mocDocument.deformers.size + if (deformerCount == 0) { + return emptyMap() + } + val ambiguous = -1 + val direct = HashMap() + val subtree = HashMap() + + /** + * Records [drawableIndex] against [deformerIndex], marking the slot ambiguous on a second hit. + * + * @param HashMap into The tally to record into. + * @param Int deformerIndex The owning deformer's file index. + * @param Int drawableIndex The drawable's file index. + */ + fun record( + into: HashMap, + deformerIndex: Int, + drawableIndex: Int, + ) { + into[deformerIndex] = if (deformerIndex in into) ambiguous else drawableIndex + } + for ((drawableIndex, artMesh) in mocDocument.artMeshes.withIndex()) { + var ancestorIndex = artMesh.parentDeformerIndex + if (ancestorIndex !in 0 until deformerCount) { + continue + } + record(direct, ancestorIndex, drawableIndex) + // Walk to the root so an ancestor that deforms no drawable directly still sees the meshes + // below it; the visited set guards a malformed cyclic chain. + val visited = HashSet() + while (ancestorIndex in 0 until deformerCount && visited.add(ancestorIndex)) { + record(subtree, ancestorIndex, drawableIndex) + ancestorIndex = mocDocument.deformers[ancestorIndex].parentDeformerIndex + } + } + val resolved = HashMap(deformerCount) + for (deformerIndex in 0 until deformerCount) { + val drawableIndex = direct[deformerIndex] ?: subtree[deformerIndex] ?: continue + if (drawableIndex != ambiguous) { + resolved[deformerIndex] = drawableIndex + } + } + return resolved +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3DrawableImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3DrawableImport.kt new file mode 100644 index 0000000..e8a6868 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3DrawableImport.kt @@ -0,0 +1,146 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.moc.ConstantFlag +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.interop.alphaBlendOfPacked +import org.umamo.interop.colorBlendOfPacked +import org.umamo.runtime.keyform.fanOutMesh +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.MeshForm + +/** + * Imports every art mesh, in file order. + * + * File order is preserved here and re-sorted into panel order only once the render tree has been read, + * because a MOC3 addresses drawables positionally - masks, glues, and render-order leaves are all file + * indices into this list. + * + * The rest mesh comes from the DEFAULT-POSE cell of the drawable's keyform grid, and every cell then + * re-expresses as a delta against it. Which cell is chosen changes `mesh.positions` and every delta + * while leaving evaluated geometry bit-identical - the multilinear blend is base-independent - so no + * evaluation oracle can see this go wrong. `Moc3Cmo3ParityTest` (rest vertices against the CMO3 twin) + * and the export round trip's MESH_POSITIONS are what actually pin it. + * + * @param Moc3ImportContext context The import's derived state. + * @return List The runtime drawables, in file order. + */ +internal fun importDrawables(context: Moc3ImportContext): List = + context.mocDocument.artMeshes.mapIndexed { drawableIndex, source -> + val space = context.pointSpaceOf(source.parentDeformerIndex) + val binding = context.bindingOf(source.keyformBindingIndex) + // MOC3 keyforms are absolute; the default-pose cell serves as the rest mesh and every cell + // re-expresses as a delta against it (the multilinear blend is base-independent, so evaluated + // geometry is unaffected by the choice). + val basePositions = + source.keyforms.getOrNull(defaultCellIndexOf(context, binding))?.let { keyform -> + context.convertPoints(space, keyform.vertexPositions) + } + val mesh = + basePositions?.let { positions -> + DrawableMesh( + positions = positions, + uvs = source.vertexUvs.copyOf(), + // MOC3 §5.6 INDEX_DATA is u16; widen unsigned so meshes past 32767 vertices survive. + indices = IntArray(source.triangleIndices.size) { indexIndex -> source.triangleIndices[indexIndex].toInt() and 0xFFFF }, + ) + } + // One bundled grid, then split into per-vertex deltas and the render channels. + val fannedMesh = + gridOf(context, binding) { gridIndex -> + source.keyforms.getOrNull(gridIndex)?.let { keyform -> + MeshForm( + positionDeltas = + deltaVsBase( + basePositions, + context.convertPoints(space, keyform.vertexPositions), + ), + drawOrder = keyform.drawOrder, + opacity = keyform.opacity, + // MOC3 color-table rows 108-113: the 5.3 per-art-mesh multiply/screen color; null + // (pre-5.3, no color table) falls back to the tint identities. + multiplyColor = colorRgbOf(keyform.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(keyform.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + }?.fanOutMesh() + val drawable = + Drawable( + // Through the context's table, not from source.id: a file carrying the same id twice + // resolves the repeat to a synthesized id there, and building it here instead would + // re-merge the two - masks, part membership, and keyforms landing on one drawable. + id = context.drawableIdsByFileIndex[drawableIndex], + // The MOC3 itself carries no drawable names; only the cdi3 Meshes extension does, so a + // file the official editor wrote falls back to the format id. + name = context.drawableNameById[source.id] ?: source.id, + parentDeformerId = context.deformerIds.getOrNull(source.parentDeformerIndex), + // MOC3 v6 §5.6 s153: a nonzero packed extended blend overrides the legacy 2-bit + // constant-flags field (which then only carries the old-runtime approximation). + blendMode = + if (source.extendedBlend != 0) { + colorBlendOfPacked(source.extendedBlend) + } else { + blendModeOf(source.constantFlags) + }, + alphaBlendMode = alphaBlendOfPacked(source.extendedBlend), + // MOC3 §5.6 MASK_INDEX_DATA: mask sources are drawable file indices. + maskedBy = + source.maskDrawableIndices.toList() + .mapNotNull { maskIndex -> context.drawableIdsByFileIndex.getOrNull(maskIndex) }, + invertMask = source.constantFlags and ConstantFlag.IS_INVERTED_MASK != 0, + // MOC3 §5.5: constant-flags bit 2 is IS_DOUBLE_SIDED; culling is its inverse. + culling = source.constantFlags and ConstantFlag.IS_DOUBLE_SIDED == 0, + // MOC3 §5.6 s37: the editor's eye toggle. A bake normally deletes what is hidden, so + // this is true for almost every imported drawable - but a file exported with hidden + // meshes kept carries the flag, and Umamo's own export always does. + isVisible = source.isVisible, + // Lock IS editor-only authoring state the bake drops, so everything imports unlocked. + isSelectable = true, + // MOC3 §5.6 s41: the atlas page this mesh samples, so a detached model can still say. + texturePage = source.textureIndex, + mesh = mesh, + geometryGrid = fannedMesh?.geometry, + channelGrids = fannedMesh?.channels ?: ChannelGrids.Empty, + ) + val meshRecords = context.blendRecordsByTarget[BlendShapeTarget.ART_MESH to drawableIndex].orEmpty() + if (meshRecords.isEmpty()) { + drawable + } else { + drawable.copy(blendShapes = meshBlendShapesOf(context, drawable, space, meshRecords)) + } + } + +/** + * Maps a moc drawable's constant-flag bitmask to the runtime [BlendMode]. + * + * @param Int constantFlags The [ConstantFlag] bitmask (MOC3 §5.5). + * @return BlendMode The runtime blend mode (defaults to Normal). + */ +private fun blendModeOf(constantFlags: Int): BlendMode = + when { + constantFlags and ConstantFlag.BLEND_ADDITIVE != 0 -> BlendMode.AdditivePremultiplied + constantFlags and ConstantFlag.BLEND_MULTIPLICATIVE != 0 -> BlendMode.MultiplyPremultiplied + else -> BlendMode.Normal + } + +/** + * Per-vertex deltas of [positions] vs [base] (`positions − base`), or a copy of positions when + * there is no size-matching base, so the form is kept absolute rather than dropped (matching + * `Cmo3Import`'s convention). + * + * @param FloatArray? base The rest-mesh positions. + * @param FloatArray positions The keyform's absolute positions. + * @return FloatArray The deltas, or a copy of positions. + */ +private fun deltaVsBase( + base: FloatArray?, + positions: FloatArray, +): FloatArray { + if (base == null || base.size != positions.size) { + return positions.copyOf() + } + return FloatArray(positions.size) { coordIndex -> positions[coordIndex] - base[coordIndex] } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3GlueImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3GlueImport.kt new file mode 100644 index 0000000..ddf7390 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3GlueImport.kt @@ -0,0 +1,56 @@ +package org.umamo.interop.moc3.import + +import org.umamo.runtime.keyform.asChannelTrack +import org.umamo.runtime.keyform.channelGridsOf +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GlueForm +import org.umamo.runtime.model.GluePair + +/** + * Imports every glue whose two meshes both resolve. + * + * @param Moc3ImportContext context The import's derived state. + * @return List The runtime glues, in file order. + */ +internal fun importGlues(context: Moc3ImportContext): List { + val mocDocument = context.mocDocument + return mocDocument.glues.mapNotNull { source -> + val meshA = context.drawableIdsByFileIndex.getOrNull(source.meshAIndex) ?: return@mapNotNull null + val meshB = context.drawableIdsByFileIndex.getOrNull(source.meshBIndex) ?: return@mapNotNull null + // MOC3 §5.6 glue: vertex indices are already mesh-local (no UID indirection, unlike CMO3). + // Pairs whose indices fall outside either mesh are dropped, mirroring Cmo3Import's + // UID-resolution behavior - the glue layout planner indexes vertex arrays directly, so an + // unvalidated index from a malformed moc would throw on the render thread after a + // nominally successful import. + val vertexCountA = mocDocument.artMeshes.getOrNull(source.meshAIndex)?.vertexCount ?: 0 + val vertexCountB = mocDocument.artMeshes.getOrNull(source.meshBIndex)?.vertexCount ?: 0 + val pairs = + source.pairs.mapNotNull { pair -> + if (pair.vertexA in 0 until vertexCountA && pair.vertexB in 0 until vertexCountB) { + GluePair(pair.vertexA, pair.vertexB, pair.weightA, pair.weightB) + } else { + null + } + } + val intensityTrack = + gridOf(context, context.bindingOf(source.keyformBindingIndex)) { gridIndex -> + GlueForm( + source.intensityKeyforms.getOrElse(gridIndex) { + source.intensityKeyforms.lastOrNull() ?: 1f + }, + ) + }?.asChannelTrack { form -> ChannelValue.Scalar(form.intensity) } + // A glue with no keyed intensity welds fully, which is the runtime's long-standing fallback. + Glue( + meshA, + meshB, + pairs, + channelGridsOf(FormChannel.GLUE_INTENSITY to intensityTrack), + intensity = 1f, + // MOC3 §5.6 s90: the authored name, so a round trip does not synthesize a new one. + id = source.id.takeIf { it.isNotEmpty() }, + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3Import.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3Import.kt new file mode 100644 index 0000000..b2e096c --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3Import.kt @@ -0,0 +1,149 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.interop.runtimeTargetOfMocVersion +import org.umamo.runtime.keyform.withChannelsCompacted +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.deriveRenderRoot +import org.umamo.runtime.model.partByDrawable + +/** + * Maps a decoded MOC3 document (`:format`) plus its optional cdi3 display info into the concrete + * [PuppetModel] (`:runtime`) - the baked-runtime counterpart of `Cmo3Import`. + * + * MOC3 references everything by index (list position), so the mapping is a single pass over each + * list with index → id tables built up front. Three format gaps shape the result: + * + * - Coordinate space. MOC3 keyform positions are absolute values in the OWNING OBJECT'S PARENT + * SPACE, and every parent space but the root matches the runtime's convention VERBATIM (verified + * value-for-value against the CMO3 corpus twin): normalized lattice (u, v) under a warp parent and + * the pixel-scale local frame under a rotation parent, angles in degrees with the same sign. Only + * the root space differs - the MOC stores model units around CanvasInfo's origin, same Y-down + * orientation - so root-space values map through the affine canvas = origin + ppu·model (see + * [Moc3ImportContext.pointSpaceOf]). The one unit seam: a rotation parented to the root or a warp + * carries the px→model factor in its keyform scale, so those scales multiply by ppu to land in the + * runtime's pixel world; rotation-parented rotations keep their scale verbatim. One caveat: the + * runtime's rest mesh (Drawable.mesh.positions) is canvas-space EDITING geometry in the CMO3 + * convention, which a MOC does not store - this import leaves the rest mesh in parent space (exact + * for evaluation, since the base cancels out of the keyform blend), and `:render`'s + * restMeshesToCanvasSpace finishes the job by evaluating the default pose (the document loader + * applies it). + * - Names. The binary stores ids (deformers included, §5.6 s11) but no display names; parameter/part + * names come from cdi3.json when present, and everything else falls back to the format id - the same + * rule `Cmo3Import` uses for an unnamed source. A deformer's authored label is lost for good (the + * bake drops it and cdi3 carries no deformer entries), so its name is the id, plus the drawable it + * deforms when exactly one is in reach: "Warp40 (ArtMesh5)". + * - Blend shapes. MOC3 records store per-key DELTAS relative to the object's grid form at the + * DEFAULT pose (MOC3.md §5.6), while the runtime `BlendShapeBinding` keeps grid-convention + * forms (MeshForm rest-relative; Warp/RotationForm absolute) and the evaluator re-subtracts + * that same grid-at-default reference. The mapping therefore ADDS the reference back when + * synthesizing each form - computed with the shared org.umamo.runtime.eval sampling helpers, + * the exact functions the evaluator later calls, so the round trip cancels to ULP. Delta + * geometry converts like the grid keyforms minus the origin term (a delta in root space scales + * by ppu only; lattice/rotation-local deltas pass through; the rotation-scale ppu seam applies + * to scale deltas too). Neutral form slots import as null (the stored neutral row is all-zero). + * PART-owned records carry only a draw-order delta (a part has no other blendable channel) and + * ingest onto [org.umamo.runtime.model.Part.blendShapes]. Offscreens ingest into + * [org.umamo.runtime.model.PartComposite] per owner part (packed blend int, flags, mask indices) + * - the part's group mode becomes Isolated - with the keyformed opacity/color channels merged + * into the part's `PartForm` grid (they ride the same cells, MOC3 §5.6). + * + * This object is only the orchestrator. The work sits in per-concern producers beside it - + * [importParameters], [importParameterLinks], [importParameterTree], [importDeformers], + * [importDrawables], [importGlues], [importRenderRoot], and [importParts] - over one immutable + * [Moc3ImportContext]. There is no mutable collaborator to pass alongside it, unlike the export's + * keyform pool and notice sink: an import reports nothing and interns nothing, so a producer's whole + * input is the context. + * + * @see MOC3.md §5 + */ +object Moc3Import { + /** + * Builds a [PuppetModel] from a decoded [MocDocument] (e.g. from `Moc3.read(bytes)`). + * + * @param MocDocument mocDocument The decoded semantic model. + * @param Cdi3Json? displayInfo The sibling cdi3.json (display names, parameter groups, combined + * parameters), or null to fall back to raw format ids everywhere. + * @param Boolean compactChannels Whether to run the post-import channel compaction (on by default); + * see Cmo3Import.fromModelSource. + * @return PuppetModel The concrete runtime puppet. + */ + fun fromMocDocument( + mocDocument: MocDocument, + displayInfo: Cdi3Json?, + compactChannels: Boolean = true, + ): PuppetModel { + val context = Moc3ImportContext(mocDocument, displayInfo) + + val parameters = importParameters(context) + val parameterLinks = importParameterLinks(context) + val parameterTree = importParameterTree(context) + val deformers = importDeformers(context) + val drawables = importDrawables(context) + val glues = importGlues(context) + + // THE ordering contract of this import. Panel order - the parts panel's stacking - is not stored + // in a moc at all; it is RECONSTRUCTED from the render tree, and both the org tree's child sort + // and the flat drawable order below read that reconstruction. Running the org tree first throws + // nothing: every panel index would simply be absent, which yields a different and entirely + // plausible ordering. Moc3ImportOrderTest is what makes that visible. + val renderRoot = importRenderRoot(context) + val panelIndexByDrawable = panelIndexesFrom(renderRoot) + val importedParts = importParts(context, panelIndexByDrawable) + + // The flat drawables list is kept back-to-front (the storage/base order, mirroring Cmo3Import's + // panel-derived ordering); unplaced drawables keep file order at the back. + val orderedDrawables = + drawables.sortedByDescending { drawable -> panelIndexByDrawable[drawable.id] ?: Int.MAX_VALUE } + + val model = + PuppetModel( + parameters = parameters, + parts = importedParts.records, + deformers = deformers, + drawables = orderedDrawables, + rootChildren = importedParts.rootChildren, + // MOC3 has no synthetic root part; entities at the root simply carry parentPartIndex -1. + rootPartId = null, + glues = glues, + parameterLinks = parameterLinks, + parameterTree = parameterTree, + // MOC3 §5.3 CanvasInfo: width/height are the canvas size in pixels; the world origin is the + // canvas-space origin with Y negated into world space (same convention as Cmo3Import). + canvasWidth = context.canvas?.width ?: 0f, + canvasHeight = context.canvas?.height ?: 0f, + worldOriginX = context.canvasOriginX, + worldOriginZ = -context.canvasOriginY, + // Retained purely so an export can invert this import's space conversions; the evaluator and + // the renderer never read it. The CANVAS's own value, not the 1f identity that + // Moc3ImportContext.canvasMapping substitutes for a canvas-less model - an export has to be + // able to tell "this moc baked at 1" from "this document never had a bake scale" and pick + // its own default for the second. + pixelsPerUnit = context.canvas?.pixelsPerUnit, + // MOC3 §3 Version Gating: the version byte is a hard fact of the baked file, so the import + // starts at the matching Cubism target rather than NoTarget. + runtimeTarget = runtimeTargetOfMocVersion(mocDocument.version), + ) + // Three post-passes, and their order is load-bearing in one place: compaction runs LAST, after the + // render-root fallback, because deriveRenderRoot reads the channel tracks that compaction lifts + // into statics. + // + // Section 15 is authoritative when it places anything. When it places NOTHING - a stripped or + // synthesized MOC3 that omits or zeroes the section, which MocDecoder reads defensively for - the + // org tree would be a flat root, so fall back to inferring membership from the drawables. + val withDeformerParts = + if (deformers.isNotEmpty() && deformers.all { deformer -> deformer.partId == null }) { + model.copy(deformers = inferDeformerParts(deformers, orderedDrawables, model.partByDrawable())) + } else { + model + } + val withRenderRoot = + if (renderRoot != null) { + withDeformerParts.copy(renderRoot = renderRoot) + } else { + withDeformerParts.copy(renderRoot = withDeformerParts.deriveRenderRoot()) + } + return if (compactChannels) withRenderRoot.withChannelsCompacted() else withRenderRoot + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3ImportContext.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3ImportContext.kt new file mode 100644 index 0000000..a40ddab --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3ImportContext.kt @@ -0,0 +1,281 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.format.moc3.moc.CanvasInfo +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.format.moc3.model.Offscreen +import org.umamo.format.moc3.model.Rgb +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.interop.moc3.MocCanvasMapping +import org.umamo.interop.moc3.PointSpace +import org.umamo.interop.moc3.convertDeltasToRuntime +import org.umamo.interop.moc3.convertPointsToRuntime +import org.umamo.interop.moc3.rotationAncestorFlags +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.format.moc3.model.BlendShape as MocBlendShape + +/** + * Everything the import producers derive from a document before any of them builds a runtime object. + * + * Immutable, and with no mutable collaborator alongside it - unlike the export, which passes a keyform + * pool and a notice sink beside its context because a producer mutates both. An import reports nothing + * and interns nothing, so a producer's only input is this. + * + * What lives here is what MORE THAN ONE producer needs and what they must not disagree about: the file + * index to runtime id tables that every cross-reference resolves through, the canvas mapping every + * coordinate conversion goes through, and the blend records keyed the way each target kind looks them up. + * Deriving any of it twice is how two producers come to hold different answers. + * + * @see MOC3.md §5.6 + */ +internal class Moc3ImportContext( + val mocDocument: MocDocument, + val displayInfo: Cdi3Json?, +) { + /** + * The document's canvas record, or null on a canvas-less model. + * + * MOC3 §5.3 CanvasInfo: pixelsPerUnit + origin place stored model space onto the canvas as a plain + * affine, same Y-down orientation: canvasX = originX + ppu·modelX, canvasY = originY + ppu·modelY + * (corpus-verified against the CMO3 twin; the Umamo C++ runtime's Y-up presentation happens at eval + * time, not in the stored tables). A canvas-less model keeps the identity mapping so import still + * succeeds (degenerate, like CMO3's 0×0 default). + */ + val canvas: CanvasInfo? = mocDocument.canvas + + /** The canvas origin's x in canvas space. */ + val canvasOriginX: Float = canvas?.originX ?: 0f + + /** The canvas origin's y in canvas space, before the negation into world space. */ + val canvasOriginY: Float = canvas?.originY ?: 0f + + /** The px↔model mapping every geometry conversion goes through. */ + val canvasMapping: MocCanvasMapping = MocCanvasMapping(canvas?.pixelsPerUnit ?: 1f, canvasOriginX, canvasOriginY) + + /** cdi3 parameter id → display label. */ + val parameterNameById: Map = displayInfo?.parameters?.associate { it.id to it.name } ?: emptyMap() + + /** cdi3 part id → display label. */ + val partNameById: Map = displayInfo?.parts?.associate { it.id to it.name } ?: emptyMap() + + /** cdi3 drawable id → display label; the Umamo extension, since a moc alone cannot carry these. */ + val drawableNameById: Map = displayInfo?.drawables?.associate { it.id to it.name } ?: emptyMap() + + /** + * Parameter file index → runtime id, with blank and duplicate slots synthesized. + * + * This and the three tables below are all in FILE order, because every cross-reference in a MOC3 is + * a file-order index - and all four are DE-DUPLICATED, because the runtime addresses by id instead. + * A moc names nothing by id, so nothing in the format stops two records from carrying the same one; + * Umamo's own export can even mint the pair, since an id too wide for the 64-byte record is written + * shortened. Mapping both records onto one runtime id would merge the two objects - one drawable's + * masks, part membership, and keyforms landing on the other - so the first claimant keeps the file's + * id and every later one falls back to a synthesized id. + */ + val parameterIds: List = + distinctIdsOf(mocDocument.parameters.map { parameter -> parameter.id }, "Parameter").map(::ParameterId) + + /** Part file index → runtime id, with blank and duplicate slots synthesized. */ + val partIds: List = + distinctIdsOf(mocDocument.parts.map { part -> part.id }, "Part").map(::PartId) + + /** Drawable file index → runtime id, with blank and duplicate slots synthesized. */ + val drawableIdsByFileIndex: List = + distinctIdsOf(mocDocument.artMeshes.map { artMesh -> artMesh.id }, "ArtMesh").map(::DrawableId) + + /** + * Deformer file index → runtime id, with blank and duplicate slots synthesized. + * + * MOC3 §5.6 s11 carries the editor's own identifiers, the same ones the CMO3 side carries, so a + * MOC3-origin export writes back the ids the model was authored with. A blank slot - a hand-built + * document, or a MOC3 written without s11 - is the case this table reaches most often; the other + * three are blank only in a malformed file. + */ + val deformerIds: List = + distinctIdsOf(mocDocument.deformers.map { deformer -> deformer.id }, "Deformer").map(::DeformerId) + + /** + * Per deformer file index, whether a rotation ancestor already applied the px→model factor. + * + * The px→model unit seam; see `Moc3SpaceSeam` for why only the first rotation on a path carries it. + */ + val hasRotationAncestor: BooleanArray = + rotationAncestorFlags( + mocDocument.deformers.size, + { index -> mocDocument.deformers[index].parentDeformerIndex }, + { index -> mocDocument.deformers[index] is RotationDeformer }, + ) + + /** + * Blend records (MOC3 v4+ §5.6) pre-indexed per target object. + * + * `targetIndex` is a deformer index for WARP/ROTATION (already remapped by the decoder), a drawable + * file index for ART_MESH, and a part file index for PART - which is why the key carries the target + * kind alongside the number. + */ + val blendRecordsByTarget: Map, List> = + mocDocument.blendShapes.groupBy { record -> record.target to record.targetIndex } + + // Keyed by the DE-DUPLICATED id, never by the raw file id: on a document carrying the same parameter + // id twice, a raw-keyed map keeps only the last, so the first parameter's blend records would read + // the second's default. Keying by parameterIds makes this lookup and the index-addressed one below + // two views of the same table rather than two answers. + private val defaultValueById: Map = + parameterIds.withIndex().associate { (parameterIndex, parameterId) -> + parameterId to mocDocument.parameters[parameterIndex].defaultValue + } + + /** + * The default value of the parameter at [parameterIndex], as a keyform axis names it. + * + * @param Int parameterIndex The parameter's file index. + * @return Float The default, or 0 when the index names nothing. + */ + fun defaultValueAt(parameterIndex: Int): Float = mocDocument.parameters.getOrNull(parameterIndex)?.defaultValue ?: 0f + + /** + * The default value of [parameterId], as a blend record's driving parameter names it. + * + * @param ParameterId parameterId The parameter's runtime id. + * @return Float The default, or 0 when the id names nothing. + */ + fun defaultValueOf(parameterId: ParameterId): Float = defaultValueById[parameterId] ?: 0f + + /** + * Offscreen records by their owner part's FILE INDEX. + * + * MOC3 v6 §5.6 s155: each offscreen names its owner part by index, and both the part import and the + * render-order import need to look one up from a part they already hold - so the relation is + * inverted once here rather than scanned per part. Keyed by the index the record itself stores, + * not by the owner's id: two parts carrying the same id would otherwise both read whichever + * offscreen came last, isolating a part the file never isolated. + */ + val offscreenByPartIndex: Map = + mocDocument.offscreens + .filter { offscreen -> offscreen.ownerPartIndex in mocDocument.parts.indices } + .associateBy { offscreen -> offscreen.ownerPartIndex } + + /** + * Resolves the keyform binding for [bindingIndex], or null when the document carries none. + * + * @param Int bindingIndex A `keyformBindingIndex` from a moc object. + * @return KeyformBinding? The binding (a static object resolves to a zero-axis binding). + */ + fun bindingOf(bindingIndex: Int): KeyformBinding? = mocDocument.keyformBinding(bindingIndex) + + /** + * The coordinate space a child object of [parentDeformerIndex] stores its positions in. Any + * unresolvable index (negative OR out of range) is root space - the same normalization the id + * mapping applies via deformerIds.getOrNull, so a malformed parent index cannot leave an object + * treated as root-parented but converted as rotation-local. + * + * @param Int parentDeformerIndex The owning object's parent deformer index (-1 at the root). + * @return PointSpace The stored space. + */ + fun pointSpaceOf(parentDeformerIndex: Int): PointSpace = + when (mocDocument.deformers.getOrNull(parentDeformerIndex)) { + is WarpDeformer -> PointSpace.WarpLattice + is RotationDeformer -> PointSpace.RotationLocal + null -> PointSpace.ModelRoot + } + + /** + * Converts interleaved x,y [points] from the moc's stored [space] to the runtime's convention + * (CMO3 canvas pixels at the root; parent-local elsewhere). Warp-lattice and rotation-local + * values are stored in the runtime's own convention already (corpus-verified) and pass through + * untouched; only root-space values map through CanvasInfo's affine. + * + * @param PointSpace space The stored space (from [pointSpaceOf]). + * @param FloatArray points Interleaved x,y positions as stored in the moc. + * @return FloatArray The converted positions (always a fresh array). + */ + fun convertPoints( + space: PointSpace, + points: FloatArray, + ): FloatArray = convertPointsToRuntime(space, points, canvasMapping) + + /** + * Converts interleaved delta components from the moc's stored [space] to the runtime's + * convention. Unlike [convertPoints] the canvas ORIGIN does not apply - it cancels out of a + * difference - so a root-space delta scales by ppu only; the other spaces pass through. + * + * @param PointSpace space The stored space (from [pointSpaceOf]). + * @param FloatArray deltas Interleaved x,y deltas as stored in the moc. + * @return FloatArray The converted deltas (always a fresh array). + */ + fun convertDeltas( + space: PointSpace, + deltas: FloatArray, + ): FloatArray = convertDeltasToRuntime(space, deltas, canvasMapping) +} + +/** + * Converts a decoded moc3 [Rgb] to the runtime [ColorRgb]. + * + * Lives beside the context rather than with any one producer because the deformer, drawable, and part + * imports all read the same two color rows off their keyforms, and a second conversion is how one of + * them would come to disagree about what an absent row means. + * + * @param Rgb? color The decoded color row (MOC3 color tables 108-113), or null when absent. + * @return ColorRgb? The runtime color, or null so the caller can apply its own channel identity. + */ +internal fun colorRgbOf(color: Rgb?): ColorRgb? = color?.let { ColorRgb(it.r, it.g, it.b) } + +/** + * Maps one section's file ids onto distinct runtime ids, in file order. + * + * The first record to carry a given id keeps it verbatim; a blank or repeated one falls back to a + * synthesized id. A file id always outranks a synthesized one, even when the synthesizer would have + * wanted it first - every file id is claimed before the walk starts - so what the file says survives + * and only what it leaves ambiguous is invented. + * + * @param List fileIds The section's ids, in file order. + * @param String fallbackPrefix The stem a synthesized id is built from ("Deformer", "Part", …). + * @return List One distinct id per file index. + */ +private fun distinctIdsOf( + fileIds: List, + fallbackPrefix: String, +): List { + val claimedIds = fileIds.filterTo(HashSet()) { fileId -> fileId.isNotEmpty() } + val usedIds = HashSet() + return fileIds.mapIndexed { fileIndex, fileId -> + if (fileId.isNotEmpty() && usedIds.add(fileId)) { + fileId + } else { + synthesizedId(fallbackPrefix, fileIndex, claimedIds) + } + } +} + +/** + * Synthesizes an id for a slot the file leaves blank (or duplicates). + * + * The result joins [claimedIds], so it collides neither with an id the file already uses nor with + * another synthesized one. + * + * @param String fallbackPrefix The stem to build from. + * @param Int fileIndex The record's file index. + * @param MutableSet claimedIds Every id already spoken for; the returned id is added to it. + * @return String The synthesized id. + */ +private fun synthesizedId( + fallbackPrefix: String, + fileIndex: Int, + claimedIds: MutableSet, +): String { + var candidate = "$fallbackPrefix$fileIndex" + var disambiguator = 2 + while (!claimedIds.add(candidate)) { + candidate = "$fallbackPrefix$fileIndex-$disambiguator" + disambiguator++ + } + return candidate +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3KeyformImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3KeyformImport.kt new file mode 100644 index 0000000..29d8796 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3KeyformImport.kt @@ -0,0 +1,90 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import kotlin.math.abs + +/* + * The keyform grid seam, shared by every object kind the import builds: deformers, drawables, glues, and + * parts all resolve a binding index into a grid the same way, and a second implementation of the stride + * folding would put two objects on the same axes at different cell coordinates. + */ + +/** + * Builds a runtime keyform grid over [binding], one cell per grid index. + * + * A static object (a zero-axis binding) becomes a zero-axis single-cell grid, which the evaluator + * resolves to a single full-weight corner - keeping the baked draw order/opacity that a null grid would + * lose. + * + * @param Moc3ImportContext context The import's derived state, for the parameter id table. + * @param KeyformBinding? binding The object's keyform binding. + * @param Function formAt The typed form payload at a grid index, or null to skip the cell. + * @return KeyformGrid? The grid, or null when there is no binding. + */ +internal fun gridOf( + context: Moc3ImportContext, + binding: KeyformBinding?, + formAt: (gridIndex: Int) -> TForm?, +): KeyformGrid? { + if (binding == null) { + return null + } + // MOC3 §5.6: axes are in stride order (first = fastest varying), matching the runtime grid's + // stride folding, so keyIndices(gridIndex) is the cell coordinate as-is. + val axes = + binding.axes.map { axis -> + KeyformAxis( + parameterId = context.parameterIds.getOrElse(axis.parameterIndex) { ParameterId("") }, + keys = axis.keyPositions.copyOf(), + ) + } + val cells = + (0 until binding.gridSize).mapNotNull { gridIndex -> + formAt(gridIndex)?.let { form -> KeyformCell(binding.keyIndices(gridIndex), form) } + } + return KeyformGrid(axes, cells) +} + +/** + * The grid index of the default-pose cell of [binding]: per axis, the key nearest the driving + * parameter's default value, stride-folded. + * + * This cell's baked values serve as the editor's rest state (rest mesh, static draw order); the + * multilinear blend is base-independent, so the choice never changes evaluated output - which is also + * why no evaluation oracle can see it go wrong. + * + * Resolves the default by parameter INDEX, not by id. [Moc3ImportContext.defaultValueOf] answers the + * same question keyed by id for the blend-shape pass, and on a document carrying one parameter id twice + * the two disagree; an axis names its parameter positionally, so this is the accessor that matches what + * the file said. + * + * @param Moc3ImportContext context The import's derived state, for the parameter defaults. + * @param KeyformBinding? binding The object's keyform binding, or null for a static object. + * @return Int The default-pose grid index (0 when static or axis data is degenerate). + */ +internal fun defaultCellIndexOf( + context: Moc3ImportContext, + binding: KeyformBinding?, +): Int { + if (binding == null) { + return 0 + } + var linearIndex = 0 + var stride = 1 + for (axis in binding.axes) { + val defaultValue = context.defaultValueAt(axis.parameterIndex) + var nearestKey = 0 + for (keyIndex in axis.keyPositions.indices) { + if (abs(axis.keyPositions[keyIndex] - defaultValue) < abs(axis.keyPositions[nearestKey] - defaultValue)) { + nearestKey = keyIndex + } + } + linearIndex += nearestKey * stride + stride *= axis.keyCount + } + return linearIndex +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3ParameterImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3ParameterImport.kt new file mode 100644 index 0000000..3926123 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3ParameterImport.kt @@ -0,0 +1,121 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode + +/** + * Imports the parameter axes, in file order. + * + * File order is the addressing every keyform axis and every blend record uses to name its driving + * parameter, so this list is not reordered. + * + * @param Moc3ImportContext context The import's derived state. + * @return List The runtime parameters, in file order. + */ +internal fun importParameters(context: Moc3ImportContext): List = + context.mocDocument.parameters.mapIndexed { parameterIndex, source -> + Parameter( + // Through the context's table, not from source.id: a file carrying the same id twice resolves + // the repeat to a synthesized id there, and building it here instead would re-merge the two. + id = context.parameterIds[parameterIndex], + // cdi3: DisplayParameter.name is the display label; fall back to the id (ParamAngleX). + name = context.parameterNameById[source.id] ?: source.id, + min = source.minimumValue, + max = source.maximumValue, + default = source.defaultValue, + // MOC3 v4+ section 114 Parameter types (null on moc < 4 = all normal). + kind = if (source.type == ParameterType.BLEND_SHAPE) ParameterKind.BLEND_SHAPE else ParameterKind.NORMAL, + // MOC3 §5.5 s54: wrap rather than clamp at the limits. + repeat = source.repeats, + ) + } + +/** + * Imports the LINKED ("combined") parameter pairs that cdi3 records - the editor's 2D pads. + * + * @param Moc3ImportContext context The import's derived state. + * @return List The pairs, empty without cdi3. + */ +internal fun importParameterLinks(context: Moc3ImportContext): List { + val knownParameterIds = context.parameterIds.toSet() + // cdi3: CombinedParameters is an array of [horizontal, vertical] id pairs - the editor's LINKED + // parameter pads. Entries that are not a 2-pair or name an unknown parameter are skipped. + return context.displayInfo?.combinedParameters.orEmpty().mapNotNull { pair -> + val horizontalId = pair.getOrNull(0)?.let(::ParameterId) ?: return@mapNotNull null + val verticalId = pair.getOrNull(1)?.let(::ParameterId) ?: return@mapNotNull null + if (pair.size == 2 && horizontalId in knownParameterIds && verticalId in knownParameterIds) { + ParameterLink(horizontalId, verticalId) + } else { + null + } + } +} + +/** + * Builds the parameter-panel group tree from cdi3 display info. + * + * cdi3 stores two flat lists (parameters and groups, each naming an owning groupId; "" = root), so + * within each group the leaf parameters come first (cdi3 order) followed by sub-groups (cdi3 order) - + * the original interleaving is not recorded in a baked export. Parameters cdi3 never places (or + * placed under an unknown group) are appended at the root so every axis stays reachable in the panel. + * + * @param Moc3ImportContext context The import's derived state. + * @return List The root children (empty when cdi3 is absent). + */ +internal fun importParameterTree(context: Moc3ImportContext): List { + val displayInfo = context.displayInfo ?: return emptyList() + val parameterIds = context.parameterIds + val knownParameterIds = parameterIds.toSet() + val groupsByParent = displayInfo.parameterGroups.groupBy { group -> group.groupId } + val groupIds = displayInfo.parameterGroups.mapTo(HashSet()) { group -> group.id } + val parametersByGroup = + displayInfo.parameters + .filter { parameter -> ParameterId(parameter.id) in knownParameterIds } + .groupBy { parameter -> if (parameter.groupId in groupIds) parameter.groupId else "" } + val visited = HashSet() + + fun childrenOf(ownerGroupId: String): List = + buildList { + for (parameter in parametersByGroup[ownerGroupId].orEmpty()) { + add(ParameterNode.Param(ParameterId(parameter.id))) + } + for (group in groupsByParent[ownerGroupId].orEmpty()) { + if (!visited.add(group.id)) { + continue + } + add( + ParameterNode.Group( + id = ParameterGroupId(group.id), + name = group.name, + // cdi3 records no fold state; open reads better than a wall of collapsed rows. + initiallyOpen = true, + children = childrenOf(group.id), + ), + ) + } + } + + val tree = childrenOf("") + + // Safety net: any moc parameter cdi3 never mentions still gets a root leaf, so the panel tree + // covers every axis (the tree replaces the flat list when non-empty). + val placedParameterIds = + buildSet { + fun walk(nodes: List) { + for (node in nodes) { + when (node) { + is ParameterNode.Param -> add(node.id) + is ParameterNode.Group -> walk(node.children) + } + } + } + walk(tree) + } + val unplaced = parameterIds.filter { parameterId -> parameterId !in placedParameterIds } + return tree + unplaced.map { parameterId -> ParameterNode.Param(parameterId) } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3PartImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3PartImport.kt new file mode 100644 index 0000000..92278fc --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3PartImport.kt @@ -0,0 +1,328 @@ +package org.umamo.interop.moc3.import + +import org.umamo.format.moc3.moc.ConstantFlag +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.interop.alphaBlendOfPacked +import org.umamo.interop.colorBlendOfPacked +import org.umamo.runtime.keyform.asChannelTrack +import org.umamo.runtime.keyform.channelGridsOf +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.PartGroupMode +import org.umamo.format.moc3.model.Part as MocPart + +/** + * The runtime parts and the org tree's top level, which are one result because they are one traversal. + * + * @property List records The runtime parts, in FILE order (the addressing every moc index uses). + * @property List rootChildren The org tree's top level, in panel order. + */ +internal class Moc3ImportedParts( + val records: List, + val rootChildren: List, +) + +/** + * Imports the parts list and the org tree's root children. + * + * Runs AFTER [importRenderRoot] and the panel-index reconstruction it feeds, because MOC3 stores parent + * indices but no interleaved panel order: each parent's sub-parts and drawables are sorted by the panel + * index recovered from the render tree, a part taking the minimum over its descendants, with ties + * keeping file order. Handed an empty [panelIndexByDrawable] this still succeeds and simply produces a + * different, plausible ordering - which is why `Moc3ImportOrderTest` pins the sequence rather than + * leaving it to be noticed. + * + * Malformed parent links are normalized so nothing is dropped from the outliner: an out-of-range parent + * index goes to the root, and every member of a parent cycle is re-parented to the root (breaking the + * cycle's edges keeps the forest acyclic and every part reachable). + * + * @param Moc3ImportContext context The import's derived state. + * @param Map panelIndexByDrawable Reconstructed panel index per drawable. + * @return Moc3ImportedParts The parts (file order) and the root children (panel order). + */ +internal fun importParts( + context: Moc3ImportContext, + panelIndexByDrawable: Map, +): Moc3ImportedParts { + val mocDocument = context.mocDocument + val partIds = context.partIds + val drawableIdsByFileIndex = context.drawableIdsByFileIndex + val partCount = mocDocument.parts.size + val drawOrderGroupPartIndices = drawOrderGroupPartIndices(context) + + // Normalize part parents in two steps: an out-of-range index goes to the root, and any part + // whose ancestor chain never reaches the root (a malformed parent CYCLE - every member + // in-range, so the range check alone misses it) is re-parented to the root too. Without this + // the whole cycle cluster is unreachable from childrenOf(-1), and since both the outliner and + // the renderer's visibility gate walk the org tree from the root, its parts AND drawables + // silently vanish. Re-parenting every cycle member breaks all cycle edges, so the resulting + // forest is acyclic and complete. + val rangedParentIndices = + IntArray(partCount) { partIndex -> + val parentIndex = mocDocument.parts[partIndex].parentPartIndex + if (parentIndex in 0 until partCount && parentIndex != partIndex) parentIndex else -1 + } + + fun reachesRoot(startIndex: Int): Boolean { + var currentIndex = rangedParentIndices[startIndex] + var steps = 0 + while (currentIndex != -1) { + if (steps > partCount) { + return false + } + steps++ + currentIndex = rangedParentIndices[currentIndex] + } + return true + } + + val normalizedParentIndices = + IntArray(partCount) { partIndex -> + if (reachesRoot(partIndex)) rangedParentIndices[partIndex] else -1 + } + + val childPartIndices = HashMap>() + val childDrawableIndices = HashMap>() + mocDocument.parts.forEachIndexed { partIndex, _ -> + childPartIndices.getOrPut(normalizedParentIndices[partIndex], ::mutableListOf).add(partIndex) + } + mocDocument.artMeshes.forEachIndexed { drawableIndex, artMesh -> + val parentIndex = if (artMesh.parentPartIndex in 0 until partCount) artMesh.parentPartIndex else -1 + childDrawableIndices.getOrPut(parentIndex, ::mutableListOf).add(drawableIndex) + } + + // A part's panel index is the minimum over its descendants' reconstructed indices, memoized over + // the parent-index tree. The cache is seeded before recursing so a malformed parent cycle + // terminates instead of overflowing the stack. + val partPanelIndexCache = HashMap() + + fun partPanelIndex(partIndex: Int): Int { + partPanelIndexCache[partIndex]?.let { cachedIndex -> + return cachedIndex + } + partPanelIndexCache[partIndex] = Int.MAX_VALUE + var minimumIndex = Int.MAX_VALUE + for (drawableIndex in childDrawableIndices[partIndex].orEmpty()) { + val panelIndex = panelIndexByDrawable[drawableIdsByFileIndex[drawableIndex]] ?: Int.MAX_VALUE + if (panelIndex < minimumIndex) { + minimumIndex = panelIndex + } + } + for (childPartIndex in childPartIndices[partIndex].orEmpty()) { + val panelIndex = partPanelIndex(childPartIndex) + if (panelIndex < minimumIndex) { + minimumIndex = panelIndex + } + } + partPanelIndexCache[partIndex] = minimumIndex + return minimumIndex + } + + fun childrenOf(parentIndex: Int): List { + data class ChildEntry(val child: OrgChild, val panelIndex: Int) + + val entries = ArrayList() + for (childPartIndex in childPartIndices[parentIndex].orEmpty()) { + entries.add(ChildEntry(OrgChild.Part(partIds[childPartIndex]), partPanelIndex(childPartIndex))) + } + for (drawableIndex in childDrawableIndices[parentIndex].orEmpty()) { + val drawableId = drawableIdsByFileIndex[drawableIndex] + entries.add( + ChildEntry( + OrgChild.Drawable(drawableId), + panelIndexByDrawable[drawableId] ?: Int.MAX_VALUE, + ), + ) + } + return entries.sortedBy { entry -> entry.panelIndex }.map { entry -> entry.child } + } + + val parts = + mocDocument.parts.mapIndexed { partIndex, source -> + // MOC3 (runtime format) only records composite data for offscreen parts, so this is null for + // the rest; the composite is stored latently and applied only while the part is Isolated. + val offscreenComposite = partCompositeOf(context, source, partIndex) + val partChannels = partChannelsOf(context, source, partIndex) + Part( + id = partIds[partIndex], + // cdi3: DisplayPart.name is the display label; fall back to the id. + name = context.partNameById[source.id] ?: source.id, + children = childrenOf(partIndex), + // MOC3 §5.6 s7/s8 carry the part's visibility (both flags, split unpinned). Sketch and + // lock ARE editor-only state the bake drops, so those still default to shown/unlocked. + isVisible = source.isVisible, + isSketch = false, + isSelectable = true, + // An owned offscreen wins over render-order-group membership (an isolated part is + // always grouped; the bake records both). + groupMode = + when { + offscreenComposite != null -> PartGroupMode.Isolated + partIndex in drawOrderGroupPartIndices -> PartGroupMode.Grouped + else -> PartGroupMode.PassThrough + }, + drawOrder = partStaticDrawOrder(context, source), + channelGrids = partChannels, + composite = offscreenComposite ?: PartComposite(), + // MOC3 v5+ §5.6: a part-target blend record, whose only channel is the draw order. + blendShapes = partBlendShapesOfBound(context, source, partIndex, partChannels), + ) + } + return Moc3ImportedParts(parts, childrenOf(-1)) +} + +/** + * The static (default-pose) draw order of a moc part - the sort key of its render-order slot. + * + * @param Moc3ImportContext context The import's derived state. + * @param MocPart source The moc part. + * @return Int The quantized draw order (Cubism default 500 when the part carries no keyforms). + */ +internal fun partStaticDrawOrder( + context: Moc3ImportContext, + source: MocPart, +): Int { + // MOC3: PART_KEYFORM_BINDING 0 means static for parts (a single draw-order value), unlike + // meshes/deformers where 0 is a real binding. + val binding = if (source.keyformBindingIndex > 0) context.bindingOf(source.keyformBindingIndex) else null + val defaultCell = defaultCellIndexOf(context, binding) + val drawOrder = + source.drawOrderKeyforms.getOrElse(defaultCell) { + source.drawOrderKeyforms.firstOrNull() ?: DEFAULT_DRAW_ORDER.toFloat() + } + return (drawOrder + 0.001f).toInt() +} + +/** + * The compositing settings of a moc part, or null when the part owns no offscreen (i.e. its + * group mode is not Isolated). + * + * Takes the part's file index rather than looking the offscreen up by the part's id, for the same + * reason [partBlendShapesOfBound] does: a moc addresses its offscreens by index and nothing guarantees + * the id strings are unique, so two same-named parts would both read whichever record came last. + * + * @param Moc3ImportContext context The import's derived state. + * @param MocPart source The moc part. + * @param Int partIndex The part's file index. + * @return PartComposite? The runtime compositing settings, or null. + */ +internal fun partCompositeOf( + context: Moc3ImportContext, + source: MocPart, + partIndex: Int, +): PartComposite? { + val offscreen = context.offscreenByPartIndex[partIndex] ?: return null + // The first keyform doubles as the static fallback (a static part stores exactly one row). + val staticKeyform = offscreen.keyforms.firstOrNull() + return PartComposite( + // MOC3 v6 §5.6 s157: packed colorMode | (alphaMode shl 8). + blendMode = colorBlendOfPacked(offscreen.blendMode), + alphaBlendMode = alphaBlendOfPacked(offscreen.blendMode), + // MOC3 §5.6: offscreen mask sources are drawable file indices (the MASK_INDEX_DATA prefix). + maskedBy = + offscreen.maskIndices.toList() + .mapNotNull { maskIndex -> context.drawableIdsByFileIndex.getOrNull(maskIndex) }, + // MOC3 v6 §5.6 s156 bit 3: invert clipping mask (same bit position as the drawable flag). + invertMask = offscreen.constantFlags and ConstantFlag.IS_INVERTED_MASK != 0, + opacity = staticKeyform?.opacity ?: 1f, + multiplyColor = colorRgbOf(staticKeyform?.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(staticKeyform?.screenColor) ?: ColorRgb.ScreenIdentity, + ) +} + +/** + * The parameter-driven per-channel tracks of a moc part, empty when the part is static. Carries + * the draw order always; for an isolated part the offscreen's keyformed opacity/color + * channels merge in, riding the same grid cells (MOC3 §5.6: Σ owner grid == CountInfo 36). + * + * @param Moc3ImportContext context The import's derived state. + * @param MocPart source The moc part. + * @param Int partIndex The part's file index, which is how its offscreen names it. + * @return ChannelGrids The part's per-channel tracks, empty when it is unbound. + */ +internal fun partChannelsOf( + context: Moc3ImportContext, + source: MocPart, + partIndex: Int, +): ChannelGrids { + if (source.keyformBindingIndex <= 0) { + return ChannelGrids.Empty + } + val offscreenKeyforms = context.offscreenByPartIndex[partIndex]?.keyforms + val bundled = + gridOf(context, context.bindingOf(source.keyformBindingIndex)) { gridIndex -> + source.drawOrderKeyforms.getOrNull(gridIndex)?.let { drawOrder -> + val offscreenKeyform = offscreenKeyforms?.getOrNull(gridIndex) + PartForm( + drawOrder = drawOrder, + opacity = offscreenKeyform?.opacity ?: 1f, + multiplyColor = colorRgbOf(offscreenKeyform?.multiplyColor) ?: ColorRgb.MultiplyIdentity, + screenColor = colorRgbOf(offscreenKeyform?.screenColor) ?: ColorRgb.ScreenIdentity, + ) + } + } ?: return ChannelGrids.Empty + // Fan the one bundled grid out into per-channel tracks sharing its axes: a pure re-shape, so the + // blended values are bit-identical to what the bundled cell produced. + return channelGridsOf( + FormChannel.DRAW_ORDER to bundled.asChannelTrack { form -> ChannelValue.Scalar(form.drawOrder) }, + FormChannel.OPACITY to bundled.asChannelTrack { form -> ChannelValue.Scalar(form.opacity) }, + FormChannel.MULTIPLY_COLOR to bundled.asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) }, + FormChannel.SCREEN_COLOR to bundled.asChannelTrack { form -> ChannelValue.Color(form.screenColor) }, + ) +} + +/** + * [partBlendShapesOf] with this part's records looked up. + * + * Takes the part's file index rather than searching for it by id. A MOC3 addresses blend records + * by index and nothing guarantees the id strings are unique, so resolving the index from the id + * would give two same-named parts the SAME records - the first part's, applied twice, with the + * second part's own records never read. The caller is iterating by index already. + * + * @param Moc3ImportContext context The import's derived state. + * @param MocPart source The moc part. + * @param Int partIndex The part's file index. + * @param ChannelGrids channelGrids The part's tracks, already built by the caller. + * @return List> The runtime bindings, empty when the part has none. + */ +private fun partBlendShapesOfBound( + context: Moc3ImportContext, + source: MocPart, + partIndex: Int, + channelGrids: ChannelGrids, +): List> { + val records = context.blendRecordsByTarget[BlendShapeTarget.PART to partIndex].orEmpty() + if (records.isEmpty()) { + return emptyList() + } + return partBlendShapesOf(context, partStaticDrawOrder(context, source).toFloat(), channelGrids, records) +} + +/** + * The part file indices the render-order tree names as "Group by Draw Order" groups. + * + * @param Moc3ImportContext context The import's derived state. + * @return Set The grouped parts' file indices. + */ +private fun drawOrderGroupPartIndices(context: Moc3ImportContext): Set = + buildSet { + // The draw-order tree: moc3 stores it explicitly (MOC3 §5.6 render-order groups, group 0 = root), + // so it is taken as the baked authority rather than re-derived from the reconstructed org tree. + // Parts referenced as kind-1 children are the "Group by Draw Order" parts. + for (group in context.mocDocument.renderOrderGroups) { + for (child in group.children) { + if (child.kind == 1) { + add(child.index) + } + } + } + } \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3RenderOrderImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3RenderOrderImport.kt new file mode 100644 index 0000000..3e3797b --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/moc3/import/Moc3RenderOrderImport.kt @@ -0,0 +1,114 @@ +package org.umamo.interop.moc3.import + +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode + +/** + * Builds the runtime render-order tree from the moc's explicit render-order groups (group 0 is the + * root), or null when the document carries none (degenerate; the caller derives from the org tree). + * + * A kind-0 child is a drawable leaf; a kind-1 child is a "Group by Draw Order" part whose sub-group + * record is [org.umamo.format.moc3.model.RenderOrderChild.groupIndex]. A visited set guards a + * malformed cyclic group reference, and drawables the stored tree never places are appended at the + * root (the renderer draws exclusively from this tree, so a missing leaf would never render). + * + * Runs BEFORE the part import, and reads the same part attributes it does - a grouped part's draw + * order, tracks, and composite appear on both its render group and its runtime `Part` - which is why + * those live in `Moc3PartImport` as plain functions over the context rather than being computed here. + * + * @param Moc3ImportContext context The import's derived state. + * @return RenderGroup? The render root, or null when the moc has no render-order groups. + */ +internal fun importRenderRoot(context: Moc3ImportContext): RenderGroup? { + val mocDocument = context.mocDocument + if (mocDocument.renderOrderGroups.isEmpty()) { + return null + } + val visitedGroups = HashSet() + + fun childrenOf(groupIndex: Int): List { + val group = mocDocument.renderOrderGroups.getOrNull(groupIndex) ?: return emptyList() + if (!visitedGroups.add(groupIndex)) { + return emptyList() + } + return group.children.mapNotNull { child -> + when (child.kind) { + // MOC3 §5.6 render-order child kind 0: a drawable leaf. + 0 -> context.drawableIdsByFileIndex.getOrNull(child.index)?.let(::RenderDrawable) + // Kind 1: a draw-order group part; its members live in the referenced sub-group record. + 1 -> { + val part = mocDocument.parts.getOrNull(child.index) ?: return@mapNotNull null + val partId = context.partIds.getOrNull(child.index) ?: return@mapNotNull null + RenderGroup( + partId = partId, + drawOrder = partStaticDrawOrder(context, part), + children = childrenOf(child.groupIndex), + channelGrids = partChannelsOf(context, part, child.index), + composite = partCompositeOf(context, part, child.index), + ) + } + + else -> null + } + } + } + + val root = RenderGroup(null, DEFAULT_DRAW_ORDER, childrenOf(0)) + // Safety net, mirroring deriveRenderRoot's: the renderer draws EXCLUSIVELY from this tree, so + // a drawable the stored groups never place (out-of-range child index, an unknown future child + // kind, or a truncated tree) would silently never render. Append the missing leaves at the + // root, where they sort by their own draw order like any other root-level drawable. + val placedLeaves = ArrayList() + collectRenderLeaves(root, placedLeaves) + val placedDrawableIds = placedLeaves.toHashSet() + val missingLeaves = + context.drawableIdsByFileIndex.filter { drawableId -> drawableId !in placedDrawableIds }.map(::RenderDrawable) + return if (missingLeaves.isEmpty()) { + root + } else { + root.copy(children = root.children + missingLeaves) + } +} + +/** + * Reconstructs each drawable's panel index from [renderRoot]. + * + * Panel order (top = front) is not stored in moc3. Render order is back-to-front, so the REVERSED + * leaf sequence is the panel order. A null root - a document with no render-order groups - yields an + * empty map, and every reader then falls back to file order. + * + * @param RenderGroup? renderRoot The render tree, or null when the moc carried none. + * @return Map Panel index per placed drawable, front-most at 0. + */ +internal fun panelIndexesFrom(renderRoot: RenderGroup?): Map = + buildMap { + if (renderRoot != null) { + val leaves = ArrayList() + collectRenderLeaves(renderRoot, leaves) + leaves.asReversed().forEachIndexed { panelIndex, drawableId -> + if (drawableId !in this) { + put(drawableId, panelIndex) + } + } + } + } + +/** + * Collects a render tree's drawable leaves depth-first into [into] (back-to-front order). + * + * @param RenderNode node The subtree root. + * @param ArrayList into The destination leaf list. + * @return Unit + */ +private fun collectRenderLeaves( + node: RenderNode, + into: ArrayList, +) { + when (node) { + is RenderDrawable -> into.add(node.id) + is RenderGroup -> node.children.forEach { child -> collectRenderLeaves(child, into) } + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaDocumentBridge.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaDocumentBridge.kt new file mode 100644 index 0000000..442cb27 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaDocumentBridge.kt @@ -0,0 +1,97 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.format.uma.textures.UmaTextures +import org.umamo.interop.AtlasPageSet +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel + +/** + * What a reopened document's renderer needs beside its model (docs/format/UMA.md §5.5): the page images its drawables + * sample, or null when the pages derive from the tiles, and every tile's PNG for the document's pixel store. + * + * @property AtlasPageSet? pageSet The imported page images with each drawable's image, or null when the loader + * composes the pages from the tiles (`deriveAtlasTextures`). + * @property Function tilePng Yields a tile's PNG by tile id, or null for a tile the document does not hold. + */ +class UmaDocumentPages( + val pageSet: AtlasPageSet?, + val tilePng: (AtlasTileId) -> ByteArray?, +) + +/** + * The whole-document bridge: a [PuppetModel] with its atlas and linked source art saved into a UMA document's + * puppet, textures, and sources entries, and read back out. + */ +object UmaDocumentBridge { + /** + * [base] with its puppet, textures, and sources entries set from [model], each laid over the entry as read so + * every key this writer does not own survives. + * + * An entry too new for this reader occupies its kind and is carried byte for byte (UMA §3.3). Only an optional + * one leaves the document editable, so a save skips its kind while [model] has nothing to write there - no linked + * source art for the sources entry; no atlas and no stored render pages for the textures entry, whose thumbnail + * goes unwritten with it - and fails once it does. + * + * @param UmaModel base The document to save over: the one the model was opened from, or a new one. + * @param PuppetModel model The model. + * @param UmaPixelSource pixels The pixels the save writes: the tiles' PNGs, what the drawables sample, and the + * thumbnail. + * @return UmaModel The updated document. + * @throws UmaWriteException When the model holds a value the format cannot represent, a pixel entry is missing, + * or the model has content for a kind whose entry is too new to replace. + */ + fun documentOf(base: UmaModel, model: PuppetModel, pixels: UmaPixelSource): UmaModel { + var document = base.withPuppet(UmaPuppetExport.puppetOf(model)) + val textures = UmaTexturesBridge.texturesOf(model) + val texturesHaveContent = textures != UmaTextures() || pixels.renderPages is UmaRenderPagePixels.Stored + if (!base.holdsTooNewEntry(UmaEntryKind.Textures) || texturesHaveContent) { + document = document.withTextures(textures, pixels) + } + if (!base.holdsTooNewEntry(UmaEntryKind.Sources) || model.sources.isNotEmpty()) { + document = document.withSources(UmaSourcesBridge.sourcesOf(model)) + } + return document + } + + /** + * The model [document] describes: the puppet with its atlas and linked source art. + * + * The editor entry is not read here, and that is the whole of the rule: a file with `editor/` stripped loads the + * same model because nothing in the model ever came from it (docs/format/UMA.md § 7). + * + * @param UmaModel document The document. + * @return PuppetModel The model. + * @throws UmaFormatException When the document has no puppet entry this reader can read. + */ + fun modelOf(document: UmaModel): PuppetModel { + val puppet = document.puppet ?: throw UmaFormatException(UmaReadFailure.MissingEntry(UmaEntryKind.Puppet.defaultPath)) + return UmaPuppetImport.modelOf(puppet).copy(atlas = UmaTexturesBridge.atlasOf(document.textures), sources = UmaSourcesBridge.sourcesOf(document.sources)) + } + + /** + * The page images a reopened [document]'s drawables sample, and its tiles' PNGs (UMA §5.5): the stored render + * pages with their map when the document was saved with its imported pages, or no page set when its pages derive + * from the tiles. + * + * @param UmaModel document The document. + * @return UmaDocumentPages The page set and the tile PNGs. + */ + fun pagesOf(document: UmaModel): UmaDocumentPages { + val textures = document.textures + val tilePathById = textures?.tiles.orEmpty().mapNotNull { tile -> tile.path?.let { path -> tile.id to path } }.toMap() + val tilePng: (AtlasTileId) -> ByteArray? = { tileId -> tilePathById[tileId.raw]?.let(document::payloadBytes) } + val pageSet = + textures?.renderPages?.let { renderPages -> + // UMA §5.5: the format layer has already checked every render page's entry is there. + AtlasPageSet(renderPages.pages.map { page -> checkNotNull(document.payloadBytes(page.path)) }, renderPages.drawablePages.orEmpty()) + } + return UmaDocumentPages(pageSet, tilePng) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaEnumTables.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaEnumTables.kt new file mode 100644 index 0000000..36c7d63 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaEnumTables.kt @@ -0,0 +1,221 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.puppet.UmaAlphaBlendMode +import org.umamo.format.uma.puppet.UmaBlendMode +import org.umamo.format.uma.puppet.UmaFormChannel +import org.umamo.format.uma.puppet.UmaGroupMode +import org.umamo.format.uma.puppet.UmaParameterKind +import org.umamo.format.uma.puppet.UmaRuntimeTarget +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.RuntimeTarget + +/* + * The runtime model's enums against the puppet entry's (docs/format/UMA.md §4.1). Every mapping is an + * exhaustive `when` in both directions, so a constant added on either side is a compile error here rather + * than a value that silently fails to round-trip. + */ + +/** + * The file-side spelling of a blend mode. + * + * @return UmaBlendMode The file's value. + */ +internal fun BlendMode.toUma(): UmaBlendMode = + when (this) { + BlendMode.Normal -> UmaBlendMode.Normal + BlendMode.AdditivePremultiplied -> UmaBlendMode.AdditivePremultiplied + BlendMode.MultiplyPremultiplied -> UmaBlendMode.MultiplyPremultiplied + BlendMode.Additive -> UmaBlendMode.Additive + BlendMode.AdditiveGlow -> UmaBlendMode.AdditiveGlow + BlendMode.Darken -> UmaBlendMode.Darken + BlendMode.Multiply -> UmaBlendMode.Multiply + BlendMode.ColorBurn -> UmaBlendMode.ColorBurn + BlendMode.LinearBurn -> UmaBlendMode.LinearBurn + BlendMode.Lighten -> UmaBlendMode.Lighten + BlendMode.Screen -> UmaBlendMode.Screen + BlendMode.ColorDodge -> UmaBlendMode.ColorDodge + BlendMode.Overlay -> UmaBlendMode.Overlay + BlendMode.SoftLight -> UmaBlendMode.SoftLight + BlendMode.HardLight -> UmaBlendMode.HardLight + BlendMode.LinearLight -> UmaBlendMode.LinearLight + BlendMode.Hue -> UmaBlendMode.Hue + BlendMode.Color -> UmaBlendMode.Color + } + +/** + * The runtime blend mode a file value names. + * + * @return BlendMode The runtime value. + */ +internal fun UmaBlendMode.toRuntime(): BlendMode = + when (this) { + UmaBlendMode.Normal -> BlendMode.Normal + UmaBlendMode.AdditivePremultiplied -> BlendMode.AdditivePremultiplied + UmaBlendMode.MultiplyPremultiplied -> BlendMode.MultiplyPremultiplied + UmaBlendMode.Additive -> BlendMode.Additive + UmaBlendMode.AdditiveGlow -> BlendMode.AdditiveGlow + UmaBlendMode.Darken -> BlendMode.Darken + UmaBlendMode.Multiply -> BlendMode.Multiply + UmaBlendMode.ColorBurn -> BlendMode.ColorBurn + UmaBlendMode.LinearBurn -> BlendMode.LinearBurn + UmaBlendMode.Lighten -> BlendMode.Lighten + UmaBlendMode.Screen -> BlendMode.Screen + UmaBlendMode.ColorDodge -> BlendMode.ColorDodge + UmaBlendMode.Overlay -> BlendMode.Overlay + UmaBlendMode.SoftLight -> BlendMode.SoftLight + UmaBlendMode.HardLight -> BlendMode.HardLight + UmaBlendMode.LinearLight -> BlendMode.LinearLight + UmaBlendMode.Hue -> BlendMode.Hue + UmaBlendMode.Color -> BlendMode.Color + } + +/** + * The file-side spelling of an alpha blend mode. + * + * @return UmaAlphaBlendMode The file's value. + */ +internal fun AlphaBlendMode.toUma(): UmaAlphaBlendMode = + when (this) { + AlphaBlendMode.Over -> UmaAlphaBlendMode.Over + AlphaBlendMode.Atop -> UmaAlphaBlendMode.Atop + AlphaBlendMode.Out -> UmaAlphaBlendMode.Out + AlphaBlendMode.Conjoint -> UmaAlphaBlendMode.Conjoint + AlphaBlendMode.Disjoint -> UmaAlphaBlendMode.Disjoint + } + +/** + * The runtime alpha blend mode a file value names. + * + * @return AlphaBlendMode The runtime value. + */ +internal fun UmaAlphaBlendMode.toRuntime(): AlphaBlendMode = + when (this) { + UmaAlphaBlendMode.Over -> AlphaBlendMode.Over + UmaAlphaBlendMode.Atop -> AlphaBlendMode.Atop + UmaAlphaBlendMode.Out -> AlphaBlendMode.Out + UmaAlphaBlendMode.Conjoint -> AlphaBlendMode.Conjoint + UmaAlphaBlendMode.Disjoint -> AlphaBlendMode.Disjoint + } + +/** + * The file-side spelling of a parameter kind. + * + * @return UmaParameterKind The file's value. + */ +internal fun ParameterKind.toUma(): UmaParameterKind = + when (this) { + ParameterKind.NORMAL -> UmaParameterKind.Normal + ParameterKind.BLEND_SHAPE -> UmaParameterKind.BlendShape + } + +/** + * The runtime parameter kind a file value names. + * + * @return ParameterKind The runtime value. + */ +internal fun UmaParameterKind.toRuntime(): ParameterKind = + when (this) { + UmaParameterKind.Normal -> ParameterKind.NORMAL + UmaParameterKind.BlendShape -> ParameterKind.BLEND_SHAPE + } + +/** + * The file-side spelling of a part group mode. + * + * @return UmaGroupMode The file's value. + */ +internal fun PartGroupMode.toUma(): UmaGroupMode = + when (this) { + PartGroupMode.PassThrough -> UmaGroupMode.PassThrough + PartGroupMode.Grouped -> UmaGroupMode.Grouped + PartGroupMode.Isolated -> UmaGroupMode.Isolated + } + +/** + * The runtime part group mode a file value names. + * + * @return PartGroupMode The runtime value. + */ +internal fun UmaGroupMode.toRuntime(): PartGroupMode = + when (this) { + UmaGroupMode.PassThrough -> PartGroupMode.PassThrough + UmaGroupMode.Grouped -> PartGroupMode.Grouped + UmaGroupMode.Isolated -> PartGroupMode.Isolated + } + +/** + * The file-side spelling of a runtime target. + * + * @return UmaRuntimeTarget The file's value. + */ +internal fun RuntimeTarget.toUma(): UmaRuntimeTarget = + when (this) { + RuntimeTarget.NoTarget -> UmaRuntimeTarget.NoTarget + RuntimeTarget.Ayagami -> UmaRuntimeTarget.Ayagami + RuntimeTarget.Cubism30 -> UmaRuntimeTarget.Cubism30 + RuntimeTarget.Cubism33 -> UmaRuntimeTarget.Cubism33 + RuntimeTarget.Cubism40 -> UmaRuntimeTarget.Cubism40 + RuntimeTarget.Cubism42 -> UmaRuntimeTarget.Cubism42 + RuntimeTarget.Cubism50 -> UmaRuntimeTarget.Cubism50 + RuntimeTarget.Cubism53 -> UmaRuntimeTarget.Cubism53 + } + +/** + * The runtime target a file value names. + * + * @return RuntimeTarget The runtime value. + */ +internal fun UmaRuntimeTarget.toRuntime(): RuntimeTarget = + when (this) { + UmaRuntimeTarget.NoTarget -> RuntimeTarget.NoTarget + UmaRuntimeTarget.Ayagami -> RuntimeTarget.Ayagami + UmaRuntimeTarget.Cubism30 -> RuntimeTarget.Cubism30 + UmaRuntimeTarget.Cubism33 -> RuntimeTarget.Cubism33 + UmaRuntimeTarget.Cubism40 -> RuntimeTarget.Cubism40 + UmaRuntimeTarget.Cubism42 -> RuntimeTarget.Cubism42 + UmaRuntimeTarget.Cubism50 -> RuntimeTarget.Cubism50 + UmaRuntimeTarget.Cubism53 -> RuntimeTarget.Cubism53 + } + +/** + * The file-side spelling of a keyform channel. + * + * @return UmaFormChannel The file's value. + */ +internal fun FormChannel.toUma(): UmaFormChannel = + when (this) { + FormChannel.DRAW_ORDER -> UmaFormChannel.DrawOrder + FormChannel.OPACITY -> UmaFormChannel.Opacity + FormChannel.MULTIPLY_COLOR -> UmaFormChannel.MultiplyColor + FormChannel.SCREEN_COLOR -> UmaFormChannel.ScreenColor + FormChannel.FLIP_X -> UmaFormChannel.FlipX + FormChannel.FLIP_Y -> UmaFormChannel.FlipY + FormChannel.GLUE_INTENSITY -> UmaFormChannel.GlueIntensity + } + +/** + * The runtime keyform channel a file value names. + * + * @return FormChannel The runtime value. + */ +internal fun UmaFormChannel.toRuntime(): FormChannel = + when (this) { + UmaFormChannel.DrawOrder -> FormChannel.DRAW_ORDER + UmaFormChannel.Opacity -> FormChannel.OPACITY + UmaFormChannel.MultiplyColor -> FormChannel.MULTIPLY_COLOR + UmaFormChannel.ScreenColor -> FormChannel.SCREEN_COLOR + UmaFormChannel.FlipX -> FormChannel.FLIP_X + UmaFormChannel.FlipY -> FormChannel.FLIP_Y + UmaFormChannel.GlueIntensity -> FormChannel.GLUE_INTENSITY + } + +/** + * The key a channel's track is written under, which failure paths name. + * + * @return String The key. + */ +internal fun UmaFormChannel.wireName(): String = UmaFormChannel.serializer().descriptor.getElementName(ordinal) \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaHashes.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaHashes.kt new file mode 100644 index 0000000..c7c199e --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaHashes.kt @@ -0,0 +1,25 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.sources.UMA_SHA256_PREFIX + +/* + * The hash form the sources entry writes (docs/format/UMA.md §6.4): the model keeps a SHA-256 digest as bare + * lowercase hex, and the file names the algorithm in front of it. + */ + +/** + * The file's form of a model hash. + * + * @param String? digest The digest as bare lowercase hex, or null. + * @return String? The prefixed hash, or null. + */ +internal fun prefixedHashOf(digest: String?): String? = digest?.let { hex -> "$UMA_SHA256_PREFIX$hex" } + +/** + * The model's form of a file hash. The format layer has already refused any other algorithm, so the prefix is + * always there to strip. + * + * @param String? hash The prefixed hash, or null. + * @return String? The bare digest, or null. + */ +internal fun digestOf(hash: String?): String? = hash?.removePrefix(UMA_SHA256_PREFIX) \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaInline.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaInline.kt new file mode 100644 index 0000000..38c9987 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaInline.kt @@ -0,0 +1,24 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.UmaWriteException + +/* + * The checks every domain entry's export shares for values written inline as JSON (docs/format/UMA.md §4.1). + */ + +/** + * [value], refusing a NaN or an infinity, which JSON cannot hold. + * + * @param Float value The value. + * @param String entryPath The entry the value is written to, for the failure. + * @param String path Where the value sits in the entry, for the failure. + * @return Float The value. + * @throws UmaWriteException When the value is not finite. + */ +internal fun finiteInline(value: Float, entryPath: String, path: String): Float { + if (!value.isFinite()) { + // UMA §4.1: JSON has no NaN or infinity. + throw UmaWriteException("$entryPath: $path", "$value cannot be written as JSON") + } + return value +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaPuppetExport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaPuppetExport.kt new file mode 100644 index 0000000..d6865e7 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaPuppetExport.kt @@ -0,0 +1,596 @@ +package org.umamo.interop.uma + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.puppet.UmaAxis +import org.umamo.format.uma.puppet.UmaBlendLimit +import org.umamo.format.uma.puppet.UmaBlendLimitPoint +import org.umamo.format.uma.puppet.UmaChannelCell +import org.umamo.format.uma.puppet.UmaChannelGrid +import org.umamo.format.uma.puppet.UmaDeformer +import org.umamo.format.uma.puppet.UmaDeformerBlendShape +import org.umamo.format.uma.puppet.UmaDeformerCell +import org.umamo.format.uma.puppet.UmaDeformerForm +import org.umamo.format.uma.puppet.UmaDeformerGrid +import org.umamo.format.uma.puppet.UmaDeformerKind +import org.umamo.format.uma.puppet.UmaDrawable +import org.umamo.format.uma.puppet.UmaFormChannel +import org.umamo.format.uma.puppet.UmaGlue +import org.umamo.format.uma.puppet.UmaGluePairs +import org.umamo.format.uma.puppet.UmaMesh +import org.umamo.format.uma.puppet.UmaMeshBlendShape +import org.umamo.format.uma.puppet.UmaMeshCell +import org.umamo.format.uma.puppet.UmaMeshForm +import org.umamo.format.uma.puppet.UmaMeshGrid +import org.umamo.format.uma.puppet.UmaOrgRef +import org.umamo.format.uma.puppet.UmaParameter +import org.umamo.format.uma.puppet.UmaParameterLink +import org.umamo.format.uma.puppet.UmaParameterNode +import org.umamo.format.uma.puppet.UmaPart +import org.umamo.format.uma.puppet.UmaPartBlendShape +import org.umamo.format.uma.puppet.UmaPartComposite +import org.umamo.format.uma.puppet.UmaPartForm +import org.umamo.format.uma.puppet.UmaPuppet +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm + +/** + * Lowers a [PuppetModel] onto the puppet entry's schema (docs/format/UMA.md §4). + * + * A value is left out of the file only when it is bit-for-bit the model's default, so `-0.0` and `0.0` + * stay distinct; every float is checked to be finite first, because JSON cannot hold anything else and a + * silently dropped value would be worse than a refused save. + * + * Bulk arrays (meshes, position deltas, lattice points, glue pairs) are handed over as they are; they travel + * in the entry's buffer, which holds any float bit for bit. Inline floats (axis keys, pivots, channel values, + * form scalars) must be finite. + */ +object UmaPuppetExport { + /** + * The puppet entry for [model]. + * + * @param PuppetModel model The puppet. + * @return UmaPuppet The entry's content. + * @throws UmaWriteException When a float the entry holds is NaN or infinite. + */ + fun puppetOf(model: PuppetModel): UmaPuppet = + UmaPuppet( + canvasWidth = optionalFloat(model.canvasWidth, 0f, "canvasWidth"), + canvasHeight = optionalFloat(model.canvasHeight, 0f, "canvasHeight"), + worldOriginX = optionalFloat(model.worldOriginX, 0f, "worldOriginX"), + worldOriginZ = optionalFloat(model.worldOriginZ, 0f, "worldOriginZ"), + pixelsPerUnit = model.pixelsPerUnit?.let { scale -> finite(scale, "pixelsPerUnit") }, + runtimeTarget = model.runtimeTarget.takeIf { target -> target != RuntimeTarget.NoTarget }?.toUma(), + rendersFromSourceLayers = optionalBoolean(model.rendersFromSourceLayers, false), + parameters = model.parameters.map(::parameterOf).ifEmpty { null }, + parameterLinks = model.parameterLinks.map { link -> UmaParameterLink(link.horizontal.raw, link.vertical.raw) }.ifEmpty { null }, + parameterTree = model.parameterTree.map(::parameterNodeOf).ifEmpty { null }, + rootPart = model.rootPartId?.raw, + rootChildren = model.rootChildren.map(::orgRefOf).ifEmpty { null }, + parts = model.parts.map(::partOf).ifEmpty { null }, + deformers = model.deformers.map(::deformerOf).ifEmpty { null }, + drawables = model.drawables.map(::drawableOf).ifEmpty { null }, + glues = model.glues.map(::glueOf).ifEmpty { null }, + ) + + /** + * UMA §4.3: one parameter. + * + * @param Parameter parameter The parameter. + * @return UmaParameter The record. + */ + private fun parameterOf(parameter: Parameter): UmaParameter { + val path = "parameters[${parameter.id.raw}]" + return UmaParameter( + id = parameter.id.raw, + name = parameter.name, + min = finite(parameter.min, "$path.min"), + max = finite(parameter.max, "$path.max"), + default = finite(parameter.default, "$path.default"), + kind = parameter.kind.takeIf { kind -> kind != ParameterKind.NORMAL }?.toUma(), + repeat = optionalBoolean(parameter.repeat, false), + ) + } + + /** + * UMA §4.3: one parameter-tree node. + * + * @param ParameterNode node The node. + * @return UmaParameterNode The record. + */ + private fun parameterNodeOf(node: ParameterNode): UmaParameterNode = + when (node) { + is ParameterNode.Param -> UmaParameterNode(parameter = node.id.raw) + is ParameterNode.Group -> + UmaParameterNode( + group = node.id.raw, + name = node.name, + initiallyOpen = optionalBoolean(node.initiallyOpen, false), + children = node.children.map(::parameterNodeOf).ifEmpty { null }, + ) + } + + /** + * UMA §4.2: one organizational child. + * + * @param OrgChild child The child. + * @return UmaOrgRef The record. + */ + private fun orgRefOf(child: OrgChild): UmaOrgRef = + when (child) { + is OrgChild.Part -> UmaOrgRef(part = child.id.raw) + is OrgChild.Drawable -> UmaOrgRef(drawable = child.id.raw) + } + + /** + * UMA §4.4: one part. + * + * @param Part part The part. + * @return UmaPart The record. + */ + private fun partOf(part: Part): UmaPart { + val path = "parts[${part.id.raw}]" + return UmaPart( + id = part.id.raw, + name = part.name, + children = part.children.map(::orgRefOf).ifEmpty { null }, + isVisible = optionalBoolean(part.isVisible, true), + isSketch = optionalBoolean(part.isSketch, false), + isSelectable = optionalBoolean(part.isSelectable, true), + groupMode = part.groupMode.takeIf { mode -> mode != PartGroupMode.PassThrough }?.toUma(), + drawOrder = part.drawOrder.takeIf { order -> order != DEFAULT_DRAW_ORDER }, + composite = compositeOf(part.composite, "$path.composite"), + channels = channelsOf(part.channelGrids, path), + blendShapes = part.blendShapes.mapIndexed { bindingIndex, binding -> partBlendShapeOf(binding, "$path.blendShapes[$bindingIndex]") }.ifEmpty { null }, + ) + } + + /** + * UMA §4.4: a part's composite, or null when every setting is at its default. + * + * @param PartComposite composite The composite. + * @param String path The composite's position, for a failure. + * @return UmaPartComposite? The record. + */ + private fun compositeOf(composite: PartComposite, path: String): UmaPartComposite? { + val record = + UmaPartComposite( + blendMode = composite.blendMode.takeIf { mode -> mode != BlendMode.Normal }?.toUma(), + alphaBlendMode = composite.alphaBlendMode.takeIf { mode -> mode != AlphaBlendMode.Over }?.toUma(), + maskedBy = composite.maskedBy.map { id -> id.raw }.ifEmpty { null }, + maskedByParts = composite.maskedByParts.map { id -> id.raw }.ifEmpty { null }, + invertMask = optionalBoolean(composite.invertMask, false), + opacity = optionalFloat(composite.opacity, 1f, "$path.opacity"), + multiplyColor = optionalColor(composite.multiplyColor, ColorRgb.MultiplyIdentity, "$path.multiplyColor"), + screenColor = optionalColor(composite.screenColor, ColorRgb.ScreenIdentity, "$path.screenColor"), + ) + return record.takeIf { candidate -> candidate != UmaPartComposite() } + } + + /** + * UMA §4.5: one deformer. + * + * @param Deformer deformer The deformer. + * @return UmaDeformer The record. + */ + private fun deformerOf(deformer: Deformer): UmaDeformer { + val path = "deformers[${deformer.id.raw}]" + return when (deformer) { + is Deformer.Warp -> + UmaDeformer( + id = deformer.id.raw, + kind = UmaDeformerKind.Warp, + name = deformer.name, + parent = deformer.parent?.raw, + part = deformer.partId?.raw, + isVisible = optionalBoolean(deformer.isVisible, true), + isEnabled = optionalBoolean(deformer.isEnabled, true), + isSelectable = optionalBoolean(deformer.isSelectable, true), + opacity = optionalFloat(deformer.opacity, 1f, "$path.opacity"), + multiplyColor = optionalColor(deformer.multiplyColor, ColorRgb.MultiplyIdentity, "$path.multiplyColor"), + screenColor = optionalColor(deformer.screenColor, ColorRgb.ScreenIdentity, "$path.screenColor"), + rows = deformer.rows, + columns = deformer.columns, + isQuadTransform = deformer.isQuadTransform, + geometry = deformer.geometryGrid?.let { grid -> warpGridOf(grid, "$path.geometry") }, + channels = channelsOf(deformer.channelGrids, path), + blendShapes = deformer.blendShapes.mapIndexed { bindingIndex, binding -> warpBlendShapeOf(binding, "$path.blendShapes[$bindingIndex]") }.ifEmpty { null }, + ) + + is Deformer.Rotation -> + UmaDeformer( + id = deformer.id.raw, + kind = UmaDeformerKind.Rotation, + name = deformer.name, + parent = deformer.parent?.raw, + part = deformer.partId?.raw, + isVisible = optionalBoolean(deformer.isVisible, true), + isEnabled = optionalBoolean(deformer.isEnabled, true), + isSelectable = optionalBoolean(deformer.isSelectable, true), + opacity = optionalFloat(deformer.opacity, 1f, "$path.opacity"), + multiplyColor = optionalColor(deformer.multiplyColor, ColorRgb.MultiplyIdentity, "$path.multiplyColor"), + screenColor = optionalColor(deformer.screenColor, ColorRgb.ScreenIdentity, "$path.screenColor"), + baseAngle = finite(deformer.baseAngle, "$path.baseAngle"), + flipX = optionalBoolean(deformer.flipX, false), + flipY = optionalBoolean(deformer.flipY, false), + geometry = deformer.geometryGrid?.let { grid -> rotationGridOf(grid, "$path.geometry") }, + channels = channelsOf(deformer.channelGrids, path), + blendShapes = deformer.blendShapes.mapIndexed { bindingIndex, binding -> rotationBlendShapeOf(binding, "$path.blendShapes[$bindingIndex]") }.ifEmpty { null }, + ) + } + } + + /** + * UMA §4.6: one drawable's structure. + * + * @param Drawable drawable The drawable. + * @return UmaDrawable The record. + */ + private fun drawableOf(drawable: Drawable): UmaDrawable { + val path = "drawables[${drawable.id.raw}]" + return UmaDrawable( + id = drawable.id.raw, + name = drawable.name, + parentDeformer = drawable.parentDeformerId?.raw, + blendMode = drawable.blendMode.takeIf { mode -> mode != BlendMode.Normal }?.toUma(), + maskedBy = drawable.maskedBy.map { id -> id.raw }.ifEmpty { null }, + invertMask = optionalBoolean(drawable.invertMask, false), + drawOrder = optionalFloat(drawable.drawOrder, DEFAULT_DRAW_ORDER.toFloat(), "$path.drawOrder"), + opacity = optionalFloat(drawable.opacity, 1f, "$path.opacity"), + multiplyColor = optionalColor(drawable.multiplyColor, ColorRgb.MultiplyIdentity, "$path.multiplyColor"), + screenColor = optionalColor(drawable.screenColor, ColorRgb.ScreenIdentity, "$path.screenColor"), + alphaBlendMode = drawable.alphaBlendMode.takeIf { mode -> mode != AlphaBlendMode.Over }?.toUma(), + culling = optionalBoolean(drawable.culling, false), + isVisible = optionalBoolean(drawable.isVisible, true), + isSelectable = optionalBoolean(drawable.isSelectable, true), + textureSource = drawable.textureSourceId?.raw, + texturePage = drawable.texturePage.takeIf { page -> page != -1 }, + atlasTile = drawable.atlasTileId?.raw, + mesh = drawable.mesh?.let { mesh -> UmaMesh(mesh.positions, mesh.uvs, mesh.indices) }, + geometry = drawable.geometryGrid?.let { grid -> meshGridOf(grid, "$path.geometry") }, + channels = channelsOf(drawable.channelGrids, path), + blendShapes = drawable.blendShapes.mapIndexed { bindingIndex, binding -> meshBlendShapeOf(binding, "$path.blendShapes[$bindingIndex]") }.ifEmpty { null }, + ) + } + + /** + * UMA §4.14: one glue affecter. + * + * @param Glue glue The glue. + * @return UmaGlue The record. + */ + private fun glueOf(glue: Glue): UmaGlue { + val path = "glues[${glue.meshA.raw},${glue.meshB.raw}]" + return UmaGlue( + meshA = glue.meshA.raw, + meshB = glue.meshB.raw, + pairs = + UmaGluePairs( + indicesA = IntArray(glue.pairs.size) { pairIndex -> glue.pairs[pairIndex].indexA }, + indicesB = IntArray(glue.pairs.size) { pairIndex -> glue.pairs[pairIndex].indexB }, + weightsA = FloatArray(glue.pairs.size) { pairIndex -> glue.pairs[pairIndex].weightA }, + weightsB = FloatArray(glue.pairs.size) { pairIndex -> glue.pairs[pairIndex].weightB }, + ), + channels = channelsOf(glue.channelGrids, path), + intensity = optionalFloat(glue.intensity, 1f, "$path.intensity"), + id = glue.id, + ) + } + + /** + * UMA §4.11: a grid's axes. + * + * @param List axes The axes. + * @param String path The grid's position, for a failure. + * @return List The records. + */ + private fun axesOf(axes: List, path: String): List = + axes.mapIndexed { axisIndex, axis -> UmaAxis(axis.parameterId.raw, keysOf(axis.keys, "$path.axes[$axisIndex].keys")) } + + /** + * Inline key values, each checked to be finite. + * + * @param FloatArray keys The keys. + * @param String path Where they sit, for a failure. + * @return List The keys. + */ + private fun keysOf(keys: FloatArray, path: String): List = keys.mapIndexed { keyIndex, key -> finite(key, "$path[$keyIndex]") } + + /** + * UMA §4.11: a drawable's geometry grid. + * + * @param KeyformGrid grid The grid. + * @param String path The grid's position, for a failure. + * @return UmaMeshGrid The record. + */ + private fun meshGridOf(grid: KeyformGrid, path: String): UmaMeshGrid = + UmaMeshGrid(axesOf(grid.axes, path), grid.cells.map { cell -> UmaMeshCell(cell.coordinate.toList(), cell.form.positionDeltas) }) + + /** + * UMA §4.11: a warp's geometry grid. + * + * @param KeyformGrid grid The grid. + * @param String path The grid's position, for a failure. + * @return UmaDeformerGrid The record. + */ + private fun warpGridOf(grid: KeyformGrid, path: String): UmaDeformerGrid = + UmaDeformerGrid(axesOf(grid.axes, path), grid.cells.map { cell -> UmaDeformerCell(cell.coordinate.toList(), controlPoints = cell.form.controlPoints) }) + + /** + * UMA §4.11: a rotation's geometry grid. + * + * @param KeyformGrid grid The grid. + * @param String path The grid's position, for a failure. + * @return UmaDeformerGrid The record. + */ + private fun rotationGridOf(grid: KeyformGrid, path: String): UmaDeformerGrid = + UmaDeformerGrid( + axesOf(grid.axes, path), + grid.cells.mapIndexed { cellIndex, cell -> + val cellPath = "$path.cells[$cellIndex]" + UmaDeformerCell( + coordinate = cell.coordinate.toList(), + originX = finite(cell.form.originX, "$cellPath.originX"), + originY = finite(cell.form.originY, "$cellPath.originY"), + angle = finite(cell.form.angle, "$cellPath.angle"), + scale = finite(cell.form.scale, "$cellPath.scale"), + ) + }, + ) + + /** + * UMA §4.12: an owner's channel tracks, in channel order, or null when it keys none. + * + * @param ChannelGrids channelGrids The tracks. + * @param String path The owner's position, for a failure. + * @return Map? The records. + */ + private fun channelsOf(channelGrids: ChannelGrids, path: String): Map? { + if (channelGrids.isEmpty) { + return null + } + val tracks = LinkedHashMap() + for (channel in FormChannel.entries) { + val grid = channelGrids[channel] ?: continue + val trackPath = "$path.channels.${channel.toUma().wireName()}" + tracks[channel.toUma()] = + UmaChannelGrid( + axesOf(grid.axes, trackPath), + grid.cells.mapIndexed { cellIndex, cell -> UmaChannelCell(cell.coordinate.toList(), channelValueOf(cell.form, "$trackPath.cells[$cellIndex].value")) }, + ) + } + return tracks + } + + /** + * UMA §4.12: one channel value as JSON - a number, a color, or a boolean. + * + * @param ChannelValue value The value. + * @param String path Where it sits, for a failure. + * @return JsonElement The JSON. + */ + private fun channelValueOf(value: ChannelValue, path: String): JsonElement = + when (value) { + is ChannelValue.Scalar -> JsonPrimitive(finite(value.value, path)) + is ChannelValue.Color -> + JsonArray( + listOf( + JsonPrimitive(finite(value.color.red, "$path[0]")), + JsonPrimitive(finite(value.color.green, "$path[1]")), + JsonPrimitive(finite(value.color.blue, "$path[2]")), + ), + ) + + is ChannelValue.Flag -> JsonPrimitive(value.flag) + } + + /** + * UMA §4.13: a binding's limits, or null when it has none. + * + * @param List limits The limits. + * @param String path The binding's position, for a failure. + * @return List? The records. + */ + private fun limitsOf(limits: List, path: String): List? = + limits.mapIndexed { limitIndex, limit -> + UmaBlendLimit( + limit.parameterId.raw, + limit.points.mapIndexed { pointIndex, point -> + val pointPath = "$path.limits[$limitIndex].points[$pointIndex]" + UmaBlendLimitPoint(finite(point.value, "$pointPath.value"), finite(point.weight, "$pointPath.weight")) + }, + ) + }.ifEmpty { null } + + /** + * UMA §4.13: a drawable's blend-shape binding. + * + * @param BlendShapeBinding binding The binding. + * @param String path Its position, for a failure. + * @return UmaMeshBlendShape The record. + */ + private fun meshBlendShapeOf(binding: BlendShapeBinding, path: String): UmaMeshBlendShape = + UmaMeshBlendShape( + parameter = binding.parameterId.raw, + keys = keysOf(binding.keys, "$path.keys"), + neutralIndex = binding.neutralIndex, + forms = + binding.forms.mapIndexed { formIndex, form -> + form?.let { + val formPath = "$path.forms[$formIndex]" + UmaMeshForm( + positionDeltas = form.positionDeltas, + drawOrder = optionalFloat(form.drawOrder, DEFAULT_DRAW_ORDER.toFloat(), "$formPath.drawOrder"), + opacity = optionalFloat(form.opacity, 1f, "$formPath.opacity"), + multiplyColor = optionalColor(form.multiplyColor, ColorRgb.MultiplyIdentity, "$formPath.multiplyColor"), + screenColor = optionalColor(form.screenColor, ColorRgb.ScreenIdentity, "$formPath.screenColor"), + ) + } + }, + limits = limitsOf(binding.limits, path), + ) + + /** + * UMA §4.13: a warp's blend-shape binding. + * + * @param BlendShapeBinding binding The binding. + * @param String path Its position, for a failure. + * @return UmaDeformerBlendShape The record. + */ + private fun warpBlendShapeOf(binding: BlendShapeBinding, path: String): UmaDeformerBlendShape = + UmaDeformerBlendShape( + parameter = binding.parameterId.raw, + keys = keysOf(binding.keys, "$path.keys"), + neutralIndex = binding.neutralIndex, + forms = + binding.forms.mapIndexed { formIndex, form -> + form?.let { + val formPath = "$path.forms[$formIndex]" + UmaDeformerForm( + controlPoints = form.controlPoints, + opacity = optionalFloat(form.opacity, 1f, "$formPath.opacity"), + multiplyColor = optionalColor(form.multiplyColor, ColorRgb.MultiplyIdentity, "$formPath.multiplyColor"), + screenColor = optionalColor(form.screenColor, ColorRgb.ScreenIdentity, "$formPath.screenColor"), + ) + } + }, + limits = limitsOf(binding.limits, path), + ) + + /** + * UMA §4.13: a rotation's blend-shape binding. + * + * @param BlendShapeBinding binding The binding. + * @param String path Its position, for a failure. + * @return UmaDeformerBlendShape The record. + */ + private fun rotationBlendShapeOf(binding: BlendShapeBinding, path: String): UmaDeformerBlendShape = + UmaDeformerBlendShape( + parameter = binding.parameterId.raw, + keys = keysOf(binding.keys, "$path.keys"), + neutralIndex = binding.neutralIndex, + forms = + binding.forms.mapIndexed { formIndex, form -> + form?.let { + val formPath = "$path.forms[$formIndex]" + UmaDeformerForm( + originX = finite(form.originX, "$formPath.originX"), + originY = finite(form.originY, "$formPath.originY"), + angle = finite(form.angle, "$formPath.angle"), + scale = finite(form.scale, "$formPath.scale"), + flipX = optionalBoolean(form.flipX, false), + flipY = optionalBoolean(form.flipY, false), + opacity = optionalFloat(form.opacity, 1f, "$formPath.opacity"), + multiplyColor = optionalColor(form.multiplyColor, ColorRgb.MultiplyIdentity, "$formPath.multiplyColor"), + screenColor = optionalColor(form.screenColor, ColorRgb.ScreenIdentity, "$formPath.screenColor"), + ) + } + }, + limits = limitsOf(binding.limits, path), + ) + + /** + * UMA §4.13: a part's blend-shape binding. + * + * @param BlendShapeBinding binding The binding. + * @param String path Its position, for a failure. + * @return UmaPartBlendShape The record. + */ + private fun partBlendShapeOf(binding: BlendShapeBinding, path: String): UmaPartBlendShape = + UmaPartBlendShape( + parameter = binding.parameterId.raw, + keys = keysOf(binding.keys, "$path.keys"), + neutralIndex = binding.neutralIndex, + forms = + binding.forms.mapIndexed { formIndex, form -> + form?.let { + val formPath = "$path.forms[$formIndex]" + UmaPartForm( + drawOrder = finite(form.drawOrder, "$formPath.drawOrder"), + opacity = optionalFloat(form.opacity, 1f, "$formPath.opacity"), + multiplyColor = optionalColor(form.multiplyColor, ColorRgb.MultiplyIdentity, "$formPath.multiplyColor"), + screenColor = optionalColor(form.screenColor, ColorRgb.ScreenIdentity, "$formPath.screenColor"), + ) + } + }, + limits = limitsOf(binding.limits, path), + ) + + /** + * [value], refusing a NaN or infinity. + * + * @param Float value The value. + * @param String path Where the value sits in the entry, for the failure. + * @return Float The value. + * @throws UmaWriteException When the value is not finite. + */ + private fun finite(value: Float, path: String): Float = finiteInline(value, UmaEntryKind.Puppet.defaultPath, path) + + /** + * [value], or null when it is bit-for-bit [default]. + * + * @param Float value The value. + * @param Float default The model's default. + * @param String path Where the value sits, for a failure. + * @return Float? The value to write. + * @throws UmaWriteException When the value is not finite. + */ + private fun optionalFloat(value: Float, default: Float, path: String): Float? = + finite(value, path).takeIf { candidate -> candidate.toRawBits() != default.toRawBits() } + + /** + * [color] as red, green, blue, or null when every channel is bit-for-bit [identity]'s. + * + * @param ColorRgb color The color. + * @param ColorRgb identity The channel's identity color. + * @param String path Where the color sits, for a failure. + * @return List? The channels to write. + * @throws UmaWriteException When a channel is not finite. + */ + private fun optionalColor(color: ColorRgb, identity: ColorRgb, path: String): List? { + val channels = listOf(finite(color.red, "$path[0]"), finite(color.green, "$path[1]"), finite(color.blue, "$path[2]")) + val identityChannels = listOf(identity.red, identity.green, identity.blue) + val isIdentity = channels.indices.all { channelIndex -> channels[channelIndex].toRawBits() == identityChannels[channelIndex].toRawBits() } + return if (isIdentity) null else channels + } + + /** + * [value], or null when it is [default]. + * + * @param Boolean value The value. + * @param Boolean default The model's default. + * @return Boolean? The value to write. + */ + private fun optionalBoolean(value: Boolean, default: Boolean): Boolean? = value.takeIf { candidate -> candidate != default } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaPuppetImport.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaPuppetImport.kt new file mode 100644 index 0000000..1d9e753 --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaPuppetImport.kt @@ -0,0 +1,523 @@ +package org.umamo.interop.uma + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.floatOrNull +import org.umamo.format.uma.puppet.UmaAxis +import org.umamo.format.uma.puppet.UmaBlendLimit +import org.umamo.format.uma.puppet.UmaChannelGrid +import org.umamo.format.uma.puppet.UmaDeformer +import org.umamo.format.uma.puppet.UmaDeformerBlendShape +import org.umamo.format.uma.puppet.UmaDeformerGrid +import org.umamo.format.uma.puppet.UmaDeformerKind +import org.umamo.format.uma.puppet.UmaDrawable +import org.umamo.format.uma.puppet.UmaFormChannel +import org.umamo.format.uma.puppet.UmaGlue +import org.umamo.format.uma.puppet.UmaMeshBlendShape +import org.umamo.format.uma.puppet.UmaMeshGrid +import org.umamo.format.uma.puppet.UmaOrgRef +import org.umamo.format.uma.puppet.UmaParameter +import org.umamo.format.uma.puppet.UmaParameterNode +import org.umamo.format.uma.puppet.UmaPart +import org.umamo.format.uma.puppet.UmaPartBlendShape +import org.umamo.format.uma.puppet.UmaPartComposite +import org.umamo.format.uma.puppet.UmaPuppet +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.BlendWeightLimitPoint +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ChannelValueKind +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.runtime.model.withDerivedRenderRoot + +/** + * Builds a [PuppetModel] from the puppet entry (docs/format/UMA.md §4): restores each absent value to the + * model's default and derives the render root from the organizational tree (UMA §4.2). + * + * The entry comes from the codec, which has already refused every shape the model cannot hold (UMA §4.8): a field + * that belongs to another kind of object, arrays that disagree in size, and indices or keys out of range or order. + * Ids are taken verbatim and references are not resolved: a reference to an object the entry does not hold is + * carried as it is, never dropped. + */ +object UmaPuppetImport { + /** + * The model [puppet] describes. + * + * @param UmaPuppet puppet The puppet entry's content, as the codec decoded it (`UmaModel.puppet`). + * @return PuppetModel The model. + */ + fun modelOf(puppet: UmaPuppet): PuppetModel { + val model = + PuppetModel( + parameters = puppet.parameters.orEmpty().map(::parameterOf), + parts = puppet.parts.orEmpty().map(::partOf), + deformers = puppet.deformers.orEmpty().map(::deformerOf), + drawables = puppet.drawables.orEmpty().map(::drawableOf), + glues = puppet.glues.orEmpty().map(::glueOf), + rootChildren = puppet.rootChildren.orEmpty().map(::orgChildOf), + rootPartId = puppet.rootPart?.let(::PartId), + parameterLinks = puppet.parameterLinks.orEmpty().map { link -> ParameterLink(ParameterId(link.horizontal), ParameterId(link.vertical)) }, + parameterTree = puppet.parameterTree.orEmpty().map(::parameterNodeOf), + canvasWidth = puppet.canvasWidth ?: 0f, + canvasHeight = puppet.canvasHeight ?: 0f, + worldOriginX = puppet.worldOriginX ?: 0f, + worldOriginZ = puppet.worldOriginZ ?: 0f, + pixelsPerUnit = puppet.pixelsPerUnit, + runtimeTarget = puppet.runtimeTarget?.toRuntime() ?: RuntimeTarget.NoTarget, + rendersFromSourceLayers = puppet.rendersFromSourceLayers ?: false, + ) + // UMA §4.2: the render root is never written; it is always the organizational tree's derivation. + return model.withDerivedRenderRoot() + } + + /** + * UMA §4.3: one parameter. + * + * @param UmaParameter record The record. + * @return Parameter The parameter. + */ + private fun parameterOf(record: UmaParameter): Parameter = + Parameter( + id = ParameterId(record.id), + name = record.name, + min = record.min, + max = record.max, + default = record.default, + kind = record.kind?.toRuntime() ?: ParameterKind.NORMAL, + repeat = record.repeat ?: false, + ) + + /** + * UMA §4.3: one parameter-tree node, which the codec has checked is exactly one of a leaf and a named group. + * + * @param UmaParameterNode record The record. + * @return ParameterNode The node. + */ + private fun parameterNodeOf(record: UmaParameterNode): ParameterNode { + val leaf = record.parameter + if (leaf != null) { + return ParameterNode.Param(ParameterId(leaf)) + } + return ParameterNode.Group( + id = ParameterGroupId(checkNotNull(record.group) { "the codec checked a tree node names a parameter or a group" }), + name = checkNotNull(record.name) { "the codec checked a group has a name" }, + initiallyOpen = record.initiallyOpen ?: false, + children = record.children.orEmpty().map(::parameterNodeOf), + ) + } + + /** + * UMA §4.2: one organizational child, which the codec has checked is exactly one of a part and a drawable. + * + * @param UmaOrgRef record The record. + * @return OrgChild The child. + */ + private fun orgChildOf(record: UmaOrgRef): OrgChild { + val part = record.part + if (part != null) { + return OrgChild.Part(PartId(part)) + } + return OrgChild.Drawable(DrawableId(checkNotNull(record.drawable) { "the codec checked an org reference names a part or a drawable" })) + } + + /** + * UMA §4.4: one part. + * + * @param UmaPart record The record. + * @return Part The part. + */ + private fun partOf(record: UmaPart): Part = + Part( + id = PartId(record.id), + name = record.name, + children = record.children.orEmpty().map(::orgChildOf), + isVisible = record.isVisible ?: true, + isSketch = record.isSketch ?: false, + isSelectable = record.isSelectable ?: true, + groupMode = record.groupMode?.toRuntime() ?: PartGroupMode.PassThrough, + drawOrder = record.drawOrder ?: DEFAULT_DRAW_ORDER, + composite = compositeOf(record.composite ?: UmaPartComposite()), + channelGrids = channelsOf(record.channels), + blendShapes = record.blendShapes.orEmpty().map(::partBlendShapeOf), + ) + + /** + * UMA §4.4: a part's composite. + * + * @param UmaPartComposite record The record. + * @return PartComposite The composite. + */ + private fun compositeOf(record: UmaPartComposite): PartComposite = + PartComposite( + blendMode = record.blendMode?.toRuntime() ?: BlendMode.Normal, + alphaBlendMode = record.alphaBlendMode?.toRuntime() ?: AlphaBlendMode.Over, + maskedBy = record.maskedBy.orEmpty().map(::DrawableId), + maskedByParts = record.maskedByParts.orEmpty().map(::PartId), + invertMask = record.invertMask ?: false, + opacity = record.opacity ?: 1f, + multiplyColor = colorOf(record.multiplyColor, ColorRgb.MultiplyIdentity), + screenColor = colorOf(record.screenColor, ColorRgb.ScreenIdentity), + ) + + /** + * UMA §4.5: one deformer, whose kind decides which kind-specific fields it carries. + * + * @param UmaDeformer record The record. + * @return Deformer The deformer. + */ + private fun deformerOf(record: UmaDeformer): Deformer { + val multiplyColor = colorOf(record.multiplyColor, ColorRgb.MultiplyIdentity) + val screenColor = colorOf(record.screenColor, ColorRgb.ScreenIdentity) + return when (record.kind) { + UmaDeformerKind.Warp -> + Deformer.Warp( + id = DeformerId(record.id), + name = record.name, + parent = record.parent?.let(::DeformerId), + partId = record.part?.let(::PartId), + rows = checkNotNull(record.rows) { "the codec checked a warp has rows" }, + columns = checkNotNull(record.columns) { "the codec checked a warp has columns" }, + isQuadTransform = checkNotNull(record.isQuadTransform) { "the codec checked a warp has isQuadTransform" }, + geometryGrid = record.geometry?.let(::warpGridOf), + channelGrids = channelsOf(record.channels), + blendShapes = record.blendShapes.orEmpty().map(::warpBlendShapeOf), + opacity = record.opacity ?: 1f, + multiplyColor = multiplyColor, + screenColor = screenColor, + isSelectable = record.isSelectable ?: true, + isVisible = record.isVisible ?: true, + isEnabled = record.isEnabled ?: true, + ) + + UmaDeformerKind.Rotation -> + Deformer.Rotation( + id = DeformerId(record.id), + name = record.name, + parent = record.parent?.let(::DeformerId), + partId = record.part?.let(::PartId), + baseAngle = checkNotNull(record.baseAngle) { "the codec checked a rotation has baseAngle" }, + geometryGrid = record.geometry?.let(::rotationGridOf), + channelGrids = channelsOf(record.channels), + blendShapes = record.blendShapes.orEmpty().map(::rotationBlendShapeOf), + opacity = record.opacity ?: 1f, + multiplyColor = multiplyColor, + screenColor = screenColor, + flipX = record.flipX ?: false, + flipY = record.flipY ?: false, + isSelectable = record.isSelectable ?: true, + isVisible = record.isVisible ?: true, + isEnabled = record.isEnabled ?: true, + ) + } + } + + /** + * UMA §4.6: one drawable. + * + * @param UmaDrawable record The record. + * @return Drawable The drawable. + */ + private fun drawableOf(record: UmaDrawable): Drawable = + Drawable( + id = DrawableId(record.id), + name = record.name, + parentDeformerId = record.parentDeformer?.let(::DeformerId), + blendMode = record.blendMode?.toRuntime() ?: BlendMode.Normal, + maskedBy = record.maskedBy.orEmpty().map(::DrawableId), + mesh = record.mesh?.let { mesh -> DrawableMesh(mesh.positions, mesh.uvs, mesh.indices) }, + geometryGrid = record.geometry?.let(::meshGridOf), + channelGrids = channelsOf(record.channels), + drawOrder = record.drawOrder ?: DEFAULT_DRAW_ORDER.toFloat(), + opacity = record.opacity ?: 1f, + multiplyColor = colorOf(record.multiplyColor, ColorRgb.MultiplyIdentity), + screenColor = colorOf(record.screenColor, ColorRgb.ScreenIdentity), + invertMask = record.invertMask ?: false, + alphaBlendMode = record.alphaBlendMode?.toRuntime() ?: AlphaBlendMode.Over, + culling = record.culling ?: false, + isVisible = record.isVisible ?: true, + isSelectable = record.isSelectable ?: true, + textureSourceId = record.textureSource?.let(::DrawableId), + texturePage = record.texturePage ?: -1, + atlasTileId = record.atlasTile?.let(::AtlasTileId), + blendShapes = record.blendShapes.orEmpty().map(::meshBlendShapeOf), + ) + + /** + * UMA §4.14: one glue affecter. + * + * @param UmaGlue record The record. + * @return Glue The glue. + */ + private fun glueOf(record: UmaGlue): Glue { + val pairs = record.pairs + return Glue( + meshA = DrawableId(record.meshA), + meshB = DrawableId(record.meshB), + pairs = List(pairs.indicesA.size) { pairIndex -> GluePair(pairs.indicesA[pairIndex], pairs.indicesB[pairIndex], pairs.weightsA[pairIndex], pairs.weightsB[pairIndex]) }, + channelGrids = channelsOf(record.channels), + intensity = record.intensity ?: 1f, + id = record.id, + ) + } + + /** + * UMA §4.11: a grid's axes. + * + * @param List records The records. + * @return List The axes. + */ + private fun axesOf(records: List): List = records.map { axis -> KeyformAxis(ParameterId(axis.parameter), axis.keys.toFloatArray()) } + + /** + * UMA §4.11: a drawable's geometry grid. + * + * @param UmaMeshGrid record The record. + * @return KeyformGrid The grid. + */ + private fun meshGridOf(record: UmaMeshGrid): KeyformGrid = + KeyformGrid(axesOf(record.axes), record.cells.map { cell -> KeyformCell(cell.coordinate.toIntArray(), MeshDeltaForm(cell.positionDeltas)) }) + + /** + * UMA §4.11: a warp's geometry grid, whose cells carry a whole lattice. + * + * @param UmaDeformerGrid record The record. + * @return KeyformGrid The grid. + */ + private fun warpGridOf(record: UmaDeformerGrid): KeyformGrid = + KeyformGrid( + axesOf(record.axes), + record.cells.map { cell -> KeyformCell(cell.coordinate.toIntArray(), WarpLatticeForm(checkNotNull(cell.controlPoints) { "the codec checked a warp cell has controlPoints" })) }, + ) + + /** + * UMA §4.11: a rotation's geometry grid, whose cells carry a whole pivot. + * + * @param UmaDeformerGrid record The record. + * @return KeyformGrid The grid. + */ + private fun rotationGridOf(record: UmaDeformerGrid): KeyformGrid = + KeyformGrid( + axesOf(record.axes), + record.cells.map { cell -> + KeyformCell( + cell.coordinate.toIntArray(), + RotationPivotForm( + originX = checkNotNull(cell.originX) { PIVOT_CHECKED }, + originY = checkNotNull(cell.originY) { PIVOT_CHECKED }, + angle = checkNotNull(cell.angle) { PIVOT_CHECKED }, + scale = checkNotNull(cell.scale) { PIVOT_CHECKED }, + ), + ) + }, + ) + + /** + * UMA §4.12: an owner's channel tracks. + * + * @param Map? records The records, or null when the owner keys none. + * @return ChannelGrids The tracks. + */ + private fun channelsOf(records: Map?): ChannelGrids { + if (records.isNullOrEmpty()) { + return ChannelGrids.Empty + } + val tracks = LinkedHashMap>() + for ((umaChannel, record) in records) { + val channel = umaChannel.toRuntime() + tracks[channel] = KeyformGrid(axesOf(record.axes), record.cells.map { cell -> KeyformCell(cell.coordinate.toIntArray(), channelValueOf(cell.value, channel.valueKind)) }) + } + return ChannelGrids(tracks) + } + + /** + * UMA §4.12: one channel value - a number, a color, or a boolean, as the channel's kind requires, which the codec + * has checked. + * + * @param JsonElement value The JSON. + * @param ChannelValueKind kind The channel's kind. + * @return ChannelValue The value. + */ + private fun channelValueOf(value: JsonElement, kind: ChannelValueKind): ChannelValue = + when (kind) { + ChannelValueKind.SCALAR -> ChannelValue.Scalar(numberOf(value)) + ChannelValueKind.COLOR -> { + val channels = (value as JsonArray).map(::numberOf) + ChannelValue.Color(ColorRgb(channels[0], channels[1], channels[2])) + } + + ChannelValueKind.FLAG -> ChannelValue.Flag(checkNotNull((value as JsonPrimitive).booleanOrNull) { "the codec checked a flag value is a boolean" }) + } + + /** + * [value] as the float the codec has checked it holds. + * + * @param JsonElement value The JSON. + * @return Float The number. + */ + private fun numberOf(value: JsonElement): Float = checkNotNull((value as JsonPrimitive).floatOrNull) { "the codec checked a channel value is a number" } + + /** + * UMA §4.13: a binding's limits. + * + * @param List? records The records. + * @return List The limits. + */ + private fun limitsOf(records: List?): List = + records.orEmpty().map { limit -> BlendWeightLimit(ParameterId(limit.parameter), limit.points.map { point -> BlendWeightLimitPoint(point.value, point.weight) }) } + + /** + * UMA §4.13: a drawable's blend-shape binding. + * + * @param UmaMeshBlendShape record The record. + * @return BlendShapeBinding The binding. + */ + private fun meshBlendShapeOf(record: UmaMeshBlendShape): BlendShapeBinding = + BlendShapeBinding( + parameterId = ParameterId(record.parameter), + keys = record.keys.toFloatArray(), + neutralIndex = record.neutralIndex, + forms = + record.forms.map { form -> + form?.let { + MeshForm( + positionDeltas = form.positionDeltas, + drawOrder = form.drawOrder ?: DEFAULT_DRAW_ORDER.toFloat(), + opacity = form.opacity ?: 1f, + multiplyColor = colorOf(form.multiplyColor, ColorRgb.MultiplyIdentity), + screenColor = colorOf(form.screenColor, ColorRgb.ScreenIdentity), + ) + } + }, + limits = limitsOf(record.limits), + ) + + /** + * UMA §4.13: a warp's blend-shape binding, whose forms carry a whole lattice. + * + * @param UmaDeformerBlendShape record The record. + * @return BlendShapeBinding The binding. + */ + private fun warpBlendShapeOf(record: UmaDeformerBlendShape): BlendShapeBinding = + BlendShapeBinding( + parameterId = ParameterId(record.parameter), + keys = record.keys.toFloatArray(), + neutralIndex = record.neutralIndex, + forms = + record.forms.map { form -> + form?.let { + WarpForm( + controlPoints = checkNotNull(form.controlPoints) { "the codec checked a warp form has controlPoints" }, + opacity = form.opacity ?: 1f, + multiplyColor = colorOf(form.multiplyColor, ColorRgb.MultiplyIdentity), + screenColor = colorOf(form.screenColor, ColorRgb.ScreenIdentity), + ) + } + }, + limits = limitsOf(record.limits), + ) + + /** + * UMA §4.13: a rotation's blend-shape binding, whose forms carry a whole pivot. + * + * @param UmaDeformerBlendShape record The record. + * @return BlendShapeBinding The binding. + */ + private fun rotationBlendShapeOf(record: UmaDeformerBlendShape): BlendShapeBinding = + BlendShapeBinding( + parameterId = ParameterId(record.parameter), + keys = record.keys.toFloatArray(), + neutralIndex = record.neutralIndex, + forms = + record.forms.map { form -> + form?.let { + RotationForm( + originX = checkNotNull(form.originX) { PIVOT_CHECKED }, + originY = checkNotNull(form.originY) { PIVOT_CHECKED }, + angle = checkNotNull(form.angle) { PIVOT_CHECKED }, + scale = checkNotNull(form.scale) { PIVOT_CHECKED }, + flipX = form.flipX ?: false, + flipY = form.flipY ?: false, + opacity = form.opacity ?: 1f, + multiplyColor = colorOf(form.multiplyColor, ColorRgb.MultiplyIdentity), + screenColor = colorOf(form.screenColor, ColorRgb.ScreenIdentity), + ) + } + }, + limits = limitsOf(record.limits), + ) + + /** + * UMA §4.13: a part's blend-shape binding. + * + * @param UmaPartBlendShape record The record. + * @return BlendShapeBinding The binding. + */ + private fun partBlendShapeOf(record: UmaPartBlendShape): BlendShapeBinding = + BlendShapeBinding( + parameterId = ParameterId(record.parameter), + keys = record.keys.toFloatArray(), + neutralIndex = record.neutralIndex, + forms = + record.forms.map { form -> + form?.let { + PartForm( + drawOrder = form.drawOrder, + opacity = form.opacity ?: 1f, + multiplyColor = colorOf(form.multiplyColor, ColorRgb.MultiplyIdentity), + screenColor = colorOf(form.screenColor, ColorRgb.ScreenIdentity), + ) + } + }, + limits = limitsOf(record.limits), + ) + + /** + * UMA §4.1: a color, which the codec has checked is exactly three channels, or [identity] when absent. + * + * @param List? channels The record's channels. + * @param ColorRgb identity The channel's identity color. + * @return ColorRgb The color. + */ + private fun colorOf(channels: List?, identity: ColorRgb): ColorRgb = channels?.let { ColorRgb(channels[0], channels[1], channels[2]) } ?: identity + + /** The failure a rotation form without its whole pivot reports, which the codec has already refused. */ + private const val PIVOT_CHECKED = "the codec checked a rotation form carries its whole pivot" +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaSourcesBridge.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaSourcesBridge.kt new file mode 100644 index 0000000..049c79a --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaSourcesBridge.kt @@ -0,0 +1,93 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.sources.UmaSource +import org.umamo.format.uma.sources.UmaSourceLayer +import org.umamo.format.uma.sources.UmaSources +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.PuppetModel + +/** + * Lowers a [PuppetModel]'s linked source art onto the sources entry's schema (docs/format/UMA.md §6), and back: + * every inventory row with every flag, and the hashes in the file's prefixed form (UMA §6.4). + */ +object UmaSourcesBridge { + /** + * The sources entry's content for [model]. + * + * @param PuppetModel model The model. + * @return UmaSources The content; an empty object when the document links no source art. + */ + fun sourcesOf(model: PuppetModel): UmaSources = + UmaSources( + model.sources.map { source -> + UmaSource( + id = source.id.raw, + name = source.name, + format = source.format, + path = source.path, + contentHash = prefixedHashOf(source.contentHash), + lastModified = source.lastModified, + layers = + source.layers.map { layer -> + UmaSourceLayer( + key = layer.key, + name = layer.name, + groupPath = layer.groupPath, + left = layer.left, + top = layer.top, + width = layer.width, + height = layer.height, + visible = layer.visible, + present = layer.present.takeIf { present -> !present }, + contentHash = prefixedHashOf(layer.contentHash), + empty = layer.empty.takeIf { empty -> empty }, + replaced = layer.replaced.takeIf { replaced -> replaced }, + ignored = layer.ignored.takeIf { ignored -> ignored }, + ) + }.ifEmpty { null }, + offsetX = source.offsetX.takeIf { offset -> offset != 0 }, + offsetZ = source.offsetZ.takeIf { offset -> offset != 0 }, + ) + }.ifEmpty { null }, + ) + + /** + * The linked source art the sources entry describes. + * + * @param UmaSources? sources The entry's content, or null when the document has none. + * @return List The sources, in document order. + */ + fun sourcesOf(sources: UmaSources?): List = + sources?.sources.orEmpty().map { source -> + ArtSource( + id = ArtSourceId(source.id), + name = source.name, + path = source.path, + format = source.format, + layers = + source.layers.orEmpty().map { layer -> + ArtSourceLayer( + key = layer.key, + name = layer.name, + groupPath = layer.groupPath, + left = layer.left, + top = layer.top, + width = layer.width, + height = layer.height, + visible = layer.visible, + present = layer.present ?: true, + contentHash = digestOf(layer.contentHash), + empty = layer.empty ?: false, + replaced = layer.replaced ?: false, + ignored = layer.ignored ?: false, + ) + }, + contentHash = digestOf(source.contentHash), + lastModified = source.lastModified, + offsetX = source.offsetX ?: 0, + offsetZ = source.offsetZ ?: 0, + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaTexturesBridge.kt b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaTexturesBridge.kt new file mode 100644 index 0000000..352bd9c --- /dev/null +++ b/module/interop/src/commonMain/kotlin/org/umamo/interop/uma/UmaTexturesBridge.kt @@ -0,0 +1,126 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.textures.UmaComposition +import org.umamo.format.uma.textures.UmaPage +import org.umamo.format.uma.textures.UmaPlacement +import org.umamo.format.uma.textures.UmaSourceRef +import org.umamo.format.uma.textures.UmaTextures +import org.umamo.format.uma.textures.UmaTile +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasComposition +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef + +/** + * Lowers a [PuppetModel]'s atlas onto the textures entry's schema (docs/format/UMA.md §5), and back. + * + * The atlas records only; the images the drawables sample (the render pages) and every path are the format layer's + * to lay out from the pixels a save hands it. A value is left out only when it is the model's default. + */ +object UmaTexturesBridge { + /** + * The textures entry's records for [model]. + * + * @param PuppetModel model The model. + * @return UmaTextures The records, without paths. + * @throws UmaWriteException When a placement holds a value JSON cannot. + */ + fun texturesOf(model: PuppetModel): UmaTextures { + val atlas = model.atlas + val composition = atlas.composition + val default = AtlasComposition.Default + return UmaTextures( + storedUvsAddressPages = atlas.storedUvsAddressPages.takeIf { addressesPages -> !addressesPages }, + composition = + UmaComposition( + alphaThreshold = composition.alphaThreshold.takeIf { threshold -> threshold != default.alphaThreshold }, + extrude = composition.extrude.takeIf { extrude -> extrude != default.extrude }, + ).takeIf { record -> record != UmaComposition() }, + pages = atlas.pages.map { page -> UmaPage(page.width, page.height) }.ifEmpty { null }, + tiles = atlas.tiles.map(::tileOf).ifEmpty { null }, + ) + } + + /** + * UMA §5.4: one tile's record. + * + * @param AtlasTile tile The tile. + * @return UmaTile The record. + * @throws UmaWriteException When its placement holds a value JSON cannot. + */ + private fun tileOf(tile: AtlasTile): UmaTile { + val path = "tiles[${tile.id.raw}].placement" + + /** + * [value], refused when it is not finite. + * + * @param Float value The value. + * @param String key The placement key, for the failure. + * @return Float The value. + */ + fun finite(value: Float, key: String): Float = finiteInline(value, UmaEntryKind.Textures.defaultPath, "$path.$key") + return UmaTile( + id = tile.id.raw, + name = tile.name, + width = tile.width, + height = tile.height, + placement = + tile.placement?.let { placement -> + UmaPlacement( + page = placement.pageIndex, + positionX = finite(placement.positionX, "positionX"), + positionY = finite(placement.positionY, "positionY"), + scaleX = finite(placement.scaleX, "scaleX"), + scaleY = finite(placement.scaleY, "scaleY"), + rotationDegrees = finite(placement.rotationDegrees, "rotationDegrees"), + ) + }, + source = tile.source?.let { source -> UmaSourceRef(source.sourceId.raw, source.layerKey, source.stableKey) }, + pinned = tile.pinned.takeIf { pinned -> pinned }, + replaces = tile.replaces?.raw, + ) + } + + /** + * The atlas the textures entry describes. + * + * @param UmaTextures? textures The entry's content, or null when the document has none. + * @return PuppetAtlas The atlas. + */ + fun atlasOf(textures: UmaTextures?): PuppetAtlas { + if (textures == null) { + return PuppetAtlas.Empty + } + val tiles = + textures.tiles.orEmpty().map { record -> + AtlasTile( + id = AtlasTileId(record.id), + name = record.name, + width = record.width, + height = record.height, + placement = + record.placement?.let { placement -> + AtlasPlacement(placement.page, placement.positionX, placement.positionY, placement.scaleX, placement.scaleY, placement.rotationDegrees) + }, + source = record.source?.let { source -> SourceLayerRef(ArtSourceId(source.art), source.layerKey, source.stableKey) }, + pinned = record.pinned ?: false, + replaces = record.replaces?.let(::AtlasTileId), + ) + } + val default = AtlasComposition.Default + return PuppetAtlas( + pages = textures.pages.orEmpty().map { page -> AtlasPage(page.width, page.height) }, + tiles = tiles, + storedUvsAddressPages = textures.storedUvsAddressPages ?: true, + // UMA §5.2: the format layer has already refused a composition outside the ranges the model allows. + composition = AtlasComposition(textures.composition?.alphaThreshold ?: default.alphaThreshold, textures.composition?.extrude ?: default.extrude), + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/BlendModeMappingTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/BlendModeMappingTest.kt new file mode 100644 index 0000000..0f4e21c --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/BlendModeMappingTest.kt @@ -0,0 +1,108 @@ +package org.umamo.interop + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the blend-mode bijections against the extraction tables in docs/plan/offscreen-support.md: + * every CMO3 token and every MOC3 packed int maps to its distinct runtime mode, the two encodings + * agree pairwise, and unknown values fall back to Normal/Over. + */ +class BlendModeMappingTest { + /** One row of the extraction table: CMO3 token, MOC3 colorMode int, runtime mode. */ + private data class ColorRow(val token: String, val packedColor: Int, val mode: BlendMode) + + private val colorRows = + listOf( + ColorRow("NORMAL", 0, BlendMode.Normal), + ColorRow("ADD", 1, BlendMode.AdditivePremultiplied), + ColorRow("MULTIPLY", 2, BlendMode.MultiplyPremultiplied), + ColorRow("ADD_R2_TSL", 3, BlendMode.Additive), + ColorRow("ADD_R2", 4, BlendMode.AdditiveGlow), + ColorRow("DARKEN", 5, BlendMode.Darken), + ColorRow("MULTIPLY_R2", 6, BlendMode.Multiply), + ColorRow("COLORBURN_TSL", 7, BlendMode.ColorBurn), + ColorRow("LINEARBURN_TSL", 8, BlendMode.LinearBurn), + ColorRow("LIGHTEN", 9, BlendMode.Lighten), + ColorRow("SCREEN", 10, BlendMode.Screen), + ColorRow("COLORDODGE_TSL", 11, BlendMode.ColorDodge), + ColorRow("OVERLAY", 12, BlendMode.Overlay), + ColorRow("SOFTLIGHT", 13, BlendMode.SoftLight), + ColorRow("HARDLIGHT", 14, BlendMode.HardLight), + ColorRow("LINEARLIGHT_TSL", 15, BlendMode.LinearLight), + ColorRow("HSL_HUE", 16, BlendMode.Hue), + ColorRow("HSL_COLOR", 17, BlendMode.Color), + ) + + /** One row of the alpha table: CMO3 token, MOC3 alphaMode int, runtime mode. */ + private data class AlphaRow(val token: String, val packedAlpha: Int, val mode: AlphaBlendMode) + + private val alphaRows = + listOf( + AlphaRow("OVER", 0, AlphaBlendMode.Over), + AlphaRow("ATOP", 1, AlphaBlendMode.Atop), + AlphaRow("OUT", 2, AlphaBlendMode.Out), + AlphaRow("CONJOINT", 3, AlphaBlendMode.Conjoint), + AlphaRow("DISJOINT", 4, AlphaBlendMode.Disjoint), + ) + + @Test + fun colorTableIsACompleteBijection() { + assertEquals(BlendMode.entries.size, colorRows.size, "one row per BlendMode constant") + assertEquals(colorRows.size, colorRows.map { it.mode }.toSet().size, "modes are distinct") + for (row in colorRows) { + assertEquals(row.mode, colorBlendOfToken(row.token), "token ${row.token}") + assertEquals(row.mode, colorBlendOfPacked(row.packedColor), "packed colorMode ${row.packedColor}") + } + } + + @Test + fun alphaTableIsACompleteBijection() { + assertEquals(AlphaBlendMode.entries.size, alphaRows.size, "one row per AlphaBlendMode constant") + assertEquals(alphaRows.size, alphaRows.map { it.mode }.toSet().size, "modes are distinct") + for (row in alphaRows) { + assertEquals(row.mode, alphaBlendOfToken(row.token), "token ${row.token}") + assertEquals(row.mode, alphaBlendOfPacked(row.packedAlpha shl 8), "packed alphaMode ${row.packedAlpha}") + } + } + + @Test + fun packedHalvesAreIndependent() { + // The corpus-observed combinations: 522 = Screen or (Out shl 8) (the PartClipping drawable), + // 262 = Multiply or (Atop shl 8), 256 = Normal or (Atop shl 8) (Model A offscreens). + assertEquals(BlendMode.Screen, colorBlendOfPacked(522)) + assertEquals(AlphaBlendMode.Out, alphaBlendOfPacked(522)) + assertEquals(BlendMode.Multiply, colorBlendOfPacked(262)) + assertEquals(AlphaBlendMode.Atop, alphaBlendOfPacked(262)) + assertEquals(BlendMode.Normal, colorBlendOfPacked(256)) + assertEquals(AlphaBlendMode.Atop, alphaBlendOfPacked(256)) + assertEquals(BlendMode.Normal, colorBlendOfPacked(0)) + assertEquals(AlphaBlendMode.Over, alphaBlendOfPacked(0)) + } + + @Test + fun unknownValuesFallBackToDefaults() { + assertEquals(BlendMode.Normal, colorBlendOfToken(null)) + assertEquals(BlendMode.Normal, colorBlendOfToken("SOME_FUTURE_MODE")) + assertEquals(AlphaBlendMode.Over, alphaBlendOfToken(null)) + assertEquals(AlphaBlendMode.Over, alphaBlendOfToken("SOME_FUTURE_MODE")) + assertEquals(BlendMode.Normal, colorBlendOfPacked(99)) + assertEquals(AlphaBlendMode.Over, alphaBlendOfPacked(99 shl 8)) + } + + @Test + fun legacyPredicateCoversExactlyThePreFiveThreeModes() { + val legacyModes = BlendMode.entries.filter { it.isLegacy } + assertEquals(listOf(BlendMode.Normal, BlendMode.AdditivePremultiplied, BlendMode.MultiplyPremultiplied), legacyModes) + assertTrue(BlendMode.entries.filterNot { it.isLegacy }.size == 15, "fifteen 5.3 modes") + } + + @Test + fun ignoresAlphaBlendCoversExactlyTheTwoPremultipliedModes() { + val ignoringModes = BlendMode.entries.filter { it.ignoresAlphaBlend } + assertEquals(listOf(BlendMode.AdditivePremultiplied, BlendMode.MultiplyPremultiplied), ignoringModes) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/ExportNoticeDescriptionTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/ExportNoticeDescriptionTest.kt new file mode 100644 index 0000000..f1af2c0 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/ExportNoticeDescriptionTest.kt @@ -0,0 +1,46 @@ +package org.umamo.interop + +import org.umamo.runtime.model.RuntimeFeature +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the one log line per export notice that the editor's log and the command-line tool's report share. + * + * The line is a diagnostic surface read off a bug report, so it has to name what it is about and stay + * short: a finding over a whole rig can list hundreds of drawables, and the line names the first few and + * counts the rest instead of burying every other line of the log. + */ +class ExportNoticeDescriptionTest { + @Test + fun anUnsupportedChangeNamesItsCategoryItsSubjectAndItsReason() { + val onAnEntity = ExportNotice.UnsupportedChange(ExportEntityCategory.Drawable, "ArtMesh12", ExportNoticeReason.DrawableHasNoMesh) + val onTheDocument = ExportNotice.UnsupportedChange(ExportEntityCategory.Document, null, ExportNoticeReason.NoAuthoredWorldOrigin) + + assertEquals("[Drawable] ArtMesh12: DrawableHasNoMesh", describeExportNotice(onAnEntity)) + assertEquals("[Document] NoAuthoredWorldOrigin", describeExportNotice(onTheDocument), "a document-level finding has no subject to name") + } + + @Test + fun aLongSubjectListNamesTheFirstEightAndCountsTheRest() { + val names = (1..11).map { index -> "Mesh$index" } + + val stripped = describeExportNotice(ExportNotice.FeatureStripped(RuntimeFeature.ReversedMask, names)) + val twins = describeExportNotice(ExportNotice.SharedAtlasSlotKept(names)) + + for (line in listOf(stripped, twins)) { + assertTrue(line.contains("Mesh8"), line) + assertTrue(!line.contains("Mesh9"), line) + assertTrue(line.contains("(+3 more)"), line) + } + assertTrue(stripped.startsWith("ReversedMask "), stripped) + } + + @Test + fun aShortSubjectListIsNamedInFull() { + val line = describeExportNotice(ExportNotice.WeldDivergence(listOf("Hair", "Brow"))) + + assertEquals("weld divergence on Hair, Brow", line) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/ExportNoticeReasonTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/ExportNoticeReasonTest.kt new file mode 100644 index 0000000..6971f1b --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/ExportNoticeReasonTest.kt @@ -0,0 +1,54 @@ +package org.umamo.interop + +import org.umamo.runtime.model.FormChannel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the structural rendering [ExportNoticeReason] promises its log mirror. + * + * The app logs each notice with the reason's own `toString()` rather than a hand-written English + * sentence, so that the diagnostic surface cannot drift from the case list the way a second copy of + * the prose would. That only works while every case is a `data object` or `data class` - a bare + * `object` would print an identity hash - and while no field's own `toString()` is an identity one. + * These tests fail the moment either holds false. + */ +class ExportNoticeReasonTest { + @Test + fun anArgumentFreeReasonPrintsItsCaseName() { + assertEquals( + "NoMatchingSourceToReconcile", + ExportNoticeReason.NoMatchingSourceToReconcile.toString(), + ) + assertEquals("DrawableHasNoMesh", ExportNoticeReason.DrawableHasNoMesh.toString()) + assertEquals("NoAuthoredWorldOrigin", ExportNoticeReason.NoAuthoredWorldOrigin.toString()) + } + + @Test + fun aParameterizedReasonPrintsItsFieldsByName() { + val truncated = ExportNoticeReason.IdTruncated(recordByteWidth = 64, writtenId = "Param01") + assertTrue(truncated.toString().contains("writtenId=Param01"), truncated.toString()) + assertTrue(truncated.toString().contains("recordByteWidth=64"), truncated.toString()) + + val reordered = ExportNoticeReason.CombinedPairReordered("ParamAngleX", "ParamAngleY") + assertTrue(reordered.toString().contains("ParamAngleX"), reordered.toString()) + assertTrue(reordered.toString().contains("ParamAngleY"), reordered.toString()) + } + + @Test + fun aNestedRejectionPrintsThroughItsWrapper() { + // KeyformCannotBundle is the one case carrying another sealed type, so its log line depends on + // KeyformBundleRejection honoring the same data-class rule. + val nested = + ExportNoticeReason.KeyformCannotBundle( + KeyformBundleRejection.KeysOutsideChannelSpan(FormChannel.OPACITY), + ) + assertTrue(nested.toString().contains("OPACITY"), nested.toString()) + assertTrue(nested.toString().contains("KeysOutsideChannelSpan"), nested.toString()) + assertEquals( + "KeysOutsideGeometrySpan", + KeyformBundleRejection.KeysOutsideGeometrySpan.toString(), + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/KeyformBundleTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/KeyformBundleTest.kt new file mode 100644 index 0000000..e40a753 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/KeyformBundleTest.kt @@ -0,0 +1,218 @@ +package org.umamo.interop + +import org.umamo.runtime.keyform.ChannelValueInterpolator +import org.umamo.runtime.keyform.FormInterpolator +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The shared re-bundler's contract, and in particular the two [OutOfSpanPolicy] branches. + * + * The out-of-span case is the one worth pinning: a channel keyed over a NARROWER span than the union + * cannot be placed in the bundled grid without inventing values at the keys it never covered. CMO3 + * declines the whole owner; MOC3 cannot, because a MOC3 object with no keyform produces a file the + * runtime will not load, so it drops that one channel to its static instead. Both branches are + * exercised here because each caller only ever reaches its own - `Cmo3KeyformLowering` never passes + * DemoteChannel and `Moc3KeyformLowering` never passes RejectOwner - so neither format's own gates + * can catch a regression in the other's policy. + */ +class KeyformBundleTest { + private val angleX = ParameterId("ParamAngleX") + + /** + * A single-axis channel track over [keys] with a distinct scalar per key. + * + * @param FloatArray keys The axis key positions. + * @return KeyformGrid The track. + */ + private fun track(keys: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, keys)), + keys.indices.map { keyIndex -> + KeyformCell(intArrayOf(keyIndex), ChannelValue.Scalar(keyIndex.toFloat())) + }, + ) + + /** + * A geometry grid over [keys], carrying the key index as its form so cells stay identifiable. + * + * @param FloatArray keys The axis key positions. + * @return KeyformGrid The grid. + */ + private fun geometry(keys: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, keys)), + keys.indices.map { keyIndex -> KeyformCell(intArrayOf(keyIndex), keyIndex.toFloat()) }, + ) + + /** A float interpolator, so the geometry can be refined onto the union like a real payload. */ + private val floatBlend = + object : FormInterpolator { + override fun interpolate(lower: Float, upper: Float, fraction: Float): Float = + lower + (upper - lower) * fraction + + override fun isExactlyEqual(left: Float, right: Float): Boolean = left == right + } + + private val statics = mapOf(FormChannel.OPACITY to ChannelValue.Scalar(1f)) + + /** Geometry spanning -30..30 with a channel keyed only over the NARROWER -10..10. */ + private fun outOfSpanInputs(): Pair, ChannelGrids> = + geometry(floatArrayOf(-30f, 0f, 30f)) to + ChannelGrids(mapOf(FormChannel.OPACITY to track(floatArrayOf(-10f, 0f, 10f)))) + + @Test + fun rejectOwnerRefusesAChannelKeyedOutsideTheUnionSpan() { + val (geometryGrid, channels) = outOfSpanInputs() + val result = + buildKeyformBundle( + geometryGrid, + floatBlend, + channels, + statics, + requireGeometry = false, + outOfSpanPolicy = OutOfSpanPolicy.RejectOwner, + ) + assertTrue(result is KeyformBundleResult.Unrepresentable, "an out-of-span channel rejects the owner") + val rejection = result.rejection + assertTrue( + rejection is KeyformBundleRejection.KeysOutsideChannelSpan && + rejection.channel == FormChannel.OPACITY, + "the rejection names the offending channel: $rejection", + ) + } + + @Test + fun demoteChannelKeepsTheOwnerAndNamesWhatItDropped() { + val (geometryGrid, channels) = outOfSpanInputs() + val result = + buildKeyformBundle( + geometryGrid, + floatBlend, + channels, + statics, + requireGeometry = false, + outOfSpanPolicy = OutOfSpanPolicy.DemoteChannel, + ) + assertTrue(result is KeyformBundleResult.Bundled, "the owner still bundles") + val bundle = result.bundle + assertEquals(listOf(FormChannel.OPACITY), bundle.demotedChannels, "the dropped channel is named") + // Every cell falls back to the static rather than to an invented interpolation. + assertTrue(bundle.cells.isNotEmpty(), "the bundle has cells") + assertTrue( + bundle.cells.all { cell -> cell.channels[FormChannel.OPACITY] == statics.getValue(FormChannel.OPACITY) }, + "a demoted channel reads its static in every cell", + ) + // The union is BOTH sets of keys (-30, -10, 0, 10, 30): the geometry refines onto all five + // because they fall inside its own span, which is precisely why the narrower channel cannot - + // it would have to invent values at -30 and 30. Demoting it does not shrink the grid. + assertEquals(5, bundle.cells.size, "the union keeps every key from both sides") + assertEquals( + listOf(-30f, -10f, 0f, 10f, 30f), + bundle.axes.single().keys.toList(), + "the union axis carries both key sets", + ) + } + + @Test + fun bothPoliciesAgreeWhenNothingIsOutOfSpan() { + val geometryGrid = geometry(floatArrayOf(-30f, 0f, 30f)) + val channels = ChannelGrids(mapOf(FormChannel.OPACITY to track(floatArrayOf(-30f, 0f, 30f)))) + val bundles = + listOf(OutOfSpanPolicy.RejectOwner, OutOfSpanPolicy.DemoteChannel).map { policy -> + val result = + buildKeyformBundle(geometryGrid, floatBlend, channels, statics, false, policy) + assertTrue(result is KeyformBundleResult.Bundled, "$policy bundles an in-span owner") + result.bundle + } + val (rejectBundle, demoteBundle) = bundles + assertEquals(emptyList(), rejectBundle.demotedChannels, "nothing is demoted when nothing is out of span") + assertEquals(emptyList(), demoteBundle.demotedChannels, "nothing is demoted when nothing is out of span") + assertEquals(rejectBundle.cells.size, demoteBundle.cells.size, "the policies produce the same grid") + for (cellIndex in rejectBundle.cells.indices) { + assertEquals( + rejectBundle.cells[cellIndex].channels, + demoteBundle.cells[cellIndex].channels, + "cell $cellIndex agrees across policies", + ) + } + } + + @Test + fun aFullyUnkeyedOwnerBundlesToNothing() { + val result = + buildKeyformBundle( + null as KeyformGrid?, + floatBlend, + ChannelGrids.Empty, + statics, + requireGeometry = false, + outOfSpanPolicy = OutOfSpanPolicy.RejectOwner, + ) + assertTrue(result is KeyformBundleResult.Bundled, "an unkeyed owner is not an error") + assertEquals(emptyList(), result.bundle.axes, "no axes") + assertEquals(emptyList(), result.bundle.cells, "no cells") + } + + @Test + fun geometryRequiredMeansAChannelOnlyOwnerIsUnrepresentable() { + val channels = ChannelGrids(mapOf(FormChannel.OPACITY to track(floatArrayOf(-10f, 10f)))) + val result = + buildKeyformBundle( + null as KeyformGrid?, + floatBlend, + channels, + statics, + requireGeometry = true, + outOfSpanPolicy = OutOfSpanPolicy.DemoteChannel, + ) + // Not demotable: a warp or rotation with keyed channels but no lattice has nothing to write. + assertTrue(result is KeyformBundleResult.Unrepresentable, "geometry-less is an error when required") + } + + /** + * An AXIS-LESS channel track still carries its value, and that value beats the owner's static. + * + * A track can be a single cell with no axes - an authored constant that was never lifted into the + * static - and the static in that state still holds an untouched default. The early return for + * "no keys anywhere" used to fill channels straight from the statics, which silently replaced every + * such value; a MOC3 export of an uncompacted import wrote 1.0 opacity over an authored 0.66. + */ + @Test + fun anAxisLessChannelTrackBeatsTheStatic() { + val authored: ChannelValue = ChannelValue.Scalar(0.66f) + val axisLessTrack = KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), authored))) + val result = + buildKeyformBundle( + KeyformGrid(emptyList(), listOf(KeyformCell(IntArray(0), 0f))), + floatBlend, + ChannelGrids(mapOf(FormChannel.OPACITY to axisLessTrack)), + // The static is the constructor default the import leaves behind when nothing lifted it. + mapOf(FormChannel.OPACITY to ChannelValue.Scalar(1f)), + requireGeometry = false, + outOfSpanPolicy = OutOfSpanPolicy.DemoteChannel, + ) + assertTrue(result is KeyformBundleResult.Bundled, "an axis-less owner still bundles") + assertEquals(1, result.bundle.cells.size, "one static cell") + assertEquals( + authored, + result.bundle.cells.single().channels[FormChannel.OPACITY], + "the track's authored value wins over the static", + ) + } + + /** Guards the interpolator the other cases lean on, so a failure there reads as its own cause. */ + @Test + fun channelValueInterpolatorBlendsScalars() { + val blended = ChannelValueInterpolator.interpolate(ChannelValue.Scalar(0f), ChannelValue.Scalar(10f), 0.25f) + assertEquals(ChannelValue.Scalar(2.5f), blended) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/PuppetModelDiffTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/PuppetModelDiffTest.kt new file mode 100644 index 0000000..577628a --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/PuppetModelDiffTest.kt @@ -0,0 +1,447 @@ +package org.umamo.interop + +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * Pins diffPuppetModels' contract directly - the reconcile backbone every CMO3 export round-trip + * test exercises only end to end. Covers each category's Created/Deleted set-difference, the exact + * Changed field sets (ParameterField and GlueField exhaustively; representative shallow/deep/ + * reference fields for parts, deformers, and drawables), the glue ordered-pair + ordinal keying, + * bit-exact float comparison, and baseline-order emission. + */ +class PuppetModelDiffTest { + private val angleX = ParameterId("ParamAngleX") + + private fun parameter(id: String, min: Float = -1f, max: Float = 1f, default: Float = 0f): Parameter = + Parameter(ParameterId(id), id, min = min, max = max, default = default) + + /** A one-triangle drawable with no keyforms and no deformer parent. */ + private fun drawable(id: String): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f), + uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + indices = intArrayOf(0, 1, 2), + ), + geometryGrid = null, + ) + + private fun part(id: String): Part = Part(id = PartId(id), name = id, children = emptyList()) + + /** A one-axis mesh-delta grid on angleX whose single interesting delta is [firstDelta]. */ + private fun deltaGrid(firstDelta: Float): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(firstDelta, 0f, 0f, 0f, 0f, 0f))), + ), + ) + + /** A one-axis opacity track on angleX ending at [lastValue]. */ + private fun opacityTrack(lastValue: Float): ChannelGrids = + ChannelGrids( + mapOf( + FormChannel.OPACITY to + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(1f) as ChannelValue), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(lastValue)), + ), + ), + ), + ) + + /** + * A minimal model over explicit entity lists. rootChildren stays empty on purpose, so mutating an + * entity list never doubles as a ROOT_CHILDREN document diff. + */ + private fun puppet( + parameters: List = emptyList(), + parts: List = emptyList(), + deformers: List = emptyList(), + drawables: List = emptyList(), + glues: List = emptyList(), + parameterTree: List = emptyList(), + ): PuppetModel = + PuppetModel( + parameters = parameters, + parts = parts, + deformers = deformers, + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + glues = glues, + parameterTree = parameterTree, + canvasWidth = 100f, + canvasHeight = 100f, + ) + + /** The field set of a category's single Changed entry, asserting it is the only diff. */ + private fun onlyChangedFields(diffs: List>): Set { + assertEquals(1, diffs.size) + return when (val entry = diffs.single()) { + is EntityDiff.Changed -> entry.fields + else -> fail("expected a Changed entry, got $entry") + } + } + + /** The same instance on both sides is semantically identical. */ + @Test + fun identicalModelInstanceProducesEmptyDiff() { + val model = puppet(parameters = listOf(parameter("ParamA")), drawables = listOf(drawable("d1"))) + assertTrue(diffPuppetModels(model, model).isEmpty) + } + + /** Field-equal copies (fresh instances) still diff empty - equality is by value, not identity. */ + @Test + fun fieldEqualCopyProducesEmptyDiff() { + val baseline = puppet(parameters = listOf(parameter("ParamA")), drawables = listOf(drawable("d1"))) + val edited = baseline.copy(drawables = baseline.drawables.map { entity -> entity.copy() }) + assertTrue(diffPuppetModels(baseline, edited).isEmpty) + } + + /** Creation and deletion are id set-difference: one-sided ids yield Created/Deleted entries. */ + @Test + fun parameterCreatedAndDeletedById() { + val kept = parameter("ParamKept") + val baseline = puppet(parameters = listOf(kept, parameter("ParamGone"))) + val edited = puppet(parameters = listOf(kept, parameter("ParamNew"))) + val diff = diffPuppetModels(baseline, edited) + assertEquals( + listOf(EntityDiff.Deleted(ParameterId("ParamGone")), EntityDiff.Created(ParameterId("ParamNew"))), + diff.parameters, + ) + } + + /** Each ParameterField flags exactly its own edit - the full enum, one field per case. */ + @Test + fun parameterChangedFieldsAreExact() { + val baseline = puppet(parameters = listOf(parameter("ParamA"))) + + fun fieldsAfter(edit: (Parameter) -> Parameter): Set = + onlyChangedFields(diffPuppetModels(baseline, puppet(parameters = listOf(edit(baseline.parameters.single())))).parameters) + assertEquals(setOf(ParameterField.NAME), fieldsAfter { entity -> entity.copy(name = "Renamed") }) + assertEquals(setOf(ParameterField.RANGE), fieldsAfter { entity -> entity.copy(max = 2f) }) + assertEquals(setOf(ParameterField.KIND), fieldsAfter { entity -> entity.copy(kind = ParameterKind.BLEND_SHAPE) }) + } + + /** A one-ULP float nudge is a reported change - the diff is bit-exact, never tolerance-based. */ + @Test + fun oneUlpFloatDifferenceIsReported() { + val baseline = puppet(parameters = listOf(parameter("ParamA", min = 0.5f))) + val nudgedMin = Float.fromBits(0.5f.toRawBits() + 1) + val edited = puppet(parameters = listOf(baseline.parameters.single().copy(min = nudgedMin))) + assertEquals(setOf(ParameterField.RANGE), onlyChangedFields(diffPuppetModels(baseline, edited).parameters)) + } + + /** A group rename flags only that group; its unchanged identity keeps the document tree quiet. */ + @Test + fun parameterGroupChangedFieldsAreExact() { + val groupId = ParameterGroupId("Group1") + + fun treeOf(group: ParameterNode.Group): List = listOf(group) + val baselineGroup = ParameterNode.Group(groupId, "Face", initiallyOpen = true, children = listOf(ParameterNode.Param(angleX))) + val baseline = puppet(parameterTree = treeOf(baselineGroup)) + + fun diffAfter(edited: ParameterNode.Group): PuppetDiff = diffPuppetModels(baseline, puppet(parameterTree = treeOf(edited))) + val renamed = diffAfter(baselineGroup.copy(name = "Body")) + assertEquals(setOf(ParameterGroupField.NAME), onlyChangedFields(renamed.parameterGroups)) + assertEquals(emptySet(), renamed.document, "a rename keeps the tree's identity sequence") + val collapsed = diffAfter(baselineGroup.copy(initiallyOpen = false)) + assertEquals(setOf(ParameterGroupField.INITIALLY_OPEN), onlyChangedFields(collapsed.parameterGroups)) + val emptied = diffAfter(baselineGroup.copy(children = emptyList())) + assertEquals(setOf(ParameterGroupField.CHILDREN), onlyChangedFields(emptied.parameterGroups)) + assertEquals(emptySet(), emptied.document, "group content is reported per group, not as a tree change") + } + + /** Adding a group is a Created entry AND a document tree change - the top level gained a node. */ + @Test + fun parameterGroupCreatedFlagsTheDocumentTree() { + val baseline = puppet(parameterTree = listOf(ParameterNode.Param(angleX))) + val added = ParameterNode.Group(ParameterGroupId("Group1"), "Face", initiallyOpen = true, children = emptyList()) + val diff = diffPuppetModels(baseline, puppet(parameterTree = listOf(ParameterNode.Param(angleX), added))) + assertEquals(listOf>(EntityDiff.Created(added.id)), diff.parameterGroups) + assertEquals(setOf(DocumentField.PARAMETER_TREE), diff.document) + } + + /** Part diffs: a shallow scalar (NAME), a reference list (CHILDREN), plus Created and Deleted. */ + @Test + fun partChangesAndSetDifference() { + val keptPart = part("PartKept") + val editablePart = part("PartEdited") + val baseline = puppet(parts = listOf(keptPart, editablePart, part("PartGone"))) + val edited = + puppet( + parts = + listOf( + keptPart, + editablePart.copy(name = "Renamed", children = listOf(OrgChild.Drawable(DrawableId("d1")))), + part("PartNew"), + ), + ) + val diff = diffPuppetModels(baseline, edited) + assertEquals( + listOf( + EntityDiff.Changed(editablePart.id, setOf(PartField.NAME, PartField.CHILDREN)), + EntityDiff.Deleted(PartId("PartGone")), + EntityDiff.Created(PartId("PartNew")), + ), + diff.parts, + ) + } + + /** Deformer diffs: warp lattice/geometry/statics fields, and a kind swap reports only KIND. */ + @Test + fun deformerChangesAndKindSwap() { + val warp = + Deformer.Warp( + id = DeformerId("Warp1"), + name = "Warp1", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = false, + geometryGrid = null, + ) + val baseline = puppet(deformers = listOf(warp)) + + fun fieldsAfter(edited: Deformer): Set = + onlyChangedFields(diffPuppetModels(baseline, puppet(deformers = listOf(edited))).deformers) + assertEquals(setOf(DeformerField.LATTICE), fieldsAfter(warp.copy(rows = 3))) + assertEquals(setOf(DeformerField.STATICS), fieldsAfter(warp.copy(opacity = 0.5f))) + assertEquals(setOf(DeformerField.PARENT), fieldsAfter(warp.copy(parent = DeformerId("Other")))) + val rotationUnderSameId = + Deformer.Rotation( + id = warp.id, + name = warp.name, + parent = null, + partId = null, + baseAngle = 0f, + geometryGrid = null, + ) + assertEquals(setOf(DeformerField.KIND), fieldsAfter(rotationUnderSameId), "a kind swap short-circuits the field walk") + } + + /** Drawable diffs: geometry grid, channel tracks, and the topology-vs-positions mesh split. */ + @Test + fun drawableChangedFieldsAreExact() { + val gridded = drawable("d1").copy(geometryGrid = deltaGrid(1f), channelGrids = opacityTrack(0.5f)) + val baseline = puppet(drawables = listOf(gridded)) + + fun fieldsAfter(edited: Drawable): Set = + onlyChangedFields(diffPuppetModels(baseline, puppet(drawables = listOf(edited))).drawables) + assertEquals(setOf(DrawableField.BLEND_MODE), fieldsAfter(gridded.copy(blendMode = BlendMode.Multiply))) + assertEquals(setOf(DrawableField.GEOMETRY), fieldsAfter(gridded.copy(geometryGrid = deltaGrid(2f)))) + assertEquals(setOf(DrawableField.CHANNELS), fieldsAfter(gridded.copy(channelGrids = opacityTrack(0.25f)))) + val mesh = gridded.mesh!! + val movedVertex = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 10f, 0f, 5f, 10f), + uvs = mesh.uvs, + indices = mesh.indices, + ) + assertEquals(setOf(DrawableField.MESH_POSITIONS), fieldsAfter(gridded.copy(mesh = movedVertex))) + val rewound = + DrawableMesh( + positions = mesh.positions, + uvs = mesh.uvs, + indices = intArrayOf(2, 1, 0), + ) + assertEquals(setOf(DrawableField.MESH_TOPOLOGY), fieldsAfter(gridded.copy(mesh = rewound))) + } + + /** A glue is keyed by its ORDERED mesh pair - reversing the pair is a delete plus a create. */ + @Test + fun glueKeyedByOrderedPairAndOrdinal() { + val meshA = DrawableId("a") + val meshB = DrawableId("b") + val weld = Glue(meshA, meshB, listOf(GluePair(0, 0, 0.5f, 0.5f))) + val baseline = puppet(drawables = listOf(drawable("a"), drawable("b")), glues = listOf(weld)) + val reversed = puppet(drawables = baseline.drawables, glues = listOf(Glue(meshB, meshA, weld.pairs))) + assertEquals( + setOf(GlueDiff.Deleted(meshA, meshB, 0), GlueDiff.Created(meshB, meshA, 0)), + diffPuppetModels(baseline, reversed).glues.toSet(), + ) + val doubled = puppet(drawables = baseline.drawables, glues = listOf(weld, Glue(meshA, meshB, weld.pairs))) + assertEquals(listOf(GlueDiff.Created(meshA, meshB, 1)), diffPuppetModels(baseline, doubled).glues) + } + + /** Each GlueField flags exactly its own edit - the full enum, one field per case. */ + @Test + fun glueChangedFieldsAreExact() { + val meshA = DrawableId("a") + val meshB = DrawableId("b") + val weld = Glue(meshA, meshB, listOf(GluePair(0, 0, 0.5f, 0.5f))) + val baseline = puppet(drawables = listOf(drawable("a"), drawable("b")), glues = listOf(weld)) + + fun fieldsAfter(edited: Glue): Set { + val diff = diffPuppetModels(baseline, puppet(drawables = baseline.drawables, glues = listOf(edited))).glues + return (diff.single() as GlueDiff.Changed).fields + } + assertEquals(setOf(GlueField.PAIRS), fieldsAfter(Glue(meshA, meshB, listOf(GluePair(0, 0, 0.9f, 0.5f))))) + assertEquals(setOf(GlueField.INTENSITY), fieldsAfter(Glue(meshA, meshB, weld.pairs, intensity = 0.5f))) + assertEquals(setOf(GlueField.CHANNELS), fieldsAfter(Glue(meshA, meshB, weld.pairs, channelGrids = opacityTrack(0.5f)))) + } + + /** Document-level edits flag their own field and nothing else. */ + @Test + fun documentFieldChangesAreExact() { + val baseline = puppet(parameters = listOf(parameter("ParamA"), parameter("ParamB"))) + val resized = diffPuppetModels(baseline, baseline.copy(canvasWidth = 200f)) + assertEquals(setOf(DocumentField.CANVAS_SIZE), resized.document) + assertTrue(resized.parameters.isEmpty()) + val retargeted = diffPuppetModels(baseline, baseline.copy(runtimeTarget = RuntimeTarget.entries.first { target -> target != RuntimeTarget.NoTarget })) + assertEquals(setOf(DocumentField.RUNTIME_TARGET), retargeted.document) + val reordered = diffPuppetModels(baseline, baseline.copy(parameters = baseline.parameters.reversed())) + assertEquals(setOf(DocumentField.PARAMETER_ORDER), reordered.document) + assertTrue(reordered.parameters.isEmpty(), "a pure reorder changes no parameter entity") + } + + /** + * A moved placement surfaces as exactly that tile's PLACEMENT, and nothing else. + * + * The completeness rule bites hardest here: an atlas change the diff misses is an atlas change the + * export silently drops, and a placement the file keeps while the model moved on leaves every mesh + * over it sampling the wrong pixels. + */ + @Test + fun atlasTileChangesAreExact() { + val tileId = AtlasTileId("tile0") + val placed = AtlasPlacement(0, 4f, 8f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f) + val baseline = + puppet().copy( + atlas = PuppetAtlas(listOf(AtlasPage(64, 64)), listOf(AtlasTile(tileId, "Art", 16, 16, placed))), + ) + + val moved = + diffPuppetModels( + baseline, + baseline.copy(atlas = baseline.atlas.copy(tiles = listOf(baseline.atlas.tiles.single().copy(placement = placed.copy(positionX = 40f))))), + ) + assertEquals( + listOf(EntityDiff.Changed(tileId, setOf(AtlasTileField.PLACEMENT))), + moved.atlasTiles, + ) + assertTrue(moved.document.isEmpty(), "moving art on a page changes no document field") + assertTrue(moved.drawables.isEmpty(), "and no drawable, when none is bound to it") + + val renamed = + diffPuppetModels( + baseline, + baseline.copy(atlas = baseline.atlas.copy(tiles = listOf(baseline.atlas.tiles.single().copy(name = "Other")))), + ) + assertEquals(listOf(EntityDiff.Changed(tileId, setOf(AtlasTileField.METADATA))), renamed.atlasTiles) + + // A source binding is what the art IS, so rebinding it reads as metadata like a rename does. + val rebound = + diffPuppetModels( + baseline, + baseline.copy( + atlas = + baseline.atlas.copy( + tiles = listOf(baseline.atlas.tiles.single().copy(source = SourceLayerRef(ArtSourceId("art-0"), "lyid:3", stableKey = true))), + ), + ), + ) + assertEquals(listOf(EntityDiff.Changed(tileId, setOf(AtlasTileField.METADATA))), rebound.atlasTiles) + + val repaged = diffPuppetModels(baseline, baseline.copy(atlas = baseline.atlas.copy(pages = listOf(AtlasPage(128, 128))))) + val record = ArtSource(ArtSourceId("art-0"), "a.psd", "/a.psd", "psd", listOf(ArtSourceLayer("lyid:3", "L", "", 0, 0, 4, 4, true))) + val listed = baseline.copy(sources = listOf(record)) + val relinked = diffPuppetModels(listed, listed.copy(sources = listOf(record.copy(path = "/elsewhere/a.psd")))) + assertEquals(setOf(DocumentField.SOURCE_FILES), relinked.document, "a source record pointing at another file is a document change") + val reloaded = diffPuppetModels(listed, listed.copy(sources = listOf(record.copy(contentHash = "other", layers = emptyList())))) + assertTrue(DocumentField.SOURCE_FILES !in reloaded.document, "a reload's inventory and hash are not") + val touched = diffPuppetModels(listed, listed.copy(sources = listOf(record.copy(lastModified = 123L)))) + assertEquals(setOf(DocumentField.SOURCE_FILES), touched.document, "the file's modification time is, since the CMO3 keeps it") + val foreign = diffPuppetModels(listed, listed.copy(sources = listOf(record.copy(id = ArtSourceId("page-0"), name = "page-0.png", path = null)))) + assertTrue(DocumentField.SOURCE_FILES !in foreign.document, "a record only one side lists (a fresh synthesis's page slices, art added this session) is not a repointed file") + assertEquals(setOf(DocumentField.ATLAS_PAGES), repaged.document, "the page list is document-level") + assertTrue(repaged.atlasTiles.isEmpty(), "resizing a page moves no tile") + + assertTrue(diffPuppetModels(baseline, baseline).isEmpty, "an untouched atlas is no difference at all") + } + + /** Rebinding a drawable to different art is a drawable-level difference the export must see. */ + @Test + fun aDrawableRetiedToDifferentArtSurfaces() { + val baseline = puppet(drawables = listOf(drawable("D1").copy(atlasTileId = AtlasTileId("tile0")))) + val rebound = + diffPuppetModels( + baseline, + baseline.copy(drawables = listOf(baseline.drawables.single().copy(atlasTileId = AtlasTileId("tile1")))), + ) + + assertEquals( + listOf(EntityDiff.Changed(DrawableId("D1"), setOf(DrawableField.ATLAS_TILE))), + rebound.drawables, + ) + } + + /** Diffs emit in BASELINE order regardless of the edited list's order, with creations appended. */ + @Test + fun changedEntitiesEmitInBaselineOrder() { + val partA = part("PartA") + val partB = part("PartB") + val partC = part("PartC") + val baseline = puppet(parts = listOf(partA, partB, partC)) + val edited = + puppet( + parts = + listOf( + part("PartNew"), + partC.copy(name = "RenamedC"), + partA, + partB.copy(name = "RenamedB"), + ), + ) + val diff = diffPuppetModels(baseline, edited) + assertEquals(listOf(PartId("PartB"), PartId("PartC"), PartId("PartNew")), diff.parts.map { entry -> entry.id }) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/RuntimeTargetMappingTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/RuntimeTargetMappingTest.kt new file mode 100644 index 0000000..af1db23 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/RuntimeTargetMappingTest.kt @@ -0,0 +1,84 @@ +package org.umamo.interop + +import org.umamo.format.cmo3.Cmo3TargetVersion +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.runtime.model.RuntimeTarget +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pins the RuntimeTarget ↔ format-version mapping per version boundary: the moc version each + * target bakes, the CMO3 target version each target persists as, and the target each decoded + * version selects on ingest. (The capability matrix itself is pinned in :runtime's + * RuntimeTargetTest.) + */ +class RuntimeTargetMappingTest { + @Test + fun mocVersionsMatchEachTargetsLevel() { + assertEquals(MocVersion.V53, RuntimeTarget.NoTarget.mocVersion(), "nothing restricted, bake latest") + assertEquals(MocVersion.V50, RuntimeTarget.Ayagami.mocVersion(), "Ayagami's effective level") + assertEquals(MocVersion.V30, RuntimeTarget.Cubism30.mocVersion()) + assertEquals(MocVersion.V33, RuntimeTarget.Cubism33.mocVersion()) + assertEquals(MocVersion.V40, RuntimeTarget.Cubism40.mocVersion()) + assertEquals(MocVersion.V42, RuntimeTarget.Cubism42.mocVersion()) + assertEquals(MocVersion.V50, RuntimeTarget.Cubism50.mocVersion()) + assertEquals(MocVersion.V53, RuntimeTarget.Cubism53.mocVersion()) + } + + @Test + fun cmo3TargetVersionsRoundTripPerTarget() { + assertNull(RuntimeTarget.NoTarget.cmo3TargetVersion(), "NoTarget has no target VERSION, only the sentinel") + assertEquals( + RuntimeTarget.Cubism50.cmo3TargetVersion(), + RuntimeTarget.Ayagami.cmo3TargetVersion(), + "Ayagami persists at its effective Cubism level", + ) + val cubismTargets = + listOf( + RuntimeTarget.Cubism30, + RuntimeTarget.Cubism33, + RuntimeTarget.Cubism40, + RuntimeTarget.Cubism42, + RuntimeTarget.Cubism50, + RuntimeTarget.Cubism53, + ) + cubismTargets.forEach { target -> + assertEquals(target, runtimeTargetOfCmo3Target(target.cmo3TargetVersion()), "round trip for $target") + } + // Ayagami's identity cannot survive CMO3 - it reopens as its effective Cubism level. + assertEquals(RuntimeTarget.Cubism50, runtimeTargetOfCmo3Target(RuntimeTarget.Ayagami.cmo3TargetVersion())) + } + + @Test + fun persistedVersionNoCoversEveryTarget() { + assertEquals( + Cmo3TargetVersion.LATEST_VERSION_NO, + RuntimeTarget.NoTarget.cmo3TargetVersionNo(), + "NoTarget persists as the SDK(N/A)/Latest sentinel", + ) + assertEquals(5_000_000, RuntimeTarget.Ayagami.cmo3TargetVersionNo(), "Ayagami persists as Cubism 5.0") + assertEquals(4_020_000, RuntimeTarget.Cubism42.cmo3TargetVersionNo(), "a Cubism target persists its literal") + // The sentinel round-trips through ingest: it decodes to no version, which maps to NoTarget. + assertEquals( + RuntimeTarget.NoTarget, + runtimeTargetOfCmo3Target(Cmo3TargetVersion.fromVersionNo(RuntimeTarget.NoTarget.cmo3TargetVersionNo())), + ) + } + + @Test + fun unknownCmo3TargetFallsBackToNoTarget() { + assertEquals(RuntimeTarget.NoTarget, runtimeTargetOfCmo3Target(null)) + assertEquals(RuntimeTarget.Cubism42, runtimeTargetOfCmo3Target(Cmo3TargetVersion.V42)) + } + + @Test + fun mocVersionsMapToTheirCubismTargets() { + assertEquals(RuntimeTarget.Cubism30, runtimeTargetOfMocVersion(MocVersion.V30)) + assertEquals(RuntimeTarget.Cubism33, runtimeTargetOfMocVersion(MocVersion.V33)) + assertEquals(RuntimeTarget.Cubism40, runtimeTargetOfMocVersion(MocVersion.V40)) + assertEquals(RuntimeTarget.Cubism42, runtimeTargetOfMocVersion(MocVersion.V42)) + assertEquals(RuntimeTarget.Cubism50, runtimeTargetOfMocVersion(MocVersion.V50)) + assertEquals(RuntimeTarget.Cubism53, runtimeTargetOfMocVersion(MocVersion.V53)) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/art/SourceArtImportTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/art/SourceArtImportTest.kt new file mode 100644 index 0000000..7b6ee7d --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/art/SourceArtImportTest.kt @@ -0,0 +1,492 @@ +package org.umamo.interop.art + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.OrgInsertion +import org.umamo.runtime.model.OrgSlot +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins what the bridge makes of a layered document: which layers become drawables and which are + * skipped with a note, the birth quad's geometry in both frames, the clipping and blend mappings, the + * folder-to-part tree with its order and its composites, the tiles and their source bindings, the + * source inventory, and the seeded parameters. Synthetic art throughout - the corpus twin is + * SourceArtImportCorpusTest. + */ +class SourceArtImportTest { + private class FixtureLayer( + override val id: LayerId, + override val idIsStable: Boolean, + override val name: String, + override val groupPath: String, + override val order: Int, + override val bounds: LayerBounds, + override val raster: LayerRaster, + override val kind: SourceLayerKind = SourceLayerKind.Raster, + override val visible: Boolean = true, + override val opacity: Float = 1f, + override val clipped: Boolean = false, + override val blend: LayerBlend = LayerBlend.Normal, + ) : SourceLayer + + private class FixtureGroup( + override val path: String, + override val name: String, + override val visible: Boolean = true, + override val opacity: Float = 1f, + override val clipped: Boolean = false, + override val blend: LayerBlend = LayerBlend.Normal, + override val passThrough: Boolean = true, + ) : SourceGroup + + private class FixtureArt( + override val widthPx: Int, + override val heightPx: Int, + override val layers: List, + override val groups: List = emptyList(), + ) : SourceArt + + /** A raster opaque inside [opaque] (raster-local) and transparent elsewhere; fully transparent when null. */ + private fun rasterOf(width: Int, height: Int, opaque: LayerBounds? = LayerBounds(0, 0, width, height)): LayerRaster { + val rgba = ByteArray(width * height * 4) + if (opaque != null) { + for (row in opaque.top until opaque.top + opaque.height) { + for (column in opaque.left until opaque.left + opaque.width) { + rgba[(row * width + column) * 4 + 3] = 0xFF.toByte() + } + } + } + return LayerRaster(width, height, rgba) + } + + private fun layer( + id: String, + name: String, + order: Int, + left: Int, + top: Int, + raster: LayerRaster, + groupPath: String = "", + stable: Boolean = true, + kind: SourceLayerKind = SourceLayerKind.Raster, + visible: Boolean = true, + opacity: Float = 1f, + clipped: Boolean = false, + blend: LayerBlend = LayerBlend.Normal, + ): FixtureLayer = + FixtureLayer( + id = LayerId(id), + idIsStable = stable, + name = name, + groupPath = groupPath, + order = order, + bounds = LayerBounds(left, top, raster.width, raster.height), + raster = raster, + kind = kind, + visible = visible, + opacity = opacity, + clipped = clipped, + blend = blend, + ) + + private val eyeRaster = rasterOf(10, 8, opaque = LayerBounds(2, 1, 4, 3)) + + /** The fixture, listed bottom-to-top the way the readers emit it; [SourceLayer.order] is what counts. */ + private fun fixture(): SourceArt = + FixtureArt( + widthPx = 200, + heightPx = 100, + layers = + listOf( + layer("lyid:7", "Lonely", order = 7, left = 5, top = 5, raster = rasterOf(3, 3), groupPath = "Solo", clipped = true), + layer("lyid:6", "Hidden", order = 6, left = 20, top = 20, raster = rasterOf(5, 5), groupPath = "Body/Arm", visible = false, opacity = 0.5f), + layer("lyid:5", "Odd", order = 5, left = 10, top = 0, raster = rasterOf(6, 6), blend = LayerBlend.Difference), + layer("Glow#4", "Glow", order = 4, left = 0, top = 0, raster = rasterOf(6, 6), stable = false, blend = LayerBlend.AddGlow), + layer("lyid:3", "Empty", order = 3, left = 0, top = 0, raster = rasterOf(4, 4, opaque = null), groupPath = "Head"), + layer("lyid:2", "Face", order = 2, left = 90, top = 40, raster = rasterOf(20, 20), groupPath = "Head"), + layer("lyid:1", "Eye", order = 1, left = 100, top = 50, raster = eyeRaster, groupPath = "Head", clipped = true), + layer("lyid:0", "Title", order = 0, left = 0, top = 0, raster = rasterOf(1, 1, opaque = null), groupPath = "Head", kind = SourceLayerKind.Text), + ), + groups = + listOf( + FixtureGroup("Head", "Head", visible = false), + FixtureGroup("Body", "Body", opacity = 0.5f, passThrough = false), + FixtureGroup("Body/Arm", "Arm"), + ), + ) + + private val descriptor = ArtSourceDescriptor(name = "fixture.psd", path = "/art/fixture.psd", format = "psd") + + @Test + fun rasterLayersWithArtBecomeDrawablesTopMostFirst() { + val result = SourceArtImport.fromSourceArt(fixture(), descriptor) + val puppet = result.puppet + + assertEquals(listOf("Eye", "Face", "Glow", "Odd", "Hidden", "Lonely"), puppet.drawables.map { drawable -> drawable.name }) + assertEquals((1..6).map { index -> DrawableId("ArtMesh$index") }, puppet.drawables.map { drawable -> drawable.id }, "ids follow the panel order") + assertEquals( + setOf( + SourceArtImportNotice.NonRasterLayer("Title", SourceLayerKind.Text), + SourceArtImportNotice.EmptyLayer("Empty"), + SourceArtImportNotice.BlendUnsupported("Odd", LayerBlend.Difference), + SourceArtImportNotice.ClipBaseMissing("Lonely"), + ), + result.notices.toSet(), + "every skipped or altered layer is named, and nothing else is", + ) + } + + /** The quad spans the opaque bounds plus the margin, in canvas pixels and in the art's own frame. */ + @Test + fun theBirthQuadIsTheOpaqueBoundsPlusTheMarginInBothFrames() { + val puppet = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val mesh = assertNotNull(puppet.drawables.first { drawable -> drawable.name == "Eye" }.mesh) + + // Opaque (2, 1) 4x3 in a 10x8 raster at canvas (100, 50), margin 2: the quad is (0, -1)..(8, 6) + // raster-local, so canvas (100, 49)..(108, 56) and art-frame (0, -1/8)..(0.8, 0.75). + assertTrue(mesh.positions.contentEquals(floatArrayOf(100f, 49f, 108f, 49f, 108f, 56f, 100f, 56f)), "positions: ${mesh.positions.toList()}") + assertTrue(mesh.uvs.contentEquals(floatArrayOf(0f, -0.125f, 0.8f, -0.125f, 0.8f, 0.75f, 0f, 0.75f)), "uvs: ${mesh.uvs.toList()}") + assertTrue(mesh.indices.contentEquals(intArrayOf(0, 1, 2, 0, 2, 3)), "two triangles over the four corners") + } + + @Test + fun aClippingLayerMasksByTheFirstUnclippedLayerBelowItInItsFolder() { + val puppet = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val byName = puppet.drawables.associateBy { drawable -> drawable.name } + + assertEquals(listOf(byName.getValue("Face").id), byName.getValue("Eye").maskedBy, "Eye clips to Face, the layer below it in Head") + assertTrue(byName.getValue("Lonely").maskedBy.isEmpty(), "a clipping layer with no base imports unclipped") + } + + @Test + fun blendVisibilityAndOpacityCarryOntoTheDrawable() { + val puppet = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val byName = puppet.drawables.associateBy { drawable -> drawable.name } + + assertEquals(BlendMode.AdditiveGlow, byName.getValue("Glow").blendMode) + assertEquals(BlendMode.Normal, byName.getValue("Odd").blendMode, "an unsupported blend falls back to Normal") + assertTrue(!byName.getValue("Hidden").isVisible, "a hidden layer imports hidden, not dropped") + assertEquals(0.5f, byName.getValue("Hidden").opacity) + assertTrue(byName.getValue("Eye").isVisible) + } + + /** Folders become parts nested by path, ordered where their top-most layer sits, composited when they must be. */ + @Test + fun foldersBecomePartsInPanelOrderWithTheirComposites() { + val puppet = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val byName = puppet.drawables.associateBy { drawable -> drawable.name } + val partById = puppet.parts.associateBy { part -> part.id } + + assertEquals(listOf("Head", "Body", "Arm", "Solo"), puppet.parts.map { part -> part.name }, "parts are minted in pre-order") + assertEquals((1..4).map { index -> PartId("Part$index") }, puppet.parts.map { part -> part.id }) + assertEquals( + listOf( + OrgChild.Part(PartId("Part1")), + OrgChild.Drawable(byName.getValue("Glow").id), + OrgChild.Drawable(byName.getValue("Odd").id), + OrgChild.Part(PartId("Part2")), + OrgChild.Part(PartId("Part4")), + ), + puppet.rootChildren, + "the root interleaves folders and layers in the file's own order", + ) + + val head = partById.getValue(PartId("Part1")) + assertEquals(listOf(OrgChild.Drawable(byName.getValue("Eye").id), OrgChild.Drawable(byName.getValue("Face").id)), head.children) + assertTrue(!head.isVisible, "a hidden folder imports as a hidden part") + assertEquals(PartGroupMode.PassThrough, head.groupMode, "a plain folder is pass-through") + + val body = partById.getValue(PartId("Part2")) + assertEquals(listOf(OrgChild.Part(PartId("Part3"))), body.children) + assertEquals(PartGroupMode.Isolated, body.groupMode, "a translucent folder must composite as one layer") + assertEquals(0.5f, body.composite.opacity) + assertEquals(BlendMode.Normal, body.composite.blendMode) + + assertEquals(listOf(OrgChild.Drawable(byName.getValue("Hidden").id)), partById.getValue(PartId("Part3")).children) + assertEquals("Solo", partById.getValue(PartId("Part4")).name, "a folder the reader did not describe is synthesized from the layer's path") + assertTrue(puppet.renderRoot.children.isNotEmpty(), "the render root is derived from the tree") + } + + @Test + fun everyDrawableGetsAnUnplacedTileBoundToItsSourceLayer() { + val result = SourceArtImport.fromSourceArt(fixture(), descriptor) + val puppet = result.puppet + val atlas = puppet.atlas + + assertTrue(atlas.pages.isEmpty(), "the bridge packs nothing") + assertTrue(atlas.storedUvsAddressPages, "but the coordinates are declared page-frame, so the pack at open re-derives them through the identity") + assertEquals(6, atlas.tiles.size) + assertTrue(atlas.tiles.all { tile -> tile.placement == null }, "every tile is unplaced") + + val eye = puppet.drawables.first { drawable -> drawable.name == "Eye" } + val eyeTile = assertNotNull(atlas.tileById[assertNotNull(eye.atlasTileId)]) + assertEquals(AtlasTileId("art-0/lyid:1"), eyeTile.id) + assertEquals(SourceLayerRef(ArtSourceId("art-0"), "lyid:1", stableKey = true), eyeTile.source) + assertEquals(10, eyeTile.width) + assertEquals(8, eyeTile.height) + assertSame(eyeRaster, result.rasterByTile[eyeTile.id], "the tile's pixels are the layer's own raster") + + val glowTile = assertNotNull(atlas.tileById[assertNotNull(puppet.drawables.first { drawable -> drawable.name == "Glow" }.atlasTileId)]) + assertEquals(false, assertNotNull(glowTile.source).stableKey, "a name-and-order key is recorded as unstable") + } + + /** The inventory marks a raster layer with no alpha anywhere as empty; every other row is not. */ + @Test + fun theInventoryMarksAnErasedLayerEmpty() { + val rows = SourceArtImport.inventoryOf(fixture()).associateBy { row -> row.key } + assertTrue(rows.getValue("lyid:3").empty, "the Empty layer has no alpha") + assertTrue(!rows.getValue("lyid:2").empty, "Face has art") + assertTrue(!rows.getValue("lyid:0").empty, "a text layer is not a raster erased to nothing") + } + + @Test + fun theSourceListRecordsTheFileAndEveryLayerSkippedOnesIncluded() { + val puppet = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val source = puppet.sources.single() + + assertEquals(ArtSourceId("art-0"), source.id) + assertEquals("fixture.psd", source.name) + assertEquals("/art/fixture.psd", source.path) + assertEquals("psd", source.format) + assertEquals(listOf("Title", "Eye", "Face", "Empty", "Glow", "Odd", "Hidden", "Lonely"), source.layers.map { entry -> entry.name }, "top-most first, nothing left out") + val eyeEntry = source.layers.first { entry -> entry.name == "Eye" } + assertEquals("lyid:1", eyeEntry.key) + assertEquals("Head", eyeEntry.groupPath) + assertEquals(listOf(100, 50, 10, 8), listOf(eyeEntry.left, eyeEntry.top, eyeEntry.width, eyeEntry.height)) + } + + @Test + fun theCanvasAndOriginAndDisplayModeMatchAFreshImport() { + val puppet = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + + assertEquals(200f, puppet.canvasWidth) + assertEquals(100f, puppet.canvasHeight) + assertEquals(100f, puppet.worldOriginX) + assertEquals(-50f, puppet.worldOriginZ, "the origin is the canvas center, y negated into world space") + assertTrue(puppet.rendersFromSourceLayers, "a fresh import shows the layers as drawn") + assertNull(puppet.pixelsPerUnit) + assertTrue(puppet.deformers.isEmpty()) + } + + @Test + fun theSeedParametersLandVerbatimOrNothingIsSeeded() { + val seed = + listOf( + Parameter(id = ParameterId("ParamAngleX"), name = "Angle X", min = -30f, max = 30f, default = 0f), + Parameter(id = ParameterId("ParamEyeLOpen"), name = "Eye L Open", min = 0f, max = 1f, default = 1f), + ) + val seeded = SourceArtImport.fromSourceArt(fixture(), descriptor, SourceArtImportOptions(parameters = seed)).puppet + val bare = SourceArtImport.fromSourceArt(fixture(), descriptor, SourceArtImportOptions()).puppet + + assertEquals(seed, seeded.parameters, "the bridge seeds exactly what it is handed, in order") + assertEquals( + seed.map { parameter -> ParameterNode.Param(parameter.id) }, + seeded.parameterTree, + "the tree is materialized flat, so an export places every parameter in the group hierarchy", + ) + assertTrue(bare.parameters.isEmpty(), "the bridge's own default seeds nothing; the template is the caller's policy") + assertTrue(bare.parameterTree.isEmpty()) + } + + /** + * Added to an open document, a file's ids continue the document's own sequences and its root + * order lands after the existing children - so the additions can be appended without a rename. + * The same additions over a blank model are exactly what a fresh import assembles. + */ + @Test + fun additionsContinueTheExistingIdSequences() { + val fresh = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val existing = + fresh.copy( + drawables = fresh.drawables.take(1).map { drawable -> drawable.copy(id = DrawableId("ArtMesh3")) }, + parts = fresh.parts.take(1).map { part -> part.copy(id = PartId("Part2"), children = emptyList()) }, + rootChildren = listOf(OrgChild.Part(PartId("Part2")), OrgChild.Drawable(DrawableId("ArtMesh3"))), + atlas = fresh.atlas.copy(tiles = fresh.atlas.tiles.take(1)), + ) + + val added = SourceArtImport.additionsFor(fixture(), ArtSourceDescriptor("second.psd", null, "psd"), SourceArtImportOptions(), existing).additions + assertEquals(ArtSourceId("art-1"), added.source.id, "the source continues past art-0") + assertEquals((4..9).map { index -> DrawableId("ArtMesh$index") }, added.drawables.map { drawable -> drawable.id }, "drawables continue past ArtMesh3") + assertEquals((3..6).map { index -> PartId("Part$index") }, added.parts.map { part -> part.id }, "parts continue past Part2") + assertTrue(added.tiles.all { tile -> tile.id.raw.startsWith("art-1/") }, "tiles are keyed under the new source") + assertTrue(added.tiles.all { tile -> tile.source?.sourceId == ArtSourceId("art-1") }) + assertEquals(5, added.rootChildren.size, "the file's own top-level order, to append after the existing children") + + val overBlank = SourceArtImport.additionsFor(fixture(), descriptor, SourceArtImportOptions(), fresh.copy(drawables = emptyList(), parts = emptyList(), rootChildren = emptyList(), atlas = PuppetAtlas.Empty, sources = emptyList())).additions + assertEquals(fresh.drawables.map { drawable -> drawable.id }, overBlank.drawables.map { drawable -> drawable.id }, "over a blank model the additions are the fresh import's") + } + + /** + * A reload's additions (under a listed source) mint only the folders the added layers live in; a + * folder the document already keeps as a part - found through the source's bindings, since a part + * carries no folder of its own - takes the layers as children instead of a second part of the same + * name; a new sub-folder inside such a part is minted as a new part under it; and every new child is + * placed among the existing children where the file puts it: after its nearest shown sibling above, + * else before its nearest below, so a layer added at the top of the file lands first. + */ + @Test + fun additionsUnderAListedSourceReuseTheDocumentsPartsAndPlaceByTheFilesOrder() { + val existing = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val existingByName = existing.drawables.associateBy { drawable -> drawable.name } + val headPart = existing.parts.first { part -> part.name == "Head" } + val bodyPart = existing.parts.first { part -> part.name == "Body" } + val armPart = existing.parts.first { part -> part.name == "Arm" } + val cap = layer("lyid:11", "Cap", order = -1, left = 0, top = 0, raster = rasterOf(2, 2)) + val brow = layer("lyid:8", "Brow", order = 8, left = 90, top = 30, raster = rasterOf(4, 4), groupPath = "Head") + val lash = layer("lyid:9", "Lash", order = 9, left = 95, top = 45, raster = rasterOf(3, 3), groupPath = "Head/Lashes") + val tail = layer("lyid:10", "Tail", order = 10, left = 0, top = 80, raster = rasterOf(6, 6), groupPath = "Body/Tail") + val wholeFile = + FixtureArt( + widthPx = 200, + heightPx = 100, + layers = fixture().layers + cap + brow + lash + tail, + groups = fixture().groups + FixtureGroup("Head/Lashes", "Lashes") + FixtureGroup("Body/Tail", "Tail"), + ) + val gained = setOf("lyid:11", "lyid:8", "lyid:9", "lyid:10") + + val added = SourceArtImport.additionsFor(wholeFile, descriptor, SourceArtImportOptions(), existing, underSource = ArtSourceId("art-0"), layerKeys = gained).additions + val byName = added.drawables.associateBy { drawable -> drawable.name } + assertEquals(listOf("Cap", "Brow", "Lash", "Tail"), added.drawables.map { drawable -> drawable.name }, "only the named layers are minted, top-most first") + assertEquals(listOf("Lashes", "Tail"), added.parts.map { part -> part.name }, "only the folders the document has no part for are minted; Head, Body, Arm, and Solo are not") + assertEquals(listOf(PartId("Part5"), PartId("Part6")), added.parts.map { part -> part.id }, "past the document's four parts") + assertTrue(added.rootChildren.isEmpty(), "a listed file appends nothing after the root; its new children are placed") + val lashes = added.parts.first { part -> part.name == "Lashes" } + val tailPart = added.parts.first { part -> part.name == "Tail" } + assertEquals(listOf(OrgChild.Drawable(byName.getValue("Lash").id)), lashes.children) + assertEquals( + listOf( + OrgInsertion(null, OrgChild.Drawable(byName.getValue("Cap").id), OrgSlot.Before(OrgChild.Part(headPart.id))), + OrgInsertion(headPart.id, OrgChild.Drawable(byName.getValue("Brow").id), OrgSlot.After(OrgChild.Drawable(existingByName.getValue("Face").id))), + OrgInsertion(headPart.id, OrgChild.Part(lashes.id), OrgSlot.After(OrgChild.Drawable(byName.getValue("Brow").id))), + OrgInsertion(bodyPart.id, OrgChild.Part(tailPart.id), OrgSlot.After(OrgChild.Part(armPart.id))), + ), + added.insertions, + "the top layer goes before the root's first folder; Brow after Face (the empty layer above it shows nothing); the new Lashes folder after Brow; the new Tail folder after Arm", + ) + + val fresh = SourceArtImport.additionsFor(wholeFile, ArtSourceDescriptor("other.psd", null, "psd"), SourceArtImportOptions(), existing).additions + assertEquals(listOf("Head", "Lashes", "Body", "Arm", "Tail", "Solo"), fresh.parts.map { part -> part.name }, "a NEW file still mints every folder it has, in pre-order") + assertTrue(fresh.insertions.isEmpty(), "and appends its whole tree after the root") + assertEquals(OrgChild.Drawable(fresh.drawables.first { drawable -> drawable.name == "Cap" }.id), fresh.rootChildren.first()) + } + + /** Two layers sharing a weak key still get distinct tiles, disambiguated by draw order. */ + @Test + fun aDuplicateLayerKeyIsDisambiguatedByOrder() { + val art = + FixtureArt( + widthPx = 10, + heightPx = 10, + layers = + listOf( + layer("Same#0", "Same", order = 0, left = 0, top = 0, raster = rasterOf(2, 2), stable = false), + layer("Same#0", "Same", order = 1, left = 4, top = 4, raster = rasterOf(2, 2), stable = false), + ), + ) + val puppet = SourceArtImport.fromSourceArt(art, descriptor).puppet + + assertEquals(listOf(AtlasTileId("art-0/Same#0"), AtlasTileId("art-0/Same#0#1")), puppet.atlas.tiles.map { tile -> tile.id }) + assertEquals(2, puppet.drawables.map { drawable -> drawable.atlasTileId }.toSet().size, "each drawable samples its own tile") + } + + /** + * Placing a file shifts every layer's bounds and nothing else: the rasters are the same instances + * (the decode memo and the texture cache key on them), the file's canvas and folders pass through, + * and a zero offset hands the art back untouched. + */ + @Test + fun placingAFileShiftsItsBoundsAndKeepsItsRasters() { + val art = fixture() + assertSame(art, art.placedBy(CanvasOffset.Zero), "a zero offset places nothing") + + val placed = art.placedBy(CanvasOffset(30, -10)) + assertEquals(art.widthPx to art.heightPx, placed.widthPx to placed.heightPx, "the file's own canvas passes through") + assertSame(art.groups, placed.groups) + for ((original, moved) in art.layers.zip(placed.layers)) { + assertSame(original.raster, moved.raster, "'${original.name}' keeps its raster instance") + assertEquals(LayerBounds(original.bounds.left + 30, original.bounds.top + 10, original.bounds.width, original.bounds.height), moved.bounds, "z is up, so a negative z lowers the layer") + assertEquals(original.id, moved.id) + assertEquals(original.groupPath, moved.groupPath) + assertEquals(original.clipped, moved.clipped) + } + val source = ArtSource(ArtSourceId("art-3"), "x.psd", null, "psd", offsetX = 4, offsetZ = 6) + assertEquals(LayerBounds(104, 44, 10, 8), art.placedFor(source).layers.first { layer -> layer.name == "Eye" }.bounds, "a record's offset places the same way") + } + + /** + * The anchor splits the room between the document's canvas and the file's by its fraction, rounded + * down, and the nudge is added on top - in world axes, so a file placed below the document's top edge + * carries a negative z; a file larger than the canvas overhangs it; a rig's first artwork and a + * document with no canvas are never placed. + */ + @Test + fun theOffsetFollowsTheAnchorAndTheNudge() { + val host = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet.copy(canvasWidth = 300f, canvasHeight = 250f) + val small = FixtureArt(widthPx = 101, heightPx = 50, layers = listOf(layer("lyid:0", "Dot", order = 0, left = 0, top = 0, raster = rasterOf(2, 2)))) + val large = FixtureArt(widthPx = 400, heightPx = 250, layers = small.layers) + + fun offsetOf(art: SourceArt, anchor: ArtworkAnchor, nudgeX: Int = 0, nudgeZ: Int = 0): CanvasOffset = + SourceArtImport.offsetFor(host, art, SourceArtImportOptions(anchor = anchor, nudgeX = nudgeX, nudgeZ = nudgeZ)) + + assertEquals(CanvasOffset(99, -100), offsetOf(small, ArtworkAnchor.Center), "199 x 200 of room, halved and rounded down; 100 px down the canvas is z = -100") + assertEquals(CanvasOffset(0, 0), offsetOf(small, ArtworkAnchor.TopLeft)) + assertEquals(CanvasOffset(199, -200), offsetOf(small, ArtworkAnchor.BottomRight)) + assertEquals(CanvasOffset(99, 0), offsetOf(small, ArtworkAnchor.Top)) + assertEquals(CanvasOffset(0, -100), offsetOf(small, ArtworkAnchor.Left)) + assertEquals(CanvasOffset(199, -100), offsetOf(small, ArtworkAnchor.Right)) + assertEquals(CanvasOffset(102, -104), offsetOf(small, ArtworkAnchor.Center, nudgeX = 3, nudgeZ = -4), "the nudge is added to the anchor's placement") + assertEquals(CanvasOffset(-50, 0), offsetOf(large, ArtworkAnchor.Center), "a wider file overhangs both sides by the same amount") + assertEquals(CanvasOffset(-100, 0), offsetOf(large, ArtworkAnchor.BottomRight)) + + val blank = host.copy(drawables = emptyList(), atlas = PuppetAtlas.Empty) + assertEquals(CanvasOffset.Zero, SourceArtImport.offsetFor(blank, small, SourceArtImportOptions(nudgeX = 7)), "a first artwork sets the canvas and is never placed") + assertTrue(SourceArtImport.isFirstArtwork(blank)) + assertTrue(!SourceArtImport.isFirstArtwork(host)) + assertEquals(CanvasOffset.Zero, SourceArtImport.offsetFor(host.copy(canvasWidth = 0f), small, SourceArtImportOptions()), "no canvas, nothing to place within") + } + + /** + * A placed file's birth quads sit at the placed positions, its inventory rows are recorded in the + * document frame, and its record keeps the offset; a listed file's additions keep the offset its + * record already carries, whatever the caller passes. + */ + @Test + fun additionsRecordTheOffsetTheFileWasPlacedBy() { + val existing = SourceArtImport.fromSourceArt(fixture(), descriptor).puppet + val offset = CanvasOffset(50, 20) + val added = SourceArtImport.additionsFor(fixture().placedBy(offset), ArtSourceDescriptor("second.psd", null, "psd"), SourceArtImportOptions(), existing, offset = offset).additions + + assertEquals(50 to 20, added.source.offsetX to added.source.offsetZ, "the new record keeps the offset") + val eye = assertNotNull(added.drawables.first { drawable -> drawable.name == "Eye" }.mesh) + assertTrue(eye.positions.contentEquals(floatArrayOf(150f, 29f, 158f, 29f, 158f, 36f, 150f, 36f)), "the quad is the fixture's, shifted right and UP: ${eye.positions.toList()}") + assertEquals(150 to 30, added.source.layers.first { row -> row.name == "Eye" }.let { row -> row.left to row.top }, "the inventory row is in the document frame") + + val listed = existing.copy(sources = existing.sources.map { source -> source.copy(offsetX = 8, offsetZ = 9) }) + val underListed = SourceArtImport.additionsFor(fixture(), descriptor, SourceArtImportOptions(), listed, underSource = ArtSourceId("art-0"), layerKeys = setOf("lyid:1"), offset = offset).additions + assertEquals(8 to 9, underListed.source.offsetX to underListed.source.offsetZ, "a listed file's record keeps its own offset") + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPagesTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPagesTest.kt new file mode 100644 index 0000000..1ae84d3 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPagesTest.kt @@ -0,0 +1,147 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.identity.Id +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Contract checks for [cmo3AtlasPages] over hand-built graphs. The walk takes a CModelSource plus an + * injected pixel lookup rather than a Cmo3Model, which is exactly what lets this run without a corpus + * `.cmo3` - and on every target, since the CMO3 node classes are commonMain. + * + * Only the WALK is covered here: which resources become pages and who samples them. Whether a page's + * bytes decode, and what a broken one costs, belongs to the renderer's shared builder and is covered by + * PuppetTexturesTest - this walk never decodes anything. + */ +class Cmo3AtlasPagesTest { + /** + * Builds an art mesh bound to [resource], mirroring the shape the CMO3 serializer produces. + * + * @param String drawableId The mesh's id string. + * @param CImageResource? resource The page it samples, or null for a texture with no source. + * @param Boolean premultiplied The page's GTexture2D.isPremultiplied flag. + * @return CArtMeshSource The assembled mesh. + */ + private fun artMesh(drawableId: String, resource: CImageResource?, premultiplied: Boolean = false): CArtMeshSource = + CArtMeshSource().apply { + id = Id("ArtMesh").apply { idstr = drawableId } + texture = + GTexture2D().apply { + srcImageResource = resource + isPremultiplied = premultiplied + } + } + + /** + * Wraps [meshes] in the drawable-source-set container a CModelSource holds them in. + * + * @param CArtMeshSource meshes The meshes to mount. + * @return CModelSource The assembled root. + */ + private fun modelSourceOf(vararg meshes: CArtMeshSource): CModelSource = + CModelSource().apply { + drawableSourceSet = CDrawableSourceSet().apply { _sources = meshes.toList() } + } + + @Test + fun sharedResourceIsFetchedOnceAndBothDrawablesPointAtIt() { + val page = CImageResource() + val root = modelSourceOf(artMesh("ArtMeshLeft", page), artMesh("ArtMeshRight", page)) + + var reads = 0 + val pageSet = + cmo3AtlasPages(root) { requested -> + reads++ + if (requested === page) byteArrayOf(1, 2, 3) else null + } + + assertEquals(1, pageSet.pageBytes.size, "one distinct resource is one atlas page") + assertEquals(0, pageSet.atlasIndexByDrawableId["ArtMeshLeft"]) + assertEquals(0, pageSet.atlasIndexByDrawableId["ArtMeshRight"]) + assertEquals(1, reads, "the shared page's bytes are fetched once, not per drawable") + } + + @Test + fun distinctResourcesBecomeDistinctPagesInEncounterOrder() { + val firstPage = CImageResource() + val secondPage = CImageResource() + val root = modelSourceOf(artMesh("ArtMeshFirst", firstPage), artMesh("ArtMeshSecond", secondPage)) + + val pageSet = + cmo3AtlasPages(root) { requested -> if (requested === firstPage) byteArrayOf(1) else byteArrayOf(2, 2) } + + assertEquals(2, pageSet.pageBytes.size) + assertEquals(0, pageSet.atlasIndexByDrawableId["ArtMeshFirst"]) + assertEquals(1, pageSet.atlasIndexByDrawableId["ArtMeshSecond"]) + assertEquals(1, pageSet.pageBytes[0].size, "page order follows drawable encounter order") + assertEquals(2, pageSet.pageBytes[1].size) + } + + @Test + fun aResourceCarryingNoBytesLeavesItsDrawablesUnbound() { + val goodPage = CImageResource() + val absentPage = CImageResource() + val root = + modelSourceOf( + artMesh("ArtMeshGood", goodPage), + artMesh("ArtMeshAbsent", absentPage), + artMesh("ArtMeshAbsentSibling", absentPage), + ) + + var reads = 0 + val pageSet = + cmo3AtlasPages(root) { requested -> + reads++ + if (requested === goodPage) byteArrayOf(1) else null + } + + // A resource that yielded nothing is a remembered answer too, so its second drawable costs no + // second lookup - two distinct resources, two reads. + assertEquals(2, reads, "each distinct resource is resolved once, failures included") + assertEquals(1, pageSet.pageBytes.size, "only the resource with bytes becomes a page") + assertEquals(0, pageSet.atlasIndexByDrawableId["ArtMeshGood"]) + assertNull(pageSet.atlasIndexByDrawableId["ArtMeshAbsent"], "a resource with no bytes is skipped") + assertNull(pageSet.atlasIndexByDrawableId["ArtMeshAbsentSibling"], "and so is everything else on it") + } + + @Test + fun meshesWithoutAnIdOrATextureAreSkipped() { + val page = CImageResource() + val unnamed = artMesh("", page) + val textureless = CArtMeshSource().apply { id = Id("ArtMesh").apply { idstr = "ArtMeshTextureless" } } + val root = modelSourceOf(unnamed, textureless, artMesh("ArtMeshReal", page)) + + val pageSet = cmo3AtlasPages(root) { byteArrayOf(1) } + + assertEquals(mapOf("ArtMeshReal" to 0), pageSet.atlasIndexByDrawableId) + } + + @Test + fun premultipliedIsTheOrFoldAcrossTextures() { + val page = CImageResource() + val straight = modelSourceOf(artMesh("ArtMeshA", page, premultiplied = false)) + val mixed = + modelSourceOf( + artMesh("ArtMeshA", page, premultiplied = false), + artMesh("ArtMeshB", page, premultiplied = true), + ) + + assertEquals(false, cmo3AtlasPages(straight) { byteArrayOf(1) }.premultipliedAlpha) + assertTrue(cmo3AtlasPages(mixed) { byteArrayOf(1) }.premultipliedAlpha, "any premultiplied texture sets it") + } + + @Test + fun aRootWithNoDrawableSourceSetYieldsNoPages() { + val pageSet = cmo3AtlasPages(CModelSource()) { byteArrayOf(1) } + + assertTrue(pageSet.pageBytes.isEmpty()) + assertTrue(pageSet.atlasIndexByDrawableId.isEmpty()) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/cmo3/Cmo3TextureFramesTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/cmo3/Cmo3TextureFramesTest.kt new file mode 100644 index 0000000..e20a756 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/cmo3/Cmo3TextureFramesTest.kt @@ -0,0 +1,215 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The CMO3 texture-frame rules over a hand-built graph: one model image with its raster and a reduced + * cache copy, one atlas page, and a drawable over each kind of image. + */ +class Cmo3TextureFramesTest { + /** The raster-to-cache scale every texture here carries (an art size over its 64-aligned padding). */ + private val cacheScaleU = 0.75f + private val cacheScaleV = 0.5f + + private val page = CImageResource() + private val raster = CImageResource() + private val copy = CImageResource() + private val modelImage = + CModelImage().apply { + _filteredImage = raster + cachedImageManager = + CCachedImageManager().apply { + cachedImages = + listOf( + CCachedImage().apply { _cachedImageResource = raster }, + CCachedImage().apply { + _cachedImageResource = copy + reductionRatio = 2 + }, + ) + } + } + + /** + * A drawable over [resource], packed (with an atlas-region input) or not. + * + * @param String drawableId The drawable's id string. + * @param CImageResource resource The image its texture names. + * @param Boolean packed Whether it carries an atlas-region input. + * @param Boolean scaled Whether its texture carries the cache scale rather than the identity. + * @return CArtMeshSource The drawable. + */ + private fun drawable(drawableId: String, resource: CImageResource, packed: Boolean, scaled: Boolean = true): CArtMeshSource = + CArtMeshSource().apply { + id = Id("ArtMesh").apply { idstr = drawableId } + texture = + GTexture2D().apply { + srcImageResource = resource + transformImageResource01toLogical01 = + CAffine().apply { + if (scaled) { + m00 = cacheScaleU + m11 = cacheScaleV + } + } + } + _extensions = + listOf( + CTextureInputExtension().apply { + _textureInputs = if (packed) listOf(CTextureInput_TextureAtlasRegion()) else emptyList() + }, + ) + } + + private val onPage = drawable("ArtMeshPage", page, packed = true, scaled = false) + private val onRaster = drawable("ArtMeshRaster", raster, packed = true) + private val onCopy = drawable("ArtMeshCopy", copy, packed = true) + private val unpacked = drawable("ArtMeshUnpacked", raster, packed = false) + + /** + * The graph holding every drawable, the page, and the model image. + * + * @return CModelSource The root. + */ + private fun modelSource(): CModelSource = + CModelSource().apply { + textureManager = + CTextureManager().apply { + _textureAtlases = listOf(CTextureAtlas().apply { cachedAtlasImage = page }) + _modelImageGroups = listOf(CModelImageGroup().apply { _modelImages = listOf(modelImage) }) + } + drawableSourceSet = CDrawableSourceSet().apply { _sources = listOf(onPage, onRaster, onCopy, unpacked) } + } + + /** + * Asserts two coordinate arrays agree to within float rounding. + * + * @param FloatArray expected The expected coordinates. + * @param FloatArray actual The coordinates produced. + * @param String message What is being compared. + */ + private fun assertClose(expected: FloatArray, actual: FloatArray, message: String) { + assertEquals(expected.size, actual.size, message) + for (componentIndex in expected.indices) { + assertTrue(abs(expected[componentIndex] - actual[componentIndex]) < 1e-6f, "$message: component $componentIndex is ${actual[componentIndex]}, not ${expected[componentIndex]}") + } + } + + @Test + fun eachDrawableStoresTheFrameOfWhatItsTextureNames() { + val frames = Cmo3TextureFrames(modelSource()) + + assertEquals(Cmo3StoredFrame.Page, frames.storedFrameOf(onPage), "a packed drawable over a page stores the page's frame") + assertEquals(Cmo3StoredFrame.Raster, frames.storedFrameOf(onRaster), "a packed drawable over its raster stores the raster's frame") + assertEquals(Cmo3StoredFrame.Cache, frames.storedFrameOf(onCopy), "a drawable over a reduced copy stores the cache frame") + assertEquals(Cmo3StoredFrame.Cache, frames.storedFrameOf(unpacked), "an unpacked drawable stores the cache frame") + assertTrue(frames.samplesReducedCopy(onCopy)) + assertFalse(frames.samplesReducedCopy(onRaster)) + assertFalse(frames.samplesReducedCopy(unpacked)) + } + + @Test + fun aReducedCopyIsShownFromItsModelImagesRaster() { + val frames = Cmo3TextureFrames(modelSource()) + + assertSame(raster, frames.renderedImageOf(onCopy), "the copy gives way to the raster it was reduced from") + assertSame(page, frames.renderedImageOf(onPage)) + assertSame(raster, frames.renderedImageOf(onRaster)) + assertTrue(frames.isShownFrom(onCopy, modelImage)) + assertTrue(frames.isShownFrom(onRaster, modelImage)) + assertFalse(frames.isShownFrom(onPage, modelImage)) + } + + @Test + fun cacheFrameCoordinatesInvertIntoTheRasterAndBack() { + val frames = Cmo3TextureFrames(modelSource()) + val stored = floatArrayOf(cacheScaleU, cacheScaleV, 0.3f, 0.1f) + + val model = frames.modelUvsOf(onCopy, stored) + assertClose(floatArrayOf(1f, 1f, 0.3f / cacheScaleU, 0.1f / cacheScaleV), model, "the cache frame's art edge is the raster's") + assertClose(stored, frames.storedUvsOf(onCopy, model), "the forward affine restores the stored coordinates") + assertSame(stored, frames.modelUvsOf(onRaster, stored), "a drawable storing its image's own frame is taken verbatim") + assertContentEquals(stored, frames.storedUvsOf(onRaster, stored), "and written back verbatim") + } + + @Test + fun aPlacedTilesCoordinatesGoOntoItsPageAndBackOff() { + val frames = Cmo3TextureFrames(modelSource()) + // The tile's model-to-art affine: its art occupies a quarter by a half of the page, from (0.25, 0.25). + val storedToArt = floatArrayOf(4f, 0f, -1f, 0f, 2f, -0.5f) + val stored = floatArrayOf(cacheScaleU * 0.5f, cacheScaleV * 0.5f, 0f, 0f) + + // Over a copy: out of the cache frame to the art's center (0.5, 0.5), then onto the page. + val model = frames.modelUvsOf(onCopy, stored, storedToArt) + assertClose(floatArrayOf(0.375f, 0.5f, 0.25f, 0.25f), model, "the art's center and corner land on the page") + assertClose(stored, frames.storedUvsOf(onCopy, model, storedToArt), "and come back off it into the cache frame") + // Over the raster: no cache step, the same placement. + val rasterModel = frames.modelUvsOf(onRaster, floatArrayOf(0.5f, 0.5f), storedToArt) + assertClose(floatArrayOf(0.375f, 0.5f), rasterModel, "a raster pair lands on the page") + assertClose(floatArrayOf(0.5f, 0.5f), frames.storedUvsOf(onRaster, rasterModel, storedToArt), "and comes back in the raster's frame") + // Over the page: already there, whatever the placement. + assertSame(stored, frames.modelUvsOf(onPage, stored, storedToArt), "page coordinates are taken verbatim") + assertContentEquals(stored, frames.storedUvsOf(onPage, stored, storedToArt), "and stored verbatim") + // An unplaced tile's identity affine changes nothing past the cache step. + assertClose(floatArrayOf(0.5f, 0.5f, 0f, 0f), frames.modelUvsOf(onCopy, stored, floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f)), "without a placement the raster frame is the model's") + } + + @Test + fun anUnchangedPairKeepsItsStoredBits() { + val frames = Cmo3TextureFrames(modelSource()) + val stored = floatArrayOf(0.3f, 0.7f, 0.1f, 0.2f) + val baseline = frames.modelUvsOf(onCopy, stored) + val edited = baseline.copyOf().also { uvs -> uvs[2] = 0.5f } + + val written = frames.storedUvsOf(onCopy, edited, storedUvs = stored, baselineUvs = baseline) + + assertEquals(stored[0].toRawBits(), written[0].toRawBits(), "the untouched pair keeps its stored u") + assertEquals(stored[1].toRawBits(), written[1].toRawBits(), "the untouched pair keeps its stored v") + assertClose(floatArrayOf(0.5f * cacheScaleU, baseline[3] * cacheScaleV), written.copyOfRange(2, 4), "the edited pair goes through the affine") + } + + @Test + fun theCopySetIsTakenAsReadAndOnlyARetargetedTextureLeavesTheCacheFrame() { + val frames = Cmo3TextureFrames(modelSource()) + + // A rewrite rebuilds the image's cache without the copy; the drawable still samples it. + modelImage.cachedImageManager = CCachedImageManager().apply { cachedImages = listOf(CCachedImage().apply { _cachedImageResource = raster }) } + assertEquals(Cmo3StoredFrame.Cache, frames.storedFrameOf(onCopy), "a cache rebuild does not change what the drawable's coordinates mean") + + // Retargeting the texture onto the raster does. + (onCopy.texture as GTexture2D).srcImageResource = raster + assertEquals(Cmo3StoredFrame.Raster, frames.storedFrameOf(onCopy), "a packed drawable moved onto its raster stores the raster's frame") + assertSame(raster, frames.renderedImageOf(onCopy)) + } + + @Test + fun anAtlasPageIsNeverAReducedCopy() { + modelImage.cachedImageManager = CCachedImageManager().apply { cachedImages = listOf(CCachedImage().apply { _cachedImageResource = page }) } + val frames = Cmo3TextureFrames(modelSource()) + + assertFalse(frames.isReducedCopy(page)) + assertEquals(Cmo3StoredFrame.Page, frames.storedFrameOf(onPage)) + assertSame(page, frames.renderedImageOf(onPage)) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3BlendShapeSpaceTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3BlendShapeSpaceTest.kt new file mode 100644 index 0000000..307c882 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3BlendShapeSpaceTest.kt @@ -0,0 +1,164 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A blend-shape owner's positional deltas are un-converted from ITS OWN parent's space. + * + * The blend pass is the third caller of the context's `spaceOfParent`, alongside the art-mesh and + * deformer lowerings, and the three must agree. Root space is the only one carrying the px→model + * divide, so resolving a parented owner as root scales its whole blend shape by the pixels-per-unit - + * a rig-scale error rather than a rounding one, and invisible in a document whose ppu happens to be 1. + * This rig therefore uses a ppu of 4 so the two arms cannot produce the same numbers. + */ +class Moc3BlendShapeSpaceTest { + private val morphParameter = ParameterId("ParamMorph") + private val poseParameter = ParameterId("ParamPose") + private val pixelsPerUnit = 4f + + /** The authored delta, chosen so dividing by [pixelsPerUnit] lands on exact binary fractions. */ + private val authoredDeltas = floatArrayOf(8f, -16f, 32f, 64f) + + /** + * A blend-shape binding carrying [authoredDeltas] at its non-neutral key. + * + * @return BlendShapeBinding The binding to hang on an owner. + */ + private fun morphBinding(): BlendShapeBinding = + BlendShapeBinding( + parameterId = morphParameter, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, MeshForm(authoredDeltas.copyOf())), + ) + + /** + * A drawable with a two-vertex mesh and one blend shape, under [parentDeformerId]. + * + * The mesh is present because the pass sizes its delta row from the vertex count. The geometry grid + * is all zeros rather than absent: a parented drawable with no grid has no parent-local form to + * write and export eligibility drops it, and zeros keep the subtracted default-pose reference at + * zero so the stored row is the authored delta converted, with nothing else folded in. + * + * @param String id The drawable id. + * @param DeformerId? parentDeformerId The owning deformer, null at the root. + * @return Drawable The drawable. + */ + private fun blendDrawable(id: String, parentDeformerId: DeformerId?): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = parentDeformerId, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = + DrawableMesh( + positions = FloatArray(authoredDeltas.size), + uvs = FloatArray(authoredDeltas.size), + indices = intArrayOf(0, 1, 0), + ), + geometryGrid = + KeyformGrid( + axes = listOf(KeyformAxis(poseParameter, floatArrayOf(0f, 1f))), + cells = + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(authoredDeltas.size))), + KeyformCell(intArrayOf(1), MeshDeltaForm(FloatArray(authoredDeltas.size))), + ), + ), + blendShapes = listOf(morphBinding()), + ) + + /** + * The stored art-mesh delta row of the named drawable's single blend shape at its non-neutral key. + * + * @param PuppetModel puppet The rig to export. + * @param String id The owning drawable's id. + * @return FloatArray The stored vertex-position row. + */ + private fun storedMeshRow(puppet: PuppetModel, id: String): FloatArray { + val document = Moc3Export.toMocDocument(puppet, MocVersion.V50).document + val drawableIndex = document.artMeshes.indexOfFirst { artMesh -> artMesh.id == id } + val record = + document.blendShapes.single { blendShape -> + blendShape.target == BlendShapeTarget.ART_MESH && blendShape.targetIndex == drawableIndex + } + return (record.keyforms[1] as BlendShapeKeyform.Mesh).form.vertexPositions + } + + @Test + fun aParentedOwnerStoresVerbatimWhileARootOwnerTakesThePpuDivide() { + val warp = + Deformer.Warp( + id = DeformerId("Warp1"), + name = "Warp1", + parent = null, + partId = PartId("Part1"), + rows = 1, + columns = 1, + isQuadTransform = false, + geometryGrid = null, + ) + val underWarp = blendDrawable("UnderWarp", warp.id) + val atRoot = blendDrawable("AtRoot", null) + val part = + Part( + id = PartId("Part1"), + name = "Part1", + children = listOf(OrgChild.Drawable(underWarp.id), OrgChild.Drawable(atRoot.id)), + ) + val puppet = + PuppetModel( + parameters = + listOf( + Parameter(morphParameter, "Morph", 0f, 1f, 0f, ParameterKind.BLEND_SHAPE), + Parameter(poseParameter, "Pose", 0f, 1f, 0f), + ), + parts = listOf(part), + deformers = listOf(warp), + drawables = listOf(underWarp, atRoot), + rootChildren = listOf(OrgChild.Part(part.id)), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + pixelsPerUnit = pixelsPerUnit, + ) + + // A warp parent's lattice is the same in both conventions, so the authored delta survives as-is. + assertEquals( + authoredDeltas.toList(), + storedMeshRow(puppet, "UnderWarp").toList(), + "a warp-parented blend shape must store its deltas verbatim", + ) + // Root space is the one that carries the affine, so the same delta divides by the ppu. + assertEquals( + authoredDeltas.map { delta -> delta / pixelsPerUnit }, + storedMeshRow(puppet, "AtRoot").toList(), + "a root blend shape must store its deltas in model units", + ) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ExportIdFitTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ExportIdFitTest.kt new file mode 100644 index 0000000..baf8eed --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ExportIdFitTest.kt @@ -0,0 +1,267 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Sections +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNotice +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * An id too wide for a moc's id record is shortened to fit, and the shortening never mints a duplicate. + * + * MOC3 §5.4 makes every id a fixed 64-byte record while CMO3 places no width limit on the same string, + * so an over-wide id is a rig a rigger can really author - 22 CJK characters already exceed the record. + * Truncating it is the only way to write it, and truncation is what creates the collision this guards: + * two names differing only past the 63rd byte truncate to one. A MOC3 addresses nothing by id, so the + * file takes the duplicate silently and the loss surfaces on the way back, where the import merges the + * two objects into one. + * + * Synthetic rather than corpus-backed on purpose: the corpus is what the official editor wrote, and its + * own ids all fit. + * + * @see MOC3.md §5.4 + */ +class Moc3ExportIdFitTest { + /** A name whose UTF-8 form runs well past the record, so every mesh below has to be shortened. */ + private val overlongStem = "あ".repeat(40) + + /** + * Builds a one-triangle drawable with no keyforms, parented to [partId]. + * + * @param String id The drawable's model id. + * @param PartId partId Its owning part. + * @return Drawable The drawable. + */ + private fun drawable( + id: String, + partId: PartId, + ): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + // Bound to a page, so the only notice a rig here can raise is about its ids. + texturePage = 0, + mesh = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + indices = intArrayOf(0, 1, 2), + ), + geometryGrid = null, + ) + + /** + * A rig whose drawables carry [ids], all under one part. + * + * @param List ids The drawable ids, in model order. + * @return PuppetModel The rig. + */ + private fun puppetWithDrawableIds(ids: List): PuppetModel { + val partId = PartId("Part1") + val drawables = ids.map { id -> drawable(id, partId) } + return PuppetModel( + parameters = emptyList(), + parts = listOf(Part(id = partId, name = "Part1", children = drawables.map { OrgChild.Drawable(it.id) })), + deformers = emptyList(), + drawables = drawables, + rootChildren = listOf(OrgChild.Part(partId)), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + ) + } + + /** + * Two ids that differ only past the record width must not be written as one name. + * + * The second is also checked for still FITTING: disambiguating by appending a suffix to an id + * already trimmed to the limit would push it back over, and the writer's own precondition would + * then reject the file the notice said it had written. + */ + @Test + fun idsTruncatingOntoEachOtherAreDisambiguated() { + val lowered = + Moc3Export.toMocDocument( + puppetWithDrawableIds(listOf(overlongStem + "左", overlongStem + "右")), + MocVersion.V50, + ) + + val writtenIds = lowered.document.artMeshes.map { artMesh -> artMesh.id } + assertEquals(2, writtenIds.toSet().size, "the two drawables were written under one id: $writtenIds") + for (writtenId in writtenIds) { + assertTrue( + writtenId.encodeToByteArray().size < Sections.ID_STRIDE, + "\"$writtenId\" does not fit a ${Sections.ID_STRIDE}-byte id record", + ) + } + // Each shortening is reported against the id the RIG carries, so the rigger can find the object + // the notice is about; the written name is on the reason. + val subjects = + lowered.report.notices + .filterIsInstance() + .filter { notice -> notice.category == ExportEntityCategory.Drawable } + .map { notice -> notice.subject } + assertEquals(listOf(overlongStem + "左", overlongStem + "右"), subjects, "both shortenings were reported") + } + + /** + * A shortened id never takes a name another object holds outright. + * + * The short drawable here is exactly what the long one truncates to, and it is written LAST - so + * resolving collisions in lowering order, as they came, would hand its own id away to the long one + * and rename the object that never needed shortening at all. + */ + @Test + fun aShortenedIdNeverTakesAnIdSomethingElseHoldsOutright() { + val overlong = "A".repeat(Sections.ID_STRIDE + 20) + val truncated = "A".repeat(Sections.ID_STRIDE - 1) + val lowered = Moc3Export.toMocDocument(puppetWithDrawableIds(listOf(overlong, truncated)), MocVersion.V50) + + val writtenIds = lowered.document.artMeshes.map { artMesh -> artMesh.id } + assertEquals(truncated, writtenIds[1], "the id that fits was written verbatim") + assertTrue(writtenIds[0] != truncated, "the shortened id took a name that was already spoken for") + } + + /** + * The cdi3 beside the MOC3 names the objects by the ids the MOC got, not the ones the model carries. + * + * The two files are joined on that string by every runtime and by Umamo's own import: a cdi3 built + * from the model's ids would name an object the MOC3 does not contain under that name, so the display + * name - the one thing the MOC3 cannot carry, which is the entire reason the cdi3 is written - is lost + * on exactly the objects whose ids had to be shortened. + */ + @Test + fun theCdi3NamesTheIdsTheMocWasWrittenWith() { + val bundle = + Moc3Sidecars.bundle( + puppetWithDrawableIds(listOf(overlongStem + "左", overlongStem + "右")), + basename = "rig", + version = MocVersion.V50, + pages = emptyList(), + ) + + val mocFile = bundle.files.first { file -> file.name == bundle.mocFileName } + val displayInfoFile = bundle.files.first { file -> file.name == "rig.cdi3.json" } + val writtenIds = Moc3.read(mocFile.bytes).artMeshes.map { artMesh -> artMesh.id } + val displayInfo = Moc3.readCdi3(displayInfoFile.bytes.decodeToString()) + + assertEquals( + writtenIds, + displayInfo.drawables.orEmpty().map { drawable -> drawable.id }, + "the cdi3 names drawables the moc does not contain", + ) + // And the pairing survives a round trip: each mesh gets its own name back rather than falling + // back to the shortened id. + val reimported = Moc3Import.fromMocDocument(Moc3.read(mocFile.bytes), displayInfo) + assertEquals( + setOf(overlongStem + "左", overlongStem + "右"), + reimported.drawables.mapTo(HashSet()) { drawable -> drawable.name }, + "a shortened drawable lost its display name", + ) + } + + /** + * The cdi3 names only the objects the moc contains - never one the export dropped. + * + * The mesh-less drawable here is dropped, and its id is exactly what the kept drawable's over-long id + * shortens to. A dropped object claims no id, so the shortening lands on that very string: naming + * the dropped one anyway would put TWO entries under a single id in the cdi3, and the import's join + * on that string would pick between them arbitrarily - handing a mesh a deleted object's name. + */ + @Test + fun theCdi3OmitsObjectsTheExportDropped() { + val overlong = "A".repeat(Sections.ID_STRIDE + 20) + val truncated = "A".repeat(Sections.ID_STRIDE - 1) + val partId = PartId("Part1") + val kept = drawable(overlong, partId) + // Mesh-less, so the eligibility pass drops it before the plan is built. + val dropped = drawable(truncated, partId).copy(mesh = null) + val sketchPartId = PartId("Sketch") + val puppet = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + Part(id = partId, name = "Part1", children = listOf(OrgChild.Drawable(kept.id), OrgChild.Drawable(dropped.id))), + Part(id = sketchPartId, name = "Sketch", children = emptyList(), isSketch = true), + ), + deformers = emptyList(), + drawables = listOf(kept, dropped), + rootChildren = listOf(OrgChild.Part(partId), OrgChild.Part(sketchPartId)), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + ) + + val bundle = Moc3Sidecars.bundle(puppet, basename = "rig", version = MocVersion.V50, pages = emptyList()) + val displayInfo = Moc3.readCdi3(bundle.files.first { file -> file.name == "rig.cdi3.json" }.bytes.decodeToString()) + + assertEquals( + listOf(truncated), + displayInfo.drawables.orEmpty().map { drawable -> drawable.id }, + "the cdi3 names a drawable the moc does not contain", + ) + assertEquals(overlong, displayInfo.drawables.orEmpty().single().name, "the entry is the kept mesh's, not the dropped one's") + assertEquals( + listOf("Part1"), + displayInfo.parts.map { part -> part.id }, + "the cdi3 names a sketch part the bake leaves out", + ) + } + + /** An id that fits is written verbatim and raises nothing. */ + @Test + fun idsThatFitAreWrittenVerbatimAndReportNothing() { + val lowered = Moc3Export.toMocDocument(puppetWithDrawableIds(listOf("ArtMesh1", "ArtMesh2")), MocVersion.V50) + + assertEquals(listOf("ArtMesh1", "ArtMesh2"), lowered.document.artMeshes.map { artMesh -> artMesh.id }) + assertEquals(emptyList(), lowered.report.notices, "a rig within the record width has nothing to report") + } + + /** Drawable moc ids come from sanitized display names, not Cubism ArtMeshN model ids. */ + @Test + fun drawableIdsPreferSanitizedDisplayNames() { + val partId = PartId("Part1") + val teeth = + drawable("ArtMesh13", partId).copy(name = "TopTeeth") + val drawstring = + drawable("ArtMesh3", partId).copy(name = "Right Drawstring") + val puppet = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + Part( + id = partId, + name = "Part1", + children = listOf(OrgChild.Drawable(teeth.id), OrgChild.Drawable(drawstring.id)), + ), + ), + deformers = emptyList(), + drawables = listOf(teeth, drawstring), + rootChildren = listOf(OrgChild.Part(partId)), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + ) + val lowered = Moc3Export.toMocDocument(puppet, MocVersion.V50) + assertEquals(listOf("TopTeeth", "Right_Drawstring"), lowered.document.artMeshes.map { artMesh -> artMesh.id }) + assertEquals(emptyList(), lowered.report.notices) + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ExportOptionsTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ExportOptionsTest.kt new file mode 100644 index 0000000..a8e129d --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ExportOptionsTest.kt @@ -0,0 +1,318 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * What [Moc3ExportOptions] includes and omits, and that the options-less default stays the carrying + * behavior the lowering always had. + * + * Synthetic rigs on purpose: the corpus is what the official editor wrote, and its bakes already had + * their hidden objects deleted or carried by the editor's own dialog - the option surface under test + * here is Umamo's. + */ +class Moc3ExportOptionsTest { + /** + * Builds a one-triangle drawable with no keyforms and no deformer parent. + * + * @param String id The drawable's model id. + * @param Boolean isVisible The drawable's own eyeball flag. + * @param List maskedBy The drawables whose alpha clips this one. + * @return Drawable The drawable. + */ + private fun drawable( + id: String, + isVisible: Boolean = true, + maskedBy: List = emptyList(), + ): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = maskedBy, + texturePage = 0, + isVisible = isVisible, + mesh = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f), + uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + indices = intArrayOf(0, 1, 2), + ), + geometryGrid = null, + ) + + /** + * A rig of the given parts, each owning the drawables its children name. + * + * @param List parts The parts, in panel order; all become root children. + * @param List drawables Every drawable the parts reference. + * @return PuppetModel The rig. + */ + private fun puppetOf( + parts: List, + drawables: List, + ): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = parts, + deformers = emptyList(), + drawables = drawables, + rootChildren = parts.map { part -> OrgChild.Part(part.id) }, + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + ) + + /** + * A rig with a hidden part whose subtree holds a visible child part, plus a visible part with + * one visible and one own-flag-hidden drawable. + * + * @return PuppetModel The rig. + */ + private fun puppetWithHiddenObjects(): PuppetModel { + val hiddenRootId = PartId("HiddenRoot") + val visibleChildId = PartId("VisibleChild") + val visiblePartId = PartId("VisiblePart") + val underHiddenRoot = drawable("UnderHiddenRoot") + val underVisibleChild = drawable("UnderVisibleChild") + val shown = drawable("Shown") + val ownFlagHidden = drawable("OwnFlagHidden", isVisible = false) + return puppetOf( + parts = + listOf( + Part( + id = hiddenRootId, + name = "HiddenRoot", + children = listOf(OrgChild.Drawable(underHiddenRoot.id), OrgChild.Part(visibleChildId)), + isVisible = false, + ), + Part(id = visibleChildId, name = "VisibleChild", children = listOf(OrgChild.Drawable(underVisibleChild.id))), + Part( + id = visiblePartId, + name = "VisiblePart", + children = listOf(OrgChild.Drawable(shown.id), OrgChild.Drawable(ownFlagHidden.id)), + ), + ), + drawables = listOf(underHiddenRoot, underVisibleChild, shown, ownFlagHidden), + ).copy( + // The child part sits under the hidden root, not at the model root. + rootChildren = listOf(OrgChild.Part(hiddenRootId), OrgChild.Part(visiblePartId)), + ) + } + + /** The reasons of every drop notice in [report], keyed by the dropped drawable's id. */ + private fun dropReasonsBySubject(report: List): Map = + report + .filterIsInstance() + .associate { notice -> notice.subject to notice.reason } + + /** The options-less export carries every hidden object with its flag clear, exactly as before. */ + @Test + fun defaultOptionsCarryHiddenObjectsWithTheFlagClear() { + val lowered = Moc3Export.toMocDocument(puppetWithHiddenObjects(), MocVersion.V50) + + assertEquals( + listOf("HiddenRoot", "VisibleChild", "VisiblePart"), + lowered.document.parts.map { part -> part.id }, + "a hidden part was dropped without the option asking for it", + ) + assertFalse( + lowered.document.parts.first { part -> part.id == "HiddenRoot" }.isVisible, + "the hidden part lost its cleared flag", + ) + assertEquals( + listOf("UnderHiddenRoot", "UnderVisibleChild", "Shown", "OwnFlagHidden"), + lowered.document.artMeshes.map { artMesh -> artMesh.id }, + ) + assertFalse( + lowered.document.artMeshes.first { artMesh -> artMesh.id == "OwnFlagHidden" }.isVisible, + "the hidden art mesh lost its cleared flag", + ) + assertEquals(emptyList(), lowered.report.notices, "carrying everything has nothing to report") + } + + /** Omitting hidden parts drops the whole subtree - the visible child part included - with notices. */ + @Test + fun omittingHiddenPartsDropsTheSubtree() { + val options = Moc3ExportOptions(exportHiddenParts = false) + val lowered = Moc3Export.toMocDocument(puppetWithHiddenObjects(), MocVersion.V50, options = options) + + assertEquals(listOf("VisiblePart"), lowered.document.parts.map { part -> part.id }) + assertEquals( + listOf("Shown", "OwnFlagHidden"), + lowered.document.artMeshes.map { artMesh -> artMesh.id }, + "a drawable under the hidden subtree survived", + ) + val reasons = dropReasonsBySubject(lowered.report.notices) + assertEquals(ExportNoticeReason.HiddenPartOmittedByExportOption, reasons["UnderHiddenRoot"]) + assertEquals( + ExportNoticeReason.HiddenPartOmittedByExportOption, + reasons["UnderVisibleChild"], + "the hidden-part cascade missed the visible child part's drawable", + ) + } + + /** Omitting hidden art meshes drops own-flag-hidden drawables and leaves their siblings intact. */ + @Test + fun omittingHiddenArtMeshesDropsOwnFlagHiddenDrawables() { + val options = Moc3ExportOptions(exportHiddenDrawables = false) + val lowered = Moc3Export.toMocDocument(puppetWithHiddenObjects(), MocVersion.V50, options = options) + + assertEquals( + listOf("UnderHiddenRoot", "UnderVisibleChild", "Shown"), + lowered.document.artMeshes.map { artMesh -> artMesh.id }, + "only the own-flag-hidden drawable should drop; hidden PARTS were not omitted", + ) + assertEquals( + ExportNoticeReason.HiddenDrawableOmittedByExportOption, + dropReasonsBySubject(lowered.report.notices)["OwnFlagHidden"], + ) + } + + /** A hidden mask a surviving drawable clips by is kept, flag clear, rather than unclipping it. */ + @Test + fun aHiddenMaskASurvivorReferencesIsKept() { + val partId = PartId("Part1") + val mask = drawable("Mask", isVisible = false) + val clipped = drawable("Clipped", maskedBy = listOf(mask.id)) + val unreferencedHidden = drawable("UnreferencedHidden", isVisible = false) + val puppet = + puppetOf( + parts = + listOf( + Part( + id = partId, + name = "Part1", + children = + listOf( + OrgChild.Drawable(mask.id), + OrgChild.Drawable(clipped.id), + OrgChild.Drawable(unreferencedHidden.id), + ), + ), + ), + drawables = listOf(mask, clipped, unreferencedHidden), + ) + val options = Moc3ExportOptions(exportHiddenDrawables = false) + val lowered = Moc3Export.toMocDocument(puppet, MocVersion.V50, options = options) + + assertEquals( + listOf("Mask", "Clipped"), + lowered.document.artMeshes.map { artMesh -> artMesh.id }, + "the referenced mask must survive; the unreferenced hidden drawable must not", + ) + assertFalse(lowered.document.artMeshes.first { artMesh -> artMesh.id == "Mask" }.isVisible) + assertEquals( + 1, + lowered.document.artMeshes.first { artMesh -> artMesh.id == "Clipped" }.maskDrawableIndices.size, + "the survivor's mask reference resolved to nothing", + ) + val reasons = dropReasonsBySubject(lowered.report.notices) + assertNull(reasons["Mask"], "the kept mask must not be reported as dropped") + assertEquals(ExportNoticeReason.HiddenDrawableOmittedByExportOption, reasons["UnreferencedHidden"]) + assertTrue( + lowered.report.notices.none { notice -> + notice is ExportNotice.UnsupportedChange && notice.reason is ExportNoticeReason.ClippingMaskNotInExport + }, + "keeping the mask should leave nothing for the mask filter to report", + ) + } + + /** Keeping guide-image parts writes the sketch subtree the default drops. */ + @Test + fun keepingGuideImagePartsWritesTheSketchSubtree() { + val sketchPartId = PartId("Sketch") + val guide = drawable("Guide") + val puppet = + puppetOf( + parts = + listOf( + Part(id = sketchPartId, name = "Sketch", children = listOf(OrgChild.Drawable(guide.id)), isSketch = true), + ), + drawables = listOf(guide), + ) + + val kept = Moc3Export.toMocDocument(puppet, MocVersion.V50, options = Moc3ExportOptions(exportGuideImageParts = true)) + assertEquals(listOf("Guide"), kept.document.artMeshes.map { artMesh -> artMesh.id }) + assertEquals(emptyList(), kept.report.notices, "a kept guide has nothing to report") + + val dropped = Moc3Export.toMocDocument(puppet, MocVersion.V50) + assertEquals(emptyList(), dropped.document.artMeshes, "the options-less default must still drop the sketch subtree") + } + + /** The scale override lands in the canvas record AND rescales the geometry with it. */ + @Test + fun pixelsPerUnitOverrideScalesTheBake() { + val partId = PartId("Part1") + val mesh = drawable("ArtMesh1") + val puppet = + puppetOf( + parts = listOf(Part(id = partId, name = "Part1", children = listOf(OrgChild.Drawable(mesh.id)))), + drawables = listOf(mesh), + ) + + val defaulted = Moc3Export.toMocDocument(puppet, MocVersion.V50) + // pixelsPerUnit is null on the rig, so the heuristic resolves to the canvas width. + assertEquals(100f, defaulted.document.canvas?.pixelsPerUnit) + + val doubled = + Moc3Export.toMocDocument(puppet, MocVersion.V50, options = Moc3ExportOptions(pixelsPerUnitOverride = 200f)) + assertEquals(200f, doubled.document.canvas?.pixelsPerUnit) + + // Twice the pixels per unit means every model-space position is half the size. The record and + // the geometry must come from the same number - a header-only override would fail this. + val defaultedPositions = defaulted.document.artMeshes.single().keyforms.single().vertexPositions + val doubledPositions = doubled.document.artMeshes.single().keyforms.single().vertexPositions + val coordinateIndex = defaultedPositions.indices.first { index -> abs(defaultedPositions[index]) > 1e-6f } + assertEquals( + defaultedPositions[coordinateIndex] / 2f, + doubledPositions[coordinateIndex], + 1e-6f, + "the geometry did not follow the overridden scale", + ) + } + + /** Opting the cdi3 out removes the file and the manifest's reference together. */ + @Test + fun omittingTheDisplayInfoDropsTheFileAndTheManifestReference() { + val partId = PartId("Part1") + val mesh = drawable("ArtMesh1") + val puppet = + puppetOf( + parts = listOf(Part(id = partId, name = "Part1", children = listOf(OrgChild.Drawable(mesh.id)))), + drawables = listOf(mesh), + ) + + val bundle = + Moc3Sidecars.bundle( + puppet, + basename = "rig", + version = MocVersion.V50, + pages = emptyList(), + options = Moc3ExportOptions(includeDisplayInfo = false), + ) + + assertTrue(bundle.files.none { file -> file.name == "rig.cdi3.json" }, "the opted-out cdi3 was still written") + val manifestFile = bundle.files.first { file -> file.name == "rig.model3.json" } + val manifest = Moc3.readModel3(manifestFile.bytes.decodeToString()) + assertNull(manifest.fileReferences.displayInfo, "the manifest still references the opted-out cdi3") + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ImportIdentityTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ImportIdentityTest.kt new file mode 100644 index 0000000..9ff82f5 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3ImportIdentityTest.kt @@ -0,0 +1,265 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.moc.CanvasInfo +import org.umamo.format.moc3.moc.MocParameter +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.ParameterType +import org.umamo.format.moc3.model.ArtMesh +import org.umamo.format.moc3.model.ArtMeshKeyform +import org.umamo.format.moc3.model.Deformer +import org.umamo.format.moc3.model.KeyformBinding +import org.umamo.format.moc3.model.Part +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.format.moc3.model.WarpKeyform +import org.umamo.interop.moc3.import.Moc3Import +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Hand-built-document tests for the two identity fallbacks [Moc3Import] applies when a MOC3 does not + * carry what the corpus always carries: a blank or duplicated id (MOC3 §5.4) and an absent + * deformer→part column (s15). + * + * The corpus cannot reach either path - every sample has unique non-empty ids and an s15 that places + * something - so these are synthetic documents rather than corpus gates. The inputs are exactly the + * shapes a stripped, third-party, or synthesized MOC3 produces, which is the case `MocDecoder` reads + * the block's common head defensively for. + * + * @see MOC3.md §5.4 + */ +class Moc3ImportIdentityTest { + /** + * Builds a one-keyform warp deformer (a 2x2 lattice), static on binding 0. + * + * @param String id The s11 id, possibly blank. + * @param Int parentPartIndex The s15 part index, -1 at the root. + * @return WarpDeformer The deformer. + */ + private fun staticWarp(id: String, parentPartIndex: Int): WarpDeformer = + WarpDeformer( + id = id, + keyformBindingIndex = 0, + isVisible = true, + isEnabled = true, + parentPartIndex = parentPartIndex, + parentDeformerIndex = -1, + rows = 1, + columns = 1, + mode = 0, + keyforms = listOf(WarpKeyform(FloatArray(8), opacity = 1f, multiplyColor = null, screenColor = null)), + ) + + /** + * Builds a one-keyform, one-triangle art mesh, static on binding 0. + * + * @param String id The s33 id. + * @param Int parentPartIndex The s39 part index, -1 at the root. + * @param Int parentDeformerIndex The s40 deformer index, -1 when parented to the part. + * @return ArtMesh The drawable. + */ + private fun staticMesh(id: String, parentPartIndex: Int, parentDeformerIndex: Int): ArtMesh = + ArtMesh( + id = id, + textureIndex = 0, + constantFlags = 0, + parentPartIndex = parentPartIndex, + parentDeformerIndex = parentDeformerIndex, + vertexUvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + triangleIndices = shortArrayOf(0, 1, 2), + maskDrawableIndices = IntArray(0), + keyformBindingIndex = 0, + keyforms = + listOf( + ArtMeshKeyform( + vertexPositions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + opacity = 1f, + drawOrder = 500f, + multiplyColor = null, + screenColor = null, + ), + ), + ) + + /** + * Assembles a document around the given deformers and meshes. Binding 0 is the zero-axis static + * binding every corpus file reserves, which is what makes every object here static. + * + * @param List deformers The deformer list, in file order. + * @param List artMeshes The drawable list, in file order. + * @param List parts The part list, in file order. + * @param List parameters The parameter list, in file order. + * @return MocDocument The assembled document. + */ + private fun documentOf( + deformers: List, + artMeshes: List, + parts: List = listOf(part("PartHead"), part("PartBody")), + parameters: List = emptyList(), + ): MocDocument = + MocDocument( + version = MocVersion.V50, + canvas = CanvasInfo(pixelsPerUnit = 1f, originX = 0f, originY = 0f, width = 100f, height = 100f), + parameters = parameters, + keyformBindings = mapOf(0 to KeyformBinding(index = 0, axes = emptyList())), + parts = parts, + deformers = deformers, + artMeshes = artMeshes, + glues = emptyList(), + renderOrderGroups = emptyList(), + ) + + /** + * Builds a static root part. + * + * @param String id The part id. + * @return Part The part. + */ + private fun part(id: String): Part = + Part(id = id, parentPartIndex = -1, keyformBindingIndex = 0, drawOrderKeyforms = floatArrayOf(0f)) + + /** + * Builds a plain parameter axis. + * + * @param String id The parameter id. + * @param Float defaultValue Its default, which is also what the keyform grid samples at rest. + * @return MocParameter The parameter. + */ + private fun parameter( + id: String, + defaultValue: Float, + ): MocParameter = + MocParameter( + id = id, + minimumValue = -30f, + maximumValue = 30f, + defaultValue = defaultValue, + type = ParameterType.NORMAL, + ) + + /** + * A blank id, a duplicate id, and a file id that collides with what the synthesizer would have + * produced must all still yield distinct runtime ids, with the file's own ids kept verbatim. + * + * The collision is the interesting slot: deformer 0 is blank, so it synthesizes from its index and + * would take "Deformer0" - which deformer 3 already carries in the file. The synthesizer has to + * dodge it rather than duplicate it, because the org tree and every cross-reference key off the id. + */ + @Test + fun blankDuplicateAndCollidingDeformerIdsResolveDistinctly() { + val document = + documentOf( + deformers = + listOf( + staticWarp(id = "", parentPartIndex = 0), + staticWarp(id = "A", parentPartIndex = 0), + staticWarp(id = "A", parentPartIndex = 0), + staticWarp(id = "Deformer0", parentPartIndex = 0), + ), + artMeshes = emptyList(), + ) + + val ids = Moc3Import.fromMocDocument(document, displayInfo = null).deformers.map { it.id.raw } + + assertEquals(4, ids.toSet().size, "every deformer id is distinct: $ids") + // The first claimant of a file id keeps it; the later duplicate is the one that gets renamed. + assertEquals("A", ids[1], "first claimant keeps its file id") + assertTrue(ids[2] != "A", "the duplicate slot does not reuse the id") + // A real file id always outranks a synthesized one, even when the synthesizer wanted it first. + assertEquals("Deformer0", ids[3], "a file id is kept verbatim") + assertTrue(ids[0] != "Deformer0", "the synthesized id dodges the file id it would have collided with") + } + + /** + * The same rule holds for the other three id spaces, which a moc leaves just as unconstrained. + * + * Reachable through Umamo's own export, not only through a hand-built file: an id too wide for the + * 64-byte record is written shortened, so two names differing past the 63rd byte can arrive here as + * one. Merging them would put both meshes' masks, part membership, and keyforms on one drawable and + * leave the other with none - a silent identity merge on a round trip, which is why every id space + * de-duplicates rather than only the deformers'. + */ + @Test + fun duplicateParameterPartAndDrawableIdsResolveDistinctly() { + val document = + documentOf( + deformers = emptyList(), + artMeshes = + listOf( + staticMesh("Mesh", parentPartIndex = 0, parentDeformerIndex = -1), + staticMesh("Mesh", parentPartIndex = 1, parentDeformerIndex = -1), + ), + parts = listOf(part("Part"), part("Part")), + parameters = listOf(parameter("ParamAngleX", defaultValue = 0f), parameter("ParamAngleX", defaultValue = 30f)), + ) + + val puppet = Moc3Import.fromMocDocument(document, displayInfo = null) + + val parameterIds = puppet.parameters.map { it.id.raw } + assertEquals(2, parameterIds.toSet().size, "every parameter id is distinct: $parameterIds") + assertEquals("ParamAngleX", parameterIds[0], "the first claimant keeps its file id") + // Both defaults survive: an id-keyed lookup over the raw file ids would give the first parameter + // the second's default, which is what a blend record on it would then be resolved against. + assertEquals(listOf(0f, 30f), puppet.parameters.map { it.default }, "each parameter keeps its own default") + val drawableIds = puppet.drawables.map { it.id.raw } + assertEquals(2, drawableIds.toSet().size, "every drawable id is distinct: $drawableIds") + assertTrue("Mesh" in drawableIds, "the first claimant keeps its file id") + val partIds = puppet.parts.map { it.id.raw } + assertEquals(2, partIds.toSet().size, "every part id is distinct: $partIds") + assertEquals("Part", partIds[0], "the first claimant keeps its file id") + // Each part keeps its OWN drawable rather than both landing in one: the merge this guards against + // is invisible in an id list, but it shows up here as an empty part. + assertTrue( + puppet.parts.all { part -> part.children.size == 1 }, + "each part keeps its own drawable: ${puppet.parts.map { part -> part.children.size }}", + ) + } + + /** + * With s15 absent (every deformer at -1) the org tree would be flat, so membership is inferred from + * the drawables each deformer deforms. + */ + @Test + fun deformerPartsAreInferredWhenSection15PlacesNothing() { + val document = + documentOf( + deformers = listOf(staticWarp("Warp0", parentPartIndex = -1), staticWarp("Warp1", parentPartIndex = -1)), + artMeshes = + listOf( + staticMesh("Mesh0", parentPartIndex = 0, parentDeformerIndex = 0), + staticMesh("Mesh1", parentPartIndex = 1, parentDeformerIndex = 1), + ), + ) + + val deformers = Moc3Import.fromMocDocument(document, displayInfo = null).deformers.associateBy { it.id.raw } + + assertEquals("PartHead", deformers.getValue("Warp0").partId?.raw, "inferred from its own drawable") + assertEquals("PartBody", deformers.getValue("Warp1").partId?.raw, "inferred from its own drawable") + } + + /** + * s15 is authoritative: when it places even one deformer, nothing is inferred - a deformer the file + * really does put at the root stays there rather than being pulled into a drawable's part. + */ + @Test + fun section15WinsWheneverItPlacesAnything() { + val document = + documentOf( + // Warp1 is deliberately at the root while deforming a drawable that lives in PartBody - + // exactly the disagreement inference would "fix" if it were allowed to run. + deformers = listOf(staticWarp("Warp0", parentPartIndex = 0), staticWarp("Warp1", parentPartIndex = -1)), + artMeshes = + listOf( + staticMesh("Mesh0", parentPartIndex = 0, parentDeformerIndex = 0), + staticMesh("Mesh1", parentPartIndex = 1, parentDeformerIndex = 1), + ), + ) + + val deformers = Moc3Import.fromMocDocument(document, displayInfo = null).deformers.associateBy { it.id.raw } + + assertEquals("PartHead", deformers.getValue("Warp0").partId?.raw, "s15 placement is kept") + assertNull(deformers.getValue("Warp1").partId, "a root deformer stays at the root") + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3SpaceSeamTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3SpaceSeamTest.kt new file mode 100644 index 0000000..4b70286 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3SpaceSeamTest.kt @@ -0,0 +1,102 @@ +package org.umamo.interop.moc3 + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The MOC3 coordinate seam round-trips to float precision. + * + * Every value an export writes goes through one of these inverses, so a discrepancy here is a + * discrepancy in every exported position at once - and one that a semantic round trip cannot see, + * because it would convert and unconvert with the same wrong pair and cancel. + * + * The rotation scale seam gets its own case because it is the one piece of this that is not a + * per-value transform: which factor applies depends on a deformer's ANCESTRY, so the two directions + * can agree on the arithmetic and still disagree on which deformers it applies to. + */ +class Moc3SpaceSeamTest { + private val canvas = MocCanvasMapping(pixelsPerUnit = 900f, originX = 450f, originY = 600f) + + /** Values chosen to span sign, magnitude, and zero rather than a single happy sample. */ + private val points = floatArrayOf(0f, 0f, 1.5f, -2.25f, -1000f, 1000f, 0.001f, -0.001f) + + @Test + fun pointsRoundTripThroughEverySpace() { + for (space in PointSpace.entries) { + val stored = convertPointsToMoc(space, convertPointsToRuntime(space, points, canvas), canvas) + for (index in points.indices) { + assertTrue( + kotlin.math.abs(stored[index] - points[index]) <= 1e-3f, + "$space point[$index]: ${points[index]} -> ${stored[index]}", + ) + } + } + } + + @Test + fun deltasRoundTripThroughEverySpace() { + for (space in PointSpace.entries) { + val stored = convertDeltasToMoc(space, convertDeltasToRuntime(space, points, canvas), canvas) + for (index in points.indices) { + assertTrue( + kotlin.math.abs(stored[index] - points[index]) <= 1e-3f, + "$space delta[$index]: ${points[index]} -> ${stored[index]}", + ) + } + } + } + + /** + * A delta must NOT pick up the canvas origin - it cancels out of a difference - while a point must. + * Getting this wrong shifts every keyed offset by the origin, which looks like a plausible rig at + * the default pose and falls apart the moment a parameter moves. + */ + @Test + fun rootSpaceDeltasScaleButDoNotTranslate() { + val delta = floatArrayOf(1f, 1f) + val asDelta = convertDeltasToRuntime(PointSpace.ModelRoot, delta, canvas) + val asPoint = convertPointsToRuntime(PointSpace.ModelRoot, delta, canvas) + assertEquals(900f, asDelta[0], "a root delta scales by ppu alone") + assertEquals(450f + 900f, asPoint[0], "a root point also translates by the origin") + } + + /** A zero pixels-per-unit substitutes a unit scale, so the stored values stay finite rather than infinite. */ + @Test + fun aDegenerateCanvasIsTheIdentity() { + val degenerate = MocCanvasMapping(pixelsPerUnit = 0f, originX = 0f, originY = 0f) + val stored = convertPointsToMoc(PointSpace.ModelRoot, points, degenerate) + for (value in stored) { + assertTrue(value.isFinite(), "a zero ppu must not produce infinities: $value") + } + } + + /** + * Only the FIRST rotation on each root path carries the px→model factor. + * + * Chain: rootRotation -> warp -> nestedRotation. The nested rotation's direct parent is a WARP, so + * a predicate that only looked at the immediate parent would wrongly give it the factor too - the + * question is whether a rotation appears anywhere above, not directly above. + */ + @Test + fun onlyTheFirstRotationOnAPathCarriesTheUnitFactor() { + val parents = intArrayOf(-1, 0, 1) + val isRotation = booleanArrayOf(true, false, true) + val flags = rotationAncestorFlags(3, { parents[it] }, { isRotation[it] }) + + assertTrue(!flags[0], "the root rotation has no rotation above it") + assertTrue(flags[1], "the warp sits under a rotation") + assertTrue(flags[2], "the nested rotation sits under one too, through the warp") + + assertEquals(900f, rotationScaleFactor(flags[0], canvas), "the first rotation carries the factor") + assertEquals(1f, rotationScaleFactor(flags[2], canvas), "a nested rotation inherits it instead") + } + + /** A malformed parent cycle terminates instead of hanging the export. */ + @Test + fun aCyclicParentChainTerminates() { + val parents = intArrayOf(1, 0) + val flags = rotationAncestorFlags(2, { parents[it] }, { false }) + assertTrue(flags.none { it }, "no rotation exists, cycle or not") + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3VersionDowngradeTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3VersionDowngradeTest.kt new file mode 100644 index 0000000..bf5a3cd --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/moc3/Moc3VersionDowngradeTest.kt @@ -0,0 +1,270 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.interop.ExportNotice +import org.umamo.interop.moc3.export.Moc3VersionDowngrade +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.unsupportedFeaturesInUse +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The version strip removes exactly what the target cannot load, and says what it removed. + * + * Built on one kitchen-sink rig rather than a model per feature, because the interesting property is + * that the strips COMPOSE: a Cubism 3.0 export runs eight of them over the same model in sequence, + * and a strip that rebuilt a list from the original instead of from the running copy would silently + * undo whichever strip ran before it. + * + * The corpus-backed half of this lives in `Moc3DowngradeOracleTest`, which proves the stripped files + * actually load; this half proves the model-level rules without needing a corpus or a C core. + */ +class Moc3VersionDowngradeTest { + private val morphParameter = ParameterId("ParamMorph") + + /** A rig using every restricted feature that [PuppetModel] can express. */ + private fun kitchenSink(): PuppetModel { + val warp = + Deformer.Warp( + id = DeformerId("Warp1"), + name = "Warp1", + parent = null, + partId = PartId("Part1"), + rows = 2, + columns = 2, + isQuadTransform = true, + geometryGrid = null, + multiplyColor = ColorRgb(0.5f, 0.5f, 0.5f), + blendShapes = + listOf( + BlendShapeBinding( + parameterId = morphParameter, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, WarpForm(FloatArray(8))), + ), + ), + ) + val rotation = + Deformer.Rotation( + id = DeformerId("Rotation1"), + name = "Rotation1", + parent = null, + partId = PartId("Part1"), + baseAngle = 0f, + geometryGrid = null, + screenColor = ColorRgb(0.25f, 0.25f, 0.25f), + blendShapes = + listOf( + BlendShapeBinding( + parameterId = morphParameter, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, null), + ), + ), + ) + val drawable = + Drawable( + id = DrawableId("ArtMesh1"), + name = "ArtMesh1", + parentDeformerId = null, + blendMode = BlendMode.Overlay, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + alphaBlendMode = AlphaBlendMode.Atop, + invertMask = true, + blendShapes = + listOf( + BlendShapeBinding( + parameterId = morphParameter, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, MeshForm(FloatArray(0))), + ), + ), + ) + val part = + Part( + id = PartId("Part1"), + name = "Part1", + children = listOf(OrgChild.Drawable(drawable.id)), + groupMode = PartGroupMode.Isolated, + composite = + PartComposite( + blendMode = BlendMode.Screen, + alphaBlendMode = AlphaBlendMode.Out, + invertMask = true, + multiplyColor = ColorRgb(0.5f, 0.5f, 0.5f), + ), + ) + return PuppetModel( + parameters = + listOf( + Parameter(morphParameter, "Morph", 0f, 1f, 0f, ParameterKind.BLEND_SHAPE), + Parameter(ParameterId("ParamWheel"), "Wheel", 0f, 360f, 0f, repeat = true), + ), + parts = listOf(part), + deformers = listOf(warp, rotation), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Part(part.id)), + rootPartId = null, + ) + } + + /** + * The features named by notices, for comparing against the scan. + * + * @param List notices The strip's notices. + * @return Set The features reported. + */ + private fun strippedFeatures(notices: List): Set = + notices.filterIsInstance().map { it.feature }.toSet() + + @Test + fun theOldestTargetStripsEveryRepresentableFeature() { + val original = kitchenSink() + val stripped = Moc3VersionDowngrade.strip(original, MocVersion.V30) + val puppet = stripped.puppet + + val warp = puppet.deformers.first { it is Deformer.Warp } as Deformer.Warp + val rotation = puppet.deformers.first { it is Deformer.Rotation } as Deformer.Rotation + val drawable = puppet.drawables.single() + val part = puppet.parts.single() + + assertFalse(warp.isQuadTransform, "the 3.3 warp method must be gone") + assertEquals(emptyList(), warp.blendShapes, "warp blend shapes must be gone") + assertEquals(emptyList(), rotation.blendShapes, "rotation blend shapes must be gone") + assertEquals(emptyList(), drawable.blendShapes, "mesh blend shapes must be gone") + // NOT stripped at v1: the mask bit and the repeat section exist in every moc version, whatever + // the editor's target dialog says about when a rigger may author them. + assertTrue(drawable.invertMask, "the reversed mask is carried by every version") + assertTrue(puppet.parameters.any { it.repeat }, "the repeat flag is carried by every version") + assertEquals(BlendMode.Normal, drawable.blendMode, "Overlay has no pre-5.3 ancestor") + assertEquals(AlphaBlendMode.Over, drawable.alphaBlendMode, "the alpha mode must be back to Over") + assertEquals(ColorRgb.MultiplyIdentity, warp.multiplyColor, "the warp tint must be gone") + assertEquals(ColorRgb.ScreenIdentity, rotation.screenColor, "the rotation tint must be gone") + assertEquals(PartGroupMode.Grouped, part.groupMode, "an isolated part must demote to grouped") + assertEquals( + ParameterKind.NORMAL, + puppet.parameters.first { it.id == morphParameter }.kind, + "a blend-shape parameter must demote to normal", + ) + + // The pre-export scan and the strip differ by exactly the two features the editor gates later + // than the file format does - the scan over-warns about them, and pinning that here is what keeps + // the difference deliberate instead of a drift nobody notices. + assertEquals( + original.unsupportedFeaturesInUse(RuntimeTarget.Cubism30) - + setOf(RuntimeFeature.ReversedMask, RuntimeFeature.ParameterRepeat), + strippedFeatures(stripped.notices) - + setOf(RuntimeFeature.ReversedMask, RuntimeFeature.ParameterRepeat), + "the strip and the scan disagree about what a 3.0 export loses", + ) + } + + @Test + fun theSourceModelIsNeverMutated() { + val original = kitchenSink() + val before = original.unsupportedFeaturesInUse(RuntimeTarget.Cubism30) + Moc3VersionDowngrade.strip(original, MocVersion.V30) + assertEquals( + before, + original.unsupportedFeaturesInUse(RuntimeTarget.Cubism30), + "the caller's model must still use everything it started with", + ) + assertTrue(before.isNotEmpty(), "the fixture must actually use restricted features") + } + + @Test + fun eachTargetStripsOnlyWhatItsVersionPredates() { + val original = kitchenSink() + // 5.0 keeps blend shapes and color, and loses only the two 5.3 features in use. + val toFiveZero = Moc3VersionDowngrade.strip(original, MocVersion.V50) + assertEquals( + setOf(RuntimeFeature.ExtendedBlendModes, RuntimeFeature.PartComposite), + strippedFeatures(toFiveZero.notices), + ) + assertEquals( + 1, + (toFiveZero.puppet.deformers.first { it is Deformer.Warp } as Deformer.Warp).blendShapes.size, + "5.0 carries warp blend shapes", + ) + assertEquals( + ColorRgb(0.5f, 0.5f, 0.5f), + (toFiveZero.puppet.deformers.first { it is Deformer.Warp } as Deformer.Warp).multiplyColor, + "5.0 carries deformer color", + ) + + // 4.2 additionally loses the rotation-target blend record, but keeps the mesh and warp ones. + val toFourTwo = Moc3VersionDowngrade.strip(original, MocVersion.V42) + assertTrue(RuntimeFeature.ExtendedBlendShapes in strippedFeatures(toFourTwo.notices)) + assertEquals( + 1, + toFourTwo.puppet.drawables.single().blendShapes.size, + "4.2 carries mesh blend shapes", + ) + + // 5.3 is the ceiling: nothing is stripped and the model comes back unchanged. + val toFiveThree = Moc3VersionDowngrade.strip(original, MocVersion.V53) + assertEquals(emptyList(), toFiveThree.notices) + assertTrue(toFiveThree.puppet === original, "an unrestricted target must not copy the model") + } + + @Test + fun aColourTrackIsDroppedAlongWithTheStatic() { + val original = kitchenSink() + val tracked = + original.copy( + drawables = + original.drawables.map { drawable -> + drawable.copy( + multiplyColor = ColorRgb(0.5f, 0.5f, 0.5f), + channelGrids = ChannelGrids(mapOf(FormChannel.MULTIPLY_COLOR to colourTrack())), + ) + }, + ) + val stripped = Moc3VersionDowngrade.strip(tracked, MocVersion.V40).puppet.drawables.single() + assertEquals(ColorRgb.MultiplyIdentity, stripped.multiplyColor, "the static must reset") + assertEquals(null, stripped.channelGrids[FormChannel.MULTIPLY_COLOR], "the track must go with it") + } + + /** + * A one-cell multiply track, enough to make the channel count as in use. + * + * @return KeyformGrid The track. + */ + private fun colourTrack(): KeyformGrid = + KeyformGrid( + axes = emptyList(), + cells = listOf(KeyformCell(intArrayOf(), ChannelValue.Color(ColorRgb(0.5f, 0.5f, 0.5f)))), + ) +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/PuppetStructureDifferences.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/PuppetStructureDifferences.kt new file mode 100644 index 0000000..d3acb9a --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/PuppetStructureDifferences.kt @@ -0,0 +1,519 @@ +package org.umamo.interop.uma + +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.WarpForm + +/* + * The structural comparer the UMA round-trip tests share: every field the puppet entry carries - structure, + * meshes, keyform grids, channel tracks, blend shapes, glue - and the derived render root, compared exactly: + * floats by their bits, since a shortest-round-trip decimal and a buffer both give back the same bits and + * anything less is a bug. + */ + +/** + * Collects differences between an expected and an actual value by path. + * + * @property MutableList differences One line per difference. + */ +private class DifferenceCollector(val differences: MutableList = ArrayList()) { + /** + * Records a difference when two values are not equal. + * + * @param String path Where the values sit. + * @param Any? expected The expected value. + * @param Any? actual The actual value. + */ + fun same(path: String, expected: Any?, actual: Any?) { + if (expected != actual) { + differences += "$path: expected $expected, got $actual" + } + } + + /** + * Records a difference when two floats differ in any bit. + * + * @param String path Where the values sit. + * @param Float expected The expected value. + * @param Float actual The actual value. + */ + fun bits(path: String, expected: Float, actual: Float) { + if (expected.toRawBits() != actual.toRawBits()) { + differences += "$path: expected $expected (0x${expected.toRawBits().toUInt().toString(16)}), got $actual (0x${actual.toRawBits().toUInt().toString(16)})" + } + } + + /** + * Records a difference when two colors differ in any channel's bits. + * + * @param String path Where the values sit. + * @param ColorRgb expected The expected color. + * @param ColorRgb actual The actual color. + */ + fun color(path: String, expected: ColorRgb, actual: ColorRgb) { + bits("$path.red", expected.red, actual.red) + bits("$path.green", expected.green, actual.green) + bits("$path.blue", expected.blue, actual.blue) + } + + /** + * Records a difference when two float arrays differ in length or in any bit. + * + * @param String path Where the arrays sit. + * @param FloatArray expected The expected array. + * @param FloatArray actual The actual array. + */ + fun floats(path: String, expected: FloatArray, actual: FloatArray) { + if (expected.size != actual.size) { + differences += "$path: expected ${expected.size} floats, got ${actual.size}" + return + } + val first = expected.indices.firstOrNull { valueIndex -> expected[valueIndex].toRawBits() != actual[valueIndex].toRawBits() } ?: return + differences += "$path[$first]: expected ${expected[first]}, got ${actual[first]}" + } + + /** + * Records a difference when two int arrays differ. + * + * @param String path Where the arrays sit. + * @param IntArray expected The expected array. + * @param IntArray actual The actual array. + */ + fun ints(path: String, expected: IntArray, actual: IntArray) { + if (!expected.contentEquals(actual)) { + differences += "$path: the arrays differ" + } + } + + /** + * Compares two optional meshes. + * + * @param String path Where the meshes sit. + * @param DrawableMesh? expected The expected mesh. + * @param DrawableMesh? actual The actual mesh. + */ + fun mesh(path: String, expected: DrawableMesh?, actual: DrawableMesh?) { + if (expected == null || actual == null) { + same("$path present", expected != null, actual != null) + return + } + floats("$path.positions", expected.positions, actual.positions) + floats("$path.uvs", expected.uvs, actual.uvs) + ints("$path.indices", expected.indices, actual.indices) + } + + /** + * Compares two optional keyform grids: axes, cell order, coordinates, and each cell's form. + * + * @param String path Where the grids sit. + * @param KeyformGrid? expected The expected grid. + * @param KeyformGrid? actual The actual grid. + * @param Function compareForm Compares one pair of forms given its path. + */ + fun grid(path: String, expected: KeyformGrid?, actual: KeyformGrid?, compareForm: (String, T, T) -> Unit) { + if (expected == null || actual == null) { + same("$path present", expected != null, actual != null) + return + } + each("$path.axes", expected.axes, actual.axes) { axisPath, left, right -> + same("$axisPath.parameter", left.parameterId, right.parameterId) + floats("$axisPath.keys", left.keys, right.keys) + } + each("$path.cells", expected.cells, actual.cells) { cellPath, left, right -> + ints("$cellPath.coordinate", left.coordinate, right.coordinate) + compareForm(cellPath, left.form, right.form) + } + } + + /** + * Compares two owners' channel tracks, channel by channel. + * + * @param String path Where the tracks sit. + * @param ChannelGrids expected The expected tracks. + * @param ChannelGrids actual The actual tracks. + */ + fun channels(path: String, expected: ChannelGrids, actual: ChannelGrids) { + same("$path.channels keys", expected.gridsByChannel.keys, actual.gridsByChannel.keys) + for ((channel, expectedGrid) in expected.gridsByChannel) { + val actualGrid = actual.gridsByChannel[channel] ?: continue + grid("$path.channels.${channel.name}", expectedGrid, actualGrid) { valuePath, left, right -> channelValue("$valuePath.value", left, right) } + } + } + + /** + * Compares two channel values by kind and bits. + * + * @param String path Where the values sit. + * @param ChannelValue expected The expected value. + * @param ChannelValue actual The actual value. + */ + fun channelValue(path: String, expected: ChannelValue, actual: ChannelValue) { + when { + expected is ChannelValue.Scalar && actual is ChannelValue.Scalar -> bits(path, expected.value, actual.value) + expected is ChannelValue.Color && actual is ChannelValue.Color -> color(path, expected.color, actual.color) + expected is ChannelValue.Flag && actual is ChannelValue.Flag -> same(path, expected.flag, actual.flag) + else -> differences += "$path: expected a ${expected::class.simpleName}, got a ${actual::class.simpleName}" + } + } + + /** + * Compares two owners' blend-shape bindings: parameters, keys, neutrals, forms, and limits. + * + * @param String path Where the bindings sit. + * @param List expected The expected bindings. + * @param List actual The actual bindings. + * @param Function compareForm Compares one pair of non-null forms given its path. + */ + fun blendShapes(path: String, expected: List>, actual: List>, compareForm: (String, T, T) -> Unit) { + each("$path.blendShapes", expected, actual) { bindingPath, left, right -> + same("$bindingPath.parameter", left.parameterId, right.parameterId) + floats("$bindingPath.keys", left.keys, right.keys) + same("$bindingPath.neutralIndex", left.neutralIndex, right.neutralIndex) + each("$bindingPath.forms", left.forms, right.forms) { formPath, leftForm, rightForm -> + if (leftForm == null || rightForm == null) { + same("$formPath present", leftForm != null, rightForm != null) + } else { + compareForm(formPath, leftForm, rightForm) + } + } + each("$bindingPath.limits", left.limits, right.limits) { limitPath, leftLimit, rightLimit -> + same("$limitPath.parameter", leftLimit.parameterId, rightLimit.parameterId) + each("$limitPath.points", leftLimit.points, rightLimit.points) { pointPath, leftPoint, rightPoint -> + bits("$pointPath.value", leftPoint.value, rightPoint.value) + bits("$pointPath.weight", leftPoint.weight, rightPoint.weight) + } + } + } + } + + /** + * Compares two render-tree nodes and their subtrees. + * + * @param String path Where the nodes sit. + * @param RenderNode expected The expected node. + * @param RenderNode actual The actual node. + */ + fun renderNode(path: String, expected: RenderNode, actual: RenderNode) { + when { + expected is RenderDrawable && actual is RenderDrawable -> same("$path.id", expected.id, actual.id) + expected is RenderGroup && actual is RenderGroup -> { + same("$path.partId", expected.partId, actual.partId) + same("$path.drawOrder", expected.drawOrder, actual.drawOrder) + same("$path.composite", expected.composite, actual.composite) + channels(path, expected.channelGrids, actual.channelGrids) + each("$path.children", expected.children, actual.children) { childPath, left, right -> renderNode(childPath, left, right) } + } + + else -> differences += "$path: expected a ${expected::class.simpleName}, got a ${actual::class.simpleName}" + } + } + + /** + * Compares two lists element by element after checking their sizes. + * + * @param String path Where the lists sit. + * @param List expected The expected list. + * @param List actual The actual list. + * @param Function compare Compares one pair of elements given its path. + */ + fun each(path: String, expected: List, actual: List, compare: (String, T, T) -> Unit) { + if (expected.size != actual.size) { + differences += "$path: expected ${expected.size} elements, got ${actual.size}" + return + } + for (elementIndex in expected.indices) { + compare("$path[$elementIndex]", expected[elementIndex], actual[elementIndex]) + } + } +} + +/** + * Every difference between two models across the structure the puppet entry carries. + * + * @param PuppetModel expected The model before the round trip. + * @param PuppetModel actual The model after it. + * @return List One line per difference; empty when the structure is identical. + */ +internal fun puppetStructureDifferences(expected: PuppetModel, actual: PuppetModel): List { + val collector = DifferenceCollector() + with(collector) { + bits("canvasWidth", expected.canvasWidth, actual.canvasWidth) + bits("canvasHeight", expected.canvasHeight, actual.canvasHeight) + bits("worldOriginX", expected.worldOriginX, actual.worldOriginX) + bits("worldOriginZ", expected.worldOriginZ, actual.worldOriginZ) + same("pixelsPerUnit bits", expected.pixelsPerUnit?.toRawBits(), actual.pixelsPerUnit?.toRawBits()) + same("runtimeTarget", expected.runtimeTarget, actual.runtimeTarget) + same("rendersFromSourceLayers", expected.rendersFromSourceLayers, actual.rendersFromSourceLayers) + same("rootPartId", expected.rootPartId, actual.rootPartId) + same("rootChildren", expected.rootChildren, actual.rootChildren) + same("parameterLinks", expected.parameterLinks, actual.parameterLinks) + same("parameterTree", expected.parameterTree, actual.parameterTree) + + each("parameters", expected.parameters, actual.parameters) { path, left, right -> + same("$path.id", left.id, right.id) + same("$path.name", left.name, right.name) + bits("$path.min", left.min, right.min) + bits("$path.max", left.max, right.max) + bits("$path.default", left.default, right.default) + same("$path.kind", left.kind, right.kind) + same("$path.repeat", left.repeat, right.repeat) + } + + each("parts", expected.parts, actual.parts) { path, left, right -> + same("$path.id", left.id, right.id) + same("$path.name", left.name, right.name) + same("$path.children", left.children, right.children) + same("$path.isVisible", left.isVisible, right.isVisible) + same("$path.isSketch", left.isSketch, right.isSketch) + same("$path.isSelectable", left.isSelectable, right.isSelectable) + same("$path.groupMode", left.groupMode, right.groupMode) + same("$path.drawOrder", left.drawOrder, right.drawOrder) + val leftComposite = left.composite + val rightComposite = right.composite + same("$path.composite.blendMode", leftComposite.blendMode, rightComposite.blendMode) + same("$path.composite.alphaBlendMode", leftComposite.alphaBlendMode, rightComposite.alphaBlendMode) + same("$path.composite.maskedBy", leftComposite.maskedBy, rightComposite.maskedBy) + same("$path.composite.maskedByParts", leftComposite.maskedByParts, rightComposite.maskedByParts) + same("$path.composite.invertMask", leftComposite.invertMask, rightComposite.invertMask) + bits("$path.composite.opacity", leftComposite.opacity, rightComposite.opacity) + color("$path.composite.multiplyColor", leftComposite.multiplyColor, rightComposite.multiplyColor) + color("$path.composite.screenColor", leftComposite.screenColor, rightComposite.screenColor) + channels(path, left.channelGrids, right.channelGrids) + blendShapes(path, left.blendShapes, right.blendShapes) { formPath, leftForm: PartForm, rightForm -> partForm(formPath, leftForm, rightForm) } + } + + each("deformers", expected.deformers, actual.deformers) { path, left, right -> + same("$path.id", left.id, right.id) + same("$path.name", left.name, right.name) + same("$path.parent", left.parent, right.parent) + same("$path.partId", left.partId, right.partId) + same("$path.isVisible", left.isVisible, right.isVisible) + same("$path.isEnabled", left.isEnabled, right.isEnabled) + same("$path.isSelectable", left.isSelectable, right.isSelectable) + when { + left is Deformer.Warp && right is Deformer.Warp -> { + same("$path.rows", left.rows, right.rows) + same("$path.columns", left.columns, right.columns) + same("$path.isQuadTransform", left.isQuadTransform, right.isQuadTransform) + bits("$path.opacity", left.opacity, right.opacity) + color("$path.multiplyColor", left.multiplyColor, right.multiplyColor) + color("$path.screenColor", left.screenColor, right.screenColor) + grid("$path.geometry", left.geometryGrid, right.geometryGrid) { formPath, leftForm, rightForm -> floats("$formPath.controlPoints", leftForm.controlPoints, rightForm.controlPoints) } + blendShapes(path, left.blendShapes, right.blendShapes) { formPath, leftForm: WarpForm, rightForm -> warpForm(formPath, leftForm, rightForm) } + } + + left is Deformer.Rotation && right is Deformer.Rotation -> { + bits("$path.baseAngle", left.baseAngle, right.baseAngle) + same("$path.flipX", left.flipX, right.flipX) + same("$path.flipY", left.flipY, right.flipY) + bits("$path.opacity", left.opacity, right.opacity) + color("$path.multiplyColor", left.multiplyColor, right.multiplyColor) + color("$path.screenColor", left.screenColor, right.screenColor) + grid("$path.geometry", left.geometryGrid, right.geometryGrid) { formPath, leftForm, rightForm -> + bits("$formPath.originX", leftForm.originX, rightForm.originX) + bits("$formPath.originY", leftForm.originY, rightForm.originY) + bits("$formPath.angle", leftForm.angle, rightForm.angle) + bits("$formPath.scale", leftForm.scale, rightForm.scale) + } + blendShapes(path, left.blendShapes, right.blendShapes) { formPath, leftForm: RotationForm, rightForm -> rotationForm(formPath, leftForm, rightForm) } + } + + else -> differences += "$path: expected a ${left::class.simpleName}, got a ${right::class.simpleName}" + } + channels(path, left.channelGrids, right.channelGrids) + } + + each("drawables", expected.drawables, actual.drawables) { path, left, right -> + same("$path.id", left.id, right.id) + same("$path.name", left.name, right.name) + same("$path.parentDeformerId", left.parentDeformerId, right.parentDeformerId) + same("$path.blendMode", left.blendMode, right.blendMode) + same("$path.maskedBy", left.maskedBy, right.maskedBy) + same("$path.invertMask", left.invertMask, right.invertMask) + bits("$path.drawOrder", left.drawOrder, right.drawOrder) + bits("$path.opacity", left.opacity, right.opacity) + color("$path.multiplyColor", left.multiplyColor, right.multiplyColor) + color("$path.screenColor", left.screenColor, right.screenColor) + same("$path.alphaBlendMode", left.alphaBlendMode, right.alphaBlendMode) + same("$path.culling", left.culling, right.culling) + same("$path.isVisible", left.isVisible, right.isVisible) + same("$path.isSelectable", left.isSelectable, right.isSelectable) + same("$path.textureSourceId", left.textureSourceId, right.textureSourceId) + same("$path.texturePage", left.texturePage, right.texturePage) + same("$path.atlasTileId", left.atlasTileId, right.atlasTileId) + mesh("$path.mesh", left.mesh, right.mesh) + grid("$path.geometry", left.geometryGrid, right.geometryGrid) { formPath, leftForm, rightForm -> floats("$formPath.positionDeltas", leftForm.positionDeltas, rightForm.positionDeltas) } + channels(path, left.channelGrids, right.channelGrids) + blendShapes(path, left.blendShapes, right.blendShapes) { formPath, leftForm: MeshForm, rightForm -> meshForm(formPath, leftForm, rightForm) } + } + + each("glues", expected.glues, actual.glues) { path, left, right -> + same("$path.meshA", left.meshA, right.meshA) + same("$path.meshB", left.meshB, right.meshB) + same("$path.id", left.id, right.id) + bits("$path.intensity", left.intensity, right.intensity) + each("$path.pairs", left.pairs, right.pairs) { pairPath, leftPair, rightPair -> + same("$pairPath.indexA", leftPair.indexA, rightPair.indexA) + same("$pairPath.indexB", leftPair.indexB, rightPair.indexB) + bits("$pairPath.weightA", leftPair.weightA, rightPair.weightA) + bits("$pairPath.weightB", leftPair.weightB, rightPair.weightB) + } + channels(path, left.channelGrids, right.channelGrids) + } + + renderNode("renderRoot", expected.renderRoot, actual.renderRoot) + } + return collector.differences +} + +/** + * Every difference between two models' atlases: page sizes, the page addressing and composition, and every tile + * with its placement compared by bits, its binding, pin, and lineage. + * + * @param PuppetModel expected The model before the round trip. + * @param PuppetModel actual The model after it. + * @return List One line per difference; empty when the atlases are identical. + */ +internal fun atlasDifferences(expected: PuppetModel, actual: PuppetModel): List { + val collector = DifferenceCollector() + with(collector) { + val left = expected.atlas + val right = actual.atlas + same("atlas.pages", left.pages, right.pages) + same("atlas.storedUvsAddressPages", left.storedUvsAddressPages, right.storedUvsAddressPages) + same("atlas.composition", left.composition, right.composition) + each("atlas.tiles", left.tiles, right.tiles) { path, leftTile, rightTile -> + same("$path.id", leftTile.id, rightTile.id) + same("$path.name", leftTile.name, rightTile.name) + same("$path.width", leftTile.width, rightTile.width) + same("$path.height", leftTile.height, rightTile.height) + same("$path.source", leftTile.source, rightTile.source) + same("$path.pinned", leftTile.pinned, rightTile.pinned) + same("$path.replaces", leftTile.replaces, rightTile.replaces) + val leftPlacement = leftTile.placement + val rightPlacement = rightTile.placement + if (leftPlacement == null || rightPlacement == null) { + same("$path.placement present", leftPlacement != null, rightPlacement != null) + } else { + same("$path.placement.pageIndex", leftPlacement.pageIndex, rightPlacement.pageIndex) + bits("$path.placement.positionX", leftPlacement.positionX, rightPlacement.positionX) + bits("$path.placement.positionY", leftPlacement.positionY, rightPlacement.positionY) + bits("$path.placement.scaleX", leftPlacement.scaleX, rightPlacement.scaleX) + bits("$path.placement.scaleY", leftPlacement.scaleY, rightPlacement.scaleY) + bits("$path.placement.rotationDegrees", leftPlacement.rotationDegrees, rightPlacement.rotationDegrees) + } + } + } + return collector.differences +} + +/** + * Every difference between two models' linked source art: each source's record and every inventory row with every + * flag and hash. + * + * @param PuppetModel expected The model before the round trip. + * @param PuppetModel actual The model after it. + * @return List One line per difference; empty when the sources are identical. + */ +internal fun sourcesDifferences(expected: PuppetModel, actual: PuppetModel): List { + val collector = DifferenceCollector() + with(collector) { + each("sources", expected.sources, actual.sources) { path, left, right -> + same("$path.id", left.id, right.id) + same("$path.name", left.name, right.name) + same("$path.path", left.path, right.path) + same("$path.format", left.format, right.format) + same("$path.contentHash", left.contentHash, right.contentHash) + same("$path.lastModified", left.lastModified, right.lastModified) + same("$path.offsetX", left.offsetX, right.offsetX) + same("$path.offsetZ", left.offsetZ, right.offsetZ) + each("$path.layers", left.layers, right.layers) { layerPath, leftLayer, rightLayer -> same(layerPath, leftLayer, rightLayer) } + } + } + return collector.differences +} + +/** + * Every difference between two models across everything a UMA document carries: the puppet entry's structure and + * geometry, the atlas, and the linked source art. + * + * @param PuppetModel expected The model before the round trip. + * @param PuppetModel actual The model after it. + * @return List One line per difference; empty when the documents are identical. + */ +internal fun documentDifferences(expected: PuppetModel, actual: PuppetModel): List = + puppetStructureDifferences(expected, actual) + atlasDifferences(expected, actual) + sourcesDifferences(expected, actual) + +/** + * Compares two drawable blend forms. + * + * @param String path Where the forms sit. + * @param MeshForm expected The expected form. + * @param MeshForm actual The actual form. + */ +private fun DifferenceCollector.meshForm(path: String, expected: MeshForm, actual: MeshForm) { + floats("$path.positionDeltas", expected.positionDeltas, actual.positionDeltas) + bits("$path.drawOrder", expected.drawOrder, actual.drawOrder) + bits("$path.opacity", expected.opacity, actual.opacity) + color("$path.multiplyColor", expected.multiplyColor, actual.multiplyColor) + color("$path.screenColor", expected.screenColor, actual.screenColor) +} + +/** + * Compares two warp blend forms. + * + * @param String path Where the forms sit. + * @param WarpForm expected The expected form. + * @param WarpForm actual The actual form. + */ +private fun DifferenceCollector.warpForm(path: String, expected: WarpForm, actual: WarpForm) { + floats("$path.controlPoints", expected.controlPoints, actual.controlPoints) + bits("$path.opacity", expected.opacity, actual.opacity) + color("$path.multiplyColor", expected.multiplyColor, actual.multiplyColor) + color("$path.screenColor", expected.screenColor, actual.screenColor) +} + +/** + * Compares two rotation blend forms. + * + * @param String path Where the forms sit. + * @param RotationForm expected The expected form. + * @param RotationForm actual The actual form. + */ +private fun DifferenceCollector.rotationForm(path: String, expected: RotationForm, actual: RotationForm) { + bits("$path.originX", expected.originX, actual.originX) + bits("$path.originY", expected.originY, actual.originY) + bits("$path.angle", expected.angle, actual.angle) + bits("$path.scale", expected.scale, actual.scale) + same("$path.flipX", expected.flipX, actual.flipX) + same("$path.flipY", expected.flipY, actual.flipY) + bits("$path.opacity", expected.opacity, actual.opacity) + color("$path.multiplyColor", expected.multiplyColor, actual.multiplyColor) + color("$path.screenColor", expected.screenColor, actual.screenColor) +} + +/** + * Compares two part blend forms. + * + * @param String path Where the forms sit. + * @param PartForm expected The expected form. + * @param PartForm actual The actual form. + */ +private fun DifferenceCollector.partForm(path: String, expected: PartForm, actual: PartForm) { + bits("$path.drawOrder", expected.drawOrder, actual.drawOrder) + bits("$path.opacity", expected.opacity, actual.opacity) + color("$path.multiplyColor", expected.multiplyColor, actual.multiplyColor) + color("$path.screenColor", expected.screenColor, actual.screenColor) +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaDocumentBridgeTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaDocumentBridgeTest.kt new file mode 100644 index 0000000..32b7a7b --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaDocumentBridgeTest.kt @@ -0,0 +1,235 @@ +package org.umamo.interop.uma + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasComposition +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the whole-document bridge (docs/format/UMA.md §5, §6) on synthetic models: every atlas and source field + * survives a save exactly for every atlas shape, a reopened document samples the render pages it was saved with or + * derives them, and the comparer the corpus gate relies on sees a one-bit change. + */ +class UmaDocumentBridgeTest { + private val writer = UmaWriterInfo("Umamo", "test") + + private val digest = "0123456789abcdef".repeat(4) + + /** + * A PNG of one flat color. + * + * @param Int width The width. + * @param Int height The height. + * @param Int value The byte every channel takes. + * @return ByteArray The PNG. + */ + private fun png(width: Int, height: Int, value: Int): ByteArray = PngCodec.write(RasterImage(width, height, ByteArray(width * height * 4) { value.toByte() })) + + /** + * A drawable bound to [tile], or to a page when [texturePage] is given. + * + * @param String id The drawable's id. + * @param String? tile The tile it samples. + * @param Int texturePage The page it samples, or -1. + * @return Drawable The drawable. + */ + private fun drawable(id: String, tile: String?, texturePage: Int = -1): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + texturePage = texturePage, + atlasTileId = tile?.let(::AtlasTileId), + ) + + /** + * A model over [drawables] with [atlas] and [sources]. + * + * @param List drawables The drawables. + * @param PuppetAtlas atlas The atlas. + * @param List sources The linked source art. + * @return PuppetModel The model. + */ + private fun modelOf(drawables: List, atlas: PuppetAtlas, sources: List = emptyList()): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { item -> OrgChild.Drawable(item.id) }, + rootPartId = null, + atlas = atlas, + sources = sources, + ).withDerivedRenderRoot() + + /** + * An atlas using every field: layer-addressed coordinates, a composition off the defaults, a placed and pinned + * tile with a stable binding and a placement whose floats a decimal round trip is most likely to bend, a + * reloaded tile with a weak binding and a lineage, and a bare tile. + * + * @return PuppetAtlas The atlas. + */ + private fun fullAtlas(): PuppetAtlas = + PuppetAtlas( + pages = listOf(AtlasPage(16, 16)), + tiles = + listOf( + AtlasTile(AtlasTileId("art-0/lyid:1"), "Eye", 4, 3, AtlasPlacement(0, 1.5f, -0.0f, -1f, Float.MIN_VALUE, 90.25f), SourceLayerRef(ArtSourceId("art-0"), "lyid:1", true), pinned = true), + AtlasTile(AtlasTileId("art-0/name:Mouth#2~1"), "Mouth", 2, 2, source = SourceLayerRef(ArtSourceId("art-0"), "name:Mouth#2", false), replaces = AtlasTileId("art-0/name:Mouth#2")), + AtlasTile(AtlasTileId("guid-3"), "Hair", 5, 1), + ), + storedUvsAddressPages = false, + composition = AtlasComposition(alphaThreshold = 8, extrude = 0), + ) + + /** + * Sources using every field and flag. + * + * @return List The sources. + */ + private fun fullSources(): List = + listOf( + ArtSource( + id = ArtSourceId("art-0"), + name = "character.clip", + path = "C:/work/character.clip", + format = "clip", + layers = + listOf( + ArtSourceLayer("lyid:1", "Eye", "Head/Face", -12, 180, 4, 3, visible = false, present = false, contentHash = digest, empty = true, replaced = true, ignored = true), + ArtSourceLayer("name:Mouth#2", "Mouth", "", 0, 0, 2, 2, visible = true), + ), + contentHash = digest, + lastModified = 1_757_894_400_123L, + offsetX = 64, + offsetZ = -32, + ), + ArtSource(ArtSourceId("guid-7"), "Erica.psd", null, "psd"), + ) + + /** The PNG per tile of [fullAtlas], by id. */ + private val tilePngs: Map = + mapOf("art-0/lyid:1" to png(4, 3, 10), "art-0/name:Mouth#2~1" to png(2, 2, 20), "guid-3" to png(5, 1, 30)) + + /** + * [model] saved as a whole document and read back. + * + * @param PuppetModel model The model. + * @param UmaRenderPagePixels renderPages What its drawables sample. + * @return UmaModel The reopened document. + */ + private fun saved(model: PuppetModel, renderPages: UmaRenderPagePixels): UmaModel = + Uma.read(Uma.write(UmaDocumentBridge.documentOf(UmaModel.create(writer), model, UmaPixelSource({ id -> tilePngs[id] }, renderPages, null)))) + + /** + * Every atlas and source field survives a save exactly, and the render pages come back with each drawable's image. + */ + @Test + fun everyAtlasAndSourceFieldRoundTrips() { + val model = modelOf(listOf(drawable("D0", "art-0/lyid:1"), drawable("D1", "guid-3")), fullAtlas(), fullSources()) + val reducedCopy = png(2, 2, 60) + val document = saved(model, UmaRenderPagePixels.Stored(listOf(reducedCopy, tilePngs.getValue("guid-3")), mapOf("D0" to 0, "D1" to 1))) + val reopened = UmaDocumentBridge.modelOf(document) + val differences = documentDifferences(model, reopened) + assertTrue(differences.isEmpty(), "differences: $differences") + assertEquals(model.atlas, reopened.atlas) + assertEquals(model.sources, reopened.sources) + + val pages = UmaDocumentBridge.pagesOf(document) + val pageSet = assertNotNull(pages.pageSet, "stored render pages come back as a page set") + assertEquals(mapOf("D0" to 0, "D1" to 1), pageSet.atlasIndexByDrawableId) + assertContentEquals(reducedCopy, pageSet.pageBytes[0]) + assertContentEquals(tilePngs.getValue("guid-3"), pageSet.pageBytes[1]) + assertContentEquals(tilePngs.getValue("art-0/name:Mouth#2~1"), pages.tilePng(AtlasTileId("art-0/name:Mouth#2~1")), "an unbound tile's pixels are there") + } + + /** + * A document whose pages derive stores no render pages, so the loader composes them. + */ + @Test + fun derivedPagesStoreNoPageSet() { + val model = modelOf(listOf(drawable("D0", "art-0/lyid:1")), fullAtlas().copy(storedUvsAddressPages = true)) + val document = saved(model, UmaRenderPagePixels.Derived) + assertNull(UmaDocumentBridge.pagesOf(document).pageSet) + assertEquals(model.atlas, UmaDocumentBridge.modelOf(document).atlas) + } + + /** + * Every atlas shape round-trips exactly: pages with no tiles (a CMO3 whose atlas holds no model image), and no + * pages or tiles at all beside stored render pages the drawables name by page number (a MOC3-origin rig). + */ + @Test + fun everyAtlasShapeRoundTrips() { + val pagesOnly = modelOf(emptyList(), PuppetAtlas(pages = listOf(AtlasPage(1024, 1024)))) + assertEquals(pagesOnly.atlas, UmaDocumentBridge.modelOf(saved(pagesOnly, UmaRenderPagePixels.Derived)).atlas, "pages without tiles") + + val tileless = modelOf(listOf(drawable("ArtMesh0", null, texturePage = 1), drawable("ArtMesh1", null, texturePage = 0)), PuppetAtlas.Empty) + val pagePngs = listOf(png(16, 16, 1), png(8, 8, 2)) + val document = saved(tileless, UmaRenderPagePixels.Stored(pagePngs, mapOf("ArtMesh0" to 1, "ArtMesh1" to 0))) + val reopened = UmaDocumentBridge.modelOf(document) + assertEquals(PuppetAtlas.Empty, reopened.atlas, "the render pages do not enter an empty atlas") + assertEquals(listOf(1, 0), reopened.drawables.map { item -> item.texturePage }) + val pageSet = assertNotNull(UmaDocumentBridge.pagesOf(document).pageSet) + assertContentEquals(pagePngs[1], pageSet.pageBytes[pageSet.atlasIndexByDrawableId.getValue("ArtMesh0")]) + assertContentEquals(pagePngs[0], pageSet.pageBytes[pageSet.atlasIndexByDrawableId.getValue("ArtMesh1")]) + } + + /** + * The comparer sees a one-bit change in a placement, a flipped inventory flag, and a changed hash. + */ + @Test + fun comparerSeesSmallDifferences() { + val model = modelOf(listOf(drawable("D0", "art-0/lyid:1")), fullAtlas(), fullSources()) + val placement = model.atlas.tiles[0].placement!! + val nudged = placement.copy(positionX = Float.fromBits(placement.positionX.toRawBits() + 1)) + val movedTile = model.copy(atlas = model.atlas.copy(tiles = listOf(model.atlas.tiles[0].copy(placement = nudged)) + model.atlas.tiles.drop(1))) + assertEquals(1, atlasDifferences(model, movedTile).size, "a one-bit placement change") + val source = model.sources[0] + val flipped = model.copy(sources = listOf(source.copy(layers = listOf(source.layers[0].copy(ignored = false)) + source.layers.drop(1))) + model.sources.drop(1)) + assertEquals(1, sourcesDifferences(model, flipped).size, "a flipped ignore mark") + val rehashed = model.copy(sources = listOf(source.copy(contentHash = digest.reversed())) + model.sources.drop(1)) + assertEquals(1, sourcesDifferences(model, rehashed).size, "a changed file hash") + } + + /** + * A save refuses a placement JSON cannot hold, naming where. + */ + @Test + fun unwritableAtlasesAreRefused() { + val atlas = fullAtlas() + val nanTile = atlas.tiles[0].copy(placement = atlas.tiles[0].placement!!.copy(rotationDegrees = Float.NaN)) + val failure = assertFailsWith { UmaTexturesBridge.texturesOf(modelOf(emptyList(), atlas.copy(tiles = listOf(nanTile)))) } + assertTrue(failure.path.contains("tiles[art-0/lyid:1].placement.rotationDegrees"), "the failure names ${failure.path}") + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaPuppetBridgeTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaPuppetBridgeTest.kt new file mode 100644 index 0000000..82ab2b3 --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaPuppetBridgeTest.kt @@ -0,0 +1,261 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.uma.puppet.UmaDeformer +import org.umamo.format.uma.puppet.UmaDeformerKind +import org.umamo.format.uma.puppet.UmaDrawable +import org.umamo.format.uma.puppet.UmaParameter +import org.umamo.format.uma.puppet.UmaPart +import org.umamo.format.uma.puppet.UmaPuppet +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.deriveRenderRoot +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * Pins the puppet entry's bridge in both directions (docs/format/UMA.md §4) on synthetic models: every + * structure field away from its default and every enum value survives a save exactly, and defaults stay out of + * the file. The shapes the flat schema cannot enforce are the format layer's (UmaPuppetShapeTest). + */ +class UmaPuppetBridgeTest { + private val writer = UmaWriterInfo("Umamo", "test") + + /** + * [model] saved as UMA and read back. + * + * @param PuppetModel model The model. + * @return PuppetModel The model the file describes. + */ + private fun roundTrip(model: PuppetModel): PuppetModel { + val bytes = Uma.write(UmaModel.create(writer).withPuppet(UmaPuppetExport.puppetOf(model))) + return UmaPuppetImport.modelOf(Uma.read(bytes).puppet!!) + } + + /** + * A model with every structure field away from its default, every enum value used somewhere, and the + * floats a decimal round trip is most likely to bend. + * + * @param RuntimeTarget runtimeTarget The document's target. + * @return PuppetModel The model. + */ + private fun fullModel(runtimeTarget: RuntimeTarget): PuppetModel { + val drawables = + BlendMode.entries.mapIndexed { modeIndex, mode -> + val alphaMode = AlphaBlendMode.entries[modeIndex % AlphaBlendMode.entries.size] + if (modeIndex == 0) { + Drawable( + id = DrawableId("D0"), + name = "Eye L", + parentDeformerId = DeformerId("R1"), + blendMode = mode, + maskedBy = listOf(DrawableId("D1")), + mesh = null, + geometryGrid = null, + drawOrder = 499.5f, + opacity = -0.0f, + multiplyColor = ColorRgb(0.5f, -0.0f, Float.MIN_VALUE), + screenColor = ColorRgb(0.1f, 0.2f, 0.3f), + invertMask = true, + alphaBlendMode = alphaMode, + culling = true, + isVisible = false, + isSelectable = false, + textureSourceId = DrawableId("D1"), + texturePage = 2, + atlasTileId = AtlasTileId("art-0/lyid:12~1"), + ) + } else { + Drawable(DrawableId("D$modeIndex"), "Drawable $modeIndex", null, mode, emptyList(), null, null, alphaBlendMode = alphaMode) + } + } + return PuppetModel( + parameters = + listOf( + Parameter(ParameterId("P0"), "Angle", -0.0f, 30f, Float.MIN_VALUE), + Parameter(ParameterId("P1"), "Morph", -1f, 1f, 1.4e-44f, ParameterKind.BLEND_SHAPE, repeat = true), + ), + parts = + listOf( + Part( + id = PartId("Head"), + name = "Head", + children = listOf(OrgChild.Drawable(DrawableId("D1")), OrgChild.Part(PartId("Arm"))), + isVisible = false, + isSketch = true, + isSelectable = false, + groupMode = PartGroupMode.Grouped, + drawOrder = 700, + composite = + PartComposite( + blendMode = BlendMode.Multiply, + alphaBlendMode = AlphaBlendMode.Disjoint, + maskedBy = listOf(DrawableId("D0")), + maskedByParts = listOf(PartId("Body")), + invertMask = true, + opacity = 0.25f, + multiplyColor = ColorRgb(0.5f, 0.25f, 1f), + screenColor = ColorRgb(0.125f, 0f, 0f), + ), + ), + Part(PartId("Body"), "Body", listOf(OrgChild.Drawable(DrawableId("D2"))), groupMode = PartGroupMode.Isolated), + Part(PartId("Arm"), "Arm", emptyList()), + ), + deformers = + listOf( + Deformer.Warp( + id = DeformerId("W1"), + name = "Warp", + parent = null, + partId = PartId("Head"), + rows = 3, + columns = 4, + isQuadTransform = false, + geometryGrid = null, + opacity = 0.5f, + multiplyColor = ColorRgb(0.9f, 0.8f, 0.7f), + screenColor = ColorRgb(0.01f, 0.02f, 0.03f), + isSelectable = false, + isVisible = false, + isEnabled = false, + ), + Deformer.Rotation( + id = DeformerId("R1"), + name = "Rotation", + parent = DeformerId("W1"), + partId = PartId("Body"), + baseAngle = -0.0f, + geometryGrid = null, + flipX = true, + flipY = true, + ), + ), + drawables = drawables, + rootChildren = listOf(OrgChild.Part(PartId("Head")), OrgChild.Part(PartId("Body")), OrgChild.Drawable(DrawableId("D0"))), + rootPartId = PartId("__RootPart__"), + parameterLinks = listOf(ParameterLink(ParameterId("P0"), ParameterId("P1"))), + parameterTree = + listOf( + ParameterNode.Group( + ParameterGroupId("G1"), + "Face", + initiallyOpen = true, + children = listOf(ParameterNode.Param(ParameterId("P0")), ParameterNode.Group(ParameterGroupId("G2"), "", false, listOf(ParameterNode.Param(ParameterId("P1"))))), + ), + ), + canvasWidth = 2400f, + canvasHeight = 3000f, + worldOriginX = 1200f, + worldOriginZ = -0.0f, + pixelsPerUnit = 1f, + runtimeTarget = runtimeTarget, + rendersFromSourceLayers = true, + ).withDerivedRenderRoot() + } + + /** + * Every structure field survives a save exactly, under every runtime target. + */ + @Test + fun everyStructureFieldRoundTripsExactly() { + for (target in RuntimeTarget.entries) { + val model = fullModel(target) + val differences = puppetStructureDifferences(model, roundTrip(model)) + assertTrue(differences.isEmpty(), "$target: ${differences.take(20)}") + } + } + + /** + * The comparer the round trips rest on does see a single flipped bit, a renamed object, and a reordered + * list, so an empty result means something. + */ + @Test + fun comparerSeesSmallDifferences() { + val model = fullModel(RuntimeTarget.NoTarget) + val signFlip = model.copy(drawables = model.drawables.map { drawable -> if (drawable.id == DrawableId("D0")) drawable.copy(opacity = 0.0f) else drawable }) + assertEquals(listOf("drawables[0].opacity"), puppetStructureDifferences(model, signFlip).map { difference -> difference.substringBefore(':') }, "-0.0 against 0.0") + val renamed = model.copy(parts = model.parts.map { part -> if (part.id == PartId("Arm")) part.copy(name = "Arm L") else part }) + assertEquals(listOf("parts[2].name"), puppetStructureDifferences(model, renamed).map { difference -> difference.substringBefore(':') }, "a rename") + assertTrue(puppetStructureDifferences(model, model.copy(parameters = model.parameters.reversed())).isNotEmpty(), "a reorder") + } + + /** + * The render root is never read from the file; the model always carries the organizational tree's own + * derivation. + */ + @Test + fun renderRootIsDerived() { + val reopened = roundTrip(fullModel(RuntimeTarget.NoTarget)) + assertEquals(reopened.deriveRenderRoot(), reopened.renderRoot, "the render root is the derivation") + assertTrue(reopened.renderRoot.children.any { node -> node is RenderGroup && node.partId == PartId("Head") }, "and a grouped part forms its group") + } + + /** + * A model at every default writes only what the schema requires. + */ + @Test + fun defaultsStayOutOfTheFile() { + val model = + PuppetModel( + parameters = listOf(Parameter(ParameterId("P"), "P", 0f, 1f, 0f)), + parts = listOf(Part(PartId("Part"), "Part", emptyList())), + deformers = + listOf( + Deformer.Warp(DeformerId("W"), "W", null, null, 2, 2, true, null), + Deformer.Rotation(DeformerId("R"), "R", null, null, 0f, null), + ), + drawables = listOf(Drawable(DrawableId("D"), "D", null, BlendMode.Normal, emptyList(), null, null)), + rootChildren = emptyList(), + rootPartId = null, + ).withDerivedRenderRoot() + val expected = + UmaPuppet( + parameters = listOf(UmaParameter("P", "P", 0f, 1f, 0f)), + parts = listOf(UmaPart("Part", "Part")), + deformers = + listOf( + UmaDeformer("W", UmaDeformerKind.Warp, "W", rows = 2, columns = 2, isQuadTransform = true), + UmaDeformer("R", UmaDeformerKind.Rotation, "R", baseAngle = 0f), + ), + drawables = listOf(UmaDrawable("D", "D")), + ) + assertEquals(expected, UmaPuppetExport.puppetOf(model)) + assertTrue(puppetStructureDifferences(model, roundTrip(model)).isEmpty(), "and restores every default on read") + } + + /** + * A non-finite value refuses the save and names where it sits. + */ + @Test + fun nonFiniteValueRefusesTheSaveByPath() { + val model = fullModel(RuntimeTarget.NoTarget).let { base -> base.copy(drawables = base.drawables.map { drawable -> if (drawable.id == DrawableId("D3")) drawable.copy(opacity = Float.NaN) else drawable }) } + val failure = assertFailsWith { UmaPuppetExport.puppetOf(model) } + assertTrue(failure.message.orEmpty().contains("drawables[D3].opacity"), "the failure names the value: ${failure.message}") + } +} \ No newline at end of file diff --git a/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaPuppetGeometryBridgeTest.kt b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaPuppetGeometryBridgeTest.kt new file mode 100644 index 0000000..681ea2a --- /dev/null +++ b/module/interop/src/commonTest/kotlin/org/umamo/interop/uma/UmaPuppetGeometryBridgeTest.kt @@ -0,0 +1,224 @@ +package org.umamo.interop.uma + +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.BlendWeightLimitPoint +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartForm +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * Pins the puppet entry's geometry half in both directions (docs/format/UMA.md §4.9-§4.14) on synthetic + * models: meshes, every grid kind (a sparse one included), every channel, every blend form, and glue survive a + * save bit for bit, and the buffer carries even a NaN payload while inline JSON refuses one. The geometry + * invariants the renderer relies on are the format layer's (UmaPuppetShapeTest). + */ +class UmaPuppetGeometryBridgeTest { + private val writer = UmaWriterInfo("Umamo", "test") + + /** + * [model] saved as UMA and read back. + * + * @param PuppetModel model The model. + * @return PuppetModel The model the file describes. + */ + private fun roundTrip(model: PuppetModel): PuppetModel { + val bytes = Uma.write(UmaModel.create(writer).withPuppet(UmaPuppetExport.puppetOf(model))) + return UmaPuppetImport.modelOf(Uma.read(bytes).puppet!!) + } + + /** + * Eight distinct floats for a quad's four vertices, starting at [start]. + * + * @param Float start The first value. + * @return FloatArray The values. + */ + private fun quadFloats(start: Float): FloatArray = FloatArray(8) { valueIndex -> start + valueIndex * 0.125f } + + /** + * A one-axis channel track over P0 with one value per key. + * + * @param List values The three values. + * @return KeyformGrid The track. + */ + private fun track(values: List): KeyformGrid = + KeyformGrid(listOf(KeyformAxis(ParameterId("P0"), floatArrayOf(-30f, 0f, 30f))), values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), value) }) + + /** + * A model exercising every geometry field. + * + * @return PuppetModel The model. + */ + private fun geometryModel(): PuppetModel { + val axes = listOf(KeyformAxis(ParameterId("P0"), floatArrayOf(-30f, 0f, 30f)), KeyformAxis(ParameterId("P1"), floatArrayOf(-0.0f, 1f))) + val denseCells = (0 until 2).flatMap { secondKey -> (0 until 3).map { firstKey -> KeyformCell(intArrayOf(firstKey, secondKey), MeshDeltaForm(quadFloats(firstKey + secondKey * 3f))) } } + val quad = DrawableMesh(floatArrayOf(0f, 0f, 10f, 0f, 10f, 10f, 0f, 10f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + val colorTracks = + ChannelGrids( + linkedMapOf( + FormChannel.DRAW_ORDER to track(listOf(ChannelValue.Scalar(490f), ChannelValue.Scalar(-0.0f), ChannelValue.Scalar(510.5f))), + FormChannel.OPACITY to track(listOf(ChannelValue.Scalar(0f), ChannelValue.Scalar(0.5f), ChannelValue.Scalar(1f))), + FormChannel.MULTIPLY_COLOR to track(listOf(ChannelValue.Color(ColorRgb(1f, 0.5f, 0.25f)), ChannelValue.Color(ColorRgb.MultiplyIdentity), ChannelValue.Color(ColorRgb(0f, 0f, Float.MIN_VALUE)))), + FormChannel.SCREEN_COLOR to track(listOf(ChannelValue.Color(ColorRgb(0.1f, 0.2f, 0.3f)), ChannelValue.Color(ColorRgb.ScreenIdentity), ChannelValue.Color(ColorRgb.ScreenIdentity))), + ), + ) + val limits = listOf(BlendWeightLimit(ParameterId("P0"), listOf(BlendWeightLimitPoint(-30f, 0f), BlendWeightLimitPoint(30f, 1f)))) + return PuppetModel( + parameters = listOf(Parameter(ParameterId("P0"), "Angle", -30f, 30f, 0f), Parameter(ParameterId("P1"), "Morph", 0f, 1f, 0f)), + parts = + listOf( + Part( + id = PartId("Head"), + name = "Head", + children = listOf(OrgChild.Drawable(DrawableId("D0")), OrgChild.Drawable(DrawableId("D1"))), + groupMode = PartGroupMode.Isolated, + channelGrids = ChannelGrids(linkedMapOf(FormChannel.DRAW_ORDER to track(listOf(ChannelValue.Scalar(400f), ChannelValue.Scalar(500f), ChannelValue.Scalar(600f))))), + blendShapes = listOf(BlendShapeBinding(ParameterId("P1"), floatArrayOf(0f, 1f), 0, listOf(null, PartForm(600f, 0.75f, ColorRgb(0.5f, 0.5f, 0.5f))), limits)), + ), + ), + deformers = + listOf( + Deformer.Warp( + id = DeformerId("W1"), + name = "Warp", + parent = null, + partId = PartId("Head"), + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = KeyformGrid(axes.take(1), (0 until 3).map { keyIndex -> KeyformCell(intArrayOf(keyIndex), WarpLatticeForm(quadFloats(keyIndex * 10f))) }), + channelGrids = ChannelGrids(linkedMapOf(FormChannel.OPACITY to track(listOf(ChannelValue.Scalar(1f), ChannelValue.Scalar(0.25f), ChannelValue.Scalar(1f))))), + blendShapes = listOf(BlendShapeBinding(ParameterId("P1"), floatArrayOf(0f, 1f), 0, listOf(null, WarpForm(quadFloats(-5f), 0.5f)))), + ), + Deformer.Rotation( + id = DeformerId("R1"), + name = "Rotation", + parent = DeformerId("W1"), + partId = PartId("Head"), + baseAngle = 15f, + geometryGrid = KeyformGrid(axes.take(1), (0 until 3).map { keyIndex -> KeyformCell(intArrayOf(keyIndex), RotationPivotForm(0.5f, -0.0f, keyIndex * 15f, 1f + keyIndex)) }), + channelGrids = + ChannelGrids( + linkedMapOf( + FormChannel.FLIP_X to track(listOf(ChannelValue.Flag(false), ChannelValue.Flag(true), ChannelValue.Flag(false))), + FormChannel.FLIP_Y to track(listOf(ChannelValue.Flag(true), ChannelValue.Flag(true), ChannelValue.Flag(false))), + ), + ), + blendShapes = listOf(BlendShapeBinding(ParameterId("P1"), floatArrayOf(0f, 1f), 0, listOf(null, RotationForm(1f, 2f, 45f, 0.5f, flipX = true, flipY = false, opacity = 0.5f)), limits)), + ), + ), + drawables = + listOf( + Drawable( + id = DrawableId("D0"), + name = "Eye", + parentDeformerId = DeformerId("R1"), + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = quad, + geometryGrid = KeyformGrid(axes, denseCells), + channelGrids = colorTracks, + blendShapes = listOf(BlendShapeBinding(ParameterId("P1"), floatArrayOf(0f, 1f), 0, listOf(null, MeshForm(quadFloats(9f), 510f, 0.5f, ColorRgb(0.9f, 0.9f, 0.9f), ColorRgb(0.1f, 0f, 0f))), limits)), + ), + Drawable( + id = DrawableId("D1"), + name = "Brow", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(quad.positions.copyOf(), quad.uvs.copyOf(), quad.indices.copyOf()), + // A sparse grid: one of the six cells is missing, and the others keep their order. + geometryGrid = KeyformGrid(axes, denseCells.filterIndexed { cellIndex, _ -> cellIndex != 4 }.reversed()), + ), + ), + rootChildren = listOf(OrgChild.Part(PartId("Head"))), + rootPartId = null, + glues = + listOf( + Glue( + meshA = DrawableId("D0"), + meshB = DrawableId("D1"), + pairs = listOf(GluePair(0, 3, 0.5f, 0.25f), GluePair(1, 2, 1f, -0.0f)), + channelGrids = ChannelGrids(linkedMapOf(FormChannel.GLUE_INTENSITY to track(listOf(ChannelValue.Scalar(0f), ChannelValue.Scalar(1f), ChannelValue.Scalar(0.5f))))), + intensity = 0.75f, + id = "Glue__D0__D1", + ), + ), + ).withDerivedRenderRoot() + } + + /** + * Every geometry field survives a save bit for bit. + */ + @Test + fun everyGeometryFieldRoundTripsExactly() { + val model = geometryModel() + val differences = puppetStructureDifferences(model, roundTrip(model)) + assertTrue(differences.isEmpty(), differences.take(20).toString()) + } + + /** + * The comparer does see a single flipped bit deep inside a delta buffer. + */ + @Test + fun comparerSeesADeltaBit() { + val model = geometryModel() + val drawable = model.drawables.first() + val grid = drawable.geometryGrid!! + val flipped = grid.cells.first().form.positionDeltas.copyOf().also { deltas -> deltas[5] = Float.fromBits(deltas[5].toRawBits() xor 1) } + val changedGrid = KeyformGrid(grid.axes, listOf(KeyformCell(grid.cells.first().coordinate, MeshDeltaForm(flipped))) + grid.cells.drop(1)) + val changed = model.copy(drawables = listOf(drawable.copy(geometryGrid = changedGrid)) + model.drawables.drop(1)) + assertEquals(listOf("drawables[0].geometry.cells[0].positionDeltas[5]"), puppetStructureDifferences(model, changed).map { difference -> difference.substringBefore(':') }) + } + + /** + * A buffer carries any float bit for bit, a NaN payload included; the same value inline refuses the save. + */ + @Test + fun bufferCarriesNaNWhileInlineRefuses() { + val base = geometryModel() + val payloadNaN = Float.fromBits(0x7FC00001) + val withNaN = base.copy(drawables = base.drawables.map { drawable -> if (drawable.id == DrawableId("D1")) drawable.copy(mesh = DrawableMesh(floatArrayOf(payloadNaN, 0f, 10f, 0f, 10f, 10f, 0f, 10f), drawable.mesh!!.uvs, drawable.mesh!!.indices)) else drawable }) + val reopened = roundTrip(withNaN) + assertEquals(payloadNaN.toRawBits(), reopened.drawables.first { drawable -> drawable.id == DrawableId("D1") }.mesh!!.positions[0].toRawBits(), "the payload survives") + + val inlineNaN = base.copy(parameters = base.parameters, parts = base.parts, deformers = base.deformers.map { deformer -> if (deformer is Deformer.Rotation) deformer.copy(geometryGrid = KeyformGrid(deformer.geometryGrid!!.axes, listOf(KeyformCell(intArrayOf(0), RotationPivotForm(Float.NaN, 0f, 0f, 1f))))) else deformer }) + val failure = assertFailsWith { UmaPuppetExport.puppetOf(inlineNaN) } + assertTrue(failure.message.orEmpty().contains("deformers[R1].geometry.cells[0].originX"), "the failure names the value: ${failure.message}") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasUndedup.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasUndedup.kt new file mode 100644 index 0000000..b1adedd --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasUndedup.kt @@ -0,0 +1,237 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.atlas.AtlasPackItem +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.AtlasPackReserve +import org.umamo.format.atlas.AtlasPackSkipReason +import org.umamo.format.atlas.packAtlas +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel + +/** + * Un-deduplicates baked atlas twins before fresh-graph synthesis. + * + * A .moc3 bake may pack mirrored duplicates as ONE atlas slot sampled by drawables at different + * canvas placements. The CMO3 model-image web cannot express that shape: a CModelImage carries a + * single canvas placement, so a shared material loses every twin but the first in the editor's + * source-image mode, while duplicated materials over one slot make the editor's atlas recomposite + * stack the shared art's alpha. Official documents never contain the shape either - every corpus + * multi-drawable material is co-located (Erica: 45 of 45 groups share mesh AND placement), and + * real mirror pairs are separate source layers in separate slots. This prepass restores that + * structure: each ADDITIONAL placement of a shared slot gets the patch pixels copied onto a + * synthesized extra page, packed by the shared atlas packer, and its drawables' uvs remapped + * there, so every slot downstream carries a single canvas placement and the image chain builds one + * correctly-placed material per twin. + */ +internal object Cmo3AtlasUndedup { + /** Transparent spacing between packed patches (and the page border): the packer's gutter. */ + private const val PACK_GUTTER = 2 + + /** The un-deduplicated inputs for the fresh-graph pipeline. */ + internal class Result( + val puppet: PuppetModel, + val pages: List, + val pageIndexByDrawableId: Map, + /** The drawables whose uvs were remapped onto a synthesized page, for tests and reports. */ + val duplicatedDrawableIds: List, + /** + * The drawables of a further placement whose patch is too large for a page even on its own, + * left sharing the source slot with their uvs untouched, for the export notice. A further + * placement with no opaque pixel (a hit area's twin) shares silently and is listed nowhere: + * there is nothing to show at either placement, so the web's single placement costs nothing. + */ + val sharedDrawableIds: List = emptyList(), + ) + + /** One atlas slot shared by several drawables: page + uv bbox + the mesh arrays. */ + private class SlotKey( + val pageIndex: Int, + private val uvs: FloatArray, + private val indices: IntArray, + ) { + override fun equals(other: Any?): Boolean = + other is SlotKey && + pageIndex == other.pageIndex && + uvs.contentEquals(other.uvs) && + indices.contentEquals(other.indices) + + override fun hashCode(): Int { + var result = pageIndex + result = 31 * result + uvs.contentHashCode() + result = 31 * result + indices.contentHashCode() + return result + } + } + + /** One placement sub-group needing its own copy of a slot's patch. */ + private class DuplicationJob( + val sourcePageIndex: Int, + val sourceRect: IntArray, + val drawableIds: List, + ) + + /** + * Detects shared slots sampled from multiple canvas placements and gives every additional + * placement its own patch copy on a synthesized page. + * + * @param PuppetModel puppet The model to convert; canvas-frame rest meshes. + * @param List pages The atlas pages, in model3 texture order. + * @param Map pageIndexByDrawableId Each drawable id's atlas page index. + * @return Result The (possibly) remapped puppet, extended page list, and updated page map. + */ + fun undeduplicate( + puppet: PuppetModel, + pages: List, + pageIndexByDrawableId: Map, + ): Result { + // Group drawables by slot, then by quantized placement within the slot. + val placementsBySlot = LinkedHashMap, MutableList>>() + val rectBySlot = HashMap() + for (drawable in puppet.drawables) { + val pageIndex = pageIndexByDrawableId[drawable.id.raw] ?: continue + val page = pages.getOrNull(pageIndex) ?: continue + val mesh = drawable.mesh ?: continue + val rect = Cmo3ImageChainBuilder.patchRectOf(mesh.uvs, page.width, page.height) ?: continue + val slotKey = SlotKey(pageIndex, mesh.uvs, mesh.indices) + rectBySlot[slotKey] = rect + val fit = fitAtlasPageToCanvasTransform(mesh.uvs, mesh.positions, page.width, page.height) + val placementKey = + listOf( + Math.round(fit.m00.toDouble() * 1024), + Math.round(fit.m01.toDouble() * 1024), + Math.round(fit.m10.toDouble() * 1024), + Math.round(fit.m11.toDouble() * 1024), + Math.round(fit.m02.toDouble()), + Math.round(fit.m12.toDouble()), + ) + placementsBySlot + .getOrPut(slotKey) { LinkedHashMap() } + .getOrPut(placementKey) { ArrayList() } + .add(drawable.id.raw) + } + + // The first placement of a slot keeps the original pixels; every further placement is a job. + val jobs = ArrayList() + for ((slotKey, placements) in placementsBySlot) { + if (placements.size < 2) { + continue + } + for ((placementIndex, drawableIds) in placements.values.withIndex()) { + if (placementIndex == 0) { + continue + } + jobs.add(DuplicationJob(slotKey.pageIndex, rectBySlot.getValue(slotKey), drawableIds)) + } + } + if (jobs.isEmpty()) { + return Result(puppet, pages, pageIndexByDrawableId, emptyList()) + } + + // Each job's patch is cut out of its source page and handed to the shared packer as a tile + // whose reserve is the whole patch: the mesh's uv box reaches into the transparent margin + // around the opaque art, and the reserve keeps that margin on the tile's own transparent space + // rather than on a neighbor's pixels. The key is the job's first drawable, stable and unique, + // so the pack is deterministic run to run. + val decodedPages = HashMap() + val jobByKey = LinkedHashMap() + val items = + jobs.map { job -> + val sourcePage = decodedPages.getOrPut(job.sourcePageIndex) { PngCodec.read(pages[job.sourcePageIndex].pngBytes) } + val key = job.drawableIds.first() + jobByKey[key] = job + val width = job.sourceRect[2] - job.sourceRect[0] + val height = job.sourceRect[3] - job.sourceRect[1] + AtlasPackItem(key, width, height, cutPatch(sourcePage, job.sourceRect), reserve = AtlasPackReserve(0, 0, width, height)) + } + // Extrusion stays off and the trim threshold at one: the image chain crops each layer PNG by + // its uv box, so an extruded band inside the reserved margin would put edge color where the + // bake had transparent pixels, and a lossless trim blitted into a transparent reserve + // reproduces the patch verbatim. + val pageCap = maxOf(1024, pages.maxOf { page -> maxOf(page.width, page.height) }) + val packed = + packAtlas( + items, + AtlasPackOptions( + maxPageSize = pageCap, + gutter = PACK_GUTTER, + extrude = 0, + allowRotation = false, + powerOfTwoPages = true, + squarePages = true, + shrinkPages = true, + alphaThreshold = 1, + ), + ) + + // Remap the duplicated drawables' uvs onto the synthesized pages. + val newPageIndexByDrawableId = HashMap(pageIndexByDrawableId) + val remapByDrawableId = HashMap() + val duplicatedIds = ArrayList() + for (placement in packed.placements) { + check(placement.quarterTurns == 0) { "the un-dedup packs without rotation" } + val job = jobByKey.getValue(placement.key) + val sourcePage = pages[job.sourcePageIndex] + val page = packed.pages[placement.pageIndex] + val pageIndex = pages.size + placement.pageIndex + // The packer placed the patch's opaque trim at (pageX, pageY), the trim sitting + // (trimLeft, trimTop) inside the patch: newPagePx = pageX + (oldPagePx - (sourceX + trimLeft)). + val deltaX = (placement.pageX - job.sourceRect[0] - placement.trimLeft).toFloat() + val deltaY = (placement.pageY - job.sourceRect[1] - placement.trimTop).toFloat() + for (drawableId in job.drawableIds) { + newPageIndexByDrawableId[drawableId] = pageIndex + remapByDrawableId[drawableId] = + floatArrayOf(deltaX, deltaY, sourcePage.width.toFloat(), sourcePage.height.toFloat(), page.width.toFloat(), page.height.toFloat()) + duplicatedIds.add(drawableId) + } + } + // A patch the packer could not place keeps its drawables on the source slot. One with no + // opaque pixel shares silently, since nothing shows at either placement; one larger than a + // page even alone is the unrepresentable case the conversion reports. + val sharedIds = + packed.skipped + .filter { skip -> skip.reason == AtlasPackSkipReason.LargerThanPage } + .flatMap { skip -> jobByKey.getValue(skip.key).drawableIds } + val builtPages = pages + packed.pages.map { page -> Cmo3Conversion.AtlasPage(PngCodec.write(page), page.width, page.height) } + + val remappedDrawables = + puppet.drawables.map { drawable -> + val remap = remapByDrawableId[drawable.id.raw] ?: return@map drawable + val mesh = drawable.mesh ?: return@map drawable + val newUvs = FloatArray(mesh.uvs.size) + var componentIndex = 0 + while (componentIndex + 1 < mesh.uvs.size) { + newUvs[componentIndex] = (mesh.uvs[componentIndex] * remap[2] + remap[0]) / remap[4] + newUvs[componentIndex + 1] = (mesh.uvs[componentIndex + 1] * remap[3] + remap[1]) / remap[5] + componentIndex += 2 + } + drawable.copy(mesh = DrawableMesh(mesh.positions, newUvs, mesh.indices)) + } + return Result( + puppet.copy(drawables = remappedDrawables), + builtPages, + newPageIndexByDrawableId, + duplicatedIds, + sharedIds, + ) + } + + /** + * The pixels of one patch rect cut out of a decoded page, as their own straight-alpha raster. + * + * @param RasterImage page The decoded source page. + * @param IntArray rect The patch rect on the page, [x0, y0, x1, y1] with exclusive maxima. + * @return ByteArray The patch's RGBA pixels, row-major from its top row. + */ + private fun cutPatch(page: RasterImage, rect: IntArray): ByteArray { + val width = rect[2] - rect[0] + val height = rect[3] - rect[1] + val rgba = ByteArray(width * height * 4) + for (rowIndex in 0 until height) { + val sourceOffset = ((rect[1] + rowIndex) * page.width + rect[0]) * 4 + page.rgba.copyInto(rgba, rowIndex * width * 4, sourceOffset, sourceOffset + width * 4) + } + return rgba + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasWebIndex.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasWebIndex.kt new file mode 100644 index 0000000..acb4e30 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasWebIndex.kt @@ -0,0 +1,92 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.type.CAffine + +/* + * The retained graph's atlas web indexed by tile id (the model image guid), the one walk both the + * web reconcile and the per-tile placement lowering read. Two copies of the walk would have to + * agree on guid filtering and on capturing the FULL canvas affine, or the reconcile and the lowering + * that runs right after it could classify one tile differently inside a single export. + */ + +/** + * One tracked entry: the element, the atlas that currently holds it, and that atlas's index. + * + * @property ModelImageEntry entry The packed entry. + * @property CTextureAtlas atlas The atlas element holding it. + * @property Int atlasIndex That atlas's index in the texture manager's list. + */ +internal class AtlasEntrySite( + val entry: ModelImageEntry, + val atlas: CTextureAtlas, + val atlasIndex: Int, +) + +/** + * A texture manager's atlas web, keyed by tile id. + * + * @property Map siteByTileId Each tracked entry by the tile it packs. + * @property List strayEntryAtlasIndices The atlas index of every entry that cannot be tracked (no + * guid, or a guid already seen), one element per such entry. + * @property Map modelImageByTileId Each pooled model image by its guid. + * @property Map canvasAffineByTileId Each model image's canvas placement as a six-float affine. + */ +internal class Cmo3AtlasWebIndex( + val siteByTileId: Map, + val strayEntryAtlasIndices: List, + val modelImageByTileId: Map, + val canvasAffineByTileId: Map, +) + +/** + * Indexes [textureManager]'s atlas web. + * + * Built fresh by every pass that reads it rather than shared between them: the web reconcile moves + * entries between atlases, so an index taken before it is stale for the placement lowering that runs + * after. + * + * @param CTextureManager textureManager The retained graph's texture manager. + * @return Cmo3AtlasWebIndex The web as it stands now. + */ +internal fun indexAtlasWeb(textureManager: CTextureManager): Cmo3AtlasWebIndex { + // CMO3: CTextureManager field _textureAtlases -> CTextureAtlas field modelImages -> ModelImageEntry + // field modelImageGuid. Which atlas holds an entry IS the tile's page membership. A guid-less or + // guid-duplicated entry cannot be tracked against the model; it stays where it sits and only + // constrains page deletion. Indices are the RAW list positions, which is what the reconcile + // addresses the list by. + val siteByTileId = HashMap() + val strayEntryAtlasIndices = ArrayList() + for ((atlasIndex, member) in Cmo3Import.elementsOf(textureManager._textureAtlases).withIndex()) { + val atlas = member as? CTextureAtlas ?: continue + for (entry in Cmo3Import.elementsOf(atlas.modelImages).filterIsInstance()) { + val uuid = Cmo3Import.uuidOf(entry.modelImageGuid) + if (uuid == null || siteByTileId.containsKey(uuid)) { + strayEntryAtlasIndices.add(atlasIndex) + } else { + siteByTileId[uuid] = AtlasEntrySite(entry, atlas, atlasIndex) + } + } + } + // CMO3: CTextureManager field _modelImageGroups -> CModelImageGroup field _modelImages -> CModelImage + // fields guid / _materialLocalToCanvasTransform - where the art sits on the CANVAS. A repack moves + // art on the page and never on the canvas, so this is the fixed point every rewritten transform + // pair has to keep composing to. The FULL affine, not just its translation: an official file's + // model images are pure translations, but a converted graph carries the original packing's linear + // part here, and the composition must reproduce it. + val modelImageByTileId = HashMap() + val canvasAffineByTileId = HashMap() + for (group in Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance()) { + for (modelImage in Cmo3Import.elementsOf(group._modelImages).filterIsInstance()) { + val uuid = Cmo3Import.uuidOf(modelImage.guid) ?: continue + modelImageByTileId[uuid] = modelImage + val canvas = modelImage._materialLocalToCanvasTransform as? CAffine ?: continue + canvasAffineByTileId[uuid] = canvas.toAffineArray() + } + } + return Cmo3AtlasWebIndex(siteByTileId, strayEntryAtlasIndices, modelImageByTileId, canvasAffineByTileId) +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasWebLowering.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasWebLowering.kt new file mode 100644 index 0000000..fa2acd6 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3AtlasWebLowering.kt @@ -0,0 +1,539 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3GraphEditor +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.composeAffine +import org.umamo.runtime.model.inversePlacementAffine +import org.umamo.runtime.model.lineageRoot +import org.umamo.runtime.model.placementAffine +import java.util.IdentityHashMap + +/** + * The full atlas-web reconcile: page set, entry membership, drawable texture + * references, and page images, brought to the EDITED model's packing as one all-or-nothing pass. + * + * The membership half is the load-bearing one: a ModelImageEntry physically lives inside its page's + * CTextureAtlas element, and the import reads a tile's page purely from which atlas holds its entry. + * Rewriting the entry's transforms without also moving the entry between atlases would leave a file + * whose placements point at one page while the membership still names another - a jumbled reimport, + * the failure mode this class exists to close. + * + * Everything here follows the model's page order: model page i is `_textureAtlases[i]`, so the page + * set reconciles positionally - retained atlases are reused in place (their page resources mutated, + * never replaced, because page-resource IDENTITY is what storedUvsAddressPages recovery reads), + * atlases past the retained count are minted with the fresh conversion's own builders, and retained + * atlases past the edited count are deleted after everything living has moved out of them. + * + * A pack-in - a bound tile that never had an entry gaining a placement - mints the entry and each + * bound drawable's region input, so a whole-model repack of a document with never-packed bound art + * (Erica carries three such drawables) exports consistently too. + * + * The art itself is the retained layer web's ([Cmo3RetainedLayerWeb]): a tile the graph has no + * model image for (a reload's added layer, an Add Artwork file) has its layer and model image minted + * before the pack-in mints its entry, and a reloaded tile has its lineage root's layer rewritten to + * the new pixels before the entry moves - so the layered image the official editor shows is the art + * the pages carry. A created drawable over any tile with a model image and a placement is handed a + * texture binding ([Result.mintedBindings]), which the structural pass binds it through. + * + * All or nothing: validation runs first and any gap declines the WHOLE reconcile - the honest + * notices then flow from the property lowering unchanged. Nothing here may half-write, because the + * reconcile has no rollback. + */ +internal class Cmo3AtlasWebLowering( + private val target: Cmo3Model, + private val modelSource: CModelSource, + private val baseline: PuppetModel, + private val edited: PuppetModel, + private val editor: Cmo3GraphEditor, + private val tileRasters: (AtlasTileId) -> RasterImage?, + private val nowMillis: Long, + // The document's texture frames, taken from the graph before the export changed it. + private val textureFrames: Cmo3TextureFrames, +) { + /** + * What the reconcile did. + * + * @property Boolean pagesRecomposed True when the full web reconcile ran; the stale-page notices + * key on it. + * @property Boolean pruneNeeded True when graph structure was dropped, so the export must run + * the shared-pool prune. + * @property Map mintedBindings A texture binding for every created drawable over a tile the + * web now holds, by drawable id; the structural pass binds + * such a drawable through it. + * @property Set reconciledTileIds The lineage roots whose layer web was minted or rewritten, + * so the tile lowering owes no metadata notice for them. + */ + class Result( + val pagesRecomposed: Boolean, + val pruneNeeded: Boolean, + val mintedBindings: Map = emptyMap(), + val reconciledTileIds: Set = emptySet(), + ) { + companion object { + /** The no-op outcome: nothing touched, notices stay. */ + val Declined: Result = Result(pagesRecomposed = false, pruneNeeded = false) + } + } + + /** One drawable source whose region input must be rewritten for its tile's new placement. */ + private class RetargetCandidate( + val source: CArtMeshSource, + val region: CTextureInput_TextureAtlasRegion, + val input: CAffine, + val tileId: String, + ) + + /** One drawable source over a packed-IN tile, which gains a fresh region input. */ + private class PackInCandidate( + val source: CArtMeshSource, + val extension: CTextureInputExtension, + val tileId: String, + ) + + /** + * Reconciles the atlas web onto [recomposedPages], or declines whole. + * + * @param List recomposedPages The pages composed for the edited model's packing, in its page order. + * @return Result Whether the reconcile ran, and whether it dropped structure. + */ + fun reconcile(recomposedPages: List): Result { + if (recomposedPages.isEmpty()) { + return Result.Declined + } + // CMO3: CModelSource field textureManager -> CTextureManager field _textureAtlases. + val textureManager = modelSource.textureManager as? CTextureManager ?: return Result.Declined + val atlasList = mutableGraphListOf(textureManager._textureAtlases) ?: return Result.Declined + if (atlasList.any { member -> member !is CTextureAtlas }) { + return Result.Declined + } + val newPageCount = edited.atlas.pages.size + // The pages are the EDITED model's inventory, in its own page order: same count, positionally + // indexed. The patch stays authoritative on dimensions, matching the reuse arm's existing + // contract. + if (recomposedPages.size != newPageCount) { + return Result.Declined + } + + // --- Gather the web. --- + // The model-image and canvas-placement maps are LOCAL copies: the layer web below extends them + // with what it mints and moves, and every composition after that reads the extended state. + val web = indexAtlasWeb(textureManager) + val siteByTileId = web.siteByTileId + val strayEntryAtlasIndices = web.strayEntryAtlasIndices + val canvasAffineByTileId = HashMap(web.canvasAffineByTileId) + val modelImageByTileId = HashMap(web.modelImageByTileId) + val retainedWeb = Cmo3RetainedLayerWeb(target, textureManager, editor, edited, tileRasters, nowMillis, textureFrames) + + // --- Classify every edited tile; ANY gap declines whole. --- + // Every tile is keyed by its LINEAGE ROOT: a reloaded tile (`~`, AtlasTile.replaces) is + // the model image its root imported from as far as the web knows, so its placement reads as that + // entry moving - and its layer is rewritten to the new art (a rewrite job) before the entry + // does. A tile with no model image at all has its whole layer web minted (a mint job), which + // is what lets its pack-in mint an entry. + val baselinePlacementByTileId = baseline.atlas.tiles.associateBy({ tile -> tile.id.lineageRoot.raw }, { tile -> tile.placement }) + val editedTileIds = HashSet() + val changedPlacementByTileId = HashMap>() + val boundTileIds = edited.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId?.lineageRoot?.raw } + val moves = ArrayList>() + val packOuts = ArrayList() + val packInPlacementByTileId = LinkedHashMap() + val rewriteJobs = ArrayList() + val mintJobs = ArrayList() + for (tile in edited.atlas.tiles) { + val tileId = tile.id.lineageRoot.raw + editedTileIds.add(tileId) + val newPlacement = tile.placement + val site = siteByTileId[tileId] + val modelImage = modelImageByTileId[tileId] + if (modelImage == null) { + // No model image: the tile's art is minted when the document holds it. An unplaced + // tile with nothing to mint has nothing to reconcile either; a placed one must mint, + // or its pack-in has no image to hang the entry on. + val job = retainedWeb.mintJobFor(tile) + if (job != null) { + mintJobs.add(job) + canvasAffineByTileId[tileId] = job.canvasAffine + } else if (newPlacement != null) { + return Result.Declined + } + } else if (tile.replaces != null) { + // A reloaded tile: the root's layer takes the new art, and the canvas placement every + // composition below reads is the refreshed row's origin. + val job = retainedWeb.rewriteJobFor(tile, modelImage) ?: return Result.Declined + rewriteJobs.add(job) + canvasAffineByTileId[tileId] = job.canvasAffine + } + if (newPlacement == null) { + if (site != null) { + // A pack-out removes the entry; a drawable still sampling the page through it + // would be stranded, so a BOUND pack-out declines (the repack never produces one). + if (tileId in boundTileIds) { + return Result.Declined + } + packOuts.add(site) + } + continue + } + if (site == null) { + // Pack-in: a never-packed tile gaining a placement mints its entry and its bound + // drawables' region inputs below - possible only when the tile's canvas placement + // resolves (a minted tile's is the job's). + if (canvasAffineByTileId[tileId] == null) { + return Result.Declined + } + if (newPlacement.pageIndex !in 0 until newPageCount || inversePlacementAffine(newPlacement) == null) { + return Result.Declined + } + packInPlacementByTileId[tileId] = newPlacement + continue + } + if (newPlacement.pageIndex !in 0 until newPageCount) { + return Result.Declined + } + if (canvasAffineByTileId[tileId] == null || inversePlacementAffine(newPlacement) == null) { + return Result.Declined + } + val oldPlacement = baselinePlacementByTileId[tileId] + if (oldPlacement != newPlacement) { + changedPlacementByTileId[tileId] = oldPlacement to newPlacement + } + if (newPlacement.pageIndex != site.atlasIndex) { + moves.add(site to newPlacement) + } + } + // Entries the edited model does not track (stray, or a tile outside the edited set) stay + // where they sit - which must survive the page-set reconcile. + for (atlasIndex in strayEntryAtlasIndices) { + if (atlasIndex >= newPageCount) { + return Result.Declined + } + } + for ((tileId, site) in siteByTileId) { + if (tileId !in editedTileIds && site.atlasIndex >= newPageCount) { + return Result.Declined + } + } + + // --- Gather the drawables to retarget: every source over a placement-changed tile. --- + // CMO3: CDrawableSourceSet field _sources -> CArtMeshSource field _extensions -> + // CTextureInputExtension field _textureInputs. + val artMeshes = + Cmo3Import.elementsOf((modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + val editedDrawableIds = edited.drawables.mapTo(HashSet()) { drawable -> drawable.id.raw } + val fileDrawableIds = HashSet() + val meshByDrawableId = HashMap() + val candidates = ArrayList() + val packInCandidates = ArrayList() + val existingTextureByAtlasIndex = HashMap() + for (mesh in artMeshes) { + val drawableId = Cmo3Import.idStrOf(mesh.id) ?: continue + fileDrawableIds.add(drawableId) + val texture = mesh.texture as? GTexture2D + if (texture != null) { + // The page's ONE shared texture, found by resource identity - the same rule the + // import's page-packed classification reads. + val sampled = texture.srcImageResource + for ((atlasIndex, member) in atlasList.withIndex()) { + if ((member as CTextureAtlas).cachedAtlasImage === sampled) { + existingTextureByAtlasIndex.putIfAbsent(atlasIndex, texture) + } + } + } + if (drawableId !in editedDrawableIds) { + // Pending deletion: the structural pass removes the source; nothing to retarget. + continue + } + meshByDrawableId[drawableId] = mesh + val extension = + Cmo3Import.elementsOf(mesh._extensions).filterIsInstance().firstOrNull() ?: continue + val tileId = + Cmo3Import.uuidOf( + Cmo3Import.elementsOf(extension._textureInputs) + .filterIsInstance() + .firstOrNull() + ?._modelImageGuid, + ) ?: continue + val region = + Cmo3Import.elementsOf(extension._textureInputs) + .filterIsInstance() + .firstOrNull() + if (tileId in packInPlacementByTileId) { + if (region != null) { + // A region input over a tile with no entry is an inconsistent web; decline whole + // rather than guess which half to trust. + return Result.Declined + } + packInCandidates.add(PackInCandidate(mesh, extension, tileId)) + continue + } + if (tileId !in changedPlacementByTileId) { + continue + } + if (region == null) { + // A bound drawable sampling its art directly while its tile's packing moved: the + // re-derived page-frame coordinates have no region input to ride, so decline whole. + return Result.Declined + } + val input = region.inputImageLocalToCanvasTransform as? CAffine ?: return Result.Declined + candidates.add(RetargetCandidate(mesh, region, input, tileId)) + } + // Every EDITED drawable the file holds over a packed-in tile must have been found file-side, + // or its re-derived page-frame coordinates would export with nothing retargeting its sampling. + // A created drawable (not in the file yet) takes the binding path instead. + for (tileId in packInPlacementByTileId.keys) { + val editedBound = edited.drawables.count { drawable -> drawable.atlasTileId?.lineageRoot?.raw == tileId && drawable.id.raw in fileDrawableIds } + val found = packInCandidates.count { candidate -> candidate.tileId == tileId } + if (editedBound != found) { + return Result.Declined + } + } + + val reconciledTileIds = HashSet() + rewriteJobs.mapTo(reconciledTileIds) { job -> job.tileId } + mintJobs.mapTo(reconciledTileIds) { job -> job.tileId } + + // --- Mutation. Validation is complete; anything impossible past here is a caller bug. --- + // 0. The layer web: rewrites and mints, so every model image the steps below hang an entry on + // or compose against exists and holds the edited art. A file-side drawable over reconciled + // art has its icons re-rendered, since they show the pixels that just changed. + val applied = retainedWeb.apply(rewriteJobs, mintJobs) + modelImageByTileId.putAll(applied.modelImageByTileId) + for (drawable in edited.drawables) { + val mesh = meshByDrawableId[drawable.id.raw] ?: continue + val editedTileId = drawable.atlasTileId ?: continue + if (editedTileId.lineageRoot.raw !in reconciledTileIds) { + continue + } + val raster = tileRasters(editedTileId) ?: continue + retainedWeb.replaceDrawableIcons(mesh, raster, Cmo3Icons.artUvsOf(edited, drawable)) + } + + // 1. Snapshots, so every rewrite reads pre-mutation values regardless of sharing. + val oldEntryHalfByTileId = HashMap() + for (tileId in changedPlacementByTileId.keys) { + val entryHalf = siteByTileId.getValue(tileId).entry.atlasLocalToCanvasTransform as? CAffine ?: continue + oldEntryHalfByTileId[tileId] = entryHalf.toAffineArray() + } + val oldInputByRegion = IdentityHashMap() + for (candidate in candidates) { + oldInputByRegion.getOrPut(candidate.region) { candidate.input.toAffineArray() } + } + + // 2. Reuse retained pages in model order: bytes always, the dimension web on a resize. The + // resource is mutated IN PLACE, never replaced - its identity is the storedUvsAddressPages + // recovery test. + val retainedCount = minOf(atlasList.size, newPageCount) + for (pageIndex in 0 until retainedCount) { + val atlas = atlasList[pageIndex] as CTextureAtlas + val page = recomposedPages[pageIndex] + // CMO3: CTextureAtlas field cachedAtlasImage - the page's CImageResource. + val resource = atlas.cachedAtlasImage as? CImageResource ?: return Result.Declined + if (resource.imageFileBuf == null) { + return Result.Declined + } + target.replaceLayerPng(resource, page.pngBytes) + if (resource.width != page.width || resource.height != page.height) { + // CMO3: CImageResource fields width / height - corpus-verified to equal the decoded PNG's. + resource.width = page.width + resource.height = page.height + // CMO3: CTextureAtlas fields width / height - the page extent the reader trusts. + atlas.width = page.width + atlas.height = page.height + // CMO3: CTextureAtlas field cachedImageManager - rebuilt so the cache raster's + // 64-aligned padding transform describes the NEW dimensions. + atlas.cachedImageManager = Cmo3ImageChainBuilder.paddedCacheManager(resource, page.width, page.height) + } + } + + // 3. Mint pages past the retained count, with the fresh conversion's own builders. + val mintedTextureByAtlasIndex = HashMap() + for (pageIndex in atlasList.size until newPageCount) { + val page = recomposedPages[pageIndex] + val path = target.nextImageFileBufPath() + val resource = Cmo3ImageChainBuilder.pageImageResource(path, page.width, page.height, page.pngBytes.size) + target.addLayerPng(resource, page.pngBytes) + val atlas = Cmo3ImageChainBuilder.pageAtlas(pageIndex, page.width, page.height, resource) + atlasList.add(atlas) + mintedTextureByAtlasIndex[pageIndex] = Cmo3ImageChainBuilder.pageTexture(atlas.name, resource) + } + + // 4. Re-home every cross-page entry: list membership plus the owning-page back-reference. + for ((site, newPlacement) in moves) { + val destination = atlasList[newPlacement.pageIndex] as CTextureAtlas + mutableGraphListOf(site.atlas.modelImages)?.remove(site.entry) + mutableGraphListOf(destination.modelImages)?.add(site.entry) + // CMO3: ModelImageEntry field atlas - the owning-page back-reference. + site.entry.atlas = destination + } + + // 5. Pack-outs: the entry leaves its page (import reads placement=null from entry absence); + // the tile's CModelImage web stays - the art inventory is untouched. + for (site in packOuts) { + mutableGraphListOf(site.atlas.modelImages)?.remove(site.entry) + } + + // The page's shared texture, for every drawable that samples the page from here on. + fun pageTextureFor(pageIndex: Int): GTexture2D { + mintedTextureByAtlasIndex[pageIndex]?.let { minted -> return minted } + return existingTextureByAtlasIndex.getOrPut(pageIndex) { + // No drawable ever sampled this retained page; give it the shared texture the fresh + // path would have built. + val atlas = atlasList[pageIndex] as CTextureAtlas + Cmo3ImageChainBuilder.pageTexture(atlas.name, atlas.cachedAtlasImage as CImageResource) + } + } + + // 6. Pack-ins: mint the entry the tile never had. The transforms are written with the same + // shared math the property lowering uses, which then rewrites them identically for the + // placement diff - the mint exists so an entry is THERE to rewrite. + for ((tileId, newPlacement) in packInPlacementByTileId) { + val destination = atlasList[newPlacement.pageIndex] as CTextureAtlas + val modelImage = modelImageByTileId.getValue(tileId) + val canvasAffine = canvasAffineByTileId.getValue(tileId) + val entryHalf = + checkNotNull(atlasLocalToCanvasFor(canvasAffine, newPlacement)) { + "pack-in tile '$tileId' lost its composition after validation" + } + val entry = + Cmo3ImageChainBuilder.packedEntry( + atlas = destination, + modelImageGuid = modelImage.guid, + atlasLocalToCanvas = affineOf(entryHalf), + packing = Cmo3ImageChainBuilder.writePacking(GTransform2(), newPlacement), + ) + mutableGraphListOf(destination.modelImages)?.add(entry) + } + + // 7. Delete retained atlases past the edited count, highest first. Validation moved or + // removed every tracked entry; a leftover here is a validation bug, not document state. + var deletedAny = false + for (pageIndex in atlasList.size - 1 downTo newPageCount) { + val atlas = atlasList[pageIndex] as CTextureAtlas + check(Cmo3Import.elementsOf(atlas.modelImages).filterIsInstance().isEmpty()) { + "atlas $pageIndex still holds entries after the membership reconcile" + } + (atlas.cachedAtlasImage as? CImageResource)?.let { resource -> target.removeLayerPng(resource) } + atlasList.removeAt(pageIndex) + deletedAny = true + } + + // 8. Retarget every candidate from the snapshots. + for (candidate in candidates) { + val (oldPlacement, newPlacement) = changedPlacementByTileId.getValue(candidate.tileId) + val site = siteByTileId.getValue(candidate.tileId) + if (newPlacement.pageIndex != site.atlasIndex) { + val destination = atlasList[newPlacement.pageIndex] as CTextureAtlas + // CMO3: CArtMeshSource field texture - the page's shared GTexture2D. + candidate.source.texture = pageTextureFor(newPlacement.pageIndex) + // CMO3: CTextureInput_TextureAtlasRegion field textureAtlasGuid - repointed at the + // destination atlas's own guid object (the official files' shared-ref shape). + candidate.region.textureAtlasGuid = destination.guid + } + val canvasAffine = canvasAffineByTileId.getValue(candidate.tileId) + val snapshotInput = oldInputByRegion.getValue(candidate.region) + val entryOldHalf = oldEntryHalfByTileId[candidate.tileId] + // CMO3: CTextureInput_TextureAtlasRegion field inputImageLocalToCanvasTransform - the + // PAGE-pixels-to-canvas placement the editor inverts for its mesh-over-patch views. The + // corpus keeps it equal to the entry's atlasLocalToCanvasTransform, so when the old input + // matched the entry's old half it is written through the same shared math the entry pair + // takes (bit-identical); a drawable carrying its own placement (a shared tile sampled + // from two spots) keeps its own via the exact re-fit oldInput + // composed-with P_old composed-with P_new-inverse. + val newInput = + if (entryOldHalf != null && snapshotInput.contentEquals(entryOldHalf)) { + atlasLocalToCanvasFor(canvasAffine, newPlacement) + } else if (oldPlacement != null) { + inversePlacementAffine(newPlacement)?.let { inverseNew -> + composeAffine(composeAffine(snapshotInput, placementAffine(oldPlacement)), inverseNew) + } + } else { + atlasLocalToCanvasFor(canvasAffine, newPlacement) + } + checkNotNull(newInput) { "tile '${candidate.tileId}' lost its input re-fit after validation" } + candidate.input.setFromAffineArray(newInput) + } + + // 9. Pack-in drawables: a fresh region input into the EXISTING extension (the shape + // freshTextureInputExtension writes for a created drawable), the page's shared texture, and + // the live input pointer when the document displays from the atlas. The reconcile runs + // before the drawable lowering, so storedUvsFor then sees the region and writes the repack's + // page-frame coordinates verbatim. + for (candidate in packInCandidates) { + val newPlacement = packInPlacementByTileId.getValue(candidate.tileId) + val destination = atlasList[newPlacement.pageIndex] as CTextureAtlas + val inputAffine = + checkNotNull(atlasLocalToCanvasFor(canvasAffineByTileId.getValue(candidate.tileId), newPlacement)) { + "pack-in tile '${candidate.tileId}' lost its input re-fit after validation" + } + // CMO3: CArtMeshSource field texture - the page's shared GTexture2D. + candidate.source.texture = pageTextureFor(newPlacement.pageIndex) + val region = + CTextureInput_TextureAtlasRegion().apply { + // CMO3: CTextureInput_TextureAtlasRegion fields textureAtlasGuid + + // inputImageLocalToCanvasTransform (ACTextureInput super carries the owner backref). + optionalTransformOnCanvas = CAffine() + _owner = candidate.extension + textureAtlasGuid = destination.guid + inputImageLocalToCanvasTransform = affineOf(inputAffine) + } + mutableGraphListOf(candidate.extension._textureInputs)?.add(region) + if (!edited.rendersFromSourceLayers) { + // CMO3: CTextureInputExtension field currentTextureInputData - which input the + // document's display mode samples. + candidate.extension.currentTextureInputData = region + } + } + + // 10. Bindings for the created drawables: every drawable the file does not hold yet whose tile + // has a model image and a placement gets the page's shared texture, the page's atlas, the + // model image, the entry's transform as its region input, and its own icons over its patch - + // the official relation, and the shape the fresh web hands the structural pass for the same + // drawable. + val editedPlacementByTileId = edited.atlas.tiles.associateBy({ tile -> tile.id.lineageRoot.raw }, { tile -> tile.placement }) + val mintedBindings = HashMap() + for (drawable in edited.drawables) { + if (drawable.id.raw in fileDrawableIds) { + continue + } + val editedTileId = drawable.atlasTileId ?: continue + val tileId = editedTileId.lineageRoot.raw + val placement = editedPlacementByTileId[tileId] ?: continue + val modelImage = modelImageByTileId[tileId] ?: continue + val canvasAffine = canvasAffineByTileId[tileId] ?: continue + val entryHalf = atlasLocalToCanvasFor(canvasAffine, placement) ?: continue + val destination = atlasList.getOrNull(placement.pageIndex) as? CTextureAtlas ?: continue + val icons = tileRasters(editedTileId)?.let { raster -> retainedWeb.drawableIcons(raster, Cmo3Icons.artUvsOf(edited, drawable)) } + mintedBindings[drawable.id.raw] = + Cmo3DrawableTextureBinding( + pageTextureFor(placement.pageIndex), + destination.guid as Guid, + modelImage.guid as Guid, + affineOf(entryHalf), + icon32 = icons?.first, + icon16 = icons?.second, + ) + } + + return Result(pagesRecomposed = true, pruneNeeded = deletedAny || packOuts.isNotEmpty() || applied.releasedCopy, mintedBindings = mintedBindings, reconciledTileIds = reconciledTileIds) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Conversion.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Conversion.kt new file mode 100644 index 0000000..a5e553a --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Conversion.kt @@ -0,0 +1,210 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.raster.RasterImage +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportReport +import org.umamo.interop.cmo3TargetVersionNo +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import kotlin.math.roundToInt + +/** + * Converts a puppet with NO retained CMO3 graph (a MOC3-origin or artwork-origin document) into a + * fresh Cmo3Model: the blank skeleton plus the image chain are synthesized, serialized, and read + * back through the normal codec, then the ordinary reconcile lowers the whole puppet onto the empty + * baseline as created entities. Stateless - each call builds a new graph; the caller writes the + * result with Cmo3.write. + * + * The file this produces opens and renders in the official Cubism Editor and switches between its + * layered-art and texture-atlas display modes. An artwork-origin document writes its REAL source + * art: every tile with a raster and an inventory row becomes a layer of its file's layered image + * ([Cmo3SourceLayerWeb]), so the export is the shape the editor writes for its own PSD import and + * reopens with the same layer identities. A MOC3-origin document has none of that: a .moc3 + * carries only the packed pages, so [Cmo3ImageChainBuilder] fabricates a source document by slicing + * the packed atlas back apart, every layer in that output is a slice of a baked page rather than the + * artwork the rig was drawn from, and the report leads with MissingSourceArt for as long as any + * drawable's art came out of a page. + * + * One open issue at scale: modelF (~850 MB, several hundred layers) OOMs the official editor when + * switched back to texture-atlas mode. Atlas mode recomposites the page from the materials, so + * peak memory tracks the TOTAL crop area this builder emits rather than the page size - measure + * that ratio before treating it as an editor limit. + * + * The CMO3-origin path ([Cmo3Export.apply] onto a retained graph) keeps the document's real + * layered art, and its byte-identity gates hold. + */ +public object Cmo3Conversion { + /** One atlas page: the original PNG bytes (model3 texture order) plus its pixel dimensions. */ + public class AtlasPage( + public val pngBytes: ByteArray, + public val width: Int, + public val height: Int, + ) + + /** + * The conversion outcome: the fresh model, the reconcile's advisory report, and the puppet + * actually encoded - the input after the atlas un-dedup prepass, whose uvs differ from the + * caller's wherever a baked twin was routed to its own synthesized slot. Round-trip checks + * must compare a re-import against THIS puppet, not the caller's. + */ + public class Result( + public val model: Cmo3Model, + public val report: ExportReport, + public val puppet: PuppetModel, + ) + + /** + * Builds a fresh CMO3 for [puppet]. + * + * @param PuppetModel puppet The model to convert (the session's current state). + * @param List pages The atlas pages, in model3 texture order. + * @param Map pageIndexByDrawableId Each drawable id's atlas page index; a drawable + * missing here cannot bind a texture and surfaces as a notice. + * @param String modelName The document display name the skeleton records. + * @param Long nowMillis The wall-clock import timestamp the image chain records. + * @param Int obfuscateKey The container XOR key; the editor mints one per save. + * @param Function tileRasters The document's own pixels for a tile, or null when it holds + * none; a tile with a raster and an inventory row writes its real + * layer, every other drawable takes the crop stand-in. A + * MOC3-origin document has no tiles and passes nothing. + * @param RasterImage modelThumbnail The model's rest-pose thumbnail the three model icons fit, + * or null for the blank icons the editor writes for a model it + * never rendered. + * @return Result The fresh model plus the reconcile report. + */ + public fun freshCmo3( + puppet: PuppetModel, + pages: List, + pageIndexByDrawableId: Map, + modelName: String, + nowMillis: Long, + obfuscateKey: Int, + tileRasters: (AtlasTileId) -> RasterImage? = { null }, + modelThumbnail: RasterImage? = null, + ): Result { + // Real layers first: a drawable whose tile has a raster and an inventory row writes that + // raster as its own layer, and leaves the crop path - the un-dedup included, since a real + // tile's model image is the single-placement shape by construction. + val sourceImages = Cmo3SourceLayerWeb.inputsOf(puppet, tileRasters) + val realDrawableIds = sourceImages.flatMapTo(HashSet()) { image -> image.layers.flatMap { layer -> layer.drawableIds } } + val cropPageIndexByDrawableId = pageIndexByDrawableId.filterKeys { drawableId -> drawableId !in realDrawableIds } + // Baked twins (one atlas slot, several canvas placements) are unrepresentable in the + // model-image web; the prepass copies each additional placement's patch onto a synthesized + // page and remaps those drawables' uvs there. Everything below runs on ITS outputs. + val undedup = Cmo3AtlasUndedup.undeduplicate(puppet, pages, cropPageIndexByDrawableId) + val effectivePuppet = undedup.puppet + val effectivePages = undedup.pages + val effectivePageIndexByDrawableId = undedup.pageIndexByDrawableId + val skeleton = + Cmo3SkeletonBuilder.buildBlank( + modelName = modelName, + canvasWidth = effectivePuppet.canvasWidth.roundToInt(), + canvasHeight = effectivePuppet.canvasHeight.roundToInt(), + targetVersionNo = effectivePuppet.runtimeTarget.cmo3TargetVersionNo(), + modelThumbnail = modelThumbnail, + ) + // Each page's drawable regions feed the per-drawable patch webs (crop + placement fit). + // The puppet's mesh.positions MUST be canvas-frame here: the app's MOC3 document loader + // normalizes parent-local rest meshes through :render's restMeshesToCanvasSpace before any + // export, and callers converting a raw Moc3Import puppet must do the same (the official + // source-level positions and the whole placement web are canvas geometry). + val regionsByPage = List(effectivePages.size) { ArrayList() } + for (drawable in effectivePuppet.drawables) { + val pageIndex = effectivePageIndexByDrawableId[drawable.id.raw] ?: continue + val mesh = drawable.mesh ?: continue + regionsByPage.getOrNull(pageIndex)?.add( + Cmo3ImageChainBuilder.DrawableRegion(drawable.id.raw, mesh.uvs, mesh.positions, mesh.indices), + ) + } + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + effectivePages, + regionsByPage, + nowMillis, + fromSourceLayers = effectivePuppet.rendersFromSourceLayers, + sourceImages = sourceImages, + ) + val model = + Cmo3.read( + Cmo3FreshFile.assemble( + skeleton.root, + skeleton.iconEntries.map { icon -> + Cmo3FreshFile.PngEntry( + icon.path, + icon.pngBytes, + ) + } + chain.pngEntries, + obfuscateKey, + ), + ) + rebindPageResources(chain, model) + val bindings = HashMap() + for (drawable in effectivePuppet.drawables) { + // A real-layer drawable has its own binding; a crop-path drawable its own or its page's. + val binding = + chain.bindingByDrawableId[drawable.id.raw] + ?: effectivePageIndexByDrawableId[drawable.id.raw]?.let { pageIndex -> chain.pageFallbackBindings.getOrNull(pageIndex) } + binding?.let { resolved -> bindings[drawable.id.raw] = resolved } + } + val report = Cmo3Export.apply(effectivePuppet, model, bindings) + // An export whose art did not all come from real layers - a drawable sliced out of a page or + // bound to no page, or a document with no real layer to write at all - is source-art-less, so + // the notice leads the report rather than hiding behind the per-entity findings. It is the + // one finding that describes the WHOLE file rather than an entity in it, which no amount of + // per-drawable detail would tell the user; a document whose every drawable wrote its real + // layer carries no such finding. A twin the prepass had to leave sharing its slot follows + // it, for the same reason. + val everyDrawableIsReal = sourceImages.isNotEmpty() && effectivePuppet.drawables.all { drawable -> drawable.id.raw in realDrawableIds } + val leading = ArrayList() + if (!everyDrawableIsReal) { + leading.add(ExportNotice.MissingSourceArt(effectivePages.size)) + } + if (undedup.sharedDrawableIds.isNotEmpty()) { + val nameById = effectivePuppet.drawables.associate { drawable -> drawable.id.raw to drawable.name } + leading.add(ExportNotice.SharedAtlasSlotKept(undedup.sharedDrawableIds.map { drawableId -> nameById[drawableId] ?: drawableId })) + } + return Result(model, report.copy(notices = leading + report.notices), effectivePuppet) + } + + /** + * Re-points each page texture at the RE-READ atlas's own page resource. + * + * The image chain is built over the pre-serialization skeleton, so a binding's GTexture2D still + * carries that graph's CImageResource - while the reconcile hangs that texture off drawables in + * the graph read back out of the assembled bytes. Left alone the document ends up with two + * equal-but-distinct resources per page (one under the atlas's cachedAtlasImage, one under the + * drawables' texture) where the editor's own files share a single one by reference. + * + * That split is not cosmetic: whether a drawable's uvs are page-frame is decided by whether the + * resource it samples IS one of the atlases' page resources (docs/format/CMO3.md section 6 - a + * document can carry an atlas while its drawables sample per-layer rasters instead), and the test + * is identity because a CImageResource has no value equality. With the twin resource in place + * every re-imported drawable reads as never-packed, so its source-layer view drops the packing + * inverse and draws atlas-frame uvs straight onto the layer crop. + * + * @param Cmo3ImageChainBuilder.BuiltImageChain chain The image chain built over the skeleton. + * @param Cmo3Model model The model read back out of the assembled bytes. + */ + private fun rebindPageResources(chain: Cmo3ImageChainBuilder.BuiltImageChain, model: Cmo3Model) { + // CMO3: CModelSource field textureManager -> CTextureManager field _textureAtlases -> + // CTextureAtlas field cachedAtlasImage - the page's own pixels. + val textureManager = (model.root as? CModelSource)?.textureManager as? CTextureManager ?: return + val pageResourceByPath = HashMap() + for (atlas in Cmo3Import.elementsOf(textureManager._textureAtlases).filterIsInstance()) { + val pageResource = atlas.cachedAtlasImage as? CImageResource ?: continue + pageResource.imageFileBuf?.archivePath?.let { path -> pageResourceByPath[path] = pageResource } + } + // One texture per page, shared by every binding on it, so the page fallbacks reach them all. + for (binding in chain.pageFallbackBindings) { + val path = (binding.texture.srcImageResource as? CImageResource)?.imageFileBuf?.archivePath ?: continue + pageResourceByPath[path]?.let { pageResource -> binding.texture.srcImageResource = pageResource } + } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3DrawableTextureBinding.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3DrawableTextureBinding.kt new file mode 100644 index 0000000..5b82db7 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3DrawableTextureBinding.kt @@ -0,0 +1,163 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.type.CAffine + +/** + * The texture web a synthesized drawable binds to when it has no existing source to clone - the + * per-page objects the image-chain builder created (docs/format/CMO3.md §4 How a Drawable + * References its Texture). Instances are shared per atlas page: every drawable on the page + * references the SAME GTexture2D and guid objects, so the writer hoists them exactly like the + * editor's own files (one atlas GTexture2D for all packed drawables). The icons are the drawable's + * own (one per drawable, like the editor's files), their PNG entries already collected or embedded + * by whoever built the binding. + */ +public class Cmo3DrawableTextureBinding( + /** The page's shared texture (srcImageResource = the page CImageResource). */ + val texture: GTexture2D, + /** The page's CTextureAtlas guid - the atlas-region input's target. */ + val textureAtlasGuid: Guid, + /** The drawable's own CModelImage guid (its patch web), or null when it has no patch. */ + val modelImageGuid: Guid?, + /** The drawable's fitted atlas-page-to-canvas placement (the region input's transform). */ + val inputImageLocalToCanvasTransform: CAffine, + /** The drawable's 32px thumbnail of its texture patch, or null when it has no art to show. */ + val icon32: CImageIcon? = null, + /** The drawable's 16px thumbnail, or null likewise. */ + val icon16: CImageIcon? = null, +) + +/** + * Fits a drawable's atlas-page-to-canvas placement transform: the affine mapping page pixel + * coordinates (uv times page size) onto the drawable's base mesh positions. + * + * CMO3: CTextureInput_TextureAtlasRegion field inputImageLocalToCanvasTransform - the editor + * inverts this to place the mesh over its texture patch in the atlas and mesh-edit views, so an + * identity here draws every mesh at its assembled canvas position instead. Cubism-authored + * mappings are exact per-drawable affines (the layer's canvas translation composed with the + * packer's scale, rotation, and translate), so a least-squares fit recovers them to float + * precision; a degenerate mesh falls back to a single-axis regression, then to a pure centroid + * translation. + * + * The moments are accumulated about the point cloud's MEAN, not about the page origin, and that is + * load-bearing rather than a tidiness preference. A patch sits thousands of pixels out on a + * 16384-square page while spanning only a few hundred, so origin-referenced moments are dominated + * by the offset: the system's conditioning picks up the squared offset-to-spread ratio, the + * informative pivot falls far below any offset-scaled singularity tolerance, and a perfectly + * determined fit is rejected as degenerate. What it degrades to - a per-axis regression - cannot + * express an off-diagonal term at all, so a drawable the packer rotated comes back squashed onto + * the wrong axis. Centering drops the offset term outright: the solve sees only the cloud's own + * shape, and the translation comes back from the means. + * + * A packing that rotates or mirrors the patch is therefore carried faithfully. The crop the image + * chain slices out is still the axis-aligned uv bounding box, which for a rotated patch encloses + * the art plus its surrounding page pixels - that is a property of reconstructing source art from a + * baked page, and real source art removes it along with the fit itself. + * + * This fit exists only because a MOC3-origin export has to RECONSTRUCT the placement a CMO3 would + * have read straight off its source art - see [Cmo3ImageChainBuilder]'s header for why that whole + * reconstruction is a stopgap. A residual survives it by construction for any drawable under a + * warp deformer: the exported base mesh is the rest pose pushed through the warp's lattice, whose + * bilinear map is not affine, so no CAffine reproduces it exactly. The fit is the closest affine, + * which is what the atlas view needs. + * + * @param FloatArray uvs Interleaved atlas-frame texture coordinates (u then v per vertex). + * @param FloatArray positions Interleaved base canvas positions (x then y per vertex). + * @param Int pageWidth The atlas page's pixel width. + * @param Int pageHeight The atlas page's pixel height. + * @return CAffine The fitted transform (identity when there are no vertices). + */ +internal fun fitAtlasPageToCanvasTransform(uvs: FloatArray, positions: FloatArray, pageWidth: Int, pageHeight: Int): CAffine { + val vertexCount = minOf(uvs.size, positions.size) / 2 + if (vertexCount == 0) { + return CAffine() + } + val pointCount = vertexCount.toDouble() + var meanPageX = 0.0 + var meanPageY = 0.0 + val meanCanvas = DoubleArray(2) + for (vertexIndex in 0 until vertexCount) { + meanPageX += uvs[2 * vertexIndex].toDouble() * pageWidth + meanPageY += uvs[2 * vertexIndex + 1].toDouble() * pageHeight + for (axis in 0 until 2) { + meanCanvas[axis] += positions[2 * vertexIndex + axis].toDouble() + } + } + meanPageX /= pointCount + meanPageY /= pointCount + meanCanvas[0] /= pointCount + meanCanvas[1] /= pointCount + // Centered second moments: the page cloud's own covariance plus its cross-covariance with each + // canvas axis. These are the normal equations of `canvas = a*pageX + b*pageY + t` with t + // eliminated, which is exactly what centering buys. + var pageXX = 0.0 + var pageXY = 0.0 + var pageYY = 0.0 + val canvasPageX = DoubleArray(2) + val canvasPageY = DoubleArray(2) + for (vertexIndex in 0 until vertexCount) { + val pageX = uvs[2 * vertexIndex].toDouble() * pageWidth - meanPageX + val pageY = uvs[2 * vertexIndex + 1].toDouble() * pageHeight - meanPageY + pageXX += pageX * pageX + pageXY += pageX * pageY + pageYY += pageY * pageY + for (axis in 0 until 2) { + val canvas = positions[2 * vertexIndex + axis].toDouble() - meanCanvas[axis] + canvasPageX[axis] += pageX * canvas + canvasPageY[axis] += pageY * canvas + } + } + val determinant = pageXX * pageYY - pageXY * pageXY + // Relative test: the page cloud spans two independent directions only when its covariance + // determinant is a real fraction of the product of its variances. A patch collapsed to a line + // (a degenerate mesh) fails here and takes the single-axis path below. + val hasTwoAxisSpread = determinant > 1e-12 * pageXX * pageYY + val linear = Array(2) { DoubleArray(2) } + for (axis in 0 until 2) { + if (hasTwoAxisSpread) { + linear[axis][0] = (canvasPageX[axis] * pageYY - canvasPageY[axis] * pageXY) / determinant + linear[axis][1] = (canvasPageY[axis] * pageXX - canvasPageX[axis] * pageXY) / determinant + continue + } + // Collinear page cloud: regress against whichever page axis actually carries the spread, so + // a rotated strip still recovers its coefficient instead of dividing by nothing. The other + // column is unconstrained by the data and takes its identity value rather than zero - a zero + // column would make the affine singular, and the editor INVERTS this transform to draw the + // mesh over its patch. + if (pageXX >= pageYY && pageXX > 0.0) { + linear[axis][0] = canvasPageX[axis] / pageXX + linear[axis][1] = if (axis == 1) 1.0 else 0.0 + } else if (pageYY > 0.0) { + linear[axis][0] = if (axis == 0) 1.0 else 0.0 + linear[axis][1] = canvasPageY[axis] / pageYY + } else { + // Every vertex shares one page pixel: nothing to scale, so place by the centroid alone. + linear[axis][0] = if (axis == 0) 1.0 else 0.0 + linear[axis][1] = if (axis == 0) 0.0 else 1.0 + } + } + // A near-identity linear part is least-squares noise on a pure translation (the editor's own + // unscaled packings): snap it so the written transform matches the editor's exact-translation + // shape instead of 0.9999997-style drift. + if (kotlin.math.abs(linear[0][0] - 1.0) < 1e-3 && + kotlin.math.abs(linear[0][1]) < 1e-3 && + kotlin.math.abs(linear[1][0]) < 1e-3 && + kotlin.math.abs(linear[1][1] - 1.0) < 1e-3 + ) { + linear[0][0] = 1.0 + linear[0][1] = 0.0 + linear[1][0] = 0.0 + linear[1][1] = 1.0 + } + val transform = CAffine() + // The translation is whatever carries the page mean onto the canvas mean under the linear part. + transform.m00 = linear[0][0].toFloat() + transform.m01 = linear[0][1].toFloat() + transform.m02 = (meanCanvas[0] - linear[0][0] * meanPageX - linear[0][1] * meanPageY).toFloat() + transform.m10 = linear[1][0].toFloat() + transform.m11 = linear[1][1].toFloat() + transform.m12 = (meanCanvas[1] - linear[1][0] * meanPageX - linear[1][1] * meanPageY).toFloat() + return transform +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Export.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Export.kt new file mode 100644 index 0000000..684051e --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Export.kt @@ -0,0 +1,387 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.edit +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.raster.RasterImage +import org.umamo.interop.DeformerField +import org.umamo.interop.DrawableField +import org.umamo.interop.EntityDiff +import org.umamo.interop.ExportFormat +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportReport +import org.umamo.interop.GlueDiff +import org.umamo.interop.GlueField +import org.umamo.interop.ParameterField +import org.umamo.interop.ParameterGroupField +import org.umamo.interop.PartField +import org.umamo.interop.PuppetDiff +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PuppetModel + +/** + * Lowers an edited [PuppetModel] back onto the retained CMO3 graph it was imported from - the + * export half of the CMO3 interop boundary (Cmo3Import is the import half). + * + * The design is a state-based reconcile, not a Change-log replay: [apply] re-imports the graph + * to get a baseline, diffs the edited model against it, and only diff entries touch the graph. + * An unedited model therefore leaves the graph untouched and a subsequent Cmo3.write byte- + * identical; a re-export after an export reconciles against the just-updated graph and is a + * no-op. Structure runs first (created entities get identity shells, deleted ones leave their + * source sets), then every surviving/created entity's fields flow through the one field-level + * lowering path. Edits the lowering cannot (yet or ever) express in CMO3 are returned as + * notices, never silently dropped. + * + * The graph is mutated IN PLACE ([Cmo3Model] holds identity-keyed reconcile metadata a deep + * copy cannot carry). The full diff is computed before any mutation, so a failed export + * leaves either the untouched or the fully-reconciled graph - and either way the next apply + * self-heals from model state. + */ +object Cmo3Export { + /** Every field of a synthesized drawable, so its shell is populated through the Changed path. */ + private val ALL_DRAWABLE_FIELDS = + setOf( + DrawableField.NAME, + DrawableField.PARENT_DEFORMER, + DrawableField.BLEND_MODE, + DrawableField.ALPHA_BLEND_MODE, + DrawableField.MASKED_BY, + DrawableField.INVERT_MASK, + DrawableField.CULLING, + DrawableField.VISIBLE, + DrawableField.SELECTABLE, + DrawableField.MESH_TOPOLOGY, + DrawableField.GEOMETRY, + DrawableField.CHANNELS, + DrawableField.STATICS, + DrawableField.BLEND_SHAPES, + ) + + /** Every field of a synthesized part. */ + private val ALL_PART_FIELDS = PartField.entries.toSet() + + /** Every warp field except KIND (fixed at synthesis) and the rotation-only BASE_ANGLE. */ + private val ALL_WARP_FIELDS = DeformerField.entries.toSet() - DeformerField.KIND - DeformerField.BASE_ANGLE + + /** Every rotation field except KIND (fixed at synthesis) and the warp-only lattice pair. */ + private val ALL_ROTATION_FIELDS = + DeformerField.entries.toSet() - DeformerField.KIND - DeformerField.LATTICE - DeformerField.QUAD_TRANSFORM + + /** Every field of a synthesized glue. */ + private val ALL_GLUE_FIELDS = GlueField.entries.toSet() + + /** + * Reconciles [edited] onto [target]'s graph in place and returns the advisory report. + * + * The fresh-graph synthesis path (MOC3-origin -> CMO3) constructs a blank target graph and + * reuses this same reconcile: an empty baseline lowers everything as created, with + * [drawableTextureBindings] supplying the texture web created drawables bind to when they have + * no existing source to clone (a session duplicate) - the CMO3-origin export path passes none, + * and its created drawables over reconciled art bind through the bindings the atlas-web + * reconcile mints instead. + * + * @param PuppetModel edited The session's current model (EditorSession.model.value - NOT the + * document's original import, which edits never update). + * @param Cmo3Model target The retained CMO3 model whose graph receives the edits. + * @param Map drawableTextureBindings Per-drawable-id texture webs for created drawables + * without a texture source; empty for CMO3-origin exports. + * @param List recomposedPages The pages a repack composed for the edited model's packing, + * in the edited model's page order; empty when the session did not + * repack, which leaves the graph and archive untouched. + * @param Function tileRasters The document's own pixels for a tile, or null when it holds none; + * a reloaded or added tile with a raster writes its real layer into the + * retained graph, and one without declines the atlas-web reconcile. + * @param Long nowMillis The timestamp a layer minted into the retained graph records. + * @param RasterImage modelThumbnail The model's rest-pose thumbnail the three model icons take on + * an edited export, or null to leave the icons the graph has. + * @return ExportReport The notices for everything not (yet) lowered. + */ + fun apply( + edited: PuppetModel, + target: Cmo3Model, + drawableTextureBindings: Map = emptyMap(), + recomposedPages: List = emptyList(), + tileRasters: (AtlasTileId) -> RasterImage? = { null }, + nowMillis: Long = 0L, + modelThumbnail: RasterImage? = null, + ): ExportReport { + val modelSource = target.root as? CModelSource ?: error("CMO3 model root is not a CModelSource") + val baseline = Cmo3Import.fromModelSource(modelSource) + val diff = diffPuppetModels(baseline, edited) + if (diff.isEmpty) { + return ExportReport(ExportFormat.Cmo3, emptyList()) + } + // Taken before any pass writes: a reload rewrite rebuilds a model image's cache, and every later + // pass must still know which textures were the editor's reduced copies. + val textureFrames = Cmo3TextureFrames(modelSource) + val notices = ArrayList() + val editor = target.edit() + // The atlas-web reconcile runs before the graph lowering so the stale-page notices know + // whether the stored pages already show the new packing. Strictly diff-gated by the CALLER: + // an unedited document passes no pages, and the graph and archive are then never touched. + val webResult = Cmo3AtlasWebLowering(target, modelSource, baseline, edited, editor, tileRasters, nowMillis, textureFrames).reconcile(recomposedPages) + val pagesRecomposed = webResult.pagesRecomposed + // The model icons follow an edited export (the diff is non-empty here): the editor regenerates + // them on its own saves, and a thumbnail of the rest pose is what it shows for the file. + if (modelThumbnail != null) { + (modelSource.textureManager as? CTextureManager)?.let { textureManager -> + Cmo3RetainedLayerWeb(target, textureManager, editor, edited, tileRasters, nowMillis, textureFrames).replaceModelIcons(modelSource, modelThumbnail) + } + } + // A created drawable over art the reconcile minted binds through the binding it handed back; + // a caller's own binding for the same drawable (the fresh-graph path) outranks it. + val bindings = + if (webResult.mintedBindings.isEmpty()) { + drawableTextureBindings + } else { + webResult.mintedBindings + drawableTextureBindings + } + + // Structural pass - set membership: identity shells for creations, source removal for + // deletions. Category order follows the reference web (parameters/groups first, then parts + // and deformers, then the drawables that bind to them, then the glues that bind drawables), + // and the structural index is REBUILT between categories so same-export creations resolve. + var anyDeleted = webResult.pruneNeeded + var structural = + Cmo3StructureLowering( + modelSource, + Cmo3GraphIndex(modelSource), + editor, + edited, + notices, + textureFrames, + bindings, + ) + + /** + * Rolls the structural lowering onto a fresh index, carrying the deletion flag forward. + * + * @return Cmo3StructureLowering The replacement instance. + */ + fun refreshedStructural(): Cmo3StructureLowering { + anyDeleted = anyDeleted || structural.deletedAnything + return Cmo3StructureLowering( + modelSource, + Cmo3GraphIndex(modelSource), + editor, + edited, + notices, + textureFrames, + bindings, + ) + } + + val editedParameterById = edited.parameters.associateBy(Parameter::id) + val editedPartById = edited.parts.associateBy(Part::id) + val editedDeformerById = edited.deformers.associateBy(Deformer::id) + val editedDrawableById = edited.drawables.associateBy(Drawable::id) + val synthesizedParameters = HashSet() + val synthesizedGroups = HashSet() + val synthesizedParts = HashSet() + val synthesizedDeformers = HashSet() + val synthesizedDrawables = HashSet() + val synthesizedGlues = HashSet>() + for (entityDiff in diff.parameters) { + when (entityDiff) { + is EntityDiff.Created -> + editedParameterById[entityDiff.id]?.let { parameter -> + if (structural.synthesizeParameter(parameter)) { + synthesizedParameters.add(entityDiff.id) + } + } + + is EntityDiff.Deleted -> structural.deleteParameter(entityDiff.id) + is EntityDiff.Changed -> Unit + } + } + for (entityDiff in diff.parameterGroups) { + when (entityDiff) { + is EntityDiff.Created -> + if (structural.synthesizeParameterGroup(entityDiff.id)) { + synthesizedGroups.add(entityDiff.id) + } + + is EntityDiff.Deleted -> structural.deleteParameterGroup(entityDiff.id) + is EntityDiff.Changed -> Unit + } + } + for (entityDiff in diff.parts) { + when (entityDiff) { + is EntityDiff.Created -> + editedPartById[entityDiff.id]?.let { part -> + if (structural.synthesizePart(part)) { + synthesizedParts.add(entityDiff.id) + } + } + + is EntityDiff.Deleted -> structural.deletePart(entityDiff.id.raw) + is EntityDiff.Changed -> Unit + } + } + for (entityDiff in diff.deformers) { + when (entityDiff) { + is EntityDiff.Created -> + editedDeformerById[entityDiff.id]?.let { deformer -> + if (structural.synthesizeDeformer(deformer)) { + synthesizedDeformers.add(entityDiff.id) + } + } + + is EntityDiff.Deleted -> structural.deleteDeformer(entityDiff.id.raw) + is EntityDiff.Changed -> Unit + } + } + structural = refreshedStructural() + for (entityDiff in diff.drawables) { + when (entityDiff) { + is EntityDiff.Created -> + editedDrawableById[entityDiff.id]?.let { drawable -> + if (structural.synthesizeDrawable(drawable)) { + synthesizedDrawables.add(entityDiff.id) + } + } + + is EntityDiff.Deleted -> structural.deleteDrawable(entityDiff.id) + is EntityDiff.Changed -> Unit + } + } + structural = refreshedStructural() + val editedGluesByPair = edited.glues.groupBy { glue -> glue.meshA to glue.meshB } + for (glueDiff in diff.glues) { + when (glueDiff) { + is GlueDiff.Created -> + editedGluesByPair[glueDiff.meshA to glueDiff.meshB]?.getOrNull(glueDiff.ordinal)?.let { glue -> + if (structural.synthesizeGlue(glue, glueDiff.ordinal)) { + synthesizedGlues.add(Triple(glueDiff.meshA, glueDiff.meshB, glueDiff.ordinal)) + } + } + + is GlueDiff.Deleted -> structural.deleteGlue(glueDiff.meshA, glueDiff.meshB, glueDiff.ordinal) + is GlueDiff.Changed -> Unit + } + } + anyDeleted = anyDeleted || structural.deletedAnything + + // Deletions are done; synthesized creations become Changed-with-every-field so their shells + // are populated by the ordinary field lowering (one tested path, no synthesis copy of it). + val upgradedDiff = + PuppetDiff( + parameters = + diff.parameters.mapNotNull { entityDiff -> + when { + entityDiff is EntityDiff.Created && entityDiff.id in synthesizedParameters -> + EntityDiff.Changed(entityDiff.id, setOf(ParameterField.NAME, ParameterField.RANGE)) + + entityDiff is EntityDiff.Deleted -> null + else -> entityDiff + } + }, + parameterGroups = + diff.parameterGroups.mapNotNull { entityDiff -> + when { + entityDiff is EntityDiff.Created && entityDiff.id in synthesizedGroups -> + EntityDiff.Changed( + entityDiff.id, + setOf( + ParameterGroupField.NAME, + ParameterGroupField.INITIALLY_OPEN, + ParameterGroupField.CHILDREN, + ), + ) + + entityDiff is EntityDiff.Deleted -> null + else -> entityDiff + } + }, + parts = + diff.parts.mapNotNull { entityDiff -> + when { + entityDiff is EntityDiff.Created && entityDiff.id in synthesizedParts -> + EntityDiff.Changed(entityDiff.id, ALL_PART_FIELDS) + + entityDiff is EntityDiff.Deleted -> null + else -> entityDiff + } + }, + deformers = + diff.deformers.mapNotNull { entityDiff -> + when { + entityDiff is EntityDiff.Created && entityDiff.id in synthesizedDeformers -> + EntityDiff.Changed( + entityDiff.id, + if (editedDeformerById[entityDiff.id] is Deformer.Warp) ALL_WARP_FIELDS else ALL_ROTATION_FIELDS, + ) + + entityDiff is EntityDiff.Deleted -> null + else -> entityDiff + } + }, + drawables = + diff.drawables.mapNotNull { entityDiff -> + when { + entityDiff is EntityDiff.Created && entityDiff.id in synthesizedDrawables -> + EntityDiff.Changed(entityDiff.id, ALL_DRAWABLE_FIELDS) + + entityDiff is EntityDiff.Deleted -> null + else -> entityDiff + } + }, + glues = + diff.glues.mapNotNull { glueDiff -> + when { + glueDiff is GlueDiff.Created && + Triple( + glueDiff.meshA, + glueDiff.meshB, + glueDiff.ordinal, + ) in synthesizedGlues -> + GlueDiff.Changed(glueDiff.meshA, glueDiff.meshB, glueDiff.ordinal, ALL_GLUE_FIELDS) + + glueDiff is GlueDiff.Deleted -> null + else -> glueDiff + } + }, + // Tiles have no structural pass: art arrives and leaves with an import, never with a pack, + // so a created or deleted tile forwards as-is and takes its notice in the lowering. + atlasTiles = diff.atlasTiles, + document = diff.document, + ) + + // Field-lowering pass over a REBUILT index (it must see the shells and forget the removed + // sources). Parameters and groups first (tree rebuilds reference their sources), then + // deformer moves (they mutate _childGuids), then parts (whose CHILDREN rebuild anchors on + // the moved lists), then drawables, glues, and the document fields. + val lowering = + Cmo3PropertyLowering( + target = target, + index = Cmo3GraphIndex(modelSource), + editor = editor, + baseline = baseline, + edited = edited, + notices = notices, + textureFrames = textureFrames, + pagesRecomposed = pagesRecomposed, + reconciledTileIds = webResult.reconciledTileIds, + ) + lowering.lowerParameters(upgradedDiff.parameters) + lowering.lowerParameterGroups(upgradedDiff.parameterGroups) + lowering.lowerDeformers(upgradedDiff.deformers) + lowering.lowerParts(upgradedDiff.parts) + lowering.lowerDrawables(upgradedDiff.drawables) + lowering.flushWeldNotice() + lowering.lowerGlues(upgradedDiff.glues) + lowering.lowerAtlasTiles(upgradedDiff.atlasTiles) + lowering.lowerDocument(upgradedDiff.document) + + if (anyDeleted) { + editor.pruneUnreachableShared() + } + return ExportReport(ExportFormat.Cmo3, notices) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3FreshFile.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3FreshFile.kt new file mode 100644 index 0000000..ec646db --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3FreshFile.kt @@ -0,0 +1,40 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3Author +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.caff.CaffEntry +import org.umamo.format.cmo3.caff.CompressOption + +/** + * Assembles a complete .cmo3 byte stream for a fresh (never-read) model root, following the + * corpus-wide container conventions (docs/format/CMO3.md §2 invariants): every entry obfuscated, + * PNG entries RAW with an empty tag, main.xml FAST-compressed and LAST in the file table. + * + * The result is meant to be fed straight back through `Cmo3.read`, which returns a [Cmo3Model] + * with normal read-side metadata - the reconcile exporter then treats the fresh graph exactly + * like a read document. + */ +internal object Cmo3FreshFile { + /** One embedded PNG entry: the unique archive path plus the raw PNG bytes. */ + internal class PngEntry(val path: String, val pngBytes: ByteArray) + + /** + * Serializes [root] via [Cmo3Author] and wraps it with the given PNGs into a CAFF container. + * + * @param Any root The fresh model root (a CModelSource web built in memory). + * @param List pngEntries The embedded PNGs, in allocation order (icons, then pages). + * @param Int obfuscateKey The container XOR key; the editor mints one per save. + * @return ByteArray The complete .cmo3 file bytes. + */ + internal fun assemble(root: Any, pngEntries: List, obfuscateKey: Int): ByteArray { + val entries = ArrayList(pngEntries.size + 1) + for (pngEntry in pngEntries) { + // CMO3: PNG entries - tag "", RAW compression, obfuscated (corpus invariant). + entries.add(CaffEntry(pngEntry.path, "", pngEntry.pngBytes, CompressOption.RAW, obfuscated = true)) + } + // CMO3: the main_xml entry - FAST compression, obfuscated, LAST in the table (corpus invariant). + entries.add(CaffEntry("main.xml", CaffArchive.TAG_MAIN_XML, Cmo3Author.writeFreshMainXml(root), CompressOption.FAST, obfuscated = true)) + return CaffCodec.write(CaffArchive(obfuscateKey = obfuscateKey, entries = entries)) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3GraphIndex.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3GraphIndex.kt new file mode 100644 index 0000000..1df2928 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3GraphIndex.kt @@ -0,0 +1,84 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACDeformerSource +import org.umamo.format.cmo3.model.gen.CAffecterSourceSet +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CGlueSource +import org.umamo.format.cmo3.model.gen.CParameterGroup +import org.umamo.format.cmo3.model.gen.CParameterGroupSet +import org.umamo.format.cmo3.model.gen.CParameterSource +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CPartSourceSet + +/** + * Lookup index over a CMO3 model graph for the export reconcile: every source category listed and + * keyed by its runtime id (the Id.idstr the import carries verbatim) and by GUID uuid. Mirrors + * Cmo3Import's pass 1, in the opposite direction: where import resolves graph references to runtime + * ids, the lowering resolves runtime ids back to the graph objects it must mutate. + */ +internal class Cmo3GraphIndex(val modelSource: CModelSource) { + val parameterSources: List = + Cmo3Import.elementsOf((modelSource.parameterSourceSet as? CParameterSourceSet)?._sources) + .filterIsInstance() + + private val allPartSources: List = + Cmo3Import.elementsOf((modelSource.partSourceSet as? CPartSourceSet)?._sources) + .filterIsInstance() + + /** The synthetic __RootPart__ tree anchor (excluded from the runtime parts list). */ + val rootPartSource: CPartSource? = modelSource.rootPart as? CPartSource + + /** The user-facing parts, excluding the synthetic root - the ones runtime PartIds resolve to. */ + val userPartSources: List = + allPartSources.filter { part -> Cmo3Import.uuidOf(part.guid) != Cmo3Import.uuidOf(rootPartSource?.guid) } + + val deformerSources: List = + Cmo3Import.elementsOf((modelSource.deformerSourceSet as? CDeformerSourceSet)?._sources) + .filterIsInstance() + + val drawableSources: List = + Cmo3Import.elementsOf((modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + + val glueSources: List = + Cmo3Import.elementsOf((modelSource.affecterSourceSet as? CAffecterSourceSet)?._sources) + .filterIsInstance() + + val groupSources: List = + Cmo3Import.elementsOf((modelSource.parameterGroupSet as? CParameterGroupSet)?._groups) + .filterIsInstance() + + /** The hidden top parameter group whose _childGuids is the panel's authoritative root order. */ + val rootParameterGroup: CParameterGroup? = modelSource.rootParameterGroup as? CParameterGroup + + val parameterByIdStr: Map = byIdStr(parameterSources) { it.id } + val partByIdStr: Map = byIdStr(userPartSources) { it.id } + val deformerByIdStr: Map = byIdStr(deformerSources) { it.id } + val drawableByIdStr: Map = byIdStr(drawableSources) { it.id } + val groupByIdStr: Map = byIdStr(groupSources) { it.id } + + /** User-part uuids - with [drawableUuids], the org-child classification for _childGuids walks. */ + val userPartUuids: Set = userPartSources.mapNotNull { Cmo3Import.uuidOf(it.guid) }.toSet() + val drawableUuids: Set = drawableSources.mapNotNull { Cmo3Import.uuidOf(it.guid) }.toSet() + + /** Drawable guid uuid to its runtime id string - the glue targets' resolution key. */ + val drawableIdStrByUuid: Map = + buildMap { + for (source in drawableSources) { + val uuid = Cmo3Import.uuidOf(source.guid) ?: continue + val idStr = Cmo3Import.idStrOf(source.id) ?: continue + put(uuid, idStr) + } + } + + private fun byIdStr(sources: List, idOf: (TSource) -> Any?): Map = + buildMap { + for (source in sources) { + Cmo3Import.idStrOf(idOf(source))?.let { idStr -> put(idStr, source) } + } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3GraphLists.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3GraphLists.kt new file mode 100644 index 0000000..383ef80 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3GraphLists.kt @@ -0,0 +1,12 @@ +package org.umamo.interop.cmo3 + +/** + * The graph collection field as the mutable list the XML reader materialized, or null when the + * field is absent or holds no list. The reader's collections erase to MutableList, so this + * is the one home for the unavoidable unchecked cast every in-place list mutation needs. + * + * @param Any? field The owner's collection field value. + * @return MutableList? The field's mutable list, or null. + */ +@Suppress("UNCHECKED_CAST") +internal fun mutableGraphListOf(field: Any?): MutableList? = field as? MutableList \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Icons.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Icons.kt new file mode 100644 index 0000000..fdde7d4 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3Icons.kt @@ -0,0 +1,134 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.art.LayerBounds +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.cropped +import org.umamo.format.raster.fittedInto +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.storedToArtAffineForTile +import kotlin.math.ceil +import kotlin.math.floor + +/* + * The thumbnails a CMO3 carries, as the official editor writes them (docs/format/CMO3.md section 4, + * Thumbnails): every icon is a CImageIcon over a CWritableImage naming an image*.png entry, a + * straight-alpha RGBA PNG exactly the square's size, holding the art fitted into the square. A + * layer's icons fit its whole raster, a model image's its filtered image, a drawable's the patch its + * mesh covers on that image, the model's a rendered thumbnail. One builder serves the fresh graph + * (entries collected for the assembler) and the retained graph (entries embedded as they are + * minted, or replaced in place at an icon's existing path). + */ + +/** + * The icon builders. + */ +internal object Cmo3Icons { + /** The three model icon edges, in the order CModelSource carries them (_icon64, _icon32, _icon16). */ + val MODEL_ICON_SIZES: List = listOf(64, 32, 16) + + /** + * The PNG an icon of [size] holds for [raster]. + * + * @param RasterImage raster The art. + * @param Int size The square's edge. + * @return ByteArray The encoded PNG. + */ + fun iconPngOf(raster: RasterImage, size: Int): ByteArray = PngCodec.write(raster.fittedInto(size)) + + /** + * An icon of [raster] at [size], its PNG collected for the assembler under [path]. + * + * @param RasterImage raster The art. + * @param Int size The square's edge. + * @param String path The unique archive path for the PNG entry. + * @param MutableList entries The PNG entry collector. + * @return CImageIcon The icon. + */ + fun iconOf(raster: RasterImage, size: Int, path: String, entries: MutableList): CImageIcon { + entries.add(Cmo3FreshFile.PngEntry(path, iconPngOf(raster, size))) + return iconReferencing(size, path) + } + + /** + * An icon wrapper referencing an embedded PNG entry the caller owns. + * + * @param Int size The square's edge. + * @param String path The archive entry path the icon references. + * @return CImageIcon The icon. + */ + fun iconReferencing(size: Int, path: String): CImageIcon = + CImageIcon().apply { + image = + CWritableImage().apply { + // CMO3: CWritableImage attrs width/height/type + file child (every corpus icon). + width = size + height = size + type = "INT_ARGB" + image = FileRef().apply { archivePath = path } + } + } + + /** + * The archive path an icon's PNG lives at, or null when the slot holds no such icon. + * + * @param Any? icon A CImageIcon slot. + * @return String? The path. + */ + fun archivePathOf(icon: Any?): String? = ((icon as? CImageIcon)?.image as? CWritableImage)?.image?.archivePath + + /** + * The patch a drawable's icon shows: the mesh's uv bounding box on its art, or the whole art when + * the mesh is unknown. + * + * @param RasterImage raster The art the drawable samples, in its own frame. + * @param FloatArray? artUvs The drawable's texture coordinates in that frame, interleaved, or null. + * @return RasterImage The patch. + */ + fun patchOf(raster: RasterImage, artUvs: FloatArray?): RasterImage { + if (artUvs == null || artUvs.size < 2 || raster.width <= 0 || raster.height <= 0) { + return raster + } + var minU = Float.POSITIVE_INFINITY + var minV = Float.POSITIVE_INFINITY + var maxU = Float.NEGATIVE_INFINITY + var maxV = Float.NEGATIVE_INFINITY + var componentIndex = 0 + while (componentIndex + 1 < artUvs.size) { + minU = minOf(minU, artUvs[componentIndex]) + maxU = maxOf(maxU, artUvs[componentIndex]) + minV = minOf(minV, artUvs[componentIndex + 1]) + maxV = maxOf(maxV, artUvs[componentIndex + 1]) + componentIndex += 2 + } + if (!minU.isFinite() || !minV.isFinite() || !maxU.isFinite() || !maxV.isFinite()) { + return raster + } + // The box in pixels, clamped to the art and at least one pixel each way. + val left = floor(minU * raster.width).toInt().coerceIn(0, raster.width - 1) + val top = floor(minV * raster.height).toInt().coerceIn(0, raster.height - 1) + val right = ceil(maxU * raster.width).toInt().coerceIn(left + 1, raster.width) + val bottom = ceil(maxV * raster.height).toInt().coerceIn(top + 1, raster.height) + return raster.cropped(LayerBounds(left, top, right - left, bottom - top)) + } + + /** + * A drawable's texture coordinates in its tile's own frame, or null when it has no mesh or its + * tile's mapping cannot be formed - the same mapping the rig-work check reads. + * + * @param PuppetModel model The model the drawable belongs to. + * @param Drawable drawable The drawable. + * @return FloatArray? The art-frame uvs, interleaved. + */ + fun artUvsOf(model: PuppetModel, drawable: Drawable): FloatArray? { + val uvs = drawable.mesh?.uvs?.takeIf { stored -> stored.isNotEmpty() } ?: return null + val tileId = drawable.atlasTileId ?: return null + val storedToArt = model.atlas.storedToArtAffineForTile(tileId) ?: return null + return applyUvAffine(uvs, storedToArt) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3ImageChainBuilder.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3ImageChainBuilder.kt new file mode 100644 index 0000000..e68e05e --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3ImageChainBuilder.kt @@ -0,0 +1,1539 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CSize +import org.umamo.format.cmo3.model.custom.FilterInstance +import org.umamo.format.cmo3.model.gen.Anisotropy +import org.umamo.format.cmo3.model.gen.AutoLayoutLock +import org.umamo.format.cmo3.model.gen.CBlend_Normal +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.gen.CLayerGroup +import org.umamo.format.cmo3.model.gen.CLayerIdentifier +import org.umamo.format.cmo3.model.gen.CLayerInputData +import org.umamo.format.cmo3.model.gen.CLayerSelectorMap +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.CachedImageType +import org.umamo.format.cmo3.model.gen.EnvConnection +import org.umamo.format.cmo3.model.gen.EnvValueConnector +import org.umamo.format.cmo3.model.gen.EnvValueSet +import org.umamo.format.cmo3.model.gen.FilterMode +import org.umamo.format.cmo3.model.gen.FilterOutputValueConnector +import org.umamo.format.cmo3.model.gen.FilterValue +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.LayerSet +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.gen.MagFilter +import org.umamo.format.cmo3.model.gen.MinFilter +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.gen.ModelImageFilterEnv +import org.umamo.format.cmo3.model.gen.ModelImageFilterSet +import org.umamo.format.cmo3.model.gen.WrapMode +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.CRect +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.cmo3.model.type.GVector2 +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.format.cmo3.type.CHashMap +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.cropped +import org.umamo.runtime.model.AtlasPlacement + +/* + * WHY THIS FILE EXISTS, AND WHY IT CUTS UP THE ATLAS + * + * A CMO3 is built around SOURCE ART: the editor decomposes an imported PSD/CLIP/KRA into a + * CLayeredImage tree of per-layer images, and everything else (model images, atlas entries, + * placements) hangs off that. A .moc3 carries none of it - only the packed atlas pages and UVs. + * So a MOC3-origin export has to FABRICATE a source document, and the only raw material available + * is the packed page. That is the whole reason this builder slices each drawable's uv bounding + * box back out of the atlas and presents the crop as if it were an imported layer. None of that + * cutting is inherent to the format; it is reconstruction of information the bake threw away. + * + * An artwork-origin document needs none of it: its tiles hold the real rasters, so those write as + * real layers of their file's layered image through Cmo3SourceLayerWeb, and the crop path here + * serves only the drawables that have no such art. The page half (one atlas and one shared texture + * per page) and the model-image web around a layer (modelImageOver) are shared by both. + * + * The cutting is NOT what makes a file render. A third-party converter's CMO3 renders in the + * official editor with NO source document at all (zero CLayeredImage / CLayer / CModelImage / + * ModelImageEntry, drawables carrying only a CTextureInput_TextureAtlasRegion) - and it renders + * despite geometry that is offset by a constant from Cubism's own golden file for the same model. + * The web here exists for the editor's texture-atlas and mesh-edit VIEWS, which derive + * mesh-over-texture placement from the model images; a single whole-page image cannot place + * hundreds of drawables and drew every mesh at its assembled canvas position instead. Do not + * "simplify" by deleting the web: that shape was tested and the editor errors with an empty atlas. + * + * The output renders in the official editor and switches between layered-art and texture-atlas + * display modes. The one known failure is scale: modelF (~850 MB, several hundred layers) OOMs + * the editor on the switch BACK to atlas mode. Atlas mode recomposites the page out of the + * materials, so peak memory tracks the total area of the crops cut below, not the page size - a uv + * bounding box overlaps its neighbours, so that total can run to a multiple of the page. Measure + * it before concluding the editor is simply out of room. + * + * WHAT IT BUILDS, mirroring the official ATLAS-MODE shape (EricaTamamo, + * isTextureInputModelImageMode=false): one CTextureAtlas + ONE SHARED GTexture2D per page that + * every packed drawable on the page samples with atlas-frame UVs, plus a PER-DRAWABLE model-image + * web - each drawable's texture patch cropped out of the page as its own CLayer + CModelImage + + * ModelImageEntry, the entry carrying the patch's packing origin (materialLocalToAtlasTransform) + * and the drawable's fitted atlas-to-canvas placement (atlasLocalToCanvasTransform). + * + * Every CModelImage carries the editor's layer-filter web (a CLayerSelector feeding a + * CLayerFilter, connected through per-document shared FilterValue definitions) plus a filtered + * image, a cached-image manager, and icon thumbnails - the official reader's custom deserializers + * dereference these, so a null is a hard failure, not a cosmetic gap. The filter definition + * guids are editor-static constants (identical uuids in every corpus file). + * + * The synthetic source doc is the ATLAS PAGE's own frame, mirroring how an official document's + * CLayeredImage carries the source PSD's size rather than the canvas + * (ModelWithOffscreenPartClipping: a 500x500 doc inside a 1000x2000 canvas - Erica's doc merely + * happens to equal its canvas). Each layer's boundsOnImageDoc carries the placement translation + * as its origin (equal to the owning CModelImage's _materialLocalToCanvasTransform translation on + * all 892 corpus layers) and the imageResource dims as its size (also 892 of 892); official docs + * sit origin-aligned on the canvas, so their doc rects and canvas placements coincide, and our + * patch layers keep that equality by writing the canvas placement. + * + * WHERE THE PACKING'S SCALE AND ROTATION LIVE: not on the ModelImageEntry. Each crop is an + * axis-aligned rect of page pixels lifted at scale 1, so position-only IS the honest + * materialLocalToAtlasTransform for it; whatever the packer did to the art - rotate, mirror, scale + * - is carried by the page fit, which both atlasLocalToCanvasTransform and the model image's + * _materialLocalToCanvasTransform compose (see fitAtlasPageToCanvasTransform, and note the + * mean-centering there is what lets a rotated packing survive the fit at all). + * + * A patch rect starts as a uv BOUNDING BOX, so unless the mesh is itself a page-aligned rectangle + * the rect also spans page pixels the packer nested into the leftover corners - a neighbour's + * artwork. The crop is therefore masked to the mesh's own triangles (coverageMaskOf) rather than + * copied verbatim, then TRIMMED to the masked pixels' opaque bounds, with the packing origin, + * placement, and layer bounds all derived from the trimmed rect together. Un-masked, the editor + * takes the foreign pixels for this drawable's artwork - they follow the patch when the atlas is + * rearranged, and a repack stamps them back into the page. + * + * Remaining deliberate simplification, validated by the official-editor gate: the cached images + * are the raw resources themselves (SCALE_1, nothing prerendered; their + * transformRawImageToCachedImage records the 64-aligned padding fraction like every corpus + * cache entry). The icons are real: each layer's, model image's, and drawable's is its art fitted + * into the square the way the editor writes it (Cmo3Icons). + */ +internal object Cmo3ImageChainBuilder { + /** + * One drawable's geometry on its page: id, interleaved atlas-frame uvs and base positions, plus + * the triangle indices that say which page pixels inside the uv bounding box are actually this + * drawable's (see [coverageMaskOf]). + */ + internal class DrawableRegion( + val drawableIdStr: String, + val uvs: FloatArray, + val positions: FloatArray, + val indices: IntArray, + ) + + /** + * The populated chain: the PNG entries to embed and the texture bindings. + * + * @property List pngEntries The PNG entries to embed. + * @property Map bindingByDrawableId The texture web per drawable that got one. + * @property List pageFallbackBindings The per-page bindings for a drawable with no web of its own. + * @property Int cropDrawableCount How many drawables took the crop path - the stand-in sliced + * out of a page - which is what the missing-source-art notice reports; zero when every + * drawable's art came from a real layer. + */ + internal class BuiltImageChain( + val pngEntries: List, + val bindingByDrawableId: Map, + val pageFallbackBindings: List, + val cropDrawableCount: Int = 0, + ) + + /** + * The per-document state an image chain threads through every page, crop, and real layer it + * writes: the archive-entry path minters (the editor's imageFileBuf / image_N de-dupe sequences, + * which must stay unique across the whole file), the filter web's shared definitions, and the + * blend and option instances every layer shares. + * + * A fresh graph takes the defaults: counters from the skeleton's own first indices and fresh + * filter definitions. A retained graph hands in the archive's own minters and the definitions + * recovered from a model image it already holds, so a layer minted into it continues the file's + * sequences and shares its singletons rather than growing a second set. + * + * @param FilterCommons filters The filter web's per-document singletons. + * @param Function mintImageFileBufPath The next unique archive path for an image buffer. + * @param Function mintIconPath The next unique archive path for an icon. + */ + internal class Cmo3FreshChainNames( + val filters: FilterCommons = FilterCommons.fresh(), + // CMO3: the imageFileBuf de-dupe naming convention (imageFileBuf, imageFileBuf_0, ...); pages + // claim the first indices, then crops and real layers continue the sequence. + private val mintImageFileBufPath: () -> String = FreshPathSequence("imageFileBuf", firstSuffix = -1)::next, + // The skeleton's three model icons take image.png / image_0.png / image_1.png, so icon entries + // continue the editor's image_N naming from suffix 2. + private val mintIconPath: () -> String = FreshPathSequence("image", firstSuffix = 2)::next, + ) { + /** The one blend node every synthesized layer and group references. */ + val sharedBlend: CBlend_Normal = CBlend_Normal() + + /** The one option map every synthesized layer and group references. */ + val sharedOptions: CHashMap = CHashMap() + + /** + * The next unique archive path for an image buffer. + * + * @return String The path. + */ + fun nextImageFileBufPath(): String = mintImageFileBufPath() + + /** + * The next unique archive path for an icon. + * + * @return String The path. + */ + fun nextIconPath(): String = mintIconPath() + } + + /** + * One of the editor's archive de-dupe sequences: `.png` for suffix -1, then `_.png`. + * A fresh archive starts at the skeleton's first free suffix; a retained archive continues from + * the first path its own minter reports ([continuingFrom]) and counts locally from there, so a + * batch of icons minted before their entries are embedded still takes distinct paths. + * + * @param String stem The sequence's stem. + * @param Int firstSuffix The suffix the first minted path takes. + */ + internal class FreshPathSequence(private val stem: String, firstSuffix: Int) { + private var nextSuffix = firstSuffix + + /** + * Mints the next path. + * + * @return String The path. + */ + fun next(): String { + val suffix = nextSuffix + nextSuffix += 1 + return if (suffix < 0) "$stem.png" else "${stem}_$suffix.png" + } + + companion object { + /** + * The sequence whose first path is [firstPath], as a retained archive's minter reports it. + * + * @param String stem The sequence's stem. + * @param String firstPath The next unused path in the archive, in the sequence's own form. + * @return FreshPathSequence The sequence. + */ + fun continuingFrom(stem: String, firstPath: String): FreshPathSequence { + val firstSuffix = + if (firstPath == "$stem.png") { + -1 + } else { + checkNotNull(firstPath.removePrefix("${stem}_").removeSuffix(".png").toIntOrNull()) { "'$firstPath' is not in the $stem sequence" } + } + return FreshPathSequence(stem, firstSuffix) + } + } + } + + /** + * What makes two drawables share one CModelImage: the same crop rect and the same mesh. The + * mesh is part of the identity because it masks the crop - two drawables over one rect with + * different topology no longer produce the same pixels. The fitted PLACEMENT is deliberately + * NOT part of the key, and that is only safe because Cmo3AtlasUndedup has already routed every + * different-placement twin to its own slot: official multi-drawable materials are always + * CO-LOCATED (Erica: 45 of 45 shared groups have identical mesh and placement), the shared + * image carries a single canvas placement, and duplicating a material over one slot instead + * makes the editor's atlas view - a recomposite of the materials - stack the shared art's + * alpha (2a - a*a per extra copy), rendering the atlas more opaque than source-image mode. + */ + private class PatchWebKey( + private val patchRect: IntArray, + private val uvs: FloatArray, + private val indices: IntArray, + ) { + override fun equals(other: Any?): Boolean = + other is PatchWebKey && + patchRect.contentEquals(other.patchRect) && + uvs.contentEquals(other.uvs) && + indices.contentEquals(other.indices) + + override fun hashCode(): Int { + var result = patchRect.contentHashCode() + result = 31 * result + uvs.contentHashCode() + result = 31 * result + indices.contentHashCode() + return result + } + } + + /** + * CMO3: GTexture2D field mipmapLevel - what every corpus texture over a full-resolution image (an atlas + * page or a model image's raster) writes; a texture over a reduced cache copy writes that copy's 32. + */ + internal const val FULL_RESOLUTION_MIPMAP_LEVEL = 64 + + /** CMO3: FilterInstance filterDefGuid for "CLayerSelector" - fixed uuid in every corpus file. */ + private const val LAYER_SELECTOR_DEF_UUID = "5e9fe1ea-0ec3-4d68-a5fa-018fc7abe301" + + /** CMO3: FilterInstance filterDefGuid for "CLayerFilter" - fixed uuid in every corpus file. */ + private const val LAYER_FILTER_DEF_UUID = "4083cd1f-40ba-4eda-8400-379019d55ed8" + + /** + * The per-document singletons of the filter web, shared by every model image's ModelImageFilterSet: + * the value ids the connectors are keyed by, the FilterValue definitions they name, and the two + * filter-definition guids. Minted fresh for a new graph, or recovered from a model image a + * retained graph already holds so a minted image shares the file's own objects. + * + * @param Map idByIdStr Each value id by its idstr. + * @param Map valueByIdStr Each FilterValue definition by its own id's idstr. + * @param Guid selectorDefGuid The CLayerSelector definition guid. + * @param Guid layerFilterDefGuid The CLayerFilter definition guid. + */ + internal class FilterCommons private constructor( + private val idByIdStr: Map, + private val valueByIdStr: Map, + val selectorDefGuid: Guid, + val layerFilterDefGuid: Guid, + ) { + val inputLayerData: Id get() = idByIdStr.getValue(INPUT_LAYER_DATA) + val currentImageGuid: Id get() = idByIdStr.getValue(CURRENT_IMAGE_GUID) + val outputImage: Id get() = idByIdStr.getValue(OUTPUT_IMAGE) + val outputTransform: Id get() = idByIdStr.getValue(OUTPUT_TRANSFORM) + val selectorInputLayerData: Id get() = idByIdStr.getValue(SELECTOR_INPUT_LAYER_DATA) + val selectorCurrentImageGuid: Id get() = idByIdStr.getValue(SELECTOR_CURRENT_IMAGE_GUID) + val selectorOutputLayerData: Id get() = idByIdStr.getValue(SELECTOR_OUTPUT_LAYER_DATA) + val filterInputLayer: Id get() = idByIdStr.getValue(FILTER_INPUT_LAYER) + + val selectLayer: FilterValue get() = valueByIdStr.getValue(SELECTOR_OUTPUT_LAYER_DATA) + val importLayer: FilterValue get() = valueByIdStr.getValue(INPUT_LAYER_DATA) + val importLayerSelection: FilterValue get() = valueByIdStr.getValue(SELECTOR_INPUT_LAYER_DATA) + val currentGuid: FilterValue get() = valueByIdStr.getValue(CURRENT_IMAGE_GUID) + val selectedSourceGuid: FilterValue get() = valueByIdStr.getValue(SELECTOR_CURRENT_IMAGE_GUID) + val outputImageValue: FilterValue get() = valueByIdStr.getValue(OUTPUT_IMAGE) + val outputImageResource: FilterValue get() = valueByIdStr.getValue(SELECTOR_OUTPUT_IMAGE_RESOURCE) + val layerToCanvasEnv: FilterValue get() = valueByIdStr.getValue(OUTPUT_TRANSFORM) + val layerToCanvasFilter: FilterValue get() = valueByIdStr.getValue(SELECTOR_OUTPUT_TRANSFORM) + + companion object { + // CMO3: the FilterValueId idstrs of the model-image filter web, transcribed from the corpus + // (MultiplyScreenColors.cmo3, identical across files). "mi_" ids are the env side, "ilf_" + // ids the filter side. + private const val INPUT_LAYER_DATA = "mi_input_layerInputData" + private const val CURRENT_IMAGE_GUID = "mi_currentImageGuid" + private const val OUTPUT_IMAGE = "mi_output_image" + private const val OUTPUT_TRANSFORM = "mi_output_transform" + private const val SELECTOR_INPUT_LAYER_DATA = "ilf_inputLayerData" + private const val SELECTOR_CURRENT_IMAGE_GUID = "ilf_currentImageGuid" + private const val SELECTOR_OUTPUT_LAYER_DATA = "ilf_outputLayerData" + private const val FILTER_INPUT_LAYER = "ilf_inputLayer" + private const val SELECTOR_OUTPUT_IMAGE_RESOURCE = "ilf_outputImageRes" + private const val SELECTOR_OUTPUT_TRANSFORM = "ilf_outputTransform" + + /** The ids the connectors are keyed by, every one of which a recovery must find. */ + private val KEY_ID_STRS = + listOf( + INPUT_LAYER_DATA, + CURRENT_IMAGE_GUID, + OUTPUT_IMAGE, + OUTPUT_TRANSFORM, + SELECTOR_INPUT_LAYER_DATA, + SELECTOR_CURRENT_IMAGE_GUID, + SELECTOR_OUTPUT_LAYER_DATA, + FILTER_INPUT_LAYER, + ) + + /** The definitions' own ids, every one of which a recovery must find. */ + private val VALUE_ID_STRS = + listOf( + SELECTOR_OUTPUT_LAYER_DATA, + INPUT_LAYER_DATA, + SELECTOR_INPUT_LAYER_DATA, + CURRENT_IMAGE_GUID, + SELECTOR_CURRENT_IMAGE_GUID, + OUTPUT_IMAGE, + SELECTOR_OUTPUT_IMAGE_RESOURCE, + OUTPUT_TRANSFORM, + SELECTOR_OUTPUT_TRANSFORM, + ) + + /** + * Fresh singletons for a new graph. + * + * @return FilterCommons The definitions. + */ + fun fresh(): FilterCommons { + val idByIdStr = HashMap() + + /** + * The one Id per idstr. + * + * @param String idStr The idstr. + * @return Id The id. + */ + fun valueId(idStr: String): Id = idByIdStr.getOrPut(idStr) { Id("FilterValueId").apply { idstr = idStr } } + + /** + * A FilterValue definition. + * + * @param String displayName The editor's display name for the value. + * @param String idStr The value's own id. + * @return FilterValue The definition. + */ + fun value(displayName: String, idStr: String): FilterValue = + FilterValue().apply { + name = displayName + id = valueId(idStr) + } + // CMO3: the FilterValue definitions - names and value-id wiring transcribed from the + // corpus (MultiplyScreenColors.cmo3, identical across files). + val values = + listOf( + value("Select Layer", SELECTOR_OUTPUT_LAYER_DATA), + value("Import Layer", INPUT_LAYER_DATA), + value("Import Layer selection", SELECTOR_INPUT_LAYER_DATA), + value("Current GUID", CURRENT_IMAGE_GUID), + value("GUID of Selected Source Image", SELECTOR_CURRENT_IMAGE_GUID), + value("Output image", OUTPUT_IMAGE), + value("Output Image (Resource Format)", SELECTOR_OUTPUT_IMAGE_RESOURCE), + value("LayerToCanvas変換", OUTPUT_TRANSFORM), + value("LayerToCanvas変換", SELECTOR_OUTPUT_TRANSFORM), + ) + for (idStr in KEY_ID_STRS) { + valueId(idStr) + } + return FilterCommons( + idByIdStr, + values.associateBy { value -> (value.id as Id).idstr }, + Guid("StaticFilterDefGuid").apply { + uuid = LAYER_SELECTOR_DEF_UUID + note = "(no debug info)" + }, + Guid("StaticFilterDefGuid").apply { + uuid = LAYER_FILTER_DEF_UUID + note = "(no debug info)" + }, + ) + } + + /** + * The singletons a retained graph's model image already wires, so an image minted beside it + * shares the same objects; null when the set does not carry the full web (a graph another + * writer produced), in which case the caller falls back to [fresh]. + * + * @param ModelImageFilterSet filterSet A retained model image's inputFilter. + * @return FilterCommons? The recovered definitions, or null. + */ + fun fromFilterSet(filterSet: ModelImageFilterSet): FilterCommons? { + val idByIdStr = HashMap() + val valueByIdStr = HashMap() + var selectorDefGuid: Guid? = null + var layerFilterDefGuid: Guid? = null + + /** + * Records an id the web references. + * + * @param Any? candidate A key or a connector's id slot. + */ + fun noteId(candidate: Any?) { + val id = candidate as? Id ?: return + idByIdStr.putIfAbsent(id.idstr, id) + } + + /** + * Records a definition the web references, and its own id. + * + * @param Any? candidate A connector's definition slot. + */ + fun noteValue(candidate: Any?) { + val value = candidate as? FilterValue ?: return + val id = value.id as? Id ?: return + noteId(id) + valueByIdStr.putIfAbsent(id.idstr, value) + } + // CMO3: ModelImageFilterSet field filterMap -> FilterInstance fields filterName / + // filterDefGuid / inputConnectors / outputConnectors, the connectors keyed by value id. + for (instance in (filterSet.filterMap as? Map<*, *>)?.values.orEmpty().filterIsInstance()) { + when (instance.filterName) { + "CLayerSelector" -> selectorDefGuid = instance.filterDefGuid as? Guid + "CLayerFilter" -> layerFilterDefGuid = instance.filterDefGuid as? Guid + } + for ((key, connector) in (instance.inputConnectors as? Map<*, *>).orEmpty()) { + noteId(key) + noteId((connector as? EnvValueConnector)?.envValueId) + } + for ((key, connector) in (instance.outputConnectors as? Map<*, *>).orEmpty()) { + noteId(key) + val output = connector as? FilterOutputValueConnector ?: continue + noteId(output.id) + noteValue(output.valueDef) + } + } + // CMO3: ModelImageFilterSet fields _externalInputs / _externalOutputs -> EnvConnection + // fields _envValueDef / filterValueDef. + for (external in listOf(filterSet._externalInputs, filterSet._externalOutputs)) { + for ((key, connection) in (external as? Map<*, *>).orEmpty()) { + noteId(key) + val envConnection = connection as? EnvConnection ?: continue + noteValue(envConnection._envValueDef) + noteValue(envConnection.filterValueDef) + } + } + val selector = selectorDefGuid ?: return null + val layerFilter = layerFilterDefGuid ?: return null + if (KEY_ID_STRS.any { idStr -> idStr !in idByIdStr } || VALUE_ID_STRS.any { idStr -> idStr !in valueByIdStr }) { + return null + } + return FilterCommons(idByIdStr, valueByIdStr, selector, layerFilter) + } + } + } + + /** + * Builds one model image's ModelImageFilterSet: a CLayerSelector instance feeding a CLayerFilter, + * with the external input/output connections the editor's model-image pipeline expects. + * + * @param FilterCommons commons The per-document shared definitions. + * @return ModelImageFilterSet The fresh filter set. + */ + internal fun buildFilterSet(commons: FilterCommons): ModelImageFilterSet { + val filterSet = ModelImageFilterSet() + val selectorId = Id("FilterInstanceId").apply { idstr = "filter0" } + val layerFilterId = Id("FilterInstanceId").apply { idstr = "filter1" } + val selector = + FilterInstance().apply { + filterName = "CLayerSelector" + filterDefGuid = commons.selectorDefGuid + filterId = selectorId + ownerFilterSet = filterSet + } + val selectorOutput = + FilterOutputValueConnector().apply { + instance = selector + id = commons.selectorOutputLayerData + valueDef = commons.selectLayer + } + selector.inputConnectors = + CHashMap().apply { + put(commons.selectorInputLayerData, EnvValueConnector().apply { envValueId = commons.inputLayerData }) + put(commons.selectorCurrentImageGuid, EnvValueConnector().apply { envValueId = commons.currentImageGuid }) + } + selector.outputConnectors = CHashMap().apply { put(commons.selectorOutputLayerData, selectorOutput) } + val layerFilter = + FilterInstance().apply { + filterName = "CLayerFilter" + filterDefGuid = commons.layerFilterDefGuid + filterId = layerFilterId + inputConnectors = CHashMap().apply { put(commons.filterInputLayer, selectorOutput) } + outputConnectors = CHashMap() + ownerFilterSet = filterSet + } + filterSet.filterMap = + LinkedHashMap().apply { + put(selectorId, selector) + put(layerFilterId, layerFilter) + } + filterSet._externalInputs = + LinkedHashMap().apply { + put( + commons.inputLayerData, + EnvConnection().apply { + _envValueDef = commons.importLayer + filter = selector + filterValueDef = commons.importLayerSelection + }, + ) + put( + commons.currentImageGuid, + EnvConnection().apply { + _envValueDef = commons.currentGuid + filter = selector + filterValueDef = commons.selectedSourceGuid + }, + ) + } + filterSet._externalOutputs = + LinkedHashMap().apply { + put( + commons.outputImage, + EnvConnection().apply { + _envValueDef = commons.outputImageValue + filter = layerFilter + filterValueDef = commons.outputImageResource + }, + ) + put( + commons.outputTransform, + EnvConnection().apply { + _envValueDef = commons.layerToCanvasEnv + filter = layerFilter + filterValueDef = commons.layerToCanvasFilter + }, + ) + } + return filterSet + } + + /** + * A page's image resource: the embedded page PNG's dimensions, type, and archive link. + * + * Shared by the fresh conversion and the export's page mint, so a page minted into a retained + * graph is field-for-field the shape the fresh path writes. + * + * @param String path The archive path the page PNG is stored under. + * @param Int width The page width in pixels. + * @param Int height The page height in pixels. + * @param Int pngSize The encoded PNG's byte size. + * @return CImageResource The page resource. + */ + internal fun pageImageResource(path: String, width: Int, height: Int, pngSize: Int): CImageResource = + CImageResource().apply { + // CMO3: CImageResource attrs width/height/type + the imageFileBuf file child. + this.width = width + this.height = height + type = "INT_ARGB" + imageFileBuf = FileRef().apply { archivePath = path } + imageFileBuf_size = pngSize + } + + /** + * A page's texture atlas element, empty of entries: the editor's naming, a fresh guid, and the + * cached-image manager whose padding diagonal the editor's source-image sampling depends on. + * + * @param Int pageOrdinal The zero-based page index ("TextureAtlas1" is page 0). + * @param Int width The page width in pixels. + * @param Int height The page height in pixels. + * @param CImageResource resource The page's image resource. + * @return CTextureAtlas The atlas element. + */ + internal fun pageAtlas(pageOrdinal: Int, width: Int, height: Int, resource: CImageResource): CTextureAtlas = + CTextureAtlas().apply { + // CMO3: CTextureAtlas fields name/width/height/cachedAtlasImage/guid/modelImages/ + // cachedImageManager. + name = "TextureAtlas${pageOrdinal + 1}" + this.width = width + this.height = height + cachedAtlasImage = resource + guid = Cmo3SkeletonBuilder.freshGuid("CTextureAtlasGuid") + modelImages = CArrayList() + cachedImageManager = paddedCacheManager(resource, width, height) + } + + /** + * A page's ONE shared texture: every drawable on the page references this instance (the writer + * hoists it), like the editor's own atlas files. + * + * @param String? atlasName The owning atlas's name, which the texture shares. + * @param CImageResource resource The page's image resource the texture samples. + * @return GTexture2D The page texture. + */ + internal fun pageTexture(atlasName: String?, resource: CImageResource): GTexture2D { + val texture = + GTexture2D().apply { + // CMO3: GTexture2D - the page's shared texture. + name = atlasName + // CMO3: GTexture fields wrapMode / filterMode / anisotropy - the editor's fixed + // sampling setup on every corpus texture. + wrapMode = WrapMode.CLAMP_TO_BORDER + guid = Cmo3SkeletonBuilder.freshGuid("GTextureGuid") + anisotropy = Anisotropy.ON + srcImageResource = resource + transformImageResource01toLogical01 = CAffine() + mipmapLevel = FULL_RESOLUTION_MIPMAP_LEVEL + // CMO3: GTexture2D field isPremultiplied - true on EVERY corpus texture (178 of + // 178, every era), including the many whose embedded PNG bytes are straight + // alpha. The flag records the editor's texture-render/upload convention, not + // the byte storage (see the Premultiplied section), so a MOC3 sidecar page - + // straight alpha like the corpus ones - writes true as well. + isPremultiplied = true + } + texture.filterMode = + FilterMode().apply { + minFilter = MinFilter.LINEAR_MIPMAP_LINEAR + magFilter = MagFilter.LINEAR + owner = texture + } + return texture + } + + /** + * The raster-to-cache affine of an image: its size over its 64-aligned padding, per axis. The cache + * frame the editor keeps for every image, and the scale a texture sampling the raster carries as + * `GTexture2D.transformImageResource01toLogical01` - every corpus texture over a model image's raster + * writes exactly its cache's value. + * + * @param Int width The image width in pixels. + * @param Int height The image height in pixels. + * @return CAffine A fresh diagonal affine. + */ + internal fun paddedFrameAffine(width: Int, height: Int): CAffine = + CAffine().apply { + m00 = width.toFloat() / ((width + 63) / 64 * 64) + m11 = height.toFloat() / ((height + 63) / 64 * 64) + } + + /** + * The cached-image manager the editor expects on every model image and texture atlas: the raw + * page cached as itself at SCALE_1 (nothing prerendered). + * + * @param CImageResource pageResource The page image resource. + * @param Int width The page width in pixels. + * @param Int height The page height in pixels. + * @return CCachedImageManager The fresh manager. + */ + internal fun paddedCacheManager(pageResource: CImageResource, width: Int, height: Int): CCachedImageManager = + CCachedImageManager().apply { + // CMO3: CCachedImageManager fields defaultCacheType / rawImage / cachedImages / + // requiredMipmapLevel (corpus flat imports cache the raw resource itself). + defaultCacheType = CachedImageType.SCALE_1 + rawImage = pageResource + cachedImages = + ArrayList( + mutableListOf( + CCachedImage().apply { + _cachedImageResource = pageResource + isSharedImage = true + rawImageSize = + CSize().apply { + this.width = width + this.height = height + } + reductionRatio = 1 + mipmapLevel = 64 + hasMargin = false + isCleaned = false + // CMO3: CCachedImage field transformRawImageToCachedImage - the raw + // dims over the cache raster's 64-aligned padding, per axis: every + // corpus reductionRatio=1 cache writes exactly dim / ceil64(dim) + // (1073 of 1073). Identity here makes the editor's source-image + // sampling stretch the art by the padding fraction. + transformRawImageToCachedImage = paddedFrameAffine(width, height) + }, + ), + ) + requiredMipmapLevel = 64 + } + + /** + * A drawable's pixel-aligned texture-patch rect on its page, from its atlas-frame uv bounds. + * + * Mesh margins may reach slightly outside [0,1]; the rect is clamped to the page and forced to + * at least one pixel. + * + * @param FloatArray uvs Interleaved atlas-frame uvs. + * @param Int pageWidth The page's pixel width. + * @param Int pageHeight The page's pixel height. + * @return IntArray? [x0, y0, x1, y1] (exclusive max), or null when there are no uvs. + */ + internal fun patchRectOf(uvs: FloatArray, pageWidth: Int, pageHeight: Int): IntArray? { + if (uvs.size < 2) { + return null + } + var minU = Float.POSITIVE_INFINITY + var minV = Float.POSITIVE_INFINITY + var maxU = Float.NEGATIVE_INFINITY + var maxV = Float.NEGATIVE_INFINITY + var componentIndex = 0 + while (componentIndex + 1 < uvs.size) { + minU = minOf(minU, uvs[componentIndex]) + maxU = maxOf(maxU, uvs[componentIndex]) + minV = minOf(minV, uvs[componentIndex + 1]) + maxV = maxOf(maxV, uvs[componentIndex + 1]) + componentIndex += 2 + } + if (!minU.isFinite() || !minV.isFinite() || !maxU.isFinite() || !maxV.isFinite()) { + return null + } + val x0 = kotlin.math.floor(minU * pageWidth).toInt().coerceIn(0, pageWidth - 1) + val y0 = kotlin.math.floor(minV * pageHeight).toInt().coerceIn(0, pageHeight - 1) + val x1 = kotlin.math.ceil(maxU * pageWidth).toInt().coerceIn(x0 + 1, pageWidth) + val y1 = kotlin.math.ceil(maxV * pageHeight).toInt().coerceIn(y0 + 1, pageHeight) + return intArrayOf(x0, y0, x1, y1) + } + + /** + * The material-local point whose image under [pageFit] is the given canvas point. + * + * This back-solves the declared packing origin from the snapped integer placement so that + * atlasLocalToCanvasTransform composed with materialLocalToAtlasTransform reproduces + * _materialLocalToCanvasTransform exactly - the official files' structure (their packing + * origins are fractional, carrying the complement of the fit's fractional translation). + * + * @param CAffine pageFit The page-to-canvas fit. + * @param Float canvasX The snapped placement x. + * @param Float canvasY The snapped placement y. + * @return FloatArray The (x, y) material-local origin, or null when the fit is degenerate. + */ + private fun solvePageFitFor(pageFit: CAffine, canvasX: Float, canvasY: Float): FloatArray? { + val determinant = pageFit.m00.toDouble() * pageFit.m11 - pageFit.m01.toDouble() * pageFit.m10 + if (determinant == 0.0) { + return null + } + val deltaX = canvasX.toDouble() - pageFit.m02 + val deltaY = canvasY.toDouble() - pageFit.m12 + return floatArrayOf( + ((pageFit.m11 * deltaX - pageFit.m01 * deltaY) / determinant).toFloat(), + ((pageFit.m00 * deltaY - pageFit.m10 * deltaX) / determinant).toFloat(), + ) + } + + /** + * Writes a packing origin into [transform]: the position in page pixels, the packer's resampling + * scale, and its rotation in degrees. + * + * CMO3: ModelImageEntry field materialLocalToAtlasTransform - a GTransform2 whose position is the + * packing origin in page pixels, scale the packer's resampling, and eulerAngle its rotation in + * DEGREES. Shared by the fresh conversion, the export's pack-in mint, and the placement lowering, + * so the three write one convention. + * + * @param GTransform2 transform The transform to write into; an entry's own, so it keeps its instance. + * @param Float positionX The packing origin's x on the page. + * @param Float positionY The packing origin's y on the page. + * @param Float scaleX The packer's horizontal scale. + * @param Float scaleY The packer's vertical scale. + * @param Float rotationDegrees The packer's rotation, counter-clockwise degrees. + * @return GTransform2 The same [transform]. + */ + internal fun writePacking( + transform: GTransform2, + positionX: Float, + positionY: Float, + scaleX: Float, + scaleY: Float, + rotationDegrees: Float, + ): GTransform2 { + transform.position = + GVector2().apply { + x = positionX + y = positionY + } + transform.scale = + GVector2().apply { + x = scaleX + y = scaleY + } + transform.eulerAngle = rotationDegrees + return transform + } + + /** + * [writePacking] from a runtime placement. + * + * @param GTransform2 transform The transform to write into. + * @param AtlasPlacement placement Where the art sits on its page. + * @return GTransform2 The same [transform]. + */ + internal fun writePacking(transform: GTransform2, placement: AtlasPlacement): GTransform2 = + writePacking( + transform, + placement.positionX, + placement.positionY, + placement.scaleX, + placement.scaleY, + placement.rotationDegrees, + ) + + /** + * A page's packed entry for one model image: the membership back-reference, the shared guid, and + * the transform pair the editor's atlas and mesh-edit views derive mesh-over-texture placement + * from. + * + * CMO3: ModelImageEntry fields atlas / modelImageGuid / autoLayoutLock / + * atlasLocalToCanvasTransform / materialLocalToAtlasTransform. The guid is the model image's OWN + * instance, so the writer shares it like the editor's files; autoLayoutLock is an AutoLayoutLock + * enum (v="NONE") - the editor's field is enum-typed and class-casts a boolean. Shared by the + * fresh conversion and the export's pack-in mint, so an entry minted into a retained graph is + * field-for-field the shape the fresh path writes. + * + * @param CTextureAtlas atlas The page the entry lives in. + * @param Any? modelImageGuid The model image's own guid instance. + * @param CAffine atlasLocalToCanvas The fitted atlas-to-canvas placement, an independent instance. + * @param GTransform2 packing The packing origin on the page. + * @return ModelImageEntry The entry. + */ + internal fun packedEntry( + atlas: CTextureAtlas, + modelImageGuid: Any?, + atlasLocalToCanvas: CAffine, + packing: GTransform2, + ): ModelImageEntry = + ModelImageEntry().apply { + this.atlas = atlas + this.modelImageGuid = modelImageGuid + autoLayoutLock = AutoLayoutLock.NONE + atlasLocalToCanvasTransform = atlasLocalToCanvas + materialLocalToAtlasTransform = packing + } + + /** + * The model image's material-local-to-canvas placement: the page fit composed with the patch + * origin, so patch pixel (0,0) maps to the canvas point the page fit sends (x0, y0) to. + * + * CMO3: CModelImage field _materialLocalToCanvasTransform (official layers carry their canvas + * origin here - translate(144, 222) in ModelWithOffscreenPartClipping). + * + * @param CAffine pageFit The atlas-page-to-canvas fit. + * @param Int x0 The patch origin x on the page. + * @param Int y0 The patch origin y on the page. + * @return CAffine The material-local placement. + */ + private fun materialLocalToCanvas(pageFit: CAffine, x0: Int, y0: Int): CAffine = + pageFit.copyAffine().apply { + m02 = pageFit.m00 * x0 + pageFit.m01 * y0 + pageFit.m02 + m12 = pageFit.m10 * x0 + pageFit.m11 * y0 + pageFit.m12 + } + + /** + * How far kept coverage grows past the mesh's own triangles, in page pixels. + * + * Cutting exactly on the outermost edge would fringe the silhouette: the drawable's UVs reach + * that edge, so a bilinear tap there blends against the transparent pixel immediately outside. + * Two pixels covers a bilinear tap plus a mip level while staying well inside the gutter a + * packer leaves between neighbouring patches. + */ + private const val COVERAGE_BLEED_MARGIN = 2 + + /** + * Which pixels of a patch rect the drawable's own mesh covers, grown by [COVERAGE_BLEED_MARGIN]. + * + * A patch rect is the mesh's axis-aligned uv bounding box, so for any mesh that is not itself a + * page-aligned rectangle the rect also spans page pixels belonging to whatever the packer nested + * into the leftover corners. Copying the rect verbatim hands those foreign pixels to this + * drawable's CModelImage, which the editor treats as the drawable's own artwork - it travels + * with the patch when the atlas is rearranged and gets stamped back into the page on a repack. + * Masking to the triangles keeps the crop rect (so every placement transform is unchanged) while + * dropping pixels the mesh never samples. + * + * Rasterization is CONSERVATIVE - a pixel counts as covered when its square overlaps a triangle + * at all, not when its center happens to land inside one. Cubism meshes carry long sliver + * triangles along a silhouette, and center sampling drops the ones thinner than a pixel. + * + * @param FloatArray uvs Interleaved atlas-frame uvs. + * @param IntArray indices Triangle indices, three per triangle. + * @param Int pageWidth The page's pixel width. + * @param Int pageHeight The page's pixel height. + * @param Int patchX0 The patch rect's origin x on the page. + * @param Int patchY0 The patch rect's origin y on the page. + * @param Int cropWidth The patch rect's width. + * @param Int cropHeight The patch rect's height. + * @return BooleanArray One flag per crop pixel in row-major order, or null when the mesh carries + * no triangles to mask with (the whole rect is then kept, as before). + */ + private fun coverageMaskOf( + uvs: FloatArray, + indices: IntArray, + pageWidth: Int, + pageHeight: Int, + patchX0: Int, + patchY0: Int, + cropWidth: Int, + cropHeight: Int, + ): BooleanArray? { + if (indices.size < 3) { + return null + } + val vertexCount = uvs.size / 2 + val covered = BooleanArray(cropWidth * cropHeight) + var triangleStart = 0 + while (triangleStart + 2 < indices.size) { + val indexA = indices[triangleStart] + val indexB = indices[triangleStart + 1] + val indexC = indices[triangleStart + 2] + triangleStart += 3 + if (indexA !in 0 until vertexCount || indexB !in 0 until vertexCount || indexC !in 0 until vertexCount) { + continue + } + val cornerAx = uvs[2 * indexA].toDouble() * pageWidth - patchX0 + val cornerAy = uvs[2 * indexA + 1].toDouble() * pageHeight - patchY0 + val cornerBx = uvs[2 * indexB].toDouble() * pageWidth - patchX0 + val cornerBy = uvs[2 * indexB + 1].toDouble() * pageHeight - patchY0 + val cornerCx = uvs[2 * indexC].toDouble() * pageWidth - patchX0 + val cornerCy = uvs[2 * indexC + 1].toDouble() * pageHeight - patchY0 + val doubledArea = (cornerBx - cornerAx) * (cornerCy - cornerAy) - (cornerCx - cornerAx) * (cornerBy - cornerAy) + if (!doubledArea.isFinite() || doubledArea == 0.0) { + continue + } + // Normalize the winding so "inside" is uniformly a non-negative edge value. + val winding = if (doubledArea > 0.0) 1.0 else -1.0 + // One extra pixel each way: the conservative test below reaches half a pixel past the + // triangle, and a bounding box rounded inward would clip that reach off. + val firstColumn = kotlin.math.floor(minOf(cornerAx, cornerBx, cornerCx)).toInt().coerceIn(0, cropWidth - 1) - 1 + val lastColumn = kotlin.math.ceil(maxOf(cornerAx, cornerBx, cornerCx)).toInt().coerceIn(0, cropWidth - 1) + 1 + val firstRow = kotlin.math.floor(minOf(cornerAy, cornerBy, cornerCy)).toInt().coerceIn(0, cropHeight - 1) - 1 + val lastRow = kotlin.math.ceil(maxOf(cornerAy, cornerBy, cornerCy)).toInt().coerceIn(0, cropHeight - 1) + 1 + for (rowIndex in maxOf(0, firstRow)..minOf(cropHeight - 1, lastRow)) { + val pointY = rowIndex + 0.5 + for (columnIndex in maxOf(0, firstColumn)..minOf(cropWidth - 1, lastColumn)) { + val flatIndex = rowIndex * cropWidth + columnIndex + if (covered[flatIndex]) { + continue + } + val pointX = columnIndex + 0.5 + if (overlapsEdge(cornerAx, cornerAy, cornerBx, cornerBy, pointX, pointY, winding) && + overlapsEdge(cornerBx, cornerBy, cornerCx, cornerCy, pointX, pointY, winding) && + overlapsEdge(cornerCx, cornerCy, cornerAx, cornerAy, pointX, pointY, winding) + ) { + covered[flatIndex] = true + } + } + } + } + return dilate(covered, cropWidth, cropHeight, COVERAGE_BLEED_MARGIN) + } + + /** + * Whether a pixel's unit square reaches the inside half-plane of one triangle edge. + * + * The edge value at the pixel center varies by at most half the sum of the edge normal's + * components across the square, so adding that slack turns a center test into a square-overlap + * test - which is what keeps sub-pixel slivers from vanishing. + * + * @param Double fromX Edge start x, in crop-local pixels. + * @param Double fromY Edge start y. + * @param Double toX Edge end x. + * @param Double toY Edge end y. + * @param Double pointX The pixel center's x. + * @param Double pointY The pixel center's y. + * @param Double winding +1 when the triangle winds counter-clockwise, -1 when clockwise. + * @return Boolean True when the pixel square is not fully outside this edge. + */ + private fun overlapsEdge( + fromX: Double, + fromY: Double, + toX: Double, + toY: Double, + pointX: Double, + pointY: Double, + winding: Double, + ): Boolean { + val edgeX = toX - fromX + val edgeY = toY - fromY + val edgeValue = winding * (edgeX * (pointY - fromY) - edgeY * (pointX - fromX)) + return edgeValue + 0.5 * (kotlin.math.abs(edgeX) + kotlin.math.abs(edgeY)) >= 0.0 + } + + /** + * Grows a coverage mask by [margin] pixels, as two linear-time passes over a sliding window. + * + * @param BooleanArray covered The raw per-pixel coverage, row-major. + * @param Int width The mask width. + * @param Int height The mask height. + * @param Int margin How many pixels to grow by. + * @return BooleanArray The grown mask ([covered] itself when the margin is zero). + */ + private fun dilate(covered: BooleanArray, width: Int, height: Int, margin: Int): BooleanArray { + if (margin <= 0) { + return covered + } + val grownAcross = BooleanArray(covered.size) + for (rowIndex in 0 until height) { + val rowStart = rowIndex * width + var windowCount = 0 + for (columnIndex in 0..minOf(margin, width - 1)) { + if (covered[rowStart + columnIndex]) { + windowCount += 1 + } + } + for (columnIndex in 0 until width) { + grownAcross[rowStart + columnIndex] = windowCount > 0 + val leavingColumn = columnIndex - margin + val enteringColumn = columnIndex + margin + 1 + if (leavingColumn >= 0 && covered[rowStart + leavingColumn]) { + windowCount -= 1 + } + if (enteringColumn < width && covered[rowStart + enteringColumn]) { + windowCount += 1 + } + } + } + val grown = BooleanArray(covered.size) + for (columnIndex in 0 until width) { + var windowCount = 0 + for (rowIndex in 0..minOf(margin, height - 1)) { + if (grownAcross[rowIndex * width + columnIndex]) { + windowCount += 1 + } + } + for (rowIndex in 0 until height) { + grown[rowIndex * width + columnIndex] = windowCount > 0 + val leavingRow = rowIndex - margin + val enteringRow = rowIndex + margin + 1 + if (leavingRow >= 0 && grownAcross[leavingRow * width + columnIndex]) { + windowCount -= 1 + } + if (enteringRow < height && grownAcross[enteringRow * width + columnIndex]) { + windowCount += 1 + } + } + } + return grown + } + + /** + * Copies the patch rect out of a decoded page, clearing pixels outside [coverage]. + * + * @param RasterImage decodedPage The decoded page pixels. + * @param Int x0 Patch origin x. + * @param Int y0 Patch origin y. + * @param Int cropWidth Patch width. + * @param Int cropHeight Patch height. + * @param BooleanArray coverage The mesh coverage mask, or null to keep the whole rect. + * @return RasterImage The masked crop pixels. + */ + private fun maskedCropOf( + decodedPage: RasterImage, + x0: Int, + y0: Int, + cropWidth: Int, + cropHeight: Int, + coverage: BooleanArray?, + ): RasterImage { + val cropRgba = ByteArray(cropWidth * cropHeight * 4) + for (rowIndex in 0 until cropHeight) { + val sourceOffset = ((y0 + rowIndex) * decodedPage.width + x0) * 4 + val targetOffset = rowIndex * cropWidth * 4 + decodedPage.rgba.copyInto(cropRgba, targetOffset, sourceOffset, sourceOffset + cropWidth * 4) + if (coverage == null) { + continue + } + for (columnIndex in 0 until cropWidth) { + if (coverage[rowIndex * cropWidth + columnIndex]) { + continue + } + val pixelOffset = targetOffset + columnIndex * 4 + cropRgba.fill(0, pixelOffset, pixelOffset + 4) + } + } + return RasterImage(cropWidth, cropHeight, cropRgba) + } + + /** + * The crop web's one model-image group and the two lists the pages append to, minted only once a + * drawable actually takes the crop path. + * + * @property CModelImageGroup group The group. + * @property CArrayList linkedRawImageGuids The stand-in documents' guids, one per cropped page. + * @property CArrayList modelImages The crop model images. + */ + private class CropGroup( + val group: CModelImageGroup, + val linkedRawImageGuids: CArrayList, + val modelImages: CArrayList, + ) + + /** + * Populates [root]'s texture manager with one page chain per atlas page, the real-layer web for + * every artwork file in [sourceImages] (a layered image per file, a layer and model image per + * tile from the document's own raster, entries and bindings off the tiles' placements), and the + * crop web for the drawables [regionsByPage] lists - the MOC3-origin stand-in that slices each + * drawable's patch out of its page. A page with no crop regions mints no stand-in document, so an + * artwork-origin file carries none. + * + * @param CModelSource root The fresh skeleton root (its textureManager must exist). + * @param List pages The atlas pages, in model3 texture order. + * @param List regionsByPage Each page's crop-path drawable regions (geometry for the patch + * crop and the placement fit), indexed like [pages]. + * @param Long nowMillis The import timestamp the wrappers record (caller-supplied + * so tests stay deterministic). + * @param Boolean fromSourceLayers The document's display mode: true writes the texture + * manager's combined-layer mode, false the packed-atlas one. + * @param List sourceImages The artwork files whose tiles have real art, with their layers. + * @return BuiltImageChain The PNG entries plus the texture bindings. + */ + internal fun populate( + root: CModelSource, + pages: List, + regionsByPage: List>, + nowMillis: Long, + fromSourceLayers: Boolean = false, + sourceImages: List = emptyList(), + ): BuiltImageChain { + val textureManager = root.textureManager as? CTextureManager ?: error("skeleton has no texture manager") + val names = Cmo3FreshChainNames() + val rawImages = + mutableGraphListOf(textureManager._rawImages) ?: error("skeleton texture manager has no raw-image list") + val textureAtlases = + mutableGraphListOf(textureManager._textureAtlases) ?: error("skeleton texture manager has no texture-atlas list") + val modelImageGroups = + mutableGraphListOf(textureManager._modelImageGroups) ?: error("skeleton texture manager has no model-image-group list") + val pngEntries = ArrayList() + val bindingByDrawableId = HashMap() + val pageFallbackBindings = ArrayList(pages.size) + val atlases = ArrayList(pages.size) + val textures = ArrayList(pages.size) + var cropGroup: CropGroup? = null + var cropDrawableCount = 0 + for ((pageIndex, page) in pages.withIndex()) { + val pagePath = names.nextImageFileBufPath() + pngEntries.add(Cmo3FreshFile.PngEntry(pagePath, page.pngBytes)) + val pageResource = pageImageResource(pagePath, page.width, page.height, page.pngBytes.size) + val atlas = pageAtlas(pageIndex, page.width, page.height, pageResource) + val texture = pageTexture(atlas.name, pageResource) + atlases.add(atlas) + textures.add(texture) + val regions = regionsByPage.getOrNull(pageIndex).orEmpty() + if (regions.isNotEmpty()) { + val group = + cropGroup ?: run { + val linkedRawImageGuids = CArrayList() + val modelImages = CArrayList() + val minted = + CModelImageGroup().apply { + memo = "" + groupName = "Textures" + _linkedRawImageGuids = linkedRawImageGuids + _modelImages = modelImages + } + CropGroup(minted, linkedRawImageGuids, modelImages).also { cropGroup = it } + } + cropDrawableCount += regions.size + rawImages.add(cropWeb(page, pageIndex, regions, atlas, texture, group, names, pngEntries, bindingByDrawableId, nowMillis)) + } + pageFallbackBindings.add(Cmo3DrawableTextureBinding(texture, atlas.guid as Guid, null, CAffine())) + textureAtlases.add(atlas) + } + cropGroup?.let { group -> modelImageGroups.add(group.group) } + for (image in sourceImages) { + val written = Cmo3SourceLayerWeb.write(image, atlases, textures, names, pngEntries, nowMillis) + rawImages.add(written.wrapper) + modelImageGroups.add(written.group) + bindingByDrawableId.putAll(written.bindingByDrawableId) + } + // CMO3: CTextureManager field isTextureInputModelImageMode - the document's own display mode. + // The synthesized web carries BOTH inputs per drawable (a model image and an atlas region), so + // either mode is representable; the diff-driven lowering retargets currentTextureInputData to + // match. This path is not covered by that lowering, so it reads the model directly rather than + // hardcoding a mode the document may not be in. + textureManager.isTextureInputModelImageMode = fromSourceLayers + return BuiltImageChain(pngEntries, bindingByDrawableId, pageFallbackBindings, cropDrawableCount) + } + + /** + * One model image over one layer: the editor's layer-filter web selecting [layer] at identity, + * the layer's own resource as the filtered image, the padded cache manager over it, the icon of + * its pixels, and the canvas placement. Shared by the crop web and the real-layer web, so a crop + * and a real layer carry field-for-field the same shape around their pixels. + * + * @param String name The model image's name (the drawable's, as the editor writes it). + * @param CLayeredImage layeredImage The layered image the layer belongs to. + * @param CLayer layer The layer the image composites. + * @param CImageResource resource The layer's own resource, which is also the filtered image. + * @param RasterImage raster The resource's pixels, which the icon shows fitted. + * @param CAffine placement The material-local-to-canvas placement, an independent instance. + * @param CModelImageGroup group The group the image belongs to. + * @param Cmo3FreshChainNames names The document's shared filter definitions and naming counters. + * @param MutableList pngEntries The PNG entry collector, for the icon. + * @param Long nowMillis The timestamp the env values record. + * @return CModelImage The model image. + */ + internal fun modelImageOver( + name: String, + layeredImage: CLayeredImage, + layer: CLayer, + resource: CImageResource, + raster: RasterImage, + placement: CAffine, + group: CModelImageGroup, + names: Cmo3FreshChainNames, + pngEntries: MutableList, + nowMillis: Long, + ): CModelImage = + CModelImage().apply { + guid = Cmo3SkeletonBuilder.freshGuid("CModelImageGuid") + this.name = name + // CMO3: CModelImage fields inputFilter / inputFilterEnv - the layer-filter web selecting + // this layer; the deserializer dereferences both. + inputFilter = buildFilterSet(names.filters) + inputFilterEnv = + ModelImageFilterEnv().apply { + envValues = + CHashMap().apply { + put( + names.filters.currentImageGuid, + EnvValueSet().apply { + id = names.filters.currentImageGuid + value = layeredImage.guid + updateTimeMs = nowMillis + }, + ) + put( + names.filters.inputLayerData, + EnvValueSet().apply { + id = names.filters.inputLayerData + value = + CLayerSelectorMap().apply { + _imageToLayerInput = + LinkedHashMap().apply { + put( + layeredImage.guid, + ArrayList( + mutableListOf( + CLayerInputData().apply { + this.layer = layer + affine = CAffine() + }, + ), + ), + ) + } + } + updateTimeMs = nowMillis + }, + ) + } + } + _filteredImage = resource + // CMO3: CModelImage fields icon16 / cachedImageManager - present on every corpus model + // image; the icon is the filtered image fitted into its square. + icon16 = Cmo3Icons.iconOf(raster, 16, names.nextIconPath(), pngEntries) + // CMO3: CModelImage field _materialLocalToCanvasTransform - the layer's canvas placement + // (official layers carry their canvas origin here), the same numbers the layer's + // boundsOnImageDoc origin carries. + _materialLocalToCanvasTransform = placement + _group = group + linkedRawImageGuids = CArrayList(mutableListOf(layeredImage.guid)) + cachedImageManager = paddedCacheManager(resource, resource.width, resource.height) + memo = "" + } + + /** + * The crop web for one page: a stand-in layered image whose frame is the page itself, one layer + * and model image per distinct (patch, mesh) crop, an entry per crop on the page's atlas, and a + * binding per drawable. The MOC3-origin path: the only raw material a bake leaves is the page, + * so each drawable's patch is sliced back out of it (see the file comment). + * + * @param Cmo3Conversion.AtlasPage page The page. + * @param Int pageIndex The page's index. + * @param List regions The crop-path drawables on the page, at least one. + * @param CTextureAtlas atlas The page's atlas element. + * @param GTexture2D texture The page's shared texture. + * @param CropGroup group The crop web's model-image group. + * @param Cmo3FreshChainNames names The document's shared definitions and naming counters. + * @param MutableList pngEntries The PNG entry collector. + * @param MutableMap bindingByDrawableId The binding collector. + * @param Long nowMillis The import timestamp the wrapper records. + * @return LayeredImageWrapper The stand-in document's wrapper, for the texture manager's raw-image list. + */ + private fun cropWeb( + page: Cmo3Conversion.AtlasPage, + pageIndex: Int, + regions: List, + atlas: CTextureAtlas, + texture: GTexture2D, + group: CropGroup, + names: Cmo3FreshChainNames, + pngEntries: MutableList, + bindingByDrawableId: MutableMap, + nowMillis: Long, + ): LayeredImageWrapper { + val pageName = "Texture_$pageIndex.png" + val layeredImage = CLayeredImage() + val patchLayers = CArrayList() + val rootLayerGroup = + CLayerGroup().apply { + name = "root" + memo = "" + isVisible = true + blend = names.sharedBlend + guid = Cmo3SkeletonBuilder.freshGuid("CLayerGuid") + opacity255 = 255 + _optionOfIOption = names.sharedOptions + _layeredImage = layeredImage + _children = patchLayers + } + val layerEntryList = CArrayList(mutableListOf(rootLayerGroup)) + layeredImage.apply { + name = pageName + memo = "" + // CMO3: CLayeredImage width/height - the SOURCE document's own frame, unrelated to + // the canvas (ModelWithOffscreenPartClipping: a 500x500 doc in a 1000x2000 canvas). + // Our synthetic source document IS the atlas page, so the page dims are its frame. + width = page.width + height = page.height + // A rendered page has no source file on anyone's disk; the bare name is the honest + // breadcrumb (the editor stores the importing machine's absolute path here). + psdFile = FileRef().apply { textPath = pageName } + description = "" + guid = Cmo3SkeletonBuilder.freshGuid("CLayeredImageGuid") + psdFileLastModified = nowMillis + _rootLayer = rootLayerGroup + layerSet = + LayerSet().apply { + _layeredImage = layeredImage + _layerEntryList = layerEntryList + } + } + val wrapper = + LayeredImageWrapper().apply { + image = layeredImage + importedTimeMSec = nowMillis + lastModifiedTimeMSec = nowMillis + } + val atlasEntries = checkNotNull(mutableGraphListOf(atlas.modelImages)) { "pageAtlas builds a list" } + // Patch webs, shared across drawables sampling the same crop with the same mesh (mirror + // twins get ONE material like official files; each twin's placement rides its own + // region input, and the shared image keeps the first drawable's placement). + val decodedPage = PngCodec.read(page.pngBytes) + val patchWebByKey = HashMap() + + /** + * An icon entry of its own for one drawable, over PNG bytes twins share. + * + * @param ByteArray png The encoded icon. + * @param Int size The square's edge. + * @return CImageIcon The icon. + */ + fun iconEntry(png: ByteArray, size: Int): CImageIcon { + val path = names.nextIconPath() + pngEntries.add(Cmo3FreshFile.PngEntry(path, png)) + return Cmo3Icons.iconReferencing(size, path) + } + for (region in regions) { + val pageFit = fitAtlasPageToCanvasTransform(region.uvs, region.positions, page.width, page.height) + val patch = patchRectOf(region.uvs, page.width, page.height) + if (patch == null) { + bindingByDrawableId[region.drawableIdStr] = + Cmo3DrawableTextureBinding(texture, atlas.guid as Guid, null, pageFit) + continue + } + val patchX0 = patch[0] + val patchY0 = patch[1] + val cropWidth = patch[2] - patch[0] + val cropHeight = patch[3] - patch[1] + val webKey = PatchWebKey(patch, region.uvs, region.indices) + val patchWeb = + patchWebByKey.getOrPut(webKey) { + val coverage = + coverageMaskOf(region.uvs, region.indices, page.width, page.height, patchX0, patchY0, cropWidth, cropHeight) + val maskedCrop = maskedCropOf(decodedPage, patchX0, patchY0, cropWidth, cropHeight, coverage) + // Trim the masked crop to its opaque pixel bounds: an official layer rect + // records the ART's own bounds, not the mesh's reach (the auto-mesh margin + // the uv bbox includes), and trimming lands within ~1px median of the + // editor's own rects on the EricaTamamo differential. A fully transparent + // crop (a mesh over empty page pixels) keeps the untrimmed rect. + val opaqueBounds = + analyzeAlpha(cropWidth, cropHeight, maskedCrop.rgba, contourEpsilon = 0f)?.opaqueBounds + val trimmedCrop = if (opaqueBounds == null) maskedCrop else maskedCrop.cropped(opaqueBounds) + val trimmedX0 = patchX0 + (opaqueBounds?.left ?: 0) + val trimmedY0 = patchY0 + (opaqueBounds?.top ?: 0) + // Anchor the web on an INTEGER canvas placement, official-style: every + // official _materialLocalToCanvasTransform translation is a whole number + // (176 of 176 on EricaTamamo) while the packing origin and the page fit + // carry complementary FRACTIONS whose composition reproduces it exactly. + // So snap the placement to the nearest canvas pixel and back-solve the + // declared packing origin through the fit - the whole chain then composes + // without a rounding step, and boundsOnImageDoc equals the placement + // bit-for-bit instead of disagreeing by the rounding residue (the editor's + // source-image view shows that residue as a subtle per-layer misplacement). + val patchPlacement = materialLocalToCanvas(pageFit, trimmedX0, trimmedY0) + patchPlacement.m02 = kotlin.math.round(patchPlacement.m02) + patchPlacement.m12 = kotlin.math.round(patchPlacement.m12) + val packingOrigin = solvePageFitFor(pageFit, patchPlacement.m02, patchPlacement.m12) + val cropBytes = PngCodec.write(trimmedCrop) + val cropPath = names.nextImageFileBufPath() + pngEntries.add(Cmo3FreshFile.PngEntry(cropPath, cropBytes)) + val cropResource = + CImageResource().apply { + // CMO3: CImageResource - the drawable's patch cropped out of the page. + width = trimmedCrop.width + height = trimmedCrop.height + type = "INT_ARGB" + imageFileBuf = FileRef().apply { archivePath = cropPath } + imageFileBuf_size = cropBytes.size + } + val patchLayer = + CLayer().apply { + // CMO3: CLayer - the patch as its own layer on the canvas-frame doc, + // layerId null (no PSD layer identity exists for a rendered atlas). + name = region.drawableIdStr + memo = "" + isVisible = true + blend = names.sharedBlend + guid = Cmo3SkeletonBuilder.freshGuid("CLayerGuid") + opacity255 = 255 + _optionOfIOption = names.sharedOptions + _layeredImage = layeredImage + imageResource = cropResource + // CMO3: CLayer field boundsOnImageDoc - the layer's pixel rect on the + // layered-image doc: origin = the placement translation (equals the + // CModelImage's _materialLocalToCanvasTransform translation on all 892 + // corpus layers), size = the imageResource dims (also 892 of 892). + boundsOnImageDoc = + CRect().apply { + // The placement translation is already snapped integral, so + // this equals the transform without a second rounding. + x = patchPlacement.m02.toInt() + y = patchPlacement.m12.toInt() + width = trimmedCrop.width + height = trimmedCrop.height + } + layerIdentifier = + CLayerIdentifier().apply { + layerName = region.drawableIdStr + layerIdValue_testImpl = -1 + } + // CMO3: CLayer fields icon16 / icon64 - thumbnails on every corpus layer, + // the crop fitted into each square. + icon16 = Cmo3Icons.iconOf(trimmedCrop, 16, names.nextIconPath(), pngEntries) + icon64 = Cmo3Icons.iconOf(trimmedCrop, 64, names.nextIconPath(), pngEntries) + layerInfo = LinkedHashMap() + this.group = rootLayerGroup + } + patchLayers.add(patchLayer) + layerEntryList.add(patchLayer) + val patchImage = + modelImageOver(region.drawableIdStr, layeredImage, patchLayer, cropResource, trimmedCrop, patchPlacement.copyAffine(), group.group, names, pngEntries, nowMillis) + group.modelImages.add(patchImage) + atlasEntries.add( + // The declared packing origin is the fit-inverse of the snapped placement + // (fractional, like every official entry), NOT the raw crop rect origin, so + // the web composes to the integer placement exactly. + packedEntry( + atlas = atlas, + modelImageGuid = patchImage.guid, + atlasLocalToCanvas = pageFit.copyAffine(), + packing = + writePacking( + GTransform2(), + positionX = packingOrigin?.get(0) ?: trimmedX0.toFloat(), + positionY = packingOrigin?.get(1) ?: trimmedY0.toFloat(), + scaleX = 1f, + scaleY = 1f, + rotationDegrees = 0f, + ), + ), + ) + // The drawable icons show the crop, which IS the mesh's uv box; twins share the + // bytes and each takes an entry of its own, like the editor's one icon per drawable. + PatchWeb(patchImage.guid as Guid, Cmo3Icons.iconPngOf(trimmedCrop, 32), Cmo3Icons.iconPngOf(trimmedCrop, 16)) + } + bindingByDrawableId[region.drawableIdStr] = + Cmo3DrawableTextureBinding( + texture, + atlas.guid as Guid, + patchWeb.imageGuid, + pageFit.copyAffine(), + icon32 = iconEntry(patchWeb.icon32Png, 32), + icon16 = iconEntry(patchWeb.icon16Png, 16), + ) + } + group.linkedRawImageGuids.add(layeredImage.guid) + return wrapper + } + + /** + * One minted patch web, shared by every drawable sampling the same crop with the same mesh. + * + * @property Guid imageGuid The crop's model image guid. + * @property ByteArray icon32Png The 32px drawable icon's bytes. + * @property ByteArray icon16Png The 16px drawable icon's bytes. + */ + private class PatchWeb(val imageGuid: Guid, val icon32Png: ByteArray, val icon16Png: ByteArray) +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3KeyformLowering.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3KeyformLowering.kt new file mode 100644 index 0000000..5c59407 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3KeyformLowering.kt @@ -0,0 +1,1128 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3GraphEditor +import org.umamo.format.cmo3.model.custom.CFloatColor +import org.umamo.format.cmo3.model.custom.CRotationDeformerForm +import org.umamo.format.cmo3.model.gen.ACForm +import org.umamo.format.cmo3.model.gen.CArtMeshForm +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CGlueForm +import org.umamo.format.cmo3.model.gen.CGlueSource +import org.umamo.format.cmo3.model.gen.CPartForm +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CRotationDeformerSource +import org.umamo.format.cmo3.model.gen.CWarpDeformerForm +import org.umamo.format.cmo3.model.gen.CWarpDeformerSource +import org.umamo.format.cmo3.model.gen.KeyFormMorphTarget +import org.umamo.format.cmo3.model.gen.KeyFormMorphTargetSet +import org.umamo.format.cmo3.model.gen.KeyOnParameter +import org.umamo.format.cmo3.model.gen.KeyformBindingSource +import org.umamo.format.cmo3.model.gen.KeyformGridAccessKey +import org.umamo.format.cmo3.model.gen.KeyformGridSource +import org.umamo.format.cmo3.model.gen.KeyformOnGrid +import org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraint +import org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraintSet +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.KeyformBundle +import org.umamo.interop.KeyformBundleCell +import org.umamo.interop.KeyformBundleResult +import org.umamo.interop.OutOfSpanPolicy +import org.umamo.interop.buildKeyformBundle +import org.umamo.runtime.keyform.FormInterpolator +import org.umamo.runtime.keyform.MeshDeltaInterpolator +import org.umamo.runtime.keyform.RotationPivotInterpolator +import org.umamo.runtime.keyform.WarpLatticeInterpolator +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm + +/* + * The keyform half of the CMO3 export reconcile: re-bundling Umamo's split representation (a + * geometry grid plus independent per-channel tracks plus statics) back into CMO3's all-or-nothing + * keyform cells, and rebuilding the grid web (KeyformGridSource / KeyformBindingSource / + * KeyformOnGrid / KeyOnParameter / the forms pool) that encodes it. + * + * The re-bundling itself is the format-neutral buildKeyformBundle (KeyformBundle.kt), shared with the + * MOC3 export so both formats union the axes and re-interpolate through the same grid algebra. What + * stays here is CMO3's half: the RejectOwner policy and the graph writing. So a track whose own span + * does not cover the union of its parameter's keys cannot be represented in a bundled cell without + * inventing out-of-span values, and its owner is left untouched and reported rather than partially + * written. + * + * Object reuse is the byte-diff minimizer: surviving bindings, forms, and set objects are mutated + * in place (their recorded child slots replay), so an untouched value re-emits byte-identically; + * fresh objects are created only for genuinely new cells/axes, cloning conventions (guid kind, + * coordType, backrefs) from a surviving sibling. + */ +internal class Cmo3KeyformLowering( + private val index: Cmo3GraphIndex, + private val editor: Cmo3GraphEditor, + private val baseline: PuppetModel, + private val notices: MutableList, +) { + private val parameterIdByUuid: Map = + buildMap { + for (source in index.parameterSources) { + val uuid = Cmo3Import.uuidOf(source.guid) ?: continue + val idStr = Cmo3Import.idStrOf(source.id) ?: continue + put(uuid, ParameterId(idStr)) + } + } + private val baselineDrawableById = baseline.drawables.associateBy(Drawable::id) + + /** + * Per-name CoordType instances shared across every fresh form this lowering creates, so the + * writer hoists one shared def per name (the editor's own shape; it never writes a null + * coordType). + */ + private val coordTypes = HashMap() + + /** + * The CoordType a fresh form gets when no sibling template supplies one. + * + * CMO3: ACForm field coordType - corpus forms carry "DeformerLocal" under a parent deformer + * and "Canvas" at the deformer-tree root (the space the stored positions are expressed in). + * + * @param Boolean hasParentDeformer Whether the owning item deforms under a parent deformer. + * @return CoordType The shared per-export instance for that name. + */ + private fun formCoordType(hasParentDeformer: Boolean): org.umamo.format.cmo3.model.drawable.CoordType = + coordTypes.getOrPut(if (hasParentDeformer) "DeformerLocal" else "Canvas") { + org.umamo.format.cmo3.model.drawable.CoordType().apply { + coordName = if (hasParentDeformer) "DeformerLocal" else "Canvas" + } + } + + private fun unsupported( + category: ExportEntityCategory, + subject: String?, + reason: ExportNoticeReason, + ) { + notices.add(ExportNotice.UnsupportedChange(category, subject, reason)) + } + + /** + * [buildKeyformBundle] with CMO3's policy applied: an owner whose split state cannot be expressed + * as one grid is REJECTED and reported, rather than partially written, and an owner with no keys + * anywhere gets ONE default cell rather than no grid. + * + * The default cell is the editor's own requirement, not a convenience. Every + * ACParameterControllableSource in the official editor carries a KeyformGridSource with at least + * the default form: its setKeyformGridSource rejects null and CArtMeshSource.getDefaultKeyForm + * throws "no KeyForms" on an empty pool, and a model with either fails to open (Cubism 5.4 alpha1, + * checked 2026-09-04 against a file whose meshes had no grid). The corpus agrees - every unkeyed + * source, part, and glue holds an axis-less grid with one form, which is also what the structural + * create synthesizes for a fresh part or glue. So a fully unkeyed owner whose rest state lives + * outside its grid (a drawable's base mesh, a part's or glue's statics) bundles here to that one + * cell: no axes, no geometry payload (the form writers fall back to the owner's base), the statics + * as its channel values. A geometry owner (warp, rotation) with no grid has no rest geometry + * anywhere - it left with the last axis - so nothing is invented for it and the empty bundle + * stands. The shared bundler keeps returning the empty bundle because MOC3 has its own answer + * for an unkeyed owner (its lowering emits the rest form itself). + * + * CMO3 can decline to write an object's grid over a split state; MOC3 cannot (every object needs a + * keyform), which is why the shared bundler takes the policy as a parameter instead of assuming one. + * + * @param ExportEntityCategory category The notice category. + * @param String subject The owner's id for notices. + * @param KeyformGrid? geometryGrid The geometry grid, or null for a channel-only owner. + * @param FormInterpolator geometryBlend The geometry interpolator (unused when no geometry). + * @param ChannelGrids channels The owner's channel tracks. + * @param Map statics Fallback value per relevant channel. + * @param Boolean requireGeometry Whether a geometry-less bundle is an error (warp/rotation). + * @return KeyformBundle? The bundle, or null when unrepresentable (reported). + */ + private fun buildBundle( + category: ExportEntityCategory, + subject: String, + geometryGrid: KeyformGrid?, + geometryBlend: FormInterpolator, + channels: ChannelGrids, + statics: Map, + requireGeometry: Boolean, + ): KeyformBundle? = + when ( + val result = + buildKeyformBundle( + geometryGrid, + geometryBlend, + channels, + statics, + requireGeometry, + OutOfSpanPolicy.RejectOwner, + ) + ) { + is KeyformBundleResult.Bundled -> + if (!requireGeometry && result.bundle.axes.isEmpty() && result.bundle.cells.isEmpty()) { + KeyformBundle(emptyList(), listOf(KeyformBundleCell(IntArray(0), emptyMap(), null, statics))) + } else { + result.bundle + } + is KeyformBundleResult.Unrepresentable -> { + unsupported(category, subject, ExportNoticeReason.KeyformCannotBundle(result.rejection)) + null + } + } + + /** + * The forms of the CURRENT graph grid keyed by their per-parameter key values, for reuse. + * + * @param Any? gridSourceField The owner's keyformGridSource. + * @param Any? formsField The owner's keyforms pool. + * @return Map Value-coordinate key to form object. + */ + private fun existingFormsByValues(gridSourceField: Any?, formsField: Any?): Map { + val gridSource = gridSourceField as? KeyformGridSource ?: return emptyMap() + val bindings = + Cmo3Import.elementsOf(gridSource.keyformBindings).filterIsInstance() + val keysByBinding = + bindings.associateWith { binding -> + Cmo3Import.elementsOf(binding.keys).mapNotNull { (it as? Number)?.toFloat() } + } + val parameterByBinding = + bindings.associateWith { binding -> parameterIdByUuid[Cmo3Import.uuidOf(binding.parameterGuid)] } + val formByUuid = + Cmo3Import.elementsOf(formsField).filterIsInstance() + .associateBy { form -> Cmo3Import.uuidOf(form.guid) } + val byValues = HashMap() + for (cell in Cmo3Import.elementsOf(gridSource.keyformsOnGrid).filterIsInstance()) { + val form = formByUuid[Cmo3Import.uuidOf(cell.keyformGuid)] ?: continue + val values = HashMap() + val keyList = (cell.accessKey as? KeyformGridAccessKey)?._keyOnParameterList + var resolvable = true + for (keyOnParameter in Cmo3Import.elementsOf(keyList).filterIsInstance()) { + val binding = keyOnParameter.binding as? KeyformBindingSource ?: continue + val parameterId = parameterByBinding[binding] ?: continue + val keys = keysByBinding[binding] ?: continue + val key = keys.getOrNull(keyOnParameter.keyIndex) + if (key == null) { + resolvable = false + break + } + values[parameterId] = key + } + if (resolvable) { + byValues[valueKey(values)] = form + } + } + return byValues + } + + private fun valueKey(values: Map): String = + values.entries + .sortedBy { entry -> entry.key.raw } + .joinToString("|") { entry -> "${entry.key.raw}=${entry.value.toRawBits()}" } + + /** A fresh Guid cloning [template]'s kind (the tag the identity subsystem writes). */ + private fun freshGuidLike(template: Guid?): Guid = + Guid(template?.kind ?: "CFormGuid").apply { + uuid = java.util.UUID.randomUUID().toString() + note = template?.note ?: "(no debug info)" + } + + /** A template form of [TFormClass] from [ownForms], falling back to any owner of the same kind. */ + private inline fun templateForm(ownForms: Any?, fallbackPools: List): TFormClass? { + Cmo3Import.elementsOf(ownForms).filterIsInstance().firstOrNull()?.let { return it } + for (pool in fallbackPools) { + Cmo3Import.elementsOf(pool).filterIsInstance().firstOrNull()?.let { return it } + } + return null + } + + /** + * Rebuilds the grid web from [bundle]: bindings reused per parameter (keys rewritten), fresh + * cell records, and the given per-cell forms. + * + * @param Any owner The source object owning keyformGridSource. + * @param String subject The owner's id for notices. + * @param Any? currentGrid The current keyformGridSource. + * @param Function assignGrid Assigns a fresh grid source. + * @param KeyformBundle bundle The re-bundled grid. + * @param List cellForms One form object per bundle cell, in cell order. + * @return Boolean True on success. + */ + private fun writeGridWeb( + owner: Any, + subject: String, + currentGrid: Any?, + assignGrid: (Any?) -> Unit, + bundle: KeyformBundle, + cellForms: List, + ): Boolean { + if (bundle.cells.isEmpty()) { + // Only a geometry owner reaches here (buildBundle gives every other unkeyed owner its default + // cell): its rest geometry left with its last axis, so there is no form to write and the grid + // is removed. The editor wants a default cell there too; keeping an axis-less rest cell when + // the last axis collapses is the model's job (:edit), not this writer's to invent. + assignGrid(null) + editor.ensureChildSlot(owner, "ACParameterControllableSource", "keyformGridSource", "keyformMorphTargetSet") + return true + } + val gridSource = + currentGrid as? KeyformGridSource + ?: KeyformGridSource().also { + assignGrid(it) + editor.ensureChildSlot(owner, "ACParameterControllableSource", "keyformGridSource", "keyformMorphTargetSet") + } + val existingBindings = + Cmo3Import.elementsOf(gridSource.keyformBindings).filterIsInstance() + .associateBy { binding -> Cmo3Import.uuidOf(binding.parameterGuid) } + val bindingPerAxis = ArrayList(bundle.axes.size) + for (axis in bundle.axes) { + val parameterSource = index.parameterByIdStr[axis.parameterId.raw] + if (parameterSource == null) { + unsupported(ExportEntityCategory.Keyform, subject, ExportNoticeReason.AxisParameterHasNoSource(axis.parameterId.raw)) + return false + } + val binding = + existingBindings[Cmo3Import.uuidOf(parameterSource.guid)] + ?: KeyformBindingSource().apply { + _gridSource = gridSource + parameterGuid = parameterSource.guid + keys = ArrayList() + // CMO3: KeyformBindingSource fields interpolationType / + // extendedInterpolationType / insertPointCount / extendedInterpolationScale / + // description - every corpus binding writes LINEAR / LINEAR / 1 / 1.0 / "". + interpolationType = org.umamo.format.cmo3.model.gen.InterpolationType.LINEAR + extendedInterpolationType = org.umamo.format.cmo3.model.gen.ExtendedInterpolationType.LINEAR + insertPointCount = 1 + extendedInterpolationScale = 1f + description = "" + } + val keysList = mutableGraphListOf(binding.keys) + if (keysList != null) { + keysList.clear() + axis.keys.forEach { key -> keysList.add(key) } + } else { + binding.keys = ArrayList(axis.keys.map { it }) + editor.ensureChildSlot(binding, "KeyformBindingSource", "keys", "interpolationType") + } + bindingPerAxis.add(binding) + } + // CMO3: KeyformGridSource fields keyformBindings / keyformsOnGrid - array_list in every + // corpus model (vs the carray_list keyforms pools). + writeCollection(gridSource, "KeyformGridSource", "keyformBindings", "keyformsOnGrid", gridSource.keyformBindings, bindingPerAxis, { ArrayList() }) { + gridSource.keyformBindings = it + } + val cellRecords = ArrayList(bundle.cells.size) + for (cellIndex in bundle.cells.indices) { + val cell = bundle.cells[cellIndex] + val record = + KeyformOnGrid().apply { + keyformGuid = cellForms[cellIndex].guid + accessKey = + KeyformGridAccessKey().apply { + _keyOnParameterList = + ArrayList().apply { + for (axisIndex in bundle.axes.indices) { + add( + KeyOnParameter().apply { + binding = bindingPerAxis[axisIndex] + keyIndex = cell.coordinate[axisIndex] + }, + ) + } + } + } + } + cellRecords.add(record) + } + writeCollection(gridSource, "KeyformGridSource", "keyformsOnGrid", null, gridSource.keyformsOnGrid, cellRecords, { ArrayList() }) { + gridSource.keyformsOnGrid = it + } + return true + } + + /** + * Rewrites a collection field in place, or creates a fresh list and records its slot. + * + * The fresh list's runtime type decides the serialized tag (ArrayList = array_list, + * CArrayList = carray_list), and the official editor requires the exact tag per field: + * its deserializers cast carray_list fields to CArrayList, so a wrong tag is a + * ClassCastException on load. Every corpus model agrees on the tag per field, so each + * call site passes the factory matching what the editor writes there. + * + * @param Any owner The graph object owning the collection field. + * @param String tag The owner's serial tag for the child-slot record. + * @param String property The collection field's name. + * @param String? beforeProperty The sibling field the slot precedes, or null for last. + * @param Any? current The current field value. + * @param List newElements The elements to write. + * @param Function freshList Creates the list when the field is empty; the list type + * must match the tag the official editor writes. + * @param Function assign Assigns the fresh list to the field. + */ + private fun writeCollection( + owner: Any, + tag: String, + property: String, + beforeProperty: String?, + current: Any?, + newElements: List, + freshList: () -> MutableList, + assign: (MutableList) -> Unit, + ) { + val mutable = mutableGraphListOf(current) + if (mutable != null) { + mutable.clear() + mutable.addAll(newElements) + return + } + val fresh: MutableList = freshList() + fresh.addAll(newElements) + assign(fresh) + editor.ensureChildSlot(owner, tag, property, beforeProperty) + } + + /** Writes a color channel value into a form's CFloatColor field, creating one only when needed. */ + private fun writeFormColor( + form: ACForm, + formTag: String, + property: String, + beforeProperty: String?, + current: Any?, + assign: (Any?) -> Unit, + color: ColorRgb, + identity: ColorRgb, + ) { + val existing = current as? CFloatColor + if (existing != null) { + existing.red = color.red + existing.green = color.green + existing.blue = color.blue + return + } + if (color == identity) { + // An absent color already reads as the identity (the pre-5.3 convention); keep it absent. + return + } + assign( + CFloatColor().apply { + red = color.red + green = color.green + blue = color.blue + alpha = 1f + }, + ) + editor.ensureChildSlot(form, formTag, property, beforeProperty) + } + + private fun scalarOf(value: ChannelValue?): Float? = (value as? ChannelValue.Scalar)?.value + + private fun colorOf(value: ChannelValue?): ColorRgb? = (value as? ChannelValue.Color)?.color + + private fun flagOf(value: ChannelValue?): Boolean? = (value as? ChannelValue.Flag)?.flag + + /** True when every DRAW_ORDER value in [bundle] is integral (CMO3 stores draw order as Int). */ + private fun drawOrdersAreIntegral(bundle: KeyformBundle): Boolean = + bundle.cells.all { cell -> + val drawOrder = scalarOf(cell.channels[FormChannel.DRAW_ORDER]) ?: return@all true + drawOrder == drawOrder.toInt().toFloat() + } + + /** + * Lowers a drawable's keyforms and/or blend shapes. + * + * @param CArtMeshSource source The drawable's graph source. + * @param Drawable editedDrawable The edited drawable. + * @param Boolean rebuildGrid Whether the grid/channel/static state changed. + * @param Boolean rebuildMorphs Whether the blend shapes changed. + * @param Boolean alsoWriteBase Whether the base mesh moved too (positions rewritten here). + */ + fun lowerDrawable( + source: CArtMeshSource, + editedDrawable: Drawable, + rebuildGrid: Boolean, + rebuildMorphs: Boolean, + alsoWriteBase: Boolean, + ) { + val subject = editedDrawable.id.raw + val editedBase = editedDrawable.mesh?.positions + if (editedBase == null) { + unsupported(ExportEntityCategory.Drawable, subject, ExportNoticeReason.KeyformsWithoutBaseMesh) + return + } + val baselineBase = baselineDrawableById[editedDrawable.id]?.mesh?.positions + val statics = + mapOf( + FormChannel.DRAW_ORDER to ChannelValue.Scalar(editedDrawable.drawOrder), + FormChannel.OPACITY to ChannelValue.Scalar(editedDrawable.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(editedDrawable.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(editedDrawable.screenColor), + ) + val bundle = + buildBundle( + ExportEntityCategory.Drawable, + subject, + editedDrawable.geometryGrid, + MeshDeltaInterpolator, + editedDrawable.channelGrids, + statics, + requireGeometry = false, + ) ?: return + if (!drawOrdersAreIntegral(bundle)) { + unsupported(ExportEntityCategory.Drawable, subject, ExportNoticeReason.FractionalDrawOrderNotStorable) + return + } + val existingForms = existingFormsByValues(source.keyformGridSource, source.keyforms) + val template = + templateForm(source.keyforms, index.drawableSources.map { it.keyforms }) + + fun writeMeshForm(existing: CArtMeshForm?, deltas: FloatArray?, channels: Map): CArtMeshForm { + val form = + existing + ?: CArtMeshForm().apply { + guid = freshGuidLike((template?.guid ?: existingForms.values.firstOrNull()?.let { (it as ACForm).guid }) as? Guid) + isAnimatedForm = template?.isAnimatedForm ?: false + isLocalAnimatedForm = template?.isLocalAnimatedForm ?: false + _source = source + // CMO3: ACForm field notes - non-null in the editor's model (its setter rejects + // null), and every corpus form writes the empty string. + notes = template?.notes ?: "" + // CMO3: form multiply/screen colors - modern-era forms always carry identity + // values; the channel lowering overwrites them when a color channel exists. + multiplyColor = Cmo3SkeletonBuilder.identityMultiplyColor() + screenColor = Cmo3SkeletonBuilder.identityScreenColor() + coordType = template?.coordType ?: formCoordType(editedDrawable.parentDeformerId != null) + } + val origAbsolute = (existing?.positions as? FloatArray)?.takeIf { it.size == editedBase.size } + val absolute = + FloatArray(editedBase.size) { component -> + val delta = deltas?.getOrNull(component) ?: 0f + val reusable = + origAbsolute != null && + baselineBase != null && + baselineBase.size == editedBase.size && + editedBase[component].toRawBits() == baselineBase[component].toRawBits() && + delta.toRawBits() == (origAbsolute[component] - baselineBase[component]).toRawBits() + if (reusable) origAbsolute[component] else editedBase[component] + delta + } + // CMO3: CArtMeshForm field positions (absolute), ACDrawableForm fields drawOrder / + // opacity / multiplyColor / screenColor. + form.positions = absolute + editor.ensureChildSlot(form, "CArtMeshForm", "positions") + scalarOf(channels[FormChannel.DRAW_ORDER])?.let { drawOrder -> + form.drawOrder = drawOrder.toInt() + editor.ensureChildSlot(form, "ACDrawableForm", "drawOrder", "opacity") + } + scalarOf(channels[FormChannel.OPACITY])?.let { opacity -> + form.opacity = opacity + editor.ensureChildSlot(form, "ACDrawableForm", "opacity", "multiplyColor") + } + colorOf(channels[FormChannel.MULTIPLY_COLOR])?.let { color -> + writeFormColor(form, "ACDrawableForm", "multiplyColor", "screenColor", form.multiplyColor, { form.multiplyColor = it }, color, ColorRgb.MultiplyIdentity) + } + colorOf(channels[FormChannel.SCREEN_COLOR])?.let { color -> + writeFormColor(form, "ACDrawableForm", "screenColor", "coordType", form.screenColor, { form.screenColor = it }, color, ColorRgb.ScreenIdentity) + } + return form + } + + val gridForms = ArrayList(bundle.cells.size) + if (rebuildGrid) { + for (cell in bundle.cells) { + val existing = existingForms[valueKey(cell.values)] as? CArtMeshForm + gridForms.add(writeMeshForm(existing, (cell.geometry as? MeshDeltaForm)?.positionDeltas, cell.channels)) + } + if (alsoWriteBase) { + // Morph-target absolutes follow the base move (import re-derives blend-shape deltas + // as absolute minus base), so surviving morph forms rebase BEFORE the base swap - + // the same recompute lowerMeshPositions applies to its pool. Grid forms were just + // rewritten against the new base above and must not shift twice (identity skip), + // and a morph rebuild below writes fresh absolutes itself. + val origBase = source.positions as? FloatArray + if (!rebuildMorphs && origBase != null && origBase.size == editedBase.size) { + val rewrittenGridForms = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + gridForms.forEach { gridForm -> rewrittenGridForms.add(gridForm) } + for (morphForm in existingMorphForms(source.keyformMorphTargetSet, source.keyforms)) { + if (morphForm in rewrittenGridForms || morphForm !is CArtMeshForm) { + continue + } + val origAbsolute = morphForm.positions as? FloatArray + if (origAbsolute == null || origAbsolute.size != editedBase.size) { + continue + } + // CMO3: CArtMeshForm field positions - absolute vertex positions. Unchanged + // base components keep the stored value bit-identically (recompute the delta + // from the stored values, never (a-b)+b through IEEE rounding). + morphForm.positions = + FloatArray(origAbsolute.size) { component -> + if (editedBase[component].toRawBits() == origBase[component].toRawBits()) { + origAbsolute[component] + } else { + editedBase[component] + (origAbsolute[component] - origBase[component]) + } + } + editor.ensureChildSlot(morphForm, "CArtMeshForm", "positions") + } + } + source.positions = editedBase.copyOf() + editor.ensureChildSlot(source, "CArtMeshSource", "positions", "uvs") + val editableMesh = Cmo3Import.editableMeshOf(source) + val pointArray = editableMesh?.point as? FloatArray + if (editableMesh != null && (pointArray == null || pointArray.size == editedBase.size)) { + editableMesh.point = editedBase.copyOf() + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "point", "pointPriority") + } + } + if (!writeGridWeb(source, subject, source.keyformGridSource, { source.keyformGridSource = it }, bundle, gridForms)) { + return + } + } else { + // Grid untouched: keep its existing forms for the pool assembly below. + val gridGuids = gridFormGuids(source.keyformGridSource) + Cmo3Import.elementsOf(source.keyforms).filterIsInstance() + .filterTo(gridForms) { form -> Cmo3Import.uuidOf(form.guid) in gridGuids } + } + + val morphForms = + if (rebuildMorphs) { + rebuildMorphTargets( + ownerSource = source, + subject = subject, + currentSet = source.keyformMorphTargetSet, + assignSet = { source.keyformMorphTargetSet = it }, + formsField = source.keyforms, + bindings = editedDrawable.blendShapes, + ) { existing, payload: MeshForm -> + writeMeshForm( + existing as? CArtMeshForm, + payload.positionDeltas, + mapOf( + FormChannel.DRAW_ORDER to ChannelValue.Scalar(payload.drawOrder), + FormChannel.OPACITY to ChannelValue.Scalar(payload.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(payload.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(payload.screenColor), + ), + ) + } ?: return + } else { + existingMorphForms(source.keyformMorphTargetSet, source.keyforms) + } + writePool(source, "CArtMeshSource", "keyforms", "positions", source.keyforms, gridForms, morphForms) { + source.keyforms = it + } + } + + /** Lowers a warp deformer's keyforms and/or blend shapes. */ + fun lowerWarp(source: CWarpDeformerSource, editedWarp: Deformer.Warp, rebuildGrid: Boolean, rebuildMorphs: Boolean) { + val subject = editedWarp.id.raw + val statics = + mapOf( + FormChannel.OPACITY to ChannelValue.Scalar(editedWarp.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(editedWarp.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(editedWarp.screenColor), + ) + val bundle = + buildBundle(ExportEntityCategory.Deformer, subject, editedWarp.geometryGrid, WarpLatticeInterpolator, editedWarp.channelGrids, statics, requireGeometry = true) + ?: return + val existingForms = existingFormsByValues(source.keyformGridSource, source.keyforms) + val template = templateForm(source.keyforms, index.deformerSources.filterIsInstance().map { it.keyforms }) + + fun writeWarpForm(existing: CWarpDeformerForm?, payload: WarpLatticeForm?, channels: Map): CWarpDeformerForm { + val form = + existing + ?: CWarpDeformerForm().apply { + guid = freshGuidLike(template?.guid as? Guid) + isAnimatedForm = template?.isAnimatedForm ?: false + isLocalAnimatedForm = template?.isLocalAnimatedForm ?: false + _source = source + // CMO3: ACForm field notes - non-null in the editor's model (its setter rejects + // null), and every corpus form writes the empty string. + notes = template?.notes ?: "" + // CMO3: form multiply/screen colors - modern-era forms always carry identity + // values; the channel lowering overwrites them when a color channel exists. + multiplyColor = Cmo3SkeletonBuilder.identityMultiplyColor() + screenColor = Cmo3SkeletonBuilder.identityScreenColor() + coordType = template?.coordType ?: formCoordType(editedWarp.parent != null) + } + val newPoints = payload?.controlPoints + if (newPoints != null) { + val origPoints = existing?.positions as? FloatArray + // CMO3: CWarpDeformerForm field positions - absolute FFD control points. + form.positions = if (origPoints != null && origPoints.contentEquals(newPoints)) origPoints else newPoints.copyOf() + editor.ensureChildSlot(form, "CWarpDeformerForm", "positions") + } + scalarOf(channels[FormChannel.OPACITY])?.let { opacity -> + // CMO3: ACDeformerForm field opacity. + form.opacity = opacity + editor.ensureChildSlot(form, "ACDeformerForm", "opacity", "multiplyColor") + } + colorOf(channels[FormChannel.MULTIPLY_COLOR])?.let { color -> + writeFormColor(form, "ACDeformerForm", "multiplyColor", "screenColor", form.multiplyColor, { form.multiplyColor = it }, color, ColorRgb.MultiplyIdentity) + } + colorOf(channels[FormChannel.SCREEN_COLOR])?.let { color -> + writeFormColor(form, "ACDeformerForm", "screenColor", "coordType", form.screenColor, { form.screenColor = it }, color, ColorRgb.ScreenIdentity) + } + return form + } + + val gridForms = ArrayList(bundle.cells.size) + if (rebuildGrid) { + for (cell in bundle.cells) { + gridForms.add(writeWarpForm(existingForms[valueKey(cell.values)] as? CWarpDeformerForm, cell.geometry as? WarpLatticeForm, cell.channels)) + } + if (!writeGridWeb(source, subject, source.keyformGridSource, { source.keyformGridSource = it }, bundle, gridForms)) { + return + } + } else { + val gridGuids = gridFormGuids(source.keyformGridSource) + Cmo3Import.elementsOf(source.keyforms).filterIsInstance() + .filterTo(gridForms) { form -> Cmo3Import.uuidOf(form.guid) in gridGuids } + } + val morphForms = + if (rebuildMorphs) { + rebuildMorphTargets(source, subject, source.keyformMorphTargetSet, { source.keyformMorphTargetSet = it }, source.keyforms, editedWarp.blendShapes) { existing, payload: WarpForm -> + writeWarpForm( + existing as? CWarpDeformerForm, + WarpLatticeForm(payload.controlPoints), + mapOf( + FormChannel.OPACITY to ChannelValue.Scalar(payload.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(payload.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(payload.screenColor), + ), + ) + } ?: return + } else { + existingMorphForms(source.keyformMorphTargetSet, source.keyforms) + } + writePool(source, "CWarpDeformerSource", "keyforms", null, source.keyforms, gridForms, morphForms) { + source.keyforms = it + } + } + + /** Lowers a rotation deformer's keyforms and/or blend shapes. */ + fun lowerRotation(source: CRotationDeformerSource, editedRotation: Deformer.Rotation, rebuildGrid: Boolean, rebuildMorphs: Boolean) { + val subject = editedRotation.id.raw + val statics = + mapOf( + FormChannel.OPACITY to ChannelValue.Scalar(editedRotation.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(editedRotation.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(editedRotation.screenColor), + FormChannel.FLIP_X to ChannelValue.Flag(editedRotation.flipX), + FormChannel.FLIP_Y to ChannelValue.Flag(editedRotation.flipY), + ) + val bundle = + buildBundle(ExportEntityCategory.Deformer, subject, editedRotation.geometryGrid, RotationPivotInterpolator, editedRotation.channelGrids, statics, requireGeometry = true) + ?: return + val existingForms = existingFormsByValues(source.keyformGridSource, source.keyforms) + val template = templateForm(source.keyforms, index.deformerSources.filterIsInstance().map { it.keyforms }) + + fun writeRotationForm(existing: CRotationDeformerForm?, payload: RotationPivotForm?, channels: Map): CRotationDeformerForm { + val form = + existing + ?: CRotationDeformerForm().apply { + guid = freshGuidLike(template?.guid as? Guid) + isAnimatedForm = template?.isAnimatedForm ?: false + isLocalAnimatedForm = template?.isLocalAnimatedForm ?: false + _source = source + // CMO3: ACForm field notes - non-null in the editor's model (its setter rejects + // null), and every corpus form writes the empty string. + notes = template?.notes ?: "" + // CMO3: form multiply/screen colors - modern-era forms always carry identity + // values; the channel lowering overwrites them when a color channel exists. + multiplyColor = Cmo3SkeletonBuilder.identityMultiplyColor() + screenColor = Cmo3SkeletonBuilder.identityScreenColor() + coordType = template?.coordType ?: formCoordType(editedRotation.parent != null) + } + if (payload != null) { + // CMO3: CRotationDeformerForm attributes originX / originY / angle / scale. + form.originX = payload.originX + form.originY = payload.originY + form.angle = payload.angle + form.scale = payload.scale + for (attr in listOf("originX", "originY", "angle", "scale")) { + editor.ensurePresentAttr(form, "CRotationDeformerForm", attr) + } + } + flagOf(channels[FormChannel.FLIP_X])?.let { flip -> + // CMO3: CRotationDeformerForm attribute isReflectX. + form.isReflectX = flip + editor.ensurePresentAttr(form, "CRotationDeformerForm", "isReflectX") + } + flagOf(channels[FormChannel.FLIP_Y])?.let { flip -> + // CMO3: CRotationDeformerForm attribute isReflectY. + form.isReflectY = flip + editor.ensurePresentAttr(form, "CRotationDeformerForm", "isReflectY") + } + scalarOf(channels[FormChannel.OPACITY])?.let { opacity -> + form.opacity = opacity + editor.ensureChildSlot(form, "ACDeformerForm", "opacity", "multiplyColor") + } + colorOf(channels[FormChannel.MULTIPLY_COLOR])?.let { color -> + writeFormColor(form, "ACDeformerForm", "multiplyColor", "screenColor", form.multiplyColor, { form.multiplyColor = it }, color, ColorRgb.MultiplyIdentity) + } + colorOf(channels[FormChannel.SCREEN_COLOR])?.let { color -> + writeFormColor(form, "ACDeformerForm", "screenColor", "coordType", form.screenColor, { form.screenColor = it }, color, ColorRgb.ScreenIdentity) + } + return form + } + + val gridForms = ArrayList(bundle.cells.size) + if (rebuildGrid) { + for (cell in bundle.cells) { + gridForms.add(writeRotationForm(existingForms[valueKey(cell.values)] as? CRotationDeformerForm, cell.geometry as? RotationPivotForm, cell.channels)) + } + if (!writeGridWeb(source, subject, source.keyformGridSource, { source.keyformGridSource = it }, bundle, gridForms)) { + return + } + } else { + val gridGuids = gridFormGuids(source.keyformGridSource) + Cmo3Import.elementsOf(source.keyforms).filterIsInstance() + .filterTo(gridForms) { form -> Cmo3Import.uuidOf(form.guid) in gridGuids } + } + val morphForms = + if (rebuildMorphs) { + rebuildMorphTargets(source, subject, source.keyformMorphTargetSet, { source.keyformMorphTargetSet = it }, source.keyforms, editedRotation.blendShapes) { existing, payload: RotationForm -> + writeRotationForm( + existing as? CRotationDeformerForm, + RotationPivotForm(payload.originX, payload.originY, payload.angle, payload.scale), + mapOf( + FormChannel.OPACITY to ChannelValue.Scalar(payload.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(payload.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(payload.screenColor), + FormChannel.FLIP_X to ChannelValue.Flag(payload.flipX), + FormChannel.FLIP_Y to ChannelValue.Flag(payload.flipY), + ), + ) + } ?: return + } else { + existingMorphForms(source.keyformMorphTargetSet, source.keyforms) + } + writePool(source, "CRotationDeformerSource", "keyforms", "handleLengthOnCanvas", source.keyforms, gridForms, morphForms) { + source.keyforms = it + } + } + + /** Lowers a part's channel tracks (the CPartForm grid). */ + fun lowerPart(source: CPartSource, editedPart: Part) { + val subject = editedPart.id.raw + val isPre53 = source.colorComposition == null + val statics = + mapOf( + FormChannel.DRAW_ORDER to ChannelValue.Scalar(editedPart.drawOrder.toFloat()), + FormChannel.OPACITY to ChannelValue.Scalar(editedPart.composite.opacity), + FormChannel.MULTIPLY_COLOR to ChannelValue.Color(editedPart.composite.multiplyColor), + FormChannel.SCREEN_COLOR to ChannelValue.Color(editedPart.composite.screenColor), + ) + val bundle = + buildBundle(ExportEntityCategory.Part, subject, null as KeyformGrid?, UnitInterpolator, editedPart.channelGrids, statics, requireGeometry = false) + ?: return + if (!drawOrdersAreIntegral(bundle)) { + unsupported(ExportEntityCategory.Part, subject, ExportNoticeReason.FractionalDrawOrderNotStorable) + return + } + if (bundle.axes.isEmpty()) { + // No tracks: the part keeps its existing (axis-less) grid; statics are written by the + // composite/draw-order lowerings, not here. + return + } + val existingForms = existingFormsByValues(source.keyformGridSource, source.keyforms) + val template = templateForm(source.keyforms, index.userPartSources.map { it.keyforms }) + val gridForms = ArrayList(bundle.cells.size) + for (cell in bundle.cells) { + val existing = existingForms[valueKey(cell.values)] as? CPartForm + val form = + existing + ?: CPartForm().apply { + guid = freshGuidLike(template?.guid as? Guid) + isAnimatedForm = template?.isAnimatedForm ?: false + isLocalAnimatedForm = template?.isLocalAnimatedForm ?: false + _source = source + // CMO3: ACForm field notes - a non-null String in the editor's model (its + // setter rejects null); every corpus form writes "" when unannotated. + notes = template?.notes ?: "" + // CMO3: CPartForm multiply/screen colors - a modern-era part form carries all + // of drawOrder/opacity/multiplyColor/screenColor, and CPartForm.deserialize + // dereferences the colors unconditionally (a form with drawOrder + opacity but + // no colors NPEs at load). Corpus signatures are all-five or the pre-5.3 + // drawOrder-only shape, never the partial middle; the channel lowering + // overwrites these when a color channel exists. + multiplyColor = Cmo3SkeletonBuilder.identityMultiplyColor() + screenColor = Cmo3SkeletonBuilder.identityScreenColor() + } + scalarOf(cell.channels[FormChannel.DRAW_ORDER])?.let { drawOrder -> + // CMO3: CPartForm field drawOrder. + form.drawOrder = drawOrder.toInt() + editor.ensureChildSlot(form, "CPartForm", "drawOrder", "opacity") + } + scalarOf(cell.channels[FormChannel.OPACITY])?.let { opacity -> + // CMO3: CPartForm field opacity - a pre-5.3 part's unset 0f means opaque, so an + // opaque value on a pre-5.3 form is left as stored rather than authored anew. + if (!(isPre53 && opacity == 1f && existing != null)) { + form.opacity = opacity + editor.ensureChildSlot(form, "CPartForm", "opacity", "multiplyColor") + } + } + colorOf(cell.channels[FormChannel.MULTIPLY_COLOR])?.let { color -> + writeFormColor(form, "CPartForm", "multiplyColor", "screenColor", form.multiplyColor, { form.multiplyColor = it }, color, ColorRgb.MultiplyIdentity) + } + colorOf(cell.channels[FormChannel.SCREEN_COLOR])?.let { color -> + writeFormColor(form, "CPartForm", "screenColor", null, form.screenColor, { form.screenColor = it }, color, ColorRgb.ScreenIdentity) + } + gridForms.add(form) + } + if (!writeGridWeb(source, subject, source.keyformGridSource, { source.keyformGridSource = it }, bundle, gridForms)) { + return + } + writePool(source, "CPartSource", "keyforms", "enableDrawOrderGroup", source.keyforms, gridForms, emptyList()) { + source.keyforms = it + } + } + + /** + * Writes a part's composite statics (opacity / colors) into every existing CPartForm - the home + * CMO3 gives them when the part has no composite channel tracks. A pre-5.3 form's unset 0f + * opacity means opaque, so an opaque value leaves the stored raw untouched. + * + * @param CPartSource source The part's graph source. + * @param Part editedPart The edited part. + */ + fun writePartCompositeStatics(source: CPartSource, editedPart: Part) { + val isPre53 = source.colorComposition == null + for (form in Cmo3Import.elementsOf(source.keyforms).filterIsInstance()) { + val opacity = editedPart.composite.opacity + if (!(isPre53 && opacity == 1f)) { + // CMO3: CPartForm field opacity. + form.opacity = opacity + editor.ensureChildSlot(form, "CPartForm", "opacity", "multiplyColor") + } + writeFormColor(form, "CPartForm", "multiplyColor", "screenColor", form.multiplyColor, { form.multiplyColor = it }, editedPart.composite.multiplyColor, ColorRgb.MultiplyIdentity) + writeFormColor(form, "CPartForm", "screenColor", null, form.screenColor, { form.screenColor = it }, editedPart.composite.screenColor, ColorRgb.ScreenIdentity) + } + } + + /** Lowers a glue's intensity track (the CGlueForm grid) and its static intensity. */ + fun lowerGlue(source: CGlueSource, editedGlue: Glue) { + val subject = "${editedGlue.meshA.raw}+${editedGlue.meshB.raw}" + val statics = mapOf(FormChannel.GLUE_INTENSITY to ChannelValue.Scalar(editedGlue.intensity)) + val bundle = + buildBundle(ExportEntityCategory.Glue, subject, null as KeyformGrid?, UnitInterpolator, editedGlue.channelGrids, statics, requireGeometry = false) + ?: return + if (bundle.axes.isEmpty() && bundle.cells.isEmpty()) { + // No intensity track: write the static into whatever forms exist (an unkeyed glue welds + // fully, so a non-1 static without forms has no CMO3 home) - never clear a glue's grid. + val forms = Cmo3Import.elementsOf(source.keyforms).filterIsInstance() + if (forms.isEmpty() && editedGlue.intensity != 1f) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.StaticGlueIntensityWithoutKeyforms) + return + } + for (form in forms) { + form.intensity = editedGlue.intensity + editor.ensureChildSlot(form, "CGlueForm", "intensity") + } + return + } + val existingForms = existingFormsByValues(source.keyformGridSource, source.keyforms) + val template = templateForm(source.keyforms, index.glueSources.map { it.keyforms }) + val gridForms = ArrayList(bundle.cells.size) + for (cell in bundle.cells) { + val form = + existingForms[valueKey(cell.values)] as? CGlueForm + ?: CGlueForm().apply { + guid = freshGuidLike(template?.guid as? Guid) + isAnimatedForm = template?.isAnimatedForm ?: false + isLocalAnimatedForm = template?.isLocalAnimatedForm ?: false + _source = source + // CMO3: ACForm field notes - non-null in the editor's model. + notes = template?.notes ?: "" + } + scalarOf(cell.channels[FormChannel.GLUE_INTENSITY])?.let { intensity -> + // CMO3: CGlueForm field intensity - the weld strength at this cell. + form.intensity = intensity + editor.ensureChildSlot(form, "CGlueForm", "intensity") + } + gridForms.add(form) + } + if (!writeGridWeb(source, subject, source.keyformGridSource, { source.keyformGridSource = it }, bundle, gridForms)) { + return + } + writePool(source, "CGlueSource", "keyforms", "targetArtMeshA_guid", source.keyforms, gridForms, emptyList()) { + source.keyforms = it + } + } + + /** The guids of the forms the current grid's cells reference. */ + private fun gridFormGuids(gridSourceField: Any?): Set { + val gridSource = gridSourceField as? KeyformGridSource ?: return emptySet() + return Cmo3Import.elementsOf(gridSource.keyformsOnGrid).filterIsInstance() + .mapNotNull { cell -> Cmo3Import.uuidOf(cell.keyformGuid) } + .toSet() + } + + /** The morph-target form objects the current morph set references, for pool assembly. */ + private fun existingMorphForms(morphSetField: Any?, formsField: Any?): List { + val set = morphSetField as? KeyFormMorphTargetSet ?: return emptyList() + val formByUuid = + Cmo3Import.elementsOf(formsField).filterIsInstance() + .associateBy { form -> Cmo3Import.uuidOf(form.guid) } + return Cmo3Import.elementsOf(set._morphTargets).filterIsInstance() + .mapNotNull { record -> formByUuid[Cmo3Import.uuidOf(record.keyformGuid)] } + } + + /** + * Rebuilds an owner's morph-target set from the edited blend-shape bindings, reusing records + * and forms matched by (parameter, key value). The inserted neutral key (null form at value 0) + * is dropped again - CMO3 stores no record for it. + * + * @param Any ownerSource The source object owning the morph target set. + * @param String subject The owner's id for notices. + * @param Any? currentSet The current keyformMorphTargetSet, or null when absent. + * @param Function assignSet Assigns a freshly created morph target set. + * @param Any? formsField The owner's keyforms pool, for resolving forms already on disk. + * @param List bindings The edited blend-shape bindings to rebuild from. + * @param Function writeForm Writes or creates the form for one binding's payload. + * @return List? The morph form objects for the pool, or null when a parameter is unresolvable. + */ + private fun rebuildMorphTargets( + ownerSource: Any, + subject: String, + currentSet: Any?, + assignSet: (Any?) -> Unit, + formsField: Any?, + bindings: List>, + writeForm: (existing: Any?, payload: TForm) -> ACForm, + ): List? { + val set = currentSet as? KeyFormMorphTargetSet + if (bindings.isEmpty()) { + if (set != null) { + // CMO3: KeyFormMorphTargetSet field _morphTargets / MorphTargetBlendWeightConstraintSet + // field _constraints - carray_list in every corpus model. + writeCollection(set, "KeyFormMorphTargetSet", "_morphTargets", "blendWeightConstraintSet", set._morphTargets, emptyList(), { CArrayList() }) { + set._morphTargets = it + } + (set.blendWeightConstraintSet as? MorphTargetBlendWeightConstraintSet)?.let { constraintSet -> + writeCollection(constraintSet, "MorphTargetBlendWeightConstraintSet", "_constraints", null, constraintSet._constraints, emptyList(), { CArrayList() }) { + constraintSet._constraints = it + } + } + } + return emptyList() + } + val targetSet = + set + ?: KeyFormMorphTargetSet().also { + it.blendWeightConstraintSet = MorphTargetBlendWeightConstraintSet().apply { _constraints = CArrayList() } + assignSet(it) + editor.ensureChildSlot(ownerSource, "ACParameterControllableSource", "keyformMorphTargetSet", "_extensions") + } + val formByUuid = + Cmo3Import.elementsOf(formsField).filterIsInstance() + .associateBy { form -> Cmo3Import.uuidOf(form.guid) } + val existingRecords = + Cmo3Import.elementsOf(targetSet._morphTargets).filterIsInstance() + .associateBy { record -> "${Cmo3Import.uuidOf(record.parameterGuid)}@${record.keyValue.toRawBits()}" } + val records = ArrayList() + val morphForms = ArrayList() + val constraints = ArrayList() + for (binding in bindings) { + val parameterSource = index.parameterByIdStr[binding.parameterId.raw] + if (parameterSource == null) { + unsupported(ExportEntityCategory.Keyform, subject, ExportNoticeReason.BlendShapeParameterHasNoSource(binding.parameterId.raw)) + return null + } + val parameterUuid = Cmo3Import.uuidOf(parameterSource.guid) + for (keyIndex in binding.keys.indices) { + val payload = binding.forms[keyIndex] ?: continue + val keyValue = binding.keys[keyIndex] + val existingRecord = existingRecords["$parameterUuid@${keyValue.toRawBits()}"] + val existingForm = existingRecord?.let { record -> formByUuid[Cmo3Import.uuidOf(record.keyformGuid)] } + val form = writeForm(existingForm, payload) + morphForms.add(form) + val record = + existingRecord + ?: KeyFormMorphTarget().apply { + parameterGuid = parameterSource.guid + owner = ownerSource + // CMO3: KeyFormMorphTarget field editBaseParameterMap - corpus records + // carry the wrapper with a null baseParameterMap, never a bare null. + editBaseParameterMap = + org.umamo.format.cmo3.model.gen.MorphTargetEditBaseParameterMap() + } + record.keyValue = keyValue + record.keyformGuid = form.guid + records.add(record) + } + for (limit in binding.limits) { + val constraintSource = index.parameterByIdStr[limit.parameterId.raw] ?: continue + for (point in limit.points) { + constraints.add( + MorphTargetBlendWeightConstraint().apply { + morphTargetParameterGuid = parameterSource.guid + constraintParameterGuid = constraintSource.guid + constraintParameterValue = point.value + blendWeight = point.weight + }, + ) + } + } + } + // CMO3: KeyFormMorphTargetSet field _morphTargets / MorphTargetBlendWeightConstraintSet + // field _constraints - carray_list in every corpus model. + writeCollection(targetSet, "KeyFormMorphTargetSet", "_morphTargets", "blendWeightConstraintSet", targetSet._morphTargets, records, { CArrayList() }) { + targetSet._morphTargets = it + } + val constraintSet = + targetSet.blendWeightConstraintSet as? MorphTargetBlendWeightConstraintSet + ?: MorphTargetBlendWeightConstraintSet().also { + targetSet.blendWeightConstraintSet = it + editor.ensureChildSlot(targetSet, "KeyFormMorphTargetSet", "blendWeightConstraintSet") + } + writeCollection(constraintSet, "MorphTargetBlendWeightConstraintSet", "_constraints", null, constraintSet._constraints, constraints, { CArrayList() }) { + constraintSet._constraints = it + } + return morphForms + } + + /** Writes the owner's keyforms pool: the grid forms in cell order, then the morph forms. */ + private fun writePool( + owner: Any, + ownerTag: String, + property: String, + beforeProperty: String?, + current: Any?, + gridForms: List, + morphForms: List, + assign: (MutableList) -> Unit, + ) { + val gridIdentity = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + gridForms.forEach { gridIdentity.add(it) } + val pool = ArrayList(gridForms.size + morphForms.size) + pool.addAll(gridForms) + for (form in morphForms) { + if (form !in gridIdentity) { + pool.add(form) + gridIdentity.add(form) + } + } + // CMO3: ACParameterControllableSource field keyforms - carray_list in every corpus model; + // the editor's deserializers cast it to CArrayList, so array_list fails its load. + writeCollection(owner, ownerTag, property, beforeProperty, current, pool, { CArrayList() }, assign) + } + + /** The no-op interpolator for channel-only owners (parts, glues) whose bundles carry no geometry. */ + private object UnitInterpolator : FormInterpolator { + override fun interpolate(lower: Unit, upper: Unit, fraction: Float): Unit = Unit + + override fun isExactlyEqual(left: Unit, right: Unit): Boolean = true + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3PropertyLowering.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3PropertyLowering.kt new file mode 100644 index 0000000..e2fcc4b --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3PropertyLowering.kt @@ -0,0 +1,1291 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3GraphEditor +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.gen.ACDeformerSource +import org.umamo.format.cmo3.model.gen.ACParameterControllableSource +import org.umamo.format.cmo3.model.gen.CArtMeshForm +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CImageCanvas +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CParameterGroup +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CPartForm +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CRotationDeformerSource +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.CWarpDeformerSource +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.interop.AtlasTileField +import org.umamo.interop.DeformerField +import org.umamo.interop.DocumentField +import org.umamo.interop.DrawableField +import org.umamo.interop.EntityDiff +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.GlueDiff +import org.umamo.interop.GlueField +import org.umamo.interop.ParameterField +import org.umamo.interop.ParameterGroupField +import org.umamo.interop.PartField +import org.umamo.interop.alphaCompositionOf +import org.umamo.interop.cmo3TargetVersionNo +import org.umamo.interop.colorCompositionOf +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.composeAffine +import org.umamo.runtime.model.inversePlacementAffine +import org.umamo.runtime.model.isOriginAtCanvasCenter +import org.umamo.runtime.model.lineageRoot +import org.umamo.runtime.model.storedToArtAffineForTile + +/** + * The flat-property half of the CMO3 export reconcile: every diffed field with a direct CMO3 field + * to write - names, flags, blend modes, masks, reference reparents, tree orders, parameter ranges + * and links, and the canvas. Channel-backed values (statics, keyforms, geometry) dispatch to the + * shared [Cmo3KeyformLowering]; mesh topology and glue re-binding dispatch to [Cmo3StructureLowering]. + * Entity creation/deletion runs earlier, in Cmo3Export.apply's structural pass. A Created diff + * that still reaches this class means that pass already tried to synthesize the entity, failed, + * and already reported why - this class has nothing to lower for it and skips it silently. + * Deleted diffs never arrive: the structural pass consumes every deletion and Cmo3Export strips + * them from the diff it forwards. + * + * Every assignment that can target an element or attribute the source document omitted pairs with + * the graph editor's ensure call - the writer replays recorded slots, so a bare assignment on a + * read object would otherwise be dropped silently. Anchors follow the generated model's declared + * field order (the editor's document order), so an ensured element lands where the editor writes it. + */ +internal class Cmo3PropertyLowering( + private val target: Cmo3Model, + private val index: Cmo3GraphIndex, + private val editor: Cmo3GraphEditor, + private val baseline: PuppetModel, + private val edited: PuppetModel, + private val notices: MutableList, + // The document's texture frames, taken from the graph before the export changed it. + private val textureFrames: Cmo3TextureFrames, + // True when the caller replaced the stored page images with pages recomposed for the edited + // placements (Cmo3Export's same-count patch); the stale-page notices below are then false and stay + // quiet. Defaults false so every other construction keeps the honest warning. + private val pagesRecomposed: Boolean = false, + // The lineage roots whose layer web the atlas-web reconcile minted or rewrote to the edited art; + // their metadata (name, size, binding) is reconciled there, so no notice is owed for it. + private val reconciledTileIds: Set = emptySet(), +) { + private val editedParameterById = edited.parameters.associateBy(Parameter::id) + private val editedPartById = edited.parts.associateBy(Part::id) + private val editedDeformerById = edited.deformers.associateBy(Deformer::id) + private val editedDrawableById = edited.drawables.associateBy(Drawable::id) + private val baselinePartById = baseline.parts.associateBy(Part::id) + private val baselineDeformerById = baseline.deformers.associateBy(Deformer::id) + private val baselineDrawableById = baseline.drawables.associateBy(Drawable::id) + + /** Drawables whose base geometry/UVs diverged from the imported weld - one aggregated notice. */ + private val weldDivergedDrawableNames = ArrayList() + + /** The keyform re-bundling engine, shared by the drawable/deformer/part/glue dispatches. */ + private val keyforms = Cmo3KeyformLowering(index, editor, baseline, notices) + + /** The structural engine, for topology rewrites and glue re-binding on Changed entities. */ + private val structure = Cmo3StructureLowering(index.modelSource, index, editor, edited, notices, textureFrames) + + private fun unsupported( + category: ExportEntityCategory, + subject: String?, + reason: ExportNoticeReason, + ) { + notices.add(ExportNotice.UnsupportedChange(category, subject, reason)) + } + + fun lowerParameters(diffs: List>) { + for (diff in diffs) { + when (diff) { + // Structural synthesis already failed and reported why; see the class docblock. + is EntityDiff.Created -> Unit + // Deletions are consumed by the structural pass and stripped from the forwarded diff. + is EntityDiff.Deleted -> Unit + is EntityDiff.Changed -> { + val source = index.parameterByIdStr[diff.id.raw] + val editedParameter = editedParameterById[diff.id] + if (source == null || editedParameter == null) { + unsupported(ExportEntityCategory.Parameter, diff.id.raw, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + for (field in diff.fields) { + when (field) { + ParameterField.NAME -> { + // CMO3: CParameterSource field name - the localizable display label. + source.name = editedParameter.name + editor.ensureChildSlot(source, "CParameterSource", "name", "description") + } + ParameterField.RANGE -> { + // CMO3: CParameterSource fields minValue / maxValue / defaultValue. + source.minValue = editedParameter.min + source.maxValue = editedParameter.max + source.defaultValue = editedParameter.default + editor.ensureChildSlot(source, "CParameterSource", "minValue", "maxValue") + editor.ensureChildSlot(source, "CParameterSource", "maxValue", "defaultValue") + editor.ensureChildSlot(source, "CParameterSource", "defaultValue", "isRepeat") + } + ParameterField.KIND -> + unsupported(ExportEntityCategory.Parameter, diff.id.raw, ExportNoticeReason.ParameterKindChangeNotLowered) + } + } + } + } + } + } + + fun lowerParameterGroups(diffs: List>) { + for (diff in diffs) { + when (diff) { + // Structural synthesis already failed and reported why; see the class docblock. + is EntityDiff.Created -> Unit + // Deletions are consumed by the structural pass and stripped from the forwarded diff. + is EntityDiff.Deleted -> Unit + is EntityDiff.Changed -> { + val group = index.groupByIdStr[diff.id.raw] + val editedGroup = findEditedGroup(diff.id) + if (group == null || editedGroup == null) { + unsupported(ExportEntityCategory.ParameterGroup, diff.id.raw, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + for (field in diff.fields) { + when (field) { + ParameterGroupField.NAME -> { + // CMO3: CParameterGroup field name - the folder label (not unique; identity is the id). + group.name = editedGroup.name + editor.ensureChildSlot(group, "CParameterGroup", "name", "description") + } + ParameterGroupField.INITIALLY_OPEN -> { + // CMO3: CParameterGroup field folderIsOpened - the saved expand/collapse state. + group.folderIsOpened = editedGroup.initiallyOpen + editor.ensureChildSlot(group, "CParameterGroup", "folderIsOpened", "guid") + } + ParameterGroupField.CHILDREN -> rebuildGroupChildren(group, editedGroup.children) + } + } + } + } + } + } + + fun lowerParts(diffs: List>) { + for (diff in diffs) { + when (diff) { + // Structural synthesis already failed and reported why; see the class docblock. + is EntityDiff.Created -> Unit + // Deletions are consumed by the structural pass and stripped from the forwarded diff. + is EntityDiff.Deleted -> Unit + is EntityDiff.Changed -> { + val source = index.partByIdStr[diff.id.raw] + val editedPart = editedPartById[diff.id] + // A synthesized shell has no baseline; a default part stands in so the composite + // lowering diffs the edited state against defaults (the shell's own values). + val baselinePart = baselinePartById[diff.id] ?: Part(id = diff.id, name = "", children = emptyList()) + if (source == null || editedPart == null) { + unsupported(ExportEntityCategory.Part, diff.id.raw, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + for (field in diff.fields) { + when (field) { + PartField.NAME -> lowerLocalName(source, editedPart.name) + PartField.VISIBLE -> lowerIsVisible(source, editedPart.isVisible) + PartField.SELECTABLE -> lowerIsLocked(source, editedPart.isSelectable) + PartField.SKETCH -> { + // CMO3: CPartSource field isSketch - the "Guide Image" reference-only flag. + source.isSketch = editedPart.isSketch + editor.ensureChildSlot(source, "CPartSource", "isSketch", "partsEditColor") + } + PartField.GROUP_MODE -> { + // CMO3: CPartSource fields useOffscreen / enableDrawOrderGroup - Cubism's two + // entangled checkboxes; offscreen forces grouping on, so Isolated writes both. + source.useOffscreen = editedPart.groupMode is PartGroupMode.Isolated + source.enableDrawOrderGroup = editedPart.groupMode !is PartGroupMode.PassThrough + editor.ensureChildSlot(source, "CPartSource", "useOffscreen", "clipGuidList") + editor.ensureChildSlot(source, "CPartSource", "enableDrawOrderGroup", "defaultOrder_forEditor") + } + PartField.DRAW_ORDER -> lowerPartDrawOrder(source, editedPart) + PartField.CHILDREN -> rebuildOrgChildren(source, editedPart.children) + PartField.CHANNELS -> keyforms.lowerPart(source, editedPart) + PartField.COMPOSITE -> lowerPartComposite(source, diff.id, baselinePart, editedPart) + } + } + } + } + } + } + + fun lowerDeformers(diffs: List>) { + for (diff in diffs) { + when (diff) { + // Structural synthesis already failed and reported why; see the class docblock. + is EntityDiff.Created -> Unit + // Deletions are consumed by the structural pass and stripped from the forwarded diff. + is EntityDiff.Deleted -> Unit + is EntityDiff.Changed -> { + val source = index.deformerByIdStr[diff.id.raw] + val editedDeformer = editedDeformerById[diff.id] + if (source == null || editedDeformer == null) { + unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + for (field in diff.fields) { + when (field) { + DeformerField.KIND -> unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.DeformerKindChangeNotLowered) + DeformerField.NAME -> lowerLocalName(source, editedDeformer.name) + DeformerField.SELECTABLE -> lowerIsLocked(source, editedDeformer.isSelectable) + DeformerField.PARENT -> { + // CMO3: ACDeformerSource field targetDeformerGuid - the transform-tree parent, + // or the editor's fixed ROOT sentinel at the tree root (official deformers + // never write null here). Reusing the parent's own guid instance keeps the + // shared xs.ref identity the editor writes. + source.targetDeformerGuid = + editedDeformer.parent?.let { index.deformerByIdStr[it.raw]?.guid } + ?: Cmo3SkeletonBuilder.rootDeformerSentinel() + editor.ensureChildSlot(source, "ACDeformerSource", "targetDeformerGuid") + } + DeformerField.PART -> lowerDeformerPart(source, diff.id, editedDeformer.partId) + DeformerField.QUAD_TRANSFORM -> { + val warpSource = source as? CWarpDeformerSource + if (warpSource == null) { + unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.DeformerEditNeedsWarpSource) + } else { + // CMO3: CWarpDeformerSource field isQuadTransform - the FFD interpolation mode. + warpSource.isQuadTransform = (editedDeformer as Deformer.Warp).isQuadTransform + editor.ensureChildSlot(warpSource, "CWarpDeformerSource", "isQuadTransform", "keyforms") + } + } + DeformerField.BASE_ANGLE -> { + val rotationSource = source as? CRotationDeformerSource + if (rotationSource == null) { + unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.DeformerEditNeedsRotationSource) + } else { + // CMO3: CRotationDeformerSource field baseAngle - the static editor reference angle. + rotationSource.baseAngle = (editedDeformer as Deformer.Rotation).baseAngle + editor.ensureChildSlot(rotationSource, "CRotationDeformerSource", "baseAngle") + } + } + DeformerField.LATTICE -> { + val warpSource = source as? CWarpDeformerSource + if (warpSource != null && editedDeformer is Deformer.Warp) { + // CMO3: CWarpDeformerSource fields col / row - the FFD lattice + // dimensions; the resized control-point forms ride the grid rebuild. + warpSource.col = editedDeformer.columns + warpSource.row = editedDeformer.rows + editor.ensureChildSlot(warpSource, "CWarpDeformerSource", "col", "row") + editor.ensureChildSlot(warpSource, "CWarpDeformerSource", "row", "isQuadTransform") + } else { + unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.DeformerEditNeedsWarpSource) + } + } + // Handled once per deformer by the keyform rebuild below. + DeformerField.GEOMETRY, + DeformerField.CHANNELS, + DeformerField.STATICS, + DeformerField.BLEND_SHAPES, + -> Unit + } + } + val rebuildGrid = + DeformerField.GEOMETRY in diff.fields || + DeformerField.CHANNELS in diff.fields || + DeformerField.STATICS in diff.fields || + DeformerField.LATTICE in diff.fields + val rebuildMorphs = DeformerField.BLEND_SHAPES in diff.fields + if (rebuildGrid || rebuildMorphs) { + when (editedDeformer) { + is Deformer.Warp -> { + val warpSource = source as? CWarpDeformerSource + if (warpSource == null) { + unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.DeformerEditNeedsWarpSource) + } else { + keyforms.lowerWarp(warpSource, editedDeformer, rebuildGrid, rebuildMorphs) + } + } + + is Deformer.Rotation -> { + val rotationSource = source as? CRotationDeformerSource + if (rotationSource == null) { + unsupported(ExportEntityCategory.Deformer, diff.id.raw, ExportNoticeReason.DeformerEditNeedsRotationSource) + } else { + keyforms.lowerRotation(rotationSource, editedDeformer, rebuildGrid, rebuildMorphs) + } + } + } + } + } + } + } + } + + fun lowerDrawables(diffs: List>) { + for (diff in diffs) { + when (diff) { + // Structural synthesis already failed and reported why; see the class docblock. + is EntityDiff.Created -> Unit + // Deletions are consumed by the structural pass and stripped from the forwarded diff. + is EntityDiff.Deleted -> Unit + is EntityDiff.Changed -> { + val source = index.drawableByIdStr[diff.id.raw] + val editedDrawable = editedDrawableById[diff.id] + if (source == null || editedDrawable == null) { + unsupported(ExportEntityCategory.Drawable, diff.id.raw, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + for (field in diff.fields) { + when (field) { + DrawableField.NAME -> lowerLocalName(source, editedDrawable.name) + DrawableField.VISIBLE -> lowerIsVisible(source, editedDrawable.isVisible) + DrawableField.SELECTABLE -> lowerIsLocked(source, editedDrawable.isSelectable) + DrawableField.PARENT_DEFORMER -> { + // CMO3: ACDrawableSource field targetDeformerGuid - the deforming parent, or + // the editor's fixed root-deformer sentinel when the drawable sits at the + // deformer-tree root. Never null: the editor's setter is non-null and NPEs + // on absence, and no corpus drawable nulls it in any era. + source.targetDeformerGuid = + editedDrawable.parentDeformerId?.let { index.deformerByIdStr[it.raw]?.guid } + ?: Cmo3SkeletonBuilder.rootDeformerSentinel() + editor.ensureChildSlot(source, "ACDrawableSource", "targetDeformerGuid", "clipGuidList") + } + DrawableField.BLEND_MODE -> { + // CMO3: CArtMeshSource field colorComposition. + source.colorComposition = colorCompositionOf(editedDrawable.blendMode) + editor.ensureChildSlot(source, "CArtMeshSource", "colorComposition", "culling") + } + DrawableField.ALPHA_BLEND_MODE -> { + // CMO3: CArtMeshSource field alphaComposition (absent pre-5.3). + source.alphaComposition = alphaCompositionOf(editedDrawable.alphaBlendMode) + editor.ensureChildSlot(source, "CArtMeshSource", "alphaComposition") + } + DrawableField.MASKED_BY -> { + // CMO3: ACDrawableSource field clipGuidList - always drawable GUIDs. + writeListField( + owner = source, + tag = "ACDrawableSource", + property = "clipGuidList", + beforeProperty = "invertClippingMask", + current = source.clipGuidList, + newElements = editedDrawable.maskedBy.mapNotNull { index.drawableByIdStr[it.raw]?.guid }, + assign = { list -> source.clipGuidList = list }, + ) + } + DrawableField.INVERT_MASK -> { + // CMO3: ACDrawableSource field invertClippingMask. + source.invertClippingMask = editedDrawable.invertMask + editor.ensureChildSlot(source, "ACDrawableSource", "invertClippingMask", "icon32") + } + DrawableField.CULLING -> { + // CMO3: CArtMeshSource field culling - back-face culling. + source.culling = editedDrawable.culling + editor.ensureChildSlot(source, "CArtMeshSource", "culling", "textureState") + } + DrawableField.TEXTURE_SOURCE -> + unsupported(ExportEntityCategory.Drawable, diff.id.raw, ExportNoticeReason.TextureSourceRebindingIsEditorOnly) + DrawableField.ATLAS_TILE -> + unsupported(ExportEntityCategory.Drawable, diff.id.raw, ExportNoticeReason.AtlasTileRebindingNotLowered) + DrawableField.MESH_TOPOLOGY -> { + // The weld notice means "the base left the IMPORTED weld" - a drawable + // with no baseline was never welded, so synthesis stays notice-free. + val hadBaseline = baselineDrawableById[diff.id] != null + if (structure.lowerMeshTopology(source, editedDrawable) && hadBaseline) { + weldDivergedDrawableNames.add(editedDrawable.name) + } + } + DrawableField.MESH_POSITIONS -> { + // A base move combined with keyform-delta edits routes through the grid + // rebuild below, which writes the base and the absolutes together. + if (DrawableField.GEOMETRY !in diff.fields) { + lowerMeshPositions(source, diff.id, editedDrawable) + } + if (baselineDrawableById[diff.id] != null) { + weldDivergedDrawableNames.add(editedDrawable.name) + } + } + DrawableField.MESH_UVS -> { + lowerMeshUvs(source, diff.id, editedDrawable) + if (baselineDrawableById[diff.id] != null) { + weldDivergedDrawableNames.add(editedDrawable.name) + } + } + // Handled once per drawable by the keyform rebuild below. + DrawableField.GEOMETRY, + DrawableField.CHANNELS, + DrawableField.STATICS, + DrawableField.BLEND_SHAPES, + -> Unit + } + } + val rebuildGrid = + DrawableField.GEOMETRY in diff.fields || + DrawableField.CHANNELS in diff.fields || + DrawableField.STATICS in diff.fields || + DrawableField.MESH_TOPOLOGY in diff.fields + val rebuildMorphs = DrawableField.BLEND_SHAPES in diff.fields + if (rebuildGrid || rebuildMorphs) { + keyforms.lowerDrawable( + source = source, + editedDrawable = editedDrawable, + rebuildGrid = rebuildGrid, + rebuildMorphs = rebuildMorphs, + alsoWriteBase = DrawableField.MESH_POSITIONS in diff.fields && DrawableField.GEOMETRY in diff.fields, + ) + } + } + } + } + } + + /** + * Flushes the aggregated weld-divergence notice. Call after lowerDrawables: exported geometry + * and UVs are written as authored, a deliberate choice, and this tells the user which meshes + * Cubism's own mesh-edit / re-atlas operations could re-derive. + */ + fun flushWeldNotice() { + if (weldDivergedDrawableNames.isNotEmpty()) { + notices.add(ExportNotice.WeldDivergence(weldDivergedDrawableNames.toList())) + } + } + + /** + * Lowers an edited base mesh: rewrites CArtMeshSource.positions, mirrors the editable mesh's + * point array, and rebases every CArtMeshForm's ABSOLUTE positions onto the new base - keeping + * untouched vertices bit-identical by recomputing each delta from the stored values rather than + * re-deriving (a-b)+b through IEEE rounding. + * + * @param CArtMeshSource source The drawable's graph source. + * @param DrawableId drawableId The drawable's id (for notices). + * @param Drawable editedDrawable The edited drawable. + */ + private fun lowerMeshPositions(source: CArtMeshSource, drawableId: DrawableId, editedDrawable: Drawable) { + val origBase = source.positions as? FloatArray + val newBase = editedDrawable.mesh?.positions + if (origBase == null || newBase == null || origBase.size != newBase.size) { + unsupported(ExportEntityCategory.Drawable, drawableId.raw, ExportNoticeReason.BaseGeometryVertexCountMismatch) + return + } + // Rebase the forms BEFORE swapping the base: CMO3 stores absolutes, so every form follows + // the base move (grid cells and morph-target forms live in the same pool and rebase alike). + for (form in Cmo3Import.elementsOf(source.keyforms).filterIsInstance()) { + val origAbsolute = form.positions as? FloatArray ?: continue + if (origAbsolute.size != newBase.size) { + continue + } + val rebased = + FloatArray(origAbsolute.size) { component -> + if (newBase[component].toRawBits() == origBase[component].toRawBits()) { + origAbsolute[component] + } else { + newBase[component] + (origAbsolute[component] - origBase[component]) + } + } + // CMO3: CArtMeshForm field positions - absolute vertex positions. + form.positions = rebased + editor.ensureChildSlot(form, "CArtMeshForm", "positions") + } + // CMO3: CArtMeshSource field positions - the rest/default geometry. + source.positions = newBase.copyOf() + editor.ensureChildSlot(source, "CArtMeshSource", "positions", "uvs") + // CMO3: GEditableMesh2 field point mirrors the positions as its OWN float-array (the corpus + // never shares the two array objects, and a shared object would hoist as an xs.ref). + val editableMesh = Cmo3Import.editableMeshOf(source) + val pointArray = editableMesh?.point as? FloatArray + if (editableMesh != null && (pointArray == null || pointArray.size == newBase.size)) { + editableMesh.point = newBase.copyOf() + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "point", "pointPriority") + } + } + + /** + * Lowers edited UVs into the frame the drawable stores ([Cmo3TextureFrames.storedUvsOf]) - the import's + * remap run backward, off the edited tile's page through its EDITED placement when it has one. + * Unchanged texel pairs keep the stored values so the round trip cannot drift them, but only while the + * tile's placement is the one those values were read under: a moved placement moves every model pair. + * + * @param CArtMeshSource source The drawable's graph source. + * @param DrawableId drawableId The drawable's id (for notices). + * @param Drawable editedDrawable The edited drawable. + */ + private fun lowerMeshUvs(source: CArtMeshSource, drawableId: DrawableId, editedDrawable: Drawable) { + val newUvs = editedDrawable.mesh?.uvs + if (newUvs == null) { + unsupported(ExportEntityCategory.Drawable, drawableId.raw, ExportNoticeReason.NoUvsToReconcile) + return + } + val baselineDrawable = baselineDrawableById[drawableId] + val editedToArt = editedDrawable.atlasTileId?.let { tileId -> edited.atlas.storedToArtAffineForTile(tileId) } + val baselineToArt = baselineDrawable?.atlasTileId?.let { tileId -> baseline.atlas.storedToArtAffineForTile(tileId) } + val placementKept = editedToArt.contentEquals(baselineToArt) + // CMO3: CArtMeshSource field uvs. + source.uvs = + textureFrames.storedUvsOf( + source, + newUvs, + editedToArt, + (source.uvs as? FloatArray).takeIf { placementKept }, + baselineDrawable?.mesh?.uvs.takeIf { placementKept }, + ) + editor.ensureChildSlot(source, "CArtMeshSource", "uvs", "texture") + } + + fun lowerGlues(diffs: List) { + if (diffs.isEmpty()) { + return + } + // A glue has no id: resolve the graph source and the edited glue by ordered mesh pair plus + // ordinal, the same keying the diff used. + val sourcesByPair = + index.glueSources.groupBy { glueSource -> + val meshA = index.drawableIdStrByUuid[Cmo3Import.uuidOf(glueSource.targetArtMeshA_guid)] + val meshB = index.drawableIdStrByUuid[Cmo3Import.uuidOf(glueSource.targetArtMeshB_guid)] + meshA to meshB + } + val editedByPair = edited.glues.groupBy { glue -> glue.meshA.raw to glue.meshB.raw } + for (diff in diffs) { + val subject = "${diff.meshA.raw}+${diff.meshB.raw}" + when (diff) { + // Structural synthesis already failed and reported why; see the class docblock. + is GlueDiff.Created -> Unit + // Deletions are consumed by the structural pass and stripped from the forwarded diff. + is GlueDiff.Deleted -> Unit + is GlueDiff.Changed -> { + val pairKey = diff.meshA.raw to diff.meshB.raw + val glueSource = sourcesByPair[pairKey as Pair]?.getOrNull(diff.ordinal) + val editedGlue = editedByPair[pairKey]?.getOrNull(diff.ordinal) + if (glueSource == null || editedGlue == null) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + if (GlueField.PAIRS in diff.fields) { + structure.lowerGluePairsFor(editedGlue) + } + if (GlueField.CHANNELS in diff.fields || GlueField.INTENSITY in diff.fields) { + keyforms.lowerGlue(glueSource, editedGlue) + } + } + } + } + } + + /** + * Lowers each moved atlas tile onto its packed entry - the packing transform AND the inverse the + * file composes it against. + * + * A model image is UPRIGHT CANVAS-SPACE art, and the format states the invariant as a composition + * (docs/format/CMO3.md §6): `atlasLocalToCanvasTransform` composed with + * `materialLocalToAtlasTransform` reproduces `_materialLocalToCanvasTransform`, a pure translation + * every one of the corpus's model images obeys. A repack moves art on the PAGE, never on the + * CANVAS, so the canvas placement is deliberately left alone and the atlas-to-canvas half is + * recomputed to hold the composition. Writing only the packing transform would break an invariant + * the official editor's own reader depends on. + * + * What this does NOT do is redraw the page. When the caller has not patched the stored page + * images (pagesRecomposed), they still show the art where it used to be, so a moved placement + * takes [ExportNoticeReason.AtlasPageNotRecomposed]; a patched export clears it. + * + * @param List diffs The per-tile diffs. + */ + fun lowerAtlasTiles(diffs: List>) { + if (diffs.isEmpty()) { + return + } + // CMO3: CModelSource field textureManager -> CTextureManager field _textureAtlases. + val textureManager = index.modelSource.textureManager as? CTextureManager + if (textureManager == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoTextureManagerToReconcile) + return + } + // Indexed fresh here rather than shared with the web reconcile, which runs first and moves + // entries between atlases. The canvas placement it carries is the fixed point every rewritten + // transform pair has to keep composing to (see indexAtlasWeb). + val web = indexAtlasWeb(textureManager) + // Keyed by lineage root: the diff names the baseline's tile, and a reloaded tile (`~`) + // is that tile's art to the graph, so its placement is what the root's entry takes. + val editedTileById = edited.atlas.tiles.associateBy { tile -> tile.id.lineageRoot } + + for (diff in diffs) { + when (diff) { + // The diff compares shared tiles only, because art arrives and leaves with an import + // rather than with an edit - so these arms are unreachable today. They stay defensive + // rather than silent: whoever makes the inventory editable (re-import) lands the lowering + // that serves them, and until then an appearance here is a bug worth reporting. + is EntityDiff.Created, is EntityDiff.Deleted -> + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.AtlasTileMetadataNotReconcilable) + + is EntityDiff.Changed -> { + if (AtlasTileField.METADATA in diff.fields && diff.id.raw !in reconciledTileIds) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.AtlasTileMetadataNotReconcilable) + } + if (AtlasTileField.PLACEMENT !in diff.fields) { + continue + } + val placement = editedTileById[diff.id]?.placement + if (placement == null && pagesRecomposed) { + // A pack-out under the full web reconcile: the entry already left its page, + // which is the whole lowering a null placement takes. + continue + } + val entry = web.siteByTileId[diff.id.raw]?.entry + if (placement == null || entry == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoAtlasEntryToReconcile) + continue + } + val canvasAffine = web.canvasAffineByTileId[diff.id.raw] + if (canvasAffine == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoAtlasEntryToReconcile) + continue + } + lowerAtlasEntry(entry, placement, canvasAffine) + if (!pagesRecomposed) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.AtlasPageNotRecomposed) + } + } + } + } + } + + /** + * Writes one packed entry's transform pair. + * + * @param ModelImageEntry entry The packed entry to move. + * @param AtlasPlacement placement Where the art now sits on its page. + * @param FloatArray canvasAffine Where the art sits on the CANVAS, which does not move. + */ + private fun lowerAtlasEntry(entry: ModelImageEntry, placement: AtlasPlacement, canvasAffine: FloatArray) { + // CMO3: ModelImageEntry field materialLocalToAtlasTransform - written into the entry's EXISTING + // GTransform2 when it has one, so the element keeps its instance. + val transform = (entry.materialLocalToAtlasTransform as? GTransform2) ?: GTransform2() + entry.materialLocalToAtlasTransform = Cmo3ImageChainBuilder.writePacking(transform, placement) + editor.ensureChildSlot(entry, "ModelImageEntry", "materialLocalToAtlasTransform", "atlasLocalToCanvasTransform") + + // CMO3: ModelImageEntry field atlasLocalToCanvasTransform - the other half of the composition. + // + // NOT simply the placement's inverse: the pair must compose to the art's CANVAS placement, + // which does not move when the art is repacked. The full composition canvas-affine after + // placement-inverse serves both corpus shapes: an official file's pure-translation canvas + // placement reduces it to the inverse plus that origin (dropping the origin term would slide + // every model image to the canvas corner), and a converted graph's canvas placement carries + // the original packing's linear part, which a translation-only write would drop. + val canvasTransform = entry.atlasLocalToCanvasTransform as? CAffine + if (canvasTransform == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoAtlasEntryToReconcile) + return + } + val composed = atlasLocalToCanvasFor(canvasAffine, placement) + if (composed == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoAtlasEntryToReconcile) + return + } + canvasTransform.setFromAffineArray(composed) + editor.ensureChildSlot(entry, "ModelImageEntry", "atlasLocalToCanvasTransform", null) + } + + fun lowerDocument(fields: Set) { + // Order and links rewrite the same _sources list; run the shared lowering once. + if (DocumentField.PARAMETER_ORDER in fields || DocumentField.PARAMETER_LINKS in fields) { + lowerParameterOrderAndLinks() + } + for (field in fields) { + when (field) { + // CMO3: CModelSource field targetVersionNo (via the Cmo3Model facade, which also + // records the slot on documents that never carried the element). + DocumentField.RUNTIME_TARGET -> target.setTargetVersionNo(edited.runtimeTarget.cmo3TargetVersionNo()) + DocumentField.CANVAS_SIZE -> lowerCanvasSize() + DocumentField.SOURCE_LAYER_DISPLAY -> lowerSourceLayerDisplay() + DocumentField.SOURCE_FILES -> lowerSourceFiles() + // A page appearing, vanishing, or resizing is a repack's output, and repacking rewrites + // the page IMAGES too. When the caller patched them (pagesRecomposed) the page set IS + // reconciled and nothing is owed; otherwise the per-tile placements still lower and this + // says the page set itself was not. + DocumentField.ATLAS_PAGES -> { + if (!pagesRecomposed) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.AtlasPageNotRecomposed) + } + } + DocumentField.WORLD_ORIGIN -> { + // An origin AT the canvas center survives implicitly (import derives exactly that), + // so only an off-center origin is unrepresentable and worth a notice. + if (!edited.isOriginAtCanvasCenter()) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoAuthoredWorldOrigin) + } + } + DocumentField.PARAMETER_ORDER, DocumentField.PARAMETER_LINKS -> Unit + DocumentField.PARAMETER_TREE -> { + val rootGroup = index.rootParameterGroup + if (rootGroup == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoRootParameterGroup) + } else { + rebuildGroupChildren(rootGroup, edited.parameterTree) + } + } + DocumentField.ROOT_CHILDREN -> { + val rootPart = index.rootPartSource + if (rootPart == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoRootPart) + } else { + rebuildOrgChildren(rootPart, edited.rootChildren) + } + } + } + } + } + + /** CMO3: ACParameterControllableSource field localName - the user-facing display name. */ + private fun lowerLocalName(source: ACParameterControllableSource, name: String) { + source.localName = name + editor.ensureChildSlot(source, "ACParameterControllableSource", "localName", "isVisible") + } + + /** CMO3: ACParameterControllableSource field isVisible - the Parts-panel eyeball. */ + private fun lowerIsVisible(source: ACParameterControllableSource, isVisible: Boolean) { + source.isVisible = isVisible + editor.ensureChildSlot(source, "ACParameterControllableSource", "isVisible", "isLocked") + } + + /** CMO3: ACParameterControllableSource field isLocked (inverted: Cubism lock = not selectable). */ + private fun lowerIsLocked(source: ACParameterControllableSource, isSelectable: Boolean) { + source.isLocked = !isSelectable + editor.ensureChildSlot(source, "ACParameterControllableSource", "isLocked", "parentGuid") + } + + /** + * Lowers a part's static draw order. With no DRAW_ORDER track the value lives in + * defaultOrder_forEditor and every CPartForm cell (import reads the first form), so both are + * written; with a track the static is shadowed by the grid and has no independent CMO3 home. + * + * @param CPartSource source The part's graph source. + * @param Part editedPart The edited part. + */ + private fun lowerPartDrawOrder(source: CPartSource, editedPart: Part) { + val drawOrderTrack = editedPart.channelGrids[FormChannel.DRAW_ORDER] + if (drawOrderTrack != null) { + // Import re-derives the static from the FIRST grid form, so a static that matches the + // track's head cell survives on its own; only a disagreeing static is actually lost. + val headDrawOrder = (drawOrderTrack.cells.firstOrNull()?.form as? ChannelValue.Scalar)?.value?.toInt() + if (headDrawOrder != editedPart.drawOrder) { + unsupported(ExportEntityCategory.Part, editedPart.id.raw, ExportNoticeReason.StaticDrawOrderShadowedByKeyforms) + } + return + } + // CMO3: CPartSource field defaultOrder_forEditor + CPartForm field drawOrder. + source.defaultOrder_forEditor = editedPart.drawOrder + editor.ensureChildSlot(source, "CPartSource", "defaultOrder_forEditor", "isSketch") + for (form in Cmo3Import.elementsOf(source.keyforms).filterIsInstance()) { + form.drawOrder = editedPart.drawOrder + editor.ensureChildSlot(form, "CPartForm", "drawOrder", "opacity") + } + } + + /** + * Lowers a part composite's flat fields (blend modes, masks, invert); the keyformed statics + * (opacity, colors) live in CPartForm cells and land with keyform lowering. Part-typed masks + * (an Umamo extension) flatten to their descendant drawables - CMO3 has nowhere to keep the + * part reference, so the grouping itself is reported as not carried. + * + * @param CPartSource source The part's graph source. + * @param PartId partId The part's id (for notices). + * @param Part baselinePart The baseline part. + * @param Part editedPart The edited part. + */ + private fun lowerPartComposite(source: CPartSource, partId: PartId, baselinePart: Part, editedPart: Part) { + val baselineComposite = baselinePart.composite + val editedComposite = editedPart.composite + if (baselineComposite.blendMode != editedComposite.blendMode) { + // CMO3: CPartSource field colorComposition. + source.colorComposition = colorCompositionOf(editedComposite.blendMode) + editor.ensureChildSlot(source, "CPartSource", "colorComposition", "alphaComposition") + } + if (baselineComposite.alphaBlendMode != editedComposite.alphaBlendMode) { + // CMO3: CPartSource field alphaComposition. + source.alphaComposition = alphaCompositionOf(editedComposite.alphaBlendMode) + editor.ensureChildSlot(source, "CPartSource", "alphaComposition", "targetDeformerGuid") + } + if ( + baselineComposite.maskedBy != editedComposite.maskedBy || + baselineComposite.maskedByParts != editedComposite.maskedByParts + ) { + if (editedComposite.maskedByParts.isNotEmpty()) { + unsupported(ExportEntityCategory.Part, partId.raw, ExportNoticeReason.PartMasksFlattenToDrawables) + } + // CMO3: CPartSource field clipGuidList - always drawable GUIDs, so part-typed masks are + // expanded to the part's descendant drawables (the same expansion the render tree applies). + val expandedMask = editedComposite.maskedBy + editedComposite.maskedByParts.flatMap(::descendantDrawables) + writeListField( + owner = source, + tag = "CPartSource", + property = "clipGuidList", + beforeProperty = "invertClippingMask", + current = source.clipGuidList, + newElements = expandedMask.distinct().mapNotNull { index.drawableByIdStr[it.raw]?.guid }, + assign = { list -> source.clipGuidList = list }, + ) + } + if (baselineComposite.invertMask != editedComposite.invertMask) { + // CMO3: CPartSource field invertClippingMask. + source.invertClippingMask = editedComposite.invertMask + editor.ensureChildSlot(source, "CPartSource", "invertClippingMask", "colorComposition") + } + val staticsChanged = + baselineComposite.opacity != editedComposite.opacity || + baselineComposite.multiplyColor != editedComposite.multiplyColor || + baselineComposite.screenColor != editedComposite.screenColor + if (staticsChanged) { + val opacityTrack = editedPart.channelGrids[FormChannel.OPACITY] + val multiplyTrack = editedPart.channelGrids[FormChannel.MULTIPLY_COLOR] + val screenTrack = editedPart.channelGrids[FormChannel.SCREEN_COLOR] + if (opacityTrack != null || multiplyTrack != null || screenTrack != null) { + // With tracks present the statics live in the grid cells; import re-derives each + // from the FIRST form, so a static matching its track's head cell survives on its + // own and only a disagreeing (or track-less-but-changed) one is actually lost. + val opacitySurvives = (opacityTrack?.cells?.firstOrNull()?.form as? ChannelValue.Scalar)?.value == editedComposite.opacity + val multiplySurvives = + (multiplyTrack?.cells?.firstOrNull()?.form as? ChannelValue.Color)?.color == editedComposite.multiplyColor + val screenSurvives = + (screenTrack?.cells?.firstOrNull()?.form as? ChannelValue.Color)?.color == editedComposite.screenColor + if (!opacitySurvives || !multiplySurvives || !screenSurvives) { + unsupported(ExportEntityCategory.Part, partId.raw, ExportNoticeReason.CompositeStaticsShadowedByKeyforms) + } + } else { + keyforms.writePartCompositeStatics(source, editedPart) + } + } + } + + /** + * Moves a deformer to another part: rewrites its parentGuid and moves its guid between the + * parts' _childGuids lists (deformers live in the parts-panel child order even though the + * runtime routes them out of the org tree). Runs before any CHILDREN rebuild, so the rebuild's + * anchor pass sees the deformer already in its new list. + * + * @param ACDeformerSource source The deformer's graph source. + * @param DeformerId deformerId The deformer's id. + * @param PartId? newPartId The new owning part, or null for the root. + */ + private fun lowerDeformerPart(source: ACDeformerSource, deformerId: DeformerId, newPartId: PartId?) { + val deformerUuid = Cmo3Import.uuidOf(source.guid) + val oldPartId = baselineDeformerById[deformerId]?.partId + val oldPartSource = oldPartId?.let { index.partByIdStr[it.raw] } ?: index.rootPartSource + val newPartSource = newPartId?.let { index.partByIdStr[it.raw] } ?: index.rootPartSource + if (newPartSource == null) { + unsupported(ExportEntityCategory.Deformer, deformerId.raw, ExportNoticeReason.DeformerHasNoPartToMoveTo) + return + } + // CMO3: ACParameterControllableSource field parentGuid - the org-tree owner; the synthetic + // root part is the "no part" owner. + source.parentGuid = newPartSource.guid + editor.ensureChildSlot(source, "ACParameterControllableSource", "parentGuid", "keyformGridSource") + if (deformerUuid == null) { + return + } + mutableGraphListOf(oldPartSource?._childGuids)?.removeAll { entry -> Cmo3Import.uuidOf(entry) == deformerUuid } + val newChildList = mutableGraphListOf(newPartSource._childGuids) + if (newChildList != null) { + if (newChildList.none { entry -> Cmo3Import.uuidOf(entry) == deformerUuid }) { + newChildList.add(source.guid) + } + } else { + writeListField( + owner = newPartSource, + tag = "CPartSource", + property = "_childGuids", + beforeProperty = "useOffscreen", + current = newPartSource._childGuids, + newElements = listOf(source.guid), + assign = { list -> newPartSource._childGuids = list }, + ) + } + } + + /** + * Rebuilds a part's _childGuids from the edited org children, preserving non-org entries + * (deformers, unknown guids) by anchor: each keeps its position after the nearest preceding org + * child that survives, else moves to the end. The org tree's single source of truth is the + * model's ordered children; the graph list is derived from it plus the preserved entries. + * + * @param CPartSource source The part (or root part) whose list is rebuilt. + * @param List editedChildren The edited model's ordered org children. + */ + private fun rebuildOrgChildren(source: CPartSource, editedChildren: List) { + val currentEntries = Cmo3Import.elementsOf(source._childGuids) + val nonOrgAfterAnchor = LinkedHashMap>() + var lastOrgUuid: String? = null + for (entry in currentEntries) { + val uuid = Cmo3Import.uuidOf(entry) + val isOrgChild = uuid != null && (uuid in index.drawableUuids || uuid in index.userPartUuids) + if (isOrgChild) { + lastOrgUuid = uuid + } else { + nonOrgAfterAnchor.getOrPut(lastOrgUuid) { ArrayList() }.add(entry) + } + } + val newEntries = ArrayList() + nonOrgAfterAnchor[null]?.let(newEntries::addAll) + for (child in editedChildren) { + val childGuid = + when (child) { + is OrgChild.Drawable -> index.drawableByIdStr[child.id.raw]?.guid + is OrgChild.Part -> index.partByIdStr[child.id.raw]?.guid + } + if (childGuid == null) { + val childId = if (child is OrgChild.Drawable) child.id.raw else (child as OrgChild.Part).id.raw + unsupported(ExportEntityCategory.Part, childId, ExportNoticeReason.CreatedEntityHasNoSourceYet) + continue + } + newEntries.add(childGuid) + nonOrgAfterAnchor.remove(Cmo3Import.uuidOf(childGuid))?.let(newEntries::addAll) + } + // Non-org entries whose anchor did not survive keep existing at the end of the list. + for ((anchorUuid, trailing) in nonOrgAfterAnchor) { + if (anchorUuid != null) { + newEntries.addAll(trailing) + } + } + writeListField( + owner = source, + tag = "CPartSource", + property = "_childGuids", + beforeProperty = "useOffscreen", + current = source._childGuids, + newElements = newEntries, + assign = { list -> source._childGuids = list }, + ) + } + + /** + * Rebuilds a parameter group's _childGuids from the edited tree nodes, and refreshes every + * child's redundant parentGroupGuid back-pointer to this group (the walk is authoritative, but + * the editor maintains the back-pointers, so the export does too). + * + * @param CParameterGroup group The group (or the hidden root group) to rebuild. + * @param List editedNodes The edited model's ordered child nodes. + */ + private fun rebuildGroupChildren(group: CParameterGroup, editedNodes: List) { + val newEntries = ArrayList() + for (node in editedNodes) { + when (node) { + is ParameterNode.Param -> { + val parameterSource = index.parameterByIdStr[node.id.raw] + if (parameterSource == null) { + unsupported(ExportEntityCategory.Parameter, node.id.raw, ExportNoticeReason.CreatedEntityHasNoSourceYet) + continue + } + newEntries.add(parameterSource.guid) + // CMO3: CParameterSource field parentGroupGuid - the redundant membership back-pointer. + parameterSource.parentGroupGuid = group.guid + editor.ensureChildSlot(parameterSource, "CParameterSource", "parentGroupGuid") + } + is ParameterNode.Group -> { + val childGroup = index.groupByIdStr[node.id.raw] + if (childGroup == null) { + unsupported(ExportEntityCategory.ParameterGroup, node.id.raw, ExportNoticeReason.CreatedEntityHasNoSourceYet) + continue + } + newEntries.add(childGroup.guid) + // CMO3: CParameterGroup field parentGroupGuid - the enclosing group back-pointer. + childGroup.parentGroupGuid = group.guid + editor.ensureChildSlot(childGroup, "CParameterGroup", "parentGroupGuid", "_childGuids") + } + } + } + writeListField( + owner = group, + tag = "CParameterGroup", + property = "_childGuids", + beforeProperty = "id", + current = group._childGuids, + newElements = newEntries, + assign = { list -> group._childGuids = list }, + ) + } + + /** + * Rewrites the parameter source order and combined flags from the edited model. Document order + * is semantic: a combined (2D) pair is encoded positionally, X flagged and Y immediately next. + * The target order is the edited parameter order with each link's Y moved directly after its X + * when not already adjacent (reported, since the reimported order will then differ); sources + * with no edited counterpart (deletions pending structural lowering) keep a stable tail. + */ + private fun lowerParameterOrderAndLinks() { + val sourceSet = index.modelSource.parameterSourceSet as? CParameterSourceSet + if (sourceSet == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoParameterSourceSet) + return + } + val orderedSources = ArrayList() + val placed = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + for (parameter in edited.parameters) { + val source = index.parameterByIdStr[parameter.id.raw] ?: continue + orderedSources.add(source) + placed.add(source) + } + for (source in index.parameterSources) { + if (source !in placed) { + orderedSources.add(source) + } + } + // CMO3: CParameterSource field combined - true only on the X member of a linked pair. + val linkByHorizontal = edited.parameterLinks.associateBy { link -> link.horizontal } + for (source in index.parameterSources) { + val idStr = Cmo3Import.idStrOf(source.id) ?: continue + val shouldCombine = ParameterId(idStr) in linkByHorizontal + if (source.combined != shouldCombine) { + source.combined = shouldCombine + editor.ensureChildSlot(source, "CParameterSource", "combined", "parentGroupGuid") + } + } + for (link in edited.parameterLinks) { + val horizontalSource = index.parameterByIdStr[link.horizontal.raw] ?: continue + val verticalSource = index.parameterByIdStr[link.vertical.raw] ?: continue + val horizontalIndex = orderedSources.indexOfFirst { it === horizontalSource } + val verticalIndex = orderedSources.indexOfFirst { it === verticalSource } + if (horizontalIndex < 0 || verticalIndex < 0 || verticalIndex == horizontalIndex + 1) { + continue + } + orderedSources.removeAt(verticalIndex) + val anchorIndex = orderedSources.indexOfFirst { it === horizontalSource } + orderedSources.add(anchorIndex + 1, verticalSource) + unsupported( + ExportEntityCategory.Document, + null, + ExportNoticeReason.CombinedPairReordered(link.horizontal.raw, link.vertical.raw), + ) + } + writeListField( + owner = sourceSet, + tag = "CParameterSourceSet", + property = "_sources", + beforeProperty = null, + current = sourceSet._sources, + newElements = orderedSources, + assign = { list -> sourceSet._sources = list }, + ) + } + + /** + * Lowers each listed file's name, path, and modification time onto the layered image the editor + * decomposed it into, so a document reopened in either editor points at the file the rigger last + * relinked and knows when it was read. + * + * CMO3: CModelSource field textureManager -> CTextureManager field _rawImages -> LayeredImageWrapper + * field image -> CLayeredImage fields name / psdFile / psdFileLastModified. The image is keyed by + * the guid the import minted the source id from; psdFile is the external-reference file shape, its + * text the absolute path on the machine that linked it, and psdFileLastModified the source's + * modification time in epoch milliseconds (docs/format/CMO3.md section 4). Only a record the + * baseline also lists is a repointed file; one it lacks is art added this session, whose export + * story is the atlas web's, and is passed over here. A shared record whose image the graph has + * lost is noted; a record with no known time leaves the image's as it was. + */ + private fun lowerSourceFiles() { + val textureManager = index.modelSource.textureManager as? CTextureManager + if (textureManager == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoTextureManagerToReconcile) + return + } + val imageByGuid = HashMap() + for (wrapper in Cmo3Import.elementsOf(textureManager._rawImages)) { + val image = (wrapper as? LayeredImageWrapper)?.image as? CLayeredImage ?: continue + val guid = Cmo3Import.uuidOf(image.guid) ?: continue + imageByGuid.putIfAbsent(guid, image) + } + val baselineById = baseline.sources.associateBy { source -> source.id } + for (source in edited.sources) { + val before = baselineById[source.id] ?: continue + if (before.name == source.name && before.path == source.path && before.lastModified == source.lastModified) { + continue + } + val image = imageByGuid[source.id.raw] + if (image == null) { + unsupported(ExportEntityCategory.Document, source.name, ExportNoticeReason.NoMatchingSourceToReconcile) + continue + } + image.name = source.name + val fileRef = + image.psdFile as? FileRef + ?: FileRef().also { created -> + image.psdFile = created + editor.ensureChildSlot(image, "CLayeredImage", "psdFile", "description") + } + fileRef.archivePath = null + fileRef.textPath = source.path.orEmpty() + // CMO3: CLayeredImage field psdFileLastModified - epoch milliseconds; a record with no known + // time leaves the image's as it was. + val lastModified = source.lastModified + if (lastModified != null) { + image.psdFileLastModified = lastModified + editor.ensureChildSlot(image, "CLayeredImage", "psdFileLastModified", "_rootLayer") + } + } + } + + /** + * Lowers the source-artwork display mode: the texture manager's flag AND the per-drawable input + * pointer it selects. + * + * The flag alone is not the whole state. Flipping the mode in the official editor also retargets + * each art mesh's currentTextureInputData between its model-image input and its atlas-region one + * (docs/format/CMO3.md §4), so writing only the flag would leave every drawable pointing at the + * input the OTHER mode samples - a file that says one thing and points at another. A drawable + * missing the input the mode needs keeps the pointer it has and takes a notice, rather than being + * given a dangling one. + */ + private fun lowerSourceLayerDisplay() { + // CMO3: CModelSource field textureManager -> CTextureManager field isTextureInputModelImageMode. + val textureManager = index.modelSource.textureManager as? CTextureManager + if (textureManager == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoTextureManagerToReconcile) + return + } + val fromSourceLayers = edited.rendersFromSourceLayers + textureManager.isTextureInputModelImageMode = fromSourceLayers + editor.ensureChildSlot(textureManager, "CTextureManager", "isTextureInputModelImageMode", "previewReductionRatio") + for (drawable in edited.drawables) { + val source = index.drawableByIdStr[drawable.id.raw] ?: continue + // CMO3: CArtMeshSource field _extensions -> CTextureInputExtension fields _textureInputs / + // currentTextureInputData - the pointer names which of the drawable's inputs is live. + val extension = Cmo3Import.elementsOf(source._extensions).filterIsInstance().firstOrNull() ?: continue + val inputs = Cmo3Import.elementsOf(extension._textureInputs) + val wanted = + if (fromSourceLayers) { + inputs.filterIsInstance().firstOrNull() + } else { + inputs.filterIsInstance().firstOrNull() + } + if (wanted == null) { + // An unpacked drawable in atlas mode, or one with no model image in layer mode. Leaving + // the live pointer alone keeps the file self-consistent; the notice names the gap. + unsupported(ExportEntityCategory.Drawable, drawable.name, ExportNoticeReason.NoTextureInputForDisplayMode) + continue + } + extension.currentTextureInputData = wanted + editor.ensureChildSlot(extension, "CTextureInputExtension", "currentTextureInputData", null) + } + } + + /** CMO3: CModelSource.canvas -> CImageCanvas fields pixelWidth / pixelHeight. */ + private fun lowerCanvasSize() { + val canvas = index.modelSource.canvas as? CImageCanvas + if (canvas == null) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.NoCanvasToReconcile) + return + } + val width = edited.canvasWidth + val height = edited.canvasHeight + if (width != width.toInt().toFloat() || height != height.toInt().toFloat()) { + unsupported(ExportEntityCategory.Document, null, ExportNoticeReason.FractionalCanvasSizeNotStorable) + return + } + canvas.pixelWidth = width.toInt() + canvas.pixelHeight = height.toInt() + editor.ensureChildSlot(canvas, "CImageCanvas", "pixelWidth", "pixelHeight") + editor.ensureChildSlot(canvas, "CImageCanvas", "pixelHeight", "background") + } + + /** The drawables under a part in the edited model's org tree, in panel order. */ + private fun descendantDrawables(partId: PartId): List { + val part = editedPartById[partId] ?: return emptyList() + val drawableIds = ArrayList() + + fun walk(children: List) { + for (child in children) { + when (child) { + is OrgChild.Drawable -> drawableIds.add(child.id) + is OrgChild.Part -> editedPartById[child.id]?.let { walk(it.children) } + } + } + } + walk(part.children) + return drawableIds + } + + private fun findEditedGroup(groupId: ParameterGroupId): ParameterNode.Group? { + fun walk(nodes: List): ParameterNode.Group? { + for (node in nodes) { + if (node is ParameterNode.Group) { + if (node.id == groupId) { + return node + } + walk(node.children)?.let { return it } + } + } + return null + } + return walk(edited.parameterTree) + } + + /** + * Rewrites a collection field in place, or creates a fresh CArrayList and records its slot. + * + * The fresh list's runtime type decides the serialized tag, and every field this helper + * serves (_childGuids, _sources) is carray_list in every corpus model; the official + * editor's deserializers cast such fields to CArrayList, so array_list fails its load. + * + * @param Any owner The graph object owning the collection field. + * @param String tag The owner's serial tag for the child-slot record. + * @param String property The collection field's name. + * @param String? beforeProperty The sibling field the slot precedes, or null for last. + * @param Any? current The current field value. + * @param List newElements The elements to write. + * @param Function assign Assigns the fresh list to the field. + */ + private fun writeListField( + owner: Any, + tag: String, + property: String, + beforeProperty: String?, + current: Any?, + newElements: List, + assign: (MutableList) -> Unit, + ) { + val mutable = mutableGraphListOf(current) + if (mutable != null) { + mutable.clear() + mutable.addAll(newElements) + return + } + val fresh: MutableList = CArrayList() + fresh.addAll(newElements) + assign(fresh) + editor.ensureChildSlot(owner, tag, property, beforeProperty) + } +} + +/** + * The atlas-to-canvas half a packed entry carries at [placement]: the tile's full canvas placement + * composed with the placement's inverse, so the entry pair keeps composing to + * CModelImage._materialLocalToCanvasTransform. + * + * One helper shared by the entry lowering and the drawable region-input rewrite, so the two values + * the corpus keeps equal stay bit-identical when both are written. + * + * @param FloatArray canvasAffine The tile's canvas placement, all six components. + * @param AtlasPlacement placement Where the art sits on its page. + * @return FloatArray? The composed 2x3 affine, or null when the placement is degenerate. + */ +internal fun atlasLocalToCanvasFor(canvasAffine: FloatArray, placement: AtlasPlacement): FloatArray? { + val inverse = inversePlacementAffine(placement) ?: return null + return composeAffine(canvasAffine, inverse) +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3RetainedLayerWeb.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3RetainedLayerWeb.kt new file mode 100644 index 0000000..0f43386 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3RetainedLayerWeb.kt @@ -0,0 +1,799 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3GraphEditor +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.gen.ACLayerGroup +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.gen.CLayerGroup +import org.umamo.format.cmo3.model.gen.CLayerSelectorMap +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.EnvValueSet +import org.umamo.format.cmo3.model.gen.FilterEnv +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.LayerSet +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.gen.ModelImageFilterSet +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.CRect +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.lineageRoot +import org.umamo.runtime.model.storedToArtAffineForTile +import kotlin.math.roundToInt + +/* + * The real-layer web of a RETAINED graph: what a CMO3-origin export writes for the art that changed + * since the import. A reload supersedes a tile with a new one (`~n`) whose pixels reach the + * pages, while the layered image the editor decomposed at import still holds the layer as imported; + * a reload's added layer and an Add Artwork file mint tiles the graph has no model image for at all. + * This brings the layered-image tree, the model images, and their canvas placements to the edited + * model, with the same builders the fresh web uses, so the official editor's layered view shows the + * art the rigger sees and a reopened export re-imports against the file by key. + * + * Two jobs, both validated before anything is written: + * - a rewrite, for a reloaded tile whose lineage root has a model image: the layer that image + * composites takes the tile's pixels, rect, name, and visibility, and the image's canvas + * placement moves to the row's origin (a relink repoints the image at the row's layer first, + * minting the layer when the file never had it); + * - a mint, for a tile with no model image: a layer under its file's layered image (found by the + * source's guid, minted for a file the graph never held) in the folder its row names, and a + * model image over it. + * The entry and the drawables' region inputs are the atlas-web reconcile's, which runs over the maps + * this class extends. + */ + +/** + * The retained-graph layer writer. Validation ([rewriteJobFor], [mintJobFor]) hands the reconcile a + * job per tile or null to decline whole; [apply] runs the jobs it was handed. + * + * @param Cmo3Model target The retained model, whose archive receives the pixels. + * @param CTextureManager textureManager The graph's texture manager. + * @param Cmo3GraphEditor editor The graph editor, for slots the retained document omitted. + * @param PuppetModel edited The session's model. + * @param Function tileRasters The document's pixels for a tile, or null. + * @param Long nowMillis The timestamp minted env values and wrappers record. + * @param Cmo3TextureFrames textureFrames The document's texture frames, taken before the export wrote. + */ +internal class Cmo3RetainedLayerWeb( + private val target: Cmo3Model, + private val textureManager: CTextureManager, + private val editor: Cmo3GraphEditor, + private val edited: PuppetModel, + private val tileRasters: (AtlasTileId) -> RasterImage?, + private val nowMillis: Long, + private val textureFrames: Cmo3TextureFrames, +) { + /** + * The art a job writes: the tile, its file and inventory row, and its pixels. + * + * @property String tileId The tile's lineage root - the key the atlas web tracks. + * @property AtlasTile tile The edited tile. + * @property ArtSource source The file the tile is bound to. + * @property ArtSourceLayer row The inventory row the binding names. + * @property RasterImage raster The tile's pixels, straight alpha. + * @property FloatArray canvasAffine The model image's canvas placement: a pure translation to + * the row's origin, as a six-float affine. + */ + internal open class Job( + val tileId: String, + val tile: AtlasTile, + val source: ArtSource, + val row: ArtSourceLayer, + val raster: RasterImage, + ) { + val canvasAffine: FloatArray = floatArrayOf(1f, 0f, row.left.toFloat(), 0f, 1f, row.top.toFloat()) + } + + /** + * A reloaded tile whose lineage root's model image is rewritten to the tile's art. + * + * @property CModelImage modelImage The root's model image. + * @property SoleLayerInput sole The one layer input the image composites today. + * @property CImageResource filtered The image's filtered resource, which holds an archive entry. + */ + internal class RewriteJob( + tileId: String, + tile: AtlasTile, + source: ArtSource, + row: ArtSourceLayer, + raster: RasterImage, + val modelImage: CModelImage, + val sole: SoleLayerInput, + val filtered: CImageResource, + ) : Job(tileId, tile, source, row, raster) + + /** A tile with no model image, whose whole layer web is minted. */ + internal class MintJob( + tileId: String, + tile: AtlasTile, + source: ArtSource, + row: ArtSourceLayer, + raster: RasterImage, + ) : Job(tileId, tile, source, row, raster) + + /** + * What [apply] added to the web, for the reconcile's maps. + * + * @property Map modelImageByTileId The model image of every minted tile, by lineage root. + * @property Boolean releasedCopy True when a rewrite left a reduced cache copy unreferenced and + * removed its pixels, so the shared pool needs a prune. + */ + internal class Applied(val modelImageByTileId: Map, val releasedCopy: Boolean = false) + + /** Set once a rewrite removes a reduced copy nothing samples any more. */ + private var releasedCopy = false + + /** The edited drawables by raw id, for the coordinates a retargeted drawable stores. */ + private val editedDrawableById by lazy { edited.drawables.associateBy { drawable -> drawable.id.raw } } + + private val sourceById = edited.sources.associateBy { source -> source.id } + + /** Whether the graph carries the two lists a new file's web is added to. */ + private val canMintFiles: Boolean = + mutableGraphListOf(textureManager._rawImages) != null && mutableGraphListOf(textureManager._modelImageGroups) != null + + /** + * The names object every mint threads, built on first use: the archive's own path sequences, and + * the filter definitions of a model image the graph already holds (fresh ones when it holds none, + * or one another writer shaped differently). + */ + private val names: Cmo3ImageChainBuilder.Cmo3FreshChainNames by lazy { namesFor() } + + /** The PNG entries the shared builders collected since the last [embedPending]. */ + private val pendingEntries = ArrayList() + + /** + * Embeds every collected entry in the archive. Called after each builder call, so the local path + * sequences and the archive never disagree about what is taken. + */ + private fun embedPending() { + for (entry in pendingEntries) { + target.addPng(entry.path, entry.pngBytes) + } + pendingEntries.clear() + } + + /** + * The art a tile carries, when its binding names a listed file's row and the document holds its + * pixels; null otherwise. + * + * @param AtlasTile tile The edited tile. + * @return Job? The art, as a plain job. + */ + private fun artOf(tile: AtlasTile): Job? { + val ref = tile.source ?: return null + val source = sourceById[ref.sourceId] ?: return null + val row = source.layers.firstOrNull { candidate -> candidate.key == ref.layerKey } ?: return null + val raster = tileRasters(tile.id) ?: return null + return Job(tile.id.lineageRoot.raw, tile, source, row, raster) + } + + /** + * The rewrite job for a reloaded tile, or null when the graph cannot take it: no pixels or no row + * for the tile, a model image that composites anything but exactly one layer, or a filtered + * resource with no archive entry to replace. + * + * @param AtlasTile tile The edited tile, a reloaded one. + * @param CModelImage modelImage Its lineage root's model image. + * @return RewriteJob? The job, or null. + */ + fun rewriteJobFor(tile: AtlasTile, modelImage: CModelImage): RewriteJob? { + val art = artOf(tile) ?: return null + val sole = soleLayerInputOf(modelImage) ?: return null + if (sole.input.layer !is CLayer) { + return null + } + // CMO3: CModelImage field _filteredImage - the composite the editor shows; for a single layer + // at identity it is the layer's own pixels, so it takes the new raster too. + val filtered = modelImage._filteredImage as? CImageResource ?: return null + if (filtered.imageFileBuf?.archivePath == null) { + return null + } + if (art.source.id.raw != sole.imageGuid && !canMintFiles) { + // A relink into a file the graph never held needs the file's web minted. + return null + } + return RewriteJob(art.tileId, tile, art.source, art.row, art.raster, modelImage, sole, filtered) + } + + /** + * The mint job for a tile with no model image, or null when the tile has no pixels or no row, or + * the graph has no lists to add a file's web to. + * + * @param AtlasTile tile The edited tile. + * @return MintJob? The job, or null. + */ + fun mintJobFor(tile: AtlasTile): MintJob? { + val art = artOf(tile) ?: return null + if (!canMintFiles) { + return null + } + return MintJob(art.tileId, tile, art.source, art.row, art.raster) + } + + /** + * One retained or minted layered image with the lists a layer is added through. + * + * @property CLayeredImage image The layered image. + * @property CModelImageGroup group Its model-image group. + * @param Function entryListOf The flat entry list every group and layer joins, resolved + * on first use so a rewrite that adds nothing never creates + * a list the file omitted. + */ + private class ImageSite( + val image: CLayeredImage, + val group: CModelImageGroup, + entryListOf: () -> MutableList, + ) { + /** The flat entry list every group and layer joins. */ + val layerEntryList: MutableList by lazy(entryListOf) + + /** The folder at each slash-joined path found or minted so far. */ + val folderByPath = HashMap() + + /** The layer minted for each binding key so far, so a second tile on one key shares it. */ + val mintedLayerByKey = HashMap() + } + + /** + * Runs the jobs: every rewrite, then every mint, sharing one set of file sites so two jobs on one + * file mint its web once. Every pixel entry is embedded as its job completes. + * + * @param List rewrites The rewrite jobs. + * @param List mints The mint jobs. + * @return Applied The minted model images. + */ + fun apply(rewrites: List, mints: List): Applied { + if (rewrites.isEmpty() && mints.isEmpty()) { + return Applied(emptyMap()) + } + val siteBySourceId = HashMap() + val modelImageByTileId = HashMap() + for (job in rewrites) { + rewrite(job, siteBySourceId) + } + for (job in mints) { + modelImageByTileId[job.tileId] = mint(job, siteBySourceId) + } + return Applied(modelImageByTileId, releasedCopy) + } + + /** + * A drawable's own icons over its texture patch, embedded now. + * + * @param RasterImage raster The art the drawable samples, in its own frame. + * @param FloatArray? artUvs The drawable's texture coordinates in that frame, or null for the whole art. + * @return Pair The 32px and 16px icons. + */ + fun drawableIcons(raster: RasterImage, artUvs: FloatArray?): Pair { + val patch = Cmo3Icons.patchOf(raster, artUvs) + val icon32 = Cmo3Icons.iconOf(patch, 32, names.nextIconPath(), pendingEntries) + val icon16 = Cmo3Icons.iconOf(patch, 16, names.nextIconPath(), pendingEntries) + embedPending() + return icon32 to icon16 + } + + /** + * Re-renders a file-side drawable's icons over its (changed) art, in place where the icons have + * entries and minted with their slots recorded where the file carried none. + * + * @param CArtMeshSource mesh The drawable source. + * @param RasterImage raster The art it samples, in its own frame. + * @param FloatArray? artUvs Its texture coordinates in that frame, or null for the whole art. + */ + fun replaceDrawableIcons(mesh: CArtMeshSource, raster: RasterImage, artUvs: FloatArray?) { + val patch = Cmo3Icons.patchOf(raster, artUvs) + // CMO3: ACDrawableSource fields icon32 / icon16, in that order after invertClippingMask. + refreshIcon(mesh.icon32, patch, 32) { icon -> + mesh.icon32 = icon + editor.ensureChildSlot(mesh, "ACDrawableSource", "icon32", "icon16") + } + refreshIcon(mesh.icon16, patch, 16) { icon -> + mesh.icon16 = icon + editor.ensureChildSlot(mesh, "ACDrawableSource", "icon16") + } + } + + /** + * Writes the model's three icons as fits of [thumbnail], in place where they have entries and + * minted with their slots recorded where the file carried none. + * + * @param CModelSource modelSource The model root. + * @param RasterImage thumbnail The model's rest-pose thumbnail. + */ + fun replaceModelIcons(modelSource: CModelSource, thumbnail: RasterImage) { + // CMO3: CModelSource fields _icon64 / _icon32 / _icon16, in that order before gameMotionSet. + refreshIcon(modelSource._icon64, thumbnail, 64) { icon -> + modelSource._icon64 = icon + editor.ensureChildSlot(modelSource, "CModelSource", "_icon64", "_icon32") + } + refreshIcon(modelSource._icon32, thumbnail, 32) { icon -> + modelSource._icon32 = icon + editor.ensureChildSlot(modelSource, "CModelSource", "_icon32", "_icon16") + } + refreshIcon(modelSource._icon16, thumbnail, 16) { icon -> + modelSource._icon16 = icon + editor.ensureChildSlot(modelSource, "CModelSource", "_icon16", "gameMotionSet") + } + } + + /** + * Re-renders one icon slot: the existing entry's bytes are replaced when the slot names one the + * archive holds, else a fresh icon is minted and handed to [assign] to set and record its slot. + * + * @param Any? current The slot's icon today. + * @param RasterImage raster The art to fit. + * @param Int size The square's edge. + * @param Function assign Sets a minted icon on its owner and records the slot. + */ + private fun refreshIcon(current: Any?, raster: RasterImage, size: Int, assign: (CImageIcon) -> Unit) { + val path = Cmo3Icons.archivePathOf(current) + if (path != null && target.archive.byPath(path) != null) { + target.replacePng(path, Cmo3Icons.iconPngOf(raster, size)) + (current as CImageIcon).image.let { image -> + if (image is CWritableImage) { + image.width = size + image.height = size + } + } + return + } + assign(Cmo3Icons.iconOf(raster, size, names.nextIconPath(), pendingEntries)) + embedPending() + } + + /** + * Re-renders a rewritten layer's icons over its new art. + * + * @param CLayer layer The layer. + * @param RasterImage raster Its new pixels. + */ + private fun replaceLayerIcons(layer: CLayer, raster: RasterImage) { + // CMO3: CLayer fields icon16 / icon64, in that order before layerInfo. + refreshIcon(layer.icon16, raster, 16) { icon -> + layer.icon16 = icon + editor.ensureChildSlot(layer, "CLayer", "icon16", "icon64") + } + refreshIcon(layer.icon64, raster, 64) { icon -> + layer.icon64 = icon + editor.ensureChildSlot(layer, "CLayer", "icon64", "layerInfo") + } + } + + /** + * Re-renders a rewritten model image's icon over its new art. + * + * @param CModelImage modelImage The model image. + * @param RasterImage raster Its new pixels. + */ + private fun replaceModelImageIcon(modelImage: CModelImage, raster: RasterImage) { + // CMO3: CModelImage field icon16, before _materialLocalToCanvasTransform. + refreshIcon(modelImage.icon16, raster, 16) { icon -> + modelImage.icon16 = icon + editor.ensureChildSlot(modelImage, "CModelImage", "icon16", "_materialLocalToCanvasTransform") + } + } + + /** + * The names object a minted web threads: the archive's own path sequences, and the filter + * definitions of a model image the graph already holds (fresh ones when it holds none, or one + * another writer shaped differently). + * + * @return Cmo3FreshChainNames The names. + */ + private fun namesFor(): Cmo3ImageChainBuilder.Cmo3FreshChainNames { + val retainedFilterSet = + Cmo3Import.elementsOf(textureManager._modelImageGroups) + .filterIsInstance() + .flatMap { group -> Cmo3Import.elementsOf(group._modelImages).filterIsInstance() } + .firstNotNullOfOrNull { modelImage -> modelImage.inputFilter as? ModelImageFilterSet } + val filters = + retainedFilterSet?.let { filterSet -> Cmo3ImageChainBuilder.FilterCommons.fromFilterSet(filterSet) } + ?: Cmo3ImageChainBuilder.FilterCommons.fresh() + val bufferPaths = Cmo3ImageChainBuilder.FreshPathSequence.continuingFrom("imageFileBuf", target.nextImageFileBufPath()) + val iconPaths = Cmo3ImageChainBuilder.FreshPathSequence.continuingFrom("image", target.nextImagePath()) + return Cmo3ImageChainBuilder.Cmo3FreshChainNames(filters, bufferPaths::next, iconPaths::next) + } + + /** + * Rewrites a reloaded tile's model image to the tile's art: the row's layer (the composited one + * when the binding did not move, else found by key in the row's file or minted) takes the pixels, + * rect, name, and visibility; the image's placement, name, and cache follow. + * + * @param RewriteJob job The job. + * @param MutableMap siteBySourceId The file sites found or minted so far. + */ + private fun rewrite(job: RewriteJob, siteBySourceId: MutableMap) { + val modelImage = job.modelImage + val compositedLayer = job.sole.input.layer as CLayer + val sourceGuid = job.source.id.raw + val site = siteFor(job.source, siteBySourceId) + // The layer the row names: the composited one when the tile was reloaded in place, which is + // the common case and touches no selector; otherwise the relink's target, repointed to below. + val sameFile = sourceGuid == job.sole.imageGuid + val compositedKey = walkLayeredImage(site.image).firstOrNull { walked -> walked.layer === compositedLayer }?.key + val layer = + if (sameFile && compositedKey == job.row.key) { + compositedLayer + } else { + layerFor(site, job.row, job.raster) + } + val pngBytes = PngCodec.write(job.raster) + writeLayer(layer, job.row, job.raster, pngBytes) + replaceLayerIcons(layer, job.raster) + // CMO3: CModelImage field _filteredImage - replaced in place when it is a resource of its own + // rather than the layer's (the fresh web shares one instance; an editor import may not). + val filtered = job.filtered + if (filtered !== layer.imageResource) { + if (filtered.imageFileBuf?.archivePath != null) { + target.replaceLayerPng(filtered, pngBytes) + } + filtered.width = job.raster.width + filtered.height = job.raster.height + } + if (layer !== compositedLayer) { + // CMO3: CLayerInputData field layer - the selector's target, repointed at the row's layer. + job.sole.input.layer = layer + if (!sameFile) { + repointImage(modelImage, job.sole, site.image) + } + } + // CMO3: CModelImage fields name / _materialLocalToCanvasTransform / cachedImageManager - the + // tile's name, the row's origin as a pure translation, and a cache over the new dimensions. + modelImage.name = job.tile.name + val placement = modelImage._materialLocalToCanvasTransform as? CAffine + if (placement == null) { + modelImage._materialLocalToCanvasTransform = Cmo3SourceLayerWeb.layerPlacement(job.row.left, job.row.top) + editor.ensureChildSlot(modelImage, "CModelImage", "_materialLocalToCanvasTransform", "_group") + } else { + placement.setFromAffineArray(job.canvasAffine) + } + modelImage.cachedImageManager = Cmo3ImageChainBuilder.paddedCacheManager(filtered, job.raster.width, job.raster.height) + retargetDrawablesOnto(modelImage, filtered, job.raster.width, job.raster.height) + replaceModelImageIcon(modelImage, job.raster) + embedPending() + } + + /** + * Brings every drawable shown from a rewritten model image onto its new raster: the reduced cache copy + * the editor made of the old art no longer shows the art, and a texture over the raster must carry the + * new size's cache scale. + * + * Each texture over the image (its raster, or its copy as the graph was read) samples the raster with + * the scale and mip level the editor writes for one, shared textures once. A drawable whose stored + * coordinates now mean something else - it moved off a copy, or it stores the cache frame and the scale + * changed - stores the edited model's coordinates afresh; every other drawable's are left to the + * property pass. A copy nothing samples any more has its pixels removed, and the pool prune drops it. + * + * @param CModelImage modelImage The rewritten model image. + * @param CImageResource raster Its raster, holding the new art. + * @param Int width The new art's width in pixels. + * @param Int height The new art's height in pixels. + */ + private fun retargetDrawablesOnto(modelImage: CModelImage, raster: CImageResource, width: Int, height: Int) { + val modelSource = target.root as? CModelSource ?: return + // CMO3: CModelSource field drawableSourceSet -> CDrawableSourceSet field _sources. + val drawableSources = Cmo3Import.elementsOf((modelSource.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + val shownFromImage = drawableSources.filter { source -> textureFrames.isShownFrom(source, modelImage) } + if (shownFromImage.isEmpty()) { + return + } + // The frames as they are before any texture moves: shared textures make a later read stale. + val frameBefore = shownFromImage.associateWith { source -> textureFrames.storedFrameOf(source) } + val scaleBefore = shownFromImage.associateWith { source -> affineValuesOf((source.texture as? GTexture2D)?.transformImageResource01toLogical01) } + val releasedCopies = HashSet() + val retargeted = HashSet() + for (source in shownFromImage) { + val texture = source.texture as? GTexture2D ?: continue + if (!retargeted.add(texture)) { + continue + } + (texture.srcImageResource as? CImageResource)?.takeIf { sampled -> textureFrames.isReducedCopy(sampled) }?.let(releasedCopies::add) + // CMO3: GTexture2D fields srcImageResource / transformImageResource01toLogical01 / mipmapLevel - + // the raster, its cache scale, and the full-resolution level, as every corpus texture over a + // model image's raster writes them. + texture.srcImageResource = raster + texture.transformImageResource01toLogical01 = Cmo3ImageChainBuilder.paddedFrameAffine(width, height) + texture.mipmapLevel = Cmo3ImageChainBuilder.FULL_RESOLUTION_MIPMAP_LEVEL + editor.ensureChildSlot(texture, "GTexture2D", "transformImageResource01toLogical01", "mipmapLevel") + editor.ensureChildSlot(texture, "GTexture2D", "mipmapLevel", "isPremultiplied") + } + for (source in shownFromImage) { + val frameNow = textureFrames.storedFrameOf(source) + val scaleNow = affineValuesOf((source.texture as? GTexture2D)?.transformImageResource01toLogical01) + val meaningChanged = frameNow != frameBefore[source] || (frameNow == Cmo3StoredFrame.Cache && !scaleNow.contentEquals(scaleBefore[source])) + if (!meaningChanged) { + continue + } + val drawableId = (source.id as? Id)?.idstr ?: continue + val editedDrawable = editedDrawableById[drawableId] ?: continue + val editedUvs = editedDrawable.mesh?.uvs ?: continue + val storedToArt = editedDrawable.atlasTileId?.let { tileId -> edited.atlas.storedToArtAffineForTile(tileId) } + // CMO3: CArtMeshSource field uvs. + source.uvs = textureFrames.storedUvsOf(source, editedUvs, storedToArt) + editor.ensureChildSlot(source, "CArtMeshSource", "uvs", "texture") + } + for (copy in releasedCopies) { + val stillSampled = drawableSources.any { source -> (source.texture as? GTexture2D)?.srcImageResource === copy } + if (stillSampled) { + continue + } + if (copy.imageFileBuf?.archivePath != null) { + target.removeLayerPng(copy) + } + releasedCopy = true + } + } + + /** + * A CMO3 affine's six values, identity for none, so two can be compared. + * + * @param Any? affine The field value. + * @return FloatArray The values, m00 m01 m02 m10 m11 m12. + */ + private fun affineValuesOf(affine: Any?): FloatArray { + val values = affine as? CAffine ?: return floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f) + return floatArrayOf(values.m00, values.m01, values.m02, values.m10, values.m11, values.m12) + } + + /** + * Moves a model image to another file: the selector map's key, the current-image env value, and + * the linked-image list all name the new layered image. + * + * @param CModelImage modelImage The model image. + * @param SoleLayerInput sole Its one layer input, already repointed at the new file's layer. + * @param CLayeredImage image The new file's layered image. + */ + private fun repointImage(modelImage: CModelImage, sole: SoleLayerInput, image: CLayeredImage) { + // CMO3: ModelImageFilterEnv field envValues -> EnvValueSet field value: the CLayerSelectorMap's + // _imageToLayerInput keyed by image guid, and the current-image guid value beside it. + val filterEnv = modelImage.inputFilterEnv as? FilterEnv ?: return + for (valueSet in Cmo3Import.elementsOf(filterEnv.envValues).filterIsInstance()) { + val selectorMap = valueSet.value as? CLayerSelectorMap + if (selectorMap != null) { + selectorMap._imageToLayerInput = LinkedHashMap().apply { put(image.guid, ArrayList(mutableListOf(sole.input))) } + valueSet.updateTimeMs = nowMillis + } else if (Cmo3Import.uuidOf(valueSet.value) == sole.imageGuid) { + valueSet.value = image.guid + valueSet.updateTimeMs = nowMillis + } + } + // CMO3: CModelImage field linkedRawImageGuids. + modelImage.linkedRawImageGuids = CArrayList(mutableListOf(image.guid)) + } + + /** + * Writes a tile's art into a layer: the archive entry, the resource dimensions, the rect at the + * row's origin, and the row's name and visibility. + * + * @param CLayer layer The layer. + * @param ArtSourceLayer row The inventory row. + * @param RasterImage raster The pixels. + * @param ByteArray pngBytes The pixels, encoded. + */ + private fun writeLayer(layer: CLayer, row: ArtSourceLayer, raster: RasterImage, pngBytes: ByteArray) { + val resource = layer.imageResource as? CImageResource + if (resource != null && resource.imageFileBuf?.archivePath != null) { + target.replaceLayerPng(resource, pngBytes) + // CMO3: CImageResource fields width / height - corpus-verified to equal the decoded PNG's. + resource.width = raster.width + resource.height = raster.height + } + // CMO3: CLayer field boundsOnImageDoc, written into the existing rect when there is one. + val bounds = layer.boundsOnImageDoc as? CRect + if (bounds == null) { + layer.boundsOnImageDoc = Cmo3SourceLayerWeb.layerBounds(row.left, row.top, raster.width, raster.height) + editor.ensureChildSlot(layer, "CLayer", "boundsOnImageDoc", "layerIdentifier") + } else { + bounds.x = row.left + bounds.y = row.top + bounds.width = raster.width + bounds.height = raster.height + } + // CMO3: ACLayerEntry fields name / isVisible - as the file reads today. + layer.name = row.name + layer.isVisible = row.visible + } + + /** + * Mints a tile's layer web: the layer under its file in the row's folder, and a model image over + * it at the row's origin. + * + * @param MintJob job The job. + * @param MutableMap siteBySourceId The file sites found or minted so far. + * @return CModelImage The minted model image. + */ + private fun mint(job: MintJob, siteBySourceId: MutableMap): CModelImage { + val site = siteFor(job.source, siteBySourceId) + val layer = layerFor(site, job.row, job.raster) + // A second tile on one key (a double binding) shares the layer the first minted, pixels + // included, since a model image composites its layer's own resource; only the model image is + // its own. + val resource = layer.imageResource as CImageResource + val modelImage = + Cmo3ImageChainBuilder.modelImageOver( + job.tile.name, + site.image, + layer, + resource, + job.raster, + Cmo3SourceLayerWeb.layerPlacement(job.row.left, job.row.top), + site.group, + names, + pendingEntries, + nowMillis, + ) + checkNotNull(mutableGraphListOf(site.group._modelImages)) { "a site's group has a model-image list" }.add(modelImage) + embedPending() + return modelImage + } + + /** + * The file's site: its retained layered image and group (the group minted when the image has + * none), or a whole minted web for a file the graph never held. + * + * @param ArtSource source The file. + * @param MutableMap siteBySourceId The sites so far. + * @return ImageSite The site. + */ + private fun siteFor(source: ArtSource, siteBySourceId: MutableMap): ImageSite { + siteBySourceId[source.id.raw]?.let { existing -> return existing } + val rawImages = checkNotNull(mutableGraphListOf(textureManager._rawImages)) { "validated: the raw-image list exists" } + val groups = checkNotNull(mutableGraphListOf(textureManager._modelImageGroups)) { "validated: the group list exists" } + // CMO3: CTextureManager field _rawImages -> LayeredImageWrapper field image -> CLayeredImage + // field guid - the source id a CMO3-origin document carries. + val retainedImage = + rawImages.firstNotNullOfOrNull { wrapper -> + ((wrapper as? LayeredImageWrapper)?.image as? CLayeredImage)?.takeIf { image -> Cmo3Import.uuidOf(image.guid) == source.id.raw } + } + val site = + if (retainedImage != null) { + // CMO3: CModelImageGroup field _linkedRawImageGuids - the group a file's images live in. + val retainedGroup = + groups.filterIsInstance().firstOrNull { group -> + Cmo3Import.elementsOf(group._linkedRawImageGuids).any { guid -> Cmo3Import.uuidOf(guid) == source.id.raw } && + mutableGraphListOf(group._modelImages) != null + } + val group = + retainedGroup + ?: Cmo3SourceLayerWeb.mintModelImageGroup(source.name, retainedImage).also { minted -> groups.add(minted) } + ImageSite(retainedImage, group) { layerEntryListOf(retainedImage) } + } else { + val canvasWidth = edited.canvasWidth.roundToInt() + val canvasHeight = edited.canvasHeight.roundToInt() + val minted = Cmo3SourceLayerWeb.mintLayeredImage(source.name, source.path, source.lastModified, canvasWidth, canvasHeight, names, nowMillis) + rawImages.add(minted.wrapper) + val group = Cmo3SourceLayerWeb.mintModelImageGroup(source.name, minted.image) + groups.add(group) + ImageSite(minted.image, group) { minted.layerEntryList }.also { site -> site.folderByPath[""] = minted.rootGroup } + } + siteBySourceId[source.id.raw] = site + return site + } + + /** + * A retained image's flat entry list, created (with its slot recorded) when the file omitted it. + * + * @param CLayeredImage image The layered image. + * @return MutableList The list. + */ + private fun layerEntryListOf(image: CLayeredImage): MutableList { + // CMO3: CLayeredImage field layerSet -> LayerSet field _layerEntryList. + val layerSet = + image.layerSet as? LayerSet + ?: LayerSet().also { created -> + created._layeredImage = image + image.layerSet = created + editor.ensureChildSlot(image, "CLayeredImage", "layerSet") + } + return mutableGraphListOf(layerSet._layerEntryList) + ?: CArrayList().also { created -> + layerSet._layerEntryList = created + editor.ensureChildSlot(layerSet, "LayerSet", "_layerEntryList") + } + } + + /** + * The row's layer in a site: one minted this pass for the same key, else the file's own layer + * under that key, else a fresh layer with the tile's pixels in the row's folder. + * + * @param ImageSite site The file's site. + * @param ArtSourceLayer row The inventory row. + * @param RasterImage raster The pixels a minted layer takes. + * @return CLayer The layer. + */ + private fun layerFor(site: ImageSite, row: ArtSourceLayer, raster: RasterImage): CLayer { + site.mintedLayerByKey[row.key]?.let { minted -> return minted } + walkLayeredImage(site.image).firstOrNull { walked -> walked.key == row.key }?.let { walked -> return walked.layer } + val folder = folderAt(site, row.groupPath) + val pngBytes = PngCodec.write(raster) + val path = names.nextImageFileBufPath() + pendingEntries.add(Cmo3FreshFile.PngEntry(path, pngBytes)) + val resource = Cmo3SourceLayerWeb.layerResource(path, raster, pngBytes.size) + val layer = + Cmo3SourceLayerWeb.layerOver( + name = row.name, + layerKey = row.key, + visible = row.visible, + canvasLeft = row.left, + canvasTop = row.top, + resource = resource, + raster = raster, + layeredImage = site.image, + folder = folder, + names = names, + pngEntries = pendingEntries, + ) + childrenOf(folder).add(layer) + site.layerEntryList.add(layer) + site.mintedLayerByKey[row.key] = layer + embedPending() + return layer + } + + /** + * The folder at a slash-joined path in a site's tree, walking the retained groups by name and + * minting each missing segment under its parent. + * + * @param ImageSite site The file's site. + * @param String path The folder path, "" for the root. + * @return CLayerGroup The folder. + */ + private fun folderAt(site: ImageSite, path: String): CLayerGroup { + site.folderByPath[path]?.let { known -> return known } + if (path.isEmpty()) { + // CMO3: CLayeredImage field _rootLayer - the tree's root group. + val root = + site.image._rootLayer as? CLayerGroup + ?: Cmo3SourceLayerWeb.layerGroup("root", site.image, CArrayList(), names).also { minted -> + site.image._rootLayer = minted + editor.ensureChildSlot(site.image, "CLayeredImage", "_rootLayer", "layerSet") + site.layerEntryList.add(0, minted) + } + site.folderByPath[""] = root + return root + } + val parent = folderAt(site, path.substringBeforeLast('/', "")) + val name = path.substringAfterLast('/') + val siblings = childrenOf(parent) + // CMO3: ACLayerEntry field name - a folder is found by its own name under its parent. + val folder = + siblings.filterIsInstance().firstOrNull { group -> group.name == name } + ?: Cmo3SourceLayerWeb.layerGroup(name, site.image, CArrayList(), names).also { minted -> + siblings.add(minted) + site.layerEntryList.add(minted) + } + site.folderByPath[path] = folder + return folder + } + + /** + * A group's child list, created (with its slot recorded) when the file omitted it. + * + * @param ACLayerGroup group The group. + * @return MutableList The list. + */ + private fun childrenOf(group: ACLayerGroup): MutableList = + // CMO3: ACLayerGroup field _children. + mutableGraphListOf(group._children) + ?: CArrayList().also { created -> + group._children = created + editor.ensureChildSlot(group, "ACLayerGroup", "_children") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3SkeletonBuilder.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3SkeletonBuilder.kt new file mode 100644 index 0000000..74f6aa2 --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3SkeletonBuilder.kt @@ -0,0 +1,349 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CLabelColor +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CAffecterSourceSet +import org.umamo.format.cmo3.model.gen.CArtPathBrushSetting +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CEffectParameterGroups +import org.umamo.format.cmo3.model.gen.CGameMotionSet +import org.umamo.format.cmo3.model.gen.CGuidesSetting +import org.umamo.format.cmo3.model.gen.CImageCanvas +import org.umamo.format.cmo3.model.gen.CLabelColorType +import org.umamo.format.cmo3.model.gen.CModelInfo +import org.umamo.format.cmo3.model.gen.CParameterGroup +import org.umamo.format.cmo3.model.gen.CParameterGroupSet +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CPartForm +import org.umamo.format.cmo3.model.gen.CPartSource +import org.umamo.format.cmo3.model.gen.CPartSourceSet +import org.umamo.format.cmo3.model.gen.CPhysicsSettingsSourceSet +import org.umamo.format.cmo3.model.gen.CPoint +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.EditorEdition +import org.umamo.format.cmo3.model.gen.KeyformGridAccessKey +import org.umamo.format.cmo3.model.gen.KeyformGridSource +import org.umamo.format.cmo3.model.gen.KeyformOnGrid +import org.umamo.format.cmo3.model.gen.ModelViewerSetting +import org.umamo.format.cmo3.model.gen.TextureImageGroup +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CColor +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.format.cmo3.type.CHashMap +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage + +/** + * Builds the blank CModelSource spine a fresh (never-read) CMO3 starts from, mirroring what the + * official editor writes for New -> Save As (BareMinimum.cmo3; docs/format/CMO3.md §3 The + * Blank-Model Skeleton). Everything content-bearing - parameters, parts, deformers, drawables, + * glues, the image chain - is deliberately absent: the reconcile exporter creates the model's own + * entities against this skeleton, and the image-chain builder populates the texture manager. + * + * Fields the modern editor always writes as explicit defaults (useOffscreen=false, + * invertClippingMask=false, an explicit null internalColor_direct_argb) emit on fresh objects + * too - their DontSerializeIfDefault annotations are hand-removed in the generated model, because + * the official reader's custom deserializers reject their absence. + * + * ERA NOTE, unresolved: seeding from BareMinimum means a fresh graph declares fileFormatVersion + * 504000000 (Cubism 5.4) even though a MOC3-origin conversion populates nothing 5.x and its + * targetVersionNo says SDK 4.0. Both files that are known to RENDER for the same model - Cubism's + * own golden (402030000) and a third-party converter's output (401030000) - are 4.x. The standing + * theory for the MOC3-origin render gap (see [Cmo3Conversion]) is that the 5.4 reader composites + * through the model-image web, so a merely shape-correct synthetic web is not enough, while a 4.x + * file draws straight from the atlas. Emitting an era-matched graph (4.x version PIs, dropping + * the 5.x-only fields) would test it; it was not pursued because the art-sourcing pipeline + * supersedes the whole synthetic path. + */ +internal object Cmo3SkeletonBuilder { + /** + * The root parameter group's well-known guid - identical across corpus files, never minted. + * CMO3: CParameterGroup rootParameterGroup guid (constant across eras; see CMO3.md §3). + */ + internal const val ROOT_PARAMETER_GROUP_UUID: String = "e9fe6eff-953b-4ce2-be7c-4a7c3913686b" + + /** The synthetic root part's id string. CMO3: CPartSource rootPart, CPartId idstr. */ + internal const val ROOT_PART_ID_STR: String = "__RootPart__" + + /** The root parameter group's id string. CMO3: CParameterGroupId idstr. */ + internal const val ROOT_PARAMETER_GROUP_ID_STR: String = "ParamGroupRoot" + + /** + * The editor's root-deformer marker uuid. + * + * CMO3: CDeformerGuid uuid + note "ROOT" - the same fixed uuid in every corpus file, written + * as an affecter's or root-level deformer's targetDeformerGuid. + */ + internal const val ROOT_DEFORMER_SENTINEL_UUID: String = "71fae776-e218-4aee-873e-78e8ac0cb48a" + + /** + * A fresh root-deformer sentinel guid (see ROOT_DEFORMER_SENTINEL_UUID). + * + * @return Guid The sentinel CDeformerGuid. + */ + internal fun rootDeformerSentinel(): Guid = + Guid("CDeformerGuid").apply { + uuid = ROOT_DEFORMER_SENTINEL_UUID + note = "ROOT" + } + + /** One embedded PNG the skeleton's icons reference: the archive entry path plus its bytes. */ + internal class IconEntry(val path: String, val pngBytes: ByteArray) + + /** The built spine: the fresh root object plus the icon PNGs its CImageIcons reference. */ + internal class BlankSkeleton(val root: CModelSource, val iconEntries: List) + + /** + * Builds the blank spine for a fresh document. + * + * @param String modelName The model's display name (CModelSource field name). + * @param Int canvasWidth The canvas width in pixels (CImageCanvas field pixelWidth). + * @param Int canvasHeight The canvas height in pixels (CImageCanvas field pixelHeight). + * @param Int targetVersionNo The persisted runtime target (CModelSource field targetVersionNo). + * @param RasterImage modelThumbnail The model's rest-pose thumbnail the three model icons fit, or + * null for the blank icons the editor writes for a model it never + * rendered (ModelWithOffscreenPartClipping carries exactly that). + * @return BlankSkeleton The fresh root plus icon PNG entries. + */ + internal fun buildBlank( + modelName: String, + canvasWidth: Int, + canvasHeight: Int, + targetVersionNo: Int, + modelThumbnail: RasterImage? = null, + ): BlankSkeleton { + val rootPart = buildRootPart() + val rootGroup = buildRootParameterGroup() + // CMO3: CModelSource fields _icon64 / _icon32 / _icon16 - backed by image.png, image_0.png, + // image_1.png in the blank default, the model's rendered thumbnail at each size. + val iconPaths = listOf("image.png", "image_0.png", "image_1.png") + val icons = + Cmo3Icons.MODEL_ICON_SIZES.mapIndexed { sizeIndex, size -> + IconEntry(iconPaths[sizeIndex], if (modelThumbnail == null) blankPng(size) else Cmo3Icons.iconPngOf(modelThumbnail, size)) + } + val root = + CModelSource().apply { + guid = freshGuid("CModelGuid") + name = modelName + // CMO3: CModelSource field editorEdition (BareMinimum writes edition 11). + editorEdition = EditorEdition().apply { edition = 11 } + canvas = + CImageCanvas().apply { + // CMO3: CImageCanvas fields pixelWidth/pixelHeight + empty CColor background. + pixelWidth = canvasWidth + pixelHeight = canvasHeight + background = CColor() + } + parameterSourceSet = CParameterSourceSet().apply { _sources = CArrayList() } + textureManager = + CTextureManager().apply { + // CMO3: CTextureManager - mandatory even when empty (BareMinimum). + textureList = TextureImageGroup().apply { children = CArrayList() } + _rawImages = CArrayList() + _modelImageGroups = CArrayList() + _textureAtlases = CArrayList() + // CMO3: CTextureManager field isTextureInputModelImageMode - the blank 5.4 document's + // own value. A skeleton has no drawables, so the mode selects nothing; whoever + // populates the image chain writes the document's real one over this. + isTextureInputModelImageMode = true + previewReductionRatio = 1 + artPathBrushUsingLayeredImageIds = CArrayList() + } + useLegacyDrawOrder__testImpl = false + drawableSourceSet = CDrawableSourceSet().apply { _sources = CArrayList() } + deformerSourceSet = CDeformerSourceSet().apply { _sources = CArrayList() } + affecterSourceSet = CAffecterSourceSet().apply { _sources = CArrayList() } + partSourceSet = CPartSourceSet().apply { _sources = CArrayList(mutableListOf(rootPart)) } + physicsSettingsSourceSet = + CPhysicsSettingsSourceSet().apply { + _sourceCubismPhysics = CArrayList() + // CMO3: CPhysicsSettingsSourceSet field settingFPS (BareMinimum writes 120). + settingFPS = 120 + } + this.rootPart = rootPart + parameterGroupSet = CParameterGroupSet().apply { _groups = CArrayList(mutableListOf(rootGroup)) } + rootParameterGroup = rootGroup + modelInfo = + CModelInfo().apply { + pixelsPerUnit = 1f + originInPixels = CPoint() + // CMO3: CEffectParameterGroups field _parameterGroups - a hash_map in every + // corpus file (keyType="string" when empty); the editor's field is Map-typed + // and rejects a list. + _effectParameterGroups = CEffectParameterGroups().apply { _parameterGroups = CHashMap() } + } + modelOptions = CHashMap() + _icon64 = Cmo3Icons.iconReferencing(64, icons[0].path) + _icon32 = Cmo3Icons.iconReferencing(32, icons[1].path) + _icon16 = Cmo3Icons.iconReferencing(16, icons[2].path) + gameMotionSet = + CGameMotionSet().apply { + gameMotions = CArrayList() + gameMotionGroups = CArrayList() + } + modelViewerSetting = ModelViewerSetting().apply { trackCursorSettings = ArrayList() } + guides = CGuidesSetting().apply { guidesModeling = CArrayList() } + this.targetVersionNo = targetVersionNo + // CMO3: CModelSource field latestVersionOfLastModelerNo (BareMinimum writes 5030000). + latestVersionOfLastModelerNo = 5030000 + artPathBrushesSetting = CArtPathBrushSetting().apply { brushes = CArrayList() } + // CMO3: CModelSource fields randomPoseSetting / motionSyncSettingsSet / + // modelStateSetSet - every 5.4 corpus file writes all three (empty when the + // features are unused), modelStateSetSet as the root's last child; its presence + // also drives the ModelStateSet:1 version PI. + randomPoseSetting = + org.umamo.format.cmo3.model.gen.CRandomPoseSettingManager().apply { + // CMO3: CRandomPoseSettingManager field _settings - array_list, unlike the + // carray_list sibling collections. + _settings = ArrayList() + } + motionSyncSettingsSet = + org.umamo.format.cmo3.model.gen.CMotionSyncSettingSourceSet().apply { + _settingSourceSetMotionSync = LinkedHashSet() + } + modelStateSetSet = + org.umamo.format.cmo3.model.gen.CModelStateSetSet().apply { + _modelStateSets = CArrayList() + } + } + return BlankSkeleton(root, icons) + } + + /** + * Builds the synthetic root part with its one-cell keyform grid (a single CPartForm at draw + * order 500, opacity 1), exactly the shape BareMinimum's __RootPart__ carries. + * + * @return CPartSource The fresh root part. + */ + private fun buildRootPart(): CPartSource { + val part = CPartSource() + val formGuid = freshGuid("CFormGuid") + val form = + CPartForm().apply { + guid = formGuid + _source = part + notes = "" + // CMO3: CPartForm fields drawOrder/opacity/multiplyColor/screenColor. + drawOrder = 500 + opacity = 1f + multiplyColor = identityMultiplyColor() + screenColor = identityScreenColor() + } + return part.apply { + localName = "Root Part" + isVisible = true + keyformGridSource = + KeyformGridSource().apply { + keyformsOnGrid = + ArrayList( + mutableListOf( + KeyformOnGrid().apply { + accessKey = KeyformGridAccessKey().apply { _keyOnParameterList = ArrayList() } + keyformGuid = formGuid + }, + ), + ) + keyformBindings = ArrayList() + } + keyformMorphTargetSet = emptyMorphTargetSet() + _extensions = CArrayList() + labelColor = undefinedLabelColor() + guid = freshGuid("CPartGuid") + id = Id("CPartId").apply { idstr = ROOT_PART_ID_STR } + keyforms = CArrayList(mutableListOf(form)) + defaultOrder_forEditor = 500 + partsEditColor = CColor() + _childGuids = CArrayList() + clipGuidList = CArrayList() + colorComposition = org.umamo.format.cmo3.model.gen.ColorComposition.NORMAL + alphaComposition = org.umamo.format.cmo3.model.gen.AlphaComposition.OVER + } + } + + /** + * Builds the root parameter group with its well-known constant guid. + * + * @return CParameterGroup The fresh root group. + */ + private fun buildRootParameterGroup(): CParameterGroup = + CParameterGroup().apply { + name = "Root Parameter Group" + description = "" + folderIsOpened = false + guid = + Guid("CParameterGroupGuid").apply { + uuid = ROOT_PARAMETER_GROUP_UUID + note = "Root Parameter Group" + } + _childGuids = CArrayList() + id = Id("CParameterGroupId").apply { idstr = ROOT_PARAMETER_GROUP_ID_STR } + labelColor = undefinedLabelColor() + } + + /** + * Mints a fresh guid of the given kind. + * + * @param String kind The typed guid tag (e.g. "CPartGuid"). + * @return Guid The fresh guid. + */ + internal fun freshGuid(kind: String): Guid = + Guid(kind).apply { + uuid = java.util.UUID.randomUUID().toString() + note = "(no debug info)" + } + + /** + * An empty morph-target set (empty targets + empty constraint set). + * + * @return Any The fresh KeyFormMorphTargetSet. + */ + internal fun emptyMorphTargetSet(): Any = + org.umamo.format.cmo3.model.gen.KeyFormMorphTargetSet().apply { + _morphTargets = CArrayList() + blendWeightConstraintSet = + org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraintSet().apply { _constraints = CArrayList() } + } + + /** + * The identity multiply tint (white, opaque). + * + * @return CFloatColor The fresh color. + */ + internal fun identityMultiplyColor(): org.umamo.format.cmo3.model.custom.CFloatColor = + org.umamo.format.cmo3.model.custom.CFloatColor().apply { + red = 1f + green = 1f + blue = 1f + alpha = 1f + } + + /** + * The identity screen tint (black, opaque). + * + * @return CFloatColor The fresh color. + */ + internal fun identityScreenColor(): org.umamo.format.cmo3.model.custom.CFloatColor = + org.umamo.format.cmo3.model.custom.CFloatColor().apply { alpha = 1f } + + /** + * The default label color (uncustomized, UNDEFINED type). + * + * @return CLabelColor The fresh label color. + */ + internal fun undefinedLabelColor(): CLabelColor = + CLabelColor().apply { + // CMO3: CLabelColor attr customizedColorInt (-1 = none) + CLabelColorType labelType. + customizedColorInt = -1 + labelType = CLabelColorType.UNDEFINED + } + + /** + * A fully transparent square PNG for the model icons. + * + * @param Int size The square dimension in pixels. + * @return ByteArray The encoded PNG. + */ + internal fun blankPng(size: Int): ByteArray = PngCodec.write(RasterImage(size, size, ByteArray(size * size * 4))) +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3SourceLayerWeb.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3SourceLayerWeb.kt new file mode 100644 index 0000000..9f3447b --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3SourceLayerWeb.kt @@ -0,0 +1,518 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.gen.CLayerGroup +import org.umamo.format.cmo3.model.gen.CLayerIdentifier +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.LayerSet +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.CRect +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import kotlin.math.roundToInt + +/* + * The real-layer half of a fresh image chain: what an artwork-origin document (a PSD, CLIP, or KRA + * the bridge opened) writes in place of the crop stand-in. One CLayeredImage per artwork file with + * the file's folders as CLayerGroups and one CLayer per tile holding the document's own raster for + * it, one CModelImage per tile at the layer's canvas origin, an entry on the tile's page for every + * placed tile, and a binding for every drawable over it - the shape the official editor writes when + * it imports a PSD, so the file reopens in either editor with its real art and, through the Photoshop + * layer ids, re-imports against the PSD by key. + */ + +/** + * The real-layer web writer. [inputsOf] routes a puppet's tiles into per-file inputs, and [write] + * mints one file's web into the texture manager the caller is populating. + */ +internal object Cmo3SourceLayerWeb { + /** + * One tile with real art, as the conversion routes it here. + * + * @property String tileId The tile's id. + * @property String name The layer's name, which is the tile's. + * @property String layerKey The binding key; a "lyid:" key writes Photoshop's layer id. + * @property String groupPath The folder path in the file, "" at the root. + * @property Boolean visible The layer's visibility as last read. + * @property Int canvasLeft The art frame's canvas x - the inventory row's origin. + * @property Int canvasTop The art frame's canvas y. + * @property RasterImage raster The tile's pixels, straight alpha. + * @property AtlasPlacement? placement Where the tile sits on its page, or null when unpacked. + * @property List drawableIds The drawables sampling the tile, in document order. + * @property Map artUvsByDrawableId Each drawable's texture coordinates in the tile's + * own frame, for the patch its icon shows; a drawable absent here shows the whole layer. + */ + internal class SourceLayerInput( + val tileId: String, + val name: String, + val layerKey: String, + val groupPath: String, + val visible: Boolean, + val canvasLeft: Int, + val canvasTop: Int, + val raster: RasterImage, + val placement: AtlasPlacement?, + val drawableIds: List, + val artUvsByDrawableId: Map = emptyMap(), + ) + + /** + * One artwork file with those of its tiles that have real art, in the file's layer order. + * + * @property String name The file's display name. + * @property String? path The file's recorded path, or null when the record has none. + * @property Long? lastModified The file's modification time as last read, or null. + * @property Int width The frame the layers' canvas coordinates live in. + * @property Int height Its height. + * @property List layers The tiles to write as layers. + */ + internal class SourceImageInput( + val name: String, + val path: String?, + val lastModified: Long?, + val width: Int, + val height: Int, + val layers: List, + ) + + /** + * What one file's web produced. + * + * @property LayeredImageWrapper wrapper The layered image, for the texture manager's raw-image list. + * @property CModelImageGroup group The file's model-image group. + * @property Map bindingByDrawableId The texture web of every drawable over a placed tile. + */ + internal class Written( + val wrapper: LayeredImageWrapper, + val group: CModelImageGroup, + val bindingByDrawableId: Map, + ) + + /** + * Routes [puppet]'s tiles into per-file inputs: every tile bound to a listed file whose binding + * names an inventory row (present or lost - its tile still holds the art) and for which + * [tileRasters] has pixels, in the file's inventory order. A tile nothing samples is still a + * layer of its file; a tile with no row or no raster is left to the crop path. + * + * The layered image's frame is the document canvas: an import sets the canvas from the art, and + * the inventory's canvas coordinates live in that frame - a later file's rows already carry the + * offset it was placed by (ArtSource.offsetX), so they are written as they are. The CMO3 keeps + * no such offset of its own, so a document reopened from the export reads every file at offset 0. + * + * @param PuppetModel puppet The model being converted. + * @param Function tileRasters The document's pixels for a tile, or null. + * @return List One input per file with at least one real tile, in the model's source order. + */ + internal fun inputsOf(puppet: PuppetModel, tileRasters: (AtlasTileId) -> RasterImage?): List { + val drawableIdsByTile = HashMap>() + val artUvsByTile = HashMap>() + for (drawable in puppet.drawables) { + val tileId = drawable.atlasTileId ?: continue + drawableIdsByTile.getOrPut(tileId) { ArrayList() }.add(drawable.id.raw) + Cmo3Icons.artUvsOf(puppet, drawable)?.let { artUvs -> artUvsByTile.getOrPut(tileId) { HashMap() }[drawable.id.raw] = artUvs } + } + val canvasWidth = puppet.canvasWidth.roundToInt() + val canvasHeight = puppet.canvasHeight.roundToInt() + val images = ArrayList() + for (source in puppet.sources) { + val rowIndexByKey = HashMap() + for ((rowIndex, row) in source.layers.withIndex()) { + rowIndexByKey.putIfAbsent(row.key, rowIndex) + } + val ordered = ArrayList>() + for (tile in puppet.atlas.tiles) { + val ref = tile.source ?: continue + if (ref.sourceId != source.id) { + continue + } + val rowIndex = rowIndexByKey[ref.layerKey] ?: continue + val row = source.layers[rowIndex] + val raster = tileRasters(tile.id) ?: continue + ordered.add( + rowIndex to + SourceLayerInput( + tileId = tile.id.raw, + name = tile.name, + layerKey = ref.layerKey, + groupPath = row.groupPath, + visible = row.visible, + canvasLeft = row.left, + canvasTop = row.top, + raster = raster, + placement = tile.placement, + drawableIds = drawableIdsByTile[tile.id].orEmpty(), + artUvsByDrawableId = artUvsByTile[tile.id].orEmpty(), + ), + ) + } + if (ordered.isEmpty()) { + continue + } + // A stable sort: two tiles bound to one row (a double binding) keep their atlas order. + images.add(SourceImageInput(source.name, source.path, source.lastModified, canvasWidth, canvasHeight, ordered.sortedBy { (rowIndex, _) -> rowIndex }.map { (_, layer) -> layer })) + } + return images + } + + /** + * Writes one file's web: the layered image with its folder tree and layers, the model-image group + * with one image per layer, an entry on each placed tile's atlas, and the bindings. + * + * @param SourceImageInput image The file and its tiles. + * @param List atlases The pages' atlas elements, in model page order. + * @param List textures The pages' shared textures, index-parallel to [atlases]. + * @param Cmo3FreshChainNames names The document's shared definitions and naming counters. + * @param MutableList pngEntries The PNG entry collector. + * @param Long nowMillis The import timestamp the wrapper and env values record, standing in + * for a time the record lacks. + * @return Written The wrapper, the group, and the bindings. + */ + internal fun write( + image: SourceImageInput, + atlases: List, + textures: List, + names: Cmo3ImageChainBuilder.Cmo3FreshChainNames, + pngEntries: MutableList, + nowMillis: Long, + ): Written { + val minted = mintLayeredImage(image.name, image.path, image.lastModified, image.width, image.height, names, nowMillis) + val layeredImage = minted.image + val rootChildren = minted.rootChildren + val rootGroup = minted.rootGroup + val layerEntryList = minted.layerEntryList + val group = mintModelImageGroup(image.name, layeredImage) + val groupModelImages = checkNotNull(mutableGraphListOf(group._modelImages)) { "mintModelImageGroup builds a list" } + // Folders are minted on first encounter along each layer's path, so only the folders that + // hold a written layer exist, nested the way the file nests them. + val childrenByPath = HashMap>() + val groupByPath = HashMap() + childrenByPath[""] = rootChildren + groupByPath[""] = rootGroup + + fun folderAt(path: String): CLayerGroup { + groupByPath[path]?.let { existing -> return existing } + val parentPath = path.substringBeforeLast('/', "") + folderAt(parentPath) + val children = CArrayList() + val folder = layerGroup(path.substringAfterLast('/'), layeredImage, children, names) + childrenByPath.getValue(parentPath).add(folder) + layerEntryList.add(folder) + childrenByPath[path] = children + groupByPath[path] = folder + return folder + } + val bindings = HashMap() + for (layerInput in image.layers) { + val raster = layerInput.raster + val pngBytes = PngCodec.write(raster) + val path = names.nextImageFileBufPath() + pngEntries.add(Cmo3FreshFile.PngEntry(path, pngBytes)) + val resource = layerResource(path, raster, pngBytes.size) + val folder = folderAt(layerInput.groupPath) + val layer = + layerOver( + name = layerInput.name, + layerKey = layerInput.layerKey, + visible = layerInput.visible, + canvasLeft = layerInput.canvasLeft, + canvasTop = layerInput.canvasTop, + resource = resource, + raster = raster, + layeredImage = layeredImage, + folder = folder, + names = names, + pngEntries = pngEntries, + ) + childrenByPath.getValue(layerInput.groupPath).add(layer) + layerEntryList.add(layer) + val modelImage = Cmo3ImageChainBuilder.modelImageOver(layerInput.name, layeredImage, layer, resource, raster, layerPlacement(layerInput.canvasLeft, layerInput.canvasTop), group, names, pngEntries, nowMillis) + groupModelImages.add(modelImage) + val tilePlacement = layerInput.placement ?: continue + val atlas = atlases.getOrNull(tilePlacement.pageIndex) ?: continue + val texture = textures[tilePlacement.pageIndex] + // The entry pair: the packing as the placement records it, and the atlas-to-canvas half + // composed so the two compose back to the layer's translation. Every drawable over the + // tile carries the entry's transform as its region input, the official relation - a + // duplicate moved elsewhere keeps sampling the same tile, as a Cubism duplicate does. + val canvasAffine = floatArrayOf(1f, 0f, layerInput.canvasLeft.toFloat(), 0f, 1f, layerInput.canvasTop.toFloat()) + val entryHalf = atlasLocalToCanvasFor(canvasAffine, tilePlacement) ?: continue + checkNotNull(mutableGraphListOf(atlas.modelImages)) { "pageAtlas builds a list" }.add( + Cmo3ImageChainBuilder.packedEntry( + atlas = atlas, + modelImageGuid = modelImage.guid, + atlasLocalToCanvas = affineOf(entryHalf), + packing = Cmo3ImageChainBuilder.writePacking(GTransform2(), tilePlacement), + ), + ) + for (drawableId in layerInput.drawableIds) { + // The drawable's icons show the patch its mesh covers on the layer, one icon per + // drawable like the editor's files. + val patch = Cmo3Icons.patchOf(raster, layerInput.artUvsByDrawableId[drawableId]) + bindings[drawableId] = + Cmo3DrawableTextureBinding( + texture, + atlas.guid as Guid, + modelImage.guid as Guid, + affineOf(entryHalf), + icon32 = Cmo3Icons.iconOf(patch, 32, names.nextIconPath(), pngEntries), + icon16 = Cmo3Icons.iconOf(patch, 16, names.nextIconPath(), pngEntries), + ) + } + } + return Written(minted.wrapper, group, bindings) + } + + /** + * A freshly minted layered image with the lists a layer is added through. + * + * @property LayeredImageWrapper wrapper The wrapper, for the texture manager's raw-image list. + * @property CLayeredImage image The layered image. + * @property CLayerGroup rootGroup Its root folder. + * @property CArrayList rootChildren The root folder's child list. + * @property CArrayList layerEntryList The flat entry list every group and layer joins. + */ + internal class MintedLayeredImage( + val wrapper: LayeredImageWrapper, + val image: CLayeredImage, + val rootGroup: CLayerGroup, + val rootChildren: CArrayList, + val layerEntryList: CArrayList, + ) + + /** + * Mints one artwork file's layered image: the document frame, the file reference, an empty root + * folder, and the flat entry list, wrapped for the texture manager's raw-image list. Shared by the + * fresh web and the retained-graph mint, so a file added to a retained document takes the same + * shape as one in a fresh export. + * + * @param String name The file's display name. + * @param String? path The file's recorded path, or null when the record has none. + * @param Long? lastModified The file's modification time as last read, or null. + * @param Int width The frame the layers' canvas coordinates live in. + * @param Int height Its height. + * @param Cmo3FreshChainNames names The document's shared blend and options. + * @param Long nowMillis The import timestamp, standing in for a time the record lacks. + * @return MintedLayeredImage The image and its lists. + */ + internal fun mintLayeredImage( + name: String, + path: String?, + lastModified: Long?, + width: Int, + height: Int, + names: Cmo3ImageChainBuilder.Cmo3FreshChainNames, + nowMillis: Long, + ): MintedLayeredImage { + val layeredImage = CLayeredImage() + val rootChildren = CArrayList() + val rootGroup = layerGroup("root", layeredImage, rootChildren, names) + val layerEntryList = CArrayList(mutableListOf(rootGroup)) + layeredImage.apply { + this.name = name + memo = "" + // CMO3: CLayeredImage fields width / height - the source document's own frame; the + // inventory's canvas coordinates live in the document canvas, so that is the frame here. + this.width = width + this.height = height + // CMO3: CLayeredImage field psdFile - the external-reference shape whose text is the + // source's path on the importing machine; the name stands in when the record has none. + psdFile = FileRef().apply { textPath = path ?: name } + description = "" + guid = Cmo3SkeletonBuilder.freshGuid("CLayeredImageGuid") + // CMO3: CLayeredImage field psdFileLastModified - the source's modification time as last read. + psdFileLastModified = lastModified ?: nowMillis + _rootLayer = rootGroup + layerSet = + LayerSet().apply { + _layeredImage = layeredImage + _layerEntryList = layerEntryList + } + } + val wrapper = + LayeredImageWrapper().apply { + image = layeredImage + importedTimeMSec = nowMillis + lastModifiedTimeMSec = lastModified ?: nowMillis + } + return MintedLayeredImage(wrapper, layeredImage, rootGroup, rootChildren, layerEntryList) + } + + /** + * A file's model-image group, linked to its layered image and empty of images. + * + * @param String name The file's display name, which the group takes. + * @param CLayeredImage layeredImage The file's layered image. + * @return CModelImageGroup The group. + */ + internal fun mintModelImageGroup(name: String, layeredImage: CLayeredImage): CModelImageGroup = + CModelImageGroup().apply { + // CMO3: CModelImageGroup fields groupName / _linkedRawImageGuids / _modelImages. + memo = "" + groupName = name + _linkedRawImageGuids = CArrayList(mutableListOf(layeredImage.guid)) + _modelImages = CArrayList() + } + + /** + * A layer's own image resource: the raster's dimensions, type, and archive link. + * + * @param String path The archive path the layer PNG is stored under. + * @param RasterImage raster The layer's pixels. + * @param Int pngSize The encoded PNG's byte size. + * @return CImageResource The resource. + */ + internal fun layerResource(path: String, raster: RasterImage, pngSize: Int): CImageResource = + CImageResource().apply { + // CMO3: CImageResource - the layer's own pixels, the document's raster for the tile. + width = raster.width + height = raster.height + type = "INT_ARGB" + imageFileBuf = FileRef().apply { archivePath = path } + imageFileBuf_size = pngSize + } + + /** + * A tile's layer on its file's document: the name, visibility, resource, rect, identifier, and + * icons the official editor writes for a PSD layer. Shared by the fresh web and the + * retained-graph mint, so a layer minted into a retained file is field-for-field the fresh shape. + * + * @param String name The layer's name. + * @param String layerKey The binding key; a "lyid:" key writes Photoshop's layer id. + * @param Boolean visible The layer's visibility. + * @param Int canvasLeft The art frame's canvas x. + * @param Int canvasTop The art frame's canvas y. + * @param CImageResource resource The layer's own resource. + * @param RasterImage raster The resource's pixels, which the icons show fitted. + * @param CLayeredImage layeredImage The owning layered image. + * @param CLayerGroup folder The folder the layer sits in. + * @param Cmo3FreshChainNames names The document's shared blend, options, and icon paths. + * @param MutableList pngEntries The PNG entry collector, for the icons. + * @return CLayer The layer, not yet added to any list. + */ + internal fun layerOver( + name: String, + layerKey: String, + visible: Boolean, + canvasLeft: Int, + canvasTop: Int, + resource: CImageResource, + raster: RasterImage, + layeredImage: CLayeredImage, + folder: CLayerGroup, + names: Cmo3ImageChainBuilder.Cmo3FreshChainNames, + pngEntries: MutableList, + ): CLayer = + CLayer().apply { + // CMO3: CLayer - the tile's layer on the file's document. + this.name = name + memo = "" + isVisible = visible + blend = names.sharedBlend + guid = Cmo3SkeletonBuilder.freshGuid("CLayerGuid") + opacity255 = 255 + _optionOfIOption = names.sharedOptions + _layeredImage = layeredImage + imageResource = resource + // CMO3: CLayer field boundsOnImageDoc - the layer's rect on the document: the art frame's + // canvas origin, the raster's size (the two invariants every corpus layer obeys: origin = + // the model image's canvas placement, size = the resource dims). + boundsOnImageDoc = layerBounds(canvasLeft, canvasTop, resource.width, resource.height) + layerIdentifier = identifierOf(name, layerKey) + // CMO3: CLayer fields icon16 / icon64 - thumbnails on every corpus layer, the whole + // layer fitted into each square. + icon16 = Cmo3Icons.iconOf(raster, 16, names.nextIconPath(), pngEntries) + icon64 = Cmo3Icons.iconOf(raster, 64, names.nextIconPath(), pngEntries) + layerInfo = LinkedHashMap() + this.group = folder + } + + /** + * A layer's rect on its document. + * + * @param Int left The origin x. + * @param Int top The origin y. + * @param Int width The width. + * @param Int height The height. + * @return CRect The rect. + */ + internal fun layerBounds(left: Int, top: Int, width: Int, height: Int): CRect = + CRect().apply { + x = left + y = top + this.width = width + this.height = height + } + + /** + * A model image's canvas placement for a layer: upright canvas-space art, a pure translation to + * the layer's origin - the invariant every corpus model image carries; the packer's work rides the + * entry. + * + * @param Int canvasLeft The layer's canvas x. + * @param Int canvasTop The layer's canvas y. + * @return CAffine The placement, an independent instance. + */ + internal fun layerPlacement(canvasLeft: Int, canvasTop: Int): CAffine = + CAffine().apply { + m02 = canvasLeft.toFloat() + m12 = canvasTop.toFloat() + } + + /** + * A folder of the layered image: a group element over [children]. + * + * @param String name The folder's name (one path segment, "root" for the root). + * @param CLayeredImage layeredImage The owning layered image. + * @param CArrayList children The list the folder's layers and sub-folders go into. + * @param Cmo3FreshChainNames names The document's shared blend and options. + * @return CLayerGroup The group. + */ + internal fun layerGroup(name: String, layeredImage: CLayeredImage, children: CArrayList, names: Cmo3ImageChainBuilder.Cmo3FreshChainNames): CLayerGroup = + CLayerGroup().apply { + // CMO3: CLayerGroup - a folder of the decomposed file; ACLayerGroup field _children. + this.name = name + memo = "" + isVisible = true + blend = names.sharedBlend + guid = Cmo3SkeletonBuilder.freshGuid("CLayerGuid") + opacity255 = 255 + _optionOfIOption = names.sharedOptions + _layeredImage = layeredImage + _children = children + } + + /** + * The layer's identifier: its name, and Photoshop's layer id when the binding key carries one. + * + * @param String name The layer's name. + * @param String layerKey The binding key. + * @return CLayerIdentifier The identifier. + */ + internal fun identifierOf(name: String, layerKey: String): CLayerIdentifier = + CLayerIdentifier().apply { + layerName = name + val photoshopId = layerKey.takeIf { key -> key.startsWith("lyid:") }?.removePrefix("lyid:")?.toIntOrNull() + if (photoshopId == null) { + // A CLIP or KRA uuid has no home in a CMO3, so a reopened export keys the layer by name. + layerIdValue_testImpl = -1 + } else { + // CMO3: CLayerIdentifier field layerId - Photoshop's lyid as four dash-separated hex + // bytes, big-endian (the form the atlas ingest parses); layerIdValue_testImpl mirrors + // it in decimal. + layerId = (3 downTo 0).joinToString("-") { shift -> ((photoshopId ushr (shift * 8)) and 0xFF).toString(16).padStart(2, '0') } + layerIdValue_testImpl = photoshopId + } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3StructureLowering.kt b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3StructureLowering.kt new file mode 100644 index 0000000..11917cb --- /dev/null +++ b/module/interop/src/jvmAndroidMain/kotlin/org/umamo/interop/cmo3/Cmo3StructureLowering.kt @@ -0,0 +1,821 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3GraphEditor +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.GEditableMesh2 +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CEditableMeshExtension +import org.umamo.format.cmo3.model.gen.CParameterGroup +import org.umamo.format.cmo3.model.gen.CParameterGroupSet +import org.umamo.format.cmo3.model.gen.CParameterSource +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage +import org.umamo.format.cmo3.model.gen.Type +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.type.CArrayList +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.partByDrawable +import org.umamo.runtime.model.storedToArtAffineForTile + +/* + * The structural half of the CMO3 export reconcile: set membership. Creations synthesize an + * IDENTITY SHELL only (fresh guid/id, the texture/extension chain a duplicate shares with its + * source) and are appended to their source set; the caller then routes the new entity through the + * ordinary Changed lowering with every field flagged, so field writes flow through the one tested + * path rather than a parallel synthesis copy. Deletions remove the source AND strip its guid from + * every parts-panel child list (a removed guid the org rebuild would otherwise preserve as an + * unknown entry); the dangling cross-references (masks, axes, glues) fall out of the model-driven + * Changed diffs, and the shared pool is pruned once at the end. + * + * Topology rewrites and glue vertex re-binding also live here: they regenerate the GEditableMesh2 + * identity surface (point mirror, fresh vertex uids, the triangle edge set) that the rest of the + * document hangs off. + */ +internal class Cmo3StructureLowering( + private val modelSource: CModelSource, + private val index: Cmo3GraphIndex, + private val editor: Cmo3GraphEditor, + private val edited: PuppetModel, + private val notices: MutableList, + // The document's texture frames, taken from the graph before the export changed it. + private val textureFrames: Cmo3TextureFrames, + private val drawableBindings: Map = emptyMap(), +) { + /** True once any deletion ran - the caller prunes the shared pool exactly once at the end. */ + var deletedAnything: Boolean = false + private set + + private fun unsupported( + category: ExportEntityCategory, + subject: String?, + reason: ExportNoticeReason, + ) { + notices.add(ExportNotice.UnsupportedChange(category, subject, reason)) + } + + private fun freshGuidLike(template: Guid?, fallbackKind: String): Guid = + Guid(template?.kind ?: fallbackKind).apply { + uuid = java.util.UUID.randomUUID().toString() + note = template?.note ?: "(no debug info)" + } + + /** + * The shared CoordType every fresh editable mesh gets. + * + * CMO3: GEditableMesh2 field coordType - corpus meshes always carry a CoordType with coordName + * "Basic Coord"; one instance is reused so the writer hoists a single shared def. + */ + private val basicCoordType: org.umamo.format.cmo3.model.drawable.CoordType by lazy { + org.umamo.format.cmo3.model.drawable.CoordType().apply { coordName = "Basic Coord" } + } + + private fun freshIdLike(template: Id?, fallbackKind: String, idStr: String): Id = + Id(template?.kind ?: fallbackKind).apply { idstr = idStr } + + private fun appendToCollection(owner: Any, ownerTag: String, property: String, current: Any?, assign: (MutableList) -> Unit, element: Any) { + val mutable = mutableGraphListOf(current) + if (mutable != null) { + mutable.add(element) + return + } + // Every field this helper serves (_sources, _groups, _childGuids) is carray_list in every + // corpus model; the official editor's deserializers cast such fields to CArrayList, so an + // array_list tag fails its load. + val fresh: MutableList = CArrayList() + fresh.add(element) + assign(fresh) + editor.ensureChildSlot(owner, ownerTag, property) + } + + private fun removeFromCollection(current: Any?, matches: (Any?) -> Boolean): Boolean { + val mutable = mutableGraphListOf(current) ?: return false + return mutable.removeAll(matches) + } + + /** Strips [uuid] from every parts-panel child list (all user parts plus the synthetic root). */ + private fun stripFromChildLists(uuid: String?) { + if (uuid == null) { + return + } + val parts = index.userPartSources + listOfNotNull(index.rootPartSource) + for (part in parts) { + mutableGraphListOf(part._childGuids)?.removeAll { entry -> Cmo3Import.uuidOf(entry) == uuid } + } + } + + /** + * Synthesizes the identity shell for a created parameter and appends it in document order (the + * PARAMETER_ORDER lowering re-sorts afterwards). + * + * @param Parameter editedParameter The created parameter. + * @return Boolean True on success. + */ + fun synthesizeParameter(editedParameter: Parameter): Boolean { + val sourceSet = modelSource.parameterSourceSet as? CParameterSourceSet + if (sourceSet == null) { + unsupported(ExportEntityCategory.Parameter, editedParameter.id.raw, ExportNoticeReason.NoSourceSetToCreateInto) + return false + } + val template = index.parameterSources.firstOrNull() + val fresh = + CParameterSource().apply { + // CMO3: CParameterSource - identity plus the editor conventions cloned from a sibling + // (decimal places, snap epsilon, the explicit paramType). + guid = freshGuidLike(template?.guid as? Guid, "CParameterGuid") + id = freshIdLike(template?.id as? Id, "CParameterId", editedParameter.id.raw) + decimalPlaces = template?.decimalPlaces ?: 3 // Documented default from surveying 50+ CMO3 files. + snapEpsilon = template?.snapEpsilon ?: 0.001f // Documented default from surveying 50+ CMO3 files. + minValue = editedParameter.min + maxValue = editedParameter.max + defaultValue = editedParameter.default + isRepeat = false + // CMO3: CParameterSource fields paramType / description - a Type element plus the + // (possibly empty) description string on every corpus parameter, never null. + paramType = if (editedParameter.kind == ParameterKind.BLEND_SHAPE) Type.MORPH_TARGET else template?.paramType ?: Type.NORMAL + description = "" + name = editedParameter.name + combined = false + parentGroupGuid = index.rootParameterGroup?.guid + } + appendToCollection(sourceSet, "CParameterSourceSet", "_sources", sourceSet._sources, { sourceSet._sources = it }, fresh) + return true + } + + /** Removes a deleted parameter's source. */ + fun deleteParameter(parameterId: ParameterId) { + val sourceSet = modelSource.parameterSourceSet as? CParameterSourceSet ?: return + if (removeFromCollection(sourceSet._sources) { entry -> + entry is CParameterSource && Cmo3Import.idStrOf(entry.id) == parameterId.raw + } + ) { + deletedAnything = true + } + } + + /** + * Synthesizes the identity shell for a created parameter group. + * + * @param ParameterGroupId groupId The created group's id. + * @return Boolean True on success. + */ + fun synthesizeParameterGroup(groupId: ParameterGroupId): Boolean { + val groupSet = modelSource.parameterGroupSet as? CParameterGroupSet + if (groupSet == null) { + unsupported(ExportEntityCategory.ParameterGroup, groupId.raw, ExportNoticeReason.NoSourceSetToCreateInto) + return false + } + val editedGroup = findEditedGroup(groupId) + if (editedGroup == null) { + unsupported(ExportEntityCategory.ParameterGroup, groupId.raw, ExportNoticeReason.CreatedGroupIsNotInTheEditedTree) + return false + } + val template = index.groupSources.firstOrNull() ?: index.rootParameterGroup + val fresh = + CParameterGroup().apply { + // CMO3: CParameterGroup - identity shell; name/open state/children flow through the + // ordinary group lowering. + guid = freshGuidLike(template?.guid as? Guid, "CParameterGroupGuid") + id = freshIdLike(template?.id as? Id, "CParameterGroupId", groupId.raw) + name = editedGroup.name + // CMO3: CParameterGroup fields description / labelColor - present on every corpus + // group, never null. + description = "" + labelColor = Cmo3SkeletonBuilder.undefinedLabelColor() + folderIsOpened = editedGroup.initiallyOpen + _childGuids = CArrayList() + parentGroupGuid = index.rootParameterGroup?.guid + } + appendToCollection(groupSet, "CParameterGroupSet", "_groups", groupSet._groups, { groupSet._groups = it }, fresh) + return true + } + + /** Removes a deleted parameter group's source. */ + fun deleteParameterGroup(groupId: ParameterGroupId) { + val groupSet = modelSource.parameterGroupSet as? CParameterGroupSet ?: return + if (removeFromCollection(groupSet._groups) { entry -> + entry is CParameterGroup && Cmo3Import.idStrOf(entry.id) == groupId.raw + } + ) { + deletedAnything = true + } + } + + /** + * Synthesizes the identity shell for a session-created drawable (an Object-mode duplicate): + * fresh guid/id and editable mesh, the texture binding SHARED with its texture source (the + * atlas slot both render from; no new CAFF entry). Geometry, keyforms, and every flat field + * flow through the ordinary Changed lowering afterwards. + * + * @param Drawable editedDrawable The created drawable. + * @return Boolean True on success. + */ + fun synthesizeDrawable(editedDrawable: Drawable): Boolean { + val subject = editedDrawable.id.raw + val sourceSet = modelSource.drawableSourceSet as? org.umamo.format.cmo3.model.gen.CDrawableSourceSet + if (sourceSet == null) { + unsupported(ExportEntityCategory.Drawable, subject, ExportNoticeReason.NoSourceSetToCreateInto) + return false + } + val textureSource = editedDrawable.textureSourceId?.let { index.drawableByIdStr[it.raw] } + val binding = drawableBindings[subject] + if (textureSource == null && binding == null) { + unsupported(ExportEntityCategory.Drawable, subject, ExportNoticeReason.CreatedDrawableHasNoTextureSource) + return false + } + val templateMesh = textureSource?.let(Cmo3Import::editableMeshOf) + val ownerPartId = edited.partByDrawable()[editedDrawable.id] + val ownerGuid = ownerPartId?.let { index.partByIdStr[it.raw]?.guid } ?: index.rootPartSource?.guid + val fresh = CArtMeshSource() + fresh.apply { + guid = freshGuidLike(textureSource?.guid as? Guid, "CDrawableGuid") + id = freshIdLike(textureSource?.id as? Id, "CDrawableId", subject) + parentGuid = ownerGuid + // CMO3: ACParameterControllableSource fields keyformMorphTargetSet / labelColor and + // CArtMeshSource field userData - present on every corpus drawable, never omitted. + keyformMorphTargetSet = Cmo3SkeletonBuilder.emptyMorphTargetSet() + labelColor = Cmo3SkeletonBuilder.undefinedLabelColor() + userData = "" + // CMO3: ACDrawableSource fields icon32 / icon16 - the drawable's own thumbnails of its + // texture patch, minted by whoever built the binding; a drawable with no binding (a clone + // of a source with no art of its own) carries none. + icon32 = binding?.icon32 + icon16 = binding?.icon16 + if (textureSource != null) { + // CMO3: CArtMeshSource identity shell. The texture and texture-input extension are + // the SOURCE drawable's own objects (the writer hoists the shared references), so the + // duplicate samples the same atlas slot without new image-chain entries. + texture = textureSource.texture + textureState = textureSource.textureState + } else { + // CMO3: the fresh-graph binding - the page's SHARED GTexture2D plus a per-drawable + // CTextureInput_TextureAtlasRegion, so UVs stay in the atlas frame (hasAtlasRegion). + texture = binding!!.texture + textureState = org.umamo.format.cmo3.model.gen.TextureState.TEXTURE_ATLAS + } + _extensions = + CArrayList().apply { + if (textureSource != null) { + Cmo3Import.elementsOf(textureSource._extensions) + .filterIsInstance() + .firstOrNull() + ?.let(::add) + } else { + add(freshTextureInputExtension(fresh, binding!!, editedDrawable.name)) + } + add( + CEditableMeshExtension().apply { + guid = freshGuidLike(null, "CExtensionGuid") + // CMO3: ACExtension field _owner - the owning drawable source; every + // corpus extension carries the backref. + _owner = fresh + editableMesh = + GEditableMesh2().apply { + // CMO3: GEditableMesh2 field meshGuid - kind GEditableMeshGuid + // (com.live2d.type.GEditableMeshGuid); no corpus file ever emits a + // CMeshGuid tag, so that kind would author an unimportable class. + meshGuid = freshGuidLike(templateMesh?.meshGuid as? Guid, "GEditableMeshGuid") + // CMO3: GEditableMesh2 field coordType - corpus meshes always + // carry "Basic Coord" (never null). + coordType = templateMesh?.coordType ?: basicCoordType + useDelaunayTriangulation = false + } + }, + ) + } + } + appendToCollection(sourceSet, "CDrawableSourceSet", "_sources", sourceSet._sources, { sourceSet._sources = it }, fresh) + return true + } + + /** + * Builds the per-drawable texture-input extension for a fresh-graph binding: both input kinds + * (model image + atlas region), with the one the document's display mode samples made active, + * mirroring the editor's packed drawables. + * + * @param CArtMeshSource owner The drawable source under construction. + * @param Cmo3DrawableTextureBinding binding The drawable's texture web (page texture + patch). + * @param String subjectName The drawable's display name, naming it in the display-mode notice. + * @return CTextureInputExtension The fresh extension. + */ + private fun freshTextureInputExtension( + owner: CArtMeshSource, + binding: Cmo3DrawableTextureBinding, + subjectName: String, + ): CTextureInputExtension { + val extension = CTextureInputExtension() + val atlasRegion = + org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion().apply { + // CMO3: CTextureInput_TextureAtlasRegion fields textureAtlasGuid + + // inputImageLocalToCanvasTransform (ACTextureInput super carries the owner backref). + // The transform places the atlas page's pixel frame on the canvas so this drawable's + // texture patch coincides with its base mesh - the editor inverts it to draw the mesh + // over the texture in the atlas and mesh-edit views. + optionalTransformOnCanvas = CAffine() + _owner = extension + textureAtlasGuid = binding.textureAtlasGuid + inputImageLocalToCanvasTransform = binding.inputImageLocalToCanvasTransform + } + val modelImage = + binding.modelImageGuid?.let { imageGuid -> + org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage().apply { + // CMO3: CTextureInput_ModelImage field _modelImageGuid. + optionalTransformOnCanvas = CAffine() + _owner = extension + _modelImageGuid = imageGuid + } + } + // A layer-mode document whose created drawable has no model image keeps the atlas region active: + // it is the only input such a drawable has, and leaving the live pointer there is what keeps the + // file self-consistent. The notice names the gap, matching what the property lowering reports + // for an EXISTING drawable in the same state - one reason, reported the same way from both paths. + if (edited.rendersFromSourceLayers && modelImage == null) { + unsupported(ExportEntityCategory.Drawable, subjectName, ExportNoticeReason.NoTextureInputForDisplayMode) + } + return extension.apply { + guid = freshGuidLike(null, "CExtensionGuid") + _owner = owner + _textureInputs = + CArrayList().apply { + modelImage?.let(::add) + add(atlasRegion) + } + // CMO3: CTextureInputExtension field currentTextureInputData - which input the document's + // display mode samples. A drawable created in a layer-mode document must point at its model + // image, or the file's flag and its drawables disagree. + currentTextureInputData = + if (edited.rendersFromSourceLayers) { + modelImage ?: atlasRegion + } else { + atlasRegion + } + } + } + + /** + * Synthesizes the identity shell for a created part: the super web plus a one-cell keyform grid + * with a single CPartForm, so static draw-order/opacity/composite writes have a form to land in + * (the field lowering only fills EXISTING part forms). Panel placement flows from the parent's + * CHILDREN rebuild. + * + * @param Part editedPart The created part. + * @return Boolean True on success. + */ + fun synthesizePart(editedPart: org.umamo.runtime.model.Part): Boolean { + val sourceSet = modelSource.partSourceSet as? org.umamo.format.cmo3.model.gen.CPartSourceSet + if (sourceSet == null) { + unsupported(ExportEntityCategory.Part, editedPart.id.raw, ExportNoticeReason.NoSourceSetToCreateInto) + return false + } + val template = index.userPartSources.firstOrNull() ?: index.rootPartSource + val part = org.umamo.format.cmo3.model.gen.CPartSource() + val formGuid = freshGuidLike(null, "CFormGuid") + val form = + org.umamo.format.cmo3.model.gen.CPartForm().apply { + // CMO3: CPartForm - the one default-cell form (drawOrder/opacity/colors). + guid = formGuid + _source = part + notes = "" + drawOrder = editedPart.drawOrder + opacity = 1f + multiplyColor = Cmo3SkeletonBuilder.identityMultiplyColor() + screenColor = Cmo3SkeletonBuilder.identityScreenColor() + } + part.apply { + localName = editedPart.name + isVisible = true + keyformGridSource = + org.umamo.format.cmo3.model.gen.KeyformGridSource().apply { + // CMO3: KeyformGridSource - one unkeyed cell (empty access key) like the blank's parts. + keyformsOnGrid = + ArrayList( + mutableListOf( + org.umamo.format.cmo3.model.gen.KeyformOnGrid().apply { + accessKey = + org.umamo.format.cmo3.model.gen.KeyformGridAccessKey().apply { + _keyOnParameterList = ArrayList() + } + keyformGuid = formGuid + }, + ), + ) + keyformBindings = ArrayList() + } + keyformMorphTargetSet = Cmo3SkeletonBuilder.emptyMorphTargetSet() + _extensions = CArrayList() + labelColor = Cmo3SkeletonBuilder.undefinedLabelColor() + guid = freshGuidLike(template?.guid as? Guid, "CPartGuid") + id = freshIdLike(template?.id as? Id, "CPartId", editedPart.id.raw) + keyforms = CArrayList(mutableListOf(form)) + defaultOrder_forEditor = editedPart.drawOrder + partsEditColor = org.umamo.format.cmo3.model.type.CColor() + _childGuids = CArrayList() + clipGuidList = CArrayList() + colorComposition = org.umamo.format.cmo3.model.gen.ColorComposition.NORMAL + alphaComposition = org.umamo.format.cmo3.model.gen.AlphaComposition.OVER + } + appendToCollection(sourceSet, "CPartSourceSet", "_sources", sourceSet._sources, { sourceSet._sources = it }, part) + return true + } + + /** + * Synthesizes the identity shell for a created deformer (warp or rotation). Lattice/angle + * fields, parent/part wiring, and the whole keyform web flow through the Changed lowering. + * + * @param Deformer editedDeformer The created deformer. + * @return Boolean True on success. + */ + fun synthesizeDeformer(editedDeformer: org.umamo.runtime.model.Deformer): Boolean { + val sourceSet = modelSource.deformerSourceSet as? org.umamo.format.cmo3.model.gen.CDeformerSourceSet + if (sourceSet == null) { + unsupported(ExportEntityCategory.Deformer, editedDeformer.id.raw, ExportNoticeReason.NoSourceSetToCreateInto) + return false + } + val fresh: org.umamo.format.cmo3.model.gen.ACDeformerSource = + when (editedDeformer) { + is org.umamo.runtime.model.Deformer.Warp -> { + val template = + index.deformerSources.filterIsInstance().firstOrNull() + org.umamo.format.cmo3.model.gen.CWarpDeformerSource().apply { + guid = freshGuidLike(template?.guid as? Guid, "CDeformerGuid") + id = freshIdLike(template?.id as? Id, "CDeformerId", editedDeformer.id.raw) + keyforms = CArrayList() + } + } + is org.umamo.runtime.model.Deformer.Rotation -> { + val template = + index.deformerSources.filterIsInstance().firstOrNull() + org.umamo.format.cmo3.model.gen.CRotationDeformerSource().apply { + guid = freshGuidLike(template?.guid as? Guid, "CDeformerGuid") + id = freshIdLike(template?.id as? Id, "CDeformerId", editedDeformer.id.raw) + keyforms = CArrayList() + // CMO3: CRotationDeformerSource fields handleLengthOnCanvas / + // circleRadiusOnCanvas - editor gizmo sizing only; cloned from a sibling when + // one exists, else nominal defaults (no runtime consumes them). + handleLengthOnCanvas = template?.handleLengthOnCanvas ?: 100f + circleRadiusOnCanvas = template?.circleRadiusOnCanvas ?: 20f + } + } + } + fresh.apply { + localName = editedDeformer.name + isVisible = true + isLocked = !editedDeformer.isSelectable + keyformMorphTargetSet = Cmo3SkeletonBuilder.emptyMorphTargetSet() + _extensions = CArrayList() + labelColor = Cmo3SkeletonBuilder.undefinedLabelColor() + } + appendToCollection(sourceSet, "CDeformerSourceSet", "_sources", sourceSet._sources, { sourceSet._sources = it }, fresh) + return true + } + + /** + * Synthesizes the identity shell for a created glue. Pair weights/uids and the intensity + * track flow through the Changed lowering (lowerGluePairsFor + lowerGlue). + * + * @param Glue editedGlue The created glue. + * @param Int ordinal The glue's ordinal among same-pair glues (the diff key). + * @return Boolean True on success. + */ + fun synthesizeGlue(editedGlue: Glue, ordinal: Int): Boolean { + val subject = "${editedGlue.meshA.raw}~${editedGlue.meshB.raw}" + val sourceSet = modelSource.affecterSourceSet as? org.umamo.format.cmo3.model.gen.CAffecterSourceSet + if (sourceSet == null) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.NoSourceSetToCreateInto) + return false + } + val meshAGuid = index.drawableByIdStr[editedGlue.meshA.raw]?.guid as? Guid + val meshBGuid = index.drawableByIdStr[editedGlue.meshB.raw]?.guid as? Guid + if (meshAGuid == null || meshBGuid == null) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.GluedDrawableHasNoSource) + return false + } + val template = index.glueSources.firstOrNull() + val ownerPartId = edited.partByDrawable()[editedGlue.meshA] + val ownerPart = ownerPartId?.let { index.partByIdStr[it.raw] } ?: index.rootPartSource + val ownerGuid = ownerPart?.guid + val fresh = org.umamo.format.cmo3.model.gen.CGlueSource() + val glueGuid = freshGuidLike(template?.guid as? Guid, "CAffecterGuid") + val formGuid = freshGuidLike(null, "CFormGuid") + val form = + org.umamo.format.cmo3.model.gen.CGlueForm().apply { + // CMO3: CGlueForm - the one default-cell form; every corpus glue carries at least + // this cell, and the intensity lowering writes only into existing forms. + guid = formGuid + isAnimatedForm = false + isLocalAnimatedForm = false + _source = fresh + notes = "" + intensity = 1f + } + fresh.apply { + localName = "" + isVisible = true + // CMO3: ACParameterControllableSource field parentGuid - the owning part, like the + // glued drawables' own panel parent (corpus glues always sit under a part). + parentGuid = ownerGuid + keyformGridSource = + org.umamo.format.cmo3.model.gen.KeyformGridSource().apply { + // CMO3: KeyformGridSource - one unkeyed cell (empty access key), the corpus + // glue default; an intensity track later rebuilds this web via writeGridWeb. + keyformsOnGrid = + ArrayList( + mutableListOf( + org.umamo.format.cmo3.model.gen.KeyformOnGrid().apply { + accessKey = + org.umamo.format.cmo3.model.gen.KeyformGridAccessKey().apply { + _keyOnParameterList = ArrayList() + } + keyformGuid = formGuid + }, + ), + ) + keyformBindings = ArrayList() + } + keyformMorphTargetSet = Cmo3SkeletonBuilder.emptyMorphTargetSet() + _extensions = CArrayList() + labelColor = Cmo3SkeletonBuilder.undefinedLabelColor() + guid = glueGuid + // The model keys glues by mesh pair + ordinal (they carry no id of their own), so the + // minted idstr only needs uniqueness within the document. + id = freshIdLike(template?.id as? Id, "CAffecterId", "Glue_${editedGlue.meshA.raw}_${editedGlue.meshB.raw}_$ordinal") + // CMO3: ACAffecterSource field targetDeformerGuid - the editor's fixed root-deformer + // sentinel (uuid identical in every corpus file; the editor writes it even for glues + // whose meshes have real deformer parents). + targetDeformerGuid = Cmo3SkeletonBuilder.rootDeformerSentinel() + // CMO3: CGlueSource fields targetArtMeshA_guid / targetArtMeshB_guid - identity refs + // to the glued drawables' own guid objects. + targetArtMeshA_guid = meshAGuid + targetArtMeshB_guid = meshBGuid + // CMO3: CGlueSource field tabPosOnCanvas - the glue tab marker, never null; the editor + // stacks them at x = -100 down the canvas's left margin. + tabPosOnCanvas = + org.umamo.format.cmo3.model.type.GVector2().apply { + x = -100f + y = 100f * (ordinal + 1) + } + keyforms = CArrayList(mutableListOf(form)) + } + appendToCollection(sourceSet, "CAffecterSourceSet", "_sources", sourceSet._sources, { sourceSet._sources = it }, fresh) + // CMO3: CPartSource field _childGuids - the owning part lists the glue's CAffecterGuid + // after its drawables and deformers; the editor's load-time verify repairs (and 5.4 + // crashes on) an affecter absent from the part hierarchy. + if (ownerPart != null) { + appendToCollection(ownerPart, "CPartSource", "_childGuids", ownerPart._childGuids, { ownerPart._childGuids = it }, glueGuid) + } + return true + } + + /** Removes a deleted drawable's source and strips its guid from every panel child list. */ + fun deleteDrawable(drawableId: DrawableId) { + val sourceSet = modelSource.drawableSourceSet as? org.umamo.format.cmo3.model.gen.CDrawableSourceSet ?: return + val source = index.drawableByIdStr[drawableId.raw] + if (removeFromCollection(sourceSet._sources) { entry -> entry === source }) { + stripFromChildLists(Cmo3Import.uuidOf(source?.guid)) + deletedAnything = true + } + } + + /** Removes a deleted part's source and strips its guid from every panel child list. */ + fun deletePart(partIdRaw: String) { + val sourceSet = modelSource.partSourceSet as? org.umamo.format.cmo3.model.gen.CPartSourceSet ?: return + val source = index.partByIdStr[partIdRaw] + if (removeFromCollection(sourceSet._sources) { entry -> entry === source }) { + stripFromChildLists(Cmo3Import.uuidOf(source?.guid)) + deletedAnything = true + } + } + + /** Removes a deleted deformer's source and strips its guid from every panel child list. */ + fun deleteDeformer(deformerIdRaw: String) { + val sourceSet = modelSource.deformerSourceSet as? org.umamo.format.cmo3.model.gen.CDeformerSourceSet ?: return + val source = index.deformerByIdStr[deformerIdRaw] + if (removeFromCollection(sourceSet._sources) { entry -> entry === source }) { + stripFromChildLists(Cmo3Import.uuidOf(source?.guid)) + deletedAnything = true + } + } + + /** Removes a deleted glue's source, resolved by mesh pair plus ordinal. */ + fun deleteGlue(meshA: DrawableId, meshB: DrawableId, ordinal: Int) { + val sourceSet = modelSource.affecterSourceSet as? org.umamo.format.cmo3.model.gen.CAffecterSourceSet ?: return + val matching = + index.glueSources.filter { glueSource -> + index.drawableIdStrByUuid[Cmo3Import.uuidOf(glueSource.targetArtMeshA_guid)] == meshA.raw && + index.drawableIdStrByUuid[Cmo3Import.uuidOf(glueSource.targetArtMeshB_guid)] == meshB.raw + } + val victim = matching.getOrNull(ordinal) ?: return + if (removeFromCollection(sourceSet._sources) { entry -> entry === victim }) { + stripFromChildLists(Cmo3Import.uuidOf(victim.guid)) + deletedAnything = true + } + } + + /** + * Rewrites a drawable's topology surface: indices, base positions, UVs, and the full + * GEditableMesh2 rebuild (point mirror, freshly minted vertex uids, the unique triangle-edge + * set), then re-binds every glue touching the drawable to the new uid table. + * + * @param CArtMeshSource source The drawable's graph source. + * @param Drawable editedDrawable The edited drawable. + * @return Boolean True on success. + */ + fun lowerMeshTopology(source: CArtMeshSource, editedDrawable: Drawable): Boolean { + val subject = editedDrawable.id.raw + val mesh = editedDrawable.mesh + if (mesh == null) { + unsupported(ExportEntityCategory.Drawable, subject, ExportNoticeReason.DrawableHasNoMesh) + return false + } + // CMO3: CArtMeshSource fields indices / positions / uvs. The positions are CANVAS-frame + // in every official file, and mesh.positions is canvas-frame by the runtime's contract: + // the MOC3 document loader normalizes parent-local rest meshes through :render's + // restMeshesToCanvasSpace at import (rendering never notices the base's frame - grids sum + // to one - but the editor's atlas and mesh-edit views read this field as canvas geometry). + source.indices = mesh.indices.copyOf() + editor.ensureChildSlot(source, "CArtMeshSource", "indices", "keyforms") + source.positions = mesh.positions.copyOf() + editor.ensureChildSlot(source, "CArtMeshSource", "positions", "uvs") + source.uvs = storedUvsFor(source, mesh.uvs, editedDrawable) + editor.ensureChildSlot(source, "CArtMeshSource", "uvs", "texture") + + val editableMesh = Cmo3Import.editableMeshOf(source) + if (editableMesh != null) { + val vertexCount = mesh.vertexCount + // CMO3: GEditableMesh2 - point mirrors the positions as its own array; pointUid gets a + // freshly minted 0..n-1 table (glues re-bind below, so re-minting is safe); edge is the + // unique undirected triangle-edge set; the Delaunay flag drops (the triangulation is + // authored by the indices now). + editableMesh.point = mesh.positions.copyOf() + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "point", "pointPriority") + editableMesh.pointUid = IntArray(vertexCount) { vertexOrdinal -> vertexOrdinal } + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "pointUid", "meshGuid") + editableMesh.nextPointUid = vertexCount + editor.ensurePresentAttr(editableMesh, "GEditableMesh2", "nextPointUid") + editableMesh.useDelaunayTriangulation = false + editor.ensurePresentAttr(editableMesh, "GEditableMesh2", "useDelaunayTriangulation") + if (vertexCount <= Short.MAX_VALUE.toInt()) { + editableMesh.edge = triangleEdges(mesh.indices) + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "edge", "edgePriority") + } else { + unsupported( + ExportEntityCategory.Drawable, + subject, + ExportNoticeReason.VertexCountExceedsEdgeTable(vertexCount, Short.MAX_VALUE.toInt()), + ) + } + // Priority arrays resize to the new counts, keeping whichever array type was stored. + editableMesh.pointPriority = resizedPriorityArray(editableMesh.pointPriority, vertexCount, freshDefault = 10) + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "pointPriority", "edge") + (editableMesh.edge as? ShortArray)?.let { edges -> + editableMesh.edgePriority = resizedPriorityArray(editableMesh.edgePriority, edges.size / 2, freshDefault = 30) + editor.ensureChildSlot(editableMesh, "GEditableMesh2", "edgePriority", "pointUid") + } + } + for (glue in edited.glues) { + if (glue.meshA != editedDrawable.id && glue.meshB != editedDrawable.id) { + continue + } + // A partner whose uid table is still missing is a fresh shell whose own topology pass is + // later in this same export - ITS re-bind loop covers this glue with both tables minted, + // so a premature attempt here would only raise a spurious notice. + if (uidTableOf(glue.meshA) == null || uidTableOf(glue.meshB) == null) { + continue + } + lowerGluePairsFor(glue) + } + return true + } + + /** + * Rewrites a glue's vertex binding (weights + bindVertexUids) from the edited model's + * index-based pairs against both meshes' CURRENT uid tables. + * + * @param Glue editedGlue The edited glue. + * @return Boolean True on success. + */ + fun lowerGluePairsFor(editedGlue: Glue): Boolean { + val subject = "${editedGlue.meshA.raw}+${editedGlue.meshB.raw}" + val editedByPair = edited.glues.filter { it.meshA == editedGlue.meshA && it.meshB == editedGlue.meshB } + val ordinal = editedByPair.indexOfFirst { it === editedGlue }.coerceAtLeast(0) + val glueSource = + index.glueSources.filter { candidate -> + index.drawableIdStrByUuid[Cmo3Import.uuidOf(candidate.targetArtMeshA_guid)] == editedGlue.meshA.raw && + index.drawableIdStrByUuid[Cmo3Import.uuidOf(candidate.targetArtMeshB_guid)] == editedGlue.meshB.raw + }.getOrNull(ordinal) + if (glueSource == null) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.NoMatchingSourceToReconcile) + return false + } + val uidTableA = uidTableOf(editedGlue.meshA) + val uidTableB = uidTableOf(editedGlue.meshB) + if (uidTableA == null || uidTableB == null) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.GluedMeshHasNoUidTable) + return false + } + val pairCount = editedGlue.pairs.size + val weights = FloatArray(pairCount * 2) + val uids = LongArray(pairCount * 2) + for (pairIndex in 0 until pairCount) { + val pair = editedGlue.pairs[pairIndex] + val uidA = uidTableA.getOrNull(pair.indexA) + val uidB = uidTableB.getOrNull(pair.indexB) + if (uidA == null || uidB == null) { + unsupported(ExportEntityCategory.Glue, subject, ExportNoticeReason.GluePairIndexesPastUidTable) + return false + } + // CMO3: CGlueSource fields weights / bindVertexUids - [A, B]-interleaved per pair. + weights[pairIndex * 2] = pair.weightA + weights[pairIndex * 2 + 1] = pair.weightB + uids[pairIndex * 2] = uidA.toLong() + uids[pairIndex * 2 + 1] = uidB.toLong() + } + glueSource.weights = weights + editor.ensureChildSlot(glueSource, "CGlueSource", "weights", "keyforms") + glueSource.bindVertexUids = uids + editor.ensureChildSlot(glueSource, "CGlueSource", "bindVertexUids", "tabPosOnCanvas") + return true + } + + private fun uidTableOf(drawableId: DrawableId): IntArray? = + index.drawableByIdStr[drawableId.raw]?.let { source -> Cmo3Import.editableMeshOf(source)?.pointUid as? IntArray } + + /** The unique undirected triangle edges as the editable mesh's short-indexed pair list. */ + private fun triangleEdges(indices: IntArray): ShortArray { + val seen = LinkedHashSet() + var triangleStart = 0 + while (triangleStart + 2 < indices.size) { + for (cornerIndex in 0 until 3) { + val endpointA = indices[triangleStart + cornerIndex] + val endpointB = indices[triangleStart + (cornerIndex + 1) % 3] + val low = minOf(endpointA, endpointB) + val high = maxOf(endpointA, endpointB) + seen.add(low shl 16 or high) + } + triangleStart += 3 + } + val edges = ShortArray(seen.size * 2) + var writeIndex = 0 + for (packed in seen) { + edges[writeIndex++] = (packed shr 16).toShort() + edges[writeIndex++] = (packed and 0xFFFF).toShort() + } + return edges + } + + /** + * A priority array of [count] entries matching [existing]'s stored type, or a fresh byte + * array filled with [freshDefault] when none was stored. + * + * CMO3: GEditableMesh2 fields pointPriority / edgePriority - byte arrays on every corpus + * mesh, never null (the editor NPEs on a null); points carry 10, triangle edges 30. + */ + private fun resizedPriorityArray(existing: Any?, count: Int, freshDefault: Byte): Any? = + when (existing) { + is IntArray -> IntArray(count) + is ShortArray -> ShortArray(count) + is FloatArray -> FloatArray(count) + is ByteArray -> ByteArray(count) { freshDefault } + else -> ByteArray(count) { freshDefault } + } + + /** + * The UVs as CMO3 stores them, in the frame the drawable stores ([Cmo3TextureFrames.storedUvsOf]), off + * its tile's page through the edited placement when the tile has one. + * + * @param CArtMeshSource source The drawable's graph source. + * @param FloatArray uvs The model-frame UVs. + * @param Drawable editedDrawable The edited drawable, whose tile the UVs address. + * @return FloatArray The stored-frame UVs. + */ + private fun storedUvsFor(source: CArtMeshSource, uvs: FloatArray, editedDrawable: Drawable): FloatArray = + textureFrames.storedUvsOf(source, uvs, editedDrawable.atlasTileId?.let { tileId -> edited.atlas.storedToArtAffineForTile(tileId) }) + + private fun findEditedGroup(groupId: ParameterGroupId): ParameterNode.Group? { + fun walk(nodes: List): ParameterNode.Group? { + for (node in nodes) { + if (node is ParameterNode.Group) { + if (node.id == groupId) { + return node + } + walk(node.children)?.let { return it } + } + } + return null + } + return walk(edited.parameterTree) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/Cmo3ToMoc3CrossFormatTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/Cmo3ToMoc3CrossFormatTest.kt new file mode 100644 index 0000000..c19ac2a --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/Cmo3ToMoc3CrossFormatTest.kt @@ -0,0 +1,252 @@ +package org.umamo.interop + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.partByDrawable +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * A CMO3 exported to MOC3 describes the same rig as the editor's own bake of that model. + * + * The corpus holds TWINS - the same model saved as `.cmo3` and baked to `.moc3` by the official + * editor - which makes this the only test that can check the export against something other than our + * own reading of it. Every other MOC3 gate starts from a moc: import it, write it back, compare. + * That proves self-consistency and nothing about whether our lowering agrees with Cubism's. + * + * STRUCTURE is compared as equality, and by id: object sets, kinds, parentage, mesh topology, mask + * lists, parameter ranges. Those are decisions, not arithmetic - if the editor put a drawable under a + * warp, so must we. + * + * The TEXTURE PAGE is not compared, and cannot be: a CMO3 has no atlas. Its pixels are + * embedded per drawable, and the packed pages a moc indexes into are produced BY the bake - so the + * editor's page numbers describe a packing this file does not contain. What the export writes is its + * own page set (one per embedded image, or the retained atlas for a MOC3-origin document), and the + * family it writes is self-consistent with it. + * + * GEOMETRY is not compared here at all. The two files are separate authoring artifacts: the CMO3 + * holds the editor's source-space values and the moc holds its baked ones, and the transform between + * them is the editor's own, not a spec. `Cmo3ToMoc3OracleTest` compares the EVALUATED result through + * the official core instead, which is the question that actually matters and the only one with a + * defensible tolerance. + * + * Gated on `cmo3.probe` + `moc3.samples`, joined by base name; self-skips whenever the two sets share + * no base name, which includes either property being absent. + */ +class Cmo3ToMoc3CrossFormatTest { + /** + * The corpus twins, keyed by base name. + * + * @return List Each (base name, cmo3, moc3) triple the corpus can pair. + */ + private fun twins(): List> { + val cmo3Files = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map { path -> File(path.trim()) } + ?.filter { file -> file.isFile } + ?.associateBy { file -> file.nameWithoutExtension } + .orEmpty() + val moc3Files = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { directory -> directory.isDirectory } + ?.walkTopDown() + ?.filter { file -> file.isFile && file.extension == "moc3" && file.parentFile?.name != "work" } + ?.associateBy { file -> file.nameWithoutExtension } + .orEmpty() + return cmo3Files.keys + .intersect(moc3Files.keys) + .sorted() + .map { name -> Triple(name, cmo3Files.getValue(name), moc3Files.getValue(name)) } + } + + /** + * Exports [cmo3File]'s rig at [baked]'s own version, so the comparison is version-for-version. + * + * @param File cmo3File The source CMO3. + * @param MocDocument baked The editor's bake of the same model. + * @return MocDocument Our lowering of the CMO3. + */ + private fun exportedFrom(cmo3File: File, baked: MocDocument): Pair { + val model = Cmo3.read(cmo3File) + val root = model.root as? CModelSource ?: error("${cmo3File.name}: root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(root) + return imported to Moc3Export.toMocDocument(imported, baked.version).document + } + + @Test + fun everyTwinLowersToTheSameStructure() { + val twins = twins() + if (twins.isEmpty()) { + println("no cmo3/moc3 twins in the corpus; skipping cross-format comparison") + return + } + val failures = ArrayList() + val differentRevisions = ArrayList() + var compared = 0 + for ((name, cmo3File, moc3File) in twins) { + val baked = Moc3.read(moc3File.readBytes()) + val (source, ours) = + runCatching { exportedFrom(cmo3File, baked) }.getOrElse { failure -> + failures.add("$name: the CMO3 would not lower to a moc ($failure)") + continue + } + // A twin pair is only an oracle when the two files are the same REVISION of the model. The + // corpus has one pair that is not - the moc was baked from a different edit of the project, and + // it disagrees about meshes, parameters, and the deformer tree alike - so comparing them would + // report dozens of "divergences" that say nothing about the lowering. Detected rather than + // named, so the rule survives a corpus change, and counted in the summary so a pair that + // silently stops comparing cannot hide. + val bakedMeshIds = baked.artMeshes.map { it.id }.toSet() + val missingMeshes = bakedMeshIds - ours.artMeshes.map { it.id }.toSet() + if (missingMeshes.size > bakedMeshIds.size / 10) { + differentRevisions.add("$name (${missingMeshes.size}/${bakedMeshIds.size} art meshes absent)") + continue + } + compared++ + // What the editor's bake omits and ours keeps: HIDDEN objects. The official bake deletes them + // unless "export invisible drawable" is ticked; Umamo asks the same through Moc3ExportOptions, + // but this test lowers with the options-less API default, which keeps them (flag clear) - + // deleting something the rigger can still see in the outliner is a silent destructive edit. + // That makes an unexpected id acceptable ONLY when the source says it is hidden - anything + // else is a bug. + val hiddenParts = source.parts.filterNot { part -> part.isVisible }.mapTo(HashSet()) { it.id.raw } + val hiddenDrawables = + source.drawables + .filterNot { drawable -> drawable.isVisible } + .mapTo(HashSet()) { drawable -> drawable.id.raw } + val partByDrawable = source.partByDrawable() + val hiddenByPart = + source.drawables + .filter { drawable -> partByDrawable[drawable.id]?.raw in hiddenParts } + .mapTo(HashSet()) { drawable -> drawable.id.raw } + + /** + * Records a divergence against this twin. + * + * @param String what What differed. + * @param Any? expected The editor's bake. + * @param Any? actual Our lowering. + */ + fun check(what: String, expected: Any?, actual: Any?) { + if (expected != actual) { + failures.add("$name: $what editor=$expected umamo=$actual") + } + } + + /** + * Compares two id sets, reporting only what differs. + * + * Dumping both sets whole is what a plain equality assert does, and on a real model that is a + * thousand ids of which two matter. + * + * @param String what The object category. + * @param Set expected The editor's ids. + * @param Set actual Ours. + * @param Set keptWhenHidden Ids ours may carry that the bake drops for being hidden. + */ + fun checkIds(what: String, expected: Set, actual: Set, keptWhenHidden: Set) { + val missing = (expected - actual).sorted() + val extra = (actual - expected - keptWhenHidden).sorted() + if (missing.isNotEmpty() || extra.isNotEmpty()) { + failures.add( + "$name: $what differ - ${missing.size} missing ${missing.take(4)}, " + + "${extra.size} unexpected ${extra.take(4)}", + ) + } + } + + checkIds( + "art mesh ids", + baked.artMeshes.map { it.id }.toSet(), + ours.artMeshes.map { it.id }.toSet(), + hiddenDrawables + hiddenByPart, + ) + checkIds("part ids", baked.parts.map { it.id }.toSet(), ours.parts.map { it.id }.toSet(), hiddenParts) + checkIds("parameter ids", baked.parameters.map { it.id }.toSet(), ours.parameters.map { it.id }.toSet(), emptySet()) + checkIds("deformer ids", baked.deformers.map { it.id }.toSet(), ours.deformers.map { it.id }.toSet(), emptySet()) + + val ourMeshes = ours.artMeshes.associateBy { it.id } + val ourParts = ours.parts.associateBy { it.id } + val ourDeformers = ours.deformers.associateBy { it.id } + val ourParameters = ours.parameters.associateBy { it.id } + + for (mesh in baked.artMeshes) { + val mine = ourMeshes[mesh.id] ?: continue + check("${mesh.id} vertex count", mesh.vertexCount, mine.vertexCount) + check("${mesh.id} triangle indices", mesh.triangleIndices.size, mine.triangleIndices.size) + // Resolved to IDS: the two files number their objects independently, so an index compare + // would report every model with a different authoring order as wrong. + check( + "${mesh.id} parent deformer", + baked.deformers.getOrNull(mesh.parentDeformerIndex)?.id, + ours.deformers.getOrNull(mine.parentDeformerIndex)?.id, + ) + check( + "${mesh.id} owning part", + baked.parts.getOrNull(mesh.parentPartIndex)?.id, + ours.parts.getOrNull(mine.parentPartIndex)?.id, + ) + check( + "${mesh.id} clip masks", + mesh.maskDrawableIndices.filter { it >= 0 }.mapNotNull { baked.artMeshes.getOrNull(it)?.id }.sorted(), + mine.maskDrawableIndices.filter { it >= 0 }.mapNotNull { ours.artMeshes.getOrNull(it)?.id }.sorted(), + ) + } + + for (part in baked.parts) { + val mine = ourParts[part.id] ?: continue + check( + "part ${part.id} parent", + baked.parts.getOrNull(part.parentPartIndex)?.id, + ours.parts.getOrNull(mine.parentPartIndex)?.id, + ) + } + + for (deformer in baked.deformers) { + val mine = ourDeformers[deformer.id] ?: continue + check("deformer ${deformer.id} kind", deformer::class.simpleName, mine::class.simpleName) + check( + "deformer ${deformer.id} parent", + baked.deformers.getOrNull(deformer.parentDeformerIndex)?.id, + ours.deformers.getOrNull(mine.parentDeformerIndex)?.id, + ) + if (deformer is WarpDeformer && mine is WarpDeformer) { + check("deformer ${deformer.id} lattice", deformer.rows to deformer.columns, mine.rows to mine.columns) + } + if (deformer is RotationDeformer && mine is RotationDeformer) { + check("deformer ${deformer.id} base angle", deformer.baseAngle, mine.baseAngle) + } + } + + for (parameter in baked.parameters) { + val mine = ourParameters[parameter.id] ?: continue + check("parameter ${parameter.id} minimum", parameter.minimumValue, mine.minimumValue) + check("parameter ${parameter.id} maximum", parameter.maximumValue, mine.maximumValue) + check("parameter ${parameter.id} default", parameter.defaultValue, mine.defaultValue) + check("parameter ${parameter.id} type", parameter.type, mine.type) + } + } + assertTrue(compared > 0, "no twin could be lowered") + assertTrue( + differentRevisions.size < twins.size / 2, + "most corpus twins are no longer the same revision, so this gate has stopped testing anything: " + + differentRevisions, + ) + println( + "[cross-format] $compared cmo3/moc3 twins compared, ${failures.size} structural divergences" + + (if (differentRevisions.isEmpty()) "" else "; skipped as different revisions: $differentRevisions"), + ) + assertEquals(emptyList(), failures.take(25), "our lowering disagrees with the editor's bake") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/CompositeImportTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/CompositeImportTest.kt new file mode 100644 index 0000000..bbb93e8 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/CompositeImportTest.kt @@ -0,0 +1,225 @@ +package org.umamo.interop + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +// The MultiplyScreenColors sample's authored colors: multiply #677CD1, screen #95C068 (editor hex, +// each channel serialized as hex / 255 in f32 on both formats - verified channel-exact in the +// extraction, docs/plan/offscreen-support.md). +private val AUTHORED_MULTIPLY = ColorRgb(103f / 255f, 124f / 255f, 209f / 255f) +private val AUTHORED_SCREEN = ColorRgb(149f / 255f, 192f / 255f, 104f / 255f) +private const val COLOR_TOLERANCE = 1e-6f + +/** + * Corpus-gated offscreen ingest anchors over the authored extraction family (see + * docs/plan/offscreen-support.md § corpus evidence): part offscreen state, clip lists, invert, + * static and keyformed colors, and the drawable-level extended blend + culling - on BOTH import + * paths. Skips gracefully without the corpus. + */ +class CompositeImportTest { + private fun probeFiles(): Map = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map(::File) + ?.filter { it.isFile } + ?.associateBy { it.name } + ?: emptyMap() + + private fun mocFiles(): Map = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" } + ?.associateBy { it.name } + ?: emptyMap() + + private fun importCmo3(file: File): PuppetModel { + val root = Cmo3.read(file).root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + return Cmo3Import.fromModelSource(root) + } + + private fun importMoc3(file: File): PuppetModel = Moc3Import.fromMocDocument(Moc3.read(file.readBytes()), null) + + private fun assertColorClose(expected: ColorRgb, actual: ColorRgb, label: String) { + assertTrue( + abs(expected.red - actual.red) < COLOR_TOLERANCE && + abs(expected.green - actual.green) < COLOR_TOLERANCE && + abs(expected.blue - actual.blue) < COLOR_TOLERANCE, + "$label: expected $expected, got $actual", + ) + } + + @Test + fun cmo3BaseFamilyPinsCompositionEnums() { + val file = probeFiles()["ModelWithOffscreen.cmo3"] ?: return println("ModelWithOffscreen.cmo3 not present; skipping") + val puppet = importCmo3(file) + // Authored: Face = Normal/Over, Eye = Multiply (Before 5.3)/Disjoint, both offscreen. + val isolatedParts = puppet.parts.filter { it.activeComposite != null } + assertEquals(2, isolatedParts.size, "isolated part count") + val face = assertNotNull(puppet.parts.find { it.name == "Face" }?.activeComposite, "Face offscreen") + assertEquals(BlendMode.Normal, face.blendMode, "Face color blend") + assertEquals(AlphaBlendMode.Over, face.alphaBlendMode, "Face alpha blend") + val eye = assertNotNull(puppet.parts.find { it.name == "Eye" }?.activeComposite, "Eye offscreen") + assertEquals(BlendMode.MultiplyPremultiplied, eye.blendMode, "Eye color blend (bare legacy token)") + assertEquals(AlphaBlendMode.Disjoint, eye.alphaBlendMode, "Eye alpha blend") + } + + @Test + fun cmo3ClippingReverseMaskPinsClipAndLatentFields() { + val file = + probeFiles()["ModelWithOffscreenClippingIDReverseMask.cmo3"] + ?: return println("ModelWithOffscreenClippingIDReverseMask.cmo3 not present; skipping") + val puppet = importCmo3(file) + val drawableIds = puppet.drawables.mapTo(HashSet()) { it.id } + // The authored clip: an offscreen part with Reverse mask on and one drawable as Clipping ID. + val clipped = assertNotNull(puppet.parts.mapNotNull { it.activeComposite }.find { it.maskedBy.isNotEmpty() }, "clipped offscreen part") + assertTrue(clipped.invertMask, "reverse mask on") + assertEquals(1, clipped.maskedBy.size, "one clip source") + assertTrue(clipped.maskedBy.all { it in drawableIds }, "clip sources resolve to drawables") + // The fields-survive-uncheck evidence: latent composition values on a NON-offscreen part must + // not materialize an Isolated group mode. + assertTrue(puppet.parts.any { it.activeComposite == null }, "non-offscreen parts stay non-isolated") + // Latent capture: those authored composition values are now stored on the part regardless of mode + // (for UMA to track), so a non-isolated part carries a non-default composite while activeComposite + // stays null. + assertTrue( + puppet.parts.any { it.activeComposite == null && it.composite != PartComposite() }, + "a non-offscreen part captured its latent composite settings", + ) + } + + @Test + fun cmo3PartClippingPinsDrawableExtendedBlendAndCulling() { + val file = + probeFiles()["ModelWithOffscreenPartClipping.cmo3"] + ?: return println("ModelWithOffscreenPartClipping.cmo3 not present; skipping") + val puppet = importCmo3(file) + // The authored drawable: color blend Screen, alpha blend Out, Culling on. + val screenDrawable = assertNotNull(puppet.drawables.find { it.blendMode == BlendMode.Screen }, "Screen drawable") + assertEquals(AlphaBlendMode.Out, screenDrawable.alphaBlendMode, "Out alpha blend") + assertTrue(puppet.drawables.any { it.culling }, "a drawable has culling on") + // The part-as-clip-source expansion: the offscreen part's clip list resolves to the OTHER + // part's constituent drawables (never a part id). + val drawableIds = puppet.drawables.mapTo(HashSet()) { it.id } + val clipped = assertNotNull(puppet.parts.mapNotNull { it.activeComposite }.find { it.maskedBy.isNotEmpty() }, "clipped offscreen part") + assertTrue(clipped.maskedBy.all { it in drawableIds }, "part clip expanded to drawables") + } + + @Test + fun cmo3MultiplyScreenColorsPinsAuthoredColors() { + val file = probeFiles()["MultiplyScreenColors.cmo3"] ?: return println("MultiplyScreenColors.cmo3 not present; skipping") + val puppet = importCmo3(file) + val composite = assertNotNull(puppet.parts.mapNotNull { it.activeComposite }.firstOrNull(), "an offscreen part") + assertColorClose(AUTHORED_MULTIPLY, composite.multiplyColor, "multiply color") + assertColorClose(AUTHORED_SCREEN, composite.screenColor, "screen color") + } + + @Test + fun moc3PartClippingPinsDrawableExtendedBlendAndCulling() { + val file = + mocFiles()["ModelWithOffscreenPartClipping.moc3"] + ?: return println("ModelWithOffscreenPartClipping.moc3 not present; skipping") + val puppet = importMoc3(file) + // MOC3 v6 §5.6 s153: the authored drawable stored packed 522 = Screen or (Out shl 8). + val screenDrawable = assertNotNull(puppet.drawables.find { it.blendMode == BlendMode.Screen }, "Screen drawable") + assertEquals(AlphaBlendMode.Out, screenDrawable.alphaBlendMode, "Out alpha blend") + // Culling = the inverse of drawable constant-flags bit 2 (double-sided). + assertTrue(puppet.drawables.any { it.culling }, "a drawable has culling on") + assertTrue(puppet.drawables.any { !it.culling }, "default drawables stay double-sided") + val drawableIds = puppet.drawables.mapTo(HashSet()) { it.id } + val clipped = assertNotNull(puppet.parts.mapNotNull { it.activeComposite }.find { it.maskedBy.isNotEmpty() }, "clipped offscreen part") + assertTrue(clipped.maskedBy.all { it in drawableIds }, "offscreen mask indices resolve to drawables") + } + + @Test + fun moc3MultiplyScreenColorsPinsAuthoredColors() { + val file = mocFiles()["MultiplyScreenColors.moc3"] ?: return println("MultiplyScreenColors.moc3 not present; skipping") + val puppet = importMoc3(file) + val composite = assertNotNull(puppet.parts.mapNotNull { it.activeComposite }.firstOrNull(), "an offscreen part") + assertColorClose(AUTHORED_MULTIPLY, composite.multiplyColor, "multiply color") + assertColorClose(AUTHORED_SCREEN, composite.screenColor, "screen color") + } + + @Test + fun moc3ModelAPinsOrganicOffscreenCount() { + val file = mocFiles()["modelA.moc3"] ?: return println("modelA.moc3 not present; skipping") + val puppet = importMoc3(file) + // Model A's 24 offscreen parts (== the moc's CountInfo[35]); the organic cross-check that the + // owner-part join holds beyond the authored extraction family. + assertEquals(24, puppet.parts.count { it.activeComposite != null }, "isolated part count") + // The keyformed-opacity evidence: at least one offscreen part carries a grid whose opacity + // varies across cells (the ParamHologram crossfade). + val hasKeyformedOpacity = + puppet.parts.any { part -> + part.activeComposite != null && (opacityValues(part.channelGrids).distinct().size) > 1 + } + assertTrue(hasKeyformedOpacity, "an offscreen part has keyformed opacity") + } + + @Test + fun pre53PartOpacityDefaultsToOpaque() { + // Erica Tamamo is a pre-5.3 model whose parts never author the float CPartForm.opacity, so the + // @DontSerializeIfDefault field parses as 0f = "unset -> fully opaque" (Cubism's semantic default), + // NOT 0%. Without the ingest remap the part-opacity cascade renders the whole part subtree invisible + // (every drawable under a part goes to opacity 0); only the two root-level drawables stayed visible. + val file = probeFiles()["EricaTamamo.cmo3"] ?: return println("EricaTamamo.cmo3 not present; skipping") + val model = importCmo3(file) + assertTrue(model.parts.isNotEmpty(), "EricaTamamo carries parts") + assertTrue(model.parts.none { it.composite.opacity == 0f }, "no pre-5.3 part is spuriously transparent") + assertTrue( + model.parts.none { part -> opacityValues(part.channelGrids).any { opacity -> opacity == 0f } }, + "no pre-5.3 part keyform cell is spuriously transparent", + ) + } + + @Test + fun staticCmo3PartCarriesNoKeyformGrid() { + // A CMO3 part with no parameter binding must NOT keep a single-cell channel track: the eval samples + // the track OVER the static PartComposite, so a lingering track would shadow an edited composite + // opacity/color and an isolated static part's edit would never render (Moc3Import already yields + // empty channel grids for an unbound part - this keeps CMO3 consistent). A part with real + // animation keeps its tracks (below). + probeFiles()["EricaTamamo.cmo3"]?.let { file -> + val model = importCmo3(file) + val frontHair = model.parts.firstOrNull { it.name.equals("Front hair", ignoreCase = true) } + assertNotNull(frontHair, "EricaTamamo has a Front hair part") + assertTrue(frontHair.channelGrids.isEmpty, "a static (unbound) part carries no keyform tracks") + } ?: println("EricaTamamo.cmo3 not present; skipping") + + // An animated part - keyformed part draw order / opacity - keeps its tracks (non-empty axes). + probeFiles()["modelA.cmo3"]?.let { file -> + val model = importCmo3(file) + assertTrue( + model.parts.any { part -> part.channelGrids.gridsByChannel.values.any { track -> track.axes.isNotEmpty() } }, + "a parameter-bound CMO3 part keeps its keyform tracks", + ) + } ?: println("modelA.cmo3 not present; skipping") + } + + /** + * Every opacity value stored across a part's opacity track (empty when it has none). + * + * @param ChannelGrids channels The part's per-channel tracks. + * @return List The stored opacities, in cell order. + */ + private fun opacityValues(channels: ChannelGrids): List = + channels[FormChannel.OPACITY]?.cells?.mapNotNull { cell -> (cell.form as? ChannelValue.Scalar)?.value } ?: emptyList() +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/art/SourceArtImportCorpusTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/art/SourceArtImportCorpusTest.kt new file mode 100644 index 0000000..acd2f72 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/art/SourceArtImportCorpusTest.kt @@ -0,0 +1,81 @@ +package org.umamo.interop.art + +import org.umamo.format.FormatRegistry +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.art.analyzeAlpha +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Runs the bridge over every real layered file in the local corpus (PSD, CLIP, KRA), which is the + * only way to see what a reader actually emits - folder paths no group describes, weak keys that + * collide, text and empty layers - land on the model as the synthetic test says they should. + * + * Corpus-gated the way the readers' own tests are: every sample under `test/corpus/{psd,clip,krita}` + * found by walking up from the working directory, self-skipping with a printed line when none exist. + */ +class SourceArtImportCorpusTest { + private fun locateSamples(): List { + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return listOf("psd", "clip", "krita") + .flatMap { folder -> File(corpus, folder).listFiles { file -> file.isFile }.orEmpty().toList() } + .filter { file -> file.extension.lowercase() in setOf("psd", "clip", "kra") } + .sortedBy { file -> file.name } + } + directory = directory.parentFile + } + return emptyList() + } + + @Test + fun everyCorpusArtworkImportsToARig() { + val samples = locateSamples() + if (samples.isEmpty()) { + println("no test/corpus artwork samples; skipping the artwork import corpus test") + return + } + for (sample in samples) { + checkSample(sample) + } + } + + private fun checkSample(sample: File) { + val bytes = sample.readBytes() + val codec = assertNotNull(FormatRegistry.detect(bytes, sample.name), "${sample.name}: detected") + val art = codec.read(bytes) as SourceArt + val result = SourceArtImport.fromSourceArt(art, ArtSourceDescriptor(sample.name, sample.path, codec.kind.extension)) + val puppet = result.puppet + + // One drawable per raster layer with art in it, named after the layer, top-most first. + val expectedNames = + art.layers + .sortedBy { layer -> layer.order } + .filter { layer -> layer.kind == SourceLayerKind.Raster && layer.analyzeAlpha() != null } + .map { layer -> layer.name } + assertEquals(expectedNames, puppet.drawables.map { drawable -> drawable.name }, "${sample.name}: drawables") + assertEquals(puppet.drawables.size, puppet.drawables.map { drawable -> drawable.id }.toSet().size, "${sample.name}: drawable ids are unique") + assertEquals(puppet.atlas.tiles.size, puppet.atlas.tiles.map { tile -> tile.id }.toSet().size, "${sample.name}: tile ids are unique") + + // Every drawable samples a tile whose size is its layer's raster, bound to that layer's key. + for (drawable in puppet.drawables) { + val tile = assertNotNull(puppet.atlas.tileById[assertNotNull(drawable.atlasTileId)], "${sample.name}: ${drawable.name} has a tile") + val raster = assertNotNull(result.rasterByTile[tile.id], "${sample.name}: ${drawable.name} has pixels") + assertEquals(raster.width, tile.width, "${sample.name}: ${drawable.name} tile width") + assertEquals(raster.height, tile.height, "${sample.name}: ${drawable.name} tile height") + val source = assertNotNull(tile.source, "${sample.name}: ${drawable.name} is bound to its source layer") + assertEquals(puppet.sources.single().id, source.sourceId) + assertTrue(puppet.sources.single().layers.any { entry -> entry.key == source.layerKey }, "${sample.name}: the binding names an inventory layer") + } + assertEquals(art.layers.size, puppet.sources.single().layers.size, "${sample.name}: the inventory lists every layer") + assertTrue(puppet.parts.size >= art.groups.size, "${sample.name}: every described folder is a part") + assertEquals(art.widthPx.toFloat(), puppet.canvasWidth, "${sample.name}: canvas width") + println("imported ${sample.name}: ${puppet.drawables.size} drawables, ${puppet.parts.size} parts, ${result.notices.size} notes") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasIngestCorpusTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasIngestCorpusTest.kt new file mode 100644 index 0000000..016b4f3 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasIngestCorpusTest.kt @@ -0,0 +1,500 @@ +package org.umamo.interop.cmo3 + +import org.junit.Assume +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.GVector2 +import org.umamo.format.psd.PsdReader +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.atlasBindingFor +import org.umamo.runtime.model.atlasPixelOf +import org.umamo.runtime.model.layerUvsFromAtlasUvs +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Validates the atlas-placement recovery convention against real files, which is what keeps a sign or + * ordering error from passing unnoticed: a wrong rotation sign still round-trips (the synthetic tests + * in SourceArtRastersTest cannot catch it), and it is invisible on the axis-aligned majority - only the + * corpus's genuinely rotated packings expose it. + * + * The check is the format's own documented composition (docs/format/CMO3.md §6): a model image is + * upright canvas-space art, so `atlasLocalToCanvasTransform` composed with + * `materialLocalToAtlasTransform` must reproduce `_materialLocalToCanvasTransform` exactly. Reading + * our AtlasPlacement out of the entry and pushing a point through [atlasPixelOf] must therefore land + * where the file's own two affines say it lands. + * + * Gated on `cmo3.probe` (the whole corpus, comma-separated; the build defaults it to the local corpus, + * and an explicit `-D` overrides that); self-skips by JUnit assumption when it names no readable file, so + * an unfed run reports skipped rather than green. + */ +class Cmo3AtlasIngestCorpusTest { + private companion object { + /** + * How much of a drawable's recovered mapping must land on its layer's frame. Generous, because + * an authored mesh reaching well past its art is normal; a mis-wired recovery overlaps by nothing + * at all, so anything short of total displacement still fails this decisively. + */ + const val MINIMUM_FRAME_OVERLAP = 0.25f + + /** + * How far past its art a mesh may reach before that counts against the overlap, in layer pixels. + * The auto-mesh rings outside the opaque region (CMO3.md §6 measures ~20px per side on Erica) and + * authored meshes extend further for deformation coverage. A pixel quantity, deliberately: as a + * fraction the same margin is nothing on a 1021x1405 layer and everything on a 14x10 one. + */ + const val MESH_MARGIN_PIXELS = 32f + } + + /** + * The fraction of a mapping's own bounding box that falls inside the layer's frame, that frame + * widened by [MESH_MARGIN_PIXELS] so a normal mesh margin does not read as a miss. + * + * @param FloatArray layerUvs The recovered layer-frame texture coordinates, interleaved (u, v). + * @param Int layerWidth The layer's width in pixels (converts the margin into this uv frame). + * @param Int layerHeight The layer's height in pixels. + * @return Float The overlapping fraction, 0 when the mapping misses the frame entirely. + */ + private fun frameOverlapFractionOf(layerUvs: FloatArray, layerWidth: Int, layerHeight: Int): Float { + var minU = Float.MAX_VALUE + var maxU = -Float.MAX_VALUE + var minV = Float.MAX_VALUE + var maxV = -Float.MAX_VALUE + var componentIndex = 0 + while (componentIndex + 1 < layerUvs.size) { + minU = minOf(minU, layerUvs[componentIndex]) + maxU = maxOf(maxU, layerUvs[componentIndex]) + minV = minOf(minV, layerUvs[componentIndex + 1]) + maxV = maxOf(maxV, layerUvs[componentIndex + 1]) + componentIndex += 2 + } + val spanU = maxU - minU + val spanV = maxV - minV + if (spanU <= 0f || spanV <= 0f) { + return 0f + } + val marginU = MESH_MARGIN_PIXELS / layerWidth + val marginV = MESH_MARGIN_PIXELS / layerHeight + val insideU = minOf(maxU, 1f + marginU) - maxOf(minU, -marginU) + val insideV = minOf(maxV, 1f + marginV) - maxOf(minV, -marginV) + if (insideU <= 0f || insideV <= 0f) { + return 0f + } + return (insideU * insideV) / (spanU * spanV) + } + + /** + * Whether the mapping's bounding box fully covers the layer's frame, each edge allowed to fall + * short by [MESH_MARGIN_PIXELS]. + * + * The second acceptance shape beside the overlap fraction: a converted document's layer is the + * crop TRIMMED to its opaque pixels, so a mesh with a wide transparent reach maps to a box many + * times the layer's area and the landing fraction goes small - while the box still sits squarely + * OVER the art. A mis-wired recovery displaces the box off the layer entirely and satisfies + * neither shape. + * + * @param FloatArray layerUvs The recovered layer-frame texture coordinates, interleaved (u, v). + * @param Int layerWidth The layer's width in pixels (converts the margin into this uv frame). + * @param Int layerHeight The layer's height in pixels. + * @return Boolean True when the mapping's box covers the layer's frame within the margin. + */ + private fun mappingCoversLayer(layerUvs: FloatArray, layerWidth: Int, layerHeight: Int): Boolean { + var minU = Float.MAX_VALUE + var maxU = -Float.MAX_VALUE + var minV = Float.MAX_VALUE + var maxV = -Float.MAX_VALUE + var componentIndex = 0 + while (componentIndex + 1 < layerUvs.size) { + minU = minOf(minU, layerUvs[componentIndex]) + maxU = maxOf(maxU, layerUvs[componentIndex]) + minV = minOf(minV, layerUvs[componentIndex + 1]) + maxV = maxOf(maxV, layerUvs[componentIndex + 1]) + componentIndex += 2 + } + val marginU = MESH_MARGIN_PIXELS / layerWidth + val marginV = MESH_MARGIN_PIXELS / layerHeight + return minU <= marginU && minV <= marginV && maxU >= 1f - marginU && maxV >= 1f - marginV + } + + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun corpusFiles(): List = + (System.getProperty("cmo3.probe") ?: "") + .split(",") + .map { path -> path.trim() } + .filter { path -> path.isNotEmpty() } + .map { path -> File(path) } + .filter { file -> file.isFile } + + /** Applies a CMO3 affine (m00 m01 m02 / m10 m11 m12) to a point. */ + private fun applyAffine(affine: CAffine, x: Float, y: Float): FloatArray = + floatArrayOf( + affine.m00 * x + affine.m01 * y + affine.m02, + affine.m10 * x + affine.m11 * y + affine.m12, + ) + + /** Our AtlasPlacement as read out of one atlas entry, matching cmo3AtlasIngest's own reading. */ + private fun placementOf(entry: ModelImageEntry, pageIndex: Int): AtlasPlacement? { + // CMO3: ModelImageEntry field materialLocalToAtlasTransform + val transform = entry.materialLocalToAtlasTransform as? GTransform2 ?: return null + val position = transform.position as? GVector2 + val scale = transform.scale as? GVector2 + return AtlasPlacement( + pageIndex = pageIndex, + positionX = position?.x ?: 0f, + positionY = position?.y ?: 0f, + scaleX = scale?.x ?: 1f, + scaleY = scale?.y ?: 1f, + rotationDegrees = transform.eulerAngle, + ) + } + + /** + * The store builder end to end on real documents: an art-bearing model must surface an inventory, + * bind its drawables to it, and land each bound drawable's recovered mapping ON its layer's art. + * + * Overlap, not containment, is the invariant. A mesh legitimately reaches past the art it samples - + * the auto-mesh rings outside the opaque region and an authored mesh often extends further still so + * deformation has coverage (the corpus's forearms reach ~140px past a 576x646 layer) - and the UV + * editor draws unclipped for exactly that reason. What a mis-wired recovery does instead is land the + * mesh somewhere else entirely: applying a page-space placement to uvs that already address their art + * threw modelA's meshes thousands of pixels off, overlapping their layer not at all. + */ + @Test + fun storeBindsCorpusDrawablesToArtTheirMappingsLandOn() { + val files = corpusFiles() + Assume.assumeTrue("[layer-store] no cmo3.probe corpus models", files.isNotEmpty()) + + var filesWithLayers = 0 + var boundDrawables = 0 + var checkedMappings = 0 + var worstOverlap = 1f + var missedMappings = 0 + val failures = mutableListOf() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + val puppet = Cmo3Import.fromModelSource(root) + if (puppet.atlas.isEmpty) { + continue + } + filesWithLayers++ + for (drawable in puppet.drawables) { + val binding = puppet.atlasBindingFor(drawable) ?: continue + boundDrawables++ + val layer = puppet.atlas.tileById[drawable.atlasTileId] ?: continue + val uvs = drawable.mesh?.uvs ?: continue + if (uvs.isEmpty()) { + continue + } + val layerUvs = layerUvsFromAtlasUvs(uvs, binding, layer.width, layer.height) ?: continue + checkedMappings++ + val overlap = frameOverlapFractionOf(layerUvs, layer.width, layer.height) + // Either shape says the mapping lands ON its art: mostly inside the layer, or fully + // covering it (a trim-tight converted crop under a wide-reaching mesh). + val landsOnLayer = overlap >= MINIMUM_FRAME_OVERLAP || mappingCoversLayer(layerUvs, layer.width, layer.height) + worstOverlap = minOf(worstOverlap, overlap) + if (!landsOnLayer) { + missedMappings++ + } + if (!landsOnLayer && failures.size < 10) { + failures.add( + "${file.name} ${drawable.id.raw} -> ${layer.name}: only $overlap of its mapping lands on the " + + "layer (${layer.width}x${layer.height}) on a ${binding.pageWidth}x${binding.pageHeight} " + + "page, placement=${binding.placement}", + ) + } + } + } + + println( + "[layer-store] $filesWithLayers art-bearing files, $boundDrawables bound drawables, " + + "$checkedMappings mappings checked, $missedMappings below the $MINIMUM_FRAME_OVERLAP overlap bound, " + + "least overlap $worstOverlap", + ) + assertTrue(filesWithLayers > 0, "no corpus file surfaced any source layers; the builder walk is broken") + assertTrue(boundDrawables > 0, "no drawable bound to a source layer; the drawable join is broken") + assertTrue(checkedMappings > 0, "no uv mapping was checked; the recovery is untested against real meshes") + assertTrue(failures.isEmpty(), "recovered mappings do not land on their layer:\n" + failures.joinToString("\n")) + } + + /** + * Toggling the source-artwork display changes nothing about how coordinates are read. + * + * The display mode picks which texture is sampled; the frame the stored coordinates live in is a + * fact of the file. Deriving the frame from the mode passed every import-time check - the two agree + * there - and broke the moment a rigger flipped the switch, drawing every mesh in the layer view at + * its atlas position instead of on its artwork. Checked on real documents in BOTH modes, because + * the corpus carries files saved each way. + */ + @Test + fun theDisplayModeNeverReinterpretsCorpusCoordinates() { + val files = corpusFiles() + Assume.assumeTrue("[layer-toggle] no cmo3.probe corpus models", files.isNotEmpty()) + + var checkedFiles = 0 + var checkedBindings = 0 + var placedBindings = 0 + val failures = mutableListOf() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + val asSaved = Cmo3Import.fromModelSource(root) + if (asSaved.atlas.isEmpty) { + continue + } + checkedFiles++ + val toggled = asSaved.copy(rendersFromSourceLayers = !asSaved.rendersFromSourceLayers) + for (drawable in asSaved.drawables) { + val before = asSaved.atlasBindingFor(drawable) + val after = toggled.atlasBindingFor(drawable) + checkedBindings++ + if (before?.placement != null) { + placedBindings++ + } + if (before != after && failures.size < 10) { + failures.add("${file.name} ${drawable.id.raw}: $before became $after when the display flipped") + } + } + } + + println( + "[layer-toggle] $checkedFiles art-bearing files, $checkedBindings bindings held across the toggle, " + + "$placedBindings of them placed", + ) + assertTrue(checkedFiles > 0, "no corpus file surfaced an atlas; the walk is broken") + assertTrue(placedBindings > 0, "no placed binding was checked; the toggle guard would pass vacuously") + assertTrue(failures.isEmpty(), "the display mode reinterpreted coordinates:\n" + failures.joinToString("\n")) + } + + @Test + fun placementForwardMatchesTheFormatsOwnComposition() { + val files = corpusFiles() + Assume.assumeTrue("[layer-recovery] no cmo3.probe corpus models", files.isNotEmpty()) + + // Sample points spanning a plausible layer extent, so a rotation error shows up as a mismatch + // rather than cancelling at the origin. + val samplePoints = listOf(0f to 0f, 137f to 0f, 0f to 251f, 137f to 251f) + val sampleExtent = 251f + // The composition cannot be exact: the entry's scale and the atlas-to-canvas fit are separately + // rounded floats, so their product misses identity by a small relative epsilon that the art's own + // extent multiplies up (modelA's worst case measures ~1e-3 relative). A model image is upright + // canvas-space art - its material-to-canvas is a pure translation - so layer units ARE canvas + // units here and the bound is simply proportional to the sample extent. This stays a razor-sharp + // convention check regardless: a wrong rotation sign or operand order displaces a sample by the + // extent itself (hundreds of units), three orders of magnitude past this. + val tolerance = 0.05f + 2e-3f * sampleExtent + var checkedEntries = 0 + var checkedRotated = 0 + var checkedScaled = 0 + var worstResidual = 0f + var worstRotatedResidual = 0f + val failures = mutableListOf() + + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + val textureManager = root.textureManager as? CTextureManager ?: continue + val modelImagesByGuid = + elements(textureManager._modelImageGroups) + .filterIsInstance() + .flatMap { group -> elements(group._modelImages).filterIsInstance() } + .mapNotNull { image -> (image.guid as? Guid)?.uuid?.let { uuid -> uuid to image } } + .toMap() + + for ((pageIndex, atlas) in elements(textureManager._textureAtlases).filterIsInstance().withIndex()) { + for (entry in elements(atlas.modelImages).filterIsInstance()) { + val guid = (entry.modelImageGuid as? Guid)?.uuid ?: continue + val modelImage = modelImagesByGuid[guid] ?: continue + // CMO3: ModelImageEntry field atlasLocalToCanvasTransform / CModelImage field + // _materialLocalToCanvasTransform - the two halves of the documented composition. + val atlasToCanvas = entry.atlasLocalToCanvasTransform as? CAffine ?: continue + val materialToCanvas = modelImage._materialLocalToCanvasTransform as? CAffine ?: continue + val placement = placementOf(entry, pageIndex) ?: continue + + checkedEntries++ + if (placement.rotationDegrees != 0f) { + checkedRotated++ + } + if (placement.scaleX != 1f || placement.scaleY != 1f) { + checkedScaled++ + } + for ((layerX, layerY) in samplePoints) { + val viaPlacement = atlasPixelOf(placement, layerX, layerY) + val throughFile = applyAffine(atlasToCanvas, viaPlacement[0], viaPlacement[1]) + val expected = applyAffine(materialToCanvas, layerX, layerY) + val residual = + maxOf( + kotlin.math.abs(throughFile[0] - expected[0]), + kotlin.math.abs(throughFile[1] - expected[1]), + ) + worstResidual = maxOf(worstResidual, residual) + if (placement.rotationDegrees != 0f) { + worstRotatedResidual = maxOf(worstRotatedResidual, residual) + } + if (residual > tolerance && failures.size < 10) { + failures.add( + "${file.name} guid=$guid angle=${placement.rotationDegrees} " + + "scale=(${placement.scaleX}, ${placement.scaleY}) at ($layerX, $layerY): " + + "placement->file (${throughFile[0]}, ${throughFile[1]}) vs " + + "declared (${expected[0]}, ${expected[1]}), residual $residual", + ) + } + } + } + } + } + + println( + "[layer-recovery] composed $checkedEntries placements ($checkedRotated rotated, $checkedScaled scaled) " + + "across ${files.size} corpus files; worst residual $worstResidual (rotated: $worstRotatedResidual), " + + "tolerance $tolerance", + ) + assertTrue(checkedEntries > 0, "no atlas placements were checked; the corpus walk is broken") + // Non-vacuity: an axis-aligned-only run would pass under EITHER rotation sign, so the rotated + // packings must actually be present for this test to mean anything. + assertTrue(checkedRotated > 0, "no rotated placement was checked; the rotation convention is unverified") + assertTrue( + failures.isEmpty(), + "placement composition disagrees with the file's own affines:\n" + failures.joinToString("\n"), + ) + // The rotated packings are what the convention actually hinges on, so hold them to the same bound + // explicitly rather than letting them hide inside an aggregate that the axis-aligned majority passes. + assertTrue( + worstRotatedResidual <= tolerance, + "a rotated placement composes to $worstRotatedResidual, past the $tolerance bound", + ) + } + + /** + * Every CMO3-origin tile that recovers a source binding names one of the layered images the texture + * manager lists, keyed the way the inventory walk keys the decomposed tree: by the Photoshop layer + * id the editor recorded ("lyid:", stable unless suffixed for a duplicate), else by name ("name:", + * never stable) - and the model must say which, rather than pass a name off as a stable key. + */ + @Test + fun corpusTilesBindToTheLayeredImagesTheEditorDecomposed() { + val files = corpusFiles() + Assume.assumeTrue("cmo3.probe names no readable file", files.isNotEmpty()) + for (file in files) { + val puppet = Cmo3Import.fromModelSource(Cmo3.read(file.readBytes()).root as CModelSource) + if (puppet.atlas.tiles.isEmpty()) { + // The blank skeleton: no PSD was ever imported into it, so there is nothing to bind. + println("${file.name}: no tiles, nothing to bind") + continue + } + val sourceIds = puppet.sources.map { source -> source.id }.toSet() + assertTrue(puppet.sources.isNotEmpty(), "${file.name}: the layered images the editor imported are listed") + assertTrue(puppet.sources.all { source -> source.format.isNotEmpty() }, "${file.name}: every source records its format") + var bound = 0 + for (tile in puppet.atlas.tiles) { + val source = tile.source ?: continue + bound++ + assertTrue(source.sourceId in sourceIds, "${file.name}: tile '${tile.name}' binds to a listed source") + val byLayerId = source.layerKey.startsWith("lyid:") + assertTrue(byLayerId || source.layerKey.startsWith("name:"), "${file.name}: tile '${tile.name}' is keyed by Photoshop layer id or by name") + assertEquals(byLayerId && '#' !in source.layerKey, source.stableKey, "${file.name}: a layer-id key is stable, a name or suffixed key is not") + } + assertTrue(bound > 0, "${file.name}: at least one tile recovers its source layer") + // The inventory walk lists the decomposed layer tree, and every binding names one of its rows + // under the same key - the Sources space shows a stray binding otherwise. + val inventoryKeysBySource = puppet.sources.associate { source -> source.id to source.layers.mapTo(HashSet()) { layer -> layer.key } } + assertTrue(puppet.sources.any { source -> source.layers.isNotEmpty() }, "${file.name}: the layered images list their layers") + for (source in puppet.sources) { + // The Sources space keys its rows on the layer key; Erica alone has twenty layers named "1". + assertEquals(source.layers.size, inventoryKeysBySource.getValue(source.id).size, "${file.name}: '${source.name}' lists one key per layer") + } + var stray = 0 + for (tile in puppet.atlas.tiles) { + val source = tile.source ?: continue + if (source.layerKey !in inventoryKeysBySource[source.sourceId].orEmpty()) { + stray++ + } + } + assertEquals(0, stray, "${file.name}: bindings that name no inventory row") + println("${file.name}: ${puppet.sources.size} source(s), ${puppet.sources.sumOf { source -> source.layers.size }} inventory rows, $bound of ${puppet.atlas.tiles.size} tiles bound") + } + } + + /** + * The walk's layer-id keys are the PSD reader's own: for every corpus CMO3 with a same-named PSD + * beside it (test/corpus/psd/.psd), the layered image the editor decomposed from that PSD + * shares its "lyid:" keys with a fresh read of the file, and each shared key names the same layer in + * both. That is the identity a CMO3-origin document re-imports against its PSD on, so a numeric + * coincidence would be caught by the name check and a wrong byte order by the share count. + */ + @Test + fun cmo3LayerIdsAreThePsdReadersKeys() { + val pairs = + corpusFiles().mapNotNull { cmo3File -> + val psdFile = File(cmo3File.parentFile?.parentFile, "psd/${cmo3File.nameWithoutExtension}.psd") + if (psdFile.isFile) cmo3File to psdFile else null + } + Assume.assumeTrue("no corpus CMO3 has a same-named PSD beside it", pairs.isNotEmpty()) + for ((cmo3File, psdFile) in pairs) { + val puppet = Cmo3Import.fromModelSource(Cmo3.read(cmo3File.readBytes()).root as CModelSource) + val psdNameByKey = PsdReader.read(psdFile.readBytes()).layers.associate { layer -> layer.id.raw to layer.name } + // The decomposed image with the most layers is the model's main PSD; its recorded name is the + // artist's file name, not the corpus's, so it cannot be matched by name. + val source = assertNotNull(puppet.sources.filter { source -> source.format == "psd" }.maxByOrNull { source -> source.layers.size }, "${cmo3File.name}: a decomposed PSD is listed") + val layerIdRows = source.layers.filter { layer -> layer.key.startsWith("lyid:") } + assertTrue(layerIdRows.isNotEmpty(), "${cmo3File.name}: the editor recorded Photoshop layer ids") + var shared = 0 + for (row in layerIdRows) { + val psdName = psdNameByKey[row.key] ?: continue + shared++ + assertEquals(psdName, row.name, "${cmo3File.name}: ${row.key} names the same layer in the CMO3 and the PSD") + } + assertTrue(shared * 2 >= layerIdRows.size, "${cmo3File.name}: the PSD shares most of the CMO3's layer ids ($shared of ${layerIdRows.size})") + println("${cmo3File.name} vs ${psdFile.name}: ${layerIdRows.size} layer-id rows, $shared shared with the PSD reader, every name agrees") + } + } + + /** + * The decomposed layer tree reads back as source art keyed exactly as the bindings are: every + * listed file yields a document whose layer keys are the inventory's, and each raster layer's + * pixels decode at its recorded bounds - the pixels a relink pulls when the file itself is gone. + */ + @Test + fun decomposedLayersReadBackAsSourceArt() { + val files = corpusFiles() + Assume.assumeTrue("cmo3.probe names no readable file", files.isNotEmpty()) + var decodedLayers = 0 + for (file in files) { + val cmo3 = Cmo3.read(file.readBytes()) + val root = cmo3.root as CModelSource + val puppet = Cmo3Import.fromModelSource(root) + for (source in puppet.sources) { + val art = assertNotNull(cmo3SourceArtOf(root, source.id) { resource -> cmo3.extractLayerPng(resource) }, "${file.name}: '${source.name}' reads back") + assertEquals(source.layers.map { layer -> layer.key }, art.layers.map { layer -> layer.id.raw }, "${file.name}: '${source.name}' keys as the inventory does") + for ((row, layer) in source.layers.zip(art.layers)) { + assertEquals(row.left, layer.bounds.left) + assertEquals(row.top, layer.bounds.top) + if (layer.kind != SourceLayerKind.Raster) { + continue + } + assertEquals(row.width, layer.raster.width, "${file.name}: '${layer.name}' decodes at its bounds' width") + assertEquals(row.height, layer.raster.height, "${file.name}: '${layer.name}' decodes at its bounds' height") + decodedLayers++ + } + } + } + assertTrue(decodedLayers > 0, "some raster layer decoded") + println("decomposed art: $decodedLayers layer(s) decoded across ${files.size} file(s)") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPlacementFitTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPlacementFitTest.kt new file mode 100644 index 0000000..bbc6734 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasPlacementFitTest.kt @@ -0,0 +1,133 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.type.CAffine +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The atlas-page-to-canvas placement fit behind CTextureInput_TextureAtlasRegion's + * inputImageLocalToCanvasTransform: a least-squares affine from uv*pageSize onto base positions, + * recovered exactly for Cubism-authored (exactly affine) mappings and degraded gracefully for + * degenerate meshes. + */ +class Cmo3AtlasPlacementFitTest { + /** + * Applies the affine to a page-frame point. + * + * @param CAffine transform The fitted transform. + * @param Double pageX Page-frame x. + * @param Double pageY Page-frame y. + * @return Pair The mapped canvas point. + */ + private fun apply(transform: CAffine, pageX: Double, pageY: Double): Pair = + Pair( + transform.m00 * pageX + transform.m01 * pageY + transform.m02, + transform.m10 * pageX + transform.m11 * pageY + transform.m12, + ) + + @Test + fun recoversAnExactAffineMappingIncludingAFlip() { + // canvasX = 0.002*pageX - 1.5; canvasY = -0.002*pageY + 3.25 (a y-flip, the MOC3 case). + val uvs = floatArrayOf(0.1f, 0.2f, 0.6f, 0.2f, 0.1f, 0.9f, 0.6f, 0.9f, 0.35f, 0.55f) + val pageWidth = 4096 + val pageHeight = 2048 + val positions = + FloatArray(uvs.size) { index -> + val vertexIndex = index / 2 + if (index % 2 == 0) { + (0.002 * uvs[2 * vertexIndex] * pageWidth - 1.5).toFloat() + } else { + (-0.002 * uvs[2 * vertexIndex + 1] * pageHeight + 3.25).toFloat() + } + } + val transform = fitAtlasPageToCanvasTransform(uvs, positions, pageWidth, pageHeight) + assertEquals(0.002f, transform.m00, 1e-6f, "x scale") + assertEquals(0f, transform.m01, 1e-6f, "x shear") + assertEquals(-1.5f, transform.m02, 1e-4f, "x offset") + assertEquals(0f, transform.m10, 1e-6f, "y shear") + assertEquals(-0.002f, transform.m11, 1e-6f, "y scale (flip)") + assertEquals(3.25f, transform.m12, 1e-4f, "y offset") + } + + @Test + fun recoversAQuarterTurnPackingFarFromThePageOrigin() { + // The packer rotated this patch a quarter turn, and it sits ~12000 px out on a 16384-square + // page while spanning only ~700. Both halves matter: an origin-referenced normal system is + // swamped by the offset and reads as singular, and what it degrades to - a per-axis + // regression - has no off-diagonal term to put the rotation in, so the patch comes back + // squashed onto the wrong axis (the misplaced-FACE report, off by ~380 px). + val pageWidth = 16384 + val pageHeight = 16384 + val patchOriginX = 12.0 + val patchOriginY = 11782.0 + // canvas = rotate(-90 deg) * (page - patchOrigin) + canvasOrigin. + val canvasOriginX = 1937.0 + val canvasOriginY = 1166.0 + val uvs = FloatArray(2 * 16) + val positions = FloatArray(2 * 16) + var vertexIndex = 0 + for (columnIndex in 0 until 4) { + for (rowIndex in 0 until 4) { + val pageX = patchOriginX + columnIndex * 247.0 + val pageY = patchOriginY + rowIndex * 187.0 + uvs[2 * vertexIndex] = (pageX / pageWidth).toFloat() + uvs[2 * vertexIndex + 1] = (pageY / pageHeight).toFloat() + positions[2 * vertexIndex] = (canvasOriginX + (pageY - patchOriginY)).toFloat() + positions[2 * vertexIndex + 1] = (canvasOriginY - (pageX - patchOriginX)).toFloat() + vertexIndex += 1 + } + } + val transform = fitAtlasPageToCanvasTransform(uvs, positions, pageWidth, pageHeight) + assertEquals(0f, transform.m00, 1e-3f, "x from page x (a quarter turn decouples them)") + assertEquals(1f, transform.m01, 1e-3f, "x from page y") + assertEquals(-1f, transform.m10, 1e-3f, "y from page x") + assertEquals(0f, transform.m11, 1e-3f, "y from page y") + for (checkedVertex in 0 until 16) { + val (canvasX, canvasY) = + apply(transform, uvs[2 * checkedVertex] * pageWidth.toDouble(), uvs[2 * checkedVertex + 1] * pageHeight.toDouble()) + assertEquals(positions[2 * checkedVertex].toDouble(), canvasX, 1.0, "x of vertex $checkedVertex") + assertEquals(positions[2 * checkedVertex + 1].toDouble(), canvasY, 1.0, "y of vertex $checkedVertex") + } + } + + @Test + fun degenerateVerticalSpanStillFitsTheHorizontalAxis() { + // All v identical: the page cloud spans one direction, so the second column is unconstrained; + // x must still fit exactly and y must land on the centroid. + val uvs = floatArrayOf(0.0f, 0.5f, 0.25f, 0.5f, 1.0f, 0.5f) + val positions = floatArrayOf(10f, 7f, 12.5f, 7f, 20f, 7f) + val transform = fitAtlasPageToCanvasTransform(uvs, positions, 100, 100) + for (vertexIndex in 0 until 3) { + val (canvasX, canvasY) = apply(transform, uvs[2 * vertexIndex] * 100.0, uvs[2 * vertexIndex + 1] * 100.0) + assertEquals(positions[2 * vertexIndex].toDouble(), canvasX, 1e-3, "x of vertex $vertexIndex") + assertEquals(7.0, canvasY, 1e-3, "y of vertex $vertexIndex") + } + // The unconstrained direction takes its identity value, never zero: the editor inverts this + // transform to draw the mesh over its patch, and a singular one has no inverse. + val determinant = transform.m00 * transform.m11 - transform.m01 * transform.m10 + assertTrue(kotlin.math.abs(determinant) > 1e-6f, "the fitted affine stays invertible, got determinant $determinant") + } + + @Test + fun singlePointMapsByCentroidTranslation() { + val transform = fitAtlasPageToCanvasTransform(floatArrayOf(0.5f, 0.25f), floatArrayOf(42f, -7f), 200, 400) + val (canvasX, canvasY) = apply(transform, 100.0, 100.0) + assertEquals(42.0, canvasX, 1e-3) + assertEquals(-7.0, canvasY, 1e-3) + } + + @Test + fun emptyMeshYieldsIdentity() { + val transform = fitAtlasPageToCanvasTransform(FloatArray(0), FloatArray(0), 1024, 1024) + assertTrue( + transform.m00 == 1f && + transform.m01 == 0f && + transform.m02 == 0f && + transform.m10 == 0f && + transform.m11 == 1f && + transform.m12 == 0f, + "identity for an empty mesh", + ) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasUndedupTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasUndedupTest.kt new file mode 100644 index 0000000..6ef5a12 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3AtlasUndedupTest.kt @@ -0,0 +1,238 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +class Cmo3AtlasUndedupTest { + private val pageSize = 32 + private val uvs = floatArrayOf(4f / 32f, 4f / 32f, 28f / 32f, 4f / 32f, 4f / 32f, 28f / 32f, 28f / 32f, 28f / 32f) + private val indices = intArrayOf(0, 1, 2, 1, 2, 3) + + private fun page(): Cmo3Conversion.AtlasPage { + val rgba = ByteArray(pageSize * pageSize * 4) + for (rowIndex in 12 until 19) { + for (columnIndex in 10 until 15) { + rgba.fill(0xFF.toByte(), (rowIndex * pageSize + columnIndex) * 4, (rowIndex * pageSize + columnIndex) * 4 + 4) + } + } + return Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, rgba)), pageSize, pageSize) + } + + private fun drawable(id: String, positions: FloatArray): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions = positions, uvs = uvs.copyOf(), indices = indices.copyOf()), + geometryGrid = null, + ) + + private fun puppet(drawables: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { OrgChild.Drawable(it.id) }, + rootPartId = null, + canvasWidth = 200f, + canvasHeight = 200f, + worldOriginX = 100f, + worldOriginZ = -100f, + runtimeTarget = RuntimeTarget.Cubism53, + ) + + @Test + fun mirroredTwinsGetOwnSlots() { + val straightPositions = FloatArray(uvs.size) { index -> uvs[index] * pageSize } + val shiftedPositions = FloatArray(uvs.size) { index -> uvs[index] * pageSize + if (index % 2 == 0) 50f else 0f } + val model = puppet(listOf(drawable("TwinA", straightPositions), drawable("TwinB", shiftedPositions))) + val pageIndexByDrawableId = mapOf("TwinA" to 0, "TwinB" to 0) + val result = Cmo3AtlasUndedup.undeduplicate(model, listOf(page()), pageIndexByDrawableId) + + assertEquals(listOf("TwinB"), result.duplicatedDrawableIds, "the second placement duplicates") + assertEquals(2, result.pages.size, "a synthesized page is appended") + assertEquals(0, result.pageIndexByDrawableId.getValue("TwinA"), "the first placement keeps its page") + assertEquals(1, result.pageIndexByDrawableId.getValue("TwinB"), "the duplicate moves to the new page") + val twinA = result.puppet.drawables.single { it.id.raw == "TwinA" } + assertContentEquals(uvs, twinA.mesh?.uvs, "the first placement keeps its uvs") + + // The remapped uvs must sample the same pixels on the new page as the originals did on the + // old page. + val twinB = result.puppet.drawables.single { it.id.raw == "TwinB" } + val newUvs = twinB.mesh?.uvs ?: error("twin B lost its mesh") + val sourcePage = PngCodec.read(page().pngBytes) + val extraPage = PngCodec.read(result.pages[1].pngBytes) + var componentIndex = 0 + while (componentIndex + 1 < uvs.size) { + // Sample just inside the quad corner so both lookups stay in range. + val sourceX = (uvs[componentIndex] * pageSize).toInt().coerceIn(0, pageSize - 1) + val sourceY = (uvs[componentIndex + 1] * pageSize).toInt().coerceIn(0, pageSize - 1) + val newX = (newUvs[componentIndex] * extraPage.width).toInt().coerceIn(0, extraPage.width - 1) + val newY = (newUvs[componentIndex + 1] * extraPage.height).toInt().coerceIn(0, extraPage.height - 1) + // Compare a pixel INSIDE the block region via the same offset from the quad corner. + val insideSourceX = sourceX + (12 - 4) + val insideSourceY = sourceY + (14 - 4) + val insideNewX = newX + (12 - 4) + val insideNewY = newY + (14 - 4) + if (insideSourceX in 0 until pageSize && + insideSourceY in 0 until pageSize && + insideNewX in 0 until extraPage.width && + insideNewY in 0 until extraPage.height + ) { + assertEquals( + sourcePage.rgba[(insideSourceY * pageSize + insideSourceX) * 4 + 3], + extraPage.rgba[(insideNewY * extraPage.width + insideNewX) * 4 + 3], + "pixel content under the remapped uvs matches", + ) + } + componentIndex += 2 + } + // The block itself must be present somewhere opaque on the synthesized page. + assertTrue(extraPage.rgba.indices.step(4).any { offset -> extraPage.rgba[offset + 3].toInt() != 0 }, "the extra page carries pixels") + } + + @Test + fun coLocatedDuplicatesAreNotSplit() { + val positions = FloatArray(uvs.size) { index -> uvs[index] * pageSize } + val model = puppet(listOf(drawable("VariantA", positions), drawable("VariantB", positions.copyOf()))) + val result = Cmo3AtlasUndedup.undeduplicate(model, listOf(page()), mapOf("VariantA" to 0, "VariantB" to 0)) + assertTrue(result.duplicatedDrawableIds.isEmpty(), "co-located duplicates share their slot") + assertEquals(1, result.pages.size, "no synthesized page") + assertEquals(model, result.puppet, "the puppet passes through untouched") + } + + /** + * A 64 x 64 page with two slots - one block in each - so two independent twin pairs share one + * synthesized page. + */ + private val wideSize = 64 + private val slotAUvs = floatArrayOf(4f / 64f, 4f / 64f, 28f / 64f, 4f / 64f, 4f / 64f, 28f / 64f, 28f / 64f, 28f / 64f) + private val slotBUvs = floatArrayOf(36f / 64f, 36f / 64f, 60f / 64f, 36f / 64f, 36f / 64f, 60f / 64f, 60f / 64f, 60f / 64f) + + private fun widePage(blocks: List): Cmo3Conversion.AtlasPage { + val rgba = ByteArray(wideSize * wideSize * 4) + for (block in blocks) { + for (rowIndex in block[1] until block[3]) { + for (columnIndex in block[0] until block[2]) { + val offset = (rowIndex * wideSize + columnIndex) * 4 + rgba[offset] = block[4].toByte() + rgba[offset + 1] = (columnIndex * 3).toByte() + rgba[offset + 2] = (rowIndex * 5).toByte() + rgba[offset + 3] = 0xFF.toByte() + } + } + } + return Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(wideSize, wideSize, rgba)), wideSize, wideSize) + } + + private fun drawableOver(id: String, slotUvs: FloatArray, shiftX: Float): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions = FloatArray(slotUvs.size) { index -> slotUvs[index] * wideSize + if (index % 2 == 0) shiftX else 0f }, uvs = slotUvs.copyOf(), indices = indices.copyOf()), + geometryGrid = null, + ) + + /** + * Every pixel of a duplicated drawable's patch rect, transparent margin included, sits under its + * remapped uvs exactly as it sat under the originals: the reserve keeps the margin clear and + * nothing is extruded into it. + */ + private fun assertPatchCarriedWhole(drawableId: String, result: Cmo3AtlasUndedup.Result, sourcePage: Cmo3Conversion.AtlasPage, slotUvs: FloatArray) { + val drawable = result.puppet.drawables.single { candidate -> candidate.id.raw == drawableId } + val newUvs = drawable.mesh?.uvs ?: error("$drawableId lost its mesh") + val newPage = PngCodec.read(result.pages[result.pageIndexByDrawableId.getValue(drawableId)].pngBytes) + val source = PngCodec.read(sourcePage.pngBytes) + val rect = Cmo3ImageChainBuilder.patchRectOf(slotUvs, sourcePage.width, sourcePage.height)!! + // The remap is a whole-pixel translation: read it off the first vertex. + val deltaX = Math.round(newUvs[0] * newPage.width - slotUvs[0] * sourcePage.width) + val deltaY = Math.round(newUvs[1] * newPage.height - slotUvs[1] * sourcePage.height) + for (rowIndex in rect[1] until rect[3]) { + for (columnIndex in rect[0] until rect[2]) { + val sourceOffset = (rowIndex * source.width + columnIndex) * 4 + val newOffset = ((rowIndex + deltaY) * newPage.width + columnIndex + deltaX) * 4 + for (channel in 0 until 4) { + assertEquals(source.rgba[sourceOffset + channel], newPage.rgba[newOffset + channel], "$drawableId pixel ($columnIndex, $rowIndex) channel $channel") + } + } + } + } + + @Test + fun severalTwinsPackOntoOnePageAndEachKeepsItsWholePatch() { + val page = widePage(listOf(intArrayOf(10, 12, 15, 19, 40), intArrayOf(44, 40, 50, 47, 90))) + val model = + puppet( + listOf( + drawableOver("A1", slotAUvs, 0f), + drawableOver("A2", slotAUvs, 50f), + drawableOver("B1", slotBUvs, 0f), + drawableOver("B2", slotBUvs, 70f), + ), + ) + val pageIndexByDrawableId = mapOf("A1" to 0, "A2" to 0, "B1" to 0, "B2" to 0) + val result = Cmo3AtlasUndedup.undeduplicate(model, listOf(page), pageIndexByDrawableId) + assertEquals(listOf("A2", "B2"), result.duplicatedDrawableIds.sorted()) + assertTrue(result.sharedDrawableIds.isEmpty()) + assertEquals(2, result.pages.size, "both further placements share one synthesized page") + assertEquals(1, result.pageIndexByDrawableId.getValue("A2")) + assertEquals(1, result.pageIndexByDrawableId.getValue("B2")) + assertEquals(0, result.pageIndexByDrawableId.getValue("A1")) + assertEquals(0, result.pageIndexByDrawableId.getValue("B1")) + assertPatchCarriedWhole("A2", result, page, slotAUvs) + assertPatchCarriedWhole("B2", result, page, slotBUvs) + val a2 = result.puppet.drawables.single { drawable -> drawable.id.raw == "A2" }.mesh!!.uvs + val b2 = result.puppet.drawables.single { drawable -> drawable.id.raw == "B2" }.mesh!!.uvs + assertNotEquals(a2[0] to a2[1], b2[0] to b2[1], "the two patches landed apart") + val synthesized = PngCodec.read(result.pages[1].pngBytes) + assertTrue(synthesized.width <= wideSize && synthesized.height <= wideSize, "the page shrinks to its content") + + // Deterministic: the same inputs pack to the same bytes and the same remaps. + val again = Cmo3AtlasUndedup.undeduplicate(model, listOf(page), pageIndexByDrawableId) + assertContentEquals(result.pages[1].pngBytes, again.pages[1].pngBytes) + assertContentEquals(a2, again.puppet.drawables.single { drawable -> drawable.id.raw == "A2" }.mesh!!.uvs) + assertContentEquals(b2, again.puppet.drawables.single { drawable -> drawable.id.raw == "B2" }.mesh!!.uvs) + } + + @Test + fun aTransparentTwinSharesItsSlotSilently() { + // Slot A has no opaque pixel at all (a hit area's): the packer has nothing to place, so the + // further placement stays on the source slot with its uvs as they were, and nothing is + // reported - nothing shows at either placement. + val page = widePage(listOf(intArrayOf(44, 40, 50, 47, 90))) + val model = + puppet( + listOf( + drawableOver("GhostA", slotAUvs, 0f), + drawableOver("GhostB", slotAUvs, 50f), + drawableOver("B1", slotBUvs, 0f), + drawableOver("B2", slotBUvs, 70f), + ), + ) + val result = Cmo3AtlasUndedup.undeduplicate(model, listOf(page), mapOf("GhostA" to 0, "GhostB" to 0, "B1" to 0, "B2" to 0)) + assertTrue(result.sharedDrawableIds.isEmpty(), "a transparent twin is not the export notice's case") + assertEquals(listOf("B2"), result.duplicatedDrawableIds) + assertEquals(2, result.pages.size, "one synthesized page, for the twin with art") + assertEquals(0, result.pageIndexByDrawableId.getValue("GhostB"), "the transparent twin stays on the source page") + assertContentEquals(slotAUvs, result.puppet.drawables.single { drawable -> drawable.id.raw == "GhostB" }.mesh?.uvs, "with its uvs untouched") + assertPatchCarriedWhole("B2", result, page, slotBUvs) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ConversionRoundTripTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ConversionRoundTripTest.kt new file mode 100644 index 0000000..829279b --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ConversionRoundTripTest.kt @@ -0,0 +1,268 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.png.PngCodec +import org.umamo.interop.DocumentField +import org.umamo.interop.EntityDiff +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.cmo3.Cmo3Conversion.AtlasPage +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The MOC3 -> CMO3 self round trip: every corpus .moc3 with a model3 sidecar converts to a + * fresh CMO3, and re-importing the written file reproduces the source PuppetModel with only the + * documented residues - WORLD_ORIGIN (the moc stores a real origin; CMO3 import derives the + * canvas center), MESH_POSITIONS (the exported base is the rest-pose canvas frame while a + * MOC3-origin puppet's base is parent-deformer-local), and bounded-ULP drift on keyform deltas + * (fresh absolutes are base + delta and the re-import subtracts, which is not an IEEE identity). + */ +class Cmo3ConversionRoundTripTest { + private val geometryUlpTolerance = 1e-3f + + @Test + fun corpusMocModelsConvertAndRoundTrip() { + val samplesDirectory = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + ?: run { + println("moc3.samples not present; skipping MOC3 conversion round trip") + return + } + val mocFiles = + samplesDirectory + .walkTopDown() + .filter { file -> file.isFile && file.extension == "moc3" } + .filter { file -> File(file.parentFile, "${file.nameWithoutExtension}.model3.json").isFile } + .sortedBy { file -> file.name } + .toList() + assertTrue(mocFiles.isNotEmpty(), "no corpus moc3 with a model3 sidecar under $samplesDirectory") + val failures = ArrayList() + for (mocFile in mocFiles) { + runCatching { roundTripOne(mocFile, failures) } + .onFailure { failure -> failures.add("${mocFile.name}: threw $failure") } + } + assertTrue(failures.isEmpty(), "MOC3 conversion round trip failed:\n" + failures.joinToString("\n")) + } + + /** + * Converts one corpus moc and validates the self round trip. + * + * @param File mocFile The .moc3 file (sidecars beside it). + * @param ArrayList failures The shared violation collector. + */ + private fun roundTripOne(mocFile: File, failures: ArrayList) { + val label = mocFile.name + val mocDocument = Moc3.read(mocFile.readBytes()) + val manifest = Moc3.readModel3(File(mocFile.parentFile, "${mocFile.nameWithoutExtension}.model3.json").readText()) + val textureFiles = manifest.fileReferences.textures.map { textureReference -> File(mocFile.parentFile, textureReference) } + if (textureFiles.any { textureFile -> !textureFile.isFile }) { + println("$label: atlas pages not in the corpus; skipping") + return + } + val pages = + textureFiles.map { textureFile -> + val pngBytes = textureFile.readBytes() + val decoded = PngCodec.read(pngBytes) + AtlasPage(pngBytes, decoded.width, decoded.height) + } + // displayInfo deliberately null: the same puppet is both the conversion source and the + // comparison target, so cosmetic names/groups cancel out either way. The rest meshes are + // normalized to canvas space exactly like the app's MOC3 document loader - the export's + // source-level positions and the whole texture-placement web are canvas geometry, so + // converting a raw parent-local puppet would write deformer-local coordinates there. + val puppet = org.umamo.render.restMeshesToCanvasSpace(Moc3Import.fromMocDocument(mocDocument, displayInfo = null)) + val pageIndexByDrawableId = mocDocument.artMeshes.associate { artMesh -> artMesh.id to artMesh.textureIndex } + + val result = + Cmo3Conversion.freshCmo3( + puppet = puppet, + pages = pages, + pageIndexByDrawableId = pageIndexByDrawableId, + modelName = mocFile.nameWithoutExtension, + nowMillis = 1_700_000_000_000L, + obfuscateKey = 0x5EEDBEEF, + ) + // Every MOC3-origin conversion MUST warn that it has no source artwork - that is the one + // notice describing the whole file rather than an entity in it, so its absence is as much a + // defect as a spurious notice would be. + if (result.report.notices.none { notice -> notice is ExportNotice.MissingSourceArt }) { + failures.add("$label: missing the MissingSourceArt notice") + } + // Documented residues may notice: the world origin (moc stores one; CMO3 derives the canvas + // center) and part statics shadowed by their keyform tracks (import re-derives from the + // first form, so a disagreeing static cannot be stored independently). + result.report.notices.filterNot { notice -> + notice is ExportNotice.MissingSourceArt || + ( + notice is ExportNotice.UnsupportedChange && + ( + notice.reason == ExportNoticeReason.NoAuthoredWorldOrigin || + notice.reason == ExportNoticeReason.StaticDrawOrderShadowedByKeyforms || + notice.reason == ExportNoticeReason.CompositeStaticsShadowedByKeyforms + ) + ) + }.forEach { notice -> + failures.add("$label: unexpected notice $notice") + } + + val written = Cmo3.write(result.model) + // Each converted corpus model doubles as a manual official-editor gate input. + File("build/converted-${mocFile.nameWithoutExtension}.cmo3").writeBytes(written) + + // Prologue completeness: re-running the writer's own reconciliation on the written bytes + // must be a no-op - a missing or stale import/version PI here is exactly the malformed-file + // class the official editor rejects (it resolves element tags through the import list). + val writtenMainXml = + org.umamo.format.cmo3.caff.CaffCodec.read(written) + .firstByTag(org.umamo.format.cmo3.caff.CaffArchive.TAG_MAIN_XML)!! + .content + val reparsed = org.umamo.format.cmo3.xml.XmlCodec.parse(writtenMainXml) + org.umamo.format.cmo3.Cmo3Author.completePrologue(reparsed) + if (!org.umamo.format.cmo3.xml.XmlCodec.write(reparsed).contentEquals(writtenMainXml)) { + failures.add("$label: written prologue is incomplete (completePrologue on the output is not a no-op)") + } + val reimportedSource = + Cmo3.read(written).root as? CModelSource + ?: run { + failures.add("$label: re-read root is not a CModelSource") + return + } + checkDrawablesSampleTheAtlasPages(label, reimportedSource, failures) + // Diff against the puppet the conversion ENCODED: the atlas un-dedup prepass remaps a + // baked twin's uvs onto its own synthesized slot, so the caller's puppet is not the + // round-trip target wherever twins existed. + val reimported = Cmo3Import.fromModelSource(reimportedSource) + val residual = org.umamo.interop.diffPuppetModels(reimported, result.puppet) + if (residual.isEmpty) { + return + } + + // Allowed residues: WORLD_ORIGIN plus bounded-ULP GEOMETRY/BLEND_SHAPES drift. + (residual.document - setOf(DocumentField.WORLD_ORIGIN)).forEach { field -> + failures.add("$label: unexpected document residue $field") + } + residual.parameters.forEach { failures.add("$label: parameter residue $it") } + residual.parameterGroups.forEach { failures.add("$label: group residue $it") } + for (entityDiff in residual.parts) { + // The statics-shadowed residue class: a static disagreeing with its track's head cell + // (noticed above) re-imports as the head value. + if (entityDiff !is EntityDiff.Changed || entityDiff.fields.any { field -> field.name !in setOf("DRAW_ORDER", "COMPOSITE") }) { + failures.add("$label: part residue $entityDiff") + } + } + residual.glues.forEach { failures.add("$label: glue residue $it") } + for (entityDiff in residual.deformers) { + if (entityDiff !is EntityDiff.Changed || entityDiff.fields.any { field -> field.name !in setOf("GEOMETRY", "BLEND_SHAPES") }) { + failures.add("$label: deformer residue $entityDiff") + } + } + for (entityDiff in residual.drawables) { + // MESH_POSITIONS: the exported base is the rest-pose CANVAS frame while a MOC3-origin + // puppet's base is parent-deformer-local; the absolute-geometry drift check below is + // what guards the semantics (base + delta is the render-visible invariant). + if (entityDiff !is EntityDiff.Changed || entityDiff.fields.any { field -> field.name !in setOf("GEOMETRY", "BLEND_SHAPES", "MESH_POSITIONS") }) { + failures.add("$label: drawable residue $entityDiff") + continue + } + val drift = maxGeometryDrift(result.puppet, reimported, entityDiff.id.raw) + if (drift > geometryUlpTolerance) { + failures.add("$label: drawable ${entityDiff.id.raw} geometry drifted by $drift") + } + } + } + + /** + * Asserts every re-read drawable samples one of the document's own atlas page resources, by + * IDENTITY rather than by dimensions or archive path. + * + * This is the invariant that decides whether a drawable's stored uvs are page-frame + * (docs/format/CMO3.md section 6): a document may carry an atlas while its drawables sample + * per-layer rasters instead, so the reader compares the sampled resource against the atlases' + * cachedAtlasImage - and a CImageResource has no value equality, which makes that comparison + * identity. A conversion that hands the drawables their own equal-but-distinct twin of the page + * therefore writes a file whose every drawable re-imports as never-packed, dropping the packing + * inverse that maps its mesh onto its source layer. Nothing in the model diff sees that - the + * uvs themselves round-trip fine - so it needs its own check. + * + * @param String label The corpus model name, for failure text. + * @param CModelSource source The re-read model root. + * @param ArrayList failures The shared violation collector. + */ + private fun checkDrawablesSampleTheAtlasPages(label: String, source: CModelSource, failures: ArrayList) { + // CMO3: CTextureManager field _textureAtlases -> CTextureAtlas field cachedAtlasImage. + val textureManager = source.textureManager as? org.umamo.format.cmo3.model.gen.CTextureManager ?: return + val pageResources = + Cmo3Import + .elementsOf(textureManager._textureAtlases) + .filterIsInstance() + .mapNotNull { atlas -> atlas.cachedAtlasImage as? org.umamo.format.cmo3.model.custom.CImageResource } + if (pageResources.isEmpty()) { + return + } + val pageIdentities = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + pageIdentities.addAll(pageResources) + // CMO3: CDrawableSourceSet field _sources -> CArtMeshSource field texture -> GTexture2D field + // srcImageResource. + val meshes = + Cmo3Import + .elementsOf((source.drawableSourceSet as? org.umamo.format.cmo3.model.gen.CDrawableSourceSet)?._sources) + .filterIsInstance() + val strays = + meshes.filter { mesh -> + val sampled = + (mesh.texture as? org.umamo.format.cmo3.model.gen.GTexture2D) + ?.srcImageResource as? org.umamo.format.cmo3.model.custom.CImageResource + sampled != null && sampled !in pageIdentities + } + if (strays.isNotEmpty()) { + failures.add( + "$label: ${strays.size} of ${meshes.size} drawables sample a resource that is not one of the " + + "${pageResources.size} atlas page resources", + ) + } + } + + /** + * The largest per-component ABSOLUTE keyform-position difference between the two models' + * drawable grids (base + delta per cell). + * + * Absolutes, not raw deltas: the exported source-level base is the rest-pose CANVAS frame + * while a MOC3-origin puppet's base is parent-deformer-local, so the re-imported deltas shift + * by exactly the base difference. The blended geometry - base plus delta - is the semantic + * invariant (grids sum to one, so the base cancels out of every rendered pose). + * + * @param PuppetModel source The conversion source. + * @param PuppetModel reimported The re-imported model. + * @param String drawableIdRaw The drawable to compare. + * @return Float The maximum absolute component difference (0 when either grid is absent). + */ + private fun maxGeometryDrift( + source: org.umamo.runtime.model.PuppetModel, + reimported: org.umamo.runtime.model.PuppetModel, + drawableIdRaw: String, + ): Float { + val sourceDrawable = source.drawables.firstOrNull { it.id.raw == drawableIdRaw } + val reimportedDrawable = reimported.drawables.firstOrNull { it.id.raw == drawableIdRaw } + val sourceGrid = sourceDrawable?.geometryGrid ?: return 0f + val reimportedGrid = reimportedDrawable?.geometryGrid ?: return 0f + val sourceBase = sourceDrawable.mesh?.positions ?: return 0f + val reimportedBase = reimportedDrawable.mesh?.positions ?: return 0f + val reimportedByCoordinate = reimportedGrid.cells.associate { cell -> cell.coordinate.toList() to cell.form.positionDeltas } + var maxDifference = 0f + for (cell in sourceGrid.cells) { + val reimportedDeltas = reimportedByCoordinate[cell.coordinate.toList()] ?: return Float.MAX_VALUE + for (component in cell.form.positionDeltas.indices) { + val sourceAbsolute = sourceBase.getOrElse(component) { 0f } + cell.form.positionDeltas[component] + val reimportedAbsolute = reimportedBase.getOrElse(component) { 0f } + reimportedDeltas.getOrElse(component) { 0f } + maxDifference = maxOf(maxDifference, abs(sourceAbsolute - reimportedAbsolute)) + } + } + return maxDifference + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ExportIdentityTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ExportIdentityTest.kt new file mode 100644 index 0000000..db280ef --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ExportIdentityTest.kt @@ -0,0 +1,93 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.diffPuppetModels +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The export reconcile's no-change gate, across the whole corpus: importing a CMO3 and applying the + * unchanged model back must leave the graph untouched - zero notices, and the re-emitted + * decompressed main.xml byte-identical to the source. Also pins that two imports of the same graph + * diff empty (import determinism), which is what the reconcile baseline relies on. + */ +class Cmo3ExportIdentityTest { + @Test + fun unchangedModelAppliesAsAByteIdenticalNoOp() { + val spec = + System.getProperty("cmo3.probe") + ?: run { + println("cmo3.probe not present; skipping export identity gate") + return + } + val files = spec.split(',').map { File(it.trim()) }.filter { it.isFile } + if (files.isEmpty()) { + println("cmo3.probe lists no readable samples; skipping") + return + } + + val failures = ArrayList() + for (file in files) { + val bytes = file.readBytes() + val sourceMainXml = CaffCodec.read(bytes).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + val cmo3 = Cmo3.read(bytes) + val modelSource = cmo3.root as? CModelSource + if (modelSource == null) { + failures.add("${file.name}: root is not a CModelSource") + continue + } + val puppet = Cmo3Import.fromModelSource(modelSource) + + // Import determinism: the reconcile baseline is a second import of the same graph, so + // two imports must diff empty or every export would see phantom changes. + val baseline = Cmo3Import.fromModelSource(modelSource) + val selfDiff = diffPuppetModels(baseline, puppet) + if (!selfDiff.isEmpty) { + failures.add("${file.name}: two imports of one graph diff non-empty: $selfDiff") + continue + } + + val report = Cmo3Export.apply(puppet, cmo3) + if (!report.isEmpty) { + failures.add("${file.name}: no-change apply produced notices: ${report.notices}") + continue + } + + val reemittedMainXml = + CaffCodec.read(Cmo3.write(cmo3)).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + firstByteDiff(sourceMainXml, reemittedMainXml)?.let { message -> + failures.add("${file.name}: $message") + } + } + assertTrue(failures.isEmpty(), "export identity gate failed:\n" + failures.joinToString("\n")) + } + + /** + * The first byte difference between the two buffers as a windowed diagnostic, or null when they + * are byte-identical (the AllVersionsGateTest reporter shape). + * + * @param ByteArray expected The source main.xml bytes. + * @param ByteArray actual The re-emitted main.xml bytes. + * @return String? The diagnostic, or null on identity. + */ + private fun firstByteDiff(expected: ByteArray, actual: ByteArray): String? { + val limit = minOf(expected.size, actual.size) + val diff = (0 until limit).firstOrNull { expected[it] != actual[it] } ?: -1 + if (diff < 0 && expected.size == actual.size) { + return null + } + val at = if (diff < 0) limit else diff + val start = maxOf(0, at - 80) + + fun ByteArray.window() = decodeToString(start, minOf(size, at + 90)).replace("\r", "\\r").replace("\n", "\\n") + return buildString { + append("not byte-identical: sizes expected=${expected.size} actual=${actual.size}, first diff @ $at\n") + append(" expected: …${expected.window()}\n") + append(" actual: …${actual.window()}") + } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3IconDifferentialTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3IconDifferentialTest.kt new file mode 100644 index 0000000..997d140 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3IconDifferentialTest.kt @@ -0,0 +1,188 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.cropped +import org.umamo.format.raster.fittedInto +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Our icon fit against the official editor's own icons, over every layer and model image of the + * corpus sample: the same art fitted into the same square lands on the same pixels - the alpha + * bounding box within a pixel, the covered pixels' channels close on average. This is what pins + * the fit rule (longer edge fills, aspect held, centered) to the editor's, rather than to a + * guess. The whole-art fit is the rule the corpus supports (517 of 528 Erica icons within a pixel; + * a fit of the art trimmed to its non-transparent bounds lands 506); the bounds are loose on + * purpose, since the editor's resampling filter is its own and a per-pixel match is not the claim. + * + * Skips without the corpus sample. + */ +class Cmo3IconDifferentialTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + /** The alpha bounding box of a square icon as (left, top, width, height), or null when blank. */ + private fun alphaBox(image: RasterImage): IntArray? { + var minX = Int.MAX_VALUE + var minY = Int.MAX_VALUE + var maxX = -1 + var maxY = -1 + for (y in 0 until image.height) { + for (x in 0 until image.width) { + if ((image.rgba[(y * image.width + x) * 4 + 3].toInt() and 0xFF) > 0) { + minX = minOf(minX, x) + minY = minOf(minY, y) + maxX = maxOf(maxX, x) + maxY = maxOf(maxY, y) + } + } + } + return if (maxX < 0) null else intArrayOf(minX, minY, maxX - minX + 1, maxY - minY + 1) + } + + /** The mean absolute channel difference over pixels either image covers, premultiplied so a fringe compares by what it shows. */ + private fun meanDifference(ours: RasterImage, official: RasterImage): Double { + var total = 0.0 + var count = 0 + for (pixel in 0 until ours.width * ours.height) { + val offset = pixel * 4 + val ourAlpha = ours.rgba[offset + 3].toInt() and 0xFF + val theirAlpha = official.rgba[offset + 3].toInt() and 0xFF + if (ourAlpha == 0 && theirAlpha == 0) { + continue + } + for (channel in 0 until 3) { + val ourPremultiplied = (ours.rgba[offset + channel].toInt() and 0xFF) * ourAlpha / 255.0 + val theirPremultiplied = (official.rgba[offset + channel].toInt() and 0xFF) * theirAlpha / 255.0 + total += abs(ourPremultiplied - theirPremultiplied) + } + total += abs(ourAlpha - theirAlpha) + count += 4 + } + return if (count == 0) 0.0 else total / count + } + + private class Comparison(val name: String, val size: Int, val artWidth: Int, val artHeight: Int, val boxDelta: Int, val trimmedBoxDelta: Int, val meanDifference: Double, val trimmedMeanDifference: Double, val ourBox: IntArray?, val trimmedBox: IntArray?, val theirBox: IntArray?) + + /** The art trimmed to its non-transparent bounds, or the art itself when it has none or is already tight. */ + private fun trimmed(art: RasterImage): RasterImage { + val box = alphaBox(art) ?: return art + return art.cropped(org.umamo.format.art.LayerBounds(box[0], box[1], box[2], box[3])) + } + + private fun boxDeltaOf(ours: IntArray?, theirs: IntArray?, size: Int): Int = + if (ours == null || theirs == null) { + if (ours == null && theirs == null) 0 else size + } else { + (0 until 4).maxOf { component -> abs(ours[component] - theirs[component]) } + } + + @Test + fun ourFitLandsOnTheOfficialIcons() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the icon differential") + return + } + val cmo3 = Cmo3.read(file.readBytes()) + val root = cmo3.root as CModelSource + val textureManager = root.textureManager as CTextureManager + val comparisons = ArrayList() + + /** + * Compares our fit of [art] at [size] with the official icon at [iconSlot]. + * + * @param String name The owner's name, for the report. + * @param RasterImage art The art the icon shows. + * @param Int size The square's edge. + * @param Any? iconSlot The official CImageIcon. + */ + fun compare(name: String, art: RasterImage, size: Int, iconSlot: Any?) { + val path = Cmo3Icons.archivePathOf(iconSlot) ?: return + val official = PngCodec.read(cmo3.archive.byPath(path)?.content ?: return) + if (official.width != size || official.height != size) { + return + } + val ours = art.fittedInto(size) + val oursTrimmed = trimmed(art).fittedInto(size) + val theirBox = alphaBox(official) + val ourBox = alphaBox(ours) + val trimmedBox = alphaBox(oursTrimmed) + comparisons.add( + Comparison( + name, + size, + art.width, + art.height, + boxDeltaOf(ourBox, theirBox, size), + boxDeltaOf(trimmedBox, theirBox, size), + meanDifference(ours, official), + meanDifference(oursTrimmed, official), + ourBox, + trimmedBox, + theirBox, + ), + ) + } + for (wrapper in Cmo3Import.elementsOf(textureManager._rawImages).filterIsInstance()) { + val image = wrapper.image as? CLayeredImage ?: continue + for (walked in walkLayeredImage(image)) { + val resource = walked.layer.imageResource as? CImageResource ?: continue + val art = PngCodec.read(cmo3.extractLayerPng(resource) ?: continue) + compare("layer ${walked.layer.name}", art, 64, walked.layer.icon64) + compare("layer ${walked.layer.name}", art, 16, walked.layer.icon16) + } + } + for (group in Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance()) { + for (modelImage in Cmo3Import.elementsOf(group._modelImages).filterIsInstance()) { + val resource = modelImage._filteredImage as? CImageResource ?: continue + val art = PngCodec.read(cmo3.extractLayerPng(resource) ?: continue) + compare("model image ${modelImage.name}", art, 16, modelImage.icon16) + } + } + assertTrue(comparisons.isNotEmpty(), "the sample carries icons to compare") + println( + "icon differential: ${comparisons.size} icons; whole-art fit: box<=1 ${comparisons.count { comparison -> comparison.boxDelta <= 1 }}, mean avg ${"%.2f".format(comparisons.map { comparison -> comparison.meanDifference }.average())}; " + + "trimmed fit: box<=1 ${comparisons.count { comparison -> comparison.trimmedBoxDelta <= 1 }}, mean avg ${"%.2f".format(comparisons.map { comparison -> comparison.trimmedMeanDifference }.average())}", + ) + for (comparison in comparisons.sortedByDescending { comparison -> comparison.boxDelta }.take(6)) { + println(" box outlier ${comparison.name}@${comparison.size} art ${comparison.artWidth}x${comparison.artHeight}: ours ${comparison.ourBox?.toList()} trimmed ${comparison.trimmedBox?.toList()} theirs ${comparison.theirBox?.toList()} mean ${"%.1f".format(comparison.meanDifference)} / trimmed ${"%.1f".format(comparison.trimmedMeanDifference)}") + } + for (comparison in comparisons.sortedByDescending { comparison -> comparison.meanDifference }.take(6)) { + println(" mean outlier ${comparison.name}@${comparison.size} art ${comparison.artWidth}x${comparison.artHeight}: ours ${comparison.ourBox?.toList()} trimmed ${comparison.trimmedBox?.toList()} theirs ${comparison.theirBox?.toList()} mean ${"%.1f".format(comparison.meanDifference)} / trimmed ${"%.1f".format(comparison.trimmedMeanDifference)}") + } + // The rule is pinned by the population, the per-icon bounds catch a gross error: nearly every + // icon's box lands within a pixel of the editor's (the rest are soft-alpha layers whose faint + // fringe the editor's filter drops), and the thin 16px icons carry the largest per-icon means + // because a one-pixel width difference on a five-pixel sliver is a large fraction of it. + val withinAPixel = comparisons.count { comparison -> comparison.boxDelta <= 1 } + assertTrue(withinAPixel >= comparisons.size * 95 / 100, "at least 95% of the boxes land within a pixel: $withinAPixel of ${comparisons.size}") + val averageMean = comparisons.map { comparison -> comparison.meanDifference }.average() + assertTrue(averageMean <= AVERAGE_MEAN_DIFFERENCE_BOUND, "the icons are close to the editor's on average: ${"%.2f".format(averageMean)}") + val boxOutliers = comparisons.filter { comparison -> comparison.boxDelta > BOX_DELTA_BOUND } + assertTrue(boxOutliers.isEmpty(), "alpha boxes near the official icons: ${boxOutliers.take(8).map { comparison -> "${comparison.name}@${comparison.size}=${comparison.boxDelta}" }}") + val meanOutliers = comparisons.filter { comparison -> comparison.meanDifference > MEAN_DIFFERENCE_BOUND } + assertTrue(meanOutliers.isEmpty(), "covered pixels close to the official icons: ${meanOutliers.take(8).map { comparison -> "${comparison.name}@${comparison.size}=${"%.1f".format(comparison.meanDifference)}" }}") + } + + private companion object { + /** How far one icon's alpha box may sit from the editor's, in pixels of the square (Erica: 4, a soft shadow at 16px). */ + const val BOX_DELTA_BOUND = 4 + + /** The mean premultiplied channel difference, out of 255, one icon may show against the editor's (Erica: 68.8, a thin sliver at 16px). */ + const val MEAN_DIFFERENCE_BOUND = 80.0 + + /** The average of those means over every icon (Erica: 16.5). */ + const val AVERAGE_MEAN_DIFFERENCE_BOUND = 24.0 + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3IconsTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3IconsTest.kt new file mode 100644 index 0000000..c7e353d --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3IconsTest.kt @@ -0,0 +1,52 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.fittedInto +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** + * The icon builders: a drawable's patch is its uv box on the art, and an icon is a CImageIcon over + * a square PNG entry holding the fit. + */ +class Cmo3IconsTest { + private fun gradient(width: Int, height: Int): RasterImage = RasterImage(width, height, ByteArray(width * height * 4) { index -> (index * 3 + 1).toByte() }) + + @Test + fun thePatchIsTheUvBoxClampedToTheArt() { + val art = gradient(8, 8) + // u in [0.25, 0.75), v in [0.5, 1.0) -> columns 2..5, rows 4..7. + val patch = Cmo3Icons.patchOf(art, floatArrayOf(0.25f, 0.5f, 0.75f, 0.5f, 0.75f, 1f, 0.25f, 1f)) + assertEquals(4 to 4, patch.width to patch.height) + for (row in 0 until 4) { + val expectedStart = ((4 + row) * 8 + 2) * 4 + assertContentEquals(art.rgba.copyOfRange(expectedStart, expectedStart + 16), patch.rgba.copyOfRange(row * 16, row * 16 + 16), "row $row") + } + assertSame(art, Cmo3Icons.patchOf(art, null), "no uvs show the whole art") + val sliver = Cmo3Icons.patchOf(art, floatArrayOf(0.3f, 0.3f, 0.3f, 0.3f)) + assertEquals(1 to 1, sliver.width to sliver.height, "a degenerate box is at least one pixel") + val outside = Cmo3Icons.patchOf(art, floatArrayOf(-1f, -1f, 2f, 2f)) + assertEquals(8 to 8, outside.width to outside.height, "a box past the art clamps to it") + } + + @Test + fun anIconIsASquarePngEntryHoldingTheFit() { + val art = gradient(6, 3) + val entries = ArrayList() + val icon = Cmo3Icons.iconOf(art, 16, "image_9.png", entries) + val image = icon.image as CWritableImage + assertEquals(16 to 16, image.width to image.height) + assertEquals("INT_ARGB", image.type) + assertEquals("image_9.png", Cmo3Icons.archivePathOf(icon)) + val entry = entries.single() + assertEquals("image_9.png", entry.path) + val decoded = PngCodec.read(entry.pngBytes) + assertEquals(16 to 16, decoded.width to decoded.height) + assertContentEquals(art.fittedInto(16).rgba, decoded.rgba, "the entry holds the fit") + assertContentEquals(entry.pngBytes, Cmo3Icons.iconPngOf(art, 16), "the in-place form encodes the same bytes") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImageChainBuilderTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImageChainBuilderTest.kt new file mode 100644 index 0000000..dd75caa --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImageChainBuilderTest.kt @@ -0,0 +1,472 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.interop.cmo3TargetVersionNo +import org.umamo.interop.diffPuppetModels +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Gates the fresh-graph image chain: atlas pages embed as by-name CAFF entries the read-back + * model resolves (the extractPuppetTextures contract - texture -> srcImageResource -> archive + * path), and a drawable bound through Cmo3DrawableTextureBinding round-trips with VERBATIM UVs + * (the atlas-region input keeps the importer on the packed, no-remap path). + */ +class Cmo3ImageChainBuilderTest { + private fun solidPage(size: Int, value: Byte): Cmo3Conversion.AtlasPage { + val rgba = ByteArray(size * size * 4) { value } + return Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(size, size, rgba)), size, size) + } + + @Test + fun pageChainEmbedsAndResolvesPagesByName() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Chain Test", 100, 100, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + val pages = listOf(solidPage(4, 0x40), solidPage(8, 0x7F)) + val chain = + Cmo3ImageChainBuilder.populate(skeleton.root, pages, listOf(emptyList(), emptyList()), nowMillis = 1_700_000_000_000L) + val bytes = + Cmo3FreshFile.assemble( + skeleton.root, + skeleton.iconEntries.map { icon -> Cmo3FreshFile.PngEntry(icon.path, icon.pngBytes) } + chain.pngEntries, + obfuscateKey = 0x1234ABCD, + ) + val model = Cmo3.read(bytes) + val resources = model.imageResources() + assertEquals(2, resources.size, "one CImageResource per page") + // No crop region on either page: no stand-in document, no crop group, nothing counted. + val textureManager = skeleton.root.textureManager as org.umamo.format.cmo3.model.gen.CTextureManager + assertTrue(Cmo3Import.elementsOf(textureManager._rawImages).isEmpty(), "no crop region, no stand-in document") + assertTrue(Cmo3Import.elementsOf(textureManager._modelImageGroups).isEmpty(), "and no crop group") + assertEquals(0, chain.cropDrawableCount) + // The reachability walk's order is unspecified; the by-name path attribute is the contract. + // Only the page buffers (imageFileBuf*) have a CImageResource; a chain's icon entries + // (image_N.png) never do, and this chain has none. + val resourcePaths = resources.map { resource -> resource.imageFileBuf?.archivePath }.toSet() + val pagePaths = chain.pngEntries.map { entry -> entry.path }.filter { path -> path.startsWith("imageFileBuf") }.toSet() + assertEquals(pagePaths, resourcePaths, "one resource per page path") + val entriesByPath = chain.pngEntries.associateBy { entry -> entry.path } + for ((pageIndex, page) in pages.withIndex()) { + val pagePath = if (pageIndex == 0) "imageFileBuf.png" else "imageFileBuf_${pageIndex - 1}.png" + assertContentEquals(page.pngBytes, entriesByPath.getValue(pagePath).pngBytes, "page $pageIndex entry bytes") + val resource = resources.single { candidate -> candidate.imageFileBuf?.archivePath == pagePath } + assertContentEquals(page.pngBytes, model.extractLayerPng(resource), "page $pageIndex bytes resolve by name") + } + } + + @Test + fun boundDrawableRoundTripsWithVerbatimUvs() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Bound Test", 100, 100, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + val uvs = floatArrayOf(0.1f, 0.2f, 0.9f, 0.2f, 0.5f, 0.8f) + val positions = floatArrayOf(10f, 10f, 90f, 10f, 50f, 90f) + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(solidPage(4, 0x11)), + listOf(listOf(Cmo3ImageChainBuilder.DrawableRegion("BoundDrawable", uvs, positions, intArrayOf(0, 1, 2)))), + nowMillis = 1_700_000_000_000L, + ) + val model = + Cmo3.read( + Cmo3FreshFile.assemble( + skeleton.root, + skeleton.iconEntries.map { icon -> Cmo3FreshFile.PngEntry(icon.path, icon.pngBytes) } + chain.pngEntries, + obfuscateKey = 0x1234ABCD, + ), + ) + val drawableId = DrawableId("BoundDrawable") + val puppet = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "Bound Drawable", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = + DrawableMesh( + positions = positions, + uvs = uvs, + indices = intArrayOf(0, 1, 2), + ), + geometryGrid = null, + ), + ), + rootChildren = listOf(OrgChild.Drawable(drawableId)), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = -50f, + runtimeTarget = RuntimeTarget.Cubism53, + ) + val report = Cmo3Export.apply(puppet, model, mapOf(drawableId.raw to chain.bindingByDrawableId.getValue(drawableId.raw))) + assertTrue(report.isEmpty, "expected no notices, got ${report.notices}") + + val reimportedSource = Cmo3.read(Cmo3.write(model)).root as? CModelSource ?: error("re-read root is not a CModelSource") + val reimported = Cmo3Import.fromModelSource(reimportedSource) + val residual = diffPuppetModels(reimported, puppet) + assertTrue(residual.isEmpty, "bound drawable lost through export/import: $residual") + assertContentEquals(uvs, reimported.drawables.single().mesh?.uvs, "UVs are verbatim (atlas frame)") + + // The texture web the renderer's extraction walks: drawable -> GTexture2D -> page resource. + val drawableSource = + (Cmo3Import.elementsOf((reimportedSource.drawableSourceSet as CDrawableSourceSet)._sources)) + .filterIsInstance() + .single() + val texture = drawableSource.texture as? GTexture2D ?: error("bound drawable has no GTexture2D") + assertTrue(texture.srcImageResource != null, "texture reaches the page resource") + } + + @Test + fun cropClearsPagePixelsTheMeshDoesNotCover() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Mask Test", 32, 32, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + // A fully opaque page: every pixel the crop keeps or clears is distinguishable from padding. + val pageSize = 32 + val pageRgba = ByteArray(pageSize * pageSize * 4) { 0x7F } + val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, pageRgba)), pageSize, pageSize) + // A right triangle over page (4,4)-(28,4)-(4,28): its uv bounding box is the full 24-square + // patch, so half of that rect is page pixels the mesh never samples. + val uvs = floatArrayOf(4f / 32f, 4f / 32f, 28f / 32f, 4f / 32f, 4f / 32f, 28f / 32f) + val positions = FloatArray(uvs.size) { index -> uvs[index] * pageSize } + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(page), + listOf(listOf(Cmo3ImageChainBuilder.DrawableRegion("MaskDrawable", uvs, positions, intArrayOf(0, 1, 2)))), + nowMillis = 1_700_000_000_000L, + ) + val crop = PngCodec.read(chain.pngEntries.single { entry -> entry.path == "imageFileBuf_0.png" }.pngBytes) + // The page is fully opaque and the triangle's legs run along the rect's edges, so the + // opaque-bbox trim is a no-op here and the rect stays the uv bounding box. + assertEquals(24, crop.width, "crop width is still the uv bounding box") + assertEquals(24, crop.height, "crop height is still the uv bounding box") + // Well inside the triangle. + assertEquals(0x7F.toByte(), crop.rgba[(2 * 24 + 2) * 4 + 3], "a covered pixel keeps the page's alpha") + // Well past the hypotenuse (x + y = 24 in crop-local pixels), far outside the bleed margin. + for (channel in 0 until 4) { + assertEquals(0, crop.rgba[(22 * 24 + 22) * 4 + channel], "an uncovered pixel is cleared, channel $channel") + } + } + + @Test + fun cropTrimsToOpaquePixelBounds() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Trim Test", 32, 32, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + // A transparent page with one opaque block at x 10..14, y 12..18: the mesh's uv bbox is + // much larger, so the trim must shrink the crop to the block - what an official layer + // rect records (the art's bounds, not the mesh's reach). + val pageSize = 32 + val pageRgba = ByteArray(pageSize * pageSize * 4) + for (rowIndex in 12 until 19) { + for (columnIndex in 10 until 15) { + pageRgba.fill(0xFF.toByte(), (rowIndex * pageSize + columnIndex) * 4, (rowIndex * pageSize + columnIndex) * 4 + 4) + } + } + val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, pageRgba)), pageSize, pageSize) + // A quad over uv bbox [4, 28] squared, positions = page pixels (identity fit). + val uvs = floatArrayOf(4f / 32f, 4f / 32f, 28f / 32f, 4f / 32f, 4f / 32f, 28f / 32f, 28f / 32f, 28f / 32f) + val positions = FloatArray(uvs.size) { index -> uvs[index] * pageSize } + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(page), + listOf(listOf(Cmo3ImageChainBuilder.DrawableRegion("TrimDrawable", uvs, positions, intArrayOf(0, 1, 2, 1, 2, 3)))), + nowMillis = 1_700_000_000_000L, + ) + val crop = PngCodec.read(chain.pngEntries.single { entry -> entry.path == "imageFileBuf_0.png" }.pngBytes) + assertEquals(5, crop.width, "crop width is the opaque block's width") + assertEquals(7, crop.height, "crop height is the opaque block's height") + val textureManager = skeleton.root.textureManager as org.umamo.format.cmo3.model.gen.CTextureManager + val atlas = + Cmo3Import.elementsOf(textureManager._textureAtlases) + .filterIsInstance() + .single() + val entry = + Cmo3Import.elementsOf(atlas.modelImages) + .filterIsInstance() + .single() + val packing = entry.materialLocalToAtlasTransform as org.umamo.format.cmo3.model.gen.GTransform2 + val packingPosition = packing.position as org.umamo.format.cmo3.model.type.GVector2 + assertEquals(10f, packingPosition.x, 1e-6f, "packing origin x is the block's page origin") + assertEquals(12f, packingPosition.y, 1e-6f, "packing origin y is the block's page origin") + val layeredImage = + Cmo3Import.elementsOf(textureManager._rawImages) + .filterIsInstance() + .single() + .image as org.umamo.format.cmo3.model.gen.CLayeredImage + val patchLayer = + Cmo3Import.elementsOf((layeredImage._rootLayer as org.umamo.format.cmo3.model.gen.CLayerGroup)._children) + .filterIsInstance() + .single() + val bounds = patchLayer.boundsOnImageDoc as org.umamo.format.cmo3.model.type.CRect + assertEquals(10, bounds.x, "bounds origin x is the block's canvas position (identity fit)") + assertEquals(12, bounds.y, "bounds origin y is the block's canvas position (identity fit)") + assertEquals(5, bounds.width, "bounds width is the trimmed crop's width") + assertEquals(7, bounds.height, "bounds height is the trimmed crop's height") + // The cache transform records the raw dims over the 64-aligned cache raster (5/64, 7/64); + // identity here stretches the art by the padding fraction in the editor's source-image mode. + val modelImage = + Cmo3Import.elementsOf( + Cmo3Import.elementsOf(textureManager._modelImageGroups) + .filterIsInstance() + .single() + ._modelImages, + ).filterIsInstance().single() + val cachedImage = + Cmo3Import.elementsOf((modelImage.cachedImageManager as org.umamo.format.cmo3.model.gen.CCachedImageManager).cachedImages) + .filterIsInstance() + .single() + val cacheTransform = cachedImage.transformRawImageToCachedImage as org.umamo.format.cmo3.model.type.CAffine + assertEquals(5f / 64f, cacheTransform.m00, "cache transform x is raw width over the 64-padded raster") + assertEquals(7f / 64f, cacheTransform.m11, "cache transform y is raw height over the 64-padded raster") + } + + @Test + fun sameSlotSameMeshSharesOneMaterial() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Twin Test", 100, 100, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + // Two drawables sampling the SAME atlas slot with the SAME mesh share one CModelImage at + // the builder level (duplicating a material over one slot makes the editor's atlas + // recomposite stack the shared art's alpha). Different-placement twins only reach the + // builder like this when the caller skips Cmo3AtlasUndedup - the conversion routes them + // to their own slots first, because the shared image carries a single canvas placement + // and the second twin would go missing in source-image mode. + val pageSize = 32 + val pageRgba = ByteArray(pageSize * pageSize * 4) + for (rowIndex in 12 until 19) { + for (columnIndex in 10 until 15) { + pageRgba.fill(0xFF.toByte(), (rowIndex * pageSize + columnIndex) * 4, (rowIndex * pageSize + columnIndex) * 4 + 4) + } + } + val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, pageRgba)), pageSize, pageSize) + val uvs = floatArrayOf(4f / 32f, 4f / 32f, 28f / 32f, 4f / 32f, 4f / 32f, 28f / 32f, 28f / 32f, 28f / 32f) + val indices = intArrayOf(0, 1, 2, 1, 2, 3) + val straightPositions = FloatArray(uvs.size) { index -> uvs[index] * pageSize } + val mirroredPositions = + FloatArray(uvs.size) { index -> + if (index % 2 == 0) { + -(uvs[index] * pageSize) + 100f + } else { + uvs[index] * pageSize + } + } + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(page), + listOf( + listOf( + Cmo3ImageChainBuilder.DrawableRegion("TwinA", uvs, straightPositions, indices), + Cmo3ImageChainBuilder.DrawableRegion("TwinB", uvs, mirroredPositions, indices), + ), + ), + nowMillis = 1_700_000_000_000L, + ) + val bindingA = chain.bindingByDrawableId.getValue("TwinA") + val bindingB = chain.bindingByDrawableId.getValue("TwinB") + assertEquals(bindingA.modelImageGuid, bindingB.modelImageGuid, "twins share one model image") + assertEquals(1f, bindingA.inputImageLocalToCanvasTransform.m00, 1e-4f, "twin A keeps its own fit") + assertEquals(-1f, bindingB.inputImageLocalToCanvasTransform.m00, 1e-4f, "twin B keeps its mirrored fit") + val textureManager = skeleton.root.textureManager as org.umamo.format.cmo3.model.gen.CTextureManager + val modelImages = + Cmo3Import.elementsOf( + Cmo3Import.elementsOf(textureManager._modelImageGroups) + .filterIsInstance() + .single() + ._modelImages, + ).filterIsInstance() + assertEquals(1, modelImages.size, "one shared material, not one per twin") + val entries = + Cmo3Import.elementsOf( + Cmo3Import.elementsOf(textureManager._textureAtlases) + .filterIsInstance() + .single() + .modelImages, + ).filterIsInstance() + assertEquals(1, entries.size, "one atlas entry for the shared material") + // The shared image keeps the FIRST drawable's placement (identity fit -> the block origin). + val placement = modelImages.single()._materialLocalToCanvasTransform as org.umamo.format.cmo3.model.type.CAffine + assertEquals(10f, placement.m02, "shared placement is twin A's") + assertEquals(12f, placement.m12, "shared placement is twin A's") + } + + @Test + fun placementSnapsToIntegerCanvasOrigin() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Snap Test", 32, 32, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + // The trim fixture's opaque block, but positions carry a FRACTIONAL translation + // (+0.4, -0.3): the layer placement must snap to whole canvas pixels (every official + // _materialLocalToCanvasTransform translation is integral), bounds must equal the + // snapped transform without a second rounding, and the declared packing origin must + // carry the complementary fraction so the web still composes exactly. + val pageSize = 32 + val pageRgba = ByteArray(pageSize * pageSize * 4) + for (rowIndex in 12 until 19) { + for (columnIndex in 10 until 15) { + pageRgba.fill(0xFF.toByte(), (rowIndex * pageSize + columnIndex) * 4, (rowIndex * pageSize + columnIndex) * 4 + 4) + } + } + val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, pageRgba)), pageSize, pageSize) + val uvs = floatArrayOf(4f / 32f, 4f / 32f, 28f / 32f, 4f / 32f, 4f / 32f, 28f / 32f, 28f / 32f, 28f / 32f) + val positions = + FloatArray(uvs.size) { index -> + if (index % 2 == 0) { + uvs[index] * pageSize + 0.4f + } else { + uvs[index] * pageSize - 0.3f + } + } + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(page), + listOf(listOf(Cmo3ImageChainBuilder.DrawableRegion("SnapDrawable", uvs, positions, intArrayOf(0, 1, 2, 1, 2, 3)))), + nowMillis = 1_700_000_000_000L, + ) + val textureManager = skeleton.root.textureManager as org.umamo.format.cmo3.model.gen.CTextureManager + val modelImage = + Cmo3Import.elementsOf( + Cmo3Import.elementsOf(textureManager._modelImageGroups) + .filterIsInstance() + .single() + ._modelImages, + ).filterIsInstance().single() + val placement = modelImage._materialLocalToCanvasTransform as org.umamo.format.cmo3.model.type.CAffine + assertEquals(10f, placement.m02, "placement x snaps to the whole canvas pixel (10.4 -> 10)") + assertEquals(12f, placement.m12, "placement y snaps to the whole canvas pixel (11.7 -> 12)") + val atlas = + Cmo3Import.elementsOf(textureManager._textureAtlases) + .filterIsInstance() + .single() + val entry = + Cmo3Import.elementsOf(atlas.modelImages) + .filterIsInstance() + .single() + val packing = entry.materialLocalToAtlasTransform as org.umamo.format.cmo3.model.gen.GTransform2 + val packingPosition = packing.position as org.umamo.format.cmo3.model.type.GVector2 + assertEquals(9.6f, packingPosition.x, 1e-4f, "packing origin carries the complementary x fraction") + assertEquals(12.3f, packingPosition.y, 1e-4f, "packing origin carries the complementary y fraction") + val layeredImage = + Cmo3Import.elementsOf(textureManager._rawImages) + .filterIsInstance() + .single() + .image as org.umamo.format.cmo3.model.gen.CLayeredImage + val patchLayer = + Cmo3Import.elementsOf((layeredImage._rootLayer as org.umamo.format.cmo3.model.gen.CLayerGroup)._children) + .filterIsInstance() + .single() + val bounds = patchLayer.boundsOnImageDoc as org.umamo.format.cmo3.model.type.CRect + assertEquals(10, bounds.x, "bounds origin x equals the snapped placement") + assertEquals(12, bounds.y, "bounds origin y equals the snapped placement") + } + + @Test + fun patchWebCarriesPlacementAndCropBytes() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Patch Test", 100, 100, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + // A gradient page so the crop subregion is verifiable byte-for-byte. + val pageSize = 8 + val pageRgba = ByteArray(pageSize * pageSize * 4) { index -> index.toByte() } + val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, pageRgba)), pageSize, pageSize) + // uv bbox [0.25, 0.5] x [0.5, 1.0] -> patch x 2..4, y 4..8; positions via the exact affine + // canvas = (2*pageX + 3, -1*pageY + 10) so the fit recovers it. + val uvs = floatArrayOf(0.25f, 0.5f, 0.5f, 0.5f, 0.25f, 1.0f, 0.5f, 1.0f) + val positions = + FloatArray(uvs.size) { index -> + val vertexIndex = index / 2 + if (index % 2 == 0) { + 2f * (uvs[2 * vertexIndex] * pageSize) + 3f + } else { + -1f * (uvs[2 * vertexIndex + 1] * pageSize) + 10f + } + } + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(page), + listOf(listOf(Cmo3ImageChainBuilder.DrawableRegion("PatchDrawable", uvs, positions, intArrayOf(0, 1, 2, 1, 2, 3)))), + nowMillis = 1_700_000_000_000L, + ) + val binding = chain.bindingByDrawableId.getValue("PatchDrawable") + assertTrue(binding.modelImageGuid != null, "drawable gets its own model image") + assertEquals(2f, binding.inputImageLocalToCanvasTransform.m00, 1e-4f, "fitted x scale") + assertEquals(-1f, binding.inputImageLocalToCanvasTransform.m11, 1e-4f, "fitted y scale (flip)") + assertEquals(3f, binding.inputImageLocalToCanvasTransform.m02, 1e-3f, "fitted x offset") + assertEquals(10f, binding.inputImageLocalToCanvasTransform.m12, 1e-3f, "fitted y offset") + + // The atlas entry carries the patch origin and the same fitted placement. + val textureManager = skeleton.root.textureManager as org.umamo.format.cmo3.model.gen.CTextureManager + val atlas = + Cmo3Import.elementsOf(textureManager._textureAtlases) + .filterIsInstance() + .single() + val entry = + Cmo3Import.elementsOf(atlas.modelImages) + .filterIsInstance() + .single() + assertEquals(binding.modelImageGuid, entry.modelImageGuid, "entry joins the drawable's model image") + val packing = entry.materialLocalToAtlasTransform as org.umamo.format.cmo3.model.gen.GTransform2 + val packingPosition = packing.position as org.umamo.format.cmo3.model.type.GVector2 + assertEquals(2f, packingPosition.x, 1e-6f, "patch origin x on the page") + assertEquals(4f, packingPosition.y, 1e-6f, "patch origin y on the page") + val entryPlacement = entry.atlasLocalToCanvasTransform as org.umamo.format.cmo3.model.type.CAffine + assertEquals(2f, entryPlacement.m00, 1e-4f, "entry placement matches the fit") + assertEquals(10f, entryPlacement.m12, 1e-3f, "entry placement matches the fit") + + // The synthetic source doc is the PAGE's frame (official docs carry the source image's own + // size, not the canvas), and the layer's boundsOnImageDoc carries the patch's canvas + // placement as its origin with the crop dims as its size - every corpus layer's rect + // equals its model image's _materialLocalToCanvasTransform translation plus its + // imageResource dims. + val layeredImage = + Cmo3Import.elementsOf(textureManager._rawImages) + .filterIsInstance() + .single() + .image as org.umamo.format.cmo3.model.gen.CLayeredImage + assertEquals(pageSize, layeredImage.width, "doc width is the page") + assertEquals(pageSize, layeredImage.height, "doc height is the page") + val patchLayer = + Cmo3Import.elementsOf((layeredImage._rootLayer as org.umamo.format.cmo3.model.gen.CLayerGroup)._children) + .filterIsInstance() + .single() + val bounds = patchLayer.boundsOnImageDoc as org.umamo.format.cmo3.model.type.CRect + assertEquals(7, bounds.x, "bounds origin x is the fitted patch-origin placement (2*2 + 3)") + assertEquals(6, bounds.y, "bounds origin y is the fitted patch-origin placement (-1*4 + 10)") + assertEquals(2, bounds.width, "bounds width is the crop width") + assertEquals(4, bounds.height, "bounds height is the crop height") + + // The crop PNG is the page subregion (x 2..4, y 4..8). + val cropEntry = chain.pngEntries.single { pngEntry -> pngEntry.path == "imageFileBuf_0.png" } + val crop = PngCodec.read(cropEntry.pngBytes) + assertEquals(2, crop.width, "crop width") + assertEquals(4, crop.height, "crop height") + for (rowIndex in 0 until crop.height) { + for (columnIndex in 0 until crop.width) { + val cropOffset = (rowIndex * crop.width + columnIndex) * 4 + val pageOffset = ((4 + rowIndex) * pageSize + (2 + columnIndex)) * 4 + for (channel in 0 until 4) { + assertEquals( + pageRgba[pageOffset + channel], + crop.rgba[cropOffset + channel], + "crop pixel ($columnIndex, $rowIndex) channel $channel", + ) + } + } + } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImageResourceUvTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImageResourceUvTest.kt new file mode 100644 index 0000000..8a596a5 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImageResourceUvTest.kt @@ -0,0 +1,220 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.atlasPixelOf +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertTrue + +/** + * Locks in the UV frame convention CMO3 ingest must honor (see docs/format/CMO3.md §4): + * + * - An UNPACKED drawable (no CTextureInput_TextureAtlasRegion) stores its UVs in the editor's cache frame, + * scaled by GTexture2D.transformImageResource01toLogical01; ingest inverts that affine so the UVs span + * its model image's raster. Skipping it clips the outer margin and enlarges the art. + * - A PACKED drawable over an atlas page or its model image's raster stores that image's own frame, and + * ingest leaves its UVs VERBATIM. + * - A drawable over the editor's reduced cache copy of its model image stores the copy's frame, which is + * the cache frame: ingest inverts the affine, and the drawable is shown from what its new coordinates + * address. The two go together - inverting the UVs while still sampling the copy shrinks the art. + * - A placed tile's drawable, whatever its texture names, is read onto its atlas page (a model saved in + * source-layer display still carries the page) and shown from that page. + * + * Corpus-gated by name; self-skips when a sample is absent. + */ +class Cmo3ImageResourceUvTest { + private fun corpusFile(fileName: String): File? { + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return corpus.walkTopDown().firstOrNull { it.isFile && it.name == fileName } + } + directory = directory.parentFile + } + return null + } + + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun artMeshes(root: CModelSource): List = + elements((root.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + + private fun hasAtlasRegion(source: CArtMeshSource): Boolean { + val extension = elements(source._extensions).filterIsInstance().firstOrNull() ?: return false + return elements(extension._textureInputs).any { it is CTextureInput_TextureAtlasRegion } + } + + private fun maxUvComponent(uvs: FloatArray): Float = uvs.maxOrNull() ?: Float.NaN + + @Test + fun unpackedPerLayerUvsSpanFullImageAfterInverseTransform() { + val file = + corpusFile("MultiplyScreenColors.cmo3") ?: run { + println("MultiplyScreenColors.cmo3 not present; skipping unpacked-UV test") + return + } + val root = Cmo3.read(file).root as? CModelSource ?: error("root is not a CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + + // Inset_Pink_Square is unpacked (no atlas); its logical UVs top out at ~0.965 (the affine scale) and + // must reach the image edge (~1.0) after inversion so the whole PNG - white border included - maps on. + val insetPink = puppet.drawables.first { it.id == DrawableId("Inset_Pink_Square") } + val insetUvMax = maxUvComponent(insetPink.mesh!!.uvs) + assertTrue(insetUvMax > 0.99f, "unpacked UVs must reach the image edge; got max $insetUvMax") + assertTrue(insetUvMax < 1.05f, "unpacked UVs must not wildly overshoot; got max $insetUvMax") + } + + /** + * Each reduced cache copy in the graph, to the model image it was reduced from - read straight off the + * file, so the test's classification owes nothing to the import. + * + * @param CModelSource root The CMO3's model source. + * @return Map The copies and their owners. + */ + private fun reducedCopyOwners(root: CModelSource): Map { + val textureManager = root.textureManager as? CTextureManager ?: return emptyMap() + val owners = HashMap() + for (group in elements(textureManager._modelImageGroups).filterIsInstance()) { + for (modelImage in elements(group._modelImages).filterIsInstance()) { + val manager = modelImage.cachedImageManager as? CCachedImageManager ?: continue + for (cached in elements(manager.cachedImages).filterIsInstance()) { + val resource = cached._cachedImageResource as? CImageResource ?: continue + if (resource !== modelImage._filteredImage) { + owners[resource] = modelImage + } + } + } + } + return owners + } + + /** + * A model saved in source-layer display is read onto its own atlas page: every placed drawable's UVs + * leave the frame its texture names - its raster's, or the cache frame through the affine's inverse when + * it samples a reduced copy - and go through its tile's placement onto the page, and the drawable is + * shown from that page, never the copy or the raster. The expected coordinates are computed here from + * the file's own fields, independently of the import. + */ + @Test + fun aSourceModeSaveIsReadOntoItsOwnAtlasPage() { + val file = + corpusFile("modelA.cmo3") ?: run { + println("modelA.cmo3 not present; skipping the source-mode page test") + return + } + val cmo3 = Cmo3.read(file) + val root = cmo3.root as? CModelSource ?: error("root is not a CModelSource") + val imported = Cmo3Import.importModelSource(root) + val puppet = imported.puppet + val renderPages = cmo3AtlasPages(root, cmo3::extractLayerPng) + val copyOwners = reducedCopyOwners(root) + val pagePngs = + elements((root.textureManager as CTextureManager)._textureAtlases).filterIsInstance() + .map { atlas -> (atlas.cachedAtlasImage as? CImageResource)?.let(cmo3::extractLayerPng) } + + val sourcesById = artMeshes(root).associateBy { (it.id as? Id)?.idstr } + var rasterChecked = 0 + var reducedCopyChecked = 0 + for (drawable in puppet.drawables) { + val source = sourcesById[drawable.id.raw] ?: continue + val tile = drawable.atlasTileId?.let { tileId -> puppet.atlas.tileById[tileId] } ?: continue + val placement = tile.placement ?: continue + val page = puppet.atlas.pages[placement.pageIndex] + val sourceUvs = source.uvs as? FloatArray ?: continue + val sampled = (source.texture as? GTexture2D)?.srcImageResource as? CImageResource ?: continue + val overCopy = sampled in copyOwners + val affine = (source.texture as GTexture2D).transformImageResource01toLogical01 as CAffine + val determinant = affine.m00 * affine.m11 - affine.m01 * affine.m10 + val modelUvs = drawable.mesh!!.uvs + var componentIndex = 0 + while (componentIndex + 1 < sourceUvs.size) { + // Into the raster frame: verbatim over the raster, through the cache affine's inverse over a copy. + val artU: Float + val artV: Float + if (overCopy) { + val cacheU = sourceUvs[componentIndex] - affine.m02 + val cacheV = sourceUvs[componentIndex + 1] - affine.m12 + artU = (affine.m11 * cacheU - affine.m01 * cacheV) / determinant + artV = (-affine.m10 * cacheU + affine.m00 * cacheV) / determinant + } else { + artU = sourceUvs[componentIndex] + artV = sourceUvs[componentIndex + 1] + } + // Onto the page: the placement takes art pixels to page pixels. + val pagePixel = atlasPixelOf(placement, artU * tile.width, artV * tile.height) + val expectedU = pagePixel[0] / page.width + val expectedV = pagePixel[1] / page.height + assertTrue( + abs(modelUvs[componentIndex] - expectedU) < 1e-5f && abs(modelUvs[componentIndex + 1] - expectedV) < 1e-5f, + "drawable ${drawable.id.raw} UV ${componentIndex / 2} is (${modelUvs[componentIndex]}, ${modelUvs[componentIndex + 1]}), not the page's ($expectedU, $expectedV)", + ) + componentIndex += 2 + } + val pageIndex = renderPages.atlasIndexByDrawableId[drawable.id.raw] + val pagePng = pagePngs.getOrNull(placement.pageIndex) + assertTrue( + pageIndex != null && pagePng != null && renderPages.pageBytes[pageIndex].contentEquals(pagePng), + "drawable ${drawable.id.raw} must be shown from its tile's atlas page", + ) + if (overCopy) { + reducedCopyChecked++ + } else { + rasterChecked++ + } + } + assertTrue(puppet.atlas.storedUvsAddressPages, "a source-mode save's coordinates address its pages") + assertTrue(rasterChecked > 0, "expected placed drawables over their raster; found none") + assertTrue(reducedCopyChecked > 0, "expected placed drawables over a reduced copy (the regression surface); found none") + } + + /** + * A model saved in atlas display keeps its drawables' page coordinates byte for byte. + */ + @Test + fun pageSamplingUvsAreLeftVerbatim() { + val file = + corpusFile("EricaTamamo.cmo3") ?: run { + println("EricaTamamo.cmo3 not present; skipping the verbatim page test") + return + } + val root = Cmo3.read(file).root as? CModelSource ?: error("root is not a CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + val sourcesById = artMeshes(root).associateBy { (it.id as? Id)?.idstr } + var checked = 0 + for (drawable in puppet.drawables) { + val source = sourcesById[drawable.id.raw] ?: continue + if (!hasAtlasRegion(source)) { + continue + } + val sourceUvs = source.uvs as? FloatArray ?: continue + assertContentEquals(sourceUvs, drawable.mesh!!.uvs, "page-sampling drawable ${drawable.id.raw} UVs must be verbatim") + checked++ + } + assertTrue(checked > 0, "expected page-sampling drawables; found none") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImportTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImportTest.kt new file mode 100644 index 0000000..5dc01b4 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3ImportTest.kt @@ -0,0 +1,597 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDeformerSourceSet +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CParameterSource +import org.umamo.format.cmo3.model.gen.CParameterSourceSet +import org.umamo.format.cmo3.model.gen.CRotationDeformerSource +import org.umamo.format.cmo3.model.gen.CWarpDeformerForm +import org.umamo.format.cmo3.model.gen.CWarpDeformerSource +import org.umamo.format.cmo3.model.gen.KeyFormMorphTarget +import org.umamo.format.cmo3.model.gen.KeyFormMorphTargetSet +import org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraint +import org.umamo.format.cmo3.model.gen.MorphTargetBlendWeightConstraintSet +import org.umamo.format.cmo3.model.gen.Type +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.partByDrawable +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Reads a real `.cmo3` corpus sample, maps it to a `PuppetModel`, and checks the structural tree. + * + * Self-contained (no editor jar); skips when the sample is absent. Pass + * `-Dcmo3.sample=/path/to/Model.cmo3`. The printed summary matches the official editor's Parts/Parameters + * panels; the assertions verify referential integrity (every GUID cross-reference resolves to a real entity). + */ +class Cmo3ImportTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun mapsCorpusModelToStructuralTree() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping import test") + return + } + val root = Cmo3.read(file).root as? CModelSource ?: error("root is not a CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + + val warpCount = puppet.deformers.count { it is Deformer.Warp } + val rotationCount = puppet.deformers.count { it is Deformer.Rotation } + println( + "[Umamo][import] parameters=${puppet.parameters.size} parts=${puppet.parts.size} " + + "deformers=${puppet.deformers.size} (warp=$warpCount rotation=$rotationCount) " + + "drawables=${puppet.drawables.size} rootPart=${puppet.rootPartId?.raw}", + ) + println("[Umamo][import] first params: " + puppet.parameters.take(10).joinToString { it.id.raw }) + + val totalVertices = puppet.drawables.sumOf { it.mesh?.vertexCount ?: 0 } + val totalPolygons = puppet.drawables.sumOf { it.mesh?.triangleCount ?: 0 } + println("[Umamo][import] vertices=$totalVertices polygons=$totalPolygons") + + val artInterpolations = puppet.drawables.sumOf { it.geometryGrid?.cells?.size ?: 0 } + val deformerInterpolations = + puppet.deformers.sumOf { deformer -> + when (deformer) { + is Deformer.Warp -> deformer.geometryGrid?.cells?.size ?: 0 + is Deformer.Rotation -> deformer.geometryGrid?.cells?.size ?: 0 + } + } + println( + "[Umamo][import] artInterpolations=$artInterpolations " + + "deformerInterpolations=$deformerInterpolations", + ) + + // Golden gate: for the EricaTamamo corpus, assert the exact figures from + // test/corpus/EricaTamamo.stats. Other samples get only the sample-agnostic integrity checks + // below. (Parameter count is observed - the stats file does not list it.) + if (file.name.startsWith("EricaTamamo")) { + assertEquals(116, puppet.parameters.size, "parameters") + // CMO3 combined-parameter pairs: head Angle X/Y and Eyeball X/Y are the model's only links. + assertEquals( + listOf( + ParameterLink(ParameterId("ParamAngleX"), ParameterId("ParamAngleY")), + ParameterLink(ParameterId("ParamEyeBallX"), ParameterId("ParamEyeBallY")), + ), + puppet.parameterLinks, + "parameter links", + ) + + // CMO3 parameter-panel folders: the rootParameterGroup has 71 panel-order children - 67 loose + // parameters interleaved with 4 subgroups (two share the display name "Eye", so identity is by id). + fun walkGroups(nodes: List): List = + nodes.filterIsInstance().flatMap { group -> listOf(group) + walkGroups(group.children) } + + fun walkLeaves(nodes: List): List = + nodes.flatMap { node -> + when (node) { + is ParameterNode.Param -> listOf(node.id) + is ParameterNode.Group -> walkLeaves(node.children) + } + } + + assertEquals(71, puppet.parameterTree.size, "parameter tree top-level nodes") + val parameterGroups = walkGroups(puppet.parameterTree) + assertEquals( + listOf("ParamGroup", "ParamGroup2", "ParamGroup3", "ParamGroup4"), + parameterGroups.map { it.id.raw }, + "parameter group ids", + ) + assertEquals( + listOf("Eye", "Eye", "Folder 1", "Tail Rotation"), + parameterGroups.map { it.name }, + "parameter group names", + ) + assertEquals( + listOf(3, 3, 40, 3), + parameterGroups.map { it.children.size }, + "parameter group child counts", + ) + val parameterTreeLeaves = walkLeaves(puppet.parameterTree) + assertEquals(116, parameterTreeLeaves.size, "parameter tree leaves") + assertEquals( + puppet.parameters.map { it.id }.toSet(), + parameterTreeLeaves.toSet(), + "every panel leaf is a real parameter", + ) + assertEquals(42, puppet.parts.size, "parts") + assertEquals(350, warpCount, "warp deformers") + assertEquals(6, rotationCount, "rotation deformers") + assertEquals(177, puppet.drawables.size, "art meshes") + assertEquals(31470, totalVertices, "vertices") + assertEquals(50933, totalPolygons, "polygons") + assertEquals(337, artInterpolations, "art mesh interpolations") + assertEquals(1297, deformerInterpolations, "deformer interpolations") + } + + val partIds = puppet.parts.map { it.id }.toSet() + val deformerIds = puppet.deformers.map { it.id }.toSet() + val drawableIds = puppet.drawables.map { it.id }.toSet() + + assertTrue(puppet.parameters.isNotEmpty(), "expected parameters") + assertTrue(puppet.drawables.isNotEmpty(), "expected drawables") + + // Referential integrity: every org-tree child resolves to a real entity, and every drawable is + // placed somewhere in the tree (membership lives only in the tree now - the import's safety net + // guarantees no mesh is orphaned). + fun checkOrgChildren(children: List, owner: String) { + for (child in children) { + when (child) { + is OrgChild.Part -> assertTrue(child.id in partIds, "$owner -> unknown sub-part ${child.id.raw}") + is OrgChild.Drawable -> assertTrue(child.id in drawableIds, "$owner -> unknown mesh ${child.id.raw}") + } + } + } + checkOrgChildren(puppet.rootChildren, "root") + for (part in puppet.parts) { + checkOrgChildren(part.children, "part ${part.id.raw}") + } + val placedDrawables = puppet.partByDrawable().keys + for (drawable in puppet.drawables) { + assertTrue(drawable.id in placedDrawables, "drawable ${drawable.id.raw} is missing from the org tree") + drawable.parentDeformerId?.let { + assertTrue(it in deformerIds, "drawable ${drawable.id.raw} -> unknown deformer ${it.raw}") + } + for (mask in drawable.maskedBy) { + assertTrue(mask in drawableIds, "drawable ${drawable.id.raw} -> unknown mask ${mask.raw}") + } + } + for (deformer in puppet.deformers) { + deformer.parent?.let { + assertTrue(it in deformerIds, "deformer ${deformer.id.raw} -> unknown parent ${it.raw}") + } + deformer.partId?.let { + assertTrue(it in partIds, "deformer ${deformer.id.raw} -> unknown part ${it.raw}") + } + } + } + + /** + * Corpus-free check that drawable and deformer display names come from CMO3 localName, falling back to + * the id when localName is absent - the same rule the outliner relies on to label its rows readably. + */ + @Test + fun capturesLocalNameWithIdFallbackForDrawablesAndDeformers() { + fun makeId(value: String) = Id("").apply { idstr = value } + + val namedMesh = + CArtMeshSource().apply { + id = makeId("ArtMesh1") + localName = "Front Hair" + } + val unnamedMesh = CArtMeshSource().apply { id = makeId("ArtMesh9") } // localName null -> id + val namedWarp = + CWarpDeformerSource().apply { + id = makeId("Warp1") + localName = "Warp Deformer of Bag front12" + } + val unnamedWarp = CWarpDeformerSource().apply { id = makeId("Warp9") } // localName null -> id + + val model = + CModelSource().apply { + drawableSourceSet = CDrawableSourceSet().apply { _sources = arrayListOf(namedMesh, unnamedMesh) } + deformerSourceSet = CDeformerSourceSet().apply { _sources = arrayListOf(namedWarp, unnamedWarp) } + } + + val puppet = Cmo3Import.fromModelSource(model) + + assertEquals("Front Hair", puppet.drawables.first { it.id.raw == "ArtMesh1" }.name, "named drawable") + assertEquals("ArtMesh9", puppet.drawables.first { it.id.raw == "ArtMesh9" }.name, "unnamed drawable falls back to id") + assertEquals("Warp Deformer of Bag front12", puppet.deformers.first { it.id.raw == "Warp1" }.name, "named deformer") + assertEquals("Warp9", puppet.deformers.first { it.id.raw == "Warp9" }.name, "unnamed deformer falls back to id") + } + + /** + * Corpus-free check that the CMO3 editor lock maps inverted onto the runtime selectable flag: a locked + * source ingests as isSelectable = false and an unlocked one as isSelectable = true, for drawables and + * both deformer kinds alike (Cubism lock = not selectable). + */ + @Test + fun mapsCmo3LockInvertedOntoSelectable() { + fun makeId(value: String) = Id("").apply { idstr = value } + + val lockedMesh = + CArtMeshSource().apply { + id = makeId("ArtMesh1") + isLocked = true + } + val unlockedMesh = CArtMeshSource().apply { id = makeId("ArtMesh2") } + val lockedWarp = + CWarpDeformerSource().apply { + id = makeId("Warp1") + isLocked = true + } + val lockedRotation = + CRotationDeformerSource().apply { + id = makeId("Rotation1") + isLocked = true + } + val unlockedWarp = CWarpDeformerSource().apply { id = makeId("Warp2") } + + val model = + CModelSource().apply { + drawableSourceSet = CDrawableSourceSet().apply { _sources = arrayListOf(lockedMesh, unlockedMesh) } + deformerSourceSet = CDeformerSourceSet().apply { _sources = arrayListOf(lockedWarp, lockedRotation, unlockedWarp) } + } + + val puppet = Cmo3Import.fromModelSource(model) + + assertFalse(puppet.drawables.first { it.id.raw == "ArtMesh1" }.isSelectable, "locked drawable ingests unselectable") + assertTrue(puppet.drawables.first { it.id.raw == "ArtMesh2" }.isSelectable, "unlocked drawable ingests selectable") + assertFalse(puppet.deformers.first { it.id.raw == "Warp1" }.isSelectable, "locked warp ingests unselectable") + assertFalse(puppet.deformers.first { it.id.raw == "Rotation1" }.isSelectable, "locked rotation ingests unselectable") + assertTrue(puppet.deformers.first { it.id.raw == "Warp2" }.isSelectable, "unlocked warp ingests selectable") + } + + // ---- blend shapes (CMO3 MorphTargets) ---- + + /** All blend-shape bindings of [puppet], across drawables and both deformer kinds. */ + private fun allBindings(puppet: PuppetModel): List> = + puppet.drawables.flatMap { it.blendShapes } + + puppet.deformers.flatMap { deformer -> + when (deformer) { + is Deformer.Warp -> deformer.blendShapes + is Deformer.Rotation -> deformer.blendShapes + } + } + + /** + * Probe loop over the whole corpus (`cmo3.probe`, comma-separated; defaults to every corpus + * .cmo3): every model ingests with well-formed blend-shape bindings, and the two blend-shape + * corpus anchors (Model A, Model B) match their golden counts. Skips gracefully without the corpus. + */ + @Test + fun blendShapeBindingsAcrossCorpus() { + val files = + System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { it.isFile }.orEmpty() + if (files.isEmpty()) { + println("cmo3.probe not present; skipping blend-shape corpus probe") + return + } + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + val bindings = allBindings(puppet) + val blendShapeParams = puppet.parameters.filter { it.kind == ParameterKind.BLEND_SHAPE } + val meshBindings = puppet.drawables.sumOf { it.blendShapes.size } + val warpBindings = puppet.deformers.filterIsInstance().sumOf { it.blendShapes.size } + val rotationBindings = puppet.deformers.filterIsInstance().sumOf { it.blendShapes.size } + val limitCount = bindings.sumOf { it.limits.size } + val limitPointCount = bindings.sumOf { binding -> binding.limits.sumOf { it.points.size } } + val formCount = bindings.sumOf { binding -> binding.forms.count { it != null } } + println( + "${file.name}: blendShapeParams=${blendShapeParams.size} bindings=${bindings.size} " + + "(mesh=$meshBindings warp=$warpBindings rotation=$rotationBindings) forms=$formCount " + + "limits=$limitCount points=$limitPointCount", + ) + + val parameterById = puppet.parameters.associateBy { it.id } + for (binding in bindings) { + val parameter = parameterById[binding.parameterId] + assertTrue(parameter != null, "${file.name}: binding driver ${binding.parameterId.raw} resolves") + assertEquals( + ParameterKind.BLEND_SHAPE, + parameter.kind, + "${file.name}: binding driver ${binding.parameterId.raw} is a blend-shape parameter", + ) + assertTrue( + binding.keys.toList() == binding.keys.toList().distinct().sorted(), + "${file.name}: binding keys ascending and distinct", + ) + assertEquals(binding.keys.size, binding.forms.size, "${file.name}: one form slot per key") + // The neutral sits at parameter VALUE 0, not the default. + assertEquals( + 0f, + binding.keys[binding.neutralIndex], + "${file.name}: neutral key sits at parameter value 0", + ) + // The neutral form is null when inserted (always, in the corpus - a morph authored + // exactly at value 0 would occupy the slot but is never read by the evaluator). + for (formIndex in binding.forms.indices) { + if (formIndex != binding.neutralIndex) { + assertTrue(binding.forms[formIndex] != null, "${file.name}: non-neutral form present") + } + } + for (limit in binding.limits) { + assertTrue(parameterById.containsKey(limit.parameterId), "${file.name}: limit constraint parameter resolves") + assertTrue( + limit.points.map { it.value } == limit.points.map { it.value }.sorted(), + "${file.name}: limit points sorted by constraint value", + ) + } + } + + // Golden anchors: the corpus blend-shape models of record. + if (file.name.startsWith("modelA")) { + assertEquals(12, blendShapeParams.size, "Model A: blend-shape parameter count") + assertEquals(60, bindings.size, "Model A: binding count (one per source × driving parameter)") + assertEquals(118, formCount, "Model A: morph-target form count") + assertEquals(0, limitCount, "Model A: no populated blend-weight constraints") + } + if (file.name.startsWith("modelB")) { + assertEquals(5, blendShapeParams.size, "Model B: blend-shape parameter count") + assertEquals(45, bindings.size, "Model B: binding count") + assertEquals(45, formCount, "Model B: morph-target form count") + assertEquals(44, limitCount, "Model B: limit curve count") + assertEquals(88, limitPointCount, "Model B: one point per XML constraint record") + } + // Model C: the corpus constraint + edge-case model. 146 XML morph targets ingest as 145 + // forms: exactly one is owned by a CPartSource (part blend shapes, a moc v5 feature) and + // part morph targets are not ingested yet - deferred with the part/glue target kinds. + // Model C also authors one morph target AT the parameter default (an explicit neutral form). + if (file.name.startsWith("modelC")) { + assertEquals(33, blendShapeParams.size, "Model C: blend-shape parameter count") + assertEquals(123, bindings.size, "Model C: binding count (mesh+warp+rotation; 1 part-owned target excluded)") + assertEquals(145, formCount, "Model C: morph-target form count (146 XML records - 1 part-owned)") + assertEquals(468, limitPointCount, "Model C: one point per XML constraint record") + } + } + } + + /** + * Corpus-free check of the binding derivation rule: morph targets group per driving parameter, + * keys sort ascending, and the neutral key is inserted at parameter VALUE 0 with a null form - + * NOT at the parameter's default (the default here is deliberately 1.0, the Model C + * ParamMouthUp shape that discriminates the two readings against the MOC3 bake). + */ + @Test + fun ingestsMorphTargetSetIntoBlendShapeBindings() { + fun makeId(value: String) = Id("").apply { idstr = value } + + fun makeGuid(value: String) = Guid("").apply { uuid = value } + + val parameter = + CParameterSource().apply { + guid = makeGuid("param-a") + id = makeId("ParamShrink") + minValue = -1f + maxValue = 1f + defaultValue = 1f + paramType = Type.MORPH_TARGET + } + val formAtMinusOne = + CWarpDeformerForm().apply { + guid = makeGuid("form-minus") + positions = floatArrayOf(-1f, -2f) + } + val formAtPlusOne = + CWarpDeformerForm().apply { + guid = makeGuid("form-plus") + positions = floatArrayOf(1f, 2f) + } + val warp = + CWarpDeformerSource().apply { + guid = makeGuid("warp-a") + id = makeId("Warp1") + keyforms = arrayListOf(formAtMinusOne, formAtPlusOne) + keyformMorphTargetSet = + KeyFormMorphTargetSet().apply { + _morphTargets = + arrayListOf( + // Deliberately unsorted: the +1 key first. + KeyFormMorphTarget().apply { + parameterGuid = makeGuid("param-a") + keyValue = 1f + keyformGuid = makeGuid("form-plus") + }, + KeyFormMorphTarget().apply { + parameterGuid = makeGuid("param-a") + keyValue = -1f + keyformGuid = makeGuid("form-minus") + }, + ) + } + } + val model = + CModelSource().apply { + parameterSourceSet = CParameterSourceSet().apply { _sources = arrayListOf(parameter) } + deformerSourceSet = CDeformerSourceSet().apply { _sources = arrayListOf(warp) } + } + + val puppet = Cmo3Import.fromModelSource(model) + + assertEquals(ParameterKind.BLEND_SHAPE, puppet.parameters.single().kind, "MORPH_TARGET paramType maps to kind") + val binding = (puppet.deformers.single() as Deformer.Warp).blendShapes.single() + assertEquals(ParameterId("ParamShrink"), binding.parameterId, "binding driver") + assertEquals(listOf(-1f, 0f, 1f), binding.keys.toList(), "keys sorted with neutral inserted at value 0") + assertEquals(1, binding.neutralIndex, "neutral at parameter value 0, not the default (1.0)") + assertNull(binding.forms[1], "inserted neutral has no source form") + assertEquals(listOf(-1f, -2f), binding.forms[0]?.controlPoints?.toList(), "form at key -1") + assertEquals(listOf(1f, 2f), binding.forms[2]?.controlPoints?.toList(), "form at key +1") + } + + /** + * Corpus-free check that flat constraint records group into per-parameter limit curves sorted by + * the constraint parameter's value, attached to the driving parameter they cap. + */ + @Test + fun groupsBlendWeightConstraintsIntoLimitCurves() { + fun makeId(value: String) = Id("").apply { idstr = value } + + fun makeGuid(value: String) = Guid("").apply { uuid = value } + + val morphParameter = + CParameterSource().apply { + guid = makeGuid("param-a") + id = makeId("ParamShrink") + defaultValue = 0f + paramType = Type.MORPH_TARGET + } + val constraintParameter = + CParameterSource().apply { + guid = makeGuid("param-b") + id = makeId("ParamAngleX") + defaultValue = 0f + } + val form = + CWarpDeformerForm().apply { + guid = makeGuid("form-1") + positions = floatArrayOf(3f, 4f) + } + val warp = + CWarpDeformerSource().apply { + guid = makeGuid("warp-a") + id = makeId("Warp1") + keyforms = arrayListOf(form) + keyformMorphTargetSet = + KeyFormMorphTargetSet().apply { + _morphTargets = + arrayListOf( + KeyFormMorphTarget().apply { + parameterGuid = makeGuid("param-a") + keyValue = 1f + keyformGuid = makeGuid("form-1") + }, + ) + blendWeightConstraintSet = + MorphTargetBlendWeightConstraintSet().apply { + _constraints = + arrayListOf( + // Deliberately out of order by constraint value. + MorphTargetBlendWeightConstraint().apply { + morphTargetParameterGuid = makeGuid("param-a") + constraintParameterGuid = makeGuid("param-b") + constraintParameterValue = 30f + blendWeight = 0.2f + }, + MorphTargetBlendWeightConstraint().apply { + morphTargetParameterGuid = makeGuid("param-a") + constraintParameterGuid = makeGuid("param-b") + constraintParameterValue = -30f + blendWeight = 1f + }, + // A constraint for a DIFFERENT morph parameter: excluded from this binding. + MorphTargetBlendWeightConstraint().apply { + morphTargetParameterGuid = makeGuid("param-other") + constraintParameterGuid = makeGuid("param-b") + constraintParameterValue = 0f + blendWeight = 0.5f + }, + ) + } + } + } + val model = + CModelSource().apply { + parameterSourceSet = CParameterSourceSet().apply { _sources = arrayListOf(morphParameter, constraintParameter) } + deformerSourceSet = CDeformerSourceSet().apply { _sources = arrayListOf(warp) } + } + + val binding = (Cmo3Import.fromModelSource(model).deformers.single() as Deformer.Warp).blendShapes.single() + + val limit = binding.limits.single() + assertEquals(ParameterId("ParamAngleX"), limit.parameterId, "limit constraint parameter") + assertEquals(listOf(-30f, 30f), limit.points.map { it.value }, "points sorted by constraint value") + assertEquals(listOf(1f, 0.2f), limit.points.map { it.weight }, "weights follow their points") + } + + /** + * Corpus-free check that unresolvable morph targets degrade without crashing: an unknown driving + * parameter drops its binding, an unknown form guid drops that key, and a source without morph + * targets ingests with empty blend shapes. + */ + @Test + fun skipsUnresolvableMorphTargets() { + fun makeId(value: String) = Id("").apply { idstr = value } + + fun makeGuid(value: String) = Guid("").apply { uuid = value } + + val parameter = + CParameterSource().apply { + guid = makeGuid("param-a") + id = makeId("ParamShrink") + defaultValue = 0f + paramType = Type.MORPH_TARGET + } + val form = + CWarpDeformerForm().apply { + guid = makeGuid("form-1") + positions = floatArrayOf(3f, 4f) + } + val warp = + CWarpDeformerSource().apply { + guid = makeGuid("warp-a") + id = makeId("Warp1") + keyforms = arrayListOf(form) + keyformMorphTargetSet = + KeyFormMorphTargetSet().apply { + _morphTargets = + arrayListOf( + // Unknown parameter: the whole binding is skipped. + KeyFormMorphTarget().apply { + parameterGuid = makeGuid("param-unknown") + keyValue = 1f + keyformGuid = makeGuid("form-1") + }, + // Known parameter, unknown form: the key is dropped, the binding survives. + KeyFormMorphTarget().apply { + parameterGuid = makeGuid("param-a") + keyValue = -1f + keyformGuid = makeGuid("form-unknown") + }, + KeyFormMorphTarget().apply { + parameterGuid = makeGuid("param-a") + keyValue = 1f + keyformGuid = makeGuid("form-1") + }, + ) + } + } + val bareWarp = + CWarpDeformerSource().apply { + guid = makeGuid("warp-b") + id = makeId("Warp2") + } + val model = + CModelSource().apply { + parameterSourceSet = CParameterSourceSet().apply { _sources = arrayListOf(parameter) } + deformerSourceSet = CDeformerSourceSet().apply { _sources = arrayListOf(warp, bareWarp) } + } + + val puppet = Cmo3Import.fromModelSource(model) + + val binding = (puppet.deformers.first { it.id.raw == "Warp1" } as Deformer.Warp).blendShapes.single() + assertEquals(listOf(0f, 1f), binding.keys.toList(), "unresolvable form's key dropped; neutral + resolvable key remain") + assertTrue( + (puppet.deformers.first { it.id.raw == "Warp2" } as Deformer.Warp).blendShapes.isEmpty(), + "source without morph targets ingests empty", + ) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3LayerWebProbeTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3LayerWebProbeTest.kt new file mode 100644 index 0000000..ba616ac --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3LayerWebProbeTest.kt @@ -0,0 +1,359 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACTextureInput +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CLayerInputData +import org.umamo.format.cmo3.model.gen.CLayerSelectorMap +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.GVector2 +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Surveys the CMO3 layered-art web across the whole corpus, so the layer-view data model is pinned + * against counted reality rather than assumption (see docs/format/CMO3.md §4). Every quantitative + * claim §4 and §6 make came from probes that no longer live in the tree; this is the one that stays. + * + * What it answers, per corpus file: how many drawables join a model image at all, how many model + * images were ever packed, how many packings are rotated / scaled / mirrored (the cases a + * rect-shaped placement type would silently lose), how many model images composite MORE than one + * source layer (where "which layer is this drawable bound to" has no unique answer), and how many + * texture inputs carry an ACTextureInput.optionalTransformOnCanvas at all (it is modeled but read + * nowhere, and the corpus answer is all of them - whether any is non-identity, an unaccounted third + * transform in the mapping chain, is what [characterizesTheOptionalCanvasTransform] settles). + * + * Corpus-gated: self-skips when no corpus is present. The counts print; the assertions only guard + * against a silently broken walk (a file with an atlas whose joins all resolve to nothing). + */ +class Cmo3LayerWebProbeTest { + /** One file's survey. */ + private data class LayerWebSurvey( + val fileName: String, + val drawableCount: Int, + val drawablesWithModelImage: Int, + val modelImageCount: Int, + val packedModelImages: Int, + val atlasCount: Int, + val rotatedPlacements: Int, + val scaledPlacements: Int, + val mirroredPlacements: Int, + val fractionalPlacements: Int, + val multiLayerModelImages: Int, + val modelImagesWithoutPixels: Int, + val optionalTransformsOnCanvas: Int, + ) + + /** + * The corpus samples this probe runs over, from the `cmo3.probe` property the `umamo.test-corpus` + * plugin forwards (comma-separated, resolved against the repo root). + * + * Read from the property rather than discovered by walking up from `user.dir`: an explicit `-D` + * pointing at a corpus outside the working tree is exactly the case a directory walk misses, and a + * probe that cannot find its input returns early and reports PASSED while covering nothing. + * + * @return List The readable samples, empty when the property names none. + */ + private fun corpusFiles(): List = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map { entry -> File(entry.trim()) } + ?.filter { file -> file.isFile } + ?.sortedBy { file -> file.name } + .orEmpty() + + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun artMeshes(root: CModelSource): List = + elements((root.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + + /** The model images pooled under the texture manager's groups. */ + private fun modelImagesOf(textureManager: CTextureManager?): List = + // CMO3: CTextureManager field _modelImageGroups -> CModelImageGroup field _modelImages + elements(textureManager?._modelImageGroups) + .filterIsInstance() + .flatMap { group -> elements(group._modelImages).filterIsInstance() } + + /** Every atlas placement record in the document, in atlas order. */ + private fun placementEntriesOf(textureManager: CTextureManager?): List = + // CMO3: CTextureManager field _textureAtlases -> CTextureAtlas field modelImages + elements(textureManager?._textureAtlases) + .filterIsInstance() + .flatMap { atlas -> elements(atlas.modelImages).filterIsInstance() } + + /** The layer inputs a model image composites; more than one means no unique source layer. */ + private fun layerInputsOf(modelImage: CModelImage): List { + // CMO3: CModelImage field inputFilterEnv -> CLayerSelectorMap field _imageToLayerInput + val selectorMap = modelImage.inputFilterEnv as? CLayerSelectorMap ?: return emptyList() + return elements(selectorMap._imageToLayerInput).flatMap { perImage -> + elements(perImage).filterIsInstance() + } + } + + private fun surveyOf(fileName: String, root: CModelSource): LayerWebSurvey { + // CMO3: CModelSource field textureManager + val textureManager = root.textureManager as? CTextureManager + val modelImages = modelImagesOf(textureManager) + val placements = placementEntriesOf(textureManager) + val packedGuids = + placements + // CMO3: ModelImageEntry field modelImageGuid + .mapNotNull { entry -> (entry.modelImageGuid as? Guid)?.uuid } + .toSet() + + var drawablesWithModelImage = 0 + var optionalTransformsOnCanvas = 0 + for (mesh in artMeshes(root)) { + // CMO3: CArtMeshSource field _extensions -> CTextureInputExtension field _textureInputs + val extension = elements(mesh._extensions).filterIsInstance().firstOrNull() + val inputs = elements(extension?._textureInputs) + if (inputs.any { input -> input is CTextureInput_ModelImage }) { + drawablesWithModelImage++ + } + // CMO3: ACTextureInput field optionalTransformOnCanvas + optionalTransformsOnCanvas += + inputs.count { input -> (input as? org.umamo.format.cmo3.model.gen.ACTextureInput)?.optionalTransformOnCanvas != null } + } + + var rotated = 0 + var scaled = 0 + var mirrored = 0 + var fractional = 0 + for (entry in placements) { + // CMO3: ModelImageEntry field materialLocalToAtlasTransform (GTransform2: position, scale, eulerAngle) + val placement = entry.materialLocalToAtlasTransform as? GTransform2 ?: continue + if (placement.eulerAngle != 0f) { + rotated++ + } + val scale = placement.scale as? GVector2 + if (scale != null) { + if (scale.x < 0f || scale.y < 0f) { + mirrored++ + } + if (kotlin.math.abs(kotlin.math.abs(scale.x) - 1f) > 1e-4f || kotlin.math.abs(kotlin.math.abs(scale.y) - 1f) > 1e-4f) { + scaled++ + } + } + val position = placement.position as? GVector2 + if (position != null && (position.x != kotlin.math.floor(position.x) || position.y != kotlin.math.floor(position.y))) { + fractional++ + } + } + + return LayerWebSurvey( + fileName = fileName, + drawableCount = artMeshes(root).size, + drawablesWithModelImage = drawablesWithModelImage, + modelImageCount = modelImages.size, + // CMO3: CModelImage field guid joins the drawable's input to the atlas entry + packedModelImages = modelImages.count { image -> (image.guid as? Guid)?.uuid in packedGuids }, + atlasCount = elements(textureManager?._textureAtlases).filterIsInstance().size, + rotatedPlacements = rotated, + scaledPlacements = scaled, + mirroredPlacements = mirrored, + fractionalPlacements = fractional, + multiLayerModelImages = modelImages.count { image -> layerInputsOf(image).size > 1 }, + // CMO3: CModelImage field _filteredImage - the baked composite the layer view samples + modelImagesWithoutPixels = modelImages.count { image -> image._filteredImage !is CImageResource }, + optionalTransformsOnCanvas = optionalTransformsOnCanvas, + ) + } + + @Test + fun surveysTheLayeredArtWebAcrossTheCorpus() { + val files = corpusFiles() + if (files.isEmpty()) { + println("cmo3.probe lists no readable samples; skipping the layered-art web probe") + return + } + + val surveys = mutableListOf() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + surveys.add(surveyOf(file.name, root)) + } + + println("CMO3 layered-art web survey (${surveys.size} files)") + println("file | drawables (w/ model image) | model images (packed) | atlases | rot | scaled | mirrored | fractional | multi-layer | no pixels | optionalTransform") + for (survey in surveys) { + println( + "${survey.fileName} | ${survey.drawableCount} (${survey.drawablesWithModelImage}) | " + + "${survey.modelImageCount} (${survey.packedModelImages}) | ${survey.atlasCount} | " + + "${survey.rotatedPlacements} | ${survey.scaledPlacements} | ${survey.mirroredPlacements} | " + + "${survey.fractionalPlacements} | ${survey.multiLayerModelImages} | " + + "${survey.modelImagesWithoutPixels} | ${survey.optionalTransformsOnCanvas}", + ) + } + + // Non-vacuity: a file carrying both an atlas and model images must resolve SOME drawable-to-model-image + // join, or the walk above is broken rather than the corpus being sparse. + val webBearing = surveys.filter { survey -> survey.atlasCount > 0 && survey.modelImageCount > 0 } + assertTrue(webBearing.isNotEmpty(), "no corpus file carries both an atlas and model images; the walk is broken") + for (survey in webBearing) { + assertTrue( + survey.drawablesWithModelImage > 0, + "${survey.fileName} has ${survey.modelImageCount} model images but no drawable joins one; the walk is broken", + ) + } + } + + /** + * Characterizes ACTextureInput.optionalTransformOnCanvas, which the survey shows is present on EVERY + * texture input rather than being the rare slot its name suggests. What matters for the mapping chain + * is whether it ever carries anything but an identity: a non-identity would be a third transform + * between the sampled image and the canvas that the model-image / atlas-entry pair does not account for. + */ + @Test + fun characterizesTheOptionalCanvasTransform() { + val files = corpusFiles() + if (files.isEmpty()) { + println("cmo3.probe lists no readable samples; skipping the optional-canvas-transform probe") + return + } + val typeCounts = mutableMapOf() + var identityCount = 0 + var nonIdentityCount = 0 + val nonIdentityExamples = mutableListOf() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + for (mesh in artMeshes(root)) { + val extension = elements(mesh._extensions).filterIsInstance().firstOrNull() + for (input in elements(extension?._textureInputs)) { + // CMO3: ACTextureInput field optionalTransformOnCanvas + val transform = (input as? ACTextureInput)?.optionalTransformOnCanvas ?: continue + val typeName = "${input::class.simpleName}.${transform::class.simpleName}" + typeCounts[typeName] = (typeCounts[typeName] ?: 0) + 1 + val affine = transform as? CAffine + if (affine != null && + affine.m00 == 1f && + affine.m01 == 0f && + affine.m02 == 0f && + affine.m10 == 0f && + affine.m11 == 1f && + affine.m12 == 0f + ) { + identityCount++ + } else { + nonIdentityCount++ + if (nonIdentityExamples.size < 8) { + nonIdentityExamples.add("${file.name} ${(mesh.id as? Id)?.idstr} $typeName $transform") + } + } + } + } + } + println("optionalTransformOnCanvas: identity=$identityCount nonIdentity=$nonIdentityCount") + println(" by type: $typeCounts") + for (example in nonIdentityExamples) { + println(" non-identity: $example") + } + assertTrue(typeCounts.isNotEmpty(), "no optionalTransformOnCanvas values were seen; the walk is broken") + } + + /** + * Counts model images whose bound drawables DISAGREE about sampling an atlas page. + * + * `PuppetModel.atlasBindingForTile` hands out one placement per tile and documents that every + * drawable over one layer shares it. But `cmo3AtlasIngest` derives whether a drawable samples a + * packed page per drawable, from whether THAT drawable's own `srcImageResource` is one of the atlas + * pages - so two drawables on one model image could in principle disagree, one getting a placement + * and one getting null. If that happens, the UV editor builds its authoring frame from one drawable's + * placement while projecting another through its own, and an edit commits through the wrong frame. + * + * This settles whether the shape occurs in real files rather than only in the type system. A + * non-zero count here is a bug report; zero makes the shared-placement assumption an invariant worth + * asserting rather than a guess. + */ + @Test + fun boundDrawablesAgreeOnSamplingTheAtlas() { + val files = corpusFiles() + if (files.isEmpty()) { + println("cmo3.probe lists no readable samples; skipping the placement-agreement probe") + return + } + var checkedModelImages = 0 + var sharedModelImages = 0 + val disagreements = mutableListOf() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + // CMO3: CTextureAtlas field cachedAtlasImage - identity membership is the test the real + // derivation uses (CImageResource is a plain class, so equality is identity). + val textureManager = root.textureManager as? CTextureManager + val atlasPageResources = + elements(textureManager?._textureAtlases) + .filterIsInstance() + .mapNotNull { atlas -> atlas.cachedAtlasImage as? CImageResource } + .toHashSet() + // Per model image, the distinct samplesAtlasPage answers its drawables give. + val answersByModelImage = HashMap>() + for (mesh in artMeshes(root)) { + // CMO3: CArtMeshSource field _extensions -> CTextureInputExtension field _textureInputs -> + // CTextureInput_ModelImage field _modelImageGuid + val extension = elements(mesh._extensions).filterIsInstance().firstOrNull() + val modelImageInput = + elements(extension?._textureInputs).filterIsInstance().firstOrNull() ?: continue + val key = (modelImageInput._modelImageGuid as? Guid)?.uuid?.takeIf { it.isNotEmpty() } ?: continue + // CMO3: CArtMeshSource field texture -> GTexture2D field srcImageResource + val sampledResource = (mesh.texture as? GTexture2D)?.srcImageResource as? CImageResource + answersByModelImage.getOrPut(key) { mutableSetOf() }.add(sampledResource != null && sampledResource in atlasPageResources) + } + for ((key, answers) in answersByModelImage) { + checkedModelImages++ + if (answers.size > 1) { + disagreements.add("${file.name}: model image $key has drawables on both sides") + } + } + sharedModelImages += answersByModelImage.count { (_, answers) -> answers.isNotEmpty() } + } + println("[placement-agreement] $checkedModelImages model images across ${files.size} files, $sharedModelImages bound") + disagreements.forEach { line -> println("[placement-agreement] DISAGREEMENT $line") } + assertTrue(checkedModelImages > 0, "the walk found no bound model images at all, so it proved nothing") + assertTrue( + disagreements.isEmpty(), + "drawables over one model image disagree about sampling the atlas, so a layer has no single " + + "placement and atlasBindingForTile's shared-placement contract does not hold:\n${disagreements.joinToString("\n")}", + ) + } + + /** The drawable id every join keys on must survive; a blank id would silently orphan the binding. */ + @Test + fun everyArtMeshCarriesAJoinableId() { + val files = corpusFiles() + if (files.isEmpty()) { + println("cmo3.probe lists no readable samples; skipping the art-mesh id probe") + return + } + var checked = 0 + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + for (mesh in artMeshes(root)) { + // CMO3: CArtMeshSource field id - the DrawableId Cmo3Import mints, and the store's join key. + val idString = (mesh.id as? Id)?.idstr + assertTrue(!idString.isNullOrEmpty(), "${file.name}: an art mesh carries no id string") + checked++ + } + } + assertTrue(checked > 0, "no art meshes were checked; the corpus walk is broken") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3RetainedLayerWebTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3RetainedLayerWebTest.kt new file mode 100644 index 0000000..0dc4bef --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3RetainedLayerWebTest.kt @@ -0,0 +1,443 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CSize +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.GVector2 +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.fittedInto +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.reloadTileId +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The retained-graph layer web a CMO3-origin export writes: a reloaded tile rewrites its root's + * layer and model image, a reload's added layer mints a layer in its folder, an added file mints a + * whole layered image, the created drawables over them bind, and the whole thing reads back through + * the codec, the ingest, and the layered-art reader. The retained graph is an artwork-origin export + * read back, so no corpus is needed. + */ +class Cmo3RetainedLayerWebTest { + private val pageSize = 16 + private val now = 1_700_000_000_000L + private val sourceA = ArtSourceId("art-0") + + private val tileEye = AtlasTile(AtlasTileId("art-0/lyid:1576"), "Eye", 4, 4, placement = AtlasPlacement(0, 2f, 2f, 1f, 1f, 0f), source = SourceLayerRef(sourceA, "lyid:1576", true)) + private val tileHair = AtlasTile(AtlasTileId("art-0/lyid:5"), "Hair", 4, 4, placement = AtlasPlacement(0, 8f, 2f, 1f, 1f, 0f), source = SourceLayerRef(sourceA, "lyid:5", true)) + + private fun row(key: String, name: String, groupPath: String, left: Int, top: Int, size: Int = 4): ArtSourceLayer = ArtSourceLayer(key, name, groupPath, left, top, size, size, visible = true) + + private fun gradient(size: Int, seed: Int): RasterImage = RasterImage(size, size, ByteArray(size * size * 4) { index -> (index * 7 + seed).toByte() }) + + private fun quad(left: Float, top: Float, size: Float = 4f): DrawableMesh = + DrawableMesh( + positions = floatArrayOf(left, top, left + size, top, left + size, top + size, left, top + size), + uvs = floatArrayOf(0.1f, 0.1f, 0.35f, 0.1f, 0.35f, 0.35f, 0.1f, 0.35f), + indices = intArrayOf(0, 1, 2, 0, 2, 3), + ) + + private fun drawable(id: String, tile: AtlasTile, left: Float, top: Float): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), quad(left, top), null, atlasTileId = tile.id) + + private val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, ByteArray(pageSize * pageSize * 4) { 0x40 })), pageSize, pageSize) + + /** + * A retained graph: an artwork-origin fixture (one file, an eye in Head/Eyes and hair at the root, + * both placed) exported fresh and read back, with the baseline the reconcile will diff against. + * + * @return Pair The model and its import. + */ + private fun retainedGraph(): Pair { + val drawables = listOf(drawable("EyeL", tileEye, 10f, 20f), drawable("Hair", tileHair, 30f, 40f)) + val puppet = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = -50f, + runtimeTarget = RuntimeTarget.Cubism53, + atlas = PuppetAtlas(pages = listOf(AtlasPage(pageSize, pageSize)), tiles = listOf(tileEye, tileHair)), + sources = listOf(ArtSource(sourceA, "a.psd", "/art/a.psd", "psd", listOf(row("lyid:1576", "Eye", "Head/Eyes", 10, 20), row("lyid:5", "Hair", "", 30, 40)), contentHash = null, lastModified = 123L)), + ) + val rasters = mapOf(tileEye.id to gradient(4, 1), tileHair.id to gradient(4, 2)) + val fresh = + Cmo3Conversion.freshCmo3( + puppet = puppet, + pages = listOf(page), + pageIndexByDrawableId = mapOf("EyeL" to 0, "Hair" to 0), + modelName = "Retained", + nowMillis = now, + obfuscateKey = 0x1234ABCD, + tileRasters = { tileId -> rasters[tileId] }, + ) + assertTrue(fresh.report.notices.isEmpty(), "the fixture exports clean: ${fresh.report.notices}") + val retained = Cmo3.read(Cmo3.write(fresh.model)) + return retained to Cmo3Import.fromModelSource(retained.root as CModelSource) + } + + private fun mainXmlOf(model: Cmo3Model): ByteArray = CaffCodec.read(Cmo3.write(model)).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + + private fun imagesOf(root: CModelSource): List = + Cmo3Import.elementsOf((root.textureManager as CTextureManager)._rawImages).filterIsInstance().map { wrapper -> wrapper.image as CLayeredImage } + + private fun meshesOf(root: CModelSource): List = + Cmo3Import.elementsOf((root.drawableSourceSet as CDrawableSourceSet)._sources).filterIsInstance() + + private fun iconPath(icon: Any?): String? = ((icon as? CImageIcon)?.image as? CWritableImage)?.image?.archivePath + + @Test + fun reloadedAddedAndNewFileArtReachTheRetainedGraphAndReadBack() { + val (retained, baseline) = retainedGraph() + val retainedSource = baseline.sources.single() + val eyeTile = baseline.atlas.tiles.first { tile -> tile.source?.layerKey == "lyid:1576" } + val hairTile = baseline.atlas.tiles.first { tile -> tile.source?.layerKey == "lyid:5" } + val eyeDrawable = baseline.drawables.first { drawable -> drawable.id.raw == "EyeL" } + + // A reload of the eye: repainted at 6x6, moved on the canvas, repacked lower on the page. + val eyeReloaded = AtlasTile(reloadTileId(eyeTile.id, baseline.atlas.tiles.mapTo(HashSet()) { tile -> tile.id }), "Eye", 6, 6, placement = AtlasPlacement(0, 2f, 8f, 1f, 1f, 0f), source = eyeTile.source, replaces = eyeTile.id) + // The same reload's added layer, in a folder the file never had, with a created drawable over it. + val browTile = AtlasTile(AtlasTileId("${retainedSource.id.raw}/lyid:77"), "Brow", 4, 4, placement = AtlasPlacement(0, 8f, 8f, 1f, 1f, 0f), source = SourceLayerRef(retainedSource.id, "lyid:77", true)) + // Add Artwork of a second file, with a created drawable over its one tile. + val sourceC = ArtSourceId("art-9") + val wingTile = AtlasTile(AtlasTileId("art-9/uuid-w"), "Wing", 4, 4, placement = AtlasPlacement(0, 12f, 12f, 1f, 1f, 0f), source = SourceLayerRef(sourceC, "uuid-w", true)) + val editedSources = + listOf( + retainedSource.copy(layers = retainedSource.layers.map { layer -> if (layer.key == "lyid:1576") layer.copy(left = 12, top = 24, width = 6, height = 6) else layer } + row("lyid:77", "Brow", "Head/Brows", 40, 44)), + ArtSource(sourceC, "c.clip", null, "clip", listOf(row("uuid-w", "Wing", "", 50, 50))), + ) + val brow = drawable("Brow", browTile, 40f, 44f) + val wing = drawable("Wing", wingTile, 50f, 50f) + val edited = + baseline.copy( + drawables = baseline.drawables.map { drawable -> if (drawable.id == eyeDrawable.id) drawable.copy(atlasTileId = eyeReloaded.id) else drawable } + brow + wing, + rootChildren = baseline.rootChildren + OrgChild.Drawable(brow.id) + OrgChild.Drawable(wing.id), + atlas = baseline.atlas.copy(tiles = listOf(eyeReloaded, hairTile, browTile, wingTile)), + sources = editedSources, + ) + val rasters = mapOf(eyeReloaded.id to gradient(6, 11), browTile.id to gradient(4, 12), wingTile.id to gradient(4, 13)) + val thumbnail = gradient(4, 21) + // The icon entries the reload must refresh IN PLACE: the eye layer's, EyeL's, and the model's. + val retainedRoot = retained.root as CModelSource + val retainedEyeLayer = walkLayeredImage(imagesOf(retainedRoot).single()).first { walked -> walked.key == "lyid:1576" }.layer + val eyeIcon64Path = assertNotNull(Cmo3Icons.archivePathOf(retainedEyeLayer.icon64)) + val eyeLMesh = meshesOf(retainedRoot).first { mesh -> Cmo3Import.idStrOf(mesh.id) == "EyeL" } + val eyeLIcon32Path = assertNotNull(Cmo3Icons.archivePathOf(eyeLMesh.icon32)) + val eyeLIcon32Before = assertNotNull(retained.archive.byPath(eyeLIcon32Path)).content + val modelIcon64Path = assertNotNull(Cmo3Icons.archivePathOf(retainedRoot._icon64)) + + val report = Cmo3Export.apply(edited, retained, recomposedPages = listOf(page), tileRasters = { tileId -> rasters[tileId] }, nowMillis = now, modelThumbnail = thumbnail) + assertTrue(report.notices.isEmpty(), "the reconcile owes nothing: ${report.notices}") + + val reread = Cmo3.read(Cmo3.write(retained)) + val rereadRoot = reread.root as CModelSource + val textureManager = rereadRoot.textureManager as CTextureManager + + // The inventory: the eye's rect moved and grew, the brow sits in Head/Brows, the new file lists its wing. + val ingest = cmo3AtlasIngest(rereadRoot) + val rereadA = assertNotNull(ingest.sources.firstOrNull { source -> source.id == retainedSource.id }, "a.psd keeps its identity") + assertEquals(listOf("lyid:1576", "lyid:77", "lyid:5"), rereadA.layers.map { layer -> layer.key }, "the brow joins Head beside Eyes, before the root's hair") + assertEquals(listOf("Head/Eyes", "Head/Brows", ""), rereadA.layers.map { layer -> layer.groupPath }) + assertEquals(listOf(12, 24, 6, 6), rereadA.layers[0].let { layer -> listOf(layer.left, layer.top, layer.width, layer.height) }, "the eye's rect is the refreshed row") + assertEquals(listOf(40, 44, 4, 4), rereadA.layers[1].let { layer -> listOf(layer.left, layer.top, layer.width, layer.height) }) + val rereadC = assertNotNull(ingest.sources.firstOrNull { source -> source.name == "c.clip" }, "the added file is a layered image: ${ingest.sources.map { source -> source.name }}") + assertEquals(listOf("name:Wing"), rereadC.layers.map { layer -> layer.key }, "a uuid key reopens as a name key") + + // The tiles: the eye keeps its root identity at the new placement and size; the minted ones are placed. + val tileByKey = ingest.atlas.tiles.associateBy { tile -> tile.source?.layerKey } + val eyeBack = tileByKey.getValue("lyid:1576") + assertEquals(eyeTile.id, eyeBack.id, "the reloaded tile is its root's model image") + assertEquals(AtlasPlacement(0, 2f, 8f, 1f, 1f, 0f), eyeBack.placement) + assertEquals(6 to 6, eyeBack.width to eyeBack.height) + assertEquals("Eye", eyeBack.name) + assertEquals(AtlasPlacement(0, 8f, 8f, 1f, 1f, 0f), tileByKey.getValue("lyid:77").placement) + assertEquals(AtlasPlacement(0, 12f, 12f, 1f, 1f, 0f), tileByKey.getValue("name:Wing").placement) + assertEquals(AtlasPlacement(0, 8f, 2f, 1f, 1f, 0f), tileByKey.getValue("lyid:5").placement, "the untouched hair did not move") + + // The pixels: the layered-art reader decodes the new rasters out of the retained file. + val artA = assertNotNull(cmo3SourceArtOf(rereadRoot, retainedSource.id) { resource -> reread.extractLayerPng(resource) }) + assertContentEquals(gradient(6, 11).rgba, assertNotNull(artA.layers.firstOrNull { layer -> layer.id.raw == "lyid:1576" }).raster.rgba, "the eye's layer holds the repainted pixels") + assertContentEquals(gradient(4, 12).rgba, assertNotNull(artA.layers.firstOrNull { layer -> layer.id.raw == "lyid:77" }).raster.rgba, "the brow's layer holds its pixels") + val artC = assertNotNull(cmo3SourceArtOf(rereadRoot, rereadC.id) { resource -> reread.extractLayerPng(resource) }) + assertContentEquals(gradient(4, 13).rgba, artC.layers.single().raster.rgba) + + // The model image and entry: the canvas placement is the new origin, the entry pair composes to it. + val modelImages = + Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance() + .flatMap { group -> Cmo3Import.elementsOf(group._modelImages).filterIsInstance() } + val eyeImage = assertNotNull(modelImages.firstOrNull { modelImage -> Cmo3Import.uuidOf(modelImage.guid) == eyeTile.id.raw }) + val eyePlacement = eyeImage._materialLocalToCanvasTransform as CAffine + assertEquals(listOf(1f, 0f, 12f, 0f, 1f, 24f), listOf(eyePlacement.m00, eyePlacement.m01, eyePlacement.m02, eyePlacement.m10, eyePlacement.m11, eyePlacement.m12)) + assertEquals(6 to 6, (eyeImage._filteredImage as CImageResource).let { resource -> resource.width to resource.height }) + val atlas = Cmo3Import.elementsOf(textureManager._textureAtlases).filterIsInstance().single() + val entries = Cmo3Import.elementsOf(atlas.modelImages).filterIsInstance() + assertEquals(4, entries.size, "eye, hair, brow, wing") + val eyeEntry = assertNotNull(entries.firstOrNull { entry -> Cmo3Import.uuidOf(entry.modelImageGuid) == eyeTile.id.raw }) + assertEquals(2f to 8f, ((eyeEntry.materialLocalToAtlasTransform as GTransform2).position as GVector2).let { position -> position.x to position.y }) + val eyeAtlasToCanvas = eyeEntry.atlasLocalToCanvasTransform as CAffine + assertEquals(10f, eyeAtlasToCanvas.m02, 1e-5f, "translate(12, 24) composed with the placement's inverse") + assertEquals(16f, eyeAtlasToCanvas.m12, 1e-5f) + val groups = Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance() + assertEquals(listOf("a.psd", "c.clip"), groups.map { group -> group.groupName }, "one group per file") + + // Every icon a minted layer or image references is an archive entry, on a path of its own. + val images = Cmo3Import.elementsOf(textureManager._rawImages).filterIsInstance().map { wrapper -> wrapper.image as CLayeredImage } + val iconPaths = ArrayList() + for (image in images) { + for (walked in walkLayeredImage(image)) { + iconPaths.add(assertNotNull(iconPath(walked.layer.icon16), "${walked.layer.name} has a 16px icon")) + iconPaths.add(assertNotNull(iconPath(walked.layer.icon64), "${walked.layer.name} has a 64px icon")) + } + } + for (modelImage in modelImages) { + iconPaths.add(assertNotNull(iconPath(modelImage.icon16), "${modelImage.name} has an icon")) + } + assertEquals(iconPaths.size, iconPaths.toSet().size, "icon paths are unique: $iconPaths") + for (path in iconPaths) { + assertNotNull(reread.archive.byPath(path), "icon '$path' is embedded") + } + // The rewritten layer's icon shows the new art at its old entry; so does EyeL's, over the patch + // its mesh now covers; the minted layers' and drawables' icons exist; the model icons are the + // thumbnail, at their old entries. + val eyeLayerBack = walkLayeredImage(images[0]).first { walked -> walked.key == "lyid:1576" }.layer + assertEquals(eyeIcon64Path, Cmo3Icons.archivePathOf(eyeLayerBack.icon64), "the rewritten layer keeps its icon entry") + assertContentEquals(gradient(6, 11).fittedInto(64).rgba, PngCodec.read(assertNotNull(reread.archive.byPath(eyeIcon64Path)).content).rgba, "which now holds the new raster's fit") + val eyeLBack = meshesOf(rereadRoot).first { mesh -> Cmo3Import.idStrOf(mesh.id) == "EyeL" } + assertEquals(eyeLIcon32Path, Cmo3Icons.archivePathOf(eyeLBack.icon32), "EyeL keeps its icon entry") + val eyeLIcon32After = assertNotNull(reread.archive.byPath(eyeLIcon32Path)).content + assertTrue(!eyeLIcon32After.contentEquals(eyeLIcon32Before), "EyeL's icon was re-rendered") + val eyeLEdited = edited.drawables.first { drawable -> drawable.id.raw == "EyeL" } + assertContentEquals( + Cmo3Icons.patchOf(gradient(6, 11), Cmo3Icons.artUvsOf(edited, eyeLEdited)).fittedInto(32).rgba, + PngCodec.read(eyeLIcon32After).rgba, + "over the patch its mesh covers on the new art", + ) + for (name in listOf("Brow", "Wing")) { + val mesh = meshesOf(rereadRoot).first { candidate -> Cmo3Import.idStrOf(candidate.id) == name } + for ((icon, size) in listOf(mesh.icon32 to 32, mesh.icon16 to 16)) { + val decoded = PngCodec.read(assertNotNull(reread.archive.byPath(assertNotNull(Cmo3Icons.archivePathOf(icon), "$name has a ${size}px icon"))).content) + assertEquals(size to size, decoded.width to decoded.height) + } + } + assertEquals(modelIcon64Path, Cmo3Icons.archivePathOf(rereadRoot._icon64), "the model icon keeps its entry") + assertContentEquals(thumbnail.fittedInto(64).rgba, PngCodec.read(assertNotNull(reread.archive.byPath(modelIcon64Path)).content).rgba, "and holds the thumbnail's fit") + assertContentEquals(thumbnail.fittedInto(16).rgba, PngCodec.read(assertNotNull(reread.archive.byPath(assertNotNull(Cmo3Icons.archivePathOf(rereadRoot._icon16)))).content).rgba) + + // The drawables: the created ones bind to their tiles, and every drawable re-imports verbatim. + assertEquals(tileByKey.getValue("lyid:77").id, ingest.tileIdByDrawableId["Brow"], "the brow binds to its minted tile") + assertEquals(tileByKey.getValue("name:Wing").id, ingest.tileIdByDrawableId["Wing"]) + assertEquals(eyeTile.id, ingest.tileIdByDrawableId["EyeL"], "the eye's drawable samples the root's model image") + val reimported = Cmo3Import.fromModelSource(rereadRoot) + for (drawable in edited.drawables) { + val back = assertNotNull(reimported.drawables.firstOrNull { candidate -> candidate.id == drawable.id }, "${drawable.name} re-imports") + assertContentEquals(drawable.mesh?.uvs, back.mesh?.uvs, "${drawable.name} uvs are verbatim") + } + } + + /** The hair drawable's coordinates in its art's own frame, before the reduced copy's scale. */ + private val hairArtUvs = floatArrayOf(0.1f, 0.1f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f) + + /** + * Recasts the retained graph's hair the way an editor model saved in combined-layer display holds its + * art: its own texture over a reduced cache copy of its model image (the 4px raster padded to 64 and + * halved), carrying the raster-to-cache scale, with its coordinates in the copy's frame. Written and + * read back, like a file the editor saved. + * + * @param Cmo3Model retained The retained graph. + * @param AtlasTile hairTile The hair's tile, whose guid names its model image. + * @return Pair The re-read model and the copy's archive path. + */ + private fun withHairOverAReducedCopy(retained: Cmo3Model, hairTile: AtlasTile): Pair { + val root = retained.root as CModelSource + val textureManager = root.textureManager as CTextureManager + val hairImage = + Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance() + .flatMap { group -> Cmo3Import.elementsOf(group._modelImages).filterIsInstance() } + .first { modelImage -> Cmo3Import.uuidOf(modelImage.guid) == hairTile.id.raw } + val copyPath = retained.nextImageFileBufPath() + val copyPng = PngCodec.write(RasterImage(32, 32, ByteArray(32 * 32 * 4) { 0x22 })) + val copy = Cmo3ImageChainBuilder.pageImageResource(copyPath, 32, 32, copyPng.size) + retained.addLayerPng(copy, copyPng) + val manager = hairImage.cachedImageManager as CCachedImageManager + manager.cachedImages = + ArrayList( + Cmo3Import.elementsOf(manager.cachedImages) + + CCachedImage().apply { + _cachedImageResource = copy + isSharedImage = false + rawImageSize = + CSize().apply { + width = 4 + height = 4 + } + reductionRatio = 2 + mipmapLevel = 32 + transformRawImageToCachedImage = + CAffine().apply { + m00 = 0.5f + m11 = 0.5f + } + }, + ) + val hairMesh = meshesOf(root).first { mesh -> Cmo3Import.idStrOf(mesh.id) == "Hair" } + hairMesh.texture = + Cmo3ImageChainBuilder.pageTexture("Hair", copy).apply { + transformImageResource01toLogical01 = Cmo3ImageChainBuilder.paddedFrameAffine(4, 4) + mipmapLevel = 32 + } + val scale = Cmo3ImageChainBuilder.paddedFrameAffine(4, 4) + hairMesh.uvs = FloatArray(hairArtUvs.size) { componentIndex -> hairArtUvs[componentIndex] * if (componentIndex % 2 == 0) scale.m00 else scale.m11 } + return Cmo3.read(Cmo3.write(retained)) to copyPath + } + + @Test + fun aReloadMovesDrawablesOffTheReducedCopyOntoTheNewRaster() { + val (fixture, fixtureBaseline) = retainedGraph() + val (retained, copyPath) = withHairOverAReducedCopy(fixture, fixtureBaseline.atlas.tiles.first { tile -> tile.source?.layerKey == "lyid:5" }) + val baseline = Cmo3Import.fromModelSource(retained.root as CModelSource) + val hairTile = baseline.atlas.tiles.first { tile -> tile.source?.layerKey == "lyid:5" } + val hair = baseline.drawables.first { drawable -> drawable.id.raw == "Hair" } + // The hair's tile is placed, so the import reads it out of the copy's frame and onto the page: tile + // pixel (x, y) sits at page pixel (8 + x, 2 + y) of the 16px page. + for (componentIndex in hairArtUvs.indices) { + val expected = if (componentIndex % 2 == 0) (8f + hairArtUvs[componentIndex] * 4f) / pageSize else (2f + hairArtUvs[componentIndex] * 4f) / pageSize + assertEquals(expected, hair.mesh!!.uvs[componentIndex], 1e-6f, "the import reads the copy's frame onto the hair's page") + } + + // A reload of the hair, repainted at 6x6. + val hairReloaded = AtlasTile(reloadTileId(hairTile.id, baseline.atlas.tiles.mapTo(HashSet()) { tile -> tile.id }), "Hair", 6, 6, placement = AtlasPlacement(0, 8f, 2f, 1f, 1f, 0f), source = hairTile.source, replaces = hairTile.id) + val retainedSource = baseline.sources.single() + val edited = + baseline.copy( + drawables = baseline.drawables.map { drawable -> if (drawable.id == hair.id) drawable.copy(atlasTileId = hairReloaded.id) else drawable }, + atlas = baseline.atlas.copy(tiles = baseline.atlas.tiles.map { tile -> if (tile.id == hairTile.id) hairReloaded else tile }), + sources = listOf(retainedSource.copy(layers = retainedSource.layers.map { layer -> if (layer.key == "lyid:5") layer.copy(width = 6, height = 6) else layer })), + ) + val report = Cmo3Export.apply(edited, retained, recomposedPages = listOf(page), tileRasters = { tileId -> if (tileId == hairReloaded.id) gradient(6, 31) else null }, nowMillis = now) + assertTrue(report.notices.isEmpty(), "the reconcile owes nothing: ${report.notices}") + + val reread = Cmo3.read(Cmo3.write(retained)) + val root = reread.root as CModelSource + val hairImage = + Cmo3Import.elementsOf((root.textureManager as CTextureManager)._modelImageGroups).filterIsInstance() + .flatMap { group -> Cmo3Import.elementsOf(group._modelImages).filterIsInstance() } + .first { modelImage -> Cmo3Import.uuidOf(modelImage.guid) == hairTile.id.raw } + val hairMesh = meshesOf(root).first { mesh -> Cmo3Import.idStrOf(mesh.id) == "Hair" } + val texture = hairMesh.texture as GTexture2D + assertSame(hairImage._filteredImage, texture.srcImageResource, "the hair samples its model image's new raster, not the copy") + val scale = texture.transformImageResource01toLogical01 as CAffine + assertEquals(listOf(6f / 64f, 0f, 0f, 0f, 6f / 64f, 0f), listOf(scale.m00, scale.m01, scale.m02, scale.m10, scale.m11, scale.m12), "with the new size's cache scale") + assertEquals(Cmo3ImageChainBuilder.FULL_RESOLUTION_MIPMAP_LEVEL, texture.mipmapLevel) + // A packed drawable over its raster stores the raster's frame: the edited page coordinates off the + // reloaded 6px tile's placement. + val storedAfter = hairMesh.uvs as FloatArray + for (componentIndex in storedAfter.indices) { + val pageCoordinate = hair.mesh!!.uvs[componentIndex] * pageSize + val expected = if (componentIndex % 2 == 0) (pageCoordinate - 8f) / 6f else (pageCoordinate - 2f) / 6f + assertEquals(expected, storedAfter[componentIndex], 1e-5f, "the hair stores its new raster's frame at component $componentIndex") + } + val reimportedHair = Cmo3Import.fromModelSource(root).drawables.first { drawable -> drawable.id == hair.id } + for (componentIndex in storedAfter.indices) { + assertEquals(hair.mesh!!.uvs[componentIndex], reimportedHair.mesh!!.uvs[componentIndex], 1e-6f, "and re-imports to the page coordinates it was edited with") + } + + // The copy is gone from the graph and the archive; the eye still samples the page. + assertNull(reread.archive.byPath(copyPath), "the copy's pixels are removed") + val cachedResources = + Cmo3Import.elementsOf((hairImage.cachedImageManager as CCachedImageManager).cachedImages).filterIsInstance().map { cached -> cached._cachedImageResource as? CImageResource } + assertTrue(cachedResources.none { resource -> resource?.imageFileBuf?.archivePath == copyPath }, "no cache names the copy") + assertTrue(meshesOf(root).none { mesh -> ((mesh.texture as? GTexture2D)?.srcImageResource as? CImageResource)?.imageFileBuf?.archivePath == copyPath }, "no texture names the copy") + val eyeMesh = meshesOf(root).first { mesh -> Cmo3Import.idStrOf(mesh.id) == "EyeL" } + val pageResource = (Cmo3Import.elementsOf((root.textureManager as CTextureManager)._textureAtlases).filterIsInstance().single().cachedAtlasImage) + assertSame(pageResource, (eyeMesh.texture as GTexture2D).srcImageResource, "the eye is untouched") + } + + @Test + fun aReloadedTileWithNoPixelsDeclinesTheWebAndLeavesTheLayersAlone() { + val (retained, baseline) = retainedGraph() + val eyeTile = baseline.atlas.tiles.first { tile -> tile.source?.layerKey == "lyid:1576" } + val eyeReloaded = AtlasTile(reloadTileId(eyeTile.id, baseline.atlas.tiles.mapTo(HashSet()) { tile -> tile.id }), "Eye", 6, 6, placement = AtlasPlacement(0, 2f, 8f, 1f, 1f, 0f), source = eyeTile.source, replaces = eyeTile.id) + val edited = + baseline.copy( + drawables = baseline.drawables.map { drawable -> if (drawable.id.raw == "EyeL") drawable.copy(atlasTileId = eyeReloaded.id) else drawable }, + atlas = baseline.atlas.copy(tiles = baseline.atlas.tiles.map { tile -> if (tile.id == eyeTile.id) eyeReloaded else tile }), + ) + val entryCountBefore = retained.archive.entries.size + val entriesBefore = retained.archive.entries.map { entry -> entry.path to entry.content.copyOf() } + + val report = Cmo3Export.apply(edited, retained, recomposedPages = listOf(page), tileRasters = { null }, nowMillis = now) + val reasons = report.notices.filterIsInstance().map { notice -> notice.reason } + assertTrue(ExportNoticeReason.AtlasPageNotRecomposed in reasons, "the whole web declined, so the moved placement is reported: ${report.notices}") + assertTrue(ExportNoticeReason.AtlasTileMetadataNotReconcilable in reasons, "the size change is reported rather than half-written") + assertEquals(entryCountBefore, retained.archive.entries.size, "nothing was embedded") + for ((path, content) in entriesBefore) { + if (path.startsWith("image")) { + assertContentEquals(content, assertNotNull(retained.archive.byPath(path)).content, "icon '$path' is untouched") + } + } + val root = retained.root as CModelSource + val art = assertNotNull(cmo3SourceArtOf(root, baseline.sources.single().id) { resource -> retained.extractLayerPng(resource) }) + assertContentEquals(gradient(4, 1).rgba, assertNotNull(art.layers.firstOrNull { layer -> layer.id.raw == "lyid:1576" }).raster.rgba, "the eye's layer still holds the imported pixels") + } + + @Test + fun anUneditedApplyLeavesTheGraphByteIdentical() { + val (retained, baseline) = retainedGraph() + val before = mainXmlOf(retained) + val modelIconBefore = assertNotNull(retained.archive.byPath(assertNotNull(Cmo3Icons.archivePathOf((retained.root as CModelSource)._icon64)))).content.copyOf() + val report = Cmo3Export.apply(baseline, retained, tileRasters = { gradient(4, 99) }, nowMillis = now, modelThumbnail = gradient(4, 23)) + assertTrue(report.isEmpty, "no-change apply produced notices: ${report.notices}") + assertContentEquals(before, mainXmlOf(retained), "main.xml is unchanged") + assertNull(report.notices.firstOrNull(), "nothing reported") + assertContentEquals(modelIconBefore, assertNotNull(retained.archive.byPath(assertNotNull(Cmo3Icons.archivePathOf((retained.root as CModelSource)._icon64)))).content, "the model icon is untouched by an unedited export") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SkeletonBuilderTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SkeletonBuilderTest.kt new file mode 100644 index 0000000..e9dcc38 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SkeletonBuilderTest.kt @@ -0,0 +1,86 @@ +package org.umamo.interop.cmo3 + +import org.jdom.Element +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Author +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.xml.XmlCodec +import org.umamo.interop.cmo3TargetVersionNo +import org.umamo.runtime.model.RuntimeTarget +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Gates the blank-skeleton builder, part of the fresh-graph synthesis: a built blank assembles + * into a .cmo3 that reads back through the normal codec and imports as an empty puppet with the + * right document fields, and its CModelSource child sequence matches BareMinimum.cmo3 (the + * official editor's own New -> Save As) exactly. + */ +class Cmo3SkeletonBuilderTest { + @Test + fun blankSkeletonReadsBackAsAnEmptyPuppet() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Untitled Model", 1000, 2000, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + val bytes = + Cmo3FreshFile.assemble( + skeleton.root, + skeleton.iconEntries.map { icon -> Cmo3FreshFile.PngEntry(icon.path, icon.pngBytes) }, + obfuscateKey = 0x49C74776.toInt(), + ) + // The assembled blank doubles as the manual official-editor gate's input: open + // build/fresh-blank.cmo3 in the Cubism Editor to validate from-scratch acceptance. + File("build/fresh-blank.cmo3").writeBytes(bytes) + + val model = Cmo3.read(bytes) + val modelSource = model.root as? CModelSource ?: error("fresh blank did not read back as CModelSource") + assertEquals("Untitled Model", modelSource.name, "model name survives") + assertEquals(4, model.archive.entries.size, "three icon PNGs + main.xml") + assertEquals(CaffArchive.TAG_MAIN_XML, model.archive.entries.last().tag, "main.xml is the last entry") + + val puppet = Cmo3Import.fromModelSource(modelSource) + assertEquals(1000f, puppet.canvasWidth, "canvas width") + assertEquals(2000f, puppet.canvasHeight, "canvas height") + assertEquals(RuntimeTarget.Cubism53, puppet.runtimeTarget, "runtime target round-trips") + assertTrue(puppet.parameters.isEmpty(), "no parameters in a blank") + assertTrue(puppet.parts.isEmpty(), "no user parts in a blank (the root part is synthetic)") + assertTrue(puppet.deformers.isEmpty(), "no deformers in a blank") + assertTrue(puppet.drawables.isEmpty(), "no drawables in a blank") + assertTrue(puppet.glues.isEmpty(), "no glues in a blank") + } + + @Test + fun blankSpineMatchesBareMinimumChildSequence() { + val bareMinimum = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map { path -> File(path.trim()) } + ?.firstOrNull { file -> file.name == "BareMinimum.cmo3" && file.isFile } + ?: run { + println("BareMinimum.cmo3 not in cmo3.probe; skipping spine comparison") + return + } + val blankArchive = CaffCodec.read(bareMinimum.readBytes()) + val blankXml = blankArchive.firstByTag(CaffArchive.TAG_MAIN_XML) ?: error("BareMinimum has no main_xml") + val editorSpine = modelSourceChildren(XmlCodec.parse(blankXml.content).rootElement) + + val skeleton = Cmo3SkeletonBuilder.buildBlank("Untitled Model", 1000, 2000, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + val freshSpine = modelSourceChildren(XmlCodec.parse(Cmo3Author.writeFreshMainXml(skeleton.root)).rootElement) + + assertEquals(editorSpine, freshSpine, "CModelSource child (tag, xs.n) sequence matches the editor's blank") + } + + /** + * The (tag, xs.n) sequence of the document's CModelSource children. + * + * @param Element rootElement The parsed root element. + * @return List The child descriptors in document order. + */ + private fun modelSourceChildren(rootElement: Element): List> { + val mainElement = rootElement.getChild("main") ?: error("no
element") + val modelSource = mainElement.children.filterIsInstance().firstOrNull() ?: error("no model root element") + return modelSource.children.filterIsInstance().map { child -> child.name to child.getAttributeValue("xs.n") } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceFileExportTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceFileExportTest.kt new file mode 100644 index 0000000..91c4772 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceFileExportTest.kt @@ -0,0 +1,55 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * A relinked artwork file survives the CMO3 round trip: the record's new path and name lower onto + * the layered image the editor decomposed the file into, so the re-read document points at the file + * the rigger chose rather than at the path of the machine that first imported it. + * + * Skips without the corpus sample. + */ +class Cmo3SourceFileExportTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aRelinkedSourcePathAndNameSurviveTheRoundTrip() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the source-file export gate") + return + } + val cmo3 = Cmo3.read(file.readBytes()) + val puppet = Cmo3Import.fromModelSource(cmo3.root as CModelSource) + assertTrue(puppet.sources.isNotEmpty(), "the sample lists its decomposed artwork") + assertTrue(puppet.sources.all { source -> source.lastModified != null }, "the editor's psdFileLastModified comes in as the record's time") + val relinked = + puppet.copy( + sources = + puppet.sources.mapIndexed { index, source -> + if (index == 0) { + source.copy(name = "Relinked.clip", path = "/home/rigger/art/Relinked.clip", lastModified = 1_700_000_000_000L) + } else { + source.copy(path = "/home/rigger/art/${source.name}") + } + }, + ) + + val report = Cmo3Export.apply(relinked, cmo3) + assertTrue(report.notices.isEmpty(), "every listed file has an image to write to: ${report.notices}") + + val reread = Cmo3Import.fromModelSource(Cmo3.read(Cmo3.write(cmo3)).root as CModelSource) + assertEquals(relinked.sources.map { source -> source.id to source.path }, reread.sources.map { source -> source.id to source.path }, "the new paths came back") + val first = reread.sources.first() + assertEquals("Relinked.clip", first.name, "the new name came back") + assertEquals("clip", first.format, "and the format follows the name") + assertEquals(1_700_000_000_000L, first.lastModified, "and so did the modification time") + assertEquals(puppet.sources.drop(1).map { source -> source.lastModified }, reread.sources.drop(1).map { source -> source.lastModified }, "an untouched time stays") + assertEquals(puppet.sources.first().layers.map { layer -> layer.key }, first.layers.map { layer -> layer.key }, "the inventory is untouched") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceLayerWebTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceLayerWebTest.kt new file mode 100644 index 0000000..fef1083 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceLayerWebTest.kt @@ -0,0 +1,292 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.ACLayerEntry +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CLayerGroup +import org.umamo.format.cmo3.model.gen.CLayerIdentifier +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTransform2 +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.cmo3.model.type.CRect +import org.umamo.format.cmo3.model.type.FileRef +import org.umamo.format.cmo3.model.type.GVector2 +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.fittedInto +import org.umamo.interop.ExportNotice +import org.umamo.interop.cmo3TargetVersionNo +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The real-layer web an artwork-origin export writes: the routing of tiles into per-file inputs, the + * layered image with its folders and layers, the model images and entries, the bindings, and the + * whole thing read back through the codec, the ingest, and the layered-art reader. + */ +class Cmo3SourceLayerWebTest { + private val pageSize = 16 + private val now = 1_700_000_000_000L + private val sourceA = ArtSourceId("art-0") + private val sourceB = ArtSourceId("art-1") + + private val tileEye = AtlasTile(AtlasTileId("art-0/lyid:1576"), "Eye", 4, 4, placement = AtlasPlacement(0, 2f, 2f, 1f, 1f, 0f), source = SourceLayerRef(sourceA, "lyid:1576", true)) + private val tileHair = AtlasTile(AtlasTileId("art-0/lyid:5"), "Hair", 4, 4, placement = AtlasPlacement(0, 8f, 2f, 1f, 1f, -90f), source = SourceLayerRef(sourceA, "lyid:5", true)) + private val tileGuide = AtlasTile(AtlasTileId("art-0/lyid:9"), "Guide", 4, 4, placement = null, source = SourceLayerRef(sourceA, "lyid:9", true)) + private val tileWing = AtlasTile(AtlasTileId("art-1/uuid-w"), "Wing", 4, 4, placement = AtlasPlacement(0, 2f, 8f, 1f, 1f, 0f), source = SourceLayerRef(sourceB, "uuid-w", true)) + + private fun row(key: String, name: String, groupPath: String, left: Int, top: Int): ArtSourceLayer = ArtSourceLayer(key, name, groupPath, left, top, 4, 4, visible = true) + + private val sources = + listOf( + ArtSource(sourceA, "a.psd", "/art/a.psd", "psd", listOf(row("lyid:1576", "Eye", "Head/Eyes", 10, 20), row("lyid:5", "Hair", "", 30, 40), row("lyid:9", "Guide", "", 60, 60)), contentHash = null, lastModified = 123L), + ArtSource(sourceB, "b.clip", null, "clip", listOf(row("uuid-w", "Wing", "", 50, 50))), + ) + + private fun gradient(seed: Int): RasterImage = RasterImage(4, 4, ByteArray(4 * 4 * 4) { index -> (index * 7 + seed).toByte() }) + + private val rasters = mapOf(tileEye.id to gradient(1), tileHair.id to gradient(2), tileGuide.id to gradient(3), tileWing.id to gradient(4)) + + private fun quad(left: Float, top: Float): DrawableMesh = + DrawableMesh( + positions = floatArrayOf(left, top, left + 4f, top, left + 4f, top + 4f, left, top + 4f), + uvs = floatArrayOf(0.1f, 0.1f, 0.35f, 0.1f, 0.35f, 0.35f, 0.1f, 0.35f), + indices = intArrayOf(0, 1, 2, 0, 2, 3), + ) + + private fun drawable(id: String, tile: AtlasTile, left: Float, top: Float): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), quad(left, top), null, atlasTileId = tile.id) + + private val drawables = + listOf( + drawable("EyeL", tileEye, 10f, 20f), + drawable("EyeCopy", tileEye, 40f, 20f), + drawable("Hair", tileHair, 30f, 40f), + drawable("Guide", tileGuide, 60f, 60f), + drawable("Wing", tileWing, 50f, 50f), + ) + + private val puppet = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = -50f, + runtimeTarget = RuntimeTarget.Cubism53, + atlas = PuppetAtlas(pages = listOf(AtlasPage(pageSize, pageSize)), tiles = listOf(tileEye, tileHair, tileGuide, tileWing)), + sources = sources, + ) + + private val page = Cmo3Conversion.AtlasPage(PngCodec.write(RasterImage(pageSize, pageSize, ByteArray(pageSize * pageSize * 4) { 0x40 })), pageSize, pageSize) + + private fun names(entries: Any?): List = Cmo3Import.elementsOf(entries).filterIsInstance().map { entry -> entry.name.orEmpty() } + + @Test + fun theRoutingTakesEveryTileWithARasterAndARowInInventoryOrder() { + val inputs = Cmo3SourceLayerWeb.inputsOf(puppet) { tileId -> rasters[tileId] } + assertEquals(listOf("a.psd", "b.clip"), inputs.map { image -> image.name }) + val imageA = inputs[0] + assertEquals("/art/a.psd", imageA.path) + assertEquals(123L, imageA.lastModified) + assertEquals(100 to 100, imageA.width to imageA.height, "the frame is the document canvas") + assertEquals(listOf("Eye", "Hair", "Guide"), imageA.layers.map { layer -> layer.name }, "the file's layer order") + assertEquals(listOf("EyeL", "EyeCopy"), imageA.layers[0].drawableIds, "both drawables over the tile") + assertEquals("Head/Eyes", imageA.layers[0].groupPath) + assertNull(imageA.layers[2].placement, "the guide is unpacked") + assertNull(inputs[1].path) + assertNull(inputs[1].lastModified) + + val withoutWing = Cmo3SourceLayerWeb.inputsOf(puppet) { tileId -> if (tileId == tileWing.id) null else rasters[tileId] } + assertEquals(listOf("a.psd"), withoutWing.map { image -> image.name }, "a tile with no raster leaves its file out when it was the only one") + } + + @Test + fun theWebWritesRealLayersFoldersEntriesAndBindingsAndReadsBack() { + val skeleton = Cmo3SkeletonBuilder.buildBlank("Layer Test", 100, 100, RuntimeTarget.Cubism53.cmo3TargetVersionNo()) + val chain = + Cmo3ImageChainBuilder.populate( + skeleton.root, + listOf(page), + listOf(emptyList()), + nowMillis = now, + fromSourceLayers = true, + sourceImages = Cmo3SourceLayerWeb.inputsOf(puppet) { tileId -> rasters[tileId] }, + ) + assertEquals(0, chain.cropDrawableCount, "nothing took the crop path") + val textureManager = skeleton.root.textureManager as CTextureManager + val images = Cmo3Import.elementsOf(textureManager._rawImages).filterIsInstance().map { wrapper -> wrapper.image as CLayeredImage } + assertEquals(listOf("a.psd", "b.clip"), images.map { image -> image.name }, "one layered image per file, no stand-in") + val imageA = images[0] + assertEquals("/art/a.psd", (imageA.psdFile as FileRef).textPath) + assertEquals(123L, imageA.psdFileLastModified) + assertEquals(100 to 100, imageA.width to imageA.height) + assertEquals("b.clip", (images[1].psdFile as FileRef).textPath, "a record with no path writes its name") + assertEquals(now, images[1].psdFileLastModified, "a record with no time writes now") + + // The folder tree: Head/Eyes holds the eye, the rest sits at the root, in file order. + val rootA = imageA._rootLayer as CLayerGroup + assertEquals(listOf("Head", "Hair", "Guide"), names(rootA._children)) + val head = Cmo3Import.elementsOf(rootA._children).filterIsInstance().single() + val eyes = Cmo3Import.elementsOf(head._children).filterIsInstance().single() + assertEquals("Eyes", eyes.name) + assertEquals(listOf("Eye"), names(eyes._children)) + assertEquals(listOf("root", "Head", "Eyes", "Eye", "Hair", "Guide"), names(imageA.layerSet?.let { set -> (set as org.umamo.format.cmo3.model.gen.LayerSet)._layerEntryList }), "the flat set lists groups and layers in walk order") + + // Each layer's rect is the art frame at the row's origin; the identifier carries the lyid. + val eye = Cmo3Import.elementsOf(eyes._children).filterIsInstance().single() + val eyeBounds = eye.boundsOnImageDoc as CRect + assertEquals(listOf(10, 20, 4, 4), listOf(eyeBounds.x, eyeBounds.y, eyeBounds.width, eyeBounds.height)) + val eyeIdentifier = eye.layerIdentifier as CLayerIdentifier + assertEquals("00-00-06-28", eyeIdentifier.layerId, "1576 as four hex bytes") + assertEquals(1576, eyeIdentifier.layerIdValue_testImpl) + assertEquals("Eye", eyeIdentifier.layerName) + val wing = Cmo3Import.elementsOf((images[1]._rootLayer as CLayerGroup)._children).filterIsInstance().single() + val wingIdentifier = wing.layerIdentifier as CLayerIdentifier + assertNull(wingIdentifier.layerId, "a uuid key has no Photoshop id to write") + assertEquals(-1, wingIdentifier.layerIdValue_testImpl) + + // One model image per layer at a pure translation; one group per file. + val groups = Cmo3Import.elementsOf(textureManager._modelImageGroups).filterIsInstance() + assertEquals(listOf("a.psd", "b.clip"), groups.map { group -> group.groupName }) + val imagesA = Cmo3Import.elementsOf(groups[0]._modelImages).filterIsInstance() + assertEquals(listOf("Eye", "Hair", "Guide"), imagesA.map { modelImage -> modelImage.name as String }) + val eyePlacement = imagesA[0]._materialLocalToCanvasTransform as CAffine + assertEquals(listOf(1f, 0f, 10f, 0f, 1f, 20f), listOf(eyePlacement.m00, eyePlacement.m01, eyePlacement.m02, eyePlacement.m10, eyePlacement.m11, eyePlacement.m12)) + + // Entries for the placed tiles only, off their placements; the guide has none. + val atlas = Cmo3Import.elementsOf(textureManager._textureAtlases).filterIsInstance().single() + val entries = Cmo3Import.elementsOf(atlas.modelImages).filterIsInstance() + assertEquals(3, entries.size, "eye, hair, wing") + val eyeEntry = assertNotNull(entries.firstOrNull { entry -> entry.modelImageGuid == imagesA[0].guid }, "the eye has an entry") + val eyePacking = eyeEntry.materialLocalToAtlasTransform as GTransform2 + assertEquals(2f to 2f, (eyePacking.position as GVector2).let { position -> position.x to position.y }) + assertEquals(0f, eyePacking.eulerAngle) + val eyeAtlasToCanvas = eyeEntry.atlasLocalToCanvasTransform as CAffine + assertEquals(8f, eyeAtlasToCanvas.m02, 1e-5f, "translate(10, 20) composed with the placement's inverse") + assertEquals(18f, eyeAtlasToCanvas.m12, 1e-5f) + val hairEntry = assertNotNull(entries.firstOrNull { entry -> entry.modelImageGuid == imagesA[1].guid }, "the hair has an entry") + assertEquals(-90f, (hairEntry.materialLocalToAtlasTransform as GTransform2).eulerAngle, "the quarter turn rides the entry") + assertTrue(entries.none { entry -> entry.modelImageGuid == imagesA[2].guid }, "an unpacked tile has no entry") + + // Bindings: both drawables over the eye share its model image and the entry's transform. + val eyeL = chain.bindingByDrawableId.getValue("EyeL") + val eyeCopy = chain.bindingByDrawableId.getValue("EyeCopy") + assertEquals(imagesA[0].guid, eyeL.modelImageGuid, "the eye binding names the eye's model image") + assertEquals(eyeL.modelImageGuid, eyeCopy.modelImageGuid, "the duplicate shares it") + assertEquals(8f, eyeL.inputImageLocalToCanvasTransform.m02, 1e-5f) + assertEquals(8f, eyeCopy.inputImageLocalToCanvasTransform.m02, 1e-5f) + assertTrue("Hair" in chain.bindingByDrawableId && "Wing" in chain.bindingByDrawableId) + assertNull(chain.bindingByDrawableId["Guide"], "an unpacked tile's drawable gets no binding") + + // The layer PNG is the tile's raster. + val eyeResource = eye.imageResource as org.umamo.format.cmo3.model.custom.CImageResource + val eyeEntryBytes = assertNotNull(chain.pngEntries.firstOrNull { entry -> entry.path == eyeResource.imageFileBuf?.archivePath }, "the eye layer's PNG is an entry").pngBytes + assertContentEquals(gradient(1).rgba, PngCodec.read(eyeEntryBytes).rgba) + + // The icons: the layer's and the model image's fit the whole raster; each drawable's fits the + // patch its mesh covers (the whole tile here), one entry per drawable. + fun iconPixels(icon: Any?): RasterImage { + val path = assertNotNull(Cmo3Icons.archivePathOf(icon), "the icon names an entry") + return PngCodec.read(assertNotNull(chain.pngEntries.firstOrNull { entry -> entry.path == path }, "icon entry '$path' was collected").pngBytes) + } + assertContentEquals(gradient(1).fittedInto(64).rgba, iconPixels(eye.icon64).rgba, "the eye's 64px icon is the fitted raster") + assertContentEquals(gradient(1).fittedInto(16).rgba, iconPixels(eye.icon16).rgba, "and its 16px icon") + assertContentEquals(gradient(1).fittedInto(16).rgba, iconPixels(imagesA[0].icon16).rgba, "the model image's icon too") + assertContentEquals(gradient(1).fittedInto(32).rgba, iconPixels(eyeL.icon32).rgba, "the drawable's icon shows its patch") + assertContentEquals(gradient(1).fittedInto(16).rgba, iconPixels(eyeL.icon16).rgba) + assertNotEquals(Cmo3Icons.archivePathOf(eyeL.icon32), Cmo3Icons.archivePathOf(eyeCopy.icon32), "the duplicate has an icon of its own") + + // Through the codec, the reconcile, and back: the ingest reads the same web, the layered-art + // reader the same pixels, the import the same uvs. + val model = + Cmo3.read( + Cmo3FreshFile.assemble( + skeleton.root, + skeleton.iconEntries.map { icon -> Cmo3FreshFile.PngEntry(icon.path, icon.pngBytes) } + chain.pngEntries, + obfuscateKey = 0x1234ABCD, + ), + ) + val report = Cmo3Export.apply(puppet, model, chain.bindingByDrawableId) + assertTrue(report.notices.all { notice -> notice is ExportNotice.UnsupportedChange && notice.subject == "Guide" }, "only the unpacked guide is reported: ${report.notices}") + val reread = Cmo3.read(Cmo3.write(model)) + val rereadRoot = reread.root as CModelSource + val ingest = cmo3AtlasIngest(rereadRoot) + val rereadA = assertNotNull(ingest.sources.firstOrNull { source -> source.name == "a.psd" }, "a.psd reads back: ${ingest.sources.map { source -> source.name }}") + assertEquals("/art/a.psd", rereadA.path) + assertEquals(123L, rereadA.lastModified) + assertEquals(listOf("lyid:1576", "lyid:5", "lyid:9"), rereadA.layers.map { layer -> layer.key }) + assertEquals(listOf("Head/Eyes", "", ""), rereadA.layers.map { layer -> layer.groupPath }) + assertEquals(listOf(10, 20, 4, 4), rereadA.layers[0].let { layer -> listOf(layer.left, layer.top, layer.width, layer.height) }) + val rereadB = assertNotNull(ingest.sources.firstOrNull { source -> source.name == "b.clip" }, "b.clip reads back") + assertEquals(listOf("name:Wing"), rereadB.layers.map { layer -> layer.key }, "a uuid key reopens as a name key") + val tileByKey = ingest.atlas.tiles.associateBy { tile -> tile.source?.layerKey } + assertEquals(AtlasPlacement(0, 2f, 2f, 1f, 1f, 0f), tileByKey.getValue("lyid:1576").placement) + assertEquals(-90f, assertNotNull(tileByKey.getValue("lyid:5").placement).rotationDegrees) + assertNull(tileByKey.getValue("lyid:9").placement) + assertEquals(AtlasPlacement(0, 2f, 8f, 1f, 1f, 0f), tileByKey.getValue("name:Wing").placement) + assertEquals(4 to 4, tileByKey.getValue("lyid:1576").let { tile -> tile.width to tile.height }) + assertEquals(ingest.tileIdByDrawableId["EyeL"], ingest.tileIdByDrawableId["EyeCopy"], "the duplicates share their tile") + val rereadArt = assertNotNull(cmo3SourceArtOf(rereadRoot, rereadA.id) { resource -> reread.extractLayerPng(resource) }) + val rereadEye = assertNotNull(rereadArt.layers.firstOrNull { layer -> layer.id.raw == "lyid:1576" }, "the eye reads back as a source layer: ${rereadArt.layers.map { layer -> layer.id.raw }}") + assertContentEquals(gradient(1).rgba, rereadEye.raster.rgba, "the eye's pixels read back") + // Every written drawable carries its icons through the codec, at distinct entries. + val rereadMeshes = Cmo3Import.elementsOf((rereadRoot.drawableSourceSet as CDrawableSourceSet)._sources).filterIsInstance() + val rereadIconPaths = ArrayList() + for (mesh in rereadMeshes) { + for ((icon, size) in listOf(mesh.icon32 to 32, mesh.icon16 to 16)) { + val path = assertNotNull(Cmo3Icons.archivePathOf(icon), "${Cmo3Import.idStrOf(mesh.id)} has a ${size}px icon") + val decoded = PngCodec.read(assertNotNull(reread.archive.byPath(path), "icon '$path' is embedded").content) + assertEquals(size to size, decoded.width to decoded.height) + rereadIconPaths.add(path) + } + } + assertEquals(rereadIconPaths.size, rereadIconPaths.toSet().size, "one icon entry per drawable and size") + val reimported = Cmo3Import.fromModelSource(rereadRoot) + for (drawable in puppet.drawables) { + if (drawable.id.raw == "Guide") { + // An unpacked tile's drawable has no texture to bind and is reported rather than written, + // as in the crop path; the unpacked-drawable input shape is the follow-up. + assertNull(reimported.drawables.firstOrNull { candidate -> candidate.id == drawable.id }, "the unpacked guide is reported, not written") + continue + } + val back = assertNotNull(reimported.drawables.firstOrNull { candidate -> candidate.id == drawable.id }, "${drawable.name} re-imports") + assertContentEquals(drawable.mesh?.uvs, back.mesh?.uvs, "${drawable.name} uvs are verbatim") + } + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceModeAtlasTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceModeAtlasTest.kt new file mode 100644 index 0000000..4c28750 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3SourceModeAtlasTest.kt @@ -0,0 +1,162 @@ +package org.umamo.interop.cmo3 + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.storedToArtAffineForTile +import java.io.File +import kotlin.math.abs +import kotlin.math.floor +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * A model saved in source-layer display is read onto the atlas pages the file carries. + * + * The editor keeps a model's atlas whichever display it was saved in; saved in source-layer display, its + * drawables' textures name model images instead, and nothing a drawable samples names the page. Umamo + * still reads every placed tile's drawable onto that page, so its atlas display is the editor's atlas. + * For every such corpus save: the coordinates address pages, every placed drawable is shown from its + * tile's page image byte for byte, and the page at a drawable's coordinates shows what its tile's raster + * shows at the same point through the placement - the atlas display and the source display agree. + * + * Gated on `cmo3.probe`; skips by assumption when no corpus save is of this shape. + */ +class Cmo3SourceModeAtlasTest { + private companion object { + /** The least raster alpha a sample needs to count. */ + const val OPAQUE_ALPHA = 200 + + /** The largest per-channel difference the page's (often scaled) copy of the art may show. */ + const val CHANNEL_TOLERANCE = 60 + + /** The share of one model's samples on which the page and the raster may disagree. */ + const val MAXIMUM_MISMATCH_FRACTION = 0.03f + + /** Barycentric sample points per triangle: the centroid and one point near each corner. */ + val SAMPLE_WEIGHTS: List = + listOf( + floatArrayOf(1f / 3f, 1f / 3f, 1f / 3f), + floatArrayOf(0.6f, 0.2f, 0.2f), + floatArrayOf(0.2f, 0.6f, 0.2f), + floatArrayOf(0.2f, 0.2f, 0.6f), + ) + } + + /** + * The texel nearest a texture coordinate, or null outside the image. + * + * @param RasterImage image The image. + * @param Float u The horizontal coordinate, 0 at the left edge. + * @param Float v The vertical coordinate, 0 at the top row. + * @return IntArray? The RGBA channels, 0 to 255. + */ + private fun texelAt(image: RasterImage, u: Float, v: Float): IntArray? { + val column = floor(u * image.width).toInt() + val row = floor(v * image.height).toInt() + if (column < 0 || row < 0 || column >= image.width || row >= image.height) { + return null + } + val offset = (row * image.width + column) * 4 + return IntArray(4) { channelIndex -> image.rgba[offset + channelIndex].toInt() and 0xFF } + } + + @Test + fun aSourceModeSaveIsReadOntoTheAtlasPagesItCarries() { + val files = + (System.getProperty("cmo3.probe") ?: "").split(',').map { path -> path.trim() }.filter { path -> path.isNotEmpty() }.map(::File).filter { file -> file.isFile } + Assume.assumeTrue("[source-mode] no cmo3.probe", files.isNotEmpty()) + + var checkedFiles = 0 + val failures = ArrayList() + for (file in files) { + val cmo3 = Cmo3.read(file) + val root = cmo3.root as? CModelSource ?: continue + val textureManager = root.textureManager as? CTextureManager ?: continue + // CMO3: CTextureManager field _textureAtlases -> CTextureAtlas field cachedAtlasImage. + val pageResources = Cmo3Import.elementsOf(textureManager._textureAtlases).filterIsInstance().map { atlas -> atlas.cachedAtlasImage as? CImageResource } + val imported = Cmo3Import.importModelSource(root) + val puppet = imported.puppet + val sourceById = + Cmo3Import.elementsOf((root.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + .mapNotNull { source -> (source.id as? Id)?.idstr?.let { idStr -> idStr to source } }.toMap() + // Placed drawables whose file texture names no page: what a source-layer save is made of. + val sourceModeDrawables = + puppet.drawables.filter { drawable -> + val placed = drawable.atlasTileId?.let { tileId -> puppet.atlas.tileById[tileId]?.placement } != null + val sampled = (sourceById[drawable.id.raw]?.texture as? GTexture2D)?.srcImageResource + placed && pageResources.none { page -> page === sampled } + } + if (sourceModeDrawables.isEmpty()) { + continue + } + checkedFiles++ + if (!puppet.atlas.storedUvsAddressPages) { + failures.add("${file.name}: its coordinates do not address its pages") + } + val renderPages = cmo3AtlasPages(root, cmo3::extractLayerPng) + val decodedRenderPages = HashMap() + val decodedTiles = HashMap() + var samples = 0 + var mismatches = 0 + for (drawable in sourceModeDrawables) { + val tileId = drawable.atlasTileId!! + val placement = puppet.atlas.tileById.getValue(tileId).placement!! + val renderPageIndex = renderPages.atlasIndexByDrawableId[drawable.id.raw] + val pagePng = pageResources.getOrNull(placement.pageIndex)?.let(cmo3::extractLayerPng) + if (renderPageIndex == null || pagePng == null || !renderPages.pageBytes[renderPageIndex].contentEquals(pagePng)) { + failures.add("${file.name} ${drawable.id.raw}: not shown from its tile's page image") + continue + } + val page = decodedRenderPages.getOrPut(renderPageIndex) { PngCodec.read(renderPages.pageBytes[renderPageIndex]) } + val raster = decodedTiles.getOrPut(tileId) { imported.atlasIngest.imageResourceByTile[tileId]?.let(cmo3::extractLayerPng)?.let(PngCodec::read) } ?: continue + val storedToArt = puppet.atlas.storedToArtAffineForTile(tileId) ?: continue + val mesh = drawable.mesh ?: continue + var triangleStart = 0 + while (triangleStart + 2 < mesh.indices.size) { + for (weights in SAMPLE_WEIGHTS) { + var modelU = 0f + var modelV = 0f + for (cornerIndex in 0 until 3) { + val vertex = mesh.indices[triangleStart + cornerIndex] + modelU += weights[cornerIndex] * mesh.uvs[vertex * 2] + modelV += weights[cornerIndex] * mesh.uvs[vertex * 2 + 1] + } + val artU = storedToArt[0] * modelU + storedToArt[1] * modelV + storedToArt[2] + val artV = storedToArt[3] * modelU + storedToArt[4] * modelV + storedToArt[5] + val rasterTexel = texelAt(raster, artU, artV) ?: continue + if (rasterTexel[3] < OPAQUE_ALPHA) { + continue + } + samples++ + val pageTexel = texelAt(page, modelU, modelV) + if (pageTexel == null || (0 until 4).any { channelIndex -> abs(pageTexel[channelIndex] - rasterTexel[channelIndex]) > CHANNEL_TOLERANCE }) { + mismatches++ + } + } + triangleStart += 3 + } + } + val mismatchFraction = if (samples == 0) 0f else mismatches.toFloat() / samples + println("[source-mode] ${file.name}: ${sourceModeDrawables.size} placed drawables off their page in the file, ${renderPages.pageBytes.size} render page(s), $mismatches of $samples samples disagree ($mismatchFraction)") + if (samples == 0) { + failures.add("${file.name}: no opaque sample compared") + } + if (mismatchFraction > MAXIMUM_MISMATCH_FRACTION) { + failures.add("${file.name}: the page and the rasters disagree on $mismatchFraction of samples") + } + } + Assume.assumeTrue("[source-mode] no cmo3.probe model was saved in source-layer display", checkedFiles > 0) + assertTrue(failures.isEmpty(), "source-mode saves are not read onto their pages:\n" + failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3TextureFrameOracleTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3TextureFrameOracleTest.kt new file mode 100644 index 0000000..edd8c37 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3TextureFrameOracleTest.kt @@ -0,0 +1,321 @@ +package org.umamo.interop.cmo3 + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CImageResource +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CCachedImage +import org.umamo.format.cmo3.model.gen.CCachedImageManager +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.moc3.Moc3 +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.interop.moc3.import.moc3AtlasPages +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.storedToArtAffineForTile +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Every CMO3 drawable's texture mapping, checked against the Cubism Editor's own MOC3 export of the same + * model: its atlas sampled at its own coordinates is what the drawable really shows, so it is ground truth + * for both of Umamo's displays and owes nothing to Umamo's reading of the CMO3. + * + * The atlas display is the document's render image sampled at the model's coordinates; the source display + * is the tile's raster sampled through the tile's stored-to-art mapping. Both must show the art the MOC3 + * shows at the same point of the same mesh. A drawable whose texture is the editor's reduced cache copy + * of its model image is the class this exists for: its stored coordinates address the padded copy, not + * the model image's own raster, so a reading that confuses the two draws the art squeezed and cut off. + * + * Pairs `cmo3/.cmo3` from `cmo3.probe` with `moc3//.moc3` under `moc3.samples`; skips by + * assumption when no pair exists, so an unfed run reports skipped rather than green. + */ +class Cmo3TextureFrameOracleTest { + private companion object { + /** The share of one model's samples a display may miss: edge texels land differently at the two resolutions. */ + const val MAXIMUM_MISMATCH_FRACTION = 0.03f + + /** The least MOC3 alpha a sample needs to count: a translucent edge texel says nothing about placement. */ + const val OPAQUE_ALPHA = 200 + + /** The largest per-channel difference two texels of the same art may show across resampling. */ + const val CHANNEL_TOLERANCE = 60 + + /** Barycentric sample points per triangle: the centroid and one point near each corner. */ + val SAMPLE_WEIGHTS: List = + listOf( + floatArrayOf(1f / 3f, 1f / 3f, 1f / 3f), + floatArrayOf(0.6f, 0.2f, 0.2f), + floatArrayOf(0.2f, 0.6f, 0.2f), + floatArrayOf(0.2f, 0.2f, 0.6f), + ) + } + + /** + * One model's tally. + * + * @property String name The CMO3's file name. + */ + private class ModelTally(val name: String) { + var drawables = 0 + var reducedCopyDrawables = 0 + var reducedCopySamples = 0 + var samples = 0 + var atlasMismatches = 0 + var sourceMismatches = 0 + var renderImageBytes = 0L + val worstSourceDrawables = ArrayList() + } + + /** + * Flattens a CMO3 collection field (held as `Any?`) to a plain list. + * + * @param Any? collection The raw field. + * @return List The elements, empty for any other shape. + */ + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + /** + * The CMO3/MOC3 pairs the corpus holds. + * + * @return List> Each CMO3 with its MOC3 twin. + */ + private fun corpusPairs(): List> { + val mocDirectory = System.getProperty("moc3.samples")?.let(::File)?.takeIf { directory -> directory.isDirectory } ?: return emptyList() + return (System.getProperty("cmo3.probe") ?: "") + .split(',') + .map { path -> path.trim() } + .filter { path -> path.isNotEmpty() } + .map(::File) + .filter { file -> file.isFile } + .mapNotNull { cmo3File -> + val stem = cmo3File.nameWithoutExtension + File(File(mocDirectory, stem), "$stem.moc3").takeIf { file -> file.isFile }?.let { mocFile -> cmo3File to mocFile } + } + } + + /** + * The resources that are a model image's reduced cache copy rather than its raster or an atlas page - + * worked out here from the file alone, so the oracle's own classification owes nothing to the import. + * + * @param CModelSource root The CMO3's model source. + * @return Set The copies, compared by identity. + */ + private fun reducedCopiesOf(root: CModelSource): Set { + val textureManager = root.textureManager as? CTextureManager ?: return emptySet() + val pages = elements(textureManager._textureAtlases).filterIsInstance().mapNotNull { atlas -> atlas.cachedAtlasImage as? CImageResource }.toHashSet() + val copies = HashSet() + for (group in elements(textureManager._modelImageGroups).filterIsInstance()) { + for (modelImage in elements(group._modelImages).filterIsInstance()) { + val raster = modelImage._filteredImage as? CImageResource + val manager = modelImage.cachedImageManager as? CCachedImageManager ?: continue + for (cached in elements(manager.cachedImages).filterIsInstance()) { + val resource = cached._cachedImageResource as? CImageResource ?: continue + if (resource !== raster && resource !in pages) { + copies.add(resource) + } + } + } + } + return copies + } + + /** + * The texel nearest a texture coordinate, or null outside the image. + * + * @param RasterImage image The image. + * @param Float u The horizontal coordinate, 0 at the left edge. + * @param Float v The vertical coordinate, 0 at the top row. + * @return IntArray? The RGBA channels, 0 to 255. + */ + private fun texelAt(image: RasterImage, u: Float, v: Float): IntArray? { + if (!u.isFinite() || !v.isFinite()) { + return null + } + val column = kotlin.math.floor(u * image.width).toInt() + val row = kotlin.math.floor(v * image.height).toInt() + if (column < 0 || row < 0 || column >= image.width || row >= image.height) { + return null + } + val offset = (row * image.width + column) * 4 + return IntArray(4) { channelIndex -> image.rgba[offset + channelIndex].toInt() and 0xFF } + } + + /** + * Whether a displayed texel shows the art the reference texel shows. + * + * @param IntArray reference The MOC3 texel. + * @param IntArray? displayed The texel a display samples, or null when it samples outside its image. + * @return Boolean True when every channel is within [CHANNEL_TOLERANCE]. + */ + private fun matches(reference: IntArray, displayed: IntArray?): Boolean = + displayed != null && (0 until 4).all { channelIndex -> abs(reference[channelIndex] - displayed[channelIndex]) <= CHANNEL_TOLERANCE } + + /** + * Measures one CMO3 against its MOC3 twin. + * + * @param File cmo3File The CMO3. + * @param File mocFile Its MOC3 twin, beside its model3.json and texture files. + * @return ModelTally? The tally, or null when the MOC3 family on disk is incomplete. + */ + private fun measure(cmo3File: File, mocFile: File): ModelTally? { + val manifestFile = File(mocFile.parentFile, "${Moc3Sidecars.basenameFor(mocFile.name)}.model3.json") + if (!manifestFile.isFile) { + println("[texture-frame] ${cmo3File.name}: no ${manifestFile.name} beside its MOC3; skipped") + return null + } + val manifest = Moc3.readModel3(manifestFile.readText()) + // model3: FileReferences.Textures - the page paths, relative to the manifest. + val mocPageFiles = manifest.fileReferences.textures.map { path -> File(manifestFile.parentFile, path) } + if (mocPageFiles.isEmpty() || mocPageFiles.any { file -> !file.isFile }) { + println("[texture-frame] ${cmo3File.name}: its MOC3's texture files are not all on disk; skipped") + return null + } + val tally = ModelTally(cmo3File.name) + val cmo3: Cmo3Model = Cmo3.read(cmo3File) + val root = cmo3.root as CModelSource + val imported = Cmo3Import.importModelSource(root) + val puppet: PuppetModel = imported.puppet + val renderPages = cmo3AtlasPages(root, cmo3::extractLayerPng) + val decodedRenderPages = HashMap() + val decodedTiles = HashMap() + val reducedCopies = reducedCopiesOf(root) + val sampledResourceByDrawableId = + elements((root.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + .mapNotNull { source -> + val drawableId = (source.id as? Id)?.idstr ?: return@mapNotNull null + val resource = (source.texture as? GTexture2D)?.srcImageResource as? CImageResource ?: return@mapNotNull null + drawableId to resource + }.toMap() + + val mocDocument = Moc3.read(mocFile.readBytes()) + val mocPages = moc3AtlasPages(mocDocument, mocPageFiles.map { file -> file.readBytes() }) + val decodedMocPages = HashMap() + val mocMeshById = Moc3Import.fromMocDocument(mocDocument, null).drawables.associate { drawable -> drawable.id.raw to drawable.mesh } + + for (drawable in puppet.drawables) { + val mesh = drawable.mesh ?: continue + val mocMesh = mocMeshById[drawable.id.raw] ?: continue + if (mocMesh.uvs.size != mesh.uvs.size || mesh.indices.isEmpty()) { + continue + } + val mocPageIndex = mocPages.atlasIndexByDrawableId[drawable.id.raw] ?: continue + val mocPage = decodedMocPages.getOrPut(mocPageIndex) { PngCodec.read(mocPages.pageBytes[mocPageIndex]) } + val renderPage = + renderPages.atlasIndexByDrawableId[drawable.id.raw]?.let { pageIndex -> + decodedRenderPages.getOrPut(pageIndex) { PngCodec.read(renderPages.pageBytes[pageIndex]) } + } + val tileId = drawable.atlasTileId + val tile = + tileId?.let { id -> + decodedTiles.getOrPut(id) { imported.atlasIngest.imageResourceByTile[id]?.let(cmo3::extractLayerPng)?.let(PngCodec::read) } + } + val storedToArt = tileId?.let { id -> puppet.atlas.storedToArtAffineForTile(id) } + val reducedCopy = sampledResourceByDrawableId[drawable.id.raw]?.let { resource -> resource in reducedCopies } == true + tally.drawables++ + if (reducedCopy) { + tally.reducedCopyDrawables++ + } + var drawableSamples = 0 + var drawableSourceMismatches = 0 + var triangleStart = 0 + while (triangleStart + 2 < mesh.indices.size) { + for (weights in SAMPLE_WEIGHTS) { + var mocU = 0f + var mocV = 0f + var modelU = 0f + var modelV = 0f + for (cornerIndex in 0 until 3) { + val vertex = mesh.indices[triangleStart + cornerIndex] + mocU += weights[cornerIndex] * mocMesh.uvs[vertex * 2] + mocV += weights[cornerIndex] * mocMesh.uvs[vertex * 2 + 1] + modelU += weights[cornerIndex] * mesh.uvs[vertex * 2] + modelV += weights[cornerIndex] * mesh.uvs[vertex * 2 + 1] + } + val reference = texelAt(mocPage, mocU, mocV) ?: continue + if (reference[3] < OPAQUE_ALPHA) { + continue + } + tally.samples++ + drawableSamples++ + if (reducedCopy) { + tally.reducedCopySamples++ + } + if (renderPage != null && !matches(reference, texelAt(renderPage, modelU, modelV))) { + tally.atlasMismatches++ + } + if (tile != null && storedToArt != null) { + val artU = storedToArt[0] * modelU + storedToArt[1] * modelV + storedToArt[2] + val artV = storedToArt[3] * modelU + storedToArt[4] * modelV + storedToArt[5] + if (!matches(reference, texelAt(tile, artU, artV))) { + tally.sourceMismatches++ + drawableSourceMismatches++ + } + } + } + triangleStart += 3 + } + if (drawableSamples > 0 && drawableSourceMismatches * 5 > drawableSamples && tally.worstSourceDrawables.size < 5) { + tally.worstSourceDrawables.add("${drawable.id.raw} '${drawable.name}' $drawableSourceMismatches/$drawableSamples") + } + } + tally.renderImageBytes = decodedRenderPages.values.sumOf { page -> page.width.toLong() * page.height.toLong() * 4L } + return tally + } + + /** + * Both displays of every paired corpus model show the art Cubism's own export shows. + */ + @Test + fun bothDisplaysMatchTheEditorsOwnExport() { + val pairs = corpusPairs() + Assume.assumeTrue("[texture-frame] no cmo3.probe / moc3.samples pair", pairs.isNotEmpty()) + + val failures = ArrayList() + var checkedSamples = 0 + var reducedCopyDrawables = 0 + var reducedCopySamples = 0 + for ((cmo3File, mocFile) in pairs) { + val tally = measure(cmo3File, mocFile) ?: continue + checkedSamples += tally.samples + reducedCopyDrawables += tally.reducedCopyDrawables + reducedCopySamples += tally.reducedCopySamples + val atlasFraction = if (tally.samples == 0) 0f else tally.atlasMismatches.toFloat() / tally.samples + val sourceFraction = if (tally.samples == 0) 0f else tally.sourceMismatches.toFloat() / tally.samples + println( + "[texture-frame] ${tally.name}: ${tally.drawables} drawables (${tally.reducedCopyDrawables} over a reduced copy), " + + "${tally.samples} samples, atlas display $atlasFraction, source display $sourceFraction mismatched, " + + "render images ${tally.renderImageBytes / (1024 * 1024)} MiB decoded", + ) + if (atlasFraction > MAXIMUM_MISMATCH_FRACTION) { + failures.add("${tally.name}: the atlas display misses $atlasFraction of the export's samples") + } + if (sourceFraction > MAXIMUM_MISMATCH_FRACTION) { + failures.add("${tally.name}: the source display misses $sourceFraction of the export's samples; worst ${tally.worstSourceDrawables}") + } + } + assertTrue(checkedSamples > 0, "no opaque sample was compared; the oracle checked nothing") + assertTrue(reducedCopyDrawables == 0 || reducedCopySamples > 0, "reduced-copy drawables were paired but none was sampled") + assertTrue(failures.isEmpty(), "displays disagree with the editor's own export:\n" + failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3UnkeyedDrawableExportTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3UnkeyedDrawableExportTest.kt new file mode 100644 index 0000000..e25a37c --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/Cmo3UnkeyedDrawableExportTest.kt @@ -0,0 +1,85 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshForm +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.KeyformGridSource +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * An UNKEYED drawable - no geometry grid, no channel track, the state every drawable born from an + * artwork import is in - exports to a CMO3 the official editor can open. + * + * The editor requires a keyform grid with its default form on every source: setKeyformGridSource + * rejects null and getDefaultKeyForm throws "no KeyForms" on an empty pool, and a model with either + * floods the log and crashes on open. So the written art mesh must carry an axis-less grid with one + * cell and one form holding the base mesh, and the file must re-import to the same drawable. Pinned + * here on a synthetic puppet, so the rule cannot rot behind corpus models whose meshes are all keyed. + */ +class Cmo3UnkeyedDrawableExportTest { + private val base = floatArrayOf(1f, 1f, 7f, 1f, 7f, 7f, 1f, 7f) + + private fun unkeyedPuppet(): PuppetModel { + val drawable = + Drawable( + id = DrawableId("ArtMesh1"), + name = "Eye", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(base.copyOf(), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)), + geometryGrid = null, + ) + return PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + canvasWidth = 8f, + canvasHeight = 8f, + ) + } + + @Test + fun anUnkeyedDrawableWritesADefaultCellAndReimports() { + val page = PngCodec.write(RasterImage(8, 8, ByteArray(8 * 8 * 4) { index -> if (index % 4 == 3) 0xFF.toByte() else 0x40 })) + val result = + Cmo3Conversion.freshCmo3( + puppet = unkeyedPuppet(), + pages = listOf(Cmo3Conversion.AtlasPage(page, 8, 8)), + pageIndexByDrawableId = mapOf("ArtMesh1" to 0), + modelName = "unkeyed", + nowMillis = 0L, + obfuscateKey = 0, + ) + + val root = result.model.root as CModelSource + val artMesh = + Cmo3Import.elementsOf((root.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance().single() + val gridSource = assertNotNull(artMesh.keyformGridSource as? KeyformGridSource, "the mesh keeps a keyform grid") + assertTrue(Cmo3Import.elementsOf(gridSource.keyformBindings).isEmpty(), "an unkeyed mesh binds no parameter") + assertEquals(1, Cmo3Import.elementsOf(gridSource.keyformsOnGrid).size, "one default cell") + val form = Cmo3Import.elementsOf(artMesh.keyforms).filterIsInstance().single() + assertTrue(base.contentEquals(form.positions as? FloatArray), "the default form holds the base mesh: ${(form.positions as? FloatArray)?.toList()}") + + val reimported = Cmo3Import.fromModelSource(Cmo3.read(Cmo3.write(result.model)).root as CModelSource) + val reread = reimported.drawables.single { drawable -> drawable.id == DrawableId("ArtMesh1") } + assertEquals("Eye", reread.name) + assertTrue(base.contentEquals(assertNotNull(reread.mesh).positions), "the base comes back as written") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/RuntimeTargetIngestTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/RuntimeTargetIngestTest.kt new file mode 100644 index 0000000..ac2fbe7 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/cmo3/RuntimeTargetIngestTest.kt @@ -0,0 +1,71 @@ +package org.umamo.interop.cmo3 + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.unsupportedFeaturesInUse +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Corpus-gated ingest of the authored runtime target, and the strip diff against a document that + * deliberately exceeds its own target. Skips (with a note) when the probe property is absent. + */ +class RuntimeTargetIngestTest { + private val probeFilesByName: Map = + System.getProperty("cmo3.probe") + ?.split(",") + ?.map(::File) + ?.filter { it.isFile } + ?.associateBy { it.name } + .orEmpty() + + private fun importByName(fileName: String): PuppetModel? { + val file = probeFilesByName[fileName] ?: return null + val root = Cmo3.read(file).root as? CModelSource ?: error("$fileName root is not a CModelSource") + return Cmo3Import.fromModelSource(root) + } + + @Test + fun authoredTargetLandsOnThePuppetModel() { + val puppet = + importByName("EricaTamamo.cmo3") ?: run { + println("cmo3.probe has no EricaTamamo.cmo3; skipping runtime-target ingest test") + return + } + // CMO3: CModelSource field targetVersionNo - EricaTamamo was authored targeting SDK 4.0. + assertEquals(RuntimeTarget.Cubism40, puppet.runtimeTarget) + } + + @Test + fun latestSentinelIngestsAsNoTarget() { + val puppet = + importByName("ModelWithoutOffscreenSDKNA.cmo3") ?: run { + println("cmo3.probe has no ModelWithoutOffscreenSDKNA.cmo3; skipping sentinel ingest test") + return + } + // CMO3: CModelSource field targetVersionNo - the SDK(N/A)/Latest selection restricts nothing. + assertEquals(RuntimeTarget.NoTarget, puppet.runtimeTarget) + } + + @Test + fun overreachingDocumentReportsItsStripDiff() { + // ModelWithOffscreenSDK3.3 was saved by the official editor with offscreen drawing enabled + // BEFORE the target was switched to SDK 3.3 - the editor keeps the out-of-target data in the + // file, the exact never-break behavior Umamo mirrors. Its ingest must land on Cubism33 and + // the strip diff against that target must flag the offscreen use. + val puppet = + importByName("ModelWithOffscreenSDK3.3.cmo3") ?: run { + println("cmo3.probe has no ModelWithOffscreenSDK3.3.cmo3; skipping strip-diff corpus test") + return + } + assertEquals(RuntimeTarget.Cubism33, puppet.runtimeTarget) + val stripDiff = puppet.unsupportedFeaturesInUse(RuntimeTarget.Cubism33) + assertTrue(RuntimeFeature.PartComposite in stripDiff, "offscreen use is flagged, got $stripDiff") + assertEquals(emptySet(), puppet.unsupportedFeaturesInUse(RuntimeTarget.NoTarget), "NoTarget strips nothing") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3DowngradeContentTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3DowngradeContentTest.kt new file mode 100644 index 0000000..34fce2d --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3DowngradeContentTest.kt @@ -0,0 +1,112 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.model.ArtMesh +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins that a DOWNGRADING export writes a document its target version can actually hold. + * + * The export strips the model before lowering it, and every other export gate exports at the model's + * own version - or at V53, which is an upgrade. On all of those `Moc3VersionDowngrade.strip` returns + * the SAME `PuppetModel` instance it was handed, so a lowering that read the un-stripped model instead + * of the stripped one would be a no-op and pass every one of them. This is the only gate that makes + * the strip observable without the C core. + * + * The floors asserted below are the section table's, not the editor's target-version dialog's - see + * `Moc3VersionDowngrade`, which is deliberate about the two ladders differing. + * + * Skips gracefully without samples, so it covers nothing on CI - the corpus is gitignored. + * + * @see MOC3.md §version gating + */ +class Moc3DowngradeContentTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir + ?.walkTopDown() + // work/ holds our own bake outputs - same models, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + @Test + fun aDowngradedExportCarriesNothingItsVersionCannotHold() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping downgrade content gate") + return + } + val failures = ArrayList() + var covered = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + for (targetVersion in listOf(MocVersion.V30, MocVersion.V42)) { + if (targetVersion.byteValue >= source.version.byteValue) { + continue + } + val label = "${file.name} → ${targetVersion.name}" + val exported = Moc3Export.toMocDocument(puppet, targetVersion).document + covered++ + + // Blend shapes arrived at moc v4, offscreen rendering at v6. + if (targetVersion.byteValue < 4 && exported.blendShapes.isNotEmpty()) { + failures.add("$label: carries ${exported.blendShapes.size} blend shapes below their v4 floor") + } + if (targetVersion.byteValue < 6 && exported.offscreens.isNotEmpty()) { + failures.add("$label: carries ${exported.offscreens.size} offscreens below their v6 floor") + } + // Per-object multiply/screen color arrived at v4; below that the tables do not exist, so a + // keyform must carry null rather than an identity or the lowering synthesizes a section the + // version cannot address. + if (targetVersion.byteValue < 4) { + val coloredObject = + exported.deformers.firstOrNull { deformer -> + when (deformer) { + is WarpDeformer -> deformer.keyforms.any { it.multiplyColor != null || it.screenColor != null } + is RotationDeformer -> deformer.keyforms.any { it.multiplyColor != null || it.screenColor != null } + } + }?.id + ?: exported.artMeshes.firstOrNull { mesh -> + mesh.keyforms.any { it.multiplyColor != null || it.screenColor != null } + }?.id + if (coloredObject != null) { + failures.add("$label: $coloredObject keeps a color channel below the v4 color floor") + } + val typedParameter = exported.parameters.firstOrNull { it.type != null } + if (typedParameter != null) { + failures.add("$label: parameter ${typedParameter.id} keeps a type below the v4 Parameter.Types floor") + } + } + // The packed extended blend is v6-only (MOC3 v6 §5.6 s153). + if (targetVersion.byteValue < 6) { + val extended: ArtMesh? = exported.artMeshes.firstOrNull { it.extendedBlend != 0 } + if (extended != null) { + failures.add("$label: art mesh ${extended.id} keeps extendedBlend=${extended.extendedBlend} below its v6 floor") + } + } + // The document has to survive its own writer: a section whose declared count exceeds its + // slice, or a table the version cannot address, fails here rather than in the official core. + MocCodec.read(MocEncoder.bakeFresh(targetVersion, exported)) + } + } + // The whole point is the path where strip returns a DIFFERENT model; a run that only ever + // re-targeted upward exercised nothing. + assertTrue(covered > 0, "no export in this run actually downgraded - no corpus model was above V30/V42") + println("[downgrade] $covered downgrading exports checked across ${files.size} models") + assertEquals(emptyList(), failures.take(25), "a downgraded export kept what its version cannot hold") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportBindingOrderTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportBindingOrderTest.kt new file mode 100644 index 0000000..cbf59d0 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportBindingOrderTest.kt @@ -0,0 +1,140 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the two orderings a reference-free export gets from the sequence its lowering runs in. + * + * The keyform pool assigns binding indices by first intern, so the order parts, deformers, art meshes, + * and glues are lowered in IS the file's binding numbering. That numbering is a pure permutation - + * nothing downstream reads it, and `Moc3ExportRoundTripTest` deliberately does not compare it - so a + * reorder produces a different but equally correct file. It is pinned anyway: a reorder is the visible + * symptom of a producer moving relative to a data dependency it has, and that second thing is not + * harmless. Without this test, splitting the lowering into per-concern producers could reorder them + * and every existing gate would stay green. + * + * The offscreen check is the other half. An offscreen's keyform rows come from its owner part's + * bundle, which the part lowering builds and hands on; on 14 of the 15 v6 corpus models an empty + * hand-off is undetectable because they are fully static and the row count collapses to 1 either way. + * Only `modelA.moc3` distinguishes the two. + * + * Skips gracefully without samples, so it covers nothing on CI - the corpus is gitignored. + * + * @see MOC3.md §5.6 + */ +class Moc3ExportBindingOrderTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir + ?.walkTopDown() + // work/ holds our own bake outputs - same models, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + @Test + fun bindingIndicesAreAssignedInLoweringOrder() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping export binding-order gate") + return + } + val failures = ArrayList() + var covered = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + val exported = Moc3Export.toMocDocument(puppet, source.version).document + covered++ + + // The pool reserves index 0 for the empty-axis record before anything can claim it, and every + // static object stores 0 to name it. A pool handed to a producer already primed, or built + // fresh per producer, loses that reservation. + val firstBinding = exported.bindings.firstOrNull() + if (firstBinding == null || firstBinding.index != 0 || firstBinding.axes.isNotEmpty()) { + failures.add("${file.name}: binding 0 is not the reserved empty-axis record (got $firstBinding)") + } + + // Walking the document's own lists in the order the lowering produces them, each newly-seen + // binding index must be larger than every index seen before. Gaps are legal: a static part + // interns a binding and then stores 0 instead, and a grid-less warp never interns at all. + val seen = HashSet() + var highestSoFar = -1 + val walk = + exported.parts.map { "part ${it.id}" to it.keyformBindingIndex } + + exported.deformers.map { "deformer ${it.id}" to it.keyformBindingIndex } + + exported.artMeshes.map { "artMesh ${it.id}" to it.keyformBindingIndex } + + exported.glues.map { "glue ${it.id}" to it.keyformBindingIndex } + for ((subject, bindingIndex) in walk) { + if (bindingIndex == 0 || !seen.add(bindingIndex)) { + continue + } + if (bindingIndex < highestSoFar) { + failures.add( + "${file.name}: $subject introduces binding $bindingIndex after $highestSoFar - " + + "the lowering ran out of order", + ) + } + highestSoFar = maxOf(highestSoFar, bindingIndex) + } + } + assertTrue(covered > 0, "no corpus model to check binding order against") + println("[export-order] $covered models, binding numbering follows lowering order") + assertEquals(emptyList(), failures.take(25), "export binding order diverged") + } + + @Test + fun offscreenKeyformRowsComeFromTheOwnerPartsBundle() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping offscreen row gate") + return + } + val failures = ArrayList() + var withOffscreens = 0 + var withMultiRowOffscreens = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + val exported = Moc3Export.toMocDocument(puppet, source.version).document + if (exported.offscreens.isEmpty()) { + continue + } + withOffscreens++ + for ((offscreenIndex, offscreen) in exported.offscreens.withIndex()) { + val ownerPart = exported.parts.getOrNull(offscreen.ownerPartIndex) + if (ownerPart == null) { + failures.add("${file.name}: offscreen $offscreenIndex names part ${offscreen.ownerPartIndex}, which does not exist") + continue + } + if (ownerPart.drawOrderKeyforms.size > 1) { + withMultiRowOffscreens++ + } + if (offscreen.keyforms.size != ownerPart.drawOrderKeyforms.size) { + failures.add( + "${file.name}: offscreen on ${ownerPart.id} has ${offscreen.keyforms.size} rows but its " + + "owner part's grid has ${ownerPart.drawOrderKeyforms.size} - the part bundle did not reach it", + ) + } + } + } + assertTrue(withOffscreens > 0, "no corpus model carries an offscreen") + // A fully-static owner part collapses to one row whether or not its bundle arrived, so a run that + // saw only static owners proved nothing about the hand-off. + assertTrue( + withMultiRowOffscreens > 0, + "every offscreen owner in this run was static - the part-bundle hand-off was not actually exercised", + ) + println("[export-order] $withOffscreens models with offscreens, $withMultiRowOffscreens multi-row owners") + assertEquals(emptyList(), failures.take(25), "offscreen keyform rows diverged from the owner part") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportCompactionTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportCompactionTest.kt new file mode 100644 index 0000000..0e005a6 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportCompactionTest.kt @@ -0,0 +1,174 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Channel compaction must be invisible to the export. + * + * The import runs `withChannelsCompacted` by default: a channel track whose values are constant along + * an axis has that axis's interior keys DROPPED, and a fully-constant track is lifted into a static. + * The export's re-bundling is supposed to be the exact inverse - `refinedToUnion` re-interpolates the + * dropped keys back - so importing the same file with compaction on and off and exporting both must + * produce identical documents. + * + * This is worth its own gate because the two halves live far apart and neither is obviously the + * other's inverse by inspection. A compaction that drops one key too many, or a refinement that + * restores it at a subtly different value, would leave the round trip passing (it compacts and + * restores consistently) while quietly changing what a SECOND export writes. Here the uncompacted + * import is the control: it never lost the key in the first place. + * + * For an owner WITH geometry the comparison is exact: a MOC3 stores one grid per object, so every + * channel track the import fans out starts with the geometry's own axes, and the geometry keeps those + * axes in the union whatever compaction does to the channels. + * + * A GEOMETRY-LESS owner - a part, a glue - is different, and the difference is legitimate rather than + * a bug. Its axes come only from its channel tracks, so lifting a constant track to a static removes + * the last axis and collapses the grid to a single cell. The uncompacted export then writes N + * identical values where the compacted one writes 1. Both are correct and evaluate identically, so + * the invariant asserted for those is the one that actually holds: the collapsed value equals every + * value it replaced. + */ +class Moc3ExportCompactionTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + /** The versions the export currently covers in full. */ + private val supportedVersions = setOf(1, 2, 3, 4, 5, 6) + + private fun samples(): List = + samplesDir + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + /** + * Asserts a geometry-less owner's track either kept its shape or collapsed value-preservingly. + * + * @param ArrayList failures The shared collector. + * @param String fileName The model being checked. + * @param String what The owner and channel being checked. + * @param FloatArray control The uncompacted values. + * @param FloatArray collapsed The compacted values. + */ + private fun checkCollapsed( + failures: ArrayList, + fileName: String, + what: String, + control: FloatArray, + collapsed: FloatArray, + ) { + if (control.contentEquals(collapsed)) { + return + } + if (collapsed.size == 1 && control.all { value -> value == collapsed[0] }) { + // The legitimate collapse: every cell held the same value, so one cell says the same thing. + return + } + failures.add( + "$fileName: $what collapsed lossily (uncompacted=${control.toList().take(4)} " + + "compacted=${collapsed.toList().take(4)})", + ) + } + + @Test + fun compactionDoesNotChangeWhatTheExportWrites() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping export compaction test") + return + } + val failures = ArrayList() + var covered = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + if (source.version.byteValue !in supportedVersions) { + continue + } + covered++ + val compacted = + Moc3Export.toMocDocument( + Moc3Import.fromMocDocument(source, displayInfo = null, compactChannels = true), + source.version, + ).document + val uncompacted = + Moc3Export.toMocDocument( + Moc3Import.fromMocDocument(source, displayInfo = null, compactChannels = false), + source.version, + ).document + + /** + * Records a divergence between the two exports. + * + * @param String what What differed. + * @param Any? expected The uncompacted (control) value. + * @param Any? actual The compacted value. + */ + fun check(what: String, expected: Any?, actual: Any?) { + if (expected != actual) { + failures.add("${file.name}: $what uncompacted=$expected compacted=$actual") + } + } + + // The document types implement structural equality over their arrays, so these compare values + // and not identities - which is the whole point. + check("parameters", uncompacted.parameters, compacted.parameters) + val compactedParts = compacted.parts.associateBy { it.id } + for (part in uncompacted.parts) { + val other = compactedParts[part.id] ?: continue + check("part ${part.id} parent", part.parentPartIndex, other.parentPartIndex) + check("part ${part.id} visibility", part.isVisible, other.isVisible) + checkCollapsed(failures, file.name, "part ${part.id} draw order", part.drawOrderKeyforms, other.drawOrderKeyforms) + } + check("deformers", uncompacted.deformers, compacted.deformers) + // Geometry-less owners: a collapsed grid is expected, so assert the collapse is VALUE-preserving + // rather than demanding the same cell count. + val compactedGlues = compacted.glues.associateBy { it.id } + for (glue in uncompacted.glues) { + val other = compactedGlues[glue.id] ?: continue + check("glue ${glue.id} mesh pair", glue.meshAIndex to glue.meshBIndex, other.meshAIndex to other.meshBIndex) + check("glue ${glue.id} pairs", glue.pairs, other.pairs) + checkCollapsed(failures, file.name, "glue ${glue.id} intensity", glue.intensityKeyforms, other.intensityKeyforms) + } + + // Field-level for art meshes: dumping whole objects buries which value moved. + val compactedMeshes = compacted.artMeshes.associateBy { it.id } + for (mesh in uncompacted.artMeshes) { + val other = compactedMeshes[mesh.id] ?: continue + check("mesh ${mesh.id} keyform count", mesh.keyforms.size, other.keyforms.size) + check("mesh ${mesh.id} binding", mesh.keyformBindingIndex, other.keyformBindingIndex) + for (keyIndex in mesh.keyforms.indices) { + val a = mesh.keyforms.getOrNull(keyIndex) ?: continue + val b = other.keyforms.getOrNull(keyIndex) ?: continue + if (!a.vertexPositions.contentEquals(b.vertexPositions)) { + val worst = + a.vertexPositions.indices.maxByOrNull { component -> + kotlin.math.abs(a.vertexPositions[component] - (b.vertexPositions.getOrNull(component) ?: 0f)) + } ?: 0 + failures.add( + "${file.name}: mesh ${mesh.id} keyform $keyIndex positions differ at $worst " + + "uncompacted=${a.vertexPositions.getOrNull(worst)} compacted=${b.vertexPositions.getOrNull(worst)}", + ) + } + check("mesh ${mesh.id} keyform $keyIndex opacity", a.opacity, b.opacity) + check("mesh ${mesh.id} keyform $keyIndex drawOrder", a.drawOrder, b.drawOrder) + } + } + check("render-order groups", uncompacted.renderOrderGroups, compacted.renderOrderGroups) + check("binding count", uncompacted.bindings.size, compacted.bindings.size) + for (index in uncompacted.bindings.indices) { + check("binding[$index]", uncompacted.bindings.getOrNull(index), compacted.bindings.getOrNull(index)) + } + } + assertTrue(covered > 0, "no v1-v6 corpus model to compare") + println("[export] compaction-invariant across $covered v1-v6 models, ${failures.size} divergences") + assertEquals(emptyList(), failures.take(15), "compaction changed the exported document") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportCountInfoTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportCountInfoTest.kt new file mode 100644 index 0000000..b8ec087 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportCountInfoTest.kt @@ -0,0 +1,120 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.encode.MocEncoder +import org.umamo.format.moc3.encode.MocLowering +import org.umamo.format.moc3.io.LittleEndianReader +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.format.moc3.moc.Section +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * CountInfo self-consistency on the REFERENCE-FREE export path. + * + * `:format`'s own CountInfo gate runs over documents decoded from corpus files, which share a shape + * the exporter never produces: every v4+ blend-free sample has zero parameter bindings, so the branch + * that writes KEY_POSITIONS' per-parameter union region is never reached with a non-empty key set. + * A freshly exported rig hits it on essentially every model, and nothing downstream would notice a + * wrong count - `Moc3ExportRoundTripTest` compares documents, `Moc3FamilyExportTest` re-imports + * through our own decoder, and our `MocSections` reads KEY_POSITIONS as a TABLE section, so its + * declared extent is invisible to every reader we own. The official core is not: it sizes its + * parameter key store from field 14 and then reads the section-103/104 runs out of that buffer. + * + * Exported at each model's own version and at V53. A MOC3-imported puppet's runtime target mirrors + * its source version, so the former is what `Moc3Export.write` defaults to for these documents; the + * latter is the newest table layout, which a re-target or a target-less document bakes. Skips + * without samples. + * + * @see MOC3.md §5.6 + */ +class Moc3ExportCountInfoTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir + ?.walkTopDown() + // work/ holds our own bake outputs - same models, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + /** + * Reads a lowered section back as an [IntArray]. + * + * @param Map sections The lowered section map, keyed by table index. + * @param Section section The section to read. + * @param MocVersion version The version whose table index applies. + * @return IntArray The decoded values, empty when the section is absent. + */ + private fun intsOf(sections: Map, section: Section, version: MocVersion): IntArray { + val bytes = sections[section.indexIn(version)] ?: return IntArray(0) + val reader = LittleEndianReader(bytes) + return IntArray(bytes.size / 4) { reader.readInt32() } + } + + @Test + fun freshlyExportedDocumentsDeclareTheSectionsTheyCarry() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping export CountInfo gate") + return + } + val failures = ArrayList() + var covered = 0 + var withKeyPositions = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + for (targetVersion in listOf(source.version, MocVersion.V53)) { + val exported = Moc3Export.toMocDocument(puppet, targetVersion).document + val lowered = MocLowering.lower(exported) + val countInfo = intsOf(lowered, Section.COUNT_INFO, targetVersion) + val label = "${file.name} → ${targetVersion.name}" + covered++ + + val keyPositions = lowered[Section.KEY_POSITIONS.indexIn(targetVersion)] ?: ByteArray(0) + if (keyPositions.isNotEmpty()) { + withKeyPositions++ + } + if (countInfo[14] * 4 != keyPositions.size) { + failures.add( + "$label: CountInfo[14] declares ${countInfo[14]} floats but KEY_POSITIONS carries" + + " ${keyPositions.size / 4}", + ) + } + val bindingStart = intsOf(lowered, Section.KEYFORM_BINDING_START, targetVersion) + if (countInfo[12] != bindingStart.size) { + failures.add( + "$label: CountInfo[12] declares ${countInfo[12]} bindings but s73 carries ${bindingStart.size}", + ) + } + // 103/104 address runs INSIDE the buffer field 14 sizes, so a run ending past the declared + // extent reads off the end of the arena the runtime just allocated. + val keyStart = intsOf(lowered, Section.PARAM_KEY_START, targetVersion) + val keyCount = intsOf(lowered, Section.PARAM_KEY_COUNT, targetVersion) + if (keyStart.isNotEmpty()) { + val lastRunEnd = keyStart.last() + keyCount.last() + if (lastRunEnd > countInfo[14]) { + failures.add("$label: parameter key runs end at $lastRunEnd, past the declared ${countInfo[14]}") + } + } + // The bake has to survive its own writer: an over-long offset table or a section whose + // declared count exceeds its slice fails here rather than inside the official core. + val baked = MocEncoder.bakeFresh(targetVersion, exported) + MocCodec.read(baked) + } + } + failures.forEach { failureMessage -> println("[export-countinfo] FAIL $failureMessage") } + assertTrue(failures.isEmpty(), "exported CountInfo disagrees with its sections:\n" + failures.joinToString("\n")) + println("[export-countinfo] $covered exports checked, $withKeyPositions with a non-empty KEY_POSITIONS") + // The whole point is the union-region branch the corpus cannot reach; if no export produced key + // positions at all, this gate proved nothing. + assertTrue(withKeyPositions > 0, "no exported document carried KEY_POSITIONS - the gate covered nothing") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportRoundTripTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportRoundTripTest.kt new file mode 100644 index 0000000..5130863 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ExportRoundTripTest.kt @@ -0,0 +1,183 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The core reference-free export gate: `moc3 -> PuppetModel -> moc3` preserves the rig. + * + * This is the test that says whether a reference-free export actually works. It imports a corpus + * MOC3, exports the resulting [org.umamo.runtime.model.PuppetModel] back to a document with NO + * reference container, and compares the two documents structurally. + * + * Comparison is by ID, never by list position. A MOC3 addresses everything by index, but the + * export re-derives those indices from the runtime model's own ordering (parents before children, + * which the source file also satisfies but need not have satisfied in the same order), so equal + * indices are not part of the contract - equal CONTENT under the same id is. Keyform-binding + * numbering is likewise not compared: a MOC3's binding indices are the editor's internal creation + * order, unrecoverable from a runtime model, so the pool is semantically equivalent rather than + * identically numbered. + * + * Scoped to v1-v6 - every version the format models. + */ +class Moc3ExportRoundTripTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + /** The versions the export currently covers in full. */ + private val supportedVersions = setOf(1, 2, 3, 4, 5, 6) + + private fun samples(): List = + samplesDir + ?.walkTopDown() + // work/ holds our own bake outputs - same models, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + @Test + fun exportedDocumentMatchesTheImportedOne() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping export round trip") + return + } + val failures = ArrayList() + var covered = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + if (source.version.byteValue !in supportedVersions) { + continue + } + covered++ + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + val exported = Moc3Export.toMocDocument(puppet, source.version).document + + /** + * Records a mismatch against this file. + * + * @param String what What differed. + * @param Any? expected The source's value. + * @param Any? actual The exported value. + */ + fun check(what: String, expected: Any?, actual: Any?) { + if (expected != actual) { + failures.add("${file.name}: $what expected=$expected actual=$actual") + } + } + + check("parameter count", source.parameters.size, exported.parameters.size) + check("part count", source.parts.size, exported.parts.size) + check("deformer count", source.deformers.size, exported.deformers.size) + check("art mesh count", source.artMeshes.size, exported.artMeshes.size) + check("glue count", source.glues.size, exported.glues.size) + + // Parameters keep their file order (nothing reorders them), so compare positionally. + for (index in source.parameters.indices) { + val expected = source.parameters.getOrNull(index) + val actual = exported.parameters.getOrNull(index) + check("parameter[$index]", expected, actual) + } + + // Parts and drawables are compared by id: the export re-derives file order from the runtime + // tree, which need not reproduce the source's ordering. + val sourcePartsById = source.parts.associateBy { it.id } + for (part in exported.parts) { + val expected = sourcePartsById[part.id] + if (expected == null) { + failures.add("${file.name}: exported an unknown part ${part.id}") + continue + } + // A part has no geometry, so its only axes come from its draw-order track - and compaction + // lifts a CONSTANT track into the static, collapsing the grid to one cell. That is + // value-preserving, so the invariant is that the collapse says the same thing, not that the + // cell count survived. + if (part.drawOrderKeyforms.size != expected.drawOrderKeyforms.size) { + val collapsedToConstant = + part.drawOrderKeyforms.size == 1 && + expected.drawOrderKeyforms.all { value -> value == part.drawOrderKeyforms[0] } + if (!collapsedToConstant) { + failures.add( + "${file.name}: part ${part.id} draw order collapsed lossily " + + "(source=${expected.drawOrderKeyforms.toList().take(4)} " + + "exported=${part.drawOrderKeyforms.toList().take(4)})", + ) + } + } + check("part ${part.id} visibility", expected.isVisible, part.isVisible) + } + + val sourceMeshesById = source.artMeshes.associateBy { it.id } + for (mesh in exported.artMeshes) { + val expected = sourceMeshesById[mesh.id] + if (expected == null) { + failures.add("${file.name}: exported an unknown art mesh ${mesh.id}") + continue + } + check("mesh ${mesh.id} vertex count", expected.vertexCount, mesh.vertexCount) + check("mesh ${mesh.id} texture", expected.textureIndex, mesh.textureIndex) + check("mesh ${mesh.id} constant flags", expected.constantFlags, mesh.constantFlags) + check("mesh ${mesh.id} keyform count", expected.keyforms.size, mesh.keyforms.size) + // A moc mask column can carry -1 placeholders alongside real references; the import drops + // them and the export does not invent them back, so compare against the VALID count. + check( + "mesh ${mesh.id} mask count", + expected.maskDrawableIndices.count { index -> index >= 0 }, + mesh.maskDrawableIndices.size, + ) + check("mesh ${mesh.id} index count", expected.triangleIndices.size, mesh.triangleIndices.size) + } + + // Offscreens (moc 6), by owner part id: the export renumbers parts, so the owner INDEX is not + // comparable across the two files - and a keyform row count that disagrees with the owner + // part's grid desynchronizes the runtime's per-offscreen base for every later offscreen. + val sourceOffscreensByOwner = + source.offscreens.mapNotNull { offscreen -> + source.parts.getOrNull(offscreen.ownerPartIndex)?.id?.to(offscreen) + }.toMap() + val exportedOffscreensByOwner = + exported.offscreens.mapNotNull { offscreen -> + exported.parts.getOrNull(offscreen.ownerPartIndex)?.id?.to(offscreen) + }.toMap() + check("offscreen owners", sourceOffscreensByOwner.keys.sorted(), exportedOffscreensByOwner.keys.sorted()) + for ((ownerId, expected) in sourceOffscreensByOwner) { + val actual = exportedOffscreensByOwner[ownerId] ?: continue + val exportedOwnerPart = exported.parts.first { it.id == ownerId } + check("offscreen($ownerId) blend", expected.blendMode, actual.blendMode) + check("offscreen($ownerId) flags", expected.constantFlags, actual.constantFlags) + check("offscreen($ownerId) mask count", expected.maskCount, actual.maskIndices.size) + // The invariant evalOffscreens depends on: one row per cell of the OWNER PART's grid. + check( + "offscreen($ownerId) keyform rows", + exportedOwnerPart.drawOrderKeyforms.size, + actual.keyforms.size, + ) + check( + "offscreen($ownerId) mask ids", + expected.maskIndices.toList().mapNotNull { source.artMeshes.getOrNull(it)?.id }.toSet(), + actual.maskIndices.toList().mapNotNull { exported.artMeshes.getOrNull(it)?.id }.toSet(), + ) + } + + val sourceDeformersById = source.deformers.associateBy { it.id } + for (deformer in exported.deformers) { + val expected = sourceDeformersById[deformer.id] + if (expected == null) { + failures.add("${file.name}: exported an unknown deformer ${deformer.id}") + continue + } + check("deformer ${deformer.id} kind", expected::class.simpleName, deformer::class.simpleName) + check("deformer ${deformer.id} visibility", expected.isVisible, deformer.isVisible) + } + } + assertTrue(covered > 0, "no v1-v6 corpus model to round trip") + println("[export] round-tripped $covered v1-v6 models, ${failures.size} mismatches") + assertEquals(emptyList(), failures.take(25), "export round trip diverged") + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ImportOrderTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ImportOrderTest.kt new file mode 100644 index 0000000..dde792d --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ImportOrderTest.kt @@ -0,0 +1,239 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the orderings the MOC3 import derives from its own internal sequence. + * + * Panel order - the parts panel's top-to-bottom stacking - is not stored in a `.moc3` at all. The import + * RECONSTRUCTS it by walking the render tree and reversing the leaf sequence, and then two separate + * results read that reconstruction: the flat drawable list and every org-tree child list. So the import + * has a real ordering contract, render tree BEFORE panel indices BEFORE the org tree, and breaking it + * throws nothing: the panel indices simply come back empty and every drawable ranks `Int.MAX_VALUE`, + * which yields a different, entirely plausible order. + * + * Nothing else notices. `Moc3ExportRoundTripTest` compares by id precisely so that index churn cannot + * red it; `Moc3ImportTest` asserts each drawable is placed in the org tree exactly once, not where. This + * is the gate that would fail if a decomposition ran those three passes in the wrong order. + * + * Skips gracefully without samples, so it covers nothing on CI - the corpus is gitignored. + * + * @see MOC3.md §5.6 + */ +class Moc3ImportOrderTest { + private val samplesDir: File? = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + private fun samples(): List = + samplesDir + ?.walkTopDown() + // work/ holds our own bake outputs - same models, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + + @Test + fun theFlatDrawableListIsTheRenderTreesLeafOrder() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping import order gate") + return + } + val failures = ArrayList() + var covered = 0 + var reordered = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + // A document with no render-order groups reconstructs no panel order at all - the import falls + // back to deriving a tree from the org tree, which is a different contract than this one. + if (source.renderOrderGroups.isEmpty()) { + continue + } + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + covered++ + + val flatOrder = puppet.drawables.map { drawable -> drawable.id } + val leafOrder = leavesOf(puppet.renderRoot) + if (flatOrder != leafOrder) { + failures.add( + "${file.name}: the flat drawable list is not the render tree's leaf order " + + "(${firstDivergence(flatOrder, leafOrder)})", + ) + } + + // THE discriminating count. When the render tree happens to place drawables in file order the + // invariant above also holds for an import that reconstructed nothing at all, because an empty + // panel-index map leaves the stable sort on file order. Only a model whose leaf order differs + // from its file order can tell the two apart. + val fileOrder = source.artMeshes.map { artMesh -> DrawableId(artMesh.id) } + if (leafOrder != fileOrder) { + reordered++ + } + } + assertTrue(covered > 0, "no corpus model carries render-order groups") + assertTrue( + reordered > 0, + "every model in this run renders in file order - a reconstruction that produced nothing would pass too", + ) + println("[import-order] $covered models with render groups, $reordered where leaf order differs from file order") + assertEquals(emptyList(), failures.take(25), "the flat drawable order diverged from the render tree") + } + + @Test + fun orgTreeChildrenFollowPanelOrder() { + val files = samples() + if (files.isEmpty()) { + println("moc3.samples not present; skipping org-tree order gate") + return + } + val failures = ArrayList() + var covered = 0 + var multiChildContainers = 0 + for (file in files) { + val source = Moc3.decode(MocCodec.read(file.readBytes())) + if (source.renderOrderGroups.isEmpty()) { + continue + } + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + covered++ + + // The org tree sorts front-to-back and the flat list back-to-front, so one is the other + // reversed - both being views of the same reconstructed panel index. + val panelRank = + puppet.drawables + .asReversed() + .withIndex() + .associate { (rank, drawable) -> drawable.id to rank } + val partRanks = HashMap() + + for ((containerName, children) in containersOf(puppet)) { + if (children.size > 1) { + multiChildContainers++ + } + var previousRank = Int.MIN_VALUE + for (child in children) { + val rank = + when (child) { + is OrgChild.Drawable -> panelRank[child.id] ?: Int.MAX_VALUE + is OrgChild.Part -> partRankOf(puppet, child.id, panelRank, partRanks, HashSet()) + } + if (rank < previousRank) { + failures.add( + "${file.name}: $containerName lists $child at panel rank $rank after $previousRank - " + + "its children are not in panel order", + ) + break + } + previousRank = rank + } + } + } + assertTrue(covered > 0, "no corpus model carries render-order groups") + // A tree of single-child containers is sorted no matter what the sort did. + assertTrue(multiChildContainers > 0, "no container in this run had two children to order") + println("[import-order] $covered models, $multiChildContainers containers with more than one child") + assertEquals(emptyList(), failures.take(25), "org-tree children diverged from panel order") + } + + /** + * Every ordered child list in [puppet]'s org tree: the root's, then one per part. + * + * @param PuppetModel puppet The imported rig. + * @return List>> Each container's label and its children. + */ + private fun containersOf(puppet: PuppetModel): List>> = + listOf("root" to puppet.rootChildren) + puppet.parts.map { part -> "part ${part.id.raw}" to part.children } + + /** + * A part's panel rank: the minimum over every drawable in its subtree. + * + * Memoized into [partRanks], and guarded by [visiting] so a malformed parent cycle - which the import + * normalizes but this walk would otherwise follow - terminates. + * + * @param PuppetModel puppet The imported rig. + * @param PartId partId The part to rank. + * @param Map panelRank Each drawable's panel rank. + * @param MutableMap partRanks The memo table. + * @param MutableSet visiting The parts already on this walk's stack. + * @return Int The rank, or Int.MAX_VALUE when the subtree holds no drawable. + */ + private fun partRankOf( + puppet: PuppetModel, + partId: PartId, + panelRank: Map, + partRanks: MutableMap, + visiting: MutableSet, + ): Int { + partRanks[partId]?.let { cached -> + return cached + } + if (!visiting.add(partId)) { + return Int.MAX_VALUE + } + var minimum = Int.MAX_VALUE + for (child in puppet.partById[partId]?.children.orEmpty()) { + val rank = + when (child) { + is OrgChild.Drawable -> panelRank[child.id] ?: Int.MAX_VALUE + is OrgChild.Part -> partRankOf(puppet, child.id, panelRank, partRanks, visiting) + } + if (rank < minimum) { + minimum = rank + } + } + visiting.remove(partId) + partRanks[partId] = minimum + return minimum + } + + /** + * The render tree's drawable leaves, depth-first - the back-to-front draw sequence. + * + * @param RenderNode node The subtree root. + * @return List The leaves, in order. + */ + private fun leavesOf(node: RenderNode): List { + val leaves = ArrayList() + + fun walk(current: RenderNode) { + when (current) { + is RenderDrawable -> leaves.add(current.id) + is RenderGroup -> current.children.forEach(::walk) + } + } + walk(node) + return leaves + } + + /** + * Where two id sequences first differ, for a failure message that names the position rather than + * dumping two lists of several hundred ids. + * + * @param List actual The sequence under test. + * @param List expected The sequence it should equal. + * @return String A one-line description of the first divergence. + */ + private fun firstDivergence( + actual: List, + expected: List, + ): String { + if (actual.size != expected.size) { + return "${actual.size} drawables vs ${expected.size} leaves" + } + val position = actual.indices.firstOrNull { index -> actual[index] != expected[index] } ?: return "same order" + return "at $position: ${actual[position].raw} vs ${expected[position].raw}" + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ImportTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ImportTest.kt new file mode 100644 index 0000000..5e79012 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/moc3/Moc3ImportTest.kt @@ -0,0 +1,374 @@ +package org.umamo.interop.moc3 + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.eval.flagAt +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode +import org.umamo.runtime.model.partByDrawable +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Reads a real `.moc3` corpus sample (plus its sibling cdi3.json when present), maps it to a + * `PuppetModel`, and checks the structural tree - the MOC3 counterpart of [Cmo3ImportTest]. + * + * Self-contained; skips when the sample is absent. `moc3.sample` (singular) has no default in this + * module, so the test only runs when `-Dmoc3.sample=/path/to/Model.moc3` is passed explicitly. The + * assertions verify referential integrity (every index cross-reference resolves to a real entity), + * that deformer ids and part membership come from the file rather than being synthesized or inferred, + * that every anchored deformer label names a mesh the deformer really reaches, plus golden counts + * pinned per corpus model. + */ +class Moc3ImportTest { + private val sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun mapsCorpusModelToStructuralTree() { + val file = sample + if (file == null) { + println("moc3.sample not present; skipping import test") + return + } + val mocDocument = Moc3.read(file.readBytes()) + val displayInfo = siblingDisplayInfo(file) + val puppet = Moc3Import.fromMocDocument(mocDocument, displayInfo) + + val warpCount = puppet.deformers.count { it is Deformer.Warp } + val rotationCount = puppet.deformers.count { it is Deformer.Rotation } + println( + "[Umamo][moc3import] parameters=${puppet.parameters.size} parts=${puppet.parts.size} " + + "deformers=${puppet.deformers.size} (warp=$warpCount rotation=$rotationCount) " + + "drawables=${puppet.drawables.size} glues=${puppet.glues.size}", + ) + val totalVertices = puppet.drawables.sumOf { it.mesh?.vertexCount ?: 0 } + val totalPolygons = puppet.drawables.sumOf { it.mesh?.triangleCount ?: 0 } + println("[Umamo][moc3import] vertices=$totalVertices polygons=$totalPolygons") + val artInterpolations = puppet.drawables.sumOf { it.geometryGrid?.cells?.size ?: 0 } + val deformerInterpolations = + puppet.deformers.sumOf { deformer -> + when (deformer) { + is Deformer.Warp -> deformer.geometryGrid?.cells?.size ?: 0 + is Deformer.Rotation -> deformer.geometryGrid?.cells?.size ?: 0 + } + } + println("[Umamo][moc3import] artInterpolations=$artInterpolations deformerInterpolations=$deformerInterpolations") + println("[Umamo][moc3import] parameterTree top=${puppet.parameterTree.size} links=${puppet.parameterLinks.size}") + println( + "[Umamo][moc3import] canvas=${puppet.canvasWidth}x${puppet.canvasHeight} " + + "origin=(${puppet.worldOriginX}, ${puppet.worldOriginZ})", + ) + + // Model A: BLEND_SHAPE-typed parameters carry their kind through the import (MOC3 section 114). + if (file.name.startsWith("modelA")) { + assertEquals( + 12, + puppet.parameters.count { it.kind == org.umamo.runtime.model.ParameterKind.BLEND_SHAPE }, + "modelA: blend-shape parameter kinds mapped", + ) + } + + // Golden gate: for the EricaTamamo corpus, pin the imported structure. Drawable-derived counts + // intentionally differ from the CMO3 sample's (177 drawables / 31470 vertices / 337 art + // interpolations): the bake drops the three sketch ("Guide Image") drawables. + if (file.name.startsWith("EricaTamamo")) { + assertEquals(116, puppet.parameters.size, "parameters") + assertEquals(42, puppet.parts.size, "parts") + assertEquals(350, warpCount, "warp deformers") + assertEquals(6, rotationCount, "rotation deformers") + assertEquals(174, puppet.drawables.size, "art meshes") + assertEquals(4, puppet.glues.size, "glues") + assertEquals(30638, totalVertices, "vertices") + assertEquals(49510, totalPolygons, "polygons") + assertEquals(334, artInterpolations, "art mesh interpolations") + assertEquals(1297, deformerInterpolations, "deformer interpolations") + assertEquals(71, puppet.parameterTree.size, "parameter tree top-level nodes") + assertEquals(4500f, puppet.canvasWidth, "canvas width") + assertEquals(6500f, puppet.canvasHeight, "canvas height") + assertEquals(2250f, puppet.worldOriginX, "world origin x") + assertEquals(-3250f, puppet.worldOriginZ, "world origin y") + assertEquals( + listOf( + ParameterLink(ParameterId("ParamAngleX"), ParameterId("ParamAngleY")), + ParameterLink(ParameterId("ParamEyeBallX"), ParameterId("ParamEyeBallY")), + ), + puppet.parameterLinks, + "parameter links", + ) + // cdi3 display names resolved for parameters and parts (spot checks; names are user data). + assertTrue( + puppet.parameters.any { it.id.raw != it.name }, + "expected cdi3 display names to differ from raw parameter ids somewhere", + ) + } + + val partIds = puppet.parts.map { it.id }.toSet() + val deformerIds = puppet.deformers.map { it.id }.toSet() + val drawableIds = puppet.drawables.map { it.id }.toSet() + + assertTrue(puppet.parameters.isNotEmpty(), "expected parameters") + assertTrue(puppet.drawables.isNotEmpty(), "expected drawables") + + // Referential integrity: every org-tree child resolves, every drawable is placed in the tree, + // and every cross-reference (deformer parents, masks, glue meshes) resolves to a real entity. + fun checkOrgChildren(children: List, owner: String) { + for (child in children) { + when (child) { + is OrgChild.Part -> assertTrue(child.id in partIds, "$owner -> unknown sub-part ${child.id.raw}") + is OrgChild.Drawable -> assertTrue(child.id in drawableIds, "$owner -> unknown mesh ${child.id.raw}") + } + } + } + checkOrgChildren(puppet.rootChildren, "root") + for (part in puppet.parts) { + checkOrgChildren(part.children, "part ${part.id.raw}") + } + val placedDrawables = puppet.partByDrawable().keys + for (drawable in puppet.drawables) { + assertTrue(drawable.id in placedDrawables, "drawable ${drawable.id.raw} is missing from the org tree") + drawable.parentDeformerId?.let { + assertTrue(it in deformerIds, "drawable ${drawable.id.raw} -> unknown deformer ${it.raw}") + } + for (mask in drawable.maskedBy) { + assertTrue(mask in drawableIds, "drawable ${drawable.id.raw} -> unknown mask ${mask.raw}") + } + } + for (deformer in puppet.deformers) { + deformer.parent?.let { + assertTrue(it in deformerIds, "deformer ${deformer.id.raw} -> unknown parent ${it.raw}") + } + deformer.partId?.let { + assertTrue(it in partIds, "deformer ${deformer.id.raw} -> unknown part ${it.raw}") + } + } + + // Deformer identity and org placement are READ from the moc (MOC3 §5.6 s11/s15), not synthesized + // or inferred: each imported deformer keeps the file's own id and sits in exactly the part the + // file names for it, in file order. + for ((deformerIndex, source) in mocDocument.deformers.withIndex()) { + val expectedPartId = mocDocument.parts.getOrNull(source.parentPartIndex)?.let { PartId(it.id) } + assertEquals( + source.id, + puppet.deformers[deformerIndex].id.raw, + "deformer $deformerIndex id", + ) + assertEquals( + expectedPartId, + puppet.deformers[deformerIndex].partId, + "deformer $deformerIndex (${source.id}) part membership", + ) + } + + // Deformer labels: the id, optionally anchored with the one drawable the deformer reaches. The + // anchor is checked for TRUTH rather than by restating the rule - whatever mesh a label names + // must really be deformed by that deformer, directly or through its descendants. + val subtreeDrawables = HashMap>() + for (artMesh in mocDocument.artMeshes) { + var ancestorIndex = artMesh.parentDeformerIndex + val visited = HashSet() + while (ancestorIndex in mocDocument.deformers.indices && visited.add(ancestorIndex)) { + subtreeDrawables.getOrPut(ancestorIndex) { HashSet() }.add(artMesh.id) + ancestorIndex = mocDocument.deformers[ancestorIndex].parentDeformerIndex + } + } + val labelPattern = Regex("""^(.*) \((.*)\)$""") + for ((deformerIndex, source) in mocDocument.deformers.withIndex()) { + val name = puppet.deformers[deformerIndex].name + val anchor = labelPattern.matchEntire(name) + if (anchor == null) { + assertEquals(source.id, name, "deformer $deformerIndex unanchored label is its id") + continue + } + assertEquals(source.id, anchor.groupValues[1], "deformer $deformerIndex anchored label keeps its id") + assertTrue( + anchor.groupValues[2] in subtreeDrawables[deformerIndex].orEmpty(), + "deformer ${source.id} is labelled with ${anchor.groupValues[2]}, which it does not deform", + ) + } + val anchoredLabels = puppet.deformers.filter { labelPattern.matches(it.name) } + println( + "[Umamo][moc3import] deformer labels anchored=${anchoredLabels.size}/${puppet.deformers.size} " + + "e.g. ${anchoredLabels.take(3).map { it.name }}", + ) + for (glue in puppet.glues) { + assertTrue(glue.meshA in drawableIds, "glue -> unknown mesh A ${glue.meshA.raw}") + assertTrue(glue.meshB in drawableIds, "glue -> unknown mesh B ${glue.meshB.raw}") + } + + // The imported render tree's leaves are exactly the drawables (the baked draw-order tree places + // every mesh once). + val renderLeaves = ArrayList() + + fun collectLeaves(node: RenderNode) { + when (node) { + is RenderDrawable -> renderLeaves.add(node) + is RenderGroup -> node.children.forEach(::collectLeaves) + } + } + collectLeaves(puppet.renderRoot) + assertEquals(puppet.drawables.size, renderLeaves.size, "render tree leaf count") + for (leaf in renderLeaves) { + assertTrue((leaf as RenderDrawable).id in drawableIds, "render leaf -> unknown drawable") + } + + // The panel tree covers every parameter exactly once when cdi3 was present. + if (displayInfo != null) { + fun walkLeaves(nodes: List): List = + nodes.flatMap { node -> + when (node) { + is ParameterNode.Param -> listOf(node.id) + is ParameterNode.Group -> walkLeaves(node.children) + } + } + + val parameterTreeLeaves = walkLeaves(puppet.parameterTree) + assertEquals(puppet.parameters.size, parameterTreeLeaves.size, "parameter tree leaves") + assertEquals( + puppet.parameters.map { it.id }.toSet(), + parameterTreeLeaves.toSet(), + "every panel leaf is a real parameter", + ) + } + } + + /** + * Corpus gate for the blend mapping: every blend-shape corpus moc3 imports its records into + * per-object BlendShapeBindings whose shape matches the CMO3 twin's ingest (the same + * goldens as Cmo3ImportTest.blendShapeBindingsAcrossCorpus, with Model C's single PART-owned + * record excluded on both sides). Driven by -Dmoc3.samples (defaulted by the build). + */ + @Test + fun blendShapeBindingsAcrossCorpus() { + val samplesDir = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + val samples = + samplesDir?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + .filter { file -> listOf("modelA", "modelB", "modelC").any { prefix -> file.name.startsWith(prefix) } } + if (samples.isEmpty()) { + println("moc3.samples not present; skipping blend-binding corpus gate") + return + } + for (file in samples) { + val puppet = Moc3Import.fromMocDocument(Moc3.read(file.readBytes()), siblingDisplayInfo(file)) + val drawableBindings = puppet.drawables.flatMap { it.blendShapes } + val warpBindings = puppet.deformers.filterIsInstance().flatMap { it.blendShapes } + val rotationBindings = puppet.deformers.filterIsInstance().flatMap { it.blendShapes } + val allBindings = drawableBindings + warpBindings + rotationBindings + val defaultByParameter = puppet.parameters.associate { it.id to it.default } + val kindByParameter = puppet.parameters.associate { it.id to it.kind } + for (binding in allBindings) { + val keys = binding.keys.toList() + assertEquals(keys, keys.sorted(), "${file.name}: binding keys ascending") + assertEquals(keys.size, keys.distinct().size, "${file.name}: binding keys distinct") + assertEquals( + 0f, + binding.keys[binding.neutralIndex], + "${file.name}: neutral key at parameter value 0 (param=${binding.parameterId.raw})", + ) + assertEquals(keys.size, binding.forms.size, "${file.name}: forms parallel keys") + assertEquals(null, binding.forms[binding.neutralIndex], "${file.name}: neutral form slot null") + binding.forms.forEachIndexed { formIndex, form -> + if (formIndex != binding.neutralIndex) { + assertTrue(form != null, "${file.name}: non-neutral form non-null") + } + } + assertEquals( + org.umamo.runtime.model.ParameterKind.BLEND_SHAPE, + kindByParameter[binding.parameterId], + "${file.name}: driving parameter is BLEND_SHAPE-typed", + ) + } + // The rotation forms' flips must pin the FLIP tracks' value at the default pose. The statics are + // not lifted until compaction runs at the end of the import, so a form built from the statics + // would read constant false and silently un-mirror a reflected deformer's morph targets - the + // regression this block guards. The count is printed so the gate's coverage stays visible. + var reflectedForms = 0 + val defaultPose: (ParameterId) -> Float = { id -> defaultByParameter[id] ?: 0f } + for (rotation in puppet.deformers.filterIsInstance()) { + val expectedFlipX = rotation.channelGrids.flagAt(FormChannel.FLIP_X, rotation.flipX, defaultPose) + val expectedFlipY = rotation.channelGrids.flagAt(FormChannel.FLIP_Y, rotation.flipY, defaultPose) + for (binding in rotation.blendShapes) { + for (form in binding.forms) { + if (form == null) { + continue + } + assertEquals(expectedFlipX, form.flipX, "${file.name}: rotation blend form flipX pins the default-pose flip") + assertEquals(expectedFlipY, form.flipY, "${file.name}: rotation blend form flipY pins the default-pose flip") + if (form.flipX || form.flipY) { + reflectedForms++ + } + } + } + } + val blendParameterCount = puppet.parameters.count { it.kind == org.umamo.runtime.model.ParameterKind.BLEND_SHAPE } + val nonNeutralForms = allBindings.sumOf { binding -> binding.forms.count { it != null } } + val limitCurves = allBindings.sumOf { it.limits.size } + val limitPoints = allBindings.sumOf { binding -> binding.limits.sumOf { it.points.size } } + println( + "[moc3import] ${file.name}: blendParams=$blendParameterCount bindings=${allBindings.size} " + + "(drawable=${drawableBindings.size} warp=${warpBindings.size} rotation=${rotationBindings.size}) " + + "forms=$nonNeutralForms limits=$limitCurves points=$limitPoints reflectedForms=$reflectedForms", + ) + // Goldens mirror Cmo3ImportTest.blendShapeBindingsAcrossCorpus (Model C's PART record + // excluded on both sides; MOC3 limit refs expand the dedup pool per record, one curve + // per ref, two points per corpus curve). + if (file.name.startsWith("modelA")) { + assertEquals(12, blendParameterCount, "Model A: blend parameters") + assertEquals(60, allBindings.size, "Model A: bindings") + assertEquals(48, warpBindings.size, "Model A: warp bindings") + assertEquals(8, drawableBindings.size, "Model A: mesh bindings") + assertEquals(4, rotationBindings.size, "Model A: rotation bindings") + assertEquals(118, nonNeutralForms, "Model A: non-neutral forms") + assertEquals(0, limitCurves, "Model A: no limits") + } + if (file.name.startsWith("modelB")) { + assertEquals(5, blendParameterCount, "Model B: blend parameters") + assertEquals(45, allBindings.size, "Model B: bindings") + assertEquals(5, warpBindings.size, "Model B: warp bindings") + assertEquals(40, drawableBindings.size, "Model B: mesh bindings") + assertEquals(45, nonNeutralForms, "Model B: non-neutral forms") + assertEquals(44, limitCurves, "Model B: limit curves") + assertEquals(88, limitPoints, "Model B: limit points") + } + if (file.name.startsWith("modelC")) { + assertEquals(33, blendParameterCount, "Model C: blend parameters") + assertEquals(123, allBindings.size, "Model C: bindings (PART record excluded)") + assertEquals(11, warpBindings.size, "Model C: warp bindings") + assertEquals(105, drawableBindings.size, "Model C: mesh bindings") + assertEquals(7, rotationBindings.size, "Model C: rotation bindings") + assertEquals(145, nonNeutralForms, "Model C: non-neutral forms") + assertEquals(468, limitPoints, "Model C: limit points") + } + } + } + + /** + * Reads the sample's sibling `.cdi3.json`, or null when absent - the same basename + * discovery the document loader performs. + * + * @param File mocFile The `.moc3` sample. + * @return Cdi3Json? The parsed display info, or null. + */ + private fun siblingDisplayInfo(mocFile: File): Cdi3Json? { + val basename = Moc3Sidecars.basenameFor(mocFile.name) + val cdi3File = mocFile.parentFile.resolve("$basename.cdi3.json") + if (!cdi3File.isFile) { + return null + } + return Moc3.readCdi3(cdi3File.readText()) + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/uma/UmaDocumentRoundTripCorpusTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/uma/UmaDocumentRoundTripCorpusTest.kt new file mode 100644 index 0000000..3fa7fc9 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/uma/UmaDocumentRoundTripCorpusTest.kt @@ -0,0 +1,307 @@ +package org.umamo.interop.uma + +import org.umamo.format.FormatRegistry +import org.umamo.format.art.SourceArt +import org.umamo.format.binary.contentHashOf +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.interop.AtlasPageSet +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasPages +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.interop.moc3.import.moc3AtlasPages +import org.umamo.render.eval.CpuDeformationEvaluator +import org.umamo.render.eval.DeformedGeometry +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.visibleDrawableIds +import java.io.File +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The native format's whole-document gate over the corpus (docs/format/UMA.md §4-§6): every CMO3, every MOC3, + * and every layered artwork file imports, saves as UMA with its pixels, reopens, and compares identical and + * bit-exact across the puppet, the atlas, and the linked source art; every tile's PNG comes back byte for byte, + * and each drawable samples the same image bytes the source format's loader gave it; the saved file rewrites byte + * for byte; and the CPU evaluation of the reopened model matches the original's bit for bit at the default + * pose, the all-minimum and all-maximum poses, and eight seeded random ones. The models named for measurement + * print their save and open costs. + * + * Corpus-gated: `cmo3.probe` (every corpus .cmo3 by default), `moc3.samples` (the moc3 corpus directory, each + * moc's pages read beside it through its model3.json), and the PSD / CLIP / KRA files under test/corpus found by + * walking up from the working directory. Each format self-skips with a printed line when its samples are absent. + */ +class UmaDocumentRoundTripCorpusTest { + private val writer = UmaWriterInfo("Umamo", "corpus-test") + + private val evaluator = CpuDeformationEvaluator() + + // World position floats the default-pose evaluations produced, so a run can show it compared real geometry. + private var evaluatedPositionCount = 0L + + // Tile and page PNGs compared byte for byte after the reopen, so a run can show it compared real pixels. + private var comparedPngCount = 0L + + // Every sample's failure, so one run reports the whole corpus rather than its first broken sample. + private val failures = ArrayList() + + // The models whose save and open costs are recorded in the design plan. + private val measuredSamples = setOf("EricaTamamo.cmo3", "modelF.cmo3", "EricaTamamo.moc3", "modelF.moc3") + + /** + * Saves [model] as a whole document, reopens it, and fails on any difference, an unstable rewrite, a tile that + * did not come back, a drawable that samples other pixels, or an evaluation that no longer matches. + * + * @param String label The sample's name, for failures. + * @param PuppetModel model The imported model. + * @param UmaPixelSource pixels The pixels the save writes. + * @param AtlasPageSet? expectedPages The page set the source format's loader builds, or null when the pages + * derive. + */ + private fun assertRoundTrips(label: String, model: PuppetModel, pixels: UmaPixelSource, expectedPages: AtlasPageSet?) { + val writeStart = System.nanoTime() + val bytes = Uma.write(UmaDocumentBridge.documentOf(UmaModel.create(writer), model, pixels)) + val writeNanos = System.nanoTime() - writeStart + val readStart = System.nanoTime() + val document = Uma.read(bytes) + val reopened = UmaDocumentBridge.modelOf(document) + val readNanos = System.nanoTime() - readStart + val differences = documentDifferences(model, reopened) + assertTrue(differences.isEmpty(), "$label: ${differences.size} differences, first ${differences.take(20)}") + assertContentEquals(bytes, Uma.write(document), "$label: an unedited reopen rewrites byte for byte") + + val documentPages = UmaDocumentBridge.pagesOf(document) + for (tile in model.atlas.tiles) { + assertContentEquals(pixels.tile(tile.id.raw), documentPages.tilePng(tile.id), "$label: tile ${tile.id.raw}'s PNG") + comparedPngCount++ + } + if (expectedPages == null) { + assertEquals(null, documentPages.pageSet, "$label: derived pages store no page set") + } else { + assertSamePagesPerDrawable(label, expectedPages, assertNotNull(documentPages.pageSet, "$label: the render pages come back")) + } + assertEvaluationsMatch(label, model, reopened) + if (label in measuredSamples) { + println("[Umamo][uma] $label: ${"%.2f".format(bytes.size / (1024.0 * 1024.0))} MiB document, save ${writeNanos / 1_000_000} ms, open ${readNanos / 1_000_000} ms") + } + } + + /** + * Fails unless every drawable the source format's page set maps samples a page with the same bytes after the + * reopen, and the reopened set maps no drawable the source did not. + * + * @param String label The sample's name, for failures. + * @param AtlasPageSet expected The source format's page set. + * @param AtlasPageSet actual The reopened document's. + */ + private fun assertSamePagesPerDrawable(label: String, expected: AtlasPageSet, actual: AtlasPageSet) { + comparedPngCount += expected.pageBytes.size + val mismatched = + expected.atlasIndexByDrawableId.filter { (drawableId, pageIndex) -> + val reopenedIndex = actual.atlasIndexByDrawableId[drawableId] + reopenedIndex == null || !expected.pageBytes[pageIndex].contentEquals(actual.pageBytes[reopenedIndex]) + }.keys + assertTrue(mismatched.isEmpty(), "$label: ${mismatched.size} drawables sample other pixels after the reopen, first ${mismatched.take(10)}") + val extra = actual.atlasIndexByDrawableId.keys - expected.atlasIndexByDrawableId.keys + assertTrue(extra.isEmpty(), "$label: ${extra.size} drawables sample a page they did not before, first ${extra.take(10)}") + } + + /** + * Fails unless both models evaluate to the same bits at every sampled pose. + * + * @param String label The sample's name, for failures. + * @param PuppetModel expected The model before the round trip. + * @param PuppetModel actual The model after it. + */ + private fun assertEvaluationsMatch(label: String, expected: PuppetModel, actual: PuppetModel) { + val random = Random(20260917) + val poses = + listOf( + emptyMap(), + expected.parameters.associate { parameter -> parameter.id to parameter.min }, + expected.parameters.associate { parameter -> parameter.id to parameter.max }, + ) + List(8) { expected.parameters.associate { parameter -> parameter.id to parameter.min + random.nextFloat() * (parameter.max - parameter.min) } } + for ((poseIndex, pose) in poses.withIndex()) { + val expectedGeometry = evaluator.evaluate(expected, pose) + if (poseIndex == 0) { + // Two empty evaluations would match without comparing anything, so a model that draws something must + // evaluate to something. + val visible = expected.visibleDrawableIds() + val drawsSomething = expected.drawables.any { drawable -> drawable.mesh != null && drawable.id in visible } + assertTrue(!drawsSomething || expectedGeometry.worldPositions.values.any { positions -> positions.isNotEmpty() }, "$label: the evaluation is not empty") + evaluatedPositionCount += expectedGeometry.worldPositions.values.sumOf { positions -> positions.size.toLong() } + } + assertSameGeometry("$label pose $poseIndex", expectedGeometry, evaluator.evaluate(actual, pose)) + } + } + + /** + * Fails unless two evaluations hold the same drawables with the same bits. + * + * @param String label What is compared, for failures. + * @param DeformedGeometry expected The original model's evaluation. + * @param DeformedGeometry actual The reopened model's evaluation. + */ + private fun assertSameGeometry(label: String, expected: DeformedGeometry, actual: DeformedGeometry) { + assertEquals(expected.worldPositions.keys, actual.worldPositions.keys, "$label: visible drawables") + for ((drawableId, positions) in expected.worldPositions) { + val reopenedPositions = actual.worldPositions.getValue(drawableId) + assertTrue( + positions.size == reopenedPositions.size && positions.indices.all { valueIndex -> positions[valueIndex].toRawBits() == reopenedPositions[valueIndex].toRawBits() }, + "$label: ${drawableId.raw} world positions", + ) + assertEquals(expected.drawOrder[drawableId]?.toRawBits(), actual.drawOrder[drawableId]?.toRawBits(), "$label: ${drawableId.raw} draw order") + assertEquals(expected.opacity[drawableId]?.toRawBits(), actual.opacity[drawableId]?.toRawBits(), "$label: ${drawableId.raw} opacity") + } + } + + /** + * Runs [check] for one sample, recording its failure rather than stopping the corpus. + * + * @param String label The sample's name. + * @param Function check The sample's round trip. + */ + private fun recording(label: String, check: () -> Unit) { + try { + check() + } catch (failure: AssertionError) { + failures += "$label: ${failure.message}" + } catch (failure: Exception) { + failures += "$label: ${failure::class.simpleName}: ${failure.message}" + } + } + + /** + * Fails with every recorded sample failure, one per line. + * + * @param String corpus The corpus's name. + */ + private fun assertNoFailures(corpus: String) { + assertTrue(failures.isEmpty(), "${failures.size} $corpus samples failed:\n${failures.joinToString("\n") { failure -> failure.take(600) }}") + } + + /** + * Every corpus CMO3: tiles from its model images, and the images its drawables sample stored as its render pages. + */ + @Test + fun cmo3Corpus() { + val samples = System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { file -> file.isFile }.orEmpty() + if (samples.isEmpty()) { + println("no cmo3.probe samples; skipping the CMO3 document round trip") + return + } + for (sample in samples) { + recording(sample.name) { + val cmo3 = Cmo3.read(sample) + val root = cmo3.root as? CModelSource ?: error("${sample.name}: root is not a CModelSource") + val imported = Cmo3Import.importModelSource(root) + val resourceByTile = imported.atlasIngest.imageResourceByTile + val loaderPages = cmo3AtlasPages(root, cmo3::extractLayerPng) + val pixels = UmaPixelSource({ tileId -> resourceByTile[AtlasTileId(tileId)]?.let(cmo3::extractLayerPng) }, UmaRenderPagePixels.Stored(loaderPages.pageBytes, loaderPages.atlasIndexByDrawableId), null) + assertRoundTrips(sample.name, imported.puppet, pixels, loaderPages) + } + } + assertNoFailures("CMO3") + println( + "[Umamo][uma] ${samples.size} CMO3 samples round-trip as documents ($comparedPngCount PNGs and " + + "$evaluatedPositionCount default-pose world floats compared)", + ) + } + + /** + * Every corpus MOC3: no tiles, its pages stored as render pages from the files its model3.json names when they are + * there. + */ + @Test + fun moc3Corpus() { + val samples = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { directory -> directory.isDirectory } + ?.walkTopDown()?.filter { file -> file.isFile && file.extension == "moc3" }?.sortedBy { file -> file.path }?.toList().orEmpty() + if (samples.isEmpty()) { + println("no moc3.samples; skipping the MOC3 document round trip") + return + } + var pagedSamples = 0 + for (sample in samples) { + recording(sample.name) { + val mocDocument = Moc3.read(sample.readBytes()) + val model = Moc3Import.fromMocDocument(mocDocument, null) + val manifest = File(sample.parentFile, "${Moc3Sidecars.basenameFor(sample.name)}.model3.json").takeIf { file -> file.isFile }?.let { file -> Moc3.readModel3(file.readText()) } + val pageFiles = manifest?.fileReferences?.textures?.map { reference -> File(sample.parentFile, reference) }.orEmpty() + if (pageFiles.isEmpty() || pageFiles.any { file -> !file.isFile }) { + println("[Umamo][uma] ${sample.name}: its pages are not beside it, so only the model round-trips") + assertRoundTrips(sample.name, model, UmaPixelSource({ null }, UmaRenderPagePixels.Derived, null), null) + return@recording + } + pagedSamples++ + val loaderPages = moc3AtlasPages(mocDocument, pageFiles.map { file -> file.readBytes() }) + val pixels = UmaPixelSource({ null }, UmaRenderPagePixels.Stored(loaderPages.pageBytes, loaderPages.atlasIndexByDrawableId), null) + assertRoundTrips(sample.name, model, pixels, loaderPages) + } + } + assertNoFailures("MOC3") + assertTrue(pagedSamples > 0, "no MOC3 sample had its pages beside it, so the page leg compared nothing") + println("[Umamo][uma] ${samples.size} MOC3 samples round-trip as documents ($pagedSamples with pages; $comparedPngCount PNGs and $evaluatedPositionCount default-pose world floats compared)") + } + + /** + * Every layered artwork file in the corpus, imported as a fresh unpacked rig with its hashes. + */ + @Test + fun artworkCorpus() { + val samples = locateArtworkSamples() + if (samples.isEmpty()) { + println("no test/corpus artwork samples; skipping the artwork document round trip") + return + } + for (sample in samples) { + recording(sample.name) { + val bytes = sample.readBytes() + val codec = assertNotNull(FormatRegistry.detect(bytes, sample.name), "${sample.name}: detected") + val art = codec.read(bytes) as SourceArt + val result = SourceArtImport.fromSourceArt(art, ArtSourceDescriptor(sample.name, sample.path, codec.kind.extension, contentHashOf(bytes), sample.lastModified())) + val pngByTile = result.rasterByTile.mapKeys { (tileId, _) -> tileId.raw }.mapValues { (_, raster) -> PngCodec.write(RasterImage(raster.width, raster.height, raster.rgba)) } + assertTrue(result.puppet.sources.single().layers.isNotEmpty(), "${sample.name}: the inventory is not empty") + assertRoundTrips(sample.name, result.puppet, UmaPixelSource({ tileId -> pngByTile[tileId] }, UmaRenderPagePixels.Derived, null), null) + } + } + assertNoFailures("artwork") + println("[Umamo][uma] ${samples.size} artwork samples round-trip as documents ($comparedPngCount PNGs and $evaluatedPositionCount default-pose world floats compared)") + } + + /** + * Every PSD, CLIP, and KRA under test/corpus, found by walking up from the working directory. + * + * @return List The samples, empty when there is no corpus. + */ + private fun locateArtworkSamples(): List { + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return listOf("psd", "clip", "krita") + .flatMap { folder -> File(corpus, folder).listFiles { file -> file.isFile }.orEmpty().toList() } + .filter { file -> file.extension.lowercase() in setOf("psd", "clip", "kra") } + .sortedBy { file -> file.name } + } + directory = directory.parentFile + } + return emptyList() + } +} \ No newline at end of file diff --git a/module/interop/src/jvmTest/kotlin/org/umamo/interop/uma/UmaDocumentTooNewEntryTest.kt b/module/interop/src/jvmTest/kotlin/org/umamo/interop/uma/UmaDocumentTooNewEntryTest.kt new file mode 100644 index 0000000..da19658 --- /dev/null +++ b/module/interop/src/jvmTest/kotlin/org/umamo/interop/uma/UmaDocumentTooNewEntryTest.kt @@ -0,0 +1,185 @@ +package org.umamo.interop.uma + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins how a save treats an optional entry too new for this reader (docs/format/UMA.md §3.3): the document stays + * editable, a save carries the entry byte for byte while the model has nothing for its kind, and a save with content + * for the kind is refused rather than dropping what a newer writer put there. + * + * The fixtures re-zip a saved document with a newer manifest record, which only a foreign ZIP writer can build, so + * the test sits in jvmTest beside java.util.zip. + */ +class UmaDocumentTooNewEntryTest { + private val writer = UmaWriterInfo("Umamo", "test") + + private val tilePng: ByteArray = PngCodec.write(RasterImage(2, 2, ByteArray(16) { 40 })) + + /** + * A model with [atlas] and [sources] and nothing else. + * + * @param PuppetAtlas atlas The atlas. + * @param List sources The linked source art. + * @return PuppetModel The model. + */ + private fun modelOf(atlas: PuppetAtlas, sources: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + atlas = atlas, + sources = sources, + ).withDerivedRenderRoot() + + /** A model holding one tile on one page and one linked source. */ + private val fullModel: PuppetModel = + modelOf( + PuppetAtlas(pages = listOf(AtlasPage(4, 4)), tiles = listOf(AtlasTile(AtlasTileId("T"), "Tile", 2, 2))), + listOf(ArtSource(ArtSourceId("art-0"), "art.psd", null, "psd")), + ) + + /** A model with no atlas and no linked source art. */ + private val emptyModel: PuppetModel = modelOf(PuppetAtlas.Empty, emptyList()) + + /** + * The pixels a save of [fullModel] needs. + * + * @param UmaRenderPagePixels renderPages What the drawables sample. + * @return UmaPixelSource The pixels. + */ + private fun pixels(renderPages: UmaRenderPagePixels = UmaRenderPagePixels.Derived): UmaPixelSource = UmaPixelSource({ tilePng }, renderPages, null) + + /** + * [bytes] re-zipped with the manifest record of [kind] declared too new for this reader and optional. + * + * @param ByteArray bytes A UMA archive. + * @param UmaEntryKind kind The kind whose record to age forward. + * @return ByteArray The archive. + */ + private fun withTooNewRecord(bytes: ByteArray, kind: UmaEntryKind): ByteArray { + val output = ByteArrayOutputStream() + ZipInputStream(ByteArrayInputStream(bytes)).use { input -> + ZipOutputStream(output).use { zip -> + while (true) { + val entry = input.nextEntry ?: break + var contents = input.readBytes() + if (entry.name == "manifest.json") { + val manifest = Json.parseToJsonElement(contents.decodeToString()).jsonObject + val records = + manifest.getValue("entries").jsonArray.map { record -> + if (record.jsonObject["kind"] == JsonPrimitive(kind.wireName)) { + JsonObject(record.jsonObject + mapOf("version" to JsonPrimitive(2), "minVersion" to JsonPrimitive(2), "required" to JsonPrimitive(false))) + } else { + record + } + } + contents = Json.encodeToString(JsonObject.serializer(), JsonObject(manifest + ("entries" to JsonArray(records)))).encodeToByteArray() + } + zip.putNextEntry(ZipEntry(entry.name)) + zip.write(contents) + zip.closeEntry() + } + } + } + return output.toByteArray() + } + + /** + * Each archive entry's uncompressed bytes, by name. + * + * @param ByteArray bytes A ZIP archive. + * @return Map The contents. + */ + private fun contentsOf(bytes: ByteArray): Map { + val contents = LinkedHashMap() + ZipInputStream(ByteArrayInputStream(bytes)).use { input -> + while (true) { + val entry = input.nextEntry ?: break + contents[entry.name] = input.readBytes() + } + } + return contents + } + + /** + * A too-new sources entry is carried through a save of a model that links no source art, and refuses a save of + * one that does. + */ + @Test + fun tooNewSourcesEntryIsCarriedUntilTheModelLinksArt() { + val saved = Uma.write(UmaDocumentBridge.documentOf(UmaModel.create(writer), fullModel, pixels())) + val aged = withTooNewRecord(saved, UmaEntryKind.Sources) + val document = Uma.read(aged) + assertFalse(document.isReadOnly, "an optional entry leaves the document editable") + assertTrue(document.holdsTooNewEntry(UmaEntryKind.Sources)) + val reopened = UmaDocumentBridge.modelOf(document) + assertTrue(reopened.sources.isEmpty(), "the carried entry links nothing") + + val resaved = Uma.write(UmaDocumentBridge.documentOf(document, reopened, pixels())) + assertContentEquals(contentsOf(aged).getValue("source/index.json"), contentsOf(resaved).getValue("source/index.json"), "the entry survives the save") + assertTrue(Uma.read(resaved).holdsTooNewEntry(UmaEntryKind.Sources), "and is still carried") + + val failure = assertFailsWith { UmaDocumentBridge.documentOf(document, fullModel, pixels()) } + assertEquals("source/index.json", failure.path, "the refusal names the carried entry") + } + + /** + * A too-new textures entry is carried, pixel entries and all, through a save of a model with no atlas, and refuses + * a save with an atlas or stored render pages. + */ + @Test + fun tooNewTexturesEntryIsCarriedUntilTheModelHasAnAtlas() { + val saved = Uma.write(UmaDocumentBridge.documentOf(UmaModel.create(writer), fullModel, pixels())) + val aged = withTooNewRecord(saved, UmaEntryKind.Textures) + val document = Uma.read(aged) + assertFalse(document.isReadOnly, "an optional entry leaves the document editable") + assertTrue(document.holdsTooNewEntry(UmaEntryKind.Textures)) + + val resaved = Uma.write(UmaDocumentBridge.documentOf(document, emptyModel, pixels())) + val agedContents = contentsOf(aged) + val resavedContents = contentsOf(resaved) + assertContentEquals(agedContents.getValue("textures/index.json"), resavedContents.getValue("textures/index.json"), "the index survives the save") + assertContentEquals(agedContents.getValue("textures/tile-0.png"), resavedContents.getValue("textures/tile-0.png"), "and so do the pixels it names") + + assertFailsWith("a model with an atlas") { UmaDocumentBridge.documentOf(document, fullModel.copy(sources = emptyList()), pixels()) } + assertFailsWith("stored render pages") { + UmaDocumentBridge.documentOf(document, emptyModel, pixels(UmaRenderPagePixels.Stored(listOf(tilePng), emptyMap()))) + } + } +} \ No newline at end of file diff --git a/module/reimport/build.gradle.kts b/module/reimport/build.gradle.kts new file mode 100644 index 0000000..7377c43 --- /dev/null +++ b/module/reimport/build.gradle.kts @@ -0,0 +1,46 @@ +// :reimport — non-destructive reconcile over the model's source bindings. Depends on :format (the +// re-read art), :runtime (the bindings live on the model's atlas tiles), and :interop (the bridge that +// births a layer's mesh and mints the additions for the layers a file gained). + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) +} + +kotlin { + jvmToolchain(21) + + jvm() + + android { + namespace = "org.umamo.reimport" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + commonMain { + dependencies { + implementation(project(":format")) + implementation(project(":interop")) + // The content hash the watcher compares a save against, and okio (its `api`), which the + // polling watcher stats files through - the one file-system API that runs on every + // Kotlin target, so nothing here is JVM-bound. + implementation(project(":storage")) + api(project(":runtime")) + // The watch coordinator is coroutine-driven (settle timers, the idle wait); `api` because + // its scope and flows are its public surface. + api(libs.kotlinxCoroutinesCore) + } + } + commonTest { + dependencies { + implementation(kotlin("test")) + // runTest + the virtual clock the coordinator's settle and the watcher's polling are tested on. + implementation(libs.kotlinxCoroutinesTest) + // An in-memory file system for the polling watcher's test. + implementation(libs.okio.fakefilesystem) + } + } + } +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/ArtworkReloadPlanner.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/ArtworkReloadPlanner.kt new file mode 100644 index 0000000..6ba26a6 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/ArtworkReloadPlanner.kt @@ -0,0 +1,545 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.art.isFullyTransparent +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.ArtworkReload +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.ReplacedTile +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.isUntouchedBirthQuad +import org.umamo.runtime.model.reloadTileId +import org.umamo.runtime.model.storedToArtAffineForTile + +/* + * The reload planner: the re-read file's matched and added halves turned into the model delta a + * reload commits. Pure over the model and the art - the pixels of the OLD tiles come in through a + * callback, the pixels of the new ones go out beside the delta - so the same plan runs against the + * live model and against the operation strip's base when a row is adjusted. + * + * What it never does: touch a tile whose layer the file lost without a confident match (the reconcile + * flags it for review), change a drawable's positions, or delete rig work - the one thing it removes + * is a fresh, untouched drawable whose layer a lost layer's rig work claims, and only when the caller + * names it. A drawable's mesh changes in only two ways: an untouched birth quad is re-born over the + * new art, and an edited mesh keeps its vertices with its texture coordinates carried so each vertex + * samples the canvas pixel it did before - Cubism's own re-import behavior, where the art moves under + * a mesh that stays. Its visibility follows the file's eye toggle only while it still shows the state + * the file last had: a toggle the rigger made in the outliner is rig work and stays. + */ + +/** + * A planned reload: the delta, the new tiles' pixels, the reconcile it followed, its notes, and what + * the matcher proposed but did not apply. + * + * @property ArtworkReload reload The model delta. + * @property Map rasterByTile Each new tile's pixels, by its new id. + * @property ReconcileReport report The classification the plan followed (review items included). + * @property List notices What the reload could not carry as drawn, in document order. + * @property Map leftovers Each lost binding's best candidate that fell under the bar, by + * its lost key - scored before anything was minted, so a candidate the plan then minted a fresh + * drawable for is still named; what the caller publishes for the review chips. + */ +class ReloadPlan( + val reload: ArtworkReload, + val rasterByTile: Map, + val report: ReconcileReport, + val notices: List, + val leftovers: Map = emptyMap(), +) + +/** One tile's replacement and everything that came with it. */ +private class TileReplacement( + val replaced: ReplacedTile, + val raster: LayerRaster, + val meshes: Map, + val outgrown: List, +) + +/** Half a pixel: how far a mesh may fall short of the opaque art before it counts as outgrown. */ +private const val COVERAGE_TOLERANCE = 0.5f + +/** + * Plans reloads and relinks. See the file comment for the rules. + */ +object ArtworkReloadPlanner { + /** + * Plans re-reading one listed file into [model]. + * + * A bound tile is replaced when its layer's pixels, size, or canvas bounds differ from what the + * document holds; an unchanged layer costs nothing. A binding whose key the art lost is scored by + * [matcher] against the layers no tile is bound to BEFORE anything is minted: at or above + * [matchThreshold] its tile takes the best candidate's art (the layer re-created under a new key), so + * the rig work follows the layer and no fresh drawable is minted beside it; below the bar the layer + * is minted and the binding is left for review, the proposal kept in [ReloadPlan.leftovers] so the + * row can still offer it (accepting then retires the fresh drawable). The remaining raster layers + * no tile is bound to are minted through the bridge under the same source - except those the rigger + * ignored ([ArtSourceLayer.ignored]), which stay out however many reloads find them. A drawable whose + * layer's eye toggle changed since the last read follows it while it still shows the old state + * ([ArtworkReload.drawableVisibility]); one the rigger toggled since is left alone. The source record + * takes the inventory as just read. Null when the file is not one the model lists or when nothing at + * all changed - not even the inventory - so a reload with nothing to do pushes no step. + * + * @param PuppetModel model The model the plan applies to. + * @param ArtSourceId sourceId The listed file being re-read. + * @param SourceArt art The file as just read. + * @param SourceArtImportOptions options The threshold and margin every re-born quad and added layer use. + * @param Function oldRasterOf The document's pixels for a tile, or null when it has none. + * @param String? contentHash The whole-file content hash of the bytes [art] was read from, + * recorded on the refreshed source; null keeps the record's. A hash that changed while nothing in the + * layers did does not by itself make a plan - the watcher acknowledges such a save instead. + * @param ArtSourceDescriptor? replacement The file the record is repointed to (Replace Artwork): its + * name, path, and format take over, every binding the new art cannot resolve reads as SourceReplaced, + * and the plan is made even when no layer changed. Layers no tile is bound to are NOT minted under + * a replacement - they are the candidates the unresolved bindings are matched against, and a Reload + * brings in whatever is still unbound once the review is done. Null re-reads the record's own file. + * @param List inventory The inventory of [art], for a caller that already computed it + * (it hashes every layer's pixels, so one read file should pay for it once); computed here by default. + * @param Long? lastModified The file's modification time when [art] was read, recorded on + * the refreshed source; null keeps the record's. A replacement records its own descriptor's instead. + * @param Float matchThreshold The confidence, 0..1 inclusive, at or above which a lost + * binding takes its best candidate in this plan. + * @param LayerMatcher matcher The matcher that ranks a lost binding's candidates. + * @return ReloadPlan? The plan, or null when there is nothing to commit. + */ + fun plan( + model: PuppetModel, + sourceId: ArtSourceId, + art: SourceArt, + options: SourceArtImportOptions, + oldRasterOf: (AtlasTileId) -> LayerRaster?, + contentHash: String? = null, + replacement: ArtSourceDescriptor? = null, + inventory: List = SourceArtImport.inventoryOf(art), + lastModified: Long? = null, + matchThreshold: Float = InventoryLayerMatcher.DEFAULT_THRESHOLD, + matcher: LayerMatcher = InventoryLayerMatcher, + ): ReloadPlan? { + val source = model.sources.firstOrNull { candidate -> candidate.id == sourceId } ?: return null + val layersByKey = rasterLayersByKey(art) + val boundTiles = model.atlas.tiles.filter { tile -> tile.source?.sourceId == sourceId } + val keyReport = KeyReconciler.reconcile(boundTiles.mapNotNull { tile -> tile.source }, art) + // The matcher runs over the review half before anything is minted: a lost layer's best candidate + // at or above the bar is that layer re-created under a new key, and the rig work over the lost + // layer's tile follows it. + val suggestions = suggestionsAgainstRead(model, sourceId, inventory, oldRasterOf, { key -> layersByKey[key]?.raster }, matcher) + val accepted = confidentMatches(suggestions, matchThreshold) + // The rigger's ignore marks live on the record's rows: a marked layer is left out of the rig however + // many reloads find it unbound. + val ignoredKeys = source.layers.filter { row -> row.ignored }.mapTo(HashSet()) { row -> row.key } + + fun reboundFor(binding: SourceLayerRef): ReconcileResult.Rebound? { + val candidateKey = accepted[binding.layerKey] ?: return null + return ReconcileResult.Rebound(binding, candidateKey, suggestions.getValue(binding.layerKey).score) + } + val report = + ReconcileReport( + keyReport.results.mapNotNull { result -> + when (result) { + is ReconcileResult.Matched -> reboundFor(result.binding) ?: result + is ReconcileResult.NeedsReview -> + reboundFor(result.binding) ?: if (replacement != null) result.copy(reason = ReviewReason.SourceReplaced) else result + is ReconcileResult.Added -> result.takeIf { added -> added.layerKey !in accepted.values && added.layerKey !in ignoredKeys } + is ReconcileResult.Rebound -> result + } + }, + ) + val oldInventoryByKey = source.layers.associateBy { layer -> layer.key } + val taken = model.atlas.tiles.mapTo(HashSet()) { tile -> tile.id } + val replaced = ArrayList() + val meshes = LinkedHashMap() + val outgrown = ArrayList() + val rasters = LinkedHashMap() + val notices = ArrayList() + val emptied = ArrayList() + val visibility = LinkedHashMap() + for (tile in boundTiles) { + val ref = tile.source ?: continue + val candidateKey = accepted[ref.layerKey] + if (candidateKey != null) { + // The lost (or erased) layer's tile takes the re-created layer, the mesh over it carried the + // way a relink carries it. + val candidate = layersByKey[candidateKey] ?: continue + followVisibility(model, tile, oldInventoryByKey[ref.layerKey], candidate, visibility) + val candidateRef = SourceLayerRef(sourceId, candidateKey, stableKey = candidate.idIsStable) + val rebinding = + replaceTile(model, tile, candidate, candidateRef, oldInventoryByKey[ref.layerKey], options, oldRasterOf, taken, notices, force = true) + ?: continue + replaced.add(rebinding.replaced) + rasters[rebinding.replaced.tile.id] = rebinding.raster + meshes.putAll(rebinding.meshes) + outgrown.addAll(rebinding.outgrown) + continue + } + val layer = layersByKey[ref.layerKey] ?: continue + followVisibility(model, tile, oldInventoryByKey[ref.layerKey], layer, visibility) + if (layer.raster.isFullyTransparent()) { + // Erased to nothing rather than deleted: the tile keeps its art and the binding goes to + // review, since the artist may have meant either (deleted the layer another way, or left + // it blank on purpose). + notices.add(SourceArtImportNotice.EmptyLayer(layer.name)) + emptied.add(ReconcileResult.NeedsReview(ref, ReviewReason.LayerEmptied)) + continue + } + val tileReplacement = + replaceTile(model, tile, layer, ref, oldInventoryByKey[ref.layerKey], options, oldRasterOf, taken, notices, force = false) + ?: continue + replaced.add(tileReplacement.replaced) + rasters[tileReplacement.replaced.tile.id] = tileReplacement.raster + meshes.putAll(tileReplacement.meshes) + outgrown.addAll(tileReplacement.outgrown) + } + val addedKeys = report.results.filterIsInstance().mapTo(HashSet()) { result -> result.layerKey } + val added = + if (addedKeys.isEmpty() || replacement != null) { + null + } else { + // The whole file goes to the bridge with the gained layers named, so each new drawable is + // placed among the existing ones where the file puts it. + SourceArtImport.additionsFor(art, ArtSourceDescriptor(source.name, source.path, source.format), options, model, underSource = sourceId, layerKeys = addedKeys, inventory = inventory) + } + if (added != null) { + rasters.putAll(added.rasterByTile) + notices.addAll(added.notices) + } + // The file's bindings after the plan: a rebound tile binds its candidate. + val boundKeys = boundTiles.mapNotNullTo(HashSet()) { tile -> tile.source?.let { ref -> accepted[ref.layerKey] ?: ref.layerKey } } + val layers = inventoryWithMissing(source.layers, inventory, boundKeys, lostByReplacement = replacement != null) + val refreshed = + if (replacement == null) { + source.copy(layers = layers, contentHash = contentHash ?: source.contentHash, lastModified = lastModified ?: source.lastModified) + } else { + source.copy( + name = replacement.name, + path = replacement.path, + format = replacement.format, + layers = layers, + contentHash = contentHash, + lastModified = replacement.lastModified, + ) + } + // The hash and the time say when the file was read, not what changed in it: masked out, so a save + // that changed no layer plans nothing (the watcher acknowledges it instead). + if (replacement == null && replaced.isEmpty() && added == null && refreshed.copy(contentHash = source.contentHash, lastModified = source.lastModified) == source) { + return null + } + val leftovers = suggestions.filterKeys { lostKey -> lostKey !in accepted } + return ReloadPlan( + ArtworkReload(refreshed, replaced, meshes, added?.additions, outgrown, drawableVisibility = visibility), + rasters, + ReconcileReport(report.results + emptied), + notices, + leftovers, + ) + } + + /** + * Plans rebinding every tile in [accepted] to the layer named beside it, with that layer's art pulled + * in - Match Automatically's step, a review row's accepted proposal, and the relink a tile chip + * makes, once per pair. A tile may come from another listed file (a relink across files): its old + * inventory row is read from that file, so the carried mesh still knows where its art sat. A pair + * whose tile the model lacks, whose key names no raster layer, or whose tile already holds exactly + * that binding over the same art is skipped; the file's record takes the inventory as just read, the + * lost rows the accepted tiles no longer bind dropped. The tiles in [retire] that are bound to a + * claimed key and carry no rig work ([retirableTiles]) leave with their drawables - the fresh + * drawable a reload minted for the layer, named by the proposal being accepted - so accepting after + * a reload merges rather than doubles; a tile with rig work over it is never retired, whatever the + * caller names. Null when the file is unknown or no pair could be applied. + * + * @param PuppetModel model The model the plan applies to. + * @param ArtSourceId sourceId The file whose layers the tiles move to. + * @param SourceArt art The file as just read. + * @param List accepted Each tile and the key of the layer it takes. + * @param SourceArtImportOptions options The threshold and margin a re-born quad uses. + * @param Function oldRasterOf The document's pixels for a tile, or null when it has none. + * @param String? contentHash The whole-file hash of the bytes [art] came from; null keeps the record's. + * @param List inventory The inventory of [art], for a caller that already computed it; computed here by default. + * @param Long? lastModified The file's modification time when [art] was read; null keeps the record's. + * @param Set retire The tiles the caller's proposal named as going with the move. + * @return ReloadPlan? The plan, or null when nothing could be rebound. + */ + fun planMatches( + model: PuppetModel, + sourceId: ArtSourceId, + art: SourceArt, + accepted: List>, + options: SourceArtImportOptions, + oldRasterOf: (AtlasTileId) -> LayerRaster?, + contentHash: String? = null, + inventory: List = SourceArtImport.inventoryOf(art), + lastModified: Long? = null, + retire: Set = emptySet(), + ): ReloadPlan? { + val source = model.sources.firstOrNull { candidate -> candidate.id == sourceId } ?: return null + val layersByKey = rasterLayersByKey(art) + val taken = model.atlas.tiles.mapTo(HashSet()) { tile -> tile.id } + val replaced = ArrayList() + val meshes = LinkedHashMap() + val outgrown = ArrayList() + val rasters = LinkedHashMap() + val notices = ArrayList() + val results = ArrayList() + val rebound = HashMap() + val claiming = accepted.mapTo(HashSet()) { (tileId, _) -> tileId } + val retired = LinkedHashSet() + for ((tileId, key) in accepted) { + val tile = model.atlas.tileById[tileId] ?: continue + val layer = layersByKey[key] ?: continue + val ref = SourceLayerRef(sourceId, key, stableKey = layer.idIsStable) + val oldRef = tile.source + val oldInventory = oldRef?.let { previous -> inventoryRowOf(model, previous) } + val replacement = + replaceTile(model, tile, layer, ref, oldInventory, options, oldRasterOf, taken, notices, force = oldRef != ref) ?: continue + replaced.add(replacement.replaced) + rasters[replacement.replaced.tile.id] = replacement.raster + meshes.putAll(replacement.meshes) + outgrown.addAll(replacement.outgrown) + results.add(ReconcileResult.Matched(ref, key)) + rebound[tileId] = key + if (retire.isNotEmpty()) { + retired.addAll(retirableTiles(model, sourceId, key, except = claiming).filter { candidate -> candidate in retire }) + } + } + if (replaced.isEmpty()) { + return null + } + // The file's bindings after the plan: a rebound tile binds its new key whichever file it came + // from, a retired tile nothing, every other tile of this file what it did. + val boundKeys = + model.atlas.tiles.filter { tile -> tile.id !in retired }.mapNotNullTo(HashSet()) { tile -> + rebound[tile.id] ?: tile.source?.takeIf { previous -> previous.sourceId == sourceId }?.layerKey + } + val layers = inventoryWithMissing(source.layers, inventory, boundKeys, untouchedKeys = boundKeys - rebound.values.toSet()) + val refreshed = source.copy(layers = layers, contentHash = contentHash ?: source.contentHash, lastModified = lastModified ?: source.lastModified) + return ReloadPlan(ArtworkReload(refreshed, replaced, meshes, additions = null, outgrown = outgrown, retiredTiles = retired.toList()), rasters, ReconcileReport(results), notices) + } + + /** + * The inventory row a binding names, read from the binding's own file - which need not be the file + * a tile is moving to. + * + * @param PuppetModel model The model the files are listed in. + * @param SourceLayerRef ref The binding. + * @return ArtSourceLayer? The row, or null when the file or the key is not listed. + */ + private fun inventoryRowOf(model: PuppetModel, ref: SourceLayerRef): ArtSourceLayer? = + model.sources.firstOrNull { candidate -> candidate.id == ref.sourceId }?.layers?.firstOrNull { row -> row.key == ref.layerKey } + + /** + * Plans rebinding one tile to [ref]'s layer with that layer's art pulled in: the tile is replaced + * whenever the binding changes or the layer's art differs from what the tile holds, and the layer's + * file takes the inventory as just read. Null when the tile or the file is unknown, the layer is not + * a raster layer with art, or the tile already holds exactly this binding and this art - the caller + * then has nothing to pull and rewrites the binding alone if it differs. The one-pair form of + * [planMatches]; the replacement's binding says what the reader says about the key's strength. + * + * @param PuppetModel model The model the plan applies to. + * @param AtlasTileId tileId The tile being rebound. + * @param SourceLayerRef ref The binding it takes. + * @param SourceArt art The file [ref] names, as just read. + * @param SourceArtImportOptions options The threshold and margin a re-born quad uses. + * @param Function oldRasterOf The document's pixels for a tile, or null when it has none. + * @param List inventory The inventory of [art], for a caller that already computed it; computed here by default. + * @return ReloadPlan? The plan, or null when there is nothing to pull. + */ + fun planRelink( + model: PuppetModel, + tileId: AtlasTileId, + ref: SourceLayerRef, + art: SourceArt, + options: SourceArtImportOptions, + oldRasterOf: (AtlasTileId) -> LayerRaster?, + inventory: List = SourceArtImport.inventoryOf(art), + ): ReloadPlan? = planMatches(model, ref.sourceId, art, listOf(tileId to ref.layerKey), options, oldRasterOf, inventory = inventory) + + /** + * The raster layers of [art] by key - the only layers a tile can be bound to. + * + * @param SourceArt art The file as read. + * @return Map The raster layers, keyed by the reader's key. + */ + private fun rasterLayersByKey(art: SourceArt): Map = + art.layers.filter { layer -> layer.kind == SourceLayerKind.Raster }.associateBy { layer -> layer.id.raw } + + /** + * Records, for the drawables over [tile], the visibility the file's eye toggle now asks for, when it + * changed since the last read: a drawable still showing the OLD file state follows the new one; a + * drawable the rigger toggled since (its flag already differs from the old state) is left alone, since + * that toggle is rig work. A document that never recorded the old state cannot tell the two apart and + * records nothing. + * + * @param PuppetModel model The model the tile lives in. + * @param AtlasTile tile The tile whose drawables are considered. + * @param ArtSourceLayer? oldInventory The layer's inventory row at the last read, or null. + * @param SourceLayer layer The layer as read now. + * @param MutableMap visibility Appended with each drawable that follows, keyed by its id. + */ + private fun followVisibility( + model: PuppetModel, + tile: AtlasTile, + oldInventory: ArtSourceLayer?, + layer: SourceLayer, + visibility: MutableMap, + ) { + val oldVisible = oldInventory?.visible ?: return + if (oldVisible == layer.visible) { + return + } + for (drawable in model.drawables) { + if (drawable.atlasTileId == tile.id && drawable.isVisible == oldVisible) { + visibility[drawable.id] = layer.visible + } + } + } + + /** + * Replaces one tile with [layer]'s art when the art differs from what the tile holds (or when + * [force] says the tile must change regardless, a rebinding), deciding each drawable's mesh over it. + * + * @param PuppetModel model The model the tile lives in. + * @param AtlasTile tile The tile being replaced. + * @param SourceLayer layer The layer whose art it takes. + * @param SourceLayerRef ref The binding the replacement carries. + * @param ArtSourceLayer? oldInventory The layer's inventory row at the last read, for the old + * art frame's canvas origin; null when the document never recorded one. + * @param SourceArtImportOptions options The threshold and margin a re-born quad uses. + * @param Function oldRasterOf The document's pixels for the tile. + * @param MutableSet taken Every tile id in use; the new id is added to it. + * @param MutableList notices Appended with anything the replacement could not carry. + * @param Boolean force Replace even when the art is unchanged. + * @return TileReplacement? The replacement, or null when there is nothing to change. + */ + private fun replaceTile( + model: PuppetModel, + tile: AtlasTile, + layer: SourceLayer, + ref: SourceLayerRef, + oldInventory: ArtSourceLayer?, + options: SourceArtImportOptions, + oldRasterOf: (AtlasTileId) -> LayerRaster?, + taken: MutableSet, + notices: MutableList, + force: Boolean, + ): TileReplacement? { + val raster = layer.raster + val old = oldRasterOf(tile.id) + val boundsUnchanged = + oldInventory != null && + oldInventory.left == layer.bounds.left && + oldInventory.top == layer.bounds.top && + oldInventory.width == layer.bounds.width && + oldInventory.height == layer.bounds.height + val pixelsUnchanged = + old != null && old.width == raster.width && old.height == raster.height && old.rgba.contentEquals(raster.rgba) + if (!force && boundsUnchanged && pixelsUnchanged) { + return null + } + // A layer erased to nothing has no art to give: the tile keeps what it has, and the note says why. + val analysis = layer.analyzeAlpha(alphaThreshold = options.alphaThreshold) + if (analysis == null) { + notices.add(SourceArtImportNotice.EmptyLayer(layer.name)) + return null + } + val newId = reloadTileId(tile.id, taken) + taken.add(newId) + val newTile = + AtlasTile( + id = newId, + name = layer.name, + width = raster.width, + height = raster.height, + placement = null, + source = ref, + pinned = tile.pinned, + replaces = tile.id, + ) + // The old art frame's canvas origin: the inventory's record of where the layer sat, else the + // layer's own bounds now (a document that never recorded it can only assume the art stayed put). + val oldLeft = (oldInventory?.left ?: layer.bounds.left).toFloat() + val oldTop = (oldInventory?.top ?: layer.bounds.top).toFloat() + val newLeft = layer.bounds.left.toFloat() + val newTop = layer.bounds.top.toFloat() + val opaqueOnCanvas = + LayerBounds( + left = layer.bounds.left + analysis.opaqueBounds.left, + top = layer.bounds.top + analysis.opaqueBounds.top, + width = analysis.opaqueBounds.width, + height = analysis.opaqueBounds.height, + ) + val storedToArt = model.atlas.storedToArtAffineForTile(tile.id) + val meshes = LinkedHashMap() + val outgrown = ArrayList() + for (drawable in model.drawables) { + if (drawable.atlasTileId != tile.id) { + continue + } + val mesh = drawable.mesh ?: continue + if (storedToArt == null) { + // The tile's mapping cannot be read (a placement naming a page the atlas lacks); the mesh + // is left as it is rather than guessed at. + continue + } + val artUvs = applyUvAffine(mesh.uvs, storedToArt) + if (mesh.isUntouchedBirthQuad(artUvs, tile.width, tile.height, oldLeft, oldTop)) { + val reborn = SourceArtImport.birthMeshFor(layer, options.alphaThreshold, options.birthMeshMargin) ?: continue + meshes[drawable.id] = reborn + continue + } + // Canvas-attached: the vertex stays where it is and keeps sampling the canvas pixel under it, + // so the coordinate moves from the old art frame to the new one through the bounds delta. + val carried = FloatArray(artUvs.size) + for (vertex in 0 until artUvs.size / 2) { + carried[vertex * 2] = (artUvs[vertex * 2] * tile.width + oldLeft - newLeft) / raster.width + carried[vertex * 2 + 1] = (artUvs[vertex * 2 + 1] * tile.height + oldTop - newTop) / raster.height + } + meshes[drawable.id] = DrawableMesh(mesh.positions, carried, mesh.indices) + if (!covers(mesh.positions, opaqueOnCanvas)) { + outgrown.add(drawable.id) + } + } + return TileReplacement(ReplacedTile(tile.id, newTile), raster, meshes, outgrown) + } + + /** + * Whether a mesh's canvas extent contains the opaque art's canvas rectangle, within half a pixel. + * + * @param FloatArray positions The mesh's canvas positions, x then y per vertex. + * @param LayerBounds opaque The opaque art's rectangle on the canvas. + * @return Boolean True when the art lies inside the mesh's reach. + */ + private fun covers(positions: FloatArray, opaque: LayerBounds): Boolean { + if (positions.size < 2) { + return false + } + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + for (vertex in 0 until positions.size / 2) { + val x = positions[vertex * 2] + val y = positions[vertex * 2 + 1] + minX = minOf(minX, x) + minY = minOf(minY, y) + maxX = maxOf(maxX, x) + maxY = maxOf(maxY, y) + } + return minX <= opaque.left + COVERAGE_TOLERANCE && + minY <= opaque.top + COVERAGE_TOLERANCE && + maxX >= opaque.left + opaque.width - COVERAGE_TOLERANCE && + maxY >= opaque.top + opaque.height - COVERAGE_TOLERANCE + } +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/InventoryLayerMatcher.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/InventoryLayerMatcher.kt new file mode 100644 index 0000000..1b03a2b --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/InventoryLayerMatcher.kt @@ -0,0 +1,276 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.runtime.model.ArtSourceLayer +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min + +/* + * The matcher over what the inventory knows plus, when the file could be read, the pixels: a layer + * that kept its pixels under a new name is recognized by its content hash outright; otherwise the + * name, the folder, where it sits on the canvas, how big it is, and what it looks like each vote, + * and the votes are averaged over the signals that could be read. Pixels are compared only for the + * candidates the metadata already likes, so a file of hundreds of layers costs a handful of small + * resamples, not hundreds of decodes. + */ + +/** The weight each signal carries in the combined score. */ +private const val WEIGHT_NAME = 0.35f +private const val WEIGHT_PATH = 0.10f +private const val WEIGHT_BOUNDS = 0.20f +private const val WEIGHT_SIZE = 0.10f +private const val WEIGHT_PIXELS = 0.25f + +/** How many metadata-ranked candidates have their pixels compared. */ +private const val PIXEL_CANDIDATES = 5 + +/** The grid both rasters are resampled to for the pixel comparison. */ +private const val PIXEL_GRID = 32 + +/** The alpha byte at or above which a resampled pixel counts as opaque. */ +private const val OPAQUE_ALPHA = 128 + +/** + * The [LayerMatcher] the Sources space and Match Automatically use. See the file comment. + */ +object InventoryLayerMatcher : LayerMatcher { + /** The confidence at or above which Match Automatically applies a match unasked, as a fraction. */ + const val DEFAULT_THRESHOLD: Float = 0.7f + + /** + * Ranks [candidates] for [missing]: metadata first, then the pixels of the best few. + * + * @param ArtSourceLayer missing The lost layer as the inventory recorded it. + * @param LayerRaster? missingRaster The pixels the document holds for it, or null. + * @param List candidates The layers it could move to. + * @return List Every candidate scored, best first. + */ + override fun rank(missing: ArtSourceLayer, missingRaster: LayerRaster?, candidates: List): List { + val byMetadata = + candidates + .map { candidate -> candidate to metadataSignals(missing, candidate.row) } + .sortedWith(compareByDescending> { (_, signals) -> combine(signals) }.thenBy { (candidate, _) -> candidate.row.name }) + return byMetadata + .mapIndexed { index, (candidate, signals) -> + val pixels = + if (missingRaster != null && index < PIXEL_CANDIDATES) { + candidate.raster()?.let { raster -> pixelSimilarity(missingRaster, raster) } + } else { + null + } + val scored = signals.copy(pixels = pixels) + LayerMatch(candidate.row.key, combine(scored), scored) + } + .sortedWith(compareByDescending { match -> match.score }.thenBy { match -> candidates.first { candidate -> candidate.row.key == match.key }.row.name }) + } + + /** + * The signals the inventory alone can score. + * + * @param ArtSourceLayer missing The lost layer. + * @param ArtSourceLayer candidate The candidate. + * @return MatchSignals The scores, pixels unset. + */ + private fun metadataSignals(missing: ArtSourceLayer, candidate: ArtSourceLayer): MatchSignals { + val missingBounds = boundsOf(missing) + val candidateBounds = boundsOf(candidate) + val extentKnown = missingBounds.area > 0L && candidateBounds.area > 0L + return MatchSignals( + name = nameSimilarity(missing.name, candidate.name), + path = pathAgreement(missing.groupPath, candidate.groupPath), + bounds = if (extentKnown) missingBounds.intersectionOverUnion(candidateBounds) else null, + size = if (extentKnown) sizeSimilarity(missingBounds, candidateBounds) else null, + pixels = null, + hashEqual = missing.contentHash != null && missing.contentHash == candidate.contentHash, + ) + } + + /** + * The combined confidence: 1 on a content-hash match, else the weighted mean of the signals that + * could be scored. + * + * @param MatchSignals signals The per-signal scores. + * @return Float The confidence, 0..1. + */ + private fun combine(signals: MatchSignals): Float { + if (signals.hashEqual) { + return 1f + } + var total = WEIGHT_NAME * signals.name + WEIGHT_PATH * signals.path + var weight = WEIGHT_NAME + WEIGHT_PATH + val bounds = signals.bounds + if (bounds != null) { + total += WEIGHT_BOUNDS * bounds + weight += WEIGHT_BOUNDS + } + val size = signals.size + if (size != null) { + total += WEIGHT_SIZE * size + weight += WEIGHT_SIZE + } + val pixels = signals.pixels + if (pixels != null) { + total += WEIGHT_PIXELS * pixels + weight += WEIGHT_PIXELS + } + return (total / weight).coerceIn(0f, 1f) + } + + /** + * A layer row's canvas rectangle. + * + * @param ArtSourceLayer row The row. + * @return LayerBounds Its rectangle. + */ + private fun boundsOf(row: ArtSourceLayer): LayerBounds = LayerBounds(row.left, row.top, row.width, row.height) + + /** + * The smaller area over the larger. + * + * @param LayerBounds first One rectangle, with area. + * @param LayerBounds second The other, with area. + * @return Float The ratio, 0..1. + */ + private fun sizeSimilarity(first: LayerBounds, second: LayerBounds): Float = + min(first.area, second.area).toFloat() / max(first.area, second.area).toFloat() +} + +/** + * How alike two layer names are: one minus the edit distance over the longer length, after lowercasing + * and collapsing whitespace, so "Hair Front" and "hair front" agree and "Hair Front" and "Hair + * Front 2" nearly do. Two empty names agree. + * + * @param String first One name. + * @param String second The other. + * @return Float The similarity, 0..1. + */ +fun nameSimilarity(first: String, second: String): Float { + val left = normalizeName(first) + val right = normalizeName(second) + if (left.isEmpty() && right.isEmpty()) { + return 1f + } + val longest = max(left.length, right.length) + return 1f - editDistance(left, right).toFloat() / longest.toFloat() +} + +/** + * How far two folder paths agree: 1 for the same path, else the leading segments they share over the + * longer path's segment count (a layer that moved one folder deeper keeps most of its agreement). + * + * @param String first One slash-joined path ("" at the root). + * @param String second The other. + * @return Float The agreement, 0..1. + */ +fun pathAgreement(first: String, second: String): Float { + if (first == second) { + return 1f + } + val left = first.split('/').filter { segment -> segment.isNotEmpty() } + val right = second.split('/').filter { segment -> segment.isNotEmpty() } + val longest = max(left.size, right.size) + if (longest == 0) { + return 1f + } + var shared = 0 + while (shared < min(left.size, right.size) && left[shared] == right[shared]) { + shared++ + } + return shared.toFloat() / longest.toFloat() +} + +/** + * How alike two rasters look, over a coarse grid each is resampled to: half the overlap of their opaque + * shapes, half one minus the mean color distance where both are opaque. Sizes need not agree - a + * layer that grew resamples to the same grid - and two empty rasters count as alike. + * + * @param LayerRaster first One raster. + * @param LayerRaster second The other. + * @return Float The similarity, 0..1. + */ +fun pixelSimilarity(first: LayerRaster, second: LayerRaster): Float { + if (first.width <= 0 || first.height <= 0 || second.width <= 0 || second.height <= 0) { + return 0f + } + var both = 0 + var either = 0 + var colorDistance = 0f + for (gridY in 0 until PIXEL_GRID) { + for (gridX in 0 until PIXEL_GRID) { + val firstIndex = sampleIndex(first, gridX, gridY) + val secondIndex = sampleIndex(second, gridX, gridY) + val firstOpaque = (first.rgba[firstIndex + 3].toInt() and 0xFF) >= OPAQUE_ALPHA + val secondOpaque = (second.rgba[secondIndex + 3].toInt() and 0xFF) >= OPAQUE_ALPHA + if (firstOpaque || secondOpaque) { + either++ + } + if (firstOpaque && secondOpaque) { + both++ + var channels = 0 + for (channel in 0 until 3) { + channels += abs((first.rgba[firstIndex + channel].toInt() and 0xFF) - (second.rgba[secondIndex + channel].toInt() and 0xFF)) + } + colorDistance += channels.toFloat() / (3f * 255f) + } + } + } + if (either == 0) { + return 1f + } + val shape = both.toFloat() / either.toFloat() + val color = if (both == 0) 0f else 1f - colorDistance / both.toFloat() + return (0.5f * shape + 0.5f * color).coerceIn(0f, 1f) +} + +/** + * The byte offset of the raster pixel a grid cell samples (nearest neighbor). + * + * @param LayerRaster raster The raster. + * @param Int gridX The cell's column on the grid. + * @param Int gridY The cell's row on the grid. + * @return Int The offset of the pixel's red byte. + */ +private fun sampleIndex(raster: LayerRaster, gridX: Int, gridY: Int): Int { + val x = min(raster.width - 1, gridX * raster.width / PIXEL_GRID) + val y = min(raster.height - 1, gridY * raster.height / PIXEL_GRID) + return (y * raster.width + x) * 4 +} + +/** + * A name lowercased with its whitespace collapsed, so spelling differences that no artist means count for nothing. + * + * @param String name The name. + * @return String The normalized name. + */ +private fun normalizeName(name: String): String = name.trim().lowercase().split(Regex("\\s+")).filter { part -> part.isNotEmpty() }.joinToString(" ") + +/** + * The Levenshtein distance between two strings. + * + * @param String first One string. + * @param String second The other. + * @return Int The edit distance. + */ +private fun editDistance(first: String, second: String): Int { + if (first.isEmpty()) { + return second.length + } + if (second.isEmpty()) { + return first.length + } + var previous = IntArray(second.length + 1) { column -> column } + var current = IntArray(second.length + 1) + for (row in 1..first.length) { + current[0] = row + for (column in 1..second.length) { + val substitution = previous[column - 1] + if (first[row - 1] == second[column - 1]) 0 else 1 + current[column] = min(min(previous[column] + 1, current[column - 1] + 1), substitution) + } + val swap = previous + previous = current + current = swap + } + return previous[second.length] +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/PollingSourceWatcher.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/PollingSourceWatcher.kt new file mode 100644 index 0000000..5cc0d91 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/PollingSourceWatcher.kt @@ -0,0 +1,165 @@ +package org.umamo.reimport + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okio.FileSystem +import okio.Path +import okio.Path.Companion.toPath +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.EmptyCoroutineContext + +/** + * A [SourceWatcher] that polls: every [pollMillis] each watched file is stat-ed through okio, and a + * change of size or modification time - or of existence - is a change. Polling rather than a + * platform notification API on purpose: okio's file system is the one that runs on every Kotlin + * target, JVM, Android, and Native alike, and a document watches a handful of files, so a stat per + * file per second is nothing. The coordinator above settles and hashes, so a poll only has to say + * "something happened"; an art program's temp-file-then-rename save changes the watched file's + * metadata like any other write. + * + * A file's baseline stamp is taken the moment it is watched, not at the loop's next tick: a caller + * that hashes the file right after subscribing (the coordinator's open-time check) waits on the + * subscription's [SourceWatcher.Subscription.awaitArmed], so the stamp precedes the hash and a save + * landing between the two is a change against the stamp rather than the stamp itself. + * + * Listeners are called in [scope]'s own dispatcher; the stats run under [statContext] (an IO + * dispatcher from the app), so a slow network drive never holds the UI. + * + * @param CoroutineScope scope The scope the poll loop and the deliveries run in. + * @param FileSystem fileSystem The file system the paths live on. + * @param Long pollMillis How often every watched file is stat-ed. + * @param CoroutineContext statContext Extra context for the stats; empty runs them in the scope. + */ +class PollingSourceWatcher( + private val scope: CoroutineScope, + private val fileSystem: FileSystem, + private val pollMillis: Long = DEFAULT_POLL_MILLIS, + private val statContext: CoroutineContext = EmptyCoroutineContext, +) : SourceWatcher, AutoCloseable { + /** What a stat sees of a file: absent, or its size and modification time. */ + private data class Stamp(val size: Long?, val modifiedAtMillis: Long?) + + /** + * One watch() call, the stamp it last saw, and the signal that it has seen one. + * + * @property String path The path as the caller gave it, echoed to the listener. + * @property Path filePath The path as okio reads it. + * @property ChangeListener listener Who hears the changes. + */ + private inner class Registration(val path: String, val filePath: Path, val listener: SourceWatcher.ChangeListener) : SourceWatcher.Subscription { + /** The stamp last seen, or null until the baseline stat lands. */ + var last: Stamp? = null + + /** Completed once [last] is set, or on close, so a waiter is never left hanging. */ + val armed = CompletableDeferred() + + override suspend fun awaitArmed() { + armed.await() + } + + override fun close() { + registrations.remove(this) + armed.complete(Unit) + if (registrations.isEmpty()) { + loop?.cancel() + loop = null + } + } + } + + /** A subscription for a path that cannot be polled: armed from the start, hears nothing, closes to nothing. */ + private object NoOpSubscription : SourceWatcher.Subscription { + override suspend fun awaitArmed() = Unit + + override fun close() = Unit + } + + private val registrations = ArrayList() + private var loop: Job? = null + + /** + * Begins polling [path]: its baseline stamp is taken at once (off the caller's thread), and every + * later tick compares against it. + * + * @param String path The file to watch; a uri gets a no-op subscription. + * @param ChangeListener listener Told in the scope whenever the file's size, modification time, or existence changes. + * @return Subscription The subscription. + */ + override fun watch(path: String, listener: SourceWatcher.ChangeListener): SourceWatcher.Subscription { + if (path.contains("://")) { + return NoOpSubscription + } + val filePath = runCatching { path.toPath() }.getOrNull() ?: return NoOpSubscription + val registration = Registration(path, filePath, listener) + registrations.add(registration) + scope.launch { baseline(registration) } + if (loop == null) { + loop = scope.launch { pollLoop() } + } + return registration + } + + /** Stops polling; every subscription is dead after this. */ + override fun close() { + for (registration in registrations.toList()) { + registration.armed.complete(Unit) + } + registrations.clear() + loop?.cancel() + loop = null + } + + /** + * Takes a registration's baseline stamp and arms it. A tick that stat-ed the file first has already + * set the baseline; that one stands, since a change between the two stats must then be reported + * against it rather than folded into a later one. + * + * @param Registration registration The registration to baseline. + */ + private suspend fun baseline(registration: Registration) { + val stamp = withContext(statContext) { stampOf(registration.filePath) } + if (registration.last == null) { + registration.last = stamp + } + registration.armed.complete(Unit) + } + + /** + * Stats every watched file each period and reports the ones whose stamp moved. A registration + * still waiting on its baseline takes this stat as it - a file is not "changed" by being watched. + */ + private suspend fun pollLoop() { + while (true) { + val snapshot = registrations.toList() + val stamps = withContext(statContext) { snapshot.map { registration -> stampOf(registration.filePath) } } + for ((registration, stamp) in snapshot.zip(stamps)) { + val previous = registration.last + registration.last = stamp + if (previous != null && previous != stamp && registration in registrations) { + registration.listener.onChanged(registration.path) + } + } + delay(pollMillis) + } + } + + /** + * The stamp of one file now. + * + * @param Path filePath The file. + * @return Stamp Its size and modification time, both null when absent or unreadable. + */ + private fun stampOf(filePath: Path): Stamp { + val metadata = runCatching { fileSystem.metadataOrNull(filePath) }.getOrNull() + return Stamp(metadata?.size, metadata?.lastModifiedAtMillis) + } + + private companion object { + /** How often the watched files are stat-ed; the coordinator's settle window sits on top of this. */ + const val DEFAULT_POLL_MILLIS = 1_000L + } +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/ReconcileResult.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/ReconcileResult.kt new file mode 100644 index 0000000..199c942 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/ReconcileResult.kt @@ -0,0 +1,54 @@ +package org.umamo.reimport + +import org.umamo.runtime.model.SourceLayerRef + +/* + * The reconcile's vocabulary. The binding itself is model state - `AtlasTile.source`, a + * SourceLayerRef naming the artwork file and the layer key the reader minted - so this module adds + * no identity type of its own: one key representation, minted by the readers, persisted on the tile, + * and diffed here. See CLAUDE.md "Source-art binding". + */ + +/** Why a binding needs a person's decision rather than an automatic update. */ +enum class ReviewReason { + /** The re-read art has no layer under the binding's key: removed, or renamed under a weak key. */ + LayerMissing, + + /** The file was repointed to art that mints different keys (another format), so the binding's key names nothing there. */ + SourceReplaced, + + /** The layer is still in the file but erased to nothing: deleted by another route, or meant to be blank - a person decides. */ + LayerEmptied, +} + +/** + * Outcome of reconciling one tile's binding against re-read art. Removals and renames are flagged, + * never silently applied - re-import must never destroy rig work (CLAUDE.md hard rule). + */ +sealed interface ReconcileResult { + /** + * The binding's layer is present under the same key; its art updates in place. + * + * @property SourceLayerRef binding The binding that matched. + * @property String layerKey The key it matched on - the binding's own, restated so a report + * reads uniformly with [Added]. + */ + data class Matched(val binding: SourceLayerRef, val layerKey: String) : ReconcileResult + + /** A layer the re-read art has that no tile is bound to; it becomes a new tile bound to it. */ + data class Added(val layerKey: String) : ReconcileResult + + /** + * A binding whose key the re-read art no longer has, rebound by the matcher to a layer no tile was + * bound to at or above the threshold - the lost layer re-created under a new key - so its tile + * takes that layer's art in the same step instead of a fresh drawable being minted beside it. + * + * @property SourceLayerRef binding The binding as it was, under the lost key. + * @property String layerKey The layer it moved to. + * @property Float score The matcher's confidence, 0..1. + */ + data class Rebound(val binding: SourceLayerRef, val layerKey: String, val score: Float) : ReconcileResult + + /** Needs human review - surfaced, never deleted. */ + data class NeedsReview(val binding: SourceLayerRef, val reason: ReviewReason) : ReconcileResult +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/Reconciler.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/Reconciler.kt new file mode 100644 index 0000000..b596ea6 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/Reconciler.kt @@ -0,0 +1,137 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayerKind +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.SourceLayerRef + +/** + * Reconciles existing rig bindings (the model's per-tile [SourceLayerRef]s) against freshly-read + * source art - the headline "file refreshes" feature. + * + * Hard rule: re-import never destroys rig work. Matched layers update in place; + * added layers become new tiles bound to their layer; removed/renamed layers are flagged for review, + * never silently deleted. The output [ReconcileReport] is therefore a reviewable diff, not an applied + * mutation - [ArtworkReloadPlanner] turns the matched and added halves into a model delta. + */ +interface Reconciler { + fun reconcile(bindings: List, newArt: SourceArt): ReconcileReport +} + +/** + * The result of a reconcile pass: every binding's outcome, plus a convenience view of the items a + * human must adjudicate before anything is applied. + */ +data class ReconcileReport( + val results: List, +) { + /** Items that must not be auto-applied - removed/renamed/fuzzy-matched layers. */ + val needsReview: List + get() = results.filterIsInstance() +} + +/** + * The reconcile every reload runs: a binding matches when the re-read art has a raster layer under + * exactly its key, a raster layer no binding names is added, and a binding whose key the art no + * longer has needs review. Keys only - the readers mint them stable where the format allows (a CLIP + * or Krita uuid, Photoshop's lyid) and the fuzzy matching a weak key needs is a [LayerMatcher]'s work + * ([InventoryLayerMatcher], run over the review half by [suggestionsFor]), never this reconcile's. + * + * Non-raster layers (folders, text, adjustment layers) are invisible to it: they never became tiles + * at import, so they are neither matched nor added, and a raster layer that turned into one reads as + * missing, which is the honest answer. + */ +object KeyReconciler : Reconciler { + /** + * Classifies [bindings] against [newArt]. + * + * @param List bindings The bindings of every tile bound to the re-read file. + * @param SourceArt newArt The file as just read. + * @return ReconcileReport One result per binding, then one per added layer, in the art's order. + */ + override fun reconcile(bindings: List, newArt: SourceArt): ReconcileReport { + val rasterKeys = LinkedHashSet() + for (layer in newArt.layers.sortedBy { candidate -> candidate.order }) { + if (layer.kind == SourceLayerKind.Raster) { + rasterKeys.add(layer.id.raw) + } + } + val boundKeys = bindings.mapTo(HashSet()) { binding -> binding.layerKey } + val results = ArrayList(bindings.size + rasterKeys.size) + for (binding in bindings) { + if (binding.layerKey in rasterKeys) { + results.add(ReconcileResult.Matched(binding, binding.layerKey)) + } else { + results.add(ReconcileResult.NeedsReview(binding, ReviewReason.LayerMissing)) + } + } + for (key in rasterKeys) { + if (key !in boundKeys) { + results.add(ReconcileResult.Added(key)) + } + } + return ReconcileReport(results) + } +} + +/** + * One layer a missing layer's binding could move to: its inventory row and, when the file could be + * read, its pixels on demand. + * + * @property ArtSourceLayer row The candidate as the inventory records it. + * @property Function raster Its pixels, decoded on first use; null when they cannot be read. + */ +class MatchCandidate( + val row: ArtSourceLayer, + val raster: () -> LayerRaster?, +) + +/** + * How one candidate scored on each signal, kept beside the score so a person can see why. + * + * @property Float name Name similarity, 0..1. + * @property Float path Folder-path agreement, 0..1. + * @property Float? bounds Canvas overlap of the two rectangles, 0..1, or null when either has no known extent. + * @property Float? size The smaller area over the larger, 0..1, or null when either has no known extent. + * @property Float? pixels Pixel similarity, 0..1, or null when either side's pixels were not read. + * @property Boolean hashEqual Whether both rows carry a content hash and they agree - the same pixels. + */ +data class MatchSignals( + val name: Float, + val path: Float, + val bounds: Float?, + val size: Float?, + val pixels: Float?, + val hashEqual: Boolean, +) + +/** + * One ranked candidate for a missing layer. + * + * @property String key The candidate's layer key. + * @property Float score The combined confidence, 0..1. + * @property MatchSignals signals The per-signal scores behind it. + */ +data class LayerMatch( + val key: String, + val score: Float, + val signals: MatchSignals, +) + +/** + * The matcher for the hard case: a binding whose layer key the file no longer has, ranked against the + * file's layers no tile is bound to. Scored rather than decided - the caller applies a threshold or + * shows the ranking, and a person can always override. + */ +fun interface LayerMatcher { + /** + * Ranks [candidates] for [missing], best first. + * + * @param ArtSourceLayer missing The lost layer as the inventory recorded it. + * @param LayerRaster? missingRaster The pixels the document holds for it, or null. + * @param List candidates The layers it could move to. + * @return List Every candidate with its score, best first; empty when there are none. + */ + fun rank(missing: ArtSourceLayer, missingRaster: LayerRaster?, candidates: List): List +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/RigWork.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/RigWork.kt new file mode 100644 index 0000000..6d66f06 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/RigWork.kt @@ -0,0 +1,56 @@ +package org.umamo.reimport + +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.isUntouchedBirthQuad +import org.umamo.runtime.model.storedToArtAffineForTile + +/* + * What a merge may remove. A reload that finds a layer no tile binds mints a fresh drawable for it; + * when that layer turns out to be a lost layer re-created (a duplicate, a paste), the rigged tile + * takes the layer and the fresh drawable is redundant - but only while nothing has been done to it. + * One predicate says so, read by the planner, the suggestions, and the Sources space alike, so the + * proposal, the step, and the chip's wording agree on what goes. + */ + +/** + * Whether every drawable over [tileId] is exactly what an import mints and nothing more: a birth quad + * that still samples the whole tile at the layer's canvas place, no parent deformer, no clip mask + * either way, no glue, no geometry or channel keys, and no blend shapes. A tile no drawable samples + * qualifies too, since there is nothing over it to lose. Without [row], or without a readable mapping + * for the tile, the answer is false: the quad cannot be told untouched, so the drawable is kept; so is + * a tile the model lacks. + * + * @param AtlasTileId tileId The tile whose drawables are judged. + * @param ArtSourceLayer? row The tile's layer as the inventory records it, for the canvas origin the + * birth quad was born at; null when the inventory has no row for it. + * @return Boolean True when removing the tile's drawables would lose no rig work. + */ +fun PuppetModel.tileCarriesNoRigWork(tileId: AtlasTileId, row: ArtSourceLayer?): Boolean { + val tile = atlas.tileById[tileId] ?: return false + val over = drawables.filter { drawable -> drawable.atlasTileId == tileId } + if (over.isEmpty()) { + return true + } + if (row == null) { + return false + } + val storedToArt = atlas.storedToArtAffineForTile(tileId) ?: return false + val overIds = over.mapTo(HashSet()) { drawable -> drawable.id } + val masksAnother = drawables.any { drawable -> drawable.id !in overIds && drawable.maskedBy.any { maskId -> maskId in overIds } } + val glued = glues.any { glue -> glue.meshA in overIds || glue.meshB in overIds } + if (masksAnother || glued) { + return false + } + return over.all { drawable -> + val mesh = drawable.mesh ?: return@all false + drawable.parentDeformerId == null && + drawable.maskedBy.isEmpty() && + drawable.geometryGrid == null && + drawable.channelGrids.isEmpty && + drawable.blendShapes.isEmpty() && + mesh.isUntouchedBirthQuad(applyUvAffine(mesh.uvs, storedToArt), tile.width, tile.height, row.left.toFloat(), row.top.toFloat()) + } +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/SourceWatchCoordinator.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/SourceWatchCoordinator.kt new file mode 100644 index 0000000..e3714d0 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/SourceWatchCoordinator.kt @@ -0,0 +1,393 @@ +package org.umamo.reimport + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import org.umamo.runtime.model.ArtSourceId + +/* + * The policy between a file watcher and a reload: which files a document watches, when a burst of + * write events has settled, whether the settled file actually changed (its hash against what the + * document last read), and when the editor is idle enough to take the reload. Pure over injected + * time and hashing, so the whole of it runs under a test clock; the watcher and the hash are the only + * things that touch a disk. + * + * Every field is confined to the scope's dispatcher: the watcher delivers on it, the app calls on + * it, and the timers run on it. Nothing here is thread-safe by any other means. + */ + +/** + * One listed artwork file the coordinator tracks. + * + * @property ArtSourceId sourceId The file's record in the model. + * @property String path The path the document recorded for it. + * @property String? recordedHash The content hash the document last read, or null when it never read bytes. + * @property Long? recordedModifiedAt The file's modification time (epoch milliseconds) the document + * recorded, or null; the stale-at-open check's fallback where no hash was recorded (a CMO3-origin file). + */ +class WatchedSource( + val sourceId: ArtSourceId, + val path: String, + val recordedHash: String?, + val recordedModifiedAt: Long? = null, +) + +/** What the coordinator tells the app. */ +sealed interface SourceWatchEvent { + /** Changed files have settled and the editor is idle: reload these as one operation. */ + data class ReloadDue(val sourceIds: Set) : SourceWatchEvent + + /** Changed files have settled; the mode is notify, so a person decides. */ + data class ChangedOnDisk(val sourceIds: Set) : SourceWatchEvent + + /** Files differed from their recorded hash when tracking began - edited while the document was closed. */ + data class StaleAtOpen(val sourceIds: Set) : SourceWatchEvent + + /** A tracked file is no longer where the document recorded it. */ + data class Missing(val sourceId: ArtSourceId) : SourceWatchEvent +} + +/** How a reload the coordinator asked for ended, so it knows whether to wait, retry, or let go. */ +enum class WatchedReloadResult { + /** The reload landed; the model's recorded hashes refresh through [SourceWatchCoordinator.track]. */ + Applied, + + /** The files were read and nothing in them changed the document; the hashes are acknowledged. */ + NothingChanged, + + /** An edit landed while the reload was planned; the coordinator tries again after a settle. */ + Superseded, + + /** The reload was refused or could not read the files; the person was told, so let go. */ + Abandoned, +} + +/** One tracked file's live state. */ +private class TrackedSource( + var source: WatchedSource, + var handle: SourceWatcher.Subscription, +) { + /** The hash last read from the disk, or null when the file could not be read. */ + var observedHash: String? = null + + /** A disk hash a reload found nothing to change for; dropped rather than reported again. */ + var acknowledgedHash: String? = null + + /** Whether the last read found the file absent, so its return counts as a change. */ + var missing: Boolean = false + + /** The settle timer, restarted by every event. */ + var settle: Job? = null +} + +/** + * The reload policy over a [SourceWatcher]. See the file comment. + * + * @param CoroutineScope scope The scope everything runs in; its dispatcher confines the state. + * @param SourceWatcher watcher Where change notifications come from. + * @param Function hashOf The content hash of the file at a path, or null when unreadable. + * @param Function exists Whether a path exists, or null when the platform cannot say. + * @param Function isIdle Whether the editor can take a reload right now. + * @param Function mode The watch mode, read live at each decision. + * @param Long settleMillis How long after the last event a file is left alone before it is hashed. + * @param Long idlePollMillis How often the idle gate is re-asked while a reload waits. + */ +class SourceWatchCoordinator( + private val scope: CoroutineScope, + private val watcher: SourceWatcher, + private val hashOf: suspend (String) -> String?, + private val exists: suspend (String) -> Boolean?, + private val isIdle: () -> Boolean, + private val mode: () -> WatchMode, + private val settleMillis: Long = DEFAULT_SETTLE_MILLIS, + private val idlePollMillis: Long = DEFAULT_IDLE_POLL_MILLIS, + private val modifiedAtOf: suspend (String) -> Long? = { null }, +) { + private val tracked = LinkedHashMap() + private val mutablePending = MutableStateFlow>(emptySet()) + private val mutableSerial = MutableStateFlow(0) + private val mutableEvents = MutableSharedFlow(extraBufferCapacity = EVENT_BUFFER) + private var dueWait: Job? = null + + /** The files whose settled content differs from what the document last read, awaiting a reload. */ + val pending: StateFlow> = mutablePending.asStateFlow() + + /** Bumped whenever a file's presence changed, so a presence probe re-runs. */ + val serial: StateFlow = mutableSerial.asStateFlow() + + /** What the app acts on. */ + val events: SharedFlow = mutableEvents.asSharedFlow() + + /** + * Tracks exactly [sources]: new files begin watching and are checked once against their recorded + * hash (a file edited while the document was closed is reported as stale), files no longer listed + * stop, and a file whose recorded hash caught up with the disk leaves the pending set. Called with + * the model's source list whenever it changes; with the mode off, tracks nothing. + * + * @param List sources The listed files with real paths. + */ + fun track(sources: List) { + if (mode() == WatchMode.Off) { + stopAll() + return + } + val wanted = sources.associateBy { source -> source.sourceId } + for (sourceId in tracked.keys.toList()) { + val entry = tracked.getValue(sourceId) + val next = wanted[sourceId] + if (next == null || next.path != entry.source.path) { + stop(sourceId) + } + } + val toCheck = ArrayList() + for (source in sources) { + val existing = tracked[source.sourceId] + if (existing != null) { + existing.source = source + // A reload landed: the record caught up with the disk, and this file is no longer owed one. + if (source.recordedHash != null && source.recordedHash == existing.observedHash) { + setPending(source.sourceId, false) + } + continue + } + val entry = TrackedSource(source, watcher.watch(source.path) { onChanged(source.sourceId) }) + tracked[source.sourceId] = entry + toCheck.add(entry) + } + if (toCheck.isNotEmpty()) { + scope.launch { checkAtOpen(toCheck) } + } + } + + /** + * Records how the reload asked for by a [SourceWatchEvent.ReloadDue] ended, for the files it named. + * + * @param Set sourceIds The files the reload covered. + * @param WatchedReloadResult result How it ended. + */ + fun reloadFinished(sourceIds: Set, result: WatchedReloadResult) { + when (result) { + // The model's new hashes arrive through track(); nothing to do until then. + WatchedReloadResult.Applied -> Unit + WatchedReloadResult.NothingChanged, WatchedReloadResult.Abandoned -> { + for (sourceId in sourceIds) { + val entry = tracked[sourceId] ?: continue + entry.acknowledgedHash = entry.observedHash + setPending(sourceId, false) + } + } + WatchedReloadResult.Superseded -> { + for (sourceId in sourceIds) { + if (tracked.containsKey(sourceId)) { + onChanged(sourceId) + } + } + } + } + } + + /** Stops watching everything and clears the pending set; the coordinator is done. */ + fun close() { + stopAll() + dueWait?.cancel() + dueWait = null + } + + /** + * A change notification for [sourceId]: restarts its settle timer. + * + * @param ArtSourceId sourceId The changed file. + */ + private fun onChanged(sourceId: ArtSourceId) { + val entry = tracked[sourceId] ?: return + entry.settle?.cancel() + entry.settle = scope.launch { settle(entry) } + } + + /** + * Waits for the writes to stop, then reads the file's hash and decides: unreadable while present + * means the editor is still writing (wait again, up to a limit), absent means missing, a hash the + * document already holds or already acknowledged means nothing to do, and anything else is a change. + * + * @param TrackedSource entry The file. + */ + private suspend fun settle(entry: TrackedSource) { + var attempts = 0 + while (true) { + delay(settleMillis) + val hash = hashOf(entry.source.path) + if (hash != null) { + val returned = entry.missing + entry.missing = false + entry.observedHash = hash + if (returned) { + mutableSerial.value = mutableSerial.value + 1 + } + decide(entry, hash) + return + } + if (exists(entry.source.path) == false) { + if (!entry.missing) { + entry.missing = true + entry.observedHash = null + setPending(entry.source.sourceId, false) + mutableSerial.value = mutableSerial.value + 1 + mutableEvents.tryEmit(SourceWatchEvent.Missing(entry.source.sourceId)) + } + return + } + attempts++ + if (attempts >= MAX_SETTLE_ATTEMPTS) { + return + } + } + } + + /** + * A settled file's hash against what the document holds. + * + * @param TrackedSource entry The file. + * @param String hash Its content hash as just read. + */ + private fun decide(entry: TrackedSource, hash: String) { + val sourceId = entry.source.sourceId + if (hash == entry.source.recordedHash || hash == entry.acknowledgedHash) { + setPending(sourceId, false) + return + } + setPending(sourceId, true) + when (mode()) { + WatchMode.Auto -> requestReload() + WatchMode.Notify -> mutableEvents.tryEmit(SourceWatchEvent.ChangedOnDisk(setOf(sourceId))) + WatchMode.Off -> Unit + } + } + + /** + * Arranges one reload of everything pending once the editor is idle; a wait already under way + * picks the new files up when it fires. + */ + private fun requestReload() { + if (dueWait?.isActive == true) { + return + } + dueWait = + scope.launch { + while (!isIdle()) { + delay(idlePollMillis) + } + val due = mutablePending.value + if (due.isNotEmpty()) { + mutableEvents.tryEmit(SourceWatchEvent.ReloadDue(due)) + } + } + } + + /** + * The one-time check a newly tracked file gets: its disk hash against the recorded one - or, for a + * file the document recorded no hash for (a CMO3-origin source), its modification time against the + * recorded one - so a file edited while the document was closed is reported before anyone asks. + * Batched per track call. The hash is the surer signal and wins wherever it exists; a time can move + * with no change in the bytes, which a reload then finds and acknowledges. + * + * Each file is hashed only once its watch is armed: the watcher's baseline stamp then precedes the + * hash, so a save landing between the two reads as a change against that stamp on the next tick + * instead of becoming the stamp and going unreported. + * + * @param List entries The files that just began tracking. + */ + private suspend fun checkAtOpen(entries: List) { + val stale = LinkedHashSet() + for (entry in entries) { + entry.handle.awaitArmed() + if (!tracked.containsValue(entry)) { + continue + } + val hash = hashOf(entry.source.path) + if (hash == null) { + entry.missing = exists(entry.source.path) == false + continue + } + entry.observedHash = hash + if (isStaleAtOpen(entry.source, hash)) { + stale.add(entry.source.sourceId) + setPending(entry.source.sourceId, true) + } + } + if (stale.isNotEmpty()) { + mutableEvents.tryEmit(SourceWatchEvent.StaleAtOpen(stale)) + } + } + + /** + * Whether a newly tracked file differs from what the document recorded: by hash when one was + * recorded, else by modification time when one was, else not knowable. + * + * @param WatchedSource source The file as recorded. + * @param String hash Its hash on disk now. + * @return Boolean True when the file changed while the document was closed. + */ + private suspend fun isStaleAtOpen(source: WatchedSource, hash: String): Boolean { + val recordedHash = source.recordedHash + if (recordedHash != null) { + return hash != recordedHash + } + val recordedModifiedAt = source.recordedModifiedAt ?: return false + val modifiedAt = modifiedAtOf(source.path) ?: return false + return modifiedAt != recordedModifiedAt + } + + /** + * Adds or removes [sourceId] from the pending set. + * + * @param ArtSourceId sourceId The file. + * @param Boolean pending Whether it awaits a reload. + */ + private fun setPending(sourceId: ArtSourceId, pending: Boolean) { + val current = mutablePending.value + val next = if (pending) current + sourceId else current - sourceId + if (next != current) { + mutablePending.value = next + } + } + + /** + * Stops watching one file. + * + * @param ArtSourceId sourceId The file. + */ + private fun stop(sourceId: ArtSourceId) { + val entry = tracked.remove(sourceId) ?: return + entry.settle?.cancel() + entry.handle.close() + setPending(sourceId, false) + } + + /** Stops watching every file. */ + private fun stopAll() { + for (sourceId in tracked.keys.toList()) { + stop(sourceId) + } + } + + private companion object { + /** How long a file is left alone after its last event before it is read - past the pause a save's writes leave. */ + const val DEFAULT_SETTLE_MILLIS = 750L + + /** How often the idle gate is re-asked while a reload waits for a gesture to end. */ + const val DEFAULT_IDLE_POLL_MILLIS = 250L + + /** How many settle windows an unreadable, present file is retried over before it is left for the next event. */ + const val MAX_SETTLE_ATTEMPTS = 8 + + /** Events buffered for a slow collector before the newest are dropped. */ + const val EVENT_BUFFER = 64 + } +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/SourceWatcher.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/SourceWatcher.kt new file mode 100644 index 0000000..9fd4862 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/SourceWatcher.kt @@ -0,0 +1,42 @@ +package org.umamo.reimport + +/** + * Watches a source-art file for on-disk changes - the trigger of the headline "file refreshes" + * workflow. + * + * Modelled with a `fun interface` (SAM) listener and an [AutoCloseable] subscription so the contract + * carries no coroutine/Flow dependency at this layer. [PollingSourceWatcher] is the one + * implementation, over okio so it runs on every Kotlin target; a platform notification API could + * back another, but none is needed. The policy above it - settling a burst of events, hashing to + * skip a save that changed nothing, waiting for the editor to go idle - is [SourceWatchCoordinator]'s, + * so an implementation only has to say "this path changed". + */ +interface SourceWatcher { + /** Receives change notifications for a watched path. */ + fun interface ChangeListener { + fun onChanged(path: String) + } + + /** + * One watch of one file: close it to stop the notifications, and wait on [awaitArmed] before + * reading the file for a baseline of your own. + */ + interface Subscription : AutoCloseable { + /** + * Suspends until the watcher holds the file's baseline, from which point every change is + * reported. A change the watcher first sees while taking that baseline is folded into it, so a + * caller that reads the file BEFORE this returns and takes what it read as current could have the + * file change under it, unreported, in between. Returns at once for a closed subscription. + */ + suspend fun awaitArmed() + } + + /** + * Begins watching [path]; close the returned subscription to stop. + * + * @param String path The file to watch. + * @param ChangeListener listener Told whenever the file is written, replaced, created, or deleted. + * @return Subscription The subscription; closing it stops the notifications. + */ + fun watch(path: String, listener: ChangeListener): Subscription +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/Suggestions.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/Suggestions.kt new file mode 100644 index 0000000..3247f4e --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/Suggestions.kt @@ -0,0 +1,209 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerRaster +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel + +/* + * What the document proposes for a binding its file no longer resolves. The inventory keeps a lost + * layer's row, flagged not present, for as long as a tile binds it - its name, bounds, and hash are + * what the matcher scores candidates against and what the Sources space names the row by - and the + * row leaves the inventory on the first refresh after nothing binds it. A suggestion is only ever a + * proposal: accepting one is the same relink a person makes by hand. + */ + +/** + * The inventory a refresh records: [fresh] as read, plus every [previous] row whose key the fresh art + * lacks and a tile still binds, marked not present. A previous row already not present stays so, and + * a lost row nothing binds is dropped - there is no binding left to review. A row losing its presence + * in this refresh records why ([ArtSourceLayer.replaced]): the file was repointed at art that mints + * other keys when [lostByReplacement] says so, else the layer left the file. + * + * A plan that pulls art for some tiles and not others (a relink, an accepted match) names the bound + * keys it left alone in [untouchedKeys]: their previous rows are kept over the fresh ones, so a change + * to those layers the plan did not carry into their tiles is still seen by the next reload instead of + * being recorded as already taken. + * + * A row that reads as erased keeps the canvas frame its art last had: an art program saves an erased + * layer with a collapsed rectangle, and the tile still holds the art from the frame before, so a + * reload that finds the art back (an undo in the art program) measures it against that frame rather + * than against the collapse - which would carry every coordinate by the bogus difference. + * + * The rigger's ignore mark ([ArtSourceLayer.ignored]) is the document's, not the file's, so a fresh + * row carries its previous row's mark; a layer new to the file starts unmarked. + * + * @param List previous The inventory as the document held it. + * @param List fresh The inventory of the art as just read. + * @param Set boundKeys The keys the tiles bound to this file carry after the plan. + * @param Set untouchedKeys The bound keys whose tiles the plan did not update. + * @param Boolean lostByReplacement Whether the rows lost in this refresh were lost to a Replace Artwork. + * @return List The rows to record, the fresh ones first in their order, then the kept lost ones in theirs. + */ +fun inventoryWithMissing( + previous: List, + fresh: List, + boundKeys: Set, + untouchedKeys: Set = emptySet(), + lostByReplacement: Boolean = false, +): List { + val previousByKey = previous.associateBy { row -> row.key } + val freshKeys = fresh.mapTo(HashSet()) { row -> row.key } + val refreshed = + fresh.map { row -> + val previousRow = previousByKey[row.key] + val carried = if (previousRow?.ignored == true) row.copy(ignored = true) else row + when { + row.key in untouchedKeys && previousRow != null && previousRow.present -> previousRow + // The previous row already holds the last frame with art when it was itself erased. + row.empty && previousRow != null -> + carried.copy(left = previousRow.left, top = previousRow.top, width = previousRow.width, height = previousRow.height) + else -> carried + } + } + val lost = + previous + .filter { row -> row.key !in freshKeys && row.key in boundKeys } + .map { row -> if (row.present) row.copy(present = false, replaced = lostByReplacement) else row } + return refreshed + lost +} + +/** + * The row the matcher scores a lost binding by: the inventory's not-present row when it kept one, else + * a row made from the tile itself - its name and size, at an unknown place - so a binding the + * inventory never listed (a CMO3 walk's stray) still gets candidates. + * + * @param ArtSourceLayer? row The inventory's row for the key, or null. + * @param AtlasTile tile The tile bound to it. + * @return ArtSourceLayer The row to score with. + */ +private fun missingRowFor(row: ArtSourceLayer?, tile: AtlasTile): ArtSourceLayer = + row ?: ArtSourceLayer(tile.source?.layerKey ?: tile.id.raw, tile.name, "", 0, 0, 0, 0, visible = true, present = false) + +/** + * The best candidate for every binding to [sourceId] its inventory does not list as present - or lists + * as erased to nothing - keyed by the lost layer's key. The candidates are the file's present layers + * with art that no tile is bound to and the rigger has not ignored - never a bound one, since on the + * model alone nothing tells a re-created layer's fresh drawable from any other untouched drawable; the + * proposal that names a + * bound layer comes only from a reload that scored the binding before it minted the layer. Without + * rasters the ranking rests on the inventory alone; with them the matcher compares pixels too. + * + * @param PuppetModel model The document's model. + * @param ArtSourceId sourceId The file whose lost layers are scored. + * @param Function missingRasterOf The document's pixels for a tile, or null when unread. + * @param Function candidateRasterOf The pixels of a present layer by key, or null when unread. + * @param LayerMatcher matcher The matcher to rank with. + * @return Map Each lost binding's best match by its key; one with no candidate is absent. + */ +fun suggestionsFor( + model: PuppetModel, + sourceId: ArtSourceId, + missingRasterOf: (AtlasTileId) -> LayerRaster? = { null }, + candidateRasterOf: (String) -> LayerRaster? = { null }, + matcher: LayerMatcher = InventoryLayerMatcher, +): Map { + val source = model.sources.firstOrNull { candidate -> candidate.id == sourceId } ?: return emptyMap() + val boundTiles = model.atlas.tiles.filter { tile -> tile.source?.sourceId == sourceId } + val tileByKey = HashMap() + for (tile in boundTiles) { + val key = tile.source?.layerKey ?: continue + tileByKey.putIfAbsent(key, tile.id) + } + val candidates = + source.layers + .filter { row -> row.present && !row.empty && !row.ignored && row.key !in tileByKey && row.width > 0 && row.height > 0 } + .map { row -> MatchCandidate(row) { candidateRasterOf(row.key) } } + if (candidates.isEmpty()) { + return emptyMap() + } + val rowByKey = source.layers.associateBy { row -> row.key } + val suggestions = LinkedHashMap() + for (tile in boundTiles) { + val key = tile.source?.layerKey ?: continue + if (key in suggestions || tileByKey[key] != tile.id) { + continue + } + val row = rowByKey[key] + if (row != null && row.present && !row.empty) { + continue + } + val best = matcher.rank(missingRowFor(row, tile), missingRasterOf(tile.id), candidates).firstOrNull() ?: continue + suggestions[key] = best + } + return suggestions +} + +/** + * The suggestions for [sourceId]'s unresolved bindings against its art as just read: the record's + * inventory refreshed with [inventory] first - the lost rows kept, and every bound layer's previous row + * kept too, since nothing here carries a change into a tile - so a file never reloaded still scores, + * then [suggestionsFor] over that. What the reload planner scores before it mints, and what an + * operation that read the file publishes for the review chips. + * + * @param PuppetModel model The model as it stands. + * @param ArtSourceId sourceId The file. + * @param List inventory The inventory of the file as just read. + * @param Function missingRasterOf The document's pixels for a tile, or null when unread. + * @param Function candidateRasterOf The pixels of a present layer by key, or null when unread. + * @param LayerMatcher matcher The matcher to rank with. + * @return Map Each unresolved binding's best match by its key; one with no candidate is absent. + */ +fun suggestionsAgainstRead( + model: PuppetModel, + sourceId: ArtSourceId, + inventory: List, + missingRasterOf: (AtlasTileId) -> LayerRaster? = { null }, + candidateRasterOf: (String) -> LayerRaster? = { null }, + matcher: LayerMatcher = InventoryLayerMatcher, +): Map { + val source = model.sources.firstOrNull { candidate -> candidate.id == sourceId } ?: return emptyMap() + val boundKeys = model.atlas.tiles.filter { tile -> tile.source?.sourceId == sourceId }.mapNotNullTo(HashSet()) { tile -> tile.source?.layerKey } + val refreshed = source.copy(layers = inventoryWithMissing(source.layers, inventory, boundKeys, untouchedKeys = boundKeys)) + val scoringModel = model.copy(sources = model.sources.map { candidate -> if (candidate.id == sourceId) refreshed else candidate }) + return suggestionsFor(scoringModel, sourceId, missingRasterOf, candidateRasterOf, matcher) +} + +/** + * The matches to apply out of [suggestions]: those at or above [threshold], best first, each candidate + * taken once - two lost layers that both prefer one candidate are settled in favor of the more + * confident, the other left for a person (its suggestion stands). + * + * @param Map suggestions The best candidate per lost key. + * @param Float threshold The confidence bar, 0..1, inclusive. + * @return Map The candidate key each accepted lost key moves to, most confident first. + */ +fun confidentMatches(suggestions: Map, threshold: Float): Map { + val takenCandidates = HashSet() + val accepted = LinkedHashMap() + for ((lostKey, match) in suggestions.entries.sortedByDescending { (_, match) -> match.score }) { + if (match.score < threshold || !takenCandidates.add(match.key)) { + continue + } + accepted[lostKey] = match.key + } + return accepted +} + +/** + * The tiles a rebinding onto [candidateKey] may retire: every tile of [sourceId] bound to that key + * other than [except] whose drawables carry no rig work - the fresh drawable a reload minted for the + * layer before the lost layer's rig work claimed it. A tile with rig work over it stays bound; two + * tiles then share the layer, which a person sorts out. What the Sources space shows against a + * proposal naming a bound layer, and what a match re-checks before it retires anything. + * + * @param PuppetModel model The model the rebinding applies to. + * @param ArtSourceId sourceId The file. + * @param String candidateKey The layer being claimed. + * @param Set except The tiles doing the claiming. + * @return List The tiles to retire, in atlas order. + */ +fun retirableTiles(model: PuppetModel, sourceId: ArtSourceId, candidateKey: String, except: Set): List { + val row = model.sources.firstOrNull { source -> source.id == sourceId }?.layers?.firstOrNull { layer -> layer.key == candidateKey } + return model.atlas.tiles + .filter { tile -> tile.id !in except && tile.source?.sourceId == sourceId && tile.source?.layerKey == candidateKey } + .filter { tile -> model.tileCarriesNoRigWork(tile.id, row) } + .map { tile -> tile.id } +} \ No newline at end of file diff --git a/module/reimport/src/commonMain/kotlin/org/umamo/reimport/WatchMode.kt b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/WatchMode.kt new file mode 100644 index 0000000..49a2714 --- /dev/null +++ b/module/reimport/src/commonMain/kotlin/org/umamo/reimport/WatchMode.kt @@ -0,0 +1,32 @@ +package org.umamo.reimport + +/** + * What a document does when a watched artwork file changes on disk - the `import.watchMode` setting. + * + * @property String key The setting value. + */ +enum class WatchMode(val key: String) { + /** Reload the changed files as soon as the editor is idle, as one undo step. */ + Auto("auto"), + + /** Say that files changed and light the Reload button; nothing changes until it is pressed. */ + Notify("notify"), + + /** Watch nothing. */ + Off("off"), + ; + + companion object { + /** The mode a fresh install runs with. */ + val Default: WatchMode = Auto + + /** + * The mode a setting value names, or [Default] for a value no mode carries (a stale or absent + * setting must not turn watching off by accident). + * + * @param String? key The setting value. + * @return WatchMode The mode. + */ + fun fromKey(key: String?): WatchMode = entries.firstOrNull { mode -> mode.key == key } ?: Default + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/ArtworkReloadPlannerTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/ArtworkReloadPlannerTest.kt new file mode 100644 index 0000000..742f8f7 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/ArtworkReloadPlannerTest.kt @@ -0,0 +1,515 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.CanvasOffset +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.interop.art.placedBy +import org.umamo.interop.art.placedFor +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.OrgInsertion +import org.umamo.runtime.model.OrgSlot +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * The reload planner over a hand-built model and in-memory art: what a changed, unchanged, moved, + * added, and removed layer each turn into, and what a relink pulls. + */ +class ArtworkReloadPlannerTest { + private val source = ArtSourceId("art-0") + private val options = SourceArtImportOptions(alphaThreshold = 1, birthMeshMargin = 2) + private val ref1 = SourceLayerRef(source, "lyid:1", true) + private val ref2 = SourceLayerRef(source, "lyid:2", true) + private val tile1 = AtlasTileId("art-0/lyid:1") + private val tile2 = AtlasTileId("art-0/lyid:2") + + /** Layer 1 at (10, 20), 4x4, and layer 2 at (30, 40), 4x4, as the document last read them. */ + private val layer1 = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), solidRaster(4, 4, 1)) + private val layer2 = TestLayer("lyid:2", "Two", 1, LayerBounds(30, 40, 4, 4), solidRaster(4, 4, 2)) + private val oldRasters = mapOf(tile1 to layer1.raster, tile2 to layer2.raster) + private val oldRasterOf: (AtlasTileId) -> LayerRaster? = { tileId -> oldRasters[tileId] } + + /** The mesh an untouched drawable over layer 1 carries: its birth quad. */ + private val birthQuad1: DrawableMesh = SourceArtImport.birthMeshFor(layer1, options.alphaThreshold, options.birthMeshMargin)!! + + /** An edited mesh over layer 2: a triangle covering only the layer's top-left pixel. */ + private val editedMesh2 = DrawableMesh(floatArrayOf(30f, 40f, 31f, 40f, 30f, 41f), floatArrayOf(0f, 0f, 0.25f, 0f, 0f, 0.25f), intArrayOf(0, 1, 2)) + + private fun drawable(id: String, tileId: AtlasTileId, mesh: DrawableMesh): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), mesh, null, atlasTileId = tileId) + + private fun model(): PuppetModel { + val drawables = listOf(drawable("d1", tile1, birthQuad1), drawable("d2", tile2, editedMesh2)) + return PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + atlas = + PuppetAtlas( + tiles = + listOf( + AtlasTile(tile1, "One", 4, 4, source = ref1, pinned = true), + AtlasTile(tile2, "Two", 4, 4, source = ref2), + ), + ), + sources = listOf(ArtSource(source, "a.psd", "/a.psd", "psd", SourceArtImport.inventoryOf(TestArt(listOf(layer1, layer2))))), + ) + } + + @Test + fun anUnchangedFilePlansNothing() { + assertNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(layer1, layer2)), options, oldRasterOf)) + } + + @Test + fun changedPixelsMintAReplacementAndRebirthAnUntouchedQuad() { + val repainted = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 6, 6), solidRaster(6, 6, 9)) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(repainted, layer2)), options, oldRasterOf)) + val replaced = plan.reload.replacedTiles.single() + assertEquals(tile1, replaced.oldId) + assertEquals(AtlasTileId("art-0/lyid:1~1"), replaced.tile.id) + assertEquals(6, replaced.tile.width) + assertEquals(6, replaced.tile.height) + assertNull(replaced.tile.placement, "the replacement is unplaced until the pack") + assertTrue(replaced.tile.pinned, "the pin is carried") + assertEquals(tile1, replaced.tile.replaces) + assertEquals(ref1, replaced.tile.source) + assertSame(repainted.raster, plan.rasterByTile.getValue(replaced.tile.id)) + val reborn = plan.reload.drawableMeshes.getValue(DrawableId("d1")) + val expected = SourceArtImport.birthMeshFor(repainted, options.alphaThreshold, options.birthMeshMargin)!! + assertContentEquals(expected.positions, reborn.positions, "an untouched birth quad is re-born over the new art") + assertContentEquals(expected.uvs, reborn.uvs) + assertTrue(plan.reload.outgrown.isEmpty()) + assertNull(plan.reload.additions) + assertEquals(listOf(6, 6), plan.reload.source.layers.first { layer -> layer.key == "lyid:1" }.let { layer -> listOf(layer.width, layer.height) }, "the inventory is refreshed") + } + + @Test + fun aMovedLayerUnderAnEditedMeshKeepsThePositionsAndCarriesTheCoordinates() { + // Layer 2 moved right by 3 and down by 1 with the same pixels: the mesh stays on the canvas and + // each vertex keeps sampling the canvas pixel under it, which is 3 art pixels further left now. + val moved = TestLayer("lyid:2", "Two", 1, LayerBounds(33, 41, 4, 4), layer2.raster) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(layer1, moved)), options, oldRasterOf)) + assertEquals(listOf(tile2), plan.reload.replacedTiles.map { replaced -> replaced.oldId }) + val carried = plan.reload.drawableMeshes.getValue(DrawableId("d2")) + assertSame(editedMesh2.positions, carried.positions, "positions pass through by reference") + assertContentEquals(floatArrayOf(-0.75f, -0.25f, -0.5f, -0.25f, -0.75f, 0f), carried.uvs) + assertEquals(listOf(DrawableId("d2")), plan.reload.outgrown, "the moved art now reaches past the small mesh") + } + + @Test + fun addedAndRemovedLayersLandUnderTheSameFile() { + val third = TestLayer("lyid:3", "Three", 2, LayerBounds(50, 50, 2, 2), solidRaster(2, 2, 3)) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(layer1, third)), options, oldRasterOf)) + assertTrue(plan.reload.replacedTiles.isEmpty(), "neither kept layer changed") + val additions = assertNotNull(plan.reload.additions) + assertEquals(listOf(AtlasTileId("art-0/lyid:3")), additions.tiles.map { tile -> tile.id }) + assertEquals(SourceLayerRef(source, "lyid:3", true), additions.tiles.single().source, "the added tile binds under the existing file") + assertEquals(listOf("ArtMesh1"), additions.drawables.map { drawable -> drawable.id.raw }, "ids mint past the model's") + assertEquals(listOf("lyid:1", "lyid:3", "lyid:2"), plan.reload.source.layers.map { layer -> layer.key }, "the removed layer's row is kept after the fresh ones while a tile binds it") + assertEquals(listOf(true, true, false), plan.reload.source.layers.map { layer -> layer.present }) + assertTrue(plan.reload.source.layers.none { layer -> layer.replaced }, "a layer that left the file is not a replacement's loss") + assertEquals(listOf(ReconcileResult.NeedsReview(ref2, ReviewReason.LayerMissing)), plan.report.needsReview) + assertTrue(plan.rasterByTile.containsKey(AtlasTileId("art-0/lyid:3"))) + } + + /** + * A reload that finds a new layer inside a folder the document already holds as a part (the case + * of every CMO3-origin document, whose parts are the PSD's folders) lands it in that part and mints + * no part for any folder it added nothing to. + */ + @Test + fun anAddedLayerJoinsTheExistingPartOfItsFolderAndUntouchedFoldersMintNothing() { + val headLayer1 = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), solidRaster(4, 4, 1), groupPath = "Head") + val bodyLayer2 = TestLayer("lyid:2", "Two", 1, LayerBounds(30, 40, 4, 4), solidRaster(4, 4, 2), groupPath = "Body") + val base = model() + val headPart = PartId("Part1") + val bodyPart = PartId("Part2") + val model = + base.copy( + parts = + listOf( + Part(headPart, "Head", listOf(OrgChild.Drawable(DrawableId("d1")))), + Part(bodyPart, "Body", listOf(OrgChild.Drawable(DrawableId("d2")))), + ), + rootChildren = listOf(OrgChild.Part(headPart), OrgChild.Part(bodyPart)), + sources = listOf(ArtSource(source, "a.psd", "/a.psd", "psd", SourceArtImport.inventoryOf(TestArt(listOf(headLayer1, bodyLayer2))))), + ) + val brow = TestLayer("lyid:3", "Brow", 2, LayerBounds(50, 50, 2, 2), solidRaster(2, 2, 3), groupPath = "Head") + val art = TestArt(listOf(headLayer1, bodyLayer2, brow), groups = listOf(TestGroup("Head"), TestGroup("Body"), TestGroup("Legs"))) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model, source, art, options, oldRasterOf)) + val additions = assertNotNull(plan.reload.additions) + assertTrue(additions.parts.isEmpty(), "no part is minted: Head exists, and Body and Legs gained nothing") + assertTrue(additions.rootChildren.isEmpty()) + assertEquals( + listOf(OrgInsertion(headPart, OrgChild.Drawable(DrawableId("ArtMesh1")), OrgSlot.After(OrgChild.Drawable(DrawableId("d1"))))), + additions.insertions, + "the brow joins the Head part, right after the layer above it in the file", + ) + } + + @Test + fun aRelinkPullsTheTargetLayer() { + val art = TestArt(listOf(layer1, layer2)) + val plan = assertNotNull(ArtworkReloadPlanner.planRelink(model(), tile1, ref2, art, options, oldRasterOf)) + val replaced = plan.reload.replacedTiles.single() + assertEquals(tile1, replaced.oldId) + assertEquals(ref2, replaced.tile.source, "the replacement carries the new binding") + assertEquals("Two", replaced.tile.name) + assertSame(layer2.raster, plan.rasterByTile.getValue(replaced.tile.id)) + assertNull(ArtworkReloadPlanner.planRelink(model(), tile1, ref1, art, options, oldRasterOf), "the same binding over the same art pulls nothing") + assertNull(ArtworkReloadPlanner.planRelink(model(), tile1, SourceLayerRef(source, "lyid:9", true), art, options, oldRasterOf), "a layer the file lacks pulls nothing") + } + + @Test + fun aRelinkAcrossFilesReadsTheOldRowFromTheTilesOwnFile() { + // Tile 2 (file a, layer at (30, 40)) moves to file b's layer at (50, 60). The edited mesh stays on + // the canvas, so its coordinates carry by the delta between the OLD row in file a and the new + // layer: read the old row from file b instead and the carry would be zero. + val other = ArtSourceId("art-1") + val layer3 = TestLayer("lyid:3", "Three", 0, LayerBounds(50, 60, 4, 4), solidRaster(4, 4, 3)) + val otherArt = TestArt(listOf(layer3)) + val model = model().let { base -> base.copy(sources = base.sources + ArtSource(other, "b.psd", "/b.psd", "psd", SourceArtImport.inventoryOf(otherArt))) } + val target = SourceLayerRef(other, "lyid:3", true) + val plan = assertNotNull(ArtworkReloadPlanner.planMatches(model, other, otherArt, listOf(tile2 to "lyid:3"), options, oldRasterOf)) + val replaced = plan.reload.replacedTiles.single() + assertEquals(tile2, replaced.oldId) + assertEquals(target, replaced.tile.source) + val carried = plan.reload.drawableMeshes.getValue(DrawableId("d2")) + assertContentEquals(floatArrayOf(-5f, -5f, -4.75f, -5f, -5f, -4.75f), carried.uvs, "carried by the old row's origin in file a") + assertEquals(other, plan.reload.source.id, "the target file's record is the one refreshed") + assertEquals(listOf("lyid:3"), plan.reload.source.layers.map { layer -> layer.key }) + assertTrue(plan.reload.source.layers.single().present, "the new binding's row is present, not lost") + } + + /** + * A file placed on the document canvas (its record carries an offset) reloads in the document frame: + * the read is placed by the record before the planner sees it, so an unchanged file plans nothing, a + * repainted layer's untouched quad is re-born at the PLACED position, and the refreshed record keeps + * the offset. + */ + @Test + fun aPlacedFileReloadsInTheDocumentFrameAndKeepsItsOffset() { + // Placed 100 px right and 200 px DOWN the canvas, which is z = -200 in the world axes. + val offset = CanvasOffset(100, -200) + val placedArt = TestArt(listOf(layer1, layer2)).placedBy(offset) + val placedQuad1 = SourceArtImport.birthMeshFor(placedArt.layers[0], options.alphaThreshold, options.birthMeshMargin)!! + val base = model() + val placedModel = + base.copy( + drawables = base.drawables.map { drawable -> if (drawable.id == DrawableId("d1")) drawable.copy(mesh = placedQuad1) else drawable }, + sources = listOf(ArtSource(source, "a.psd", "/a.psd", "psd", SourceArtImport.inventoryOf(placedArt), offsetX = offset.x, offsetZ = offset.z)), + ) + val record = placedModel.sources.single() + assertEquals(110 to 220, record.layers.first().let { row -> row.left to row.top }, "the inventory is in the document frame") + + assertNull(ArtworkReloadPlanner.plan(placedModel, source, TestArt(listOf(layer1, layer2)).placedFor(record), options, oldRasterOf), "the same file, placed the same way, plans nothing") + + val repainted = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 6, 6), solidRaster(6, 6, 9)) + val plan = assertNotNull(ArtworkReloadPlanner.plan(placedModel, source, TestArt(listOf(repainted, layer2)).placedFor(record), options, oldRasterOf)) + assertEquals(listOf(tile1), plan.reload.replacedTiles.map { replaced -> replaced.oldId }) + val reborn = plan.reload.drawableMeshes.getValue(DrawableId("d1")) + assertContentEquals(floatArrayOf(108f, 218f, 118f, 218f, 118f, 228f, 108f, 228f), reborn.positions, "re-born over the repainted art at its placed position") + assertEquals(offset.x to offset.z, plan.reload.source.offsetX to plan.reload.source.offsetZ, "the refreshed record keeps the offset") + assertEquals(110 to 220, plan.reload.source.layers.first { row -> row.key == "lyid:1" }.let { row -> row.left to row.top }, "and its rows stay in the document frame") + } + + /** + * A relink onto a placed file carries the mesh by the OLD row in the tile's own file against the + * target layer's PLACED bounds, so the canvas-attached vertex keeps sampling the same canvas pixel. + */ + @Test + fun aRelinkOntoAPlacedFileCarriesAgainstThePlacedLayer() { + val other = ArtSourceId("art-1") + val layer3 = TestLayer("lyid:3", "Three", 0, LayerBounds(50, 60, 4, 4), solidRaster(4, 4, 3)) + val otherRecord = ArtSource(other, "b.psd", "/b.psd", "psd", offsetX = -20, offsetZ = 19) + val otherArt = TestArt(listOf(layer3)).placedFor(otherRecord) + val model = model().let { base -> base.copy(sources = base.sources + otherRecord.copy(layers = SourceArtImport.inventoryOf(otherArt))) } + val plan = assertNotNull(ArtworkReloadPlanner.planMatches(model, other, otherArt, listOf(tile2 to "lyid:3"), options, oldRasterOf)) + val carried = plan.reload.drawableMeshes.getValue(DrawableId("d2")) + // The target sits at (30, 41) placed: the old row's (30, 40) is one pixel above it, so every + // coordinate moves up by a quarter of the 4 px raster. + assertContentEquals(floatArrayOf(0f, -0.25f, 0.25f, -0.25f, 0f, 0f), carried.uvs, "carried against the placed bounds") + assertEquals(-20 to 19, plan.reload.source.offsetX to plan.reload.source.offsetZ, "the target's record keeps its offset") + } + + /** The read's modification time rides the refreshed record like the hash, and alone plans nothing. */ + @Test + fun theModificationTimeIsRecordedLikeTheHashAndAloneChangesNothing() { + val art = TestArt(listOf(layer1, layer2)) + assertNull(ArtworkReloadPlanner.plan(model(), source, art, options, oldRasterOf, contentHash = "h", lastModified = 5L), "a time and hash alone plan nothing") + val repainted = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), solidRaster(4, 4, 9)) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(repainted, layer2)), options, oldRasterOf, contentHash = "h", lastModified = 5L)) + assertEquals(5L, plan.reload.source.lastModified) + assertEquals("h", plan.reload.source.contentHash) + val matched = assertNotNull(ArtworkReloadPlanner.planMatches(model(), source, art, listOf(tile1 to "lyid:2"), options, oldRasterOf, lastModified = 7L)) + assertEquals(7L, matched.reload.source.lastModified) + val replaced = assertNotNull(ArtworkReloadPlanner.plan(model(), source, art, options, oldRasterOf, replacement = ArtSourceDescriptor("b.psd", "/b.psd", "psd", lastModified = 9L))) + assertEquals(9L, replaced.reload.source.lastModified, "a replacement records its own file's time") + } + + /** + * A layer erased to nothing is not a deletion the reconcile can act on: the tile keeps its art, the + * inventory records the layer as empty, and the binding goes to review with its own reason - the + * artist may have deleted it this way or left it blank on purpose. + */ + @Test + fun aLayerErasedToNothingLeavesItsTileAndGoesToReview() { + val erased = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), LayerRaster(4, 4, ByteArray(64))) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(erased, layer2)), options, oldRasterOf)) + assertTrue(plan.reload.replacedTiles.isEmpty()) + assertEquals(listOf(SourceArtImportNotice.EmptyLayer("One")), plan.notices) + assertEquals(listOf(ReconcileResult.NeedsReview(ref1, ReviewReason.LayerEmptied)), plan.report.needsReview) + val row = plan.reload.source.layers.first { layer -> layer.key == "lyid:1" } + assertTrue(row.present && row.empty, "still in the file, recorded as empty") + assertEquals(listOf(10, 20, 4, 4), listOf(row.left, row.top, row.width, row.height), "with the frame the art last had, not the collapse") + + // The artist undoes the erasure (the art program saves the layer collapsed to nothing meanwhile): + // the art is back where the tile's art came from, so nothing is replaced and no coordinate moves. + val collapsed = TestLayer("lyid:1", "One", 0, LayerBounds(0, 0, 0, 0), LayerRaster(0, 0, ByteArray(0))) + val whileErased = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(collapsed, layer2)), options, oldRasterOf)) + val erasedModel = model().copy(sources = listOf(whileErased.reload.source)) + val restored = assertNotNull(ArtworkReloadPlanner.plan(erasedModel, source, TestArt(listOf(layer1, layer2)), options, oldRasterOf)) + assertTrue(restored.reload.replacedTiles.isEmpty(), "the same art at the same frame replaces nothing") + assertTrue(restored.reload.drawableMeshes.isEmpty(), "and moves no coordinate") + assertTrue(restored.report.needsReview.isEmpty(), "and the review is over") + val back = restored.reload.source.layers.first { layer -> layer.key == "lyid:1" } + assertTrue(back.present && !back.empty, "the row reads as art again") + } + + @Test + fun acceptedMatchesReplaceTheirTilesInOnePlanAndDropTheLostRows() { + // Layer 2 was renamed under a new key and left for review by an earlier reload (its bar raised + // past the match), so its row is kept not present and the tile still binds the old key; the + // matcher's accepted pair moves the tile to the new layer. + val renamed = TestLayer("lyid:5", "Two (final)", 1, LayerBounds(30, 40, 4, 4), layer2.raster) + val previous = model().sources.single() + val lostRows = inventoryWithMissing(previous.layers, SourceArtImport.inventoryOf(TestArt(listOf(layer1, renamed))), boundKeys = setOf("lyid:1", "lyid:2")) + assertEquals(listOf(true, true, false), lostRows.map { layer -> layer.present }) + val model = model().copy(sources = listOf(previous.copy(layers = lostRows))) + val plan = assertNotNull(ArtworkReloadPlanner.planMatches(model, source, TestArt(listOf(layer1, renamed)), listOf(tile2 to "lyid:5"), options, oldRasterOf)) + val replaced = plan.reload.replacedTiles.single() + assertEquals(tile2, replaced.oldId) + assertEquals(SourceLayerRef(source, "lyid:5", true), replaced.tile.source) + assertEquals("Two (final)", replaced.tile.name) + assertEquals(listOf(ReconcileResult.Matched(SourceLayerRef(source, "lyid:5", true), "lyid:5")), plan.report.results) + assertEquals(listOf("lyid:1", "lyid:5"), plan.reload.source.layers.map { layer -> layer.key }, "the lost row leaves once nothing binds it") + assertNull(plan.reload.additions) + assertNull(ArtworkReloadPlanner.planMatches(model, source, TestArt(listOf(layer1, renamed)), listOf(tile2 to "lyid:9"), options, oldRasterOf), "a key the file lacks rebinds nothing") + } + + @Test + fun aReplacementRewritesTheRecordReboundsTheConfidentBindingsAndFlagsTheRest() { + // The same art saved from another program: new keys for the same layers, so both bindings are + // rebound by their pixels inside the replace step itself. + val clipOne = TestLayer("clip:a", "One", 0, LayerBounds(10, 20, 4, 4), layer1.raster) + val clipTwo = TestLayer("clip:b", "Two", 1, LayerBounds(30, 40, 4, 4), layer2.raster) + val descriptor = ArtSourceDescriptor("a.clip", "/a.clip", "clip") + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(clipOne, clipTwo)), options, oldRasterOf, contentHash = "h", replacement = descriptor)) + assertEquals("a.clip", plan.reload.source.name) + assertEquals("/a.clip", plan.reload.source.path) + assertEquals("clip", plan.reload.source.format) + assertEquals("h", plan.reload.source.contentHash) + assertEquals(listOf(tile1, tile2), plan.reload.replacedTiles.map { replaced -> replaced.oldId }, "both bindings rebound") + assertEquals(listOf(SourceLayerRef(source, "clip:a", true), SourceLayerRef(source, "clip:b", true)), plan.reload.replacedTiles.map { replaced -> replaced.tile.source }) + assertEquals(listOf(ReconcileResult.Rebound(ref1, "clip:a", 1f), ReconcileResult.Rebound(ref2, "clip:b", 1f)), plan.report.results) + assertEquals(listOf("clip:a", "clip:b"), plan.reload.source.layers.map { layer -> layer.key }, "no lost row remains") + assertNull(plan.reload.additions) + + // Art that resolves nothing: every binding is flagged as replaced, and the new file's layers stay + // unbound as the candidates the review matches against. + val strangers = + TestArt( + listOf( + TestLayer("clip:y", "Why", 0, LayerBounds(200, 200, 8, 8), solidRaster(8, 8, 7)), + TestLayer("clip:z", "Zed", 1, LayerBounds(300, 300, 8, 8), solidRaster(8, 8, 8)), + ), + ) + val flagged = assertNotNull(ArtworkReloadPlanner.plan(model(), source, strangers, options, oldRasterOf, contentHash = "h", replacement = descriptor)) + assertEquals(listOf("clip:y", "clip:z", "lyid:1", "lyid:2"), flagged.reload.source.layers.map { layer -> layer.key }) + assertEquals(listOf(true, true, false, false), flagged.reload.source.layers.map { layer -> layer.present }) + assertEquals(listOf(false, false, true, true), flagged.reload.source.layers.map { layer -> layer.replaced }, "the rows the replace lost say so") + assertTrue(flagged.reload.replacedTiles.isEmpty(), "no binding resolved by key or by match") + assertNull(flagged.reload.additions, "the new file's layers stay unbound as the candidates the review matches against") + assertEquals( + listOf(ReconcileResult.NeedsReview(ref1, ReviewReason.SourceReplaced), ReconcileResult.NeedsReview(ref2, ReviewReason.SourceReplaced)), + flagged.report.needsReview, + ) + // A same-format twin resolves by key and the plan still lands, if only to rewrite the record. + val twin = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(layer1, layer2)), options, oldRasterOf, replacement = ArtSourceDescriptor("b.psd", "/b.psd", "psd"))) + assertEquals("b.psd", twin.reload.source.name) + assertTrue(twin.report.needsReview.isEmpty()) + + // The replacement stands in for the same art, so the record's placement on the canvas is kept. + val placedModel = model().let { base -> base.copy(sources = base.sources.map { record -> record.copy(offsetX = 5, offsetZ = 6) }) } + val placedTwin = assertNotNull(ArtworkReloadPlanner.plan(placedModel, source, TestArt(listOf(layer1, layer2)), options, oldRasterOf, replacement = ArtSourceDescriptor("b.psd", "/b.psd", "psd"))) + assertEquals(5 to 6, placedTwin.reload.source.offsetX to placedTwin.reload.source.offsetZ, "the replaced record keeps its offset") + } + + @Test + fun aReCreatedLayerIsReboundInTheReloadInsteadOfMinted() { + // Layer 1 deleted and re-created under a new key (a duplicate, a paste) with its pixels and place: + // the rigged tile follows it in the same step and nothing is minted beside it. + val recreated = TestLayer("lyid:3", "One", 0, LayerBounds(10, 20, 4, 4), layer1.raster) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(recreated, layer2)), options, oldRasterOf)) + val replaced = plan.reload.replacedTiles.single() + assertEquals(tile1, replaced.oldId) + assertEquals(SourceLayerRef(source, "lyid:3", true), replaced.tile.source) + assertEquals("One", replaced.tile.name) + assertSame(recreated.raster, plan.rasterByTile.getValue(replaced.tile.id)) + assertNull(plan.reload.additions, "the re-created layer is not minted beside the rebound tile") + assertTrue(plan.reload.retiredTiles.isEmpty()) + assertEquals(listOf(ReconcileResult.Rebound(ref1, "lyid:3", 1f), ReconcileResult.Matched(ref2, "lyid:2")), plan.report.results) + assertTrue(plan.report.needsReview.isEmpty()) + assertEquals(listOf("lyid:3", "lyid:2"), plan.reload.source.layers.map { layer -> layer.key }, "no lost row is kept") + assertTrue(plan.reload.source.layers.all { layer -> layer.present }) + assertTrue(plan.leftovers.isEmpty()) + val expected = SourceArtImport.birthMeshFor(recreated, options.alphaThreshold, options.birthMeshMargin)!! + assertContentEquals(expected.positions, plan.reload.drawableMeshes.getValue(DrawableId("d1")).positions, "the untouched quad is re-born over the layer") + } + + @Test + fun belowTheBarTheLayerIsMintedAndTheRowStaysForReviewWhileALowerBarRebinds() { + // Layer 1 deleted and an unrelated layer added: nothing near the bar, so the stranger is minted + // and the binding waits for a person; the same read at a lower bar rebinds instead. + val stranger = TestLayer("lyid:3", "Something else", 0, LayerBounds(200, 200, 8, 8), solidRaster(8, 8, 7)) + val art = TestArt(listOf(stranger, layer2)) + val atBar = assertNotNull(ArtworkReloadPlanner.plan(model(), source, art, options, oldRasterOf)) + assertEquals(listOf(ReconcileResult.NeedsReview(ref1, ReviewReason.LayerMissing)), atBar.report.needsReview) + assertEquals(listOf(AtlasTileId("art-0/lyid:3")), assertNotNull(atBar.reload.additions).tiles.map { tile -> tile.id }, "the stranger is minted") + assertTrue(atBar.reload.replacedTiles.isEmpty()) + assertEquals(listOf(true, true, false), atBar.reload.source.layers.map { layer -> layer.present }) + val leftover = assertNotNull(atBar.leftovers["lyid:1"], "the proposal under the bar is handed out, scored before the mint") + assertEquals("lyid:3", leftover.key) + val lowered = assertNotNull(ArtworkReloadPlanner.plan(model(), source, art, options, oldRasterOf, matchThreshold = 0f)) + assertEquals(tile1, lowered.reload.replacedTiles.single().oldId) + assertNull(lowered.reload.additions) + val rebound = lowered.report.results.filterIsInstance().single() + assertEquals("lyid:3", rebound.layerKey) + assertTrue(rebound.score < InventoryLayerMatcher.DEFAULT_THRESHOLD, "well under the default bar: ${rebound.score}") + assertTrue(lowered.report.needsReview.isEmpty()) + assertTrue(lowered.leftovers.isEmpty()) + } + + @Test + fun twoLostKeysPreferringOneAddedLayerSettleOnTheMoreConfident() { + // Both layers deleted and one re-created with layer 1's pixels; the other lost binding hashes to + // it too (the same pixels), so the first in binding order takes it and the other waits. + val samePixels = TestLayer("lyid:2", "Two", 1, LayerBounds(30, 40, 4, 4), layer1.raster) + val model = model().copy(sources = listOf(ArtSource(source, "a.psd", "/a.psd", "psd", SourceArtImport.inventoryOf(TestArt(listOf(layer1, samePixels)))))) + val rasters = mapOf(tile1 to layer1.raster, tile2 to layer1.raster) + val twin = TestLayer("lyid:3", "One", 0, LayerBounds(10, 20, 4, 4), layer1.raster) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model, source, TestArt(listOf(twin)), options, { tileId -> rasters[tileId] })) + assertEquals(listOf(tile1), plan.reload.replacedTiles.map { replaced -> replaced.oldId }, "one binding takes the twin") + assertEquals(listOf(ReconcileResult.NeedsReview(ref2, ReviewReason.LayerMissing)), plan.report.needsReview, "the other stays for review") + assertNull(plan.reload.additions, "the twin is not minted, it was claimed") + assertEquals(listOf("lyid:3", "lyid:2"), plan.reload.source.layers.map { layer -> layer.key }) + assertEquals(listOf(true, false), plan.reload.source.layers.map { layer -> layer.present }) + } + + @Test + fun anAcceptedMatchRetiresTheUntouchedDrawableOverItsLayerAndKeepsARiggedOne() { + // Layer 1 was re-created under lyid:3 and an earlier reload minted a fresh drawable for it (the + // match scored under the bar); accepting the reload's proposal now moves the rigged tile onto the + // layer and retires the fresh drawable with its tile - the tile the proposal named, and only + // when it still carries no rig work: the same fresh drawable, once edited, stays, and the layer + // is then bound twice for a person to sort out. + val recreated = TestLayer("lyid:3", "One", 0, LayerBounds(10, 20, 4, 4), layer1.raster) + val freshQuad = SourceArtImport.birthMeshFor(recreated, options.alphaThreshold, options.birthMeshMargin)!! + val tile3 = AtlasTileId("art-0/lyid:3") + val base = model() + val freshInventory = + inventoryWithMissing(base.sources.single().layers, SourceArtImport.inventoryOf(TestArt(listOf(recreated, layer2))), boundKeys = setOf("lyid:1", "lyid:2", "lyid:3")) + val afterMint = + base.copy( + drawables = base.drawables + drawable("d3", tile3, freshQuad), + rootChildren = base.rootChildren + OrgChild.Drawable(DrawableId("d3")), + atlas = base.atlas.copy(tiles = base.atlas.tiles + AtlasTile(tile3, "One", 4, 4, source = SourceLayerRef(source, "lyid:3", true))), + sources = listOf(base.sources.single().copy(layers = freshInventory)), + ) + val rasters = oldRasters + (tile3 to recreated.raster) + val art = TestArt(listOf(recreated, layer2)) + assertTrue(suggestionsFor(afterMint, source).isEmpty(), "on the model alone the bound layer is no candidate; the proposal is the reload's") + val plan = assertNotNull(ArtworkReloadPlanner.planMatches(afterMint, source, art, listOf(tile1 to "lyid:3"), options, { tileId -> rasters[tileId] }, retire = setOf(tile3))) + assertEquals(tile1, plan.reload.replacedTiles.single().oldId) + assertEquals(listOf(tile3), plan.reload.retiredTiles, "the fresh drawable's tile goes with the move") + assertEquals(listOf("lyid:3", "lyid:2"), plan.reload.source.layers.map { layer -> layer.key }, "the lost row leaves; the claimed layer stays bound through the rebound tile") + val unnamed = assertNotNull(ArtworkReloadPlanner.planMatches(afterMint, source, art, listOf(tile1 to "lyid:3"), options, { tileId -> rasters[tileId] })) + assertTrue(unnamed.reload.retiredTiles.isEmpty(), "a relink that names nothing retires nothing") + + val editedFresh = DrawableMesh(floatArrayOf(10f, 20f, 11f, 20f, 10f, 21f), floatArrayOf(0f, 0f, 0.25f, 0f, 0f, 0.25f), intArrayOf(0, 1, 2)) + val edited = afterMint.copy(drawables = afterMint.drawables.map { drawable -> if (drawable.id.raw == "d3") drawable.copy(mesh = editedFresh) else drawable }) + val kept = assertNotNull(ArtworkReloadPlanner.planMatches(edited, source, art, listOf(tile1 to "lyid:3"), options, { tileId -> rasters[tileId] }, retire = setOf(tile3))) + assertTrue(kept.reload.retiredTiles.isEmpty(), "rig work over the layer is never removed, whatever the proposal named") + } + + @Test + fun anIgnoredLayerIsNeverMintedUntilTheMarkIsCleared() { + // A third layer the rigger ignored (a sketch kept in the file): every reload finds it unbound and + // leaves it out, the mark rides the refreshed inventory, and the matcher never proposes it; clear + // the mark and the next reload mints it. + val third = TestLayer("lyid:3", "Sketch", 2, LayerBounds(50, 50, 2, 2), solidRaster(2, 2, 3)) + val art = TestArt(listOf(layer1, layer2, third)) + val base = model() + val listed = base.copy(sources = listOf(base.sources.single().copy(layers = SourceArtImport.inventoryOf(art).map { row -> if (row.key == "lyid:3") row.copy(ignored = true) else row }))) + assertNull(ArtworkReloadPlanner.plan(listed, source, art, options, oldRasterOf), "nothing to do: the ignored layer is not an addition") + val repainted = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), solidRaster(4, 4, 9)) + val plan = assertNotNull(ArtworkReloadPlanner.plan(listed, source, TestArt(listOf(repainted, layer2, third)), options, oldRasterOf)) + assertNull(plan.reload.additions, "the ignored layer stays out while another layer reloads") + assertTrue(plan.report.results.none { result -> result is ReconcileResult.Added }) + assertTrue(plan.reload.source.layers.first { layer -> layer.key == "lyid:3" }.ignored, "the mark rides the refreshed inventory") + assertTrue(suggestionsFor(listed, source).isEmpty(), "and the matcher never proposes it") + val cleared = listed.copy(sources = listOf(listed.sources.single().copy(layers = listed.sources.single().layers.map { row -> row.copy(ignored = false) }))) + val minted = assertNotNull(ArtworkReloadPlanner.plan(cleared, source, art, options, oldRasterOf)) + assertEquals(listOf(AtlasTileId("art-0/lyid:3")), assertNotNull(minted.reload.additions).tiles.map { tile -> tile.id }, "un-ignored, the next reload mints it") + } + + @Test + fun aLayerEyeToggleFollowsIntoAnUntouchedDrawableAndLeavesAToggledOne() { + // Layer 1 hidden in the file: d1 still shows the state the file last had (shown), so it follows, + // with no tile replaced. Hidden by the rigger first, d1 already differs from that state - its + // toggle is rig work - so the file's toggle changes nothing. + val hidden = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), layer1.raster, visible = false) + val plan = assertNotNull(ArtworkReloadPlanner.plan(model(), source, TestArt(listOf(hidden, layer2)), options, oldRasterOf)) + assertEquals(mapOf(DrawableId("d1") to false), plan.reload.drawableVisibility) + assertTrue(plan.reload.replacedTiles.isEmpty(), "an eye toggle replaces no tile") + assertEquals(false, plan.reload.source.layers.first { layer -> layer.key == "lyid:1" }.visible, "the inventory records the new state") + + // d1 hidden while the inventory still says shown: the rigger's own toggle, so the file hiding the + // layer changes nothing; once the inventory records hidden too, the file showing it again is + // followed, since d1 then shows exactly the state the file last had. + val riggerHid = model().let { base -> base.copy(drawables = base.drawables.map { drawable -> if (drawable.id.raw == "d1") drawable.copy(isVisible = false) else drawable }) } + val untouched = assertNotNull(ArtworkReloadPlanner.plan(riggerHid, source, TestArt(listOf(hidden, layer2)), options, oldRasterOf)) + assertTrue(untouched.reload.drawableVisibility.isEmpty(), "a drawable the rigger already hid is left alone") + assertEquals(false, untouched.reload.source.layers.first { layer -> layer.key == "lyid:1" }.visible, "while the inventory still records the file's state") + val recorded = riggerHid.copy(sources = listOf(untouched.reload.source)) + assertNull(ArtworkReloadPlanner.plan(recorded, source, TestArt(listOf(hidden, layer2)), options, oldRasterOf), "recorded and unchanged: nothing to do") + val shownAgain = assertNotNull(ArtworkReloadPlanner.plan(recorded, source, TestArt(listOf(layer1, layer2)), options, oldRasterOf)) + assertEquals(mapOf(DrawableId("d1") to true), shownAgain.reload.drawableVisibility, "shown again in the file, a hidden drawable that matches the recorded state follows back") + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/InventoryLayerMatcherTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/InventoryLayerMatcherTest.kt new file mode 100644 index 0000000..5b1bbb6 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/InventoryLayerMatcherTest.kt @@ -0,0 +1,108 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerRaster +import org.umamo.runtime.model.ArtSourceLayer +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The inventory matcher's signals and their combination: a hash match is certain, a rename at the + * same place scores high, a namesake far away scores low, pixels count when they can be read, and + * only the best few candidates pay for a pixel comparison. + */ +class InventoryLayerMatcherTest { + private fun row(key: String, name: String, left: Int, top: Int, width: Int, height: Int, groupPath: String = "", hash: String? = null): ArtSourceLayer = + ArtSourceLayer(key, name, groupPath, left, top, width, height, visible = true, contentHash = hash) + + private fun candidate(row: ArtSourceLayer, raster: LayerRaster? = null): MatchCandidate = MatchCandidate(row) { raster } + + @Test + fun aContentHashMatchIsCertainWhateverTheNameAndPlace() { + val missing = row("lyid:1", "Hair Front", 10, 20, 40, 40, hash = "abc") + val ranked = + InventoryLayerMatcher.rank( + missing, + null, + listOf(candidate(row("lyid:7", "Hair Front", 12, 22, 40, 40)), candidate(row("lyid:9", "Untitled 3", 500, 500, 8, 8, hash = "abc"))), + ) + assertEquals("lyid:9", ranked.first().key) + assertEquals(1f, ranked.first().score) + assertTrue(ranked.first().signals.hashEqual) + } + + @Test + fun aRenamedLayerAtTheSamePlaceScoresAboveTheThresholdAndANamesakeFarAwayBelowIt() { + val missing = row("lyid:1", "Hair Front", 10, 20, 40, 40, groupPath = "Head") + val ranked = + InventoryLayerMatcher.rank( + missing, + null, + listOf(candidate(row("lyid:2", "Hair Front 2", 10, 20, 40, 40, groupPath = "Head")), candidate(row("lyid:3", "Hair Front", 900, 900, 400, 10, groupPath = "Body"))), + ) + assertEquals(listOf("lyid:2", "lyid:3"), ranked.map { match -> match.key }) + assertTrue(ranked[0].score >= InventoryLayerMatcher.DEFAULT_THRESHOLD, "renamed in place: ${ranked[0].score}") + assertTrue(ranked[1].score < InventoryLayerMatcher.DEFAULT_THRESHOLD, "a namesake elsewhere: ${ranked[1].score}") + assertNull(ranked[0].signals.pixels, "no pixels were read") + } + + @Test + fun aRowWithNoKnownExtentScoresOnNameAndPathAlone() { + val missing = row("lyid:1", "Hair Front", 0, 0, 0, 0) + val match = InventoryLayerMatcher.rank(missing, null, listOf(candidate(row("lyid:2", "Hair Front", 300, 300, 40, 40)))).single() + assertNull(match.signals.bounds) + assertNull(match.signals.size) + assertEquals(1f, match.score, "the name and path agree, and nothing else could be scored") + } + + @Test + fun nameSimilarityIgnoresCaseAndSpacing() { + assertEquals(1f, nameSimilarity("Hair Front", "hair front")) + assertEquals(1f, nameSimilarity("", "")) + assertTrue(nameSimilarity("Hair Front", "Hair Front 2") > 0.8f) + assertTrue(nameSimilarity("Eye L", "Mouth") < 0.3f) + } + + @Test + fun pathAgreementCountsSharedLeadingFolders() { + assertEquals(1f, pathAgreement("", "")) + assertEquals(1f, pathAgreement("Head/Hair", "Head/Hair")) + assertEquals(0.5f, pathAgreement("Head", "Head/Hair")) + assertEquals(0f, pathAgreement("Head", "Body")) + } + + @Test + fun pixelSimilarityCountsShapeAndColorAcrossSizes() { + val white = solidRaster(4, 4, 0xFF.toByte()) + assertEquals(1f, pixelSimilarity(white, white)) + assertEquals(1f, pixelSimilarity(white, solidRaster(16, 8, 0xFF.toByte())), "the same picture at another size resamples alike") + val black = solidRaster(4, 4, 0) + assertEquals(0.5f, pixelSimilarity(white, black), "the same shape, opposite colors") + val empty = LayerRaster(4, 4, ByteArray(64)) + assertEquals(0f, pixelSimilarity(white, empty), "nothing in common") + assertEquals(1f, pixelSimilarity(empty, empty)) + assertEquals(0f, pixelSimilarity(white, LayerRaster(0, 0, ByteArray(0)))) + } + + @Test + fun pixelsJoinTheScoreWhenReadAndOnlyForTheBestFewCandidates() { + val missing = row("lyid:1", "Hair", 0, 0, 4, 4) + val missingRaster = solidRaster(4, 4, 0xFF.toByte()) + var reads = 0 + val candidates = + (0 until 8).map { index -> + MatchCandidate(row("lyid:${index + 2}", "Hair $index", 0, 0, 4, 4)) { + reads++ + if (index == 6) missingRaster else solidRaster(4, 4, 0) + } + } + val ranked = InventoryLayerMatcher.rank(missing, missingRaster, candidates) + assertEquals(5, reads, "only the top five metadata candidates are pixel-scored") + assertEquals(5, ranked.count { match -> match.signals.pixels != null }) + val withPixels = ranked.filter { match -> match.signals.pixels != null } + val without = ranked.filter { match -> match.signals.pixels == null } + assertTrue(withPixels.all { match -> match.score < without.first().score }, "opposite pixels pull a candidate below one whose pixels were not read") + assertTrue(without.map { match -> match.key }.contains("lyid:8"), "the seventh candidate by name was never read") + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/KeyReconcilerTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/KeyReconcilerTest.kt new file mode 100644 index 0000000..e427881 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/KeyReconcilerTest.kt @@ -0,0 +1,35 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.SourceLayerKind +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The reconcile by key: matched, added, and missing, with non-raster layers invisible to it. */ +class KeyReconcilerTest { + private val source = ArtSourceId("art-0") + + private fun layer(key: String, order: Int, kind: SourceLayerKind = SourceLayerKind.Raster): TestLayer = + TestLayer(key, key, order, LayerBounds(0, 0, 2, 2), solidRaster(2, 2, 1), kind = kind) + + @Test + fun bindingsMatchByKeyAndTheRestClassify() { + val art = TestArt(listOf(layer("lyid:2", 0), layer("lyid:1", 1), layer("text", 2, SourceLayerKind.Text), layer("lyid:9", 3))) + val bindings = listOf(SourceLayerRef(source, "lyid:1", true), SourceLayerRef(source, "lyid:7", true), SourceLayerRef(source, "text", true)) + val report = KeyReconciler.reconcile(bindings, art) + assertEquals( + listOf( + ReconcileResult.Matched(bindings[0], "lyid:1"), + ReconcileResult.NeedsReview(bindings[1], ReviewReason.LayerMissing), + ReconcileResult.NeedsReview(bindings[2], ReviewReason.LayerMissing), + ReconcileResult.Added("lyid:2"), + ReconcileResult.Added("lyid:9"), + ), + report.results, + "bindings first in their order, then the added raster layers in the art's order; a folder is neither", + ) + assertEquals(2, report.needsReview.size) + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/PollingSourceWatcherTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/PollingSourceWatcherTest.kt new file mode 100644 index 0000000..58e9a18 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/PollingSourceWatcherTest.kt @@ -0,0 +1,108 @@ +package org.umamo.reimport + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runTest +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The polling watcher over an in-memory file system under the test clock: a write, a temp-file-then- + * rename replace, and a delete each reach the listener of the file they touch; a sibling's write does + * not; watching a file is not a change; and a closed subscription hears nothing. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class PollingSourceWatcherTest { + @Test + fun changesToTheWatchedFileReachItsListenerAndNothingElseDoes() = + runTest { + val fileSystem = FakeFileSystem() + val directory = "/art".toPath() + val watched = directory / "art.psd" + val sibling = directory / "other.psd" + fileSystem.createDirectories(directory) + fileSystem.write(watched) { writeUtf8("1") } + fileSystem.write(sibling) { writeUtf8("1") } + val watcher = PollingSourceWatcher(this, fileSystem, pollMillis = 100) + val deliveries = ArrayList() + val handle = watcher.watch(watched.toString()) { path -> deliveries.add(path) } + + advanceTimeBy(250) + assertTrue(deliveries.isEmpty(), "watching a file is not a change") + + // A write that grows the file. + fileSystem.write(watched) { writeUtf8("22") } + advanceTimeBy(100) + assertEquals(listOf(watched.toString()), deliveries, "the listener hears its own path") + + // A sibling's write is not this file's change. + fileSystem.write(sibling) { writeUtf8("22") } + advanceTimeBy(300) + assertEquals(1, deliveries.size, "a sibling file is nobody's change") + + // The save an art program performs: a temporary file renamed over the watched one. + val temporary = directory / "art.psd.tmp" + fileSystem.write(temporary) { writeUtf8("333") } + fileSystem.atomicMove(temporary, watched) + advanceTimeBy(100) + assertEquals(2, deliveries.size, "a rename-replace is a change") + + // A delete is a change, and so is the file returning. + fileSystem.delete(watched) + advanceTimeBy(100) + assertEquals(3, deliveries.size, "a delete is a change") + fileSystem.write(watched) { writeUtf8("4444") } + advanceTimeBy(100) + assertEquals(4, deliveries.size, "a return is a change") + + // Closed: silence, and the poll loop is gone. + handle.close() + fileSystem.write(watched) { writeUtf8("55555") } + advanceTimeBy(300) + assertEquals(4, deliveries.size, "a closed subscription hears nothing") + watcher.close() + } + + @Test + fun aFileWatchedWhileTheLoopRunsIsBaselinedAtOnceSoASaveBeforeTheNextTickIsSeen() = + runTest { + // The loop is already ticking for one file. A second file joins mid-period and is saved + // before the next tick: its baseline must be the stamp at watch time, not the tick's, or the + // save would become the baseline and never be reported. + val fileSystem = FakeFileSystem() + val directory = "/art".toPath() + val first = directory / "a.psd" + val second = directory / "b.psd" + fileSystem.createDirectories(directory) + fileSystem.write(first) { writeUtf8("1") } + fileSystem.write(second) { writeUtf8("1") } + val watcher = PollingSourceWatcher(this, fileSystem, pollMillis = 100) + val deliveries = ArrayList() + watcher.watch(first.toString()) { path -> deliveries.add(path) } + advanceTimeBy(150) + assertTrue(deliveries.isEmpty()) + + val late = watcher.watch(second.toString()) { path -> deliveries.add(path) } + late.awaitArmed() + fileSystem.write(second) { writeUtf8("22") } + advanceTimeBy(100) + assertEquals(listOf(second.toString()), deliveries, "the save after the watch-time baseline is a change") + + // Arming is a one-time event; a closed subscription arms too, so a waiter never hangs. + late.close() + late.awaitArmed() + watcher.close() + } + + @Test + fun aUriGetsANoOpHandle() = + runTest { + val watcher = PollingSourceWatcher(this, FakeFileSystem(), pollMillis = 100) + watcher.watch("content://documents/1") {}.close() + advanceTimeBy(300) + watcher.close() + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/RigWorkTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/RigWorkTest.kt new file mode 100644 index 0000000..2e01811 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/RigWorkTest.kt @@ -0,0 +1,84 @@ +package org.umamo.reimport + +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** What counts as rig work over a tile: anything beyond the birth an import mints. */ +class RigWorkTest { + private val source = ArtSourceId("art-0") + private val tile = AtlasTileId("t") + private val row = ArtSourceLayer("k", "K", "", 50, 50, 10, 10, visible = true) + + /** The birth quad over a 10 x 10 tile whose layer sits at (50, 50). */ + private val birthQuad = DrawableMesh(floatArrayOf(50f, 50f, 60f, 50f, 60f, 60f, 50f, 60f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + + /** The same quad with one corner dragged. */ + private val moved = DrawableMesh(floatArrayOf(50f, 50f, 60f, 50f, 61f, 61f, 50f, 60f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + + private val boundTile = AtlasTile(tile, "K", 10, 10, source = SourceLayerRef(source, "k", true)) + + private fun drawable(id: String, mesh: DrawableMesh? = birthQuad, tileId: AtlasTileId? = tile): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), mesh, null, atlasTileId = tileId) + + private fun model(vararg drawables: Drawable, atlas: PuppetAtlas = PuppetAtlas(tiles = listOf(boundTile)), glues: List = emptyList()): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables.toList(), + rootChildren = emptyList(), + rootPartId = null, + atlas = atlas, + glues = glues, + sources = emptyList(), + ) + + @Test + fun aFreshBirthOverTheTileCarriesNoRigWorkAndAnythingMoreDoes() { + assertTrue(model(drawable("d")).tileCarriesNoRigWork(tile, row), "a birth quad sampling the whole tile at the layer's place") + assertTrue(model().tileCarriesNoRigWork(tile, row), "nothing over the tile at all") + assertTrue(model(drawable("d"), drawable("e")).tileCarriesNoRigWork(tile, row), "two fresh births") + assertFalse(model(drawable("d")).tileCarriesNoRigWork(tile, row = null), "without the row the quad cannot be told untouched") + assertFalse(model(drawable("d")).tileCarriesNoRigWork(AtlasTileId("nope"), row), "a tile the model lacks") + assertFalse(model(drawable("d", mesh = moved)).tileCarriesNoRigWork(tile, row), "a moved vertex") + assertFalse(model(drawable("d"), drawable("e", mesh = moved)).tileCarriesNoRigWork(tile, row), "one of two moved") + assertFalse(model(drawable("d", mesh = null)).tileCarriesNoRigWork(tile, row), "no mesh to judge") + assertFalse(model(drawable("d").copy(parentDeformerId = DeformerId("warp"))).tileCarriesNoRigWork(tile, row), "a parent deformer") + assertFalse(model(drawable("d").copy(maskedBy = listOf(DrawableId("other")))).tileCarriesNoRigWork(tile, row), "a clip mask on it") + assertFalse(model(drawable("d"), drawable("other", tileId = null).copy(maskedBy = listOf(DrawableId("d")))).tileCarriesNoRigWork(tile, row), "it masking another") + assertFalse(model(drawable("d").copy(geometryGrid = KeyformGrid(emptyList(), emptyList()))).tileCarriesNoRigWork(tile, row), "geometry keys") + assertFalse( + model(drawable("d").copy(channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to KeyformGrid(emptyList(), emptyList()))))).tileCarriesNoRigWork(tile, row), + "a channel track", + ) + assertFalse( + model(drawable("d").copy(blendShapes = listOf(BlendShapeBinding(ParameterId("p"), floatArrayOf(0f), 0, listOf(null))))).tileCarriesNoRigWork(tile, row), + "a blend shape", + ) + assertFalse(model(drawable("d"), glues = listOf(Glue(DrawableId("d"), DrawableId("other"), emptyList()))).tileCarriesNoRigWork(tile, row), "a glue") + val degenerate = PuppetAtlas(pages = listOf(AtlasPage(16, 16)), tiles = listOf(boundTile.copy(placement = AtlasPlacement(0, 0f, 0f, 0f, 0f, 0f)))) + assertFalse(model(drawable("d"), atlas = degenerate).tileCarriesNoRigWork(tile, row), "a mapping that cannot be read") + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/SourceWatchCoordinatorTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/SourceWatchCoordinatorTest.kt new file mode 100644 index 0000000..4dd8d77 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/SourceWatchCoordinatorTest.kt @@ -0,0 +1,334 @@ +package org.umamo.reimport + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.umamo.runtime.model.ArtSourceId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The reload policy under a test clock: settling, the hash check that drops a no-op save, the idle + * gate, the three modes, a missing and returning file, the open-time staleness check, and how a + * finished reload feeds back. The watcher is a fake that fires on demand; the disk is a map. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class SourceWatchCoordinatorTest { + private val fileA = ArtSourceId("art-0") + private val fileB = ArtSourceId("art-1") + + /** + * A watcher the test fires by hand, recording who watches what. Every subscription is armed at + * once unless [armByHand] is set, in which case the test arms it through [arm]. + */ + private class FakeWatcher(private val armByHand: Boolean = false) : SourceWatcher { + val listeners = LinkedHashMap>() + val armed = LinkedHashMap>() + + override fun watch(path: String, listener: SourceWatcher.ChangeListener): SourceWatcher.Subscription { + listeners.getOrPut(path) { ArrayList() }.add(listener) + val signal = armed.getOrPut(path) { CompletableDeferred() } + if (!armByHand) { + signal.complete(Unit) + } + return object : SourceWatcher.Subscription { + override suspend fun awaitArmed() { + signal.await() + } + + override fun close() { + listeners[path]?.remove(listener) + signal.complete(Unit) + } + } + } + + fun fire(path: String) { + listeners[path].orEmpty().toList().forEach { listener -> listener.onChanged(path) } + } + + fun arm(path: String) { + armed.getValue(path).complete(Unit) + } + } + + /** The disk: a hash per path, or null for a file that cannot be read; absent means missing. */ + private class Disk { + val hashByPath = HashMap() + val modifiedAtByPath = HashMap() + + fun hashOf(path: String): String? = hashByPath[path] + + fun exists(path: String): Boolean = hashByPath.containsKey(path) + + fun modifiedAt(path: String): Long? = modifiedAtByPath[path] + } + + /** + * The coordinator over the TEST scope itself (this coroutines-test version does not advance + * backgroundScope work on advanceUntilIdle), so every test ends by calling [finish]. + */ + private class Harness(scope: TestScope, val mode: () -> WatchMode, val idle: () -> Boolean = { true }, armByHand: Boolean = false) { + val watcher = FakeWatcher(armByHand) + val disk = Disk() + val events = ArrayList() + val coordinator = + SourceWatchCoordinator( + scope = scope, + watcher = watcher, + hashOf = { path -> disk.hashOf(path) }, + exists = { path -> disk.exists(path) }, + isIdle = idle, + mode = mode, + settleMillis = 100, + idlePollMillis = 10, + modifiedAtOf = { path -> disk.modifiedAt(path) }, + ) + private val collector: Job = scope.launch { coordinator.events.collect { event -> events.add(event) } } + + fun finish() { + coordinator.close() + collector.cancel() + } + } + + private fun TestScope.harness(mode: WatchMode = WatchMode.Auto, idle: () -> Boolean = { true }, armByHand: Boolean = false): Harness = + Harness(this, { mode }, idle, armByHand) + + @Test + fun theOpenTimeHashWaitsForTheWatchToArm() = + runTest { + // The hash must not be read before the watcher holds its baseline: a save between the two + // would otherwise become the baseline and go unreported. Here the disk changes while the + // watch is still arming, and the check reads the state AFTER arming. + val harness = harness(armByHand = true) + harness.disk.hashByPath["/a.psd"] = "h1" + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"))) + advanceTimeBy(1_000) + assertTrue(harness.events.isEmpty(), "nothing is read while the watch arms") + assertTrue(harness.coordinator.pending.value.isEmpty()) + + harness.disk.hashByPath["/a.psd"] = "h2" + harness.watcher.arm("/a.psd") + advanceTimeBy(1) + assertEquals(listOf(SourceWatchEvent.StaleAtOpen(setOf(fileA))), harness.events, "the check ran once armed and saw the change") + assertEquals(setOf(fileA), harness.coordinator.pending.value) + harness.finish() + } + + @Test + fun aWatchStoppedWhileArmingIsSkippedWithoutHanging() = + runTest { + val harness = harness(armByHand = true) + harness.disk.hashByPath["/a.psd"] = "h2" + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"))) + harness.coordinator.track(emptyList()) + advanceTimeBy(1_000) + assertTrue(harness.events.isEmpty(), "an untracked file is never checked") + harness.finish() + } + + @Test + fun aSettledChangeReloadsOnceAndANoOpSaveIsDropped() = + runTest { + val harness = harness() + harness.disk.hashByPath["/a.psd"] = "h1" + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"))) + advanceUntilIdle() + assertTrue(harness.events.isEmpty(), "a file matching its record is quiet at open") + + // A save that changed nothing: the hash is the record's. + harness.watcher.fire("/a.psd") + advanceTimeBy(200) + advanceUntilIdle() + assertTrue(harness.events.isEmpty(), "the same hash is dropped") + assertTrue(harness.coordinator.pending.value.isEmpty()) + + // A real change, written in two bursts inside one settle window. + harness.disk.hashByPath["/a.psd"] = "h2" + harness.watcher.fire("/a.psd") + advanceTimeBy(50) + harness.watcher.fire("/a.psd") + advanceTimeBy(50) + assertTrue(harness.events.isEmpty(), "the second event restarted the settle") + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ReloadDue(setOf(fileA))), harness.events) + assertEquals(setOf(fileA), harness.coordinator.pending.value) + + // The reload landed: the model's record caught up, and tracking it clears the debt. + harness.coordinator.reloadFinished(setOf(fileA), WatchedReloadResult.Applied) + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h2"))) + advanceUntilIdle() + assertTrue(harness.coordinator.pending.value.isEmpty()) + harness.finish() + } + + @Test + fun anUnreadableFileWaitsAndAMissingOneIsReported() = + runTest { + val harness = harness() + harness.disk.hashByPath["/a.psd"] = "h1" + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"))) + advanceUntilIdle() + + // Mid-write: present but unreadable for two windows, then done. + harness.disk.hashByPath["/a.psd"] = null + harness.watcher.fire("/a.psd") + advanceTimeBy(250) + assertTrue(harness.events.isEmpty(), "an unreadable file is waited for") + harness.disk.hashByPath["/a.psd"] = "h2" + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ReloadDue(setOf(fileA))), harness.events) + harness.events.clear() + + // Deleted: reported once, the pending debt dropped, the presence serial bumped. + val serialBefore = harness.coordinator.serial.value + harness.disk.hashByPath.remove("/a.psd") + harness.watcher.fire("/a.psd") + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.Missing(fileA)), harness.events) + assertTrue(harness.coordinator.pending.value.isEmpty()) + assertEquals(serialBefore + 1, harness.coordinator.serial.value) + harness.events.clear() + + // Back, with new content: a change, and the serial moves again. + harness.disk.hashByPath["/a.psd"] = "h3" + harness.watcher.fire("/a.psd") + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ReloadDue(setOf(fileA))), harness.events) + assertEquals(serialBefore + 2, harness.coordinator.serial.value) + harness.finish() + } + + @Test + fun autoWaitsForTheEditorToGoIdleAndGathersWhatArrivedMeanwhile() = + runTest { + var idle = false + val harness = harness(idle = { idle }) + harness.disk.hashByPath["/a.psd"] = "h1" + harness.disk.hashByPath["/b.psd"] = "k1" + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"), WatchedSource(fileB, "/b.psd", "k1"))) + advanceUntilIdle() + harness.disk.hashByPath["/a.psd"] = "h2" + harness.watcher.fire("/a.psd") + advanceTimeBy(500) + assertTrue(harness.events.isEmpty(), "nothing fires while a gesture is in flight") + harness.disk.hashByPath["/b.psd"] = "k2" + harness.watcher.fire("/b.psd") + advanceTimeBy(500) + idle = true + advanceTimeBy(20) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ReloadDue(setOf(fileA, fileB))), harness.events, "one reload for both once idle") + harness.finish() + } + + @Test + fun notifyReportsAndOffTracksNothing() = + runTest { + val notify = harness(WatchMode.Notify) + notify.disk.hashByPath["/a.psd"] = "h1" + notify.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"))) + advanceUntilIdle() + notify.disk.hashByPath["/a.psd"] = "h2" + notify.watcher.fire("/a.psd") + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ChangedOnDisk(setOf(fileA))), notify.events) + assertEquals(setOf(fileA), notify.coordinator.pending.value, "the debt stays until Reload is pressed") + + val off = harness(WatchMode.Off) + off.disk.hashByPath["/a.psd"] = "h1" + off.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h0"))) + advanceUntilIdle() + assertTrue(off.watcher.listeners.values.all { listeners -> listeners.isEmpty() }, "off watches nothing") + assertTrue(off.events.isEmpty()) + notify.finish() + off.finish() + } + + /** + * A file the document recorded no hash for (a CMO3-origin source) is judged at open by its + * modification time against the recorded one; a recorded hash always outranks the time; and with + * neither recorded there is nothing to judge by. + */ + @Test + fun aFileWithNoRecordedHashIsStaleAtOpenByItsModificationTime() = + runTest { + val harness = harness() + harness.disk.hashByPath["/a.psd"] = "h1" + harness.disk.modifiedAtByPath["/a.psd"] = 2_000L + harness.disk.hashByPath["/b.psd"] = "h2" + harness.disk.modifiedAtByPath["/b.psd"] = 2_000L + harness.disk.hashByPath["/c.psd"] = "h3" + harness.disk.modifiedAtByPath["/c.psd"] = 2_000L + harness.coordinator.track( + listOf( + WatchedSource(fileA, "/a.psd", recordedHash = null, recordedModifiedAt = 1_000L), + WatchedSource(fileB, "/b.psd", recordedHash = "h2", recordedModifiedAt = 1_000L), + WatchedSource(ArtSourceId("art-2"), "/c.psd", recordedHash = null, recordedModifiedAt = null), + ), + ) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.StaleAtOpen(setOf(fileA))), harness.events, "only the hash-less file whose time moved is stale; a matching hash outranks a moved time, and no record at all is silent") + assertEquals(setOf(fileA), harness.coordinator.pending.value) + harness.finish() + } + + @Test + fun aFileEditedWhileClosedIsStaleAtOpenAndAFinishedReloadFeedsBack() = + runTest { + val harness = harness() + harness.disk.hashByPath["/a.psd"] = "h9" + harness.coordinator.track(listOf(WatchedSource(fileA, "/a.psd", "h1"))) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.StaleAtOpen(setOf(fileA))), harness.events, "reported, never auto-reloaded") + assertEquals(setOf(fileA), harness.coordinator.pending.value) + harness.events.clear() + + // A reload that found nothing to change acknowledges the disk hash: no further report for it. + harness.coordinator.reloadFinished(setOf(fileA), WatchedReloadResult.NothingChanged) + assertTrue(harness.coordinator.pending.value.isEmpty()) + harness.watcher.fire("/a.psd") + advanceTimeBy(100) + advanceUntilIdle() + assertTrue(harness.events.isEmpty(), "the acknowledged hash is dropped") + + // A superseded reload is tried again after a settle. + harness.disk.hashByPath["/a.psd"] = "h10" + harness.watcher.fire("/a.psd") + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ReloadDue(setOf(fileA))), harness.events) + harness.events.clear() + harness.coordinator.reloadFinished(setOf(fileA), WatchedReloadResult.Superseded) + advanceTimeBy(100) + advanceUntilIdle() + assertEquals(listOf(SourceWatchEvent.ReloadDue(setOf(fileA))), harness.events, "asked again") + + // Untracked files stop; the coordinator closes clean. + harness.coordinator.track(emptyList()) + assertTrue(harness.watcher.listeners.values.all { listeners -> listeners.isEmpty() }) + assertTrue(harness.coordinator.pending.value.isEmpty()) + harness.finish() + } + + @Test + fun theModeKeyRoundTripsAndAStaleValueFallsBack() { + for (mode in WatchMode.entries) { + assertEquals(mode, WatchMode.fromKey(mode.key)) + } + assertEquals(WatchMode.Default, WatchMode.fromKey("not-a-mode")) + assertEquals(WatchMode.Default, WatchMode.fromKey(null)) + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/SuggestionsTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/SuggestionsTest.kt new file mode 100644 index 0000000..e5e8ef0 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/SuggestionsTest.kt @@ -0,0 +1,179 @@ +package org.umamo.reimport + +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** The lost-row retention, the per-row suggestions over a model alone and against a read, and the confident picks. */ +class SuggestionsTest { + private val source = ArtSourceId("art-0") + + private fun row(key: String, name: String, left: Int, top: Int, present: Boolean = true): ArtSourceLayer = + ArtSourceLayer(key, name, "", left, top, 10, 10, visible = true, present = present) + + /** A birth quad over a 10 x 10 tile whose layer sits at (50, 50): what an import mints, and nothing more. */ + private val freshQuad = DrawableMesh(floatArrayOf(50f, 50f, 60f, 50f, 60f, 60f, 50f, 60f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + + /** A three-vertex mesh: edited, so rig work. */ + private val editedMesh = DrawableMesh(floatArrayOf(50f, 50f, 51f, 50f, 50f, 51f), floatArrayOf(0f, 0f, 0.1f, 0f, 0f, 0.1f), intArrayOf(0, 1, 2)) + + private fun drawable(id: String, tileId: String, mesh: DrawableMesh): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), mesh, null, atlasTileId = AtlasTileId(tileId)) + + private fun model(drawables: List, tiles: List, layers: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + atlas = PuppetAtlas(tiles = tiles), + sources = listOf(ArtSource(source, "a.psd", null, "psd", layers)), + ) + + @Test + fun theRefreshKeepsOnlyTheLostRowsATileStillBinds() { + val previous = listOf(row("a", "A", 0, 0), row("b", "B", 0, 0), row("c", "C", 0, 0, present = false)) + val fresh = listOf(row("a", "A", 5, 5), row("d", "D", 0, 0)) + val refreshed = inventoryWithMissing(previous, fresh, boundKeys = setOf("a", "b", "c")) + assertEquals(listOf("a", "d", "b", "c"), refreshed.map { layer -> layer.key }) + assertEquals(listOf(true, true, false, false), refreshed.map { layer -> layer.present }) + assertEquals(5, refreshed.first().left, "the fresh row wins over the previous one") + assertEquals(listOf("a", "d"), inventoryWithMissing(previous, fresh, boundKeys = setOf("a")).map { layer -> layer.key }, "an unbound lost row is dropped") + val untouched = inventoryWithMissing(previous, fresh, boundKeys = setOf("a"), untouchedKeys = setOf("a")) + assertEquals(0, untouched.first().left, "a bound layer the plan left alone keeps its previous row, so the next reload still sees its change") + + // An erased layer saves with a collapsed rectangle; its row keeps the frame the art last had. + val erasedFresh = listOf(row("a", "A", 0, 0).copy(width = 0, height = 0, empty = true, contentHash = "blank")) + val erased = inventoryWithMissing(listOf(row("a", "A", 30, 40)), erasedFresh, boundKeys = setOf("a")).single() + assertEquals(listOf(30, 40, 10, 10), listOf(erased.left, erased.top, erased.width, erased.height), "the frame the art last had") + assertTrue(erased.empty && erased.contentHash == "blank", "while the erasure itself is recorded") + val stillErased = inventoryWithMissing(listOf(erased), erasedFresh, boundKeys = setOf("a")).single() + assertEquals(listOf(30, 40, 10, 10), listOf(stillErased.left, stillErased.top, stillErased.width, stillErased.height), "and keeps it across further saves") + + // A row lost to Replace Artwork says so; one lost before the replace keeps the deletion reading. + val replaced = inventoryWithMissing(previous, fresh, boundKeys = setOf("a", "b", "c"), lostByReplacement = true) + assertEquals(listOf(false, false, true, false), replaced.map { layer -> layer.replaced }, "only the row lost in this refresh reads as replaced") + assertTrue(inventoryWithMissing(previous, fresh, boundKeys = setOf("a", "b", "c")).none { layer -> layer.replaced }, "a plain reload records a deletion") + // The rigger's ignore mark is the document's, not the file's: it rides the fresh row, and a new layer starts unmarked. + val marked = inventoryWithMissing(listOf(row("a", "A", 0, 0).copy(ignored = true)), fresh, boundKeys = emptySet()) + assertEquals(listOf(true, false), marked.map { layer -> layer.ignored }) + val markedErased = inventoryWithMissing(listOf(row("a", "A", 30, 40).copy(ignored = true)), erasedFresh, boundKeys = emptySet()).single() + assertTrue(markedErased.ignored && markedErased.left == 30, "the mark and the kept frame ride together") + } + + @Test + fun eachLostRowGetsItsBestUnboundCandidate() { + // The Nose has an edited mesh over its tile: rig work, so it is never a candidate. + val model = + model( + drawables = listOf(drawable("nose", "t3", editedMesh)), + tiles = + listOf( + AtlasTile(AtlasTileId("t1"), "Eye L", 10, 10, source = SourceLayerRef(source, "name:Eye L#1", false)), + AtlasTile(AtlasTileId("t2"), "Mouth", 10, 10, source = SourceLayerRef(source, "lyid:9", true)), + AtlasTile(AtlasTileId("t3"), "Nose", 10, 10, source = SourceLayerRef(source, "lyid:3", true)), + AtlasTile(AtlasTileId("t4"), "Brow", 10, 10, source = SourceLayerRef(source, "lyid:77", true)), + ), + layers = + listOf( + row("lyid:3", "Nose", 50, 50), + row("lyid:4", "Eye Left", 0, 0), + row("lyid:5", "Mouth Open", 100, 100), + row("lyid:6", "Brow Left", 20, 0), + row("name:Eye L#1", "Eye L", 0, 0, present = false), + row("lyid:9", "Mouth", 100, 100, present = false), + ), + ) + val suggestions = suggestionsFor(model, source) + assertEquals(setOf("name:Eye L#1", "lyid:9", "lyid:77"), suggestions.keys) + assertEquals("lyid:4", suggestions.getValue("name:Eye L#1").key, "the bound Nose, under rig work, is never a candidate") + assertEquals("lyid:5", suggestions.getValue("lyid:9").key) + assertEquals("lyid:6", suggestions.getValue("lyid:77").key, "a binding the inventory never listed is scored from its tile") + + // A layer erased to nothing is reviewed like a lost one, and never offered as a candidate. + val erasedModel = + model.copy( + sources = + listOf( + model.sources.single().copy( + layers = + listOf( + row("lyid:3", "Nose", 50, 50).copy(empty = true), + row("lyid:4", "Eye Left", 0, 0), + row("lyid:8", "Nose (blank)", 50, 50).copy(empty = true), + row("lyid:9", "Mouth", 100, 100, present = false), + row("lyid:5", "Mouth Open", 100, 100), + ), + ), + ), + ) + val erased = suggestionsFor(erasedModel, source) + val proposedForNose = erased.getValue("lyid:3").key + assertTrue(proposedForNose == "lyid:4" || proposedForNose == "lyid:5", "the emptied Nose is proposed a layer with art, got $proposedForNose") + assertTrue(erased.values.none { match -> match.key == "lyid:8" }, "the blank namesake is never a candidate") + // An ignored layer is never a candidate either: the rigger keeps it out of the rig. + val ignoredModel = + model.copy(sources = listOf(model.sources.single().copy(layers = model.sources.single().layers.map { layer -> if (layer.key == "lyid:4") layer.copy(ignored = true) else layer }))) + assertTrue(suggestionsFor(ignoredModel, source).values.none { match -> match.key == "lyid:4" }, "an ignored layer is no candidate") + assertTrue(suggestionsFor(model, ArtSourceId("art-9")).isEmpty(), "an unknown file proposes nothing") + } + + @Test + fun aBoundLayerIsNeverProposedOnTheModelAloneAndTheConfidentPicksTakeEachCandidateOnce() { + // The lost Nose was re-created as lyid:3 and a reload minted a fresh drawable for it. On the + // model alone the layer is bound and so not a candidate - nothing here tells that fresh drawable + // from any other untouched one - but a proposal that names it (the reload's own, scored before it + // minted) retires exactly that tile, and never a tile with rig work over it. + val fresh = drawable("fresh", "t3", freshQuad) + val tiles = + listOf( + AtlasTile(AtlasTileId("t1"), "Nose", 10, 10, source = SourceLayerRef(source, "lyid:1", true)), + AtlasTile(AtlasTileId("t3"), "Nose", 10, 10, source = SourceLayerRef(source, "lyid:3", true)), + ) + val layers = listOf(row("lyid:3", "Nose", 50, 50), row("lyid:1", "Nose", 50, 50, present = false)) + val model = model(listOf(fresh), tiles, layers) + assertTrue(suggestionsFor(model, source).isEmpty(), "a bound layer is no candidate on the model alone") + assertEquals(listOf(AtlasTileId("t3")), retirableTiles(model, source, "lyid:3", except = setOf(AtlasTileId("t1"))), "what a proposal naming the layer retires") + val deformed = model.copy(drawables = listOf(fresh.copy(parentDeformerId = DeformerId("warp")))) + assertTrue(retirableTiles(deformed, source, "lyid:3", except = setOf(AtlasTileId("t1"))).isEmpty(), "under a deformer it is rig work, and stays") + assertTrue(retirableTiles(model, source, "lyid:3", except = setOf(AtlasTileId("t3"))).isEmpty(), "the tiles doing the claiming are never retired") + + val signals = MatchSignals(1f, 1f, 1f, 1f, null, hashEqual = false) + val suggestions = + mapOf( + "a" to LayerMatch("x", 0.9f, signals), + "b" to LayerMatch("x", 0.95f, signals), + "c" to LayerMatch("y", 0.7f, signals), + "d" to LayerMatch("z", 0.69f, signals), + ) + assertEquals(mapOf("b" to "x", "c" to "y"), confidentMatches(suggestions, 0.7f), "best first, each candidate once, the bar inclusive") + assertEquals(listOf("b", "c"), confidentMatches(suggestions, 0.7f).keys.toList(), "most confident first") + assertTrue(confidentMatches(suggestions, 1f).isEmpty()) + } + + @Test + fun scoringAgainstAReadRefreshesTheInventoryFirst() { + // The model still lists lyid:1 as present (the file was never reloaded); the art as read has + // lyid:3 in its place. On the model alone nothing is lost; against the read, the binding is. + val model = model(emptyList(), listOf(AtlasTile(AtlasTileId("t1"), "Nose", 10, 10, source = SourceLayerRef(source, "lyid:1", true))), listOf(row("lyid:1", "Nose", 50, 50))) + val read = listOf(row("lyid:3", "Nose", 50, 50)) + assertTrue(suggestionsFor(model, source).isEmpty()) + assertEquals("lyid:3", suggestionsAgainstRead(model, source, read).getValue("lyid:1").key) + assertTrue(suggestionsAgainstRead(model, ArtSourceId("art-9"), read).isEmpty(), "an unknown file proposes nothing") + } +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/TestArt.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/TestArt.kt new file mode 100644 index 0000000..09255d2 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/TestArt.kt @@ -0,0 +1,70 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceGroup +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind + +/** + * An in-memory source layer, so the engine's tests need no file: a raster of one color at a canvas + * position, keyed the way a reader keys it. + */ +internal class TestLayer( + id: String, + override val name: String, + override val order: Int, + override val bounds: LayerBounds, + override val raster: LayerRaster, + override val groupPath: String = "", + override val kind: SourceLayerKind = SourceLayerKind.Raster, + override val idIsStable: Boolean = true, + override val visible: Boolean = true, +) : SourceLayer { + override val id: LayerId = LayerId(id) + override val opacity: Float = 1f + override val clipped: Boolean = false + override val blend: LayerBlend = LayerBlend.Normal +} + +/** An in-memory source document over [layers], with the folders [groups] describes. */ +internal class TestArt( + override val layers: List, + override val widthPx: Int = 64, + override val heightPx: Int = 64, + override val groups: List = emptyList(), +) : SourceArt + +/** An in-memory plain folder at [path], named by its last segment. */ +internal class TestGroup( + override val path: String, +) : SourceGroup { + override val name: String = path.substringAfterLast('/') + override val visible: Boolean = true + override val opacity: Float = 1f + override val clipped: Boolean = false + override val blend: LayerBlend = LayerBlend.Normal + override val passThrough: Boolean = true +} + +/** + * A raster filled with one opaque color. + * + * @param Int width The width in pixels. + * @param Int height The height in pixels. + * @param Byte value The byte every color channel takes. + * @return LayerRaster The raster. + */ +internal fun solidRaster(width: Int, height: Int, value: Byte): LayerRaster { + val rgba = ByteArray(width * height * 4) + for (pixel in 0 until width * height) { + rgba[pixel * 4] = value + rgba[pixel * 4 + 1] = value + rgba[pixel * 4 + 2] = value + rgba[pixel * 4 + 3] = 0xFF.toByte() + } + return LayerRaster(width, height, rgba) +} \ No newline at end of file diff --git a/module/reimport/src/commonTest/kotlin/org/umamo/reimport/UmaReopenReloadTest.kt b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/UmaReopenReloadTest.kt new file mode 100644 index 0000000..c781246 --- /dev/null +++ b/module/reimport/src/commonTest/kotlin/org/umamo/reimport/UmaReopenReloadTest.kt @@ -0,0 +1,125 @@ +package org.umamo.reimport + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerRaster +import org.umamo.format.binary.contentHashOf +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.CanvasOffset +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.interop.art.placedBy +import org.umamo.interop.art.placedFor +import org.umamo.interop.uma.UmaDocumentBridge +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The reopen-then-reload promise the native format makes (docs/format/UMA.md §5, §6): a reload planned against a + * document before it was saved and one planned against the same document reopened from its `.uma` are the same + * plan, because the file carries the whole re-import baseline - the inventory with its flags and hashes, the + * bindings, the lineage, the file's placement on the canvas, and the tiles' pixels byte for byte. + */ +class UmaReopenReloadTest { + private val options = SourceArtImportOptions(alphaThreshold = 1, birthMeshMargin = 2) + + private val repainted = TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 4, 4), solidRaster(4, 4, 1)) + private val kept = TestLayer("lyid:2", "Two", 1, LayerBounds(30, 40, 4, 4), solidRaster(4, 4, 2)) + private val removed = TestLayer("lyid:3", "Three", 2, LayerBounds(50, 10, 6, 6), solidRaster(6, 6, 3), visible = false) + private val ignored = TestLayer("lyid:4", "Sketch", 3, LayerBounds(0, 0, 8, 8), LayerRaster(8, 8, ByteArray(8 * 8 * 4))) + + /** + * A reloaded file's lines, reduced to text that is equal exactly when the plans are: meshes by their arrays, + * rasters by their content hash, and everything else by its data-class form. + * + * @param ReloadPlan? plan The plan, or null when there is nothing to do. + * @return List The lines. + */ + private fun fingerprintOf(plan: ReloadPlan?): List { + if (plan == null) { + return listOf("no plan") + } + + /** + * A mesh as text. + * + * @param DrawableMesh? mesh The mesh. + * @return String The text. + */ + fun meshText(mesh: DrawableMesh?): String = mesh?.let { present -> "${present.positions.contentToString()} ${present.uvs.contentToString()} ${present.indices.contentToString()}" } ?: "none" + val reload = plan.reload + val lines = ArrayList() + lines += "source ${reload.source}" + reload.replacedTiles.forEach { replaced -> lines += "replaced ${replaced.oldId.raw} with ${replaced.tile}" } + reload.drawableMeshes.entries.sortedBy { (drawableId, _) -> drawableId.raw }.forEach { (drawableId, mesh) -> lines += "mesh ${drawableId.raw} ${meshText(mesh)}" } + reload.additions?.let { additions -> + lines += "added source ${additions.source}" + additions.tiles.forEach { tile -> lines += "added tile $tile" } + additions.drawables.forEach { drawable -> lines += "added drawable ${drawable.copy(mesh = null)} ${meshText(drawable.mesh)}" } + additions.parts.forEach { part -> lines += "added part $part" } + lines += "added root ${additions.rootChildren} insertions ${additions.insertions}" + } + lines += "outgrown ${reload.outgrown} retired ${reload.retiredTiles} visibility ${reload.drawableVisibility}" + plan.rasterByTile.entries.sortedBy { (tileId, _) -> tileId.raw }.forEach { (tileId, raster) -> lines += "raster ${tileId.raw} ${raster.width}x${raster.height} ${contentHashOf(raster.rgba)}" } + lines += "report ${plan.report.results}" + lines += "notices ${plan.notices}" + lines += "leftovers ${plan.leftovers}" + return lines + } + + /** + * A reload of a file whose first layer was repainted, whose third was deleted, whose ignored layer gained pixels, + * and which gained a fifth layer plans the same against the document and against its reopened `.uma`. + */ + @Test + fun aReopenedDocumentReloadsAsTheOriginalDoes() { + val fileBytes = "the file as imported".encodeToByteArray() + // The file was placed on the canvas when it was added, so every read of it is placed the same way. + val offset = CanvasOffset(7, 11) + val imported = SourceArtImport.fromSourceArt(TestArt(listOf(repainted, kept, removed, ignored)).placedBy(offset), ArtSourceDescriptor("a.clip", "/art/a.clip", "clip", contentHashOf(fileBytes), 1_757_894_400_000L), options) + val sourceId = imported.puppet.sources.single().id + // Rig work the reload must respect: the rigger ignored the sketch layer. + val source = imported.puppet.sources.single().copy(offsetX = offset.x, offsetZ = offset.z) + val model = imported.puppet.copy(sources = listOf(source.copy(layers = source.layers.map { layer -> if (layer.key == "lyid:4") layer.copy(ignored = true) else layer }))) + assertTrue(model.sources.single().layers.single { layer -> layer.key == "lyid:4" }.empty, "the sketch reads as an empty layer") + + val pngByTile = imported.rasterByTile.mapKeys { (tileId, _) -> tileId.raw }.mapValues { (_, raster) -> PngCodec.write(RasterImage(raster.width, raster.height, raster.rgba)) } + val saved = UmaDocumentBridge.documentOf(UmaModel.create(UmaWriterInfo("Umamo", "test")), model, UmaPixelSource({ tileId -> pngByTile[tileId] }, UmaRenderPagePixels.Derived, null)) + val document = Uma.read(Uma.write(saved)) + val reopened: PuppetModel = UmaDocumentBridge.modelOf(document) + assertEquals(offset.x to offset.z, reopened.sources.single().let { record -> record.offsetX to record.offsetZ }, "the placement survives the save") + val pages = UmaDocumentBridge.pagesOf(document) + val reopenedRasterOf: (AtlasTileId) -> LayerRaster? = { tileId -> pages.tilePng(tileId)?.let(PngCodec::read)?.let { image -> LayerRaster(image.width, image.height, image.rgba) } } + + val newArt = + TestArt( + listOf( + TestLayer("lyid:1", "One", 0, LayerBounds(10, 20, 5, 4), solidRaster(5, 4, 9)), + kept, + TestLayer("lyid:4", "Sketch", 2, LayerBounds(0, 0, 8, 8), solidRaster(8, 8, 4)), + TestLayer("lyid:5", "Five", 3, LayerBounds(60, 60, 3, 3), solidRaster(3, 3, 5)), + ), + ).placedFor(reopened.sources.single()) + val newHash = contentHashOf("the file as saved again".encodeToByteArray()) + val before = ArtworkReloadPlanner.plan(model, sourceId, newArt, options, { tileId -> imported.rasterByTile[tileId] }, newHash) + val after = ArtworkReloadPlanner.plan(reopened, sourceId, newArt, options, reopenedRasterOf, newHash) + + val plan = assertNotNull(before, "the changed file plans a reload") + assertTrue(plan.reload.replacedTiles.isNotEmpty(), "the repainted layer supersedes its tile") + assertTrue(plan.reload.additions != null, "the new layer is added") + assertTrue(plan.report.needsReview.isNotEmpty(), "the deleted layer is left for review") + assertEquals(offset.x to offset.z, plan.reload.source.let { record -> record.offsetX to record.offsetZ }, "the refreshed record keeps the placement") + assertEquals(fingerprintOf(before), fingerprintOf(after)) + } +} \ No newline at end of file diff --git a/module/render/build.gradle.kts b/module/render/build.gradle.kts new file mode 100644 index 0000000..419e9db --- /dev/null +++ b/module/render/build.gradle.kts @@ -0,0 +1,123 @@ +// :render — deformation eval (CPU) + the backend-neutral PuppetRenderer + morph-blend shaders, over a +// RenderDevice backend seam. Everything except the device impls is commonMain (jvm/android/iosArm64); +// GlRenderDevice (LWJGL, desktop GL 3.3) lives in jvmMain, the GLES/Metal devices are stubs in +// androidMain/iosMain. Zero expect/actual. Depends on :runtime for the puppet model. +// :render — 変形評価(CPU)+バックエンド非依存の PuppetRenderer。RenderDevice が継ぎ目で、GL 実装のみ +// jvmMain。GLES / Metal デバイスはスタブ。:runtime に依存。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + // Umamo's own conventions (gradle/build-logic): the iosArm64 → `check` wiring, and the corpus/-D + // forwarding configured by `umamoTestCorpus` below. Deliberately NOT umamo.kmp-jvmandroid — this + // module has no JVM-bound shared code; see the commonMain :format comment below. + id("umamo.kmp-ios-gate") + id("umamo.test-corpus") +} + +// EN: LWJGL ships its native libraries as classifier'd artifacts; pick the one for the build target. +// Default is the host; -Pumamo.target=- cross-resolves (e.g. windows-x64 from WSL2). The +// selection is shared with :desktop so a cross-build can't bundle this module's host natives by +// mistake — see gradle/build-target.gradle.kts. (Desktop only — Android uses GLES via android.opengl.) +// JA: LWJGL のネイティブ分類子を選ぶ。既定はホスト、-Pumamo.target で他プラットフォーム向けに解決。 +apply(from = rootProject.file("gradle/build-target.gradle.kts")) +val lwjglNatives = extra["umamoLwjglNatives"] as String + +kotlin { + jvmToolchain(21) + + // (The -Xexpect-actual-classes opt-in that used to sit here left with its only user, the + // `expect class GpuRenderer` — this module is zero expect/actual now; the backend seam is the + // RenderDevice interface instead.) + + jvm() + + // The iPadOS ship target, mirroring :format/:runtime (see :format's docblock for the rationale). + // This is what the Metal engineer builds against: iosMain sees the whole backend-neutral stack — + // PuppetRenderer, the RenderDevice API, eval, pose/diff/glue planning — and supplies one + // MetalRenderDevice. It also turns commonMain purity for all of that from the root regex gate's + // convention into a compiler guarantee. Compiles on Linux/CI (klib only, no Xcode linker); a device + // target has no runnable test task, so `umamo.kmp-ios-gate` wires `check` to the compiles. + iosArm64() + + android { + namespace = "org.umamo.render" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + commonMain { + dependencies { + // `api` (not `implementation`): the deformation eval's public surface returns/accepts + // :runtime model types (PuppetModel, DrawableId, …), so consumers see them transitively. + api(project(":runtime")) + // `api`: :format types sit in the renderer's own public surface too — RasterImage in + // RenderDevice's upload API, PngCodec behind the atlas decode, and the CMO3/MOC3 node + // types the two texture adapters walk — and :runtime is format-free, so nothing supplies + // :format transitively. Those adapters are commonMain: the CMO3 graph node types live in + // :format's commonMain, and only the JDOM-built Cmo3Model wrapper does not, so the + // adapter takes a CModelSource plus an injected pixel lookup and this module needs no + // jvmAndroidMain at all. + api(project(":format")) + } + } + jvmMain { + dependencies { + // BOM aligns every LWJGL module to one version; the `::classifier` (empty + // version) coordinate inherits that version while adding the host natives. + implementation(project.dependencies.platform(libs.lwjgl.bom)) + implementation(libs.lwjgl.core) + implementation(libs.lwjgl.opengl) + runtimeOnly("org.lwjgl:lwjgl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives") + } + } + commonTest { + dependencies { + implementation(kotlin("test")) + } + } + jvmTest { + dependencies { + // The oracle/parity tests ingest corpus models through :interop's Cmo3Import/Moc3Import. + implementation(project(":interop")) + // Headless GL (GLFW hidden window) for the GPU-vs-CPU transform-feedback validation test. + // `implementation` here (not inherited from jvmMain's `implementation`) so the test sources + // compile against the GL/GLFW bindings; natives are pulled for the host. + implementation(project.dependencies.platform(libs.lwjgl.bom)) + implementation(libs.lwjgl.core) + implementation(libs.lwjgl.opengl) + implementation(libs.lwjgl.glfw) + runtimeOnly("org.lwjgl:lwjgl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives") + } + } + } +} + +// Corpus + differential-oracle paths for the eval's gated tests (the `umamo.test-corpus` convention +// plugin): `./gradlew :render:jvmTest -Dcmo3.sample=… -Dmoc3.sample=… -Drelive.dumpModel=… +// -Drelive.coreLib=…`. +// +// `cmo3.sample`, `cmo3.probe`, and `moc3.samples` carry corpus DEFAULTS (see +// org.umamo.buildlogic.sharedCorpusDefault). Without them this module's corpus gates — the GPU-vs-CPU +// deform oracle above all — only ran when someone remembered the flag, so in practice they never ran: +// GpuDeformValidationTest, GlueCorpusTest, and RenderOrderCorpusTest all sat skipping on a machine that +// had the corpus the whole time. The deform oracle is the only pin on DEFORM_GLSL's math and the thing +// a Metal port will check itself against, so "runs only if asked" was the wrong default for it. The +// relive.* oracle paths and moc3.sample stay explicit-only. +// +// Absent entirely (a fresh clone, CI) → the tests skip and the build stays green, since test/corpus is +// gitignored on purpose (see README). That is deliberate; CI passes no sample flags. +// +// `umamo.requireGl` is forwarded for the opposite reason: it turns the GL tests' missing-context skip +// into a hard failure (see HeadlessGlGate). CI sets it so the GL suite can never silently stop covering +// anything; a developer machine leaves it unset and gets the skip. It is a flag, not a path, so it goes +// through `flag` and skips the file-existence check. +umamoTestCorpus { + maxHeap("4g") + sample("cmo3.sample", "cmo3.probe", "moc3.sample", "moc3.samples", "relive.dumpModel", "relive.coreLib") + flag("umamo.requireGl") +} \ No newline at end of file diff --git a/module/render/src/androidMain/kotlin/org/umamo/render/gles/GlesRenderDevice.kt b/module/render/src/androidMain/kotlin/org/umamo/render/gles/GlesRenderDevice.kt new file mode 100644 index 0000000..6b8cd57 --- /dev/null +++ b/module/render/src/androidMain/kotlin/org/umamo/render/gles/GlesRenderDevice.kt @@ -0,0 +1,134 @@ +package org.umamo.render.gles + +import org.umamo.format.raster.RasterImage +import org.umamo.render.device.DeformCapturePipeline +import org.umamo.render.device.DeformedPositionStore +import org.umamo.render.device.FrameEncoder +import org.umamo.render.device.GpuMesh +import org.umamo.render.device.GpuTexture +import org.umamo.render.device.MeshSpec +import org.umamo.render.device.ReadbackTicket +import org.umamo.render.device.RenderDevice +import org.umamo.render.device.RenderPipeline +import org.umamo.render.device.RenderPipelineSpec +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.ScissorRect +import org.umamo.render.device.TextureFilter +import org.umamo.render.device.TextureFormat +import org.umamo.render.device.TextureWrap + +/** + * The Android GLES 3.0 [RenderDevice] - a STUB marking the port's entry point; nothing is implemented. + * + * The port is a near-transliteration of the desktop `GlRenderDevice` (jvmMain, `org.umamo.render.gl`): + * the calls are the same, the shared GLSL comes from `org.umamo.render.glsl` with + * `GlslDialect.Es300`, and `PuppetRenderer` needs no changes at all. The mechanical difference is + * binding style - LWJGL statics returning values vs `android.opengl.GLES30`'s out-parameter form + * (`glGenTextures(1, ids, 0)` instead of `glGenTextures()`). + * + * The ONE real divergence is [createDeformedPositionStore]. The desktop device backs the glue store + * with a texture buffer object, and TBOs are GLES 3.2 - the baseline here is 3.0. The 3.0-clean + * route (TODO.md Claude Note § Android GLES renderer backend, option (b)): + * - Store: a regular RG32F 2D texture, indexed `(index % width, index / width)` via texelFetch. + * - Capture: transform feedback IS core in ES 3.0 but can only target a buffer, so pass 1 becomes + * TF into a buffer, then buffer → texture via a GL_PIXEL_UNPACK_BUFFER bind + glTexSubImage2D + * (both core 3.0). Do NOT reach for the point-scatter alternative here: rendering INTO an RG32F + * target needs EXT_color_buffer_float, which is not core until 3.2 either. + * - Shader: `glueVertexShader(Es300)` still emits `samplerBuffer` and must gain the 2D-texelFetch + * variant as part of this port - its `@warning` says so. + * + * Everything else - pipelines keyed by `PipelinePurpose`, the pass encoders, `barrier` as glFinish, + * `readPixels` flipping GL's bottom-up read to the API's top-first contract - carries over as is. + * Validate against the same oracles the desktop device passes: `GpuDeformValidationTest` and + * `GpuGlueValidationTest` are the correctness bar, run on-device or on an emulator. + * + * Android GLES 3.0 デバイスのスタブ。デスクトップ GL デバイスの移植入口。未実装。 + */ +class GlesRenderDevice : RenderDevice { + override fun createTexture( + width: Int, + height: Int, + format: TextureFormat, + filter: TextureFilter, + pixels: ByteArray?, + wrap: TextureWrap, + ): GpuTexture = + TODO("GLES port: transliterate GlRenderDevice.createTexture (GLES30.glGenTextures out-param form)") + + override fun createFloatTexture(width: Int, height: Int, filter: TextureFilter, texels: FloatArray): GpuTexture = + TODO("GLES port: transliterate GlRenderDevice.createFloatTexture") + + override fun updateFloatTexture(texture: GpuTexture, width: Int, height: Int, texels: FloatArray): Unit = + TODO("GLES port: transliterate GlRenderDevice.updateFloatTexture (keep the once-per-pose contract)") + + override fun createMesh(spec: MeshSpec): GpuMesh = TODO("GLES port: transliterate GlRenderDevice.createMesh") + + override fun updateMeshPositions(mesh: GpuMesh, restPositions: FloatArray): Unit = + TODO("GLES port: transliterate GlRenderDevice.updateMeshPositions") + + override fun updateMeshUvs(mesh: GpuMesh, uvs: FloatArray): Unit = TODO("GLES port: transliterate GlRenderDevice.updateMeshUvs") + + override fun createRenderTarget(spec: RenderTargetSpec): RenderTarget = + TODO("GLES port: transliterate GlRenderDevice.createRenderTarget") + + override fun createDeformedPositionStore(vertexCapacity: Int): DeformedPositionStore = + TODO("GLES port: THE divergence - RG32F 2D texture store + TF-to-buffer + PBO copy; see the class docblock") + + override fun createRenderPipeline(spec: RenderPipelineSpec): RenderPipeline = + TODO("GLES port: link from org.umamo.render.glsl with GlslDialect.Es300") + + override fun createDeformCapturePipeline(): DeformCapturePipeline = + TODO("GLES port: TF program (core in ES 3.0), capture into the store's staging buffer") + + override fun destroyTexture(texture: GpuTexture): Unit = TODO("GLES port") + + override fun destroyMesh(mesh: GpuMesh): Unit = TODO("GLES port") + + override fun destroyRenderTarget(target: RenderTarget): Unit = TODO("GLES port") + + override fun beginFrame(): FrameEncoder = TODO("GLES port: transliterate GlFrameEncoder") + + override fun resolve(source: RenderTarget, destination: RenderTarget, region: ScissorRect?): Unit = + TODO( + "GLES port: two branches like desktop GlRenderDevice - region == null is the full-surface " + + "GL_LINEAR downscale blit (the supersample resolve); region != null is a same-size, top-left-" + + "origin sub-rect GL_NEAREST copy (the composite snapshot). glBlitFramebuffer is core in ES 3.0.", + ) + + override fun resolveUsed( + source: RenderTarget, + sourceUsedWidth: Int, + sourceUsedHeight: Int, + destination: RenderTarget, + destinationUsedWidth: Int, + destinationUsedHeight: Int, + region: ScissorRect?, + ): Unit = + TODO( + "GLES port: like resolve but over the bottom-left used regions (passes viewport at the " + + "origin), flipping a non-null region against the USED height - see desktop GlRenderDevice.", + ) + + override fun beginReadback(target: RenderTarget): ReadbackTicket = + TODO("GLES port: PBO + fence, same as desktop - GL_PIXEL_PACK_BUFFER and fence sync are core in ES 3.0") + + override fun beginReadback(target: RenderTarget, usedWidth: Int, usedHeight: Int): ReadbackTicket = + TODO("GLES port: the full-target beginReadback with glReadPixels(0, 0, usedWidth, usedHeight, ...)") + + override fun pollReadback(ticket: ReadbackTicket): RasterImage? = + TODO("GLES port: clientWaitSync(0) + glMapBufferRange (ES has no glMapBuffer; use the Range form)") + + override fun cancelReadback(ticket: ReadbackTicket): Unit = TODO("GLES port") + + override fun readPixels(target: RenderTarget): RasterImage = + TODO("GLES port: glReadPixels + flipRowsVertically - GLES reads bottom-up like GL; the API contract is top-first") + + override fun readPixels(target: RenderTarget, usedWidth: Int, usedHeight: Int): RasterImage = + TODO("GLES port: the full-target readPixels with glReadPixels(0, 0, usedWidth, usedHeight, ...)") + + override fun maxRenderTargetSize(): Int = + TODO("GLES port: the least of GL_MAX_TEXTURE_SIZE, GL_MAX_RENDERBUFFER_SIZE, and both GL_MAX_VIEWPORT_DIMS") + + override fun describeBackend(): String = TODO("GLES port: GLES20.glGetString(GL_RENDERER / GL_VERSION / GL_VENDOR)") +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/AtlasPlacementDrag.kt b/module/render/src/commonMain/kotlin/org/umamo/render/AtlasPlacementDrag.kt new file mode 100644 index 0000000..332e42d --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/AtlasPlacementDrag.kt @@ -0,0 +1,658 @@ +package org.umamo.render + +import org.umamo.format.art.LayerBounds +import org.umamo.format.atlas.AtlasPackReserve +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.inversePlacementAffine +import org.umamo.runtime.model.placementAffine +import org.umamo.runtime.model.storedToArtAffineForTile +import kotlin.math.ceil +import kotlin.math.floor + +/* + * The placement gizmo's page-space bookkeeping: the mesh reach each tile must keep clear, the + * footprint a placement occupies on its page, and the two regions a collision is made of. + * + * A collision is asymmetric and exact on both sides. What goes wrong when tiles overlap is a mesh + * SAMPLING another tile's opaque pixels, so every tile has a sampled region - the coverage of its + * triangles, rasterized in its own pixel frame, through its placement - and a painted region - its + * opaque texels, the composer never letting a transparent one erase anything - and tile A collides + * with tile B when A's triangles land on B's paint or B's triangles land on A's paint. The two sides + * are different shapes on purpose: the typical mesh extends PAST its art, and those overhanging + * triangles are exactly where a neighbor's pixels cause damage, while a tile's pixels outside its own + * mesh are still paint another tile's triangles can land on. A bounding box on either side lies for + * strand-shaped art and for meshes that sample only part of their layer. A mover's paint is its own + * opaque mask; the bystanders' paint is the shown page itself, whose composed alpha IS what is painted + * there. + * + * Session-free and GL-free. It lives beside the derivation rather than in the editing module because + * a footprint is a derivation question (which pixels will the compose write) and needs the trim the + * derivation draws, and because the repack and the drag must reserve by ONE rule - a reserve computed + * two ways would let a hand-nudged tile land where the next repack refuses to put it. + */ + +/** + * Per tile, the union of its bound drawables' mesh reach in the tile's own art frame, rounded out to + * whole pixels - what a pack must keep clear BEYOND the opaque pixels. + * + * The pixels alone do not bound what samples a tile: an art mesh rings outside the opaque region + * (Erica's reach up to 58px past their trim, and past the raster itself), so a pack spaced by + * opaque bounds puts one tile's mesh footprint over its neighbor's art - the mesh then renders the + * neighbor's pixels wherever they are opaque. The official editor's own packing keeps mesh + * footprints disjoint, and this is how the repack matches it. + * + * A drawable whose mapping will not resolve (a placement naming a page the atlas lacks) contributes + * nothing here; if it is bound, the repack's refusal pass aborts before the reserve could have + * mattered. + * + * @param PuppetModel model The model whose bindings to measure. + * @return Map Each bound tile's reserve, absent when a tile has no measurable mesh. + */ +public fun meshReserveByTile(model: PuppetModel): Map { + val boundsByTile = HashMap() + for (drawable in model.drawables) { + val tileId = drawable.atlasTileId ?: continue + val tile = model.atlas.tileById[tileId] ?: continue + val uvs = drawable.mesh?.uvs ?: continue + if (uvs.size < 2) { + continue + } + val storedToArt = model.atlas.storedToArtAffineForTile(tileId) ?: continue + val artUvs = applyUvAffine(uvs, storedToArt) + val bounds = boundsByTile.getOrPut(tileId) { floatArrayOf(Float.MAX_VALUE, Float.MAX_VALUE, -Float.MAX_VALUE, -Float.MAX_VALUE) } + var componentIndex = 0 + while (componentIndex + 1 < artUvs.size) { + val artX = artUvs[componentIndex] * tile.width + val artY = artUvs[componentIndex + 1] * tile.height + bounds[0] = minOf(bounds[0], artX) + bounds[1] = minOf(bounds[1], artY) + bounds[2] = maxOf(bounds[2], artX) + bounds[3] = maxOf(bounds[3], artY) + componentIndex += 2 + } + } + return boundsByTile.mapValues { (_, bounds) -> + AtlasPackReserve( + left = floor(bounds[0]).toInt(), + top = floor(bounds[1]).toInt(), + right = ceil(bounds[2]).toInt(), + bottom = ceil(bounds[3]).toInt(), + ) + } +} + +/** + * A placement's axis-aligned extent on its page, in continuous page pixels: the bounds of the + * tile-local rectangle (the trim, widened by the mesh reserve) through the placement. + * + * A rotated tile's footprint is its bounding box, so a test over one over-warns for a turned tile and + * never under-warns - the first-cut approximation the gizmo's warnings run on. + * + * @property Float left The left edge. + * @property Float top The top edge. + * @property Float right The right edge, exclusive. + * @property Float bottom The bottom edge, exclusive. + */ +data class PlacementFootprint( + val left: Float, + val top: Float, + val right: Float, + val bottom: Float, +) { + /** + * This footprint grown by [margin] on every side - the gutter a neighbor must stay clear of. + * + * @param Float margin The growth in page pixels. + * @return PlacementFootprint The grown footprint. + */ + fun expanded(margin: Float): PlacementFootprint = PlacementFootprint(left - margin, top - margin, right + margin, bottom + margin) + + /** + * True when this footprint and [other] share any area (touching edges do not count). + * + * @param PlacementFootprint other The footprint to test against. + * @return Boolean Whether they overlap. + */ + fun overlaps(other: PlacementFootprint): Boolean = + left < other.right && other.left < right && top < other.bottom && other.top < bottom + + /** + * True when any part of this footprint lies outside a page of the given size. + * + * @param Int pageWidth The page width in pixels. + * @param Int pageHeight The page height in pixels. + * @return Boolean Whether the footprint spills off the page. + */ + fun exceeds(pageWidth: Int, pageHeight: Int): Boolean = left < 0f || top < 0f || right > pageWidth || bottom > pageHeight +} + +/** + * The footprint [placement] occupies: its tile's [trim] widened by [reserve] (when the tile has a + * measurable mesh), carried through the placement onto the page. + * + * @param AtlasPlacement placement The tile's placement. + * @param LayerBounds trim The tile's opaque bounds, raster-local. + * @param AtlasPackReserve? reserve The tile's mesh reach, raster-local, or null when none. + * @return PlacementFootprint The page-space bounds. + */ +fun placementFootprint(placement: AtlasPlacement, trim: LayerBounds, reserve: AtlasPackReserve?): PlacementFootprint { + var localLeft = trim.left.toFloat() + var localTop = trim.top.toFloat() + var localRight = (trim.left + trim.width).toFloat() + var localBottom = (trim.top + trim.height).toFloat() + if (reserve != null) { + localLeft = minOf(localLeft, reserve.left.toFloat()) + localTop = minOf(localTop, reserve.top.toFloat()) + localRight = maxOf(localRight, reserve.right.toFloat()) + localBottom = maxOf(localBottom, reserve.bottom.toFloat()) + } + val affine = placementAffine(placement) + var left = Float.POSITIVE_INFINITY + var top = Float.POSITIVE_INFINITY + var right = Float.NEGATIVE_INFINITY + var bottom = Float.NEGATIVE_INFINITY + for (cornerIndex in 0 until 4) { + val cornerX = if (cornerIndex and 1 == 0) localLeft else localRight + val cornerY = if (cornerIndex and 2 == 0) localTop else localBottom + val pageX = affine[0] * cornerX + affine[1] * cornerY + affine[2] + val pageY = affine[3] * cornerX + affine[4] * cornerY + affine[5] + left = minOf(left, pageX) + top = minOf(top, pageY) + right = maxOf(right, pageX) + bottom = maxOf(bottom, pageY) + } + return PlacementFootprint(left, top, right, bottom) +} + +/** The side of one occupancy block, in page pixels. */ +private const val OCCUPANCY_BLOCK_SIDE = 8 + +/** + * A tile's opaque texels within its trim, one bit each, trim-local - a mover's painted region. + * + * @property LayerBounds trim The trim the mask covers, raster-local. + */ +class TileOpaqueMask private constructor( + val trim: LayerBounds, + private val words: LongArray, +) { + /** + * Whether the raster texel at ([tileX], [tileY]) is opaque; false outside the trim. + * + * @param Int tileX The texel column, raster-local. + * @param Int tileY The texel row, raster-local. + * @return Boolean True when the texel meets the mask's threshold. + */ + fun isOpaque(tileX: Int, tileY: Int): Boolean { + val column = tileX - trim.left + val row = tileY - trim.top + if (column < 0 || row < 0 || column >= trim.width || row >= trim.height) { + return false + } + val bitIndex = row * trim.width + column + return (words[bitIndex ushr 6] ushr (bitIndex and 63)) and 1L == 1L + } + + companion object { + /** + * The mask of [raster]'s texels inside [trim] whose alpha reaches [alphaThreshold]. + * + * @param DecodedImage raster The tile's decoded art. + * @param LayerBounds trim The sub-rectangle to mask, raster-local. + * @param Int alphaThreshold The alpha a texel needs to count as opaque. + * @return TileOpaqueMask The mask. + */ + fun of(raster: DecodedImage, trim: LayerBounds, alphaThreshold: Int): TileOpaqueMask { + val bitCount = trim.width * trim.height + val words = LongArray((bitCount + 63) ushr 6) + for (row in 0 until trim.height) { + val rowOffset = (trim.top + row) * raster.width + trim.left + for (column in 0 until trim.width) { + val alpha = raster.rgba[(rowOffset + column) * 4 + 3].toInt() and 0xFF + if (alpha >= alphaThreshold) { + val bitIndex = row * trim.width + column + words[bitIndex ushr 6] = words[bitIndex ushr 6] or (1L shl (bitIndex and 63)) + } + } + } + return TileOpaqueMask(trim, words) + } + } +} + +/** + * An integer pixel rectangle on a page, right and bottom exclusive. + * + * @property Int left The left edge. + * @property Int top The top edge. + * @property Int right The right edge, exclusive. + * @property Int bottom The bottom edge, exclusive. + */ +data class PixelRect( + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, +) { + /** + * Whether ([x], [y]) lies inside. + * + * @param Int x The pixel column. + * @param Int y The pixel row. + * @return Boolean True when inside. + */ + fun contains(x: Int, y: Int): Boolean = x >= left && x < right && y >= top && y < bottom +} + +/** + * The shown page's painted pixels - the bystanders' painted region as one surface. + * + * The composed page's alpha IS what is painted there (a bleed band carries none, so it reads empty), so no tile needs + * decoding: one pass over the page reduces it to a bitset of 8x8 blocks for fast rejection, and the + * exact alpha stays behind it for the pixels a sampled region actually touches. The rectangles a + * caller names are read as empty - the spots the movers are leaving. + * + * Holds the page's pixel buffer by reference; it is never written. + * + * @property Int width The page width in pixels. + * @property Int height The page height in pixels. + */ +class PageOccupancy private constructor( + val width: Int, + val height: Int, + private val rgba: ByteArray, + private val blockColumns: Int, + private val blockWords: LongArray, + private val excluded: List, +) { + /** + * Whether the page pixel at ([x], [y]) is painted: on the page, outside every excluded + * rectangle, and not fully transparent. + * + * @param Int x The pixel column. + * @param Int y The pixel row. + * @return Boolean True when painted. + */ + fun isPainted(x: Int, y: Int): Boolean { + if (x < 0 || y < 0 || x >= width || y >= height) { + return false + } + for (rect in excluded) { + if (rect.contains(x, y)) { + return false + } + } + return (rgba[(y * width + x) * 4 + 3].toInt() and 0xFF) != 0 + } + + /** + * Whether the 8x8 block at ([blockX], [blockY]) holds any painted pixel - the cheap rejection the + * exact test hides behind. Excluded rectangles are not applied here; a block that overlaps one may + * answer true and the exact test then says no. + * + * @param Int blockX The block column. + * @param Int blockY The block row. + * @return Boolean True when the block may be painted. + */ + fun blockMayBePainted(blockX: Int, blockY: Int): Boolean { + val bitIndex = blockY * blockColumns + blockX + return (blockWords[bitIndex ushr 6] ushr (bitIndex and 63)) and 1L == 1L + } + + /** + * Whether any painted pixel lies inside [region]. + * + * Walks the blocks under the region's bounds, and only for a block that may be painted tests its + * pixels exactly against the region and the page. + * + * @param SampledRegion region The region to test. + * @return PixelRect? A one-pixel rectangle at the first painted pixel found, or null when none. + */ + fun firstPaintedPixelIn(region: SampledRegion): PixelRect? { + val bounds = region.bounds + val startX = floor(bounds.left).toInt().coerceAtLeast(0) + val endX = ceil(bounds.right).toInt().coerceAtMost(width) + val startY = floor(bounds.top).toInt().coerceAtLeast(0) + val endY = ceil(bounds.bottom).toInt().coerceAtMost(height) + if (startX >= endX || startY >= endY) { + return null + } + for (blockY in (startY / OCCUPANCY_BLOCK_SIDE)..((endY - 1) / OCCUPANCY_BLOCK_SIDE)) { + for (blockX in (startX / OCCUPANCY_BLOCK_SIDE)..((endX - 1) / OCCUPANCY_BLOCK_SIDE)) { + if (!blockMayBePainted(blockX, blockY)) { + continue + } + val pixelStartX = maxOf(startX, blockX * OCCUPANCY_BLOCK_SIDE) + val pixelEndX = minOf(endX, (blockX + 1) * OCCUPANCY_BLOCK_SIDE) + val pixelStartY = maxOf(startY, blockY * OCCUPANCY_BLOCK_SIDE) + val pixelEndY = minOf(endY, (blockY + 1) * OCCUPANCY_BLOCK_SIDE) + for (y in pixelStartY until pixelEndY) { + for (x in pixelStartX until pixelEndX) { + if (region.contains(x + 0.5f, y + 0.5f) && isPainted(x, y)) { + return PixelRect(x, y, x + 1, y + 1) + } + } + } + } + } + return null + } + + companion object { + /** + * The occupancy of [page], with [excluded] read as empty. + * + * @param DecodedImage page The shown page. + * @param List excluded Rectangles to read as unpainted (the movers' old spots). + * @return PageOccupancy The occupancy. + */ + fun of(page: DecodedImage, excluded: List): PageOccupancy { + val blockColumns = (page.width + OCCUPANCY_BLOCK_SIDE - 1) / OCCUPANCY_BLOCK_SIDE + val blockRows = (page.height + OCCUPANCY_BLOCK_SIDE - 1) / OCCUPANCY_BLOCK_SIDE + val blockWords = LongArray((blockColumns * blockRows + 63) ushr 6) + for (y in 0 until page.height) { + val rowOffset = y * page.width + val blockRow = (y / OCCUPANCY_BLOCK_SIDE) * blockColumns + for (x in 0 until page.width) { + if (page.rgba[(rowOffset + x) * 4 + 3].toInt() != 0) { + val bitIndex = blockRow + x / OCCUPANCY_BLOCK_SIDE + blockWords[bitIndex ushr 6] = blockWords[bitIndex ushr 6] or (1L shl (bitIndex and 63)) + } + } + } + return PageOccupancy(page.width, page.height, page.rgba, blockColumns, blockWords, excluded) + } + } +} + +/** + * The coverage of a tile's meshes in the tile's own pixel frame, one bit per pixel over the meshes' + * bounding box - which may extend past the raster, since a mesh typically overhangs its art. + * + * @property LayerBounds bounds The box the bits cover, raster-local (left / top may be negative). + */ +class TileMeshMask private constructor( + val bounds: LayerBounds, + private val words: LongArray, +) { + /** + * Whether the tile pixel at ([tileX], [tileY]) is covered by a triangle (within the one-pixel + * conservative margin); false outside the box. + * + * @param Int tileX The pixel column, raster-local. + * @param Int tileY The pixel row, raster-local. + * @return Boolean True when covered. + */ + fun isCovered(tileX: Int, tileY: Int): Boolean { + val column = tileX - bounds.left + val row = tileY - bounds.top + if (column < 0 || row < 0 || column >= bounds.width || row >= bounds.height) { + return false + } + val bitIndex = row * bounds.width + column + return (words[bitIndex ushr 6] ushr (bitIndex and 63)) and 1L == 1L + } + + companion object { + /** + * The mask of [triangles] (art-pixel coordinates, nine floats per triangle: three interleaved + * (x, y) corners) filled by pixel-center test and dilated by one pixel in every direction, so a + * bilinear sampler reading half a texel past any covered point is inside it. Every corner's own + * pixel is marked too, so a sliver too thin to cover a center still contributes. + * + * @param List triangles The triangles, art-local. + * @return TileMeshMask? The mask, or null when there are no triangles. + */ + fun of(triangles: List): TileMeshMask? { + if (triangles.isEmpty()) { + return null + } + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + for (triangle in triangles) { + for (cornerIndex in 0 until 3) { + minX = minOf(minX, triangle[cornerIndex * 2]) + maxX = maxOf(maxX, triangle[cornerIndex * 2]) + minY = minOf(minY, triangle[cornerIndex * 2 + 1]) + maxY = maxOf(maxY, triangle[cornerIndex * 2 + 1]) + } + } + // One pixel of margin for the dilation on every side. + val left = floor(minX).toInt() - 1 + val top = floor(minY).toInt() - 1 + val width = ceil(maxX).toInt() + 1 - left + val height = ceil(maxY).toInt() + 1 - top + val raw = LongArray((width * height + 63) ushr 6) + + fun mark(column: Int, row: Int) { + if (column < 0 || row < 0 || column >= width || row >= height) { + return + } + val bitIndex = row * width + column + raw[bitIndex ushr 6] = raw[bitIndex ushr 6] or (1L shl (bitIndex and 63)) + } + for (triangle in triangles) { + val x0 = triangle[0] - left + val y0 = triangle[1] - top + val x1 = triangle[2] - left + val y1 = triangle[3] - top + val x2 = triangle[4] - left + val y2 = triangle[5] - top + mark(floor(x0).toInt(), floor(y0).toInt()) + mark(floor(x1).toInt(), floor(y1).toInt()) + mark(floor(x2).toInt(), floor(y2).toInt()) + val area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) + if (area == 0f) { + continue + } + val startColumn = floor(minOf(x0, x1, x2)).toInt().coerceAtLeast(0) + val endColumn = ceil(maxOf(x0, x1, x2)).toInt().coerceAtMost(width - 1) + val startRow = floor(minOf(y0, y1, y2)).toInt().coerceAtLeast(0) + val endRow = ceil(maxOf(y0, y1, y2)).toInt().coerceAtMost(height - 1) + val orientation = if (area > 0f) 1f else -1f + for (row in startRow..endRow) { + val centerY = row + 0.5f + for (column in startColumn..endColumn) { + val centerX = column + 0.5f + val edge0 = ((x1 - x0) * (centerY - y0) - (y1 - y0) * (centerX - x0)) * orientation + val edge1 = ((x2 - x1) * (centerY - y1) - (y2 - y1) * (centerX - x1)) * orientation + val edge2 = ((x0 - x2) * (centerY - y2) - (y0 - y2) * (centerX - x2)) * orientation + if (edge0 >= 0f && edge1 >= 0f && edge2 >= 0f) { + mark(column, row) + } + } + } + } + // Dilate by one pixel: a bit set anywhere in the 3x3 neighborhood sets the pixel. + val dilated = LongArray(raw.size) + for (row in 0 until height) { + for (column in 0 until width) { + var covered = false + for (rowOffset in -1..1) { + val neighborRow = row + rowOffset + if (neighborRow < 0 || neighborRow >= height) { + continue + } + for (columnOffset in -1..1) { + val neighborColumn = column + columnOffset + if (neighborColumn < 0 || neighborColumn >= width) { + continue + } + val bitIndex = neighborRow * width + neighborColumn + if ((raw[bitIndex ushr 6] ushr (bitIndex and 63)) and 1L == 1L) { + covered = true + } + } + } + if (covered) { + val bitIndex = row * width + column + dilated[bitIndex ushr 6] = dilated[bitIndex ushr 6] or (1L shl (bitIndex and 63)) + } + } + } + return TileMeshMask(LayerBounds(left, top, width, height), dilated) + } + } +} + +/** + * The triangles of every drawable bound to [tileId], in the tile's own pixel frame - the same + * uv-to-art conversion [meshReserveByTile] measures with. + * + * @param PuppetModel model The model. + * @param AtlasTileId tileId The tile. + * @return List The triangles, nine floats each; empty when nothing measurable is bound. + */ +fun meshTrianglesOf(model: PuppetModel, tileId: AtlasTileId): List { + val tile = model.atlas.tileById[tileId] ?: return emptyList() + val storedToArt = model.atlas.storedToArtAffineForTile(tileId) ?: return emptyList() + val triangles = ArrayList() + for (drawable in model.drawables) { + if (drawable.atlasTileId != tileId) { + continue + } + val mesh = drawable.mesh ?: continue + if (mesh.uvs.size < 2 || mesh.indices.size < 3) { + continue + } + val artUvs = applyUvAffine(mesh.uvs, storedToArt) + val vertexCount = artUvs.size / 2 + var indexOffset = 0 + while (indexOffset + 2 < mesh.indices.size) { + val cornerA = mesh.indices[indexOffset] + val cornerB = mesh.indices[indexOffset + 1] + val cornerC = mesh.indices[indexOffset + 2] + indexOffset += 3 + if (cornerA >= vertexCount || cornerB >= vertexCount || cornerC >= vertexCount) { + continue + } + triangles.add( + floatArrayOf( + artUvs[cornerA * 2] * tile.width, + artUvs[cornerA * 2 + 1] * tile.height, + artUvs[cornerB * 2] * tile.width, + artUvs[cornerB * 2 + 1] * tile.height, + artUvs[cornerC * 2] * tile.width, + artUvs[cornerC * 2 + 1] * tile.height, + ), + ) + } + } + return triangles +} + +/** + * The coverage mask of every mesh bound to [tileId], or null when the tile has no measurable mesh. + * + * @param PuppetModel model The model. + * @param AtlasTileId tileId The tile. + * @return TileMeshMask? The mask. + */ +fun meshMaskOf(model: PuppetModel, tileId: AtlasTileId): TileMeshMask? = TileMeshMask.of(meshTrianglesOf(model, tileId)) + +/** + * A tile's sampled region on the page: the coverage of its meshes carried through its placement and + * tested exactly - a page point maps back into the tile through the placement inverse and reads the + * coverage bit, so a rotated tile's region stays its true shape. + * + * @property AtlasPlacement placement The tile's placement. + * @property TileMeshMask mask The meshes' coverage, raster-local. + */ +class SampledRegion( + val placement: AtlasPlacement, + val mask: TileMeshMask, +) { + private val pageToTile: FloatArray? = inversePlacementAffine(placement) + + /** The region's page-space bounds (the coverage box through the placement). */ + val bounds: PlacementFootprint = placementFootprint(placement, mask.bounds, reserve = null) + + /** + * Whether the page point ([pageX], [pageY]) lands on a covered tile pixel. + * + * @param Float pageX The page x. + * @param Float pageY The page y. + * @return Boolean True when covered; false for a degenerate placement. + */ + fun contains(pageX: Float, pageY: Float): Boolean { + val inverse = pageToTile ?: return false + val tileX = inverse[0] * pageX + inverse[1] * pageY + inverse[2] + val tileY = inverse[3] * pageX + inverse[4] * pageY + inverse[5] + return mask.isCovered(floor(tileX).toInt(), floor(tileY).toInt()) + } +} + +/** + * Whether [region] samples any opaque texel of [mask] placed at [placement], the composer's extrusion + * band counted as painted (a page pixel within [extrude] of the trim reads the nearest edge texel). + * + * Scans the intersection of the region's bounds with the placed trim's bounds grown by the band, and + * tests each pixel center both ways: inside the region, and on an opaque texel through the mask + * placement's inverse. + * + * @param SampledRegion region The sampling tile's region. + * @param AtlasPlacement placement Where the painting tile sits. + * @param TileOpaqueMask mask The painting tile's opaque texels. + * @param Int extrude The composer's edge extrusion. + * @return Boolean True when the region samples paint. + */ +fun sampledRegionHitsMask( + region: SampledRegion, + placement: AtlasPlacement, + mask: TileOpaqueMask, + extrude: Int, +): Boolean { + val painted = placementFootprint(placement, mask.trim, reserve = null).expanded(extrude.toFloat()) + val bounds = region.bounds + if (!bounds.overlaps(painted)) { + return false + } + val inverse = inversePlacementAffine(placement) ?: return false + val forward = placementAffine(placement) + val startX = floor(maxOf(bounds.left, painted.left)).toInt() + val endX = ceil(minOf(bounds.right, painted.right)).toInt() + val startY = floor(maxOf(bounds.top, painted.top)).toInt() + val endY = ceil(minOf(bounds.bottom, painted.bottom)).toInt() + val trim = mask.trim + val trimLeft = trim.left.toFloat() + val trimTop = trim.top.toFloat() + val trimRight = (trim.left + trim.width).toFloat() + val trimBottom = (trim.top + trim.height).toFloat() + val extrudeSquared = extrude.toFloat() * extrude.toFloat() + for (y in startY until endY) { + val centerY = y + 0.5f + for (x in startX until endX) { + val centerX = x + 0.5f + if (!region.contains(centerX, centerY)) { + continue + } + val tileX = inverse[0] * centerX + inverse[1] * centerY + inverse[2] + val tileY = inverse[3] * centerX + inverse[4] * centerY + inverse[5] + val clampedX = tileX.coerceIn(trimLeft, trimRight) + val clampedY = tileY.coerceIn(trimTop, trimBottom) + if (clampedX != tileX || clampedY != tileY) { + if (extrude == 0) { + continue + } + val backX = forward[0] * clampedX + forward[1] * clampedY + forward[2] + val backY = forward[3] * clampedX + forward[4] * clampedY + forward[5] + val deltaX = backX - centerX + val deltaY = backY - centerY + if (deltaX * deltaX + deltaY * deltaY > extrudeSquared) { + continue + } + } + val texelX = floor(clampedX).toInt().coerceIn(trim.left, trim.left + trim.width - 1) + val texelY = floor(clampedY).toInt().coerceIn(trim.top, trim.top + trim.height - 1) + if (mask.isOpaque(texelX, texelY)) { + return true + } + } + } + return false +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/DecodedImage.kt b/module/render/src/commonMain/kotlin/org/umamo/render/DecodedImage.kt new file mode 100644 index 0000000..d44df81 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/DecodedImage.kt @@ -0,0 +1,4 @@ +package org.umamo.render + +/** A decoded RGBA image (top row first), ready for GL upload. */ +class DecodedImage(val rgba: ByteArray, val width: Int, val height: Int) \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/DerivedAtlasTextures.kt b/module/render/src/commonMain/kotlin/org/umamo/render/DerivedAtlasTextures.kt new file mode 100644 index 0000000..73700d6 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/DerivedAtlasTextures.kt @@ -0,0 +1,233 @@ +package org.umamo.render + +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.atlas.AtlasPackItem +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.AtlasPackPlacement +import org.umamo.format.atlas.AtlasTilePlacement +import org.umamo.format.atlas.composeAtlasPagesAffine +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.AtlasComposition +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.placementAffine + +/* + * Page derivation for a GENERATED atlas: the pixels a model's authored placements denote, composed + * from the source art. An imported document's original pages never come through here while its + * atlas is the baseline - the session's page resolver short-circuits that value to the document's own + * decoded pages - but the moment a rigger moves one tile the whole page set derives from here, imported + * placements included, so nothing in this file may assume the packer authored every placement. + * + * Two steps on purpose: PLAN resolves what will be drawn (every placed tile's pixels, trim, and page + * affine) without touching a page buffer, and COMPOSE draws it. The plan is cheap and is also the + * footprint inventory the placement gizmo reads before it lets a gesture commit, so the drag and the + * resolver cannot disagree about what a placement will paint. + */ + +/** + * The rotation a placement carries for one of the packer's counter-clockwise quarter turns. + * + * [placementAffine] turns by +rotationDegrees with the matrix ((cos, -sin), (sin, cos)) in the page's + * y-down frame; the packer's turn sends trim-local (u, v) to (v, -u), which is that matrix at -90. + */ +private const val QUARTER_TURN_DEGREES = -90f + +/** + * The trim a derivation draws of [raster]: the packer's own opaque-bounds analysis at + * [alphaThreshold], or null when nothing in the raster is opaque. + * + * @param DecodedImage raster The tile's decoded source art. + * @param Int alphaThreshold The atlas's trim threshold (`PuppetAtlas.composition`). + * @return LayerBounds? The opaque sub-rectangle, raster-local. + */ +public fun derivedTileTrim(raster: DecodedImage, alphaThreshold: Int): LayerBounds? = + analyzeAlpha(raster.width, raster.height, raster.rgba, alphaThreshold)?.opaqueBounds + +/** + * The composition policy a pack under [options] leaves on the model, so the derivation trims and + * bleeds exactly as the pack did. + * + * @param AtlasPackOptions options The options the pack ran with. + * @return AtlasComposition The two derivation-relevant options, as model state. + */ +fun atlasCompositionOf(options: AtlasPackOptions): AtlasComposition = AtlasComposition(options.alphaThreshold, options.extrude) + +/** + * An [AtlasPackPlacement] lowered onto the model's placement transform: the trim origin folds into + * the position and scale stays 1. + * + * Upright, the tile's origin sits trimLeft / trimTop above and left of the packed rect. Turned, the + * packer sends trim-local (u, v) to (pageX + v, pageY + trimWidth - u), so over the untrimmed tile + * frame the origin lands at (pageX - trimTop, pageY + trimWidth + trimLeft) under a -90 degree + * rotation - the affine the composer's own exact quarter-turn path recognises, so a turned pack + * derives through the packer's blit. Any other turn count is a packer contract violation. + * + * @param AtlasPackPlacement packPlacement Where the packer put one tile. + * @return AtlasPlacement The equivalent authored placement. + */ +fun atlasPlacementFromPack(packPlacement: AtlasPackPlacement): AtlasPlacement { + require(packPlacement.quarterTurns in 0..1) { + "tile '${packPlacement.key}' has an unsupported rotation: ${packPlacement.quarterTurns} quarter turns" + } + return if (packPlacement.quarterTurns == 0) { + AtlasPlacement( + pageIndex = packPlacement.pageIndex, + positionX = (packPlacement.pageX - packPlacement.trimLeft).toFloat(), + positionY = (packPlacement.pageY - packPlacement.trimTop).toFloat(), + scaleX = 1f, + scaleY = 1f, + rotationDegrees = 0f, + ) + } else { + AtlasPlacement( + pageIndex = packPlacement.pageIndex, + positionX = (packPlacement.pageX - packPlacement.trimTop).toFloat(), + positionY = (packPlacement.pageY + packPlacement.trimWidth + packPlacement.trimLeft).toFloat(), + scaleX = 1f, + scaleY = 1f, + rotationDegrees = QUARTER_TURN_DEGREES, + ) + } +} + +/** + * What a derivation will compose: every placed tile's pixels, trim, and page affine, resolved + * before any page buffer is allocated. + * + * @property List items The placed tiles' pixels, keyed by tile id. + * @property List placements Each placed tile's trim and tile-to-page affine. + * @property Map trimByTile Each drawn tile's trim, for callers reasoning about footprints. + */ +class AtlasDerivationPlan( + val items: List, + val placements: List, + val trimByTile: Map, +) + +/** + * Resolves what [model]'s atlas denotes without composing a pixel. + * + * Null when the atlas cannot be derived at all: a placement naming a page the atlas lacks, art that + * will not decode, or art whose size disagrees with its tile - faults in the document, not in the + * placement. A placed tile with nothing opaque is skipped rather than refused (there is nothing to + * draw), and scale, rotation, fractional positions, and footprints past the page edge all derive: + * the composer resamples and clips them. + * + * Thread-safe: reads pixels through [SourceArtRasters.decodeRaster] and shares nothing, so callers + * run it off the UI thread. + * + * @param PuppetModel model The model whose atlas to resolve. + * @param SourceArtRasters artRasters The source-art pixel store. + * @return AtlasDerivationPlan? The plan, or null when the atlas cannot be derived. + */ +fun planAtlasDerivation(model: PuppetModel, artRasters: SourceArtRasters): AtlasDerivationPlan? { + val atlas = model.atlas + val items = ArrayList() + val placements = ArrayList() + val trimByTile = HashMap() + for (tile in atlas.tiles) { + val placement = tile.placement ?: continue + if (placement.pageIndex !in atlas.pages.indices) { + return null + } + val raster = artRasters.decodeRaster(tile.id) ?: return null + if (raster.width != tile.width || raster.height != tile.height) { + return null + } + // The packer trimmed each tile to its opaque bounds before placing it; the placement holds only + // the untrimmed origin, so the same analysis on the same pixels, under the threshold the atlas + // records, reconstructs the trim exactly. + val trim = derivedTileTrim(raster, atlas.composition.alphaThreshold) ?: continue + trimByTile[tile.id] = trim + items.add(AtlasPackItem(tile.id.raw, raster.width, raster.height, raster.rgba)) + placements.add(AtlasTilePlacement(tile.id.raw, placement.pageIndex, trim, placementAffine(placement))) + } + return AtlasDerivationPlan(items, placements, trimByTile) +} + +/** + * The [PuppetTextures] a generated atlas value denotes: pages composed from the model's tiles, + * placements, and decoded source art. + * + * For a page set built here, the model's page numbering and the renderer's COINCIDE by construction: + * [PuppetTextures.atlases] is index-parallel to `PuppetAtlas.pages`, and the drawable map carries + * each placement's own page index. That guarantee holds for GENERATED sets only - an imported + * document's two numberings stay independent (see [AtlasPlacement]), because its renderer pages were + * collected by a different walk than its document pages. + * + * A placement the packer authored (an integer translation with room for its extrusion) composes + * through the packer's own blit, byte-identical to the pages the repack produced; every other + * placement resamples through the affine composer. Null exactly when [planAtlasDerivation] is null; + * the caller treats that as "keep showing the pages you have". + * + * Thread-safe, like the plan. + * + * @param PuppetModel model The model whose atlas to compose. + * @param SourceArtRasters artRasters The source-art pixel store. + * @param Boolean premultipliedAlpha The document's texture-convention flag, carried through. + * @return PuppetTextures? The composed page set, or null when the atlas cannot be derived. + */ +fun deriveAtlasTextures( + model: PuppetModel, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, +): PuppetTextures? { + val plan = planAtlasDerivation(model, artRasters) ?: return null + val atlas = model.atlas + val pages = + composeAtlasPagesAffine( + pageWidths = IntArray(atlas.pages.size) { pageIndex -> atlas.pages[pageIndex].width }, + pageHeights = IntArray(atlas.pages.size) { pageIndex -> atlas.pages[pageIndex].height }, + items = plan.items, + placements = plan.placements, + extrude = atlas.composition.extrude, + ) + return generatedPuppetTextures(pages, model, premultipliedAlpha) +} + +/** + * The [PuppetTextures] a GENERATED page set is: [pages] wrapped as decoded images, index-parallel to + * `PuppetAtlas.pages`, under the drawable map of [generatedAtlasIndexByDrawableId]. + * + * One function used by the repack (from the pack it just ran), the derivation above (for an undone + * generation), and the export gate, so no caller assembles the wrapper on its own and the page cache's + * identity-keyed sets are always built the same way. + * + * @param List pages The composed pages, in the model's page order. + * @param PuppetModel model The model whose bindings key the drawable map. + * @param Boolean premultipliedAlpha The document's texture-convention flag, carried through. + * @return PuppetTextures The page set. + */ +fun generatedPuppetTextures( + pages: List, + model: PuppetModel, + premultipliedAlpha: Boolean, +): PuppetTextures = + PuppetTextures( + atlases = pages.map { page -> DecodedImage(page.rgba, page.width, page.height) }, + atlasIndexByDrawableId = generatedAtlasIndexByDrawableId(model), + premultipliedAlpha = premultipliedAlpha, + ) + +/** + * The drawable-to-page map a GENERATED page set carries: every drawable bound to a placed tile maps + * to that tile's own page index, so the map shares the model's page numbering. + * + * @param PuppetModel model The model whose bindings to map. + * @return Map The renderer's drawable-to-page lookup. + */ +fun generatedAtlasIndexByDrawableId(model: PuppetModel): Map { + val placementByTileId = model.atlas.tiles.associateBy({ tile -> tile.id }, { tile -> tile.placement }) + val atlasIndexByDrawableId = HashMap() + for (drawable in model.drawables) { + val tileId = drawable.atlasTileId ?: continue + val placement = placementByTileId[tileId] ?: continue + // Keyed the way the renderer looks it up: a duplicated drawable resolves its page through the + // drawable it was duplicated from (Drawable.textureSourceId), and shared sources share a tile. + atlasIndexByDrawableId[(drawable.textureSourceId ?: drawable.id).raw] = placement.pageIndex + } + return atlasIndexByDrawableId +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/FrameBackdrop.kt b/module/render/src/commonMain/kotlin/org/umamo/render/FrameBackdrop.kt new file mode 100644 index 0000000..fc266b6 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/FrameBackdrop.kt @@ -0,0 +1,67 @@ +package org.umamo.render + +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.setOpaqueAlphaInPlace +import org.umamo.format.raster.unpremultiplyInPlace + +/** + * What a puppet frame is drawn over. + * + * The viewport always draws over its grid; an image captured from the renderer chooses, because a + * transparent or flat background is what makes the capture usable outside the editor. + */ +sealed interface FrameBackdrop { + /** + * The themed grid backdrop the viewport shows, with the world-origin axes when the renderer has them + * turned on. + */ + data object Grid : FrameBackdrop + + /** + * A flat fill, as premultiplied 0..1 RGBA. Transparent is all four at zero; an opaque color has alpha + * 1, where premultiplied and straight color are the same. No grid and no axes are drawn. + * + * @property Float red The fill's red. + * @property Float green The fill's green. + * @property Float blue The fill's blue. + * @property Float alpha The fill's alpha. + */ + data class Clear( + val red: Float, + val green: Float, + val blue: Float, + val alpha: Float, + ) : FrameBackdrop + + companion object { + /** Nothing at all: every pixel the puppet does not cover stays fully transparent. */ + val Transparent: FrameBackdrop = Clear(0f, 0f, 0f, 0f) + } +} + +/** + * Turns a premultiplied capture drawn over [backdrop] into the straight-alpha image a file stores, in place. + * + * Over an opaque backdrop every pixel is opaque, so the color is already straight and only the alpha + * channel is set to 255. Over anything with coverage to spare (transparency, or a translucent fill) the + * color divides back out by its alpha. + * + * Consumes the capture: its own buffer is converted and the same image returned, because a capture can be + * a gigabyte and a converted copy would double that. The caller must own the pixels. + * + * @param FrameBackdrop backdrop What the capture was drawn over. + * @return RasterImage This image, now straight alpha, top row first. + */ +fun RasterImage.capturedOver(backdrop: FrameBackdrop): RasterImage { + val opaque = + when (backdrop) { + FrameBackdrop.Grid -> true + is FrameBackdrop.Clear -> backdrop.alpha >= 1f + } + if (opaque) { + setOpaqueAlphaInPlace() + } else { + unpremultiplyInPlace() + } + return this +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/GridColors.kt b/module/render/src/commonMain/kotlin/org/umamo/render/GridColors.kt new file mode 100644 index 0000000..2abbd95 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/GridColors.kt @@ -0,0 +1,77 @@ +package org.umamo.render + +/** + * The three colors of the viewport grid backdrop, as 0..1 linear RGB triples: the flat canvas fill, the + * major grid line color, and the minor (subdivision) grid line color. Kept as plain floats (not a Compose + * Color) so :render stays free of any UI dependency; the editor maps its themed palette into this at the + * call site. [Classic] is a neutral grey grid, used as the default so a caller that does not theme the + * backdrop still gets a sensible surface. + * + * ビューポートのグリッド背景の 3 色(0..1 の RGB)。背景・主線・副線。:render を UI 非依存に保つため素の float。 + * + * @property Float backgroundRed Red of the flat canvas fill. + * @property Float backgroundGreen Green of the flat canvas fill. + * @property Float backgroundBlue Blue of the flat canvas fill. + * @property Float majorRed Red of the major grid line. + * @property Float majorGreen Green of the major grid line. + * @property Float majorBlue Blue of the major grid line. + * @property Float minorRed Red of the minor (subdivision) grid line. + * @property Float minorGreen Green of the minor grid line. + * @property Float minorBlue Blue of the minor grid line. + */ +data class GridColors( + val backgroundRed: Float, + val backgroundGreen: Float, + val backgroundBlue: Float, + val majorRed: Float, + val majorGreen: Float, + val majorBlue: Float, + val minorRed: Float, + val minorGreen: Float, + val minorBlue: Float, +) { + companion object { + /** A neutral dark-grey grid: #2E2E2E fill, #484848 major lines, #3A3A3A minor lines. */ + val Classic: GridColors = + GridColors( + 0.204f, + 0.204f, + 0.204f, + 0.317f, + 0.317f, + 0.317f, + 0.270f, + 0.270f, + 0.270f, + ) + } +} + +/** + * The two world-axis line colors, as 0..1 linear RGB triples - the red X axis and the blue Z axis + * drawn through the world origin behind the puppet (the project's display convention is Y+ forward, + * Z+ up, so the vertical world axis is presented as Z). Plain floats for the same reason as + * [GridColors]: :render stays free of any UI dependency. + * + * ワールド軸線の 2 色(0..1 の RGB)。横が赤い X 軸、縦が青い Z 軸(表示規約は Y+ 前、Z+ 上)。 + * + * @property Float xRed Red of the horizontal X axis line. + * @property Float xGreen Green of the horizontal X axis line. + * @property Float xBlue Blue of the horizontal X axis line. + * @property Float zRed Red of the vertical Z axis line. + * @property Float zGreen Green of the vertical Z axis line. + * @property Float zBlue Blue of the vertical Z axis line. + */ +data class WorldAxisColors( + val xRed: Float, + val xGreen: Float, + val xBlue: Float, + val zRed: Float, + val zGreen: Float, + val zBlue: Float, +) { + companion object { + /** Blender-like axis colors: a muted red X and a muted blue Z. */ + val Classic: WorldAxisColors = WorldAxisColors(0.84f, 0.31f, 0.36f, 0.31f, 0.44f, 0.85f) + } +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/LayerDrawPlan.kt b/module/render/src/commonMain/kotlin/org/umamo/render/LayerDrawPlan.kt new file mode 100644 index 0000000..78c03b3 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/LayerDrawPlan.kt @@ -0,0 +1,128 @@ +package org.umamo.render + +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.atlasBindingFor +import org.umamo.runtime.model.layerUvAffineOf + +/** + * One drawable's source-artwork draw: which image it samples, and the affine carrying its stored + * texture coordinates into that image's frame. + * + * @property String layerKey The artwork this drawable samples, keyed into [LayerRasterBatch.rastersByLayerKey]. + * @property FloatArray uvAffine The 2x3 row-major stored-to-artwork affine (see `layerUvAffineOf`). + */ +class DrawableLayerDraw(val layerKey: String, val uvAffine: FloatArray) + +/** + * Which artwork every drawable would display from, and what each image would cost to hold - the + * mapping half of source-artwork display, carrying no pixels at all. + * + * ALWAYS COMPLETE: it covers every drawable whose art this document can recover, whether or not that + * art is currently decoded or resident on the GPU. That completeness is what lets the renderer bound + * residency without losing information - a layer dropped for budget can be promoted again later + * because its mapping never went away, and [unresolvedDrawableCount] keeps meaning "no artwork + * exists" rather than drifting into "not resident right now". + * + * Cheap to build and cheap to hold: [layerByteCostByKey] comes from the model's atlas tile sizes, so + * the cost of every image is known BEFORE any of them decode, which is what makes a budget + * enforceable up front instead of after the memory is already spent. + * + * A drawable absent from [drawsByDrawableId] renders from its atlas page as usual, so a document + * whose artwork is only partly recoverable still draws whole. + * + * @property Map drawsByDrawableId Each drawable's draw, by raw drawable id. + * @property Map layerByteCostByKey What each distinct image costs decoded, in bytes. + * Keyed by LAYER, not by drawable: duplicated art is shared, so a layer is paid for once. + * @property Int unresolvedDrawableCount How many meshed drawables have no recoverable artwork at all + * and so keep displaying from the atlas. Reported rather than hidden: a puppet drawn mostly from + * its atlas should not look like one drawn from its artwork. + */ +class LayerDrawPlan( + val drawsByDrawableId: Map, + val layerByteCostByKey: Map, + val unresolvedDrawableCount: Int = 0, +) { + /** True when there is nothing to display from, so the puppet stays on the atlas. */ + val isEmpty: Boolean get() = drawsByDrawableId.isEmpty() + + /** + * Which drawables draw over any of the given layers. + * + * @param Set layerKeys The layers in question. + * @return Set The raw ids of the drawables mapped onto them. + */ + fun drawableIdsUsing(layerKeys: Set): Set = + drawsByDrawableId.filterValues { draw -> draw.layerKey in layerKeys }.keys + + companion object { + /** The empty plan: display from the atlas. */ + val EMPTY: LayerDrawPlan = LayerDrawPlan(emptyMap(), emptyMap()) + } +} + +/** + * A delivery of decoded artwork answering what the renderer asked for - the pixel half, transient by + * design. + * + * Pixels arrive in batches rather than as one complete set, and THAT is what keeps this affordable: + * the producer decodes a chunk, hands it over, and drops its reference before decoding the next, so + * the heap holds one chunk rather than the document's whole artwork. A rig whose layers would be a + * gigabyte decoded costs a few tens of megabytes to stream. + * + * Batches are additive and order-independent - the renderer uploads whatever a batch carries that its + * current plan still maps, and ignores the rest - so a late batch from a superseded plan is harmless + * rather than something to detect. + * + * @property Map rastersByLayerKey The decoded images, by layer key. + * @property Set undecodableLayerKeys Layers whose pixels would not decode. Reported so the + * drawables over them can be counted as artwork-less rather than merely absent from this batch. + */ +class LayerRasterBatch( + val rastersByLayerKey: Map, + val undecodableLayerKeys: Set = emptySet(), +) + +/** + * Works out which source artwork each drawable would display from, and what each image would cost. + * + * Decodes NOTHING. It reads only the model's atlas - tile sizes and placements - so it is cheap + * enough to build eagerly for the whole document and to rebuild whenever the drawable set or a + * placement changes. Deciding the mapping separately from paying for the pixels is what lets a budget + * be applied before any memory is spent, and what keeps a budget-evicted layer promotable later. + * + * Safe on a background thread: it reads only the immutable model and touches neither the document's + * decode cache nor the device. + * + * A drawable is left out (and counted in [LayerDrawPlan.unresolvedDrawableCount]) when the document + * retains no art for it or when its placement will not invert. A layer whose pixels turn out not to + * decode is NOT known here - that surfaces later, from the batch that tried, so this count means + * exactly "no artwork exists" and never "not decoded yet". + * + * @param PuppetModel model The puppet whose drawables need artwork. + * @return LayerDrawPlan Each drawable's mapping plus the per-layer byte cost. + */ +fun buildLayerDrawPlan(model: PuppetModel): LayerDrawPlan { + if (model.atlas.tiles.isEmpty()) { + return LayerDrawPlan.EMPTY + } + val drawsByDrawableId = HashMap() + val layerByteCostByKey = HashMap() + var unresolved = 0 + for (drawable in model.drawables) { + if (drawable.mesh == null) { + continue + } + val binding = model.atlasBindingFor(drawable) + val tile = drawable.atlasTileId?.let { tileId -> model.atlas.tileById[tileId] } + val affine = if (binding != null && tile != null) layerUvAffineOf(binding, tile.width, tile.height) else null + if (binding == null || tile == null || affine == null) { + unresolved++ + continue + } + // Four bytes per pixel: what the image occupies once decoded to RGBA and again once uploaded, + // which is the quantity the residency budget is denominated in. + layerByteCostByKey[binding.layerKey] = tile.width.toLong() * tile.height.toLong() * 4L + drawsByDrawableId[drawable.id.raw] = DrawableLayerDraw(binding.layerKey, affine) + } + return LayerDrawPlan(drawsByDrawableId, layerByteCostByKey, unresolved) +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/Moc3RestMesh.kt b/module/render/src/commonMain/kotlin/org/umamo/render/Moc3RestMesh.kt new file mode 100644 index 0000000..939240e --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/Moc3RestMesh.kt @@ -0,0 +1,314 @@ +package org.umamo.render + +import org.umamo.render.eval.CpuDeformationEvaluator +import org.umamo.render.eval.DeformedGeometry +import org.umamo.render.eval.drawableSpaceMapping +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.math.max +import kotlin.math.min + +/** The warp inverse's neutral seed: the middle of the normalized [0,1] lattice. */ +private const val LATTICE_CENTRE: Float = 0.5f + +/** + * Rewrites each drawable's rest mesh to its default-pose canvas-space geometry, matching the CMO3 + * convention the editor is built on. + * + * The runtime convention (set by CMO3, verified against the corpus): Drawable.mesh.positions is the + * EDITABLE canvas-space geometry - what the gizmo overlay edits and the viewport maps gestures into - + * while each MeshForm's absolute positions (base + delta) live in the drawable's PARENT-DEFORMER + * space. The deformation eval only ever sees `base + Σ wᵢ·Δᵢ` with weights summing to 1, so the base + * cancels and this mixed-space encoding is exact, not an approximation. + * + * A `.moc3` stores only the parent-space keyforms, so :interop's `Moc3Import` can give + * a warp/rotation-parented drawable nothing better than a parent-local base. This pass finishes the + * import: it evaluates the default pose through the validated deformer cascade (glue excluded - the + * weld is a render-time effect, not rest geometry), takes the pre-Y-negation canvas positions as the + * new base, and re-expresses every keyform delta against it so `base + delta` still reconstructs the + * same parent-space absolutes. Drawables the raw default pose hides (a keyform axis whose keys do + * not bracket the driving parameter's default - the toggle-part authoring pattern) get a second + * evaluation at a pose with those parameters clamped into their axes' key ranges, so their rest + * meshes still land in canvas space. It lives in `:render` (not `:runtime`) because it is the + * evaluator that turns parent-space keyforms into canvas geometry. + * + * @param PuppetModel model An imported model whose rest meshes may be parent-local (a MOC3 import). + * @return PuppetModel The model with canvas-space rest meshes (a drawable that stays hidden even at + * the clamped pose keeps its parent-local base, which still evaluates correctly). + */ +fun restMeshesToCanvasSpace(model: PuppetModel): PuppetModel { + val preGlueModel = model.copy(glues = emptyList()) + val evaluator = CpuDeformationEvaluator() + val defaultPose = evaluator.evaluate(preGlueModel, emptyMap()) + + // Second chance for drawables absent from the raw default pose: clamp every involved parameter + // into its axes' key ranges and evaluate once more. Only the still-missing drawables read from + // this pose, so in-range drawables keep their true default geometry. + val fallback = defaultPoseFallbackFor(model, defaultPose) + val clampedPose = fallback?.let { rescue -> evaluator.evaluate(preGlueModel, rescue.clampedDefaults) } + + val drawables = + model.drawables.map { drawable -> + val mesh = drawable.mesh ?: return@map drawable + val worldPositions = + defaultPose.worldPositions[drawable.id] + ?: clampedPose?.worldPositions?.get(drawable.id) + ?: return@map drawable + if (worldPositions.size != mesh.positions.size) { + return@map drawable + } + // All-or-nothing: a size-mismatched delta array holds ABSOLUTE positions by the importer's + // fallback convention, so rebasing any prefix of it would double-count the base and mix two + // spaces in one array. A drawable carrying such a cell keeps its whole grid AND base + // untouched - partially rewriting either would corrupt what malformed data still encodes. + // Blend-shape forms are rest-relative like the grid cells, so they gate (and rebase) the + // same way - leaving them on the old base while the grid moves would shift every blend + // contribution by exactly (new base - old base). + val anyCellMismatches = + (drawable.geometryGrid?.cells?.any { cell -> cell.form.positionDeltas.size != mesh.positions.size } ?: false) || + drawable.blendShapes.any { binding -> + binding.forms.any { form -> form != null && form.positionDeltas.size != mesh.positions.size } + } + if (anyCellMismatches) { + return@map drawable + } + // The eval negates Y into world space; canvas space is the pre-negation Y-down convention. + val canvasBase = + FloatArray(worldPositions.size) { coordIndex -> + if (coordIndex % 2 == 1) -worldPositions[coordIndex] else worldPositions[coordIndex] + } + // Only the geometry rebases - and since the split that is structural rather than something the + // copy has to remember: the channel tracks are a separate field and are simply not touched. + val rebasedGeometry = + drawable.geometryGrid?.let { grid -> + KeyformGrid( + grid.axes, + grid.cells.map { cell -> + val oldDeltas = cell.form.positionDeltas + KeyformCell( + cell.coordinate, + MeshDeltaForm( + FloatArray(oldDeltas.size) { coordIndex -> + (mesh.positions[coordIndex] + oldDeltas[coordIndex]) - canvasBase[coordIndex] + }, + ), + ) + }, + ) + } + val rebasedBlendShapes = + drawable.blendShapes.map { binding -> + binding.copy( + forms = + binding.forms.map { form -> + form?.let { meshForm -> + MeshForm( + FloatArray(meshForm.positionDeltas.size) { coordIndex -> + (mesh.positions[coordIndex] + meshForm.positionDeltas[coordIndex]) - canvasBase[coordIndex] + }, + meshForm.drawOrder, + meshForm.opacity, + meshForm.multiplyColor, + meshForm.screenColor, + ) + } + }, + ) + } + drawable.copy( + mesh = DrawableMesh(canvasBase, mesh.uvs, mesh.indices), + geometryGrid = rebasedGeometry, + blendShapes = rebasedBlendShapes, + ) + } + return model.copy(drawables = drawables) +} + +/** + * The drawables the raw default pose hides, paired with the clamped pose that rescues them. + * + * @property Set hiddenIds Drawables with a mesh but no default-pose geometry. + * @property Map clampedDefaults The pose to evaluate those drawables at. + */ +private class DefaultPoseFallback( + val hiddenIds: Set, + val clampedDefaults: Map, +) + +/** + * Which drawables need the clamped second-chance pose, and what that pose is. + * + * Both directions of the canvas-space conversion ask this, and they MUST agree: the forward pass maps + * such a drawable through the clamped pose, so an export that inverted it through the raw default + * would be undoing a transform that was never applied. + * + * No `keyforms != null` gate: an unkeyed drawable evaluates at its rest mesh rather than being skipped, + * so one still absent from the default pose is genuinely hidden (a hidden ancestor deformer) and + * deserves the same second chance as any other. + * + * @param PuppetModel model The model being converted. + * @param DeformedGeometry defaultPose Its evaluation at the raw default parameters. + * @return DefaultPoseFallback? The hidden set and their pose, or null when nothing is hidden. + */ +private fun defaultPoseFallbackFor(model: PuppetModel, defaultPose: DeformedGeometry): DefaultPoseFallback? { + val hiddenAtDefault = + model.drawables.filter { drawable -> + drawable.mesh != null && defaultPose.worldPositions[drawable.id] == null + }.map { drawable -> drawable.id } + if (hiddenAtDefault.isEmpty()) { + return null + } + return DefaultPoseFallback(hiddenAtDefault.toSet(), clampedDefaultsFor(model, hiddenAtDefault)) +} + +/** + * Lattice-UV band for an already-parent-local warp child. Wider than [0,1] so mild extrapolation + * (Bear TopTeeth reaches ~1.06) still counts as local; far tighter than canvas pixel rests, which + * sit in the hundreds or thousands after [restMeshesToCanvasSpace]. + */ +private const val LATTICE_UV_MIN: Float = -1f +private const val LATTICE_UV_MAX: Float = 2f + +/** + * The export's space seam for [puppet]: ensures an unkeyed drawable's rest mesh is parent-local for + * the MOC3 write. + * + * Two document origins store that rest differently: + * - After [restMeshesToCanvasSpace] (MOC3 import), the rest is canvas-space and must be inverted + * through the parent chain at the same pose the forward pass used. + * - UMA / CMO3 / warp-create remaps already author the rest in parent-local space (lattice UV under a + * warp). Blindly inverting those as if they were canvas double-transforms them - MouthCircle-class + * meshes crush to garbage coordinates and fly off when the parent warp opens. + * + * Under a warp, already-local rests are recognized by lying in the lattice-UV band; canvas rests fall + * well outside it and take the inverse. (A Newton round-trip cannot tell the two apart: an + * extrapolated preimage of a UV-as-canvas point still forward-maps to that point.) A drawable the + * chain cannot map returns null, which the export turns into a notice rather than a silently + * mis-scaled mesh. + * + * The pose is the neutral one for most drawables - the pose the rest mesh is defined at. A drawable + * the raw default hides went forward through the clamped second-chance pose instead, so it is inverted + * through that same clamped pose; using the raw default for it would undo a transform that was never + * applied. + * + * @param PuppetModel puppet The rig being exported. + * @return Function2 The seam: drawable id plus interleaved rest positions to parent-space positions, + * or null when the chain cannot invert. + */ +fun canvasToParentSpaceFor(puppet: PuppetModel): (DrawableId, FloatArray) -> FloatArray? { + // Resolved once per export rather than per drawable: the evaluation is the expensive part and the + // answer is a property of the model, not of whichever drawable is being written. + val preGlueModel = puppet.copy(glues = emptyList()) + val defaultPose = CpuDeformationEvaluator().evaluate(preGlueModel, emptyMap()) + val fallback = defaultPoseFallbackFor(puppet, defaultPose) + val drawableById = puppet.drawables.associateBy { drawable -> drawable.id } + val deformerById = puppet.deformers.associateBy { deformer -> deformer.id } + + return space@{ drawableId, positions -> + val pose = + if (fallback != null && drawableId in fallback.hiddenIds) { + fallback.clampedDefaults + } else { + emptyMap() + } + // Warp children whose rest already sits in lattice UV must not be inverted - that is the + // MouthCircle double-transform. Detect before asking the chain so a UV rest never enters Newton + // as a fake canvas target. + val parent = drawableById[drawableId]?.parentDeformerId?.let { parentId -> deformerById[parentId] } + if (parent is Deformer.Warp && looksLikeLatticeUv(positions)) { + return@space positions + } + drawableSpaceMapping(puppet, pose, drawableId)?.let { mapping -> + // worldToLocal expects the renderer's Y-negated world space, and every vertex is solved. + val world = FloatArray(positions.size) { index -> if (index % 2 == 0) positions[index] else -positions[index] } + // The seed matters only for the warp inverse, and it must be a LATTICE UV, not a canvas + // coordinate: seeding Newton with the canvas-space value starts it hundreds of units outside + // the [0,1] lattice, where the damped step cannot walk back. The lattice center is the + // neutral seed - at most half a lattice away from any target, which the damped step covers. + val seed = FloatArray(positions.size) { LATTICE_CENTRE } + mapping.worldToLocal(world, seed, positions.indices.step(2).map { index -> index / 2 }.toSet()) + } + } +} + +/** + * Whether [positions] lie in the normalized lattice-UV band a warp child authors in parent-local + * space, as opposed to canvas-pixel rests from [restMeshesToCanvasSpace]. + * + * @param FloatArray positions Interleaved rest coordinates. + * @return Boolean True when every coordinate is inside [[LATTICE_UV_MIN], [LATTICE_UV_MAX]]. + */ +private fun looksLikeLatticeUv(positions: FloatArray): Boolean { + for (coordinate in positions) { + if (coordinate < LATTICE_UV_MIN || coordinate > LATTICE_UV_MAX) { + return false + } + } + return positions.isNotEmpty() +} + +/** + * The clamped evaluation pose for drawables hidden at the raw default: every parameter driving a + * hidden drawable's own keyform grid or any grid on its ancestor deformer chain is coerced into the + * intersection of those axes' key ranges (the tightest span that satisfies every involved axis). + * When the intersection is empty (conflicting axes - pathological), the lower bound wins; unlisted + * parameters keep their defaults via the evaluator's fallback. + * + * @param PuppetModel model The imported model. + * @param List hiddenIds The drawables absent from the raw default pose. + * @return Map The clamped values for the involved parameters only. + */ +private fun clampedDefaultsFor(model: PuppetModel, hiddenIds: List): Map { + val drawableById = model.drawables.associateBy { it.id } + val deformerById = model.deformers.associateBy { it.id } + val lowerByParameter = HashMap() + val upperByParameter = HashMap() + + fun addAxes(grid: KeyformGrid<*>?) { + for (axis in grid?.axes.orEmpty()) { + if (axis.keys.isEmpty()) { + continue + } + val firstKey = axis.keys.first() + val lastKey = axis.keys.last() + lowerByParameter[axis.parameterId] = max(lowerByParameter[axis.parameterId] ?: firstKey, firstKey) + upperByParameter[axis.parameterId] = min(upperByParameter[axis.parameterId] ?: lastKey, lastKey) + } + } + + for (drawableId in hiddenIds) { + val drawable = drawableById[drawableId] ?: continue + addAxes(drawable.geometryGrid) + var parentId = drawable.parentDeformerId + var chainSteps = 0 + while (parentId != null && chainSteps <= model.deformers.size) { + val deformer = deformerById[parentId] ?: break + // Geometry AND channel tracks: a deformer keyed only on, say, opacity still constrains which + // parameters have to be clamped for the second-chance default-pose evaluation. + when (deformer) { + is Deformer.Warp -> addAxes(deformer.geometryGrid) + is Deformer.Rotation -> addAxes(deformer.geometryGrid) + } + deformer.channelGrids.gridsByChannel.values.forEach { track: KeyformGrid<*> -> addAxes(track) } + parentId = deformer.parent + chainSteps++ + } + } + + val defaultByParameter = model.parameters.associate { parameter -> parameter.id to parameter.default } + return buildMap { + for ((parameterId, lowerBound) in lowerByParameter) { + val upperBound = upperByParameter[parameterId] ?: lowerBound + val defaultValue = defaultByParameter[parameterId] ?: 0f + val clampedValue = if (lowerBound <= upperBound) defaultValue.coerceIn(lowerBound, upperBound) else lowerBound + put(parameterId, clampedValue) + } + } +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/PuppetTextures.kt b/module/render/src/commonMain/kotlin/org/umamo/render/PuppetTextures.kt new file mode 100644 index 0000000..bf70ed8 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/PuppetTextures.kt @@ -0,0 +1,169 @@ +package org.umamo.render + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.PuppetModel + +/** + * The texture data backing a puppet preview: the distinct atlas page(s) the art meshes sample, plus a + * per-drawable index into them. Art meshes typically share one atlas page in `TEXTURE_ATLAS` mode, but + * this structure generalises to multiple pages. + * + * For an IMPORTED document [atlases] is ordered by the renderer's own page walk and shares no + * numbering with the model's `PuppetAtlas.pages`. A page set Umamo generates itself (a repack's, + * built by `deriveAtlasTextures`) is index-parallel to `PuppetAtlas.pages` instead, so for generated + * sets a placement's page index is valid against both lists. + * + * [premultipliedAlpha] is the OR-fold of the CMO3 `GTexture2D.isPremultiplied` bits and is currently + * UNCONSUMED - and is deliberately kept that way. It is an editor texture-upload-convention flag + * (serialized true on nearly every model), NOT a claim that the decoded bytes are premultiplied: every + * ingested page is straight-alpha (PngCodec yields straight alpha; the fragment shader premultiplies + * in-shader with source factor GL_ONE), so wiring this to "unpremultiply the bytes" would over-darken + * the whole corpus. The version-dependent premultiplied-vs-straight COMPOSITING distinction (Cubism + * 5.2 and earlier plus the "(Before 5.3)" modes composite premultiplied; 5.3+ Color blend composites + * straight) is a separate axis, carried by `BlendMode.isLegacy` and handled in + * `BlendMath.compositeReference`, not by this field. See docs/format/CMO3.md, "Premultiplied vs + * straight alpha". + * + * @property List atlases The distinct decoded atlas pages. + * @property Map atlasIndexByDrawableId Drawable id (`ArtMesh…`) → index into [atlases]. + * @property Boolean premultipliedAlpha Aggregated `GTexture2D.isPremultiplied`; unconsumed + * (see the note above) - do not drive rendering off it. + */ +class PuppetTextures( + val atlases: List, + val atlasIndexByDrawableId: Map, + val premultipliedAlpha: Boolean, +) + +/** + * How [buildPuppetTextures] treats an atlas page whose bytes will not decode. + * + * The two ingest paths want opposite answers and each is right for its format, so the policy is the + * caller's to state rather than something the shared builder decides for them. + */ +enum class UndecodablePagePolicy { + /** + * Drop the page and unmap every drawable that sampled it; the build still succeeds. What a CMO3 + * wants: its pixels are embedded in the model file, so a page that will not decode is one corrupt + * resource inside an otherwise editable rig, and refusing to open the document over it would cost + * the rigger everything else in the file. Those drawables render in fallback color. + */ + Skip, + + /** + * Fail the whole build so the loader can report a broken import. What a MOC3 wants: its pages are + * sibling files named by model3.json, so one that will not decode means the family on disk is + * incomplete or mismatched - an import error to surface, not a puppet to render half of. + */ + Fail, +} + +/** + * Builds the [PuppetTextures] for a puppet from its atlas page bytes and a per-drawable index into + * them - the format-agnostic core both ingest paths end at. + * + * Each format's own atlas-page walk (`cmo3AtlasPages`, `moc3AtlasPages`, in `:interop`) produces a + * neutral `AtlasPageSet` that the document loader unpacks into these two arguments and hands here, so + * the decode, the page-index validation, and the PuppetTextures shape are written once. Nothing about + * this function knows a format; it is deliberately reachable with hand-built arguments so tests need + * no corpus file. + * + * @param List pageBytes The PNG bytes per atlas page, in index order. + * @param Map atlasIndexByDrawableId Drawable id (`ArtMesh…`) → index into [pageBytes]. + * @param Boolean premultipliedAlpha Passed through to [PuppetTextures.premultipliedAlpha]; + * see its docblock - aggregated by the CMO3 adapter + * and unconsumed, false everywhere else. + * @param UndecodablePagePolicy undecodablePage What an undecodable page costs. + * @return PuppetTextures? The decoded pages + index, or null when [undecodablePage] is + * [UndecodablePagePolicy.Fail] and a page failed to decode or a drawable's + * index fell outside [pageBytes]. Never null under + * [UndecodablePagePolicy.Skip]. + */ +fun buildPuppetTextures( + pageBytes: List, + atlasIndexByDrawableId: Map, + premultipliedAlpha: Boolean = false, + undecodablePage: UndecodablePagePolicy = UndecodablePagePolicy.Fail, +): PuppetTextures? { + val failOnBadPage = undecodablePage == UndecodablePagePolicy.Fail + // An index outside the page list must never reach the renderer: PuppetRenderer resolves pages by + // direct list indexing, so broken atlas wiring is caught here rather than crashing the render + // thread at first frame. Under Skip the same guard applies per drawable instead of per build - + // an unresolvable page number simply leaves that drawable out of the rebuilt map below. + if (failOnBadPage && atlasIndexByDrawableId.values.any { pageIndex -> pageIndex !in pageBytes.indices }) { + return null + } + + // Skip can drop pages, which shifts every later page down by however many preceded it, so decoding + // records where each surviving page landed and the drawable map is rebuilt against that numbering. + // Under Fail nothing is ever dropped and the remap is an identity copy. + val atlases = ArrayList(pageBytes.size) + val keptIndexBySourceIndex = HashMap(pageBytes.size) + for ((sourceIndex, bytes) in pageBytes.withIndex()) { + val image = + try { + PngCodec.read(bytes) + } catch (_: Exception) { + if (failOnBadPage) { + return null + } + continue + } + keptIndexBySourceIndex[sourceIndex] = atlases.size + atlases.add(DecodedImage(image.rgba, image.width, image.height)) + } + + val keptIndexByDrawableId = LinkedHashMap(atlasIndexByDrawableId.size) + for ((drawableId, sourceIndex) in atlasIndexByDrawableId) { + keptIndexBySourceIndex[sourceIndex]?.let { keptIndex -> keptIndexByDrawableId[drawableId] = keptIndex } + } + return PuppetTextures(atlases, keptIndexByDrawableId, premultipliedAlpha) +} + +/** + * Re-encodes a decoded atlas page as PNG, for a page the document retains no source bytes for. + * + * The fallback half of both exports' page payload: a retained source PNG is written verbatim, which is + * faster and lossless, and this covers every page there is no such PNG for. A CMO3-origin document + * reaches it for every page (its pixels are embedded per drawable, so it retains no atlas PNGs at all). + * A MOC3-origin one retains a PNG per decoded page and so does not reach it, and falls back here only + * if those two lists ever diverge - which would otherwise leave that page with no bytes to write. + * + * Re-encoding rather than dropping the page is what keeps page INDICES stable - drawables address + * pages by number, so omitting one would renumber every page after it. + * + * @param DecodedImage atlas The decoded page. + * @return ByteArray The PNG bytes. + */ +fun encodeAtlasPng(atlas: DecodedImage): ByteArray = + PngCodec.write(RasterImage(width = atlas.width, height = atlas.height, rgba = atlas.rgba)) + +/** + * [puppet] with every drawable's atlas page taken from [textures]. + * + * A MOC3 addresses its pages by index on the art mesh, so the export needs one on every drawable. A + * MOC3-origin document already carries them (the import reads them straight off the art mesh), but a + * CMO3 has no page index at all - its pixels are embedded per drawable - so those documents reach the + * export with every drawable still on the -1 sentinel, which the MOC3 lowering clamps to page 0, + * pointing a multi-page rig at one atlas. The decoded texture set is what knows the answer either + * way, so it is the one asked. + * + * @param PuppetModel puppet The rig being exported. + * @param PuppetTextures textures The document's decoded atlas set. + * @return PuppetModel The rig with its page bindings resolved, or [puppet] when none moved. + */ +fun withTexturePagesFrom(puppet: PuppetModel, textures: PuppetTextures): PuppetModel { + var moved = false + val drawables = + puppet.drawables.map { drawable -> + val page = textures.atlasIndexByDrawableId[drawable.id.raw] ?: return@map drawable + if (page == drawable.texturePage) { + drawable + } else { + moved = true + drawable.copy(texturePage = page) + } + } + return if (moved) puppet.copy(drawables = drawables) else puppet +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/SourceArtRasters.kt b/module/render/src/commonMain/kotlin/org/umamo/render/SourceArtRasters.kt new file mode 100644 index 0000000..93c030f --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/SourceArtRasters.kt @@ -0,0 +1,119 @@ +package org.umamo.render + +import org.umamo.format.png.PngCodec +import org.umamo.runtime.model.AtlasTileId +import kotlin.concurrent.Volatile + +/** + * A document's source-art pixels, decoded on demand and keyed by atlas tile. + * + * Pixels only. Which tiles exist, how big they are, and where each one packs are model state + * (`PuppetModel.atlas`), because a repack authors them; this holds the one thing a model must not, + * since a raster in the model would ride along in every undo snapshot. + * + * Nothing is decoded until it is asked for: a CMO3 document loads synchronously on the UI thread, so + * decoding every tile up front would stall the open by seconds on a real model. A decoded tile is + * retained for the store's life, which is the document's life - a replaced document drops the store. + * + * Format-agnostic by construction: the decoder is injected. A CMO3 document supplies one over its + * retained graph's PNG bytes ([fromPng]); an artwork-origin document, whose reader already decoded + * every layer, supplies one over those rasters directly. + * + * @property Function decode Yields a tile's decoded pixels, or null when it has none or they will not + * decode. Called from any thread, possibly several at once, so it must share nothing mutable - and + * it must return the SAME instance for the same tile on every call when it can, because the + * renderer's texture cache and the viewport's freshness test compare decoded images by identity. + */ +class SourceArtRasters( + private val decode: (AtlasTileId) -> DecodedImage?, +) { + // A null value is a remembered failure (no bytes, or bytes that will not decode), which is why this + // is not a getOrPut - getOrPut treats a stored null as absent and would retry the decode every time. + private val decodedByTile = HashMap() + + // Rasters added after the store was built - artwork brought into an open document, the replacement + // tiles a reload mints - read before the injected decoder. An immutable map swapped whole behind a + // volatile reference, so the off-thread repack decode sees a complete map or the previous one, + // never a half-written one. + @Volatile + private var added: Map = emptyMap() + + /** + * Adds already-decoded rasters for tiles the injected decoder knows nothing about - the layers of + * an artwork file added to the document after it opened, and the replacement tiles a reload, + * relink, or match mints over new art. Document-lifetime like the rest of the store: an added + * raster stays even if the edit that brought it is undone, which is harmless since its tile is then + * gone from the model. Re-adding a tile replaces its raster. + * + * @param Map rasters The decoded pixels by tile. + */ + fun addDecoded(rasters: Map) { + if (rasters.isEmpty()) { + return + } + added = added + rasters + } + + /** + * A tile's pixels, decoding them on first request and caching the result (failures included). + * + * A raster added through [addDecoded] wins over the cache: a reload's replacement id (`~`) + * is minted past the ids the model holds NOW, so reload, undo, reload mints the same id twice with + * different pixels, and a cache entry taken between the two would otherwise stand in for the second. + * Both twins then hand out the added instance, which is what the identity comparisons need. + * + * CALLER-CONFINED: the cache is a plain map with no synchronization, so every call must come from + * the same thread (today, the UI thread). A second caller would not merely race the map - it could + * hand out a SECOND decoded instance for one tile, and both the renderer's texture cache and the + * viewport's freshness test compare decoded images by identity. Anything off that thread uses + * [decodeRaster] instead, which shares nothing. + * + * @param AtlasTileId tileId The tile to read. + * @return DecodedImage? The decoded raster, or null when the tile has no usable pixels. + */ + fun rasterFor(tileId: AtlasTileId): DecodedImage? { + added[tileId]?.let { raster -> return raster } + if (decodedByTile.containsKey(tileId)) { + return decodedByTile[tileId] + } + // The cached twin decodes through the uncached one: the two must produce the same image for the + // same bytes, because callers compare a cached result against a freshly decoded one by identity. + val decoded = decodeRaster(tileId) + decodedByTile[tileId] = decoded + return decoded + } + + /** + * A tile's pixels, decoded fresh and cached nowhere - safe to call from any thread, including + * several at once. + * + * The uncached twin of [rasterFor], for callers that own their own result: the injected decoder + * shares nothing mutable, so nothing here is shared. Costs a repeat decode when a tile is already + * cached (for a store over encoded bytes), which is the price of not sharing a cache across threads. + * + * @param AtlasTileId tileId The tile to read. + * @return DecodedImage? The decoded raster, or null when the tile has no usable pixels. + */ + fun decodeRaster(tileId: AtlasTileId): DecodedImage? = added[tileId] ?: decode(tileId) + + companion object { + /** + * A store over encoded PNG bytes - the CMO3 case, where every tile's pixels sit in the retained + * graph as an embedded PNG and decoding is deferred to first request. + * + * @param Function readBytes Yields a tile's PNG bytes, or null when it has none. + * @return SourceArtRasters The store; bytes that will not decode read as no raster. + */ + fun fromPng(readBytes: (AtlasTileId) -> ByteArray?): SourceArtRasters = + SourceArtRasters { tileId -> + readBytes(tileId)?.let { bytes -> + try { + val image = PngCodec.read(bytes) + DecodedImage(image.rgba, image.width, image.height) + } catch (_: Exception) { + null + } + } + } + } +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/SupersampledSurface.kt b/module/render/src/commonMain/kotlin/org/umamo/render/SupersampledSurface.kt new file mode 100644 index 0000000..623c9e0 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/SupersampledSurface.kt @@ -0,0 +1,125 @@ +package org.umamo.render + +import org.umamo.render.device.RenderDevice +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import kotlin.math.max + +/** + * The viewport's offscreen surface pair: a supersampled draw target the renderer draws into, and a + * display-size resolve target the draw is box-downscaled into for read-back. + * + * Backend-neutral - both targets and the resolve come from the [device], so every backend's viewport + * host shares this class instead of re-owning two framebuffers apiece. The draw target is write-only + * (`sampled = false`, a renderbuffer on GL); the resolve target is sampled so it can be read back. + * + * Allocation is GROW-ONLY: the targets are kept at a per-axis high-water capacity and each render + * uses only its bottom-left (render-origin) used region, resolved and read back at the used size. + * A gutter drag resizes the viewport every frame, and one surface is shared by every area, so + * differently-sized areas alternate sizes render-to-render - a recreate-on-any-change policy paid a + * framebuffer destroy + create per frame in both cases. The cost is that the session retains the + * high-water allocation (a 2x draw target at 4K is about 130 MB). + * + * All calls run on the render thread with the device's context current; this class never crosses + * threads. + * + * @property RenderDevice device The backend the targets live on. + * @property Int scale The maximum framebuffer pixels per display pixel (the full + * supersample factor). It bounds ensure's activeScale; capacity itself follows the high-water of + * the pixel sizes actually requested, so a session that never renders above 1x never pays a 2x + * allocation, and the first higher-scale render grows the targets once. + * + * @note Shrink-on-idle (trimming the high-water allocation after a quiet period) is the named + * future refinement if the retained memory ever matters in practice. + */ +class SupersampledSurface( + private val device: RenderDevice, + val scale: Int, +) { + private var draw: RenderTarget? = null + private var resolve: RenderTarget? = null + private var drawCapacityWidth = 0 + private var drawCapacityHeight = 0 + private var resolveCapacityWidth = 0 + private var resolveCapacityHeight = 0 + + /** The display-pixel width of the most recent [ensure] - the used extent of both targets. */ + var usedWidth: Int = 0 + private set + + /** The display-pixel height of the most recent [ensure] - the used extent of both targets. */ + var usedHeight: Int = 0 + private set + + /** The supersample factor of the most recent [ensure] (1 up to [scale]). */ + var usedScale: Int = scale + private set + + /** The supersampled draw target (capacity-sized; render its used region). Call [ensure] first. */ + val drawTarget: RenderTarget + get() = draw ?: error("ensure(width, height) before drawTarget") + + /** The resolve target the read-back reads (capacity-sized; used region only). Call [ensure] first. */ + val resolveTarget: RenderTarget + get() = resolve ?: error("ensure(width, height) before resolveTarget") + + /** + * Ensures both targets can hold a [width] x [height] render (the draw target at [activeScale] x), + * growing a target only when a requested axis exceeds its capacity, and returns the draw target. + * Always records the used size and scale; a smaller or equal request never reallocates. + * + * @param Int width The display width in pixels. + * @param Int height The display height in pixels. + * @param Int activeScale The supersample factor for this render (defaults to the full [scale]). + * @return RenderTarget The supersampled draw target. + */ + fun ensure(width: Int, height: Int, activeScale: Int = scale): RenderTarget { + require(width > 0 && height > 0) { "surface size must be positive, got ${width}x$height" } + require(activeScale in 1..scale) { "activeScale must be in 1..$scale, got $activeScale" } + val drawWidth = width * activeScale + val drawHeight = height * activeScale + if (drawWidth > drawCapacityWidth || drawHeight > drawCapacityHeight) { + draw?.let { existing -> device.destroyRenderTarget(existing) } + drawCapacityWidth = max(drawWidth, drawCapacityWidth) + drawCapacityHeight = max(drawHeight, drawCapacityHeight) + draw = + device.createRenderTarget( + RenderTargetSpec(drawCapacityWidth, drawCapacityHeight, TextureFormat.Rgba8, sampled = false), + ) + } + if (width > resolveCapacityWidth || height > resolveCapacityHeight) { + resolve?.let { existing -> device.destroyRenderTarget(existing) } + resolveCapacityWidth = max(width, resolveCapacityWidth) + resolveCapacityHeight = max(height, resolveCapacityHeight) + resolve = + device.createRenderTarget( + RenderTargetSpec(resolveCapacityWidth, resolveCapacityHeight, TextureFormat.Rgba8, sampled = true), + ) + } + usedWidth = width + usedHeight = height + usedScale = activeScale + return drawTarget + } + + /** Box-downscales the draw target's used region into the resolve target's used region. */ + fun resolve() { + device.resolveUsed(drawTarget, usedWidth * usedScale, usedHeight * usedScale, resolveTarget, usedWidth, usedHeight) + } + + /** Frees both targets and resets the capacities. Safe to call before the first [ensure] and idempotent. */ + fun dispose() { + draw?.let { device.destroyRenderTarget(it) } + resolve?.let { device.destroyRenderTarget(it) } + draw = null + resolve = null + drawCapacityWidth = 0 + drawCapacityHeight = 0 + resolveCapacityWidth = 0 + resolveCapacityHeight = 0 + usedWidth = 0 + usedHeight = 0 + usedScale = scale + } +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/ViewportCamera.kt b/module/render/src/commonMain/kotlin/org/umamo/render/ViewportCamera.kt new file mode 100644 index 0000000..edb6975 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/ViewportCamera.kt @@ -0,0 +1,183 @@ +package org.umamo.render + +import kotlin.math.roundToInt + +/** + * The visible content extent in world space (the renderer's post-deform, Y-up pixel space). It frames + * the model for an initial fit; width and height are clamped by the producer to at least 1 so a + * degenerate model never divides by zero downstream. + * + * 内容の存在範囲(ワールド空間、ピクセル単位)。モデルの初期フレーミングに使う。 + * + * @property Float minX Left edge in world units. + * @property Float minY Bottom edge in world units. + * @property Float width Extent along X in world units. + * @property Float height Extent along Y in world units. + */ +data class ContentBounds(val minX: Float, val minY: Float, val width: Float, val height: Float) + +/** + * A 2D viewport camera over the puppet's world space: an orthographic pan/zoom, no rotation. The model + * renders 1:1 (one world unit = one model pixel = one screen pixel) at [zoom] == 1. Deformation never + * reframes the view - the camera is set once (fit on open) and thereafter moved only by the user. + * + * Every edit helper is PURE - it returns a new camera and touches no GL - so the navigation maths + * unit-tests without a context, the same discipline as the workspace splitter's pure ratio function. + * The render backend consumes only [worldToNdc]. + * + * Coordinate conventions: screen pixels measure +x right, +y DOWN from the top-left; world space is + * +y UP (the deform shader flips Cubism's native +y-down before projection). The screen-to-world maths + * below therefore carries the Y sign explicitly. + * + * 2D ビューポートカメラ(平行投影のパン/ズーム、回転なし)。zoom==1 で 1 ワールド単位=1 画面ピクセル。 + * 編集ヘルパは全て純粋関数(新しいカメラを返し GL に触れない)なので、操作の数学を文脈なしでテストできる。 + * + * @property Float centerX World X shown at the viewport center. + * @property Float centerY World Y shown at the viewport center. + * @property Float zoom Screen pixels per world unit (1 == true 1:1). + */ +data class ViewportCamera(val centerX: Float, val centerY: Float, val zoom: Float) { + /** + * Builds the affine world-to-NDC parameters the vertex shader applies as + * `ndc = world * (scaleX, scaleY) + (transformX, transformY)`. A world point at the camera center + * maps to NDC origin (the viewport center); a point one unit to the right maps [zoom] pixels right. + * + * @param Int viewportWidth Target width in pixels. + * @param Int viewportHeight Target height in pixels. + * @return FloatArray [scaleX, scaleY, transformX, transformY]. + */ + fun worldToNdc(viewportWidth: Int, viewportHeight: Int): FloatArray { + val scaleX = 2f * zoom / viewportWidth + val scaleY = 2f * zoom / viewportHeight + return floatArrayOf(scaleX, scaleY, -centerX * scaleX, -centerY * scaleY) + } + + /** + * Pans by a screen-pixel drag delta in grab style - the world point under the pointer stays under + * the pointer. Y carries the screen-down vs world-up sign flip. + * + * @param Float deltaXpx Horizontal drag in pixels (+ right). + * @param Float deltaYpx Vertical drag in pixels (+ down). + * @return ViewportCamera The panned camera. + */ + fun panByScreen(deltaXpx: Float, deltaYpx: Float): ViewportCamera = + copy(centerX = centerX - deltaXpx / zoom, centerY = centerY + deltaYpx / zoom) + + /** + * Cursor-anchored zoom by [deltaPercent] percentage points (the wheel zoom): the world point under + * the cursor stays pinned to that same pixel, and the result snaps to the [stepPercent] grid so clean + * values (… 100%, 50%, 25% …) are reachable instead of drifting off the fit-derived ratio. The recenter + * uses the snapped, clamped zoom so the pin holds exactly even at the limits. + * + * @param Float deltaPercent Percentage points to add (negative zooms out). + * @param Float stepPercent The grid the result snaps to (e.g. 1 or 5). + * @param Float cursorXpx Cursor X in pixels from the left. + * @param Float cursorYpx Cursor Y in pixels from the top. + * @param Int viewportWidth Viewport width in pixels. + * @param Int viewportHeight Viewport height in pixels. + * @return ViewportCamera The zoomed camera. + */ + fun zoomAtCursorByPercent(deltaPercent: Float, stepPercent: Float, cursorXpx: Float, cursorYpx: Float, viewportWidth: Int, viewportHeight: Int): ViewportCamera { + val newZoom = snappedZoom(deltaPercent, stepPercent) + val halfWidth = viewportWidth / 2f + val halfHeight = viewportHeight / 2f + val worldX = centerX + (cursorXpx - halfWidth) / zoom + val worldZ = centerY + (halfHeight - cursorYpx) / zoom + return ViewportCamera( + worldX - (cursorXpx - halfWidth) / newZoom, + worldZ - (halfHeight - cursorYpx) / newZoom, + newZoom, + ) + } + + /** + * Centerd zoom by [deltaPercent] percentage points (the keyboard zoom-in/out), snapping to the + * [stepPercent] grid and leaving the centerd world point fixed. + * + * @param Float deltaPercent Percentage points to add (negative zooms out). + * @param Float stepPercent The grid the result snaps to. + * @return ViewportCamera The zoomed camera. + */ + fun zoomedByPercent(deltaPercent: Float, stepPercent: Float): ViewportCamera = copy(zoom = snappedZoom(deltaPercent, stepPercent)) + + /** + * The zoom scale after adding [deltaPercent] points to the current zoom-percentage and snapping to the + * [stepPercent] grid, clamped to the limits. Snapping to the grid is what makes round percentages + * land exactly: from a 41.3% fit, +1%-steps pass through 42, 43, … 100, and +5%-steps through 45, 50, … + * + * @param Float deltaPercent Percentage points to add. + * @param Float stepPercent The grid to snap to. + * @return Float The new zoom scale (screen px per world unit). + */ + private fun snappedZoom(deltaPercent: Float, stepPercent: Float): Float { + val targetPercent = zoom * 100f + deltaPercent + val snappedPercent = (targetPercent / stepPercent).roundToInt() * stepPercent + return (snappedPercent / 100f).coerceIn(MIN_ZOOM, MAX_ZOOM) + } + + /** + * Returns the camera at true 1:1 (zoom 1) about the current center - the "actual size" / 100% view. + * + * @return ViewportCamera The 1:1 camera. + */ + fun withActualSize(): ViewportCamera = copy(zoom = 1f) + + /** + * Frames a screen-pixel rectangle (Blender's Zoom Region / Shift+B): the dragged box fills the viewport, + * centerd on the box center. The two corners may be given in any order. The scale uses min() so the + * WHOLE box fits inside the viewport (letterboxed on the looser axis) rather than cropping it; a degenerate + * (zero-area) box is guarded by a one-pixel floor, and the zoom is clamped to the limits so a tiny box + * cannot explode past MAX_ZOOM. Pure, so the framing maths unit-tests without a context. + * + * @param Float leftPx One horizontal box edge in screen pixels. + * @param Float topPx One vertical box edge in screen pixels. + * @param Float rightPx The other horizontal box edge in screen pixels. + * @param Float bottomPx The other vertical box edge in screen pixels. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return ViewportCamera The camera framing the box. + */ + fun framingScreenRect(leftPx: Float, topPx: Float, rightPx: Float, bottomPx: Float, viewportWidth: Int, viewportHeight: Int): ViewportCamera { + val minX = minOf(leftPx, rightPx) + val maxX = maxOf(leftPx, rightPx) + val minY = minOf(topPx, bottomPx) + val maxY = maxOf(topPx, bottomPx) + val rectWidth = (maxX - minX).coerceAtLeast(1f) + val rectHeight = (maxY - minY).coerceAtLeast(1f) + // min() so the whole box fits inside the viewport (letterboxed on the looser axis), never cropped. + val fitScale = minOf(viewportWidth / rectWidth, viewportHeight / rectHeight) + val newZoom = (zoom * fitScale).coerceIn(MIN_ZOOM, MAX_ZOOM) + val rectCenterXpx = (minX + maxX) / 2f + val rectCenterYpx = (minY + maxY) / 2f + // Unproject the box center through the CURRENT camera (screen->world; Y flips), the inverse of the + // same affine worldToNdc applies, so the box center lands at the viewport center under the new camera. + val worldCenterX = centerX + (rectCenterXpx - viewportWidth / 2f) / zoom + val worldCenterZ = centerY + (viewportHeight / 2f - rectCenterYpx) / zoom + return ViewportCamera(worldCenterX, worldCenterZ, newZoom) + } + + companion object { + /** Hard zoom floor / ceiling, so a stray wheel spin can't lose or explode the model. */ + const val MIN_ZOOM: Float = 0.02f + const val MAX_ZOOM: Float = 64f + + /** Fraction of the viewport a fit leaves the content occupying, so it isn't edge-to-edge. */ + const val FIT_MARGIN: Float = 0.9f + + /** + * Frames [content] centerd in the viewport with a small margin - the default view on open and the + * target of the Fit command. + * + * @param ContentBounds content The extent to frame. + * @param Int viewportWidth Viewport width in pixels. + * @param Int viewportHeight Viewport height in pixels. + * @return ViewportCamera The fitted camera. + */ + fun fit(content: ContentBounds, viewportWidth: Int, viewportHeight: Int): ViewportCamera { + val zoom = + (FIT_MARGIN * minOf(viewportWidth.toFloat() / content.width, viewportHeight.toFloat() / content.height)) + .coerceIn(MIN_ZOOM, MAX_ZOOM) + return ViewportCamera(content.minX + content.width / 2f, content.minY + content.height / 2f, zoom) + } + } +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/device/DrawUniforms.kt b/module/render/src/commonMain/kotlin/org/umamo/render/device/DrawUniforms.kt new file mode 100644 index 0000000..fd6ad5f --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/device/DrawUniforms.kt @@ -0,0 +1,214 @@ +package org.umamo.render.device + +import org.umamo.render.GridColors +import org.umamo.render.glsl.MAX_BLEND_CORNERS +import org.umamo.render.glsl.MAX_CORNERS + +// The per-draw and per-pass shader inputs, as structs rather than named scalars. +// +// The renderer names no uniform. Each backend hand-writes one marshaller per struct: the GL family caches +// the locations once at pipeline creation and issues glUniform*; a Metal backend would write a mirroring +// MSL struct and setVertexBytes it. Deliberately NOT reflection-driven - kotlin-reflect does not exist on +// Kotlin/Native - and deliberately not a writeTo(sink), which would force this shared code to commit to a +// memory layout when std140 and MSL alignment disagree. commonMain supplies VALUES; layout is the +// backend's. That split is the cleanest line in the design. + +/** The camera's world→NDC affine: `ndc = world * (scaleX, scaleY) + (offsetX, offsetY)`. */ +public data class WorldToNdc(val scaleX: Float, val scaleY: Float, val offsetX: Float, val offsetY: Float) + +/** + * One drawable's per-pose deform inputs: the active morph corners and the baked parent transform. + * + * MUTABLE AND REUSED. The renderer refills one instance per draw rather than allocating ~60 of these a + * frame. A device implementation MUST therefore marshal every field before returning and MUST NOT retain + * the instance. Both `glUniform*` and Metal's `setVertexBytes` copy, so both can honor that; a backend + * that wanted to record and replay a command buffer could not, and would need its own copy. + * + * Getting this wrong renders garbage that looks exactly like a driver bug, which is why it is stated here + * rather than left to be discovered. + * + * @property Int cornerCount Active corners, 0..MAX_CORNERS. + * @property IntArray cornerCell Each active corner's keyform cell linear index; length MAX_CORNERS. + * @property FloatArray cornerWeight Each active corner's blend weight; length MAX_CORNERS. + * @property Int parentType 0 = direct, 1 = rotation, 2 = warp. + * @property FloatArray rotation The rotation affine (c12,c13,c14,c15,ox,oy); read when parentType==1. + * @property Int warpColumns Warp lattice columns; read when parentType==2. + * @property Int warpRows Warp lattice rows; read when parentType==2. + * @property Boolean warpBilinear Bilinear vs triangle blend; read when parentType==2. + */ +public class DeformUniforms { + var cornerCount: Int = 0 + val cornerCell: IntArray = IntArray(MAX_CORNERS) + val cornerWeight: FloatArray = FloatArray(MAX_CORNERS) + + // Blend-shape delta columns (appended after the grid cells in the delta texture); zero-blend + // drawables keep blendCount == 0 so the shader loop never runs. + var blendCount: Int = 0 + val blendCell: IntArray = IntArray(MAX_BLEND_CORNERS) + val blendWeight: FloatArray = FloatArray(MAX_BLEND_CORNERS) + var parentType: Int = 0 + val rotation: FloatArray = FloatArray(6) + var warpColumns: Int = 0 + var warpRows: Int = 0 + var warpBilinear: Boolean = false +} + +/** + * One draw's fragment inputs, shared by the puppet and atlas-page pipelines. + * + * Mutable and reused on the same contract as [DeformUniforms]. + * + * @property Boolean useTexture Sample [DrawTextures.atlas] rather than the flat color below. + * @property Float colorRed Flat color red, used when [useTexture] is false. + * @property Float colorGreen Flat color green, used when [useTexture] is false. + * @property Float colorBlue Flat color blue, used when [useTexture] is false. + * @property Float colorAlpha Flat color alpha, used when [useTexture] is false. + * @property Float opacity The pose-blended opacity, multiplied into alpha. + * @property Boolean useMask Multiply alpha by the mask coverage. + * @property Boolean invertMask Use 1 - coverage instead. + * @property Float multiplyRed Per-drawable multiply-color red (identity 1), applied before premultiply. + * @property Float multiplyGreen Per-drawable multiply-color green (identity 1). + * @property Float multiplyBlue Per-drawable multiply-color blue (identity 1). + * @property Float screenRed Per-drawable screen-color red (identity 0). + * @property Float screenGreen Per-drawable screen-color green (identity 0). + * @property Float screenBlue Per-drawable screen-color blue (identity 0). + * @property Float highlight How far to tint toward the highlight color (0 = untinted). + * @property Float highlightRed Highlight tint red. + * @property Float highlightGreen Highlight tint green. + * @property Float highlightBlue Highlight tint blue. + * @property FloatArray uvAffine The 2x3 row-major affine (m00, m01, m02, m10, m11, m12) applied to the + * interpolated texture coordinate before sampling. Identity leaves the stored mapping alone; a + * drawable sampling its SOURCE ARTWORK instead of the packed atlas carries the transform between + * those two frames here, so the same stored coordinates address either image. Rides on the fragment + * uniforms deliberately: the glue draw path marshals only these, so a vertex-stage home would + * silently miss glue meshes. + */ +public class FragmentUniforms { + var useTexture: Boolean = false + var colorRed: Float = 0f + var colorGreen: Float = 0f + var colorBlue: Float = 0f + var colorAlpha: Float = 0f + var opacity: Float = 1f + var useMask: Boolean = false + var invertMask: Boolean = false + var multiplyRed: Float = 1f + var multiplyGreen: Float = 1f + var multiplyBlue: Float = 1f + var screenRed: Float = 0f + var screenGreen: Float = 0f + var screenBlue: Float = 0f + var highlight: Float = 0f + var highlightRed: Float = 0f + var highlightGreen: Float = 0f + var highlightBlue: Float = 0f + + // Six floats reused in place, like every other value here - see the class contract. Identity, NOT + // zeroes: a zeroed affine collapses every coordinate onto one texel. + val uvAffine: FloatArray = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f) +} + +/** + * The textures one draw samples. Null means the draw does not use that slot. + * + * Mutable and reused per draw on the same contract as [DeformUniforms] - the renderer refills one instance + * rather than allocating a bundle per drawable per frame; the device must read the fields before returning + * and must not retain the instance (binding a texture reads its handle synchronously, so both backends can). + * + * @property GpuTexture? atlas The art texture the draw samples - the packed atlas page, or the + * drawable's source artwork when the puppet displays from that - or null to draw the flat color. + * @property GpuTexture? maskCoverage The clip mask's coverage, or null when unmasked. + * @property GpuTexture? deltaTexture The mesh's morph delta table (deform draws only). + * @property GpuTexture? warpControlPoints The parent warp's baked control points, or null when the parent + * is not a warp. + */ +public class DrawTextures { + public var atlas: GpuTexture? = null + public var maskCoverage: GpuTexture? = null + public var deltaTexture: GpuTexture? = null + public var warpControlPoints: GpuTexture? = null + + /** The rendered layer a [composite draw][CompositeUniforms] blends in. */ + public var compositeLayer: GpuTexture? = null + + /** The destination snapshot the composite blends against (a copy of the target so far). */ + public var destinationSnapshot: GpuTexture? = null +} + +/** + * One composite draw's inputs: which color/alpha blend to compute in-shader, the composite's + * pose-blended channels, and its optional clip-mask sampling. + * + * Mutable and reused on the same contract as [DeformUniforms]. The mode ints are the MOC3 packed + * encodings' halves (colorMode 0-17, alphaMode 0-4 - see BlendModeMapping); the composite shader + * switches on them, and the pure reference `compositeReference` documents the exact math. + * + * @property Int colorMode The color blend mode int (0-17). + * @property Int alphaMode The alpha blend mode int (0-4). + * @property Float opacity The composite opacity (0..1), applied to the layer before blending. + * @property Float multiplyRed Multiply color red (identity 1). + * @property Float multiplyGreen Multiply color green (identity 1). + * @property Float multiplyBlue Multiply color blue (identity 1). + * @property Float screenRed Screen color red (identity 0). + * @property Float screenGreen Screen color green (identity 0). + * @property Float screenBlue Screen color blue (identity 0). + * @property Boolean useMask Multiply the layer's alpha by the mask coverage. + * @property Boolean invertMask Use 1 - coverage instead. + */ +public class CompositeUniforms { + public var colorMode: Int = 0 + public var alphaMode: Int = 0 + public var opacity: Float = 1f + public var multiplyRed: Float = 1f + public var multiplyGreen: Float = 1f + public var multiplyBlue: Float = 1f + public var screenRed: Float = 0f + public var screenGreen: Float = 0f + public var screenBlue: Float = 0f + public var useMask: Boolean = false + public var invertMask: Boolean = false +} + +/** + * The grid backdrop's inputs for one pass. + * + * @property WorldToNdc worldToNdc The affine the fragment inverts to recover its world position. + * @property Int viewportWidth The framebuffer width, for the fragment's screen-to-world math. + * @property Int viewportHeight The framebuffer height. + * @property Float originX World x the lattice is anchored on (a major line crosses it). + * @property Float originY World y the lattice is anchored on. + * @property Float majorSpacingX Major line spacing along X, in world units. + * @property Float majorSpacingY Major line spacing along Y, in world units. + * @property Int subdivisions Minor lines per major cell. + * @property Float lineWidthPx Line half-width in framebuffer pixels (accounts for supersampling). + * @property GridColors colors The background / major / minor colors. + */ +public data class GridUniforms( + val worldToNdc: WorldToNdc, + val viewportWidth: Int, + val viewportHeight: Int, + val originX: Float, + val originY: Float, + val majorSpacingX: Float, + val majorSpacingY: Float, + val subdivisions: Int, + val lineWidthPx: Float, + val colors: GridColors, +) + +/** + * One axis line's inputs. + * + * @property Float linePositionNdc The line's fixed coordinate, in NDC. + * @property Boolean vertical True for the vertical axis, false for the horizontal one. + * @property Float red Line red. + * @property Float green Line green. + * @property Float blue Line blue. + */ +public data class AxisLineUniforms( + val linePositionNdc: Float, + val vertical: Boolean, + val red: Float, + val green: Float, + val blue: Float, +) \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/device/GpuResources.kt b/module/render/src/commonMain/kotlin/org/umamo/render/device/GpuResources.kt new file mode 100644 index 0000000..19051e2 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/device/GpuResources.kt @@ -0,0 +1,190 @@ +package org.umamo.render.device + +import org.umamo.render.puppet.GlueVertexAttributes + +// The device's opaque handles and the specs used to create them. +// +// Handles are interfaces with no members on purpose: a caller can hold one and hand it back, and can do +// nothing else with it. The concrete type is backend state - a GL name, an MTLBuffer - and keeping it +// unreachable is what stops backend concepts leaking into the shared renderer. + +/** A texture the device owns, sampleable from a shader. */ +public interface GpuTexture + +/** + * One mesh's vertex + index residency: rest positions, UVs, indices, and - for a glue mesh - the + * per-vertex weld attributes. Whatever the backend needs to issue one indexed draw of it. + */ +public interface GpuMesh + +/** A compiled, immutable draw pipeline: shader stages, blend, and attribute layout, fixed at creation. */ +public interface RenderPipeline + +/** A compiled pipeline that evaluates the deform per vertex and writes positions, drawing nothing. */ +public interface DeformCapturePipeline + +/** + * A surface a pass renders into. + * + * Never implicitly current: every pass names the target it writes. The renderer used to discover its own + * target by reading the bound framebuffer out of ambient GL state, which worked only because the caller + * happened to have bound it first - a coupling that was invisible at both ends. + */ +public interface RenderTarget { + /** This target's contents as a sampleable texture, or null when created with `sampled = false`. */ + val sampledTexture: GpuTexture? +} + +/** + * The shared store of pass-1 deformed world positions, addressed by GLOBAL vertex index across every + * glue-involved mesh (see `org.umamo.render.puppet.planGlueLayout`). + * + * How the GPU actually holds it is the backend's business - a texture buffer on desktop GL today, and a + * 2D texture once the GLES 3.0 path lands, since texture buffers are 3.2 there. The renderer only ever + * says "the store", which is why that change does not reach it. + */ +public interface DeformedPositionStore + +/** A texture/target pixel format. Only the two the renderer actually uses. */ +public enum class TextureFormat { + /** 8-bit RGBA: atlases, mask coverage, and any target read back to the host. */ + Rgba8, + + /** 32-bit float RG: per-vertex morph deltas, warp control points, deformed positions. */ + Rg32F, +} + +/** How a texture's texels are filtered between sample points. */ +public enum class TextureFilter { + /** No interpolation. Correct for data textures, where a blend between texels is meaningless. */ + Nearest, + + /** Bilinear. Correct for art. */ + Linear, +} + +/** What a texture yields for a coordinate outside [0, 1]. */ +public enum class TextureWrap { + /** Repeats the nearest edge texel outward. Correct for an atlas page, whose art never reaches its border. */ + ClampToEdge, + + /** + * Yields transparent black outside the image. Correct for art sampled in its OWN frame, which a mesh + * routinely overhangs: an art mesh rings outside the opaque region and authored meshes extend further + * still for deformation coverage, so a drawable's coordinates run past its layer image by tens to + * hundreds of pixels. Clamping to the edge would repeat the border row or column across that overhang + * as a streak; transparent black reproduces what the packed atlas showed there, which is its padding. + * Atlas pages take it too: a document's page can be a single model image, with no padding at all. + * + * @note GL_CLAMP_TO_BORDER with a zero border color on the GL family (core in GL 3.3 and GLES 3.2), + * MTLSamplerAddressMode.clampToZero on Metal. + */ + ClampToTransparentBorder, +} + +/** + * Which draw a pipeline performs. + * + * The device is asked for a pipeline by PURPOSE, never by shader source, so each backend owns its own + * shader library: the GL family reads `org.umamo.render.glsl`, and a Metal backend would supply MSL from + * a precompiled library. A `source(purpose, stage): String` seam was considered and rejected for + * assuming source text exists at runtime, which is false for a `.metallib`. + * + * Closed on purpose: adding a pipeline forces every backend to answer for it rather than silently + * lacking one. + */ +public enum class PipelinePurpose { + /** A non-glue art mesh: deform in the vertex stage, project, sample the atlas. */ + PuppetDeformDraw, + + /** A glue art mesh: read pass-1 own/partner positions, weld, project, sample the atlas. */ + PuppetGlueDraw, + + /** The UV editor's flat atlas-page underlay quad (attribute-less; corners from the vertex index). */ + AtlasPageDraw, + + /** The world-aligned grid backdrop (attribute-less full-screen triangle). */ + GridBackdrop, + + /** One world-origin axis line (attribute-less; two endpoints from the vertex index). */ + WorldAxisLine, + + /** + * The layer composite: an attribute-less full-screen triangle whose fragment blends a + * rendered layer against a destination snapshot in-shader (the 18 color x 5 alpha modes are not + * fixed-function-expressible), writing with blending DISABLED. Pair with [PipelineBlend.Opaque]. + */ + Composite, +} + +/** + * How a pipeline's fragments combine with the target. + * + * Semantic rather than factor-level: only these four combinations exist, they are model concepts, and a + * 15-factor x 4-slot surface would be API nobody uses that every backend would still have to map. An + * exhaustive `when` over four values also means adding a mode cannot be forgotten in a backend. + * + * [Opaque] is not one of `org.umamo.runtime.model.BlendMode`'s three - it is the backdrop's + * blending-disabled write, which is why this is its own enum rather than a reuse of that one. + */ +public enum class PipelineBlend { + /** Blending off: the fragment replaces the target. The grid and axis backdrop. */ + Opaque, + + /** Premultiplied source-over. The default for art. */ + Normal, + + /** Additive. Glows and highlights. */ + Additive, + + /** Multiply. Shadows and shading. */ + Multiply, +} + +/** + * The immutable description of a draw pipeline. Created once at init and reused every frame. + * + * @property PipelinePurpose purpose Which draw this pipeline performs. + * @property PipelineBlend blend How its fragments combine with the target. + * @property Boolean cullBackFaces Whether back faces are culled (the Cubism drawable + * Culling toggle); false = double-sided, the default. Part of the spec (not a draw parameter) + * so the state is bound with the pipeline, like blend. + */ +public data class RenderPipelineSpec( + val purpose: PipelinePurpose, + val blend: PipelineBlend, + val cullBackFaces: Boolean = false, +) + +/** + * A render target to allocate. + * + * @property Int width Width in pixels. + * @property Int height Height in pixels. + * @property TextureFormat format The pixel format. + * @property Boolean sampled Whether a later pass samples this target as a texture. False lets a + * backend pick a write-only surface - the GL device allocates a renderbuffer rather than a texture, + * which cannot be read back directly but is otherwise cheaper. + */ +public data class RenderTargetSpec( + val width: Int, + val height: Int, + val format: TextureFormat, + val sampled: Boolean, +) + +/** + * A mesh's static residency to upload. + * + * @property FloatArray restPositions Rest positions, interleaved x,y. + * @property FloatArray uvs Atlas UVs, interleaved u,v. + * @property IntArray indices Triangle indices. EMPTY IS LEGAL: a zero-triangle glue + * anchor draws nothing and exists only so its deformed positions can be a weld partner. + * @property GlueVertexAttributes? glueAttributes Per-vertex weld attributes, or null for a non-glue mesh. + */ +public class MeshSpec( + val restPositions: FloatArray, + val uvs: FloatArray, + val indices: IntArray, + val glueAttributes: GlueVertexAttributes?, +) \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/device/RenderDevice.kt b/module/render/src/commonMain/kotlin/org/umamo/render/device/RenderDevice.kt new file mode 100644 index 0000000..df7bfcd --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/device/RenderDevice.kt @@ -0,0 +1,556 @@ +package org.umamo.render.device + +import org.umamo.format.raster.RasterImage + +/** + * The GPU backend seam: one implementation per graphics API. + * + * Everything above it - the puppet renderer, the deform eval, the pose resolution, the model diff - is + * backend-neutral. Desktop OpenGL 3.3 core is implemented; Android GLES 3.0 is a near-transliteration of + * it (the two differ in binding style, not semantics); iPadOS Metal is a later port. + * + * Shaped for the GL family first, deliberately. Where avoiding a GL-ism costs nothing it is avoided - + * passes name their target, pipelines are immutable, uniforms are structs - because those read better + * regardless. Where pre-solving Metal would cost real complexity for a backend that does not exist yet, + * it is not done; that bill is paid if and when Metal asks for it. + * + * A device is created by the host, which owns whatever context or queue the backend needs, and is used + * from ONE thread only - the render thread. + * + * Two kinds of work sit on this interface. Drawing is RECORDED into a frame: [beginFrame] hands out a + * [FrameEncoder] whose passes must all be begun and ended within one begin/end. The remaining + * operations - [resolve], [beginReadback] / [pollReadback], [readPixels], and every resource create / + * destroy - are SELF-CONTAINED: each is a complete unit of work on its own, called outside any frame, and + * a backend that records into command buffers (Metal) is free to open and commit its own buffer internally + * to service one. They are not part of a FrameEncoder because they do not compose with a pass - a resolve + * runs between a render frame and its read-back, and a read-back is polled across many later frames. + * + * GPU バックエンドの継ぎ目。GL / GLES / Metal ごとに実装する。描画はフレームに記録し、resolve / 読み戻し / + * リソース操作はフレーム外の自己完結操作。 + */ +public interface RenderDevice { + // --- Resources. Everything the device hands out, the device frees. --- + + /** + * Uploads an image as a sampleable texture. + * + * @param Int width Width in pixels. + * @param Int height Height in pixels. + * @param TextureFormat format The pixel format. + * @param TextureFilter filter How texels are filtered between sample points. + * @param ByteArray? pixels RGBA8888, top row first; null allocates without uploading. + * @param TextureWrap wrap What a coordinate outside [0, 1] yields. + * @return GpuTexture The texture. + */ + fun createTexture( + width: Int, + height: Int, + format: TextureFormat, + filter: TextureFilter, + pixels: ByteArray?, + wrap: TextureWrap = TextureWrap.ClampToEdge, + ): GpuTexture + + /** + * Uploads float texels (RG pairs, row-major from the top) as a sampleable texture. + * + * @param Int width Width in texels. + * @param Int height Height in texels. + * @param TextureFilter filter How texels are filtered. + * @param FloatArray texels The texels. + * @return GpuTexture The texture. + */ + fun createFloatTexture(width: Int, height: Int, filter: TextureFilter, texels: FloatArray): GpuTexture + + /** + * Re-specifies an existing float texture's contents in place, keeping the same handle. + * + * The renderer calls this once per POSE CHANGE, never in the draw loop, and a backend must not + * re-create the resource here. Warp control points are pose-dependent but frame-invariant, and + * re-specifying that texture 60x/sec churned the d3d12/Mesa driver into progressively corrupting the + * points it sampled - the "facial features warp over time" bug, worst on masked warp meshes, which + * draw twice. The frequency is the fix; keep it. + * + * @param GpuTexture texture The texture to overwrite. + * @param Int width Width in texels. + * @param Int height Height in texels. + * @param FloatArray texels The new texels. + */ + fun updateFloatTexture(texture: GpuTexture, width: Int, height: Int, texels: FloatArray) + + /** + * Uploads a mesh's static residency. + * + * @param MeshSpec spec The mesh's rest geometry and, for a glue mesh, its weld attributes. + * @return GpuMesh The resident mesh. + */ + fun createMesh(spec: MeshSpec): GpuMesh + + /** + * Re-uploads a resident mesh's rest positions in place; the topology is unchanged. + * + * @param GpuMesh mesh The resident mesh. + * @param FloatArray restPositions The new positions, same length as at upload. + */ + fun updateMeshPositions(mesh: GpuMesh, restPositions: FloatArray) + + /** + * Re-uploads a resident mesh's UVs in place; the topology is unchanged. + * + * @param GpuMesh mesh The resident mesh. + * @param FloatArray uvs The new UVs, same length as at upload. + */ + fun updateMeshUvs(mesh: GpuMesh, uvs: FloatArray) + + /** + * Allocates a render target. + * + * @param RenderTargetSpec spec What to allocate. + * @return RenderTarget The target. + */ + fun createRenderTarget(spec: RenderTargetSpec): RenderTarget + + /** + * Allocates the shared pass-1 deformed-position store. + * + * @param Int vertexCapacity The total glue vertex count across every glue mesh. + * @return DeformedPositionStore The store. + */ + fun createDeformedPositionStore(vertexCapacity: Int): DeformedPositionStore + + /** + * Returns the draw pipeline for [spec], creating it on first ask. Pipelines are immutable and reused. + * + * @param RenderPipelineSpec spec Which draw, and how it blends. + * @return RenderPipeline The pipeline. + */ + fun createRenderPipeline(spec: RenderPipelineSpec): RenderPipeline + + /** + * Returns the pipeline that evaluates the deform per vertex and writes positions without drawing. + * + * @return DeformCapturePipeline The pipeline. + */ + fun createDeformCapturePipeline(): DeformCapturePipeline + + /** Frees [texture]. */ + fun destroyTexture(texture: GpuTexture) + + /** Frees [mesh] and every buffer it owns. */ + fun destroyMesh(mesh: GpuMesh) + + /** Frees [target]. */ + fun destroyRenderTarget(target: RenderTarget) + + // --- Frame recording --- + + /** + * Begins recording a frame's work. End it with [FrameEncoder.endFrame]. + * + * @return FrameEncoder The encoder. + */ + fun beginFrame(): FrameEncoder + + /** + * Copies [source] into [destination], filtered - the supersample resolve (a box downscale when the + * source is larger). + * + * A device primitive rather than a caller-side blit, because "blit" is the GL spelling only: + * `glBlitFramebuffer` with GL_LINEAR does this in one call, but Metal's `MTLBlitCommandEncoder` + * can neither filter nor scale - a Metal backend implements this as a full-screen textured draw + * (or MPSImageBilinearScale). Exposing the honest verb keeps that difference inside the device. + * + * The layer-composite path also calls this BETWEEN two passes of one frame (snapshotting the + * destination before a composite draw samples it). On GL that is naturally ordered; a + * command-buffer backend must order the copy against the passes recorded before and after it. + * + * @param RenderTarget source The surface to read (any size). + * @param RenderTarget destination The surface to fill, at its own size. + * @param ScissorRect? region The sub-rectangle to copy (same coordinates in both surfaces), + * or null for the whole surface. Only valid when [source] and [destination] are the same size - + * the scaled supersample resolve always passes null. The composite path passes its layer bounds + * here so the destination snapshot copies only the pixels the scissored composite will sample. + * Equivalent to [resolveUsed] at the targets' full allocated sizes. + */ + fun resolve(source: RenderTarget, destination: RenderTarget, region: ScissorRect? = null) + + /** + * [resolve] restricted to each target's USED region - the (width x height) extent the last pass + * actually rendered, anchored at the render origin (the GL device's bottom-left rows; a + * top-left-origin backend's top-left rows). This is the primitive a grow-only surface needs: + * its targets are allocated at a high-water capacity and only the used region holds pixels, so a + * full-allocation copy would read garbage and a full-allocation scale would misplace the content. + * + * @param RenderTarget source The surface to read. + * @param Int sourceUsedWidth The rendered extent of [source] along x, in pixels. + * @param Int sourceUsedHeight The rendered extent of [source] along y, in pixels. + * @param RenderTarget destination The surface to fill. + * @param Int destinationUsedWidth The rendered extent of [destination] along x, in pixels. + * @param Int destinationUsedHeight The rendered extent of [destination] along y, in pixels. + * @param ScissorRect? region The sub-rectangle to copy (same top-left-origin coordinates in both + * used regions, flipped against the USED height on a bottom-up backend), or null to scale the + * whole source used region onto the destination used region (filtered - the supersample + * resolve). Only valid when the used sizes are equal, exactly like [resolve]'s same-size rule. + */ + fun resolveUsed( + source: RenderTarget, + sourceUsedWidth: Int, + sourceUsedHeight: Int, + destination: RenderTarget, + destinationUsedWidth: Int, + destinationUsedHeight: Int, + region: ScissorRect? = null, + ) + + // --- Read-back --- + + /** + * Begins an ASYNCHRONOUS read-back of [target], returning immediately. + * + * The synchronous [readPixels] stalls the pipeline until the GPU finishes; this schedules the copy + * on the GPU timeline instead, so a per-frame caller (the viewport read-back) never blocks while a + * slider is dragged. Poll the ticket with [pollReadback] on later ticks. + * + * The GL device implements this as glReadPixels into a pooled pixel-buffer object gated by a fence; + * a Metal backend would stash the bytes from a command-buffer completion handler and hand them over + * on the poll - polling (rather than a callback) is deliberate, so results always arrive on the + * render thread on every backend, whatever thread the backend completes on. + * + * @param RenderTarget target The target to read. + * @return ReadbackTicket The claim ticket to poll. + */ + fun beginReadback(target: RenderTarget): ReadbackTicket + + /** + * [beginReadback] restricted to the target's USED region (see [resolveUsed] for the anchoring + * contract). The delivered image is usedWidth x usedHeight, top row first as always. + * + * @param RenderTarget target The target to read. + * @param Int usedWidth The rendered extent along x, in pixels. + * @param Int usedHeight The rendered extent along y, in pixels. + * @return ReadbackTicket The claim ticket to poll. + */ + fun beginReadback(target: RenderTarget, usedWidth: Int, usedHeight: Int): ReadbackTicket + + /** + * The pixels of an in-flight read-back once ready, or null while the GPU is still copying. + * + * Non-blocking, and null means STILL IN FLIGHT and nothing else: once the copy is done the ticket is + * spent and this returns a non-null image, EVEN if the backend then hit an error retrieving the bytes + * (in which case the image is a same-size zero fill - one lost frame, never a null the caller would + * mistake for still-in-flight and re-poll into the spent-ticket check). One-shot: the first non-null + * return spends the ticket and recycles its staging; polling a spent ticket is a caller bug. Same + * orientation contract as [readPixels]: RGBA8888, TOP row first, whatever the backend's framebuffer + * origin. + * + * @param ReadbackTicket ticket The claim ticket from [beginReadback]. + * @return RasterImage? The pixels once ready, or null while still in flight. + */ + fun pollReadback(ticket: ReadbackTicket): RasterImage? + + /** + * Abandons an in-flight read-back, freeing its staging without waiting for the pixels. For + * teardown; a spent ticket is a no-op. + * + * @param ReadbackTicket ticket The claim ticket to abandon. + */ + fun cancelReadback(ticket: ReadbackTicket) + + /** + * Reads [target] back to the host, synchronously. + * + * Always RGBA8888 with the TOP row first, whatever the backend's framebuffer origin: the GL device + * flips its bottom-up read, and a top-left-origin backend would not. Fixing the convention here is + * what stops every caller having to ask which way up a backend is. + * + * Synchronous, so it stalls the pipeline. Fine for verification and thumbnails; the per-frame path + * uses an asynchronous read-back instead. + * + * @param RenderTarget target The target to read. + * @return RasterImage The pixels, top row first. + */ + fun readPixels(target: RenderTarget): RasterImage + + /** + * [readPixels] restricted to the target's USED region (see [resolveUsed] for the anchoring + * contract). The returned image is usedWidth x usedHeight, top row first. + * + * @param RenderTarget target The target to read. + * @param Int usedWidth The rendered extent along x, in pixels. + * @param Int usedHeight The rendered extent along y, in pixels. + * @return RasterImage The pixels, top row first. + */ + fun readPixels(target: RenderTarget, usedWidth: Int, usedHeight: Int): RasterImage + + /** + * The largest render target edge this device can allocate AND draw to, in pixels. + * + * The smallest of the limits a render target meets on its way through a frame: the texture size, the + * renderbuffer size, and the viewport size. A caller rendering something larger than this splits it + * into tiles rather than asking the device for a target it cannot make. + * + * @return Int The edge, in pixels. + */ + fun maxRenderTargetSize(): Int + + /** + * The backend's device / driver / version as one line - a startup diagnostic confirming which backend + * actually drives the viewport (a hardware driver vs a software rasterizer, say). + * + * @return String The description. + */ + fun describeBackend(): String +} + +/** + * An in-flight asynchronous read-back - an opaque claim ticket for [RenderDevice.pollReadback]. + * + * One-shot: a ticket yields its pixels exactly once, after which it is spent and the backend has + * recycled its staging. + */ +public interface ReadbackTicket + +/** + * One frame's recorded work. Passes run in the order they are begun. + * + * A pass that reads what an earlier pass wrote must be separated from it by [barrier]. + */ +public interface FrameEncoder { + /** + * Begins a render pass. End it before beginning another - passes do not nest. + * + * @param RenderPassSpec spec The target, what to do with its existing contents, and the viewport. + * @return RenderPassEncoder The pass encoder. + */ + fun beginRenderPass(spec: RenderPassSpec): RenderPassEncoder + + /** + * Begins the deform-capture pass (glue pass 1). + * + * @param DeformCapturePipeline pipeline The capture pipeline. + * @param DeformedPositionStore store Where the deformed positions land. + * @return DeformCapturePassEncoder The pass encoder. + */ + fun beginDeformCapturePass(pipeline: DeformCapturePipeline, store: DeformedPositionStore): DeformCapturePassEncoder + + /** + * Declares that work after this point reads [store] as written by work before it, so the backend + * orders the write against the read. + * + * A declared DEPENDENCY, not an instruction to stall - which is what lets each backend meet it its own + * way. The GL device issues `glFinish`: the WSL d3d12/Mesa stack does not reliably order transform + * feedback's writes before a later texture read, so pass 2 sampled a half-written store and produced + * garbage welds while a parameter moved. `glMemoryBarrier` cannot help - feedback writes are + * coherent-pipeline writes, outside its scope - so the full sync is the honest fix. A Metal backend + * would implement this as a genuine no-op, since it tracks the dependency itself within a command + * buffer; that is correct, not a stub. + * + * The renderer calls it only on pose-change frames, so a static pose pays nothing. + * + * @param DeformedPositionStore store The store written before and read after. + */ + fun barrier(store: DeformedPositionStore) + + /** Submits the frame. */ + fun endFrame() +} + +/** + * What a render pass does with its target's existing contents on entry. + * + * GL needs none of this and ignores it; it is stated because a tile-based GPU cannot infer it, and + * because it is genuinely free information the renderer already has. The grid is an opaque full-screen + * fill that both clears and paints, so its pass is [DontCare] - and on a tile-based GPU that means the + * tile is never fetched at all. + */ +public enum class LoadAction { + /** Discard and fill with the clear color. */ + Clear, + + /** Preserve: the pass reads what was already there. */ + Load, + + /** The pass overwrites every pixel, so the previous contents need not be fetched. */ + DontCare, +} + +/** Whether a pass's results are kept. [DontCare] lets a tile-based GPU skip the write-back. */ +public enum class StoreAction { + /** Keep the results. */ + Store, + + /** Discard them. */ + DontCare, +} + +/** + * An axis-aligned pixel rectangle restricting where a pass (or a region resolve) writes. + * + * Coordinates follow the read-back convention: (0, 0) is the TOP-LEFT pixel, whatever the backend's + * framebuffer origin (the GL device converts to its bottom-left origin internally). Fixing the + * convention here is what stops every caller having to ask which way up a backend is. + * + * @property Int x Left edge in pixels. + * @property Int y Top edge in pixels. + * @property Int width Width in pixels (> 0). + * @property Int height Height in pixels (> 0). + */ +public data class ScissorRect( + val x: Int, + val y: Int, + val width: Int, + val height: Int, +) + +/** + * One render pass. + * + * Every field is explicit because a pass that discovered its own target could not exist on a backend with + * no bound-framebuffer concept - and because, even on GL, discovering it from ambient state hid a real + * coupling between the renderer and whoever bound the framebuffer first. + * + * @property RenderTarget colorTarget The surface this pass writes. + * @property LoadAction loadAction What to do with its existing contents on entry. + * @property StoreAction storeAction Whether to keep the results. + * @property Float clearRed Clear red; read only when [loadAction] is [LoadAction.Clear]. + * @property Float clearGreen Clear green; read only when [loadAction] is [LoadAction.Clear]. + * @property Float clearBlue Clear blue; read only when [loadAction] is [LoadAction.Clear]. + * @property Float clearAlpha Clear alpha; read only when [loadAction] is [LoadAction.Clear]. + * @property Int viewportWidth The viewport width in pixels. + * @property Int viewportHeight The viewport height in pixels. + * @property ScissorRect? scissor Restricts every write of the pass - the clear included - to the + * rectangle, for the whole pass (per-pass fixed state, like the target). Null writes everywhere. + * The composite path uses this to confine a layer's clear + composite to the subtree's bounds. + */ +public data class RenderPassSpec( + val colorTarget: RenderTarget, + val loadAction: LoadAction, + val viewportWidth: Int, + val viewportHeight: Int, + val storeAction: StoreAction = StoreAction.Store, + val clearRed: Float = 0f, + val clearGreen: Float = 0f, + val clearBlue: Float = 0f, + val clearAlpha: Float = 0f, + val scissor: ScissorRect? = null, +) + +/** Records draws into one render pass. */ +public interface RenderPassEncoder { + /** + * Binds the pipeline subsequent draws use. Blend and shader stages are fixed by it. + * + * @param RenderPipeline pipeline The pipeline. + */ + fun setPipeline(pipeline: RenderPipeline) + + /** + * Sets the pass-wide world→NDC affine and the screen-space texture divisor. + * + * The divisor is the ALLOCATED size of the screen-space side textures (mask coverage, composite + * layer, destination snapshot) a draw may sample by `gl_FragCoord / screenTexSize` - never the + * pass viewport, which lives in [RenderPassSpec]. The two agree only when the side targets are + * exactly viewport-sized; with grow-only side targets the divisor is the high-water capacity. + * + * @param WorldToNdc worldToNdc The camera affine. + * @param Int screenTexWidth The sampled side textures' allocated width, in pixels. + * @param Int screenTexHeight The sampled side textures' allocated height, in pixels. + */ + fun setCamera(worldToNdc: WorldToNdc, screenTexWidth: Int, screenTexHeight: Int) + + /** + * Draws one deforming art mesh. + * + * @param GpuMesh mesh The mesh. + * @param DeformUniforms deform Its per-pose deform inputs (marshal, do not retain). + * @param FragmentUniforms fragment Its appearance (marshal, do not retain). + * @param DrawTextures textures The textures it samples. + */ + fun drawPuppetMesh(mesh: GpuMesh, deform: DeformUniforms, fragment: FragmentUniforms, textures: DrawTextures) + + /** + * Draws one glue art mesh, welding against pass-1's positions. + * + * @param GpuMesh mesh The mesh. + * @param DeformedPositionStore store The shared pass-1 positions. + * @param Int baseVertexOffset This mesh's first vertex index in the store. + * @param FloatArray glueIntensities Per-glue weld intensity, by glue index. + * @param FragmentUniforms fragment Its appearance (marshal, do not retain). + * @param DrawTextures textures The textures it samples. + */ + fun drawGlueMesh( + mesh: GpuMesh, + store: DeformedPositionStore, + baseVertexOffset: Int, + glueIntensities: FloatArray, + fragment: FragmentUniforms, + textures: DrawTextures, + ) + + /** + * Draws the atlas-page underlay quad. + * + * @param GpuTexture atlas The page. + * @param Float pageWidth The page width in texels. + * @param Float pageHeight The page height in texels. + * @param FragmentUniforms fragment Its appearance. + */ + fun drawAtlasPage(atlas: GpuTexture, pageWidth: Float, pageHeight: Float, fragment: FragmentUniforms) + + /** + * Fills the target with the grid backdrop. + * + * @param GridUniforms uniforms The grid's inputs. + */ + fun drawGrid(uniforms: GridUniforms) + + /** + * Composites a rendered layer over the destination, blending in-shader (full-screen triangle; + * the pipeline must be [PipelinePurpose.Composite], whose blending is disabled - the shader + * computes the whole blend from the layer and the destination snapshot). + * + * @param CompositeUniforms composite The blend modes, channels, and mask flags (marshal, do not retain). + * @param DrawTextures textures [DrawTextures.compositeLayer] + [DrawTextures.destinationSnapshot], + * plus [DrawTextures.maskCoverage] when the composite is clipped. + */ + fun drawComposite(composite: CompositeUniforms, textures: DrawTextures) + + /** + * Draws one world-origin axis line. + * + * @param AxisLineUniforms uniforms The line's inputs. + */ + fun drawAxisLine(uniforms: AxisLineUniforms) + + /** Ends the pass. */ + fun end() +} + +/** Records the pass-1 deform capture. */ +public interface DeformCapturePassEncoder { + /** + * Evaluates the deform for every vertex of [mesh] and writes each result into the store at + * [destinationVertexOffset] plus the vertex's own index. Draws nothing. + * + * The name describes the EFFECT, not the mechanism, which is what lets the mechanism change without + * touching the renderer: the GL family runs it as transform feedback today and may become a + * point-scatter render once the store is a 2D texture (a texture cannot be a feedback target); Metal + * has no transform feedback at all and would use a compute kernel. None of that reaches here. + * + * @param GpuMesh mesh The mesh to deform. + * @param DeformUniforms deform Its per-pose deform inputs (marshal, do not retain). + * @param DrawTextures textures Its delta and warp control-point textures. + * @param Int destinationVertexOffset This mesh's base index in the store. + * @param Int vertexCount How many vertices to capture. + */ + fun captureDeformedPositions( + mesh: GpuMesh, + deform: DeformUniforms, + textures: DrawTextures, + destinationVertexOffset: Int, + vertexCount: Int, + ) + + /** Ends the pass. */ + fun end() +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/BlendShapeEval.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/BlendShapeEval.kt new file mode 100644 index 0000000..771a651 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/BlendShapeEval.kt @@ -0,0 +1,416 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.meshGridDefaultDeltas +import org.umamo.runtime.eval.rotationFormAt +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.RotationPivotForm + +/* + * Blend-shape ("MorphTarget") evaluation: the additive pass applied on top of the multilinear + * keyform-grid blend. + * + * - A binding's weight is a LINEAR interpolation between the two keys bracketing the driving + * parameter's value; the neutral key (at the parameter default) contributes zero. + * - Out-of-range driving values SATURATE - the end key's full delta is held (Umamo C++ Runtime + * verdict, Model A's ParamEyeSize matrix; a competing hide-on-out-of-range hypothesis was + * overruled). + * - The bracket has NO epsilon, unlike the grid path's EPS_KEY snapping - mirrored from the + * reference runtime for ULP parity. + * - The weight is multiplied by the MINIMUM over the binding's limit curves (end-clamped + * piecewise-linear over OTHER parameters); Model B-measured: a half-ramp scales deltas by + * exactly 0.5000. + * - Deltas are relative to the object's grid form INTERPOLATED AT THE DEFAULT POSE, not the rest + * shape (refuted 16/16 on Model A). Forms with a null entry (an inserted neutral) never reach + * the contribution list. + */ + +/** One active key of a binding at the current pose: the key's form index and its net weight. */ +internal class ActiveBlendKey(val keyIndex: Int, val weight: Float) + +/** + * Resolves which of [binding]'s keys contribute at [value], with the net weight of each + * (bracket interpolation x [limitMultiplier]). At most two entries; EMPTY at the neutral value, + * so the default pose stays arithmetic-free. Out-of-range values saturate to the end key. + * + * @param BlendShapeBinding binding The binding to resolve. + * @param Float value The driving parameter's current value. + * @param Float limitMultiplier The binding's min-combined limit multiplier (0..1). + * @return List The active keys with nonzero weight. + */ +internal fun activeBlendKeys( + binding: BlendShapeBinding<*>, + value: Float, + limitMultiplier: Float, +): List { + if (limitMultiplier <= 0f) { + return emptyList() + } + val keys = binding.keys + if (keys.size < 2) { + // A lone key is necessarily the neutral (ingest always inserts it): nothing to add. + return emptyList() + } + // Saturating bracket, no epsilon: grid = last key <= value, clamped to the ends. + var lowerKeyIndex = 0 + while (lowerKeyIndex + 1 < keys.size && keys[lowerKeyIndex + 1] <= value) { + lowerKeyIndex++ + } + val span = if (lowerKeyIndex + 1 < keys.size) keys[lowerKeyIndex + 1] - keys[lowerKeyIndex] else 0f + val fraction = + when { + value <= keys[0] -> 0f + lowerKeyIndex + 1 >= keys.size -> 0f + span > 0f -> (value - keys[lowerKeyIndex]) / span + else -> 0f + } + val active = ArrayList(2) + val lowerWeight = (1f - fraction) * limitMultiplier + if (lowerKeyIndex != binding.neutralIndex && lowerWeight > 0f) { + active.add(ActiveBlendKey(lowerKeyIndex, lowerWeight)) + } + val upperWeight = fraction * limitMultiplier + if (fraction > 0f && lowerKeyIndex + 1 != binding.neutralIndex && upperWeight > 0f) { + active.add(ActiveBlendKey(lowerKeyIndex + 1, upperWeight)) + } + return active +} + +/** + * The binding's blend-weight limit multiplier at the current pose: the MINIMUM over its limit + * curves, each an end-clamped piecewise-linear (value, weight) map over another parameter. + * 1 when the binding has no limits. + * + * @param List limits The binding's limit curves. + * @param Function paramValue Current value per parameter id. + * @return Float The multiplier in [0..1] (whatever the curves yield). + */ +internal fun limitMultiplier(limits: List, paramValue: (ParameterId) -> Float): Float { + var multiplier = 1f + for (limit in limits) { + val points = limit.points + if (points.isEmpty()) { + continue + } + val value = paramValue(limit.parameterId) + val capped = + when { + value <= points.first().value -> points.first().weight + value >= points.last().value -> points.last().weight + else -> { + var lowerPointIndex = 0 + while (lowerPointIndex + 1 < points.size && points[lowerPointIndex + 1].value <= value) { + lowerPointIndex++ + } + val lower = points[lowerPointIndex] + val upper = points[lowerPointIndex + 1] + val span = upper.value - lower.value + if (span > 0f) { + val fraction = (value - lower.value) / span + lower.weight + fraction * (upper.weight - lower.weight) + } else { + lower.weight + } + } + } + if (capped < multiplier) { + multiplier = capped + } + } + return multiplier +} + +/** One active mesh blend contribution: the form, its net weight, and its (binding, key) identity. */ +internal class MeshBlendContribution( + val bindingIndex: Int, + val keyIndex: Int, + val form: MeshForm, + val weight: Float, +) + +/** + * A mesh drawable's resolved blend state at one pose: the active contributions plus the shared + * delta reference (the grid form at the DEFAULT pose, as deltas vs the rest mesh - static per + * drawable, null when the drawable is ungridded so the reference is zero). + */ +internal class MeshBlendState( + val contributions: List, + val referenceDeltas: FloatArray?, + val referenceDrawOrder: Float, + val referenceOpacity: Float, + // Default to the channel identities: a drawable with no color tables has no reference to subtract, + // and the identities make the subtraction a no-op rather than a shift. + val referenceMultiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val referenceScreenColor: ColorRgb = ColorRgb.ScreenIdentity, +) + +/** + * Resolves [drawable]'s blend-shape state at the current pose, or null when it has no bindings + * (the caller then takes the exact pre-blend-shape code path). + * + * @param Drawable drawable The drawable. + * @param Function paramValue Current value per parameter id. + * @param Function defaultValue Default value per parameter id (the neutral pose). + * @return MeshBlendState? The resolved state, or null when binding-free. + */ +internal fun meshBlendState( + drawable: Drawable, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, +): MeshBlendState? { + if (drawable.blendShapes.isEmpty()) { + return null + } + val contributions = ArrayList() + for (bindingIndex in drawable.blendShapes.indices) { + val binding = drawable.blendShapes[bindingIndex] + val active = + activeBlendKeys(binding, paramValue(binding.parameterId), limitMultiplier(binding.limits, paramValue)) + for (key in active) { + val form = binding.forms[key.keyIndex] ?: continue + contributions.add(MeshBlendContribution(bindingIndex, key.keyIndex, form, key.weight)) + } + } + // The reference is the entity's state at the DEFAULT pose (E5): geometry deltas vs the rest mesh, + // plus each scalar channel's own value there. An untracked or out-of-range channel resolves to the + // drawable's static, which for an imported drawable is Cubism's 500 / full opacity - the same + // statics scalarAt falls back to everywhere else, so the evaluator's subtraction still cancels exactly. + return MeshBlendState( + contributions = contributions, + referenceDeltas = meshGridDefaultDeltas(drawable, defaultValue), + referenceDrawOrder = drawable.channelGrids.scalarAt(FormChannel.DRAW_ORDER, drawable.drawOrder, defaultValue), + referenceOpacity = drawable.channelGrids.scalarAt(FormChannel.OPACITY, drawable.opacity, defaultValue), + referenceMultiplyColor = + drawable.channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor, defaultValue), + referenceScreenColor = + drawable.channelGrids.colorAt(FormChannel.SCREEN_COLOR, drawable.screenColor, defaultValue), + ) +} + +/** + * The summed weighted control-point delta of [warp]'s blend bindings at the current pose, or null + * when nothing contributes. Deltas are relative to the lattice's grid form at the DEFAULT pose + * (E5); WarpForm control points are absolute, so the reference is subtracted here. + * + * @param Deformer.Warp warp The warp deformer. + * @param Function paramValue Current value per parameter id. + * @param Function defaultValue Default value per parameter id. + * @return FloatArray? Interleaved control-point deltas to ADD to the grid-blended lattice, or null. + */ +internal fun warpBlendDeltas( + warp: Deformer.Warp, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, +): FloatArray? { + if (warp.blendShapes.isEmpty()) { + return null + } + var deltas: FloatArray? = null + var reference: FloatArray? = null + for (binding in warp.blendShapes) { + val active = + activeBlendKeys(binding, paramValue(binding.parameterId), limitMultiplier(binding.limits, paramValue)) + for (key in active) { + val form = binding.forms[key.keyIndex] ?: continue + if (reference == null) { + reference = warpControlPointsAt(warp.geometryGrid, defaultValue) ?: FloatArray(form.controlPoints.size) + } + val target = deltas ?: FloatArray(form.controlPoints.size).also { deltas = it } + for (componentIndex in target.indices) { + target[componentIndex] += key.weight * (form.controlPoints[componentIndex] - reference[componentIndex]) + } + } + } + return deltas +} + +/** A rotation deformer's summed weighted blend deltas (the reflect flags are not blendable). */ +internal class RotationBlendDeltas( + val originX: Float, + val originY: Float, + val angle: Float, + val scale: Float, +) + +/** + * The summed weighted affine deltas of [rotation]'s blend bindings at the current pose, or null + * when nothing contributes. Deltas are relative to the rotation's grid form at the DEFAULT pose + * (E5); RotationForm fields are absolute, so the reference is subtracted here. + * + * @param Deformer.Rotation rotation The rotation deformer. + * @param Function paramValue Current value per parameter id. + * @param Function defaultValue Default value per parameter id. + * @return RotationBlendDeltas? The deltas to ADD to the grid-blended transform, or null. + */ +internal fun rotationBlendDeltas( + rotation: Deformer.Rotation, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, +): RotationBlendDeltas? { + if (rotation.blendShapes.isEmpty()) { + return null + } + var originX = 0f + var originY = 0f + var angle = 0f + var scale = 0f + var contributed = false + var reference: RotationPivotForm? = null + for (binding in rotation.blendShapes) { + val active = + activeBlendKeys(binding, paramValue(binding.parameterId), limitMultiplier(binding.limits, paramValue)) + for (key in active) { + val form = binding.forms[key.keyIndex] ?: continue + if (reference == null) { + // The identity fallback mirrors the importer's, so the subtraction cancels exactly even for + // an unkeyed rotation. Flips are FLAG channels and never take part in a blend-shape delta. + reference = rotationFormAt(rotation.geometryGrid, defaultValue) + ?: RotationPivotForm(0f, 0f, 0f, 1f) + } + originX += key.weight * (form.originX - reference.originX) + originY += key.weight * (form.originY - reference.originY) + angle += key.weight * (form.angle - reference.angle) + scale += key.weight * (form.scale - reference.scale) + contributed = true + } + } + return if (contributed) RotationBlendDeltas(originX, originY, angle, scale) else null +} + +/** + * A deformer's summed weighted blend-shape CHANNEL deltas - the render channels that cascade onto + * every drawable underneath, as additive offsets to be applied on top of the grid blend. + */ +internal class DeformerBlendChannelDeltas( + val opacity: Float, + val multiplyColor: ColorRgb, + val screenColor: ColorRgb, +) + +/** + * Sums [bindings]' weighted channel deltas at the current pose, or null when nothing contributes. + * + * The forms carry each channel's value as (stored delta + the grid-at-default reference), the same + * convention the geometry uses, so the reference is subtracted back out here. Sampling the reference + * from [channelGrids] rather than from the form list is what makes an UNKEYED channel cancel exactly: + * both sides then resolve to the deformer's static. + * + * Warp and rotation share this because their channel triple is identical - only the geometry payload + * differs - and two copies would drift the moment one gained a clamp the other lacked. + * + * @param List bindings The deformer's blend bindings. + * @param ChannelGrids channelGrids The deformer's own keyform tracks (the reference source). + * @param Float staticOpacity The deformer's static opacity. + * @param ColorRgb staticMultiply The deformer's static multiply color. + * @param ColorRgb staticScreen The deformer's static screen color. + * @param Function paramValue Current value per parameter id. + * @param Function defaultValue Default value per parameter id (the neutral pose). + * @return DeformerBlendChannelDeltas? The summed offsets, or null when nothing contributes. + */ +internal fun deformerBlendChannelDeltas( + bindings: List>, + channelGrids: ChannelGrids, + staticOpacity: Float, + staticMultiply: ColorRgb, + staticScreen: ColorRgb, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, + channelsOf: (F) -> DeformerBlendChannelDeltas, +): DeformerBlendChannelDeltas? { + if (bindings.isEmpty()) { + return null + } + var opacity = 0f + var multiplyRed = 0f + var multiplyGreen = 0f + var multiplyBlue = 0f + var screenRed = 0f + var screenGreen = 0f + var screenBlue = 0f + var contributed = false + var reference: DeformerBlendChannelDeltas? = null + for (binding in bindings) { + val active = + activeBlendKeys(binding, paramValue(binding.parameterId), limitMultiplier(binding.limits, paramValue)) + for (key in active) { + val form = binding.forms[key.keyIndex] ?: continue + if (reference == null) { + reference = + DeformerBlendChannelDeltas( + channelGrids.scalarAt(FormChannel.OPACITY, staticOpacity, defaultValue), + channelGrids.colorAt(FormChannel.MULTIPLY_COLOR, staticMultiply, defaultValue), + channelGrids.colorAt(FormChannel.SCREEN_COLOR, staticScreen, defaultValue), + ) + } + val channels = channelsOf(form) + contributed = true + opacity += key.weight * (channels.opacity - reference.opacity) + multiplyRed += key.weight * (channels.multiplyColor.red - reference.multiplyColor.red) + multiplyGreen += key.weight * (channels.multiplyColor.green - reference.multiplyColor.green) + multiplyBlue += key.weight * (channels.multiplyColor.blue - reference.multiplyColor.blue) + screenRed += key.weight * (channels.screenColor.red - reference.screenColor.red) + screenGreen += key.weight * (channels.screenColor.green - reference.screenColor.green) + screenBlue += key.weight * (channels.screenColor.blue - reference.screenColor.blue) + } + } + if (!contributed) { + return null + } + return DeformerBlendChannelDeltas( + opacity, + ColorRgb(multiplyRed, multiplyGreen, multiplyBlue), + ColorRgb(screenRed, screenGreen, screenBlue), + ) +} + +/** + * A part's summed weighted blend-shape draw-order delta at the current pose, or null when nothing + * contributes. + * + * Draw order is a part's only blendable channel, so unlike the drawable and deformer paths there is + * one scalar to sum. The reference is the channel's value at the DEFAULT pose - sampled from the + * part's own track, falling back to its static - which is exactly what the import added, so the two + * cancel. + * + * @param Part part The part. + * @param Function paramValue Current value per parameter id. + * @param Function defaultValue Default value per parameter id (the neutral pose). + * @return Float? The summed delta, or null when the part has no active contribution. + */ +internal fun partBlendDrawOrderDelta( + part: Part, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, +): Float? { + if (part.blendShapes.isEmpty()) { + return null + } + var delta = 0f + var contributed = false + var reference: Float? = null + for (binding in part.blendShapes) { + val active = + activeBlendKeys(binding, paramValue(binding.parameterId), limitMultiplier(binding.limits, paramValue)) + for (key in active) { + val form = binding.forms[key.keyIndex] ?: continue + if (reference == null) { + reference = + part.channelGrids.scalarAt(FormChannel.DRAW_ORDER, part.drawOrder.toFloat(), defaultValue) + } + contributed = true + delta += key.weight * (form.drawOrder - reference) + } + } + return if (contributed) delta else null +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/CpuDeformationEvaluator.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/CpuDeformationEvaluator.kt new file mode 100644 index 0000000..7dc3981 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/CpuDeformationEvaluator.kt @@ -0,0 +1,21 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel + +/** + * CPU implementation of [DeformationEvaluator]. Deformation is split into a cheap, backend-neutral + * [preparePose] (keyform weights + baked deformer transforms) and the per-vertex [applyCpuDeform] that + * finishes it (blend → cascade → Y-flip → glue). The GPU path reuses the same [preparePose] and + * uploads its inputs to a vertex shader instead of finishing on the CPU. + */ +class CpuDeformationEvaluator : DeformationEvaluator { + /** + * Evaluates [model] at [parameters], falling back to each parameter's default when unspecified. + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id → value (partial; the rest default). + * @return DeformedGeometry World positions per visible drawable. + */ + override fun evaluate(model: PuppetModel, parameters: Map): DeformedGeometry = applyCpuDeform(model, preparePose(model, parameters)) +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformPrepare.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformPrepare.kt new file mode 100644 index 0000000..63de44f --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformPrepare.kt @@ -0,0 +1,356 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.gridCorners +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.eval.scalarOrNull +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderGroup + +/** + * Backend-neutral per-pose deform inputs for one drawable - the cheap output of [preparePose]: which + * keyform cells are active and their weights ([corners]), the mesh's baked parent-deformer transform + * ([parentWorld]; null for a direct, deformer-less mesh), and the blended scalar attributes. [corners] + * null means the mesh is hidden at this pose; [isParented] with a null [parentWorld] means a hidden + * ancestor deformer (also hidden). Nothing here is per-vertex - the CPU finishes it in [applyCpuDeform], + * and the GPU path uploads the same corners (→ weight uniforms) + baked transform instead. + */ +internal class DrawableDeformInputs( + val drawableId: DrawableId, + val corners: List?, + val parentWorld: DeformerWorld?, + val isParented: Boolean, + val drawOrder: Float, + val opacity: Float, + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, + val blend: MeshBlendState? = null, +) + +/** + * The corner set of an entity with no keyform grid: one full-weight corner into a cell map that holds + * nothing, so every blend contributes zero and the entity evaluates at its rest state. + * + * Shared rather than rebuilt per drawable per frame, and deliberately NOT an empty list - an empty corner + * set would make the weights sum to zero, which is a different thing entirely. + */ +private val REST_CORNERS: List = listOf(WeightedCell(0, 1f)) + +/** A glue affecter with its pose-blended weld [intensity] already resolved, so the apply pass is param-free. */ +internal class GlueInputs( + val meshA: DrawableId, + val meshB: DrawableId, + val pairs: List, + val intensity: Float, +) + +/** + * The full per-pose, backend-neutral deform inputs ([preparePose]'s output): per-drawable weights + baked + * transforms and the resolved glues. The CPU finishes it per vertex via [applyCpuDeform]; the GPU path + * uploads the same data as uniforms instead of re-uploading every deformed vertex - that re-use is exactly + * why the deformation is split into a cheap "prepare" and a backend-specific "apply". + */ +internal class PoseDeformInputs( + val drawables: List, + val glues: List, + /** Pose-blended draw order per grouped part (animated part order); missing → the static value. */ + val partDrawOrders: Map = emptyMap(), + /** + * Pose-blended composite channels per ISOLATED part (opacity, multiply/screen colors), present + * for every isolated group - a static or out-of-range part carries its PartComposite fallbacks, + * so the composite pass never has to re-derive them. + */ + val partCompositeStates: Map = emptyMap(), +) + +/** + * Computes the cheap, backend-neutral deform inputs for [model] at [parameters]: the multilinear keyform + * weights per mesh and each mesh's baked deformer-cascade transform - never per-vertex geometry. Shared + * verbatim by the CPU ([applyCpuDeform]) and the eventual GPU apply paths. + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id → value (partial; the rest default). + * @param Map channelOverrides Pending unkeyed channel edits, which win over the stored value - how + * a value the user typed but has not keyed shows in the viewport without entering the document. + * @return PoseDeformInputs The backend-neutral per-pose inputs. + */ +internal fun preparePose( + model: PuppetModel, + parameters: Map, + channelOverrides: Map = emptyMap(), +): PoseDeformInputs { + val defaults = model.parameters.associate { it.id to it.default } + val paramValue: (ParameterId) -> Float = { parameters[it] ?: defaults[it] ?: 0f } + val defaultValue: (ParameterId) -> Float = { defaults[it] ?: 0f } + // Null in the steady state (no pending unkeyed edit), so every lookup below short-circuits before + // constructing its KeyableTarget key - the per-frame path otherwise allocated a handful of key + // objects per entity purely to probe an empty map. + val overrides = channelOverrides.takeIf { pending -> pending.isNotEmpty() } + val deformerWorlds = buildDeformerWorlds(model.deformers, paramValue, defaultValue, channelOverrides) + val drawables = ArrayList(model.drawables.size) + for (drawable in model.drawables) { + if (drawable.mesh?.positions == null) { + continue + } + // An UNKEYED drawable renders at its rest mesh rather than vanishing: one full-weight corner into + // an empty cell map contributes no deltas, and every blend site already treats a missing cell as a + // zero contribution. Null corners keep meaning HIDDEN (a pose outside a keyed grid's range), so + // "no grid" and "out of range" stay distinguishable - they are opposite outcomes. + val grid = drawable.geometryGrid + val corners = if (grid != null) gridCorners(grid, paramValue) else REST_CORNERS + val parentDeformerId = drawable.parentDeformerId + val parentWorld = parentDeformerId?.let { deformerWorlds[it] } + val blend = meshBlendState(drawable, paramValue, defaultValue) + // Each channel resolves against its own track and falls back to the drawable's static; a channel + // out of range never hides, which is the geometry grid's decision alone (corners == null above). + val drawableOwner = KeyformOwner.Drawable(drawable.id) + var drawOrder = + drawable.channelGrids.scalarAt( + FormChannel.DRAW_ORDER, + drawable.drawOrder, + paramValue, + overrides?.get(KeyableTarget(drawableOwner, FormChannel.DRAW_ORDER)), + ) + var opacity = + drawable.channelGrids.scalarAt( + FormChannel.OPACITY, + drawable.opacity, + paramValue, + overrides?.get(KeyableTarget(drawableOwner, FormChannel.OPACITY)), + ) + var multiplyColor = + drawable.channelGrids.colorAt( + FormChannel.MULTIPLY_COLOR, + drawable.multiplyColor, + paramValue, + overrides?.get(KeyableTarget(drawableOwner, FormChannel.MULTIPLY_COLOR)), + ) + var screenColor = + drawable.channelGrids.colorAt( + FormChannel.SCREEN_COLOR, + drawable.screenColor, + paramValue, + overrides?.get(KeyableTarget(drawableOwner, FormChannel.SCREEN_COLOR)), + ) + // Blend shapes: additive deltas on every channel the record carries, not just the scalars. Each + // contribution's form holds its stored delta plus the grid-at-default reference (added at import), + // so subtracting that reference back out here recovers the delta exactly. Opacity and the colours + // clamp to [0,1] only AFTER summing - clamping per contribution would bias a record whose + // neighbours pull the other way. Draw order is left unrounded (the Umamo C++ Runtime rounds + // (int)(0.001+v) at sort time; Umamo sorts floats - MOC3.md §5.6). + if (blend != null) { + for (contribution in blend.contributions) { + val form = contribution.form + drawOrder += contribution.weight * (form.drawOrder - blend.referenceDrawOrder) + opacity += contribution.weight * (form.opacity - blend.referenceOpacity) + multiplyColor = + ColorRgb( + multiplyColor.red + contribution.weight * (form.multiplyColor.red - blend.referenceMultiplyColor.red), + multiplyColor.green + + contribution.weight * (form.multiplyColor.green - blend.referenceMultiplyColor.green), + multiplyColor.blue + + contribution.weight * (form.multiplyColor.blue - blend.referenceMultiplyColor.blue), + ) + screenColor = + ColorRgb( + screenColor.red + contribution.weight * (form.screenColor.red - blend.referenceScreenColor.red), + screenColor.green + contribution.weight * (form.screenColor.green - blend.referenceScreenColor.green), + screenColor.blue + contribution.weight * (form.screenColor.blue - blend.referenceScreenColor.blue), + ) + } + opacity = opacity.coerceIn(0f, 1f) + multiplyColor = multiplyColor.coerceToUnit() + screenColor = screenColor.coerceToUnit() + } + // Then the parent deformer chain's accumulated channels. A deformer's opacity multiplies, its + // multiply color multiplies, its screen color screens - each already folded over every ancestor + // deformer by buildDeformerWorlds, so one composition here covers the whole chain. Clamped + // because a blended color can leave [0,1] at the ends of a keyed range. + parentWorld?.let { world -> + opacity *= world.accumulatedOpacity + multiplyColor = + ColorRgb( + (multiplyColor.red * world.accumulatedMultiplyColor.red).coerceIn(0f, 1f), + (multiplyColor.green * world.accumulatedMultiplyColor.green).coerceIn(0f, 1f), + (multiplyColor.blue * world.accumulatedMultiplyColor.blue).coerceIn(0f, 1f), + ) + screenColor = + ColorRgb( + screenCompose(screenColor.red, world.accumulatedScreenColor.red).coerceIn(0f, 1f), + screenCompose(screenColor.green, world.accumulatedScreenColor.green).coerceIn(0f, 1f), + screenCompose(screenColor.blue, world.accumulatedScreenColor.blue).coerceIn(0f, 1f), + ) + } + drawables.add( + DrawableDeformInputs( + drawableId = drawable.id, + corners = corners, + parentWorld = parentWorld, + isParented = parentDeformerId != null, + drawOrder = drawOrder, + opacity = opacity, + multiplyColor = multiplyColor, + screenColor = screenColor, + blend = blend, + ), + ) + } + val glues = + model.glues.map { glue -> + GlueInputs( + meshA = glue.meshA, + meshB = glue.meshB, + pairs = glue.pairs, + intensity = + glue.channelGrids.scalarAt( + FormChannel.GLUE_INTENSITY, + glue.intensity, + paramValue, + overrides?.get(KeyableTarget(KeyformOwner.Glue(glue.meshA, glue.meshB), FormChannel.GLUE_INTENSITY)), + ), + ) + } + // Blend each group's (animated) part draw order, so the renderer can position whole groups per + // pose - part groups with parameter-driven draw order swap front/back as their parameter moves. + // The same walk blends each ISOLATED group's composite channels (opacity, multiply/screen + // colors), falling back to the PartComposite statics when the part has no grid or the axis is + // out of range. + val partDrawOrders = HashMap() + val partCompositeStates = HashMap() + // The render tree carries a group's tracks but not its part's blend records, so the blend pass + // needs the part itself. Taken from the model, which memoizes it: this runs once per rendered + // frame, so building the map here would allocate one entry per part per frame for data that is + // immutable across all of them. + val partsById = model.partById + + fun blendGroupStates(group: RenderGroup) { + val partId = group.partId + val channels = group.channelGrids + val partOwner = partId?.let { KeyformOwner.Part(it) } + if (partId != null && partOwner != null) { + // Null when the part has no draw-order track or the pose is out of its range; with no blend + // record contributing either, the map entry is then left ABSENT so the renderer keeps the + // part's static slot - the map's sparseness is the signal. + val tracked = + channels.scalarOrNull( + FormChannel.DRAW_ORDER, + paramValue, + overrides?.get(KeyableTarget(partOwner, FormChannel.DRAW_ORDER)), + ) + // A part-target blend record moves the slot too, and it can do so on a part with no track at + // all - so an entry appears whenever EITHER contributes, with the static standing in as the + // base when only the record does. + val blendDelta = partsById[partId]?.let { part -> partBlendDrawOrderDelta(part, paramValue, defaultValue) } + if (tracked != null || blendDelta != null) { + val base = tracked ?: partsById[partId]?.drawOrder?.toFloat() ?: DEFAULT_DRAW_ORDER.toFloat() + partDrawOrders[partId] = base + (blendDelta ?: 0f) + } + } + val composite = group.composite + if (partId != null && composite != null) { + // Each composite channel resolves independently against its own static, so an isolated part + // can key opacity alone without dragging its tints onto the same axes. + partCompositeStates[partId] = + PartRenderState( + channels.scalarAt( + FormChannel.OPACITY, + composite.opacity, + paramValue, + partOwner?.let { owner -> overrides?.get(KeyableTarget(owner, FormChannel.OPACITY)) }, + ), + channels.colorAt( + FormChannel.MULTIPLY_COLOR, + composite.multiplyColor, + paramValue, + partOwner?.let { owner -> overrides?.get(KeyableTarget(owner, FormChannel.MULTIPLY_COLOR)) }, + ), + channels.colorAt( + FormChannel.SCREEN_COLOR, + composite.screenColor, + paramValue, + partOwner?.let { owner -> overrides?.get(KeyableTarget(owner, FormChannel.SCREEN_COLOR)) }, + ), + ) + } + for (child in group.children) { + if (child is RenderGroup) { + blendGroupStates(child) + } + } + } + blendGroupStates(model.renderRoot) + return PoseDeformInputs(drawables, glues, partDrawOrders, partCompositeStates) +} + +/** + * Finishes [inputs] on the CPU: per drawable, blends the active corners into local positions, pushes them + * through the baked parent transform, negates Y, then welds the glue pairs in place. Output is identical + * to evaluating the model in one pass. + * + * @param PuppetModel model The rig (for each drawable's base positions + grid). + * @param PoseDeformInputs inputs The prepared per-pose inputs. + * @return DeformedGeometry World positions + scalars per visible drawable. + */ +internal fun applyCpuDeform(model: PuppetModel, inputs: PoseDeformInputs): DeformedGeometry { + val drawableById = model.drawables.associateBy { it.id } + val worldPositions = HashMap(inputs.drawables.size) + val drawOrders = HashMap(inputs.drawables.size) + val opacities = HashMap(inputs.drawables.size) + for (drawableInputs in inputs.drawables) { + val corners = drawableInputs.corners ?: continue + // A parented mesh whose ancestor deformer is hidden produces no geometry (the cascade omitted it). + if (drawableInputs.isParented && drawableInputs.parentWorld == null) { + continue + } + val drawable = drawableById[drawableInputs.drawableId] ?: continue + val base = drawable.mesh?.positions ?: continue + // A null grid is an unkeyed drawable, which deforms to its rest mesh - see preparePose. + worldPositions[drawableInputs.drawableId] = + deformMeshWorldFromCorners(drawable.geometryGrid, base, corners, drawableInputs.parentWorld, drawableInputs.blend) + drawOrders[drawableInputs.drawableId] = drawableInputs.drawOrder + opacities[drawableInputs.drawableId] = drawableInputs.opacity + } + applyGluesResolved(inputs.glues, worldPositions) + return DeformedGeometry(worldPositions, drawOrders, opacities) +} + +/** + * Seam-welds each glue's vertex pairs in place from pre-resolved intensities: `A' = A + (B−A)·wA·i`, + * `B' = B + (A−B)·wB·i` (the Umamo C++ Runtime's `applyGlue`, on the Y-flipped world buffers). + * + * @param List glues The resolved glue affecters. + * @param Map worldPositions Per-drawable deformed positions (mutated). + */ +internal fun applyGluesResolved(glues: List, worldPositions: Map) { + for (glue in glues) { + val vertsA = worldPositions[glue.meshA] ?: continue + val vertsB = worldPositions[glue.meshB] ?: continue + val intensity = glue.intensity + for (pair in glue.pairs) { + val indexA = pair.indexA * 2 + val indexB = pair.indexB * 2 + if (indexA + 1 >= vertsA.size || indexB + 1 >= vertsB.size) { + continue + } + val ax = vertsA[indexA] + val ay = vertsA[indexA + 1] + val bx = vertsB[indexB] + val by = vertsB[indexB + 1] + vertsA[indexA] = (bx - ax) * pair.weightA * intensity + ax + vertsA[indexA + 1] = (by - ay) * pair.weightA * intensity + ay + vertsB[indexB] = (ax - bx) * pair.weightB * intensity + bx + vertsB[indexB + 1] = (ay - by) * pair.weightB * intensity + by + } + } +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformTransforms.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformTransforms.kt new file mode 100644 index 0000000..08a7daa --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformTransforms.kt @@ -0,0 +1,106 @@ +package org.umamo.render.eval + +import kotlin.math.cos +import kotlin.math.sin +import org.umamo.runtime.eval.warpApply as runtimeWarpApply +import org.umamo.runtime.eval.warpExtrap as runtimeWarpExtrap +import org.umamo.runtime.eval.warpInGrid as runtimeWarpInGrid + +// The float pi the Umamo C++ Runtime uses (matches its sincosf bit-for-bit) +internal const val PI_F = 3.1415927f + +/** + * In-grid warp transform — delegates to [org.umamo.runtime.eval.warpInGrid]. + * + * @return Boolean true when in grid (and written), false when outside. + */ +internal fun warpInGrid( + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, + u: Float, + v: Float, + out: FloatArray, + outIndex: Int, +): Boolean = runtimeWarpInGrid(cp, cols, rows, bilinear, u, v, out, outIndex) + +/** Out-of-grid warp extrapolation — delegates to [org.umamo.runtime.eval.warpExtrap]. */ +internal fun warpExtrap(cp: FloatArray, cols: Int, rows: Int, u: Float, v: Float, out: FloatArray, outIndex: Int) { + runtimeWarpExtrap(cp, cols, rows, u, v, out, outIndex) +} + +/** Warp-transforms `(u, v)` through [cp] — delegates to [org.umamo.runtime.eval.warpApply]. */ +internal fun warpApply( + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, + u: Float, + v: Float, + out: FloatArray, + outIndex: Int, +) { + runtimeWarpApply(cp, cols, rows, bilinear, u, v, out, outIndex) +} + +/** + * A rotation deformer's baked world affine - the per-vertex-invariant coefficients (xformSetup's exact + * grouping), applied as `x' = c15·y + c12·x + ox`, `y' = c13·y + c14·x + oy`. + */ +internal class RotationXform( + val c12: Float, + val c13: Float, + val c14: Float, + val c15: Float, + val ox: Float, + val oy: Float, +) { + /** + * Applies the affine to point `(x, y)`, writing the result to `out[outIndex]`,`out[outIndex+1]`. + * + * @param Float x Input x. + * @param Float y Input y. + * @param FloatArray out Destination for the transformed point. + * @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`). + */ + fun apply(x: Float, y: Float, out: FloatArray, outIndex: Int) { + out[outIndex] = c15 * y + c12 * x + ox + out[outIndex + 1] = y * c13 + x * c14 + oy + } +} + +/** + * Builds a [RotationXform] from a rotation deformer's world angle (degrees), scale, reflection flags, + * and origin. + * + * @param Float angleDegrees World rotation angle in degrees. + * @param Float scale World scale. + * @param Boolean flipX Reflect across the vertical axis. + * @param Boolean flipY Reflect across the horizontal axis. + * @param Float ox World origin x. + * @param Float oy World origin y. + * @return RotationXform The baked affine. + */ +internal fun rotationXform( + angleDegrees: Float, + scale: Float, + flipX: Boolean, + flipY: Boolean, + ox: Float, + oy: Float, +): RotationXform { + val radians = angleDegrees * PI_F / 180f + val sn = sin(radians.toDouble()).toFloat() + val cs = cos(radians.toDouble()).toFloat() + val fx = if (flipX) -1f else 1f + val fy = if (flipY) -1f else 1f + return RotationXform( + c12 = cs * scale * fx, + c13 = fy * cs * scale, + c14 = fx * scale * sn, + c15 = -sn * scale * fy, + ox = ox, + oy = oy, + ) +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformationEvaluator.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformationEvaluator.kt new file mode 100644 index 0000000..efc6135 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformationEvaluator.kt @@ -0,0 +1,39 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel + +/** + * Computed render state for one parameter pose. [worldPositions] are interleaved (x,y) world vertices + * per drawable (in the CMO3/MOC3 reverse-coordinate / Y-down model space). [drawOrder] and + * [opacity] are the per-drawable scalars blended from the same keyform grid with the same weights - + * [drawOrder] is the primary render-order sort key (the parts-tree order breaks ties), [opacity] is + * multiplied into the drawable's alpha. All three maps share the same visible-drawable keys; hidden + * drawables are absent from every map. + */ +class DeformedGeometry( + val worldPositions: Map, + val drawOrder: Map, + val opacity: Map, +) + +/** + * Evaluates a [PuppetModel] at a set of parameter values into drawable geometry. + * + * The core math is parameter-driven morph blending (`p = base + Σ wᵢ·Δᵢ`, multilinear across the + * N-D keyform grid) composed through the deformer hierarchy. The weights are cheap and computed + * CPU-side; the per-vertex delta-sum runs in a vertex shader in `:gpu`. + * + * パラメータ値からドロウアブルのジオメトリを評価する契約。 + */ +interface DeformationEvaluator { + /** + * Evaluates [model] at [parameters]; unspecified parameters fall back to their defaults. + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id → value (partial; the rest default). + * @return DeformedGeometry World positions per visible drawable. + */ + fun evaluate(model: PuppetModel, parameters: Map): DeformedGeometry +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformerCascade.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformerCascade.kt new file mode 100644 index 0000000..a2d51ce --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DeformerCascade.kt @@ -0,0 +1,577 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.flagAt +import org.umamo.runtime.eval.gridCorners +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import kotlin.math.atan2 + +/** + * A deformer's baked world transform - a warp lattice or a rotation affine - through which child + * deformers and bound meshes transform their points. [accY] is the Y-scale accumulator passed to + * child rotation deformers (warps pass the parent's through; rotations contribute their world scale). + * + * The three `accumulated*` channels are the deformer's own render channels composed with every + * ancestor's, and they apply to every DRAWABLE under this deformer (see [DeformerChannels] for the + * composition rules and [preparePose] for where they land). Riggers key a deformer's opacity to + * show and hide a whole subtree, so these are not a decorative extra - ignoring them renders effect + * subtrees permanently visible. + */ +internal sealed interface DeformerWorld { + val accY: Float + + /** This deformer's opacity times every ancestor's; multiplies each descendant drawable's own. */ + val accumulatedOpacity: Float + + /** This deformer's multiply color composed with every ancestor's (componentwise product). */ + val accumulatedMultiplyColor: ColorRgb + + /** This deformer's screen color composed with every ancestor's (`a + b - a*b` per channel). */ + val accumulatedScreenColor: ColorRgb + + /** + * Transforms point `(x, y)` through this deformer, writing to `out[outIndex]`,`out[outIndex+1]`. + * + * @param Float x Input x. + * @param Float y Input y. + * @param FloatArray out Destination for the transformed point. + * @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`). + */ + fun apply(x: Float, y: Float, out: FloatArray, outIndex: Int) +} + +/** + * A deformer's render channels at one point in the cascade - either its own blended local values or + * those composed with its ancestors'. + * + * @property Float opacity Opacity in [0,1]. + * @property ColorRgb multiplyColor Multiply tint (identity = white). + * @property ColorRgb screenColor Screen tint (identity = black). + */ +internal class DeformerChannels( + val opacity: Float, + val multiplyColor: ColorRgb, + val screenColor: ColorRgb, +) { + companion object { + /** The no-op channels a root deformer composes against. */ + val Identity: DeformerChannels = + DeformerChannels(1f, ColorRgb.MultiplyIdentity, ColorRgb.ScreenIdentity) + } +} + +/** + * Composes a deformer's local channels onto its parent's accumulated ones. + * + * Opacity and multiply color compose by product; screen color composes by the screen operator + * `a + b - a*b`. The identities are chosen so a ROOT deformer needs no special case: multiplying by + * white and screening with black both return the local value unchanged. + * + * @param DeformerChannels local This deformer's own blended channels. + * @param DeformerWorld? parent The parent's world transform, or null at the root. + * @return DeformerChannels The accumulated channels to hand to children and descendant drawables. + */ +internal fun cascadeDeformerChannels(local: DeformerChannels, parent: DeformerWorld?): DeformerChannels { + val parentOpacity = parent?.accumulatedOpacity ?: 1f + val parentMultiply = parent?.accumulatedMultiplyColor ?: ColorRgb.MultiplyIdentity + val parentScreen = parent?.accumulatedScreenColor ?: ColorRgb.ScreenIdentity + return DeformerChannels( + opacity = local.opacity * parentOpacity, + multiplyColor = + ColorRgb( + local.multiplyColor.red * parentMultiply.red, + local.multiplyColor.green * parentMultiply.green, + local.multiplyColor.blue * parentMultiply.blue, + ), + screenColor = + ColorRgb( + screenCompose(local.screenColor.red, parentScreen.red), + screenCompose(local.screenColor.green, parentScreen.green), + screenCompose(local.screenColor.blue, parentScreen.blue), + ), + ) +} + +/** + * The screen operator on one channel: `a + b - a*b`. + * + * @param Float a One operand. + * @param Float b The other. + * @return Float The screened channel. + */ +internal fun screenCompose(a: Float, b: Float): Float = a + b - a * b + +/** + * A warp deformer's world transform: its baked world control points + lattice mode. The control-point + * fields are `internal` (not `private`) so the GPU renderer in this module can upload them as the + * shader's lattice uniforms - the same baked data the CPU `apply` walks via [warpApply]. + */ +internal class WarpWorld( + internal val cp: FloatArray, + internal val cols: Int, + internal val rows: Int, + internal val bilinear: Boolean, + override val accY: Float, + override val accumulatedOpacity: Float = 1f, + override val accumulatedMultiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + override val accumulatedScreenColor: ColorRgb = ColorRgb.ScreenIdentity, +) : DeformerWorld { + /** + * Warp-transforms `(x, y)` through the baked lattice. + * + * @param Float x Input x. + * @param Float y Input y. + * @param FloatArray out Destination. + * @param Int outIndex Index of the x slot. + */ + override fun apply(x: Float, y: Float, out: FloatArray, outIndex: Int) { + warpApply(cp, cols, rows, bilinear, x, y, out, outIndex) + } +} + +/** A rotation deformer's world transform: a baked affine. [xform] is `internal` so the GPU renderer can + * upload its 6 coefficients as shader uniforms (the same affine the CPU `apply` evaluates). */ +internal class RotationWorld( + internal val xform: RotationXform, + override val accY: Float, + override val accumulatedOpacity: Float = 1f, + override val accumulatedMultiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + override val accumulatedScreenColor: ColorRgb = ColorRgb.ScreenIdentity, +) : DeformerWorld { + /** + * Applies the rotation affine to `(x, y)`. + * + * @param Float x Input x. + * @param Float y Input y. + * @param FloatArray out Destination. + * @param Int outIndex Index of the x slot. + */ + override fun apply(x: Float, y: Float, out: FloatArray, outIndex: Int) { + xform.apply(x, y, out, outIndex) + } +} + +/** + * Builds every deformer's world transform top-down (parents first), composing each local + * keyform-blended transform with its parent's world transform. + * + * Out-of-range (hidden) deformers, and any whose ancestor is hidden, are omitted from the result. At + * default parameters nothing is hidden, so this only affects out-of-range poses. + * + * @param List deformers All deformers in the model. + * @param Function paramValue Current value for a given parameter id. + * @param Function defaultValue Default value for a given parameter id (the blend-shape delta reference pose). + * @param Map channelOverrides Pending unkeyed channel edits, which win over a deformer's stored channel value. + * @return Map The built world transforms, keyed by deformer id. + */ +internal fun buildDeformerWorlds( + deformers: List, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float = paramValue, + channelOverrides: Map = emptyMap(), +): Map { + val worlds = HashMap(deformers.size) + val ids = deformers.mapTo(HashSet()) { it.id } + var pending = deformers + var passes = 0 + while (pending.isNotEmpty() && passes <= deformers.size + 2) { + passes++ + val deferred = ArrayList() + var built = false + for (deformer in pending) { + val parentId = deformer.parent + val parentKnown = parentId == null || parentId !in ids || parentId in worlds + if (!parentKnown) { + deferred.add(deformer) + continue + } + val parentWorld = parentId?.let { worlds[it] } + val world = buildDeformerWorld(deformer, paramValue, defaultValue, parentWorld, channelOverrides) + if (world != null) { + worlds[deformer.id] = world + built = true + } + } + if (!built) { + break // no progress: the rest are hidden or orphaned + } + pending = deferred + } + return worlds +} + +/** + * Builds one deformer's world transform given its parent's (or null at the root). + * + * @param Deformer deformer The deformer. + * @param Function paramValue Current value for a given parameter id. + * @param Function defaultValue Default value for a given parameter id (the blend-shape delta reference pose). + * @param DeformerWorld? parentWorld The parent's world transform, or null. + * @param Map channelOverrides Pending unkeyed channel edits, which win over a deformer's stored channel value. + * @return DeformerWorld? The world transform, or null when hidden. + */ +private fun buildDeformerWorld( + deformer: Deformer, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, + parentWorld: DeformerWorld?, + channelOverrides: Map, +): DeformerWorld? = + when (deformer) { + is Deformer.Warp -> buildWarpWorld(deformer, paramValue, defaultValue, parentWorld, channelOverrides) + is Deformer.Rotation -> buildRotationWorld(deformer, paramValue, defaultValue, parentWorld, channelOverrides) + } + +/** + * Builds a warp's world transform: blend its keyform control points, then push each through the parent + * (warps inherit the parent's accY; they add no scale of their own). + * + * @param Deformer.Warp warp The warp deformer. + * @param Function paramValue Current value for a given parameter id. + * @param Function defaultValue Default value for a given parameter id (the blend-shape delta reference pose). + * @param DeformerWorld? parentWorld The parent's world transform, or null. + * @param Map channelOverrides Pending unkeyed channel edits, which win over the warp's stored channel value. + * @return DeformerWorld? The world transform, or null when hidden. + */ +private fun buildWarpWorld( + warp: Deformer.Warp, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, + parentWorld: DeformerWorld?, + channelOverrides: Map, +): DeformerWorld? { + val grid = warp.geometryGrid ?: return null + val corners = gridCorners(grid, paramValue) ?: return null + val cells = cellsByLinearIndex(grid) + val pointCount = (warp.rows + 1) * (warp.columns + 1) + val cp = FloatArray(pointCount * 2) + for (corner in corners) { + val controlPoints = cells[corner.linearIndex]?.form?.controlPoints ?: continue + val count = minOf(cp.size, controlPoints.size) + for (coordIndex in 0 until count) { + cp[coordIndex] += corner.weight * controlPoints[coordIndex] + } + } + // Blend shapes: additive control-point deltas on top of the grid blend, before parent transforms. + warpBlendDeltas(warp, paramValue, defaultValue)?.let { deltas -> + val count = minOf(cp.size, deltas.size) + for (coordIndex in 0 until count) { + cp[coordIndex] += deltas[coordIndex] + } + } + // The render channels are blended, never snapped to the nearest key, or they step instead of fading + // at mid-parameter values. Each track resolves its own corners; pre-compaction those are the same + // corners in the same order as the control points', so the sums are unchanged. + // A constant null in the steady state (no pending edit), so the per-channel lookups below allocate + // no KeyableTarget keys on the per-frame path. + val warpOverride: (FormChannel) -> ChannelValue? = + if (channelOverrides.isEmpty()) { + { null } + } else { + { channel -> channelOverrides[KeyableTarget(KeyformOwner.Deformer(warp.id), channel)] } + } + val channels = + cascadeDeformerChannels( + withBlendChannelDeltas( + DeformerChannels( + warp.channelGrids.scalarAt(FormChannel.OPACITY, warp.opacity, paramValue, warpOverride(FormChannel.OPACITY)), + warp.channelGrids.colorAt( + FormChannel.MULTIPLY_COLOR, + warp.multiplyColor, + paramValue, + warpOverride(FormChannel.MULTIPLY_COLOR), + ), + warp.channelGrids.colorAt( + FormChannel.SCREEN_COLOR, + warp.screenColor, + paramValue, + warpOverride(FormChannel.SCREEN_COLOR), + ), + ), + deformerBlendChannelDeltas( + warp.blendShapes, + warp.channelGrids, + warp.opacity, + warp.multiplyColor, + warp.screenColor, + paramValue, + defaultValue, + ) { form -> DeformerBlendChannelDeltas(form.opacity, form.multiplyColor, form.screenColor) }, + ), + parentWorld, + ) + val parentAccY = parentWorld?.accY ?: 1f + if (parentWorld != null) { + for (pointIndex in 0 until pointCount) { + parentWorld.apply(cp[pointIndex * 2], cp[pointIndex * 2 + 1], cp, pointIndex * 2) + } + } + return WarpWorld( + cp, + warp.columns, + warp.rows, + warp.isQuadTransform, + parentAccY, + channels.opacity, + channels.multiplyColor, + channels.screenColor, + ) +} + +/** + * Builds a rotation's world transform: blend its keyform origin/angle/scale (flip snaps to the first + * corner), compose scale with the parent's accY, and - for a non-root - derive the inherited angle by + * numerically probing the parent transform. + * + * @param Deformer.Rotation rotation The rotation deformer. + * @param Function paramValue Current value for a given parameter id. + * @param Function defaultValue Default value for a given parameter id (the blend-shape delta reference pose). + * @param DeformerWorld? parentWorld The parent's world transform, or null. + * @param Map channelOverrides Pending unkeyed channel edits, which win over the rotation's stored channel value. + * @return DeformerWorld? The world transform, or null when hidden. + */ +private fun buildRotationWorld( + rotation: Deformer.Rotation, + paramValue: (ParameterId) -> Float, + defaultValue: (ParameterId) -> Float, + parentWorld: DeformerWorld?, + channelOverrides: Map, +): DeformerWorld? { + val grid = rotation.geometryGrid ?: return null + val corners = gridCorners(grid, paramValue) ?: return null + val cells = cellsByLinearIndex(grid) + var originX = 0f + var originY = 0f + var scaleAccum = 0f + var angleAccum = 0f + for (corner in corners) { + val form = cells[corner.linearIndex]?.form ?: continue + originX += corner.weight * form.originX + originY += corner.weight * form.originY + scaleAccum += corner.weight * form.scale + angleAccum += corner.weight * form.angle + } + // The render channels blend, never snap to the nearest key (unlike the flip flags below, which are + // not interpolable and take the floor cell). + // A constant null in the steady state, so the lookups allocate nothing (see buildWarpWorld's note). + val rotationOverride: (FormChannel) -> ChannelValue? = + if (channelOverrides.isEmpty()) { + { null } + } else { + { channel -> channelOverrides[KeyableTarget(KeyformOwner.Deformer(rotation.id), channel)] } + } + val channels = + cascadeDeformerChannels( + withBlendChannelDeltas( + DeformerChannels( + rotation.channelGrids.scalarAt( + FormChannel.OPACITY, + rotation.opacity, + paramValue, + rotationOverride(FormChannel.OPACITY), + ), + rotation.channelGrids.colorAt( + FormChannel.MULTIPLY_COLOR, + rotation.multiplyColor, + paramValue, + rotationOverride(FormChannel.MULTIPLY_COLOR), + ), + rotation.channelGrids.colorAt( + FormChannel.SCREEN_COLOR, + rotation.screenColor, + paramValue, + rotationOverride(FormChannel.SCREEN_COLOR), + ), + ), + deformerBlendChannelDeltas( + rotation.blendShapes, + rotation.channelGrids, + rotation.opacity, + rotation.multiplyColor, + rotation.screenColor, + paramValue, + defaultValue, + ) { form -> DeformerBlendChannelDeltas(form.opacity, form.multiplyColor, form.screenColor) }, + ), + parentWorld, + ) + // Blend shapes: additive origin/scale/angle deltas on top of the grid blend (flip stays grid-only). + rotationBlendDeltas(rotation, paramValue, defaultValue)?.let { deltas -> + originX += deltas.originX + originY += deltas.originY + scaleAccum += deltas.scale + angleAccum += deltas.angle + } + // Reflections snap to the floor cell (corner 0 is the all-lower-key corner), which is what flagAt does. + val flipX = rotation.channelGrids.flagAt(FormChannel.FLIP_X, rotation.flipX, paramValue, rotationOverride(FormChannel.FLIP_X)) + val flipY = rotation.channelGrids.flagAt(FormChannel.FLIP_Y, rotation.flipY, paramValue, rotationOverride(FormChannel.FLIP_Y)) + val angleDegrees = rotation.baseAngle + angleAccum + val parentAccY = parentWorld?.accY ?: 1f + val scale = parentAccY * scaleAccum + val worldPivotX: Float + val worldPivotY: Float + val worldAngle: Float + if (parentWorld == null) { + worldPivotX = originX + worldPivotY = originY + worldAngle = angleDegrees + } else { + // Probe the parent's local rotation at the origin: displace along -Y and read the resulting + // direction. -10 step for a rotation parent, -0.1 for a warp (degenerate steps shrink ×0.1). + val disp = if (parentWorld is RotationWorld) -10f else -0.1f + val scratch = FloatArray(2) + parentWorld.apply(originX, originY, scratch, 0) + val worldPosX = scratch[0] + val worldPosY = scratch[1] + var dx = 0f + var dy = 0f + var probeScale = 1f + var iteration = 0 + while (iteration < 10) { + parentWorld.apply(originX, originY + disp * probeScale, scratch, 0) + dx = scratch[0] - worldPosX + dy = scratch[1] - worldPosY + if (dx != 0f || dy != 0f) { + break + } + parentWorld.apply(originX, originY - disp * probeScale, scratch, 0) + dx = worldPosX - scratch[0] + dy = worldPosY - scratch[1] + if (dx != 0f || dy != 0f) { + break + } + probeScale *= 0.1f + iteration++ + } + var inherited = atan2(disp.toDouble(), 0.0).toFloat() - atan2(dy.toDouble(), dx.toDouble()).toFloat() + while (inherited > PI_F) { + inherited -= 2f * PI_F + } + while (inherited < -PI_F) { + inherited += 2f * PI_F + } + worldPivotX = worldPosX + worldPivotY = worldPosY + worldAngle = angleDegrees - inherited * 180f / PI_F + } + return RotationWorld( + rotationXform(worldAngle, scale, flipX, flipY, worldPivotX, worldPivotY), + scale, + channels.opacity, + channels.multiplyColor, + channels.screenColor, + ) +} + +/** + * Deforms a deformer-parented mesh: blend its local vertices, push each through the parent deformer's + * world transform, then negate Y (reverse-coordinate). Returns null when the mesh is hidden. + * + * @param KeyformGrid grid The mesh's keyform grid. + * @param FloatArray base The mesh's rest-pose positions (interleaved x,y). + * @param DeformerWorld parent The mesh's parent deformer's world transform. + * @param Function paramValue Current value for a given parameter id. + * @return FloatArray? World positions (interleaved x,y), or null when hidden. + */ +internal fun deformMeshThroughParent(grid: KeyformGrid, base: FloatArray, parent: DeformerWorld, paramValue: (ParameterId) -> Float): FloatArray? { + val local = sampleMeshLocal(grid, base, paramValue) ?: return null + val world = FloatArray(local.size) + val vertexCount = local.size / 2 + for (vertexIndex in 0 until vertexCount) { + parent.apply(local[vertexIndex * 2], local[vertexIndex * 2 + 1], world, vertexIndex * 2) + world[vertexIndex * 2 + 1] = -world[vertexIndex * 2 + 1] + } + return world +} + +/** + * Deforms a mesh to world positions from precomputed corners: blend `base + Σ wᵢ·Δᵢ`, push each vertex + * through [parent] (or pass through when null - a direct, deformer-less mesh), then negate Y. This is the + * corners-first union of [deformMeshThroughParent] and `evalDirectMeshWorld`, fed by `preparePose`'s + * backend-neutral corner set; output is identical to the parameter-driven path. + * + * @param KeyformGrid grid The mesh's keyform grid. + * @param FloatArray base The mesh's rest-pose positions (interleaved x,y). + * @param List corners The active keyform corners + weights. + * @param DeformerWorld? parent The mesh's parent deformer world transform, or null when direct. + * @param MeshBlendState? blend The drawable's resolved blend-shape state, or null when binding-free. + * @return FloatArray World positions (interleaved x,y). + */ +internal fun deformMeshWorldFromCorners( + grid: KeyformGrid?, + base: FloatArray, + corners: List, + parent: DeformerWorld?, + blend: MeshBlendState? = null, +): FloatArray { + val local = blendLocalFromCorners(grid, base, corners) + // Blend shapes: additive per-vertex deltas (form minus the grid-at-default reference) on top of + // the grid blend, before the parent transform. Binding-free drawables never reach this loop. + if (blend != null) { + for (contribution in blend.contributions) { + val deltas = contribution.form.positionDeltas + val count = minOf(local.size, deltas.size) + for (componentIndex in 0 until count) { + val reference = blend.referenceDeltas?.get(componentIndex) ?: 0f + local[componentIndex] += contribution.weight * (deltas[componentIndex] - reference) + } + } + } + val world = FloatArray(local.size) + val vertexCount = local.size / 2 + for (vertexIndex in 0 until vertexCount) { + if (parent != null) { + parent.apply(local[vertexIndex * 2], local[vertexIndex * 2 + 1], world, vertexIndex * 2) + } else { + world[vertexIndex * 2] = local[vertexIndex * 2] + world[vertexIndex * 2 + 1] = local[vertexIndex * 2 + 1] + } + world[vertexIndex * 2 + 1] = -world[vertexIndex * 2 + 1] + } + return world +} + +/** + * Applies a deformer's blend-shape channel offsets onto its grid-blended channels. + * + * Additive like every other blend contribution, clamped to 0..1 only AFTER the sum so a record whose + * neighbours pull the other way is not biased. Returns [local] untouched when nothing contributes, + * which keeps the blend-free path allocation-identical to before. + * + * @param DeformerChannels local The deformer's own grid-blended channels. + * @param DeformerBlendChannelDeltas? deltas The summed blend offsets, or null when none apply. + * @return DeformerChannels The channels to cascade. + */ +internal fun withBlendChannelDeltas( + local: DeformerChannels, + deltas: DeformerBlendChannelDeltas?, +): DeformerChannels { + if (deltas == null) { + return local + } + return DeformerChannels( + (local.opacity + deltas.opacity).coerceIn(0f, 1f), + ColorRgb( + local.multiplyColor.red + deltas.multiplyColor.red, + local.multiplyColor.green + deltas.multiplyColor.green, + local.multiplyColor.blue + deltas.multiplyColor.blue, + ).coerceToUnit(), + ColorRgb( + local.screenColor.red + deltas.screenColor.red, + local.screenColor.green + deltas.screenColor.green, + local.screenColor.blue + deltas.screenColor.blue, + ).coerceToUnit(), + ) +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/DrawableSpaceMapping.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DrawableSpaceMapping.kt new file mode 100644 index 0000000..872bf50 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/DrawableSpaceMapping.kt @@ -0,0 +1,420 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.warpControlPointsAt +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.sqrt + +/** Newton iteration cap for the warp inverse; drag-sized motion converges in a handful of steps. */ +private const val WARP_INVERSE_MAX_ITERATIONS = 20 + +/** Finite-difference step (in the lattice's normalized UV units) for the warp inverse's Jacobian. */ +private const val WARP_INVERSE_JACOBIAN_STEP = 1e-4f + +/** Damping clamp on one Newton step (UV units), so an extrapolation seam cannot fling the estimate. */ +private const val WARP_INVERSE_MAX_STEP = 0.5f + +/** + * Iteration cap for the per-vertex reach-uncapped Newton in the world-rigid inverse. Higher than the + * damped [WARP_INVERSE_MAX_ITERATIONS] because there is no per-step clamp: a far target is reached by + * full Newton steps that re-anchor the Jacobian, converging in a handful once the estimate lands in the + * lattice's far-field affine region; the cap only bounds a pathological (folded / multivalued) case. + */ +private const val RIGID_INVERSE_MAX_ITERATIONS = 24 + +/** + * Maps between a drawable's local mesh space and the evaluator's world space at one fixed pose - the + * `DeformedGeometry.worldPositions` space the viewport camera and picker use. Local space is whatever + * the drawable's `DrawableMesh.positions` are stored in: model space for a direct (deformer-less) + * drawable, the parent's normalized lattice UV for a warp child, the parent's affine frame for a + * rotation child. The parent transform here is the FULLY COMPOSED chain (`buildDeformerWorlds` bakes + * every ancestor in), so both directions are a single transform, never a chain walk. + * + * The Edit-mode gizmo is the intended caller: it projects the active drawable's local shape to world + * for drawing and hit-testing (forward), and converts a world-space drag back into local vertex + * positions to write into the model (inverse). + * + * ドロウアブルのローカル座標と評価器のワールド座標を、固定ポーズで相互変換する。 + */ +class DrawableSpaceMapping internal constructor( + private val parentWorld: DeformerWorld?, +) { + /** + * Maps interleaved (x, y) local positions to world positions: the composed parent transform (or a + * pass-through for a direct drawable) followed by the renderer's Y negation - the exact composition + * of `deformMeshWorldFromCorners`. + * + * @param FloatArray local The interleaved local positions. + * @return FloatArray The interleaved world positions (a new array). + */ + fun localToWorld(local: FloatArray): FloatArray { + val world = FloatArray(local.size) + val vertexCount = local.size / 2 + for (vertexIndex in 0 until vertexCount) { + if (parentWorld != null) { + parentWorld.apply(local[vertexIndex * 2], local[vertexIndex * 2 + 1], world, vertexIndex * 2) + } else { + world[vertexIndex * 2] = local[vertexIndex * 2] + world[vertexIndex * 2 + 1] = local[vertexIndex * 2 + 1] + } + world[vertexIndex * 2 + 1] = -world[vertexIndex * 2 + 1] + } + return world + } + + /** + * Maps world positions back to local positions for the given vertex [indices], leaving every other + * vertex at its [seedLocal] value. The rotation affine inverts in closed form; the warp lattice + * inverts by damped Newton iteration on the forward transform, seeded per vertex from [seedLocal] + * (the vertex's own original UV), keeping the best estimate when it cannot converge - a vertex + * sticks rather than jumps. A degenerate transform (zero determinant) keeps the seed. + * + * @param FloatArray world The interleaved world positions to invert. + * @param FloatArray seedLocal The local positions to start from (and to keep for untouched vertices). + * @param Set indices The vertex indices to solve. + * @return FloatArray The interleaved local positions (a new array). + */ + fun worldToLocal(world: FloatArray, seedLocal: FloatArray, indices: Set): FloatArray { + val local = seedLocal.copyOf() + val scratch = FloatArray(2) + for (vertexIndex in indices) { + val coordIndex = vertexIndex * 2 + if (coordIndex + 1 >= world.size || coordIndex + 1 >= local.size) { + continue + } + // Un-negate Y first: the parent transforms operate in the pre-negate model space. + val targetX = world[coordIndex] + val targetY = -world[coordIndex + 1] + when (parentWorld) { + null -> { + local[coordIndex] = targetX + local[coordIndex + 1] = targetY + } + + is RotationWorld -> invertRotation(parentWorld, targetX, targetY, local, coordIndex) + is WarpWorld -> invertWarp(parentWorld, targetX, targetY, local, coordIndex, scratch) + } + } + return local + } + + /** + * Maps world positions back to local for the given vertex [indices] with a per-vertex EXACT inverse, + * leaving every other vertex at its [seedLocal] value. A direct parent inverts by pure Y un-negation and + * a rotation parent by its closed-form affine inverse (both one step); a warp parent inverts each vertex + * independently by a reach-uncapped Newton ([invertWarpUncapped]) seeded from its own rest UV, so every + * vertex lands on its own world target - the mesh stays rigid in world space (no squish), which the + * shared-Jacobian linearizations cannot achieve on a curved cage. + * + * Seeding each warp vertex from its rest UV keeps neighbours converging to nearby pre-images, so the + * result stays coherent (no scatter) wherever the forward map is injective. Where a target sits in a + * folded / multivalued extrapolation region the Newton keeps its best estimate near the seed rather than + * flinging - so a truly unreachable vertex lags instead of boiling. Not capping the per-step reach + * (unlike [invertWarp]) is what lets a large grab follow instead of pinning / ovalizing; the risk traded + * back is that a strongly non-injective cage can still scatter far outside the lattice (the reason the + * shared-Jacobian inverse exists). + * + * The warp tolerance and scratch are hoisted out of the vertex loop (constant per mapping), and the + * Newton early-exits the moment a vertex converges, so the whole-selection Object-mode grab (hundreds of + * warp vertices per drawable, over many drawables) stays interactive. A degenerate Jacobian (a + * zero-scale deformer) keeps the seed. + * + * @param FloatArray world The interleaved transformed world targets to invert. + * @param FloatArray seedLocal The rest local coords (per-vertex Newton seed; kept for untouched vertices). + * @param FloatArray worldRest The frozen pre-transform world positions (unused here; kept for the shared + * caller signature and the linearized-inverse contract). + * @param Set indices The vertex indices to solve. + * @return FloatArray The interleaved local positions (a new array). + */ + fun worldToLocalLinearized(world: FloatArray, seedLocal: FloatArray, worldRest: FloatArray, indices: Set): FloatArray { + val local = seedLocal.copyOf() + when (parentWorld) { + null -> { + for (vertexIndex in indices) { + val coordIndex = vertexIndex * 2 + if (coordIndex + 1 >= world.size || coordIndex + 1 >= local.size) { + continue + } + // Un-negate Y: the parent frame is the pre-negate model space. + local[coordIndex] = world[coordIndex] + local[coordIndex + 1] = -world[coordIndex + 1] + } + } + + is RotationWorld -> { + for (vertexIndex in indices) { + val coordIndex = vertexIndex * 2 + if (coordIndex + 1 >= world.size || coordIndex + 1 >= local.size) { + continue + } + invertRotation(parentWorld, world[coordIndex], -world[coordIndex + 1], local, coordIndex) + } + } + + is WarpWorld -> { + // Constant per mapping, so it's computed once here rather than per vertex. + val toleranceSquared = warpInverseToleranceSquared(parentWorld.cp) + val scratch = FloatArray(2) + for (vertexIndex in indices) { + val coordIndex = vertexIndex * 2 + if (coordIndex + 1 >= world.size || coordIndex + 1 >= local.size) { + continue + } + invertWarpUncapped(parentWorld, world[coordIndex], -world[coordIndex + 1], local, coordIndex, toleranceSquared, scratch) + } + } + } + return local + } + + /** + * Reach-uncapped world-rigid inverse of the warp lattice: solves `warpApply(u, v) = (targetX, targetY)` + * from the seed already in `local[coordIndex]`,`local[coordIndex+1]`, writing the best estimate back. + * Identical to [invertWarp] except it has no per-step damping clamp, so a full Newton step reaches a + * far target instead of pinning at [WARP_INVERSE_MAX_STEP], which keeps the mesh from pinning / + * ovalizing on a big grab. Allocation-free (reuses [scratch]) and early-exits at [toleranceSquared], so + * it stays cheap for a whole-selection Object-mode grab; [toleranceSquared] is passed in because it is + * constant per lattice. + * + * @param WarpWorld warp The baked world lattice. + * @param Float targetX The pre-negate world x to invert. + * @param Float targetY The pre-negate world y to invert. + * @param FloatArray local The output array, seeded with the starting UV at [coordIndex]. + * @param Int coordIndex Index of the u slot in [local]. + * @param Float toleranceSquared The squared convergence tolerance for this lattice. + * @param FloatArray scratch A reusable 2-slot scratch for forward evaluations. + */ + private fun invertWarpUncapped(warp: WarpWorld, targetX: Float, targetY: Float, local: FloatArray, coordIndex: Int, toleranceSquared: Float, scratch: FloatArray) { + var currentU = local[coordIndex] + var currentV = local[coordIndex + 1] + var bestU = currentU + var bestV = currentV + var bestErrorSquared = Float.MAX_VALUE + for (iteration in 0 until RIGID_INVERSE_MAX_ITERATIONS) { + warpApply(warp.cp, warp.cols, warp.rows, warp.bilinear, currentU, currentV, scratch, 0) + val residualX = scratch[0] - targetX + val residualY = scratch[1] - targetY + val errorSquared = residualX * residualX + residualY * residualY + if (errorSquared < bestErrorSquared) { + bestErrorSquared = errorSquared + bestU = currentU + bestV = currentV + } + if (errorSquared <= toleranceSquared) { + break + } + warpApply(warp.cp, warp.cols, warp.rows, warp.bilinear, currentU + WARP_INVERSE_JACOBIAN_STEP, currentV, scratch, 0) + val dxDu = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP + val dyDu = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP + warpApply(warp.cp, warp.cols, warp.rows, warp.bilinear, currentU, currentV + WARP_INVERSE_JACOBIAN_STEP, scratch, 0) + val dxDv = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP + val dyDv = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP + val determinant = dxDu * dyDv - dxDv * dyDu + if (abs(determinant) < 1e-12f) { + break + } + currentU += (-residualX * dyDv + dxDv * residualY) / determinant + currentV += (-residualY * dxDu + dyDu * residualX) / determinant + } + local[coordIndex] = bestU + local[coordIndex + 1] = bestV + } +} + +/** + * Builds the local<->world mapping for [drawableId] at the given pose, resolving parameters with the + * evaluator's fallback (`parameters[id] ?: parameter.default ?: 0`). Returns null when the drawable + * does not exist or its parent deformer's world transform cannot be built (a hidden ancestor) - the + * drawable is not on screen, so there is nothing to map onto. + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id -> value (partial; the rest default). + * @param DrawableId drawableId The drawable to map. + * @return DrawableSpaceMapping? The mapping, or null when unmappable. + */ +fun drawableSpaceMapping(model: PuppetModel, parameters: Map, drawableId: DrawableId): DrawableSpaceMapping? { + val drawable = model.drawables.firstOrNull { it.id == drawableId } ?: return null + val parentDeformerId = drawable.parentDeformerId ?: return DrawableSpaceMapping(null) + val defaults = model.parameters.associate { it.id to it.default } + val paramValue: (ParameterId) -> Float = { parameters[it] ?: defaults[it] ?: 0f } + val parentWorld = buildDeformerWorlds(model.deformers, paramValue)[parentDeformerId] ?: return null + return DrawableSpaceMapping(parentWorld) +} + +/** + * Maps a warp deformer's lattice-local control points to viewport world space the same way + * [drawableSpaceMapping] maps a child mesh: through the warp's PARENT chain, then the renderer's Y + * negation. Null when the warp is missing or its parent is hidden at this pose. + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id -> value (partial; the rest default). + * @param org.umamo.runtime.model.DeformerId deformerId The warp to map. + * @return DrawableSpaceMapping? The mapping, or null when unmappable. + */ +fun warpLatticeSpaceMapping( + model: PuppetModel, + parameters: Map, + deformerId: DeformerId, +): DrawableSpaceMapping? { + val deformer = model.deformers.firstOrNull { it.id == deformerId } as? Deformer.Warp ?: return null + val parentDeformerId = deformer.parent ?: return DrawableSpaceMapping(null) + val defaults = model.parameters.associate { it.id to it.default } + val paramValue: (ParameterId) -> Float = { parameters[it] ?: defaults[it] ?: 0f } + val parentWorld = buildDeformerWorlds(model.deformers, paramValue)[parentDeformerId] ?: return null + return DrawableSpaceMapping(parentWorld) +} + +/** + * The warp's blended lattice-local control points at [parameters], or null when the warp is unkeyed / + * hidden. Same space [WarpLatticeForm] stores - parent-local, before the parent chain and Y flip. + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id -> value. + * @param DeformerId deformerId The warp. + * @return FloatArray? Interleaved local control points, or null. + */ +fun warpLatticeLocalAt( + model: PuppetModel, + parameters: Map, + deformerId: DeformerId, +): FloatArray? { + val deformer = model.deformers.firstOrNull { it.id == deformerId } as? Deformer.Warp ?: return null + val defaults = model.parameters.associate { it.id to it.default } + val paramValue: (ParameterId) -> Float = { parameters[it] ?: defaults[it] ?: 0f } + return warpControlPointsAt(deformer.geometryGrid, paramValue)?.copyOf() +} + +/** + * The drawable's blended LOCAL posed positions at the given pose - base plus the multilinear keyform + * blend, before any parent deformer. This is the local shape the renderer feeds the deformer chain, so + * a display that projects it through [DrawableSpaceMapping.localToWorld] lands exactly on the rendered + * art at ANY pose (including between keys, where a single cell's deltas would not). + * + * @param PuppetModel model The rig. + * @param Map parameters Parameter id -> value (partial; the rest default). + * @param DrawableId drawableId The drawable to sample. + * @return FloatArray? The interleaved local posed positions, or null when the drawable / mesh / grid is + * missing or the pose hides it (out of range). + */ +fun drawableLocalPosed(model: PuppetModel, parameters: Map, drawableId: DrawableId): FloatArray? { + val drawable = model.drawables.firstOrNull { it.id == drawableId } ?: return null + val mesh = drawable.mesh ?: return null + // An unkeyed drawable sits at its rest mesh, which is exactly the state a rigger needs the gizmo to + // show - returning null here would hide the vertices of the drawable they are about to key. + val grid = drawable.geometryGrid ?: return mesh.positions.copyOf() + val defaults = model.parameters.associate { it.id to it.default } + val paramValue: (ParameterId) -> Float = { parameters[it] ?: defaults[it] ?: 0f } + return sampleMeshLocal(grid, mesh.positions, paramValue) +} + +/** + * Closed-form inverse of the baked rotation affine `x' = c12*x + c15*y + ox, y' = c14*x + c13*y + oy`, + * writing the solved local point to `local[coordIndex]`,`local[coordIndex+1]`. A near-zero determinant + * (a zero-scale deformer) keeps the seed untouched. + * + * @param RotationWorld rotation The baked world affine. + * @param Float targetX The pre-negate world x to invert. + * @param Float targetY The pre-negate world y to invert. + * @param FloatArray local The output array (seeded; written only on success). + * @param Int coordIndex Index of the x slot in [local]. + */ +private fun invertRotation(rotation: RotationWorld, targetX: Float, targetY: Float, local: FloatArray, coordIndex: Int) { + val xform = rotation.xform + val determinant = xform.c12 * xform.c13 - xform.c15 * xform.c14 + if (abs(determinant) < 1e-12f) { + return + } + val relativeX = targetX - xform.ox + val relativeY = targetY - xform.oy + local[coordIndex] = (relativeX * xform.c13 - xform.c15 * relativeY) / determinant + local[coordIndex + 1] = (xform.c12 * relativeY - xform.c14 * relativeX) / determinant +} + +/** + * Damped Newton inverse of the warp lattice: solves `warpApply(u, v) = target` starting from the seed + * already in `local[coordIndex]`,`local[coordIndex+1]`, using a finite-difference Jacobian. Writes the + * best estimate found (by residual) back into [local]; the tolerance scales with the lattice's control + * point extent so convergence means sub-art-pixel accuracy at any canvas size. + * + * @param WarpWorld warp The baked world lattice. + * @param Float targetX The pre-negate world x to invert. + * @param Float targetY The pre-negate world y to invert. + * @param FloatArray local The output array, seeded with the starting UV. + * @param Int coordIndex Index of the u slot in [local]. + * @param FloatArray scratch A reusable 2-slot scratch for forward evaluations. + */ +private fun invertWarp(warp: WarpWorld, targetX: Float, targetY: Float, local: FloatArray, coordIndex: Int, scratch: FloatArray) { + val toleranceSquared = warpInverseToleranceSquared(warp.cp) + var currentU = local[coordIndex] + var currentV = local[coordIndex + 1] + var bestU = currentU + var bestV = currentV + var bestErrorSquared = Float.MAX_VALUE + for (iteration in 0 until WARP_INVERSE_MAX_ITERATIONS) { + warpApply(warp.cp, warp.cols, warp.rows, warp.bilinear, currentU, currentV, scratch, 0) + val residualX = scratch[0] - targetX + val residualY = scratch[1] - targetY + val errorSquared = residualX * residualX + residualY * residualY + if (errorSquared < bestErrorSquared) { + bestErrorSquared = errorSquared + bestU = currentU + bestV = currentV + } + if (errorSquared <= toleranceSquared) { + break + } + warpApply(warp.cp, warp.cols, warp.rows, warp.bilinear, currentU + WARP_INVERSE_JACOBIAN_STEP, currentV, scratch, 0) + val dxDu = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP + val dyDu = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP + warpApply(warp.cp, warp.cols, warp.rows, warp.bilinear, currentU, currentV + WARP_INVERSE_JACOBIAN_STEP, scratch, 0) + val dxDv = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP + val dyDv = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP + val determinant = dxDu * dyDv - dxDv * dyDu + if (abs(determinant) < 1e-12f) { + break + } + var stepU = (-residualX * dyDv + dxDv * residualY) / determinant + var stepV = (-residualY * dxDu + dyDu * residualX) / determinant + val stepLength = sqrt(stepU * stepU + stepV * stepV) + if (stepLength > WARP_INVERSE_MAX_STEP) { + val damping = WARP_INVERSE_MAX_STEP / stepLength + stepU *= damping + stepV *= damping + } + currentU += stepU + currentV += stepV + } + local[coordIndex] = bestU + local[coordIndex + 1] = bestV +} + +/** + * The squared convergence tolerance for the warp inverse, scaled to the lattice's control-point extent + * (1e-5 of the larger bounding-box span, floored well above float noise). + * + * @param FloatArray cp The lattice's world control points, interleaved x,y. + * @return Float The squared world-distance tolerance. + */ +private fun warpInverseToleranceSquared(cp: FloatArray): Float { + var minX = Float.MAX_VALUE + var maxX = -Float.MAX_VALUE + var minY = Float.MAX_VALUE + var maxY = -Float.MAX_VALUE + val pointCount = cp.size / 2 + for (pointIndex in 0 until pointCount) { + val x = cp[pointIndex * 2] + val y = cp[pointIndex * 2 + 1] + minX = minOf(minX, x) + maxX = maxOf(maxX, x) + minY = minOf(minY, y) + maxY = maxOf(maxY, y) + } + val span = max(maxX - minX, maxY - minY) + val tolerance = max(1e-5f * span, 1e-6f) + return tolerance * tolerance +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/KeyformBlend.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/KeyformBlend.kt new file mode 100644 index 0000000..40b1de7 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/KeyformBlend.kt @@ -0,0 +1,21 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.Keyform + +/** + * Multilinear blend for a single parameter axis: `base + Σ wᵢ·Δᵢ`. + * + * A 1-D isolation of the blend math also used, generalized to N dimensions, by the real keyform-grid + * blend in [blendLocalFromCorners]. Kept as a free function so it's trivially testable on its own. + * + * 単一パラメータ軸の多重線形ブレンド。実 N 次元評価の 1 次元プレースホルダ。 + */ +fun blend(base: FloatArray, keyforms: List>): FloatArray { + val result = base.copyOf() + for ((weight, keyform) in keyforms) { + for (i in result.indices) { + result[i] += weight * keyform.delta[i] + } + } + return result +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/KeyformGridEval.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/KeyformGridEval.kt new file mode 100644 index 0000000..3e0d431 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/KeyformGridEval.kt @@ -0,0 +1,105 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.eval.gridCorners +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId + +/* + * Grid sampling over the runtime's shared multilinear corner selection. The corner selection, + * bracket, and pose-sampling primitives (bindBracket / gridCorners / cellsByLinearIndex / + * plus the blend-shape default-pose reference helpers) live in + * org.umamo.runtime.eval (KeyformGridSampling.kt) so Moc3Import shares them - see the note there. + * This file keeps the render-side blends built on top of them. + */ + +/** + * Samples an art-mesh keyform grid into local (parent-deformer-space) vertex positions: + * `base + Σ wᵢ·Δᵢ` (interleaved x,y). Because the corner weights sum to 1, this equals the + * Umamo C++ Runtime's absolute-keyform blend. Returns null when the mesh is hidden at + * these parameters. + * + * @param KeyformGrid grid The mesh's keyform grid. + * @param FloatArray base The mesh's rest-pose positions. + * @param Function paramValue Current value for a given parameter id. + * @return FloatArray? The local vertex positions, or null when hidden. + */ +internal fun sampleMeshLocal( + grid: KeyformGrid, + base: FloatArray, + paramValue: (ParameterId) -> Float, +): FloatArray? { + val corners = gridCorners(grid, paramValue) ?: return null + return blendLocalFromCorners(grid, base, corners) +} + +/** + * Blends a mesh's local positions from precomputed corners: `base + Σ wᵢ·Δᵢ`. Splitting corner selection + * out of [sampleMeshLocal] lets `preparePose` compute the weights once - backend-neutrally - and feed both + * the CPU apply path and (later) the GPU shader the same corner set. + * + * A null [grid] is an UNKEYED drawable, not an error: it contributes no deltas, so the result is the rest + * mesh. An unkeyed drawable is a normal state - a freshly created one, or one whose last keyform axis was + * just removed - and it has to render, or the rigger cannot see the thing they are about to key. + * + * @param KeyformGrid? grid The mesh's keyform grid, or null when the drawable is unkeyed. + * @param FloatArray base The mesh's rest-pose positions (interleaved x,y). + * @param List corners The active keyform corners + weights (from [gridCorners]). + * @return FloatArray The blended local positions (interleaved x,y). + */ +internal fun blendLocalFromCorners(grid: KeyformGrid?, base: FloatArray, corners: List): FloatArray { + val cells = if (grid != null) cellsByLinearIndex(grid) else emptyMap() + val out = base.copyOf() + for (corner in corners) { + val delta = cells[corner.linearIndex]?.form?.positionDeltas ?: continue + val count = minOf(out.size, delta.size) + for (coordIndex in 0 until count) { + out[coordIndex] += corner.weight * delta[coordIndex] + } + } + return out +} + +/** + * An isolated part's pose-blended composite channels - what the renderer applies when it + * composites the part's subtree layer back into the scene. + * + * @property Float opacity The composite opacity (0..1). + * @property ColorRgb multiplyColor The composite multiply color. + * @property ColorRgb screenColor The composite screen color. + */ +internal class PartRenderState( + val opacity: Float, + val multiplyColor: ColorRgb, + val screenColor: ColorRgb, +) + +/** + * Evaluates a direct (deformer-less) art mesh into world positions: the keyform-blended local + * vertices with the Y component negated (`vp = (x, −y)`; only Y flips). This matches the CMO3/MOC3 + * world-space convention, which is Y-down relative to the local mesh space Umamo blends in - required for + * preview parity with the official Cubism Editor. Returns null when the mesh is hidden at these + * parameters. Deformer-parented meshes go through the cascade instead, which applies the same negation + * after composing through the parent transform. + * + * @param KeyformGrid grid The mesh's keyform grid. + * @param FloatArray base The mesh's rest-pose positions (interleaved x,y). + * @param Function paramValue Current value for a given parameter id. + * @return FloatArray? World positions (interleaved x,y), or null when hidden. + */ +internal fun evalDirectMeshWorld( + grid: KeyformGrid, + base: FloatArray, + paramValue: (ParameterId) -> Float, +): FloatArray? { + val world = sampleMeshLocal(grid, base, paramValue) ?: return null + var yIndex = 1 + while (yIndex < world.size) { + world[yIndex] = -world[yIndex] + yIndex += 2 + } + return world +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/eval/RenderOrder.kt b/module/render/src/commonMain/kotlin/org/umamo/render/eval/RenderOrder.kt new file mode 100644 index 0000000..47228d1 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/eval/RenderOrder.kt @@ -0,0 +1,147 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode + +/** + * A node of the resolved per-pose render plan: the back-to-front order WITH the isolated group + * boundaries preserved. A plain Grouped part needs no boundary (its children flatten into the + * surrounding order, exactly one slot's worth) - only an ISOLATED group becomes a node, because + * the renderer must know which span of drawables renders into a layer and composites back as one + * unit. Nesting is direct: a composite node's children may contain further composite nodes. + */ +sealed interface RenderPlanNode + +/** A drawable drawn directly into the current render target. */ +class RenderPlanDrawable(val id: DrawableId) : RenderPlanNode + +/** + * An isolated part's subtree: render [children] (back-to-front) into a layer, then composite that + * layer back as one unit using [composite]'s blend modes/masks and the pose's blended channels + * (PoseDeformInputs.partCompositeStates keyed by [partId]). + */ +class RenderPlanComposite( + val partId: PartId, + val composite: PartComposite, + val children: List, +) : RenderPlanNode + +/** + * The per-pose render plan over the draw-order group tree: [renderOrder]'s hierarchical sort with + * isolated group boundaries kept as [RenderPlanComposite] nodes. Plain groups flatten away + * exactly as before - `renderOrder` IS this plan flattened, so the two can never disagree. + * + * @param RenderGroup root The draw-order group tree root (`PuppetModel.renderRoot`). + * @param Map drawOrder Blended draw order per drawable (missing → the Cubism default). + * @param Map partDrawOrders Blended per-group part draw order (missing → the static value). + * @return List The plan nodes, back-to-front. + */ +fun renderPlan( + root: RenderGroup, + drawOrder: Map, + partDrawOrders: Map = emptyMap(), +): List { + fun sortKey(node: RenderNode): Int = + when (node) { + is RenderDrawable -> ((drawOrder[node.id] ?: DEFAULT_DRAW_ORDER.toFloat()) + 0.001f).toInt() + is RenderGroup -> node.partId?.let { partDrawOrders[it] }?.let { (it + 0.001f).toInt() } ?: node.drawOrder + } + + fun emit(group: RenderGroup, into: ArrayList) { + for (child in group.children.sortedBy(::sortKey)) { + when (child) { + is RenderDrawable -> into.add(RenderPlanDrawable(child.id)) + is RenderGroup -> { + val composite = child.composite + val partId = child.partId + if (composite != null && partId != null) { + val subtree = ArrayList() + emit(child, subtree) + into.add(RenderPlanComposite(partId, composite, subtree)) + } else { + emit(child, into) + } + } + } + } + } + + val nodes = ArrayList() + emit(root, nodes) + return nodes +} + +/** + * Flattens a render plan to its drawables in back-to-front order (composite boundaries dropped). + * + * @param List nodes The plan nodes. + * @return List The drawables, back-to-front. + */ +fun flattenRenderPlan(nodes: List): List { + val result = ArrayList() + + fun walk(node: RenderPlanNode) { + when (node) { + is RenderPlanDrawable -> result.add(node.id) + is RenderPlanComposite -> node.children.forEach(::walk) + } + } + nodes.forEach(::walk) + return result +} + +/** + * The back-to-front paint order for one pose, computed hierarchically over the draw-order group tree. + * Within each [RenderGroup] the children are stably sorted by an int sort key (a [RenderDrawable] by + * its own quantised draw order, a sub-[RenderGroup] by the part's draw order), then emitted depth-first. + * So a drawable's draw order only sorts it among its group siblings, and a "Group by Draw Order" part + * moves as a unit - a child can't escape the group's slot. + * + * A group-less model is one flat group of all drawables, so this reduces exactly to [paintOrder]'s global + * sort. Quantisation (`+0.001`→int) matches the Umamo C++ runtime and de-noises tied float draw orders + * (see [paintOrder]). + * + * A sub-group's key is its part draw order, which can itself be parameter-driven ([partDrawOrders]) + * - blended per pose, quantised the same way; missing → the group's static [RenderGroup.drawOrder]. + * So whole groups swap front/back as their controlling parameters move. + * + * @param RenderGroup root The draw-order group tree root (`PuppetModel.renderRoot`). + * @param Map drawOrder Blended draw order per drawable (missing → the Cubism default). + * @param Map partDrawOrders Blended per-group part draw order (missing → the static value). + * @return List The drawables in back-to-front paint order. + */ +fun renderOrder( + root: RenderGroup, + drawOrder: Map, + partDrawOrders: Map = emptyMap(), +): List = flattenRenderPlan(renderPlan(root, drawOrder, partDrawOrders)) + +/** + * The back-to-front paint order for one pose. [baseOrder] is the model's parts-tree (panel) drawable + * order - already back-to-front when draw orders are equal - and this stably re-sorts it by the + * per-drawable blended [drawOrder], the primary key. A higher draw order paints later (in front) across + * the whole model regardless of part; equal draw orders keep [baseOrder]. This mirrors how the Cubism + * editor stacks drawables (drawOrder first, the parts tree breaking ties). + * + * Quantise to int before sorting: (`drawDrawOrders[i] = (int)(0.001f + drawOrder)`). + * Draw order is authored as an integer (0-1000, default 500); the multilinear keyform blend + * `Σ wᵢ·orderᵢ` only lands near an integer (float-summation gives e.g. 499.99997 vs 500.00003), so + * sorting the raw float reshuffles drawables that should be tied - a sub-ULP-noise reorder that makes a + * coincident-order drawable (e.g. a masked head shadow at 500) flicker in front of the face at the + * parameter values where the noise crosses. Flooring `+0.001` collapses the noise to a true tie so the + * stable sort preserves [baseOrder]; the `+0.001` rescues a value sitting just below its intended integer. + * + * Because draw order rides on the keyform, it is param-dependent - pass the [DeformedGeometry.drawOrder] + * for the current pose, so a parameter that animates stacking reorders correctly per frame. + * + * @param List baseOrder The model's drawables, in parts-tree back-to-front order. + * @param Map drawOrder Blended draw order per drawable (missing → the Cubism default). + * @return List The drawables in back-to-front paint order. + */ +fun paintOrder(baseOrder: List, drawOrder: Map): List = + baseOrder.sortedBy { ((drawOrder[it] ?: DEFAULT_DRAW_ORDER.toFloat()) + 0.001f).toInt() } \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/glsl/BackdropShaders.kt b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/BackdropShaders.kt new file mode 100644 index 0000000..ae60bf4 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/BackdropShaders.kt @@ -0,0 +1,131 @@ +package org.umamo.render.glsl + +// The canvas backdrop's GLSL - the world-aligned grid and the world-origin axis lines. +// +// These were previously hand-copied between the desktop and Android backends, identical but for the +// preamble, with nothing pinning the two together. They had already begun to drift: the Android copies +// had silently lost three of the explanatory comments. Only comments so far, which is precisely why +// merging them now was worth doing - the next divergence would have been in the math, and nothing would +// have caught it. +// +// Metal shares none of this; see GlslDialect. + +/** + * The full-screen pass's vertex shader: one oversized triangle covering the viewport. + * + * No vertex buffer - the three corners are derived from `gl_VertexID`, so no attributes are needed (and + * on a core profile, only an empty VAO). + * + * 頂点バッファ無しの全画面パス。三角形の頂点は gl_VertexID から生成する。 + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun gridVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + """ + void main() { + // id 0 -> (-1,-1), 1 -> (-1,3), 2 -> (3,-1): one oversized triangle covering the viewport. + gl_Position = vec4(float(gl_VertexID / 2) * 4.0 - 1.0, float(gl_VertexID % 2) * 4.0 - 1.0, 0.0, 1.0); + } + """.trimIndent() + +/** + * The world-aligned grid backdrop's fragment shader. + * + * Each fragment recovers its world position by inverting the same world-to-NDC affine the puppet is + * projected through, then draws anti-aliased lines wherever that world coord is near a multiple of the + * major or minor spacing. Colors and spacings arrive as uniforms so the backdrop follows the editor + * theme and the per-document grid config. Opaque, so it both clears and paints in one pass. + * + * ワールド整列グリッド。worldToNdc を逆変換して各フラグメントのワールド座標を求め、主線・副線を描く。 + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun gridFragmentShader(dialect: GlslDialect): String = + glslHeader(dialect) + + """ + out vec4 fragColor; + uniform vec2 viewportSize; + uniform vec4 worldToNdc; // scaleX, scaleY, offsetX, offsetY + uniform vec2 majorSpacing; // world units per major cell, per axis + uniform float subdivisions; // minor lines per major cell + uniform float lineWidthPx; // line half-width in framebuffer pixels + uniform vec3 backgroundColor; + uniform vec3 majorColor; + uniform vec3 minorColor; + uniform vec2 gridOrigin; // world point a major line passes through (the world axes) + + // Anti-aliased line coverage for a coordinate on a lattice of the given spacing. cellDist is the + // fractional distance to the nearest line in cell units (0 on a line, 0.5 mid-cell); scaling it by + // spacing / worldPerPixel converts it to framebuffer pixels, so the band stays a constant on-screen + // width at any zoom - derived from the affine, not GLSL derivatives, so it is driver-independent. + float lineCoverage(vec2 world, vec2 spacing, vec2 worldPerPixel) { + vec2 cell = world / spacing; + vec2 cellDist = abs(fract(cell - 0.5) - 0.5); + vec2 pixelDist = cellDist * spacing / worldPerPixel; + float nearestPx = min(pixelDist.x, pixelDist.y); + return 1.0 - smoothstep(0.0, lineWidthPx, nearestPx); + } + + void main() { + vec2 ndc = (gl_FragCoord.xy / viewportSize) * 2.0 - 1.0; + vec2 world = (ndc - worldToNdc.zw) / worldToNdc.xy; + // World units per framebuffer pixel, from the affine: an NDC span of 2 covers viewportSize pixels + // and worldToNdc.xy world units per NDC unit. abs() drops the Y-axis flip sign. + vec2 worldPerPixel = abs((2.0 / viewportSize) / worldToNdc.xy); + // Anchor the lattice on the world origin (the axes), so a major line always crosses the axes + // rather than falling mid-cell for an arbitrary canvas size. + vec2 gridWorld = world - gridOrigin; + vec2 minorSpacing = majorSpacing / max(subdivisions, 1.0); + // Fade the minor lines out as their on-screen spacing collapses, so a zoomed-out grid does not + // alias into a solid wash: minorScreenPx is the minor spacing measured in framebuffer pixels. + vec2 minorScreenPx = minorSpacing / worldPerPixel; + float minorFade = clamp((min(minorScreenPx.x, minorScreenPx.y) - 4.0) / 8.0, 0.0, 1.0); + float minor = lineCoverage(gridWorld, minorSpacing, worldPerPixel) * minorFade; + float major = lineCoverage(gridWorld, majorSpacing, worldPerPixel); + vec3 color = mix(backgroundColor, minorColor, minor); + color = mix(color, majorColor, major); + fragColor = vec4(color, 1.0); + } + """.trimIndent() + +/** + * One world-origin axis line's vertex shader. + * + * The two endpoints come from `gl_VertexID` (-1 / +1 along the line); the fixed coordinate and the + * orientation arrive as uniforms, so one program draws both axes. + * + * 軸線 1 本を描くパス。端点は gl_VertexID から生成し、固定座標と向きは uniform で受け取る。 + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun axisVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + """ + uniform float linePositionNdc; + uniform float lineVertical; + void main() { + float along = float(gl_VertexID) * 2.0 - 1.0; + vec2 position = mix(vec2(along, linePositionNdc), vec2(linePositionNdc, along), lineVertical); + gl_Position = vec4(position, 0.0, 1.0); + } + """.trimIndent() + +/** + * The axis line's fragment shader: a flat, opaque line color. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun axisFragmentShader(dialect: GlslDialect): String = + glslHeader(dialect) + + """ + out vec4 fragColor; + uniform vec3 lineColor; + void main() { + fragColor = vec4(lineColor, 1.0); + } + """.trimIndent() \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/glsl/CompositeShaders.kt b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/CompositeShaders.kt new file mode 100644 index 0000000..095a047 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/CompositeShaders.kt @@ -0,0 +1,250 @@ +package org.umamo.render.glsl + +// The layer-composite program's GLSL, shared by the GL-family backends. +// +// The fragment shader is a line-for-line mirror of the pure reference in +// org.umamo.render.puppet.BlendMath (`compositeReference`) - the reference is the spec, the +// analytic GL tests compare read-back pixels against it, and any change must land in both. +// Formulas are the PUBLIC standards only (W3C Compositing and Blending Level 1, Porter-Duff, +// X Render conjoint/disjoint); nothing here is derived from the official Cubism SDK. + +/** + * The composite vertex shader: an attribute-less full-screen triangle from `gl_VertexID` + * (draw 3 vertices with an empty VAO, like the grid backdrop). + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun compositeVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + "void main() {\n" + + " vec2 corner = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));\n" + + " gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);\n" + + "}\n" + +/** + * The composite fragment shader: samples the rendered layer and the destination snapshot at the + * fragment's screen position, applies the composite's channels (opacity, mask coverage, + * multiply/screen colors) to the layer, then computes the color blend B(Cb, Cs) and the alpha + * mode's Porter-Duff combination in-shader, writing premultiplied with blending DISABLED. + * + * The colorMode/alphaMode ints are the MOC3 packed halves (colorMode 0-17, alphaMode 0-4). The legacy + * "(Before 5.3)" Add/Multiply (colorMode 1/2) take the fixed-function premultiplied branch regardless of + * the alpha mode (they ignore Alpha blend, per BlendMath.compositeReference); Normal (0) does so only + * under Over. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun compositeFragmentShader(dialect: GlslDialect): String = + glslHeader(dialect) + + """ + out vec4 fragColor; + uniform sampler2D layerTexture; + uniform sampler2D destTexture; + uniform sampler2D maskTexture; + uniform vec2 screenTexSize; + uniform int colorMode; + uniform int alphaMode; + uniform float opacity; + uniform vec3 multiplyColor; + uniform vec3 screenColor; + uniform int useMask; + uniform int invertMask; + + float lum3(vec3 c) { + return 0.3 * c.r + 0.59 * c.g + 0.11 * c.b; + } + + vec3 clipColor3(vec3 c) { + float l = lum3(c); + float n = min(c.r, min(c.g, c.b)); + float x = max(c.r, max(c.g, c.b)); + if (n < 0.0) { + c = l + (c - l) * l / (l - n); + } + if (x > 1.0) { + c = l + (c - l) * (1.0 - l) / (x - l); + } + return c; + } + + vec3 setLum3(vec3 c, float l) { + return clipColor3(c + (l - lum3(c))); + } + + float sat3(vec3 c) { + return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); + } + + vec3 setSat3(vec3 c, float s) { + float mn = min(c.r, min(c.g, c.b)); + float mx = max(c.r, max(c.g, c.b)); + return (mx > mn) ? (c - mn) * s / (mx - mn) : vec3(0.0); + } + + float hardLightChannel(float base, float selector) { + float doubled = 2.0 * selector - 1.0; + return (selector <= 0.5) ? 2.0 * selector * base : base + doubled - base * doubled; + } + + float softLightD(float x) { + return (x <= 0.25) ? ((16.0 * x - 12.0) * x + 4.0) * x : sqrt(x); + } + + float blendChannel(float b, float s) { + if (colorMode == 1 || colorMode == 3 || colorMode == 4) { + //Additive Premultiplied, Additive, Additive Glow + return min(1.0, b + s); + } + + if (colorMode == 2 || colorMode == 6) { + //Multiply + return b * s; + } + + if (colorMode == 5) { + //Darken + return min(b, s); + } + + if (colorMode == 7) { + //Color Burn + return (b >= 1.0) ? 1.0 : ((s <= 0.0) ? 0.0 : 1.0 - min(1.0, (1.0 - b) / s)); + } + + if (colorMode == 8) { + //Linear Burn + return max(0.0, b + s - 1.0); + } + + if (colorMode == 9) { + //Lighten + return max(b, s); + } + + if (colorMode == 10) { + //Screen + return b + s - b * s; + } + + if (colorMode == 11) { + //Color Doge + return (b <= 0.0) ? 0.0 : ((s >= 1.0) ? 1.0 : min(1.0, b / (1.0 - s))); + } + + if (colorMode == 12) { + //Overlay + return hardLightChannel(s, b); + } + + if (colorMode == 13) { + //Soft Light + return (s <= 0.5) ? b - (1.0 - 2.0 * s) * b * (1.0 - b) : b + (2.0 * s - 1.0) * (softLightD(b) - b); + } + + if (colorMode == 14) { + //Hard Light + return hardLightChannel(b, s); + } + + if (colorMode == 15) { + //Linear Light + return clamp(b + 2.0 * s - 1.0, 0.0, 1.0); + } + + return s; + } + + vec3 blendColor3(vec3 Cb, vec3 Cs) { + if (colorMode == 16) { + return setLum3(setSat3(Cs, sat3(Cb)), lum3(Cb)); + } + + if (colorMode == 17) { + return setLum3(Cs, lum3(Cb)); + } + + return vec3(blendChannel(Cb.r, Cs.r), blendChannel(Cb.g, Cs.g), blendChannel(Cb.b, Cs.b)); + } + + void main() { + vec2 screenUv = gl_FragCoord.xy / screenTexSize; + vec4 layer = texture(layerTexture, screenUv); + vec4 dest = texture(destTexture, screenUv); + float layerScale = opacity; + + if (useMask == 1) { + float coverage = texture(maskTexture, screenUv).a; + layerScale *= (invertMask == 1) ? (1.0 - coverage) : coverage; + } + + layer *= layerScale; + float as = layer.a; + float ab = dest.a; + vec3 Cs = (as > 0.0) ? clamp(layer.rgb / as, 0.0, 1.0) : vec3(0.0); + Cs = Cs * multiplyColor; + Cs = Cs + screenColor - Cs * screenColor; + vec3 Cb = (ab > 0.0) ? clamp(dest.rgb / ab, 0.0, 1.0) : vec3(0.0); + vec4 outColor; + + if (colorMode == 1 || colorMode == 2 || (alphaMode == 0 && colorMode == 0)) { + //Repremultiply after tinting. + vec3 srcPremul = Cs * as; + + if (colorMode == 0) { + //Standard premultiplied source over. + outColor = vec4(srcPremul + dest.rgb * (1.0 - as), as + ab * (1.0 - as)); + } else if (colorMode == 1) { + //Legacy Add + outColor = vec4(srcPremul + dest.rgb, ab); + } else { + //Legacy Multiply + outColor = vec4(srcPremul * dest.rgb + dest.rgb * (1.0 - as), ab); + } + } else { + float p0 = as * ab; //Uncorrelated (OVER/ATOP): w == ab, the same as W3C. + + if (alphaMode == 3) { + //CONJOINT, maximal overlap. + p0 = min(as, ab); + } else if (alphaMode == 4) { + //DISJOINT, minimal overlap. + p0 = max(as + ab - 1.0, 0.0); + } + + float w = (as > 0.0) ? p0 / as : 0.0; + //W3C Cs' = (1-w)*Cs + w*B(Cb, Cs). The specification's uncorrelated case has w = ab. + vec3 mixed = (1.0 - w) * Cs + w * blendColor3(Cb, Cs); + + //Porter-Duff: co = as*Fa*Cs' + ab*Fb*Cb (premultiplied), ao = as*Fa + ab*Fb. The whole branch expands to p0*B + p1*Cs + p2*Cb with the KHR p-weights for the selected overlap mode. + float Fa; + float Fb; + + if (alphaMode == 1) { + //SRC-ATOP: output keeps canvas alpha (ao = ab) + Fa = ab; + Fb = 1.0 - as; + } else if (alphaMode == 2) { + //DST-OUT: ao = ab*(1-as); Fa = 0 so 'mixed' is unused. + Fa = 0.0; + Fb = 1.0 - as; + } else if (alphaMode == 3) { + //CONJOINT: ao = max(as, ab) + Fa = 1.0; + Fb = (ab <= 0.0 || as >= ab) ? 0.0 : 1.0 - as / ab; + } else if (alphaMode == 4) { + //DISJOINT: ao = min(1, as + ab) + Fa = 1.0; + Fb = (ab <= 0.0) ? 0.0 : min(1.0, (1.0 - as) / ab); + } else { + //OVER + Fa = 1.0; + Fb = 1.0 - as; + } + outColor = vec4(as * Fa * mixed + ab * Fb * Cb, as * Fa + ab * Fb); + } + //UNORM target, also bounds legacy add. + fragColor = clamp(outColor, 0.0, 1.0); + } + """.trimIndent() \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/glsl/DeformGlsl.kt b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/DeformGlsl.kt new file mode 100644 index 0000000..806409f --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/DeformGlsl.kt @@ -0,0 +1,261 @@ +package org.umamo.render.glsl + +/** + * The shared GLSL for Umamo's GPU deformation - the per-vertex morph + deformer cascade. Both the live + * renderer (`PuppetRenderer`, which projects the result to `gl_Position`) and the GPU-vs-CPU + * transform-feedback test (which captures the world position) prepend their own `#version` + in/out + * declarations and `main`, then call [deformWorld]. Sharing this snippet means the test exercises the + * exact deform math the renderer ships, not a hand-kept copy. + * + * The uniforms it declares are filled per pose from the backend-neutral `PoseDeformInputs`: + * - [deltaTex] - RG = a keyform cell's per-vertex delta; texel (col = cell linear index, row = vertex id). + * - cornerCount / cornerCell[] / cornerWeight[] - the active multilinear corners + weights. + * - parentType / rot[] / cpTex / warp* - the baked parent-deformer transform (0 direct, 1 rotation, 2 warp). + */ +internal const val DEFORM_GLSL = + """ + uniform sampler2D deltaTex; + uniform int cornerCount; + uniform int cornerCell[$MAX_CORNERS]; + uniform float cornerWeight[$MAX_CORNERS]; + uniform int blendCount; + uniform int blendCell[$MAX_BLEND_CORNERS]; + uniform float blendWeight[$MAX_BLEND_CORNERS]; + uniform int parentType; + uniform float rot[6]; + uniform sampler2D cpTex; + uniform int warpCols; + uniform int warpRows; + uniform int warpBilinear; + + vec2 cpAt(int index) { + int pointsPerRow = warpCols + 1; + return texelFetch(cpTex, ivec2(index % pointsPerRow, index / pointsPerRow), 0).rg; + } + + vec2 warpExtrap(vec2 uv) { + int pointsPerRow = warpCols + 1; + int lastRowBase = warpRows * pointsPerRow; + vec2 topLeft = cpAt(0); + vec2 topRight = cpAt(warpCols); + vec2 botLeft = cpAt(lastRowBase); + vec2 botRight = cpAt(warpCols + lastRowBase); + float gridU = float(warpCols) * uv.x; + float gridV = float(warpRows) * uv.y; + vec2 deltaU = ((botRight - topLeft) + (topRight - botLeft)) * 0.5; + vec2 deltaV = ((botRight - topLeft) - (topRight - botLeft)) * 0.5; + vec2 origin = (topLeft + topRight + botLeft + botRight) * 0.25 - (botRight - topLeft) * 0.5; + if (uv.x <= -2.0 || uv.x >= 3.0 || uv.y <= -2.0 || uv.y >= 3.0) { + return origin + deltaU * uv.x + deltaV * uv.y; + } + float blendU = 0.0; + float blendV = 0.0; + vec2 corner0 = vec2(0.0); + vec2 corner1 = vec2(0.0); + vec2 corner2 = vec2(0.0); + vec2 corner3 = vec2(0.0); + if (uv.x <= 0.0) { + blendU = (uv.x + 2.0) * 0.5; + corner3 = origin - 2.0 * deltaU; + if (uv.y <= 0.0) { + corner2 = topLeft; + blendV = (uv.y + 2.0) * 0.5; + corner1 = origin - 2.0 * deltaV; + corner0 = corner3 - 2.0 * deltaV; + } else if (uv.y < 1.0) { + int loIdx = int(gridV); + float edgeHi; + int hiIdx; + if (warpRows == loIdx) { + loIdx = warpRows - 1; + hiIdx = warpRows; + edgeHi = float(warpRows); + } else { + hiIdx = loIdx + 1; + edgeHi = float(loIdx + 1); + } + blendV = gridV - float(loIdx); + float edgeLo = float(loIdx) / float(warpRows); + corner1 = cpAt(loIdx * pointsPerRow); + corner2 = cpAt(hiIdx * pointsPerRow); + corner0 = edgeLo * deltaV + corner3; + corner3 = (edgeHi / float(warpRows)) * deltaV + corner3; + } else { + corner1 = botLeft; + blendV = (uv.y - 1.0) * 0.5; + corner0 = corner3 + deltaV; + corner3 = 3.0 * deltaV + corner3; + corner2 = 3.0 * deltaV + origin; + } + } else if (uv.x < 1.0) { + if (uv.y <= 0.0) { + int loIdx = int(gridU); + vec2 edge; + float edgeHi; + if (warpCols == loIdx) { + loIdx = warpCols - 1; + edge = topRight; + edgeHi = float(warpCols); + } else { + edge = cpAt(loIdx + 1); + edgeHi = float(loIdx + 1); + } + blendV = (uv.y + 2.0) * 0.5; + blendU = gridU - float(loIdx); + float edgeLo = float(loIdx) / float(warpCols); + corner3 = cpAt(loIdx); + corner2 = edge; + corner0 = (edgeLo * deltaU + origin) - 2.0 * deltaV; + corner1 = ((edgeHi / float(warpCols)) * deltaU + origin) - 2.0 * deltaV; + } else if (uv.y >= 1.0) { + int loIdx = int(gridU); + float edgeHi; + int hiIdx; + if (warpCols == loIdx) { + loIdx = warpCols - 1; + hiIdx = warpCols; + edgeHi = float(warpCols); + } else { + hiIdx = loIdx + 1; + edgeHi = float(loIdx + 1); + } + blendV = (uv.y - 1.0) * 0.5; + blendU = gridU - float(loIdx); + float edgeLo = float(loIdx) / float(warpCols); + corner0 = cpAt(loIdx + lastRowBase); + corner1 = cpAt(lastRowBase + hiIdx); + corner2 = (edgeHi / float(warpCols)) * deltaU + origin + 3.0 * deltaV; + corner3 = edgeLo * deltaU + origin + 3.0 * deltaV; + } else { + return origin + deltaU * uv.x + deltaV * uv.y; + } + } else { + blendU = (uv.x - 1.0) * 0.5; + corner2 = 3.0 * deltaU + origin; + if (uv.y <= 0.0) { + corner3 = topRight; + blendV = (uv.y + 2.0) * 0.5; + corner0 = (origin + deltaU) - 2.0 * deltaV; + corner1 = corner2 - 2.0 * deltaV; + } else if (uv.y < 1.0) { + int loIdx = int(gridV); + float edgeHi; + int hiIdx; + if (warpRows == loIdx) { + loIdx = warpRows - 1; + hiIdx = warpRows; + edgeHi = float(warpRows); + } else { + hiIdx = loIdx + 1; + edgeHi = float(loIdx + 1); + } + blendV = gridV - float(loIdx); + corner0 = cpAt(loIdx * pointsPerRow + warpCols); + corner3 = cpAt(hiIdx * pointsPerRow + warpCols); + float edgeLo = float(loIdx) / float(warpRows); + corner1 = edgeLo * deltaV + corner2; + corner2 = (edgeHi / float(warpRows)) * deltaV + corner2; + } else { + corner0 = botRight; + blendV = (uv.y - 1.0) * 0.5; + corner1 = corner2 + deltaV; + corner3 = origin + deltaU + 3.0 * deltaV; + corner2 = 3.0 * deltaV + corner2; + } + } + if (blendU + blendV <= 1.0) { + return (corner1 - corner0) * blendU + corner0 + (corner3 - corner0) * blendV; + } + return (corner3 - corner2) * (1.0 - blendU) + corner2 + (corner1 - corner2) * (1.0 - blendV); + } + + // Warp lattice map of normalized (u,v): in-grid bilinear/triangle blend of the 4 surrounding control + // points, else warpExtrap's full edge-blend extrapolation outside the lattice (ported from the CPU). + vec2 warpDeform(vec2 uv) { + int pointsPerRow = warpCols + 1; + if (uv.x >= 0.0 && uv.y >= 0.0 && uv.x < 1.0 && uv.y < 1.0) { + float gridU = float(warpCols) * uv.x; + float gridV = float(warpRows) * uv.y; + int cellU = int(gridU); + int cellV = int(gridV); + float fu = gridU - float(cellU); + float fv = gridV - float(cellV); + int cell = cellV * pointsPerRow + cellU; + vec2 p00 = cpAt(cell); + vec2 p10 = cpAt(cell + 1); + vec2 p01 = cpAt(cell + pointsPerRow); + vec2 p11 = cpAt(cell + pointsPerRow + 1); + if (warpBilinear == 0) { + if (fu + fv <= 1.0) { + return p10 * fu + p00 * (1.0 - fu - fv) + p01 * fv; + } + float w = (fu - 1.0) + fv; + return p01 * (1.0 - fu) + p11 * w + p10 * (1.0 - fv); + } + float ifv = 1.0 - fv; + return p10 * (fu * ifv) + p00 * ((1.0 - fu) * ifv) + p01 * ((1.0 - fu) * fv) + p11 * (fu * fv); + } + return warpExtrap(uv); + } + + // Full per-vertex deform: blend base + Σ wᵢ·Δᵢ (active cells fetched from deltaTex by gl_VertexID), + // push through the parent transform (rotation affine / warp lattice / none), then negate Y. Glue is + // not applied here (a cross-mesh post-pass) - matches the CPU deform before its glue weld. + vec2 deformWorld(vec2 base) { + vec2 local = base; + for (int corner = 0; corner < cornerCount && corner < $MAX_CORNERS; corner++) { + vec2 delta = texelFetch(deltaTex, ivec2(cornerCell[corner], gl_VertexID), 0).rg; + local += cornerWeight[corner] * delta; + } + // Blend shapes: additive delta columns appended after the grid cells in deltaTex, weighted + // per pose (zero-blend models keep blendCount == 0 and skip the loop entirely). + for (int blendCorner = 0; blendCorner < blendCount && blendCorner < $MAX_BLEND_CORNERS; blendCorner++) { + vec2 blendDelta = texelFetch(deltaTex, ivec2(blendCell[blendCorner], gl_VertexID), 0).rg; + local += blendWeight[blendCorner] * blendDelta; + } + vec2 world; + if (parentType == 1) { + world = vec2(rot[3] * local.y + rot[0] * local.x + rot[4], + local.y * rot[1] + local.x * rot[2] + rot[5]); + } else if (parentType == 2) { + world = warpDeform(local); + } else { + world = local; + } + world.y = -world.y; + return world; + } + """ + +/** + * The transform-feedback deform shader: runs [DEFORM_GLSL]'s `deformWorld` and captures the result as + * `outWorld` (no projection). + * + * Used by the renderer's glue pass 1 to write every glue mesh's deformed world positions into the shared + * position buffer, and by the GPU-vs-CPU validation test - which is the point: the test pins the exact + * deform body that ships, not a copy of it. Its varying `outWorld` must be registered via + * `glTransformFeedbackVaryings` before linking. + * + * Transform feedback is core in GL 3.3 AND GLES 3.0, so both dialects can run this as-is. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun tfDeformVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + "layout(location = 0) in vec2 inBase;\n" + + "out vec2 outWorld;\n" + + DEFORM_GLSL.trimIndent() + "\n" + + "void main() {\n" + + " outWorld = deformWorld(inBase);\n" + + " gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n" + + "}\n" + +/** + * The do-nothing fragment stage the transform-feedback program links against - it captures vertices and + * rasterizes nothing, but a program still needs a fragment shader to link. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun tfDiscardFragmentShader(dialect: GlslDialect): String = glslHeader(dialect) + "void main() {}\n" \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/glsl/GlslDialect.kt b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/GlslDialect.kt new file mode 100644 index 0000000..92d2b75 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/GlslDialect.kt @@ -0,0 +1,35 @@ +package org.umamo.render.glsl + +/** + * A GLSL flavor one of the GL-family backends compiles. + * + * The sources in this package are shared by the desktop GL 3.3 core backend and the Android GLES 3.0 + * one, which want the same bodies behind different preambles. A Metal backend shares NOTHING here - MSL + * is a different language, supplied by that backend - so this enum is deliberately GL-family only rather + * than pretending to be a backend-neutral shader abstraction. + * + * GL 系(デスクトップ GL 3.3 / Android GLES 3.0)のシェーダ方言。Metal は MSL を別途持つ。 + */ +internal enum class GlslDialect { + /** Desktop OpenGL 3.3 core profile. */ + Core330, + + /** OpenGL ES 3.0 - the Android baseline (3.0 is the floor because VAOs and gl_VertexID need it). */ + Es300, +} + +/** + * The `#version` preamble for [dialect], including the precision qualifiers ES requires. + * + * ES has no default precision for floats or ints in a fragment shader, so omitting these is a compile + * error there and a silent no-op on desktop - which is exactly the sort of divergence that made keeping + * two hand-copied shader sets untenable. + * + * @param GlslDialect dialect The target flavor. + * @return String The preamble, newline-terminated. + */ +internal fun glslHeader(dialect: GlslDialect): String = + when (dialect) { + GlslDialect.Core330 -> "#version 330 core\n" + GlslDialect.Es300 -> "#version 300 es\nprecision highp float;\nprecision highp int;\n" + } \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/glsl/PuppetShaders.kt b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/PuppetShaders.kt new file mode 100644 index 0000000..7130db4 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/PuppetShaders.kt @@ -0,0 +1,195 @@ +package org.umamo.render.glsl + +// The puppet render programs' GLSL, shared by the GL-family backends. +// +// Each builder returns a READY-TO-COMPILE source: the preamble is already applied and there is no +// `trimIndent()` left for a caller to remember. That is deliberate - the sources these replaced were +// trimmed inconsistently (inside the backdrop's `link`, at the call site for the fragment shader, and +// not at all for the concatenated vertex shaders), which is a trap with no upside. +// +// Metal shares none of this; see GlslDialect. + +/** + * The live-render vertex shader: deforms via [DEFORM_GLSL]'s `deformWorld`, then projects. + * + * The deform body is shared with the glue pass-1 capture shader and the GPU-vs-CPU validation test, so + * all three exercise identical math rather than three hand-kept copies. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun puppetVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + "layout(location = 0) in vec2 inBase;\n" + // rest-pose position (parent-deformer-local space) + "layout(location = 1) in vec2 inUv;\n" + // atlas texture coordinate (CMO3 [0,1]) + "uniform vec4 worldToNdc;\n" + // (scaleX, scaleY, offsetX, offsetY) - the camera's world→NDC affine + "out vec2 vUv;\n" + + DEFORM_GLSL.trimIndent() + "\n" + + "void main() {\n" + + " vUv = inUv;\n" + + " vec2 world = deformWorld(inBase);\n" + + " gl_Position = vec4(world.x * worldToNdc.x + worldToNdc.z, world.y * worldToNdc.y + worldToNdc.w, 0.0, 1.0);\n" + + "}\n" + +/** + * The glue pass-2 vertex shader: welds against pass-1's shared positions, then projects. + * + * Positions are NOT deformed here - pass 1 already wrote them to the shared position buffer (world + * space, post-Y-flip). Each vertex reads its own deformed position and, when it is a glued seam vertex, + * its partner's, and applies `own + (partner − own)·w·intensity` on the GPU, matching the CPU + * `applyGluesResolved`. Non-glued vertices pass through unchanged. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + * @warning The [GlslDialect.Es300] output is NOT compilable as-is: `samplerBuffer` is GLES 3.2, and the + * Android baseline is 3.0. Making it portable means repacking the shared position buffer as a regular + * 2D texture indexed `(i % width, i / width)` - see TODO.md § Android GLES renderer backend option (b). + * The parameter is accepted here so the seam exists, not because ES works today. + */ +internal fun glueVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + "layout(location = 1) in vec2 inUv;\n" + + "layout(location = 2) in int inPartnerIndex;\n" + // partner vertex's global index, or own when not glued + "layout(location = 3) in int inGlueIndex;\n" + // which glue (for its per-pose intensity), or -1 + "layout(location = 4) in float inWeldWeight;\n" + // this vertex's weld weight (0 when not glued) + "uniform vec4 worldToNdc;\n" + + "uniform samplerBuffer positionBuffer;\n" + // RG = pass-1 deformed world positions, by global index + "uniform int baseOffset;\n" + // this mesh's base index in positionBuffer + "uniform float glueIntensity[$MAX_GLUES];\n" + + "out vec2 vUv;\n" + + "void main() {\n" + + " vUv = inUv;\n" + + " vec2 own = texelFetch(positionBuffer, baseOffset + gl_VertexID).rg;\n" + + " vec2 world = own;\n" + + // Skip the partner read when the weld is a no-op: a zero per-pose intensity also flags an unposed + // partner (set CPU-side), whose position-buffer region is uninitialised - so it is never read. + " if (inGlueIndex >= 0 && inWeldWeight != 0.0 && glueIntensity[inGlueIndex] != 0.0) {\n" + + " vec2 partner = texelFetch(positionBuffer, inPartnerIndex).rg;\n" + + " vec2 welded = own + (partner - own) * (inWeldWeight * glueIntensity[inGlueIndex]); if (welded.x == welded.x && welded.y == welded.y && distance(welded, own) < 100000.0) { world = welded; }\n" + + " }\n" + + " gl_Position = vec4(world.x * worldToNdc.x + worldToNdc.z, world.y * worldToNdc.y + worldToNdc.w, 0.0, 1.0);\n" + + "}\n" + +/** + * The shared puppet fragment shader: samples the bound art texture through the stored-to-sampled uv + * affine (or a flat color), applies the clip mask, tints the selection highlight, and writes + * PREMULTIPLIED alpha (`rgb * alpha, alpha`) - which is why every blend mode's source factor is `GL_ONE`. + * + * A linear art texture is filtered in-shader, in premultiplied space: four `texelFetch` taps, each + * weighted by its own coverage, then converted back to straight color for the tint math. Art is stored + * straight, and the hardware filter averages straight colors, so an alpha edge takes on whatever color + * the neighboring transparent texels hold - black on every CMO3 layer image, and on any page composed + * from them - as a dark, texel-stepped fringe. Because the taps bypass the sampler, the shader applies + * the texture's wrap itself, told by the `atlasTransparentBorder` flag; a nearest texture reads one + * texel, where the two color spaces agree, so it keeps the hardware lookup. A port must keep this + * filter rather than trade it back for a plain `texture()` call. + * + * The mask is sampled by `gl_FragCoord.xy / screenTexSize` - screen space, with the divisor the mask + * texture's ALLOCATED size (equal to the viewport size only when the texture is exactly viewport-sized; + * side targets are grow-only, so it is usually the high-water capacity). The coverage pass renders at + * the same origin-anchored viewport, so fragment (x, y) reads coverage texel (x, y) exactly. That is + * self-consistent under either framebuffer origin convention (GL's bottom-left, Metal's top-left) and so + * needs no per-dialect flip; it only holds while the mask pass and this pass share a convention, which a + * port must keep true. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun puppetFragmentShader(dialect: GlslDialect): String = + glslHeader(dialect) + + """ + in vec2 vUv; + out vec4 fragColor; + uniform sampler2D atlas; + uniform int useTexture; + uniform vec4 drawColor; + uniform float opacity; + uniform int useMask; + uniform sampler2D maskTexture; + uniform vec2 screenTexSize; + uniform int invertMask; + uniform vec3 multiplyColor; + uniform vec3 screenColor; + uniform float highlight; + uniform vec3 highlightColor; + // The stored-to-sampled texture-coordinate affine, as two row vectors (m00 m01 m02 / m10 m11 m12). + // Rows rather than a mat3 because the value arrives row-major and a GLSL mat3 is column-major - + // passing rows keeps one convention end to end, and transliterates to MSL unchanged. Identity + // for a drawable sampling the atlas it was authored against. + uniform vec3 uvAffineRow0; + uniform vec3 uvAffineRow1; + // How the bound art texture was created: 1 when it filters linearly (0 nearest), and 1 when it + // wraps to a transparent border (0 to its edge texels). + uniform int atlasLinear; + uniform int atlasTransparentBorder; + // One art texel, premultiplied. A texel outside the image reads as the texture's wrap says. + vec4 premultipliedTexel(ivec2 texel, ivec2 size) { + if (atlasTransparentBorder == 1 && (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, size)))) { + return vec4(0.0); + } + vec4 straight = texelFetch(atlas, clamp(texel, ivec2(0), size - ivec2(1)), 0); + return vec4(straight.rgb * straight.a, straight.a); + } + // The art at a texture coordinate, as straight color. Linear filtering blends the four surrounding + // texels premultiplied, so a transparent texel's color never reaches the edge it borders. + vec4 sampleArt(vec2 uv) { + if (atlasLinear == 0) { + return texture(atlas, uv); + } + ivec2 size = textureSize(atlas, 0); + vec2 corner = uv * vec2(size) - 0.5; + vec2 cornerFloor = floor(corner); + vec2 fraction = corner - cornerFloor; + ivec2 origin = ivec2(cornerFloor); + vec4 firstRow = mix(premultipliedTexel(origin, size), premultipliedTexel(origin + ivec2(1, 0), size), fraction.x); + vec4 secondRow = mix(premultipliedTexel(origin + ivec2(0, 1), size), premultipliedTexel(origin + ivec2(1, 1), size), fraction.x); + vec4 premultiplied = mix(firstRow, secondRow, fraction.y); + if (premultiplied.a <= 0.0) { + return vec4(0.0); + } + return vec4(min(premultiplied.rgb / premultiplied.a, vec3(1.0)), premultiplied.a); + } + void main() { + vec3 uvHomogeneous = vec3(vUv, 1.0); + vec2 sampleUv = vec2(dot(uvAffineRow0, uvHomogeneous), dot(uvAffineRow1, uvHomogeneous)); + vec4 base = (useTexture == 1) ? sampleArt(sampleUv) : drawColor; + float alpha = base.a * opacity; + if (useMask == 1) { + float coverage = texture(maskTexture, gl_FragCoord.xy / screenTexSize).a; + alpha *= (invertMask == 1) ? (1.0 - coverage) : coverage; + } + vec3 tinted = base.rgb * multiplyColor; + tinted = tinted + screenColor - tinted * screenColor; + vec3 rgb = mix(tinted, highlightColor, highlight); + fragColor = vec4(rgb * alpha, alpha); + } + """.trimIndent() + +/** + * The UV editor's underlay vertex shader, for an atlas page or a source-layer image. + * + * Emits the underlay rectangle's four corners from `gl_VertexID` (no vertex buffer, only an empty VAO), + * directly in Y-up display / texel space - world X in [0, W], Y in [0, H] - with NO Cubism Y negation + * (unlike `deformWorld`: the image is placed straight into the already-Y-up display space). The UVs carry + * the V-flip so the image's V=0 (its top texel row) lands at the top of the Y-up quad - corner (0, H) -> + * uv (0, 0) - matching UvDisplayMapping's `displayY = (1-v)*H`. Projects through the same worldToNdc + * affine as the puppet. + * + * That V-flip is a CONTENT convention (Y-up display vs top-first image rows), not a backend one, so it is + * identical in MSL - a Metal port must keep it, not "correct" it for Metal's top-left texture origin. + * + * @param GlslDialect dialect The target flavor. + * @return String The ready-to-compile source. + */ +internal fun atlasPageVertexShader(dialect: GlslDialect): String = + glslHeader(dialect) + + "uniform vec4 worldToNdc;\n" + // (scaleX, scaleY, offsetX, offsetY) - the camera's world→NDC affine + "uniform vec2 pageSize;\n" + // the underlay image's size in texels (W, H) + "out vec2 vUv;\n" + + "void main() {\n" + + " float cornerX = float(gl_VertexID & 1);\n" + // 0,1,0,1 across the triangle strip + " float cornerY = float((gl_VertexID >> 1) & 1);\n" + // 0,0,1,1 + " vec2 world = vec2(cornerX * pageSize.x, cornerY * pageSize.y);\n" + + " vUv = vec2(cornerX, 1.0 - cornerY);\n" + // V-flip: display top (Y=H) samples the image's top row (v=0) + " gl_Position = vec4(world.x * worldToNdc.x + worldToNdc.z, world.y * worldToNdc.y + worldToNdc.w, 0.0, 1.0);\n" + + "}\n" \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/glsl/ShaderContract.kt b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/ShaderContract.kt new file mode 100644 index 0000000..4cf5610 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/glsl/ShaderContract.kt @@ -0,0 +1,58 @@ +package org.umamo.render.glsl + +// The limits and binding points the shader sources and the backends must agree on. +// +// These are a CONTRACT, not tuning knobs: each is interpolated into the GLSL below and read by the +// backend that fills the matching uniform, so the two cannot be changed independently. They live here, +// beside the sources that interpolate them, precisely so that stays true - [MAX_CORNERS] previously sat +// in the desktop renderer while the GLSL hardcoded a bare `16` in three places, which meant changing the +// constant silently disagreed with the shader. + +/** + * The most keyform-grid corners a single mesh's morph can blend at once. + * + * A hard ceiling, not a guess: it sizes the `cornerCell` / `cornerWeight` uniform arrays, so a mesh with + * more active corners has the surplus dropped rather than blended. 16 corners is a 4-dimensional + * keyform grid (2^4). + */ +internal const val MAX_CORNERS = 16 + +/** + * The most blend-shape delta columns a single mesh can have active at once. + * + * Sizes the `blendCell` / `blendWeight` uniform arrays - the additive blend-shape pass's analogue + * of [MAX_CORNERS], kept SEPARATE so zero-blend models keep exactly the pre-blend uniform traffic. + * Corpus maximum is 18 active forms (Model C: 9 bindings x 2 bracketing keys); 32 gives headroom at a + * worst-case cost of 64 uniform components against GL 3.3 / GLES 3.0's guaranteed 1024. Surplus + * contributions are dropped deterministically, with the same cap applied CPU-side. + */ +internal const val MAX_BLEND_CORNERS = 32 + +/** + * The most glue affecters one model can weld on the GPU. + * + * Sizes the `glueIntensity` uniform array. A model's glue #65 and beyond render UNWELDED rather than + * failing - the renderer drops them when resolving the pose. A shader contract, so raising it means + * raising the array here and re-checking the uniform budget, not just editing a number. + */ +internal const val MAX_GLUES = 64 + +/** + * How strongly a selected drawable tints toward the selection accent (0 = untinted, 1 = fully the accent). + * A subtle wash, so the art stays readable under the highlight. + */ +internal const val SELECTION_TINT_STRENGTH = 0.35f + +// Texture units, shared across every program so the per-mesh deform uniforms can be set the same way +// regardless of which program is bound. atlas/mask are fragment-stage; delta/cp/position are +// vertex-stage (texture fetch). +internal const val UNIT_ATLAS = 0 +internal const val UNIT_MASK = 1 +internal const val UNIT_DELTA = 2 +internal const val UNIT_CP = 3 +internal const val UNIT_POSITION = 4 + +// The composite pass's two extra fragment samplers: the rendered layer (the isolated subtree's +// buffer) and the destination snapshot it blends against. +internal const val UNIT_LAYER = 5 +internal const val UNIT_DEST = 6 \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/pick/Picker.kt b/module/render/src/commonMain/kotlin/org/umamo/render/pick/Picker.kt new file mode 100644 index 0000000..233e642 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/pick/Picker.kt @@ -0,0 +1,329 @@ +package org.umamo.render.pick + +import org.umamo.runtime.model.DrawableId +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.sin + +/** Minimum atlas-texel alpha (0..1) for a click to count as a hit — rejects the transparent triangle + * overhang that art meshes carry past the visible art edge, while keeping faint-but-real art (~10/255). */ +const val PICK_ALPHA_THRESHOLD = 0.04f + +// Centrality (how deep inside the opaque region a hit is) ray-march tuning, in texture-space texels. +private const val CENTRALITY_RAY_COUNT = 16 +private const val CENTRALITY_MAX_RADIUS_TEXELS = 64f +private const val CENTRALITY_STEP_TEXELS = 2f + +/** + * One opaque candidate under the cursor: the drawable, its front-rank (higher = drawn more in front), + * and its centrality (0..1, higher = the click is deeper inside the opaque art). Used to build the + * overlap-picker popup. + * + * カーソル下の不透明候補。前面ランクと中心度を持つ。 + */ +data class PickCandidate(val id: DrawableId, val frontRank: Float, val centrality: Float) + +/** + * Reports whether a point lies inside (or on an edge of) a triangle, using the sign of the three edge + * cross products. Works for either winding order; a point exactly on an edge counts as inside. A + * degenerate (zero-area) triangle accepts only points lying on its collapsed span. + * + * 点が三角形の内部(辺上を含む)にあるかを、3辺の外積の符号で判定する。巻き方向に依存しない。 + * + * @param Float pointX The test point X. + * @param Float pointY The test point Y. + * @param Float firstX First vertex X. + * @param Float firstY First vertex Y. + * @param Float secondX Second vertex X. + * @param Float secondY Second vertex Y. + * @param Float thirdX Third vertex X. + * @param Float thirdY Third vertex Y. + * @return Boolean True when the point is inside or on the triangle. + */ +fun pointInTriangle( + pointX: Float, + pointY: Float, + firstX: Float, + firstY: Float, + secondX: Float, + secondY: Float, + thirdX: Float, + thirdY: Float, +): Boolean { + val sideAb = edgeSide(pointX, pointY, firstX, firstY, secondX, secondY) + val sideBc = edgeSide(pointX, pointY, secondX, secondY, thirdX, thirdY) + val sideCa = edgeSide(pointX, pointY, thirdX, thirdY, firstX, firstY) + val hasNegative = sideAb < 0f || sideBc < 0f || sideCa < 0f + val hasPositive = sideAb > 0f || sideBc > 0f || sideCa > 0f + // Inside when the point is not strictly on both sides of the edges (zero counts as on-edge). + return !(hasNegative && hasPositive) +} + +/** + * The signed area term for the point relative to the directed edge (start to end): positive on one + * side, negative on the other, zero on the line. The sign, not the magnitude, is what + * [pointInTriangle] consumes. + * + * 点と有向辺の符号付き面積項。 + * + * @param Float pointX The test point X. + * @param Float pointY The test point Y. + * @param Float startX Edge start X. + * @param Float startY Edge start Y. + * @param Float endX Edge end X. + * @param Float endY Edge end Y. + * @return Float The signed area term. + */ +private fun edgeSide( + pointX: Float, + pointY: Float, + startX: Float, + startY: Float, + endX: Float, + endY: Float, +): Float = (pointX - endX) * (startY - endY) - (startX - endX) * (pointY - endY) + +/** + * The barycentric weights (w0, w1, w2) of a point relative to a triangle, used to interpolate + * per-vertex attributes (the UV) at a hit point. Weights sum to 1; a degenerate (zero-area) triangle + * returns equal thirds rather than dividing by zero. + * + * 三角形に対する点の重心座標。頂点属性(UV)の補間に使う。退化三角形は 1/3 ずつを返す。 + * + * @param Float pointX The point X. + * @param Float pointY The point Y. + * @param Float firstX First vertex X. + * @param Float firstY First vertex Y. + * @param Float secondX Second vertex X. + * @param Float secondY Second vertex Y. + * @param Float thirdX Third vertex X. + * @param Float thirdY Third vertex Y. + * @return FloatArray The three weights (w0, w1, w2). + */ +fun barycentricWeights( + pointX: Float, + pointY: Float, + firstX: Float, + firstY: Float, + secondX: Float, + secondY: Float, + thirdX: Float, + thirdY: Float, +): FloatArray { + val denominator = (secondY - thirdY) * (firstX - thirdX) + (thirdX - secondX) * (firstY - thirdY) + if (abs(denominator) < 1e-7f) { + return floatArrayOf(1f / 3f, 1f / 3f, 1f / 3f) + } + val weightFirst = ((secondY - thirdY) * (pointX - thirdX) + (thirdX - secondX) * (pointY - thirdY)) / denominator + val weightSecond = ((thirdY - firstY) * (pointX - thirdX) + (firstX - thirdX) * (pointY - thirdY)) / denominator + val weightThird = 1f - weightFirst - weightSecond + return floatArrayOf(weightFirst, weightSecond, weightThird) +} + +/** + * Finds the FRONT-MOST drawable whose deformed mesh contains the point AND whose texel there is opaque, + * or null on a miss. Candidates are the drawables present in [worldPositions] (the evaluator's visible + * set) that also have triangle [indices], [meshUvs], and a [frontRank] (so a drawable not actually drawn + * this frame is skipped). For each, the first containing triangle's UV is barycentric-interpolated and + * [sampleAlpha]d; a texel below [alphaThreshold] is rejected (the transparent overhang). Among the + * opaque hits, the highest [frontRank] wins — the renderer's resolved paint order, which is correct + * where the raw draw-order scalar (ignoring the group hierarchy) is not. + * + * 変形メッシュが点を含み、かつその位置のテクセルが不透明な最前面のドロウアブルを返す。前面ランクは + * レンダラの解決済み描画順に基づく(生のドローオーダー値ではない)。 + * + * @param Float worldX The point X in post-deform world space. + * @param Float worldZ The point Z (up) in post-deform world space. + * @param Map worldPositions Interleaved (x,y) deformed vertices per drawable. + * @param Map indices Triangle index triples per drawable. + * @param Map meshUvs Interleaved (u,v) per vertex per drawable. + * @param Map frontRank Front rank per drawn drawable (higher = more front). + * @param Function sampleAlpha (id, u, v) -> texel alpha 0..1 (untextured = 1). + * @param Float alphaThreshold Minimum alpha to count as a hit. + * @return DrawableId The front-most opaque hit, or null on a miss. + */ +fun pickDrawable( + worldX: Float, + worldZ: Float, + worldPositions: Map, + indices: Map, + meshUvs: Map, + frontRank: Map, + sampleAlpha: (DrawableId, Float, Float) -> Float, + alphaThreshold: Float = PICK_ALPHA_THRESHOLD, +): DrawableId? { + var bestId: DrawableId? = null + var bestRank = Float.NEGATIVE_INFINITY + for ((drawableId, positions) in worldPositions) { + val triangleIndices = indices[drawableId] ?: continue + val uvs = meshUvs[drawableId] ?: continue + val rank = frontRank[drawableId] ?: continue + val uv = hitUv(worldX, worldZ, positions, triangleIndices, uvs) ?: continue + if (sampleAlpha(drawableId, uv[0], uv[1]) < alphaThreshold) { + continue + } + if (bestId == null || rank > bestRank) { + bestId = drawableId + bestRank = rank + } + } + return bestId +} + +/** + * All opaque candidates under the point, FRONT-TO-BACK (front first), each with its centrality. Uses the + * same hit + alpha gate as [pickDrawable]; built for the overlap-picker popup. Centrality (how deep the + * hit is inside the opaque art) is computed per survivor from its atlas size via [atlasSizeOf]; an + * untextured drawable (null size) scores full centrality. + * + * 点の下の不透明候補すべてを前面順に返す(各々の中心度付き)。重なり選択ポップアップ用。 + * + * @param Float worldX The point X in post-deform world space. + * @param Float worldZ The point Z (up) in post-deform world space. + * @param Map worldPositions Interleaved (x,y) deformed vertices per drawable. + * @param Map indices Triangle index triples per drawable. + * @param Map meshUvs Interleaved (u,v) per vertex per drawable. + * @param Map frontRank Front rank per drawn drawable (higher = more front). + * @param Function atlasSizeOf (id) -> the drawable's atlas (width, height), or null if untextured. + * @param Function sampleAlpha (id, u, v) -> texel alpha 0..1 (untextured = 1). + * @param Float alphaThreshold Minimum alpha to count as a hit. + * @return List the opaque candidates, front-to-back. + */ +fun pickAllDrawables( + worldX: Float, + worldZ: Float, + worldPositions: Map, + indices: Map, + meshUvs: Map, + frontRank: Map, + atlasSizeOf: (DrawableId) -> Pair?, + sampleAlpha: (DrawableId, Float, Float) -> Float, + alphaThreshold: Float = PICK_ALPHA_THRESHOLD, +): List { + val candidates = mutableListOf() + for ((drawableId, positions) in worldPositions) { + val triangleIndices = indices[drawableId] ?: continue + val uvs = meshUvs[drawableId] ?: continue + val rank = frontRank[drawableId] ?: continue + val uv = hitUv(worldX, worldZ, positions, triangleIndices, uvs) ?: continue + if (sampleAlpha(drawableId, uv[0], uv[1]) < alphaThreshold) { + continue + } + val atlasSize = atlasSizeOf(drawableId) + val centrality = + if (atlasSize == null) { + 1f + } else { + centralityAt(drawableId, uv[0], uv[1], atlasSize.first, atlasSize.second, sampleAlpha, alphaThreshold) + } + candidates += PickCandidate(drawableId, rank, centrality) + } + candidates.sortByDescending { candidate -> candidate.frontRank } + return candidates +} + +/** + * Approximate "depth inside the opaque region" at a UV hit, in 0..1. Casts [CENTRALITY_RAY_COUNT] rays + * outward in texture space (stepping [CENTRALITY_STEP_TEXELS]) up to [CENTRALITY_MAX_RADIUS_TEXELS], + * finds the nearest texel where alpha drops below [alphaThreshold], and returns that min distance + * normalised by the cap (1 = no transparent texel within the cap, i.e. deep inside). The middle of a + * large opaque region scores high; a hit near a transparent boundary scores low. Approximate + * (ray-sampled, not an exact distance transform), and it cannot tell apart adjacently-packed atlas art. + * + * UV ヒット位置が不透明領域のどれだけ奥かを近似する(0..1)。テクスチャ空間で放射状にレイを飛ばし、 + * 最も近い透明テクセルまでの距離を上限で正規化する。 + * + * @param DrawableId id The drawable being scored. + * @param Float u The hit U (full-atlas). + * @param Float v The hit V (full-atlas). + * @param Int atlasWidth The drawable's atlas page width in texels. + * @param Int atlasHeight The drawable's atlas page height in texels. + * @param Function sampleAlpha (id, u, v) -> texel alpha 0..1. + * @param Float alphaThreshold The transparent cutoff. + * @return Float The centrality, 0..1. + */ +fun centralityAt( + id: DrawableId, + u: Float, + v: Float, + atlasWidth: Int, + atlasHeight: Int, + sampleAlpha: (DrawableId, Float, Float) -> Float, + alphaThreshold: Float = PICK_ALPHA_THRESHOLD, +): Float { + if (atlasWidth <= 0 || atlasHeight <= 0) { + return 1f + } + var minRadius = CENTRALITY_MAX_RADIUS_TEXELS + for (rayIndex in 0 until CENTRALITY_RAY_COUNT) { + val angle = 2.0 * PI * rayIndex / CENTRALITY_RAY_COUNT + val directionX = cos(angle).toFloat() + val directionY = sin(angle).toFloat() + var radius = CENTRALITY_STEP_TEXELS + while (radius <= CENTRALITY_MAX_RADIUS_TEXELS) { + val sampleU = u + directionX * radius / atlasWidth + val sampleV = v + directionY * radius / atlasHeight + if (sampleAlpha(id, sampleU, sampleV) < alphaThreshold) { + if (radius < minRadius) { + minRadius = radius + } + break + } + radius += CENTRALITY_STEP_TEXELS + } + } + return (minRadius / CENTRALITY_MAX_RADIUS_TEXELS).coerceIn(0f, 1f) +} + +/** + * The barycentric-interpolated (u, v) at the first triangle of a drawable's mesh that contains the point, + * or null when no triangle does. Index triples address vertices in the interleaved [positions] and [uvs] + * arrays (vertex n at index 2n, 2n+1). Shared by [pickDrawable] and [pickAllDrawables]. + * + * 点を含む最初の三角形での補間 UV を返す(無ければ null)。 + * + * @param Float worldX The point X. + * @param Float worldZ The point Z (up). + * @param FloatArray positions Interleaved (x,y) deformed vertices. + * @param IntArray triangleIndices Triangle index triples. + * @param FloatArray uvs Interleaved (u,v) per vertex. + * @return FloatArray (u, v) at the hit, or null. + */ +private fun hitUv( + worldX: Float, + worldZ: Float, + positions: FloatArray, + triangleIndices: IntArray, + uvs: FloatArray, +): FloatArray? { + var triangleStart = 0 + while (triangleStart + 2 < triangleIndices.size) { + val firstVertex = triangleIndices[triangleStart] * 2 + val secondVertex = triangleIndices[triangleStart + 1] * 2 + val thirdVertex = triangleIndices[triangleStart + 2] * 2 + if ( + firstVertex + 1 < positions.size && + secondVertex + 1 < positions.size && + thirdVertex + 1 < positions.size && + firstVertex + 1 < uvs.size && + secondVertex + 1 < uvs.size && + thirdVertex + 1 < uvs.size + ) { + val ax = positions[firstVertex] + val ay = positions[firstVertex + 1] + val bx = positions[secondVertex] + val by = positions[secondVertex + 1] + val cx = positions[thirdVertex] + val cy = positions[thirdVertex + 1] + if (pointInTriangle(worldX, worldZ, ax, ay, bx, by, cx, cy)) { + val weights = barycentricWeights(worldX, worldZ, ax, ay, bx, by, cx, cy) + val hitU = weights[0] * uvs[firstVertex] + weights[1] * uvs[secondVertex] + weights[2] * uvs[thirdVertex] + val hitV = weights[0] * uvs[firstVertex + 1] + weights[1] * uvs[secondVertex + 1] + weights[2] * uvs[thirdVertex + 1] + return floatArrayOf(hitU, hitV) + } + } + triangleStart += 3 + } + return null +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/pick/RegionPick.kt b/module/render/src/commonMain/kotlin/org/umamo/render/pick/RegionPick.kt new file mode 100644 index 0000000..f4f4afd --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/pick/RegionPick.kt @@ -0,0 +1,101 @@ +package org.umamo.render.pick + +import org.umamo.runtime.model.DrawableId + +/* + * Region enclosure for object-mode box / circle select. Object selection is whole-drawable, so a region + * selects a drawable by its geometry CENTROID (the mean of its posed world vertices), Blender's object-mode + * rule: a drawable is selected when its centroid falls inside the box or circle. Centroid-inside is stable + * and predictable - a full-canvas layer whose centroid sits at the canvas center is not grabbed by a region + * that only grazes its edge, unlike an any-vertex-touching rule. + * + * These functions are pure and work in the same interleaved (x, y) world space as + * org.umamo.render.eval.DeformedGeometry.worldPositions, which is exactly what an overlay caches at + * gesture start and tests against each frame - so the selection math is unit-testable with no render or + * Compose context. Only drawables appear in worldPositions (deformers and parts have no viewport geometry), + * and hidden / mesh-less drawables are already absent, so the enclosure naturally covers only real drawables. + * + * オブジェクトモードのボックス / サークル選択の領域判定。描画メッシュの重心が領域内にあるとき選択する。 + */ + +/** + * The world-space centroid of each drawable: the mean of its interleaved (x, y) world vertices. A drawable + * with an empty array is skipped (it has no centroid to test). + * + * @param Map worldPositions Interleaved world vertices per drawable. + * @return Map A two-element [x, y] centroid per drawable. + */ +fun drawableCentroids(worldPositions: Map): Map { + val centroids = LinkedHashMap(worldPositions.size) + for ((drawableId, positions) in worldPositions) { + var sumX = 0f + var sumY = 0f + var vertexCount = 0 + var slotIndex = 0 + while (slotIndex + 1 < positions.size) { + sumX += positions[slotIndex] + sumY += positions[slotIndex + 1] + vertexCount++ + slotIndex += 2 + } + if (vertexCount > 0) { + centroids[drawableId] = floatArrayOf(sumX / vertexCount, sumY / vertexCount) + } + } + return centroids +} + +/** + * The drawables whose centroid lies inside the axis-aligned world rectangle (a box select). Boundaries are + * inclusive. The caller normalises the corners, so [minX] <= [maxX] and [minY] <= [maxY] is assumed. + * + * @param Map centroids The per-drawable [x, y] centroids (see [drawableCentroids]). + * @param Float minX The rectangle's low x edge. + * @param Float minY The rectangle's low y edge. + * @param Float maxX The rectangle's high x edge. + * @param Float maxY The rectangle's high y edge. + * @return Set The enclosed drawable ids. + */ +fun drawablesInBox( + centroids: Map, + minX: Float, + minY: Float, + maxX: Float, + maxY: Float, +): Set { + val enclosed = LinkedHashSet() + for ((drawableId, centroid) in centroids) { + if (centroid[0] in minX..maxX && centroid[1] in minY..maxY) { + enclosed.add(drawableId) + } + } + return enclosed +} + +/** + * The drawables whose centroid lies within [radius] of ([centerX], [centerY]) in world space (a circle + * select brush stamp). A point exactly on the circle counts as inside. + * + * @param Map centroids The per-drawable [x, y] centroids (see [drawableCentroids]). + * @param Float centerX The brush center x in world space. + * @param Float centerY The brush center y in world space. + * @param Float radius The brush radius in world units. + * @return Set The enclosed drawable ids. + */ +fun drawablesInCircle( + centroids: Map, + centerX: Float, + centerY: Float, + radius: Float, +): Set { + val radiusSquared = radius * radius + val enclosed = LinkedHashSet() + for ((drawableId, centroid) in centroids) { + val offsetX = centroid[0] - centerX + val offsetY = centroid[1] - centerY + if (offsetX * offsetX + offsetY * offsetY <= radiusSquared) { + enclosed.add(drawableId) + } + } + return enclosed +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/pick/ScreenSpacePick.kt b/module/render/src/commonMain/kotlin/org/umamo/render/pick/ScreenSpacePick.kt new file mode 100644 index 0000000..bdff8e1 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/pick/ScreenSpacePick.kt @@ -0,0 +1,531 @@ +package org.umamo.render.pick + +import org.umamo.render.ViewportCamera +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sqrt + +/* + * Screen-space hit-testing and region enclosure over an interleaved (x, y) positions array, projected + * through a ViewportCamera - the geometry seam the Edit-mode gizmo overlays use for element picking, + * box select, and the circle brush, and that a UV editor can reuse verbatim by projecting through its + * own camera. Everything here is pure and Compose-free: points are plain floats, sizes are plain ints, + * and results are ORDINALS - vertex indices, edge ordinals into the caller's edge array, and triangle + * ordinals - so this module never depends on any UI element type. + * + * Edges come in as an interleaved endpoint array (two vertex indices per edge, the caller's edge order); + * the point-in-triangle test is shared with the world-space picker (pointInTriangle in Picker.kt), + * which is coordinate-space agnostic. + * + * 画面空間のヒットテストと範囲選択。カメラで投影する純粋な幾何で、UI 型に依存しない(結果は序数)。 + * UV エディタも同じ関数を自分のカメラで再利用できる。 + */ + +/** + * Maps a world x to its screen pixel x through [camera]. + * + * @param Float worldX The world-space x. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @return Float The screen x in pixels. + */ +fun worldToScreenX(worldX: Float, camera: ViewportCamera, viewportWidth: Int): Float = + (worldX - camera.centerX) * camera.zoom + viewportWidth / 2f + +/** + * Maps a world z to its screen pixel y through [camera]. The vertical axis flips: screen y grows + * downward, world z grows upward. + * + * @param Float worldZ The world-space z (up). + * @param ViewportCamera camera The projecting camera. + * @param Int viewportHeight The viewport height in pixels. + * @return Float The screen y in pixels. + */ +fun worldToScreenY(worldZ: Float, camera: ViewportCamera, viewportHeight: Int): Float = + (camera.centerY - worldZ) * camera.zoom + viewportHeight / 2f + +/** + * Maps a screen pixel x back to world space - the exact inverse of [worldToScreenX]. + * + * @param Float screenX The screen x in pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @return Float The world-space x. + */ +fun screenToWorldX(screenX: Float, camera: ViewportCamera, viewportWidth: Int): Float = + camera.centerX + (screenX - viewportWidth / 2f) / camera.zoom + +/** + * Maps a screen pixel y back to world space - the exact inverse of [worldToScreenY]. + * + * @param Float screenY The screen y in pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportHeight The viewport height in pixels. + * @return Float The world-space z (up). + */ +fun screenToWorldZ(screenY: Float, camera: ViewportCamera, viewportHeight: Int): Float = + camera.centerY - (screenY - viewportHeight / 2f) / camera.zoom + +/** + * The unclamped parameter of [point] along the infinite line through [start]→[end] (0 at start, 1 at + * end). A degenerate segment returns 0.5 so callers that clamp into `(ε, 1−ε)` still land mid-edge. + * + * @return Float The projection parameter (may lie outside [0, 1]). + */ +fun parameterAlongSegment( + pointX: Float, + pointY: Float, + startX: Float, + startY: Float, + endX: Float, + endY: Float, +): Float { + val segmentX = endX - startX + val segmentY = endY - startY + val lengthSquared = segmentX * segmentX + segmentY * segmentY + if (lengthSquared <= 1e-6f) { + return 0.5f + } + return ((pointX - startX) * segmentX + (pointY - startY) * segmentY) / lengthSquared +} + +/** + * The distance from a point to the segment start-end: the point is projected onto the segment's line + * with the projection parameter clamped into [0, 1], so endpoints measure correctly. Space-agnostic + * (the gizmos use it in screen pixels). + * + * @param Float pointX The point x. + * @param Float pointY The point y. + * @param Float startX The segment start x. + * @param Float startY The segment start y. + * @param Float endX The segment end x. + * @param Float endY The segment end y. + * @return Float The distance. + */ +fun distanceToSegment(pointX: Float, pointY: Float, startX: Float, startY: Float, endX: Float, endY: Float): Float { + val segmentX = endX - startX + val segmentY = endY - startY + val lengthSquared = segmentX * segmentX + segmentY * segmentY + // A degenerate (zero-length) segment measures as the distance to its single point. + if (lengthSquared <= 1e-6f) { + val deltaX = pointX - startX + val deltaY = pointY - startY + return sqrt(deltaX * deltaX + deltaY * deltaY) + } + val clamped = parameterAlongSegment(pointX, pointY, startX, startY, endX, endY).coerceIn(0f, 1f) + val nearestX = startX + segmentX * clamped + val nearestY = startY + segmentY * clamped + val deltaX = pointX - nearestX + val deltaY = pointY - nearestY + return sqrt(deltaX * deltaX + deltaY * deltaY) +} + +/** + * The vertex index under the pointer within [hitRadiusPx], or null. Picks the nearest within the radius. + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param Float pointerX The pointer x in screen pixels. + * @param Float pointerY The pointer y in screen pixels. + * @param Float hitRadiusPx The pick radius in screen pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Int? The hit vertex index, or null. + */ +fun hitTestVertex( + positions: FloatArray, + pointerX: Float, + pointerY: Float, + hitRadiusPx: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Int? { + var best = -1 + var bestDistance = hitRadiusPx + val vertexCount = positions.size / 2 + for (vertexIndex in 0 until vertexCount) { + val screenX = worldToScreenX(positions[vertexIndex * 2], camera, viewportWidth) + val screenY = worldToScreenY(positions[vertexIndex * 2 + 1], camera, viewportHeight) + val deltaX = screenX - pointerX + val deltaY = screenY - pointerY + val distance = sqrt(deltaX * deltaX + deltaY * deltaY) + if (distance <= bestDistance) { + bestDistance = distance + best = vertexIndex + } + } + return if (best >= 0) best else null +} + +/** + * The edge under the pointer within [hitRadiusPx], or null. Picks the nearest by point-to-segment + * distance in screen space, so a click between two close edges resolves to the closer one. + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param IntArray edgeEndpoints The edges as interleaved endpoint vertex indices (two per edge). + * @param Float pointerX The pointer x in screen pixels. + * @param Float pointerY The pointer y in screen pixels. + * @param Float hitRadiusPx The pick radius in screen pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Int? The hit edge's ordinal (its pair index within [edgeEndpoints]), or null. + */ +fun hitTestEdge( + positions: FloatArray, + edgeEndpoints: IntArray, + pointerX: Float, + pointerY: Float, + hitRadiusPx: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Int? { + var best = -1 + var bestDistance = hitRadiusPx + val vertexCount = positions.size / 2 + val edgeCount = edgeEndpoints.size / 2 + for (edgeOrdinal in 0 until edgeCount) { + val endpointA = edgeEndpoints[edgeOrdinal * 2] + val endpointB = edgeEndpoints[edgeOrdinal * 2 + 1] + if (endpointA >= vertexCount || endpointB >= vertexCount) { + continue + } + val startX = worldToScreenX(positions[endpointA * 2], camera, viewportWidth) + val startY = worldToScreenY(positions[endpointA * 2 + 1], camera, viewportHeight) + val endX = worldToScreenX(positions[endpointB * 2], camera, viewportWidth) + val endY = worldToScreenY(positions[endpointB * 2 + 1], camera, viewportHeight) + val distance = distanceToSegment(pointerX, pointerY, startX, startY, endX, endY) + if (distance <= bestDistance) { + bestDistance = distance + best = edgeOrdinal + } + } + return if (best >= 0) best else null +} + +/** + * The triangle under the pointer, or null. A point-in-triangle test on the projected positions; when a + * deformed mesh overlaps itself and several triangles contain the pointer, the one with the nearest + * centroid wins (a deterministic tie-break that favors the face whose click affordance is closest). + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Float pointerX The pointer x in screen pixels. + * @param Float pointerY The pointer y in screen pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Int? The hit triangle's ordinal, or null. + */ +fun hitTestFace( + positions: FloatArray, + triangleIndices: IntArray, + pointerX: Float, + pointerY: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Int? { + var best = -1 + var bestCentroidDistance = Float.MAX_VALUE + val vertexCount = positions.size / 2 + val triangleCount = triangleIndices.size / 3 + for (triangleOrdinal in 0 until triangleCount) { + val cornerA = triangleIndices[triangleOrdinal * 3] + val cornerB = triangleIndices[triangleOrdinal * 3 + 1] + val cornerC = triangleIndices[triangleOrdinal * 3 + 2] + if (cornerA >= vertexCount || cornerB >= vertexCount || cornerC >= vertexCount) { + continue + } + val screenAx = worldToScreenX(positions[cornerA * 2], camera, viewportWidth) + val screenAy = worldToScreenY(positions[cornerA * 2 + 1], camera, viewportHeight) + val screenBx = worldToScreenX(positions[cornerB * 2], camera, viewportWidth) + val screenBy = worldToScreenY(positions[cornerB * 2 + 1], camera, viewportHeight) + val screenCx = worldToScreenX(positions[cornerC * 2], camera, viewportWidth) + val screenCy = worldToScreenY(positions[cornerC * 2 + 1], camera, viewportHeight) + if (!pointInTriangle(pointerX, pointerY, screenAx, screenAy, screenBx, screenBy, screenCx, screenCy)) { + continue + } + val centroidX = (screenAx + screenBx + screenCx) / 3f + val centroidY = (screenAy + screenBy + screenCy) / 3f + val deltaX = pointerX - centroidX + val deltaY = pointerY - centroidY + val centroidDistance = sqrt(deltaX * deltaX + deltaY * deltaY) + if (centroidDistance < bestCentroidDistance) { + bestCentroidDistance = centroidDistance + best = triangleOrdinal + } + } + return if (best >= 0) best else null +} + +/** + * The set of vertices whose screen projection lies inside the rectangle spanned by the two corners + * (a rubber-band box select). + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param Float cornerAx One box corner's x in screen pixels. + * @param Float cornerAy One box corner's y in screen pixels. + * @param Float cornerBx The opposite corner's x. + * @param Float cornerBy The opposite corner's y. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Set The enclosed vertex indices. + */ +fun verticesInBox( + positions: FloatArray, + cornerAx: Float, + cornerAy: Float, + cornerBx: Float, + cornerBy: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Set { + val minX = min(cornerAx, cornerBx) + val maxX = max(cornerAx, cornerBx) + val minY = min(cornerAy, cornerBy) + val maxY = max(cornerAy, cornerBy) + val result = HashSet() + val vertexCount = positions.size / 2 + for (vertexIndex in 0 until vertexCount) { + val screenX = worldToScreenX(positions[vertexIndex * 2], camera, viewportWidth) + val screenY = worldToScreenY(positions[vertexIndex * 2 + 1], camera, viewportHeight) + if (screenX in minX..maxX && screenY in minY..maxY) { + result.add(vertexIndex) + } + } + return result +} + +/** + * The set of edges fully enclosed by the box (both endpoints inside) - Blender's edge box-select rule. + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param IntArray edgeEndpoints The edges as interleaved endpoint vertex indices (two per edge). + * @param Float cornerAx One box corner's x in screen pixels. + * @param Float cornerAy One box corner's y in screen pixels. + * @param Float cornerBx The opposite corner's x. + * @param Float cornerBy The opposite corner's y. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Set The enclosed edges' ordinals. + */ +fun edgesInBox( + positions: FloatArray, + edgeEndpoints: IntArray, + cornerAx: Float, + cornerAy: Float, + cornerBx: Float, + cornerBy: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Set { + val insideVertices = verticesInBox(positions, cornerAx, cornerAy, cornerBx, cornerBy, camera, viewportWidth, viewportHeight) + val result = HashSet() + val edgeCount = edgeEndpoints.size / 2 + for (edgeOrdinal in 0 until edgeCount) { + if (edgeEndpoints[edgeOrdinal * 2] in insideVertices && edgeEndpoints[edgeOrdinal * 2 + 1] in insideVertices) { + result.add(edgeOrdinal) + } + } + return result +} + +/** + * The set of triangles whose screen centroid lies inside the box - matching the centroid dot drawn as + * the face-mode click affordance, so the box selects exactly the visible dots it covers. + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Float cornerAx One box corner's x in screen pixels. + * @param Float cornerAy One box corner's y in screen pixels. + * @param Float cornerBx The opposite corner's x. + * @param Float cornerBy The opposite corner's y. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Set The enclosed triangles' ordinals. + */ +fun facesInBox( + positions: FloatArray, + triangleIndices: IntArray, + cornerAx: Float, + cornerAy: Float, + cornerBx: Float, + cornerBy: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Set { + val minX = min(cornerAx, cornerBx) + val maxX = max(cornerAx, cornerBx) + val minY = min(cornerAy, cornerBy) + val maxY = max(cornerAy, cornerBy) + val result = HashSet() + val vertexCount = positions.size / 2 + val triangleCount = triangleIndices.size / 3 + for (triangleOrdinal in 0 until triangleCount) { + val cornerA = triangleIndices[triangleOrdinal * 3] + val cornerB = triangleIndices[triangleOrdinal * 3 + 1] + val cornerC = triangleIndices[triangleOrdinal * 3 + 2] + if (cornerA >= vertexCount || cornerB >= vertexCount || cornerC >= vertexCount) { + continue + } + val centroidX = + ( + worldToScreenX(positions[cornerA * 2], camera, viewportWidth) + + worldToScreenX(positions[cornerB * 2], camera, viewportWidth) + + worldToScreenX(positions[cornerC * 2], camera, viewportWidth) + ) / 3f + val centroidY = + ( + worldToScreenY(positions[cornerA * 2 + 1], camera, viewportHeight) + + worldToScreenY(positions[cornerB * 2 + 1], camera, viewportHeight) + + worldToScreenY(positions[cornerC * 2 + 1], camera, viewportHeight) + ) / 3f + if (centroidX in minX..maxX && centroidY in minY..maxY) { + result.add(triangleOrdinal) + } + } + return result +} + +/** + * The set of vertices whose screen projection lies within [radiusPx] of the brush center - the + * Circle-select brush. + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param Float centerX The brush center x in screen pixels. + * @param Float centerY The brush center y in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Set The enclosed vertex indices. + */ +fun verticesInCircle( + positions: FloatArray, + centerX: Float, + centerY: Float, + radiusPx: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Set { + val result = HashSet() + val vertexCount = positions.size / 2 + for (vertexIndex in 0 until vertexCount) { + val deltaX = worldToScreenX(positions[vertexIndex * 2], camera, viewportWidth) - centerX + val deltaY = worldToScreenY(positions[vertexIndex * 2 + 1], camera, viewportHeight) - centerY + if (sqrt(deltaX * deltaX + deltaY * deltaY) <= radiusPx) { + result.add(vertexIndex) + } + } + return result +} + +/** + * The set of edges the brush touches: an edge is included when the brush center is within [radiusPx] of + * the edge segment in screen space (Blender's circle brush paints any edge the disc overlaps). + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param IntArray edgeEndpoints The edges as interleaved endpoint vertex indices (two per edge). + * @param Float centerX The brush center x in screen pixels. + * @param Float centerY The brush center y in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Set The touched edges' ordinals. + */ +fun edgesInCircle( + positions: FloatArray, + edgeEndpoints: IntArray, + centerX: Float, + centerY: Float, + radiusPx: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Set { + val vertexCount = positions.size / 2 + val result = HashSet() + val edgeCount = edgeEndpoints.size / 2 + for (edgeOrdinal in 0 until edgeCount) { + val endpointA = edgeEndpoints[edgeOrdinal * 2] + val endpointB = edgeEndpoints[edgeOrdinal * 2 + 1] + if (endpointA >= vertexCount || endpointB >= vertexCount) { + continue + } + val startX = worldToScreenX(positions[endpointA * 2], camera, viewportWidth) + val startY = worldToScreenY(positions[endpointA * 2 + 1], camera, viewportHeight) + val endX = worldToScreenX(positions[endpointB * 2], camera, viewportWidth) + val endY = worldToScreenY(positions[endpointB * 2 + 1], camera, viewportHeight) + if (distanceToSegment(centerX, centerY, startX, startY, endX, endY) <= radiusPx) { + result.add(edgeOrdinal) + } + } + return result +} + +/** + * The set of triangles whose screen centroid lies within [radiusPx] of the brush center - matching the + * centroid dot the face-mode overlay draws, so the brush paints the dots it covers (consistent with box + * select). + * + * @param FloatArray positions The interleaved (x, y) world positions. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Float centerX The brush center x in screen pixels. + * @param Float centerY The brush center y in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The projecting camera. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return Set The touched triangles' ordinals. + */ +fun facesInCircle( + positions: FloatArray, + triangleIndices: IntArray, + centerX: Float, + centerY: Float, + radiusPx: Float, + camera: ViewportCamera, + viewportWidth: Int, + viewportHeight: Int, +): Set { + val result = HashSet() + val vertexCount = positions.size / 2 + val triangleCount = triangleIndices.size / 3 + for (triangleOrdinal in 0 until triangleCount) { + val cornerA = triangleIndices[triangleOrdinal * 3] + val cornerB = triangleIndices[triangleOrdinal * 3 + 1] + val cornerC = triangleIndices[triangleOrdinal * 3 + 2] + if (cornerA >= vertexCount || cornerB >= vertexCount || cornerC >= vertexCount) { + continue + } + val centroidX = + ( + worldToScreenX(positions[cornerA * 2], camera, viewportWidth) + + worldToScreenX(positions[cornerB * 2], camera, viewportWidth) + + worldToScreenX(positions[cornerC * 2], camera, viewportWidth) + ) / 3f + val centroidY = + ( + worldToScreenY(positions[cornerA * 2 + 1], camera, viewportHeight) + + worldToScreenY(positions[cornerB * 2 + 1], camera, viewportHeight) + + worldToScreenY(positions[cornerC * 2 + 1], camera, viewportHeight) + ) / 3f + val deltaX = centroidX - centerX + val deltaY = centroidY - centerY + if (sqrt(deltaX * deltaX + deltaY * deltaY) <= radiusPx) { + result.add(triangleOrdinal) + } + } + return result +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/BlendMath.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/BlendMath.kt new file mode 100644 index 0000000..37c92ba --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/BlendMath.kt @@ -0,0 +1,325 @@ +package org.umamo.render.puppet + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sqrt + +/* + * The layer-composite reference math - the single spec the composite fragment shader + * (glsl/CompositeShaders.kt) and the analytic GL tests both follow. Sources are the PUBLIC + * standard formulas only: W3C Compositing and Blending Level 1 for the separable and + * non-separable (Hue/Color) blend functions, Porter-Duff for Over/Atop and a DST-flavored Out + * (the source erases the destination and contributes no color), the X Render extension's + * conjoint/disjoint over variants, and KHR_blend_equation_advanced's p0 overlap weights for how + * much of the source takes the blended color. Cubism's own `_TSL`/`_R2` math is NOT derived + * from the official SDK - the standard-formula reading has been checked against the official + * editor's rendering of Model A's authored combinations (NORMAL / MULTIPLY_R2 composites; HSL_COLOR / + * ADD_R2 (Glow) / HARDLIGHT / MULTIPLY_R2 drawable blends; OVER / ATOP / OUT / DISJOINT alphas). + * OUT in particular was confirmed DST-flavored: the SRC-out reading rendered Model A's hologram + * cutouts as destination-erasing silhouettes instead of cutting the effect to the body shape. + * Combinations the corpus does not yet exercise with real art (the remaining `_TSL` variants, + * Conjoint) are unconfirmed against the editor. + * + * Everything operates on PREMULTIPLIED RGBA (the renderer's framebuffer convention). The fixed-function + * premultiplied path replicates the equations of GlFrameEncoder.applyBlend EXACTLY (pinned by a + * shader==fixed-function GL test) and is taken by legacy Normal under Over alpha, plus + * AdditivePremultiplied / MultiplyPremultiplied under ANY alpha mode - the "(Before 5.3)" Add and + * Multiply ignore the Alpha blend setting per the Cubism editor. Every other combination takes the + * generic unpremultiply -> blend -> Porter-Duff path. + */ + +/** + * The composite shader's colorMode int for a blend mode - the MOC3 packed encoding's color half + * (editor-dropdown order, legacy first; MUST agree with BlendModeMapping.colorBlendOfPacked). + * + * @param BlendMode blendMode The color blend mode. + * @return Int The shader's colorMode uniform value (0-17). + */ +public fun packedColorModeOf(blendMode: BlendMode): Int = + when (blendMode) { + BlendMode.Normal -> 0 + BlendMode.AdditivePremultiplied -> 1 + BlendMode.MultiplyPremultiplied -> 2 + BlendMode.Additive -> 3 + BlendMode.AdditiveGlow -> 4 + BlendMode.Darken -> 5 + BlendMode.Multiply -> 6 + BlendMode.ColorBurn -> 7 + BlendMode.LinearBurn -> 8 + BlendMode.Lighten -> 9 + BlendMode.Screen -> 10 + BlendMode.ColorDodge -> 11 + BlendMode.Overlay -> 12 + BlendMode.SoftLight -> 13 + BlendMode.HardLight -> 14 + BlendMode.LinearLight -> 15 + BlendMode.Hue -> 16 + BlendMode.Color -> 17 + } + +/** + * The composite shader's alphaMode int for an alpha blend mode - the MOC3 packed encoding's alpha + * half (dropdown order; MUST agree with BlendModeMapping.alphaBlendOfPacked). + * + * @param AlphaBlendMode alphaBlendMode The alpha blend mode. + * @return Int The shader's alphaMode uniform value (0-4). + */ +public fun packedAlphaModeOf(alphaBlendMode: AlphaBlendMode): Int = + when (alphaBlendMode) { + AlphaBlendMode.Over -> 0 + AlphaBlendMode.Atop -> 1 + AlphaBlendMode.Out -> 2 + AlphaBlendMode.Conjoint -> 3 + AlphaBlendMode.Disjoint -> 4 + } + +/** + * Composites one premultiplied source pixel over one premultiplied destination pixel. + * + * @param FloatArray srcPremul The layer pixel, premultiplied RGBA (after opacity, colors, + * and mask have been applied to it). + * @param FloatArray dstPremul The destination pixel, premultiplied RGBA. + * @param BlendMode blendMode The color blend mode. + * @param AlphaBlendMode alphaBlendMode The alpha blend mode. + * @return FloatArray The composited pixel, premultiplied RGBA, channels clamped to [0,1]. + */ +public fun compositeReference( + srcPremul: FloatArray, + dstPremul: FloatArray, + blendMode: BlendMode, + alphaBlendMode: AlphaBlendMode, +): FloatArray { + val sourceAlpha = srcPremul[3] + val destinationAlpha = dstPremul[3] + + // Fixed-function premultiplied path: legacy Normal under Over, and the "(Before 5.3)" Add/Multiply + // under ANY alpha (they ignore the Alpha blend setting). Everything else goes through the generic path. + if ((alphaBlendMode == AlphaBlendMode.Over && blendMode.isLegacy) || blendMode.ignoresAlphaBlend) { + val out = + when (blendMode) { + // (ONE, ONE_MINUS_SRC_ALPHA) on both color and alpha - premultiplied source-over. + BlendMode.Normal -> + floatArrayOf( + srcPremul[0] + dstPremul[0] * (1f - sourceAlpha), + srcPremul[1] + dstPremul[1] * (1f - sourceAlpha), + srcPremul[2] + dstPremul[2] * (1f - sourceAlpha), + sourceAlpha + destinationAlpha * (1f - sourceAlpha), + ) + // (ONE, ONE) color, (ZERO, ONE) alpha. + BlendMode.AdditivePremultiplied -> + floatArrayOf( + srcPremul[0] + dstPremul[0], + srcPremul[1] + dstPremul[1], + srcPremul[2] + dstPremul[2], + destinationAlpha, + ) + // (DST_COLOR, ONE_MINUS_SRC_ALPHA) color, (ZERO, ONE) alpha. + else -> + floatArrayOf( + srcPremul[0] * dstPremul[0] + dstPremul[0] * (1f - sourceAlpha), + srcPremul[1] * dstPremul[1] + dstPremul[1] * (1f - sourceAlpha), + srcPremul[2] * dstPremul[2] + dstPremul[2] * (1f - sourceAlpha), + destinationAlpha, + ) + } + return FloatArray(4) { channelIndex -> out[channelIndex].coerceIn(0f, 1f) } + } + + // Generic path: unpremultiply, blend, then weight the blended color by the overlap fraction + // w = p0/as, where p0 is the KHR advanced-blend overlap weight for the alpha mode's coverage + // model: as*ab uncorrelated (Over/Atop/Out), min(as, ab) conjoint (maximal overlap), and + // max(as + ab - 1, 0) disjoint (minimal overlap). The uncorrelated case reduces to the W3C + // backdrop-alpha weighting (w = ab). Then the alpha mode's Porter-Duff factors on + // premultiplied terms: co = as*Fa*Cm + ab*Fb*Cb, ao = as*Fa + ab*Fb. + val sourceColor = unpremultiply(srcPremul) + val destinationColor = unpremultiply(dstPremul) + val blended = blendColor(blendMode, destinationColor, sourceColor) + val overlap = + when (alphaBlendMode) { + AlphaBlendMode.Conjoint -> min(sourceAlpha, destinationAlpha) + AlphaBlendMode.Disjoint -> max(sourceAlpha + destinationAlpha - 1f, 0f) + else -> sourceAlpha * destinationAlpha + } + val blendWeight = if (sourceAlpha > 0f) overlap / sourceAlpha else 0f + val mixed = + FloatArray(3) { channelIndex -> + (1f - blendWeight) * sourceColor[channelIndex] + blendWeight * blended[channelIndex] + } + val sourceFactor: Float + val destinationFactor: Float + when (alphaBlendMode) { + AlphaBlendMode.Over -> { + sourceFactor = 1f + destinationFactor = 1f - sourceAlpha + } + AlphaBlendMode.Atop -> { + sourceFactor = destinationAlpha + destinationFactor = 1f - sourceAlpha + } + // DST-out: the source erases the destination where it covers (ao = ab*(1-as)); Fa = 0 so + // the source contributes no color of its own. + AlphaBlendMode.Out -> { + sourceFactor = 0f + destinationFactor = 1f - sourceAlpha + } + // X Render conjoint over: maximal overlap - the destination shows only where it exceeds + // the source (ao = max(as, ab)). + AlphaBlendMode.Conjoint -> { + sourceFactor = 1f + destinationFactor = if (destinationAlpha <= 0f || sourceAlpha >= destinationAlpha) 0f else 1f - sourceAlpha / destinationAlpha + } + // X Render disjoint over: minimal overlap - the coverages pack side by side + // (ao = min(1, as + ab)). + AlphaBlendMode.Disjoint -> { + sourceFactor = 1f + destinationFactor = if (destinationAlpha <= 0f) 0f else min(1f, (1f - sourceAlpha) / destinationAlpha) + } + } + val outAlpha = sourceAlpha * sourceFactor + destinationAlpha * destinationFactor + return floatArrayOf( + (sourceAlpha * sourceFactor * mixed[0] + destinationAlpha * destinationFactor * destinationColor[0]).coerceIn(0f, 1f), + (sourceAlpha * sourceFactor * mixed[1] + destinationAlpha * destinationFactor * destinationColor[1]).coerceIn(0f, 1f), + (sourceAlpha * sourceFactor * mixed[2] + destinationAlpha * destinationFactor * destinationColor[2]).coerceIn(0f, 1f), + outAlpha.coerceIn(0f, 1f), + ) +} + +/** The straight-alpha color of a premultiplied pixel, clamped to [0,1] (0 where the alpha is 0). */ +private fun unpremultiply(premul: FloatArray): FloatArray { + val alpha = premul[3] + if (alpha <= 0f) { + return floatArrayOf(0f, 0f, 0f) + } + return floatArrayOf( + (premul[0] / alpha).coerceIn(0f, 1f), + (premul[1] / alpha).coerceIn(0f, 1f), + (premul[2] / alpha).coerceIn(0f, 1f), + ) +} + +/** + * The color blend function B(Cb, Cs) for [blendMode], on straight-alpha colors. + * + * @param BlendMode blendMode The color mode. + * @param FloatArray backdrop Cb, straight RGB. + * @param FloatArray source Cs, straight RGB. + * @return FloatArray The blended color, straight RGB. + */ +public fun blendColor(blendMode: BlendMode, backdrop: FloatArray, source: FloatArray): FloatArray = + when (blendMode) { + BlendMode.Normal -> source.copyOf() + // The additive family reads as linear dodge (add) in the generic path; the legacy mode's + // fixed-function semantics apply only under Over (see compositeReference). Add (Glow) has + // been checked against the official editor via Model A and matches this shared formula; + // Add's modern (_TSL) variant shares it too but is unconfirmed against the editor. + BlendMode.AdditivePremultiplied, BlendMode.Additive, BlendMode.AdditiveGlow -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> min(1f, backdropChannel + sourceChannel) } + BlendMode.MultiplyPremultiplied, BlendMode.Multiply -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> backdropChannel * sourceChannel } + BlendMode.Darken -> perChannel(backdrop, source) { backdropChannel, sourceChannel -> min(backdropChannel, sourceChannel) } + BlendMode.Lighten -> perChannel(backdrop, source) { backdropChannel, sourceChannel -> max(backdropChannel, sourceChannel) } + BlendMode.Screen -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> + backdropChannel + sourceChannel - backdropChannel * sourceChannel + } + BlendMode.ColorBurn -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> + when { + backdropChannel >= 1f -> 1f + sourceChannel <= 0f -> 0f + else -> 1f - min(1f, (1f - backdropChannel) / sourceChannel) + } + } + BlendMode.LinearBurn -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> max(0f, backdropChannel + sourceChannel - 1f) } + BlendMode.ColorDodge -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> + when { + backdropChannel <= 0f -> 0f + sourceChannel >= 1f -> 1f + else -> min(1f, backdropChannel / (1f - sourceChannel)) + } + } + BlendMode.Overlay -> perChannel(backdrop, source) { backdropChannel, sourceChannel -> hardLight(sourceChannel, backdropChannel) } + BlendMode.HardLight -> perChannel(backdrop, source) { backdropChannel, sourceChannel -> hardLight(backdropChannel, sourceChannel) } + BlendMode.SoftLight -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> + if (sourceChannel <= 0.5f) { + backdropChannel - (1f - 2f * sourceChannel) * backdropChannel * (1f - backdropChannel) + } else { + backdropChannel + (2f * sourceChannel - 1f) * (softLightD(backdropChannel) - backdropChannel) + } + } + BlendMode.LinearLight -> + perChannel(backdrop, source) { backdropChannel, sourceChannel -> + (backdropChannel + 2f * sourceChannel - 1f).coerceIn(0f, 1f) + } + BlendMode.Hue -> setLuminosity(setSaturation(source, saturation(backdrop)), luminosity(backdrop)) + BlendMode.Color -> setLuminosity(source, luminosity(backdrop)) + } + +private inline fun perChannel(backdrop: FloatArray, source: FloatArray, operation: (Float, Float) -> Float): FloatArray = + FloatArray(3) { channelIndex -> operation(backdrop[channelIndex], source[channelIndex]) } + +/** W3C hard-light: multiply below the midpoint of [selector], screen above it. */ +private fun hardLight(base: Float, selector: Float): Float = + if (selector <= 0.5f) { + 2f * selector * base + } else { + val screened = base + (2f * selector - 1f) - base * (2f * selector - 1f) + screened + } + +/** W3C soft-light's D(x) helper. */ +private fun softLightD(value: Float): Float = + if (value <= 0.25f) { + ((16f * value - 12f) * value + 4f) * value + } else { + sqrt(value) + } + +/** W3C Lum(C). */ +private fun luminosity(color: FloatArray): Float = 0.3f * color[0] + 0.59f * color[1] + 0.11f * color[2] + +/** W3C Sat(C). */ +private fun saturation(color: FloatArray): Float = + max(color[0], max(color[1], color[2])) - min(color[0], min(color[1], color[2])) + +/** W3C ClipColor(C): pulls out-of-range channels back toward the luminosity. */ +private fun clipColor(color: FloatArray): FloatArray { + val lum = luminosity(color) + val minChannel = min(color[0], min(color[1], color[2])) + val maxChannel = max(color[0], max(color[1], color[2])) + var result = color + if (minChannel < 0f) { + val below = result + result = FloatArray(3) { channelIndex -> lum + (below[channelIndex] - lum) * lum / (lum - minChannel) } + } + if (maxChannel > 1f) { + val above = result + result = FloatArray(3) { channelIndex -> lum + (above[channelIndex] - lum) * (1f - lum) / (maxChannel - lum) } + } + return result +} + +/** W3C SetLum(C, l). */ +private fun setLuminosity(color: FloatArray, lum: Float): FloatArray { + val delta = lum - luminosity(color) + return clipColor(floatArrayOf(color[0] + delta, color[1] + delta, color[2] + delta)) +} + +/** W3C SetSat(C, s): rescales the mid channel between min and max, on sorted channels. */ +private fun setSaturation(color: FloatArray, sat: Float): FloatArray { + val result = FloatArray(3) + val indices = intArrayOf(0, 1, 2).sortedBy { color[it] } + val minIndex = indices[0] + val midIndex = indices[1] + val maxIndex = indices[2] + if (color[maxIndex] > color[minIndex]) { + result[midIndex] = (color[midIndex] - color[minIndex]) * sat / (color[maxIndex] - color[minIndex]) + result[maxIndex] = sat + } + return result +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/ContentBoundsEval.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/ContentBoundsEval.kt new file mode 100644 index 0000000..1fce540 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/ContentBoundsEval.kt @@ -0,0 +1,87 @@ +package org.umamo.render.puppet + +import org.umamo.render.ContentBounds +import org.umamo.render.eval.DeformedGeometry +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * The side of the square an empty model with no canvas frames, in world units: room to start drawing in, + * around the world origin, at a zoom where the grid reads as a grid. + */ +private const val EMPTY_FRAME_EXTENT = 1000f + +/** + * Computes the world-space extent of a deformed pose's shown drawables - the framing `view.fit` frames to. + * + * Backend-neutral: a bounding box over already-deformed positions, so every renderer backend shares it + * rather than re-deriving it beside its own GPU calls. + * + * Hidden drawables are excluded deliberately: a hidden full-canvas guide image or background must not + * stretch the framing of a view it is not drawn in. + * + * @param DeformedGeometry geometry The CPU-evaluated pose to measure. + * @param Set shownIds The drawables actually drawn (the resolved visibility cascade). + * @return ContentBounds? The extent, with each span floored at 1 so a degenerate model never divides by + * zero downstream; null when no shown drawable has a vertex, so there is nothing to measure. + * @note Null rather than a sentinel rectangle on purpose. The sweep starts from the float extremes, and a + * rectangle left there frames a camera at the edge of float range, where the grid has no precision + * left to draw with - a blank viewport. That is the FIRST frame of a new, empty document, and what + * Fit does once every drawable is hidden, so the caller must choose what to frame instead + * ([emptyContentBoundsOf]). + */ +internal fun contentBoundsOf(geometry: DeformedGeometry, shownIds: Set): ContentBounds? { + var loX = Float.MAX_VALUE + var loY = Float.MAX_VALUE + var hiX = -Float.MAX_VALUE + var hiY = -Float.MAX_VALUE + for ((drawableId, world) in geometry.worldPositions) { + // A hidden full-canvas guide image / background must not stretch the framing it isn't drawn in. + if (drawableId !in shownIds) { + continue + } + var coordIndex = 0 + while (coordIndex < world.size) { + loX = minOf(loX, world[coordIndex]) + hiX = maxOf(hiX, world[coordIndex]) + loY = minOf(loY, world[coordIndex + 1]) + hiY = maxOf(hiY, world[coordIndex + 1]) + coordIndex += 2 + } + } + if (loX > hiX || loY > hiY) { + return null + } + return ContentBounds(loX, loY, maxOf(hiX - loX, 1f), maxOf(hiY - loY, 1f)) +} + +/** + * What a view frames when the model shows nothing to measure: the document's canvas, or - for a model that + * carries no canvas - a square around the world origin. + * + * The canvas is where the art will go, so it is the honest frame for a new, empty document and for a rig + * whose every drawable is hidden. World space is canvas x with canvas y negated, so a canvas spanning + * [0, width] x [0, height] occupies x in [0, width] and y in [-height, 0] here. + * + * @param PuppetModel model The model being framed. + * @return ContentBounds The rectangle to fit. + */ +internal fun emptyContentBoundsOf(model: PuppetModel): ContentBounds = + canvasBoundsOf(model) + ?: ContentBounds(model.worldOriginX - EMPTY_FRAME_EXTENT / 2f, model.worldOriginZ - EMPTY_FRAME_EXTENT / 2f, EMPTY_FRAME_EXTENT, EMPTY_FRAME_EXTENT) + +/** + * The document's canvas rectangle in world space, or null for a model that carries no canvas. + * + * World space is canvas x with canvas y negated, so a canvas spanning [0, width] x [0, height] occupies + * x in [0, width] and y in [-height, 0] here. + * + * @param PuppetModel model The model whose canvas to place. + * @return ContentBounds? The canvas rectangle, or null when either canvas dimension is not positive. + */ +fun canvasBoundsOf(model: PuppetModel): ContentBounds? = + if (model.canvasWidth > 0f && model.canvasHeight > 0f) { + ContentBounds(0f, -model.canvasHeight, model.canvasWidth, model.canvasHeight) + } else { + null + } \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/DeltaTexels.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/DeltaTexels.kt new file mode 100644 index 0000000..20d0283 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/DeltaTexels.kt @@ -0,0 +1,172 @@ +package org.umamo.render.puppet + +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.eval.meshGridDefaultDeltas +import org.umamo.runtime.keyform.cellCount +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId + +/** + * The linear cell extent of a keyform grid - the product of each axis's key count. + * + * This is the delta texture's width: one column per keyform cell, addressed by the cell's linear index + * (the same index [org.umamo.runtime.eval.WeightedCell.linearIndex] carries, which is how the vertex + * shader's active corners find their column). + * + * A null grid is an UNKEYED drawable and gets a single column, which the texel build fills with zeros - + * so the shader fetches column 0 at full weight and reads no offset, leaving the mesh at rest. That is + * what lets an unkeyed drawable render with no shader, uniform-layout, or RenderDevice change at all. + * + * @param KeyformGrid? grid The mesh's keyform grid, or null when the drawable is unkeyed. + * @return Int The cell count, floored at 1 so an axis-less or absent grid still gets its single rest cell. + */ +internal fun keyformCellCount(grid: KeyformGrid?): Int = maxOf(1, grid?.cellCount ?: 1) + +/** + * Builds a mesh's per-keyform-cell vertex deltas as RG texels: row = vertex id, column = cell linear + * index, RG = (Δx, Δy). This is the `p = base + Σ wᵢ·Δᵢ` morph's Δ table, which the vertex shader + * texel-fetches per active corner. + * + * Backend-neutral by construction: it returns plain texels, so each backend uploads them its own way + * (an RG32F 2D texture on the GL family; whatever Metal prefers). Emitting a backend's buffer type here + * would put a texture-upload decision in shared code. + * + * A cell with no keyform, or one whose delta array is too short for this vertex, contributes (0, 0) - + * i.e. that cell leaves the vertex at its rest position. Both cases are reachable in real models, so + * they are a normal absence rather than an error. + * + * @param KeyformGrid? grid The mesh's keyform grid, or null when the drawable is unkeyed (which + * yields an all-zero single column - the rest mesh). + * @param Int vertexCount The mesh's vertex count (the texture height). + * @param Int cellCount The grid's linear cell extent from [keyformCellCount] (the width). + * @param Map cells The grid's cells by linear index; defaults to [cellsByLinearIndex] of + * [grid], but a caller that already built the map (the drawable upload also needs it for the composite + * bounds walk) can pass it in to avoid rebuilding it. + * @return FloatArray The texels, row-major, length `vertexCount * cellCount * 2`. + */ +internal fun buildDeltaTexels( + grid: KeyformGrid?, + vertexCount: Int, + cellCount: Int, + cells: Map> = if (grid != null) cellsByLinearIndex(grid) else emptyMap(), +): FloatArray { + val texels = FloatArray(vertexCount * cellCount * 2) + var writeIndex = 0 + for (vertexIndex in 0 until vertexCount) { + for (cellIndex in 0 until cellCount) { + val deltas = cells[cellIndex]?.form?.positionDeltas + if (deltas != null && vertexIndex * 2 + 1 < deltas.size) { + texels[writeIndex] = deltas[vertexIndex * 2] + texels[writeIndex + 1] = deltas[vertexIndex * 2 + 1] + } + // else: leave (0, 0) - a missing cell or a short delta array means no offset from rest. + writeIndex += 2 + } + } + return texels +} + +/** + * The static column assignment of a drawable's blend-shape delta forms in its delta texture: + * blend columns are appended after the grid's [cellCount] columns, in (binding order, key order), + * skipping neutral/absent forms (their delta is zero and never fetched). CPU pose prep, the texel + * bake, and the per-frame uniform fill all agree through this one mapping. + * + * @property Int cellCount The grid's own column count (blend columns start here). + * @property Int blendColumnCount Number of appended blend columns. + */ +internal class BlendColumnLayout( + val cellCount: Int, + val blendColumnCount: Int, + private val columnByKey: Map, +) { + /** + * The texture column of one binding's key form, or null when that key holds no form (neutral). + * + * @param Int bindingIndex Index into the drawable's blendShapes. + * @param Int keyIndex Key index within that binding. + * @return Int? The absolute texture column, or null. + */ + fun columnOf(bindingIndex: Int, keyIndex: Int): Int? = columnByKey[packKey(bindingIndex, keyIndex)] + + internal companion object { + /** Packs a (binding, key) pair into one map key. */ + internal fun packKey(bindingIndex: Int, keyIndex: Int): Long = bindingIndex.toLong() shl 32 or keyIndex.toLong() + } +} + +/** + * Builds the blend-column layout for [drawable] over a grid of [cellCount] columns. + * + * @param Drawable drawable The drawable (its blendShapes define the columns). + * @param Int cellCount The grid's own column count. + * @return BlendColumnLayout The layout (zero blend columns when binding-free). + */ +internal fun blendColumnLayout(drawable: Drawable, cellCount: Int): BlendColumnLayout { + val columnByKey = HashMap() + var nextColumn = cellCount + for (bindingIndex in drawable.blendShapes.indices) { + val binding = drawable.blendShapes[bindingIndex] + for (keyIndex in binding.forms.indices) { + if (binding.forms[keyIndex] != null) { + columnByKey[BlendColumnLayout.packKey(bindingIndex, keyIndex)] = nextColumn + nextColumn++ + } + } + } + return BlendColumnLayout(cellCount, nextColumn - cellCount, columnByKey) +} + +/** + * Builds a mesh's delta texels INCLUDING its appended blend-shape columns: the grid columns as + * [buildDeltaTexels], then one column per non-neutral blend form holding the E5-resolved delta + * (form minus the grid-at-default reference) per vertex. Static per model, like the grid columns. + * + * @param KeyformGrid grid The mesh's keyform grid. + * @param Drawable drawable The drawable (blend forms + reference resolution). + * @param Function defaultValue Default value per parameter id (the reference pose). + * @param Int vertexCount The mesh's vertex count (the texture height). + * @param BlendColumnLayout layout The column assignment from [blendColumnLayout]. + * @param Map cells The grid's cells by linear index; defaults to [cellsByLinearIndex] + * of [grid], but a caller that already built the map can pass it in to avoid rebuilding it. + * @return FloatArray The texels, row-major, length `vertexCount * (cellCount + blendColumnCount) * 2`. + */ +internal fun buildDeltaTexelsWithBlend( + grid: KeyformGrid?, + drawable: Drawable, + defaultValue: (ParameterId) -> Float, + vertexCount: Int, + layout: BlendColumnLayout, + cells: Map> = if (grid != null) cellsByLinearIndex(grid) else emptyMap(), +): FloatArray { + val width = layout.cellCount + layout.blendColumnCount + val texels = FloatArray(vertexCount * width * 2) + val reference = meshGridDefaultDeltas(drawable, defaultValue) + for (vertexIndex in 0 until vertexCount) { + val rowBase = vertexIndex * width * 2 + for (cellIndex in 0 until layout.cellCount) { + val deltas = cells[cellIndex]?.form?.positionDeltas + if (deltas != null && vertexIndex * 2 + 1 < deltas.size) { + texels[rowBase + cellIndex * 2] = deltas[vertexIndex * 2] + texels[rowBase + cellIndex * 2 + 1] = deltas[vertexIndex * 2 + 1] + } + } + for (bindingIndex in drawable.blendShapes.indices) { + val binding = drawable.blendShapes[bindingIndex] + for (keyIndex in binding.forms.indices) { + val form = binding.forms[keyIndex] ?: continue + val column = layout.columnOf(bindingIndex, keyIndex) ?: continue + if (vertexIndex * 2 + 1 < form.positionDeltas.size) { + val referenceX = reference?.getOrNull(vertexIndex * 2) ?: 0f + val referenceY = reference?.getOrNull(vertexIndex * 2 + 1) ?: 0f + texels[rowBase + column * 2] = form.positionDeltas[vertexIndex * 2] - referenceX + texels[rowBase + column * 2 + 1] = form.positionDeltas[vertexIndex * 2 + 1] - referenceY + } + } + } + } + return texels +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/FallbackColor.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/FallbackColor.kt new file mode 100644 index 0000000..0d662ce --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/FallbackColor.kt @@ -0,0 +1,23 @@ +package org.umamo.render.puppet + +/** + * A stable, readable flat color for an untextured drawable, derived from its id. + * + * Only reached when a drawable resolves to no atlas page, so it is a development affordance rather than + * anything a rigger sees in a textured model - it exists so an untextured mesh is visible and tellable + * apart from its neighbours instead of rendering invisible. Hashing the id (rather than cycling a + * palette by index) keeps a given drawable the same color across reorders and reloads. + * + * The channel floor of 0.35 and the 0.6 span keep every result mid-bright: dark enough to read against + * the light grid, light enough against the dark one. + * + * @param String id The drawable's raw id. + * @return FloatArray RGBA, each 0..1, at a fixed 0.85 alpha. + */ +internal fun fallbackColorFor(id: String): FloatArray { + val hash = id.hashCode() + val red = 0.35f + ((hash shr 16) and 0xFF) / 255f * 0.6f + val green = 0.35f + ((hash shr 8) and 0xFF) / 255f * 0.6f + val blue = 0.35f + (hash and 0xFF) / 255f * 0.6f + return floatArrayOf(red, green, blue, 0.85f) +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/GlueLayout.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/GlueLayout.kt new file mode 100644 index 0000000..a5678e6 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/GlueLayout.kt @@ -0,0 +1,140 @@ +package org.umamo.render.puppet + +import org.umamo.render.glsl.MAX_GLUES +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * One glue mesh's per-vertex weld attributes, parallel arrays indexed by the mesh's own vertex index. + * + * A vertex that is not glued points at ITSELF with weight 0 - a weld that is arithmetically a no-op + * (`own + (own - own) * 0`), which is why the shader needs no "is this vertex glued" branch beyond the + * cheap [glueIndex] test. + * + * Three arrays rather than one packed byte blob deliberately. The packed form is a GL vertex-attribute + * layout (12 bytes/vertex, native byte order), and encoding it here would put a backend's memory layout + * into shared code AND force this module to invent an endianness convention that the GL side would then + * have to honor silently. What each vertex welds to is shared; how the bytes sit is the backend's. + * + * @property IntArray partnerIndex Per vertex: the partner's GLOBAL index in the shared position store, + * or the vertex's own global index when it is not glued. + * @property IntArray glueIndex Per vertex: which glue supplies the per-pose intensity, or -1 when + * not glued. + * @property FloatArray weldWeight Per vertex: how far to move toward the partner (0 when not glued). + */ +public class GlueVertexAttributes( + val partnerIndex: IntArray, + val glueIndex: IntArray, + val weldWeight: FloatArray, +) + +/** + * The addressing plan for a model's glue: who participates, where each mesh sits in the shared deformed + * position store, and what every vertex welds to. + * + * @property Set glueMeshIds Every mesh in any glue pair, INCLUDING zero-triangle anchors, which + * draw nothing but whose deformed positions are weld partners. + * @property Map baseOffsetById Each glue mesh's first vertex index in the shared store. + * @property Int globalVertexCount The store's total vertex capacity. + * @property Map attributesById Each glue mesh's per-vertex weld attributes. + */ +internal class GlueLayout( + val glueMeshIds: Set, + val baseOffsetById: Map, + val globalVertexCount: Int, + val attributesById: Map, +) + +/** + * Plans [model]'s glue addressing: the participating meshes, their base offsets in the shared deformed + * position store, and every vertex's weld attributes. + * + * Backend-neutral - it decides WHAT welds to what, in terms of vertex indices, and nothing about how a + * GPU stores it. + * + * The offsets are assigned by walking [PuppetModel.drawables] in order and giving each glue mesh the next + * region, so that iteration order DEFINES the addressing. Both the GPU write (pass 1 deforms each mesh + * into its own region) and the GPU read (pass 2 fetches a partner by global index) depend on producer and + * consumer agreeing on it exactly. + * + * @param PuppetModel model The rig. + * @return GlueLayout The addressing plan; empty throughout when the model has no glue. + * @note A glue pair whose vertex index is outside its mesh throws here, whereas the CPU weld + * (`applyGluesResolved`) silently skips it. That divergence predates this extraction and is preserved + * rather than quietly papered over - a malformed pair should be dealt with deliberately, not by two + * different behaviours in two backends. + */ +internal fun planGlueLayout(model: PuppetModel): GlueLayout { + val glueMeshIds = HashSet() + for (glue in model.glues) { + glueMeshIds.add(glue.meshA) + glueMeshIds.add(glue.meshB) + } + val vertexCountById = HashMap(glueMeshIds.size) + val baseOffsetById = HashMap(glueMeshIds.size) + var globalVertexCount = 0 + // model.drawables order defines the offsets - see the docblock. + for (drawable in model.drawables) { + if (drawable.id !in glueMeshIds) { + continue + } + val vertexCount = (drawable.mesh?.positions?.size ?: 0) / 2 + vertexCountById[drawable.id] = vertexCount + baseOffsetById[drawable.id] = globalVertexCount + globalVertexCount += vertexCount + } + + // Every vertex starts as an un-glued no-op weld: partner = self, no glue, zero weight. + val attributesById = HashMap(glueMeshIds.size) + for (id in glueMeshIds) { + val base = baseOffsetById[id] ?: continue // a glue naming a drawable the model does not carry + val vertexCount = vertexCountById[id] ?: continue + attributesById[id] = + GlueVertexAttributes( + partnerIndex = IntArray(vertexCount) { vertexIndex -> base + vertexIndex }, + glueIndex = IntArray(vertexCount) { -1 }, + weldWeight = FloatArray(vertexCount), + ) + } + + // Then each pair points both members at each other, by global index. + for ((glueIndex, glue) in model.glues.withIndex()) { + // glue #65+ has no slot in the shader's fixed glueIntensity[MAX_GLUES] uniform array, and a + // vertex tagged with it would index that array out of bounds. Leave those vertices at their -1 + // (unwelded) default rather than tag them - this is what makes resolvePose's "renders unwelded" + // promise actually true. + if (glueIndex >= MAX_GLUES) { + continue + } + val baseA = baseOffsetById[glue.meshA] ?: continue + val baseB = baseOffsetById[glue.meshB] ?: continue + val attributesA = attributesById[glue.meshA] ?: continue + val attributesB = attributesById[glue.meshB] ?: continue + for (pair in glue.pairs) { + writeGlueVertex(attributesA, pair.indexA, baseB + pair.indexB, glueIndex, pair.weightA) + writeGlueVertex(attributesB, pair.indexB, baseA + pair.indexA, glueIndex, pair.weightB) + } + } + return GlueLayout(glueMeshIds, baseOffsetById, globalVertexCount, attributesById) +} + +/** + * Points one vertex at its weld partner. + * + * @param GlueVertexAttributes attributes The owning mesh's attributes. + * @param Int vertexIndex The vertex, in its own mesh's indexing. + * @param Int partnerGlobalIndex The partner's index in the shared store. + * @param Int glueIndex Which glue supplies the per-pose intensity. + * @param Float weight How far to move toward the partner. + */ +private fun writeGlueVertex( + attributes: GlueVertexAttributes, + vertexIndex: Int, + partnerGlobalIndex: Int, + glueIndex: Int, + weight: Float, +) { + attributes.partnerIndex[vertexIndex] = partnerGlobalIndex + attributes.glueIndex[vertexIndex] = glueIndex + attributes.weldWeight[vertexIndex] = weight +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/ModelDiff.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/ModelDiff.kt new file mode 100644 index 0000000..2cf2451 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/ModelDiff.kt @@ -0,0 +1,145 @@ +package org.umamo.render.puppet + +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * What a backend must do to one drawable to reconcile its residency with an edited model. + * + * The decision, not the doing: which tier a drawable falls into is backend-neutral, while freeing GPU + * objects and re-uploading buffers is the backend's. + */ +internal sealed interface DrawableAction { + /** The drawable this action concerns. */ + val drawableId: DrawableId + + /** + * The backend has never seen this drawable - an Object-mode duplicate, or one skipped at load for + * having no geometry. Upload it whole. Never part of the load-time glue layout, so it welds nothing. + */ + class Upload(val drawable: Drawable) : DrawableAction { + override val drawableId: DrawableId get() = drawable.id + } + + /** + * The topology changed (vertex count, indices, the keyform grid, or the blend-shape bindings), or + * the drawable was reparented across the warp boundary (gaining or losing a control-point texture), + * so every buffer and the delta texture are stale. Free the resident and upload it whole against + * the new mesh. + */ + class Reupload(val drawable: Drawable) : DrawableAction { + override val drawableId: DrawableId get() = drawable.id + } + + /** + * The residency is reusable. Non-null [positions] / [uvs] are in-place re-uploads for the tiers that + * changed; both null means no BUFFER work - but the resident's static composite state (blend/alpha + * mode, culling, mask ids, invert) is still re-stamped from [drawable], since a composite-only edit + * changes no mesh array and so lands here, not in Reupload. + */ + class Keep( + val drawable: Drawable, + val positions: FloatArray?, + val uvs: FloatArray?, + ) : DrawableAction { + override val drawableId: DrawableId get() = drawable.id + } +} + +/** + * A reconcile plan: what to do with each drawable, and which residents to free. + * + * @property List actions Per-drawable actions in [PuppetModel.drawables] order, so applying them in + * sequence rebuilds residency in that same order. + * @property List removed Resident ids the edit dropped entirely; free them after applying [actions]. + */ +internal class ModelDiff( + val actions: List, + val removed: List, +) + +/** + * Decides how to reconcile a backend's resident drawables with an edited model - four tiers, cheapest + * first. + * + * A layer reorder or a reparent that does not change control-point ownership needs no buffer work at all + * (every drawable is a no-op [Keep]); a base-mesh move re-uploads positions; a UV edit re-uploads UVs; and + * a structural change - a drawable added, removed, remeshed, its blend-shape bindings changed, or + * reparented across the warp boundary (which gains or loses its control-point texture) - frees and + * re-uploads whole. + * + * The diff is keyed by drawable id (so it is robust to a simultaneous reorder) and by ARRAY REFERENCE + * identity: the edit path is copy-on-write, so an untouched drawable keeps its exact array instances and + * is skipped by an `!==` test without comparing any element. + * + * @param PuppetModel model The model the residency currently reflects. + * @param PuppetModel newModel The edited model. + * @param Map residentVertexCountById Each resident drawable's uploaded vertex count. An INPUT + * rather than something derived from [model], and deliberately so: a drawable whose mesh went null is + * kept resident, after which [model] no longer carries the count its buffers were built at - only the + * backend still knows it. Its keys are also the authoritative "what is resident" set, which is not the + * same as [model]'s drawables (one with no geometry is skipped at upload). + * @return ModelDiff The reconcile plan. + * @pre Call BEFORE reassigning the backend's current model - the diff reads [model] as the state the + * GPU buffers still match. + */ +internal fun diffModel( + model: PuppetModel, + newModel: PuppetModel, + residentVertexCountById: Map, +): ModelDiff { + val oldDrawableById = model.drawables.associateBy { it.id } + // Warp parenting decides whether a drawable owns a control-point texture, and that is fixed at upload: + // a reparent that flips it (deleting a rotation deformer between a drawable and a warp, say) leaves a + // resident whose cp texture is stale or absent, so it must re-upload, not Keep. Derived purely from the + // two models - residency === `model`, so the old warp set matches what the backend actually uploaded. + val oldWarpIds = model.deformers.filterIsInstance().mapTo(HashSet()) { it.id } + val newWarpIds = newModel.deformers.filterIsInstance().mapTo(HashSet()) { it.id } + val actions = ArrayList(newModel.drawables.size) + for (drawable in newModel.drawables) { + val residentVertexCount = residentVertexCountById[drawable.id] + if (residentVertexCount == null) { + actions.add(DrawableAction.Upload(drawable)) + continue + } + val newMesh = drawable.mesh + val oldDrawable = oldDrawableById[drawable.id] + val oldMesh = oldDrawable?.mesh + val warpParentingFlipped = + (oldDrawable != null && oldDrawable.parentDeformerId in oldWarpIds) != (drawable.parentDeformerId in newWarpIds) + val remeshed = + warpParentingFlipped || + ( + newMesh != null && + ( + newMesh.positions.size != residentVertexCount * 2 || + (oldMesh != null && newMesh.indices !== oldMesh.indices) || + drawable.geometryGrid !== oldDrawable?.geometryGrid || + // Blend-shape deltas are baked into the delta texture's appended + // columns, so a binding change invalidates the texture layout. + drawable.blendShapes !== oldDrawable?.blendShapes + ) + ) + if (remeshed) { + actions.add(DrawableAction.Reupload(drawable)) + continue + } + if (newMesh == null || oldMesh == null) { + actions.add(DrawableAction.Keep(drawable, positions = null, uvs = null)) + continue + } + val positions = newMesh.positions.takeIf { it !== oldMesh.positions } + // The length guard is defensive: the copy-on-write UV edit never changes the array length, so a + // mismatch can only mean a mesh the backend padded at upload - leave that resident's UVs alone. + val uvs = newMesh.uvs.takeIf { it !== oldMesh.uvs && it.size == residentVertexCount * 2 } + actions.add(DrawableAction.Keep(drawable, positions, uvs)) + } + // Anything resident with no action is gone from the model. A Reupload is an ACTION, so a drawable that + // is freed and then fails to re-upload cannot also appear here - which is what stops the free happening + // twice, and with it the chance of the second free hitting a GL name the driver has since recycled. + val actioned = actions.mapTo(HashSet(actions.size)) { it.drawableId } + val removed = residentVertexCountById.keys.filter { it !in actioned } + return ModelDiff(actions, removed) +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PixelRows.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PixelRows.kt new file mode 100644 index 0000000..48b3e23 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PixelRows.kt @@ -0,0 +1,29 @@ +package org.umamo.render.puppet + +/** + * Reverses an RGBA8888 image's row order into a fresh buffer. + * + * The bridge between a bottom-up framebuffer read-back and the top-first convention every consumer + * here uses (`org.umamo.format.raster.RasterImage`, and the layered readers' pixel form). OpenGL's + * `glReadPixels` returns the bottom row first, so its device's read-back flips through this; a + * top-left-origin backend (Metal) does not. Which way up a backend reads is therefore a fact confined + * to that backend, and no caller of `readPixels` ever asks. + * + * Row-wise, not per-pixel: the channel order is already what the caller wants, so only the row + * ordering changes. + * + * @param ByteArray rgba The source pixels, RGBA8888, tightly packed, `width * height * 4` bytes. + * @param Int width The image width in pixels. + * @param Int height The image height in pixels. + * @return ByteArray A new buffer with the row order reversed. + */ +internal fun flipRowsVertically(rgba: ByteArray, width: Int, height: Int): ByteArray { + val rowBytes = width * 4 + val flipped = ByteArray(rgba.size) + for (rowIndex in 0 until height) { + val sourceStart = rowIndex * rowBytes + val destinationStart = (height - 1 - rowIndex) * rowBytes + rgba.copyInto(flipped, destinationStart, sourceStart, sourceStart + rowBytes) + } + return flipped +} \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PoseResolve.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PoseResolve.kt new file mode 100644 index 0000000..9579031 --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PoseResolve.kt @@ -0,0 +1,159 @@ +package org.umamo.render.puppet + +import org.umamo.render.eval.DeformerWorld +import org.umamo.render.eval.MeshBlendState +import org.umamo.render.eval.PoseDeformInputs +import org.umamo.render.eval.RenderPlanComposite +import org.umamo.render.eval.RenderPlanDrawable +import org.umamo.render.eval.RenderPlanNode +import org.umamo.render.eval.flattenRenderPlan +import org.umamo.render.eval.paintOrder +import org.umamo.render.eval.renderPlan +import org.umamo.render.glsl.MAX_GLUES +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.RenderGroup + +/** + * One drawable's resolved per-pose deform state - what the backend must hand its shaders to draw it. + * + * @property DrawableId drawableId The drawable. + * @property List corners The active keyform-grid corners and their blend weights. + * @property DeformerWorld parentWorld The baked parent-deformer transform, or null for a direct mesh. + * @property Float opacity The pose-blended opacity. + */ +internal class PosedDrawable( + val drawableId: DrawableId, + val corners: List, + val parentWorld: DeformerWorld?, + val opacity: Float, + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, + val blend: MeshBlendState? = null, +) + +/** + * A pose resolved against what a backend actually has resident. + * + * @property Map posed Every drawable that produced geometry this pose, in + * [PoseDeformInputs.drawables] order. This is a SUPERSET of what is drawn: it includes index-less glue + * anchors and hidden mask sources, both of which must still deform. + * @property List renderPlan The drawn drawables in resolved back-to-front order WITH the + * isolated group boundaries preserved ([RenderPlanComposite] nodes) - what a compositing renderer + * walks. Filtered like [drawOrder]; a composite node whose subtree filtered to empty is dropped. + * @property List drawOrder The drawn drawables, back-to-front (last = front): posed AND + * renderable AND shown, in resolved render order. Always equals the flattened [renderPlan]. + * @property FloatArray glueIntensities Per-glue weld intensity by glue index, length [MAX_GLUES]. + */ +internal class ResolvedPose( + val posed: Map, + val renderPlan: List, + val drawOrder: List, + val glueIntensities: FloatArray, +) + +/** + * Resolves a prepared pose against a backend's residency: which drawables deform, which are actually + * drawn and in what order, and each glue's weld intensity. + * + * Backend-neutral - it decides WHAT to draw, never how. The one thing it needs from the backend is + * [renderableById], because "posed" and "drawn" are genuinely different questions and only the backend + * knows the answer to the second. + * + * @param PoseDeformInputs inputs The prepared per-pose inputs. + * @param Map renderableById Resident drawable id → whether it carries triangles. The KEYS + * are the residency set (a drawable the backend never uploaded cannot pose); the VALUE says whether it + * draws anything. The two differ: an index-less glue anchor is resident and poses - its deformed + * positions are a weld partner - but renders nothing. + * @param Set shownIds The resolved Parts-panel visibility cascade. + * @param List baseOrder The model's flat drawable order, for a group-less model. + * @param RenderGroup renderRoot The draw-order group tree. + * @param FloatArray glueIntensities A caller-owned array of length [MAX_GLUES] this fills in place + * (and returns in [ResolvedPose.glueIntensities]), so a per-pose render allocates no intensity buffer. + * @return ResolvedPose The pose, resolved. + */ +internal fun resolvePose( + inputs: PoseDeformInputs, + renderableById: Map, + shownIds: Set, + baseOrder: List, + renderRoot: RenderGroup, + glueIntensities: FloatArray, +): ResolvedPose { + // LinkedHashMap: iteration follows inputs.drawables order, which the backend's per-pose uploads walk. + val posed = LinkedHashMap(inputs.drawables.size) + val drawOrderById = HashMap(inputs.drawables.size) + for (drawableInputs in inputs.drawables) { + if (drawableInputs.drawableId !in renderableById) { + continue // not resident: the backend has nothing to draw it with + } + val corners = drawableInputs.corners ?: continue // hidden at this pose + if (drawableInputs.isParented && drawableInputs.parentWorld == null) { + continue // a hidden ancestor deformer produced no transform, so the mesh has no geometry + } + posed[drawableInputs.drawableId] = + PosedDrawable( + drawableInputs.drawableId, + corners, + drawableInputs.parentWorld, + drawableInputs.opacity, + drawableInputs.multiplyColor, + drawableInputs.screenColor, + drawableInputs.blend, + ) + drawOrderById[drawableInputs.drawableId] = drawableInputs.drawOrder + } + + // Weld intensity per pose, gated on BOTH meshes being posed. Pass 1 only writes a posed glue mesh's + // region of the shared position store; if a partner is unposed its region is uninitialised, so welding + // toward it would read garbage (random spikes on a live, dirty GPU). A zero intensity makes the weld + // skip the partner read entirely - matching the CPU applyGluesResolved, which skips a glue whose + // partner produced no geometry. Note this asks whether the partner POSED, not whether it draws: an + // index-less anchor is a legitimate partner. + glueIntensities.fill(1f) // slots beyond glues.size stay 1f and are never read by the shader + for ((glueIndex, glue) in inputs.glues.withIndex()) { + if (glueIndex >= MAX_GLUES) { + continue // beyond the shader's glueIntensity[] array: this glue renders unwelded + } + val bothPosed = glue.meshA in posed && glue.meshB in posed + glueIntensities[glueIndex] = if (bothPosed) glue.intensity else 0f + } + + // Hierarchical render plan over the draw-order group tree (with per-pose animated part order); the + // flat base order when the model carries no groups. The drawn-filter applies to the PLAN (an + // isolated subtree that filters to empty disappears with its composite), and the flat draw order + // is its flattening - the two views can never disagree. + val plan = + if (renderRoot.children.isEmpty()) { + paintOrder(baseOrder, drawOrderById).map(::RenderPlanDrawable) + } else { + renderPlan(renderRoot, drawOrderById, inputs.partDrawOrders) + } + val drawnPlan = filterPlan(plan) { it in posed && renderableById[it] == true && it in shownIds } + return ResolvedPose(posed, drawnPlan, flattenRenderPlan(drawnPlan), glueIntensities) +} + +/** + * Filters a render plan's drawable leaves by [isDrawn], dropping a composite node whose whole + * subtree filtered away (compositing an empty layer would be a wasted pass, and the visibility + * cascade lands here - a hidden part's drawables all fail the shown filter). + * + * @param List nodes The plan nodes. + * @param Function isDrawn Whether a drawable is actually drawn this pose. + * @return List The filtered plan. + */ +private fun filterPlan(nodes: List, isDrawn: (DrawableId) -> Boolean): List = + nodes.mapNotNull { node -> + when (node) { + is RenderPlanDrawable -> node.takeIf { isDrawn(it.id) } + is RenderPlanComposite -> { + val children = filterPlan(node.children, isDrawn) + if (children.isEmpty()) { + null + } else { + RenderPlanComposite(node.partId, node.composite, children) + } + } + } + } \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PosedAabb.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PosedAabb.kt new file mode 100644 index 0000000..74bc8eb --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PosedAabb.kt @@ -0,0 +1,125 @@ +package org.umamo.render.puppet + +import org.umamo.render.eval.DeformerWorld +import org.umamo.render.eval.MeshBlendState +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.MeshDeltaForm +import kotlin.math.max +import kotlin.math.min + +/* + * Exact per-pose drawable world bounds - the screen rectangle the composite scissor is built from. + * + * The renderer confines a composite layer's clear, destination snapshot, and composite draw to the + * isolated subtree's screen rect, so an isolated group costs fill proportional to its own extent + * rather than the whole viewport. Conservatism is the whole contract: an undersized bound clips + * rendered pixels (a head-top or an arm past its warp lattice would vanish), so this evaluates the + * SAME deform the shader does - `base + Sigma w_i * delta_i`, plus blend-shape deltas, through the + * parent deformer, then the Y negation - and takes the true AABB of the deformed vertices. A cheap + * analytic lattice bound was tried and abandoned: a warp deformer's out-of-lattice extrapolation is + * piecewise and does not decompose into a conservative closed form, so it undersized at the extremes. + * + * The per-vertex walk is allocation-free (a running min/max plus a 2-float transform scratch) and the + * cells map is precomputed once at upload, so it costs only the composited drawables' vertices per + * pose - a fraction of a full CPU deform, and dwarfed by the fill it saves. + */ + +/** An axis-aligned bounding rectangle in the renderer's post-Y-negation world space. */ +internal class PosedAabb( + val minX: Float, + val minY: Float, + val maxX: Float, + val maxY: Float, +) + +/** + * The exact deformed-world AABB of one drawable at the current pose: the keyform-blended local + * vertices (plus blend-shape deltas) pushed through [parentWorld] and Y-negated, min/maxed. Mirrors + * `deformMeshWorldFromCorners` component for component so the bound can never disagree with the + * rendered geometry. Returns null when the mesh is empty. + * + * @param FloatArray base The mesh's rest positions, interleaved x,y. + * @param Map> cells The grid's cells by linear index (precomputed once). + * @param List corners The pose's active keyform corners and weights. + * @param DeformerWorld? parentWorld The baked parent transform, or null for a direct mesh. + * @param MeshBlendState? blend The pose's resolved blend-shape state, or null. + * @return PosedAabb? The world bounds, or null when the mesh has no vertices or a vertex deforms to a + * non-finite position (an unusable bound the renderer treats as "no bound", keeping the full-viewport path). + */ +internal fun deformedWorldBounds( + base: FloatArray, + cells: Map>, + corners: List, + parentWorld: DeformerWorld?, + blend: MeshBlendState?, +): PosedAabb? { + val vertexCount = base.size / 2 + if (vertexCount == 0) { + return null + } + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + val scratch = FloatArray(2) + for (vertexIndex in 0 until vertexCount) { + val componentX = vertexIndex * 2 + val componentY = componentX + 1 + var localX = base[componentX] + var localY = base[componentY] + // The multilinear keyform blend: base + Sigma w_i * delta_i (a missing cell or short delta + // array contributes zero, exactly as buildDeltaTexels and blendLocalFromCorners treat it). + for (corner in corners) { + val deltas = cells[corner.linearIndex]?.form?.positionDeltas ?: continue + if (componentY < deltas.size) { + localX += corner.weight * deltas[componentX] + localY += corner.weight * deltas[componentY] + } + } + // Blend shapes: additive per-vertex deltas relative to the grid-at-default reference, on top + // of the grid blend, before the parent transform - the exact deformMeshWorldFromCorners loop. + if (blend != null) { + for (contribution in blend.contributions) { + val deltas = contribution.form.positionDeltas + if (componentY < deltas.size) { + val referenceX = blend.referenceDeltas?.getOrNull(componentX) ?: 0f + val referenceY = blend.referenceDeltas?.getOrNull(componentY) ?: 0f + localX += contribution.weight * (deltas[componentX] - referenceX) + localY += contribution.weight * (deltas[componentY] - referenceY) + } + } + } + val worldX: Float + var worldZ: Float + if (parentWorld != null) { + parentWorld.apply(localX, localY, scratch, 0) + worldX = scratch[0] + worldZ = scratch[1] + } else { + worldX = localX + worldZ = localY + } + worldZ = -worldZ // the renderer's final Y negation + minX = min(minX, worldX) + minY = min(minY, worldZ) + maxX = max(maxX, worldX) + maxY = max(maxY, worldZ) + } + // A non-finite extent (a warp-extrapolated vertex divided by a degenerate cell, or corrupt control + // points) is NOT a usable bound: publish none, so the renderer keeps the safe full-viewport path + // rather than deriving a garbage scissor rect that would clip the whole subtree. + if (!minX.isFinite() || !minY.isFinite() || !maxX.isFinite() || !maxY.isFinite()) { + return null + } + return PosedAabb(minX, minY, maxX, maxY) +} + +/** The union of two bounds. */ +internal fun unionBounds(first: PosedAabb, second: PosedAabb): PosedAabb = + PosedAabb( + min(first.minX, second.minX), + min(first.minY, second.minY), + max(first.maxX, second.maxX), + max(first.maxY, second.maxY), + ) \ No newline at end of file diff --git a/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PuppetRenderer.kt b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PuppetRenderer.kt new file mode 100644 index 0000000..f73242b --- /dev/null +++ b/module/render/src/commonMain/kotlin/org/umamo/render/puppet/PuppetRenderer.kt @@ -0,0 +1,2280 @@ +package org.umamo.render.puppet + +import org.umamo.format.raster.RasterImage +import org.umamo.render.ContentBounds +import org.umamo.render.DecodedImage +import org.umamo.render.FrameBackdrop +import org.umamo.render.GridColors +import org.umamo.render.LayerDrawPlan +import org.umamo.render.LayerRasterBatch +import org.umamo.render.PuppetTextures +import org.umamo.render.SupersampledSurface +import org.umamo.render.ViewportCamera +import org.umamo.render.WorldAxisColors +import org.umamo.render.device.AxisLineUniforms +import org.umamo.render.device.CompositeUniforms +import org.umamo.render.device.DeformCapturePipeline +import org.umamo.render.device.DeformUniforms +import org.umamo.render.device.DeformedPositionStore +import org.umamo.render.device.DrawTextures +import org.umamo.render.device.FragmentUniforms +import org.umamo.render.device.FrameEncoder +import org.umamo.render.device.GpuMesh +import org.umamo.render.device.GpuTexture +import org.umamo.render.device.GridUniforms +import org.umamo.render.device.LoadAction +import org.umamo.render.device.MeshSpec +import org.umamo.render.device.PipelineBlend +import org.umamo.render.device.PipelinePurpose +import org.umamo.render.device.RenderDevice +import org.umamo.render.device.RenderPassEncoder +import org.umamo.render.device.RenderPipeline +import org.umamo.render.device.RenderPipelineSpec +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.ScissorRect +import org.umamo.render.device.TextureFilter +import org.umamo.render.device.TextureFormat +import org.umamo.render.device.TextureWrap +import org.umamo.render.device.WorldToNdc +import org.umamo.render.eval.DeformedGeometry +import org.umamo.render.eval.DeformerWorld +import org.umamo.render.eval.MeshBlendState +import org.umamo.render.eval.PartRenderState +import org.umamo.render.eval.PoseDeformInputs +import org.umamo.render.eval.RenderPlanComposite +import org.umamo.render.eval.RenderPlanDrawable +import org.umamo.render.eval.RenderPlanNode +import org.umamo.render.eval.RotationWorld +import org.umamo.render.eval.WarpWorld +import org.umamo.render.eval.applyCpuDeform +import org.umamo.render.eval.preparePose +import org.umamo.render.glsl.MAX_BLEND_CORNERS +import org.umamo.render.glsl.MAX_CORNERS +import org.umamo.render.glsl.MAX_GLUES +import org.umamo.render.glsl.SELECTION_TINT_STRENGTH +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.visibleDrawableIds +import kotlin.concurrent.Volatile +import kotlin.math.ceil +import kotlin.math.floor + +/** + * How many on-demand underlay images stay uploaded at once. Small on purpose: a UV editor shows one + * layer at a time, so this covers a few areas plus the layer they were just looking at, and bounds + * GPU memory against a document carrying hundreds of layers. + */ +private const val UNDERLAY_TEXTURE_CACHE_SIZE = 4 + +/** + * Framebuffer pixels per output pixel for an image capture. Two, and only two: the resolve is a + * filtered blit, which at exactly 2:1 samples the midpoint of each 2x2 block and so IS the box average, + * while at 4:1 it would sample 4 of 16 texels and alias. + */ +const val SNAPSHOT_SUPERSAMPLE = 2 + +/** + * The largest tile an image capture renders in one piece, in output pixels. At the 2x supersample a + * tile's targets are at most 4096 square (64 MiB each), so a capture's GPU memory stays bounded whatever + * the image size - a 1:1 capture of a tall Live2D canvas is thousands of pixels on a side. + */ +const val SNAPSHOT_TILE_EDGE = 2048 + +/** + * The smallest posed opacity that leaves any coverage in an 8-bit image: below half of one alpha step the + * drawable rounds to nothing, so a capture's framing does not measure it. + */ +private const val MINIMUM_DRAWN_OPACITY = 0.5f / 255f + +/** + * GPU-deforming puppet renderer, over a [RenderDevice]. + * + * The keyform morph + deformer cascade run in the vertex shader; the CPU only prepares the cheap per-pose + * data. Glue (seam-welding vertex pairs across two meshes) is a two-pass GPU step: pass 1 + * transform-feedback-deforms every glue-involved mesh into one shared position store, pass 2 renders the + * visible glue meshes welding own + partner positions read from that store. Non-glue meshes render in a + * single deform pass. Draws in Cubism render order with per-drawable opacity, blend, and masks. + * + * This class holds NO GL - every GPU operation goes through [device], and every decision (glue layout, + * pose resolution, model diff) is a backend-neutral call into `org.umamo.render.puppet`. A second + * backend is therefore a second [RenderDevice], not a second renderer. It runs on the render thread; the + * host makes [device]'s context current there. + */ +class PuppetRenderer( + private val model: PuppetModel, + // var: the session owns the effective page set now - a repack swaps it mid-session through + // setAtlasPages, which re-points this at the set the uploaded handles came from. + private var textures: PuppetTextures, + private val device: RenderDevice, +) { + // Draw pipelines by blend x cull, plus the fixed-purpose ones, created lazily and reused every frame. + // Cull is index [0]=double-sided / [1]=back-face-culled so the per-draw lookup allocates no key. + private val puppetPipelines = Array(2) { HashMap() } + private val gluePipelines = Array(2) { HashMap() } + private var atlasPagePipeline: RenderPipeline? = null + private var gridPipeline: RenderPipeline? = null + private var axisPipeline: RenderPipeline? = null + private var compositePipeline: RenderPipeline? = null + private var capturePipeline: DeformCapturePipeline? = null + + // Rest-pose content extent, computed lazily and reused for contentBounds()/the fit fallback; re-armed + // by updateModel/setShownDrawables so the framing follows geometry and visibility edits. + private var minX = 0f + private var minY = 0f + private var spanX = 1f + private var spanY = 1f + private var bboxReady = false + + // The view to project through. null until setCamera; render() then fits contentBounds by default. + private var currentCamera: ViewportCamera? = null + + // The last pose's prepared deform inputs, cached so picking can re-run the CPU deform on demand (at + // click time, off the render thread) without re-doing it every frame. Immutable once built, so the + // volatile reference is a safe publish to the UI thread that calls pickGeometry. null before first pose. + @Volatile + private var lastPoseInputs: PoseDeformInputs? = null + + // Drawables currently selected, tinted by the highlight uniform when drawn. Set from the UI thread + // (a wholesale immutable-set swap, so a volatile reference is a safe publish); read on the render thread. + @Volatile + private var selectedIds: Set = emptySet() + + // The color selected drawables are tinted toward (the selection highlight), fed from the editor settings + // on the UI thread and read on the render thread. Defaults to the classic blue accent until the host + // pushes the configured color. RGB, each 0..1; the immutable FloatArray swap makes the volatile + // reference a safe publish. + @Volatile + private var highlightColor: FloatArray = floatArrayOf(0.20f, 0.55f, 1.0f) + + // The active (last-selected) drawable, tinted toward activeHighlightColor instead of highlightColor so + // the primary target of a multi-selection reads apart from the rest. Set from the UI thread; null when + // nothing is active. Always a member of selectedIds when non-null. + @Volatile + private var activeId: DrawableId? = null + + // The color the active drawable is tinted toward, fed from the editor settings alongside highlightColor. + // Defaults to the edit-mode active green (#7DE400) until the host pushes the configured color. + @Volatile + private var activeHighlightColor: FloatArray = floatArrayOf(0.49f, 0.89f, 0.0f) + + // The last pose's resolved draw list (back-to-front; last = front), published for picking. This folds + // in the parts/group hierarchy, so it is the authoritative front/back order. Render-thread-written, + // UI-thread-read; the immutable list swap is a safe publish. + @Volatile + private var lastDrawnOrder: List = emptyList() + + // Framebuffer pixels per on-screen pixel. 1 = native; the offscreen service sets >1 when it supersamples, + // so the grid line width scales to match and reads back at a constant on-screen size. + private var gridPixelScale: Float = 1f + + // The grid backdrop colors, set from the editor theme via setGrid; defaults to a neutral grey grid. + private var gridColors: GridColors = GridColors.Classic + + // The per-document grid geometry (major line spacing in world units, and subdivisions per major cell). + private var gridScale: Float = 100f + private var gridSubdivisions: Int = 10 + + // The coverage target the mask pass renders into and the masked draws sample. Grow-only: kept at + // a per-axis high-water capacity and rendered into via an origin-anchored viewport, so a gutter + // drag's per-frame size changes never destroy + recreate it. The shader's screen-space lookup + // divides gl_FragCoord by the ALLOCATED size (screenTexSize), which is what keeps the lookup + // lined up when the capacity exceeds the viewport. + private var maskTarget: RenderTarget? = null + + // The layer-composite targets: one layer target per nesting depth (grown lazily to the deepest + // isolated group actually rendered) plus one shared destination-snapshot target - composites are + // strictly sequential, so a single snapshot suffices. All allocated at the SAME capacity as the + // mask target, because the composite shader samples layer, snapshot, and mask through one + // screenTexSize divisor - so the three must share allocation dims, and they grow together. + private val compositeTargets = ArrayList() + private var snapshotTarget: RenderTarget? = null + + // The shared side-target capacity (mask + snapshot + composite pool), each axis a high-water mark. + private var sideTargetCapacityWidth = 0 + private var sideTargetCapacityHeight = 0 + + // The shared pass-1 deformed-position store; null when the model has no glue. + private var store: DeformedPositionStore? = null + private var glueIntensities = FloatArray(MAX_GLUES) { 1f } + + // Pass 1 only needs to re-deform the shared store when the pose changed; on a static pose its contents + // are unchanged. Set by setPose, consumed by render. Gating here also confines the write→read barrier + // to pose-change frames. + private var glueBufferDirty = true + + // Reused per-draw uniform + texture scratch, refilled each draw rather than allocated. Render-thread only. + private val deformScratch = DeformUniforms() + private val fragmentScratch = FragmentUniforms() + private val texturesScratch = DrawTextures() + private val compositeScratch = CompositeUniforms() + + // Which resident drawables carry triangles (id → indexCount > 0). Residency changes only at initGl and + // updateModel, and setPose is far hotter (every pose tick during a drag), so this is cached and rebuilt + // only where gpuById itself changes rather than mapped afresh every pose. + private var renderableById: Map = emptyMap() + + // Edit-mode mesh-edit guide: while a drawable id is in this set, updateModel keeps its GPU mesh + // (positions / uvs / indices / deltas) frozen at the geometry it had when frozen, so deleting verts / + // faces only updates the Compose wireframe and never punches holes in the textured image under it + // (Cubism Mesh Edit's model-guide image). Leaving Edit clears the set and force-reuploads from the + // live model. Render-thread only. + private var editMeshFrozenIds: Set = emptySet() + + /** + * A drawable resident on the GPU. Static residency (mesh, delta texture, optional warp control-point + * texture, atlas) plus the per-pose state setPose stamps onto it. [isGlueMesh] meshes are deformed in + * pass 1 (even index-less anchors, whose positions are weld partners) and rendered via the glue pipeline + * in pass 2. + */ + private class GpuDrawable( + val id: DrawableId, + val mesh: GpuMesh, + val deltaTexture: GpuTexture, + val vertexCount: Int, + val indexCount: Int, + val cpTexture: GpuTexture?, + // The atlas page this drawable samples. A var because a repack swaps the page set mid-session + // and setAtlasPages re-stamps every resident - the index map moves with the pages, not just the + // handles. + var atlasTexture: GpuTexture?, + // The drawable's SOURCE ARTWORK alternative to the atlas, and the affine carrying its stored + // coordinates into that image's frame. Both var: a drawable acquires them when the document + // switches to source-artwork display, which is a state change, not a re-upload. Null means this + // drawable has no recoverable art and keeps rendering from the atlas - the mode is best-effort + // per drawable, so a document is routinely mixed. + var layerTexture: GpuTexture? = null, + var layerUvAffine: FloatArray? = null, + val color: FloatArray, + // Static composite state: var because a composite-only edit is a ModelDiff Keep (no buffer work), + // which re-stamps these on the reused resident in updateModel - or the viewport would keep drawing + // with the blend/mask/culling captured at upload until an unrelated topology change forced a reupload. + var blendMode: BlendMode, + /** The drawable's 5.3 alpha blend; non-Over routes the draw through the composite path. */ + var alphaBlendMode: AlphaBlendMode, + /** The Cubism Culling toggle: true culls back faces, false (default) is double-sided. */ + var culling: Boolean, + var maskIds: List, + var invertMask: Boolean, + val isGlueMesh: Boolean, + val glueBaseOffset: Int, + /** The static blend-shape column assignment in [deltaTexture] (empty when binding-free). */ + val blendLayout: BlendColumnLayout, + /** + * Rest positions for the exact composite-scissor bounds (see PosedAabb). A var because an + * in-place base-mesh move (updateModel's Keep-with-positions tier) re-uploads new positions to + * the GPU mesh and must re-point this at them, or the bounds walk would size the scissor to the + * pre-edit geometry and clip the moved vertices. + */ + var boundsBase: FloatArray, + /** Grid cells by linear index for the bounds walk; a keyform edit re-uploads whole (Reupload). */ + val boundsCells: Map>, + ) { + /** + * The texture this drawable actually samples: its source artwork when the document displays from + * artwork AND this drawable has recoverable art, else the atlas page it was packed onto. + * + * The fallback is per drawable on purpose - art the document does not retain, a placement that + * will not invert, or a layer that would not decode all leave a drawable on the atlas rather than + * removing it from the puppet. + * + * @return GpuTexture? The texture to bind, or null when the drawable has neither. + */ + fun activeTexture(): GpuTexture? = layerTexture ?: atlasTexture + + var corners: List? = null + var parentWorld: DeformerWorld? = null + var opacity: Float = 1f + var multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity + var screenColor: ColorRgb = ColorRgb.ScreenIdentity + var visible: Boolean = false + + /** The pose's resolved blend-shape state; null for binding-free drawables. */ + var blend: MeshBlendState? = null + + /** + * Whether this drawable's blend is a 5.3 extended blend (not fixed-function-expressible), so it + * routes through the destination-sampling composite path rather than a plain draw. + */ + val isExtendedBlend: Boolean + get() = !blendMode.isLegacy || alphaBlendMode != AlphaBlendMode.Over + } + + // The live model used for the per-pose deform eval, the render order, and the reconcile diff. A var so + // an edit can re-push it via updateModel. @Volatile because the render thread writes it while the UI + // thread reads it (pickGeometry); a PuppetModel is immutable, so the reference swap is a safe publish. + @Volatile + private var currentModel: PuppetModel = model + private var baseOrder: List = model.drawables.map { it.id } + private var currentRenderRoot: RenderGroup = model.renderRoot + + // Effective Parts-panel visibility (own eyeball ∧ every ancestor part's), resolved once per change. Gates + // only the drawn list; hidden meshes that are mask sources or glue partners still deform. Render-thread only. + private var shownDrawableIds: Set = model.visibleDrawableIds() + private var glueDeformList: List = emptyList() + private var gpuById: Map = emptyMap() + + // The pose's resolved render plan (back-to-front with composite boundaries) and the per-isolated-part + // pose-blended composite channels, both set by setPose and walked by render. Render-thread only. + private var currentPlan: List = emptyList() + private var currentCompositeStates: Map = emptyMap() + + // Per-pose composite acceleration state, derived from the plan by setPose (render-thread only): + // isolated parts whose composite is a pose-identity Normal/Over over an all-Normal/Over subtree + // (render() draws those inline - no layer, no snapshot, no composite draw; premultiplied Over is + // associative, so the pixels are identical up to one less 8-bit quantization), and the + // conservative world bounds of each isolated subtree / extended-blend drawable (render() scissors + // the layer clear, snapshot copy, and composite draw to them - except Out-alpha composites, whose + // blend erases the destination wherever the layer is EMPTY, so they keep the full-viewport path). + private var flattenableComposites: Set = emptySet() + private var compositeWorldBounds: Map = emptyMap() + private var extendedDrawableWorldBounds: Map = emptyMap() + + // The two composite accelerations, each independently switchable so a correctness test can render + // the same pose with either or both disabled and assert every combination is pixel-preserving on + // real corpus models. [compositeFlattenEnabled] draws identity Normal/Over groups inline; + // [compositeBoundsScissorEnabled] confines a composite's layer work (and the empty-layer skip) to + // the subtree's bounds. Both on by default. + internal var compositeFlattenEnabled = true + internal var compositeBoundsScissorEnabled = true + + // Glue weld partners by drawable (both directions), rebuilt with residency: a glue mesh's welded + // vertices stay inside the hull of its own and its partners' unwelded bounds, so the bounds walk + // unions the partner extents in. + private var gluePartnersById: Map> = emptyMap() + + // The uploaded atlas pages, index-parallel to PuppetTextures.atlases. Retained so a structural reconcile + // in updateModel can bind a newly-uploaded drawable to its page. + private var atlasHandles: List = emptyList() + + // Underlay images uploaded on demand (the UV editor's source-layer view), keyed by image identity and + // insertion-ordered so eviction drops the oldest. Unlike atlasHandles, which upload and free as one + // whole page set (at init, or wholesale on a setAtlasPages swap), these arrive and are created or + // destroyed one at a time across the renderer's life - as the source-artwork textures below also are. + private val underlayTextures = LinkedHashMap() + + // Which artwork every drawable would display from - the mapping, complete for the whole document and + // carrying no pixels. Retained so a structural reconcile can re-stamp a rebuilt resident, exactly as + // atlasHandles is, and so a layer dropped for budget can be promoted again without rebuilding it. + private var layerPlan: LayerDrawPlan = LayerDrawPlan.EMPTY + + // The uploaded artwork, keyed by LAYER (duplicated art is shared, so this is the count of distinct + // images, not of drawables). Only applySourceLayerDisplay adds to or removes from it, because + // freeing a texture is only safe together with the re-stamp that stops drawables pointing at it. + private val layerTextures = HashMap() + + // Layers the document references but whose pixels would not decode. Held so the ask stops repeating + // them; cleared with the plan, because a new document may well decode them. + private val undecodableLayerKeys = HashSet() + + // Whether the puppet is actually displaying from artwork. False until every mapped layer has landed, + // which is what keeps the mode from ever showing a half-artwork puppet. + private var sourceLayerDisplayReady = false + + // Whether render() draws the world-origin axis lines. Off by default so headless render-diff tests stay + // line-free; the editor's viewport host opts in. + private var worldAxesVisible = false + + /** + * Creates the pipelines, uploads the atlas page(s), lays out the shared glue store, and uploads each + * drawable's static data. Must run with the device's context current. + */ + fun initGl() { + capturePipeline = device.createDeformCapturePipeline() + atlasPagePipeline = device.createRenderPipeline(RenderPipelineSpec(PipelinePurpose.AtlasPageDraw, PipelineBlend.Normal)) + gridPipeline = device.createRenderPipeline(RenderPipelineSpec(PipelinePurpose.GridBackdrop, PipelineBlend.Opaque)) + axisPipeline = device.createRenderPipeline(RenderPipelineSpec(PipelinePurpose.WorldAxisLine, PipelineBlend.Opaque)) + // Blending disabled: the composite shader computes the whole blend from layer + snapshot. + compositePipeline = device.createRenderPipeline(RenderPipelineSpec(PipelinePurpose.Composite, PipelineBlend.Opaque)) + atlasHandles = textures.atlases.map(::atlasPageTexture) + val warpDeformerIds = model.deformers.filterIsInstance().map { it.id }.toSet() + + // Glue addressing is planned in commonMain; the device holds the store and the interleaved attrs. + val glueLayout = planGlueLayout(model) + if (glueLayout.globalVertexCount > 0) { + store = device.createDeformedPositionStore(glueLayout.globalVertexCount) + } + + val uploaded = ArrayList() + for (drawable in model.drawables) { + val gpuDrawable = + uploadDrawable( + drawable = drawable, + glueAttributes = glueLayout.attributesById[drawable.id], + glueBaseOffset = glueLayout.baseOffsetById[drawable.id] ?: 0, + warpDeformerIds = warpDeformerIds, + ) ?: continue + uploaded.add(gpuDrawable) + } + gpuById = uploaded.associateBy { it.id } + glueDeformList = uploaded.filter { it.isGlueMesh } + renderableById = gpuById.mapValues { (_, resident) -> resident.indexCount > 0 } + rebuildGluePartners(model) + } + + /** + * Uploads one drawable's static GPU data and returns its resident [GpuDrawable], or null when it draws + * nothing (no mesh, no keyforms, empty geometry, or a triangle-less non-glue mesh). Shared by [initGl] + * and the structural reconcile in [updateModel]; must run with the device's context current. + * + * @param Drawable drawable The model drawable. + * @param GlueVertexAttributes? glueAttributes Its planned weld attributes, or null when not glued. + * @param Int glueBaseOffset Its base index in the shared glue store (0 when not glued). + * @param Set warpDeformerIds The model's warp deformers. + * @return GpuDrawable? The uploaded drawable, or null when it draws nothing. + */ + private fun uploadDrawable( + drawable: Drawable, + glueAttributes: GlueVertexAttributes?, + glueBaseOffset: Int, + warpDeformerIds: Set, + ): GpuDrawable? { + val mesh = drawable.mesh ?: return null + // A null grid is an UNKEYED drawable, which uploads a single all-zero delta column and renders at + // its rest mesh. Refusing to upload it would leave a freshly created (or freshly unbound) drawable + // invisible - the one state where the rigger most needs to see it. + val grid = drawable.geometryGrid + if (mesh.positions.isEmpty()) { + return null + } + val isGlue = glueAttributes != null + if (!isGlue && mesh.indices.isEmpty()) { + return null // a non-glue mesh with no triangles draws nothing and is no weld partner + } + val cellCount = keyformCellCount(grid) + val vertexCount = mesh.positions.size / 2 + // Built once and shared: the delta-texel bake and the composite-bounds walk both need it. An + // unkeyed drawable has no cells, so every lookup misses and contributes a zero offset. + val cells = if (grid != null) cellsByLinearIndex(grid) else emptyMap() + // Blend-shape delta columns append after the grid cells; the zero-blend layout is empty and + // the texture build reduces to the plain grid texels. + val blendLayout = blendColumnLayout(drawable, cellCount) + val defaults = currentModel.parameters.associate { it.id to it.default } + val texels = + if (blendLayout.blendColumnCount > 0) { + buildDeltaTexelsWithBlend(grid, drawable, { defaults[it] ?: 0f }, vertexCount, blendLayout, cells) + } else { + buildDeltaTexels(grid, vertexCount, cellCount, cells) + } + val deltaTexture = + device.createFloatTexture(cellCount + blendLayout.blendColumnCount, vertexCount, TextureFilter.Nearest, texels) + val gpuMesh = device.createMesh(MeshSpec(mesh.positions, mesh.uvs, mesh.indices, glueAttributes)) + // A warp-parented drawable needs a control-point texture setPose re-specifies each pose. Created as a + // 1x1 placeholder here so updateFloatTexture always has a handle to overwrite. + val cpTexture = + if (drawable.parentDeformerId in warpDeformerIds) { + device.createFloatTexture(1, 1, TextureFilter.Nearest, FloatArray(2)) + } else { + null + } + // The atlas mapping is keyed by the SOURCE format's drawable ids, so a session-created copy resolves + // its page through the drawable it was duplicated from (Drawable.textureSourceId). + val atlasIndex = textures.atlasIndexByDrawableId[(drawable.textureSourceId ?: drawable.id).raw] + return GpuDrawable( + id = drawable.id, + mesh = gpuMesh, + deltaTexture = deltaTexture, + vertexCount = vertexCount, + indexCount = mesh.indices.size, + cpTexture = cpTexture, + atlasTexture = atlasIndex?.let { atlasHandles[it] }, + color = fallbackColorFor(drawable.id.raw), + blendMode = drawable.blendMode, + alphaBlendMode = drawable.alphaBlendMode, + culling = drawable.culling, + maskIds = drawable.maskedBy, + invertMask = drawable.invertMask, + isGlueMesh = isGlue, + glueBaseOffset = glueBaseOffset, + blendLayout = blendLayout, + boundsBase = mesh.positions, + boundsCells = cells, + ) + } + + /** + * Sets which artwork every drawable would display from. An empty plan returns the whole puppet to + * its atlas pages. + * + * The plan carries no pixels, so this is cheap. The pixels follow through + * [deliverSourceLayerRasters], and the puppet keeps displaying from its atlas until they ALL have - + * the producer streams them in chunks rather than holding the document's artwork decoded at once. + * + * Render thread only - it frees GPU resources through the display pass below. + * + * @param LayerDrawPlan plan The mapping to display by, or [LayerDrawPlan.EMPTY] for the atlas. + */ + fun setSourceLayerPlan(plan: LayerDrawPlan) { + if (plan === layerPlan) { + return + } + layerPlan = plan + // A new plan is a new document or a new drawable set; a layer that would not decode for the old + // one deserves another chance rather than being written off for the renderer's life. + undecodableLayerKeys.clear() + applySourceLayerDisplay() + } + + /** + * Takes delivery of decoded artwork, uploading it for the current plan. + * + * Render thread only: it creates and destroys GPU resources, so it must run with the context + * current. The engine holds the pending value and calls this from inside the render loop, the way + * every other renderer input arrives. + * + * The batch is consumed, never retained - its images are uploaded and the reference dropped, so the + * decoded bytes do not outlive the call. + * + * @param LayerRasterBatch batch The decoded artwork to take up. + */ + fun deliverSourceLayerRasters(batch: LayerRasterBatch) { + undecodableLayerKeys.addAll(batch.undecodableLayerKeys) + for ((layerKey, image) in batch.rastersByLayerKey) { + if (layerKey in layerTextures || layerKey !in layerPlan.layerByteCostByKey) { + continue + } + layerTextures[layerKey] = + device.createTexture( + image.width, + image.height, + TextureFormat.Rgba8, + TextureFilter.Linear, + image.rgba, + // A drawable's mesh overhangs the art it samples, so its recovered coordinates run past + // this image - across the corpus by up to 443 layer pixels. An atlas page absorbs that + // overhang in its own padding; a layer image has no padding to absorb it, so the wrap + // mode is what has to supply the transparency (see TextureWrap). + TextureWrap.ClampToTransparentBorder, + ) + } + applySourceLayerDisplay() + } + + /** + * Frees artwork the current plan does not want, re-points every resident, and republishes the ask. + * + * THE ONLY MUTATOR of [layerTextures]: freeing a texture while a drawable still points at it leaves a + * dangling handle that draws garbage, so freeing and the re-stamp are one operation rather than two a + * caller must remember to pair. + * + * Display is ALL OR NOTHING. Source-artwork display is an inspection mode - the rigger is looking at + * the art to judge it - so a puppet showing artwork for some drawables and atlas pages for the rest + * is not a partial success, it is a view that cannot be trusted, because nothing on screen + * distinguishes the two. Until every layer the plan maps has either landed or proved undecodable, + * the whole puppet stays on its atlas. + * + * The one permitted mix is artwork that does not EXIST: a drawable the document retains no art for, + * or art that will not decode, keeps its atlas page and is counted and reported to the rigger. That + * is honest - the mode cannot show what is not there - and it is bounded and named, where a + * memory-driven mix would be silent and arbitrary. + */ + private fun applySourceLayerDisplay() { + val wanted = layerPlan.layerByteCostByKey.keys - undecodableLayerKeys + // Artwork no longer mapped is freed whether or not the mode is engaged: it is dead either way, and + // holding it would let a document switch leak the previous one's pages. + val obsolete = layerTextures.keys.filter { layerKey -> layerKey !in wanted } + for (layerKey in obsolete) { + layerTextures.remove(layerKey)?.let { texture -> device.destroyTexture(texture) } + } + sourceLayerDisplayReady = wanted.isNotEmpty() && layerTextures.keys.containsAll(wanted) + for ((drawableId, gpuDrawable) in gpuById) { + stampSourceLayer(gpuDrawable, drawableId) + } + } + + /** + * Whether the puppet is displaying from source artwork, for tests and diagnostics. + * + * @return Triple Whether the mode is engaged, the resident layer count, and how many the plan maps. + */ + internal fun sourceLayerDisplayState(): Triple = + Triple(sourceLayerDisplayReady, layerTextures.size, layerPlan.layerByteCostByKey.size) + + /** + * Points one resident at its source artwork, or back at its atlas page when the current set does not + * cover it. + * + * Applied to EVERY resident, not just the drawn ones: a mask source is posed and drawn into the + * coverage pass while sitting outside the shown set, and a mask sampling one frame while the art it + * clips samples the other cuts the silhouette to garbage. + * + * Nothing points at artwork until the mode is READY - every mapped layer landed - so the puppet is + * never caught half in one frame and half in the other. After that, the only drawables left on the + * atlas are the ones whose artwork does not exist, which are counted and reported. + * + * @param GpuDrawable gpuDrawable The resident to stamp. + * @param DrawableId drawableId Its id, keying into the current plan. + */ + private fun stampSourceLayer(gpuDrawable: GpuDrawable, drawableId: DrawableId) { + val draw = if (sourceLayerDisplayReady) layerPlan.drawsByDrawableId[drawableId.raw] else null + val texture = draw?.let { layerTextures[it.layerKey] } + gpuDrawable.layerTexture = texture + gpuDrawable.layerUvAffine = if (texture != null) draw.uvAffine else null + } + + /** + * Swaps the atlas page set: destroys the uploaded pages, uploads [next]'s, re-points [textures], and + * re-stamps every resident's page binding. One operation, because freeing a page is only safe + * together with the re-stamp that stops drawables sampling it - the same rule + * [applySourceLayerDisplay] states for artwork. Must run with the device's context current. + * + * @param PuppetTextures next The new page set. + */ + fun setAtlasPages(next: PuppetTextures) { + if (next === textures) { + // The set the handles already came from - a re-published wrapper around unchanged pages. + return + } + for (handle in atlasHandles) { + device.destroyTexture(handle) + } + textures = next + atlasHandles = next.atlases.map(::atlasPageTexture) + applyAtlasBinding() + } + + /** + * Uploads one atlas page. + * + * The page wraps to a transparent border, like a layer image: a document's pages are not always + * packed atlases - a CMO3 draws some drawables straight from their model image - and a mesh + * overhangs its art, so an edge-clamped page would repeat its border across the overhang as a + * streak. On a packed page the overhang lands on padding and the wrap never comes into play. + * + * @param DecodedImage page The page's pixels. + * @return GpuTexture The texture handle. + */ + private fun atlasPageTexture(page: DecodedImage): GpuTexture = + device.createTexture(page.width, page.height, TextureFormat.Rgba8, TextureFilter.Linear, page.rgba, TextureWrap.ClampToTransparentBorder) + + /** + * Re-points every resident at its atlas page under the current [textures] - the atlas twin of + * [applySourceLayerDisplay]'s stamp pass. The index map is re-read per resident, not just the + * handles: a repack can move a drawable to a different page, so the old index is as stale as the + * old texture. + */ + private fun applyAtlasBinding() { + val bindingSourceById = currentModel.drawables.associateBy({ it.id }, { it.textureSourceId ?: it.id }) + for ((drawableId, gpuDrawable) in gpuById) { + // The atlas mapping is keyed by the SOURCE format's drawable ids, exactly as at upload: a + // session-created copy resolves its page through the drawable it was duplicated from. + val bindingKey = (bindingSourceById[drawableId] ?: drawableId).raw + gpuDrawable.atlasTexture = textures.atlasIndexByDrawableId[bindingKey]?.let { atlasHandles.getOrNull(it) } + } + } + + /** + * Frees one resident drawable's device objects: its mesh and delta / control-point textures. The atlas + * and any source-artwork texture are shared across drawables and stay. Must run with the device's + * context current. + * + * @param GpuDrawable gpuDrawable The resident drawable to free. + */ + private fun deleteDrawable(gpuDrawable: GpuDrawable) { + device.destroyMesh(gpuDrawable.mesh) + device.destroyTexture(gpuDrawable.deltaTexture) + gpuDrawable.cpTexture?.let { device.destroyTexture(it) } + } + + /** + * Frees every device object this renderer owns. Must run with the context current, and nothing may + * render afterwards. + * + * The artwork and underlay caches are created and destroyed across the renderer's life rather than + * uploaded once, so letting them die with the context is no longer enough: an engine that outlives + * one renderer would leak everything the previous one had admitted. The pipelines and the shared + * position store are not freed here because the device seam exposes no way to - they remain + * context-lifetime objects. + */ + fun disposeGl() { + for (gpuDrawable in gpuById.values) { + deleteDrawable(gpuDrawable) + } + gpuById = emptyMap() + glueDeformList = emptyList() + renderableById = emptyMap() + editMeshFrozenIds = emptySet() + for (texture in layerTextures.values) { + device.destroyTexture(texture) + } + layerTextures.clear() + for (texture in underlayTextures.values) { + device.destroyTexture(texture) + } + underlayTextures.clear() + for (texture in atlasHandles) { + device.destroyTexture(texture) + } + atlasHandles = emptyList() + } + + /** + * Freezes the textured GPU mesh for [ids] as the Edit-mode guide image (Cubism Mesh Edit): later + * [updateModel] calls keep those residents' geometry while the live model may lose triangles. Ids + * leaving the set are force-reuploaded from [currentModel] so leaving Edit shows the authored mesh. + * Newly frozen ids assume the GPU already matches the live mesh (true at Edit enter). + * + * Render thread only. + * + * @param Set ids The Edit-session drawable ids to freeze, or empty to thaw all. + */ + fun setEditMeshFrozen(ids: Set) { + if (ids == editMeshFrozenIds) { + return + } + val thawed = editMeshFrozenIds - ids + editMeshFrozenIds = ids + if (thawed.isNotEmpty()) { + forceReupload(thawed) + } + } + + /** + * Re-uploads [ids] from [currentModel], replacing any resident (used when thawing Edit-mode freeze). + * + * @param Set ids The drawable ids to rebuild on the GPU. + */ + private fun forceReupload(ids: Set) { + val warpDeformerIds = currentModel.deformers.filterIsInstance().map { it.id }.toSet() + val next = LinkedHashMap(gpuById) + for (drawableId in ids) { + val drawable = currentModel.drawables.firstOrNull { candidate -> candidate.id == drawableId } ?: continue + next[drawableId]?.let { resident -> deleteDrawable(resident) } + val uploaded = + uploadDrawable(drawable, glueAttributes = null, glueBaseOffset = 0, warpDeformerIds = warpDeformerIds) + if (uploaded != null) { + next[drawableId] = uploaded + } else { + next.remove(drawableId) + } + } + gpuById = next + glueDeformList = next.values.filter { resident -> resident.isGlueMesh } + renderableById = next.mapValues { (_, resident) -> resident.indexCount > 0 } + applySourceLayerDisplay() + bboxReady = false + } + + /** + * Copies blend / mask / culling flags from [drawable] onto a frozen or kept resident so composite + * edits still land while geometry stays put. + * + * @param GpuDrawable resident The GPU resident to stamp. + * @param Drawable drawable The model drawable supplying the flags. + */ + private fun stampCompositeFlags(resident: GpuDrawable, drawable: Drawable) { + resident.blendMode = drawable.blendMode + resident.alphaBlendMode = drawable.alphaBlendMode + resident.culling = drawable.culling + resident.maskIds = drawable.maskedBy + resident.invertMask = drawable.invertMask + } + + fun setPose(parameters: Map, channelOverrides: Map = emptyMap()) { + // currentModel (not the construction-time model) so a deformer reparent / reorder re-evaluates here. + val inputs = preparePose(currentModel, parameters, channelOverrides) + lastPoseInputs = inputs // publish for on-demand picking (CPU deform re-run at click time) + glueBufferDirty = true // the pose moved: pass 1 must re-deform the shared store next render + // Resolve first, in backend-neutral terms; then apply onto the resident drawables and upload. + val resolved = + resolvePose( + inputs = inputs, + renderableById = renderableById, + shownIds = shownDrawableIds, + baseOrder = baseOrder, + renderRoot = currentRenderRoot, + glueIntensities = glueIntensities, + ) + for (gpuDrawable in gpuById.values) { + gpuDrawable.visible = false + } + for (posedDrawable in resolved.posed.values) { + val gpuDrawable = gpuById[posedDrawable.drawableId] ?: continue + gpuDrawable.corners = posedDrawable.corners + val parentWorld = posedDrawable.parentWorld + gpuDrawable.parentWorld = parentWorld + // Warp control points are pose-dependent but frame-INVARIANT: upload them here, once per pose + // change, NOT every frame in the draw loop. Re-specifying this texture 60×/sec would churn the + // d3d12/Mesa driver and progressively corrupt the sampled control points, causing visible + // warp flicker over time - worst on masked warp meshes, which draw twice per frame. + if (parentWorld is WarpWorld && gpuDrawable.cpTexture != null) { + device.updateFloatTexture(gpuDrawable.cpTexture, parentWorld.cols + 1, parentWorld.rows + 1, parentWorld.cp) + } + gpuDrawable.opacity = posedDrawable.opacity + gpuDrawable.multiplyColor = posedDrawable.multiplyColor + gpuDrawable.screenColor = posedDrawable.screenColor + gpuDrawable.blend = posedDrawable.blend + gpuDrawable.visible = true + } + // resolvePose filled glueIntensities (this renderer's own array) in place - no copy needed. + currentPlan = resolved.renderPlan + currentCompositeStates = inputs.partCompositeStates + prepareCompositeAuxState() + lastDrawnOrder = resolved.drawOrder // publish the resolved back-to-front order for picking + } + + /** + * Derives the per-pose composite acceleration state from the freshly resolved plan: which + * isolated parts flatten into their parent pass this pose (identity Normal/Over composite over + * an all-Normal/Over subtree - premultiplied Over is associative, so inlining is pixel-exact), + * and the conservative world bounds of each isolated subtree and extended-blend drawable, which + * render() turns into layer scissors. A subtree containing a drawable whose bounds cannot be + * computed publishes NO bounds, so render() falls back to the full-viewport path - conservatism + * is the contract, an undersized bound would clip pixels. + */ + private fun prepareCompositeAuxState() { + if (!compositeFlattenEnabled && !compositeBoundsScissorEnabled) { + flattenableComposites = emptySet() + compositeWorldBounds = emptyMap() + extendedDrawableWorldBounds = emptyMap() + return + } + val flattenable = HashSet() + val compositeBounds = HashMap() + val extendedBounds = HashMap() + // Memoized per-drawable UNWELDED world bounds; a glue mesh's welded bounds union its posed + // partners' in (welds move each side within the hull of both unwelded shapes). + val ownBoundsById = HashMap() + + fun ownWorldBounds(id: DrawableId): PosedAabb? { + if (id in ownBoundsById) { + return ownBoundsById[id] + } + val gpuDrawable = gpuById[id] + val corners = gpuDrawable?.corners + // visible == posed this frame, so corners are fresh (they stay stale-but-non-null on a + // drawable that dropped out of the pose); an unposed one has nothing to bound. + val bounds = + if (gpuDrawable == null || corners == null || !gpuDrawable.visible) { + null + } else { + deformedWorldBounds(gpuDrawable.boundsBase, gpuDrawable.boundsCells, corners, gpuDrawable.parentWorld, gpuDrawable.blend) + } + ownBoundsById[id] = bounds + return bounds + } + + fun weldedWorldBounds(id: DrawableId): PosedAabb? { + var bounds = ownWorldBounds(id) ?: return null + for (partnerId in gluePartnersById[id].orEmpty()) { + if (gpuById[partnerId]?.visible != true) { + continue // an unposed partner welds at zero intensity and moves nothing + } + val partnerBounds = ownWorldBounds(partnerId) ?: return null + bounds = unionBounds(bounds, partnerBounds) + } + return bounds + } + + // Walks one composite subtree, returning its bounds (null = at least one drawn child had no + // computable bounds) and whether its CONTENT is flatten-transparent: every drawn drawable + // plain Normal/Over, and every nested composite itself blending Normal/Over (its internals + // only shape its own layer; Over's associativity makes its placement dest-agnostic). + fun walkComposite(node: RenderPlanComposite): Pair { + var bounds: PosedAabb? = null + var boundsComplete = true + var contentFlattenable = true + for (child in node.children) { + when (child) { + is RenderPlanDrawable -> { + val gpuDrawable = gpuById[child.id] ?: continue + val extended = gpuDrawable.isExtendedBlend + if (gpuDrawable.blendMode != BlendMode.Normal || gpuDrawable.alphaBlendMode != AlphaBlendMode.Over) { + contentFlattenable = false + } + val childBounds = weldedWorldBounds(child.id) + if (childBounds == null) { + boundsComplete = false + } else { + if (extended) { + extendedBounds[child.id] = childBounds + } + bounds = bounds?.let { unionBounds(it, childBounds) } ?: childBounds + } + } + + is RenderPlanComposite -> { + val (childBounds, childContent) = walkComposite(child) + if (child.composite.blendMode != BlendMode.Normal || child.composite.alphaBlendMode != AlphaBlendMode.Over) { + contentFlattenable = false + } + if (childBounds == null) { + boundsComplete = false + } else { + bounds = bounds?.let { unionBounds(it, childBounds) } ?: childBounds + } + } + } + } + val subtreeBounds = if (boundsComplete) bounds else null + subtreeBounds?.let { compositeBounds[node.partId] = it } + if (compositeFlattenEnabled && contentFlattenable && compositeStateIsIdentity(node)) { + flattenable.add(node.partId) + } + return subtreeBounds to contentFlattenable + } + + for (node in currentPlan) { + when (node) { + is RenderPlanDrawable -> { + val gpuDrawable = gpuById[node.id] ?: continue + if (gpuDrawable.isExtendedBlend) { + weldedWorldBounds(node.id)?.let { extendedBounds[node.id] = it } + } + } + + is RenderPlanComposite -> walkComposite(node) + } + } + flattenableComposites = flattenable + compositeWorldBounds = if (compositeBoundsScissorEnabled) compositeBounds else emptyMap() + extendedDrawableWorldBounds = if (compositeBoundsScissorEnabled) extendedBounds else emptyMap() + } + + /** + * Whether an isolated part's composite is a pose-identity source-over: Normal/Over, unmasked, + * and its pose-blended channels exactly at identity. Exact equality on purpose - a channel a + * hair off identity takes the real composite path rather than a visibly-approximate flatten. + */ + private fun compositeStateIsIdentity(node: RenderPlanComposite): Boolean { + val composite = node.composite + if (composite.blendMode != BlendMode.Normal || composite.alphaBlendMode != AlphaBlendMode.Over) { + return false + } + if (composite.maskedBy.isNotEmpty()) { + return false + } + val state = currentCompositeStates[node.partId] + val opacity = state?.opacity ?: composite.opacity + val multiply = state?.multiplyColor ?: composite.multiplyColor + val screen = state?.screenColor ?: composite.screenColor + return opacity == 1f && multiply == ColorRgb.MultiplyIdentity && screen == ColorRgb.ScreenIdentity + } + + fun setCamera(camera: ViewportCamera) { + currentCamera = camera + } + + /** + * Sets how many framebuffer pixels map to one on-screen pixel, so the grid line width stays a constant + * on-screen size when the offscreen service renders supersampled and downscales. 1 = native, 2 = 2×. + * + * @param Float scale Framebuffer pixels per on-screen pixel. + */ + fun setRenderScale(scale: Float) { + gridPixelScale = scale + } + + /** + * Sets the grid backdrop's colors and geometry, so the viewport can follow the editor theme and the + * per-document grid config. The next [render] picks them up. + * + * @param GridColors colors The background / major / minor grid colors. + * @param Float scale The major grid line spacing in world units. + * @param Int subdivisions The minor lines per major cell. + */ + fun setGrid(colors: GridColors, scale: Float, subdivisions: Int) { + gridColors = colors + gridScale = scale + gridSubdivisions = subdivisions + } + + /** + * Sets which drawables are highlighted (object-mode selection). The next [render] tints them. + * + * @param Set ids The selected drawable ids. + */ + fun setSelection(ids: Set) { + selectedIds = ids + } + + /** + * Sets which drawable is active (the last-selected object of a multi-selection), tinted toward + * [activeHighlightColor] rather than [highlightColor]. Null clears the distinction. + * + * @param DrawableId? id The active drawable id, or null when none is active. + */ + fun setActiveSelection(id: DrawableId?) { + activeId = id + } + + /** + * Updates the set of drawables actually drawn (the resolved visibility cascade), so a visibility edit + * takes effect on the next [render]. + * + * @param Set ids The drawable ids to draw. + */ + fun setShownDrawables(ids: Set) { + if (ids != shownDrawableIds) { + // The bbox skips hidden drawables, so a visibility change invalidates the cached framing. + bboxReady = false + } + shownDrawableIds = ids + } + + /** + * Shows or hides the world-origin axis lines (the red X / blue Z cross at the model's world origin). + * + * @param Boolean visible True to draw the axes each frame. + */ + fun setWorldAxesVisible(visible: Boolean) { + worldAxesVisible = visible + } + + /** + * Reconciles the renderer with the current model after an edit, via a backend-neutral [diffModel] whose + * four tiers are applied here as device calls: a reorder / reparent needs no buffer work; a base-mesh + * move re-uploads positions; a UV edit re-uploads UVs; a structural change frees and re-uploads whole. + * + * Structural limits: a session-created drawable never joins the load-time glue layout (glues reference + * source ids, so a fresh id welds nothing), and a REMESHED glue mesh degrades to an unwelded draw (its + * store region and weld attrs index the old vertex order and are not remapped here). + * + * The diff compares against [currentModel] and therefore runs BEFORE the reassignment, keeping the + * invariant "GPU buffer contents === currentModel's arrays". + * + * @param PuppetModel newModel The current model. + */ + fun updateModel(newModel: PuppetModel) { + val warpDeformerIds = newModel.deformers.filterIsInstance().map { it.id }.toSet() + val diff = diffModel(currentModel, newModel, gpuById.mapValues { (_, resident) -> resident.vertexCount }) + val reconciled = LinkedHashMap() + for (action in diff.actions) { + when (action) { + is DrawableAction.Upload -> + uploadDrawable(action.drawable, glueAttributes = null, glueBaseOffset = 0, warpDeformerIds = warpDeformerIds) + ?.let { reconciled[action.drawableId] = it } + + is DrawableAction.Reupload -> { + // Edit-mode guide: keep the frozen textured mesh when the LIVE mesh SHRINKS (deletes) + // so the image under the wireframe stays. Compare against [currentModel], not the + // frozen GPU resident — otherwise Accept after a wipe looks "smaller than freeze" + // and either keeps the stale guide forever or reuploads an empty-index mesh and the + // drawable vanishes from the GPU. + val existing = gpuById[action.drawableId] + val newMesh = action.drawable.mesh + val oldLive = currentModel.drawables.firstOrNull { candidate -> candidate.id == action.drawableId }?.mesh + val freezeKeeps = + action.drawableId in editMeshFrozenIds && + existing != null && + newMesh != null && + oldLive != null && + newMesh.indices.size <= oldLive.indices.size && + newMesh.vertexCount <= oldLive.vertexCount + if (freezeKeeps) { + reconciled[action.drawableId] = existing + stampCompositeFlags(existing, action.drawable) + } else { + val uploaded = + uploadDrawable( + action.drawable, + glueAttributes = null, + glueBaseOffset = 0, + warpDeformerIds = warpDeformerIds, + ) + if (uploaded != null) { + existing?.let { resident -> deleteDrawable(resident) } + reconciled[action.drawableId] = uploaded + } else if (existing != null) { + // Live mesh draws nothing (e.g. verts but no triangles) — keep the prior + // resident instead of blanking the drawable out of the GPU. + reconciled[action.drawableId] = existing + stampCompositeFlags(existing, action.drawable) + } + } + } + + is DrawableAction.Keep -> { + val existing = gpuById[action.drawableId] ?: continue + reconciled[action.drawableId] = existing + // Re-stamp the static composite state from the edited drawable: a blend/alpha/culling/ + // mask/invert edit does no buffer work, so it lands here, and these were otherwise + // frozen at upload (isExtendedBlend is a getter, so draw routing updates for free). + stampCompositeFlags(existing, action.drawable) + // Frozen guides also ignore position / UV patch-ups (Cubism: moving verts does not + // move the model-guide image; the wireframe overlay reads the live model instead). + if (action.drawableId !in editMeshFrozenIds) { + action.positions?.let { + device.updateMeshPositions(existing.mesh, it) + // Re-point the bounds walk at the new rest positions too, or the composite scissor + // would keep sizing to the pre-edit geometry and clip the moved vertices. + existing.boundsBase = it + } + action.uvs?.let { device.updateMeshUvs(existing.mesh, it) } + } + } + } + } + // Free residents the edit dropped. A Reupload already freed its own and is never in `removed`, so + // nothing is freed twice. + for (drawableId in diff.removed) { + gpuById[drawableId]?.let { deleteDrawable(it) } + } + gpuById = reconciled + glueDeformList = reconciled.values.filter { it.isGlueMesh } + renderableById = reconciled.mapValues { (_, resident) -> resident.indexCount > 0 } + currentModel = newModel + currentRenderRoot = newModel.renderRoot + baseOrder = newModel.drawables.map { it.id } + rebuildGluePartners(newModel) + // A rebuilt resident comes back on its atlas page, so re-point the whole set at the artwork the + // document displays from - otherwise an edit silently drops that drawable back to the atlas. + applySourceLayerDisplay() + bboxReady = false + } + + /** Rebuilds the two-way glue partner map the composite bounds walk unions across. */ + private fun rebuildGluePartners(fromModel: PuppetModel) { + if (fromModel.glues.isEmpty()) { + gluePartnersById = emptyMap() + return + } + val partners = HashMap>() + for ((glueIndex, glue) in fromModel.glues.withIndex()) { + // Glues past MAX_GLUES render unwelded (resolvePose / planGlueLayout skip them by the same + // index), so their partners move nothing - don't union those extents into the bounds. + if (glueIndex >= MAX_GLUES) { + break + } + partners.getOrPut(glue.meshA) { ArrayList() }.add(glue.meshB) + partners.getOrPut(glue.meshB) { ArrayList() }.add(glue.meshA) + } + gluePartnersById = partners + } + + /** + * Sets the color selected drawables are tinted toward (the selection highlight). + * + * @param Float red The tint red, 0..1. + * @param Float green The tint green, 0..1. + * @param Float blue The tint blue, 0..1. + */ + fun setSelectionHighlightColor(red: Float, green: Float, blue: Float) { + highlightColor = floatArrayOf(red, green, blue) + } + + /** + * Sets the color the active drawable is tinted toward (the active-selection highlight). + * + * @param Float red The tint red, 0..1. + * @param Float green The tint green, 0..1. + * @param Float blue The tint blue, 0..1. + */ + fun setActiveSelectionHighlightColor(red: Float, green: Float, blue: Float) { + activeHighlightColor = floatArrayOf(red, green, blue) + } + + /** + * Evaluates the current pose's deformed world geometry on the CPU for hit-testing, or null before the + * first pose. Pure CPU with no device calls, so it is safe from the UI thread; it reuses the immutable + * per-pose inputs cached by the last [setPose]. + * + * @return DeformedGeometry The current deformed geometry, or null before the first pose. + */ + fun pickGeometry(): DeformedGeometry? { + val inputs = lastPoseInputs ?: return null + return applyCpuDeform(currentModel, inputs) + } + + /** + * The world-space extent of what the current pose actually draws, from the same CPU deform as + * [pickGeometry] - so, like it, safe from the UI thread. Where [contentBounds] measures the rest pose + * a view fits to, this measures the pose on screen, which is what a capture of it frames. + * + * A shown drawable whose posed opacity leaves no coverage in an 8-bit image is not measured: a guide or + * effect keyed to zero opacity draws nothing, and framing it would pad the capture with empty pixels. + * The view fit keeps measuring it, since a rigger fitting the view wants every drawable the rig can show. + * + * @param Set shownIds The drawables actually drawn (the resolved visibility cascade). + * @return ContentBounds? The extent, or null before the first pose or when nothing drawn has a vertex. + */ + fun posedContentBounds(shownIds: Set): ContentBounds? { + val geometry = pickGeometry() ?: return null + val drawnIds = shownIds.filterTo(HashSet()) { drawableId -> (geometry.opacity[drawableId] ?: 0f) >= MINIMUM_DRAWN_OPACITY } + return contentBoundsOf(geometry, drawnIds) + } + + /** + * The last frame's resolved draw order (back-to-front; last = front), or empty before the first pose - + * the hierarchy-correct front/back ranking picking uses to choose among overlapping meshes. + * + * @return List The drawn drawables, back-to-front. + */ + fun drawnOrder(): List = lastDrawnOrder + + fun contentBounds(): ContentBounds { + ensureContentBounds() + return ContentBounds(minX, minY, spanX, spanY) + } + + /** + * Draws the current pose into [target]. + * + * The target is explicit rather than the bound framebuffer: a pass that discovered its own target could + * not exist on a backend with no bound-framebuffer concept, and even on GL, discovering it hid a real + * coupling with whoever bound it first. + * + * @param RenderTarget target The surface to draw into. + * @param Int viewportWidth The target width in pixels. + * @param Int viewportHeight The target height in pixels. + * @param FrameBackdrop backdrop What the puppet is drawn over: the grid (the viewport), or a flat + * fill (an image capture). + */ + fun render(target: RenderTarget, viewportWidth: Int, viewportHeight: Int, backdrop: FrameBackdrop = FrameBackdrop.Grid) { + ensureSideTargets(viewportWidth, viewportHeight) + val frame = device.beginFrame() + + // Pass 1: capture every glue mesh's deformed positions into the shared store. Only when the pose + // changed - a static pose leaves the store (and pass 2's reads of it) unchanged. + val activeStore = store + if (activeStore != null && glueBufferDirty) { + val capture = frame.beginDeformCapturePass(capturePipeline!!, activeStore) + for (gpuDrawable in glueDeformList) { + if (gpuDrawable.corners == null) { + continue + } + fillDeform(deformScratch, gpuDrawable) + texturesScratch.atlas = null + texturesScratch.maskCoverage = null + texturesScratch.deltaTexture = gpuDrawable.deltaTexture + texturesScratch.warpControlPoints = gpuDrawable.cpTexture + capture.captureDeformedPositions( + gpuDrawable.mesh, + deformScratch, + texturesScratch, + gpuDrawable.glueBaseOffset, + gpuDrawable.vertexCount, + ) + } + capture.end() + frame.barrier(activeStore) + glueBufferDirty = false + } + + val camera = effectiveCamera(viewportWidth, viewportHeight) + val transform = camera.worldToNdc(viewportWidth, viewportHeight) + val affine = WorldToNdc(transform[0], transform[1], transform[2], transform[3]) + + // Main pass. The grid is an opaque full-screen fill, so it both clears and paints - DontCare load. + // A flat backdrop is the pass's own clear, and the puppet blends over it exactly as over the grid. + var pass = + when (backdrop) { + FrameBackdrop.Grid -> { + val gridPass = frame.beginRenderPass(passSpec(target, LoadAction.DontCare, viewportWidth, viewportHeight)) + drawBackdrop(gridPass, affine, viewportWidth, viewportHeight) + gridPass + } + + is FrameBackdrop.Clear -> + frame.beginRenderPass( + passSpec( + target, + LoadAction.Clear, + viewportWidth, + viewportHeight, + clearRed = backdrop.red, + clearGreen = backdrop.green, + clearBlue = backdrop.blue, + clearAlpha = backdrop.alpha, + ), + ) + } + pass = renderPlanNodes(frame, currentPlan, target, 0, affine, viewportWidth, viewportHeight, pass, scissor = null) + pass.end() + frame.endFrame() + } + + /** + * Renders the current pose into a CPU image: the puppet as the viewport draws it, over [backdrop], with + * no selection tint and no editor chrome. + * + * The image renders at [SNAPSHOT_SUPERSAMPLE] into a surface of its own and is resolved and read back + * synchronously, in tiles of at most [tileEdge] output pixels (and never past what the device can + * allocate), stitched into one image. A tile is the same camera re-centered on its own rectangle, so + * the pieces meet exactly: tile edges fall on whole output pixels, and the resolve never averages + * across one. + * + * Nothing the host set is disturbed: the camera, render scale, and selection are restored afterwards, + * and the side targets are released again when the capture grew them, so a large capture does not + * leave its high-water allocation behind for the viewport to carry. + * + * Over a transparent backdrop, a fixed-function Additive drawable adds color but no alpha, and Multiply + * scales what is beneath it. Where nothing lies beneath them they leave no coverage, so they drop out + * of the image, as they do wherever the puppet is composited over transparency. + * + * Must run on the render thread with the device's context current, between frames. A large capture is + * many tiles, so [shouldContinue] is asked before each one: a host shutting down stops the capture at + * the next tile rather than waiting for the whole image. + * + * @param ViewportCamera camera The view: the world point at the image's center and the output + * pixels per world unit. + * @param Int width The image width in pixels. + * @param Int height The image height in pixels. + * @param FrameBackdrop backdrop What the puppet is drawn over. + * @param Int tileEdge The largest tile edge in output pixels (tests shrink it to force + * tiling). + * @param Function shouldContinue Asked before each tile; false abandons the capture. + * @return RasterImage? The pixels, PREMULTIPLIED, top row first, or null when the capture was abandoned. + */ + fun renderSnapshot( + camera: ViewportCamera, + width: Int, + height: Int, + backdrop: FrameBackdrop, + tileEdge: Int = SNAPSHOT_TILE_EDGE, + shouldContinue: () -> Boolean = { true }, + ): RasterImage? { + require(width > 0 && height > 0) { "a snapshot needs a positive size, got ${width}x$height" } + val maximumTile = minOf(tileEdge, device.maxRenderTargetSize() / SNAPSHOT_SUPERSAMPLE).coerceAtLeast(1) + val previousCamera = currentCamera + val previousPixelScale = gridPixelScale + val previousSelection = selectedIds + val previousActive = activeId + val previousCapacityWidth = sideTargetCapacityWidth + val previousCapacityHeight = sideTargetCapacityHeight + val surface = SupersampledSurface(device, SNAPSHOT_SUPERSAMPLE) + val stitched = ByteArray(width * height * 4) + try { + selectedIds = emptySet() + activeId = null + gridPixelScale = SNAPSHOT_SUPERSAMPLE.toFloat() + for (tileTop in 0 until height step maximumTile) { + val tileHeight = minOf(maximumTile, height - tileTop) + for (tileLeft in 0 until width step maximumTile) { + if (!shouldContinue()) { + return null + } + val tileWidth = minOf(maximumTile, width - tileLeft) + // The tile's center in whole-image pixels, carried back into world units: x runs right + // in both, while image rows run down and world z runs up. + val tileCenterX = camera.centerX + (tileLeft + tileWidth / 2f - width / 2f) / camera.zoom + val tileCenterY = camera.centerY - (tileTop + tileHeight / 2f - height / 2f) / camera.zoom + currentCamera = ViewportCamera(tileCenterX, tileCenterY, camera.zoom * SNAPSHOT_SUPERSAMPLE) + val drawTarget = surface.ensure(tileWidth, tileHeight) + render(drawTarget, tileWidth * SNAPSHOT_SUPERSAMPLE, tileHeight * SNAPSHOT_SUPERSAMPLE, backdrop) + surface.resolve() + val tile = device.readPixels(surface.resolveTarget, tileWidth, tileHeight) + for (tileRow in 0 until tileHeight) { + tile.rgba.copyInto( + stitched, + ((tileTop + tileRow) * width + tileLeft) * 4, + tileRow * tileWidth * 4, + (tileRow + 1) * tileWidth * 4, + ) + } + } + } + } finally { + currentCamera = previousCamera + gridPixelScale = previousPixelScale + selectedIds = previousSelection + activeId = previousActive + surface.dispose() + if (sideTargetCapacityWidth > previousCapacityWidth || sideTargetCapacityHeight > previousCapacityHeight) { + releaseSideTargets() + } + } + return RasterImage(width, height, stitched) + } + + /** + * Frees the mask, destination-snapshot, and composite-layer targets and resets their shared capacity, + * so the next [render] allocates them afresh at its own size. The capacity is otherwise grow-only; + * this is how a one-off large render gives the memory back. + */ + fun releaseSideTargets() { + maskTarget?.let { target -> device.destroyRenderTarget(target) } + maskTarget = null + for (target in compositeTargets) { + device.destroyRenderTarget(target) + } + compositeTargets.clear() + snapshotTarget?.let { target -> device.destroyRenderTarget(target) } + snapshotTarget = null + sideTargetCapacityWidth = 0 + sideTargetCapacityHeight = 0 + } + + /** + * The shared side-target capacity (mask, destination snapshot, composite pool) as (width, height), for + * tests that pin a capture's release of it. + * + * @return Pair The capacity in pixels. + */ + internal fun sideTargetCapacity(): Pair = sideTargetCapacityWidth to sideTargetCapacityHeight + + /** + * Walks a render-plan span into [target]: plain drawables draw directly (with the mask-coverage + * pass fragmentation), a drawable whose blend is not fixed-function-expressible composites as an + * implicit singleton composite, and a [RenderPlanComposite] node renders its subtree into a + * pooled layer target and composites it back as one layer. Passes never nest - the frame stays + * a flat pass sequence, and the CURRENT pass travels through as the return value. + * + * Two per-pose accelerations short-circuit the composite machinery (both pixel-preserving; see + * [prepareCompositeAuxState]): a pose-identity Normal/Over composite over an all-Normal/Over + * subtree draws inline into the current pass, and a non-Out composite whose layer would land + * empty on screen (bounds off-viewport, or pose-blended opacity 0) is skipped outright. The + * remaining composites confine their layer work to the subtree's bounds via [scissor] rects. + * + * A plan with no composite nodes and no extended-blend drawables takes exactly the old flat + * path: zero extra passes, zero resolves - the regression guard. + * + * @param FrameEncoder frame The frame being recorded. + * @param List nodes The span to draw, back-to-front. + * @param RenderTarget target The surface this span draws into. + * @param Int depth The composite nesting depth (0 = the real target). + * @param WorldToNdc affine The camera affine. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @param RenderPassEncoder startPass The open pass on [target]. + * @param ScissorRect? scissor [target]'s own pass scissor (a composite layer's + * bounds rect when this span IS an isolated subtree), re-applied whenever the span resumes a + * pass on [target]; null at the top level. + * @return RenderPassEncoder The open pass on [target] after the span (may differ from [startPass]). + */ + private fun renderPlanNodes( + frame: FrameEncoder, + nodes: List, + target: RenderTarget, + depth: Int, + affine: WorldToNdc, + viewportWidth: Int, + viewportHeight: Int, + startPass: RenderPassEncoder, + scissor: ScissorRect?, + ): RenderPassEncoder { + var pass = startPass + for (node in nodes) { + when (node) { + is RenderPlanDrawable -> { + val gpuDrawable = gpuById[node.id] ?: continue + if (gpuDrawable.isExtendedBlend) { + // A 5.3 extended blend: not fixed-function-expressible, so draw the drawable + // alone into a layer target and composite it in-shader. + // An empty (fully faded) non-Out layer composites to the unchanged destination, so + // skip it outright - independent of the bounds-scissor toggle (Out erases the + // destination where the layer is empty, so it must keep the real composite path). + if (gpuDrawable.alphaBlendMode != AlphaBlendMode.Out && gpuDrawable.opacity == 0f) { + continue + } + var layerRect: ScissorRect? = null + if (compositeBoundsScissorEnabled && gpuDrawable.alphaBlendMode != AlphaBlendMode.Out) { + val bounds = extendedDrawableWorldBounds[gpuDrawable.id] + if (bounds != null) { + layerRect = scissorRectOf(bounds, affine, viewportWidth, viewportHeight) ?: continue + } + } + pass.end() + pass = compositeDrawable(frame, gpuDrawable, target, depth, affine, viewportWidth, viewportHeight, layerRect, scissor) + continue + } + var maskCoverage: GpuTexture? = null + if (gpuDrawable.maskIds.isNotEmpty()) { + // Mask by pass fragmentation: end the pass, render coverage into the mask target, + // resume preserving what is drawn so far. Correct on every backend and non-nesting. + pass.end() + renderMaskCoverage(frame, gpuDrawable.maskIds, affine, viewportWidth, viewportHeight) + pass = frame.beginRenderPass(passSpec(target, LoadAction.Load, viewportWidth, viewportHeight, scissor = scissor)) + maskCoverage = maskTarget?.sampledTexture + } + val isActive = activeId != null && gpuDrawable.id == activeId + val highlight = if (isActive || gpuDrawable.id in selectedIds) SELECTION_TINT_STRENGTH else 0f + drawDrawable( + pass, + gpuDrawable, + affine, + gpuDrawable.blendMode, + gpuDrawable.opacity, + highlight, + isActive, + maskCoverage != null, + maskCoverage, + ) + } + + is RenderPlanComposite -> { + if (node.partId in flattenableComposites) { + // Identity source-over of an all-Normal/Over subtree: Over is associative, + // so the subtree draws inline - no layer, no snapshot, no composite draw. + pass = renderPlanNodes(frame, node.children, target, depth, affine, viewportWidth, viewportHeight, pass, scissor) + continue + } + // A fully faded non-Out layer composites to the unchanged destination, so skip it + // outright - independent of the bounds-scissor toggle (see the extended-blend branch). + val poseOpacity = currentCompositeStates[node.partId]?.opacity ?: node.composite.opacity + if (node.composite.alphaBlendMode != AlphaBlendMode.Out && poseOpacity == 0f) { + continue + } + var layerRect: ScissorRect? = null + if (compositeBoundsScissorEnabled && node.composite.alphaBlendMode != AlphaBlendMode.Out) { + val bounds = compositeWorldBounds[node.partId] + if (bounds != null) { + layerRect = scissorRectOf(bounds, affine, viewportWidth, viewportHeight) ?: continue + } + } + pass.end() + pass = compositeGroup(frame, node, target, depth, affine, viewportWidth, viewportHeight, layerRect, scissor) + } + } + } + return pass + } + + /** + * Maps world bounds to a padded, viewport-clamped scissor rectangle (top-left-origin pixels), + * or null when the bounds land entirely off the viewport. + * + * @param PosedAabb bounds The world-space bounds. + * @param WorldToNdc affine The camera affine. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @return ScissorRect? The scissor rect, or null when empty. + */ + private fun scissorRectOf(bounds: PosedAabb, affine: WorldToNdc, viewportWidth: Int, viewportHeight: Int): ScissorRect? { + val ndcXa = affine.scaleX * bounds.minX + affine.offsetX + val ndcXb = affine.scaleX * bounds.maxX + affine.offsetX + val ndcYa = affine.scaleY * bounds.minY + affine.offsetY + val ndcYb = affine.scaleY * bounds.maxY + affine.offsetY + val pixelLeft = (minOf(ndcXa, ndcXb) * 0.5f + 0.5f) * viewportWidth + val pixelRight = (maxOf(ndcXa, ndcXb) * 0.5f + 0.5f) * viewportWidth + // NDC +Y is up; top-left-origin rows count down from the top. + val pixelTop = (0.5f - maxOf(ndcYa, ndcYb) * 0.5f) * viewportHeight + val pixelBottom = (0.5f - minOf(ndcYa, ndcYb) * 0.5f) * viewportHeight + // The fringe guard is a constant ON-SCREEN size, so it scales with the supersample factor + // (gridPixelScale = framebuffer pixels per on-screen pixel), or a 1x-sufficient pad under-covers + // the fringe at 2x+ and clips an edge texel. + val pad = SCISSOR_PAD_PX * gridPixelScale + val viewportWidthF = viewportWidth.toFloat() + val viewportHeightF = viewportHeight.toFloat() + // Pad and clamp in FLOAT space before the Int conversion. A warp-extrapolated vertex can push a + // pixel edge far past Int range; Float.toInt() would then saturate and the -/+ pad would wrap via + // unchecked Int overflow to the WRONG end of the clamp, vanishing the layer instead of covering + // the viewport. Float coerceIn clamps ±Infinity correctly; a NaN edge never reaches here + // (deformedWorldBounds publishes no bound for a non-finite vertex, so render() keeps the full + // viewport path). + val left = (floor(pixelLeft) - pad).coerceIn(0f, viewportWidthF).toInt() + val right = (ceil(pixelRight) + pad).coerceIn(0f, viewportWidthF).toInt() + val top = (floor(pixelTop) - pad).coerceIn(0f, viewportHeightF).toInt() + val bottom = (ceil(pixelBottom) + pad).coerceIn(0f, viewportHeightF).toInt() + if (right <= left || bottom <= top) { + return null + } + return ScissorRect(left, top, right - left, bottom - top) + } + + /** + * Renders an isolated part's subtree into the depth's pooled layer target, then composites it + * back into [target] as one layer with the part's blend modes, pose-blended channels, and + * optional clip mask. Returns the fresh open pass on [target]. + * + * @param FrameEncoder frame The frame being recorded. + * @param RenderPlanComposite node The isolated part's plan node (subtree + composite settings). + * @param RenderTarget target The surface the layer composites back into. + * @param Int depth The composite nesting depth (its layer target's pool slot). + * @param WorldToNdc affine The camera affine. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @param ScissorRect? layerRect The subtree's bounds - confines the layer clear + subtree + * draw, null for a full-viewport layer (Out alpha or uncomputable bounds). + * @param ScissorRect? parentScissor [target]'s own scissor (the enclosing layer's rect), null at + * the top level; the composite-back is confined to it intersected with [layerRect]. + * @return RenderPassEncoder The fresh open pass on [target] after the composite. + */ + private fun compositeGroup( + frame: FrameEncoder, + node: RenderPlanComposite, + target: RenderTarget, + depth: Int, + affine: WorldToNdc, + viewportWidth: Int, + viewportHeight: Int, + layerRect: ScissorRect?, + parentScissor: ScissorRect?, + ): RenderPassEncoder { + val layerTarget = acquireCompositeTarget(depth) + var subtreePass = + frame.beginRenderPass(passSpec(layerTarget, LoadAction.Clear, viewportWidth, viewportHeight, clearAlpha = 0f, scissor = layerRect)) + subtreePass = renderPlanNodes(frame, node.children, layerTarget, depth + 1, affine, viewportWidth, viewportHeight, subtreePass, layerRect) + subtreePass.end() + val masked = node.composite.maskedBy.isNotEmpty() + if (masked) { + renderMaskCoverage(frame, node.composite.maskedBy, affine, viewportWidth, viewportHeight) + } + // The pose-blended channels; a part missing from the map (never the case for an isolated + // group, but harmless) falls back to its static channels. + val state = currentCompositeStates[node.partId] + compositeScratch.colorMode = packedColorModeOf(node.composite.blendMode) + compositeScratch.alphaMode = packedAlphaModeOf(node.composite.alphaBlendMode) + compositeScratch.opacity = state?.opacity ?: node.composite.opacity + val multiply = state?.multiplyColor ?: node.composite.multiplyColor + val screen = state?.screenColor ?: node.composite.screenColor + compositeScratch.multiplyRed = multiply.red + compositeScratch.multiplyGreen = multiply.green + compositeScratch.multiplyBlue = multiply.blue + compositeScratch.screenRed = screen.red + compositeScratch.screenGreen = screen.green + compositeScratch.screenBlue = screen.blue + compositeScratch.useMask = masked + compositeScratch.invertMask = masked && node.composite.invertMask + return encodeComposite(frame, layerTarget, target, affine, viewportWidth, viewportHeight, intersectScissor(layerRect, parentScissor), parentScissor) + } + + /** + * Draws one extended-blend drawable as an implicit singleton composite: the drawable alone (with + * its own opacity and clip mask) into the depth's layer target, composited back with its color + * and alpha modes at identity channels. Returns the fresh open pass on [target]. + * + * @param FrameEncoder frame The frame being recorded. + * @param GpuDrawable gpuDrawable The extended-blend drawable to composite. + * @param RenderTarget target The surface the layer composites back into. + * @param Int depth The composite nesting depth (its layer target's pool slot). + * @param WorldToNdc affine The camera affine. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @param ScissorRect? layerRect The drawable's bounds - confines the layer clear + draw, null + * for a full-viewport layer (Out alpha or uncomputable bounds). + * @param ScissorRect? parentScissor [target]'s own scissor, null at the top level. + * @return RenderPassEncoder The fresh open pass on [target] after the composite. + */ + private fun compositeDrawable( + frame: FrameEncoder, + gpuDrawable: GpuDrawable, + target: RenderTarget, + depth: Int, + affine: WorldToNdc, + viewportWidth: Int, + viewportHeight: Int, + layerRect: ScissorRect?, + parentScissor: ScissorRect?, + ): RenderPassEncoder { + var maskCoverage: GpuTexture? = null + if (gpuDrawable.maskIds.isNotEmpty()) { + renderMaskCoverage(frame, gpuDrawable.maskIds, affine, viewportWidth, viewportHeight) + maskCoverage = maskTarget?.sampledTexture + } + val layerTarget = acquireCompositeTarget(depth) + val layerPass = + frame.beginRenderPass(passSpec(layerTarget, LoadAction.Clear, viewportWidth, viewportHeight, clearAlpha = 0f, scissor = layerRect)) + val isActive = activeId != null && gpuDrawable.id == activeId + val highlight = if (isActive || gpuDrawable.id in selectedIds) SELECTION_TINT_STRENGTH else 0f + // Normal blend onto the cleared transparent layer just writes the premultiplied pixels; the + // drawable's real blend happens in the composite below. + drawDrawable( + layerPass, + gpuDrawable, + affine, + BlendMode.Normal, + gpuDrawable.opacity, + highlight, + isActive, + maskCoverage != null, + maskCoverage, + ) + layerPass.end() + compositeScratch.colorMode = packedColorModeOf(gpuDrawable.blendMode) + compositeScratch.alphaMode = packedAlphaModeOf(gpuDrawable.alphaBlendMode) + compositeScratch.opacity = 1f + compositeScratch.multiplyRed = 1f + compositeScratch.multiplyGreen = 1f + compositeScratch.multiplyBlue = 1f + compositeScratch.screenRed = 0f + compositeScratch.screenGreen = 0f + compositeScratch.screenBlue = 0f + compositeScratch.useMask = false + compositeScratch.invertMask = false + return encodeComposite(frame, layerTarget, target, affine, viewportWidth, viewportHeight, intersectScissor(layerRect, parentScissor), parentScissor) + } + + /** + * Snapshots [target], begins a fresh Load pass on it, and issues the composite draw from + * [layerTarget] against the snapshot using the already-filled [compositeScratch]. + * + * The composite reads and writes the same fragments, so [compositeScissor] bounds BOTH the + * destination snapshot copy and the composite draw - the whole target when null. + * + * The composite draw runs in its OWN pass under [compositeScissor], which is then ended; the + * returned continuation pass is scissored to [continuationScissor] (the enclosing span's own + * scissor, null at the top level) so the drawables the caller draws AFTER this composite are NOT + * clipped to the composite's bounds - reusing the composite's own scissor for the continuation + * pass would incorrectly shrink everything drawn behind it in the same span. + * + * @param FrameEncoder frame The frame being recorded. + * @param RenderTarget layerTarget The pooled layer holding the subtree/drawable to composite. + * @param RenderTarget target The surface the layer composites back into. + * @param WorldToNdc affine The camera affine. + * @param Int viewportWidth The viewport width in pixels. + * @param Int viewportHeight The viewport height in pixels. + * @param ScissorRect? compositeScissor The rect the snapshot + composite are confined to, or null. + * @param ScissorRect? continuationScissor The scissor the returned pass carries, or null. + * @return RenderPassEncoder A fresh open pass on [target] under [continuationScissor]. + */ + private fun encodeComposite( + frame: FrameEncoder, + layerTarget: RenderTarget, + target: RenderTarget, + affine: WorldToNdc, + viewportWidth: Int, + viewportHeight: Int, + compositeScissor: ScissorRect?, + continuationScissor: ScissorRect?, + ): RenderPassEncoder { + // Snapshot the destination so the composite shader can sample it (a pass cannot sample its + // own target); the copy is ordered between the passes around it, and confined to the same + // rect the composite draw reads and writes. Used-region resolve: [target] can be the main + // draw target (the surface's capacity) or a pooled layer (the side-target capacity), and the + // snapshot has its own capacity - equal USED extents anchored at the origin is the invariant, + // and the scissor rect flips against the used height. + val snapshot = snapshotTarget ?: error("composite targets not allocated") + device.resolveUsed(target, viewportWidth, viewportHeight, snapshot, viewportWidth, viewportHeight, compositeScissor) + val compositePass = frame.beginRenderPass(passSpec(target, LoadAction.Load, viewportWidth, viewportHeight, scissor = compositeScissor)) + compositePass.setPipeline(compositePipeline!!) + compositePass.setCamera(affine, sideTargetCapacityWidth, sideTargetCapacityHeight) + texturesScratch.atlas = null + texturesScratch.deltaTexture = null + texturesScratch.warpControlPoints = null + texturesScratch.maskCoverage = if (compositeScratch.useMask) maskTarget?.sampledTexture else null + texturesScratch.compositeLayer = layerTarget.sampledTexture + texturesScratch.destinationSnapshot = snapshot.sampledTexture + compositePass.drawComposite(compositeScratch, texturesScratch) + texturesScratch.compositeLayer = null + texturesScratch.destinationSnapshot = null + compositePass.end() + // A fresh pass under the ENCLOSING span's scissor - the composite's own scissor must not leak + // onto whatever the caller draws next into this target. + return frame.beginRenderPass(passSpec(target, LoadAction.Load, viewportWidth, viewportHeight, scissor = continuationScissor)) + } + + /** + * Renders one atlas page as a flat, upright underlay for a UV-editor area (instead of the posed + * puppet): the themed grid backdrop, then the whole page as a single textured quad. A null or + * out-of-range [pageIndex] paints the grid only. + * + * The page samples the SAME uploaded atlas texture a drawable binds while the puppet displays from the + * atlas, through the same premultiplied fragment shader, so the underlay matches the puppet's texel + * rendering exactly. + * + * @param RenderTarget target The surface to draw into. + * @param Int pageIndex The atlas page to draw, or null for none. + * @param Int viewportWidth The target width in pixels. + * @param Int viewportHeight The target height in pixels. + */ + fun renderAtlasPage(target: RenderTarget, pageIndex: Int?, viewportWidth: Int, viewportHeight: Int) { + val page = pageIndex?.let { textures.atlases.getOrNull(it) } + renderUnderlay(target, page, pageIndex?.let { atlasHandles.getOrNull(it) }, viewportWidth, viewportHeight) + } + + /** + * Draws an arbitrary image as the flat underlay - the UV editor's source-layer view, the pre-atlas + * counterpart of [renderAtlasPage]. + * + * Unlike the atlas pages, which upload as a whole set (at init, or wholesale on a [setAtlasPages] + * swap) rather than one image at a time, a layer image arrives whenever the editor is pointed at + * one, so its texture is created on first sight and cached (see [underlayTextureFor]). A null + * image paints the grid only. + * + * @param RenderTarget target The surface to draw into. + * @param DecodedImage image The image to draw, or null for none. + * @param Int viewportWidth The target width in pixels. + * @param Int viewportHeight The target height in pixels. + */ + fun renderUnderlayImage(target: RenderTarget, image: DecodedImage?, viewportWidth: Int, viewportHeight: Int) { + renderUnderlay(target, image, image?.let { underlayTextureFor(it) }, viewportWidth, viewportHeight) + } + + /** + * The flat underlay draw both UV scenes share: the themed grid backdrop, then the image as a single + * textured quad at the world origin. A null image or handle paints the grid alone. + * + * The quad samples through the same premultiplied fragment shader the puppet uses, so an underlay + * matches the puppet's texel rendering exactly. + * + * @param RenderTarget target The surface to draw into. + * @param DecodedImage image The image whose extent the quad and grid tile take, or null. + * @param GpuTexture handle The uploaded texture for [image], or null. + * @param Int viewportWidth The target width in pixels. + * @param Int viewportHeight The target height in pixels. + */ + private fun renderUnderlay( + target: RenderTarget, + image: DecodedImage?, + handle: GpuTexture?, + viewportWidth: Int, + viewportHeight: Int, + ) { + val camera = effectiveCamera(viewportWidth, viewportHeight) + val transform = camera.worldToNdc(viewportWidth, viewportHeight) + val affine = WorldToNdc(transform[0], transform[1], transform[2], transform[3]) + // The UV grid's major lines fall on the unit image tile (UV integers), so the major spacing is the + // image's pixel extent; minor lines subdivide the tile. With no image, fall back to the square grid. + val majorSpacingX = image?.width?.toFloat() ?: gridScale + val majorSpacingY = image?.height?.toFloat() ?: gridScale + + val frame = device.beginFrame() + val pass = frame.beginRenderPass(passSpec(target, LoadAction.DontCare, viewportWidth, viewportHeight)) + pass.setPipeline(gridPipeline!!) + // The UV grid's unit tile starts at the image origin (UV 0,0 = image-pixel 0,0), so anchor at (0, 0). + pass.drawGrid( + GridUniforms(affine, viewportWidth, viewportHeight, 0f, 0f, majorSpacingX, majorSpacingY, gridSubdivisions, gridPixelScale, gridColors), + ) + if (image != null && handle != null) { + pass.setPipeline(atlasPagePipeline!!) + pass.setCamera(affine, viewportWidth, viewportHeight) + fragmentScratch.reset() + fragmentScratch.useTexture = true + pass.drawAtlasPage(handle, image.width.toFloat(), image.height.toFloat(), fragmentScratch) + } + pass.end() + frame.endFrame() + } + + /** + * The uploaded texture for an underlay image, uploading it on first sight. + * + * Keyed on image IDENTITY, not content: the store hands out the same decoded instance for a given + * layer, so identity is both correct and free. The cache is deliberately tiny - a UV editor shows + * one layer at a time and only a handful of areas can exist - and evicts in insertion order, which + * costs a re-upload in the pathological case and bounds GPU memory in every other. Rendering the + * whole document's layers at once is a different problem with a different answer (paging or + * rebatching), and it belongs to the viewport's layer display mode, not here. + * + * Render thread only: it creates GPU resources, so it must run with the context current. + * + * @param DecodedImage image The image to upload. + * @return GpuTexture The texture handle. + */ + private fun underlayTextureFor(image: DecodedImage): GpuTexture { + underlayTextures[image]?.let { existing -> + return existing + } + while (underlayTextures.size >= UNDERLAY_TEXTURE_CACHE_SIZE) { + val evicted = underlayTextures.keys.first() + underlayTextures.remove(evicted)?.let { handle -> device.destroyTexture(handle) } + } + val created = device.createTexture(image.width, image.height, TextureFormat.Rgba8, TextureFilter.Linear, image.rgba) + underlayTextures[image] = created + return created + } + + /** Draws the grid backdrop and, when enabled, the world-origin axis lines behind the puppet. */ + private fun drawBackdrop(pass: RenderPassEncoder, affine: WorldToNdc, viewportWidth: Int, viewportHeight: Int) { + pass.setPipeline(gridPipeline!!) + pass.drawGrid( + GridUniforms( + affine, + viewportWidth, + viewportHeight, + currentModel.worldOriginX, + currentModel.worldOriginZ, + gridScale, + gridScale, + gridSubdivisions, + gridPixelScale, + gridColors, + ), + ) + if (worldAxesVisible) { + // The axes sit between the backdrop and the drawables, reading as part of the canvas. + val originNdcX = affine.scaleX * currentModel.worldOriginX + affine.offsetX + val originNdcY = affine.scaleY * currentModel.worldOriginZ + affine.offsetY + val axisColors = WorldAxisColors.Classic + pass.setPipeline(axisPipeline!!) + pass.drawAxisLine(AxisLineUniforms(originNdcY, vertical = false, axisColors.xRed, axisColors.xGreen, axisColors.xBlue)) + pass.drawAxisLine(AxisLineUniforms(originNdcX, vertical = true, axisColors.zRed, axisColors.zGreen, axisColors.zBlue)) + } + } + + /** + * Renders the mask sources' coverage into the shared mask target, as its own cleared pass at the + * render's USED viewport (the same origin-anchored projection as the main pass, so fragment (x, y) + * there reads coverage texel (x, y) here). The Clear load fills the whole capacity texture + * (a clear ignores the viewport) - harmless, and cheap next to the realloc it replaces. + * + * @param FrameEncoder frame The frame being recorded. + * @param List maskIds The mask source drawables. + * @param WorldToNdc affine The camera affine. + * @param Int viewportWidth The render width in pixels. + * @param Int viewportHeight The render height in pixels. + */ + private fun renderMaskCoverage( + frame: org.umamo.render.device.FrameEncoder, + maskIds: List, + affine: WorldToNdc, + viewportWidth: Int, + viewportHeight: Int, + ) { + val target = maskTarget ?: return + val coverage = frame.beginRenderPass(passSpec(target, LoadAction.Clear, viewportWidth, viewportHeight, clearAlpha = 0f)) + for (maskId in maskIds) { + val mask = gpuById[maskId] ?: continue + if (!mask.visible || mask.indexCount == 0) { + continue + } + // Coverage is the mask's shape at full intensity, unmasked, and ALWAYS Normal blend regardless + // of the mask drawable's own blend mode: an Additive or Multiply source would leave the cleared + // coverage target's alpha at 0, so the masked drawable would sample zero coverage and vanish. + drawDrawable( + coverage, + mask, + affine, + blendMode = BlendMode.Normal, + opacity = 1f, + highlight = 0f, + isActive = false, + masked = false, + maskCoverage = null, + ) + } + coverage.end() + } + + /** + * Binds a drawable's pipeline + per-pose state and issues its draw into [pass]. The camera's + * screen-space divisor is always the side-target capacity: a masked draw samples the mask + * coverage texture at that allocation, and for an unmasked (or coverage-pass) draw the divisor + * is simply unused. + * + * @param BlendMode blendMode The blend to draw with - the drawable's own for the main pass, forced + * [BlendMode.Normal] for a mask-coverage draw (see [renderMaskCoverage]). + */ + private fun drawDrawable( + pass: RenderPassEncoder, + gpuDrawable: GpuDrawable, + affine: WorldToNdc, + blendMode: BlendMode, + opacity: Float, + highlight: Float, + isActive: Boolean, + masked: Boolean, + maskCoverage: GpuTexture?, + ) { + pass.setPipeline(pipelineFor(gpuDrawable.isGlueMesh, blendMode, gpuDrawable.culling)) + pass.setCamera(affine, sideTargetCapacityWidth, sideTargetCapacityHeight) + fillFragment(fragmentScratch, gpuDrawable, opacity, highlight, isActive, masked) + // Reused per draw rather than allocating a bundle per drawable per frame, matching the deform / + // fragment scratch. A glue draw does not deform, so it needs no delta / control-point textures. + texturesScratch.atlas = gpuDrawable.activeTexture() + texturesScratch.maskCoverage = maskCoverage + if (gpuDrawable.isGlueMesh) { + texturesScratch.deltaTexture = null + texturesScratch.warpControlPoints = null + pass.drawGlueMesh(gpuDrawable.mesh, store!!, gpuDrawable.glueBaseOffset, glueIntensities, fragmentScratch, texturesScratch) + } else { + texturesScratch.deltaTexture = gpuDrawable.deltaTexture + texturesScratch.warpControlPoints = gpuDrawable.cpTexture + fillDeform(deformScratch, gpuDrawable) + pass.drawPuppetMesh(gpuDrawable.mesh, deformScratch, fragmentScratch, texturesScratch) + } + } + + /** The cached draw pipeline for a glue vs non-glue mesh at a blend mode and cull state. */ + private fun pipelineFor(isGlueMesh: Boolean, blendMode: BlendMode, cullBackFaces: Boolean): RenderPipeline { + val cache = (if (isGlueMesh) gluePipelines else puppetPipelines)[if (cullBackFaces) 1 else 0] + return cache.getOrPut(blendMode) { + val purpose = if (isGlueMesh) PipelinePurpose.PuppetGlueDraw else PipelinePurpose.PuppetDeformDraw + device.createRenderPipeline(RenderPipelineSpec(purpose, blendOf(blendMode), cullBackFaces)) + } + } + + /** Fills a drawable's per-pose deform uniforms (active corners + baked parent transform). */ + private fun fillDeform(deform: DeformUniforms, gpuDrawable: GpuDrawable) { + val corners = gpuDrawable.corners ?: return + val cornerCount = minOf(MAX_CORNERS, corners.size) + deform.cornerCount = cornerCount + for (cornerIndex in 0 until cornerCount) { + deform.cornerCell[cornerIndex] = corners[cornerIndex].linearIndex + deform.cornerWeight[cornerIndex] = corners[cornerIndex].weight + } + // Blend-shape columns: map the pose's active contributions through the static layout. + // Surplus beyond MAX_BLEND_CORNERS is dropped deterministically (corpus max is 18). + var blendCount = 0 + val blend = gpuDrawable.blend + if (blend != null) { + for (contribution in blend.contributions) { + if (blendCount >= MAX_BLEND_CORNERS) { + break + } + val column = gpuDrawable.blendLayout.columnOf(contribution.bindingIndex, contribution.keyIndex) ?: continue + deform.blendCell[blendCount] = column + deform.blendWeight[blendCount] = contribution.weight + blendCount++ + } + } + deform.blendCount = blendCount + when (val parentWorld = gpuDrawable.parentWorld) { + is RotationWorld -> { + deform.parentType = 1 + val xform = parentWorld.xform + deform.rotation[0] = xform.c12 + deform.rotation[1] = xform.c13 + deform.rotation[2] = xform.c14 + deform.rotation[3] = xform.c15 + deform.rotation[4] = xform.ox + deform.rotation[5] = xform.oy + } + + is WarpWorld -> { + deform.parentType = 2 + deform.warpColumns = parentWorld.cols + deform.warpRows = parentWorld.rows + deform.warpBilinear = parentWorld.bilinear + } + + else -> deform.parentType = 0 + } + } + + /** Fills a drawable's fragment uniforms (texture-or-color, opacity, mask flags, highlight). */ + private fun fillFragment( + fragment: FragmentUniforms, + gpuDrawable: GpuDrawable, + opacity: Float, + highlight: Float, + isActive: Boolean, + masked: Boolean, + ) { + fragment.reset() + // The CHOSEN handle, not the atlas one: a drawable rendering from its source artwork has no atlas + // binding in play, and keying off the wrong field would draw it as a flat color. + val activeTexture = gpuDrawable.activeTexture() + if (activeTexture != null) { + fragment.useTexture = true + // Identity unless this drawable is sampling its artwork, in which case the affine is what + // makes its stored (atlas-frame) coordinates address that image instead. + if (activeTexture === gpuDrawable.layerTexture) { + gpuDrawable.layerUvAffine?.copyInto(fragment.uvAffine) + } + } else { + fragment.colorRed = gpuDrawable.color[0] + fragment.colorGreen = gpuDrawable.color[1] + fragment.colorBlue = gpuDrawable.color[2] + fragment.colorAlpha = gpuDrawable.color[3] + } + fragment.opacity = opacity + fragment.useMask = masked + fragment.invertMask = masked && gpuDrawable.invertMask + fragment.multiplyRed = gpuDrawable.multiplyColor.red + fragment.multiplyGreen = gpuDrawable.multiplyColor.green + fragment.multiplyBlue = gpuDrawable.multiplyColor.blue + fragment.screenRed = gpuDrawable.screenColor.red + fragment.screenGreen = gpuDrawable.screenColor.green + fragment.screenBlue = gpuDrawable.screenColor.blue + fragment.highlight = highlight + val tint = if (isActive) activeHighlightColor else highlightColor + fragment.highlightRed = tint[0] + fragment.highlightGreen = tint[1] + fragment.highlightBlue = tint[2] + } + + /** + * The camera to project through this frame: the one set by [setCamera], or a fit of the rest-pose + * content into the viewport before any is set. + */ + private fun effectiveCamera(viewportWidth: Int, viewportHeight: Int): ViewportCamera = + currentCamera ?: ViewportCamera.fit(contentBounds(), viewportWidth, viewportHeight) + + /** + * Computes the rest-pose content bounds lazily, from a CPU eval at default parameters (shown drawables + * only). Re-armed by [updateModel] / [setShownDrawables] so a base-mesh edit re-frames view.fit. A + * model that shows nothing - a new, empty document, or a rig with every drawable hidden - frames its + * canvas instead, so the view opens on the work surface rather than on nothing. + */ + private fun ensureContentBounds() { + if (bboxReady) { + return + } + val bounds = + contentBoundsOf(applyCpuDeform(currentModel, preparePose(currentModel, emptyMap())), shownDrawableIds) + ?: emptyContentBoundsOf(currentModel) + minX = bounds.minX + minY = bounds.minY + spanX = bounds.width + spanY = bounds.height + bboxReady = true + } + + /** + * Grows the shared side-target capacity (mask + snapshot + composite pool) to hold a + * [viewportWidth] x [viewportHeight] render, per-axis high-water: a request inside the current + * capacity allocates nothing (the per-frame path during a gutter drag), growth destroys the mask, + * snapshot, and pool together and recreates mask + snapshot at the new capacity (the pool refills + * lazily in [acquireCompositeTarget]). The three kinds share one capacity because the composite + * shader samples all of them through a single screenTexSize divisor. + * + * @param Int viewportWidth The render width in pixels. + * @param Int viewportHeight The render height in pixels. + */ + private fun ensureSideTargets(viewportWidth: Int, viewportHeight: Int) { + if (viewportWidth > sideTargetCapacityWidth || viewportHeight > sideTargetCapacityHeight) { + maskTarget?.let { device.destroyRenderTarget(it) } + compositeTargets.forEach { device.destroyRenderTarget(it) } + compositeTargets.clear() + snapshotTarget?.let { device.destroyRenderTarget(it) } + snapshotTarget = null + sideTargetCapacityWidth = maxOf(viewportWidth, sideTargetCapacityWidth) + sideTargetCapacityHeight = maxOf(viewportHeight, sideTargetCapacityHeight) + maskTarget = + device.createRenderTarget( + RenderTargetSpec(sideTargetCapacityWidth, sideTargetCapacityHeight, TextureFormat.Rgba8, sampled = true), + ) + } + if (snapshotTarget == null) { + snapshotTarget = + device.createRenderTarget( + RenderTargetSpec(sideTargetCapacityWidth, sideTargetCapacityHeight, TextureFormat.Rgba8, sampled = true), + ) + } + } + + /** + * The pooled layer target for one composite nesting depth, allocated on first use at the shared + * side-target capacity. Slots below [depth] are ancestors mid-composite; the slot itself is + * always free when asked for, because composites at one level are strictly sequential. + */ + private fun acquireCompositeTarget(depth: Int): RenderTarget { + while (compositeTargets.size <= depth) { + compositeTargets.add( + device.createRenderTarget( + RenderTargetSpec(sideTargetCapacityWidth, sideTargetCapacityHeight, TextureFormat.Rgba8, sampled = true), + ), + ) + } + return compositeTargets[depth] + } + + /** A render-pass spec for [target] at [load], with an optional clear color and pass scissor. */ + private fun passSpec( + target: RenderTarget, + load: LoadAction, + viewportWidth: Int, + viewportHeight: Int, + clearAlpha: Float = 0f, + scissor: ScissorRect? = null, + clearRed: Float = 0f, + clearGreen: Float = 0f, + clearBlue: Float = 0f, + ) = org.umamo.render.device.RenderPassSpec( + colorTarget = target, + loadAction = load, + viewportWidth = viewportWidth, + viewportHeight = viewportHeight, + clearRed = clearRed, + clearGreen = clearGreen, + clearBlue = clearBlue, + clearAlpha = clearAlpha, + scissor = scissor, + ) + + /** + * Intersects two scissor rects, treating null as "the whole viewport". A composite layer's own + * bounds ([first]) are always contained in its parent layer's ([second]) by construction, so a + * non-empty intersection is expected; an empty intersection (only reachable if that containment ever + * failed) falls back to [first], the layer's own rect, rather than null - so it can never silently + * widen to the whole viewport. + * + * @param ScissorRect? first The inner rect (the composite layer's own bounds), or null. + * @param ScissorRect? second The outer rect (the enclosing span's scissor), or null. + * @return ScissorRect? The intersection, or [first] on an empty intersection, or null when both are null. + */ + private fun intersectScissor(first: ScissorRect?, second: ScissorRect?): ScissorRect? { + if (first == null) { + return second + } + if (second == null) { + return first + } + val left = maxOf(first.x, second.x) + val top = maxOf(first.y, second.y) + val right = minOf(first.x + first.width, second.x + second.width) + val bottom = minOf(first.y + first.height, second.y + second.height) + if (right <= left || bottom <= top) { + return first + } + return ScissorRect(left, top, right - left, bottom - top) + } + + private fun blendOf(mode: BlendMode): PipelineBlend = + when (mode) { + BlendMode.Normal -> PipelineBlend.Normal + BlendMode.AdditivePremultiplied -> PipelineBlend.Additive + BlendMode.MultiplyPremultiplied -> PipelineBlend.Multiply + // Scene draws never reach here with a 5.3 mode (renderPlanNodes routes extended blends + // through the destination-sampling composite pass); these branches are a safe fallback + // approximating with the legacy fixed-function analog where one exists - the same + // approximation the MOC3 constant-flags 2-bit field encodes for old runtimes. + BlendMode.Additive, BlendMode.AdditiveGlow -> PipelineBlend.Additive + BlendMode.Multiply -> PipelineBlend.Multiply + BlendMode.Darken, + BlendMode.ColorBurn, + BlendMode.LinearBurn, + BlendMode.Lighten, + BlendMode.Screen, + BlendMode.ColorDodge, + BlendMode.Overlay, + BlendMode.SoftLight, + BlendMode.HardLight, + BlendMode.LinearLight, + BlendMode.Hue, + BlendMode.Color, + -> PipelineBlend.Normal + } +} + +// Padding (in ON-SCREEN pixels, scaled to framebuffer pixels by gridPixelScale in scissorRectOf) added +// around a composite layer's conservative bounds before it becomes a scissor rect - a small guard so +// bilinear atlas sampling at the mesh edge and float rounding in the world->pixel map can never clip a +// fringe pixel the un-scissored path would keep. +private const val SCISSOR_PAD_PX = 2 + +/** Resets every field to its "nothing set" default, for reuse across draws. */ +private fun FragmentUniforms.reset() { + useTexture = false + colorRed = 0f + colorGreen = 0f + colorBlue = 0f + colorAlpha = 0f + opacity = 1f + useMask = false + invertMask = false + multiplyRed = 1f + multiplyGreen = 1f + multiplyBlue = 1f + screenRed = 0f + screenGreen = 0f + screenBlue = 0f + highlight = 0f + highlightRed = 0f + highlightGreen = 0f + highlightBlue = 0f + // IDENTITY, not zero. Every other field here resets to a harmless zero; this one cannot - a zeroed + // affine maps every texture coordinate onto texel (0, 0), so the whole draw samples one pixel. + setIdentityUvAffine(uvAffine) +} + +/** + * Writes the identity 2x3 affine into a uv-affine array in place. + * + * @param FloatArray affine The six-float affine to overwrite. + */ +private fun setIdentityUvAffine(affine: FloatArray) { + affine[0] = 1f + affine[1] = 0f + affine[2] = 0f + affine[3] = 0f + affine[4] = 1f + affine[5] = 0f +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/AtlasCollisionRegionsTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/AtlasCollisionRegionsTest.kt new file mode 100644 index 0000000..0af0277 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/AtlasCollisionRegionsTest.kt @@ -0,0 +1,169 @@ +package org.umamo.render + +import org.umamo.format.art.LayerBounds +import org.umamo.runtime.model.AtlasPlacement +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the collision regions the placement gizmo warns over: a tile's opaque mask marks exactly the + * texels at or above the threshold; a mesh mask covers a triangle's pixels plus one pixel of margin + * and leaves the corners of a thin diagonal mesh's box clear; a page occupancy finds painted pixels + * only where a sampled region actually covers them (not in a strand's empty corner, nor in a spot a + * mover is leaving); a sampled region hits a placed mask only on opaque texels or their extrusion + * band; and two tiles whose boxes overlap while their triangles and pixels stay apart never collide. + */ +class AtlasCollisionRegionsTest { + private fun raster(width: Int, height: Int, opaque: (Int, Int) -> Boolean): DecodedImage { + val rgba = ByteArray(width * height * 4) + for (y in 0 until height) { + for (x in 0 until width) { + if (opaque(x, y)) { + val offset = (y * width + x) * 4 + rgba[offset] = 0x40 + rgba[offset + 3] = 0xFF.toByte() + } + } + } + return DecodedImage(rgba, width, height) + } + + private fun placement(x: Float, y: Float, rotationDegrees: Float = 0f): AtlasPlacement = + AtlasPlacement(0, x, y, 1f, 1f, rotationDegrees) + + private fun triangle(x0: Float, y0: Float, x1: Float, y1: Float, x2: Float, y2: Float): FloatArray = + floatArrayOf(x0, y0, x1, y1, x2, y2) + + /** A mesh covering the axis-aligned rectangle [left, right) by [top, bottom) with two triangles. */ + private fun quadMesh(left: Float, top: Float, right: Float, bottom: Float): TileMeshMask = + assertNotNull( + TileMeshMask.of( + listOf(triangle(left, top, right, top, right, bottom), triangle(left, top, right, bottom, left, bottom)), + ), + ) + + @Test + fun theOpaqueMaskMarksTexelsAtTheThreshold() { + val art = raster(6, 6) { x, y -> x == y } + val mask = TileOpaqueMask.of(art, LayerBounds(1, 1, 4, 4), alphaThreshold = 1) + assertTrue(mask.isOpaque(2, 2), "a diagonal texel inside the trim") + assertFalse(mask.isOpaque(2, 3), "an off-diagonal texel") + assertFalse(mask.isOpaque(0, 0), "outside the trim, even though the raster is opaque there") + } + + @Test + fun theMeshMaskCoversATriangleAndOnePixelAround() { + // A right triangle with the right angle at (10, 10), legs of 8 along +x and +y. + val mask = assertNotNull(TileMeshMask.of(listOf(triangle(10f, 10f, 18f, 10f, 10f, 18f)))) + assertTrue(mask.isCovered(11, 11), "inside") + assertTrue(mask.isCovered(9, 9), "the one-pixel margin around a corner") + assertFalse(mask.isCovered(17, 17), "the far corner of the bounding box, past the hypotenuse") + assertFalse(mask.isCovered(7, 7), "two pixels out is beyond the margin") + assertNull(TileMeshMask.of(emptyList()), "no triangles, no mask") + } + + @Test + fun aThinDiagonalMeshLeavesItsBoxCornersClear() { + // A sliver along the diagonal of a 40x40 box. + val strand = assertNotNull(TileMeshMask.of(listOf(triangle(0f, 0f, 2f, 0f, 40f, 40f), triangle(0f, 0f, 40f, 40f, 38f, 40f)))) + assertTrue(strand.isCovered(20, 20), "on the diagonal") + assertFalse(strand.isCovered(35, 5), "the box's top-right corner") + assertFalse(strand.isCovered(5, 35), "the box's bottom-left corner") + assertEquals(-1, strand.bounds.left, "the box carries the margin") + } + + @Test + fun theOccupancyFindsPaintedPixelsInsideASampledRegionOnly() { + // A diagonal strand across a 32x32 page: painted only where x == y. + val page = raster(32, 32) { x, y -> x == y } + val occupancy = PageOccupancy.of(page, excluded = emptyList()) + assertTrue(occupancy.isPainted(10, 10)) + assertFalse(occupancy.isPainted(10, 11)) + // A mesh in the strand's empty corner samples nothing, although the strand's box is the whole page. + val corner = SampledRegion(placement(20f, 2f), quadMesh(0f, 0f, 6f, 6f)) + assertNull(occupancy.firstPaintedPixelIn(corner), "a region in the strand's empty corner is clear") + val across = SampledRegion(placement(12f, 12f), quadMesh(1f, 1f, 5f, 5f)) + assertEquals(PixelRect(12, 12, 13, 13), occupancy.firstPaintedPixelIn(across), "a region across the strand hits its first painted pixel (the margin reaches one pixel out)") + } + + @Test + fun anExcludedRectangleReadsAsEmpty() { + val page = raster(16, 16) { x, y -> x in 4 until 8 && y in 4 until 8 } + val occupancy = PageOccupancy.of(page, excluded = listOf(PixelRect(4, 4, 8, 8))) + assertFalse(occupancy.isPainted(5, 5), "the mover's old spot reads as empty") + assertTrue(occupancy.blockMayBePainted(0, 0), "the block bit ignores exclusions and the exact test decides") + assertNull(occupancy.firstPaintedPixelIn(SampledRegion(placement(3f, 3f), quadMesh(0f, 0f, 6f, 6f)))) + } + + @Test + fun aSampledRegionKeepsItsShapeUnderRotation() { + // A 10x4 mesh turned a quarter stands 4 wide and 10 tall (plus the margin), and the box's empty + // corners stay outside the region. + val region = SampledRegion(placement(20f, 20f, rotationDegrees = 90f), quadMesh(0f, 0f, 10f, 4f)) + assertTrue(region.contains(18f, 25f), "inside the turned rectangle") + assertFalse(region.contains(13f, 25f), "beyond its short side and margin") + assertTrue(region.bounds.right - region.bounds.left in 5.9f..6.1f, "the bounds are 4 wide plus the margin") + assertTrue(region.bounds.bottom - region.bounds.top in 11.9f..12.1f, "and 10 tall plus the margin") + } + + @Test + fun aSampledRegionHitsAPlacedMaskOnlyOnOpaqueTexelsOrTheirBand() { + // A painter whose only opaque texel is at (2, 2) of a 5x5 trim, placed at (10, 10): opaque + // page pixel (12, 12). + val painter = TileOpaqueMask.of(raster(5, 5) { x, y -> x == 2 && y == 2 }, LayerBounds(0, 0, 5, 5), alphaThreshold = 1) + val painterAt = placement(10f, 10f) + val point = quadMesh(0f, 0f, 1f, 1f) + // The mesh's margin reaches one pixel around (10, 10): pixels 9..11, all transparent. + val overTransparentCorner = SampledRegion(placement(10f, 10f), point) + assertFalse(sampledRegionHitsMask(overTransparentCorner, painterAt, painter, extrude = 2), "a transparent texel of the painter's rectangle is not paint") + val overTheTexel = SampledRegion(placement(12f, 12f), point) + assertTrue(sampledRegionHitsMask(overTheTexel, painterAt, painter, extrude = 0), "the opaque texel is paint") + // The band: a mesh two pixels past the trim's right edge, beside an opaque edge texel. + val bandRegion = SampledRegion(placement(16f, 12f), point) + assertFalse(sampledRegionHitsMask(bandRegion, painterAt, painter, extrude = 0), "without a band the edge is transparent") + val edgePainter = TileOpaqueMask.of(raster(5, 5) { x, _ -> x == 4 }, LayerBounds(0, 0, 5, 5), alphaThreshold = 1) + assertTrue(sampledRegionHitsMask(bandRegion, painterAt, edgePainter, extrude = 2), "an opaque edge texel's band counts as paint") + } + + @Test + fun overlappingBoxesWithDisjointTrianglesAndPixelsNeverCollide() { + // The screenshot: a wide tile whose single triangular mesh overhangs its art and fills only the + // upper-left half of its box, and a strand whose sliver mesh hugs its diagonal pixels. Placed + // so the strand's pixels sit inside the wide mesh's BOX (its lower-right corner) while no + // triangle touches the other tile's pixels or its extrusion band. + val wideArt = raster(40, 20) { x, y -> x < 20 && y in 4 until 16 } + val wideMask = TileOpaqueMask.of(wideArt, LayerBounds(0, 4, 20, 12), alphaThreshold = 1) + val wideMesh = assertNotNull(TileMeshMask.of(listOf(triangle(0f, 2f, 24f, 2f, 0f, 18f)))) + val wideAt = placement(0f, 0f) + val strandArt = raster(30, 30) { x, y -> x == y } + val strandMask = TileOpaqueMask.of(strandArt, LayerBounds(0, 0, 30, 30), alphaThreshold = 1) + val strandMesh = assertNotNull(TileMeshMask.of(listOf(triangle(0f, -1f, 30f, 29f, 0f, 1f), triangle(0f, 1f, 30f, 29f, 30f, 31f)))) + // The strand's first pixels land at page (24, 9), (25, 10): inside the wide mesh's box (x to 25, + // y to 19), while the triangle's coverage at those rows ends near x = 16 - clear of the strand's + // two-pixel band even with the mesh's one-pixel margin - and past the wide art's own band. + val strandNear = placement(24f, 9f) + assertTrue(SampledRegion(wideAt, wideMesh).bounds.overlaps(placementFootprint(strandNear, strandMask.trim, reserve = null)), "the boxes do overlap") + assertFalse(sampledRegionHitsMask(SampledRegion(wideAt, wideMesh), strandNear, strandMask, extrude = 2), "the wide mesh's box holds the strand's pixels but its triangle does not reach them") + assertFalse(sampledRegionHitsMask(SampledRegion(strandNear, strandMesh), wideAt, wideMask, extrude = 2), "the strand's triangles never reach the wide tile's pixels or band") + // Slide the strand under the triangle and it collides. + val strandTouching = placement(4f, 6f) + assertTrue(sampledRegionHitsMask(SampledRegion(wideAt, wideMesh), strandTouching, strandMask, extrude = 2), "an overhanging triangle over the strand's pixels collides") + val strandFar = placement(30f, 0f) + assertFalse(sampledRegionHitsMask(SampledRegion(wideAt, wideMesh), strandFar, strandMask, extrude = 2), "far apart, nothing") + } + + @Test + fun aMeshCoveringHalfItsTileIgnoresPaintUnderTheOtherHalf() { + // A bystander whose mesh covers only the left half of its 20x10 tile; a mover's opaque pixel + // under its right half is paint nobody samples. + val halfMesh = quadMesh(0f, 0f, 10f, 10f) + val bystanderAt = placement(0f, 0f) + val dot = TileOpaqueMask.of(raster(3, 3) { x, y -> x == 1 && y == 1 }, LayerBounds(0, 0, 3, 3), alphaThreshold = 1) + assertFalse(sampledRegionHitsMask(SampledRegion(bystanderAt, halfMesh), placement(15f, 4f), dot, extrude = 0), "paint under the unmeshed half") + assertTrue(sampledRegionHitsMask(SampledRegion(bystanderAt, halfMesh), placement(4f, 4f), dot, extrude = 0), "paint under the meshed half") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/AtlasPlacementDragTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/AtlasPlacementDragTest.kt new file mode 100644 index 0000000..8d5a83c --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/AtlasPlacementDragTest.kt @@ -0,0 +1,70 @@ +package org.umamo.render + +import org.umamo.format.art.LayerBounds +import org.umamo.format.atlas.AtlasPackReserve +import org.umamo.runtime.model.AtlasPlacement +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins the placement footprint the gizmo warns over: an upright placement's footprint is its trim at + * its position, a mesh reserve widens it, a turned placement's footprint is the turned rectangle's + * bounding box, and the overlap / off-page tests read those edges the way the composer will paint + * them. + */ +class AtlasPlacementDragTest { + private val trim = LayerBounds(2, 3, 8, 6) + + private fun placement(x: Float, y: Float, rotationDegrees: Float = 0f, scale: Float = 1f): AtlasPlacement = + AtlasPlacement(0, x, y, scale, scale, rotationDegrees) + + private fun assertClose(expected: Float, actual: Float, message: String) { + assertTrue(abs(expected - actual) < 1e-3f, "$message: expected $expected, was $actual") + } + + private fun assertFootprint(expected: PlacementFootprint, actual: PlacementFootprint) { + assertClose(expected.left, actual.left, "left") + assertClose(expected.top, actual.top, "top") + assertClose(expected.right, actual.right, "right") + assertClose(expected.bottom, actual.bottom, "bottom") + } + + @Test + fun anUprightFootprintIsTheTrimAtThePosition() { + assertFootprint(PlacementFootprint(12f, 23f, 20f, 29f), placementFootprint(placement(10f, 20f), trim, reserve = null)) + } + + @Test + fun aMeshReserveWidensTheFootprint() { + val reserve = AtlasPackReserve(left = -1, top = 0, right = 12, bottom = 5) + assertFootprint(PlacementFootprint(9f, 20f, 22f, 29f), placementFootprint(placement(10f, 20f), trim, reserve)) + } + + @Test + fun aScaledFootprintScalesAboutTheTileOrigin() { + assertFootprint(PlacementFootprint(11f, 21.5f, 15f, 24.5f), placementFootprint(placement(10f, 20f, scale = 0.5f), trim, reserve = null)) + } + + @Test + fun aQuarterTurnedFootprintIsTheTurnedRectanglesBounds() { + // A 90 degree placement maps (x, y) to (-y, x) about the tile origin: the 8x6 trim becomes 6 wide by 8 tall. + val footprint = placementFootprint(placement(10f, 20f, rotationDegrees = 90f), trim, reserve = null) + assertClose(6f, footprint.right - footprint.left, "turned width") + assertClose(8f, footprint.bottom - footprint.top, "turned height") + assertClose(10f - 9f, footprint.left, "the trim's bottom edge (y = 9) turns to x = -9") + assertClose(20f + 2f, footprint.top, "the trim's left edge (x = 2) turns to y = 2") + } + + @Test + fun overlapAndPageTestsReadTheEdges() { + val one = PlacementFootprint(0f, 0f, 10f, 10f) + assertTrue(one.overlaps(PlacementFootprint(9f, 9f, 20f, 20f)), "shared area overlaps") + assertFalse(one.overlaps(PlacementFootprint(10f, 0f, 20f, 10f)), "a touching edge is not an overlap") + assertTrue(one.expanded(2f).overlaps(PlacementFootprint(11f, 0f, 20f, 10f)), "the gutter margin reaches a neighbor one pixel away") + assertFalse(one.exceeds(10, 10), "a footprint filling the page exactly stays on it") + assertTrue(one.expanded(1f).exceeds(10, 10), "growing past the edge spills") + assertTrue(PlacementFootprint(-0.5f, 0f, 5f, 5f).exceeds(64, 64), "a fractional overhang spills") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/DerivedAtlasTexturesTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/DerivedAtlasTexturesTest.kt new file mode 100644 index 0000000..9250731 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/DerivedAtlasTexturesTest.kt @@ -0,0 +1,389 @@ +package org.umamo.render + +import org.umamo.format.atlas.AtlasPackFixed +import org.umamo.format.atlas.AtlasPackItem +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.AtlasPackPlacement +import org.umamo.format.atlas.composeAtlasPages +import org.umamo.format.atlas.packAtlas +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.placementAffine +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the generated-page derivation against the packer itself: packing a tile set and deriving the + * pages back from the lowered placements must produce byte-identical pixels and the same page + * numbering. This is the gate on the trim/extrude coupling - the derivation re-runs the packer's + * trim analysis under the same policy, and any drift between the two shows up here as a byte diff. + * Beyond the packer's own placements, a hand-authored one (moved, scaled, rotated, off the pixel + * grid) derives through the affine composer instead of being refused - and one the packer KEPT as a + * fixed tile derives byte-identically beside the tiles it packed around it. + */ +class DerivedAtlasTexturesTest { + private val tileIds = listOf(AtlasTileId("t0"), AtlasTileId("t1"), AtlasTileId("t2")) + + /** + * A raster with a transparent margin around a filled core, so the pack genuinely trims. + * + * @param Int width The raster width in pixels. + * @param Int height The raster height in pixels. + * @param Int margin The transparent border width on every side. + * @param Int red The core's red byte. + * @return ByteArray RGBA8888 pixels. + */ + private fun tileRaster(width: Int, height: Int, margin: Int, red: Int): ByteArray { + val rgba = ByteArray(width * height * 4) + for (rowIndex in margin until height - margin) { + for (columnIndex in margin until width - margin) { + val offset = (rowIndex * width + columnIndex) * 4 + rgba[offset] = red.toByte() + rgba[offset + 1] = (rowIndex * 16 + columnIndex).toByte() + rgba[offset + 2] = 0x40 + rgba[offset + 3] = 0xFF.toByte() + } + } + return rgba + } + + private class Fixture( + val model: PuppetModel, + val store: SourceArtRasters, + val packedPages: List, + val rasters: List, + ) + + /** + * Three tiles packed by the packer, lowered onto a model, and a store serving their pixels. + * + * @param List extraTiles Tiles appended to the atlas AFTER the pack, with the raster the store serves for each. + * @return Fixture The packed model, its store, the packer's pages, and the three tile rasters. + */ + private fun packedFixture(extraTiles: List> = emptyList()): Fixture { + val rasters = + listOf( + DecodedImage(tileRaster(12, 10, 2, 0x10), 12, 10), + DecodedImage(tileRaster(8, 16, 1, 0x20), 8, 16), + DecodedImage(tileRaster(10, 10, 0, 0x30), 10, 10), + ) + val items = + tileIds.mapIndexed { tileIndex, tileId -> + AtlasPackItem(tileId.raw, rasters[tileIndex].width, rasters[tileIndex].height, rasters[tileIndex].rgba) + } + val result = packAtlas(items, AtlasPackOptions(maxPageSize = 64)) + assertEquals(tileIds.size, result.placements.size, "every fixture tile packs") + + val placementByKey = result.placements.associateBy { placement -> placement.key } + val tiles = + tileIds.mapIndexed { tileIndex, tileId -> + AtlasTile( + tileId, + tileId.raw, + rasters[tileIndex].width, + rasters[tileIndex].height, + atlasPlacementFromPack(placementByKey.getValue(tileId.raw)), + ) + } + extraTiles.map { (tile, _) -> tile } + val drawables = + tileIds.mapIndexed { tileIndex, tileId -> + Drawable( + id = DrawableId("d$tileIndex"), + name = "d$tileIndex", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + atlasTileId = tileId, + ) + } + val model = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = 50f, + atlas = + PuppetAtlas( + pages = result.pages.map { page -> AtlasPage(page.width, page.height) }, + tiles = tiles, + ), + ) + val pngByTile = HashMap() + for ((tileIndex, tileId) in tileIds.withIndex()) { + pngByTile[tileId] = encodeAtlasPng(rasters[tileIndex]) + } + for ((tile, raster) in extraTiles) { + pngByTile[tile.id] = encodeAtlasPng(raster) + } + val store = SourceArtRasters.fromPng { tileId -> pngByTile[tileId] } + return Fixture(model, store, result.pages.map { page -> DecodedImage(page.rgba, page.width, page.height) }, rasters) + } + + private fun alphaAt(page: DecodedImage, x: Int, y: Int): Int = page.rgba[(y * page.width + x) * 4 + 3].toInt() and 0xFF + + private fun pixelBytes(image: DecodedImage, x: Int, y: Int): ByteArray { + val offset = (y * image.width + x) * 4 + return image.rgba.copyOfRange(offset, offset + 4) + } + + private fun PuppetModel.withTilePlacement(tileIndex: Int, placement: AtlasPlacement): PuppetModel = + copy(atlas = atlas.copy(tiles = atlas.tiles.mapIndexed { index, tile -> if (index == tileIndex) tile.copy(placement = placement) else tile })) + + @Test + fun derivedPagesAreByteIdenticalToThePackersAndShareItsNumbering() { + val fixture = packedFixture() + val model = fixture.model + + val derived = assertNotNull(deriveAtlasTextures(model, fixture.store, premultipliedAlpha = true)) + + assertEquals(fixture.packedPages.size, derived.atlases.size, "one derived page per packed page") + for (pageIndex in fixture.packedPages.indices) { + assertEquals(fixture.packedPages[pageIndex].width, derived.atlases[pageIndex].width) + assertEquals(fixture.packedPages[pageIndex].height, derived.atlases[pageIndex].height) + assertContentEquals( + fixture.packedPages[pageIndex].rgba, + derived.atlases[pageIndex].rgba, + "page $pageIndex pixels re-derive byte-identically", + ) + } + assertTrue(derived.premultipliedAlpha, "the convention flag passes through") + for ((tileIndex, tileId) in tileIds.withIndex()) { + val placement = assertNotNull(model.atlas.tiles[tileIndex].placement) + assertEquals( + placement.pageIndex, + derived.atlasIndexByDrawableId["d$tileIndex"], + "drawable d$tileIndex maps to its tile '$${tileId.raw}' page under the MODEL's numbering", + ) + } + } + + @Test + fun aScaledPlacementDerivesThroughTheAffinePath() { + val fixture = packedFixture() + val original = assertNotNull(fixture.model.atlas.tiles[0].placement) + val scaled = fixture.model.withTilePlacement(0, original.copy(scaleX = 0.5f, scaleY = 0.5f)) + + val derived = assertNotNull(deriveAtlasTextures(scaled, fixture.store, false), "a scaled placement resamples rather than refusing") + + val page = derived.atlases[original.pageIndex] + // Tile 0's opaque core is its 8x6 trim at (2, 2); halved about the tile origin it covers + // [origin + 1, origin + 5) by [origin + 1, origin + 4), and its old far corner is vacated. + val originX = original.positionX.toInt() + val originY = original.positionY.toInt() + assertEquals(255, alphaAt(page, originX + 2, originY + 2), "inside the halved footprint") + assertEquals(0, alphaAt(page, originX + 8, originY + 6), "the unscaled footprint's far corner is empty now") + assertFalse(page.rgba.contentEquals(fixture.packedPages[original.pageIndex].rgba), "the page changed") + } + + @Test + fun aMovedPlacementComposesTheTileAtItsNewSpotAndVacatesTheOld() { + val fixture = packedFixture() + val original = assertNotNull(fixture.model.atlas.tiles[0].placement) + val packedPage = fixture.packedPages[original.pageIndex] + // The trim origin on the page, and a move of three pixels toward whichever side has room. + val trimPageX = original.positionX.toInt() + 2 + val trimPageY = original.positionY.toInt() + 2 + val deltaX = if (trimPageX + 8 + 3 + 2 <= packedPage.width) 3 else -3 + val deltaY = if (trimPageY + 6 + 2 + 2 <= packedPage.height) 2 else -2 + val moved = fixture.model.withTilePlacement(0, original.copy(positionX = original.positionX + deltaX, positionY = original.positionY + deltaY)) + + val derived = assertNotNull(deriveAtlasTextures(moved, fixture.store, false)) + + val page = derived.atlases[original.pageIndex] + assertContentEquals( + pixelBytes(fixture.rasters[0], 3, 3), + pixelBytes(page, trimPageX + deltaX + 1, trimPageY + deltaY + 1), + "the tile's pixels sit at the new spot verbatim", + ) + val vacatedX = if (deltaX > 0) trimPageX else trimPageX + 7 + assertEquals(255, alphaAt(packedPage, vacatedX, trimPageY), "the column was the tile's before the move") + assertEquals(0, alphaAt(page, vacatedX, trimPageY), "the column the tile left behind is empty (beyond the extrusion band)") + } + + @Test + fun aRotatedFractionalPlacementDerives() { + val fixture = packedFixture() + val original = assertNotNull(fixture.model.atlas.tiles[0].placement) + val turned = original.copy(positionX = original.positionX + 0.5f, rotationDegrees = 30f) + val rotated = fixture.model.withTilePlacement(0, turned) + + val derived = assertNotNull(deriveAtlasTextures(rotated, fixture.store, false), "rotation and a fractional position resample rather than refuse") + + val page = derived.atlases[original.pageIndex] + val trim = assertNotNull(derivedTileTrim(fixture.rasters[0], rotated.atlas.composition.alphaThreshold)) + val footprint = placementFootprint(turned, trim, reserve = null) + val centerX = ((footprint.left + footprint.right) / 2f).toInt().coerceIn(0, page.width - 1) + val centerY = ((footprint.top + footprint.bottom) / 2f).toInt().coerceIn(0, page.height - 1) + assertTrue(alphaAt(page, centerX, centerY) > 0, "the turned tile's center is painted") + } + + @Test + fun aTurnedPackPlacementLowersAndDerivesByteIdenticallyToThePackersPage() { + val fixture = packedFixture() + val pageSide = 64 + // Tile 1 (8x16, trimmed to 6x14 at (1, 1)) placed turned: its footprint is 14 wide by 6 tall. + val packPlacements = + listOf( + AtlasPackPlacement(tileIds[0].raw, 0, pageX = 2, pageY = 2, trimLeft = 2, trimTop = 2, trimWidth = 8, trimHeight = 6, quarterTurns = 0), + AtlasPackPlacement(tileIds[1].raw, 0, pageX = 20, pageY = 2, trimLeft = 1, trimTop = 1, trimWidth = 6, trimHeight = 14, quarterTurns = 1), + AtlasPackPlacement(tileIds[2].raw, 0, pageX = 2, pageY = 20, trimLeft = 0, trimTop = 0, trimWidth = 10, trimHeight = 10, quarterTurns = 0), + ) + val items = + tileIds.mapIndexed { tileIndex, tileId -> + AtlasPackItem(tileId.raw, fixture.rasters[tileIndex].width, fixture.rasters[tileIndex].height, fixture.rasters[tileIndex].rgba) + } + val packedPage = composeAtlasPages(intArrayOf(pageSide), intArrayOf(pageSide), items, packPlacements, extrude = 2).single() + val tiles = fixture.model.atlas.tiles.mapIndexed { tileIndex, tile -> tile.copy(placement = atlasPlacementFromPack(packPlacements[tileIndex])) } + val model = fixture.model.copy(atlas = PuppetAtlas(pages = listOf(AtlasPage(pageSide, pageSide)), tiles = tiles)) + + val turned = assertNotNull(model.atlas.tiles[1].placement) + assertEquals(-90f, turned.rotationDegrees, "a packer quarter turn lowers as a -90 degree placement rotation") + val derived = assertNotNull(deriveAtlasTextures(model, fixture.store, false)) + val page = derived.atlases[0] + // The turn sends the trim origin (1, 1) to the packed rect's bottom-left (20, 2 + 6 - 1) and the + // trim's far corner (6, 14) to its top-right (20 + 13, 2). + assertContentEquals(pixelBytes(fixture.rasters[1], 1, 1), pixelBytes(page, 20, 7), "the trim origin lands at the packed rect's bottom-left") + assertContentEquals(pixelBytes(fixture.rasters[1], 6, 14), pixelBytes(page, 33, 2), "the trim's far corner lands at the packed rect's top-right") + assertContentEquals(packedPage.rgba, page.rgba, "a turned pack derives through the packer's own blit, byte for byte") + } + + @Test + fun aPinnedTileDerivesByteIdenticallyToThePackersPage() { + val fixture = packedFixture() + // Tile 1 kept at a hand placement - turned 30 degrees, reduced to 0.75, at (30, 30) - while the + // other two pack around it. + val kept = AtlasPlacement(pageIndex = 0, positionX = 30f, positionY = 30f, scaleX = 0.75f, scaleY = 0.75f, rotationDegrees = 30f) + val items = + tileIds.mapIndexed { tileIndex, tileId -> + val raster = fixture.rasters[tileIndex] + AtlasPackItem( + tileId.raw, + raster.width, + raster.height, + raster.rgba, + fixed = if (tileIndex == 1) AtlasPackFixed(kept.pageIndex, placementAffine(kept)) else null, + ) + } + val options = AtlasPackOptions(maxPageSize = 64) + val result = packAtlas(items, options) + assertEquals(tileIds[1].raw, result.fixed.single().key, "the pinned tile is kept, not packed") + assertEquals(2, result.placements.size, "the other two pack") + val placementByKey = result.placements.associateBy { placement -> placement.key } + val tiles = + fixture.model.atlas.tiles.mapIndexed { tileIndex, tile -> + if (tileIndex == 1) { + tile.copy(placement = kept, pinned = true) + } else { + tile.copy(placement = atlasPlacementFromPack(placementByKey.getValue(tile.id.raw))) + } + } + val model = + fixture.model.copy( + atlas = + PuppetAtlas( + pages = result.pages.map { page -> AtlasPage(page.width, page.height) }, + tiles = tiles, + composition = atlasCompositionOf(options), + ), + ) + + val derived = assertNotNull(deriveAtlasTextures(model, fixture.store, false)) + + assertEquals(result.pages.size, derived.atlases.size) + for (pageIndex in result.pages.indices) { + assertContentEquals(result.pages[pageIndex].rgba, derived.atlases[pageIndex].rgba, "page $pageIndex derives byte-identically, pinned tile included") + } + val trim = assertNotNull(derivedTileTrim(fixture.rasters[1], model.atlas.composition.alphaThreshold)) + val footprint = placementFootprint(kept, trim, reserve = null) + val centerX = ((footprint.left + footprint.right) / 2f).toInt() + val centerY = ((footprint.top + footprint.bottom) / 2f).toInt() + assertEquals(255, alphaAt(derived.atlases[0], centerX, centerY), "the kept tile is painted where its placement says") + } + + @Test + fun theDerivationTrimsAndExtrudesUnderTheAtlasOwnComposition() { + // A 10x10 raster whose one-pixel border is half-transparent: inside the trim at threshold 1, + // trimmed away at threshold 128. + val side = 10 + val bordered = ByteArray(side * side * 4) + for (rowIndex in 0 until side) { + for (columnIndex in 0 until side) { + val onBorder = rowIndex == 0 || columnIndex == 0 || rowIndex == side - 1 || columnIndex == side - 1 + val offset = (rowIndex * side + columnIndex) * 4 + bordered[offset] = 0x50 + bordered[offset + 1] = (rowIndex * 16 + columnIndex).toByte() + bordered[offset + 2] = 0x40 + bordered[offset + 3] = if (onBorder) 0x60 else 0xFF.toByte() + } + } + val tileId = tileIds[0] + val options = AtlasPackOptions(maxPageSize = 32, alphaThreshold = 128, extrude = 0) + val result = packAtlas(listOf(AtlasPackItem(tileId.raw, side, side, bordered)), options) + val packPlacement = result.placements.single() + assertEquals(side - 2, packPlacement.trimWidth, "the border is trimmed away at threshold 128") + val fixture = packedFixture() + val store = SourceArtRasters.fromPng { id -> if (id == tileId) encodeAtlasPng(DecodedImage(bordered, side, side)) else null } + val tiles = listOf(AtlasTile(tileId, tileId.raw, side, side, atlasPlacementFromPack(packPlacement))) + val pages = result.pages.map { page -> AtlasPage(page.width, page.height) } + val underPolicy = fixture.model.copy(atlas = PuppetAtlas(pages, tiles, composition = atlasCompositionOf(options))) + val underDefault = fixture.model.copy(atlas = PuppetAtlas(pages, tiles)) + + val derived = assertNotNull(deriveAtlasTextures(underPolicy, store, false)) + assertContentEquals(result.pages.single().rgba, derived.atlases.single().rgba, "the stored composition reproduces the pack's page") + val defaulted = assertNotNull(deriveAtlasTextures(underDefault, store, false)) + assertFalse( + defaulted.atlases.single().rgba.contentEquals(result.pages.single().rgba), + "the default policy draws the border and an extrusion band, so it is not the pack's page", + ) + } + + @Test + fun aPlacedTileWithNothingOpaqueIsSkippedNotRefused() { + val emptyTile = AtlasTile(AtlasTileId("empty"), "empty", 4, 4, AtlasPlacement(0, 0f, 0f, 1f, 1f, 0f)) + val fixture = packedFixture(extraTiles = listOf(emptyTile to DecodedImage(ByteArray(4 * 4 * 4), 4, 4))) + + val derived = assertNotNull(deriveAtlasTextures(fixture.model, fixture.store, false), "an empty placed tile draws nothing") + + for (pageIndex in fixture.packedPages.indices) { + assertContentEquals(fixture.packedPages[pageIndex].rgba, derived.atlases[pageIndex].rgba, "page $pageIndex is untouched by the empty tile") + } + } + + @Test + fun artThatWillNotDecodeIsNotDerivable() { + val fixture = packedFixture() + val brokenStore = SourceArtRasters.fromPng { ByteArray(4) } + + assertNull(deriveAtlasTextures(fixture.model, brokenStore, false), "undecodable art cannot compose a page") + assertNull(planAtlasDerivation(fixture.model, brokenStore), "the plan refuses before any pixel is composed") + } + + @Test + fun aPlacementNamingAMissingPageIsNotDerivable() { + val fixture = packedFixture() + val original = assertNotNull(fixture.model.atlas.tiles[0].placement) + val stray = fixture.model.withTilePlacement(0, original.copy(pageIndex = fixture.model.atlas.pages.size)) + + assertNull(planAtlasDerivation(stray, fixture.store), "a page the atlas lacks is a document fault, not a placement to resample") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/LayerDrawPlanTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/LayerDrawPlanTest.kt new file mode 100644 index 0000000..c285520 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/LayerDrawPlanTest.kt @@ -0,0 +1,208 @@ +package org.umamo.render + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins which drawables map onto their source artwork and which fall back to the atlas, and that + * working the mapping out costs no decoding. + * + * The mode is best-effort per drawable rather than a clean flip, so the interesting cases are the ways + * a drawable can fail to map: no binding, or a placement that will not invert. Each keeps the drawable + * on the atlas and counts it, because a puppet drawn mostly from its atlas must not look like one drawn + * from its artwork. Art that will not DECODE is deliberately not one of those cases here - the plan + * carries no pixels, so that failure surfaces later, from the batch that tried. + */ +class LayerDrawPlanTest { + private fun meshedDrawable(rawId: String, tileId: String? = null): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2)), + geometryGrid = null, + atlasTileId = tileId?.let { raw -> AtlasTileId(raw) }, + ) + + private fun bareDrawable(rawId: String): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + private fun modelOf(atlas: PuppetAtlas = PuppetAtlas.Empty, vararg drawables: Drawable): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables.toList(), + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + atlas = atlas, + ) + + private fun onePixelPng(): ByteArray = PngCodec.write(RasterImage(1, 1, byteArrayOf(1, 2, 3, 4))) + + /** A tile whose art was never packed, so its drawables' uvs already address it. */ + private fun unpackedTile(rawId: String, width: Int = 8, height: Int = 8): AtlasTile = + AtlasTile(AtlasTileId(rawId), name = "Art", width = width, height = height) + + /** A drawable with usable artwork gets a draw; a layer is costed once, however many share it. */ + @Test + fun resolvedDrawablesShareOneLayerCost() { + val model = + modelOf( + PuppetAtlas(tiles = listOf(unpackedTile("layer0"))), + meshedDrawable("a", "layer0"), + meshedDrawable("b", "layer0"), + ) + val plan = buildLayerDrawPlan(model) + assertEquals(setOf("a", "b"), plan.drawsByDrawableId.keys, "both drawables map") + assertEquals(1, plan.layerByteCostByKey.size, "shared art is costed once, not once per drawable") + assertEquals(8L * 8L * 4L, plan.layerByteCostByKey.getValue("layer0"), "costed from the inventory size, before any decode") + assertEquals(0, plan.unresolvedDrawableCount, "nothing fell back") + } + + /** A drawable with no binding falls back to the atlas and is counted, rather than vanishing. */ + @Test + fun unboundDrawableFallsBackAndIsCounted() { + val model = + modelOf( + PuppetAtlas(tiles = listOf(unpackedTile("layer0"))), + meshedDrawable("a", "layer0"), + meshedDrawable("unbound"), + ) + val plan = buildLayerDrawPlan(model) + assertEquals(setOf("a"), plan.drawsByDrawableId.keys, "only the bound drawable maps") + assertEquals(1, plan.unresolvedDrawableCount, "the unbound one is counted, not hidden") + } + + /** A placement that will not invert leaves its drawable on the atlas. */ + @Test + fun degeneratePlacementFallsBack() { + val degenerate = + unpackedTile("layer0") + .copy(placement = AtlasPlacement(0, 0f, 0f, scaleX = 0f, scaleY = 1f, rotationDegrees = 0f)) + val model = + modelOf( + PuppetAtlas(pages = listOf(AtlasPage(64, 64)), tiles = listOf(degenerate)), + meshedDrawable("a", "layer0"), + ) + val plan = buildLayerDrawPlan(model) + assertTrue(plan.drawsByDrawableId.isEmpty(), "a mapping that cannot be formed draws nothing from artwork") + assertEquals(1, plan.unresolvedDrawableCount, "and the drawable is counted") + } + + /** + * Building the mapping decodes nothing at all. + * + * The whole point of the split: a document referencing hundreds of layers must be able to work out + * what maps where without paying for the pixels, or switching display mode would cost gigabytes + * before anything appeared. + */ + @Test + fun buildingThePlanDecodesNothing() { + var decodes = 0 + SourceArtRasters.fromPng { _ -> + decodes++ + onePixelPng() + } + val plan = + buildLayerDrawPlan( + modelOf(PuppetAtlas(tiles = listOf(unpackedTile("layer0"))), meshedDrawable("a", "layer0")), + ) + assertEquals(0, decodes, "the mapping is worked out from the inventory, never from the pixels") + assertNotNull(plan.drawsByDrawableId["a"], "and the drawable still maps") + } + + /** + * Art that will not decode is attributed to every drawable over it. + * + * The plan cannot know this - it decodes nothing - so the producer discovers it from a delivery and + * asks the plan who was affected. That is what keeps the reported gap counting drawables with no + * usable artwork, rather than layers. + */ + @Test + fun undecodableLayersMapBackToTheirDrawables() { + val model = + modelOf( + PuppetAtlas(tiles = listOf(unpackedTile("layer0"), unpackedTile("layer1"))), + meshedDrawable("a", "layer0"), + meshedDrawable("b", "layer0"), + meshedDrawable("c", "layer1"), + ) + val plan = buildLayerDrawPlan(model) + assertEquals(setOf("a", "b"), plan.drawableIdsUsing(setOf("layer0")), "both users of the failed art are named") + assertEquals(emptySet(), plan.drawableIdsUsing(emptySet()), "and nothing is named when nothing failed") + } + + /** Unmeshed drawables are not counted: they draw nothing either way. */ + @Test + fun unmeshedDrawablesAreNotCounted() { + val plan = buildLayerDrawPlan(modelOf(PuppetAtlas(tiles = listOf(unpackedTile("layer0"))), bareDrawable("c"))) + assertEquals(0, plan.unresolvedDrawableCount, "a drawable with no mesh is not a fallback") + } + + /** An empty atlas means the packed pages, with no work done at all. */ + @Test + fun anEmptyAtlasYieldsThePackedPages() { + val plan = buildLayerDrawPlan(modelOf(PuppetAtlas.Empty, meshedDrawable("a"))) + assertTrue(plan.isEmpty, "no artwork means displaying from the atlas") + } + + /** + * A session-created duplicate finds its art natively. + * + * The tile is a field on the drawable, so a copy carries it like every other field - where the atlas + * page still resolves through textureSourceId, because THAT map is keyed by the source format's own + * drawable ids and a fresh duplicate has no entry in it. + */ + @Test + fun aDuplicateCarriesItsOwnTileBinding() { + val model = + modelOf( + PuppetAtlas(tiles = listOf(unpackedTile("layer0"))), + meshedDrawable("a", "layer0"), + meshedDrawable("a copy", "layer0").copy(textureSourceId = DrawableId("a")), + ) + val plan = buildLayerDrawPlan(model) + assertNotNull(plan.drawsByDrawableId["a copy"], "the duplicate resolves its own tile") + assertEquals(0, plan.unresolvedDrawableCount, "so it is not a fallback") + } + + /** The uncached decode shares nothing with the caching one, so it is safe off the owning thread. */ + @Test + fun uncachedDecodeSharesNothing() { + val tileId = AtlasTileId("layer0") + val store = SourceArtRasters.fromPng { requested -> if (requested == tileId) onePixelPng() else null } + val cached = store.rasterFor(tileId) + val fresh = store.decodeRaster(tileId) + assertNotNull(cached, "the caching path decodes") + assertNotNull(fresh, "the uncached path decodes") + assertTrue(cached !== fresh, "the uncached path owns its result rather than sharing the cache's") + assertNull(store.decodeRaster(AtlasTileId("missing")), "an unknown tile decodes to nothing") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/Moc3HiddenDrawableSpaceTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/Moc3HiddenDrawableSpaceTest.kt new file mode 100644 index 0000000..34e9c73 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/Moc3HiddenDrawableSpaceTest.kt @@ -0,0 +1,182 @@ +package org.umamo.render + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The canvas-space conversion's two halves agree about WHICH POSE a hidden drawable is mapped at. + * + * A drawable whose keyform axis does not bracket its parameter's default - the toggle-part authoring + * pattern - is absent from the raw default pose, so [restMeshesToCanvasSpace] maps it forward through a + * second pose with that parameter clamped into its axis's key range. The export's inverse has to use + * the same clamped pose, or it undoes a transform that was never applied. + * + * With the two halves disagreeing, this drawable's chain does not resolve at the raw default at all and + * the seam returns null - which the export turns into a notice and writes the mesh as authored, in the + * wrong space. The rotation parent is what makes the poses distinguishable: it is keyed so its scale + * differs across the toggle's range, so agreeing on the pose is load-bearing rather than incidental. + */ +class Moc3HiddenDrawableSpaceTest { + private val toggle = ParameterId("Toggle") + private val drawableId = DrawableId("M") + private val deformerId = DeformerId("R") + + /** The parent-space rest positions the drawable is authored with. */ + private val parentLocal = floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f) + + /** + * A rotation deformer whose scale differs across the toggle's key range. + * + * Keys at 0.5 and 1.0 over a parameter defaulting to 0: the raw default sits BELOW the span, which + * is what hides the child, and the clamped pose lands on 0.5. + * + * @return Deformer.Rotation The parent. + */ + private fun togglingRotation(): Deformer.Rotation = + Deformer.Rotation( + deformerId, + "R", + null, + null, + 0f, + KeyformGrid( + listOf(KeyformAxis(toggle, floatArrayOf(0.5f, 1f))), + listOf( + KeyformCell(intArrayOf(0), RotationPivotForm(5f, 5f, 90f, 2f)), + KeyformCell(intArrayOf(1), RotationPivotForm(5f, 5f, 90f, 4f)), + ), + ), + ) + + /** + * A model whose only drawable is hidden at the raw default pose. + * + * @return PuppetModel The model. + */ + private fun hiddenAtDefaultModel(): PuppetModel { + val drawable = + Drawable( + id = drawableId, + name = "M", + parentDeformerId = deformerId, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(parentLocal, FloatArray(parentLocal.size), intArrayOf(0, 1, 2)), + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(toggle, floatArrayOf(0.5f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(parentLocal.size))), + KeyformCell(intArrayOf(1), MeshDeltaForm(FloatArray(parentLocal.size))), + ), + ), + ) + return PuppetModel( + parameters = listOf(Parameter(toggle, "Toggle", min = 0f, max = 1f, default = 0f)), + parts = emptyList(), + deformers = listOf(togglingRotation()), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawableId)), + rootPartId = null, + ) + } + + @Test + fun aHiddenDrawableSurvivesTheCanvasSpaceRoundTrip() { + val model = hiddenAtDefaultModel() + // Forward: the import's pass, which rescues this drawable through the clamped pose. + val canvasSpace = restMeshesToCanvasSpace(model) + val canvasMesh = assertNotNull(canvasSpace.drawables.single().mesh) + assertTrue( + canvasMesh.positions.toList() != parentLocal.toList(), + "the forward pass must actually have moved the mesh, or this proves nothing", + ) + + // Back: the export's seam. It has to pick the same pose the forward pass used. + val recovered = assertNotNull(canvasToParentSpaceFor(canvasSpace)(drawableId, canvasMesh.positions)) + + for (index in parentLocal.indices) { + val drift = abs(recovered[index] - parentLocal[index]) + assertTrue( + drift < 1e-2f, + "coordinate $index came back as ${recovered[index]}, authored ${parentLocal[index]} - " + + "the inverse used a different pose than the forward pass", + ) + } + } + + /** + * UMA / CMO3 unkeyed warp children already store lattice UV in the rest mesh. Treating that as + * canvas and inverting through the warp is the MouthCircle corruption: UV (~0..1) becomes garbage + * outside the lattice and the mesh flies off when the parent opens. + */ + @Test + fun anAlreadyParentLocalWarpChildIsNotDoubleTransformed() { + val warpId = DeformerId("W") + val pose = ParameterId("Pose") + // Canvas-space lattice; child rest is parent-local UV - the UMA MouthCircle convention. + val lattice = floatArrayOf(100f, 200f, 300f, 200f, 100f, 400f, 300f, 400f) + val warp = + Deformer.Warp( + warpId, + "W", + null, + null, + 1, + 1, + true, + KeyformGrid( + listOf(KeyformAxis(pose, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(lattice))), + ), + ) + val uvRest = floatArrayOf(0.25f, 0.25f, 0.75f, 0.25f, 0.75f, 0.75f, 0.25f, 0.75f) + val drawable = + Drawable( + id = drawableId, + name = "MouthCircle", + parentDeformerId = warpId, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(uvRest, FloatArray(uvRest.size), intArrayOf(0, 1, 2)), + geometryGrid = null, + ) + val model = + PuppetModel( + parameters = listOf(Parameter(pose, "Pose", min = 0f, max = 1f, default = 0f)), + parts = emptyList(), + deformers = listOf(warp), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawableId)), + rootPartId = null, + ) + + val recovered = assertNotNull(canvasToParentSpaceFor(model)(drawableId, uvRest)) + for (index in uvRest.indices) { + val drift = abs(recovered[index] - uvRest[index]) + assertTrue( + drift < 1e-4f, + "coordinate $index was rewritten from parent-local ${uvRest[index]} to ${recovered[index]} - " + + "the seam double-transformed an already-local rest mesh", + ) + } + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/Moc3RestMeshTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/Moc3RestMeshTest.kt new file mode 100644 index 0000000..42640cd --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/Moc3RestMeshTest.kt @@ -0,0 +1,132 @@ +package org.umamo.render + +import org.umamo.runtime.keyform.fanOutMesh +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Unit tests for [restMeshesToCanvasSpace] on a tiny synthetic model. The rebase rewrites ONLY the + * geometry (base positions and keyform/blend-shape deltas); every non-positional keyform channel must + * ride along unchanged. Pins the modelA hologram regression, where the rebase rebuilt each MeshForm + * and silently dropped its multiply/screen colours, stripping the per-drawable tints off every + * MOC3-imported model (the hologram overlay quad lost the blue that its HardLight blend needed). + */ +class Moc3RestMeshTest { + private val paramA = ParameterId("A") + private val blueMultiply = ColorRgb(0.1f, 0.7f, 1f) + private val warmScreen = ColorRgb(0.2f, 0.1f, 0f) + + private fun modelWithChannelledKeyforms(): PuppetModel { + // Built bundled and fanned out, so the fixture matches what an importer actually produces. + val fanned = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshForm(FloatArray(6), drawOrder = 400f, opacity = 0.25f, multiplyColor = blueMultiply, screenColor = warmScreen)), + KeyformCell(intArrayOf(1), MeshForm(FloatArray(6) { 2f }, drawOrder = 600f, opacity = 0.75f, multiplyColor = blueMultiply, screenColor = warmScreen)), + ), + ).fanOutMesh() + val drawable = + Drawable( + id = DrawableId("quad"), + name = "quad", + parentDeformerId = null, + blendMode = BlendMode.HardLight, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2)), + geometryGrid = fanned.geometry, + channelGrids = fanned.channels, + blendShapes = + listOf( + BlendShapeBinding( + parameterId = paramA, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, MeshForm(FloatArray(6) { 1f }, drawOrder = 500f, opacity = 0.5f, multiplyColor = blueMultiply, screenColor = warmScreen)), + ), + ), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", 0f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + } + + /** + * The rebase moves geometry only; every channel track must come through untouched. + * + * Since the channel split this is structural - the tracks are a separate field the rebase never + * writes - but it is asserted anyway, because the property is what the rebase is allowed to do, not + * an artefact of how it happens to be written today. + */ + @Test + fun rebasePreservesEveryNonPositionalKeyformChannel() { + val rebased = restMeshesToCanvasSpace(modelWithChannelledKeyforms()) + val drawable = rebased.drawables.single() + assertEquals(2, drawable.geometryGrid!!.cells.size) + val channels = drawable.channelGrids + + fun scalars(channel: FormChannel): List = + channels[channel]!!.cells.map { cell -> (cell.form as ChannelValue.Scalar).value } + + fun colors(channel: FormChannel): List = + channels[channel]!!.cells.map { cell -> (cell.form as ChannelValue.Color).color } + assertEquals(listOf(400f, 600f), scalars(FormChannel.DRAW_ORDER)) + assertEquals(listOf(0.25f, 0.75f), scalars(FormChannel.OPACITY)) + assertEquals(listOf(blueMultiply, blueMultiply), colors(FormChannel.MULTIPLY_COLOR), "keyform multiply color must survive the rebase") + assertEquals(listOf(warmScreen, warmScreen), colors(FormChannel.SCREEN_COLOR), "keyform screen color must survive the rebase") + val blendForm = drawable.blendShapes.single().forms[1]!! + assertEquals(500f, blendForm.drawOrder) + assertEquals(0.5f, blendForm.opacity) + assertEquals(blueMultiply, blendForm.multiplyColor, "blend-shape multiply color must survive the rebase") + assertEquals(warmScreen, blendForm.screenColor, "blend-shape screen color must survive the rebase") + } + + @Test + fun rebaseKeepsAbsoluteKeyformGeometryIntact() { + val original = modelWithChannelledKeyforms() + val rebased = restMeshesToCanvasSpace(original) + val originalDrawable = original.drawables.single() + val rebasedDrawable = rebased.drawables.single() + // base + delta must reconstruct the same absolute positions per cell, whatever base the + // rebase chose - that invariance is the whole contract of the rewrite. + for (cellIndex in 0 until 2) { + val originalForm = originalDrawable.geometryGrid!!.cells[cellIndex].form + val rebasedForm = rebasedDrawable.geometryGrid!!.cells[cellIndex].form + for (coordIndex in 0 until 6) { + assertEquals( + originalDrawable.mesh!!.positions[coordIndex] + originalForm.positionDeltas[coordIndex], + rebasedDrawable.mesh!!.positions[coordIndex] + rebasedForm.positionDeltas[coordIndex], + absoluteTolerance = 1e-4f, + ) + } + } + } + + private fun assertEquals(expected: Float, actual: Float, absoluteTolerance: Float) { + kotlin.test.assertTrue( + kotlin.math.abs(expected - actual) <= absoluteTolerance, + "expected $expected, got $actual", + ) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/PuppetExportTexturesTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/PuppetExportTexturesTest.kt new file mode 100644 index 0000000..b9c7e43 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/PuppetExportTexturesTest.kt @@ -0,0 +1,99 @@ +package org.umamo.render + +import org.umamo.format.png.PngCodec +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** + * The export-side texture helpers, on hand-built inputs. + * + * Both live here rather than in the app layer because they read [PuppetTextures] and touch nothing + * else - which is also what makes them reachable from commonTest at all. + */ +class PuppetExportTexturesTest { + /** + * A drawable with the given id and page binding. + * + * @param String id The drawable id. + * @param Int page Its atlas page, or -1 for the unbound sentinel. + * @return Drawable The drawable. + */ + private fun drawable(id: String, page: Int = -1): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + texturePage = page, + ) + + /** + * A model over the given drawables. + * + * @param Drawable drawables The drawables. + * @return PuppetModel The model. + */ + private fun modelOf(vararg drawables: Drawable): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables.toList(), + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + + /** + * A texture set binding the given drawable ids to pages. + * + * @param Pair bindings Drawable id to page index. + * @return PuppetTextures The set. + */ + private fun texturesBinding(vararg bindings: Pair): PuppetTextures = + PuppetTextures(emptyList(), bindings.toMap(), premultipliedAlpha = false) + + @Test + fun aCmo3OriginDrawableGetsItsPageFromTheDecodedSet() { + // The case the helper exists for: a CMO3 has no page index of its own, so every drawable arrives + // on the -1 sentinel that the moc lowering would otherwise clamp to page 0 - pointing a + // multi-page rig at one atlas. + val bound = withTexturePagesFrom(modelOf(drawable("A"), drawable("B")), texturesBinding("A" to 0, "B" to 2)) + assertEquals(listOf(0, 2), bound.drawables.map { it.texturePage }) + } + + @Test + fun anUnmappedDrawableKeepsWhateverPageItHad() { + val bound = withTexturePagesFrom(modelOf(drawable("A", page = 3), drawable("B")), texturesBinding("A" to 3)) + assertEquals(listOf(3, -1), bound.drawables.map { it.texturePage }, "B has no binding to take") + } + + @Test + fun aModelWithNothingToMoveIsReturnedUnchanged() { + // Identity, not equality: the caller re-exports this straight into the lowering, and an + // unnecessary copy would defeat every downstream identity check on the model. + val model = modelOf(drawable("A", page = 1)) + assertSame(model, withTexturePagesFrom(model, texturesBinding("A" to 1))) + } + + @Test + fun anEncodedAtlasPageRoundTripsThroughThePngCodec() { + val page = DecodedImage(ByteArray(5 * 7 * 4) { index -> index.toByte() }, width = 5, height = 7) + val decoded = PngCodec.read(encodeAtlasPng(page)) + assertEquals(5, decoded.width) + assertEquals(7, decoded.height) + assertEquals(page.rgba.toList(), decoded.rgba.toList(), "the pixels must survive the re-encode") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/PuppetTexturesTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/PuppetTexturesTest.kt new file mode 100644 index 0000000..eab5529 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/PuppetTexturesTest.kt @@ -0,0 +1,80 @@ +package org.umamo.render + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Contract checks for [buildPuppetTextures], the format-agnostic core both ingest paths end at, and + * for the two opposite [UndecodablePagePolicy] answers layered on it: MOC3 fails the whole build so a + * broken family surfaces as an import error, CMO3 drops the page and keeps the rest of the rig + * openable. Synthetic pixels only - no corpus dependency, so this runs on every target. + */ +class PuppetTexturesTest { + private fun pngOfSize(width: Int, height: Int): ByteArray = + PngCodec.write(RasterImage(width = width, height = height, rgba = ByteArray(width * height * 4) { -1 })) + + private val onePixelPng: ByteArray = pngOfSize(1, 1) + private val notAPng: ByteArray = "not a png".encodeToByteArray() + + @Test + fun decodesPagesAndKeepsTheIndexMap() { + val textures = buildPuppetTextures(listOf(onePixelPng), mapOf("ArtMesh1" to 0)) + assertNotNull(textures) + assertEquals(1, textures.atlases.size, "decoded page count") + assertEquals(1, textures.atlases[0].width, "page width") + assertEquals(0, textures.atlasIndexByDrawableId["ArtMesh1"], "page index for the drawable") + } + + @Test + fun undecodablePageFailsTheBuild() { + assertNull(buildPuppetTextures(listOf(notAPng), mapOf("ArtMesh1" to 0))) + } + + @Test + fun outOfRangePageIndexFailsTheBuild() { + assertNull(buildPuppetTextures(listOf(onePixelPng), mapOf("ArtMesh1" to 1)), "index past the page list") + assertNull(buildPuppetTextures(listOf(onePixelPng), mapOf("ArtMesh1" to -1)), "negative index") + } + + @Test + fun skipPolicyDropsOnlyTheDrawablesOnTheBrokenPage() { + val textures = + buildPuppetTextures( + listOf(pngOfSize(1, 1), notAPng, pngOfSize(2, 2)), + mapOf("ArtMeshFirst" to 0, "ArtMeshBroken" to 1, "ArtMeshLast" to 2), + undecodablePage = UndecodablePagePolicy.Skip, + ) + assertNotNull(textures, "Skip never fails the build") + assertEquals(2, textures.atlases.size, "the undecodable page is dropped") + assertNull(textures.atlasIndexByDrawableId["ArtMeshBroken"], "its drawable is unmapped, not left dangling") + assertEquals(0, textures.atlasIndexByDrawableId["ArtMeshFirst"], "an earlier page keeps its slot") + // The renumbering is the whole point: page 2 became page 1 when page 1 went away, and a stale 2 + // here would index past the list and crash PuppetRenderer's direct lookup at first frame. + assertEquals(1, textures.atlasIndexByDrawableId["ArtMeshLast"], "a later page is renumbered down") + assertEquals(2, textures.atlases[1].width, "the renumbered slot holds the page it claims to") + } + + @Test + fun skipPolicyToleratesAnOutOfRangeIndex() { + val textures = + buildPuppetTextures( + listOf(onePixelPng), + mapOf("ArtMeshOk" to 0, "ArtMeshStale" to 7), + undecodablePage = UndecodablePagePolicy.Skip, + ) + assertNotNull(textures) + assertEquals(0, textures.atlasIndexByDrawableId["ArtMeshOk"]) + assertNull(textures.atlasIndexByDrawableId["ArtMeshStale"], "an unresolvable page number drops the drawable") + } + + @Test + fun premultipliedFlagIsCarriedThrough() { + val textures = buildPuppetTextures(listOf(onePixelPng), mapOf("ArtMesh1" to 0), premultipliedAlpha = true) + assertNotNull(textures) + assertEquals(true, textures.premultipliedAlpha) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/SourceArtRastersTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/SourceArtRastersTest.kt new file mode 100644 index 0000000..c4c4936 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/SourceArtRastersTest.kt @@ -0,0 +1,314 @@ +package org.umamo.render + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableLayerBinding +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.atlasPixelOf +import org.umamo.runtime.model.identityUvAffine +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.layerPixelOf +import org.umamo.runtime.model.layerUvAffineOf +import org.umamo.runtime.model.layerUvsFromAtlasUvs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the source-layer store and the atlas-placement recovery math: the TRS round-trip across every + * shape the corpus contains (translation, quarter turns, free angles, non-unit and mirroring scale, + * fractional origins), the uv mapping in both the packed and unpacked cases, and the store's + * decode-once caching including its remembered failures. + * + * The recovery convention this locks - forward is `atlas = R(angle) . S . layer + position` in + * page pixels with y running down - is cross-checked against real files by + * Cmo3AtlasIngestCorpusTest (`:interop`), which composes it against the format's own + * atlas-to-canvas affine. + */ +class SourceArtRastersTest { + private fun placementOf( + positionX: Float = 0f, + positionY: Float = 0f, + scaleX: Float = 1f, + scaleY: Float = 1f, + rotationDegrees: Float = 0f, + ): AtlasPlacement = + AtlasPlacement( + pageIndex = 0, + positionX = positionX, + positionY = positionY, + scaleX = scaleX, + scaleY = scaleY, + rotationDegrees = rotationDegrees, + ) + + private fun assertRoundTrips(placement: AtlasPlacement, layerX: Float, layerY: Float, message: String) { + val atlasPixel = atlasPixelOf(placement, layerX, layerY) + val recovered = layerPixelOf(placement, atlasPixel[0], atlasPixel[1]) + assertNotNull(recovered, "$message: the inverse must resolve") + assertEquals(layerX, recovered[0], 1e-3f, "$message: x") + assertEquals(layerY, recovered[1], 1e-3f, "$message: y") + } + + /** Every placement shape the corpus contains inverts back to the point it started from. */ + @Test + fun placementInversionRoundTripsEveryShape() { + assertRoundTrips(placementOf(), 12f, 34f, "identity") + assertRoundTrips(placementOf(positionX = 640f, positionY = 128f), 12f, 34f, "translation") + assertRoundTrips(placementOf(positionX = 6742.03f, positionY = 6710.03f), 12f, 34f, "fractional origin") + assertRoundTrips(placementOf(rotationDegrees = 90f), 12f, 34f, "quarter turn") + assertRoundTrips(placementOf(rotationDegrees = 180f, positionX = 50f), 12f, 34f, "half turn") + assertRoundTrips(placementOf(rotationDegrees = 37.5f, positionY = 9f), 12f, 34f, "free angle") + assertRoundTrips(placementOf(scaleX = 0.8588867f, scaleY = 0.8588867f), 12f, 34f, "uniform scale") + assertRoundTrips(placementOf(scaleX = 2f, scaleY = 0.5f), 12f, 34f, "anisotropic scale") + assertRoundTrips(placementOf(scaleX = -1f), 12f, 34f, "horizontal mirror") + assertRoundTrips(placementOf(scaleY = -1f), 12f, 34f, "vertical mirror") + assertRoundTrips( + placementOf(positionX = 292.0f, positionY = 409.0863f, scaleX = 1.16431f, scaleY = 1.16431f, rotationDegrees = 90f), + 12f, + 34f, + "rotated, scaled and offset together", + ) + } + + /** + * The forward transform's orientation, stated explicitly so a sign flip cannot hide behind a + * round-trip (which passes for either convention). A 90 degree rotation with y running DOWN + * carries the +x axis onto +y. + */ + @Test + fun quarterTurnCarriesTheXAxisOntoY() { + val turned = atlasPixelOf(placementOf(rotationDegrees = 90f), 10f, 0f) + assertEquals(0f, turned[0], 1e-3f, "a quarter turn zeroes the x component") + assertEquals(10f, turned[1], 1e-3f, "a quarter turn carries +x onto +y") + } + + /** A degenerate placement (a collapsed axis) has no inverse and must report that, not divide by zero. */ + @Test + fun degeneratePlacementHasNoInverse() { + assertNull(layerPixelOf(placementOf(scaleX = 0f), 5f, 5f), "a zero x scale cannot be inverted") + assertNull(layerPixelOf(placementOf(scaleY = 0f), 5f, 5f), "a zero y scale cannot be inverted") + } + + /** A packed drawable's uvs scale up to page pixels, invert, and scale down by the layer's own size. */ + @Test + fun packedUvsMapIntoTheLayerFrame() { + // A 64x64 layer packed unrotated at (128, 256) on a 512x512 page: the layer's own corners land + // at page (128, 256) and (192, 320), i.e. uv (0.25, 0.5) and (0.375, 0.625). + val binding = + DrawableLayerBinding( + layerKey = "layer", + placement = placementOf(positionX = 128f, positionY = 256f), + pageWidth = 512, + pageHeight = 512, + ) + val layerUvs = + layerUvsFromAtlasUvs(floatArrayOf(0.25f, 0.5f, 0.375f, 0.625f), binding, layerWidth = 64, layerHeight = 64) + assertNotNull(layerUvs, "a well-formed binding maps") + assertEquals(0f, layerUvs[0], 1e-4f, "the layer's own origin maps to uv 0") + assertEquals(0f, layerUvs[1], 1e-4f, "the layer's own origin maps to uv 0") + assertEquals(1f, layerUvs[2], 1e-4f, "the layer's far corner maps to uv 1") + assertEquals(1f, layerUvs[3], 1e-4f, "the layer's far corner maps to uv 1") + } + + /** + * An unpacked drawable's uvs already address its layer image (ingest inverted the logical-frame + * affine at import), so recovery must leave them alone - applying a placement would double-transform. + */ + @Test + fun unpackedUvsPassThroughUntouched() { + val binding = DrawableLayerBinding(layerKey = "layer", placement = null, pageWidth = 0, pageHeight = 0) + val atlasUvs = floatArrayOf(0.1f, 0.2f, 0.9f, 0.8f) + val layerUvs = layerUvsFromAtlasUvs(atlasUvs, binding, layerWidth = 64, layerHeight = 64) + assertNotNull(layerUvs, "an unpacked binding maps") + assertTrue(layerUvs.contentEquals(atlasUvs), "unpacked uvs must survive verbatim") + } + + /** + * The uv affine and its inverse are the round trip a layer-view EDIT depends on: a coordinate + * authored over the art must reach the stored atlas frame and back unchanged. Checked over every + * placement shape the corpus contains, since a rotation or a mirror is exactly where an inverse + * goes wrong quietly. + */ + @Test + fun uvAffineRoundTripsThroughItsInverse() { + val shapes = + listOf( + "identity" to placementOf(), + "translation" to placementOf(positionX = 640f, positionY = 128f), + "fractional origin" to placementOf(positionX = 6742.03f, positionY = 6710.03f), + "quarter turn" to placementOf(rotationDegrees = 90f), + "free angle" to placementOf(rotationDegrees = 37.5f, positionY = 9f), + "uniform scale" to placementOf(scaleX = 0.8588867f, scaleY = 0.8588867f), + "anisotropic scale" to placementOf(scaleX = 2f, scaleY = 0.5f), + "horizontal mirror" to placementOf(scaleX = -1f), + "rotated, scaled and offset" to + placementOf(positionX = 292f, positionY = 409.0863f, scaleX = 1.16431f, scaleY = 1.16431f, rotationDegrees = 90f), + ) + val storedUvs = floatArrayOf(0.1f, 0.2f, 0.9f, 0.8f, 0.5f, 0.5f) + for ((label, placement) in shapes) { + val binding = DrawableLayerBinding("layer", placement, pageWidth = 2048, pageHeight = 1024) + val toLayer = layerUvAffineOf(binding, layerWidth = 576, layerHeight = 646) + assertNotNull(toLayer, "$label: the layer affine resolves") + val toStored = invertUvAffine(toLayer) + assertNotNull(toStored, "$label: the affine inverts") + val roundTripped = applyUvAffine(applyUvAffine(storedUvs, toLayer), toStored) + for (componentIndex in storedUvs.indices) { + assertEquals(storedUvs[componentIndex], roundTripped[componentIndex], 1e-4f, "$label: component $componentIndex") + } + } + } + + /** An unpacked drawable's mapping is the identity in BOTH directions, not a placement inverse. */ + @Test + fun unpackedBindingYieldsTheIdentityAffine() { + val binding = DrawableLayerBinding("layer", placement = null, pageWidth = 0, pageHeight = 0) + val toLayer = layerUvAffineOf(binding, layerWidth = 64, layerHeight = 64) + assertNotNull(toLayer, "an unpacked binding still maps") + assertTrue(toLayer.contentEquals(identityUvAffine()), "an unpacked mapping is the identity") + val toStored = invertUvAffine(toLayer) + assertNotNull(toStored, "the identity inverts") + val storedUvs = floatArrayOf(0.1f, 0.2f, 0.9f, 0.8f) + assertTrue(applyUvAffine(storedUvs, toStored).contentEquals(storedUvs), "and changes nothing coming back") + } + + /** A mapping that cannot be formed reports it rather than producing a wrong one. */ + @Test + fun degenerateMappingsResolveToNothing() { + val degenerate = DrawableLayerBinding("layer", placementOf(scaleX = 0f), pageWidth = 512, pageHeight = 512) + assertNull(layerUvAffineOf(degenerate, 64, 64), "a collapsed placement axis has no mapping") + val sane = DrawableLayerBinding("layer", placementOf(), pageWidth = 512, pageHeight = 512) + assertNull(layerUvAffineOf(sane, layerWidth = 0, layerHeight = 64), "a zero-width layer has no mapping") + assertNull(invertUvAffine(floatArrayOf(0f, 0f, 5f, 0f, 0f, 5f)), "a collapsed affine does not invert") + } + + /** A layer with no usable size cannot host a mapping; report it rather than dividing by zero. */ + @Test + fun zeroSizedLayerHasNoMapping() { + val binding = + DrawableLayerBinding(layerKey = "layer", placement = placementOf(), pageWidth = 512, pageHeight = 512) + assertNull(layerUvsFromAtlasUvs(floatArrayOf(0f, 0f), binding, layerWidth = 0, layerHeight = 64), "zero width") + assertNull(layerUvsFromAtlasUvs(floatArrayOf(0f, 0f), binding, layerWidth = 64, layerHeight = 0), "zero height") + } + + private fun onePixelPng(): ByteArray = PngCodec.write(RasterImage(1, 1, byteArrayOf(1, 2, 3, 4))) + + /** The store decodes a tile once and serves the same instance afterwards. */ + @Test + fun rasterDecodesOnceAndCaches() { + var readCount = 0 + val store = + SourceArtRasters.fromPng { _ -> + readCount++ + onePixelPng() + } + val first = store.rasterFor(AtlasTileId("a")) + val second = store.rasterFor(AtlasTileId("a")) + assertNotNull(first, "the tile decodes") + assertSame(first, second, "a decoded tile is cached, not re-decoded") + assertEquals(1, readCount, "the byte supplier is consulted once") + } + + /** A failed decode is remembered as a failure, not retried on every request. */ + @Test + fun rasterRemembersFailures() { + var readCount = 0 + val store = + SourceArtRasters.fromPng { _ -> + readCount++ + byteArrayOf(0, 1, 2) + } + assertNull(store.rasterFor(AtlasTileId("a")), "undecodable bytes yield no raster") + assertNull(store.rasterFor(AtlasTileId("a")), "still no raster on a second request") + assertEquals(1, readCount, "a remembered failure is not retried") + } + + /** + * A store over already-decoded rasters (an artwork-origin document) hands out the SAME instance from + * its cached and its uncached read: the renderer's texture cache and the viewport's freshness test + * compare decoded images by identity, so a fresh wrapper per call would read as a changed image. + */ + @Test + fun aDecodedStoreSharesOneInstanceAcrossBothReads() { + val image = DecodedImage(byteArrayOf(1, 2, 3, 4), 1, 1) + val store = SourceArtRasters { requested -> if (requested == AtlasTileId("a")) image else null } + assertSame(image, store.rasterFor(AtlasTileId("a")), "the cached read hands out the supplied instance") + assertSame(image, store.decodeRaster(AtlasTileId("a")), "so does the uncached read") + assertNull(store.decodeRaster(AtlasTileId("b")), "an unknown tile has no raster either way") + } + + /** + * Rasters added after the store was built (artwork brought into an open document) read from both + * twins and never shadow what the decoder already answers for other tiles. + */ + @Test + fun addedRastersReadFromBothTwinsWithoutShadowingTheDecoder() { + val decoded = DecodedImage(byteArrayOf(1, 2, 3, 4), 1, 1) + val store = SourceArtRasters { requested -> if (requested == AtlasTileId("base")) decoded else null } + val added = DecodedImage(byteArrayOf(5, 6, 7, 8), 1, 1) + store.addDecoded(mapOf(AtlasTileId("new") to added)) + + assertSame(added, store.decodeRaster(AtlasTileId("new")), "the uncached read sees the added raster") + assertSame(added, store.rasterFor(AtlasTileId("new")), "so does the cached one") + assertSame(decoded, store.rasterFor(AtlasTileId("base")), "the decoder's own tiles are untouched") + assertNull(store.rasterFor(AtlasTileId("missing")), "an unknown tile is still unknown") + } + + /** + * A raster added for a tile the cached read already answered replaces that answer: a reload's + * replacement id is minted against the model as it stands, so reload, undo, reload reuses the id + * with new pixels, and the cache must not keep handing out the first reload's. + */ + @Test + fun anAddedRasterReplacesACachedOneForTheSameTile() { + val first = DecodedImage(byteArrayOf(1, 2, 3, 4), 1, 1) + val second = DecodedImage(byteArrayOf(5, 6, 7, 8), 1, 1) + val store = SourceArtRasters { null } + val reused = AtlasTileId("art-0/lyid:1~1") + + store.addDecoded(mapOf(reused to first)) + assertSame(first, store.rasterFor(reused), "the cached read takes the first reload's pixels") + store.addDecoded(mapOf(reused to second)) + assertSame(second, store.rasterFor(reused), "and the second reload's once they replace them") + assertSame(second, store.decodeRaster(reused), "the same instance from the uncached read") + + // A tile the cache learned as absent is likewise superseded by an added raster. + val late = AtlasTileId("late") + assertNull(store.rasterFor(late)) + store.addDecoded(mapOf(late to first)) + assertSame(first, store.rasterFor(late), "a remembered miss does not outlive the raster's arrival") + } + + /** + * Two stores never share what was added to one of them. + * + * Documents hand their own store to every artwork import, which decodes into it - so a store shared + * between documents would read one document's art back out under the next document's tile ids. + */ + @Test + fun addedRastersStayInTheStoreTheyWereAddedTo() { + val tileId = AtlasTileId("tile-1") + val store = SourceArtRasters { null } + val other = SourceArtRasters { null } + + store.addDecoded(mapOf(tileId to DecodedImage(ByteArray(4) { 0xFF.toByte() }, 1, 1))) + + assertNotNull(store.rasterFor(tileId), "the store it was added to has it") + assertNull(other.rasterFor(tileId), "another document's store does not") + } + + /** A tile the supplier has no bytes for decodes to nothing, and a store over no pixels has none at all. */ + @Test + fun aTileWithoutBytesDecodesToNothing() { + val known = AtlasTileId("a") + val store = SourceArtRasters.fromPng { requested -> if (requested == known) onePixelPng() else null } + assertNotNull(store.rasterFor(known), "a known tile decodes") + assertNull(store.rasterFor(AtlasTileId("missing")), "an unknown tile has no bytes") + assertNull(SourceArtRasters { null }.rasterFor(known), "a store over no pixels at all has no rasters") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/ViewportCameraTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/ViewportCameraTest.kt new file mode 100644 index 0000000..2763b9b --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/ViewportCameraTest.kt @@ -0,0 +1,143 @@ +package org.umamo.render + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Exercises the pure viewport-camera maths (no GL): fit framing, the world-to-NDC affine, cursor-pinned + * zoom, grab pan, actual-size, and the zoom clamps. These are the invariants the interactive navigation + * relies on, isolated so they verify without a render context. + */ +class ViewportCameraTest { + private val tolerance = 1e-3f + + /** Maps a world point to a screen pixel (top-left origin) through a camera, for round-trip assertions. */ + private fun worldToScreen(camera: ViewportCamera, worldX: Float, worldZ: Float, width: Int, height: Int): Pair { + val ndc = camera.worldToNdc(width, height) + val ndcX = worldX * ndc[0] + ndc[2] + val ndcY = worldZ * ndc[1] + ndc[3] + return Pair((ndcX + 1f) / 2f * width, (1f - ndcY) / 2f * height) + } + + @Test + fun fitCentersAndScalesContent() { + val content = ContentBounds(minX = -100f, minY = -50f, width = 200f, height = 100f) + val camera = ViewportCamera.fit(content, viewportWidth = 400, viewportHeight = 400) + assertEquals(0f, camera.centerX, tolerance, "center X = content center") + assertEquals(0f, camera.centerY, tolerance, "center Y = content center") + // min(400/200, 400/100) = 2, times the 0.9 margin. + assertEquals(0.9f * 2f, camera.zoom, tolerance, "fit zoom uses the tighter axis and the margin") + } + + @Test + fun worldToNdcMapsCenterToOriginAndOneUnitToZoomPixels() { + val camera = ViewportCamera(centerX = 5f, centerY = -7f, zoom = 3f) + val width = 200 + val height = 100 + val ndc = camera.worldToNdc(width, height) + val centerX = camera.centerX * ndc[0] + ndc[2] + val centerY = camera.centerY * ndc[1] + ndc[3] + assertEquals(0f, centerX, tolerance, "camera center maps to NDC origin") + assertEquals(0f, centerY, tolerance, "camera center maps to NDC origin") + // One world unit right of center lands zoom pixels right of the viewport center. + val (screenX, screenY) = worldToScreen(camera, camera.centerX + 1f, camera.centerY, width, height) + assertEquals(width / 2f + camera.zoom, screenX, tolerance, "one world unit = zoom pixels") + assertEquals(height / 2f, screenY, tolerance, "no vertical shift along a horizontal step") + } + + @Test + fun zoomAtCursorPinsTheWorldPointUnderTheCursor() { + // Start on the grid (150%) so the +25% step lands cleanly at 175%, isolating the pin assertion. + val camera = ViewportCamera(centerX = 10f, centerY = 20f, zoom = 1.5f) + val width = 320 + val height = 240 + val cursorX = 250f + val cursorY = 60f + // The world point currently under the cursor (the camera's own inverse). + val worldX = camera.centerX + (cursorX - width / 2f) / camera.zoom + val worldZ = camera.centerY + (height / 2f - cursorY) / camera.zoom + val zoomed = camera.zoomAtCursorByPercent(deltaPercent = 25f, stepPercent = 1f, cursorXpx = cursorX, cursorYpx = cursorY, viewportWidth = width, viewportHeight = height) + assertEquals(1.75f, zoomed.zoom, tolerance, "150% + 25 points = 175%") + val (screenX, screenY) = worldToScreen(zoomed, worldX, worldZ, width, height) + assertEquals(cursorX, screenX, tolerance, "the pinned world point stays under the cursor X") + assertEquals(cursorY, screenY, tolerance, "the pinned world point stays under the cursor Y") + } + + @Test + fun zoomSnapsOffGridFitToWholePercents() { + // A fit ratio is arbitrary (41.3%); +1% steps must snap onto the integer-percent grid and reach 100. + var camera = ViewportCamera(centerX = 0f, centerY = 0f, zoom = 0.413f) + camera = camera.zoomedByPercent(deltaPercent = 1f, stepPercent = 1f) + assertEquals(42f, camera.zoom * 100f, 0.5f, "first +1% step snaps onto the integer grid") + // 58 more +1% steps reach exactly 100%. + repeat(58) { camera = camera.zoomedByPercent(deltaPercent = 1f, stepPercent = 1f) } + assertEquals(1f, camera.zoom, tolerance, "stepping reaches exactly 100%") + // A +5% step from 100% snaps onto the 5-grid at 105%. + val coarse = camera.zoomedByPercent(deltaPercent = 5f, stepPercent = 5f) + assertEquals(1.05f, coarse.zoom, tolerance, "5% steps snap onto the 5-percent grid") + } + + @Test + fun panByScreenMovesCenterByDeltaOverZoom() { + val camera = ViewportCamera(centerX = 0f, centerY = 0f, zoom = 2f) + val panned = camera.panByScreen(deltaXpx = 10f, deltaYpx = 6f) + assertEquals(-5f, panned.centerX, tolerance, "center X shifts opposite the drag, scaled by 1/zoom") + assertEquals(3f, panned.centerY, tolerance, "center Y carries the screen-down vs world-up flip") + } + + @Test + fun actualSizeSetsUnitZoomKeepingCenter() { + val camera = ViewportCamera(centerX = 42f, centerY = -9f, zoom = 7f) + val actual = camera.withActualSize() + assertEquals(1f, actual.zoom, tolerance, "actual size is true 1:1") + assertEquals(camera.centerX, actual.centerX, tolerance, "center is unchanged") + assertEquals(camera.centerY, actual.centerY, tolerance, "center is unchanged") + } + + @Test + fun framingScreenRectCentersAndFillsTheBox() { + val camera = ViewportCamera(centerX = 10f, centerY = 20f, zoom = 2f) + val width = 400 + val height = 300 + // A 100x60 box; corners passed reversed to prove the two corners may be given in any order. + val left = 50f + val top = 40f + val right = 150f + val bottom = 100f + val framed = camera.framingScreenRect(right, bottom, left, top, viewportWidth = width, viewportHeight = height) + // min(400/100, 300/60) = min(4, 5) = 4, so the looser (vertical) axis letterboxes. + assertEquals(camera.zoom * 4f, framed.zoom, tolerance, "the box fills the tighter axis") + // The world point under the box center (via the OLD camera inverse) maps to the viewport center + // under the NEW camera. + val worldX = camera.centerX + ((left + right) / 2f - width / 2f) / camera.zoom + val worldZ = camera.centerY + (height / 2f - (top + bottom) / 2f) / camera.zoom + val (screenX, screenY) = worldToScreen(framed, worldX, worldZ, width, height) + assertEquals(width / 2f, screenX, tolerance, "box center X frames to viewport center") + assertEquals(height / 2f, screenY, tolerance, "box center Y frames to viewport center") + } + + @Test + fun framingTinyRectClampsToMaxZoom() { + val camera = ViewportCamera(centerX = 0f, centerY = 0f, zoom = 1f) + val framed = camera.framingScreenRect(100f, 100f, 100.5f, 100.5f, viewportWidth = 800, viewportHeight = 800) + assertEquals(ViewportCamera.MAX_ZOOM, framed.zoom, tolerance, "a sub-pixel box cannot exceed the ceiling") + } + + @Test + fun framingDegenerateRectIsGuarded() { + val camera = ViewportCamera(centerX = 3f, centerY = -4f, zoom = 2f) + // Zero-area (a click, not a drag): the 1px floor keeps the zoom finite and clamped. + val framed = camera.framingScreenRect(200f, 150f, 200f, 150f, viewportWidth = 400, viewportHeight = 300) + assertTrue(framed.zoom in ViewportCamera.MIN_ZOOM..ViewportCamera.MAX_ZOOM, "zoom stays within the clamps") + } + + @Test + fun zoomClampsAtTheLimits() { + val far = ViewportCamera(0f, 0f, ViewportCamera.MAX_ZOOM).zoomedByPercent(deltaPercent = 100_000f, stepPercent = 5f) + assertEquals(ViewportCamera.MAX_ZOOM, far.zoom, tolerance, "cannot exceed the ceiling") + val near = ViewportCamera(0f, 0f, ViewportCamera.MIN_ZOOM).zoomedByPercent(deltaPercent = -100_000f, stepPercent = 5f) + assertEquals(ViewportCamera.MIN_ZOOM, near.zoom, tolerance, "cannot drop below the floor") + assertTrue(ViewportCamera.MIN_ZOOM < ViewportCamera.MAX_ZOOM, "floor below ceiling") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/BlendShapeEvalTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/BlendShapeEvalTest.kt new file mode 100644 index 0000000..0e918be --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/BlendShapeEvalTest.kt @@ -0,0 +1,215 @@ +package org.umamo.render.eval + +import org.umamo.runtime.keyform.asGeometryGrid +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.BlendWeightLimitPoint +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the blend-shape weight machinery: the epsilon-free saturating bracket with neutral + * suppression, the min-combined limit curves, and the grid-at-default delta reference. + */ +class BlendShapeEvalTest { + private val shrink = ParameterId("ParamShrink") + private val gate = ParameterId("ParamGate") + + /** Value lookup from explicit pairs; everything else 0. */ + private fun values(vararg pairs: Pair): (ParameterId) -> Float { + val map = mapOf(*pairs) + return { map[it] ?: 0f } + } + + private fun binding( + keys: FloatArray, + neutralIndex: Int, + forms: List, + limits: List = emptyList(), + ) = BlendShapeBinding(shrink, keys, neutralIndex, forms, limits) + + private val twoKey = + binding( + keys = floatArrayOf(-1f, 0f), + neutralIndex = 1, + forms = listOf(WarpForm(floatArrayOf(10f, 20f)), null), + ) + + /** At the neutral value the active list is EMPTY - the default pose is arithmetic-free. */ + @Test + fun neutralValueContributesNothing() { + assertTrue(activeBlendKeys(twoKey, 0f, 1f).isEmpty(), "at neutral") + assertTrue(activeBlendKeys(twoKey, 0.5f, 1f).isEmpty(), "beyond the neutral end saturates to neutral = nothing") + } + + /** Bracket interpolation between a key and the neutral: only the non-neutral key contributes. */ + @Test + fun bracketInterpolatesTowardNeutral() { + val atKey = activeBlendKeys(twoKey, -1f, 1f) + assertEquals(1, atKey.size) + assertEquals(0, atKey[0].keyIndex) + assertEquals(1f, atKey[0].weight) + + val half = activeBlendKeys(twoKey, -0.5f, 1f) + assertEquals(1, half.size) + assertEquals(0.5f, half[0].weight, "midpoint weights the key half") + } + + /** Out-of-range driving values SATURATE (Umamo C++ Runtime verdict): the end delta is held. */ + @Test + fun outOfRangeSaturates() { + val beyond = activeBlendKeys(twoKey, -1.5f, 1f) + assertEquals(1, beyond.size) + assertEquals(0, beyond[0].keyIndex) + assertEquals(1f, beyond[0].weight, "beyond the far key holds its full delta") + } + + /** Between two non-neutral keys both contribute, weights summing to the limit multiplier. */ + @Test + fun bracketBetweenTwoNonNeutralKeys() { + val threeKey = + binding( + keys = floatArrayOf(0f, 1f, 2f), + neutralIndex = 0, + forms = listOf(null, WarpForm(floatArrayOf(1f, 1f)), WarpForm(floatArrayOf(2f, 2f))), + ) + val between = activeBlendKeys(threeKey, 1.25f, 1f) + assertEquals(2, between.size) + assertEquals(1, between[0].keyIndex) + assertEquals(0.75f, between[0].weight) + assertEquals(2, between[1].keyIndex) + assertEquals(0.25f, between[1].weight) + } + + /** The limit multiplier scales weights linearly (Model B-measured: a half ramp gives exactly 0.5x). */ + @Test + fun limitRampScalesWeights() { + val ramp = listOf(BlendWeightLimit(gate, listOf(BlendWeightLimitPoint(0f, 0f), BlendWeightLimitPoint(1f, 1f)))) + assertEquals(0f, limitMultiplier(ramp, values(gate to 0f)), "closed gate suppresses") + assertEquals(0.5f, limitMultiplier(ramp, values(gate to 0.5f)), "half-open gate halves") + assertEquals(1f, limitMultiplier(ramp, values(gate to 1f)), "open gate passes") + assertEquals(0f, limitMultiplier(ramp, values(gate to -1f)), "end-clamped below") + assertEquals(1f, limitMultiplier(ramp, values(gate to 2f)), "end-clamped above") + } + + /** Multiple limits combine by MINIMUM, not product (Model C-shaped inverse ramps). */ + @Test + fun limitsCombineByMinimum() { + val inverseRamp = { parameter: ParameterId -> + BlendWeightLimit(parameter, listOf(BlendWeightLimitPoint(0f, 1f), BlendWeightLimitPoint(1f, 0f))) + } + val other = ParameterId("ParamOther") + val limits = listOf(inverseRamp(gate), inverseRamp(other)) + // gate=0.6 -> 0.4; other=0.8 -> 0.2; MIN = 0.2 (a product would give 0.08). + assertEquals(0.2f, limitMultiplier(limits, values(gate to 0.6f, other to 0.8f)), 1e-6f) + } + + /** meshBlendState resolves the grid-at-default reference and stacks bindings by summation. */ + @Test + fun meshBlendStateUsesGridAtDefaultReference() { + val axis = ParameterId("ParamAxis") + // Grid keyed on ParamAxis with keys [0 (default), 1]: the default cell carries deltas (5, 0). + val grid = + KeyformGrid( + listOf(KeyformAxis(axis, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(5f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(9f, 0f))), + ), + ) + val meshBinding = + BlendShapeBinding( + parameterId = shrink, + keys = floatArrayOf(-1f, 0f), + neutralIndex = 1, + forms = listOf(MeshForm(floatArrayOf(11f, 4f)), null), + ) + val drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = grid, + blendShapes = listOf(meshBinding), + ) + val state = meshBlendState(drawable, values(shrink to -1f), values()) + assertTrue(state != null) + assertEquals(1, state.contributions.size) + assertEquals(1f, state.contributions[0].weight) + // Reference = the default-pose grid form's deltas: (5, 0). + assertEquals(listOf(5f, 0f), state.referenceDeltas?.toList()) + // The eval adds w * (form - reference) = (11-5, 4-0) = (6, 4) on top of the grid result. + } + + /** Warp blend deltas subtract the lattice's default-pose grid form (absolute forms). */ + @Test + fun warpBlendDeltasSubtractDefaultLattice() { + val axis = ParameterId("ParamAxis") + val grid = + KeyformGrid( + listOf(KeyformAxis(axis, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), WarpForm(floatArrayOf(100f, 100f))), + KeyformCell(intArrayOf(1), WarpForm(floatArrayOf(120f, 100f))), + ), + ) + val warp = + Deformer.Warp( + id = DeformerId("w"), + name = "w", + parent = null, + partId = null, + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = grid.asGeometryGrid { form -> WarpLatticeForm(form.controlPoints) }, + blendShapes = + listOf( + BlendShapeBinding( + parameterId = shrink, + keys = floatArrayOf(-1f, 0f), + neutralIndex = 1, + forms = listOf(WarpForm(floatArrayOf(107f, 103f)), null), + ), + ), + ) + val deltas = warpBlendDeltas(warp, values(shrink to -0.5f), values()) + assertTrue(deltas != null) + // Reference = default lattice (100, 100); authored (107, 103); weight 0.5 -> (3.5, 1.5). + assertEquals(3.5f, deltas[0], 1e-6f) + assertEquals(1.5f, deltas[1], 1e-6f) + } + + /** A binding-free drawable resolves to null state - the caller keeps today's exact path. */ + @Test + fun bindingFreeDrawableHasNoState() { + val bare = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + assertEquals(null, meshBlendState(bare, values(), values())) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/ChannelOverrideEvalTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/ChannelOverrideEvalTest.kt new file mode 100644 index 0000000..00f659f --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/ChannelOverrideEvalTest.kt @@ -0,0 +1,116 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins that a pending unkeyed channel edit reaches the renderer. + * + * A pending edit is session state, never document state - so it cannot ride the model to the renderer and + * instead travels beside the pose, exactly as the pose itself travels beside the model. Without this the + * field would show a value the puppet does not reflect, which defeats the point of adjusting before keying. + * + * The override wins over BOTH a stored track and the static fallback, because it represents the value the + * user is looking at right now. + */ +class ChannelOverrideEvalTest { + private val paramA = ParameterId("A") + private val drawableId = DrawableId("d") + private val owner = KeyformOwner.Drawable(drawableId) + + private fun model(channelGrids: org.umamo.runtime.model.ChannelGrids): PuppetModel { + val positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f) + val drawable = + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2)), + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ), + channelGrids = channelGrids, + opacity = 0.25f, + multiplyColor = ColorRgb(1f, 1f, 1f), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawableId)), + rootPartId = null, + ) + } + + /** With no override, the channel reads its static as usual - the parameter is inert by default. */ + @Test + fun withoutAnOverrideTheStaticHolds() { + val inputs = preparePose(model(org.umamo.runtime.model.ChannelGrids.Empty), emptyMap()) + assertEquals(0.25f, inputs.drawables.single().opacity) + } + + /** An override replaces the static for an untracked channel. */ + @Test + fun anOverrideBeatsTheStatic() { + val overrides = mapOf(KeyableTarget(owner, FormChannel.OPACITY) to ChannelValue.Scalar(0.9f)) + val inputs = preparePose(model(org.umamo.runtime.model.ChannelGrids.Empty), emptyMap(), overrides) + assertEquals(0.9f, inputs.drawables.single().opacity, "the typed value is what the viewport shows") + } + + /** + * An override beats a STORED TRACK too. + * + * This is the case that matters: editing a property that is already keyed is precisely when the value + * on screen must follow what was typed rather than what the grid evaluates, or the field and the puppet + * disagree while the user decides whether to key it. + */ + @Test + fun anOverrideBeatsAStoredTrack() { + val track = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(-1f, 1f))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(0f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)), + ), + ) + val keyed = org.umamo.runtime.model.ChannelGrids(mapOf(FormChannel.OPACITY to track)) + val withoutOverride = preparePose(model(keyed), mapOf(paramA to 0f)) + assertEquals(0.5f, withoutOverride.drawables.single().opacity, "the track blends to its midpoint") + + val overrides = mapOf(KeyableTarget(owner, FormChannel.OPACITY) to ChannelValue.Scalar(0.1f)) + val withOverride = preparePose(model(keyed), mapOf(paramA to 0f), overrides) + assertEquals(0.1f, withOverride.drawables.single().opacity, "the pending edit wins over the stored key") + } + + /** Colors override the same way, and an override on one channel leaves the others alone. */ + @Test + fun anOverrideIsScopedToItsChannel() { + val overrides = mapOf(KeyableTarget(owner, FormChannel.MULTIPLY_COLOR) to ChannelValue.Color(ColorRgb(1f, 0f, 0f))) + val resolved = preparePose(model(org.umamo.runtime.model.ChannelGrids.Empty), emptyMap(), overrides).drawables.single() + assertEquals(ColorRgb(1f, 0f, 0f), resolved.multiplyColor) + assertEquals(0.25f, resolved.opacity, "an unrelated channel keeps its own value") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/CpuDeformationEvaluatorTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/CpuDeformationEvaluatorTest.kt new file mode 100644 index 0000000..fd203a1 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/CpuDeformationEvaluatorTest.kt @@ -0,0 +1,63 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Assembly tests for [CpuDeformationEvaluator] on tiny synthetic models: that it routes direct vs + * deformer-parented meshes correctly and resolves unspecified parameters to their defaults. The + * per-stage math is covered by the keyform/transform/cascade tests; this checks the wiring. + */ +class CpuDeformationEvaluatorTest { + private val tol = 1e-4f + private val paramA = ParameterId("A") + + private fun axis() = listOf(KeyformAxis(paramA, floatArrayOf(0f))) + + private fun zeroMeshGrid(coordCount: Int) = KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(coordCount))))) + + private fun model(deformers: List, drawable: Drawable) = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = deformers, + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + + @Test + fun routesDirectMeshWithYFlip() { + val mesh = DrawableMesh(floatArrayOf(10f, 5f, 20f, 7f), FloatArray(0), IntArray(0)) + val drawable = Drawable(DrawableId("M"), "M", null, BlendMode.Normal, emptyList(), mesh, zeroMeshGrid(4)) + val geo = CpuDeformationEvaluator().evaluate(model(emptyList(), drawable), emptyMap()) + assertEquals(listOf(10f, -5f, 20f, -7f), geo.worldPositions[DrawableId("M")]!!.toList()) + } + + @Test + fun routesMeshThroughItsWarpParent() { + val warpCp = floatArrayOf(10f, 20f, 12f, 20f, 10f, 24f, 12f, 24f) // 2×4 rect at (10,20) + val warp = Deformer.Warp(DeformerId("W"), "W", null, null, 1, 1, true, KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(warpCp))))) + val mesh = DrawableMesh(floatArrayOf(0.5f, 0.5f), FloatArray(0), IntArray(0)) + val drawable = Drawable(DrawableId("M"), "M", DeformerId("W"), BlendMode.Normal, emptyList(), mesh, zeroMeshGrid(2)) + val geo = CpuDeformationEvaluator().evaluate(model(listOf(warp), drawable), emptyMap()) + val world = geo.worldPositions[DrawableId("M")]!! + assertEquals(11f, world[0], tol) + assertEquals(-22f, world[1], tol) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/DeformTransformsTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/DeformTransformsTest.kt new file mode 100644 index 0000000..a66fc1f --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/DeformTransformsTest.kt @@ -0,0 +1,91 @@ +package org.umamo.render.eval + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Unit tests for the warp (in-grid + extrapolation) and rotation transforms on synthetic lattices. + * The identity unit-square lattice is linear everywhere, so it maps `(u,v)` to `(u,v)` both inside the + * grid and under extrapolation - a clean oracle for the FFD math without the corpus. + */ +class DeformTransformsTest { + private val tol = 1e-4f + + // Identity unit-square 1×1 lattice: cp00=(0,0) cp10=(1,0) cp01=(0,1) cp11=(1,1). + private val identity = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f) + + @Test + fun identityGridMapsUvToUvBilinear() { + val out = FloatArray(2) + assertTrue(warpInGrid(identity, 1, 1, true, 0.5f, 0.5f, out, 0)) + assertEquals(0.5f, out[0], tol) + assertEquals(0.5f, out[1], tol) + warpApply(identity, 1, 1, true, 0.25f, 0.75f, out, 0) + assertEquals(0.25f, out[0], tol) + assertEquals(0.75f, out[1], tol) + } + + @Test + fun identityGridMapsUvToUvTriangle() { + val out = FloatArray(2) + warpApply(identity, 1, 1, false, 0.25f, 0.25f, out, 0) // lower triangle (u+v <= 1) + assertEquals(0.25f, out[0], tol) + assertEquals(0.25f, out[1], tol) + warpApply(identity, 1, 1, false, 0.7f, 0.6f, out, 0) // upper triangle (u+v > 1) + assertEquals(0.7f, out[0], tol) + assertEquals(0.6f, out[1], tol) + } + + @Test + fun warpReturnsFalseOutsideGrid() { + val out = FloatArray(2) + assertFalse(warpInGrid(identity, 1, 1, true, 1.5f, 0.5f, out, 0)) + assertFalse(warpInGrid(identity, 1, 1, true, -0.1f, 0.5f, out, 0)) + } + + @Test + fun translatedScaledGridMapsCenter() { + // A 1×1 lattice placed as a 2×4 rectangle at (10,20): corners (10,20)(12,20)(10,24)(12,24). + val grid = floatArrayOf(10f, 20f, 12f, 20f, 10f, 24f, 12f, 24f) + val out = FloatArray(2) + warpApply(grid, 1, 1, true, 0.5f, 0.5f, out, 0) + assertEquals(11f, out[0], tol) + assertEquals(22f, out[1], tol) + } + + @Test + fun identityGridExtrapolatesLinearly() { + val out = FloatArray(2) + // Far outside -> pure affine; the identity lattice is linear, so (u,v) maps to (u,v). + warpApply(identity, 1, 1, true, 5f, 2f, out, 0) + assertEquals(5f, out[0], tol) + assertEquals(2f, out[1], tol) + warpApply(identity, 1, 1, true, -3f, 4f, out, 0) + assertEquals(-3f, out[0], tol) + assertEquals(4f, out[1], tol) + } + + @Test + fun rotation90DegreesRotatesPoint() { + val xform = rotationXform(90f, 1f, false, false, 0f, 0f) + val out = FloatArray(2) + xform.apply(1f, 0f, out, 0) // (1,0) rotated +90 -> (0,1) + assertEquals(0f, out[0], tol) + assertEquals(1f, out[1], tol) + xform.apply(0f, 1f, out, 0) // (0,1) -> (-1,0) + assertEquals(-1f, out[0], tol) + assertEquals(0f, out[1], tol) + } + + @Test + fun rotationAppliesScaleFlipOrigin() { + // angle 0, scale 2, flipX, origin (5,-3): x' = -2·x + 5, y' = 2·y - 3. + val xform = rotationXform(0f, 2f, true, false, 5f, -3f) + val out = FloatArray(2) + xform.apply(1f, 1f, out, 0) + assertEquals(3f, out[0], tol) + assertEquals(-1f, out[1], tol) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/DeformerCascadeTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/DeformerCascadeTest.kt new file mode 100644 index 0000000..d555a7d --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/DeformerCascadeTest.kt @@ -0,0 +1,169 @@ +package org.umamo.render.eval + +import org.umamo.runtime.keyform.fanOutWarp +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Cascade tests on synthetic single-level and nested hierarchies. A mesh's local verts are pushed + * through its parent deformer's baked world transform and Y-flipped; nesting composes the transforms + * top-down. + */ +class DeformerCascadeTest { + private val tol = 1e-4f + private val paramA = ParameterId("A") + + private fun values(vararg pairs: Pair): (ParameterId) -> Float { + val map = pairs.toMap() + return { map[it] ?: 0f } + } + + private fun singleKeyAxis() = listOf(KeyformAxis(paramA, floatArrayOf(0f))) + + private fun warp(id: String, parent: String?, cols: Int, rows: Int, bilinear: Boolean, cp: FloatArray): Deformer.Warp { + val grid = KeyformGrid(singleKeyAxis(), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(cp)))) + return Deformer.Warp(DeformerId(id), id, parent?.let(::DeformerId), null, rows, cols, bilinear, grid) + } + + private fun rotation(id: String, baseAngle: Float, originX: Float, originY: Float, angle: Float, scale: Float): Deformer.Rotation { + val grid = KeyformGrid(singleKeyAxis(), listOf(KeyformCell(intArrayOf(0), RotationPivotForm(originX, originY, angle, scale)))) + return Deformer.Rotation(DeformerId(id), id, null, null, baseAngle, grid) + } + + private fun zeroDeltaMesh(vertexCount: Int): KeyformGrid = + KeyformGrid(singleKeyAxis(), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(vertexCount * 2))))) + + @Test + fun meshUnderTranslatedWarp() { + // 1×1 lattice placed as a 2×4 rect at (10,20). + val warp = warp("W", null, 1, 1, true, floatArrayOf(10f, 20f, 12f, 20f, 10f, 24f, 12f, 24f)) + val parent = buildDeformerWorlds(listOf(warp), values(paramA to 0f))[DeformerId("W")]!! + val world = deformMeshThroughParent(zeroDeltaMesh(1), floatArrayOf(0.5f, 0.5f), parent, values(paramA to 0f))!! + assertEquals(11f, world[0], tol) + assertEquals(-22f, world[1], tol) // center (11,22), Y-flipped + } + + @Test + fun meshUnderRootRotation() { + val rotation = rotation("R", 0f, 0f, 0f, 90f, 1f) + val parent = buildDeformerWorlds(listOf(rotation), values(paramA to 0f))[DeformerId("R")]!! + val world = deformMeshThroughParent(zeroDeltaMesh(1), floatArrayOf(1f, 0f), parent, values(paramA to 0f))!! + assertEquals(0f, world[0], tol) // (1,0) rotated +90 -> (0,1) + assertEquals(-1f, world[1], tol) // Y-flipped + } + + @Test + fun nestedWarpComposesParentTransform() { + // Parent translates +100 in x; child is identity -> composed lattice is the parent's. + val parentWarp = warp("P", null, 1, 1, true, floatArrayOf(100f, 0f, 101f, 0f, 100f, 1f, 101f, 1f)) + val childWarp = warp("C", "P", 1, 1, true, floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f)) + val worlds = buildDeformerWorlds(listOf(parentWarp, childWarp), values(paramA to 0f)) + val child = worlds[DeformerId("C")]!! + val world = deformMeshThroughParent(zeroDeltaMesh(1), floatArrayOf(0.5f, 0.5f), child, values(paramA to 0f))!! + assertEquals(100.5f, world[0], tol) // center of the +100-translated lattice + assertEquals(-0.5f, world[1], tol) + } + + // --- Render-channel cascade ------------------------------------------------------------------- + // A deformer's opacity and multiply/screen colors apply to every drawable underneath it, composed + // down the chain. Riggers key the opacity as a subtree show/hide switch, so these compositions are + // load-bearing rather than cosmetic. + + /** A 1x1 identity-lattice warp carrying render channels, for channel-only assertions. */ + private fun channelWarp( + id: String, + parent: String?, + opacity: Float, + multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + screenColor: ColorRgb = ColorRgb.ScreenIdentity, + ): Deformer.Warp { + // Built bundled and fanned out, so the fixture exercises the real import split rather than + // hand-assembling tracks that could drift from what an importer actually produces. + val form = WarpForm(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), opacity, multiplyColor, screenColor) + val fanned = KeyformGrid(singleKeyAxis(), listOf(KeyformCell(intArrayOf(0), form))).fanOutWarp() + return Deformer.Warp(DeformerId(id), id, parent?.let(::DeformerId), null, 1, 1, true, fanned.geometry, fanned.channels) + } + + @Test + fun rootDeformerChannelsPassThroughUnchanged() { + val root = channelWarp("W", null, 0.5f, ColorRgb(0.25f, 0.5f, 1f), ColorRgb(0.1f, 0f, 0f)) + val world = buildDeformerWorlds(listOf(root), values(paramA to 0f))[DeformerId("W")]!! + // Identity parents: multiplying by white and screening with black both return the local value. + assertEquals(0.5f, world.accumulatedOpacity, tol) + assertEquals(0.25f, world.accumulatedMultiplyColor.red, tol) + assertEquals(1f, world.accumulatedMultiplyColor.blue, tol) + assertEquals(0.1f, world.accumulatedScreenColor.red, tol) + } + + @Test + fun nestedDeformerOpacityMultipliesDownTheChain() { + val parent = channelWarp("P", null, 0.5f) + val child = channelWarp("C", "P", 0.5f) + val worlds = buildDeformerWorlds(listOf(parent, child), values(paramA to 0f)) + assertEquals(0.5f, worlds[DeformerId("P")]!!.accumulatedOpacity, tol) + assertEquals(0.25f, worlds[DeformerId("C")]!!.accumulatedOpacity, tol) // 0.5 * 0.5 + } + + @Test + fun nestedMultiplyColorComposesComponentwise() { + val parent = channelWarp("P", null, 1f, multiplyColor = ColorRgb(0.5f, 1f, 0.25f)) + val child = channelWarp("C", "P", 1f, multiplyColor = ColorRgb(0.5f, 0.5f, 1f)) + val accumulated = buildDeformerWorlds(listOf(parent, child), values(paramA to 0f))[DeformerId("C")]!! + assertEquals(0.25f, accumulated.accumulatedMultiplyColor.red, tol) // 0.5 * 0.5 + assertEquals(0.5f, accumulated.accumulatedMultiplyColor.green, tol) // 0.5 * 1 + assertEquals(0.25f, accumulated.accumulatedMultiplyColor.blue, tol) // 1 * 0.25 + } + + @Test + fun nestedScreenColorComposesWithTheScreenOperator() { + // Screen is a + b - a*b, NOT a product: two half-screens make 0.75, not 0.25. + val parent = channelWarp("P", null, 1f, screenColor = ColorRgb(0.5f, 0f, 1f)) + val child = channelWarp("C", "P", 1f, screenColor = ColorRgb(0.5f, 0.25f, 0.5f)) + val accumulated = buildDeformerWorlds(listOf(parent, child), values(paramA to 0f))[DeformerId("C")]!! + assertEquals(0.75f, accumulated.accumulatedScreenColor.red, tol) // 0.5+0.5-0.25 + assertEquals(0.25f, accumulated.accumulatedScreenColor.green, tol) // 0.25+0-0 + assertEquals(1f, accumulated.accumulatedScreenColor.blue, tol) // screening with white saturates + } + + @Test + fun identityChannelsLeaveADeepChainUntouched() { + // The common case: nothing authored, so a three-deep chain must not drift off the identities. + val worlds = + buildDeformerWorlds( + listOf(channelWarp("A", null, 1f), channelWarp("B", "A", 1f), channelWarp("C", "B", 1f)), + values(paramA to 0f), + ) + val deepest = worlds[DeformerId("C")]!! + assertEquals(1f, deepest.accumulatedOpacity, tol) + assertEquals(ColorRgb.MultiplyIdentity, deepest.accumulatedMultiplyColor) + assertEquals(ColorRgb.ScreenIdentity, deepest.accumulatedScreenColor) + } + + @Test + fun channelsBlendAcrossKeysRatherThanSnapping() { + // A two-key axis keyed 1 -> 0: at the midpoint the subtree must be half faded, not fully on or + // fully off. Snapping to the nearest key was a real bug in the reference implementation. + val fanned = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), WarpForm(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), 1f)), + KeyformCell(intArrayOf(1), WarpForm(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), 0f)), + ), + ).fanOutWarp() + val fading = Deformer.Warp(DeformerId("F"), "F", null, null, 1, 1, true, fanned.geometry, fanned.channels) + val atMidpoint = buildDeformerWorlds(listOf(fading), values(paramA to 0.5f))[DeformerId("F")]!! + assertEquals(0.5f, atMidpoint.accumulatedOpacity, tol) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/DrawableSpaceMappingTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/DrawableSpaceMappingTest.kt new file mode 100644 index 0000000..e372467 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/DrawableSpaceMappingTest.kt @@ -0,0 +1,345 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies [DrawableSpaceMapping]: the forward local->world projection matches the evaluator's world + * positions exactly (same chain, same Y negation), and the inverse recovers local coordinates - in + * closed form for rotation parents, by Newton iteration for warp parents - including for a moved + * world target (the Edit-gizmo drag case). Degenerate transforms keep the seed instead of exploding. + * The single-step [DrawableSpaceMapping.worldToLocalLinearized] used by the transform path is exact for + * affine parents and, unlike the Newton inverse, follows a large warp-child drag without pinning or + * boiling. + */ +class DrawableSpaceMappingTest { + private val tol = 1e-3f + private val paramA = ParameterId("A") + private val drawableId = DrawableId("M") + + private fun axis() = listOf(KeyformAxis(paramA, floatArrayOf(0f))) + + private fun zeroMeshGrid(coordCount: Int) = KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(coordCount))))) + + private fun drawable(parent: DeformerId?, positions: FloatArray) = + Drawable(drawableId, "M", parent, BlendMode.Normal, emptyList(), DrawableMesh(positions, FloatArray(0), IntArray(0)), zeroMeshGrid(positions.size)) + + private fun model(deformers: List, drawable: Drawable) = + PuppetModel(listOf(Parameter(paramA, "A", -1f, 1f, 0f)), emptyList(), deformers, listOf(drawable), emptyList(), null) + + /** 2x4 world rectangle at (10,20): the same 1x1 quad lattice the evaluator's warp routing test uses. */ + private fun warpDeformer(): Deformer.Warp { + val controlPoints = floatArrayOf(10f, 20f, 12f, 20f, 10f, 24f, 12f, 24f) + return Deformer.Warp(DeformerId("W"), "W", null, null, 1, 1, true, KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(controlPoints))))) + } + + /** Rotation about (5,5): 90 degrees, scale 2, no flips. */ + private fun rotationDeformer(scale: Float = 2f) = + Deformer.Rotation( + DeformerId("R"), + "R", + null, + null, + 0f, + KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), RotationPivotForm(5f, 5f, 90f, scale)))), + ) + + /** A direct (deformer-less) drawable maps by pure Y negation, and the inverse recovers it exactly. */ + @Test + fun directDrawableIsPureYNegate() { + val local = floatArrayOf(10f, 5f, 20f, 7f) + val mapping = assertNotNull(drawableSpaceMapping(model(emptyList(), drawable(null, local)), emptyMap(), drawableId)) + val world = mapping.localToWorld(local) + assertEquals(listOf(10f, -5f, 20f, -7f), world.toList()) + val recovered = mapping.worldToLocal(world, FloatArray(local.size), setOf(0, 1)) + assertEquals(local.toList(), recovered.toList()) + } + + /** A warp child's forward projection matches the evaluator, and Newton recovers the seed UV. */ + @Test + fun warpChildMatchesEvaluatorAndRoundTrips() { + val local = floatArrayOf(0.5f, 0.5f) + val puppet = model(listOf(warpDeformer()), drawable(DeformerId("W"), local)) + val mapping = assertNotNull(drawableSpaceMapping(puppet, emptyMap(), drawableId)) + val world = mapping.localToWorld(local) + val evaluatorWorld = CpuDeformationEvaluator().evaluate(puppet, emptyMap()).worldPositions.getValue(drawableId) + assertEquals(evaluatorWorld[0], world[0], tol, "forward x matches the evaluator") + assertEquals(evaluatorWorld[1], world[1], tol, "forward y matches the evaluator") + val recovered = mapping.worldToLocal(world, local, setOf(0)) + assertEquals(0.5f, recovered[0], 1e-4f, "u round-trips") + assertEquals(0.5f, recovered[1], 1e-4f, "v round-trips") + } + + /** The drag case: inverting a MOVED world target yields a UV whose forward projection hits it. */ + @Test + fun warpInverseSolvesAMovedTarget() { + val local = floatArrayOf(0.5f, 0.5f) + val puppet = model(listOf(warpDeformer()), drawable(DeformerId("W"), local)) + val mapping = assertNotNull(drawableSpaceMapping(puppet, emptyMap(), drawableId)) + val movedWorld = mapping.localToWorld(local) + movedWorld[0] += 0.5f + movedWorld[1] -= 0.9f + val solvedLocal = mapping.worldToLocal(movedWorld, local, setOf(0)) + val reprojected = mapping.localToWorld(solvedLocal) + assertEquals(movedWorld[0], reprojected[0], tol, "reprojected x hits the moved target") + assertEquals(movedWorld[1], reprojected[1], tol, "reprojected y hits the moved target") + } + + /** A rotation child's forward projection matches the evaluator; the closed-form inverse recovers it. */ + @Test + fun rotationChildMatchesEvaluatorAndRoundTrips() { + val local = floatArrayOf(1f, 0f, 0f, 3f) + val puppet = model(listOf(rotationDeformer()), drawable(DeformerId("R"), local)) + val mapping = assertNotNull(drawableSpaceMapping(puppet, emptyMap(), drawableId)) + val world = mapping.localToWorld(local) + val evaluatorWorld = CpuDeformationEvaluator().evaluate(puppet, emptyMap()).worldPositions.getValue(drawableId) + for (coordIndex in world.indices) { + assertEquals(evaluatorWorld[coordIndex], world[coordIndex], tol, "forward coord $coordIndex matches the evaluator") + } + val recovered = mapping.worldToLocal(world, FloatArray(local.size), setOf(0, 1)) + for (coordIndex in local.indices) { + assertEquals(local[coordIndex], recovered[coordIndex], tol, "inverse coord $coordIndex round-trips") + } + } + + /** A zero-scale rotation has no inverse: the seed is kept untouched and nothing goes NaN. */ + @Test + fun degenerateRotationKeepsSeed() { + val local = floatArrayOf(1f, 0f) + val puppet = model(listOf(rotationDeformer(scale = 0f)), drawable(DeformerId("R"), local)) + val mapping = assertNotNull(drawableSpaceMapping(puppet, emptyMap(), drawableId)) + val world = mapping.localToWorld(local) + val recovered = mapping.worldToLocal(world, local, setOf(0)) + assertEquals(local.toList(), recovered.toList(), "seed kept") + assertFalse(recovered.any { it.isNaN() }, "no NaN") + } + + /** drawableLocalPosed blends base + keyform deltas exactly like the renderer's local stage. */ + @Test + fun drawableLocalPosedBlendsBetweenKeys() { + val blendGrid = + KeyformGrid( + axes = listOf(KeyformAxis(paramA, floatArrayOf(0f, 10f))), + cells = + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(4f, 0f))), + ), + ) + val blendDrawable = + Drawable(drawableId, "M", null, BlendMode.Normal, emptyList(), DrawableMesh(floatArrayOf(1f, 2f), FloatArray(0), IntArray(0)), blendGrid) + val puppet = PuppetModel(listOf(Parameter(paramA, "A", 0f, 10f, 0f)), emptyList(), emptyList(), listOf(blendDrawable), emptyList(), null) + val halfway = assertNotNull(drawableLocalPosed(puppet, mapOf(paramA to 5f), drawableId)) + assertEquals(3f, halfway[0], tol, "base 1 + half of delta 4") + assertEquals(2f, halfway[1], tol, "y unchanged") + assertNull(drawableLocalPosed(puppet, emptyMap(), DrawableId("absent")), "missing drawable") + } + + /** No such drawable, or a parent whose world cannot be built, cannot be mapped. */ + @Test + fun unmappableCasesReturnNull() { + val puppet = model(emptyList(), drawable(DeformerId("missing"), floatArrayOf(0f, 0f))) + assertNull(drawableSpaceMapping(puppet, emptyMap(), DrawableId("absent")), "missing drawable") + assertNull(drawableSpaceMapping(puppet, emptyMap(), drawableId), "unbuildable parent world") + } + + /** + * A warp-child grab far past the lattice follows the cursor with the linearized inverse, where the + * damped iterative [DrawableSpaceMapping.worldToLocal] pins short of the target: the 2x4 cage spans 2 + * world-x per lattice UV, so its damped ~10-UV Newton reach stalls near world-x 31, and a +200 grab + * targets far beyond that reach. + */ + @Test + fun warpLargeGrabFollowsInsteadOfPinning() { + val local = floatArrayOf(0.5f, 0.5f) + val puppet = model(listOf(warpDeformer()), drawable(DeformerId("W"), local)) + val mapping = assertNotNull(drawableSpaceMapping(puppet, emptyMap(), drawableId)) + val worldRest = mapping.localToWorld(local) + val worldTarget = worldRest.copyOf().also { it[0] += 200f } + + // The linearized inverse follows the 200-unit grab to within a world unit (the residual is + // finite-difference Jacobian error, not the Newton reach cliff). A true inverse would be exact, but + // sub-unit accuracy on a 200-unit drag is visually indistinguishable and never pins. + val solvedLinearized = mapping.worldToLocalLinearized(worldTarget, local, worldRest, setOf(0)) + val reprojectedLinearized = mapping.localToWorld(solvedLinearized) + val linearizedShortfall = abs(reprojectedLinearized[0] - worldTarget[0]) + assertTrue(linearizedShortfall < 1f, "linearized inverse follows the cursor (shortfall=$linearizedShortfall)") + assertEquals(worldTarget[1], reprojectedLinearized[1], tol, "no drift on the unmoved axis") + + // Regression guard: the damped iterative inverse pins well short of the target. + val solvedNewton = mapping.worldToLocal(worldTarget, local, setOf(0)) + val reprojectedNewton = mapping.localToWorld(solvedNewton) + assertTrue(abs(reprojectedNewton[0] - worldTarget[0]) > 100f, "the Newton inverse pins at its reach limit") + } + + /** + * A swept warp-child grab follows the cursor without pinning or boiling. The reach-uncapped per-vertex + * inverse lands the vertex on the moving target every frame (it reprojects onto it - never pins short), + * and the solved local coordinate advances in bounded steps (no jitter / scatter), even as the sweep + * crosses the piecewise extrapolation band where the reach-capped inverse was noisy. + */ + @Test + fun warpSweptGrabIsContinuousNoBoil() { + val controlPoints = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 14f, 12f) + val warp = Deformer.Warp(DeformerId("W"), "W", null, null, 1, 1, true, KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(controlPoints))))) + val local = floatArrayOf(0.5f, 0.5f) + val mapping = assertNotNull(drawableSpaceMapping(model(listOf(warp), drawable(DeformerId("W"), local)), emptyMap(), drawableId)) + val worldRest = mapping.localToWorld(local) + + var previousLocalU = Float.NaN + for (frame in 1..200) { + val worldTarget = + worldRest.copyOf().also { + it[0] += frame * 3f + it[1] -= frame * 2f + } + val solved = mapping.worldToLocalLinearized(worldTarget, local, worldRest, setOf(0)) + val reprojected = mapping.localToWorld(solved) + // Follows: the reach-uncapped inverse lands the vertex on the moving target (never pins). + assertEquals(worldTarget[0], reprojected[0], 1f, "swept grab follows the target x (frame $frame)") + assertEquals(worldTarget[1], reprojected[1], 1f, "swept grab follows the target y (frame $frame)") + if (!previousLocalU.isNaN()) { + // No boil: the solved coordinate advances in a bounded step, never jittering / scattering. + assertTrue(abs(solved[0] - previousLocalU) < 1f, "solved u advances smoothly, no boil (frame $frame)") + } + previousLocalU = solved[0] + } + } + + /** The linearized inverse is exact for affine parents (direct and rotation) and agrees with the closed form. */ + @Test + fun linearizedIsExactForAffineParents() { + val directLocal = floatArrayOf(10f, 5f, 20f, 7f) + val directMapping = assertNotNull(drawableSpaceMapping(model(emptyList(), drawable(null, directLocal)), emptyMap(), drawableId)) + val directRest = directMapping.localToWorld(directLocal) + val directTarget = + directRest.copyOf().also { + it[0] += 3f + it[1] += 4f + it[2] -= 5f + it[3] += 6f + } + val directSolved = directMapping.worldToLocalLinearized(directTarget, directLocal, directRest, setOf(0, 1)) + val directReprojected = directMapping.localToWorld(directSolved) + for (coordIndex in directTarget.indices) { + assertEquals(directTarget[coordIndex], directReprojected[coordIndex], tol, "direct reprojects onto target") + } + val directClosed = directMapping.worldToLocal(directTarget, directLocal, setOf(0, 1)) + for (coordIndex in directSolved.indices) { + assertEquals(directClosed[coordIndex], directSolved[coordIndex], tol, "direct agrees with the closed form") + } + + val rotationLocal = floatArrayOf(1f, 0f, 0f, 3f) + val rotationMapping = assertNotNull(drawableSpaceMapping(model(listOf(rotationDeformer()), drawable(DeformerId("R"), rotationLocal)), emptyMap(), drawableId)) + val rotationRest = rotationMapping.localToWorld(rotationLocal) + val rotationTarget = + rotationRest.copyOf().also { + it[0] += 40f + it[1] -= 25f + } + val rotationSolved = rotationMapping.worldToLocalLinearized(rotationTarget, rotationLocal, rotationRest, setOf(0)) + val rotationReprojected = rotationMapping.localToWorld(rotationSolved) + assertEquals(rotationTarget[0], rotationReprojected[0], tol, "rotation reprojects onto target") + assertEquals(rotationTarget[1], rotationReprojected[1], tol, "rotation reprojects onto target") + assertEquals(rotationLocal[2], rotationSolved[2], tol, "untouched vertex kept") + assertEquals(rotationLocal[3], rotationSolved[3], tol, "untouched vertex kept") + } + + /** + * A warp-child Grab is world-rigid: the per-vertex exact inverse lands every vertex on its own world + * target, so the mesh translates as a rigid body in world space with no squish at all - the property + * the shared-Jacobian linearizations cannot hold on a curved cage. + */ + @Test + fun warpGrabIsWorldRigid() { + // A non-parallelogram cage so the warp Jacobian genuinely varies across the lattice. + val controlPoints = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 14f, 12f) + val warp = Deformer.Warp(DeformerId("W"), "W", null, null, 1, 1, true, KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(controlPoints))))) + val local = floatArrayOf(0.3f, 0.3f, 0.7f, 0.6f) + val mapping = assertNotNull(drawableSpaceMapping(model(listOf(warp), drawable(DeformerId("W"), local)), emptyMap(), drawableId)) + val worldRest = mapping.localToWorld(local) + // One shared world delta on both vertices (a Grab). + val worldTarget = + worldRest.copyOf().also { + it[0] += 8f + it[1] -= 5f + it[2] += 8f + it[3] -= 5f + } + + val solved = mapping.worldToLocalLinearized(worldTarget, local, worldRest, setOf(0, 1)) + val reprojected = mapping.localToWorld(solved) + for (coordIndex in worldTarget.indices) { + assertEquals(worldTarget[coordIndex], reprojected[coordIndex], tol, "vertex reprojects exactly onto its world target (coord $coordIndex)") + } + } + + /** + * On a strongly curved cage - the real-model failure (three nested, upward-bowed warps) in miniature - + * a large multi-vertex grab lands the selection's centroid on the cursor. The world-rigid inverse lands + * every vertex on target, so the centroid trivially follows too (the shared-Jacobian inverses miss here). + */ + @Test + fun warpCurvedCageGrabLandsCentroidOnTarget() { + // A 2x1 cage bowed upward in the middle column, so the local->world scale varies sharply across it. + val controlPoints = floatArrayOf(0f, 0f, 10f, -4f, 20f, 0f, 0f, 10f, 10f, 6f, 20f, 10f) + val warp = Deformer.Warp(DeformerId("W"), "W", null, null, 1, 2, true, KeyformGrid(axis(), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(controlPoints))))) + val local = floatArrayOf(0.2f, 0.4f, 0.5f, 0.3f, 0.8f, 0.4f, 0.5f, 0.7f) + val indices = setOf(0, 1, 2, 3) + val mapping = assertNotNull(drawableSpaceMapping(model(listOf(warp), drawable(DeformerId("W"), local)), emptyMap(), drawableId)) + val worldRest = mapping.localToWorld(local) + // A large grab: shift every vertex by the same world delta, far past the cage. + val worldTarget = worldRest.copyOf() + for (vertexIndex in 0 until 4) { + worldTarget[vertexIndex * 2] += 60f + worldTarget[vertexIndex * 2 + 1] += 40f + } + val solved = mapping.worldToLocalLinearized(worldTarget, local, worldRest, indices) + + // Reproject the solved centroid and compare to the target centroid: the gross offset is gone. + var centroidU = 0f + var centroidV = 0f + for (vertexIndex in 0 until 4) { + centroidU += solved[vertexIndex * 2] + centroidV += solved[vertexIndex * 2 + 1] + } + val reprojectedCentroid = mapping.localToWorld(floatArrayOf(centroidU / 4f, centroidV / 4f)) + val targetCentroidX = (worldTarget[0] + worldTarget[2] + worldTarget[4] + worldTarget[6]) / 4f + val targetCentroidY = (worldTarget[1] + worldTarget[3] + worldTarget[5] + worldTarget[7]) / 4f + assertEquals(targetCentroidX, reprojectedCentroid[0], 1f, "grabbed centroid lands on the cursor x") + assertEquals(targetCentroidY, reprojectedCentroid[1], 1f, "grabbed centroid lands on the cursor y") + } + + /** A zero-scale (degenerate) rotation parent keeps the seed in the linearized inverse; nothing goes NaN. */ + @Test + fun linearizedDegenerateRotationKeepsSeed() { + val local = floatArrayOf(1f, 0f) + val puppet = model(listOf(rotationDeformer(scale = 0f)), drawable(DeformerId("R"), local)) + val mapping = assertNotNull(drawableSpaceMapping(puppet, emptyMap(), drawableId)) + val worldRest = mapping.localToWorld(local) + val worldTarget = worldRest.copyOf().also { it[0] += 9f } + val solved = mapping.worldToLocalLinearized(worldTarget, local, worldRest, setOf(0)) + assertEquals(local.toList(), solved.toList(), "seed kept") + assertFalse(solved.any { it.isNaN() }, "no NaN") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/GlueTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/GlueTest.kt new file mode 100644 index 0000000..596a5d0 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/GlueTest.kt @@ -0,0 +1,91 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Verifies the glue weld ([applyGluesResolved]): each pair slides `A' = A + (B−A)·wA`, `B' = B + (A−B)·wB` + * from the pre-blend positions. When `wA + wB = 1` (the editor's case) the two converge to one point. + */ +class GlueTest { + /** A direct (deformer-less) one-vertex drawable resting at `(x, y)` - evaluates to world `(x, −y)`. */ + private fun pointDrawable(raw: String, x: Float, y: Float): Drawable { + val grid = KeyformGrid(emptyList(), listOf(KeyformCell(intArrayOf(), MeshDeltaForm(floatArrayOf(0f, 0f))))) + return Drawable( + id = DrawableId(raw), + name = raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(x, y), floatArrayOf(0f, 0f), IntArray(0)), + geometryGrid = grid, + ) + } + + private fun modelWith(a: Drawable, b: Drawable, glue: Glue) = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(a, b), + rootChildren = listOf(OrgChild.Drawable(a.id), OrgChild.Drawable(b.id)), + rootPartId = null, + glues = listOf(glue), + ) + + @Test + fun equalWeightsWeldToMidpoint() { + val model = + modelWith( + pointDrawable("A", 10f, 0f), + pointDrawable("B", 20f, 0f), + Glue(DrawableId("A"), DrawableId("B"), listOf(GluePair(0, 0, 0.5f, 0.5f))), + ) + val geometry = CpuDeformationEvaluator().evaluate(model, emptyMap()) + assertEquals(15f, geometry.worldPositions.getValue(DrawableId("A"))[0], 1e-4f) + assertEquals(15f, geometry.worldPositions.getValue(DrawableId("B"))[0], 1e-4f) + } + + @Test + fun complementaryWeightsConvergeToOnePoint() { + // wA + wB = 1 (the editor's seam case): A' and B' land on the exact same point. + val model = + modelWith( + pointDrawable("A", 10f, 4f), + pointDrawable("B", 22f, -8f), + Glue(DrawableId("A"), DrawableId("B"), listOf(GluePair(0, 0, 0.25f, 0.75f))), + ) + val geometry = CpuDeformationEvaluator().evaluate(model, emptyMap()) + val a = geometry.worldPositions.getValue(DrawableId("A")) + val b = geometry.worldPositions.getValue(DrawableId("B")) + assertEquals(a[0], b[0], 1e-4f) + assertEquals(a[1], b[1], 1e-4f) + assertEquals(13f, a[0], 1e-4f) // 10 + (22−10)·0.25 + } + + @Test + fun fullWeightSnapsOneSideOnly() { + // wA = 1 → A snaps onto B; wB = 0 → B stays put. + val model = + modelWith( + pointDrawable("A", 10f, 0f), + pointDrawable("B", 20f, 0f), + Glue(DrawableId("A"), DrawableId("B"), listOf(GluePair(0, 0, 1f, 0f))), + ) + val geometry = CpuDeformationEvaluator().evaluate(model, emptyMap()) + assertEquals(20f, geometry.worldPositions.getValue(DrawableId("A"))[0], 1e-4f) + assertEquals(20f, geometry.worldPositions.getValue(DrawableId("B"))[0], 1e-4f) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/KeyformBlendTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/KeyformBlendTest.kt new file mode 100644 index 0000000..b7d33e1 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/KeyformBlendTest.kt @@ -0,0 +1,21 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.Keyform +import kotlin.test.Test +import kotlin.test.assertEquals + +class KeyformBlendTest { + @Test + fun blendSumsWeightedDeltas() { + // base + 0.5*[2,4] + 1.0*[1,1] = [1+1+1, 1+2+1] = [3, 4] + val base = floatArrayOf(1f, 1f) + val keyforms = + listOf( + 0.5f to Keyform(atValue = 0f, delta = floatArrayOf(2f, 4f)), + 1.0f to Keyform(atValue = 1f, delta = floatArrayOf(1f, 1f)), + ) + val out = blend(base, keyforms) + assertEquals(3f, out[0]) + assertEquals(4f, out[1]) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/KeyformGridEvalTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/KeyformGridEvalTest.kt new file mode 100644 index 0000000..fcb87aa --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/KeyformGridEvalTest.kt @@ -0,0 +1,96 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.gridCorners +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Unit tests for the multilinear keyform blend on synthetic grids (no corpus): the snap/interpolate/ + * N-D/out-of-range behaviour of [gridCorners] and the cell reproduction of [sampleMeshLocal]. + */ +class KeyformGridEvalTest { + private val paramA = ParameterId("A") + private val paramB = ParameterId("B") + + private fun values(vararg pairs: Pair): (ParameterId) -> Float { + val map = pairs.toMap() + return { map[it] ?: 0f } + } + + @Test + fun snapsToTheNearestKey() { + val grid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(-1f, 0f, 1f))), emptyList()) + val corners = gridCorners(grid, values(paramA to 0f))!! + assertEquals(1, corners.size) + assertEquals(1, corners[0].linearIndex) // the middle key + assertEquals(1f, corners[0].weight) + } + + @Test + fun interpolatesBetweenTwoKeys() { + val grid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(-1f, 0f, 1f))), emptyList()) + val corners = gridCorners(grid, values(paramA to 0.5f))!!.sortedBy { it.linearIndex } + assertEquals(2, corners.size) + assertEquals(1, corners[0].linearIndex) + assertEquals(2, corners[1].linearIndex) + assertEquals(0.5f, corners[0].weight) + assertEquals(0.5f, corners[1].weight) + } + + @Test + fun foldsTwoAxesIntoFourWeightedCorners() { + val axes = listOf(KeyformAxis(paramA, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(paramB, floatArrayOf(-1f, 0f, 1f))) + val grid = KeyformGrid(axes, emptyList()) + val corners = gridCorners(grid, values(paramA to 0.5f, paramB to 0.5f))!! + assertEquals(4, corners.size) + corners.forEach { assertEquals(0.25f, it.weight) } + // coord (a,b) folds to a + b*3: the four cells surrounding (0.5, 0.5) are (1,1)(2,1)(1,2)(2,2). + assertEquals(setOf(4, 5, 7, 8), corners.map { it.linearIndex }.toSet()) + assertEquals(1f, corners.fold(0f) { acc, c -> acc + c.weight }) + } + + @Test + fun hidesWhenAParameterIsOutOfRange() { + val grid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(-1f, 0f, 1f))), emptyList()) + assertNull(gridCorners(grid, values(paramA to -2f))) + } + + @Test + fun reproducesAndInterpolatesCellForms() { + val cell0 = KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(10f, 0f))) + val cell1 = KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(20f, 0f))) + val cell2 = KeyformCell(intArrayOf(2), MeshDeltaForm(floatArrayOf(30f, 0f))) + val grid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(-1f, 0f, 1f))), listOf(cell0, cell1, cell2)) + val base = floatArrayOf(0f, 0f) + // At an exact key the output equals that cell's absolute form (base + delta). + assertEquals(listOf(10f, 0f), sampleMeshLocal(grid, base, values(paramA to -1f))!!.toList()) + assertEquals(listOf(30f, 0f), sampleMeshLocal(grid, base, values(paramA to 1f))!!.toList()) + // Midway, the linear blend of the two bracketing forms. + assertEquals(listOf(25f, 0f), sampleMeshLocal(grid, base, values(paramA to 0.5f))!!.toList()) + } + + @Test + fun directMeshBlendsThenNegatesY() { + val cell0 = KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(10f, 5f))) + val cell1 = KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(20f, 7f))) + val grid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(-1f, 1f))), listOf(cell0, cell1)) + val base = floatArrayOf(0f, 0f) + // At a key: world = (formX, -formY) - only Y flips. + assertEquals(listOf(10f, -5f), evalDirectMeshWorld(grid, base, values(paramA to -1f))!!.toList()) + // Midway: blend (x=15, y=6) then negate Y -> (15, -6). + assertEquals(listOf(15f, -6f), evalDirectMeshWorld(grid, base, values(paramA to 0f))!!.toList()) + } + + @Test + fun directMeshHiddenWhenOutOfRange() { + val cell = KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(10f, 5f))) + val grid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(-1f, 1f))), listOf(cell)) + assertNull(evalDirectMeshWorld(grid, floatArrayOf(0f, 0f), values(paramA to 5f))) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/PartCompositeEvalTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/PartCompositeEvalTest.kt new file mode 100644 index 0000000..2223cc3 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/PartCompositeEvalTest.kt @@ -0,0 +1,295 @@ +package org.umamo.render.eval + +import org.umamo.runtime.eval.colorAt +import org.umamo.runtime.eval.scalarAt +import org.umamo.runtime.eval.scalarOrNull +import org.umamo.runtime.keyform.fanOutMesh +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the isolated part channel eval on synthetic tracks: the per-channel multilinear blend, the + * out-of-range fallback to the owner's statics, and [preparePose]'s aggregation into + * [PoseDeformInputs.partCompositeStates]. + */ +class PartCompositeEvalTest { + private val paramA = ParameterId("A") + + private fun values(vararg pairs: Pair): (ParameterId) -> Float { + val map = pairs.toMap() + return { map[it] ?: 0f } + } + + /** A two-key scalar track on paramA. */ + private fun scalarTrack(low: Float, high: Float): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(low)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(high)), + ), + ) + + /** A two-key color track on paramA. */ + private fun colorTrack(low: ColorRgb, high: ColorRgb): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Color(low)), + KeyformCell(intArrayOf(1), ChannelValue.Color(high)), + ), + ) + + /** The composite channels as independent tracks - what one bundled part grid fans out into. */ + private fun compositeChannels(): ChannelGrids = + ChannelGrids( + mapOf( + FormChannel.DRAW_ORDER to scalarTrack(500f, 500f), + FormChannel.OPACITY to scalarTrack(1f, 0.5f), + FormChannel.MULTIPLY_COLOR to colorTrack(ColorRgb(1f, 1f, 1f), ColorRgb(0f, 0.5f, 1f)), + FormChannel.SCREEN_COLOR to colorTrack(ColorRgb(0f, 0f, 0f), ColorRgb(1f, 0.5f, 0f)), + ), + ) + + private val staticComposite = + PartComposite( + opacity = 0.3f, + multiplyColor = ColorRgb(0.1f, 0.2f, 0.3f), + screenColor = ColorRgb(0.4f, 0.5f, 0.6f), + ) + + @Test + fun blendsEveryChannelWithTheGridWeights() { + val channels = compositeChannels() + val pose = values(paramA to 0.5f) + assertEquals(0.75f, channels.scalarAt(FormChannel.OPACITY, staticComposite.opacity, pose), "opacity midpoint") + assertEquals( + ColorRgb(0.5f, 0.75f, 1f), + channels.colorAt(FormChannel.MULTIPLY_COLOR, staticComposite.multiplyColor, pose), + "multiply midpoint", + ) + assertEquals( + ColorRgb(0.5f, 0.25f, 0f), + channels.colorAt(FormChannel.SCREEN_COLOR, staticComposite.screenColor, pose), + "screen midpoint", + ) + } + + @Test + fun snapsToAKeyExactly() { + val channels = compositeChannels() + val pose = values(paramA to 1f) + assertEquals(0.5f, channels.scalarAt(FormChannel.OPACITY, staticComposite.opacity, pose)) + assertEquals(ColorRgb(0f, 0.5f, 1f), channels.colorAt(FormChannel.MULTIPLY_COLOR, staticComposite.multiplyColor, pose)) + assertEquals(ColorRgb(1f, 0.5f, 0f), channels.colorAt(FormChannel.SCREEN_COLOR, staticComposite.screenColor, pose)) + } + + /** + * Out of range a channel falls back to its owner's static value and NEVER hides. Hiding is the + * geometry grid's decision alone - a part has no geometry, and making a keyed opacity able to hide art + * would turn keying opacity on a narrow parameter into a disappearing act at the slider's ends. + */ + @Test + fun outOfRangeChannelsFallBackToTheirStatics() { + val channels = compositeChannels() + val pose = values(paramA to -1f) + assertEquals(staticComposite.opacity, channels.scalarAt(FormChannel.OPACITY, staticComposite.opacity, pose)) + assertEquals(staticComposite.multiplyColor, channels.colorAt(FormChannel.MULTIPLY_COLOR, staticComposite.multiplyColor, pose)) + // The nullable read still reports absence, which is what keeps the part draw-order map sparse. + assertNull(channels.scalarOrNull(FormChannel.DRAW_ORDER, pose)) + } + + private fun modelWithIsolatedPart(channelGrids: ChannelGrids): PuppetModel { + val part = + Part( + id = PartId("fx"), + name = "fx", + children = emptyList(), + groupMode = PartGroupMode.Isolated, + composite = staticComposite, + channelGrids = channelGrids, + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = listOf(part), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(part.id)), + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ).withDerivedRenderRoot() + } + + @Test + fun preparePoseBlendsAGriddedIsolatedPart() { + val inputs = preparePose(modelWithIsolatedPart(compositeChannels()), mapOf(paramA to 0.5f)) + val state = assertNotNull(inputs.partCompositeStates[PartId("fx")], "isolated part carries a state") + assertEquals(0.75f, state.opacity) + assertEquals(ColorRgb(0.5f, 0.75f, 1f), state.multiplyColor) + } + + @Test + fun preparePoseFallsBackToStaticChannelsWithoutAGrid() { + val inputs = preparePose(modelWithIsolatedPart(ChannelGrids.Empty), emptyMap()) + val state = assertNotNull(inputs.partCompositeStates[PartId("fx")]) + assertEquals(0.3f, state.opacity, "PartComposite static opacity") + assertEquals(ColorRgb(0.1f, 0.2f, 0.3f), state.multiplyColor) + assertEquals(ColorRgb(0.4f, 0.5f, 0.6f), state.screenColor) + } + + @Test + fun preparePoseFallsBackToStaticChannelsOutOfRange() { + // The controlling axis sits below the grid's key range → the grid sample hides, and the + // composite falls back to the static channels (mirroring the part draw-order fallback). + val inputs = preparePose(modelWithIsolatedPart(compositeChannels()), mapOf(paramA to -1f)) + val state = assertNotNull(inputs.partCompositeStates[PartId("fx")]) + assertEquals(0.3f, state.opacity) + } + + @Test + fun preparePoseLeavesNonIsolatedPartsOutOfTheMap() { + val plain = + modelWithIsolatedPart(ChannelGrids.Empty) + .let { source -> source.copy(parts = source.parts.map { it.copy(groupMode = PartGroupMode.Grouped) }) } + .withDerivedRenderRoot() + assertTrue(preparePose(plain, emptyMap()).partCompositeStates.isEmpty()) + } + + private fun drawable(id: String, ownOpacity: Float): Drawable { + val positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f) + val fanned = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshForm(FloatArray(positions.size), opacity = ownOpacity))), + ).fanOutMesh() + return Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2)), + // Bundled then fanned, so the fixture matches importer output and the opacity lands on its + // own track rather than being hand-placed. + geometryGrid = fanned.geometry, + channelGrids = fanned.channels, + ) + } + + /** A part with a static (grid-less) opacity, so the cascade reads it off PartComposite. */ + private fun partWith(id: String, mode: PartGroupMode, opacity: Float, children: List): Part = + Part(id = PartId(id), name = id, children = children, groupMode = mode, composite = PartComposite(opacity = opacity)) + + private fun cascadeModel(parts: List, drawables: List, rootChildren: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = parts, + deformers = emptyList(), + drawables = drawables, + rootChildren = rootChildren, + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ).withDerivedRenderRoot() + + /** The pose-resolved opacity of drawable [id] in [model] at the default pose. */ + private fun drawableOpacity(model: PuppetModel, id: String): Float = + preparePose(model, emptyMap()).drawables.first { it.drawableId == DrawableId(id) }.opacity + + @Test + fun nonIsolatedPartOpacityDoesNotCascadeToItsDrawables() { + // Cubism only exposes/applies a part's composite opacity while it is Isolated (offscreen drawing); + // a Grouped or PassThrough part's latent composite.opacity is stored but never rendered. + val part = partWith("grp", PartGroupMode.Grouped, opacity = 0.5f, children = listOf(OrgChild.Drawable(DrawableId("d")))) + val model = cascadeModel(listOf(part), listOf(drawable("d", ownOpacity = 0.8f)), listOf(OrgChild.Part(PartId("grp")))) + assertEquals(0.8f, drawableOpacity(model, "d"), 1e-6f, "own opacity only; the non-isolated part's composite opacity is inert") + } + + @Test + fun isolatedPartOpacityDoesNotCascadeToDrawables() { + // An isolated part applies its opacity at the composite pass, so its drawable keeps its own opacity + // (the part's 0.5 shows up in partCompositeStates instead - covered above). + val part = partWith("fx", PartGroupMode.Isolated, opacity = 0.5f, children = listOf(OrgChild.Drawable(DrawableId("d")))) + val model = cascadeModel(listOf(part), listOf(drawable("d", ownOpacity = 0.8f)), listOf(OrgChild.Part(PartId("fx")))) + assertEquals(0.8f, drawableOpacity(model, "d"), 1e-6f, "isolated part opacity rides its composite, not the drawable") + } + + @Test + fun nestedNonIsolatedPartOpacitiesDoNotCascade() { + val inner = partWith("inner", PartGroupMode.Grouped, opacity = 0.5f, children = listOf(OrgChild.Drawable(DrawableId("d")))) + val outer = partWith("outer", PartGroupMode.PassThrough, opacity = 0.5f, children = listOf(OrgChild.Part(PartId("inner")))) + val model = cascadeModel(listOf(outer, inner), listOf(drawable("d", ownOpacity = 1f)), listOf(OrgChild.Part(PartId("outer")))) + assertEquals(1f, drawableOpacity(model, "d"), 1e-6f, "neither non-isolated part's opacity applies") + } + + @Test + fun drawableKeyformColorResolvesInPreparePose() { + // The 5.3 per-art-mesh multiply/screen colors ride their own channel tracks; preparePose must blend + // them onto DrawableDeformInputs so the renderer can tint (a GL-independent proof of the resolve). + val positions = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f) + val fanned = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf( + KeyformCell( + intArrayOf(0), + MeshForm(FloatArray(positions.size), multiplyColor = ColorRgb(1f, 0f, 0f), screenColor = ColorRgb(0f, 0f, 0.5f)), + ), + ), + ).fanOutMesh() + val drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2)), + geometryGrid = fanned.geometry, + channelGrids = fanned.channels, + ) + val model = cascadeModel(emptyList(), listOf(drawable), listOf(OrgChild.Drawable(DrawableId("d")))) + val resolved = preparePose(model, emptyMap()).drawables.first { it.drawableId == DrawableId("d") } + assertEquals(ColorRgb(1f, 0f, 0f), resolved.multiplyColor) + assertEquals(ColorRgb(0f, 0f, 0.5f), resolved.screenColor) + } + + @Test + fun nonIsolatedAncestorOpacityDoesNotReachAnIsolatedChild() { + // Neither the non-isolated outer part's opacity nor the isolated inner part's opacity (which rides + // its own composite pass) touches the drawable directly. + val inner = partWith("fx", PartGroupMode.Isolated, opacity = 0.5f, children = listOf(OrgChild.Drawable(DrawableId("d")))) + val outer = partWith("outer", PartGroupMode.Grouped, opacity = 0.5f, children = listOf(OrgChild.Part(PartId("fx")))) + val model = cascadeModel(listOf(outer, inner), listOf(drawable("d", ownOpacity = 1f)), listOf(OrgChild.Part(PartId("outer")))) + assertEquals(1f, drawableOpacity(model, "d"), 1e-6f, "outer's composite opacity is inert; inner's rides its composite") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/RenderOrderTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/RenderOrderTest.kt new file mode 100644 index 0000000..6ab587a --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/RenderOrderTest.kt @@ -0,0 +1,234 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs + +/** + * Verifies [paintOrder]: drawOrder is the primary key, the parts-tree base order breaks ties. This is + * the unit-test stand-in for the official editor (which we can't re-save under its EULA) - the + * Layer68→600 case is `higherDrawOrderPaintsInFront`. + */ +class RenderOrderTest { + private fun id(name: String) = DrawableId(name) + + @Test + fun equalDrawOrderKeepsPartsTreeBaseOrder() { + val base = listOf(id("a"), id("b"), id("c")) + val order = paintOrder(base, base.associateWith { 500f }) + assertEquals(base, order) + } + + @Test + fun higherDrawOrderPaintsInFront() { + // Layer68 → 600: a backmost drawable raised above the default 500s paints last (frontmost), + // regardless of which part it lives in. + val base = listOf(id("a"), id("b"), id("c")) + val order = paintOrder(base, mapOf(id("a") to 600f, id("b") to 500f, id("c") to 500f)) + assertEquals(listOf(id("b"), id("c"), id("a")), order) + } + + @Test + fun lowerDrawOrderPaintsBehind() { + val base = listOf(id("a"), id("b"), id("c")) + val order = paintOrder(base, mapOf(id("a") to 500f, id("b") to 500f, id("c") to 400f)) + assertEquals(listOf(id("c"), id("a"), id("b")), order) + } + + @Test + fun missingDrawOrderTreatedAsCubismDefault() { + val base = listOf(id("a"), id("b")) + // b has no entry → DEFAULT_DRAW_ORDER (500) < a's 600, so b stays behind a. + val order = paintOrder(base, mapOf(id("a") to 600f)) + assertEquals(listOf(id("b"), id("a")), order) + } + + @Test + fun subIntegerDrawOrderNoiseDoesNotReorder() { + // The keyform blend `Σ wᵢ·500` lands just off 500.0 due to float-summation noise, so a + // raw-float sort reshuffles drawables that should be tied. Quantising `+0.001`→int collapses + // the noise to a true 500 tie, preserving the parts-tree base order. Without quantising, + // `sortedBy` would order c (499.99997) < a (500.0) < b (500.00003) and lift c in front of the rest. + val base = listOf(id("a"), id("b"), id("c")) + val order = paintOrder(base, mapOf(id("a") to 500f, id("b") to 500.00003f, id("c") to 499.99997f)) + assertEquals(base, order) + } + + @Test + fun fractionalDrawOrderFloorsLikeCubism() { + // Cubism floors `(int)(0.001 + order)`, so 500.6 and 500.9 are still 500 (tie → base order kept), + // and only a full integer step (502) actually moves a drawable. + val base = listOf(id("a"), id("b"), id("c")) + val order = paintOrder(base, mapOf(id("a") to 500.6f, id("b") to 500.9f, id("c") to 502f)) + assertEquals(listOf(id("a"), id("b"), id("c")), order) + } + + @Test + fun drawOrderGroupConfinesChildrenToTheGroupSlot() { + // An "eye" group (part draw order 600) holds two eye drawables; the root also holds + // back/mid/front drawables. A flat global sort would slot mid (550) BETWEEN eyeLow (510) and + // eyeHigh (590); the group must keep the eyes contiguous at the group's 600 slot, so mid stays + // before the whole group. Within the group the eyes still sort by their own order (510 < 590). + val root = + RenderGroup( + partId = null, + drawOrder = 500, + children = + listOf( + RenderDrawable(id("back")), + RenderDrawable(id("mid")), + RenderGroup(null, 600, listOf(RenderDrawable(id("eyeHigh")), RenderDrawable(id("eyeLow")))), + RenderDrawable(id("front")), + ), + ) + val drawOrders = + mapOf( + id("back") to 100f, + id("mid") to 550f, + id("eyeLow") to 510f, + id("eyeHigh") to 590f, + id("front") to 900f, + ) + val order = renderOrder(root, drawOrders) + assertEquals(listOf(id("back"), id("mid"), id("eyeLow"), id("eyeHigh"), id("front")), order) + + // A flat sort would interleave mid between the eyes - the divergence the group fixes. + val flat = paintOrder(order, drawOrders).map { it.raw } + assertEquals(listOf("back", "eyeLow", "mid", "eyeHigh", "front"), flat) + } + + @Test + fun flatGroupMatchesGlobalPaintOrder() { + // A group-less model is one flat RenderGroup, so renderOrder reduces exactly to paintOrder. + val ids = listOf(id("a"), id("b"), id("c")) + val root = RenderGroup(null, 500, ids.map { RenderDrawable(it) }) + val drawOrders = mapOf(id("a") to 600f, id("b") to 500f, id("c") to 500f) + assertEquals(paintOrder(ids, drawOrders), renderOrder(root, drawOrders)) + } + + @Test + fun isolatedGroupBecomesAPlanBoundaryAndPlainGroupsFlatten() { + // The fx part is isolated → it must survive as a RenderPlanComposite node (the renderer needs + // the subtree span to composite it as one layer); the plain 700-group stays transparent in the + // plan exactly as it always was in the flat order. + val root = + RenderGroup( + partId = null, + drawOrder = 500, + children = + listOf( + RenderDrawable(id("back")), + RenderGroup( + PartId("fx"), + 600, + listOf(RenderDrawable(id("fxHigh")), RenderDrawable(id("fxLow"))), + ChannelGrids.Empty, + PartComposite(), + ), + RenderGroup(null, 700, listOf(RenderDrawable(id("plain")))), + RenderDrawable(id("front")), + ), + ) + val drawOrders = + mapOf( + id("back") to 100f, + id("fxLow") to 510f, + id("fxHigh") to 590f, + id("plain") to 500f, + id("front") to 900f, + ) + val plan = renderPlan(root, drawOrders) + assertEquals(4, plan.size, "back, the composite node, plain (flattened), front") + assertEquals(id("back"), assertIs(plan[0]).id) + val compositeNode = assertIs(plan[1]) + assertEquals(PartId("fx"), compositeNode.partId) + assertEquals( + listOf(id("fxLow"), id("fxHigh")), + compositeNode.children.map { assertIs(it).id }, + "the subtree still sorts internally by drawable order", + ) + assertEquals(id("plain"), assertIs(plan[2]).id) + assertEquals(id("front"), assertIs(plan[3]).id) + // The flat order is exactly the plan flattened - one sort implementation, two views. + assertEquals(renderOrder(root, drawOrders), flattenRenderPlan(plan)) + } + + @Test + fun nestedIsolatedGroupsNestInThePlan() { + val inner = + RenderGroup(PartId("inner"), 500, listOf(RenderDrawable(id("leaf"))), ChannelGrids.Empty, PartComposite()) + val outer = + RenderGroup( + PartId("outer"), + 600, + listOf(RenderDrawable(id("sibling")), inner), + ChannelGrids.Empty, + PartComposite(), + ) + val root = RenderGroup(null, 500, listOf(RenderDrawable(id("back")), outer)) + val plan = renderPlan(root, mapOf(id("back") to 100f, id("sibling") to 400f, id("leaf") to 500f)) + val outerNode = assertIs(plan[1]) + assertEquals(PartId("outer"), outerNode.partId) + val innerNode = assertIs(outerNode.children[1]) + assertEquals(PartId("inner"), innerNode.partId) + assertEquals(id("leaf"), assertIs(innerNode.children.single()).id) + } + + @Test + fun animatedPartDrawOrderMovesAnIsolatedBoundary() { + // An isolated group is still a draw-order group: its parameter-driven part order moves the + // whole boundary node through the sibling order. + val root = + RenderGroup( + partId = null, + drawOrder = 500, + children = + listOf( + RenderDrawable(id("back")), + RenderGroup( + PartId("fx"), + 500, + listOf(RenderDrawable(id("fxA"))), + ChannelGrids.Empty, + PartComposite(), + ), + RenderDrawable(id("front")), + ), + ) + val drawOrders = mapOf(id("back") to 100f, id("fxA") to 500f, id("front") to 900f) + val behind = renderPlan(root, drawOrders, mapOf(PartId("fx") to 300f)) + assertIs(behind[1], "part order 300 keeps the composite behind front") + val front = renderPlan(root, drawOrders, mapOf(PartId("fx") to 950f)) + assertIs(front[2], "part order 950 lifts the whole composite frontmost") + } + + @Test + fun animatedPartDrawOrderMovesTheWholeGroup() { + // A sub-group's sort key is its (parameter-driven) PART draw order, so the whole arm set swaps + // front/back as the arm parameter moves it 400↔700, without re-sorting its members. + val root = + RenderGroup( + partId = null, + drawOrder = 500, + children = + listOf( + RenderDrawable(id("back")), + RenderGroup(PartId("arm"), 500, listOf(RenderDrawable(id("armA")), RenderDrawable(id("armB")))), + RenderDrawable(id("front")), + ), + ) + val drawOrders = mapOf(id("back") to 100f, id("armA") to 500f, id("armB") to 500f, id("front") to 900f) + + // Part order 300 → the arm group sits behind front (900); 950 → it jumps in front of everything. + val behind = renderOrder(root, drawOrders, mapOf(PartId("arm") to 300f)) + assertEquals(listOf(id("back"), id("armA"), id("armB"), id("front")), behind) + val front = renderOrder(root, drawOrders, mapOf(PartId("arm") to 950f)) + assertEquals(listOf(id("back"), id("front"), id("armA"), id("armB")), front) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/eval/UnkeyedDrawableRenderTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/eval/UnkeyedDrawableRenderTest.kt new file mode 100644 index 0000000..a87ae00 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/eval/UnkeyedDrawableRenderTest.kt @@ -0,0 +1,96 @@ +package org.umamo.render.eval + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Pins that an UNKEYED drawable renders at its rest mesh instead of vanishing, and that this stays + * distinguishable from the genuinely hidden case. + * + * Keyform authoring makes "unkeyed" a normal state - a drawable that has never been bound to a parameter, + * or one whose last axis was just removed - so a drawable with no grid has to be visible or the rigger + * cannot see the thing they are about to key. Before this, preparePose skipped any drawable with a null + * grid outright and the renderer never even uploaded it. + * + * The two null-ish states are opposites and must not collapse into one: NO GRID means render at rest, + * while a keyed grid whose pose falls outside its key range means hide. + */ +class UnkeyedDrawableRenderTest { + private val paramA = ParameterId("A") + private val drawableId = DrawableId("M") + + private fun mesh(): DrawableMesh = DrawableMesh(floatArrayOf(10f, 5f, 20f, 7f), FloatArray(0), intArrayOf(0, 1, 0)) + + private fun model(drawable: Drawable): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + + /** With no keyform grid at all the drawable still deforms - to exactly its rest mesh (Y negated). */ + @Test + fun anUnkeyedDrawableRendersItsRestMesh() { + val drawable = Drawable(drawableId, "M", null, BlendMode.Normal, emptyList(), mesh(), geometryGrid = null) + val geometry = CpuDeformationEvaluator().evaluate(model(drawable), emptyMap()) + val positions = + assertNotNull(geometry.worldPositions[drawableId], "an unkeyed drawable must still produce geometry") + assertEquals(listOf(10f, -5f, 20f, -7f), positions.toList()) + } + + /** An unkeyed drawable takes the Cubism default scalars rather than being dropped from the pose. */ + @Test + fun anUnkeyedDrawableTakesDefaultScalars() { + val drawable = Drawable(drawableId, "M", null, BlendMode.Normal, emptyList(), mesh(), geometryGrid = null) + val geometry = CpuDeformationEvaluator().evaluate(model(drawable), emptyMap()) + assertEquals(1f, geometry.opacity[drawableId]) + assertEquals(DEFAULT_DRAW_ORDER.toFloat(), geometry.drawOrder[drawableId]) + } + + /** + * A KEYED drawable whose pose is outside its key range is still hidden. This is the case that must not + * be confused with the one above - out of range is a deliberate authoring device (the toggle-part + * pattern), and turning it into "render at rest" would make hidden art reappear. + */ + @Test + fun anOutOfRangeKeyedDrawableStaysHidden() { + val grid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0.5f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(4))), + KeyformCell(intArrayOf(1), MeshDeltaForm(FloatArray(4))), + ), + ) + val drawable = Drawable(drawableId, "M", null, BlendMode.Normal, emptyList(), mesh(), geometryGrid = grid) + // The parameter defaults to 0, below the axis's first key of 0.5. + val geometry = CpuDeformationEvaluator().evaluate(model(drawable), emptyMap()) + assertNull(geometry.worldPositions[drawableId], "a pose outside the key range still hides the drawable") + } + + /** The gizmo's local-posed read falls back to the rest mesh too, so an unkeyed drawable is editable. */ + @Test + fun localPosedFallsBackToTheRestMesh() { + val drawable = Drawable(drawableId, "M", null, BlendMode.Normal, emptyList(), mesh(), geometryGrid = null) + val local = assertNotNull(drawableLocalPosed(model(drawable), emptyMap(), drawableId)) + assertEquals(listOf(10f, 5f, 20f, 7f), local.toList(), "local space is the rest mesh, un-negated") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/pick/PickerTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/pick/PickerTest.kt new file mode 100644 index 0000000..82e64dc --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/pick/PickerTest.kt @@ -0,0 +1,217 @@ +package org.umamo.render.pick + +import org.umamo.runtime.model.DrawableId +import kotlin.math.sqrt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the pure picking math: point-in-triangle, barycentric weights, front-most-by-paint-order + * ranking, the atlas-alpha coverage gate, the front-to-back candidate list, and centrality scoring. + * All pure — alpha is supplied by an injected lambda, so no GL or textures are needed. + */ +class PickerTest { + // A unit square at the origin, two triangles; UVs equal the positions (already in [0,1]). + private val squarePositions = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f) + private val squareUvs = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f) + private val squareIndices = intArrayOf(0, 1, 2, 0, 2, 3) + + // An always-opaque sampler for the geometry-only cases. + private val opaque: (DrawableId, Float, Float) -> Float = { _, _, _ -> 1f } + + /** + * A point well inside a triangle is contained. + */ + @Test + fun pointInsideTriangle() { + assertTrue(pointInTriangle(0.25f, 0.25f, 0f, 0f, 1f, 0f, 0f, 1f)) + } + + /** + * A point outside the triangle is not contained. + */ + @Test + fun pointOutsideTriangle() { + assertFalse(pointInTriangle(0.9f, 0.9f, 0f, 0f, 1f, 0f, 0f, 1f)) + } + + /** + * A point exactly on an edge counts as contained, and winding order does not matter. + */ + @Test + fun pointOnEdgeIsInsideRegardlessOfWinding() { + assertTrue(pointInTriangle(0.5f, 0.5f, 0f, 0f, 1f, 0f, 0f, 1f)) + assertTrue(pointInTriangle(0.25f, 0.25f, 0f, 1f, 1f, 0f, 0f, 0f)) + } + + /** + * A degenerate (collinear) triangle contains points on its span but rejects points off the line. + */ + @Test + fun degenerateTriangle() { + assertTrue(pointInTriangle(0.5f, 0f, 0f, 0f, 1f, 0f, 2f, 0f)) + assertFalse(pointInTriangle(0.5f, 0.5f, 0f, 0f, 1f, 0f, 2f, 0f)) + } + + /** + * Barycentric weights sum to 1, give a unit weight at a vertex, and fall back to thirds when + * degenerate. + */ + @Test + fun barycentricWeightsBasics() { + val centroid = barycentricWeights(1f / 3f, 1f / 3f, 0f, 0f, 1f, 0f, 0f, 1f) + assertEquals(1f, centroid[0] + centroid[1] + centroid[2], 1e-4f) + + val atFirst = barycentricWeights(0f, 0f, 0f, 0f, 1f, 0f, 0f, 1f) + assertEquals(1f, atFirst[0], 1e-4f) + assertEquals(0f, atFirst[1], 1e-4f) + assertEquals(0f, atFirst[2], 1e-4f) + + val degenerate = barycentricWeights(0.5f, 0.5f, 0f, 0f, 0f, 0f, 0f, 0f) + assertEquals(1f / 3f, degenerate[0], 1e-4f) + } + + /** + * A point inside a single opaque drawable's mesh picks that drawable. + */ + @Test + fun picksContainingDrawable() { + val id = DrawableId("square") + val hit = + pickDrawable( + 0.5f, + 0.5f, + mapOf(id to squarePositions), + mapOf(id to squareIndices), + mapOf(id to squareUvs), + mapOf(id to 0f), + opaque, + ) + assertEquals(id, hit) + } + + /** + * A point outside every mesh picks nothing. + */ + @Test + fun pointOutsideAllReturnsNull() { + val id = DrawableId("square") + val hit = + pickDrawable( + 5f, + 5f, + mapOf(id to squarePositions), + mapOf(id to squareIndices), + mapOf(id to squareUvs), + mapOf(id to 0f), + opaque, + ) + assertNull(hit) + } + + /** + * Among overlapping opaque drawables, the highest front-rank (the renderer's resolved paint order, + * front = higher) wins — not the raw draw-order scalar, which ignores the group hierarchy. + */ + @Test + fun overlappingPicksHighestFrontRank() { + val under = DrawableId("under") + val over = DrawableId("over") + val hit = + pickDrawable( + 0.5f, + 0.5f, + mapOf(under to squarePositions, over to squarePositions), + mapOf(under to squareIndices, over to squareIndices), + mapOf(under to squareUvs, over to squareUvs), + mapOf(under to 3f, over to 7f), // over is drawn later (more front) + opaque, + ) + assertEquals(over, hit) + } + + /** + * A click on a transparent texel is rejected: the front mesh is transparent there, so the opaque mesh + * behind it is picked. Inverting the alpha picks the front one. + */ + @Test + fun transparentOverhangRejectedSoBehindWins() { + val front = DrawableId("front") + val back = DrawableId("back") + val positions = mapOf(front to squarePositions, back to squarePositions) + val indices = mapOf(front to squareIndices, back to squareIndices) + val uvs = mapOf(front to squareUvs, back to squareUvs) + val rank = mapOf(front to 9f, back to 1f) // front is more front, but transparent here + + val frontTransparent: (DrawableId, Float, Float) -> Float = { id, _, _ -> if (id == front) 0f else 1f } + assertEquals(back, pickDrawable(0.5f, 0.5f, positions, indices, uvs, rank, frontTransparent)) + + val frontOpaque: (DrawableId, Float, Float) -> Float = { id, _, _ -> if (id == front) 1f else 1f } + assertEquals(front, pickDrawable(0.5f, 0.5f, positions, indices, uvs, rank, frontOpaque)) + } + + /** + * A drawable not in the front-rank map (not drawn this frame) is skipped. + */ + @Test + fun drawableAbsentFromFrontRankSkipped() { + val id = DrawableId("ghost") + val hit = + pickDrawable( + 0.5f, + 0.5f, + mapOf(id to squarePositions), + mapOf(id to squareIndices), + mapOf(id to squareUvs), + emptyMap(), // not drawn → no rank + opaque, + ) + assertNull(hit) + } + + /** + * pickAllDrawables returns every opaque candidate front-to-back; a fully transparent one is absent. + */ + @Test + fun pickAllIsFrontToBackAndAlphaGated() { + val back = DrawableId("back") + val mid = DrawableId("mid") + val front = DrawableId("front") + val positions = mapOf(back to squarePositions, mid to squarePositions, front to squarePositions) + val indices = mapOf(back to squareIndices, mid to squareIndices, front to squareIndices) + val uvs = mapOf(back to squareUvs, mid to squareUvs, front to squareUvs) + val rank = mapOf(back to 0f, mid to 1f, front to 2f) + // mid is transparent at the click, so it drops out. + val sampler: (DrawableId, Float, Float) -> Float = { id, _, _ -> if (id == mid) 0f else 1f } + + val candidates = + pickAllDrawables(0.5f, 0.5f, positions, indices, uvs, rank, atlasSizeOf = { null }, sampleAlpha = sampler) + + assertEquals(listOf(front, back), candidates.map { it.id }) // front-to-back, mid gated out + assertTrue(candidates.all { it.centrality == 1f }) // untextured (null atlas size) ⇒ full centrality + } + + /** + * Centrality is higher for a hit deep in the opaque region than for one near a transparent boundary. + */ + @Test + fun centralityDeepBeatsBoundary() { + val id = DrawableId("art") + val centerU = 0.5f + val centerV = 0.5f + val radiusUv = 40f / 256f // opaque disc of ~40 texels radius on a 256² atlas + val discField: (DrawableId, Float, Float) -> Float = { _, u, v -> + val du = u - centerU + val dv = v - centerV + if (sqrt(du * du + dv * dv) <= radiusUv) 1f else 0f + } + + val deep = centralityAt(id, centerU, centerV, 256, 256, discField) + val nearEdge = centralityAt(id, centerU + 35f / 256f, centerV, 256, 256, discField) + + assertTrue(deep > nearEdge, "a central hit ($deep) should score above a near-boundary hit ($nearEdge)") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/pick/RegionPickTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/pick/RegionPickTest.kt new file mode 100644 index 0000000..04ac0ea --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/pick/RegionPickTest.kt @@ -0,0 +1,69 @@ +package org.umamo.render.pick + +import org.umamo.runtime.model.DrawableId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Verifies the pure Object-mode region enclosure: centroids reduce a drawable to a single test point, and box + * / circle enclosure select exactly the drawables whose centroid falls inside - including the decisive case + * that a large layer whose centroid sits outside a grazing region is NOT grabbed (centroid-inside, not + * any-vertex-touching). + */ +class RegionPickTest { + // A small square drawable centerd at (1, 1). + private fun square(): FloatArray = floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f, 2f, 2f) + + // A full-canvas layer spanning (-100, -100)..(100, 100); its centroid is the origin. + private fun canvasLayer(): FloatArray = floatArrayOf(-100f, -100f, 100f, -100f, -100f, 100f, 100f, 100f) + + /** A drawable's centroid is the mean of its interleaved vertices; an empty array is skipped. */ + @Test + fun centroidIsVertexMean() { + val centroids = drawableCentroids(mapOf(DrawableId("s") to square(), DrawableId("blank") to FloatArray(0))) + assertEquals(1f, centroids.getValue(DrawableId("s"))[0], "centroid x") + assertEquals(1f, centroids.getValue(DrawableId("s"))[1], "centroid y") + assertTrue(DrawableId("blank") !in centroids, "an empty array has no centroid") + } + + /** Box select selects a drawable whose centroid is inside and excludes one whose centroid is outside. */ + @Test + fun boxSelectsByCentroid() { + val centroids = drawableCentroids(mapOf(DrawableId("in") to square(), DrawableId("out") to canvasLayer())) + // A box around (1,1) that does NOT contain the origin. + val enclosed = drawablesInBox(centroids, minX = 0.5f, minY = 0.5f, maxX = 1.5f, maxY = 1.5f) + assertEquals(setOf(DrawableId("in")), enclosed, "only the drawable centerd in the box is selected") + } + + /** A box grazing a full-canvas layer's edge does not grab it - its centroid (the origin) is far outside. */ + @Test + fun grazingBoxDoesNotGrabFullCanvasLayer() { + val centroids = drawableCentroids(mapOf(DrawableId("canvas") to canvasLayer())) + // A box in the top-right corner that overlaps the layer's geometry but not its centroid at the origin. + val enclosed = drawablesInBox(centroids, minX = 50f, minY = 50f, maxX = 90f, maxY = 90f) + assertTrue(enclosed.isEmpty(), "centroid-inside means a grazing box does not select the whole layer") + } + + /** Circle select selects by centroid-within-radius; a centroid outside the disc is excluded. */ + @Test + fun circleSelectsByCentroidWithinRadius() { + // "near" centroid (1,1) sits at distance sqrt(2) ~= 1.41 from (1,1)'s... the canvas centroid is the origin. + val centroids = drawableCentroids(mapOf(DrawableId("near") to square(), DrawableId("far") to canvasLayer())) + + // Center at (1,1), radius 0.5: the square's centroid (1,1) is inside, the origin (distance ~1.41) is not. + assertEquals(setOf(DrawableId("near")), drawablesInCircle(centroids, centerX = 1f, centerY = 1f, radius = 0.5f)) + + // A radius of 1.5 (> the ~1.41 distance to the origin) also encloses the canvas layer's centroid. + val reaching = drawablesInCircle(centroids, centerX = 1f, centerY = 1f, radius = 1.5f) + assertTrue(DrawableId("far") in reaching, "a centroid within the radius is enclosed") + assertTrue(DrawableId("near") in reaching, "the closer centroid is enclosed too") + } + + /** Empty geometry encloses nothing. */ + @Test + fun emptyGeometryEnclosesNothing() { + assertTrue(drawablesInBox(emptyMap(), 0f, 0f, 1f, 1f).isEmpty()) + assertTrue(drawablesInCircle(emptyMap(), 0f, 0f, 1f).isEmpty()) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/pick/ScreenSpacePickTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/pick/ScreenSpacePickTest.kt new file mode 100644 index 0000000..9d9e9d9 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/pick/ScreenSpacePickTest.kt @@ -0,0 +1,137 @@ +package org.umamo.render.pick + +import org.umamo.render.ViewportCamera +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the pure screen-space geometry the gizmo overlays (and the future UV editor) pick with: + * the world-to-screen projection and its inverse, nearest-within-radius vertex and edge hit tests, + * the centroid tie-break for overlapping faces, and the box / circle enclosure rules (vertex inside, + * edge both-endpoints / segment-overlap, face by centroid). + */ +class ScreenSpacePickTest { + private val viewportWidth = 400 + private val viewportHeight = 300 + + // A centered 1:1 camera: world (0, 0) projects to screen (200, 150) and one world unit is one pixel. + private val camera = ViewportCamera(0f, 0f, 1f) + + // A unit-quad-scaled mesh: v0 bottom-left origin, v1 right, v2 up, v3 diagonal (world y is up). + // Screens at the fixed camera: v0 (200, 150), v1 (210, 150), v2 (200, 140), v3 (210, 140). + private val positions = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 10f, 10f) + private val triangleIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // The quad's five unique edges, in a fixed ordinal order the assertions reference. + private val edgeEndpoints = intArrayOf(0, 1, 1, 2, 0, 2, 1, 3, 2, 3) + + /** The projection round-trips exactly and flips Y (world up = screen up = smaller y). */ + @Test + fun projectionRoundTripsAndFlipsY() { + val zoomedCamera = ViewportCamera(centerX = 5f, centerY = -3f, zoom = 2f) + val worldX = 12.5f + val worldZ = -7.25f + val screenX = worldToScreenX(worldX, zoomedCamera, viewportWidth) + val screenY = worldToScreenY(worldZ, zoomedCamera, viewportHeight) + assertEquals(worldX, screenToWorldX(screenX, zoomedCamera, viewportWidth), 1e-4f, "x round-trips") + assertEquals(worldZ, screenToWorldZ(screenY, zoomedCamera, viewportHeight), 1e-4f, "y round-trips") + + val higherY = worldToScreenY(worldZ + 1f, zoomedCamera, viewportHeight) + assertTrue(higherY < screenY, "a higher world point draws at a smaller screen y") + } + + /** hitTestVertex picks the nearest vertex within the radius and misses outside it. */ + @Test + fun hitTestVertexPicksNearestWithinRadius() { + // Screen (208, 150): 8 px from v1's projection, 8+ px from v0's - v1 is nearer. + assertEquals(1, hitTestVertex(positions, 208f, 150f, 10f, camera, viewportWidth, viewportHeight)) + // Nothing within a 3 px radius at that point. + assertNull(hitTestVertex(positions, 205f, 150f, 2f, camera, viewportWidth, viewportHeight)) + } + + /** parameterAlongSegment returns the unclamped line parameter (and 0.5 for a degenerate segment). */ + @Test + fun parameterAlongSegmentProjectsOntoTheLine() { + assertEquals(0.5f, parameterAlongSegment(5f, 4f, 0f, 0f, 10f, 0f), 1e-4f) + assertEquals(1.3f, parameterAlongSegment(13f, 0f, 0f, 0f, 10f, 0f), 1e-4f) + assertEquals(0.5f, parameterAlongSegment(3f, 4f, 0f, 0f, 0f, 0f), 1e-4f) + } + + /** distanceToSegment projects onto the segment, clamps at the endpoints, and survives degeneracy. */ + @Test + fun distanceToSegmentClampsToEndpoints() { + // Perpendicular drop onto the middle of a horizontal segment. + assertEquals(4f, distanceToSegment(5f, 4f, 0f, 0f, 10f, 0f), 1e-4f) + // Beyond the end: the distance is to the endpoint, not the infinite line. + assertEquals(5f, distanceToSegment(13f, 4f, 0f, 0f, 10f, 0f), 1e-4f) + // A zero-length segment measures as the distance to its single point. + assertEquals(5f, distanceToSegment(3f, 4f, 0f, 0f, 0f, 0f), 1e-4f) + } + + /** hitTestEdge returns the ordinal of the nearest segment within the radius. */ + @Test + fun hitTestEdgePicksNearestSegment() { + // Screen (205, 152): 2 px below the v0-v1 segment (ordinal 0), farther from every other edge. + assertEquals(0, hitTestEdge(positions, edgeEndpoints, 205f, 152f, 10f, camera, viewportWidth, viewportHeight)) + // Screen (210, 145): on the vertical v1-v3 segment (ordinal 3). + assertEquals(3, hitTestEdge(positions, edgeEndpoints, 210f, 145f, 10f, camera, viewportWidth, viewportHeight)) + // Far from everything within a tight radius. + assertNull(hitTestEdge(positions, edgeEndpoints, 250f, 200f, 5f, camera, viewportWidth, viewportHeight)) + // An edge referencing a missing vertex is skipped rather than crashing. + assertNull(hitTestEdge(positions, intArrayOf(0, 9), 205f, 150f, 10f, camera, viewportWidth, viewportHeight)) + } + + /** hitTestFace picks a containing triangle, breaking overlaps by the nearest centroid. */ + @Test + fun hitTestFaceUsesCentroidTieBreak() { + // Screen (202, 148) = world (2, 2): inside triangle 0 only. + assertEquals(0, hitTestFace(positions, triangleIndices, 202f, 148f, camera, viewportWidth, viewportHeight)) + // Screen (208, 142) = world (8, 8): inside triangle 1 only. + assertEquals(1, hitTestFace(positions, triangleIndices, 208f, 142f, camera, viewportWidth, viewportHeight)) + // Outside the quad entirely. + assertNull(hitTestFace(positions, triangleIndices, 250f, 250f, camera, viewportWidth, viewportHeight)) + + // Two coincident triangles both contain the pointer: the one with the nearer centroid wins. + // Triangle 0 spans the quad's lower-left half; triangle 1 (here duplicated smaller) hugs v0. + val overlappingPositions = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 4f, 0f, 0f, 4f) + val overlappingTriangles = intArrayOf(0, 1, 2, 0, 3, 4) + // World (1, 1) is inside both; the small triangle's centroid is much closer. + assertEquals(1, hitTestFace(overlappingPositions, overlappingTriangles, 201f, 149f, camera, viewportWidth, viewportHeight)) + } + + /** verticesInBox encloses by screen position, corner order agnostic. */ + @Test + fun verticesInBoxEnclosesByScreenPosition() { + // A box around v0 and v2's column (screen x 195..205, y 135..155). + assertEquals(setOf(0, 2), verticesInBox(positions, 205f, 135f, 195f, 155f, camera, viewportWidth, viewportHeight)) + // The whole quad. + assertEquals(setOf(0, 1, 2, 3), verticesInBox(positions, 195f, 135f, 215f, 155f, camera, viewportWidth, viewportHeight)) + // An empty region. + assertEquals(emptySet(), verticesInBox(positions, 0f, 0f, 50f, 50f, camera, viewportWidth, viewportHeight)) + } + + /** edgesInBox requires both endpoints inside (Blender's rule); facesInBox uses the centroid. */ + @Test + fun boxRulesForEdgesAndFaces() { + // The v0-v2 column box encloses edge ordinal 2 (0-2) only - every other edge has an endpoint outside. + assertEquals(setOf(2), edgesInBox(positions, edgeEndpoints, 205f, 135f, 195f, 155f, camera, viewportWidth, viewportHeight)) + // Triangle 0's centroid is world (10/3, 10/3) = screen (~203.3, ~146.7); a tight box around it + // selects face 0 only even though its corners poke out. + assertEquals(setOf(0), facesInBox(positions, triangleIndices, 202f, 145f, 205f, 148f, camera, viewportWidth, viewportHeight)) + } + + /** The circle brush encloses vertices by distance, edges by segment overlap, faces by centroid. */ + @Test + fun circleRulesPerDomain() { + // A 6 px brush at v1's projection: only v1 within reach. + assertEquals(setOf(1), verticesInCircle(positions, 210f, 150f, 6f, camera, viewportWidth, viewportHeight)) + // The same brush touches every edge incident to v1 (ordinals 0: 0-1, 1: 1-2, 3: 1-3). + assertEquals(setOf(0, 1, 3), edgesInCircle(positions, edgeEndpoints, 210f, 150f, 6f, camera, viewportWidth, viewportHeight)) + // A 3 px brush at triangle 0's centroid paints face 0 only. + assertEquals(setOf(0), facesInCircle(positions, triangleIndices, 203.3f, 146.7f, 3f, camera, viewportWidth, viewportHeight)) + // A brush over empty canvas paints nothing. + assertEquals(emptySet(), verticesInCircle(positions, 50f, 50f, 10f, camera, viewportWidth, viewportHeight)) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/BlendMathEmptyLayerTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/BlendMathEmptyLayerTest.kt new file mode 100644 index 0000000..f1f26f2 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/BlendMathEmptyLayerTest.kt @@ -0,0 +1,45 @@ +package org.umamo.render.puppet + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * An offscreen composite runs over the FULL viewport, so where its layer has no coverage the layer's + * source alpha is 0 and the composite must leave the destination untouched. This was NOT true while + * Out was misread as Porter-Duff SRC-out (destination factor 0): an empty Out layer wrote transparent + * over every pixel and blanked the whole frame - which is what a deformer-hidden Out mesh (modelA's + * hologram overlay at ParamHologram=0) did to the entire character. The corrected DST-flavored Out + * (Fa = 0, Fb = 1-as) preserves an untouched destination inherently, as do the other four modes. + * + * This pins the invariant at the reference level for every alpha mode; `CompositeSweepTest` then pins + * the composite shader to this reference, so the two cannot drift. + */ +class BlendMathEmptyLayerTest { + private val destinations = + listOf( + floatArrayOf(0.4f, 0.2f, 0.7f, 1.0f), // opaque backdrop (the grid / an opaque character pixel) + floatArrayOf(0.1f, 0.1f, 0.1f, 0.5f), // semi-transparent + floatArrayOf(0.0f, 0.0f, 0.0f, 0.0f), // fully transparent + ) + + @Test + fun anEmptyLayerPreservesTheDestinationForEveryAlphaMode() { + val emptySource = floatArrayOf(0f, 0f, 0f, 0f) + for (alphaMode in AlphaBlendMode.entries) { + for (colorMode in listOf(BlendMode.Normal, BlendMode.Multiply, BlendMode.Overlay, BlendMode.Color)) { + for (destination in destinations) { + val result = compositeReference(emptySource, destination, colorMode, alphaMode) + for (channel in 0 until 4) { + assertTrue( + kotlin.math.abs(result[channel] - destination[channel]) < 1e-6f, + "empty layer under $colorMode / $alphaMode must preserve the destination " + + "(channel $channel: got ${result[channel]}, expected ${destination[channel]})", + ) + } + } + } + } + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/ContentBoundsEvalTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/ContentBoundsEvalTest.kt new file mode 100644 index 0000000..be80be6 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/ContentBoundsEvalTest.kt @@ -0,0 +1,106 @@ +package org.umamo.render.puppet + +import org.umamo.render.ContentBounds +import org.umamo.render.eval.DeformedGeometry +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins [contentBoundsOf] and the fallback beside it: the extent spans only the shown drawables, each span + * is floored at 1, nothing shown measures as null, and an empty view frames the canvas. Reachable without + * a GPU, unlike the framing path in the renderer. + */ +class ContentBoundsEvalTest { + private fun geometryOf(vararg drawables: Pair): DeformedGeometry = + DeformedGeometry( + worldPositions = drawables.associate { (id, positions) -> DrawableId(id) to positions }, + drawOrder = emptyMap(), + opacity = emptyMap(), + ) + + @Test + fun contentBoundsOfSpansEveryShownVertex() { + val geometry = geometryOf("a" to floatArrayOf(-10f, -20f, 30f, 5f), "b" to floatArrayOf(0f, 40f)) + val bounds = assertNotNull(contentBoundsOf(geometry, setOf(DrawableId("a"), DrawableId("b")))) + assertEquals(-10f, bounds.minX, "left edge is the smallest x across both meshes") + assertEquals(-20f, bounds.minY, "bottom edge is the smallest y across both meshes") + assertEquals(40f, bounds.width, "width spans -10..30") + assertEquals(60f, bounds.height, "height spans -20..40") + } + + @Test + fun contentBoundsOfIgnoresHiddenDrawables() { + // The hidden mesh is far larger; if the filter regressed, the bounds would swell to it. + val geometry = geometryOf("shown" to floatArrayOf(0f, 0f, 10f, 10f), "hidden" to floatArrayOf(-500f, -500f, 500f, 500f)) + val bounds = assertNotNull(contentBoundsOf(geometry, setOf(DrawableId("shown")))) + assertEquals(0f, bounds.minX) + assertEquals(0f, bounds.minY) + assertEquals(10f, bounds.width, "the hidden full-canvas mesh must not stretch the framing") + assertEquals(10f, bounds.height) + } + + @Test + fun contentBoundsOfFloorsDegenerateSpansAtOne() { + // A single vertex has zero extent; the floor is what keeps a fit from dividing by zero. + val bounds = assertNotNull(contentBoundsOf(geometryOf("dot" to floatArrayOf(7f, 9f)), setOf(DrawableId("dot")))) + assertEquals(1f, bounds.width, "a zero-width extent floors at 1") + assertEquals(1f, bounds.height, "a zero-height extent floors at 1") + } + + /** + * Nothing shown is nothing to measure: null, never a rectangle left at the float extremes - a camera + * fitted to that sits where the grid has no precision to draw with, and the viewport goes blank. + */ + @Test + fun contentBoundsOfIsNullWhenNothingIsShown() { + assertNull(contentBoundsOf(geometryOf("a" to floatArrayOf(0f, 0f)), emptySet()), "every drawable hidden") + assertNull(contentBoundsOf(geometryOf(), emptySet()), "an empty model") + assertNull(contentBoundsOf(geometryOf("empty" to FloatArray(0)), setOf(DrawableId("empty"))), "a shown drawable with no vertices") + } + + /** An empty view frames the canvas, which world space holds at x in [0, width] and y in [-height, 0]. */ + @Test + fun anEmptyViewFramesTheCanvas() { + val bounds = emptyContentBoundsOf(emptyModel(canvasWidth = 1200f, canvasHeight = 800f)) + + assertEquals(ContentBounds(0f, -800f, 1200f, 800f), bounds) + } + + /** With no canvas either, it frames a square around the world origin, so the origin's axes are on screen. */ + @Test + fun anEmptyViewWithNoCanvasFramesTheWorldOrigin() { + val bounds = emptyContentBoundsOf(emptyModel(canvasWidth = 0f, canvasHeight = 0f, worldOriginX = 40f, worldOriginZ = -60f)) + + assertEquals(40f, bounds.minX + bounds.width / 2f, "centered on the origin's x") + assertEquals(-60f, bounds.minY + bounds.height / 2f, "centered on the origin's y") + assertTrue(bounds.width > 1f && bounds.height > 1f, "with room to work in, not a degenerate point") + } + + /** + * A model with nothing in it. + * + * @param Float canvasWidth The canvas width, or 0 for none. + * @param Float canvasHeight The canvas height, or 0 for none. + * @param Float worldOriginX The world origin's x. + * @param Float worldOriginZ The world origin's z (up). + * @return PuppetModel The model. + */ + private fun emptyModel(canvasWidth: Float, canvasHeight: Float, worldOriginX: Float = 0f, worldOriginZ: Float = 0f): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = canvasWidth, + canvasHeight = canvasHeight, + worldOriginX = worldOriginX, + worldOriginZ = worldOriginZ, + ) +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/DeltaTexelsTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/DeltaTexelsTest.kt new file mode 100644 index 0000000..df4a56c --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/DeltaTexelsTest.kt @@ -0,0 +1,104 @@ +package org.umamo.render.puppet + +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins [keyformCellCount] and [buildDeltaTexels] - the morph's Δ table layout. This is the data the + * vertex shader texel-fetches per active corner, so a layout slip mis-deforms every mesh; until now it + * was reachable only through the corpus-gated GPU test, which does not run in CI. + */ +class DeltaTexelsTest { + private val paramA = ParameterId("A") + private val paramB = ParameterId("B") + + /** Reads texel (vertex, cell) out of the row-major RG buffer. */ + private fun texelAt(texels: FloatArray, cellCount: Int, vertexIndex: Int, cellIndex: Int): Pair { + val at = (vertexIndex * cellCount + cellIndex) * 2 + return texels[at] to texels[at + 1] + } + + @Test + fun keyformCellCountIsTheProductOfAxisKeyCounts() { + val grid = + KeyformGrid( + axes = listOf(KeyformAxis(paramA, floatArrayOf(-1f, 0f, 1f)), KeyformAxis(paramB, floatArrayOf(0f, 1f))), + cells = emptyList(), + ) + assertEquals(6, keyformCellCount(grid), "3 keys x 2 keys = 6 cells") + } + + @Test + fun keyformCellCountFloorsAtOneForAnAxislessGrid() { + val grid = KeyformGrid(axes = emptyList(), cells = emptyList()) + assertEquals(1, keyformCellCount(grid), "an axis-less grid still has its single rest cell") + } + + @Test + fun buildDeltaTexelsPlacesEachCellInItsLinearColumn() { + // Two vertices, two cells along one axis. Cell 0 shifts vertex 1 only; cell 1 shifts vertex 0 only, + // so a row/column transpose or an off-by-one column would be caught. + val grid = + KeyformGrid( + axes = listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f))), + cells = + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f, 5f, 6f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(7f, 8f, 0f, 0f))), + ), + ) + val texels = buildDeltaTexels(grid, vertexCount = 2, cellCount = 2) + assertEquals(2 * 2 * 2, texels.size, "vertexCount * cellCount * 2") + assertEquals(0f to 0f, texelAt(texels, 2, vertexIndex = 0, cellIndex = 0)) + assertEquals(7f to 8f, texelAt(texels, 2, vertexIndex = 0, cellIndex = 1)) + assertEquals(5f to 6f, texelAt(texels, 2, vertexIndex = 1, cellIndex = 0)) + assertEquals(0f to 0f, texelAt(texels, 2, vertexIndex = 1, cellIndex = 1)) + } + + @Test + fun buildDeltaTexelsUsesTheAxisMajorLinearIndex() { + // Strides run axis 0 fastest (stride 1), so coordinate (0,1) on a 2x2 grid is linear index 2 - + // the same indexing WeightedCell.linearIndex carries into the shader. A stride flip lands it at 1. + val grid = + KeyformGrid( + axes = listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f)), KeyformAxis(paramB, floatArrayOf(0f, 1f))), + cells = listOf(KeyformCell(intArrayOf(0, 1), MeshDeltaForm(floatArrayOf(9f, 9f)))), + ) + val texels = buildDeltaTexels(grid, vertexCount = 1, cellCount = 4) + assertEquals(9f to 9f, texelAt(texels, 4, vertexIndex = 0, cellIndex = 2), "coordinate (0,1) lands in column 2") + assertEquals(0f to 0f, texelAt(texels, 4, vertexIndex = 0, cellIndex = 1), "column 1 is coordinate (1,0), unkeyed here") + } + + @Test + fun buildDeltaTexelsZeroFillsAMissingCell() { + // A grid whose cells do not cover every combination: the absent cell means no offset from rest. + val grid = + KeyformGrid( + axes = listOf(KeyformAxis(paramA, floatArrayOf(0f, 1f))), + cells = listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(3f, 4f)))), + ) + val texels = buildDeltaTexels(grid, vertexCount = 1, cellCount = 2) + assertEquals(3f to 4f, texelAt(texels, 2, 0, 0)) + assertEquals(0f to 0f, texelAt(texels, 2, 0, 1), "the unkeyed cell contributes no delta") + } + + @Test + fun buildDeltaTexelsZeroFillsWhenTheDeltaArrayIsShorterThanTheMesh() { + // Reachable in real models: the form carries fewer vertices than the mesh. The short tail reads as + // rest rather than running off the end. + val grid = + KeyformGrid( + axes = listOf(KeyformAxis(paramA, floatArrayOf(0f))), + cells = listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(1f, 2f)))), + ) + val texels = buildDeltaTexels(grid, vertexCount = 3, cellCount = 1) + assertEquals(1f to 2f, texelAt(texels, 1, vertexIndex = 0, cellIndex = 0)) + assertEquals(0f to 0f, texelAt(texels, 1, vertexIndex = 1, cellIndex = 0), "vertex past the delta array reads rest") + assertEquals(0f to 0f, texelAt(texels, 1, vertexIndex = 2, cellIndex = 0)) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/FallbackColorTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/FallbackColorTest.kt new file mode 100644 index 0000000..87a3355 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/FallbackColorTest.kt @@ -0,0 +1,35 @@ +package org.umamo.render.puppet + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Pins [fallbackColorFor]: stable per id, distinct across ids, and always in the readable mid-band. */ +class FallbackColorTest { + @Test + fun fallbackColorForIsStableForTheSameId() { + // The point of hashing the id rather than cycling a palette: a drawable keeps its color across + // reorders and reloads. + assertTrue(fallbackColorFor("mesh_a").contentEquals(fallbackColorFor("mesh_a"))) + } + + @Test + fun fallbackColorForDiffersAcrossIds() { + assertTrue(!fallbackColorFor("mesh_a").contentEquals(fallbackColorFor("mesh_b")), "neighbouring meshes must be tellable apart") + } + + @Test + fun fallbackColorForStaysInTheReadableMidBand() { + // 0.35 floor + 0.6 span keeps every channel mid-bright, so the mesh reads against both the light + // and dark grid backdrops. + for (id in listOf("", "a", "some_long_drawable_id", "ParamAngleX", "0")) { + val color = fallbackColorFor(id) + assertEquals(4, color.size, "RGBA") + for (channelIndex in 0..2) { + assertTrue(color[channelIndex] >= 0.35f, "$id channel $channelIndex is at or above the floor") + assertTrue(color[channelIndex] <= 0.95f, "$id channel $channelIndex is at or below floor + span") + } + assertEquals(0.85f, color[3], "alpha is fixed") + } + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/GlueLayoutTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/GlueLayoutTest.kt new file mode 100644 index 0000000..383131f --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/GlueLayoutTest.kt @@ -0,0 +1,179 @@ +package org.umamo.render.puppet + +import org.umamo.render.glsl.MAX_GLUES +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins [planGlueLayout] - the glue addressing the GPU weld reads. + * + * This logic had NO coverage of any kind before it was extracted: `GpuDeformValidationTest` excludes glue + * by design, and `GlueTest` / `GlueCorpusTest` only exercise the CPU weld, which does not use these + * offsets or attributes at all. `GpuGlueValidationTest` now covers the same ground end-to-end through a + * GPU, but needs a display; these run anywhere. + */ +class GlueLayoutTest { + private val paramA = ParameterId("A") + + /** A drawable with [vertexCount] vertices; geometry values are irrelevant to addressing. */ + private fun drawable(id: String, vertexCount: Int): Drawable { + val positions = FloatArray(vertexCount * 2) + return Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), IntArray(0)), + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ), + ) + } + + private fun model(drawables: List, glues: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { OrgChild.Drawable(it.id) }, + rootPartId = null, + glues = glues, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + + @Test + fun planGlueLayoutIsEmptyWithoutGlue() { + val layout = planGlueLayout(model(listOf(drawable("a", 3)), emptyList())) + assertTrue(layout.glueMeshIds.isEmpty()) + assertEquals(0, layout.globalVertexCount, "no glue means no shared store") + assertTrue(layout.attributesById.isEmpty()) + } + + @Test + fun planGlueLayoutAssignsOffsetsInDrawableOrderSkippingUngluedMeshes() { + // "middle" is not glued, so it takes no region: offsets follow model.drawables order over the + // GLUED meshes only. Both the pass-1 write and the pass-2 partner read depend on this exactly. + val drawables = listOf(drawable("a", 4), drawable("middle", 9), drawable("b", 2)) + val glue = Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(0, 0, 0.5f, 0.5f))) + val layout = planGlueLayout(model(drawables, listOf(glue))) + assertEquals(setOf(DrawableId("a"), DrawableId("b")), layout.glueMeshIds) + assertEquals(0, layout.baseOffsetById[DrawableId("a")], "the first glued mesh starts the store") + assertEquals(4, layout.baseOffsetById[DrawableId("b")], "the next glued mesh follows a's 4 vertices") + assertEquals(null, layout.baseOffsetById[DrawableId("middle")], "an unglued mesh gets no region") + assertEquals(6, layout.globalVertexCount, "4 + 2; the unglued mesh's 9 vertices are not in the store") + } + + @Test + fun planGlueLayoutDefaultsEveryVertexToAnUngluedSelfWeld() { + val drawables = listOf(drawable("a", 3), drawable("b", 3)) + val glue = Glue(DrawableId("a"), DrawableId("b"), emptyList()) + val layout = planGlueLayout(model(drawables, listOf(glue))) + val attributesB = layout.attributesById.getValue(DrawableId("b")) + // Self-pointing by GLOBAL index (b starts at 3), so the weld is arithmetically a no-op. + assertContentEquals(intArrayOf(3, 4, 5), attributesB.partnerIndex, "an unglued vertex points at itself") + assertContentEquals(intArrayOf(-1, -1, -1), attributesB.glueIndex, "-1 means no glue") + assertContentEquals(floatArrayOf(0f, 0f, 0f), attributesB.weldWeight, "zero weight is a no-op weld") + } + + @Test + fun planGlueLayoutPointsEachPairAtItsPartnerByGlobalIndex() { + val drawables = listOf(drawable("a", 4), drawable("b", 4)) + val glue = Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(1, 2, 0.25f, 0.75f))) + val layout = planGlueLayout(model(drawables, listOf(glue))) + val attributesA = layout.attributesById.getValue(DrawableId("a")) + val attributesB = layout.attributesById.getValue(DrawableId("b")) + // a's vertex 1 -> b's vertex 2, which is GLOBAL index 4 + 2 = 6. + assertEquals(6, attributesA.partnerIndex[1], "A's seam vertex points at B's, by global index") + assertEquals(0, attributesA.glueIndex[1]) + assertEquals(0.25f, attributesA.weldWeight[1], "A carries weightA") + // b's vertex 2 -> a's vertex 1, global index 0 + 1 = 1. + assertEquals(1, attributesB.partnerIndex[2], "B's seam vertex points back at A's") + assertEquals(0, attributesB.glueIndex[2]) + assertEquals(0.75f, attributesB.weldWeight[2], "B carries weightB") + // Untouched vertices stay no-op welds. + assertEquals(-1, attributesA.glueIndex[0]) + assertEquals(-1, attributesB.glueIndex[3]) + } + + @Test + fun planGlueLayoutGivesAnIndexLessAnchorItsOwnRegion() { + // A zero-triangle anchor draws nothing but is a weld partner, so it MUST still get a region: pass 1 + // deforms it, and pass 2 reads its positions. Dropping it would weld against uninitialised memory. + val anchor = drawable("anchor", 4).let { Drawable(it.id, it.name, null, BlendMode.Normal, emptyList(), it.mesh, it.geometryGrid) } + val drawables = listOf(anchor, drawable("b", 2)) + val glue = Glue(DrawableId("anchor"), DrawableId("b"), listOf(GluePair(0, 0, 0f, 1f))) + val layout = planGlueLayout(model(drawables, listOf(glue))) + assertEquals(0, layout.baseOffsetById[DrawableId("anchor")]) + assertEquals(4, layout.baseOffsetById[DrawableId("b")], "the anchor's 4 vertices still occupy the store") + assertEquals(6, layout.globalVertexCount) + assertEquals(4, layout.attributesById.getValue(DrawableId("anchor")).partnerIndex.size) + } + + @Test + fun planGlueLayoutTagsEachGlueWithItsOwnIndex() { + // The glue index selects the per-pose intensity uniform, so a second glue must not reuse the first's. + val drawables = listOf(drawable("a", 2), drawable("b", 2), drawable("c", 2)) + val glues = + listOf( + Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(0, 0, 0.5f, 0.5f))), + Glue(DrawableId("b"), DrawableId("c"), listOf(GluePair(1, 1, 0.5f, 0.5f))), + ) + val layout = planGlueLayout(model(drawables, glues)) + val attributesB = layout.attributesById.getValue(DrawableId("b")) + assertEquals(0, attributesB.glueIndex[0], "B's vertex 0 belongs to the first glue") + assertEquals(1, attributesB.glueIndex[1], "B's vertex 1 belongs to the second") + } + + @Test + fun planGlueLayoutSkipsAGlueNamingAnAbsentDrawable() { + val drawables = listOf(drawable("a", 2)) + val glue = Glue(DrawableId("a"), DrawableId("ghost"), listOf(GluePair(0, 0, 0.5f, 0.5f))) + val layout = planGlueLayout(model(drawables, listOf(glue))) + // "ghost" is named by the glue but carried by no drawable, so it gets no region and no attributes, + // and the pair is dropped rather than welding against a region that does not exist. + assertEquals(null, layout.baseOffsetById[DrawableId("ghost")]) + assertEquals(2, layout.globalVertexCount, "only the real mesh occupies the store") + assertEquals(-1, layout.attributesById.getValue(DrawableId("a")).glueIndex[0], "the half-resolved pair is not applied") + } + + @Test + fun planGlueLayoutLeavesGlueBeyondTheShaderArrayUnwelded() { + // The shader's glueIntensity[] uniform has exactly MAX_GLUES slots; a vertex tagged with glue index + // >= MAX_GLUES would read it out of bounds. Those pairs must stay -1 (unwelded), which is what makes + // resolvePose's "renders unwelded" promise true rather than an out-of-bounds read. + val a = drawable("a", 1) + val b = drawable("b", 1) + // MAX_GLUES + 1 glues, all on the same pair. The first MAX_GLUES tag vertex 0; the last must not. + val glues = List(MAX_GLUES + 1) { Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(0, 0, 0.5f, 0.5f))) } + val layout = planGlueLayout(model(listOf(a, b), glues)) + // Each pair overwrites vertex 0's tag, so after the loop it holds the LAST in-bounds glue index. + assertEquals(MAX_GLUES - 1, layout.attributesById.getValue(DrawableId("a")).glueIndex[0], "the last addressable glue tags the vertex") + assertTrue( + layout.attributesById.getValue(DrawableId("a")).glueIndex.all { it < MAX_GLUES }, + "no vertex is ever tagged with a glue index the shader array cannot hold", + ) + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/ModelDiffTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/ModelDiffTest.kt new file mode 100644 index 0000000..c702617 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/ModelDiffTest.kt @@ -0,0 +1,219 @@ +package org.umamo.render.puppet + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins [diffModel]'s four tiers by DECISION. + * + * The three GL reconcile tests cover this ground too, but they test the diff AND the GL apply together + * and assert on pixels - so they need a display, and they cover maybe half the cases. These enumerate the + * decisions themselves and run anywhere. + */ +class ModelDiffTest { + private val paramA = ParameterId("A") + + private fun grid(positions: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ) + + private fun drawable( + id: String, + positions: FloatArray, + uvs: FloatArray = FloatArray(positions.size), + indices: IntArray = intArrayOf(0, 1, 2), + keyforms: KeyformGrid? = null, + ): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, uvs, indices), + geometryGrid = keyforms ?: grid(positions), + ) + + private fun model(vararg drawables: Drawable): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables.toList(), + rootChildren = drawables.map { OrgChild.Drawable(it.id) }, + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + + private fun resident(vararg pairs: Pair): Map = pairs.associate { DrawableId(it.first) to it.second } + + @Test + fun diffModelKeepsAnUntouchedDrawableWithNoWork() { + // Copy-on-write means an untouched drawable keeps its array instances, so both tiers are null and + // the backend does nothing at all - the case that must stay cheap, since it is every frame's. + val source = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val diff = diffModel(model(source), model(source), resident("a" to 3)) + val keep = assertIs(diff.actions.single()) + assertNull(keep.positions, "an untouched mesh re-uploads no positions") + assertNull(keep.uvs, "and no UVs") + assertTrue(diff.removed.isEmpty()) + } + + @Test + fun diffModelUploadsADrawableTheBackendHasNeverSeen() { + val existing = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val added = drawable("copy", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + // "copy" is absent from the resident map - an Object-mode duplicate, or one skipped at load. + val diff = diffModel(model(existing), model(existing, added), resident("a" to 3)) + val upload = assertIs(diff.actions[1]) + assertEquals(DrawableId("copy"), upload.drawableId) + assertTrue(diff.removed.isEmpty()) + } + + @Test + fun diffModelRemovesAResidentTheEditDropped() { + val kept = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val dropped = drawable("gone", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val diff = diffModel(model(kept, dropped), model(kept), resident("a" to 3, "gone" to 3)) + assertEquals(listOf(DrawableId("gone")), diff.removed) + } + + @Test + fun diffModelReuploadsOnEachTopologyTrigger() { + val positions = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f) + val before = drawable("a", positions) + + // 1. The vertex count changed against what the backend uploaded. + val grown = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 2f, 2f)) + assertIs(diffModel(model(before), model(grown), resident("a" to 3)).actions.single(), "vertex count") + + // 2. The indices array instance changed (a merge / rip / connect). + val reindexed = drawable("a", positions, indices = intArrayOf(0, 2, 1)) + assertIs(diffModel(model(before), model(reindexed), resident("a" to 3)).actions.single(), "indices") + + // 3. The keyform grid instance changed, so the delta texture's striding is stale. + val rekeyed = drawable("a", positions, keyforms = grid(positions)) + assertIs(diffModel(model(before), model(rekeyed), resident("a" to 3)).actions.single(), "keyforms") + } + + @Test + fun diffModelReuploadsPositionsOnlyWhenTheArrayInstanceChanged() { + val before = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val movedPositions = floatArrayOf(5f, 5f, 6f, 5f, 6f, 6f) + // withMeshPositions shares the uvs array by reference; only positions is a new instance. + val after = drawable("a", movedPositions, uvs = before.mesh!!.uvs, indices = before.mesh!!.indices, keyforms = before.geometryGrid) + val keep = assertIs(diffModel(model(before), model(after), resident("a" to 3)).actions.single()) + assertSame(movedPositions, keep.positions, "the moved positions re-upload") + assertNull(keep.uvs, "the shared uvs array does not") + } + + @Test + fun diffModelReuploadsUvsOnlyWhenTheArrayInstanceChanged() { + val before = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val movedUvs = floatArrayOf(0.5f, 0.5f, 1f, 0.5f, 1f, 1f) + val after = + drawable("a", before.mesh!!.positions, uvs = movedUvs, indices = before.mesh!!.indices, keyforms = before.geometryGrid) + val keep = assertIs(diffModel(model(before), model(after), resident("a" to 3)).actions.single()) + assertNull(keep.positions) + assertSame(movedUvs, keep.uvs, "a UV edit re-uploads the UV buffer only") + } + + @Test + fun diffModelSkipsUvsWhoseLengthDisagreesWithTheResident() { + // Defensive: the copy-on-write UV edit never changes the length, so a mismatch means the backend + // padded this mesh's UVs at upload. Re-uploading a short array would leave the tail stale. + val before = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f), uvs = FloatArray(6)) + val after = drawable("a", before.mesh!!.positions, uvs = FloatArray(2), indices = before.mesh!!.indices, keyforms = before.geometryGrid) + val keep = assertIs(diffModel(model(before), model(after), resident("a" to 3)).actions.single()) + assertNull(keep.uvs, "a length mismatch leaves the resident's UVs alone") + } + + @Test + fun diffModelNeverBothActionsAndRemovesTheSameDrawable() { + // The double-free guard. A remesh frees the resident and re-uploads; if that upload yields nothing + // (a remesh to zero triangles), the drawable must NOT also appear in `removed` - freeing the same GL + // names twice can hit a name the driver recycled for a later upload in the same pass, which would + // free a live buffer belonging to a different drawable. + val before = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val emptied = drawable("a", floatArrayOf(0f, 0f), indices = IntArray(0)) + val diff = diffModel(model(before), model(emptied), resident("a" to 3)) + assertIs(diff.actions.single()) + assertTrue(diff.removed.isEmpty(), "a re-uploaded drawable is never also removed") + } + + @Test + fun diffModelKeepsResidentWhoseMeshWentNull() { + // Reachable: a kept resident whose new mesh is null. The resident vertex count must come from the + // backend, not the model, because the model no longer carries what the buffers were built at. + val before = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val meshless = + Drawable(DrawableId("a"), "a", null, BlendMode.Normal, emptyList(), mesh = null, geometryGrid = before.geometryGrid) + val diff = diffModel(model(before), model(meshless), resident("a" to 3)) + val keep = assertIs(diff.actions.single()) + assertNull(keep.positions) + assertNull(keep.uvs) + assertTrue(diff.removed.isEmpty(), "it stays resident rather than being freed") + } + + @Test + fun diffModelActionsFollowNewModelOrderThroughAReorder() { + // Keyed by id, so a simultaneous reorder is handled; the actions follow the NEW order, which is what + // rebuilds residency in that order. + val first = drawable("a", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val second = drawable("b", floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f)) + val diff = diffModel(model(first, second), model(second, first), resident("a" to 3, "b" to 3)) + assertEquals(listOf(DrawableId("b"), DrawableId("a")), diff.actions.map { it.drawableId }) + assertTrue(diff.actions.all { it is DrawableAction.Keep }, "a reorder needs no buffer work") + assertTrue(diff.removed.isEmpty()) + } + + @Test + fun diffModelReuploadsWhenWarpParentingFlips() { + // A drawable owns a control-point texture iff its parent is a warp, and that is fixed at upload. A + // reparent that flips it (deleting a rotation deformer between a drawable and a warp, so the drawable + // now parents the warp directly) must Reupload, or the resident keeps a stale / absent cp texture and + // the shader samples whatever texture unit 3 last held. Keying purely on the two models' warp sets. + val positions = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f) + val warp = Deformer.Warp(DeformerId("warp"), "warp", parent = null, partId = null, rows = 2, columns = 2, isQuadTransform = true, geometryGrid = null) + val rotation = Deformer.Rotation(DeformerId("rot"), "rot", parent = null, partId = null, baseAngle = 0f, geometryGrid = null) + + val rotationParented = drawable("a", positions).copy(parentDeformerId = DeformerId("rot")) + val warpParented = rotationParented.copy(parentDeformerId = DeformerId("warp")) + // Non-warp parent → warp parent: gains a cp texture, so Reupload. + val gained = diffModel(modelOf(listOf(rotation, warp), rotationParented), modelOf(listOf(rotation, warp), warpParented), resident("a" to 3)) + assertIs(gained.actions.single(), "warp parenting gained") + // Warp parent → non-warp parent: loses the cp texture, so Reupload. + val lost = diffModel(modelOf(listOf(rotation, warp), warpParented), modelOf(listOf(rotation, warp), rotationParented), resident("a" to 3)) + assertIs(lost.actions.single(), "warp parenting lost") + // Warp parent → SAME warp parent (a mere reorder around it): control-point ownership unchanged, so Keep. + val unchanged = diffModel(modelOf(listOf(rotation, warp), warpParented), modelOf(listOf(rotation, warp), warpParented), resident("a" to 3)) + assertIs(unchanged.actions.single(), "unchanged warp parent needs no re-upload") + } + + /** A model with explicit deformers - the plain [model] helper carries none, which the warp cases need. */ + private fun modelOf(deformers: List, vararg drawables: Drawable): PuppetModel = + model(*drawables).copy(deformers = deformers) +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PixelRowsTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PixelRowsTest.kt new file mode 100644 index 0000000..31e2b8b --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PixelRowsTest.kt @@ -0,0 +1,48 @@ +package org.umamo.render.puppet + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +/** + * Pins [flipRowsVertically] - the bottom-up-read-back to top-first conversion. Tiny, but it is the one + * place the framebuffer Y convention is decided, and getting it backwards silently mirrors every dump. + */ +class PixelRowsTest { + /** One opaque RGBA pixel, so a row's identity is readable at the call site. */ + private fun pixel(red: Int, green: Int, blue: Int): ByteArray = byteArrayOf(red.toByte(), green.toByte(), blue.toByte(), 255.toByte()) + + private val redRow = pixel(255, 0, 0) + private val greenRow = pixel(0, 255, 0) + + @Test + fun flipRowsVerticallyReversesRowOrder() { + val flipped = flipRowsVertically(redRow + greenRow, width = 1, height = 2) + assertContentEquals(greenRow + redRow, flipped, "the bottom (green) row must come first after the flip") + } + + @Test + fun flipRowsVerticallyKeepsChannelOrderWithinAPixel() { + // Row-wise, not per-pixel: RGBA must survive untouched, only the rows move. + val singleRow = pixel(1, 2, 3) + pixel(4, 5, 6) + assertContentEquals(singleRow, flipRowsVertically(singleRow, width = 2, height = 1), "a single row is unchanged, channels included") + } + + @Test + fun flipRowsVerticallyIsItsOwnInverse() { + val original = redRow + greenRow + assertContentEquals(original, flipRowsVertically(flipRowsVertically(original, 1, 2), 1, 2), "flipping twice returns the original") + } + + @Test + fun flipRowsVerticallyMovesWholeRowsNotPixels() { + // Rows are [A B] then [C D]; the flip must yield [C D] then [A B], NOT a reversal of the whole + // buffer (which would give [D C] [B A]) - the classic way to get this wrong. + val topRow = pixel(10, 10, 10) + pixel(20, 20, 20) + val bottomRow = pixel(30, 30, 30) + pixel(40, 40, 40) + val flipped = flipRowsVertically(topRow + bottomRow, width = 2, height = 2) + assertContentEquals(bottomRow + topRow, flipped, "whole rows swap, pixel order within each row intact") + assertEquals(30, flipped[0], "the bottom row's first pixel leads after the flip") + assertEquals(40, flipped[4], "and its second pixel stays second within that row") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PoseResolveTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PoseResolveTest.kt new file mode 100644 index 0000000..2fbf7e7 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PoseResolveTest.kt @@ -0,0 +1,238 @@ +package org.umamo.render.puppet + +import org.umamo.render.eval.RenderPlanComposite +import org.umamo.render.eval.RenderPlanDrawable +import org.umamo.render.eval.flattenRenderPlan +import org.umamo.render.eval.preparePose +import org.umamo.render.glsl.MAX_GLUES +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.DEFAULT_DRAW_ORDER +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * Pins [resolvePose]: the posed-vs-drawn distinction, the drawn filter, and the glue both-posed gate. + * + * The gate had no coverage anywhere before this - not CPU, not GPU. It is the rule that stops a weld + * reading a partner's uninitialised region of the shared position store, which on a live GPU shows up as + * random geometry spikes while a parameter moves, so it is worth pinning precisely. + */ +class PoseResolveTest { + private val paramA = ParameterId("A") + + private fun drawable(id: String, indices: IntArray = intArrayOf(0, 1, 2)): Drawable { + val positions = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f) + return Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), indices), + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ), + ) + } + + private fun model(drawables: List, glues: List = emptyList()): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { OrgChild.Drawable(it.id) }, + rootPartId = null, + glues = glues, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + + private fun resolve( + source: PuppetModel, + renderable: Map, + shown: Set = source.drawables.map { it.id }.toSet(), + renderRoot: RenderGroup = RenderGroup(null, DEFAULT_DRAW_ORDER, emptyList()), + ) = resolvePose( + inputs = preparePose(source, emptyMap()), + renderableById = renderable, + shownIds = shown, + baseOrder = source.drawables.map { it.id }, + renderRoot = renderRoot, + glueIntensities = FloatArray(MAX_GLUES) { 1f }, + ) + + @Test + fun resolvePoseDrawsOnlyResidentRenderableShownDrawables() { + val source = model(listOf(drawable("a"), drawable("b"), drawable("hidden"))) + val resolved = + resolve( + source, + renderable = mapOf(DrawableId("a") to true, DrawableId("b") to true, DrawableId("hidden") to true), + shown = setOf(DrawableId("a"), DrawableId("b")), + ) + assertEquals(listOf(DrawableId("a"), DrawableId("b")), resolved.drawOrder, "the hidden drawable is not drawn") + assertTrue(DrawableId("hidden") in resolved.posed, "but it still POSES - it may be a mask source") + } + + @Test + fun resolvePosePosesAnIndexLessAnchorButDoesNotDrawIt() { + // The posed-vs-drawn distinction. An index-less glue anchor must deform (pass 1 writes its positions + // for a partner to weld against) while drawing nothing. Conflating the two breaks glue silently. + val source = model(listOf(drawable("anchor", indices = IntArray(0)), drawable("b"))) + val resolved = resolve(source, renderable = mapOf(DrawableId("anchor") to false, DrawableId("b") to true)) + assertTrue( + DrawableId("anchor") in resolved.posed, + "the anchor poses: its deformed positions are a weld partner", + ) + assertEquals(listOf(DrawableId("b")), resolved.drawOrder, "but it draws nothing") + } + + @Test + fun resolvePoseSkipsADrawableTheBackendNeverUploaded() { + val source = model(listOf(drawable("a"), drawable("absent"))) + val resolved = resolve(source, renderable = mapOf(DrawableId("a") to true)) + assertTrue(DrawableId("absent") !in resolved.posed, "a non-resident drawable cannot pose") + assertEquals(listOf(DrawableId("a")), resolved.drawOrder) + } + + @Test + fun resolvePoseGlueIntensityHoldsWhenBothMeshesPose() { + val source = + model( + listOf(drawable("a"), drawable("b")), + listOf(Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(0, 0, 0.5f, 0.5f)))), + ) + val resolved = resolve(source, renderable = mapOf(DrawableId("a") to true, DrawableId("b") to true)) + assertEquals(1f, resolved.glueIntensities[0], "both posed, so the weld runs at full intensity") + } + + @Test + fun resolvePoseZeroesGlueIntensityWhenAPartnerIsUnposed() { + // The gate. "b" is not resident, so pass 1 never writes its region of the shared store; welding + // toward it would read uninitialised memory. Zeroing makes the shader skip the partner read entirely. + val source = + model( + listOf(drawable("a"), drawable("b")), + listOf(Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(0, 0, 0.5f, 0.5f)))), + ) + val resolved = resolve(source, renderable = mapOf(DrawableId("a") to true)) + assertEquals(0f, resolved.glueIntensities[0], "an unposed partner disables the weld") + } + + @Test + fun resolvePoseGateAsksWhetherThePartnerPosedNotWhetherItDraws() { + // An index-less anchor draws nothing yet is a perfectly good partner: it poses, so the weld holds. + // Gating on "draws" instead of "poses" would silently disable every anchor-based glue. + val source = + model( + listOf(drawable("anchor", indices = IntArray(0)), drawable("b")), + listOf(Glue(DrawableId("anchor"), DrawableId("b"), listOf(GluePair(0, 0, 0f, 1f)))), + ) + val resolved = resolve(source, renderable = mapOf(DrawableId("anchor") to false, DrawableId("b") to true)) + assertEquals(1f, resolved.glueIntensities[0], "a non-drawing anchor still counts as posed") + } + + @Test + fun resolvePoseKeepsIsolatedBoundariesInThePlanAndFlattensToDrawOrder() { + val source = model(listOf(drawable("a"), drawable("b"))) + val isolatedRoot = + RenderGroup( + partId = null, + drawOrder = DEFAULT_DRAW_ORDER, + children = + listOf( + RenderDrawable(DrawableId("b")), + RenderGroup( + PartId("fx"), + 600, + listOf(RenderDrawable(DrawableId("a"))), + ChannelGrids.Empty, + PartComposite(), + ), + ), + ) + val resolved = + resolve( + source, + renderable = mapOf(DrawableId("a") to true, DrawableId("b") to true), + renderRoot = isolatedRoot, + ) + assertEquals(2, resolved.renderPlan.size) + assertEquals(DrawableId("b"), assertIs(resolved.renderPlan[0]).id) + val compositeNode = assertIs(resolved.renderPlan[1]) + assertEquals(PartId("fx"), compositeNode.partId) + assertEquals(flattenRenderPlan(resolved.renderPlan), resolved.drawOrder, "the flat order IS the plan flattened") + assertEquals(listOf(DrawableId("b"), DrawableId("a")), resolved.drawOrder) + } + + @Test + fun resolvePoseDropsACompositeNodeWhoseSubtreeFilteredAway() { + // The isolated part's only drawable is hidden → its whole composite disappears (an empty + // buffer composite would be a wasted pass); the flat order agrees. + val source = model(listOf(drawable("a"), drawable("b"))) + val isolatedRoot = + RenderGroup( + partId = null, + drawOrder = DEFAULT_DRAW_ORDER, + children = + listOf( + RenderDrawable(DrawableId("b")), + RenderGroup( + PartId("fx"), + 600, + listOf(RenderDrawable(DrawableId("a"))), + ChannelGrids.Empty, + PartComposite(), + ), + ), + ) + val resolved = + resolve( + source, + renderable = mapOf(DrawableId("a") to true, DrawableId("b") to true), + shown = setOf(DrawableId("b")), + renderRoot = isolatedRoot, + ) + assertEquals(1, resolved.renderPlan.size, "the empty composite node is dropped") + assertEquals(DrawableId("b"), assertIs(resolved.renderPlan.single()).id) + assertEquals(listOf(DrawableId("b")), resolved.drawOrder) + } + + @Test + fun resolvePoseGlueIntensitiesBeyondTheShaderArrayAreDropped() { + // MAX_GLUES is a shader contract (uniform float glueIntensity[MAX_GLUES]), not a tuning knob: glue + // #65+ renders UNWELDED rather than overrunning the array. Pinned so the ceiling is not "fixed" by + // growing the Kotlin side alone, which would silently disagree with the GLSL. + val drawables = listOf(drawable("a"), drawable("b")) + val glues = List(70) { Glue(DrawableId("a"), DrawableId("b"), listOf(GluePair(0, 0, 0.5f, 0.5f))) } + val resolved = + resolve(model(drawables, glues), renderable = mapOf(DrawableId("a") to true, DrawableId("b") to true)) + assertEquals(64, resolved.glueIntensities.size, "the array is exactly the shader's") + assertEquals(1f, resolved.glueIntensities[63], "the last addressable glue resolves") + } +} \ No newline at end of file diff --git a/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PosedBoundsTest.kt b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PosedBoundsTest.kt new file mode 100644 index 0000000..1607ac5 --- /dev/null +++ b/module/render/src/commonTest/kotlin/org/umamo/render/puppet/PosedBoundsTest.kt @@ -0,0 +1,132 @@ +package org.umamo.render.puppet + +import org.umamo.render.eval.MeshBlendContribution +import org.umamo.render.eval.MeshBlendState +import org.umamo.render.eval.RotationWorld +import org.umamo.render.eval.WarpWorld +import org.umamo.render.eval.rotationXform +import org.umamo.render.eval.warpApply +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins [deformedWorldBounds] - the exact deformed-world AABB the composite scissor is built from. + * The contract is that the bound equals the true deformed geometry (min/max of the exact deform), so + * the scissor never clips: every case here rebuilds the deform independently and asserts equality, + * including a warp vertex OUTSIDE the lattice (the extrapolation case a cheap analytic bound + * undersized, clipping heads and arm tips). Pure math, no GPU. + */ +class PosedBoundsTest { + private val paramA = ParameterId("A") + + /** A one-cell grid over [base]'s vertex count, whose single cell holds [deltas]. */ + private fun oneCellCells(deltas: FloatArray): Map> { + val grid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(deltas))), + ) + return cellsByLinearIndex(grid) + } + + private val fullCorner = listOf(WeightedCell(0, 1f)) + + @Test + fun directMeshBlendsCornersAndNegatesY() { + // base (1,2)(3,5) + cell delta (10,0)(0,0) -> local (11,2)(3,5) -> Y-negate (11,-2)(3,-5). + val base = floatArrayOf(1f, 2f, 3f, 5f) + val cells = oneCellCells(floatArrayOf(10f, 0f, 0f, 0f)) + val bounds = deformedWorldBounds(base, cells, fullCorner, parentWorld = null, blend = null)!! + assertEquals(3f, bounds.minX) + assertEquals(11f, bounds.maxX) + assertEquals(-5f, bounds.minY) + assertEquals(-2f, bounds.maxY) + } + + @Test + fun blendShapeDeltasWidenTheBound() { + // One vertex, zero grid delta, a blend contribution of (+4, +6) at weight 0.5 relative to a + // (+1, +2) reference -> local (0,0) + 0.5*((4,6)-(1,2)) = (1.5, 2) -> Y-negate (1.5, -2). + val base = floatArrayOf(0f, 0f) + val cells = oneCellCells(floatArrayOf(0f, 0f)) + val blend = + MeshBlendState( + contributions = listOf(MeshBlendContribution(bindingIndex = 0, keyIndex = 0, form = MeshForm(floatArrayOf(4f, 6f)), weight = 0.5f)), + referenceDeltas = floatArrayOf(1f, 2f), + referenceDrawOrder = 0f, + referenceOpacity = 1f, + ) + val bounds = deformedWorldBounds(base, cells, fullCorner, parentWorld = null, blend = blend)!! + assertClose(1.5f, bounds.minX) + assertClose(1.5f, bounds.maxX) + assertClose(-2f, bounds.minY) + assertClose(-2f, bounds.maxY) + } + + @Test + fun rotationParentTransformsExactly() { + // A 90-degree rotation about the origin maps (x, y) -> (-y, x) before the Y-negate; a box + // [1,3]x[0,2] -> corners approx (0,1)(0,3)(-2,1)(-2,3) -> x[-2,0], y[1,3] -> Y-negate y[-3,-1]. + val rotation = RotationWorld(rotationXform(90f, 1f, flipX = false, flipY = false, ox = 0f, oy = 0f), accY = 1f) + val base = floatArrayOf(1f, 0f, 3f, 0f, 1f, 2f, 3f, 2f) + val cells = oneCellCells(FloatArray(8)) + val bounds = deformedWorldBounds(base, cells, fullCorner, parentWorld = rotation, blend = null)!! + assertClose(-2f, bounds.minX) + assertClose(0f, bounds.maxX) + assertClose(-3f, bounds.minY) + assertClose(-1f, bounds.maxY) + } + + @Test + fun warpParentInGridMatchesTheLattice() { + // A 1x1 bilinear lattice mapping the unit square to world [10,20]x[30,50]; the unit-square mesh + // recovers that rect, Y-negated. + val warp = WarpWorld(floatArrayOf(10f, 30f, 20f, 30f, 10f, 50f, 20f, 50f), cols = 1, rows = 1, bilinear = true, accY = 1f) + val base = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f) + val cells = oneCellCells(FloatArray(8)) + val bounds = deformedWorldBounds(base, cells, fullCorner, parentWorld = warp, blend = null)!! + assertClose(10f, bounds.minX) + assertClose(20f, bounds.maxX) + assertClose(-50f, bounds.minY) + assertClose(-30f, bounds.maxY) + } + + @Test + fun warpParentExtrapolatedVertexMatchesWarpApply() { + // The case a cheap analytic bound got wrong: a vertex OUTSIDE the lattice (u = 1.5). The exact + // bound must equal warpApply itself - not an undersized approximation that would clip the vertex. + val cp = floatArrayOf(10f, 30f, 20f, 30f, 10f, 50f, 20f, 50f) + val warp = WarpWorld(cp, cols = 1, rows = 1, bilinear = true, accY = 1f) + val expected = FloatArray(2) + warpApply(cp, 1, 1, true, 1.5f, 0.5f, expected, 0) + val bounds = deformedWorldBounds(floatArrayOf(1.5f, 0.5f), oneCellCells(floatArrayOf(0f, 0f)), fullCorner, parentWorld = warp, blend = null)!! + // One vertex, so min == max == the exact warp image, Y-negated. + assertClose(expected[0], bounds.minX) + assertClose(expected[0], bounds.maxX) + assertClose(-expected[1], bounds.minY) + assertClose(-expected[1], bounds.maxY) + } + + @Test + fun unionBoundsCoversBoth() { + val union = unionBounds(PosedAabb(0f, 0f, 2f, 2f), PosedAabb(-1f, 3f, 1f, 5f)) + assertEquals(-1f, union.minX) + assertEquals(0f, union.minY) + assertEquals(2f, union.maxX) + assertEquals(5f, union.maxY) + } + + private fun assertClose(expected: Float, actual: Float) { + assertTrue(abs(expected - actual) < 1e-3f, "expected ~$expected, got $actual") + } +} \ No newline at end of file diff --git a/module/render/src/iosMain/kotlin/org/umamo/render/metal/MetalRenderDevice.kt b/module/render/src/iosMain/kotlin/org/umamo/render/metal/MetalRenderDevice.kt new file mode 100644 index 0000000..ccfe0ff --- /dev/null +++ b/module/render/src/iosMain/kotlin/org/umamo/render/metal/MetalRenderDevice.kt @@ -0,0 +1,146 @@ +package org.umamo.render.metal + +import org.umamo.format.raster.RasterImage +import org.umamo.render.device.DeformCapturePipeline +import org.umamo.render.device.DeformedPositionStore +import org.umamo.render.device.FrameEncoder +import org.umamo.render.device.GpuMesh +import org.umamo.render.device.GpuTexture +import org.umamo.render.device.MeshSpec +import org.umamo.render.device.ReadbackTicket +import org.umamo.render.device.RenderDevice +import org.umamo.render.device.RenderPipeline +import org.umamo.render.device.RenderPipelineSpec +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.ScissorRect +import org.umamo.render.device.TextureFilter +import org.umamo.render.device.TextureFormat +import org.umamo.render.device.TextureWrap + +/** + * The iPadOS Metal [RenderDevice] - a STUB marking the port's entry point; nothing is implemented. + * + * Implementing this ONE interface is the whole port: `PuppetRenderer` and everything it stands on + * (the deform eval, pose resolution, glue planning, model diff) are backend-neutral commonMain and + * come along for free. Kotlin/Native reaches Metal directly via `platform.Metal`; a Swift-side + * implementation bridged through this interface works too. + * + * What is genuinely different from the GL device, decided up front so the port does not rediscover it: + * - Shaders are MSL, keyed by [RenderPipelineSpec.purpose] - the GLSL in `org.umamo.render.glsl` is a + * GL-family asset and none of it is reused. The fidelity-critical piece is `deformWorld` + * (DeformGlsl.kt): ~200 lines whose `warpExtrap` lattice extrapolation silently breaks rig fidelity + * if mistranslated. Build the MSL equivalent of `GpuDeformValidationTest` (the GPU-vs-CPU oracle; + * the CPU side is commonMain and already available here) BEFORE trusting the translation - and the + * glue equivalent of `GpuGlueValidationTest` alongside it. + * - [createDeformCapturePipeline] / the capture pass: Metal has no transform feedback - a compute + * kernel reads base positions + the delta texture and writes the store, which is naturally a + * `device float2*` buffer here rather than any texture. + * - [FrameEncoder.barrier] is a GENUINE no-op: Metal orders encoder-to-encoder resource dependencies + * within a command buffer itself. Correct, not a stub - do not add a wait. + * - Blend is baked into the MTLRenderPipelineState per [RenderPipelineSpec] (the API is already shaped + * for that); `LoadAction`/`StoreAction` map 1:1 onto MTLRenderPassDescriptor and are real wins on a + * tile-based GPU (the grid pass is DontCare - the tile is never fetched). + * - [readPixels] returns TOP row first per the API contract. Metal's origin is already top-left, so + * unlike the GL device there is NO row flip here. + * - Two conventions inside the shaders are CONTENT, not backend, and must be kept verbatim in MSL: + * `deformWorld`'s final Y negation (the CMO3 Y-down → Umamo Y-up format convention) and the atlas + * page quad's V-flip (Y-up display vs top-first atlas rows). "Correcting" either for Metal's + * texture origin inverts the rig or the page. + * - The mask pass and the main pass must share one screen-space convention (the fragment position the + * coverage lookup divides by viewport size) - self-consistent per backend, silently wrong if only + * one pass is flipped. Worst on masked warp meshes, which draw twice. + * - The uniform structs ([org.umamo.render.device.DeformUniforms] etc.) are MUTABLE AND REUSED per + * draw: marshal every field before returning (`setVertexBytes` copies, so that is natural) and + * never retain the instance. + */ +class MetalRenderDevice : RenderDevice { + override fun createTexture( + width: Int, + height: Int, + format: TextureFormat, + filter: TextureFilter, + pixels: ByteArray?, + wrap: TextureWrap, + ): GpuTexture = + TODO( + "Metal port: MTLTexture (RGBA8Unorm / RG32Float), top-first upload needs no flip; wrap is the " + + "sampler's addressMode - clampToEdge or clampToZero, and a sampler is per-texture here", + ) + + override fun createFloatTexture(width: Int, height: Int, filter: TextureFilter, texels: FloatArray): GpuTexture = + TODO("Metal port: RG32Float MTLTexture") + + override fun updateFloatTexture(texture: GpuTexture, width: Int, height: Int, texels: FloatArray): Unit = + TODO("Metal port: replaceRegion in place (keep the once-per-pose contract)") + + override fun createMesh(spec: MeshSpec): GpuMesh = + TODO("Metal port: MTLBuffers; vertex layout lives in the pipeline descriptor, not the mesh") + + override fun updateMeshPositions(mesh: GpuMesh, restPositions: FloatArray): Unit = TODO("Metal port") + + override fun updateMeshUvs(mesh: GpuMesh, uvs: FloatArray): Unit = TODO("Metal port") + + override fun createRenderTarget(spec: RenderTargetSpec): RenderTarget = + TODO("Metal port: MTLTexture with usage renderTarget (+ shaderRead when spec.sampled)") + + override fun createDeformedPositionStore(vertexCapacity: Int): DeformedPositionStore = + TODO("Metal port: a device float2* MTLBuffer - no texture indirection needed here") + + override fun createRenderPipeline(spec: RenderPipelineSpec): RenderPipeline = + TODO("Metal port: MTLRenderPipelineState from the MSL library, keyed by spec.purpose, blend baked per spec.blend") + + override fun createDeformCapturePipeline(): DeformCapturePipeline = + TODO("Metal port: a compute pipeline - Metal has no transform feedback; see the class docblock") + + override fun destroyTexture(texture: GpuTexture): Unit = TODO("Metal port") + + override fun destroyMesh(mesh: GpuMesh): Unit = TODO("Metal port") + + override fun destroyRenderTarget(target: RenderTarget): Unit = TODO("Metal port") + + override fun beginFrame(): FrameEncoder = + TODO("Metal port: open a command buffer; passes are encoders; barrier() is a genuine no-op; endFrame commits") + + override fun resolve(source: RenderTarget, destination: RenderTarget, region: ScissorRect?): Unit = + TODO( + "Metal port: region == null is the scaled full-surface downscale (a full-screen textured draw or " + + "MPSImageBilinearScale - NOT a blit encoder, which can neither filter nor scale); region != null is a " + + "same-size sub-rect copy (the composite snapshot), for which a plain MTLBlitCommandEncoder copy is exact.", + ) + + override fun resolveUsed( + source: RenderTarget, + sourceUsedWidth: Int, + sourceUsedHeight: Int, + destination: RenderTarget, + destinationUsedWidth: Int, + destinationUsedHeight: Int, + region: ScissorRect?, + ): Unit = + TODO( + "Metal port: like resolve but over the used regions. Content anchors at Metal's TOP-LEFT origin, " + + "so the used region is the top-left rows and a non-null region needs no y conversion at all.", + ) + + override fun beginReadback(target: RenderTarget): ReadbackTicket = + TODO("Metal port: blit target into a shared-storage staging buffer, addCompletedHandler flags the ticket done") + + override fun beginReadback(target: RenderTarget, usedWidth: Int, usedHeight: Int): ReadbackTicket = + TODO("Metal port: the full-target beginReadback over the top-left used region (no flip on this backend)") + + override fun pollReadback(ticket: ReadbackTicket): RasterImage? = + TODO("Metal port: drain the completed flag ON THE POLL, so results arrive on the render thread whatever thread the handler ran on; top-first already, no row flip") + + override fun cancelReadback(ticket: ReadbackTicket): Unit = TODO("Metal port") + + override fun readPixels(target: RenderTarget): RasterImage = + TODO("Metal port: getBytes - already top-first, NO row flip (unlike the GL device)") + + override fun readPixels(target: RenderTarget, usedWidth: Int, usedHeight: Int): RasterImage = + TODO("Metal port: the full-target readPixels over the top-left used region (no flip on this backend)") + + override fun maxRenderTargetSize(): Int = TODO("Metal port: the device family's maximum 2D texture width (16384 on Apple GPU families 3 and up)") + + override fun describeBackend(): String = TODO("Metal port: MTLDevice.name") +} \ No newline at end of file diff --git a/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlFrameEncoder.kt b/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlFrameEncoder.kt new file mode 100644 index 0000000..ea32a9d --- /dev/null +++ b/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlFrameEncoder.kt @@ -0,0 +1,397 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL13 +import org.lwjgl.opengl.GL14 +import org.lwjgl.opengl.GL20 +import org.lwjgl.opengl.GL30 +import org.lwjgl.opengl.GL31 +import org.umamo.render.device.AxisLineUniforms +import org.umamo.render.device.CompositeUniforms +import org.umamo.render.device.DeformCapturePassEncoder +import org.umamo.render.device.DeformCapturePipeline +import org.umamo.render.device.DeformUniforms +import org.umamo.render.device.DeformedPositionStore +import org.umamo.render.device.DrawTextures +import org.umamo.render.device.FragmentUniforms +import org.umamo.render.device.FrameEncoder +import org.umamo.render.device.GpuMesh +import org.umamo.render.device.GpuTexture +import org.umamo.render.device.GridUniforms +import org.umamo.render.device.LoadAction +import org.umamo.render.device.RenderPassEncoder +import org.umamo.render.device.RenderPassSpec +import org.umamo.render.device.RenderPipeline +import org.umamo.render.device.TextureFilter +import org.umamo.render.device.TextureWrap +import org.umamo.render.device.WorldToNdc +import org.umamo.render.glsl.UNIT_ATLAS +import org.umamo.render.glsl.UNIT_CP +import org.umamo.render.glsl.UNIT_DELTA +import org.umamo.render.glsl.UNIT_DEST +import org.umamo.render.glsl.UNIT_LAYER +import org.umamo.render.glsl.UNIT_MASK +import org.umamo.render.glsl.UNIT_POSITION +import java.nio.FloatBuffer +import java.nio.IntBuffer + +/** + * The GL implementation of one frame's recorded work. + * + * GL has no command buffer, so "recording" is really "issuing immediately": each call runs against the + * current context as it arrives. The encoder shape still earns its keep - it names the target every pass + * writes and fixes each pipeline's blend up front, both of which read better than the ambient-state + * idiom - and it is what a Metal backend, which does have command buffers, would map onto directly. + * + * @param Int emptyVao A bound VAO for the attribute-less draws (grid, axis, atlas page); a core profile + * requires one even when the shader synthesises positions from gl_VertexID. + */ +internal class GlFrameEncoder(private val emptyVao: Int) : FrameEncoder { + override fun beginRenderPass(spec: RenderPassSpec): RenderPassEncoder { + val target = spec.colorTarget as GlRenderTarget + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, target.framebuffer) + GL11.glViewport(0, 0, spec.viewportWidth, spec.viewportHeight) + val scissor = spec.scissor + if (scissor != null) { + // The spec's rect is top-left-origin (the read-back convention); GL scissors bottom-up. + GL11.glEnable(GL11.GL_SCISSOR_TEST) + GL11.glScissor(scissor.x, spec.viewportHeight - scissor.y - scissor.height, scissor.width, scissor.height) + } else { + GL11.glDisable(GL11.GL_SCISSOR_TEST) + } + if (spec.loadAction == LoadAction.Clear) { + // With a scissor set, the clear is confined to the rect too - that is the point: a + // bounds-scissored composite layer never pays a full-viewport clear. + GL11.glClearColor(spec.clearRed, spec.clearGreen, spec.clearBlue, spec.clearAlpha) + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT) + } + // Load preserves the target's contents (a bound FBO already holds them); DontCare needs no work on + // GL - the pass overwrites every pixel, which a tile-based backend would exploit but GL cannot. + return GlRenderPassEncoder(emptyVao) + } + + override fun beginDeformCapturePass(pipeline: DeformCapturePipeline, store: DeformedPositionStore): DeformCapturePassEncoder { + val glPipeline = pipeline as GlDeformCapturePipeline + GL20.glUseProgram(glPipeline.program) + GL20.glUniform1i(glPipeline.locations.deltaTex, UNIT_DELTA) + GL20.glUniform1i(glPipeline.locations.cpTex, UNIT_CP) + // Discard the rasterizer: the capture writes positions via transform feedback and draws nothing. + GL11.glEnable(GL30.GL_RASTERIZER_DISCARD) + return GlDeformCapturePassEncoder(glPipeline, store as GlDeformedPositionStore) + } + + override fun barrier(store: DeformedPositionStore) { + // The declared write→read dependency on the position store. The WSL d3d12/Mesa stack does not order + // transform-feedback writes before a later texture-buffer read, and glMemoryBarrier does not cover + // feedback writes (they are coherent-pipeline writes), so the full sync is the only reliable fix. + // Called only on pose-change frames, so a static pose pays nothing. + GL11.glFinish() + } + + override fun endFrame() { + // Nothing to submit on GL: the calls already ran. A command-buffer backend would commit here. + } +} + +/** Records draws into one GL render pass. */ +internal class GlRenderPassEncoder(private val emptyVao: Int) : RenderPassEncoder { + private var pipeline: GlRenderPipeline? = null + private val current: GlRenderPipeline get() = pipeline ?: error("setPipeline before drawing") + + // Per-program state is re-established only when the program actually switches. A uniform keeps its value + // on the program object across binds, and the renderer passes the same camera / glue state for a whole + // pass, so re-sending them per draw (as the pre-device renderer's useProgramFor did NOT) is wasted work: + // a run of same-blend drawables would otherwise churn glUseProgram + blend + samplers + camera every draw. + private var cameraApplied = false + private var glueStateApplied = false + + // Scratch for the corner uniform arrays, reused across draws so the per-draw marshalling never allocates. + private val cornerCellScratch = BufferUtils.createIntBuffer(org.umamo.render.glsl.MAX_CORNERS) + private val cornerWeightScratch = BufferUtils.createFloatBuffer(org.umamo.render.glsl.MAX_CORNERS) + + override fun setPipeline(pipeline: RenderPipeline) { + val glPipeline = pipeline as GlRenderPipeline + if (glPipeline === this.pipeline) { + return // already bound: program, blend, and samplers are all still in effect + } + this.pipeline = glPipeline + cameraApplied = false + glueStateApplied = false + GL20.glUseProgram(glPipeline.program) + applyBlend(glPipeline.blend) + applyCull(glPipeline.cullBackFaces) + // Sampler → texture unit is constant per program; -1 for a sampler the program lacks is a no-op. + val locations = glPipeline.locations + GL20.glUniform1i(locations.atlas, UNIT_ATLAS) + GL20.glUniform1i(locations.maskTexture, UNIT_MASK) + GL20.glUniform1i(locations.deltaTex, UNIT_DELTA) + GL20.glUniform1i(locations.cpTex, UNIT_CP) + GL20.glUniform1i(locations.positionBuffer, UNIT_POSITION) + GL20.glUniform1i(locations.layerTexture, UNIT_LAYER) + GL20.glUniform1i(locations.destTexture, UNIT_DEST) + } + + override fun setCamera(worldToNdc: WorldToNdc, screenTexWidth: Int, screenTexHeight: Int) { + if (cameraApplied) { + return // the current program already holds this pass's camera (constant across the pass) + } + cameraApplied = true + val locations = current.locations + GL20.glUniform4f(locations.worldToNdc, worldToNdc.scaleX, worldToNdc.scaleY, worldToNdc.offsetX, worldToNdc.offsetY) + GL20.glUniform2f(locations.screenTexSize, screenTexWidth.toFloat(), screenTexHeight.toFloat()) + } + + override fun drawPuppetMesh(mesh: GpuMesh, deform: DeformUniforms, fragment: FragmentUniforms, textures: DrawTextures) { + marshalDeformUniforms(current.locations, deform, textures, cornerCellScratch, cornerWeightScratch) + setFragmentUniforms(current, fragment, textures) + val glMesh = mesh as GlMesh + GL30.glBindVertexArray(glMesh.vao) + GL11.glDrawElements(GL11.GL_TRIANGLES, glMesh.indexCount, GL11.GL_UNSIGNED_INT, 0L) + } + + override fun drawGlueMesh( + mesh: GpuMesh, + store: DeformedPositionStore, + baseVertexOffset: Int, + glueIntensities: FloatArray, + fragment: FragmentUniforms, + textures: DrawTextures, + ) { + val locations = current.locations + // The weld intensities and the position texture buffer are constant across the pass, so bind them + // once per glue-program bind (matching the old useProgramFor), not per glue draw. + if (!glueStateApplied) { + glueStateApplied = true + GL20.glUniform1fv(locations.glueIntensity, glueIntensities) + GL13.glActiveTexture(GL13.GL_TEXTURE0 + UNIT_POSITION) + GL11.glBindTexture(GL31.GL_TEXTURE_BUFFER, (store as GlDeformedPositionStore).textureBuffer) + } + GL20.glUniform1i(locations.baseOffset, baseVertexOffset) + setFragmentUniforms(current, fragment, textures) + val glMesh = mesh as GlMesh + GL30.glBindVertexArray(glMesh.vao) + GL11.glDrawElements(GL11.GL_TRIANGLES, glMesh.indexCount, GL11.GL_UNSIGNED_INT, 0L) + } + + override fun drawAtlasPage(atlas: GpuTexture, pageWidth: Float, pageHeight: Float, fragment: FragmentUniforms) { + val locations = current.locations + GL20.glUniform2f(locations.pageSize, pageWidth, pageHeight) + setFragmentUniforms(current, fragment, DrawTextures().also { it.atlas = atlas }) + GL30.glBindVertexArray(emptyVao) + GL11.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, 4) + } + + override fun drawComposite(composite: CompositeUniforms, textures: DrawTextures) { + val locations = current.locations + GL20.glUniform1i(locations.colorMode, composite.colorMode) + GL20.glUniform1i(locations.alphaMode, composite.alphaMode) + GL20.glUniform1f(locations.opacity, composite.opacity) + GL20.glUniform3f(locations.multiplyColor, composite.multiplyRed, composite.multiplyGreen, composite.multiplyBlue) + GL20.glUniform3f(locations.screenColor, composite.screenRed, composite.screenGreen, composite.screenBlue) + GL20.glUniform1i(locations.useMask, if (composite.useMask) 1 else 0) + GL20.glUniform1i(locations.invertMask, if (composite.invertMask) 1 else 0) + textures.compositeLayer?.let { bindTexture2D(UNIT_LAYER, it) } + textures.destinationSnapshot?.let { bindTexture2D(UNIT_DEST, it) } + if (composite.useMask) { + textures.maskCoverage?.let { bindTexture2D(UNIT_MASK, it) } + } + GL30.glBindVertexArray(emptyVao) + GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3) + } + + override fun drawGrid(uniforms: GridUniforms) { + val locations = current.locations + val affine = uniforms.worldToNdc + GL20.glUniform4f(locations.worldToNdc, affine.scaleX, affine.scaleY, affine.offsetX, affine.offsetY) + GL20.glUniform2f(locations.viewportSize, uniforms.viewportWidth.toFloat(), uniforms.viewportHeight.toFloat()) + GL20.glUniform2f(locations.majorSpacing, uniforms.majorSpacingX, uniforms.majorSpacingY) + GL20.glUniform2f(locations.gridOrigin, uniforms.originX, uniforms.originY) + GL20.glUniform1f(locations.subdivisions, uniforms.subdivisions.toFloat()) + GL20.glUniform1f(locations.lineWidthPx, uniforms.lineWidthPx) + val colors = uniforms.colors + GL20.glUniform3f(locations.backgroundColor, colors.backgroundRed, colors.backgroundGreen, colors.backgroundBlue) + GL20.glUniform3f(locations.majorColor, colors.majorRed, colors.majorGreen, colors.majorBlue) + GL20.glUniform3f(locations.minorColor, colors.minorRed, colors.minorGreen, colors.minorBlue) + GL30.glBindVertexArray(emptyVao) + GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3) + } + + override fun drawAxisLine(uniforms: AxisLineUniforms) { + val locations = current.locations + GL20.glUniform1f(locations.linePositionNdc, uniforms.linePositionNdc) + GL20.glUniform1f(locations.lineVertical, if (uniforms.vertical) 1f else 0f) + GL20.glUniform3f(locations.lineColor, uniforms.red, uniforms.green, uniforms.blue) + GL30.glBindVertexArray(emptyVao) + GL11.glDrawArrays(GL11.GL_LINES, 0, 2) + } + + override fun end() { + GL30.glBindVertexArray(0) + GL20.glUseProgram(0) + // Scissor is per-pass state established in beginRenderPass; dropping it here keeps the + // between-pass operations (resolve blits, read-backs) unclipped whatever pass ran last. + GL11.glDisable(GL11.GL_SCISSOR_TEST) + } + + /** Sets a draw's fragment uniforms and binds its atlas / mask textures when present. */ + private fun setFragmentUniforms(pipeline: GlRenderPipeline, fragment: FragmentUniforms, textures: DrawTextures) { + val locations = pipeline.locations + GL20.glUniform1i(locations.useTexture, if (fragment.useTexture) 1 else 0) + val atlas = textures.atlas + if (fragment.useTexture && atlas != null) { + bindTexture2D(UNIT_ATLAS, atlas) + // The shader filters linear art itself, past the sampler, so it is told what the sampler would do. + val glAtlas = atlas as GlTexture + GL20.glUniform1i(locations.atlasLinear, if (glAtlas.filter == TextureFilter.Linear) 1 else 0) + GL20.glUniform1i(locations.atlasTransparentBorder, if (glAtlas.wrap == TextureWrap.ClampToTransparentBorder) 1 else 0) + } else { + GL20.glUniform4f(locations.drawColor, fragment.colorRed, fragment.colorGreen, fragment.colorBlue, fragment.colorAlpha) + } + GL20.glUniform1f(locations.opacity, fragment.opacity) + GL20.glUniform3f(locations.multiplyColor, fragment.multiplyRed, fragment.multiplyGreen, fragment.multiplyBlue) + GL20.glUniform3f(locations.screenColor, fragment.screenRed, fragment.screenGreen, fragment.screenBlue) + GL20.glUniform1f(locations.highlight, fragment.highlight) + GL20.glUniform3f(locations.highlightColor, fragment.highlightRed, fragment.highlightGreen, fragment.highlightBlue) + // Sent every draw, like the rest of these - a program that does not declare them resolves -1, and + // glUniform* with -1 is a defined no-op, so the grid / composite / axis pipelines ignore it. + GL20.glUniform3f(locations.uvAffineRow0, fragment.uvAffine[0], fragment.uvAffine[1], fragment.uvAffine[2]) + GL20.glUniform3f(locations.uvAffineRow1, fragment.uvAffine[3], fragment.uvAffine[4], fragment.uvAffine[5]) + GL20.glUniform1i(locations.useMask, if (fragment.useMask) 1 else 0) + GL20.glUniform1i(locations.invertMask, if (fragment.invertMask) 1 else 0) + if (fragment.useMask) { + textures.maskCoverage?.let { bindTexture2D(UNIT_MASK, it) } + } + } +} + +/** Records the pass-1 deform capture into the shared position store. */ +internal class GlDeformCapturePassEncoder( + private val pipeline: GlDeformCapturePipeline, + private val store: GlDeformedPositionStore, +) : DeformCapturePassEncoder { + private val cornerCellScratch = BufferUtils.createIntBuffer(org.umamo.render.glsl.MAX_CORNERS) + private val cornerWeightScratch = BufferUtils.createFloatBuffer(org.umamo.render.glsl.MAX_CORNERS) + + override fun captureDeformedPositions( + mesh: GpuMesh, + deform: DeformUniforms, + textures: DrawTextures, + destinationVertexOffset: Int, + vertexCount: Int, + ) { + marshalDeformUniforms(pipeline.locations, deform, textures, cornerCellScratch, cornerWeightScratch) + GL30.glBindVertexArray((mesh as GlMesh).vao) + GL30.glBindBufferRange( + GL30.GL_TRANSFORM_FEEDBACK_BUFFER, + 0, + store.buffer, + destinationVertexOffset.toLong() * 2 * Float.SIZE_BYTES, + vertexCount.toLong() * 2 * Float.SIZE_BYTES, + ) + GL30.glBeginTransformFeedback(GL11.GL_POINTS) + GL11.glDrawArrays(GL11.GL_POINTS, 0, vertexCount) + GL30.glEndTransformFeedback() + } + + override fun end() { + GL11.glDisable(GL30.GL_RASTERIZER_DISCARD) + } +} + +/** + * Marshals a mesh's per-pose deform uniforms and binds its delta (and, for a warp parent, control-point) + * texture. + * + * Shared by the pass-2 draw and the pass-1 capture so the two paths cannot diverge: they feed the exact + * same deform inputs to the exact same DEFORM_GLSL, which is what lets GpuDeformValidationTest's pin on the + * draw path also stand for the capture path. Both pass their own reused scratch buffers. + * + * @param GlUniformLocations locations The bound program's uniform locations. + * @param DeformUniforms deform The per-pose deform inputs. + * @param DrawTextures textures The delta and (warp) control-point textures to bind. + * @param IntBuffer cornerCellScratch Reused scratch for the corner-cell uniform array. + * @param FloatBuffer cornerWeightScratch Reused scratch for the corner-weight uniform array. + */ +private fun marshalDeformUniforms( + locations: GlUniformLocations, + deform: DeformUniforms, + textures: DrawTextures, + cornerCellScratch: IntBuffer, + cornerWeightScratch: FloatBuffer, +) { + val cornerCount = minOf(org.umamo.render.glsl.MAX_CORNERS, deform.cornerCount) + cornerCellScratch.clear() + cornerWeightScratch.clear() + for (cornerIndex in 0 until cornerCount) { + cornerCellScratch.put(deform.cornerCell[cornerIndex]) + cornerWeightScratch.put(deform.cornerWeight[cornerIndex]) + } + cornerCellScratch.flip() + cornerWeightScratch.flip() + GL20.glUniform1i(locations.cornerCount, cornerCount) + GL20.glUniform1iv(locations.cornerCell, cornerCellScratch) + GL20.glUniform1fv(locations.cornerWeight, cornerWeightScratch) + // Blend-shape columns: skip the array uploads entirely for the zero-blend common case. + val blendCount = minOf(org.umamo.render.glsl.MAX_BLEND_CORNERS, deform.blendCount) + GL20.glUniform1i(locations.blendCount, blendCount) + if (blendCount > 0) { + GL20.glUniform1iv(locations.blendCell, deform.blendCell) + GL20.glUniform1fv(locations.blendWeight, deform.blendWeight) + } + GL20.glUniform1i(locations.parentType, deform.parentType) + if (deform.parentType == 1) { + GL20.glUniform1fv(locations.rot, deform.rotation) + } else if (deform.parentType == 2) { + GL20.glUniform1i(locations.warpCols, deform.warpColumns) + GL20.glUniform1i(locations.warpRows, deform.warpRows) + GL20.glUniform1i(locations.warpBilinear, if (deform.warpBilinear) 1 else 0) + textures.warpControlPoints?.let { bindTexture2D(UNIT_CP, it) } + } + textures.deltaTexture?.let { bindTexture2D(UNIT_DELTA, it) } +} + +/** Binds [texture] to the given texture unit as a 2D texture. */ +private fun bindTexture2D(unit: Int, texture: GpuTexture) { + GL13.glActiveTexture(GL13.GL_TEXTURE0 + unit) + GL11.glBindTexture(GL11.GL_TEXTURE_2D, (texture as GlTexture).handle) +} + +/** + * Sets the face-culling state for a pipeline. Applied on every pipeline bind (like blend) because + * GL cull state is global - a culled drawable's pipeline must not leak culling into the next draw. + * The front face is CW: corpus rest meshes bake CLOCKWISE in the renderer's Y-negated world space + * (probed 50933:0 on EricaTamamo), so a culled drawable stays visible at rest and disappears only + * when a deformation flips it inside-out. This winding convention is inferred from corpus mesh + * data, not yet cross-checked against the official editor's own culling render. + * + * @param Boolean cullBackFaces True to cull back faces; false leaves the mesh double-sided. + */ +private fun applyCull(cullBackFaces: Boolean) { + if (cullBackFaces) { + GL11.glEnable(GL11.GL_CULL_FACE) + GL11.glFrontFace(GL11.GL_CW) + GL11.glCullFace(GL11.GL_BACK) + } else { + GL11.glDisable(GL11.GL_CULL_FACE) + } +} + +/** Sets the fixed-function blend state for a pipeline's blend mode. */ +private fun applyBlend(blend: org.umamo.render.device.PipelineBlend) { + when (blend) { + org.umamo.render.device.PipelineBlend.Opaque -> GL11.glDisable(GL11.GL_BLEND) + org.umamo.render.device.PipelineBlend.Normal -> { + GL11.glEnable(GL11.GL_BLEND) + GL14.glBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA) + } + org.umamo.render.device.PipelineBlend.Additive -> { + GL11.glEnable(GL11.GL_BLEND) + GL14.glBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE) + } + org.umamo.render.device.PipelineBlend.Multiply -> { + GL11.glEnable(GL11.GL_BLEND) + GL14.glBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ZERO, GL11.GL_ONE) + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlHandles.kt b/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlHandles.kt new file mode 100644 index 0000000..91a0b14 --- /dev/null +++ b/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlHandles.kt @@ -0,0 +1,165 @@ +package org.umamo.render.gl + +import org.lwjgl.opengl.GL20 +import org.umamo.render.device.DeformCapturePipeline +import org.umamo.render.device.DeformedPositionStore +import org.umamo.render.device.GpuMesh +import org.umamo.render.device.GpuTexture +import org.umamo.render.device.PipelineBlend +import org.umamo.render.device.RenderPipeline +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.TextureFilter +import org.umamo.render.device.TextureWrap + +// The GL device's concrete handles. Each wraps the GL names its interface hides; nothing outside this +// package can reach them, which is what keeps GL out of the shared renderer. + +/** + * A GL texture name, with the filter and wrap it was created with. + * + * The puppet fragment shader filters art in-shader through `texelFetch`, which bypasses the sampler, so + * the encoder reads these to tell the shader what the sampler would have done. + */ +internal class GlTexture(val handle: Int, val filter: TextureFilter, val wrap: TextureWrap) : GpuTexture + +/** + * A mesh's GL residency: the VAO plus every buffer it references. + * + * The buffers are kept individually, not just the VAO, because they outlive their bindings: an edit + * re-uploads [positionVbo] / [uvVbo] in place, and freeing the mesh must free all of them. 0 where the + * mesh has none - an index-less glue anchor has no [indexEbo], a non-glue mesh no [glueVbo]. + */ +internal class GlMesh( + val vao: Int, + val positionVbo: Int, + val uvVbo: Int, + val glueVbo: Int, + val indexEbo: Int, + val vertexCount: Int, + val indexCount: Int, +) : GpuMesh + +/** + * A render target: its framebuffer plus whichever attachment backs it. + * + * Exactly one of [colorTexture] / [colorRenderbuffer] is non-zero, chosen by `RenderTargetSpec.sampled`. + * A renderbuffer is the cheaper write-only surface but cannot be sampled OR read back directly, which is + * precisely why the flag exists rather than always allocating a texture. + */ +internal class GlRenderTarget( + val framebuffer: Int, + val colorTexture: Int, + val colorRenderbuffer: Int, + val width: Int, + val height: Int, +) : RenderTarget { + override val sampledTexture: GpuTexture? = if (colorTexture != 0) GlTexture(colorTexture, TextureFilter.Linear, TextureWrap.ClampToEdge) else null +} + +/** + * The shared pass-1 position store: a buffer plus the texture-buffer view pass 2 samples it through. + * + * A texture buffer object today, which is desktop-GL only (GLES has them at 3.2, and the Android baseline + * is 3.0). The GLES port repacks this as a 2D texture; nothing above the device sees the difference. + */ +internal class GlDeformedPositionStore( + val buffer: Int, + val textureBuffer: Int, + val vertexCapacity: Int, +) : DeformedPositionStore + +/** + * Every uniform any of this backend's programs declares, resolved once at pipeline creation. + * + * One flat set rather than a per-purpose struct, because GL makes it free: `glGetUniformLocation` returns + * -1 for a uniform a program does not declare (or that its compiler optimised away), and `glUniform*` + * with -1 is a defined no-op. So the grid pipeline simply has -1 for every puppet uniform and setting + * them costs a branch in the driver. + * + * Resolving them ONCE here is the point: the renderer previously looked a location up by name on every + * draw - 36 call sites' worth of string lookups per frame. + */ +internal class GlUniformLocations(program: Int) { + // Per-pass. viewportSize is the grid program's genuine viewport extent; screenTexSize is the + // puppet/composite programs' screen-space texture divisor (the side targets' allocated size, + // which the grow-only capacity can hold above the viewport size). + val worldToNdc = GL20.glGetUniformLocation(program, "worldToNdc") + val viewportSize = GL20.glGetUniformLocation(program, "viewportSize") + val screenTexSize = GL20.glGetUniformLocation(program, "screenTexSize") + + // Samplers + val atlas = GL20.glGetUniformLocation(program, "atlas") + val maskTexture = GL20.glGetUniformLocation(program, "maskTexture") + val deltaTex = GL20.glGetUniformLocation(program, "deltaTex") + val cpTex = GL20.glGetUniformLocation(program, "cpTex") + val positionBuffer = GL20.glGetUniformLocation(program, "positionBuffer") + + // Deform + val cornerCount = GL20.glGetUniformLocation(program, "cornerCount") + val cornerCell = GL20.glGetUniformLocation(program, "cornerCell") + val cornerWeight = GL20.glGetUniformLocation(program, "cornerWeight") + val blendCount = GL20.glGetUniformLocation(program, "blendCount") + val blendCell = GL20.glGetUniformLocation(program, "blendCell") + val blendWeight = GL20.glGetUniformLocation(program, "blendWeight") + val parentType = GL20.glGetUniformLocation(program, "parentType") + val rot = GL20.glGetUniformLocation(program, "rot") + val warpCols = GL20.glGetUniformLocation(program, "warpCols") + val warpRows = GL20.glGetUniformLocation(program, "warpRows") + val warpBilinear = GL20.glGetUniformLocation(program, "warpBilinear") + + // Glue + val baseOffset = GL20.glGetUniformLocation(program, "baseOffset") + val glueIntensity = GL20.glGetUniformLocation(program, "glueIntensity") + + // Fragment + val useTexture = GL20.glGetUniformLocation(program, "useTexture") + val drawColor = GL20.glGetUniformLocation(program, "drawColor") + val opacity = GL20.glGetUniformLocation(program, "opacity") + val useMask = GL20.glGetUniformLocation(program, "useMask") + val invertMask = GL20.glGetUniformLocation(program, "invertMask") + val highlight = GL20.glGetUniformLocation(program, "highlight") + val highlightColor = GL20.glGetUniformLocation(program, "highlightColor") + val uvAffineRow0 = GL20.glGetUniformLocation(program, "uvAffineRow0") + val uvAffineRow1 = GL20.glGetUniformLocation(program, "uvAffineRow1") + val atlasLinear = GL20.glGetUniformLocation(program, "atlasLinear") + val atlasTransparentBorder = GL20.glGetUniformLocation(program, "atlasTransparentBorder") + + // Atlas page + val pageSize = GL20.glGetUniformLocation(program, "pageSize") + + // Layer composite + val layerTexture = GL20.glGetUniformLocation(program, "layerTexture") + val destTexture = GL20.glGetUniformLocation(program, "destTexture") + val colorMode = GL20.glGetUniformLocation(program, "colorMode") + val alphaMode = GL20.glGetUniformLocation(program, "alphaMode") + val multiplyColor = GL20.glGetUniformLocation(program, "multiplyColor") + val screenColor = GL20.glGetUniformLocation(program, "screenColor") + + // Grid backdrop + val majorSpacing = GL20.glGetUniformLocation(program, "majorSpacing") + val subdivisions = GL20.glGetUniformLocation(program, "subdivisions") + val lineWidthPx = GL20.glGetUniformLocation(program, "lineWidthPx") + val backgroundColor = GL20.glGetUniformLocation(program, "backgroundColor") + val majorColor = GL20.glGetUniformLocation(program, "majorColor") + val minorColor = GL20.glGetUniformLocation(program, "minorColor") + val gridOrigin = GL20.glGetUniformLocation(program, "gridOrigin") + + // Axis line + val linePositionNdc = GL20.glGetUniformLocation(program, "linePositionNdc") + val lineVertical = GL20.glGetUniformLocation(program, "lineVertical") + val lineColor = GL20.glGetUniformLocation(program, "lineColor") +} + +/** A linked draw program with its blend, cull state, and resolved uniform locations. */ +internal class GlRenderPipeline( + val program: Int, + val blend: PipelineBlend, + val cullBackFaces: Boolean, + val locations: GlUniformLocations, +) : RenderPipeline + +/** The transform-feedback program that captures deformed positions without rasterizing. */ +internal class GlDeformCapturePipeline( + val program: Int, + val locations: GlUniformLocations, +) : DeformCapturePipeline \ No newline at end of file diff --git a/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlRenderDevice.kt b/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlRenderDevice.kt new file mode 100644 index 0000000..0b53b3d --- /dev/null +++ b/module/render/src/jvmMain/kotlin/org/umamo/render/gl/GlRenderDevice.kt @@ -0,0 +1,596 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL12 +import org.lwjgl.opengl.GL13 +import org.lwjgl.opengl.GL15 +import org.lwjgl.opengl.GL20 +import org.lwjgl.opengl.GL21 +import org.lwjgl.opengl.GL30 +import org.lwjgl.opengl.GL31 +import org.lwjgl.opengl.GL32 +import org.umamo.format.raster.RasterImage +import org.umamo.render.device.DeformCapturePipeline +import org.umamo.render.device.DeformedPositionStore +import org.umamo.render.device.FrameEncoder +import org.umamo.render.device.GpuMesh +import org.umamo.render.device.GpuTexture +import org.umamo.render.device.MeshSpec +import org.umamo.render.device.PipelinePurpose +import org.umamo.render.device.ReadbackTicket +import org.umamo.render.device.RenderDevice +import org.umamo.render.device.RenderPipeline +import org.umamo.render.device.RenderPipelineSpec +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.ScissorRect +import org.umamo.render.device.TextureFilter +import org.umamo.render.device.TextureFormat +import org.umamo.render.device.TextureWrap +import org.umamo.render.glsl.GlslDialect +import org.umamo.render.glsl.atlasPageVertexShader +import org.umamo.render.glsl.axisFragmentShader +import org.umamo.render.glsl.axisVertexShader +import org.umamo.render.glsl.compositeFragmentShader +import org.umamo.render.glsl.compositeVertexShader +import org.umamo.render.glsl.glueVertexShader +import org.umamo.render.glsl.gridFragmentShader +import org.umamo.render.glsl.gridVertexShader +import org.umamo.render.glsl.puppetFragmentShader +import org.umamo.render.glsl.puppetVertexShader +import org.umamo.render.glsl.tfDeformVertexShader +import org.umamo.render.glsl.tfDiscardFragmentShader +import org.umamo.render.puppet.flipRowsVertically +import java.nio.ByteBuffer + +/** + * The desktop OpenGL 3.3 core [RenderDevice], over LWJGL. + * + * This is where the GL lives. Everything above it - the puppet renderer, the eval, the pose resolution - + * is backend-neutral, so a second backend is a second device rather than a second renderer. Every method + * assumes a GL context is current on the calling thread; the host makes it so. + * + * A near-transliteration of this becomes the Android GLES 3.0 device: the calls are the same, differing + * only in binding style (LWJGL statics vs the GLES out-param form) and the one place GLES 3.0 lacks a + * texture buffer (the glue store, [createDeformedPositionStore], where the GLES port repacks as a 2D + * texture behind [DeformedPositionStore]). + */ +class GlRenderDevice : RenderDevice { + // An empty VAO for the attribute-less draws (grid, axis lines, atlas page): a core profile still + // requires a bound VAO even when the vertex shader synthesises its positions from gl_VertexID. + private var emptyVao = 0 + + // Pipelines are immutable and reused every frame, so they are cached by their spec rather than rebuilt. + private val renderPipelines = HashMap() + private var deformCapturePipeline: GlDeformCapturePipeline? = null + + private fun ensureEmptyVao(): Int { + if (emptyVao == 0) { + emptyVao = GL30.glGenVertexArrays() + } + return emptyVao + } + + override fun createTexture( + width: Int, + height: Int, + format: TextureFormat, + filter: TextureFilter, + pixels: ByteArray?, + wrap: TextureWrap, + ): GpuTexture { + val handle = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, handle) + setTextureParameters(filter, wrap) + val pixelBuffer = + pixels?.let { + BufferUtils.createByteBuffer(it.size).apply { + put(it) + flip() + } + } + GL11.glTexImage2D( + GL11.GL_TEXTURE_2D, + 0, + internalFormatOf(format), + width, + height, + 0, + pixelFormatOf(format), + pixelTypeOf(format), + pixelBuffer, + ) + return GlTexture(handle, filter, wrap) + } + + override fun createFloatTexture(width: Int, height: Int, filter: TextureFilter, texels: FloatArray): GpuTexture { + val handle = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, handle) + setTextureParameters(filter, TextureWrap.ClampToEdge) + val texelBuffer = + BufferUtils.createFloatBuffer(texels.size).apply { + put(texels) + flip() + } + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_RG32F, width, height, 0, GL30.GL_RG, GL11.GL_FLOAT, texelBuffer) + return GlTexture(handle, filter, TextureWrap.ClampToEdge) + } + + override fun updateFloatTexture(texture: GpuTexture, width: Int, height: Int, texels: FloatArray) { + val glTexture = texture as GlTexture + val texelBuffer = + BufferUtils.createFloatBuffer(texels.size).apply { + put(texels) + flip() + } + GL11.glBindTexture(GL11.GL_TEXTURE_2D, glTexture.handle) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_RG32F, width, height, 0, GL30.GL_RG, GL11.GL_FLOAT, texelBuffer) + } + + override fun createMesh(spec: MeshSpec): GpuMesh { + val vao = GL30.glGenVertexArrays() + GL30.glBindVertexArray(vao) + + val positionVbo = uploadArrayBuffer(spec.restPositions, GL15.GL_DYNAMIC_DRAW) + GL20.glEnableVertexAttribArray(0) + GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 2 * Float.SIZE_BYTES, 0L) + + val vertexCount = spec.restPositions.size / 2 + // A mesh whose UVs are shorter than its vertices gets a zero-filled UV buffer of the right length, + // so an in-place UV re-upload later has a target of the expected size. + val safeUvs = if (spec.uvs.size >= vertexCount * 2) spec.uvs else FloatArray(vertexCount * 2) + val uvVbo = uploadArrayBuffer(safeUvs, GL15.GL_DYNAMIC_DRAW) + GL20.glEnableVertexAttribArray(1) + GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 2 * Float.SIZE_BYTES, 0L) + + var glueVbo = 0 + spec.glueAttributes?.let { attributes -> + glueVbo = GL15.glGenBuffers() + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, glueVbo) + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, interleaveGlueAttributes(attributes), GL15.GL_STATIC_DRAW) + val stride = 3 * Int.SIZE_BYTES + GL20.glEnableVertexAttribArray(2) + GL30.glVertexAttribIPointer(2, 1, GL11.GL_INT, stride, 0L) + GL20.glEnableVertexAttribArray(3) + GL30.glVertexAttribIPointer(3, 1, GL11.GL_INT, stride, Int.SIZE_BYTES.toLong()) + GL20.glEnableVertexAttribArray(4) + GL20.glVertexAttribPointer(4, 1, GL11.GL_FLOAT, false, stride, (2 * Int.SIZE_BYTES).toLong()) + } + + var indexEbo = 0 + if (spec.indices.isNotEmpty()) { + val indexBuffer = + BufferUtils.createIntBuffer(spec.indices.size).apply { + put(spec.indices) + flip() + } + indexEbo = GL15.glGenBuffers() + GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indexEbo) + GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL15.GL_STATIC_DRAW) + } + + GL30.glBindVertexArray(0) + return GlMesh(vao, positionVbo, uvVbo, glueVbo, indexEbo, vertexCount, spec.indices.size) + } + + override fun updateMeshPositions(mesh: GpuMesh, restPositions: FloatArray) { + subDataArrayBuffer((mesh as GlMesh).positionVbo, restPositions) + } + + override fun updateMeshUvs(mesh: GpuMesh, uvs: FloatArray) { + subDataArrayBuffer((mesh as GlMesh).uvVbo, uvs) + } + + override fun createRenderTarget(spec: RenderTargetSpec): RenderTarget { + val framebuffer = GL30.glGenFramebuffers() + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + var colorTexture = 0 + var colorRenderbuffer = 0 + if (spec.sampled) { + colorTexture = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, colorTexture) + setTextureParameters(TextureFilter.Linear, TextureWrap.ClampToEdge) + GL11.glTexImage2D( + GL11.GL_TEXTURE_2D, + 0, + internalFormatOf(spec.format), + spec.width, + spec.height, + 0, + pixelFormatOf(spec.format), + pixelTypeOf(spec.format), + null as ByteBuffer?, + ) + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0) + } else { + // A write-only surface: cheaper, but cannot be sampled or read back directly. + colorRenderbuffer = GL30.glGenRenderbuffers() + GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, colorRenderbuffer) + GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, internalFormatOf(spec.format), spec.width, spec.height) + GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL30.GL_RENDERBUFFER, colorRenderbuffer) + } + return GlRenderTarget(framebuffer, colorTexture, colorRenderbuffer, spec.width, spec.height) + } + + override fun createDeformedPositionStore(vertexCapacity: Int): DeformedPositionStore { + val buffer = GL15.glGenBuffers() + GL15.glBindBuffer(GL31.GL_TEXTURE_BUFFER, buffer) + GL15.glBufferData(GL31.GL_TEXTURE_BUFFER, vertexCapacity.toLong() * 2 * Float.SIZE_BYTES, GL15.GL_DYNAMIC_COPY) + val textureBuffer = GL11.glGenTextures() + GL11.glBindTexture(GL31.GL_TEXTURE_BUFFER, textureBuffer) + GL31.glTexBuffer(GL31.GL_TEXTURE_BUFFER, GL30.GL_RG32F, buffer) + return GlDeformedPositionStore(buffer, textureBuffer, vertexCapacity) + } + + override fun createRenderPipeline(spec: RenderPipelineSpec): RenderPipeline = + renderPipelines.getOrPut(spec) { + val (vertexSource, fragmentSource) = sourcesFor(spec.purpose) + val program = linkGlProgram(vertexSource, fragmentSource, spec.purpose.name) + GlRenderPipeline(program, spec.blend, spec.cullBackFaces, GlUniformLocations(program)) + } + + override fun createDeformCapturePipeline(): DeformCapturePipeline = + deformCapturePipeline ?: run { + val program = attachGlShaders(tfDeformVertexShader(DIALECT), tfDiscardFragmentShader(DIALECT)) + GL30.glTransformFeedbackVaryings(program, arrayOf("outWorld"), GL30.GL_INTERLEAVED_ATTRIBS) + GL20.glLinkProgram(program) + check(GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) != GL11.GL_FALSE) { + "deform-capture program link failed: ${GL20.glGetProgramInfoLog(program)}" + } + GlDeformCapturePipeline(program, GlUniformLocations(program)).also { deformCapturePipeline = it } + } + + override fun destroyTexture(texture: GpuTexture) { + GL11.glDeleteTextures((texture as GlTexture).handle) + } + + override fun destroyMesh(mesh: GpuMesh) { + val glMesh = mesh as GlMesh + GL30.glDeleteVertexArrays(glMesh.vao) + GL15.glDeleteBuffers(glMesh.positionVbo) + GL15.glDeleteBuffers(glMesh.uvVbo) + if (glMesh.glueVbo != 0) { + GL15.glDeleteBuffers(glMesh.glueVbo) + } + if (glMesh.indexEbo != 0) { + GL15.glDeleteBuffers(glMesh.indexEbo) + } + } + + override fun destroyRenderTarget(target: RenderTarget) { + val glTarget = target as GlRenderTarget + GL30.glDeleteFramebuffers(glTarget.framebuffer) + if (glTarget.colorTexture != 0) { + GL11.glDeleteTextures(glTarget.colorTexture) + } + if (glTarget.colorRenderbuffer != 0) { + GL30.glDeleteRenderbuffers(glTarget.colorRenderbuffer) + } + } + + override fun beginFrame(): FrameEncoder = GlFrameEncoder(ensureEmptyVao()) + + override fun resolve(source: RenderTarget, destination: RenderTarget, region: ScissorRect?) { + val glSource = source as GlRenderTarget + val glDestination = destination as GlRenderTarget + resolveUsed(glSource, glSource.width, glSource.height, glDestination, glDestination.width, glDestination.height, region) + } + + override fun resolveUsed( + source: RenderTarget, + sourceUsedWidth: Int, + sourceUsedHeight: Int, + destination: RenderTarget, + destinationUsedWidth: Int, + destinationUsedHeight: Int, + region: ScissorRect?, + ) { + val glSource = source as GlRenderTarget + val glDestination = destination as GlRenderTarget + GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, glSource.framebuffer) + GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, glDestination.framebuffer) + // Content sits at GL (0, 0): every pass runs glViewport(0, 0, used, used), so the used region + // IS the bottom-left rows. GL_LINEAR makes the downscale a box filter - the supersample + // resolve. On GL this whole primitive IS a blit; on Metal it cannot be (a blit encoder neither + // filters nor scales), which is why the interface names the effect rather than the mechanism. + if (region == null) { + GL30.glBlitFramebuffer( + 0, + 0, + sourceUsedWidth, + sourceUsedHeight, + 0, + 0, + destinationUsedWidth, + destinationUsedHeight, + GL11.GL_COLOR_BUFFER_BIT, + GL11.GL_LINEAR, + ) + } else { + // A same-size sub-rectangle copy (the composite path's snapshot). The rect is + // top-left-origin per the ScissorRect contract; GL blits bottom-up, so the flip is against + // the USED height - flipping against a larger allocation would land above the content. + val bottomUpY = sourceUsedHeight - region.y - region.height + GL30.glBlitFramebuffer( + region.x, + bottomUpY, + region.x + region.width, + bottomUpY + region.height, + region.x, + bottomUpY, + region.x + region.width, + bottomUpY + region.height, + GL11.GL_COLOR_BUFFER_BIT, + GL11.GL_NEAREST, + ) + } + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, glDestination.framebuffer) + } + + /** A recyclable pixel-buffer object and its current byte capacity. */ + private class Pbo(val id: Int, var capacity: Int) + + /** + * An in-flight asynchronous read-back: the staging PBO, the fence gating it, and the read's extent. + * [spent] flips when the ticket is consumed or cancelled, making both one-shot and idempotent. + */ + private class GlReadbackTicket( + val pbo: Pbo, + val fence: Long, + val width: Int, + val height: Int, + var spent: Boolean = false, + ) : ReadbackTicket + + // Staging PBOs are recycled rather than freed: a viewport read-back runs per frame, and reallocating + // a multi-megabyte buffer 60x/sec is churn the pool exists to avoid. Render-thread only. + private val freePbos = ArrayDeque() + + override fun beginReadback(target: RenderTarget): ReadbackTicket { + val glTarget = target as GlRenderTarget + return beginReadback(glTarget, glTarget.width, glTarget.height) + } + + override fun beginReadback(target: RenderTarget, usedWidth: Int, usedHeight: Int): ReadbackTicket { + val glTarget = target as GlRenderTarget + GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, glTarget.framebuffer) + val pbo = acquirePbo(usedWidth * usedHeight * 4) + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, pbo.id) + // With a PBO bound, the last argument is a BUFFER OFFSET, not a client pointer - glReadPixels + // returns immediately and the copy happens asynchronously on the GPU timeline. The used + // region is the bottom-left rows (passes viewport at the origin), so the read starts at (0, 0). + GL11.glReadPixels(0, 0, usedWidth, usedHeight, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, 0L) + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0) + val fence = GL32.glFenceSync(GL32.GL_SYNC_GPU_COMMANDS_COMPLETE, 0) + GL11.glFlush() // submit the commands + fence so the fence can eventually signal + return GlReadbackTicket(pbo, fence, usedWidth, usedHeight) + } + + override fun pollReadback(ticket: ReadbackTicket): RasterImage? { + val glTicket = ticket as GlReadbackTicket + check(!glTicket.spent) { "pollReadback on a spent ticket" } + val status = GL32.glClientWaitSync(glTicket.fence, 0, 0L) + if (status != GL32.GL_ALREADY_SIGNALED && status != GL32.GL_CONDITION_SATISFIED) { + return null // still in flight; the ticket stays live to poll again + } + // The fence signaled, so the read is done and the ticket is consumed HERE - exactly once, whether or + // not the map below succeeds. Returning null past this point would make the caller treat a consumed + // ticket as still-in-flight and re-poll it, tripping the spent check and killing the render thread. + glTicket.spent = true + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, glTicket.pbo.id) + // Explicitly typed: the inferred type would carry LWJGL's jspecify @Nullable, which is not + // on this module's classpath and fails compilation. + val mapped: ByteBuffer? = GL15.glMapBuffer(GL21.GL_PIXEL_PACK_BUFFER, GL15.GL_READ_ONLY) + val rowBytes = glTicket.width * 4 + val topDown = ByteArray(rowBytes * glTicket.height) + if (mapped != null) { + // Flip the GL bottom-up rows straight out of the mapped PBO into the API's top-first contract - + // one bulk get per row, the direct-buffer equivalent of System.arraycopy. + for (row in 0 until glTicket.height) { + mapped.position((glTicket.height - 1 - row) * rowBytes) + mapped.get(topDown, row * rowBytes, rowBytes) + } + GL15.glUnmapBuffer(GL21.GL_PIXEL_PACK_BUFFER) // only when the map actually succeeded + } + // A map failure (a driver error that should never happen) leaves topDown zero-filled: one black + // frame rather than a permanently frozen viewport, and null keeps meaning "still in flight". + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0) + GL32.glDeleteSync(glTicket.fence) + freePbos.addLast(glTicket.pbo) + return RasterImage(glTicket.width, glTicket.height, topDown) + } + + override fun cancelReadback(ticket: ReadbackTicket) { + val glTicket = ticket as GlReadbackTicket + if (glTicket.spent) { + return + } + glTicket.spent = true + GL32.glDeleteSync(glTicket.fence) + freePbos.addLast(glTicket.pbo) + } + + /** + * Acquires a PBO with at least [capacity] bytes from the free pool (allocating/growing as needed). + * GL_STREAM_READ: written by GL, read once by the client. + * + * @param Int capacity The minimum byte capacity needed. + * @return Pbo The acquired PBO. + */ + private fun acquirePbo(capacity: Int): Pbo { + val pbo = freePbos.removeFirstOrNull() ?: Pbo(GL15.glGenBuffers(), 0) + if (pbo.capacity < capacity) { + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, pbo.id) + GL15.glBufferData(GL21.GL_PIXEL_PACK_BUFFER, capacity.toLong(), GL15.GL_STREAM_READ) + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0) + pbo.capacity = capacity + } + return pbo + } + + override fun readPixels(target: RenderTarget): RasterImage { + val glTarget = target as GlRenderTarget + return readPixels(glTarget, glTarget.width, glTarget.height) + } + + override fun readPixels(target: RenderTarget, usedWidth: Int, usedHeight: Int): RasterImage { + val glTarget = target as GlRenderTarget + GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, glTarget.framebuffer) + val pixels = BufferUtils.createByteBuffer(usedWidth * usedHeight * 4) + // The used region is the bottom-left rows (passes viewport at the origin): read from (0, 0). + GL11.glReadPixels(0, 0, usedWidth, usedHeight, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels) + val bottomUp = ByteArray(usedWidth * usedHeight * 4) + pixels.get(bottomUp) + // GL reads bottom-up; RasterImage is top-first. The flip is this backend's; no caller asks. + return RasterImage(usedWidth, usedHeight, flipRowsVertically(bottomUp, usedWidth, usedHeight)) + } + + override fun maxRenderTargetSize(): Int { + val viewportDimensions = IntArray(2) + GL11.glGetIntegerv(GL11.GL_MAX_VIEWPORT_DIMS, viewportDimensions) + val textureSize = GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE) + val renderbufferSize = GL11.glGetInteger(GL30.GL_MAX_RENDERBUFFER_SIZE) + return minOf(textureSize, renderbufferSize, viewportDimensions[0], viewportDimensions[1]) + } + + override fun describeBackend(): String { + val renderer = GL11.glGetString(GL11.GL_RENDERER) + val version = GL11.glGetString(GL11.GL_VERSION) + val vendor = GL11.glGetString(GL11.GL_VENDOR) + val glsl = GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION) + return "renderer=$renderer | version=$version | vendor=$vendor | glsl=$glsl" + } + + /** The (vertex, fragment) GLSL for a pipeline purpose - this backend's shader library, keyed by purpose. */ + private fun sourcesFor(purpose: PipelinePurpose): Pair = + when (purpose) { + PipelinePurpose.PuppetDeformDraw -> puppetVertexShader(DIALECT) to puppetFragmentShader(DIALECT) + PipelinePurpose.PuppetGlueDraw -> glueVertexShader(DIALECT) to puppetFragmentShader(DIALECT) + PipelinePurpose.AtlasPageDraw -> atlasPageVertexShader(DIALECT) to puppetFragmentShader(DIALECT) + PipelinePurpose.GridBackdrop -> gridVertexShader(DIALECT) to gridFragmentShader(DIALECT) + PipelinePurpose.WorldAxisLine -> axisVertexShader(DIALECT) to axisFragmentShader(DIALECT) + PipelinePurpose.Composite -> compositeVertexShader(DIALECT) to compositeFragmentShader(DIALECT) + } + + /** + * Sets nearest/linear filtering and the requested wrapping on the currently-bound 2D texture. + * + * The border color is set only for the border mode: it is per-texture state, so leaving it alone on the + * edge-clamp path costs one call less and changes nothing that path can observe. + * + * @param TextureFilter filter The filtering mode. + * @param TextureWrap wrap The wrapping mode, applied to both axes. + */ + private fun setTextureParameters(filter: TextureFilter, wrap: TextureWrap) { + val glFilter = if (filter == TextureFilter.Nearest) GL11.GL_NEAREST else GL11.GL_LINEAR + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, glFilter) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, glFilter) + val glWrap = if (wrap == TextureWrap.ClampToTransparentBorder) GL13.GL_CLAMP_TO_BORDER else GL12.GL_CLAMP_TO_EDGE + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, glWrap) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, glWrap) + if (wrap == TextureWrap.ClampToTransparentBorder) { + // Transparent AND black: under linear filtering the border's RGB joins the blend across the + // art's outermost half-texel, so a border that is merely alpha-zero but colored tints that + // fringe. Zero everywhere matches what the packed atlas's own padding contributes there. + GL11.glTexParameterfv(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_BORDER_COLOR, floatArrayOf(0f, 0f, 0f, 0f)) + } + } + + private fun internalFormatOf(format: TextureFormat): Int = if (format == TextureFormat.Rgba8) GL11.GL_RGBA8 else GL30.GL_RG32F + + private fun pixelFormatOf(format: TextureFormat): Int = if (format == TextureFormat.Rgba8) GL11.GL_RGBA else GL30.GL_RG + + private fun pixelTypeOf(format: TextureFormat): Int = if (format == TextureFormat.Rgba8) GL11.GL_UNSIGNED_BYTE else GL11.GL_FLOAT + + /** Uploads a float array into a fresh GL_ARRAY_BUFFER with the given usage; leaves it bound. */ + private fun uploadArrayBuffer(values: FloatArray, usage: Int): Int { + val buffer = + BufferUtils.createFloatBuffer(values.size).apply { + put(values) + flip() + } + val vbo = GL15.glGenBuffers() + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo) + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, usage) + return vbo + } + + // Reusable scratch for in-place VBO re-uploads, grown on demand so a live preview edit never allocates. + private var uploadScratch = BufferUtils.createFloatBuffer(0) + + /** Re-specifies a whole array buffer's contents in place, reusing the scratch buffer. */ + private fun subDataArrayBuffer(vbo: Int, values: FloatArray) { + if (uploadScratch.capacity() < values.size) { + uploadScratch = BufferUtils.createFloatBuffer(values.size) + } + uploadScratch.clear() + uploadScratch.put(values).flip() + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo) + GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0L, uploadScratch) + } +} + +/** This backend is desktop OpenGL 3.3 core; the shared GLSL is emitted for it. */ +private val DIALECT = GlslDialect.Core330 + +/** + * Interleaves a mesh's planned weld attributes into the 12-byte-per-vertex form the glue VAO reads: + * int partner global index, int glue index, float weld weight, in the native byte order [BufferUtils] + * allocates - which is what `glVertexAttribIPointer` reads back. + * + * The layout is GL's; `org.umamo.render.puppet.planGlueLayout` decided the values. A free function, not + * a device method, since it touches no device state. + * + * @param GlueVertexAttributes attributes The mesh's planned per-vertex weld attributes. + * @return ByteBuffer The interleaved buffer, flipped and ready to upload. + */ +private fun interleaveGlueAttributes(attributes: org.umamo.render.puppet.GlueVertexAttributes): ByteBuffer { + val vertexCount = attributes.partnerIndex.size + val buffer = BufferUtils.createByteBuffer(vertexCount * 3 * Int.SIZE_BYTES) + for (vertexIndex in 0 until vertexCount) { + buffer.putInt(attributes.partnerIndex[vertexIndex]) + buffer.putInt(attributes.glueIndex[vertexIndex]) + buffer.putFloat(attributes.weldWeight[vertexIndex]) + } + buffer.flip() + return buffer +} + +/** + * Links a GL program from vertex + fragment source, throwing with the info log on failure. + * + * @param String vertexSource The vertex-stage GLSL. + * @param String fragmentSource The fragment-stage GLSL. + * @param String label A name for the failure message. + * @return Int The linked program handle. + */ +internal fun linkGlProgram(vertexSource: String, fragmentSource: String, label: String): Int { + val program = attachGlShaders(vertexSource, fragmentSource) + GL20.glLinkProgram(program) + check(GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) != GL11.GL_FALSE) { + "$label program link failed: ${GL20.glGetProgramInfoLog(program)}" + } + return program +} + +/** Compiles and attaches both stages onto a fresh program (not yet linked, so the TF varyings can be set). */ +internal fun attachGlShaders(vertexSource: String, fragmentSource: String): Int { + val vertexShader = compileGlShader(GL20.GL_VERTEX_SHADER, vertexSource) + val fragmentShader = compileGlShader(GL20.GL_FRAGMENT_SHADER, fragmentSource) + val program = GL20.glCreateProgram() + GL20.glAttachShader(program, vertexShader) + GL20.glAttachShader(program, fragmentShader) + return program +} + +/** Compiles one shader stage, throwing with the info log if compilation fails. */ +internal fun compileGlShader(stage: Int, source: String): Int { + val shader = GL20.glCreateShader(stage) + GL20.glShaderSource(shader, source) + GL20.glCompileShader(shader) + check(GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) != GL11.GL_FALSE) { + "GL shader compile failed: ${GL20.glGetShaderInfoLog(shader)}" + } + return shader +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/BlendBindingParityTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/BlendBindingParityTest.kt new file mode 100644 index 0000000..aa7f7dd --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/BlendBindingParityTest.kt @@ -0,0 +1,194 @@ +package org.umamo.render + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.Deformer +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Cross-import blend-binding parity: the same corpus model imported from `.cmo3` (editor forms) + * and from its baked `.moc3` (delta rows + the grid-at-default reference re-added) must produce + * structurally IDENTICAL BlendShapeBindings - same objects, driving parameters, keys, neutral + * placement, and limit curves. + * + * Form VALUES are compared under per-kind ceilings rather than exactly - float noise accumulates + * through the delta + grid-at-default reconstruction and the canvas-space rewrite. Measured, the + * corpus reconstructs SUB-PIXEL (mesh <= 0.36 px, control points and rotation fields <= 3e-4), so + * the pinned ceilings sit just above that class and reject any space or reference-frame + * regression outright. End-to-end geometric parity against the Umamo C++ Runtime is + * BlendShapeOracleTest's job; this test isolates the import mapping itself. + * + * Gated on `cmo3.probe` + `moc3.samples` (the build defaults both); skips when absent. + */ +class BlendBindingParityTest { + @Test + fun blendBindingsMatchAcrossImports() { + val cmo3Files = System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { it.isFile }.orEmpty() + val moc3Root = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + val pairs = + listOf("modelA", "modelB", "modelC").mapNotNull { prefix -> + val cmo3File = cmo3Files.firstOrNull { it.name.startsWith(prefix) } ?: return@mapNotNull null + val moc3File = + moc3Root?.walkTopDown()?.firstOrNull { it.isFile && it.name == "$prefix.moc3" } ?: return@mapNotNull null + prefix to (cmo3File to moc3File) + } + if (pairs.isEmpty()) { + println("cmo3.probe/moc3.samples not present; skipping blend-binding parity") + return + } + for ((name, files) in pairs) { + val (cmo3File, moc3File) = files + val cmo3Root = Cmo3.read(cmo3File).root as? CModelSource ?: error("$name: root is not a CModelSource") + // Both sides through the same canvas-space rewrite so mesh form deltas share a base. + val fromCmo3 = restMeshesToCanvasSpace(Cmo3Import.fromModelSource(cmo3Root)) + val fromMoc3 = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(Moc3.read(moc3File.readBytes()), null)) + + var meshBindingPairs = 0 + var maxMeshDelta = 0f + var maxScalarDelta = 0f + val moc3DrawablesById = fromMoc3.drawables.associateBy { it.id } + for (cmo3Drawable in fromCmo3.drawables) { + val moc3Drawable = moc3DrawablesById[cmo3Drawable.id] ?: continue + meshBindingPairs += + compareBindingLists(name, "drawable ${cmo3Drawable.id.raw}", cmo3Drawable.blendShapes, moc3Drawable.blendShapes) { cmo3Form, moc3Form -> + var maxComponentDelta = 0f + val componentCount = minOf(cmo3Form.positionDeltas.size, moc3Form.positionDeltas.size) + assertEquals(cmo3Form.positionDeltas.size, moc3Form.positionDeltas.size, "$name: mesh form size") + for (componentIndex in 0 until componentCount) { + maxComponentDelta = + maxOf(maxComponentDelta, abs(cmo3Form.positionDeltas[componentIndex] - moc3Form.positionDeltas[componentIndex])) + } + maxMeshDelta = maxOf(maxMeshDelta, maxComponentDelta) + maxScalarDelta = maxOf(maxScalarDelta, abs(cmo3Form.drawOrder - moc3Form.drawOrder)) + maxScalarDelta = maxOf(maxScalarDelta, abs(cmo3Form.opacity - moc3Form.opacity)) + } + } + + // Warp/rotation correspondence via the parent chains of shared drawables (a moc names its + // deformers only by synthesized index, so ids cannot join directly). + var warpBindingPairs = 0 + var rotationBindingPairs = 0 + var maxControlPointDelta = 0f + var maxRotationDelta = 0f + val cmo3DeformersById = fromCmo3.deformers.associateBy { it.id } + val moc3DeformersById = fromMoc3.deformers.associateBy { it.id } + val comparedDeformerPairs = HashSet>() + for (cmo3Drawable in fromCmo3.drawables) { + val moc3Drawable = moc3DrawablesById[cmo3Drawable.id] ?: continue + var cmo3ParentId = cmo3Drawable.parentDeformerId + var moc3ParentId = moc3Drawable.parentDeformerId + while (cmo3ParentId != null && moc3ParentId != null) { + val cmo3Deformer = cmo3DeformersById[cmo3ParentId] ?: break + val moc3Deformer = moc3DeformersById[moc3ParentId] ?: break + if (!comparedDeformerPairs.add(cmo3Deformer.id to moc3Deformer.id)) { + break + } + when (cmo3Deformer) { + is Deformer.Warp -> { + val moc3Warp = moc3Deformer as Deformer.Warp + warpBindingPairs += + compareBindingLists(name, "warp ${cmo3Deformer.id.raw}", cmo3Deformer.blendShapes, moc3Warp.blendShapes) { cmo3Form, moc3Form -> + assertEquals(cmo3Form.controlPoints.size, moc3Form.controlPoints.size, "$name: warp form size") + for (componentIndex in cmo3Form.controlPoints.indices) { + maxControlPointDelta = + maxOf(maxControlPointDelta, abs(cmo3Form.controlPoints[componentIndex] - moc3Form.controlPoints[componentIndex])) + } + } + } + is Deformer.Rotation -> { + val moc3Rotation = moc3Deformer as Deformer.Rotation + rotationBindingPairs += + compareBindingLists(name, "rotation ${cmo3Deformer.id.raw}", cmo3Deformer.blendShapes, moc3Rotation.blendShapes) { cmo3Form, moc3Form -> + maxRotationDelta = maxOf(maxRotationDelta, abs(cmo3Form.originX - moc3Form.originX)) + maxRotationDelta = maxOf(maxRotationDelta, abs(cmo3Form.originY - moc3Form.originY)) + maxRotationDelta = maxOf(maxRotationDelta, abs(cmo3Form.angle - moc3Form.angle)) + maxRotationDelta = maxOf(maxRotationDelta, abs(cmo3Form.scale - moc3Form.scale)) + } + } + } + cmo3ParentId = cmo3Deformer.parent + moc3ParentId = moc3Deformer.parent + } + } + + println( + "[parity] $name: bindingPairs mesh=$meshBindingPairs warp=$warpBindingPairs rotation=$rotationBindingPairs " + + "maxMeshDelta=$maxMeshDelta maxScalarDelta=$maxScalarDelta " + + "maxControlPointDelta=$maxControlPointDelta maxRotationDelta=$maxRotationDelta", + ) + assertTrue(meshBindingPairs + warpBindingPairs + rotationBindingPairs > 0, "$name: compared some bindings") + // Ceilings pinned from the first measured run: maxMeshDelta 0.352 px (Model A) / 0.204 + // (Model C), maxControlPointDelta 1.3e-4, maxRotationDelta 2.5e-4, scalar deltas exactly + // 0 - the reconstruction is sub-pixel across the corpus, so the ceilings sit just above + // the measured float-noise class and reject any space or reference-frame regression + // outright. + assertTrue(maxMeshDelta <= 1f, "$name: mesh form parity ceiling (got $maxMeshDelta)") + assertTrue(maxScalarDelta <= 0.001f, "$name: scalar form parity ceiling (got $maxScalarDelta)") + assertTrue(maxControlPointDelta <= 0.001f, "$name: warp cp parity ceiling (got $maxControlPointDelta)") + assertTrue(maxRotationDelta <= 0.01f, "$name: rotation parity ceiling (got $maxRotationDelta)") + } + } + + /** + * Compares two binding lists on one object: structural identity (driving parameters, keys, + * neutral index, limit curves, null pattern) asserted exactly; each non-neutral form pair is + * handed to [compareForms] for value measurement. + * + * @param String modelName The corpus model (for messages). + * @param String objectLabel The object under comparison (for messages). + * @param List cmo3Bindings The CMO3-imported bindings. + * @param List moc3Bindings The MOC3-imported bindings. + * @param Function compareForms Per-form value comparator. + * @return Int The number of binding pairs compared. + */ + private fun compareBindingLists( + modelName: String, + objectLabel: String, + cmo3Bindings: List>, + moc3Bindings: List>, + compareForms: (TForm, TForm) -> Unit, + ): Int { + assertEquals(cmo3Bindings.size, moc3Bindings.size, "$modelName: binding count on $objectLabel") + val moc3ByParameter = moc3Bindings.associateBy { it.parameterId } + for (cmo3Binding in cmo3Bindings) { + val moc3Binding = moc3ByParameter[cmo3Binding.parameterId] + assertTrue(moc3Binding != null, "$modelName: $objectLabel missing moc3 binding for ${cmo3Binding.parameterId.raw}") + assertEquals( + cmo3Binding.keys.toList(), + moc3Binding.keys.toList(), + "$modelName: keys on $objectLabel/${cmo3Binding.parameterId.raw}", + ) + assertEquals( + cmo3Binding.neutralIndex, + moc3Binding.neutralIndex, + "$modelName: neutral index on $objectLabel/${cmo3Binding.parameterId.raw}", + ) + assertEquals( + cmo3Binding.forms.map { it == null }, + moc3Binding.forms.map { it == null }, + "$modelName: form null pattern on $objectLabel/${cmo3Binding.parameterId.raw}", + ) + assertEquals( + cmo3Binding.limits.map { limit -> limit.parameterId to limit.points }.sortedBy { it.first.raw }, + moc3Binding.limits.map { limit -> limit.parameterId to limit.points }.sortedBy { it.first.raw }, + "$modelName: limit curves on $objectLabel/${cmo3Binding.parameterId.raw}", + ) + for (formIndex in cmo3Binding.forms.indices) { + val cmo3Form = cmo3Binding.forms[formIndex] + val moc3Form = moc3Binding.forms[formIndex] + if (cmo3Form != null && moc3Form != null) { + compareForms(cmo3Form, moc3Form) + } + } + } + return cmo3Bindings.size + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/CompositeImportParityTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/CompositeImportParityTest.kt new file mode 100644 index 0000000..e74d7b5 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/CompositeImportParityTest.kt @@ -0,0 +1,250 @@ +package org.umamo.render + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +// Offscreen channels are stored as plain f32 on both sides (no quantization like keyform +// coordinates), so the parity bar is tight. +private const val SCALAR_TOLERANCE = 0.001f + +/** + * Imports the offscreen corpus pairs from their `.cmo3` source and baked `.moc3` and asserts the + * composite surface agrees across the two paths: part composite state (composition enums, clip + * lists, invert, static channels), the keyformed opacity/color cells, and the drawable-level + * extended blend + culling. The offscreen counterpart of [Moc3Cmo3ParityTest]. Skips gracefully + * without the corpus. + */ +class CompositeImportParityTest { + private val pairNames = listOf("ModelWithOffscreenPartClipping", "MultiplyScreenColors", "modelA") + + private fun cmo3ByBasename(): Map = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map(::File) + ?.filter { it.isFile } + ?.associateBy { it.name.removeSuffix(".cmo3") } + ?: emptyMap() + + private fun moc3ByBasename(): Map = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" } + ?.associateBy { it.name.removeSuffix(".moc3") } + ?: emptyMap() + + private fun assertColorClose(expected: ColorRgb, actual: ColorRgb, label: String) { + assertTrue( + abs(expected.red - actual.red) < SCALAR_TOLERANCE && + abs(expected.green - actual.green) < SCALAR_TOLERANCE && + abs(expected.blue - actual.blue) < SCALAR_TOLERANCE, + "$label: expected $expected, got $actual", + ) + } + + /** + * Asserts the two imports' per-channel part tracks agree cell for cell. + * + * Compares each channel's own track rather than one bundled cell: after the fan-out the channels are + * independent tracks, and comparing them separately is what would catch a fan-out that mis-routed one + * channel's values into another's. + */ + private fun assertChannelTracksMatch(cmo3Channels: ChannelGrids, moc3Channels: ChannelGrids, label: String) { + for (channel in listOf(FormChannel.OPACITY, FormChannel.MULTIPLY_COLOR, FormChannel.SCREEN_COLOR)) { + val cmo3Track = cmo3Channels[channel] ?: continue + val moc3Track = moc3Channels[channel] ?: continue + assertEquals(cmo3Track.axes.size, moc3Track.axes.size, "$label: $channel axis count") + assertEquals(cmo3Track.cells.size, moc3Track.cells.size, "$label: $channel cell count") + val moc3ByCoordinate = moc3Track.cells.associateBy { cell -> cell.coordinate.toList() } + for (cmo3Cell in cmo3Track.cells) { + val coordinate = cmo3Cell.coordinate.toList() + val moc3Cell = assertNotNull(moc3ByCoordinate[coordinate], "$label: $channel cell $coordinate present in moc3") + val cmo3Value = cmo3Cell.form + val moc3Value = moc3Cell.form + if (cmo3Value is ChannelValue.Scalar && moc3Value is ChannelValue.Scalar) { + assertTrue( + abs(cmo3Value.value - moc3Value.value) < SCALAR_TOLERANCE, + "$label: $channel at $coordinate (${cmo3Value.value} vs ${moc3Value.value})", + ) + } else if (cmo3Value is ChannelValue.Color && moc3Value is ChannelValue.Color) { + assertColorClose(cmo3Value.color, moc3Value.color, "$label: $channel at $coordinate") + } else { + assertEquals(cmo3Value, moc3Value, "$label: $channel kind at $coordinate") + } + } + } + } + + private fun assertCompositeParity(cmo3Puppet: PuppetModel, moc3Puppet: PuppetModel, pairName: String) { + val cmo3Parts = cmo3Puppet.parts.associateBy { it.id } + var comparedComposites = 0 + for (moc3Part in moc3Puppet.parts) { + // The bake drops sketch parts; iterate the moc side, which must be a subset. + val cmo3Part = assertNotNull(cmo3Parts[moc3Part.id], "$pairName: moc part ${moc3Part.id.raw} in cmo3") + // Compare the applied composite (active only while Isolated): both import paths agree there. The + // stored latent composite differs by design off-Isolated (CMO3 captures authored fields, MOC3 has + // none), so parity is asserted on activeComposite, not the always-present stored composite. + val moc3Composite = moc3Part.activeComposite + val cmo3Composite = cmo3Part.activeComposite + assertEquals(cmo3Composite != null, moc3Composite != null, "$pairName: composite presence of ${moc3Part.id.raw}") + if (cmo3Composite == null || moc3Composite == null) { + continue + } + comparedComposites++ + val partLabel = "$pairName: ${moc3Part.id.raw}" + assertEquals(cmo3Composite.blendMode, moc3Composite.blendMode, "$partLabel color blend") + assertEquals(cmo3Composite.alphaBlendMode, moc3Composite.alphaBlendMode, "$partLabel alpha blend") + assertEquals(cmo3Composite.invertMask, moc3Composite.invertMask, "$partLabel invert mask") + assertEquals(cmo3Composite.maskedBy.toSet(), moc3Composite.maskedBy.toSet(), "$partLabel clip list") + assertTrue( + abs(cmo3Composite.opacity - moc3Composite.opacity) < SCALAR_TOLERANCE, + "$partLabel static opacity (${cmo3Composite.opacity} vs ${moc3Composite.opacity})", + ) + assertColorClose(cmo3Composite.multiplyColor, moc3Composite.multiplyColor, "$partLabel static multiply") + assertColorClose(cmo3Composite.screenColor, moc3Composite.screenColor, "$partLabel static screen") + // Keyformed channels: comparable only when both sides carry parameter-driven tracks (a static + // moc part stores none, while the cmo3 may keep a degenerate zero-axis one). + if (!cmo3Part.channelGrids.isEmpty && !moc3Part.channelGrids.isEmpty) { + assertChannelTracksMatch(cmo3Part.channelGrids, moc3Part.channelGrids, partLabel) + } + } + assertTrue(comparedComposites > 0, "$pairName: compared at least one isolated part") + + val cmo3Drawables = cmo3Puppet.drawables.associateBy { it.id } + for (moc3Drawable in moc3Puppet.drawables) { + val cmo3Drawable = assertNotNull(cmo3Drawables[moc3Drawable.id], "$pairName: moc drawable ${moc3Drawable.id.raw} in cmo3") + val drawableLabel = "$pairName: ${moc3Drawable.id.raw}" + assertEquals(cmo3Drawable.blendMode, moc3Drawable.blendMode, "$drawableLabel color blend") + assertEquals(cmo3Drawable.alphaBlendMode, moc3Drawable.alphaBlendMode, "$drawableLabel alpha blend") + assertEquals(cmo3Drawable.culling, moc3Drawable.culling, "$drawableLabel culling") + } + } + + /** + * The DISTINCT non-identity deformer render channel values in [puppet], sorted and rounded. + * + * A value set rather than a per-deformer join because the two import paths do not share deformer + * ids - MOC3 synthesizes `Deformer` from file order while CMO3 carries the authored id - so + * there is nothing to join on. + * + * DISTINCT rather than a multiset because the two files legitimately store different keyform + * COUNTS for the same rig: baking resamples the grid (one corpus model carries 191 warp keyforms + * in its .cmo3 and 436 in its .moc3). Multiplicity is therefore not a parity claim; the set of + * authored values is. That still catches what matters - a path that drops the channels yields an + * empty set, and one that mis-scales a value yields a different member. + * + * @param PuppetModel puppet The imported rig. + * @return List Sorted distinct "opacity|multiply|screen" rows. + */ + private fun deformerChannelMultiset(puppet: PuppetModel): List { + fun row(opacity: Float, multiplyColor: ColorRgb, screenColor: ColorRgb): String? { + if (opacity == 1f && multiplyColor == ColorRgb.MultiplyIdentity && screenColor == ColorRgb.ScreenIdentity) { + return null + } + + // Rounded: the two paths reach the same values through different float arithmetic (CMO3 + // parses decimal text, MOC3 reads stored f32), so exact equality is the wrong bar. + fun round(value: Float): String = ((value * 10000f).toInt() / 10000f).toString() + return "op=${round(opacity)} " + + "mul=${round(multiplyColor.red)},${round(multiplyColor.green)},${round(multiplyColor.blue)} " + + "scr=${round(screenColor.red)},${round(screenColor.green)},${round(screenColor.blue)}" + } + + // Zip the three channel tracks back together by cell so the comparison stays a per-cell + // (opacity, multiply, screen) row - the tracks share a shape, so index N means the same cell in all + // three. + fun channelRows(channels: ChannelGrids): List { + val opacities = channels[FormChannel.OPACITY]?.cells.orEmpty().map { cell -> (cell.form as? ChannelValue.Scalar)?.value ?: 1f } + val multiplies = + channels[FormChannel.MULTIPLY_COLOR]?.cells.orEmpty().map { cell -> + (cell.form as? ChannelValue.Color)?.color ?: ColorRgb.MultiplyIdentity + } + val screens = + channels[FormChannel.SCREEN_COLOR]?.cells.orEmpty().map { cell -> + (cell.form as? ChannelValue.Color)?.color ?: ColorRgb.ScreenIdentity + } + return opacities.indices.mapNotNull { cellIndex -> + row( + opacities[cellIndex], + multiplies.getOrElse(cellIndex) { ColorRgb.MultiplyIdentity }, + screens.getOrElse(cellIndex) { ColorRgb.ScreenIdentity }, + ) + } + } + return puppet.deformers + .flatMap { deformer -> channelRows(deformer.channelGrids) } + .distinct() + .sorted() + } + + @Test + fun deformerRenderChannelsAgreeAcrossImports() { + val cmo3Files = cmo3ByBasename() + val moc3Files = moc3ByBasename() + var comparedPairs = 0 + var totalChannelledKeyforms = 0 + // The corpus models that actually author a deformer channel and have both halves of a pair. + for (pairName in listOf("modelA", "modelC", "modelE")) { + val cmo3File = cmo3Files[pairName] ?: continue + val moc3File = moc3Files[pairName] ?: continue + val cmo3Root = Cmo3.read(cmo3File).root as? CModelSource ?: error("$pairName: root is not a CModelSource") + val cmo3Channels = deformerChannelMultiset(Cmo3Import.fromModelSource(cmo3Root)) + val moc3Channels = deformerChannelMultiset(Moc3Import.fromMocDocument(Moc3.read(moc3File.readBytes()), null)) + assertEquals(cmo3Channels, moc3Channels, "$pairName: deformer render channels") + assertTrue(cmo3Channels.isNotEmpty(), "$pairName: authors at least one non-identity deformer channel") + // The anchor that matters: a deformer opacity of exactly 0 is the subtree show/hide switch + // riggers use, and dropping it renders whole effect subtrees permanently visible. + assertTrue( + cmo3Channels.any { it.startsWith("op=0.0 ") }, + "$pairName: a deformer keys opacity to 0 (the subtree hide switch)", + ) + totalChannelledKeyforms += cmo3Channels.size + comparedPairs++ + println("[Umamo][deformer-channel-parity] $pairName: ${cmo3Channels.size} distinct non-identity channel values agree") + } + if (comparedPairs == 0) { + println("no deformer-channel cmo3/moc3 pairs present; skipping") + } else { + assertTrue(totalChannelledKeyforms > 0, "compared at least one channelled keyform") + } + } + + @Test + fun compositeSurfaceAgreesAcrossImports() { + val cmo3Files = cmo3ByBasename() + val moc3Files = moc3ByBasename() + var comparedPairs = 0 + for (pairName in pairNames) { + val cmo3File = cmo3Files[pairName] + val moc3File = moc3Files[pairName] + if (cmo3File == null || moc3File == null) { + println("$pairName cmo3/moc3 pair not present; skipping") + continue + } + val cmo3Root = Cmo3.read(cmo3File).root as? CModelSource ?: error("$pairName: root is not a CModelSource") + val cmo3Puppet = Cmo3Import.fromModelSource(cmo3Root) + val moc3Puppet = Moc3Import.fromMocDocument(Moc3.read(moc3File.readBytes()), null) + assertCompositeParity(cmo3Puppet, moc3Puppet, pairName) + comparedPairs++ + println("[Umamo][composite-parity] $pairName: parts=${moc3Puppet.parts.size} drawables=${moc3Puppet.drawables.size} OK") + } + if (comparedPairs == 0) { + println("no composite cmo3/moc3 pairs present; skipping") + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/DerivedAtlasPageFidelityTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/DerivedAtlasPageFidelityTest.kt new file mode 100644 index 0000000..9afa5b6 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/DerivedAtlasPageFidelityTest.kt @@ -0,0 +1,125 @@ +package org.umamo.render + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasPages +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * A page Umamo composes from a CMO3's tiles and placements shows what the editor's own page shows. + * + * The derivation is what every atlas change leaves the document drawing - a reload, a replace, an add, + * a repack all re-derive the WHOLE page from each tile's raster - and what a CMO3 export then writes + * back. So an unedited atlas, derived, must come back as the page the file holds: nothing painted + * where the editor's page is transparent (meshes reach past their art, and anything painted there + * shows as a fringe), and every edge resampled the way the editor resamples it, bilinearly against + * the transparency beyond the art, so its coverage matches to a few steps of alpha. + * + * Gated on `cmo3.sample` (Erica by default: one 8192 page, 176 tiles whose rasters are cropped tight to + * their art, 84 of them at fractional positions); skips by assumption without it. + */ +class DerivedAtlasPageFidelityTest { + private companion object { + /** Below this alpha a file pixel counts as empty page. */ + const val EMPTY_ALPHA = 16 + + /** At or above this alpha a derived pixel counts as painted. */ + const val PAINTED_ALPHA = 64 + + /** The most a derived pixel's alpha may differ from the file's: resampling rounds, it never moves an edge. */ + const val ALPHA_TOLERANCE = 8 + + /** At or above this alpha on both pages a pixel's color is compared. */ + const val COLOR_COMPARED_ALPHA = 128 + + /** How far a compared pixel's color may sit from the file's before it counts as different. */ + const val COLOR_TOLERANCE = 24 + + /** + * The share of compared pixels whose color may differ past [COLOR_TOLERANCE]. The editor's own + * translucent edge texels run slightly darker than the art's color, where the derivation keeps the + * art's color; a handful of edge pixels differ that way and nothing else does. + */ + const val MAXIMUM_COLOR_MISMATCH_FRACTION = 1e-4f + } + + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { file -> file.isFile } + + @Test + fun anUneditedAtlasDerivesBackToTheFilesOwnPages() { + val file = sample + Assume.assumeTrue("[derived-page] no cmo3.sample", file != null) + val cmo3 = Cmo3.read(file!!) + val root = cmo3.root as CModelSource + val imported = Cmo3Import.importModelSource(root) + val puppet = imported.puppet + Assume.assumeTrue("[derived-page] ${file.name} draws from its source layers, not pages", puppet.atlas.storedUvsAddressPages) + val tileResources = imported.atlasIngest.imageResourceByTile + val rasters = SourceArtRasters.fromPng { tileId -> tileResources[tileId]?.let(cmo3::extractLayerPng) } + val derived = assertNotNull(deriveAtlasTextures(puppet, rasters, premultipliedAlpha = false), "the atlas derives") + val filePages = cmo3AtlasPages(root, cmo3::extractLayerPng) + + var comparedPages = 0 + val failures = ArrayList() + for (pageIndex in puppet.atlas.pages.indices) { + // The file's page for this model page: the one a drawable over a tile placed here samples. + val drawable = + puppet.drawables.firstOrNull { candidate -> + candidate.atlasTileId?.let { tileId -> puppet.atlas.tileById[tileId]?.placement?.pageIndex } == pageIndex && + filePages.atlasIndexByDrawableId.containsKey(candidate.id.raw) + } ?: continue + val filePage: RasterImage = PngCodec.read(filePages.pageBytes[filePages.atlasIndexByDrawableId.getValue(drawable.id.raw)]) + val derivedPage = derived.atlases[pageIndex] + if (filePage.width != derivedPage.width || filePage.height != derivedPage.height) { + failures.add("page $pageIndex: the file's is ${filePage.width}x${filePage.height}, derived ${derivedPage.width}x${derivedPage.height}") + continue + } + comparedPages++ + var paintedOverEmpty = 0 + var maximumAlphaDifference = 0 + var colorCompared = 0 + var colorMismatches = 0 + for (pixelIndex in 0 until filePage.width * filePage.height) { + val byteOffset = pixelIndex * 4 + val fileAlpha = filePage.rgba[byteOffset + 3].toInt() and 0xFF + val derivedAlpha = derivedPage.rgba[byteOffset + 3].toInt() and 0xFF + if (fileAlpha < EMPTY_ALPHA && derivedAlpha >= PAINTED_ALPHA) { + paintedOverEmpty++ + } + maximumAlphaDifference = maxOf(maximumAlphaDifference, abs(fileAlpha - derivedAlpha)) + if (fileAlpha >= COLOR_COMPARED_ALPHA && derivedAlpha >= COLOR_COMPARED_ALPHA) { + colorCompared++ + val colorDifference = + (0 until 3).maxOf { channel -> abs((filePage.rgba[byteOffset + channel].toInt() and 0xFF) - (derivedPage.rgba[byteOffset + channel].toInt() and 0xFF)) } + if (colorDifference > COLOR_TOLERANCE) { + colorMismatches++ + } + } + } + val colorMismatchFraction = if (colorCompared == 0) 0f else colorMismatches.toFloat() / colorCompared + println( + "[derived-page] ${file.name} page $pageIndex: $paintedOverEmpty pixels painted over empty page, alpha within $maximumAlphaDifference, " + + "$colorMismatches of $colorCompared compared pixels off by more than $COLOR_TOLERANCE in color", + ) + if (paintedOverEmpty > 0) { + failures.add("page $pageIndex: $paintedOverEmpty pixels painted where the file's page is empty") + } + if (maximumAlphaDifference > ALPHA_TOLERANCE) { + failures.add("page $pageIndex: a pixel's alpha differs from the file's by $maximumAlphaDifference") + } + if (colorMismatchFraction > MAXIMUM_COLOR_MISMATCH_FRACTION) { + failures.add("page $pageIndex: $colorMismatchFraction of compared pixels differ in color from the file's") + } + } + assertTrue(comparedPages > 0, "no page was compared; the gate checked nothing") + assertTrue(failures.isEmpty(), "the derived pages differ from the file's own:\n" + failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/Moc3Cmo3ParityTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/Moc3Cmo3ParityTest.kt new file mode 100644 index 0000000..d04ba9e --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/Moc3Cmo3ParityTest.kt @@ -0,0 +1,484 @@ +package org.umamo.render + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import org.umamo.runtime.model.RenderNode +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +// CMO3 stores keyform coordinates lightly quantized (dyadic fractions, ~1e-4) where the moc keeps +// full precision, so parity is bounded, not exact. Canvas-pixel values agree within a pixel: the +// quantization amplifies through a warp lattice spanning thousands of pixels (corpus max observed +// 0.68px over 30k vertices; a wrong space conversion is off by hundreds). Warp-lattice (u, v) +// values compare pre-amplification, within ~1e-4 of the unit lattice. +private const val CANVAS_TOLERANCE_PX = 1.0f +private const val LATTICE_TOLERANCE = 0.001f +private const val ANGLE_TOLERANCE_DEGREES = 0.05f + +/** + * Imports the same model from its `.cmo3` source and its baked `.moc3` (with the rest-mesh post-pass + * the document loader applies) and asserts the two `PuppetModel`s agree - the gate that pins the MOC3 + * coordinate conversion (CanvasInfo root transform, rotation-local scaling, the rotation angle sign, + * and the canvas-space rest-mesh rewrite) against the CMO3 numbers, which the differential-oracle + * test already validates end-to-end. + * + * Gated on BOTH `-Dcmo3.sample` and `-Dmoc3.sample` naming the same model (the build supplies the + * local corpus Erica for both by default). Comparison runs over the drawable-id intersection: the + * bake drops sketch ("Guide Image") parts and their drawables, so the sets are not equal. + */ +class Moc3Cmo3ParityTest { + private val cmo3Sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + private val moc3Sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun mocImportMatchesCmo3Import() { + val cmo3File = cmo3Sample + val moc3File = moc3Sample + if (cmo3File == null || moc3File == null) { + println("cmo3.sample/moc3.sample not present; skipping parity test") + return + } + val cmo3Root = Cmo3.read(cmo3File).root as? CModelSource ?: error("root is not a CModelSource") + // The rest-mesh comparison normalizes BOTH sides through the same default-pose rewrite: CMO3's + // stored base is authored editing geometry that may drift a few pixels from the evaluated default + // pose (a moc has no way to recover the authored value), so comparing raw cmo3 bases against the + // moc's evaluated ones would measure that drift, not the conversion under test. + val fromCmo3 = restMeshesToCanvasSpace(Cmo3Import.fromModelSource(cmo3Root)) + val fromMoc3 = + restMeshesToCanvasSpace( + Moc3Import.fromMocDocument(Moc3.read(moc3File.readBytes()), siblingDisplayInfo(moc3File)), + ) + + // Canvas and world origin agree (CanvasInfo origin == CMO3 canvas center). + assertEquals(fromCmo3.canvasWidth, fromMoc3.canvasWidth, "canvas width") + assertEquals(fromCmo3.canvasHeight, fromMoc3.canvasHeight, "canvas height") + assertEquals(fromCmo3.worldOriginX, fromMoc3.worldOriginX, "world origin x") + assertEquals(fromCmo3.worldOriginZ, fromMoc3.worldOriginZ, "world origin y") + + // Parameters: identical axes (the bake preserves every parameter). + val cmo3Parameters = fromCmo3.parameters.associateBy { it.id } + for (mocParameter in fromMoc3.parameters) { + val cmo3Parameter = cmo3Parameters[mocParameter.id] ?: error("moc parameter ${mocParameter.id.raw} not in cmo3") + assertEquals(cmo3Parameter.min, mocParameter.min, "min of ${mocParameter.id.raw}") + assertEquals(cmo3Parameter.max, mocParameter.max, "max of ${mocParameter.id.raw}") + assertEquals(cmo3Parameter.default, mocParameter.default, "default of ${mocParameter.id.raw}") + } + assertEquals(fromCmo3.parameterLinks, fromMoc3.parameterLinks, "parameter links") + + val cmo3Drawables = fromCmo3.drawables.associateBy { it.id } + val moc3Drawables = fromMoc3.drawables.associateBy { it.id } + val sharedIds = cmo3Drawables.keys.intersect(moc3Drawables.keys) + println("[Umamo][parity] drawables cmo3=${cmo3Drawables.size} moc3=${moc3Drawables.size} shared=${sharedIds.size}") + assertTrue(sharedIds.size >= moc3Drawables.size, "every moc3 drawable should exist in the cmo3") + + // Keyform-space tolerance per drawable: warp children live on the unit lattice, everything else + // in canvas pixels. + val moc3DeformerById = fromMoc3.deformers.associateBy { it.id } + + fun keyformTolerance(parentDeformerId: DeformerId?): Float = + if (parentDeformerId != null && moc3DeformerById[parentDeformerId] is Deformer.Warp) LATTICE_TOLERANCE else CANVAS_TOLERANCE_PX + + var comparedVertices = 0 + var maxRestDelta = 0f + val restOffenders = ArrayList() + for (drawableId in sharedIds) { + val cmo3Drawable = cmo3Drawables.getValue(drawableId) + val moc3Drawable = moc3Drawables.getValue(drawableId) + assertEquals(cmo3Drawable.blendMode, moc3Drawable.blendMode, "blend mode of ${drawableId.raw}") + assertEquals(cmo3Drawable.maskedBy.toSet(), moc3Drawable.maskedBy.toSet(), "masks of ${drawableId.raw}") + assertEquals(cmo3Drawable.invertMask, moc3Drawable.invertMask, "invert mask of ${drawableId.raw}") + + val cmo3Mesh = cmo3Drawable.mesh ?: continue + val moc3Mesh = moc3Drawable.mesh ?: error("moc3 ${drawableId.raw} has no mesh but the cmo3 does") + assertEquals(cmo3Mesh.vertexCount, moc3Mesh.vertexCount, "vertex count of ${drawableId.raw}") + assertTrue(cmo3Mesh.indices.contentEquals(moc3Mesh.indices), "triangle indices of ${drawableId.raw}") + // UVs are static in both formats and untouched by the coordinate conversion. + assertTrue( + floatsClose(cmo3Mesh.uvs, moc3Mesh.uvs, 0.0005f), + "uvs of ${drawableId.raw}" + flipDiagnostic(cmo3Mesh.uvs, moc3Mesh.uvs), + ) + // Rest positions: canvas space on both sides (the moc side through the default-pose rewrite), + // so this pins the whole conversion + cascade path. Collected first (worst offender per + // drawable) so a failure reports the model-wide picture, not the first vertex hit. + assertEquals(cmo3Mesh.positions.size, moc3Mesh.positions.size, "position array of ${drawableId.raw}") + var drawableWorstDelta = 0f + var drawableWorstIndex = -1 + for (coordIndex in cmo3Mesh.positions.indices) { + val delta = abs(cmo3Mesh.positions[coordIndex] - moc3Mesh.positions[coordIndex]) + if (delta > drawableWorstDelta) { + drawableWorstDelta = delta + drawableWorstIndex = coordIndex + } + } + if (drawableWorstDelta > maxRestDelta) { + maxRestDelta = drawableWorstDelta + } + if (drawableWorstDelta > CANVAS_TOLERANCE_PX) { + restOffenders.add( + "${drawableId.raw}[$drawableWorstIndex] delta=$drawableWorstDelta " + + "cmo3=${cmo3Mesh.positions[drawableWorstIndex]} moc3=${moc3Mesh.positions[drawableWorstIndex]}", + ) + } + comparedVertices += cmo3Mesh.vertexCount + + compareMeshKeyforms( + drawableId, + cmo3Drawable.geometryGrid, + cmo3Mesh.positions, + moc3Drawable.geometryGrid, + moc3Mesh.positions, + keyformTolerance(moc3Drawable.parentDeformerId), + ) + compareMeshChannels(drawableId, cmo3Drawable.channelGrids, moc3Drawable.channelGrids) + } + println("[Umamo][parity] compared $comparedVertices rest vertices, max delta $maxRestDelta px") + assertTrue( + restOffenders.isEmpty(), + "rest positions beyond ${CANVAS_TOLERANCE_PX}px on ${restOffenders.size} drawables:\n" + + restOffenders.take(20).joinToString("\n"), + ) + + compareDeformerChains(fromCmo3, fromMoc3, sharedIds) + compareRenderOrder(fromCmo3, fromMoc3, sharedIds) + } + + /** + * Compares two mesh keyform grids cell by cell as parent-space absolutes (base + delta), matching + * cells across the grids by their axis coordinate. Skips silently when either side is unkeyed. + * + * @param DrawableId drawableId The drawable under comparison (for failure messages). + * @param KeyformGrid? cmo3Grid The CMO3 grid (deltas vs [cmo3Base]). + * @param FloatArray cmo3Base The CMO3 rest positions. + * @param KeyformGrid? moc3Grid The MOC3 grid (deltas vs [moc3Base]). + * @param FloatArray moc3Base The MOC3 rest positions. + * @param Float tolerance The per-coordinate tolerance in the drawable's parent space. + */ + + private fun compareMeshKeyforms( + drawableId: DrawableId, + cmo3Grid: KeyformGrid?, + cmo3Base: FloatArray, + moc3Grid: KeyformGrid?, + moc3Base: FloatArray, + tolerance: Float, + ) { + if (cmo3Grid == null || moc3Grid == null) { + return + } + val cmo3Axes = cmo3Grid.axes.map { axis -> axis.parameterId to axis.keys.toList() } + val moc3Axes = moc3Grid.axes.map { axis -> axis.parameterId to axis.keys.toList() } + assertEquals(cmo3Axes, moc3Axes, "keyform axes of ${drawableId.raw}") + val moc3Cells = moc3Grid.cells.associateBy { cell -> cell.coordinate.toList() } + for (cmo3Cell in cmo3Grid.cells) { + val moc3Cell = moc3Cells[cmo3Cell.coordinate.toList()] ?: error("moc3 ${drawableId.raw} misses cell ${cmo3Cell.coordinate.toList()}") + val cmo3Deltas = cmo3Cell.form.positionDeltas + val moc3Deltas = moc3Cell.form.positionDeltas + assertEquals(cmo3Deltas.size, moc3Deltas.size, "delta array of ${drawableId.raw}") + for (coordIndex in cmo3Deltas.indices) { + val cmo3Absolute = cmo3Base[coordIndex] + cmo3Deltas[coordIndex] + val moc3Absolute = moc3Base[coordIndex] + moc3Deltas[coordIndex] + assertTrue( + abs(cmo3Absolute - moc3Absolute) <= tolerance, + "keyform position of ${drawableId.raw}@${cmo3Cell.coordinate.toList()}[$coordIndex]: " + + "cmo3=$cmo3Absolute moc3=$moc3Absolute", + ) + } + } + } + + /** + * Asserts the two import paths agree on a drawable's scalar channel tracks, cell for cell. + * + * Draw order and opacity used to ride the geometry cell, so they were compared there; they are their + * own tracks now, but the parity claim is unchanged - both paths must land on the same values. + * + * @param DrawableId drawableId The drawable under comparison (for failure messages). + * @param ChannelGrids cmo3Channels The CMO3 import's tracks. + * @param ChannelGrids moc3Channels The MOC3 import's tracks. + */ + private fun compareMeshChannels(drawableId: DrawableId, cmo3Channels: ChannelGrids, moc3Channels: ChannelGrids) { + for (channel in listOf(FormChannel.DRAW_ORDER, FormChannel.OPACITY)) { + val cmo3Track = cmo3Channels[channel] ?: continue + val moc3Track = moc3Channels[channel] ?: continue + val moc3Cells = moc3Track.cells.associateBy { cell -> cell.coordinate.toList() } + for (cmo3Cell in cmo3Track.cells) { + val coordinate = cmo3Cell.coordinate.toList() + val moc3Cell = moc3Cells[coordinate] ?: error("moc3 ${drawableId.raw} misses $channel cell $coordinate") + val cmo3Value = (cmo3Cell.form as ChannelValue.Scalar).value + val moc3Value = (moc3Cell.form as ChannelValue.Scalar).value + assertTrue( + abs(cmo3Value - moc3Value) <= 0.001f, + "$channel of ${drawableId.raw}@$coordinate: cmo3=$cmo3Value moc3=$moc3Value", + ) + } + } + } + + /** + * Compares the deformer chains above each shared drawable. MOC3 deformers carry synthesized ids, + * so they are matched positionally along the parent chain from each drawable, then compared by + * kind, lattice size, keyform axes, and keyform values - warp control points in the parent's space + * (lattice for a nested warp, canvas pixels at the root), rotation origin/scale/reflection + * likewise, and the total angle within [ANGLE_TOLERANCE_DEGREES] (this is what pins the angle-sign + * conversion). + * + * @param PuppetModel fromCmo3 The CMO3-imported model. + * @param PuppetModel fromMoc3 The MOC3-imported model. + * @param Set sharedIds The drawable-id intersection. + */ + private fun compareDeformerChains(fromCmo3: PuppetModel, fromMoc3: PuppetModel, sharedIds: Set) { + val cmo3Deformers = fromCmo3.deformers.associateBy { it.id } + val moc3Deformers = fromMoc3.deformers.associateBy { it.id } + val cmo3Drawables = fromCmo3.drawables.associateBy { it.id } + val moc3Drawables = fromMoc3.drawables.associateBy { it.id } + val comparedPairs = HashSet>() + var maxAngleDelta = 0f + for (drawableId in sharedIds) { + var cmo3Parent = cmo3Drawables.getValue(drawableId).parentDeformerId + var moc3Parent = moc3Drawables.getValue(drawableId).parentDeformerId + while (cmo3Parent != null || moc3Parent != null) { + assertTrue( + cmo3Parent != null && moc3Parent != null, + "deformer chain of ${drawableId.raw} diverges: cmo3=${cmo3Parent?.raw} moc3=${moc3Parent?.raw}", + ) + val cmo3Deformer = cmo3Deformers.getValue(cmo3Parent) + val moc3Deformer = moc3Deformers.getValue(moc3Parent) + if (!comparedPairs.add(cmo3Deformer.id to moc3Deformer.id)) { + break + } + // A nested deformer's own keyform space is ITS parent's space. + val spaceTolerance = + if (moc3Deformer.parent != null && moc3Deformers[moc3Deformer.parent] is Deformer.Warp) LATTICE_TOLERANCE else CANVAS_TOLERANCE_PX + when (cmo3Deformer) { + is Deformer.Warp -> { + val mocWarp = moc3Deformer as? Deformer.Warp ?: error("kind mismatch above ${drawableId.raw}") + assertEquals(cmo3Deformer.rows, mocWarp.rows, "warp rows above ${drawableId.raw}") + assertEquals(cmo3Deformer.columns, mocWarp.columns, "warp columns above ${drawableId.raw}") + assertEquals(cmo3Deformer.isQuadTransform, mocWarp.isQuadTransform, "warp mode above ${drawableId.raw}") + compareWarpGrids(drawableId, cmo3Deformer.geometryGrid, mocWarp.geometryGrid, spaceTolerance) + } + is Deformer.Rotation -> { + val mocRotation = moc3Deformer as? Deformer.Rotation ?: error("kind mismatch above ${drawableId.raw}") + val angleDelta = compareRotationGrids(drawableId, cmo3Deformer, mocRotation, spaceTolerance) + if (angleDelta > maxAngleDelta) { + maxAngleDelta = angleDelta + } + } + } + cmo3Parent = cmo3Deformer.parent + moc3Parent = moc3Deformer.parent + } + } + println("[Umamo][parity] compared ${comparedPairs.size} deformer pairs, max angle delta $maxAngleDelta deg") + } + + /** + * Compares two warp keyform grids cell by cell (control points in the warp's parent space). + * + * @param DrawableId drawableId The drawable whose chain is under comparison (for messages). + * @param KeyformGrid? cmo3Grid The CMO3 warp grid. + * @param KeyformGrid? moc3Grid The MOC3 warp grid. + * @param Float tolerance The per-coordinate tolerance in the warp's parent space. + */ + private fun compareWarpGrids( + drawableId: DrawableId, + cmo3Grid: KeyformGrid?, + moc3Grid: KeyformGrid?, + tolerance: Float, + ) { + if (cmo3Grid == null || moc3Grid == null) { + return + } + // Hard-gate the grid shapes like compareMeshKeyforms does: silently skipping unmatched cells + // would let a systematic axis-order or coordinate regression pass this comparison vacuously. + assertEquals( + cmo3Grid.axes.map { axis -> axis.parameterId to axis.keys.toList() }, + moc3Grid.axes.map { axis -> axis.parameterId to axis.keys.toList() }, + "warp keyform axes above ${drawableId.raw}", + ) + val moc3Cells = moc3Grid.cells.associateBy { cell -> cell.coordinate.toList() } + for (cmo3Cell in cmo3Grid.cells) { + val moc3Cell = + moc3Cells[cmo3Cell.coordinate.toList()] + ?: error("moc3 warp above ${drawableId.raw} misses cell ${cmo3Cell.coordinate.toList()}") + val cmo3Points = cmo3Cell.form.controlPoints + val moc3Points = moc3Cell.form.controlPoints + assertEquals(cmo3Points.size, moc3Points.size, "warp control-point count above ${drawableId.raw}") + for (coordIndex in cmo3Points.indices) { + assertTrue( + abs(cmo3Points[coordIndex] - moc3Points[coordIndex]) <= tolerance, + "warp control point above ${drawableId.raw}@${cmo3Cell.coordinate.toList()}[$coordIndex]: " + + "cmo3=${cmo3Points[coordIndex]} moc3=${moc3Points[coordIndex]}", + ) + } + } + } + + /** + * Compares two rotation keyform grids cell by cell and returns the largest total-angle delta seen. + * CMO3 keyform angles are absolute where the moc splits baseAngle + delta, so totals are compared. + * + * @param DrawableId drawableId The drawable whose chain is under comparison (for messages). + * @param Deformer.Rotation cmo3Rotation The CMO3 rotation deformer. + * @param Deformer.Rotation moc3Rotation The MOC3 rotation deformer. + * @param Float tolerance The origin tolerance in the rotation's parent space. + * @return Float The largest absolute total-angle difference in degrees. + */ + private fun compareRotationGrids( + drawableId: DrawableId, + cmo3Rotation: Deformer.Rotation, + moc3Rotation: Deformer.Rotation, + tolerance: Float, + ): Float { + val cmo3Grid = cmo3Rotation.geometryGrid ?: return 0f + val moc3Grid = moc3Rotation.geometryGrid ?: return 0f + // Hard-gate the grid shapes like compareMeshKeyforms does: silently skipping unmatched cells + // would report "max angle delta 0.0" for a systematically-wrong conversion. + assertEquals( + cmo3Grid.axes.map { axis -> axis.parameterId to axis.keys.toList() }, + moc3Grid.axes.map { axis -> axis.parameterId to axis.keys.toList() }, + "rotation keyform axes above ${drawableId.raw}", + ) + val moc3Cells = moc3Grid.cells.associateBy { cell -> cell.coordinate.toList() } + var maxAngleDelta = 0f + for (cmo3Cell in cmo3Grid.cells) { + val moc3Cell = + moc3Cells[cmo3Cell.coordinate.toList()] + ?: error("moc3 rotation above ${drawableId.raw} misses cell ${cmo3Cell.coordinate.toList()}") + assertTrue( + abs(cmo3Cell.form.originX - moc3Cell.form.originX) <= tolerance && + abs(cmo3Cell.form.originY - moc3Cell.form.originY) <= tolerance, + "rotation origin above ${drawableId.raw}@${cmo3Cell.coordinate.toList()}: " + + "cmo3=(${cmo3Cell.form.originX}, ${cmo3Cell.form.originY}) " + + "moc3=(${moc3Cell.form.originX}, ${moc3Cell.form.originY})", + ) + val cmo3TotalAngle = cmo3Rotation.baseAngle + cmo3Cell.form.angle + val moc3TotalAngle = moc3Rotation.baseAngle + moc3Cell.form.angle + val angleDelta = abs(cmo3TotalAngle - moc3TotalAngle) + if (angleDelta > maxAngleDelta) { + maxAngleDelta = angleDelta + } + assertTrue( + angleDelta <= ANGLE_TOLERANCE_DEGREES, + "rotation angle above ${drawableId.raw}@${cmo3Cell.coordinate.toList()}: " + + "cmo3=$cmo3TotalAngle moc3=$moc3TotalAngle (sign convention?)", + ) + assertTrue(abs(cmo3Cell.form.scale - moc3Cell.form.scale) <= 0.001f, "rotation scale above ${drawableId.raw}") + } + // Reflections are FLAG channel tracks now, not pivot-form fields, but the parity claim is the same: + // both import paths must land on the same flip at every cell. + for (flipChannel in listOf(FormChannel.FLIP_X, FormChannel.FLIP_Y)) { + val cmo3Flips = cmo3Rotation.channelGrids[flipChannel] + val moc3Flips = moc3Rotation.channelGrids[flipChannel] + if (cmo3Flips == null || moc3Flips == null) { + continue + } + val moc3FlipCells = moc3Flips.cells.associateBy { cell -> cell.coordinate.toList() } + for (cmo3Cell in cmo3Flips.cells) { + val moc3Cell = + moc3FlipCells[cmo3Cell.coordinate.toList()] + ?: error("moc3 rotation above ${drawableId.raw} misses $flipChannel cell ${cmo3Cell.coordinate.toList()}") + assertEquals(cmo3Cell.form, moc3Cell.form, "rotation $flipChannel above ${drawableId.raw}") + } + } + return maxAngleDelta + } + + /** + * Compares the render-order leaf sequence: the MOC3 import takes the baked tree verbatim, the CMO3 + * import derives it from the org tree; restricted to the shared drawables the two must agree. + * + * @param PuppetModel fromCmo3 The CMO3-imported model. + * @param PuppetModel fromMoc3 The MOC3-imported model. + * @param Set sharedIds The drawable-id intersection. + */ + private fun compareRenderOrder(fromCmo3: PuppetModel, fromMoc3: PuppetModel, sharedIds: Set) { + fun leaves(node: RenderNode, into: ArrayList) { + when (node) { + is RenderDrawable -> into.add(node.id) + is RenderGroup -> node.children.forEach { child -> leaves(child, into) } + } + } + + val cmo3Leaves = ArrayList().also { leaves(fromCmo3.renderRoot, it) }.filter { it in sharedIds } + val moc3Leaves = ArrayList().also { leaves(fromMoc3.renderRoot, it) }.filter { it in sharedIds } + assertEquals( + cmo3Leaves.map { it.raw }, + moc3Leaves.map { it.raw }, + "render-order leaf sequence over shared drawables", + ) + } + + /** + * Whether two float arrays agree element-wise within [tolerance]. + * + * @param FloatArray left One array. + * @param FloatArray right The other. + * @param Float tolerance The per-element tolerance. + * @return Boolean True when equal within tolerance. + */ + private fun floatsClose(left: FloatArray, right: FloatArray, tolerance: Float): Boolean { + if (left.size != right.size) { + return false + } + for (valueIndex in left.indices) { + if (abs(left[valueIndex] - right[valueIndex]) > tolerance) { + return false + } + } + return true + } + + /** + * A diagnostic suffix for a UV mismatch: reports whether flipping V (v -> 1 - v) would make the + * arrays agree, so a failed assertion names the orientation problem directly. + * + * @param FloatArray cmo3Uvs The CMO3 UVs. + * @param FloatArray moc3Uvs The MOC3 UVs. + * @return String The diagnostic, or an empty string when nothing conclusive can be said. + */ + private fun flipDiagnostic(cmo3Uvs: FloatArray, moc3Uvs: FloatArray): String { + if (cmo3Uvs.size != moc3Uvs.size) { + return " (size mismatch)" + } + val flipped = + FloatArray(moc3Uvs.size) { coordIndex -> + if (coordIndex % 2 == 1) 1f - moc3Uvs[coordIndex] else moc3Uvs[coordIndex] + } + return if (floatsClose(cmo3Uvs, flipped, 0.0005f)) " (moc3 V is flipped: import needs v -> 1 - v)" else "" + } + + /** + * Reads the sample's sibling `.cdi3.json`, or null when absent. + * + * @param File mocFile The `.moc3` sample. + * @return Cdi3Json? The parsed display info, or null. + */ + private fun siblingDisplayInfo(mocFile: File): Cdi3Json? { + // Case-insensitive strip, matching the document loader's basename rule. + val basename = if (mocFile.name.endsWith(".moc3", ignoreCase = true)) mocFile.name.dropLast(".moc3".length) else mocFile.name + val cdi3File = mocFile.parentFile.resolve("$basename.cdi3.json") + if (!cdi3File.isFile) { + return null + } + return Moc3.readCdi3(cdi3File.readText()) + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/Moc3EvalSanityTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/Moc3EvalSanityTest.kt new file mode 100644 index 0000000..141942a --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/Moc3EvalSanityTest.kt @@ -0,0 +1,74 @@ +package org.umamo.render + +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.eval.CpuDeformationEvaluator +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Default-pose eval sanity over EVERY corpus moc: imports each `.moc3` found beside the + * `-Dmoc3.sample` model and asserts the evaluated world geometry is finite and lands within a + * generous multiple of the canvas. Models with no canvas, and models with no art meshes at all, are + * reported and skipped rather than failed - both are shapes a real `.moc3` takes. + */ +class Moc3EvalSanityTest { + private val sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun corpusModelsEvaluateWithinCanvasBounds() { + val corpusRoot = sample?.parentFile?.parentFile?.takeIf { it.isDirectory } + if (corpusRoot == null) { + println("moc3.sample not present; skipping eval sanity test") + return + } + val mocFiles = + corpusRoot.listFiles { candidate -> candidate.isDirectory }.orEmpty() + .flatMap { modelDirectory -> modelDirectory.listFiles { candidate -> candidate.isFile && candidate.extension == "moc3" }.orEmpty().toList() } + .sortedBy { it.path } + assertTrue(mocFiles.isNotEmpty(), "expected corpus .moc3 files under ${corpusRoot.path}") + + for (mocFile in mocFiles) { + val mocDocument = + runCatching { Moc3.read(mocFile.readBytes()) }.getOrElse { + println("${mocFile.name}: not decodable, skipping") + continue + } + val model = Moc3Import.fromMocDocument(mocDocument, null) + if (model.canvasWidth <= 0f || model.canvasHeight <= 0f) { + println("${mocFile.name}: no canvas, skipping bounds check") + continue + } + // A moc may legitimately carry no art at all: the offscreen enum-extraction fixtures are parts + // and parameters only, with offscreen flagged on a couple of parts, and the official Cubism + // Core reads drawables=0 for them too. The guard is on the MODEL rather than on the eval + // result so the assertion below stays live - a model that HAS drawables and still evaluates + // to nothing is a regression, not a fixture. + if (model.drawables.isEmpty()) { + println("${mocFile.name}: no drawables, skipping bounds check") + continue + } + val geometry = CpuDeformationEvaluator().evaluate(model, emptyMap()) + assertTrue(geometry.worldPositions.isNotEmpty(), "${mocFile.name}: nothing evaluated at the default pose") + + // World space is origin-centered: x spans about [-originX, canvasWidth - originX], y the + // negated equivalent. Allow 4x the canvas's larger side in every direction - room for real + // overhang, far below a ppu-scale (1000x+) unit-seam explosion. + val margin = 4f * maxOf(model.canvasWidth, model.canvasHeight) + var checkedValues = 0 + for ((drawableId, positions) in geometry.worldPositions) { + for (value in positions) { + assertTrue(value.isFinite(), "${mocFile.name}: non-finite world coordinate on ${drawableId.raw}") + assertTrue( + value > -margin && value < margin, + "${mocFile.name}: world coordinate $value on ${drawableId.raw} is beyond ±$margin - " + + "a coordinate/scale seam regression (see Moc3Import's unit-seam notes)", + ) + checkedValues++ + } + } + println("${mocFile.name}: ${geometry.worldPositions.size} drawables, $checkedValues coordinates within ±$margin") + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/SourceLayerPlanCorpusTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/SourceLayerPlanCorpusTest.kt new file mode 100644 index 0000000..227f9b4 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/SourceLayerPlanCorpusTest.kt @@ -0,0 +1,66 @@ +package org.umamo.render + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasIngest +import org.umamo.runtime.model.AtlasTileId +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The source-artwork display plan on real documents: how many drawables it maps, and how many it + * leaves on the atlas. + * + * The renderer engages the mode only when EVERY layer the plan maps is resident, so a plan that maps + * nothing leaves the whole puppet on its atlas - silently, because that is also what a document with + * no artwork looks like. This is the measurement that tells those two apart. + */ +class SourceLayerPlanCorpusTest { + private fun corpusFiles(): List = + System.getProperty("cmo3.probe") + .orEmpty() + .split(',') + .map { entry -> entry.trim() } + .filter { entry -> entry.isNotEmpty() } + .map(::File) + .filter { file -> file.isFile } + + @Test + fun theArtworkPlanMapsCorpusDrawables() { + val files = corpusFiles() + Assume.assumeTrue("no cmo3.probe corpus models", files.isNotEmpty()) + + var mappedTotal = 0 + var decodedTotal = 0 + val lines = mutableListOf() + for (file in files) { + val root = Cmo3.read(file).root as? CModelSource ?: continue + val puppet = Cmo3Import.fromModelSource(root).let { model -> model.copy(rendersFromSourceLayers = true) } + if (puppet.atlas.tiles.isEmpty()) { + continue + } + val plan = buildLayerDrawPlan(puppet) + val meshed = puppet.drawables.count { drawable -> drawable.mesh != null } + mappedTotal += plan.drawsByDrawableId.size + // The delivery half, assembled exactly as the document loader does it: the renderer engages + // only when EVERY mapped layer decodes, so a plan that maps everything and decodes nothing + // leaves the whole puppet on its atlas - and looks identical to having no artwork at all. + val model = Cmo3.read(file) + val tileResources = cmo3AtlasIngest(root).imageResourceByTile + val rasters = SourceArtRasters.fromPng { tileId -> tileResources[tileId]?.let(model::extractLayerPng) } + val decoded = plan.layerByteCostByKey.keys.count { key -> rasters.decodeRaster(AtlasTileId(key)) != null } + decodedTotal += decoded + lines.add( + "${file.name}: ${plan.drawsByDrawableId.size}/$meshed mapped, " + + "${plan.unresolvedDrawableCount} unresolved, $decoded/${plan.layerByteCostByKey.size} layers decoded, " + + "pagesAddressed=${puppet.atlas.storedUvsAddressPages}", + ) + } + lines.take(40).forEach { line -> println("[plan] $line") } + assertTrue(mappedTotal > 0, "no corpus drawable mapped to artwork; the plan is empty everywhere") + assertTrue(decodedTotal > 0, "no mapped layer decoded; the renderer would never engage the mode") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendDeltaFrameProbeTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendDeltaFrameProbeTest.kt new file mode 100644 index 0000000..13ca576 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendDeltaFrameProbeTest.kt @@ -0,0 +1,165 @@ +package org.umamo.render.eval + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.Section +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.runtime.eval.gridCorners +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Determines what the baked MOC3 blend-shape deltas are relative to, by joining Model A's ingested + * mesh bindings against Model A's stored delta rows and testing two hypotheses per non-neutral key: + * + * H_SETUP: stored delta = authoredForm - restMesh (the ingested MeshForm.positionDeltas verbatim) + * H_GRID: stored delta = authoredForm - gridFormInterpolatedAtDefaultPose (the same multilinear + * interpolation the runtime performs, sampled with every parameter at its default) + * + * The hypotheses coincide on drawables whose default-pose grid form equals the rest mesh; only + * records where they differ discriminate. Units: MOC3 deltas are model space; the origin cancels + * in a delta, so the conversion is x/ppu with Y components sign-flipped. + * + * MEASURED VERDICT (Model A, 16 discriminating records): H_SETUP is refuted outright (errors 20-50x + * larger than H_GRID). H_GRID holds to first order, but a residual remains on warp-parented + * meshes whose parent warp carries a morph on the same driving parameter - antisymmetric in the + * key (e.g. ArtMesh80 comp 128: implied reference deviates +-147 px at keys -+10 while the + * authored forms there are equal), consistent with the baker pre-compensating the mesh delta + * through the morphed parent warp. The assert below is therefore DIRECTIONAL (grid beats setup + * on every discriminating record); the posed oracle quantifies the coupling end to end. + * + * Skips gracefully when the Model A corpus pair is absent. + */ +class BlendDeltaFrameProbeTest { + private val modelACmo3: File? = + System.getProperty("cmo3.probe")?.split(',')?.map(::File) + ?.firstOrNull { it.isFile && it.name.startsWith("modelA") } + private val modelAMoc3: File? = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + ?.walkTopDown()?.firstOrNull { it.isFile && it.name == "modelA.moc3" } + + @Test + fun storedMeshDeltasIdentifyTheirReferenceFrame() { + val cmo3File = modelACmo3 + val moc3File = modelAMoc3 + if (cmo3File == null || moc3File == null) { + println("Model A corpus pair not present; skipping delta-frame probe") + return + } + val root = Cmo3.read(cmo3File).root as? CModelSource ?: error("root is not a CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + val model = MocCodec.read(moc3File.readBytes()) + val document = Moc3.decode(model) + val pixelsPerUnit = model.canvasInfo?.pixelsPerUnit ?: error("no canvas info") + val positionValues = model.sections.floatArray(Section.KEYFORM_POSITION_VALUES) + val meshPositionIndex = model.sections.intArray(Section.KEYFORM_POSITION_INDEX) + val defaultByParameter = puppet.parameters.associate { it.id to it.default } + + var discriminating = 0 + var setupWins = 0 + var gridWins = 0 + var coinciding = 0 + var worstGridError = 0f + + for (record in document.blendShapes) { + if (record.target != BlendShapeTarget.ART_MESH) { + continue + } + val meshId = document.artMeshes[record.targetIndex].id + val parameterId = document.parameters[record.parameterIndex].id + val drawable = puppet.drawables.firstOrNull { it.id.raw == meshId } ?: continue + val binding = drawable.blendShapes.firstOrNull { it.parameterId.raw == parameterId } ?: continue + val base = drawable.mesh?.positions ?: continue + + // The grid form at the DEFAULT pose, multilinearly interpolated (null when ungridded). + val gridAtDefault = + drawable.geometryGrid?.let { grid -> + gridCorners(grid) { queried -> defaultByParameter[queried] ?: 0f } + ?.let { corners -> blendLocalFromCorners(grid, base, corners) } + } + + for (keyIndex in binding.keys.indices) { + if (keyIndex == binding.neutralIndex) { + continue + } + val authoredDeltas = (binding.forms[keyIndex])?.positionDeltas ?: continue + val stored = meshPositionIndex[record.recordBase + keyIndex] + + var setupError = 0f + var gridError = 0f + var hypothesisGap = 0f + for (componentIndex in authoredDeltas.indices) { + // Canvas -> model: divide by ppu; Y components (odd indices) flip sign. + val sign = if (componentIndex % 2 == 1) -1f else 1f + val setupDelta = sign * authoredDeltas[componentIndex] / pixelsPerUnit + val gridReference = + gridAtDefault?.let { it[componentIndex] - base[componentIndex] } ?: 0f + val gridDelta = sign * (authoredDeltas[componentIndex] - gridReference) / pixelsPerUnit + val storedValue = positionValues[stored + componentIndex] + setupError = maxOf(setupError, abs(storedValue - setupDelta)) + gridError = maxOf(gridError, abs(storedValue - gridDelta)) + hypothesisGap = maxOf(hypothesisGap, abs(setupDelta - gridDelta)) + } + + val tolerance = 2e-3f + if (hypothesisGap <= tolerance) { + coinciding++ + } else { + discriminating++ + worstGridError = maxOf(worstGridError, gridError) + if (setupError < gridError) { + setupWins++ + } + if (gridError < setupError) { + gridWins++ + } + println( + "[probe] $meshId/$parameterId key=${binding.keys[keyIndex]} " + + "setupErr=$setupError gridErr=$gridError gap=$hypothesisGap", + ) + // Diagnostic: the reference frame the FILE implies (authored - stored, canvas + // units) vs the grid-at-default hypothesis, at the worst-residual component. + var worstComponent = 0 + var worstResidual = 0f + for (componentIndex in authoredDeltas.indices) { + val sign = if (componentIndex % 2 == 1) -1f else 1f + val impliedReference = + authoredDeltas[componentIndex] - sign * positionValues[stored + componentIndex] * pixelsPerUnit + val gridReference = gridAtDefault?.let { it[componentIndex] - base[componentIndex] } ?: 0f + val residual = abs(impliedReference - gridReference) + if (residual > worstResidual) { + worstResidual = residual + worstComponent = componentIndex + } + } + val sign = if (worstComponent % 2 == 1) -1f else 1f + val impliedReference = + authoredDeltas[worstComponent] - sign * positionValues[stored + worstComponent] * pixelsPerUnit + val gridReference = gridAtDefault?.let { it[worstComponent] - base[worstComponent] } ?: 0f + println( + "[probe] worst comp=$worstComponent (${if (worstComponent % 2 == 0) "x" else "y"}) " + + "authoredDelta=${authoredDeltas[worstComponent]} impliedRef=$impliedReference " + + "gridRef=$gridReference residualPx=$worstResidual", + ) + } + } + } + println( + "[probe] E5: discriminating=$discriminating (setup=$setupWins grid=$gridWins) " + + "coinciding=$coinciding worstGridErr=$worstGridError", + ) + assertTrue(discriminating + coinciding > 0, "Model A should yield joinable mesh records") + if (discriminating > 0) { + assertTrue( + gridWins == discriminating, + "grid-at-default should beat the setup frame on every discriminating record " + + "(setup=$setupWins grid=$gridWins)", + ) + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendShapeChannelOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendShapeChannelOracleTest.kt new file mode 100644 index 0000000..c5efda7 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendShapeChannelOracleTest.kt @@ -0,0 +1,166 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.model.BlendShape +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.Rgb +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.ParameterId +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Posed differential validation of blend-shape CHANNEL deltas, opacity and multiply/screen color. + * + * A blend-shape record carries a delta row per key for every channel its object owns, not only for + * geometry. [BlendShapeOracleTest] compares vertex-position hashes and so cannot see these at all; + * this gate poses the driving parameter at the key that actually carries a non-zero channel delta and + * compares the runtime's exposed per-drawable opacity and colours. + * + * Poses are DERIVED like the deformer-channel gate's: the test reads the format layer for records + * whose keyforms carry a non-zero channel delta and sweeps only those parameters, so a re-authored rig + * keeps being covered and a rig with no channel deltas costs nothing. A record's color delta rows are + * ADDITIVE, so their identity is zero rather than Cubism's (1,1,1) multiply / (0,0,0) screen - a row of + * all zeros contributes nothing and is not worth a pose. + * + * Gated on `relive.dumpModel` + `relive.coreLib` + `moc3.samples`; skips when any is absent. + */ +class BlendShapeChannelOracleTest { + /** Caps the poses per model so a densely-keyed rig cannot turn this into a multi-minute run. */ + private val maximumPosesPerModel = 12 + + /** + * Whether [color] carries any additive contribution (absent or all-zero rows contribute nothing). + * + * @param Rgb? color The delta row. + * @return Boolean True when the row would change the result. + */ + private fun isNonZero(color: Rgb?): Boolean = + color != null && (color.r != 0f || color.g != 0f || color.b != 0f) + + /** + * Whether [keyform] carries a non-zero opacity or color delta. + * + * @param BlendShapeKeyform keyform One key's delta payload. + * @return Boolean True when a channel would move. + */ + private fun carriesChannelDelta(keyform: BlendShapeKeyform): Boolean = + when (keyform) { + is BlendShapeKeyform.Mesh -> + keyform.form.opacity != 0f || isNonZero(keyform.form.multiplyColor) || isNonZero(keyform.form.screenColor) + is BlendShapeKeyform.Warp -> + keyform.form.opacity != 0f || isNonZero(keyform.form.multiplyColor) || isNonZero(keyform.form.screenColor) + is BlendShapeKeyform.Rotation -> + keyform.form.opacity != 0f || isNonZero(keyform.form.multiplyColor) || isNonZero(keyform.form.screenColor) + is BlendShapeKeyform.Part -> false + } + + /** + * The poses that activate each record carrying a channel delta: its driving parameter set to the + * key position of the key whose row is non-zero, everything else left at its default. + * + * @param MocDocument document The decoded model. + * @return List> One pose per (record, interesting key). + */ + private fun channelDeltaPoses(document: MocDocument): List> { + val poses = LinkedHashSet>() + for (record: BlendShape in document.blendShapes) { + val parameterId = document.parameters.getOrNull(record.parameterIndex)?.id ?: continue + for (keyIndex in record.keyforms.indices) { + if (keyIndex == record.neutralKeyIndex || !carriesChannelDelta(record.keyforms[keyIndex])) { + continue + } + val keyPosition = record.keyPositions.getOrNull(keyIndex) ?: continue + poses.add(mapOf(parameterId to keyPosition)) + } + } + return poses.take(maximumPosesPerModel) + } + + @Test + fun blendShapeChannelDeltasMatchTheOracle() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val samples = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + // work/ holds our own bake outputs - same model, different name, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samples.isNotEmpty()) + + var comparedDrawableStates = 0 + var posedModels = 0 + val mismatches = ArrayList() + + for (mocFile in samples) { + val mocDocument = runCatching { Moc3.read(mocFile.readBytes()) }.getOrNull() ?: continue + val poses = channelDeltaPoses(mocDocument) + if (poses.isEmpty()) { + continue + } + posedModels++ + // The canvas-space rebase is the app's real ingest path and the channels compared here are + // rebase-invariant, so running the rebased model keeps the gate on the rendered path. + val puppet = org.umamo.render.restMeshesToCanvasSpace(Moc3Import.fromMocDocument(mocDocument, null)) + println("[oracle] ${mocFile.name}: ${poses.size} blend-shape channel-delta poses") + + for (pose in poses) { + val dump = runOracleDump(dumpModel, coreLib, mocFile, pose) + val parameterValues = pose.entries.associate { ParameterId(it.key) to it.value } + val inputs = preparePose(puppet, parameterValues) + for (drawableInputs in inputs.drawables) { + val oracleEntry = dump.entries[drawableInputs.drawableId.raw] ?: continue + if (oracleNeverEvaluated(oracleEntry)) { + continue + } + comparedDrawableStates++ + val label = "${mocFile.name} pose=$pose ${drawableInputs.drawableId.raw}" + checkChannel(mismatches, label, "op", oracleEntry.opacity, drawableInputs.opacity) + if (oracleEntry.multiplyRgba.size == 4 && oracleEntry.screenRgba.size == 4) { + checkChannel(mismatches, label, "mulR", oracleEntry.multiplyRgba[0], drawableInputs.multiplyColor.red) + checkChannel(mismatches, label, "mulG", oracleEntry.multiplyRgba[1], drawableInputs.multiplyColor.green) + checkChannel(mismatches, label, "mulB", oracleEntry.multiplyRgba[2], drawableInputs.multiplyColor.blue) + checkChannel(mismatches, label, "scrR", oracleEntry.screenRgba[0], drawableInputs.screenColor.red) + checkChannel(mismatches, label, "scrG", oracleEntry.screenRgba[1], drawableInputs.screenColor.green) + checkChannel(mismatches, label, "scrB", oracleEntry.screenRgba[2], drawableInputs.screenColor.blue) + } + } + } + } + + // A run that posed nothing would pass while proving nothing, which is the failure mode every + // corpus gate here is prone to. modelC carries non-zero color delta rows, so the corpus reaches this. + assertTrue(posedModels > 0, "no corpus model carried a blend-shape channel delta to pose") + println( + "[oracle] blend-shape channels: $comparedDrawableStates drawable states across $posedModels models, " + + "${mismatches.size} mismatches", + ) + assertTrue( + mismatches.isEmpty(), + "blend-shape channel deltas disagree with the oracle:\n" + mismatches.take(20).joinToString("\n"), + ) + } + + /** + * Records a channel mismatch when ours differs from the oracle beyond tolerance. + * + * @param ArrayList mismatches The shared collector. + * @param String label The model/pose/drawable identifier. + * @param String channel Which channel is being compared. + * @param Float oracle The oracle's value. + * @param Float ours Our evaluated value. + */ + private fun checkChannel(mismatches: ArrayList, label: String, channel: String, oracle: Float, ours: Float) { + if (!oracleCloseEnough(oracle.toDouble(), ours.toDouble())) { + mismatches.add("$label $channel: oracle=$oracle ours=$ours") + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendShapeOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendShapeOracleTest.kt new file mode 100644 index 0000000..0171b10 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/BlendShapeOracleTest.kt @@ -0,0 +1,201 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Posed differential validation of the blend-shape eval against the Umamo C++ runtime: for + * each blend-shape corpus pair (Model A/Model B/Model C), evaluate a matrix of poses that exercise the + * additive pass - at-key, midpoint, beyond-range saturation, combined normal+blend, and the + * min-combined limit curves - and compare per-drawable position hashes against `dump_model`. + * + * Match floors are pinned from the first measured run (the DeformationOracleTest pattern): the + * same nested-warp bounded-ULP residual class shaves a few drawables, plus the mesh-under- + * morphed-warp coupling documented in BlendDeltaFrameProbeTest. Gate against the Umamo C++ Runtime + * only; divergences against the reference implementations are recorded in MOC3.md, never gated + * (reference trust order). + * + * Gated on `relive.dumpModel` + `relive.coreLib` + the corpus pair properties; skips when any is absent. + */ +class BlendShapeOracleTest { + private data class OraclePair( + val name: String, + val cmo3: File, + val moc3: File, + val poses: List>, + /** Minimum matched drawables per pose, pinned from the first measured run. */ + val matchFloor: Int, + /** Same floor for the MOC3-imported puppet leg, pinned from its first measured run. */ + val moc3ImportMatchFloor: Int, + ) + + @Test + fun posedBlendShapesMatchOracle() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val pairs = resolvePairs() + Assume.assumeTrue("[oracle] no blend-shape corpus pairs resolvable", pairs.isNotEmpty()) + + var totalCompared = 0 + var totalMatched = 0 + for (pair in pairs) { + val root = Cmo3.read(pair.cmo3).root as? CModelSource ?: error("${pair.name}: root is not a CModelSource") + val puppet = Cmo3Import.fromModelSource(root) + // The MOC3-import leg: the SAME model imported from the baked moc3 itself (the editor's + // document-loader path), so the blend mapping's reference re-addition and space + // conversion are gated end-to-end. Same-file comparison, so any cmo3-vs-moc3 + // authoring-state skew is out of the picture by construction. + val moc3Puppet = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(Moc3.read(pair.moc3.readBytes()), null)) + for (pose in pair.poses) { + val (compared, matched, worst) = comparePose(puppet, dumpModel, coreLib, pair.moc3, pose) + totalCompared += compared + totalMatched += matched + println("[oracle] ${pair.name} src=cmo3 pose=$pose matched=$matched/$compared worstRelErr=$worst") + // Every blend pose matches at or above its model's DEFAULT-POSE (blend-free) baseline + // Model A 171/198 default vs >= 170 posed (residuals <= 7.7e-5, + // the nested-warp ULP class), Model B 48/59 vs >= 48, Model C 213/260 default vs 215 + // posed. Model C's remaining residuals (<= 6.0e-4) are authored-at-default morphs + // applying correctly under the neutral-at-value-0 reading, not the cmo3/moc3 + // "authoring-state skew" that a neutral-at-default reading would misattribute them to. + // Regression = any pose below the pinned floor. + assertTrue( + matched >= pair.matchFloor, + "${pair.name} pose=$pose regressed: matched=$matched/$compared (< ${pair.matchFloor})", + ) + val (moc3Compared, moc3Matched, moc3Worst) = comparePose(moc3Puppet, dumpModel, coreLib, pair.moc3, pose) + totalCompared += moc3Compared + totalMatched += moc3Matched + println("[oracle] ${pair.name} src=moc3 pose=$pose matched=$moc3Matched/$moc3Compared worstRelErr=$moc3Worst") + assertTrue( + moc3Matched >= pair.moc3ImportMatchFloor, + "${pair.name} src=moc3 pose=$pose regressed: matched=$moc3Matched/$moc3Compared (< ${pair.moc3ImportMatchFloor})", + ) + } + } + println("[oracle] blend-shape posed total: $totalMatched/$totalCompared") + assertTrue(totalCompared > 0, "expected comparable drawables") + } + + /** + * Evaluates [puppet] at [pose] and compares against the Umamo C++ Runtime's dump of [moc3] at + * the same pose. + * + * @return Triple(compared, matched, worst relative error) for the pose. + */ + private fun comparePose( + puppet: PuppetModel, + dumpModel: File, + coreLib: File, + moc3: File, + pose: Map, + ): Triple { + val geometry = + CpuDeformationEvaluator().evaluate(puppet, pose.mapKeys { ParameterId(it.key) }) + val dump = runOracleDump(dumpModel, coreLib, moc3, pose) + var compared = 0 + var matched = 0 + var worst = 0.0 + for (drawable in puppet.drawables) { + val entry = dump.entries[drawable.id.raw] ?: continue + val world = geometry.worldPositions[drawable.id] ?: continue + compared++ + // Same transform as the default-pose gate: (x-ox)/ppu, (y+oy)/ppu (umamo pre-flips Y). + val hash = oracleTransformedHash(world, dump.originX, -dump.originY, dump.pixelsPerUnit) + if (oracleCloseEnough(hash, entry.vposH)) { + matched++ + } else { + val relativeError = Math.abs(hash - entry.vposH) / maxOf(1.0, Math.abs(entry.vposH)) + worst = maxOf(worst, relativeError) + } + } + return Triple(compared, matched, worst) + } + + /** The blend-shape corpus pairs with their pose matrices, filtered to what exists locally. */ + private fun resolvePairs(): List { + val cmo3s = + System.getProperty("cmo3.probe")?.split(',')?.map(::File)?.filter { it.isFile }.orEmpty() + val moc3Root = System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + + fun moc3(name: String): File? = moc3Root?.walkTopDown()?.firstOrNull { it.isFile && it.name == name } + + fun cmo3(prefix: String): File? = cmo3s.firstOrNull { it.name.startsWith(prefix) } + + val pairs = ArrayList() + val modelA = cmo3("modelA") + val modelAMoc = moc3("modelA.moc3") + if (modelA != null && modelAMoc != null) { + pairs.add( + OraclePair( + "Model A", + modelA, + modelAMoc, + listOf( + // Default pose first: a blend-free baseline separating pre-existing + // residuals (nested-warp ULP class, model-state skew) from blend errors. + emptyMap(), + mapOf("ParamEyeSize" to -1f), + mapOf("ParamEyeSize" to -0.5f), + // Beyond-range: saturates to the end key (confirmed via the Umamo C++ Runtime). + mapOf("ParamEyeSize" to -1.5f), + mapOf("ParamEyeSize" to -1f, "ParamAngleX" to 20f), + // The warp-coupling case documented in BlendDeltaFrameProbeTest. + mapOf("ParamBodyAngleX2" to 10f), + mapOf("ParamBrowLY" to -1f), + ), + matchFloor = 170, + moc3ImportMatchFloor = 165, + ), + ) + } + val modelB = cmo3("modelB") + val modelBMoc = moc3("modelB.moc3") + if (modelB != null && modelBMoc != null) { + pairs.add( + OraclePair( + "Model B", + modelB, + modelBMoc, + listOf( + emptyMap(), + mapOf("ParamA" to 1f, "ParamMouthOpenY" to 1f), + // The limit ramp: contribution scaled to 0.5x / suppressed to zero. + mapOf("ParamA" to 1f, "ParamMouthOpenY" to 0.5f), + mapOf("ParamA" to 1f, "ParamMouthOpenY" to 0f), + ), + matchFloor = 48, + moc3ImportMatchFloor = 44, + ), + ) + } + val modelC = cmo3("modelC") + val modelCMoc = moc3("modelC.moc3") + if (modelC != null && modelCMoc != null) { + pairs.add( + OraclePair( + "Model C", + modelC, + modelCMoc, + listOf( + emptyMap(), + // Min-combination: multiplier = min over the inverse ramps, not the product. + mapOf("ParamA" to 1f, "ParamI" to 0.6f, "ParamU" to 0.8f), + ), + matchFloor = 213, + moc3ImportMatchFloor = 212, + ), + ) + } + return pairs + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Cmo3ToMoc3OracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Cmo3ToMoc3OracleTest.kt new file mode 100644 index 0000000..6c42030 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Cmo3ToMoc3OracleTest.kt @@ -0,0 +1,155 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.moc3.export.Moc3Export +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * A CMO3 exported to MOC3 EVALUATES like the editor's own bake of the same model. + * + * The end-to-end statement of the whole export: take the source project, lower it ourselves, and let + * the official runtime pose both files. Nothing of ours is in the loop at evaluation time, so a + * disagreement is about the file we wrote, not about our math. + * + * Two tiers, because the two files are not obliged to be byte-alike: + * + * - The exported file must LOAD, and every drawable the bake has must be present and evaluated. That + * is equality, and `runOracleDump`'s non-zero-exit check gates the loading half for free. + * - GEOMETRY is a measured floor, not an equality. The editor's bake is its own derivation from the + * same source, and the two need only agree to within the authoring skew - so the test pins how many + * drawables land within tolerance and fails when that number drops, which is what a lowering + * regression looks like from here. + * + * Gated on `relive.dumpModel` + `relive.coreLib` + `cmo3.probe` + `moc3.samples`. + */ +class Cmo3ToMoc3OracleTest { + /** + * The corpus twins, joined by base name. + * + * @return List Each (base name, cmo3, moc3) triple. + */ + private fun twins(): List> { + val cmo3Files = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map { path -> File(path.trim()) } + ?.filter { file -> file.isFile } + ?.associateBy { file -> file.nameWithoutExtension } + .orEmpty() + val moc3Files = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { directory -> directory.isDirectory } + ?.walkTopDown() + ?.filter { file -> file.isFile && file.extension == "moc3" && file.parentFile?.name != "work" } + ?.associateBy { file -> file.nameWithoutExtension } + .orEmpty() + return cmo3Files.keys + .intersect(moc3Files.keys) + .sorted() + .map { name -> Triple(name, cmo3Files.getValue(name), moc3Files.getValue(name)) } + } + + @Test + fun exportedProjectsEvaluateLikeTheEditorsBake() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val twins = twins() + Assume.assumeTrue("[oracle] no cmo3/moc3 twins", twins.isNotEmpty()) + + val outputDir = File("build/cmo3-to-moc3").apply { mkdirs() } + val failures = ArrayList() + var comparedModels = 0 + var comparedDrawables = 0 + var geometryMatches = 0 + val perModel = ArrayList() + for ((name, cmo3File, moc3File) in twins) { + val baked = Moc3.decode(MocCodec.read(moc3File.readBytes())) + val root = Cmo3.read(cmo3File).root as? CModelSource ?: continue + val puppet = Cmo3Import.fromModelSource(root) + val (bytes, _) = + runCatching { Moc3Export.write(puppet, baked.version) }.getOrElse { failure -> + failures.add("$name: the CMO3 would not lower to a moc ($failure)") + continue + } + val exportedFile = File(outputDir, "$name.moc3").apply { writeBytes(bytes) } + + val bakedDump = runOracleDump(dumpModel, coreLib, moc3File, emptyMap()) + val ourDump = runOracleDump(dumpModel, coreLib, exportedFile, emptyMap()) + // A twin pair is only an oracle when both files are the same revision of the model; the + // structural gate (Cmo3ToMoc3CrossFormatTest) names the one corpus pair that is not. + val shared = bakedDump.entries.keys.intersect(ourDump.entries.keys) + if (shared.size < bakedDump.entries.size * 9 / 10) { + continue + } + comparedModels++ + var modelCompared = 0 + var modelMatches = 0 + + for (drawableId in shared) { + val expected = bakedDump.entries.getValue(drawableId) + val actual = ourDump.entries.getValue(drawableId) + if (oracleNeverEvaluated(expected)) { + continue + } + comparedDrawables++ + if (expected.vtx != actual.vtx) { + failures.add("$name $drawableId: ${expected.vtx} vertices in the bake, ${actual.vtx} in ours") + continue + } + // Opacity is a pose result, not a derived coordinate - the two files must agree exactly on + // what the default pose makes this drawable. + if (!oracleCloseEnough(expected.opacity.toDouble(), actual.opacity.toDouble())) { + failures.add("$name $drawableId op: ${expected.opacity} vs ${actual.opacity}") + } + modelCompared++ + if (oracleCloseEnough(expected.vposH, actual.vposH)) { + geometryMatches++ + modelMatches++ + } + } + if (modelCompared > 0 && modelMatches < modelCompared) { + // Printed per model so the residue is legible rather than a single percentage: it sits at + // roughly one drawable in ten across EVERY real model, which is what says it is authoring + // skew and not one model's quirk. + perModel.add("$name $modelMatches/$modelCompared") + } + } + assertTrue(comparedModels > 0, "no twin pair could be compared") + val geometryRatio = if (comparedDrawables == 0) 0.0 else geometryMatches.toDouble() / comparedDrawables + println( + "[cross-oracle] $comparedModels twins, $comparedDrawables drawables compared, " + + "$geometryMatches within the oracle's geometry tolerance " + + "(${(geometryRatio * 100).toInt()}%), ${failures.size} failures" + + (if (perModel.isEmpty()) "" else "; below par: $perModel"), + ) + assertTrue(failures.isEmpty(), "exported projects do not evaluate like the bake:\n" + failures.take(15).joinToString("\n")) + assertTrue( + geometryRatio >= GEOMETRY_FLOOR, + "only ${(geometryRatio * 100).toInt()}% of drawables land on the bake's geometry, floor is " + + "${(GEOMETRY_FLOOR * 100).toInt()}% - a lowering regression looks exactly like this", + ) + } + + private companion object { + /** + * The floor under the share of drawables whose evaluated geometry matches the editor's bake. + * + * A FLOOR rather than 100%: the bake is the editor's own derivation from the same project, so the + * two agree only to within its authoring skew - measured at 89% over 1046 drawables of 21 twins, + * spread evenly across models rather than pooled in one. Raise this when the number improves; a + * drop is a regression in the lowering, which is the only thing that can move it. + * + * For scale: writing the project's own pixels-per-unit instead of a bake scale put this at ZERO, + * and every other gate stayed green through it. That is the class of defect the floor catches. + */ + const val GEOMETRY_FLOOR: Double = 0.85 + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/CompactionEvalEquivalenceTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/CompactionEvalEquivalenceTest.kt new file mode 100644 index 0000000..511723a --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/CompactionEvalEquivalenceTest.kt @@ -0,0 +1,140 @@ +package org.umamo.render.eval + +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The compaction gate that needs NO external oracle: import every corpus model twice - once with the + * post-import channel compaction on, once off - and assert the two evaluate identically over a pose sweep. + * + * This is the cheap check that runs wherever the corpus is present, and it is the one that would actually + * catch a compaction fault: the C-core oracles need `relive.dumpModel`/`relive.coreLib` and shell out to an + * external process per pose, so their sweeps stay capped, while this needs nothing but the corpus and + * compares Umamo against ITSELF across many poses, with the un-compacted import as the reference. A + * dropped key that mattered, or a constant lifted onto the wrong static, shows up here. + * + * The comparison is to a tolerance, and the reason is worth stating: where a track collapses, compaction + * is the MORE accurate side. The reference path evaluates a constant channel as `Σ wᵢ·x` over up to 16 + * corners, which lands an ULP off (a corpus draw order of 900 sums to 899.99994); the compacted path reads + * the authored 900 from a field. Asserting equality would therefore be asserting that compaction + * reproduces the old arithmetic's noise, which is backwards. + * + * The tolerance is set far below any granularity that could change behaviour - draw order only orders + * drawables a whole unit apart, and opacity is displayed to two decimals - so it admits the ULP while + * still failing on a dropped key that mattered or a constant lifted onto the wrong static. + */ +class CompactionEvalEquivalenceTest { + private companion object { + /** Poses swept per parameter, as fractions across its min..max range. */ + val SWEEP_FRACTIONS = listOf(0f, 0.25f, 0.5f, 0.75f, 1f) + + /** Geometry is never compacted, so it should be bit-identical; this absorbs nothing in practice. */ + const val GEOMETRY_TOLERANCE = 1e-6f + + /** Admits the constant-fold ULP (see the class note) while failing on any real channel change. */ + const val SCALAR_TOLERANCE = 1e-3f + } + + private fun probeFiles(): List = + System.getProperty("cmo3.probe") + ?.split(',') + ?.map(::File) + ?.filter { it.isFile } + ?: emptyList() + + private fun importCmo3(file: File, compactChannels: Boolean): PuppetModel { + val root = Cmo3.read(file).root as? CModelSource ?: error("${file.name}: root is not a CModelSource") + return Cmo3Import.fromModelSource(root, compactChannels = compactChannels) + } + + /** + * Poses that sweep each parameter across its range one at a time, plus the all-default pose. + * + * One parameter at a time rather than a combinatorial sweep: the grids are multilinear, so a fault on + * one axis shows up while the others sit at their defaults, and the corpus models carry enough + * parameters that a product sweep would not finish. + */ + private fun sweepPoses(model: PuppetModel): List> { + val defaults = model.parameters.associate { parameter -> parameter.id to parameter.default } + val poses = mutableListOf(defaults) + for (parameter in model.parameters) { + for (fraction in SWEEP_FRACTIONS) { + poses.add(defaults + (parameter.id to (parameter.min + (parameter.max - parameter.min) * fraction))) + } + } + return poses + } + + @Test + fun compactionDoesNotChangeEvaluation() { + val files = probeFiles() + if (files.isEmpty()) { + println("cmo3.probe not present; skipping compaction equivalence") + return + } + val evaluator = CpuDeformationEvaluator() + var comparedPoses = 0 + var totalTracksBefore = 0 + var totalTracksAfter = 0 + for (file in files) { + val reference = importCmo3(file, compactChannels = false) + val compacted = importCmo3(file, compactChannels = true) + totalTracksBefore += reference.channelTrackCount() + totalTracksAfter += compacted.channelTrackCount() + + for (pose in sweepPoses(reference)) { + val referenceGeometry = evaluator.evaluate(reference, pose) + val compactedGeometry = evaluator.evaluate(compacted, pose) + assertEquals( + referenceGeometry.worldPositions.keys, + compactedGeometry.worldPositions.keys, + "${file.name}: the same drawables must be visible", + ) + for ((drawableId, referencePositions) in referenceGeometry.worldPositions) { + val compactedPositions = compactedGeometry.worldPositions.getValue(drawableId) + assertEquals(referencePositions.size, compactedPositions.size, "${file.name}: ${drawableId.raw} vertex count") + for (coordIndex in referencePositions.indices) { + assertTrue( + abs(referencePositions[coordIndex] - compactedPositions[coordIndex]) <= GEOMETRY_TOLERANCE, + "${file.name}: ${drawableId.raw}[$coordIndex] geometry moved under compaction", + ) + } + val referenceDrawOrder = referenceGeometry.drawOrder.getValue(drawableId) + val compactedDrawOrder = compactedGeometry.drawOrder.getValue(drawableId) + assertTrue( + abs(referenceDrawOrder - compactedDrawOrder) <= SCALAR_TOLERANCE, + "${file.name}: ${drawableId.raw} draw order $referenceDrawOrder -> $compactedDrawOrder", + ) + val referenceOpacity = referenceGeometry.opacity.getValue(drawableId) + val compactedOpacity = compactedGeometry.opacity.getValue(drawableId) + assertTrue( + abs(referenceOpacity - compactedOpacity) <= SCALAR_TOLERANCE, + "${file.name}: ${drawableId.raw} opacity $referenceOpacity -> $compactedOpacity", + ) + } + comparedPoses++ + } + } + println("[Umamo][compaction] $comparedPoses poses over ${files.size} models; channel tracks $totalTracksBefore -> $totalTracksAfter") + assertTrue(comparedPoses > 0, "compared at least one pose") + assertTrue( + totalTracksAfter <= totalTracksBefore, + "compaction must never ADD tracks (before=$totalTracksBefore after=$totalTracksAfter)", + ) + } + + /** Every channel track carried by every owner in the model - the thing compaction is meant to shrink. */ + private fun PuppetModel.channelTrackCount(): Int = + drawables.sumOf { it.channelGrids.gridsByChannel.size } + + deformers.sumOf { it.channelGrids.gridsByChannel.size } + + parts.sumOf { it.channelGrids.gridsByChannel.size } + + glues.sumOf { it.channelGrids.gridsByChannel.size } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/CompositeOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/CompositeOracleTest.kt new file mode 100644 index 0000000..7996a49 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/CompositeOracleTest.kt @@ -0,0 +1,131 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Posed differential validation of the offscreen channel eval against the Umamo C++ runtime: for + * each offscreen corpus model, evaluate poses that exercise the keyformed composite channels + * (opacity at-key, midpoint, and the arm draw-order crossfades; authored multiply/screen colors) + * and compare [PoseDeformInputs.partCompositeStates] against `dump_model`'s per-update + * interpolated offscreen arrays (`O` lines - probed pose-DYNAMIC: the oracle re-evaluates them + * each csmUpdateModel). The oracle's colors are RGBA with alpha pinned 1.0 (the runtime model + * carries RGB only); the mask joins are compared statically. + * + * Gated on `relive.dumpModel` + `relive.coreLib` + `moc3.samples`; skips when any is absent. + */ +class CompositeOracleTest { + private data class CompositeCase(val fileName: String, val poses: List>) + + private val cases = + listOf( + // Model A: 24 organic offscreens - the Overall hologram fade (1.0 -> 0.85) and the arm + // draw-order opacity crossfades, at keys and midpoints. + CompositeCase( + "modelA.moc3", + listOf( + emptyMap(), + mapOf("ParamHologram" to 1f), + mapOf("ParamHologram" to 0.5f), + mapOf("ParamHandRDrawOrder" to 1f), + mapOf("ParamHandRDrawOrder" to 0.5f, "ParamHandLDrawOrder" to 0.5f), + ), + ), + // The authored non-identity multiply/screen colors (#677CD1 / #95C068). + CompositeCase("MultiplyScreenColors.moc3", listOf(emptyMap())), + // Offscreen clip list (part expanded to drawables) + invert flag carrier. + CompositeCase("ModelWithOffscreenPartClipping.moc3", listOf(emptyMap())), + ) + + @Test + fun compositeChannelsMatchOracle() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val samplesByName = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" } + ?.associateBy { it.name } + ?: emptyMap() + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samplesByName.isNotEmpty()) + + var comparedOffscreens = 0 + val mismatches = ArrayList() + for (compositeCase in cases) { + val mocFile = samplesByName[compositeCase.fileName] + if (mocFile == null) { + println("[oracle] ${compositeCase.fileName} not in corpus; skipping") + continue + } + val mocDocument = Moc3.read(mocFile.readBytes()) + val puppet = Moc3Import.fromMocDocument(mocDocument, null) + // Part/drawable FILE order (oracle indices) - puppet.parts preserves it, puppet.drawables + // does not (panel reorder), so drawable joins go through the decoded artMesh list. + val drawableIdByFileIndex = mocDocument.artMeshes.map { DrawableId(it.id) } + val knownParameters = puppet.parameters.mapTo(HashSet()) { it.id.raw } + for (pose in compositeCase.poses) { + if (!pose.keys.all { it in knownParameters }) { + println("[oracle] ${compositeCase.fileName} pose=$pose names an unknown parameter; skipping") + continue + } + val dump = runOracleDump(dumpModel, coreLib, mocFile, pose) + assertEquals( + puppet.parts.count { it.activeComposite != null }, + dump.offscreens.size, + "${compositeCase.fileName}: offscreen count", + ) + val inputs = preparePose(puppet, pose.entries.associate { ParameterId(it.key) to it.value }) + for (oracleOffscreen in dump.offscreens) { + val part = puppet.parts[oracleOffscreen.ownerPartIndex] + val composite = assertNotNull(part.activeComposite, "${compositeCase.fileName}: ${part.id.raw} owns an offscreen") + val state = + assertNotNull( + inputs.partCompositeStates[part.id], + "${compositeCase.fileName}: ${part.id.raw} carries a pose state", + ) + comparedOffscreens++ + val label = "${compositeCase.fileName} pose=$pose ${part.id.raw}" + // The dynamic channels: opacity + multiply/screen RGB at the oracle tolerance. + checkChannel(mismatches, label, "op", oracleOffscreen.opacity, state.opacity) + checkChannel(mismatches, label, "mulR", oracleOffscreen.multiplyRgba[0], state.multiplyColor.red) + checkChannel(mismatches, label, "mulG", oracleOffscreen.multiplyRgba[1], state.multiplyColor.green) + checkChannel(mismatches, label, "mulB", oracleOffscreen.multiplyRgba[2], state.multiplyColor.blue) + checkChannel(mismatches, label, "scrR", oracleOffscreen.screenRgba[0], state.screenColor.red) + checkChannel(mismatches, label, "scrG", oracleOffscreen.screenRgba[1], state.screenColor.green) + checkChannel(mismatches, label, "scrB", oracleOffscreen.screenRgba[2], state.screenColor.blue) + // The RGB-only runtime model rests on alpha staying 1.0 - pin the assumption. + assertEquals(1f, oracleOffscreen.multiplyRgba[3], "$label multiply alpha") + assertEquals(1f, oracleOffscreen.screenRgba[3], "$label screen alpha") + // Static joins: the offscreen mask list resolves to the same drawables. + val oracleMaskIds = oracleOffscreen.maskIndices.mapNotNull { drawableIdByFileIndex.getOrNull(it) }.toSet() + assertEquals(oracleMaskIds, composite.maskedBy.toSet(), "$label mask list") + } + println("[oracle] ${compositeCase.fileName} pose=$pose offscreens=${dump.offscreens.size} OK") + } + } + Assume.assumeTrue("[oracle] no offscreen corpus models resolvable", comparedOffscreens > 0) + // The channels are plain multilinear blends of stored floats on both sides - exact within + // 1e-5, no pinned floor needed; any mismatch is a real regression. + assertTrue( + mismatches.isEmpty(), + "offscreen channel mismatches (${mismatches.size}):\n" + mismatches.joinToString("\n"), + ) + println("[oracle] compared $comparedOffscreens offscreen states, all within tolerance") + } + + private fun checkChannel(mismatches: ArrayList, label: String, channel: String, oracle: Float, ours: Float) { + if (!oracleCloseEnough(oracle.toDouble(), ours.toDouble())) { + mismatches.add("$label $channel: oracle=$oracle ours=$ours") + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/DeformationOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/DeformationOracleTest.kt new file mode 100644 index 0000000..0000496 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/DeformationOracleTest.kt @@ -0,0 +1,187 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Differential validation against the Umamo C++ Runtime oracle: read a `.cmo3` -> PuppetModel, + * evaluate the default pose, and compare per-drawable hashes against + * `dump_model libcore_re.so model.moc3 --update`. + * + * The oracle prints a rolling hash `hp = hp*1.0000001 + coord` over each drawable's interleaved + * positions (`vpos_h`); umamo's output is transformed to model space and re-hashed, matched by id. + * + * Result: 156/174 match to tiny-ULP (157 before the harness rebuild - see the assertion + * note); the other 18 are sub-pixel residuals (<0.6 px/vertex) + * concentrated in deeply-nested warp chains. Ruled out as causes: FMA contraction, rotation sin/cos, + * vertex extrapolation, blend-at-default - and `warpExtrap` was audited bit-for-bit against the oracle. + * The residual grows with nesting depth, which is most consistent with CMO3↔MOC3 source-data + * re-quantization amplified through the chain (umamo evaluates the CMO3, the oracle the exported MOC3), + * i.e. a serialization difference, not a math error. Well within the bounded-ULP fidelity contract. + * + * Gated on the cmo3/moc3 samples + the Umamo C++ Runtime oracle paths (system properties); skips when absent. + */ +class DeformationOracleTest { + private data class OracleEntry(val vtx: Int, val vposH: Double, val vuvH: Double) + + @Test + fun defaultPoseMatchesOracle() { + val cmo3 = requireOracleInput("cmo3.sample") + val moc3 = requireOracleInput("moc3.sample") + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + + val root = Cmo3.read(cmo3).root as? CModelSource ?: error("root is not a CModelSource") + val model = Cmo3Import.fromModelSource(root) + val geometry = CpuDeformationEvaluator().evaluate(model, emptyMap()) + val oracle = runOracle(dumpModel, coreLib, moc3) + println("[oracle] umamo drawables=${model.drawables.size} evaluated=${geometry.worldPositions.size} oracle=${oracle.size}") + + // Confirmed transform: CMO3 canvas/pixel space -> MOC3 normalized model space = (x-ox)/ppu, + // (y+oy)/ppu (origin = canvas center, ppu from the dump header; umamo already applied -Y). + val ppu = 4500f + val originX = 2250f + val originY = 3250f + val deformerById = model.deformers.associateBy { it.id } + var posMatch = 0 + var compared = 0 + val mismatches = StringBuilder() + var shown = 0 + for (drawable in model.drawables) { + val entry = oracle[drawable.id.raw] ?: continue + val world = geometry.worldPositions[drawable.id] ?: continue + compared++ + val hash = transformedHash(world, originX, -originY, ppu, 1f) + if (closeEnough(hash, entry.vposH)) { + posMatch++ + } else if (shown < 20) { + val parentId = drawable.parentDeformerId + val relativeError = abs(hash - entry.vposH) / maxOf(1.0, abs(entry.vposH)) + val rotationAncestor = hasRotationAncestor(deformerById, parentId) + mismatches.append( + " ${drawable.id.raw}: parent=${parentId?.raw} vtx=${entry.vtx} relErr=${ + "%.3g".format( + relativeError, + ) + } rotAncestor=$rotationAncestor\n", + ) + shown++ + } + } + println("[oracle] posMatch=$posMatch / $compared (transform (x-ox)/ppu,(y+oy)/ppu)") + println("[oracle] mismatches (bounded-ULP residuals):\n$mismatches") + // The gate is pinned to 156, not 157: after the oracle harness was rebuilt from csrc (the + // original prebuilt dump_model had no source), all three core builds (fresh -O2, pristine + // _o3, pristine _avx2) reproduce 156 - ArtMesh142 sits at relErr 1.11e-5 against the 1e-5 + // closeEnough knife edge, in the same nested-warp residual class as the other 17. This is + // harness FP drift on a borderline drawable, not an umamo eval change, so the gate is + // pinned to the reproducible baseline. + assertTrue(posMatch >= 156, "geometry regressed: posMatch=$posMatch (<156) — investigate before relaxing") + } + + /** + * The file [property] points at, skipping the test when it is absent. + * + * A JUnit assumption rather than an early return, so an un-runnable oracle reports SKIPPED instead of + * passing green having compared nothing. This one needs the Umamo C++ Runtime as an external oracle, + * so unlike the corpus gates it cannot be defaulted - it stays opt-in by nature. + * + * @param String property The system property naming the input. + * @return File The existing file. + */ + private fun requireOracleInput(property: String): File { + val file = sysFile(property) + Assume.assumeTrue( + "[oracle] absent -D$property (needs -Dcmo3.sample -Dmoc3.sample -Drelive.dumpModel -Drelive.coreLib)", + file != null, + ) + return file!! + } + + private fun sysFile(property: String): File? = System.getProperty(property)?.let(::File)?.takeIf { it.exists() } + + private fun rollingHash(values: FloatArray): Double { + var hp = 0.0 + for (value in values) { + hp = hp * 1.0000001 + value + } + return hp + } + + private fun closeEnough(a: Double, b: Double): Boolean { + val scale = maxOf(1.0, abs(a), abs(b)) + return abs(a - b) <= 1e-5 * scale + } + + private fun transformedHash(world: FloatArray, offsetX: Float, offsetY: Float, scale: Float, signY: Float): Double { + var hp = 0.0 + var index = 0 + while (index < world.size) { + hp = hp * 1.0000001 + (world[index] - offsetX) / scale + hp = hp * 1.0000001 + signY * (world[index + 1] - offsetY) / scale + index += 2 + } + return hp + } + + private fun printRange(id: String, world: FloatArray) { + var minX = Float.MAX_VALUE + var maxX = -Float.MAX_VALUE + var minY = Float.MAX_VALUE + var maxY = -Float.MAX_VALUE + var index = 0 + while (index < world.size) { + minX = minOf(minX, world[index]) + maxX = maxOf(maxX, world[index]) + minY = minOf(minY, world[index + 1]) + maxY = maxOf(maxY, world[index + 1]) + index += 2 + } + println("[oracle] $id raw range x[$minX..$maxX] y[$minY..$maxY] first=${world.take(4).toList()}") + } + + private fun hasRotationAncestor(deformerById: Map, start: DeformerId?): Boolean { + var current = start + var guard = 0 + while (current != null && guard < 10000) { + val deformer = deformerById[current] ?: return false + if (deformer is Deformer.Rotation) { + return true + } + current = deformer.parent + guard++ + } + return false + } + + private fun runOracle(dumpModel: File, coreLib: File, moc3: File): Map { + val command = listOf(dumpModel.absolutePath, coreLib.absolutePath, moc3.absolutePath, "--update") + val process = ProcessBuilder(command).redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().readText() + process.waitFor() + val idRegex = Regex("""id=(\S+)""") + val vtxRegex = Regex("""vtx=(\d+)""") + val vposRegex = Regex("""vpos_h=(\S+)""") + val vuvRegex = Regex("""vuv_h=(\S+)""") + val result = HashMap() + for (line in output.lineSequence()) { + if (!line.startsWith("D ")) { + continue + } + val id = idRegex.find(line)?.groupValues?.get(1) ?: continue + val vtx = vtxRegex.find(line)?.groupValues?.get(1)?.toIntOrNull() ?: continue + val vposH = vposRegex.find(line)?.groupValues?.get(1)?.toDoubleOrNull() ?: continue + val vuvH = vuvRegex.find(line)?.groupValues?.get(1)?.toDoubleOrNull() ?: continue + result[id] = OracleEntry(vtx, vposH, vuvH) + } + return result + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/DeformerChannelOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/DeformerChannelOracleTest.kt new file mode 100644 index 0000000..1a16e2a --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/DeformerChannelOracleTest.kt @@ -0,0 +1,230 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.MocDocument +import org.umamo.format.moc3.model.Deformer +import org.umamo.format.moc3.model.RotationDeformer +import org.umamo.format.moc3.model.WarpDeformer +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.ParameterId +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Posed differential validation of the DEFORMER channel cascade against the Umamo C++ runtime. + * + * A warp or rotation deformer carries its own opacity and multiply/screen color per keyform, and + * the runtime folds those down the deformer chain into every drawable underneath before exposing + * `csmGetDrawableOpacities` / `...MultiplyColors` / `...ScreenColors`. This gate compares that + * exposed per-drawable result against [preparePose]'s, so it covers the whole chain: the drawable's + * own keyform channels and the deformer cascade between them. + * + * Poses are DERIVED, not hand-written: for each model the test reads the format layer to find which + * deformers actually author a non-identity channel, walks those deformers' keyform bindings to the + * parameters that drive them, and sweeps each such parameter across its own key positions plus the + * midpoints between them. Hand-picked poses would silently stop exercising a model whose rig was + * re-authored; derived ones follow it. + * + * The format layer is also why the interesting-deformer search reads [MocDocument] rather than the + * imported [org.umamo.runtime.model.PuppetModel]: searching through the app's own import would only + * prove the cascade agrees with itself, while reading the moc3 source of truth directly keeps the + * gate honest against an independent read of which deformers actually author a channel. + * + * Gated on `relive.dumpModel` + `relive.coreLib` + `moc3.samples`; skips when any is absent. + */ +class DeformerChannelOracleTest { + /** Cubism identity: fully opaque, white multiply, black screen. */ + private val opaque = 1f + private val multiplyIdentity = Triple(1f, 1f, 1f) + private val screenIdentity = Triple(0f, 0f, 0f) + + /** How many midpoints to insert between consecutive key positions on a swept axis. */ + private val midpointsPerSegment = 1 + + /** Caps the poses per model so a densely-keyed rig cannot turn this into a multi-minute run. */ + private val maximumPosesPerModel = 24 + + @Test + fun deformerChannelsCascadeToDrawablesLikeTheOracle() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val samples = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + // work/ holds our own bake outputs - same model, different name, no new coverage. + ?.filter { it.isFile && it.extension == "moc3" && "work" !in it.path.split(File.separatorChar) } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samples.isNotEmpty()) + + var comparedModels = 0 + var comparedDrawableStates = 0 + var skippedNeverEvaluated = 0 + val mismatches = ArrayList() + + for (mocFile in samples) { + val mocDocument = runCatching { Moc3.read(mocFile.readBytes()) }.getOrNull() ?: continue + val drivingParameters = parametersDrivingChannelledDeformers(mocDocument) + if (drivingParameters.isEmpty()) { + continue + } + // The canvas-space rebase is part of the app's real ingest path, and it must preserve every + // non-positional keyform channel (the modelA hologram tint regression: the rebase rebuilt + // MeshForms and silently dropped multiply/screen colours). The channels this gate compares + // are rebase-invariant, so running the rebased model keeps the gate on the rendered path. + val puppet = org.umamo.render.restMeshesToCanvasSpace(Moc3Import.fromMocDocument(mocDocument, null)) + val poses = derivePoses(mocDocument, drivingParameters) + comparedModels++ + println("[oracle] ${mocFile.name}: ${drivingParameters.size} channelled-deformer parameters, ${poses.size} poses") + + for (pose in poses) { + val dump = runOracleDump(dumpModel, coreLib, mocFile, pose) + val parameterValues = pose.entries.associate { ParameterId(it.key) to it.value } + val inputs = preparePose(puppet, parameterValues) + for (drawableInputs in inputs.drawables) { + val oracleEntry = dump.entries[drawableInputs.drawableId.raw] ?: continue + /* + * The runtime core FREEZES an art mesh whose own keyform binding - or any ancestor + * deformer's - is out of its keyed parameter range, skipping it entirely during the + * update, so every computed field stays at the zero it was allocated with. Umamo + * instead evaluates such a drawable live, and that difference spans geometry as well + * as these channels (the oracle reports `vpos_h=0` for them), so it is a separate gap + * from the channel cascade this test gates - see TODO § Puppet Model, CMO3, MOC3. + * Excluded here so this gate keeps measuring one thing. + */ + if (oracleNeverEvaluated(oracleEntry)) { + skippedNeverEvaluated++ + continue + } + comparedDrawableStates++ + val label = "${mocFile.name} pose=$pose ${drawableInputs.drawableId.raw}" + checkChannel(mismatches, label, "op", oracleEntry.opacity, drawableInputs.opacity) + if (oracleEntry.multiplyRgba.size == 4 && oracleEntry.screenRgba.size == 4) { + checkChannel(mismatches, label, "mulR", oracleEntry.multiplyRgba[0], drawableInputs.multiplyColor.red) + checkChannel(mismatches, label, "mulG", oracleEntry.multiplyRgba[1], drawableInputs.multiplyColor.green) + checkChannel(mismatches, label, "mulB", oracleEntry.multiplyRgba[2], drawableInputs.multiplyColor.blue) + checkChannel(mismatches, label, "scrR", oracleEntry.screenRgba[0], drawableInputs.screenColor.red) + checkChannel(mismatches, label, "scrG", oracleEntry.screenRgba[1], drawableInputs.screenColor.green) + checkChannel(mismatches, label, "scrB", oracleEntry.screenRgba[2], drawableInputs.screenColor.blue) + } + } + } + } + + Assume.assumeTrue("[oracle] no corpus model authors a deformer channel", comparedModels > 0) + assertTrue( + mismatches.isEmpty(), + "deformer-channel cascade mismatches (${mismatches.size} of $comparedDrawableStates drawable states):\n" + + mismatches.take(40).joinToString("\n") + + if (mismatches.size > 40) "\n… and ${mismatches.size - 40} more" else "", + ) + println( + "[oracle] compared $comparedDrawableStates drawable channel states across $comparedModels models, " + + "all within tolerance ($skippedNeverEvaluated skipped as never-evaluated by the oracle)", + ) + } + + /** + * Finds the parameters driving any deformer that authors a non-identity opacity or color. + * + * @param MocDocument mocDocument The decoded model. + * @return Map Parameter id → the key positions of the axes that drive one. + */ + private fun parametersDrivingChannelledDeformers(mocDocument: MocDocument): Map { + val driving = LinkedHashMap() + for (deformer in mocDocument.deformers) { + if (!authorsAChannel(deformer)) { + continue + } + val binding = mocDocument.keyformBinding(deformer.keyformBindingIndex) ?: continue + for (axis in binding.axes) { + val parameter = mocDocument.parameters.getOrNull(axis.parameterIndex) ?: continue + // Union the key positions when several channelled deformers share a parameter, so a + // sweep visits every key any of them is authored at. + val existing = driving[parameter.id] + driving[parameter.id] = + if (existing == null) { + axis.keyPositions.copyOf() + } else { + (existing.toSortedSet() + axis.keyPositions.toSortedSet()).toFloatArray() + } + } + } + return driving + } + + /** + * Whether any of this deformer's keyforms departs from the identity channels. + * + * @param Deformer deformer The warp or rotation deformer. + * @return Boolean True when it authors an opacity or color worth sweeping. + */ + private fun authorsAChannel(deformer: Deformer): Boolean { + val channels = + when (deformer) { + is WarpDeformer -> deformer.keyforms.map { Triple(it.opacity, it.multiplyColor, it.screenColor) } + is RotationDeformer -> deformer.keyforms.map { Triple(it.opacity, it.multiplyColor, it.screenColor) } + } + return channels.any { (opacity, multiplyColor, screenColor) -> + opacity != opaque || + (multiplyColor != null && Triple(multiplyColor.r, multiplyColor.g, multiplyColor.b) != multiplyIdentity) || + (screenColor != null && Triple(screenColor.r, screenColor.g, screenColor.b) != screenIdentity) + } + } + + /** + * Builds the pose sweep: the default pose, then each driving parameter visited alone at each of + * its key positions and at the midpoints between them. + * + * One parameter moves at a time on purpose. A combined sweep would multiply out to thousands of + * dumps, and a mismatch in one would not say which axis caused it. + * + * @param MocDocument mocDocument The decoded model (for parameter defaults). + * @param Map drivingParameters Parameter id → key positions to visit. + * @return List> The poses to evaluate, default pose first. + */ + private fun derivePoses(mocDocument: MocDocument, drivingParameters: Map): List> { + val poses = ArrayList>() + poses.add(emptyMap()) + for ((parameterId, keyPositions) in drivingParameters) { + val parameter = mocDocument.parameters.firstOrNull { it.id == parameterId } ?: continue + val sorted = keyPositions.distinct().sorted() + val visits = ArrayList(sorted) + for (keyIndex in 0 until sorted.size - 1) { + val low = sorted[keyIndex] + val high = sorted[keyIndex + 1] + for (step in 1..midpointsPerSegment) { + visits.add(low + (high - low) * step / (midpointsPerSegment + 1f)) + } + } + // Clamp to the parameter's DECLARED range. A keyform axis can carry key positions outside + // it (nothing in the format forbids a rig keeping keys from a since-narrowed range), and + // the runtime core clamps the written value to [min, max] before evaluating. Sweeping an + // out-of-range value would compare our extrapolation against the core's clamp - a real + // difference, but a different one from the channel cascade this test gates. + for (value in visits.map { it.coerceIn(parameter.minimumValue, parameter.maximumValue) }.distinct().sorted()) { + // Skip the default - the empty pose already covers it, and repeating it wastes a dump. + if (value == parameter.defaultValue) { + continue + } + poses.add(mapOf(parameterId to value)) + if (poses.size >= maximumPosesPerModel) { + println("[oracle] pose sweep capped at $maximumPosesPerModel; later parameters not visited") + return poses + } + } + } + return poses + } + + private fun checkChannel(mismatches: ArrayList, label: String, channel: String, oracle: Float, ours: Float) { + if (!oracleCloseEnough(oracle.toDouble(), ours.toDouble())) { + mismatches.add("$label $channel: oracle=$oracle ours=$ours") + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/GlueCorpusTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/GlueCorpusTest.kt new file mode 100644 index 0000000..732965a --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/GlueCorpusTest.kt @@ -0,0 +1,48 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.runtime.model.ParameterId +import java.io.File +import kotlin.math.hypot +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Corpus E2E for glue: on a real model at a non-default tail pose, every glued seam pair must weld to + * essentially one point (the editor's weights satisfy `wA + wB ≈ 1`, so `A'` and `B'` converge). This is + * the real-model counterpart of the synthetic `GlueTest`; without the glue pass the tail strips split by + * hundreds of pixels. Gated on `-Dcmo3.sample`; self-skips without it. + */ +class GlueCorpusTest { + @Test + fun glueWeldsSeamPairsOnCorpus() { + val file = File(System.getProperty("cmo3.sample") ?: "") + Assume.assumeTrue("[glue-e2e] no cmo3.sample corpus model", file.isFile) + val root = Cmo3.read(file).root as? CModelSource ?: return + val puppet = Cmo3Import.fromModelSource(root) + assertTrue(puppet.glues.isNotEmpty(), "corpus model should carry glue affecters") + + val geometry = CpuDeformationEvaluator().evaluate(puppet, mapOf(ParameterId("Param_Angle_Rotation3") to 43.31f)) + var maxGap = 0.0 + var weldedPairs = 0 + for (glue in puppet.glues) { + val vertsA = geometry.worldPositions[glue.meshA] ?: continue + val vertsB = geometry.worldPositions[glue.meshB] ?: continue + for (pair in glue.pairs) { + val gap = + hypot( + (vertsA[pair.indexA * 2] - vertsB[pair.indexB * 2]).toDouble(), + (vertsA[pair.indexA * 2 + 1] - vertsB[pair.indexB * 2 + 1]).toDouble(), + ) + maxGap = maxOf(maxGap, gap) + weldedPairs++ + } + } + println("[glue-e2e] welded pairs=$weldedPairs maxGap=${"%.4f".format(maxGap)}px") + assertTrue(weldedPairs > 0, "should have welded at least one pair") + assertTrue(maxGap < 1.0, "glued seam pairs should weld to ~one point, but maxGap=$maxGap px") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Moc3DowngradeOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Moc3DowngradeOracleTest.kt new file mode 100644 index 0000000..1b9bf7d --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Moc3DowngradeOracleTest.kt @@ -0,0 +1,154 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.format.moc3.moc.MocVersion +import org.umamo.interop.ExportNotice +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.RuntimeFeature +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Every corpus model exports at every version BELOW its own, and each of those files loads and + * evaluates in the official core. + * + * A downgrade cannot be checked by comparing against the source - the whole point is that features + * are gone - so this asserts the two things that must hold instead: the file is loadable (the core + * rejects or crashes on a document whose CountInfo counts keyforms a stripped section no longer + * holds, and `runOracleDump` turns that into a failure), and the stripped feature is genuinely + * ABSENT from the evaluated result rather than merely unwritten in one section. + * + * That second half is what makes this more than a smoke test. Dropping a section without stripping + * the model produces a file that still loads: the drawables are all there, the geometry is right, + * and only the colours or the offscreens quietly read from the wrong place. The per-version + * invariants below fail on exactly that. + * + * Gated on `relive.dumpModel` + `relive.coreLib` + `moc3.samples`. + */ +class Moc3DowngradeOracleTest { + @Test + fun everyDowngradeLoadsAndDropsWhatItPromised() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val samples = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samples.isNotEmpty()) + + val outputDir = File("build/moc3-downgrade").apply { mkdirs() } + val failures = ArrayList() + var exported = 0 + for (mocFile in samples) { + val source = runCatching { Moc3.decode(MocCodec.read(mocFile.readBytes())) }.getOrNull() ?: continue + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + // The source's own drawable set is the reference: the ModelWithOffscreen family evaluates none + // at all (mesh-less parts and offscreens only), so "has drawables" is not a universal truth - + // "keeps the ones it had" is. + val sourceDrawables = runOracleDump(dumpModel, coreLib, mocFile, emptyMap()).entries.keys + for (version in MocVersion.entries) { + if (version.byteValue >= source.version.byteValue) { + continue + } + val (bytes, report) = Moc3Export.write(puppet, version) + val exportedFile = + File(outputDir, "${mocFile.nameWithoutExtension}-v${version.byteValue}.moc3") + .apply { writeBytes(bytes) } + exported++ + // Loading IS the assertion here: runOracleDump fails the test on a non-zero exit, which is + // what a downgrade that left the file internally inconsistent produces. + val dump = runOracleDump(dumpModel, coreLib, exportedFile, emptyMap()) + val subject = "${mocFile.name} -> v${version.byteValue}" + + val lostDrawables = sourceDrawables - dump.entries.keys + if (lostDrawables.isNotEmpty()) { + failures.add("$subject: ${lostDrawables.size} drawables lost, e.g. ${lostDrawables.take(3)}") + } + // Offscreen rendering is moc 6; below it every isolated part is demoted to grouped. + if (dump.offscreens.isNotEmpty()) { + failures.add("$subject: ${dump.offscreens.size} offscreens survived the downgrade") + } + // Per-object multiply/screen color is moc 4; below it every drawable must evaluate to the + // identity pair, which is also what proves the color TABLES went with the sections. + if (version.byteValue < 4) { + for ((drawableId, entry) in dump.entries) { + if (oracleNeverEvaluated(entry)) { + continue + } + val tinted = + entry.multiplyRgba.take(3).any { channel -> channel != 1f } || + entry.screenRgba.take(3).any { channel -> channel != 0f } + if (tinted) { + failures.add( + "$subject $drawableId: color survived a pre-4.2 downgrade " + + "(mul=${entry.multiplyRgba.take(3)} scr=${entry.screenRgba.take(3)})", + ) + break + } + } + } + // A downgrade that removed nothing must say so: the corpus models all use something the + // oldest versions cannot carry, so a silent empty report means the strip did not run. + if (version == MocVersion.V30 && report.notices.none { it is ExportNotice.FeatureStripped }) { + val inUse = + puppet.parameters.isNotEmpty() && + ( + puppet.drawables.any { drawable -> drawable.blendShapes.isNotEmpty() } || + puppet.parts.any { part -> part.isIsolated } + ) + if (inUse) { + failures.add("$subject: features were stripped but nothing was reported") + } + } + } + } + assertTrue(exported > 0, "no corpus model has a version below its own") + println("[downgrade-oracle] $exported downgraded files loaded, ${failures.size} failures") + assertTrue( + failures.isEmpty(), + "downgraded exports are not clean:\n" + failures.take(20).joinToString("\n"), + ) + } + + /** A stripped feature is named by the report, and every notice names at least one subject. */ + @Test + fun strippedFeaturesAreNamedInTheReport() { + val samples = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + // Assume, not println-and-return: a bare return reports PASSED, so an absent corpus would leave + // this gate green while covering nothing. Its sibling above gates the same way. + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samples.isNotEmpty()) + val failures = ArrayList() + val seenFeatures = linkedSetOf() + for (mocFile in samples) { + val source = runCatching { Moc3.decode(MocCodec.read(mocFile.readBytes())) }.getOrNull() ?: continue + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + val report = Moc3Export.toMocDocument(puppet, MocVersion.V30).report + for (notice in report.notices.filterIsInstance()) { + seenFeatures.add(notice.feature) + if (notice.subjects.isEmpty()) { + failures.add("${mocFile.name}: ${notice.feature} was reported with no subjects") + } + } + } + println("[downgrade] features stripped somewhere in the corpus at v1: $seenFeatures") + assertTrue(seenFeatures.isNotEmpty(), "no corpus model exercised any strip") + assertTrue(failures.isEmpty(), failures.joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Moc3ExportOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Moc3ExportOracleTest.kt new file mode 100644 index 0000000..af44d99 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/Moc3ExportOracleTest.kt @@ -0,0 +1,223 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.moc.MocCodec +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The strongest gate available on the MOC3 export: import a corpus model, export it WITHOUT a + * reference container, and make the runtime evaluate both files. + * + * Our evaluator is out of the loop entirely here. Both sides run through the same core, so the + * comparison isolates the only question that matters - did the file we wrote encode the same rig - + * from the separate question of whether our own math matches theirs. A semantic round trip cannot + * do that: it compares our reading of our own output. + * + * "The export loads at all" is gated for free. `runOracleDump` fails the test when `dump_model` + * exits non-zero, and a file with a stale CountInfo, a mis-sized runtime-slot array, an off-by-one + * prefix sum, or a draw-group rule violation makes `csmReviveMocInPlace` reject it outright. + * + * `vuvH` is a free canary on the texcoord prefix sum (section 44), which nothing else exercises. + * + * Scoped to v1-v6 - every version the format models. Gated on `relive.dumpModel` + + * `relive.coreLib` + `moc3.samples`. + */ +class Moc3ExportOracleTest { + /** The versions the export currently covers in full. */ + private val supportedVersions = setOf(1, 2, 3, 4, 5, 6) + + @Test + fun exportedFilesEvaluateLikeTheirSources() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val samples = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samples.isNotEmpty()) + + val outputDir = File("build/moc3-export").apply { mkdirs() } + val mismatches = ArrayList() + var exported = 0 + var comparedDrawables = 0 + var comparedOffscreens = 0 + var unevaluatedOffscreens = 0 + + for (mocFile in samples) { + val source = runCatching { Moc3.decode(MocCodec.read(mocFile.readBytes())) }.getOrNull() ?: continue + if (source.version.byteValue !in supportedVersions) { + continue + } + val puppet = Moc3Import.fromMocDocument(source, displayInfo = null) + val (bytes, report) = Moc3Export.write(puppet, source.version) + val exportedFile = File(outputDir, mocFile.name).apply { writeBytes(bytes) } + exported++ + println("[export-oracle] ${mocFile.name}: ${bytes.size} bytes, ${report.notices.size} notices") + + // The default pose alone is a real gate here: it exercises every static section plus the + // grid blend at each parameter's own default, which is where a mis-lowered binding shows up. + val sourceDump = runOracleDump(dumpModel, coreLib, mocFile, emptyMap()) + val exportedDump = runOracleDump(dumpModel, coreLib, exportedFile, emptyMap()) + + for ((drawableId, expected) in sourceDump.entries) { + val actual = exportedDump.entries[drawableId] + if (actual == null) { + mismatches.add("${mocFile.name}: $drawableId missing from the exported file") + continue + } + if (oracleNeverEvaluated(expected)) { + continue + } + comparedDrawables++ + if (!oracleCloseEnough(expected.vposH, actual.vposH)) { + mismatches.add("${mocFile.name} $drawableId vposH: ${expected.vposH} vs ${actual.vposH}") + } + if (!oracleCloseEnough(expected.vuvH, actual.vuvH)) { + mismatches.add("${mocFile.name} $drawableId vuvH: ${expected.vuvH} vs ${actual.vuvH}") + } + if (!oracleCloseEnough(expected.opacity.toDouble(), actual.opacity.toDouble())) { + mismatches.add("${mocFile.name} $drawableId op: ${expected.opacity} vs ${actual.opacity}") + } + compareChannel(mismatches, mocFile.name, drawableId, "mul", expected.multiplyRgba, actual.multiplyRgba) + compareChannel(mismatches, mocFile.name, drawableId, "scr", expected.screenRgba, actual.screenRgba) + } + + // Offscreens (moc 6): the `O` lines carry the owner, the packed blend, the mask list, and the + // composite channels the runtime interpolated - the only end-to-end check that an isolated + // part's own layer survived the export. + // + // Everything positional is resolved to an ID first. The export re-derives part and drawable + // ordering from the runtime model, so the two files number the same objects differently, and a + // raw index comparison would report every offscreen in a reordered model as wrong while a + // genuinely misowned one hid among them. + val expectedOffscreens = sourceDump.offscreens.associateBy { sourceDump.partIds.getOrNull(it.ownerPartIndex) } + val actualOffscreens = + exportedDump.offscreens.associateBy { exportedDump.partIds.getOrNull(it.ownerPartIndex) } + for (ownerId in expectedOffscreens.keys - actualOffscreens.keys) { + mismatches.add("${mocFile.name}: offscreen owned by $ownerId missing from the exported file") + } + for (ownerId in actualOffscreens.keys - expectedOffscreens.keys) { + mismatches.add("${mocFile.name}: exported an offscreen owned by $ownerId that the source has not") + } + for ((ownerId, expected) in expectedOffscreens) { + val actual = actualOffscreens[ownerId] ?: continue + comparedOffscreens++ + if (mocFile.name in offscreenChannelGap) { + // Structure is still compared below; only the interpolated channels are exempt. + unevaluatedOffscreens += if (actual.opacity != expected.opacity) 1 else 0 + compareOffscreenStructure(mismatches, mocFile.name, ownerId, expected, actual, sourceDump, exportedDump) + continue + } + val subject = "offscreen($ownerId)" + compareOffscreenStructure(mismatches, mocFile.name, ownerId, expected, actual, sourceDump, exportedDump) + if (!oracleCloseEnough(expected.opacity.toDouble(), actual.opacity.toDouble())) { + mismatches.add("${mocFile.name} $subject op: ${expected.opacity} vs ${actual.opacity}") + } + compareChannel(mismatches, mocFile.name, subject, "mul", expected.multiplyRgba, actual.multiplyRgba) + compareChannel(mismatches, mocFile.name, subject, "scr", expected.screenRgba, actual.screenRgba) + } + } + + assertTrue(exported > 0, "no corpus model in the export's supported versions") + println( + "[export-oracle] $exported models exported and re-evaluated, $comparedDrawables drawables and " + + "$comparedOffscreens offscreens compared ($unevaluatedOffscreens in the pinned s160 gap), " + + "${mismatches.size} mismatches", + ) + assertTrue( + mismatches.isEmpty(), + "exported files do not evaluate like their sources:\n" + mismatches.take(20).joinToString("\n"), + ) + } + + /** + * Models whose offscreen CHANNELS are a known gap; their structure is still compared. + * + * The runtime drives offscreen evaluation from section 160, not from the owner column: blanking 160 + * in an exported file leaves every offscreen at zero, and filling it for every part evaluates all of + * them. Its slots are NOT the owner parts - in modelA the two columns name different parts for 13 of + * 24 offscreens - so 160 is keyed by whichever part the runtime's own walk reaches, which we cannot + * yet reconstruct. The export writes the owner-consistent inverse, and on modelA the runtime then + * never reaches 12 of the 24, leaving them unevaluated (opacity 0, multiply 0,0,0). + * + * Every other corpus model matches exactly, including the whole ModelWithOffscreen family, because + * their part numbering survives the export unchanged. Remove this the moment 160's key is pinned. + */ + private val offscreenChannelGap = setOf("modelA.moc3") + + /** + * Compares an offscreen's static fields - blend, flags, and the clip set by drawable id. + * + * @param ArrayList mismatches The shared collector. + * @param String fileName The model being compared. + * @param String? ownerId The owner part id. + * @param OracleOffscreen expected The source file's offscreen. + * @param OracleOffscreen actual The exported file's offscreen. + * @param OracleDump sourceDump The source dump, for its drawable ids. + * @param OracleDump exportedDump The exported dump, for its drawable ids. + */ + private fun compareOffscreenStructure( + mismatches: ArrayList, + fileName: String, + ownerId: String?, + expected: OracleOffscreen, + actual: OracleOffscreen, + sourceDump: OracleDump, + exportedDump: OracleDump, + ) { + val subject = "offscreen($ownerId)" + if (expected.blendMode != actual.blendMode) { + mismatches.add("$fileName $subject blend: ${expected.blendMode} vs ${actual.blendMode}") + } + if (expected.constantFlags != actual.constantFlags) { + mismatches.add("$fileName $subject cflag: ${expected.constantFlags} vs ${actual.constantFlags}") + } + val expectedMasks = expected.maskIndices.mapNotNull { sourceDump.drawableIds.getOrNull(it) } + val actualMasks = actual.maskIndices.mapNotNull { exportedDump.drawableIds.getOrNull(it) } + // Order is not compared: a clip set is a set, and the export emits it in the runtime model's own + // order rather than the source file's. + if (expectedMasks.toSet() != actualMasks.toSet()) { + mismatches.add("$fileName $subject masks: $expectedMasks vs $actualMasks") + } + } + + /** + * Compares one RGBA channel row, recording a mismatch per differing component. + * + * @param ArrayList mismatches The shared collector. + * @param String fileName The model being compared. + * @param String subject The drawable id or offscreen being compared. + * @param String channel The channel name for the message. + * @param List expected The source file's row. + * @param List actual The exported file's row. + */ + private fun compareChannel( + mismatches: ArrayList, + fileName: String, + subject: String, + channel: String, + expected: List, + actual: List, + ) { + if (expected.size != actual.size) { + mismatches.add("$fileName $subject $channel arity: ${expected.size} vs ${actual.size}") + return + } + for (component in expected.indices) { + if (!oracleCloseEnough(expected[component].toDouble(), actual[component].toDouble())) { + mismatches.add("$fileName $subject $channel[$component]: ${expected[component]} vs ${actual[component]}") + return + } + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/OracleHarness.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/OracleHarness.kt new file mode 100644 index 0000000..5fc12d7 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/OracleHarness.kt @@ -0,0 +1,228 @@ +package org.umamo.render.eval + +import org.junit.Assume +import java.io.File +import kotlin.math.abs + +/* + * Shared helpers for differential-oracle tests that shell out to the rebuilt dump_model tool + * (the Umamo C++ Runtime harness's dump_model.c). Mirrors DeformationOracleTest's hashing/comparison exactly - + * that test's default-pose gate is deliberately left textually untouched (see its 156 re-pin + * note), so the shared pieces live here for the posed tests instead of being extracted from it. + */ + +/** + * One dumped drawable: its vertex count, the oracle's position/uv rolling hashes, and the + * post-update scalar channels ([opacity] and the multiply/screen RGBA the `--channels` flag adds). + * + * The channels are the cascade result, not the drawable's own keyform value - the oracle folds its + * parent deformer chain and its ancestor parts in before exposing them - which is exactly what makes + * them a usable gate on our own cascade. + */ +internal data class OracleEntry( + val vtx: Int, + val vposH: Double, + val vuvH: Double, + val opacity: Float, + val multiplyRgba: List, + val screenRgba: List, + /** The core's post-update draw order (its rounded integer form of the blended float). */ + val drawOrder: Int = 0, + /** The core's post-update RENDER order - the drawable's slot after draw-group depth sorting. */ + val renderOrder: Int = 0, +) + +/** + * One dumped offscreen (an `O` line): the static moc fields plus the post-update interpolated + * channels (opacity, multiply/screen RGBA - the oracle's evalOffscreens output). + */ +internal data class OracleOffscreen( + val ownerPartIndex: Int, + val blendMode: Int, + val constantFlags: Int, + val maskIndices: List, + val opacity: Float, + val multiplyRgba: List, + val screenRgba: List, +) + +/** + * A parsed dump: the model-space canvas header plus the per-drawable entries by id. + * + * The two index->id lists exist because a moc addresses parts and drawables positionally while the + * export re-derives its own ordering, so ANY cross-file comparison of an index (an offscreen's owner, + * a mask list) has to travel through the id or it compares two different numbering schemes. + */ +internal data class OracleDump( + val pixelsPerUnit: Float, + val originX: Float, + val originY: Float, + val entries: Map, + val offscreens: List = emptyList(), + /** Part ids in file-index order, from the `T` lines. */ + val partIds: List = emptyList(), + /** Drawable ids in file-index order, from the `D` lines. */ + val drawableIds: List = emptyList(), +) + +/** + * Runs dump_model against [coreLib] and [moc3] at [pose] (empty = default pose) and parses the + * canvas header plus the `T` (part), `O` (offscreen), and `D` (drawable) lines. + * + * @param File dumpModel The dump_model binary. + * @param File coreLib .so to dlopen - Must be compatible with the official Cubism API. + * @param File moc3 The model to dump. + * @param Map pose Parameter id -> value written before csmUpdateModel. + * @return OracleDump The parsed dump. + */ +internal fun runOracleDump(dumpModel: File, coreLib: File, moc3: File, pose: Map): OracleDump { + val command = ArrayList() + command.add(dumpModel.absolutePath) + command.add(coreLib.absolutePath) + command.add(moc3.absolutePath) + command.add("--update") + // Adds mul=/scr= to each D line. Always on: the extra columns cost nothing to parse and the + // alternative is two dump invocations for tests that want geometry AND color. + command.add("--channels") + for ((parameterId, value) in pose) { + command.add("--param") + command.add("$parameterId=$value") + } + val process = ProcessBuilder(command).redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().readText() + val exit = process.waitFor() + // The file is named because a non-zero exit IS the "does it even load" gate: without it a rejected + // export reads as an unattributable crash in whichever model happened to be next. + check(exit == 0) { "dump_model failed on ${moc3.path} (exit $exit): ${output.take(300)}" } + + val canvasRegex = Regex("""# canvas size=(\S+),(\S+) origin=(\S+),(\S+) ppu=(\S+)""") + val canvas = canvasRegex.find(output) ?: error("no canvas header in dump") + val idRegex = Regex("""id=(\S+)""") + val vtxRegex = Regex("""vtx=(\d+)""") + val vposRegex = Regex("""vpos_h=(\S+)""") + val vuvRegex = Regex("""vuv_h=(\S+)""") + // D-line channels: op= comes from --update, mul=/scr= from --channels. Anchored to ` op=` with a + // leading space so it cannot match the `vpos_h=`/`vuv_h=` suffixes or an id containing "op=". + val opacityRegex = Regex(""" op=(\S+)""") + val drawOrderRegex = Regex(""" draw=(-?\d+)""") + val renderOrderRegex = Regex(""" render=(-?\d+)""") + val multiplyRegex = Regex(""" mul=(\S+)""") + val screenRegex = Regex(""" scr=(\S+)""") + // O owner= blend= cflag=0x masks=:,,… op= mul=,,, scr=,,, + val offscreenRegex = + Regex("""O \d+ owner=(-?\d+) blend=(-?\d+) cflag=0x([0-9a-fA-F]+) masks=\d+:(\S*) op=(\S+) mul=(\S+) scr=(\S+)""") + val entries = HashMap() + val offscreens = ArrayList() + val partIds = ArrayList() + val drawableIds = ArrayList() + // T id= parent= + val partRegex = Regex("""T \d+ id=(\S+)""") + for (line in output.lineSequence()) { + if (line.startsWith("T ")) { + partRegex.find(line)?.let { partIds.add(it.groupValues[1]) } + continue + } + if (line.startsWith("O ")) { + val match = offscreenRegex.find(line) ?: continue + offscreens.add( + OracleOffscreen( + ownerPartIndex = match.groupValues[1].toInt(), + blendMode = match.groupValues[2].toInt(), + constantFlags = match.groupValues[3].toInt(16), + maskIndices = match.groupValues[4].split(',').mapNotNull { it.toIntOrNull() }, + opacity = match.groupValues[5].toFloat(), + multiplyRgba = match.groupValues[6].split(',').map { it.toFloat() }, + screenRgba = match.groupValues[7].split(',').map { it.toFloat() }, + ), + ) + continue + } + if (!line.startsWith("D ")) { + continue + } + val id = idRegex.find(line)?.groupValues?.get(1) ?: continue + // Recorded before the geometry parse: the id list is the file's INDEX ordering, so a line this + // parser gives up on would silently shift every later index. + drawableIds.add(id) + val vtx = vtxRegex.find(line)?.groupValues?.get(1)?.toIntOrNull() ?: continue + // Non-finite hashes are kept rather than skipped, for the same reason: a dropped entry reads as + // "the exported file has no such drawable", which points at the wrong thing entirely. + val vposH = vposRegex.find(line)?.let { it.groupValues[1].toDoubleOrNull() ?: Double.NaN } ?: continue + val vuvH = vuvRegex.find(line)?.let { it.groupValues[1].toDoubleOrNull() ?: Double.NaN } ?: continue + val opacity = opacityRegex.find(line)?.groupValues?.get(1)?.toFloatOrNull() ?: Float.NaN + // A non-finite channel is DATA, not a parse error: the core prints "-nan" for a drawable whose + // inputs went bad, and that is exactly the kind of thing a differential gate exists to catch. + // Throwing here would turn a reportable mismatch into an unattributable test crash. + val multiplyRgba = + multiplyRegex.find(line)?.groupValues?.get(1)?.split(',')?.map { it.toFloatOrNull() ?: Float.NaN } + ?: emptyList() + val screenRgba = + screenRegex.find(line)?.groupValues?.get(1)?.split(',')?.map { it.toFloatOrNull() ?: Float.NaN } + ?: emptyList() + val drawOrder = drawOrderRegex.find(line)?.groupValues?.get(1)?.toIntOrNull() ?: 0 + val renderOrder = renderOrderRegex.find(line)?.groupValues?.get(1)?.toIntOrNull() ?: 0 + entries[id] = OracleEntry(vtx, vposH, vuvH, opacity, multiplyRgba, screenRgba, drawOrder, renderOrder) + } + return OracleDump( + pixelsPerUnit = canvas.groupValues[5].toFloat(), + originX = canvas.groupValues[3].toFloat(), + originY = canvas.groupValues[4].toFloat(), + entries = entries, + offscreens = offscreens, + partIds = partIds, + drawableIds = drawableIds, + ) +} + +/** The oracle's rolling hash, `hp = hp*1.0000001 + v`, over canvas->model transformed vertices. */ +internal fun oracleTransformedHash(world: FloatArray, offsetX: Float, offsetY: Float, scale: Float): Double { + var hash = 0.0 + var index = 0 + while (index < world.size) { + hash = hash * 1.0000001 + (world[index] - offsetX) / scale + hash = hash * 1.0000001 + (world[index + 1] - offsetY) / scale + index += 2 + } + return hash +} + +/** Relative/absolute closeness at the oracle's 1e-5 tolerance (mirrors DeformationOracleTest). */ +internal fun oracleCloseEnough(a: Double, b: Double): Boolean { + val scale = maxOf(1.0, abs(a), abs(b)) + return abs(a - b) <= 1e-5 * scale +} + +/** + * Resolves a `-D`-supplied oracle input, skipping the calling test when it is absent. + * + * Every oracle gate needs the same two inputs and each had grown its own private copy of this; one + * definition keeps the skip MESSAGE identical too, which is what makes an absent harness legible in + * the test log rather than looking like a silent pass. + * + * @param String property The system property naming the file. + * @return File The existing file (the test is skipped before this returns otherwise). + */ +internal fun requireOracleInput(property: String): File { + val file = System.getProperty(property)?.let(::File)?.takeIf { it.exists() } + Assume.assumeTrue("[oracle] absent -D$property", file != null) + return file!! +} + +/** + * Whether the oracle never evaluated [entry] - an all-zero row rather than a real result. + * + * The core leaves a drawable untouched when nothing drives it at this pose, and the zeroed row is + * indistinguishable from a legitimately transparent one by value alone; the combination of a zero + * position hash AND zero opacity AND a zero (not white) multiply is what separates them, since an + * evaluated drawable still reports real geometry and a white multiply. + * + * @param OracleEntry entry The dumped drawable. + * @return Boolean True when the oracle never evaluated it. + */ +internal fun oracleNeverEvaluated(entry: OracleEntry): Boolean = + entry.vposH == 0.0 && + entry.opacity == 0f && + entry.multiplyRgba.size == 4 && + entry.multiplyRgba[0] == 0f && + entry.multiplyRgba[1] == 0f && + entry.multiplyRgba[2] == 0f \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/PartBlendShapeOracleTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/PartBlendShapeOracleTest.kt new file mode 100644 index 0000000..9e7c3ac --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/PartBlendShapeOracleTest.kt @@ -0,0 +1,109 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.model.BlendShapeKeyform +import org.umamo.format.moc3.model.BlendShapeTarget +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.runtime.model.ParameterId +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Posed differential validation of PART-target blend-shape records against the runtime. + * + * A part's only blendable channel is its draw order, so unlike the drawable and deformer records these + * carry no geometry and no color - and their effect is invisible to every other oracle gate, which + * compares positions and per-drawable channels. What a part draw-order delta actually moves is the + * SORT: a grouped part's whole subtree changes places among its siblings. So this gate compares the + * core's post-update render order (`csmGetDrawableRenderOrders`) against ours. + * + * Comparing the ORDER rather than the raw draw-order value is deliberate. The two runtimes agree on + * the ordering but not necessarily on the number behind it - Umamo sorts floats where the core rounds + * to an integer first (MOC3.md §5.6) - so the value is a weaker and noisier signal than the permutation + * it produces, which is what actually reaches the screen. + * + * Gated on `relive.dumpModel` + `relive.coreLib` + `moc3.samples`; skips when any is absent. modelC is + * the only corpus model carrying a part-target record, so the corpus reaches this through it alone. + */ +class PartBlendShapeOracleTest { + @Test + fun partBlendShapeDrawOrderMatchesTheOracleRenderOrder() { + val dumpModel = requireOracleInput("relive.dumpModel") + val coreLib = requireOracleInput("relive.coreLib") + val samples = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.filter { it.isFile && it.extension == "moc3" && it.parentFile?.name != "work" } + ?.sortedBy { it.name } + ?.toList() + .orEmpty() + Assume.assumeTrue("[oracle] absent -Dmoc3.samples", samples.isNotEmpty()) + + var posedModels = 0 + var comparedPoses = 0 + val mismatches = ArrayList() + + for (mocFile in samples) { + val mocDocument = runCatching { Moc3.read(mocFile.readBytes()) }.getOrNull() ?: continue + val partRecords = mocDocument.blendShapes.filter { it.target == BlendShapeTarget.PART } + if (partRecords.isEmpty()) { + continue + } + // Pose each record at every non-neutral key carrying an actual delta: a zero row would move + // nothing and prove nothing. + val poses = LinkedHashSet>() + for (record in partRecords) { + val parameterId = mocDocument.parameters.getOrNull(record.parameterIndex)?.id ?: continue + for (keyIndex in record.keyforms.indices) { + val delta = (record.keyforms[keyIndex] as? BlendShapeKeyform.Part)?.drawOrderDelta ?: continue + if (keyIndex == record.neutralKeyIndex || delta == 0f) { + continue + } + record.keyPositions.getOrNull(keyIndex)?.let { poses.add(mapOf(parameterId to it)) } + } + } + if (poses.isEmpty()) { + continue + } + posedModels++ + val puppet = org.umamo.render.restMeshesToCanvasSpace(Moc3Import.fromMocDocument(mocDocument, null)) + println("[oracle] ${mocFile.name}: ${poses.size} part-blend poses over ${partRecords.size} records") + + for (pose in poses) { + val dump = runOracleDump(dumpModel, coreLib, mocFile, pose) + val parameterValues = pose.entries.associate { ParameterId(it.key) to it.value } + // Our render order is the drawable id sequence back-to-front; the core reports a slot per + // drawable, so invert it to the same shape before comparing. + val inputs = preparePose(puppet, parameterValues) + val ours = + renderOrder( + puppet.renderRoot, + inputs.drawables.associate { it.drawableId to it.drawOrder }, + inputs.partDrawOrders, + ).map { it.raw } + val theirs = + dump.entries.entries + .filter { entry -> !oracleNeverEvaluated(entry.value) } + .sortedBy { entry -> entry.value.renderOrder } + .map { entry -> entry.key } + val oursEvaluated = ours.filter { id -> id in theirs.toSet() } + comparedPoses++ + if (oursEvaluated != theirs) { + val firstDivergence = oursEvaluated.zip(theirs).indexOfFirst { (a, b) -> a != b } + mismatches.add( + "${mocFile.name} pose=$pose: render order diverges at slot $firstDivergence " + + "(ours=${oursEvaluated.getOrNull(firstDivergence)} oracle=${theirs.getOrNull(firstDivergence)})", + ) + } + } + } + + assertTrue(posedModels > 0, "no corpus model carried a part-target blend record to pose") + println("[oracle] part blend shapes: $comparedPoses poses across $posedModels models, ${mismatches.size} mismatches") + assertTrue(mismatches.isEmpty(), "part blend-shape draw order disagrees:\n" + mismatches.take(10).joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/eval/RenderOrderCorpusTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/RenderOrderCorpusTest.kt new file mode 100644 index 0000000..532c93a --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/eval/RenderOrderCorpusTest.kt @@ -0,0 +1,55 @@ +package org.umamo.render.eval + +import org.junit.Assume +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshForm +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.interop.cmo3.Cmo3Import +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals + +/** + * Corpus E2E for draw order. The official editor's license blocks re-saving an edited model, so instead + * this bumps a real drawable's keyform draw order in flight and asserts the whole chain (CMO3 + * import → deformation eval → [paintOrder]) lifts it to the front - the real-model counterpart of the + * synthetic `RenderOrderTest`. Gated on `-Dcmo3.sample`; self-skips without it. + */ +class RenderOrderCorpusTest { + private fun elements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + @Test + fun bumpedDrawOrderPaintsFrontmostOnCorpus() { + val file = File(System.getProperty("cmo3.sample") ?: "") + Assume.assumeTrue("[ord-e2e] no cmo3.sample corpus model", file.isFile) + val root = Cmo3.read(file).root as? CModelSource ?: return + + // The backmost drawable at the default pose (parts-tree order, all draw orders equal - an empty + // map makes paintOrder fall back to the Cubism default for every drawable, i.e. the base order). + val baseline = Cmo3Import.fromModelSource(root) + val backmost = baseline.drawables.firstOrNull() ?: return + val defaultOrder = paintOrder(baseline.drawables.map { it.id }, emptyMap()) + assertEquals(backmost.id, defaultOrder.first(), "precondition: target starts backmost") + assertNotEquals(backmost.id, defaultOrder.last(), "precondition: target is not already frontmost") + + // Raise that drawable's keyform draw order on the shared graph, then re-run the full pipeline. + val artMeshes = elements((root.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + val target = artMeshes.firstOrNull { (it.id as? Id)?.idstr == backmost.id.raw } ?: return + elements(target.keyforms).filterIsInstance().forEach { it.drawOrder = 999 } + + val puppet = Cmo3Import.fromModelSource(root) + val geometry = CpuDeformationEvaluator().evaluate(puppet, emptyMap()) + val order = paintOrder(puppet.drawables.map { it.id }, geometry.drawOrder) + assertEquals(backmost.id, order.last(), "raised draw order should paint frontmost") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/AtlasPageRenderTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/AtlasPageRenderTest.kt new file mode 100644 index 0000000..f3ff041 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/AtlasPageRenderTest.kt @@ -0,0 +1,188 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.ContentBounds +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Proves [PuppetRenderer.renderAtlasPage] draws the atlas page UPRIGHT with the correct UV orientation + * (the V-flip is easy to get backwards): a page whose four quadrants are distinctly colored must land + * atlas-top-left at the DISPLAYED top-left, atlas-top-right at the displayed top-right, + * and atlas-bottom-left at the displayed bottom-left. A second case proves a null page paints the grid + * only (no crash, no colored art). Renders into an offscreen FBO at a page-fit 1:1 camera so the page + * fills the frame. Self-skips in a display-less environment, like [WorldAxisLinesTest]. + */ +class AtlasPageRenderTest { + private val viewportSize = 64 + private val paramA = ParameterId("A") + + // A minimal keyed quad so the renderer's CPU content-bounds eval (used only for the camera fit) is + // finite; renderAtlasPage itself ignores the model entirely. + private fun model(): PuppetModel { + val positions = floatArrayOf(0f, 0f, 64f, 0f, 0f, 64f, 64f, 64f) + val drawable = + Drawable( + id = DrawableId("probe"), + name = "probe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2, 1, 3, 2)), + geometryGrid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size))))), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + } + + /** + * A page (RGBA, top row first) with four distinctly-colored quadrants, so the rendered frame pins both + * orientation axes: atlas top-left RED, top-right GREEN, bottom-left BLUE, bottom-right WHITE. + */ + private fun quadrantPage(size: Int): DecodedImage { + val rgba = ByteArray(size * size * 4) + for (rowIndex in 0 until size) { + for (columnIndex in 0 until size) { + val top = rowIndex < size / 2 // row 0 is the atlas TOP row (top-row-first) + val left = columnIndex < size / 2 + val red: Int + val green: Int + val blue: Int + when { + top && left -> { + red = 255 + green = 0 + blue = 0 + } + top && !left -> { + red = 0 + green = 255 + blue = 0 + } + !top && left -> { + red = 0 + green = 0 + blue = 255 + } + else -> { + red = 255 + green = 255 + blue = 255 + } + } + val pixel = (rowIndex * size + columnIndex) * 4 + rgba[pixel] = red.toByte() + rgba[pixel + 1] = green.toByte() + rgba[pixel + 2] = blue.toByte() + rgba[pixel + 3] = 255.toByte() + } + } + return DecodedImage(rgba, size, size) + } + + @Test + fun atlasPageRendersUprightWithCorrectUvOrientation() { + requireHeadlessGl("[atlas-page]") + val page = quadrantPage(viewportSize) + val device = GlRenderDevice() + val renderer = PuppetRenderer(model(), PuppetTextures(listOf(page), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // Fit the page rectangle 1:1 so the whole page fills the frame. + renderer.setCamera(ViewportCamera.fit(ContentBounds(0f, 0f, viewportSize.toFloat(), viewportSize.toFloat()), viewportSize, viewportSize)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.renderAtlasPage(target, 0, viewportSize, viewportSize) + val frame = readPixels(viewportSize, viewportSize) // bottom-up rows: displayed TOP = high row index + + val near = viewportSize / 8 + val far = viewportSize - near - 1 + // The V-flip acceptance check: atlas top-left (red) must land at the displayed top-left. + assertChannel(frame, near, far, "red", "displayed top-left is the atlas top-left (red)") + // U orientation: atlas top-right (green) at the displayed top-right. + assertChannel(frame, far, far, "green", "displayed top-right is the atlas top-right (green)") + // atlas bottom-left (blue) at the displayed bottom-left. + assertChannel(frame, near, near, "blue", "displayed bottom-left is the atlas bottom-left (blue)") + } + + @Test + fun nullPageRendersGridOnly() { + requireHeadlessGl("[atlas-page]") + val device = GlRenderDevice() + val renderer = PuppetRenderer(model(), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera.fit(ContentBounds(0f, 0f, viewportSize.toFloat(), viewportSize.toFloat()), viewportSize, viewportSize)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.renderAtlasPage(target, null, viewportSize, viewportSize) + val frame = readPixels(viewportSize, viewportSize) + + // No page: the neutral grey grid (grey background + grey lines) fills the frame, so a sampled pixel + // reads near-neutral - not a saturated red / green / blue art channel. Assert grayish (all + // channels within a tight band). + val pixel = (viewportSize / 2 * viewportSize + viewportSize / 2) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + val spread = maxOf(red, green, blue) - minOf(red, green, blue) + println("[atlas-page] null-page center rgb=($red,$green,$blue) spread=$spread") + assertTrue(spread < 40, "null page paints the neutral grid, not colored art (rgb spread $spread)") + } + + /** Asserts the given channel dominates the pixel at (col, row), i.e. the expected quadrant color lands there. */ + private fun assertChannel(frame: ByteBuffer, column: Int, row: Int, channel: String, message: String) { + val pixel = (row * viewportSize + column) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + val dominant = + when (channel) { + "red" -> red > green + 60 && red > blue + 60 + "green" -> green > red + 60 && green > blue + 60 + "blue" -> blue > red + 60 && blue > green + 60 + else -> false + } + assertTrue(dominant, "$message - got rgb=($red,$green,$blue)") + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/AtlasPageSwapRenderTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/AtlasPageSwapRenderTest.kt new file mode 100644 index 0000000..f8a9705 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/AtlasPageSwapRenderTest.kt @@ -0,0 +1,153 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Proves a mid-session atlas page swap actually re-points the residents: setAtlasPages must destroy + * and re-upload the page handles AND re-stamp every resident through the NEW index map, because a + * repack can move a drawable to a different page. The swap moves the probe from page 0 of a + * one-page set to page 1 of a two-page set whose page 0 is a decoy color - a renderer that re-uploads + * handles but keeps the old index shows the decoy, and one that skips the swap entirely shows the + * original. The page view is then checked at the ORIGINAL index, which must show the new texels + * (same index, new pixels - the freshness case the engine's atlas bump exists for). + * + * Self-skips in a display-less environment (no GL context), like [SourceLayerDisplayRenderTest]. + */ +class AtlasPageSwapRenderTest { + private val viewportSize = 200 + private val paramA = ParameterId("A") + private val probeId = DrawableId("SwapProbe") + + // A 120x120 quad centered at the origin; at zoom 1 it covers pixels ~40..160 in the 200x200 viewport. + private val quadPositions = floatArrayOf(-60f, -60f, 60f, -60f, -60f, 60f, 60f, 60f) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // Sampled well inside the image so a filtered lookup never straddles an edge. + private val quadUvs = floatArrayOf(0.05f, 0.95f, 0.95f, 0.95f, 0.05f, 0.05f, 0.95f, 0.05f) + + private fun solidImage(red: Int, green: Int, blue: Int, size: Int = 8): DecodedImage { + val rgba = ByteArray(size * size * 4) + for (pixel in rgba.indices step 4) { + rgba[pixel] = red.toByte() + rgba[pixel + 1] = green.toByte() + rgba[pixel + 2] = blue.toByte() + rgba[pixel + 3] = 0xFF.toByte() + } + return DecodedImage(rgba, size, size) + } + + private fun probeModel(): PuppetModel { + val drawable = + Drawable( + id = probeId, + name = "SwapProbe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(quadPositions.copyOf(), quadUvs.copyOf(), quadIndices), + // One zero-delta keyform so the drawable is keyed; the base mesh alone drives its shape. + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(quadPositions.size)))), + ), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + } + + @Test + fun swappingPagesRestampsResidentsThroughTheNewIndexMap() { + requireHeadlessGl("[atlas-swap]") + val device = GlRenderDevice() + val renderer = + PuppetRenderer( + probeModel(), + PuppetTextures(listOf(solidImage(0xFF, 0x00, 0x00)), mapOf(probeId.raw to 0), premultipliedAlpha = false), + device, + ) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // A fixed 1:1 camera centered on the origin, so the quad never moves - only its texels do. + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setShownDrawables(setOf(probeId)) + + fun frame(): ByteBuffer { + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + return readPixels(viewportSize, viewportSize) + } + + assertCenterChannel(frame(), "red", "before the swap the probe samples its original red page") + + // The swap: two pages, the probe on page 1. Page 0 turns into a green decoy, so keeping the old + // index (or the old handles) is visibly distinct from following the new map to blue. + renderer.setAtlasPages( + PuppetTextures( + listOf(solidImage(0x00, 0xFF, 0x00), solidImage(0x00, 0x00, 0xFF)), + mapOf(probeId.raw to 1), + premultipliedAlpha = false, + ), + ) + assertCenterChannel(frame(), "blue", "after the swap the probe samples page 1 of the new set") + + // The page view at the ORIGINAL index shows the new texels: same index, new pixels. + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.renderAtlasPage(target, 0, viewportSize, viewportSize) + assertCenterChannel(readPixels(viewportSize, viewportSize), "green", "page index 0 now shows the swapped-in texels") + } + + /** Asserts the given channel dominates at the viewport center (well inside the probe quad and the page). */ + private fun assertCenterChannel(frame: ByteBuffer, channel: String, message: String) { + val pixel = (viewportSize / 2 * viewportSize + viewportSize / 2) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + val dominant = + when (channel) { + "red" -> red > green + 60 && red > blue + 60 + "green" -> green > red + 60 && green > blue + 60 + "blue" -> blue > red + 60 && blue > green + 60 + else -> false + } + assertTrue(dominant, "$message - got rgb=($red,$green,$blue)") + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeAccelerationParityTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeAccelerationParityTest.kt new file mode 100644 index 0000000..2a87e10 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeAccelerationParityTest.kt @@ -0,0 +1,110 @@ +package org.umamo.render.gl + +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.PuppetTextures +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The whole-model correctness gate for the composite acceleration: renders a real corpus model + * (Model A, 24 isolated groups + extended-blend drawables) through the OPTIMIZED path and again + * with the acceleration disabled (plain full-viewport composites), and asserts the two images are + * pixel-identical within one composite's rounding. The optimizations are only ever meant to save + * work, never change a pixel - so an undersized bounds scissor (which once clipped the head-top and + * arm tips) shows up here as a large channel diff instead of a silent visual regression. Corpus- + + * GL-gated: skips without Model A or a context. + */ +class CompositeAccelerationParityTest { + private val viewportWidth = 768 + private val viewportHeight = 1024 + + // One composite boundary re-quantizes to 8 bits; the flatten fast path removes an intermediate + // quantization, so identity groups can differ by a couple of LSB. A clip would be ~255. + private val channelTolerance = 3 + + @Test + fun acceleratedRenderMatchesTheFullViewportPath() { + val mocFile = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.firstOrNull { it.name == "modelA.moc3" } + if (mocFile == null) { + println("modelA.moc3 not present; skipping composite acceleration parity") + return + } + requireHeadlessGl("[composite-accel-parity]") + val puppet = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(Moc3.read(mocFile.readBytes()), null)) + // The plain full-viewport composite path is the reference (the pre-optimization behavior the + // oracle + composite suites already pin). Each optimization is asserted against it alone and + // combined, so a failure names which one diverged. + val reference = renderImage(puppet, flatten = false, scissor = false) + assertMatches(reference, renderImage(puppet, flatten = true, scissor = false), "identity flatten") + assertMatches(reference, renderImage(puppet, flatten = false, scissor = true), "bounds scissor") + assertMatches(reference, renderImage(puppet, flatten = true, scissor = true), "flatten + scissor") + } + + private fun assertMatches(reference: IntArray, candidate: IntArray, label: String) { + var maxDiff = 0 + var differingSamples = 0 + var minX = Int.MAX_VALUE + var minY = Int.MAX_VALUE + var maxX = -1 + var maxY = -1 + val samples = ArrayList() + for (index in reference.indices) { + val diff = abs(reference[index] - candidate[index]) + if (diff > maxDiff) { + maxDiff = diff + } + // Report every over-tolerance channel INCLUDING alpha (channel 3): the pass/fail check below + // is over all four channels, so excluding alpha here would let an alpha-only divergence fail + // the test while printing an empty, misleading diagnostic. + if (diff > channelTolerance) { + differingSamples++ + val pixel = index / 4 + val px = pixel % viewportWidth + val py = pixel / viewportWidth + minX = minOf(minX, px) + minY = minOf(minY, py) + maxX = maxOf(maxX, px) + maxY = maxOf(maxY, py) + if (samples.size < 12) { + samples.add("($px,$py) ch${index % 4} ref=${reference[index]} cand=${candidate[index]}") + } + } + } + if (differingSamples > 0) { + println("[$label] diff bbox x[$minX,$maxX] y[$minY,$maxY], $differingSamples samples, maxDiff $maxDiff") + samples.forEach { println("[$label] $it") } + } + assertTrue( + maxDiff <= channelTolerance, + "$label must match the full-viewport composite path (max channel diff $maxDiff, $differingSamples channel " + + "samples over tolerance) - a large diff means the optimization changed a pixel (e.g. a scissor clipped content)", + ) + } + + /** Renders [source] at the default fit camera with the two optimizations toggled; returns RGBA bytes. */ + private fun renderImage(source: PuppetModel, flatten: Boolean, scissor: Boolean): IntArray { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.compositeFlattenEnabled = flatten + renderer.compositeBoundsScissorEnabled = scissor + renderer.initGl() + renderer.setPose(emptyMap()) // no camera set: render() frames the content by its fit + val target = device.createRenderTarget(RenderTargetSpec(viewportWidth, viewportHeight, TextureFormat.Rgba8, sampled = true)) + renderer.render(target, viewportWidth, viewportHeight) + val image = device.readPixels(target) + return IntArray(image.rgba.size) { image.rgba[it].toInt() and 0xFF } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeEditReconcileTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeEditReconcileTest.kt new file mode 100644 index 0000000..92a6952 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeEditReconcileTest.kt @@ -0,0 +1,203 @@ +package org.umamo.render.gl + +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The "an edit reaches the viewport" gate: pushes an EDITED model through the same + * [PuppetRenderer.updateModel] + [PuppetRenderer.setPose] path the render loop drives, on ONE persistent + * renderer, and asserts the pixels change. This is what a fresh-renderer-per-model test (like + * [CompositeRendererTest]) cannot catch - a composite-only edit is a ModelDiff Keep with no buffer work, + * so the resident is reused, and the renderer must still pick up the new blend/mask (drawable) or the + * re-derived render tree (part) rather than the state captured at upload. Flat-color drawables over a + * black backdrop keep the expectations analytic. Skips without a GL context. + */ +class CompositeEditReconcileTest { + private val viewportSize = 64 + private val paramA = ParameterId("A") + private val blackGrid = GridColors(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + + private val fullQuad = floatArrayOf(-32f, -32f, 32f, -32f, -32f, 32f, 32f, 32f) + private val frontIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // The left half of the viewport, as a clip-mask source. + private val leftHalfQuad = floatArrayOf(-32f, -32f, 0f, -32f, -32f, 32f, 0f, 32f) + + private fun restGrid(positions: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ) + + private fun drawable( + id: String, + positions: FloatArray = fullQuad, + blendMode: BlendMode = BlendMode.Normal, + maskedBy: List = emptyList(), + isVisible: Boolean = true, + ): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = blendMode, + maskedBy = maskedBy, + mesh = DrawableMesh(positions, FloatArray(positions.size), frontIndices), + geometryGrid = restGrid(positions), + isVisible = isVisible, + ) + + private fun model(drawables: List, parts: List = emptyList(), rootChildren: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = parts, + deformers = emptyList(), + drawables = drawables, + rootChildren = rootChildren, + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ).withDerivedRenderRoot() + + private fun isolatedPart(partId: String, childId: String, composite: PartComposite): Part = + Part( + id = PartId(partId), + name = partId, + children = listOf(OrgChild.Drawable(DrawableId(childId))), + groupMode = PartGroupMode.Isolated, + composite = composite, + ) + + /** + * One persistent renderer that shows successive model snapshots through the edit path + * (updateModel → setPose → render), exactly as the render loop does. + */ + private inner class LiveRenderer(initial: PuppetModel) { + private val device = GlRenderDevice() + private val renderer = + PuppetRenderer(initial, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + private val target: RenderTarget + + init { + renderer.initGl() + renderer.setGrid(blackGrid, 100f, 10) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + } + + fun show(model: PuppetModel) { + renderer.updateModel(model) + renderer.setPose(emptyMap()) + renderer.render(target, viewportSize, viewportSize) + } + + fun pixel(x: Int, y: Int): IntArray { + val image = device.readPixels(target) + val pixelOffset = (y * viewportSize + x) * 4 + return IntArray(4) { channelIndex -> image.rgba[pixelOffset + channelIndex].toInt() and 0xFF } + } + + fun centerPixel(): IntArray = pixel(viewportSize / 2, viewportSize / 2) + } + + @Test + fun drawableBlendEditReflectsAfterUpdateModel() { + requireHeadlessGl("[composite-edit-reconcile]") + // A single flat quad over black. Normal draws its color; a Multiply over black collapses to 0 + // (the src factor is the destination color, which is black). The blend edit does no buffer + // work (a ModelDiff Keep), so this passes only if updateModel re-stamps the resident's blend. + val normal = model(listOf(drawable("top")), rootChildren = listOf(OrgChild.Drawable(DrawableId("top")))) + val live = LiveRenderer(normal) + live.show(normal) + assertTrue(live.centerPixel().take(3).max() > 32, "Normal over black shows the layer color") + + val multiplied = + model( + listOf(drawable("top", blendMode = BlendMode.MultiplyPremultiplied)), + rootChildren = listOf(OrgChild.Drawable(DrawableId("top"))), + ) + live.show(multiplied) + assertTrue(live.centerPixel().take(3).max() <= 3, "after the blend edit, Multiply over black is dark") + } + + @Test + fun drawableMaskEditReflectsAfterUpdateModel() { + requireHeadlessGl("[composite-edit-reconcile]") + // A full quad, then masked by a hidden left-half source: adding the mask hides the right half. + // Editing maskedBy is a Keep (no buffer work), so the right half only disappears if updateModel + // re-stamps the resident's mask ids. The mask source is already resident in both snapshots. + val maskSource = drawable("clip", positions = leftHalfQuad, isVisible = false) + val rootChildren = listOf(OrgChild.Drawable(DrawableId("clip")), OrgChild.Drawable(DrawableId("top"))) + val unmasked = model(listOf(maskSource, drawable("top")), rootChildren = rootChildren) + val rightX = viewportSize * 3 / 4 + val centerY = viewportSize / 2 + + val live = LiveRenderer(unmasked) + live.show(unmasked) + assertTrue(live.pixel(rightX, centerY).take(3).max() > 32, "unmasked quad covers the right half") + + val masked = + model( + listOf(maskSource, drawable("top", maskedBy = listOf(DrawableId("clip")))), + rootChildren = rootChildren, + ) + live.show(masked) + assertTrue(live.pixel(rightX, centerY).take(3).max() <= 3, "after the mask edit, the right half is clipped away") + } + + @Test + fun partCompositeOpacityEditReflectsAfterUpdateModel() { + requireHeadlessGl("[composite-edit-reconcile]") + + // An isolated part composited over black at opacity 1, then edited to 0.5. The edit re-derives + // renderRoot (withPartComposite does now), and updateModel + setPose rebuild the plan from it, so + // the composite must halve - the end-to-end proof that a part composite edit reaches the screen. + fun withOpacity(opacity: Float): PuppetModel = + model( + drawables = listOf(drawable("top")), + parts = listOf(isolatedPart("fx", "top", PartComposite(opacity = opacity))), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + + val live = LiveRenderer(withOpacity(1f)) + live.show(withOpacity(1f)) + val opaque = live.centerPixel() + assertTrue(opaque.take(3).max() > 32, "the composite shows at full opacity") + + live.show(withOpacity(0.5f)) + val halved = live.centerPixel() + for (channelIndex in 0 until 3) { + assertTrue( + abs(halved[channelIndex] - opaque[channelIndex] / 2) <= 3, + "opacity 0.5 halves ch$channelIndex over black: ${opaque.toList()} -> ${halved.toList()}", + ) + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeOptimizationTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeOptimizationTest.kt new file mode 100644 index 0000000..b6d6250 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeOptimizationTest.kt @@ -0,0 +1,179 @@ +package org.umamo.render.gl + +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The composite perf optimizations, verified for pixel correctness: the bounds SCISSOR that confines + * a layer composite to the isolated subtree's screen rectangle (a vertical-flip or over-clip bug + * would misplace or clip the effect), and the identity-composite FLATTEN fast path (an identity + * Normal/Over isolated part draws its subtree inline; premultiplied Over is associative, so it must + * match the same drawable drawn with no part at all). Flat-color drawables over a black backdrop, so + * every expectation is analytic. Skips without a GL context. + */ +class CompositeOptimizationTest { + private val viewportSize = 64 + private val paramA = ParameterId("A") + private val blackGrid = GridColors(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + private val frontIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // A quad in one band of the viewport (mesh y in [8, 30]). The vertex shader negates Y, so a + // positive mesh Y renders in the LOWER band of the top-first read-back image (high row numbers) - + // which is exactly what makes this quad a good scissor-placement probe: the composite must land + // where the geometry actually rasterizes, Y-negation and all. + private val bandQuad = floatArrayOf(-16f, 8f, 16f, 8f, -16f, 30f, 16f, 30f) + + // Rows (top-first) inside and outside the rendered quad band. Mesh y [8, 30] -> rendered-world y + // [-30, -8] -> top-first rows ~[40, 62]; row 50 is inside, row 12 is well above (outside). + private val insideRow = 50 + private val outsideRow = 12 + + private fun restGrid(size: Int): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(size)))), + ) + + private fun quad(id: String, positions: FloatArray = bandQuad): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + alphaBlendMode = AlphaBlendMode.Over, + culling = false, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), frontIndices), + geometryGrid = restGrid(positions.size), + isVisible = true, + ) + + private fun model(drawables: List, parts: List, rootChildren: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = parts, + deformers = emptyList(), + drawables = drawables, + rootChildren = rootChildren, + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ).withDerivedRenderRoot() + + private fun isolated(partId: String, childId: String, composite: PartComposite): Part = + Part( + id = PartId(partId), + name = partId, + children = listOf(OrgChild.Drawable(DrawableId(childId))), + groupMode = PartGroupMode.Isolated, + composite = composite, + ) + + private fun renderImage(source: PuppetModel): IntArray { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setGrid(blackGrid, 100f, 10) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setPose(emptyMap()) + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + renderer.render(target, viewportSize, viewportSize) + val image = device.readPixels(target) + return IntArray(image.rgba.size) { image.rgba[it].toInt() and 0xFF } + } + + private fun pixel(image: IntArray, x: Int, y: Int): IntArray { + val offset = (y * viewportSize + x) * 4 + return IntArray(4) { image[offset + it] } + } + + @Test + fun scissoredCompositeLandsInTheQuadBandOnly() { + requireHeadlessGl("[composite-opt]") + // An isolated part at opacity 0.5 (so the real composite path runs, not the flatten path) + // wrapping the band quad. Over black, the composite writes half the quad's premul color in + // the quad's band and nothing elsewhere - and the scissor confines the work to the quad's + // bounds. A vertical scissor-flip bug would move the effect to the opposite band. + val source = + model( + drawables = listOf(quad("top")), + parts = listOf(isolated("fx", "top", PartComposite(opacity = 0.5f))), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val image = renderImage(source) + val inside = pixel(image, viewportSize / 2, insideRow) + val outside = pixel(image, viewportSize / 2, outsideRow) + assertTrue(inside.take(3).max() > 8, "the composite is drawn in the quad's band, got ${inside.toList()}") + assertTrue(outside.take(3).max() <= 2, "outside the quad stays the black backdrop, got ${outside.toList()}") + } + + @Test + fun identityCompositeFlattensToPlainDrawing() { + requireHeadlessGl("[composite-opt]") + // The SAME quad, drawn two ways: plainly (no part), and wrapped in an identity Normal/Over + // isolated part (opacity 1, identity colors, unmasked). The identity part flattens to inline + // drawing - Over is associative - so every pixel must agree within one 8-bit rounding step. + val plain = + model( + drawables = listOf(quad("q")), + parts = emptyList(), + rootChildren = listOf(OrgChild.Drawable(DrawableId("q"))), + ) + val wrapped = + model( + drawables = listOf(quad("q")), + parts = listOf(isolated("fx", "q", PartComposite())), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val plainImage = renderImage(plain) + val wrappedImage = renderImage(wrapped) + var maxDiff = 0 + for (index in plainImage.indices) { + maxDiff = maxOf(maxDiff, abs(plainImage[index] - wrappedImage[index])) + } + assertTrue(maxDiff <= 1, "flattened identity composite matches plain drawing (max channel diff $maxDiff)") + } + + @Test + fun fadedCompositeIsSkippedLeavingTheBackdrop() { + requireHeadlessGl("[composite-opt]") + // A pose-blended opacity of 0 makes the layer empty, so the composite is skipped outright; + // over the black backdrop the result is pure black everywhere the quad would have been. + val source = + model( + drawables = listOf(quad("top")), + parts = listOf(isolated("fx", "top", PartComposite(opacity = 0f))), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val image = renderImage(source) + val inside = pixel(image, viewportSize / 2, insideRow) + assertTrue(inside.take(3).max() <= 2, "a zero-opacity composite leaves the backdrop, got ${inside.toList()}") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositePerfProbeTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositePerfProbeTest.kt new file mode 100644 index 0000000..a16b48f --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositePerfProbeTest.kt @@ -0,0 +1,89 @@ +package org.umamo.render.gl + +import org.lwjgl.opengl.GL11 +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import java.io.File +import kotlin.test.Test + +/** + * Print-only compositing perf probe on Model A: frame times with the composites live vs the same + * model with every isolated group demoted to Grouped, at a supersampled-ish viewport. With the + * bounds-scissor + identity-flatten + empty-layer-skip optimizations in place the composite path + * runs BELOW the all-grouped baseline (faded / off-viewport groups are skipped, and the surviving + * composites are scissored to their subtree bounds), so the delta is now negative. Pins nothing - + * see docs/plan/offscreen-support.md for the numbers and the mechanisms. Skips without a GL + * context or the corpus. + */ +class CompositePerfProbeTest { + private val viewportWidth = 1200 + private val viewportHeight = 1800 + private val warmupFrames = 10 + private val timedFrames = 60 + + @Test + fun probeCompositeFrameCost() { + val mocFile = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { it.isDirectory } + ?.walkTopDown() + ?.firstOrNull { it.name == "modelA.moc3" } + if (mocFile == null) { + println("modelA.moc3 not present; skipping perf probe") + return + } + requireHeadlessGl("[composite-perf]") + val puppet = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(Moc3.read(mocFile.readBytes()), null)) + // Demote Isolated to Grouped (not PassThrough) so the stripped model keeps the same + // draw-order grouping and the comparison isolates the composite cost alone. + val stripped = + puppet.copy( + parts = + puppet.parts.map { part -> + if (part.groupMode is PartGroupMode.Isolated) { + part.copy(groupMode = PartGroupMode.Grouped) + } else { + part + } + }, + ).withDerivedRenderRoot() + val withComposites = timeFrames(puppet) + val withoutComposites = timeFrames(stripped) + println( + "[composite-perf] modelA ${viewportWidth}x$viewportHeight, $timedFrames frames: " + + "composites=${"%.2f".format(withComposites)} ms/frame, " + + "stripped=${"%.2f".format(withoutComposites)} ms/frame, " + + "delta=${"%.2f".format(withComposites - withoutComposites)} ms", + ) + } + + /** Average render() wall time in milliseconds over [timedFrames] static-pose frames. */ + private fun timeFrames(source: PuppetModel): Double { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setCamera(ViewportCamera(0f, 0f, 0.5f)) + renderer.setPose(emptyMap()) + val target = device.createRenderTarget(RenderTargetSpec(viewportWidth, viewportHeight, TextureFormat.Rgba8, sampled = true)) + repeat(warmupFrames) { + renderer.render(target, viewportWidth, viewportHeight) + } + GL11.glFinish() + val startNanos = System.nanoTime() + repeat(timedFrames) { + renderer.render(target, viewportWidth, viewportHeight) + } + GL11.glFinish() + return (System.nanoTime() - startNanos) / 1e6 / timedFrames + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeRendererTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeRendererTest.kt new file mode 100644 index 0000000..d2a436a --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeRendererTest.kt @@ -0,0 +1,354 @@ +package org.umamo.render.gl + +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.withDerivedRenderRoot +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +private const val CHANNEL_TOLERANCE = 3 + +/** + * End-to-end layer compositing through [PuppetRenderer]: the always-shader legacy parity (an + * isolated part with a legacy blend renders identically to the same drawable blended + * fixed-function), the composite channels (opacity, multiply color), the composite clip mask with + * invert, two-level nesting, and back-face culling. Flat-color drawables (no atlas) keep every + * expectation analytic; the backdrop is pure black so "over black" collapses to the layer's own + * premultiplied color. Skips without a GL context. + */ +class CompositeRendererTest { + private val viewportSize = 64 + private val paramA = ParameterId("A") + private val blackGrid = GridColors(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + + // A full-viewport quad in the fixed 1:1 camera (world x,y in [-32, 32]). With the standard + // indices (0,1,2)(1,3,2) the triangles land CLOCKWISE in the renderer's Y-negated world - the + // corpus front-face convention - so they survive back-face culling. + private val fullQuad = floatArrayOf(-32f, -32f, 32f, -32f, -32f, 32f, 32f, 32f) + private val frontIndices = intArrayOf(0, 1, 2, 1, 3, 2) + private val backIndices = intArrayOf(0, 2, 1, 1, 2, 3) + + // The left half of the viewport, as a clip-mask source. + private val leftHalfQuad = floatArrayOf(-32f, -32f, 0f, -32f, -32f, 32f, 0f, 32f) + + // Opacity is its own channel now, so the geometry grid carries deltas only; callers pass the opacity + // to the drawable's static instead. + private fun restGrid(positions: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ) + + private fun drawable( + id: String, + positions: FloatArray = fullQuad, + indices: IntArray = frontIndices, + blendMode: BlendMode = BlendMode.Normal, + alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over, + culling: Boolean = false, + opacity: Float = 1f, + isVisible: Boolean = true, + ): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = blendMode, + alphaBlendMode = alphaBlendMode, + culling = culling, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), indices), + geometryGrid = restGrid(positions), + opacity = opacity, + isVisible = isVisible, + ) + + private fun model(drawables: List, parts: List = emptyList(), rootChildren: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = parts, + deformers = emptyList(), + drawables = drawables, + rootChildren = rootChildren, + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ).withDerivedRenderRoot() + + /** Renders [source] and returns the RGBA of the pixel at ([x], [y]) in top-first image space. */ + private fun renderPixel(source: PuppetModel, x: Int, y: Int): IntArray { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setGrid(blackGrid, 100f, 10) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setPose(emptyMap()) + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + renderer.render(target, viewportSize, viewportSize) + val image = device.readPixels(target) + val pixelOffset = (y * viewportSize + x) * 4 + return IntArray(4) { channelIndex -> image.rgba[pixelOffset + channelIndex].toInt() and 0xFF } + } + + private fun renderCenterPixel(source: PuppetModel): IntArray = renderPixel(source, viewportSize / 2, viewportSize / 2) + + private fun isolatedPart( + partId: String, + childId: String, + composite: PartComposite, + children: List = listOf(OrgChild.Drawable(DrawableId(childId))), + ): Part = + Part( + id = PartId(partId), + name = partId, + children = children, + groupMode = PartGroupMode.Isolated, + composite = composite, + ) + + private fun assertPixelClose(expected: IntArray, actual: IntArray, label: String) { + for (channelIndex in 0 until 3) { + assertTrue( + abs(expected[channelIndex] - actual[channelIndex]) <= CHANNEL_TOLERANCE, + "$label ch$channelIndex: expected ${expected.toList()}, got ${actual.toList()}", + ) + } + } + + @Test + fun legacyCompositeMatchesFixedFunctionBlending() { + requireHeadlessGl("[composite-renderer]") + // The same two quads: base Normal, top legacy Multiply at 0.6 opacity. Fixed-function + // path (drawable-level blend) vs the always-shader composite path (the top quad wrapped + // in a legacy Multiply/Over isolated part) must land on the same pixels. + val base = drawable("base") + val fixedFunction = + model( + drawables = listOf(base, drawable("top", blendMode = BlendMode.MultiplyPremultiplied, opacity = 0.6f)), + rootChildren = listOf(OrgChild.Drawable(DrawableId("base")), OrgChild.Drawable(DrawableId("top"))), + ) + val composited = + model( + drawables = listOf(base, drawable("top", opacity = 0.6f)), + parts = listOf(isolatedPart("fx", "top", PartComposite(blendMode = BlendMode.MultiplyPremultiplied))), + rootChildren = listOf(OrgChild.Drawable(DrawableId("base")), OrgChild.Part(PartId("fx"))), + ) + assertPixelClose(renderCenterPixel(fixedFunction), renderCenterPixel(composited), "legacy multiply parity") + } + + @Test + fun premultipliedModesIgnoreTheAlphaBlendSetting() { + requireHeadlessGl("[composite-renderer]") + // The "(Before 5.3)" Add/Multiply composite in premultiplied format and ignore the Alpha + // blend setting, so an isolated composite using one renders identically whether its alpha + // mode is Over or Disjoint. A modern mode would diverge (it honors the alpha mode). + for (mode in listOf(BlendMode.AdditivePremultiplied, BlendMode.MultiplyPremultiplied)) { + fun composited(alpha: AlphaBlendMode): PuppetModel = + model( + drawables = listOf(drawable("base"), drawable("top", opacity = 0.6f)), + parts = listOf(isolatedPart("fx", "top", PartComposite(blendMode = mode, alphaBlendMode = alpha))), + rootChildren = listOf(OrgChild.Drawable(DrawableId("base")), OrgChild.Part(PartId("fx"))), + ) + assertPixelClose( + renderCenterPixel(composited(AlphaBlendMode.Over)), + renderCenterPixel(composited(AlphaBlendMode.Disjoint)), + "$mode ignores alpha blend (Over == Disjoint)", + ) + } + } + + @Test + fun compositeOpacityAndMultiplyColorApply() { + requireHeadlessGl("[composite-renderer]") + // Over the black backdrop, source-over collapses to the layer's premultiplied color: a + // composite at opacity 0.5 must read exactly half the plain render, and a (1,0,0) + // multiply color must keep red while zeroing green/blue. + val plain = + model( + drawables = listOf(drawable("top")), + parts = listOf(isolatedPart("fx", "top", PartComposite())), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val plainPixel = renderCenterPixel(plain) + val halved = + model( + drawables = listOf(drawable("top")), + parts = listOf(isolatedPart("fx", "top", PartComposite(opacity = 0.5f))), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val halvedPixel = renderCenterPixel(halved) + assertPixelClose( + IntArray(4) { channelIndex -> if (channelIndex < 3) plainPixel[channelIndex] / 2 else halvedPixel[channelIndex] }, + halvedPixel, + "opacity 0.5 halves the composite over black", + ) + val redFiltered = + model( + drawables = listOf(drawable("top")), + parts = listOf(isolatedPart("fx", "top", PartComposite(multiplyColor = ColorRgb(1f, 0f, 0f)))), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val redPixel = renderCenterPixel(redFiltered) + assertPixelClose( + intArrayOf(plainPixel[0], 0, 0, redPixel[3]), + redPixel, + "multiply (1,0,0) keeps red and zeroes green/blue", + ) + } + + @Test + fun compositeClipMaskGatesTheCompositeAndInverts() { + requireHeadlessGl("[composite-renderer]") + + // The composite is clipped by a hidden left-half mask drawable. Coverage is the mask's + // ALPHA - the fallback color's 0.85, not 1.0 - so the clipped side shows 0.85x the plain + // composite and the inverted inside keeps the 0.15 remainder (fractional coverage is the + // Cubism semantic; a soft-edged mask clips softly). + fun clipped(invert: Boolean): PuppetModel { + val maskSource = drawable("clip", positions = leftHalfQuad, isVisible = false) + val composite = PartComposite(maskedBy = listOf(DrawableId("clip")), invertMask = invert) + return model( + drawables = listOf(maskSource, drawable("top")), + parts = listOf(isolatedPart("fx", "top", composite)), + rootChildren = listOf(OrgChild.Drawable(DrawableId("clip")), OrgChild.Part(PartId("fx"))), + ) + } + + val plain = + model( + drawables = listOf(drawable("top")), + parts = listOf(isolatedPart("fx", "top", PartComposite())), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val leftX = viewportSize / 4 + val rightX = viewportSize * 3 / 4 + val centerY = viewportSize / 2 + val plainPixel = renderPixel(plain, leftX, centerY) + val maskAlpha = 0.85f // fallbackColorFor's fixed alpha - the mask source's coverage + val straightLeft = renderPixel(clipped(invert = false), leftX, centerY) + val straightRight = renderPixel(clipped(invert = false), rightX, centerY) + assertPixelClose( + IntArray(4) { channelIndex -> if (channelIndex < 3) (plainPixel[channelIndex] * maskAlpha).toInt() else straightLeft[3] }, + straightLeft, + "clipped composite shows coverage x layer inside the mask", + ) + assertTrue(straightRight.take(3).max() <= CHANNEL_TOLERANCE, "clipped composite hides outside") + val invertedLeft = renderPixel(clipped(invert = true), leftX, centerY) + val invertedRight = renderPixel(clipped(invert = true), rightX, centerY) + assertPixelClose( + IntArray(4) { channelIndex -> if (channelIndex < 3) (plainPixel[channelIndex] * (1f - maskAlpha)).toInt() else invertedLeft[3] }, + invertedLeft, + "inverted clip keeps the coverage remainder inside", + ) + assertPixelClose( + IntArray(4) { channelIndex -> if (channelIndex < 3) plainPixel[channelIndex] else invertedRight[3] }, + invertedRight, + "inverted clip shows fully outside", + ) + } + + @Test + fun nestedCompositesComposeInnerThenOuter() { + requireHeadlessGl("[composite-renderer]") + val plain = + model( + drawables = listOf(drawable("top")), + parts = listOf(isolatedPart("fx", "top", PartComposite())), + rootChildren = listOf(OrgChild.Part(PartId("fx"))), + ) + val plainPixel = renderCenterPixel(plain) + // Inner keeps only blue (multiply 0,0,1), outer halves the whole thing (opacity 0.5) - + // over black, the pixel must be exactly (0, 0, blue/2). + val inner = isolatedPart("inner", "top", PartComposite(multiplyColor = ColorRgb(0f, 0f, 1f))) + val outer = + Part( + id = PartId("outer"), + name = "outer", + children = listOf(OrgChild.Part(PartId("inner"))), + groupMode = PartGroupMode.Isolated, + composite = PartComposite(opacity = 0.5f), + ) + val nested = + model( + drawables = listOf(drawable("top")), + parts = listOf(outer, inner), + rootChildren = listOf(OrgChild.Part(PartId("outer"))), + ) + val nestedPixel = renderCenterPixel(nested) + assertPixelClose( + intArrayOf(0, 0, plainPixel[2] / 2, nestedPixel[3]), + nestedPixel, + "inner multiply then outer opacity", + ) + } + + @Test + fun drawableMultiplyColorTintsThePlainDraw() { + requireHeadlessGl("[composite-renderer]") + // A flat drawable over black with NO composite - just its own 5.3 per-art-mesh multiply color + // (1,0,0) on the plain draw path. Over black the pixel is the layer's premultiplied color, so + // the tint must keep red and zero green/blue. + val positions = fullQuad + val tinted = + Drawable( + id = DrawableId("top"), + name = "top", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), frontIndices), + geometryGrid = restGrid(positions), + // The tint is a channel with a static; no track needed to prove the renderer applies it. + multiplyColor = ColorRgb(1f, 0f, 0f), + ) + val plainPixel = renderCenterPixel(model(listOf(drawable("top")), rootChildren = listOf(OrgChild.Drawable(DrawableId("top"))))) + val tintedPixel = renderCenterPixel(model(listOf(tinted), rootChildren = listOf(OrgChild.Drawable(DrawableId("top"))))) + assertPixelClose(intArrayOf(plainPixel[0], 0, 0, tintedPixel[3]), tintedPixel, "drawable multiply (1,0,0) keeps red, zeroes green/blue") + } + + @Test + fun backFaceCullingHidesOnlyFlippedTriangles() { + requireHeadlessGl("[composite-renderer]") + // Corpus front-face winding survives culling; the reversed winding is a flipped mesh and + // disappears exactly when culling is on. + val frontCulled = model(listOf(drawable("quad", culling = true)), rootChildren = listOf(OrgChild.Drawable(DrawableId("quad")))) + assertTrue(renderCenterPixel(frontCulled).take(3).max() > 32, "front-facing survives culling") + val backCulled = + model( + listOf(drawable("quad", indices = backIndices, culling = true)), + rootChildren = listOf(OrgChild.Drawable(DrawableId("quad"))), + ) + assertTrue(renderCenterPixel(backCulled).take(3).max() <= CHANNEL_TOLERANCE, "flipped winding is culled") + val backDoubleSided = + model( + listOf(drawable("quad", indices = backIndices)), + rootChildren = listOf(OrgChild.Drawable(DrawableId("quad"))), + ) + assertTrue(renderCenterPixel(backDoubleSided).take(3).max() > 32, "double-sided shows both windings") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeSweepTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeSweepTest.kt new file mode 100644 index 0000000..2546cf0 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/CompositeSweepTest.kt @@ -0,0 +1,168 @@ +package org.umamo.render.gl + +import org.umamo.render.device.CompositeUniforms +import org.umamo.render.device.DrawTextures +import org.umamo.render.device.LoadAction +import org.umamo.render.device.PipelineBlend +import org.umamo.render.device.PipelinePurpose +import org.umamo.render.device.RenderPassSpec +import org.umamo.render.device.RenderPipelineSpec +import org.umamo.render.device.RenderTarget +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.device.WorldToNdc +import org.umamo.render.puppet.compositeReference +import org.umamo.render.puppet.packedAlphaModeOf +import org.umamo.render.puppet.packedColorModeOf +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import kotlin.math.abs +import kotlin.math.roundToInt +import kotlin.test.Test +import kotlin.test.assertTrue + +// 8-bit target quantization + the shader's float math vs the reference's - a couple of ulps at +// 1/255 granularity. The Rgba8 inputs are pre-quantized below, so this only absorbs arithmetic +// divergence, not input rounding. +private const val CHANNEL_TOLERANCE = 3f / 255f + +/** + * The composite shader vs the pure reference, across every color x alpha mode combination: fills a + * layer and a destination target with known premultiplied colors, runs the Composite + * pipeline, and compares the read-back pixel against `compositeReference` channel by channel. + * This is what makes BlendMath.kt the spec rather than documentation - the GLSL cannot drift from + * it without this failing. Skips without a GL context. + */ +class CompositeSweepTest { + private val size = 8 + + private fun quantize(premul: FloatArray): FloatArray = + FloatArray(4) { channelIndex -> (premul[channelIndex] * 255f).roundToInt() / 255f } + + private fun target(device: GlRenderDevice): RenderTarget = + device.createRenderTarget(RenderTargetSpec(size, size, TextureFormat.Rgba8, sampled = true)) + + private fun fill(device: GlRenderDevice, target: RenderTarget, premul: FloatArray) { + val frame = device.beginFrame() + val pass = + frame.beginRenderPass( + RenderPassSpec( + colorTarget = target, + loadAction = LoadAction.Clear, + viewportWidth = size, + viewportHeight = size, + clearRed = premul[0], + clearGreen = premul[1], + clearBlue = premul[2], + clearAlpha = premul[3], + ), + ) + pass.end() + frame.endFrame() + } + + private fun centerPixel(device: GlRenderDevice, target: RenderTarget): FloatArray { + val image = device.readPixels(target) + val pixelOffset = ((size / 2) * size + size / 2) * 4 + return FloatArray(4) { channelIndex -> (image.rgba[pixelOffset + channelIndex].toInt() and 0xFF) / 255f } + } + + private fun composite( + device: GlRenderDevice, + out: RenderTarget, + layer: RenderTarget, + dest: RenderTarget, + uniforms: CompositeUniforms, + ): FloatArray { + val pipeline = device.createRenderPipeline(RenderPipelineSpec(PipelinePurpose.Composite, PipelineBlend.Opaque)) + val textures = DrawTextures() + val frame = device.beginFrame() + val pass = frame.beginRenderPass(RenderPassSpec(out, LoadAction.Clear, size, size)) + pass.setPipeline(pipeline) + pass.setCamera(WorldToNdc(1f, 1f, 0f, 0f), size, size) + textures.compositeLayer = layer.sampledTexture + textures.destinationSnapshot = dest.sampledTexture + pass.drawComposite(uniforms, textures) + pass.end() + frame.endFrame() + return centerPixel(device, out) + } + + @Test + fun compositeShaderMatchesTheReferenceAcrossAllModes() { + requireHeadlessGl("[composite-sweep]") + val device = GlRenderDevice() + val layer = target(device) + val dest = target(device) + val out = target(device) + // Valid premultiplied pixels (rgb <= a), partially transparent on both sides so every + // alpha mode's factors bite. + val sourcePremul = quantize(floatArrayOf(0.3f, 0.2f, 0.1f, 0.5f)) + val destinationPremul = quantize(floatArrayOf(0.4f, 0.5f, 0.6f, 0.75f)) + fill(device, layer, sourcePremul) + fill(device, dest, destinationPremul) + val uniforms = CompositeUniforms() + val failures = ArrayList() + var worstDelta = 0f + for (blendMode in BlendMode.entries) { + for (alphaBlendMode in AlphaBlendMode.entries) { + uniforms.colorMode = packedColorModeOf(blendMode) + uniforms.alphaMode = packedAlphaModeOf(alphaBlendMode) + val pixel = composite(device, out, layer, dest, uniforms) + val expected = compositeReference(sourcePremul, destinationPremul, blendMode, alphaBlendMode) + for (channelIndex in 0 until 4) { + val delta = abs(pixel[channelIndex] - expected[channelIndex]) + if (delta > worstDelta) { + worstDelta = delta + } + if (delta > CHANNEL_TOLERANCE) { + failures.add( + "$blendMode/$alphaBlendMode ch$channelIndex: shader=${pixel[channelIndex]} reference=${expected[channelIndex]}", + ) + } + } + } + } + println("[composite-sweep] ${BlendMode.entries.size * AlphaBlendMode.entries.size} combos, worst channel delta=$worstDelta") + assertTrue(failures.isEmpty(), "shader vs reference mismatches (${failures.size}):\n" + failures.joinToString("\n")) + } + + @Test + fun compositeChannelsApplyToTheLayerBeforeBlending() { + requireHeadlessGl("[composite-sweep]") + val device = GlRenderDevice() + val layer = target(device) + val dest = target(device) + val out = target(device) + val sourcePremul = quantize(floatArrayOf(0.3f, 0.2f, 0.1f, 0.5f)) + val destinationPremul = quantize(floatArrayOf(0.4f, 0.5f, 0.6f, 0.75f)) + fill(device, layer, sourcePremul) + fill(device, dest, destinationPremul) + val uniforms = CompositeUniforms() + uniforms.opacity = 0.5f + uniforms.multiplyRed = 0f + uniforms.multiplyGreen = 1f + uniforms.multiplyBlue = 1f + uniforms.screenRed = 0.2f + uniforms.screenGreen = 0f + uniforms.screenBlue = 0f + val pixel = composite(device, out, layer, dest, uniforms) + // The reference application order: opacity scales the premultiplied layer, then multiply + // then screen apply to the straight color - mirroring the shader line for line. + val scaled = FloatArray(4) { channelIndex -> sourcePremul[channelIndex] * 0.5f } + val alpha = scaled[3] + val straight = floatArrayOf(scaled[0] / alpha, scaled[1] / alpha, scaled[2] / alpha) + straight[0] *= 0f + straight[1] *= 1f + straight[2] *= 1f + straight[0] = straight[0] + 0.2f - straight[0] * 0.2f + val layerAfter = floatArrayOf(straight[0] * alpha, straight[1] * alpha, straight[2] * alpha, alpha) + val expected = compositeReference(layerAfter, destinationPremul, BlendMode.Normal, AlphaBlendMode.Over) + for (channelIndex in 0 until 4) { + assertTrue( + abs(pixel[channelIndex] - expected[channelIndex]) <= CHANNEL_TOLERANCE, + "channel $channelIndex: shader=${pixel[channelIndex]} reference=${expected[channelIndex]}", + ) + } + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/EmptyModelRenderTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/EmptyModelRenderTest.kt new file mode 100644 index 0000000..291e0d0 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/EmptyModelRenderTest.kt @@ -0,0 +1,87 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.ContentBounds +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Proves a model with nothing in it still paints a work surface: the renderer initializes over zero + * drawables and zero atlas pages, frames the canvas with no camera handed to it, and rasterizes the grid + * there. This is the first frame of every new document, so a blank one is the first thing a rigger sees. + * + * What it guards is the framing, not the grid: with nothing to measure, a camera fitted to a rectangle + * left at the float extremes draws nothing at all, which no unit test of the grid - each of which sets its + * own camera - could notice. Drives a high-contrast palette (black background, red major lines) so "the + * grid is there" is a count of red pixels. Self-skips in a display-less environment, like + * [GridBackdropRenderTest]. + */ +class EmptyModelRenderTest { + private val viewportSize = 400 + private val canvasSize = 1200f + + private fun emptyModel(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = canvasSize, + canvasHeight = canvasSize, + worldOriginX = canvasSize / 2f, + worldOriginZ = -(canvasSize / 2f), + ) + + @Test + fun anEmptyModelFramesItsCanvasAndPaintsTheGrid() { + requireHeadlessGl("[empty-model]") + val device = GlRenderDevice() + val renderer = PuppetRenderer(emptyModel(), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Black background, red major lines every 100 world units, black minor lines: twelve major cells + // across the canvas, so the fitted view crosses a dozen red lines each way. + renderer.setGrid(GridColors(0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f), 100f, subdivisions = 1) + renderer.setPose(emptyMap()) + + assertEquals(ContentBounds(0f, -canvasSize, canvasSize, canvasSize), renderer.contentBounds(), "with nothing to measure, the view frames the canvas") + + // No camera is set: the renderer fits its own content bounds, the path a viewport's first frame takes. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, (target as GlRenderTarget).framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frame = readPixels(viewportSize, viewportSize) + + var redPixels = 0 + var backgroundPixels = 0 + for (pixelIndex in 0 until viewportSize * viewportSize) { + val red = frame.get(pixelIndex * 4).toInt() and 0xFF + val green = frame.get(pixelIndex * 4 + 1).toInt() and 0xFF + val blue = frame.get(pixelIndex * 4 + 2).toInt() and 0xFF + if (red > green + 60 && red > blue + 60) { + redPixels++ + } else if (red < 40 && green < 40 && blue < 40) { + backgroundPixels++ + } + } + assertTrue(redPixels > viewportSize, "the grid's major lines are on screen ($redPixels red pixels)") + assertTrue(backgroundPixels > redPixels, "as lines over a backdrop, not a flooded frame ($backgroundPixels background pixels)") + } + + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/FramebufferReadbackTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/FramebufferReadbackTest.kt new file mode 100644 index 0000000..de31d1f --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/FramebufferReadbackTest.kt @@ -0,0 +1,70 @@ +package org.umamo.render.gl + +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins [GlRenderDevice.readPixels]'s orientation contract, and with it the `UMAMO_DUMP_PNG` path end to end. + * + * The read-back and the PNG dump had no coverage at all before this, while carrying the single most + * invertible convention in the renderer: GL hands back the BOTTOM row first, and every consumer here + * wants the TOP row first. Get it backwards and nothing crashes - every dump is just silently mirrored, + * which is exactly the sort of bug that survives review. + * + * The probe paints the framebuffer's top half red and bottom half green through the scissor box (in GL's + * own bottom-left coordinates), so "which row is first" has a single unambiguous answer. Then it round + * trips through the real [PngCodec] the dump uses, so an encode-side flip would be caught too. + */ +class FramebufferReadbackTest { + private val size = 16 + + /** Reads a pixel out of a top-first [RasterImage]. Row 0 is the TOP row. */ + private fun pixelAt(image: RasterImage, column: Int, row: Int): Triple { + val at = (row * image.width + column) * 4 + return Triple( + image.rgba[at].toInt() and 0xFF, + image.rgba[at + 1].toInt() and 0xFF, + image.rgba[at + 2].toInt() and 0xFF, + ) + } + + @Test + fun readPixelsReturnsTopRowFirstAndSurvivesThePngRoundTrip() { + requireHeadlessGl("[framebuffer-readback]") + val device = GlRenderDevice() + val target = device.createRenderTarget(RenderTargetSpec(size, size, TextureFormat.Rgba8, sampled = true)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, (target as GlRenderTarget).framebuffer) + GL11.glViewport(0, 0, size, size) + + // Paint through the scissor box in GL's bottom-left space: y=0 is the BOTTOM half. + GL11.glEnable(GL11.GL_SCISSOR_TEST) + GL11.glScissor(0, 0, size, size / 2) + GL11.glClearColor(0f, 1f, 0f, 1f) + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT) + GL11.glScissor(0, size / 2, size, size / 2) + GL11.glClearColor(1f, 0f, 0f, 1f) + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT) + GL11.glDisable(GL11.GL_SCISSOR_TEST) + + val image = device.readPixels(target) + assertEquals(size, image.width) + assertEquals(size, image.height) + // GL's top half is red; a top-first image must therefore lead with red. Without the flip this + // is green and the assertion fires - which is the whole point of the test. + assertEquals(Triple(255, 0, 0), pixelAt(image, 0, 0), "row 0 is the framebuffer's TOP row (red)") + assertEquals(Triple(0, 255, 0), pixelAt(image, 0, size - 1), "the last row is the BOTTOM row (green)") + + // The dump writes through PngCodec; re-decode it to prove the whole path keeps the orientation. + val decoded = PngCodec.read(PngCodec.write(image)) + assertEquals(size, decoded.width) + assertEquals(size, decoded.height) + assertEquals(Triple(255, 0, 0), pixelAt(decoded, 0, 0), "the encoded PNG still leads with the top row") + assertEquals(Triple(0, 255, 0), pixelAt(decoded, 0, size - 1)) + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GeometryReuploadTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GeometryReuploadTest.kt new file mode 100644 index 0000000..d7065f4 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GeometryReuploadTest.kt @@ -0,0 +1,230 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RotationPivotForm +import java.nio.ByteBuffer +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Proves the GPU renderer re-uploads an edited base mesh so the textured art actually moves: an + * Object/Edit-mode G/S/R commits new positions, and those positions must reach the VBO on the next + * render or the art visibly lags behind the mesh. Renders a flat-color quad into an offscreen FBO, shifts + * its base positions via [PuppetRenderer.updateModel], re-renders, and asserts the drawn art's pixel + * centroid moved by the expected screen delta - once for a direct (undeformed) drawable and once for a + * rotation-deformer-parented one, so a parented drawable's art fully tracks the edit rather than lagging + * partway. Also asserts [PuppetRenderer.pickGeometry] follows the edit, so picking stays in sync with + * what's drawn. + * + * Self-skips in a display-less environment (no GL context), like [GpuDeformValidationTest]. + */ +class GeometryReuploadTest { + private val viewportSize = 400 + private val paramA = ParameterId("A") + private val probeId = DrawableId("MotionProbe") + + // A 120x120 quad centered at the origin; at zoom 1 it covers pixels ~140..260, so a +60 shift stays fully + // on-screen in the 400x400 viewport (no edge clipping to bias the centroid). + private val quadPositions = floatArrayOf(-60f, -60f, 60f, -60f, -60f, 60f, 60f, 60f) + private val quadUvs = FloatArray(8) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + private val shiftWorld = 60f + + private fun meshAxis() = listOf(KeyformAxis(paramA, floatArrayOf(0f))) + + private fun quadDrawable(parentDeformerId: DeformerId?): Drawable = + Drawable( + id = probeId, + name = "MotionProbe", + parentDeformerId = parentDeformerId, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(quadPositions.copyOf(), quadUvs, quadIndices), + // A single zero-delta keyform so the drawable is "keyed" (an unkeyed drawable is skipped by the + // renderer); the base mesh alone drives its shape. + geometryGrid = KeyformGrid(meshAxis(), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(quadPositions.size))))), + ) + + private fun model(deformers: List, drawable: Drawable): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = deformers, + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + + /** The same model with the probe's base positions translated +[shiftWorld] in x (a fresh positions array). */ + private fun shiftedModel(source: PuppetModel): PuppetModel { + val drawable = source.drawables.single() + val shifted = + FloatArray(quadPositions.size) { coordIndex -> + drawable.mesh!!.positions[coordIndex] + if (coordIndex % 2 == 0) shiftWorld else 0f + } + return source.copy(drawables = listOf(drawable.copy(mesh = DrawableMesh(shifted, quadUvs, quadIndices)))) + } + + @Test + fun directDrawableArtFollowsBaseEdit() { + runMotionCase(model(emptyList(), quadDrawable(null)), "direct") + } + + @Test + fun rotationParentedDrawableArtFollowsBaseEdit() { + // An identity rotation (angle 0, scale 1, origin 0,0) so the parent-transform path (parentType 1) runs + // yet the expected screen delta stays the direct +shiftWorld - proving the re-uploaded base flows + // through the deformer cascade and lands at the new place, rather than the parent absorbing the move. + val deformerId = DeformerId("R") + val rotation = + Deformer.Rotation( + id = deformerId, + name = "R", + parent = null, + partId = null, + baseAngle = 0f, + geometryGrid = KeyformGrid(meshAxis(), listOf(KeyformCell(intArrayOf(0), RotationPivotForm(0f, 0f, 0f, 1f)))), + ) + runMotionCase(model(listOf(rotation), quadDrawable(deformerId)), "rotation") + } + + /** + * Renders [source] and its base-shifted variant into an offscreen FBO and asserts the drawn art moved by + * the expected screen delta and that pick geometry followed. Self-skips (returns) with no GL context. + */ + private fun runMotionCase(source: PuppetModel, label: String) { + requireHeadlessGl("[geometry-reupload]") + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // A fixed 1:1 camera centered on the origin, so one world unit == one screen pixel and the frame + // never moves - only the art does. Held across both renders. + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + // Background only (the drawable hidden), so the art can be isolated by differencing against it. + renderer.setShownDrawables(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val background = readPixels(viewportSize, viewportSize) + + // Frame A: the art at its original base positions. + renderer.setShownDrawables(setOf(probeId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frameA = readPixels(viewportSize, viewportSize) + val (centroidAx, centroidAy, massA) = maskCentroid(frameA, background, viewportSize, viewportSize) + val pickAx = pickCentroidX(renderer) + + // Edit: shift the base +shiftWorld in x and push the new model (the render loop's updateModel path). + renderer.updateModel(shiftedModel(source)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frameB = readPixels(viewportSize, viewportSize) + val (centroidBx, centroidBy, massB) = maskCentroid(frameB, background, viewportSize, viewportSize) + val pickBx = pickCentroidX(renderer) + + println( + "[geometry-reupload] $label: massA=$massA massB=$massB dx=${centroidBx - centroidAx} " + + "(expected $shiftWorld) dy=${centroidBy - centroidAy} pickDx=${pickBx - pickAx}", + ) + assertTrue(massA > 1000, "$label: frame A drew too little art (mass $massA) - the probe did not render") + assertTrue(massB > 1000, "$label: frame B drew too little art (mass $massB)") + // The whole quad translated rigidly, so its pixel centroid shifts by exactly the world delta at + // zoom 1. A generous tolerance covers anti-aliased edge pixels near the flat-color threshold. + assertEquals(shiftWorld, centroidBx - centroidAx, 4f, "$label: art did not move by the edited base delta") + assertTrue(abs(centroidBy - centroidAy) < 4f, "$label: art drifted in y (${centroidBy - centroidAy})") + // Pick geometry must follow the edit too (world x unchanged by the global Y-flip). + assertEquals(shiftWorld, pickBx - pickAx, 0.5f, "$label: pick geometry did not follow the base edit") + } + + /** The mean world-space x of the probe's current pick geometry (the CPU deform runs against currentModel). */ + private fun pickCentroidX(renderer: PuppetRenderer): Float { + val positions = renderer.pickGeometry()?.worldPositions?.getValue(probeId) ?: return Float.NaN + var sum = 0f + var vertexCount = 0 + var coordIndex = 0 + while (coordIndex + 1 < positions.size) { + sum += positions[coordIndex] + vertexCount++ + coordIndex += 2 + } + return sum / vertexCount + } + + /** + * The pixel centroid (col, row) of the art, isolated as every pixel that differs from [background] by + * more than a flat threshold on any channel, plus the count of such pixels (the art's covered area). + */ + private fun maskCentroid(frame: ByteBuffer, background: ByteBuffer, width: Int, height: Int): Triple { + val threshold = 20 + var sumX = 0.0 + var sumY = 0.0 + var count = 0 + for (row in 0 until height) { + for (col in 0 until width) { + val pixel = (row * width + col) * 4 + val deltaRed = abs((frame.get(pixel).toInt() and 0xFF) - (background.get(pixel).toInt() and 0xFF)) + val deltaGreen = abs((frame.get(pixel + 1).toInt() and 0xFF) - (background.get(pixel + 1).toInt() and 0xFF)) + val deltaBlue = abs((frame.get(pixel + 2).toInt() and 0xFF) - (background.get(pixel + 2).toInt() and 0xFF)) + if (maxOf(deltaRed, deltaGreen, deltaBlue) > threshold) { + sumX += col + sumY += row + count++ + } + } + } + if (count == 0) { + return Triple(0f, 0f, 0) + } + return Triple((sumX / count).toFloat(), (sumY / count).toFloat(), count) + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows; consistent A vs B). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } + + /** Creates and binds an RGBA8 offscreen framebuffer to render the puppet into for read-back. */ + private fun createColorFbo(width: Int, height: Int): Int { + val framebuffer = GL30.glGenFramebuffers() + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + val colorTexture = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, colorTexture) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null as ByteBuffer?) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR) + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0) + return framebuffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GpuDeformValidationTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GpuDeformValidationTest.kt new file mode 100644 index 0000000..bf2eb6f --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GpuDeformValidationTest.kt @@ -0,0 +1,381 @@ +package org.umamo.render.gl + +import org.junit.Assume +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL12 +import org.lwjgl.opengl.GL13 +import org.lwjgl.opengl.GL15 +import org.lwjgl.opengl.GL20 +import org.lwjgl.opengl.GL30 +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.render.eval.DeformerWorld +import org.umamo.render.eval.MeshBlendState +import org.umamo.render.eval.RotationWorld +import org.umamo.render.eval.WarpWorld +import org.umamo.render.eval.deformMeshWorldFromCorners +import org.umamo.render.eval.preparePose +import org.umamo.render.glsl.GlslDialect +import org.umamo.render.glsl.tfDeformVertexShader +import org.umamo.render.glsl.tfDiscardFragmentShader +import org.umamo.render.puppet.blendColumnLayout +import org.umamo.render.puppet.buildDeltaTexelsWithBlend +import org.umamo.runtime.eval.WeightedCell +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Differential validation that the GPU deform shader matches the CPU evaluator per vertex. Runs the + * shipped [DEFORM_GLSL] (the exact body [PuppetRenderer] uses) in a headless GL context with transform + * feedback capturing each vertex's world position, then diffs against [deformMeshWorldFromCorners] (the CPU + * deform, pre-glue) for the same pose. Bounded-ULP is the bar - float32 GPU vs float32 CPU diverge slightly + * by construction. Glue is excluded (the GPU path skips it), so this compares the morph + cascade math only. + * + * Gated on `-Dcmo3.sample` and on a usable GL context, both via JUnit assumptions - so an ungated run + * reports SKIPPED rather than passing green having asserted nothing. That distinction matters here more + * than anywhere: this is the only pin on the deform math, and a Metal port will check itself against it. + * Run: `./gradlew :render:jvmTest -Dcmo3.sample=… --tests *GpuDeformValidationTest`. + */ +class GpuDeformValidationTest { + // Per-coordinate bound in Umamo canvas units (~4500 across the canvas, so this is well sub-pixel). It + // tolerates float32 GPU-vs-CPU rounding and the shader's approximate out-of-grid warp extrapolation. + private val toleranceUnits = 0.5 + + @Test + fun gpuDeformMatchesCpuPerVertex() { + val file = File(System.getProperty("cmo3.sample") ?: "") + Assume.assumeTrue("[gpu-tf] no -Dcmo3.sample corpus model", file.isFile) + requireHeadlessGl("[gpu-tf]") + val root = Cmo3.read(file).root as? CModelSource ?: return + val model = Cmo3Import.fromModelSource(root) + val program = linkTransformFeedbackProgram() + GL20.glUseProgram(program) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "deltaTex"), 0) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "cpTex"), 1) + + val drawableById = model.drawables.associateBy { it.id } + // Rest plus deformed poses that push warp-bound vertices out of the lattice, exercising warpExtrap. + val poses = + listOf( + "rest" to emptyMap(), + "body" to + mapOf( + ParameterId("ParamBodyAngleX") to 30f, + ParameterId("ParamBodyAngleY") to -25f, + ParameterId("ParamBodyAngleZ") to 10f, + ), + "tail" to + mapOf( + ParameterId("Param_Angle_Rotation") to 25.58f, + ParameterId("Param_Angle_Rotation2") to 35.51f, + ParameterId("Param_Angle_Rotation3") to 43.31f, + ), + ) + var maxError = 0.0 + var worstMesh = "" + var worstPose = "" + var meshesChecked = 0 + for ((poseName, parameters) in poses) { + val inputs = preparePose(model, parameters) + for (drawableInputs in inputs.drawables) { + val corners = drawableInputs.corners ?: continue + if (drawableInputs.isParented && drawableInputs.parentWorld == null) { + continue + } + val drawable = drawableById[drawableInputs.drawableId] ?: continue + val grid = drawable.geometryGrid ?: continue + val base = drawable.mesh?.positions ?: continue + if (drawable.mesh?.indices?.isEmpty() != false) { + continue // renderer skips index-less meshes (glue anchors) + } + val cpuWorld = deformMeshWorldFromCorners(grid, base, corners, drawableInputs.parentWorld) + val gpuWorld = gpuDeform(program, base, grid, corners, drawableInputs.parentWorld) + var meshMax = 0.0 + for (coordIndex in cpuWorld.indices) { + meshMax = maxOf(meshMax, abs(cpuWorld[coordIndex] - gpuWorld[coordIndex]).toDouble()) + } + if (meshMax > maxError) { + maxError = meshMax + worstMesh = drawableInputs.drawableId.raw + worstPose = poseName + } + meshesChecked++ + } + } + println("[gpu-tf] checked $meshesChecked mesh-poses; max GPU-vs-CPU per-coord error = ${"%.5f".format(maxError)} units (worst $worstMesh @ $worstPose)") + assertTrue(meshesChecked > 0, "no meshes were validated") + assertTrue(maxError < toleranceUnits, "GPU deform diverges from CPU by $maxError units at $worstMesh @ $worstPose (> $toleranceUnits)") + } + + /** + * The blend-shape leg of the same lockstep pin: on the Model A blend-shape corpus model, drawables + * with active blend contributions must deform identically on CPU (deformMeshWorldFromCorners + * with MeshBlendState) and GPU (appended delta columns + blendCell/blendWeight uniforms). + * Gated on Model A in `-Dcmo3.probe` and on a usable GL context. + */ + @Test + fun gpuBlendDeformMatchesCpuOnModelA() { + val modelAFile = + System.getProperty("cmo3.probe")?.split(',')?.map(::File) + ?.firstOrNull { it.isFile && it.name.startsWith("modelA") } + Assume.assumeTrue("[gpu-tf] no Model A blend-shape model in -Dcmo3.probe", modelAFile != null) + requireHeadlessGl("[gpu-tf]") + val root = Cmo3.read(modelAFile!!).root as? CModelSource ?: return + val model = Cmo3Import.fromModelSource(root) + val defaults = model.parameters.associate { it.id to it.default } + val defaultValue: (ParameterId) -> Float = { defaults[it] ?: 0f } + val program = linkTransformFeedbackProgram() + GL20.glUseProgram(program) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "deltaTex"), 0) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "cpTex"), 1) + + val drawableById = model.drawables.associateBy { it.id } + val poses = + listOf( + "eyeSize" to mapOf(ParameterId("ParamEyeSize") to -1f), + "eyeHalf" to mapOf(ParameterId("ParamEyeSize") to -0.5f), + "bodyX2" to mapOf(ParameterId("ParamBodyAngleX2") to 10f), + ) + var maxError = 0.0 + var blendMeshesChecked = 0 + for ((poseName, parameters) in poses) { + val inputs = preparePose(model, parameters) + for (drawableInputs in inputs.drawables) { + val blend = drawableInputs.blend ?: continue + if (blend.contributions.isEmpty()) { + continue + } + val corners = drawableInputs.corners ?: continue + if (drawableInputs.isParented && drawableInputs.parentWorld == null) { + continue + } + val drawable = drawableById[drawableInputs.drawableId] ?: continue + val grid = drawable.geometryGrid ?: continue + val base = drawable.mesh?.positions ?: continue + if (drawable.mesh?.indices?.isEmpty() != false) { + continue + } + val cpuWorld = deformMeshWorldFromCorners(grid, base, corners, drawableInputs.parentWorld, blend) + val gpuWorld = + gpuDeform(program, base, grid, corners, drawableInputs.parentWorld, drawable, blend, defaultValue) + for (coordIndex in cpuWorld.indices) { + maxError = maxOf(maxError, abs(cpuWorld[coordIndex] - gpuWorld[coordIndex]).toDouble()) + } + blendMeshesChecked++ + } + } + println("[gpu-tf] blend: checked $blendMeshesChecked blend mesh-poses; max error = ${"%.5f".format(maxError)} units") + assertTrue(blendMeshesChecked > 0, "no blend-shaped meshes were validated") + assertTrue(maxError < toleranceUnits, "GPU blend deform diverges from CPU by $maxError units") + } + + /** + * Deforms one mesh on the GPU and reads back its world positions via transform feedback: builds the + * delta texture (+ warp control-point texture), sets the per-pose corner/transform uniforms, draws the + * vertices as points with the rasterizer discarded, and returns the captured interleaved x,y. + */ + private fun gpuDeform( + program: Int, + base: FloatArray, + grid: KeyformGrid, + corners: List, + parent: DeformerWorld?, + blendDrawable: Drawable? = null, + blend: MeshBlendState? = null, + defaultValue: ((ParameterId) -> Float)? = null, + ): FloatArray { + val vertexCount = base.size / 2 + val cellCount = maxOf(1, grid.axes.fold(1) { count, axis -> count * axis.keys.size }) + + val vao = GL30.glGenVertexArrays() + GL30.glBindVertexArray(vao) + val baseBuffer = BufferUtils.createFloatBuffer(base.size) + baseBuffer.put(base).flip() + val baseVbo = GL15.glGenBuffers() + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, baseVbo) + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, baseBuffer, GL15.GL_STATIC_DRAW) + GL20.glEnableVertexAttribArray(0) + GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 2 * Float.SIZE_BYTES, 0L) + + GL13.glActiveTexture(GL13.GL_TEXTURE0) + // With blend bindings, the texture carries the appended blend columns (the shipped path). + val blendLayout = + if (blendDrawable != null && blendDrawable.blendShapes.isNotEmpty() && defaultValue != null) { + blendColumnLayout(blendDrawable, cellCount) + } else { + null + } + val deltaTexture = + if (blendLayout != null && defaultValue != null && blendDrawable != null) { + val texels = buildDeltaTexelsWithBlend(grid, blendDrawable, defaultValue, vertexCount, blendLayout) + val data = BufferUtils.createFloatBuffer(texels.size) + data.put(texels).flip() + val texture = nearestTexture() + GL11.glTexImage2D( + GL11.GL_TEXTURE_2D, + 0, + GL30.GL_RG32F, + cellCount + blendLayout.blendColumnCount, + vertexCount, + 0, + GL30.GL_RG, + GL11.GL_FLOAT, + data, + ) + texture + } else { + uploadDeltaTexture(grid, vertexCount, cellCount) + } + + setCornerUniforms(program, corners) + // Blend uniforms are set EVERY call (the program persists across meshes; a stale nonzero + // blendCount from a previous mesh would corrupt a binding-free one). + var blendCount = 0 + if (blend != null && blendLayout != null) { + val blendCells = IntArray(org.umamo.render.glsl.MAX_BLEND_CORNERS) + val blendWeights = FloatArray(org.umamo.render.glsl.MAX_BLEND_CORNERS) + for (contribution in blend.contributions) { + if (blendCount >= org.umamo.render.glsl.MAX_BLEND_CORNERS) { + break + } + val column = blendLayout.columnOf(contribution.bindingIndex, contribution.keyIndex) ?: continue + blendCells[blendCount] = column + blendWeights[blendCount] = contribution.weight + blendCount++ + } + GL20.glUniform1iv(GL20.glGetUniformLocation(program, "blendCell"), blendCells) + GL20.glUniform1fv(GL20.glGetUniformLocation(program, "blendWeight"), blendWeights) + } + GL20.glUniform1i(GL20.glGetUniformLocation(program, "blendCount"), blendCount) + when (val parentWorld = parent) { + is RotationWorld -> { + val xform = parentWorld.xform + GL20.glUniform1fv( + GL20.glGetUniformLocation(program, "rot"), + floatArrayOf(xform.c12, xform.c13, xform.c14, xform.c15, xform.ox, xform.oy), + ) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "parentType"), 1) + } + is WarpWorld -> { + GL13.glActiveTexture(GL13.GL_TEXTURE1) + uploadControlPointTexture(parentWorld) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "warpCols"), parentWorld.cols) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "warpRows"), parentWorld.rows) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "warpBilinear"), if (parentWorld.bilinear) 1 else 0) + GL20.glUniform1i(GL20.glGetUniformLocation(program, "parentType"), 2) + } + else -> GL20.glUniform1i(GL20.glGetUniformLocation(program, "parentType"), 0) + } + + val feedbackBuffer = GL15.glGenBuffers() + GL30.glBindBufferBase(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, feedbackBuffer) + GL15.glBufferData(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, (vertexCount * 2 * Float.SIZE_BYTES).toLong(), GL15.GL_STATIC_READ) + + GL11.glEnable(GL30.GL_RASTERIZER_DISCARD) + GL30.glBeginTransformFeedback(GL11.GL_POINTS) + GL11.glDrawArrays(GL11.GL_POINTS, 0, vertexCount) + GL30.glEndTransformFeedback() + GL11.glDisable(GL30.GL_RASTERIZER_DISCARD) + GL11.glFinish() + + val out = FloatArray(vertexCount * 2) + val readBuffer = BufferUtils.createFloatBuffer(vertexCount * 2) + GL15.glGetBufferSubData(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0L, readBuffer) + readBuffer.get(out) + + GL15.glDeleteBuffers(feedbackBuffer) + GL15.glDeleteBuffers(baseVbo) + GL11.glDeleteTextures(deltaTexture) + GL30.glDeleteVertexArrays(vao) + return out + } + + /** Uploads the per-keyform-cell vertex deltas as an RG32F texture (col = cell, row = vertex), matching + * [PuppetRenderer]'s layout so the test exercises the renderer's real delta indexing. */ + private fun uploadDeltaTexture(grid: KeyformGrid, vertexCount: Int, cellCount: Int): Int { + val cells = cellsByLinearIndex(grid) + val data = BufferUtils.createFloatBuffer(vertexCount * cellCount * 2) + for (vertexIndex in 0 until vertexCount) { + for (cellIndex in 0 until cellCount) { + val deltas = cells[cellIndex]?.form?.positionDeltas + if (deltas != null && vertexIndex * 2 + 1 < deltas.size) { + data.put(deltas[vertexIndex * 2]).put(deltas[vertexIndex * 2 + 1]) + } else { + data.put(0f).put(0f) + } + } + } + data.flip() + val texture = nearestTexture() + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_RG32F, cellCount, vertexCount, 0, GL30.GL_RG, GL11.GL_FLOAT, data) + return texture + } + + private fun uploadControlPointTexture(warp: WarpWorld): Int { + val buffer = BufferUtils.createFloatBuffer(warp.cp.size) + buffer.put(warp.cp).flip() + val texture = nearestTexture() + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_RG32F, warp.cols + 1, warp.rows + 1, 0, GL30.GL_RG, GL11.GL_FLOAT, buffer) + return texture + } + + private fun nearestTexture(): Int { + val texture = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE) + return texture + } + + private fun setCornerUniforms(program: Int, corners: List) { + val cornerCount = minOf(16, corners.size) + val cellBuffer = BufferUtils.createIntBuffer(cornerCount) + val weightBuffer = BufferUtils.createFloatBuffer(cornerCount) + for (cornerIndex in 0 until cornerCount) { + cellBuffer.put(corners[cornerIndex].linearIndex) + weightBuffer.put(corners[cornerIndex].weight) + } + cellBuffer.flip() + weightBuffer.flip() + GL20.glUniform1i(GL20.glGetUniformLocation(program, "cornerCount"), cornerCount) + GL20.glUniform1iv(GL20.glGetUniformLocation(program, "cornerCell"), cellBuffer) + GL20.glUniform1fv(GL20.glGetUniformLocation(program, "cornerWeight"), weightBuffer) + } + + /** Compiles the deform vertex shader (shared [DEFORM_GLSL]) capturing `outWorld` via transform feedback, + * plus a no-op fragment shader (the rasterizer is discarded). */ + private fun linkTransformFeedbackProgram(): Int { + val vertexShader = compileShader(GL20.GL_VERTEX_SHADER, tfDeformVertexShader(GlslDialect.Core330)) + val fragmentShader = compileShader(GL20.GL_FRAGMENT_SHADER, tfDiscardFragmentShader(GlslDialect.Core330)) + val program = GL20.glCreateProgram() + GL20.glAttachShader(program, vertexShader) + GL20.glAttachShader(program, fragmentShader) + GL30.glTransformFeedbackVaryings(program, arrayOf("outWorld"), GL30.GL_INTERLEAVED_ATTRIBS) + GL20.glLinkProgram(program) + check(GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) != GL11.GL_FALSE) { + "TF program link failed: ${GL20.glGetProgramInfoLog(program)}" + } + return program + } + + private fun compileShader(stage: Int, source: String): Int { + val shader = GL20.glCreateShader(stage) + GL20.glShaderSource(shader, source) + GL20.glCompileShader(shader) + check(GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) != GL11.GL_FALSE) { + "shader compile failed: ${GL20.glGetShaderInfoLog(shader)}" + } + return shader + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GpuGlueValidationTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GpuGlueValidationTest.kt new file mode 100644 index 0000000..0c675ce --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GpuGlueValidationTest.kt @@ -0,0 +1,224 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.eval.applyCpuDeform +import org.umamo.render.eval.preparePose +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.GluePair +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Differential validation that the GPU's two-pass glue weld reaches the screen where the CPU oracle says + * it should - the first coverage the GPU glue path has ever had. + * + * [GpuDeformValidationTest]'s docblock is explicit that it excludes glue ("the GPU path skips it"), and + * `GlueTest` / `GlueCorpusTest` only exercise the CPU [applyGluesResolved]. So until this test, nothing + * checked the parts that are unique to the GPU path and easiest to get wrong: the per-vertex glue + * attribute layout ([PuppetRenderer]'s `buildGlueAttributes` - partner GLOBAL index, glue index, weld + * weight), the shared position buffer's per-mesh base offsets, the pass-1 transform-feedback deform, and + * the pass-2 weld shader's partner lookup. A wrong base offset or a swapped partner index welds a vertex + * toward garbage, and no existing test would have noticed. + * + * The probe is built so the weld's effect is unmissable rather than a sub-pixel nudge. Two quads sit far + * apart with a gap between them; the glue pulls mesh B's left edge all the way onto mesh A's right edge + * (weightB = 1), so a working weld stretches B across the gap and a broken one leaves it where it was. + * Mesh A is deliberately INDEX-LESS - a pure weld anchor that draws nothing - which both makes B's drawn + * extent unambiguous (nothing else is on screen) and exercises the anchor path, since an index-less mesh + * is skipped at upload unless it is glued. + * + * The assertion is against [applyCpuDeform], not a hardcoded pixel: the CPU oracle (which welds via + * `applyGluesResolved`) says where B's leftmost vertex lands, and the render must agree within a pixel. + * Bounded-pixel is the bar, per the geometry fidelity tier - never bit-identical. + * + * GPU グルー(2 パス)の溶接が CPU オラクルと一致することを検証する。GPU 側の初のグルー被覆。 + */ +class GpuGlueValidationTest { + private val viewportSize = 400 + private val paramA = ParameterId("A") + private val anchorId = DrawableId("glue_anchor_a") + private val weldedId = DrawableId("glue_welded_b") + + // A pure-black backdrop, so "art" is simply "not black" and no grid line can be mistaken for coverage. + private val blackGrid = GridColors(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + + // Mesh A: the weld anchor, x in [-120, -60]. Vertices 1 and 3 are its RIGHT edge (x = -60). + private val anchorPositions = floatArrayOf(-120f, -30f, -60f, -30f, -120f, 30f, -60f, 30f) + + // Mesh B: the welded quad, x in [60, 120]. Vertices 0 and 2 are its LEFT edge (x = 60). + private val weldedPositions = floatArrayOf(60f, -30f, 120f, -30f, 60f, 30f, 120f, 30f) + + /** A single-cell keyform grid with zero deltas - the mesh sits at its rest positions. */ + private fun restGrid(positions: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ) + + private fun drawable(id: DrawableId, positions: FloatArray, indices: IntArray): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), indices), + geometryGrid = restGrid(positions), + ) + + /** + * The two-quad probe. With [welded] the glue drags B's left edge onto A's right edge; without it the + * same two meshes sit apart, which is the control the weld is measured against. + */ + private fun model(welded: Boolean): PuppetModel { + // The anchor carries NO indices: it draws nothing and exists only as a weld partner. + val anchor = drawable(anchorId, anchorPositions, IntArray(0)) + val welded2 = drawable(weldedId, weldedPositions, intArrayOf(0, 1, 2, 1, 3, 2)) + // weightA = 0 pins the anchor in place; weightB = 1 moves B's seam vertex fully onto its partner. + // Pair B's left-edge vertices (0, 2) with A's right-edge vertices (1, 3) at matching y. + val glues = + if (welded) { + listOf( + Glue( + meshA = anchorId, + meshB = weldedId, + // No intensity track, so the static default of 1 (full weld) applies. + pairs = listOf(GluePair(1, 0, 0f, 1f), GluePair(3, 2, 0f, 1f)), + ), + ) + } else { + emptyList() + } + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(anchor, welded2), + rootChildren = listOf(OrgChild.Drawable(anchor.id), OrgChild.Drawable(welded2.id)), + rootPartId = null, + glues = glues, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + } + + @Test + fun gpuGlueWeldMatchesTheCpuOracle() { + requireHeadlessGl("[gpu-glue]") + val welded = artColumnExtent(model(welded = true)) + val control = artColumnExtent(model(welded = false)) + + // Where the CPU oracle - which welds through applyGluesResolved - puts B's edges. + val expectedWelded = cpuColumnExtent(model(welded = true)) + val expectedControl = cpuColumnExtent(model(welded = false)) + println("[gpu-glue] welded: gpu=$welded cpu=$expectedWelded | control: gpu=$control cpu=$expectedControl") + + // The control first: if this drifts, the probe itself is wrong and the welded case proves nothing. + assertExtentMatches("unwelded", control, expectedControl) + // The weld must actually move B, not merely agree with a CPU oracle that also did nothing. + assertTrue( + expectedWelded.first < expectedControl.first - 50, + "probe sanity: the CPU oracle's weld must move B's left edge a long way left", + ) + assertExtentMatches("welded", welded, expectedWelded) + } + + /** + * Asserts a rendered column extent matches the CPU oracle's within a pixel. + * + * BOTH edges are checked, not just the welded one. The right edge is what catches an addressing bug + * that is self-consistent but out of bounds - a uniformly shifted base offset moves the writes, the + * own-reads, and the partner-reads together, so the welded edge still lands correctly and only the + * mesh's last vertex runs off the end of the shared buffer. A left-edge-only probe is blind to it. + */ + private fun assertExtentMatches(label: String, actual: Pair, expected: Pair) { + assertTrue( + abs(actual.first - expected.first) <= 1, + "$label: B's left edge must land where the CPU oracle says (gpu ${actual.first} vs cpu ${expected.first})", + ) + assertTrue( + abs(actual.second - expected.second) <= 1, + "$label: B's right edge must land where the CPU oracle says (gpu ${actual.second} vs cpu ${expected.second})", + ) + } + + /** The CPU oracle's (leftmost, rightmost) column across mesh B's welded vertices. */ + private fun cpuColumnExtent(source: PuppetModel): Pair { + val geometry = applyCpuDeform(source, preparePose(source, emptyMap())) + val world = geometry.worldPositions[weldedId] ?: error("mesh B produced no geometry") + var minX = Float.MAX_VALUE + var maxX = -Float.MAX_VALUE + var coordIndex = 0 + while (coordIndex < world.size) { + minX = minOf(minX, world[coordIndex]) + maxX = maxOf(maxX, world[coordIndex]) + coordIndex += 2 + } + // The rightmost COVERED column is the last one inside the edge, hence the -1 against the exclusive edge. + return worldXToColumn(minX) to worldXToColumn(maxX) - 1 + } + + /** World x → framebuffer column, at the fixed 1:1 camera centerd on the world origin. */ + private fun worldXToColumn(worldX: Float): Int = ((worldX + viewportSize / 2f)).toInt() + + /** Renders [source] and returns the (leftmost, rightmost) column carrying drawn art at mid height. */ + private fun artColumnExtent(source: PuppetModel): Pair { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setGrid(blackGrid, 100f, 10) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setPose(emptyMap()) + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frame = readPixels(viewportSize, viewportSize) + // Scan the row through world y = 0, where both quads are at full height. + val row = viewportSize / 2 + val artColumns = (0 until viewportSize).filter { isArt(frame, it, row) } + check(artColumns.isNotEmpty()) { "the probe drew nothing at all - mesh B never reached the framebuffer" } + return artColumns.first() to artColumns.last() + } + + /** True when the pixel carries drawn art rather than the (pure black) backdrop. */ + private fun isArt(frame: ByteBuffer, column: Int, row: Int): Boolean { + val pixel = (row * viewportSize + column) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + return maxOf(red, green, blue) > 24 + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GridBackdropRenderTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GridBackdropRenderTest.kt new file mode 100644 index 0000000..1f46eaa --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/GridBackdropRenderTest.kt @@ -0,0 +1,158 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Proves the world-aligned grid backdrop rasterizes its major lines at world coordinates that are + * multiples of the grid scale (anchored at world origin 0, where the grid snap also rounds) and that the + * lines scale with the camera zoom. Drives the grid with a high-contrast palette (black background, red + * major lines, black minor lines with a single subdivision) so a red column pinpoints a major line. At + * a 1:1 camera centered on the origin the line at world x = 0 lands at the viewport center and the lines + * at x = +-scale land scale pixels either side, while a non-multiple column stays background. Doubling + * the zoom halves the on-screen gap between lines. Self-skips in a display-less environment, like + * [WorldAxisLinesTest]. + */ +class GridBackdropRenderTest { + private val viewportSize = 400 + private val gridScale = 100f + private val paramA = ParameterId("A") + + // A small keyed quad tucked into a corner so its pixels never overlap the sampled center rows/columns. + private fun model(originX: Float = 0f, originZ: Float = 0f): PuppetModel { + val positions = floatArrayOf(150f, 150f, 180f, 150f, 150f, 180f, 180f, 180f) + val drawable = + Drawable( + id = DrawableId("probe"), + name = "probe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2, 1, 3, 2)), + geometryGrid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size))))), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = originX, + worldOriginZ = originZ, + ) + } + + // Black background, red major lines, black minor lines; one subdivision so only the major lines show. + private fun highContrastGrid(renderer: PuppetRenderer) { + renderer.setGrid(GridColors(0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f), gridScale, subdivisions = 1) + } + + @Test + fun majorLinesLandOnWorldMultiplesAndScaleWithZoom() { + requireHeadlessGl("[grid-backdrop]") + val device = GlRenderDevice() + val renderer = PuppetRenderer(model(), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + highContrastGrid(renderer) + renderer.setPose(emptyMap()) + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + + // 1:1 camera centered on the world origin: world x = 0 is the center column, x = +-scale sit scale + // pixels either side. Sample a row OFF the horizontal y = 0 line (else every column reads that + // line's red) and clear of the corner probe quad. + val center = viewportSize / 2 + val row = center + gridScale.toInt() / 2 // world y = ~half a cell: no horizontal line here + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frame = readPixels(viewportSize, viewportSize) + assertTrue(hasRedNear(frame, center, row), "a major line at world x = 0 lands at the viewport center") + assertTrue(hasRedNear(frame, center - gridScale.toInt(), row), "a major line at world x = -scale") + assertTrue(hasRedNear(frame, center + gridScale.toInt(), row), "a major line at world x = +scale") + assertTrue(!hasRedNear(frame, center + gridScale.toInt() / 2, row, radius = 2), "no line at a non-multiple (x = scale/2)") + + // Double the zoom: the lines spread apart on screen. The world-0 line stays centered, while the + // column one scale out (a line at 1x) becomes a mid-cell gap at 2x - the on-screen spacing doubled. + renderer.setCamera(ViewportCamera(0f, 0f, 2f)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val zoomed = readPixels(viewportSize, viewportSize) + assertTrue(hasRedNear(zoomed, center, row), "the world-0 line stays centered under zoom") + assertTrue(!hasRedNear(zoomed, center + gridScale.toInt(), row, radius = 3), "the 1x line position is now a gap at 2x zoom") + } + + @Test + fun majorLineFollowsWorldOrigin() { + requireHeadlessGl("[grid-backdrop]") + // Offset the world origin by half a major cell (a mid-division case): the grid must anchor on the + // origin, so the major line lands there, NOT at world 0. + val halfCell = gridScale / 2f + val device = GlRenderDevice() + val renderer = PuppetRenderer(model(originX = halfCell, originZ = 0f), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + highContrastGrid(renderer) + renderer.setPose(emptyMap()) + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frame = readPixels(viewportSize, viewportSize) + val center = viewportSize / 2 + val row = center + gridScale.toInt() / 4 // off the horizontal origin line + assertTrue(hasRedNear(frame, center + halfCell.toInt(), row), "the major line lands on the offset world origin") + assertTrue(!hasRedNear(frame, center, row, radius = 3), "world x = 0 is a mid-cell gap when the origin is offset") + } + + /** True when any pixel within [radius] columns of [col] on [row] reads clearly red (a major grid line). */ + private fun hasRedNear(frame: ByteBuffer, col: Int, row: Int, radius: Int = 2): Boolean { + for (probe in col - radius..col + radius) { + if (probe < 0 || probe >= viewportSize) { + continue + } + val pixel = (row * viewportSize + probe) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + if (red > green + 60 && red > blue + 60) { + return true + } + } + return false + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/HeadlessGlGate.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/HeadlessGlGate.kt new file mode 100644 index 0000000..51b3176 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/HeadlessGlGate.kt @@ -0,0 +1,190 @@ +package org.umamo.render.gl + +import org.junit.Assume +import org.lwjgl.glfw.GLFW +import org.lwjgl.glfw.GLFWErrorCallback +import org.lwjgl.opengl.GL +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL13 +import org.lwjgl.opengl.GL14 +import org.lwjgl.opengl.GL15 +import org.lwjgl.opengl.GL20 +import org.lwjgl.opengl.GL21 +import org.lwjgl.opengl.GL30 +import org.lwjgl.opengl.GL31 +import org.lwjgl.system.MemoryUtil + +// Set by CI (-Dumamo.requireGl=true) to make a missing GL context a hard failure instead of a skip. +private const val REQUIRE_GL_PROPERTY = "umamo.requireGl" + +// Tries per acquisition. Context creation under CI's Xvfb + Mesa software GL fails intermittently, and +// one shared context means a single unlucky attempt would strand every GL test in the module. +private const val ACQUIRE_ATTEMPT_LIMIT = 3 + +// The hidden window is 1x1, so its default framebuffer - and a freshly created context's viewport - is +// 1x1. Restoring that is what makes a reused context indistinguishable from a new one. +private const val HIDDEN_WINDOW_SIZE = 1 + +// The process-wide context: created on first use, then kept current for the JVM's lifetime. +private var sharedGlWindow: Long = MemoryUtil.NULL +private var sharedGlAttempted = false +private var acquireFailureReason: String? = null +private var lastGlfwErrorText: String? = null + +/** + * Prepares the shared headless GL context for a test, skipping the test when there is none. + * + * One context serves the whole module, created once and never terminated - the same lifetime the desktop + * app gives its own offscreen context. That is deliberate: context creation under CI's Xvfb + Mesa + * software GL fails often enough per attempt that a context per test would put three dozen independent + * chances to fail in a single run, and most runs would lose at least one. Acquiring once holds the + * exposure to one attempt, retried up to [ACQUIRE_ATTEMPT_LIMIT] times. + * + * Reuse costs the one thing a fresh context supplies for free - a clean GL state vector - so each caller + * gets [resetSharedGlState] before its body runs, leaving bindings, capabilities, and the viewport exactly + * as a new context would have them. + * + * Two behaviors on a missing context, and the difference is the whole point. On a developer machine with + * no display the test SKIPS - via a JUnit assumption, so the run reports it as skipped rather than passing + * green having asserted nothing. Under `-Dumamo.requireGl=true` (CI passes it) it is instead a hard + * FAILURE. + * + * Why both: these tests are the only thing pinning the GL renderer's behavior, and they assert on + * read-back pixels, so a context-less run covers exactly nothing. A plain skip is right locally (not + * every machine has a display) but wrong in CI, where a silent skip is indistinguishable from a pass and + * would let the entire GL suite quietly stop covering anything. CI asserts the context exists; + * developers get the skip. + * + * @param String tag The test's log tag, e.g. "[world-axis-lines]". + */ +internal fun requireHeadlessGl(tag: String) { + val window = acquireSharedGlWindow() + if (window == MemoryUtil.NULL) { + val message = "$tag no GL context (${acquireFailureReason ?: "cause not reported"})" + if (System.getProperty(REQUIRE_GL_PROPERTY).toBoolean()) { + // CI opted in: a missing context means the GL suite would cover nothing, so fail loudly. + throw AssertionError("$message, and -D$REQUIRE_GL_PROPERTY=true requires one") + } + Assume.assumeTrue(message, false) + return + } + resetSharedGlState() +} + +/** + * Returns the process-wide GL context, creating it on the first call. + * + * The outcome is cached either way: once an acquisition has failed, later callers reuse the recorded + * reason instead of paying for another round of doomed attempts. + * + * @return Long The GLFW window handle carrying the context, or MemoryUtil.NULL if none could be had. + */ +private fun acquireSharedGlWindow(): Long { + if (sharedGlAttempted) { + return sharedGlWindow + } + sharedGlAttempted = true + installGlfwErrorReporting() + for (attempt in 1..ACQUIRE_ATTEMPT_LIMIT) { + lastGlfwErrorText = null + val window = createHeadlessGlWindow() + if (window != MemoryUtil.NULL) { + sharedGlWindow = window + GLFW.glfwMakeContextCurrent(window) + GL.createCapabilities() + return sharedGlWindow + } + System.err.println("[headless-gl] attempt $attempt/$ACQUIRE_ATTEMPT_LIMIT failed: $acquireFailureReason") + } + return MemoryUtil.NULL +} + +/** + * Creates a hidden 1x1 GL 3.3 core window, recording which step failed and what GLFW said about it. + * + * The two failure modes are reported separately on purpose: glfwInit failing means the platform layer + * never came up, while glfwCreateWindow failing means it did and the context itself was refused. Those + * point at different things, and a bare null handle names neither. + * + * @return Long The GLFW window handle, or MemoryUtil.NULL on failure. + */ +private fun createHeadlessGlWindow(): Long { + if (!GLFW.glfwInit()) { + acquireFailureReason = describeAcquireFailure("glfwInit() returned false") + return MemoryUtil.NULL + } + GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE) + GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3) + GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 3) + GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE) + GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_FORWARD_COMPAT, GLFW.GLFW_TRUE) + val window = GLFW.glfwCreateWindow(HIDDEN_WINDOW_SIZE, HIDDEN_WINDOW_SIZE, "umamo-headless", MemoryUtil.NULL, MemoryUtil.NULL) + if (window == MemoryUtil.NULL) { + acquireFailureReason = describeAcquireFailure("glfwCreateWindow() returned NULL") + // glfwInit succeeded, so the platform layer is up and owes a matching terminate before a retry. + GLFW.glfwTerminate() + return MemoryUtil.NULL + } + return window +} + +/** + * Routes GLFW's diagnostics to stderr and keeps the latest one for the acquisition-failure message. + * + * Without a callback GLFW discards its error code and description entirely, which leaves a failed + * acquisition looking like an unexplained null handle. + */ +private fun installGlfwErrorReporting() { + GLFWErrorCallback + .create { errorCode, descriptionPointer -> + val text = "GLFW error 0x${errorCode.toString(16)}: ${GLFWErrorCallback.getDescription(descriptionPointer)}" + lastGlfwErrorText = text + System.err.println("[headless-gl] $text") + }.set() +} + +/** + * Joins the failing GLFW call to whatever the error callback reported for it. + * + * @param String step The GLFW call that failed, named as it appears in the source. + * @return String A one-line reason suitable for a skip message or an assertion failure. + */ +private fun describeAcquireFailure(step: String): String = "$step; ${lastGlfwErrorText ?: "no GLFW error reported"}" + +/** + * Restores the GL state vector to its post-creation defaults, so one test cannot leak state into the next. + * + * Only the state this renderer actually touches is covered - bindings, the capabilities it toggles, the + * blend and cull configuration, the pixel-transfer alignments, and the viewport. GL objects themselves + * are deliberately left alive: each test builds its own [GlRenderDevice] and the handles die with the JVM. + */ +private fun resetSharedGlState() { + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0) + GL30.glBindVertexArray(0) + GL20.glUseProgram(0) + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0) + GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0) + GL15.glBindBuffer(GL21.GL_PIXEL_PACK_BUFFER, 0) + GL15.glBindBuffer(GL31.GL_TEXTURE_BUFFER, 0) + GL30.glBindBufferBase(GL30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0) + GL13.glActiveTexture(GL13.GL_TEXTURE0) + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0) + GL11.glBindTexture(GL31.GL_TEXTURE_BUFFER, 0) + + GL11.glDisable(GL11.GL_SCISSOR_TEST) + GL11.glDisable(GL11.GL_BLEND) + GL11.glDisable(GL11.GL_CULL_FACE) + GL11.glDisable(GL11.GL_DEPTH_TEST) + GL11.glDisable(GL11.GL_STENCIL_TEST) + GL11.glDisable(GL30.GL_RASTERIZER_DISCARD) + + GL14.glBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE, GL11.GL_ZERO) + GL11.glFrontFace(GL11.GL_CCW) + GL11.glCullFace(GL11.GL_BACK) + GL11.glColorMask(true, true, true, true) + GL11.glDepthMask(true) + GL11.glClearColor(0f, 0f, 0f, 0f) + GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 4) + GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 4) + GL11.glViewport(0, 0, HIDDEN_WINDOW_SIZE, HIDDEN_WINDOW_SIZE) +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/HologramDumpTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/HologramDumpTest.kt new file mode 100644 index 0000000..d1457bd --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/HologramDumpTest.kt @@ -0,0 +1,79 @@ +package org.umamo.render.gl + +import org.junit.Assume +import org.umamo.format.moc3.Moc3 +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.SupersampledSurface +import org.umamo.render.ViewportCamera +import org.umamo.render.buildPuppetTextures +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.awt.image.BufferedImage +import java.io.File +import javax.imageio.ImageIO +import kotlin.test.Test + +/** Dumps modelA renders to PNGs (app path: supersample + grid) so they can be inspected directly. */ +class HologramDumpTest { + private val display = 768 + private val supersample = 2 + + @Test + fun dump() { + // Assume, not return: a missing precondition must report SKIPPED, never a hollow PASSED. + // HOLO_DUMP_DIR stays a skip even under -Dumamo.requireGl=true - this is an opt-in dump + // tool, and requireGl's hard-fail contract only applies once the operator has opted in. + val out = System.getenv("HOLO_DUMP_DIR").orEmpty() + Assume.assumeTrue("[holo-dump] HOLO_DUMP_DIR not set (opt-in dump tool)", out.isNotEmpty()) + val mocFile = + System.getProperty("moc3.samples")?.let(::File)?.takeIf { it.isDirectory } + ?.walkTopDown()?.firstOrNull { it.name == "modelA.moc3" } + Assume.assumeTrue("[holo-dump] no -Dmoc3.samples corpus with modelA.moc3", mocFile != null) + val atlasPng = File(mocFile!!.parentFile, "modelA.4096/texture_00.png") + requireHeadlessGl("[holo-dump]") + val mocDocument = Moc3.read(mocFile.readBytes()) + val puppet = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(mocDocument, null)) + val textures = if (atlasPng.isFile) buildPuppetTextures(listOf(atlasPng.readBytes()), mocDocument.artMeshes.associate { it.id to 0 }) else null + for (hologram in listOf(0f, 1f)) { + val rgba = render(puppet, textures, mapOf(ParameterId("ParamHologram") to hologram)) + writePng(rgba, File(out, "modelA_holo_$hologram.png")) + println("[holo-dump] wrote modelA_holo_$hologram.png") + } + } + + private fun render(source: PuppetModel, textures: PuppetTextures?, pose: Map): IntArray { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, textures ?: PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setRenderScale(supersample.toFloat()) + renderer.setGrid(GridColors.Classic, 1f, 4) + renderer.setPose(pose) + val surface = SupersampledSurface(device, supersample) + val drawTarget = surface.ensure(display, display) + val camera = ViewportCamera.fit(renderer.contentBounds(), display, display) + renderer.setCamera(camera.copy(zoom = camera.zoom * supersample)) + renderer.render(drawTarget, display * supersample, display * supersample) + surface.resolve() + val image = device.readPixels(surface.resolveTarget) + return IntArray(image.rgba.size) { image.rgba[it].toInt() and 0xFF } + } + + private fun writePng(rgba: IntArray, file: File) { + val image = BufferedImage(display, display, BufferedImage.TYPE_INT_ARGB) + var pixel = 0 + var index = 0 + while (index < rgba.size) { + val x = pixel % display + val y = pixel / display + val argb = (rgba[index + 3] shl 24) or (rgba[index] shl 16) or (rgba[index + 1] shl 8) or rgba[index + 2] + image.setRGB(x, y, argb) + pixel++ + index += 4 + } + ImageIO.write(image, "png", file) + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/MaskCoverageBlendTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/MaskCoverageBlendTest.kt new file mode 100644 index 0000000..6ee8203 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/MaskCoverageBlendTest.kt @@ -0,0 +1,125 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Pins that the mask-coverage pass forces Normal blend regardless of the mask source's own blend mode. + * + * The coverage target is cleared to alpha 0, then the mask sources are drawn into it and the masked + * drawable multiplies its alpha by that coverage. A mask source whose blend mode is Multiply or Additive + * uses alpha factors (GL_ZERO, GL_ONE), so if the coverage draw honoured that mode the target's alpha + * would stay 0 and the masked drawable would vanish entirely. The renderer must therefore draw coverage + * at Normal, not the source's mode - this test fails if that regresses (the masked quad goes black). + * + * マスク被覆パスがマスク元のブレンドモードに関わらず Normal で描くことを検証する。Multiply / Additive の + * マスク元だと被覆アルファが 0 のままになり、被マスク描画が消えてしまう回帰を捕まえる。 + */ +class MaskCoverageBlendTest { + private val viewportSize = 64 + private val paramA = ParameterId("A") + private val maskId = DrawableId("mask_source") + private val maskedId = DrawableId("masked_quad") + + // A pure-black backdrop so "the masked quad is visible" is simply "some pixel is not black". + private val blackGrid = GridColors(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f) + + // A full-viewport quad in the fixed 1:1 camera (world x,y in [-32, 32]). + private val fullQuad = floatArrayOf(-32f, -32f, 32f, -32f, -32f, 32f, 32f, 32f) + + private fun restGrid(positions: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ) + + private fun drawable(id: DrawableId, blendMode: BlendMode, maskedBy: List): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = blendMode, + maskedBy = maskedBy, + mesh = DrawableMesh(fullQuad, FloatArray(fullQuad.size), intArrayOf(0, 1, 2, 1, 3, 2)), + geometryGrid = restGrid(fullQuad), + ) + + /** A model whose mask SOURCE has the given blend mode, clipping a full-viewport masked quad. */ + private fun model(maskBlend: BlendMode): PuppetModel { + val maskSource = drawable(maskId, maskBlend, emptyList()) + val masked = drawable(maskedId, BlendMode.Normal, listOf(maskId)) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(maskSource, masked), + rootChildren = listOf(OrgChild.Drawable(maskSource.id), OrgChild.Drawable(masked.id)), + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + } + + @Test + fun maskedDrawableSurvivesAMultiplyBlendMaskSource() { + requireHeadlessGl("[mask-blend]") + // The mask source is Multiply - the mode that most clearly breaks a coverage pass that honours it. + val litColumns = renderAndCountArtColumns(model(BlendMode.MultiplyPremultiplied)) + assertTrue( + litColumns > viewportSize / 2, + "a Multiply-blend mask source must still produce coverage: the masked quad should fill the row " + + "(got $litColumns lit columns of $viewportSize)", + ) + } + + /** Renders [source] and returns how many columns of the center row carry drawn (non-black) art. */ + private fun renderAndCountArtColumns(source: PuppetModel): Int { + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setGrid(blackGrid, 100f, 10) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setPose(emptyMap()) + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.render(target, viewportSize, viewportSize) + GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, framebuffer) + val frame = BufferUtils.createByteBuffer(viewportSize * viewportSize * 4) + GL11.glReadPixels(0, 0, viewportSize, viewportSize, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, frame) + val row = viewportSize / 2 + var lit = 0 + for (column in 0 until viewportSize) { + val pixel = (row * viewportSize + column) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + if (maxOf(red, green, blue) > 16) { + lit++ + } + } + return lit + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/PuppetSnapshotRenderTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/PuppetSnapshotRenderTest.kt new file mode 100644 index 0000000..c39248d --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/PuppetSnapshotRenderTest.kt @@ -0,0 +1,320 @@ +package org.umamo.render.gl + +import org.umamo.format.moc3.Moc3 +import org.umamo.format.raster.RasterImage +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.FrameBackdrop +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.render.puppet.fallbackColorFor +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.math.roundToInt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins [PuppetRenderer.renderSnapshot]: the image capture behind Export Image and the saved thumbnail. + * + * One flat-color quad sits in the upper-right quadrant of a 200 x 200 capture at a 1:1 camera on the + * origin, so the quad covers image columns 120..180 and rows 20..80, the world axes cross at column and + * row 100, and the top-left corner is empty canvas. The quad is untextured, so it draws its fallback + * color at 0.85 alpha - a known premultiplied value to check the read-back against. + * + * Self-skips in a display-less environment (no GL context), like [SelectionTintTest]. + */ +class PuppetSnapshotRenderTest { + private val imageSize = 200 + private val paramA = ParameterId("A") + private val quadId = DrawableId("Quad") + + /** + * One flat quad spanning world x and z in [low, high]. Mesh positions are the model's own y-down space, + * which the deform flips to world z-up, so the quad's mesh y runs from -high to -low. + * + * @param DrawableId id The drawable's id. + * @param Float low The lower world x and z. + * @param Float high The upper world x and z. + * @param Float opacity The drawable's static opacity. + * @return Drawable The quad. + */ + private fun quad(id: DrawableId, low: Float, high: Float, opacity: Float = 1f): Drawable { + val positions = floatArrayOf(low, -low, high, -low, low, -high, high, -high) + return Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2, 1, 3, 2)), + // A single zero-delta keyform so the drawable is keyed; the base mesh alone drives its shape. + geometryGrid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size))))), + opacity = opacity, + ) + } + + /** + * A model over [drawables], in that order at the root. + * + * @param List drawables The drawables. + * @return PuppetModel The model. + */ + private fun modelOf(drawables: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + ) + + /** + * The one-quad model: world x and z in [20, 80]. + * + * @return PuppetModel The model. + */ + private fun quadModel(): PuppetModel = modelOf(listOf(quad(quadId, 20f, 80f))) + + /** + * A renderer over [quadModel], posed at rest, with the quad selected and active and the world axes on: + * the viewport's state, which a capture must leave out. + * + * @param GlRenderDevice device The device to render through. + * @return PuppetRenderer The renderer. + */ + private fun viewportRenderer(device: GlRenderDevice): PuppetRenderer { + val renderer = PuppetRenderer(quadModel(), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setWorldAxesVisible(true) + renderer.setShownDrawables(setOf(quadId)) + renderer.setSelection(setOf(quadId)) + renderer.setActiveSelection(quadId) + renderer.setSelectionHighlightColor(0f, 0f, 1f) + renderer.setActiveSelectionHighlightColor(0f, 0f, 1f) + renderer.setPose(emptyMap()) + return renderer + } + + /** + * One pixel's channels, 0..255. + * + * @param RasterImage image The top-first image. + * @param Int column The pixel column. + * @param Int row The pixel row from the top. + * @return List Red, green, blue, and alpha. + */ + private fun pixelAt(image: RasterImage, column: Int, row: Int): List { + val offset = (row * image.width + column) * 4 + return (0 until 4).map { channel -> image.rgba[offset + channel].toInt() and 0xFF } + } + + /** + * Asserts two channel lists agree within a tolerance. + * + * @param List expected The expected channels. + * @param List actual The read channels. + * @param Int tolerance The largest allowed difference per channel. + * @param String label What is being compared, for the failure message. + */ + private fun assertClose(expected: List, actual: List, tolerance: Int, label: String) { + val worst = expected.zip(actual).maxOf { (want, got) -> abs(want - got) } + assertTrue(worst <= tolerance, "$label: expected $expected, read $actual") + } + + /** A transparent capture leaves empty canvas clear, draws neither axis, and draws the selected quad untinted. */ + @Test + fun transparentCaptureLeavesTheCanvasClearAndDrawsNoTintOrAxes() { + requireHeadlessGl("[snapshot-transparent]") + val renderer = viewportRenderer(GlRenderDevice()) + val image = assertNotNull(renderer.renderSnapshot(ViewportCamera(0f, 0f, 1f), imageSize, imageSize, FrameBackdrop.Transparent)) + assertEquals(imageSize to imageSize, image.width to image.height) + + assertEquals(listOf(0, 0, 0, 0), pixelAt(image, 10, 10), "empty canvas is fully transparent") + // Column 100 is the world z axis and row 100 the x axis; neither is drawn without the grid. + assertEquals(listOf(0, 0, 0, 0), pixelAt(image, 100, 150), "the z axis is not drawn") + assertEquals(listOf(0, 0, 0, 0), pixelAt(image, 50, 100), "the x axis is not drawn") + + // Premultiplied: the fallback color scaled by its 0.85 alpha, untinted although the quad is selected. + val fallback = fallbackColorFor(quadId.raw) + val alpha = 0.85f + val expected = listOf(fallback[0] * alpha, fallback[1] * alpha, fallback[2] * alpha, alpha).map { channel -> (channel * 255f).roundToInt() } + assertClose(expected, pixelAt(image, 150, 50), tolerance = 2, label = "the quad, premultiplied and untinted") + } + + /** A solid capture fills the empty canvas with its color and blends the translucent quad over it. */ + @Test + fun solidCaptureFillsTheCanvasAndBlendsTheQuadOverIt() { + requireHeadlessGl("[snapshot-solid]") + val renderer = viewportRenderer(GlRenderDevice()) + val image = assertNotNull(renderer.renderSnapshot(ViewportCamera(0f, 0f, 1f), imageSize, imageSize, FrameBackdrop.Clear(1f, 0.5f, 0f, 1f))) + + assertClose(listOf(255, 128, 0, 255), pixelAt(image, 10, 10), tolerance = 1, label = "the canvas takes the fill") + val fallback = fallbackColorFor(quadId.raw) + val alpha = 0.85f + val background = listOf(1f, 0.5f, 0f) + val expected = (0 until 3).map { channel -> ((fallback[channel] * alpha + background[channel] * (1f - alpha)) * 255f).roundToInt() } + 255 + assertClose(expected, pixelAt(image, 150, 50), tolerance = 2, label = "the quad over the fill") + } + + /** A capture hands back the camera, the selection tint, and the side-target capacity the viewport had. */ + @Test + fun captureRestoresTheViewportState() { + requireHeadlessGl("[snapshot-restore]") + val device = GlRenderDevice() + val renderer = viewportRenderer(device) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + val target = device.createRenderTarget(RenderTargetSpec(imageSize, imageSize, TextureFormat.Rgba8, sampled = true)) + renderer.render(target, imageSize, imageSize) + val capacityBefore = renderer.sideTargetCapacity() + + // A capture at another camera and a far larger size: its side targets grow past the viewport's. + renderer.renderSnapshot(ViewportCamera(500f, 500f, 3f), 1200, 900, FrameBackdrop.Transparent) + val capacityAfter = renderer.sideTargetCapacity() + assertTrue( + capacityAfter.first <= capacityBefore.first && capacityAfter.second <= capacityBefore.second, + "a capture that grew the side targets releases them (before=$capacityBefore after=$capacityAfter)", + ) + + // The viewport render afterwards is the one it was: same camera (the quad where it was) and still + // tinted toward the selection blue. + renderer.render(target, imageSize, imageSize) + val viewport = device.readPixels(target) + val quadPixel = pixelAt(viewport, 150, 50) + assertTrue(quadPixel[2] > quadPixel[0] && quadPixel[2] > quadPixel[1], "the quad is still selection-tinted at its old place (read $quadPixel)") + } + + /** A capture told to stop between tiles returns nothing and still hands the viewport its state back. */ + @Test + fun anAbandonedCaptureReturnsNothingAndRestoresTheViewportState() { + requireHeadlessGl("[snapshot-abandon]") + val device = GlRenderDevice() + val renderer = viewportRenderer(device) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + val target = device.createRenderTarget(RenderTargetSpec(imageSize, imageSize, TextureFormat.Rgba8, sampled = true)) + renderer.render(target, imageSize, imageSize) + val capacityBefore = renderer.sideTargetCapacity() + + // Nine tiles; the host lets the first one through and then shuts down. + var tilesAllowed = 1 + val image = + renderer.renderSnapshot(ViewportCamera(500f, 500f, 3f), 1200, 900, FrameBackdrop.Transparent, tileEdge = 400) { + tilesAllowed-- > 0 + } + assertNull(image, "an abandoned capture has no image") + val capacityAfter = renderer.sideTargetCapacity() + assertTrue( + capacityAfter.first <= capacityBefore.first && capacityAfter.second <= capacityBefore.second, + "an abandoned capture releases the side targets it grew (before=$capacityBefore after=$capacityAfter)", + ) + + renderer.render(target, imageSize, imageSize) + val quadPixel = pixelAt(device.readPixels(target), 150, 50) + assertTrue(quadPixel[2] > quadPixel[0] && quadPixel[2] > quadPixel[1], "the quad is still selection-tinted at its old place (read $quadPixel)") + } + + /** + * A shown drawable posed at zero opacity draws nothing, so the capture's framing leaves it out. The CPU + * deform needs no context, so this runs everywhere. + */ + @Test + fun posedContentBoundsLeaveOutAZeroOpacityDrawable() { + val ghostId = DrawableId("Ghost") + val renderer = + PuppetRenderer( + modelOf(listOf(quad(quadId, 20f, 80f), quad(ghostId, 300f, 400f, opacity = 0f))), + PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), + GlRenderDevice(), + ) + renderer.setPose(emptyMap()) + val bounds = assertNotNull(renderer.posedContentBounds(setOf(quadId, ghostId))) + assertEquals(listOf(20f, 20f, 60f, 60f), listOf(bounds.minX, bounds.minY, bounds.width, bounds.height), "only the drawn quad is framed") + assertNull(renderer.posedContentBounds(setOf(ghostId)), "a pose that draws nothing has nothing to frame") + } + + /** A capture split into partial tiles matches the same capture in one piece, grid lines included. */ + @Test + fun aTiledCaptureMatchesAWholeOne() { + requireHeadlessGl("[snapshot-tiles]") + val renderer = viewportRenderer(GlRenderDevice()) + // A contrasting grid, so a seam that shifted anything by a pixel would show on its lines too. + renderer.setGrid(GridColors(0f, 0f, 0f, 1f, 1f, 1f, 0.5f, 0.5f, 0.5f), 25f, subdivisions = 5) + // Not a multiple of the tile edge in either direction, and off-center, so edge tiles are partial. + val camera = ViewportCamera(13f, -7f, 1.37f) + val whole = assertNotNull(renderer.renderSnapshot(camera, 211, 157, FrameBackdrop.Grid)) + val tiled = assertNotNull(renderer.renderSnapshot(camera, 211, 157, FrameBackdrop.Grid, tileEdge = 64)) + var worst = 0 + var worstAt = 0 + for (byteIndex in whole.rgba.indices) { + val difference = abs((whole.rgba[byteIndex].toInt() and 0xFF) - (tiled.rgba[byteIndex].toInt() and 0xFF)) + if (difference > worst) { + worst = difference + worstAt = byteIndex / 4 + } + } + assertTrue(worst <= 2, "tiles meet exactly: worst channel difference $worst at pixel (${worstAt % 211}, ${worstAt / 211})") + } + + /** + * The same seam check on a real rig, where tiles cut through masks, isolated groups, and extended-blend + * composites - each of which renders into screen-space side targets and scissors to its own bounds per + * tile. Model A carries all three. Corpus- and GL-gated: skips without Model A or a context. + */ + @Test + fun aTiledCaptureOfACorpusRigMatchesAWholeOne() { + val mocFile = + System.getProperty("moc3.samples") + ?.let(::File) + ?.takeIf { directory -> directory.isDirectory } + ?.walkTopDown() + ?.firstOrNull { candidate -> candidate.name == "modelA.moc3" } + if (mocFile == null) { + println("modelA.moc3 not present; skipping the corpus tiled-capture check") + return + } + requireHeadlessGl("[snapshot-corpus-tiles]") + val puppet = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(Moc3.read(mocFile.readBytes()), null)) + val renderer = PuppetRenderer(puppet, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), GlRenderDevice()) + renderer.initGl() + renderer.setPose(emptyMap()) + val width = 700 + val height = 900 + val camera = ViewportCamera.fit(renderer.contentBounds(), width, height) + val whole = assertNotNull(renderer.renderSnapshot(camera, width, height, FrameBackdrop.Transparent)) + val tiled = assertNotNull(renderer.renderSnapshot(camera, width, height, FrameBackdrop.Transparent, tileEdge = 128)) + + val coveredPixels = (3 until whole.rgba.size step 4).count { alphaIndex -> whole.rgba[alphaIndex].toInt() != 0 } + assertTrue(coveredPixels > width * height / 20, "the rig covers a real part of the capture ($coveredPixels pixels)") + var worst = 0 + var worstAt = 0 + for (byteIndex in whole.rgba.indices) { + val difference = abs((whole.rgba[byteIndex].toInt() and 0xFF) - (tiled.rgba[byteIndex].toInt() and 0xFF)) + if (difference > worst) { + worst = difference + worstAt = byteIndex / 4 + } + } + // A composite boundary re-quantizes to 8 bits, the same tolerance the composite parity gate allows. + assertTrue(worst <= 3, "tiles meet on the rig: worst channel difference $worst at pixel (${worstAt % width}, ${worstAt / width})") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SelectionTintTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SelectionTintTest.kt new file mode 100644 index 0000000..143e744 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SelectionTintTest.kt @@ -0,0 +1,197 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Proves the object-mode selection tint distinguishes the active (last-selected) drawable from a merely + * selected one: both are pushed as selected, one is pushed as active, and the renderer must tint the + * active one toward [PuppetRenderer.setActiveSelectionHighlightColor] (green here) while the other tints + * toward [PuppetRenderer.setSelectionHighlightColor] (blue here). Renders two separated flat-color + * quads into an offscreen FBO and asserts the active quad reads greener and less blue than the selected + * quad. Because the two quads are identical apart from which one is active, any green/blue asymmetry is + * caused solely by the active tint - so a control frame with no active drawable first asserts the two read + * alike, isolating the effect of [PuppetRenderer.setActiveSelection]. + * + * The relative comparison (active greener / less blue than selected) holds for any base drawable color: + * the active mixes toward green and the selected toward blue at the same strength, so the active's green + * channel is always the higher and its blue the lower of the pair. + * + * Self-skips in a display-less environment (no GL context), like [GeometryReuploadTest]. + */ +class SelectionTintTest { + private val viewportSize = 400 + private val paramA = ParameterId("A") + private val leftId = DrawableId("Left") + private val rightId = DrawableId("Right") + + // Two 80x80 quads: one centered at world x=-100 (screen col ~100), one at x=+100 (screen col ~300), both + // on y=0 (screen row ~200). At the 1:1 camera below they sit well apart with no pixel overlap. + private val leftPositions = floatArrayOf(-140f, -40f, -60f, -40f, -140f, 40f, -60f, 40f) + private val rightPositions = floatArrayOf(60f, -40f, 140f, -40f, 60f, 40f, 140f, 40f) + private val quadUvs = FloatArray(8) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + private fun meshAxis() = listOf(KeyformAxis(paramA, floatArrayOf(0f))) + + private fun quad(id: DrawableId, positions: FloatArray): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions.copyOf(), quadUvs, quadIndices), + // A single zero-delta keyform so the drawable is "keyed" (an unkeyed drawable is skipped by the + // renderer); the base mesh alone drives its shape. + geometryGrid = KeyformGrid(meshAxis(), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size))))), + ) + + private fun twoQuadModel(): PuppetModel { + val left = quad(leftId, leftPositions) + val right = quad(rightId, rightPositions) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(left, right), + rootChildren = listOf(OrgChild.Drawable(left.id), OrgChild.Drawable(right.id)), + rootPartId = null, + ) + } + + @Test + fun activeDrawableTintsApartFromSelected() { + requireHeadlessGl("[selection-tint]") + val model = twoQuadModel() + val device = GlRenderDevice() + val renderer = PuppetRenderer(model, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // A fixed 1:1 camera centered on the origin, so one world unit == one screen pixel: the left quad + // lands at col ~100, the right at ~300, both at row ~200. + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setShownDrawables(setOf(leftId, rightId)) + renderer.setSelection(setOf(leftId, rightId)) + // Saturated pure colors so the active/selected channels are unambiguous in the read-back. + renderer.setSelectionHighlightColor(0f, 0f, 1f) + renderer.setActiveSelectionHighlightColor(0f, 1f, 0f) + + // Control: no active drawable, so both quads tint toward the same selection blue and read alike. + renderer.setActiveSelection(null) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val control = readPixels(viewportSize, viewportSize) + val controlLeft = averageColor(control, leftScreenCol, quadScreenRow) + val controlRight = averageColor(control, rightScreenCol, quadScreenRow) + + // The left quad is now the active one; it must tint toward green, the right stays selection blue. + renderer.setActiveSelection(leftId) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val active = readPixels(viewportSize, viewportSize) + val activeLeft = averageColor(active, leftScreenCol, quadScreenRow) + val selectedRight = averageColor(active, rightScreenCol, quadScreenRow) + + println( + "[selection-tint] control L=$controlLeft R=$controlRight | active L=$activeLeft R=$selectedRight", + ) + // Each quad is compared to ITSELF across the two frames (identical pixels, so the grid backdrop + // bleeding through the quad's alpha cancels out) - the two quads sit at different screen columns + // where the backdrop differs, so a cross-quad brightness comparison is not meaningful. + + // With no active drawable both quads tint toward the selection blue, so both read blue-dominant. + assertTrue( + controlLeft.third > controlLeft.second && controlRight.third > controlRight.second, + "both selected quads should read blue-dominant with no active drawable (L=$controlLeft R=$controlRight)", + ) + // The left quad becoming active flips it toward green: its green rises and its blue falls sharply, + // and it ends green-dominant. This within-quad transition is caused solely by setActiveSelection. + assertTrue( + activeLeft.second > controlLeft.second + 40 && activeLeft.third < controlLeft.third - 40, + "the left quad should turn greener and less blue when it becomes active (control=$controlLeft active=$activeLeft)", + ) + assertTrue( + activeLeft.second > activeLeft.third, + "the active quad should read green-dominant (active=$activeLeft)", + ) + // The right quad stayed merely selected, so it is essentially unchanged between the two frames and + // remains blue-dominant - the active tint touched only the active drawable. + assertTrue( + kotlin.math.abs(selectedRight.second - controlRight.second) < 8 && + kotlin.math.abs(selectedRight.third - controlRight.third) < 8 && + selectedRight.third > selectedRight.second, + "the merely-selected quad should stay blue-dominant and unchanged (control=$controlRight active=$selectedRight)", + ) + } + + private val leftScreenCol = 100 + private val rightScreenCol = 300 + private val quadScreenRow = 200 + + /** + * The mean (red, green, blue) over an 11x11 window centered on the given screen column/row, each 0..255. + * Averaging smooths any anti-aliased edge and flat-color dithering at the sample point. + */ + private fun averageColor(frame: ByteBuffer, centerCol: Int, centerRow: Int): Triple { + var sumRed = 0L + var sumGreen = 0L + var sumBlue = 0L + var count = 0 + for (row in (centerRow - 5)..(centerRow + 5)) { + for (col in (centerCol - 5)..(centerCol + 5)) { + val pixel = (row * viewportSize + col) * 4 + sumRed += frame.get(pixel).toInt() and 0xFF + sumGreen += frame.get(pixel + 1).toInt() and 0xFF + sumBlue += frame.get(pixel + 2).toInt() and 0xFF + count++ + } + } + return Triple((sumRed / count).toInt(), (sumGreen / count).toInt(), (sumBlue / count).toInt()) + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows; consistent across frames). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } + + /** Creates and binds an RGBA8 offscreen framebuffer to render the puppet into for read-back. */ + private fun createColorFbo(width: Int, height: Int): Int { + val framebuffer = GL30.glGenFramebuffers() + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + val colorTexture = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, colorTexture) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null as ByteBuffer?) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR) + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0) + return framebuffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SideTargetGrowthTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SideTargetGrowthTest.kt new file mode 100644 index 0000000..c7565ac --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SideTargetGrowthTest.kt @@ -0,0 +1,153 @@ +package org.umamo.render.gl + +import org.umamo.format.raster.RasterImage +import org.umamo.render.GridColors +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertTrue + +/** + * Pins the grow-only side targets (mask coverage + composite snapshot/pool): one renderer rendering + * 96 -> 64 -> 96 must produce, at each size, pixels identical to a fresh renderer whose side targets + * are exactly that size. The 64 render is the load-bearing case - the long-lived renderer's side + * targets stay at 96-capacity, so it exercises the capacity-sized screenTexSize divisor (mask AND + * composite sampling) and the used-height flip in the destination-snapshot resolve. The scene has a + * clip-masked quad and a Darken (5.3 extended blend) quad so both the mask path and the composite + * path are on screen. + */ +class SideTargetGrowthTest { + private val largeSize = 96 + private val smallSize = 64 + private val paramA = ParameterId("A") + private val maskId = DrawableId("mask_source") + private val maskedId = DrawableId("masked_quad") + private val darkenId = DrawableId("darken_quad") + + // A mid-grey backdrop so the Darken composite has a destination to blend against. + private val greyGrid = GridColors(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f) + + private fun restGrid(positions: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size)))), + ) + + /** + * A two-triangle quad drawable spanning the given world rectangle. + * + * @param DrawableId id The drawable id. + * @param BlendMode blendMode The color blend mode. + * @param List maskedBy The clipping mask sources, empty for none. + * @param FloatArray corners The world rect as (minX, minY, maxX, maxY). + * @return Drawable The drawable. + */ + private fun quad(id: DrawableId, blendMode: BlendMode, maskedBy: List, corners: FloatArray): Drawable { + val positions = + floatArrayOf( + corners[0], + corners[1], + corners[2], + corners[1], + corners[0], + corners[3], + corners[2], + corners[3], + ) + return Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = blendMode, + maskedBy = maskedBy, + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2, 1, 3, 2)), + geometryGrid = restGrid(positions), + ) + } + + /** The test scene: a mask source, a quad clipped by it, and a Darken (extended-blend) quad. */ + private fun model(): PuppetModel { + // Off-center, partial-viewport rects so a wrong screen-space divisor shifts visible edges. + val maskSource = quad(maskId, BlendMode.Normal, emptyList(), floatArrayOf(-24f, -24f, 8f, 8f)) + val masked = quad(maskedId, BlendMode.Normal, listOf(maskId), floatArrayOf(-32f, -32f, 32f, 32f)) + val darken = quad(darkenId, BlendMode.Darken, emptyList(), floatArrayOf(-8f, -8f, 24f, 24f)) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(maskSource, masked, darken), + rootChildren = listOf(OrgChild.Drawable(maskSource.id), OrgChild.Drawable(masked.id), OrgChild.Drawable(darken.id)), + rootPartId = null, + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + } + + @Test + fun shrinkAndRegrowMatchExactSizeRenders() { + requireHeadlessGl("[side-target-growth]") + val device = GlRenderDevice() + val longLived = newRenderer(device) + + // Establish the 96-capacity side targets, and pin the scene is not degenerate: some red + // byte must differ from the 0.5-grey backdrop (alpha bytes are excluded - they are 255 + // everywhere and would satisfy a whole-array check vacuously). + val firstLarge = renderAt(device, longLived, largeSize) + val drewSomething = (firstLarge.rgba.indices step 4).any { redIndex -> (firstLarge.rgba[redIndex].toInt() and 0xFF) != 0x80 } + assertTrue(drewSomething, "the scene draws over the backdrop") + + // The load-bearing case: 96-capacity side targets rendering a 64 viewport. + val shrunk = renderAt(device, longLived, smallSize) + val exactSmall = renderAt(device, newRenderer(device), smallSize) + assertContentEquals(exactSmall.rgba, shrunk.rgba, "a 64 render off 96-capacity side targets matches an exact-size renderer") + + // Regrow: back at capacity, still identical to a fresh exact-size renderer. + val regrown = renderAt(device, longLived, largeSize) + val exactLarge = renderAt(device, newRenderer(device), largeSize) + assertContentEquals(exactLarge.rgba, regrown.rgba, "the regrown 96 render matches an exact-size renderer") + } + + /** Builds and initializes a renderer for the shared test scene on [device]. */ + private fun newRenderer(device: GlRenderDevice): PuppetRenderer { + val renderer = PuppetRenderer(model(), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + renderer.setGrid(greyGrid, 100f, 10) + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setPose(emptyMap()) + return renderer + } + + /** + * Renders one frame at [size] x [size] into a fresh exact-size main target and reads it back. + * + * @param GlRenderDevice device The shared device. + * @param PuppetRenderer renderer The renderer under test. + * @param Int size The square viewport extent in pixels. + * @return RasterImage The frame, top row first. + */ + private fun renderAt(device: GlRenderDevice, renderer: PuppetRenderer, size: Int): RasterImage { + val target = device.createRenderTarget(RenderTargetSpec(size, size, TextureFormat.Rgba8, sampled = true)) + renderer.render(target, size, size) + val image = device.readPixels(target) + device.destroyRenderTarget(target) + return image + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SourceLayerDisplayRenderTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SourceLayerDisplayRenderTest.kt new file mode 100644 index 0000000..ca78ecb --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SourceLayerDisplayRenderTest.kt @@ -0,0 +1,583 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.DecodedImage +import org.umamo.render.DrawableLayerDraw +import org.umamo.render.GridColors +import org.umamo.render.LayerDrawPlan +import org.umamo.render.LayerRasterBatch +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.math.abs +import kotlin.math.hypot +import kotlin.math.roundToInt +import kotlin.test.Test +import kotlin.test.assertTrue + +// Erica's skin tone: the color of the upper-lip patch the rim fringe showed on. +private const val SKIN_RED = 255 +private const val SKIN_GREEN = 244 +private const val SKIN_BLUE = 233 + +// Rounding room for a render that should reproduce the backdrop exactly: the fixed-function blend and the +// 8-bit target can each land a unit off. The fringe it guards against runs to tens of units. +private const val RIM_TOLERANCE = 2 + +/** + * Proves the puppet actually displays from SOURCE ARTWORK rather than the packed atlas, and keeps + * doing so across an unrelated edit. + * + * The probe samples a red atlas; its artwork is a green image of its own. Switching the display + * source must turn the drawn art green without moving it - the mapping is carried by a uv affine, not + * by moving geometry. + * + * The second half is the regression the whole uniform approach exists for. The obvious alternative - + * re-uploading each mesh's UV buffer on the switch - breaks against the renderer's diff, which + * compares UV arrays by REFERENCE identity: an edit that leaves the arrays untouched produces no + * re-upload, and one that touches them rewrites the atlas-frame values, so the display would + * silently revert mid-session. So this pushes an unrelated Keep edit through updateModel while + * displaying from artwork and asserts the frame is unchanged. + * + * Self-skips in a display-less environment (no GL context), like [UvReuploadTest]. + */ +class SourceLayerDisplayRenderTest { + private val viewportSize = 200 + private val paramA = ParameterId("A") + private val probeId = DrawableId("LayerProbe") + + // A 120x120 quad centered at the origin; at zoom 1 it covers pixels ~40..160 in the 200x200 viewport. + private val quadPositions = floatArrayOf(-60f, -60f, 60f, -60f, -60f, 60f, 60f, 60f) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // Sampled well inside the image so a filtered lookup never straddles an edge. + private val quadUvs = floatArrayOf(0.05f, 0.95f, 0.95f, 0.95f, 0.05f, 0.05f, 0.95f, 0.05f) + + // The same quad reaching half its own width past the art on every side, which is the shape a real + // drawable has: an art mesh rings outside the opaque region, so its coordinates leave [0, 1]. The art + // therefore covers the middle 50% of each axis - a quarter of the quad's pixels. + private val overhangUvs = floatArrayOf(-0.5f, 1.5f, 1.5f, 1.5f, -0.5f, -0.5f, 1.5f, -0.5f) + private val overhangArtAreaFraction = 0.25f + + private fun solidImage(red: Int, green: Int, size: Int = 8): DecodedImage { + val rgba = ByteArray(size * size * 4) + for (pixel in rgba.indices step 4) { + rgba[pixel] = red.toByte() + rgba[pixel + 1] = green.toByte() + rgba[pixel + 2] = 0 + rgba[pixel + 3] = 0xFF.toByte() + } + return DecodedImage(rgba, size, size) + } + + private fun probeModel(uvs: FloatArray = quadUvs): PuppetModel { + val drawable = + Drawable( + id = probeId, + name = "LayerProbe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(quadPositions.copyOf(), uvs.copyOf(), quadIndices), + // One zero-delta keyform so the drawable is keyed; the base mesh alone drives its shape. + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(quadPositions.size)))), + ), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + } + + /** The mapping pointing the probe at its own green artwork, with an identity affine. */ + private fun artworkPlan(imageSize: Int = 8): LayerDrawPlan = + LayerDrawPlan( + drawsByDrawableId = mapOf(probeId.raw to DrawableLayerDraw("green", floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f))), + layerByteCostByKey = mapOf("green" to imageSize.toLong() * imageSize.toLong() * 4L), + ) + + /** The decoded pixels answering that mapping. */ + private fun artworkBatch(imageSize: Int = 8): LayerRasterBatch = + LayerRasterBatch(rastersByLayerKey = mapOf("green" to solidImage(red = 0x00, green = 0xFF, size = imageSize))) + + /** + * Pushes the mapping and then its pixels, the way the producer does. + * + * The renderer only uploads what it has asked for, so the plan must land before the batch - which is + * also the ordering the engine's render loop enforces. + */ + private fun PuppetRenderer.displayFromArtwork(imageSize: Int = 8) { + setSourceLayerPlan(artworkPlan(imageSize)) + deliverSourceLayerRasters(artworkBatch(imageSize)) + } + + /** + * The same model with a composite-only change (the culling toggle): positions, uvs, indices, and + * keyforms all shared BY REFERENCE, which is exactly the shape that produces a Keep with no buffer + * work. + */ + private fun compositeEditedModel(source: PuppetModel): PuppetModel { + val drawable = source.drawables.single() + return source.copy(drawables = listOf(drawable.copy(culling = !drawable.culling))) + } + + @Test + fun puppetDisplaysFromArtworkAndSurvivesAnUnrelatedEdit() { + requireHeadlessGl("[layer-display]") + val source = probeModel() + val device = GlRenderDevice() + val renderer = + PuppetRenderer( + source, + PuppetTextures(listOf(solidImage(red = 0xFF, green = 0x00)), mapOf(probeId.raw to 0), premultipliedAlpha = false), + device, + ) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // A fixed 1:1 camera centered on the origin, so the quad never moves - only its texels do. + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + fun frame(): ByteBuffer { + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + return readPixels(viewportSize, viewportSize) + } + + // Background only, so the art can be isolated by differencing against it. + renderer.setShownDrawables(emptySet()) + val background = frame() + + // Frame A: displaying from the atlas (red). + renderer.setShownDrawables(setOf(probeId)) + val statsAtlas = artColorStats(frame(), background, viewportSize, viewportSize) + + // Frame B: displaying from the artwork (green). + renderer.displayFromArtwork() + val statsArtwork = artColorStats(frame(), background, viewportSize, viewportSize) + + // Frame C: an unrelated composite edit while still displaying from the artwork. + renderer.updateModel(compositeEditedModel(source)) + val statsAfterEdit = artColorStats(frame(), background, viewportSize, viewportSize) + + // Frame D: back to the atlas. + renderer.setSourceLayerPlan(LayerDrawPlan.EMPTY) + val statsBack = artColorStats(frame(), background, viewportSize, viewportSize) + + println( + "[layer-display] atlas r=${statsAtlas.meanRed} g=${statsAtlas.meanGreen} | " + + "artwork r=${statsArtwork.meanRed} g=${statsArtwork.meanGreen} | " + + "afterEdit r=${statsAfterEdit.meanRed} g=${statsAfterEdit.meanGreen} | " + + "back r=${statsBack.meanRed} g=${statsBack.meanGreen}", + ) + + assertTrue(statsAtlas.mass > 1000, "the probe did not render from the atlas (mass ${statsAtlas.mass})") + assertTrue( + statsAtlas.meanRed > 200f && statsAtlas.meanGreen < 60f, + "the atlas frame should sample the red page (r=${statsAtlas.meanRed} g=${statsAtlas.meanGreen})", + ) + assertTrue(statsArtwork.mass > 1000, "the probe did not render from its artwork (mass ${statsArtwork.mass})") + assertTrue( + statsArtwork.meanGreen > 200f && statsArtwork.meanRed < 60f, + "the artwork frame should sample the green image (r=${statsArtwork.meanRed} g=${statsArtwork.meanGreen})", + ) + // The display source moves texels, never geometry. + assertTrue(abs(statsArtwork.centroidX - statsAtlas.centroidX) < 2f, "the art moved in x when the display source changed") + assertTrue(abs(statsArtwork.centroidY - statsAtlas.centroidY) < 2f, "the art moved in y when the display source changed") + + // THE regression: an unrelated edit must not knock the display back to the atlas. + assertTrue( + statsAfterEdit.meanGreen > 200f && statsAfterEdit.meanRed < 60f, + "an unrelated edit reverted the display to the atlas (r=${statsAfterEdit.meanRed} g=${statsAfterEdit.meanGreen})", + ) + + // And the switch is reversible. + assertTrue( + statsBack.meanRed > 200f && statsBack.meanGreen < 60f, + "clearing the artwork should return to the atlas (r=${statsBack.meanRed} g=${statsBack.meanGreen})", + ) + } + + /** + * A mesh overhanging the art it samples must show NOTHING past the art's frame - the streak regression. + * + * Every corpus drawable overhangs its layer image (the auto-mesh rings outside the opaque region and + * authored meshes extend further for deformation coverage), by up to 443 layer pixels. On an atlas page + * that overhang lands on the packer's transparent padding; a layer image has no padding, so an + * edge-clamped sampler repeats its border row and column across the overhang as streaks that follow the + * mesh and deform with it. The official editor's own layered display shows nothing there, and so must + * this: the layer texture wraps to a transparent border. + * + * The probe reaches half its width past the art on all four sides, so the art covers a QUARTER of the + * quad's pixels. Edge clamping fills the whole quad instead - four times the mass - which is a margin + * no filtering tolerance can blur away. + */ + @Test + fun artworkDisplayShowsNothingWhereTheMeshOverhangsItsArt() { + requireHeadlessGl("[layer-overhang]") + val source = probeModel(overhangUvs) + val device = GlRenderDevice() + val renderer = + PuppetRenderer( + source, + PuppetTextures(listOf(solidImage(red = 0xFF, green = 0x00)), mapOf(probeId.raw to 0), premultipliedAlpha = false), + device, + ) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + fun frame(): ByteBuffer { + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + return readPixels(viewportSize, viewportSize) + } + + renderer.setShownDrawables(emptySet()) + val background = frame() + renderer.setShownDrawables(setOf(probeId)) + + // A layer image large enough that the border blend spans well under a pixel, so the measured mass is + // the art's own extent rather than a filtering skirt around it. + renderer.displayFromArtwork(imageSize = 256) + val statsArtwork = artColorStats(frame(), background, viewportSize, viewportSize) + + // The quad is 120x120 world units at zoom 1, so its full screen footprint is 120x120 pixels. + val quadPixels = 120 * 120 + val expectedArtPixels = quadPixels * overhangArtAreaFraction + println( + "[layer-overhang] artwork mass ${statsArtwork.mass} px (quad $quadPixels, art ~$expectedArtPixels) " + + "r=${statsArtwork.meanRed} g=${statsArtwork.meanGreen}", + ) + + assertTrue(statsArtwork.mass > expectedArtPixels * 0.7f, "the art did not render at all (mass ${statsArtwork.mass})") + assertTrue( + statsArtwork.mass < expectedArtPixels * 1.4f, + "the mesh's overhang sampled the layer's border instead of nothing: ${statsArtwork.mass} px lit, " + + "~$expectedArtPixels expected (a whole-quad $quadPixels means edge clamping)", + ) + assertTrue( + statsArtwork.meanGreen > 200f && statsArtwork.meanRed < 60f, + "what did render is not the artwork (r=${statsArtwork.meanRed} g=${statsArtwork.meanGreen})", + ) + } + + /** + * A mesh overhanging the page it samples shows nothing past the page - the same streak, on the atlas. + * + * A document's page is not always a packed atlas with padding around every tile: a CMO3 draws some + * drawables straight from their model image, and the renderer takes that image as the drawable's page. + * So the page wraps to a transparent border like a layer image does, and this probe - the overhang + * probe above, displayed from a page instead of its artwork - lights a quarter of its quad, not all of it. + */ + @Test + fun atlasDisplayShowsNothingWhereTheMeshOverhangsItsPage() { + requireHeadlessGl("[page-overhang]") + val source = probeModel(overhangUvs) + val device = GlRenderDevice() + val renderer = + PuppetRenderer( + source, + PuppetTextures(listOf(solidImage(red = 0xFF, green = 0x00, size = 256)), mapOf(probeId.raw to 0), premultipliedAlpha = false), + device, + ) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + fun frame(): ByteBuffer { + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + return readPixels(viewportSize, viewportSize) + } + + renderer.setShownDrawables(emptySet()) + val background = frame() + renderer.setShownDrawables(setOf(probeId)) + val statsPage = artColorStats(frame(), background, viewportSize, viewportSize) + + val quadPixels = 120 * 120 + val expectedArtPixels = quadPixels * overhangArtAreaFraction + println("[page-overhang] page mass ${statsPage.mass} px (quad $quadPixels, art ~$expectedArtPixels) r=${statsPage.meanRed} g=${statsPage.meanGreen}") + + assertTrue(statsPage.mass > expectedArtPixels * 0.7f, "the page did not render at all (mass ${statsPage.mass})") + assertTrue( + statsPage.mass < expectedArtPixels * 1.4f, + "the mesh's overhang sampled the page's border instead of nothing: ${statsPage.mass} px lit, " + + "~$expectedArtPixels expected (a whole-quad $quadPixels means edge clamping)", + ) + assertTrue(statsPage.meanRed > 200f && statsPage.meanGreen < 60f, "what did render is not the page (r=${statsPage.meanRed} g=${statsPage.meanGreen})") + } + + /** + * The mode never shows a puppet half in artwork and half on its atlas. + * + * Source-artwork display exists so a rigger can INSPECT the art, so a mixed view is not a degraded + * success - it is untrustworthy, because nothing on screen says which drawables are showing which. + * The plan therefore engages nothing until every layer it maps has landed. + * + * Here the plan maps two layers and only one is delivered, so the probe must still be RED (its atlas), + * never green. It flips only once the second lands. + */ + @Test + fun artworkDisplayWaitsForEveryMappedLayer() { + requireHeadlessGl("[layer-allornothing]") + val source = probeModel() + val device = GlRenderDevice() + val renderer = + PuppetRenderer( + source, + PuppetTextures(listOf(solidImage(red = 0xFF, green = 0x00)), mapOf(probeId.raw to 0), premultipliedAlpha = false), + device, + ) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + fun frame(): ByteBuffer { + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + return readPixels(viewportSize, viewportSize) + } + + renderer.setShownDrawables(emptySet()) + val background = frame() + renderer.setShownDrawables(setOf(probeId)) + + // The probe draws from "green", but the plan also maps a second layer some other drawable needs. + renderer.setSourceLayerPlan( + LayerDrawPlan( + drawsByDrawableId = mapOf(probeId.raw to DrawableLayerDraw("green", floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f))), + layerByteCostByKey = mapOf("green" to 256L, "absent" to 256L), + ), + ) + renderer.deliverSourceLayerRasters(artworkBatch()) + val statsPartial = artColorStats(frame(), background, viewportSize, viewportSize) + val (readyPartial, _, _) = renderer.sourceLayerDisplayState() + + // The straggler lands: now the whole plan is covered and the mode engages. + renderer.deliverSourceLayerRasters( + LayerRasterBatch(rastersByLayerKey = mapOf("absent" to solidImage(red = 0x00, green = 0xFF))), + ) + val statsComplete = artColorStats(frame(), background, viewportSize, viewportSize) + val (readyComplete, _, _) = renderer.sourceLayerDisplayState() + + println( + "[layer-allornothing] partial ready=$readyPartial r=${statsPartial.meanRed} g=${statsPartial.meanGreen} | " + + "complete ready=$readyComplete r=${statsComplete.meanRed} g=${statsComplete.meanGreen}", + ) + + assertTrue(!readyPartial, "the mode must not engage while a mapped layer is still missing") + assertTrue( + statsPartial.meanRed > 200f && statsPartial.meanGreen < 60f, + "an incompletely covered plan must leave the puppet wholly on its atlas, not partly on artwork " + + "(r=${statsPartial.meanRed} g=${statsPartial.meanGreen})", + ) + assertTrue(readyComplete, "the mode engages once every mapped layer has landed") + assertTrue( + statsComplete.meanGreen > 200f && statsComplete.meanRed < 60f, + "and then the puppet displays from its artwork (r=${statsComplete.meanRed} g=${statsComplete.meanGreen})", + ) + } + + /** + * Art drawn over its own color must vanish, rim included: the artwork display. + * + * The upper-lip patch on EricaTamamo is skin over skin, so a correct render shows nothing at all, and + * any line around it is the filter blending the transparent texels' black into its soft rim. Cubism + * writes every layer that way, so a straight-alpha filter rings each one in a dark, texel-stepped + * outline. + */ + @Test + fun artworkRimShowsNoFringeOverItsOwnColor() { + requireHeadlessGl("[layer-rim]") + val deviation = rimDeviationOverOwnColor(fromArtwork = true) + println("[layer-rim] largest deviation from the backdrop: $deviation") + assertTrue(deviation <= RIM_TOLERANCE, "the artwork's rim darkens where it meets transparent texels (deviation $deviation)") + } + + /** + * The same probe on an atlas page, which is how a regenerated page shows a tile: the composer copies a + * tile's transparent texels as they are, so a page carries the black the layer did. + */ + @Test + fun atlasPageRimShowsNoFringeOverItsOwnColor() { + requireHeadlessGl("[page-rim]") + val deviation = rimDeviationOverOwnColor(fromArtwork = false) + println("[page-rim] largest deviation from the backdrop: $deviation") + assertTrue(deviation <= RIM_TOLERANCE, "the page's rim darkens where it meets transparent texels (deviation $deviation)") + } + + /** + * Renders [skinDiscImage] over a flat backdrop of the disc's own color and measures how far any pixel + * strays from the backdrop. + * + * The probe overhangs the image by half its width on every side, so the image fills the middle 60x60 + * pixels - 3.75 pixels per texel, enough to spread a one-texel fringe across several pixels - and the + * image's own border lies inside the drawn quad. + * + * @param Boolean fromArtwork True to display the disc as source artwork, false as the drawable's atlas page. + * @return Int The largest per-channel difference from the backdrop, 0..255. + */ + private fun rimDeviationOverOwnColor(fromArtwork: Boolean): Int { + val disc = skinDiscImage() + val source = probeModel(overhangUvs) + val device = GlRenderDevice() + val page = if (fromArtwork) solidImage(red = 0xFF, green = 0x00) else disc + val renderer = PuppetRenderer(source, PuppetTextures(listOf(page), mapOf(probeId.raw to 0), premultipliedAlpha = false), device) + renderer.initGl() + val skinRed = SKIN_RED / 255f + val skinGreen = SKIN_GREEN / 255f + val skinBlue = SKIN_BLUE / 255f + // Lines in the backdrop's own color, so the backdrop is one flat skin tone the art should vanish into. + renderer.setGrid(GridColors(skinRed, skinGreen, skinBlue, skinRed, skinGreen, skinBlue, skinRed, skinGreen, skinBlue), 100f, 1) + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + fun frame(): ByteBuffer { + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + return readPixels(viewportSize, viewportSize) + } + + renderer.setShownDrawables(emptySet()) + val background = frame() + renderer.setShownDrawables(setOf(probeId)) + if (fromArtwork) { + renderer.setSourceLayerPlan( + LayerDrawPlan( + drawsByDrawableId = mapOf(probeId.raw to DrawableLayerDraw("skin", floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f))), + layerByteCostByKey = mapOf("skin" to disc.rgba.size.toLong()), + ), + ) + renderer.deliverSourceLayerRasters(LayerRasterBatch(rastersByLayerKey = mapOf("skin" to disc))) + val (ready, _, _) = renderer.sourceLayerDisplayState() + assertTrue(ready, "the artwork display did not engage, so the probe would measure the atlas") + } + val drawn = frame() + var largest = 0 + for (index in 0 until viewportSize * viewportSize * 4) { + if (index % 4 == 3) { + continue + } + largest = maxOf(largest, abs((drawn.get(index).toInt() and 0xFF) - (background.get(index).toInt() and 0xFF))) + } + return largest + } + + /** + * A skin-colored disc with a one-texel soft rim, stored the way Cubism writes a layer: every fully + * transparent texel is black. + * + * The disc sits right of center and runs off the image's right edge, so its rim meets transparent + * texels inside the image on three sides and the image's border on the fourth, where the art is opaque. + * + * @param Int size The image's width and height in texels. + * @return DecodedImage The disc. + */ + private fun skinDiscImage(size: Int = 16): DecodedImage { + val rgba = ByteArray(size * size * 4) + val centerX = size * 0.7f + val centerY = size * 0.5f + val radius = size * 0.4f + for (row in 0 until size) { + for (column in 0 until size) { + val coverage = (radius - hypot(column + 0.5f - centerX, row + 0.5f - centerY) + 0.5f).coerceIn(0f, 1f) + val alpha = (coverage * 255f).roundToInt() + if (alpha == 0) { + continue + } + val pixel = (row * size + column) * 4 + rgba[pixel] = SKIN_RED.toByte() + rgba[pixel + 1] = SKIN_GREEN.toByte() + rgba[pixel + 2] = SKIN_BLUE.toByte() + rgba[pixel + 3] = alpha.toByte() + } + } + return DecodedImage(rgba, size, size) + } + + /** The mean color and pixel centroid of the art (every pixel differing from [background]). */ + private class ArtColorStats(val mass: Int, val meanRed: Float, val meanGreen: Float, val centroidX: Float, val centroidY: Float) + + /** + * Isolates the art as every pixel that differs from [background] by more than a flat threshold on + * any channel, and returns its mean red / green plus its pixel centroid. + * + * @param ByteBuffer frame The rendered frame's RGBA pixels. + * @param ByteBuffer background The art-hidden frame's RGBA pixels. + * @param Int width The frame width in pixels. + * @param Int height The frame height in pixels. + * @return ArtColorStats The art's mass, mean red / green, and centroid. + */ + private fun artColorStats(frame: ByteBuffer, background: ByteBuffer, width: Int, height: Int): ArtColorStats { + val threshold = 20 + var sumRed = 0.0 + var sumGreen = 0.0 + var sumX = 0.0 + var sumY = 0.0 + var count = 0 + for (row in 0 until height) { + for (col in 0 until width) { + val pixel = (row * width + col) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + val deltaRed = abs(red - (background.get(pixel).toInt() and 0xFF)) + val deltaGreen = abs(green - (background.get(pixel + 1).toInt() and 0xFF)) + val deltaBlue = abs(blue - (background.get(pixel + 2).toInt() and 0xFF)) + if (maxOf(deltaRed, deltaGreen, deltaBlue) > threshold) { + sumRed += red + sumGreen += green + sumX += col + sumY += row + count++ + } + } + } + if (count == 0) { + return ArtColorStats(0, 0f, 0f, 0f, 0f) + } + return ArtColorStats(count, (sumRed / count).toFloat(), (sumGreen / count).toFloat(), (sumX / count).toFloat(), (sumY / count).toFloat()) + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows; consistent across frames). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/StructuralReconcileTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/StructuralReconcileTest.kt new file mode 100644 index 0000000..1c86a72 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/StructuralReconcileTest.kt @@ -0,0 +1,309 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Proves [PuppetRenderer.updateModel]'s STRUCTURAL reconcile: a session-created drawable (e.g. an + * Object-mode duplicate) must reach the GPU, not just have position VBOs patched on drawables it already + * knew about, or it renders blank; likewise a remesh must re-upload the element buffer, or the + * newly-referenced geometry never draws. Renders flat-color art into an offscreen FBO and asserts by + * covered-pixel mass that: + * + * - a drawable ADDED after init (the duplicate) draws, and its removal (the undo) stops drawing it; + * - a REMESH of an existing drawable (new indices growing one triangle to two) re-uploads the element + * buffer, so the newly-referenced geometry actually draws. + * + * Self-skips in a display-less environment (no GL context), like [GpuDeformValidationTest]. + */ +class StructuralReconcileTest { + private val viewportSize = 400 + private val paramA = ParameterId("A") + private val sourceId = DrawableId("Probe") + private val copyId = DrawableId("Probe.001") + + // A 120x120 quad centered at (-80, 0); its duplicate shifts to (+80, 0) so the two never overlap and + // the covered mass simply doubles when both draw. + private val quadPositions = floatArrayOf(-140f, -60f, -20f, -60f, -140f, 60f, -20f, 60f) + private val quadUvs = FloatArray(8) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + private fun meshAxis() = listOf(KeyformAxis(paramA, floatArrayOf(0f))) + + private fun drawable(id: DrawableId, positions: FloatArray, indices: IntArray, textureSourceId: DrawableId? = null): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, quadUvs, indices), + // A single zero-delta keyform so the drawable is "keyed" (an unkeyed drawable is skipped). + geometryGrid = KeyformGrid(meshAxis(), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size))))), + textureSourceId = textureSourceId, + ) + + private fun model(drawables: List): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { OrgChild.Drawable(it.id) }, + rootPartId = null, + ) + + /** An Object-mode duplicate appears on the next reconcile, and its undo removes it again. */ + @Test + fun duplicatedDrawableAppearsAndItsUndoRemovesIt() { + requireHeadlessGl("[structural-reconcile]") + val original = model(listOf(drawable(sourceId, quadPositions.copyOf(), quadIndices))) + val device = GlRenderDevice() + val renderer = PuppetRenderer(original, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + renderer.setShownDrawables(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val background = readPixels(viewportSize, viewportSize) + + renderer.setShownDrawables(setOf(sourceId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massBefore = coveredMass(readPixels(viewportSize, viewportSize), background) + + // The duplicate: the source's mesh shifted fully clear of it, added the way DuplicateEdits does + // (fresh id, textureSourceId pointing home). + val copyPositions = FloatArray(quadPositions.size) { coordIndex -> quadPositions[coordIndex] + if (coordIndex % 2 == 0) 160f else 0f } + val duplicated = + model( + listOf( + drawable(sourceId, quadPositions.copyOf(), quadIndices), + drawable(copyId, copyPositions, quadIndices, textureSourceId = sourceId), + ), + ) + renderer.updateModel(duplicated) + renderer.setShownDrawables(setOf(sourceId, copyId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massWithCopy = coveredMass(readPixels(viewportSize, viewportSize), background) + + // The undo: back to the original model - the copy's GPU objects are freed and it stops drawing. + renderer.updateModel(original) + renderer.setShownDrawables(setOf(sourceId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massAfterUndo = coveredMass(readPixels(viewportSize, viewportSize), background) + + println("[structural-reconcile] duplicate: before=$massBefore withCopy=$massWithCopy afterUndo=$massAfterUndo") + assertTrue(massBefore > 1000, "the probe did not render at all (mass $massBefore)") + assertTrue( + abs(massWithCopy - 2 * massBefore) < massBefore / 4, + "the duplicate did not draw (mass $massWithCopy, expected ~${2 * massBefore})", + ) + assertTrue( + abs(massAfterUndo - massBefore) < massBefore / 4, + "the undone duplicate kept drawing (mass $massAfterUndo, expected ~$massBefore)", + ) + } + + /** + * Edit-mode guide freeze keeps the textured mass after a topology delete that would otherwise empty + * the mesh (and drop residency); thawing then drops the image with the live empty mesh. + */ + @Test + fun editMeshFrozenKeepsImageAfterTopologyDelete() { + requireHeadlessGl("[structural-reconcile]") + val full = model(listOf(drawable(sourceId, quadPositions.copyOf(), quadIndices.copyOf()))) + val device = GlRenderDevice() + val renderer = PuppetRenderer(full, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + renderer.setShownDrawables(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val background = readPixels(viewportSize, viewportSize) + + renderer.setShownDrawables(setOf(sourceId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massFull = coveredMass(readPixels(viewportSize, viewportSize), background) + assertTrue(massFull > 1000, "the full quad did not render (mass $massFull)") + + renderer.setEditMeshFrozen(setOf(sourceId)) + // Delete every triangle (what deleteVertices does when a shared vert goes): without freeze this + // would drop residency and draw nothing. + val emptied = model(listOf(drawable(sourceId, quadPositions.copyOf(), IntArray(0)))) + renderer.updateModel(emptied) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massFrozen = coveredMass(readPixels(viewportSize, viewportSize), background) + assertTrue( + abs(massFrozen - massFull) < massFull / 4, + "frozen guide lost the image after topology delete (mass $massFrozen, expected ~$massFull)", + ) + + renderer.setEditMeshFrozen(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massThawed = coveredMass(readPixels(viewportSize, viewportSize), background) + assertTrue(massThawed < massFull / 10, "thaw did not drop the empty live mesh (mass $massThawed)") + } + + /** + * After a frozen wipe, Accept that grows a small new triangle must reupload (compare vs live, not + * the frozen resident) so the drawable does not vanish or stay stuck on the pre-wipe guide only. + */ + @Test + fun editMeshFrozenGrowsAfterWipeShowsNewMesh() { + requireHeadlessGl("[structural-reconcile]") + val full = model(listOf(drawable(sourceId, quadPositions.copyOf(), quadIndices.copyOf()))) + val device = GlRenderDevice() + val renderer = PuppetRenderer(full, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + renderer.setShownDrawables(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val background = readPixels(viewportSize, viewportSize) + + renderer.setShownDrawables(setOf(sourceId)) + renderer.setEditMeshFrozen(setOf(sourceId)) + renderer.updateModel(model(listOf(drawable(sourceId, floatArrayOf(), IntArray(0))))) + // Grow from empty live → one triangle (smaller than the frozen guide's index count). + val grown = + model( + listOf( + drawable( + sourceId, + floatArrayOf(-60f, -60f, 60f, -60f, -60f, 60f), + intArrayOf(0, 1, 2), + ), + ), + ) + renderer.updateModel(grown) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massGrown = coveredMass(readPixels(viewportSize, viewportSize), background) + assertTrue(massGrown > 500, "Accept-after-wipe must draw the new triangle (mass $massGrown), not blank") + } + + /** A remesh (fresh indices referencing more of the mesh) re-uploads the element buffer and draws. */ + @Test + fun remeshedDrawableDrawsItsNewTopology() { + requireHeadlessGl("[structural-reconcile]") + // Start with HALF the quad (one triangle); the remesh grows it to the full quad with a fresh + // indices array - the covered mass roughly doubles only if the EBO was rebuilt. + val halfQuad = model(listOf(drawable(sourceId, quadPositions.copyOf(), intArrayOf(0, 1, 2)))) + val device = GlRenderDevice() + val renderer = PuppetRenderer(halfQuad, PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + renderer.setShownDrawables(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val background = readPixels(viewportSize, viewportSize) + + renderer.setShownDrawables(setOf(sourceId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massHalf = coveredMass(readPixels(viewportSize, viewportSize), background) + + renderer.updateModel(model(listOf(drawable(sourceId, quadPositions.copyOf(), quadIndices.copyOf())))) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val massFull = coveredMass(readPixels(viewportSize, viewportSize), background) + + println("[structural-reconcile] remesh: half=$massHalf full=$massFull") + assertTrue(massHalf > 1000, "the half quad did not render (mass $massHalf)") + assertTrue( + abs(massFull - 2 * massHalf) < massHalf / 4, + "the remeshed topology did not draw (mass $massFull, expected ~${2 * massHalf})", + ) + } + + /** The count of pixels differing from [background] by more than a flat threshold on any channel. */ + private fun coveredMass(frame: ByteBuffer, background: ByteBuffer): Int { + val threshold = 20 + var count = 0 + for (pixelIndex in 0 until viewportSize * viewportSize) { + val byteIndex = pixelIndex * 4 + val deltaRed = abs((frame.get(byteIndex).toInt() and 0xFF) - (background.get(byteIndex).toInt() and 0xFF)) + val deltaGreen = abs((frame.get(byteIndex + 1).toInt() and 0xFF) - (background.get(byteIndex + 1).toInt() and 0xFF)) + val deltaBlue = abs((frame.get(byteIndex + 2).toInt() and 0xFF) - (background.get(byteIndex + 2).toInt() and 0xFF)) + if (maxOf(deltaRed, deltaGreen, deltaBlue) > threshold) { + count++ + } + } + return count + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer. */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } + + /** Creates and binds an RGBA8 offscreen framebuffer to render the puppet into for read-back. */ + private fun createColorFbo(width: Int, height: Int): Int { + val framebuffer = GL30.glGenFramebuffers() + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + val colorTexture = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, colorTexture) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null as ByteBuffer?) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR) + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0) + return framebuffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SupersampleReadbackTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SupersampleReadbackTest.kt new file mode 100644 index 0000000..95e3b84 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/SupersampleReadbackTest.kt @@ -0,0 +1,130 @@ +package org.umamo.render.gl + +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.format.raster.RasterImage +import org.umamo.render.SupersampledSurface +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the viewport read-back tail end to end: [SupersampledSurface] (draw at Nx, resolve to display + * size), [GlRenderDevice.resolve] (the box-downscale blit), and the asynchronous + * [GlRenderDevice.beginReadback] / [GlRenderDevice.pollReadback] ticket path. + * + * This stack had NO coverage at all in its previous life as the app-side SupersampleFramebuffer + + * PixelReadbackPool - the per-frame path every viewport pixel travels was defended by nothing. The + * probe paints the supersampled draw target's top half red and bottom half green (in GL's bottom-up + * scissor coordinates), resolves, and then requires: the sync read-back sees red FIRST (top-first + * contract, correct through the downscale), and the async ticket delivers byte-identical pixels in + * submission order. + * + * ビューポート読み戻しの末尾(スーパーサンプル解決+非同期読み戻し)を初めて検証する。 + */ +class SupersampleReadbackTest { + private val displaySize = 64 + private val scale = 2 + + @Test + fun resolveDownscalesAndAsyncReadbackMatchesSync() { + requireHeadlessGl("[supersample-readback]") + val device = GlRenderDevice() + val surface = SupersampledSurface(device, scale) + val drawTarget = surface.ensure(displaySize, displaySize) as GlRenderTarget + assertEquals(displaySize * scale, drawTarget.width, "the draw target is supersampled") + + paintHalves(drawTarget, displaySize * scale, displaySize * scale) + surface.resolve() + + // Sync read of the resolve target: display-sized, top row red - the downscale kept regions in + // place and the read-back honoured the top-first contract. + val sync = device.readPixels(surface.resolveTarget) + assertEquals(displaySize, sync.width) + assertEquals(displaySize, sync.height) + assertPixel(sync, row = 0, expectedRed = 255, expectedGreen = 0, note = "top row is the red half") + assertPixel(sync, row = displaySize - 1, expectedRed = 0, expectedGreen = 255, note = "bottom row is the green half") + + // Async: two tickets in flight at once, collected in submission order, byte-identical to sync. + val firstTicket = device.beginReadback(surface.resolveTarget) + val secondTicket = device.beginReadback(surface.resolveTarget) + val first = awaitReadback(device, firstTicket) + val second = awaitReadback(device, secondTicket) + assertContentEquals(sync.rgba, first.rgba, "the async read-back returns the same pixels as the sync one") + assertContentEquals(sync.rgba, second.rgba, "a second in-flight ticket delivers too") + + // A completed poll consumes the ticket EXACTLY ONCE, at the fence-signal: re-polling a finished + // ticket must trip the spent check, not silently re-map a recycled PBO. This pins the ordering + // fix - the ticket is marked spent the moment the fence signals, before the map, so there is no + // window in which a consumed ticket reads as still-in-flight and gets re-polled. + assertFailsWith("re-polling a consumed ticket is a spent-check trip") { + device.pollReadback(firstTicket) + } + + // Grow-only: a smaller ensure keeps the high-water allocation (the SAME target instances) + // and just narrows the used region; the render, resolve, and read-back all confine + // themselves to it. + val halfSize = displaySize / 2 + val shrunk = surface.ensure(halfSize, halfSize) as GlRenderTarget + assertSame(drawTarget, shrunk, "a smaller ensure never reallocates the draw target") + assertEquals(displaySize * scale, shrunk.width, "the draw target keeps its high-water allocation") + assertEquals(displaySize, (surface.resolveTarget as GlRenderTarget).width, "the resolve target keeps its allocation too") + assertEquals(halfSize, surface.usedWidth, "the used region follows the request") + assertEquals(halfSize, surface.usedHeight) + + paintHalves(shrunk, halfSize * scale, halfSize * scale) + surface.resolve() + val small = device.readPixels(surface.resolveTarget, halfSize, halfSize) + assertEquals(halfSize, small.width) + assertEquals(halfSize, small.height) + assertPixel(small, row = 0, expectedRed = 255, expectedGreen = 0, note = "used-region top row is red after the shrink") + assertPixel(small, row = halfSize - 1, expectedRed = 0, expectedGreen = 255, note = "used-region bottom row is green after the shrink") + val smallTicket = device.beginReadback(surface.resolveTarget, halfSize, halfSize) + assertContentEquals(small.rgba, awaitReadback(device, smallTicket).rgba, "the used-region async read-back matches the sync one") + surface.dispose() + } + + /** Polls [ticket] to completion, bounded so a wedged fence fails the test instead of hanging it. */ + private fun awaitReadback(device: GlRenderDevice, ticket: org.umamo.render.device.ReadbackTicket): RasterImage { + repeat(2000) { + device.pollReadback(ticket)?.let { return it } + Thread.sleep(1) + } + error("read-back never completed - the fence did not signal within 2s") + } + + /** + * Paints the used region's TOP half red and BOTTOM half green, in GL's bottom-left scissor + * coordinates. The used region is the target's bottom-left rows (the pass viewport anchors at + * the origin), so a capacity-larger target is painted only where the render would draw. + * + * @param GlRenderTarget target The target to paint. + * @param Int usedWidth The used extent along x, in pixels. + * @param Int usedHeight The used extent along y, in pixels. + */ + private fun paintHalves(target: GlRenderTarget, usedWidth: Int, usedHeight: Int) { + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, target.framebuffer) + GL11.glViewport(0, 0, usedWidth, usedHeight) + GL11.glEnable(GL11.GL_SCISSOR_TEST) + GL11.glScissor(0, 0, usedWidth, usedHeight / 2) + GL11.glClearColor(0f, 1f, 0f, 1f) // GL's bottom half = the image's bottom = green + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT) + GL11.glScissor(0, usedHeight / 2, usedWidth, usedHeight / 2) + GL11.glClearColor(1f, 0f, 0f, 1f) // GL's top half = the image's top = red + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT) + GL11.glDisable(GL11.GL_SCISSOR_TEST) + } + + /** Asserts the pixel at column 0 of [row] (top-first) is the expected solid red/green. */ + private fun assertPixel(image: RasterImage, row: Int, expectedRed: Int, expectedGreen: Int, note: String) { + val at = row * image.width * 4 + val red = image.rgba[at].toInt() and 0xFF + val green = image.rgba[at + 1].toInt() and 0xFF + assertNotNull(image.rgba, note) + assertTrue(red == expectedRed && green == expectedGreen, "$note: got rgb($red, $green, _) at row $row") + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/UvReuploadTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/UvReuploadTest.kt new file mode 100644 index 0000000..4d31358 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/UvReuploadTest.kt @@ -0,0 +1,220 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * Proves the GPU renderer re-uploads an edited UV array in place so the textured art actually + * resamples - the UV editor's live-preview and commit path. Renders a quad sampling the LEFT (red) + * half of a two-color atlas into an offscreen FBO, retargets its UVs at the RIGHT (green) half via + * [PuppetRenderer.updateModel] with the positions, indices, and keyforms untouched by reference + * (exactly the shape a withMeshUvs edit produces, so the uvs-only tier runs - not the structural + * re-upload), re-renders, and asserts the drawn art flipped color without moving. + * + * Self-skips in a display-less environment (no GL context), like [GeometryReuploadTest]. + */ +class UvReuploadTest { + private val viewportSize = 200 + private val paramA = ParameterId("A") + private val probeId = DrawableId("UvProbe") + + // A 120x120 quad centered at the origin; at zoom 1 it covers pixels ~40..160 in the 200x200 viewport. + private val quadPositions = floatArrayOf(-60f, -60f, 60f, -60f, -60f, 60f, 60f, 60f) + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + + // The atlas halves, sampled with a safe margin so the NEAREST lookup never straddles the color seam. + private val leftHalfUvs = floatArrayOf(0.05f, 0.95f, 0.45f, 0.95f, 0.05f, 0.05f, 0.45f, 0.05f) + private val rightHalfUvs = floatArrayOf(0.55f, 0.95f, 0.95f, 0.95f, 0.55f, 0.05f, 0.95f, 0.05f) + + /** An 8x8 RGBA atlas: columns 0..3 solid red, columns 4..7 solid green, fully opaque. */ + private fun twoColorAtlas(): DecodedImage { + val size = 8 + val rgba = ByteArray(size * size * 4) + for (row in 0 until size) { + for (col in 0 until size) { + val pixel = (row * size + col) * 4 + rgba[pixel] = if (col < size / 2) 0xFF.toByte() else 0x00 + rgba[pixel + 1] = if (col < size / 2) 0x00 else 0xFF.toByte() + rgba[pixel + 2] = 0x00 + rgba[pixel + 3] = 0xFF.toByte() + } + } + return DecodedImage(rgba, size, size) + } + + private fun probeModel(): PuppetModel { + val drawable = + Drawable( + id = probeId, + name = "UvProbe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(quadPositions.copyOf(), leftHalfUvs.copyOf(), quadIndices), + // A single zero-delta keyform so the drawable is "keyed" (an unkeyed drawable is skipped + // by the renderer); the base mesh alone drives its shape. + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramA, floatArrayOf(0f))), + listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(quadPositions.size)))), + ), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + ) + } + + /** + * The same model with the probe's UVs retargeted at the green half - positions, indices, and + * keyforms shared by reference, the exact shape withMeshUvs produces, so only the uvs-only tier + * may run. + */ + private fun uvShiftedModel(source: PuppetModel): PuppetModel { + val drawable = source.drawables.single() + val mesh = drawable.mesh!! + return source.copy(drawables = listOf(drawable.copy(mesh = DrawableMesh(mesh.positions, rightHalfUvs.copyOf(), mesh.indices)))) + } + + @Test + fun artResamplesAfterUvEdit() { + requireHeadlessGl("[uv-reupload]") + val source = probeModel() + val device = GlRenderDevice() + val renderer = PuppetRenderer(source, PuppetTextures(listOf(twoColorAtlas()), mapOf(probeId.raw to 0), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // A fixed 1:1 camera centered on the origin, so the quad never moves - only its texels do. + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + + // Background only (the drawable hidden), so the art can be isolated by differencing against it. + renderer.setShownDrawables(emptySet()) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val background = readPixels(viewportSize, viewportSize) + + // Frame A: the quad sampling the red half. + renderer.setShownDrawables(setOf(probeId)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frameA = readPixels(viewportSize, viewportSize) + val statsA = artColorStats(frameA, background, viewportSize, viewportSize) + + // Edit: retarget the UVs at the green half and push the new model (the render loop's + // updateModel path, fed by the UV editor's preview and commit). + renderer.updateModel(uvShiftedModel(source)) + renderer.setPose(emptyMap()) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frameB = readPixels(viewportSize, viewportSize) + val statsB = artColorStats(frameB, background, viewportSize, viewportSize) + + println( + "[uv-reupload] massA=${statsA.mass} redA=${statsA.meanRed} greenA=${statsA.meanGreen} | " + + "massB=${statsB.mass} redB=${statsB.meanRed} greenB=${statsB.meanGreen} | " + + "centroidDx=${statsB.centroidX - statsA.centroidX} centroidDy=${statsB.centroidY - statsA.centroidY}", + ) + assertTrue(statsA.mass > 1000, "frame A drew too little art (mass ${statsA.mass}) - the probe did not render") + assertTrue(statsB.mass > 1000, "frame B drew too little art (mass ${statsB.mass})") + assertTrue(statsA.meanRed > 200f && statsA.meanGreen < 60f, "frame A should sample the red half (r=${statsA.meanRed} g=${statsA.meanGreen})") + assertTrue(statsB.meanGreen > 200f && statsB.meanRed < 60f, "frame B should sample the green half after the UV edit (r=${statsB.meanRed} g=${statsB.meanGreen})") + // A pure UV edit moves texels, never geometry: the drawn quad must stay put. + assertTrue(abs(statsB.centroidX - statsA.centroidX) < 2f, "the art moved in x under a UV-only edit") + assertTrue(abs(statsB.centroidY - statsA.centroidY) < 2f, "the art moved in y under a UV-only edit") + } + + /** The mean color and pixel centroid of the art (every pixel differing from [background]). */ + private class ArtColorStats(val mass: Int, val meanRed: Float, val meanGreen: Float, val centroidX: Float, val centroidY: Float) + + /** + * Isolates the art as every pixel that differs from [background] by more than a flat threshold on + * any channel, and returns its mean red / green plus its pixel centroid. + * + * @param ByteBuffer frame The rendered frame's RGBA pixels. + * @param ByteBuffer background The art-hidden frame's RGBA pixels. + * @param Int width The frame width in pixels. + * @param Int height The frame height in pixels. + * @return ArtColorStats The art's mass, mean red / green, and centroid. + */ + private fun artColorStats(frame: ByteBuffer, background: ByteBuffer, width: Int, height: Int): ArtColorStats { + val threshold = 20 + var sumRed = 0.0 + var sumGreen = 0.0 + var sumX = 0.0 + var sumY = 0.0 + var count = 0 + for (row in 0 until height) { + for (col in 0 until width) { + val pixel = (row * width + col) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + val deltaRed = abs(red - (background.get(pixel).toInt() and 0xFF)) + val deltaGreen = abs(green - (background.get(pixel + 1).toInt() and 0xFF)) + val deltaBlue = abs(blue - (background.get(pixel + 2).toInt() and 0xFF)) + if (maxOf(deltaRed, deltaGreen, deltaBlue) > threshold) { + sumRed += red + sumGreen += green + sumX += col + sumY += row + count++ + } + } + } + if (count == 0) { + return ArtColorStats(0, 0f, 0f, 0f, 0f) + } + return ArtColorStats(count, (sumRed / count).toFloat(), (sumGreen / count).toFloat(), (sumX / count).toFloat(), (sumY / count).toFloat()) + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows; consistent A vs B). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } + + /** Creates and binds an RGBA8 offscreen framebuffer to render the puppet into for read-back. */ + private fun createColorFbo(width: Int, height: Int): Int { + val framebuffer = GL30.glGenFramebuffers() + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + val colorTexture = GL11.glGenTextures() + GL11.glBindTexture(GL11.GL_TEXTURE_2D, colorTexture) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null as ByteBuffer?) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR) + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR) + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0) + return framebuffer + } +} \ No newline at end of file diff --git a/module/render/src/jvmTest/kotlin/org/umamo/render/gl/WorldAxisLinesTest.kt b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/WorldAxisLinesTest.kt new file mode 100644 index 0000000..9689274 --- /dev/null +++ b/module/render/src/jvmTest/kotlin/org/umamo/render/gl/WorldAxisLinesTest.kt @@ -0,0 +1,154 @@ +package org.umamo.render.gl + +import org.lwjgl.BufferUtils +import org.lwjgl.opengl.GL11 +import org.lwjgl.opengl.GL30 +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.device.RenderTargetSpec +import org.umamo.render.device.TextureFormat +import org.umamo.render.puppet.PuppetRenderer +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import java.nio.ByteBuffer +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Proves the world-origin axis lines actually rasterize: with [PuppetRenderer.setWorldAxesVisible] + * on, the frame gains a horizontal red X axis row and a vertical blue Z axis column crossing at the + * model's world origin, and with the flag off (the default, which keeps render-diff tests line-free) + * the frame contains neither. Renders into an offscreen FBO at a fixed 1:1 camera so the origin's + * pixel position is predictable. Skips in a display-less environment, like [GeometryReuploadTest] - via a + * JUnit assumption, so the run reports SKIPPED rather than a green pass that asserted nothing. + */ +class WorldAxisLinesTest { + private val viewportSize = 400 + private val paramA = ParameterId("A") + + // A small keyed quad well away from the origin so the axis pixels are never confused with art. + private fun model(): PuppetModel { + val positions = floatArrayOf(120f, 120f, 160f, 120f, 120f, 160f, 160f, 160f) + val drawable = + Drawable( + id = DrawableId("probe"), + name = "probe", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions, FloatArray(positions.size), intArrayOf(0, 1, 2, 1, 3, 2)), + geometryGrid = KeyformGrid(listOf(KeyformAxis(paramA, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(FloatArray(positions.size))))), + ) + return PuppetModel( + parameters = listOf(Parameter(paramA, "A", -1f, 1f, 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = listOf(OrgChild.Drawable(drawable.id)), + rootPartId = null, + // The origin under test sits at world (0, 0) - the viewport center at the fixed 1:1 camera. + canvasWidth = 0f, + canvasHeight = 0f, + worldOriginX = 0f, + worldOriginZ = 0f, + ) + } + + @Test + fun axisLinesDrawOnlyWhenEnabled() { + requireHeadlessGl("[world-axis-lines]") + val device = GlRenderDevice() + val renderer = PuppetRenderer(model(), PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), device) + renderer.initGl() + // Device-owned target; the raw fbo id is read for this test's own bottom-up glReadPixels. + val target = device.createRenderTarget(RenderTargetSpec(viewportSize, viewportSize, TextureFormat.Rgba8, sampled = true)) + val framebuffer = (target as GlRenderTarget).framebuffer + // A fixed 1:1 camera centered on the world origin: the axes must cross at the viewport center. + renderer.setCamera(ViewportCamera(0f, 0f, 1f)) + renderer.setPose(emptyMap()) + + // Default: axes off - the frame must contain no axis-colored pixels (render-diff tests rely on this). + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val framePlain = readPixels(viewportSize, viewportSize) + assertEquals(0, maxRedRunInCenterRows(framePlain), "no X axis pixels while the flag is off") + assertEquals(0, maxBlueRunInCenterColumns(framePlain), "no Z axis pixels while the flag is off") + + // Enabled: a red row and a blue column cross at the center. + renderer.setWorldAxesVisible(true) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) + renderer.render(target, viewportSize, viewportSize) + val frameAxes = readPixels(viewportSize, viewportSize) + val redRun = maxRedRunInCenterRows(frameAxes) + val blueRun = maxBlueRunInCenterColumns(frameAxes) + println("[world-axis-lines] redRun=$redRun blueRun=$blueRun (viewport $viewportSize)") + assertTrue(redRun > viewportSize / 2, "the X axis row spans the viewport (got $redRun red pixels)") + assertTrue(blueRun > viewportSize / 2, "the Z axis column spans the viewport (got $blueRun blue pixels)") + } + + /** Counts red-dominant pixels per row across the center band and returns the largest row count. */ + private fun maxRedRunInCenterRows(frame: ByteBuffer): Int { + var best = 0 + for (row in viewportSize / 2 - 3..viewportSize / 2 + 3) { + var count = 0 + for (col in 0 until viewportSize) { + if (isRedDominant(frame, col, row)) { + count++ + } + } + best = maxOf(best, count) + } + return best + } + + /** Counts blue-dominant pixels per column across the center band and returns the largest column count. */ + private fun maxBlueRunInCenterColumns(frame: ByteBuffer): Int { + var best = 0 + for (col in viewportSize / 2 - 3..viewportSize / 2 + 3) { + var count = 0 + for (row in 0 until viewportSize) { + if (isBlueDominant(frame, col, row)) { + count++ + } + } + best = maxOf(best, count) + } + return best + } + + /** True when the pixel reads clearly red over green and blue (the X axis color over any backdrop). */ + private fun isRedDominant(frame: ByteBuffer, col: Int, row: Int): Boolean { + val pixel = (row * viewportSize + col) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + return red > green + 40 && red > blue + 40 + } + + /** True when the pixel reads clearly blue over red and green (the Z axis color over any backdrop). */ + private fun isBlueDominant(frame: ByteBuffer, col: Int, row: Int): Boolean { + val pixel = (row * viewportSize + col) * 4 + val red = frame.get(pixel).toInt() and 0xFF + val green = frame.get(pixel + 1).toInt() and 0xFF + val blue = frame.get(pixel + 2).toInt() and 0xFF + return blue > red + 40 && blue > green + 40 + } + + /** Reads the bound framebuffer's RGBA pixels into a fresh buffer (bottom-up rows). */ + private fun readPixels(width: Int, height: Int): ByteBuffer { + val buffer = BufferUtils.createByteBuffer(width * height * 4) + GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer) + return buffer + } +} \ No newline at end of file diff --git a/module/runtime/build.gradle.kts b/module/runtime/build.gradle.kts new file mode 100644 index 0000000..4b07e33 --- /dev/null +++ b/module/runtime/build.gradle.kts @@ -0,0 +1,39 @@ +// :runtime — the pure puppet runtime: the immutable PuppetModel and its typed ids, the keyform grid +// algebra, and the sampling eval. Zero format knowledge — CMO3/MOC3 conversion lives in :interop, +// which depends on this module and :format. (Deformation eval and the renderer live in :render, +// which depends on :runtime — not the reverse.) + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + // Wires the iosArm64 compiles into `check` (a device target has no runnable test task of its own). + id("umamo.kmp-ios-gate") +} + +kotlin { + jvmToolchain(21) + + jvm() + + // The iPadOS ship target, mirroring :format (see its docblock for the full rationale). Two jobs: + // it makes commonMain purity a COMPILER GUARANTEE rather than the root regex gate's convention, and + // it is what lets :render declare the same target — :render/commonMain does api(:runtime), so the + // renderer the Metal engineer builds against could not compile for iOS until this module did. + // Compiles on Linux/CI (klib only, no Xcode linker); a device target has no runnable test task, so + // `umamo.kmp-ios-gate` wires `check` to the compiles. + iosArm64() + + android { + namespace = "org.umamo.runtime" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + commonTest { + dependencies { + implementation(kotlin("test")) + } + } + } +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/ChannelSampling.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/ChannelSampling.kt new file mode 100644 index 0000000..7c60b46 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/ChannelSampling.kt @@ -0,0 +1,148 @@ +package org.umamo.runtime.eval + +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.ParameterId + +/* + * Pose sampling for the per-channel keyform tracks, over the same multilinear corner selection the + * geometry blend uses. + * + * Each channel resolves its OWN corners from its OWN grid rather than borrowing geometry's. That is not + * an optimization left on the table - after import compaction a channel track keeps only the axes it + * actually varies along, so its cell linear indices no longer line up with geometry's and a borrowed + * corner set would read the wrong cells. Before compaction the two share axes, so the corners come out + * identical in identical order and the sums are bit-for-bit what the bundled blend produced. + * + * The static fallback applies when the owner has NO track for a channel, or when the track's pose is out + * of range. Out of range NEVER hides: hiding is the geometry grid's decision alone, so keying opacity on + * a narrow parameter cannot make the art vanish at the ends of an unrelated slider. + * + * Every read takes an optional OVERRIDE, which wins over both the track and the static. That is how a + * value the user has typed but not yet keyed reaches the viewport: the pending edit is not in the document + * (it is transient session state), so it arrives beside the pose rather than inside the model. + */ + +/** + * The blended value of a SCALAR channel at the given pose, or [staticValue] when it is untracked or the + * pose falls outside the track's key range. + * + * A cell missing from a sparse track contributes nothing rather than falling back, matching how the + * bundled blend has always treated an unresolvable cell. + * + * @param FormChannel channel The scalar channel to sample. + * @param Float staticValue The owner's static value for this channel. + * @param Function paramValue Current value for a given parameter id. + * @return Float The blended value, or [staticValue]. + */ +fun ChannelGrids.scalarAt( + channel: FormChannel, + staticValue: Float, + paramValue: (ParameterId) -> Float, + override: ChannelValue? = null, +): Float = + // One body with scalarOrNull, so the renderer's opacity read and the sparse draw-order read can never + // disagree about the blend arithmetic - two separately maintained copies would drift as one gets + // tuned and the other forgotten. + scalarOrNull(channel, paramValue, override) ?: staticValue + +/** + * The blended value of a COLOR channel at the given pose, or [staticValue] when untracked or out of range. + * + * @param FormChannel channel The color channel to sample. + * @param ColorRgb staticValue The owner's static color for this channel. + * @param Function paramValue Current value for a given parameter id. + * @return ColorRgb The blended color, or [staticValue]. + */ +fun ChannelGrids.colorAt( + channel: FormChannel, + staticValue: ColorRgb, + paramValue: (ParameterId) -> Float, + override: ChannelValue? = null, +): ColorRgb { + (override as? ChannelValue.Color)?.let { pending -> return pending.color } + val grid = this[channel] ?: return staticValue + val corners = gridCorners(grid, paramValue) ?: return staticValue + val cells = cellsByLinearIndex(grid) + var red = 0f + var green = 0f + var blue = 0f + for (corner in corners) { + val color = (cells[corner.linearIndex]?.form as? ChannelValue.Color)?.color ?: continue + red += corner.weight * color.red + green += corner.weight * color.green + blue += corner.weight * color.blue + } + return ColorRgb(red, green, blue) +} + +/** + * The value of a FLAG channel at the given pose, or [staticValue] when untracked or out of range. + * + * A flag snaps to the FLOOR cell instead of blending - [gridCorners] builds its first corner by taking the + * lower key on every axis, so corner 0 is the floor cell, which is the same cell the bundled rotation + * blend has always read its reflection flags from. + * + * @param FormChannel channel The flag channel to sample. + * @param Boolean staticValue The owner's static flag for this channel. + * @param Function paramValue Current value for a given parameter id. + * @return Boolean The floor cell's flag, or [staticValue]. + */ +fun ChannelGrids.flagAt( + channel: FormChannel, + staticValue: Boolean, + paramValue: (ParameterId) -> Float, + override: ChannelValue? = null, +): Boolean { + (override as? ChannelValue.Flag)?.let { pending -> return pending.flag } + val grid = this[channel] ?: return staticValue + val corners = gridCorners(grid, paramValue) ?: return staticValue + val floorCorner = corners.firstOrNull() ?: return staticValue + val cells = cellsByLinearIndex(grid) + return (cells[floorCorner.linearIndex]?.form as? ChannelValue.Flag)?.flag ?: staticValue +} + +/** + * The blended value of a SCALAR channel, or null when the owner does not track it or the pose is out of + * the track's range. + * + * The distinction from [scalarAt] matters where absence is itself information - the per-pose part + * draw-order map is sparse on purpose, so a part with no animated order stays out of it and the renderer + * keeps its static slot rather than being handed a value that merely equals the static. + * + * @param FormChannel channel The scalar channel to sample. + * @param Function paramValue Current value for a given parameter id. + * @param ChannelValue? override A pending unkeyed edit that wins over the track and the static. + * @return Float? The blended value, or null when untracked or out of range. + */ +fun ChannelGrids.scalarOrNull( + channel: FormChannel, + paramValue: (ParameterId) -> Float, + override: ChannelValue? = null, +): Float? { + (override as? ChannelValue.Scalar)?.let { pending -> return pending.value } + val grid = this[channel] ?: return null + val corners = gridCorners(grid, paramValue) ?: return null + val cells = cellsByLinearIndex(grid) + var total = 0f + for (corner in corners) { + val value = (cells[corner.linearIndex]?.form as? ChannelValue.Scalar)?.value ?: continue + total += corner.weight * value + } + return total +} + +/** + * Every axis of every channel track, in channel order. + * + * The panel's effective-parameter walk and key-mark scan must union geometry's axes with every channel + * track's, or an opacity-only track becomes invisible to the parameter list. This is the one flatten + * every walk shares; a walk that inlined its own copy instead would silently drift out of sync the + * moment a channel-only axis (e.g. a glue intensity track) is added. + * + * @return List The axes of every track. + */ +fun ChannelGrids.allAxes(): List = gridsByChannel.values.flatMap { grid -> grid.axes } \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/KeyformGridSampling.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/KeyformGridSampling.kt new file mode 100644 index 0000000..60622ca --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/KeyformGridSampling.kt @@ -0,0 +1,244 @@ +package org.umamo.runtime.eval + +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm + +/* + * Pure keyform-grid sampling: the multilinear corner selection and the pose-sampling helpers that + * both the renderer's evaluator (:render) and the MOC3 import (Moc3Import) must agree on. Hoisted + * from :render's eval so the import can compute the blend-shape delta reference (the grid form at + * the DEFAULT pose) with the EXACT same arithmetic the evaluator later subtracts - any divergence + * between the two would leak into every MOC3-imported blend shape as a residual offset. + */ + +// Bracket tolerances match the Umamo C++ Runtime, needed for ULP-parity with the differential-oracle test. +// A value within EPS_KEY of a key snaps to it; a key span below EPS_SPAN contributes no fraction. +// runtime.keyform's grid algebra shares them: authoring a key closer than EPS_KEY to an existing one, or a +// span below EPS_SPAN, produces a grid this evaluator cannot resolve, so the algebra refuses both - and it +// must refuse against these exact values, not a second copy of them. + +/** + * The key-coincidence tolerance. Public because :interop's keyform export refinement merges union + * axes against the same snap distance the sampling here and the grid algebra use; every consumer + * must bracket against this exact value, never a copy of it. + */ +public const val EPS_KEY: Float = 0.001f + +internal const val EPS_SPAN = 0.0015f + +// The Umamo C++ Runtime caps the multilinear corner set at 16 (kbCorners `maxc`); past that an axis snaps to its +// lower key instead of splitting. Replicated for fidelity (matters only for >4 fractional axes). +private const val MAX_CORNERS = 16 + +/** + * One axis's bracket of a parameter value: the lower key [index] and the [fraction] toward `index+1` + * (0 when snapped exactly onto a key). + */ +public data class AxisBracket(val index: Int, val fraction: Float) + +/** + * A grid cell selected by the current parameters, addressed by its stride-folded [linearIndex], with + * its multilinear [weight]. + */ +public data class WeightedCell(val linearIndex: Int, val weight: Float) + +/** + * Brackets [value] against an axis's sorted [keys]. Returns null when the value is out of range + * (the entity auto-hides / freezes), otherwise the lower key index and the blend fraction toward + * the next key (0 when snapped onto a key). + * + * @param FloatArray keys The axis's key positions (ascending parameter values). + * @param Float value The current parameter value on this axis. + * @return AxisBracket? The bracket, or null when out of range. + */ +public fun bindBracket(keys: FloatArray, value: Float): AxisBracket? { + val keyCount = keys.size + if (keyCount <= 1) { + if (keyCount == 0) { + return AxisBracket(0, 0f) + } + return if (value > keys[0] - EPS_KEY && value < keys[0] + EPS_KEY) AxisBracket(0, 0f) else null + } + if (value < keys[0] - EPS_KEY || value >= keys[keyCount - 1] + EPS_KEY) { + return null + } + if (value < keys[0] + EPS_KEY) { + return AxisBracket(0, 0f) + } + var hi = 1 + while (hi < keyCount && keys[hi] + EPS_KEY <= value) { + hi++ + } + if (value <= keys[hi] - EPS_KEY) { + val span = keys[hi] - keys[hi - 1] + val fraction = if (span >= EPS_SPAN) (value - keys[hi - 1]) / span else 0f + return AxisBracket(hi - 1, fraction) + } + return AxisBracket(hi, 0f) +} + +/** + * [gridCorners] with each axis's pose clamped into that axis's first..last key (constant hold past the + * ends). Authoring uses this when inserting a key beyond the current span: the new slice should copy the + * nearest end keyform, not fall back to the first cell or the owner's static. Render sampling stays on + * plain [gridCorners], which returns null out of range so geometry can freeze / hide. + * + * @param KeyformGrid grid The entity's keyform grid. + * @param Function paramValue Current value for a given parameter id. + * @return List? The weighted corners at the held pose, or null when an axis has no keys. + */ +public fun gridCornersHolding(grid: KeyformGrid<*>, paramValue: (ParameterId) -> Float): List? = + gridCorners(grid) { parameterId -> + val keys = grid.axes.firstOrNull { axis -> axis.parameterId == parameterId }?.keys + val value = paramValue(parameterId) + if (keys == null || keys.isEmpty()) { + value + } else { + value.coerceIn(keys.first(), keys.last()) + } + } + +/** + * The multilinear corner set for [grid] at the current parameters, or null when any controlling axis + * is out of range (the entity is frozen). Each fractional axis doubles the corner + * list (weights ×= frac / 1−frac) and folds a stride-based linear cell index, matching how + * [cellsByLinearIndex] folds each [KeyformCell.coordinate]. + * + * @param KeyformGrid grid The entity's keyform grid (only its axes are read). + * @param Function paramValue Current value for a given parameter id. + * @return List? The weighted corner cells, or null when hidden. + */ +public fun gridCorners(grid: KeyformGrid<*>, paramValue: (ParameterId) -> Float): List? { + var corners = mutableListOf(WeightedCell(0, 1f)) + var stride = 1 + for (axis in grid.axes) { + val bracket = bindBracket(axis.keys, paramValue(axis.parameterId)) ?: return null + val split = bracket.fraction > 0f && corners.size * 2 <= MAX_CORNERS + if (split) { + val next = ArrayList(corners.size * 2) + for (corner in corners) { + next.add( + WeightedCell( + corner.linearIndex + bracket.index * stride, + corner.weight * (1f - bracket.fraction), + ), + ) + next.add( + WeightedCell( + corner.linearIndex + (bracket.index + 1) * stride, + corner.weight * bracket.fraction, + ), + ) + } + corners = next + } else { + // Snap (on a key, or over the corner budget): every corner takes the lower key, weight kept. + for (cornerIndex in corners.indices) { + val corner = corners[cornerIndex] + corners[cornerIndex] = WeightedCell(corner.linearIndex + bracket.index * stride, corner.weight) + } + } + stride *= axis.keys.size + } + return corners +} + +/** + * Indexes a grid's cells by their stride-folded linear index (axis `a`'s stride = Π key counts of the + * earlier axes), so a [WeightedCell.linearIndex] from [gridCorners] resolves to the matching cell. + * + * A delegate to the grid's own CACHED index: the grid is immutable, and building the map per call put + * hundreds of transient HashMaps on every scrub frame. + * + * @param KeyformGrid grid The grid to index. + * @return Map linear index → cell. + */ +public fun cellsByLinearIndex(grid: KeyformGrid): Map> = grid.cellsByLinearIndex + +/** + * The drawable's grid form at the DEFAULT pose as position deltas vs the rest mesh - the shared + * blend-shape delta reference (E5). Null when the drawable is ungridded or the default pose is out + * of the grid's range (the reference is then zero). Static per drawable: the CPU pose prep, the + * GPU delta-texture bake, and the MOC3 import all call this and must agree. + * + * @param Drawable drawable The drawable. + * @param Function defaultValue Default value per parameter id. + * @return FloatArray? The interleaved reference deltas, or null. + */ +public fun meshGridDefaultDeltas(drawable: Drawable, defaultValue: (ParameterId) -> Float): FloatArray? { + val grid = drawable.geometryGrid ?: return null + val defaultCorners = gridCorners(grid, defaultValue) ?: return null + val deltas = FloatArray(grid.cells.firstOrNull()?.form?.positionDeltas?.size ?: 0) + val byLinearIndex = cellsByLinearIndex(grid) + for (corner in defaultCorners) { + val form = byLinearIndex[corner.linearIndex]?.form ?: continue + for (componentIndex in deltas.indices) { + deltas[componentIndex] += corner.weight * form.positionDeltas[componentIndex] + } + } + return deltas +} + +/** + * The lattice control points grid-blended at the given pose, or null when the warp is unkeyed or + * the pose is out of the grid's range. + * + * @param KeyformGrid? grid The warp's keyform grid. + * @param Function paramValue Value per parameter id defining the pose. + * @return FloatArray? The interleaved blended control points, or null. + */ +public fun warpControlPointsAt(grid: KeyformGrid?, paramValue: (ParameterId) -> Float): FloatArray? { + if (grid == null) { + return null + } + val corners = gridCorners(grid, paramValue) ?: return null + val byLinearIndex = cellsByLinearIndex(grid) + var blended: FloatArray? = null + for (corner in corners) { + val form = byLinearIndex[corner.linearIndex]?.form ?: continue + val target = blended ?: FloatArray(form.controlPoints.size).also { blended = it } + for (componentIndex in target.indices) { + target[componentIndex] += corner.weight * form.controlPoints[componentIndex] + } + } + return blended +} + +/** + * The rotation pivot transform grid-blended at the given pose, or null when unkeyed or out of range. + * + * The reflection flags are NOT here: they snap to the floor cell rather than blending, so they live as + * FLAG channels on the deformer's ChannelGrids and are read through flagAt. + * + * @param KeyformGrid? grid The rotation's geometry grid. + * @param Function paramValue Value per parameter id defining the pose. + * @return RotationPivotForm? The blended transform, or null. + */ +public fun rotationFormAt(grid: KeyformGrid?, paramValue: (ParameterId) -> Float): RotationPivotForm? { + if (grid == null) { + return null + } + val corners = gridCorners(grid, paramValue) ?: return null + val byLinearIndex = cellsByLinearIndex(grid) + var originX = 0f + var originY = 0f + var angle = 0f + var scale = 0f + var resolvedAnyCell = false + for (corner in corners) { + val form = byLinearIndex[corner.linearIndex]?.form ?: continue + resolvedAnyCell = true + originX += corner.weight * form.originX + originY += corner.weight * form.originY + angle += corner.weight * form.angle + scale += corner.weight * form.scale + } + if (!resolvedAnyCell) { + return null + } + return RotationPivotForm(originX, originY, angle, scale) +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/WarpApply.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/WarpApply.kt new file mode 100644 index 0000000..199323b --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/eval/WarpApply.kt @@ -0,0 +1,462 @@ +package org.umamo.runtime.eval + +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.sqrt + +/* + * Pure warp-lattice point mapping shared by the renderer and structure edits (deformer unwrap bake). + * Bit-identical to the historical :render DeformTransforms implementation. + */ + +/** + * In-grid warp transform: maps a child point `(u, v)` inside the lattice `[0,1)²` to world via the + * deformed control points [cp] - `(cols+1)×(rows+1)` points, interleaved x,y. [bilinear] true does the + * quad (bilinear) blend of the 4 surrounding control points, false the triangle split. Writes the + * result to `out[outIndex]`,`out[outIndex+1]`; returns false (and writes nothing) when `(u, v)` is + * outside the grid. + * + * @param FloatArray cp Control points, `(cols+1)*(rows+1)` interleaved x,y. + * @param Int cols Grid columns. + * @param Int rows Grid rows. + * @param Boolean bilinear Quad blend (true) vs triangle split (false). + * @param Float u Normalized horizontal coordinate. + * @param Float v Normalized vertical coordinate. + * @param FloatArray out Destination for the transformed point. + * @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`). + * @return Boolean true when in grid (and written), false when outside. + */ +fun warpInGrid( + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, + u: Float, + v: Float, + out: FloatArray, + outIndex: Int, +): Boolean { + if (u < 0f || v < 0f || u >= 1f || v >= 1f) { + return false + } + val pointsPerRow = cols + 1 + val gridU = cols * u + val gridV = rows * v + val cellU = gridU - gridU.toInt() + val cellV = gridV - gridV.toInt() + val cellIndex = gridV.toInt() * pointsPerRow + gridU.toInt() + val p00 = cellIndex * 2 + val p10 = (cellIndex + 1) * 2 + val p01 = (cellIndex + pointsPerRow) * 2 + val p11 = (cellIndex + pointsPerRow + 1) * 2 + if (!bilinear) { + if (cellU + cellV <= 1f) { + out[outIndex] = cp[p10] * cellU + cp[p00] * (1 - cellU - cellV) + cp[p01] * cellV + out[outIndex + 1] = (1 - cellU - cellV) * cp[p00 + 1] + cp[p10 + 1] * cellU + cp[p01 + 1] * cellV + } else { + val weight = (cellU - 1) + cellV + out[outIndex] = cp[p01] * (1 - cellU) + cp[p11] * weight + cp[p10] * (1 - cellV) + out[outIndex + 1] = weight * cp[p11 + 1] + (1 - cellU) * cp[p01 + 1] + (1 - cellV) * cp[p10 + 1] + } + } else { + val invCellV = 1 - cellV + out[outIndex] = + cp[p10] * cellU * invCellV + cp[p00] * (1 - cellU) * invCellV + cp[p01] * (1 - cellU) * cellV + cp[p11] * cellU * cellV + out[outIndex + 1] = + invCellV * cp[p10 + 1] * cellU + cp[p00 + 1] * (1 - cellU) * invCellV + (1 - cellU) * cp[p01 + 1] * cellV + cellU * cp[p11 + 1] * cellV + } + return true +} + +/** + * Out-of-grid warp extrapolation: a pure affine far outside the lattice, edge-blended near the border + * (mode-independent). Assumes `(u, v)` is outside `[0,1)²` (call only after [warpInGrid] returned + * false). + * + * @param FloatArray cp Control points, `(cols+1)*(rows+1)` interleaved x,y. + * @param Int cols Grid columns. + * @param Int rows Grid rows. + * @param Float u Normalized horizontal coordinate (outside `[0,1)`). + * @param Float v Normalized vertical coordinate (outside `[0,1)`). + * @param FloatArray out Destination for the transformed point. + * @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`). + */ +fun warpExtrap(cp: FloatArray, cols: Int, rows: Int, u: Float, v: Float, out: FloatArray, outIndex: Int) { + val pointsPerRow = cols + 1 + val lastRowBase = rows * pointsPerRow + val topLeftX = cp[0] + val topLeftY = cp[1] + val topRightX = cp[cols * 2] + val topRightY = cp[cols * 2 + 1] + val botLeftX = cp[lastRowBase * 2] + val botLeftY = cp[lastRowBase * 2 + 1] + val botRightX = cp[(cols + lastRowBase) * 2] + val botRightY = cp[(cols + lastRowBase) * 2 + 1] + val gridU = cols * u + val gridV = rows * v + val dUx = ((botRightX - topLeftX) + (topRightX - botLeftX)) * 0.5f + val dVx = ((botRightX - topLeftX) - (topRightX - botLeftX)) * 0.5f + val dUy = ((botRightY - topLeftY) + (topRightY - botLeftY)) * 0.5f + val dVy = ((botRightY - topLeftY) - (topRightY - botLeftY)) * 0.5f + val originX = (topLeftX + topRightX + botLeftX + botRightX) * 0.25f - (botRightX - topLeftX) * 0.5f + val originY = (topLeftY + topRightY + botLeftY + botRightY) * 0.25f - (botRightY - topLeftY) * 0.5f + if (u <= -2f || u >= 3f || v <= -2f || v >= 3f) { + out[outIndex] = dUx * u + originX + dVx * v + out[outIndex + 1] = dVy * v + dUy * u + originY + return + } + var blendU = 0f + var blendV = 0f + var corner0x = 0f + var corner0y = 0f + var corner1x = 0f + var corner1y = 0f + var corner2x = 0f + var corner2y = 0f + var corner3x = 0f + var corner3y = 0f + if (u <= 0f) { + blendU = (u + 2f) * 0.5f + corner3x = originX - 2f * dUx + corner3y = originY - 2f * dUy + if (v <= 0f) { + corner2x = topLeftX + corner2y = topLeftY + blendV = (v + 2f) * 0.5f + corner1x = originX - 2f * dVx + corner0x = corner3x - 2f * dVx + corner1y = originY - 2f * dVy + corner0y = corner3y - 2f * dVy + } else if (v < 1f) { + var loIdx = gridV.toInt() + val edgeHi: Float + val hiIdx: Int + if (rows == loIdx) { + loIdx = rows - 1 + hiIdx = rows + edgeHi = rows.toFloat() + } else { + hiIdx = loIdx + 1 + edgeHi = (loIdx + 1).toFloat() + } + blendV = gridV - loIdx + val edgeLo = loIdx.toFloat() / rows + corner1x = cp[loIdx * pointsPerRow * 2] + corner1y = cp[loIdx * pointsPerRow * 2 + 1] + corner2x = cp[hiIdx * pointsPerRow * 2] + corner2y = cp[hiIdx * pointsPerRow * 2 + 1] + corner0x = edgeLo * dVx + corner3x + corner0y = edgeLo * dVy + corner3y + corner3x = (edgeHi / rows) * dVx + corner3x + corner3y = (edgeHi / rows) * dVy + corner3y + } else { + corner1x = botLeftX + corner1y = botLeftY + blendV = (v - 1f) * 0.5f + corner0x = corner3x + dVx + corner0y = corner3y + dVy + corner3x = 3f * dVx + corner3x + corner2x = 3f * dVx + originX + corner3y = 3f * dVy + corner3y + corner2y = 3f * dVy + originY + } + } else if (u < 1f) { + if (v <= 0f) { + var loIdx = gridU.toInt() + val edgeX: Float + val edgeY: Float + val edgeHi: Float + if (cols == loIdx) { + loIdx = cols - 1 + edgeX = topRightX + edgeY = topRightY + edgeHi = cols.toFloat() + } else { + edgeX = cp[(loIdx + 1) * 2] + edgeY = cp[(loIdx + 1) * 2 + 1] + edgeHi = (loIdx + 1).toFloat() + } + corner2y = edgeY + blendV = (v + 2f) * 0.5f + blendU = gridU - loIdx + val edgeLo = loIdx.toFloat() / cols + corner3x = cp[loIdx * 2] + corner3y = cp[loIdx * 2 + 1] + corner2x = edgeX + corner0x = (edgeLo * dUx + originX) - 2f * dVx + corner0y = (edgeLo * dUy + originY) - 2f * dVy + corner1x = ((edgeHi / cols) * dUx + originX) - 2f * dVx + corner1y = ((edgeHi / cols) * dUy + originY) - 2f * dVy + } else if (v >= 1f) { + var loIdx = gridU.toInt() + val edgeHi: Float + val hiIdx: Int + if (cols == loIdx) { + loIdx = cols - 1 + hiIdx = cols + edgeHi = cols.toFloat() + } else { + hiIdx = loIdx + 1 + edgeHi = (loIdx + 1).toFloat() + } + blendV = (v - 1f) * 0.5f + blendU = gridU - loIdx + val edgeLo = loIdx.toFloat() / cols + corner0x = cp[(loIdx + lastRowBase) * 2] + corner0y = cp[(loIdx + lastRowBase) * 2 + 1] + corner1x = cp[(lastRowBase + hiIdx) * 2] + corner1y = cp[(lastRowBase + hiIdx) * 2 + 1] + corner2x = (edgeHi / cols) * dUx + originX + 3f * dVx + corner3x = edgeLo * dUx + originX + 3f * dVx + corner3y = edgeLo * dUy + originY + 3f * dVy + corner2y = (edgeHi / cols) * dUy + originY + 3f * dVy + } else { + out[outIndex] = originX + dUx * u + dVx * v + out[outIndex + 1] = originY + dVy * v + dUy * u + return + } + } else { + blendU = (u - 1f) * 0.5f + corner2x = 3f * dUx + originX + corner2y = 3f * dUy + originY + if (v <= 0f) { + corner3x = topRightX + corner3y = topRightY + blendV = (v + 2f) * 0.5f + corner0x = (originX + dUx) - 2f * dVx + corner1x = corner2x - 2f * dVx + corner1y = corner2y - 2f * dVy + corner0y = (originY + dUy) - 2f * dVy + } else if (v < 1f) { + var loIdx = gridV.toInt() + val edgeHi: Float + val hiIdx: Int + if (rows == loIdx) { + loIdx = rows - 1 + hiIdx = rows + edgeHi = rows.toFloat() + } else { + hiIdx = loIdx + 1 + edgeHi = (loIdx + 1).toFloat() + } + blendV = gridV - loIdx + corner0x = cp[(loIdx * pointsPerRow + cols) * 2] + corner0y = cp[(loIdx * pointsPerRow + cols) * 2 + 1] + corner3x = cp[(hiIdx * pointsPerRow + cols) * 2] + corner3y = cp[(hiIdx * pointsPerRow + cols) * 2 + 1] + val edgeLo = loIdx.toFloat() / rows + corner1x = edgeLo * dVx + corner2x + corner1y = edgeLo * dVy + corner2y + corner2x = (edgeHi / rows) * dVx + corner2x + corner2y = (edgeHi / rows) * dVy + corner2y + } else { + corner0x = botRightX + corner0y = botRightY + blendV = (v - 1f) * 0.5f + corner1x = corner2x + dVx + corner1y = corner2y + dVy + corner3x = originX + dUx + 3f * dVx + corner2x = 3f * dVx + corner2x + corner3y = originY + dUy + 3f * dVy + corner2y = 3f * dVy + corner2y + } + } + if (blendU + blendV <= 1f) { + out[outIndex] = (corner1x - corner0x) * blendU + corner0x + (corner3x - corner0x) * blendV + out[outIndex + 1] = (corner1y - corner0y) * blendU + corner0y + (corner3y - corner0y) * blendV + } else { + out[outIndex] = (corner3x - corner2x) * (1f - blendU) + corner2x + (corner1x - corner2x) * (1f - blendV) + out[outIndex + 1] = (1f - blendU) * (corner3y - corner2y) + corner2y + (1f - blendV) * (corner1y - corner2y) + } +} + +/** + * Warp-transforms `(u, v)` through [cp]: the in-grid fast path, falling back to extrapolation outside. + * + * @param FloatArray cp Control points, `(cols+1)*(rows+1)` interleaved x,y. + * @param Int cols Grid columns. + * @param Int rows Grid rows. + * @param Boolean bilinear Quad blend (true) vs triangle split (false). + * @param Float u Normalized horizontal coordinate. + * @param Float v Normalized vertical coordinate. + * @param FloatArray out Destination for the transformed point. + * @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`). + */ +fun warpApply( + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, + u: Float, + v: Float, + out: FloatArray, + outIndex: Int, +) { + if (!warpInGrid(cp, cols, rows, bilinear, u, v, out, outIndex)) { + warpExtrap(cp, cols, rows, u, v, out, outIndex) + } +} + +private const val WARP_INVERSE_MAX_ITERATIONS = 20 +private const val WARP_INVERSE_JACOBIAN_STEP = 1e-4f +private const val WARP_INVERSE_MAX_STEP = 0.5f + +/** + * Solves `warpApply(u, v) ≈ (targetX, targetY)` by damped Newton, writing the best `(u, v)` into + * [outU]/[outV]. Seeds from the values already in those holders (typically a bbox-normalized guess). + * + * @param FloatArray cp Lattice control points. + * @param Int cols Columns. + * @param Int rows Rows. + * @param Boolean bilinear Quad vs triangle. + * @param Float targetX Parent-local target x. + * @param Float targetY Parent-local target y. + * @param FloatArray outUOutV Length-2 holder: seed in, solved UV out. + */ +fun invertWarpApply( + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, + targetX: Float, + targetY: Float, + outUOutV: FloatArray, +) { + val toleranceSquared = warpInverseToleranceSquared(cp) + var currentU = outUOutV[0] + var currentV = outUOutV[1] + var bestU = currentU + var bestV = currentV + var bestErrorSquared = Float.MAX_VALUE + val scratch = FloatArray(2) + for (iteration in 0 until WARP_INVERSE_MAX_ITERATIONS) { + warpApply(cp, cols, rows, bilinear, currentU, currentV, scratch, 0) + val residualX = scratch[0] - targetX + val residualY = scratch[1] - targetY + val errorSquared = residualX * residualX + residualY * residualY + if (errorSquared < bestErrorSquared) { + bestErrorSquared = errorSquared + bestU = currentU + bestV = currentV + } + if (errorSquared <= toleranceSquared) { + break + } + warpApply(cp, cols, rows, bilinear, currentU + WARP_INVERSE_JACOBIAN_STEP, currentV, scratch, 0) + val dxDu = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP + val dyDu = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP + warpApply(cp, cols, rows, bilinear, currentU, currentV + WARP_INVERSE_JACOBIAN_STEP, scratch, 0) + val dxDv = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP + val dyDv = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP + val determinant = dxDu * dyDv - dxDv * dyDu + if (abs(determinant) < 1e-12f) { + break + } + var stepU = (-residualX * dyDv + dxDv * residualY) / determinant + var stepV = (-residualY * dxDu + dyDu * residualX) / determinant + val stepLength = sqrt(stepU * stepU + stepV * stepV) + if (stepLength > WARP_INVERSE_MAX_STEP) { + val damping = WARP_INVERSE_MAX_STEP / stepLength + stepU *= damping + stepV *= damping + } + currentU += stepU + currentV += stepV + } + outUOutV[0] = bestU + outUOutV[1] = bestV +} + +private fun warpInverseToleranceSquared(cp: FloatArray): Float { + var minX = Float.MAX_VALUE + var maxX = -Float.MAX_VALUE + var minY = Float.MAX_VALUE + var maxY = -Float.MAX_VALUE + val pointCount = cp.size / 2 + for (pointIndex in 0 until pointCount) { + val x = cp[pointIndex * 2] + val y = cp[pointIndex * 2 + 1] + minX = minOf(minX, x) + maxX = maxOf(maxX, x) + minY = minOf(minY, y) + maxY = maxOf(maxY, y) + } + val span = max(maxX - minX, maxY - minY) + val tolerance = max(1e-5f * span, 1e-6f) + return tolerance * tolerance +} + +/** + * Maps interleaved points through a warp lattice (forward). + * + * @param FloatArray points Interleaved child-local positions. + * @param FloatArray cp Control points. + * @param Int cols Columns. + * @param Int rows Rows. + * @param Boolean bilinear Blend mode. + * @return FloatArray Fresh parent-local positions. + */ +fun mapPointsThroughWarpLattice( + points: FloatArray, + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, +): FloatArray { + val out = FloatArray(points.size) + val scratch = FloatArray(2) + var index = 0 + while (index + 1 < points.size) { + warpApply(cp, cols, rows, bilinear, points[index], points[index + 1], scratch, 0) + out[index] = scratch[0] + out[index + 1] = scratch[1] + index += 2 + } + return out +} + +/** + * Inverse-maps interleaved parent-local points into a warp's UV, seeding each point from a normalized + * guess against the lattice control-point AABB. + * + * @param FloatArray points Interleaved parent-local positions. + * @param FloatArray cp Control points. + * @param Int cols Columns. + * @param Int rows Rows. + * @param Boolean bilinear Blend mode. + * @return FloatArray Fresh child-local UV positions. + */ +fun invertPointsThroughWarpLattice( + points: FloatArray, + cp: FloatArray, + cols: Int, + rows: Int, + bilinear: Boolean, +): FloatArray { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var index = 0 + while (index + 1 < cp.size) { + minX = minOf(minX, cp[index]) + maxX = maxOf(maxX, cp[index]) + minY = minOf(minY, cp[index + 1]) + maxY = maxOf(maxY, cp[index + 1]) + index += 2 + } + val width = max(maxX - minX, 1e-6f) + val height = max(maxY - minY, 1e-6f) + val out = FloatArray(points.size) + val uv = FloatArray(2) + index = 0 + while (index + 1 < points.size) { + uv[0] = (points[index] - minX) / width + uv[1] = (points[index + 1] - minY) / height + invertWarpApply(cp, cols, rows, bilinear, points[index], points[index + 1], uv) + out[index] = uv[0] + out[index + 1] = uv[1] + index += 2 + } + return out +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelCompaction.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelCompaction.kt new file mode 100644 index 0000000..9d7d17d --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelCompaction.kt @@ -0,0 +1,247 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.eval.EPS_KEY +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderGroup + +/* + * The post-import compaction pass: reduce every channel track to the axes and keys it actually needs, and + * lift a track that never varies into its owner's static field. + * + * Cubism keys every channel on every cell of one bundled grid, so straight after the fan-out a typical + * drawable's opacity track is the same value repeated across the whole grid. Compacting retires those + * tracks entirely, which is what turns an imported Cubism rig into a sparse Umamo one - and it is where + * the split pays for itself: the per-frame scalar blends collapse into field reads. + * + * Two rules keep this safe: + * + * - GEOMETRY IS NEVER COMPACTED. A toggle-part drawable can carry bit-identical geometry across an axis + * whose keys deliberately do not bracket the parameter's default; dropping that axis would make the + * drawable permanently visible, which is a change to someone's rig, not a change in precision. It + * would also move the delta texture's column layout for no benefit. + * - EXACT ONLY. A key is dropped only when the stored value is bit-equal to the blend of its + * neighbours; see KeyformGridCompaction. A near-miss is a value the rigger chose. + * + * Run as a separate model pass rather than inside the importers so it is independently testable and can be + * switched off wholesale when a result needs bisecting against the un-compacted import. + * + * DEFERRED: three importer special cases are now redundant in principle - Cmo3Import's + * `takeIf { it.axes.isNotEmpty() }` on part tracks, its PartComposite seed from the first form, and + * Moc3Import's deliberate zero-axis single-cell grid. They are left in place because removing them is a + * BEHAVIOUR change, not a cleanup: each decides whether a static part's authored composite or its baked + * keyform wins, and the compaction-on/off equivalence test cannot see the difference (both sides carry the + * special case). Only the corpus parity and C-core oracles would catch a mistake, so they should come out + * one at a time under those gates rather than as a batch. + */ + +/** + * One owner's channel tracks after compaction: the tracks that still vary, and the constants lifted out. + * + * @property ChannelGrids channelGrids The surviving tracks. + * @property Map constants The channels that collapsed, and the value each holds everywhere. + */ +private class CompactedChannels( + val channelGrids: ChannelGrids, + val constants: Map, +) + +/** + * Compacts every track, separating the ones that collapsed to a constant from the ones that still vary. + * + * @param Function axisSpansRange Whether an axis's keys bracket its parameter's whole range - the + * out-of-span gate compaction must preserve (see KeyformGridCompaction's file note). + * @return CompactedChannels The surviving tracks plus the lifted constants. + */ +private fun ChannelGrids.compactedTracks(axisSpansRange: (KeyformAxis) -> Boolean): CompactedChannels { + if (isEmpty) { + return CompactedChannels(this, emptyMap()) + } + val surviving = LinkedHashMap>(gridsByChannel.size) + val constants = LinkedHashMap() + for ((channel, grid) in gridsByChannel) { + when (val result = grid.compacted(ChannelValueInterpolator, channel.valueKind, axisSpansRange)) { + is CompactionResult.Constant -> constants[channel] = result.form + is CompactionResult.Reduced -> surviving[channel] = result.grid + } + } + val newGrids = if (surviving.isEmpty()) ChannelGrids.Empty else ChannelGrids(surviving) + return CompactedChannels(newGrids, constants) +} + +/** + * A lifted DRAW_ORDER constant resolved against an Int draw-order slot: the integral static to write (or + * null to keep the owner's), and the channel grids to keep. + * + * @property Int? staticDrawOrder The exactly-integral lifted draw order, or null. + * @property ChannelGrids channelGrids The grids to keep - the compacted set, or the compacted set with + * [originalGrids]' DRAW_ORDER track restored when the constant was fractional. + */ +private class LiftedDrawOrder( + val staticDrawOrder: Int?, + val channelGrids: ChannelGrids, +) + +/** + * Resolves a lifted DRAW_ORDER constant against an Int draw-order slot. + * + * A part-like owner's static slot is an Int, so a fractional constant would have to round, and rounding + * could reorder two siblings the track kept distinct. Such a track goes back into the kept grids from + * [originalGrids] instead - correct, just not free. + * + * @param Map constants The lifted constants. + * @param ChannelGrids compactedGrids The surviving tracks after compaction. + * @param ChannelGrids originalGrids The owner's pre-compaction tracks (the fractional track's source). + * @return LiftedDrawOrder The static to write (or null) and the grids to keep. + */ +private fun liftedDrawOrder( + constants: Map, + compactedGrids: ChannelGrids, + originalGrids: ChannelGrids, +): LiftedDrawOrder { + if (constants.hasFractionalDrawOrder()) { + val restored = compactedGrids.gridsByChannel + (FormChannel.DRAW_ORDER to (originalGrids[FormChannel.DRAW_ORDER]!!)) + return LiftedDrawOrder(staticDrawOrder = null, channelGrids = ChannelGrids(restored)) + } + return LiftedDrawOrder(constants.integralDrawOrderOrNull(), compactedGrids) +} + +/** + * This model with every channel track compacted and every collapsed track lifted into its owner's static. + * + * Geometry grids are untouched (see the file note). Evaluation is unchanged to within the tolerance the + * fidelity contract already allows for geometry, and is EXACT wherever a track collapsed to a constant - + * a field read cannot drift the way a weighted sum over corners can. An axis whose keys do not bracket + * its parameter's range is left alone entirely: out-of-span poses fall back to the owner's static, and a + * lift would overwrite exactly the static they fall back to. + * + * @return PuppetModel The compacted model. + */ +fun PuppetModel.withChannelsCompacted(): PuppetModel { + val rangeByParameterId = + parameters.associate { parameter -> + parameter.id to (minOf(parameter.min, parameter.max) to maxOf(parameter.min, parameter.max)) + } + // EPS_KEY on both ends: a key the evaluator cannot tell apart from the range end brackets it. An axis + // on a parameter the model does not list is never spanning - a dangling id must stay conservative. + val axisSpansRange: (KeyformAxis) -> Boolean = { axis -> + val range = rangeByParameterId[axis.parameterId] + range != null && + axis.keys.isNotEmpty() && + axis.keys.first() <= range.first + EPS_KEY && + axis.keys.last() >= range.second - EPS_KEY + } + return copy( + drawables = + drawables.map { drawable -> + val compacted = drawable.channelGrids.compactedTracks(axisSpansRange) + if (compacted.constants.isEmpty() && compacted.channelGrids === drawable.channelGrids) { + drawable + } else { + drawable.copy( + channelGrids = compacted.channelGrids, + drawOrder = compacted.constants.scalarOr(FormChannel.DRAW_ORDER, drawable.drawOrder), + opacity = compacted.constants.scalarOr(FormChannel.OPACITY, drawable.opacity), + multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor), + screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, drawable.screenColor), + ) + } + }, + deformers = deformers.map { deformer -> deformer.withChannelsCompacted(axisSpansRange) }, + parts = parts.map { part -> part.withChannelsCompacted(axisSpansRange) }, + glues = + glues.map { glue -> + val compacted = glue.channelGrids.compactedTracks(axisSpansRange) + if (compacted.constants.isEmpty() && compacted.channelGrids === glue.channelGrids) { + glue + } else { + glue.copy( + channelGrids = compacted.channelGrids, + intensity = compacted.constants.scalarOr(FormChannel.GLUE_INTENSITY, glue.intensity), + ) + } + }, + renderRoot = renderRoot.withChannelsCompacted(axisSpansRange), + ) +} + +/** This deformer with its channel tracks compacted and any constants lifted into its statics. */ +private fun Deformer.withChannelsCompacted(axisSpansRange: (KeyformAxis) -> Boolean): Deformer { + val compacted = channelGrids.compactedTracks(axisSpansRange) + if (compacted.constants.isEmpty() && compacted.channelGrids === channelGrids) { + return this + } + return when (this) { + is Deformer.Warp -> + copy( + channelGrids = compacted.channelGrids, + opacity = compacted.constants.scalarOr(FormChannel.OPACITY, opacity), + multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, multiplyColor), + screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, screenColor), + ) + + is Deformer.Rotation -> + copy( + channelGrids = compacted.channelGrids, + opacity = compacted.constants.scalarOr(FormChannel.OPACITY, opacity), + multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, multiplyColor), + screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, screenColor), + flipX = compacted.constants.flagOr(FormChannel.FLIP_X, flipX), + flipY = compacted.constants.flagOr(FormChannel.FLIP_Y, flipY), + ) + } +} + +/** + * This part with its channel tracks compacted, constants lifted into [Part.drawOrder] and the composite. + * + * A collapsed DRAW_ORDER is lifted only when its value is exactly an integer: the part's static slot is an + * Int, so a fractional constant would have to round, and rounding could reorder two parts that the track + * kept distinct. Such a track keeps its (reduced) grid instead - correct, just not free. + */ +private fun Part.withChannelsCompacted(axisSpansRange: (KeyformAxis) -> Boolean): Part { + val compacted = channelGrids.compactedTracks(axisSpansRange) + if (compacted.constants.isEmpty() && compacted.channelGrids === channelGrids) { + return this + } + val lifted = liftedDrawOrder(compacted.constants, compacted.channelGrids, channelGrids) + return copy( + channelGrids = lifted.channelGrids, + drawOrder = lifted.staticDrawOrder ?: drawOrder, + composite = + composite.copy( + opacity = compacted.constants.scalarOr(FormChannel.OPACITY, composite.opacity), + multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, composite.multiplyColor), + screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, composite.screenColor), + ), + ) +} + +/** + * This render group (and its subtree) with its channel tracks compacted. + * + * The render tree carries its own copy of each part's tracks, and for a MOC3 import it is the baked + * authority rather than something derived from the parts - so it is compacted in place instead of being + * re-derived, which would discard the baked order. + */ +private fun RenderGroup.withChannelsCompacted(axisSpansRange: (KeyformAxis) -> Boolean): RenderGroup { + val compacted = channelGrids.compactedTracks(axisSpansRange) + val lifted = liftedDrawOrder(compacted.constants, compacted.channelGrids, channelGrids) + return copy( + drawOrder = lifted.staticDrawOrder ?: drawOrder, + children = children.map { child -> if (child is RenderGroup) child.withChannelsCompacted(axisSpansRange) else child }, + channelGrids = lifted.channelGrids, + composite = + composite?.copy( + opacity = compacted.constants.scalarOr(FormChannel.OPACITY, composite.opacity), + multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, composite.multiplyColor), + screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, composite.screenColor), + ), + ) +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelConstants.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelConstants.kt new file mode 100644 index 0000000..1bc477e --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelConstants.kt @@ -0,0 +1,65 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel + +/* + * Readers over a map of lifted channel constants - the values that channel tracks collapsed to, waiting + * to be written into their owner's static fields. Shared by the post-import compaction pass + * (ChannelCompaction) and the parameter-delete collapse (ParameterCrudEdits in :edit), so the two paths + * that lift a track into a static cannot drift apart. + */ + +/** + * The lifted constant for [channel] as a float, or [fallback] when the channel did not collapse. + * + * @param FormChannel channel The channel to read. + * @param Float fallback The owner's current static value. + * @return Float The lifted scalar, or [fallback]. + */ +fun Map.scalarOr(channel: FormChannel, fallback: Float): Float = + (this[channel] as? ChannelValue.Scalar)?.value ?: fallback + +/** + * The lifted constant for [channel] as a color, or [fallback] when the channel did not collapse. + * + * @param FormChannel channel The channel to read. + * @param ColorRgb fallback The owner's current static value. + * @return ColorRgb The lifted color, or [fallback]. + */ +fun Map.colorOr(channel: FormChannel, fallback: ColorRgb): ColorRgb = + (this[channel] as? ChannelValue.Color)?.color ?: fallback + +/** + * The lifted constant for [channel] as a flag, or [fallback] when the channel did not collapse. + * + * @param FormChannel channel The channel to read. + * @param Boolean fallback The owner's current static value. + * @return Boolean The lifted flag, or [fallback]. + */ +fun Map.flagOr(channel: FormChannel, fallback: Boolean): Boolean = + (this[channel] as? ChannelValue.Flag)?.flag ?: fallback + +/** + * The lifted DRAW_ORDER constant as an exact Int, or null when absent or fractional. + * + * A part-like owner stores its draw order in an Int slot, so a fractional constant cannot lift - rounding + * it could reorder two siblings the track kept distinct. Callers pair this with [hasFractionalDrawOrder] + * to keep such a value as a track instead. + * + * @return Int? The exactly-integral lifted draw order, or null. + */ +fun Map.integralDrawOrderOrNull(): Int? { + val lifted = (this[FormChannel.DRAW_ORDER] as? ChannelValue.Scalar) ?: return null + return lifted.value.toInt().takeIf { candidate -> candidate.toFloat() == lifted.value } +} + +/** + * Whether a DRAW_ORDER constant was lifted but is fractional and so must stay a track rather than round + * into an Int static slot. + * + * @return Boolean True when DRAW_ORDER collapsed to a non-integral value. + */ +fun Map.hasFractionalDrawOrder(): Boolean = + this[FormChannel.DRAW_ORDER] is ChannelValue.Scalar && integralDrawOrderOrNull() == null \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelFanOut.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelFanOut.kt new file mode 100644 index 0000000..cb08b21 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/ChannelFanOut.kt @@ -0,0 +1,136 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.RotationForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm + +/* + * The import fan-out: splitting one bundled keyform grid into a geometry grid plus per-channel tracks. + * + * CMO3 and MOC3 both store an entity's keyforms as a single grid of all-or-nothing cells, so both + * importers keep building exactly that, and the split happens here afterwards. Every fanned track SHARES + * the source grid's axes list by reference and holds one cell per source cell, which makes the split a + * pure re-shape: gridCorners over a fanned track returns the same corners in the same order as over the + * source, and each channel's weighted sum accumulates in the same order the bundled blend used. The + * evaluated result is therefore bit-identical, which is what lets the whole migration be gated on a + * zero-diff oracle run rather than a tolerance. + * + * Compaction is deliberately NOT part of this - it runs as a separate model pass so the split can land + * with the oracle green by construction and compaction can be turned on (and off) independently. + */ + +/** + * This grid re-shaped into a channel track, each cell's form mapped through [valueOf]. + * + * The axes list is shared by reference, not copied - that identity is what guarantees the track brackets + * every pose exactly as the source grid does. + * + * @param Function valueOf Maps one source form to the channel value it carries. + * @return KeyformGrid The same shape, carrying channel values. + */ +fun KeyformGrid.asChannelTrack(valueOf: (TForm) -> ChannelValue): KeyformGrid = + KeyformGrid(axes, cells.map { cell -> KeyformCell(cell.coordinate, valueOf(cell.form)) }) + +/** + * This grid re-shaped into a geometry grid, each cell's form mapped through [geometryOf]. + * + * @param Function geometryOf Maps one source form to its geometry payload. + * @return KeyformGrid The same shape, carrying geometry forms. + */ +fun KeyformGrid.asGeometryGrid(geometryOf: (TForm) -> TGeometry): KeyformGrid = + KeyformGrid(axes, cells.map { cell -> KeyformCell(cell.coordinate, geometryOf(cell.form)) }) + +/** + * A [ChannelGrids] holding the given tracks, dropping any that is null. + * + * A null track means the owner does not key that channel and reads its static value instead, so an + * all-null call yields the shared empty instance and allocates nothing. + * + * @param Pair tracks The channel-to-track pairs; null tracks are omitted. + * @return ChannelGrids The tracks, or ChannelGrids.Empty when none survive. + */ +fun channelGridsOf(vararg tracks: Pair?>): ChannelGrids { + val present = LinkedHashMap>(tracks.size) + for ((channel, grid) in tracks) { + if (grid != null) { + present[channel] = grid + } + } + return if (present.isEmpty()) ChannelGrids.Empty else ChannelGrids(present) +} + +/** + * One deformer's bundled keyform grid, split into its geometry grid and its channel tracks. + * + * @property KeyformGrid geometry The lattice / pivot geometry. + * @property ChannelGrids channels The render (and, for a rotation, reflection) tracks. + */ +class FannedDeformer( + val geometry: KeyformGrid, + val channels: ChannelGrids, +) + +/** + * Splits a bundled warp grid into its lattice geometry and its render channels. + * + * Shared by both importers rather than written twice, so the two paths cannot drift in which channel a + * value lands on - the failure mode a per-importer copy invites. + * + * @return FannedDeformer The lattice grid plus the opacity / multiply / screen tracks. + */ +fun KeyformGrid.fanOutWarp(): FannedDeformer = + FannedDeformer( + asGeometryGrid { form -> WarpLatticeForm(form.controlPoints) }, + channelGridsOf( + FormChannel.OPACITY to asChannelTrack { form -> ChannelValue.Scalar(form.opacity) }, + FormChannel.MULTIPLY_COLOR to asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) }, + FormChannel.SCREEN_COLOR to asChannelTrack { form -> ChannelValue.Color(form.screenColor) }, + ), + ) + +/** + * Splits a bundled rotation grid into its pivot geometry and its channels. + * + * The reflection flags become FLAG tracks here: they snap to the floor cell rather than blending, so they + * cannot ride the pivot form beside values that interpolate. + * + * @return FannedDeformer The pivot grid plus the render and reflection tracks. + */ +fun KeyformGrid.fanOutRotation(): FannedDeformer = + FannedDeformer( + asGeometryGrid { form -> RotationPivotForm(form.originX, form.originY, form.angle, form.scale) }, + channelGridsOf( + FormChannel.OPACITY to asChannelTrack { form -> ChannelValue.Scalar(form.opacity) }, + FormChannel.MULTIPLY_COLOR to asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) }, + FormChannel.SCREEN_COLOR to asChannelTrack { form -> ChannelValue.Color(form.screenColor) }, + FormChannel.FLIP_X to asChannelTrack { form -> ChannelValue.Flag(form.flipX) }, + FormChannel.FLIP_Y to asChannelTrack { form -> ChannelValue.Flag(form.flipY) }, + ), + ) + +/** + * Splits a bundled art-mesh grid into its per-vertex deltas and its render channels. + * + * The geometry half is the only channel the GPU consumes, and its cell linear indices are the delta + * texture's column layout - which is why it stays a separate typed grid rather than another map entry. + * + * @return FannedDeformer The delta grid plus the draw-order / opacity / multiply / screen tracks. + */ +fun KeyformGrid.fanOutMesh(): FannedDeformer = + FannedDeformer( + asGeometryGrid { form -> MeshDeltaForm(form.positionDeltas) }, + channelGridsOf( + FormChannel.DRAW_ORDER to asChannelTrack { form -> ChannelValue.Scalar(form.drawOrder) }, + FormChannel.OPACITY to asChannelTrack { form -> ChannelValue.Scalar(form.opacity) }, + FormChannel.MULTIPLY_COLOR to asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) }, + FormChannel.SCREEN_COLOR to asChannelTrack { form -> ChannelValue.Color(form.screenColor) }, + ), + ) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/FormInterpolator.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/FormInterpolator.kt new file mode 100644 index 0000000..999ed4d --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/FormInterpolator.kt @@ -0,0 +1,160 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm + +/* + * The one interpolation primitive the grid algebra is allowed to use: a 1-D blend between two ADJACENT + * slices of a single axis. The algebra deliberately never performs an N-D blend - that is the evaluator's + * job in runtime.eval, and duplicating it here would put a second, drifting copy of the deformation math + * next to the one the differential oracle checks. + * + * Key insertion, export refinement, and compaction all reduce to this one operation, which is what makes + * the losslessness argument one-dimensional and therefore checkable. + */ + +/** + * Blends a form between two adjacent slices of one axis, and tests two stored forms for exact equality. + * + * The [interpolate] contract is strict: it MUST compute `(1 - fraction) * lower + fraction * upper`, the + * same expression `gridCorners` builds its corner weights from - NOT the numerically tidier + * `lower + (upper - lower) * fraction`. Compaction drops a key only when the stored form is bit-equal to + * this function's output, and refinement re-inserts that key by evaluating this same function on the same + * inputs; IEEE-754 is deterministic, so sharing one expression is exactly what makes the two mutual + * inverses. Switching to an algebraically equal formula silently breaks that. + * + * @param TForm The cell payload type this interpolator handles. + */ +interface FormInterpolator { + /** + * The form [fraction] of the way from [lower] to [upper]. + * + * @param TForm lower The form at the lower key. + * @param TForm upper The form at the next key up. + * @param Float fraction The blend position in 0..1 (0 yields [lower], 1 yields [upper]). + * @return TForm The blended form. + */ + fun interpolate(lower: TForm, upper: TForm, fraction: Float): TForm + + /** + * Whether two stored forms are EXACTLY equal - bit-equal floats, never an epsilon compare. + * + * Compaction gates on this. An epsilon here would silently alter a rigger's authored values, which + * the fidelity contract forbids; a value that is merely close is a value someone chose. + * + * @param TForm left The first form. + * @param TForm right The second form. + * @return Boolean True when the two forms are exactly equal. + */ + fun isExactlyEqual(left: TForm, right: TForm): Boolean +} + +/** + * Blends two floats with the evaluator's own corner-weight expression. + * + * @param Float lower The lower key's value. + * @param Float upper The upper key's value. + * @param Float fraction The blend position in 0..1. + * @return Float The blended value. + */ +internal fun blendScalar(lower: Float, upper: Float, fraction: Float): Float = (1f - fraction) * lower + fraction * upper + +/** + * Blends two interleaved float arrays component-wise. + * + * A length mismatch is a malformed grid rather than something to paper over, so the result takes the + * shorter length and the caller's own vertex-count guards catch it - matching how the evaluator's blend + * sites already tolerate a short delta array. + * + * @param FloatArray lower The lower key's components. + * @param FloatArray upper The upper key's components. + * @param Float fraction The blend position in 0..1. + * @return FloatArray The blended components. + */ +internal fun blendComponents(lower: FloatArray, upper: FloatArray, fraction: Float): FloatArray { + val length = minOf(lower.size, upper.size) + val blended = FloatArray(length) + for (componentIndex in 0 until length) { + blended[componentIndex] = blendScalar(lower[componentIndex], upper[componentIndex], fraction) + } + return blended +} + +/** Interpolates a drawable's per-vertex position deltas. */ +object MeshDeltaInterpolator : FormInterpolator { + override fun interpolate(lower: MeshDeltaForm, upper: MeshDeltaForm, fraction: Float): MeshDeltaForm = + MeshDeltaForm(blendComponents(lower.positionDeltas, upper.positionDeltas, fraction)) + + override fun isExactlyEqual(left: MeshDeltaForm, right: MeshDeltaForm): Boolean = + left.positionDeltas.contentEquals(right.positionDeltas) +} + +/** Interpolates a warp deformer's absolute lattice control points. */ +object WarpLatticeInterpolator : FormInterpolator { + override fun interpolate(lower: WarpLatticeForm, upper: WarpLatticeForm, fraction: Float): WarpLatticeForm = + WarpLatticeForm(blendComponents(lower.controlPoints, upper.controlPoints, fraction)) + + override fun isExactlyEqual(left: WarpLatticeForm, right: WarpLatticeForm): Boolean = + left.controlPoints.contentEquals(right.controlPoints) +} + +/** Interpolates a rotation deformer's absolute pivot transform (its flags are FLAG channels, not geometry). */ +object RotationPivotInterpolator : FormInterpolator { + override fun interpolate(lower: RotationPivotForm, upper: RotationPivotForm, fraction: Float): RotationPivotForm = + RotationPivotForm( + originX = blendScalar(lower.originX, upper.originX, fraction), + originY = blendScalar(lower.originY, upper.originY, fraction), + angle = blendScalar(lower.angle, upper.angle, fraction), + scale = blendScalar(lower.scale, upper.scale, fraction), + ) + + override fun isExactlyEqual(left: RotationPivotForm, right: RotationPivotForm): Boolean = + left.originX == right.originX && + left.originY == right.originY && + left.angle == right.angle && + left.scale == right.scale +} + +/** + * Interpolates a channel track's value. + * + * Scalars and colors blend; a FLAG snaps to [lower], which is the floor cell. That matches the evaluator + * exactly: `gridCorners` seeds a single corner and appends the lower-key split before the upper-key one, + * so `corners[0]` is always the all-lower-key corner - and that is the corner the rotation flags already + * read today. A mismatched pair (two different kinds in one track) is a malformed track; [lower] wins, + * so the track keeps its own kind rather than silently changing type mid-axis. + */ +object ChannelValueInterpolator : FormInterpolator { + override fun interpolate(lower: ChannelValue, upper: ChannelValue, fraction: Float): ChannelValue = + when (lower) { + is ChannelValue.Scalar -> { + if (upper is ChannelValue.Scalar) { + ChannelValue.Scalar(blendScalar(lower.value, upper.value, fraction)) + } else { + lower + } + } + + is ChannelValue.Color -> { + if (upper is ChannelValue.Color) { + ChannelValue.Color( + ColorRgb( + blendScalar(lower.color.red, upper.color.red, fraction), + blendScalar(lower.color.green, upper.color.green, fraction), + blendScalar(lower.color.blue, upper.color.blue, fraction), + ), + ) + } else { + lower + } + } + + // A boolean has no midpoint: the floor cell wins for the whole span, matching the evaluator. + is ChannelValue.Flag -> lower + } + + override fun isExactlyEqual(left: ChannelValue, right: ChannelValue): Boolean = left == right +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridAlgebra.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridAlgebra.kt new file mode 100644 index 0000000..b9e9155 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridAlgebra.kt @@ -0,0 +1,658 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.eval.EPS_KEY +import org.umamo.runtime.eval.EPS_SPAN +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import kotlin.math.abs + +/* + * The keyform-grid authoring algebra: bind an entity to a parameter, insert / remove a key, write a cell, + * capture a form at the current pose, and refine a grid onto a wider key set for export. + * + * Two invariants run through all of it, both forced by how the evaluator brackets a pose (see + * runtime.eval.bindBracket): + * + * 1. An axis must SPAN its parameter's range. A pose outside an axis's keys makes bindBracket return + * null, which hides the entity outright for a geometry grid and drops a channel to its static value. + * So seeding always reaches min and max, and "arbitrary key positions" means arbitrary INTERIOR keys. + * 2. An axis must keep at least TWO keys. A single-key axis resolves only within EPS_KEY of that key + * and is null everywhere else, so removing down to one key is a vanishing trap - removal collapses + * the axis instead. + * + * A new axis is always APPENDED, never spliced in parameter order: the cell linear index folds axis 0 as + * the fastest-varying, so appending leaves every existing cell's index (and therefore the GPU delta + * texture's column layout) untouched, while an insert in the middle renumbers all of them. + * + * Sparse grids - which Cmo3Import can produce when a cell's form guid does not resolve - are refused + * rather than repaired: every op below returns its receiver unchanged instead of inventing cells. + */ + +/** What [withKeyInserted] does with a key that falls outside the axis's existing key span. */ +enum class OutOfSpanKeyPolicy { + /** + * Widen the axis, replicating the nearest end slice into the new one. Constant extrapolation, never + * linear: extending a trend past its last authored key would invent motion the rigger never made. + */ + Extend, + + /** Leave the grid alone. */ + Reject, +} + +/** + * This grid with a new axis for [parameter] appended, every existing cell replicated across its keys. + * + * Binding an entity to a parameter for the first time. A null receiver seeds a brand new grid holding + * [currentForm] at every key; an existing grid is replicated once per new key, so the entity looks exactly + * as it did before at every pose - binding alone never changes the render, only the capture that follows + * does. + * + * Returns the receiver unchanged when the grid already keys [parameter] (the bind is already true), and + * NULL on a refusal - a sparse receiver, or a parameter whose range cannot support two distinct keys (a + * min == max parameter is not animatable, and a one-key axis would hide the entity). Null rather than + * the receiver, so a caller's `?: return` refusal guard fires for a non-null receiver too - returning the + * receiver here once let a capture proceed and write onto the channel's OTHER axes. + * + * The seeded keys are the parameter's minimum, default, and maximum, deduplicated - what Cubism seeds, and + * the only layout that both spans the range and puts a key at the neutral pose. A fourth key at the + * current scrub was tried and dropped: the capture that follows a bind lands at the scrub anyway, so the + * extra key changed nothing except to author one the rigger never asked for. + * + * @param Parameter parameter The parameter to bind to; its min / default / max define the seeded keys. + * @param TForm currentForm The form to hold at every seeded key (the entity's present look). + * @return KeyformGrid The grid with the axis appended, the receiver when it already keys [parameter], or + * null when nothing could be seeded. + */ +fun KeyformGrid?.withAxisSeeded(parameter: Parameter, currentForm: TForm): KeyformGrid? { + if (this != null && axisIndexOf(parameter.id) >= 0) { + return this + } + if (this != null && !isDense) { + return null + } + val seedKeys = distinctSortedKeys(floatArrayOf(parameter.min, parameter.default, parameter.max)) + if (seedKeys.size < 2) { + return null + } + val newAxis = KeyformAxis(parameter.id, seedKeys) + if (this == null) { + val cells = seedKeys.indices.map { keyIndex -> KeyformCell(intArrayOf(keyIndex), currentForm) } + return KeyformGrid(listOf(newAxis), cells) + } + // Appended, so every existing coordinate keeps its meaning and simply gains a trailing component. + val replicated = + buildList { + for (keyIndex in seedKeys.indices) { + for (cell in cells) { + add(KeyformCell(cell.coordinate + keyIndex, cell.form)) + } + } + } + return KeyformGrid(axes + newAxis, replicated) +} + +/** + * This grid with a new key at [keyValue] on [parameterId]'s axis, filling the whole new slice. + * + * Inserting a key adds an entire hyperplane of cells, not one cell: on a grid keyed over two parameters, + * a new key on the first axis needs one new cell for every key of the second. Only the interior cells can + * be derived, by blending the two neighbouring slices with [interpolator] - which is exactly the operation + * the export refinement performs, so the two share this code rather than growing a second copy. + * + * Returns the receiver unchanged when the axis is absent, the grid is sparse, [keyValue] is within EPS_KEY + * of an existing key, the insertion would leave a span below EPS_SPAN (a span that narrow evaluates as a + * step rather than a blend), or the key falls outside the span under [OutOfSpanKeyPolicy.Reject]. + * + * @param ParameterId parameterId The axis to insert into. + * @param Float keyValue The parameter value of the new key. + * @param FormInterpolator interpolator Blends the neighbouring slices into the new one. + * @param OutOfSpanKeyPolicy outOfSpan How to treat a key beyond the axis's current ends. + * @return KeyformGrid The grid with the key inserted, or the receiver when the insert was refused. + */ +fun KeyformGrid.withKeyInserted( + parameterId: ParameterId, + keyValue: Float, + interpolator: FormInterpolator, + outOfSpan: OutOfSpanKeyPolicy = OutOfSpanKeyPolicy.Extend, +): KeyformGrid { + val axisIndex = axisIndexOf(parameterId) + if (axisIndex < 0 || !isDense) { + return this + } + val oldKeys = axes[axisIndex].keys + if (oldKeys.isEmpty()) { + return this + } + // Through keyIndexAt, the one definition of the evaluator's on-a-key snap tolerance. + if (keyIndexAt(parameterId, keyValue) >= 0) { + return this + } + // The insert position in the NEW key array: the count of existing keys below the new value. + val insertPosition = oldKeys.count { existing -> existing < keyValue } + val isBelowSpan = insertPosition == 0 + val isAboveSpan = insertPosition == oldKeys.size + if ((isBelowSpan || isAboveSpan) && outOfSpan == OutOfSpanKeyPolicy.Reject) { + return this + } + if (!spansStayResolvable(oldKeys, keyValue, insertPosition)) { + return this + } + val newKeys = FloatArray(oldKeys.size + 1) + oldKeys.copyInto(newKeys, destinationOffset = 0, startIndex = 0, endIndex = insertPosition) + newKeys[insertPosition] = keyValue + oldKeys.copyInto(newKeys, destinationOffset = insertPosition + 1, startIndex = insertPosition, endIndex = oldKeys.size) + + val formByOldIndex = cells.associate { cell -> linearIndexOf(cell.coordinate) to cell.form } + val newAxes = axes.toMutableList() + newAxes[axisIndex] = KeyformAxis(parameterId, newKeys) + + // The source slices for the new one: the two it sits between, or the single nearest end when extending. + val lowerSourceKeyIndex = if (isBelowSpan) 0 else insertPosition - 1 + val upperSourceKeyIndex = if (isAboveSpan) oldKeys.size - 1 else insertPosition + val blendFraction = + if (isBelowSpan || isAboveSpan) { + // Constant extrapolation - both source indices are the same slice, so the fraction is inert. + 0f + } else { + val span = oldKeys[upperSourceKeyIndex] - oldKeys[lowerSourceKeyIndex] + if (span >= EPS_SPAN) (keyValue - oldKeys[lowerSourceKeyIndex]) / span else 0f + } + + val newCells = ArrayList>(cells.size + cells.size / maxOf(1, oldKeys.size) + 1) + // Existing cells keep their forms; those at or past the insert shift one key index up. + for (cell in cells) { + val shifted = cell.coordinate.copyOf() + if (shifted[axisIndex] >= insertPosition) { + shifted[axisIndex] = shifted[axisIndex] + 1 + } + newCells.add(KeyformCell(shifted, cell.form)) + } + // One new cell per combination of the OTHER axes, enumerated from any single existing slice. + for (cell in cells) { + if (cell.coordinate[axisIndex] != 0) { + continue + } + val lowerCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = lowerSourceKeyIndex } + val upperCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = upperSourceKeyIndex } + val lowerForm = formByOldIndex[linearIndexOf(lowerCoordinate)] ?: continue + val upperForm = formByOldIndex[linearIndexOf(upperCoordinate)] ?: continue + val insertedForm = + if (lowerSourceKeyIndex == upperSourceKeyIndex) { + lowerForm + } else { + interpolator.interpolate(lowerForm, upperForm, blendFraction) + } + val insertedCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = insertPosition } + newCells.add(KeyformCell(insertedCoordinate, insertedForm)) + } + return KeyformGrid(newAxes.toList(), newCells) +} + +/** + * The position key [keyIndex] would actually land on if moved toward [newValue] on [parameterId]'s axis. + * + * Almost always [newValue] itself. It is nudged only to keep every span RESOLVABLE: two keys closer than + * EPS_SPAN make the evaluator read fraction 0 across the gap, so the nearer one becomes unreachable and + * the blend degenerates into a step. That is a correctness floor, not a spacing preference - keys may sit + * as close as the evaluator can still tell apart, and no closer. + * + * Returns null when the axis is absent, the grid is sparse, or the index is out of range. + * + * @param ParameterId parameterId The axis the key sits on. + * @param Int keyIndex The key being moved. + * @param Float newValue The requested destination. + * @return Float? The destination it will take, or null when the move cannot apply. + */ +fun KeyformGrid<*>.keyDestinationFor(parameterId: ParameterId, keyIndex: Int, newValue: Float): Float? { + val axisIndex = axisIndexOf(parameterId) + if (axisIndex < 0 || !isDense) { + return null + } + val keys = axes[axisIndex].keys + if (keyIndex < 0 || keyIndex >= keys.size) { + return null + } + var nearestIndex = -1 + var nearestDistance = Float.MAX_VALUE + for (index in keys.indices) { + if (index == keyIndex) { + continue + } + val distance = abs(keys[index] - newValue) + if (distance < nearestDistance) { + nearestDistance = distance + nearestIndex = index + } + } + if (nearestDistance >= EPS_SPAN || nearestIndex < 0) { + return newValue + } + val nearestOther = keys[nearestIndex] + // Pushed to the side it was already approaching from, so the nudge never reverses the drag. + // + // A dead-on collision has no approach side, and resolving it by direction of travel would push a key + // dropped onto the LAST key out past it - and therefore out of the parameter's range, where the + // evaluator brackets nothing and every entity keyed on it disappears. So an exact tie nudges INWARD, + // toward the middle of the axis, which is always somewhere the axis already reaches. + val approachingFromBelow = + if (newValue == nearestOther) { + nearestOther >= axisMidpointExcluding(keys, keyIndex) + } else { + newValue < nearestOther + } + val nudged = if (approachingFromBelow) nearestOther - EPS_SPAN else nearestOther + EPS_SPAN + // The nudge is measured against the NEAREST key only, so on a crowded axis it can land right on top of + // the next one along - and two axis keys closer than EPS_SPAN is precisely the unresolvable span this + // function exists to prevent (bindBracket gives such a span fraction 0, making the upper key + // unreachable). Rather than hunt for a gap that may not exist, refuse: a move that cannot be made + // resolvable is better left undone than made silently wrong. + return if (collidesBeyond(keys, keyIndex, nearestIndex, nudged)) null else nudged +} + +/** + * Whether [value] lands unresolvably close to a key OTHER than [keyIndex] and [nudgedOffIndex]. + * + * Both exclusions are necessary and neither is slack. A key cannot collide with itself, and the key the + * nudge was measured off is EPS_SPAN away BY CONSTRUCTION - but `nearest ± EPS_SPAN` is computed in float32 + * and rounds, so testing it would reject the very destination just derived. Every other key is a real + * collision: the nudge only ever consults the NEAREST key, so on a crowded axis it can land right on top of + * the next one along, and two keys closer than EPS_SPAN is the unresolvable span this all exists to + * prevent (bindBracket gives such a span fraction 0, making the upper key unreachable). + * + * @param FloatArray keys The axis's keys. + * @param Int keyIndex The key being moved. + * @param Int nudgedOffIndex The key the destination was pushed away from. + * @param Float value The candidate destination. + * @return Boolean True when the destination would be unresolvably close to some third key. + */ +private fun collidesBeyond(keys: FloatArray, keyIndex: Int, nudgedOffIndex: Int, value: Float): Boolean { + for (index in keys.indices) { + if (index != keyIndex && index != nudgedOffIndex && abs(keys[index] - value) < EPS_SPAN) { + return true + } + } + return false +} + +/** + * The midpoint of every key except [keyIndex] - which half of the axis a colliding destination is in. + * + * @param FloatArray keys The axis's keys. + * @param Int keyIndex The key being moved, excluded from the span. + * @return Float The midpoint, or the moved key's own value when it is the only one. + */ +private fun axisMidpointExcluding(keys: FloatArray, keyIndex: Int): Float { + var lowest = Float.MAX_VALUE + var highest = -Float.MAX_VALUE + for (index in keys.indices) { + if (index == keyIndex) { + continue + } + lowest = minOf(lowest, keys[index]) + highest = maxOf(highest, keys[index]) + } + return if (lowest > highest) keys[keyIndex] else (lowest + highest) / 2f +} + +/** + * The ordinal a key inserted at [keyValue] would take on [parameterId]'s axis, or -1 when no key is added. + * + * The [keyIndexAfterMove] counterpart, and public for the same reason: an insert renumbers every key at or + * above it, so a caller holding ordinals - the keyform sheet's key selection - has to correct them, and it + * has to do so BEFORE the insert records its step. Counting the keys below the new value is exactly how + * [withKeyInserted] places it, so the two cannot disagree about where it lands. + * + * -1 covers every case that adds nothing: a missing axis, a sparse or empty grid, and a value already + * within the snap tolerance of an existing key. An insert refused for a reason only [withKeyInserted] + * knows (a span below EPS_SPAN, or an out-of-span key under [OutOfSpanKeyPolicy.Reject]) still reports the + * position it would have taken, so a caller that acts on this must confirm against the edit's own outcome. + * + * @param ParameterId parameterId The axis to insert into. + * @param Float keyValue The parameter value of the new key. + * @return Int The new key's ordinal, or -1 when the insert would add none. + */ +fun KeyformGrid<*>.keyIndexAfterInsert(parameterId: ParameterId, keyValue: Float): Int { + val axisIndex = axisIndexOf(parameterId) + if (axisIndex < 0 || !isDense) { + return -1 + } + val keys = axes[axisIndex].keys + // Through keyIndexAt, the one definition of the evaluator's on-a-key snap tolerance - the same gate + // withKeyInserted applies before it decides it has anything to add. + if (keys.isEmpty() || keyIndexAt(parameterId, keyValue) >= 0) { + return -1 + } + return keys.count { existing -> existing < keyValue } +} + +/** + * The ordinal key [keyIndex] would hold after being moved toward [newValue] - its position in the re-sorted + * axis. + * + * A move can REORDER the axis, so the key a caller is holding changes ordinal underneath it. Anything + * tracking that key (the sheet's selection) has to be told where it went. + * + * @param ParameterId parameterId The axis the key sits on. + * @param Int keyIndex The key being moved. + * @param Float newValue The requested destination. + * @return Int The ordinal after the move, or [keyIndex] when the move cannot apply. + */ +fun KeyformGrid<*>.keyIndexAfterMove(parameterId: ParameterId, keyIndex: Int, newValue: Float): Int { + val axisIndex = axisIndexOf(parameterId) + val destination = keyDestinationFor(parameterId, keyIndex, newValue) ?: return keyIndex + val keys = axes[axisIndex].keys + // Its ordinal is simply how many keys end up below it. Ties break toward the mover's old side, which + // is what sortedBy's stability gives the rebuild in withKeyMoved. + var below = 0 + for (index in keys.indices) { + if (index == keyIndex) { + continue + } + if (keys[index] < destination || (keys[index] == destination && index < keyIndex)) { + below++ + } + } + return below +} + +/** + * This grid with key [keyIndex] on [parameterId]'s axis moved to [newValue], carrying its cells with it. + * + * A move changes only WHERE a key sits, never what it holds - which is what makes it a distinct operation + * rather than a remove plus an insert. Re-inserting would rebuild the moved slice by interpolating its + * neighbours, silently discarding whatever the rigger authored there. + * + * A key MAY cross its neighbours, and doing so re-sorts the axis and PERMUTES the cells to match. That + * permutation is the whole cost of allowing it: a cell's coordinate on an axis is a key ORDINAL, and the + * evaluator requires an axis to be ascending - `bindBracket` reads keys[0] / keys[last] as the span ends, + * scans monotonically, and assumes keys[hi] - keys[hi - 1] is positive, while `gridCorners` assumes ordinal + * i + 1 is the next key by VALUE. Re-sorting the keys without moving the cells to match would satisfy + * `isDense` and corrupt silently: forms would apply at the wrong positions and poses inside the real span + * would resolve to nothing, which for a geometry grid hides its entity outright. + * + * The destination is nudged only to keep spans resolvable - see [keyDestinationFor]. + * + * Returns the receiver unchanged when the axis is absent, the index is out of range, the grid is sparse, or + * the destination is where the key already sits. + * + * @param ParameterId parameterId The axis the key sits on. + * @param Int keyIndex The key to move. + * @param Float newValue The requested new position. + * @return KeyformGrid The grid with the key moved, or the receiver when nothing moved. + */ +fun KeyformGrid.withKeyMoved(parameterId: ParameterId, keyIndex: Int, newValue: Float): KeyformGrid { + val axisIndex = axisIndexOf(parameterId) + val destination = keyDestinationFor(parameterId, keyIndex, newValue) ?: return this + val keys = axes[axisIndex].keys + if (destination == keys[keyIndex]) { + return this + } + + // Re-sort by the value each ordinal ends up holding. sortedBy is stable, so equal values keep their + // old relative order - which cannot happen anyway after the EPS_SPAN nudge, but keeps the mapping total. + val movedValues = FloatArray(keys.size) { index -> if (index == keyIndex) destination else keys[index] } + val oldOrdinalsInNewOrder = keys.indices.sortedBy { index -> movedValues[index] } + val newKeys = FloatArray(keys.size) { newIndex -> movedValues[oldOrdinalsInNewOrder[newIndex]] } + + // The inverse mapping is what the cells travel through: a cell sitting at old ordinal o now sits at the + // position o ended up in. + val newOrdinalByOld = IntArray(keys.size) + for (newIndex in oldOrdinalsInNewOrder.indices) { + newOrdinalByOld[oldOrdinalsInNewOrder[newIndex]] = newIndex + } + + val newAxes = axes.toMutableList() + newAxes[axisIndex] = KeyformAxis(parameterId, newKeys) + val reordered = oldOrdinalsInNewOrder.withIndex().any { (newIndex, oldIndex) -> newIndex != oldIndex } + if (!reordered) { + // Nothing crossed, so every coordinate still addresses the same cell and the cells can be shared. + return KeyformGrid(newAxes.toList(), cells) + } + val movedCells = + cells.map { cell -> + val coordinate = cell.coordinate.copyOf() + coordinate[axisIndex] = newOrdinalByOld[coordinate[axisIndex]] + KeyformCell(coordinate, cell.form) + } + return KeyformGrid(newAxes.toList(), movedCells) +} + +/** + * This grid with key [keyIndex] removed from [parameterId]'s axis, or the axis collapsed entirely when + * too few keys would remain. + * + * Dropping below [collapseBelowKeyCount] keys collapses the axis (via [withAxisCollapsed]) rather than + * leaving a stub: a single-key axis resolves only within EPS_KEY of its key and hides the entity + * everywhere else, so "remove the second-to-last key" would otherwise make the entity vanish. Collapsing + * the last remaining axis returns null - the entity becomes unkeyed. + * + * @param ParameterId parameterId The axis to remove a key from. + * @param Int keyIndex The key's index on that axis. + * @param Int collapseBelowKeyCount The key count below which the axis collapses instead; two by default, + * which the exporter can lower when it deliberately wants a degenerate axis. + * @return KeyformGrid The reduced grid, the receiver when the removal was refused, or null when the entity + * is left with no axes at all. + */ +fun KeyformGrid.withKeyRemoved( + parameterId: ParameterId, + keyIndex: Int, + collapseBelowKeyCount: Int = 2, +): KeyformGrid? { + val axisIndex = axisIndexOf(parameterId) + if (axisIndex < 0 || !isDense) { + return this + } + val oldKeys = axes[axisIndex].keys + if (keyIndex < 0 || keyIndex >= oldKeys.size) { + return this + } + if (oldKeys.size - 1 < collapseBelowKeyCount) { + // Keep whichever key survives the removal, so the collapsed slice is the one the rigger kept. + val survivingKeyIndex = if (keyIndex == 0) minOf(1, oldKeys.size - 1) else keyIndex - 1 + return withAxisCollapsed(parameterId, oldKeys[survivingKeyIndex]) + } + val newKeys = FloatArray(oldKeys.size - 1) + oldKeys.copyInto(newKeys, destinationOffset = 0, startIndex = 0, endIndex = keyIndex) + oldKeys.copyInto(newKeys, destinationOffset = keyIndex, startIndex = keyIndex + 1, endIndex = oldKeys.size) + val newAxes = axes.toMutableList() + newAxes[axisIndex] = KeyformAxis(parameterId, newKeys) + val newCells = + cells.mapNotNull { cell -> + val keyOnAxis = cell.coordinate[axisIndex] + when { + keyOnAxis == keyIndex -> null + keyOnAxis > keyIndex -> KeyformCell(cell.coordinate.copyOf().also { it[axisIndex] = keyOnAxis - 1 }, cell.form) + else -> cell + } + } + return KeyformGrid(newAxes.toList(), newCells) +} + +/** + * This grid with the cell at [coordinate] holding [form], appending the cell when it is absent. + * + * The write half of a capture: the shape work is already done by the time this runs, so it never changes + * the axes. A coordinate whose length does not match the axis count is refused. + * + * @param IntArray coordinate The target cell's key index per axis. + * @param TForm form The form to store there. + * @return KeyformGrid The grid with the cell written, or the receiver when the coordinate does not fit. + */ +fun KeyformGrid.withCellWritten(coordinate: IntArray, form: TForm): KeyformGrid { + if (coordinate.size != axes.size) { + return this + } + val targetIndex = linearIndexOf(coordinate) + var replaced = false + val newCells = + cells.map { cell -> + if (!replaced && linearIndexOf(cell.coordinate) == targetIndex) { + replaced = true + KeyformCell(coordinate.copyOf(), form) + } else { + cell + } + } + return if (replaced) { + KeyformGrid(axes, newCells) + } else { + KeyformGrid(axes, newCells + KeyformCell(coordinate.copyOf(), form)) + } +} + +/** + * This grid with [form] captured at [pose] - the keyform-insertion operation behind Blender-style `I`. + * + * Inserts a key on every axis whose pose value does not already land on one (each insert filling its whole + * slice by interpolation, so the entity's look is unchanged everywhere else), then writes [form] into the + * single cell the pose now sits exactly on. Because the capture always lands on a key, the write is a + * plain assignment - there is never a blend to invert. + * + * Returns the receiver when the grid is sparse, or when an axis's pose value cannot be turned into a key + * (out of span under a rejecting policy, or too close to an existing key to be distinguishable). + * + * @param Function pose The current value per parameter id. + * @param TForm form The form to capture. + * @param FormInterpolator interpolator Fills each newly inserted slice. + * @return KeyformGrid The grid with the capture written. + */ +fun KeyformGrid.withFormCaptured( + pose: (ParameterId) -> Float, + form: TForm, + interpolator: FormInterpolator, +): KeyformGrid { + if (!isDense || axes.isEmpty()) { + return this + } + var working = this + for (axis in axes) { + val poseValue = pose(axis.parameterId) + // keyIndexAt is the one definition of the on-a-key snap; inlining the epsilon here once let the + // capture and the sheet UI disagree about whether the pose sits on a key. + if (working.keyIndexAt(axis.parameterId, poseValue) >= 0) { + continue + } + working = working.withKeyInserted(axis.parameterId, poseValue, interpolator) + } + val coordinate = IntArray(working.axes.size) + for (axisIndex in working.axes.indices) { + val axis = working.axes[axisIndex] + val poseValue = pose(axis.parameterId) + val keyIndex = working.keyIndexAt(axis.parameterId, poseValue) + if (keyIndex < 0) { + // An axis refused its key (a degenerate span, say); writing a neighbouring cell would silently + // retarget the capture, so leave the grid untouched instead. + return this + } + coordinate[axisIndex] = keyIndex + } + return working.withCellWritten(coordinate, form) +} + +/** + * This grid refined onto a wider key set, for lowering a rig to a format that shares key positions. + * + * SPAN-CLAMPED on purpose. For an axis this grid already has, only union keys strictly inside its own + * first..last span are inserted; the span itself is never widened. Widening it would resurrect a drawable + * that its author deliberately keyed to vanish outside a narrow range - the toggle-part pattern - which is + * a rig-altering change, not a rounding one. For a parameter this grid does NOT key, a new axis is + * appended spanning the union plus the parameter's own min and max, with the whole grid replicated across + * it: the channel is constant along that axis, so the widening carries no motion and cannot mislead. + * + * Refining is the exact inverse of compaction: both go through [interpolator], so a key dropped because it + * was bit-equal to its interpolated neighbours is restored bit-equal here. + * + * @param Map unionKeysByParameter The key positions to refine onto, per parameter. + * @param Map parameterRanges Each parameter's min..max, used only when appending an axis this grid lacks. + * @param FormInterpolator interpolator Blends each inserted slice. + * @return KeyformGrid The refined grid, or the receiver when it is sparse. + */ +fun KeyformGrid.refinedToUnion( + unionKeysByParameter: Map, + parameterRanges: Map>, + interpolator: FormInterpolator, +): KeyformGrid { + if (!isDense) { + return this + } + var working = this + for ((parameterId, unionKeys) in unionKeysByParameter) { + val axisIndex = working.axisIndexOf(parameterId) + if (axisIndex >= 0) { + val ownKeys = working.axes[axisIndex].keys + if (ownKeys.isEmpty()) { + continue + } + val spanStart = ownKeys.first() + val spanEnd = ownKeys.last() + for (unionKey in unionKeys.sortedArray()) { + if (unionKey > spanStart && unionKey < spanEnd) { + working = working.withKeyInserted(parameterId, unionKey, interpolator, OutOfSpanKeyPolicy.Reject) + } + } + } else { + val range = parameterRanges[parameterId] ?: continue + val appendedKeys = distinctSortedKeys(unionKeys + range.start + range.endInclusive) + if (appendedKeys.size < 2) { + continue + } + val newAxis = KeyformAxis(parameterId, appendedKeys) + val replicated = + buildList { + for (keyIndex in appendedKeys.indices) { + for (cell in working.cells) { + add(KeyformCell(cell.coordinate + keyIndex, cell.form)) + } + } + } + working = KeyformGrid(working.axes + newAxis, replicated) + } + } + return working +} + +/** + * The given key candidates sorted ascending with near-duplicates (within EPS_KEY) merged. + * + * Merging on the evaluator's own snap tolerance rather than exact equality: two keys closer than EPS_KEY + * are indistinguishable to bindBracket, so keeping both would build an axis with a span the evaluator + * treats as a step. + * + * @param FloatArray candidates The raw key values, in any order. + * @return FloatArray The sorted, de-duplicated keys. + */ +private fun distinctSortedKeys(candidates: FloatArray): FloatArray { + val sorted = candidates.sortedArray() + val kept = ArrayList(sorted.size) + for (candidate in sorted) { + if (kept.isEmpty() || abs(kept.last() - candidate) >= EPS_KEY) { + kept.add(candidate) + } + } + return kept.toFloatArray() +} + +/** + * Whether inserting [keyValue] at [insertPosition] leaves every span on the axis wide enough to evaluate. + * + * A span below EPS_SPAN yields blend fraction 0 in bindBracket, so the lower key holds for the whole span + * and the upper key becomes unreachable - a grid the evaluator cannot resolve as authored. + * + * @param FloatArray existingKeys The axis's current keys, ascending. + * @param Float keyValue The candidate key value. + * @param Int insertPosition The index the key would take in the new array. + * @return Boolean True when both neighbouring spans stay at or above EPS_SPAN. + */ +private fun spansStayResolvable(existingKeys: FloatArray, keyValue: Float, insertPosition: Int): Boolean { + if (insertPosition > 0 && keyValue - existingKeys[insertPosition - 1] < EPS_SPAN) { + return false + } + if (insertPosition < existingKeys.size && existingKeys[insertPosition] - keyValue < EPS_SPAN) { + return false + } + return true +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridCompaction.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridCompaction.kt new file mode 100644 index 0000000..4753968 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridCompaction.kt @@ -0,0 +1,320 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.eval.EPS_SPAN +import org.umamo.runtime.model.ChannelValueKind +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId + +/* + * Exact-only keyform-grid compaction: drop every axis a track does not actually vary along, and every + * interior key that is bit-equal to the blend of its neighbours. + * + * This is what turns an imported Cubism rig into a sparse Umamo one. Cubism keys every channel on every + * cell of one bundled grid, so after the per-channel fan-out a typical drawable's opacity track is the + * same value repeated across the whole grid; compacting it to a constant retires the track entirely and + * the owner's static field takes over. + * + * EXACT, never an epsilon. A key that is merely close to its interpolated neighbours is a value the + * rigger chose, and silently replacing it would alter their rig - which the fidelity contract forbids. + * The greedy drop test compares against the same FormInterpolator expression refinedToUnion re-inserts + * with, and the drop set is then VERIFIED by running refinedToUnion itself and re-keeping any key whose + * restored slice is not bit-identical (two adjacent drops restore through a different rounding sequence + * than the one that justified them): compaction and refinement are mutual inverses by construction. + * + * OUT-OF-SPAN SAFETY. A pose outside any axis's key span makes the whole track fall back to its owner's + * static, so an axis whose keys do not bracket the parameter's range acts as a GATE - dropping it (or + * lifting the track to a constant that overwrites the static) would change what those poses render. The + * caller supplies the axis-spans-range predicate; a non-spanning axis is never dropped and a track whose + * last axis is non-spanning is never lifted. + */ + +/** + * The outcome of compacting one track. + * + * @param TForm The cell payload type. + */ +sealed interface CompactionResult { + /** + * The track never varies - it holds [form] at every pose, so it needs no grid at all and the value + * belongs in its owner's static field. + */ + class Constant(val form: TForm) : CompactionResult + + /** The track still varies; [grid] is it, with the redundant axes and keys removed. */ + class Reduced(val grid: KeyformGrid) : CompactionResult +} + +/** + * This grid with every redundant axis and interior key removed, or the constant it collapses to. + * + * An axis is redundant when every cell is bit-equal along it - the track simply does not respond to that + * parameter. An interior key is redundant when its whole slice is bit-equal to the blend of the slices on + * either side, so the evaluator would produce it anyway. Endpoint keys are never dropped: the blend test + * needs both neighbours, and dropping an endpoint would narrow the axis's span and change when the track + * falls out of range. + * + * A [valueKind] of FLAG restricts compaction to whole axes. A flag snaps to the floor cell rather than + * blending, so "equal to the blend of its neighbours" is not the right test for an interior flag key, and + * flag tracks are small enough that the conservatism costs nothing. + * + * A sparse grid is returned unchanged as [CompactionResult.Reduced] - the missing cells cannot be tested, + * and inventing them would be a repair this layer has no business making. + * + * @param FormInterpolator interpolator The blend and exact-equality tests; must be the same one + * [refinedToUnion] will later re-insert with. + * @param ChannelValueKind? valueKind The track's value kind when it is a channel track, or null for a + * geometry grid (which blends like a scalar). + * @param Function axisSpansRange Whether an axis's keys bracket its parameter's whole range. A + * non-spanning axis gates the track's out-of-span fallback to the owner's static, so it is never + * dropped and never lifted; channel compaction MUST pass the model-derived predicate (the permissive + * default exists for shape-only tests and single-grid callers with no parameter table in reach). + * @return CompactionResult The constant the track collapses to, or the reduced grid. + */ +fun KeyformGrid.compacted( + interpolator: FormInterpolator, + valueKind: ChannelValueKind? = null, + axisSpansRange: (KeyformAxis) -> Boolean = { true }, +): CompactionResult { + if (!isDense) { + return CompactionResult.Reduced(this) + } + val allowsInteriorKeyDrop = valueKind != ChannelValueKind.FLAG + var working = this + // Axes first: dropping one shrinks every later pass, and it can expose a key that is now interpolable. + // The last axis is left for the constant check below, which has the form to hand back to the owner. + var axisIndex = 0 + while (axisIndex < working.axes.size) { + if (working.axes.size > 1 && axisSpansRange(working.axes[axisIndex]) && working.isConstantAlong(axisIndex, interpolator)) { + working = working.withAxisDropped(axisIndex) + } else { + axisIndex++ + } + } + // A single remaining axis that the track does not vary along leaves one constant form for the owner - + // but only when the axis spans its range, else out-of-span poses must keep falling to the static. + if (working.axes.size == 1 && axisSpansRange(working.axes[0]) && working.isConstantAlong(0, interpolator)) { + val soleForm = working.cells.firstOrNull()?.form ?: return CompactionResult.Reduced(working) + return CompactionResult.Constant(soleForm) + } + if (working.axes.isEmpty()) { + val soleForm = working.cells.firstOrNull()?.form ?: return CompactionResult.Reduced(working) + return CompactionResult.Constant(soleForm) + } + if (!allowsInteriorKeyDrop) { + return CompactionResult.Reduced(working) + } + return CompactionResult.Reduced(working.withVerifiedInteriorKeyDrops(interpolator)) +} + +/** + * This grid with every interior key dropped whose restoration by [refinedToUnion] is bit-exact. + * + * The greedy pass validates each drop against the CURRENT neighbours, but a neighbour used to justify a + * drop can itself drop later, and refinedToUnion then re-blends the first key from the surviving + * endpoints - a different IEEE-754 rounding sequence that matches only algebraically. So the greedy + * result is verified by running the ACTUAL inverse and re-keeping every key involved in a slice that did + * not restore bit-identically, until the round trip verifies. + * + * Terminates: a mismatched cell always involves at least one dropped key (a cell whose keys all survived + * is carried verbatim), so every iteration moves at least one key from dropped to kept. + * + * @param FormInterpolator interpolator The blend and exact-equality tests. + * @return KeyformGrid The reduced grid whose refinement restores this grid bit-for-bit. + */ +private fun KeyformGrid.withVerifiedInteriorKeyDrops(interpolator: FormInterpolator): KeyformGrid { + val mustKeep = HashMap>() + while (true) { + val reduced = withGreedyInteriorKeyDrops(interpolator, mustKeep) + if (reduced === this) { + return this + } + val unionKeysByParameter = axes.associate { axis -> axis.parameterId to axis.keys } + val restored = reduced.refinedToUnion(unionKeysByParameter, emptyMap(), interpolator) + val offending = mismatchedKeyValues(restored, interpolator) + if (offending.isEmpty()) { + return reduced + } + for ((parameterId, keyValues) in offending) { + mustKeep.getOrPut(parameterId) { HashSet() }.addAll(keyValues) + } + } +} + +/** + * The original greedy interior-key drop pass, skipping any key value listed in [mustKeep]. + * + * @param FormInterpolator interpolator The blend and exact-equality tests. + * @param Map mustKeep Key values (per parameter) that a prior verification round proved non-restorable. + * @return KeyformGrid The reduced grid, or this same instance when nothing dropped. + */ +private fun KeyformGrid.withGreedyInteriorKeyDrops( + interpolator: FormInterpolator, + mustKeep: Map>, +): KeyformGrid { + var working = this + for (targetAxisIndex in working.axes.indices) { + var keyIndex = 1 + while (keyIndex < working.axes[targetAxisIndex].keys.size - 1) { + val axis = working.axes[targetAxisIndex] + val keptExplicitly = mustKeep[axis.parameterId]?.contains(axis.keys[keyIndex]) == true + if (!keptExplicitly && working.isKeyInterpolable(targetAxisIndex, keyIndex, interpolator)) { + working = working.withKeyIndexDropped(targetAxisIndex, keyIndex) + } else { + keyIndex++ + } + } + } + return working +} + +/** + * The key values (per parameter) touched by any cell of this grid whose counterpart in [restored] is not + * bit-identical. + * + * Conservative on purpose: every coordinate of a mismatched cell is reported, including keys that were + * never dropped - re-keeping a kept key is a no-op, and the dropped key among them is the one that makes + * the next verification round converge. + * + * @param KeyformGrid restored This grid's shape rebuilt from the reduced grid by [refinedToUnion]. + * @param FormInterpolator interpolator Supplies the exact-equality test. + * @return Map The offending key values per parameter; empty when the round trip is bit-exact. + */ +private fun KeyformGrid.mismatchedKeyValues( + restored: KeyformGrid, + interpolator: FormInterpolator, +): Map> { + val offending = HashMap>() + val restoredByIndex = restored.cells.associate { cell -> restored.linearIndexOf(cell.coordinate) to cell.form } + for (cell in cells) { + val counterpart = restoredByIndex[linearIndexOf(cell.coordinate)] + if (counterpart != null && interpolator.isExactlyEqual(counterpart, cell.form)) { + continue + } + for (axisIndex in axes.indices) { + val axis = axes[axisIndex] + offending.getOrPut(axis.parameterId) { HashSet() }.add(axis.keys[cell.coordinate[axisIndex]]) + } + } + return offending +} + +/** + * Whether every cell of this grid is bit-equal to its counterpart at key index 0 along [axisIndex]. + * + * @param Int axisIndex The axis to test. + * @param FormInterpolator interpolator Supplies the exact-equality test. + * @return Boolean True when the track does not vary along that axis. + */ +private fun KeyformGrid.isConstantAlong(axisIndex: Int, interpolator: FormInterpolator): Boolean { + val keyCount = axes[axisIndex].keys.size + if (keyCount <= 1) { + return true + } + val formByIndex = cells.associate { cell -> linearIndexOf(cell.coordinate) to cell.form } + for (cell in cells) { + if (cell.coordinate[axisIndex] == 0) { + continue + } + val baseCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = 0 } + val baseForm = formByIndex[linearIndexOf(baseCoordinate)] ?: return false + if (!interpolator.isExactlyEqual(baseForm, cell.form)) { + return false + } + } + return true +} + +/** + * Whether the whole slice at [keyIndex] on [axisIndex] is bit-equal to the blend of its neighbours - so + * the evaluator would reproduce it exactly without the key being stored. + * + * @param Int axisIndex The axis the key sits on. + * @param Int keyIndex The interior key's index. + * @param FormInterpolator interpolator The blend and exact-equality tests. + * @return Boolean True when the key carries no information. + */ +private fun KeyformGrid.isKeyInterpolable( + axisIndex: Int, + keyIndex: Int, + interpolator: FormInterpolator, +): Boolean { + val keys = axes[axisIndex].keys + val span = keys[keyIndex + 1] - keys[keyIndex - 1] + if (span < EPS_SPAN) { + return false + } + val fraction = (keys[keyIndex] - keys[keyIndex - 1]) / span + val formByIndex = cells.associate { cell -> linearIndexOf(cell.coordinate) to cell.form } + for (cell in cells) { + if (cell.coordinate[axisIndex] != keyIndex) { + continue + } + val lowerCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = keyIndex - 1 } + val upperCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = keyIndex + 1 } + val lowerForm = formByIndex[linearIndexOf(lowerCoordinate)] ?: return false + val upperForm = formByIndex[linearIndexOf(upperCoordinate)] ?: return false + if (!interpolator.isExactlyEqual(interpolator.interpolate(lowerForm, upperForm, fraction), cell.form)) { + return false + } + } + return true +} + +/** + * This grid with [axisIndex] removed, keeping the key-index-0 slice. + * + * Only ever called on an axis this track is constant along, so which slice survives is immaterial - unlike + * [withAxisCollapsed], which must pick a slice by parameter value because it is discarding real motion. + * + * @param Int axisIndex The axis to drop. + * @return KeyformGrid The grid one dimension smaller. + */ +private fun KeyformGrid.withAxisDropped(axisIndex: Int): KeyformGrid { + val newAxes = axes.filterIndexed { index, _ -> index != axisIndex } + val newCells = + cells + .filter { cell -> cell.coordinate[axisIndex] == 0 } + .map { cell -> + val reduced = IntArray(cell.coordinate.size - 1) + var writeIndex = 0 + for (readIndex in cell.coordinate.indices) { + if (readIndex != axisIndex) { + reduced[writeIndex] = cell.coordinate[readIndex] + writeIndex++ + } + } + KeyformCell(reduced, cell.form) + } + return KeyformGrid(newAxes, newCells) +} + +/** + * This grid with key [keyIndex] dropped from [axisIndex], re-projecting the coordinates above it. + * + * The index-addressed counterpart of [withKeyRemoved], without that function's collapse guard: compaction + * only ever drops interior keys, so at least the two endpoints always remain. + * + * @param Int axisIndex The axis to drop a key from. + * @param Int keyIndex The key index to drop. + * @return KeyformGrid The grid with the key removed. + */ +private fun KeyformGrid.withKeyIndexDropped(axisIndex: Int, keyIndex: Int): KeyformGrid { + val oldKeys = axes[axisIndex].keys + val newKeys = FloatArray(oldKeys.size - 1) + oldKeys.copyInto(newKeys, destinationOffset = 0, startIndex = 0, endIndex = keyIndex) + oldKeys.copyInto(newKeys, destinationOffset = keyIndex, startIndex = keyIndex + 1, endIndex = oldKeys.size) + val newAxes = axes.toMutableList() + newAxes[axisIndex] = KeyformAxis(axes[axisIndex].parameterId, newKeys) + val newCells = + cells.mapNotNull { cell -> + val keyOnAxis = cell.coordinate[axisIndex] + when { + keyOnAxis == keyIndex -> null + keyOnAxis > keyIndex -> KeyformCell(cell.coordinate.copyOf().also { it[axisIndex] = keyOnAxis - 1 }, cell.form) + else -> cell + } + } + return KeyformGrid(newAxes.toList(), newCells) +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridShape.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridShape.kt new file mode 100644 index 0000000..1bc4a04 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/keyform/KeyformGridShape.kt @@ -0,0 +1,278 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.eval.EPS_KEY +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import kotlin.math.abs + +/* + * Pure shape queries and shape edits over a KeyformGrid: strides, the linear cell index, density + * checks, and axis removal. Nothing here interpolates a form and nothing here evaluates a pose - the + * multilinear blend stays in runtime.eval, which this package must never duplicate. + * + * This lives in :runtime rather than :edit because the CMO3 / MOC3 importers need it and :runtime + * cannot depend on :edit. + */ + +/** + * The grid's linear cell extent: the product of every axis's key count. + * + * Zero for a grid carrying an empty axis, which is a malformed grid rather than a rest cell; the + * delta-texture sizing in :render floors its own copy at 1 because a texture cannot be zero-wide. + * + * @return Int The number of cells a dense grid of this shape holds. + */ +val KeyformGrid<*>.cellCount: Int + get() = axes.fold(1) { count, axis -> count * axis.keys.size } + +/** + * Whether this grid holds exactly one cell per coordinate in its shape. + * + * A CMO3 grid can arrive SPARSE - Cmo3Import drops cells whose form guid does not resolve - and a + * sparse grid blends toward zero rather than erroring. Compaction and refine both refuse a sparse + * grid rather than inventing the missing cells, so they ask this first. + * + * @return Boolean True when the grid is dense and every cell index is in range and distinct. + */ +val KeyformGrid<*>.isDense: Boolean + get() { + val expectedCellCount = cellCount + if (expectedCellCount <= 0 || cells.size != expectedCellCount) { + return false + } + val seenIndices = HashSet(cells.size) + for (cell in cells) { + if (cell.coordinate.size != axes.size) { + return false + } + val linearIndex = linearIndexOf(cell.coordinate) + if (linearIndex < 0 || linearIndex >= expectedCellCount || !seenIndices.add(linearIndex)) { + return false + } + } + return true + } + +/** + * The index of the axis keying on [parameterId], or -1 when this grid has no such axis. + * + * @param ParameterId parameterId The parameter to look for. + * @return Int The axis index, or -1 when absent. + */ +fun KeyformGrid<*>.axisIndexOf(parameterId: ParameterId): Int = axes.indexOfFirst { axis -> axis.parameterId == parameterId } + +/** + * This grid with the axis for [parameterId] removed, collapsing that dimension to the key nearest + * [keepKeyValue]. Returns this same instance when the grid has no such axis (so a caller can skip + * untouched entities by identity), or null when removing the axis leaves no axes at all (the entity + * becomes unkeyed). The surviving cells are those whose coordinate on the dropped axis is the kept key + * index, each re-projected to the N-1 coordinate; the form payloads are carried through untouched. + * + * The kept slice is the NEAREST key, not an interpolated one, so collapsing an axis whose kept value + * falls between keys discards the interpolated pose rather than baking it. + * + * @param ParameterId parameterId The axis parameter to remove. + * @param Float keepKeyValue The parameter value whose nearest key slice survives (the deleted default). + * @return KeyformGrid The collapsed grid, this if the axis was absent, or null if no axes remain. + */ +fun KeyformGrid.withAxisCollapsed(parameterId: ParameterId, keepKeyValue: Float): KeyformGrid? { + val axisIndex = axisIndexOf(parameterId) + if (axisIndex < 0) { + return this + } + val newAxes = axes.filterIndexed { index, _ -> index != axisIndex } + if (newAxes.isEmpty()) { + return null + } + val keepIndex = nearestKeyIndex(axes[axisIndex].keys, keepKeyValue) + val newCells = + cells + .filter { cell -> cell.coordinate[axisIndex] == keepIndex } + .map { cell -> KeyformCell(cell.coordinate.withElementRemoved(axisIndex), cell.form) } + return KeyformGrid(newAxes, newCells) +} + +/** + * This grid with the axis for [from] retargeted onto [to]: same key values and cells, new parameter id. + * Returns this same instance when the grid has no [from] axis. When [to] is already an axis, that + * destination axis is collapsed to the key nearest [destinationKeepValue] first (its motion is + * discarded) so the grid never carries two axes on the same parameter; the surviving [from] axis is + * then renamed to [to]. Key values are kept absolute (not range-remapped) so authored positions stay + * intact when the destination's min/max differ. + * + * @param ParameterId from The axis parameter to retarget away from. + * @param ParameterId to The parameter the axis should key on after the move. + * @param Float destinationKeepValue Kept-slice value when [to] already occupies an axis (its default). + * @return KeyformGrid The retargeted grid, or this if [from] was absent. + */ +fun KeyformGrid.withAxisRetargeted( + from: ParameterId, + to: ParameterId, + destinationKeepValue: Float, +): KeyformGrid { + val fromIndex = axisIndexOf(from) + if (fromIndex < 0) { + return this + } + if (from == to) { + return this + } + val toIndex = axisIndexOf(to) + if (toIndex >= 0) { + // Both axes present: drop the destination's motion, then rename the source onto it. + val withoutDestination = withAxisCollapsed(to, destinationKeepValue) + // [from] is still present (both were axes), so the collapse cannot empty the grid. + return withoutDestination!!.withAxisRetargeted(from, to, destinationKeepValue) + } + val newAxes = axes.toMutableList() + newAxes[fromIndex] = KeyformAxis(to, axes[fromIndex].keys.copyOf()) + return KeyformGrid(newAxes, cells) +} + +/** + * Every channel track with the axis for [from] retargeted onto [to]. Tracks that never keyed [from] + * are left untouched by identity; returns this same instance when nothing changed. + * + * @param ParameterId from The axis parameter to retarget away from. + * @param ParameterId to The parameter each matching axis should key on after the move. + * @param Float destinationKeepValue Kept-slice value when a track already keys [to]. + * @return ChannelGrids The retargeted tracks, or this if none referenced [from]. + */ +fun ChannelGrids.withAxisRetargeted( + from: ParameterId, + to: ParameterId, + destinationKeepValue: Float, +): ChannelGrids { + var changed = false + val scrubbed = LinkedHashMap>(gridsByChannel.size) + for ((channel, grid) in gridsByChannel) { + val retargeted = grid.withAxisRetargeted(from, to, destinationKeepValue) + if (retargeted !== grid) { + changed = true + } + scrubbed[channel] = retargeted + } + return if (changed) ChannelGrids(scrubbed) else this +} + +/** + * The index of the key on [parameterId]'s axis that [value] sits exactly on, or -1. + * + * "Exactly" means within the evaluator's own EPS_KEY snap tolerance, so this agrees with what is actually + * being rendered: if the pose resolves to a key, this finds it. Authoring ops use it to decide whether an + * insert lands on an existing key (overwrite) or between two (reshape). + * + * @param ParameterId parameterId The axis to look on. + * @param Float value The pose value. + * @return Int The key index, or -1 when the axis is absent or no key is in range. + */ +fun KeyformGrid<*>.keyIndexAt(parameterId: ParameterId, value: Float): Int { + val axisIndex = axisIndexOf(parameterId) + if (axisIndex < 0) { + return -1 + } + return axes[axisIndex].keys.indexOfFirst { key -> abs(key - value) < EPS_KEY } +} + +/** + * The result of collapsing an axis out of a whole owner's channel tracks: the surviving tracks, plus the + * value each fully-collapsed track held on its kept slice. + * + * The lifted value is what the owner's static field must take over so the collapse preserves the neutral + * look - dropping a track without lifting it would snap the channel back to whatever the static happened + * to hold (typically the import-time value), visibly changing the rig. + * + * @property ChannelGrids channelGrids The scrubbed tracks. + * @property Map lifted Per fully-collapsed channel, the value its kept slice held. + */ +class CollapsedChannels( + val channelGrids: ChannelGrids, + val lifted: Map, +) + +/** + * Every one of this owner's channel tracks with the axis for [parameterId] collapsed out, lifting the + * kept slice's value of any track that drops entirely. + * + * The whole-owner counterpart of [withAxisCollapsed], so deleting a parameter scrubs every track in one + * walk rather than needing a hand-written case per channel - a hand-rolled enumeration is exactly the kind + * of list a channel like a glue's intensity grid could quietly be left off. A track left with no axes is + * dropped, and the value of its kept slice is returned + * in [CollapsedChannels.lifted] for the caller to write into the owner's static. A sparse grid missing + * its kept cell lifts nothing (the static keeps its current value). Returns this same grids instance + * (with an empty lifted map) when no track referenced the parameter. + * + * @param ParameterId parameterId The axis parameter to remove from every track. + * @param Float keepKeyValue The parameter value whose nearest key slice survives. + * @return CollapsedChannels The scrubbed tracks plus the lifted slice values. + */ +fun ChannelGrids.withAxisCollapsedLifting(parameterId: ParameterId, keepKeyValue: Float): CollapsedChannels { + var changed = false + val scrubbed = LinkedHashMap>(gridsByChannel.size) + val lifted = LinkedHashMap() + for ((channel, grid) in gridsByChannel) { + val collapsed = grid.withAxisCollapsed(parameterId, keepKeyValue) + if (collapsed === grid) { + scrubbed[channel] = grid + continue + } + changed = true + if (collapsed != null) { + scrubbed[channel] = collapsed + continue + } + val axisIndex = grid.axisIndexOf(parameterId) + val keepIndex = nearestKeyIndex(grid.axes[axisIndex].keys, keepKeyValue) + val keptCell = grid.cells.firstOrNull { cell -> cell.coordinate.getOrNull(axisIndex) == keepIndex } + if (keptCell != null) { + lifted[channel] = keptCell.form + } + } + return if (changed) CollapsedChannels(ChannelGrids(scrubbed), lifted) else CollapsedChannels(this, emptyMap()) +} + +/** + * The index of the key in [keys] nearest [value] (0 for an empty axis, defensively). + * + * @param FloatArray keys The axis's key positions. + * @param Float value The parameter value to match. + * @return Int The nearest key's index. + */ +private fun nearestKeyIndex(keys: FloatArray, value: Float): Int { + if (keys.isEmpty()) { + return 0 + } + var bestIndex = 0 + var bestDistance = abs(keys[0] - value) + for (keyIndex in 1 until keys.size) { + val distance = abs(keys[keyIndex] - value) + if (distance < bestDistance) { + bestDistance = distance + bestIndex = keyIndex + } + } + return bestIndex +} + +/** + * A copy of this coordinate array with the element at [removeIndex] dropped (length shrinks by one). + * + * @param Int removeIndex The element index to drop. + * @return IntArray The shortened coordinate. + */ +private fun IntArray.withElementRemoved(removeIndex: Int): IntArray { + val result = IntArray(size - 1) + var writeIndex = 0 + for (readIndex in indices) { + if (readIndex != removeIndex) { + result[writeIndex] = this[readIndex] + writeIndex++ + } + } + return result +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/ArtSource.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/ArtSource.kt new file mode 100644 index 0000000..b0bef63 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/ArtSource.kt @@ -0,0 +1,245 @@ +package org.umamo.runtime.model + +/* + * Where a document's art came from: the artwork files it was imported from, each with the layer + * inventory it had at that import, and the per-tile link back to one of those layers. + * + * Model state because re-import is a model operation: the reconcile diffs a re-read file against + * the inventory recorded here and rebinds tiles through the refs, so both have to survive undo, a + * document swap, and the native format. Pixels are deliberately absent - a tile's raster belongs to + * the document, and the source file itself is linked, never embedded. + */ + +/** + * One artwork file the document was imported from, and the layers it had when it was last read. + * + * The inventory is the re-import baseline: a later read of the same file is diffed against it to + * classify each layer as matched, added, removed, or renamed. It records identity and layout only, + * never pixels, so a document with hundreds of layers carries it for free. + * + * @property ArtSourceId id The document-local identity every [SourceLayerRef] points at. + * @property String name The file's display name (its file name at import). + * @property String? path The advisory external path the file was read from, or null when + * unknown or platform-volatile; a missing file only stalls re-import, never the rig. + * @property String format The source format's file extension ("psd", "clip", "kra", or a + * flat raster's), recorded so a listing can say what a file is without re-reading it. + * @property List layers The layer inventory as of the last import, in the file's own + * draw order (top-most first); empty for a source whose inventory was never walked. + * @property String? contentHash The whole-file content hash (SHA-256 hex) of the bytes the + * document last read for this file, or null when it never read bytes (a CMO3-origin source). What + * the watcher compares a save against, so an unchanged file is never re-read. + * @property Long? lastModified The file's modification time (epoch milliseconds) when the + * document last read it - or, for a CMO3-origin source, when the official editor did - or null when + * neither is known. The stale-at-open check falls back to it where no hash was recorded, since a + * CMO3 keeps the time but not a hash. + * @property Int offsetX How far right of the document canvas's top-left corner the file's + * own top-left corner sits, in pixels: the translation from the file's own canvas to the document + * canvas, in the viewport's world axes (x right, z up). Every read of the file is placed by it before + * the model sees the art, so the inventory rows, the birth meshes, and the reload's frame comparisons + * all live in the document's coordinates. Zero for a file that set or shares the document's frame (a + * rig's first artwork, a CMO3's own layered image); a later file is placed by the import's Align anchor + * and Offset rows. + * @property Int offsetZ How far UP from the document canvas's top-left corner the file's + * top-left corner sits, in pixels; a file placed lower on the canvas carries a negative value, and a + * layer's canvas y (down) is its own top minus this. See [offsetX]. + */ +data class ArtSource( + val id: ArtSourceId, + val name: String, + val path: String?, + val format: String, + val layers: List = emptyList(), + val contentHash: String? = null, + val lastModified: Long? = null, + val offsetX: Int = 0, + val offsetZ: Int = 0, +) + +/** + * One layer of an [ArtSource]'s inventory: what the reader knew about it at import, without pixels. + * + * Skipped layers (non-raster, empty) are listed too, so a re-import can tell "this layer was there + * and unusable" from "this layer is new". + * + * @property String key The reader's layer key - the same string a [SourceLayerRef] carries. + * @property String name The layer's name at import. + * @property String groupPath The slash-joined enclosing-folder path at import ("" at the root). + * @property Int left The layer's position on the DOCUMENT canvas, top-left origin in source + * pixels: the file's own position plus its source's [ArtSource.offsetX], the frame every drawable's + * positions share. + * @property Int top See [left]; y runs down, so it is the file's own top minus [ArtSource.offsetZ]. + * @property Int width The layer's raster width in source pixels. + * @property Int height The layer's raster height in source pixels. + * @property Boolean visible The layer's own eye toggle at import. + * @property Boolean present Whether the file still had this layer at the last read. False keeps the row + * for a layer the file lost while a tile still binds it, so the Sources space can name and size it and + * the matcher can score candidates against it; such a row leaves the inventory once nothing binds it. + * @property String? contentHash The content hash (SHA-256 hex) of the layer's pixels at the last read, or + * null where the art was never decoded (a CMO3's decomposed tree). A renamed layer whose pixels did + * not change is recognized by it outright. + * @property Boolean empty Whether the layer had no pixel with any alpha at the last read - erased to + * nothing rather than deleted. A tile bound to such a layer keeps its art and reads as needing review, + * since the artist may have meant either; false where the art was never decoded. + * @property Boolean replaced Meaningful only while [present] is false: the row was lost because Replace + * Artwork repointed the file at art that mints other keys, not because the layer left the file - so the + * row can say which. A row lost before the replace keeps false. + * @property Boolean ignored Whether a reload leaves this layer out of the rig: a present layer no tile + * binds that the rigger keeps in the file but not in the model (a sketch, a reference), marked from its + * Sources row or by Delete Art under the import setting, and carried across every refresh until the row + * clears it. Meaningless while a tile binds the key. + */ +data class ArtSourceLayer( + val key: String, + val name: String, + val groupPath: String, + val left: Int, + val top: Int, + val width: Int, + val height: Int, + val visible: Boolean, + val present: Boolean = true, + val contentHash: String? = null, + val empty: Boolean = false, + val replaced: Boolean = false, + val ignored: Boolean = false, +) + +/** + * A tile's link to the source layer its art came from: which file, and which layer within it. + * + * The key is whatever the reader minted for the layer and is opaque here: a CLIP layer uuid, a Krita + * layer uuid, a PSD lyid, or a PSD name-plus-order fallback. [stableKey] says which of those it is + * in the one way that matters - whether the key survives a rename or reorder in the art program - so + * the reconcile knows when to trust it outright and a listing knows what to show. + * + * @property ArtSourceId sourceId The [ArtSource] the layer belongs to. + * @property String layerKey The reader's key for the layer within that source. + * @property Boolean stableKey Whether the key is a format-minted id (true) or a name-and-order + * fallback that only holds as long as the artist's layer organization does (false). + */ +data class SourceLayerRef( + val sourceId: ArtSourceId, + val layerKey: String, + val stableKey: Boolean, +) + +/** + * Where a delta places one child among a container's existing children. + */ +sealed interface OrgSlot { + /** + * Directly after [anchor], a child the container already has (or one the same delta placed before it). + * + * @property OrgChild anchor The child to follow. + */ + data class After(val anchor: OrgChild) : OrgSlot + + /** + * Directly before [anchor], a child the container already has. + * + * @property OrgChild anchor The child to precede. + */ + data class Before(val anchor: OrgChild) : OrgSlot + + /** After every child the container has. */ + data object End : OrgSlot +} + +/** + * One child a delta places inside the model's existing org tree: a reload found a layer in a folder + * the document already keeps as a part (or at the root), and the file says where among that folder's + * layers it sits, so the drawable lands there rather than at the bottom. An anchor the container no + * longer has places the child at the end. + * + * @property PartId? container The part whose children it joins, or null for the root. + * @property OrgChild child The child: a drawable of the delta, or one of its new parts. + * @property OrgSlot slot Where among the container's children it goes. + */ +data class OrgInsertion( + val container: PartId?, + val child: OrgChild, + val slot: OrgSlot, +) + +/** + * What one artwork file adds to a model: the file's record, its tiles, the drawables and parts born + * from its layers, and where they join the org tree - a fresh file's whole tree after the model's root + * children, a listed file's new layers placed among the children the model already has. A delta + * rather than a model, so the same additions can be appended to a fresh model at open or to a document + * already being rigged. + * + * Every id in here is already minted past the receiving model's (`ArtMesh`, `Part`, `art-`), + * and the new parts' children reference only ids in this delta. Pixels are absent - they travel + * beside it to the document's raster store. + * + * @property ArtSource source The file and its layer inventory. + * @property List tiles One unplaced tile per imported layer, bound to that layer. + * @property List drawables One drawable per tile, over its birth mesh. + * @property List parts One NEW part per folder the model has no part for, nested by the + * parts' own children. + * @property List rootChildren A fresh file's top-level order, appended after the model's own; + * empty for a listed file, whose new children are [insertions]. + * @property List insertions A listed file's new children placed among the existing ones - at + * the root or inside a part the document already keeps for the folder - in the order the file gives + * them, each anchored to its nearest sibling in the file; applied in list order, so a child may anchor + * on one placed before it. Empty for a fresh file, whose folders are all new. + */ +data class ArtworkAdditions( + val source: ArtSource, + val tiles: List, + val drawables: List, + val parts: List, + val rootChildren: List, + val insertions: List = emptyList(), +) + +/** + * One tile a reload supersedes: the id of the tile the art used to live in, and the tile that holds it + * now - a fresh id (`~`), the new size, no placement yet, the old pin, and [AtlasTile.replaces] + * naming the old one. + * + * @property AtlasTileId oldId The superseded tile's id; its pixels stay in the document's raster store. + * @property AtlasTile tile The replacement, unplaced. + */ +data class ReplacedTile( + val oldId: AtlasTileId, + val tile: AtlasTile, +) + +/** + * What re-reading one artwork file changes in a model: the file's record with its NEW inventory, the + * tiles whose art changed (each superseded by a fresh, unplaced tile), the meshes the drawables over + * them take (an untouched birth quad re-born over the new art, an edited mesh carried with its + * coordinates remapped so every vertex samples the same canvas pixel as before), the layers the file + * gained, the drawables whose edited mesh the new opaque art now reaches past, and the drawables whose + * visibility follows the file's eye toggle. + * + * A delta rather than a model, like [ArtworkAdditions]: the same plan applies to the live model and + * to the operation strip's rerun over its base. Pixels travel beside it to the raster store. A layer + * the file lost is deliberately absent - its tile keeps its art and its binding, and the new inventory + * carries its row flagged not present ([ArtSourceLayer.present]), which is what the Sources space shows + * as needing review. + * + * @property ArtSource source The file's record, carrying the inventory as just read. + * @property List replacedTiles The tiles whose art changed, each with its replacement. + * @property Map drawableMeshes The mesh each affected drawable takes, keyed by drawable; + * texture coordinates in the ART frame of the drawable's new tile, which the pack that follows + * converts exactly as it does an import's. + * @property ArtworkAdditions? additions The layers the file gained, minted under [source], or null. + * @property List outgrown Drawables whose kept mesh no longer covers the new opaque art. + * @property List retiredTiles Tiles a rebinding made redundant: a lost layer's rig work took + * the layer a reload had minted a fresh, untouched drawable for, so that drawable and its tile go (the + * pixels stay in the raster store for undo). Never a replaced tile; a part minted for the drawable stays. + * @property Map drawableVisibility The visibility each drawable takes, keyed by drawable, where + * the file's eye toggle changed since the last read and the drawable still showed the OLD state; a + * drawable the rigger toggled since is absent, since that toggle is rig work. + */ +data class ArtworkReload( + val source: ArtSource, + val replacedTiles: List, + val drawableMeshes: Map, + val additions: ArtworkAdditions?, + val outgrown: List, + val retiredTiles: List = emptyList(), + val drawableVisibility: Map = emptyMap(), +) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/AtlasPlacement.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/AtlasPlacement.kt new file mode 100644 index 0000000..14f8dbc --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/AtlasPlacement.kt @@ -0,0 +1,284 @@ +package org.umamo.runtime.model + +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin + +/* + * Where a document's source art sits on its atlas pages, and the affine algebra that maps between the + * two frames. + * + * Model state rather than render state: a placement is authored (a repack moves it), so it has to + * survive undo, diff, and export like any other document content. It lives here, in the module with no + * dependencies, because every consumer needs it - the renderer to sample, the UV editor to map, and the + * CMO3 export to write - and the export path deliberately cannot see the renderer. + */ + +/** + * Where one tile's upright source art sits on an atlas page: the transform the packer applied to it, as + * translation / scale / rotation. + * + * A Transform/Rotation/Scale(TRS) rather than a rect because that is what the source formats actually + * carry and what the corpus actually uses. Rotation and scale both occur, and a rect-plus-quarter-turn + * model would silently discard them on import. A packer that only ever emits axis-aligned unit-scale + * placements writes the constrained subset (scale 1, rotation 0) and loses nothing. + * + * Rotation is DEGREES, counter-clockwise, about the layer's own origin, applied after scale; the frame + * is page pixels with y running DOWN (v = 0 is the page's top row), matching how the decoder emits rows + * and how the sampler addresses them. + * + * [pageIndex] indexes [PuppetAtlas.pages], which is the DOCUMENT's page order. For an IMPORTED + * document it is deliberately NOT the renderer's page numbering: the two are derived independently + * (the renderer collects pages in drawable-encounter order and renumbers when one fails to decode), + * so an index is only ever valid against the list it came from. A page set Umamo generates itself + * (a repack's) is built index-parallel to [PuppetAtlas.pages], so for generated sets the two + * numberings coincide by construction. + * + * @property Int pageIndex The atlas page the art packs onto, indexing [PuppetAtlas.pages]. + * @property Float positionX The packing origin's x on the page, in pixels (fractional in real files). + * @property Float positionY The packing origin's y on the page, in pixels. + * @property Float scaleX The horizontal scale the packer applied (negative mirrors). + * @property Float scaleY The vertical scale the packer applied (negative mirrors). + * @property Float rotationDegrees The rotation the packer applied, counter-clockwise degrees. + */ +data class AtlasPlacement( + val pageIndex: Int, + val positionX: Float, + val positionY: Float, + val scaleX: Float, + val scaleY: Float, + val rotationDegrees: Float, +) + +/** + * One drawable's resolved link to its source art: which tile it samples, and how its stored atlas + * texture coordinates map back into that tile's own pixel frame. + * + * A null [placement] means the drawable renders from the art directly rather than from a packed page - + * its stored uvs already address the tile image, so the mapping is the identity. Applying a placement + * inverse to those would be a double transform. + * + * The page dimensions ride here rather than being looked up per call because a binding is resolved once + * and then applied per vertex, and because a drawable sampling its art directly has no page at all. + * + * @property String layerKey The tile this drawable samples. + * @property AtlasPlacement? placement The packing transform, or null when the drawable samples the art directly. + * @property Int pageWidth The atlas page's width in pixels. + * @property Int pageHeight The atlas page's height in pixels. + */ +data class DrawableLayerBinding( + val layerKey: String, + val placement: AtlasPlacement?, + val pageWidth: Int, + val pageHeight: Int, +) + +/** + * The placement's inverse as a 2x3 affine (m00, m01, m02, m10, m11, m12) mapping page pixels back to + * layer pixels. + * + * The forward transform is `atlas = R(angle) . S . layer + position`, so the inverse is + * `layer = S^-1 . R(-angle) . (atlas - position)`. Resolved once per placement so a whole mesh + * converts without recomputing the trigonometry per vertex. + * + * @param AtlasPlacement placement The packing transform to invert. + * @return FloatArray? The inverse affine, or null when the placement is degenerate (a zero scale). + */ +fun inversePlacementAffine(placement: AtlasPlacement): FloatArray? { + if (placement.scaleX == 0f || placement.scaleY == 0f) { + return null + } + val radians = placement.rotationDegrees.toDouble() * PI / 180.0 + val cosine = cos(radians) + val sine = sin(radians) + // R(-angle) then S^-1, i.e. rows scaled by the inverse scale after the transposed rotation. + val m00 = (cosine / placement.scaleX).toFloat() + val m01 = (sine / placement.scaleX).toFloat() + val m10 = (-sine / placement.scaleY).toFloat() + val m11 = (cosine / placement.scaleY).toFloat() + return floatArrayOf( + m00, + m01, + -(m00 * placement.positionX + m01 * placement.positionY), + m10, + m11, + -(m10 * placement.positionX + m11 * placement.positionY), + ) +} + +/** + * The placement's forward transform as a 2x3 affine (m00, m01, m02, m10, m11, m12) mapping layer + * pixels to page pixels - [atlasPixelOf]'s algebra as a matrix, for callers that compose it with + * other affines rather than applying it pointwise. + * + * @param AtlasPlacement placement The packing transform. + * @return FloatArray The forward affine. + */ +fun placementAffine(placement: AtlasPlacement): FloatArray { + val radians = placement.rotationDegrees.toDouble() * PI / 180.0 + val cosine = cos(radians) + val sine = sin(radians) + return floatArrayOf( + (cosine * placement.scaleX).toFloat(), + (-sine * placement.scaleY).toFloat(), + placement.positionX, + (sine * placement.scaleX).toFloat(), + (cosine * placement.scaleY).toFloat(), + placement.positionY, + ) +} + +/** + * Composes two 2x3 affines: the result applies [inner] first, then [outer]. + * + * @param FloatArray outer The affine applied second. + * @param FloatArray inner The affine applied first. + * @return FloatArray The composition, a fresh array. + */ +fun composeAffine(outer: FloatArray, inner: FloatArray): FloatArray = + floatArrayOf( + outer[0] * inner[0] + outer[1] * inner[3], + outer[0] * inner[1] + outer[1] * inner[4], + outer[0] * inner[2] + outer[1] * inner[5] + outer[2], + outer[3] * inner[0] + outer[4] * inner[3], + outer[3] * inner[1] + outer[4] * inner[4], + outer[3] * inner[2] + outer[4] * inner[5] + outer[5], + ) + +/** + * The atlas-page pixel a layer pixel packs to (the forward transform). + * + * @param AtlasPlacement placement The packing transform. + * @param Float layerX The layer-local x in pixels. + * @param Float layerY The layer-local y in pixels. + * @return FloatArray The (x, y) page pixel. + */ +fun atlasPixelOf(placement: AtlasPlacement, layerX: Float, layerY: Float): FloatArray { + val radians = placement.rotationDegrees.toDouble() * PI / 180.0 + val cosine = cos(radians) + val sine = sin(radians) + val scaledX = layerX * placement.scaleX + val scaledY = layerY * placement.scaleY + return floatArrayOf( + (cosine * scaledX - sine * scaledY).toFloat() + placement.positionX, + (sine * scaledX + cosine * scaledY).toFloat() + placement.positionY, + ) +} + +/** + * The layer pixel an atlas-page pixel came from (the inverse transform). + * + * @param AtlasPlacement placement The packing transform. + * @param Float atlasX The page x in pixels. + * @param Float atlasY The page y in pixels. + * @return FloatArray? The (x, y) layer pixel, or null when the placement is degenerate. + */ +fun layerPixelOf(placement: AtlasPlacement, atlasX: Float, atlasY: Float): FloatArray? { + val inverse = inversePlacementAffine(placement) ?: return null + return floatArrayOf( + inverse[0] * atlasX + inverse[1] * atlasY + inverse[2], + inverse[3] * atlasX + inverse[4] * atlasY + inverse[5], + ) +} + +/** + * The whole atlas-uv to layer-uv mapping for a binding, as one 2x3 affine (m00, m01, m02, m10, m11, + * m12) over NORMALIZED coordinates. + * + * The per-vertex chain is uv times the page size, through the placement inverse, divided by the layer's + * size - all affine, so it folds into a single matrix that any consumer can apply in either direction + * (see [invertUvAffine]). A drawable sampling its art directly has stored uvs that already address the + * tile image, so its mapping is the identity rather than a placement inverse; applying a placement + * there would be a double transform. + * + * @param DrawableLayerBinding binding The drawable's binding. + * @param Int layerWidth The source tile's width in pixels. + * @param Int layerHeight The source tile's height in pixels. + * @return FloatArray? The atlas-uv to layer-uv affine, or null when it cannot be formed. + */ +fun layerUvAffineOf(binding: DrawableLayerBinding, layerWidth: Int, layerHeight: Int): FloatArray? { + val placement = binding.placement ?: return identityUvAffine() + if (layerWidth <= 0 || layerHeight <= 0) { + return null + } + val inverse = inversePlacementAffine(placement) ?: return null + return floatArrayOf( + inverse[0] * binding.pageWidth / layerWidth, + inverse[1] * binding.pageHeight / layerWidth, + inverse[2] / layerWidth, + inverse[3] * binding.pageWidth / layerHeight, + inverse[4] * binding.pageHeight / layerHeight, + inverse[5] / layerHeight, + ) +} + +/** The uv affine that changes nothing - the mapping of a drawable whose uvs already address its art. */ +fun identityUvAffine(): FloatArray = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f) + +/** + * Inverts a 2x3 uv affine, turning a mapping INTO a frame into the mapping back OUT of it. + * + * @param FloatArray affine The affine to invert (m00, m01, m02, m10, m11, m12). + * @return FloatArray? The inverse, or null when the affine is degenerate (a zero determinant). + */ +fun invertUvAffine(affine: FloatArray): FloatArray? { + if (affine.size < 6) { + return null + } + val determinant = affine[0] * affine[4] - affine[1] * affine[3] + if (determinant == 0f) { + return null + } + val m00 = affine[4] / determinant + val m01 = -affine[1] / determinant + val m10 = -affine[3] / determinant + val m11 = affine[0] / determinant + return floatArrayOf( + m00, + m01, + -(m00 * affine[2] + m01 * affine[5]), + m10, + m11, + -(m10 * affine[2] + m11 * affine[5]), + ) +} + +/** + * Applies a 2x3 uv affine to a whole interleaved (u, v) array. + * + * @param FloatArray uvs The coordinates to map. + * @param FloatArray affine The affine to apply. + * @return FloatArray The mapped coordinates, a fresh array. + */ +fun applyUvAffine(uvs: FloatArray, affine: FloatArray): FloatArray { + val mapped = FloatArray(uvs.size) + var componentIndex = 0 + while (componentIndex + 1 < uvs.size) { + val u = uvs[componentIndex] + val v = uvs[componentIndex + 1] + mapped[componentIndex] = affine[0] * u + affine[1] * v + affine[2] + mapped[componentIndex + 1] = affine[3] * u + affine[4] * v + affine[5] + componentIndex += 2 + } + return mapped +} + +/** + * Maps a drawable's stored texture coordinates into its source tile's own [0,1] frame - the mapping a + * layer view draws. + * + * @param FloatArray atlasUvs The drawable's stored texture coordinates, interleaved (u, v). + * @param DrawableLayerBinding binding The drawable's binding. + * @param Int layerWidth The source tile's width in pixels. + * @param Int layerHeight The source tile's height in pixels. + * @return FloatArray? The layer-frame uvs, or null when the mapping cannot be formed. + */ +fun layerUvsFromAtlasUvs( + atlasUvs: FloatArray, + binding: DrawableLayerBinding, + layerWidth: Int, + layerHeight: Int, +): FloatArray? { + val affine = layerUvAffineOf(binding, layerWidth, layerHeight) ?: return null + return applyUvAffine(atlasUvs, affine) +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/BlendMode.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/BlendMode.kt new file mode 100644 index 0000000..e60b352 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/BlendMode.kt @@ -0,0 +1,111 @@ +package org.umamo.runtime.model + +/** + * How a drawable or a layer composite blends its color against what's already drawn. Mirrors + * Cubism's color blend modes: the three legacy pre-5.3 modes (bare CMO3 tokens, fixed-function + * blending) plus the fifteen 5.3 modes (shader compositing). An `enum` (not sealed) because the set + * is fixed and each case is a plain value with no extra data. + * + * Each constant cites its CMO3 ColorComposition token and its MOC3 packed colorMode int + * (sections 153/157, `colorMode or (alphaMode shl 8)`); the mapping lives in explicit functions + * (BlendModeMapping), never in ordinals. + * + * 描画オブジェクト/オフスクリーン合成のカラーブレンドモード。Cubism のブレンドモードに対応。 + */ +enum class BlendMode { + /** Legacy Normal. CMO3 `NORMAL`; MOC3 colorMode 0 (constant-flags bits clear). */ + Normal, + + /** Add (Before 5.3), premultiplied fixed-function. CMO3 `ADD`; MOC3 colorMode 1 (constant-flags bit 0). */ + AdditivePremultiplied, + + /** Multiply (Before 5.3), premultiplied fixed-function. CMO3 `MULTIPLY`; MOC3 colorMode 2 (constant-flags bit 1). */ + MultiplyPremultiplied, + + /** Add (5.3+). CMO3 `ADD_R2_TSL`; MOC3 colorMode 3. */ + Additive, + + /** Add (Glow) (5.3). CMO3 `ADD_R2`; MOC3 colorMode 4. */ + AdditiveGlow, + + /** Darken (5.3). CMO3 `DARKEN`; MOC3 colorMode 5. */ + Darken, + + /** Multiply (5.3+). CMO3 `MULTIPLY_R2`; MOC3 colorMode 6. */ + Multiply, + + /** Color burn (5.3). CMO3 `COLORBURN_TSL`; MOC3 colorMode 7. */ + ColorBurn, + + /** Linear burn (5.3). CMO3 `LINEARBURN_TSL`; MOC3 colorMode 8. */ + LinearBurn, + + /** Lighten (5.3). CMO3 `LIGHTEN`; MOC3 colorMode 9. */ + Lighten, + + /** Screen (5.3). CMO3 `SCREEN`; MOC3 colorMode 10. */ + Screen, + + /** Color dodge (5.3). CMO3 `COLORDODGE_TSL`; MOC3 colorMode 11. */ + ColorDodge, + + /** Overlay (5.3). CMO3 `OVERLAY`; MOC3 colorMode 12. */ + Overlay, + + /** Soft light (5.3). CMO3 `SOFTLIGHT`; MOC3 colorMode 13. */ + SoftLight, + + /** Hard light (5.3). CMO3 `HARDLIGHT`; MOC3 colorMode 14. */ + HardLight, + + /** Linear light (5.3). CMO3 `LINEARLIGHT_TSL`; MOC3 colorMode 15. */ + LinearLight, + + /** Hue (5.3, HSL non-separable). CMO3 `HSL_HUE`; MOC3 colorMode 16. */ + Hue, + + /** Color (5.3, HSL non-separable). CMO3 `HSL_COLOR`; MOC3 colorMode 17. */ + Color, + + ; + + /** + * True for the three pre-5.3 modes, whose semantics are plain fixed-function blending; every + * other mode requires the destination-sampling composite path. + */ + val isLegacy: Boolean get() = this == Normal || this == AdditivePremultiplied || this == MultiplyPremultiplied + + /** + * Whether this color blend mode ignores the Alpha blend setting. Per the Cubism editor, the pre-5.3 + * "Add (Before 5.3)" and "Multiply (Before 5.3)" modes composite in premultiplied format and disregard + * the Alpha blend selection. Drives the composite math and the properties panel alpha-field visibility. + */ + val ignoresAlphaBlend: Boolean get() = this == AdditivePremultiplied || this == MultiplyPremultiplied +} + +/** + * How a drawable or a layer composite combines its ALPHA with the destination - Cubism 5.3's + * Porter-Duff-style alpha blend list, orthogonal to [BlendMode]. Pre-5.3 sources have no alpha + * mode; they behave as [Over]. + * + * Each constant cites its CMO3 AlphaComposition token and MOC3 packed alphaMode int + * (sections 153/157, bits 8-15). + * + * アルファブレンドモード(Cubism 5.3)。カラーブレンドとは独立。 + */ +enum class AlphaBlendMode { + /** Over (the default; pre-5.3 behavior). CMO3 `OVER`; MOC3 alphaMode 0. */ + Over, + + /** Atop. CMO3 `ATOP`; MOC3 alphaMode 1. */ + Atop, + + /** Out. CMO3 `OUT`; MOC3 alphaMode 2. */ + Out, + + /** Conjoint over. CMO3 `CONJOINT`; MOC3 alphaMode 3. */ + Conjoint, + + /** Disjoint over. CMO3 `DISJOINT`; MOC3 alphaMode 4. */ + Disjoint, +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/BlendShapes.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/BlendShapes.kt new file mode 100644 index 0000000..9f963e1 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/BlendShapes.kt @@ -0,0 +1,94 @@ +package org.umamo.runtime.model + +/** + * One point of a blend-weight limit curve: at [value] on the constraint parameter, the blend + * shape's weight is capped to [weight]. + * + * ブレンドウェイト制限カーブの 1 点。制約パラメータが [value] のとき重みは [weight] に制限される。 + * + * @property Float value The constraint parameter's value this point sits at. + * @property Float weight The weight cap at that value (0..1). + */ +data class BlendWeightLimitPoint( + val value: Float, + val weight: Float, +) + +/** + * A blend-weight limit ("blend shape limit" in the Cubism editor): a piecewise-linear, end-clamped + * curve over ANOTHER parameter's value that caps a blend shape's weight. A binding's effective + * multiplier is the MINIMUM over all of its limits (1 when it has none). + * + * CMO3: MorphTargetBlendWeightConstraint - the flat (constraintParameterGuid, + * constraintParameterValue, blendWeight) records grouped per constraint parameter into one curve. + * + * ブレンドウェイト制限。別パラメータ値に対する区分線形カーブで重みを制限し、複数あれば最小値を取る。 + * + * @property ParameterId parameterId The constraint parameter whose value drives this curve. + * @property List points The curve points, sorted ascending by value. + */ +data class BlendWeightLimit( + val parameterId: ParameterId, + val points: List, +) + +/** + * A blend shape ("MorphTarget" in CMO3): an ADDITIVE deformation on one object, driven by one + * parameter. Where a keyform grid interpolates BETWEEN absolute forms (parameters select shapes), + * a blend shape ADDS a weighted delta on top of the grid result (parameters add shapes), and + * multiple bindings on the same object stack by summation. + * + * [keys] always contains the neutral key at parameter VALUE 0, not at the parameter's default. + * Ingest inserts the neutral when the document does not key value 0, so [forms] at [neutralIndex] + * is null in practice (a morph authored exactly at 0 would occupy the slot but is never read - the + * neutral key contributes zero by definition, and baked files store an all-zero delta row there). + * A morph authored AT the parameter's default (non-zero) is an ordinary non-neutral key: the + * Umamo C++ runtime applies it at the default pose. Non-neutral forms are stored exactly as the + * object's grid stores its forms ([MeshForm] position deltas are relative to the rest mesh, + * [WarpForm]/[RotationForm] are absolute); deriving the neutral-relative delta each key contributes + * is the evaluator's job, not this type's. + * + * CMO3: ACParameterControllableSource.keyformMorphTargetSet -> KeyFormMorphTargetSet - one + * KeyFormMorphTarget per (parameterGuid, keyValue, keyformGuid); one binding groups a source's + * morph targets sharing a driving parameter. + * + * ブレンドシェイプ(CMO3 の MorphTarget)。格子補間の結果に加算される差分で、同一オブジェクト上の + * 複数バインディングは合算される。[neutralIndex] は寄与ゼロのキー(フォームは null)。 + * + * @property ParameterId parameterId The driving parameter. + * @property FloatArray keys The parameter values the forms are keyed at, ascending, + * including the inserted neutral key. + * @property Int neutralIndex Index into [keys] of the zero-contribution (rest) key. + * @property List forms One form per key, parallel to [keys]; null at the neutral + * key when the neutral was inserted rather than authored. + * @property List limits Blend-weight limit curves; the effective weight multiplier is + * their minimum (1 when empty). + */ +data class BlendShapeBinding( + val parameterId: ParameterId, + val keys: FloatArray, + val neutralIndex: Int, + val forms: List, + val limits: List = emptyList(), +) { + // data class with an array field: generated equals/hashCode use referential array equality, + // which is wrong for value semantics (same rationale as Keyform). + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is BlendShapeBinding<*>) return false + return parameterId == other.parameterId && + keys.contentEquals(other.keys) && + neutralIndex == other.neutralIndex && + forms == other.forms && + limits == other.limits + } + + override fun hashCode(): Int { + var hash = parameterId.hashCode() + hash = 31 * hash + keys.contentHashCode() + hash = 31 * hash + neutralIndex + hash = 31 * hash + forms.hashCode() + hash = 31 * hash + limits.hashCode() + return hash + } +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/ColorRgb.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/ColorRgb.kt new file mode 100644 index 0000000..3baa8b2 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/ColorRgb.kt @@ -0,0 +1,35 @@ +package org.umamo.runtime.model + +/** + * A straight-alpha-free RGB color channel triple, 0..1 per channel - the multiply/screen color + * payload of a layer composite. Channels are the editor hex value / 255 as float32 (CMO3 + * `CFloatColor` red/green/blue; MOC3 color-table rows 108-113 carry the identical floats). The + * source formats' alpha attribute is always 1.0 in every observed sample, so it is not modeled. + * + * 乗算色/スクリーン色の RGB 値(0..1)。 + */ +data class ColorRgb( + val red: Float, + val green: Float, + val blue: Float, +) { + companion object { + /** The multiply-color identity (#FFFFFF - multiplying by it changes nothing). */ + val MultiplyIdentity: ColorRgb = ColorRgb(1f, 1f, 1f) + + /** The screen-color identity (#000000 - screening with it changes nothing). */ + val ScreenIdentity: ColorRgb = ColorRgb(0f, 0f, 0f) + } + + /** + * This color with every channel clamped into 0..1. + * + * Additive accumulation (blend-shape color deltas, the deformer screen composition) can leave the + * range at the ends of a keyed span, and the clamp belongs AFTER the whole sum rather than per + * term - clamping each contribution would bias a record whose neighbours pull the other way. + * + * @return ColorRgb The clamped color. + */ + fun coerceToUnit(): ColorRgb = + ColorRgb(red.coerceIn(0f, 1f), green.coerceIn(0f, 1f), blue.coerceIn(0f, 1f)) +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Deformer.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Deformer.kt new file mode 100644 index 0000000..dcabbdd --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Deformer.kt @@ -0,0 +1,178 @@ +package org.umamo.runtime.model + +/** + * A deformer in the rig hierarchy. + * + * Cubism deformation is parameter-driven morph blending, not skeletal - there are exactly two + * deformer kinds, so a `sealed interface` captures the closed taxonomy and forces `when`s over it to + * be exhaustive (adding a third kind becomes a compile error until handled everywhere). Deformers nest + * via [parent] (the transform hierarchy a drawable inherits); each also belongs to a part via [partId] + * (the organizational tree) - two independent hierarchies, mirroring CMO3's `targetDeformerGuid` vs + * `parentGuid`. + * + * リグ階層の変形器。Cubism は2種(ワープ/回転)のみ。変形系統([parent])と組織系統([partId])は別。 + */ +sealed interface Deformer { + val id: DeformerId + + /** The user-facing display name (CMO3 localName), e.g. "Warp Deformer of Bag front12"; the id when unnamed. */ + val name: String + + /** Parent deformer in the nesting (transform) hierarchy, or null at the root. */ + val parent: DeformerId? + + /** The part this deformer belongs to (organizational tree), or null at the root. */ + val partId: PartId? + + /** + * The deformer's per-channel keyform tracks. + * + * On the interface rather than only the subtypes because every generic walk over a rig - the + * parameter-delete scrub, the panel's effective-parameter set, the clamped-pose axis collection - + * needs the tracks without caring which kind of deformer carries them. + */ + val channelGrids: ChannelGrids + + /** + * Blender-style selectable toggle: an unselectable deformer cannot be picked in the viewport. + * Maps inverted to CMO3's isLocked (Cubism lock = not selectable), which the CMO3 export + * lowering emits as isLocked = !isSelectable. + */ + val isSelectable: Boolean + + /** + * The editor's eye toggle - a hidden deformer and everything under it does not render. + * + * MOC3 §5.6 s13; CMO3 ACParameterControllableSource.isVisible. A bake normally DELETES what the + * editor hides, so almost every imported deformer is visible; Azxiana is the one corpus model that + * keeps 7 hidden ones. Umamo's own export always carries hidden deformers (the export options + * offer no deformer toggle), which is what makes this round-trip rather than decay to true. + */ + val isVisible: Boolean + + /** + * The deformer's second MOC3 flag (§5.6 s14), carried so a bake reproduces it. + * + * It is 1 on every deformer of every corpus model, so its meaning is unpinned - it is NOT the + * visibility toggle ([isVisible] is, by analogy with the art-mesh pair that a CMO3 join proved). + * Nothing reads it; it exists so the value survives a round trip instead of being invented. + * + * ONLY MOC3 HAS THIS. "Enabled" is just a guess as to what it is since it seems to behave like an enabled toggle. + */ + val isEnabled: Boolean + + /** + * Warp deformer - a free-form-deformation (FFD) lattice: a [rows] × [columns] grid of control + * points whose displacement bends the bound geometry. The control-point positions are animated + * per keyform; only the lattice dimensions are static. + */ + data class Warp( + override val id: DeformerId, + override val name: String, + override val parent: DeformerId?, + override val partId: PartId?, + val rows: Int, + val columns: Int, + /** FFD interpolation mode: true = bilinear (quad), false = triangle split (the Umamo C++ Runtime's warp mode). */ + val isQuadTransform: Boolean, + /** + * Per-parameter lattice control-point forms, or null if unkeyed. + * + * A warp carries no separate rest lattice, so this is the ONLY source of its geometry - an unkeyed + * warp therefore still cannot render, unlike an unkeyed drawable which falls back to its rest mesh. + */ + val geometryGrid: KeyformGrid?, + /** + * The deformer's per-channel render tracks (opacity, multiply / screen color), each falling back to + * the statics below. These CASCADE onto every drawable under the deformer. + */ + override val channelGrids: ChannelGrids = ChannelGrids.Empty, + /** Static opacity used when [channelGrids] has no opacity track. */ + val opacity: Float = 1f, + /** Static multiply color used when [channelGrids] has no multiply track. */ + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + /** Static screen color used when [channelGrids] has no screen track. */ + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, + override val isSelectable: Boolean = true, + override val isVisible: Boolean = true, + override val isEnabled: Boolean = true, + /** + * Additive blend-shape bindings on the lattice control points, applied on top of the + * [geometryGrid] result; empty when the deformer has none. (CMO3 keyformMorphTargetSet.) + */ + val blendShapes: List> = emptyList(), + ) : Deformer + + /** + * Rotation deformer - a nesting pivot transform. Its origin/angle/scale are animated per keyform + * [baseAngle] is the static editor reference angle. + */ + data class Rotation( + override val id: DeformerId, + override val name: String, + override val parent: DeformerId?, + override val partId: PartId?, + val baseAngle: Float, + /** Per-parameter pivot-transform forms (origin / angle / scale), or null if unkeyed. */ + val geometryGrid: KeyformGrid?, + /** + * The deformer's per-channel tracks: the render channels (opacity, multiply / screen color) that + * cascade onto every drawable underneath, plus the two reflection FLAGS. The flags live here rather + * than on the pivot form because they snap to the floor cell instead of blending, so they do not + * belong beside values that interpolate. + */ + override val channelGrids: ChannelGrids = ChannelGrids.Empty, + /** Static opacity used when [channelGrids] has no opacity track. */ + val opacity: Float = 1f, + /** Static multiply color used when [channelGrids] has no multiply track. */ + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + /** Static screen color used when [channelGrids] has no screen track. */ + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, + /** Static horizontal reflection used when [channelGrids] has no flip-X track. */ + val flipX: Boolean = false, + /** Static vertical reflection used when [channelGrids] has no flip-Y track. */ + val flipY: Boolean = false, + override val isSelectable: Boolean = true, + override val isVisible: Boolean = true, + override val isEnabled: Boolean = true, + /** + * Additive blend-shape bindings on the pivot transform, applied on top of the [geometryGrid] + * result; empty when the deformer has none. (CMO3 keyformMorphTargetSet.) + */ + val blendShapes: List> = emptyList(), + ) : Deformer +} + +/* + * The statics every deformer subtype carries, read through the sealed supertype. + * + * Deformer is a sealed interface whose statics live on the subtypes, so anything wanting "this deformer's + * opacity" had to write the two-branch when itself - and three separate copies of each had accumulated + * (the Properties row, the edit op, and their tests), so adding a third subtype meant fixing them in + * lockstep and any divergence would silently make the panel disagree with the edit. One definition here, + * exhaustive over the sealed type, so a new subtype is a compile error in exactly one place. + */ + +/** This deformer's static opacity, whichever subtype it is. */ +val Deformer.opacity: Float + get() = + when (this) { + is Deformer.Warp -> opacity + is Deformer.Rotation -> opacity + } + +/** This deformer's static multiply color, whichever subtype it is. */ +val Deformer.multiplyColor: ColorRgb + get() = + when (this) { + is Deformer.Warp -> multiplyColor + is Deformer.Rotation -> multiplyColor + } + +/** This deformer's static screen color, whichever subtype it is. */ +val Deformer.screenColor: ColorRgb + get() = + when (this) { + is Deformer.Warp -> screenColor + is Deformer.Rotation -> screenColor + } \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/DrawableMesh.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/DrawableMesh.kt new file mode 100644 index 0000000..49886f1 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/DrawableMesh.kt @@ -0,0 +1,87 @@ +package org.umamo.runtime.model + +/** + * An art mesh's static (rest-pose) geometry: interleaved [positions] and [uvs] (x then y per vertex) + * and the triangle [indices] (three per polygon). Deformation deltas live in the drawable's keyform + * grid; this is the base the deltas are applied to in `p = base + Σ wᵢ·Δᵢ`. + * + * A plain `class`, not a `data class`: the fields are arrays, whose identity-based `equals` would make + * a generated structural `equals` quietly wrong (the same trap [Keyform] sidesteps by hand). A mesh is + * referenced, not value-compared, so reference identity is the honest default here. + */ +class DrawableMesh( + val positions: FloatArray, + val uvs: FloatArray, + val indices: IntArray, +) { + /** Vertex count - two floats (x, y) per vertex. */ + val vertexCount: Int get() = positions.size / 2 + + /** Triangle (polygon) count - three indices per triangle. */ + val triangleCount: Int get() = indices.size / 3 +} + +/** The two triangles a birth quad is always wound with: corners in the order left-top, right-top, right-bottom, left-bottom. */ +private val BIRTH_QUAD_INDICES = intArrayOf(0, 1, 2, 0, 2, 3) + +/** + * Whether this mesh is still the quad an artwork import gave the drawable at birth, untouched since: + * four corners wound as the import winds them, an axis-aligned rectangle, and texture coordinates that + * are the same rectangle in the tile's art - each corner samples exactly the art pixel under it. A + * moved vertex breaks the alignment or the position-to-texel agreement, a subdivision the count, so no + * edit history is needed to tell an untouched quad from an authored mesh. + * + * Read on a reload to decide whether the drawable gets a fresh quad over the new art (an untouched + * quad has nothing to preserve) or keeps its mesh. + * + * @param FloatArray artUvs The mesh's texture coordinates in the ART frame (0..1 across the tile). + * @param Int tileWidth The tile's width in pixels. + * @param Int tileHeight The tile's height in pixels. + * @param Float layerLeft The layer's canvas x at the last read - the art frame's origin. + * @param Float layerTop The layer's canvas y at the last read. + * @param Float tolerance How far, in pixels, a corner may sit from its texel before the quad + * counts as edited; half a pixel absorbs float round trips. + * @return Boolean True for an untouched birth quad. + */ +fun DrawableMesh.isUntouchedBirthQuad( + artUvs: FloatArray, + tileWidth: Int, + tileHeight: Int, + layerLeft: Float, + layerTop: Float, + tolerance: Float = 0.1f, +): Boolean { + if (vertexCount != 4 || artUvs.size != 8 || !indices.contentEquals(BIRTH_QUAD_INDICES)) { + return false + } + val left = positions[0] + val top = positions[1] + val right = positions[2] + val bottom = positions[5] + val axisAligned = + near(positions[3], top, tolerance) && + near(positions[4], right, tolerance) && + near(positions[6], left, tolerance) && + near(positions[7], bottom, tolerance) + if (!axisAligned || right <= left || bottom <= top) { + return false + } + for (corner in 0 until 4) { + val texelX = artUvs[corner * 2] * tileWidth + layerLeft + val texelY = artUvs[corner * 2 + 1] * tileHeight + layerTop + if (!near(texelX, positions[corner * 2], tolerance) || !near(texelY, positions[corner * 2 + 1], tolerance)) { + return false + } + } + return true +} + +/** + * Whether two coordinates agree within [tolerance]. + * + * @param Float first One coordinate. + * @param Float second The other. + * @param Float tolerance The largest difference that still counts as agreement. + * @return Boolean True when they agree. + */ +private fun near(first: Float, second: Float, tolerance: Float): Boolean = kotlin.math.abs(first - second) <= tolerance \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/FormChannel.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/FormChannel.kt new file mode 100644 index 0000000..e8f370d --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/FormChannel.kt @@ -0,0 +1,126 @@ +package org.umamo.runtime.model + +/* + * The per-channel keyform tracks: an entity's animatable non-geometry properties, each keyed on its own + * axes at its own key positions rather than riding one bundled keyform cell. + * + * Cubism's keyform cell is all-or-nothing - CArtMeshForm carries positions, draw order, opacity, and the + * multiply/screen tints together, so keying any one of them keys all of them. Splitting them lets a + * rigger key opacity on one parameter without touching geometry, which is the whole point: the bundled + * shape cannot express it at all. ONE enum plus ONE map rather than a map per value type, because every + * generic walk over an entity's channels - the parameter-delete scrub, compaction, the export refine, + * the dope-sheet track list - needs to iterate them uniformly, and a flag channel fits no scalar/color + * split. + */ + +/** The kind of value a [FormChannel] stores, and therefore how it interpolates between keys. */ +enum class ChannelValueKind { + /** Blends linearly. */ + SCALAR, + + /** Blends linearly per component. */ + COLOR, + + /** Snaps to the floor cell - a boolean has no meaningful midpoint. */ + FLAG, +} + +/** + * One animatable non-geometry channel of a keyable entity. + * + * Every format citation for a keyformed scalar or color lives here, now that the bundled form classes + * have retired to being import intermediates. Adding a channel later is one constant, not a new field + * on every owner. + */ +enum class FormChannel(val valueKind: ChannelValueKind) { + // CMO3: CArtMeshForm field drawOrder / CPartForm field drawOrder; MOC3 §5.6 keyform draw order. + DRAW_ORDER(ChannelValueKind.SCALAR), + + // CMO3: CArtMeshForm / CPartForm / ACDeformerForm field opacity; MOC3 §5.6 keyform opacity. + OPACITY(ChannelValueKind.SCALAR), + + // CMO3: CArtMeshForm / CPartForm / ACDeformerForm field multiplyColor; MOC3 color-table rows 108-113. + MULTIPLY_COLOR(ChannelValueKind.COLOR), + + // CMO3: CArtMeshForm / CPartForm / ACDeformerForm field screenColor; MOC3 color-table rows 108-113. + SCREEN_COLOR(ChannelValueKind.COLOR), + + // CMO3: CRotationDeformerForm field isReflectX; MOC3 §5.6 s66 rotation reflect x. The Umamo C++ + // Runtime snaps this per grid cell into the affine's flipX, so it is NOT interpolable. + FLIP_X(ChannelValueKind.FLAG), + + // CMO3: CRotationDeformerForm field isReflectY; MOC3 §5.6 s67 rotation reflect y. + FLIP_Y(ChannelValueKind.FLAG), + + // CMO3: CGlueForm field intensity; MOC3 §5.6 s100 glue intensities. + GLUE_INTENSITY(ChannelValueKind.SCALAR), +} + +/** + * The value stored in one cell of a channel track. + * + * Sealed so interpolation is an exhaustive `when` rather than a strategy object: adding a fourth value + * kind becomes a compile error at every site that has to handle it. + */ +sealed interface ChannelValue { + /** The channel's [ChannelValueKind], so a generic walk can check a value against its channel. */ + val valueKind: ChannelValueKind + + /** A linearly blended scalar (opacity, draw order, glue intensity). */ + data class Scalar(val value: Float) : ChannelValue { + override val valueKind: ChannelValueKind get() = ChannelValueKind.SCALAR + } + + /** A per-component blended color (the multiply / screen tints). */ + data class Color(val color: ColorRgb) : ChannelValue { + override val valueKind: ChannelValueKind get() = ChannelValueKind.COLOR + } + + /** A boolean that snaps to the floor cell (the rotation deformer's reflection flags). */ + data class Flag(val flag: Boolean) : ChannelValue { + override val valueKind: ChannelValueKind get() = ChannelValueKind.FLAG + } +} + +/** + * One owner's non-geometry channel tracks, keyed by channel. + * + * A plain class with referential equality, matching [KeyformGrid], so the renderer's identity-based + * model diff keeps behaving exactly as it does today - a data class here would make an unrelated + * deep compare run on every frame's reconcile. A channel with no entry falls back to the owner's + * static field for that property, which after import compaction is the overwhelmingly common case; + * [Empty] is shared so it allocates nothing. + */ +class ChannelGrids(val gridsByChannel: Map>) { + /** True when this owner has no channel tracks at all (every property reads its static value). */ + val isEmpty: Boolean get() = gridsByChannel.isEmpty() + + /** + * The track for [channel], or null when this owner does not key it. + * + * @param FormChannel channel The channel to look up. + * @return KeyformGrid? The channel's track, or null when unkeyed. + */ + operator fun get(channel: FormChannel): KeyformGrid? = gridsByChannel[channel] + + /** + * Whether this owner's [channel] track holds any value other than [identity]. + * + * A track's mere PRESENCE is not use. A MOC3 import fans every channel out of one bundled grid, so a + * drawable that was never tinted still gets a color track of pure identity cells - and compaction + * deliberately leaves it alone when its axis does not bracket the parameter's range, since an + * out-of-span pose has to fall back to the static. Counting that as "the document uses color" + * makes an export warn about losing a tint that does not exist. + * + * @param FormChannel channel The channel to inspect. + * @param ChannelValue identity The channel's neutral value. + * @return Boolean True when some cell differs from the identity. + */ + fun varies(channel: FormChannel, identity: ChannelValue): Boolean = + this[channel]?.cells?.any { cell -> cell.form != identity } ?: false + + companion object { + /** The shared no-tracks instance - every property falls back to its owner's static value. */ + val Empty: ChannelGrids = ChannelGrids(emptyMap()) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/GeometryForm.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/GeometryForm.kt new file mode 100644 index 0000000..ad31e52 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/GeometryForm.kt @@ -0,0 +1,41 @@ +package org.umamo.runtime.model + +/* + * The geometry half of a split keyform: the only channel whose payload is per-vertex / per-control-point, + * the only one the GPU consumes, and the only one whose out-of-range pose HIDES its entity. That is why + * geometry stays a separate typed field on each owner rather than another FormChannel entry - a scalar + * track can never be handed to the delta-texture bake by mistake, because it would not type-check. + * + * These mirror the bundled MeshForm / WarpForm / RotationForm minus their scalar and color channels, which + * moved to ChannelGrids. The bundled classes stay as the import intermediate and the blend-shape payload. + */ + +/** + * A drawable keyform's geometry: per-vertex position deltas (interleaved x,y) relative to the mesh base. + * + * Stored as deltas rather than absolute positions to match the GPU vertex-shader morph `p = base + Σ wᵢ·Δᵢ` + * - the delta table is exactly what the shader texel-fetches per active corner. + */ +class MeshDeltaForm(val positionDeltas: FloatArray) + +/** + * A warp deformer keyform's geometry: the ABSOLUTE FFD lattice control-point positions (interleaved x,y). + * + * Absolute, not deltas: a warp source carries no separate rest lattice to be relative to, so these forms + * are the only place the lattice geometry exists. That is why an unkeyed warp cannot yet render. + */ +class WarpLatticeForm(val controlPoints: FloatArray) + +/** + * A rotation deformer keyform's geometry: the ABSOLUTE pivot transform captured at one grid cell. + * + * The reflection flags that rode the bundled RotationForm are now [FormChannel.FLIP_X] / [FormChannel.FLIP_Y] + * channels, because they snap to the floor cell rather than blending and so do not belong beside values + * that interpolate. + */ +class RotationPivotForm( + val originX: Float, + val originY: Float, + val angle: Float, + val scale: Float, +) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Glue.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Glue.kt new file mode 100644 index 0000000..72fd16a --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Glue.kt @@ -0,0 +1,77 @@ +package org.umamo.runtime.model + +/** + * One glued vertex pair: vertex [indexA] of the glue's mesh A welded to vertex [indexB] of mesh B, each + * pulled toward the other by its per-side weight. Indices are into the meshes' deformed position arrays, + * so each importer has to land them in that space: a CMO3 import resolves that format's stable vertex + * UIDs, while MOC3 (§5.6 s99) already stores them mesh-local. + */ +class GluePair( + val indexA: Int, + val indexB: Int, + val weightA: Float, + val weightB: Float, +) + +/** + * A glue keyform: the weld intensity (0 = no weld, 1 = full) at one grid cell. + * + * Retained as the CMO3 / MOC3 import intermediate; the model itself keys weld strength through + * [FormChannel.GLUE_INTENSITY] on [Glue.channelGrids]. + */ +class GlueForm(val intensity: Float) + +/** + * A glue affecter - seam-welds two art meshes' shared-edge vertices so they move together (a tail's + * two skinned strips, a sleeve seam, …). It runs after both meshes are deformed: for each [GluePair] + * each side slides toward the other by `weight · intensity` from the pre-blend positions - + * `A' = A + (B−A)·wA·i`, `B' = B + (A−B)·wB·i`. Without it the welded strips drift apart into "two + * copies". + * + * Weld strength is the [FormChannel.GLUE_INTENSITY] track when one is keyed, else the static + * [intensity] - which is 1 (full weld) for a glue that was never animated. + */ +class Glue( + val meshA: DrawableId, + val meshB: DrawableId, + val pairs: List, + val channelGrids: ChannelGrids = ChannelGrids.Empty, + val intensity: Float = 1f, + /** + * The source's authored identifier (MOC3 §5.6 s90, e.g. "Glue__ArtMesh48__ArtMesh49"), or null + * when the source carried none. + * + * A plain string rather than a typed id because nothing REFERENCES a glue - it is addressed only by + * list position, so there is no lookup for an id type to make safe. It is carried purely so a + * round trip writes back the name the model was authored with instead of a synthesized one. + */ + val id: String? = null, +) { + /** + * This glue with the given fields replaced, every other one carried over. + * + * Every rewrite goes through here rather than the constructor, so changing one field cannot silently + * drop another - a positional rebuild that stops early resets the rest to their defaults, and [id] + * is the one whose default is indistinguishable from a source that carried none. + * + * Hand-written rather than a `data class` conversion: the generated `equals`/`hashCode` would + * compare [pairs] and the channel grids by reference anyway, so that would buy this one method at + * the cost of a misleading equality contract. + * + * @param DrawableId meshA The first welded mesh. + * @param DrawableId meshB The second welded mesh. + * @param List pairs The welded vertex pairs. + * @param ChannelGrids channelGrids The keyed channel tracks. + * @param Float intensity The static weld strength. + * @param String? id The source's authored identifier. + * @return Glue The rewritten glue. + */ + fun copy( + meshA: DrawableId = this.meshA, + meshB: DrawableId = this.meshB, + pairs: List = this.pairs, + channelGrids: ChannelGrids = this.channelGrids, + intensity: Float = this.intensity, + id: String? = this.id, + ): Glue = Glue(meshA, meshB, pairs, channelGrids, intensity, id) +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Ids.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Ids.kt new file mode 100644 index 0000000..44822e8 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Ids.kt @@ -0,0 +1,50 @@ +package org.umamo.runtime.model + +import kotlin.jvm.JvmInline + +/** + * Typed identifiers for model entities. + * + * Each is a `@JvmInline value class` - a zero-cost wrapper the compiler erases to the bare + * underlying value where it can, while keeping the types distinct at compile time. This replaces + * the "stringly-typed" anti-pattern (`Map` where any String fits any slot): you can't + * pass a [DrawableId] where a [PartId] is wanted. Cheap safety, no allocation. + * + * The import is load-bearing, not noise: `kotlin.jvm.*` is a default import only on JVM targets, so + * without it this file stops compiling the moment a non-JVM target (Kotlin/Native, for iPadOS) is + * added. The annotation itself is an optional expectation, so non-JVM targets simply ignore it. + */ +@JvmInline +value class PartId(val raw: String) + +@JvmInline +value class DrawableId(val raw: String) + +@JvmInline +value class DeformerId(val raw: String) + +@JvmInline +value class ParameterId(val raw: String) + +@JvmInline +value class ParameterGroupId(val raw: String) + +@JvmInline +value class KeyformId(val raw: String) + +/** + * One piece of source art in the document's atlas. + * + * Distinct from a source-LAYER identity, which says which artwork file and layer a tile came from: + * this only names a tile within one document, and the two coincide only for a rig built from layered + * art in the first place. + */ +@JvmInline +value class AtlasTileId(val raw: String) + +/** + * One artwork file in the document's source list ([PuppetModel.sources]) - what a tile's + * [SourceLayerRef] names as the file half of its binding. + */ +@JvmInline +value class ArtSourceId(val raw: String) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/KeyableTarget.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/KeyableTarget.kt new file mode 100644 index 0000000..2693f2c --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/KeyableTarget.kt @@ -0,0 +1,82 @@ +package org.umamo.runtime.model + +/* + * How a keyform channel is ADDRESSED: an entity plus one of its channels. + * + * In :runtime rather than :edit because it is vocabulary about the model, not about editing - the renderer + * needs it too, to accept per-channel overrides for a value the user has typed but not yet keyed, and + * :render depends on :runtime but not on :edit. + */ + +/** + * The entity a keyform channel belongs to. + * + * Its own taxonomy rather than [SelectionTarget] because a glue is keyable but not selectable, and a glue + * carries no id - it is addressed by the mesh pair it welds, which is stable across edits in a way a list + * index is not. + */ +sealed interface KeyformOwner { + /** A textured drawable mesh. */ + data class Drawable(val id: DrawableId) : KeyformOwner + + /** An organizational tree part. */ + data class Part(val id: PartId) : KeyformOwner + + /** A warp or rotation deformer. */ + data class Deformer(val id: DeformerId) : KeyformOwner + + /** A glue affecter, addressed by the pair of meshes it welds. */ + data class Glue(val meshA: DrawableId, val meshB: DrawableId) : KeyformOwner +} + +/** + * One keyable property: an entity and one of its channels. + * + * This is what a keyform insert aims at, and what the properties panel and the keyform sheet both resolve + * a hover or a click into. + * + * @property KeyformOwner owner The entity. + * @property FormChannel channel The channel on it. + */ +data class KeyableTarget( + val owner: KeyformOwner, + val channel: FormChannel, +) + +/** + * One keyform TRACK: an entity's geometry, or one of its channels. + * + * The sheet edits both with the same three gestures (drag a key, insert one, remove one), so it addresses + * them through one type rather than branching per gesture. They stay distinct cases rather than folding + * geometry into [FormChannel] because geometry is a separate typed field on every owner precisely so a + * scalar track can never reach the delta-texture builder - a GEOMETRY channel constant would undo that. + */ +sealed interface KeyformTrackRef { + /** The entity the track belongs to. */ + val owner: KeyformOwner + + /** A channel track, holding [ChannelValue] cells. */ + data class Channel(val target: KeyableTarget) : KeyformTrackRef { + override val owner: KeyformOwner get() = target.owner + } + + /** The owner's geometry track, holding whichever form type that owner deforms with. */ + data class Geometry(override val owner: KeyformOwner) : KeyformTrackRef +} + +/** + * This model's channel tracks for [owner], or null when it has no such entity. + * + * Public and here rather than private in an editing file because both the edit ops and the UI's keyed-field + * tinting need it, and two copies of an owner dispatch is exactly how the two drift. + * + * @param KeyformOwner owner The entity to look up. + * @return ChannelGrids? Its tracks, or null when the entity is absent. + */ +fun PuppetModel.channelGridsOf(owner: KeyformOwner): ChannelGrids? = + when (owner) { + is KeyformOwner.Drawable -> drawables.firstOrNull { it.id == owner.id }?.channelGrids + is KeyformOwner.Part -> parts.firstOrNull { it.id == owner.id }?.channelGrids + is KeyformOwner.Deformer -> deformers.firstOrNull { it.id == owner.id }?.channelGrids + is KeyformOwner.Glue -> glues.firstOrNull { it.meshA == owner.meshA && it.meshB == owner.meshB }?.channelGrids + } \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/KeyformGrid.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/KeyformGrid.kt new file mode 100644 index 0000000..1a45763 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/KeyformGrid.kt @@ -0,0 +1,153 @@ +package org.umamo.runtime.model + +/** + * One axis of a keyform grid: the parameter it keys on and the key values along it (the parameter + * values where keyforms exist, e.g. `[-1, 0, 1]`). + */ +class KeyformAxis( + val parameterId: ParameterId, + val keys: FloatArray, +) + +/** + * A single keyform cell: its N-D [coordinate] (key index per axis, in [KeyformGrid.axes] order) and + * the deformation [form] captured at that parameter combination. + */ +class KeyformCell( + val coordinate: IntArray, + val form: TForm, +) + +/** + * The keyform grid for one controllable entity (drawable / deformer): the [axes] (one parameter each) + * and the keyed [cells]. `cells.size == Π(axis key counts)` - the "interpolation" count the editor + * reports. Cells are tagged with their coordinate rather than stored row-major, so the evaluator + * can build whatever lookup the deformation math needs. + */ +class KeyformGrid( + val axes: List, + val cells: List>, +) { + /** + * This grid's per-axis strides for folding a coordinate into a linear cell index. + * + * Axis 0 is the FASTEST varying (stride 1). The resulting index is the shared contract between a + * WeightedCell, a stored cell, and the GPU delta texture's column - defined HERE, on the type that + * owns it, so the evaluator, the shape queries, and the grid algebra cannot drift apart. + * + * @return IntArray One stride per axis, in axis order. + */ + fun strides(): IntArray { + val strides = IntArray(axes.size) + var stride = 1 + for (axisIndex in axes.indices) { + strides[axisIndex] = stride + stride *= axes[axisIndex].keys.size + } + return strides + } + + /** + * Folds a per-axis key-index [coordinate] into this grid's linear cell index. + * + * A coordinate shorter than the axis list contributes only the axes it covers, matching the + * defensive handling of a malformed imported cell. + * + * @param IntArray coordinate The key index per axis, in axis order. + * @return Int The stride-folded linear index. + */ + fun linearIndexOf(coordinate: IntArray): Int { + val strides = strides() + var linearIndex = 0 + val axisCount = minOf(coordinate.size, strides.size) + for (axisIndex in 0 until axisCount) { + linearIndex += coordinate[axisIndex] * strides[axisIndex] + } + return linearIndex + } + + /** + * The cells indexed by their stride-folded linear index, built on first use and cached. + * + * Cached because the grid is immutable and the per-frame evaluator once rebuilt this map on every + * channel sample of every entity - hundreds of transient HashMaps per scrub frame on a corpus rig. + * PUBLICATION mode: a racing first read may compute twice but never blocks, and the render thread + * must never take a lock. + */ + val cellsByLinearIndex: Map> by lazy(LazyThreadSafetyMode.PUBLICATION) { + val byIndex = HashMap>(cells.size) + for (cell in cells) { + byIndex[linearIndexOf(cell.coordinate)] = cell + } + byIndex + } +} + +/** + * A drawable keyform: per-vertex position deltas (interleaved x,y) relative to the mesh base + * (`p = base + Σ wᵢ·Δᵢ`, stored as deltas to match the GPU vertex-shader morph), plus the animatable + * scalars that ride on the same keyform. [drawOrder] (Cubism default 500) is the primary render-order + * sort key; [opacity] (0..1) scales the drawable's alpha; [multiplyColor] / [screenColor] tint the + * drawable per the Cubism per-art-mesh color (CMO3 `CArtMeshForm.multiplyColor`/`screenColor`, MOC3 + * color-table rows 108-113), left at their identities on pre-5.3 sources. All blend with the same + * multilinear weights as the positions. + */ +class MeshForm( + val positionDeltas: FloatArray, + // Defaults are Cubism's own (drawOrder 500, fully opaque, identity tints); the CMO3 importer always + // sets them explicitly, so the defaults only serve geometry-only unit tests that don't exercise these. + val drawOrder: Float = DEFAULT_DRAW_ORDER.toFloat(), + val opacity: Float = 1f, + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, +) + +/** + * A part keyform: the animatable per-cell channels of a part, riding the part's own keyform grid. + * [drawOrder] positions a grouped part's stacking slot (Cubism `CPartForm.drawOrder`); the + * remaining channels are the layer composite's keyformed state ([opacity], [multiplyColor], + * [screenColor] - CMO3 `CPartForm.opacity`/`multiplyColor`/`screenColor`, MOC3 §5.6 section 161 + + * the color-table offscreen prefix rows), meaningful only when the part's group mode is Isolated + * and left at their identities otherwise. + */ +class PartForm( + val drawOrder: Float, + val opacity: Float = 1f, + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, +) + +/** + * A warp-deformer keyform: the absolute FFD control-point positions (interleaved x,y). Warp + * sources carry no separate rest lattice, so the forms are kept absolute; the evaluator interpolates + * them directly. + * + * [opacity] / [multiplyColor] / [screenColor] are the deformer's own render channels, which CASCADE + * down the deformer chain onto every drawable underneath (see `DeformerCascade`). Riggers use the + * opacity as a parameter-driven subtree show/hide switch, so dropping it renders whole effect + * subtrees permanently visible. (CMO3 `ACDeformerForm.opacity`/`multiplyColor`/`screenColor`; + * MOC3 `WarpKeyform`.) A deformer has no draw order - that is a drawable/part concept. + */ +class WarpForm( + val controlPoints: FloatArray, + val opacity: Float = 1f, + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, +) + +/** + * A rotation-deformer keyform: the absolute pivot transform captured at this grid cell, plus the + * same cascading render channels a [WarpForm] carries. + */ +class RotationForm( + val originX: Float, + val originY: Float, + val angle: Float, + val scale: Float, + /** Reflection flags (the Umamo C++ Runtime snaps these per grid cell into the affine's flipX/flipY). */ + val flipX: Boolean, + val flipY: Boolean, + val opacity: Float = 1f, + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, +) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Keyforms.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Keyforms.kt new file mode 100644 index 0000000..1512d8a --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/Keyforms.kt @@ -0,0 +1,105 @@ +package org.umamo.runtime.model + +/** + * The two parameter kinds Cubism distinguishes: a NORMAL parameter drives keyform-grid + * interpolation (circle points on the slider); a BLEND_SHAPE parameter drives additive + * [BlendShapeBinding] deltas (square points). + * + * CMO3: CParameterSource field paramType (NORMAL | MORPH_TARGET). MOC3 v4+: Parameter types, + * section index 114 (0 normal, 1 blend-shape). + */ +enum class ParameterKind { + NORMAL, + BLEND_SHAPE, +} + +/** + * An animation axis, e.g. `ParamAngleX`. Drives keyform blending at runtime. + * + * [id] is the format-level identifier (`ParamAngleX`, …) - kept verbatim for interop, never + * localised. [name] is the user-facing display name (the editor's `cdi3`-style label), free to + * localise. + */ +data class Parameter( + val id: ParameterId, + val name: String, + val min: Float, + val max: Float, + val default: Float, + val kind: ParameterKind = ParameterKind.NORMAL, + /** + * Whether the axis WRAPS at its limits instead of clamping - a value past [max] re-enters at [min]. + * + * Used for continuously-cycling rigs (a spinning wheel, a looping tail). MOC3 §5.5 s54. The + * evaluator does not honor it yet, so it feeds the runtime-target feature scan and MOC3 + * round-trip fidelity rather than driving deformation. + */ + val repeat: Boolean = false, +) + +/** + * A LINKED ("combined") pair of parameters that the editor presents as a single 2D pad instead of two + * independent sliders - e.g. head "Angle X" + "Angle Y" shown as one grid control. [horizontal] drives + * the X axis (Cubism's first/topmost member of the pair), [vertical] drives the Y axis (the next member + * in document order). Both remain ordinary, independently-keyable [Parameter]s; this record only states + * that they should be scrubbed together as a 2D unit. + * + * @property ParameterId horizontal The X-axis parameter (the pair's first/topmost member). + * @property ParameterId vertical The Y-axis parameter (the pair's second/bottommost member). + */ +data class ParameterLink( + val horizontal: ParameterId, + val vertical: ParameterId, +) + +/** + * One node of the parameter-panel group tree - Cubism's "CParameterGroup" organisation, the + * collapsible groups the editor sorts parameters into. A node is either a leaf [Param] (one + * parameter axis) or a [Group] (a named group holding ordered child nodes, which may nest). The + * tree records panel layout only; the flat [Parameter] list remains the authoritative source of axes + * (live values, ranges, links). A model with no groups has an empty tree, and callers fall back to + * rendering the flat list. + */ +sealed interface ParameterNode { + /** + * A leaf node binding one parameter axis into the panel tree by its id. + * + * @property ParameterId id The parameter this leaf represents. + */ + data class Param(val id: ParameterId) : ParameterNode + + /** + * A named group of parameters, holding its [children] in editor panel order; groups may nest. + * + * @property ParameterGroupId id The group's stable identifier (display names are not unique). + * @property String name The group's display label (user data - never localised). + * @property Boolean initiallyOpen The editor's saved expanded state (CMO3 folderIsOpened). + * @property List children The ordered child nodes (parameters and/or nested groups). + */ + data class Group( + val id: ParameterGroupId, + val name: String, + val initiallyOpen: Boolean, + val children: List, + ) : ParameterNode +} + +/** + * A captured delta at a specific parameter value. The runtime blends across the N-D grid of + * keyforms: `p = base + Σ wᵢ·Δᵢ` (multilinear interpolation). Weights are cheap and computed + * CPU-side per frame; the per-vertex delta-sum runs in the vertex shader (see `:render`). + */ +data class Keyform( + val atValue: Float, + val delta: FloatArray, +) { + // data class with an array field: generated equals/hashCode use referential array equality, + // which is wrong for value semantics. Override so two keyforms with equal deltas compare equal. + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is Keyform) return false + return atValue == other.atValue && delta.contentEquals(other.delta) + } + + override fun hashCode(): Int = 31 * atValue.hashCode() + delta.contentHashCode() +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/OriginRelativeCoordinates.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/OriginRelativeCoordinates.kt new file mode 100644 index 0000000..e0f6804 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/OriginRelativeCoordinates.kt @@ -0,0 +1,110 @@ +package org.umamo.runtime.model + +/* + * The rigger's coordinate frame. Every X or Z the rigger reads or types is measured from the world axes: + * (0, 0) is where the viewport's axis lines cross, the world origin, with X+ right and Z+ up. + * + * World space itself does not move. Its zero stays at the canvas's top-left corner (canvas x, negated + * canvas y), because the evaluator, the renderer, every importer and exporter, UMA, and every undo snapshot + * share it, and the rigger would see no difference if it were re-based. Only the numbers that cross the + * display boundary convert, through these helpers, and nothing shows a raw world coordinate. + * + * The Origin fields are the one reading that cannot be measured from the origin, because they place it. + * They are measured on the canvas instead, from its bottom-left corner with Z up, so they count the same + * direction as every other number. + * + * World z already grows upward, so the panel's Z is world z with only the origin subtracted - no sign flip. + */ + +/** + * The origin-relative X of a world x: how far right of the world axes it sits. + * + * @param Float worldX A world-space x. + * @return Float The X the rigger reads. + */ +fun PuppetModel.originRelativeX(worldX: Float): Float = worldX - worldOriginX + +/** + * The origin-relative Z of a world z: how far above the world axes it sits. + * + * @param Float worldZ A world-space z (grows upward). + * @return Float The Z the rigger reads. + */ +fun PuppetModel.originRelativeZ(worldZ: Float): Float = worldZ - worldOriginZ + +/** + * The world x of an origin-relative X - the inverse of [originRelativeX]. + * + * @param Float originRelativeX An X measured from the world axes. + * @return Float The world-space x. + */ +fun PuppetModel.worldXFromOriginRelative(originRelativeX: Float): Float = originRelativeX + worldOriginX + +/** + * The world z of an origin-relative Z - the inverse of [originRelativeZ]. + * + * @param Float originRelativeZ A Z measured from the world axes. + * @return Float The world-space z. + */ +fun PuppetModel.worldZFromOriginRelative(originRelativeZ: Float): Float = originRelativeZ + worldOriginZ + +/** + * How far the world origin sits from the canvas's left edge, in canvas pixels - the Origin X reading. + * + * @return Float The origin's distance from the canvas's left edge. + */ +fun PuppetModel.originFromCanvasLeft(): Float = worldOriginX + +/** + * How far the world origin sits above the canvas's bottom edge, in canvas pixels - the Origin Z reading. + * + * The canvas grows and shrinks at its bottom edge while the origin keeps its world point, so a canvas height + * change moves this reading by the same amount. With no canvas (height 0) it is the raw world z. + * + * @return Float The origin's height above the canvas's bottom edge. + */ +fun PuppetModel.originFromCanvasBottom(): Float = worldOriginZ + canvasHeight + +/** + * The world-origin x for an Origin X reading - the inverse of [originFromCanvasLeft]. The canvas's left edge + * is world x 0, so this is the identity; it exists so both Origin rows convert the same way. + * + * @param Float fromCanvasLeft The origin's distance from the canvas's left edge. + * @return Float The world-origin x to store. + */ +fun PuppetModel.worldOriginXFromCanvasLeft(fromCanvasLeft: Float): Float = fromCanvasLeft + +/** + * The world-origin z for an Origin Z reading - the inverse of [originFromCanvasBottom]. + * + * @param Float fromCanvasBottom The origin's height above the canvas's bottom edge. + * @return Float The world-origin z to store. + */ +fun PuppetModel.worldOriginZFromCanvasBottom(fromCanvasBottom: Float): Float = fromCanvasBottom - canvasHeight + +/** + * The world-origin x of a canvas's center - the default origin every importer and a new document derive. + * + * @param Float canvasWidth The canvas width, in canvas pixels. + * @return Float The world-origin x. + */ +fun canvasCenterWorldOriginX(canvasWidth: Float): Float = canvasWidth / 2f + +/** + * The world-origin z of a canvas's center - the default origin every importer and a new document derive. + * The center is half the height down from the canvas's top edge, and world z is the negated canvas y. + * + * @param Float canvasHeight The canvas height, in canvas pixels. + * @return Float The world-origin z. + */ +fun canvasCenterWorldOriginZ(canvasHeight: Float): Float = -(canvasHeight / 2f) + +/** + * Whether the world origin sits exactly on the canvas center, the default [canvasCenterWorldOriginX] and + * [canvasCenterWorldOriginZ] derive. A CMO3 stores no authored origin and its import derives the center, so + * only a centered origin survives a CMO3 round trip. + * + * @return Boolean True when the origin is the canvas center. + */ +fun PuppetModel.isOriginAtCanvasCenter(): Boolean = + worldOriginX == canvasCenterWorldOriginX(canvasWidth) && worldOriginZ == canvasCenterWorldOriginZ(canvasHeight) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PartGroupMode.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PartGroupMode.kt new file mode 100644 index 0000000..fbda084 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PartGroupMode.kt @@ -0,0 +1,69 @@ +package org.umamo.runtime.model + +/** + * How a part groups its subtree for rendering. Three levels of one grouping mode - Cubism models + * these as two entangled checkboxes ("Group by Draw Order" and "offscreen drawing", the latter + * forcing the former on); Umamo folds them into a single sealed type so the illegal combination is + * unrepresentable and the Cubism naming stops at the CMO3/MOC3 import boundary. + */ +sealed interface PartGroupMode { + /** + * Transparent to draw order - the subtree's drawables stack individually with the enclosing + * group's. (Cubism: both checkboxes off.) + */ + data object PassThrough : PartGroupMode + + /** + * The whole subtree takes one slot in the parent's stacking and orders internally among + * itself. (Cubism "Group by Draw Order"; CMO3 CPartSource.enableDrawOrderGroup.) + */ + data object Grouped : PartGroupMode + + /** + * Grouped, and additionally rendered to its own layer and composited back into the scene as one + * unit per the part's [Part.composite] settings. Payload-free: the compositing settings live on the + * part (latent), not on the mode, so they survive the part leaving and re-entering Isolated. (Cubism + * 5.3 "offscreen drawing"; CMO3 CPartSource.useOffscreen; MOC3 §5.6 sections 152-163.) + */ + data object Isolated : PartGroupMode +} + +/** + * A part's latent compositing settings: how the subtree's rendered layer blends back into the scene + * when the part's group mode is [PartGroupMode.Isolated]. Stored on [Part.composite] independent of the + * mode, so the settings survive the part leaving and re-entering Isolated (and the UMA native format can + * track them). The keyformed composite channels (opacity, multiply/screen colors) ride the part's + * [Part.channelGrids]; the static fallbacks here apply when that grid is absent, mirroring the + * [Part.drawOrder] + grid pattern. (Cubism 5.3 "offscreen drawing" - CMO3 + * `CPartSource.useOffscreen` and friends; MOC3 §5.6 sections 152-163.) + */ +data class PartComposite( + /** The composite's color blend mode. (CMO3 colorComposition; MOC3 s157 colorMode.) */ + val blendMode: BlendMode = BlendMode.Normal, + /** The composite's alpha blend mode. (CMO3 alphaComposition; MOC3 s157 alphaMode.) */ + val alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over, + /** + * Drawables whose alpha clips the whole composite (Cubism clipping masks at the part level). + * Always drawables - a part chosen as Clipping ID in the editor is expanded to its constituent + * drawables at authoring time. (CMO3 clipGuidList; MOC3 offscreen mask prefix.) + */ + val maskedBy: List = emptyList(), + /** + * Parts whose descendant drawables also clip the composite - an Umamo extension over the Cubism data + * model, which stores only drawable ids. Keeping the part reference (rather than expanding it at + * authoring time, as Cubism does) means the mask follows the part as its children change. The render + * tree sees the expansion, never these ids: [PuppetModel.deriveRenderRoot] resolves each part to its + * descendant drawables and merges them into [maskedBy] for the [RenderGroup] it builds, so the stored + * value keeps the grouping for the UI while the renderer stays drawable-only. A CMO3 export flattens + * this away (that format has nowhere to put it); UMA will carry it. + */ + val maskedByParts: List = emptyList(), + /** When true, the clip is inverted - the composite shows outside the [maskedBy] coverage. (CMO3 invertClippingMask; MOC3 offscreen flags bit 3.) */ + val invertMask: Boolean = false, + /** Static composite opacity (0..1) when the part has no keyform grid. (CMO3 CPartForm.opacity; MOC3 s161.) */ + val opacity: Float = 1f, + /** Static multiply color when the part has no keyform grid. (CMO3 CPartForm.multiplyColor.) */ + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + /** Static screen color when the part has no keyform grid. (CMO3 CPartForm.screenColor.) */ + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, +) \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetAtlas.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetAtlas.kt new file mode 100644 index 0000000..b41e228 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetAtlas.kt @@ -0,0 +1,191 @@ +package org.umamo.runtime.model + +/* + * The document's atlas: the pages it packs onto and the tiles packed onto them. + * + * This is the source-to-atlas indirection made explicit. A drawable's uvs address a page, but what + * they MEAN is a position in its source art, and the placement is the only thing that connects the + * two - so a repack that moves pixels around a page must move uvs with them and leave the art mapping + * untouched. Keeping the placement as model state is what lets a repack be an undoable edit and lets + * an export write where the art actually went, rather than both guessing from uvs. + */ + +/** + * One packed page's dimensions. + * + * Pixels are not model state - a page's bytes belong to the document, and hundreds of undo snapshots + * holding them would be ruinous - but the SIZE is, because a placement in page pixels means nothing + * without it and every uv derivation needs it. + * + * @property Int width The page width in pixels. + * @property Int height The page height in pixels. + */ +data class AtlasPage( + val width: Int, + val height: Int, +) + +/** + * One piece of source art the atlas packs: its identity, its size, and where it landed. + * + * A tile is per ARTWORK, not per drawable - several drawables can sample one piece of art, and they all + * move together when it is repacked, which is why the placement lives here and not on the drawable. + * + * A null [placement] means the art is in the document but was never packed onto a page; drawables + * bound to it sample it directly and their uvs already address it. + * + * A [pinned] tile is one a rigger placed by hand and wants kept: a repack packs the other tiles + * around it and leaves its placement - page, position, rotation, and scale - exactly as it is. + * Record data, not editor state: it changes what a repack produces, so it persists on the tile in a + * `.uma` (docs/format/UMA.md § 5.4). CMO3 and MOC3 have nowhere to hold it, so the model diff + * ignores it and an export never sees it. A tile without a placement is never pinned - there is + * nothing to keep. + * + * @property AtlasTileId id The tile's stable document-local identity. + * @property String name The tile's display name. + * @property Int width The art's width in pixels. + * @property Int height The art's height in pixels. + * @property AtlasPlacement? placement Where it sits on its page, or null when it was never packed. + * @property SourceLayerRef? source The source layer this tile's art came from - the artwork file + * and the layer key within it - or null when the document retains no binding (a MOC3-origin rig; + * a CMO3-origin one recovers a name-keyed ref from its image chain). Editor and native-format + * data: no container format encodes it, the model diff reads it as tile metadata, and an export + * never sees it. + * @property Boolean pinned Whether a repack keeps this tile's placement where it is. + * @property AtlasTileId? replaces The tile this one superseded when its source layer was reloaded, + * or null for a tile born at import. A tile's pixels are immutable: reloading a layer mints a new + * tile (id `~`, see [reloadTileId]) so the old tile and its pixels stay addressable for undo, + * and this is the lineage a consumer keyed on the ORIGINAL tile follows - a CMO3 export resolves the + * reloaded tile to the model image its root imported from. Editor and native-format data, like [source]. + */ +data class AtlasTile( + val id: AtlasTileId, + val name: String, + val width: Int, + val height: Int, + val placement: AtlasPlacement? = null, + val source: SourceLayerRef? = null, + val pinned: Boolean = false, + val replaces: AtlasTileId? = null, +) + +/** The separator between a reloaded tile's root id and its revision number. */ +private const val TILE_REVISION_SEPARATOR = '~' + +/** + * The id this tile's lineage started from: the id before any `~` revision suffix, or the id itself + * for a tile born at import. Readable from the id alone, so a consumer holding only the id (the CMO3 + * export's model-image web) needs no tile lookup. + */ +val AtlasTileId.lineageRoot: AtlasTileId + get() { + val separator = raw.lastIndexOf(TILE_REVISION_SEPARATOR) + if (separator <= 0 || raw.substring(separator + 1).toIntOrNull() == null) { + return this + } + return AtlasTileId(raw.substring(0, separator)) + } + +/** + * The revision a tile id carries: 0 for a tile born at import, n for the n-th reload of its lineage. + */ +val AtlasTileId.revision: Int + get() { + val separator = raw.lastIndexOf(TILE_REVISION_SEPARATOR) + if (separator <= 0) { + return 0 + } + return raw.substring(separator + 1).toIntOrNull() ?: 0 + } + +/** + * The id the next reload of [previous]'s lineage mints: the lineage root with the revision after + * [previous]'s, skipping any id [taken] already holds so a lineage can never collide with a tile the + * document happens to name that way. + * + * @param AtlasTileId previous The tile being superseded. + * @param Set taken Every tile id the document has. + * @return AtlasTileId The new tile's id. + */ +fun reloadTileId(previous: AtlasTileId, taken: Set): AtlasTileId { + val root = previous.lineageRoot + var revision = previous.revision + 1 + while (true) { + val candidate = AtlasTileId("${root.raw}$TILE_REVISION_SEPARATOR$revision") + if (candidate !in taken) { + return candidate + } + revision++ + } +} + +/** + * The policy the atlas's pages are composed under: which alpha counts as opaque when a tile is + * trimmed to its content, and how far each tile's edge color is bled, at zero alpha, into the gutter + * around it. + * + * Model state because the pages are DERIVED state. A placement records only where a tile's art + * sits, not which opaque sub-rectangle the packer trimmed it to or how wide a band it extruded, so a + * derivation re-runs both on the same pixels and must do so under the policy the pack used - held + * here, beside the placements, so an undo across a repack that changed the threshold re-derives the + * pages that repack composed rather than the current default's. Options that only decide WHERE + * tiles land (gutter, rotation, page shape) leave no trace here: the placements are their record. + * + * The defaults match the packer's own defaults; this module cannot see the packer, so the two are + * kept equal by the derivation gate that composes a pack's pages back from a lowered model. + * + * @property Int alphaThreshold Minimum alpha byte (1..255) for a pixel to count as opaque when trimming. + * @property Int extrude How many pixels of each tile's edge color are bled outward, at zero alpha. + */ +data class AtlasComposition( + val alphaThreshold: Int = 1, + val extrude: Int = 2, +) { + init { + require(alphaThreshold in 1..255) { "alphaThreshold must be in 1..255: $alphaThreshold" } + require(extrude >= 0) { "extrude must be non-negative: $extrude" } + } + + companion object { + /** The policy of an atlas nothing has repacked: the packer's defaults. */ + val Default: AtlasComposition = AtlasComposition() + } +} + +/** + * A document's whole atlas: its pages and the tiles packed onto them. + * + * Empty for a document with no source art at all - a MOC3-origin rig, whose pages are the packed + * endpoint of someone else's pipeline and whose tiles were never separable. + * + * @property List pages The packed pages, in the document's own page order. + * @property List tiles Every piece of source art, in document order. + * @property Boolean storedUvsAddressPages Whether the drawables' stored texture coordinates address the + * packed PAGES rather than the art itself. + * + * A fact about the document, fixed when it was read, and deliberately NOT the display mode: a rigger + * toggling between the artwork and the atlas changes which texture is sampled, never what the stored + * coordinates mean. False for a document saved sampling its per-layer rasters - a packed atlas can + * sit beside it untouched - where the coordinates already address the art and inverting a placement + * over them would throw every mesh clear of its artwork. + * @property AtlasComposition composition The trim and extrusion policy the pages derive under - the one + * the last repack packed with, or the default for an atlas nothing has repacked. + */ +data class PuppetAtlas( + val pages: List = emptyList(), + val tiles: List = emptyList(), + val storedUvsAddressPages: Boolean = true, + val composition: AtlasComposition = AtlasComposition.Default, +) { + /** True when the document carries no source art at all. */ + val isEmpty: Boolean + get() = pages.isEmpty() && tiles.isEmpty() + + /** Tiles by id, for the per-drawable resolution every uv derivation starts from. */ + val tileById: Map by lazy { tiles.associateBy { tile -> tile.id } } + + companion object { + /** The atlas of a document with no source art. */ + val Empty: PuppetAtlas = PuppetAtlas() + } +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetModel.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetModel.kt new file mode 100644 index 0000000..0873886 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetModel.kt @@ -0,0 +1,434 @@ +package org.umamo.runtime.model + +/** + * The whole rig as a concrete, in-memory puppet: what `:runtime` evaluates and the editor renders. + * A parsed `.cmo3` / `.moc3` maps into this; the deformation core depends only on this model, never + * on the format's serialization quirks (that mapping lives in `:interop`). + */ +data class PuppetModel( + val parameters: List, + val parts: List, + val deformers: List, + val drawables: List, + /** + * The organizational tree's top level: sub-parts and drawables interleaved in parts-panel order, the + * same ordered child list as [Part.children]. Single source of truth for top-level structure and + * order; [parts] / [drawables] are flat lookup lists. Draw order derives from this (deriveRenderRoot). + */ + val rootChildren: List, + /** The organizational tree root (the Parts panel's top), or null if the model is flat. */ + val rootPartId: PartId?, + /** Glue affecters - seam-weld pairs of drawables' shared vertices after deformation. */ + val glues: List = emptyList(), + /** + * The draw-order group tree (Cubism's "Group by Draw Order" hierarchy) used to compute render order. A + * group-less model is one flat [RenderGroup]; empty (the default) means "fall back to the flat base order". + */ + val renderRoot: RenderGroup = RenderGroup(null, DEFAULT_DRAW_ORDER, emptyList()), + /** + * LINKED ("combined") parameter pairs - each renders as one 2D pad instead of two sliders. Empty + * (the default) means every parameter is an independent 1D axis. Both members of a link also remain + * in [parameters]; this list only records the X/Y pairing. + */ + val parameterLinks: List = emptyList(), + /** + * The parameter-panel group tree (Cubism's CParameterGroup organisation): the root group's children + * in panel order, each a [ParameterNode.Param] or a (possibly nested) [ParameterNode.Group]. Empty + * (the default) means the model has no groups, so the panel renders the flat [parameters] list. This + * is layout only - every leaf id also appears in [parameters], which stays the authoritative axis list. + */ + val parameterTree: List = emptyList(), + /** + * The document canvas size in world units (canvas px), or 0 when the source carried no canvas. + * Drawable rest positions live in canvas space, with the canvas rect spanning [0, canvasWidth] x + * [0, canvasHeight] (art may overhang it). + */ + val canvasWidth: Float = 0f, + /** The document canvas height in world units; see [canvasWidth]. */ + val canvasHeight: Float = 0f, + /** + * The world origin in WORLD space (the deform eval's output space, canvas x / negated canvas y, whose + * zero is the canvas's top-left corner) - where the viewport's axis lines cross, the anchor for + * origin-relative operations (the 2D cursor's snap home, frame grids), and the zero point of every + * coordinate the rigger reads or types. Never shown raw: the helpers in OriginRelativeCoordinates.kt + * convert at the display boundary. + * + * Imported documents put it at the canvas center. A CMO3 import derives the center rather than reading + * CModelInfo.originInPixels, which is (0, 0) in every corpus model; a MOC3 import reads CanvasInfo's + * origin. (0, 0) when the source carried no canvas. + * + * Axis names follow the viewport's convention, X right, Y forward (depth), and Z up: wherever a name + * says it is world space, its vertical axis is Z (worldOriginZ, Cursor2d.worldZ, screenToWorldZ, + * setWorldOrigin(x, z)). Space-agnostic math keeps x / y - interleaved [x, y] arrays, MeshBounds, deltas, + * the camera's center, GLSL vec2 - as do canvas, screen, UV, and NDC names, and the deform eval's + * pre-negation space, whose y still grows downward. + */ + val worldOriginX: Float = 0f, + /** The world origin's z (up) in world space (negated canvas y); see [worldOriginX]. */ + val worldOriginZ: Float = 0f, + /** + * Pixels per unit is used only for runtime export. It is stored inside of UMA and CMO3, but it is + * not used for anything internal to Umamo. + * + * Canvas pixels per model unit - the scale factor between the source's model space and the world + * space everything here is expressed in - or null when the document has no bake scale of its own. + * + * MOC3 stores geometry in model units around its canvas origin and this factor converts it, so a + * MOC3-origin document carries the value its file recorded. A CMO3 authors directly in canvas + * pixels and its `CModelInfo.pixelsPerUnit` is 1 on every corpus model, which describes the project + * rather than any bake - so a CMO3-origin document carries null and the export picks a default. + * Nothing in the editor or the evaluator reads it - both work purely in world space - but an EXPORT + * cannot invert the import without it: the root-space affine and the scale of every root-path + * rotation deformer both fold it in. + * + * NULLABLE rather than a sentinel because 1 is a legitimate bake scale. Inferring the origin from + * the magnitude instead would rescale a moc whose own scale happens to be 1 by the canvas width. + */ + val pixelsPerUnit: Float? = null, + /** + * The document's runtime-compatibility target; [RuntimeTarget.NoTarget] restricts nothing. Gates + * editing controls only - never rendering or saving. See [RuntimeTarget]. + */ + val runtimeTarget: RuntimeTarget = RuntimeTarget.NoTarget, + /** + * Whether the puppet displays from its SOURCE ARTWORK rather than from the packed atlas pages. + * + * A display choice, but document content: the source formats author it (CMO3 stores it on its + * texture manager) and a rigger's answer to "am I looking at the art or at the pack?" belongs to + * the document, not to the app. Nothing in the evaluator reads it - it selects which texture the + * renderer samples, and false (the atlas) is the default because that is what a document carrying + * no such flag means. + * + * Honoring it is best-effort per drawable: art the document does not retain keeps rendering from + * the atlas, so the puppet stays whole rather than developing holes. + */ + val rendersFromSourceLayers: Boolean = false, + /** + * The document's source art and where it packs onto the atlas pages. + * + * Document content, and authored: a repack moves placements, so they have to undo, diff, and export + * like anything else the rigger changes. Empty for a document with no separable source art - a + * MOC3-origin rig, whose pages arrived already packed. + * + * Pixels are deliberately absent. A page's bytes and a tile's raster belong to the document, which + * loads them once; putting them here would put them in every undo snapshot. + */ + val atlas: PuppetAtlas = PuppetAtlas.Empty, + /** + * The artwork files this document was imported from, each with its layer inventory as of its last + * read - the baseline a re-import diffs against - or empty for a document with no linked source art. + * + * Document content, like the atlas: a re-import rebinds tiles through it, so it undoes and persists + * with the rest of the model. The UMA sources entry encodes it; the diff and every export ignore it. + */ + val sources: List = emptyList(), +) { + /** + * Every part by id, built once per model instance. + * + * The model is immutable, so this cannot go stale, and the pose evaluation runs it every frame - + * rebuilding the map there allocates one entry per part per frame for data that never changes. + * Outside the primary constructor deliberately: it is derived, not state, and must stay out of + * `equals`, `hashCode`, and `copy`. + */ + val partById: Map by lazy { parts.associateBy { part -> part.id } } +} + +/** + * Cubism's neutral draw order: the midpoint of the 0-1000 scale a part's slot and an art mesh's stacking + * both sort on, and what the official editor's Inspector shows for an untouched object. + * + * One constant for both, because it is one number in the format - a drawable's order is merely carried as a + * (keyable, therefore fractional) Float, so the Float sites read it .toFloat() rather than keeping a second + * copy that can drift. + */ +const val DEFAULT_DRAW_ORDER = 500 + +/** + * One ordered child of the organizational tree: a sub-part or a drawable. Cubism's parts panel keeps + * sub-parts and drawables in one interleaved sibling order per level (a loose mesh can sit between two + * folders), and that order is also the draw-order tiebreak. This sealed type is how [Part.children] and + * [PuppetModel.rootChildren] express that single order, instead of splitting parts and drawables apart. + */ +sealed interface OrgChild { + /** + * A sub-part child. + * + * @property PartId id The sub-part. + */ + data class Part(val id: PartId) : OrgChild + + /** + * A drawable child. + * + * @property DrawableId id The drawable. + */ + data class Drawable(val id: DrawableId) : OrgChild +} + +/** A node in the parts tree - the organizational hierarchy shown in the Parts panel. */ +data class Part( + val id: PartId, + val name: String, + /** + * This part's ordered children - sub-parts and drawables interleaved, in parts-panel (top = front) + * order. The single source of truth for the hierarchy AND the panel order at this level; draw order + * derives from it (see [PuppetModel.deriveRenderRoot]). + */ + val children: List, + /** The Parts-panel eyeball: when false, this part and everything under it are hidden (cascades). */ + val isVisible: Boolean = true, + /** A "Guide Image" / sketch part - an editor reference overlay, excluded from runtime (MOC3) export. */ + val isSketch: Boolean = false, + /** + * Blender-style selectable toggle: an unselectable part cannot be picked in the viewport. + * Maps inverted to CMO3's isLocked (Cubism lock = not selectable), which the CMO3 export + * lowering emits as isLocked = !isSelectable. + */ + val isSelectable: Boolean = true, + /** + * How this part groups its subtree for rendering: transparent to draw order (PassThrough), + * one slot in the parent's stacking (Grouped), or composited as one layer (Isolated). + * See [PartGroupMode]. + */ + val groupMode: PartGroupMode = PartGroupMode.PassThrough, + /** + * The part's own draw order (0-1000, default 500) - the sort key for its slot when it is + * grouped or isolated. (CMO3 CPartForm.drawOrder / defaultOrder_forEditor.) + */ + val drawOrder: Int = DEFAULT_DRAW_ORDER, + /** + * The part's per-channel keyform tracks, empty for a fully static part. + * + * [FormChannel.DRAW_ORDER] animates a grouped part's stacking slot per pose, like a drawable's own + * draw order; [FormChannel.OPACITY] and the two color channels key an isolated part's composite. + * Each channel falls back to [drawOrder] / [composite] when it has no track. + */ + val channelGrids: ChannelGrids = ChannelGrids.Empty, + /** + * The part's compositing settings, stored latently regardless of [groupMode] so they survive the + * part leaving and re-entering [PartGroupMode.Isolated] (and so the UMA format can track them). Only + * applied while the part is Isolated - see [activeComposite], the accessor the render pipeline reads. + */ + val composite: PartComposite = PartComposite(), + /** + * Additive blend-shape bindings on this part's channels, applied on top of [channelGrids]; empty + * when the part has none. + * + * A part owns only ONE blendable channel - its draw order - so unlike a drawable or a deformer + * these records carry no geometry and no color. The effect is on stacking: a record can lift a + * grouped part's whole subtree in front of its siblings for the span of a parameter. + */ + val blendShapes: List> = emptyList(), +) { + /** True when this part composites its subtree as one layer. */ + val isIsolated: Boolean + get() = groupMode is PartGroupMode.Isolated + + /** + * The composite to apply when rendering: [composite] while the part is [PartGroupMode.Isolated], else + * null. The single "is this part compositing" signal the render tree keys off (its null-ness decides + * the offscreen-layer boundary), so the latent [composite] of a non-isolated part is never applied. + */ + val activeComposite: PartComposite? + get() = composite.takeIf { isIsolated } +} + +/** + * A textured triangle mesh - the thing actually drawn. Two bindings place it: [partId] (organizational + * tree) and [parentDeformerId] (the deformer chain that deforms it) - these are independent + * hierarchies in Cubism. + */ +data class Drawable( + val id: DrawableId, + /** The user-facing display name (CMO3 localName), e.g. "ArtMesh1"; the id when unnamed. */ + val name: String, + /** The innermost deformer that deforms this drawable, or null if it is undeformed. */ + val parentDeformerId: DeformerId?, + val blendMode: BlendMode, + /** Drawables whose alpha clips this one (Cubism clipping masks). */ + val maskedBy: List, + /** Rest-pose mesh, or null if the source carried no geometry. */ + val mesh: DrawableMesh?, + /** + * Per-parameter morph deltas over the mesh, or null if the drawable is unkeyed. + * + * An unkeyed drawable is a NORMAL state - freshly created, or one whose last keyform axis was + * removed - and renders at its rest mesh rather than vanishing. + */ + val geometryGrid: KeyformGrid?, + /** + * The drawable's per-channel keyform tracks (draw order, opacity, multiply / screen color), each + * falling back to the statics below when it has no track. + */ + val channelGrids: ChannelGrids = ChannelGrids.Empty, + /** Static draw order (Cubism's 500) used when [channelGrids] has no draw-order track. */ + val drawOrder: Float = DEFAULT_DRAW_ORDER.toFloat(), + /** Static opacity used when [channelGrids] has no opacity track. */ + val opacity: Float = 1f, + /** Static multiply color used when [channelGrids] has no multiply track. */ + val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + /** Static screen color used when [channelGrids] has no screen track. */ + val screenColor: ColorRgb = ColorRgb.ScreenIdentity, + /** When true, the clip is inverted - this drawable shows outside the [maskedBy] coverage. */ + val invertMask: Boolean = false, + /** + * How the drawable's alpha combines with the destination (Cubism 5.3); pre-5.3 sources have no + * alpha mode and stay [AlphaBlendMode.Over]. (CMO3 alphaComposition; MOC3 s153 alphaMode.) + */ + val alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over, + /** + * When true, back faces are culled - a mesh flipped inside-out by deformation disappears + * instead of showing mirrored. Default false = double-sided, Cubism's default. (CMO3 culling; + * MOC3 = the INVERSE of drawable constant-flags bit 2, IS_DOUBLE_SIDED.) + */ + val culling: Boolean = false, + /** The drawable's own Parts-panel eyeball; the effective shown-state also folds in ancestor parts. */ + val isVisible: Boolean = true, + /** + * Blender-style selectable toggle: an unselectable drawable cannot be picked in the viewport. + * Maps inverted to CMO3's isLocked (Cubism lock = not selectable), which the CMO3 export + * lowering emits as isLocked = !isSelectable. + */ + val isSelectable: Boolean = true, + /** + * The drawable whose texture-atlas binding this one shares, or null when it binds by its own [id]. + * The atlas page mapping is keyed by the SOURCE format's drawable ids (see PuppetTextures), so a + * session-created copy (Object-mode duplicate) carries its source's id here and the renderer + * resolves the atlas through it; a copy of a copy inherits the original. Editor-only - no source + * format persists it. + */ + val textureSourceId: DrawableId? = null, + /** + * Which atlas page this drawable samples (MOC3 §5.6 s41), or -1 when the source carried none. + * + * Distinct from [textureSourceId], which says WHOSE binding to use; this is the binding itself. + * The renderer does not read it - it resolves pages through the source document's own map, keyed by + * drawable id - but a detached [PuppetModel] otherwise has no texture binding at all, so an export + * could not say which page a drawable belongs to. CMO3 has no equivalent field (it binds through + * the layered-art web instead), so a CMO3-origin drawable leaves this at -1. + */ + val texturePage: Int = -1, + /** + * The atlas tile whose art this drawable samples, or null when the document retains none for it. + * + * Distinct from [texturePage], which names a page in the RENDERER's numbering: this names a piece of + * source art in [PuppetModel.atlas], and the placement on that tile is what says where the art sits + * on its page. A drawable with no tile has no source-art view and renders from the atlas alone. + */ + val atlasTileId: AtlasTileId? = null, + /** + * Additive blend-shape bindings on this drawable's mesh, applied on top of the [geometryGrid] + * result; empty when the drawable has none. (CMO3 keyformMorphTargetSet.) + */ + val blendShapes: List> = emptyList(), +) + +/** + * The drawables that are actually shown, after cascading the Parts-panel visibility toggles: a drawable is + * shown only when its own [Drawable.isVisible] is set and every ancestor part up the tree is visible. + * This is Cubism's editor-preview rule - hiding a folder hides everything inside it (e.g. a hidden + * `[Guide Image]` sketch part hides its art) - and it is static (the eyeball is an authoring toggle, not + * parameter-animated), so callers compute it once. It gates only what is drawn: a hidden drawable that is + * still a mask source or a glue partner must keep being deformed, so apply those gates elsewhere. + * + * @return Set The ids of the drawables to draw. + */ +fun PuppetModel.visibleDrawableIds(): Set { + val partById = parts.associateBy { it.id } + val drawableById = drawables.associateBy { it.id } + val shown = HashSet() + + fun walk(children: List, ancestorsVisible: Boolean) { + for (child in children) { + when (child) { + is OrgChild.Drawable -> { + val drawable = drawableById[child.id] ?: continue + if (ancestorsVisible && drawable.isVisible) { + shown.add(child.id) + } + } + + is OrgChild.Part -> { + val part = partById[child.id] ?: continue + walk(part.children, ancestorsVisible && part.isVisible) + } + } + } + } + walk(rootChildren, ancestorsVisible = true) + return shown +} + +/** + * The owning part of each drawable, derived from the org tree (the drawable's parent in [rootChildren] / + * [Part.children]), or null for a root-level drawable. Since membership lives only in the tree, this is how + * the few sites that need "which part owns this mesh" (the Inspector) read it - computed once per model. + * + * @return Map Drawable id to its owning part id, or null at the root. + */ +fun PuppetModel.partByDrawable(): Map { + val partById = parts.associateBy { it.id } + val owner = HashMap() + + fun walk(children: List, parent: PartId?) { + for (child in children) { + when (child) { + is OrgChild.Drawable -> owner[child.id] = parent + is OrgChild.Part -> partById[child.id]?.let { walk(it.children, child.id) } + } + } + } + walk(rootChildren, parent = null) + return owner +} + +/** + * The first drawable in Parts-panel order (top = front) that can actually be edited: it carries a mesh + * and is shown (its own [Drawable.isVisible] is set and every ancestor part is visible). Edit mode seeds + * onto this when nothing is selected or remembered, so a fresh document lands on the topmost editable mesh + * instead of an inert Edit session. A drawable without a mesh, or a hidden one, leaves the gizmo overlay + * with nothing to draw, so both are skipped. The scan is the same forward pre-order walk of the org tree + * as [visibleDrawableIds], short-circuiting at the first match. Only when the org tree carries no drawable + * at all (a degenerate model with an empty [rootChildren]) does it fall back to a flat scan of [drawables]; + * a populated tree that yields no shown, meshed drawable returns null (nothing editable to seed onto). + * + * @return DrawableId? The topmost editable drawable, or null when the model has none. + */ +fun PuppetModel.firstEditableDrawableInPanelOrder(): DrawableId? { + val partById = parts.associateBy { it.id } + val drawableById = drawables.associateBy { it.id } + + fun walk(children: List, ancestorsVisible: Boolean): DrawableId? { + for (child in children) { + when (child) { + is OrgChild.Drawable -> { + val drawable = drawableById[child.id] ?: continue + if (ancestorsVisible && drawable.isVisible && drawable.mesh != null) { + return child.id + } + } + + is OrgChild.Part -> { + val part = partById[child.id] ?: continue + val found = walk(part.children, ancestorsVisible && part.isVisible) + if (found != null) { + return found + } + } + } + } + return null + } + + val fromTree = walk(rootChildren, ancestorsVisible = true) + if (fromTree != null) { + return fromTree + } + // Degenerate model with no org tree: the visibility cascade has nothing to say, so fall back to the + // flat list (a drawable's own eyeball still gates it). + if (rootChildren.isEmpty()) { + return drawables.firstOrNull { candidate -> candidate.mesh != null && candidate.isVisible }?.id + } + return null +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetModelQueries.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetModelQueries.kt new file mode 100644 index 0000000..48590f7 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/PuppetModelQueries.kt @@ -0,0 +1,356 @@ +package org.umamo.runtime.model + +/* + * Pure per-drawable index queries over a PuppetModel. The picking-oriented queries are shared by + * every platform viewport service (the desktop offscreen renderer today, the Android GLES service + * when it lands): the pickable geometry sets picking iterates, and the display lookups the overlap + * picker labels rows with. The atlas queries resolve a drawable's or tile's source-art binding, the + * same resolution the renderer and UV editor build on. All derive from the model alone, so callers + * recompute them on each model swap. + */ + +/** + * The per-drawable triangle indices picking iterates: the shown, meshed drawables only, so + * unshown / mesh-less drawables are never hit. + * + * @return Map Drawable id to its triangle indices. + */ +fun PuppetModel.pickableIndicesByDrawable(): Map = + visibleDrawableIds().let { shownIds -> + drawables + .filter { drawable -> drawable.id in shownIds } + .mapNotNull { drawable -> + drawable.mesh?.takeIf { it.indices.isNotEmpty() }?.let { drawable.id to it.indices } + } + .toMap() + } + +/** + * The per-drawable full-atlas UVs for the same pickable set as [pickableIndicesByDrawable], so + * picking can interpolate a hit point's UV and sample the atlas alpha. + * + * @return Map Drawable id to its mesh UVs. + */ +fun PuppetModel.pickableUvsByDrawable(): Map = + visibleDrawableIds().let { shownIds -> + drawables + .filter { drawable -> drawable.id in shownIds } + .mapNotNull { drawable -> + drawable.mesh?.takeIf { it.indices.isNotEmpty() }?.let { drawable.id to it.uvs } + } + .toMap() + } + +/** + * Drawable id to owning part name, for the overlap-picker row labels. + * + * @return Map Drawable id to its owning part's name. + */ +fun PuppetModel.partNameByDrawable(): Map = + parts.associate { part -> part.id to part.name }.let { partNameById -> + val ownerByDrawable = partByDrawable() + drawables + .mapNotNull { drawable -> + ownerByDrawable[drawable.id]?.let { partId -> partNameById[partId]?.let { name -> drawable.id to name } } + } + .toMap() + } + +/** + * Drawable id to its own display name, for the overlap-picker row labels. Names are returned as the + * model holds them - a blank one is a display decision the caller makes, not a lookup failure. + * + * @return Map Drawable id to its name. + */ +fun PuppetModel.drawableNameByDrawable(): Map = + drawables.associate { drawable -> drawable.id to drawable.name } + +/** + * Drawable id to the source-format id its atlas region is keyed by: itself, or its texture source for + * a session-created duplicate (a copy of a copy resolves to the original). + * + * @return Map Drawable id to its atlas lookup key. + */ +fun PuppetModel.atlasKeyByDrawable(): Map = + drawables.associate { drawable -> drawable.id to (drawable.textureSourceId ?: drawable.id).raw } + +/** + * How one drawable's stored texture coordinates map back into its source art's own pixel frame. + * + * The single resolution every source-art consumer starts from - the renderer sampling per-layer + * textures, the UV editor drawing a mapping over the artwork - so the tile lookup, the page lookup, and + * the packed-versus-direct decision are made once here rather than reassembled at each call site. + * + * A placement applies only when the document's stored coordinates address the packed pages and this + * tile was actually packed; otherwise the coordinates already address the art and the mapping is the + * identity. The DISPLAY mode is deliberately not consulted - it decides which texture is sampled, not + * what the coordinates mean, and reinterpreting them on a toggle would draw every mesh at its atlas + * position. + * + * @param Drawable drawable The drawable to resolve. + * @return DrawableLayerBinding? The binding, or null when the document retains no art for it. + */ +fun PuppetModel.atlasBindingFor(drawable: Drawable): DrawableLayerBinding? = + drawable.atlasTileId?.let { tileId -> atlasBindingForTile(tileId) } + +/** + * Every drawable sampling each tile, in document order. + * + * The inverse of [Drawable.atlasTileId], and the answer to "how many drawables share this art" - + * duplicated art is common, and a surface offering a tile needs to say what picking it will select. + * + * @return Map> Tile to its drawables; a tile nothing samples is absent. + */ +fun PuppetModel.drawableIdsByAtlasTile(): Map> { + val byTile = LinkedHashMap>() + for (drawable in drawables) { + val tileId = drawable.atlasTileId ?: continue + byTile.getOrPut(tileId) { ArrayList() }.add(drawable.id) + } + return byTile +} + +/** + * How a tile's stored texture coordinates map back into its own pixel frame. + * + * The placement is a property of the TILE, so every drawable over one piece of art shares this binding - + * which is what lets the editor describe a tile's frame without first deciding which of its users to + * ask, and keeps that frame stable as the selection narrows. + * + * @param AtlasTileId tileId The tile to resolve. + * @return DrawableLayerBinding? The binding, or null when the tile is unknown or its page is missing. + */ +fun PuppetModel.atlasBindingForTile(tileId: AtlasTileId): DrawableLayerBinding? = atlas.bindingForTile(tileId) + +/** + * How a tile's stored texture coordinates map back into its own pixel frame, resolved against THIS + * atlas value's pages. + * + * The atlas-level form of [PuppetModel.atlasBindingForTile], for callers holding an atlas that is not + * the model's own - a repack reads a tile's OLD mapping against the current page inventory and its NEW + * one against the replacement inventory, and the page a placement names supplies the normalization, + * so the two reads must not share pages. + * + * @param AtlasTileId tileId The tile to resolve. + * @return DrawableLayerBinding? The binding, or null when the tile is unknown or its page is missing. + */ +fun PuppetAtlas.bindingForTile(tileId: AtlasTileId): DrawableLayerBinding? { + val tile = tileById[tileId] ?: return null + val placement = tile.placement?.takeIf { storedUvsAddressPages } + val page = placement?.let { packed -> pages.getOrNull(packed.pageIndex) } + if (placement != null && page == null) { + // A placement naming a page the document does not have is broken wiring, not a tile that is + // sampled directly - resolving it to the identity would silently draw the wrong frame. + return null + } + return DrawableLayerBinding(tile.id.raw, placement, page?.width ?: 0, page?.height ?: 0) +} + +/** + * The whole stored-uv to art-uv mapping of a tile under this atlas value, as one 2x3 affine - the + * [bindingForTile] resolution folded with the tile's own size through [layerUvAffineOf], so every + * consumer that needs the mapping rather than the binding (a repack's re-derivation, a mesh-reach + * measurement) reads it from one place. + * + * @param AtlasTileId tileId The tile to resolve. + * @return FloatArray? The affine, or null when the binding or the mapping cannot be formed. + */ +fun PuppetAtlas.storedToArtAffineForTile(tileId: AtlasTileId): FloatArray? { + val tile = tileById[tileId] ?: return null + val binding = bindingForTile(tileId) ?: return null + return layerUvAffineOf(binding, tile.width, tile.height) +} + +/** + * Part id to every drawable in its subtree, walking nested parts. The inverse direction of + * [partByDrawable], and the resolution behind a part used as a clip mask ([PartComposite.maskedByParts]): + * masking by a part means masking by all of its descendant drawables, recomputed from the tree so the mask + * follows the part as its children change. A part with no drawables under it maps to an empty list. + * + * @return Map> Part id to its descendant drawables, in tree order. + */ +fun PuppetModel.drawablesByPartSubtree(): Map> { + val partById = parts.associateBy { part -> part.id } + val collected = HashMap>(parts.size) + + fun collect(partId: PartId, guard: MutableSet): List { + collected[partId]?.let { return it } + // A malformed tree could cycle; the guard makes this terminate rather than blow the stack. + if (!guard.add(partId)) { + return emptyList() + } + val part = partById[partId] + val gathered = + if (part == null) { + emptyList() + } else { + val into = ArrayList() + for (child in part.children) { + when (child) { + is OrgChild.Drawable -> into.add(child.id) + is OrgChild.Part -> into.addAll(collect(child.id, guard)) + } + } + into + } + guard.remove(partId) + collected[partId] = gathered + return gathered + } + + for (part in parts) { + collect(part.id, mutableSetOf()) + } + return collected +} + +/** + * Part id to the part that owns it, for the parts nested under another part. A top-level part (one sitting + * in [PuppetModel.rootChildren]) has no entry. Part membership lives only in the org tree - there is no + * back-pointer on [Part] - so this is the part-side counterpart of [partByDrawable], recomputed from the + * child lists. + * + * @return Map Nested part id to its owning part. + */ +fun PuppetModel.parentPartByPart(): Map { + val parentOf = HashMap(parts.size) + for (part in parts) { + for (child in part.children) { + if (child is OrgChild.Part) { + parentOf[child.id] = part.id + } + } + } + return parentOf +} + +/** + * Every part in [id]'s org-tree subtree, including [id] itself. The set a part may NOT be re-homed under - + * doing so would orphan a cycle - so the org-move guard and the Properties picker's candidate filter derive + * from this one definition instead of each walking the tree its own way (they walked it in OPPOSITE + * directions before this existed, which is exactly how two implementations of one invariant drift). + * + * The org tree is the only hierarchy source for parts: a part's children live in [Part.children], and there + * is no parent back-pointer, so this walks DOWN like [deformerSelfAndDescendants] does. + * + * @param PartId id The part whose subtree to collect. + * @return Set The part and every part beneath it. + */ +fun PuppetModel.partSelfAndDescendants(id: PartId): Set { + val partById = parts.associateBy { part -> part.id } + val collected = LinkedHashSet() + + fun walk(current: PartId) { + // add() guards a malformed (already cyclic) tree from recursing forever. + if (!collected.add(current)) { + return + } + partById[current]?.children?.forEach { child -> + if (child is OrgChild.Part) { + walk(child.id) + } + } + } + walk(id) + return collected +} + +/** + * Every deformer in [id]'s nesting subtree, including [id] itself. The set a deformer may NOT be re-nested + * under - doing so would make the hierarchy a cycle - so both the move guard and the Properties picker's + * candidate filter derive from this one definition rather than each rolling their own walk. + * + * @param DeformerId id The deformer whose subtree to collect. + * @return Set The deformer and everything nested beneath it. + */ +fun PuppetModel.deformerSelfAndDescendants(id: DeformerId): Set { + val childrenByParent = deformers.groupBy { deformer -> deformer.parent } + val collected = LinkedHashSet() + + fun walk(current: DeformerId) { + // add() guards a malformed (already cyclic) hierarchy from recursing forever. + if (!collected.add(current)) { + return + } + childrenByParent[current]?.forEach { child -> walk(child.id) } + } + walk(id) + return collected +} + +/** + * A composite's clip masks as ONE flat drawable list: its direct [PartComposite.maskedBy] plus every + * drawable beneath each [PartComposite.maskedByParts] entry, de-duplicated (a drawable masked both + * directly and through an ancestor part counts once). + * + * This is the single definition of "what actually clips this layer". The render tree resolves composites + * through it, and an exporter to a format that cannot express part masks MUST use it too, so the two can + * never disagree about the clipping the user sees. + * + * Takes the part-subtree index rather than building it: both callers resolve MANY composites in one pass, + * and [drawablesByPartSubtree] walks the whole part tree, so building it per composite would make a model + * with K part-masked composites over N parts cost O(K*N) on every render-root derive. Pass + * `drawablesByPartSubtree()` computed once for the batch. + * + * @param PartComposite composite The authored composite. + * @param Map subtrees Each part's descendant drawables, from [drawablesByPartSubtree], built once per batch. + * @return List The effective clip masks, in order. + */ +fun flattenedMasks(composite: PartComposite, subtrees: Map>): List { + if (composite.maskedByParts.isEmpty()) { + return composite.maskedBy + } + val expanded = composite.maskedByParts.flatMap { maskPartId -> subtrees[maskPartId].orEmpty() } + return (composite.maskedBy + expanded).distinct() +} + +/** + * A copy of this model with every part composite's part-masks expanded into plain drawable masks and + * [PartComposite.maskedByParts] emptied - the conversion an export to a drawable-only mask format (CMO3, + * MOC3) MUST apply. + * + * Call it and the clipping SURVIVES the export exactly as the viewport shows it; what is lost is only the + * authoring grouping ("masked by this part", which follows the part as its children change), because those + * formats have nowhere to record it. Skipping this call would instead drop the part masks outright and + * silently change how the model renders - so exporters flatten, never ignore. UMA keeps the grouping and + * needs no flattening. + * + * @return PuppetModel The model with part-masks flattened, or [this] when none are used. + */ +fun PuppetModel.withPartMasksFlattened(): PuppetModel { + if (parts.none { part -> part.composite.maskedByParts.isNotEmpty() }) { + return this + } + // One index for the whole batch (see flattenedMasks). + val subtrees = drawablesByPartSubtree() + val flattened = + parts.map { part -> + val composite = part.composite + if (composite.maskedByParts.isEmpty()) { + part + } else { + part.copy( + composite = composite.copy(maskedBy = flattenedMasks(composite, subtrees), maskedByParts = emptyList()), + ) + } + } + return copy(parts = flattened).withDerivedRenderRoot() +} + +/** + * The drawable's 5.3 per-art-mesh multiply color for display in the Properties panel. + * + * A plain static read now that the tint is its own channel: it used to have to reach into the first + * keyform cell, which was only representative because the editor wrote the color across every cell. + * + * @return ColorRgb The drawable's static multiply color. + */ +fun Drawable.displayMultiplyColor(): ColorRgb = multiplyColor + +/** + * The drawable's 5.3 per-art-mesh screen color for display in the Properties panel; see + * [displayMultiplyColor]. + * + * @return ColorRgb The drawable's screen color, or [ColorRgb.ScreenIdentity] when unkeyed. + */ +fun Drawable.displayScreenColor(): ColorRgb = screenColor \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RenderGroup.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RenderGroup.kt new file mode 100644 index 0000000..d9290a0 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RenderGroup.kt @@ -0,0 +1,39 @@ +package org.umamo.runtime.model + +/** + * A node in the render-order tree - Cubism's draw-order group hierarchy. The model carries this tree so the + * renderer can reproduce the hierarchical render order: a drawable's draw order sorts it only + * among its group siblings, and a "Group by Draw Order" part moves as a unit positioned by the part's + * draw order. A model with no draw-order groups is one flat [RenderGroup] of all drawables - equivalent to a + * global sort (what `paintOrder` does). + */ +sealed interface RenderNode + +/** A drawable leaf; its sort key is its own pose-blended draw order, quantised to an int. */ +data class RenderDrawable(val id: DrawableId) : RenderNode + +/** + * A draw-order group: the implicit root, or a part whose [PartGroupMode] is Grouped or Isolated. Its + * [children] sort among themselves (in [drawOrder]-then-panel order); the group as a whole takes [drawOrder] + * (the part's draw order) as its sort key in its parent, so a child can't escape the group's slot. + * Basically, override the draw order of children of the part. + * + * @param PartId? partId The owning part, or null for the implicit root. + * @param Int drawOrder The part's default-pose draw order - the static fallback sort key. + * @param List children The group's members, in parts-panel (authoring) order. + * @param ChannelGrids channelGrids The owning part's per-channel keyform tracks, copied from the + * part onto the derived render tree. DRAW_ORDER blends per pose + * into the sort key; OPACITY and the color channels feed an + * isolated part's composite. A channel with no track falls back + * to [drawOrder] / [composite]. + * @param PartComposite? composite The owning part's compositing settings, or null when the part + * is not isolated - carried on the render tree so the renderer + * can composite the group's subtree as one layer. + */ +data class RenderGroup( + val partId: PartId?, + val drawOrder: Int, + val children: List, + val channelGrids: ChannelGrids = ChannelGrids.Empty, + val composite: PartComposite? = null, +) : RenderNode \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RenderRootDerive.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RenderRootDerive.kt new file mode 100644 index 0000000..fc89ca4 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RenderRootDerive.kt @@ -0,0 +1,103 @@ +package org.umamo.runtime.model + +/** + * A copy of this model with [PuppetModel.renderRoot] recomputed from the current org tree. Every edit that + * changes the org tree (a move, a delete) ends with this, so draw order stays a consistent derivation of + * the tree rather than something the edit has to maintain by hand. + * + * @return PuppetModel This model with a freshly derived render root. + */ +fun PuppetModel.withDerivedRenderRoot(): PuppetModel = copy(renderRoot = deriveRenderRoot()) + +/** + * Derives the draw-order group tree ([PuppetModel.renderRoot]) from the organizational tree. The org tree + * ([PuppetModel.rootChildren] / [Part.children]) is the single source of truth for hierarchy + panel + * order; draw order is a pure function of it plus the explicit draw-order levers ([Part.groupMode] / + * [Part.drawOrder] / [Part.channelGrids], and each drawable's keyformed draw order). This walks the org + * tree to materialise the structure the renderer consumes, so any org-tree edit yields correct draw order + * by recomputing it - there is no parallel render structure to drift out of sync. + * + * Mirrors Cubism: panel order is top = front, so the render tree (back-to-front) walks each child list + * reversed; a grouped or isolated part becomes a [RenderGroup] boundary (carrying its part draw order + * and grid), a pass-through part is transparent (its children hoist into the enclosing group). A safety + * net appends any drawable the org walk missed, so the render never silently drops a mesh. + * + * @return RenderGroup The derived render-order root. + */ +fun PuppetModel.deriveRenderRoot(): RenderGroup { + val partById = parts.associateBy { it.id } + val drawableIds = drawables.mapTo(HashSet()) { it.id } + + // Parts used as clip masks are an Umamo extension the renderer never sees: expand each to its + // descendant drawables here, so a RenderGroup's composite carries one flat drawable-only mask list. + // Shares flattenedMasks with the export path, so what ships can never clip differently from what the + // viewport shows. Most models mask by drawables alone and short-circuit without walking anything. + // + // The index is built at most once per derive, and only when some composite actually uses part masks - + // building it per composite would cost O(parts * masked composites) on every model mutation. + val maskSubtrees by lazy { drawablesByPartSubtree() } + + fun resolvedComposite(part: Part): PartComposite? { + val composite = part.activeComposite ?: return null + if (composite.maskedByParts.isEmpty()) { + return composite + } + // maskedByParts is CLEARED, not just expanded: PartComposite documents that the render tree sees the + // expansion and never these ids, so leaving them would let any consumer that later honors them apply + // the same drawables twice. + return composite.copy(maskedBy = flattenedMasks(composite, maskSubtrees), maskedByParts = emptyList()) + } + + fun collect(children: List, into: ArrayList) { + // Panel order is top = front; render order is back-to-front, so walk reversed. + for (child in children.asReversed()) { + when (child) { + is OrgChild.Drawable -> + if (child.id in drawableIds) { + into.add(RenderDrawable(child.id)) + } + + is OrgChild.Part -> { + val part = partById[child.id] ?: continue + if (part.groupMode is PartGroupMode.PassThrough) { + collect(part.children, into) // transparent: hoist its children up + } else { + val groupChildren = ArrayList() + collect(part.children, groupChildren) + into.add( + RenderGroup( + part.id, + part.drawOrder, + groupChildren, + part.channelGrids, + resolvedComposite(part), + ), + ) + } + } + } + } + } + + val rootNodes = ArrayList() + collect(rootChildren, rootNodes) + val root = RenderGroup(null, DEFAULT_DRAW_ORDER, rootNodes) + + // Safety net: append any drawable the org walk did not place (e.g. one reachable only under a deformer), + // so the render never silently drops a mesh. + val placed = HashSet() + + fun collectPlaced(node: RenderNode) { + when (node) { + is RenderDrawable -> placed.add(node.id) + is RenderGroup -> node.children.forEach(::collectPlaced) + } + } + collectPlaced(root) + val missing = drawables.map { it.id }.filter { it !in placed }.map { RenderDrawable(it) } + return if (missing.isEmpty()) { + root + } else { + root.copy(children = root.children + missing) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RuntimeFeatureScan.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RuntimeFeatureScan.kt new file mode 100644 index 0000000..cdf4014 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RuntimeFeatureScan.kt @@ -0,0 +1,101 @@ +package org.umamo.runtime.model + +/** + * The restricted features this document ACTUALLY USES under [target] - the decision aid the + * Properties Document tab marks its per-target restricted list with. A feature the target supports + * is never reported, and neither is a restricted feature the document does not use. A MOC3 + * export's own "was removed" notices come from the version-downgrade pass, not from here. + * + * [RuntimeFeature.MotionSync] and [RuntimeFeature.ArtPath] are never reported: they are not + * representable in [PuppetModel] (motion-sync is a sidecar family, an art path survives only as CMO3 + * round-trip payload), so an export dialog cannot warn about them from the model alone. + * + * Latent state does not count as use: a non-isolated part's stored [Part.composite] is invisible + * to both renderer and runtime, so only isolated parts' composites are scanned. + * + * @param RuntimeTarget target The target to diff against. + * @return Set The restricted features in use; empty when the document fits the target. + */ +fun PuppetModel.unsupportedFeaturesInUse(target: RuntimeTarget): Set { + val unsupportedFeatures = RuntimeFeature.entries.filterNot { feature -> target.supports(feature) } + if (unsupportedFeatures.isEmpty()) { + return emptySet() + } + // Materialized once for the whole scan rather than inside every feature branch. + val activeComposites = parts.mapNotNull { part -> part.activeComposite } + return unsupportedFeatures.filterTo(linkedSetOf()) { feature -> usesFeature(feature, activeComposites) } +} + +/** + * Whether the document uses [feature] at all, independent of any target. + * + * @param RuntimeFeature feature The feature to probe for. + * @param List activeComposites The isolated parts' composites, precomputed by the caller. + * @return Boolean True when the feature is present somewhere in the document. + */ +private fun PuppetModel.usesFeature(feature: RuntimeFeature, activeComposites: List): Boolean = + when (feature) { + RuntimeFeature.WarpQuadTransform -> + deformers.any { deformer -> deformer is Deformer.Warp && deformer.isQuadTransform } + + RuntimeFeature.ReversedMask -> + drawables.any { drawable -> drawable.invertMask } || activeComposites.any { composite -> composite.invertMask } + + RuntimeFeature.MeshWarpBlendShapes -> + drawables.any { drawable -> drawable.blendShapes.isNotEmpty() } || + deformers.any { deformer -> deformer is Deformer.Warp && deformer.blendShapes.isNotEmpty() } + + RuntimeFeature.BlendShapeParameters -> + parameters.any { parameter -> parameter.kind == ParameterKind.BLEND_SHAPE } + + RuntimeFeature.MultiplyColor -> usesColorChannel(FormChannel.MULTIPLY_COLOR, ColorRgb.MultiplyIdentity) + + RuntimeFeature.ScreenColor -> usesColorChannel(FormChannel.SCREEN_COLOR, ColorRgb.ScreenIdentity) + + RuntimeFeature.ExtendedBlendShapes -> + deformers.any { deformer -> deformer is Deformer.Rotation && deformer.blendShapes.isNotEmpty() } + + RuntimeFeature.ExtendedBlendModes -> + drawables.any { drawable -> !drawable.blendMode.isLegacy || drawable.alphaBlendMode != AlphaBlendMode.Over } || + activeComposites.any { composite -> !composite.blendMode.isLegacy || composite.alphaBlendMode != AlphaBlendMode.Over } + + RuntimeFeature.PartComposite -> parts.any { part -> part.isIsolated } + + RuntimeFeature.ParameterRepeat -> parameters.any { parameter -> parameter.repeat } + + RuntimeFeature.MotionSync, + RuntimeFeature.ArtPath, + -> false + } + +/** + * Whether any drawable, deformer, or isolated part tints through [channel] - a non-identity static, + * or a keyform track holding some non-identity cell. A track of pure identity cells is not use, so + * the track side goes through [ChannelGrids.varies] rather than a mere presence check. + * + * @param FormChannel channel The color channel (multiply or screen). + * @param ColorRgb identity That channel's identity color (leaves pixels unchanged). + * @return Boolean True when the channel is in use somewhere. + */ +private fun PuppetModel.usesColorChannel(channel: FormChannel, identity: ColorRgb): Boolean { + val isMultiply = channel == FormChannel.MULTIPLY_COLOR + val identityValue = ChannelValue.Color(identity) + val drawableUses = + drawables.any { drawable -> + val staticColor = if (isMultiply) drawable.multiplyColor else drawable.screenColor + staticColor != identity || drawable.channelGrids.varies(channel, identityValue) + } + val deformerUses = + deformers.any { deformer -> + val staticColor = if (isMultiply) deformer.multiplyColor else deformer.screenColor + staticColor != identity || deformer.channelGrids.varies(channel, identityValue) + } + // A part's color track keys its composite, so it only counts while the part is isolated. + val compositeUses = + parts.any { part -> + val composite = part.activeComposite ?: return@any false + val staticColor = if (isMultiply) composite.multiplyColor else composite.screenColor + staticColor != identity || part.channelGrids.varies(channel, identityValue) + } + return drawableUses || deformerUses || compositeUses +} \ No newline at end of file diff --git a/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RuntimeTarget.kt b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RuntimeTarget.kt new file mode 100644 index 0000000..a306482 --- /dev/null +++ b/module/runtime/src/commonMain/kotlin/org/umamo/runtime/model/RuntimeTarget.kt @@ -0,0 +1,165 @@ +package org.umamo.runtime.model + +/** + * The document's runtime-compatibility target: which runtime the rigger intends this puppet to run + * on, selected in Properties > Document > Runtime. + * + * A target gates EDITING CONTROLS ONLY. It never gates rendering (a document whose content already + * exceeds the target keeps rendering everything), never gates saving to the native format or to + * CMO3 (both always carry every feature), and only informs MOC3 export, where it selects the moc + * version and drives the feature-strip confirmation. This mirrors the official editor's own + * "Model target version selection" behavior, which likewise keeps out-of-target data in the file. + * + * Ayagami is a third-party runtime (not an Umamo project) that is effectively Cubism 5.0 + * compatible at present per its maintainer; it has its own entry, rather than aliasing Cubism50, + * so its capabilities can advance independently of the Cubism ladder. + */ +enum class RuntimeTarget( + /** + * The verbatim product name shown in the target dropdown. Cubism entries display this + * directly; NoTarget's phrasing and Ayagami's equivalence parenthetical are chrome, so those + * two resolve through the string catalog instead - with the name "Ayagami" itself kept + * verbatim inside the localized string, and its level fed from [cubismLevelText] so the label + * can never drift from the gating level. + */ + val displayName: String, + /** + * The Cubism feature ceiling as major * 10 + minor (30, 33, 40, 42, 50, 53), or null for no + * ceiling at all. [supports] compares features against this level. + */ + val cubismLevel: Int?, +) { + /** No restriction - every feature Umamo models is authorable. */ + NoTarget("No Target", null), + + /** The Ayagami third-party runtime - effectively Cubism 5.0 at present (see the class docblock). */ + Ayagami("Ayagami", 50), + + Cubism30("Cubism 3.0", 30), + Cubism33("Cubism 3.3", 33), + Cubism40("Cubism 4.0", 40), + Cubism42("Cubism 4.2", 42), + Cubism50("Cubism 5.0", 50), + Cubism53("Cubism 5.3", 53), + ; + + /** + * Whether this target's runtime supports authoring [feature]. + * + * The thresholds follow the official Cubism Editor's "Model target version selection" dialog, + * which is the authority for edit gating even where the MOC3 section table disagrees (the new + * warp method is gated at 3.3 though the WARP_MODE section only exists from moc v3, and the + * reversed mask at 4.0 though its constant-flag bit exists from moc v1) - editor parity is the + * product requirement; the section-level nuances belong to export lowering. + * + * @param RuntimeFeature feature The feature to check. + * @return Boolean True when the feature may be authored under this target. + */ + fun supports(feature: RuntimeFeature): Boolean { + val level = cubismLevel ?: return true + return when (feature) { + RuntimeFeature.WarpQuadTransform -> level >= 33 + RuntimeFeature.ReversedMask -> level >= 40 + RuntimeFeature.MeshWarpBlendShapes, + RuntimeFeature.BlendShapeParameters, + RuntimeFeature.MultiplyColor, + RuntimeFeature.ScreenColor, + -> level >= 42 + RuntimeFeature.ExtendedBlendShapes, + RuntimeFeature.MotionSync, + -> level >= 50 + RuntimeFeature.ExtendedBlendModes, + RuntimeFeature.PartComposite, + RuntimeFeature.ParameterRepeat, + -> level >= 53 + RuntimeFeature.ArtPath -> false + } + } + + /** + * The Cubism ceiling as display text ("5.0"), or null for no ceiling. Derived from + * [cubismLevel] so UI text can never drift from the gating level. + * + * @return String? The version text, or null when this target has no Cubism ceiling. + */ + fun cubismLevelText(): String? { + val level = cubismLevel ?: return null + return "${level / 10}.${level % 10}" + } + + /** + * The features this target restricts, in [RuntimeFeature] declaration (version-tier) order - + * the "unsupported list" the Document > Runtime section shows. Always derived from [supports], + * never a hardcoded per-target list. + * + * @return List The restricted features; empty when nothing is restricted. + */ + fun restrictedFeatures(): List = RuntimeFeature.entries.filterNot { feature -> supports(feature) } +} + +/** + * A version-gated authoring feature - the unit the runtime repository restricts. + * + * Tier source of truth: the official Cubism Editor's "Model target version selection" dialog (its + * restriction list is transcribed per entry below), cross-cited to docs/format/MOC3.md where a moc + * section backs the feature. Entries are declared in ascending version-tier order so + * [RuntimeTarget.restrictedFeatures] lists them oldest-tier first. + * + * Some entries are informational only: Umamo has no authoring surface (or no model representation) + * for them yet, so they appear in the restricted list and, where representable, in + * [unsupportedFeaturesInUse], but gate no control. + * + * Part-typed composite masks ([PartComposite.maskedByParts], an Umamo extension) are deliberately + * NOT a feature here: the part reference decomposes into its descendant drawable ids at the + * CMO3/MOC3 boundary, so the exported result works on every target and there is nothing to + * restrict or strip. + */ +enum class RuntimeFeature { + /** + * The bilinear (quad) warp interpolation mode, [Deformer.Warp.isQuadTransform]. Official + * dialog: "New warp deformer method - SDK3.3/Cubism3.3 or later". (MOC3 §5.6 WARP_MODE s101, + * absent = triangle split.) + */ + WarpQuadTransform, + + /** Inverted clipping, [Drawable.invertMask] / [PartComposite.invertMask]. Official dialog: "Reversed Mask - SDK4.0+". (MOC3 §5.5 constant-flag bit 3.) */ + ReversedMask, + + /** Blend shapes on art meshes and warp deformers. Official dialog: "Blend Shape - SDK4.2+ (Form of ArtMesh and Warp Deformer)". (MOC3 §5.6 blend-shape sections 115-136.) */ + MeshWarpBlendShapes, + + /** Blend-shape parameters ([ParameterKind.BLEND_SHAPE]) - same 4.2 tier as the forms they drive. (MOC3 §5.5 Parameter.Types s114.) */ + BlendShapeParameters, + + /** The multiply tint on drawables, deformers, and composites. Official dialog: "Multiply Color - SDK4.2+". (MOC3 color tables s105-113.) */ + MultiplyColor, + + /** The screen tint on drawables, deformers, and composites. Official dialog: "Screen Color - SDK4.2+". (MOC3 color tables s105-113.) */ + ScreenColor, + + /** + * Blend shapes beyond meshes and warps - parts, rotation deformers, glue, and the scalar + * channels. Official dialog: "Blend Shape - SDK5.0+ (Part, ArtMesh, Warp Deformer, Rotation + * Deformer, Glue)". Only the rotation-deformer slice is modeled in [PuppetModel] today. + */ + ExtendedBlendShapes, + + /** Motion-sync (the motionsync3.json sidecar family). Official dialog: "Motion-sync - SDK5.0+". Informational only - not modeled. */ + MotionSync, + + /** + * The Cubism 5.3 blend-mode family: the 15 non-legacy color modes ([BlendMode.isLegacy] false) + * AND the [AlphaBlendMode] list. Official dialog: "Blend mode - SDK5.3+". (MOC3 §5.6 s153/s157 + * packed blend.) + */ + ExtendedBlendModes, + + /** Offscreen drawing - [PartGroupMode.Isolated] plus [PartComposite]. Official dialog: "Offscreen drawing - SDK5.3+". (MOC3 §5.6 sections 152-163.) */ + PartComposite, + + /** Parameter repeat flags. A 5.3 moc feature (MOC3 §5.5 s54). Informational only - not modeled. */ + ParameterRepeat, + + /** Vector-line art paths. Official dialog: "ArtPath - SDK(N/A)/Latest Cubism only". Informational only - CMO3 round-trip payload, not modeled. */ + ArtPath, +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/eval/ChannelSamplingTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/eval/ChannelSamplingTest.kt new file mode 100644 index 0000000..110ccc2 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/eval/ChannelSamplingTest.kt @@ -0,0 +1,125 @@ +package org.umamo.runtime.eval + +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the per-channel pose sampling: the static fallback (untracked, or out of range - which NEVER + * hides), the override precedence (a pending unkeyed edit wins over both track and static), the + * flag channel's floor-cell snap, and allAxes' flatten across every track. + */ +class ChannelSamplingTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + /** A one-axis track on the given parameter, each cell holding the matching value. */ + private fun track(parameterId: ParameterId, keys: FloatArray, values: List): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(parameterId, keys)), + values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), value) }, + ) + + /** A pose lambda reading angleX only. */ + private fun poseX(value: Float): (ParameterId) -> Float = { parameterId -> if (parameterId == angleX) value else 0f } + + private fun scalarTrack(vararg values: Float): KeyformGrid = + track(angleX, FloatArray(values.size) { keyIndex -> keyIndex.toFloat() }, values.map { value -> ChannelValue.Scalar(value) }) + + /** An untracked channel reads the static, and a tracked one blends its own grid at the pose. */ + @Test + fun scalarAtFallsBackToStaticAndBlendsWhenTracked() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f))) + assertEquals(0.25f, grids.scalarAt(FormChannel.DRAW_ORDER, 0.25f, poseX(0.5f)), "untracked channel reads the static") + assertEquals(1f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(1f)), "on-key pose reads the cell") + assertEquals(0.5f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(0.5f)), "between keys blends") + } + + /** Out of the track's range falls back to the static - keying opacity never hides the art. */ + @Test + fun scalarAtOutOfRangeFallsBackToStatic() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f))) + assertEquals(0.25f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(5f))) + } + + /** A pending scalar override wins over both the track and the static. */ + @Test + fun scalarAtOverrideWinsOverTrackAndStatic() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f))) + val override = ChannelValue.Scalar(0.7f) + assertEquals(0.7f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(1f), override), "override beats the track") + assertEquals(0.7f, grids.scalarAt(FormChannel.DRAW_ORDER, 0.25f, poseX(1f), override), "override beats the static") + } + + /** Color sampling mirrors the scalar precedence, blending per component. */ + @Test + fun colorAtBlendsPerComponentWithSamePrecedence() { + val colorTrack = + track( + angleX, + floatArrayOf(0f, 1f), + listOf(ChannelValue.Color(ColorRgb(0f, 0f, 1f)), ChannelValue.Color(ColorRgb(1f, 0f, 0f))), + ) + val grids = ChannelGrids(mapOf(FormChannel.MULTIPLY_COLOR to colorTrack)) + val staticColor = ColorRgb(0.2f, 0.4f, 0.6f) + assertEquals(staticColor, grids.colorAt(FormChannel.SCREEN_COLOR, staticColor, poseX(0.5f)), "untracked channel reads the static") + assertEquals(ColorRgb(0.5f, 0f, 0.5f), grids.colorAt(FormChannel.MULTIPLY_COLOR, staticColor, poseX(0.5f))) + assertEquals(staticColor, grids.colorAt(FormChannel.MULTIPLY_COLOR, staticColor, poseX(5f)), "out of range falls back") + val override = ChannelValue.Color(ColorRgb(0.9f, 0.9f, 0.9f)) + assertEquals(override.color, grids.colorAt(FormChannel.MULTIPLY_COLOR, staticColor, poseX(0.5f), override)) + } + + /** A flag snaps to the FLOOR cell between keys rather than blending a boolean. */ + @Test + fun flagAtSnapsToTheFloorCell() { + val flagTrack = track(angleX, floatArrayOf(0f, 1f), listOf(ChannelValue.Flag(false), ChannelValue.Flag(true))) + val grids = ChannelGrids(mapOf(FormChannel.FLIP_X to flagTrack)) + assertFalse(grids.flagAt(FormChannel.FLIP_X, true, poseX(0.5f)), "midway reads the lower key's flag") + assertTrue(grids.flagAt(FormChannel.FLIP_X, false, poseX(1f)), "on the upper key reads it exactly") + assertTrue(grids.flagAt(FormChannel.FLIP_Y, true, poseX(0.5f)), "untracked channel reads the static") + assertTrue(grids.flagAt(FormChannel.FLIP_X, true, poseX(5f)), "out of range falls back") + assertTrue(grids.flagAt(FormChannel.FLIP_X, false, poseX(0.5f), ChannelValue.Flag(true)), "override wins") + } + + /** scalarOrNull reports absence itself: untracked and out-of-range are null, override still wins. */ + @Test + fun scalarOrNullDistinguishesAbsenceFromValue() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f))) + assertNull(grids.scalarOrNull(FormChannel.DRAW_ORDER, poseX(0.5f)), "untracked channel is absent") + assertNull(grids.scalarOrNull(FormChannel.OPACITY, poseX(5f)), "out of range is absent") + assertEquals(0.5f, grids.scalarOrNull(FormChannel.OPACITY, poseX(0.5f))) + assertEquals(0.7f, grids.scalarOrNull(FormChannel.DRAW_ORDER, poseX(0.5f), ChannelValue.Scalar(0.7f))) + } + + /** + * allAxes is a FLATTEN in channel order, not a dedupe: two tracks keying the same parameter each + * contribute their own axis, because each track brackets its own keys. + */ + @Test + fun allAxesFlattensEveryTrackAxisInChannelOrder() { + val opacityTrack = scalarTrack(0f, 1f) + val drawOrderTrack = track(angleY, floatArrayOf(-1f, 1f), listOf(ChannelValue.Scalar(400f), ChannelValue.Scalar(600f))) + val glueTrack = track(angleX, floatArrayOf(0f, 2f), listOf(ChannelValue.Scalar(0f), ChannelValue.Scalar(1f))) + val grids = + ChannelGrids( + linkedMapOf( + FormChannel.OPACITY to opacityTrack, + FormChannel.DRAW_ORDER to drawOrderTrack, + FormChannel.GLUE_INTENSITY to glueTrack, + ), + ) + val axes = grids.allAxes() + assertEquals(listOf(angleX, angleY, angleX), axes.map { axis -> axis.parameterId }) + assertEquals(emptyList(), ChannelGrids.Empty.allAxes()) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/eval/KeyformGridSamplingTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/eval/KeyformGridSamplingTest.kt new file mode 100644 index 0000000..d393746 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/eval/KeyformGridSamplingTest.kt @@ -0,0 +1,298 @@ +package org.umamo.runtime.eval + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.RotationPivotForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the pure grid-sampling layer: bindBracket's range/snap contract, gridCorners' multilinear + * corner selection (including the 16-corner budget), and the pose-sampling helpers the renderer's + * evaluator and the MOC3 import both call (meshGridDefaultDeltas, warpControlPointsAt, + * rotationFormAt). + * + * The grid ALGEBRA (seeding, insertion, compaction) is pinned in runtime.keyform; this file pins the + * read side that every other feature blends through. + */ +class KeyformGridSamplingTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + /** A pose lambda over explicit per-parameter values, defaulting unmentioned parameters to zero. */ + private fun pose(vararg values: Pair): (ParameterId) -> Float { + val byId = values.toMap() + return { parameterId -> byId[parameterId] ?: 0f } + } + + /** An axis-only grid (gridCorners reads no cells), each axis holding keys 0..count-1. */ + private fun axisOnlyGrid(vararg axes: Pair): KeyformGrid = + KeyformGrid(axes.map { (parameterId, keys) -> KeyformAxis(parameterId, keys) }, emptyList()) + + /** A value inside the bracket snaps by fraction; assertEquals on floats pins it exactly. */ + @Test + fun bindBracketBetweenKeysReturnsLowerIndexAndFraction() { + val bracket = assertNotNull(bindBracket(floatArrayOf(0f, 1f, 2f), 0.25f)) + assertEquals(0, bracket.index) + assertEquals(0.25f, bracket.fraction) + } + + /** A value landing exactly on an interior key brackets that key with zero fraction. */ + @Test + fun bindBracketExactKeyHitSnapsWithZeroFraction() { + assertEquals(AxisBracket(1, 0f), bindBracket(floatArrayOf(0f, 1f, 2f), 1f)) + } + + /** Out of range hides the entity: below the first key and at/above last-key + EPS_KEY are null. */ + @Test + fun bindBracketOutOfRangeReturnsNull() { + val keys = floatArrayOf(0f, 1f, 2f) + assertNull(bindBracket(keys, -0.5f)) + assertNull(bindBracket(keys, 2.5f)) + assertNull(bindBracket(keys, 2f + EPS_KEY)) + } + + /** Authoring hold clamps past the ends onto the nearest key instead of hiding. */ + @Test + fun gridCornersHoldingClampsPastTheEnds() { + val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f, 2f)) + val pastLast = assertNotNull(gridCornersHolding(grid, pose(angleX to 10f))) + assertEquals(listOf(WeightedCell(2, 1f)), pastLast, "past the last key holds the last slice") + val beforeFirst = assertNotNull(gridCornersHolding(grid, pose(angleX to -10f))) + assertEquals(listOf(WeightedCell(0, 1f)), beforeFirst, "before the first key holds the first slice") + } + + /** Within EPS_KEY of a key the value snaps onto it; just outside it interpolates. */ + @Test + fun bindBracketSnapsOnlyWithinEpsilonOfAKey() { + val keys = floatArrayOf(0f, 1f, 2f) + assertEquals(AxisBracket(1, 0f), bindBracket(keys, 1f + 0.0005f), "inside EPS_KEY snaps") + val outside = assertNotNull(bindBracket(keys, 1f + 0.002f)) + assertEquals(1, outside.index) + assertTrue(outside.fraction > 0f, "outside EPS_KEY interpolates") + } + + /** The snap window extends past the LAST key too, so a slider resting a hair over stays keyed. */ + @Test + fun bindBracketSnapsJustAboveTheLastKey() { + assertEquals(AxisBracket(2, 0f), bindBracket(floatArrayOf(0f, 1f, 2f), 2.0005f)) + } + + /** A single-key axis brackets only within its snap window and hides everywhere else. */ + @Test + fun bindBracketSingleKeyAxisSnapsOrHides() { + assertEquals(AxisBracket(0, 0f), bindBracket(floatArrayOf(0.5f), 0.5f)) + assertNull(bindBracket(floatArrayOf(0.5f), 0.6f)) + } + + /** An axis-less (empty-keys) bracket is the zero bracket - the entity never hides on it. */ + @Test + fun bindBracketEmptyKeysReturnsZeroBracket() { + assertEquals(AxisBracket(0, 0f), bindBracket(floatArrayOf(), 12f)) + } + + /** One fractional axis doubles the corner set; the two weights are the complementary fractions. */ + @Test + fun gridCornersOneFractionalAxisYieldsTwoWeightedCells() { + val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f)) + val corners = assertNotNull(gridCorners(grid, pose(angleX to 0.25f))) + assertEquals(mapOf(0 to 0.75f, 1 to 0.25f), corners.associate { corner -> corner.linearIndex to corner.weight }) + } + + /** Two fractional axes fold to four bilinear corners whose weights multiply and sum to one. */ + @Test + fun gridCornersTwoFractionalAxesYieldFourBilinearCorners() { + val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f), angleY to floatArrayOf(0f, 1f)) + val corners = assertNotNull(gridCorners(grid, pose(angleX to 0.5f, angleY to 0.25f))) + val weightByIndex = corners.associate { corner -> corner.linearIndex to corner.weight } + assertEquals(mapOf(0 to 0.375f, 1 to 0.375f, 2 to 0.125f, 3 to 0.125f), weightByIndex) + assertEquals(1f, corners.map { corner -> corner.weight }.sum()) + } + + /** A pose exactly on every key resolves to the single matching cell at full weight. */ + @Test + fun gridCornersOnKeyPoseYieldsOneFullWeightCell() { + val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f), angleY to floatArrayOf(0f, 1f)) + val corners = assertNotNull(gridCorners(grid, pose(angleX to 1f, angleY to 0f))) + assertEquals(listOf(WeightedCell(1, 1f)), corners) + } + + /** Any single controlling axis out of range hides the whole entity. */ + @Test + fun gridCornersOutOfRangeAxisReturnsNull() { + val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f), angleY to floatArrayOf(0f, 1f)) + assertNull(gridCorners(grid, pose(angleX to 0.5f, angleY to 2f))) + } + + /** + * Past the 16-corner budget an axis snaps to its lower key instead of splitting: five fractional + * two-key axes yield 16 corners (four split), with the fifth axis pinned at key 0 - every linear + * index stays below the fifth axis's stride. + */ + @Test + fun gridCornersFifthFractionalAxisSnapsWithinCornerBudget() { + val parameterIds = (1..5).map { axisNumber -> ParameterId("ParamAxis$axisNumber") } + val grid = + KeyformGrid( + parameterIds.map { parameterId -> KeyformAxis(parameterId, floatArrayOf(0f, 1f)) }, + emptyList(), + ) + val corners = assertNotNull(gridCorners(grid) { 0.5f }) + assertEquals(16, corners.size) + val fifthAxisStride = 16 + assertTrue(corners.all { corner -> corner.linearIndex < fifthAxisStride }, "the snapped axis contributes only its lower key") + assertEquals(1f, corners.map { corner -> corner.weight }.sum()) + } + + /** The exposed cell index is the grid's own cached one, and it round-trips every coordinate. */ + @Test + fun cellsByLinearIndexDelegatesToTheGridAndRoundTripsCoordinates() { + val cells = + listOf( + KeyformCell(intArrayOf(0, 0), WarpLatticeForm(floatArrayOf(0f))), + KeyformCell(intArrayOf(1, 0), WarpLatticeForm(floatArrayOf(1f))), + KeyformCell(intArrayOf(2, 0), WarpLatticeForm(floatArrayOf(2f))), + KeyformCell(intArrayOf(0, 1), WarpLatticeForm(floatArrayOf(3f))), + KeyformCell(intArrayOf(1, 1), WarpLatticeForm(floatArrayOf(4f))), + KeyformCell(intArrayOf(2, 1), WarpLatticeForm(floatArrayOf(5f))), + ) + val grid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f, 2f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))), + cells, + ) + val byIndex = cellsByLinearIndex(grid) + assertSame(grid.cellsByLinearIndex, byIndex) + for (cell in cells) { + assertSame(cell, byIndex[grid.linearIndexOf(cell.coordinate)]) + } + } + + /** A drawable with the given one-axis geometry grid on angleX; the mesh itself is never read. */ + private fun gridded(grid: KeyformGrid?): Drawable = + Drawable( + id = DrawableId("d1"), + name = "d1", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = grid, + ) + + /** An ungridded drawable has no delta reference. */ + @Test + fun meshGridDefaultDeltasUngriddedDrawableReturnsNull() { + assertNull(meshGridDefaultDeltas(gridded(null)) { 0f }) + } + + /** A default pose outside the grid's range has no reference either (the reference is then zero). */ + @Test + fun meshGridDefaultDeltasOutOfRangeDefaultReturnsNull() { + val grid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(2f, 4f))), + ), + ) + assertNull(meshGridDefaultDeltas(gridded(grid)) { 5f }) + } + + /** The reference is the grid form blended at the default pose, sized like a cell's delta array. */ + @Test + fun meshGridDefaultDeltasBlendsAtTheDefaultPose() { + val grid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(2f, 4f))), + ), + ) + val deltas = assertNotNull(meshGridDefaultDeltas(gridded(grid)) { 0.5f }) + assertEquals(listOf(1f, 2f), deltas.toList()) + } + + /** A one-axis warp grid with the given control points per key. */ + private fun warpGrid(vararg controlPointsPerKey: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, FloatArray(controlPointsPerKey.size) { keyIndex -> keyIndex.toFloat() })), + controlPointsPerKey.mapIndexed { keyIndex, points -> KeyformCell(intArrayOf(keyIndex), WarpLatticeForm(points)) }, + ) + + /** An unkeyed warp has no lattice at all. */ + @Test + fun warpControlPointsAtNullGridReturnsNull() { + assertNull(warpControlPointsAt(null, pose())) + } + + /** On a key the lattice is that cell's points exactly; between keys it blends componentwise. */ + @Test + fun warpControlPointsAtBlendsBetweenKeys() { + val grid = warpGrid(floatArrayOf(0f, 10f), floatArrayOf(4f, 30f)) + assertEquals(listOf(0f, 10f), assertNotNull(warpControlPointsAt(grid, pose(angleX to 0f))).toList()) + assertEquals(listOf(2f, 20f), assertNotNull(warpControlPointsAt(grid, pose(angleX to 0.5f))).toList()) + } + + /** Out of range or no resolvable cell both yield null rather than a partial lattice. */ + @Test + fun warpControlPointsAtOutOfRangeOrCellLessReturnsNull() { + val grid = warpGrid(floatArrayOf(0f), floatArrayOf(4f)) + assertNull(warpControlPointsAt(grid, pose(angleX to 9f))) + val cellLess = KeyformGrid(listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), emptyList()) + assertNull(warpControlPointsAt(cellLess, pose(angleX to 0.5f))) + } + + /** A one-axis rotation grid with the given pivot forms per key. */ + private fun rotationGrid(vararg formsPerKey: RotationPivotForm): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, FloatArray(formsPerKey.size) { keyIndex -> keyIndex.toFloat() })), + formsPerKey.mapIndexed { keyIndex, form -> KeyformCell(intArrayOf(keyIndex), form) }, + ) + + /** An unkeyed rotation has no transform. */ + @Test + fun rotationFormAtNullGridReturnsNull() { + assertNull(rotationFormAt(null, pose())) + } + + /** On a key the transform is that cell's exactly; between keys every component lerps. */ + @Test + fun rotationFormAtBlendsBetweenKeys() { + val grid = + rotationGrid( + RotationPivotForm(originX = 0f, originY = 10f, angle = 0f, scale = 1f), + RotationPivotForm(originX = 4f, originY = 30f, angle = 90f, scale = 3f), + ) + val atKey = assertNotNull(rotationFormAt(grid, pose(angleX to 1f))) + assertEquals(4f, atKey.originX) + assertEquals(90f, atKey.angle) + val midway = assertNotNull(rotationFormAt(grid, pose(angleX to 0.5f))) + assertEquals(2f, midway.originX) + assertEquals(20f, midway.originY) + assertEquals(45f, midway.angle) + assertEquals(2f, midway.scale) + } + + /** Out of range or no resolvable cell both yield null rather than an identity transform. */ + @Test + fun rotationFormAtOutOfRangeOrCellLessReturnsNull() { + val grid = rotationGrid(RotationPivotForm(0f, 0f, 0f, 1f)) + assertNull(rotationFormAt(grid, pose(angleX to 9f))) + val cellLess = KeyformGrid(listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), emptyList()) + assertNull(rotationFormAt(cellLess, pose(angleX to 0.5f))) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformCompactionTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformCompactionTest.kt new file mode 100644 index 0000000..b35a3b3 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformCompactionTest.kt @@ -0,0 +1,358 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ChannelValueKind +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins exact-only compaction and, most importantly, that compaction and refinement are MUTUAL INVERSES + * bit-for-bit. + * + * That property is the whole basis for compacting an imported rig: a key is dropped only when the stored + * form is bit-equal to the blend of its neighbours, and refinement restores it by evaluating the very same + * FormInterpolator expression on the very same inputs, so IEEE-754 determinism does the rest. It is a + * theorem about shared code, not about tolerance - which is why this file asserts equality exactly, while + * KeyformGridAlgebraTest's arbitrary key insertion may only assert to a bound. + */ +class KeyformCompactionTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + private fun scalar(value: Float): ChannelValue = ChannelValue.Scalar(value) + + /** A one-axis scalar track on angleX. */ + private fun track(keys: FloatArray, values: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, keys)), + values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), scalar(value)) }, + ) + + /** Every cell's value in linear-index order, so two grids of the same shape compare directly. */ + private fun valuesInIndexOrder(grid: KeyformGrid): List = + (0 until grid.cellCount).map { linearIndex -> + grid.cells.first { cell -> grid.linearIndexOf(cell.coordinate) == linearIndex }.form + } + + /** A track holding one value everywhere collapses to that constant, freeing its owner's static field. */ + @Test + fun aConstantTrackCollapsesToItsValue() { + val result = track(floatArrayOf(-1f, 0f, 1f), floatArrayOf(7f, 7f, 7f)).compacted(ChannelValueInterpolator) + assertEquals(scalar(7f), assertIs>(result).form) + } + + /** A perfectly linear track keeps only its endpoints - the interior keys carry no information. */ + @Test + fun aLinearTrackKeepsOnlyItsEndpoints() { + val result = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50f, 100f)).compacted(ChannelValueInterpolator) + val reduced = assertIs>(result).grid + assertEquals(listOf(0f, 10f), reduced.axes.single().keys.toList()) + } + + /** A key that genuinely bends the curve survives, however slightly it differs from the blend. */ + @Test + fun aBendingKeySurvives() { + val result = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50.0001f, 100f)).compacted(ChannelValueInterpolator) + val reduced = assertIs>(result).grid + assertEquals(listOf(0f, 5f, 10f), reduced.axes.single().keys.toList(), "an exact-only test never rounds a rigger's value away") + } + + /** An axis the track does not respond to is dropped entirely, even when another axis still varies. */ + @Test + fun aConstantAxisIsDropped() { + val axes = listOf(KeyformAxis(angleX, floatArrayOf(0f, 10f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))) + // Varies along angleX, identical along angleY. + val cells = + listOf( + KeyformCell(intArrayOf(0, 0), scalar(0f)), + KeyformCell(intArrayOf(1, 0), scalar(100f)), + KeyformCell(intArrayOf(0, 1), scalar(0f)), + KeyformCell(intArrayOf(1, 1), scalar(100f)), + ) + val result = KeyformGrid(axes, cells).compacted(ChannelValueInterpolator) + val reduced = assertIs>(result).grid + assertEquals(listOf(angleX), reduced.axes.map { axis -> axis.parameterId }) + assertEquals(listOf(scalar(0f), scalar(100f)), valuesInIndexOrder(reduced)) + } + + /** Colors compact per component, so an identity tint across a whole grid becomes one constant. */ + @Test + fun aConstantColorTrackCollapses() { + val grid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f, 2f))), + List(3) { keyIndex -> KeyformCell(intArrayOf(keyIndex), ChannelValue.Color(ColorRgb.MultiplyIdentity)) }, + ) + val result = grid.compacted(ChannelValueInterpolator, ChannelValueKind.COLOR) + assertEquals(ChannelValue.Color(ColorRgb.MultiplyIdentity), assertIs>(result).form) + } + + /** + * A flag track drops constant AXES but never an interior key: a flag snaps to the floor cell instead + * of blending, so "equal to the blend of its neighbours" is not a sound drop test for one. + */ + @Test + fun aFlagTrackKeepsItsInteriorKeys() { + val grid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 5f, 10f))), + listOf>( + KeyformCell(intArrayOf(0), ChannelValue.Flag(false)), + KeyformCell(intArrayOf(1), ChannelValue.Flag(false)), + KeyformCell(intArrayOf(2), ChannelValue.Flag(true)), + ), + ) + val reduced = assertIs>(grid.compacted(ChannelValueInterpolator, ChannelValueKind.FLAG)).grid + assertEquals(listOf(0f, 5f, 10f), reduced.axes.single().keys.toList()) + } + + /** + * Two ADJACENT interpolable keys are the trap the greedy pass falls into: the first key's drop is + * justified against a neighbour that itself drops next, and refinement then rebuilds the first from + * the surviving endpoints - a different IEEE-754 rounding sequence. The values below are a concrete + * float32 case where that direct rebuild differs by an ULP (found by exhaustive search), so this test + * fails against an unverified greedy drop pass. + */ + @Test + fun adjacentInterpolableKeysStayMutualInverses() { + val v0 = scalar(0.102f) + val v3 = scalar(0.1014f) + // Constructed to make the greedy pass drop key 1 (against 0 and 3) and then key 3 (against 0 and 4). + val v2 = ChannelValueInterpolator.interpolate(v0, v3, 0.75f) + val v1 = ChannelValueInterpolator.interpolate(v0, v2, 1f / 3f) + val original = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f, 3f, 4f))), + listOf(v0, v1, v2, v3).mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), value) }, + ) + + val reduced = assertIs>(original.compacted(ChannelValueInterpolator)).grid + val restored = + reduced.refinedToUnion( + mapOf(angleX to original.axes.single().keys), + emptyMap(), + ChannelValueInterpolator, + ) + + assertEquals(listOf(0f, 1f, 3f, 4f), restored.axes.single().keys.toList()) + assertEquals(valuesInIndexOrder(original), valuesInIndexOrder(restored), "every dropped key restores bit-for-bit") + } + + /** + * An axis whose keys do not bracket the parameter's range gates the track's out-of-span fallback to + * the owner's static, so it is never dropped and its track is never lifted to a constant. + */ + @Test + fun aNonSpanningConstantAxisIsNeverDroppedOrLifted() { + val spans: (KeyformAxis) -> Boolean = { axis -> axis.keys.first() <= -1f && axis.keys.last() >= 1f } + + // Constant along a NON-spanning sole axis: kept as-is, because poses below 0.5 read the static. + val gated = track(floatArrayOf(0.5f, 1f), floatArrayOf(0.4f, 0.4f)) + val gatedResult = gated.compacted(ChannelValueInterpolator, axisSpansRange = spans) + assertSame(gated, assertIs>(gatedResult).grid) + + // The same constant on a spanning axis lifts as before. + val spanning = track(floatArrayOf(-1f, 1f), floatArrayOf(0.4f, 0.4f)) + val liftedResult = spanning.compacted(ChannelValueInterpolator, axisSpansRange = spans) + assertEquals(scalar(0.4f), assertIs>(liftedResult).form) + + // Mixed: the spanning constant axis drops, the non-spanning one survives as the gate. + val axes = listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f)), KeyformAxis(angleY, floatArrayOf(0.5f, 1f))) + val cells = + listOf( + KeyformCell(intArrayOf(0, 0), scalar(0.4f)), + KeyformCell(intArrayOf(1, 0), scalar(0.4f)), + KeyformCell(intArrayOf(0, 1), scalar(0.4f)), + KeyformCell(intArrayOf(1, 1), scalar(0.4f)), + ) + val mixedResult = KeyformGrid(axes, cells).compacted(ChannelValueInterpolator, axisSpansRange = spans) + val mixedReduced = assertIs>(mixedResult).grid + assertEquals(listOf(angleY), mixedReduced.axes.map { axis -> axis.parameterId }, "only the gate axis survives") + } + + /** + * The model-level pass derives the spanning gate from the parameter table: a glue keyed constant 0.4 + * on keys [0.5, 1.0] of a -1..1 parameter welds at the 1.0 static fallback below 0.5, so lifting the + * constant would change those poses. The track must survive and the static must keep its value; the + * same constant on a spanning axis lifts as before. + */ + @Test + fun modelCompactionKeepsTheOutOfSpanStaticFallback() { + val gatedTrack = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(0.5f, 1f))), + listOf>( + KeyformCell(intArrayOf(0), scalar(0.4f)), + KeyformCell(intArrayOf(1), scalar(0.4f)), + ), + ) + val spanningTrack = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf>( + KeyformCell(intArrayOf(0), scalar(0.4f)), + KeyformCell(intArrayOf(1), scalar(0.4f)), + ), + ) + val model = + PuppetModel( + parameters = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + glues = + listOf( + Glue(DrawableId("a"), DrawableId("b"), emptyList(), ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to gatedTrack))), + Glue(DrawableId("c"), DrawableId("d"), emptyList(), ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to spanningTrack))), + ), + ) + + val compacted = model.withChannelsCompacted() + + val gated = compacted.glues.first { glue -> glue.meshA == DrawableId("a") } + assertSame(gatedTrack, gated.channelGrids[FormChannel.GLUE_INTENSITY], "the non-spanning track survives untouched") + assertEquals(1f, gated.intensity, "the full-weld fallback below the span keeps its static") + + val lifted = compacted.glues.first { glue -> glue.meshA == DrawableId("c") } + assertEquals(null, lifted.channelGrids[FormChannel.GLUE_INTENSITY], "the spanning constant still lifts") + assertEquals(0.4f, lifted.intensity) + } + + /** + * A compacted glue keeps its authored id. + * + * Compaction runs on the MOC3 import path itself, so a glue whose intensity track lifts passes + * through here before any export sees it. The id exists purely so a round trip writes back the name + * the model was authored with, which a rewrite that dropped it would silently defeat - the export + * would synthesize `Glue_ArtMeshNN_ArtMeshMM_` and nothing would report a loss. + */ + @Test + fun aCompactedGlueKeepsItsAuthoredId() { + val spanningTrack = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf>( + KeyformCell(intArrayOf(0), scalar(0.4f)), + KeyformCell(intArrayOf(1), scalar(0.4f)), + ), + ) + val model = + PuppetModel( + parameters = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + glues = + listOf( + Glue( + DrawableId("a"), + DrawableId("b"), + emptyList(), + ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to spanningTrack)), + id = "Glue__ArtMesh48__ArtMesh49", + ), + ), + ) + + val compacted = model.withChannelsCompacted() + + // The glue IS rewritten here - its track lifts to a static - so this is the rewrite that must + // carry the id, not a pass-through that trivially would. + assertEquals(0.4f, compacted.glues.single().intensity, "the spanning constant lifted") + assertEquals("Glue__ArtMesh48__ArtMesh49", compacted.glues.single().id) + } + + /** A sparse grid is passed straight through - its missing cells cannot be tested, so nothing is dropped. */ + @Test + fun aSparseGridIsUntouched() { + val dense = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50f, 100f)) + val sparse = KeyformGrid(dense.axes, dense.cells.drop(1)) + assertSame(sparse, assertIs>(sparse.compacted(ChannelValueInterpolator)).grid) + } + + /** + * THE invariant: compact, then refine back onto the original key set, and every stored value is + * bit-identical to what it was. This is the property an importer's compaction pass and an exporter's + * union bake both rest on. + */ + @Test + fun compactionAndRefinementAreMutualInverses() { + val originals = + listOf( + // Exactly linear - loses its interior key to compaction, so refinement has to rebuild it. + track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50f, 100f)), + // Irregular key spacing, so the rebuilt fraction is not a tidy one half. + track(floatArrayOf(-30f, -7f, 30f), floatArrayOf(1f, (1f + 59f * (23f / 60f)), 60f)), + // Constant, which compacts all the way out and must replicate back. + track(floatArrayOf(-1f, 0f, 1f), floatArrayOf(0.25f, 0.25f, 0.25f)), + // Genuinely bending, so nothing is dropped and refinement is a no-op. + track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 90f, 100f)), + ) + for (original in originals) { + val originalKeys = original.axes.single().keys + val compacted = original.compacted(ChannelValueInterpolator) + val restored = + when (compacted) { + is CompactionResult.Constant -> + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(originalKeys.first(), originalKeys.last()))), + listOf(KeyformCell(intArrayOf(0), compacted.form), KeyformCell(intArrayOf(1), compacted.form)), + ).refinedToUnion(mapOf(angleX to originalKeys), emptyMap(), ChannelValueInterpolator) + + is CompactionResult.Reduced -> + compacted.grid.refinedToUnion(mapOf(angleX to originalKeys), emptyMap(), ChannelValueInterpolator) + } + assertEquals(originalKeys.toList(), restored.axes.single().keys.toList(), "every original key is restored") + assertEquals(valuesInIndexOrder(original), valuesInIndexOrder(restored), "restored bit-for-bit") + } + } + + /** + * Refinement is span-clamped: a union key outside a track's own key span is NOT inserted. Widening the + * span would resurrect a track its author keyed to fall out of range - the toggle-part pattern - which + * is a change to the rig, not a change in precision. + */ + @Test + fun refinementNeverWidensAnExistingSpan() { + val narrow = track(floatArrayOf(-1f, 1f), floatArrayOf(0f, 100f)) + val refined = narrow.refinedToUnion(mapOf(angleX to floatArrayOf(-30f, 0f, 30f)), emptyMap(), ChannelValueInterpolator) + assertEquals(listOf(-1f, 0f, 1f), refined.axes.single().keys.toList(), "only the interior union key is taken") + } + + /** + * A parameter the track does not key at all gets an appended axis spanning the parameter's own range - + * safe precisely because the track is constant along it, so the widening carries no motion. + */ + @Test + fun refinementAppendsAWholeAxisForAnUnkeyedParameter() { + val single = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + val refined = + single.refinedToUnion( + mapOf(angleY to floatArrayOf(0f)), + mapOf(angleY to -1f..1f), + ChannelValueInterpolator, + ) + assertEquals(listOf(angleX, angleY), refined.axes.map { axis -> axis.parameterId }, "the new axis is appended") + assertEquals(listOf(-1f, 0f, 1f), refined.axes[1].keys.toList()) + assertTrue(refined.isDense) + assertEquals(6, refined.cells.size) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformGridAlgebraTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformGridAlgebraTest.kt new file mode 100644 index 0000000..29c6550 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformGridAlgebraTest.kt @@ -0,0 +1,333 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.eval.EPS_SPAN +import org.umamo.runtime.eval.gridCorners +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the keyform authoring algebra: seeding an axis spans the parameter range and leaves the entity + * looking unchanged, key insertion fills a whole slice by interpolation, removal collapses rather than + * leaving a one-key axis that would hide the entity, and capture always lands on an exact cell. + * + * The refusals matter as much as the successes - a key too close to an existing one, or a span the + * evaluator resolves as a step, produces a grid that cannot be evaluated as authored. + */ +class KeyformGridAlgebraTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + + private fun parameter(id: ParameterId, min: Float = -1f, default: Float = 0f, max: Float = 1f): Parameter = + Parameter(id, id.raw, min = min, max = max, default = default) + + private fun scalar(value: Float): ChannelValue = ChannelValue.Scalar(value) + + private fun scalarOf(cell: KeyformCell): Float = (cell.form as ChannelValue.Scalar).value + + /** A one-axis track on angleX with the given keys, each cell holding the matching value. */ + private fun track(keys: FloatArray, values: FloatArray): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, keys)), + values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), scalar(value)) }, + ) + + /** The track's value at [poseValue], read through the real evaluator rather than a reimplementation. */ + private fun sample(grid: KeyformGrid, poseValue: Float, otherValue: Float = 0f): Float? { + val corners = gridCorners(grid) { parameterId -> if (parameterId == angleX) poseValue else otherValue } ?: return null + val formByIndex = grid.cells.associate { cell -> grid.linearIndexOf(cell.coordinate) to cell.form } + var total = 0f + for (corner in corners) { + total += corner.weight * ((formByIndex[corner.linearIndex] as? ChannelValue.Scalar)?.value ?: 0f) + } + return total + } + + /** Seeding a fresh axis spans min..max so the entity never falls out of range inside the slider. */ + @Test + fun seedingSpansTheParameterRange() { + val seeded = null.withAxisSeeded(parameter(angleX, min = -30f, default = 0f, max = 30f), scalar(0.5f)) + assertNotNull(seeded) + assertEquals(listOf(-30f, 0f, 30f), seeded.axes.single().keys.toList()) + assertEquals(listOf(0.5f, 0.5f, 0.5f), seeded.cells.map { cell -> scalarOf(cell) }, "every seeded key holds the current value") + } + + /** A default that coincides with an endpoint collapses to two keys rather than a degenerate span. */ + @Test + fun seedingDeduplicatesACoincidentDefault() { + val seeded = null.withAxisSeeded(parameter(angleX, min = 0f, default = 0f, max = 1f), scalar(1f)) + assertEquals(listOf(0f, 1f), assertNotNull(seeded).axes.single().keys.toList()) + } + + /** A parameter that cannot yield two distinct keys is refused rather than seeded into a hiding axis. */ + @Test + fun seedingRefusesADegenerateRange() { + assertNull(null.withAxisSeeded(parameter(angleX, min = 0f, default = 0f, max = 0f), scalar(1f))) + } + + /** Binding a second parameter appends its axis and replicates the grid, so nothing moves. */ + @Test + fun seedingASecondAxisAppendsAndReplicates() { + val existing = track(floatArrayOf(-1f, 1f), floatArrayOf(10f, 20f)) + val seeded = assertNotNull(existing.withAxisSeeded(parameter(angleY), scalar(99f))) + assertEquals(listOf(angleX, angleY), seeded.axes.map { axis -> axis.parameterId }, "the new axis is appended, not spliced") + assertEquals(6, seeded.cells.size) + assertTrue(seeded.isDense) + // The pre-existing motion is unchanged at every angleY key, which is what makes binding non-destructive. + for (poseY in listOf(-1f, 0f, 1f)) { + assertEquals(15f, sample(seeded, poseValue = 0f, otherValue = poseY)) + } + } + + /** + * Inserting a key leaves the evaluated curve alone - it adds a sample, not a shape change. + * + * Asserted to a tolerance, NOT bit-equality, and deliberately so: re-associating one linear blend into + * two consecutive ones is exact in the reals but lands a few ULP apart in float (pose 6 evaluates + * 60.000004 before the insert and 60.0 after). The bit-exact claim in this layer belongs only to + * compaction and refinement being mutual inverses, which evaluate the SAME expression on the SAME + * inputs - see KeyformCompactionTest. Asserting bit-equality here would be claiming something the + * arithmetic does not support. + */ + @Test + fun insertingAKeyPreservesTheCurve() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + val after = before.withKeyInserted(angleX, 2.5f, ChannelValueInterpolator) + assertEquals(listOf(0f, 2.5f, 10f), after.axes.single().keys.toList()) + assertEquals(25f, scalarOf(after.cells.first { cell -> cell.coordinate.single() == 1 })) + for (poseValue in listOf(0f, 1f, 2.5f, 6f, 10f)) { + val beforeValue = assertNotNull(sample(before, poseValue)) + val afterValue = assertNotNull(sample(after, poseValue)) + assertEquals(beforeValue, afterValue, absoluteTolerance = 1e-3f, message = "pose $poseValue is unchanged") + } + } + + /** Inserting on a multi-axis grid adds a whole slice, one cell per key of every other axis. */ + @Test + fun insertingAddsAWholeSliceNotOneCell() { + val axes = listOf(KeyformAxis(angleX, floatArrayOf(0f, 10f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))) + val cells = + listOf( + KeyformCell(intArrayOf(0, 0), scalar(0f)), + KeyformCell(intArrayOf(1, 0), scalar(100f)), + KeyformCell(intArrayOf(0, 1), scalar(0f)), + KeyformCell(intArrayOf(1, 1), scalar(200f)), + ) + val after = KeyformGrid(axes, cells).withKeyInserted(angleX, 5f, ChannelValueInterpolator) + assertEquals(6, after.cells.size, "a 2x2 grid gains a column, not a single cell") + assertTrue(after.isDense) + val insertedSlice = after.cells.filter { cell -> cell.coordinate[0] == 1 }.sortedBy { cell -> cell.coordinate[1] } + assertEquals(listOf(50f, 100f), insertedSlice.map { cell -> scalarOf(cell) }, "each new cell blends its own row") + } + + /** A key within the evaluator's snap tolerance of an existing one is refused, not stacked beside it. */ + @Test + fun insertingRefusesAKeyInsideTheSnapTolerance() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + assertSame(before, before.withKeyInserted(angleX, 0.0005f, ChannelValueInterpolator)) + } + + /** A key that would leave a span the evaluator resolves as a step is refused. */ + @Test + fun insertingRefusesASubResolutionSpan() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + assertSame(before, before.withKeyInserted(angleX, 0.0012f, ChannelValueInterpolator)) + } + + /** Beyond the span, Extend replicates the end slice - constant extrapolation, never a projected trend. */ + @Test + fun insertingBeyondTheSpanExtrapolatesFlat() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + val after = before.withKeyInserted(angleX, 20f, ChannelValueInterpolator, OutOfSpanKeyPolicy.Extend) + assertEquals(listOf(0f, 10f, 20f), after.axes.single().keys.toList()) + assertEquals(100f, scalarOf(after.cells.first { cell -> cell.coordinate.single() == 2 }), "the end value is held, not projected to 200") + assertSame(before, before.withKeyInserted(angleX, 20f, ChannelValueInterpolator, OutOfSpanKeyPolicy.Reject)) + } + + /** Removing an interior key leaves the axis intact and re-projects the coordinates above it. */ + @Test + fun removingAnInteriorKeyKeepsTheAxis() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 40f, 100f)) + val after = assertNotNull(before.withKeyRemoved(angleX, keyIndex = 1)) + assertEquals(listOf(0f, 10f), after.axes.single().keys.toList()) + assertEquals(listOf(0f, 100f), after.cells.map { cell -> scalarOf(cell) }) + } + + /** + * Removing down to one key collapses the axis instead of leaving a stub, because a single-key axis + * resolves only within EPS_KEY of that key and hides the entity everywhere else. + */ + @Test + fun removingBelowTwoKeysCollapsesTheAxis() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(7f, 100f)) + // Sole axis, so the collapse leaves the entity unkeyed entirely. + assertNull(before.withKeyRemoved(angleX, keyIndex = 1)) + + val twoAxis = assertNotNull(before.withAxisSeeded(parameter(angleY), scalar(0f))) + val collapsed = assertNotNull(twoAxis.withKeyRemoved(angleX, keyIndex = 1)) + assertEquals(listOf(angleY), collapsed.axes.map { axis -> axis.parameterId }, "angleX collapsed rather than keeping one key") + } + + /** Capture inserts a key at the pose, writes exactly one cell, and leaves every other pose alone. */ + @Test + fun captureWritesOneCellAtThePose() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + val after = before.withFormCaptured({ 4f }, scalar(80f), ChannelValueInterpolator) + assertEquals(listOf(0f, 4f, 10f), after.axes.single().keys.toList()) + assertEquals(80f, assertNotNull(sample(after, 4f)), "the captured value lands exactly on the pose") + assertEquals(0f, assertNotNull(sample(after, 0f)), "the endpoints are untouched") + assertEquals(100f, assertNotNull(sample(after, 10f))) + } + + /** Capturing at an existing key overwrites that cell without reshaping the axis. */ + @Test + fun captureOnAnExistingKeyDoesNotReshape() { + val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f)) + val after = before.withFormCaptured({ 10f }, scalar(55f), ChannelValueInterpolator) + assertEquals(listOf(0f, 10f), after.axes.single().keys.toList()) + assertEquals(55f, assertNotNull(sample(after, 10f))) + } + + /** A sparse grid is refused by every reshaping op rather than being silently repaired. */ + @Test + fun sparseGridsAreRefused() { + val dense = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 40f, 100f)) + val sparse = KeyformGrid(dense.axes, dense.cells.drop(1)) + assertSame(sparse, sparse.withKeyInserted(angleX, 2f, ChannelValueInterpolator)) + assertSame(sparse, sparse.withKeyRemoved(angleX, keyIndex = 1)) + assertSame(sparse, sparse.withFormCaptured({ 2f }, scalar(1f), ChannelValueInterpolator)) + } + + /** Moving a key changes only WHERE it applies; the value it holds rides along. */ + @Test + fun movingAKeyCarriesItsValue() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f)) + val after = before.withKeyMoved(angleX, keyIndex = 1, newValue = 8f) + assertEquals(listOf(0f, 8f, 10f), after.axes.single().keys.toList()) + assertEquals(42f, assertNotNull(sample(after, 8f)), "the moved key still holds what it held") + } + + /** + * A key may CROSS its neighbours; the axis re-sorts and the cells permute to match. + * + * The permutation is the whole cost of allowing it. A cell's coordinate on an axis is a key ORDINAL + * and the evaluator requires an ascending axis, so re-sorting the keys alone would still satisfy + * isDense while silently applying every form at the wrong position. + */ + @Test + fun movingAcrossANeighbourPermutesTheCells() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f)) + val crossed = before.withKeyMoved(angleX, keyIndex = 1, newValue = 20f) + + assertEquals(listOf(0f, 10f, 20f), crossed.axes.single().keys.toList(), "the axis re-sorts") + assertTrue(crossed.isDense, "and stays dense") + assertEquals(42f, assertNotNull(sample(crossed, 20f)), "the moved key still holds what it held") + assertEquals(100f, assertNotNull(sample(crossed, 10f)), "the key it passed still holds what it held") + assertEquals(0f, assertNotNull(sample(crossed, 0f)), "and the untouched key is untouched") + } + + /** Crossing works downward too, and the whole run of passed keys shifts up by one ordinal. */ + @Test + fun movingDownAcrossSeveralNeighbours() { + val before = track(floatArrayOf(0f, 5f, 10f, 15f), floatArrayOf(0f, 42f, 100f, 7f)) + val crossed = before.withKeyMoved(angleX, keyIndex = 3, newValue = 2f) + + assertEquals(listOf(0f, 2f, 5f, 10f), crossed.axes.single().keys.toList()) + assertTrue(crossed.isDense) + assertEquals(7f, assertNotNull(sample(crossed, 2f)), "the dragged key kept its value across three crossings") + assertEquals(42f, assertNotNull(sample(crossed, 5f))) + assertEquals(100f, assertNotNull(sample(crossed, 10f))) + } + + /** + * A destination that would collide with another key is nudged just far enough to stay resolvable. + * + * Not a spacing preference: two keys closer than EPS_SPAN make the evaluator read fraction 0 across the + * gap, so the nearer one becomes unreachable and the blend degenerates into a step. + */ + @Test + fun aCollidingDestinationStaysResolvable() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f)) + val landed = before.withKeyMoved(angleX, keyIndex = 0, newValue = 5f) + val keys = landed.axes.single().keys.toList() + + assertTrue(keys[1] - keys[0] >= EPS_SPAN, "the two keys stay at least a resolvable span apart") + assertEquals(42f, assertNotNull(sample(landed, 5f)), "the key it landed beside is still reachable") + } + + /** + * A key dropped exactly onto the LAST key is nudged inward, never past it. + * + * Outward would put it beyond the axis's own span - and so beyond the parameter's range, where the + * evaluator brackets nothing and every entity keyed on it disappears. That is the difference between + * a sub-pixel nudge and a vanishing rig. + */ + @Test + fun aCollisionAtAnEndpointNudgesInward() { + val before = track(floatArrayOf(-30f, 0f, 30f), floatArrayOf(0f, 42f, 100f)) + val onTheLast = before.withKeyMoved(angleX, keyIndex = 1, newValue = 30f) + val highest = onTheLast.axes.single().keys.max() + assertEquals(30f, highest, "the axis did not grow past where it already reached") + + val onTheFirst = before.withKeyMoved(angleX, keyIndex = 1, newValue = -30f) + assertEquals(-30f, onTheFirst.axes.single().keys.min(), "and not below it either") + } + + /** The mover's new ordinal is reported, so whatever is holding that key can follow it. */ + @Test + fun theNewOrdinalIsReported() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f)) + assertEquals(2, before.keyIndexAfterMove(angleX, keyIndex = 1, newValue = 20f), "crossed to the end") + assertEquals(0, before.keyIndexAfterMove(angleX, keyIndex = 2, newValue = -5f), "crossed to the start") + assertEquals(1, before.keyIndexAfterMove(angleX, keyIndex = 1, newValue = 6f), "stayed put") + } + + /** An endpoint has one wall only, so a move can still widen the axis - that is real authoring. */ + @Test + fun movingAnEndpointResizesTheSpan() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f)) + val widened = before.withKeyMoved(angleX, keyIndex = 2, newValue = 30f) + assertEquals(listOf(0f, 5f, 30f), widened.axes.single().keys.toList()) + } + + /** A move to where the key already sits, or on a missing axis, records nothing. */ + @Test + fun aPointlessMoveIsARefusal() { + val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f)) + assertSame(before, before.withKeyMoved(angleX, keyIndex = 1, newValue = 5f)) + assertSame(before, before.withKeyMoved(angleY, keyIndex = 0, newValue = 1f)) + } + + /** + * The collision nudge never lands ON another key, even where the only gap is one it created itself. + * + * The nudge is measured against the NEAREST key, so on a crowded axis "nearest + EPS_SPAN" can be + * exactly where the next key along already sits - and two keys closer than EPS_SPAN is the + * unresolvable span the nudge exists to prevent (bindBracket gives such a span fraction 0, so the + * upper key can never be reached). A move that cannot be made resolvable is refused instead. + */ + @Test + fun theCollisionNudgeNeverLandsOnAnotherKey() { + val crowded = track(floatArrayOf(0f, EPS_SPAN, 10f), floatArrayOf(0f, 1f, 2f)) + // Aimed just above the key at 0: the nearest is 0, so the nudge goes to 0 + EPS_SPAN - which is + // exactly the second key. + assertNull( + crowded.keyDestinationFor(angleX, keyIndex = 2, newValue = EPS_SPAN / 3f), + "nudging onto an existing key is refused rather than authored", + ) + assertSame(crowded, crowded.withKeyMoved(angleX, keyIndex = 2, newValue = EPS_SPAN / 3f), "so the move is a no-op") + + // The same axis still accepts a destination with room on both sides. + val moved = crowded.withKeyMoved(angleX, keyIndex = 2, newValue = 5f) + assertEquals(listOf(0f, EPS_SPAN, 5f), moved.axes.single().keys.toList()) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformGridShapeTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformGridShapeTest.kt new file mode 100644 index 0000000..9a6b549 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/keyform/KeyformGridShapeTest.kt @@ -0,0 +1,182 @@ +package org.umamo.runtime.keyform + +import org.umamo.runtime.eval.cellsByLinearIndex +import org.umamo.runtime.model.GlueForm +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the keyform-grid shape layer: the stride folding (which must agree with the evaluator's own, + * since the resulting linear index is the shared contract between a weighted corner, a stored cell, + * and the GPU delta texture's column), the coordinate round trip, the density check that compaction + * and refine gate on, and withAxisCollapsed's coordinate re-projection. + */ +class KeyformGridShapeTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val angleZ = ParameterId("ParamAngleZ") + + /** + * Unfolds a linear index back into a per-axis coordinate - the inverse of linearIndexOf, kept as a + * fixture helper (production code only ever folds). + */ + private fun KeyformGrid<*>.coordinateOf(linearIndex: Int): IntArray { + val coordinate = IntArray(axes.size) + var remaining = linearIndex + for (axisIndex in axes.indices) { + val keyCount = axes[axisIndex].keys.size + if (keyCount <= 0) { + continue + } + coordinate[axisIndex] = remaining % keyCount + remaining /= keyCount + } + return coordinate + } + + /** + * A dense grid over the given axis key counts, each cell carrying its own linear index as its + * payload so a re-shape can be traced by value. + */ + private fun denseGrid(vararg keyCounts: Int): KeyformGrid { + val parameterIds = listOf(angleX, angleY, angleZ) + val axes = + keyCounts.mapIndexed { axisIndex, keyCount -> + KeyformAxis(parameterIds[axisIndex], FloatArray(keyCount) { keyIndex -> keyIndex.toFloat() }) + } + val grid = KeyformGrid(axes, emptyList>()) + val cells = + (0 until grid.cellCount).map { linearIndex -> + KeyformCell(grid.coordinateOf(linearIndex), GlueForm(linearIndex.toFloat())) + } + return KeyformGrid(axes, cells) + } + + /** cellCount is the product of the axis key counts, and 1 for an axis-less grid. */ + @Test + fun cellCountIsTheAxisProduct() { + assertEquals(6, denseGrid(3, 2).cellCount) + assertEquals(24, denseGrid(4, 3, 2).cellCount) + assertEquals(1, KeyformGrid(emptyList(), listOf(KeyformCell(intArrayOf(), GlueForm(1f)))).cellCount) + } + + /** + * The stride folding matches the evaluator's cellsByLinearIndex exactly. Both now share + * KeyformGrid's own members, so this pins the contract rather than guarding a duplicate. + */ + @Test + fun linearIndexMatchesTheEvaluatorFolding() { + for (grid in listOf(denseGrid(3, 2), denseGrid(4, 3, 2), denseGrid(5))) { + val evaluatorIndexed = cellsByLinearIndex(grid) + for (cell in grid.cells) { + val shapeIndex = grid.linearIndexOf(cell.coordinate) + assertSame(cell, evaluatorIndexed[shapeIndex], "cell ${cell.coordinate.toList()} folds to the same index") + } + } + } + + /** coordinateOf inverts linearIndexOf for every cell in the grid's shape. */ + @Test + fun coordinateRoundTripsThroughLinearIndex() { + val grid = denseGrid(4, 3, 2) + for (linearIndex in 0 until grid.cellCount) { + assertEquals(linearIndex, grid.linearIndexOf(grid.coordinateOf(linearIndex))) + } + } + + /** Axis 0 varies fastest, matching the evaluator's stride accumulation order. */ + @Test + fun axisZeroVariesFastest() { + val grid = denseGrid(3, 2) + assertEquals(listOf(1, 3), grid.strides().toList()) + assertEquals(listOf(1, 0), grid.coordinateOf(1).toList(), "the second cell steps along axis 0") + } + + /** A grid with one cell per coordinate is dense; a grid missing a cell is not. */ + @Test + fun densityDetectsAMissingCell() { + val dense = denseGrid(3, 2) + assertTrue(dense.isDense) + val sparse = KeyformGrid(dense.axes, dense.cells.drop(1)) + assertFalse(sparse.isDense, "a dropped cell makes the grid sparse") + val duplicated = KeyformGrid(dense.axes, dense.cells.dropLast(1) + dense.cells.first()) + assertFalse(duplicated.isDense, "a duplicated coordinate makes the grid sparse") + } + + /** axisIndexOf finds an axis by parameter and reports -1 when the grid has none. */ + @Test + fun axisIndexOfLocatesTheAxis() { + val grid = denseGrid(3, 2) + assertEquals(0, grid.axisIndexOf(angleX)) + assertEquals(1, grid.axisIndexOf(angleY)) + assertEquals(-1, grid.axisIndexOf(angleZ)) + } + + /** withAxisCollapsed drops the named axis and re-projects each surviving cell's coordinate. */ + @Test + fun withAxisCollapsedReprojectsCoordinates() { + val axes = listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))) + val cells = + listOf( + KeyformCell(intArrayOf(0, 0), GlueForm(0f)), + KeyformCell(intArrayOf(0, 1), GlueForm(1f)), + KeyformCell(intArrayOf(1, 0), GlueForm(2f)), + KeyformCell(intArrayOf(1, 1), GlueForm(3f)), + ) + // Collapse angleX keeping the value-0 slice (key index 0): surviving cells are (0,0) and (0,1). + val collapsed = KeyformGrid(axes, cells).withAxisCollapsed(angleX, keepKeyValue = 0f)!! + assertEquals(listOf(angleY), collapsed.axes.map { axis -> axis.parameterId }) + assertEquals(listOf(listOf(0), listOf(1)), collapsed.cells.map { cell -> cell.coordinate.toList() }) + assertEquals(listOf(0f, 1f), collapsed.cells.map { cell -> cell.form.intensity }) + } + + /** The kept slice is the NEAREST key, so a value between keys snaps rather than interpolating. */ + @Test + fun withAxisCollapsedSnapsToTheNearestKey() { + val grid = denseGrid(3, 2) + // angleX keys are 0, 1, 2; 1.6 is nearest key index 2, whose cells are linear indices 2 and 5. + val collapsed = grid.withAxisCollapsed(angleX, keepKeyValue = 1.6f)!! + assertEquals(listOf(2f, 5f), collapsed.cells.map { cell -> cell.form.intensity }) + } + + /** withAxisCollapsed returns the same instance when the grid has no such axis. */ + @Test + fun withAxisCollapsedAbsentAxisReturnsSame() { + val grid = denseGrid(3, 2) + assertSame(grid, grid.withAxisCollapsed(angleZ, keepKeyValue = 0f)) + } + + /** Collapsing the only axis leaves nothing to key on, so the grid becomes null (the entity unkeyed). */ + @Test + fun withAxisCollapsedSoleAxisBecomesNull() { + assertNull(denseGrid(3).withAxisCollapsed(angleX, keepKeyValue = 0f)) + } + + /** withAxisRetargeted renames the axis and keeps key values / cells. */ + @Test + fun withAxisRetargetedRenamesAxisKeepsKeys() { + val grid = denseGrid(3) + val retargeted = grid.withAxisRetargeted(angleX, angleY, destinationKeepValue = 0f) + assertEquals(listOf(angleY), retargeted.axes.map { it.parameterId }) + assertTrue(retargeted.axes.single().keys.contentEquals(grid.axes.single().keys)) + assertEquals(grid.cells.map { it.form.intensity }, retargeted.cells.map { it.form.intensity }) + } + + /** withAxisRetargeted collapses an existing destination axis before renaming the source onto it. */ + @Test + fun withAxisRetargetedCollapsesExistingDestination() { + val grid = denseGrid(3, 2) + // Destination default 0 keeps angleY key index 0; then angleX renames onto angleY. + val retargeted = grid.withAxisRetargeted(angleX, angleY, destinationKeepValue = 0f) + assertEquals(listOf(angleY), retargeted.axes.map { it.parameterId }) + assertEquals(listOf(0f, 1f, 2f), retargeted.cells.map { it.form.intensity }) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/AtlasPlacementAffineTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/AtlasPlacementAffineTest.kt new file mode 100644 index 0000000..a951f0e --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/AtlasPlacementAffineTest.kt @@ -0,0 +1,69 @@ +package org.umamo.runtime.model + +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Pins the placement's matrix form against its pointwise reference, and the affine composition the + * export's transform rewrites lean on: forward-composed-with-inverse must be the identity for every + * placement shape the corpus contains. + */ +class AtlasPlacementAffineTest { + private fun placementOf( + positionX: Float = 0f, + positionY: Float = 0f, + scaleX: Float = 1f, + scaleY: Float = 1f, + rotationDegrees: Float = 0f, + ): AtlasPlacement = AtlasPlacement(0, positionX, positionY, scaleX, scaleY, rotationDegrees) + + private val shapes = + listOf( + placementOf(), + placementOf(positionX = 137.5f, positionY = -12.25f), + placementOf(rotationDegrees = 90f, positionX = 40f), + placementOf(rotationDegrees = 33.7f, scaleX = 0.5f, scaleY = 2f, positionX = 7f, positionY = 9f), + placementOf(scaleX = -1f, positionY = 512f), + ) + + private fun applyAffine(affine: FloatArray, x: Float, y: Float): FloatArray = + floatArrayOf( + affine[0] * x + affine[1] * y + affine[2], + affine[3] * x + affine[4] * y + affine[5], + ) + + @Test + fun placementAffineMatchesAtlasPixelOf() { + val probePoints = listOf(0f to 0f, 12f to 34f, -5f to 100f, 250.5f to 0.25f) + for (placement in shapes) { + val affine = placementAffine(placement) + for ((layerX, layerY) in probePoints) { + val pointwise = atlasPixelOf(placement, layerX, layerY) + val viaMatrix = applyAffine(affine, layerX, layerY) + assertTrue( + abs(pointwise[0] - viaMatrix[0]) < 1e-3f && abs(pointwise[1] - viaMatrix[1]) < 1e-3f, + "$placement at ($layerX, $layerY): pointwise (${pointwise[0]}, ${pointwise[1]})" + + " vs matrix (${viaMatrix[0]}, ${viaMatrix[1]})", + ) + } + } + } + + @Test + fun composeWithInverseIsIdentity() { + for (placement in shapes) { + val forward = placementAffine(placement) + val inverse = assertNotNull(inversePlacementAffine(placement), "$placement inverts") + val composed = composeAffine(forward, inverse) + val identity = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f) + for (componentIndex in identity.indices) { + assertTrue( + abs(composed[componentIndex] - identity[componentIndex]) < 1e-3f, + "$placement component $componentIndex: ${composed[componentIndex]}", + ) + } + } + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/DeformerSubtreeTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/DeformerSubtreeTest.kt new file mode 100644 index 0000000..74bf0fa --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/DeformerSubtreeTest.kt @@ -0,0 +1,73 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the deformer subtree query behind both the reparent cycle guard and the Properties picker's + * candidate filter: a deformer plus everything nested beneath it, which is exactly the set it may not be + * re-nested under. Sharing one definition is what keeps the picker from offering a target the move would + * then silently refuse. + */ +class DeformerSubtreeTest { + private val rootId = DeformerId("root") + private val childId = DeformerId("child") + private val grandchildId = DeformerId("grandchild") + private val siblingId = DeformerId("sibling") + + private fun warp(id: DeformerId, parent: DeformerId?): Deformer.Warp = + Deformer.Warp( + id = id, + name = id.raw, + parent = parent, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = false, + geometryGrid = null, + ) + + /** root > child > grandchild, with an unrelated sibling at the armature root. */ + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = + listOf( + warp(rootId, null), + warp(childId, rootId), + warp(grandchildId, childId), + warp(siblingId, null), + ), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ) + + @Test + fun collectsTheDeformerAndEveryDescendant() { + assertEquals(setOf(rootId, childId, grandchildId), model().deformerSelfAndDescendants(rootId)) + assertEquals(setOf(childId, grandchildId), model().deformerSelfAndDescendants(childId)) + // A leaf is just itself - self-parenting is still refused because the set contains it. + assertEquals(setOf(grandchildId), model().deformerSelfAndDescendants(grandchildId)) + } + + @Test + fun excludesUnrelatedBranchesSoTheyStayValidParents() { + val forbidden = model().deformerSelfAndDescendants(rootId) + assertTrue(siblingId !in forbidden, "an unrelated deformer is a legal parent") + } + + @Test + fun aMoveIntoTheOwnSubtreeIsRefusedAndAnUnrelatedOneIsNot() { + val base = model() + // Every member of the subtree is an illegal parent for root, self included. + for (candidate in base.deformerSelfAndDescendants(rootId)) { + assertTrue(candidate in base.deformerSelfAndDescendants(rootId)) + } + // The picker filters on exactly this, so what it offers is what the move accepts. + assertTrue(rootId in base.deformerSelfAndDescendants(rootId), "self is in the forbidden set") + assertTrue(grandchildId in base.deformerSelfAndDescendants(rootId), "a descendant is forbidden") + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/FirstEditableDrawableTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/FirstEditableDrawableTest.kt new file mode 100644 index 0000000..cf17a30 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/FirstEditableDrawableTest.kt @@ -0,0 +1,77 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Unit-tests [firstEditableDrawableInPanelOrder]: Edit mode seeds onto the topmost drawable in Parts-panel + * order (top = front) that both carries a mesh and is shown, so a fresh document never opens Edit on + * nothing. Corpus-free - hand-built trees exercise panel order, the mesh-less skip, the visibility + * cascade, the empty-tree flat fallback, and the nothing-editable null. + */ +class FirstEditableDrawableTest { + private fun mesh(): DrawableMesh = DrawableMesh(floatArrayOf(0f, 0f), floatArrayOf(0f, 0f), intArrayOf()) + + private fun drawable(id: String, hasMesh: Boolean = true, isVisible: Boolean = true): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = if (hasMesh) mesh() else null, + geometryGrid = null, + isVisible = isVisible, + ) + + @Test + fun picksFrontOfPanelOrder() { + val drawables = listOf(drawable("front"), drawable("back")) + // Panel order top = front: "front" precedes "back" at the root. + val rootChildren = listOf(OrgChild.Drawable(DrawableId("front")), OrgChild.Drawable(DrawableId("back"))) + val model = PuppetModel(emptyList(), emptyList(), emptyList(), drawables, rootChildren, rootPartId = null) + + assertEquals(DrawableId("front"), model.firstEditableDrawableInPanelOrder()) + } + + @Test + fun skipsMeshlessAndHiddenDrawables() { + val hiddenPart = Part(PartId("hidden"), "[Guide Image]", listOf(OrgChild.Drawable(DrawableId("inHidden"))), isVisible = false) + val drawables = + listOf( + drawable("noMesh", hasMesh = false), // no mesh → skipped + drawable("inHidden", hasMesh = true), // ancestor part hidden → skipped + drawable("ownHidden", hasMesh = true, isVisible = false), // own eyeball off → skipped + drawable("editable", hasMesh = true), // first shown + meshed → the pick + ) + val rootChildren = + listOf( + OrgChild.Drawable(DrawableId("noMesh")), + OrgChild.Part(PartId("hidden")), + OrgChild.Drawable(DrawableId("ownHidden")), + OrgChild.Drawable(DrawableId("editable")), + ) + val model = PuppetModel(emptyList(), listOf(hiddenPart), emptyList(), drawables, rootChildren, rootPartId = null) + + assertEquals(DrawableId("editable"), model.firstEditableDrawableInPanelOrder()) + } + + @Test + fun returnsNullWhenNothingEditable() { + val drawables = listOf(drawable("a", hasMesh = false), drawable("b", hasMesh = true, isVisible = false)) + val rootChildren = listOf(OrgChild.Drawable(DrawableId("a")), OrgChild.Drawable(DrawableId("b"))) + val model = PuppetModel(emptyList(), emptyList(), emptyList(), drawables, rootChildren, rootPartId = null) + + assertNull(model.firstEditableDrawableInPanelOrder()) + } + + @Test + fun fallsBackToFlatListWhenTreeIsEmpty() { + // A degenerate model with no org tree still finds its meshed, visible drawable. + val drawables = listOf(drawable("orphan", hasMesh = true)) + val model = PuppetModel(emptyList(), emptyList(), emptyList(), drawables, rootChildren = emptyList(), rootPartId = null) + + assertEquals(DrawableId("orphan"), model.firstEditableDrawableInPanelOrder()) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/OriginRelativeCoordinatesTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/OriginRelativeCoordinatesTest.kt new file mode 100644 index 0000000..c8404f8 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/OriginRelativeCoordinatesTest.kt @@ -0,0 +1,110 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Unit-tests the rigger's coordinate frame: positions read from the world axes, and the Origin fields read + * from the canvas's bottom-left corner with Z up. Corpus-free - hand-built models with a canvas and an origin + * exercise the default center origin, both round trips off center, the canvas-less model, and a canvas height + * change. + */ +class OriginRelativeCoordinatesTest { + /** + * A model with no content, a [width] x [height] canvas, and its world origin at ([originX], [originZ]). + * + * @param Float width The canvas width. + * @param Float height The canvas height. + * @param Float originX The world-origin x. + * @param Float originZ The world-origin z (up; world space, negated canvas y). + * @return PuppetModel The model. + */ + private fun model(width: Float, height: Float, originX: Float, originZ: Float): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = width, + canvasHeight = height, + worldOriginX = originX, + worldOriginZ = originZ, + ) + + /** The origin every importer derives: the center of a 1200 x 1200 canvas, stored as (600, -600). */ + private val centered = model(1200f, 1200f, 600f, -600f) + + @Test + fun theDefaultOriginReadsFromTheCanvasBottomLeft() { + assertEquals(600f, centered.originFromCanvasLeft()) + assertEquals(600f, centered.originFromCanvasBottom(), "Z counts up from the bottom edge, so the center reads positive") + } + + @Test + fun positionsReadFromTheWorldAxes() { + // The world point the axes cross at reads (0, 0). + assertEquals(0f, centered.originRelativeX(600f)) + assertEquals(0f, centered.originRelativeZ(-600f)) + // The canvas's top-left corner (world zero) sits left of and above the axes. + assertEquals(-600f, centered.originRelativeX(0f)) + assertEquals(600f, centered.originRelativeZ(0f)) + } + + @Test + fun positionsRoundTripOffCenter() { + val offCenter = model(1000f, 800f, 250f, -600f) + + assertEquals(40f, offCenter.originRelativeX(offCenter.worldXFromOriginRelative(40f))) + assertEquals(-75f, offCenter.originRelativeZ(offCenter.worldZFromOriginRelative(-75f))) + assertEquals(310f, offCenter.worldXFromOriginRelative(offCenter.originRelativeX(310f))) + assertEquals(-120f, offCenter.worldZFromOriginRelative(offCenter.originRelativeZ(-120f))) + } + + @Test + fun theOriginRoundTripsThroughTheCanvasReading() { + val offCenter = model(1000f, 800f, 250f, -600f) + + // Stored 600 below the top of an 800-tall canvas, so 200 above its bottom. + assertEquals(250f, offCenter.originFromCanvasLeft()) + assertEquals(200f, offCenter.originFromCanvasBottom()) + assertEquals(250f, offCenter.worldOriginXFromCanvasLeft(offCenter.originFromCanvasLeft())) + assertEquals(-600f, offCenter.worldOriginZFromCanvasBottom(offCenter.originFromCanvasBottom())) + assertEquals(-500f, offCenter.worldOriginZFromCanvasBottom(300f), "typing 300 puts the origin 300 above the bottom edge") + } + + @Test + fun aCanvaslessModelReadsWorldSpace() { + val canvasless = model(0f, 0f, 0f, 0f) + + assertEquals(35f, canvasless.originRelativeX(35f)) + assertEquals(-12f, canvasless.originRelativeZ(-12f)) + assertEquals(0f, canvasless.originFromCanvasBottom(), "with no canvas the bottom reading is the raw world z") + } + + @Test + fun aCanvasHeightChangeMovesOnlyTheOriginZReading() { + // The canvas grows at its bottom edge and the origin keeps its world point. + val taller = centered.copy(canvasHeight = 1300f) + + assertEquals(700f, taller.originFromCanvasBottom(), "the bottom edge moved 100 further from the origin") + assertEquals(600f, taller.originFromCanvasLeft()) + assertEquals(centered.originRelativeX(420f), taller.originRelativeX(420f), "positions still read from the same axes") + assertEquals(centered.originRelativeZ(-300f), taller.originRelativeZ(-300f)) + } + + @Test + fun theCanvasCenterOriginIsTheImportersDefault() { + assertEquals(600f, canvasCenterWorldOriginX(1200f)) + assertEquals(-400f, canvasCenterWorldOriginZ(800f), "half the height down from the top edge, negated into world z") + assertEquals(0f, canvasCenterWorldOriginX(0f), "no canvas keeps the (0, 0) origin") + + assertTrue(centered.isOriginAtCanvasCenter()) + assertTrue(model(0f, 0f, 0f, 0f).isOriginAtCanvasCenter(), "a canvas-less model's (0, 0) origin is its center") + assertFalse(centered.copy(worldOriginZ = -500f).isOriginAtCanvasCenter(), "a moved origin is off center") + assertFalse(centered.copy(canvasHeight = 1300f).isOriginAtCanvasCenter(), "a resized canvas leaves the origin behind") + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PartMaskResolveTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PartMaskResolveTest.kt new file mode 100644 index 0000000..b683c59 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PartMaskResolveTest.kt @@ -0,0 +1,155 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the part-as-mask extension: a part used as a clip mask expands to its descendant drawables (through + * nested parts) in the DERIVED render tree only, while the authored composite keeps the part reference for + * the UI. Also pins the dedup when a drawable is masked both directly and through an ancestor part. + */ +class PartMaskResolveTest { + private val maskLeafId = DrawableId("maskLeaf") + private val maskNestedId = DrawableId("maskNested") + private val subjectId = DrawableId("subject") + private val maskPartId = PartId("maskPart") + private val nestedPartId = PartId("nestedPart") + private val subjectPartId = PartId("subjectPart") + + private fun drawable(id: DrawableId): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + /** A mask part holding one drawable plus a nested part holding another, beside an isolated subject part. */ + private fun model(composite: PartComposite): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + Part(maskPartId, "maskPart", children = listOf(OrgChild.Drawable(maskLeafId), OrgChild.Part(nestedPartId))), + Part(nestedPartId, "nestedPart", children = listOf(OrgChild.Drawable(maskNestedId))), + Part( + subjectPartId, + "subjectPart", + children = listOf(OrgChild.Drawable(subjectId)), + groupMode = PartGroupMode.Isolated, + composite = composite, + ), + ), + deformers = emptyList(), + drawables = listOf(drawable(maskLeafId), drawable(maskNestedId), drawable(subjectId)), + rootChildren = listOf(OrgChild.Part(maskPartId), OrgChild.Part(subjectPartId)), + rootPartId = null, + ) + + /** The composite the render tree carries for the subject part. */ + private fun renderedComposite(model: PuppetModel): PartComposite? { + val root = model.deriveRenderRoot() + + fun find(node: RenderNode): RenderGroup? = + when (node) { + is RenderDrawable -> null + is RenderGroup -> + if (node.partId == subjectPartId) { + node + } else { + node.children.firstNotNullOfOrNull { child -> find(child) } + } + } + return find(root)?.composite + } + + @Test + fun parentPartLookupCoversNestedPartsOnly() { + // Part membership lives only in the tree, so the Properties panel needs this to show a nested part's + // owner; a top-level part has no entry and reads as unbound. + val parents = model(PartComposite()).parentPartByPart() + assertEquals(maskPartId, parents[nestedPartId]) + assertNull(parents[maskPartId], "a top-level part has no owning part") + assertNull(parents[subjectPartId]) + } + + @Test + fun subtreeQueryWalksNestedParts() { + val subtrees = model(PartComposite()).drawablesByPartSubtree() + assertEquals(listOf(maskLeafId, maskNestedId), subtrees[maskPartId], "nested part contributes its drawables") + assertEquals(listOf(maskNestedId), subtrees[nestedPartId]) + assertEquals(listOf(subjectId), subtrees[subjectPartId]) + } + + @Test + fun aMaskPartExpandsToItsDescendantDrawablesInTheRenderTree() { + val authored = PartComposite(maskedByParts = listOf(maskPartId)) + val model = model(authored) + + assertEquals(listOf(maskLeafId, maskNestedId), renderedComposite(model)?.maskedBy, "expanded for the renderer") + // The authored value is untouched, so the panel still shows the part, not its expansion. + val storedComposite = model.parts.first { it.id == subjectPartId }.composite + assertEquals(listOf(maskPartId), storedComposite.maskedByParts) + assertTrue(storedComposite.maskedBy.isEmpty()) + } + + @Test + fun theRenderCompositeCarriesNoPartIdsAtAll() { + // PartComposite documents that the render tree sees the EXPANSION and never the part ids. Leaving + // them beside the expansion would let any consumer that later honours them clip by the same drawables + // twice, so the resolved copy must clear the field, not merely add to maskedBy. + val authored = PartComposite(maskedByParts = listOf(maskPartId)) + val rendered = renderedComposite(model(authored)) + + assertTrue(rendered?.maskedByParts?.isEmpty() == true, "the renderer must not receive part ids") + assertEquals(listOf(maskLeafId, maskNestedId), rendered.maskedBy) + } + + @Test + fun directAndPartReachedMasksMergeWithoutDuplicates() { + // maskLeaf is masked directly AND sits under the masking part: it must appear once. + val authored = PartComposite(maskedBy = listOf(maskLeafId), maskedByParts = listOf(maskPartId)) + assertEquals(listOf(maskLeafId, maskNestedId), renderedComposite(model(authored))?.maskedBy) + } + + @Test + fun flatteningForExportPreservesExactlyWhatTheRendererClipsWith() { + // The guarantee behind withPartMasksFlattened: an export to a drawable-only mask format (CMO3) keeps + // the clipping the viewport shows. Only the "masked by this part" grouping is lost, which those + // formats cannot record - so the conversion is explicit, never a silent drop. + val authored = PartComposite(maskedBy = listOf(maskLeafId), maskedByParts = listOf(maskPartId)) + val model = model(authored) + val rendered = renderedComposite(model)?.maskedBy + + val exported = model.withPartMasksFlattened() + val exportedComposite = exported.parts.first { it.id == subjectPartId }.composite + + assertEquals(rendered, exportedComposite.maskedBy, "export clips exactly as the viewport does") + assertTrue(exportedComposite.maskedByParts.isEmpty(), "the part reference is expanded, not carried") + // Flattening is idempotent, and the render tree of a flattened model is unchanged. + assertEquals(rendered, renderedComposite(exported)?.maskedBy) + assertSame(exported, exported.withPartMasksFlattened()) + } + + @Test + fun flatteningIsAnIdentityForAModelWithNoPartMasks() { + // The common case pays nothing and an exporter can call it unconditionally. + val model = model(PartComposite(maskedBy = listOf(maskLeafId))) + assertSame(model, model.withPartMasksFlattened()) + } + + @Test + fun withoutPartMasksTheCompositeInstanceIsPassedThroughUntouched() { + // The common case pays nothing: no part masks means the authored composite reaches the render tree + // as the very same instance. + val authored = PartComposite(maskedBy = listOf(maskLeafId)) + val model = model(authored) + assertSame(model.parts.first { it.id == subjectPartId }.composite, renderedComposite(model)) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PartSubtreeTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PartSubtreeTest.kt new file mode 100644 index 0000000..039fc47 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PartSubtreeTest.kt @@ -0,0 +1,74 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the part subtree query behind both the org-move cycle guard and the Properties picker's owner + * filter: a part plus every part beneath it, which is exactly the set it may NOT be re-homed under. + * + * This replaced two private implementations that walked the tree in OPPOSITE directions - one down from + * the part, one up the parent chain - so the point of the test is that ONE definition serves both, and + * that a malformed (already cyclic) tree terminates rather than hanging the editor. + */ +class PartSubtreeTest { + private val rootId = PartId("root") + private val childId = PartId("child") + private val grandchildId = PartId("grandchild") + private val siblingId = PartId("sibling") + + private fun part(id: PartId, children: List = emptyList()): Part = Part(id, id.raw, children = children) + + /** root > child > grandchild, with an unrelated sibling at the top level. */ + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + part(rootId, listOf(OrgChild.Part(childId))), + part(childId, listOf(OrgChild.Part(grandchildId))), + part(grandchildId), + part(siblingId), + ), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = listOf(OrgChild.Part(rootId), OrgChild.Part(siblingId)), + rootPartId = null, + ) + + @Test + fun collectsThePartAndEveryDescendant() { + assertEquals(setOf(rootId, childId, grandchildId), model().partSelfAndDescendants(rootId)) + assertEquals(setOf(childId, grandchildId), model().partSelfAndDescendants(childId)) + // A leaf is just itself - self-parenting is still refused because the set contains it. + assertEquals(setOf(grandchildId), model().partSelfAndDescendants(grandchildId)) + } + + @Test + fun excludesUnrelatedBranchesSoTheyStayValidOwners() { + val forbidden = model().partSelfAndDescendants(rootId) + assertTrue(siblingId !in forbidden, "an unrelated part is a legal owner") + assertTrue(rootId in forbidden, "self is in the forbidden set") + assertTrue(grandchildId in forbidden, "a descendant is forbidden") + } + + @Test + fun aMalformedCyclicTreeTerminates() { + // child claims root as a child, so the tree already contains a cycle. The walk must stop, not hang. + val cyclic = + model().copy( + parts = + listOf( + part(rootId, listOf(OrgChild.Part(childId))), + part(childId, listOf(OrgChild.Part(rootId))), + ), + ) + assertEquals(setOf(rootId, childId), cyclic.partSelfAndDescendants(rootId)) + } + + @Test + fun aPartMissingFromTheListIsJustItself() { + assertEquals(setOf(PartId("ghost")), model().partSelfAndDescendants(PartId("ghost"))) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PuppetAtlasTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PuppetAtlasTest.kt new file mode 100644 index 0000000..763935c --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PuppetAtlasTest.kt @@ -0,0 +1,215 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Covers how a drawable resolves to its source art: which tile, whether it reads a packed page or the + * art directly, and which page's dimensions the mapping is built against. + * + * The packed-versus-direct decision is the load-bearing one. It used to be read off CMO3 resource + * identity at import; the model derives it instead, from whether the document's stored coordinates + * address the packed pages ([PuppetAtlas.storedUvsAddressPages]) and whether the tile was packed at + * all. Getting it wrong does not fail loudly - it silently swaps a drawable's UV editor between the + * layer frame and the atlas frame - so each arm is pinned here. + */ +class PuppetAtlasTest { + private fun drawable(rawId: String, tileId: String? = null): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + atlasTileId = tileId?.let { raw -> AtlasTileId(raw) }, + ) + + private fun modelOf(atlas: PuppetAtlas, fromSourceLayers: Boolean = false, vararg drawables: Drawable): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables.toList(), + rootChildren = drawables.map { entry -> OrgChild.Drawable(entry.id) }, + rootPartId = null, + rendersFromSourceLayers = fromSourceLayers, + atlas = atlas, + ) + + private fun packedTile(rawId: String, pageIndex: Int = 0): AtlasTile = + AtlasTile( + id = AtlasTileId(rawId), + name = "Art", + width = 8, + height = 16, + placement = AtlasPlacement(pageIndex, 4f, 6f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f), + ) + + private fun unpackedTile(rawId: String): AtlasTile = AtlasTile(AtlasTileId(rawId), "Art", 8, 16) + + @Test + fun aPackedTileInAtlasModeCarriesItsPlacementAndItsPageSize() { + val model = + modelOf( + PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(packedTile("t0"))), + drawables = arrayOf(drawable("a", "t0")), + ) + + val binding = assertNotNull(model.atlasBindingFor(model.drawables.single())) + assertEquals("t0", binding.layerKey) + assertNotNull(binding.placement, "a packed tile in atlas mode reads its page") + assertEquals(64, binding.pageWidth) + assertEquals(32, binding.pageHeight) + } + + @Test + fun aTileThatWasNeverPackedIsReadDirectly() { + val model = + modelOf( + PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(unpackedTile("t0"))), + drawables = arrayOf(drawable("a", "t0")), + ) + + val binding = assertNotNull(model.atlasBindingFor(model.drawables.single())) + assertNull(binding.placement, "art that was never packed is sampled where it lies") + assertTrue( + layerUvAffineOf(binding, 8, 16).contentEquals(identityUvAffine()), + "so its stored coordinates already address it and the mapping is the identity", + ) + } + + /** + * Which frame the stored coordinates are in is a fact about the FILE, not about what is on screen. + * + * A document whose drawables sample the packed pages has page-space coordinates whether or not the + * rigger is currently looking at the artwork - so toggling the display must not reinterpret them. + * Deriving the frame from the display mode looked right at import, where the two agree, and broke + * the moment anyone flipped the switch: the layer view drew every mesh at its atlas position. + */ + @Test + fun theDisplayModeDoesNotReinterpretStoredCoordinates() { + val atlas = PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(packedTile("t0"))) + val showingAtlas = modelOf(atlas, fromSourceLayers = false, drawables = arrayOf(drawable("a", "t0"))) + val showingArtwork = showingAtlas.copy(rendersFromSourceLayers = true) + + assertEquals( + showingAtlas.atlasBindingFor(showingAtlas.drawables.single()), + showingArtwork.atlasBindingFor(showingArtwork.drawables.single()), + "the mapping is the same either way - only which texture is sampled differs", + ) + assertNotNull( + showingArtwork.atlasBindingFor(showingArtwork.drawables.single())?.placement, + "packed art keeps its placement while the artwork is displayed", + ) + } + + /** + * A document saved sampling its per-layer rasters has coordinates that already address the art. + * + * The corpus case is a model saved in combined-layer display mode: a packed atlas sits beside it, + * but the drawables point at the layer images, so inverting a page-space placement over those + * coordinates would throw every mesh thousands of pixels away. + */ + @Test + fun aDocumentWhoseCoordinatesAddressTheArtMapsThroughTheIdentity() { + val model = + modelOf( + PuppetAtlas( + pages = listOf(AtlasPage(64, 32)), + tiles = listOf(packedTile("t0")), + storedUvsAddressPages = false, + ), + drawables = arrayOf(drawable("a", "t0")), + ) + + val binding = assertNotNull(model.atlasBindingFor(model.drawables.single())) + assertNull(binding.placement, "the coordinates already address the art, so recovery is the identity") + } + + @Test + fun aDrawableWithNoTileHasNoBinding() { + val model = + modelOf(PuppetAtlas(tiles = listOf(unpackedTile("t0"))), drawables = arrayOf(drawable("a"))) + + assertNull(model.atlasBindingFor(model.drawables.single()), "no tile means no source-art view") + } + + @Test + fun aPlacementNamingAMissingPageResolvesToNothingRatherThanTheIdentity() { + // Broken wiring, not a directly-sampled tile: answering "identity" would draw the mesh in the + // wrong frame instead of admitting the binding cannot be formed. + val model = + modelOf( + PuppetAtlas(pages = emptyList(), tiles = listOf(packedTile("t0", pageIndex = 3))), + drawables = arrayOf(drawable("a", "t0")), + ) + + assertNull(model.atlasBindingFor(model.drawables.single())) + } + + @Test + fun anUnknownTileIdResolvesToNothing() { + val model = modelOf(PuppetAtlas(tiles = listOf(unpackedTile("t0"))), drawables = arrayOf(drawable("a", "gone"))) + + assertNull(model.atlasBindingFor(model.drawables.single())) + assertNull(model.atlasBindingForTile(AtlasTileId("gone"))) + } + + @Test + fun everyDrawableOverOneTileSharesItsBinding() { + val model = + modelOf( + PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(packedTile("t0"))), + drawables = arrayOf(drawable("a", "t0"), drawable("b", "t0")), + ) + + val first = assertNotNull(model.atlasBindingFor(model.drawables[0])) + val second = assertNotNull(model.atlasBindingFor(model.drawables[1])) + assertEquals(first, second, "the placement belongs to the art, so its users cannot disagree") + assertEquals(first, model.atlasBindingForTile(AtlasTileId("t0")), "and the tile answers the same alone") + } + + @Test + fun theTileInverseNamesEveryDrawableInDocumentOrder() { + val model = + modelOf( + PuppetAtlas(tiles = listOf(unpackedTile("t0"), unpackedTile("t1"))), + drawables = arrayOf(drawable("a", "t0"), drawable("b", "t1"), drawable("c", "t0"), drawable("d")), + ) + + assertEquals( + mapOf( + AtlasTileId("t0") to listOf(DrawableId("a"), DrawableId("c")), + AtlasTileId("t1") to listOf(DrawableId("b")), + ), + model.drawableIdsByAtlasTile(), + "a drawable with no tile is absent, and the rest keep document order", + ) + } + + @Test + fun anEmptyAtlasReportsEmpty() { + assertTrue(PuppetAtlas.Empty.isEmpty) + assertTrue(PuppetAtlas(pages = listOf(AtlasPage(1, 1))).isEmpty.not(), "a page alone is still an atlas") + } + + /** + * A tile's source binding is document data that rides through every tile edit: a placement change + * copies the tile and must keep the binding, and a model with no linked art has no sources at all. + */ + @Test + fun aTileKeepsItsSourceBindingThroughAPlacementChange() { + val source = SourceLayerRef(ArtSourceId("art-0"), layerKey = "lyid:7", stableKey = true) + val tile = unpackedTile("t0").copy(source = source) + val placed = tile.copy(placement = AtlasPlacement(0, 1f, 2f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f)) + + assertEquals(source, placed.source, "the binding is what the tile IS, not where it packs") + assertNull(unpackedTile("t1").source, "a tile with no retained binding has none") + assertTrue(modelOf(PuppetAtlas.Empty).sources.isEmpty(), "a document with no linked art lists no sources") + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PuppetModelQueriesTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PuppetModelQueriesTest.kt new file mode 100644 index 0000000..b07eac2 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/PuppetModelQueriesTest.kt @@ -0,0 +1,111 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Unit-tests the per-drawable service queries in PuppetModelQueries: the pickable sets exclude + * hidden and mesh-less drawables, the part-name lookup follows the org tree, and the atlas key + * resolves a duplicate to its texture source. + */ +class PuppetModelQueriesTest { + private val meshedId = DrawableId("meshed") + private val hiddenId = DrawableId("hidden") + private val meshlessId = DrawableId("meshless") + private val duplicateId = DrawableId("duplicate") + + /** + * A quad mesh so pickable queries have geometry to report. + * + * @return DrawableMesh The mesh. + */ + private fun quadMesh(): DrawableMesh = + DrawableMesh( + positions = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 10f, 10f), + uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), + indices = intArrayOf(0, 1, 2, 1, 3, 2), + ) + + /** + * A minimal drawable for query tests. + * + * @param DrawableId id The drawable's id. + * @param DrawableMesh? mesh Its mesh, or null for a geometry-less drawable. + * @param Boolean isVisible Its own eyeball flag. + * @param DrawableId? textureSource Its texture source when it is a duplicate. + * @return Drawable The drawable. + */ + private fun drawable(id: DrawableId, mesh: DrawableMesh?, isVisible: Boolean = true, textureSource: DrawableId? = null): Drawable = + Drawable( + id = id, + name = id.raw, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = mesh, + geometryGrid = null, + isVisible = isVisible, + textureSourceId = textureSource, + ) + + /** + * A model with one part ("Face") owning the meshed drawable, plus hidden / mesh-less / duplicate + * drawables at the root. + * + * @return PuppetModel The fixture model. + */ + private fun model(): PuppetModel { + val facePart = Part(PartId("face"), "Face", children = listOf(OrgChild.Drawable(meshedId))) + return PuppetModel( + parameters = emptyList(), + parts = listOf(facePart), + deformers = emptyList(), + drawables = + listOf( + drawable(meshedId, quadMesh()), + drawable(hiddenId, quadMesh(), isVisible = false), + drawable(meshlessId, mesh = null), + drawable(duplicateId, quadMesh(), textureSource = meshedId), + ), + rootChildren = + listOf( + OrgChild.Part(PartId("face")), + OrgChild.Drawable(hiddenId), + OrgChild.Drawable(meshlessId), + OrgChild.Drawable(duplicateId), + ), + rootPartId = null, + ) + } + + @Test + fun pickableSetsExcludeHiddenAndMeshless() { + val model = model() + assertEquals(setOf(meshedId, duplicateId), model.pickableIndicesByDrawable().keys) + assertEquals(setOf(meshedId, duplicateId), model.pickableUvsByDrawable().keys) + } + + @Test + fun pickableGeometryMatchesTheMesh() { + val model = model() + val mesh = quadMesh() + assertEquals(mesh.indices.toList(), model.pickableIndicesByDrawable().getValue(meshedId).toList()) + assertEquals(mesh.uvs.toList(), model.pickableUvsByDrawable().getValue(meshedId).toList()) + } + + @Test + fun partNamesFollowTheOrgTree() { + val names = model().partNameByDrawable() + assertEquals("Face", names[meshedId]) + // Root-level drawables have no owning part, so no label entry. + assertNull(names[hiddenId]) + } + + @Test + fun atlasKeyResolvesDuplicateToItsSource() { + val keys = model().atlasKeyByDrawable() + assertEquals(meshedId.raw, keys[duplicateId]) + assertEquals(meshedId.raw, keys[meshedId]) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/RuntimeFeatureScanTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/RuntimeFeatureScanTest.kt new file mode 100644 index 0000000..af98672 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/RuntimeFeatureScanTest.kt @@ -0,0 +1,192 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the strip diff: a restricted feature is reported only when the document actually uses it, + * latent state never counts, and a supporting target reports nothing. + */ +class RuntimeFeatureScanTest { + private val drawableId = DrawableId("drawable") + private val partId = PartId("part") + private val deformerId = DeformerId("deformer") + private val parameterId = ParameterId("Param") + + private fun drawable( + blendMode: BlendMode = BlendMode.Normal, + alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over, + invertMask: Boolean = false, + multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity, + blendShapes: List> = emptyList(), + ): Drawable = + Drawable( + id = drawableId, + name = drawableId.raw, + parentDeformerId = null, + blendMode = blendMode, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + alphaBlendMode = alphaBlendMode, + invertMask = invertMask, + multiplyColor = multiplyColor, + blendShapes = blendShapes, + ) + + private fun model( + drawables: List = emptyList(), + parts: List = emptyList(), + deformers: List = emptyList(), + parameters: List = emptyList(), + ): PuppetModel = + PuppetModel( + parameters = parameters, + parts = parts, + deformers = deformers, + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) } + parts.map { part -> OrgChild.Part(part.id) }, + rootPartId = null, + ) + + @Test + fun bareModelReportsNothingUnderAnyTarget() { + val bare = model() + RuntimeTarget.entries.forEach { target -> + assertEquals(emptySet(), bare.unsupportedFeaturesInUse(target), "bare model under $target") + } + } + + @Test + fun supportingTargetsReportNothing() { + val kitchenSink = + model( + drawables = listOf(drawable(blendMode = BlendMode.Overlay, invertMask = true)), + parts = listOf(Part(partId, "part", children = emptyList(), groupMode = PartGroupMode.Isolated)), + ) + assertEquals(emptySet(), kitchenSink.unsupportedFeaturesInUse(RuntimeTarget.NoTarget)) + assertEquals(emptySet(), kitchenSink.unsupportedFeaturesInUse(RuntimeTarget.Cubism53)) + } + + @Test + fun isolatedPartReportsPartCompositeOnly() { + val isolated = model(parts = listOf(Part(partId, "part", children = emptyList(), groupMode = PartGroupMode.Isolated))) + assertEquals(setOf(RuntimeFeature.PartComposite), isolated.unsupportedFeaturesInUse(RuntimeTarget.Cubism50)) + } + + @Test + fun latentCompositeDoesNotCount() { + // A PassThrough part with stored composite settings is invisible to the runtime - not "in use". + val latent = + model( + parts = + listOf( + Part( + partId, + "part", + children = emptyList(), + groupMode = PartGroupMode.PassThrough, + composite = PartComposite(blendMode = BlendMode.Overlay, invertMask = true), + ), + ), + ) + assertEquals(emptySet(), latent.unsupportedFeaturesInUse(RuntimeTarget.Cubism30)) + } + + @Test + fun extendedBlendModesCoverColorAndAlpha() { + val extendedColor = model(drawables = listOf(drawable(blendMode = BlendMode.Overlay))) + assertEquals(setOf(RuntimeFeature.ExtendedBlendModes), extendedColor.unsupportedFeaturesInUse(RuntimeTarget.Cubism50)) + val extendedAlpha = model(drawables = listOf(drawable(alphaBlendMode = AlphaBlendMode.Atop))) + assertEquals(setOf(RuntimeFeature.ExtendedBlendModes), extendedAlpha.unsupportedFeaturesInUse(RuntimeTarget.Cubism50)) + } + + @Test + fun reversedMaskReportsBelowFourOh() { + val inverted = model(drawables = listOf(drawable(invertMask = true))) + assertEquals(setOf(RuntimeFeature.ReversedMask), inverted.unsupportedFeaturesInUse(RuntimeTarget.Cubism33)) + assertEquals(emptySet(), inverted.unsupportedFeaturesInUse(RuntimeTarget.Cubism40)) + } + + @Test + fun multiplyColorStaticReportsBelowFourTwo() { + val tinted = model(drawables = listOf(drawable(multiplyColor = ColorRgb(0.5f, 0.5f, 0.5f)))) + assertEquals(setOf(RuntimeFeature.MultiplyColor), tinted.unsupportedFeaturesInUse(RuntimeTarget.Cubism40)) + assertEquals(emptySet(), tinted.unsupportedFeaturesInUse(RuntimeTarget.Cubism42)) + } + + @Test + fun quadWarpReportsBelowThreeThree() { + val quadWarp = + model( + deformers = + listOf( + Deformer.Warp( + id = deformerId, + name = "warp", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = true, + geometryGrid = null, + ), + ), + ) + assertEquals(setOf(RuntimeFeature.WarpQuadTransform), quadWarp.unsupportedFeaturesInUse(RuntimeTarget.Cubism30)) + assertEquals(emptySet(), quadWarp.unsupportedFeaturesInUse(RuntimeTarget.Cubism33)) + } + + @Test + fun rotationBlendShapesReportBelowFiveOh() { + val binding = BlendShapeBinding(parameterId, floatArrayOf(0f, 1f), 0, listOf(null, null)) + val rotation = + model( + deformers = + listOf( + Deformer.Rotation( + id = deformerId, + name = "rotation", + parent = null, + partId = null, + baseAngle = 0f, + geometryGrid = null, + blendShapes = listOf(binding), + ), + ), + ) + assertEquals(setOf(RuntimeFeature.ExtendedBlendShapes), rotation.unsupportedFeaturesInUse(RuntimeTarget.Cubism42)) + assertEquals(emptySet(), rotation.unsupportedFeaturesInUse(RuntimeTarget.Cubism50)) + } + + @Test + fun blendShapeParametersReportBelowFourTwo() { + val blendShapeParameter = model(parameters = listOf(Parameter(parameterId, "Param", 0f, 1f, 0f, ParameterKind.BLEND_SHAPE))) + assertEquals( + setOf(RuntimeFeature.BlendShapeParameters), + blendShapeParameter.unsupportedFeaturesInUse(RuntimeTarget.Cubism40), + ) + assertEquals(emptySet(), blendShapeParameter.unsupportedFeaturesInUse(RuntimeTarget.Cubism42)) + } + + @Test + fun partMasksAreNotAFeature() { + // Part-typed composite masks decompose to drawable ids at the CMO3/MOC3 boundary, so their use + // is never reported under any target - only the offscreen composite itself is a 5.3 feature. + val partMasked = + model( + parts = + listOf( + Part( + partId, + "part", + children = emptyList(), + groupMode = PartGroupMode.Isolated, + composite = PartComposite(maskedByParts = listOf(partId)), + ), + ), + ) + assertEquals(emptySet(), partMasked.unsupportedFeaturesInUse(RuntimeTarget.Cubism53)) + assertEquals(setOf(RuntimeFeature.PartComposite), partMasked.unsupportedFeaturesInUse(RuntimeTarget.Cubism50)) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/RuntimeTargetTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/RuntimeTargetTest.kt new file mode 100644 index 0000000..9c72cac --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/RuntimeTargetTest.kt @@ -0,0 +1,77 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the runtime repository's capability matrix to the official Cubism Editor's "Model target + * version selection" dialog, both sides of every version boundary. (The format-version mapping + * each target persists as is pinned in :interop's RuntimeTargetMappingTest.) + */ +class RuntimeTargetTest { + @Test + fun featureBoundariesMatchTheOfficialDialog() { + // New warp deformer method: SDK3.3+. + assertTrue(!RuntimeTarget.Cubism30.supports(RuntimeFeature.WarpQuadTransform)) + assertTrue(RuntimeTarget.Cubism33.supports(RuntimeFeature.WarpQuadTransform)) + // Reversed Mask: SDK4.0+. + assertTrue(!RuntimeTarget.Cubism33.supports(RuntimeFeature.ReversedMask)) + assertTrue(RuntimeTarget.Cubism40.supports(RuntimeFeature.ReversedMask)) + // Blend Shape (art mesh + warp), blend-shape parameters, multiply color, screen color: SDK4.2+. + listOf( + RuntimeFeature.MeshWarpBlendShapes, + RuntimeFeature.BlendShapeParameters, + RuntimeFeature.MultiplyColor, + RuntimeFeature.ScreenColor, + ).forEach { feature -> + assertTrue(!RuntimeTarget.Cubism40.supports(feature), "$feature is 4.2+, not 4.0") + assertTrue(RuntimeTarget.Cubism42.supports(feature), "$feature is supported at 4.2") + } + // Blend Shape (part / rotation / glue / scalar) and motion-sync: SDK5.0+. + listOf(RuntimeFeature.ExtendedBlendShapes, RuntimeFeature.MotionSync).forEach { feature -> + assertTrue(!RuntimeTarget.Cubism42.supports(feature), "$feature is 5.0+, not 4.2") + assertTrue(RuntimeTarget.Cubism50.supports(feature), "$feature is supported at 5.0") + } + // Blend mode, offscreen drawing, parameter repeat: SDK5.3+. + listOf(RuntimeFeature.ExtendedBlendModes, RuntimeFeature.PartComposite, RuntimeFeature.ParameterRepeat) + .forEach { feature -> + assertTrue(!RuntimeTarget.Cubism50.supports(feature), "$feature is 5.3+, not 5.0") + assertTrue(RuntimeTarget.Cubism53.supports(feature), "$feature is supported at 5.3") + } + // ArtPath is "Latest Cubism only": no Cubism ceiling allows it. + assertTrue(!RuntimeTarget.Cubism53.supports(RuntimeFeature.ArtPath), "ArtPath is beyond every Cubism target") + assertTrue(RuntimeTarget.NoTarget.supports(RuntimeFeature.ArtPath), "ArtPath is authorable with no target") + } + + @Test + fun restrictedListsDeriveFromTheMatrix() { + assertEquals(emptyList(), RuntimeTarget.NoTarget.restrictedFeatures(), "NoTarget restricts nothing") + assertEquals( + RuntimeTarget.Cubism50.restrictedFeatures(), + RuntimeTarget.Ayagami.restrictedFeatures(), + "Ayagami is effectively Cubism 5.0 at present", + ) + assertEquals(listOf(RuntimeFeature.ArtPath), RuntimeTarget.Cubism53.restrictedFeatures()) + assertEquals( + RuntimeFeature.entries.toList(), + RuntimeTarget.Cubism30.restrictedFeatures(), + "every feature postdates Cubism 3.0", + ) + } + + @Test + fun displayNamesAreDistinctAndNonBlank() { + val names = RuntimeTarget.entries.map { target -> target.displayName } + assertEquals(names.size, names.toSet().size, "display names are distinct") + assertTrue(names.none { name -> name.isBlank() }, "display names are non-blank") + } + + @Test + fun cubismLevelTextTracksTheGatingLevel() { + assertNull(RuntimeTarget.NoTarget.cubismLevelText(), "no ceiling, no text") + assertEquals("5.0", RuntimeTarget.Ayagami.cubismLevelText(), "the Ayagami label's level feed") + assertEquals("3.3", RuntimeTarget.Cubism33.cubismLevelText()) + } +} \ No newline at end of file diff --git a/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/VisibilityCascadeTest.kt b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/VisibilityCascadeTest.kt new file mode 100644 index 0000000..7e97a36 --- /dev/null +++ b/module/runtime/src/commonTest/kotlin/org/umamo/runtime/model/VisibilityCascadeTest.kt @@ -0,0 +1,59 @@ +package org.umamo.runtime.model + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Unit-tests [visibleDrawableIds]: the Parts-panel eyeball cascades down the org tree, so a drawable is + * shown only when its own flag and every ancestor part are visible. Corpus-free - a hand-built tree + * exercises own-hidden, direct-parent-hidden, ancestor-hidden, and root-level (no part) cases. + */ +class VisibilityCascadeTest { + private fun drawable(id: String, isVisible: Boolean): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + isVisible = isVisible, + ) + + @Test + fun cascadesEyeballThroughAncestorParts() { + val parts = + listOf( + Part(PartId("root"), "Root", listOf(OrgChild.Part(PartId("hidden")), OrgChild.Part(PartId("shown"))), isVisible = true), + Part( + PartId("hidden"), + "[Guide Image]", + listOf(OrgChild.Part(PartId("grandchild")), OrgChild.Drawable(DrawableId("inHidden"))), + isVisible = false, + ), + Part(PartId("grandchild"), "Under Hidden", listOf(OrgChild.Drawable(DrawableId("underHidden"))), isVisible = true), + Part( + PartId("shown"), + "Visible Folder", + listOf(OrgChild.Drawable(DrawableId("inShown")), OrgChild.Drawable(DrawableId("ownHidden"))), + isVisible = true, + ), + ) + val drawables = + listOf( + drawable("inHidden", isVisible = true), // parent hidden → excluded + drawable("underHidden", isVisible = true), // grandparent hidden → excluded + drawable("inShown", isVisible = true), // all visible → shown + drawable("ownHidden", isVisible = false), // own eyeball off → excluded + drawable("rootLevel", isVisible = true), // no part → shown + ) + // Top level: the "root" folder plus a loose root-level mesh. + val rootChildren = listOf(OrgChild.Part(PartId("root")), OrgChild.Drawable(DrawableId("rootLevel"))) + val model = PuppetModel(emptyList(), parts, emptyList(), drawables, rootChildren, rootPartId = PartId("root")) + + val shown = model.visibleDrawableIds() + + assertEquals(setOf(DrawableId("inShown"), DrawableId("rootLevel")), shown) + } +} \ No newline at end of file diff --git a/module/settings/build.gradle.kts b/module/settings/build.gradle.kts new file mode 100644 index 0000000..ba77f80 --- /dev/null +++ b/module/settings/build.gradle.kts @@ -0,0 +1,41 @@ +// :settings — JSON settings engine over :storage: bundled defaults ← user overrides (← vendor later), +// dotted-key get/set, persistence, and a change-event Flow. → :storage, kotlinx-serialization, coroutines. +// :settings — :storage 上の JSON 設定エンジン。デフォルト←ユーザー設定の重ね合わせ、ドットキー get/set、変更通知。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + alias(libs.plugins.kotlinSerialization) +} + +kotlin { + jvmToolchain(21) + + jvm() + + android { + namespace = "org.umamo.settings" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + commonMain { + dependencies { + // `api`: AppStorage + JsonElement appear in the Settings surface, so consumers see them. + api(project(":storage")) + api(libs.kotlinxSerializationJson) + implementation(libs.kotlinxCoroutinesCore) + } + } + commonTest { + dependencies { + implementation(kotlin("test")) + // In-memory FileSystem so settings load/merge/persist is tested with no real disk. + implementation(libs.okio.fakefilesystem) + // runTest for the change-event Flow assertion. + implementation(libs.kotlinxCoroutinesTest) + } + } + } +} \ No newline at end of file diff --git a/module/settings/src/commonMain/kotlin/org/umamo/settings/Settings.kt b/module/settings/src/commonMain/kotlin/org/umamo/settings/Settings.kt new file mode 100644 index 0000000..c0451e4 --- /dev/null +++ b/module/settings/src/commonMain/kotlin/org/umamo/settings/Settings.kt @@ -0,0 +1,154 @@ +package org.umamo.settings + +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.doubleOrNull +import kotlinx.serialization.json.intOrNull +import org.umamo.storage.AppStorage + +/** + * The app's settings: a merged JSON tree of bundled defaults ← user overrides (← vendor extension + * defaults, later), addressed by dotted keys (`getString("interface.theme")`). No caller ever passes a + * default - `defaultSettings.json` is the single source of baseline values, so reads are + * default-by-construction. Writes go to the user layer only, re-merge, persist via [AppStorage], and emit + * the changed key on [changes] (the reactive spine the UI/keymap/History collect). + * + * Build it with [Settings.load]. The tree is held as a dynamic [JsonObject] (not typed `@Serializable` + * classes) because settings are open-ended and merged; typed per-domain views can layer on top later. + * + * @property Boolean foundUserFile Whether a user settings file was on disk when these settings loaded - false + * on a first launch. A fact about the load, so it stays false for this instance's whole life, even after + * the first write creates the file. A file that exists but does not parse still counts as found. + */ +class Settings private constructor( + private val storage: AppStorage, + private val userFile: okio.Path, + private val defaults: JsonObject, + private var user: JsonObject, + val foundUserFile: Boolean, +) { + private var merged: JsonObject = deepMerge(defaults, user) + + private val mutableChanges = MutableSharedFlow(extraBufferCapacity = 64) + + /** Emits a setting's dotted key whenever it is written, so consumers re-read just what changed. */ + val changes: SharedFlow = mutableChanges.asSharedFlow() + + /** + * Resolves a dotted [key] to its merged value. + * + * @param String key Dotted key, e.g. `"input.keybinding.preset"`. + * @return JsonElement? The value (user override, else default), or null if absent. + */ + fun get(key: String): JsonElement? { + var current: JsonElement = merged + for (segment in key.split('.')) { + current = (current as? JsonObject)?.get(segment) ?: return null + } + return current + } + + /** @return String? The [key]'s string value, or null if absent / not a string. */ + fun getString(key: String): String? = (get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content + + /** @return Boolean? The [key]'s boolean value, or null if absent / not a boolean. */ + fun getBoolean(key: String): Boolean? = (get(key) as? JsonPrimitive)?.booleanOrNull + + /** @return Int? The [key]'s integer value, or null if absent / not an integer. */ + fun getInt(key: String): Int? = (get(key) as? JsonPrimitive)?.intOrNull + + /** @return Double? The [key]'s number value, or null if absent / not a number. */ + fun getDouble(key: String): Double? = (get(key) as? JsonPrimitive)?.doubleOrNull + + /** Sets a string value at [key]. */ + fun setString(key: String, value: String) = set(key, JsonPrimitive(value)) + + /** Sets a boolean value at [key]. */ + fun setBoolean(key: String, value: Boolean) = set(key, JsonPrimitive(value)) + + /** Sets an integer value at [key]. */ + fun setInt(key: String, value: Int) = set(key, JsonPrimitive(value)) + + /** Sets a number value at [key]. */ + fun setDouble(key: String, value: Double) = set(key, JsonPrimitive(value)) + + /** + * Writes [value] into the user layer at dotted [key] (creating intermediate objects), re-merges over + * the defaults, persists the user layer, and emits [key] on [changes]. + * + * @param Path key Dotted key. + * @param JsonElement value The value to store. + */ + fun set(key: String, value: JsonElement) { + user = putAtPath(user, key.split('.'), value) + merged = deepMerge(defaults, user) + storage.writeText(userFile, JSON.encodeToString(JsonObject.serializer(), user)) + mutableChanges.tryEmit(key) + } + + companion object { + private val JSON = + Json { + ignoreUnknownKeys = true + prettyPrint = true + } + + /** + * Loads settings: parses bundled [defaultSettingsJson] as the baseline and overlays the user file + * ([fileName] under [storage]'s config directory) if present and valid. A missing or corrupt user + * file falls back to defaults-only (never throws). + * + * @param AppStorage storage Where the user file lives + IO. + * @param String defaultSettingsJson The bundled `defaultSettings.json` contents. + * @param String fileName The user settings file name under the config directory. + * @return Settings The loaded settings. + */ + fun load(storage: AppStorage, defaultSettingsJson: String, fileName: String = "settings.json"): Settings { + val defaults = parseObjectOrEmpty(defaultSettingsJson) + val userFile = storage.configDirectory / fileName + val userText = storage.readText(userFile) + val user = userText?.let { parseObjectOrEmpty(it) } ?: JsonObject(emptyMap()) + return Settings(storage, userFile, defaults, user, foundUserFile = userText != null) + } + + /** Parses [text] to a [JsonObject], or an empty object when it is absent/blank/not an object/invalid. */ + private fun parseObjectOrEmpty(text: String): JsonObject = + runCatching { JSON.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap()) + + /** Deep-merges [overlay] onto [base]: nested objects merge recursively; any other value is replaced. */ + private fun deepMerge(base: JsonObject, overlay: JsonObject): JsonObject { + val result = base.toMutableMap() + for ((key, overlayValue) in overlay) { + val baseValue = result[key] + result[key] = + if (baseValue is JsonObject && overlayValue is JsonObject) { + deepMerge(baseValue, overlayValue) + } else { + overlayValue + } + } + return JsonObject(result) + } + + /** Returns a copy of [root] with [value] set at the dotted [path], creating intermediate objects. */ + private fun putAtPath(root: JsonObject, path: List, value: JsonElement): JsonObject { + if (path.isEmpty()) { + return root + } + val head = path.first() + val child = + if (path.size == 1) { + value + } else { + putAtPath(root[head] as? JsonObject ?: JsonObject(emptyMap()), path.drop(1), value) + } + return JsonObject(root.toMutableMap().apply { put(head, child) }) + } + } +} \ No newline at end of file diff --git a/module/settings/src/commonTest/kotlin/org/umamo/settings/SettingsTest.kt b/module/settings/src/commonTest/kotlin/org/umamo/settings/SettingsTest.kt new file mode 100644 index 0000000..2170a34 --- /dev/null +++ b/module/settings/src/commonTest/kotlin/org/umamo/settings/SettingsTest.kt @@ -0,0 +1,170 @@ +package org.umamo.settings + +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import okio.Path +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.storage.OkioAppStorage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** Settings load/merge/get/set/persist + change-event coverage, all on okio's in-memory FakeFileSystem. */ +class SettingsTest { + private val configDir: Path = "/config".toPath() + + /** A FakeFileSystem seeded with an optional user settings file, plus an [OkioAppStorage] over it. */ + private fun storageWith(userJson: String? = null): Pair { + val fileSystem = FakeFileSystem() + fileSystem.createDirectories(configDir) + if (userJson != null) { + fileSystem.write(configDir / "settings.json") { writeUtf8(userJson) } + } + return fileSystem to OkioAppStorage(fileSystem, configDir, "/data".toPath()) + } + + @Test + fun readsDefaultsWhenNoUserFile() { + val (_, storage) = storageWith() + val settings = Settings.load(storage, """{"interface":{"theme":"dark"},"localization":{"locale":"en"}}""") + assertEquals("dark", settings.getString("interface.theme")) + assertEquals("en", settings.getString("localization.locale")) + assertNull(settings.getString("does.not.exist")) + } + + @Test + fun userOverridesDefaultsButKeepsUnsetSiblings() { + val (_, storage) = storageWith(userJson = """{"interface":{"theme":"light"}}""") + val settings = Settings.load(storage, """{"interface":{"theme":"dark","fontSize":12}}""") + assertEquals("light", settings.getString("interface.theme")) // overridden + assertEquals(12, settings.getInt("interface.fontSize")) // default kept (deep merge, not replace) + } + + @Test + fun typedGettersParsePrimitives() { + val (_, storage) = storageWith() + val settings = Settings.load(storage, """{"a":{"flag":true,"count":7,"ratio":0.5,"name":"x"}}""") + assertEquals(true, settings.getBoolean("a.flag")) + assertEquals(7, settings.getInt("a.count")) + assertEquals(0.5, settings.getDouble("a.ratio")) + assertEquals("x", settings.getString("a.name")) + assertNull(settings.getInt("a.name")) // wrong type → null, not a throw + } + + @Test + fun setWritesUserLayerAndSurvivesReload() { + val (fileSystem, storage) = storageWith() + val settings = Settings.load(storage, """{"interface":{"theme":"dark","fontSize":12}}""") + settings.setString("interface.theme", "light") + settings.setInt("interface.fontSize", 16) + + // A fresh load over the same filesystem sees the persisted user overrides on top of the defaults. + val reloaded = Settings.load(OkioAppStorage(fileSystem, configDir, "/data".toPath()), """{"interface":{"theme":"dark","fontSize":12}}""") + assertEquals("light", reloaded.getString("interface.theme")) + assertEquals(16, reloaded.getInt("interface.fontSize")) + } + + @Test + fun corruptUserFileFallsBackToDefaults() { + val (_, storage) = storageWith(userJson = "{ this is not json") + val settings = Settings.load(storage, """{"interface":{"theme":"dark"}}""") + assertEquals("dark", settings.getString("interface.theme")) // no throw; defaults stand + } + + @Test + fun foundUserFileIsFalseWithNoFile() { + val (_, storage) = storageWith() + assertFalse(Settings.load(storage, "{}").foundUserFile) + } + + @Test + fun foundUserFileIsTrueWithAValidFile() { + val (_, storage) = storageWith(userJson = """{"interface":{"theme":"light"}}""") + assertTrue(Settings.load(storage, "{}").foundUserFile) + } + + @Test + fun foundUserFileIsTrueWithACorruptFile() { + // Present but unreadable is still found: the rigger's settings exist, they just did not parse. + val (_, storage) = storageWith(userJson = "{ this is not json") + assertTrue(Settings.load(storage, "{}").foundUserFile) + } + + @Test + fun foundUserFileStaysFalseAfterTheFirstWrite() { + val (fileSystem, storage) = storageWith() + val settings = Settings.load(storage, """{"a":{"b":1}}""") + settings.setInt("a.b", 2) + // The write created the file, but the flag describes the load, not the disk now. + assertTrue(fileSystem.exists(configDir / "settings.json")) + assertFalse(settings.foundUserFile) + // The next load finds it. + assertTrue(Settings.load(OkioAppStorage(fileSystem, configDir, "/data".toPath()), "{}").foundUserFile) + } + + @Test + fun setEmitsChangedKey() = + runTest { + val (_, storage) = storageWith() + val settings = Settings.load(storage, """{"a":{"b":1}}""") + val received = mutableListOf() + val collector = launch { settings.changes.collect { received.add(it) } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() // let the collector subscribe before we emit + settings.setInt("a.b", 2) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() // deliver the emission + collector.cancel() + assertEquals(listOf("a.b"), received) + assertTrue(settings.getInt("a.b") == 2) + } + + @Test + fun sequentialSetsEmitTheirKeysInOrder() = + runTest { + val (_, storage) = storageWith() + val settings = Settings.load(storage, """{"a":{"b":1,"c":"x"},"d":{"e":true}}""") + val received = mutableListOf() + val collector = launch { settings.changes.collect { received.add(it) } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + settings.setInt("a.b", 2) + settings.setString("a.c", "y") + settings.setBoolean("d.e", false) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + collector.cancel() + assertEquals(listOf("a.b", "a.c", "d.e"), received) + } + + @Test + fun lateSubscriberReceivesOnlySubsequentEvents() = + runTest { + val (_, storage) = storageWith() + val settings = Settings.load(storage, """{"a":{"b":1,"c":"x"}}""") + val earlyEvents = mutableListOf() + val earlyCollector = launch { settings.changes.collect { earlyEvents.add(it) } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + settings.setInt("a.b", 2) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + // The changes flow has no replay: a subscriber arriving after an event never sees it. + val lateEvents = mutableListOf() + val lateCollector = launch { settings.changes.collect { lateEvents.add(it) } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + settings.setString("a.c", "y") + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + earlyCollector.cancel() + lateCollector.cancel() + assertEquals(listOf("a.b", "a.c"), earlyEvents) + assertEquals(listOf("a.c"), lateEvents) + } +} \ No newline at end of file diff --git a/module/storage/build.gradle.kts b/module/storage/build.gradle.kts new file mode 100644 index 0000000..81c3e04 --- /dev/null +++ b/module/storage/build.gradle.kts @@ -0,0 +1,43 @@ +// :storage — multiplatform app-file foundation: per-OS config/data directories, file IO (okio), and a +// native open/save dialog contract. The low-level base :settings (and later the editor UI) build on. +// :storage — マルチプラットフォームのアプリ保存基盤:OS 別の設定/データ場所、ファイル IO(okio)、ファイルダイアログ契約。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) +} + +kotlin { + jvmToolchain(21) + + jvm() + + android { + namespace = "org.umamo.storage" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + commonMain { + dependencies { + // `api` (not `implementation`): okio's `Path`/`FileSystem` appear in AppStorage's public + // surface, so consumers (:settings, apps) see them transitively. + api(libs.okio) + // `api` again: FileKit's `PlatformFile` is the FilePicker contract's return type, and the + // apps call `FileKit.init`, so both must reach consumers transitively. Pulls filekit-core. + api(libs.filekitDialogs) + // `api` because UmamoLog's retained-log buffer exposes a StateFlow in its public surface, so + // consumers (the UI's Logs panel) see kotlinx-coroutines transitively - same rule as okio/FileKit. + api(libs.kotlinxCoroutinesCore) + } + } + commonTest { + dependencies { + implementation(kotlin("test")) + // okio's in-memory FileSystem, so OkioAppStorage's tests run with no real disk. + implementation(libs.okio.fakefilesystem) + } + } + } +} \ No newline at end of file diff --git a/module/storage/src/androidMain/kotlin/org/umamo/storage/AndroidStorage.kt b/module/storage/src/androidMain/kotlin/org/umamo/storage/AndroidStorage.kt new file mode 100644 index 0000000..007fdec --- /dev/null +++ b/module/storage/src/androidMain/kotlin/org/umamo/storage/AndroidStorage.kt @@ -0,0 +1,24 @@ +package org.umamo.storage + +import android.content.Context +import okio.FileSystem +import okio.Path.Companion.toPath + +/** + * Builds the Android [AppStorage] from a [Context]: app-private internal storage (`filesDir`), split into + * `config/` and `data/` subdirectories. Android sandboxes each app, so there is no XDG-style global split - + * [applicationName] is accepted only for API symmetry with `desktopAppStorage`. + * + * The [FilePicker] is not platform-specific: [FileKitFilePicker] (commonMain) drives the Storage + * Access Framework through FileKit. The Android app only needs to call `FileKit.init(activity)` once in its + * Activity (it owns the result registry); no separate Android picker implementation is required. + * + * @param Context context The application context. + * @param String applicationName Unused on Android (sandboxed); for symmetry with desktop. + * @return AppStorage The Android storage. + */ +@Suppress("UNUSED_PARAMETER") +fun androidAppStorage(context: Context, applicationName: String = "umamo"): AppStorage { + val base = context.filesDir.absolutePath.toPath() + return OkioAppStorage(FileSystem.SYSTEM, configDirectory = base / "config", dataDirectory = base / "data") +} \ No newline at end of file diff --git a/module/storage/src/androidMain/kotlin/org/umamo/storage/PlatformFiles.android.kt b/module/storage/src/androidMain/kotlin/org/umamo/storage/PlatformFiles.android.kt new file mode 100644 index 0000000..3d92751 --- /dev/null +++ b/module/storage/src/androidMain/kotlin/org/umamo/storage/PlatformFiles.android.kt @@ -0,0 +1,32 @@ +package org.umamo.storage + +import android.net.Uri +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.write +import java.io.File + +/** + * Android actual: a Storage Access Framework pick stores a `content://` URI string (there is no real + * filesystem path behind it), so it routes back through a Uri; anything else is a plain file path. + * Reopening a content URI across process restarts may still be refused until persistable URI + * permissions are taken — callers treat a failed open as a soft miss. + * + * @param String path The stored path or URI string. + * @return PlatformFile The reconstructed file handle. + */ +actual fun platformFileFromSavedPath(path: String): PlatformFile = + if (path.startsWith("content://")) { + PlatformFile(Uri.parse(path)) + } else { + PlatformFile(File(path)) + } + +/** + * Android actual: a Storage Access Framework uri has no directory to stage a temporary in and cannot be + * renamed over, so the bytes are written in place - complete in memory before the write begins. + * + * @param ByteArray bytes The complete contents. + */ +actual suspend fun PlatformFile.writeReplacing(bytes: ByteArray) { + write(bytes) +} \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/AppStorage.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/AppStorage.kt new file mode 100644 index 0000000..19b72a9 --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/AppStorage.kt @@ -0,0 +1,69 @@ +package org.umamo.storage + +import okio.FileSystem +import okio.Path + +/** + * The app's file foundation: where its config/data live (per-OS) and read/write over those locations. + * The platform factories (`desktopAppStorage`, `androidAppStorage`) resolve the directories; everything + * else is shared. Backed by okio so one API covers desktop and Android - Kotlin's stdlib has no common + * `File` type, and `java.io.File` is JVM-only. + */ +interface AppStorage { + /** Per-user config directory (small JSON: settings, keymaps, layout). Parents created on write. */ + val configDirectory: Path + + /** Per-user data directory (larger app data, caches). */ + val dataDirectory: Path + + /** + * Reads [path] as UTF-8 text. + * + * @param Path path The file to read. + * @return String? The contents, or null if the file does not exist. + */ + fun readText(path: Path): String? + + /** + * Writes [text] to [path] as UTF-8, creating parent directories as needed. + * + * @param Path path The destination file. + * @param String text The contents to write. + */ + fun writeText(path: Path, text: String) + + /** + * @param Path path The path to test. + * @return Boolean Whether [path] exists. + */ + fun exists(path: Path): Boolean +} + +/** + * okio-backed [AppStorage]: directories come from the platform factory; IO goes through the supplied + * [fileSystem] - the real one on a device, or okio's `FakeFileSystem` in tests (so settings logic is + * testable with no real disk). + * + * @property FileSystem fileSystem The filesystem to read/write through. + * @property Path configDirectory Resolved config directory. + * @property Path dataDirectory Resolved data directory. + */ +class OkioAppStorage( + private val fileSystem: FileSystem, + override val configDirectory: Path, + override val dataDirectory: Path, +) : AppStorage { + override fun readText(path: Path): String? = + if (fileSystem.exists(path)) { + fileSystem.read(path) { readUtf8() } + } else { + null + } + + override fun writeText(path: Path, text: String) { + path.parent?.let { fileSystem.createDirectories(it) } + fileSystem.write(path) { writeUtf8(text) } + } + + override fun exists(path: Path): Boolean = fileSystem.exists(path) +} \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/ContentHash.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/ContentHash.kt new file mode 100644 index 0000000..bf48a4d --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/ContentHash.kt @@ -0,0 +1,25 @@ +package org.umamo.storage + +import okio.FileSystem +import okio.HashingSource +import okio.Path +import okio.blackholeSink +import okio.buffer + +/** + * The content hash of the file at [path], streamed rather than loaded - an artwork file can run to + * hundreds of megabytes, and the watcher hashes it on every settled save. The same digest as + * :format's contentHashOf (SHA-256 as lowercase hex), which is where the algorithm is named. + * + * @param FileSystem fileSystem The file system to read through. + * @param Path path The file. + * @return String? The digest as lowercase hex, or null when the file cannot be read (missing, being + * written, or refused). + */ +fun contentHashOfFile(fileSystem: FileSystem, path: Path): String? = + runCatching { + HashingSource.sha256(fileSystem.source(path)).use { hashing -> + hashing.buffer().use { source -> source.readAll(blackholeSink()) } + hashing.hash.hex() + } + }.getOrNull() \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/FileKitFilePicker.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/FileKitFilePicker.kt new file mode 100644 index 0000000..b3d4560 --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/FileKitFilePicker.kt @@ -0,0 +1,38 @@ +package org.umamo.storage + +import io.github.vinceglb.filekit.FileKit +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.dialogs.FileKitType +import io.github.vinceglb.filekit.dialogs.openFilePicker +import io.github.vinceglb.filekit.dialogs.openFileSaver + +/** + * The [FilePicker] over FileKit's native dialogs. FileKit already abstracts each platform's picker (Win32 / + * Cocoa / GTK on desktop, Storage Access Framework on Android), so this single commonMain implementation + * serves every platform, including Android once the Activity calls `FileKit.init`. + * + * `FileKit.init` must run once at startup before any call here (desktop: in `main`; Android: in the Activity). + */ +class FileKitFilePicker : FilePicker { + override suspend fun openFile(extensions: List): PlatformFile? = + FileKit.openFilePicker(type = fileKitType(extensions)) + + override suspend fun saveFile(suggestedName: String, extension: String): PlatformFile? = + // `defaultExtension` is the hint FileKit appends to the saved name (the `extension` arg is deprecated). + FileKit.openFileSaver(suggestedName = suggestedName, defaultExtension = extension) + + /** + * Maps our extension allow-list to a FileKit type filter: a specific [FileKitType.File] when extensions + * are given, or the unfiltered "any file" type when the list is empty (an empty filter would otherwise + * mean "allow nothing"). + * + * @param List extensions Allowed extensions without the dot; empty = any. + * @return FileKitType The matching FileKit type filter. + */ + private fun fileKitType(extensions: List): FileKitType = + if (extensions.isEmpty()) { + FileKitType.File() + } else { + FileKitType.File(extensions) + } +} \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/FilePicker.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/FilePicker.kt new file mode 100644 index 0000000..23d4932 --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/FilePicker.kt @@ -0,0 +1,32 @@ +package org.umamo.storage + +import io.github.vinceglb.filekit.PlatformFile + +/** + * A native open/save file dialog - a platform service (not Compose UI), so it belongs in :storage with the + * other file concerns. Backed by FileKit ([org.umamo.storage.FileKitFilePicker]), which already speaks each + * platform's native dialog, so the single implementation covers desktop and Android alike. + * + * Returns a FileKit [PlatformFile] rather than an okio `Path`: on Android the Storage Access Framework hands + * back a `content://` URI that has no real filesystem path, which a `Path` cannot represent - `PlatformFile` + * abstracts that and exposes read/write directly. Suspending so the (potentially async) native flow is + * awaited the same way on every platform. + */ +interface FilePicker { + /** + * Prompts the user to choose an existing file to open. + * + * @param List extensions Allowed extensions without the dot (e.g. `["cmo3", "psd"]`); empty = any. + * @return PlatformFile? The chosen file, or null if cancelled. + */ + suspend fun openFile(extensions: List): PlatformFile? + + /** + * Prompts the user to choose a destination to save to. + * + * @param String suggestedName Pre-filled file name without extension (e.g. "MyModel"). + * @param String extension Target extension without the dot (e.g. "cmo3"). + * @return PlatformFile? The chosen destination, or null if cancelled. + */ + suspend fun saveFile(suggestedName: String, extension: String): PlatformFile? +} \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/FileWrite.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/FileWrite.kt new file mode 100644 index 0000000..f8f121b --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/FileWrite.kt @@ -0,0 +1,50 @@ +package org.umamo.storage + +import okio.FileSystem +import okio.IOException +import okio.Path +import kotlin.random.Random + +/** + * Writes [bytes] over [target] without ever leaving a half-written file at [target]. + * + * The bytes go to a temporary sibling in the target's directory first, and only a complete temporary is + * moved over the target - one rename, which the file system makes atomic. If anything fails before the + * move, the target is untouched and the temporary is removed; if the move itself fails, the target is + * still whatever it was. A sibling rather than a system temp directory because a rename is atomic only + * within one file system. + * + * A process killed mid-write (a crash, a power cut, a forced quit) cannot run that cleanup, and a + * document-sized temporary is left beside the target. The next save of the same file sweeps any such + * leftover before writing its own, so it costs one save at most; the prefix is this function's own, so + * nothing else is ever touched. + * + * The file system is a parameter so the rule tests against okio's in-memory file system; the platform + * seam hands it the real one. + * + * @param FileSystem fileSystem The file system holding [target]. + * @param Path target The file to replace, or create. + * @param ByteArray bytes The complete contents to write. + * @throws IOException When the temporary cannot be written or the move fails. + */ +internal fun writeReplacing(fileSystem: FileSystem, target: Path, bytes: ByteArray) { + val directory = target.parent ?: throw IOException("$target has no directory to write a temporary in") + val temporaryPrefix = ".${target.name}.tmp-" + for (sibling in fileSystem.listOrNull(directory).orEmpty()) { + if (sibling.name.startsWith(temporaryPrefix)) { + try { + fileSystem.delete(sibling, mustExist = false) + } catch (_: IOException) { + // A leftover that will not delete is not a reason to fail the save that found it. + } + } + } + val temporary = directory / "$temporaryPrefix${Random.nextLong().toULong().toString(16)}" + try { + fileSystem.write(temporary) { write(bytes) } + fileSystem.atomicMove(temporary, target) + } catch (failure: IOException) { + fileSystem.delete(temporary, mustExist = false) + throw failure + } +} \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/PlatformFiles.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/PlatformFiles.kt new file mode 100644 index 0000000..7f04837 --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/PlatformFiles.kt @@ -0,0 +1,30 @@ +package org.umamo.storage + +import io.github.vinceglb.filekit.PlatformFile + +/** + * Rebuilds a [PlatformFile] from a path string previously stored from `PlatformFile.absolutePath()` + * (e.g. the recent-files list). FileKit's `PlatformFile(path)` constructors are per-platform API — + * not visible from shared code — and Android must additionally route SAF `content://` strings back + * through a Uri, hence the seam. + * + * 保存済みパス文字列から PlatformFile を再構築する継ぎ目。Android は content:// を Uri 経由で戻す。 + * + * @param String path The stored path or URI string. + * @return PlatformFile The reconstructed file handle. + */ +expect fun platformFileFromSavedPath(path: String): PlatformFile + +/** + * Writes [bytes] as this file's complete contents, never leaving a half-written file where it can be + * avoided. + * + * A real path takes the temporary-then-atomic-move route ([writeReplacing]), so the file on disk is either + * the old one or the new one. An Android `content://` uri cannot be renamed over, so it is written in + * place, and only once the bytes are complete in memory - the one case where a failure mid-write can + * leave a partial file. + * + * @param ByteArray bytes The complete contents. + * @throws IOException When the write fails; the caller reports it and marks nothing saved. + */ +expect suspend fun PlatformFile.writeReplacing(bytes: ByteArray) \ No newline at end of file diff --git a/module/storage/src/commonMain/kotlin/org/umamo/storage/UmamoLog.kt b/module/storage/src/commonMain/kotlin/org/umamo/storage/UmamoLog.kt new file mode 100644 index 0000000..ffbd8a3 --- /dev/null +++ b/module/storage/src/commonMain/kotlin/org/umamo/storage/UmamoLog.kt @@ -0,0 +1,114 @@ +package org.umamo.storage + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update + +/** + * The severity of a logged line. Nominal today (the stdout transport prints every level identically), + * but retained on each entry so an in-app console can color Warn and Error distinctly. + */ +enum class LogLevel { + Info, + Warn, + Error, +} + +/** + * One retained log line: its severity and its already-composed message (for an Error with a cause the + * message is the same "message: cause" text the terminal prints, so nothing is lost off the console). + * + * @property LogLevel level The severity the call site named. + * @property String message The final, fully-composed message text. + */ +data class LogEntry(val level: LogLevel, val message: String) + +/** + * The app's minimal diagnostic log. A seam, not a framework: call sites name a severity instead of + * hardcoding the transport, so routing (a file via AppStorage, logcat, an in-app console) can change + * in one place later. The transport today is stdout with the established "[Umamo]" prefix, plus a + * bounded in-memory buffer ([entries]) the editor's Logs panel collects - so a user who launched + * without a terminal can still read the output. + * + * Lives in :storage because it is the bottom-most shared module every target already depends on; + * logging is platform plumbing in the same sense as config directories and file IO. + * + * This is for diagnostics only. Anything the user must see goes through a UI surface (a notice or + * a dialog), never only through this log. + */ +object UmamoLog { + /** + * The retained log lines, oldest first, capped at [MAX_LOG_ENTRIES] (oldest dropped past the cap). + * A StateFlow so the Logs panel recomposes as lines arrive; writes are lock-free and thread-safe, + * so any thread (the GL thread, a coroutine dispatcher) may log. + */ + val entries: StateFlow> + get() = mutableEntries.asStateFlow() + + private val mutableEntries = MutableStateFlow>(emptyList()) + + /** + * Logs a routine status line (startup info, a completed save/export). + * + * @param String message The already-formatted message. + */ + fun info(message: String) { + println("[Umamo] $message") + record(LogLevel.Info, message) + } + + /** + * Logs an unexpected-but-recovered condition (a rejected file, a refused platform call). + * + * @param String message The already-formatted message. + */ + fun warn(message: String) { + println("[Umamo] $message") + record(LogLevel.Warn, message) + } + + /** + * Logs a failure worth investigating, with the throwable's message appended when present. + * + * @param String message The already-formatted message. + * @param Throwable? cause The originating failure, or null when there is none. + */ + fun error(message: String, cause: Throwable? = null) { + // Compose once so the terminal and the retained buffer show the cause identically. + val composed = + if (cause != null) { + "$message: ${cause.message}" + } else { + message + } + println("[Umamo] $composed") + record(LogLevel.Error, composed) + } + + /** + * Appends one entry to the retained buffer, dropping the oldest lines past the cap. update{} is a + * lock-free compare-and-set loop (safe from any thread) and its transform is pure, so a retry under + * contention is harmless. + * + * @param LogLevel level The entry's severity. + * @param String message The fully-composed message text. + */ + private fun record(level: LogLevel, message: String) { + mutableEntries.update { existing -> (existing + LogEntry(level, message)).takeLast(MAX_LOG_ENTRIES) } + } + + /** + * Empties the retained buffer. Test-only: [UmamoLog] is an app-lifetime singleton, so tests reset it + * between cases to avoid order coupling. Not a user-facing clear. + */ + internal fun clear() { + mutableEntries.value = emptyList() + } +} + +/** + * The most recent log lines kept in memory. A whole session's diagnostics fit comfortably; the log is + * low-traffic (startup, GL init, file-IO outcomes), so this is generous headroom, not a tight ring. + */ +private const val MAX_LOG_ENTRIES = 2000 \ No newline at end of file diff --git a/module/storage/src/commonTest/kotlin/org/umamo/storage/ContentHashTest.kt b/module/storage/src/commonTest/kotlin/org/umamo/storage/ContentHashTest.kt new file mode 100644 index 0000000..62e09e6 --- /dev/null +++ b/module/storage/src/commonTest/kotlin/org/umamo/storage/ContentHashTest.kt @@ -0,0 +1,20 @@ +package org.umamo.storage + +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** A file hashes to the same digest as its bytes, and a missing one to null. */ +class ContentHashTest { + @Test + fun aFileHashesToTheSameDigestAsItsBytesAndAMissingOneToNull() { + val fileSystem = FakeFileSystem() + val path = "/art/a.psd".toPath() + fileSystem.createDirectories(path.parent!!) + fileSystem.write(path) { write("abc".encodeToByteArray()) } + assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", contentHashOfFile(fileSystem, path), "the published SHA-256 vector for abc") + assertNull(contentHashOfFile(fileSystem, "/art/missing.psd".toPath())) + } +} \ No newline at end of file diff --git a/module/storage/src/commonTest/kotlin/org/umamo/storage/OkioAppStorageTest.kt b/module/storage/src/commonTest/kotlin/org/umamo/storage/OkioAppStorageTest.kt new file mode 100644 index 0000000..d7c0083 --- /dev/null +++ b/module/storage/src/commonTest/kotlin/org/umamo/storage/OkioAppStorageTest.kt @@ -0,0 +1,72 @@ +package org.umamo.storage + +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Unit-tests [OkioAppStorage] over okio's in-memory FakeFileSystem - the persistence foundation + * settings/keymaps/layout all write through, exercised with no real disk. + */ +class OkioAppStorageTest { + private fun storage(fileSystem: FakeFileSystem): OkioAppStorage = + OkioAppStorage( + fileSystem = fileSystem, + configDirectory = "/config".toPath(), + dataDirectory = "/data".toPath(), + ) + + @Test + fun writeThenReadRoundTripsUtf8Text() { + val storage = storage(FakeFileSystem()) + val path = storage.configDirectory / "settings.json" + + storage.writeText(path, "{\"theme\":\"dark\", \"言語\":\"日本語\"}") + + assertEquals("{\"theme\":\"dark\", \"言語\":\"日本語\"}", storage.readText(path)) + } + + @Test + fun writeCreatesMissingParentDirectories() { + val fileSystem = FakeFileSystem() + val storage = storage(fileSystem) + val nested = storage.configDirectory / "keymaps" / "presets" / "custom.json" + + storage.writeText(nested, "{}") + + assertTrue(fileSystem.exists(storage.configDirectory / "keymaps" / "presets")) + assertEquals("{}", storage.readText(nested)) + } + + @Test + fun readReturnsNullForAMissingFile() { + val storage = storage(FakeFileSystem()) + + assertNull(storage.readText(storage.configDirectory / "absent.json")) + } + + @Test + fun existsTracksTheWrittenFile() { + val storage = storage(FakeFileSystem()) + val path = storage.dataDirectory / "recent.json" + + assertFalse(storage.exists(path)) + storage.writeText(path, "[]") + assertTrue(storage.exists(path)) + } + + @Test + fun rewritingAFileReplacesItsContents() { + val storage = storage(FakeFileSystem()) + val path = storage.configDirectory / "settings.json" + + storage.writeText(path, "first") + storage.writeText(path, "second") + + assertEquals("second", storage.readText(path)) + } +} \ No newline at end of file diff --git a/module/storage/src/commonTest/kotlin/org/umamo/storage/UmamoLogTest.kt b/module/storage/src/commonTest/kotlin/org/umamo/storage/UmamoLogTest.kt new file mode 100644 index 0000000..33d9c8a --- /dev/null +++ b/module/storage/src/commonTest/kotlin/org/umamo/storage/UmamoLogTest.kt @@ -0,0 +1,66 @@ +package org.umamo.storage + +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Unit-tests [UmamoLog]'s retained buffer - the in-memory log the editor's Logs panel reads. Resets the + * buffer before each case because UmamoLog is an app-lifetime singleton whose state would otherwise leak + * between tests. + */ +class UmamoLogTest { + @BeforeTest + fun reset() { + UmamoLog.clear() + } + + @Test + fun infoRecordsAnInfoEntry() { + UmamoLog.info("started") + + val entry = UmamoLog.entries.value.single() + assertEquals(LogLevel.Info, entry.level) + assertEquals("started", entry.message) + } + + @Test + fun warnRecordsAWarnEntry() { + UmamoLog.warn("odd") + + assertEquals(LogLevel.Warn, UmamoLog.entries.value.single().level) + } + + @Test + fun errorWithCauseRecordsTheComposedMessage() { + UmamoLog.error("could not open", RuntimeException("missing")) + + val entry = UmamoLog.entries.value.single() + assertEquals(LogLevel.Error, entry.level) + // The cause is folded into the message exactly as the terminal prints it, so the panel keeps it. + assertEquals("could not open: missing", entry.message) + } + + @Test + fun errorWithoutCauseRecordsTheBareMessage() { + UmamoLog.error("plain failure") + + assertEquals("plain failure", UmamoLog.entries.value.single().message) + } + + @Test + fun bufferCapsAtTheMaximumDroppingOldest() { + // Append past the documented cap (MAX_LOG_ENTRIES = 2000); the oldest lines fall off the front. + val cap = 2000 + val overflow = 50 + for (lineIndex in 0 until cap + overflow) { + UmamoLog.info("line $lineIndex") + } + + val entries = UmamoLog.entries.value + assertEquals(cap, entries.size) + // The first `overflow` lines were dropped: the window now starts at `overflow` and ends at the last. + assertEquals("line $overflow", entries.first().message) + assertEquals("line ${cap + overflow - 1}", entries.last().message) + } +} \ No newline at end of file diff --git a/module/storage/src/commonTest/kotlin/org/umamo/storage/WriteReplacingTest.kt b/module/storage/src/commonTest/kotlin/org/umamo/storage/WriteReplacingTest.kt new file mode 100644 index 0000000..1c25cdd --- /dev/null +++ b/module/storage/src/commonTest/kotlin/org/umamo/storage/WriteReplacingTest.kt @@ -0,0 +1,96 @@ +package org.umamo.storage + +import okio.Buffer +import okio.ForwardingFileSystem +import okio.ForwardingSink +import okio.IOException +import okio.Path +import okio.Path.Companion.toPath +import okio.Sink +import okio.fakefilesystem.FakeFileSystem +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse + +/** + * Pins the one promise a save makes about the file on disk: it is either the old file or the new one, + * never something in between, and no temporary is left behind either way. + */ +class WriteReplacingTest { + private val directory = "/documents".toPath() + + /** + * A file system whose [directory] exists. + * + * @return FakeFileSystem The file system. + */ + private fun fileSystem(): FakeFileSystem = FakeFileSystem().also { fileSystem -> fileSystem.createDirectories(directory) } + + @Test + fun replacesAnExistingFileAndLeavesNoTemporary() { + val fileSystem = fileSystem() + val target = directory / "rig.uma" + fileSystem.write(target) { write(byteArrayOf(1, 2, 3)) } + + writeReplacing(fileSystem, target, byteArrayOf(9, 8, 7, 6)) + + assertContentEquals(byteArrayOf(9, 8, 7, 6), fileSystem.read(target) { readByteArray() }) + assertEquals(listOf(target), fileSystem.list(directory), "nothing but the target remains") + } + + @Test + fun createsAFileThatDidNotExist() { + val fileSystem = fileSystem() + val target = directory / "new.uma" + + writeReplacing(fileSystem, target, byteArrayOf(4, 2)) + + assertContentEquals(byteArrayOf(4, 2), fileSystem.read(target) { readByteArray() }) + assertEquals(listOf(target), fileSystem.list(directory)) + } + + /** + * A process killed mid-save leaves its temporary behind; the next save of that file sweeps it, and + * touches nothing that is not its own. + */ + @Test + fun aLeftoverTemporaryIsSweptByTheNextSaveOfThatFile() { + val fileSystem = fileSystem() + val target = directory / "rig.uma" + val leftover = directory / ".rig.uma.tmp-deadbeef" + val anothersTemporary = directory / ".other.uma.tmp-cafe" + val lookAlike = directory / "rig.uma.tmp-notes" + for (path in listOf(leftover, anothersTemporary, lookAlike)) { + fileSystem.write(path) { write(byteArrayOf(0)) } + } + + writeReplacing(fileSystem, target, byteArrayOf(5, 5)) + + assertEquals(listOf(anothersTemporary, target, lookAlike).sortedBy { path -> path.name }, fileSystem.list(directory).sortedBy { path -> path.name }, "only this file's own leftover went") + assertContentEquals(byteArrayOf(5, 5), fileSystem.read(target) { readByteArray() }) + } + + @Test + fun aFailedWriteLeavesTheOldFileAndNoTemporary() { + val disk = fileSystem() + val target = directory / "rig.uma" + disk.write(target) { write(byteArrayOf(1, 2, 3)) } + // A disk that fails every write mid-stream: the temporary is opened, the bytes never land. + val failing = + object : ForwardingFileSystem(disk) { + override fun sink(file: Path, mustCreate: Boolean): Sink { + val sink = super.sink(file, mustCreate) + return object : ForwardingSink(sink) { + override fun write(source: Buffer, byteCount: Long): Unit = throw IOException("no space left on device") + } + } + } + + assertFailsWith { writeReplacing(failing, target, byteArrayOf(9, 9, 9)) } + + assertContentEquals(byteArrayOf(1, 2, 3), disk.read(target) { readByteArray() }, "the old file is intact") + assertFalse(disk.list(directory).any { path -> path.name.contains(".tmp-") }, "no temporary is left behind") + } +} \ No newline at end of file diff --git a/module/storage/src/jvmMain/kotlin/org/umamo/storage/DesktopStorage.kt b/module/storage/src/jvmMain/kotlin/org/umamo/storage/DesktopStorage.kt new file mode 100644 index 0000000..123bcdc --- /dev/null +++ b/module/storage/src/jvmMain/kotlin/org/umamo/storage/DesktopStorage.kt @@ -0,0 +1,48 @@ +package org.umamo.storage + +import okio.FileSystem +import okio.Path +import okio.Path.Companion.toPath +import java.io.File + +/** + * Builds the desktop [AppStorage], resolving per-OS config/data directories under [applicationName]: + * Linux follows XDG (`~/.config`, `~/.local/share`), macOS uses `~/Library/Application Support`, Windows + * uses `%APPDATA%` / `%LOCALAPPDATA%`. IO goes through the real filesystem (`FileSystem.SYSTEM`). + * + * @param String applicationName The app's directory name (e.g. "umamo"). + * @return AppStorage The desktop storage. + */ +fun desktopAppStorage(applicationName: String): AppStorage = + OkioAppStorage( + FileSystem.SYSTEM, + configDirectory = desktopBaseDirectory(config = true).toOkioPath() / applicationName, + dataDirectory = desktopBaseDirectory(config = false).toOkioPath() / applicationName, + ) + +/** + * Resolves the OS's base config or data directory (without the app name). + * + * @param Boolean config True for the config base, false for the data base. + * @return File The base directory. + */ +private fun desktopBaseDirectory(config: Boolean): File { + val home = System.getProperty("user.home") ?: "." + val os = System.getProperty("os.name").orEmpty().lowercase() + return when { + os.contains("win") -> { + val variable = if (config) "APPDATA" else "LOCALAPPDATA" + val fallback = if (config) "$home\\AppData\\Roaming" else "$home\\AppData\\Local" + File(System.getenv(variable) ?: fallback) + } + os.contains("mac") || os.contains("darwin") -> File("$home/Library/Application Support") + else -> { + val variable = if (config) "XDG_CONFIG_HOME" else "XDG_DATA_HOME" + val fallback = if (config) "$home/.config" else "$home/.local/share" + File(System.getenv(variable)?.takeIf { it.isNotBlank() } ?: fallback) + } + } +} + +/** Converts a `java.io.File` to an okio [Path] via its absolute path. */ +private fun File.toOkioPath(): Path = absolutePath.toPath() \ No newline at end of file diff --git a/module/storage/src/jvmMain/kotlin/org/umamo/storage/PlatformFiles.jvm.kt b/module/storage/src/jvmMain/kotlin/org/umamo/storage/PlatformFiles.jvm.kt new file mode 100644 index 0000000..9dc62cc --- /dev/null +++ b/module/storage/src/jvmMain/kotlin/org/umamo/storage/PlatformFiles.jvm.kt @@ -0,0 +1,27 @@ +package org.umamo.storage + +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.absolutePath +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okio.FileSystem +import okio.Path.Companion.toPath +import java.io.File + +/** + * Desktop actual: a stored path is an ordinary filesystem path. + * + * @param String path The stored path. + * @return PlatformFile The reconstructed file handle. + */ +actual fun platformFileFromSavedPath(path: String): PlatformFile = PlatformFile(File(path)) + +/** + * Desktop actual: a temporary sibling moved atomically over the target, off the caller's thread. + * + * @param ByteArray bytes The complete contents. + */ +actual suspend fun PlatformFile.writeReplacing(bytes: ByteArray) { + val target = absolutePath().toPath() + withContext(Dispatchers.IO) { writeReplacing(FileSystem.SYSTEM, target, bytes) } +} \ No newline at end of file diff --git a/module/ui/build.gradle.kts b/module/ui/build.gradle.kts new file mode 100644 index 0000000..bfb4c35 --- /dev/null +++ b/module/ui/build.gradle.kts @@ -0,0 +1,164 @@ +// :ui — Compose Multiplatform editor shell (panels, tree, timeline, parameter grid). +// Hosts the :render viewport, injected by each app as a composable slot (see ViewportHost). +// :ui — Compose Multiplatform 製エディタ UI。ビューポートは各アプリがスロットで注入する。 + +plugins { + alias(libs.plugins.kotlinMultiplatform) + alias(libs.plugins.androidKmpLibrary) + alias(libs.plugins.composeMultiplatform) + alias(libs.plugins.composeCompiler) + // kotlinx.serialization codegen: the workspace/area-tree layout is `@Serializable` and persisted + // to the `interface.layout` settings key. The plugin generates the serializers at compile time. + alias(libs.plugins.kotlinSerialization) + // Umamo's own conventions (gradle/build-logic): the shared jvmAndroidMain source-set group, and the + // corpus/-D forwarding configured by `umamoTestCorpus` below. (No iOS target here yet, so no + // `umamo.kmp-ios-gate` — Compose Multiplatform's iOS story is a separate piece of work.) + id("umamo.kmp-jvmandroid") + id("umamo.test-corpus") +} + +// Resolve the host "-" token (see gradle/build-target.gradle.kts) — jvmTest needs the +// matching Compose Desktop artifact for Skiko's native runtime (rasterizing tests load it). +apply(from = rootProject.file("gradle/build-target.gradle.kts")) +val buildTarget = extra["umamoBuildTarget"] as String + +kotlin { + jvmToolchain(21) + + // The `jvmAndroidMain` group comes from the `umamo.kmp-jvmandroid` convention plugin. This module + // needs it because commonMain cannot see :format's own jvmAndroidMain types (FormatRegistry, + // Cmo3Model — the JDOM-backed CMO3 codec), but the shared document/file layer and app shell do. + + jvm() + + android { + namespace = "org.umamo.ui" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + } + + sourceSets { + // The `umamo.kmp-jvmandroid` convention plugin creates this group and wires androidMain onto it; + // it is not a well-known source-set name, so it has no generated accessor and is looked up here. + val jvmAndroidMain = getByName("jvmAndroidMain") + + commonMain { + dependencies { + // Direct Compose Multiplatform coordinates via the version catalog — the old + // `compose.runtime` plugin aliases were deprecated in CMP 1.10/1.11. The artifacts + // still redirect to androidx.compose on Android (Gradle metadata), so per-target + // resolution is unchanged; see the catalog note on the `compose-*` entries. + implementation(libs.compose.runtime) + implementation(libs.compose.foundation) + implementation(libs.compose.ui) + // Compose Multiplatform resources — bundles defaultSettings.json so desktop + Android + // share one baseline; read via the generated `Res` (see SettingsProvider). + implementation(libs.compose.components.resources) + // Layout serialization (the area-tree → `interface.layout` JSON) and coroutines for the + // debounced `snapshotFlow` persist. Declared directly rather than leaned on transitively + // from :settings — coroutines is `implementation` there, so it would not leak through. + implementation(libs.kotlinxSerializationJson) + implementation(libs.kotlinxCoroutinesCore) + implementation(project(":runtime")) + // Format↔runtime conversion: the CMO3/MOC3 import + export entry points the document + // layer calls, and the export report/notice types the shell overlays render. + // `implementation` — ShellOverlayState is internal, so nothing re-exports them. + implementation(project(":interop")) + // `api` (not `implementation`): the viewport seam's public surface exposes :render types + // (PuppetViewportService returns ViewportCamera / PickCandidate / CheckerboardColors), so + // consumers see them transitively. + api(project(":render")) + // Editing core: the Selection / EditorMode model and the EditorSession the panels read and + // drive (LocalEditorSession, the session-backed handles); declared directly, the project's + // convention even though :edit also surfaces transitively. + implementation(project(":edit")) + // The re-import engine: the reload planner the Sources space's Reload and relink run. + implementation(project(":reimport")) + implementation(project(":settings")) + implementation(project(":storage")) + } + } + // Shared by desktop JVM + Android: the document/file layer and the shared EditorApp shell. + // They call :format's FormatRegistry / Cmo3 codec, which live in :format's jvmAndroidMain + // (the JDOM XML serializer is JVM-only API) — so this layer can't sit in commonMain. + jvmAndroidMain.dependencies { + implementation(project(":format")) + } + commonTest { + dependencies { + implementation(kotlin("test")) + // In-memory FileSystem + storage so the layout persistence round-trip runs with no real disk. + implementation(libs.okio) + implementation(libs.okio.fakefilesystem) + } + } + jvmTest { + dependencies { + // Skiko's native runtime for the host, so commonTest code that rasterizes (the thumbnailer's + // rgbaToImageBitmap → Image.makeRaster) can run under :ui:jvmTest — the plain compose-ui + // coordinate carries no natives. Same direct-coordinate rationale as app/desktop. + runtimeOnly("org.jetbrains.compose.desktop:desktop-jvm-$buildTarget:${libs.versions.composeMultiplatform.get()}") + // A real composition with real pointer input. The panels' gesture code (tap-versus-drag off + // one raw stream, selection round-tripping through hoisted state) is not reachable from a + // pure-function test, and that is exactly where the interaction bugs have been living. + implementation(libs.compose.ui.test) + implementation(libs.compose.ui.test.junit4) + // sealedSubclasses, for the export-notice label coverage test. Without it the reflection + // call resolves to an empty list rather than failing, which would make that test vacuous. + implementation(kotlin("reflect")) + } + } + } +} + +// Bundle the repo-root CREDITS.md as a compose resource at build time, so the Help → Credits dialog +// ships the one authored file on desktop and Android alike — a single source of truth, no checked-in +// copy to drift. customDirectory REPLACES the source set's default resource directory rather than +// adding one, so the replacement is a Sync-merged root: the checked-in composeResources plus +// CREDITS.md under files/, readable as Res.readBytes("files/CREDITS.md"). +val syncBundledCredits = + tasks.register("syncBundledCredits") { + from(layout.projectDirectory.dir("src/commonMain/composeResources")) + from(rootProject.file("CREDITS.md")) { + into("files") + } + into(layout.buildDirectory.dir("generated/bundledCredits")) + } + +// Generated resource accessor package. Public so the desktop/Android app modules can localize their +// own chrome (e.g. the desktop menu bar) against the same EN/JA string catalogs via stringResource — +// the shared UI strings live here, not duplicated per app. +compose.resources { + packageOfResClass = "org.umamo.ui.resources" + publicResClass = true + // The map over the task output carries the task dependency into the provider, so the resource + // pipeline orders after the Sync (and the configuration cache stays happy). + customDirectory( + sourceSetName = "commonMain", + directoryProvider = layout.dir(syncBundledCredits.map { syncTask -> syncTask.destinationDir }), + ) +} + +// Forward the MOC3 corpus sample to the test JVM so the sidecar-loader tests can exercise the +// moc-dependent paths (a decodable .moc3 is needed before texture resolution runs). Explicit -D wins; +// otherwise the local (gitignored) corpus is the default. Absent entirely (CI, a fresh clone) → those +// tests self-skip and the build stays green. +umamoTestCorpus { + // The corpus loader test decodes the 8192² atlas (256MB of RGBA) more than once; the JVM default + // heap cannot hold that. Same figure :format's tests use. + maxHeap("4g") + // Model A: the corpus family that is COMPLETE on disk (manifest + textures + cdi3 + physics all + // resolve). The EricaTamamo corpus copy carries no texture folder, so the family loader test would + // fail on it rather than exercise the load path. Hence a module-specific default rather than the + // shared table, which deliberately leaves moc3.sample explicit-only for :interop and :render. + sampleWithCorpusDefault("moc3.sample", "moc3/modelA/modelA.moc3") + // The CMO3 loader test's counterpart. Takes the shared table's default (a whole .cmo3 embeds its + // own pixels, so unlike the moc family there is no sidecar folder that has to resolve). + sample("cmo3.sample") + // The converted-repack export gate's fixture: a MOC3-origin conversion of the modelG family + // (test/corpus/moc3/modelG) saved as a .cmo3. It lives OUTSIDE the golden glob because a + // converted file fails the corpus invariants by nature, and it self-skips until the file exists. + sampleWithCorpusDefault("cmo3.repackSample", "cmo3/invalid/modelG.cmo3") + // The artwork-import gate's fixture: a real layered PSD, imported, packed at open, and exported. + sampleWithCorpusDefault("psd.sample", "psd/EricaTamamo.psd") +} \ No newline at end of file diff --git a/module/ui/licenses/Inter-OFL.txt b/module/ui/licenses/Inter-OFL.txt new file mode 100644 index 0000000..9b2ca37 --- /dev/null +++ b/module/ui/licenses/Inter-OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/module/ui/licenses/NotoSansCJK-OFL.txt b/module/ui/licenses/NotoSansCJK-OFL.txt new file mode 100644 index 0000000..d952d62 --- /dev/null +++ b/module/ui/licenses/NotoSansCJK-OFL.txt @@ -0,0 +1,92 @@ +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/action/AcceleratorText.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/action/AcceleratorText.android.kt new file mode 100644 index 0000000..280d2b9 --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/action/AcceleratorText.android.kt @@ -0,0 +1,12 @@ +package org.umamo.ui.action + +/** + * Android primary-modifier label: always "Ctrl" (a tablet with an attached keyboard uses Ctrl; there is + * no macOS Android host). Accelerator hints are a keyboard affordance - a keyboardless tablet shows + * none, so this only surfaces when a hardware keyboard is present. + * + * Android の主修飾ラベル。常に "Ctrl"(物理キーボード接続時のみ表示される)。 + * + * @return String The primary modifier label. + */ +actual fun primaryModifierLabel(): String = "Ctrl" \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/action/KeyName.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/action/KeyName.android.kt new file mode 100644 index 0000000..c2fa56b --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/action/KeyName.android.kt @@ -0,0 +1,12 @@ +package org.umamo.ui.action + +import androidx.compose.ui.input.key.Key + +/** + * The identity: Android key codes carry no location (KEYCODE_NUMPAD_DOT is its own code), so the + * event key already equals the named constant. + * + * @param Key key The key from a key event. + * @return Key The key unchanged. + */ +internal actual fun normalizeKeyPosition(key: Key): Key = key \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.android.kt new file mode 100644 index 0000000..d3552cb --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.android.kt @@ -0,0 +1,35 @@ +package org.umamo.ui.graphics + +import android.graphics.Bitmap +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap + +/** + * Android actual: packs the RGBA bytes into non-premultiplied ARGB ints and wraps them in a Bitmap. + * setPixels takes non-premultiplied colors and premultiplies internally — visually equivalent for + * previews/thumbnails, which is this seam's use. + * + * @param ByteArray rgba The pixel bytes, 4 per texel, top row first. + * @param Int width The image width in texels. + * @param Int height The image height in texels. + * @param RgbaAlphaType alphaType How the alpha channel is interpreted. + * @return ImageBitmap The wrapped Compose bitmap. + */ +actual fun rgbaToImageBitmap(rgba: ByteArray, width: Int, height: Int, alphaType: RgbaAlphaType): ImageBitmap { + val argb = IntArray(width * height) + for (pixelIndex in argb.indices) { + val base = pixelIndex * 4 + val red = rgba[base].toInt() and 0xFF + val green = rgba[base + 1].toInt() and 0xFF + val blue = rgba[base + 2].toInt() and 0xFF + val alpha = + when (alphaType) { + RgbaAlphaType.Opaque -> 0xFF + RgbaAlphaType.Straight -> rgba[base + 3].toInt() and 0xFF + } + argb[pixelIndex] = (alpha shl 24) or (red shl 16) or (green shl 8) or blue + } + val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + bitmap.setPixels(argb, 0, width, 0, 0, width, height) + return bitmap.asImageBitmap() +} \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/ContextMenu.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/ContextMenu.android.kt new file mode 100644 index 0000000..feb2d00 --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/ContextMenu.android.kt @@ -0,0 +1,34 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.IntOffset + +/** + * Touch context-menu trigger: a long press (there is no secondary button on a touch screen). Uses the + * standard tap-gesture detector, which fires onLongPress with the press point once the finger has been + * held past the long-press timeout without moving. + * + * @param Function onContextMenu Called with the press point in local coordinates. + * @return Modifier The modifier with the long-press detector attached. + */ +internal actual fun Modifier.contextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier = + this.pointerInput(Unit) { + detectTapGestures(onLongPress = { offset -> onContextMenu(offset.toIntOffset()) }) + } + +/** + * Touch text-field context-menu trigger: the same long press, with no attempt to outrank the platform. + * + * The desktop actual has to beat the text field's built-in secondary-click menu; here the corresponding + * gesture is a long press, and on a touch screen long-pressing text means SELECT A WORD, which is correct + * platform behaviour and not ours to take away. So this loses to the platform where the two collide, and a + * field inside a context-menu area does not offer that area's items on Android. Revisit alongside the + * Android viewport - until that lands the editor does not run here, so the gap costs nothing today. + * + * @param Function onContextMenu Called with the press point in local coordinates. + * @return Modifier The modifier with the detector attached. + */ +internal actual fun Modifier.textEditContextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier = + contextMenuGesture(onContextMenu) \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/FileDropTarget.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/FileDropTarget.android.kt new file mode 100644 index 0000000..cc20d77 --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/FileDropTarget.android.kt @@ -0,0 +1,30 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.draganddrop.DragAndDropEvent + +/* + * Android takes no file drops yet, so both halves of the seam answer "nothing here" and the drop target + * never joins a session - no frame is drawn and no drop is claimed, which leaves a drag to whatever else + * on screen wants it. + * + * What is missing is not the payload read - a drop's ClipData carries the uris plainly enough. It is the + * grant behind them: a uri from another application is readable only under the DragAndDropPermissions the + * Activity takes for the drop, and that grant has to outlive the read, which here is an asynchronous + * document load. Getting that wrong leaks a grant or releases it mid-read, and neither failure is visible + * without a tablet to run it on. It lands with the rest of Android's file story (the SAF reader and + * watcher the artwork reload still wants), not ahead of it. + */ + +/** + * Whether the drag carries files: always false, so the drop target stays out of every session on Android. + * + * @return Boolean False. + */ +actual fun DragAndDropEvent.carriesFiles(): Boolean = false + +/** + * The dropped files' paths: always empty, since no drop is ever claimed here. + * + * @return List An empty list. + */ +actual fun DragAndDropEvent.droppedFilePaths(): List = emptyList() \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/Scrollbar.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/Scrollbar.android.kt new file mode 100644 index 0000000..91a44d9 --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/Scrollbar.android.kt @@ -0,0 +1,31 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.Composable + +/** + * Android actual: a no-op. Touch scrolling has its own overscroll affordance and Foundation's draggable + * VerticalScrollbar is desktop-only, so there is no scrollbar to draw here - the overlay stays callable + * from shared UI without pulling a desktop API onto Android. + * + * Android 実装:何もしない(タッチのオーバースクロール表示があり、デスクトップ専用のバーは描かない)。 + * + * @param ScrollState scrollState Unused on Android; present to match the shared signature. + */ +@Composable +actual fun BoxScope.VerticalScrollbarOverlay(scrollState: ScrollState) { +} + +/** + * Android actual: a no-op, for the same reason as the [ScrollState] overload (touch scrolling needs no + * desktop-style draggable bar). + * + * Android 実装:何もしない(LazyColumn 版も同様)。 + * + * @param LazyListState listState Unused on Android; present to match the shared signature. + */ +@Composable +actual fun BoxScope.VerticalScrollbarOverlay(listState: LazyListState) { +} \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/Tooltip.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/Tooltip.android.kt new file mode 100644 index 0000000..abafc6c --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/kit/Tooltip.android.kt @@ -0,0 +1,24 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier + +/** + * Touch tooltip: touch input has no hover, so the content renders unchanged - only the caller's layout + * [modifier] is carried through. A long-press tooltip using [TooltipCard] will land with the Android + * target, at which point [text] starts being used. + * + * タッチはホバーが無いのでそのまま描画する(レイアウト modifier のみ適用)。長押しツールチップは + * Android ターゲットで対応予定。 + * + * @param String text The tooltip label (unused until long-press tooltips land). + * @param Modifier modifier The layout modifier, applied to the wrapper. + * @param Function content The control the tooltip describes. + */ +@Composable +actual fun Tooltip(text: String, modifier: Modifier, content: @Composable () -> Unit) { + Box(modifier = modifier) { + content() + } +} \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/l10n/SystemLanguage.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/l10n/SystemLanguage.android.kt new file mode 100644 index 0000000..4039a8a --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/l10n/SystemLanguage.android.kt @@ -0,0 +1,15 @@ +package org.umamo.ui.l10n + +import android.content.res.Resources + +/** + * The device's preferred UI languages, from the system configuration's locale list (the order the user set in + * the system language settings). Resources.getSystem() is the system's own configuration, which neither + * Locale.setDefault - what applyAppLocale calls - nor a per-app override changes. + * + * @return List The preferred language tags, most preferred first. + */ +actual fun systemLanguageTags(): List { + val locales = Resources.getSystem().configuration.locales + return (0 until locales.size()).map { localeIndex -> locales.get(localeIndex).toLanguageTag() } +} \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/theme/SystemCursor.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/theme/SystemCursor.android.kt new file mode 100644 index 0000000..86f479f --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/theme/SystemCursor.android.kt @@ -0,0 +1,24 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.input.pointer.PointerIcon + +/** + * Android actual: touch has no hover pointer, so there is no cursor to reshape and the art is never + * rasterized. (A mouse connected to a tablet still works; Android does not take a custom cursor bitmap + * through Compose here.) + * + * Android 実装:タッチにはホバーカーソルが無いため既定を返す。 + * + * @param UmamoCursor cursor The cursor definition (unused on Android). + * @return PointerIcon The default pointer icon. + */ +actual fun umamoPointerIcon(cursor: UmamoCursor): PointerIcon = PointerIcon.Default + +/** + * Android actual: touch has no cursor to hide, so the default pointer icon is returned. + * + * Android 実装:タッチにはカーソルが無いため既定を返す。 + * + * @return PointerIcon The default pointer icon. + */ +actual fun hiddenPointerIcon(): PointerIcon = PointerIcon.Default \ No newline at end of file diff --git a/module/ui/src/androidMain/kotlin/org/umamo/ui/viewport/ViewportCursor.android.kt b/module/ui/src/androidMain/kotlin/org/umamo/ui/viewport/ViewportCursor.android.kt new file mode 100644 index 0000000..84b0914 --- /dev/null +++ b/module/ui/src/androidMain/kotlin/org/umamo/ui/viewport/ViewportCursor.android.kt @@ -0,0 +1,15 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset + +/** + * Android actual: touch has no cursor to warp, so a modal transform simply stops at the viewport edge. + * Always returns null so the caller does not compensate its gesture anchor. + * + * Android 実装:タッチにはカーソルが無いため何もしない。 + * + * @param Float screenX Unused - there is no cursor to move. + * @param Float screenY Unused - there is no cursor to move. + * @return Offset? Always null - no warp happens. + */ +actual fun warpViewportCursor(screenX: Float, screenY: Float): Offset? = null \ No newline at end of file diff --git a/module/ui/src/commonMain/composeResources/drawable/app_icon.png b/module/ui/src/commonMain/composeResources/drawable/app_icon.png new file mode 100644 index 0000000..88acee3 Binary files /dev/null and b/module/ui/src/commonMain/composeResources/drawable/app_icon.png differ diff --git a/module/ui/src/commonMain/composeResources/drawable/splash_banner.png b/module/ui/src/commonMain/composeResources/drawable/splash_banner.png new file mode 100644 index 0000000..05ae98f Binary files /dev/null and b/module/ui/src/commonMain/composeResources/drawable/splash_banner.png differ diff --git a/module/ui/src/commonMain/composeResources/files/defaultSettings.json b/module/ui/src/commonMain/composeResources/files/defaultSettings.json new file mode 100644 index 0000000..3009c7a --- /dev/null +++ b/module/ui/src/commonMain/composeResources/files/defaultSettings.json @@ -0,0 +1,65 @@ +{ + "localization": { + "locale": "en" + }, + "input": { + "keybinding": { + "preset": "default", + "overrides": {} + }, + "pen": { + "backend": "auto" + } + }, + "interface": { + "theme": "dark", + "historyLimit": 200, + "layout": { + "workspaces": [] + }, + "viewport": { + "showToolbar": true, + "showSidebar": false + } + }, + "viewport": { + "zoomStepPercent": 1.0, + "zoomStepCoarsePercent": 5.0, + "selectionHighlightColor": "#FF338CFF", + "activeSelectionHighlightColor": "#FF7DE400", + "warningColor": "#FFFF5A5A", + "pinnedPlacementColor": "#FFB266FF", + "grid": { + "scale": 100.0, + "subdivisions": 10 + }, + "rendering": { + "supersample": true, + "supersampleWhileResizing": true + }, + "meshEdit": { + "vertexIdle": "#FFFF00EC", + "vertexSelected": "#FFFF7A00", + "vertexActive": "#FF7DE400", + "vertexOffKey": "#66888888", + "edgeIdle": "#99000000", + "edgeSelected": "#FFFF7A00", + "edgeActive": "#FF7DE400", + "edgeOffKey": "#44888888", + "faceIdle": "#22000000", + "faceSelected": "#66FF7A00", + "faceActive": "#FF7DE400", + "faceOffKey": "#44888888" + } + }, + "import": { + "parameterTemplate": "humanoid", + "alignment": "center", + "watchMode": "auto", + "deleteArtIgnoresLayer": false, + "layerPositionsFromWorldAxes": false + }, + "app": { + "launchCount": 0 + } +} diff --git a/module/ui/src/commonMain/composeResources/font/inter_regular.ttf b/module/ui/src/commonMain/composeResources/font/inter_regular.ttf new file mode 100644 index 0000000..b7aaca8 Binary files /dev/null and b/module/ui/src/commonMain/composeResources/font/inter_regular.ttf differ diff --git a/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_hk_regular.otf b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_hk_regular.otf new file mode 100644 index 0000000..e28d5f1 Binary files /dev/null and b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_hk_regular.otf differ diff --git a/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_jp_regular.otf b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_jp_regular.otf new file mode 100644 index 0000000..f562249 Binary files /dev/null and b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_jp_regular.otf differ diff --git a/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_kr_regular.otf b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_kr_regular.otf new file mode 100644 index 0000000..dc4a7c6 Binary files /dev/null and b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_kr_regular.otf differ diff --git a/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_sc_regular.otf b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_sc_regular.otf new file mode 100644 index 0000000..dc15562 Binary files /dev/null and b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_sc_regular.otf differ diff --git a/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_tc_regular.otf b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_tc_regular.otf new file mode 100644 index 0000000..f9376ba Binary files /dev/null and b/module/ui/src/commonMain/composeResources/font/noto_sans_cjk_tc_regular.otf differ diff --git a/module/ui/src/commonMain/composeResources/values-ja/strings.xml b/module/ui/src/commonMain/composeResources/values-ja/strings.xml new file mode 100644 index 0000000..8e4a3e0 --- /dev/null +++ b/module/ui/src/commonMain/composeResources/values-ja/strings.xml @@ -0,0 +1,1013 @@ + + + + Umamo + 名称未設定 + (読み取り専用) + + 展開 + 折りたたむ + フィルター + + モデリング + テクスチャ + 物理演算 + 新しいワークスペース + ワークスペース + 名前を変更 + 複製 + コピー + 削除 + 前のワークスペース + 次のワークスペース + ワークスペースをリセット + + 2D ビューポート + UV エディタ + アウトライナー + パラメータ + プロパティ + ツール設定 + 履歴 + ログ + ソース + + クリップボードにコピー + ファイルに書き出し… + ログ出力はまだありません + + 左右に分割 + 上下に分割 + エリアを閉じる + エディタの種類を変更 + + ファイル + 新規 + 開く… + 保存 + 名前を付けて保存… + 最近使ったファイル + インポート + エクスポート + CMO3… + MOC3… + アートワーク… + CMO3… + MOC3… + 画像… + 新規ドキュメント + ドキュメントを開く… + ドキュメントを保存 + ドキュメントに名前を付けて保存… + CMO3をインポート… + MOC3をインポート… + アートワークをインポート… + アートワークを再読み込み + アートを再リンク + アートワークを自動で照合 + アートワークを差し替え… + アートを削除 + CMO3をエクスポート… + MOC3をエクスポート… + 画像をエクスポート… + 終了 + + 編集 + 元に戻す + やり直す + 設定… + + ワークスペース + ワークスペースをリセット + このワークスペースをエクスポート… + すべてのワークスペースをエクスポート… + ワークスペースをインポート… + + 確定 + キャンセル + + 破棄 + リセット + 置き換え + 上書き + 保存せずに終了 + 保存 + 保存しない + このワークスペースを既定のレイアウトに戻しますか? + インポートしたファイルですべてのワークスペースを置き換えますか? + 現在のドキュメントには保存していない変更があります。破棄しますか? + 現在のドキュメントには保存していない変更があります。保存せずに終了しますか? + 現在のドキュメントには保存していない変更があります。先に保存しますか? + 現在のドキュメントには保存していない変更があります。終了する前に保存しますか? + + ファイルは書き出されましたが、以下は CMO3 に引き継げませんでした: + ファイルは書き出されましたが、以下は MOC3 に引き継げませんでした: + アトラスは再パックされませんでした。次の画像はパックできません: + 描画オブジェクトのメッシュがアトラスページのサイズより大きいです。 + 原画レイヤーに不透明なピクセルがありません。 + 原画レイヤーの不透明ピクセルの割合が最小値を下回っています。 + 原画レイヤーをデコードできませんでした。 + この描画オブジェクトの現在の配置を逆変換できませんでした。 + ピン留めされた配置が最大ページサイズに収まりません。 + %1$s のベース形状または UV が編集されています。書き出しは編集どおりの値を保持しますが、Cubism Editor 側でそのメッシュやアトラスを編集すると UV マッピングが再導出されて壊れる可能性があります。 + このモデルには元となる原画データがありません(MOC3 由来のため、パックされたテクスチャアトラスのみを保持しています)。%1$d 枚のアトラスから代替のソースドキュメントを再構成したので、リグ情報はすべて保持され Umamo でも Cubism Editor でも開けますが、収録されているレイヤーはすべて焼き込み済みアトラスの切り出しであり、このリグの元になった原画ではありません。編集可能な本来のレイヤーを書き出すには、元のレイヤー原画(PSD/CLIP/KRA)をこのドキュメントに取り込んでください。 + %1$s は別の配置にある双子と同じアトラス領域を共有しており、独自の領域を用意できませんでした(アートがアトラス 1 ページより大きいため)。Cubism Editor のレイヤー表示では最初の双子の配置に表示されますが、アトラス表示とランタイムには影響しません。 + %1$s は書き出したバージョンでは利用できないため、次の対象から削除されました: %2$s。ドキュメント側には残っているので、新しいバージョンで書き出せば元に戻ります。 + (ほか %1$d 件) + + パラメータ + パラメータグループ + パーツ + デフォーマ + 描画オブジェクト + グルー + ドキュメント + キーフォーム + + メッシュのない描画オブジェクトは書き出せません。 + + %1$s はオブジェクトのグリッドより狭い範囲にしかキーがないため、定数として書き出しました。MOC3 はオブジェクトごとに 1 つのグリッドしか保持できません。 + 下絵(スケッチ)パーツはランタイムの内容ではないため、除外しました。 + 非表示のパーツを書き出さない設定のため、このパーツの内容を除外しました。 + 非表示のアートメッシュを書き出さない設定のため、このアートメッシュを除外しました。 + デフォーマ配下でキーを持たない描画オブジェクトは親空間の形状を書き出せないため、除外しました。 + キャンバスから親空間への変換が %2$d に対して %1$d 個の座標を返したため、元のメッシュを変換せずに書き出しました。 + この描画オブジェクトにはアトラスページが割り当てられていないため、ページ 0 を指す状態で書き出しました。 + クリッピングマスク %1$s はこの書き出しに含まれないため、メッシュはそのマスクなしで書き出しました。 + クリッピングマスクが書き出せなかった描画オブジェクトを指しているため、オフスクリーンから除外しました。 + 制御点グリッドのないワープデフォーマには書き出せる格子がありません。ファイルが読み込める状態を保つため空の格子を書き出しましたが、このデフォーマに紐づくものはすべて原点に潰れます。 + 基準点グリッドのない回転デフォーマには書き出せる変換がないため、単位変換を代わりに書き出しました。 + この書き出しに含まれない描画オブジェクトを指すグルーを除外しました。 + ID が moc の %1$d バイトの ID レコードに収まらないため、「%2$s」に切り詰めて書き出しました。 + ID が moc の %1$d バイトの ID レコードに収まらず、切り詰めた結果が他のオブジェクトの ID と衝突したため、「%2$s」として書き出しました。 + + 対応する CMO3 側の要素がないため、この変更は書き出されませんでした。 + パラメータの種別変更(通常/ブレンドシェイプ)は書き出しに反映されません。 + デフォーマの種別変更は書き出しに反映されません。 + CMO3 側がワープデフォーマではないため、ワープ固有の編集(ベジェ分割、格子、キーフォーム)は書き出されませんでした。 + CMO3 側が回転デフォーマではないため、回転固有の編集(基準角度、キーフォーム)は書き出されませんでした。 + テクスチャの割り当て変更はエディタ内部の状態であり、CMO3 には書き出されません。 + ベース形状の頂点数が CMO3 側と一致しないため、書き出されませんでした。 + この描画オブジェクトには反映できる UV がないため、書き出されませんでした。 + 移動先に対応する CMO3 のパーツがないため、デフォーマの所属は変更されませんでした。 + 固定の描画順がキーフォームトラックに上書きされるため、CMO3 では個別に保持できません。 + 合成の固定値がパーツのキーフォームトラックに上書きされるため、CMO3 では個別に保持できません。 + パーツ単位の合成マスクは、CMO3 では配下の描画オブジェクトに展開されます。 + + CMO3 側に該当する種別の格納先がないため、新規要素は生成されませんでした。 + 新しく作成した要素にはまだ CMO3 側の実体がないため、パネルの並び順から除外しました。 + 作成したグループが編集中のパラメータツリーに存在しないため、生成されませんでした。 + 作成した描画オブジェクトに複製元のテクスチャがないため、生成されませんでした。 + グルー対象の描画オブジェクトに CMO3 側の実体がないため、グルーは生成されませんでした。 + + メッシュの頂点数 %1$d が編集用メッシュのエッジテーブルで扱える上限 %2$d を超えるため、エッジテーブルは再構築されませんでした。 + グルー対象のメッシュに編集用メッシュの頂点 ID テーブルがないため、グルーを再結合できませんでした。 + グルーの頂点対がメッシュの頂点 ID テーブルの範囲を超えているため、再結合されませんでした。 + + %1$s CMO3 はオブジェクトごとに 1 つのグリッドしか保持できません。 + グリッドの軸パラメータ %1$s に CMO3 側の実体がないため、キーフォームグリッドは書き出されませんでした。 + ブレンドシェイプのパラメータ %1$s に CMO3 側の実体がないため、ブレンドシェイプは書き出されませんでした。 + ベースメッシュのないキーフォームは CMO3 にまとめられません。 + CMO3 の描画順は整数のため、小数の値は書き出されませんでした。 + キーフォームのない固定のグルー強度は、CMO3 に保持する場所がありません。 + + 形状のキー範囲外にキーがあるため、1 つのグリッドにまとめられません。 + 形状を伴わないチャンネルのキーは、1 つのグリッドにまとめられません。 + %1$s トラックのキー範囲外にキーがあるため、1 つのグリッドにまとめられません。 + + CMO3 はワールド原点を保持しないため、ファイルを開き直すとキャンバス中心から導出されます。 + モデルにルートのパラメータグループがないため、パラメータツリーは再構築されませんでした。 + モデルにルートパーツがないため、パーツパネルの並び順は再構築されませんでした。 + モデルにパラメータの格納先がないため、パラメータの並び順は書き出されませんでした。 + 組み合わせパラメータ %1$s ・ %2$s が隣り合うように、パラメータの並び順を調整しました。 + モデルにキャンバスがないため、キャンバスサイズは書き出されませんでした。 + このドキュメントにはテクスチャマネージャがないため、原画表示モードを書き出せませんでした。 + この描画オブジェクトには選択した表示モード用のテクスチャ入力がないため、元の入力を維持しました。 + この原画はどのアトラスページにも配置されていないため、更新する配置情報がありませんでした。 + この原画はアトラスページ上で移動しましたが、ページ画像には移動前の位置のまま残っています。再パックすると描き直されます。 + この原画の名前またはサイズが変更されました。アトラス配置では表現できないため、原画を再取り込みしてください。 + この描画オブジェクトは別の原画に結び付けられました。再パックではなく原画の再取り込みが必要です。 + CMO3 のキャンバスサイズは整数ピクセルのため、小数の値は書き出されませんでした。 + + 書き出しにより既存の %1$d 個のファイルを上書きします: %2$s + + MOC3 書き出しオプション + 書き出し + 内容 + サイドカーファイル + スケール + 非表示のパーツを書き出す + 非表示のアートメッシュを書き出す + 下絵(スケッチ)パーツを書き出す + 物理演算設定(physics3.json) + ユーザーデータ(userdata3.json) + 表示補助情報(cdi3.json) + ピクセル / ユニット + キャンバス: %1$s × %2$s ユニット + 画像をエクスポート + 範囲 + ビューポート + キャンバス + 表示中の内容 + 倍率 + 背景 + 透明 + 単色 + ビューポートのグリッド + 色 + %1$d × %2$d px + 表示中のものがありません。 + 書き出すビューポートがありません。 2Dビューポートを指してからエクスポートしてください。 + このドキュメントにはキャンバスがありません。 + %1$d × %2$d px は上限の %3$d px を超えています。 + + Okay + %1$s を読み込めませんでした。 + %1$s は Umamo が認識できるファイル形式ではありません。 + %1$s はまだエディタで開けないファイル形式です。 + %1$s を開けませんでした。ファイルが破損している可能性があります。 + %1$sをインポートできませんでした。model3.json マニフェストが同じフォルダに見つかりません。 + %1$sをインポートできませんでした。model3.json が参照するテクスチャが見つからないか読み込めません。 + %1$sにはインポートできるピクセルを持つレイヤーがありません。 + %1$s はより新しいバージョンの Umamo で作成されたため、このバージョンでは開けません。 + %1$s は読み取り専用で開きました。このバージョンの Umamo が解釈できないエントリを含むため、保存はできません: %2$s + %1$s を保存できませんでした。 %2$s + %1$s をエクスポートできませんでした。 %2$s + ビューポートのレンダラーが画像を描画できませんでした。 + %1$d × %2$d px の画像を作るためのメモリが足りません。倍率を下げてください。 + + ヘルプ + ソースコード… + ホームページ… + 文献集… + クレジット… + クイックセットアップ… + Umamoについて… + + Umamoについて + + バージョン %1$s + GNU 一般公衆利用許諾書 v3.0 のもとで提供されます + クレジットとサードパーティライセンス + 閉じる + + ビューをフィット + 全体を表示 + 等倍 (100%) + ズームイン + ズームアウト + ズームイン(大) + ズームアウト(大) + 領域をズーム + + 選択を解除 + すべて選択 + 選択を反転 + 編集モード切り替え + オブジェクトモード + 編集モード + 頂点を移動 + 左右で位置を入れ替え + 上下で位置を入れ替え + 頂点を拡縮 + 頂点を回転 + 頂点選択モード + 辺選択モード + 面選択モード + ボックス選択 + サークル選択 + ブラシ半径を拡大 + ブラシ半径を縮小 + UV を左右反転 + UV を上下反転 + + + X ミラー + Y ミラー + + + 選択に追従 + ページ %1$d + ページ %1$d · %2$d × %3$d · メッシュ %4$d + ソースレイヤー + アートワークから検索 + %1$s · %2$d × %3$d · メッシュ %4$d + 一致するアートワークがありません + このドキュメントにはソースアートワークがありません + 原画表示を切り替え + アトラスを再パック + 次のテクスチャページ + 前のテクスチャページ + テクスチャページ:選択に追従 + 画像の配置をピン留め + 画像の配置のピン留めを解除 + + 元に戻す + やり直す + 直前の操作を調整 + 表示の切り替え + + 検索 + 検索をクリア + + + 切り取り + コピー + 貼り付け + すべて選択 + + + 開く + 編集 + 選択 + モード変更 + パーツの表示を切り替え + パーツ名を変更 + パーツの選択可否を切り替え + パーツを移動 + メッシュの表示を切り替え + メッシュ名を変更 + メッシュの選択可否を切り替え + メッシュを移動 + デフォーマ名を変更 + デフォーマの選択可否を切り替え + デフォーマを移動 + キーフレーム挿入 + キーフレーム移動 + キーフレーム削除 + キーフレームを選択 + パラメータ選択 + パラメータを調整 + パラメータの範囲を編集 + パラメータをリンク + パラメータのリンクを解除 + パラメータを移動 + グループを作成 + グループを削除 + グループ名を変更 + パラメータを追加 + パラメータ名を変更 + パラメータを削除 + パラメータを削除(キーを移動) + 頂点を移動 + 位置を入れ替え + 位置を入れ替え + 頂点を拡縮 + 頂点を回転 + 頂点をスライド + UV を移動 + UV を拡縮 + UV を回転 + UV を反転 + オブジェクトを移動 + オブジェクトを拡縮 + オブジェクトを回転 + メッシュ要素を選択 + 選択モード変更 + パーツを削除 + メッシュを削除 + デフォーマを削除 + ガイド画像を切り替え + パーツの描画順を設定 + グループモードを設定 + 合成設定を設定 + ブレンドモードを設定 + アルファモードを設定 + 裏面カリングを切り替え + マスク反転を切り替え + 親デフォーマを設定 + マスクを設定 + 乗算色を設定 + スクリーン色を設定 + 不透明度を設定 + 描画順を設定 + デフォーマの不透明度を設定 + デフォーマの乗算色を設定 + デフォーマのスクリーン色を設定 + 左右反転を設定 + 上下反転を設定 + パーツを設定 + 基準角度を設定 + バイリニアワープを切り替え + ワープ格子を変更 + キャンバスサイズを設定 + ワールド原点を設定 + テクスチャ表示を変更 + アトラス上の画像を移動 + アトラス上の画像を回転 + アトラス上の画像を拡大縮小 + アトラス上の画像をピン留め + アトラス上の画像のピン留めを解除 + アトラスを再パック + アートを再リンク + アートのリンクを解除 + アートを削除 + アートを削除してレイヤーを無視 + レイヤーを無視 + レイヤーの無視を解除 + アートワークをインポート + アートワークを再読み込み + アートを再リンク + アートワークを照合 + アートワークを差し替え + ランタイムターゲットを設定 + + 人形 + アーマチュア + パーツ + デフォーマ + アートワークファイルを再読み込み + アートワークファイルがディスク上で変更されています。再読み込みで反映します。 + 自動で照合:ファイルにレイヤーがなくなったアートを、最も近いレイヤーに再リンクします + ファイルの操作 + アートワークを差し替え… + このファイルを再読み込み + レイヤーの操作 + レイヤーを無視 + 無視を解除 + このリンクを確認 + %1$s を採用(%2$d%) + %1$s を採用(%2$d%)し、新しいドローアブルを削除 + 手動で再リンク… + 今は保留 + リンク済み + 未リンク + 見つからないファイル + 要確認 + あり + 見つかりません + 不明 + リンク済み + 名前でリンク + 未リンク + 未配置 + 要確認:ファイルにこのレイヤーがありません + 要確認:ファイル内でこのレイヤーは空です + 要確認:差し替え後のファイルにこのキーのレイヤーがありません + 無視中:再読み込みでこのレイヤーは追加されません + 未リンクのアート + %1$s · %2$d レイヤー + パス未記録 + %1$d × %2$d、位置 %3$d, %4$d + %1$d × %2$d、位置 X %3$s, Z %4$s + ページ %1$d + レイヤーに再リンク + リンクを解除 + アートを削除 + 一致するレイヤーがありません。 + ドローアブル + 制限の切り替え + 選択可否列 + 表示列 + 空 + + + 表示の切り替え + 選択可否の切り替え + 名前を変更 + 削除 + 階層を削除 + + パーツ: %1$d + 描画オブジェクト: %1$d + パラメータ: %1$d + デフォーマ: %1$d + グルー: %1$d + + + LMB / Enter: 確定 + RMB / Esc: キャンセル + 編集モード + 表示切替 + 移動 + 拡大縮小 + 回転 + キー挿入 + キー削除 + ピン留め + 選択モード + 頂点 %1$d/%2$d + 辺 %1$d/%2$d + 面 %1$d/%2$d + 頂点: %1$d + 頂点: %1$d/%2$d + 三角形: %1$d + 三角形: %1$d/%2$d + + 選択に変形できるものがありません。デフォーマは未対応です。 + メッシュの変形中は変形操作できません。先にパラメータをすべてリセットしてください。 + ワープデフォーマで包むメッシュのある描画オブジェクトまたはパーツを選択してください。 + ワープデフォーマを作成 + ワープデフォーマを作成 + ワープデフォーマを作成 + ワープデフォーマ + ワープデフォーマを作成 + この操作は実行できません。 + + X方向 + Z方向 + + ピボットポイント + 中点 + それぞれの原点 + アクティブ要素 + 2Dカーソル + スナップ + カーソル → ワールド原点 + カーソル → 選択物 + カーソル → アクティブ + カーソル → グリッド + 選択物 → グリッド + 選択物 → カーソル + 選択物 → カーソル(オフセット維持) + 選択物 → アクティブ + + 選択物 → ピクセル + 選択物 → カーソル + 選択物 → カーソル(オフセット維持) + 選択物 → グリッド + カーソル → ピクセル + カーソル → 選択物 + カーソル → グリッド + + リンク選択(カーソル下) + リンク選択 + 選択部分を画面に収める + 編集メッシュを切り替え + 階層を選択 + 階層を選択 + + 複製 + 頂点をマージ + 中心にマージ + 最初の頂点にマージ + 最後の頂点にマージ + リップ + 頂点を連結 + 頂点を追加 + 頂点スライド + 複製 + 頂点をマージ + リップ + 頂点を連結 + 頂点を追加 + 頂点を削除 + 描画オブジェクトを複製 + マージには2つ以上の選択頂点が必要です(頂点モード)。 + 連結にはちょうど2つの選択頂点が必要です(頂点モード)。 + 連結できません。カットが何も横断しないか、形状が退化しています。 + 頂点追加を確定できません。三角形を閉じてから Enter。詳細はログを参照。 + ここではリップできません。分割できる面の扇がありません。 + 一部の描画オブジェクトには原画がないため、アトラスから表示しています。 + すべての描画オブジェクトには原画がないため、アトラスから表示しています。 + アトラスを再パックしました。 + 注記付きでアートワークをインポートしました。ログを参照してください。 + アートワークを追加しました。 + 保存中… + %1$s を保存しました。 + 画像をエクスポートしています… + %1$s をエクスポートしました。 + 保存を実行中です。 + 先に保存を完了しています… + UMA として保存しました。Umamo が扱わない CMO3 の構造はこのファイルには含まれません。このセッションのエクスポートは引き続き元の CMO3 に照合されます。 + UMA として保存しました。MOC3 ファミリーの物理演算、モーション、表情、ユーザーデータ、ポーズはこのファイルには含まれません。 + アートワークの追加中にドキュメントが変更されたため、何も適用されませんでした。 + このファイルには追加できるピクセルを持つレイヤーがありません。 + アートワークを再読み込みしました:%1$d 件更新、%2$d 件追加、%3$d 件照合。 + アートワークを再読み込みしました:%1$d 件更新、%2$d 件追加、%3$d 件照合、%4$d 件要確認。ログを参照してください。 + アートワークを再読み込みしました:%1$d 件更新、%2$d 件追加、%3$d 件照合、%4$d 件要確認。一部のアートがメッシュの外に出ています。ログを参照してください。 + %1$d 個のアートワークファイルがディスク上で変更されました。再読み込みで反映します。 + %1$d 個のアートワークファイルが前回の読み込み後に変更されています。再読み込みで反映します。 + %1$s は読み込んだ場所にありません。 + アートワークファイルに変更はありません。 + 読み込めるアートワークファイルがなく、何も再読み込みされませんでした。 + アートを再リンクして再読み込みしました。 + アートを再リンクしましたが、ファイルを読み込めなかったためアートは変わっていません。 + %1$d 件のレイヤーを照合、%2$d 件が要確認です。 + 十分な確度で照合できたリンクはありません。候補は要確認の行に表示されています。 + 照合できるレイヤーが残っていません。候補のレイヤーはすべてリンク済みです。再読み込みの操作設定で照合しきい値を調整するか、手動で再リンクしてください。 + アートワークを差し替えました:%1$d 件をキーで再読み込み、%2$d 件を照合、%3$d 件が要確認です。 + 再パックを中止しました: パック中にアトラスが変更されました。 + アトラスは既にパック済みのため、変更はありません。 + 選択範囲に編集可能な UV がありません。 + ミラーする対象が選択されていません。 + 人形の UV はアトラスではなく原画を参照しているため、移動できる配置がありません。 + 選択範囲にアトラスページへパック済みのアートがないか、原画がありません。 + 配置を移動するには UV エディタでアトラスページを表示してください。 + 選択範囲にこのページへパック済みのアートがありません。 + ソースアートからアトラスを再構成できないため、配置を移動できません。 + 配置が他のタイルと重なっています。アトラスを再パックすると解消できます。 + 配置がページの端を超えています。はみ出した部分は切り取られます。 + 選択した画像はピン留めされています。移動するにはピン留めを解除してください。 + ここでは編集できません。選択中の描画オブジェクトはすべて親によって非表示です。 + + プロポーショナル編集の切り替え + プロポーショナル減衰: スムーズ + プロポーショナル減衰: 球状 + プロポーショナル減衰: ルート + プロポーショナル減衰: シャープ + プロポーショナル減衰: リニア + プロポーショナル減衰: 一定 + スムーズ + 球状 + ルート + シャープ + リニア + 一定 + プロポーショナル %1$s · %2$d + プロポーショナル編集: オン + プロポーショナル編集: オフ + プロポーショナル減衰 + その他 + プロポーショナル編集の「接続のみ」を切り替え + 接続のみ + 配置 + 重なりあり + ページ外 + Δ %1$d, %2$d px + %1$s° + ×%1$s + プロポーショナル編集: 接続のみ + プロポーショナル編集: 半径内すべて + + ピボットポイント + スナップ + UV スナップ + マージ + + ツールバーの切り替え + サイドバーの切り替え + サイドバー + ツールやアイテムのパネルがここに入ります。 + + 親パーツ + 親デフォーマ + マスク: %1$d + メッシュ: 頂点 %1$d / 三角 %2$d + メッシュなし + 格子: %1$d × %2$d + 格子 X: %1$d + 格子 Y: %1$d + 格子 + ワープ格子の各軸の分割数(2~16)。増やすと現在の変形をサンプリングして制御点を追加するので、見た目を保ったまま格子を細かくできます。 + %1$d 個選択 + + + 一致するプロパティがありません + ドキュメント + オブジェクト + データ + キャンバス + 表示 + 原画から表示 + ランタイム + トランスフォーム + リレーション + メッシュ + テクスチャ + 合成 + デフォーマ + パーツ + キャンバスなし + + ターゲット + ターゲットなし(全機能) + Ayagami(Cubism %1$s 相当) + 制限される機能: + すべての機能が利用できます。 + %1$s — このドキュメントで使用中 + 新しいワープデフォーマ方式 + 反転マスク + ブレンドシェイプ(アートメッシュ・ワープデフォーマ) + ブレンドシェイプパラメータ + 乗算色 + スクリーン色 + ブレンドシェイプ(パーツ・回転デフォーマ・グルー) + モーションシンク + ブレンドモード + パーツ合成(オフスクリーン描画) + パラメータのリピート + アートパス + テクスチャソース: %1$s + 独自のアトラス割り当て + ピン留め + + + 幅 + 高さ + 原点 X + 原点 Z + 位置 X + 位置 Z + サイズ X + サイズ Z + 縦横比を固定 + ブレンド + アルファ + 裏面をカリング + マスクを反転 + 左右反転 + 上下反転 + 基準角度 + バイリニア(クアッド) + ガイド画像 + 描画順 + グループモード + 不透明度 + 乗算色 + スクリーン色 + マスク + マスクを追加… + マスクを削除 + リレーションをクリア + ビューポートまたはアウトライナから取得 + px + ° + % + + + 最大ページサイズ + 余白 + 縁の延長 + 回転を許可 + ピン留めしたタイルを維持 + 2のべき乗のページ + 正方形のページ + ページを縮小 + アルファしきい値 + + 移動 X + 移動 Y + 角度 + 拡大縮小 X + 拡大縮小 Y + + 移動 Z + 拡大縮小 Z + プロポーショナル編集 + 減衰 + プロポーショナルサイズ + 接続のみ + 係数 + + 結合位置 + 中心 + 最初 + 最後 + 基準位置 + オフセット X + オフセット Z + アルファしきい値 + 初期メッシュの余白 + 左上 + 上 + 右上 + 左 + 中央 + 右 + 左下 + 下 + 右下 + 照合のしきい値 + + + キャンバスの幅(ピクセル)。変更すると右端だけが動くため、アートの位置は変わりません。 + キャンバスの高さ(ピクセル)。変更すると下端だけが動くため、アートとワールド軸はそのままで、原点 Z が同じだけ変わります。 + ワールド軸が交差する位置(キャンバスの左端からのピクセル)。「位置」の値はこの軸を基準に測ります。 + ワールド軸が交差する位置(キャンバスの下端から上向きのピクセル)。「位置」の値はこの軸を基準に測ります。 + パックされたアトラスではなく、元のアートワークのレイヤーから各メッシュを描画します。ドキュメントがレイヤーを保持していないメッシュは、アトラスから描画されます。 + このモデルの対象ランタイム。そのランタイムで再生できない機能の設定は隠されますが、ドキュメントからは何も削除されません。それらの機能が除かれるのは MOC3 の書き出しだけです。 + ビューポートで見えているメッシュの水平方向の中心(ワールド軸からの距離)。すべてのパラメータが初期値のときだけ編集できます。 + ビューポートで見えているメッシュの垂直方向の中心(ワールド軸から上が正)。すべてのパラメータが初期値のときだけ編集できます。 + ビューポートで見えているメッシュの幅。変更すると中心を基準に拡大縮小します。すべてのパラメータが初期値のときだけ編集できます。 + ビューポートで見えているメッシュの高さ。変更すると中心を基準に拡大縮小します。すべてのパラメータが初期値のときだけ編集できます。 + デフォーマの基準の回転(度)。各キーフォームが設定する角度は、この値に加算されます。 + この項目が属するパーツ。クリアすると、どのパーツにも属さなくなります。 + この項目が付いているデフォーマ。そのデフォーマが動いたり、曲がったり、回転したりすると、この項目も追従します。 + アトラスページ上のこのアートの位置を固定します。UV エディタで手動で動かすことはできず、「ピン留めしたタイルを維持」がオフでない限り、再パックでもその場に残ります。 + このメッシュの重なり順(0〜1000)。値が大きいほど手前に描画され、同じ値ならアウトライナーで上にあるほうが手前になります。「グループ化」か「分離」のパーツの中では、そのパーツの中身の間だけで重なり順が決まります。 + メッシュの不透明度。0 で透明、1 で完全に不透明です。 + メッシュの色を背後の描画とどう混ぜるか。ペイントソフトのレイヤーの合成モードと同じ考え方です。「レガシー」のモードは「アルファ」の設定を無視します。 + メッシュの透明度を背後とどう合成するか。「オーバー」は通常の重ね方、「アトップ」は背後にあるアートの上にだけ描画し、「アウト」は描画せずに背後を消します。「コンジョイント」と「ディスジョイント」は半透明の縁の重なり方を変えます。 + メッシュの色にこの色を乗算し、暗くしたり色味を付けたりします。白では変化しません。 + この色をメッシュにスクリーン合成して明るくします。黒では変化しません。 + 変形で裏返った部分を、反転して描画せずに非表示にします。 + ここに挙げたメッシュでこのメッシュをクリッピングし、それらのアートがある部分にだけ表示します。 + マスクのアートがある部分ではなく、ない部分にだけメッシュを表示します。 + このデフォーマが動かすすべてのもの(入れ子のデフォーマを含む)の不透明度に掛かります。0 で透明、1 で変化しません。 + このデフォーマが動かすすべてのものの色に、この色を乗算します。白では変化しません。 + このデフォーマが動かすすべてのものに、この色をスクリーン合成します。黒では変化しません。 + 格子の各セルを2つの三角形としてではなく、4つの角の間でなめらかに変形し、セルの対角線でアートが折れないようにします。新しいワープデフォーマ方式で、古いランタイムでは再生できません。 + このデフォーマが動かすすべてのものを、ピボットを中心に左右反転します。 + このデフォーマが動かすすべてのものを、ピボットを中心に上下反転します。 + このパーツを、参考用のラフなどのガイド画像にします。エディタには表示されますが、MOC3 の書き出しではこのパーツと中身がすべて除かれます。 + パーツ全体の重なり順(0〜1000)。値が大きいほど手前に描画されます。グループモードが「グループ化」か「分離」のときだけ使われます。 + パーツの中身をモデルの他の部分とどう重ねるか。「パススルー」は各メッシュをそれぞれの描画順で、「グループ化」はパーツ全体をパーツの描画順で重ね、「分離」はさらに独自の不透明度・合成・色・マスクを持つ1枚のレイヤーとして描画します。 + パーツの合成レイヤーの不透明度。0 で透明、1 で完全に不透明です。レイヤー全体に一度だけ掛かるため、パーツ内で重なったメッシュ同士は透けて見えません。 + パーツの合成レイヤーの色を背後の描画とどう混ぜるか。ペイントソフトのレイヤーの合成モードと同じ考え方です。「レガシー」のモードは「アルファ」の設定を無視します。 + パーツの合成レイヤーの透明度を背後とどう合成するか。「オーバー」は通常の重ね方、「アトップ」は背後にあるアートの上にだけ描画し、「アウト」は描画せずに背後を消します。「コンジョイント」と「ディスジョイント」は半透明の縁の重なり方を変えます。 + パーツの合成レイヤーの色に、この色を乗算します。白では変化しません。 + パーツの合成レイヤーに、この色をスクリーン合成します。黒では変化しません。 + ここに挙げたメッシュやパーツでパーツの合成レイヤーをクリッピングし、それらのアートがある部分にだけ表示します。 + マスクのアートがある部分ではなく、ない部分にだけパーツの合成レイヤーを表示します。 + パックで使えるページの最大サイズ(ピクセル)。「ページを縮小」がオンの場合、アートに必要なときだけこの大きさになります。 + 各アートの周囲とページの端に確保する空白(ピクセル)。テクスチャのサンプリング時に、隣のアートがにじみ込まないようにします。 + 各アートの縁の色を余白へ外向きに延ばすピクセル数。アートの縁の継ぎ目を目立たなくします。余白より広くはできません。 + ページにより多く収めるため、アートを90度回転して配置できるようにします。 + ピン留めしたアートをその場に残し、ほかのアートをその周りにパックします。オフにすると、ピン留めしたアートもほかと同じようにパックされます。 + 各ページの幅と高さを、1024 や 2048 などの2のべき乗に切り上げます。 + すべてのページを正方形にします。 + 常に最大ページサイズを使うのではなく、各ページを収めるアートに合わせた大きさにします。 + パックの前に各アートの周囲の空白を切り詰めるとき、アートとみなすピクセルの不透明度(1〜255)。 + アートがページ上で右に移動した距離(ピクセル)。負の値は左への移動です。 + アートがページ上で下に移動した距離(ピクセル)。負の値は上への移動です。 + アートがページ上で回転した角度(度)。 + アート自身の幅方向に拡大縮小した倍率。1 では変化しません。 + アート自身の高さ方向に拡大縮小した倍率。1 では変化しません。 + 追加したファイルのキャンバスを、ドキュメントのキャンバスのどこに置くか。「左上」は左上の角同士を合わせ、「中央」は中央に置きます。 + 基準位置で置いた位置から、追加したアートを右へずらす量(ピクセル)。負の値は左です。 + 基準位置で置いた位置から、追加したアートを上へずらす量(ピクセル)。負の値は下です。 + レイヤーの初期メッシュをアートに合わせるとき、アートとみなすピクセルの不透明度(1〜255)。 + レイヤーの初期メッシュが、見えているアートの外側へ各辺でどれだけはみ出すか(ピクセル)。 + 見失ったレイヤーを自動で再リンクするのに必要な照合の確かさ(パーセント)。これに満たない候補は、ソースパネルで確認できるように残されます。 + 選択が右に移動した距離(ピクセル)。負の値は左です。 + 選択がテクスチャ上で下に移動した距離(ピクセル)。負の値は上です。 + 選択が上に移動した距離(ピクセル)。負の値は下です。 + 選択が回転した角度(度)。 + 選択を横方向に拡大縮小した倍率。1 では変化しません。 + 選択をテクスチャ上で縦方向に拡大縮小した倍率。1 では変化しません。 + 選択を縦方向に拡大縮小した倍率。1 では変化しません。 + 選択の近くにある未選択の頂点も、離れるほど弱く一緒に動かします。 + プロポーショナル編集の影響が、「プロポーショナルサイズ」の端に向かって弱まっていく曲線。 + プロポーショナル編集の影響が選択から届く距離(ピクセル)。 + プロポーショナル編集の影響を、メッシュの辺で選択とつながった頂点に限り、距離を辺に沿って測ります。 + 頂点が辺上のどこに移動したか。0 は元の位置、1 は隣の頂点の位置です。 + 結合した頂点を集める位置。中心、または最初か最後に選択した頂点の位置です。 + + 通常 + 加算 + 乗算 + 加算(レガシー) + 加算(グロー) + 比較(暗) + 乗算(レガシー) + 焼き込みカラー + 焼き込みリニア + 比較(明) + スクリーン + 覆い焼きカラー + オーバーレイ + ソフトライト + ハードライト + リニアライト + 色相 + カラー + + オーバー + アトップ + アウト + コンジョイント + ディスジョイント + + パススルー + グループ化 + 分離 + + 既定値にリセット + すべて既定値に + 範囲 + 下のパラメータとリンク + リンクを解除して2つのスライダーに戻す + ドラッグして並べ替え + 新規グループ + 新規グループ + 名前を変更 + グループを削除 + パラメータを追加 + キーフォームパラメータを追加 + ブレンドシェイプパラメータを追加 + パラメータを削除 + キーを破棄 + キーの移動先… + 新規パラメータ + 選択項目が使うパラメータのみ + 最小 + 既定 + 最大 + + + 設定 + 設定 + 設定を閉じる + クイックセットアップ + 続ける + インターフェース + カラー + ビューポート + キーバインド + ペン + インポート + + テーマ + ダーク + ライト + システム + 言語 + + 履歴のステップ数 + + プリセット + キーバインドのプリセット + デフォルト + Cubism + Blender + プリセットに戻す + ショートカットを押してください… + 未割り当て + ショートカットを解除 + + %1$s は既に「%2$s」に割り当てられています。再割り当てしますか? + 再割り当て + + ペンの設定は近日対応予定です。 + パラメータテンプレート + 追加アートワークの基準位置 + アートワークファイルの監視 + 自動で再読み込み + 通知のみ + オフ + 「ソース」でアートを削除したとき、そのレイヤーも無視としてマークする + 「ソース」のレイヤー位置を、アートファイルの左上ではなくワールド軸から測って表示する + 人型 + なし + + ズーム刻み (%) + 粗いズーム刻み (%) + グリッド間隔(既定) + グリッド分割数 + + スーパーサンプリング(2 倍精細レンダリング) + パネルのリサイズ中もスーパーサンプリングを維持 + + ビューポート + 選択ハイライト + アクティブ選択のハイライト + 警告 + ピン留めした配置 + メッシュ編集 + 頂点 + 辺 + 面 + 通常 + 選択中 + アクティブ + キー外 + + メッシュ: %1$s + パーツ: %1$s + デフォーマ: %1$s + キーフォームシート + どのパラメータにキーを挿入しますか? + どのパラメータのキーを削除しますか? + %1$s を選択 + すべてのトラックがフィルターで非表示です。 + 変形トラック + プロパティトラック + ブレンドシェイプトラック + このパラメータにはまだ何もキーされていません + ドローアブル + ワープデフォーマ + 回転デフォーマ + パーツ + グルー + ジオメトリ + ブレンドシェイプ + 描画順 + 不透明度 + 乗算 + スクリーン + X反転 + Y反転 + グルー強度 + キーフレーム挿入 + すべてのキーを表示 + キーフレームを左へ微調整 + キーフレームを右へ微調整 + 選択したキーを削除 + キーフレーム削除 + キー可能なプロパティを指してください + キーを打つパラメータを選択してください + \ No newline at end of file diff --git a/module/ui/src/commonMain/composeResources/values-ko/strings.xml b/module/ui/src/commonMain/composeResources/values-ko/strings.xml new file mode 100644 index 0000000..3165441 --- /dev/null +++ b/module/ui/src/commonMain/composeResources/values-ko/strings.xml @@ -0,0 +1,697 @@ + + + + Umamo + 펼치기 + 접기 + 필터 + 모델링 + 텍스처 + 물리 + 새 워크스페이스 + 워크스페이스 + 이름 변경 + 복제 + 복사 + 삭제 + 이전 워크스페이스 + 다음 워크스페이스 + 워크스페이스 초기화 + 2D 뷰포트 + UV 에디터 + 아웃라이너 + 파라미터 + 속성 + 도구 설정 + 작업 내역 + 로그 + 클립보드에 복사 + 파일로 내보내기… + 아직 로그 출력이 없습니다 + 왼쪽/오른쪽으로 분할 + 위/아래로 분할 + 영역 닫기 + 에디터 유형 변경 + 파일 + 최근 항목 열기 + 가져오기 + 내보내기 + CMO3… + MOC3… + CMO3… + MOC3… + CMO3 가져오기… + MOC3 가져오기… + CMO3 내보내기… + MOC3 내보내기… + 종료 + 편집 + 실행 취소 + 다시 실행 + 설정… + 워크스페이스 + 워크스페이스 초기화 + 이 워크스페이스 내보내기… + 모든 워크스페이스 내보내기… + 워크스페이스 가져오기… + 확인 + 취소 + 이 워크스페이스를 기본 레이아웃으로 초기화하시겠습니까? + 모든 워크스페이스를 가져온 파일로 교체하시겠습니까? + 문서에 저장하지 않은 변경 사항이 있습니다. 변경 사항을 취소하시겠습니까? + 파일을 내보냈지만, 다음 항목은 CMO3에 포함할 수 없습니다: + 파일을 내보냈지만, 다음 항목은 MOC3에 포함할 수 없습니다: + 아틀라스를 다시 패킹하지 못했습니다. 다음 타일은 패킹할 수 없습니다: + 드로어블 메쉬가 아틀라스 페이지 크기보다 큽니다. + 원본 아트워크 레이어에 불투명한 픽셀이 없습니다. + 원본 아트워크 레이어의 불투명 영역이 최소 범위보다 작습니다. + 원본 아트워크 레이어를 디코딩할 수 없습니다. + 드로어블의 현재 배치를 역변환할 수 없습니다. + 고정된 배치가 최대 페이지 크기에 맞지 않습니다. + 기본 지오메트리 또는 UV가 다음에서 편집되었습니다: %1$s. 내보내기에서는 작성된 상태 그대로 유지되지만, Cubism Editor에서 해당 메시 또는 아틀라스를 편집하면 UV 매핑이 다시 계산되어 손상될 수 있습니다. + 이 모델에는 원본 아트워크가 없습니다(MOC3에서 가져온 모델로, MOC3에는 패킹된 텍스처 아틀라스만 저장됩니다). %1$d개의 아틀라스 페이지를 기반으로 대체용 원본 문서를 재구성했기 때문에 이 파일에는 전체 리깅 정보가 포함되어 있으며 Umamo와 Cubism Editor에서 모두 열 수 있습니다. 하지만 이 문서의 각 레이어는 이 리그를 제작할 때 사용한 원본 아트워크가 아니라, 구워진 아틀라스 페이지를 잘라낸 이미지입니다. 실제 편집 가능한 레이어를 내보내려면 원본 레이어 아트워크(PSD/CLIP/KRA)를 이 문서에 맞춰 통합하세요. + %1$s은(는) 대상 런타임 버전에서 사용할 수 없으므로 %2$s에서 제거되었습니다. + (+%1$d개 더) + 파라미터 + 파라미터 그룹 + 파트 + 디포머 + 드로어블 + 글루 + 문서 + 키폼 + 메쉬가 없는 드로어블은 저장할 수 없습니다. + %1$s의 키 범위가 오브젝트 격자보다 좁아 상수로 출력되었습니다. MOC3는 오브젝트당 하나의 격자만 저장합니다. + 가이드 이미지(스케치) 파트는 런타임 콘텐츠가 아니므로 제외되었습니다. + 파트가 숨겨져 있고 내보내기 옵션에서 숨겨진 파트 제외가 설정되어 있어 해당 내용이 제외되었습니다. + 드로어블이 숨겨져 있고 내보내기 옵션에서 숨겨진 아트메쉬 제외가 설정되어 있어 제외되었습니다. + 디포머 아래의 키가 지정되지 않은 드로어블에는 기록할 상위 공간 지오메트리가 없어 제외되었습니다. + 캔버스에서 상위 공간으로의 변환 결과 %2$d에 대해 %1$d개의 좌표만 반환되어, 나머지 메쉬에는 변환을 적용하지 않고 기록했습니다. + 이 드로어블에 연결된 아틀라스 페이지가 없어 0번 페이지를 가리키도록 기록했습니다. + 클리핑 마스크 %1$s가 이 내보내기에 포함되지 않아 메쉬에 해당 마스크를 적용하지 않은 상태로 기록했습니다. + 클리핑 마스크가 기록할 수 없는 드로어블을 지정하고 있어 오프스크린에서 제외되었습니다. + 컨트롤 포인트 그리드가 없는 워프 디포머에는 기록할 래티스가 없습니다. 파일을 정상적으로 읽을 수 있도록 그 대신 빈 래티스 하나를 기록했으며, 이 디포머에 연결된 모든 항목은 원점으로 이동합니다. + 기준점 없는 회전 디포머에는 기록할 변환이 없어 그 대신 항등 변환을 기록했습니다. + 이 내보내기에 포함되지 않은 드로어블을 지정하는 글루가 제외되었습니다. + ID가 MOC의 %1$d바이트 ID 레코드에 맞지 않아 “%2$s”로 잘라서 기록했습니다. + ID가 MOC의 %1$d바이트 ID 레코드에 맞지 않고, 잘라낼 경우 다른 객체의 ID와 충돌하므로 “%2$s”로 변경하여 기록했습니다. + 대조할 일치하는 CMO3 원본이 없어 변경 사항을 기록하지 않았습니다. + 파라미터 종류 변경(일반 / 블렌드 셰이프)은 하위 버전으로 변환되지 않습니다. + 디포머 종류 변경은 하위 버전으로 변환되지 않습니다. + CMO3 원본이 워프 디포머가 아니므로 워프 전용 편집 사항(이중선형 모드, 래티스, 키폼)은 기록하지 않았습니다. + CMO3 원본이 회전 디포머가 아니므로 회전 전용 편집 사항(기본 각도, 키폼)은 기록하지 않았습니다. + 텍스처 소 재연결은 에디터에서만 사용하는 상태이므로 CMO3에 기록되지 않습니다. + 기본 지오메트리의 정점 수가 CMO3 원본과 일치하지 않아 기록하지 않았습니다. + 대조할 UV가 드로어블에 없어 UV를 기록하지 않았습니다. + 디포머를 이동할 CMO3 파트가 없어 해당 파트는 변경하지 않았습니다. + 고정 그리기 순서가 키폼 트랙에 의해 가려져 있어 CMO3에서 별도로 저장할 수 없습니다. + 컴포지트의 고정 값이 파트의 키폼 트랙에 의해 가려져 있어 CMO3에서 별도로 저장할 수 없습니다. + 파트 유형의 컴포지트 마스크는 CMO3에서 하위 드로어블로 평탄화됩니다. + CMO3 모델에 이 유형의 항목을 생성할 세트가 없어 새 항목을 생성하지 않았습니다. + 새로 생성된 항목에는 아직 CMO3 원본이 없어 패널 순서에서 제외되었습니다. + 생성된 그룹이 편집된 파라미터 트리에 없어 생성하지 않았습니다. + 생성된 드로어블에 복제할 텍스처 소스가 없어 생성하지 않았습니다. + 글루가 적용된 드로어블에 CMO3 원본이 없어 글루를 생성하지 않았습니다. + 메쉬에 %1$d개의 정점이 있으며, 편집 가능한 메쉬의 간선 테이블이 인덱싱할 수 있는 %2$d개를 초과하므로 간선 테이블을 다시 생성하지 않았습니다. + 글루가 적용된 메쉬에 편집 가능한 메쉬의 정점 ID 테이블이 없어 글루를 다시 연결할 수 없습니다. + 글루 쌍의 인덱스가 해당 메쉬의 정점 ID 테이블 범위를 초과하여 글루를 다시 연결하지 않았습니다. + %1$s CMO3는 객체당 하나의 그리드만 저장합니다. + 그리드 축 파라미터 %1$s에 CMO3 원본이 없어 키폼 그리드를 기록하지 않았습니다. + 블렌드 셰이프 파라미터 %1$s에 CMO3 원본이 없어 블렌드 셰이프를 기록하지 않았습니다. + 기본 메쉬가 없는 키폼은 CMO3에 포함할 수 없습니다. + CMO3는 정수 단위의 드로우 순서만 저장하므로 소수 값은 기록하지 않았습니다. + 키폼이 없는 고정 글루 강도는 CMO3에 저장할 수 없습니다. + 지오메트리의 키가 지정된 범위를 벗어난 키는 하나의 그리드에 포함할 수 없습니다. + 지오메트리가 없는 채널 키는 하나의 그리드에 포함할 수 없습니다. + %1$s 트랙의 범위를 벗어난 키는 하나의 그리드에 포함할 수 없습니다. + CMO3에는 지정된 월드 원점을 저장하지 않으므로 파일을 다시 열 때 캔버스 중앙을 기준으로 원점을 계산합니다. + 모델에 루트 파라미터 그룹이 없어 파라미터 트리를 다시 생성하지 않았습니다. + 모델에 루트 파트가 없어 파트 패널 순서를 다시 생성하지 않았습니다. + 모델에 파라미터 세트가 없어 파라미터 순서를 기록하지 않았습니다. + 결합된 쌍 %1$s + %2$s가 서로 인접하도록 파라미터 순서를 조정했습니다. + 모델에 캔버스가 없어 캔버스 크기를 기록하지 않았습니다. + 이 문서에 텍스처 관리자가 없어 원본 아트워크 표시 모드를 기록할 수 없습니다. + 이 드로어블에는 선택한 표시 모드에 사용할 텍스처 입력이 없어 기존 표시 모드를 유지합니다. + 이 아트워크는 어떤 아틀라스 페이지에도 패킹되어 있지 않아 업데이트할 배치가 없습니다. + 이 아트워크가 아틀라스 페이지에서 이동했지만 페이지 이미지에는 여전히 이전 위치에 표시됩니다. 다시 패킹하여 해당 위치를 갱신하세요. + 이 아트워크의 이름 또는 크기가 변경되어 아틀라스 배치에 반영할 수 없습니다. 대신 아트워크를 다시 가져오세요. + 이 드로어블이 다른 아트워크에 연결되어 있으므로 다시 패킹하는 대신 아트워크를 다시 가져와야 합니다. + CMO3는 캔버스 크기를 정수 픽셀 단위로 저장하므로 소수 값은 기록하지 않았습니다. + 내보내기를 진행하면 기존 파일 %1$d개를 덮어씁니다: %2$s + MOC3 내보내기 옵션 + 내보내기 + 콘텐츠 + 부속 파일 + 크기 + 숨겨진 파트 내보내기 + 숨겨진 드로어블 내보내기 + 스케치 파트 내보내기 + 물리 설정 (physics3.json) + 유저 데이터 (userdata3.json) + 표시 정보 (cdi3.json) + 유닛당 픽셀 수 + 캔버스: %1$s × %2$s 유닛 + 확인 + %1$s을(를) 읽을 수 없습니다. + %1$s은(는) 호환되지 않는 파일 형식입니다. + %1$s을(를) 아직 에디터에서 열 수 없습니다. + %1$s을(를) 열 수 없습니다. 파일이 손상되었을 수 있습니다. + %1$s을(를) 가져올 수 없습니다. 동일한 위치에서 model3.json 매니페스트 파일을 찾을 수 없습니다. + %1$s을(를) 가져올 수 없습니다. model3.json에서 참조하는 텍스처가 없거나 읽을 수 없습니다. + 도움말 + 소스 코드… + 웹사이트… + 공식 문서… + 제작진… + 빠른 설정… + Umamo에 대해서… + Umamo에 대해서 + 버전 %1$s + GNU General Public License v3.0에 따라 라이선스가 부여됨 + 제작진 및 오픈소스 라이선스 + 닫기 + 뷰 맞춤 + 전체 프레임 맞춤 + 실제 크기 (100%) + 확대 + 축소 + 크게 확대 + 크게 축소 + 영역 확대 + 선택 해제 + 전체 선택 + 선택 반전 + 편집 모드 전환 + 오브젝트 모드 + 편집 모드 + 정점 잡기 + 좌우 위치 맞바꾸기 + 상하 위치 맞바꾸기 + 정점 크기 조절 + 정점 회전 + 정점 선택 모드 + 간선 선택 모드 + 면 선택 모드 + 사각형 선택 + 원형 선택 + 원형 반경 확대 + 원형 반경 축소 + UV 수평 반전 + UV 수직 반전 + X축 대칭 + Y축 대칭 + 선택 항목 추적 + %1$d페이지 + %1$d페이지 · %2$d × %3$d · 메쉬 %4$d개 + 원본 레이어 + 아트워크에서 찾기 + %1$s · %2$d × %3$d · 메쉬 %4$d개 + 일치하는 아트워크가 없습니다 + 이 문서에는 원본 아트워크가 없습니다. + 원본 아트워크 표시 전환 + 아틀라스 재배치 + 다음 텍스처 페이지 + 이전 텍스처 페이지 + 텍스처 페이지: 선택 항목 추적 + 핀 아트 배치 + 핀 아트 배치 해제 + 실행 취소 + 다시 실행 + 이전 작업 조정 + 표시/숨기기 + 검색 + 검색 초기화 + 잘라내기 + 복사 + 붙여넣기 + 전체 선택 + 열기 + 편집 + 선택 + 모드 변경 + 파트 표시/숨기기 전환 + 파트 이름 변경 + 파트 선택 가능/불가능 전환 + 파트 이동 + 메쉬 표시/숨기기 전환 + 메쉬 이름 변경 + 메쉬 선택 가능/불가능 전환 + 메쉬 이동 + 디포머 이름 변경 + 디포머 선택 가능/불가능 전환 + 디포머 이동 + 키프레임 삽입 + 키프레임 이동 + 키프레임 제거 + 키프레임 선 + 파라미터 선택 + 파라미터 조정 + 파라미터 범위 편집 + 파라미터 연결 + 파라미터 연결 해제 + 파라미터 이동 + 그룹 만들기 + 그룹 삭제 + 그룹 이름 변경 + 파라미터 추가 + 파라미터 이름 변경 + 파라미터 삭제 + 파라미터 삭제 (키 이동) + 정점 이동 + 위치 맞바꾸기 + 위치 맞바꾸기 + 정점 크기 조절 + 정점 회전 + 정점 슬라이드 + UV 이동 + UV 크기 조절 + UV 회전 + UV 대칭 + 오브젝트 이동 + 오브젝트 크기 조절 + 오브젝트 회전 + 요소 선택 + 선택 모드 변경 + 파트 삭제 + 메쉬 삭제 + 디포머 삭제 + 가이드 이미지 표시/숨기기 전환 + 파트 그리기 순서 설정 + 그룹 모드 설정 + 컴포지트 설정 + 혼합 모드 설정 + 알파 모드 설정 + 후면 제거 전환 + 마스크 반전 전환 + 상위 디포머 설정 + 마스크 설정 + 곱하기 색상 설정 + 스크린 색상 설정 + 불투명도 설정 + 그리기 순서 설정 + 디포머 불투명도 설정 + 디포머 곱하기 색상 설정 + 디포머 스크린 색상 설정 + X축 반전 설정 + Y축 반전 설정 + 파트 설정 + 기본 각도 설정 + 바이리니어 워프 전환 + 워프 그리드 변경 + 캔버스 크기 설정 + 월드 원점 설정 + 텍스처 표시 변경 + 아틀라스 내부 아트 이동 + 아틀라스 내부 아트 회전 + 아틀라스 내부 아트 크기 조절 + 아틀라스 내부 아트 고정 + 아틀라스 내부 아트 고정 해제 + 아틀라스 재배치 + 런타임 타겟 설정 + 퍼펫 + 아마추어 + 파트 + 디포머 + 드로어블 + 제한 활성/비활성 전환 + 선택 가능 열 + 표시 열 + 빈 오브젝트 + 표시/숨기기 전환 + 선택 가능/불가능 전환 + 이름 변경 + 삭제 + 계층 삭제 + 파트: %1$d + 드로어블: %1$d + 파라미터: %1$d + 디포머: %1$d + 글루: %1$d + LMB / Enter: 확인 + RMB / Esc: 취소 + 편집 모드 + 표시 + 그랩 + 크기 조절 + 회전 + 키 추가 + 키 삭제 + 고정 + 선택 모드 + %1$d/%2$d개 정점 + %1$d/%2$d개 간선 + %1$d/%2$d개 면 + 정점 수: %1$d + 정점 수: %1$d/%2$d + 삼각면: %1$d + 삼각면: %1$d/%2$d + 선택에 변형할 수 있는 항목이 없습니다. 디포머는 아직 지원되지 않습니다. + 메쉬가 변형된 상태에서는 변형할 수 없습니다. 먼저 모든 파라미터를 초기화해 주세요. + 워프 디포머로 감쌀 메시가 있는 드로어블 또는 파트를 선택하세요. + 워프 디포머 만들기 + 워프 디포머 만들기 + 워프 디포머 만들기 + 워프 디포머 + 워프 디포머 만들기 + 작업을 수행할 수 없습니다. + X축 기준 + Z축 기준 + 기준점 + 중간점 + 개별 원점 + 활성 요소 + 2D 커서 + 스냅 + 월드 원점으로 커서 이동 + 선택 항목으로 커서 이동 + 활성 요소로 커서 이동 + 그리드로 커서 이동 + 그리드로 선택 항목 이동 + 커서로 선택 항목 이동 + 커서로 선택 항목 이동 (간격 유지) + 활성 요소로 선택 항목 이동 + 픽셀로 선택 항목 이동 + 커서로 선택 항목 이동 + 커서로 선택 항목 이동 (간격 유지) + 그리드로 선택 항목 이동 + 픽셀로 커서 이동 + 선택 항목으로 커서 이동 + 그리드로 커서 이동 + 커서 아래 연결된 항목 선택 + 연결된 항목 선택 + 선택 항목 프레임 맞춤 + 편집 중인 메쉬 전환 + 계층 선택 + 계층 선택 + 복제 + 정점 병합 + 중심점에 병합 + 첫 번째 점에 병합 + 마지막 점에 병합 + 분리 + 정점 연결 + 정점 추가 + 정점 슬라이드 + 복제 + 정점 병합 + 분리 + 정점 연결 + 정점 추가 + 정점 삭제 + 드로어블 복제 + 병합하려면 정점 모드에서 두 개 이상의 정점을 선택해야 합니다. + 연결하려면 정점 모드에서 정확히 두 개의 정점을 선택해야 합니다. + 연결할 수 없습니다: 절단선이 교차하는 대상이 없거나 지오메트리가 비정상적입니다. + 정점 추가를 적용할 수 없습니다. 삼각형을 닫은 뒤 Enter. 자세한 내용은 로그를 보세요. + 분리할 수 없습니다: 선택 영역에 분할할 수 있는 팬이 존재하지 않습니다. + 일부 드로어블에 원본 아트워크가 없지만 여전히 아틀라스에서 표시되고 있습니다. + 모든 드로어블에 원본 아트워크 레이어가 없으며 아틀라스에서 표시되고 있습니다. + 아틀라스 재배치 완료. + 재배치 취소됨: 배치되는 동안 아틀라스가 변경되었습니다. + 아틀라스가 이미 배치되어 있습니다. 변경된 사항이 없습니다. + 선택 영역에 편집할 수 있는 UV가 없습니다. + 대칭 복사할 대상이 없습니다. + 퍼펫의 UV가 아틀라스가 아닌 원본 아트워크를 참조하고 있으므로 이동할 배치가 없습니다. + 선택한 항목이 아틀라스 페이지에 패킹되어 있지 않거나 원본 아트워크가 없습니다. + 배치를 이동하려면 UV 편집기에서 아틀라스 페이지를 표시하세요. + 이 페이지에 배치된 선택 항목이 없습니다. + 원본 아트에서 아틀라스를 재구성할 수 없으므로 배치를 이동할 수 없습니다. + 배치가 다른 타일과 겹칩니다. 충돌을 해결하려면 아틀라스를 다시 배치하세요. + 배치가 페이지 경계를 벗어납니다. 튀어나간 영역은 잘려 나갑니다. + 선택한 타일이 고정되어 있습니다. 변형하려면 고정을 해제하세요. + 선택한 모든 드로어블이 상위 항목에 숨겨져 있어 편집할 수 없습니다. + 비례 편집 켜기/끄기 전 + 비례 편집 감쇠: 부드럽게 + 비례 편집 감쇠: 구체 + 비례 편집 감쇠: 루트 + 비례 편집 감쇠: 날카롭게 + 비례 편집 감쇠: 선형 + 비례 편집 감쇠: 균일 + 부드럽게 + 구형 + 루트 + 날카롭게 + 선형 + 균일 + 비례 %1$s · %2$d + 비례 편집 켜짐. + 비례 편집 꺼짐. + 비례 감쇠 + 더 보기 + 연결된 요소만 비례 편집 전환 + 연결됨 + 배치 + 겹침 + 페이지 바깥 + Δ %1$d, %2$d px + %1$s° + ×%1$s + 비례 편집: 연결된 요소만. + 비례 편집: 반경 내 모두. + 기준점 + 스냅 + UV 스냅 + 병합 + 툴바 전환 + 사이드바 전환 + 사이드바 + 도구 및 항목 패널이 여기에 표시됩니다. + 상위 파트 + 상위 디포머 + 마스크: %1$d + 메쉬: 정점 %1$d개, 삼각면 %2$d개 + 메쉬 없음 + 그리드: %1$d × %2$d + 그리드 X: %1$d + 그리드 Y: %1$d + 그리드 + 워프 격자 각 축의 분할 수(2–16). 값을 올리면 현재 변형을 샘플링해 제어점을 추가하므로, 모양은 유지한 채 격자를 더 촘촘하게 만들 수 있습니다. + %1$d 선택됨 + 일치하는 속성이 없습니다. + 문서 + 오브젝트 + 데이터 + 캔버스 + 표시 + 원본 아트워크 표시 + 런타임 + 변형 + 관계 + 메쉬 + 텍스처 + 혼합 + 디포머 + 파트 + 캔버스 없음 + 타겟 + 타겟 없음 (모든 기능) + Ayagami (Cubism %1$s 호환) + 제한된 기능: + 모든 기능을 사용할 수 있습니다. + %1$s - 현재 사용 중 + 새로운 워프 디포머 방식 + 마스크 반전 + 블렌드 셰이프 (아트 메쉬 및 워프 디포머) + 블렌드 셰이프 파라미터 + 곱하기 색상 + 스크린 색상 + 블렌드 셰이프 (파트, 회전 디포머, 글루) + 모션-싱크 + 혼합 모드 + 파트 컴포지트 (오프스크린 드로잉) + 파라미터 반복 + 아트 패스 + 텍스처 소스: %1$s + 개별 아틀라스 바인딩 + 고정 + 너비 + 높이 + X 중심 + Z 중심 + X 위치 + Z 위치 + X 크기 + Z 크기 + 종횡비 고정 + 혼합 + 알파 + 후면 제거 + 마스크 반전 + X축 반전 + Y축 반전 + 기본 각도 + 이중선형(사각형) + 가이드 이미지 + 그리기 순서 + 그룹 모드 + 불투명도 + 곱하기 색상 + 스크린 색상 + 마스크 적용 대상 + 마스크 추가… + 마스크 제거 + 관계 초기화 + 뷰포트 또는 아웃라이너에서 선택하세요. + px + ° + % + 최대 페이지 크기 + 여백 + 돌출 + 회전 허용 + 고정된 타일 유지 + 2의 거듭제곱 페이지 + 정사각형 페이지 + 페이지 축소 + 알파 임계값 + X 이동 + Y 이동 + 각도 + X 크기 조절 + Y 크기 조절 + + Z 이동 + Z 크기 조절 + 비례 편집 + 감쇠 + 비례 편집 크기 + 연결된 것만 + 계수 + + 병합 위치 + 중심 + 처음 + 마지막 + 표준 + 가산 + 곱하기 + 가산 (레거시) + 가산 (발광) + 어둡게 하기 + 곱하기 (레거시) + 색상 번 + 선형 번 + 밝게 하기 + 스크린 + 색상 닷지 + 오버레이 + 소프트 라이트 + 하드 라이트 + 선형 라이트 + 색조 + 색상 + 위에 놓기 + 위에 합성 + 제외 + 결합 + 분리 + 통과 + 그룹화 + 격리 + 기본으로 초기화 + 전체 초기화 + 범위 + 아래 파라미터와 연결 + 연결 해제 후 두 슬라이더로 분리 + 드래그하여 순서 변경 + 새 그룹 + 새 그룹 + 이름 변경 + 그룹 삭제 + 파라미터 추가 + 키폼 파라미터 추가 + 블렌드 셰이프 파라미터 추가 + 파라미터 삭제 + 키 버리기 + 키 이동… + 새 파라미터 + 선택 항목이 사용하는 파라미터만 표시 + 최소 + 기본 + 최대 + 설정 + 설정 + 설정 닫기 + 빠른 설정 + 계속 + 인터페이스 + 색상 + 뷰포트 + 단축키 설정 + 펜 + 테마 + 다크 + 라이트 + 시스템 + 언어 + 작업 내역 단계 + 프리셋 + 단축키 프리셋 + 기본 + Cubism + Blender + 프리셋으로 초기화 + 단축키를 누르세요… + 지정되지 않음 + 단축키 지우기 + %1$s은(는) 이미 “%2$s”에 지정되어 있습니다. 다시 지정하시겠습니까? + 다시 지정 + 펜 설정은 곧 지원될 예정입니다. + 확대/축소 단계(%) + 확대/축소 큰 단계(%) + 그리드 크기 + 그리드 세분화 + 슈퍼샘플링(2배 렌더링 품질) + 패널 크기 조정 중에도 슈퍼샘플링 유지 + 뷰포트 + 선택 강조 + 활성 선택 강조 + 경고 + 고정된 배치 + 메쉬 편집 + 정점 + 간선 + 면 + 대기 + 선택됨 + 활성 + 키 외 + 드로어블: %1$s + 파트: %1$s + 디포머: %1$s + 키폼 시트 + 어떤 파라미터에 키를 삽입하시겠습니까? + 어떤 파라미터에서 키를 제거하시겠습니까? + %1$s 선택 + 필터로 인해 모든 트랙이 숨겨져 있습니다. + 변형 트랙 + 속성 트랙 + 블렌드 셰이프 트랙 + 이 파라미터에는 아직 키가 지정되지 않았습니다. + 드로어블 + 워프 디포머 + 회전 디포머 + 파트 + 글루 + 지오메트리 + 블렌드 셰이프 + 그리기 순서 + 불투명도 + 곱하기 + 스크린 + X축 뒤집기 + Y축 뒤집기 + 글루 강도 + 키프레임 추가 + 모든 키에 맞추기 + 키프레임 왼쪽으로 미세 이동 + 키프레임 오른쪽으로 미세 이동 + 선택된 키 삭제 + 키프레임 삭제 + 키를 지정할 수 있는 속성을 가리켜 키프레임을 삽입하세요. + 키를 추가할 파라미터를 선택하세요. + diff --git a/module/ui/src/commonMain/composeResources/values/strings.xml b/module/ui/src/commonMain/composeResources/values/strings.xml new file mode 100644 index 0000000..c315fda --- /dev/null +++ b/module/ui/src/commonMain/composeResources/values/strings.xml @@ -0,0 +1,1081 @@ + + + + Umamo + + Untitled + (read-only) + + + Expand + Collapse + Filters + + + Modelling + Texture + Physics + + New Workspace + Workspace + Rename + Duplicate + copy + Delete + + Previous Workspace + Next Workspace + + Reset Workspace + + + 2D Viewport + UV Editor + Outliner + Parameters + Properties + Tool Settings + History + Logs + Sources + + + Copy to Clipboard + Export to File… + No log output yet + + + Split Left/Right + Split Top/Bottom + Close Area + Change Editor Type + + + File + New + Open… + Save + Save As… + Open Recent + Import + Export + CMO3… + MOC3… + Artwork… + CMO3… + MOC3… + Image… + New Document + Open Document… + Save Document + Save Document As… + Import CMO3… + Import MOC3… + Import Artwork… + Reload Artwork + Relink Art + Match Artwork Automatically + Replace Artwork… + Delete Art + Export CMO3… + Export MOC3… + Export Image… + Exit + + + Edit + Undo + Redo + Settings… + + + Workspace + Reset Workspace + Export This Workspace… + Export All Workspaces… + Import Workspace… + + + Confirm + Cancel + + Discard + Reset + Replace + Overwrite + Quit Without Saving + Save + Don’t Save + Reset this workspace to its default layout? + Replace all workspaces with the imported file? + The document has unsaved changes. Discard them? + The document has unsaved changes. Quit without saving? + The document has unsaved changes. Save them first? + The document has unsaved changes. Save them before quitting? + + The file was exported, but the following could not be carried into CMO3: + The file was exported, but the following could not be carried into MOC3: + The atlas was not repacked. These tiles could not be packed: + Drawable mesh is larger than the atlas page size. + Source artwork layer has no opaque pixels. + Source artwork layer is below the minimum opaque coverage. + Source artwork layer could not be decoded. + Drawable's current placement could not be inverted. + Pinned placement does not fit inside the maximum page size. + Base geometry or UVs were edited on: %1$s. The export keeps them as authored, but editing those meshes or their atlas in the Cubism Editor may re-derive and corrupt the UV mapping. + This model has no source artwork(it came from a MOC3, which stores only packed texture atlases). A stand-in source document was rebuilt from the %1$d atlas page(s), so the file carries the full rig and opens in both Umamo and the Cubism Editor, but every layer in it is a slice of a baked atlas page rather than the artwork this rig was drawn from. Reconcile the original layered artwork(PSD/CLIP/KRA) into this document to export real, editable layers. + %1$s share an atlas slot with a twin at another placement and could not be given a slot of their own (the art is larger than an atlas page). The Cubism Editor's layered view shows them at the first twin's placement; the atlas view and the runtime are unaffected. + + %1$s is not available for the target runtime version, so it was removed from: %2$s. + (+%1$d more) + + Parameter + Parameter Group + Part + Deformer + Drawable + Glue + Document + Keyform + + A drawable with no mesh cannot be written. + + %1$s is keyed over a narrower span than the object's grid, so it was written as a constant. MOC3 stores one grid per object. + A guide-image (sketch) part is not runtime content, so it was left out. + The part is hidden and the export options omit hidden parts, so its contents were left out. + The drawable is hidden and the export options omit hidden art meshes, so it was left out. + An unkeyed drawable under a deformer has no parent-space geometry to write, so it was left out. + The canvas-to-parent conversion returned %1$d coordinates for %2$d, so the rest mesh was written unconverted. + No atlas page is bound to this drawable, so it was written pointing at page 0. + The clipping mask %1$s is not in this export, so the mesh was written unclipped by it. + A clipping mask names a drawable that could not be written, so it was dropped from the offscreen. + A warp deformer with no control-point grid has no lattice to write. One empty lattice was written in its place so the file stays readable, and everything bound to this deformer collapses to the origin. + A rotation deformer with no pivot grid has no transform to write, so the identity transform was written in its place. + A glue naming a drawable that is not in this export was dropped. + The id does not fit a moc's %1$d-byte id record, so it was written truncated to “%2$s”. + The id does not fit a moc's %1$d-byte id record, and truncating it collided with another object's id, so it was written as “%2$s”. + + There is no matching CMO3 source to reconcile against, so the change was not written. + A parameter's kind change (normal / blend shape) is not lowered. + A deformer's kind change is not lowered. + The CMO3 source is not a warp deformer, so warp-only edits (bilinear mode, lattice, keyforms) were not written. + The CMO3 source is not a rotation deformer, so rotation-only edits (base angle, keyforms) were not written. + Texture-source rebinding is editor-only state and is not written to CMO3. + The base geometry does not match the CMO3 source's vertex count, so it was not written. + The drawable has no UVs to reconcile, so none were written. + There is no CMO3 part to move the deformer to, so its part was left unchanged. + The static draw order is shadowed by its keyform track, so CMO3 cannot store it independently. + The composite's static values are shadowed by the part's keyform tracks, so CMO3 cannot store them independently. + Part-typed composite masks flatten to their descendant drawables in CMO3. + + The CMO3 model has no set of this kind to create into, so the new entity was not synthesized. + The newly created entity has no CMO3 source yet, so it was left out of the panel order. + The created group is not in the edited parameter tree, so it was not synthesized. + The created drawable has no texture source to clone, so it was not synthesized. + A glued drawable has no CMO3 source, so the glue was not synthesized. + + The mesh has %1$d vertices, past the %2$d the editable mesh's edge table can index, so the edge table was not rebuilt. + A glued mesh has no editable-mesh vertex-id table, so the glue could not be re-bound. + A glue pair indexes past its mesh's vertex-id table, so the glue was not re-bound. + + %1$s CMO3 stores one grid per object. + The grid axis parameter %1$s has no CMO3 source, so the keyform grid was not written. + The blend-shape parameter %1$s has no CMO3 source, so the blend shape was not written. + Keyforms without a base mesh cannot be bundled into CMO3. + CMO3 stores a whole-number draw order, so the fractional value was not written. + A static glue intensity with no keyforms has nowhere to live in CMO3. + + Keys outside the geometry's keyed span cannot be bundled into one grid. + Channel keys with no geometry cannot be bundled into one grid. + Keys outside the %1$s track's span cannot be bundled into one grid. + + CMO3 stores no authored world origin, so reopening the file derives it from the canvas center. + The model has no root parameter group, so the parameter tree was not rebuilt. + The model has no root part, so the parts panel order was not rebuilt. + The model has no parameter set, so the parameter order was not written. + The parameter order was adjusted so the combined pair %1$s + %2$s stays adjacent. + The model has no canvas, so the canvas size was not written. + This document has no texture manager, so the source-artwork display mode could not be written. + This drawable has no texture input for the chosen display mode, so it keeps the one it had. + This artwork is not packed onto any atlas page, so there was no placement to update. + This artwork was moved on its atlas page, but the page image still shows it at its old spot; repack to redraw it. + This artwork's name or size changed, which an atlas placement cannot carry; re-import the artwork instead. + This drawable was bound to different artwork, which needs the artwork re-imported rather than repacked. + CMO3 stores whole canvas pixels, so the fractional canvas size was not written. + + Exporting will overwrite %1$d existing file(s): %2$s + + MOC3 Export Options + Export + Content + Sidecar Files + Scale + Export hidden parts + Export hidden drawables + Export sketch parts + Physics settings (physics3.json) + User data (userdata3.json) + Display info (cdi3.json) + Pixels per unit + Canvas: %1$s × %2$s units + + Export Image + Region + Viewport + Canvas + Visible Content + Scale + Background + Transparent + Solid Color + Viewport Grid + Color + %1$d × %2$d px + Nothing is visible to capture. + No viewport to capture. Point at a 2D viewport before exporting. + The document has no canvas. + %1$d × %2$d px is past the %3$d px limit. + + Okay + Could not read %1$s. + %1$s is not a file format Umamo recognizes. + %1$s cannot be opened in the editor yet. + Could not open %1$s. The file may be damaged. + Could not import %1$s. Its model3.json manifest was not found next to the file. + Could not import %1$s. A texture referenced by its model3.json is missing or unreadable. + %1$s has no layers with pixels to import. + %1$s was made by a newer version of Umamo and cannot be opened by this one. + + %1$s opened read-only. It holds entries this version of Umamo cannot interpret, so Save is unavailable: %2$s + Could not save %1$s. %2$s + + Could not export %1$s. %2$s + The viewport renderer could not draw the image. + There was not enough memory for a %1$d × %2$d px image. Try a smaller scale. + + + Help + Source Code… + Web Site… + Documentation… + Credits… + Quick Setup… + About Umamo… + + About Umamo + + Version %1$s + Licensed under the GNU General Public License v3.0 + Credits & Third-Party Licenses + Close + + + Fit View + Frame All + Actual Size (100%) + Zoom In + Zoom Out + Zoom In (Large Step) + Zoom Out (Large Step) + Zoom Region + + + Clear Selection + Select All + Invert Selection + Toggle Edit Mode + Object Mode + Edit Mode + Grab Vertices + Reverse Positions Horizontally + Reverse Positions Vertically + Scale Vertices + Rotate Vertices + Vertex Select Mode + Edge Select Mode + Face Select Mode + Box Select + Circle Select + Grow Circle Radius + Shrink Circle Radius + Mirror UVs Horizontally + Mirror UVs Vertically + + + Mirror X + Mirror Y + + + Follow Selection + Page %1$d + Page %1$d · %2$d × %3$d · %4$d meshes + Source Layer + Find by Artwork + %1$s · %2$d × %3$d · %4$d meshes + No artwork matches + This document has no source artwork. + Toggle Source Artwork Display + Repack Atlas + Next Texture Page + Previous Texture Page + Texture Page: Follow Selection + Pin Art Placement + Unpin Art Placement + + + Undo + Redo + Adjust Last Operation + Toggle Visibility + + + Search + Clear search + + + Cut + Copy + Paste + Select All + + + Open + Edit + Select + Change Mode + Toggle Part Visibility + Rename Part + Toggle Part Selectability + Move Part + Toggle Mesh Visibility + Rename Mesh + Toggle Mesh Selectability + Move Mesh + Rename Deformer + Toggle Deformer Selectability + Move Deformer + Insert Keyframe + Move Keyframe + Remove Keyframe + Select Keyframe + Select Parameter + Adjust Parameter + Edit Parameter Range + Link Parameters + Unlink Parameters + Move Parameter + Create Group + Delete Group + Rename Group + Add Parameter + Rename Parameter + Delete Parameter + Delete Parameter (Move Keys) + Move Vertices + Scale Vertices + Rotate Vertices + Slide Vertex + Reverse Positions + Reverse Positions + Move UVs + Scale UVs + Rotate UVs + Mirror UVs + Move Objects + Scale Objects + Rotate Objects + Select Elements + Change Select Mode + Delete Part + Delete Mesh + Delete Deformer + Toggle Guide Image + Set Part Draw Order + Set Group Mode + Set Composite + Set Blend Mode + Set Alpha Mode + Toggle Back-Face Culling + Toggle Invert Mask + Set Parent Deformer + Set Masks + Set Multiply Color + Set Screen Color + Set Opacity + Set Draw Order + Set Deformer Opacity + Set Deformer Multiply Color + Set Deformer Screen Color + Set Flip X + Set Flip Y + Set Part + Set Base Angle + Toggle Bilinear Warp + Change Warp Grid + Set Canvas Size + Set World Origin + Change Texture Display + Move Art On Atlas + Rotate Art On Atlas + Scale Art On Atlas + Pin Art On Atlas + Unpin Art On Atlas + Repack Atlas + Relink Art + Unbind Art + Delete Art + Delete Art, Ignore Layer + Ignore Layer + Stop Ignoring Layer + Import Artwork + Reload Artwork + Relink Art + Match Artwork + Replace Artwork + Set Runtime Target + + + Puppet + Armature + Parts + Deformers + Reload Artwork Files + Artwork files changed on disk. Reload to take the changes. + Match Automatically: Rebind the art whose layers the files no longer have to their best matches. + File Actions + Replace Artwork… + Reload This File + Layer Actions + Ignore Layer + Stop Ignoring + Review this binding + Accept %1$s (%2$d%) + Accept %1$s (%2$d%) and remove its new drawable + Relink Manually… + Leave for Now + Bound + Unbound + Missing Files + Needs Review + Present + Missing + Unknown + Bound + Bound by name + Unbound + Unplaced + Needs review: The file no longer has this layer + Needs review: The layer is empty in the file + Needs review: The replacement file has no layer under this key + Ignored: A reload never adds this layer + Unbound Art + %1$s · %2$d layers + no path recorded + %1$d × %2$d at %3$d, %4$d + %1$d × %2$d at %3$s x, %4$s z + page %1$d + Relink to a Layer + Unbind + Delete Art + No layer matches. + Drawables + Restriction Toggles + Selectable Column + Visibility Column + Empty + + + Toggle Visibility + Toggle Selectability + Rename + Delete + Delete Hierarchy + + + Parts: %1$d + Drawables: %1$d + Parameters: %1$d + Deformers: %1$d + Glues: %1$d + + + LMB / Enter: Confirm + RMB / Esc: Cancel + Edit Mode + Visibility + Grab + Scale + Rotate + Insert Key + Delete Key + Pin + Select Mode + %1$d/%2$d vertices + %1$d/%2$d edges + %1$d/%2$d faces + Verts: %1$d + Verts: %1$d/%2$d + Tris: %1$d + Tris: %1$d/%2$d + + + Nothing transformable in the selection. Deformers are not yet supported. + Can't transform while mesh is deformed. Reset all parameters first. + Select a drawable or part that has meshes to wrap in a warp deformer. + Create Warp Deformer + Create Warp Deformer + Create Warp Deformer + Warp Deformer + Create Warp Deformer + Action unavailable. + + + Along X + Along Z + + + Pivot Point + Median Point + Individual Origins + Active Element + 2D Cursor + Snap + Cursor to World Origin + Cursor to Selected + Cursor to Active + Cursor to Grid + Selection to Grid + Selection to Cursor + Selection to Cursor (Keep Offset) + Selection to Active + + + Selection to Pixels + Selection to Cursor + Selection to Cursor (Keep Offset) + Selection to Grid + Cursor to Pixels + Cursor to Selected + Cursor to Grid + + + Select Linked under Cursor + Select Linked + Frame Selected + Switch Edited Mesh + Select Hierarchy + Select Hierarchy + + + Duplicate + Merge Vertices + Merge at Center + Merge at First + Merge at Last + Rip + Connect Vertices + Add Vertex + Vertex Slide + Duplicate + Merge Vertices + Rip + Connect Vertices + Add Vertex + Delete Vertex + Duplicate Drawable + Merge needs two or more selected vertices (vertex mode). + Connect needs exactly two selected vertices (vertex mode). + Can't connect: The cut crosses nothing, or the geometry is degenerate. + Couldn't accept Add Vertex: close a triangle (three edges), then Enter. See Logs for details. + Nothing to rip here: The selection has no fan to split. + Some drawables have no source artwork and are still displaying from the atlas. + All drawables do not have source artwork layers and are displaying from the atlas. + Atlas repacked. + Artwork imported with notes. See the log. + Artwork added. + Saving… + Saved %1$s. + Exporting image… + Exported %1$s. + A save is already in progress. + Waiting on save to finish… + Saved as UMA. The CMO3 structure Umamo does not model is not carried in this file; exports from this session still reconcile onto the original. + Saved as UMA. Physics, motions, expressions, user data, and pose from the MOC3 family are not carried in this file. + The document changed while the artwork was being added; nothing was applied. + The file has no layers with pixels to add. + Artwork reloaded: %1$d updated, %2$d added, %3$d matched. + Artwork reloaded: %1$d updated, %2$d added, %3$d matched, %4$d need review. See the log. + Artwork reloaded: %1$d updated, %2$d added, %3$d matched, %4$d need review; some art now reaches past its mesh. See the log. + %1$d artwork file(s) changed on disk. Press Reload to take the changes. + %1$d artwork file(s) changed since they were last read. Press Reload to take the changes. + %1$s is no longer where the document read it. + The artwork file(s) have not changed. + No artwork file could be read; nothing was reloaded. + Art relinked and reloaded. + Art relinked; its file could not be read, so the art did not change. + %1$d layer(s) matched, %2$d left for review. + No binding matched confidently enough; the suggestions are on the rows that need review. + Nothing left to match against: every candidate layer is already bound. Adjust Match Threshold on the reload's strip, or relink manually. + Artwork replaced: %1$d layer(s) reloaded by key, %2$d matched, %3$d left for review. + Repack canceled: the atlas changed while packing. + Atlas already packed; nothing changed. + The selection has no editable UVs. + Nothing is selected to mirror. + The puppet's UVs address the source artwork and not the atlas so there is no placement to move. + Nothing selected is packed on an atlas page or there is no source artwork. + Show an atlas page in the UV editor to move placements. + Nothing selected is packed on this page. + The atlas cannot be recomposed from its source art, so placements cannot move. + Placement overlaps another tile. Repack the atlas to clear the collision. + Placement extends past the page edge. The overhang is cropped. + Selected tile is pinned. Unpin it to transform it. + Nothing to edit, every selected drawable is hidden by a parent. + + + Toggle Proportional Editing + Proportional Falloff: Smooth + Proportional Falloff: Sphere + Proportional Falloff: Root + Proportional Falloff: Sharp + Proportional Falloff: Linear + Proportional Falloff: Constant + Smooth + Sphere + Root + Sharp + Linear + Constant + + Proportional %1$s · %2$d + Proportional editing on. + Proportional editing off. + Proportional Falloff + + More + Toggle Proportional Connected Only + Connected + Placement + Overlapping + Off page + Δ %1$d, %2$d px + %1$s° + ×%1$s + Proportional editing: connected only. + Proportional editing: all within radius. + + + Pivot Point + Snap + UV Snap + Merge + + + Toggle Toolbar + Toggle Sidebar + Sidebar + Tool and item panels will live here. + + + Parent Part + Parent Deformer + Masks: %1$d + Mesh: %1$d verts, %2$d tris + No mesh + Grid: %1$d × %2$d + Grid X: %1$d + Grid Y: %1$d + Grid + Conversion divisions for the warp lattice (2–16) on each axis. Raising a count adds control points by sampling the current deformation, so the art stays put while the lattice gets denser. + %1$d selected + + + No matching properties. + Document + Object + Data + Canvas + Display + Show source artwork + Runtime + Transform + Relations + Mesh + Texture + Blend + Deformer + Part + No canvas + Target + No Target (All Features) + Ayagami (Cubism %1$s Equivalent) + Restricted features: + All features are available. + %1$s - CURRENTLY IN USE + New Warp Deformer Method + Reversed Mask + Blend Shapes (Art Mesh and Warp Deformer) + Blend Shape Parameters + Multiply Color + Screen Color + Blend Shapes (Part, Rotation Deformer, Glue) + Motion-sync + Blend Mode + Part Composite (Offscreen Drawing) + Parameter Repeat + Art Path + Texture Source: %1$s + Own Atlas Binding + Pinned + + + Width + Height + Origin X + Origin Z + Position X + Position Z + Size X + Size Z + Lock Aspect Ratio + Blend + Alpha + Cull Back Faces + Invert Mask + Flip X + Flip Y + Base Angle + Bilinear (Quad) + Guide Image + Draw Order + Group Mode + Opacity + Multiply Color + Screen Color + Masked By + Add Mask… + Remove Mask + Clear relation + Pick from the viewport or outliner. + px + ° + % + + + Max Page Size + Gutter + Extrude + Allow Rotation + Keep Pinned Tiles + Power-of-Two Pages + Square Pages + Shrink Pages + Alpha Threshold + + Move X + Move Y + Angle + Scale X + Scale Y + + Move Z + Scale Z + Proportional Editing + Falloff + Proportional Size + Connected Only + Factor + + Merge At + Center + First + Last + Align + Offset X + Offset Z + Alpha Threshold + Birth Mesh Margin + Top Left + Top + Top Right + Left + Center + Right + Bottom Left + Bottom + Bottom Right + Match Threshold + + + The canvas width, in pixels. Resizing moves only its right edge, so the art stays where it is. + The canvas height, in pixels. Resizing moves only its bottom edge, so the art and the world axes stay put while Origin Z changes by the same amount. + Where the world axes cross, in pixels from the canvas's left edge. The Position fields measure from these axes. + Where the world axes cross, in pixels up from the canvas's bottom edge. The Position fields measure from these axes. + Draws each mesh from its original artwork layer instead of the packed atlas. A mesh whose layer the document does not keep still draws from the atlas. + The runtime this model is made for. Controls for features it cannot play are hidden, but nothing is removed from the document; only a MOC3 export leaves those features out. + The horizontal center of the mesh as it appears in the viewport, measured from the world axes. Editable only while every parameter is at its default. + The vertical center of the mesh as it appears in the viewport, measured up from the world axes. Editable only while every parameter is at its default. + The width of the mesh as it appears in the viewport, scaled about its center when changed. Editable only while every parameter is at its default. + The height of the mesh as it appears in the viewport, scaled about its center when changed. Editable only while every parameter is at its default. + The deformer's base rotation, in degrees. The angle each keyform sets is added to it. + The part this item belongs to. Clearing it moves the item out of every part. + The deformer this item is attached to. The item follows it as it moves, bends, or turns. + Holds this art in place on its atlas page. Moving it by hand in the UV editor is refused, and a repack leaves it where it is unless Keep Pinned Tiles is off. + Where this mesh stacks, from 0 to 1000: higher draws in front, and a tie goes to the one higher in the outliner. Inside a Grouped or Isolated part, it stacks only among that part's contents. + How opaque the mesh is, from 0 (invisible) to 1 (fully opaque). + How the mesh's colors mix with what is drawn behind it, like a paint app's layer blend modes. The Legacy modes ignore the Alpha setting. + How the mesh's transparency combines with what is behind it. Over stacks normally, Atop draws only over art already there, and Out erases what is behind it instead of drawing. Conjoint and Disjoint change how soft edges overlap. + Multiplies the mesh's colors by this color to darken or tint it. White leaves it unchanged. + Screens this color over the mesh to lighten it. Black leaves it unchanged. + Hides any part of the mesh that a deformation flips over, instead of drawing it mirrored. + Clips this mesh to the meshes listed here, so it shows only where they have art. + Shows the mesh only where its masks have no art, instead of only where they do. + Scales the opacity of everything this deformer moves, nested deformers included, from 0 (invisible) to 1 (unchanged). + Multiplies the colors of everything this deformer moves by this color. White leaves them unchanged. + Screens this color over everything this deformer moves. Black leaves it unchanged. + Bends each lattice cell smoothly between its four corners instead of as two triangles, so the art does not fold along the cell's diagonal. This is the new warp deformer method, which older runtimes cannot play. + Mirrors everything this deformer moves left to right, about its pivot. + Mirrors everything this deformer moves top to bottom, about its pivot. + Marks this part as a guide image, such as a reference sketch. It shows in the editor, but a MOC3 export leaves it and everything in it out. + Where the whole part stacks, from 0 to 1000: higher draws in front. Used only when Group Mode is Grouped or Isolated. + How the part's contents stack with the rest of the model. Pass Through stacks each mesh by its own draw order, Grouped stacks the whole part at the part's draw order, and Isolated also draws it as one layer with its own opacity, blend, colors, and masks. + How opaque the part's combined layer is, from 0 (invisible) to 1 (fully opaque). It applies once to the whole layer, so meshes overlapping inside the part do not show through each other. + How the part's combined layer mixes with what is drawn behind it, like a paint app's layer blend modes. The Legacy modes ignore the Alpha setting. + How the transparency of the part's combined layer combines with what is behind it. Over stacks normally, Atop draws only over art already there, and Out erases what is behind it instead of drawing. Conjoint and Disjoint change how soft edges overlap. + Multiplies the colors of the part's combined layer by this color. White leaves it unchanged. + Screens this color over the part's combined layer. Black leaves it unchanged. + Clips the part's combined layer to the meshes and parts listed here, so it shows only where they have art. + Shows the part's combined layer only where its masks have no art, instead of only where they do. + The largest page the pack may use, in pixels. With Shrink Pages on, a page is only this large when the art needs the room. + Empty space kept around each piece of art and along the page edge, in pixels, so neighboring art cannot bleed in when the texture is sampled. + How many pixels of each piece's edge color are copied outward into the gutter, which hides seams at the art's edges. It cannot be wider than the gutter. + Lets the pack turn art a quarter turn to fit more onto a page. + Leaves pinned art where it is and packs the rest around it. Turn it off to pack pinned art like everything else. + Rounds each page's width and height up to a power of two, such as 1024 or 2048. + Makes every page square. + Sizes each page to the art it holds instead of always using the maximum page size. + How opaque a pixel must be, from 1 to 255, to count as art when the empty border around each piece is trimmed away before packing. + How far the art moved right on the page, in pixels. Negative moves it left. + How far the art moved down the page, in pixels. Negative moves it up. + How far the art turned on the page, in degrees. + How much the art was scaled along its own width. 1 leaves it unchanged. + How much the art was scaled along its own height. 1 leaves it unchanged. + Where the added file's canvas sits on the document's canvas: Top Left lines up their top-left corners, Center centers it, and so on. + Moves the added art right from where Align puts it, in pixels. Negative moves it left. + Moves the added art up from where Align puts it, in pixels. Negative moves it down. + How opaque a pixel must be, from 1 to 255, to count as art when a layer's starting mesh is fitted around it. + How far a layer's starting mesh reaches past its visible art on every side, in pixels. + How sure a match must be, as a percentage, before a lost layer is relinked to it automatically. Weaker matches are left for review in the Sources panel. + How far the selection moved right, in pixels. Negative moves it left. + How far the selection moved down the texture, in pixels. Negative moves it up. + How far the selection moved up, in pixels. Negative moves it down. + How far the selection turned, in degrees. + How much the selection was scaled horizontally. 1 leaves it unchanged. + How much the selection was scaled vertically on the texture. 1 leaves it unchanged. + How much the selection was scaled vertically. 1 leaves it unchanged. + Also moves the unselected vertices near the selection, less the farther away they are. + The curve the proportional influence follows as it fades out toward the edge of Proportional Size. + How far the proportional influence reaches from the selection, in pixels. + Limits the proportional influence to vertices joined to the selection by mesh edges, measuring distance along those edges. + Where along its edge the vertex landed: 0 is where it started, and 1 is the neighboring vertex. + Where the merged vertices come together: at their center, or on the first or last vertex selected. + + Normal + Additive + Multiply + Additive (Legacy) + Additive (Glow) + Darken + Multiply (Legacy) + Color Burn + Linear Burn + Lighten + Screen + Color Dodge + Overlay + Soft Light + Hard Light + Linear Light + Hue + Color + + Over + Atop + Out + Conjoint + Disjoint + + Pass Through + Grouped + Isolated + + + Reset to default + Reset All + Range + Link with the parameter below + Unlink into two sliders + Drag to reorder + New Group + New Group + Rename + Delete Group + Add Parameter + Add Key Form Parameter + Add Blend Shape Parameter + Delete Parameter + Discard keys + Move keys to… + New Parameter + Only parameters the selection uses + Min + Default + Max + + + Settings + Settings + Close settings + + Quick Setup + Continue + + Interface + Colors + Viewport + Keybindings + Pen + Import + + Theme + Dark + Light + System + Language + + History Steps + + Preset + Keybindings Preset + Default + Cubism + Blender + Reset to Preset + Press a shortcut… + Unbound + Clear shortcut + + %1$s is already bound to “%2$s”. Reassign it? + Reassign + + Pen configuration is coming soon. + Parameter Template + Align Added Artwork + Watch Artwork Files + Reload Automatically + Notify Only + Off + When deleting art in the sources, also mark the layer as ignored. + In the Sources area, measure layer positions from the world axes instead of the art file's top-left corner. + Humanoid + None + + Zoom Step (%) + Coarse Zoom Step (%) + Grid Scale + Grid Subdivisions + + Supersampling (2x Render Quality) + Keep supersampling while resizing panels + + Viewport + Selection Highlight + Active Selection Highlight + Warning + Pinned Placement + Mesh Editing + Vertex + Edge + Face + Idle + Selected + Active + Off-key + + Drawable: %1$s + Part: %1$s + Deformer: %1$s + Keyform Sheet + Insert key on which parameter? + Remove key from which parameter? + Select %1$s + All tracks hidden by filters. + Deformation Tracks + Property Tracks + Blend Shape Tracks + Nothing is keyed on this parameter yet. + Drawable + Warp Deformer + Rotation Deformer + Part + Glue + Geometry + Blend Shape + Draw Order + Opacity + Multiply + Screen + Flip X + Flip Y + Glue Intensity + Insert Keyframe + Frame All Keys + Nudge Keyframe Left + Nudge Keyframe Right + Delete Selected Keys + Delete Keyframe + Point at a keyable property to insert a keyframe. + Select a parameter to key on. + \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/SettingsProvider.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/SettingsProvider.kt new file mode 100644 index 0000000..1c6b439 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/SettingsProvider.kt @@ -0,0 +1,78 @@ +package org.umamo.ui + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.settings.Settings +import org.umamo.storage.AppStorage +import org.umamo.ui.l10n.LOCALE_SETTINGS_KEY +import org.umamo.ui.l10n.UI_LANGUAGE_ENDONYMS +import org.umamo.ui.l10n.matchUiLanguage +import org.umamo.ui.l10n.systemLanguageTags +import org.umamo.ui.resources.Res + +/** + * App-wide settings, provided once at the Compose root by [ProvideSettings]. Reading it before it is + * provided is a programming error (the `error` default fires). `static` because the [Settings] instance + * is stable for the app's life - individual values change through its `changes` flow, not by swapping the + * local - so Compose need not track reads of this local for recomposition. + */ +val LocalSettings = staticCompositionLocalOf { error("LocalSettings not provided — wrap content in ProvideSettings") } + +/** + * Loads [Settings] over the platform [storage] (bundled `defaultSettings.json` ← the user's file) and + * provides it as [LocalSettings] to [content]. The load is async (the bundled default is a Compose + * resource), so [content] renders once settings are ready; for a tiny config file that's an imperceptible + * first frame. Each app supplies the right [storage] (`desktopAppStorage` / `androidAppStorage`). + * + * @param AppStorage storage The platform storage (config directory + IO). + * @param Function content The app content that may read [LocalSettings]. + */ +@Composable +fun ProvideSettings(storage: AppStorage, content: @Composable () -> Unit) { + val settings by produceState(initialValue = null, storage) { + value = loadAppSettings(storage) + } + settings?.let { loaded -> + CompositionLocalProvider(LocalSettings provides loaded, content = content) + } +} + +/** + * Reads the bundled `defaultSettings.json` (a Compose Multiplatform resource, so desktop and Android share + * one baseline) as text. + * + * @return String The default settings JSON. + */ +suspend fun defaultSettingsJson(): String = Res.readBytes("files/defaultSettings.json").decodeToString() + +/** + * Loads the app's settings - the bundled defaults under the user's file - and seeds a first run's choices, so + * every platform starts from the same state. The one load path both apps take: the desktop entrypoint calls + * it directly (it must hold settings before its window opens), and [ProvideSettings] calls it for Android. + * + * @param AppStorage storage The platform storage (config directory + IO). + * @return Settings The loaded, first-run-seeded settings. + */ +suspend fun loadAppSettings(storage: AppStorage): Settings = Settings.load(storage, defaultSettingsJson()).also { settings -> seedFirstRunSettings(settings) } + +/** + * Seeds what a first run decides before anything is shown: the UI language, matched from the operating + * system's preferred languages (English when none has a catalog). Runs only when no user settings file was + * found at load, so a language the rigger chose is never overridden. + * + * The match is written even when it is English: it pins the language the app first opened in, and it creates + * the user file, so the next launch finds settings and does not treat itself as a first run. The Quick Setup + * modal a first run opens then shows this language already selected. + * + * @param Settings settings The freshly loaded settings. + * @param List systemTags The operating system's preferred language tags, most preferred first. + */ +fun seedFirstRunSettings(settings: Settings, systemTags: List = systemLanguageTags()) { + if (settings.foundUserFile) { + return + } + settings.setString(LOCALE_SETTINGS_KEY, matchUiLanguage(systemTags, UI_LANGUAGE_ENDONYMS.keys)) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/SettingsState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/SettingsState.kt new file mode 100644 index 0000000..9144776 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/SettingsState.kt @@ -0,0 +1,220 @@ +package org.umamo.ui + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import org.umamo.settings.Settings + +/** + * A write-through, reactive binding to one string setting: reading the returned state yields the current + * value (the user override, else the default), and assigning to it persists immediately via + * [Settings.setString] - the auto-save the preferences UI is built on, with no commit step. A change to + * the same key from elsewhere (another control, a future shortcut) flows back in through the settings + * `changes` flow, so the binding stays in sync without the read-once-then-collect boilerplate each call + * site would otherwise repeat (cf. ProvideAppThemeFromSettings, PersistentEditorShell). + * + * @param String key The dotted settings key (e.g. "interface.theme"). + * @param String default The value used when the key is absent (rarely hit; defaultSettings.json seeds most). + * @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer. + */ +@Composable +fun rememberStringSetting(key: String, default: String): MutableState { + val settings = LocalSettings.current + val backing = remember(settings, key) { mutableStateOf(settings.getString(key) ?: default) } + // Re-read when this key is written from anywhere, so a value changed by another control or command + // (not just this binding's own setter) reflects here too. + LaunchedEffect(settings, key) { + settings.changes.collect { changedKey -> + if (changedKey == key) { + backing.value = settings.getString(key) ?: default + } + } + } + return remember(settings, key, backing) { WriteThroughSettingState(settings, key, backing) } +} + +/** + * The [MutableState] returned by [rememberStringSetting]: reads delegate to [backing] (kept current by + * the settings `changes` collector), and a write both persists through [Settings.setString] and updates + * [backing] at once so the new value is visible on the very next read without waiting for the flow to + * round-trip. + * + * @property Settings settings The settings instance the write persists into. + * @property String key The dotted key being bound. + * @property MutableState backing The local state mirroring the merged value. + */ +private class WriteThroughSettingState( + private val settings: Settings, + private val key: String, + private val backing: MutableState, +) : MutableState { + override var value: String + get() = backing.value + set(newValue) { + // Update the local mirror first so the read is immediate, then persist (which also emits on + // `changes`; the collector re-reading the now-identical value is a harmless no-op). + backing.value = newValue + settings.setString(key, newValue) + } + + override fun component1(): String = value + + override fun component2(): (String) -> Unit = { newValue -> value = newValue } +} + +/** + * A write-through, reactive binding to one number-valued setting - the [rememberStringSetting] + * counterpart for numeric keys, with the same auto-save and external-change semantics. + * + * @param String key The dotted settings key (e.g. "viewport.zoomStepPercent"). + * @param Int default The value used when the key is absent (rarely hit; defaultSettings.json seeds most). + * @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer. + */ +@Composable +fun rememberIntSetting(key: String, default: Int): MutableState { + val settings = LocalSettings.current + val backing = remember(settings, key) { mutableStateOf(settings.getInt(key) ?: default) } + // Re-read when this key is written from anywhere, so a value changed by another control or command + // (not just this binding's own setter) reflects here too. + LaunchedEffect(settings, key) { + settings.changes.collect { changedKey -> + if (changedKey == key) { + backing.value = settings.getInt(key) ?: default + } + } + } + return remember(settings, key, backing) { WriteThroughIntSettingState(settings, key, backing) } +} + +/** + * The [MutableState] returned by [rememberIntSetting]: the numeric twin of + * [WriteThroughSettingState], persisting through [Settings.setInt]. + * + * @property Settings settings The settings instance the write persists into. + * @property String key The dotted key being bound. + * @property MutableState backing The local state mirroring the merged value. + */ +private class WriteThroughIntSettingState( + private val settings: Settings, + private val key: String, + private val backing: MutableState, +) : MutableState { + override var value: Int + get() = backing.value + set(newValue) { + // Update the local mirror first so the read is immediate, then persist (which also emits on + // `changes`; the collector re-reading the now-identical value is a harmless no-op). + backing.value = newValue + settings.setInt(key, newValue) + } + + override fun component1(): Int = value + + override fun component2(): (Int) -> Unit = { newValue -> value = newValue } +} + +/** + * A write-through, reactive binding to one number-valued setting - the [rememberStringSetting] + * counterpart for numeric keys, with the same auto-save and external-change semantics. + * + * @param String key The dotted settings key (e.g. "viewport.zoomStepPercent"). + * @param Double default The value used when the key is absent (rarely hit; defaultSettings.json seeds most). + * @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer. + */ +@Composable +fun rememberDoubleSetting(key: String, default: Double): MutableState { + val settings = LocalSettings.current + val backing = remember(settings, key) { mutableStateOf(settings.getDouble(key) ?: default) } + // Re-read when this key is written from anywhere, so a value changed by another control or command + // (not just this binding's own setter) reflects here too. + LaunchedEffect(settings, key) { + settings.changes.collect { changedKey -> + if (changedKey == key) { + backing.value = settings.getDouble(key) ?: default + } + } + } + return remember(settings, key, backing) { WriteThroughDoubleSettingState(settings, key, backing) } +} + +/** + * The [MutableState] returned by [rememberDoubleSetting]: the numeric twin of + * [WriteThroughSettingState], persisting through [Settings.setDouble]. + * + * @property Settings settings The settings instance the write persists into. + * @property String key The dotted key being bound. + * @property MutableState backing The local state mirroring the merged value. + */ +private class WriteThroughDoubleSettingState( + private val settings: Settings, + private val key: String, + private val backing: MutableState, +) : MutableState { + override var value: Double + get() = backing.value + set(newValue) { + // Update the local mirror first so the read is immediate, then persist (which also emits on + // `changes`; the collector re-reading the now-identical value is a harmless no-op). + backing.value = newValue + settings.setDouble(key, newValue) + } + + override fun component1(): Double = value + + override fun component2(): (Double) -> Unit = { newValue -> value = newValue } +} + +/** + * A write-through, reactive binding to one boolean-valued setting - the [rememberStringSetting] + * counterpart for flag keys, with the same auto-save and external-change semantics. + * + * @param String key The dotted settings key (e.g. "viewport.rendering.supersample"). + * @param Boolean default The value used when the key is absent (rarely hit; defaultSettings.json seeds most). + * @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer. + */ +@Composable +fun rememberBooleanSetting(key: String, default: Boolean): MutableState { + val settings = LocalSettings.current + val backing = remember(settings, key) { mutableStateOf(settings.getBoolean(key) ?: default) } + // Re-read when this key is written from anywhere, so a value changed by another control or command + // (not just this binding's own setter) reflects here too. + LaunchedEffect(settings, key) { + settings.changes.collect { changedKey -> + if (changedKey == key) { + backing.value = settings.getBoolean(key) ?: default + } + } + } + return remember(settings, key, backing) { WriteThroughBooleanSettingState(settings, key, backing) } +} + +/** + * The [MutableState] returned by [rememberBooleanSetting]: the flag twin of + * [WriteThroughSettingState], persisting through [Settings.setBoolean]. + * + * @property Settings settings The settings instance the write persists into. + * @property String key The dotted key being bound. + * @property MutableState backing The local state mirroring the merged value. + */ +private class WriteThroughBooleanSettingState( + private val settings: Settings, + private val key: String, + private val backing: MutableState, +) : MutableState { + override var value: Boolean + get() = backing.value + set(newValue) { + // Update the local mirror first so the read is immediate, then persist (which also emits on + // `changes`; the collector re-reading the now-identical value is a harmless no-op). + backing.value = newValue + settings.setBoolean(key, newValue) + } + + override fun component1(): Boolean = value + + override fun component2(): (Boolean) -> Unit = { newValue -> value = newValue } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/AcceleratorText.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/AcceleratorText.kt new file mode 100644 index 0000000..1b5eece --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/AcceleratorText.kt @@ -0,0 +1,87 @@ +package org.umamo.ui.action + +/** + * Renders [chord] as a human accelerator hint for a menu row (e.g. "Ctrl+Shift+P", "⌘O"). The primary + * modifier resolves per platform via [primaryModifierLabel] (⌘ on macOS, Ctrl elsewhere); the rest is + * pure and position-based. + * + * chord をメニュー行のアクセラレータ表記に整形する。主修飾キーはプラットフォーム依存で解決する。 + * + * @param KeyChord chord The chord to format. + * @return String The display hint. + */ +fun formatAccelerator(chord: KeyChord): String = formatAccelerator(chord, primaryModifierLabel()) + +/** + * The pure core of [formatAccelerator]: assembles the modifier labels (primary, Alt, Shift) and the key + * glyph into a "+"-joined hint, taking the platform-specific [primaryLabel] as a parameter so it can be + * unit-tested deterministically (the public overload supplies the host's label). Modifiers are ordered + * primary, Alt, Shift to match the common platform convention. + * + * formatAccelerator の純粋核。主修飾ラベルを引数で受け取り、決定的にテストできるようにする。 + * + * @param KeyChord chord The chord to format. + * @param String primaryLabel The platform label for the primary modifier ("Ctrl" or "⌘"). + * @return String The display hint. + */ +internal fun formatAccelerator(chord: KeyChord, primaryLabel: String): String { + val parts = + buildList { + if (chord.primaryModifier) { + add(primaryLabel) + } + if (chord.alt) { + add("Alt") + } + if (chord.shift) { + add("Shift") + } + add(keyGlyph(chord.keyName)) + } + return parts.joinToString(separator = "+") +} + +/** + * Maps a position-based key token to its display glyph: "KeyO" to "O", "Digit0" to "0", and the few + * named keys to short symbols. An unrecognized token falls back to itself so a newly bound key still + * shows something readable rather than vanishing. + * + * 位置ベースのキートークンを表示用の字形に変換する。未知のトークンはそのまま返す。 + * + * @param String keyName The position-based key token (e.g. "KeyO"). + * @return String The display glyph. + */ +internal fun keyGlyph(keyName: String): String = + when (keyName) { + "Space" -> "Space" + "Escape" -> "Esc" + "Equals" -> "=" + "Minus" -> "−" + "PageUp" -> "Page Up" + "PageDown" -> "Page Down" + "NumpadAdd" -> "Num +" + "NumpadSubtract" -> "Num −" + "NumpadMultiply" -> "Num *" + "NumpadDivide" -> "Num /" + "NumpadDecimal" -> "Num ." + "NumpadEnter" -> "Num Enter" + else -> + when { + keyName.startsWith("Key") -> keyName.removePrefix("Key") + keyName.startsWith("Digit") -> keyName.removePrefix("Digit") + // The remaining numpad tokens are the digits: "Numpad7" reads as "Num 7". + keyName.startsWith("Numpad") -> "Num " + keyName.removePrefix("Numpad") + else -> keyName + } + } + +/** + * The platform's label for the primary accelerator modifier: "⌘" on macOS, "Ctrl" elsewhere. This is + * the one platform-dependent piece of accelerator formatting (the key glyph and modifier order are + * shared). Localizing the modifier labels is a deferred follow-up. + * + * 主修飾キーのプラットフォーム別ラベル。macOS は "⌘"、それ以外は "Ctrl"。 + * + * @return String The primary modifier label. + */ +expect fun primaryModifierLabel(): String \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/Command.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/Command.kt new file mode 100644 index 0000000..92c2b86 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/Command.kt @@ -0,0 +1,67 @@ +package org.umamo.ui.action + +import org.jetbrains.compose.resources.StringResource + +/** + * Receives a command invocation. A `fun interface` (Kotlin SAM) so call sites can pass a lambda - + * `CommandHandler { argument -> … }` - instead of an anonymous object. + * + * コマンド実行を受け取る関数型インターフェース。ラムダで渡せる。 + */ +fun interface CommandHandler { + /** + * Runs the command. + * + * @param Any? argument Optional context the caller passes (e.g. a target area id); null for nullary commands. + */ + fun run(argument: Any?) +} + +/** + * Reports whether a command currently applies - the context filter behind the command palette (an + * Edit-mode select-mode command is hidden in Object mode) and the dispatch guard in + * [CommandRegistry.invoke]. A `fun interface` so registration sites pass a lambda closing over live + * session state, evaluated fresh at each query rather than captured once. + * + * コマンドが現在のコンテキストで有効かを返す。パレットの絞り込みとディスパッチのガードに使う。 + */ +fun interface CommandAvailability { + /** + * Reports whether the command currently applies. + * + * @return Boolean True when the command may be shown and invoked. + */ + fun isAvailable(): Boolean + + companion object { + /** The default availability: always applicable (context-free commands like palette.toggle). */ + val Always: CommandAvailability = CommandAvailability { true } + } +} + +/** + * A named, invokable editor operation - the atom the action registry dispatches. Every operation + * (split an area, open a file, fit the view) is one of these, addressed by a stable dotted [id] + * ("area.split.leftRight", "file.open"). Menus, the area header, the command palette, and key + * bindings all resolve to a Command and run its [handler]; nothing hardcodes a handler, so rebinding + * a key or relabelling a menu changes one place. + * + * @property String id The stable dotted identifier used to look the command up and to bind keys to it. + * @property StringResource? title The localized menu/palette label, or null for commands never shown in UI (e.g. test-only). + * @property CommandAvailability availability Whether the command currently applies (palette filter + + * dispatch guard); defaults to always. + * @property CommandSpaces spaces The editor spaces the command belongs to (palette filter + status bar + * suggestion, never a dispatch guard); defaults to everywhere. + * @property CommandHint? hint What the status bar suggests the command under and when, or null for a + * command it never suggests. A hinted command's [availability] must depend on the document and the + * mode alone - see [CommandHint] for why. + * @property CommandHandler handler The work to perform when invoked. + */ +class Command( + val id: String, + val title: StringResource?, + val availability: CommandAvailability = CommandAvailability.Always, + val spaces: CommandSpaces = CommandSpaces.Everywhere, + val hint: CommandHint? = null, + val handler: CommandHandler, +) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandHint.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandHint.kt new file mode 100644 index 0000000..a6070af --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandHint.kt @@ -0,0 +1,25 @@ +package org.umamo.ui.action + +import org.jetbrains.compose.resources.StringResource + +/** + * What the status bar suggests a [Command] under, and when. + * + * A command is suggested when its own [Command.availability] and [suggestedWhen] both hold. + * [suggestedWhen] narrows the SUGGESTION alone: dispatch and the command palette never read it, so a + * command can run in a mode the bar does not advertise it in - Tab toggles Edit mode from either side, + * and is worth suggesting only from Object mode. + * + * The status bar recomputes its suggestions when the registered table (and so the document), the editor + * mode, the hovered space, or the keymap changes. Both predicates of a hinted command must therefore + * depend on the document and the mode alone, or the suggestion goes stale. + * + * @property StringResource label The short label the command is suggested under ("Grab", where the title + * reads "Grab Vertices"). Commands sharing one label are suggested as one entry ("1/2/3 Select Mode"). + * @property CommandAvailability suggestedWhen Whether the command is worth suggesting right now, on top + * of being available; defaults to always. + */ +class CommandHint( + val label: StringResource, + val suggestedWhen: CommandAvailability = CommandAvailability.Always, +) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandPalette.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandPalette.kt new file mode 100644 index 0000000..6415529 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandPalette.kt @@ -0,0 +1,211 @@ +package org.umamo.ui.action + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.TextField +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.search_hint +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * The searchable command overlay: a scrim over the shell with a search field and a filtered list of the + * registered [Command]s, each invokable by click or by keyboard. A discoverability surface that falls + * almost free out of the registry - the caller passes the already-filtered, user-facing commands + * (title != null) in registration order. + * + * It is keyboard-first (Blender-like): the search field autofocuses on open, typing narrows the list + * (ranked by match quality; a blank query keeps registration order), Up/Down move a highlighted + * selection, Enter invokes it, and Escape (or a scrim click) dismisses. The + * shell yields every non-Escape key to this overlay while it is open, so the field and the navigation keys + * receive input; the bound accelerator for each command is shown on the right via the active [Keymap]. + * + * 検索可能なコマンドパレット。検索欄は自動でフォーカスされ、入力で絞り込み、上下で選択、Enter で実行、Esc で閉じる。 + * + * @param List commands The commands to list (already filtered to titled, user-facing ones; registry order). + * @param Function onDismiss Called to close the palette without invoking. + * @param Function onInvoke Called with the chosen command. + */ +@Composable +fun CommandPalette(commands: List, onDismiss: () -> Unit, onInvoke: (Command) -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val keymap = LocalKeymap.current + + var query by remember { mutableStateOf("") } + // The highlighted row, driven by Up/Down and Enter. Clamped at read (filtering can shrink the list + // out from under it), and reset to the top whenever the query changes the result set (the effect below). + var selectedIndex by remember { mutableStateOf(0) } + val searchFocus = remember { FocusRequester() } + val listState = rememberLazyListState() + + // Labels need stringResource (a composable), so resolve them here; filtering is then plain Kotlin. The + // list is small (~a dozen commands) so resolving every label each recomposition is cheap. + val labeled = + commands.map { command -> + command to (command.title?.let { title -> stringResource(title) } ?: command.id) + } + val filtered = + if (query.isBlank()) { + labeled + } else { + // Ranked match over the visible label or the dotted id ("view.zoom" works directly): a label + // prefix beats a word start beats a substring beats an id-only hit - see CommandSearch. + rankCommandMatches(labeled, query, labelOf = { entry -> entry.second }, idOf = { entry -> entry.first.id }) + } + val safeIndex = selectedIndex.coerceIn(0, maxOf(0, filtered.size - 1)) + + // Reset the highlight to the top result whenever the query (and thus the filtered list) changes. + LaunchedEffect(query) { + selectedIndex = 0 + } + // Autofocus the search field on open. The palette is composed fresh each time it opens, so Unit keys + // the effect to that single open. + LaunchedEffect(Unit) { + searchFocus.requestFocus() + } + // Keep the highlighted row scrolled into view as Up/Down move it. + LaunchedEffect(safeIndex) { + if (filtered.isNotEmpty()) { + listState.scrollToItem(safeIndex) + } + } + + Box( + // Dismiss on an outside pointer tap only - a tap gesture, not a clickable. A keyboard-activatable + // clickable scrim would let Space (or Enter) typed in the search field bubble up to it and fire + // onDismiss, closing the palette mid-search; keyboard dismissal stays Escape (handled by the card's + // onPreviewKeyEvent and the shell). + modifier = + Modifier + .fillMaxSize() + .pointerInput(Unit) { detectTapGestures { onDismiss() } }, + contentAlignment = Alignment.TopCenter, + ) { + Surface( + modifier = + Modifier.padding(top = 80.dp).width(480.dp).clickable(enabled = false, onClick = {}) + // onPreviewKeyEvent on this ancestor sees keys before the focused search field, so the + // navigation keys drive the list while ordinary typing falls through to the field. + .onPreviewKeyEvent { event -> + if (event.type != KeyEventType.KeyDown) { + false + } else { + when (event.key) { + Key.DirectionDown -> { + if (filtered.isNotEmpty()) { + selectedIndex = (safeIndex + 1) % filtered.size + } + true + } + + Key.DirectionUp -> { + if (filtered.isNotEmpty()) { + selectedIndex = (safeIndex - 1 + filtered.size) % filtered.size + } + true + } + + Key.Enter, Key.NumPadEnter -> { + filtered.getOrNull(safeIndex)?.let { (command, _) -> onInvoke(command) } + true + } + // Belt-and-suspenders: the shell already consumes Escape to close the palette, but + // handle it here too so the overlay stands alone if reused. + Key.Escape -> { + onDismiss() + true + } + + else -> false + } + } + }, + color = colors.menuBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.fillMaxWidth()) { + TextField( + value = query, + onValueChange = { newQuery -> query = newQuery }, + modifier = Modifier.fillMaxWidth().focusRequester(searchFocus).padding(8.dp), + placeholder = stringResource(Res.string.search_hint), + ) + LazyColumn(state = listState, modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp)) { + itemsIndexed(filtered) { index, entry -> + val command = entry.first + val label = entry.second + val isSelected = index == safeIndex + Row( + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = 4.dp, vertical = 4.dp) + .background( + when { + isSelected -> colors.selection + else -> Color.Transparent + }, + shape = LocalUmamoShapes.current.small, + ) + .clickable { onInvoke(command) } + .padding(horizontal = 4.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = label, + style = typography.bodyMedium, + color = if (isSelected) colors.selectionText else colors.text, + modifier = Modifier.weight(1f), + ) + // The command's bound accelerator (canonical chord), dimmed; omitted when unbound. + keymap.chordFor(command.id)?.let { chord -> + Text( + text = formatAccelerator(chord), + style = typography.bodySmall, + color = if (isSelected) colors.selectionText else colors.textMuted, + ) + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandRegistry.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandRegistry.kt new file mode 100644 index 0000000..52016bb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandRegistry.kt @@ -0,0 +1,100 @@ +package org.umamo.ui.action + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * The central table of named [Command]s and the single dispatch point for invoking them. Menus, the + * area header, the command palette, and the keymap all go through here, so an operation has exactly + * one implementation regardless of how it was triggered. + * + * Insertion order is preserved (a LinkedHashMap) so the command palette can list commands in a + * stable, registration order rather than a hash-shuffled one. + */ +class CommandRegistry { + private val commandsById = LinkedHashMap() + + /** + * Counts every change to the table, as snapshot state - what a composable listing [all] reads so that + * it recomposes when the table changes. + * + * The table itself is a plain map, and the document-scoped groups re-register from effects that run + * AFTER the composition a document swap caused. Without this, a listing recomposed by that swap + * reads the outgoing document's commands - whose availability still answers for the old session - and + * nothing recomposes it again once the new ones land. + */ + var revision: Int by mutableIntStateOf(0) + private set + + /** + * Registers (or replaces) a command under its [Command.id]. + * + * @param Command command The command to register. + */ + fun register(command: Command) { + commandsById[command.id] = command + revision++ + } + + /** + * Removes a command by id, if present. + * + * @param String id The command id to remove. + */ + fun unregister(id: String) { + if (commandsById.remove(id) != null) { + revision++ + } + } + + /** + * Looks up a command by id without invoking it (e.g. to read its title for a menu). + * + * @param String id The command id. + * @return Command? The command, or null if none is registered. + */ + operator fun get(id: String): Command? = commandsById[id] + + /** + * Every registered command in registration order - the source for the command palette listing. + * + * @return List the registered commands. + */ + fun all(): List = commandsById.values.toList() + + /** + * Invokes the command bound to [id], passing [argument] to its handler. + * + * Returns whether a command was found AND currently applicable, rather than throwing, so a stray + * key chord or a menu item whose command was unregistered fails quietly instead of crashing the + * editor - and a chord bound to a command outside its context (an Edit-mode operator pressed in + * Object mode) falls through unconsumed rather than running a guaranteed no-op. + * + * @param String id The command id to invoke. + * @param Any? argument Optional context forwarded to the handler (default null). + * @return Boolean true if a command was found, applicable, and run; false otherwise. + */ + fun invoke(id: String, argument: Any? = null): Boolean { + val command = commandsById[id] ?: return false + if (!command.availability.isAvailable()) { + return false + } + command.handler.run(argument) + return true + } +} + +/** + * The active [CommandRegistry] for the composition. `static` because the registry instance is stable + * for the app's lifetime (commands are registered into it, not swapped); descendants read + * `LocalCommands.current` to dispatch. The default errors loudly so a missing provider is caught at + * the first dispatch rather than silently no-op'ing. + * + * コンポジション内で有効なコマンドレジストリ。アプリ生存期間中インスタンスは不変なので static。 + */ +val LocalCommands = + staticCompositionLocalOf { + error("LocalCommands not provided — wrap the editor in a CommandRegistry provider") + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandSearch.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandSearch.kt new file mode 100644 index 0000000..16e6b2f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandSearch.kt @@ -0,0 +1,47 @@ +package org.umamo.ui.action + +/** + * Scores how well one command matches a palette query; lower is better, null is no match. + * + * The tiers keep the intuitive result first: a query that starts the visible label ("ac" -> + * "Actual Size") outranks a label whose later word starts with it ("Zoom In" for "in"), which + * outranks a mere substring hit ("Workspace" for "ac"), which outranks a match found only in the + * dotted command id. Matching is case-insensitive. + * + * @param String label The command's resolved, user-visible label. + * @param String commandId The command's dotted id (e.g. "view.zoomIn"). + * @param String query The typed query (non-blank). + * @return Int? The match tier (0 label prefix, 1 label word start, 2 label substring, 3 id + * substring), or null when the command matches nowhere. + */ +internal fun commandMatchScore(label: String, commandId: String, query: String): Int? = + when { + label.startsWith(query, ignoreCase = true) -> 0 + label.split(' ').any { word -> word.startsWith(query, ignoreCase = true) } -> 1 + label.contains(query, ignoreCase = true) -> 2 + commandId.contains(query, ignoreCase = true) -> 3 + else -> null + } + +/** + * Filters and ranks palette entries for a query: non-matches drop, the rest sort by match tier + * (see [commandMatchScore]) with alphabetical label order breaking ties. + * + * @param List entries The candidate entries, in registry order. + * @param String query The typed query (non-blank). + * @param Function labelOf Extracts an entry's user-visible label. + * @param Function idOf Extracts an entry's dotted command id. + * @return List The matching entries, best first. + */ +internal fun rankCommandMatches( + entries: List, + query: String, + labelOf: (TEntry) -> String, + idOf: (TEntry) -> String, +): List = + entries + .mapNotNull { entry -> + commandMatchScore(labelOf(entry), idOf(entry), query)?.let { score -> entry to score } + } + .sortedWith(compareBy({ scored -> scored.second }, { scored -> labelOf(scored.first).lowercase() })) + .map { scored -> scored.first } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandSpaces.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandSpaces.kt new file mode 100644 index 0000000..24c913b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandSpaces.kt @@ -0,0 +1,96 @@ +package org.umamo.ui.action + +import org.umamo.ui.workspace.SpaceKind + +/** + * The editor spaces a [Command] belongs to - the "where" beside [CommandAvailability]'s "when". + * + * A declaration about VISIBILITY and SUGGESTION only: the command palette hides a command outside its + * spaces and the status bar suggests it only inside them. Dispatch never reads it - + * [CommandRegistry.invoke] and the keymap run a command wherever the pointer is, and its handler goes on + * deciding for itself what a press means there. + * + * The set is read off what the handler's routing actually does, never narrower: a handler that reaches + * back to a surface the pointer has left (the lone open keyform sheet, the last work surface touched) + * works from anywhere, and so it is [Everywhere]. Narrowing a scope past its handler hides a command that + * would have run. + */ +sealed interface CommandSpaces { + /** + * Reports whether a command with these spaces belongs to a surface of [kind]. + * + * @param SpaceKind? kind The space the pointer last touched, or null before it touched any. + * @return Boolean True when the command is shown and suggested there. + */ + fun appliesIn(kind: SpaceKind?): Boolean + + /** Belongs to every space, and to no space at all - the scope of a command that routes by nothing. */ + data object Everywhere : CommandSpaces { + /** + * Always applies. + * + * @param SpaceKind? kind The space the pointer last touched, or null before it touched any. + * @return Boolean Always true. + */ + override fun appliesIn(kind: SpaceKind?): Boolean = true + } + + /** + * Belongs to the listed spaces alone. + * + * @property Set kinds The spaces the command acts in; never empty, so a command that is + * allowed nowhere cannot be declared. + */ + data class Only(val kinds: Set) : CommandSpaces { + init { + require(kinds.isNotEmpty()) { "A command scoped to no space could never be shown; use Everywhere or name a space" } + } + + /** + * Applies when [kind] is one of [kinds]. A null kind matches nothing: the pointer has touched no + * surface, so the handler would resolve no area to act in either. + * + * @param SpaceKind? kind The space the pointer last touched, or null before it touched any. + * @return Boolean True when [kind] is listed. + */ + override fun appliesIn(kind: SpaceKind?): Boolean = kind != null && kind in kinds + } + + companion object { + /** The kinds behind [WorkSurfaces], held once so every set built on the work surfaces follows it. */ + private val workSurfaceKinds = setOf(SpaceKind.Viewport2D, SpaceKind.UvEditor) + + /** The 2D viewport alone: world-space operations whose overlay is the only collector. */ + val Viewport2D: CommandSpaces = Only(setOf(SpaceKind.Viewport2D)) + + /** The UV editor alone: texture-coordinate operations. */ + val UvEditor: CommandSpaces = Only(setOf(SpaceKind.UvEditor)) + + /** + * The two work surfaces, the 2D viewport and the UV editor: the modal transforms, the select + * tools, and the camera commands. A new camera-bearing or transform-hosting space joins here. + */ + val WorkSurfaces: CommandSpaces = Only(workSurfaceKinds) + + /** + * The work surfaces plus the keyform sheet: the commands that mean one thing over a work surface + * and the sheet's own version of it over a sheet (Frame All, Box Select). Derived from the work + * surfaces, so a space that joins them is covered here too. + */ + val WorkSurfacesAndSheet: CommandSpaces = Only(workSurfaceKinds + SpaceKind.KeyformSheet) + + /** + * The surfaces showing keyable properties, the keyform sheet's lanes and the Properties rows: the + * insert / delete pair that writes to whichever keyable the pointer is over. + */ + val KeyableSurfaces: CommandSpaces = Only(setOf(SpaceKind.KeyformSheet, SpaceKind.Properties)) + + /** + * Builds the scope of a command whose spaces match none of the named sets. + * + * @param SpaceKind kinds The spaces the command acts in; at least one. + * @return CommandSpaces The scope over exactly those spaces. + */ + fun of(vararg kinds: SpaceKind): CommandSpaces = Only(kinds.toSet()) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandVisibility.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandVisibility.kt new file mode 100644 index 0000000..cb1fd46 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/CommandVisibility.kt @@ -0,0 +1,30 @@ +package org.umamo.ui.action + +import org.umamo.ui.workspace.SpaceKind + +/** + * Reports whether this command is offered over a surface of [kind]: it belongs to that space and + * currently applies. The one rule the command palette and the status bar share, so the two cannot + * come to disagree about what "offered here" means. + * + * @param SpaceKind? kind The space the pointer last touched, or null before it touched any. + * @return Boolean True when the command is listed and suggested there. + */ +internal fun Command.isOfferedIn(kind: SpaceKind?): Boolean = spaces.appliesIn(kind) && availability.isAvailable() + +/** + * The commands the palette offers over a surface of [hoveredKind]: titled, currently available, and + * belonging to that space. + * + * A null title marks a command as not a palette entry at all (internal toggles like palette.toggle and + * area.dragCancel, and the argument-only document commands); an unavailable command is hidden rather + * than dimmed, and so is one outside its spaces - the palette lists what would do something from where + * the pointer is, in the current mode. The hidden commands stay discoverable in the keybindings editor, + * which lists the whole table. + * + * @param List commands The registered commands, in registration order. + * @param SpaceKind? hoveredKind The space the pointer last touched, or null before it touched any. + * @return List The commands to list, in the order given. + */ +internal fun paletteCommands(commands: List, hoveredKind: SpaceKind?): List = + commands.filter { command -> command.title != null && command.isOfferedIn(hoveredKind) } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/KeyName.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/KeyName.kt new file mode 100644 index 0000000..891f238 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/KeyName.kt @@ -0,0 +1,124 @@ +package org.umamo.ui.action + +import androidx.compose.ui.input.key.Key + +/** + * Normalizes a key event's [Key] before name lookup. Desktop Compose builds its located numpad + * constants from different AWT codes than AWT actually delivers (Key.NumPadDot is Key(VK_PERIOD, + * NUMPAD) while the physical key arrives as VK_DECIMAL), so without normalization the numpad decimal + * - and with it the NumpadDecimal binding - can never match. The desktop actual remaps those codes + * (and defensively re-locates the numpad-only ones); Android keys carry no location and match their + * constants directly, so its actual is the identity. + * + * @param Key key The key from a key event. + * @return Key The key to match the named constants against. + */ +internal expect fun normalizeKeyPosition(key: Key): Key + +/** + * Maps a Compose [Key] to the position-based token a [KeyChord] stores ("KeyP", "Digit0", "F5", "ArrowUp", + * …), or null for a key the keymap does not bind (modifiers, media keys, anything unlisted). This is the + * single source of truth shared by the live keyboard dispatch (handleShellKey) and the rebinding editor's + * chord capture, so a captured chord and a dispatched chord always agree on a key's name - the tokens here + * are exactly the ones a preset spec or a stored override uses. + * + * Compose の Key を KeyChord が保持する位置ベースのトークンに変換する。入力ディスパッチと再割り当て UI で共有し、 + * 取り込んだコードと発火するコードのキー名が必ず一致するようにする。 + * + * @param Key key The Compose key from a key event. + * @return String? The position-based token, or null if the key is not bindable. + */ +fun keyName(key: Key): String? = + when (normalizeKeyPosition(key)) { + Key.A -> "KeyA" + Key.B -> "KeyB" + Key.C -> "KeyC" + Key.D -> "KeyD" + Key.E -> "KeyE" + Key.F -> "KeyF" + Key.G -> "KeyG" + Key.H -> "KeyH" + Key.I -> "KeyI" + Key.J -> "KeyJ" + Key.K -> "KeyK" + Key.L -> "KeyL" + Key.M -> "KeyM" + Key.N -> "KeyN" + Key.O -> "KeyO" + Key.P -> "KeyP" + Key.Q -> "KeyQ" + Key.R -> "KeyR" + Key.S -> "KeyS" + Key.T -> "KeyT" + Key.U -> "KeyU" + Key.V -> "KeyV" + Key.W -> "KeyW" + Key.X -> "KeyX" + Key.Y -> "KeyY" + Key.Z -> "KeyZ" + Key.Zero -> "Digit0" + Key.One -> "Digit1" + Key.Two -> "Digit2" + Key.Three -> "Digit3" + Key.Four -> "Digit4" + Key.Five -> "Digit5" + Key.Six -> "Digit6" + Key.Seven -> "Digit7" + Key.Eight -> "Digit8" + Key.Nine -> "Digit9" + Key.F1 -> "F1" + Key.F2 -> "F2" + Key.F3 -> "F3" + Key.F4 -> "F4" + Key.F5 -> "F5" + Key.F6 -> "F6" + Key.F7 -> "F7" + Key.F8 -> "F8" + Key.F9 -> "F9" + Key.F10 -> "F10" + Key.F11 -> "F11" + Key.F12 -> "F12" + Key.Spacebar -> "Space" + Key.Enter -> "Enter" + Key.Tab -> "Tab" + Key.Escape -> "Escape" + Key.Backspace -> "Backspace" + Key.Delete -> "Delete" + Key.Insert -> "Insert" + Key.DirectionUp -> "ArrowUp" + Key.DirectionDown -> "ArrowDown" + Key.DirectionLeft -> "ArrowLeft" + Key.DirectionRight -> "ArrowRight" + Key.MoveHome -> "Home" + Key.MoveEnd -> "End" + Key.PageUp -> "PageUp" + Key.PageDown -> "PageDown" + Key.Comma -> "Comma" + Key.Period -> "Period" + Key.Minus -> "Minus" + Key.Equals -> "Equals" + Key.Semicolon -> "Semicolon" + Key.Apostrophe -> "Quote" + Key.LeftBracket -> "BracketLeft" + Key.RightBracket -> "BracketRight" + Key.Backslash -> "Backslash" + Key.Slash -> "Slash" + Key.Grave -> "Backquote" + Key.NumPadAdd -> "NumpadAdd" + Key.NumPadSubtract -> "NumpadSubtract" + Key.NumPadMultiply -> "NumpadMultiply" + Key.NumPadDivide -> "NumpadDivide" + Key.NumPadDot -> "NumpadDecimal" + Key.NumPadEnter -> "NumpadEnter" + Key.NumPad0 -> "Numpad0" + Key.NumPad1 -> "Numpad1" + Key.NumPad2 -> "Numpad2" + Key.NumPad3 -> "Numpad3" + Key.NumPad4 -> "Numpad4" + Key.NumPad5 -> "Numpad5" + Key.NumPad6 -> "Numpad6" + Key.NumPad7 -> "Numpad7" + Key.NumPad8 -> "Numpad8" + Key.NumPad9 -> "Numpad9" + else -> null + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/Keymap.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/Keymap.kt new file mode 100644 index 0000000..c14170f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/Keymap.kt @@ -0,0 +1,377 @@ +package org.umamo.ui.action + +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * One key combination, stored logically rather than as a literal character. [primaryModifier] is the + * platform's main accelerator (Cmd on macOS, Ctrl elsewhere) - the intent is stored, not "Ctrl", so a + * binding resolves correctly per OS. [keyName] names the physical key by position + * ("KeyP", "KeyK"), not the produced character, so a chord survives non-QWERTY layouts. + * + * @property String keyName The position-based key token (e.g. "KeyP"), layout-independent. + * @property Boolean primaryModifier Whether the platform primary accelerator (Cmd/Ctrl) is held. + * @property Boolean shift Whether Shift is held. + * @property Boolean alt Whether Alt/Option is held. + */ +data class KeyChord( + val keyName: String, + val primaryModifier: Boolean = false, + val shift: Boolean = false, + val alt: Boolean = false, +) + +/** + * Parses a human-authored chord spec like "primary+shift+KeyP" into a [KeyChord]. Tokens are split on + * '+'; the final token is the key, the rest are modifiers ("primary", "shift", "alt"/"option", case + * insensitive). This is the on-disk keymap form (settings input.keybinding) and the form preset files + * use, so it must be tolerant of case and whitespace but reject a malformed spec (empty key, unknown + * modifier) rather than silently mis-binding. + * + * @param String spec The chord spec, modifiers and key joined by '+'. + * @return KeyChord? The parsed chord, or null if the spec is malformed. + */ +fun parseKeyChord(spec: String): KeyChord? { + val tokens = spec.split('+').map { token -> token.trim() }.filter { token -> token.isNotEmpty() } + if (tokens.isEmpty()) { + return null + } + val keyName = tokens.last() + if (keyName.isEmpty()) { + return null + } + var primaryModifier = false + var shift = false + var alt = false + for (modifierIndex in 0 until tokens.size - 1) { + when (tokens[modifierIndex].lowercase()) { + "primary", "cmd", "ctrl", "control" -> primaryModifier = true + "shift" -> shift = true + "alt", "option", "opt" -> alt = true + else -> return null + } + } + return KeyChord(keyName, primaryModifier, shift, alt) +} + +/** + * Serializes a [KeyChord] back to the spec string [parseKeyChord] reads ("primary+shift+KeyP") - the form + * stored in settings input.keybinding.overrides. Modifiers are emitted in a fixed order (primary, shift, + * alt) so a given chord always round-trips to the same string and the stored override key stays stable; + * parseKeyChord itself accepts any order, so this is the inverse of parsing for any chord it produced. + * + * @param KeyChord chord The chord to serialize. + * @return String The spec string. + */ +fun chordToSpec(chord: KeyChord): String = + buildList { + if (chord.primaryModifier) { + add("primary") + } + if (chord.shift) { + add("shift") + } + if (chord.alt) { + add("alt") + } + add(chord.keyName) + }.joinToString(separator = "+") + +/** + * A resolved set of key-chord → command-id bindings, plus the lookup the input layer uses. Built from + * a preset spec map; conflicts (two chords on the same command, or a re-bound chord) are resolved + * last-write-wins at build time. The keymap holds only ids - it never references [Command] objects - + * so it stays decoupled from registration order and from whether a command currently exists. + */ +class Keymap(private val commandIdByChord: Map) { + /** + * The command id bound to [chord], or null if the chord is unbound. + * + * @param KeyChord chord The pressed chord. + * @return String? The bound command id, or null. + */ + fun commandFor(chord: KeyChord): String? = commandIdByChord[chord] + + /** + * The first chord bound to [commandId], or null if none is - the reverse of [commandFor], used to + * render a menu row's accelerator hint. When several chords map to one command (palette.toggle has + * both primary+KeyP and Space) the first in insertion order wins, so a menu shows the canonical + * accelerator (primary+KeyP) rather than whichever the map happens to yield first. + * + * @param String commandId The command id to find an accelerator for. + * @return KeyChord? The first bound chord, or null. + */ + fun chordFor(commandId: String): KeyChord? { + // LinkedHashMap iterates in insertion order, so the first match is the canonical binding. + for ((chord, boundCommandId) in commandIdByChord) { + if (boundCommandId == commandId) { + return chord + } + } + return null + } + + /** + * The number of bindings - handy for tests and a future conflict/coverage report. + * + * @return Int the binding count. + */ + fun size(): Int = commandIdByChord.size + + companion object { + /** + * Builds a [Keymap] from a preset's chord-spec → command-id map, parsing each spec via + * [parseKeyChord]. A spec that fails to parse is dropped (a malformed preset entry must not + * shadow a valid one); callers that need strict validation can compare [size] to the input. + * + * @param Map specs The preset bindings (chord spec → command id). + * @return Keymap the resolved keymap. + */ + fun fromSpecs(specs: Map): Keymap { + val resolved = LinkedHashMap() + for ((spec, commandId) in specs) { + val chord = parseKeyChord(spec) ?: continue + resolved[chord] = commandId + } + return Keymap(resolved) + } + } +} + +/** + * The ids of the built-in keymap presets, in display order. [keymapPresetSpecs] resolves each to its + * bindings; the persisted choice lives in settings input.keybinding.preset and user overrides layer on top. + */ +val KEYMAP_PRESET_IDS: List = listOf("default", "cubism", "blender") + +/** + * The "default" preset: a small, neutral starter set. Bindings are by key position with the logical + * primary modifier, so they hold across OSes and layouts. + */ +private val DEFAULT_KEYMAP_SPECS: Map = + presetSpecs( + "primary+KeyP" to "palette.toggle", + "Space" to "palette.toggle", + "Escape" to "area.dragCancel", + "Tab" to "mode.toggleEdit", + "primary+PageUp" to "workspace.prev", + "primary+PageDown" to "workspace.next", + // The document's own chords: Open, Save, and Save As on the keys every application uses for them. + // Import CMO3 has no chord - an import is not an open - and the File menu and the palette reach it. + "primary+KeyN" to "file.new", + "primary+KeyO" to "file.open", + "primary+KeyS" to "file.save", + "primary+shift+KeyS" to "file.saveAs", + "primary+shift+KeyO" to "file.importArtwork", + "primary+KeyZ" to "edit.undo", + "primary+shift+KeyZ" to "edit.redo", + "F9" to "edit.adjustLastOperation", + "KeyP" to "uv.pinPlacement", + "alt+KeyP" to "uv.unpinPlacement", + "KeyH" to "object.toggleVisibility", + "KeyG" to "mesh.grab", + "KeyS" to "mesh.scale", + "KeyR" to "mesh.rotate", + "Digit1" to "mesh.selectMode.vertex", + "Digit2" to "mesh.selectMode.edge", + "Digit3" to "mesh.selectMode.face", + "KeyA" to "select.all", + "primary+KeyI" to "select.invert", + "KeyI" to "keyform.insert", + "alt+KeyI" to "keyform.delete", + "Delete" to "keyform.deleteSelectedKeys", + "ArrowLeft" to "keyform.nudgeKeyLeft", + "ArrowRight" to "keyform.nudgeKeyRight", + // Context-aware, Blender's Home semantics: frames the hovered editor (keyform sheet → the keys, + // anything else → the viewport). + "Home" to "frame.all", + "KeyB" to "mesh.boxSelect", + "KeyC" to "mesh.circleSelect", + "shift+KeyB" to "view.zoomRegion", + "NumpadAdd" to "mesh.circleSelect.grow", + "NumpadSubtract" to "mesh.circleSelect.shrink", + "Period" to "transform.pivotPie", + "shift+KeyS" to "snap.pie", + "KeyL" to "mesh.selectLinkedAtCursor", + "primary+KeyL" to "mesh.selectLinked", + "alt+KeyQ" to "edit.switchObjectUnderCursor", + "NumpadDecimal" to "view.frameSelected", + "shift+KeyD" to "mesh.duplicate", + "KeyM" to "mesh.merge", + "KeyV" to "mesh.rip", + "KeyJ" to "mesh.connect", + "KeyK" to "mesh.insertVertex", + "shift+KeyV" to "mesh.vertexSlide", + "KeyO" to "mesh.proportional.toggle", + "alt+KeyO" to "mesh.proportional.connectedToggle", + "KeyT" to "view.toggleToolbar", + "KeyN" to "view.toggleSidebar", + "primary+Comma" to "edit.preferences", + "primary+Digit0" to "view.fit", + "primary+Digit1" to "view.zoomActualSize", + "primary+Equals" to "view.zoomIn", + "primary+shift+Equals" to "view.zoomInCoarse", + "primary+Minus" to "view.zoomOut", + "primary+shift+Minus" to "view.zoomOutCoarse", + ) + +/** + * The "Cubism-like" preset for migrants from the official Cubism Editor. A starting point keyed to Cubism + * muscle memory (the command palette on the primary modifier, no bare Space - Cubism reserves Space for + * canvas panning); fully rebindable in the keybindings editor. + */ +private val CUBISM_KEYMAP_SPECS: Map = + presetSpecs( + "primary+KeyP" to "palette.toggle", + "Escape" to "area.dragCancel", + "primary+PageUp" to "workspace.prev", + "primary+PageDown" to "workspace.next", + // The document's own chords: Open, Save, and Save As on the keys every application uses for them. + // Import CMO3 has no chord - an import is not an open - and the File menu and the palette reach it. + "primary+KeyN" to "file.new", + "primary+KeyO" to "file.open", + "primary+KeyS" to "file.save", + "primary+shift+KeyS" to "file.saveAs", + "primary+shift+KeyO" to "file.importArtwork", + // Undo / redo: Ctrl+Z plus both redo conventions Cubism migrants carry (Ctrl+Shift+Z and Ctrl+Y). + "primary+KeyZ" to "edit.undo", + "primary+shift+KeyZ" to "edit.redo", + "F9" to "edit.adjustLastOperation", + "KeyP" to "uv.pinPlacement", + "alt+KeyP" to "uv.unpinPlacement", + "primary+KeyY" to "edit.redo", + "primary+Comma" to "edit.preferences", + "primary+Digit0" to "view.fit", + // Frame Selected joins the Ctrl+0 fit family (Cubism has no numpad-framing convention). + "primary+shift+Digit0" to "view.frameSelected", + "primary+Digit1" to "view.zoomActualSize", + "primary+Equals" to "view.zoomIn", + "primary+shift+Equals" to "view.zoomInCoarse", + "primary+Minus" to "view.zoomOut", + "primary+shift+Minus" to "view.zoomOutCoarse", + ) + +/** + * The "Blender-like" preset for migrants from Blender (whose editing model Umamo borrows). A starting + * point keyed to Blender muscle memory (operator search on F3, Frame All on Home - context-aware per + * hovered editor, exactly as in Blender); fully rebindable in the keybindings editor. + */ +private val BLENDER_KEYMAP_SPECS: Map = + presetSpecs( + "F3" to "palette.toggle", + "Escape" to "area.dragCancel", + "Tab" to "mode.toggleEdit", + "primary+PageUp" to "workspace.prev", + "primary+PageDown" to "workspace.next", + // The document's own chords: Open, Save, and Save As on the keys every application uses for them. + // Import CMO3 has no chord - an import is not an open - and the File menu and the palette reach it. + "primary+KeyN" to "file.new", + "primary+KeyO" to "file.open", + "primary+KeyS" to "file.save", + "primary+shift+KeyS" to "file.saveAs", + "primary+shift+KeyO" to "file.importArtwork", + "primary+KeyZ" to "edit.undo", + "primary+shift+KeyZ" to "edit.redo", + "F9" to "edit.adjustLastOperation", + "KeyP" to "uv.pinPlacement", + "alt+KeyP" to "uv.unpinPlacement", + "KeyH" to "object.toggleVisibility", + "KeyG" to "mesh.grab", + "KeyS" to "mesh.scale", + "KeyR" to "mesh.rotate", + "Digit1" to "mesh.selectMode.vertex", + "Digit2" to "mesh.selectMode.edge", + "Digit3" to "mesh.selectMode.face", + "KeyA" to "select.all", + "primary+KeyI" to "select.invert", + "KeyI" to "keyform.insert", + "alt+KeyI" to "keyform.delete", + "Delete" to "keyform.deleteSelectedKeys", + "ArrowLeft" to "keyform.nudgeKeyLeft", + "ArrowRight" to "keyform.nudgeKeyRight", + "KeyB" to "mesh.boxSelect", + "KeyC" to "mesh.circleSelect", + "shift+KeyB" to "view.zoomRegion", + "NumpadAdd" to "mesh.circleSelect.grow", + "NumpadSubtract" to "mesh.circleSelect.shrink", + "Period" to "transform.pivotPie", + "shift+KeyS" to "snap.pie", + "KeyL" to "mesh.selectLinkedAtCursor", + "primary+KeyL" to "mesh.selectLinked", + "alt+KeyQ" to "edit.switchObjectUnderCursor", + "NumpadDecimal" to "view.frameSelected", + "shift+KeyD" to "mesh.duplicate", + "KeyM" to "mesh.merge", + "KeyV" to "mesh.rip", + "KeyJ" to "mesh.connect", + "KeyK" to "mesh.insertVertex", + "shift+KeyV" to "mesh.vertexSlide", + "KeyO" to "mesh.proportional.toggle", + "alt+KeyO" to "mesh.proportional.connectedToggle", + "KeyT" to "view.toggleToolbar", + "KeyN" to "view.toggleSidebar", + "primary+Comma" to "edit.preferences", + // Blender's Home is Frame All in WHICHEVER editor the pointer is over, so a single context-aware + // binding covers both cases; two separate Home entries would collide silently under mapOf's + // last-wins semantics. + "Home" to "frame.all", + "primary+Digit1" to "view.zoomActualSize", + "Equals" to "view.zoomIn", + "shift+Equals" to "view.zoomInCoarse", + "Minus" to "view.zoomOut", + "shift+Minus" to "view.zoomOutCoarse", + ) + +/** + * Builds a preset's chord-spec table, refusing duplicate chords. + * + * mapOf would keep only the LAST of two same-chord pairs, silently dropping the other - invisible even to + * the keybindings editor's conflict detection, which only ever sees the already-collapsed map. Failing at + * build time turns a duplicate chord into a test failure instead of a silent loss. + * + * @param Pair bindings The chord-spec to command-id pairs, in presentation order. + * @return Map The bindings as a map. + */ +private fun presetSpecs(vararg bindings: Pair): Map { + val byChord = LinkedHashMap(bindings.size) + for ((chord, commandId) in bindings) { + val previous = byChord.put(chord, commandId) + require(previous == null) { "duplicate chord $chord: bound to both $previous and $commandId" } + } + return byChord +} + +/** + * The chord-spec → command-id bindings for the built-in preset [presetId], falling back to the default + * preset's bindings for an unknown id so a stale or hand-edited settings value can never leave the editor + * with no keymap at all. + * + * @param String presetId The preset id (see [KEYMAP_PRESET_IDS]). + * @return Map The preset's chord-spec → command-id bindings. + */ +fun keymapPresetSpecs(presetId: String): Map = + when (presetId) { + "cubism" -> CUBISM_KEYMAP_SPECS + "blender" -> BLENDER_KEYMAP_SPECS + else -> DEFAULT_KEYMAP_SPECS + } + +/** + * The built-in "default" keymap preset as a resolved [Keymap]. Used directly by tests, and as + * [org.umamo.ui.workspace.EditorShell]'s default parameter when no settings-backed keymap + * ([org.umamo.ui.action.loadKeymap]) is supplied by the caller. + * + * @return Keymap the default preset. + */ +fun defaultKeymap(): Keymap = Keymap.fromSpecs(DEFAULT_KEYMAP_SPECS) + +/** + * The active [Keymap] for the composition. `static` because the keymap instance only changes when the + * settings-resolved preset/overrides change (see [org.umamo.ui.action.loadKeymap]), so a menu rendered + * deep in the tree can resolve a command's accelerator (via [Keymap.chordFor]) without prop-drilling + * the keymap through every intervening composable. The default errors loudly so a missing provider is + * caught at first use rather than silently showing no accelerators. + */ +val LocalKeymap = + staticCompositionLocalOf { + error("LocalKeymap not provided — wrap the editor in an EditorShell") + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/action/KeymapPersistence.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/KeymapPersistence.kt new file mode 100644 index 0000000..f8debc2 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/action/KeymapPersistence.kt @@ -0,0 +1,197 @@ +package org.umamo.ui.action + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.produceState +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonPrimitive +import org.umamo.settings.Settings + +/** The settings key holding the selected built-in preset id (see [KEYMAP_PRESET_IDS]). */ +const val KEYMAP_PRESET_KEY: String = "input.keybinding.preset" + +/** + * The settings key holding the user's per-chord overrides: a JSON object of chord-spec → command-id that + * layers over the selected preset. An empty-string value is an explicit "unbind" marker (it masks a chord + * the preset binds); a deleted entry falls back to the preset. This mirrors the settings engine's own + * defaults-then-overrides shape, one level down at the keymap. + */ +const val KEYMAP_OVERRIDES_KEY: String = "input.keybinding.overrides" + +/** + * Reads the user's chord overrides as a plain chord-spec → command-id map (an empty value means the chord + * is explicitly unbound). Never throws: a malformed or absent overrides object yields an empty map, so a + * corrupt settings value falls back to the bare preset rather than breaking input. + * + * ユーザーのコード上書きを「指定文字列→コマンド id」のマップとして読む(空値は明示的な解除)。例外は投げない。 + * + * @param Settings settings The settings store to read from. + * @return Map The override map (chord spec → command id; "" = unbound). + */ +internal fun readKeymapOverrides(settings: Settings): Map { + val element = settings.get(KEYMAP_OVERRIDES_KEY) as? JsonObject ?: return emptyMap() + val overrides = LinkedHashMap() + for ((spec, value) in element) { + val commandId = runCatching { value.jsonPrimitive.contentOrNull }.getOrNull() ?: "" + overrides[spec] = commandId + } + return overrides +} + +/** + * Writes the chord overrides back to settings as a JSON object (chord-spec → command-id), replacing the + * stored value wholesale. Persists via the Settings user layer and emits the [KEYMAP_OVERRIDES_KEY] change + * so the reactive keymap resolver rebuilds. + * + * コード上書きを JSON オブジェクトとして保存する(全置換)。 + * + * @param Settings settings The settings store to write to. + * @param Map overrides The override map to persist. + */ +internal fun writeKeymapOverrides(settings: Settings, overrides: Map) { + settings.set(KEYMAP_OVERRIDES_KEY, JsonObject(overrides.mapValues { entry -> JsonPrimitive(entry.value) })) +} + +/** + * Resolves the active [Keymap] from settings: the selected preset's bindings ([keymapPresetSpecs]) with the + * user's overrides layered on top (an empty-string override unbinds the chord). This is the settings-backed + * replacement for the bare [defaultKeymap]; the shell resolves it reactively and re-resolves on any + * input.keybinding change. + * + * 設定から有効なキーマップを解決する(プリセット+ユーザー上書き、空値は解除)。 + * + * @param Settings settings The settings store to resolve from. + * @return Keymap The resolved keymap. + */ +fun loadKeymap(settings: Settings): Keymap { + val presetId = settings.getString(KEYMAP_PRESET_KEY) ?: "default" + val resolved = LinkedHashMap() + for ((spec, commandId) in keymapPresetSpecs(presetId)) { + val chord = parseKeyChord(spec) ?: continue + resolved[chord] = commandId + } + for ((spec, commandId) in readKeymapOverrides(settings)) { + val chord = parseKeyChord(spec) ?: continue + if (commandId.isEmpty()) { + resolved.remove(chord) // explicit unbind: mask a chord the preset binds + } else { + resolved[chord] = commandId + } + } + return Keymap(resolved) +} + +/** The prefix every keymap setting sits under; a change to any key below it re-resolves the live keymap. */ +private const val KEYMAP_SETTINGS_PREFIX: String = "input.keybinding" + +/** + * The active [Keymap] as live state: resolved from the selected preset plus the user's overrides, and + * re-resolved whenever any input.keybinding setting changes, so a preset switch or a rebind in the + * settings window reaches the menu's accelerator hints, the palette, and live dispatch at once. + * + * @param Settings settings The settings store to resolve from and follow. + * @return State The live keymap. + */ +@Composable +fun rememberLiveKeymap(settings: Settings): State = + produceState(initialValue = loadKeymap(settings), settings) { + settings.changes.collect { changedKey -> + if (changedKey.startsWith(KEYMAP_SETTINGS_PREFIX)) { + value = loadKeymap(settings) + } + } + } + +/** + * Selects the built-in preset [presetId] (persisted; user overrides still layer on top). An unknown id is + * stored as-is and resolves to the default preset via [keymapPresetSpecs]'s fallback. + * + * @param Settings settings The settings store to write to. + * @param String presetId The preset id to select. + */ +fun setKeymapPreset(settings: Settings, presetId: String) { + settings.setString(KEYMAP_PRESET_KEY, presetId) +} + +/** + * Whether [chord] is bound by the currently selected preset's base bindings (before overrides). Used when + * releasing a chord: a preset binding must be masked with an unbind marker, while a pure override is simply + * dropped. + * + * @param Settings settings The settings store (for the selected preset). + * @param KeyChord chord The chord to test. + * @return Boolean true if the preset base binds this chord. + */ +private fun isPresetChord(settings: Settings, chord: KeyChord): Boolean { + val presetId = settings.getString(KEYMAP_PRESET_KEY) ?: "default" + return keymapPresetSpecs(presetId).keys.any { spec -> parseKeyChord(spec) == chord } +} + +/** + * Releases [chord] in [overrides] (mutated in place): masks it with an unbind marker if the preset binds it, + * otherwise removes the override entry. Either way the chord ends up unbound after resolution. + * + * @param Settings settings The settings store (for the preset check). + * @param MutableMap overrides The override map being edited. + * @param KeyChord chord The chord to release. + */ +private fun releaseChord(settings: Settings, overrides: MutableMap, chord: KeyChord) { + val spec = chordToSpec(chord) + if (isPresetChord(settings, chord)) { + overrides[spec] = "" + } else { + overrides.remove(spec) + } +} + +/** + * Rebinds [commandId] to [newChord], persisting the change. Releases the command's existing canonical chord + * first so the command moves rather than gaining a second binding, then binds [newChord] to it - which also + * resolves any conflict, since the new entry wins over whatever previously held that chord (the caller is + * expected to confirm a conflict with the user first; see the keybindings editor). + * + * commandId を newChord に再割り当てして保存する。既存の正規コードを解放してから新コードを束縛する。 + * + * @param Settings settings The settings store to write to. + * @param String commandId The command being rebound. + * @param KeyChord newChord The chord to bind it to. + */ +fun rebindCommand(settings: Settings, commandId: String, newChord: KeyChord) { + val overrides = readKeymapOverrides(settings).toMutableMap() + val previous = loadKeymap(settings).chordFor(commandId) + if (previous != null && previous != newChord) { + releaseChord(settings, overrides, previous) + } + overrides[chordToSpec(newChord)] = commandId + writeKeymapOverrides(settings, overrides) +} + +/** + * Unbinds [commandId]'s canonical chord, persisting the change (a no-op if it has no binding). A preset + * binding is masked with an unbind marker; a pure override is dropped. + * + * commandId の正規コードを解除して保存する(束縛が無ければ何もしない)。 + * + * @param Settings settings The settings store to write to. + * @param String commandId The command to unbind. + */ +fun unbindCommand(settings: Settings, commandId: String) { + val chord = loadKeymap(settings).chordFor(commandId) ?: return + val overrides = readKeymapOverrides(settings).toMutableMap() + releaseChord(settings, overrides, chord) + writeKeymapOverrides(settings, overrides) +} + +/** + * Clears all user overrides, returning the keymap to the selected preset's bindings (the preset choice is + * left unchanged). The "reset shortcuts" action. + * + * すべてのユーザー上書きを消去し、選択中のプリセットに戻す(プリセットの選択はそのまま)。 + * + * @param Settings settings The settings store to write to. + */ +fun resetKeymapOverrides(settings: Settings) { + writeKeymapOverrides(settings, emptyMap()) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/app/ExitGuard.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/app/ExitGuard.kt new file mode 100644 index 0000000..80a7899 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/app/ExitGuard.kt @@ -0,0 +1,58 @@ +package org.umamo.ui.app + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember + +/** + * The host's route into the shell's quit guard. + * + * The host owns the ways out that the shell never sees: the window's close button, the OS's own quit, and + * Android's back gesture. Each hands its exit to [request], and the shell, once composed, installs the + * guard that decides whether the exit runs at once or waits on the unsaved-changes prompt. Before the + * shell installs anything, and after it is gone, an exit runs directly, because there is no document + * whose edits could be lost. + */ +class ExitGuard { + private var installedGuard: ((() -> Unit) -> Unit)? = null + + /** + * Asks to exit: the installed guard receives the exit and runs it when the rigger agrees, or the exit + * runs at once when no guard is installed. + * + * @param Function exit Closes the application. + */ + fun request(exit: () -> Unit) { + val guard = installedGuard + if (guard == null) { + exit() + } else { + guard(exit) + } + } + + /** + * Installs the guard every later request passes through. + * + * The returned cleanup removes this guard only while it is still the installed one, so a replacement + * installed before the previous cleanup ran is left in place. + * + * @param Function guard Receives each requested exit and decides whether and when it runs. + * @return Function The cleanup that uninstalls this guard. + */ + fun install(guard: (() -> Unit) -> Unit): () -> Unit { + installedGuard = guard + return { + if (installedGuard === guard) { + installedGuard = null + } + } + } +} + +/** + * Remembers one [ExitGuard] for the host's composition, shared by the host's exits and the shell it mounts. + * + * @return ExitGuard The guard. + */ +@Composable +fun rememberExitGuard(): ExitGuard = remember { ExitGuard() } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/document/DocumentOpenFailure.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/document/DocumentOpenFailure.kt new file mode 100644 index 0000000..a79cd34 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/document/DocumentOpenFailure.kt @@ -0,0 +1,44 @@ +package org.umamo.ui.document + +/** + * Why a file failed to open in the editor. A stable reason the shell maps to a localized message - + * the document layer never carries display text. + */ +enum class DocumentOpenError { + /** The file could not be read at all (missing, unreadable, permission revoked). */ + ReadFailed, + + /** The contents match no format Umamo recognizes. */ + Unrecognized, + + /** A recognized format the editor shell cannot open as a document (a JSON sidecar on its own). */ + NotOpenable, + + /** A recognized format whose contents failed to parse or import. */ + ParseFailed, + + /** A `.moc3` whose required model3.json manifest was not found next to it (or failed to parse). */ + MissingManifest, + + /** A `.moc3` whose model3.json references a texture that is missing or unreadable. */ + MissingTexture, + + /** An artwork file with no raster layer that has any pixel over the alpha threshold - nothing to rig. */ + NoArtLayers, + + /** A `.uma` whose container is newer than this version reads - made by a newer Umamo. */ + NewerFormat, +} + +/** + * The payload of the document.openFailed command: what went wrong and which file, so the shell can + * alert the user instead of failing silently to the log. Lives in commonMain (unlike the JVM-bound + * document loader) so the shell's command handler can receive it on every platform. + * + * @property DocumentOpenError error The failure reason. + * @property String displayName The file's display name, the alert message's one format argument. + */ +class DocumentOpenFailure( + val error: DocumentOpenError, + val displayName: String, +) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/document/Files.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/document/Files.kt new file mode 100644 index 0000000..16dad78 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/document/Files.kt @@ -0,0 +1,47 @@ +package org.umamo.ui.document + +/** + * The display name for a stored file path (titles, the Open Recent menu). A pure string helper — it + * never touches the filesystem — so it degrades gracefully for Android SAF `content://` URIs, whose + * last segment stands in until real SAF display-name resolution lands. + * + * @param String path The stored path or URI string. + * @return String The trailing segment, with both separator conventions handled. + */ +fun fileDisplayName(path: String): String = path.substringAfterLast('/').substringAfterLast('\\') + +/** + * Whether [path] is a path the file system can probe, read, and watch, as opposed to a platform uri. + * Android's SAF hands back `content://` handles with no path behind them, so every file-system + * operation over a stored path asks this first and treats a uri as unknowable rather than missing. + * + * @param String path The stored path or uri string. + * @return Boolean True for a file-system path, false for a uri. + */ +fun isFileSystemPath(path: String): Boolean = !path.contains("://") + +/** + * The base name to seed a Save As or an export dialog with: [displayName] minus whatever file extension it + * carries. + * + * Any extension, not only the formats a rig is saved in. A document can start from an artwork file (a rig + * built by importing `hero.psd` into a new document is still named after it), and its first save should + * suggest `hero`, never `hero.psd.uma`; an export of it `hero.png`, never `hero.psd.png`. Only a trailing + * extension of a few letters is stripped, so a name with a dot in it (`v1.2 sketch`) is left alone. FileKit + * re-appends the destination's extension itself. + * + * @param String displayName The document's file name. + * @return String The name without its extension. + */ +fun saveSuggestedName(displayName: String): String { + val dot = displayName.lastIndexOf('.') + val extension = if (dot > 0) displayName.substring(dot + 1) else "" + return if (extension.length in 1..MAXIMUM_EXTENSION_LENGTH && extension.all { character -> character.isLetterOrDigit() }) { + displayName.substring(0, dot) + } else { + displayName + } +} + +/** The longest extension a source file plausibly carries (`.webp`, `.jpeg`, `.tiff`, `.clip`). */ +private const val MAXIMUM_EXTENSION_LENGTH = 5 \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/document/RecentFiles.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/document/RecentFiles.kt new file mode 100644 index 0000000..0e556d8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/document/RecentFiles.kt @@ -0,0 +1,29 @@ +package org.umamo.ui.document + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonPrimitive +import org.umamo.settings.Settings + +private const val RECENT_FILES_KEY = "app.recentFiles" +private const val RECENT_FILES_MAX = 10 + +/** + * The recently-opened file paths, most-recent first (the `app.recentFiles` setting). + * + * @return List The recent paths. + */ +fun Settings.recentFiles(): List = + (get(RECENT_FILES_KEY) as? JsonArray) + ?.mapNotNull { (it as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.content } + ?: emptyList() + +/** + * Records [path] as the most-recently-opened, moving it to the front (de-duplicated) and capping the list. + * Persists immediately and emits the change (so the Open Recent menu refreshes). + * + * @param String path The opened file path. + */ +fun Settings.addRecentFile(path: String) { + val updated = (listOf(path) + recentFiles().filterNot { it == path }).take(RECENT_FILES_MAX) + set(RECENT_FILES_KEY, JsonArray(updated.map { JsonPrimitive(it) })) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/ColorRgbBridge.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/ColorRgbBridge.kt new file mode 100644 index 0000000..d7ec33e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/ColorRgbBridge.kt @@ -0,0 +1,22 @@ +package org.umamo.ui.graphics + +import androidx.compose.ui.graphics.Color +import org.umamo.runtime.model.ColorRgb + +/** + * Converts the model's [ColorRgb] (three 0..1 float channels, no alpha) to a Compose [Color], forced + * opaque. The composite tint colors are stored as [ColorRgb]; the UI edits them through Compose's + * [Color] and the hex helpers ([formatHexColor] / [parseHexColor]), so this is the model-to-UI half of + * that bridge. + * + * @return Color The opaque Compose color with the same red / green / blue. + */ +fun ColorRgb.toComposeColor(): Color = Color(red = red, green = green, blue = blue, alpha = 1f) + +/** + * Converts a Compose [Color] back to the model's [ColorRgb], dropping the alpha channel ([ColorRgb] has + * none - the source formats' alpha is always opaque). The UI-to-model half of the composite color bridge. + * + * @return ColorRgb The red / green / blue as 0..1 floats. + */ +fun Color.toColorRgb(): ColorRgb = ColorRgb(red = red, green = green, blue = blue) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/HexColor.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/HexColor.kt new file mode 100644 index 0000000..6cc4e87 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/HexColor.kt @@ -0,0 +1,38 @@ +package org.umamo.ui.graphics + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb + +/** + * Parses a hex color string into a Compose color: 8 hex digits are AARRGGBB, 6 are RRGGBB with an opaque + * alpha. A leading '#' and surrounding whitespace are tolerated. Returns null for anything else (wrong + * length, non-hex characters, empty), so callers can fall back to a default rather than render garbage. + * + * @param String text The hex string to parse (e.g. "#CCFF9800" or "2962FF"). + * @return Color? The parsed color, or null when [text] is not a valid hex color. + */ +fun parseHexColor(text: String): Color? { + val cleaned = text.trim().removePrefix("#") + // Reject signs and whitespace that toLongOrNull would tolerate: hex digits only. + if (!cleaned.all { character -> character.isDigit() || character in 'a'..'f' || character in 'A'..'F' }) { + return null + } + val packed = cleaned.toLongOrNull(16) ?: return null + return when (cleaned.length) { + 8 -> Color(packed and 0xFFFFFFFFL) + 6 -> Color(packed or 0xFF000000L) + else -> null + } +} + +/** + * Formats a color as the canonical uppercase "#AARRGGBB" hex string [parseHexColor] accepts, so a parsed + * and re-formatted value round-trips exactly (the settings layer stores this canonical form). + * + * @param Color color The color to format. + * @return String The canonical "#AARRGGBB" string. + */ +fun formatHexColor(color: Color): String { + val packed = color.toArgb().toLong() and 0xFFFFFFFFL + return "#" + packed.toString(16).uppercase().padStart(8, '0') +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.kt new file mode 100644 index 0000000..851a980 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.kt @@ -0,0 +1,26 @@ +package org.umamo.ui.graphics + +import androidx.compose.ui.graphics.ImageBitmap + +/** How the RGBA bytes' alpha channel is to be interpreted when wrapped as an [ImageBitmap]. */ +enum class RgbaAlphaType { + /** Every texel is fully opaque; the alpha bytes are ignored. */ + Opaque, + + /** Straight (non-premultiplied) alpha: RGB is not scaled by A. */ + Straight, +} + +/** + * Wraps raw top-first RGBA bytes as a Compose [ImageBitmap]. + * + * Platform seam: desktop wraps via Skiko's Image.makeRaster, Android via android.graphics.Bitmap — + * both preserve straight alpha so a transparent texel's leftover matte RGB does not ghost through. + * + * @param ByteArray rgba The pixel bytes, 4 per texel, top row first. + * @param Int width The image width in texels. + * @param Int height The image height in texels. + * @param RgbaAlphaType alphaType How the alpha channel is interpreted. + * @return ImageBitmap The wrapped Compose bitmap. + */ +expect fun rgbaToImageBitmap(rgba: ByteArray, width: Int, height: Int, alphaType: RgbaAlphaType): ImageBitmap \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/help/AboutDialog.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/AboutDialog.kt new file mode 100644 index 0000000..f7bf07f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/AboutDialog.kt @@ -0,0 +1,100 @@ +package org.umamo.ui.help + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.button.CloseButton +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.about_license +import org.umamo.ui.resources.about_title +import org.umamo.ui.resources.about_version +import org.umamo.ui.resources.app_name +import org.umamo.ui.resources.dialog_close +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * The Help → About dialog: application name, version, license line, and the project URLs, in the + * same scrim-plus-card modal family as the settings window (opened by the help.about command; the + * shell owns the visible state and routes Escape, this composable only renders). + * + * @param Function onDismiss Closes the dialog (Escape is routed here by the shell; also the scrim / close button). + */ +@Composable +fun AboutDialog(onDismiss: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + Box( + modifier = + Modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Surface( + modifier = Modifier.width(420.dp).clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier.fillMaxWidth().background(colors.headerBackground).padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text = stringResource(Res.string.about_title), style = typography.titleSmall, modifier = Modifier.weight(1f)) + CloseButton(onClick = onDismiss, contentDescription = stringResource(Res.string.dialog_close)) + } + Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider)) + Column(modifier = Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(text = stringResource(Res.string.app_name), style = typography.titleSmall) + Text(text = stringResource(Res.string.about_version, ProjectInfo.VERSION), style = typography.bodyMedium) + Text(text = stringResource(Res.string.about_license), style = typography.bodySmall, color = colors.textMuted) + LinkLine(ProjectInfo.WEB_SITE_URL) + LinkLine(ProjectInfo.SOURCE_CODE_URL) + } + } + } + } +} + +/** + * One clickable URL line: shown accent-colored and opened through the platform UriHandler on click, + * failing quietly (a log line, never a crash) when the platform refuses - the same policy as the + * Help menu's link items. + * + * @param String url The URL shown and opened. + */ +@Composable +private fun LinkLine(url: String) { + val uriHandler = LocalUriHandler.current + Text( + text = url, + style = LocalUmamoTypography.current.bodySmall, + color = LocalUmamoColors.current.accent, + modifier = + Modifier.clickable { uriHandler.openLinkQuietly(url) }, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/help/CreditsDialog.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/CreditsDialog.kt new file mode 100644 index 0000000..17ad021 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/CreditsDialog.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.help + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.kit.button.CloseButton +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.credits_title +import org.umamo.ui.resources.dialog_close +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * The Help → Credits dialog: the bundled CREDITS.md (the single consolidated home of credits and + * third-party license attributions) rendered as a scrollable sheet, in the same scrim-plus-card + * modal family as the settings window. The file is read from the build-time-bundled compose + * resource, so editing the repo-root CREDITS.md and rebuilding is the whole update path. + * + * The rendering is deliberately line-based, not a Markdown engine: headings get title styles, the + * fenced license block gets monospace, everything else is body text - sufficient for this one + * document and nothing more to maintain. + * + * クレジットダイアログ。ビルド時に同梱した CREDITS.md をスクロール表示する(Markdown エンジンは使わず、 + * 行単位の簡易整形のみ)。 + * + * @param Function onDismiss Closes the dialog (Escape is routed here by the shell; also the scrim / close button). + */ +@Composable +fun CreditsDialog(onDismiss: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + // Null until the resource read lands (one frame, tiny file); rendered as an empty sheet meanwhile. + val creditsText by produceState(initialValue = null) { + value = + runCatching { Res.readBytes("files/CREDITS.md").decodeToString() } + .getOrElse { failure -> "CREDITS.md could not be loaded: ${failure.message}" } + } + Box( + modifier = + Modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Surface( + modifier = + Modifier + .fillMaxWidth(0.82f) + .fillMaxHeight(0.82f) + .widthIn(max = 760.dp) + .heightIn(max = 560.dp) + .clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.fillMaxSize()) { + Row( + modifier = Modifier.fillMaxWidth().background(colors.headerBackground).padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text = stringResource(Res.string.credits_title), style = typography.titleSmall, modifier = Modifier.weight(1f)) + CloseButton(onClick = onDismiss, contentDescription = stringResource(Res.string.dialog_close)) + } + Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider)) + Box(modifier = Modifier.fillMaxWidth().weight(1f).padding(20.dp)) { + val scrollState = rememberScrollState() + Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) { + CreditsBody(creditsText.orEmpty()) + } + VerticalScrollbarOverlay(scrollState) + } + } + } + } +} + +/** + * Renders the credits text line by line: "# " and "## " headings get title/label styles (with + * breathing room above subsections), ``` fences toggle a monospace style for the embedded license + * block (the fence lines themselves are dropped), blank lines become spacers, and everything else is + * small body text. + * + * @param String text The full CREDITS.md contents. + */ +@Composable +private fun CreditsBody(text: String) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val monospace = typography.bodySmall.copy(fontFamily = FontFamily.Monospace) + var insideFence = false + for (line in text.lines()) { + when { + line.trimStart().startsWith("```") -> { + insideFence = !insideFence + } + + insideFence -> { + Text(text = line, style = monospace, color = colors.textMuted) + } + + line.startsWith("## ") -> { + Spacer(modifier = Modifier.height(12.dp)) + Text(text = line.removePrefix("## "), style = typography.labelMedium) + Spacer(modifier = Modifier.height(4.dp)) + } + + line.startsWith("# ") -> { + Text(text = line.removePrefix("# "), style = typography.titleSmall) + Spacer(modifier = Modifier.height(4.dp)) + } + + line.isBlank() -> { + Spacer(modifier = Modifier.height(6.dp)) + } + + else -> { + Text(text = line, style = typography.bodySmall) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/help/OpenLink.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/OpenLink.kt new file mode 100644 index 0000000..eece641 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/OpenLink.kt @@ -0,0 +1,15 @@ +package org.umamo.ui.help + +import androidx.compose.ui.platform.UriHandler +import org.umamo.storage.UmamoLog + +/** + * Opens [url] through the platform's handler - the browser on desktop, an intent on Android - failing + * quietly when the platform refuses: a log line, never a crash. A link is a convenience, and a machine + * with no browser registered must not take the editor down for following one. + * + * @param String url The URL to open. + */ +internal fun UriHandler.openLinkQuietly(url: String) { + runCatching { openUri(url) }.onFailure { failure -> UmamoLog.error("could not open $url", failure) } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/help/ProjectInfo.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/ProjectInfo.kt new file mode 100644 index 0000000..0eded91 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/help/ProjectInfo.kt @@ -0,0 +1,15 @@ +package org.umamo.ui.help + +/** + * Application identity constants: the version and the project URLs, the single source of truth the + * About dialog and the Help menu read. This constant IS the application version; the build derives + * its version stamps from it (gradle/project-version.gradle.kts parses the VERSION line at + * configuration time for the Android versionName and the desktop packaging) — never introduce a + * second definition. + */ +internal object ProjectInfo { + const val VERSION = "0.3.0-dev" + const val WEB_SITE_URL = "https://umamo.org" + const val SOURCE_CODE_URL = "https://github.com/umamoorg/umamo" + const val DOCUMENTATION_URL = "https://docs.umamo.org/" +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ClickGestures.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ClickGestures.kt new file mode 100644 index 0000000..3222bc8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ClickGestures.kt @@ -0,0 +1,128 @@ +package org.umamo.ui.kit + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerKeyboardModifiers +import androidx.compose.ui.input.pointer.isCtrlPressed +import androidx.compose.ui.input.pointer.isMetaPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.pointerInput + +/** + * Longest gap between two presses that still counts as a double click. One fixed window for every caller + * and platform, rather than each gesture reading its own view configuration, so a double click feels the + * same in every panel and the timing core stays free of composition. + */ +private const val DOUBLE_CLICK_MILLIS = 300L + +/** + * The press-to-press timing behind every double click in the editor. Pure state with no Compose types: + * [singleOrDoubleClick] runs on it, and a gesture that cannot use that modifier (the workspace tabs, whose + * double click shares a gesture with a reorder drag) calls it from its own pointer loop. + * + * Only two consecutive unmodified presses pair. A modified press (one carrying a selection modifier) is + * its own action, such as toggling a row in or out of the selection, so it never completes a double click + * and never arms one. + * + * @param Long windowMillis The double-click window in milliseconds, inclusive. + */ +class DoubleClickTracker(private val windowMillis: Long = DOUBLE_CLICK_MILLIS) { + /** The uptime of the press waiting for its second half, or null when none is pending. */ + private var pendingPressUptime: Long? = null + + /** + * Records a press and reports whether it completes a double click. A completed double clears the + * pending press, so a third quick press starts a fresh single rather than a second double. + * + * @param Long uptimeMillis The press's event time. + * @param Boolean modified Whether the press carries a selection modifier. + * @return Boolean True when this press is the second half of a double click. + */ + fun registerPress(uptimeMillis: Long, modified: Boolean = false): Boolean { + val pending = pendingPressUptime + if (modified) { + pendingPressUptime = null + return false + } + if (pending != null && uptimeMillis - pending <= windowMillis) { + pendingPressUptime = null + return true + } + pendingPressUptime = uptimeMillis + return false + } + + /** + * Forgets the pending press, so the next press starts fresh. For a press that turned into something + * other than a click, such as a drag. + */ + fun reset() { + pendingPressUptime = null + } +} + +/** + * A single- and double-click detector that fires the single-click action IMMEDIATELY on press, with no + * wait for a possible second click. `Modifier.clickable` and `detectTapGestures(onDoubleTap = …)` both + * defer the single click by the platform double-tap window to disambiguate it; this does not. It + * dispatches [onSingle] on a primary press and, if the press is the second half of a double click (see + * [DoubleClickTracker]), dispatches [onDouble] instead. So a double click runs the single action once and + * then the double action; callers rely on the double action replacing what the single one showed (e.g. an + * inline rename field taking over a row). + * + * [onSingle] receives the press's keyboard modifiers. A press holding Ctrl, Meta, or Shift, the selection + * modifiers, always goes to [onSingle] and never takes part in a double click, so Ctrl-clicking a row twice + * toggles it twice rather than renaming it. + * + * Secondary (right) presses and already-consumed presses are ignored, so a wrapping context menu still + * opens and child controls that consume their own press are not double-handled. Uses raw pointerInput, + * which never requests focus, so keyboard dispatch stays on the shell root. While [enabled] is false no + * pointer handling is installed at all, and a press pending from before is forgotten. + * + * @param Function onSingle Called on a primary press that is not the second half of a double click. + * @param Function onDouble Called on a second unmodified primary press within [doubleClickMillis]. + * @param Boolean enabled Whether presses are handled at all. + * @param Long doubleClickMillis The double-click window in milliseconds. + * @return Modifier The modifier with the press-timing detector attached. + */ +@Composable +fun Modifier.singleOrDoubleClick( + onSingle: (PointerKeyboardModifiers) -> Unit, + onDouble: () -> Unit, + enabled: Boolean = true, + doubleClickMillis: Long = DOUBLE_CLICK_MILLIS, +): Modifier { + // The pointer loop restarts only when the window changes, so it would otherwise keep the lambdas of the + // composition it started in; read the latest through these (matching the kit Slider). + val currentOnSingle by rememberUpdatedState(onSingle) + val currentOnDouble by rememberUpdatedState(onDouble) + if (!enabled) { + return this + } + return this.pointerInput(doubleClickMillis) { + val tracker = DoubleClickTracker(doubleClickMillis) + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if ( + event.type != PointerEventType.Press || + event.buttons.isSecondaryPressed || + event.changes.any { change -> change.isConsumed } + ) { + continue + } + val modifiers = event.keyboardModifiers + val modified = modifiers.isCtrlPressed || modifiers.isMetaPressed || modifiers.isShiftPressed + if (tracker.registerPress(event.changes.first().uptimeMillis, modified)) { + currentOnDouble() + } else { + currentOnSingle(modifiers) + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ConfirmDialog.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ConfirmDialog.kt new file mode 100644 index 0000000..e05cc58 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ConfirmDialog.kt @@ -0,0 +1,105 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.button.Button +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.dialog_cancel +import org.umamo.ui.resources.dialog_confirm +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A dialog's third choice beside Cancel and Confirm - "Don't Save" beside "Save". + * + * @property String label The already-localized button label. + * @property Function onSelect Called when the user picks it. + */ +class DialogChoice( + val label: String, + val onSelect: () -> Unit, +) + +/** + * A minimal modal confirm dialog: a scrim over the whole shell with a small centered card carrying the + * [message] and its buttons. Presentation-only and shell-agnostic so it is reusable for any destructive + * action - the caller owns the pending-request state and supplies the actions (the kit has no dialog of its + * own otherwise). Clicking the scrim, like Cancel, dismisses without confirming; the card swallows clicks so + * a press inside it does not count as a scrim dismissal. + * + * The confirm button is the primary one - the dialog's default, which Enter activates wherever the caller + * routes its keys. An [alternative] sits apart at the left, so a three-way choice reads as the action, the + * escape hatch, and the other outcome rather than three peers. + * + * @param String message The already-localized prompt shown in the card. + * @param Function onConfirm Called when the user confirms the action. + * @param Function onCancel Called when the user cancels (Cancel button or scrim click). + * @param Modifier modifier Layout modifier for the scrim. + * @param String? confirmLabel An already-localized label for the confirm button naming its action + * ("Discard", "Reassign"); null uses the generic "Confirm". + * @param String? cancelLabel An already-localized label for the cancel button; null uses "Cancel". + * @param DialogChoice? alternative A third choice shown at the left, or null for a two-button dialog. + */ +@Composable +fun ConfirmDialog( + message: String, + onConfirm: () -> Unit, + onCancel: () -> Unit, + modifier: Modifier = Modifier, + confirmLabel: String? = null, + cancelLabel: String? = null, + alternative: DialogChoice? = null, +) { + val colors = LocalUmamoColors.current + Box( + // indication = null (the kit convention): a bare clickable renders the default hover/press + // indication across the whole scrim, a stray dimming layer that toggles on pointer enter/leave. + modifier = + modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onCancel), + contentAlignment = Alignment.Center, + ) { + Surface( + // The card swallows clicks (enabled = false) so a press on it is not read as a scrim dismissal. + modifier = Modifier.widthIn(min = 280.dp, max = 420.dp).clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.padding(20.dp)) { + Text(text = message, style = LocalUmamoTypography.current.bodyMedium) + Row( + modifier = Modifier.padding(top = 20.dp).fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + alternative?.let { choice -> Button(label = choice.label, onClick = choice.onSelect, primary = false) } + Spacer(modifier = Modifier.weight(1f)) + Button(label = cancelLabel ?: stringResource(Res.string.dialog_cancel), onClick = onCancel, primary = false) + Button(label = confirmLabel ?: stringResource(Res.string.dialog_confirm), onClick = onConfirm, primary = true) + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ContextMenu.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ContextMenu.kt new file mode 100644 index 0000000..1ee1a6e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/ContextMenu.kt @@ -0,0 +1,98 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntOffset +import kotlin.math.roundToInt + +/** + * Wraps [content] so a context-menu request - a secondary (right) click on desktop, or a long press on a + * touch screen - opens [items] as a [Menu] at the pointer. The menu is positioned at the click point + * rather than anchored to an element, which is what distinguishes a context menu from a dropdown. + * + * The items are a pre-built value, not a lambda, because their labels are localized via stringResource - + * a @Composable call that can only run during composition, not on the pointer event that opens the menu. + * The list is cheap to rebuild each recomposition and is therefore always current. + * + * 二次クリック(デスクトップ)または長押し(タッチ)で、ポインタ位置に items をメニューとして開く。 + * + * @param List items The menu entries (built in composition, so labels can be localized). + * @param Modifier modifier The layout modifier for the wrapping box. + * @param Function content The content the context menu is attached to. + */ +@Composable +fun ContextMenuArea(items: List, modifier: Modifier = Modifier, content: @Composable () -> Unit) { + var open by remember { mutableStateOf(false) } + var anchorOffset by remember { mutableStateOf(IntOffset.Zero) } + Box( + modifier = + modifier.contextMenuGesture { localOffset -> + anchorOffset = localOffset + open = true + }, + ) { + CompositionLocalProvider(LocalContextMenuItems provides items) { + content() + } + if (open) { + Menu( + items = items, + onDismissRequest = { open = false }, + positionProvider = AtPointPositionProvider(anchorOffset), + focusable = true, + ) + } + } +} + +/** + * The items of the innermost enclosing [ContextMenuArea], for content that has to build its OWN menu. + * + * A text field is the case this exists for: it cannot simply sit inside a [ContextMenuArea] and inherit the + * behaviour, because it needs its own clipboard entries appended and its own gesture to beat the one the + * text-field primitive installs. Reading the enclosing items here rather than passing them down means a + * field picks up whatever menu it happens to be nested in - the keyframe menu on a Properties row, the area + * menu in a panel header - with no call site changed. + * + * Empty outside any area, which reads as "no items to prepend" rather than as an error. + */ +internal val LocalContextMenuItems = compositionLocalOf { emptyList() } + +/** + * Reports a context-menu request with the pointer position in the modified element's local space. The + * trigger is platform-specific - a secondary (right) click on desktop, a long press on a touch screen - + * because pointer-button state is a desktop-only (skiko) detail, so the detector is provided per platform. + * + * コンテキストメニュー要求を局所座標で通知する。トリガーはプラットフォーム依存(右クリック / 長押し)。 + * + * @param Function onContextMenu Called with the request point in local coordinates. + * @return Modifier The modifier with the platform's gesture detector attached. + */ +internal expect fun Modifier.contextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier + +/** + * [contextMenuGesture]'s variant for a TEXT FIELD, which has to beat the field primitive's own handler. + * + * Compose installs its built-in Cut / Copy / Paste menu on the text-field node itself. That node is inside + * ours, and the main pointer pass runs innermost-first, so an ordinary [contextMenuGesture] never sees the + * press - the built-in menu has already consumed it. The trigger therefore has to be watched a pass earlier. + * + * @param Function onContextMenu Called with the request point in local coordinates. + * @return Modifier The modifier with the detector attached. + */ +internal expect fun Modifier.textEditContextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier + +/** + * Rounds a pointer [Offset] to the integer pixel offset the popup position providers work in. + * + * @return IntOffset The rounded offset. + */ +internal fun Offset.toIntOffset(): IntOffset = IntOffset(x.roundToInt(), y.roundToInt()) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/DisclosureChevron.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/DisclosureChevron.kt new file mode 100644 index 0000000..3366af9 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/DisclosureChevron.kt @@ -0,0 +1,53 @@ +package org.umamo.ui.kit + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.button.IconSlot +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons + +/** + * The expand / collapse chevron every tree in the app draws: a down glyph while open, a right glyph while + * closed, named for the action a click performs. Consolidates what were separate copies of the same + * conditional glyph in the panel section header, the keyform sheet, the parameter groups, and the track + * sheet, so the art and the label stay in one place. + * + * The default label matters more than it looks: a disclosure row's visible text names the section but never + * says whether it is open, so the chevron's accessible name is the only place that state is exposed. For + * the same reason the tooltip is off by default - the chevron always sits beside its own readable label, and + * a hover card repeating on-screen text is noise. A caller with a genuinely icon-only chevron passes + * [hoverLabel]. + * + * @param Boolean expanded Whether the section is open (down glyph) or closed (right glyph). + * @param Color tint The glyph color, resolved by the caller against its own row state. + * @param Modifier modifier Applied to the glyph's box, so a caller's toggle gesture covers it. + * @param Dp glyphSize The drawn chevron size; the hit box matches it. + * @param String contentDescription The accessible name, defaulting to the action the chevron performs. + * @param String hoverLabel The tooltip text; blank (the default) attaches none. + */ +@Composable +fun DisclosureChevron( + expanded: Boolean, + tint: Color, + modifier: Modifier = Modifier, + glyphSize: Dp = 12.dp, + contentDescription: String = + stringResource(if (expanded) Res.string.common_collapse else Res.string.common_expand), + hoverLabel: String = "", +) { + val icons = LocalUmamoIcons + IconSlot( + icon = if (expanded) icons.chevronDown else icons.chevronRight, + contentDescription = contentDescription, + tint = tint, + modifier = modifier, + slotSize = DpSize(glyphSize, glyphSize), + glyphSize = glyphSize, + hoverLabel = hoverLabel, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/DropdownChip.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/DropdownChip.kt new file mode 100644 index 0000000..6d2c622 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/DropdownChip.kt @@ -0,0 +1,196 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.requiredSize +import androidx.compose.foundation.layout.requiredWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** + * The roles a [DropdownChip] plays: a [Header] chrome chip (content-width, tab-fill, an accent open + * state, a right/down disclosure chevron), a form [Field] (fills its column over the control fill, a + * down/up chevron pushed to the trailing edge) that sits beside the other form controls, or a [Compact] + * header chip sized for a 22.dp list row (a 14.dp glyph in 2.dp padding, so the face is 18.dp tall + * where a Header's 24.dp would overflow the row). Sanctioned variations of the one chip rather than + * forks, so every role shares the anatomy. + */ +enum class DropdownChipStyle { + Header, + Field, + Compact, +} + +/** + * The header dropdown chip, Blender-style: an optional 16.dp leading glyph, an optional labelMedium + * text, and a 12.dp chevron that points right while the dropdown is closed and down while it is open. + * Flat like the rest of the kit - the default indication is suppressed and the chip paints its own + * three-state border and fill: accent while open, panelBackground / panelBorderHover under the + * pointer, tabBackground / panelBorder at rest; content is accentText while open, controlGlyph + * otherwise. The face is explicit params rather than a content slot on purpose: the anatomy (sizes, + * paddings, chevron) stays un-forkable across every header chip, which is the drift this component + * exists to prevent. The dropdown stays a slot because consumers differ (a kit Menu that dismisses + * per click vs a stay-open Popup). + * + * A Header chip holds its intrinsic width: the glyphs and the label ignore the incoming maximum, so a + * parent with no room left pushes the chip off its edge instead of squeezing it down to an empty + * padding box. A Field chip still ellipsizes its label, which is what a form column wants. + * + * @param Boolean expanded Whether the chip's dropdown is open (drives the accent state). + * @param Function onExpandRequest Invoked on click to open the dropdown. + * @param String contentDescription The accessible label (the face may be icon-only). + * @param Modifier modifier The layout modifier. + * @param UmamoIcon icon Optional leading 16.dp glyph. + * @param String label Optional labelMedium text between the icon and the chevron. + * @param Boolean enabled When false the content dims to the disabled tint and clicks are inert + * (no-document chrome renders its chips this way rather than hiding them). + * @param DropdownChipStyle style Which role the chip plays; see [DropdownChipStyle]. + * @param Color? iconTint A status color for the glyph at rest, or null for the chip's own content color. + * @param Function dropdown The popup content, rendered while expanded. + */ +@Composable +fun DropdownChip( + expanded: Boolean, + onExpandRequest: () -> Unit, + contentDescription: String, + modifier: Modifier = Modifier, + icon: UmamoIcon? = null, + label: String? = null, + enabled: Boolean = true, + style: DropdownChipStyle = DropdownChipStyle.Header, + iconTint: Color? = null, + dropdown: @Composable () -> Unit, +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hoveredLive by interaction.collectIsHoveredAsState() + // A disabled chip shows no hover feedback (the border and fill stay at rest). + val hovered = hoveredLive && enabled + val isField = style == DropdownChipStyle.Field + // A Compact chip keeps the Header anatomy at list-row scale: the glyph matches the row's own 14.dp + // icons and the padding halves, so the 18.dp face sits inside a 22.dp row instead of overflowing it. + val isCompact = style == DropdownChipStyle.Compact + val facePadding = if (isCompact) 2.dp else 4.dp + val glyphSize = if (isCompact) 14.dp else 16.dp + val chevronSize = if (isCompact) 10.dp else 12.dp + val borderColor = + when { + expanded -> colors.accent + hovered -> colors.panelBorderHover + else -> colors.panelBorder + } + val backgroundColor = + when { + expanded -> colors.accent + hovered -> colors.panelBackground + else -> colors.tabBackground + } + val chipContentColor = + when { + !enabled -> colors.textDisabled + expanded -> colors.accentText + else -> colors.text + } + // The popup is a child of this Box rather than of the padded chip Row: the position provider is + // handed the anchor's bounds, and the Row's inner box excludes its own padding and background, which + // would shift the menu off the chip's painted corner (same pattern as MenuBarLabel). + Box(modifier = modifier) { + // The tooltip wraps the chip face only; the popup is a sibling below, so it is never wrapped and + // its anchor bounds (the box) stay the chip's bounds. + Tooltip(text = contentDescription) { + // A Field fills its column so it lines up with the other form controls. A Header chip is pinned to + // its own intrinsic width and IGNORES the incoming maximum: a Row clamps itself to whatever width is + // left, which would shrink the painted face out from under the glyphs. Overflowing the parent (and + // being clipped) is the legible failure; a chip squeezed down to an empty padding box is not. + val faceWidth = + if (isField) { + Modifier.fillMaxWidth() + } else { + Modifier.requiredWidth(IntrinsicSize.Max) + } + Row( + modifier = + faceWidth + .clip(shapes.small) + // NOT focusable, like SectionHeader and Checkbox: the popup owns its own focus while open, + // and on close the keyboard must return to the shell root, not to a chip that transient + // chrome (the operation settings strip) may dispose on the next edit. + .focusProperties { canFocus = false } + .clickable(interactionSource = interaction, indication = null, enabled = enabled, onClick = onExpandRequest) + .border(width = 1.dp, color = borderColor, shape = shapes.small) + .background(backgroundColor, shape = shapes.small) + .padding(facePadding) + .semantics { this.contentDescription = contentDescription }, + verticalAlignment = Alignment.CenterVertically, + ) { + if (icon != null) { + // requiredSize, not size: size coerces to the incoming constraints, so a starved parent + // measures the glyph at zero and the chip renders as an empty padding box. The chip holds + // its glyphs at full size and overflows instead - being pushed off the edge is legible, + // silently shrinking to nothing is not. + // A status tint colors the glyph at rest only; the open and disabled faces keep their own contrast. + val glyphColor = if (iconTint != null && enabled && !expanded) iconTint else chipContentColor + Canvas(modifier = Modifier.requiredSize(glyphSize)) { + drawIcon(icon, glyphColor) + } + } + if (label != null) { + // A Field weights its label so it fills the chip (ellipsizing when long) and pushes the + // chevron to the trailing edge; a Header keeps the label content-width, which the Row's own + // intrinsic sizing already guarantees room for. + val labelModifier = + if (isField) { + Modifier.weight(1f).padding(horizontal = 4.dp) + } else { + Modifier.padding(horizontal = 4.dp) + } + Text( + text = label, + style = LocalUmamoTypography.current.labelMedium, + color = chipContentColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = labelModifier, + ) + } + val chevron = + when { + expanded -> LocalUmamoIcons.chevronDown + else -> LocalUmamoIcons.chevronRight + } + Canvas(modifier = Modifier.requiredSize(chevronSize)) { + drawIcon(chevron, chipContentColor) + } + } + } + if (expanded) { + dropdown() + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FieldRow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FieldRow.kt new file mode 100644 index 0000000..f2e7323 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FieldRow.kt @@ -0,0 +1,80 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** The default width of a [FieldRow]'s label column, so a column of rows aligns its controls. */ +val FIELD_ROW_LABEL_WIDTH = 180.dp + +/** The default spacing between stacked [FieldRow]s in a section. */ +val FIELD_ROW_SPACING = 14.dp + +/** + * The uniform height of a compact inline form control (a NumberField, a SelectField), so a column of mixed + * controls lines up to one height rather than each sizing to its own text metrics. A single source shared + * by every field control keeps them exactly matched - change it here and the whole form follows. + */ +val FIELD_CONTROL_HEIGHT = 20.dp + +/** The drawn size of a [FieldRow]'s optional label icon. */ +private val FIELD_ROW_ICON_SIZE = 16.dp + +/** + * One labelled control row: a fixed-width label on the left and its [control] on the right, so the + * controls down a section align. The shared label:control primitive the settings sections and the + * Properties panel build on (promoted here from the settings package so both reuse one row). + * + * An [icon] leads the label inside the same column, so the controls stay aligned with the rows that + * have none. It is decorative - the label beside it is the row's name - so it carries no semantics. + * + * @param String label The already-localized row label. + * @param Modifier modifier The layout modifier for the row. + * @param Dp labelWidth The label column width (narrow it for a tight panel). + * @param UmamoIcon? icon A glyph drawn before the label, or null for a text-only label. + * @param Function control The control composable (a SelectField, NumberField, Checkbox, etc.). + */ +@Composable +fun FieldRow( + label: String, + modifier: Modifier = Modifier, + labelWidth: Dp = FIELD_ROW_LABEL_WIDTH, + icon: UmamoIcon? = null, + control: @Composable () -> Unit, +) { + val colors = LocalUmamoColors.current + Row(modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Row(modifier = Modifier.width(labelWidth), verticalAlignment = Alignment.CenterVertically) { + if (icon != null) { + Canvas(modifier = Modifier.size(FIELD_ROW_ICON_SIZE)) { + drawIcon(icon, colors.text) + } + Spacer(modifier = Modifier.width(6.dp)) + } + Text( + text = label, + style = LocalUmamoTypography.current.bodyMedium, + color = colors.text, + ) + } + Spacer(modifier = Modifier.width(12.dp)) + // The control fills the remaining width, so a fillMaxWidth field / dropdown spans the row and a + // fixed-width control sits at the column start - both stay aligned down a section. + Box(modifier = Modifier.weight(1f)) { + control() + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FieldStack.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FieldStack.kt new file mode 100644 index 0000000..5839db8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FieldStack.kt @@ -0,0 +1,42 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +/** + * The hairline seam between two butted fields in a vertical [FieldStack]. The panel surface behind the + * stack shows through this gap, so the division follows the theme (a dark seam over a dark island, a light + * seam over a light one) rather than being a drawn border - the vertical analogue of a ButtonGroup's + * SEGMENT_GAP, keeping both stacked runs visually consistent. + */ +val FIELD_STACK_SEAM = 1.dp + +/** + * Lays out a vertical run of butted fields as one joined group, Blender-style: the fields sit flush with a + * [FIELD_STACK_SEAM] hairline between them, and only the run's outer corners round. Mirrors [ButtonGroup] + * for the vertical axis - the container owns the seams and hands each row its [StackPosition] (via + * [stackPositionOf]), so a caller stacks fields without hand-threading First / Middle / Last and can never + * get an end wrong. Each row is a composable taking the position it should pass to its field's + * stackPosition (so the row's own label / control layout stays the caller's concern). + * + * @param List rows The stacked rows in top-to-bottom order; each is given its position in the run. + * @param Modifier modifier The layout modifier for the enclosing column. + */ +@Composable +fun FieldStack( + rows: List<@Composable (StackPosition) -> Unit>, + modifier: Modifier = Modifier, +) { + Column(modifier = modifier) { + rows.forEachIndexed { rowIndex, row -> + if (rowIndex > 0) { + Spacer(modifier = Modifier.height(FIELD_STACK_SEAM)) + } + row(stackPositionOf(rowIndex, rows.size)) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FileDropTarget.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FileDropTarget.kt new file mode 100644 index 0000000..84ab899 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FileDropTarget.kt @@ -0,0 +1,109 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.draganddrop.dragAndDropTarget +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draganddrop.DragAndDropEvent +import androidx.compose.ui.draganddrop.DragAndDropTarget +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes + +/** + * Whether this drag-and-drop event carries files at all - the question a drop target answers before it + * joins a session. + * + * Separate from [droppedFilePaths] because of when each may be asked. A platform may not hand over the + * payload of a drag still in flight (AWT says so explicitly: a drag event's transfer data can be + * unavailable until the drop), while what KINDS of data the drag carries is known from the start. So this + * inspects only the advertised shape, and the paths are read once the file has actually been let go. + * + * @return Boolean True when the drag advertises files this target could take. + */ +expect fun DragAndDropEvent.carriesFiles(): Boolean + +/** + * The stored paths a completed drop carries, or empty when it carries none. + * + * A path here is in the form the recent-files list stores - a file-system path on desktop, a `content://` + * uri string on Android - so a caller hands one straight to the document loader. + * + * @return List The dropped files as stored paths, in the order the platform reported them. + */ +expect fun DragAndDropEvent.droppedFilePaths(): List + +/** + * Wraps [content] in a surface that accepts files dropped on it from outside the application, framing + * itself in the accent color while a drag it would accept is over it. + * + * Only a drag carrying files starts a session here ([carriesFiles]), so a text or image drag falls through + * to whatever else in the hierarchy wants it. Nothing is read or validated beyond that: [onDrop] is handed + * the paths and decides what each one means, because the way a file is opened is the caller's business and + * the file's contents are the loader's. + * + * The frame is drawn here rather than left to the caller so the over-state and the thing it paints cannot + * drift apart, and it is drawn as an overlaid sibling so it neither re-lays-out [content] nor takes any + * space from it. + * + * @param Function onDrop Called with the dropped files' stored paths; never called with an empty list. + * @param Function content The content the drop target covers. + */ +@Composable +fun FileDropTarget(onDrop: (List) -> Unit, content: @Composable () -> Unit) { + // The target node outlives recompositions, so it reads the caller's lambda through a holder rather + // than capturing the first composition's. + val currentOnDrop by rememberUpdatedState(onDrop) + var dragOver by remember { mutableStateOf(false) } + val target = + remember { + object : DragAndDropTarget { + override fun onEntered(event: DragAndDropEvent) { + dragOver = true + } + + override fun onExited(event: DragAndDropEvent) { + dragOver = false + } + + // Clears on the session's end as well as on exit: a drag cancelled outside the window + // (Escape, or a release over another application) sends no exit, and the frame would stay. + override fun onEnded(event: DragAndDropEvent) { + dragOver = false + } + + override fun onDrop(event: DragAndDropEvent): Boolean { + val paths = event.droppedFilePaths() + if (paths.isEmpty()) { + return false + } + currentOnDrop(paths) + return true + } + } + } + Box( + Modifier.fillMaxSize().dragAndDropTarget( + shouldStartDragAndDrop = { startEvent -> startEvent.carriesFiles() }, + target = target, + ), + ) { + content() + if (dragOver) { + Box( + Modifier + .fillMaxSize() + .background(LocalUmamoColors.current.accent.copy(alpha = 0.5f), LocalUmamoShapes.current.large) + .border(2.dp, LocalUmamoColors.current.accent, LocalUmamoShapes.current.large), + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FilterPopupChip.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FilterPopupChip.kt new file mode 100644 index 0000000..da76348 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/FilterPopupChip.kt @@ -0,0 +1,61 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon + +/** + * A header filter dropdown: the shared [PopupChip] wearing a funnel, holding a panel of view toggles. + * The panel stays open while toggling, so several filters can be flipped in one visit, and the open + * state stays inside the chip - a panel adds a filter menu by supplying only its toggle rows. + * + * @param String contentDescription The accessible label for the chip (the face is icon-only). + * @param Modifier modifier The layout modifier. + * @param UmamoIcon icon The chip's leading glyph; the funnel by default. + * @param Boolean enabled When false the chip dims and clicks are inert. + * @param Function content The toggle rows, stacked in the popup panel. + */ +@Composable +fun FilterPopupChip( + contentDescription: String, + modifier: Modifier = Modifier, + icon: UmamoIcon = LocalUmamoIcons.filterFiltered, + enabled: Boolean = true, + content: @Composable ColumnScope.() -> Unit, +) { + PopupChip( + contentDescription = contentDescription, + modifier = modifier, + icon = icon, + enabled = enabled, + content = content, + ) +} + +/** + * A muted caption heading one group of rows inside a [FilterPopupChip] panel. Extracted so every + * filter panel's section headings share one type style and inset. One line, ellipsized: a heading + * that names a document object (an artwork file) can be arbitrarily long, and it must not widen or + * wrap the panel the rows beneath it are sized for. + * + * @param String text The heading text. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun FilterSectionLabel(text: String, modifier: Modifier = Modifier) { + Text( + text = text, + style = LocalUmamoTypography.current.labelSmall, + color = LocalUmamoColors.current.textMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = modifier.padding(horizontal = 8.dp, vertical = 2.dp), + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/HexColorField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/HexColorField.kt new file mode 100644 index 0000000..52a4046 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/HexColorField.kt @@ -0,0 +1,305 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupProperties +import org.umamo.ui.graphics.formatHexColor +import org.umamo.ui.graphics.parseHexColor +import org.umamo.ui.model.KeyedFieldState +import org.umamo.ui.model.backgroundTint +import org.umamo.ui.model.tint +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import kotlin.math.roundToInt + +/** + * A compact hex color entry: a live swatch beside a text field accepting "#AARRGGBB" (or "#RRGGBB", + * treated as opaque). Every keystroke that parses is committed immediately through [onValueChange] in + * canonical form - the auto-save model the settings window uses, so the swatch and any live consumer (the + * viewport gizmo) follow the typing with no confirm step. Text that does not parse stays local to the + * field (the swatch holds the last good color) and is discarded on focus loss, which re-seeds the field + * from the persisted [value]. Enter confirms by clearing focus. + * + * Clicking the swatch opens an RGB-slider popover for graphical picking; a slider drag commits once at its + * end (one write per gesture, not per frame), while the text field stays the path for exact entry. + * + * Like [NumberField], it lends its cancel hook to [LocalInlineEditController] while focused, so the editor + * shell's root key handler yields keystrokes to the field (hex digits are also bare-digit shortcuts) and + * routes Escape here (clearing focus) instead. + * + * @param String value The persisted color as canonical "#AARRGGBB" text. + * @param Function onValueChange Called with the canonical hex of each parseable edit. + * @param Modifier modifier Layout modifier (the caller supplies the width). + * @param KeyedFieldState keyState The keyform state to tint the field with (outline on the swatch, background + * fill on the text field). + */ +@Composable +fun HexColorField( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + keyState: KeyedFieldState = KeyedFieldState.None, +) { + val colors = LocalUmamoColors.current + // The SWATCH keeps the outline form of the keyed tint, because its background IS the user's own color and + // has nothing to spare; the hex field beside it takes the tint as a fill, like every other text control. + val swatchBorderColor = keyState.tint(colors) ?: colors.controlBorder + val keyedFill = keyState.backgroundTint(colors) ?: Color.Transparent + val shapes = LocalUmamoShapes.current + val controller = LocalInlineEditController.current + val focusManager = LocalFocusManager.current + var focused by remember { mutableStateOf(false) } + // A TextFieldValue rather than a String so the context menu can act on a selection. + var text by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) } + var pickerOpen by remember { mutableStateOf(false) } + + // Mirror the external value - and do it EVEN WHILE FOCUSED, because this field is not the only writer + // of what it shows. The swatch's own picker, a parameter scrub moving a keyed channel, and undo all + // change the value underneath it; skipping the mirror while focused pinned the field to whatever it + // last held, and since nothing takes focus back off it, a keyed color stayed frozen on its first key + // forever while the viewport went on blending. + // + // The compare is on the PARSED color, not the text, and that is what keeps this from fighting the + // typist: the user's own keystroke round-trips out through onValueChange and comes back equal, so it + // re-seeds nothing. Half-typed text that does not parse is left alone for the same reason. + LaunchedEffect(value, focused) { + val typed = parseHexColor(text.text) + if (!focused || (typed != null && typed != parseHexColor(value))) { + text = TextFieldValue(value, TextRange(value.length)) + } + } + + // Drop the lent cancel hook if the field disposes while focused (a section switch mid-edit). + DisposableEffect(Unit) { + onDispose { + if (focused) { + controller.cancel = null + } + } + } + + Row(verticalAlignment = Alignment.CenterVertically, modifier = modifier) { + // The live swatch: the color being typed when parseable, else the last persisted one. Clicking it + // opens the slider popover, anchored to this swatch (the Box wrapper is the popup's anchor bounds). + val swatchColor = parseHexColor(text.text) ?: parseHexColor(value) ?: Color.Transparent + Box { + Box( + modifier = + Modifier + .size(18.dp) + .clip(shapes.small) + .background(swatchColor) + .border(1.dp, swatchBorderColor, shapes.small) + // Opens only. It must NOT toggle: an outside-click dismiss fires first and closes the + // popover, and this click would then immediately reopen it, so the swatch could never + // be used to close. Closing is the popup's own job (click-away or Escape). + .clickable { pickerOpen = true }, + ) + if (pickerOpen) { + Popup( + popupPositionProvider = BelowAnchorPositionProvider, + onDismissRequest = { pickerOpen = false }, + // NOT focusable: a focusable popup pulls focus off the shell root, and nothing restores it + // on dismiss - every keyboard shortcut stays dead until Tab traversal reclaims it (the + // hazard IconButton.suppressFocus exists to avoid). The sliders are pointer-driven, so the + // popover needs no focus of its own; dismissal still works via the outside-click handler. + properties = PopupProperties(focusable = false), + ) { + // The popover edits the persisted color; a slider commit round-trips through onValueChange + // (canonical hex), which re-seeds the swatch and the text field. + ColorSliderPopover( + color = parseHexColor(value) ?: Color.Black, + onColorChange = { picked -> onValueChange(formatHexColor(picked)) }, + ) + } + } + } + Spacer(modifier = Modifier.width(6.dp)) + TextEditContextMenuArea( + value = text, + onValueChange = { edited -> commitHexEdit(edited, text, onValueChange) { updated -> text = updated } }, + modifier = Modifier.weight(1f), + ) { gesture -> + BasicTextField( + value = text, + onValueChange = { edited -> commitHexEdit(edited, text, onValueChange) { updated -> text = updated } }, + textStyle = LocalUmamoTypography.current.bodySmall.copy(color = colors.text), + singleLine = true, + cursorBrush = SolidColor(colors.text), + modifier = + gesture + .textEntrySurface(controller) + .fillMaxWidth() + .clip(shapes.small) + .background(colors.controlBackground) + .background(keyedFill, shapes.small) + .border(1.dp, colors.controlBorder, shapes.small) + .padding(horizontal = 6.dp, vertical = 4.dp) + .onFocusChanged { focusState -> + // hasFocus (not isFocused): BasicTextField focuses an internal child, so this node only + // ever sees its subtree's focus. + if (focusState.hasFocus) { + if (!focused) { + focused = true + // Escape routes here via the shell: end the edit by clearing focus (the mirror + // effect above then re-seeds the text from the persisted value). + controller.cancel = { focusManager.clearFocus() } + } + } else if (focused) { + focused = false + controller.cancel = null + } + } + .onKeyEvent { event -> + // Hardware Enter confirms by clearing focus (edits are already persisted live). + if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) { + focusManager.clearFocus() + true + } else { + false + } + }, + ) + } + } +} + +/** + * Applies one hex-field edit: shows it, and persists it when the TEXT changed and parses. + * + * Shared by the field and its context menu so a pasted color takes effect exactly like a typed one - the + * menu writing only the local text would have shown a color the document never received. + * + * Selection-only changes are shown and not persisted. BasicTextField's TextFieldValue overload reports a + * caret or selection move through the same callback as an edit, so persisting unconditionally re-committed + * the stored value for merely clicking into the field, dragging a selection across it, or picking Select + * All - and on a keyed channel that is an undo step plus an uncommitted-edit tint for a value that never + * changed. + * + * @param TextFieldValue edited The value the field or menu produced. + * @param TextFieldValue previous The value it replaces, for telling an edit from a selection move. + * @param Function onValueChange The caller's persist callback, given canonical hex. + * @param Function show Writes the edited value back to the field's own state. + */ +private fun commitHexEdit( + edited: TextFieldValue, + previous: TextFieldValue, + onValueChange: (String) -> Unit, + show: (TextFieldValue) -> Unit, +) { + show(edited) + if (edited.text == previous.text) { + return + } + parseHexColor(edited.text)?.let { parsed -> onValueChange(formatHexColor(parsed)) } +} + +/** + * The RGB-slider popover a [HexColorField] swatch opens: a preview strip over three channel sliders. The + * sliders drive a local draft so the preview follows every frame, but the outer [onColorChange] fires only + * when a slider gesture ends - so a whole drag is one commit (and one undo step), not one per frame. The + * draft re-seeds whenever the committed [color] changes externally (e.g. the text field is typed while the + * popover is open). A slider edits only its channel, so the color's alpha (if any) is preserved. + * + * @param Color color The current committed color the sliders start from. + * @param Function onColorChange Commits a picked color (fired at each slider gesture's end). + */ +@Composable +private fun ColorSliderPopover(color: Color, onColorChange: (Color) -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + var draft by remember { mutableStateOf(color) } + LaunchedEffect(color) { + draft = color + } + Surface(color = colors.menuBackground, shape = shapes.medium) { + Column( + modifier = Modifier.width(184.dp).padding(8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Box( + modifier = + Modifier + .fillMaxWidth() + .height(22.dp) + .clip(shapes.small) + .background(draft) + .border(1.dp, colors.controlBorder, shapes.small), + ) + ColorChannelSlider("R", draft.red, { channel -> draft = draft.copy(red = channel) }, { onColorChange(draft) }) + ColorChannelSlider("G", draft.green, { channel -> draft = draft.copy(green = channel) }, { onColorChange(draft) }) + ColorChannelSlider("B", draft.blue, { channel -> draft = draft.copy(blue = channel) }, { onColorChange(draft) }) + } + } +} + +/** + * One 0..255 channel row inside [ColorSliderPopover]: a letter label, the slider, and a numeric readout. + * The slider streams its channel value as a 0..1 fraction to [onChannel] for the live preview and calls + * [onCommit] once when the gesture ends. + * + * @param String label The channel letter ("R" / "G" / "B"). + * @param Float channel The channel's current 0..1 value. + * @param Function onChannel Called with the new 0..1 channel value on each slider frame. + * @param Function onCommit Called once when the slider gesture ends. + */ +@Composable +private fun ColorChannelSlider(label: String, channel: Float, onChannel: (Float) -> Unit, onCommit: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + Row(verticalAlignment = Alignment.CenterVertically) { + Text(text = label, style = typography.labelSmall, color = colors.textMuted, modifier = Modifier.width(12.dp)) + Slider( + value = channel * 255f, + onValueChange = { raw -> onChannel((raw / 255f).coerceIn(0f, 1f)) }, + modifier = Modifier.weight(1f), + onValueChangeFinished = onCommit, + valueRange = 0f..255f, + ) + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = (channel * 255f).roundToInt().toString(), + style = typography.labelSmall, + color = colors.text, + textAlign = TextAlign.End, + modifier = Modifier.width(28.dp), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/InlineEditController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/InlineEditController.kt new file mode 100644 index 0000000..41d6c20 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/InlineEditController.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.kit + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * A coordination seam between a transient inline text editor (today: renaming a workspace tab) and a + * host that runs its own keyboard dispatch. A bare text field cannot defend itself here: the editor + * lives inside the editor shell, whose root key handler previews every keystroke before the focused + * field sees it, so the shell would claim Space (palette), letters (file commands), and Escape while the + * user is merely typing a name. While an editor is open it parks its cancel callback here; the host + * checks this first and, finding it non-null, routes Escape to the cancel and lets every other key fall + * through to the field instead of running its own shortcuts. Holds null whenever no inline editor is + * open. Only the editor should write it. + * + * The same seam answers the other question a host has about text entry: whether the press it is + * watching landed on the editor itself. A press anywhere else ends text entry (the shell hands the + * keyboard back to its root), and only the editor's own node can say that the press was meant for it. + * + * @property Function cancel Cancels the open inline editor, or null when none is open. + * @property Boolean pressLandedOnTextEditor Whether the press being dispatched hit a text editor. + */ +class InlineEditController { + var cancel: (() -> Unit)? by mutableStateOf(null) + + /** + * Whether the press currently being dispatched landed on a live text editor's own node. The host + * clears this on the press's Initial pass (an ancestor sees that pass before any descendant), each + * text editor sets it on its own Initial pass, and the host reads it on the Final pass, after every + * descendant has handled the press. One synchronous dispatch on one thread, so the flag never has to + * tell one press from the next and needs no token. + * + * A plain var, deliberately, where [cancel] is snapshot state: nothing displays this, and making it + * observable would recompose the whole shell twice on every mouse press. + */ + var pressLandedOnTextEditor: Boolean = false +} + +/** + * Supplies the [InlineEditController] a host shares with the inline editors nested under it. Defaults to + * a standalone instance so an editor used without a coordinating host still functions (it falls back to + * its own focus-loss commit and to the field's own key handling). + */ +val LocalInlineEditController = staticCompositionLocalOf { InlineEditController() } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/InlineRenameField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/InlineRenameField.kt new file mode 100644 index 0000000..eee2559 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/InlineRenameField.kt @@ -0,0 +1,132 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.TextFieldValue + +/** + * A single-line inline rename text field, the shared core behind every in-place rename in the editor + * (the workspace tab and the outliner row). The whole name starts selected so typing replaces it; it + * commits on Enter or when focus leaves (clicking away), and cancels on Escape. Escape is routed in by + * the host through [LocalInlineEditController], because the editor shell's root key handler previews + * Escape (and every shortcut) before this field could see it. A blank name commits as a cancel, so the + * entity keeps its old name. The caller supplies the surrounding styling (a tab fill, a tree row); this + * owns only the field and its commit/cancel lifecycle. + * + * 共通のインライン名前編集フィールド(タブとアウトライナーで再利用)。Enter/フォーカス喪失で確定、 + * Escape で取消(シェル経由)。空名は取消扱い。装飾は呼び出し側が与える。 + * + * @param String initialName The current name, pre-selected for replacement. + * @param TextStyle textStyle The text style (the caller supplies the color to match its context). + * @param Color cursorColor The text-cursor color. + * @param Function onCommit Called with the trimmed new name when the edit is confirmed (never blank). + * @param Function onCancel Called when the edit is abandoned (Escape or a blank name). + * @param Modifier modifier The layout modifier for the field. + */ +@Composable +fun InlineRenameField( + initialName: String, + textStyle: TextStyle, + cursorColor: Color, + onCommit: (String) -> Unit, + onCancel: () -> Unit, + modifier: Modifier = Modifier, +) { + val controller = LocalInlineEditController.current + val focusRequester = remember { FocusRequester() } + var fieldValue by remember { + mutableStateOf(TextFieldValue(initialName, selection = TextRange(0, initialName.length))) + } + // Guards against resolving twice: e.g. Enter commits, then the editor's disposal fires onFocusChanged, + // which would otherwise commit again. + var resolved by remember { mutableStateOf(false) } + var hasFocused by remember { mutableStateOf(false) } + + fun commit() { + if (resolved) { + return + } + resolved = true + val trimmed = fieldValue.text.trim() + if (trimmed.isEmpty()) { + onCancel() + } else { + onCommit(trimmed) + } + } + + fun cancel() { + if (resolved) { + return + } + resolved = true + onCancel() + } + + // While mounted, lend the shell this editor's cancel so it can route Escape here (it intercepts Escape + // before the field would receive it); clear the hook on dispose. + DisposableEffect(Unit) { + controller.cancel = { cancel() } + onDispose { controller.cancel = null } + } + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + + BasicTextField( + value = fieldValue, + onValueChange = { newValue -> fieldValue = newValue }, + singleLine = true, + textStyle = textStyle, + cursorBrush = SolidColor(cursorColor), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { commit() }), + modifier = + modifier + .textEntrySurface(controller) + .focusRequester(focusRequester) + .onFocusChanged { focusState -> + // hasFocus, not isFocused: BasicTextField focuses an internal child node, so this node is + // never itself focused - only its subtree is. isFocused would never fire, and the click-away + // commit below would never run. + if (focusState.hasFocus) { + hasFocused = true + } else if (hasFocused) { + // Clicking away commits, mirroring renaming a file in an explorer. + commit() + } + } + .onKeyEvent { event -> + // Hardware Enter confirms (the soft-keyboard Done action is wired above). Escape is left for + // the shell to route into cancel(), so it is deliberately not handled here. + if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) { + commit() + true + } else { + false + } + }, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Inputs.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Inputs.kt new file mode 100644 index 0000000..82241be --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Inputs.kt @@ -0,0 +1,207 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import org.umamo.ui.model.KeyedFieldState +import org.umamo.ui.model.tint +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A compact checkbox row: a small box (accent-filled with a checkmark when on, neutral when off) plus a + * label, the whole row toggling [onCheckedChange]. A disabled row ignores clicks and dims - it still + * shows its stored state, so a setting gated behind another one reads as "remembered but inert". + * + * @param Boolean checked Current state. + * @param Function onCheckedChange Toggle callback. + * @param String label The row label. + * @param KeyedFieldState keyState The keyform state to tint the box's border with. + * @param Boolean enabled Whether the row accepts clicks; false renders it dimmed. + */ +@Composable +fun Checkbox( + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + label: String, + keyState: KeyedFieldState = KeyedFieldState.None, + enabled: Boolean = true, +) { + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val boxFill = + when { + checked && enabled -> colors.accent + checked -> colors.controlBorder + else -> colors.controlBackground + } + // The keyed tint replaces the box's ordinary border, the way HexColorField does it - a checkbox is + // small enough that a second mark beside it would be the louder signal, not the quieter one. + val boxBorder = keyState.tint(colors) ?: colors.controlBorder + val checkColor = colors.accentText + val labelColor = if (enabled) colors.text else colors.textDisabled + Row( + modifier = + Modifier + .fillMaxWidth() + .height(22.dp) + // NOT focusable, like SectionHeader: a toggle in transient chrome (the operation settings + // strip) would otherwise carry focus out of the composition with it and strand the keyboard. + .focusProperties { canFocus = false } + .clickable( + interactionSource = interaction, + indication = null, + enabled = enabled, + onClick = { onCheckedChange(!checked) }, + ) + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Canvas(modifier = Modifier.size(13.dp)) { + val radius = CornerRadius(2.dp.toPx()) + drawRoundRect(color = boxFill, cornerRadius = radius) + drawRoundRect(color = boxBorder, cornerRadius = radius, style = Stroke(1.dp.toPx())) + if (checked) { + val tick = Path() + tick.moveTo(size.width * 0.22f, size.height * 0.52f) + tick.lineTo(size.width * 0.42f, size.height * 0.72f) + tick.lineTo(size.width * 0.78f, size.height * 0.28f) + drawPath(tick, color = checkColor, style = Stroke(1.6.dp.toPx())) + } + } + Spacer(modifier = Modifier.width(6.dp)) + Text(text = label, style = LocalUmamoTypography.current.labelMedium, color = labelColor) + } +} + +/** + * A compact bordered text field wrapping Foundation's [BasicTextField] (which already handles cursor, + * selection, and IME). Single line, tight padding. When [placeholder] is set it shows as dimmed hint + * text while the field is empty. + * + * Like [NumberField], it lends a cancel hook to [LocalInlineEditController] while focused so the editor + * shell's root key handler stops claiming keystrokes the field needs - notably Space (which otherwise + * opens the command palette) and letter shortcuts - and routes Escape here (clearing focus) instead. + * + * @param String value The current text. + * @param Function onValueChange Edit callback. + * @param Modifier modifier Layout modifier. + * @param String? placeholder Optional dimmed hint shown while the field is empty. + * @param Function? trailing Optional control pinned inside the field's trailing edge (a clear + * affordance, a unit label). It takes its width out of the text's, so it never overlaps the value. + */ +@Composable +fun TextField( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + placeholder: String? = null, + trailing: (@Composable () -> Unit)? = null, +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val controller = LocalInlineEditController.current + val focusManager = LocalFocusManager.current + var focused by remember { mutableStateOf(false) } + // Held as a TextFieldValue purely so the context menu can act on a selection; the public API stays + // String-shaped, and the caret is re-pinned to the end whenever the caller replaces the text out from + // under the field (a cleared search box, a reset). + var fieldValue by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) } + if (fieldValue.text != value) { + fieldValue = TextFieldValue(value, TextRange(value.length)) + } + // Park the cancel hook only while focused; the shell checks it to yield Space / letters to the field + // and to route Escape (clear focus) here. Drop it on focus loss and on dispose-while-focused. + DisposableEffect(Unit) { + onDispose { + if (focused) { + controller.cancel = null + } + } + } + val applyEdit: (TextFieldValue) -> Unit = { edited -> + fieldValue = edited + if (edited.text != value) { + onValueChange(edited.text) + } + } + TextEditContextMenuArea(value = fieldValue, onValueChange = applyEdit) { gesture -> + BasicTextField( + value = fieldValue, + onValueChange = applyEdit, + textStyle = LocalUmamoTypography.current.bodySmall.copy(color = colors.text), + singleLine = true, + cursorBrush = SolidColor(colors.text), + modifier = + gesture + .then(modifier) + .textEntrySurface(controller) + .clip(shapes.small) + .background(colors.controlBackground) + .border(1.dp, colors.controlBorder, shapes.small) + .padding(horizontal = 6.dp, vertical = 4.dp) + .onFocusChanged { focusState -> + // hasFocus (not isFocused): BasicTextField focuses an internal child, so this node only + // ever sees its subtree's focus. + if (focusState.hasFocus) { + if (!focused) { + focused = true + controller.cancel = { focusManager.clearFocus() } + } + } else if (focused) { + focused = false + controller.cancel = null + } + }, + decorationBox = { innerTextField -> + Row(verticalAlignment = Alignment.CenterVertically) { + // The weighted box IS the text viewport - BasicTextField scrolls the caret into THIS box - so + // a trailing control takes its width out of the text's rather than sitting on top of it. An + // overlaid control would hide the caret exactly when the value outgrows the field. + Box(modifier = Modifier.weight(1f)) { + // Overlay the placeholder behind the field's own text so it disappears as soon as the user types. + if (placeholder != null && value.isEmpty()) { + Text(text = placeholder, style = LocalUmamoTypography.current.bodySmall, color = colors.textMuted) + } + innerTextField() + } + if (trailing != null) { + Spacer(modifier = Modifier.width(4.dp)) + trailing() + } + } + }, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/KeyCaptureController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/KeyCaptureController.kt new file mode 100644 index 0000000..5ecdce8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/KeyCaptureController.kt @@ -0,0 +1,45 @@ +package org.umamo.ui.kit + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * A coordination seam between a control that is capturing the next key press (the keybindings editor's chord + * chip) and a host that runs its own keyboard dispatch. + * + * The host's root key handler previews every key before the focused control sees it, so a capture cannot defend + * itself: the host would take Escape for whatever overlay the control sits in and close it, where the control + * means Escape to cancel the capture alone. This is narrower than [InlineEditController] on purpose. A text + * field inside an overlay gives Escape to the overlay, which is what a rigger expects of a dialog; a capture is + * an armed state that owns the WHOLE keyboard - any key may be the one being bound - so while one is live the + * host stands aside entirely and the control's own handler decides every key, Escape included. + * + * A count rather than a flag: one control can end its capture in the same pass another begins, and the order + * of those two must not leave the host thinking nothing is capturing. + */ +class KeyCaptureController { + private var liveCaptures by mutableIntStateOf(0) + + /** Whether a control is capturing key presses now. */ + val active: Boolean + get() = liveCaptures > 0 + + /** Marks a capture as begun; pair every call with one [end]. */ + fun begin() { + liveCaptures++ + } + + /** Marks a capture as over, whether it bound a key or was cancelled. */ + fun end() { + liveCaptures = (liveCaptures - 1).coerceAtLeast(0) + } +} + +/** + * Supplies the [KeyCaptureController] a host shares with the capturing controls nested under it. Defaults to a + * standalone instance, so a control used without a coordinating host still works - with no host previewing keys + * there is nobody to stand aside. + */ +val LocalKeyCapture = staticCompositionLocalOf { KeyCaptureController() } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Menu.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Menu.kt new file mode 100644 index 0000000..f243c96 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Menu.kt @@ -0,0 +1,539 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties +import kotlinx.coroutines.delay +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.search_hint +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.drawIcon +import kotlin.math.max + +/** How long the pointer may be off both a submenu row and its flyout before the flyout closes. */ +private const val SUBMENU_CLOSE_GRACE_MS = 180L + +/** The guaranteed gap between a row's label and its trailing shortcut or submenu arrow. */ +private val ROW_TRAILING_GAP = 24.dp + +/** Edge length of a row's leading icon, matching the kit's other 16.dp Canvas icons. */ +private val MENU_ICON_SIZE = 16.dp + +/** + * The breathing room kept between a menu and the window edge. A menu grows to the window minus this and + * only then scrolls, so a long-but-fitting list (the blend modes) shows in full rather than being cut off. + */ +private val MENU_WINDOW_MARGIN = 16.dp + +/** The shortest a menu is ever capped to, so a tiny window still shows a usable strip of rows. */ +private val MENU_MIN_HEIGHT = 96.dp + +/** The cap used when a menu is measured unbounded (no window height to subtract from). */ +private val MENU_FALLBACK_MAX_HEIGHT = 360.dp + +/** The inset a pinned search box keeps from the menu's edges, matching the rows' own. */ +private val MENU_SEARCH_INSET = 8.dp + +/** The gap between a row's leading icon (or its reserved slot) and the label. */ +private val MENU_ICON_LABEL_GAP = 8.dp + +/** + * True while composing inside a popup that already owns the outside-click and Esc dismiss. Only one + * popup in a tree may be focusable, so a popup opened from inside another one must not take focus and + * fight it for the dismiss - the inner press would otherwise read as "outside" to the outer popup, which + * would tear the inner one down mid-click. Popups that host arbitrary caller content (the overflow + * dropdown, a filter panel) provide this so the menus and chips inside them yield automatically. + */ +val LocalPopupDismissOwned = compositionLocalOf { false } + +/** + * Notifies an ancestor submenu whether this branch still wants the parent flyout kept open. Each + * submenu flyout is its own [Popup] window, so hovering a grandchild does not count as hovering the + * parent's hoverable box - without this bridge a third-level flyout closes the parent after the grace + * and tears itself down. Null at the root (nothing to notify). + */ +private val LocalSubmenuKeepOpen = compositionLocalOf<((Boolean) -> Unit)?> { null } + +/** + * A popup menu rendered from a [MenuItem] list - the one menu surface used across the menu bar, context + * menus, and the area type selector. Styled to the kit's menu look: medium rounded corners, the dark + * panel fill, no border, and no drop shadow. Hosted in a [Popup] so it escapes its parent's bounds, + * positioned by [positionProvider]; a focusable root dismisses on an outside click or Esc via + * [onDismissRequest]. Renders [MenuItem.Submenu] entries as nested flyouts that open on hover (desktop) + * or tap (touch). + * + * @param List items The entries to render. + * @param Function onDismissRequest Called to close the whole menu tree (outside click / Esc / selection). + * @param PopupPositionProvider positionProvider Where the popup is placed relative to its anchor. + * @param Modifier modifier Modifier for the menu's content column. + * @param Boolean focusable Whether this popup owns focus and the dismiss - true for a root menu, false + * for a nested submenu flyout (only one popup in the tree may be focusable, or they fight over focus). + * Defaults to yielding whenever an enclosing popup already owns it (see [LocalPopupDismissOwned]). + */ +@Composable +fun Menu( + items: List, + onDismissRequest: () -> Unit, + positionProvider: PopupPositionProvider, + modifier: Modifier = Modifier, + focusable: Boolean = !LocalPopupDismissOwned.current, +) { + Popup( + popupPositionProvider = positionProvider, + onDismissRequest = onDismissRequest, + properties = PopupProperties(focusable = focusable), + ) { + MenuPanel(items = items, dismissRoot = onDismissRequest, modifier = modifier) + } +} + +/** + * The styled column of rows inside a [Menu]'s popup. Tracks which submenu (if any) is currently open so + * exactly one flyout shows per level; [dismissRoot] is threaded down so selecting a leaf anywhere in the + * tree tears the whole menu down. When any action row in this panel carries an icon, every row reserves + * the icon slot so all labels share one column (Blender-style); each flyout is its own panel, so the + * decision never leaks across nesting levels. + * + * A [MenuItem.Search] pins above the scrolling rows and fixes the panel to its width; without one the + * panel hugs its widest row. + * + * @param List items The entries to render. + * @param Function dismissRoot Closes the entire menu tree. + * @param Modifier modifier Modifier for the column. + */ +@Composable +private fun MenuPanel(items: List, dismissRoot: () -> Unit, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + val density = LocalDensity.current + var openSubmenuIndex by remember { mutableStateOf(null) } + val searches = items.filterIsInstance() + val rows = items.filter { menuEntry -> menuEntry !is MenuItem.Search } + val fixedWidth = searches.firstOrNull()?.width + // A search menu caps its rows well under the window: a picker over a whole layer inventory would + // otherwise stand as tall as the window, fit neither below nor above its chip, and open clamped to + // the window's bottom edge - far from the chip - until a search shrank it back under the anchor. + val searchRowsCap = searches.firstOrNull()?.maxRowsHeight + val reserveIconSlot = rows.any { menuEntry -> menuEntry is MenuItem.Action && menuEntry.icon != null } + val scrollState = rememberScrollState() + // The pinned search's height, measured, so the row cap below leaves room for it: the rows' box is + // still measured against the window height, not the height left under the search. + var pinnedHeight by remember { mutableStateOf(0.dp) } + Surface(color = colors.menuBackground, shape = LocalUmamoShapes.current.medium) { + Column(modifier = if (fixedWidth != null) Modifier.width(fixedWidth) else Modifier) { + if (searches.isNotEmpty()) { + Column(modifier = Modifier.onSizeChanged { size -> pinnedHeight = with(density) { size.height.toDp() } }) { + for (search in searches) { + MenuSearchRow(search) + } + } + } + // A popup is measured against the window, so its incoming max height IS the window height: cap the + // rows to that minus a margin and only then scroll. A long-but-fitting menu (the blend modes) shows + // in full instead of being cut off at an arbitrary constant. + BoxWithConstraints { + val available = this@BoxWithConstraints.maxHeight + val windowCap = + if (available == Dp.Infinity) { + MENU_FALLBACK_MAX_HEIGHT + } else { + (available - MENU_WINDOW_MARGIN - pinnedHeight).coerceAtLeast(MENU_MIN_HEIGHT) + } + val rowCap = if (searchRowsCap != null && searchRowsCap < windowCap) searchRowsCap else windowCap + Box { + // The cap and the scroll ride on an OUTER column so the row column below keeps measuring its + // IntrinsicSize.Max width exactly as before - intrinsics are asked of that node, never + // through the scrolling one. Under a search the width is the search's, and the rows fill it. + Column(modifier = Modifier.heightIn(max = rowCap).verticalScroll(scrollState)) { + val rowColumnWidth = if (fixedWidth != null) Modifier.fillMaxWidth() else Modifier.width(IntrinsicSize.Max) + Column(modifier = modifier.then(rowColumnWidth).padding(vertical = 2.dp)) { + rows.forEachIndexed { index, item -> + when (item) { + is MenuItem.Action -> + MenuActionRow( + item = item, + reserveIconSlot = reserveIconSlot, + onClick = { + item.onSelect() + dismissRoot() + }, + ) + + is MenuItem.Separator -> MenuSeparatorRow() + is MenuItem.Heading -> MenuHeadingRow(item) + is MenuItem.Submenu -> + MenuSubmenuRow( + item = item, + reserveIconSlot = reserveIconSlot, + expanded = openSubmenuIndex == index, + onRequestOpen = { openSubmenuIndex = index }, + onRequestClose = { + if (openSubmenuIndex == index) { + openSubmenuIndex = null + } + }, + dismissRoot = dismissRoot, + ) + + is MenuItem.Search -> Unit + } + } + } + } + // matchParentSize keeps the scrollbar a pure overlay: it fills its own box rather than the + // popup's window-sized constraints, so it can no longer inflate the menu to full height. + Box(modifier = Modifier.matchParentSize()) { + VerticalScrollbarOverlay(scrollState) + } + } + } + } + } +} + +/** + * The pinned search box: the kit [SearchField] at the panel's width less the row inset, focused as + * soon as it composes so the menu opens ready to type into. Esc and a pick dismiss the menu as ever - + * the popup owns both - and Compose hands focus back to whatever held it before the popup opened. + * + * @param MenuItem.Search item The search entry. + */ +@Composable +private fun MenuSearchRow(item: MenuItem.Search) { + val focusRequester = remember { FocusRequester() } + SearchField( + value = item.value, + onValueChange = item.onValueChange, + modifier = Modifier.padding(horizontal = MENU_SEARCH_INSET, vertical = 6.dp).focusRequester(focusRequester), + width = item.width - MENU_SEARCH_INSET * 2, + placeholder = item.placeholder ?: stringResource(Res.string.search_hint), + ) + LaunchedEffect(focusRequester) { + focusRequester.requestFocus() + } +} + +/** + * A section heading: the same muted caption a filter panel heads its groups with, so a menu's file + * names and a panel's section titles read as one thing. Inert, and outside the icon column. + * + * @param MenuItem.Heading item The heading entry. + */ +@Composable +private fun MenuHeadingRow(item: MenuItem.Heading) { + FilterSectionLabel(text = item.label) +} + +/** + * One selectable menu row: an optional leading icon, the label, an optional shortcut hint right-aligned. + * A disabled row is dimmed (icon included) and neither hovers nor clicks. An icon-less row in a panel + * that reserves the slot indents its label to the shared column. + * + * @param MenuItem.Action item The row to render. + * @param Boolean reserveIconSlot Whether icon-less rows indent to the panel's shared label column. + * @param Function onClick Invoked when an enabled row is chosen. + */ +@Composable +private fun MenuActionRow(item: MenuItem.Action, reserveIconSlot: Boolean, onClick: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val rowModifier = + if (item.enabled) { + Modifier.clickable(interactionSource = interaction, indication = null, onClick = onClick) + } else { + Modifier + } + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp, vertical = 1.dp) + .then(rowModifier) + .background( + when { + hovered && item.enabled -> colors.rowHover + else -> Color.Transparent + }, + shape = LocalUmamoShapes.current.small, + ) + .padding(horizontal = 4.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (item.icon != null) { + val iconTint = if (item.enabled) colors.text else colors.textMuted + Canvas(modifier = Modifier.size(MENU_ICON_SIZE)) { + drawIcon(item.icon, iconTint) + } + Spacer(modifier = Modifier.width(MENU_ICON_LABEL_GAP)) + } else if (reserveIconSlot) { + Spacer(modifier = Modifier.width(MENU_ICON_SIZE + MENU_ICON_LABEL_GAP)) + } + // One line, ellipsized, and the row's slack is the label's: a fixed-width menu (one with a search + // box) must never wrap a long layer name, and the shortcut stays at the row's end. A hugging menu + // is as wide as its widest row, so nothing changes there. + Text( + text = item.label, + style = typography.labelMedium, + color = if (item.enabled) colors.text else colors.textMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (item.shortcut != null) { + Spacer(modifier = Modifier.width(ROW_TRAILING_GAP)) + Text(text = item.shortcut, style = typography.labelSmall, color = colors.textMuted) + } + } +} + +/** A separator rule between groups of rows, inset so it does not touch the menu's rounded corners. */ +@Composable +private fun MenuSeparatorRow() { + val colors = LocalUmamoColors.current + Divider(modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), color = colors.guideLine) +} + +/** + * A submenu row: label, a trailing arrow, and a nested flyout that opens to its right. On desktop the + * flyout opens on hover and closes after a short grace once the pointer leaves the row, the flyout, and + * every nested descendant flyout (so a diagonal move across the gap does not snap it shut, and a + * third-level flyout does not tear its parent down - each flyout is its own popup window, so grandchild + * hover is reported up via [LocalSubmenuKeepOpen]); on a touch screen, with no hover, tapping the row + * toggles it. The flyout popup is non-focusable so the focusable root menu stays the sole owner of the + * outside-click / Esc dismiss for the whole tree. + * + * @param MenuItem.Submenu item The submenu row. + * @param Boolean reserveIconSlot Whether this row indents its label to the panel's shared label column. + * @param Boolean expanded Whether this row's flyout is currently shown. + * @param Function onRequestOpen Asks the panel to open this row's flyout (closing any sibling's). + * @param Function onRequestClose Asks the panel to close this row's flyout. + * @param Function dismissRoot Closes the entire menu tree (forwarded to the flyout). + */ +@Composable +private fun MenuSubmenuRow( + item: MenuItem.Submenu, + reserveIconSlot: Boolean, + expanded: Boolean, + onRequestOpen: () -> Unit, + onRequestClose: () -> Unit, + dismissRoot: () -> Unit, +) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val rowInteraction = remember { MutableInteractionSource() } + val rowHovered by rowInteraction.collectIsHoveredAsState() + val flyoutInteraction = remember { MutableInteractionSource() } + val flyoutHovered by flyoutInteraction.collectIsHoveredAsState() + // A nested flyout is a separate Popup, so its hover never reaches [flyoutHovered]; descendants report + // through LocalSubmenuKeepOpen so this row stays open while the pointer is in a grandchild. + var descendantKeepOpen by remember { mutableStateOf(false) } + val reportKeepOpenToParent = LocalSubmenuKeepOpen.current + val keepOpen = rowHovered || flyoutHovered || descendantKeepOpen + + // Open on hover (desktop only - touch never reports hover, so the row's clickable carries that there). + LaunchedEffect(rowHovered) { + if (rowHovered && item.enabled) { + onRequestOpen() + } + } + // Tell the ancestor whether this branch still wants it open (row, own flyout, or a nested flyout). + LaunchedEffect(keepOpen) { + reportKeepOpenToParent?.invoke(keepOpen) + } + DisposableEffect(reportKeepOpenToParent) { + onDispose { reportKeepOpenToParent?.invoke(false) } + } + LaunchedEffect(expanded) { + if (!expanded) { + descendantKeepOpen = false + } + } + // Close after a grace once neither the row, the flyout, nor any nested descendant is hovered, + // re-checking after the delay so a diagonal move across the gap (or into a grandchild) keeps it open. + LaunchedEffect(rowHovered, flyoutHovered, descendantKeepOpen) { + if (!rowHovered && !flyoutHovered && !descendantKeepOpen) { + delay(SUBMENU_CLOSE_GRACE_MS) + if (!rowHovered && !flyoutHovered && !descendantKeepOpen) { + onRequestClose() + } + } + } + + // clickable feeds hover into rowInteraction (so rowHovered tracks the desktop pointer) and toggles the + // flyout on tap (the touch path, where hover never fires). + val rowModifier = + if (item.enabled) { + Modifier.clickable(indication = null, interactionSource = rowInteraction) { + if (expanded) { + onRequestClose() + } else { + onRequestOpen() + } + } + } else { + Modifier + } + Box { + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp, vertical = 1.dp) + .then(rowModifier) + .background( + when { + ((rowHovered || expanded) && item.enabled) -> colors.rowHover + else -> Color.Transparent + }, + shape = LocalUmamoShapes.current.small, + ) + .padding(horizontal = 4.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (reserveIconSlot) { + Spacer(modifier = Modifier.width(MENU_ICON_SIZE + MENU_ICON_LABEL_GAP)) + } + Text( + text = item.label, + style = typography.labelMedium, + color = if (item.enabled) colors.text else colors.textMuted, + ) + Spacer(modifier = Modifier.weight(1f)) + Spacer(modifier = Modifier.width(ROW_TRAILING_GAP)) + Text(text = "▸", style = typography.labelMedium, color = colors.textMuted) + } + if (expanded) { + Popup( + popupPositionProvider = SubmenuPositionProvider, + onDismissRequest = dismissRoot, + properties = PopupProperties(focusable = false), + ) { + // Descendants call this so hovering a nested flyout counts as keeping THIS flyout open. + CompositionLocalProvider( + LocalSubmenuKeepOpen provides { active -> descendantKeepOpen = active }, + ) { + Box(modifier = Modifier.hoverable(flyoutInteraction)) { + MenuPanel(items = item.items, dismissRoot = dismissRoot) + } + } + } + } + } +} + +/** + * Positions a popup at its anchor's bottom-left - a menu dropping straight down from its trigger (the + * menu-bar label or the area type selector) - kept on screen: the left edge is clamped into the window, + * and a menu that would overflow the bottom flips ABOVE its anchor instead, falling back to a clamped + * position when it fits neither way (a menu taller than the window then starts at the top edge and + * scrolls). Without this a long dropdown simply ran off the bottom and its tail was unreachable. + */ +internal object BelowAnchorPositionProvider : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val left = anchorBounds.left.coerceIn(0, max(0, windowSize.width - popupContentSize.width)) + val fitsBelow = anchorBounds.bottom + popupContentSize.height <= windowSize.height + val above = anchorBounds.top - popupContentSize.height + val top = + when { + fitsBelow -> anchorBounds.bottom + above >= 0 -> above + else -> windowSize.height - popupContentSize.height + } + return IntOffset(left, top.coerceIn(0, max(0, windowSize.height - popupContentSize.height))) + } +} + +/** + * Positions a submenu flyout flush to the right of its parent row, aligned with the row's top, flipping + * to the row's left when a right-side flyout would overflow the window, and clamping the top so a tall + * flyout near the window bottom stays on screen. + */ +private object SubmenuPositionProvider : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val fitsRight = anchorBounds.right + popupContentSize.width <= windowSize.width + val left = + if (fitsRight) { + anchorBounds.right + } else { + max(0, anchorBounds.left - popupContentSize.width) + } + val top = anchorBounds.top.coerceIn(0, max(0, windowSize.height - popupContentSize.height)) + return IntOffset(left, top) + } +} + +/** + * Positions a popup at a point [localOffset] inside its anchor (the context-menu host), so the menu opens + * at the cursor. The point is offset by the anchor's window origin and then clamped to keep the whole + * menu on screen. + * + * @property IntOffset localOffset The cursor point relative to the anchor's top-left. + */ +internal class AtPointPositionProvider(private val localOffset: IntOffset) : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val x = (anchorBounds.left + localOffset.x).coerceIn(0, max(0, windowSize.width - popupContentSize.width)) + val y = (anchorBounds.top + localOffset.y).coerceIn(0, max(0, windowSize.height - popupContentSize.height)) + return IntOffset(x, y) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MenuBar.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MenuBar.kt new file mode 100644 index 0000000..b6e7bb9 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MenuBar.kt @@ -0,0 +1,193 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A tiny coordination seam between a [MenuBar] and a host that runs its own keyboard dispatch. While a + * menu-bar menu is open the bar parks a close callback here; a host whose key handler would otherwise + * claim Escape first (the editor shell's root onPreviewKeyEvent, where Escape is bound to a command) + * pulls this and dismisses the menu before its own shortcut for that key fires. Holds null whenever no + * menu-bar menu is open. Only a [MenuBar] should write it. + * + * MenuBar とホスト側のキー処理をつなぐ小さな仲介。メニューが開いている間だけ閉じる関数を預ける。 + * + * @property Function closeOpenMenu Closes the currently open menu, or null when none is open. + */ +class MenuBarController { + var closeOpenMenu: (() -> Unit)? by mutableStateOf(null) +} + +/** + * Supplies the [MenuBarController] a host shares with its [MenuBar]. Defaults to a standalone instance + * so a bar used without a coordinating host still works: it falls back to its own focus-based Escape + * handling and to pointer dismissal (outside click / selection). + */ +val LocalMenuBarController = staticCompositionLocalOf { MenuBarController() } + +/** + * A horizontal strip of top-level menu labels (File, Help, …), each opening its [TopLevelMenu] as a + * [Menu] dropped beneath it. Clicking a label toggles its menu; while any menu is open, hovering a + * different label switches to it (the standard menu-bar behavior), so a user can sweep across the bar + * without re-clicking. Built from kit [Menu]s, so it shares the menu look and works on desktop and + * tablet alike - an in-window bar rather than a host-OS menu strip. + * + * The dropdowns open non-focusable so the host window keeps focus while a menu is open - a focusable + * popup steals focus and the labels (which live in that now-unfocused window) stop receiving hover, so + * the sweep-to-switch would silently never fire. That trade-off moves the keyboard dismiss onto the bar + * itself: opening a menu pulls focus to the bar and Escape closes it (a host with its own key dispatch + * coordinates through [LocalMenuBarController] instead); pointer dismissal (outside click / selection) + * works regardless. + * + * 最上位メニューラベルの横帯。クリックで開閉、開いている間は他ラベルへのホバーで切り替わる。 + * ドロップダウンは非フォーカスで開き(フォーカスを奪うとラベルのホバーが効かなくなるため)、Esc は + * バー自身が処理する。 + * + * @param List menus The top-level menus in bar order. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun MenuBar(menus: List, modifier: Modifier = Modifier) { + var openIndex by remember { mutableStateOf(null) } + val focusRequester = remember { FocusRequester() } + val closeMenu = remember { { openIndex = null } } + val controller = LocalMenuBarController.current + + // Opening a menu pulls keyboard focus to the bar so Escape can dismiss it: the dropdowns are + // non-focusable (keeping the window focused so the labels keep receiving hover for the sweep below), + // which leaves the bar itself to own the keyboard dismiss. Keyed on the open/closed transition, not + // the index, so sweeping between menus does not re-request focus on every label change. + LaunchedEffect(openIndex != null) { + if (openIndex != null) { + focusRequester.requestFocus() + } + } + // While open, park the close callback on the shared controller so a host that dispatches keys ahead + // of this bar (the editor shell claims Escape at its root before it ever reaches here) can dismiss + // the menu first. Cleared on close and on disposal so a stale closer never lingers. + DisposableEffect(openIndex, controller) { + controller.closeOpenMenu = if (openIndex == null) null else closeMenu + onDispose { controller.closeOpenMenu = null } + } + + Row( + modifier = + modifier + .focusRequester(focusRequester) + .focusable() + .onPreviewKeyEvent { keyEvent -> + if (openIndex != null && keyEvent.type == KeyEventType.KeyDown && keyEvent.key == Key.Escape) { + closeMenu() + true + } else { + false + } + }, + verticalAlignment = Alignment.CenterVertically, + ) { + menus.forEachIndexed { index, menu -> + MenuBarLabel( + menu = menu, + menuOpen = openIndex == index, + anyMenuOpen = openIndex != null, + onToggle = { openIndex = if (openIndex == index) null else index }, + onHoverSwitch = { openIndex = index }, + onDismiss = closeMenu, + ) + } + } +} + +/** + * One menu-bar label and the [Menu] it anchors. The popup is a child of this label's [Box], so Compose + * hands the label's bounds to the below-anchor position provider and the menu drops under the label with + * no manual coordinate capture. While a menu is already open elsewhere on the bar, hovering this label + * switches the open menu to it. + * + * メニューバーの 1 ラベルとそれが開くメニュー。ポップアップはラベルの子なので真下に開く。 + * + * @param TopLevelMenu menu The menu this label opens. + * @param Boolean menuOpen Whether this label's menu is currently open. + * @param Boolean anyMenuOpen Whether some label on the bar is open (enables hover-to-switch). + * @param Function onToggle Toggles this label's menu open/closed (on click). + * @param Function onHoverSwitch Switches the open menu to this label (on hover while another is open). + * @param Function onDismiss Closes the open menu (outside click / Esc / selection). + */ +@Composable +private fun MenuBarLabel( + menu: TopLevelMenu, + menuOpen: Boolean, + anyMenuOpen: Boolean, + onToggle: () -> Unit, + onHoverSwitch: () -> Unit, + onDismiss: () -> Unit, +) { + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + // Sweeping the bar: once one menu is open, moving the pointer over another label opens that one. + LaunchedEffect(hovered) { + if (hovered && anyMenuOpen && !menuOpen) { + onHoverSwitch() + } + } + Box { + Row( + modifier = + Modifier + .clickable(interactionSource = interaction, indication = null, onClick = onToggle) + .background( + color = if (menuOpen || hovered) colors.accent else Color.Transparent, + shape = LocalUmamoShapes.current.medium, + ) + .padding(horizontal = 10.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = menu.label, + style = LocalUmamoTypography.current.labelMedium, + color = if (menuOpen || hovered) colors.accentText else colors.text, + ) + } + if (menuOpen) { + // Non-focusable so the host window keeps focus and the bar keeps receiving hover (the + // sweep-to-switch above): a focusable popup would starve the labels of hover events. The + // keyboard dismiss is owned by the bar / its host instead; outside-click dismissal still + // routes through onDismissRequest regardless of focusability. + Menu( + items = menu.items, + onDismissRequest = onDismiss, + positionProvider = BelowAnchorPositionProvider, + focusable = false, + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MenuItem.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MenuItem.kt new file mode 100644 index 0000000..0803d4b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MenuItem.kt @@ -0,0 +1,123 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoIcon + +/** + * How tall a search menu's rows grow before they scroll, unless its [MenuItem.Search] says otherwise. + * A picker over a document's whole layer inventory would otherwise take the general rule - rows up to + * the window's height - and a menu that tall fits neither below nor above its chip, so the popup is + * clamped to the window's bottom edge and opens far from the chip until a search shrinks it. + */ +val MENU_SEARCH_ROWS_MAX_HEIGHT: Dp = 320.dp + +/** + * One entry in a [Menu]: a clickable action, a nested submenu, a separator, a section heading, or a + * search box. This is a data model, not a Compose slot DSL - a caller builds a List + * (resolving localized chrome via stringResource at the call site and passing user data such as file + * names verbatim) and one renderer draws every menu identically across the menu bar, context menus, + * the area type selector, and the searchable pickers. + * + * The label is a plain String rather than a StringResource because menus mix localized chrome ("Open") + * with user data (a recent-file name, a space title) that has no StringResource; the call site resolves + * the chrome and supplies the data. An [Action] carries an onSelect lambda rather than a command id + * because not every item is command-bound (the area selector emits an AreaCommand, a recent-file row + * calls open(path), Exit calls onExit); command binding layers on top via commandMenuItem(...). + * + * メニュー 1 項目。アクション・入れ子サブメニュー・区切りのいずれか。スロット DSL ではなくデータ。 + */ +sealed interface MenuItem { + /** + * A selectable row: an optional leading [icon], the [label], an optional [shortcut] accelerator + * right-aligned, running [onSelect] on click. A disabled row renders dimmed and neither hovers nor + * responds to a click. When any sibling row in the same panel carries an icon, icon-less rows indent + * their label to the same column so labels stay aligned. + * + * 選択可能な行。任意の先頭アイコン、ラベル、右に任意のショートカット、クリックで onSelect を実行する。 + * + * @property String label The display text (already-resolved chrome or user data). + * @property Function onSelect Invoked when the row is chosen. + * @property String? shortcut The right-aligned accelerator hint (e.g. "Ctrl+O"), or null for none. + * @property Boolean enabled Whether the row is interactive. + * @property UmamoIcon? icon The leading glyph, or null for a text-only row. + */ + data class Action( + val label: String, + val onSelect: () -> Unit, + val shortcut: String? = null, + val enabled: Boolean = true, + val icon: UmamoIcon? = null, + ) : MenuItem + + /** + * A row that opens a nested flyout of [items], marked with a trailing arrow. On desktop the flyout + * opens on hover; on a touch screen (no hover) it opens on tap. A disabled submenu cannot open. + * + * ホバー(デスクトップ)またはタップ(タッチ)で入れ子フライアウトを開く行。矢印付き。 + * + * @property String label The display text. + * @property List items The submenu entries. + * @property Boolean enabled Whether the submenu can be opened. + */ + data class Submenu( + val label: String, + val items: List, + val enabled: Boolean = true, + ) : MenuItem + + /** A horizontal rule separating groups of rows. */ + data object Separator : MenuItem + + /** + * A muted caption over the rows that follow it - a file name over its layers, a group's title over + * its entries. Inert: it neither hovers nor clicks nor dismisses, and it ignores the icon column the + * action rows share. One line, ellipsized, because a heading naming a document object (an artwork + * file) can be arbitrarily long and must not widen the menu the rows beneath it are sized for. + * + * @property String label The heading text. + */ + data class Heading( + val label: String, + ) : MenuItem + + /** + * A search box pinned above the rows, taking focus when the menu opens so typing starts at once. + * The menu does no filtering: the caller keeps the query, filters the rows it passes, and hands the + * query back here - the model stays a plain list, and the ranking rule (a name match, a whole file + * when the file name matches, the palette's ranker) stays where the data is. One per menu, listed + * first; the panel pins every Search item above the rows whatever its position. + * + * The menu takes [width] as its own, fixed: a search menu that re-hugged its widest surviving row + * would resize under the user's hands on every keystroke. Its rows scroll past [maxRowsHeight], a + * cap well under the window so the menu stays anchored under its chip however long the unfiltered + * list is (see [MENU_SEARCH_ROWS_MAX_HEIGHT]). + * + * @property String value The current query. + * @property Function onValueChange Takes the edited query; the clear affordance reports an empty string. + * @property Dp width The menu's width, which the box fills less the row inset. + * @property String? placeholder The dimmed hint while the query is empty, or null for the kit's default. + * @property Dp maxRowsHeight How tall the rows grow before they scroll. + */ + data class Search( + val value: String, + val onValueChange: (String) -> Unit, + val width: Dp, + val placeholder: String? = null, + val maxRowsHeight: Dp = MENU_SEARCH_ROWS_MAX_HEIGHT, + ) : MenuItem +} + +/** + * One top-level menu-bar entry: a [label] (File, Help, …) that opens [items] as a [Menu] dropped + * beneath it. + * + * メニューバーの最上位項目。ラベルをクリックすると items を真下にメニューとして開く。 + * + * @property String label The menu-bar label. + * @property List items The menu opened beneath the label. + */ +data class TopLevelMenu( + val label: String, + val items: List, +) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MessageDialog.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MessageDialog.kt new file mode 100644 index 0000000..7058e95 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/MessageDialog.kt @@ -0,0 +1,69 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.button.Button +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.dialog_okay +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A minimal modal message dialog: a scrim over the whole shell with a small centered card carrying the + * [message] and a single OK button - [ConfirmDialog]'s one-button sibling for alerts that only inform + * (a failed file open, a rejected import). Presentation-only and shell-agnostic: the caller owns the + * visible state and supplies [onDismiss]. Clicking the scrim, like OK, dismisses; the card swallows + * clicks so a press inside it does not count as a scrim dismissal. + * + * @param String message The already-localized message shown in the card. + * @param Function onDismiss Called when the user dismisses (OK button or scrim click). + * @param Modifier modifier Layout modifier for the scrim. + */ +@Composable +fun MessageDialog( + message: String, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = LocalUmamoColors.current + Box( + // indication = null (the kit convention): a bare clickable renders the default hover/press + // indication across the whole scrim, a stray dimming layer that toggles on pointer enter/leave. + modifier = + modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Surface( + // The card swallows clicks (enabled = false) so a press on it is not read as a scrim dismissal. + modifier = Modifier.widthIn(min = 180.dp, max = 420.dp).clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.padding(20.dp)) { + Text(text = message, style = LocalUmamoTypography.current.bodyMedium) + Box(modifier = Modifier.padding(top = 20.dp).align(Alignment.End)) { + Button(label = stringResource(Res.string.dialog_okay), onClick = onDismiss, primary = true) + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/NumberField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/NumberField.kt new file mode 100644 index 0000000..9a400c2 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/NumberField.kt @@ -0,0 +1,633 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import org.umamo.ui.model.KeyedFieldState +import org.umamo.ui.model.backgroundTint +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon +import org.umamo.ui.theme.umamoPointerIcon +import kotlin.math.roundToInt + +/** The alpha applied to the accent tint when a bounded field draws its left-to-right magnitude fill. */ +private const val NUMBER_FIELD_FILL_ALPHA = 0.30f + +/** + * The field's fixed height, shared with the other inline form controls via [FIELD_CONTROL_HEIGHT] so a + * NumberField and a SelectField line up. Pinned (rather than content-driven) so the display and type-in + * faces do not jump when swapping, and so the edge chevrons' fillMaxHeight has a bounded constraint to fill + * - a scroll container hands children an unbounded max height, under which fillMaxHeight collapses to the + * glyph. With no vertical padding on the inner content, the box's fixed height plus center alignment + * position the single text line, so the glyph is never clipped by a competing content height. + */ +private val NUMBER_FIELD_HEIGHT = FIELD_CONTROL_HEIGHT + +/** + * A compact numeric field for a scalar [value], clamped to [range]. Blender-style: the field shows the + * value while idle; a quick click enters type-in mode; a horizontal drag past the touch slop scrubs the + * value (previewed live, committed once on release); hovering reveals decrement / increment chevrons that + * step by [step]. When [range] is a usable finite span a left-to-right magnitude fill tracks where the + * value sits in it. Commits (type-in confirm, chevron step, drag release) each fire [onValueChange] once + * with the value rounded to [decimals] places and clamped to [range]; a whole scrub is one commit, so a + * caller can treat it as one undo step. + * + * 数値入力欄。クリックで入力、ドラッグでスクラブ、ホバーで増減シェブロン。範囲が有限なら塗りで大きさを示す。 + * + * @param Float value The current value, shown when not being edited. + * @param Function onValueChange Called with the committed value (rounded to [decimals] and clamped to [range]). + * @param ClosedFloatingPointRange range The min..max the committed value is clamped to (an infinite endpoint = unbounded, no fill). + * @param Modifier modifier Layout modifier (the caller supplies the width). + * @param Int decimals The fractional places shown; the stored value is rounded to the same (Float-capped). + * @param Float step The increment for a chevron press and the scrub sensitivity. + * @param String? unitSuffix An optional trailing unit shown in the idle field (e.g. "px", "%"); never in the edit text. + * @param Boolean showFill Whether to draw the magnitude fill when the range is bounded (off for wide sanity clamps). + * @param Boolean plain When true, renders a bare type-in box only (no scrub, chevrons, or fill) - the simple field. + * @param Boolean enabled When false the value still shows but dimmed, and every edit path is inert. + * @param StackPosition stackPosition This field's position in a vertical stack (corner rounding + seam). + * @param KeyedFieldState keyState The keyform state to tint the field's background fill with. + * @param Function? onPreview Called with each in-flight value while the field is being drag-scrubbed. + */ +@Composable +fun NumberField( + value: Float, + onValueChange: (Float) -> Unit, + range: ClosedFloatingPointRange, + modifier: Modifier = Modifier, + decimals: Int = 2, + step: Float = 1f, + unitSuffix: String? = null, + showFill: Boolean = true, + plain: Boolean = false, + enabled: Boolean = true, + stackPosition: StackPosition = StackPosition.Single, + keyState: KeyedFieldState = KeyedFieldState.None, + onPreview: ((Float) -> Unit)? = null, +) { + val bounded = showFill && range.start.isFinite() && range.endInclusive.isFinite() && range.endInclusive > range.start + NumberFieldCore( + keyState = keyState, + value = value, + range = range, + step = step, + bounded = bounded, + format = { toFormat -> formatDecimals(toFormat, decimals) }, + parse = { typed -> typed.trim().toFloatOrNull() }, + onCommit = { raw -> onValueChange(roundToDecimals(raw, decimals).coerceIn(range.start, range.endInclusive)) }, + onPreview = + onPreview?.let { preview -> + { raw: Float -> preview(roundToDecimals(raw, decimals).coerceIn(range.start, range.endInclusive)) } + }, + modifier = modifier, + unitSuffix = unitSuffix, + plain = plain, + enabled = enabled, + stackPosition = stackPosition, + ) +} + +/** + * Integer variant of [NumberField]: shows and commits a whole number (a typed decimal or non-number is + * rejected). Same Blender-style interaction - click to type, drag to scrub, hover chevrons - stepping by + * [step]. The magnitude fill draws only for a genuinely bounded range: a half-open sanity clamp such as + * `0..Int.MAX_VALUE` reads as unbounded and shows no fill. + * + * 整数版の数値入力欄。クリックで入力、ドラッグでスクラブ、ホバーで増減。両端が有限のときだけ塗りを描く。 + * + * @param Int value The current value, shown when not being edited. + * @param Function onValueChange Called with the committed value (clamped to [range]). + * @param IntRange range The min..max the committed value is clamped to. + * @param Modifier modifier Layout modifier (the caller supplies the width). + * @param Int step The increment for a chevron press and the scrub sensitivity. + * @param String? unitSuffix An optional trailing unit shown in the idle field; never in the edit text. + * @param Boolean showFill Whether to draw the magnitude fill when the range is bounded. + * @param Boolean plain When true, renders a bare type-in box only (the simple field). + * @param Boolean enabled When false the value still shows but dimmed, and every edit path is inert. + * @param StackPosition stackPosition This field's position in a vertical stack (corner rounding + seam). + * @param KeyedFieldState keyState The keyform state to tint the field's background fill with. + * @param Function? onPreview Called with each in-flight value while the field is being drag-scrubbed. + */ +@Composable +fun NumberField( + value: Int, + onValueChange: (Int) -> Unit, + range: IntRange, + modifier: Modifier = Modifier, + step: Int = 1, + unitSuffix: String? = null, + showFill: Boolean = true, + plain: Boolean = false, + enabled: Boolean = true, + stackPosition: StackPosition = StackPosition.Single, + keyState: KeyedFieldState = KeyedFieldState.None, + onPreview: ((Int) -> Unit)? = null, +) { + val floatRange = range.first.toFloat()..range.last.toFloat() + // A whole-domain endpoint means "unbounded", so a plain int clamp such as 0..Int.MAX_VALUE draws no fill. + val bounded = showFill && range.first > Int.MIN_VALUE && range.last < Int.MAX_VALUE + NumberFieldCore( + keyState = keyState, + onPreview = + onPreview?.let { preview -> + { raw: Float -> preview(raw.roundToInt().coerceIn(range.first, range.last)) } + }, + value = value.toFloat(), + range = floatRange, + step = step.toFloat(), + bounded = bounded, + format = { toFormat -> toFormat.roundToInt().toString() }, + parse = { typed -> typed.trim().toIntOrNull()?.toFloat() }, + onCommit = { raw -> onValueChange(raw.roundToInt().coerceIn(range.first, range.last)) }, + modifier = modifier, + unitSuffix = unitSuffix, + plain = plain, + enabled = enabled, + stackPosition = stackPosition, + ) +} + +/** + * The shared engine behind both [NumberField] overloads, working in Float and delegating type-specific + * formatting / parsing / rounding to the overload via [format], [parse], and [onCommit]. Holds the two + * interaction states: a display face (tap to edit, drag to scrub, hover chevrons, magnitude fill) and the + * type-in editor swapped in while editing. A scrub previews locally (nothing commits per frame) and + * commits once on release; [plain] skips straight to a bare type-in box. + * + * @param Float value The current value (the source of truth while idle). + * @param ClosedFloatingPointRange range The clamp range. + * @param Float step The chevron / scrub increment. + * @param Boolean bounded Whether to draw the magnitude fill (a usable finite range). + * @param Function format Formats a value for display and for seeding the editor. + * @param Function parse Parses typed text to a raw value, or null when unparseable. + * @param Function onCommit Rounds / clamps a raw value and fires the caller's callback (one committed edit). + * @param Modifier modifier Layout modifier (the width). + * @param String? unitSuffix The idle trailing unit, or null. + * @param Boolean plain Whether to render the bare type-in box only. + * @param Boolean enabled Whether the field accepts edits at all. + * @param StackPosition stackPosition The field's position in a vertical stack. + * @param KeyedFieldState keyState The keyform state to tint the field's background fill with. + * @param Function? onPreview Called with each in-flight value while the field is being drag-scrubbed. + */ +@Composable +private fun NumberFieldCore( + value: Float, + range: ClosedFloatingPointRange, + step: Float, + bounded: Boolean, + format: (Float) -> String, + parse: (String) -> Float?, + onCommit: (Float) -> Unit, + modifier: Modifier, + unitSuffix: String?, + plain: Boolean, + enabled: Boolean, + stackPosition: StackPosition, + keyState: KeyedFieldState = KeyedFieldState.None, + onPreview: ((Float) -> Unit)? = null, +) { + val shapes = LocalUmamoShapes.current + val shape = stackedShape(shapes.small, stackPosition, StackAxis.Vertical) + // Parses typed text, clamps to the range, and commits; an unparseable entry does nothing. + val commitTyped: (String) -> Unit = { typed -> + parse(typed)?.let { parsed -> onCommit(parsed.coerceIn(range.start, range.endInclusive)) } + } + + if (plain) { + // The simple field: a bare type-in box, matching the pre-upgrade behavior (no scrub / chevrons / fill). + // Disabled, it degrades to the same inert display face the rich field uses, so both faces read alike. + if (enabled) { + NumberEntryField( + display = format(value), + shape = shape, + modifier = modifier, + keyState = keyState, + commit = commitTyped, + ) + } else { + NumberFieldDisplay( + text = format(value), + unitSuffix = unitSuffix, + fillFraction = null, + shape = shape, + modifier = modifier, + enabled = false, + keyState = keyState, + ) + } + return + } + + var editing by remember { mutableStateOf(false) } + // The live scrub value while a drag is in flight (null when idle); previews without committing per frame. + var dragValue by remember { mutableStateOf(null) } + // The value the drag STARTED from. scrubValue maps a TOTAL pointer delta onto a fixed base, so the base + // has to stay fixed: reading the live `value` instead would compound the movement, because onPreview feeds + // each frame's value straight back in through the pending buffer, accelerating the scrub and forcing a + // reversed drag to spend its first stretch merely unwinding the drift. + var scrubStartValue by remember { mutableStateOf(0f) } + + // Being disabled ENDS an in-flight edit rather than parking it: leaving `editing` set would re-open the + // type-in box - autoFocus and all - the moment the field became editable again, stealing focus for an + // edit the user abandoned long ago. A scrub preview is dropped for the same reason. + if (!enabled && (editing || dragValue != null)) { + editing = false + dragValue = null + } + + if (editing && enabled) { + NumberEntryField( + display = format(value), + shape = shape, + modifier = modifier, + autoFocus = true, + onFocusLost = { editing = false }, + keyState = keyState, + commit = commitTyped, + ) + } else { + val shown = dragValue ?: value + NumberFieldDisplay( + text = format(shown), + unitSuffix = unitSuffix, + fillFraction = if (bounded) numberFieldFillFraction(shown, range.start, range.endInclusive) else null, + shape = shape, + modifier = modifier, + enabled = enabled, + onTapToEdit = { editing = true }, + onScrubStart = { + scrubStartValue = value + dragValue = value + }, + onScrub = { totalDeltaPx -> + val scrubbed = scrubValue(scrubStartValue, totalDeltaPx, step, range) + dragValue = scrubbed + // Reported live so the caller can drive whatever the value affects while the drag is still + // happening. Without it a scrub moves the number and nothing else until release, which + // reads as the edit not working - the field is the only thing that responds. + onPreview?.invoke(scrubbed) + }, + onScrubEnd = { + dragValue?.let { finalValue -> onCommit(finalValue) } + dragValue = null + }, + onStep = { direction -> onCommit((value + direction * step).coerceIn(range.start, range.endInclusive)) }, + // Forwarded on the RESTING face, the one every real field shows: this is the background tint that + // warns a typed value is unkeyed and dies on the next scrub, so every enabled field must carry it, + // not only the disabled-plain display path. + keyState = keyState, + ) + } +} + +/** + * The idle display face of a [NumberField]: a box showing [text] (plus an optional [unitSuffix]) over a + * left-to-right accent magnitude fill, with decrement / increment chevrons that fade in on hover. + * A quick tap enters type-in mode ([onTapToEdit]); a horizontal drag past the touch slop scrubs + * ([onScrubStart] / [onScrub] with the total delta from the gesture start / [onScrubEnd]). The two + * pointer handlers are separate inputs like [Slider], and callbacks are read through + * [rememberUpdatedState] so a reused row slot always drives the current field. + * + * @param String text The formatted value to show. + * @param String? unitSuffix An optional trailing unit, or null. + * @param Float? fillFraction The magnitude fill in 0..1, or null for no fill. + * @param Shape shape The field's (stack-aware) corner shape. + * @param Modifier modifier Layout modifier (the width). + * @param Boolean enabled When false the text dims and NO edit affordance is attached - no scrub cursor, no + * pointer handlers, no hover chevrons - so a disabled field cannot be interacted with by any route. + * @param Function onTapToEdit Enters type-in mode (a click that did not become a drag). + * @param Function onScrubStart Begins a scrub gesture. + * @param Function onScrub Reports the total horizontal drag delta from the gesture start, in pixels. + * @param Function onScrubEnd Ends the scrub (commit the previewed value). + * @param Function onStep Steps the value by a chevron press (-1 or +1). + * @param KeyedFieldState keyState The keyform state to tint the field's background fill with. + */ +@Composable +private fun NumberFieldDisplay( + text: String, + unitSuffix: String?, + fillFraction: Float?, + shape: Shape, + modifier: Modifier, + enabled: Boolean = true, + onTapToEdit: () -> Unit = {}, + onScrubStart: () -> Unit = {}, + onScrub: (Float) -> Unit = {}, + onScrubEnd: () -> Unit = {}, + onStep: (Int) -> Unit = {}, + keyState: KeyedFieldState = KeyedFieldState.None, +) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val currentTap by rememberUpdatedState(onTapToEdit) + val currentScrubStart by rememberUpdatedState(onScrubStart) + val currentScrub by rememberUpdatedState(onScrub) + val currentScrubEnd by rememberUpdatedState(onScrubEnd) + val fillColor = colors.accent.copy(alpha = NUMBER_FIELD_FILL_ALPHA) + Box( + modifier = + modifier + .height(NUMBER_FIELD_HEIGHT) + .clip(shape) + .background(if (hovered && enabled) colors.controlBackgroundHover else colors.controlBackground) + // The keyed tint layers OVER the fill rather than replacing it, which is what keeps hover + // working on a keyed field: the base below changes, the translucent tint above does not. An + // unkeyed field paints nothing extra and looks exactly as it did. + .background(keyState.backgroundTint(colors) ?: Color.Transparent, shape) + .then( + if (!enabled) { + // A disabled field attaches no gesture or cursor affordance at all, so it cannot be + // scrubbed, typed into, or stepped, and it does not advertise that it could be. + Modifier + } else { + Modifier + .hoverable(interaction) + // The east-west arrows advertise the scrub before the user tries it - the drag is + // otherwise invisible. Not overrideDescendants: the chevrons take back the default + // pointer so they still read as buttons. + .pointerHoverIcon(umamoPointerIcon(LocalUmamoCursors.ewScroll)) + .pointerInput(Unit) { + detectTapGestures { currentTap() } + } + // Horizontal-only: the scrub claims left/right drags but leaves vertical drags to the + // enclosing scroll (a scroll gesture begun on a field must still scroll the panel). + .pointerInput(Unit) { + var total = 0f + detectHorizontalDragGestures( + onDragStart = { + total = 0f + currentScrubStart() + }, + onDragEnd = { currentScrubEnd() }, + onDragCancel = { currentScrubEnd() }, + ) { change, dragAmount -> + change.consume() + total += dragAmount + currentScrub(total) + } + } + }, + ), + contentAlignment = Alignment.Center, + ) { + if (fillFraction != null) { + // The magnitude fill sits behind the value (drawn first) and spans the fraction of the width. + Canvas(modifier = Modifier.matchParentSize()) { + drawRect(color = fillColor, size = Size(size.width * fillFraction, size.height)) + } + } + Row( + // No vertical padding: the fixed-height box centers the single text line, so it is never clipped + // by an inner content height that would exceed the box (the cause of a padded row overflowing). + modifier = Modifier.padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + val textColor = if (enabled) colors.text else colors.textDisabled + Text(text = text, style = typography.bodySmall, color = textColor) + if (unitSuffix != null) { + Spacer(modifier = Modifier.width(2.dp)) + Text(text = unitSuffix, style = typography.bodySmall, color = textColor) + } + } + if (hovered && enabled) { + StepChevron( + icon = LocalUmamoIcons.chevronLeft, + onClick = { onStep(-1) }, + modifier = Modifier.align(Alignment.CenterStart), + keyState = keyState, + ) + StepChevron( + icon = LocalUmamoIcons.chevronRight, + onClick = { onStep(1) }, + modifier = Modifier.align(Alignment.CenterEnd), + keyState = keyState, + ) + } + } +} + +/** + * A decrement / increment chevron shown on the idle field's edge while hovered: a full-height edge button + * with its own control-fill background (brightening on hover) so the glyph stays legible over the value + * text and the magnitude fill behind it. Its square outer corners are clipped to the field's rounded + * shape by the parent. A pointer convenience over the field's type-in, so it carries no accessibility + * label of its own. + * + * @param UmamoIcon icon The chevron glyph (left = decrement, right = increment). + * @param Function onClick Steps the value one increment. + * @param Modifier modifier Layout modifier (the caller aligns it to an edge). + * @param KeyedFieldState keyState The field's keyed state, tinted over this button's own opaque fill so a + * keyed field does not lose the signal at both ends exactly when the chevrons appear. + */ +@Composable +private fun StepChevron(icon: UmamoIcon, onClick: () -> Unit, modifier: Modifier, keyState: KeyedFieldState) { + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + Box( + modifier = + modifier + .fillMaxHeight() + .width(16.dp) + // Takes back the plain pointer from the field's scrub cursor: this edge is a click target, not + // a drag zone, and the innermost hover icon wins. + .pointerHoverIcon(PointerIcon.Default) + .background(if (hovered) colors.buttonHover else colors.controlBackground) + // Opaque fills over the field's own, and the chevrons show exactly WHEN the field is hovered - + // so without the tint here a keyed field loses 32dp of its signal at both ends on hover. + .background(keyState.backgroundTint(colors) ?: Color.Transparent) + .clickable(interactionSource = interaction, indication = null, onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.size(12.dp)) { + drawIcon(icon, colors.text) + } + } +} + +/** + * The single-line type-in editor: a [BasicTextField] showing [display] while idle and letting the user + * type a replacement, committing the raw text to [commit] on Enter or focus loss and discarding on Escape. + * When [autoFocus] is set it grabs focus on first composition (the field just swapped into edit mode) and + * calls [onFocusLost] when focus leaves, so the host can swap the display face back in. It lends its + * cancel hook to [LocalInlineEditController] while focused so the shell routes Escape here and yields + * shortcut keys (Space, digits, minus) to the field. + * + * @param String display The formatted external value, shown while idle. + * @param Shape shape The field's (stack-aware) corner shape. + * @param Modifier modifier Layout modifier (the width). + * @param Boolean autoFocus When true, requests focus on first composition (rich edit mode). + * @param Function onFocusLost Called after focus leaves (rich edit mode swaps back to the display face). + * @param KeyedFieldState keyState The field's keyed state, tinted behind the text so clicking a keyed field + * to type does not flash the box back to the plain fill for the length of the edit. + * @param Function commit Parses / clamps / fires the caller callback with the raw typed text. + */ +@Composable +private fun NumberEntryField( + display: String, + shape: Shape, + modifier: Modifier, + autoFocus: Boolean = false, + onFocusLost: () -> Unit = {}, + keyState: KeyedFieldState = KeyedFieldState.None, + commit: (String) -> Unit, +) { + val colors = LocalUmamoColors.current + val controller = LocalInlineEditController.current + val focusManager = LocalFocusManager.current + val focusRequester = remember { FocusRequester() } + var focused by remember { mutableStateOf(false) } + // A TextFieldValue rather than a String so the context menu can act on a selection; the caret sits at the + // end whenever the value is (re)seeded from outside, which is where a click-to-type gesture wants it. + var text by remember { mutableStateOf(TextFieldValue(display, TextRange(display.length))) } + // True between an Escape (which clears focus to discard) and the resulting focus-loss, so that path + // discards instead of committing. Plain commit paths (Enter, click-away) leave it false. + var discarding by remember { mutableStateOf(false) } + + if (autoFocus) { + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + } + // A field disposed while it holds focus (its host left the composition - the operation settings strip + // on the next edit) gets no focus-loss callback, so the cancel hook it parked would keep the shell + // yielding the keyboard to a field that no longer exists. Release it here; the host's reclaim effect + // then takes the keyboard back. + DisposableEffect(Unit) { + onDispose { + if (focused) { + controller.cancel = null + } + } + } + // While not editing, mirror the external value (a slider / pad drag or a reset updates the number). + LaunchedEffect(display, focused) { + if (!focused) { + text = TextFieldValue(display, TextRange(display.length)) + } + } + + // The visual box carries the fixed height, fill, and border so it matches the display face exactly (no + // jump on click); the inner text field wraps its own line height and the box centers it, with horizontal + // padding only - the same "let the fixed box own the height" approach the display face uses. That + // promise includes the KEYED tint: without it, clicking a keyed field to type flashed the whole box back + // to the plain fill for the length of the edit. + TextEditContextMenuArea(value = text, onValueChange = { edited -> text = edited }) { gesture -> + Box( + modifier = + gesture + .then(modifier) + .textEntrySurface(controller) + .height(NUMBER_FIELD_HEIGHT) + .clip(shape) + .background(colors.controlBackground) + .background(keyState.backgroundTint(colors) ?: Color.Transparent, shape) + .border(1.dp, colors.controlBorder, shape), + contentAlignment = Alignment.Center, + ) { + BasicTextField( + value = text, + onValueChange = { edited -> text = edited }, + textStyle = LocalUmamoTypography.current.bodySmall.copy(color = colors.text, textAlign = TextAlign.End), + singleLine = true, + cursorBrush = SolidColor(colors.text), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done), + // Soft-keyboard Done: clear focus so the single commit happens on the focus-loss path below. + keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp) + .focusRequester(focusRequester) + .onFocusChanged { focusState -> + // hasFocus (not isFocused): BasicTextField focuses an internal child, so this node only ever + // sees its subtree's focus. + if (focusState.hasFocus) { + if (!focused) { + focused = true + controller.cancel = { + discarding = true + focusManager.clearFocus() + } + } + } else if (focused) { + focused = false + controller.cancel = null + if (discarding) { + discarding = false + } else { + commit(text.text) + } + onFocusLost() + } + } + .onKeyEvent { event -> + // Hardware Enter confirms by clearing focus, so the commit runs once on the focus-loss path. + if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) { + focusManager.clearFocus() + true + } else { + false + } + }, + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/NumberFieldMath.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/NumberFieldMath.kt new file mode 100644 index 0000000..8050631 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/NumberFieldMath.kt @@ -0,0 +1,94 @@ +package org.umamo.ui.kit + +import kotlin.math.abs +import kotlin.math.pow +import kotlin.math.round + +/* + * Pure, Compose-free numeric-field math: display / storage rounding, the min-max fill fraction, the + * drag-scrub value mapping, and fixed-decimal formatting. Extracted so the field's behavior is unit + * testable without a Compose harness (see NumberFieldMathTest). + */ + +/** + * The storage-precision cap for a decimal NumberField. A Float holds roughly six to seven significant + * decimal digits, so the requested "up to eight places" is capped here - promote the field and its model + * slot to Double if eight-place fidelity is ever genuinely needed. + */ +const val NUMBER_FIELD_STORAGE_DECIMALS = 6 + +/** Pixels of horizontal drag per one [step] increment while scrubbing (the pointer-scrub sensitivity). */ +const val NUMBER_FIELD_SCRUB_PIXELS_PER_STEP = 6f + +/** + * The left-to-right fill fraction for a bounded field: where [value] sits in [min]..[max], clamped to + * 0..1. Returns null when the bounds are not a usable finite range (infinite endpoint, or max <= min), + * so an unbounded field draws no fill - the "min AND max set" rule. + * + * @param Float value The current value. + * @param Float min The range minimum. + * @param Float max The range maximum. + * @return Float? The fill fraction in 0..1, or null when unbounded. + */ +fun numberFieldFillFraction(value: Float, min: Float, max: Float): Float? { + if (!min.isFinite() || !max.isFinite() || max <= min) { + return null + } + return ((value - min) / (max - min)).coerceIn(0f, 1f) +} + +/** + * Rounds [value] to [decimals] fractional places (the field's storage rounding); [decimals] <= 0 rounds + * to a whole number. Capped at [NUMBER_FIELD_STORAGE_DECIMALS] since a Float cannot faithfully hold more. + * + * @param Float value The value to round. + * @param Int decimals The number of fractional places to keep. + * @return Float The rounded value. + */ +fun roundToDecimals(value: Float, decimals: Int): Float { + val places = decimals.coerceIn(0, NUMBER_FIELD_STORAGE_DECIMALS) + if (places <= 0) { + return round(value) + } + val scale = 10.0.pow(places).toFloat() + return round(value * scale) / scale +} + +/** + * Formats [value] to exactly [decimals] fractional places for display (Blender pads a float field to a + * fixed width, e.g. "0.500"); [decimals] <= 0 shows a whole number. Dependency-free (kotlinx / java.text + * formatting is not available in commonMain). Capped at [NUMBER_FIELD_STORAGE_DECIMALS]. + * + * @param Float value The value to format. + * @param Int decimals The number of fractional places to show. + * @return String The fixed-decimal text. + */ +fun formatDecimals(value: Float, decimals: Int): String { + val places = decimals.coerceIn(0, NUMBER_FIELD_STORAGE_DECIMALS) + if (places <= 0) { + return round(value.toDouble()).toLong().toString() + } + val scale = 10.0.pow(places).toLong() + val scaled = round(value.toDouble() * scale).toLong() + val sign = if (scaled < 0) "-" else "" + val magnitude = abs(scaled) + val whole = magnitude / scale + val fraction = (magnitude % scale).toString().padStart(places, '0') + return "$sign$whole.$fraction" +} + +/** + * Maps a horizontal drag onto a new value: [startValue] plus one [step] per + * [NUMBER_FIELD_SCRUB_PIXELS_PER_STEP] pixels of [deltaPx], clamped to [range]. Rightward drag + * increases, leftward decreases (screen-x convention). + * + * @param Float startValue The value at the gesture's start. + * @param Float deltaPx The total horizontal drag distance from the start, in pixels. + * @param Float step The value increment per scrub notch. + * @param ClosedFloatingPointRange range The clamp range. + * @return Float The scrubbed value. + */ +fun scrubValue(startValue: Float, deltaPx: Float, step: Float, range: ClosedFloatingPointRange): Float { + val raw = startValue + (deltaPx / NUMBER_FIELD_SCRUB_PIXELS_PER_STEP) * step + return raw.coerceIn(range.start, range.endInclusive) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/OverflowRow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/OverflowRow.kt new file mode 100644 index 0000000..c7ec12c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/OverflowRow.kt @@ -0,0 +1,333 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.layout.Measurable +import androidx.compose.ui.layout.Placeable +import androidx.compose.ui.layout.SubcomposeLayout +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.constrainHeight +import androidx.compose.ui.unit.constrainWidth +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons + +/** The inset around one collapsed control inside the overflow panel. */ +private val OVERFLOW_MENU_ROW_PADDING_HORIZONTAL = 8.dp + +/** The gap between two stacked controls inside the overflow panel. */ +private val OVERFLOW_MENU_ROW_PADDING_VERTICAL = 2.dp + +/** + * The separation a flexible gap keeps once its leftover is gone - the same 8.dp the strip puts between + * two adjacent controls, so a fully squeezed gap reads as ordinary spacing rather than as a seam. + */ +val FLEXIBLE_SPACE_MIN_WIDTH = 8.dp + +/** + * Declares the controls on an [OverflowRow]. Deliberately NOT a composable scope: the row has to hold + * each control's body as a value so the overflow panel can render exactly the collapsed subset, and a + * composable collector would let one inner restartable scope re-append to a list the outer scope never + * rebuilt. This is [androidx.compose.foundation.lazy.LazyListScope]'s shape, for the same reason. + * + * The consequence is worth stating plainly: CompositionLocals may only be read inside an item body, + * never in the builder that declares the items. + * + * It is also not a RowScope, so Modifier.weight inside an item is a compile error - weight distribution + * belongs to [flexibleSpace], which the packer understands. + */ +interface OverflowRowScope { + /** + * A control that collapses into the overflow dropdown when the strip runs out of room. Collapsing + * happens from the end: the last declared item goes first. + * + * Pass [minWidth] for a control that can usefully give up width before it gives up entirely - a search + * box is the obvious one - and it is measured against the room actually left, compressing down to that + * floor and only collapsing below it. Left unspecified the control is placed at its natural width or + * not at all, which is what a chip or a button wants. + * + * @param Any? key A stable identity for the slot, so its state survives a sibling appearing or + * disappearing. Defaults to the declaration index, which is only safe when the item list is fixed. + * @param Dp minWidth The narrowest this control may be squeezed to; unspecified to never compress. + * @param Function content The control. + */ + fun item(key: Any? = null, minWidth: Dp = Dp.Unspecified, content: @Composable () -> Unit) + + /** + * A control that is always placed, even when placing it overflows the strip. Reserve this for the + * one control a strip is about - a header that hides its own subject is worse than one that clips. + * + * @param Any? key A stable identity for the slot; see [item]. + * @param Function content The control. + */ + fun pinnedItem(key: Any? = null, content: @Composable () -> Unit) + + /** + * A weighted gap that absorbs leftover width - the replacement for Spacer(Modifier.weight(w)). It + * carries no spacing of its own on either side, since it IS the separation. + * + * [minWidth] is the separation the gap never closes below, reserved before the controls around it are + * admitted rather than shared out of what happens to be left. Without it a starved strip resolves the + * gap to nothing and the controls either side butt together, which reads as a rendering fault. + * + * @param Float weight This gap's share of the leftover width. + * @param Dp minWidth The separation this gap keeps even with no leftover to share. + */ + fun flexibleSpace(weight: Float = 1f, minWidth: Dp = FLEXIBLE_SPACE_MIN_WIDTH) +} + +/** + * One declared slot: its identity, how it behaves when width runs short, and its body. + * + * @property Any key The slot's stable identity, also its subcomposition slot id. + * @property OverflowSlotKind kind How the slot behaves when width runs short. + * @property Float weight The share of leftover width, for a Flexible slot. + * @property Dp minWidth A control's squeeze floor, or a gap's minimum separation. + * @property Function? content The control, or null for a Flexible gap. + */ +private class OverflowSlot( + val key: Any, + val kind: OverflowSlotKind, + val weight: Float, + val minWidth: Dp, + val content: (@Composable () -> Unit)?, +) + +/** Subcomposition slot ids, wrapped so a caller's item key can never collide with the overflow chip's. */ +private sealed interface OverflowSlotId { + data class Item(val key: Any) : OverflowSlotId + + data object OverflowButton : OverflowSlotId +} + +/** Collects the declared slots into a plain list; rebuilt on every recomposition, never remembered. */ +private class OverflowRowCollector : OverflowRowScope { + val slots = mutableListOf() + + override fun item(key: Any?, minWidth: Dp, content: @Composable () -> Unit) { + add(key, OverflowSlotKind.Collapsible, weight = 0f, minWidth = minWidth, content = content) + } + + override fun pinnedItem(key: Any?, content: @Composable () -> Unit) { + add(key, OverflowSlotKind.Pinned, weight = 0f, minWidth = Dp.Unspecified, content = content) + } + + override fun flexibleSpace(weight: Float, minWidth: Dp) { + add(key = null, kind = OverflowSlotKind.Flexible, weight = weight, minWidth = minWidth, content = null) + } + + /** + * Appends one slot, defaulting its key to the declaration index and rejecting duplicates. + * + * @param Any? key The caller's key, or null to key by declaration index. + * @param OverflowSlotKind kind How the slot behaves when width runs short. + * @param Float weight The share of leftover width, for a Flexible gap. + * @param Dp minWidth The narrowest the control may be squeezed to, or unspecified. + * @param Function? content The control, or null for a Flexible gap. + */ + private fun add(key: Any?, kind: OverflowSlotKind, weight: Float, minWidth: Dp, content: (@Composable () -> Unit)?) { + val slotKey = key ?: slots.size + // A duplicate key silently merges two slots' subcompositions, so their state would swap under the + // user. That is a programming error, not a runtime branch - same posture as SpaceRegistry. + require(slots.none { existing -> existing.key == slotKey }) { "duplicate OverflowRow slot key: $slotKey" } + slots.add(OverflowSlot(key = slotKey, kind = kind, weight = weight, minWidth = minWidth, content = content)) + } +} + +/** + * A horizontal strip whose controls collapse into a trailing overflow dropdown instead of being crushed + * when the strip runs out of room. A plain Row measures each un-weighted child against whatever width + * is left, so a narrowing strip squeezes its controls to nothing in place; this measures every control + * at its natural width and simply stops placing the ones that do not fit, handing them to the chip. + * + * Each item is measured with an unbounded width and the strip's own height, so an item must be + * intrinsically sized - Modifier.fillMaxWidth at an item root resolves to zero against an infinite + * maximum and the item is dropped. An item that renders nothing costs nothing: it measures zero and is + * skipped, spacing and all, which is how a mode-gated control disappears cleanly. + * + * Note for future adopters: this is a SubcomposeLayout, whose intrinsic measurements are expensive and + * lossy. It is fine under a fixed height (an area header), but do not drop it into a parent that asks + * for intrinsics - Modifier.height(IntrinsicSize.Min), say - without checking first. + * + * @param Modifier modifier The layout modifier. + * @param Dp horizontalSpacing The gap between adjacent controls. + * @param Alignment verticalAlignment How controls align across the strip's height. + * @param String overflowContentDescription The overflow chip's accessible label and tooltip. + * @param Function content Declares the controls; see [OverflowRowScope]. + */ +@Composable +fun OverflowRow( + modifier: Modifier = Modifier, + horizontalSpacing: Dp = 8.dp, + verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, + overflowContentDescription: String = stringResource(Res.string.header_more), + content: OverflowRowScope.() -> Unit, +) { + val collector = OverflowRowCollector() + collector.content() + val slots = collector.slots + var overflowExpanded by remember { mutableStateOf(false) } + // Keys rather than slots: keys compare cheaply and correctly, while a slot holds a lambda that is a + // fresh instance every recomposition and so would never compare equal. + val collapsedKeys = remember { mutableStateOf>(emptyList()) } + // What the verdict in collapsedKeys was computed against. Reusing it while the strip and its slot list + // are unchanged is what lets the second pass DROP the slot whose measurement decided the collapse - + // deciding it costs one composition, and without this that composition would linger unplaced, showing up + // in the semantics tree and duplicating the copy the panel renders. + val lastPackKey = remember { mutableStateOf>?>(null) } + // Remembered rather than measured up front: the chip is composed ONLY when something collapsed (an + // always-composed chip is an unplaced node in the tree), yet its width has to be reserved on every pass + // or the strip oscillates. Reserving the last measured width keeps both true. + val overflowButtonWidthPx = remember { mutableStateOf(0) } + + SubcomposeLayout(modifier = modifier) { constraints -> + val slotConstraints = Constraints(maxHeight = constraints.maxHeight) + val spacingPx = horizontalSpacing.roundToPx() + val slotKeys = slots.map { slot -> slot.key } + val packKey = constraints.maxWidth to slotKeys + // A changed width or slot list re-evaluates from scratch, so a widened strip can re-admit what it + // collapsed; an unchanged one honors the previous verdict and leaves the decided slots uncomposed. + val preCollapsed = + if (lastPackKey.value == packKey) { + slots.indices.filterTo(mutableSetOf()) { slotIndex -> slotKeys[slotIndex] in collapsedKeys.value } + } else { + emptySet() + } + + // Each slot is composed once (subcompose may not be called twice with one id in a pass) and the + // packer reads its width through INTRINSICS, never measure(): the strip is walked up to twice, a + // compressible slot is offered a different bound on each walk and again when a tail is costed, and + // Compose forbids measuring one Measurable twice in a pass. Intrinsics answer any number of times + // (a control that shrinks to its bound is min(natural, bound) wide), and every PLACED slot is then + // measured exactly once, at the width the packer settled on. + val measurables = HashMap(slots.size) + val naturalWidthPx = HashMap(slots.size) + + fun measurableFor(slotIndex: Int): Measurable = + measurables.getOrPut(slotIndex) { + val slot = slots[slotIndex] + subcompose(OverflowSlotId.Item(slot.key)) { + // One wrapper Row per item, so a multi-control item is one indivisible group whose + // internal spacing matches the strip's, and subcompose always yields one measurable. + Row(verticalAlignment = verticalAlignment, horizontalArrangement = Arrangement.spacedBy(horizontalSpacing)) { + slot.content?.invoke() + } + }.first() + } + val packing = + packOverflowRow( + slots = + slots.map { slot -> + OverflowSlotSpec( + kind = slot.kind, + weight = slot.weight, + minWidthPx = if (slot.minWidth == Dp.Unspecified) 0 else slot.minWidth.roundToPx(), + ) + }, + availableWidthPx = constraints.maxWidth, + boundedWidth = constraints.hasBoundedWidth, + spacingPx = spacingPx, + overflowButtonWidthPx = overflowButtonWidthPx.value, + preCollapsedSlotIndices = preCollapsed, + ) { slotIndex, maxWidthPx -> + val natural = naturalWidthPx.getOrPut(slotIndex) { measurableFor(slotIndex).maxIntrinsicWidth(constraints.maxHeight) } + if (maxWidthPx == OVERFLOW_WIDTH_UNBOUNDED) natural else minOf(natural, maxWidthPx.coerceAtLeast(0)) + } + val placeables = HashMap(packing.placements.size) + for (placement in packing.placements) { + if (slots[placement.slotIndex].kind == OverflowSlotKind.Flexible) { + continue + } + placeables[placement.slotIndex] = measurableFor(placement.slotIndex).measure(slotConstraints.copy(maxWidth = placement.widthPx)) + } + + val collapsed = packing.collapsedSlotIndices.map { slotIndex -> slotKeys[slotIndex] } + if (collapsedKeys.value != collapsed) { + collapsedKeys.value = collapsed + } + if (lastPackKey.value != packKey) { + lastPackKey.value = packKey + } + + val overflowPlaceable = + if (collapsed.isEmpty()) { + null + } else { + subcompose(OverflowSlotId.OverflowButton) { + val collapsedSlots = slots.filter { slot -> slot.key in collapsed } + PopupChip( + contentDescription = overflowContentDescription, + icon = LocalUmamoIcons.dots, + expanded = overflowExpanded, + onExpandedChange = { next -> overflowExpanded = next }, + ) { + collapsedSlots.forEach { slot -> + key(slot.key) { + OverflowMenuRow { slot.content?.invoke() } + } + } + } + }.first().measure(slotConstraints) + } + if (overflowPlaceable != null && overflowButtonWidthPx.value != overflowPlaceable.width) { + // The first strip to overflow reserved nothing, so it packed one chip too generously. Recording + // the real width re-measures once and settles; from then on the reserve is a constant. + overflowButtonWidthPx.value = overflowPlaceable.width + } + // The chip is gone, so an open panel would be anchored to nothing. It cannot be OPENED while + // unplaced (an absent node takes no clicks), but it can be open when the strip widens under it. + if (collapsed.isEmpty() && overflowExpanded) { + overflowExpanded = false + } + + // The chip counts toward the strip's height too - it is placed, so a strip sized to the items alone + // would clip it whenever it is the tallest thing on the row. + val contentHeight = maxOf(placeables.values.maxOfOrNull { it.height } ?: 0, overflowPlaceable?.height ?: 0) + val height = constraints.constrainHeight(contentHeight) + layout(constraints.constrainWidth(packing.contentWidthPx), height) { + packing.placements.forEach { placement -> + val placeable = placeables[placement.slotIndex] ?: return@forEach + placeable.place(x = placement.xPx, y = verticalAlignment.align(placeable.height, height)) + } + val buttonXPx = packing.overflowButtonXPx + if (overflowPlaceable != null && buttonXPx != null) { + overflowPlaceable.place(x = buttonXPx, y = verticalAlignment.align(overflowPlaceable.height, height)) + } + } + } +} + +/** + * One control's row inside the overflow panel: the control at its natural size, inset from the panel + * edges. Collapses to nothing when the control renders nothing, so a mode-gated item that ended up past + * the collapse point leaves an empty sliver rather than a visible gap. + * + * @param Function content The collapsed control. + */ +@Composable +private fun OverflowMenuRow(content: @Composable () -> Unit) { + Layout(content = content) { measurables, constraints -> + val horizontalPaddingPx = OVERFLOW_MENU_ROW_PADDING_HORIZONTAL.roundToPx() + val verticalPaddingPx = OVERFLOW_MENU_ROW_PADDING_VERTICAL.roundToPx() + val placeables = measurables.map { measurable -> measurable.measure(constraints) } + val contentWidth = placeables.maxOfOrNull { placeable -> placeable.width } ?: 0 + if (contentWidth == 0) { + return@Layout layout(0, 0) {} + } + val contentHeight = placeables.maxOf { placeable -> placeable.height } + layout(contentWidth + horizontalPaddingPx * 2, contentHeight + verticalPaddingPx * 2) { + placeables.forEach { placeable -> placeable.place(horizontalPaddingPx, verticalPaddingPx) } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/OverflowRowPacking.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/OverflowRowPacking.kt new file mode 100644 index 0000000..030d071 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/OverflowRowPacking.kt @@ -0,0 +1,410 @@ +package org.umamo.ui.kit + +/** + * What one declared slot is, from the packer's point of view. The composable content is deliberately + * absent - this file decides geometry only, so it stays a pure function the layout tests can drive + * without a composition. + */ +internal enum class OverflowSlotKind { + /** Collapses into the overflow dropdown when the strip runs out of room. */ + Collapsible, + + /** Always placed, even when that overflows the strip. */ + Pinned, + + /** A weighted gap that absorbs leftover width; never collapses and never carries spacing. */ + Flexible, +} + +/** + * Sentinel [OverflowSlotSpec.minWidthPx] and measure bound meaning "no limit" - a slot that is measured at + * whatever width it asks for, and collapses whole rather than compressing. + */ +internal const val OVERFLOW_WIDTH_UNBOUNDED = Int.MAX_VALUE + +/** + * One declared slot, stripped of its content. + * + * @property OverflowSlotKind kind How the slot behaves when width runs short. + * @property Float weight The share of leftover width, for [OverflowSlotKind.Flexible] only. + * @property Int minWidthPx For a Collapsible slot, the narrowest it may be squeezed to before + * it collapses instead; for a Flexible gap, the separation it never closes below. 0 means a control is + * placed at its natural width or not at all, and a gap may close completely. + */ +internal data class OverflowSlotSpec( + val kind: OverflowSlotKind, + val weight: Float = 0f, + val minWidthPx: Int = 0, +) + +/** + * One slot that made it onto the strip, at its resolved position. + * + * @property Int slotIndex The slot's index in the declared list. + * @property Int xPx The slot's left edge, relative to the strip. + * @property Int widthPx The slot's resolved width; for a Flexible gap, its floor plus its share of the + * leftover. + */ +internal data class OverflowPlacement( + val slotIndex: Int, + val xPx: Int, + val widthPx: Int, +) + +/** + * The resolved strip: what is placed and where, what collapsed, and where the overflow chip goes. + * + * @property List placements The placed slots in declaration order. + * @property List collapsedSlotIndices The slots that did not fit, in declaration order - the dropdown's contents. + * @property Int? overflowButtonXPx The chip's left edge, or null when nothing collapsed (it is measured + * but not placed). + * @property Int contentWidthPx The extent the strip actually occupies. + */ +internal data class OverflowRowPacking( + val placements: List, + val collapsedSlotIndices: List, + val overflowButtonXPx: Int?, + val contentWidthPx: Int, +) + +/** + * Decides which slots fit on the strip, at which x, and how wide each flexible gap resolves to. + * + * The strip is walked up to twice. The first walk charges nothing for the overflow chip, because a + * strip whose controls all fit does not show one; if that walk collapses nothing it is the answer. Only + * when something genuinely does not fit is the chip certain to exist, and the second walk charges for it. + * That ordering is what keeps the two walks from disagreeing - once a control has missed at the full + * width, reserving the chip can only push more out, never restore "everything fits" - so the strip + * settles rather than oscillating on a one-pixel resize. + * + * Widths are pulled through [slotWidthPx] rather than passed in so the caller can compose lazily: every + * Pinned slot is measured up front (they are always placed, so their width must be reserved before any + * earlier Collapsible slot is admitted), Collapsible slots are measured in declaration order until one + * does not fit, and nothing after that is measured at all. A slot measuring zero is dropped entirely - + * no spacing, not collapsed, absent from the dropdown - which is how a mode-gated control that renders + * nothing costs nothing. + * + * @param List slots The declared slots, in declaration order. + * @param Int availableWidthPx The strip's width; ignored for collapsing when [boundedWidth] is false. + * @param Boolean boundedWidth Whether the strip has a real width. When false nothing collapses and + * every flexible gap sits at its floor, since there is no leftover to share out. + * @param Int spacingPx The gap between two adjacent placed slots. + * @param Int overflowButtonWidthPx The measured width of the trailing overflow chip. + * @param Set preCollapsedSlotIndices Collapsible slots an earlier pass already ruled out, collapsed + * again without being measured. Deciding the FIRST slot that does not fit costs one measurement, so + * that slot is composed; feeding the verdict back lets the caller drop it on the next pass instead of + * leaving it composed-but-unplaced. Empty re-evaluates every slot from scratch. + * @param Function slotWidthPx Reports one slot's width at a given maximum, on demand. A slot + * declaring [OverflowSlotSpec.minWidthPx] can be asked twice with different bounds (once per walk) and + * again when a tail is costed, so the answer must be repeatable and side-effect free - an intrinsic + * width, never a measure(), which Compose allows once per slot per pass. + * @return OverflowRowPacking The resolved strip. + */ +internal fun packOverflowRow( + slots: List, + availableWidthPx: Int, + boundedWidth: Boolean, + spacingPx: Int, + overflowButtonWidthPx: Int, + preCollapsedSlotIndices: Set = emptySet(), + slotWidthPx: (slotIndex: Int, maxWidthPx: Int) -> Int, +): OverflowRowPacking { + // Pinned slots are always placed, so a pinned slot LATER in the strip still has to be reserved for + // before an earlier collapsible one is admitted. Measuring them up front is what makes that + // reservation possible without measuring the collapsible tail. + val pinnedWidths = HashMap(slots.size) + slots.forEachIndexed { slotIndex, slot -> + if (slot.kind == OverflowSlotKind.Pinned) { + pinnedWidths[slotIndex] = slotWidthPx(slotIndex, OVERFLOW_WIDTH_UNBOUNDED) + } + } + // What every slot from here on is already owed: a pinned slot's measured width (it is always placed), + // and a flexible gap's floor (it never closes below it). Charged against each admission so an earlier + // control cannot take room its successors have a claim on. One spacing per pinned slot over-reserves + // by at most a single gap - an exact figure would need the placed set, which is what this decides. + val reservedWidthAfter = IntArray(slots.size + 1) + for (slotIndex in slots.indices.reversed()) { + val slot = slots[slotIndex] + val pinnedWidth = pinnedWidths[slotIndex] ?: 0 + val ownReserve = + when { + slot.kind == OverflowSlotKind.Flexible -> slot.minWidthPx + pinnedWidth > 0 -> pinnedWidth + spacingPx + else -> 0 + } + reservedWidthAfter[slotIndex] = reservedWidthAfter[slotIndex + 1] + ownReserve + } + + // Walked twice at most. The first walk reserves NOTHING for the overflow chip, because a strip whose + // controls all fit shows no chip and must not be charged for one - reserving unconditionally collapsed + // the last control roughly a chip early, with visible slack still in the flexible gaps. If that walk + // collapses nothing, it is the answer. If it collapses something, the chip is needed for certain, so + // the second walk charges for it; that can only push MORE out, never bring the set back to "everything + // fits", so the two walks cannot disagree about whether a chip exists and the strip cannot oscillate. + val withoutChip = walkStrip(slots, availableWidthPx, boundedWidth, spacingPx, 0, preCollapsedSlotIndices, reservedWidthAfter, pinnedWidths, slotWidthPx) + val walk = + if (withoutChip.collapsedSlotIndices.isEmpty() || overflowButtonWidthPx == 0) { + withoutChip + } else { + walkStrip( + slots, + availableWidthPx, + boundedWidth, + spacingPx, + overflowButtonWidthPx, + preCollapsedSlotIndices, + reservedWidthAfter, + pinnedWidths, + slotWidthPx, + ) + } + + val placedIndices = walk.placedIndices + val placedWidths = walk.placedWidths + val collapsedSlotIndices = walk.collapsedSlotIndices + // The reserved chip width returns to the flexible gaps whenever nothing actually collapsed. + val overflowReservePx = + if (collapsedSlotIndices.isEmpty()) { + 0 + } else { + overflowButtonWidthPx + spacingPx + } + val leftoverPx = + if (boundedWidth) { + (availableWidthPx - walk.usedPx - overflowReservePx).coerceAtLeast(0) + } else { + 0 + } + distributeFlexibleWidths(slots, placedIndices, placedWidths, leftoverPx) + + val placements = mutableListOf() + var xPx = 0 + var previousPlacedWasFlexible = false + placedIndices.forEachIndexed { placedIndex, slotIndex -> + val isFlexible = slots[slotIndex].kind == OverflowSlotKind.Flexible + if (placedIndex > 0 && !previousPlacedWasFlexible && !isFlexible) { + xPx += spacingPx + } + placements.add(OverflowPlacement(slotIndex = slotIndex, xPx = xPx, widthPx = placedWidths[placedIndex])) + xPx += placedWidths[placedIndex] + previousPlacedWasFlexible = isFlexible + } + + val overflowButtonXPx = + if (collapsedSlotIndices.isEmpty()) { + null + } else { + (availableWidthPx - overflowButtonWidthPx).coerceAtLeast(0) + } + val contentWidthPx = maxOf(xPx, overflowButtonXPx?.plus(overflowButtonWidthPx) ?: 0) + return OverflowRowPacking( + placements = placements, + collapsedSlotIndices = collapsedSlotIndices, + overflowButtonXPx = overflowButtonXPx, + contentWidthPx = contentWidthPx, + ) +} + +/** + * One walk's outcome, before the flexible gaps are sized and the slots are positioned. + * + * @property MutableList placedIndices The placed slots, in declaration order. + * @property MutableList placedWidths Each placed slot's width, parallel to [placedIndices]. + * @property MutableList collapsedSlotIndices The slots that did not fit. + * @property Int usedPx The width the placed slots and their spacing consumed. + */ +private class StripWalk( + val placedIndices: MutableList, + val placedWidths: MutableList, + val collapsedSlotIndices: MutableList, + val usedPx: Int, +) + +/** + * Admits slots left to right against a budget, collapsing from the first one that does not fit. + * + * A slot declaring [OverflowSlotSpec.minWidthPx] is offered the room actually left rather than measured + * unbounded, so it compresses toward its floor instead of collapsing the moment its natural width stops + * fitting - a 160.dp search box has most of its width to give up before vanishing is the right answer. + * Below the floor it collapses like anything else. + * + * @param List slots The declared slots, in declaration order. + * @param Int availableWidthPx The strip's width. + * @param Boolean boundedWidth False when the strip has no real width, so nothing collapses. + * @param Int spacingPx The gap between two adjacent placed slots. + * @param Int reservedForChipPx Width held back for the trailing overflow chip. + * @param Set preCollapsedSlotIndices Collapsible slots an earlier pass already ruled out. + * @param IntArray reservedWidthAfter Width already owed at or after each index - pinned slots' widths + * and flexible gaps' floors - so an earlier control cannot take room its successors have a claim on. + * @param Map pinnedWidths The pinned slots' already-measured widths. + * @param Function slotWidthPx Measures one slot at a given maximum width. + * @return StripWalk What was placed, what collapsed, and how much width it took. + */ +private fun walkStrip( + slots: List, + availableWidthPx: Int, + boundedWidth: Boolean, + spacingPx: Int, + reservedForChipPx: Int, + preCollapsedSlotIndices: Set, + reservedWidthAfter: IntArray, + pinnedWidths: Map, + slotWidthPx: (slotIndex: Int, maxWidthPx: Int) -> Int, +): StripWalk { + val budgetPx = (availableWidthPx - reservedForChipPx).coerceAtLeast(0) + val placedIndices = mutableListOf() + val placedWidths = mutableListOf() + val collapsedSlotIndices = mutableListOf() + var usedPx = 0 + var previousWasFlexible = false + var anythingPlaced = false + var collapsing = false + + slots.forEachIndexed { slotIndex, slot -> + if (slot.kind == OverflowSlotKind.Flexible) { + // Placed at its floor, not at zero: the floor is the gap's guaranteed separation, so it has to be + // spent here where it counts against what the controls beside it may take. Any leftover is added + // on top afterwards. A zero-floor gap behaves exactly as before. + placedIndices.add(slotIndex) + placedWidths.add(slot.minWidthPx) + usedPx += slot.minWidthPx + previousWasFlexible = true + anythingPlaced = true + return@forEachIndexed + } + // Past the collapse point no further COLLAPSIBLE slot is even measured: composing a control only to + // hide it is the cost this packer exists to avoid. A pinned slot still goes through - the latch + // governs what may be dropped, and a pinned slot may not. + if (slot.kind == OverflowSlotKind.Collapsible && (collapsing || slotIndex in preCollapsedSlotIndices)) { + collapsing = true + collapsedSlotIndices.add(slotIndex) + return@forEachIndexed + } + // A flexible gap IS the separation, so it suppresses spacing on both sides. + val leadingSpacingPx = + if (anythingPlaced && !previousWasFlexible) { + spacingPx + } else { + 0 + } + val roomPx = budgetPx - usedPx - leadingSpacingPx - reservedWidthAfter[slotIndex + 1] + val compressible = slot.kind == OverflowSlotKind.Collapsible && boundedWidth && slot.minWidthPx > 0 + if (compressible && roomPx < slot.minWidthPx) { + collapsing = true + collapsedSlotIndices.add(slotIndex) + return@forEachIndexed + } + // A compressible slot is offered the room left AFTER the controls behind it, so it gives up width to + // keep them on the strip rather than taking its natural width and pushing them into the dropdown - a + // search box narrowing is a far better trade than a filter chip vanishing. It never yields below its + // own floor; past that the tail collapses as usual. Costing the tail means measuring it early, which + // is the one place this packer gives up laziness - bounded by the handful of controls a strip carries. + val measureMaxPx = + if (compressible) { + maxOf(slot.minWidthPx, roomPx - collapsibleTailWidthPx(slots, slotIndex, spacingPx, preCollapsedSlotIndices, slotWidthPx)) + } else { + OVERFLOW_WIDTH_UNBOUNDED + } + val width = pinnedWidths[slotIndex] ?: slotWidthPx(slotIndex, measureMaxPx) + if (width == 0) { + return@forEachIndexed + } + if (slot.kind == OverflowSlotKind.Collapsible && boundedWidth && !compressible && width > roomPx) { + collapsing = true + collapsedSlotIndices.add(slotIndex) + return@forEachIndexed + } + placedIndices.add(slotIndex) + placedWidths.add(width) + usedPx += leadingSpacingPx + width + previousWasFlexible = false + anythingPlaced = true + } + return StripWalk(placedIndices, placedWidths, collapsedSlotIndices, usedPx) +} + +/** + * The width the collapsible controls declared AFTER [slotIndex] need, so a compressible slot can leave + * room for them instead of taking its natural width and pushing them off the strip. + * + * Only non-compressible slots count: a second compressible slot could give up width of its own, so + * charging its natural width here would make the first one yield more than it has to. + * + * @param List slots The declared slots, in declaration order. + * @param Int slotIndex The compressible slot the tail is being costed for. + * @param Int spacingPx The gap between two adjacent placed slots. + * @param Set preCollapsedSlotIndices Slots an earlier pass already ruled out; they cost nothing. + * @param Function slotWidthPx Measures one slot at a given maximum width. + * @return Int The tail's width including the gap in front of each entry. + */ +private fun collapsibleTailWidthPx( + slots: List, + slotIndex: Int, + spacingPx: Int, + preCollapsedSlotIndices: Set, + slotWidthPx: (slotIndex: Int, maxWidthPx: Int) -> Int, +): Int { + var tailPx = 0 + for (laterIndex in slotIndex + 1 until slots.size) { + val later = slots[laterIndex] + if (later.kind != OverflowSlotKind.Collapsible || later.minWidthPx > 0 || laterIndex in preCollapsedSlotIndices) { + continue + } + val laterWidth = slotWidthPx(laterIndex, OVERFLOW_WIDTH_UNBOUNDED) + if (laterWidth > 0) { + tailPx += laterWidth + spacingPx + } + } + return tailPx +} + +/** + * Shares [leftoverPx] out across the placed flexible gaps in proportion to their weights, writing the + * results back into [placedWidths]. Largest-remainder rather than plain rounding, so the parts sum to + * exactly the leftover and the strip's right edge lands where the caller expects it to. + * + * @param List slots The declared slots, for their kinds and weights. + * @param List placedIndices The slot index behind each entry of [placedWidths]. + * @param MutableList placedWidths The resolved widths, mutated in place. + * @param Int leftoverPx The width to share out. + */ +private fun distributeFlexibleWidths( + slots: List, + placedIndices: List, + placedWidths: MutableList, + leftoverPx: Int, +) { + if (leftoverPx <= 0) { + return + } + val flexiblePositions = + placedIndices.indices.filter { position -> + val slot = slots[placedIndices[position]] + slot.kind == OverflowSlotKind.Flexible && slot.weight > 0f + } + if (flexiblePositions.isEmpty()) { + return + } + val totalWeight = flexiblePositions.sumOf { position -> slots[placedIndices[position]].weight.toDouble() } + var assignedPx = 0 + val fractions = DoubleArray(flexiblePositions.size) + flexiblePositions.forEachIndexed { flexibleIndex, position -> + val exact = leftoverPx * slots[placedIndices[position]].weight / totalWeight + val whole = exact.toInt() + // Added to the floor the walk already spent, not written over it - the leftover is what is free + // BEYOND the floors, so overwriting would hand the floor's own pixels out a second time. + placedWidths[position] = placedWidths[position] + whole + fractions[flexibleIndex] = exact - whole + assignedPx += whole + } + // Hand the rounding remainder to the largest fractional parts, earliest gap first on a tie. + val byLargestFraction = flexiblePositions.indices.sortedWith(compareByDescending { fractions[it] }.thenBy { it }) + var remainderPx = leftoverPx - assignedPx + var cursor = 0 + while (remainderPx > 0 && byLargestFraction.isNotEmpty()) { + val position = flexiblePositions[byLargestFraction[cursor % byLargestFraction.size]] + placedWidths[position] = placedWidths[position] + 1 + remainderPx -= 1 + cursor += 1 + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Pad2D.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Pad2D.kt new file mode 100644 index 0000000..f9f3e24 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Pad2D.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors + +/** + * A flat, draggable 2D pad for a LINKED ("combined") parameter pair: a recessed square drawing a + * nine-point reference grid plus a single handle, set by tap or drag anywhere on the control. The X axis + * runs left to right over [xRange]; the Y axis runs bottom to top over [yRange] - screen-top is the + * maximum, matching how Cubism orients its combined-parameter pad. The control is sized entirely by + * [modifier]: supply both a width and a bounded height (e.g. + * `Modifier.fillMaxWidth().heightIn(max = 200.dp)`), because a Canvas otherwise expands to fill all the + * space offered - inside a scrolling column that would overrun the rows beneath it. The grid and handle + * scale to whatever rectangle results, so a non-square pad is fine (each axis maps independently). + * + * 2D パッド(リンクパラメータ対用)。X は左右、Y は下上(上端が最大)。大きさは [modifier] で指定(幅と高さの上限)。 + * + * [onChange] streams the live (X, Y) for every tap / drag frame; [onChangeFinished] fires once at the + * gesture boundary (tap, drag release, or cancel), so a whole drag can be committed as one gesture. + * + * @param Float xValue The current X-axis value. + * @param Float yValue The current Y-axis value. + * @param Function onChange Called with (newX, newY) on each tap / drag frame (the preview). + * @param Modifier modifier Layout modifier (supply the width and a bounded height). + * @param Function onChangeFinished Called once when the gesture ends (tap, drag release, or cancel). + * @param ClosedFloatingPointRange xRange The X-axis min..max range. + * @param ClosedFloatingPointRange yRange The Y-axis min..max range. + */ +@Composable +fun Pad2D( + xValue: Float, + yValue: Float, + onChange: (Float, Float) -> Unit, + modifier: Modifier = Modifier, + onChangeFinished: () -> Unit = {}, + xRange: ClosedFloatingPointRange = 0f..1f, + yRange: ClosedFloatingPointRange = 0f..1f, +) { + val colors = LocalUmamoColors.current + val xSpan = (xRange.endInclusive - xRange.start).takeIf { it != 0f } ?: 1f + val ySpan = (yRange.endInclusive - yRange.start).takeIf { it != 0f } ?: 1f + val xFraction = ((xValue - xRange.start) / xSpan).coerceIn(0f, 1f) + // Y is inverted: the maximum sits at the top, so a value fraction of 1 maps to screen y = 0. + val yFractionFromTop = 1f - ((yValue - yRange.start) / ySpan).coerceIn(0f, 1f) + val trackColor = colors.sliderTrack + val borderColor = colors.controlBorder + val gridColor = colors.guideLine + val crossColor = colors.divider + val handleColor = colors.sliderThumb + val handleRingColor = colors.accent + // pointerInput is keyed only on the ranges, so it does not restart when a recomposition hands in a new + // onChange (a reused list slot binding to a different pair). Read the latest through this so a drag + // always drives the current pair, never the one that first occupied the slot. + val currentOnChange by rememberUpdatedState(onChange) + val currentOnChangeFinished by rememberUpdatedState(onChangeFinished) + Canvas( + modifier = + modifier + .aspectRatio(1.5f) + .pointerInput(xRange, yRange) { + detectTapGestures { offset -> + currentOnChange( + valueAt(offset.x, size.width.toFloat(), xRange, invert = false), + valueAt(offset.y, size.height.toFloat(), yRange, invert = true), + ) + currentOnChangeFinished() + } + } + .pointerInput(xRange, yRange) { + detectDragGestures( + onDragEnd = { currentOnChangeFinished() }, + onDragCancel = { currentOnChangeFinished() }, + ) { change, _ -> + change.consume() + currentOnChange( + valueAt(change.position.x, size.width.toFloat(), xRange, invert = false), + valueAt(change.position.y, size.height.toFloat(), yRange, invert = true), + ) + } + }, + ) { + val padWidth = size.width + val padHeight = size.height + drawRect(color = trackColor, size = Size(padWidth, padHeight)) + drawRect(color = borderColor, size = Size(padWidth, padHeight), style = Stroke(width = 1.dp.toPx())) + // A faint center cross for orientation; the thirds would over-clutter, so the center is enough. + drawLine(crossColor, Offset(padWidth / 2f, 0f), Offset(padWidth / 2f, padHeight), strokeWidth = 1.dp.toPx()) + drawLine(crossColor, Offset(0f, padHeight / 2f), Offset(padWidth, padHeight / 2f), strokeWidth = 1.dp.toPx()) + // Nine reference dots at the 0 / 0.5 / 1 grid intersections on each axis. + val dotRadius = 1.5.dp.toPx() + for (gridRow in 0..2) { + for (gridColumn in 0..2) { + val center = Offset(padWidth * gridColumn / 2f, padHeight * gridRow / 2f) + drawCircle(color = gridColor, radius = dotRadius, center = center) + } + } + // The handle at the current value (X across, Y measured from the top). + val handleCenter = + Offset( + (padWidth * xFraction).coerceIn(0f, padWidth), + (padHeight * yFractionFromTop).coerceIn(0f, padHeight), + ) + drawCircle(color = handleColor, radius = 5.dp.toPx(), center = handleCenter) + drawCircle( + color = handleRingColor, + radius = 5.dp.toPx(), + center = handleCenter, + style = Stroke(width = 1.5.dp.toPx()), + ) + } +} + +/** + * Maps a pointer coordinate within [extent] onto [range], clamped to the ends. When [invert] is set the + * axis is flipped so coordinate 0 (the top of a Canvas) becomes the range maximum - used for the Y axis, + * where screen-top should read as the highest value. + * + * @param Float coordinate The pointer position along the axis (x or y). + * @param Float extent The axis length in pixels (width or height). + * @param ClosedFloatingPointRange range The min..max value range. + * @param Boolean invert When true, flip so coordinate 0 maps to the range maximum. + * @return Float The clamped value for that coordinate. + */ +private fun valueAt( + coordinate: Float, + extent: Float, + range: ClosedFloatingPointRange, + invert: Boolean, +): Float { + val safeExtent = extent.takeIf { it > 0f } ?: 1f + val rawFraction = (coordinate / safeExtent).coerceIn(0f, 1f) + val fraction = + if (invert) { + 1f - rawFraction + } else { + rawFraction + } + return range.start + fraction * (range.endInclusive - range.start) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Panel.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Panel.kt new file mode 100644 index 0000000..2381cc4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Panel.kt @@ -0,0 +1,92 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A thin-bordered panel with a header bar (title on the left, an optional [headerAction] on the right) over a + * tight content column. + * + * @param String title The header title. + * @param Modifier modifier Layout modifier. + * @param Function headerAction Optional trailing header content (e.g. a [Button]). + * @param Function content The panel body. + */ +@Composable +fun Panel( + title: String, + modifier: Modifier = Modifier, + headerAction: (@Composable () -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit, +) { + val colors = LocalUmamoColors.current + Column(modifier = modifier.border(1.dp, colors.panelBorder).background(colors.panelBackground)) { + Row( + modifier = + Modifier.fillMaxWidth().background(colors.headerBackground) + .padding(horizontal = 6.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text = title, style = LocalUmamoTypography.current.labelLarge) + Spacer(modifier = Modifier.weight(1f)) + headerAction?.invoke() + } + Column(modifier = Modifier.padding(6.dp), content = content) + } +} + +/** + * A disclosure row: a small chevron (right when collapsed, down when expanded) plus a label, the whole row + * clickable to [onToggle], with a hover highlight. + * + * @param String label The section label. + * @param Boolean expanded Whether the section is open. + * @param Function onToggle Toggle callback. + * @param Modifier modifier Layout modifier (e.g. a leading indent for a nested section). + */ +@Composable +fun SectionHeader(label: String, expanded: Boolean, onToggle: () -> Unit, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + Row( + modifier = + modifier + .fillMaxWidth() + .height(22.dp) + .background(if (hovered) colors.rowHover else Color.Transparent) + // NOT focusable: a header can sit in chrome that leaves the composition on the next edit (the + // operation settings strip, a Properties section that hides when its rows go), and Compose + // leaves focus null when the focused node is disposed - every keyboard shortcut then dies + // until something focusable is clicked again. The keyboard belongs to the shell root. + .focusProperties { canFocus = false } + .clickable(interactionSource = interaction, indication = null, onClick = onToggle) + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + DisclosureChevron(expanded = expanded, tint = colors.text, glyphSize = 10.dp) + Spacer(modifier = Modifier.width(5.dp)) + Text(text = label, style = LocalUmamoTypography.current.labelMedium) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/PieMenu.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/PieMenu.kt new file mode 100644 index 0000000..668bd0b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/PieMenu.kt @@ -0,0 +1,354 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.layout +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.roundToInt +import kotlin.math.sin + +/** + * One radial pie-menu entry. Entries dispatch through the command registry (the action-registry + * guardrail - the pie never hardcodes a handler), so a rebind or palette invocation of the same + * command behaves identically. + * + * パイメニューの1項目。コマンドレジストリ経由で実行される。 + * + * @property String commandId The command to invoke when picked. + * @property StringResource label The entry's localized label. + * @property Any? argument Optional argument forwarded to the command handler. + * @property Boolean enabled False renders the entry dimmed and refuses the pick. + * @property UmamoIcon? icon The entry's leading icon; null renders the bright-pink placeholder + * square, a deliberately loud reminder that the entry still needs an authored icon. + */ +data class PieMenuEntry( + val commandId: String, + val label: StringResource, + val argument: Any? = null, + val enabled: Boolean = true, + val icon: UmamoIcon? = null, +) + +// Blender's slot order for up to eight pie entries: W, E, S, N, NW, NE, SW, SE - the first entries +// land on the cardinal directions, so a four-entry pie reads as a clean compass. Angles are radians +// in screen space (y down). +private val PIE_SLOT_ANGLES = + floatArrayOf( + PI.toFloat(), // W + 0f, // E + (PI / 2).toFloat(), // S + (-PI / 2).toFloat(), // N + (-3 * PI / 4).toFloat(), // NW + (-PI / 4).toFloat(), // NE + (3 * PI / 4).toFloat(), // SW + (PI / 4).toFloat(), // SE + ) + +/** The ring radius the entry chips sit on. */ +private val PIE_RADIUS = 96.dp + +/** How far past the chip ring the wedge background disc extends. */ +private val PIE_DISC_OVERSHOOT = 40.dp + +/** The entry chips' leading icon size (the pink placeholder square shares it). */ +private val PIE_ICON_SIZE = 12.dp + +/** + * The horizontal half-extent reserved for a West / East chip when clamping the pie center: the chips + * sit centered ON the ring, so the ring radius plus this covers the widest labels. Conservative - a + * pathological label still has the per-chip coercion as its safety net. + */ +private val PIE_CHIP_MAX_HALF_WIDTH = 120.dp + +/** Pointer travel (px) from the pie center below which a release dismisses instead of picking. */ +private const val PIE_DEAD_ZONE_PX = 24f + +/** The placeholder tint for an entry with no authored icon yet - deliberately loud (see PieMenuEntry.icon). */ +private val PIE_ICON_PLACEHOLDER = Color(0xFFFF2BD6) + +/** + * A Blender-style radial pie menu centered at [center]: up to eight entries on a ring, picked by + * DIRECTION from the center (not chip bounds), so a coarse flick works as well as a precise click - + * and the same gesture works for press-drag-release (pen-friendly; the future pen radial menu reuses + * this component). A click (or release) inside the dead zone, or on a disabled entry's direction, + * dismisses without invoking. Escape is the shell's to route (it closes the pie via the session + * latch), and so are the 1..N instant digit picks; this composable only handles pointer input. + * + * The wedge background disc makes the direction mapping readable: each entry's sector is the exact + * angular region the pick function resolves to it (the angular Voronoi of the used slot directions), + * with the hovered sector highlighted; the dead zone renders as the center disc, holding [title]. + * + * The center is CLAMPED so the full ring fits inside the overlay's bounds (Blender constrains its + * pies to the screen the same way): the whole pie shifts inward rather than squishing chips at an + * edge. The clamp lives here - not in the host - because the direction pick, the wedges, the title, + * and the chips must all share the one effective center or the pick math desyncs from the drawing. + * + * Blender 風の放射状パイメニュー。方向で選択するため、クリックでもドラッグ&リリースでも使える。 + * 扇形の背景が方向と項目の対応を示し、中央の円にタイトルが乗る。中心はリング全体が収まるよう + * オーバーレイ境界内にクランプされる。 + * + * @param List entries The entries, in Blender slot order (W, E, S, N, NW, NE, SW, SE). + * @param Offset center The requested pie center in the host's local pixels (frozen at open by the + * host); the rendered center is this clamped inside the overlay so the ring never clips. + * @param Function onDismiss Called after an invocation or a dismissing click. + * @param StringResource? title The pie's name, rendered at the center (null for none). + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +fun PieMenuOverlay( + entries: List, + center: Offset, + onDismiss: () -> Unit, + title: StringResource? = null, + modifier: Modifier = Modifier, +) { + val commands = LocalCommands.current + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val density = LocalDensity.current + val liveEntries = rememberUpdatedState(entries) + var hoveredSlot by remember { mutableStateOf(-1) } + + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + // The center everything draws and picks from: [center] shifted so the full ring - disc + // vertically, ring plus the widest chip horizontally - fits inside these bounds. An overlay + // too small to fit the pie at all centers it instead (coerceIn would throw on min > max). + val effectiveCenter = + with(density) { + val horizontalMargin = PIE_RADIUS.toPx() + PIE_CHIP_MAX_HALF_WIDTH.toPx() + val verticalMargin = PIE_RADIUS.toPx() + PIE_DISC_OVERSHOOT.toPx() + val boundsWidth = constraints.maxWidth.toFloat() + val boundsHeight = constraints.maxHeight.toFloat() + Offset( + if (boundsWidth >= 2f * horizontalMargin) center.x.coerceIn(horizontalMargin, boundsWidth - horizontalMargin) else boundsWidth / 2f, + if (boundsHeight >= 2f * verticalMargin) center.y.coerceIn(verticalMargin, boundsHeight - verticalMargin) else boundsHeight / 2f, + ) + } + // The pointer loop below outlives recompositions (pointerInput(Unit)), so it must read the + // center through a live reference - a window resize while the pie is open moves the clamp. + val liveCenter = rememberUpdatedState(effectiveCenter) + + /** + * Picks the entry slot whose direction is nearest the pointer's direction from the center. + * + * @param Offset position The pointer position in the overlay's coordinates. + * @return Int The nearest slot index, or -1 inside the dead zone. + */ + fun slotAt(position: Offset): Int { + val delta = position - liveCenter.value + if (delta.getDistance() < PIE_DEAD_ZONE_PX) { + return -1 + } + val pointerAngle = atan2(delta.y, delta.x) + var best = -1 + var bestDifference = Float.MAX_VALUE + for (slotIndex in liveEntries.value.indices) { + var difference = abs(pointerAngle - PIE_SLOT_ANGLES[slotIndex]) + if (difference > PI.toFloat()) { + difference = 2 * PI.toFloat() - difference + } + if (difference < bestDifference) { + bestDifference = difference + best = slotIndex + } + } + return best + } + + Box( + modifier = + Modifier + .fillMaxSize() + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + when (event.type) { + PointerEventType.Move -> hoveredSlot = slotAt(change.position) + + PointerEventType.Release -> { + // Only the release picks: a click and a press-drag-release both end in exactly + // one Release, so one gesture invokes the command exactly once - picking on + // Press as well would double-invoke non-idempotent commands like merge. + // A dead-zone or disabled-direction release dismisses without invoking. + val slotIndex = slotAt(change.position) + val entry = liveEntries.value.getOrNull(slotIndex) + if (entry != null && entry.enabled) { + commands.invoke(entry.commandId, entry.argument) + } + onDismiss() + } + + // A press only anchors the gesture (and is consumed below); its release decides. + PointerEventType.Press -> {} + + else -> {} + } + change.consume() + } + } + }, + ) { + // The wedge background: each used slot's sector spans the midpoints to its angular neighbors - + // exactly the region slotAt() resolves to it - with the hovered sector highlighted and the dead + // zone drawn as the center disc. Drawn beneath the chips so labels stay crisp. + Canvas(modifier = Modifier.fillMaxSize()) { + val outerRadius = PIE_RADIUS.toPx() + PIE_DISC_OVERSHOOT.toPx() + val discTopLeft = Offset(effectiveCenter.x - outerRadius, effectiveCenter.y - outerRadius) + val discSize = Size(outerRadius * 2, outerRadius * 2) + val sortedSlots = entries.indices.sortedBy { slotIndex -> PIE_SLOT_ANGLES[slotIndex] } + for ((sortedPosition, slotIndex) in sortedSlots.withIndex()) { + val slotAngle = PIE_SLOT_ANGLES[slotIndex] + val startDeg: Float + val sweepDeg: Float + if (sortedSlots.size == 1) { + startDeg = 0f + sweepDeg = 360f + } else { + val previousAngle = PIE_SLOT_ANGLES[sortedSlots[(sortedPosition - 1 + sortedSlots.size) % sortedSlots.size]] + val nextAngle = PIE_SLOT_ANGLES[sortedSlots[(sortedPosition + 1) % sortedSlots.size]] + var gapBefore = slotAngle - previousAngle + if (gapBefore <= 0f) { + gapBefore += 2f * PI.toFloat() + } + var gapAfter = nextAngle - slotAngle + if (gapAfter <= 0f) { + gapAfter += 2f * PI.toFloat() + } + startDeg = (slotAngle - gapBefore / 2f) * 180f / PI.toFloat() + sweepDeg = (gapBefore + gapAfter) / 2f * 180f / PI.toFloat() + } + val hovered = slotIndex == hoveredSlot && entries[slotIndex].enabled + drawArc( + color = if (hovered) colors.accent.copy(alpha = 0.25f) else colors.viewportBadgeBackground, + startAngle = startDeg, + sweepAngle = sweepDeg, + useCenter = true, + topLeft = discTopLeft, + size = discSize, + ) + } + // Sector separators, then the dead-zone disc (the dismiss region reads as "no pick"). + if (sortedSlots.size > 1) { + for ((sortedPosition, slotIndex) in sortedSlots.withIndex()) { + val nextAngle = PIE_SLOT_ANGLES[sortedSlots[(sortedPosition + 1) % sortedSlots.size]] + var gapAfter = nextAngle - PIE_SLOT_ANGLES[slotIndex] + if (gapAfter <= 0f) { + gapAfter += 2f * PI.toFloat() + } + val boundary = PIE_SLOT_ANGLES[slotIndex] + gapAfter / 2f + drawLine( + color = colors.panelBorder, + start = effectiveCenter, + end = Offset(effectiveCenter.x + cos(boundary) * outerRadius, effectiveCenter.y + sin(boundary) * outerRadius), + strokeWidth = 1f, + ) + } + } + drawCircle(color = colors.panelBackground, radius = PIE_DEAD_ZONE_PX * 1.6f, center = effectiveCenter) + } + if (title != null) { + Text( + text = stringResource(title), + style = LocalUmamoTypography.current.labelSmall, + color = colors.textMuted, + modifier = + Modifier.layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + layout(constraints.maxWidth, constraints.maxHeight) { + placeable.place( + (effectiveCenter.x - placeable.width / 2f).roundToInt().coerceIn(0, (constraints.maxWidth - placeable.width).coerceAtLeast(0)), + (effectiveCenter.y - placeable.height / 2f).roundToInt().coerceIn(0, (constraints.maxHeight - placeable.height).coerceAtLeast(0)), + ) + } + }, + ) + } + entries.forEachIndexed { slotIndex, entry -> + val angle = PIE_SLOT_ANGLES[slotIndex] + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + Modifier + .layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + layout(constraints.maxWidth, constraints.maxHeight) { + val radiusPx = PIE_RADIUS.toPx() + val slotX = (effectiveCenter.x + cos(angle) * radiusPx - placeable.width / 2f).roundToInt() + val slotY = (effectiveCenter.y + sin(angle) * radiusPx - placeable.height / 2f).roundToInt() + placeable.place( + slotX.coerceIn(0, (constraints.maxWidth - placeable.width).coerceAtLeast(0)), + slotY.coerceIn(0, (constraints.maxHeight - placeable.height).coerceAtLeast(0)), + ) + } + } + .background( + if (slotIndex == hoveredSlot && entry.enabled) colors.accent.copy(alpha = 0.25f) else colors.viewportBadgeBackground, + shapes.small, + ) + .alpha(if (entry.enabled) 1f else 0.4f) + .padding(horizontal = 10.dp, vertical = 5.dp), + ) { + // The leading icon; a missing one renders the loud placeholder square (an authoring reminder). + val entryIcon = entry.icon + Canvas(modifier = Modifier.size(PIE_ICON_SIZE)) { + if (entryIcon != null) { + drawIcon(entryIcon, colors.controlGlyph) + } else { + drawRect(color = PIE_ICON_PLACEHOLDER) + } + } + Spacer(modifier = Modifier.width(6.dp)) + // The instant digit shortcut (the shell's pie key branch maps 1..N to the entry order). + Text( + text = "${slotIndex + 1}", + style = LocalUmamoTypography.current.labelSmall, + color = colors.textMuted, + ) + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = stringResource(entry.label), + style = LocalUmamoTypography.current.labelMedium, + color = if (slotIndex == hoveredSlot && entry.enabled) colors.text else colors.textMuted, + ) + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/PopupChip.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/PopupChip.kt new file mode 100644 index 0000000..f12dd36 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/PopupChip.kt @@ -0,0 +1,108 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupProperties +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.UmamoIcon + +/** + * A [DropdownChip] over a stay-open panel of arbitrary content: only an outside click or Esc dismisses + * it, so several controls can be driven in one visit. That is the whole reason this is a raw [Popup] + * rather than the kit [Menu], which dismisses per click - and the reason [DropdownChip] leaves its + * dropdown a slot in the first place. + * + * The panel provides [LocalPopupDismissOwned], so a [Menu] or nested chip composed inside the content + * yields the dismiss to this popup instead of fighting it for focus. + * + * Open state is optionally hoistable: leave [expanded] null and the chip owns it (the common case), or + * pass it with [onExpandedChange] when the caller has to force the panel shut - the overflow row does, + * since a strip that widens while the panel is open would otherwise leave it anchored to nothing. + * + * @param String contentDescription The accessible label for the chip (the face is icon-only). + * @param Modifier modifier The layout modifier. + * @param UmamoIcon icon The chip's leading glyph, or null for a chevron-only face. + * @param Boolean? expanded The open state when hoisted; null to let the chip own it. + * @param Function? onExpandedChange Open-state sink, required when [expanded] is hoisted. + * @param Boolean enabled When false the chip dims and clicks are inert. + * @param DropdownChipStyle style The face's role: Header chrome by default, Compact for a list row. + * @param Color? iconTint A status color for the glyph at rest, or null for the chip's own content color. + * @param Function content The panel's rows. + */ +@Composable +fun PopupChip( + contentDescription: String, + modifier: Modifier = Modifier, + icon: UmamoIcon? = null, + expanded: Boolean? = null, + onExpandedChange: ((Boolean) -> Unit)? = null, + enabled: Boolean = true, + style: DropdownChipStyle = DropdownChipStyle.Header, + iconTint: Color? = null, + content: @Composable ColumnScope.() -> Unit, +) { + var selfOpen by remember { mutableStateOf(false) } + val open = expanded ?: selfOpen + val setOpen: (Boolean) -> Unit = { next -> + if (onExpandedChange != null) { + onExpandedChange(next) + } else { + selfOpen = next + } + } + DropdownChip( + expanded = open, + onExpandRequest = { setOpen(true) }, + contentDescription = contentDescription, + modifier = modifier, + icon = icon, + enabled = enabled, + style = style, + iconTint = iconTint, + ) { + PopupPanel(onDismissRequest = { setOpen(false) }, content = content) + } +} + +/** + * The stay-open panel a [PopupChip] drops: a raw [Popup] below its anchor, styled like the kit [Menu] + * (the dark panel fill, medium corners) but dismissed only by an outside click or Esc, so several + * controls can be driven in one visit. Composable on its own inside a [DropdownChip] slot, for a chip + * that shows a [Menu] on one visit and a panel on the next (a review chip's relink-by-hand list). + * + * The panel provides [LocalPopupDismissOwned], so a [Menu] or nested chip composed inside the content + * yields the dismiss to this popup instead of fighting it for focus. + * + * @param Function onDismissRequest Called on an outside click or Esc. + * @param Function content The panel's rows. + */ +@Composable +fun PopupPanel(onDismissRequest: () -> Unit, content: @Composable ColumnScope.() -> Unit) { + val colors = LocalUmamoColors.current + Popup( + popupPositionProvider = BelowAnchorPositionProvider, + onDismissRequest = onDismissRequest, + properties = PopupProperties(focusable = true), + ) { + CompositionLocalProvider(LocalPopupDismissOwned provides true) { + Surface(color = colors.menuBackground, shape = LocalUmamoShapes.current.medium) { + // Intrinsic width so the panel hugs its widest row rather than needing a magic dp. + Column(modifier = Modifier.width(IntrinsicSize.Max).padding(vertical = 4.dp), content = content) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/RelationField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/RelationField.kt new file mode 100644 index 0000000..8a732fa --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/RelationField.kt @@ -0,0 +1,357 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupProperties +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** Edge length of the leading type glyph and the trailing affordances inside a relation field. */ +private val RELATION_GLYPH_SIZE = 14.dp + +/** How tall the candidate dropdown may grow before it scrolls. */ +private val RELATION_DROPDOWN_MAX_HEIGHT = 260.dp + +/** The narrowest the dropdown may be, so it stays readable before the anchor has been measured. */ +private val RELATION_DROPDOWN_MIN_WIDTH = 140.dp + +/** + * A Blender-style single relation picker: one box that shows the bound entity and, once focused, doubles + * as the search field for rebinding it. A leading glyph carries the bound entity's type, a trailing "x" + * clears the binding, and a trailing eyedropper (when [onPick] is supplied) hands the pick to the viewport + * or the outliner instead of the list. + * + * `[type glyph] [current relation, or the typed query] [x] [eyedropper]` + * + * Focusing the field swaps its text for an empty query and opens the candidate list; blurring restores the + * bound entity's name. The dropdown is deliberately NON-focusable and its rows decline focus, so clicking + * a row cannot blur the field out from under the click (the classic combo-box race); it closes on commit, + * Escape, or the field losing focus. Up / Down / Enter are intercepted ahead of the field so they navigate + * the list while ordinary typing still reaches it. + * + * Like [NumberField] and [HexColorField] it lends its cancel hook to [LocalInlineEditController] while + * focused, so the shell's root key handler yields keystrokes to the field instead of firing shortcuts. + * + * @param T The candidate entity type. + * @param Object? selected The currently bound entity, or null when unbound. + * @param List candidates Every entity that may be bound, in menu order. + * @param Function label The display name of an entity (also what the search matches). + * @param Function icon The type glyph of an entity. + * @param Function onSelect Binds an entity, or null to clear the binding. + * @param Modifier modifier The layout modifier (the caller supplies the width). + * @param Function? onPick Arms an eyedropper pick, or null to omit the eyedropper. + * @param Boolean picking Whether a pick armed by THIS field is in flight (lights the eyedropper). + * @param String placeholder The muted text shown when nothing is bound. + * @param String clearDescription The accessible label of the clear button (NOT the placeholder - that + * would announce the search prompt as the button's name). + * @param String pickDescription The accessible label of the eyedropper button. + */ +@Composable +fun RelationField( + selected: T?, + candidates: List, + label: (T) -> String, + icon: (T) -> UmamoIcon, + onSelect: (T?) -> Unit, + modifier: Modifier = Modifier, + onPick: (() -> Unit)? = null, + picking: Boolean = false, + placeholder: String = "", + clearDescription: String = "", + pickDescription: String = "", +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val typography = LocalUmamoTypography.current + val controller = LocalInlineEditController.current + val focusManager = LocalFocusManager.current + val density = LocalDensity.current + val listState = rememberLazyListState() + + var focused by remember { mutableStateOf(false) } + var query by remember { mutableStateOf("") } + var highlighted by remember { mutableStateOf(0) } + var anchorWidthPx by remember { mutableStateOf(0) } + + val selectedLabel = selected?.let(label) ?: "" + // The field is a search box while focused and a read-out of the binding otherwise. + val fieldText = if (focused) query else selectedLabel + val filtered = + if (query.isBlank()) { + candidates + } else { + candidates.filter { candidate -> label(candidate).contains(query.trim(), ignoreCase = true) } + } + // Filtering can shrink the list under the highlight, so clamp at read rather than on every edit. + val safeIndex = highlighted.coerceIn(0, maxOf(0, filtered.size - 1)) + val open = focused + + LaunchedEffect(query) { + highlighted = 0 + } + LaunchedEffect(safeIndex, open, filtered.size) { + if (open && filtered.isNotEmpty()) { + listState.scrollToItem(safeIndex) + } + } + // Drop the lent cancel hook if the field disposes while focused (a section switch mid-edit). + DisposableEffect(Unit) { + onDispose { + if (focused) { + controller.cancel = null + } + } + } + + val commit: (T?) -> Unit = { value -> + onSelect(value) + query = "" + // ONLY when this field actually holds focus. The clear "x" is shown while unfocused, and clearing + // focus from there would null the shell root's focus owner - killing every keyboard shortcut until + // Tab traversal reclaims it (the same hazard IconButton.suppressFocus exists to avoid). Blurring a + // focused field is safe: dropping the lent inline-edit hook triggers the shell's focus-reclaim. + if (focused) { + focusManager.clearFocus() + } + } + + Box( + modifier = + modifier + .onSizeChanged { size -> anchorWidthPx = size.width } + // Navigation keys are claimed ahead of the focused field; ordinary typing falls through to it. + .onPreviewKeyEvent { event -> + if (!open || event.type != KeyEventType.KeyDown) { + return@onPreviewKeyEvent false + } + when (event.key) { + Key.DirectionDown -> { + if (filtered.isNotEmpty()) { + highlighted = (safeIndex + 1) % filtered.size + } + true + } + + Key.DirectionUp -> { + if (filtered.isNotEmpty()) { + highlighted = (safeIndex - 1 + filtered.size) % filtered.size + } + true + } + + Key.Enter, Key.NumPadEnter -> { + filtered.getOrNull(safeIndex)?.let { candidate -> commit(candidate) } + true + } + + Key.Escape -> { + query = "" + focusManager.clearFocus() + true + } + + else -> false + } + }, + ) { + Row( + modifier = + Modifier + .fillMaxWidth() + .height(FIELD_CONTROL_HEIGHT) + .clip(shapes.small) + .background(colors.tabBackground) + .border(1.dp, colors.controlBorder, shapes.small) + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + val leadingGlyph = selected?.let(icon) + if (leadingGlyph != null) { + Canvas(modifier = Modifier.size(RELATION_GLYPH_SIZE)) { + drawIcon(leadingGlyph, colors.textMuted) + } + Spacer(modifier = Modifier.width(4.dp)) + } + BasicTextField( + value = fieldText, + onValueChange = { newText -> query = newText }, + textStyle = typography.bodySmall.copy(color = colors.text), + singleLine = true, + cursorBrush = SolidColor(colors.text), + modifier = + Modifier + .weight(1f) + .textEntrySurface(controller) + .onFocusChanged { focusState -> + // hasFocus (not isFocused): BasicTextField focuses an internal child. + if (focusState.hasFocus) { + if (!focused) { + focused = true + query = "" + controller.cancel = { focusManager.clearFocus() } + } + } else if (focused) { + focused = false + query = "" + controller.cancel = null + } + }, + decorationBox = { inner -> + Box(contentAlignment = Alignment.CenterStart) { + if (fieldText.isEmpty()) { + Text( + text = placeholder, + style = typography.bodySmall, + color = colors.textMuted, + maxLines = 1, + ) + } + inner() + } + }, + ) + if (selected != null && !focused) { + IconButton( + icon = LocalUmamoIcons.close, + onClick = { commit(null) }, + contentDescription = clearDescription, + size = DpSize(16.dp, 16.dp), + glyphSize = 12.dp, + ) + } + if (onPick != null) { + IconButton( + icon = LocalUmamoIcons.eyedropper, + onClick = onPick, + contentDescription = pickDescription, + size = DpSize(16.dp, 16.dp), + glyphSize = 12.dp, + active = picking, + ) + } + } + if (open) { + val anchorWidth = with(density) { anchorWidthPx.toDp() } + Popup( + popupPositionProvider = BelowAnchorPositionProvider, + onDismissRequest = { focusManager.clearFocus() }, + // NOT focusable: a focusable popup would blur the search field the moment it opened. + properties = PopupProperties(focusable = false), + ) { + Surface(color = colors.menuBackground, shape = shapes.medium) { + Box { + // Pinned to the field's own width: a LazyColumn fills whatever max width it is handed, + // and inside a popup that is the whole window, so an unbounded one spans the screen. + LazyColumn( + state = listState, + modifier = + Modifier + .width(anchorWidth.coerceAtLeast(RELATION_DROPDOWN_MIN_WIDTH)) + .heightIn(max = RELATION_DROPDOWN_MAX_HEIGHT) + .padding(vertical = 2.dp), + ) { + itemsIndexed(filtered) { index, candidate -> + RelationCandidateRow( + label = label(candidate), + icon = icon(candidate), + highlighted = index == safeIndex, + onClick = { commit(candidate) }, + ) + } + } + // matchParentSize keeps the scrollbar a pure overlay - it fills this box rather than the + // popup's window-sized constraints, so it cannot inflate the dropdown to full height. + Box(modifier = Modifier.matchParentSize()) { + VerticalScrollbarOverlay(listState) + } + } + } + } + } + } +} + +/** + * One candidate row in a [RelationField]'s dropdown: the entity's type glyph and name, lit when it is the + * keyboard highlight. The row declines focus so clicking it cannot blur the search field out from under + * the click, which would tear the popup down before the click resolved. + * + * @param String label The entity's display name. + * @param UmamoIcon icon The entity's type glyph. + * @param Boolean highlighted Whether this row is the current keyboard highlight. + * @param Function onClick Binds this candidate. + */ +@Composable +private fun RelationCandidateRow(label: String, icon: UmamoIcon, highlighted: Boolean, onClick: () -> Unit) { + val colors = LocalUmamoColors.current + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp, vertical = 1.dp) + .focusProperties { canFocus = false } + .clickable(onClick = onClick) + .background( + color = if (highlighted) colors.rowHover else Color.Transparent, + shape = LocalUmamoShapes.current.small, + ) + .padding(horizontal = 4.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Canvas(modifier = Modifier.size(RELATION_GLYPH_SIZE)) { + drawIcon(icon, colors.textMuted) + } + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = label, + style = LocalUmamoTypography.current.bodySmall, + color = colors.text, + maxLines = 1, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/RelationListField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/RelationListField.kt new file mode 100644 index 0000000..d53c2aa --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/RelationListField.kt @@ -0,0 +1,229 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.DraggableState +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.draggable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** Edge length of a bound row's type glyph, matching [RelationField]'s. */ +private val RELATION_ROW_GLYPH_SIZE = 14.dp + +/** The bound-list height a relation list opens at. */ +private val RELATION_LIST_DEFAULT_HEIGHT = 76.dp + +/** The shortest the bound list may be dragged (about two rows). */ +private val RELATION_LIST_MIN_HEIGHT = 44.dp + +/** The tallest the bound list may be dragged. */ +private val RELATION_LIST_MAX_HEIGHT = 320.dp + +/** The grab handle's strip height at the bottom of the bound list. */ +private val RELATION_GRIP_HEIGHT = 10.dp + +/** + * The multi-value sibling of [RelationField]: a scrollable list of bound entities, each row carrying its + * type glyph, its name, and a remove button, over an add field that searches the remaining candidates and + * offers the same eyedropper. A grab handle under the list drags its height, so a long list can be given + * room without the whole panel growing. + * + * The bound list is a set, not a sequence - for clip masks the order does not affect coverage - so rows are + * not reorderable. + * + * @param T The bound entity type. + * @param List entries The currently bound entities, in display order. + * @param List candidates The entities the add field offers (the caller excludes those already bound). + * @param Function label The display name of an entity (also what the add field's search matches). + * @param Function keyOf The entity's STABLE identity, used to key its row. Not the label: a display name + * comes from the source art and is not unique (a PSD routinely holds several "Layer 1"), so keying on it + * would let two rows share one key and reuse each other's per-row state. + * @param Function icon The type glyph of an entity. + * @param Function onAdd Binds an entity. + * @param Function onRemove Unbinds an entity. + * @param Modifier modifier The layout modifier. + * @param Function? onPick Arms an eyedropper pick, or null to omit the eyedropper. + * @param Boolean picking Whether a pick armed by THIS field is in flight. + * @param String addPlaceholder The muted text shown in the empty add field. + * @param String emptyLabel The muted text shown when nothing is bound. + * @param String removeDescription The accessible label of a row's remove button. + * @param String pickDescription The accessible label of the add field's eyedropper. + * @param Dp? height The list's height when the caller holds it, or null for the list to hold its own. The list + * leaves the composition whenever its row does (a tab change, a folded section, another selection), so only a + * caller-held height survives that. + * @param Function? onHeightChange Receives each dragged height, for a caller that holds it. + */ +@Composable +fun RelationListField( + entries: List, + candidates: List, + label: (T) -> String, + keyOf: (T) -> Any, + icon: (T) -> UmamoIcon, + onAdd: (T) -> Unit, + onRemove: (T) -> Unit, + modifier: Modifier = Modifier, + onPick: (() -> Unit)? = null, + picking: Boolean = false, + addPlaceholder: String = "", + emptyLabel: String = "", + removeDescription: String = "", + pickDescription: String = "", + height: Dp? = null, + onHeightChange: ((Dp) -> Unit)? = null, +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val typography = LocalUmamoTypography.current + val density = LocalDensity.current + val scrollState = rememberScrollState() + var ownHeight by remember { mutableStateOf(RELATION_LIST_DEFAULT_HEIGHT) } + val listHeight = (height ?: ownHeight).coerceIn(RELATION_LIST_MIN_HEIGHT, RELATION_LIST_MAX_HEIGHT) + // The drag state is built once, so it reads the height and the callback through these rather than capturing + // the first composition's. + val latestHeight by rememberUpdatedState(listHeight) + val latestOnHeightChange by rememberUpdatedState(onHeightChange) + // The grip drags the list's own height; the panel around it is untouched (this is not an area splitter). + val dragState = + remember { + DraggableState { deltaPx -> + val delta = with(density) { deltaPx.toDp() } + val dragged = (latestHeight + delta).coerceIn(RELATION_LIST_MIN_HEIGHT, RELATION_LIST_MAX_HEIGHT) + ownHeight = dragged + latestOnHeightChange?.invoke(dragged) + } + } + + Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + RelationField( + selected = null, + candidates = candidates, + label = label, + icon = icon, + onSelect = { candidate -> candidate?.let(onAdd) }, + modifier = Modifier.fillMaxWidth(), + onPick = onPick, + picking = picking, + placeholder = addPlaceholder, + pickDescription = pickDescription, + ) + Box( + modifier = + Modifier + .fillMaxWidth() + .height(listHeight) + .clip(shapes.small) + .background(colors.tabBackground) + .border(1.dp, colors.controlBorder, shapes.small), + ) { + Column(modifier = Modifier.fillMaxWidth().verticalScroll(scrollState).padding(2.dp)) { + if (entries.isEmpty()) { + Text( + text = emptyLabel, + style = typography.bodySmall, + color = colors.textDisabled, + maxLines = 1, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp), + ) + } else { + for (entry in entries) { + key(keyOf(entry)) { + RelationBoundRow( + label = label(entry), + icon = icon(entry), + removeDescription = removeDescription, + onRemove = { onRemove(entry) }, + ) + } + } + } + } + VerticalScrollbarOverlay(scrollState) + } + // The resize grab handle: Blender puts it under the list, centerd. + Box( + modifier = + Modifier + .fillMaxWidth() + .height(RELATION_GRIP_HEIGHT) + .pointerHoverIcon(PointerIcon.Hand) + .draggable(state = dragState, orientation = Orientation.Vertical), + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.size(RELATION_ROW_GLYPH_SIZE)) { + drawIcon(LocalUmamoIcons.gripHorizontal, colors.textMuted) + } + } + } +} + +/** + * One bound row inside a [RelationListField]: the entity's type glyph and name, with a trailing remove. + * + * @param String label The entity's display name. + * @param UmamoIcon icon The entity's type glyph. + * @param String removeDescription The accessible label of the remove button. + * @param Function onRemove Unbinds this entity. + */ +@Composable +private fun RelationBoundRow(label: String, icon: UmamoIcon, removeDescription: String, onRemove: () -> Unit) { + val colors = LocalUmamoColors.current + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 1.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Canvas(modifier = Modifier.size(RELATION_ROW_GLYPH_SIZE)) { + drawIcon(icon, colors.textMuted) + } + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = label, + style = LocalUmamoTypography.current.bodySmall, + color = colors.text, + maxLines = 1, + modifier = Modifier.weight(1f), + ) + IconButton( + icon = LocalUmamoIcons.close, + onClick = onRemove, + contentDescription = removeDescription, + size = DpSize(16.dp, 16.dp), + glyphSize = 12.dp, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Scrollbar.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Scrollbar.kt new file mode 100644 index 0000000..4b0fc7c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Scrollbar.kt @@ -0,0 +1,51 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.Composable +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +/** + * The thickness every scrollbar in the editor draws at. + * + * Shared rather than restated per bar: a scrollbar is a pointer target before it is a decoration, and one + * that is thinner than the others is measurably harder to hit for no reason the user can see. + */ +val SCROLLBAR_THICKNESS: Dp = 8.dp + +/** The shortest a scrollbar thumb may draw, so a long scroll still leaves something to grab. */ +val SCROLLBAR_MIN_THUMB: Dp = 24.dp + +/** The scrollbar thumb's corner radius - a full round on [SCROLLBAR_THICKNESS]. */ +val SCROLLBAR_CORNER_RADIUS: Dp = 4.dp + +/** + * A draggable vertical scrollbar pinned to the right edge of the hosting Box, shown only while the + * [scrollState] can actually scroll (its content overflows the viewport). Overlay sibling of the + * scrolling content; call it after the content inside a Box so it draws on top. + * + * Platform-split: desktop draws Foundation's draggable VerticalScrollbar (those APIs are Compose-Desktop + * only), while Android scrolls by touch with its own overscroll affordance, so the Android actual is a + * deliberate no-op - keeping this overlay callable from shared UI without leaking a desktop-only API. + * + * 右端に固定する縦スクロールバー。デスクトップは Foundation のバー、Android はタッチ操作のため何もしない。 + * + * @param ScrollState scrollState The scroll state of the verticalScroll content to drive and gate on. + */ +@Composable +expect fun BoxScope.VerticalScrollbarOverlay(scrollState: ScrollState) + +/** + * A draggable vertical scrollbar pinned to the right edge of the hosting Box, shown only while the + * [listState] can actually scroll in either direction. Overlay sibling of a LazyColumn; call it after + * the list inside a Box so it draws on top. Platform-split like the [ScrollState] overload: a real bar on + * desktop, a no-op on touch-driven Android. + * + * LazyColumn 用の縦スクロールバー。デスクトップのみ描画、Android はタッチ操作のため何もしない。 + * + * @param LazyListState listState The LazyColumn's state to drive and gate on. + */ +@Composable +expect fun BoxScope.VerticalScrollbarOverlay(listState: LazyListState) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/SearchField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/SearchField.kt new file mode 100644 index 0000000..1725bb8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/SearchField.kt @@ -0,0 +1,70 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons + +/** + * The standard width of a header search box - wide enough for a name, narrow enough to leave the rest + * of the strip room in a tight area. + */ +val SEARCH_FIELD_WIDTH = 160.dp + +/** + * The narrowest a header search box is worth squeezing to: still wide enough to read a few characters and + * the clear affordance beside them. Below this it is better off in the overflow dropdown at full width. + */ +val SEARCH_FIELD_MIN_WIDTH = 72.dp + +/** + * A filter box: a [TextField] with a clear affordance pinned inside its trailing edge, shown only while + * there is text to clear. The X rides the field's trailing slot rather than being overlaid on it, so + * the value and the caret can never run underneath it. + * + * Every panel that filters a list mounts this one component - the outliner and the properties panel both + * did their own copy of the field-plus-X, which is exactly the drift the kit exists to prevent. + * + * @param String value The current query. + * @param Function onValueChange Edit callback; the clear affordance reports an empty string. + * @param Modifier modifier The layout modifier. + * @param Dp width The box's width; [SEARCH_FIELD_WIDTH] unless a caller needs otherwise. + * @param String placeholder The dimmed hint shown while the query is empty. + * @param String clearContentDescription The clear affordance's accessible label and hover tooltip. + */ +@Composable +fun SearchField( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + width: Dp = SEARCH_FIELD_WIDTH, + placeholder: String = stringResource(Res.string.search_hint), + clearContentDescription: String = stringResource(Res.string.search_clear), +) { + TextField( + value = value, + onValueChange = onValueChange, + modifier = modifier.width(width), + placeholder = placeholder, + trailing = + if (value.isEmpty()) { + null + } else { + { + IconButton( + icon = LocalUmamoIcons.close, + onClick = { onValueChange("") }, + contentDescription = clearContentDescription, + size = DpSize(16.dp, 16.dp), + glyphSize = 16.dp, + ) + } + }, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/SelectField.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/SelectField.kt new file mode 100644 index 0000000..34b3f42 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/SelectField.kt @@ -0,0 +1,67 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoIcon + +/** + * A single-choice form dropdown: the current selection's (optional) icon and label shown in a [DropdownChip] + * styled as a field, opening a [Menu] of the options beneath it. The one reusable select control for forms + * - settings rows and the Properties panel share it; the header chips are the same [DropdownChip] in its + * [DropdownChipStyle.Header] role, so there is one chip anatomy, not two. + * + * The popup is forced to at least the chip's own width (measured via [onSizeChanged]) so the option list + * never opens narrower than the field - a value picked near the field's trailing edge stays under the + * pointer instead of requiring an awkward reach. The menu owns its outside-click / Escape dismissal. + * + * @param T selected The currently selected option. + * @param List options The options to choose from, in display order. + * @param Function label Resolves an option to its display string (localized chrome or verbatim data). + * @param Function onSelect Called with the chosen option (a no-op selection of the current value is fine). + * @param Modifier modifier Layout modifier for the field (pass fillMaxWidth to span a form column). + * @param Function? icon Optional per-option leading glyph (e.g. a blend-mode icon), or null for none. + */ +@Composable +fun SelectField( + selected: T, + options: List, + label: (T) -> String, + onSelect: (T) -> Unit, + modifier: Modifier = Modifier, + icon: ((T) -> UmamoIcon?)? = null, +) { + var expanded by remember { mutableStateOf(false) } + var anchorWidth by remember { mutableStateOf(0.dp) } + val density = LocalDensity.current + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = !expanded }, + contentDescription = label(selected), + modifier = modifier.onSizeChanged { size -> anchorWidth = with(density) { size.width.toDp() } }, + icon = icon?.invoke(selected), + label = label(selected), + style = DropdownChipStyle.Field, + ) { + Menu( + items = + options.map { option -> + MenuItem.Action( + label = label(option), + icon = icon?.invoke(option), + onSelect = { onSelect(option) }, + ) + }, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + modifier = Modifier.widthIn(min = anchorWidth), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Slider.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Slider.kt new file mode 100644 index 0000000..0fdee6e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Slider.kt @@ -0,0 +1,182 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.height +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors + +/** The thumb dot's radius; the thumb travels inset by this from each end so it never spills past the control. */ +private val SLIDER_THUMB_RADIUS = 5.dp + +/** A per-key marker's half-extent; kept under the thumb radius so the current-value thumb stays dominant. */ +private val SLIDER_KEY_MARK_RADIUS = 3.5.dp + +/** + * The shape a slider draws for its thumb and for a per-key marker. A circle marks a key-form (grid) point; + * a square marks a blend-shape point - the parameter-cockpit distinction between the two control-point + * kinds (see ParameterKind: circle points drive keyform interpolation, square points drive additive + * blend-shape deltas). + */ +enum class SliderKeyShape { + Circle, + Square, +} + +/** + * A parameter key to mark on the slider track: its value and the shape that encodes its kind. + * + * @param Float value The parameter value the key sits at. + * @param SliderKeyShape shape The marker shape (Circle = grid key, Square = blend-shape key). + */ +data class SliderKeyMark( + val value: Float, + val shape: SliderKeyShape, +) + +/** + * A flat, draggable slider: a thin track + fill + small thumb on a [Canvas], set by tap or drag anywhere on + * the control. Replaces Material's Slider (no large thumb, no ripple). A fixed-height control; pass a width + * via [modifier] (e.g. `Modifier.fillMaxWidth()`). + * + * [onValueChange] streams the live value for every frame of a tap or drag; [onValueChangeFinished] fires + * once at the gesture boundary (the tap, or the drag's release / cancel). This lets a caller treat a whole + * continuous drag as a single committed gesture (e.g. one undo step) while still previewing each frame. + * + * @param Float value The current value. + * @param Function onValueChange Called with the new value on each tap / drag frame (the preview). + * @param Modifier modifier Layout modifier (supply the width). + * @param Function onValueChangeFinished Called once when the gesture ends (tap, drag release, or cancel). + * @param ClosedFloatingPointRange valueRange The min..max range. + * @param List keyMarks Parameter keys to mark on the track, each with its shape (circle grid key / square + * blend-shape key), so the user can see and scrub onto a key. Empty by default. + * @param SliderKeyShape thumbShape The thumb's shape (Circle for a key-form parameter, Square for a + * blend-shape parameter); defaults to Circle. + */ +@Composable +fun Slider( + value: Float, + onValueChange: (Float) -> Unit, + modifier: Modifier = Modifier, + onValueChangeFinished: () -> Unit = {}, + valueRange: ClosedFloatingPointRange = 0f..1f, + keyMarks: List = emptyList(), + thumbShape: SliderKeyShape = SliderKeyShape.Circle, +) { + val colors = LocalUmamoColors.current + val span = (valueRange.endInclusive - valueRange.start).takeIf { it != 0f } ?: 1f + val fraction = ((value - valueRange.start) / span).coerceIn(0f, 1f) + val trackColor = colors.sliderTrack + val fillColor = colors.accent + val thumbColor = colors.sliderThumb + val tickColor = colors.guideLine + // pointerInput is keyed only on valueRange, so it does not restart when a recomposition hands in a new + // onValueChange (a reused list slot binding to a different row). Read the latest through these so a drag + // always drives the current row, never the one that first occupied the slot. + val currentOnValueChange by rememberUpdatedState(onValueChange) + val currentOnValueChangeFinished by rememberUpdatedState(onValueChangeFinished) + Canvas( + modifier = + modifier + .height(18.dp) + .pointerInput(valueRange) { + val thumbRadius = SLIDER_THUMB_RADIUS.toPx() + detectTapGestures { offset -> + currentOnValueChange(valueAt(offset.x, size.width.toFloat(), thumbRadius, valueRange)) + currentOnValueChangeFinished() + } + } + .pointerInput(valueRange) { + val thumbRadius = SLIDER_THUMB_RADIUS.toPx() + detectDragGestures( + onDragEnd = { currentOnValueChangeFinished() }, + onDragCancel = { currentOnValueChangeFinished() }, + ) { change, _ -> + change.consume() + currentOnValueChange(valueAt(change.position.x, size.width.toFloat(), thumbRadius, valueRange)) + } + }, + ) { + val trackHeight = 4.dp.toPx() + val thumbRadius = SLIDER_THUMB_RADIUS.toPx() + val centerY = size.height / 2f + val corner = CornerRadius(trackHeight / 2f) + val top = Offset(0f, centerY - trackHeight / 2f) + // The thumb center travels within [thumbRadius, width - thumbRadius] so the whole dot stays inside the + // control's hit area at both ends; otherwise the outer half of the thumb would hang into the + // non-interactive padding at the track start, and a click there would miss the slider. The track fills + // the full width for the end caps. + val usableWidth = (size.width - 2f * thumbRadius).coerceAtLeast(0f) + val thumbCenterX = thumbRadius + fraction * usableWidth + drawRoundRect(color = trackColor, topLeft = top, size = Size(size.width, trackHeight), cornerRadius = corner) + drawRoundRect( + color = fillColor, + topLeft = top, + size = Size(thumbCenterX, trackHeight), + cornerRadius = corner, + ) + // Key markers: a small dot at each key value so the user can see and scrub onto a key. Shape + // encodes the key's kind - a circle for a key-form (grid) key, a square for a blend-shape key. + val markRadius = SLIDER_KEY_MARK_RADIUS.toPx() + for (mark in keyMarks) { + val keyFraction = ((mark.value - valueRange.start) / span).coerceIn(0f, 1f) + val markX = (thumbRadius + keyFraction * usableWidth).coerceIn(0f, size.width) + drawSliderShape(mark.shape, tickColor, markX, centerY, markRadius) + } + drawSliderShape(thumbShape, thumbColor, thumbCenterX, centerY, thumbRadius) + } +} + +/** + * Draws one slider marker (thumb or key mark) centered at ([centerX], [centerY]): a filled circle of + * [radius], or a square of the same half-extent with slightly rounded corners to match the flat look. + * + * @param SliderKeyShape shape The marker shape. + * @param Color color The fill color. + * @param Float centerX The marker center x. + * @param Float centerY The marker center y. + * @param Float radius The circle radius, or the square's half-side. + */ +private fun DrawScope.drawSliderShape(shape: SliderKeyShape, color: Color, centerX: Float, centerY: Float, radius: Float) { + when (shape) { + SliderKeyShape.Circle -> { + drawCircle(color = color, radius = radius, center = Offset(centerX, centerY)) + } + + SliderKeyShape.Square -> { + drawRoundRect( + color = color, + topLeft = Offset(centerX - radius, centerY - radius), + size = Size(radius * 2f, radius * 2f), + cornerRadius = CornerRadius(radius * 0.35f), + ) + } + } +} + +/** + * Maps a pointer x onto [range] over the thumb's travel band, which is inset [inset] from each end so the + * track ends map to the range ends and the whole thumb stays inside the control. Clamped to that band. + * + * @param Float x The pointer x within the control. + * @param Float width The control's full width. + * @param Float inset The thumb radius the travel band is inset by at each end. + * @param ClosedFloatingPointRange range The value range to map onto. + * @return Float The value at [x]. + */ +private fun valueAt(x: Float, width: Float, inset: Float, range: ClosedFloatingPointRange): Float { + val usableWidth = (width - 2f * inset).takeIf { it > 0f } ?: 1f + val fraction = ((x - inset) / usableWidth).coerceIn(0f, 1f) + return range.start + fraction * (range.endInclusive - range.start) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/StackedShape.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/StackedShape.kt new file mode 100644 index 0000000..da1446c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/StackedShape.kt @@ -0,0 +1,67 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.shape.CornerBasedShape +import androidx.compose.foundation.shape.ZeroCornerSize +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.graphics.Shape + +/** + * A control's position within a butted run of stacked controls, driving which corners it rounds and which + * it squares against a neighbour. [Single] is a standalone control (all corners rounded). + */ +enum class StackPosition { + Single, + First, + Middle, + Last, +} + +/** The axis a butted run of controls is laid along: a horizontal Row or a vertical Column. */ +enum class StackAxis { + Horizontal, + Vertical, +} + +/** + * Resolves an item's [StackPosition] from its index within a run of [count] items: the sole item is + * [StackPosition.Single], the ends are First / Last, and the interior is Middle. + * + * @param Int index The item's position in the run. + * @param Int count The number of items in the run. + * @return StackPosition The item's position role. + */ +fun stackPositionOf(index: Int, count: Int): StackPosition = + when { + count <= 1 -> StackPosition.Single + index <= 0 -> StackPosition.First + index >= count - 1 -> StackPosition.Last + else -> StackPosition.Middle + } + +/** + * Shapes one control in a butted run so the run reads as a single control with hairline seams: the run's + * outer corners keep [groupShape]'s rounding while the corners shared with a neighbour are squared. A + * horizontal run (ButtonGroup) squares the leading / trailing edges; a vertical run (a stacked numeric + * field group) squares the top / bottom edges. RoundedCornerShape's start / end corners already mirror + * under RTL, so the first item stays the visual leading end either way. + * + * @param CornerBasedShape groupShape The rounding applied to the run's outer corners. + * @param StackPosition position The item's position role in the run. + * @param StackAxis axis The run's layout axis. + * @return Shape The item's corner shape. + */ +fun stackedShape(groupShape: CornerBasedShape, position: StackPosition, axis: StackAxis): Shape = + when (position) { + StackPosition.Single -> groupShape + StackPosition.Middle -> RectangleShape + StackPosition.First -> + when (axis) { + StackAxis.Horizontal -> groupShape.copy(topEnd = ZeroCornerSize, bottomEnd = ZeroCornerSize) + StackAxis.Vertical -> groupShape.copy(bottomStart = ZeroCornerSize, bottomEnd = ZeroCornerSize) + } + StackPosition.Last -> + when (axis) { + StackAxis.Horizontal -> groupShape.copy(topStart = ZeroCornerSize, bottomStart = ZeroCornerSize) + StackAxis.Vertical -> groupShape.copy(topStart = ZeroCornerSize, topEnd = ZeroCornerSize) + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Surface.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Surface.kt new file mode 100644 index 0000000..d102406 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Surface.kt @@ -0,0 +1,62 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors + +/** + * A background container: a [Box] with a fill [color], an optional [shape] clip, an optional [border], and an + * optional drop [shadowElevation]. Replaces Material's Surface (its tonal-elevation tinting is intentionally + * dropped - pick an explicit [color] instead). + * + * @param Modifier modifier Layout modifier. + * @param Color color Background fill (defaults to the panel color). + * @param Shape shape Clip + border + shadow shape. + * @param BorderStroke? border Optional border. + * @param Dp shadowElevation Drop-shadow elevation (0 = none). + * @param Function content The surface content. + */ +@Composable +fun Surface( + modifier: Modifier = Modifier, + color: Color = LocalUmamoColors.current.panelBackground, + shape: Shape = RectangleShape, + border: BorderStroke? = null, + shadowElevation: Dp = 0.dp, + content: @Composable () -> Unit, +) { + var surfaceModifier = modifier + if (shadowElevation > 0.dp) { + surfaceModifier = surfaceModifier.shadow(shadowElevation, shape) + } + surfaceModifier = surfaceModifier.clip(shape).background(color) + if (border != null) { + surfaceModifier = surfaceModifier.border(border, shape) + } + Box(modifier = surfaceModifier) { content() } +} + +/** + * A thin horizontal divider line. + * + * @param Modifier modifier Layout modifier. + * @param Dp thickness Line thickness. + * @param Color color Line color (defaults to the divider color). + */ +@Composable +fun Divider(modifier: Modifier = Modifier, thickness: Dp = 1.dp, color: Color = LocalUmamoColors.current.divider) { + Box(modifier = modifier.fillMaxWidth().height(thickness).background(color)) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Tabs.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Tabs.kt new file mode 100644 index 0000000..b6414c3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Tabs.kt @@ -0,0 +1,64 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes + +/** + * A flat tab strip - a [Row] over the header background, hosting [Tab]s. No animated indicator (the active + * tab is shown by its fill); replaces Material's TabRow. + * + * @param Modifier modifier Layout modifier. + * @param Function content The [Tab]s. + */ +@Composable +fun TabRow(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) { + Row(modifier = modifier.fillMaxWidth(), content = content) +} + +/** + * One tab: a clickable cell that takes the panel color when [selected] and a hover highlight otherwise. + * + * @param Boolean selected Whether this tab is active. + * @param Function onClick Selection callback. + * @param Modifier modifier Layout modifier. + * @param Function label The tab's label content. + */ +@Composable +fun Tab(selected: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, label: @Composable () -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val fill = + when { + selected -> colors.headerBackground + hovered -> colors.rowHover + else -> colors.tabBackground + } + Box( + modifier = + modifier + .padding(horizontal = 2.dp) + .clickable(interactionSource = interaction, indication = null, onClick = onClick) + .background(fill, shape = shapes.medium) + .padding(horizontal = 10.dp, vertical = 4.dp), + contentAlignment = Alignment.Center, + ) { + label() + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Text.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Text.kt new file mode 100644 index 0000000..e7ca5ee --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Text.kt @@ -0,0 +1,59 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.takeOrElse +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography + +/* + * The custom design system (org.umamo.ui.kit): small, flat, hover-driven widgets on Compose Foundation, with + * no Material. Names are unprefixed and read the theme tokens (LocalUmamoColors / LocalUmamoTypography / + * LocalUmamoShapes) directly. There is no ripple - interaction feedback is hover-highlight throughout. + * + * 独自デザイン系。Material を使わない平坦な Foundation 製ウィジェット群。 + */ + +/** + * Renders text. Wraps Foundation's [BasicText] with the kit's type scale and color: the [style] defaults to + * the body style, and the color resolves to [color] → the style's own color → the theme's text color. + * + * @param String text The text to render. + * @param Modifier modifier Layout modifier. + * @param TextStyle style The text style (defaults to the body scale). + * @param Color color Explicit color, or Unspecified to inherit from the style/theme. + * @param TextAlign? textAlign Optional horizontal alignment override. + * @param Int maxLines Maximum line count before truncation. + * @param TextOverflow overflow How overflowing text is handled. + * @param Function? onTextLayout Called with the measured layout result, or null to skip it. + */ +@Composable +fun Text( + text: String, + modifier: Modifier = Modifier, + style: TextStyle = LocalUmamoTypography.current.bodyMedium, + color: Color = Color.Unspecified, + textAlign: TextAlign? = null, + maxLines: Int = Int.MAX_VALUE, + overflow: TextOverflow = TextOverflow.Clip, + onTextLayout: ((TextLayoutResult) -> Unit)? = null, +) { + val resolvedColor = color.takeOrElse { style.color.takeOrElse { LocalUmamoColors.current.text } } + val resolvedStyle = style.copy(color = resolvedColor, textAlign = textAlign ?: style.textAlign) + BasicText( + text = text, + modifier = modifier, + style = resolvedStyle, + // Reported so a caller can react to the MEASURED result - the only way to know a label was actually + // ellipsized, which is what decides whether a "show the full name" tooltip is noise or necessary. + onTextLayout = onTextLayout, + maxLines = maxLines, + overflow = overflow, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/TextEditContextMenu.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/TextEditContextMenu.kt new file mode 100644 index 0000000..17219ee --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/TextEditContextMenu.kt @@ -0,0 +1,153 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.IntOffset +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.text_menu_copy +import org.umamo.ui.resources.text_menu_cut +import org.umamo.ui.resources.text_menu_paste +import org.umamo.ui.resources.text_menu_select_all + +/* + * The context menu for the kit's text fields. + * + * Compose's own text fields carry a built-in Cut / Copy / Paste / Select All menu, and because that menu is + * installed on the innermost node it wins the right-click outright - so a Properties row's Insert / Remove + * Keyframe menu and a panel header's area menu were both unreachable over any field. Rather than suppress + * the built-in menu and lose the clipboard entries, this replaces it with ONE menu drawn in the kit's own + * chrome: whatever the enclosing ContextMenuArea offers, a rule, then the four clipboard actions. + * + * The clipboard actions are re-implemented here rather than delegated back to the built-in menu, which is + * why the fields that use this hold a TextFieldValue rather than a String - Cut, Copy and Select All are all + * statements about a selection range, and the String-shaped BasicTextField overload does not expose one. + */ + +/** + * Wraps a text field so a context-menu request opens the kit menu instead of Compose's built-in one. + * + * [content] receives the gesture modifier rather than having it applied to a wrapper, and must chain it AHEAD + * of its own: the caller's modifier carries focus requesters and layout that belong to the FIELD, and a + * wrapper that swallowed them would silently break things like the command palette's auto-focus. [modifier] + * is for the few things that must sit on the wrapper instead - a Row weight, which only a direct child of + * the row can carry. + * + * @param TextFieldValue value The field's current text and selection. + * @param Function onValueChange Applies a clipboard action's result back to the field. + * @param Modifier modifier Layout for the wrapping box, where the field itself cannot carry it. + * @param Function content The text field, given the modifier that opens the menu. + */ +@Composable +internal fun TextEditContextMenuArea( + value: TextFieldValue, + onValueChange: (TextFieldValue) -> Unit, + modifier: Modifier = Modifier, + content: @Composable (Modifier) -> Unit, +) { + var open by remember { mutableStateOf(false) } + var anchorOffset by remember { mutableStateOf(IntOffset.Zero) } + val gesture = + Modifier.textEditContextMenuGesture { localOffset -> + anchorOffset = localOffset + open = true + } + Box(modifier = modifier) { + // The field must NOT inherit the ambient items a second time through some nested area of its own: + // they are already the head of this menu, and a doubled list reads as a bug rather than as emphasis. + CompositionLocalProvider(LocalContextMenuItems provides emptyList()) { + content(gesture) + } + if (open) { + // Built only while the menu is up. Every kit text field mounts one of these, the entries depend + // on the CLIPBOARD (a cross-process read on desktop), and LocalContextMenuItems hands down a list + // rebuilt by its area every recomposition - so building them unconditionally read the system + // clipboard once per field per frame of any neighbouring scrub. Reading the ambient items here + // is still correct: this sits outside the provider that blanks them for `content`. + val surroundingItems = LocalContextMenuItems.current + val clipboardItems = textEditMenuItems(value, onValueChange) + Menu( + items = + if (surroundingItems.isEmpty()) { + clipboardItems + } else { + surroundingItems + MenuItem.Separator + clipboardItems + }, + onDismissRequest = { open = false }, + positionProvider = AtPointPositionProvider(anchorOffset), + focusable = true, + ) + } + } +} + +/** + * The four clipboard entries, each disabled when it would do nothing. + * + * Cut and Copy need a non-collapsed selection, Paste needs something on the clipboard, and Select All needs + * text to select. Showing them greyed rather than hiding them keeps the menu's shape stable, so the entry a + * user is reaching for does not move between right-clicks. + * + * @param TextFieldValue value The field's current text and selection. + * @param Function onValueChange Applies the result back to the field. + * @return List The clipboard entries. + */ +@Composable +private fun textEditMenuItems(value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit): List { + @Suppress("DEPRECATION") + val clipboard = LocalClipboardManager.current + val hasSelection = !value.selection.collapsed + // One clipboard read for both the Paste entry's enablement and its action; the caller only builds this + // while the menu is opening, so the cross-process query happens once per right-click. + val hasClipboardText = clipboard.hasText() + return listOf( + MenuItem.Action( + label = stringResource(Res.string.text_menu_cut), + onSelect = { + clipboard.setText(AnnotatedString(value.selectedText())) + onValueChange(value.withSelectionReplaced("")) + }, + enabled = hasSelection, + ), + MenuItem.Action( + label = stringResource(Res.string.text_menu_copy), + onSelect = { clipboard.setText(AnnotatedString(value.selectedText())) }, + enabled = hasSelection, + ), + MenuItem.Action( + label = stringResource(Res.string.text_menu_paste), + onSelect = { onValueChange(value.withSelectionReplaced(clipboard.getText()?.text.orEmpty())) }, + enabled = hasClipboardText, + ), + MenuItem.Action( + label = stringResource(Res.string.text_menu_select_all), + onSelect = { onValueChange(value.copy(selection = TextRange(0, value.text.length))) }, + enabled = value.text.isNotEmpty(), + ), + ) +} + +/** The text covered by this value's selection, or "" when the selection is a bare caret. */ +internal fun TextFieldValue.selectedText(): String = text.substring(selection.min, selection.max) + +/** + * This value with its selection replaced by [replacement], the caret left after the inserted text. + * + * @param String replacement The text to put in the selection's place. + * @return TextFieldValue The edited value. + */ +internal fun TextFieldValue.withSelectionReplaced(replacement: String): TextFieldValue { + val edited = text.replaceRange(selection.min, selection.max, replacement) + val caret = selection.min + replacement.length + return copy(text = edited, selection = TextRange(caret)) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/TextEntrySurface.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/TextEntrySurface.kt new file mode 100644 index 0000000..94acd10 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/TextEntrySurface.kt @@ -0,0 +1,24 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput + +/** + * Marks a node as a text editor's own surface, so a host watching the window can tell a press ON the + * editor from a press anywhere else. + * + * @param InlineEditController controller The seam this editor shares with its host. + * @return Modifier The node, carrying the editor's press claim. + */ +fun Modifier.textEntrySurface(controller: InlineEditController): Modifier = + this.pointerInput(controller) { + awaitPointerEventScope { + while (true) { + if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) { + controller.pressLandedOnTextEditor = true + } + } + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Thumbnail.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Thumbnail.kt new file mode 100644 index 0000000..a0637ea --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Thumbnail.kt @@ -0,0 +1,77 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import kotlin.math.ceil + +/** The default square edge of a thumbnail slot (the overlap picker's compact preview). */ +val DefaultThumbnailSize = 44.dp + +/** The cell edge of the transparency checker drawn behind a thumbnail. */ +private val ThumbnailCheckerCell = 6.dp + +/** + * A square art-mesh preview slot, shared by the overlap picker and the Outliner hover preview. When + * [thumbnail] is present it is drawn over a small transparency checker (the themed viewport checker colors) + * so the layer's silhouette reads against the surface; when it is null the slot is an empty box of the same + * size, keeping label-only rows aligned with thumbnailed ones. + * + * @param ImageBitmap? thumbnail The layer-art preview, or null for an untextured drawable. + * @param Dp size The square edge of the slot. + */ +@Composable +fun ThumbnailSlot(thumbnail: ImageBitmap?, size: Dp = DefaultThumbnailSize) { + val slotModifier = Modifier.size(size) + if (thumbnail == null) { + Box(modifier = slotModifier) + return + } + val colors = LocalUmamoColors.current + val checkerLight = colors.transparencyCheckerLight + val checkerDark = colors.transparencyCheckerDark + Box( + modifier = + slotModifier + .clip(LocalUmamoShapes.current.small) + .drawBehind { + val cell = ThumbnailCheckerCell.toPx() + val columns = ceil(this.size.width / cell).toInt() + val rows = ceil(this.size.height / cell).toInt() + var rowIndex = 0 + while (rowIndex < rows) { + var columnIndex = 0 + while (columnIndex < columns) { + val isDarkCell = (rowIndex + columnIndex) % 2 == 1 + drawRect( + color = if (isDarkCell) checkerDark else checkerLight, + topLeft = Offset(columnIndex * cell, rowIndex * cell), + size = Size(cell, cell), + ) + columnIndex += 1 + } + rowIndex += 1 + } + }, + ) { + Image( + bitmap = thumbnail, + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier.fillMaxSize(), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Tooltip.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Tooltip.kt new file mode 100644 index 0000000..8ce625f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/Tooltip.kt @@ -0,0 +1,68 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * The widest a tooltip's label runs before it wraps. A control's name never reaches it; a row's + * description is a sentence or two, and without the cap it would draw as one line across the window. + */ +private val TOOLTIP_MAX_WIDTH = 280.dp + +/** + * Wraps [content] with a hover tooltip showing [text]. Desktop reveals the tooltip after a short + * mouse-dwell over the content; touch platforms have no hover, so the content renders unchanged there (a + * long-press tooltip awaits the Android target). The caller's layout [modifier] rides on the wrapper + * (the outermost node) so alignment and weight still resolve against the parent. + * + * The label is meant to double as the control's accessible description - passing the same string to both + * the tooltip and semantics keeps the on-screen hint and the a11y name in lockstep. A blank [text] + * attaches no tooltip, so callers can pass an unconditional label. + * + * ホバー時にツールチップを表示する。デスクトップはマウス静止で表示、タッチはホバーが無いのでそのまま描画 + * (長押しツールチップは Android ターゲットで対応)。ラベルはアクセシビリティ名を兼ねる。 + * + * @param String text The tooltip label; blank attaches no tooltip. + * @param Modifier modifier The layout modifier, applied to the wrapper. + * @param Function content The control the tooltip describes. + */ +@Composable +expect fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () -> Unit) + +/** + * The tooltip's floating card: a small rounded popover reading like the kit's menus (menu fill, a + * hairline border, a soft drop shadow) with the label in the primary text color. Shared by every + * platform's [Tooltip] so the chrome stays identical, and by any other transient label that should read + * as a tooltip - the relation-pick badge positions one at the cursor through [modifier]. Keeping the + * chrome here is the point: a second hand-rolled card would drift out of step with this one. + * + * ツールチップの浮動カード。メニューと同じ見た目(塗り・枠線・影)でラベルを表示する。 + * + * @param String text The tooltip label. + * @param Modifier modifier The layout modifier, applied to the card (a caller may position it). + */ +@Composable +internal fun TooltipCard(text: String, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + Surface( + modifier = modifier, + color = colors.menuBackground, + shape = LocalUmamoShapes.current.small, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 4.dp, + ) { + Text( + text = text, + style = LocalUmamoTypography.current.labelMedium, + color = colors.text, + modifier = Modifier.widthIn(max = TOOLTIP_MAX_WIDTH).padding(horizontal = 8.dp, vertical = 4.dp), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/Button.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/Button.kt new file mode 100644 index 0000000..d9304c4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/Button.kt @@ -0,0 +1,74 @@ +package org.umamo.ui.kit.button + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.Text +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A small flat button: tight padding, small corners, hover-highlight and a darker fill while held (no + * ripple). [primary] fills with the accent; otherwise a neutral control fill. + * + * @param String label The button text. + * @param Function onClick Click callback. + * @param Modifier modifier Layout modifier. + * @param Boolean primary Accent fill when true, neutral when false. + * @param Boolean enabled When false the button rests on the neutral fill with a disabled label, shows no + * hover or press, and ignores clicks. + */ +@Composable +fun Button(label: String, onClick: () -> Unit, modifier: Modifier = Modifier, primary: Boolean = true, enabled: Boolean = true) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val pressed by interaction.collectIsPressedAsState() + // The same ramp the filled icon buttons and button-group segments use (accentControlFill), except that + // a secondary button's hover stays the softer rowHover it has always drawn; a press outranks a hover, and + // a disabled button outranks both, showing no feedback, as a disabled IconButton does. + val fill = + when { + !enabled -> colors.controlBackground + primary && pressed -> colors.accentPressed + primary && hovered -> colors.accentHover + primary -> colors.accent + pressed -> colors.buttonPressed + hovered -> colors.rowHover + else -> colors.controlBackground + } + val labelColor = + when { + !enabled -> colors.textDisabled + primary -> colors.accentText + else -> colors.text + } + Box( + modifier = + modifier + .clip(shapes.small) + .background(fill) + .clickable(interactionSource = interaction, indication = null, enabled = enabled, onClick = onClick) + .padding(horizontal = 8.dp, vertical = 3.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + style = LocalUmamoTypography.current.labelMedium, + color = labelColor, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/ButtonGroup.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/ButtonGroup.kt new file mode 100644 index 0000000..1e4203b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/ButtonGroup.kt @@ -0,0 +1,141 @@ +package org.umamo.ui.kit.button + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CornerBasedShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.StackAxis +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.kit.stackPositionOf +import org.umamo.ui.kit.stackedShape +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** One segment's face - wider than tall, like Blender's aligned toggle buttons. */ +private val SEGMENT_WIDTH = 26.dp +private val SEGMENT_HEIGHT = 20.dp + +/** Icon size inside a segment. */ +private val SEGMENT_ICON_SIZE = 16.dp + +/** The hairline seam between adjacent segments (the surface behind shows through). */ +private val SEGMENT_GAP = 1.dp + +/** + * One segment of a [ButtonGroup]: an icon toggle that lights with the accent while [selected]. This is + * a data model rather than a slot DSL (same reasoning as [MenuItem]) - the group must know each + * segment's position to shape its corners, so callers hand over a list and one renderer draws it. + * + * ButtonGroup の 1 セグメント。selected の間アクセント色で点灯するアイコントグル。 + * + * @property UmamoIcon icon The segment's glyph. + * @property Boolean selected Whether the segment is lit (the caller owns the toggle state). + * @property Function onClick Invoked on tap; the caller flips its own state. + * @property String contentDescription The accessible label, doubling as the segment's hover label. + * Required: a segment's face is only a glyph, so an absent label would leave it nameless to a screen + * reader and silent on hover at once. + */ +data class ButtonGroupItem( + val icon: UmamoIcon, + val selected: Boolean, + val onClick: () -> Unit, + val contentDescription: String, +) + +/** + * A Blender-style run of butted icon toggles: the segments sit flush against each other separated by a + * hairline seam, with the group's outer corners rounded and every shared edge square - one pill-shaped + * control rather than a row of isolated chips. Each segment carries its own selected state, so the + * group serves both independent toggles (the outliner's restriction columns) and radio-style sets (the + * viewport's mesh select modes) - the caller decides the semantics in its onClick handlers. + * + * Blender 式の連結トグル列。両端だけ角丸で、隣接辺は直角。各セグメントが自分の選択状態を持つ。 + * + * @param List items The segments, in display order. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun ButtonGroup(items: List, modifier: Modifier = Modifier) { + val shapes = LocalUmamoShapes.current + Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { + items.forEachIndexed { segmentIndex, item -> + if (segmentIndex > 0) { + Spacer(modifier = Modifier.width(SEGMENT_GAP)) + } + ButtonGroupSegment( + item = item, + shape = segmentShape(shapes.small, segmentIndex, items.size), + ) + } + } +} + +/** + * Shapes one segment by its position in the (horizontal) group, delegating to the shared [stackedShape] + * helper that the vertical numeric-field stack also uses: outer corners take the group's rounding, + * corners shared with a neighbour are squared. + * + * @param CornerBasedShape groupShape The rounding applied to the group's outer corners. + * @param Int segmentIndex This segment's position. + * @param Int segmentCount The number of segments in the group. + * @return Shape The segment's corner shape. + */ +private fun segmentShape(groupShape: CornerBasedShape, segmentIndex: Int, segmentCount: Int): Shape = + stackedShape(groupShape, stackPositionOf(segmentIndex, segmentCount), StackAxis.Horizontal) + +/** + * One rendered segment: a full-bleed fill (accent while selected, neutral control fill otherwise, both + * brightening on hover) under a centered icon. Flat like the rest of the kit - the default indication + * is suppressed and the fill carries the hover feedback. The fill and glyph share [accentControlFill] / + * [accentControlGlyph] with the filled [IconButton], so header controls and segments read as one family. + * + * @param ButtonGroupItem item The segment to draw. + * @param Shape shape The position-dependent corner shape from [segmentShape]. + */ +@Composable +private fun ButtonGroupSegment(item: ButtonGroupItem, shape: Shape) { + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val pressed by interaction.collectIsPressedAsState() + val fill = accentControlFill(colors, item.selected, hovered, pressed) + val iconTint = accentControlGlyph(colors, item.selected) + // The label doubles as the hover text, as it does on IconButton - it is the human name of the segment + // either way. + Tooltip(text = item.contentDescription) { + Box( + modifier = + Modifier + .size(width = SEGMENT_WIDTH, height = SEGMENT_HEIGHT) + .clip(shape) + .background(fill) + .clickable(interactionSource = interaction, indication = null, onClick = item.onClick) + .semantics { contentDescription = item.contentDescription }, + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.size(SEGMENT_ICON_SIZE)) { + drawIcon(item.icon, iconTint) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/CloseButton.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/CloseButton.kt new file mode 100644 index 0000000..4383cc3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/CloseButton.kt @@ -0,0 +1,34 @@ +package org.umamo.ui.kit.button + +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes + +/** + * A modal-card header close button: a flat "✕" glyph that brightens from muted to full text color on + * hover, matching the kit's other icon controls. Shared by the settings window and the Help dialogs; + * needed for keyboardless tablets where Escape is unavailable. A thin preset of [IconButton] - it fixes + * the close glyph at a larger 20dp and, sitting in stable dialog chrome, keeps keyboard focus. + * + * モーダルヘッダの閉じるボタン。ホバーで明るくなる「✕」。Esc が使えないタブレット向け。 + * + * @param Function onClick Click callback (closes the window). + * @param String contentDescription The accessible label (the face is only a glyph). + */ +@Composable +internal fun CloseButton(onClick: () -> Unit, contentDescription: String) { + IconButton( + icon = LocalUmamoIcons.close, + onClick = onClick, + contentDescription = contentDescription, + size = DpSize(20.dp, 20.dp), + glyphSize = 20.dp, + suppressFocus = false, + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/IconButton.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/IconButton.kt new file mode 100644 index 0000000..63c3d39 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/IconButton.kt @@ -0,0 +1,175 @@ +package org.umamo.ui.kit.button + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.requiredSize +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CornerBasedShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.UmamoColors +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** + * A small flat or elevation-filled icon button: a themed glyph over an optional control-fill chip, flat + * (no ripple) with hover feedback. Consolidates the kit's icon buttons - the reset and close affordances + * are this control with a preset icon and size. + * + * The default suppresses keyboard focus because these buttons live inside the shell tree, where a click + * that removes or restructures the button's own row would otherwise leave the focus owner null and the + * shell root's onPreviewKeyEvent (all keyboard dispatch) dead until Tab traversal reclaims focus. A + * button anchored in stable chrome (a dialog header) can opt back in with [suppressFocus] = false. + * + * @param UmamoIcon icon The glyph to draw. + * @param Function onClick Click callback. + * @param String contentDescription The accessible label (the face is only a glyph). + * @param Modifier modifier Layout modifier. + * @param IconButtonAppearance appearance Flat glyph, or a Filled elevation chip (background plus corners). + * @param DpSize size The button's box, square by default; 26x20 for header controls. + * @param Dp glyphSize The drawn glyph size, honored even when it exceeds [size] + * (the glyph then overhangs its box rather than being capped). + * @param Boolean active A lit toggle state (accent glyph when Flat, accent fill when Filled). + * @param Boolean enabled When false the glyph dims to the disabled tint and clicks are inert + * (no-document chrome renders its controls this way rather than hiding them). + * @param Boolean suppressFocus When true the click never pulls keyboard focus off the shell root. + */ +@Composable +fun IconButton( + icon: UmamoIcon, + onClick: () -> Unit, + contentDescription: String, + modifier: Modifier = Modifier, + appearance: IconButtonAppearance = IconButtonAppearance.Flat, + size: DpSize = DpSize(20.dp, 20.dp), + glyphSize: Dp = 16.dp, + active: Boolean = false, + enabled: Boolean = true, + suppressFocus: Boolean = true, +) { + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val hoveredLive by interaction.collectIsHoveredAsState() + val pressedLive by interaction.collectIsPressedAsState() + // A disabled button shows no hover or press feedback (the fill and border stay at rest). + val hovered = hoveredLive && enabled + val pressed = pressedLive && enabled + val glyphColor = + when { + !enabled -> colors.textDisabled + appearance is IconButtonAppearance.Filled -> accentControlGlyph(colors, active) + active -> colors.accent + hovered -> colors.text + else -> colors.textMuted + } + var faceModifier = Modifier.size(size) + if (appearance is IconButtonAppearance.Filled) { + // Elevation is the inline clip + background idiom, not kit Surface: the fill must ramp on hover, + // which a Surface's static color cannot do. + faceModifier = + faceModifier + .clip(appearance.shape) + .background(accentControlFill(colors, active && enabled, hovered, pressed)) + .border( + width = 1.dp, + color = + when { + hovered -> colors.panelBorderHover + else -> colors.controlBorder + }, + shape = appearance.shape, + ) + } + if (suppressFocus) { + faceModifier = faceModifier.focusProperties { canFocus = false } + } + faceModifier = + faceModifier + .clickable(interactionSource = interaction, indication = null, enabled = enabled, onClick = onClick) + .semantics { this.contentDescription = contentDescription } + // The caller's layout modifier rides on the tooltip wrapper (the outermost node) so alignment and + // weight still resolve against the parent; the fixed-size face sits inside it. contentDescription + // doubles as the hover label - it is the human name of the control either way. + Tooltip(text = contentDescription, modifier = modifier) { + Box(modifier = faceModifier, contentAlignment = Alignment.Center) { + // requiredSize, not size: size coerces to the box's constraints, which silently caps glyphSize at + // the smaller of the two and lets a starved parent shrink the glyph away entirely. + Canvas(modifier = Modifier.requiredSize(glyphSize)) { + drawIcon(icon, glyphColor) + } + } + } +} + +/** + * How an [IconButton]'s face is painted: a bare glyph, or a filled elevation chip. + * + * エリアヘッダのような塗り付きボタンと、ダイアログの✕のような塗りなしボタンを一つの型で表す。 + */ +sealed interface IconButtonAppearance { + /** Flat: no fill; the glyph itself carries hover and active feedback. */ + data object Flat : IconButtonAppearance + + /** + * Filled: a control-fill elevation chip (a background plus corner rounding) sits under the glyph, the + * fill brightening on hover and switching to the accent while active. This is the treatment that lets + * any icon button read as a raised button at rest. + * + * @property CornerBasedShape shape The corner rounding of the elevation fill. + */ + data class Filled(val shape: CornerBasedShape) : IconButtonAppearance +} + +/** + * The fill behind a filled icon button or button-group segment: the neutral control fill at rest, the + * accent while selected, brightening one step on hover and darkening one while held. Shared so the + * header's filled buttons and a [ButtonGroup]'s segments stay one visual family rather than two copies of + * the same ramp; [Button] restates it only because its secondary hover is the softer rowHover. + * + * A press outranks a hover because the pointer is necessarily over a control it is pressing. + * + * @param UmamoColors colors The active color scheme. + * @param Boolean selected Whether the control is lit (accent) rather than neutral. + * @param Boolean hovered Whether the pointer is over the control. + * @param Boolean pressed Whether the control is held down. + * @return Color The resolved fill color. + */ +internal fun accentControlFill(colors: UmamoColors, selected: Boolean, hovered: Boolean, pressed: Boolean): Color = + when { + selected && pressed -> colors.accentPressed + selected && hovered -> colors.accentHover + selected -> colors.accent + pressed -> colors.buttonPressed + hovered -> colors.buttonHover + else -> colors.controlBackground + } + +/** + * The glyph tint on a filled icon button or button-group segment: on-accent text while selected, the + * neutral control glyph otherwise. Paired with [accentControlFill]. + * + * @param UmamoColors colors The active color scheme. + * @param Boolean selected Whether the control is lit. + * @return Color The resolved glyph color. + */ +internal fun accentControlGlyph(colors: UmamoColors, selected: Boolean): Color = + if (selected) colors.accentText else colors.controlGlyph \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/IconSlot.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/IconSlot.kt new file mode 100644 index 0000000..a8e0fab --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/kit/button/IconSlot.kt @@ -0,0 +1,66 @@ +package org.umamo.ui.kit.button + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon + +/** + * A labelled glyph whose gesture the caller owns: a themed icon centered in a fixed-size box, carrying the + * accessible name and (by default) the matching hover tooltip. This is [IconButton]'s sibling for the + * slots that cannot be an [IconButton] - a tree row's eye, its selectable pointer, a disclosure chevron - + * because they consume their own press so the whole-row selection handler skips them, and they must not + * take keyboard focus off a row the very edit beside them can dispose. + * + * Both live here so the kit's label contract has one neighborhood rather than two: a control's accessible + * name doubles as its hover label, and passing one string to both keeps them in lockstep. + * + * @param UmamoIcon icon The glyph to draw. + * @param String contentDescription The accessible name (the face is only a glyph). + * @param Color tint The glyph color, resolved by the caller against its own row state. + * @param Modifier modifier Applied to the sized face, so the caller's gesture covers the whole slot. + * @param DpSize slotSize The hit box; set it equal to [glyphSize] for a bare inline glyph. + * @param Dp glyphSize The drawn glyph size inside the box. + * @param String hoverLabel The tooltip text, defaulting to [contentDescription]. A slot sitting + * beside its own visible text passes "" to keep the accessible name without a hover card that only + * repeats what is already on screen. + */ +@Composable +fun IconSlot( + icon: UmamoIcon, + contentDescription: String, + tint: Color, + modifier: Modifier = Modifier, + slotSize: DpSize = DpSize(20.dp, 20.dp), + glyphSize: Dp = 16.dp, + hoverLabel: String = contentDescription, +) { + // Unlike IconButton, the caller's modifier rides on the FACE rather than the tooltip wrapper: here it + // carries the gesture, which has to cover the slot's hit box exactly. The wrapper sizes to the face, + // so the hover region matches either way. + Tooltip(text = hoverLabel) { + Box( + modifier = + Modifier + .size(slotSize) + .then(modifier) + .semantics { this.contentDescription = contentDescription }, + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.size(glyphSize)) { + drawIcon(icon, tint) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/l10n/AppLocale.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/l10n/AppLocale.kt new file mode 100644 index 0000000..68e4a0f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/l10n/AppLocale.kt @@ -0,0 +1,117 @@ +package org.umamo.ui.l10n + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.State +import androidx.compose.runtime.key +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.settings.Settings + +/** + * The active UI language tag (BCP-47, e.g. "en" / "ja" / "ko") for the composition, driven by the + * localization.locale setting rather than the OS locale. Descendants that need the raw tag read + * `LocalAppLocale.current`; most code just calls stringResource() and lets the catalogs resolve. + */ +val LocalAppLocale = staticCompositionLocalOf { "en" } + +/** The settings key holding the UI language tag. */ +const val LOCALE_SETTINGS_KEY: String = "localization.locale" + +/** The language the UI falls back to when the setting holds none, and when no system language has a catalog. */ +const val FALLBACK_LOCALE_TAG: String = "en" + +/** + * The UI languages Umamo ships, in display order: one entry per composeResources/values-/ catalog, keyed + * by the BCP-47 tag written to localization.locale (which applyAppLocale feeds to the resource environment). + * + * The values are endonyms ("English" / "日本語" / "한국어"), shown verbatim whatever the active UI language: a + * language's own name is identity, not chrome to translate, and it is what a rigger who cannot read the + * current language looks for. + */ +val UI_LANGUAGE_ENDONYMS: Map = linkedMapOf("en" to "English", "ja" to "日本語", "ko" to "한국어") + +/** + * The operating system's preferred UI languages as BCP-47 tags, most preferred first; empty when the platform + * reports none. Reads the system's own preference, never the process default [applyAppLocale] overrides, so + * the answer is the same before and after the app applies its language. + * + * @return List The preferred language tags. + */ +expect fun systemLanguageTags(): List + +/** + * Picks the UI language for a list of preferred language tags: the first preferred tag with a catalog wins. + * Each tag is tried at its most specific first - the whole tag, then language-region, then the language alone - + * so a region catalog ("zh-CN") is matched before a bare language one would be. `_` separators (the JVM and + * POSIX spelling) read as `-`, and case does not matter. + * + * @param List preferredTags The preferred language tags, most preferred first. + * @param Collection supported The tags that have a catalog. + * @return String The matched supported tag, or [FALLBACK_LOCALE_TAG] when none matches. + */ +fun matchUiLanguage(preferredTags: List, supported: Collection): String { + val supportedByLowercase = supported.associateBy { tag -> tag.lowercase() } + for (preferredTag in preferredTags) { + val subtags = preferredTag.replace('_', '-').lowercase().split('-').filter { subtag -> subtag.isNotEmpty() } + val language = subtags.firstOrNull() ?: continue + // A region is the two-letter or three-digit subtag after the language (and any four-letter script). + val region = subtags.drop(1).firstOrNull { subtag -> subtag.length == 2 || (subtag.length == 3 && subtag.all(Char::isDigit)) } + val candidates = listOfNotNull(subtags.joinToString("-"), region?.let { "$language-$it" }, language) + for (candidate in candidates) { + supportedByLowercase[candidate]?.let { matched -> return matched } + } + } + return FALLBACK_LOCALE_TAG +} + +/** + * The UI language tag as live state: read from the localization.locale setting and updated when it + * changes, so whatever is keyed on it re-localizes on a runtime language switch. + * + * @param Settings settings The settings store to read and follow. + * @return State The live BCP-47 language tag. + */ +@Composable +fun rememberLocaleTag(settings: Settings): State = + produceState(initialValue = settings.getString(LOCALE_SETTINGS_KEY) ?: FALLBACK_LOCALE_TAG, settings) { + settings.changes.collect { changedKey -> + if (changedKey == LOCALE_SETTINGS_KEY) { + value = settings.getString(LOCALE_SETTINGS_KEY) ?: FALLBACK_LOCALE_TAG + } + } + } + +/** + * Applies [languageTag] as the process resource locale on the current platform. Compose + * Multiplatform has no first-party "override the resource locale at runtime" API yet (JetBrains issue + * #4197), so the portable lever is the JVM default locale, which the desktop/Android resource + * environment derives from. expect/actual keeps java.util.Locale out of commonMain (absent there). + * + * @param String languageTag The BCP-47 language tag to apply. + */ +expect fun applyAppLocale(languageTag: String) + +/** + * Provides [languageTag] to the subtree and makes stringResource() resolve against it. Two effects: + * [applyAppLocale] sets the platform locale before children compose (via remember keyed on the tag, + * so it re-runs only when the language actually changes), and `key(languageTag)` forces the subtree - + * including Compose's cached resource environment - to recompose on a switch so the new catalog is read. + * + * @param String languageTag The BCP-47 language tag to make active. + * @param Function content The subtree to render under this locale. + */ +@Composable +fun ProvideAppLocale(languageTag: String, content: @Composable () -> Unit) { + // remember(key) runs once per distinct tag - applies the locale before the keyed content composes. + remember(languageTag) { + applyAppLocale(languageTag) + languageTag + } + CompositionLocalProvider(LocalAppLocale provides languageTag) { + key(languageTag) { + content() + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/menu/AppMenu.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/menu/AppMenu.kt new file mode 100644 index 0000000..2ace28b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/menu/AppMenu.kt @@ -0,0 +1,234 @@ +package org.umamo.ui.menu + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.document.fileDisplayName +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.TopLevelMenu +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.cmd_workspace_next +import org.umamo.ui.resources.cmd_workspace_prev +import org.umamo.ui.resources.menu_about +import org.umamo.ui.resources.menu_credits +import org.umamo.ui.resources.menu_documentation +import org.umamo.ui.resources.menu_edit +import org.umamo.ui.resources.menu_exit +import org.umamo.ui.resources.menu_export +import org.umamo.ui.resources.menu_export_cmo3 +import org.umamo.ui.resources.menu_export_image +import org.umamo.ui.resources.menu_export_moc3 +import org.umamo.ui.resources.menu_file +import org.umamo.ui.resources.menu_file_new +import org.umamo.ui.resources.menu_file_open +import org.umamo.ui.resources.menu_file_save +import org.umamo.ui.resources.menu_file_save_as +import org.umamo.ui.resources.menu_help +import org.umamo.ui.resources.menu_import +import org.umamo.ui.resources.menu_import_artwork +import org.umamo.ui.resources.menu_import_cmo3 +import org.umamo.ui.resources.menu_import_moc3 +import org.umamo.ui.resources.menu_open_recent +import org.umamo.ui.resources.menu_preferences +import org.umamo.ui.resources.menu_quick_setup +import org.umamo.ui.resources.menu_redo +import org.umamo.ui.resources.menu_source_code +import org.umamo.ui.resources.menu_undo +import org.umamo.ui.resources.menu_web_site +import org.umamo.ui.resources.menu_workspace +import org.umamo.ui.resources.menu_workspace_export_all +import org.umamo.ui.resources.menu_workspace_export_this +import org.umamo.ui.resources.menu_workspace_import +import org.umamo.ui.resources.menu_workspace_reset +import org.umamo.ui.resources.workspace_new + +/** + * Runs a command by id through the action registry, with the argument an argument-only command takes (a + * recent file's path) or null. The one thing a menu row does. + */ +typealias MenuDispatch = (commandId: String, argument: Any?) -> Unit + +/** + * One menu row that stands for a command. The row is built from the command's id ALONE: selecting it + * dispatches that id, and its accelerator hint is whatever chord the keymap binds to that same id. Naming + * the id once is the point - a row that dispatched one id and looked its hint up under another would show + * no chord, or the wrong one, and nothing would say so. + * + * @param String label The localized row label. + * @param String commandId The command the row stands for. + * @param Keymap keymap The keymap the accelerator hint is resolved against. + * @param MenuDispatch dispatch Runs a command by id. + * @param Boolean enabled Whether the row can be selected. + * @return MenuItem.Action The row. + */ +private fun commandRow( + label: String, + commandId: String, + keymap: Keymap, + dispatch: MenuDispatch, + enabled: Boolean = true, +): MenuItem.Action = + MenuItem.Action( + label = label, + onSelect = { dispatch(commandId, null) }, + shortcut = keymap.chordFor(commandId)?.let { chord -> formatAccelerator(chord) }, + enabled = enabled, + ) + +/** + * Builds the File menu shared by every platform's menu bar. Open, Save, and Save As mean the native + * `.uma` document; artwork, CMO3, and MOC3 come in through the Import submenu (artwork first: it is the + * headline workflow's entry), and CMO3 / MOC3 are interop boundaries that leave through Export. Every + * row dispatches its file.* command, so the menu, the keyboard, and the palette share one path. Both + * Save rows are gated on [canSave] (a puppet document that did not open read-only), the CMO3 and MOC3 + * Export rows on [canExport] (a puppet document is open; the CMO3 export reconciles onto a CMO3-origin + * document's retained graph and synthesizes a fresh one otherwise), and Export Image on [canExportImage] + * (a puppet document is open on a platform with a puppet renderer to draw it); Open Recent labels each stored path via + * fileDisplayName, disables itself when the list is empty, and hands the path to file.openPath, which + * opens or imports by what the file is. + * + * @param Keymap keymap The keymap the accelerator hints are resolved against. + * @param List recentFiles The recent file paths for the Open Recent submenu, most-recent first. + * @param Boolean canExport Whether an exportable puppet document is open (gates the CMO3 and MOC3 rows). + * @param Boolean canExportImage Whether the open document can be rendered to an image (gates Export Image). + * @param Boolean canSave Whether the open document can be saved (gates both Save rows). + * @param MenuDispatch dispatch Runs a command by id. + * @return TopLevelMenu The File menu. + */ +@Composable +fun fileMenu( + keymap: Keymap, + recentFiles: List, + canExport: Boolean, + canExportImage: Boolean, + canSave: Boolean, + dispatch: MenuDispatch, +): TopLevelMenu = + TopLevelMenu( + label = stringResource(Res.string.menu_file), + items = + listOf( + commandRow(stringResource(Res.string.menu_file_new), "file.new", keymap, dispatch), + commandRow(stringResource(Res.string.menu_file_open), "file.open", keymap, dispatch), + MenuItem.Submenu( + label = stringResource(Res.string.menu_open_recent), + // A recent file is a row per path rather than a command per path, so these carry their + // argument and show no chord. + items = recentFiles.map { recent -> MenuItem.Action(fileDisplayName(recent), onSelect = { dispatch("file.openPath", recent) }) }, + enabled = recentFiles.isNotEmpty(), + ), + commandRow(stringResource(Res.string.menu_file_save), "file.save", keymap, dispatch, enabled = canSave), + commandRow(stringResource(Res.string.menu_file_save_as), "file.saveAs", keymap, dispatch, enabled = canSave), + MenuItem.Submenu( + label = stringResource(Res.string.menu_import), + items = + listOf( + commandRow(stringResource(Res.string.menu_import_artwork), "file.importArtwork", keymap, dispatch), + commandRow(stringResource(Res.string.menu_import_cmo3), "file.importCmo3", keymap, dispatch), + commandRow(stringResource(Res.string.menu_import_moc3), "file.importMoc3", keymap, dispatch), + ), + ), + MenuItem.Submenu( + label = stringResource(Res.string.menu_export), + items = + listOf( + commandRow(stringResource(Res.string.menu_export_cmo3), "file.exportCmo3", keymap, dispatch, enabled = canExport), + commandRow(stringResource(Res.string.menu_export_moc3), "file.exportMoc3", keymap, dispatch, enabled = canExport), + commandRow(stringResource(Res.string.menu_export_image), "file.exportImage", keymap, dispatch, enabled = canExportImage), + ), + ), + MenuItem.Separator, + commandRow(stringResource(Res.string.menu_exit), "file.exit", keymap, dispatch), + ), + ) + +/** + * Builds the Edit menu shared by every platform's menu bar, so desktop and the keyboardless tablet reach + * the same entries from one source (the "one shared interface" guardrail). Undo and Redo dispatch + * edit.undo / edit.redo and are enabled per [canUndo] / [canRedo]; Preferences dispatches + * edit.preferences, whose overlay the shell owns. + * + * @param Keymap keymap The keymap the accelerator hints are resolved against. + * @param Boolean canUndo Whether an undo step is available (gates the Undo row). + * @param Boolean canRedo Whether a redo step is available (gates the Redo row). + * @param MenuDispatch dispatch Runs a command by id. + * @return TopLevelMenu The Edit menu. + */ +@Composable +fun editMenu( + keymap: Keymap, + canUndo: Boolean, + canRedo: Boolean, + dispatch: MenuDispatch, +): TopLevelMenu = + TopLevelMenu( + label = stringResource(Res.string.menu_edit), + items = + listOf( + commandRow(stringResource(Res.string.menu_undo), "edit.undo", keymap, dispatch, enabled = canUndo), + commandRow(stringResource(Res.string.menu_redo), "edit.redo", keymap, dispatch, enabled = canRedo), + MenuItem.Separator, + commandRow(stringResource(Res.string.menu_preferences), "edit.preferences", keymap, dispatch), + ), + ) + +/** + * Builds the Workspace menu shared by every platform's menu bar: Previous / Next (the same tab shift the + * strip's context menu and primary+PageUp / PageDown reach), then New (the same create path as the tab + * strip's "+"), Reset (the shell confirms first), and the layout's trips to and from a file. Every row + * dispatches its workspace.* command. + * + * @param Keymap keymap The keymap the accelerator hints are resolved against. + * @param MenuDispatch dispatch Runs a command by id. + * @return TopLevelMenu The Workspace menu. + */ +@Composable +fun workspaceMenu( + keymap: Keymap, + dispatch: MenuDispatch, +): TopLevelMenu = + TopLevelMenu( + label = stringResource(Res.string.menu_workspace), + items = + listOf( + commandRow(stringResource(Res.string.cmd_workspace_prev), "workspace.prev", keymap, dispatch), + commandRow(stringResource(Res.string.cmd_workspace_next), "workspace.next", keymap, dispatch), + MenuItem.Separator, + commandRow(stringResource(Res.string.workspace_new), "workspace.new", keymap, dispatch), + commandRow(stringResource(Res.string.menu_workspace_reset), "workspace.reset", keymap, dispatch), + MenuItem.Separator, + commandRow(stringResource(Res.string.menu_workspace_import), "workspace.import", keymap, dispatch), + commandRow(stringResource(Res.string.menu_workspace_export_this), "workspace.exportThis", keymap, dispatch), + commandRow(stringResource(Res.string.menu_workspace_export_all), "workspace.exportAll", keymap, dispatch), + ), + ) + +/** + * Builds the Help menu shared by every platform's menu bar: the project links, then Quick Setup, then + * Credits and About. Every row dispatches its help.* command - the links open through the shell's handler + * and the three dialogs through the overlay state the shell owns - so the palette reaches all six as well. + * + * @param Keymap keymap The keymap the accelerator hints are resolved against. + * @param MenuDispatch dispatch Runs a command by id. + * @return TopLevelMenu The Help menu. + */ +@Composable +fun helpMenu( + keymap: Keymap, + dispatch: MenuDispatch, +): TopLevelMenu = + TopLevelMenu( + label = stringResource(Res.string.menu_help), + items = + listOf( + commandRow(stringResource(Res.string.menu_source_code), "help.sourceCode", keymap, dispatch), + commandRow(stringResource(Res.string.menu_web_site), "help.webSite", keymap, dispatch), + commandRow(stringResource(Res.string.menu_documentation), "help.documentation", keymap, dispatch), + MenuItem.Separator, + commandRow(stringResource(Res.string.menu_quick_setup), "help.quickSetup", keymap, dispatch), + MenuItem.Separator, + commandRow(stringResource(Res.string.menu_credits), "help.credits", keymap, dispatch), + commandRow(stringResource(Res.string.menu_about), "help.about", keymap, dispatch), + ), + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/menu/AppMenuAssembly.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/menu/AppMenuAssembly.kt new file mode 100644 index 0000000..a3fe4e2 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/menu/AppMenuAssembly.kt @@ -0,0 +1,79 @@ +package org.umamo.ui.menu + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import org.umamo.edit.EditorSession +import org.umamo.settings.Settings +import org.umamo.ui.action.rememberLiveKeymap +import org.umamo.ui.document.recentFiles +import org.umamo.ui.kit.TopLevelMenu +import org.umamo.ui.l10n.applyAppLocale +import org.umamo.ui.l10n.rememberLocaleTag + +/** + * Builds the in-window menu bar from the shared per-menu builders, and keeps it live: the accelerators + * follow the keymap settings (so a row shows the chord the keyboard uses after a preset switch or a + * rebind), Open Recent follows the recent-files list, the Edit rows follow the session's undo and redo + * availability, and the labels follow the UI language. + * + * The bar is built outside the shell's own ProvideAppLocale scope, so it re-localizes itself: the + * key on the locale re-resolves the builders' stringResource() calls against the new catalog, and the + * remember applies the platform locale that resolution reads before the builders run. That is scoped + * to the menu alone, so a language switch re-localizes the bar without re-mounting the viewport or the + * shell underneath. + * + * @param Settings settings The settings the keymap, the recent files, and the locale are read from. + * @param EditorSession? session The open document's session, or null; gates the Undo and Redo rows. + * @param Boolean canSave Whether the open document can be saved (gates both Save rows). + * @param Boolean canExport Whether an exportable puppet document is open (gates the CMO3 and MOC3 rows). + * @param Boolean canExportImage Whether the open document can be rendered to an image (gates Export Image). + * @param MenuDispatch dispatch Runs a command by id; every row of the bar stands for a command, so this is + * all the bar needs from its host, and a rebind reaches the menu, the keyboard, and the palette alike. + * @return List The top-level menus. + */ +@Composable +internal fun buildAppMenu( + settings: Settings, + session: EditorSession?, + canSave: Boolean, + canExport: Boolean, + canExportImage: Boolean, + dispatch: MenuDispatch, +): List { + // produceState runs unconditionally (the session may be null with no document) and re-collects when + // the session swaps. + val canUndo by produceState(false, session) { + val activeSession = session + if (activeSession == null) { + value = false + } else { + activeSession.canUndo.collect { value = it } + } + } + val canRedo by produceState(false, session) { + val activeSession = session + if (activeSession == null) { + value = false + } else { + activeSession.canRedo.collect { value = it } + } + } + val keymap by rememberLiveKeymap(settings) + // Re-read on any settings change, so the Open Recent menu stays current after an open or a save. + val recentFiles by produceState(initialValue = settings.recentFiles(), settings) { + settings.changes.collect { value = settings.recentFiles() } + } + val locale by rememberLocaleTag(settings) + return key(locale) { + remember(locale) { applyAppLocale(locale) } + listOf( + fileMenu(keymap = keymap, recentFiles = recentFiles, canExport = canExport, canExportImage = canExportImage, canSave = canSave, dispatch = dispatch), + editMenu(keymap = keymap, canUndo = canUndo, canRedo = canRedo, dispatch = dispatch), + workspaceMenu(keymap = keymap, dispatch = dispatch), + helpMenu(keymap = keymap, dispatch = dispatch), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AddArtworkFlow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AddArtworkFlow.kt new file mode 100644 index 0000000..9523a57 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AddArtworkFlow.kt @@ -0,0 +1,443 @@ +package org.umamo.ui.model + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.NoticePlacement +import org.umamo.edit.OperatorParameter +import org.umamo.edit.ParameterChoice +import org.umamo.edit.ParameterUnit +import org.umamo.edit.choiceValue +import org.umamo.edit.commitArtworkAdded +import org.umamo.edit.intValue +import org.umamo.edit.withArtworkAdded +import org.umamo.edit.withAtlasRepack +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.AtlasPackSkipReason +import org.umamo.format.atlas.packAtlas +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.ArtworkAnchor +import org.umamo.interop.art.SourceArtAdditions +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.interop.art.placedBy +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.render.generatedPuppetTextures +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog + +/* + * Adding an artwork file to an OPEN document: the bridge's additions appended to the live model, the + * new tiles packed into the gaps around the art already on the pages, committed as one undo step and + * registered on the operation settings strip. The repack's shape throughout - the same pack + * primitive, the same supersede checks, the same amend-in-place adjustment - so a second artwork + * file lands the way a repack does rather than through a second pipeline. + */ + +/** The parameter keys the add-artwork rows carry (the strip maps their label keys to strings). */ +internal object ImportParameterKeys { + const val ALIGN = "import.align" + const val OFFSET_X = "import.offsetX" + const val OFFSET_Z = "import.offsetZ" + const val ALPHA_THRESHOLD = "import.alphaThreshold" + const val MARGIN = "import.margin" + + /** The prefix an Align entry's label key carries in front of its [ArtworkAnchor.key]. */ + const val ANCHOR_CHOICE_PREFIX = "import.anchor." +} + +/** The widest birth-mesh margin the strip offers, in source pixels. */ +internal const val IMPORT_MAX_MARGIN = 64 + +/** How far the Offset rows reach either way, in source pixels: past any page the pack can hold. */ +internal const val IMPORT_MAX_OFFSET = 8192 + +/** + * One artwork file to add to the open document, as read from disk. + * + * Holds the parsed art for the strip's adjustments (a re-run re-derives the additions from the same + * layers) and the decoded wrapper of every layer raster, minted once: a re-run hands the raster store + * the same instances again, and the renderer's texture cache keys on that identity. + * + * @property SourceArt art The parsed source art. + * @property ArtSourceDescriptor descriptor What the model records about the file. + * @property SourceArtImportOptions options The threshold and margin the first run uses. + */ +class AddArtworkRequest( + val art: SourceArt, + val descriptor: ArtSourceDescriptor, + val options: SourceArtImportOptions, +) { + private val decoded = DecodedLayerRasters(art.layers) + + /** + * The decoded wrapper of one of this file's layer rasters. + * + * @param LayerRaster raster The layer's pixels. + * @return DecodedImage The wrapper, the same instance on every call. + */ + internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster) +} + +/** What one add-artwork pass produced, or why it produced nothing. */ +private sealed interface AddArtworkOutcome { + /** The file has no layer with art to add. */ + data object NothingToAdd : AddArtworkOutcome + + /** + * The pack could not keep some of the document's OWN art where it is - a placed tile the packer + * would not hold fixed - so nothing was applied; the refusals name the tiles. + * + * @property List refusals The document's tiles the pack could not keep. + */ + class Refused(val refusals: List) : AddArtworkOutcome + + /** + * The additions appended and packed. + * + * @property SourceArtAdditions added The bridge's delta, pixels, and notes. + * @property PuppetModel model The base with the additions appended and packed. + * @property PuppetTextures textures The pages the pack composed, index-parallel to the model's. + * @property List notices The bridge's notes plus every added tile the pack left unplaced. + */ + class Added( + val added: SourceArtAdditions, + val model: PuppetModel, + val textures: PuppetTextures, + val notices: List, + ) : AddArtworkOutcome +} + +/** + * The strip's rows for an add-artwork operation: Align and Offset X / Z for a file placed within the + * rig's canvas, then Alpha Threshold and Birth Mesh Margin. A rig's first artwork sets the canvas + * rather than landing within it, so its step carries no placement rows. + * + * The Offset rows are in the viewport's world axes (X right, Z up, like the transform rows' Move Z), + * the same axes the options' nudge and the record's offset use, so a positive Offset Z moves the art + * up on screen; the placement negates z into canvas y where the canvas math is. + * + * @param SourceArtImportOptions options The options the rows show. + * @param Boolean placed Whether the file was placed within an existing canvas. + * @return List The rows. + */ +internal fun addArtworkParameters(options: SourceArtImportOptions, placed: Boolean): List { + val rows = ArrayList() + if (placed) { + rows.add( + OperatorParameter.ChoiceParameter( + ImportParameterKeys.ALIGN, + ImportParameterKeys.ALIGN, + options.anchor.key, + ArtworkAnchor.entries.map { anchor -> ParameterChoice(anchor.key, ImportParameterKeys.ANCHOR_CHOICE_PREFIX + anchor.key) }, + ), + ) + rows.add(OperatorParameter.IntParameter(ImportParameterKeys.OFFSET_X, ImportParameterKeys.OFFSET_X, options.nudgeX, -IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET, unit = ParameterUnit.Pixels)) + rows.add(OperatorParameter.IntParameter(ImportParameterKeys.OFFSET_Z, ImportParameterKeys.OFFSET_Z, options.nudgeZ, -IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET, unit = ParameterUnit.Pixels)) + } + rows.add(OperatorParameter.IntParameter(ImportParameterKeys.ALPHA_THRESHOLD, ImportParameterKeys.ALPHA_THRESHOLD, options.alphaThreshold, 1, 255)) + rows.add(OperatorParameter.IntParameter(ImportParameterKeys.MARGIN, ImportParameterKeys.MARGIN, options.birthMeshMargin, 0, IMPORT_MAX_MARGIN, unit = ParameterUnit.Pixels)) + return rows +} + +/** + * The options [parameters] describe, over [fallback] for the seed parameters the rows do not carry + * (and for the placement, when the step had no placement rows). + * + * @param List parameters The strip's rows. + * @param SourceArtImportOptions fallback The options the first run used. + * @return SourceArtImportOptions The adjusted options. + */ +internal fun addArtworkOptionsOf(parameters: List, fallback: SourceArtImportOptions): SourceArtImportOptions = + SourceArtImportOptions( + parameters = fallback.parameters, + alphaThreshold = parameters.intValue(ImportParameterKeys.ALPHA_THRESHOLD, fallback.alphaThreshold).coerceIn(1, 255), + birthMeshMargin = parameters.intValue(ImportParameterKeys.MARGIN, fallback.birthMeshMargin).coerceIn(0, IMPORT_MAX_MARGIN), + anchor = ArtworkAnchor.fromKey(parameters.choiceValue(ImportParameterKeys.ALIGN, fallback.anchor.key)), + nudgeX = parameters.intValue(ImportParameterKeys.OFFSET_X, fallback.nudgeX).coerceIn(-IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET), + nudgeZ = parameters.intValue(ImportParameterKeys.OFFSET_Z, fallback.nudgeZ).coerceIn(-IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET), + ) + +/** + * Appends [request]'s art to [base] and packs the new tiles into the gaps: every tile already on a + * page is handed to the packer fixed (pinned or not), the additions pack around them at the + * document's own page size (once more at [MAX_IMPORT_PAGE_SIZE] if a layer does not fit), and the + * result re-derives through [withAtlasRepack] under the document's current composition so the pages + * the existing art sits on compose exactly as they did. A new tile the pack cannot carry stays + * unplaced and is a note; the source-layer display still draws it. + * + * A file joining a rig that already has art is first placed on the rig's canvas by the options' + * anchor and nudge ([SourceArtImport.offsetFor]), and its record keeps that offset so every later + * read of the file lands the same way. The request's own art stays unplaced: an adjustment places + * it again from its rows. + * + * The new rasters are added to [artRasters] here, before the pack reads them; the store is + * document-lifetime, so an adjustment finds them already present. The pack itself is + * [packNewTilesAround], shared with the reload, relink, and match flows. + * + * @param PuppetModel base The model the additions join. + * @param AddArtworkRequest request The file. + * @param SourceArtImportOptions options The placement, threshold, and margin to import with. + * @param SourceArtRasters artRasters The document's raster store. + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @return AddArtworkOutcome? The outcome, or null when the file has no layer with art to add. + */ +private fun addArtworkOutcome( + base: PuppetModel, + request: AddArtworkRequest, + options: SourceArtImportOptions, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, +): AddArtworkOutcome { + val offset = SourceArtImport.offsetFor(base, request.art, options) + val added = SourceArtImport.additionsFor(request.art.placedBy(offset), request.descriptor, options, base, offset = offset) + if (added.additions.drawables.isEmpty()) { + return AddArtworkOutcome.NothingToAdd + } + val withArt = base.withArtworkAdded(added.additions) + if (withArt === base) { + UmamoLog.error("add artwork: the additions for '${request.descriptor.name}' collide with the document's ids; nothing was applied") + return AddArtworkOutcome.NothingToAdd + } + // A rig with no art of its own takes its frame from the file that arrives - the new document starts + // on a placeholder canvas, and the first artwork is what says how big the rig really is. A rig that + // already has art keeps its canvas: a second file is placed within that frame, not around it. + val framed = if (SourceArtImport.isFirstArtwork(base)) SourceArtImport.withFirstArtworkState(withArt, request.art) else withArt + // The parameter template seeds a rig that has none, which is what makes importing art into a new + // document behave like opening that art did. Authored axes are never replaced. + val seeded = if (framed.parameters.isEmpty()) SourceArtImport.withSeedParameters(framed, options.parameters) else framed + val decodedByTile = added.rasterByTile.mapValues { (_, raster) -> request.decodedFor(raster) } + artRasters.addDecoded(decodedByTile) + val decode: (AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] ?: artRasters.decodeRaster(tileId) } + return when (val packed = packNewTilesAround(seeded, added.additions.tiles.mapTo(HashSet()) { tile -> tile.id }, decode, premultipliedAlpha, added.notices)) { + is PackAroundOutcome.Refused -> AddArtworkOutcome.Refused(packed.refusals) + is PackAroundOutcome.Packed -> AddArtworkOutcome.Added(added, packed.model, packed.textures, packed.notices) + } +} + +/** What packing new tiles around the document's art produced, or why nothing was applied. */ +internal sealed interface PackAroundOutcome { + /** + * The pack could not keep some of the document's OWN art where it is - a placed tile the packer + * would not hold fixed - so nothing was applied; the refusals name the tiles. + * + * @property List refusals The document's tiles the pack could not keep. + */ + class Refused(val refusals: List) : PackAroundOutcome + + /** + * The new tiles packed and the model re-derived over the pages. + * + * @property PuppetModel model The model with the pack applied. + * @property PuppetTextures textures The pages the pack composed, index-parallel to the model's. + * @property List notices The caller's notes plus every new tile the pack left unplaced. + */ + class Packed( + val model: PuppetModel, + val textures: PuppetTextures, + val notices: List, + ) : PackAroundOutcome +} + +/** + * Packs the tiles [model] gained into the gaps around the art already on its pages: every tile with a + * placement is handed to the packer fixed (pinned or not), the new tiles pack around them at the + * document's own page size (once more at [MAX_IMPORT_PAGE_SIZE] if one does not fit), and the result + * re-derives through [withAtlasRepack] under the document's current composition so the pages the + * existing art sits on compose exactly as they did. Shared by Add Artwork, Reload, relink, Match + * Automatically, and Replace Artwork, which differ only in how the new tiles came to be. + * + * A refusal over the document's OWN art refuses the whole pack: the lowering would pack that tile + * out, and the document's art must not move for tiles being added. A refusal over a NEW tile is a + * note - it stays unplaced and the source-layer display still draws it. + * + * @param PuppetModel model The model carrying the new, unplaced tiles. + * @param Set newTileIds Which tiles are the new ones. + * @param Function decode The pixels of any tile, the new ones included. + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @param List notices The notes gathered so far, carried through. + * @return PackAroundOutcome The packed model and pages, or the refusal. + */ +internal fun packNewTilesAround( + model: PuppetModel, + newTileIds: Set, + decode: (AtlasTileId) -> DecodedImage?, + premultipliedAlpha: Boolean, + notices: List, +): PackAroundOutcome { + // The document's composition governs the pack, so the fixed tiles compose as they already do; the + // gutter grows to hold the extrusion when a repack widened it past the default. + val composition = model.atlas.composition + val defaults = AtlasPackOptions() + var packOptions = + AtlasPackOptions( + maxPageSize = repackPageSizeOf(model), + gutter = maxOf(defaults.gutter, composition.extrude), + extrude = composition.extrude, + alphaThreshold = composition.alphaThreshold, + ) + var packed = packAtlasOf(model, decode, packOptions, keepPinned = true, fixPlaced = true) + if (packOptions.maxPageSize < MAX_IMPORT_PAGE_SIZE && packed.result.skipped.any { skip -> skip.reason == AtlasPackSkipReason.LargerThanPage }) { + packOptions = packOptions.copy(maxPageSize = MAX_IMPORT_PAGE_SIZE) + packed = PackedAtlas(packed.input, packAtlas(packed.input.itemsFor(keepPinned = true, fixPlaced = true), packOptions)) + } + val newTileNames = model.atlas.tiles.filter { tile -> tile.id in newTileIds }.mapTo(HashSet()) { tile -> tile.name } + val refusals = repackRefusals(model, packed.result.skipped, packed.input.undecodableTileIds) + val skippedKeys = packed.result.skipped.mapTo(HashSet()) { skip -> skip.key } + val existingRefusals = + refusals.filter { refusal -> + model.atlas.tiles.any { tile -> tile.name == refusal.tileName && tile.id !in newTileIds && (tile.id.raw in skippedKeys || tile.id in packed.input.undecodableTileIds) } + } + if (existingRefusals.isNotEmpty()) { + return PackAroundOutcome.Refused(existingRefusals) + } + val allNotices = ArrayList(notices) + for (refusal in refusals) { + if (refusal.tileName !in newTileNames) { + continue + } + allNotices.add( + when (refusal.reason) { + AtlasRepackRefusalReason.LargerThanPage -> SourceArtImportNotice.LayerLargerThanPage(refusal.tileName) + else -> SourceArtImportNotice.LayerNotPacked(refusal.tileName, refusal.reason.name) + }, + ) + } + val lowered = lowerPack(model.atlas, packed.result) + val repacked = model.withAtlasRepack(lowered.pages, lowered.placementsByTile, composition) + logPack(packed.result, lowered, packOptions) + return PackAroundOutcome.Packed(repacked, generatedPuppetTextures(packed.result.pages, repacked, premultipliedAlpha), allNotices) +} + +/** + * Adds an artwork file to the open document as ONE undo step, packed beside the art already there, + * and registers the step on the operation settings strip (Alpha Threshold, Birth Mesh Margin). + * + * Runs on the UI thread; the bridge and the pack hop to the default dispatcher. The additions are + * minted against the model current at the start, so ANY edit landing while they were built + * supersedes them - stricter than the repack, whose pack only depends on the atlas and the reaches. + * + * @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks. + * @param AddArtworkRequest request The file to add. + * @param String? areaId The area the command was dispatched over, or null - where the strip shows. + * @return Boolean Whether the artwork was added. + */ +suspend fun runAddArtwork(host: AtlasRepackHost, request: AddArtworkRequest, areaId: String?): Boolean { + val session = host.session + val modelAtStart = session.model.value + val outcome = + withContext(Dispatchers.Default) { + addArtworkOutcome(modelAtStart, request, request.options, host.artRasters, host.premultipliedAlpha) + } + when (outcome) { + AddArtworkOutcome.NothingToAdd -> { + UmamoLog.warn("add artwork: '${request.descriptor.name}' has no layer with pixels to add; nothing was applied") + session.emitNotice("notice.import.noArtLayers", NoticePlacement.StatusBar) + return false + } + is AddArtworkOutcome.Refused -> { + for (refusal in outcome.refusals) { + UmamoLog.warn("add artwork: the document's tile '${refusal.tileName}' could not be kept in place (${refusal.reason}); nothing was applied") + } + host.report(AtlasRepackReport(outcome.refusals)) + return false + } + is AddArtworkOutcome.Added -> Unit + } + if (session.model.value !== modelAtStart) { + UmamoLog.warn("add artwork: the document changed while '${request.descriptor.name}' was being added; nothing was applied") + session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar) + return false + } + val drawableCount = outcome.added.additions.drawables.size + val committed = session.commitArtworkAdded(request.descriptor.name, drawableCount, outcome.model) + host.sessionAtlasPages?.prewarm(committed.atlas, outcome.textures) + reportAddArtwork(request, outcome, committed) + session.emitNotice(if (outcome.notices.isEmpty()) "notice.import.artworkAdded" else "notice.import.artworkNotes", NoticePlacement.StatusBar) + session.registerAdjustableOperation(committed, areaId, addArtworkParameters(request.options, placed = !SourceArtImport.isFirstArtwork(modelAtStart))) { record -> + host.scope.launch { adjustAddArtwork(host, record, request) } + } + return true +} + +/** + * Re-derives the additions for an adjustment of the strip: the record's rows become the options, the + * SAME parsed art is imported again over the record's base model, packed, and landed over the + * operation's own step. A record cleared while the pass ran makes [org.umamo.edit.EditorSession.amendLastCommit] + * drop the result rather than commit over what the rigger did since. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param AddArtworkRequest request The first run's file. + */ +internal suspend fun adjustAddArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: AddArtworkRequest) { + val base = record.baseSnapshot.model + val options = addArtworkOptionsOf(record.parameters, request.options) + val outcome = + withContext(Dispatchers.Default) { + addArtworkOutcome(base, request, options, host.artRasters, host.premultipliedAlpha) + } + when (outcome) { + AddArtworkOutcome.NothingToAdd -> { + UmamoLog.warn("add artwork: under the adjusted options '${request.descriptor.name}' has nothing to add; the previous result stands") + return + } + is AddArtworkOutcome.Refused -> { + host.report(AtlasRepackReport(outcome.refusals)) + return + } + is AddArtworkOutcome.Added -> Unit + } + host.sessionAtlasPages?.prewarm(outcome.model.atlas, outcome.textures) + if (!host.session.amendLastCommit(record, outcome.model)) { + UmamoLog.info("add artwork: the adjustment was superseded before it landed; nothing was applied") + return + } + reportAddArtwork(request, outcome, outcome.model) +} + +/** + * Logs one add-artwork pass the way the first run and an adjustment both report it. + * + * @param AddArtworkRequest request The file. + * @param AddArtworkOutcome outcome What the pass produced. + * @param PuppetModel committed The model that landed. + */ +private fun reportAddArtwork(request: AddArtworkRequest, outcome: AddArtworkOutcome.Added, committed: PuppetModel) { + for (notice in outcome.notices) { + UmamoLog.warn("add artwork: ${describeImportNotice(notice)}") + } + val additions = outcome.added.additions + UmamoLog.info( + "add artwork: ${request.descriptor.name} -> ${additions.drawables.size} drawable(s), ${additions.parts.size} part(s)," + + " now ${committed.atlas.pages.size} page(s); ${outcome.notices.size} note(s)", + ) +} + +/** + * One import notice as a log line: plain English naming the layer and what happened to it, the same + * shape the export notices log in. Shared by the open (an artwork-origin document) and the add. + * + * @param SourceArtImportNotice notice The notice. + * @return String The log text. + */ +fun describeImportNotice(notice: SourceArtImportNotice): String = + when (notice) { + is SourceArtImportNotice.NonRasterLayer -> "layer '${notice.layerName}' is a ${notice.kind.name.lowercase()} layer with no pixels; skipped" + is SourceArtImportNotice.EmptyLayer -> "layer '${notice.layerName}' has no opaque pixels; skipped" + is SourceArtImportNotice.BlendUnsupported -> "layer '${notice.layerName}' blends with ${notice.blend.name}, which has no equivalent; imported as Normal" + is SourceArtImportNotice.BlendApproximated -> "layer '${notice.layerName}' blends with ${notice.blend.name}; imported as the nearest mode, ${notice.mappedTo.name}" + is SourceArtImportNotice.ClipBaseMissing -> "layer '${notice.layerName}' clips to the layer below but has none in its folder; imported unclipped" + is SourceArtImportNotice.ChannelMaskDropped -> "layer '${notice.layerName}' writes only some color channels; imported writing all of them" + is SourceArtImportNotice.FolderBlendUnsupported -> "folder '${notice.groupPath}' blends with ${notice.blend.name}, which has no equivalent; its part composites as Normal" + is SourceArtImportNotice.FolderClipDropped -> "folder '${notice.groupPath}' clips to the layer below; its part imports unclipped" + is SourceArtImportNotice.LayerLargerThanPage -> "layer '${notice.layerName}' is larger than the largest atlas page; left unpacked" + is SourceArtImportNotice.LayerNotPacked -> "layer '${notice.layerName}' could not be packed (${notice.reason}); left unpacked" + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AtlasRepackFlow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AtlasRepackFlow.kt new file mode 100644 index 0000000..93cc5f4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AtlasRepackFlow.kt @@ -0,0 +1,560 @@ +package org.umamo.ui.model + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.EditorSession +import org.umamo.edit.NoticePlacement +import org.umamo.edit.commitAtlasRepack +import org.umamo.edit.withAtlasRepack +import org.umamo.format.atlas.AtlasPackFixed +import org.umamo.format.atlas.AtlasPackItem +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.AtlasPackReserve +import org.umamo.format.atlas.AtlasPackResult +import org.umamo.format.atlas.AtlasPackSkip +import org.umamo.format.atlas.AtlasPackSkipReason +import org.umamo.format.atlas.packAtlas +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.render.atlasCompositionOf +import org.umamo.render.atlasPlacementFromPack +import org.umamo.render.generatedPuppetTextures +import org.umamo.render.meshReserveByTile +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.placementAffine +import org.umamo.runtime.model.storedToArtAffineForTile +import org.umamo.storage.UmamoLog + +/** The maximum page size a repack packs against when the document has no pages to take one from. */ +const val DEFAULT_REPACK_PAGE_SIZE: Int = 4096 + +/** + * The page size an artwork import retries at when a layer's trimmed art does not fit the default page + * - the largest page the official editor's own atlas settings offer, and what desktop GL 3.3 and GLES + * 3.0 both guarantee. Art that does not fit even this stays unpacked and is named in the import notes. + */ +const val MAX_IMPORT_PAGE_SIZE: Int = 8192 + +/** Why one tile kept the whole repack from running. */ +enum class AtlasRepackRefusalReason { + /** The tile's trimmed art plus its gutter does not fit a page even alone. */ + LargerThanPage, + + /** Nothing in the tile's art meets the alpha threshold, so the pack has nothing to place. */ + NoOpaquePixels, + + /** The tile's art has opaque pixels but fewer than the pack's configured minimum. */ + BelowMinimumCoverage, + + /** The tile's art would not decode, or decodes to a size that disagrees with the tile. */ + Undecodable, + + /** The tile's current placement has no invertible mapping, so its coordinates cannot follow. */ + DegeneratePlacement, + + /** The tile is pinned at a spot that does not fit inside the maximum page size, so it cannot be kept. */ + PinnedOffPage, +} + +/** + * One tile the repack refused over. + * + * @property String tileName The tile's display name - document data, shown verbatim. + * @property AtlasRepackRefusalReason reason Why it could not come along. + */ +class AtlasRepackRefusal( + val tileName: String, + val reason: AtlasRepackRefusalReason, +) + +/** + * The repack abort report: every BOUND tile the pack could not carry. A repack is all or nothing - + * a tile with drawables that came out of the pack unplaced would leave those drawables without a + * page, so one refusal aborts the whole operation and this names each one. + * + * @property List refusals The refused tiles, in document tile order. + */ +class AtlasRepackReport( + val refusals: List, +) + +/** + * What one repack feeds the packer. + * + * The items are every tile as a FREE item; the placed tiles' placements sit beside them in the + * packer's fixed form so one decoded input serves a pack that keeps the pins, a pack that ignores + * them, and a pack that holds EVERY placed tile still (art added to an open document packs into the + * gaps) - the strip's Keep Pinned Tiles row flips between the first two without re-decoding. + * + * @property List items The tiles' pixels plus their mesh reserves, all free. + * @property Map fixedByKey The pinned placed tiles' placements as the packer's fixed form, by key. + * @property Map placedByKey EVERY placed tile's placement as the packer's fixed form, by key. + * @property Set undecodableTileIds Tiles whose art would not decode or disagrees with its tile. + * @property Map reserveByTile The mesh reserves the items were built with, kept so the commit + * can tell whether a mesh edit during the pack staled them. + */ +internal class RepackPackInput( + val items: List, + val fixedByKey: Map, + val placedByKey: Map, + val undecodableTileIds: Set, + val reserveByTile: Map, +) { + /** + * The items to pack: every placed tile fixed where it is when [fixPlaced], else the pinned tiles + * fixed when [keepPinned], else every tile free. Items hold their pixels by reference, so the + * fixed copies cost nothing. + * + * @param Boolean keepPinned Whether the pinned tiles stay put. + * @param Boolean fixPlaced Whether every placed tile stays put, pinned or not. + * @return List The pack items. + */ + fun itemsFor(keepPinned: Boolean, fixPlaced: Boolean = false): List { + val fixedForms = + when { + fixPlaced -> placedByKey + keepPinned -> fixedByKey + else -> emptyMap() + } + if (fixedForms.isEmpty()) { + return items + } + return items.map { item -> + val fixed = fixedForms[item.key] ?: return@map item + AtlasPackItem(item.key, item.width, item.height, item.rgba, item.reserve, fixed) + } + } +} + +/** + * Builds the pack input for [model]: every tile that is used OR already packed, with its pixels and + * its mesh reserve. + * + * A placed tile nobody samples keeps its spot on the pages (the file's own image entries describe it + * there), while never-packed unbound art stays out. One function shared by the live repack and the + * corpus gate, so what the gate proves disjoint is exactly what the command packs. + * + * Thread-safe given a thread-safe [decodeRaster]; the live flow runs it on the default dispatcher. + * + * @param PuppetModel model The model to pack. + * @param Function decodeRaster Yields a tile's decoded pixels, or null. + * @return RepackPackInput The pack items and the tiles that would not decode. + */ +internal fun buildRepackPackInput( + model: PuppetModel, + decodeRaster: (AtlasTileId) -> DecodedImage?, +): RepackPackInput { + val boundTileIds = model.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val reserveByTile = meshReserveByTile(model) + val items = ArrayList() + val fixedByKey = HashMap() + val placedByKey = HashMap() + val undecodable = HashSet() + for (tile in model.atlas.tiles) { + if (tile.id !in boundTileIds && tile.placement == null) { + continue + } + val raster = decodeRaster(tile.id) + if (raster == null || raster.width != tile.width || raster.height != tile.height) { + undecodable.add(tile.id) + } else { + items.add(AtlasPackItem(tile.id.raw, raster.width, raster.height, raster.rgba, reserveByTile[tile.id])) + val placement = tile.placement + if (placement != null) { + val fixed = AtlasPackFixed(placement.pageIndex, placementAffine(placement)) + placedByKey[tile.id.raw] = fixed + if (tile.pinned) { + fixedByKey[tile.id.raw] = fixed + } + } + } + } + return RepackPackInput(items, fixedByKey, placedByKey, undecodable, reserveByTile) +} + +/** + * The refusals a pack outcome implies for [model]: bound tiles the packer skipped, bound tiles whose + * art would not decode, and bound tiles whose CURRENT placement has no invertible mapping (the UV + * re-derivation reads through it, so a degenerate one strands the coordinates). Unbound tiles never + * refuse - with no drawables over them there is nothing to strand. + * + * @param PuppetModel model The model the repack would apply to. + * @param List packSkips What the packer left out, keyed by tile id. + * @param Set undecodableTileIds Bound tiles whose art would not decode. + * @return List The refusals, empty when the repack may proceed. + */ +internal fun repackRefusals( + model: PuppetModel, + packSkips: List, + undecodableTileIds: Set, +): List { + val boundTileIds = model.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val skipReasonByTileId = packSkips.associateBy({ skip -> AtlasTileId(skip.key) }, { skip -> skip.reason }) + val refusals = ArrayList() + for (tile in model.atlas.tiles) { + if (tile.id !in boundTileIds) { + continue + } + if (tile.id in undecodableTileIds) { + refusals.add(AtlasRepackRefusal(tile.name, AtlasRepackRefusalReason.Undecodable)) + continue + } + val skipReason = skipReasonByTileId[tile.id] + if (skipReason != null) { + val reason = + when (skipReason) { + AtlasPackSkipReason.LargerThanPage -> AtlasRepackRefusalReason.LargerThanPage + AtlasPackSkipReason.NoOpaquePixels -> AtlasRepackRefusalReason.NoOpaquePixels + AtlasPackSkipReason.BelowMinimumCoverage -> AtlasRepackRefusalReason.BelowMinimumCoverage + AtlasPackSkipReason.FixedOutsidePage -> AtlasRepackRefusalReason.PinnedOffPage + } + refusals.add(AtlasRepackRefusal(tile.name, reason)) + continue + } + if (tile.placement != null) { + // The same mapping the re-derivation reads: the placement plus the page it names. A page + // the model does not have counts as degenerate too - the mapping cannot be formed at all. + val storedToArt = model.atlas.storedToArtAffineForTile(tile.id) + if (storedToArt == null || invertUvAffine(storedToArt) == null) { + refusals.add(AtlasRepackRefusal(tile.name, AtlasRepackRefusalReason.DegeneratePlacement)) + } + } + } + return refusals +} + +/** + * Everything a repack needs from the shell besides its options: the session to commit into, the art + * to pack, the page resolver to pre-warm, the texture convention, the scope an adjustment re-runs on, + * and the two shell callbacks - the refusal report and the sticky-options record. Built once per + * document by the shell and handed to [runAtlasRepack]; the adjustment closure keeps it. + * + * @property EditorSession session The session to commit into. + * @property SourceArtRasters artRasters The source-art pixels to pack. + * @property SessionAtlasPages? sessionAtlasPages The session's page resolver, pre-warmed on success. + * @property Boolean premultipliedAlpha The document's texture-convention flag, carried onto the new set. + * @property CoroutineScope scope Where an adjustment's re-pack launches (the shell's scope). + * @property Function report Receives the abort report when a pack refuses. + * @property Function rememberOptions Receives the options and the keep-pinned choice every + * successful pack ran with. + */ +class AtlasRepackHost( + val session: EditorSession, + val artRasters: SourceArtRasters, + val sessionAtlasPages: SessionAtlasPages?, + val premultipliedAlpha: Boolean, + val scope: CoroutineScope, + val report: (AtlasRepackReport) -> Unit, + val rememberOptions: (AtlasPackOptions, Boolean) -> Unit, +) + +/** + * The maximum page size [model]'s repack packs against by default: its largest page's side, or + * [DEFAULT_REPACK_PAGE_SIZE] when it has none. + * + * @param PuppetModel model The document. + * @return Int The page size in pixels. + */ +fun repackPageSizeOf(model: PuppetModel): Int = model.atlas.pages.maxOfOrNull { page -> maxOf(page.width, page.height) } ?: DEFAULT_REPACK_PAGE_SIZE + +/** + * One pack before anything is committed: the decoded input and what the packer made of it. Shared + * by the repack command, the pack an artwork import runs at open, and the pack-around that lands new + * tiles in an open document, so all of them pack the same way. + * + * @property RepackPackInput input The decoded tiles and their reserves. + * @property AtlasPackResult result The packer's placements, pages, and skips. + */ +internal class PackedAtlas( + val input: RepackPackInput, + val result: AtlasPackResult, +) + +/** + * Decodes and packs [model]'s atlas under [options]. Pure and thread-agnostic given a thread-safe + * [decodeRaster]: the repack command and the artwork flows run it on the default dispatcher, the + * import at open runs it inline. + * + * @param PuppetModel model The model to pack. + * @param Function decodeRaster Yields a tile's decoded pixels, or null. + * @param AtlasPackOptions options The packing policy. + * @param Boolean keepPinned Whether pinned tiles stay where they are. + * @param Boolean fixPlaced Whether every placed tile stays where it is (added art packs + * into the gaps). + * @return PackedAtlas The input and the result, not yet lowered or committed. + */ +internal fun packAtlasOf( + model: PuppetModel, + decodeRaster: (AtlasTileId) -> DecodedImage?, + options: AtlasPackOptions, + keepPinned: Boolean = true, + fixPlaced: Boolean = false, +): PackedAtlas { + val input = buildRepackPackInput(model, decodeRaster) + return PackedAtlas(input, packAtlas(input.itemsFor(keepPinned, fixPlaced), options)) +} + +/** + * What one pack produced for the model: the new pages and every tile's lowered placement. + * + * @property List pages The new page inventory. + * @property Map placementsByTile Every tile's new placement, null for one packed out. + * @property Int packedOutCount Placed-but-unbound tiles the pack could not carry, now unpacked. + */ +internal class LoweredPack( + val pages: List, + val placementsByTile: Map, + val packedOutCount: Int, +) + +/** + * Lowers a pack result onto [atlas]'s tiles: every packed tile gets its placement, every tile the + * pack kept fixed restates the placement it already has, and every other tile is restated unpacked. + * A placed-but-unbound tile the pack could not carry (empty, oversized, undecodable) leaves the + * pages rather than blocking the repack over art nothing samples; each is logged and counted. + * + * @param PuppetAtlas atlas The atlas being repacked. + * @param AtlasPackResult packResult What the packer produced. + * @return LoweredPack The pages and placements to commit. + */ +internal fun lowerPack(atlas: PuppetAtlas, packResult: AtlasPackResult): LoweredPack { + val pages = packResult.pages.map { page -> AtlasPage(page.width, page.height) } + val packedByKey = packResult.placements.associateBy { placement -> placement.key } + val keptKeys = packResult.fixed.mapTo(HashSet()) { kept -> kept.key } + val placementsByTile = HashMap() + var packedOut = 0 + for (tile in atlas.tiles) { + if (tile.id.raw in keptKeys) { + placementsByTile[tile.id] = tile.placement + continue + } + val packed = packedByKey[tile.id.raw] + placementsByTile[tile.id] = packed?.let { placement -> atlasPlacementFromPack(placement) } + if (packed == null && tile.placement != null) { + UmamoLog.warn("repack: unbound tile '${tile.name}' could not be packed and leaves the pages") + packedOut++ + } + } + return LoweredPack(pages, placementsByTile, packedOut) +} + +/** + * Logs one pack's outcome the way both the first run and an adjustment report it. + * + * @param AtlasPackResult packResult The pack. + * @param LoweredPack lowered Its lowering. + * @param AtlasPackOptions options The options it ran with. + */ +internal fun logPack(packResult: AtlasPackResult, lowered: LoweredPack, options: AtlasPackOptions) { + val occupancy = + packResult.pages.indices.joinToString(separator = ", ") { pageIndex -> + "${(packResult.pageOccupancy(pageIndex) * 100f).toInt()}%" + } + UmamoLog.info( + "repack: ${packResult.placements.size} tile(s) onto ${lowered.pages.size} page(s) at ${options.maxPageSize} px" + + " (occupancy $occupancy; gutter ${options.gutter}, extrude ${options.extrude}, rotation ${options.allowRotation});" + + " ${packResult.fixed.size} pinned tile(s) kept, ${lowered.packedOutCount} unbound tile(s) packed out", + ) +} + +/** + * Repacks the document's atlas: decodes every bound tile's art, runs the shared deterministic packer + * under [options], and commits the new pages + placements + re-derived coordinates as ONE undo step, + * pre-warming the session's page resolver with the pages the pack already composed so nothing + * composes twice. The viewport and every UV editor follow the MODEL - the resolver publishes the + * pages and the engine swaps them - so this function ends at the commit and the registration. + * + * The commit registers itself as the session's adjustable operation (the operation settings strip): + * its rows are the pack options, and editing one re-packs the SAME decoded input from the model the + * repack ran on and lands over the repack's own history step ([EditorSession.amendLastCommit]) - one + * pack per adjustment, no decode, nothing replayed. See [adjustAtlasRepack]. + * + * All or nothing: any bound tile the pack cannot carry aborts the whole repack into the host's + * report (the modal report surface - a lost tile must not be a four-second toast). Unbound tiles + * are packed out (placement null) with a log line; art nobody samples does not spend page space. + * + * Pinned tiles stay exactly where they are while [keepPinned] (the packer seeds their footprints + * and paints them through their own placements), and pack like any other tile when it is off - the + * pin itself survives either way, so the next repack honors it again. + * + * Runs on the UI thread; the decode + pack hop to the default dispatcher. The commit applies to the + * model CURRENT at completion, so non-mesh edits made while packing survive. Two things abort as + * superseded rather than applying a stale pack: the atlas itself changing (an undo across a repack, + * say), and a mesh or coordinate edit that changes a tile's reach - the pack was spaced by the + * reserves it started with, so it no longer proves the current meshes disjoint. + * + * @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks. + * @param AtlasPackOptions options The options to pack with (the strip's rows start from them). + * @param String? areaId The area the command was dispatched over, or null - where the strip shows. + * @param Boolean keepPinned Whether pinned tiles stay where they are. + */ +suspend fun runAtlasRepack( + host: AtlasRepackHost, + options: AtlasPackOptions, + areaId: String?, + keepPinned: Boolean = true, +) { + val session = host.session + val modelAtStart = session.model.value + val atlas = modelAtStart.atlas + if (atlas.tiles.isEmpty() || !atlas.storedUvsAddressPages) { + // The command's availability gates both; a race between the check and the dispatch just no-ops. + return + } + + // Only a BOUND failure refuses the repack; a placed-unbound tile that cannot come along packs out + // instead, logged in the lowering. + val packed = + withContext(Dispatchers.Default) { + packAtlasOf(modelAtStart, { tileId -> host.artRasters.decodeRaster(tileId) }, options, keepPinned) + } + val packInput = packed.input + val packResult = packed.result + + val refusals = repackRefusals(modelAtStart, packResult.skipped, packInput.undecodableTileIds) + if (refusals.isNotEmpty()) { + for (refusal in refusals) { + UmamoLog.warn("repack: tile '${refusal.tileName}' refused (${refusal.reason}); nothing was applied") + } + host.report(AtlasRepackReport(refusals)) + return + } + val lowered = lowerPack(atlas, packResult) + + // Back on the UI thread, synchronously to the commit: a pack computed against one atlas value must + // not apply over another (an undo across a repack landing mid-pack, say). + val modelAtCommit = session.model.value + if (modelAtCommit.atlas !== modelAtStart.atlas) { + UmamoLog.warn("repack: the atlas changed while packing; nothing was applied") + session.emitNotice("notice.atlas.repackSuperseded", NoticePlacement.NearCursor) + return + } + // Same rule for the reserves: the pack is only proof of disjointness for the meshes it was spaced + // by, so a mesh edit that moved a tile's reach while packing makes it stale. + val reservesAtCommit = meshReserveByTile(modelAtCommit) + if (reservesAtCommit != packInput.reserveByTile) { + val changedTileIds = (reservesAtCommit.keys + packInput.reserveByTile.keys).filter { tileId -> reservesAtCommit[tileId] != packInput.reserveByTile[tileId] } + UmamoLog.warn( + "repack: a mesh edit changed ${changedTileIds.size} tile reach(es) while packing (${changedTileIds.take(3).joinToString { tileId -> tileId.raw }}); nothing was applied", + ) + session.emitNotice("notice.atlas.repackSuperseded", NoticePlacement.NearCursor) + return + } + val committed = session.commitAtlasRepack(lowered.pages, lowered.placementsByTile, atlasCompositionOf(options)) + if (committed == null) { + UmamoLog.info("repack: the pack reproduced the current placements exactly; nothing to change") + session.emitNotice("notice.atlas.repackUnchanged", NoticePlacement.NearCursor) + return + } + // Pre-warm BEFORE the resolver's collector resumes (it is queued behind this dispatch), so the + // commit resolves its pages by cache hit instead of composing the same pages a second time. + host.sessionAtlasPages?.prewarm(committed.atlas, generatedPuppetTextures(packResult.pages, committed, host.premultipliedAlpha)) + host.rememberOptions(options, keepPinned) + logPack(packResult, lowered, options) + session.emitNotice("notice.atlas.repacked", NoticePlacement.NearCursor) + + // The decoded input is what an adjustment keeps: a re-pack costs the pack alone. The record's + // base is the model this pack ran on, so the reserves the input was spaced by are its reserves. + session.registerAdjustableOperation(committed, areaId, repackParameters(options, keepPinned)) { record -> + host.scope.launch { adjustAtlasRepack(host, record, packInput) } + } +} + +/** + * Re-packs for an adjustment of the strip: the record's parameters become the options, the SAME + * decoded [packInput] packs again off-thread, and the result lands over the repack's own step from + * the record's base model. A refusal reports like the first run's and leaves the previous result + * standing; a record cleared while the pack ran (any other edit, an undo, a document swap) makes + * [EditorSession.amendLastCommit] drop the result rather than commit over what the rigger did. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param RepackPackInput packInput The first run's decoded input, packed again as it is. + */ +internal suspend fun adjustAtlasRepack( + host: AtlasRepackHost, + record: AdjustableOperation, + packInput: RepackPackInput, +) { + val base = record.baseSnapshot.model + val options = repackOptionsOf(record.parameters, fallback = AtlasPackOptions(maxPageSize = repackPageSizeOf(base))) + val keepPinned = repackKeepPinnedOf(record.parameters) + val packResult = + try { + withContext(Dispatchers.Default) { packAtlas(packInput.itemsFor(keepPinned), options) } + } catch (exception: IllegalArgumentException) { + // The rows keep every value inside the packer's contract, so this is a bug, not a rigger's + // mistake - but a bug in an adjustment must not take the shell's scope down with it. + UmamoLog.error("repack: the adjusted options were refused by the packer (${exception.message}); the previous result stands") + return + } + val refusals = repackRefusals(base, packResult.skipped, packInput.undecodableTileIds) + if (refusals.isNotEmpty()) { + for (refusal in refusals) { + UmamoLog.warn("repack: tile '${refusal.tileName}' refused under the adjusted options (${refusal.reason}); the previous result stands") + } + host.report(AtlasRepackReport(refusals)) + return + } + val lowered = lowerPack(base.atlas, packResult) + val repacked = base.withAtlasRepack(lowered.pages, lowered.placementsByTile, atlasCompositionOf(options)) + host.sessionAtlasPages?.prewarm(repacked.atlas, generatedPuppetTextures(packResult.pages, repacked, host.premultipliedAlpha)) + if (!host.session.amendLastCommit(record, repacked)) { + UmamoLog.info("repack: the adjustment was superseded before it landed; nothing was applied") + return + } + host.rememberOptions(options, keepPinned) + logPack(packResult, lowered, options) +} + +/** + * An artwork-origin document as it opens: the model with its pages packed, the pages themselves, and + * whatever the pack could not carry. + * + * @property PuppetModel model The packed model. + * @property PuppetTextures textures The composed pages, index-parallel to the model's page list. + * @property List refusals Bound tiles the pack left unplaced, each with the packer's reason. + */ +class PackedAtOpen( + val model: PuppetModel, + val textures: PuppetTextures, + val refusals: List, +) + +/** + * Packs an UNPACKED model's atlas as an artwork import opens it: every tile unplaced, every drawable's + * coordinates addressing its own art, which is exactly the state the repack's re-derivation moves onto + * pages through the identity mapping. Packs at [DEFAULT_REPACK_PAGE_SIZE] first and once more at + * [MAX_IMPORT_PAGE_SIZE] if any tile did not fit, then commits through [withAtlasRepack] under the + * packer's default composition. + * + * Unlike the repack command, a refusal is NOT fatal: a document is still worth opening with one layer + * unpacked, so a tile the pack cannot carry stays unplaced (its coordinates keep addressing the art, + * which the source-layer display still draws) and is reported, never dropped. + * + * @param PuppetModel model The unpacked model. + * @param Function decodeRaster Yields a tile's decoded pixels, or null. + * @return PackedAtOpen The packed model, its pages, and the refusals. + */ +fun packModelAtOpen(model: PuppetModel, decodeRaster: (AtlasTileId) -> DecodedImage?): PackedAtOpen { + var options = AtlasPackOptions(maxPageSize = DEFAULT_REPACK_PAGE_SIZE) + var packed = packAtlasOf(model, decodeRaster, options, keepPinned = false) + if (packed.result.skipped.any { skip -> skip.reason == AtlasPackSkipReason.LargerThanPage }) { + options = options.copy(maxPageSize = MAX_IMPORT_PAGE_SIZE) + packed = PackedAtlas(packed.input, packAtlas(packed.input.itemsFor(keepPinned = false), options)) + } + val refusals = repackRefusals(model, packed.result.skipped, packed.input.undecodableTileIds) + val lowered = lowerPack(model.atlas, packed.result) + val repacked = model.withAtlasRepack(lowered.pages, lowered.placementsByTile, atlasCompositionOf(options)) + logPack(packed.result, lowered, options) + return PackedAtOpen(repacked, generatedPuppetTextures(packed.result.pages, repacked, premultipliedAlpha = false), refusals) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AtlasRepackOptions.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AtlasRepackOptions.kt new file mode 100644 index 0000000..2afa958 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/AtlasRepackOptions.kt @@ -0,0 +1,160 @@ +package org.umamo.ui.model + +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.edit.ParameterChoice +import org.umamo.edit.ParameterUnit +import org.umamo.edit.booleanValue +import org.umamo.edit.choiceValue +import org.umamo.edit.intValue +import org.umamo.format.atlas.AtlasPackOptions + +/* + * The repack's face on the operation settings strip: its pack options as the strip's typed rows, and + * back, plus the session memory the next repack starts from. This file is the repack's whole + * contribution to the strip - a later operation's rows are a sibling of this file, not an edit to + * the strip. + */ + +/** The parameter keys the repack's rows carry (the strip maps their label keys to strings). */ +internal object RepackParameterKeys { + const val PAGE_SIZE = "repack.pageSize" + const val GUTTER = "repack.gutter" + const val EXTRUDE = "repack.extrude" + const val ALLOW_ROTATION = "repack.allowRotation" + const val KEEP_PINNED = "repack.keepPinned" + const val POWER_OF_TWO = "repack.powerOfTwo" + const val SQUARE_PAGES = "repack.squarePages" + const val SHRINK_PAGES = "repack.shrinkPages" + const val ALPHA_THRESHOLD = "repack.alphaThreshold" +} + +/** The maximum page sizes the strip offers; the document's own size joins the list when it is none of these. */ +internal val REPACK_PAGE_SIZE_CHOICES: List = listOf(1024, 2048, 4096, 8192, 16384) + +/** The widest gutter the strip offers, in pixels. */ +internal const val REPACK_MAX_GUTTER = 64 + +/** + * The strip's rows for [options], in display order. + * + * The extrusion's range follows the gutter: the packer requires extrude in 0..gutter, so the row can + * never offer a value the packer refuses. The page size is a choice over the common sizes because a + * free integer would invite sizes no GPU wants; the document's current size is offered even when it + * is not one of them, so an imported document's own size is always one click away. It is the + * MAXIMUM page size, and the row says so: with Shrink Pages on (the default) the packer settles on + * the smallest power-of-two side that needs no more pages than this one would, so a larger choice + * changes nothing until the art needs the room or Shrink Pages is off. Keep Pinned Tiles is the + * one row that is not a packer option: it decides whether the pinned tiles are handed to the packer + * fixed or free. + * + * @param AtlasPackOptions options The options the rows show. + * @param Boolean keepPinned Whether the pinned tiles stay where they are. + * @return List The rows. + */ +internal fun repackParameters(options: AtlasPackOptions, keepPinned: Boolean = true): List { + val pageSides = (REPACK_PAGE_SIZE_CHOICES + options.maxPageSize).distinct().sorted() + return listOf( + OperatorParameter.ChoiceParameter( + RepackParameterKeys.PAGE_SIZE, + RepackParameterKeys.PAGE_SIZE, + options.maxPageSize.toString(), + pageSides.map { side -> ParameterChoice(side.toString()) }, + ), + OperatorParameter.IntParameter(RepackParameterKeys.GUTTER, RepackParameterKeys.GUTTER, options.gutter, 0, REPACK_MAX_GUTTER, unit = ParameterUnit.Pixels), + OperatorParameter.IntParameter(RepackParameterKeys.EXTRUDE, RepackParameterKeys.EXTRUDE, options.extrude, 0, options.gutter, unit = ParameterUnit.Pixels), + OperatorParameter.BooleanParameter(RepackParameterKeys.ALLOW_ROTATION, RepackParameterKeys.ALLOW_ROTATION, options.allowRotation), + OperatorParameter.BooleanParameter(RepackParameterKeys.KEEP_PINNED, RepackParameterKeys.KEEP_PINNED, keepPinned), + OperatorParameter.BooleanParameter(RepackParameterKeys.POWER_OF_TWO, RepackParameterKeys.POWER_OF_TWO, options.powerOfTwoPages), + OperatorParameter.BooleanParameter(RepackParameterKeys.SQUARE_PAGES, RepackParameterKeys.SQUARE_PAGES, options.squarePages), + OperatorParameter.BooleanParameter(RepackParameterKeys.SHRINK_PAGES, RepackParameterKeys.SHRINK_PAGES, options.shrinkPages), + OperatorParameter.IntParameter(RepackParameterKeys.ALPHA_THRESHOLD, RepackParameterKeys.ALPHA_THRESHOLD, options.alphaThreshold, 1, 255), + ) +} + +/** + * The options [parameters] describe, over [fallback] for anything the rows do not carry. + * + * The extrusion is clamped to the gutter on the way back so an edit that narrowed the gutter under + * a wider extrusion still yields options the packer accepts; the strip re-renders from the options + * the pack actually used, so the clamp shows. + * + * @param List parameters The strip's rows. + * @param AtlasPackOptions fallback The options for rows that are absent. + * @return AtlasPackOptions The options to pack with. + */ +internal fun repackOptionsOf(parameters: List, fallback: AtlasPackOptions): AtlasPackOptions { + val gutter = parameters.intValue(RepackParameterKeys.GUTTER, fallback.gutter).coerceIn(0, REPACK_MAX_GUTTER) + return fallback.copy( + maxPageSize = parameters.choiceValue(RepackParameterKeys.PAGE_SIZE, fallback.maxPageSize.toString()).toIntOrNull() ?: fallback.maxPageSize, + gutter = gutter, + extrude = parameters.intValue(RepackParameterKeys.EXTRUDE, fallback.extrude).coerceIn(0, gutter), + allowRotation = parameters.booleanValue(RepackParameterKeys.ALLOW_ROTATION, fallback.allowRotation), + powerOfTwoPages = parameters.booleanValue(RepackParameterKeys.POWER_OF_TWO, fallback.powerOfTwoPages), + squarePages = parameters.booleanValue(RepackParameterKeys.SQUARE_PAGES, fallback.squarePages), + shrinkPages = parameters.booleanValue(RepackParameterKeys.SHRINK_PAGES, fallback.shrinkPages), + alphaThreshold = parameters.intValue(RepackParameterKeys.ALPHA_THRESHOLD, fallback.alphaThreshold).coerceIn(1, 255), + ) +} + +/** + * Whether [parameters] keep the pinned tiles where they are; true when the row is absent. + * + * @param List parameters The strip's rows. + * @return Boolean The keep-pinned choice. + */ +internal fun repackKeepPinnedOf(parameters: List): Boolean = parameters.booleanValue(RepackParameterKeys.KEEP_PINNED, true) + +/** + * The repack's session memory: the options the last pack ran with, held for the life of the window + * and deliberately never persisted to settings - the pattern the MOC3 export options use. + * + * Two lifetimes in one object. The spacing, rotation, keep-pinned, page-shape, and threshold choices + * stick across documents - a rigger who packs with rotation wants that for the next model too. The page + * size sticks only within one session: it is a property of one document's pages (its default is the + * document's own side), so carrying it onto a different document would silently pack that one at + * the previous model's size. The session is remembered by hash code, never by reference, so this + * object retains nothing of a closed document. + * + * A plain class rather than Compose state on purpose: the repack copies the returned value into its + * record, so nothing observes this between packs and it stays unit-testable. + */ +class AtlasRepackSessionOptions { + private var remembered: AtlasPackOptions? = null + private var rememberedKeepPinned: Boolean = true + private var rememberedSessionHash: Int? = null + + /** + * Whether the next repack keeps the pinned tiles where they are: the last pack's choice, or true + * before any pack. + * + * @return Boolean The keep-pinned choice. + */ + fun keepPinnedFor(): Boolean = rememberedKeepPinned + + /** + * The options the next repack should run with for [session], whose default maximum page size is + * [documentPageSize]. + * + * @param EditorSession session The document's session. + * @param Int documentPageSize The document's own maximum page size. + * @return AtlasPackOptions The options to pack with. + */ + fun optionsFor(session: EditorSession, documentPageSize: Int): AtlasPackOptions { + val sticky = remembered ?: return AtlasPackOptions(maxPageSize = documentPageSize) + return if (rememberedSessionHash == session.hashCode()) sticky else sticky.copy(maxPageSize = documentPageSize) + } + + /** + * Records what a pack for [session] ran with, making it the seed for the next. + * + * @param EditorSession session The document's session. + * @param AtlasPackOptions options The options the pack used. + * @param Boolean keepPinned Whether the pack kept the pinned tiles where they were. + */ + fun record(session: EditorSession, options: AtlasPackOptions, keepPinned: Boolean = true) { + remembered = options + rememberedKeepPinned = keepPinned + rememberedSessionHash = session.hashCode() + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/DecodedLayerRasters.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/DecodedLayerRasters.kt new file mode 100644 index 0000000..3a15b56 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/DecodedLayerRasters.kt @@ -0,0 +1,29 @@ +package org.umamo.ui.model + +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceLayer +import org.umamo.render.DecodedImage + +/** + * The decoded wrapper of every layer raster of some read art, minted once per raster: a re-run of the + * operation that read the art hands the raster store the same instances again, and the renderer's + * texture cache and the viewport's freshness test key on that identity. + * + * LayerRaster is a plain class, so the map keys by identity - which is the point: the wrapper of one + * raster is one object for the request's life. Built eagerly so the off-thread passes only read. + * + * @param List layers The layers whose rasters are wrapped. + */ +internal class DecodedLayerRasters(layers: List) { + private val decodedByRaster: Map = + layers.associate { layer -> layer.raster to DecodedImage(layer.raster.rgba, layer.raster.width, layer.raster.height) } + + /** + * The decoded wrapper of one of the layers' rasters, or a fresh wrapper for a raster the art did + * not carry. + * + * @param LayerRaster raster The layer's pixels. + * @return DecodedImage The wrapper, the same instance on every call for a known raster. + */ + fun decodedFor(raster: LayerRaster): DecodedImage = decodedByRaster[raster] ?: DecodedImage(raster.rgba, raster.width, raster.height) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/DrawableThumbnailer.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/DrawableThumbnailer.kt new file mode 100644 index 0000000..821ebeb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/DrawableThumbnailer.kt @@ -0,0 +1,498 @@ +package org.umamo.ui.model + +import androidx.compose.ui.graphics.ImageBitmap +import org.umamo.format.raster.RasterImage +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.partByDrawable +import org.umamo.ui.graphics.RgbaAlphaType +import org.umamo.ui.graphics.rgbaToImageBitmap +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.roundToInt + +/** + * Longest edge (in texels) of a single art-mesh crop. The drawable's atlas crop is nearest-downsampled to + * fit within this box so the cache stays small even for large atlas pages; the consumer then scales the + * result to its display slot. 96px is comfortably above the slots that show it (the overlap picker's + * ~44dp, the Outliner and Sources hovers' ~120dp) at any reasonable display density, so the preview stays crisp. + */ +private const val CROP_MAX_DIMENSION = 96 + +/** + * Longest edge (in pixels) of a combined part-folder or whole-model preview. A touch larger than a single + * crop because it packs several layers; a part's composite is built once and cached. + */ +private const val PART_COMPOSITE_MAX_DIMENSION = 128 + +/** + * Crops small art-mesh previews from the loaded model's atlas pages, the shared source for the viewport's + * overlap picker and the Outliner's and Sources space's hover previews (per-drawable [thumbnailFor] and combined + * [partThumbnailFor]), and for the model icon a CMO3 export writes ([modelRasterFor]). Pure CPU over the + * immutable decoded atlas bytes ([PuppetTextures.atlases]) and the drawables' mesh data - no GL, no + * render-thread hand-off - so it is safe to call straight from the Compose UI thread. Results are memoized; + * [updateModel] refreshes the model-derived inputs after every committed + * edit and evicts exactly the entries the edit staled, and [setTextures] swaps the page pixels when the + * session repacks, evicting every pixel-derived entry wholesale. + * + * Rasterises to a Compose [ImageBitmap] through the rgbaToImageBitmap platform seam (Skiko on desktop, + * android.graphics.Bitmap on Android), so one implementation serves both apps. The per-drawable crop + * covers every drawable carrying mesh UVs (not just the currently visible ones), so a hidden layer + * previews too. + * + * @property PuppetModel puppet The rig whose drawables are previewed. + * @property PuppetTextures textures The decoded atlas page(s) + per-drawable page index. + */ +class DrawableThumbnailer( + private val puppet: PuppetModel, + // var: a repack swaps the page set mid-session; setTextures re-points this and evicts the caches. + private var textures: PuppetTextures, +) : DrawableThumbnailProvider { + /** A cropped art region as raw straight-alpha RGBA (top row first), reused by both the per-drawable and part previews. */ + private class RawCrop(val rgba: ByteArray, val width: Int, val height: Int) + + /** A drawable's rest-pose model-space axis-aligned bounds, the rectangle its crop is placed into when compositing. */ + private class ModelBounds(val minX: Float, val minY: Float, val maxX: Float, val maxY: Float) { + val width: Float get() = maxX - minX + val height: Float get() = maxY - minY + } + + // Drawable id -> drawable, over the CURRENT model - refreshed by [updateModel] so a session-created + // drawable (a duplicate's fresh ".001" id) resolves for crops and bounds. + private var drawableById = puppet.drawables.associateBy { it.id } + + // Per-drawable UVs (full-atlas [0,1]), over every drawable carrying mesh UVs - the hover preview should + // work on hidden layers too, so this is not restricted to the visible/pickable set. Refreshed by + // [updateModel] alongside [drawableById]. + private var uvsByDrawable: Map = uvsFor(puppet.drawables) + + // Drawable membership + paint order and the part hierarchy a part composite is built from, over the + // CURRENT model - [updateModel] refreshes them with the rest of the model-derived inputs. UI-thread + // only (the same thread the previews are requested on). + private var currentDrawables = puppet.drawables + private var currentPartChildren: Map> = + puppet.parts.associate { part -> part.id to part.children.filterIsInstance().map { it.id } } + + // Drawable -> owning part, derived from the org tree (membership lives only there now). + private var currentDrawableOwner: Map = puppet.partByDrawable() + + // Memoized derivations. The per-drawable caches are keyed by immutable geometry / UV data; [updateModel] + // evicts an entry only when its drawable's mesh data was replaced or the drawable was removed. The part + // composites depend on membership / order and are cleared wholesale. + private val cropCache = mutableMapOf() + private val boundsCache = mutableMapOf() + private val thumbnailCache = mutableMapOf() + private val partThumbnailCache = mutableMapOf() + + /** + * Swaps the atlas page set after a repack (or its undo) and evicts every cache that read pixels or + * page indices out of the old one. Wholesale rather than per-entry: a repack moves every placed + * tile, so there is nothing selective to keep. + * + * @param PuppetTextures next The new page set. + */ + fun setTextures(next: PuppetTextures) { + if (next === textures) { + return + } + textures = next + cropCache.clear() + boundsCache.clear() + thumbnailCache.clear() + partThumbnailCache.clear() + } + + /** + * Refreshes every model-derived input after an edit and evicts exactly the caches the edit staled: + * the part composites always (membership / order may have changed), and the geometry-keyed + * per-drawable entries only where the mesh data was actually copy-on-write replaced (a remesh swaps + * uvs, a vertex move swaps positions) or the drawable was removed (a later redo may recreate the id + * with different geometry). A session-added drawable - a duplicate's fresh ".001" id - needs no + * eviction; its entries fill lazily on first request now that the lookups see it. + * + * @param PuppetModel model The current model. + */ + fun updateModel(model: PuppetModel) { + val previousById = drawableById + val newById = model.drawables.associateBy { it.id } + for (drawable in model.drawables) { + val previous = previousById[drawable.id] ?: continue + if (drawable.mesh?.uvs !== previous.mesh?.uvs) { + cropCache.remove(drawable.id) + thumbnailCache.remove(drawable.id) + } + if (drawable.mesh?.positions !== previous.mesh?.positions) { + boundsCache.remove(drawable.id) + } + } + for (removedId in previousById.keys) { + if (removedId !in newById) { + cropCache.remove(removedId) + thumbnailCache.remove(removedId) + boundsCache.remove(removedId) + } + } + drawableById = newById + uvsByDrawable = uvsFor(model.drawables) + currentDrawables = model.drawables + currentPartChildren = model.parts.associate { part -> part.id to part.children.filterIsInstance().map { it.id } } + currentDrawableOwner = model.partByDrawable() + partThumbnailCache.clear() + } + + /** + * The per-drawable full-atlas UVs over every drawable carrying mesh UVs. + * + * @param List drawables The model's drawables. + * @return Map Drawable id to its mesh UVs. + */ + private fun uvsFor(drawables: List): Map = + drawables + .mapNotNull { drawable -> drawable.mesh?.uvs?.takeIf { it.isNotEmpty() }?.let { drawable.id to it } } + .toMap() + + /** + * The cropped art preview for a drawable, or null when it is untextured, mesh-less, or unknown. Memoized. + * + * @param DrawableId id The drawable to preview. + * @return ImageBitmap? The cropped preview, or null when none is available. + */ + override fun thumbnailFor(id: DrawableId): ImageBitmap? = thumbnailCache.getOrPut(id) { croppedFor(id)?.let(::rawToImage) } + + /** + * A combined preview of every art mesh under [id] (its own drawables and its sub-parts'), placed by each + * drawable's rest-pose model bounds and composited back-to-front, or null when the part holds no textured + * drawable. Reuses the cached per-drawable crops; only the bounding-box placement and the alpha-over blit + * are new work, so it stays cheap. Memoized. + * + * @param PartId id The part to preview. + * @return ImageBitmap? The composited preview, or null when the part has no previewable art. + */ + override fun partThumbnailFor(id: PartId): ImageBitmap? = partThumbnailCache.getOrPut(id) { partRasterFor(id)?.let { raster -> rawToImage(RawCrop(raster.rgba, raster.width, raster.height)) } } + + /** + * The combined part preview of [partThumbnailFor] as a neutral raster: every art mesh under [id] + * placed by its rest-pose model bounds and composited back-to-front. Not memoized; the bitmap + * wrapper is. + * + * @param PartId id The part to preview. + * @return RasterImage? The composite, straight alpha, or null when the part has no previewable art. + */ + fun partRasterFor(id: PartId): RasterImage? { + val subtree = partSubtree(id) + val members = ArrayList>() + for (drawable in currentDrawables) { + val owningPartId = currentDrawableOwner[drawable.id] ?: continue + if (owningPartId !in subtree) { + continue + } + val crop = croppedFor(drawable.id) ?: continue + val bounds = modelBoundsOf(drawable.id) ?: continue + members += crop to bounds + } + return compositeOf(members)?.let { composite -> RasterImage(composite.width, composite.height, composite.rgba) } + } + + /** + * The whole model's rest-pose preview: every VISIBLE drawable with a crop and bounds, root-level + * ones included, composited back-to-front by the same rule as a part. This is the thumbnail a + * CMO3 export writes for the model, so the official editor shows the character the file holds + * rather than a blank tile; hidden drawables (alternate expressions, guides) stay out of it the + * way they stay out of the viewport. + * + * @return RasterImage? The composite, straight alpha, or null when no visible drawable has a crop. + */ + fun modelRasterFor(): RasterImage? { + val members = ArrayList>() + for (drawable in currentDrawables) { + if (!drawable.isVisible) { + continue + } + val crop = croppedFor(drawable.id) ?: continue + val bounds = modelBoundsOf(drawable.id) ?: continue + members += crop to bounds + } + return compositeOf(members)?.let { composite -> RasterImage(composite.width, composite.height, composite.rgba) } + } + + /** The cached raw crop for a drawable, computed once. */ + private fun croppedFor(id: DrawableId): RawCrop? = cropCache.getOrPut(id) { buildCrop(id) } + + /** + * Crops the drawable's atlas page to its mesh UV bounding box and nearest-downsamples it to fit + * [CROP_MAX_DIMENSION], preserving the straight (un-premultiplied) alpha so the silhouette survives. + * + * @param DrawableId id The drawable to crop. + * @return RawCrop? The cropped RGBA region, or null when the drawable is untextured or mesh-less. + */ + private fun buildCrop(id: DrawableId): RawCrop? { + // The atlas mapping is keyed by the source format's ids, so a session-created duplicate resolves + // its page through textureSourceId (its source, or the original for a copy of a copy) - mirroring + // the GPU upload's resolution in PuppetRenderer. + val drawable = drawableById[id] ?: return null + val atlasIndex = textures.atlasIndexByDrawableId[(drawable.textureSourceId ?: drawable.id).raw] ?: return null + val image = textures.atlases.getOrNull(atlasIndex) ?: return null + val uvs = uvsByDrawable[id] ?: return null + if (uvs.isEmpty()) { + return null + } + var minU = Float.POSITIVE_INFINITY + var maxU = Float.NEGATIVE_INFINITY + var minV = Float.POSITIVE_INFINITY + var maxV = Float.NEGATIVE_INFINITY + var pairIndex = 0 + while (pairIndex < uvs.size - 1) { + val texU = uvs[pairIndex] + val texV = uvs[pairIndex + 1] + if (texU < minU) { + minU = texU + } + if (texU > maxU) { + maxU = texU + } + if (texV < minV) { + minV = texV + } + if (texV > maxV) { + maxV = texV + } + pairIndex += 2 + } + // UV bounding box → texel rectangle, clamped to the atlas and at least one texel on each side. + val cropLeft = floor(minU * image.width).toInt().coerceIn(0, image.width - 1) + val cropTop = floor(minV * image.height).toInt().coerceIn(0, image.height - 1) + val cropRight = ceil(maxU * image.width).toInt().coerceIn(cropLeft + 1, image.width) + val cropBottom = ceil(maxV * image.height).toInt().coerceIn(cropTop + 1, image.height) + val cropWidth = cropRight - cropLeft + val cropHeight = cropBottom - cropTop + // Fit the longest edge into the crop box (never upscale a region already smaller than the box). + val scale = (CROP_MAX_DIMENSION.toFloat() / maxOf(cropWidth, cropHeight)).coerceAtMost(1f) + val thumbWidth = (cropWidth * scale).toInt().coerceAtLeast(1) + val thumbHeight = (cropHeight * scale).toInt().coerceAtLeast(1) + val rowBytes = thumbWidth * 4 + val pixels = ByteArray(rowBytes * thumbHeight) + var destRow = 0 + while (destRow < thumbHeight) { + // Nearest-neighbor: map the destination texel back to a source texel within the crop rectangle. + val sourceRow = cropTop + (destRow * cropHeight) / thumbHeight + var destColumn = 0 + while (destColumn < thumbWidth) { + val sourceColumn = cropLeft + (destColumn * cropWidth) / thumbWidth + val sourceOffset = (sourceRow * image.width + sourceColumn) * 4 + val destOffset = destRow * rowBytes + destColumn * 4 + pixels[destOffset] = image.rgba[sourceOffset] + pixels[destOffset + 1] = image.rgba[sourceOffset + 1] + pixels[destOffset + 2] = image.rgba[sourceOffset + 2] + pixels[destOffset + 3] = image.rgba[sourceOffset + 3] + destColumn += 1 + } + destRow += 1 + } + return RawCrop(pixels, thumbWidth, thumbHeight) + } + + /** The cached rest-pose model bounds for a drawable, from its mesh positions. */ + private fun modelBoundsOf(id: DrawableId): ModelBounds? = boundsCache.getOrPut(id) { computeBounds(id) } + + /** + * Computes a drawable's rest-pose model-space bounding box from its mesh positions (interleaved x, y). + * + * @param DrawableId id The drawable to bound. + * @return ModelBounds? The bounds, or null when the drawable is mesh-less or degenerate. + */ + private fun computeBounds(id: DrawableId): ModelBounds? { + val positions = drawableById[id]?.mesh?.positions ?: return null + if (positions.size < 2) { + return null + } + var minX = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + var pairIndex = 0 + while (pairIndex < positions.size - 1) { + val positionX = positions[pairIndex] + val positionY = positions[pairIndex + 1] + if (positionX < minX) { + minX = positionX + } + if (positionX > maxX) { + maxX = positionX + } + if (positionY < minY) { + minY = positionY + } + if (positionY > maxY) { + maxY = positionY + } + pairIndex += 2 + } + if (minX > maxX || minY > maxY) { + return null + } + return ModelBounds(minX, minY, maxX, maxY) + } + + /** Every part id in a part's subtree (the part itself plus all descendant parts). */ + private fun partSubtree(rootPartId: PartId): Set { + val collected = LinkedHashSet() + val pending = ArrayDeque() + pending.addLast(rootPartId) + while (pending.isNotEmpty()) { + val partId = pending.removeLast() + if (!collected.add(partId)) { + continue + } + currentPartChildren[partId]?.forEach { childPartId -> pending.addLast(childPartId) } + } + return collected + } + + /** + * Composites [members], each a cached crop with its rest-pose model bounds in the model's + * back-to-front order (the [PuppetModel.drawables] base order, so a later entry paints in front): + * unions the bounds and blits each crop into its mapped rectangle with straight-alpha + * over-compositing. Only members with both a crop and bounds belong here, so untextured or + * mesh-less layers neither inflate the union nor leave a gap. + * + * @param List members The crops to place, back to front. + * @return RawCrop? The composite, or null when there are no members or their union is degenerate. + */ + private fun compositeOf(members: List>): RawCrop? { + var unionMinX = Float.POSITIVE_INFINITY + var unionMaxX = Float.NEGATIVE_INFINITY + var unionMinY = Float.POSITIVE_INFINITY + var unionMaxY = Float.NEGATIVE_INFINITY + for ((_, bounds) in members) { + if (bounds.minX < unionMinX) { + unionMinX = bounds.minX + } + if (bounds.maxX > unionMaxX) { + unionMaxX = bounds.maxX + } + if (bounds.minY < unionMinY) { + unionMinY = bounds.minY + } + if (bounds.maxY > unionMaxY) { + unionMaxY = bounds.maxY + } + } + if (members.isEmpty()) { + return null + } + val unionWidth = unionMaxX - unionMinX + val unionHeight = unionMaxY - unionMinY + if (unionWidth <= 0f || unionHeight <= 0f) { + return null + } + val scale = PART_COMPOSITE_MAX_DIMENSION.toFloat() / max(unionWidth, unionHeight) + val compositeWidth = (unionWidth * scale).roundToInt().coerceIn(1, PART_COMPOSITE_MAX_DIMENSION) + val compositeHeight = (unionHeight * scale).roundToInt().coerceIn(1, PART_COMPOSITE_MAX_DIMENSION) + val pixels = ByteArray(compositeWidth * compositeHeight * 4) + for ((crop, bounds) in members) { + // Map model bounds straight into composite pixels: Cubism's rest-pose mesh Y runs top-down, the + // same direction as the atlas crop's rows (which display upright as the single-drawable preview), + // so no Y flip - a smaller model Y is nearer the top. Flipping here would invert each layer's + // placement (frills jump to the top, stacked eye parts jumble) while leaving symmetric parts fine. + val left = (bounds.minX - unionMinX) / unionWidth * compositeWidth + val right = (bounds.maxX - unionMinX) / unionWidth * compositeWidth + val top = (bounds.minY - unionMinY) / unionHeight * compositeHeight + val bottom = (bounds.maxY - unionMinY) / unionHeight * compositeHeight + blitOver(pixels, compositeWidth, compositeHeight, crop, left, top, right, bottom) + } + return RawCrop(pixels, compositeWidth, compositeHeight) + } + + /** + * Alpha-over-composites a [crop] into the destination buffer over the floating-point rectangle + * [leftEdge, rightEdge) x [topEdge, bottomEdge), nearest-sampling the source and clamping to the buffer. + * Straight-alpha over: outA = sa + da(1-sa); outRgb = (srcRgb·sa + dstRgb·da(1-sa)) / outA. + * + * @param ByteArray destination The composite buffer (straight RGBA, top row first). + * @param Int destinationWidth The buffer width in pixels. + * @param Int destinationHeight The buffer height in pixels. + * @param RawCrop crop The source crop to place. + * @param Float leftEdge The destination rectangle's left edge, in pixels. + * @param Float topEdge The destination rectangle's top edge, in pixels. + * @param Float rightEdge The destination rectangle's right edge, in pixels. + * @param Float bottomEdge The destination rectangle's bottom edge, in pixels. + */ + private fun blitOver( + destination: ByteArray, + destinationWidth: Int, + destinationHeight: Int, + crop: RawCrop, + leftEdge: Float, + topEdge: Float, + rightEdge: Float, + bottomEdge: Float, + ) { + val spanWidth = rightEdge - leftEdge + val spanHeight = bottomEdge - topEdge + if (spanWidth <= 0f || spanHeight <= 0f) { + return + } + val firstColumn = floor(leftEdge).toInt().coerceIn(0, destinationWidth) + val lastColumn = ceil(rightEdge).toInt().coerceIn(0, destinationWidth) + val firstRow = floor(topEdge).toInt().coerceIn(0, destinationHeight) + val lastRow = ceil(bottomEdge).toInt().coerceIn(0, destinationHeight) + var destRow = firstRow + while (destRow < lastRow) { + val normalizedY = (destRow + 0.5f - topEdge) / spanHeight + val sourceRow = (normalizedY * crop.height).toInt().coerceIn(0, crop.height - 1) + var destColumn = firstColumn + while (destColumn < lastColumn) { + val normalizedX = (destColumn + 0.5f - leftEdge) / spanWidth + val sourceColumn = (normalizedX * crop.width).toInt().coerceIn(0, crop.width - 1) + val sourceOffset = (sourceRow * crop.width + sourceColumn) * 4 + val sourceAlpha = crop.rgba[sourceOffset + 3].toInt() and 0xFF + if (sourceAlpha != 0) { + overComposite(destination, (destRow * destinationWidth + destColumn) * 4, crop.rgba, sourceOffset, sourceAlpha) + } + destColumn += 1 + } + destRow += 1 + } + } + + /** + * Over-composites one source pixel onto one destination pixel, both straight-alpha RGBA. + * + * @param ByteArray destination The destination buffer. + * @param Int destinationOffset The destination pixel's byte offset. + * @param ByteArray source The source buffer. + * @param Int sourceOffset The source pixel's byte offset. + * @param Int sourceAlpha The source pixel's alpha byte (0..255), already known non-zero. + */ + private fun overComposite(destination: ByteArray, destinationOffset: Int, source: ByteArray, sourceOffset: Int, sourceAlpha: Int) { + val sourceAlphaFraction = sourceAlpha / 255f + val destinationAlphaFraction = (destination[destinationOffset + 3].toInt() and 0xFF) / 255f + val outAlphaFraction = sourceAlphaFraction + destinationAlphaFraction * (1f - sourceAlphaFraction) + if (outAlphaFraction <= 0f) { + return + } + var channelIndex = 0 + while (channelIndex < 3) { + val sourceChannel = (source[sourceOffset + channelIndex].toInt() and 0xFF) / 255f + val destinationChannel = (destination[destinationOffset + channelIndex].toInt() and 0xFF) / 255f + val outChannel = (sourceChannel * sourceAlphaFraction + destinationChannel * destinationAlphaFraction * (1f - sourceAlphaFraction)) / outAlphaFraction + destination[destinationOffset + channelIndex] = (outChannel * 255f).roundToInt().coerceIn(0, 255).toByte() + channelIndex += 1 + } + destination[destinationOffset + 3] = (outAlphaFraction * 255f).roundToInt().coerceIn(0, 255).toByte() + } + + /** + * Wraps a raw straight-alpha RGBA crop as a Compose bitmap. The bytes are UNPREMUL (straight) so a + * transparent texel's leftover matte RGB does not ghost through additively. + * + * @param RawCrop crop The raw crop to wrap. + * @return ImageBitmap The Compose bitmap. + */ + private fun rawToImage(crop: RawCrop): ImageBitmap = rgbaToImageBitmap(crop.rgba, crop.width, crop.height, RgbaAlphaType.Straight) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/KeyableHover.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/KeyableHover.kt new file mode 100644 index 0000000..1f5f73a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/KeyableHover.kt @@ -0,0 +1,158 @@ +package org.umamo.ui.model + +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import org.umamo.edit.KeyformAim +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.ParameterId + +/** + * The keyform track the pointer is currently over - what a keyform insert aims at. + * + * A TRACK rather than a channel, so the keyform sheet's rows can publish here too: pointing at a + * Geometry row and pressing `I` has to mean something, and geometry is not addressable as a channel. + * + * Hover targeting is what lets `I` work with no prior selection: point at Opacity, press I, done. It + * mirrors the shell's existing hovered-surface seam, and like that one it is resolved at DISPATCH time, + * never latched at registration - a command reads the live hover when it fires, so it can never act on a + * row the pointer left three interactions ago. + * + * Plain mutable state rather than a flow: it changes on every pointer enter / exit and nothing needs to + * observe it reactively, only sample it when a command runs. + */ +data class KeyformHover( + /** The track under the pointer. */ + val track: KeyformTrackRef, + /** + * Where along the parameter the pointer sits, or null when the row has no position axis. + * + * A Properties row is a single value with nowhere to point AT, so it publishes null and a keyframe op + * falls back to the pose. A keyform-sheet lane spans the whole parameter, so pointing at a spot on it + * is a statement about WHICH spot - and acting on the playhead instead would ignore what was aimed at. + */ + val position: Float? = null, + /** The ordinal of the key under the pointer, or null when the pointer is not on one. */ + val keyIndex: Int? = null, + /** + * The parameter [position] and [keyIndex] are measured on, or null when the hover carries no axis of + * its own (a Properties row keys the panel's targeted parameter). + * + * A keyform-sheet lane belongs to one SECTION's parameter, which is not necessarily the selection's + * active member - a linked pad targets both of its axes at once. Without this, an insert aimed at the + * other section landed its position on the active axis, and a removal applied the hovered ordinal to + * the wrong axis's keys. + */ + val parameterId: ParameterId? = null, + /** + * The keyform-sheet row the pointer is over, or null when the hover has no sheet row (a Properties row). + * + * Carried so an authoring op can reconcile the sheet's key selection against what it changed: a removal + * renumbers the keys above it, and a selection left alone then names the neighbour rather than the key + * the user selected. Row identity is the sheet's to supply - :edit treats a row key as opaque - so it + * rides the hover, which every aimed op already goes through. + */ + val rowKey: String? = null, +) { + /** + * This hover as the aim an authoring op takes: a named place when the pointer is on a positioned row, + * else the pose. + * + * The mapping lives with the fields it reads rather than at the command that passes it on, so the rule + * that [keyIndex] only means anything alongside a [position] is stated once (see [KeyformAim]). + */ + val aim: KeyformAim + get() = position?.let { at -> KeyformAim.Position(at, keyIndex) } ?: KeyformAim.Pose +} + +class KeyableHover { + /** What the pointer is over, or null when it is over nothing keyable. */ + var hovered: KeyformHover? by mutableStateOf(null) + private set + + /** + * Records what the pointer is now over. + * + * Also called as the pointer MOVES along a lane, since the position is part of what is hovered - so + * this is a plain assignment rather than an enter-once latch. + * + * @param KeyformHover hover The track, and where on it, now under the pointer. + */ + fun enter(hover: KeyformHover) { + hovered = hover + } + + /** + * Records that the pointer left [track]. + * + * Takes the track rather than clearing unconditionally, because enter / exit events for adjacent rows + * can interleave - the new row's enter can arrive before the old row's exit, and a blind clear would + * then wipe a target the pointer is actually over. + * + * @param KeyformTrackRef track The track the pointer left. + */ + fun exit(track: KeyformTrackRef) { + if (hovered?.track == track) { + hovered = null + } + } +} + +/** + * The shell's keyable-hover holder, or null outside a shell that provides one. + * + * Static because the holder instance never changes for a shell's lifetime; only its contents do. + */ +val LocalKeyableHover = staticCompositionLocalOf { null } + +/** + * Publishes this composable as the keyable property under the pointer while it is hovered. + * + * Apply to any row that edits a keyform channel, and `I` will key it with no prior selection - the command + * samples the hover when it fires. Uses hoverable / collectIsHoveredAsState rather than raw enter-exit + * events so it behaves identically on desktop and on Android, where hover only exists with a stylus. + * + * Inert (returns the receiver unchanged) outside a shell that provides a holder, so a composable carrying + * it stays usable in isolation - a preview, or a test harness. + * + * @param KeyableTarget target The property this row edits. + * @return Modifier The modifier publishing the hover. + */ +@Composable +fun Modifier.keyableTarget(target: KeyableTarget): Modifier = keyableTrack(KeyformTrackRef.Channel(target)) + +/** + * Publishes this composable as the keyform TRACK under the pointer while it is hovered. + * + * The general form of [keyableTarget], for callers that can point at a geometry track as well as a + * channel - the keyform sheet's rows. + * + * @param KeyformTrackRef track The track this row edits. + * @return Modifier The modifier publishing the hover. + */ +@Composable +fun Modifier.keyableTrack(track: KeyformTrackRef): Modifier { + val hover = LocalKeyableHover.current ?: return this + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + DisposableEffect(hover, track, hovered) { + if (hovered) { + hover.enter(KeyformHover(track)) + } else { + hover.exit(track) + } + // Leaving composition mid-hover (the panel switching tabs under the pointer) must not strand the + // target, or the next I would key a row that is no longer on screen. + onDispose { hover.exit(track) } + } + return this.hoverable(interaction) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/KeyedFieldState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/KeyedFieldState.kt new file mode 100644 index 0000000..9609ccb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/KeyedFieldState.kt @@ -0,0 +1,126 @@ +package org.umamo.ui.model + +import androidx.compose.ui.graphics.Color +import org.umamo.edit.Pose +import org.umamo.runtime.keyform.keyIndexAt +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.channelGridsOf +import org.umamo.ui.theme.UmamoColors + +/* + * The keyed state of one editable field, and the color that expresses it - Blender's keyframe tinting. + * + * What it communicates is not decoration: BetweenKeys says "edit here and it is lost unless you key it", + * and ModifiedUnkeyed says "that is exactly what has happened". Without them, manual keying silently + * discards work on the next scrub, which is the single biggest friction a Cubism migrant hits (Cubism + * auto-keys, so the situation never arises there). + */ + +/** The keyed state of a field, in the order a rigger encounters them. */ +enum class KeyedFieldState { + /** The channel carries no track at all; the field edits a plain static and behaves like any other. */ + None, + + /** The channel is keyed and the pose sits exactly on one of its keys - editing writes that key. */ + OnKey, + + /** + * The channel is keyed but the pose is not sitting on one of its keys - an edit here needs an explicit + * key to survive. What matters is the TRACK's own axes, not which parameter happens to be targeted: + * targeting decides where an insert lands, the track decides whether the value is stored. + */ + BetweenKeys, + + /** An edit has been made and not keyed; it is showing in the viewport and dies on the next scrub. */ + ModifiedUnkeyed, +} + +/** + * The tint for this state, or null for [KeyedFieldState.None] (the field keeps its ordinary colors). + * + * @param UmamoColors colors The active scheme. + * @return Color? The tint, or null when the field is not keyed. + */ +fun KeyedFieldState.tint(colors: UmamoColors): Color? = + when (this) { + KeyedFieldState.None -> null + KeyedFieldState.OnKey -> colors.keyedOnKey + KeyedFieldState.BetweenKeys -> colors.keyedBetween + KeyedFieldState.ModifiedUnkeyed -> colors.keyedModified + } + +/** + * The FILL for this state, or null for [KeyedFieldState.None] (the control keeps its ordinary background). + * + * A text control expresses its keyed state by tinting its whole background rather than by drawing an + * outline: a 1px stroke on a 20dp field is a small thing to read across a column of rows, and the column is + * how the state is actually used. Controls whose fill already MEANS something keep the outline instead - + * a checkbox's fill is its checked state and a color swatch's fill is the user's own color, so neither has a + * background to spend. The token is translucent, so the control's own hover fill still shows through. + * + * @param UmamoColors colors The active scheme. + * @return Color? The fill, or null when the field is not keyed. + */ +fun KeyedFieldState.backgroundTint(colors: UmamoColors): Color? = + when (this) { + KeyedFieldState.None -> null + KeyedFieldState.OnKey -> colors.keyedOnKeyBackground + KeyedFieldState.BetweenKeys -> colors.keyedBetweenBackground + KeyedFieldState.ModifiedUnkeyed -> colors.keyedModifiedBackground + } + +/** + * The keyed state of [target] at [pose]. + * + * The TRACK gates everything: a channel with no track stores an edit in its owner's static, which is a + * plain undoable write with nothing uncommitted about it, so such a field is never tinted. It reads the + * pending map on every channel while a field is being scrubbed (see previewChannelEdit), so testing that + * map before the track gate would paint the orange uncommitted warning across every ordinary drag. + * + * Past that gate ModifiedUnkeyed wins over the others: a pending edit is the most recent thing the user + * did, and it is the state that carries a warning. + * + * On-key is resolved against the track's OWN axes rather than against whatever parameter is targeted, and + * that distinction is the whole difference between the tint answering "is the value under this field + * stored" and answering "is it stored on the axis you happen to have clicked". Only the first is what a + * rigger reads it as; the second would paint a keyed opacity as unstored whenever the target was the other + * half of a linked pad - or nothing at all. A multi-axis track is on-key only when the pose sits on a key + * of EVERY axis, because that is exactly when a capture overwrites a cell instead of inserting one. The + * comparison uses the evaluator's own EPS_KEY snap tolerance rather than an exact compare, so the tint + * agrees with the key the pose actually resolved to instead of flickering a hair either side of one. + * + * @param PuppetModel puppet The rig. + * @param KeyableTarget target The entity and channel the field edits. + * @param Pose pose The current pose. + * @param Map pendingEdits The session's unkeyed edits. + * @return KeyedFieldState The state to tint with. + */ +fun keyedFieldStateOf( + puppet: PuppetModel, + target: KeyableTarget, + pose: Pose, + pendingEdits: Map, +): KeyedFieldState { + val track = puppet.channelGridsOf(target.owner)?.get(target.channel) ?: return KeyedFieldState.None + if (target in pendingEdits) { + return KeyedFieldState.ModifiedUnkeyed + } + // A zero-axis track holds one value everywhere and keys nothing, so there is no key to be sitting on - + // but it still shadows the static, so an edit still needs keying. That is BetweenKeys, not OnKey. + if (track.axes.isEmpty()) { + return KeyedFieldState.BetweenKeys + } + val onEveryAxis = + track.axes.all { axis -> + // A direct lookup, not a defaults map over every parameter: this runs per keyable row per + // recomposition, and only this track's own parameters can ever be read. + val poseValue = + pose[axis.parameterId] + ?: puppet.parameters.firstOrNull { parameter -> parameter.id == axis.parameterId }?.default + ?: 0f + track.keyIndexAt(axis.parameterId, poseValue) >= 0 + } + return if (onEveryAxis) KeyedFieldState.OnKey else KeyedFieldState.BetweenKeys +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/MatchArtworkFlow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/MatchArtworkFlow.kt new file mode 100644 index 0000000..72f8daf --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/MatchArtworkFlow.kt @@ -0,0 +1,677 @@ +package org.umamo.ui.model + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.DocumentChange +import org.umamo.edit.NoticePlacement +import org.umamo.edit.OperatorParameter +import org.umamo.edit.ParameterUnit +import org.umamo.edit.commitArtworkMatched +import org.umamo.edit.commitArtworkReplaced +import org.umamo.edit.floatValue +import org.umamo.edit.withArtworkReloaded +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayerKind +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.reimport.ArtworkReloadPlanner +import org.umamo.reimport.InventoryLayerMatcher +import org.umamo.reimport.LayerMatch +import org.umamo.reimport.ReconcileResult +import org.umamo.reimport.confidentMatches +import org.umamo.reimport.retirableTiles +import org.umamo.reimport.suggestionsAgainstRead +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog + +/* + * Match Automatically and Replace Artwork: the two operations that resolve a binding the file no + * longer carries a key for. Match scores every such binding against the file's unbound layers (and + * the layers bound only to fresh, untouched drawables, which a match then retires) and rebinds the + * confident ones, with the threshold on the operation strip so the same read files re-score at another + * bar; Replace repoints one record at another file, reloading what the new file resolves by key, + * rebinding what the matcher is confident about at the same threshold row, and leaving the rest for + * review. Both pack, commit, and register exactly as a reload does, and both publish the suggestions + * they could not apply, scored with the pixels they read, for the Sources space's review chips. + */ + +/** The strip row keys the match operation reads its values back by. */ +internal object MatchParameterKeys { + const val THRESHOLD = "match.threshold" +} + +/** + * Every unresolved binding's best candidate as the flows publish it, keyed by file and lost key. + */ +typealias SourceSuggestions = Map, LayerMatch> + +/** + * The files Match Automatically scores, as read, with the decoded wrapper of every layer raster + * minted once so a re-score hands the raster store the same instances. + * + * @property List entries The present files, each with its art. + * @property Float threshold The confidence at or above which a match is applied, 0..1. + * @property SourceArtImportOptions options The threshold and margin every re-born quad uses. + * @property SourceSuggestions standing The proposals published for the review chips as they + * stand: a lost binding the read files offer no unbound candidate for falls back to its standing + * proposal when that names a layer bound only to fresh, untouched drawables (a reload minted them + * for the re-created layer), and taking it retires those drawables - so a Match after a reload + * merges at the bar the way Accept on the row does. + */ +class MatchArtworkRequest( + val entries: List, + val threshold: Float, + val options: SourceArtImportOptions, + val standing: SourceSuggestions = emptyMap(), +) { + private val decoded = DecodedLayerRasters(entries.flatMap { entry -> entry.art.layers }) + + /** + * The decoded wrapper of one of the files' layer rasters. + * + * @param LayerRaster raster The layer's pixels. + * @return DecodedImage The wrapper, the same instance on every call. + */ + internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster) +} + +/** + * One record to repoint, with the new file as read. + * + * @property ArtSourceId sourceId The record being repointed. + * @property SourceArt art The new file as read. + * @property ArtSourceDescriptor descriptor The new file's name, path, and format. + * @property String? contentHash The whole-file content hash of the bytes [art] came from. + * @property SourceArtImportOptions options The threshold and margin a re-born quad uses. + * @property Float threshold The confidence, 0..1, at or above which a binding the new + * file does not resolve by key takes its best candidate among the file's layers in the same step. + */ +class ReplaceArtworkRequest( + val sourceId: ArtSourceId, + val art: SourceArt, + val descriptor: ArtSourceDescriptor, + val contentHash: String?, + val options: SourceArtImportOptions, + val threshold: Float = InventoryLayerMatcher.DEFAULT_THRESHOLD, +) { + private val decoded = DecodedLayerRasters(art.layers) + + /** + * The inventory of [art], computed once for the request's life: the planner, the scorer, and every + * strip adjustment over this read want the same rows. + */ + val inventory: List by lazy { SourceArtImport.inventoryOf(art) } + + /** + * The decoded wrapper of one of the file's layer rasters. + * + * @param LayerRaster raster The layer's pixels. + * @return DecodedImage The wrapper, the same instance on every call. + */ + internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster) +} + +/** What one match or replace pass produced, or why it produced nothing. */ +private sealed interface MatchOutcome { + /** + * Nothing was rebound; the suggestions still stand for the review chips. + * + * @property SourceSuggestions suggestions The best candidate per unresolved binding. + */ + class NothingApplied(val suggestions: SourceSuggestions) : MatchOutcome + + /** + * The pack could not keep some of the document's own art where it is; nothing was applied. + * + * @property List refusals The document's tiles the pack could not keep. + */ + class Refused(val refusals: List) : MatchOutcome + + /** + * The delta applied and packed. + * + * @property PuppetModel model The base with the delta applied and packed. + * @property PuppetTextures? textures The pages the pack composed, index-parallel to the model's, or + * null when nothing was packed and the pages stand as they are. + * @property Map decodedByTile The new tiles' pixels, for the raster store. + * @property List notices The planner's notes plus every new tile the pack left unplaced. + * @property List outgrown Drawables whose kept mesh no longer covers the new art. + * @property DocumentChange change The step's counts. + * @property SourceSuggestions suggestions The best candidate per binding still unresolved. + * @property List rebindings What the matcher rebound and retired, for the log. + */ + class Applied( + val model: PuppetModel, + val textures: PuppetTextures?, + val decodedByTile: Map, + val notices: List, + val outgrown: List, + val change: DocumentChange, + val suggestions: SourceSuggestions, + val rebindings: List, + ) : MatchOutcome +} + +/** + * The strip rows a match registers: the threshold as a percentage beside the import rows. + * + * @param Float threshold The confidence bar, 0..1. + * @param SourceArtImportOptions options The import options the rows carry. + * @return List The rows. + */ +internal fun matchArtworkParameters(threshold: Float, options: SourceArtImportOptions): List = + listOf(OperatorParameter.FloatParameter(MatchParameterKeys.THRESHOLD, MatchParameterKeys.THRESHOLD, threshold * 100f, 0f, 100f, step = 5f, unit = ParameterUnit.Percent)) + + addArtworkParameters(options, placed = false) + +/** + * The threshold [parameters] describe, as a fraction. + * + * @param List parameters The strip's rows. + * @param Float fallback The threshold the first run used. + * @return Float The adjusted threshold, 0..1. + */ +internal fun matchThresholdOf(parameters: List, fallback: Float): Float = + (parameters.floatValue(MatchParameterKeys.THRESHOLD, fallback * 100f) / 100f).coerceIn(0f, 1f) + +/** + * The document's pixels for a tile as the matcher and planner read them. + * + * @param SourceArtRasters artRasters The document's raster store. + * @return Function The lookup, null for a tile the store cannot decode. + */ +private fun tileRasterLookup(artRasters: SourceArtRasters): (AtlasTileId) -> LayerRaster? = + { tileId -> artRasters.decodeRaster(tileId)?.let { decoded -> LayerRaster(decoded.width, decoded.height, decoded.rgba) } } + +/** + * Scores [sourceId]'s unresolved bindings against [art]: the model's inventory refreshed against the + * read art (so a file never reloaded still scores), the tiles' pixels and the art's layers handed + * to the matcher - the one scorer the reload planner runs before it mints. + * + * @param PuppetModel model The model as it stands. + * @param ArtSourceId sourceId The file. + * @param SourceArt art The file as read. + * @param List inventory The inventory of [art], computed once by the read. + * @param Function tileRaster The document's pixels for a tile. + * @return Map Each unresolved binding's best candidate, by its lost key. + */ +private fun scoreSource( + model: PuppetModel, + sourceId: ArtSourceId, + art: SourceArt, + inventory: List, + tileRaster: (AtlasTileId) -> LayerRaster?, +): Map { + val rasterByKey = art.layers.filter { layer -> layer.kind == SourceLayerKind.Raster }.associate { layer -> layer.id.raw to layer.raster } + return suggestionsAgainstRead(model, sourceId, inventory, tileRaster, { key -> rasterByKey[key] }, InventoryLayerMatcher) +} + +/** + * Scores the unresolved bindings of every file in [entries] against its art as read, with the tiles' + * pixels from the store: what a reload publishes for the review chips once it has landed. + * + * @param AtlasRepackHost host The session and the raster store. + * @param List entries The files as read. + * @return SourceSuggestions Each unresolved binding's best candidate, by file and lost key. + */ +suspend fun scoreSourceSuggestions(host: AtlasRepackHost, entries: List): SourceSuggestions = + withContext(Dispatchers.Default) { + val model = host.session.model.value + val tileRaster = tileRasterLookup(host.artRasters) + val suggestions = LinkedHashMap, LayerMatch>() + for (entry in entries) { + for ((lostKey, match) in scoreSource(model, entry.sourceId, entry.art, entry.inventory, tileRaster)) { + suggestions[entry.sourceId to lostKey] = match + } + } + suggestions + } + +/** + * Scores every file in [request] against [base], rebinds the confident matches, and packs the tiles + * they replaced around the rest. + * + * @param PuppetModel base The model the match applies to. + * @param MatchArtworkRequest request The files as read. + * @param Float threshold The confidence bar, 0..1. + * @param SourceArtImportOptions options The threshold and margin to plan with. + * @param SourceArtRasters artRasters The document's raster store (read, never written here). + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @return MatchOutcome The outcome. + */ +private fun matchOutcome( + base: PuppetModel, + request: MatchArtworkRequest, + threshold: Float, + options: SourceArtImportOptions, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, +): MatchOutcome { + var model = base + val rasters = LinkedHashMap() + val notices = ArrayList() + val outgrown = ArrayList() + val remaining = LinkedHashMap, LayerMatch>() + val rebindings = ArrayList() + var matched = 0 + val tileRaster = tileRasterLookup(artRasters) + for (entry in request.entries) { + val suggestions = LinkedHashMap(scoreSource(model, entry.sourceId, entry.art, entry.inventory, tileRaster)) + val retirable = standingMerges(model, entry, request.standing, suggestions) + val acceptedByLostKey = confidentMatches(suggestions, threshold) + for ((lostKey, match) in suggestions) { + if (lostKey !in acceptedByLostKey) { + remaining[entry.sourceId to lostKey] = match + } + } + if (acceptedByLostKey.isEmpty()) { + continue + } + // Every tile bound to an accepted lost key moves with it. + val accepted = + model.atlas.tiles.mapNotNull { tile -> + val binding = tile.source?.takeIf { source -> source.sourceId == entry.sourceId } ?: return@mapNotNull null + acceptedByLostKey[binding.layerKey]?.let { candidateKey -> tile.id to candidateKey } + } + val retire = acceptedByLostKey.values.flatMapTo(HashSet()) { candidateKey -> retirable[candidateKey].orEmpty() } + val plan = + ArtworkReloadPlanner.planMatches(model, entry.sourceId, entry.art, accepted, options, tileRaster, entry.contentHash, inventory = entry.inventory, lastModified = entry.lastModified, retire = retire) + ?: continue + val next = model.withArtworkReloaded(plan.reload) + if (next === model) { + UmamoLog.error("match artwork: the plan for '${plan.reload.source.name}' collides with the document's ids; that file was skipped") + continue + } + // The rebound tiles are the ones the plan replaced; the log names them from the model before. + rebindings.addAll( + accepted.mapNotNull { (tileId, key) -> + val tile = model.atlas.tileById[tileId] ?: return@mapNotNull null + val score = tile.source?.layerKey?.let { lostKey -> suggestions[lostKey]?.score } ?: return@mapNotNull null + Rebinding.Rebound(tile.name, entry.art.layers.firstOrNull { layer -> layer.id.raw == key }?.name ?: key, score) + }, + ) + rebindings.addAll(rebindingsOf(plan, model, entry.art).filterIsInstance()) + model = next + rasters.putAll(plan.rasterByTile) + notices.addAll(plan.notices) + outgrown.addAll(plan.reload.outgrown) + matched += plan.reload.replacedTiles.size + } + if (model === base) { + return MatchOutcome.NothingApplied(remaining) + } + val change = DocumentChange.MatchArtwork(matched, remaining.size) + return packMatched(model, rasters.mapValues { (_, raster) -> request.decodedFor(raster) }, notices, artRasters, premultipliedAlpha) { packedModel, textures, packedNotices, decodedByTile -> + MatchOutcome.Applied(packedModel, textures, decodedByTile, packedNotices, outgrown, change, remaining, rebindings) + } +} + +/** + * The standing proposals that still hold for [entry]'s file, folded into [suggestions] where the read + * offered no unbound candidate: the lost key must still be bound, the proposed layer must be present + * and bound only to tiles that carry no rig work, and those tiles are what taking the proposal retires. + * + * @param PuppetModel model The model as it stands. + * @param ReloadEntry entry The file as read. + * @param SourceSuggestions standing The published proposals. + * @param MutableMap suggestions The scored proposals, added to in place. + * @return Map> The tiles to retire per proposed layer key. + */ +private fun standingMerges(model: PuppetModel, entry: ReloadEntry, standing: SourceSuggestions, suggestions: MutableMap): Map> { + val retirable = HashMap>() + val boundKeys = model.atlas.tiles.filter { tile -> tile.source?.sourceId == entry.sourceId }.mapNotNullTo(HashSet()) { tile -> tile.source?.layerKey } + for ((binding, match) in standing) { + val (sourceId, lostKey) = binding + if (sourceId != entry.sourceId || lostKey in suggestions || lostKey !in boundKeys || match.key !in boundKeys) { + continue + } + if (entry.inventory.none { row -> row.key == match.key && !row.empty }) { + continue + } + val tiles = model.atlas.tiles.filter { tile -> tile.source?.sourceId == sourceId && tile.source?.layerKey == match.key }.map { tile -> tile.id } + val retiring = retirableTiles(model, sourceId, match.key, except = emptySet()) + if (retiring.size != tiles.size) { + // Rig work sits over the proposed layer now: the proposal no longer holds. + continue + } + suggestions[lostKey] = match + retirable[match.key] = retiring + } + return retirable +} + +/** + * Repoints [request]'s record at its new file over [base]: the bindings the file resolves by key + * reload, the confident matches rebind, the rest are flagged, and the still-unresolved ones are + * scored against the file's layers. + * + * @param PuppetModel base The model the replacement applies to. + * @param ReplaceArtworkRequest request The record and the new file. + * @param SourceArtImportOptions options The threshold and margin to plan with. + * @param Float threshold The bar a binding's best candidate must reach. + * @param SourceArtRasters artRasters The document's raster store. + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @return MatchOutcome The outcome. + */ +private fun replaceOutcome( + base: PuppetModel, + request: ReplaceArtworkRequest, + options: SourceArtImportOptions, + threshold: Float, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, +): MatchOutcome { + val tileRaster = tileRasterLookup(artRasters) + val plan = + ArtworkReloadPlanner.plan(base, request.sourceId, request.art, options, tileRaster, request.contentHash, replacement = request.descriptor, inventory = request.inventory, matchThreshold = threshold) + ?: return MatchOutcome.NothingApplied(emptyMap()) + val model = base.withArtworkReloaded(plan.reload) + if (model === base) { + UmamoLog.error("replace artwork: the plan for '${request.descriptor.name}' collides with the document's ids; nothing was applied") + return MatchOutcome.NothingApplied(emptyMap()) + } + val suggestions = plan.leftovers.entries.associate { (lostKey, match) -> (request.sourceId to lostKey) to match } + val resolvedByKey = plan.report.results.count { result -> result is ReconcileResult.Matched } + val rebound = plan.report.results.count { result -> result is ReconcileResult.Rebound } + val change = DocumentChange.ReplaceArtwork(request.descriptor.name, resolvedByKey, rebound, plan.report.needsReview.size) + val rebindings = rebindingsOf(plan, base, request.art) + return packMatched(model, plan.rasterByTile.mapValues { (_, raster) -> request.decodedFor(raster) }, plan.notices, artRasters, premultipliedAlpha) { packedModel, textures, notices, decodedByTile -> + MatchOutcome.Applied(packedModel, textures, decodedByTile, notices, plan.reload.outgrown, change, suggestions, rebindings) + } +} + +/** + * Packs the tiles a match or replace minted around the document's art and builds the outcome. + * + * @param PuppetModel model The model with the delta applied. + * @param Map decodedByTile The new tiles' pixels. + * @param List notices The notes so far. + * @param SourceArtRasters artRasters The document's raster store, for every other tile. + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @param Function applied Builds the success outcome from the packed model. + * @return MatchOutcome The outcome, refused when the document's own art could not be kept. + */ +private inline fun packMatched( + model: PuppetModel, + decodedByTile: Map, + notices: List, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, + applied: (PuppetModel, PuppetTextures?, List, Map) -> MatchOutcome, +): MatchOutcome { + if (decodedByTile.isEmpty()) { + // A replacement that resolved nothing by key mints no tile: the record and the flags land as they are. + return applied(model, null, notices, decodedByTile) + } + val decode: (AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] ?: artRasters.decodeRaster(tileId) } + return when (val packed = packNewTilesAround(model, decodedByTile.keys, decode, premultipliedAlpha, notices)) { + is PackAroundOutcome.Refused -> MatchOutcome.Refused(packed.refusals) + is PackAroundOutcome.Packed -> applied(packed.model, packed.textures, packed.notices, decodedByTile) + } +} + +/** + * Matches the document's unresolved bindings to the layers the matcher is confident about as ONE + * undo step, registers it on the strip with the threshold row beside the import rows, and publishes + * the suggestions it did not apply. Nothing confident enough is a notice, not a step, and the + * suggestions are published all the same. + * + * Runs on the UI thread; the scoring, planning, and pack hop to the default dispatcher. Planned + * against the model current at the start, so any edit landing meanwhile supersedes it. + * + * @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks. + * @param MatchArtworkRequest request The files as read and the threshold. + * @param String? areaId The area the strip shows in, or null. + * @param Function publish Takes the suggestions for the review chips. + * @return Boolean Whether a step landed. + */ +suspend fun runMatchArtwork(host: AtlasRepackHost, request: MatchArtworkRequest, areaId: String?, publish: (SourceSuggestions) -> Unit): Boolean { + val session = host.session + val modelAtStart = session.model.value + val outcome = + withContext(Dispatchers.Default) { + matchOutcome(modelAtStart, request, request.threshold, request.options, host.artRasters, host.premultipliedAlpha) + } + if (!landMatch(host, "match artwork", modelAtStart, outcome, publish) { model -> session.commitArtworkMatched(outcome.appliedChange(), model) }) { + if (outcome is MatchOutcome.NothingApplied) { + UmamoLog.info("match artwork: no binding scored at or above ${percentOf(request.threshold)}% across ${request.entries.size} file(s); ${outcome.suggestions.size} suggestion(s) published") + // No suggestion at all means no candidate was left to score - every layer is bound to rig + // work - which is a different thing to tell a person than a bar nothing reached. + session.emitNotice(if (outcome.suggestions.isEmpty()) "notice.match.noCandidates" else "notice.match.nothing", NoticePlacement.StatusBar) + } + return false + } + val change = (outcome as MatchOutcome.Applied).change as DocumentChange.MatchArtwork + session.emitNotice("notice.match.done", NoticePlacement.StatusBar, listOf(change.matchedCount.toString(), change.remainingCount.toString())) + session.registerAdjustableOperation(session.model.value, areaId, matchArtworkParameters(request.threshold, request.options)) { record -> + host.scope.launch { adjustMatchArtwork(host, record, request, publish) } + } + return true +} + +/** + * Re-scores the match for an adjustment of the strip: the record's threshold and import rows over the + * record's base model with the SAME read files, landed over the operation's own step. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param MatchArtworkRequest request The first run's files. + * @param Function publish Takes the suggestions for the review chips. + */ +internal suspend fun adjustMatchArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: MatchArtworkRequest, publish: (SourceSuggestions) -> Unit) { + adjustMatch(host, record, "match artwork", publish) { base, parameters -> + val threshold = matchThresholdOf(parameters, request.threshold) + val options = addArtworkOptionsOf(parameters, request.options) + matchOutcome(base, request, threshold, options, host.artRasters, host.premultipliedAlpha) + } +} + +/** + * Lands an adjustment of a match or replace step: [compute] runs over the record's base with the + * record's parameters, and the result replaces the operation's own step. + * + * A pass that applies nothing under the new parameters amends the step back to the base and publishes + * its suggestions - a threshold raised past every match must take the earlier rebindings with it, or + * the strip would show one bar and the document another. A pass the pack refuses is reported and + * leaves the step as it was, and a record cleared while the pass ran makes + * [org.umamo.edit.EditorSession.amendLastCommit] drop the result. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param String operation The log prefix. + * @param Function publish Takes the suggestions for the review chips. + * @param Function compute The pass over the base model and the record's parameters. + */ +private suspend fun adjustMatch( + host: AtlasRepackHost, + record: AdjustableOperation, + operation: String, + publish: (SourceSuggestions) -> Unit, + compute: (PuppetModel, List) -> MatchOutcome, +) { + val base = record.baseSnapshot.model + val outcome = withContext(Dispatchers.Default) { compute(base, record.parameters) } + when (outcome) { + is MatchOutcome.NothingApplied -> { + if (!host.session.amendLastCommit(record, base)) { + UmamoLog.info("$operation: the adjustment was superseded before it landed; nothing was applied") + return + } + UmamoLog.info("$operation: under the adjusted settings nothing applies; the step now holds the document as it was, with ${outcome.suggestions.size} suggestion(s) published") + publish(outcome.suggestions) + } + is MatchOutcome.Refused -> host.report(AtlasRepackReport(outcome.refusals)) + is MatchOutcome.Applied -> { + host.artRasters.addDecoded(outcome.decodedByTile) + prewarm(host, outcome.model, outcome.textures) + if (!host.session.amendLastCommit(record, outcome.model)) { + UmamoLog.info("$operation: the adjustment was superseded before it landed; nothing was applied") + return + } + publish(outcome.suggestions) + reportMatch(operation, outcome, outcome.model) + } + } +} + +/** + * Repoints one artwork record at another file as ONE undo step, registered on the strip with the + * threshold row ahead of the import rows, and publishes the suggestions for whatever the new file + * resolved neither by key nor by a confident match. + * + * @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks. + * @param ReplaceArtworkRequest request The record and the new file. + * @param String? areaId The area the strip shows in, or null. + * @param Function publish Takes the suggestions for the review chips. + * @return Boolean Whether the step landed. + */ +suspend fun runReplaceArtwork(host: AtlasRepackHost, request: ReplaceArtworkRequest, areaId: String?, publish: (SourceSuggestions) -> Unit): Boolean { + val session = host.session + val modelAtStart = session.model.value + val outcome = + withContext(Dispatchers.Default) { + replaceOutcome(modelAtStart, request, request.options, request.threshold, host.artRasters, host.premultipliedAlpha) + } + if (!landMatch(host, "replace artwork", modelAtStart, outcome, publish) { model -> session.commitArtworkReplaced(outcome.appliedChange(), model) }) { + return false + } + val change = (outcome as MatchOutcome.Applied).change as DocumentChange.ReplaceArtwork + session.emitNotice("notice.replace.done", NoticePlacement.StatusBar, listOf(change.matchedCount.toString(), change.reboundCount.toString(), change.missingCount.toString())) + session.registerAdjustableOperation(session.model.value, areaId, matchArtworkParameters(request.threshold, request.options)) { record -> + host.scope.launch { adjustReplaceArtwork(host, record, request, publish) } + } + return true +} + +/** + * Re-plans a replacement for an adjustment of the strip over the record's base. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param ReplaceArtworkRequest request The first run's request. + * @param Function publish Takes the suggestions for the review chips. + */ +internal suspend fun adjustReplaceArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: ReplaceArtworkRequest, publish: (SourceSuggestions) -> Unit) { + adjustMatch(host, record, "replace artwork", publish) { base, parameters -> + replaceOutcome(base, request, addArtworkOptionsOf(parameters, request.options), matchThresholdOf(parameters, request.threshold), host.artRasters, host.premultipliedAlpha) + } +} + +/** + * The applied outcome's change as the type the commit expects. + * + * @return TChange The change. + */ +private inline fun MatchOutcome.appliedChange(): TChange = (this as MatchOutcome.Applied).change as TChange + +/** + * Lands a match or replace outcome: the supersede check, the rasters into the store, the commit, the + * pre-warm, the log, and the suggestions published. A pass that applied nothing publishes its + * suggestions and returns false without a step. + * + * @param AtlasRepackHost host The session, art, resolver, and shell callbacks. + * @param String operation The log prefix. + * @param PuppetModel modelAtStart The model the outcome was planned against. + * @param MatchOutcome outcome What the pass produced. + * @param Function publish Takes the suggestions for the review chips. + * @param Function commit Commits the packed model and returns the committed one. + * @return Boolean Whether a step landed. + */ +private inline fun landMatch( + host: AtlasRepackHost, + operation: String, + modelAtStart: PuppetModel, + outcome: MatchOutcome, + publish: (SourceSuggestions) -> Unit, + commit: (PuppetModel) -> PuppetModel, +): Boolean { + val session = host.session + when (outcome) { + is MatchOutcome.NothingApplied -> { + publish(outcome.suggestions) + return false + } + is MatchOutcome.Refused -> { + for (refusal in outcome.refusals) { + UmamoLog.warn("$operation: the document's tile '${refusal.tileName}' could not be kept in place (${refusal.reason}); nothing was applied") + } + host.report(AtlasRepackReport(outcome.refusals)) + return false + } + is MatchOutcome.Applied -> Unit + } + if (session.model.value !== modelAtStart) { + UmamoLog.warn("$operation: the document changed while its files were being read; nothing was applied") + session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar) + return false + } + host.artRasters.addDecoded(outcome.decodedByTile) + val committed = commit(outcome.model) + prewarm(host, committed, outcome.textures) + publish(outcome.suggestions) + reportMatch(operation, outcome, committed) + return true +} + +/** + * Pre-warms the session's page resolver with the pages a pass composed, when it composed any. + * + * @param AtlasRepackHost host The session's resolver. + * @param PuppetModel model The model whose atlas the pages belong to. + * @param PuppetTextures? textures The pages, or null when the pass packed nothing. + */ +private fun prewarm(host: AtlasRepackHost, model: PuppetModel, textures: PuppetTextures?) { + if (textures != null) { + host.sessionAtlasPages?.prewarm(model.atlas, textures) + } +} + +/** + * Logs one match or replace pass the way the first run and an adjustment both report it. + * + * @param String operation The log prefix. + * @param MatchOutcome.Applied outcome What the pass produced. + * @param PuppetModel committed The model that landed. + */ +private fun reportMatch(operation: String, outcome: MatchOutcome.Applied, committed: PuppetModel) { + for (notice in outcome.notices) { + UmamoLog.warn("$operation: ${describeImportNotice(notice)}") + } + for (drawableId in outcome.outgrown) { + val name = committed.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.name ?: drawableId.raw + UmamoLog.warn("$operation: the new art of '$name' reaches past its edited mesh; re-mesh it or extend the mesh") + } + for ((binding, match) in outcome.suggestions) { + UmamoLog.info("$operation: '${binding.second}' in '${binding.first.raw}' left for review; best candidate '${match.key}' at ${percentOf(match.score)}%") + } + reportRebindings(operation, outcome.rebindings) + when (val change = outcome.change) { + is DocumentChange.MatchArtwork -> + UmamoLog.info("$operation: ${change.matchedCount} tile(s) rebound, ${change.remainingCount} left for review; now ${committed.atlas.pages.size} page(s); ${outcome.notices.size} note(s)") + is DocumentChange.ReplaceArtwork -> + UmamoLog.info( + "$operation: '${change.sourceName}' -> ${change.matchedCount} tile(s) reloaded by key, ${change.reboundCount} rebound by match," + + " ${change.missingCount} left for review; ${outcome.notices.size} note(s)", + ) + else -> UmamoLog.info("$operation: landed") + } +} + +/** + * A confidence as the whole percentage a person reads. + * + * @param Float score The confidence, 0..1. + * @return Int The percentage. + */ +fun percentOf(score: Float): Int = (score * 100f + 0.5f).toInt().coerceIn(0, 100) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/ModelContext.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/ModelContext.kt new file mode 100644 index 0000000..8b62e89 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/ModelContext.kt @@ -0,0 +1,243 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.State +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.ImageBitmap +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.Selection +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.viewport.PuppetViewportService + +/** + * The open document's runtime [PuppetModel] for the composition, or null when nothing is open. Panels + * (Outliner, Properties, Parameters) read `LocalPuppet.current` to display parts/parameters; the host + * app provides it. Kept in `:ui` commonMain (PuppetModel is in `:runtime`, a shared dependency) so the + * panels stay common and Android-sharable while only the GL viewport is platform code. + */ +val LocalPuppet = staticCompositionLocalOf { null } + +/** + * The open document's [EditorSession] for the composition, or null when nothing is open. The session is + * the single mutable owner of the document model, the editor state (selection, mode), and the undo + * history; mutation sites (a visibility toggle, a future rename / reparent) resolve it and call its + * mutation API, while [LocalPuppet] is the read-only model projection panels display. The host provides + * both from the same session, so a mutation republishes the model and every panel recomposes. + */ +val LocalEditorSession = staticCompositionLocalOf { null } + +/** + * A thin, platform-neutral handle for streaming transient preview models to the puppet renderer, + * mirroring [LiveParamsHandle]'s preview / commit split for model-shaped edits: [previewModel] pushes + * an uncommitted model straight to the render thread every pointer frame (no undo step, no session + * write), and the gesture boundary commits through the session as usual - whose model bridge then + * republishes the committed model. [resync] restores the renderer to the session's committed model + * after a cancelled or torn-down gesture. The UV editor drives its modal G / S / R previews through + * this; the viewport's own overlays reach the service directly and do not need it. + * + * The preview is published to the COMPOSITION as well as to the render thread, through [preview]. It + * has to be: a gesture's own area draws from its local preview and the 2D viewport follows the pushes, + * but every other read-only surface derives from [LocalPuppet] and would otherwise sit on the committed + * model until the gesture confirmed - a second UV area showing the atlas page must move with the mesh + * the viewport beside it is moving. + */ +interface PuppetRenderSync { + /** + * The uncommitted model a gesture is currently previewing, or null when none is in flight. + * + * Compose state rather than a flow: it is written from the pointer loop on the main thread and read + * during composition, so a surface that reads it recomposes with the gesture and needs no collector. + * It is NOT session state - nothing here touches history, dirty, or the committed model - so a + * surface that wants the document as SAVED keeps reading [LocalPuppet]. + */ + val preview: State + + /** + * Pushes an uncommitted preview model to the renderer (transient; no undo step). + * + * @param PuppetModel model The preview model to render. + */ + fun previewModel(model: PuppetModel) + + /** Restores the renderer to the session's committed model (a cancelled / torn-down gesture). */ + fun resync() +} + +/** + * The render-sync handle for the composition, or null when no puppet renderer is present (no document, + * or a platform without the offscreen service). Preview pushes no-op when it is null - the UV editor + * still edits, just without a live GPU preview. + */ +val LocalPuppetRenderSync = staticCompositionLocalOf { null } + +/** + * The platform render service for the composition, or null when no puppet renderer is present (no + * document, or a platform without the offscreen GL engine - Android until the GLES sibling lands). The + * UV editor requires it: it registers a UV scene - an atlas page or a source layer - to render its + * underlay through the same engine the 2D viewport uses, and owns its camera through it; with no service + * the UV editor shows the grid placeholder, exactly like the 2D viewport's body. + */ +val LocalPuppetViewportService = staticCompositionLocalOf { null } + +/** + * The open document's decoded texture atlas pages for the composition, or null when nothing is open. + * The UV editor reads the full page a drawable samples to draw under its wireframe; the thumbnail + * provider below serves the cropped-preview case. Provided by the host from the SESSION's effective + * page set ([SessionAtlasPages]), which is what the renderer shows - so the value changes when a + * repack (or its undo) swaps the pages, and the whole subtree recomposes onto the new set. A repack + * is rare, so the static local's wholesale recomposition is the right price for its simplicity. + */ +val LocalPuppetTextures = staticCompositionLocalOf { null } + +/** + * The session's atlas-page resolver, or null when nothing is open (or the desync guard built a + * fallback session). The repack command reads it to pre-warm the page cache with the pages it + * composed; everything else reads the resolved pages through [LocalPuppetTextures]. + */ +val LocalSessionAtlasPages = staticCompositionLocalOf { null } + +/** + * The open document's source artwork - the layers the puppet was authored against, before packing - + * or null when nothing is open. The UV editor's layer view shows one of these under a drawable's + * mapping, which is the pre-atlas counterpart of what [LocalPuppetTextures] serves. + * + * A document whose format retains no source art (a MOC3, the packed endpoint) provides an EMPTY + * store rather than null, so a surface distinguishes "no document" from "this document has no source + * art" without a second signal. Rasters decode on first request inside the store, so the value + * handed here stays stable for the document's life - which matters, because a static local's change + * recomposes the whole subtree. + */ +val LocalSourceArtRasters = staticCompositionLocalOf { null } + +/** + * A platform-neutral source of small art-mesh previews, mirroring [SelectionHandle] / [LiveParamsHandle]. + * The Outliner and the Sources space ask for a drawable's thumbnail on hover; the host backs it with the same crop-and-downsample + * machinery the viewport's overlap picker uses (the atlas region under the mesh UV bounds). Kept an interface + * in `:ui` commonMain so the panels stay common - the desktop wraps its Skiko rasteriser, Android will wrap + * its own. A null provider (or a null result) means no preview, so callers simply show nothing. + */ +interface DrawableThumbnailProvider { + /** + * The cropped art preview for a drawable, or null when it is untextured, mesh-less, or unknown. + * + * @param DrawableId id The drawable to preview. + * @return ImageBitmap? The preview bitmap, or null when none is available. + */ + fun thumbnailFor(id: DrawableId): ImageBitmap? + + /** + * A combined preview of every art mesh under a part (its own drawables and those of its sub-parts), + * assembled in rest-pose model space so it reads like the part's art, or null when the part holds no + * textured drawable. Built by placing each drawable's cached crop at its model-space bounding box and + * compositing back-to-front, so it reuses the per-drawable previews rather than re-rendering geometry. + * + * @param PartId id The part to preview. + * @return ImageBitmap? The composited preview, or null when the part has no previewable art. + */ + fun partThumbnailFor(id: PartId): ImageBitmap? +} + +/** + * The drawable-thumbnail provider for the composition, or null when none is wired (e.g. no document open, + * or a platform without the renderer). The Outliner and Sources hover previews no-op when it is null. + */ +val LocalDrawableThumbnails = staticCompositionLocalOf { null } + +/** + * A thin, platform-neutral handle for reading and writing live parameter values (the pose) from common + * UI (the Parameters sliders) without `:ui` knowing how the value reaches the GL render thread or how it + * is recorded for undo. Scrubbing is a two-phase gesture: [preview] streams the in-progress value + * straight to the renderer every frame (transient — no undo step, no recompose churn), and [commit] + * records one undo step at the gesture boundary (drag release, a typed value, a reset). So a whole slider + * drag is a single undo step. The desktop implementation writes its volatile LiveParams hand-off on + * preview and routes commit through the EditorSession; Android will wrap its own. + */ +interface LiveParamsHandle { + /** The current parameter values (parameter id → value). */ + val values: Map + + /** + * The same values, read as Compose state so whatever reads them recomposes when the pose moves - + * including mid-scrub, where [values] is a plain volatile read that no observer ever sees change. + * + * Deliberately a second property rather than making [values] observable. The scrub path writes on + * every pointer move, so a caller that only needs the pose once (seeding a control, constructing a + * session) must be able to read it WITHOUT taking a per-frame recomposition dependency on it. + */ + val observedValues: Map + + /** + * Previews one parameter's live value toward the renderer without recording an undo step. Called every + * frame of a scrub gesture; the matching [commit] records the single step on release. + * + * @param ParameterId id The parameter to set. + * @param Float value The new value. + */ + fun preview(id: ParameterId, value: Float) + + /** + * Records the current pose as one undo step, ending a scrub gesture. The values previewed since the + * gesture began are captured as a single step labelled by which parameters [changedIds] moved. + * + * @param Set changedIds The parameters this gesture moved (for the history-panel label). + */ + fun commit(changedIds: Set) +} + +/** + * The live-parameter handle for the composition, or null when no posable document is open. The + * Parameters space writes slider changes here; the host wires it to the renderer. + */ +val LocalLiveParams = staticCompositionLocalOf { null } + +/** + * A thin, platform-neutral handle for reading and writing the current object-mode [Selection] from + * common UI, mirroring [LiveParamsHandle]. The Outliner and viewport write gestures through it; the + * Properties panel and the highlight bridge read it. The desktop implementation backs it with Compose state + * so panels recompose on change; Android will wrap its own. + */ +interface SelectionHandle { + /** The current selection. */ + val selection: Selection + + /** + * Replaces the current selection. + * + * @param Selection selection The new selection. + */ + fun set(selection: Selection) +} + +/** + * The selection handle for the composition, or null when no document is open. Panels read + * `LocalSelection.current?.selection`; gesture sites call `set`. + */ +val LocalSelection = staticCompositionLocalOf { null } + +/** + * A platform-neutral handle for reading and setting the current [EditorMode], mirroring + * [SelectionHandle]. The mode-toggle command and, later, the radial menu write it; the viewport pick + * router and the Properties panel read it. + */ +interface EditorModeHandle { + /** The current editor mode. */ + val mode: EditorMode + + /** + * Sets the editor mode. + * + * @param EditorMode mode The new mode. + */ + fun set(mode: EditorMode) +} + +/** + * The editor-mode handle for the composition, or null when no document is open. A null handle is + * treated as [EditorMode.Object] by callers. + */ +val LocalEditorMode = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/NoticeText.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/NoticeText.kt new file mode 100644 index 0000000..0825eab --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/NoticeText.kt @@ -0,0 +1,88 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.resources.* + +/** + * Maps a [org.umamo.edit.Notice.messageKey] to its localized message. The keys mirror those emitted by + * :edit (which stays presentation-free, so it cannot hold display strings itself - the same pattern as + * the history labels); an unmapped key falls back to a generic message so a newly added notice never + * renders blank. + * + * @param String messageKey The notice's stable message key. + * @param List arguments The values a formatting message substitutes, in placeholder order. + * @return String The localized notice message. + */ +@Composable +fun noticeText(messageKey: String, arguments: List = emptyList()): String = + when (messageKey) { + "notice.transform.onlyDrawables" -> stringResource(Res.string.notice_transform_only_drawables) + "notice.transform.deformed" -> stringResource(Res.string.notice_transform_deformed) + "notice.deformer.createWarp.none" -> stringResource(Res.string.notice_deformer_create_warp_none) + "notice.keyform.noTarget" -> stringResource(Res.string.notice_keyform_no_target) + "notice.keyform.noParameter" -> stringResource(Res.string.notice_keyform_no_parameter) + "notice.merge.needsVertices" -> stringResource(Res.string.notice_merge_needs_vertices) + "notice.connect.needsTwoVertices" -> stringResource(Res.string.notice_connect_needs_two_vertices) + "notice.connect.refused" -> stringResource(Res.string.notice_connect_refused) + "notice.addVertex.refused" -> stringResource(Res.string.notice_add_vertex_refused) + "notice.rip.nothing" -> stringResource(Res.string.notice_rip_nothing) + "notice.uv.noUvs" -> stringResource(Res.string.notice_uv_no_uvs) + "notice.uv.noSelection" -> stringResource(Res.string.notice_uv_no_selection) + "notice.uv.placement.layerAddressed" -> stringResource(Res.string.notice_uv_placement_layer_addressed) + "notice.uv.placement.noPlacedArt" -> stringResource(Res.string.notice_uv_placement_no_placed_art) + "notice.uv.placement.pageViewOnly" -> stringResource(Res.string.notice_uv_placement_page_view_only) + "notice.uv.placement.notOnPage" -> stringResource(Res.string.notice_uv_placement_not_on_page) + "notice.uv.placement.notDerivable" -> stringResource(Res.string.notice_uv_placement_not_derivable) + "notice.uv.placement.overlap" -> stringResource(Res.string.notice_uv_placement_overlap) + "notice.uv.placement.offPage" -> stringResource(Res.string.notice_uv_placement_off_page) + "notice.uv.placement.pinned" -> stringResource(Res.string.notice_uv_placement_pinned) + "notice.edit.noEditableGeometry" -> stringResource(Res.string.notice_edit_no_editable_geometry) + "notice.display.partialSourceArtwork" -> stringResource(Res.string.notice_display_partial_source_artwork) + "notice.display.sourceArtworkUnavailable" -> stringResource(Res.string.notice_display_source_artwork_unavailable) + "notice.atlas.repacked" -> stringResource(Res.string.notice_atlas_repacked) + "notice.import.artworkNotes" -> stringResource(Res.string.notice_import_artwork_notes) + "notice.import.artworkAdded" -> stringResource(Res.string.notice_import_artwork_added) + "notice.document.saving" -> stringResource(Res.string.notice_document_saving) + "notice.document.saved" -> stringResource(Res.string.notice_document_saved, arguments.firstOrNull().orEmpty()) + "notice.document.saveBusy" -> stringResource(Res.string.notice_document_save_busy) + "notice.document.exportingImage" -> stringResource(Res.string.notice_document_exporting_image) + "notice.document.exportedImage" -> stringResource(Res.string.notice_document_exported_image, arguments.firstOrNull().orEmpty()) + "notice.document.waitingForSave" -> stringResource(Res.string.notice_document_waiting_for_save) + "notice.document.cmo3Loss" -> stringResource(Res.string.notice_document_cmo3_loss) + "notice.document.moc3Loss" -> stringResource(Res.string.notice_document_moc3_loss) + "notice.import.artworkSuperseded" -> stringResource(Res.string.notice_import_artwork_superseded) + "notice.import.noArtLayers" -> stringResource(Res.string.notice_import_no_art_layers) + "notice.reload.done" -> stringResource(Res.string.notice_reload_done, *countArguments(arguments, 3)) + "notice.reload.notes" -> stringResource(Res.string.notice_reload_notes, *countArguments(arguments, 4)) + "notice.reload.outgrown" -> stringResource(Res.string.notice_reload_outgrown, *countArguments(arguments, 4)) + "notice.watch.changed" -> stringResource(Res.string.notice_watch_changed, *countArguments(arguments, 1)) + "notice.watch.staleAtOpen" -> stringResource(Res.string.notice_watch_stale_at_open, *countArguments(arguments, 1)) + "notice.watch.missing" -> stringResource(Res.string.notice_watch_missing, arguments.firstOrNull().orEmpty()) + "notice.reload.noChanges" -> stringResource(Res.string.notice_reload_no_changes) + "notice.reload.noFiles" -> stringResource(Res.string.notice_reload_no_files) + "notice.relink.pulled" -> stringResource(Res.string.notice_relink_pulled) + "notice.relink.bindingOnly" -> stringResource(Res.string.notice_relink_binding_only) + "notice.match.done" -> stringResource(Res.string.notice_match_done, *countArguments(arguments, 2)) + "notice.match.nothing" -> stringResource(Res.string.notice_match_nothing) + "notice.match.noCandidates" -> stringResource(Res.string.notice_match_no_candidates) + "notice.replace.done" -> stringResource(Res.string.notice_replace_done, *countArguments(arguments, 3)) + "notice.atlas.repackSuperseded" -> stringResource(Res.string.notice_atlas_repack_superseded) + "notice.atlas.repackUnchanged" -> stringResource(Res.string.notice_atlas_repack_unchanged) + "notice.proportional.on" -> stringResource(Res.string.notice_proportional_on) + "notice.proportional.off" -> stringResource(Res.string.notice_proportional_off) + "notice.proportional.connected.on" -> stringResource(Res.string.notice_proportional_connected_on) + "notice.proportional.connected.off" -> stringResource(Res.string.notice_proportional_connected_off) + else -> stringResource(Res.string.notice_unknown) + } + +/** + * The first [count] arguments as integers for a message that formats counts, zero for any the notice + * did not carry - a placeholder must never go unfilled. + * + * @param List arguments The notice's arguments. + * @param Int count How many the message formats. + * @return Array The values to substitute. + */ +private fun countArguments(arguments: List, count: Int): Array = + Array(count) { index -> arguments.getOrNull(index)?.toIntOrNull() ?: 0 } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/OverlapPickerPopup.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/OverlapPickerPopup.kt new file mode 100644 index 0000000..8de7b5a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/OverlapPickerPopup.kt @@ -0,0 +1,184 @@ +package org.umamo.ui.model + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupProperties +import org.umamo.runtime.model.DrawableId +import org.umamo.ui.kit.AtPointPositionProvider +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.ThumbnailSlot +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * One row of the overlap picker: a drawable to select, its display label, and an optional layer-art + * thumbnail (shown in the row's leading slot when present, or an empty slot when null). + * + * @property DrawableId id The drawable this row selects. + * @property String label The display label (the Outliner shows the same). + * @property ImageBitmap? thumbnail A layer-art thumbnail for the leading slot, or null. + */ +data class OverlapEntry(val id: DrawableId, val label: String, val thumbnail: ImageBitmap? = null) + +/** + * A command-palette-styled popup for choosing among art meshes stacked under the cursor, when a single + * click is ambiguous. Anchored at [anchor]; lists [entries] front-to-back with [defaultIndex] (the most + * "unambiguously clicked" mesh) pre-highlighted. There is exactly one highlight state (Blender-style, + * no separate hover): moving the mouse over a row and pressing Up/Down both drive it, Enter or a click + * picks it, Escape or a click outside dismisses. The popup itself is shared, ordinary Compose content; + * desktop's Object gizmo triggers it with an Alt-click, and Android's own trigger (a pen long-press) is + * intended for once its GLES viewport and gizmo overlay land. The popup never touches the selection + * state; it reports the chosen drawable through [onPick] and closure through [onDismiss]. + * + * @param IntOffset anchor The cursor position to anchor the popup at, local to the popup's + * parent layout node (AtPointPositionProvider offsets from the + * parent's bounds, clamped into the window). + * @param List entries The candidates, front-to-back. + * @param Int defaultIndex The pre-highlighted row (the centrality winner). + * @param Function onPick Called with the chosen drawable id. + * @param Function onDismiss Called to close without choosing. + */ +@Composable +fun OverlapPickerPopup( + anchor: IntOffset, + entries: List, + defaultIndex: Int, + onPick: (DrawableId) -> Unit, + onDismiss: () -> Unit, +) { + if (entries.isEmpty()) { + return + } + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + var highlighted by remember(entries) { mutableStateOf(defaultIndex.coerceIn(0, entries.size - 1)) } + val focusRequester = remember { FocusRequester() } + // Grab focus on open so the navigation keys reach onPreviewKeyEvent (the popup has no text field to + // hold focus, unlike the command palette). + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + Popup( + popupPositionProvider = AtPointPositionProvider(anchor), + onDismissRequest = onDismiss, + properties = PopupProperties(focusable = true), + ) { + Surface( + modifier = + Modifier + .focusRequester(focusRequester) + .focusable() + .onPreviewKeyEvent { event -> + if (event.type != KeyEventType.KeyDown) { + false + } else { + when (event.key) { + Key.DirectionDown -> { + highlighted = (highlighted + 1) % entries.size + true + } + + Key.DirectionUp -> { + highlighted = (highlighted - 1 + entries.size) % entries.size + true + } + + Key.Enter, Key.NumPadEnter -> { + onPick(entries[highlighted].id) + true + } + + Key.Escape -> { + onDismiss() + true + } + + else -> false + } + } + }, + color = colors.menuBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.width(IntrinsicSize.Max)) { + entries.forEachIndexed { index, entry -> + val isHighlighted = index == highlighted + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp, vertical = 4.dp) + .background( + if (isHighlighted) colors.selection else Color.Transparent, + shape = LocalUmamoShapes.current.small, + ) + .pointerInput(index) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + // Move only, deliberately not Enter: the popup opens under a + // stationary cursor, and a synthesized hover on open would stomp + // the pre-highlighted centrality winner. Real movement over a row + // steals the single highlight the arrow keys also drive. + if (event.type == PointerEventType.Move) { + highlighted = index + } + } + } + } + .clickable { onPick(entry.id) } + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + // Leading layer-art thumbnail. A checker backdrop sits behind it so transparent art reads as + // a clear silhouette; an untextured drawable leaves the slot empty so label-only rows align. + ThumbnailSlot(thumbnail = entry.thumbnail) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = entry.label, + style = typography.bodyMedium, + color = if (isHighlighted) colors.selectionText else colors.text, + modifier = Modifier.weight(1f), + ) + } + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/ReloadArtworkFlow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/ReloadArtworkFlow.kt new file mode 100644 index 0000000..525917f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/ReloadArtworkFlow.kt @@ -0,0 +1,695 @@ +package org.umamo.ui.model + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.DocumentChange +import org.umamo.edit.NoticePlacement +import org.umamo.edit.commitArtworkRelinked +import org.umamo.edit.commitArtworkReloaded +import org.umamo.edit.setTileSources +import org.umamo.edit.withArtworkReloaded +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.reimport.ArtworkReloadPlanner +import org.umamo.reimport.InventoryLayerMatcher +import org.umamo.reimport.LayerMatch +import org.umamo.reimport.ReconcileResult +import org.umamo.reimport.ReloadPlan +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.storage.UmamoLog + +/* + * Reloading the document's artwork files, and relinking a tile with the layer's art pulled in: the + * planner's delta applied to the live model, the changed tiles packed into the gaps around the art + * that did not change, committed as one undo step and registered on the operation settings strip. + * Add Artwork's shape throughout - the same pack-around primitive, the same supersede check, the + * same amend-in-place adjustment - because a reload is an import of the layers that changed. + * + * A reloaded tile is a NEW tile (see AtlasTile.replaces): its pixels join the raster store beside the + * old tile's, so an undo shows the old art again by pure snapshot, and nothing here ever overwrites + * a raster the document already holds. + */ + +/** + * One listed file to re-read. + * + * @property ArtSourceId sourceId The file's record in the model. + * @property SourceArt art The file as just read. + * @property String? contentHash The whole-file content hash of the bytes it was read from, recorded + * on the refreshed source so the watcher knows this save was taken; null keeps the record's. + * @property Long? lastModified The file's modification time when read, recorded beside the hash; + * null keeps the record's. + */ +class ReloadEntry( + val sourceId: ArtSourceId, + val art: SourceArt, + val contentHash: String? = null, + val lastModified: Long? = null, +) { + /** + * The inventory of [art], computed once for the entry's life: it hashes every layer's pixels, and + * the planner, the scorer, and every strip adjustment over this read want the same rows. + */ + val inventory: List by lazy { SourceArtImport.inventoryOf(art) } +} + +/** How a reload ended - what the watcher needs to know to wait, retry, or let go. */ +enum class ReloadArtworkResult { + /** The reload landed as one undo step. */ + Applied, + + /** The files were read and nothing in them changed the document. */ + NothingChanged, + + /** The pack could not keep the document's own art in place; the person was shown the report. */ + Refused, + + /** An edit landed while the reload was being planned; nothing was applied. */ + Superseded, +} + +/** + * The files a reload re-reads, as read from disk, with the decoded wrapper of every layer raster + * minted once so a re-run hands the raster store the same instances (the renderer's texture cache + * keys on that identity). + * + * @property List entries The files, each with its art. + * @property SourceArtImportOptions options The threshold and margin the first run uses. + * @property Float matchThreshold The confidence, 0..1, at or above which a lost binding + * takes the layer that re-created it in the same step. + */ +class ReloadArtworkRequest( + val entries: List, + val options: SourceArtImportOptions, + val matchThreshold: Float = InventoryLayerMatcher.DEFAULT_THRESHOLD, +) { + private val decoded = DecodedLayerRasters(entries.flatMap { entry -> entry.art.layers }) + + /** + * The decoded wrapper of one of the files' layer rasters. + * + * @param LayerRaster raster The layer's pixels. + * @return DecodedImage The wrapper, the same instance on every call. + */ + internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster) +} + +/** + * The tiles to rebind to one layer, with the layer's file as read when it could be. One tile for the + * tile chip and a drop; every tile bound to a lost key for a review row's accepted proposal or relink + * by hand, so those move as one step. + * + * @property List tileIds The tiles, in any order. + * @property SourceLayerRef ref The binding they take. + * @property SourceArt? art The file [ref] names, or null when it could not be read + * (missing, unreadable, or a platform uri) - the bindings then change alone. + * @property SourceArtImportOptions options The threshold and margin a re-born quad uses. + * @property List retire The tiles bound to the target layer that go with the move - + * the fresh drawable a reload minted for it, named by the proposal being accepted; each is re-checked + * for rig work before it leaves. Empty for a relink by hand or a drop. + */ +class RelinkArtworkRequest( + val tileIds: List, + val ref: SourceLayerRef, + val art: SourceArt?, + val options: SourceArtImportOptions, + val retire: List = emptyList(), +) { + /** + * The one-tile form. + * + * @param AtlasTileId tileId The tile. + * @param SourceLayerRef ref The binding it takes. + * @param SourceArt? art The file [ref] names, or null when it could not be read. + * @param SourceArtImportOptions options The threshold and margin a re-born quad uses. + */ + constructor(tileId: AtlasTileId, ref: SourceLayerRef, art: SourceArt?, options: SourceArtImportOptions) : this(listOf(tileId), ref, art, options) + + /** + * The inventory of [art], computed once for the request's life; empty without the file. + */ + val inventory: List by lazy { art?.let(SourceArtImport::inventoryOf).orEmpty() } + + private val decoded = DecodedLayerRasters(art?.layers.orEmpty()) + + /** + * The decoded wrapper of one of the file's layer rasters. + * + * @param LayerRaster raster The layer's pixels. + * @return DecodedImage The wrapper, the same instance on every call. + */ + internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster) +} + +/** What one reload pass produced, or why it produced nothing. */ +private sealed interface ReloadOutcome { + /** No file changed in any way the document records. */ + data object NothingChanged : ReloadOutcome + + /** + * The pack could not keep some of the document's own art where it is; nothing was applied. + * + * @property List refusals The document's tiles the pack could not keep. + */ + class Refused(val refusals: List) : ReloadOutcome + + /** + * The delta applied and packed. + * + * @property PuppetModel model The base with the reload applied and packed. + * @property PuppetTextures? textures The pages the pack composed, index-parallel to the model's, or + * null when the pass minted no tile and so packed nothing - the pages stand as they are. + * @property Map decodedByTile The new tiles' pixels, for the raster store. + * @property List notices The planner's notes plus every new tile the pack left unplaced. + * @property List outgrown Drawables whose kept mesh no longer covers the new art. + * @property DocumentChange.ReloadArtwork change The step's counts. + * @property List rebindings What the matcher rebound and retired, for the log. + * @property SourceSuggestions suggestions The proposals the matcher made but did not apply, by file + * and lost key, scored before the pass minted anything - for the review chips. + */ + class Reloaded( + val model: PuppetModel, + val textures: PuppetTextures?, + val decodedByTile: Map, + val notices: List, + val outgrown: List, + val change: DocumentChange.ReloadArtwork, + val rebindings: List = emptyList(), + val suggestions: SourceSuggestions = emptyMap(), + ) : ReloadOutcome +} + +/** + * One thing a reload, replace, match, or relink did beyond the art itself, as the log tells it: a lost + * layer's tile rebound to the layer that re-created it, a fresh drawable retired because a rigged tile + * claimed its layer, or a drawable whose visibility followed its layer's eye toggle in the file. + */ +internal sealed interface Rebinding { + /** + * A tile rebound by the matcher. + * + * @property String tileName The tile as it was named. + * @property String layerName The layer it moved to. + * @property Float score The matcher's confidence, 0..1. + */ + class Rebound(val tileName: String, val layerName: String, val score: Float) : Rebinding + + /** + * A fresh drawable removed with its tile because a rigged tile took its layer. + * + * @property String drawableName The drawable that went. + * @property String layerName The layer it sat over. + */ + class Retired(val drawableName: String, val layerName: String) : Rebinding + + /** + * A drawable whose visibility followed its layer's eye toggle in the file. + * + * @property String drawableName The drawable. + * @property Boolean visible The visibility it took. + */ + class VisibilityFollowed(val drawableName: String, val visible: Boolean) : Rebinding +} + +/** + * The rebindings one plan made, named from the model it was planned against and the art it read. + * + * @param ReloadPlan plan The plan. + * @param PuppetModel base The model the plan applies to (the names before the step). + * @param SourceArt art The file as read, for the layer names. + * @return List The rebound tiles, then the retired drawables, then the drawables that had their visibility changed. + */ +internal fun rebindingsOf(plan: ReloadPlan, base: PuppetModel, art: SourceArt): List { + val layerNameByKey = art.layers.associate { layer -> layer.id.raw to layer.name } + val rebound = + plan.report.results.filterIsInstance().flatMap { result -> + base.atlas.tiles + .filter { tile -> tile.source == result.binding } + .map { tile -> Rebinding.Rebound(tile.name, layerNameByKey[result.layerKey] ?: result.layerKey, result.score) } + } + val retired = + plan.reload.retiredTiles.flatMap { tileId -> + val tile = base.atlas.tileById[tileId] + val layerName = tile?.source?.layerKey?.let { key -> layerNameByKey[key] ?: key } ?: tileId.raw + base.drawables.filter { drawable -> drawable.atlasTileId == tileId }.map { drawable -> Rebinding.Retired(drawable.name, layerName) } + } + val followed = + plan.reload.drawableVisibility.map { (drawableId, visible) -> + Rebinding.VisibilityFollowed(base.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.name ?: drawableId.raw, visible) + } + return rebound + retired + followed +} + +/** + * Logs each rebinding under [operation]. + * + * @param String operation The log prefix. + * @param List rebindings What the matcher did. + */ +internal fun reportRebindings(operation: String, rebindings: List) { + for (rebinding in rebindings) { + when (rebinding) { + is Rebinding.Rebound -> UmamoLog.info("$operation: '${rebinding.tileName}' rebound to layer '${rebinding.layerName}' at ${percentOf(rebinding.score)}%") + is Rebinding.Retired -> UmamoLog.info("$operation: the new drawable '${rebinding.drawableName}' over layer '${rebinding.layerName}' was removed; a rebound tile took the layer") + is Rebinding.VisibilityFollowed -> + UmamoLog.info("$operation: '${rebinding.drawableName}' is now ${if (rebinding.visible) "shown" else "hidden"}, following its layer's eye toggle in the file") + } + } +} + +/** + * The document's pixels for a tile as the planner reads them: the raster store's decoded image, + * rewrapped. + * + * @param SourceArtRasters artRasters The document's raster store. + * @return Function The lookup, null for a tile the store cannot decode. + */ +private fun oldRasterLookup(artRasters: SourceArtRasters): (AtlasTileId) -> LayerRaster? = + { tileId -> artRasters.decodeRaster(tileId)?.let { decoded -> LayerRaster(decoded.width, decoded.height, decoded.rgba) } } + +/** + * Applies [request]'s files to [base] one after another and packs the tiles they replaced or added + * into the gaps around the rest. + * + * @param PuppetModel base The model the reload applies to. + * @param ReloadArtworkRequest request The files as read. + * @param SourceArtImportOptions options The threshold and margin to plan with. + * @param Float matchThreshold The bar a lost binding's best candidate must reach. + * @param SourceArtRasters artRasters The document's raster store (read, never written here). + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @return ReloadOutcome The outcome. + */ +private fun reloadOutcome( + base: PuppetModel, + request: ReloadArtworkRequest, + options: SourceArtImportOptions, + matchThreshold: Float, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, +): ReloadOutcome { + var model = base + val rasters = LinkedHashMap() + val notices = ArrayList() + val outgrown = ArrayList() + val rebindings = ArrayList() + val suggestions = LinkedHashMap, LayerMatch>() + var replaced = 0 + var added = 0 + var matched = 0 + var missing = 0 + var visibility = 0 + val oldRasterOf = oldRasterLookup(artRasters) + for (entry in request.entries) { + val plan = + ArtworkReloadPlanner.plan(model, entry.sourceId, entry.art, options, oldRasterOf, entry.contentHash, inventory = entry.inventory, lastModified = entry.lastModified, matchThreshold = matchThreshold) + ?: continue + val next = model.withArtworkReloaded(plan.reload) + if (next === model) { + UmamoLog.error("reload artwork: the plan for '${plan.reload.source.name}' collides with the document's ids; that file was skipped") + continue + } + rebindings.addAll(rebindingsOf(plan, model, entry.art)) + for ((lostKey, match) in plan.leftovers) { + suggestions[entry.sourceId to lostKey] = match + } + model = next + rasters.putAll(plan.rasterByTile) + notices.addAll(plan.notices) + outgrown.addAll(plan.reload.outgrown) + replaced += plan.reload.replacedTiles.size + added += plan.reload.additions?.drawables?.size ?: 0 + matched += plan.report.results.count { result -> result is ReconcileResult.Rebound } + missing += plan.report.needsReview.size + visibility += plan.reload.drawableVisibility.size + } + if (model === base) { + return ReloadOutcome.NothingChanged + } + val change = DocumentChange.ReloadArtwork(request.entries.size, replaced, added, matched, missing, visibility) + return packReloaded(model, rasters.mapValues { (_, raster) -> request.decodedFor(raster) }, notices, artRasters, premultipliedAlpha) { packedModel, textures, packedNotices, decodedByTile -> + ReloadOutcome.Reloaded(packedModel, textures, decodedByTile, packedNotices, outgrown, change, rebindings, suggestions) + } +} + +/** + * Packs the tiles a reload or relink minted (all of them unplaced) around the document's art and + * builds the outcome from the result. A pass that minted no tile - a layer the file lost, an + * inventory refresh - packs nothing at all: the pack would resize a page whose art did not change, + * and a placement is only ever moved by the operation that put a tile there. + * + * @param PuppetModel model The model with the delta applied. + * @param Map decodedByTile The new tiles' pixels. + * @param List notices The notes so far. + * @param SourceArtRasters artRasters The document's raster store, for every other tile. + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @param Function reloaded Builds the success outcome from the packed model. + * @return ReloadOutcome The outcome, refused when the document's own art could not be kept. + */ +private inline fun packReloaded( + model: PuppetModel, + decodedByTile: Map, + notices: List, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, + reloaded: (PuppetModel, PuppetTextures?, List, Map) -> ReloadOutcome, +): ReloadOutcome { + if (decodedByTile.isEmpty()) { + return reloaded(model, null, notices, decodedByTile) + } + val decode: (AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] ?: artRasters.decodeRaster(tileId) } + return when (val packed = packNewTilesAround(model, decodedByTile.keys, decode, premultipliedAlpha, notices)) { + is PackAroundOutcome.Refused -> ReloadOutcome.Refused(packed.refusals) + is PackAroundOutcome.Packed -> reloaded(packed.model, packed.textures, packed.notices, decodedByTile) + } +} + +/** + * Reloads the document's artwork files as ONE undo step and registers it on the operation settings + * strip (Match Threshold - the bar a lost layer's re-creation must reach to be rebound in the step - + * then Alpha Threshold and Birth Mesh Margin, the rows every re-born quad and added layer take). + * + * Runs on the UI thread; the planning and the pack hop to the default dispatcher. The delta is + * planned against the model current at the start, so any edit landing meanwhile supersedes it. The + * new rasters join the store only once the commit is certain. A reload that lands publishes the + * proposals its matcher left under the bar (scored before it minted anything, so a lost row can still + * offer the layer the reload minted a fresh drawable for); one that lands nothing publishes nothing. + * + * @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks. + * @param ReloadArtworkRequest request The files as read. + * @param String? areaId The area the strip shows in, or null. + * @param Function publish Takes the proposals left under the bar, for the review chips. + * @return ReloadArtworkResult How the reload ended. + */ +suspend fun runReloadArtwork(host: AtlasRepackHost, request: ReloadArtworkRequest, areaId: String?, publish: (SourceSuggestions) -> Unit = {}): ReloadArtworkResult { + val session = host.session + val modelAtStart = session.model.value + val outcome = + withContext(Dispatchers.Default) { + reloadOutcome(modelAtStart, request, request.options, request.matchThreshold, host.artRasters, host.premultipliedAlpha) + } + when (outcome) { + ReloadOutcome.NothingChanged -> { + UmamoLog.info("reload artwork: nothing changed in ${request.entries.size} file(s)") + session.emitNotice("notice.reload.noChanges", NoticePlacement.StatusBar) + return ReloadArtworkResult.NothingChanged + } + is ReloadOutcome.Refused -> { + for (refusal in outcome.refusals) { + UmamoLog.warn("reload artwork: the document's tile '${refusal.tileName}' could not be kept in place (${refusal.reason}); nothing was applied") + } + host.report(AtlasRepackReport(outcome.refusals)) + return ReloadArtworkResult.Refused + } + is ReloadOutcome.Reloaded -> Unit + } + if (session.model.value !== modelAtStart) { + UmamoLog.warn("reload artwork: the document changed while its files were being reloaded; nothing was applied") + session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar) + return ReloadArtworkResult.Superseded + } + host.artRasters.addDecoded(outcome.decodedByTile) + val committed = session.commitArtworkReloaded(outcome.change, outcome.model) + prewarmPages(host, committed, outcome.textures) + publish(outcome.suggestions) + reportReload(outcome, committed) + val change = outcome.change + session.emitNotice( + when { + outcome.outgrown.isNotEmpty() -> "notice.reload.outgrown" + outcome.notices.isNotEmpty() || change.missingCount > 0 -> "notice.reload.notes" + else -> "notice.reload.done" + }, + NoticePlacement.StatusBar, + // "Updated" counts the tiles that took new art and the drawables that had their visibility changed.. + listOf((change.replacedCount + change.visibilityCount).toString(), change.addedCount.toString(), change.matchedCount.toString(), change.missingCount.toString()), + ) + session.registerAdjustableOperation(committed, areaId, matchArtworkParameters(request.matchThreshold, request.options)) { record -> + host.scope.launch { adjustReloadArtwork(host, record, request, publish) } + } + return ReloadArtworkResult.Applied +} + +/** + * Re-plans the reload for an adjustment of the strip: the record's rows become the options, the SAME + * read files are planned again over the record's base model, packed, and landed over the operation's + * own step. A record cleared while the pass ran makes [org.umamo.edit.EditorSession.amendLastCommit] + * drop the result. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param ReloadArtworkRequest request The first run's files. + * @param Function publish Takes the proposals left under the adjusted bar. + */ +internal suspend fun adjustReloadArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: ReloadArtworkRequest, publish: (SourceSuggestions) -> Unit = {}) { + val base = record.baseSnapshot.model + val options = addArtworkOptionsOf(record.parameters, request.options) + val matchThreshold = matchThresholdOf(record.parameters, request.matchThreshold) + val outcome = + withContext(Dispatchers.Default) { + reloadOutcome(base, request, options, matchThreshold, host.artRasters, host.premultipliedAlpha) + } + when (outcome) { + ReloadOutcome.NothingChanged -> { + UmamoLog.warn("reload artwork: under the adjusted options nothing changes; the previous result stands") + return + } + is ReloadOutcome.Refused -> { + host.report(AtlasRepackReport(outcome.refusals)) + return + } + is ReloadOutcome.Reloaded -> Unit + } + host.artRasters.addDecoded(outcome.decodedByTile) + prewarmPages(host, outcome.model, outcome.textures) + if (!host.session.amendLastCommit(record, outcome.model)) { + UmamoLog.info("reload artwork: the adjustment was superseded before it landed; nothing was applied") + return + } + publish(outcome.suggestions) + reportReload(outcome, outcome.model) +} + +/** + * Pre-warms the session's page resolver with the pages a pass composed, when it composed any; a pass + * that packed nothing leaves the resolver to the pages it already holds. + * + * @param AtlasRepackHost host The session's resolver. + * @param PuppetModel model The model whose atlas the pages belong to. + * @param PuppetTextures? textures The pages, or null when the pass packed nothing. + */ +private fun prewarmPages(host: AtlasRepackHost, model: PuppetModel, textures: PuppetTextures?) { + if (textures != null) { + host.sessionAtlasPages?.prewarm(model.atlas, textures) + } +} + +/** + * Logs one reload pass the way the first run and an adjustment both report it. + * + * @param ReloadOutcome.Reloaded outcome What the pass produced. + * @param PuppetModel committed The model that landed. + */ +private fun reportReload(outcome: ReloadOutcome.Reloaded, committed: PuppetModel) { + for (notice in outcome.notices) { + UmamoLog.warn("reload artwork: ${describeImportNotice(notice)}") + } + for (drawableId in outcome.outgrown) { + val name = committed.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.name ?: drawableId.raw + UmamoLog.warn("reload artwork: the new art of '$name' reaches past its edited mesh; re-mesh it or extend the mesh") + } + reportRebindings("reload artwork", outcome.rebindings) + val change = outcome.change + UmamoLog.info( + "reload artwork: ${change.fileCount} file(s) -> ${change.replacedCount} tile(s) updated, ${change.addedCount} drawable(s) added," + + " ${change.matchedCount} rebound by match, ${change.missingCount} layer(s) missing, ${change.visibilityCount} visibility change, ${outcome.outgrown.size} outgrown;" + + " now ${committed.atlas.pages.size} page(s); ${outcome.notices.size} note(s)", + ) +} + +/** + * Rebinds one or more tiles to another source layer, pulling the layer's art in when the file could + * be read: each tile is replaced with the layer's art and its drawables carried over it, all as ONE + * undo step, packed beside the rest and registered on the strip like a reload; without the file, or + * when the layer has no art to give, only the bindings change (still one step) and the notice says so. + * + * @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks. + * @param RelinkArtworkRequest request The tiles, their new binding, and the file when read. + * @param String? areaId The area the strip shows in, or null. + * @return Boolean Whether the art was pulled (a binding-only change returns false). + */ +suspend fun runRelinkArtwork(host: AtlasRepackHost, request: RelinkArtworkRequest, areaId: String?): Boolean { + val session = host.session + val modelAtStart = session.model.value + val plan = + withContext(Dispatchers.Default) { + planRelinkOf(modelAtStart, request, request.options, host.artRasters) + } + if (plan == null) { + val unchanged = request.tileIds.filter { tileId -> modelAtStart.atlas.tileById[tileId]?.source == request.ref } + val toRebind = request.tileIds - unchanged.toSet() + if (toRebind.isEmpty()) { + UmamoLog.info("relink artwork: ${describeTiles(request.tileIds)} already holds this binding and this art; nothing to pull") + return false + } + session.setTileSources(toRebind, request.ref) + UmamoLog.warn("relink artwork: ${describeTiles(toRebind)} rebound to '${request.ref.layerKey}' without its art (the file could not be read, or the layer has none)") + session.emitNotice("notice.relink.bindingOnly", NoticePlacement.StatusBar) + return false + } + val outcome = + withContext(Dispatchers.Default) { + relinkOutcome(modelAtStart, plan, request, host.artRasters, host.premultipliedAlpha) + } + if (!landRelink(host, request, modelAtStart, outcome) { model -> session.commitArtworkRelinked(request.tileIds.first(), model) }) { + return false + } + session.registerAdjustableOperation(session.model.value, areaId, addArtworkParameters(request.options, placed = false)) { record -> + host.scope.launch { adjustRelinkArtwork(host, record, request) } + } + return true +} + +/** + * Plans [request]'s tiles onto their new layer over [base]: every tile paired with the one key, so + * the tiles bound to a lost key move in one plan. Null without the file or when nothing pulls. + * + * @param PuppetModel base The model the relink applies to. + * @param RelinkArtworkRequest request The tiles and their binding. + * @param SourceArtImportOptions options The threshold and margin to plan with. + * @param SourceArtRasters artRasters The document's raster store. + * @return ReloadPlan? The plan, or null when there is nothing to pull. + */ +private fun planRelinkOf(base: PuppetModel, request: RelinkArtworkRequest, options: SourceArtImportOptions, artRasters: SourceArtRasters): ReloadPlan? { + val art = request.art ?: return null + val pairs = request.tileIds.map { tileId -> tileId to request.ref.layerKey } + return ArtworkReloadPlanner.planMatches(base, request.ref.sourceId, art, pairs, options, oldRasterLookup(artRasters), inventory = request.inventory, retire = request.retire.toSet()) +} + +/** + * The tiles of a relink as the log names them. + * + * @param List tileIds The tiles. + * @return String One id quoted, or a count. + */ +private fun describeTiles(tileIds: List): String = tileIds.singleOrNull()?.let { tileId -> "'${tileId.raw}'" } ?: "${tileIds.size} tiles" + +/** + * Applies a relink plan to [base] and packs its one new tile. + * + * @param PuppetModel base The model the relink applies to. + * @param ReloadPlan plan The planner's delta for the tile. + * @param RelinkArtworkRequest request The request, for the decoded wrappers. + * @param SourceArtRasters artRasters The document's raster store. + * @param Boolean premultipliedAlpha The document's texture-convention flag. + * @return ReloadOutcome The outcome. + */ +private fun relinkOutcome( + base: PuppetModel, + plan: ReloadPlan, + request: RelinkArtworkRequest, + artRasters: SourceArtRasters, + premultipliedAlpha: Boolean, +): ReloadOutcome { + val model = base.withArtworkReloaded(plan.reload) + if (model === base) { + UmamoLog.error("relink artwork: the plan for ${describeTiles(request.tileIds)} collides with the document's ids; nothing was applied") + return ReloadOutcome.NothingChanged + } + val change = DocumentChange.ReloadArtwork(1, plan.reload.replacedTiles.size, 0, 0, 0) + val rebindings = request.art?.let { art -> rebindingsOf(plan, base, art) }.orEmpty() + return packReloaded(model, plan.rasterByTile.mapValues { (_, raster) -> request.decodedFor(raster) }, plan.notices, artRasters, premultipliedAlpha) { packedModel, textures, notices, decodedByTile -> + ReloadOutcome.Reloaded(packedModel, textures, decodedByTile, notices, plan.reload.outgrown, change, rebindings) + } +} + +/** + * Lands a relink outcome: the supersede check, the rasters into the store, the commit, the pre-warm, + * the log, and the notice. + * + * @param AtlasRepackHost host The session, art, resolver, and shell callbacks. + * @param RelinkArtworkRequest request The request, for the log. + * @param PuppetModel modelAtStart The model the outcome was planned against. + * @param ReloadOutcome outcome What the pass produced. + * @param Function commit Commits the packed model and returns the committed one. + * @return Boolean Whether the outcome landed. + */ +private inline fun landRelink( + host: AtlasRepackHost, + request: RelinkArtworkRequest, + modelAtStart: PuppetModel, + outcome: ReloadOutcome, + commit: (PuppetModel) -> PuppetModel, +): Boolean { + val session = host.session + when (outcome) { + ReloadOutcome.NothingChanged -> return false + is ReloadOutcome.Refused -> { + host.report(AtlasRepackReport(outcome.refusals)) + return false + } + is ReloadOutcome.Reloaded -> Unit + } + if (session.model.value !== modelAtStart) { + UmamoLog.warn("relink artwork: the document changed while ${describeTiles(request.tileIds)} was being relinked; nothing was applied") + session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar) + return false + } + host.artRasters.addDecoded(outcome.decodedByTile) + val committed = commit(outcome.model) + prewarmPages(host, committed, outcome.textures) + reportReload(outcome, committed) + session.emitNotice(if (outcome.outgrown.isEmpty()) "notice.relink.pulled" else "notice.reload.outgrown", NoticePlacement.StatusBar) + return true +} + +/** + * Re-plans a relink for an adjustment of the strip over the record's base, landing through + * [org.umamo.edit.EditorSession.amendLastCommit]. + * + * @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had. + * @param AdjustableOperation record The record with the adjusted parameters. + * @param RelinkArtworkRequest request The first run's request. + */ +internal suspend fun adjustRelinkArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: RelinkArtworkRequest) { + if (request.art == null) { + return + } + val base = record.baseSnapshot.model + val options = addArtworkOptionsOf(record.parameters, request.options) + val outcome = + withContext(Dispatchers.Default) { + val plan = planRelinkOf(base, request, options, host.artRasters) + if (plan == null) ReloadOutcome.NothingChanged else relinkOutcome(base, plan, request, host.artRasters, host.premultipliedAlpha) + } + when (outcome) { + ReloadOutcome.NothingChanged -> { + UmamoLog.warn("relink artwork: under the adjusted options nothing changes; the previous result stands") + return + } + is ReloadOutcome.Refused -> { + host.report(AtlasRepackReport(outcome.refusals)) + return + } + is ReloadOutcome.Reloaded -> Unit + } + host.artRasters.addDecoded(outcome.decodedByTile) + prewarmPages(host, outcome.model, outcome.textures) + if (!host.session.amendLastCommit(record, outcome.model)) { + UmamoLog.info("relink artwork: the adjustment was superseded before it landed; nothing was applied") + return + } + reportReload(outcome, outcome.model) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SessionAtlasPages.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SessionAtlasPages.kt new file mode 100644 index 0000000..06ff90d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SessionAtlasPages.kt @@ -0,0 +1,112 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.withContext +import org.umamo.edit.EditorSession +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.render.deriveAtlasTextures +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.ui.viewport.AtlasPageBinding + +/** + * The session's effective atlas pages: which pixels the model's current atlas value denotes. + * + * Pages are DERIVED state, not history state - a snapshot must never hold pixels - so this follows + * the session's model and resolves each atlas value to a page set: the document's imported baseline + * short-circuits to its own decoded pages (byte-exact originals, nothing composed on open), and a + * generated value (a repack's) composes through deriveAtlasTextures. Undo and redo therefore swap + * pages with no help from anyone: restoring the model IS the trigger. + * + * Resolution is memoized by ATLAS IDENTITY, which the model's copy-on-write discipline makes exact: + * every non-atlas edit passes `atlas` through by reference, and undo restores the very instance the + * snapshot holds. The cache is the baseline plus ONE derived entry - a page set is hundreds of + * megabytes at full size, so holding generations would be ruinous; the single slot gives redo its + * free round trip, and an older generation re-derives off-thread while the current pages keep + * rendering. The repack pre-warms the slot with the pages it already composed, so the commit that + * publishes its model cache-hits instead of composing twice. + * + * UI-thread confined (the binding is Compose state); only the derivation itself runs on the default + * dispatcher. + * + * @property EditorSession session The session whose model drives the resolution. + * @property PuppetAtlas baselineAtlas The imported document's atlas value. + * @property PuppetTextures baselineTextures The imported document's decoded pages. + * @property SourceArtRasters artRasters The source-art pixels a generated value composes from. + */ +class SessionAtlasPages( + private val session: EditorSession, + baselineAtlas: PuppetAtlas, + baselineTextures: PuppetTextures, + private val artRasters: SourceArtRasters, +) { + private val baseline = AtlasPageBinding(baselineAtlas, baselineTextures) + + // The one derived generation kept beyond baseline; replaced wholesale on the next derivation. + private var derived: AtlasPageBinding? = null + + private val mutableBinding = mutableStateOf(baseline) + + /** The pages the current model's atlas denotes, paired with that atlas value. */ + val binding: State get() = mutableBinding + + /** + * Seeds the derived slot with pages the caller already composed for [atlas], so the model commit + * that follows resolves by cache hit instead of composing the same pages again. + * + * @param PuppetAtlas atlas The atlas value the pages belong to. + * @param PuppetTextures textures The composed pages. + */ + fun prewarm(atlas: PuppetAtlas, textures: PuppetTextures) { + derived = AtlasPageBinding(atlas, textures) + } + + /** + * Follows the session's model until cancelled, publishing the binding for every atlas change. + * Launched once by the host beside the other session collectors. + */ + suspend fun follow() { + session.model + .distinctUntilChanged { previous, next -> previous.atlas === next.atlas } + .collectLatest { model -> publishFor(model) } + } + + private suspend fun publishFor(model: PuppetModel) { + val atlas = model.atlas + if (mutableBinding.value.atlas === atlas) { + return + } + if (atlas === baseline.atlas || atlas == baseline.atlas) { + mutableBinding.value = baseline + return + } + derived?.let { cached -> + if (cached.atlas === atlas) { + mutableBinding.value = cached + return + } + } + val textures = + withContext(Dispatchers.Default) { + deriveAtlasTextures(model, artRasters, baseline.textures.premultipliedAlpha) + } + val next = + if (textures != null) { + AtlasPageBinding(atlas, textures) + } else { + // Unreachable for an atlas the repack authored (its placements derive by construction). + // Publishing the previous pixels under the NEW atlas keeps the engine's model/pages pairing + // from holding forever: wrong pixels beat a frozen viewport, and the log names the fault. + UmamoLog.error("atlas pages: the current atlas is not derivable; keeping the previous pages") + AtlasPageBinding(atlas, mutableBinding.value.textures) + } + derived = next + mutableBinding.value = next + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SessionEditorState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SessionEditorState.kt new file mode 100644 index 0000000..bd07e82 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SessionEditorState.kt @@ -0,0 +1,66 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.Selection + +/** + * Backs the common [SelectionHandle] and [EditorModeHandle] with an [EditorSession], so every selection + * gesture and mode toggle the panels make flows through the session — which records selection as an undo + * step (the chosen Blender-faithful granularity) and republishes through its flows. Reads go through + * Compose [State] mirrors of the session's flows, so panels recompose on change, including when undo / + * redo restore a prior selection. + * + * Keeps :edit free of Compose (its module mandate): the session exposes coroutines flows, and this thin + * :ui adapter is the only place they become Compose-observable state. Writes are one-way to the session, + * which is the single source of truth; the mirrors only follow it. + * + * 共通の選択/モードハンドルを EditorSession に接続する :ui 側アダプタ。読みは Compose State ミラー、 + * 書きはセッションへ一方向(取り消しに記録される)。 + */ +class SessionEditorState internal constructor( + private val session: EditorSession, + private val selectionMirror: State, + private val modeMirror: State, +) : SelectionHandle, EditorModeHandle { + override val selection: Selection get() = selectionMirror.value + + /** + * Routes a selection gesture to the session, which records it as an undo step. + * + * @param Selection selection The new selection. + */ + override fun set(selection: Selection) { + session.setSelection(selection) + } + + override val mode: EditorMode get() = modeMirror.value + + /** + * Routes a mode change to the session (transient — not an undo step). + * + * @param EditorMode mode The new mode. + */ + override fun set(mode: EditorMode) { + session.setMode(mode) + } +} + +/** + * Remembers a [SessionEditorState] over [session], collecting its selection and mode flows into Compose + * state so the returned handle's reads are observable. Stable while [session] is, so providing it into + * [LocalSelection] / [LocalEditorMode] does not thrash the composition. + * + * @param EditorSession session The open document's session. + * @return SessionEditorState The session-backed selection + mode handle. + */ +@Composable +fun rememberSessionEditorState(session: EditorSession): SessionEditorState { + val selectionMirror = session.selection.collectAsState() + val modeMirror = session.mode.collectAsState() + return remember(session) { SessionEditorState(session, selectionMirror, modeMirror) } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceFilePresence.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceFilePresence.kt new file mode 100644 index 0000000..99e1273 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceFilePresence.kt @@ -0,0 +1,57 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.storage.UmamoLog +import kotlin.concurrent.Volatile + +/** + * Whether an artwork file is still where the document last read it: true when present, false when + * missing, null when the platform cannot say (a content uri, a path it will not probe). + * + * @param String path The advisory path the model recorded. + * @return Boolean? The answer, or null for unknown. + */ +typealias SourceFilePresence = (path: String) -> Boolean? + +/** + * The app's file-presence probe for the Sources space, or null on a platform without one. A probe + * that answers null for a path leaves that source's status Unknown; without a probe every source + * reads Unknown, never Missing - the space must not accuse a file it cannot check. + */ +val LocalSourceFilePresence = staticCompositionLocalOf { null } + +/** + * The presence probe with a log line the first time a path is asked about and whenever its answer + * changes - found, missing, or unknowable - so a document whose recorded path is wrong shows the + * exact path being checked. The Sources space asks on every refresh and the watcher every second, + * so only a change earns a line. Shared across documents for the app's life, like the probe itself. + * + * @property SourceFilePresence answers The probe the answers come from. + */ +internal class LoggedSourceFilePresence( + private val answers: SourceFilePresence, +) { + /** The last answer per path; copy-on-write, since the watcher asks off the UI thread. */ + @Volatile + private var lastAnswerByPath: Map = emptyMap() + + /** + * Answers for [path], logging when the answer is new. + * + * @param String path The advisory path the model recorded. + * @return Boolean? The answer: present, missing, or null for unknown. + */ + fun probe(path: String): Boolean? { + val answer = answers(path) + val known = lastAnswerByPath + if (path !in known || known[path] != answer) { + lastAnswerByPath = known + (path to answer) + when (answer) { + true -> UmamoLog.info("source artwork: found at $path") + false -> UmamoLog.warn("source artwork: missing at $path") + null -> UmamoLog.info("source artwork: presence unknown at $path (not a file path this platform can probe)") + } + } + return answer + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceSuggestionState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceSuggestionState.kt new file mode 100644 index 0000000..be5d934 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceSuggestionState.kt @@ -0,0 +1,21 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.staticCompositionLocalOf +import kotlinx.coroutines.flow.StateFlow +import org.umamo.reimport.LayerMatch +import org.umamo.runtime.model.ArtSourceId + +/** + * The pixel-scored suggestions the last operation that read a file published for its unresolved + * bindings, keyed by file and lost layer key: what the Sources space prefers over the ranking it can + * make from the model alone. Read-only here; the app publishes into it after a reload, a replace, or + * a Match Automatically, and clears it on a document swap. + * + * @property StateFlow suggestions The best candidate per lost binding, by (file, lost key). + */ +class SourceSuggestionState( + val suggestions: StateFlow, LayerMatch>>, +) + +/** The open document's published suggestions, or null when none were published (no document, or outside the app). */ +val LocalSourceSuggestions = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceTileThumbnails.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceTileThumbnails.kt new file mode 100644 index 0000000..f234057 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceTileThumbnails.kt @@ -0,0 +1,63 @@ +package org.umamo.ui.model + +import androidx.compose.ui.graphics.ImageBitmap +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.fittedInto +import org.umamo.render.DecodedImage +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.AtlasTileId +import org.umamo.ui.graphics.RgbaAlphaType +import org.umamo.ui.graphics.rgbaToImageBitmap + +/** + * The square edge, in pixels, a tile's preview is fitted into: the size [DrawableThumbnailer] composites a + * part to, so a Sources layer and an Outliner part read at the same sharpness in the same 120dp slot. + */ +private const val TILE_PREVIEW_EDGE = 128 + +/** + * Small previews of a document's source art, one per atlas tile: the art a layer was read as, before any + * packing, for the Sources space's hover. + * + * The pixels come from the document's [SourceArtRasters], not from the atlas pages: a page crop would show + * the art packed, possibly quarter-turned, and cut to one drawable's mesh, where a layer's preview should + * show the layer. Each is fitted into a transparent square by the premultiplied area average every CMO3 + * layer icon is drawn with, so an edge stays clean at any reduction. + * + * A preview is valid only while the store hands back the same raster instance for its tile. A reload, + * its undo, and a second reload mint the same tile id twice with different pixels, and the store's + * addDecoded replaces the first, so a cache keyed on the id alone would show the first reload's art. + * + * CALLER-CONFINED like [SourceArtRasters.rasterFor], which it calls: every call must come from the UI + * thread. Sharing that store's decode means a later UV editor view of the same layer decodes nothing. + * + * @property SourceArtRasters rasters The document's source-art pixels. + */ +class SourceTileThumbnails( + private val rasters: SourceArtRasters, +) { + /** A fitted preview and the raster it was fitted from, which decides whether it is still current. */ + private class Entry(val raster: DecodedImage, val bitmap: ImageBitmap) + + private val cache = HashMap() + + /** + * The preview of a tile's source art, fitted into a [TILE_PREVIEW_EDGE] square, or null when the tile + * has no pixels the store can decode. + * + * @param AtlasTileId tileId The tile to preview. + * @return ImageBitmap? The preview, or null. + */ + fun thumbnailFor(tileId: AtlasTileId): ImageBitmap? { + val raster = rasters.rasterFor(tileId) ?: return null + cache[tileId]?.let { entry -> + if (entry.raster === raster) { + return entry.bitmap + } + } + val fitted = RasterImage(raster.width, raster.height, raster.rgba).fittedInto(TILE_PREVIEW_EDGE) + val bitmap = rgbaToImageBitmap(fitted.rgba, fitted.width, fitted.height, RgbaAlphaType.Straight) + cache[tileId] = Entry(raster, bitmap) + return bitmap + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceWatchState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceWatchState.kt new file mode 100644 index 0000000..10968e3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/model/SourceWatchState.kt @@ -0,0 +1,21 @@ +package org.umamo.ui.model + +import androidx.compose.runtime.staticCompositionLocalOf +import kotlinx.coroutines.flow.StateFlow +import org.umamo.runtime.model.ArtSourceId + +/** + * What the open document's artwork watcher tells the Sources space: which files changed on disk and + * await a reload (the header's alert glyph), and a serial that moves whenever a file's presence did + * (the tree re-probes). Read-only here; the app owns the watcher. + * + * @property StateFlow pending The files whose settled content differs from what the document last read. + * @property StateFlow serial Bumped on every presence change. + */ +class SourceWatchState( + val pending: StateFlow>, + val serial: StateFlow, +) + +/** The open document's watch state, or null when nothing is watching (no document, or outside the app). */ +val LocalSourceWatch = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/DataTabSections.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/DataTabSections.kt new file mode 100644 index 0000000..27d0fba --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/DataTabSections.kt @@ -0,0 +1,890 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.Change +import org.umamo.edit.DeformerChange +import org.umamo.edit.DrawableChange +import org.umamo.edit.EditorSession +import org.umamo.edit.MAX_WARP_DIVISIONS +import org.umamo.edit.MIN_WARP_DIVISIONS +import org.umamo.edit.PartChange +import org.umamo.edit.SelectionTarget +import org.umamo.edit.editKeyedChannel +import org.umamo.edit.previewChannelEdit +import org.umamo.edit.setAtlasPins +import org.umamo.edit.setDeformerBaseAngle +import org.umamo.edit.setDeformerFlipX +import org.umamo.edit.setDeformerFlipY +import org.umamo.edit.setDeformerMultiplyColor +import org.umamo.edit.setDeformerOpacity +import org.umamo.edit.setDeformerQuadTransform +import org.umamo.edit.setDeformerScreenColor +import org.umamo.edit.setDeformerWarpGrid +import org.umamo.edit.setDrawableAlphaBlendMode +import org.umamo.edit.setDrawableBlendMode +import org.umamo.edit.setDrawableCulling +import org.umamo.edit.setDrawableDrawOrder +import org.umamo.edit.setDrawableInvertMask +import org.umamo.edit.setDrawableMultiplyColor +import org.umamo.edit.setDrawableOpacity +import org.umamo.edit.setDrawableScreenColor +import org.umamo.edit.setPartComposite +import org.umamo.edit.setPartDrawOrder +import org.umamo.edit.setPartGroupMode +import org.umamo.edit.setPartSketch +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.displayMultiplyColor +import org.umamo.runtime.model.displayScreenColor +import org.umamo.runtime.model.multiplyColor +import org.umamo.runtime.model.opacity +import org.umamo.runtime.model.screenColor +import org.umamo.ui.graphics.formatHexColor +import org.umamo.ui.graphics.parseHexColor +import org.umamo.ui.graphics.toColorRgb +import org.umamo.ui.graphics.toComposeColor +import org.umamo.ui.kit.HexColorField +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.SelectField +import org.umamo.ui.kit.Slider +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.UmamoIcon +import kotlin.math.roundToInt + +/* + * The Data tab's sections and its per-type dispatch. Unlike the other two tabs, both the icon and the + * section list resolve from the ACTIVE ITEM'S TYPE (dataTabIcon / dataTabSections), so a drawable, a + * deformer, and a part each get their own face of this tab. + */ + +/** Data (drawable): mesh vertex / triangle counts. */ +internal val MeshSection = + PropertySection( + id = "data.mesh", + title = Res.string.properties_section_mesh, + rows = { context -> + val mesh = context.activeDrawable()?.mesh + listOf( + PropertyRow(terms = listOf(Res.string.properties_mesh)) { _ -> + if (mesh != null) { + PropertyLine(stringResource(Res.string.properties_mesh, mesh.vertexCount, mesh.triangleCount)) + } else { + PropertyLine(stringResource(Res.string.properties_no_mesh)) + } + }, + ) + }, + ) + +/** + * Data (drawable): the atlas texture binding, and the pin on the tile's placement when the drawable's + * art is packed on a page (the same flag the UV editor's P / Alt+P set). + */ +internal val TextureSection = + PropertySection( + id = "data.texture", + title = Res.string.properties_section_texture, + rows = { context -> + val drawable = context.activeDrawable() + val source = drawable?.textureSourceId + val tile = drawable?.atlasTileId?.let { tileId -> context.puppet.atlas.tileById[tileId] } + val session = context.session + buildList { + add( + PropertyRow(terms = listOf(Res.string.properties_texture_source)) { _ -> + if (source != null) { + PropertyLine(stringResource(Res.string.properties_texture_source, source.raw)) + } else { + PropertyLine(stringResource(Res.string.properties_texture_own)) + } + }, + ) + if (tile != null && tile.placement != null) { + add( + PropertyRow(terms = listOf(Res.string.properties_field_pinned)) { _ -> + PropertyCheckboxRow( + checked = tile.pinned, + onCheckedChange = { checked -> session?.setAtlasPins(listOf(tile.id), checked) }, + label = stringResource(Res.string.properties_field_pinned), + description = stringResource(Res.string.properties_field_pinned_description), + ) + }, + ) + } + } + }, + ) + +/** Data (drawable): draw order, opacity, blend mode, alpha composition, tint colors, back-face culling, and masking. */ +internal val BlendSection = + PropertySection( + id = "data.blend", + title = Res.string.properties_section_blend, + rows = { context -> + val drawable = context.activeDrawable() + if (drawable != null) { + val session = context.session + val target = context.puppet.runtimeTarget + listOfNotNull( + // Opacity and draw order are keyable channels like the colours below, each with its own + // static and its own optional track. Draw order is a FLOAT here, unlike a part's int: + // it blends per pose, so a fractional value between two keys is meaningful. + PropertyRow(terms = listOf(Res.string.properties_field_draw_order)) { _ -> + KeyableScalarChannelRow( + label = stringResource(Res.string.properties_field_draw_order), + description = stringResource(Res.string.properties_field_draw_order_description), + owner = KeyformOwner.Drawable(drawable.id), + channel = FormChannel.DRAW_ORDER, + stored = drawable.drawOrder, + session = session, + range = 0f..1000f, + decimals = 0, + step = 1f, + changeFor = { order -> DrawableChange.SetDrawOrder(drawable.id, order) }, + writeStatic = { order -> session?.setDrawableDrawOrder(drawable.id, order) }, + ) + }, + PropertyRow(terms = listOf(Res.string.properties_field_opacity)) { _ -> + KeyableScalarChannelRow( + label = stringResource(Res.string.properties_field_opacity), + description = stringResource(Res.string.properties_field_opacity_description), + owner = KeyformOwner.Drawable(drawable.id), + channel = FormChannel.OPACITY, + stored = drawable.opacity, + session = session, + range = 0f..1f, + decimals = 3, + step = 0.05f, + changeFor = { opacity -> DrawableChange.SetOpacity(drawable.id, opacity) }, + writeStatic = { opacity -> session?.setDrawableOpacity(drawable.id, opacity) }, + ) + }, + PropertyRow(terms = listOf(Res.string.properties_field_blend_mode)) { _ -> + val blendLabels = blendModeLabels() + PropertyFieldRow( + stringResource(Res.string.properties_field_blend_mode), + description = stringResource(Res.string.properties_field_blend_mode_description), + ) { + SelectField( + selected = drawable.blendMode, + modifier = Modifier.fillMaxWidth(), + options = blendModeOptionsFor(target, drawable.blendMode), + label = { mode -> blendLabels[mode] ?: mode.name }, + onSelect = { mode -> session?.setDrawableBlendMode(drawable.id, mode) }, + ) + } + }, + if (!showsAlphaBlendRow(target, drawable.blendMode, drawable.alphaBlendMode)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_alpha_mode)) { _ -> + val alphaLabels = alphaBlendModeLabels() + PropertyFieldRow( + stringResource(Res.string.properties_field_alpha_mode), + description = stringResource(Res.string.properties_field_alpha_mode_description), + ) { + SelectField( + selected = drawable.alphaBlendMode, + modifier = Modifier.fillMaxWidth(), + options = alphaBlendModeOptionsFor(target, drawable.alphaBlendMode), + label = { mode -> alphaLabels[mode] ?: mode.name }, + onSelect = { mode -> session?.setDrawableAlphaBlendMode(drawable.id, mode) }, + ) + } + } + }, + // The 4.2 per-art-mesh multiply/screen color: a channel with its own static and its own + // optional keyform track, so the picker writes the static and `I` over the row keys it. + if (!target.supports(RuntimeFeature.MultiplyColor)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_multiply_color)) { _ -> + KeyableColorChannelRow( + label = stringResource(Res.string.properties_field_multiply_color), + description = stringResource(Res.string.properties_field_multiply_color_description), + owner = KeyformOwner.Drawable(drawable.id), + channel = FormChannel.MULTIPLY_COLOR, + stored = drawable.displayMultiplyColor(), + session = session, + changeFor = { color -> DrawableChange.SetMultiplyColor(drawable.id, color) }, + writeStatic = { color -> session?.setDrawableMultiplyColor(drawable.id, color) }, + ) + } + }, + if (!target.supports(RuntimeFeature.ScreenColor)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_screen_color)) { _ -> + KeyableColorChannelRow( + label = stringResource(Res.string.properties_field_screen_color), + description = stringResource(Res.string.properties_field_screen_color_description), + owner = KeyformOwner.Drawable(drawable.id), + channel = FormChannel.SCREEN_COLOR, + stored = drawable.displayScreenColor(), + session = session, + changeFor = { color -> DrawableChange.SetScreenColor(drawable.id, color) }, + writeStatic = { color -> session?.setDrawableScreenColor(drawable.id, color) }, + ) + } + }, + PropertyRow(terms = listOf(Res.string.properties_field_culling)) { _ -> + PropertyCheckboxRow( + checked = drawable.culling, + onCheckedChange = { culling -> session?.setDrawableCulling(drawable.id, culling) }, + label = stringResource(Res.string.properties_field_culling), + description = stringResource(Res.string.properties_field_culling_description), + ) + }, + // Clipping lives with the blend data, not under Relations: it is how the drawable is + // composited, and it pairs with the invert toggle right below it. + PropertyRow(terms = listOf(Res.string.properties_field_masked_by, Res.string.properties_mask_count)) { _ -> + DrawableMaskEditor(drawable, context) + }, + // Reversed masking is a 4.0 feature (official target dialog), gated separately from the + // always-available masks above it. + if (!target.supports(RuntimeFeature.ReversedMask)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_invert_mask)) { _ -> + PropertyCheckboxRow( + checked = drawable.invertMask, + onCheckedChange = { invert -> session?.setDrawableInvertMask(drawable.id, invert) }, + label = stringResource(Res.string.properties_field_invert_mask), + description = stringResource(Res.string.properties_field_invert_mask_description), + ) + } + }, + ) + } else { + emptyList() + } + }, + ) + +/** Data (deformer): opacity and tint colors, plus the warp lattice / quad-transform flag or the rotation base angle and flip flags. */ +internal val DeformerSection = + PropertySection( + id = "data.deformer", + title = Res.string.properties_section_deformer, + rows = { context -> + val session = context.session + val target = context.puppet.runtimeTarget + when (val deformer = context.activeDeformer()) { + is Deformer.Warp -> + deformerRenderChannelRows(deformer, session, target) + + listOfNotNull( + PropertyRow( + terms = + listOf( + Res.string.properties_warp_grid, + Res.string.properties_warp_grid_x, + Res.string.properties_field_warp_grid, + ), + ) { _ -> + WarpGridAxisSlider( + deformer = deformer, + session = session, + axis = WarpGridAxis.Columns, + ) + }, + PropertyRow( + terms = + listOf( + Res.string.properties_warp_grid, + Res.string.properties_warp_grid_y, + Res.string.properties_field_warp_grid, + ), + ) { _ -> + WarpGridAxisSlider( + deformer = deformer, + session = session, + axis = WarpGridAxis.Rows, + ) + }, + // The bilinear mode is the official dialog's "new warp deformer method" (3.3+). + if (!target.supports(RuntimeFeature.WarpQuadTransform)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_quad_transform)) { _ -> + PropertyCheckboxRow( + checked = deformer.isQuadTransform, + onCheckedChange = { quad -> session?.setDeformerQuadTransform(deformer.id, quad) }, + label = stringResource(Res.string.properties_field_quad_transform), + description = stringResource(Res.string.properties_field_quad_transform_description), + ) + } + }, + ) + + is Deformer.Rotation -> + deformerRenderChannelRows(deformer, session, target) + + listOf( + PropertyRow(terms = listOf(Res.string.properties_field_base_angle)) { _ -> + PropertyFieldRow( + stringResource(Res.string.properties_field_base_angle), + description = stringResource(Res.string.properties_field_base_angle_description), + ) { + NumberField( + value = deformer.baseAngle, + onValueChange = { newAngle -> session?.setDeformerBaseAngle(deformer.id, newAngle) }, + modifier = Modifier.fillMaxWidth(), + range = UNBOUNDED_RANGE, + decimals = 1, + unitSuffix = stringResource(Res.string.unit_degrees), + ) + } + }, + PropertyRow(terms = listOf(Res.string.properties_field_flip_x)) { _ -> + KeyableFlagChannelRow( + label = stringResource(Res.string.properties_field_flip_x), + description = stringResource(Res.string.properties_field_flip_x_description), + owner = KeyformOwner.Deformer(deformer.id), + channel = FormChannel.FLIP_X, + stored = deformer.flipX, + session = session, + changeFor = { flip -> DeformerChange.SetFlipX(deformer.id, flip) }, + writeStatic = { flip -> session?.setDeformerFlipX(deformer.id, flip) }, + ) + }, + PropertyRow(terms = listOf(Res.string.properties_field_flip_y)) { _ -> + KeyableFlagChannelRow( + label = stringResource(Res.string.properties_field_flip_y), + description = stringResource(Res.string.properties_field_flip_y_description), + owner = KeyformOwner.Deformer(deformer.id), + channel = FormChannel.FLIP_Y, + stored = deformer.flipY, + session = session, + changeFor = { flip -> DeformerChange.SetFlipY(deformer.id, flip) }, + writeStatic = { flip -> session?.setDeformerFlipY(deformer.id, flip) }, + ) + }, + ) + + null -> emptyList() + } + }, + ) + +/** Data (part): the guide-image flag, draw order, group mode, and, while isolated, the composite's render channels and masks. */ +internal val PartSection = + PropertySection( + id = "data.part", + title = Res.string.properties_section_part, + rows = { context -> + val part = context.activePart() + if (part != null) { + val session = context.session + val target = context.puppet.runtimeTarget + buildList { + add( + PropertyRow(terms = listOf(Res.string.properties_field_sketch)) { _ -> + PropertyCheckboxRow( + checked = part.isSketch, + onCheckedChange = { sketch -> session?.setPartSketch(part.id, sketch) }, + label = stringResource(Res.string.properties_field_sketch), + description = stringResource(Res.string.properties_field_sketch_description), + ) + }, + ) + add( + PropertyRow(terms = listOf(Res.string.properties_field_draw_order)) { _ -> + KeyablePropertyRow( + target = KeyableTarget(KeyformOwner.Part(part.id), FormChannel.DRAW_ORDER), + ) { + PropertyFieldRow( + stringResource(Res.string.properties_field_draw_order), + description = stringResource(Res.string.properties_field_draw_order_part_description), + ) { + val target = KeyableTarget(KeyformOwner.Part(part.id), FormChannel.DRAW_ORDER) + NumberField( + keyState = keyedFieldStateOf(KeyformOwner.Part(part.id), FormChannel.DRAW_ORDER), + // What is APPLIED: a keyed channel's track shadows the Int static. + value = + displayedChannelScalar( + KeyformOwner.Part(part.id), + FormChannel.DRAW_ORDER, + part.drawOrder.toFloat(), + ).roundToInt(), + onValueChange = { order: Int -> + session?.editKeyedChannel( + target, + ChannelValue.Scalar(order.toFloat()), + PartChange.SetDrawOrder(part.id, order), + ) { + session.setPartDrawOrder(part.id, order) + } + }, + onPreview = { order: Int -> + session?.previewChannelEdit(target, ChannelValue.Scalar(order.toFloat())) + }, + range = 0..1000, + modifier = Modifier.fillMaxWidth(), + ) + } + } + }, + ) + add( + PropertyRow(terms = listOf(Res.string.properties_field_group_mode)) { _ -> + val groupLabels = partGroupModeLabels() + PropertyFieldRow( + stringResource(Res.string.properties_field_group_mode), + description = stringResource(Res.string.properties_field_group_mode_description), + ) { + SelectField( + selected = part.groupMode.kind(), + modifier = Modifier.fillMaxWidth(), + options = partGroupModeOptionsFor(target, part.groupMode.kind()), + label = { kind -> groupLabels[kind] ?: kind.name }, + onSelect = { kind -> session?.setPartGroupMode(part.id, partGroupModeOf(kind)) }, + ) + } + }, + ) + // An isolated part composites its subtree as one layer; expose the composite's scalar channels, + // tint colors, and clip masks. The composite is stored latently on the part, so each sub-field + // edits it via setPartComposite - it survives a mode round-trip and is shown only while the part + // is Isolated (activeComposite is non-null exactly then). The whole block additionally gates on + // the 5.3 offscreen feature: an out-of-target isolated part keeps rendering, but its composite + // stops being editable. No inner gates - 5.3 support implies every lower tier (colors, alpha, + // reversed mask). + val composite = part.activeComposite + if (composite != null && target.supports(RuntimeFeature.PartComposite)) { + add( + PropertyRow(terms = listOf(Res.string.properties_field_opacity)) { _ -> + KeyableScalarChannelRow( + label = stringResource(Res.string.properties_field_opacity), + description = stringResource(Res.string.properties_field_opacity_part_description), + owner = KeyformOwner.Part(part.id), + channel = FormChannel.OPACITY, + stored = composite.opacity, + session = session, + range = 0f..1f, + decimals = 3, + step = 0.05f, + changeFor = { opacity -> PartChange.SetComposite(part.id, composite.copy(opacity = opacity)) }, + writeStatic = { opacity -> + session?.setPartComposite(part.id, composite.copy(opacity = opacity)) + }, + ) + }, + ) + add( + PropertyRow(terms = listOf(Res.string.properties_field_blend_mode)) { _ -> + val blendLabels = blendModeLabels() + PropertyFieldRow( + stringResource(Res.string.properties_field_blend_mode), + description = stringResource(Res.string.properties_field_blend_mode_part_description), + ) { + SelectField( + selected = composite.blendMode, + modifier = Modifier.fillMaxWidth(), + options = blendModeDisplayOrder(), + label = { mode -> blendLabels[mode] ?: mode.name }, + onSelect = { mode -> session?.setPartComposite(part.id, composite.copy(blendMode = mode)) }, + ) + } + }, + ) + if (!composite.blendMode.ignoresAlphaBlend) { + add( + PropertyRow(terms = listOf(Res.string.properties_field_alpha_mode)) { _ -> + val alphaLabels = alphaBlendModeLabels() + PropertyFieldRow( + stringResource(Res.string.properties_field_alpha_mode), + description = stringResource(Res.string.properties_field_alpha_mode_part_description), + ) { + SelectField( + selected = composite.alphaBlendMode, + modifier = Modifier.fillMaxWidth(), + options = AlphaBlendMode.entries, + label = { mode -> alphaLabels[mode] ?: mode.name }, + onSelect = { mode -> session?.setPartComposite(part.id, composite.copy(alphaBlendMode = mode)) }, + ) + } + }, + ) + } + add( + PropertyRow(terms = listOf(Res.string.properties_field_multiply_color)) { _ -> + KeyableColorChannelRow( + label = stringResource(Res.string.properties_field_multiply_color), + description = stringResource(Res.string.properties_field_multiply_color_part_description), + owner = KeyformOwner.Part(part.id), + channel = FormChannel.MULTIPLY_COLOR, + stored = composite.multiplyColor, + session = session, + changeFor = { color -> PartChange.SetComposite(part.id, composite.copy(multiplyColor = color)) }, + writeStatic = { color -> + session?.setPartComposite(part.id, composite.copy(multiplyColor = color)) + }, + ) + }, + ) + add( + PropertyRow(terms = listOf(Res.string.properties_field_screen_color)) { _ -> + KeyableColorChannelRow( + label = stringResource(Res.string.properties_field_screen_color), + description = stringResource(Res.string.properties_field_screen_color_part_description), + owner = KeyformOwner.Part(part.id), + channel = FormChannel.SCREEN_COLOR, + stored = composite.screenColor, + session = session, + changeFor = { color -> PartChange.SetComposite(part.id, composite.copy(screenColor = color)) }, + writeStatic = { color -> + session?.setPartComposite(part.id, composite.copy(screenColor = color)) + }, + ) + }, + ) + add( + PropertyRow(terms = listOf(Res.string.properties_field_masked_by)) { rowContext -> + PartMaskEditor(part, composite, rowContext) + }, + ) + add( + PropertyRow(terms = listOf(Res.string.properties_field_invert_mask)) { _ -> + PropertyCheckboxRow( + checked = composite.invertMask, + onCheckedChange = { invert -> session?.setPartComposite(part.id, composite.copy(invertMask = invert)) }, + label = stringResource(Res.string.properties_field_invert_mask), + description = stringResource(Res.string.properties_field_invert_mask_part_description), + ) + }, + ) + } + } + } else { + emptyList() + } + }, + ) + +/** + * The Data tab's sections for the active item's type: mesh / texture / blend for a drawable, the lattice + * or rotation for a deformer, the part fields for a part, and none when nothing is active. + * + * @param PropertyContext context The current context. + * @return List The Data tab's sections, top to bottom. + */ +internal fun dataTabSections(context: PropertyContext): List = + when (context.activeTarget) { + is SelectionTarget.Drawable -> listOf(MeshSection, TextureSection, BlendSection) + is SelectionTarget.Deformer -> listOf(DeformerSection) + is SelectionTarget.Part -> listOf(PartSection) + null -> emptyList() + } + +/** + * The Data tab's glyph for the active item's type - the mesh, warp / rotation deformer, or part icon (the + * warp-versus-rotation split needs the model, hence the context rather than just the target). + * + * @param PropertyContext context The current context. + * @return UmamoIcon The Data tab's adaptive icon. + */ +internal fun dataTabIcon(context: PropertyContext): UmamoIcon = + when (val target = context.activeTarget) { + is SelectionTarget.Drawable -> LocalUmamoIcons.mesh + // Through the shared glyph so the tab icon and the Relations row can never disagree about a deformer. + is SelectionTarget.Deformer -> + context.puppet.deformers.firstOrNull { it.id == target.id } + ?.let { deformer -> deformerIcon(deformer) } + ?: LocalUmamoIcons.warpDeformer + + is SelectionTarget.Part -> LocalUmamoIcons.part + null -> LocalUmamoIcons.mesh + } + +/** + * One keyable COLOR channel's field row: the label, the hex field with its keyed tint, the + * track-resolved display value, and the keyed-goes-pending edit routing. + * + * ONE composable for every color channel row - drawable or part, multiply or screen - rather than the + * routing rule hand-copied per row: a rule duplicated across every row is exactly the kind of thing that + * drifts, and a row missing it writes a static the track shadows, so the edit appears to be silently + * rejected. + * + * @param String label The row's field label. + * @param String description What the channel does, as the label's tooltip. + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The color channel the row edits. + * @param ColorRgb stored The owner's static color. + * @param EditorSession? session The open document's session, or null. + * @param Function changeFor The history descriptor for a committed color, whichever branch stores it. + * @param Function writeStatic Writes the owner's static color (the unkeyed path). + */ +@Composable +private fun KeyableColorChannelRow( + label: String, + description: String, + owner: KeyformOwner, + channel: FormChannel, + stored: ColorRgb, + session: EditorSession?, + changeFor: (ColorRgb) -> Change, + writeStatic: (ColorRgb) -> Unit, +) { + val target = KeyableTarget(owner, channel) + KeyablePropertyRow(target = target) { + PropertyFieldRow(label, description = description) { + HexColorField( + keyState = keyedFieldStateOf(owner, channel), + // What is APPLIED, not what is stored: on a keyed channel the static is shadowed by the + // track, and a pending unkeyed edit lives outside the model altogether. + value = formatHexColor(displayedChannelColor(owner, channel, stored).toComposeColor()), + onValueChange = { hex -> + parseHexColor(hex)?.let { picked -> + val color = picked.toColorRgb() + session?.editKeyedChannel(target, ChannelValue.Color(color), changeFor(color)) { + writeStatic(color) + } + } + }, + modifier = Modifier.fillMaxWidth(), + ) + } + } +} + +/** + * One keyable FLAG channel's row: the scalar and color rows' counterpart for a checkbox. + * + * A flag snaps to the floor cell rather than blending, which is why it is a channel at all rather than a + * field on the pivot form - but from the row's point of view it keys exactly like the others. + * + * @param String label The checkbox's label. + * @param String description What the channel does, as the label's tooltip. + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The flag channel the row edits. + * @param Boolean stored The owner's static value. + * @param EditorSession? session The open document's session, or null. + * @param Function changeFor The history descriptor for a committed value, whichever branch stores it. + * @param Function writeStatic Writes the owner's static value (the unkeyed path). + */ +@Composable +private fun KeyableFlagChannelRow( + label: String, + description: String, + owner: KeyformOwner, + channel: FormChannel, + stored: Boolean, + session: EditorSession?, + changeFor: (Boolean) -> Change, + writeStatic: (Boolean) -> Unit, +) { + val target = KeyableTarget(owner, channel) + KeyablePropertyRow(target = target) { + PropertyCheckboxRow( + keyState = keyedFieldStateOf(owner, channel), + // What is APPLIED: a keyed channel's track shadows the static. + checked = displayedChannelFlag(owner, channel, stored), + onCheckedChange = { flag -> + session?.editKeyedChannel(target, ChannelValue.Flag(flag), changeFor(flag)) { writeStatic(flag) } + }, + label = label, + description = description, + ) + } +} + +/** + * A deformer's keyable render channels: opacity, multiply color, screen color. + * + * Shared by both subtypes because both carry them and both cascade them. Listed FIRST in the section, so + * the channels a rigger keys sit above the structural fields (lattice dimensions, base angle) that are set + * once and left alone. Opacity is always shown; the two color rows are each gated on [target] supporting + * their feature, so the result can be fewer than three rows. + * + * @param Deformer deformer The deformer the rows edit. + * @param EditorSession? session The open document's session, or null. + * @param RuntimeTarget target The document's runtime-compatibility target, gating the color rows. + * @return List The opacity row, plus each color row the target still supports. + */ +private fun deformerRenderChannelRows( + deformer: Deformer, + session: EditorSession?, + target: RuntimeTarget, +): List { + val owner = KeyformOwner.Deformer(deformer.id) + return listOfNotNull( + PropertyRow(terms = listOf(Res.string.properties_field_opacity)) { _ -> + KeyableScalarChannelRow( + label = stringResource(Res.string.properties_field_opacity), + description = stringResource(Res.string.properties_field_opacity_deformer_description), + owner = owner, + channel = FormChannel.OPACITY, + stored = deformer.opacity, + session = session, + range = 0f..1f, + decimals = 3, + step = 0.05f, + changeFor = { opacity -> DeformerChange.SetOpacity(deformer.id, opacity) }, + writeStatic = { opacity -> session?.setDeformerOpacity(deformer.id, opacity) }, + ) + }, + // The deformer color cascade is a 4.2 feature (official target dialog), like the drawable tints. + if (!target.supports(RuntimeFeature.MultiplyColor)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_multiply_color)) { _ -> + KeyableColorChannelRow( + label = stringResource(Res.string.properties_field_multiply_color), + description = stringResource(Res.string.properties_field_multiply_color_deformer_description), + owner = owner, + channel = FormChannel.MULTIPLY_COLOR, + stored = deformer.multiplyColor, + session = session, + changeFor = { color -> DeformerChange.SetMultiplyColor(deformer.id, color) }, + writeStatic = { color -> session?.setDeformerMultiplyColor(deformer.id, color) }, + ) + } + }, + if (!target.supports(RuntimeFeature.ScreenColor)) { + null + } else { + PropertyRow(terms = listOf(Res.string.properties_field_screen_color)) { _ -> + KeyableColorChannelRow( + label = stringResource(Res.string.properties_field_screen_color), + description = stringResource(Res.string.properties_field_screen_color_deformer_description), + owner = owner, + channel = FormChannel.SCREEN_COLOR, + stored = deformer.screenColor, + session = session, + changeFor = { color -> DeformerChange.SetScreenColor(deformer.id, color) }, + writeStatic = { color -> session?.setDeformerScreenColor(deformer.id, color) }, + ) + } + }, + ) +} + +/** + * One keyable SCALAR channel's field row: [KeyableColorChannelRow]'s counterpart for a number field. + * + * @param String label The row's field label. + * @param String description What the channel does, as the label's tooltip. + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The scalar channel the row edits. + * @param Float stored The owner's static value. + * @param EditorSession? session The open document's session, or null. + * @param ClosedFloatingPointRange range The field's legal range. + * @param Int decimals The field's display precision. + * @param Float step The field's chevron step. + * @param Function changeFor The history descriptor for a committed value, whichever branch stores it. + * @param Function writeStatic Writes the owner's static value (the unkeyed path). + */ +@Composable +private fun KeyableScalarChannelRow( + label: String, + description: String, + owner: KeyformOwner, + channel: FormChannel, + stored: Float, + session: EditorSession?, + range: ClosedFloatingPointRange, + decimals: Int, + step: Float, + changeFor: (Float) -> Change, + writeStatic: (Float) -> Unit, +) { + val target = KeyableTarget(owner, channel) + KeyablePropertyRow(target = target) { + PropertyFieldRow(label, description = description) { + NumberField( + keyState = keyedFieldStateOf(owner, channel), + // What is APPLIED: a keyed channel's track shadows the static. + value = displayedChannelScalar(owner, channel, stored), + onValueChange = { value: Float -> + session?.editKeyedChannel(target, ChannelValue.Scalar(value), changeFor(value)) { + writeStatic(value) + } + }, + modifier = Modifier.fillMaxWidth(), + range = range, + decimals = decimals, + step = step, + // A drag-scrub previews through the pending buffer so the viewport follows the pointer, and + // commits once on release - the same two-phase contract the parameter sliders have. + onPreview = { previewed: Float -> + session?.previewChannelEdit(target, ChannelValue.Scalar(previewed)) + }, + ) + } + } +} + +/** Which conversion-division axis a [WarpGridAxisSlider] edits. */ +private enum class WarpGridAxis { + Columns, + Rows, +} + +/** + * Properties > Data > Deformer: one conversion-division slider (X = columns, Y = rows). The drag + * drafts locally and commits once on release so a scrub is a single undo step; the other axis keeps + * its committed value. + * + * @param Deformer.Warp deformer The selected warp. + * @param EditorSession? session The editing session, or null when the panel is browse-only. + * @param WarpGridAxis axis Which lattice axis this slider drives. + */ +@Composable +private fun WarpGridAxisSlider( + deformer: Deformer.Warp, + session: EditorSession?, + axis: WarpGridAxis, +) { + val committed = + when (axis) { + WarpGridAxis.Columns -> deformer.columns + WarpGridAxis.Rows -> deformer.rows + }.coerceIn(MIN_WARP_DIVISIONS, MAX_WARP_DIVISIONS) + var draft by remember(deformer.id, axis, committed) { mutableFloatStateOf(committed.toFloat()) } + val divisions = draft.roundToInt().coerceIn(MIN_WARP_DIVISIONS, MAX_WARP_DIVISIONS) + val label = + when (axis) { + WarpGridAxis.Columns -> stringResource(Res.string.properties_warp_grid_x, divisions) + WarpGridAxis.Rows -> stringResource(Res.string.properties_warp_grid_y, divisions) + } + PropertyFieldRow( + label, + description = stringResource(Res.string.properties_field_warp_grid_description), + ) { + Slider( + value = divisions.toFloat(), + onValueChange = { value -> draft = value.roundToInt().toFloat() }, + onValueChangeFinished = { + val rows = + when (axis) { + WarpGridAxis.Columns -> deformer.rows + WarpGridAxis.Rows -> divisions + } + val columns = + when (axis) { + WarpGridAxis.Columns -> divisions + WarpGridAxis.Rows -> deformer.columns + } + session?.setDeformerWarpGrid(deformer.id, rows, columns) + }, + modifier = Modifier.fillMaxWidth(), + valueRange = MIN_WARP_DIVISIONS.toFloat()..MAX_WARP_DIVISIONS.toFloat(), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/DocumentTabSections.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/DocumentTabSections.kt new file mode 100644 index 0000000..e052a82 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/DocumentTabSections.kt @@ -0,0 +1,230 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.setCanvasSize +import org.umamo.edit.setRuntimeTarget +import org.umamo.edit.setSourceLayerDisplay +import org.umamo.edit.setWorldOrigin +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.runtime.model.originFromCanvasBottom +import org.umamo.runtime.model.originFromCanvasLeft +import org.umamo.runtime.model.unsupportedFeaturesInUse +import org.umamo.runtime.model.worldOriginXFromCanvasLeft +import org.umamo.runtime.model.worldOriginZFromCanvasBottom +import org.umamo.ui.kit.FieldStack +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.SelectField +import org.umamo.ui.resources.* + +/* + * The Document tab's sections: properties of the document itself rather than of any selected item, so they + * are the one tab that shows with an empty selection. + */ + +/** Document > Canvas: the document canvas size and world origin. */ +internal val CanvasSection = + PropertySection( + id = "document.canvas", + title = Res.string.properties_section_canvas, + rows = { context -> + val puppet = context.puppet + val session = context.session + listOf( + // Width + height joined into one stacked group; the whole stack is one searchable row. + PropertyRow( + terms = listOf(Res.string.properties_field_canvas_width, Res.string.properties_field_canvas_height), + ) { _ -> + val pixels = stringResource(Res.string.unit_pixels) + FieldStack( + listOf( + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_canvas_width), + description = stringResource(Res.string.properties_field_canvas_width_description), + ) { + NumberField( + value = puppet.canvasWidth, + onValueChange = { newWidth -> session?.setCanvasSize(newWidth, puppet.canvasHeight) }, + modifier = Modifier.fillMaxWidth(), + range = POSITIVE_RANGE, + decimals = 0, + unitSuffix = pixels, + stackPosition = position, + ) + } + }, + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_canvas_height), + description = stringResource(Res.string.properties_field_canvas_height_description), + ) { + NumberField( + value = puppet.canvasHeight, + onValueChange = { newHeight -> session?.setCanvasSize(puppet.canvasWidth, newHeight) }, + modifier = Modifier.fillMaxWidth(), + range = POSITIVE_RANGE, + decimals = 0, + unitSuffix = pixels, + stackPosition = position, + ) + } + }, + ), + ) + }, + // The origin x / z into a second stacked group below it. The origin places the world axes every + // other position reads from, so it alone is measured on the canvas: from its bottom-left corner, + // Z up. Each row converts only its own axis and passes the other's stored value through. + PropertyRow( + terms = listOf(Res.string.properties_field_origin_x, Res.string.properties_field_origin_z), + ) { _ -> + FieldStack( + listOf( + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_origin_x), + description = stringResource(Res.string.properties_field_origin_x_description), + ) { + NumberField( + value = puppet.originFromCanvasLeft(), + onValueChange = { newX -> + session?.setWorldOrigin(puppet.worldOriginXFromCanvasLeft(newX), puppet.worldOriginZ) + }, + modifier = Modifier.fillMaxWidth(), + range = UNBOUNDED_RANGE, + decimals = 1, + stackPosition = position, + ) + } + }, + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_origin_z), + description = stringResource(Res.string.properties_field_origin_z_description), + ) { + NumberField( + value = puppet.originFromCanvasBottom(), + onValueChange = { newZ -> + session?.setWorldOrigin(puppet.worldOriginX, puppet.worldOriginZFromCanvasBottom(newZ)) + }, + modifier = Modifier.fillMaxWidth(), + range = UNBOUNDED_RANGE, + decimals = 1, + stackPosition = position, + ) + } + }, + ), + ) + }, + ) + }, + ) + +/** + * Document > Display: whether the puppet displays from its source artwork or from the packed atlas. + * + * Document content rather than an app preference - the source formats author it, and a CMO3 carries it + * on its texture manager - so the toggle writes the model as one undo step and round-trips on export. + * + * Shown for every open document, including one whose artwork the renderer cannot display from (a MOC3 + * origin is the packed endpoint of that pipeline and retains none): the toggle records authored INTENT, + * which round-trips and applies once the artwork is there, so it is not gated on today's recoverability. + * Honoring it is best-effort per drawable, so a document whose artwork is only partly recoverable + * displays from a mix and says so. + */ +internal val DisplaySection = + PropertySection( + id = "document.display", + title = Res.string.properties_section_display, + rows = { context -> + val puppet = context.puppet + val session = context.session + listOf( + PropertyRow(terms = listOf(Res.string.properties_field_source_layer_display)) { _ -> + PropertyCheckboxRow( + checked = puppet.rendersFromSourceLayers, + onCheckedChange = { enabled -> session?.setSourceLayerDisplay(enabled) }, + label = stringResource(Res.string.properties_field_source_layer_display), + description = stringResource(Res.string.properties_field_source_layer_display_description), + ) + }, + ) + }, + ) + +/** + * Document > Runtime: the document's runtime-compatibility target (Cubism, Ayagami) and the features + * it restricts. The selector writes [org.umamo.runtime.model.PuppetModel.runtimeTarget] as one undo + * step; the restricted list derives from the capability matrix, never a hardcoded per-target list. + * + * A CMO3 export persists every target: Cubism targets as their literals, NoTarget as the editor's + * SDK(N/A)/Latest sentinel, and Ayagami at its effective Cubism level (its identity cannot survive + * CMO3, so a reopen shows Cubism 5.0 - UMA will carry the identity natively). + */ +internal val RuntimeSection = + PropertySection( + id = "document.runtime", + title = Res.string.properties_section_runtime, + rows = { context -> + val puppet = context.puppet + val session = context.session + listOf( + PropertyRow(terms = listOf(Res.string.properties_field_runtime_target)) { _ -> + val targetLabels = runtimeTargetLabels() + PropertyFieldRow( + stringResource(Res.string.properties_field_runtime_target), + description = stringResource(Res.string.properties_field_runtime_target_description), + ) { + SelectField( + selected = puppet.runtimeTarget, + modifier = Modifier.fillMaxWidth(), + options = RuntimeTarget.entries, + label = { target -> targetLabels[target] ?: target.displayName }, + onSelect = { target -> session?.setRuntimeTarget(target) }, + ) + } + }, + // The whole restricted list is one searchable row so header search keeps the block + // intact, same rationale as the stacked canvas fields above. + PropertyRow( + terms = listOf(Res.string.properties_runtime_restricted, Res.string.properties_runtime_no_restrictions), + ) { _ -> + val restricted = puppet.runtimeTarget.restrictedFeatures() + if (restricted.isEmpty()) { + PropertyLine(stringResource(Res.string.properties_runtime_no_restrictions)) + } else { + // Marking the entries THIS document actually uses turns the abstract per-target + // list into a decision aid (the same strip diff a MOC3 export will confirm). The + // scan walks every drawable, part, and deformer, so it is keyed to the model + // instance rather than recomputed on every recomposition. + val featuresInUse = remember(puppet) { puppet.unsupportedFeaturesInUse(puppet.runtimeTarget) } + Column { + PropertyLine(stringResource(Res.string.properties_runtime_restricted)) + restricted.forEach { feature -> + val featureLabel = stringResource(runtimeFeatureLabelRes(feature)) + val line = + if (feature in featuresInUse) { + stringResource(Res.string.properties_runtime_feature_in_use, featureLabel) + } else { + featureLabel + } + Box(modifier = Modifier.padding(start = 12.dp)) { + PropertyLine(line) + } + } + } + } + }, + ) + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/EnumLabels.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/EnumLabels.kt new file mode 100644 index 0000000..119faa4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/EnumLabels.kt @@ -0,0 +1,272 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.alpha_blend_atop +import org.umamo.ui.resources.alpha_blend_conjoint +import org.umamo.ui.resources.alpha_blend_disjoint +import org.umamo.ui.resources.alpha_blend_out +import org.umamo.ui.resources.alpha_blend_over +import org.umamo.ui.resources.blend_mode_additive +import org.umamo.ui.resources.blend_mode_additive_glow +import org.umamo.ui.resources.blend_mode_additive_premultiplied +import org.umamo.ui.resources.blend_mode_color +import org.umamo.ui.resources.blend_mode_color_burn +import org.umamo.ui.resources.blend_mode_color_dodge +import org.umamo.ui.resources.blend_mode_darken +import org.umamo.ui.resources.blend_mode_hard_light +import org.umamo.ui.resources.blend_mode_hue +import org.umamo.ui.resources.blend_mode_lighten +import org.umamo.ui.resources.blend_mode_linear_burn +import org.umamo.ui.resources.blend_mode_linear_light +import org.umamo.ui.resources.blend_mode_multiply +import org.umamo.ui.resources.blend_mode_multiply_premultiplied +import org.umamo.ui.resources.blend_mode_normal +import org.umamo.ui.resources.blend_mode_overlay +import org.umamo.ui.resources.blend_mode_screen +import org.umamo.ui.resources.blend_mode_soft_light +import org.umamo.ui.resources.channel_draw_order +import org.umamo.ui.resources.channel_flip_x +import org.umamo.ui.resources.channel_flip_y +import org.umamo.ui.resources.channel_glue_intensity +import org.umamo.ui.resources.channel_multiply_color +import org.umamo.ui.resources.channel_opacity +import org.umamo.ui.resources.channel_screen_color +import org.umamo.ui.resources.part_group_grouped +import org.umamo.ui.resources.part_group_isolated +import org.umamo.ui.resources.part_group_pass_through +import org.umamo.ui.resources.runtime_feature_art_path +import org.umamo.ui.resources.runtime_feature_blend_shape_parameters +import org.umamo.ui.resources.runtime_feature_extended_blend_modes +import org.umamo.ui.resources.runtime_feature_extended_blend_shapes +import org.umamo.ui.resources.runtime_feature_mesh_warp_blend_shapes +import org.umamo.ui.resources.runtime_feature_motion_sync +import org.umamo.ui.resources.runtime_feature_multiply_color +import org.umamo.ui.resources.runtime_feature_parameter_repeat +import org.umamo.ui.resources.runtime_feature_part_composite +import org.umamo.ui.resources.runtime_feature_reversed_mask +import org.umamo.ui.resources.runtime_feature_screen_color +import org.umamo.ui.resources.runtime_feature_warp_quad_transform +import org.umamo.ui.resources.runtime_target_ayagami +import org.umamo.ui.resources.runtime_target_no_target + +/* + * Localized display names for the format-level enums the Properties dropdowns edit (blend mode, alpha + * blend mode, part group mode). The label is UI chrome - the enum entry itself is the data model and + * stays verbatim. Each mapping is an exhaustive `when`, so adding an enum entry is a compile error until + * it gets a label (compile-time completeness, in place of a runtime coverage test). + */ + +/** + * The flat, closed set of part group-mode choices for a dropdown. [PartGroupMode] is a sealed type whose + * Isolated case carries a composite; this projects it to a plain three-way selector so the dropdown edits + * the mode while the composite rides along (default when first switched to Isolated). + */ +enum class PartGroupModeKind { + PassThrough, + Grouped, + Isolated, +} + +/** + * The [PartGroupModeKind] of this mode (drops the Isolated composite payload). + * + * @return PartGroupModeKind The mode's kind. + */ +fun PartGroupMode.kind(): PartGroupModeKind = + when (this) { + PartGroupMode.PassThrough -> PartGroupModeKind.PassThrough + PartGroupMode.Grouped -> PartGroupModeKind.Grouped + is PartGroupMode.Isolated -> PartGroupModeKind.Isolated + } + +/** + * Builds a [PartGroupMode] from a chosen [kind]. The modes are payload-free now that a part's composite + * lives latently on the part itself (independent of the mode), so this is a plain projection - switching a + * part's mode never touches its composite settings. + * + * @param PartGroupModeKind kind The chosen kind. + * @return PartGroupMode The mode for that kind. + */ +fun partGroupModeOf(kind: PartGroupModeKind): PartGroupMode = + when (kind) { + PartGroupModeKind.PassThrough -> PartGroupMode.PassThrough + PartGroupModeKind.Grouped -> PartGroupMode.Grouped + PartGroupModeKind.Isolated -> PartGroupMode.Isolated + } + +/** + * The [StringResource] naming a blend mode in the UI. + * + * @param BlendMode mode The blend mode. + * @return StringResource The localized label resource. + */ +fun blendModeLabelRes(mode: BlendMode): StringResource = + when (mode) { + BlendMode.Normal -> Res.string.blend_mode_normal + BlendMode.Additive -> Res.string.blend_mode_additive + BlendMode.Multiply -> Res.string.blend_mode_multiply + BlendMode.AdditivePremultiplied -> Res.string.blend_mode_additive_premultiplied + BlendMode.AdditiveGlow -> Res.string.blend_mode_additive_glow + BlendMode.Darken -> Res.string.blend_mode_darken + BlendMode.MultiplyPremultiplied -> Res.string.blend_mode_multiply_premultiplied + BlendMode.ColorBurn -> Res.string.blend_mode_color_burn + BlendMode.LinearBurn -> Res.string.blend_mode_linear_burn + BlendMode.Lighten -> Res.string.blend_mode_lighten + BlendMode.Screen -> Res.string.blend_mode_screen + BlendMode.ColorDodge -> Res.string.blend_mode_color_dodge + BlendMode.Overlay -> Res.string.blend_mode_overlay + BlendMode.SoftLight -> Res.string.blend_mode_soft_light + BlendMode.HardLight -> Res.string.blend_mode_hard_light + BlendMode.LinearLight -> Res.string.blend_mode_linear_light + BlendMode.Hue -> Res.string.blend_mode_hue + BlendMode.Color -> Res.string.blend_mode_color + } + +/** + * The [StringResource] naming an alpha blend mode in the UI. + * + * @param AlphaBlendMode mode The alpha blend mode. + * @return StringResource The localized label resource. + */ +fun alphaBlendModeLabelRes(mode: AlphaBlendMode): StringResource = + when (mode) { + AlphaBlendMode.Over -> Res.string.alpha_blend_over + AlphaBlendMode.Atop -> Res.string.alpha_blend_atop + AlphaBlendMode.Out -> Res.string.alpha_blend_out + AlphaBlendMode.Conjoint -> Res.string.alpha_blend_conjoint + AlphaBlendMode.Disjoint -> Res.string.alpha_blend_disjoint + } + +/** + * The [StringResource] naming a part group-mode choice in the UI. + * + * @param PartGroupModeKind kind The group-mode kind. + * @return StringResource The localized label resource. + */ +fun partGroupModeLabelRes(kind: PartGroupModeKind): StringResource = + when (kind) { + PartGroupModeKind.PassThrough -> Res.string.part_group_pass_through + PartGroupModeKind.Grouped -> Res.string.part_group_grouped + PartGroupModeKind.Isolated -> Res.string.part_group_isolated + } + +/** + * Resolves every blend-mode label once, as an option-to-string map for a dropdown. The call count is + * fixed ([BlendMode] is a closed enum), so it stays within Compose's positional-memoization rules. + * + * @return Map Each blend mode to its localized label. + */ +@Composable +fun blendModeLabels(): Map = BlendMode.entries.associateWith { mode -> stringResource(blendModeLabelRes(mode)) } + +/** + * The blend modes in dropdown display order: the 5.3 modes first, in their canonical MOC3 colorMode + * order, then the "(Legacy)" pre-5.3 premultiplied modes (AdditivePremultiplied and + * MultiplyPremultiplied - exactly the two that ignore the alpha blend setting) sunk to the bottom so + * they stay out of the way for new work. [BlendMode.entries] - the enum/format order backing the + * packed-int mapping - is NOT reordered; only the picker's presentation changes. + * + * @return List The blend modes in the order the picker should present them. + */ +fun blendModeDisplayOrder(): List = + BlendMode.entries.filterNot { it.ignoresAlphaBlend } + BlendMode.entries.filter { it.ignoresAlphaBlend } + +/** + * Resolves every alpha-blend-mode label once, as an option-to-string map for a dropdown. + * + * @return Map Each alpha blend mode to its localized label. + */ +@Composable +fun alphaBlendModeLabels(): Map = + AlphaBlendMode.entries.associateWith { mode -> stringResource(alphaBlendModeLabelRes(mode)) } + +/** + * Resolves every part group-mode label once, as a kind-to-string map for a dropdown. + * + * @return Map Each group-mode kind to its localized label. + */ +@Composable +fun partGroupModeLabels(): Map = + PartGroupModeKind.entries.associateWith { kind -> stringResource(partGroupModeLabelRes(kind)) } + +/** + * The [StringResource] naming a restricted runtime feature in the UI, phrased to match the official + * Cubism editor's "Model target version selection" dialog so migrants recognize each entry. + * + * @param RuntimeFeature feature The restricted feature. + * @return StringResource The localized label resource. + */ +fun runtimeFeatureLabelRes(feature: RuntimeFeature): StringResource = + when (feature) { + RuntimeFeature.WarpQuadTransform -> Res.string.runtime_feature_warp_quad_transform + RuntimeFeature.ReversedMask -> Res.string.runtime_feature_reversed_mask + RuntimeFeature.MeshWarpBlendShapes -> Res.string.runtime_feature_mesh_warp_blend_shapes + RuntimeFeature.BlendShapeParameters -> Res.string.runtime_feature_blend_shape_parameters + RuntimeFeature.MultiplyColor -> Res.string.runtime_feature_multiply_color + RuntimeFeature.ScreenColor -> Res.string.runtime_feature_screen_color + RuntimeFeature.ExtendedBlendShapes -> Res.string.runtime_feature_extended_blend_shapes + RuntimeFeature.MotionSync -> Res.string.runtime_feature_motion_sync + RuntimeFeature.ExtendedBlendModes -> Res.string.runtime_feature_extended_blend_modes + RuntimeFeature.PartComposite -> Res.string.runtime_feature_part_composite + RuntimeFeature.ParameterRepeat -> Res.string.runtime_feature_parameter_repeat + RuntimeFeature.ArtPath -> Res.string.runtime_feature_art_path + } + +/** + * The [StringResource] naming a keyform channel in the UI. + * + * Shared by the keyform sheet's track headers and the export report, so a demoted channel is named + * with the same word the sheet showed it under. + * + * @param FormChannel channel The channel to label. + * @return StringResource The localized label resource. + */ +fun formChannelLabelRes(channel: FormChannel): StringResource = + when (channel) { + FormChannel.DRAW_ORDER -> Res.string.channel_draw_order + FormChannel.OPACITY -> Res.string.channel_opacity + FormChannel.MULTIPLY_COLOR -> Res.string.channel_multiply_color + FormChannel.SCREEN_COLOR -> Res.string.channel_screen_color + FormChannel.FLIP_X -> Res.string.channel_flip_x + FormChannel.FLIP_Y -> Res.string.channel_flip_y + FormChannel.GLUE_INTENSITY -> Res.string.channel_glue_intensity + } + +/** + * The display label for a runtime target: NoTarget and Ayagami resolve through the string catalog + * (their parentheticals are chrome), while the Cubism entries are product identity shown verbatim + * from [RuntimeTarget.displayName], never localized. + * + * @param RuntimeTarget target The target to label. + * @return String The dropdown label. + */ +@Composable +fun runtimeTargetLabel(target: RuntimeTarget): String = + when (target) { + RuntimeTarget.NoTarget -> stringResource(Res.string.runtime_target_no_target) + RuntimeTarget.Ayagami -> stringResource(Res.string.runtime_target_ayagami, target.cubismLevelText().orEmpty()) + RuntimeTarget.Cubism30, + RuntimeTarget.Cubism33, + RuntimeTarget.Cubism40, + RuntimeTarget.Cubism42, + RuntimeTarget.Cubism50, + RuntimeTarget.Cubism53, + -> target.displayName + } + +/** + * Resolves every runtime-target label once, as a target-to-string map for the dropdown. + * + * @return Map Each runtime target to its display label. + */ +@Composable +fun runtimeTargetLabels(): Map = RuntimeTarget.entries.associateWith { target -> runtimeTargetLabel(target) } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/KeyablePropertyRow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/KeyablePropertyRow.kt new file mode 100644 index 0000000..4e6c7b1 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/KeyablePropertyRow.kt @@ -0,0 +1,60 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import org.jetbrains.compose.resources.stringResource +import org.umamo.runtime.model.KeyableTarget +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.model.keyableTarget +import org.umamo.ui.resources.* + +/* + * The keyable-property row wrapper: hover targeting plus the Insert / Remove Keyframe context menu. + * + * Both affordances belong to the same rows and neither is useful without the other - the shortcut is the + * fast path and the menu is how a user finds out the shortcut exists - so they are applied together + * rather than left to be remembered separately at each call site. + */ + +/** + * Wraps [content] as a keyable property row: it publishes [target] on hover and carries the keyframe + * context menu. + * + * The menu dispatches through the action registry rather than calling the session directly, per the + * project's input rule - so a rebind reaches the menu too, and the menu shows whatever chord is currently + * bound. The commands resolve the HOVERED target when they fire, and a right-click necessarily leaves the + * pointer over this row, so they aim here without the menu having to pass anything. + * + * @param KeyableTarget target The entity and channel this row edits. + * @param Modifier modifier The layout modifier for the row. + * @param Function content The row itself. + */ +@Composable +internal fun KeyablePropertyRow( + target: KeyableTarget, + modifier: Modifier = Modifier, + content: @Composable () -> Unit, +) { + val commands = LocalCommands.current + val keymap = LocalKeymap.current + val items = + listOf( + MenuItem.Action( + label = stringResource(Res.string.cmd_keyform_insert), + onSelect = { commands.invoke("keyform.insert") }, + shortcut = keymap.chordFor("keyform.insert")?.let { chord -> formatAccelerator(chord) }, + ), + MenuItem.Action( + label = stringResource(Res.string.cmd_keyform_delete), + onSelect = { commands.invoke("keyform.delete") }, + shortcut = keymap.chordFor("keyform.delete")?.let { chord -> formatAccelerator(chord) }, + ), + ) + ContextMenuArea(items = items, modifier = modifier.keyableTarget(target)) { + content() + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/KeyedFieldResolve.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/KeyedFieldResolve.kt new file mode 100644 index 0000000..7817aab --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/KeyedFieldResolve.kt @@ -0,0 +1,137 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import org.umamo.edit.EditorSession +import org.umamo.edit.Pose +import org.umamo.edit.channelValueAt +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformOwner +import org.umamo.ui.model.KeyedFieldState +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalLiveParams +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.keyedFieldStateOf + +/* + * Resolving a properties-panel row's keyed state from the session. + * + * Kept beside the panel rather than inside the field primitives: the kit knows how to PAINT a keyed state + * and nothing about parameters, poses, or sessions, which is what lets the same fields serve rows that are + * not keyable at all. + */ + +/** + * The keyed state of [channel] on [drawable] at the displayed pose. + * + * @param Drawable drawable The drawable the row edits. + * @param FormChannel channel The channel the row edits. + * @return KeyedFieldState The state to tint the field with. + */ +@Composable +internal fun keyedFieldStateOf(drawable: Drawable, channel: FormChannel): KeyedFieldState = + keyedFieldStateOf(KeyformOwner.Drawable(drawable.id), channel) + +/** + * The keyed state of [channel] on any [owner] at the displayed pose. + * + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The channel the row edits. + * @return KeyedFieldState The state to tint the field with. + */ +@Composable +internal fun keyedFieldStateOf(owner: KeyformOwner, channel: FormChannel): KeyedFieldState { + val puppet = LocalPuppet.current ?: return KeyedFieldState.None + val session = LocalEditorSession.current ?: return KeyedFieldState.None + val pendingEdits by remember(session) { session.pendingChannelEdits }.collectAsState() + return keyedFieldStateOf( + puppet = puppet, + target = KeyableTarget(owner, channel), + pose = displayPose(session), + pendingEdits = pendingEdits, + ) +} + +/** + * The pose the Properties panel should resolve against: the LIVE preview pose when a viewport is + * publishing one, else the session's committed pose. + * + * A preview deliberately never touches session.pose (that is what keeps a whole drag to one undo step), so + * resolving at the committed pose alone would freeze every keyable field and its OnKey/BetweenKeys tint at + * the gesture-start value while the viewport animated - the exact field/viewport disagreement this resolver + * exists to prevent. The observed map is snapshot state, so the reading row recomposes as it moves. + * + * @param EditorSession session The open document's session. + * @return Pose The pose to resolve displayed values at. + */ +@Composable +private fun displayPose(session: EditorSession): Pose { + val committedPose by remember(session) { session.pose }.collectAsState() + return LocalLiveParams.current?.observedValues ?: committedPose +} + +/** + * The value a keyable row should DISPLAY: the pending unkeyed edit, else the track's value at the current + * pose, else the owner's static. + * + * The same resolution order the renderer uses, which is the point. Showing the static alone would be + * wrong twice over: on a keyed channel the static is shadowed by the track, so the field would disagree + * with the viewport at every pose; and a pending edit lives outside the model entirely, so typing a new + * value on a keyed channel would appear to be rejected - the field would snap straight back to the shadowed + * static. + * + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The channel the row edits. + * @param ChannelValue stored The owner's static value, used when nothing overrides it. + * @return ChannelValue The value to show. + */ +@Composable +internal fun displayedChannelValue(owner: KeyformOwner, channel: FormChannel, stored: ChannelValue): ChannelValue { + val puppet = LocalPuppet.current ?: return stored + val session = LocalEditorSession.current ?: return stored + val pendingEdits by remember(session) { session.pendingChannelEdits }.collectAsState() + val target = KeyableTarget(owner, channel) + return pendingEdits[target] ?: puppet.channelValueAt(target, displayPose(session)) ?: stored +} + +/** + * The [displayedChannelValue] of a flag channel, unwrapped. + * + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The flag channel the row edits. + * @param Boolean stored The owner's static value. + * @return Boolean The value to show. + */ +@Composable +internal fun displayedChannelFlag(owner: KeyformOwner, channel: FormChannel, stored: Boolean): Boolean = + (displayedChannelValue(owner, channel, ChannelValue.Flag(stored)) as? ChannelValue.Flag)?.flag ?: stored + +/** + * The [displayedChannelValue] of a scalar channel, unwrapped. + * + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The scalar channel the row edits. + * @param Float stored The owner's static value. + * @return Float The value to show. + */ +@Composable +internal fun displayedChannelScalar(owner: KeyformOwner, channel: FormChannel, stored: Float): Float = + (displayedChannelValue(owner, channel, ChannelValue.Scalar(stored)) as? ChannelValue.Scalar)?.value ?: stored + +/** + * The [displayedChannelValue] of a color channel, unwrapped. + * + * @param KeyformOwner owner The entity the row edits. + * @param FormChannel channel The color channel the row edits. + * @param ColorRgb stored The owner's static color. + * @return ColorRgb The color to show. + */ +@Composable +internal fun displayedChannelColor(owner: KeyformOwner, channel: FormChannel, stored: ColorRgb): ColorRgb = + (displayedChannelValue(owner, channel, ChannelValue.Color(stored)) as? ChannelValue.Color)?.color ?: stored \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/MaskEditors.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/MaskEditors.kt new file mode 100644 index 0000000..c56628a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/MaskEditors.kt @@ -0,0 +1,245 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.SelectionTarget +import org.umamo.edit.setDrawableMaskedBy +import org.umamo.edit.setPartComposite +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartComposite +import org.umamo.runtime.model.PartId +import org.umamo.ui.kit.RelationListField +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.workspace.LocalRelationPick +import org.umamo.ui.workspace.PickKind +import org.umamo.ui.workspace.pickingFor + +/* + * The clip-mask relation lists - a part composite's masks and a drawable's own. Both are add / remove + * lists over the shared RelationListField, and both resolve their picks against the LIVE model rather than + * the value captured in composition (an armed eyedropper resolves long after it was armed). + */ + +/** The "Masked By" relation list's name in the editor entry's `listHeights` (UMA §7.3); a part's and a drawable's share it. */ +private const val MASKED_BY_LIST_NAME = "maskedBy" + +/** + * The drawables eligible to be added as clip masks for a composite: every drawable not already applied. + * Any drawable is a valid mask target (the model has no is-mask flag), so the candidate set is simply the + * complement of [current]. Pure, so the "add mask" menu contents are unit-testable. + * + * @param List drawables Every drawable in the model. + * @param List current The mask ids already applied to the composite. + * @return List The drawables not yet masking, in model order. + */ +internal fun maskCandidates(drawables: List, current: List): List { + val applied = current.toSet() + return drawables.filter { drawable -> drawable.id !in applied } +} + +/** + * One entry in a composite's clip-mask list. A drawable clips directly; a part stands for every drawable + * in its subtree and is resolved to them only in the derived render tree, so the mask follows the part as + * its children change (see [org.umamo.runtime.model.PartComposite.maskedByParts]). + */ +private sealed interface MaskEntry { + /** The entry's display name. */ + val name: String + + /** A drawable whose alpha clips directly. */ + data class OfDrawable(val id: DrawableId, override val name: String) : MaskEntry + + /** A part standing for its descendant drawables. */ + data class OfPart(val id: PartId, override val name: String) : MaskEntry +} + +/** + * A mask entry's stable row identity. The wrapping entry is rebuilt every recomposition, and the display + * name is source-art data that repeats, so the underlying id is the only thing that identifies a row. + * + * @return Any The entry's stable key. + */ +private fun MaskEntry.key(): Any = + when (this) { + is MaskEntry.OfDrawable -> id + is MaskEntry.OfPart -> id + } + +/** + * The type glyph for a mask entry, so drawable and part masks read apart in the list. + * + * @return UmamoIcon The entry's type icon. + */ +private fun MaskEntry.glyph(): UmamoIcon = + when (this) { + is MaskEntry.OfDrawable -> LocalUmamoIcons.mesh + is MaskEntry.OfPart -> LocalUmamoIcons.part + } + +/** + * The isolated part composite's clip-mask editor: a scrollable, resizable list of the drawables and parts + * clipping the layer, over a search field whose eyedropper takes a mask straight from the viewport or the + * outliner. Every edit routes the whole updated composite through setPartComposite, so it is one undo step + * and survives a mode round-trip like the other composite fields. Masks are a set (order does not affect + * coverage), so the list is not reorderable. + * + * A viewport click resolves to the drawable it hits; picking a whole part is done from the list or the + * outliner, since the viewport hit test is drawable-only. + * + * @param Part part The part whose composite is edited. + * @param PartComposite composite The active (Isolated) composite being edited. + * @param PropertyContext context The context supplying the model and session. + */ +@Composable +internal fun PartMaskEditor(part: Part, composite: PartComposite, context: PropertyContext) { + val session = context.session + val relationPick = LocalRelationPick.current + val owner = "part.maskedBy:${part.id.raw}" + // Every write re-reads the part's CURRENT composite rather than the one captured in this composition. + // An armed eyedropper resolves LONG after it was armed and the panel stays editable in between, so + // closing over `composite` would silently revert any opacity / color edit made while the pick was in + // flight - one undo step that quietly undoes two others. + val mutateComposite: (PartComposite.() -> PartComposite) -> Unit = { change -> + val live = session?.model?.value?.parts?.firstOrNull { it.id == part.id }?.activeComposite + if (live != null) { + session.setPartComposite(part.id, live.change()) + } + } + + val entries = + buildList { + for (maskId in composite.maskedBy) { + context.puppet.drawables.firstOrNull { it.id == maskId }?.let { masker -> + add(MaskEntry.OfDrawable(masker.id, masker.name.ifBlank { masker.id.raw })) + } + } + for (maskPartId in composite.maskedByParts) { + context.puppet.parts.firstOrNull { it.id == maskPartId }?.let { masker -> + add(MaskEntry.OfPart(masker.id, masker.name.ifBlank { masker.id.raw })) + } + } + } + val candidates = + buildList { + for (candidate in maskCandidates(context.puppet.drawables, composite.maskedBy)) { + add(MaskEntry.OfDrawable(candidate.id, candidate.name.ifBlank { candidate.id.raw })) + } + // A part cannot mask itself (it would clip the very layer it composites). + for (candidate in context.puppet.parts) { + if (candidate.id != part.id && candidate.id !in composite.maskedByParts) { + add(MaskEntry.OfPart(candidate.id, candidate.name.ifBlank { candidate.id.raw })) + } + } + } + val addEntry: (MaskEntry) -> Unit = { entry -> + when (entry) { + is MaskEntry.OfDrawable -> mutateComposite { copy(maskedBy = (maskedBy + entry.id).distinct()) } + // A part masking itself would clip the very layer it composites; the candidate list excludes it, + // and the eyedropper has to refuse it too or the outliner becomes a way around the guard. + is MaskEntry.OfPart -> if (entry.id != part.id) mutateComposite { copy(maskedByParts = (maskedByParts + entry.id).distinct()) } + } + } + + val viewState = LocalPropertiesViewState.current + RelationListBlock( + stringResource(Res.string.properties_field_masked_by), + description = stringResource(Res.string.properties_field_masked_by_part_description), + ) { + RelationListField( + entries = entries, + candidates = candidates, + label = { entry -> entry.name }, + keyOf = { entry -> entry.key() }, + icon = { entry -> entry.glyph() }, + onAdd = addEntry, + onRemove = { entry -> + when (entry) { + is MaskEntry.OfDrawable -> mutateComposite { copy(maskedBy = maskedBy - entry.id) } + is MaskEntry.OfPart -> mutateComposite { copy(maskedByParts = maskedByParts - entry.id) } + } + }, + modifier = Modifier.fillMaxWidth(), + height = viewState?.listHeights?.get(MASKED_BY_LIST_NAME), + onHeightChange = { dragged -> viewState?.listHeights?.set(MASKED_BY_LIST_NAME, dragged) }, + onPick = { + relationPick.arm(setOf(PickKind.Drawable, PickKind.Part), owner) { target -> + when (target) { + is SelectionTarget.Drawable -> addEntry(MaskEntry.OfDrawable(target.id, target.id.raw)) + is SelectionTarget.Part -> addEntry(MaskEntry.OfPart(target.id, target.id.raw)) + is SelectionTarget.Deformer -> {} + } + } + }, + picking = relationPick.pickingFor(owner), + addPlaceholder = stringResource(Res.string.properties_mask_add), + removeDescription = stringResource(Res.string.properties_mask_remove), + pickDescription = stringResource(Res.string.properties_relation_pick), + ) + } +} + +/** + * A drawable's own clip-mask editor, the same list over [org.umamo.runtime.model.Drawable.maskedBy]. Only + * drawables may clip a drawable (the part extension applies to the composite layer alone), and a drawable + * may not mask itself. + * + * @param Drawable drawable The drawable whose masks are edited. + * @param PropertyContext context The context supplying the model and session. + */ +@Composable +internal fun DrawableMaskEditor(drawable: Drawable, context: PropertyContext) { + val session = context.session + val relationPick = LocalRelationPick.current + val owner = "drawable.maskedBy:${drawable.id.raw}" + val entries = drawable.maskedBy.mapNotNull { maskId -> context.puppet.drawables.firstOrNull { it.id == maskId } } + val candidates = maskCandidates(context.puppet.drawables, drawable.maskedBy).filterNot { it.id == drawable.id } + // Live read for the same reason as PartMaskEditor's mutateComposite: an armed pick resolves later, and + // the captured list would revert any mask added in the meantime. + val addMask: (DrawableId) -> Unit = { maskId -> + val live = session?.model?.value?.drawables?.firstOrNull { it.id == drawable.id }?.maskedBy + if (live != null) { + session.setDrawableMaskedBy(drawable.id, (live + maskId).distinct()) + } + } + + val viewState = LocalPropertiesViewState.current + RelationListBlock( + stringResource(Res.string.properties_field_masked_by), + description = stringResource(Res.string.properties_field_masked_by_description), + ) { + RelationListField( + entries = entries, + candidates = candidates, + label = { masker -> masker.name.ifBlank { masker.id.raw } }, + keyOf = { masker -> masker.id }, + icon = { LocalUmamoIcons.mesh }, + onAdd = { masker -> addMask(masker.id) }, + onRemove = { masker -> session?.setDrawableMaskedBy(drawable.id, drawable.maskedBy - masker.id) }, + modifier = Modifier.fillMaxWidth(), + height = viewState?.listHeights?.get(MASKED_BY_LIST_NAME), + onHeightChange = { dragged -> viewState?.listHeights?.set(MASKED_BY_LIST_NAME, dragged) }, + onPick = { + relationPick.arm(setOf(PickKind.Drawable), owner) { target -> + (target as? SelectionTarget.Drawable)?.let { picked -> + if (picked.id != drawable.id) { + addMask(picked.id) + } + } + } + }, + picking = relationPick.pickingFor(owner), + addPlaceholder = stringResource(Res.string.properties_mask_add), + removeDescription = stringResource(Res.string.properties_mask_remove), + pickDescription = stringResource(Res.string.properties_relation_pick), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/ObjectTabSections.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/ObjectTabSections.kt new file mode 100644 index 0000000..6312cc7 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/ObjectTabSections.kt @@ -0,0 +1,373 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.MeshBounds +import org.umamo.edit.Pose +import org.umamo.edit.moveDeformer +import org.umamo.edit.moveOrgChild +import org.umamo.edit.setDeformerBaseAngle +import org.umamo.edit.setDeformerPart +import org.umamo.edit.setDrawableParentDeformer +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.deformerSelfAndDescendants +import org.umamo.runtime.model.originRelativeX +import org.umamo.runtime.model.originRelativeZ +import org.umamo.runtime.model.parentPartByPart +import org.umamo.runtime.model.partByDrawable +import org.umamo.runtime.model.partSelfAndDescendants +import org.umamo.runtime.model.worldXFromOriginRelative +import org.umamo.runtime.model.worldZFromOriginRelative +import org.umamo.ui.kit.FieldStack +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.transform.drawableWorldTransform +import org.umamo.ui.transform.setDrawableWorldCenter +import org.umamo.ui.transform.setDrawableWorldSize + +/* + * The Object tab's sections: the universal properties of whatever single item is active - where it sits and + * what it is bound to - as opposed to the type-specific data in DataTabSections.kt. + */ + +/** + * Object > Transform: the active item's placement. A drawable has no scalar transform - its placement IS + * its geometry - so the rows measure its WORLD bounds and write back through the deformer chain (see + * DrawableWorldTransform.kt for why world, and not the raw base mesh array). + * + * Axes are labelled by the DISPLAYED convention (Y+ forward, Z+ up), so the vertical field is Z and maps to + * world y, which grows upward - the same naming the G / S / R axis lock uses. + * + * An item with no transform to show (a Part, a warp deformer, a mesh-less drawable) contributes NO rows, + * and sectionVisibility then hides the whole section rather than drawing an empty card. + */ +internal val TransformSection = + PropertySection( + id = "object.transform", + title = Res.string.properties_section_transform, + rows = { context -> + val drawable = context.activeDrawable() + val deformer = context.activeDeformer() + val session = context.session + val mesh = drawable?.mesh + if (drawable != null && mesh != null && mesh.vertexCount > 0) { + listOf( + PropertyRow( + terms = listOf(Res.string.properties_field_position_x, Res.string.properties_field_position_z), + ) { rowContext -> + DrawableTransformRows(rowContext, drawable.id, showSize = false) + }, + PropertyRow( + terms = listOf(Res.string.properties_field_size_x, Res.string.properties_field_size_z), + ) { rowContext -> + DrawableTransformRows(rowContext, drawable.id, showSize = true) + }, + ) + } else if (deformer is Deformer.Rotation) { + listOf( + PropertyRow(terms = listOf(Res.string.properties_field_base_angle)) { _ -> + PropertyFieldRow( + stringResource(Res.string.properties_field_base_angle), + description = stringResource(Res.string.properties_field_base_angle_description), + ) { + NumberField( + value = deformer.baseAngle, + onValueChange = { newAngle -> session?.setDeformerBaseAngle(deformer.id, newAngle) }, + modifier = Modifier.fillMaxWidth(), + range = UNBOUNDED_RANGE, + decimals = 1, + unitSuffix = stringResource(Res.string.unit_degrees), + ) + } + }, + ) + } else { + // Nothing transformable: contribute no rows so the section hides entirely (see the docblock). + emptyList() + } + }, + ) + +/** + * One of the two drawable Transform rows - Position X/Z, or Size X/Z with its aspect lock. + * + * Both live in one composable because both need the same two things resolved IN the composition: the live + * pose (so the fields disable the moment a parameter leaves its default) and the world bounds derived from + * it. The section's rows() lambda cannot do that - it is not composable, and it only re-runs when the + * MODEL changes, so a pose scrub would never reach it. + * + * While the pose is off neutral the fields show the current world numbers but are inert: the write path + * inverts through the deformer chain, which is exact only at the neutral pose, so this is the panel's face + * of the same guard that blocks a viewport object transform on a posed rig. + * + * Position reads from the world axes, so it converts at this boundary: shown values subtract the world + * origin, and an edited value adds it back. Only the edited axis converts - the other passes its world + * value through untouched, because a subtract-then-add can land one float step off and record a spurious + * move on an axis nobody edited. Size is a difference and needs no conversion. + * + * @param PropertyContext context The row's context (its session supplies the live pose). + * @param DrawableId drawableId The active drawable. + * @param Boolean showSize False for the Position pair, true for the Size pair. + */ +@Composable +private fun DrawableTransformRows(context: PropertyContext, drawableId: DrawableId, showSize: Boolean) { + val session = context.session + // Collected, not read: the pose changes without the model changing, and the disabled state tracks it. + val pose: Pose = session?.pose?.collectAsState()?.value ?: emptyMap() + // Keyed, because this is a full posed evaluation of the drawable's deformer chain - not something to + // redo when an unrelated recomposition happens to sweep the panel. (Both Transform rows still evaluate + // once each when the model or pose genuinely changes; sharing one evaluation across them would mean + // merging them into a single row and giving up per-row search.) + val transform = + remember(context.puppet, pose, drawableId) { + drawableWorldTransform(context.puppet, pose, drawableId) + } ?: return + val bounds = transform.bounds + val editable = session != null && transform.editable + if (showSize) { + SizeFieldsWithAspectLock(bounds, editable) { newWidth, newHeight -> + session?.setDrawableWorldSize(drawableId, newWidth, newHeight) + } + } else { + val puppet = context.puppet + FieldStack( + listOf( + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_position_x), + description = stringResource(Res.string.properties_field_position_x_description), + ) { + NumberField( + value = puppet.originRelativeX(bounds.centerX), + onValueChange = { newX -> + session?.setDrawableWorldCenter(drawableId, puppet.worldXFromOriginRelative(newX), bounds.centerY) + }, + modifier = Modifier.fillMaxWidth(), + range = UNBOUNDED_RANGE, + decimals = 1, + enabled = editable, + stackPosition = position, + ) + } + }, + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_position_z), + description = stringResource(Res.string.properties_field_position_z_description), + ) { + NumberField( + value = puppet.originRelativeZ(bounds.centerY), + onValueChange = { newZ -> + session?.setDrawableWorldCenter(drawableId, bounds.centerX, puppet.worldZFromOriginRelative(newZ)) + }, + modifier = Modifier.fillMaxWidth(), + range = UNBOUNDED_RANGE, + decimals = 1, + enabled = editable, + stackPosition = position, + ) + } + }, + ), + ) + } +} + +/** + * The Size X / Size Z stack plus its aspect-ratio lock. Its own composable rather than an inline pair of + * rows because the lock is stateful and the two fields are coupled through it: while locked, editing one + * axis scales the other by the same factor, so the mesh keeps its proportions. + * + * The lock is transient UI state (a tool preference, not document data), so it lives in a remember and + * resets when the panel unmounts. The ratio is read from the CURRENT bounds at commit time rather than + * captured when the lock was engaged, so it always reflects what the fields are showing. + * + * A degenerate axis (zero extent) has no ratio to preserve, so a locked edit against one falls back to + * changing only the edited axis - and [resizedAboutBoundsCenter] then leaves the degenerate one alone. + * + * @param MeshBounds bounds The active drawable's current world bounds (the displayed extents). + * @param Boolean enabled Whether the fields and the lock accept input (false on a posed rig). + * @param Function onResize Commits new (width, height) extents as one undo step. + */ +@Composable +private fun SizeFieldsWithAspectLock(bounds: MeshBounds, enabled: Boolean, onResize: (Float, Float) -> Unit) { + var lockAspect by remember { mutableStateOf(false) } + val icons = LocalUmamoIcons + // A locked edit on one axis derives the other from the ratio the mesh currently has. + val commitWidth: (Float) -> Unit = { newWidth -> + val scaledHeight = + if (lockAspect && bounds.width > 0f) { + bounds.height * (newWidth / bounds.width) + } else { + bounds.height + } + onResize(newWidth, scaledHeight) + } + val commitHeight: (Float) -> Unit = { newHeight -> + val scaledWidth = + if (lockAspect && bounds.height > 0f) { + bounds.width * (newHeight / bounds.height) + } else { + bounds.width + } + onResize(scaledWidth, newHeight) + } + // The lock overlays the gutter the rows reserve, so the fields shrink by exactly the lock's width while + // the label column keeps its half of the FULL row width - that is what keeps these rows lined up with + // the Position rows above. + Box(modifier = Modifier.fillMaxWidth()) { + FieldStack( + listOf( + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_size_x), + description = stringResource(Res.string.properties_field_size_x_description), + trailingGutter = ASPECT_LOCK_GUTTER, + ) { + NumberField( + value = bounds.width, + onValueChange = commitWidth, + modifier = Modifier.fillMaxWidth(), + range = DRAWABLE_EXTENT_RANGE, + decimals = 1, + enabled = enabled, + stackPosition = position, + ) + } + }, + { position -> + PropertyFieldRow( + stringResource(Res.string.properties_field_size_z), + description = stringResource(Res.string.properties_field_size_z_description), + trailingGutter = ASPECT_LOCK_GUTTER, + ) { + NumberField( + value = bounds.height, + onValueChange = commitHeight, + modifier = Modifier.fillMaxWidth(), + range = DRAWABLE_EXTENT_RANGE, + decimals = 1, + enabled = enabled, + stackPosition = position, + ) + } + }, + ), + ) + // The chain glyph spans both fields. IconButton tooltips itself from contentDescription, and its own + // modifier already rides on that tooltip wrapper, so the alignment goes here rather than into a second + // enclosing Tooltip. + IconButton( + icon = if (lockAspect) icons.linked else icons.unlinked, + contentDescription = stringResource(Res.string.properties_transform_lock_aspect), + onClick = { lockAspect = !lockAspect }, + modifier = Modifier.align(Alignment.CenterEnd), + active = lockAspect, + enabled = enabled, + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + } +} + +/** Object > Relations: owning part, parent deformer, masks / children of the active item. */ +internal val RelationsSection = + PropertySection( + id = "object.relations", + title = Res.string.properties_section_relations, + rows = { context -> + val drawable = context.activeDrawable() + val deformer = context.activeDeformer() + val part = context.activePart() + val session = context.session + if (drawable != null) { + listOf( + PropertyRow(terms = listOf(Res.string.properties_part_ref)) { _ -> + // Part membership lives only in the org tree, so re-homing a drawable is a tree move. + // Note it appends at the destination, which changes draw order (Cubism does the same). + PartRelationRow( + labelRes = Res.string.properties_part_ref, + descriptionRes = Res.string.properties_part_ref_description, + context = context, + selectedPartId = context.puppet.partByDrawable()[drawable.id], + owner = "drawable.part:${drawable.id.raw}", + ) { partId -> session?.moveOrgChild(OrgChild.Drawable(drawable.id), partId, null) } + }, + PropertyRow(terms = listOf(Res.string.properties_parent_deformer)) { _ -> + DeformerRelationRow( + labelRes = Res.string.properties_parent_deformer, + descriptionRes = Res.string.properties_parent_deformer_description, + context = context, + selectedDeformerId = drawable.parentDeformerId, + owner = "drawable.parentDeformer:${drawable.id.raw}", + ) { deformerId -> session?.setDrawableParentDeformer(drawable.id, deformerId) } + }, + ) + } else if (deformer != null) { + // Computed once for the row rather than per candidate, so filtering the list stays linear. + val cyclicParents = context.puppet.deformerSelfAndDescendants(deformer.id) + listOf( + PropertyRow(terms = listOf(Res.string.properties_part_ref)) { _ -> + PartRelationRow( + labelRes = Res.string.properties_part_ref, + descriptionRes = Res.string.properties_part_ref_description, + context = context, + selectedPartId = deformer.partId, + owner = "deformer.part:${deformer.id.raw}", + ) { partId -> session?.setDeformerPart(deformer.id, partId) } + }, + PropertyRow(terms = listOf(Res.string.properties_parent_deformer)) { _ -> + DeformerRelationRow( + labelRes = Res.string.properties_parent_deformer, + descriptionRes = Res.string.properties_parent_deformer_description, + context = context, + selectedDeformerId = deformer.parent, + // Nesting a deformer inside its own subtree would make the hierarchy a cycle, so + // those candidates are dropped rather than offered and then silently refused by + // withDeformerMoved. Same query the move guard uses, so the two cannot disagree. + excluding = { candidate -> candidate.id in cyclicParents }, + owner = "deformer.parent:${deformer.id.raw}", + ) { parentId -> session?.moveDeformer(deformer.id, parentId, null) } + }, + ) + } else if (part != null) { + // A part nested under another part shows (and can rebind) its owner; a top-level part reads + // as unbound, and clearing the field moves it back out to the root. + val parentOf = context.puppet.parentPartByPart() + // Computed once for the row, not per candidate: withOrgChildMoved refuses a move into this set + // anyway, and filtering on the same query keeps an illegal target out of the list entirely. + val cyclicOwners = context.puppet.partSelfAndDescendants(part.id) + listOf( + PropertyRow(terms = listOf(Res.string.properties_part_ref)) { _ -> + PartRelationRow( + labelRes = Res.string.properties_part_ref, + descriptionRes = Res.string.properties_part_ref_description, + context = context, + selectedPartId = parentOf[part.id], + excluding = { candidate -> candidate.id in cyclicOwners }, + owner = "part.parent:${part.id.raw}", + ) { parentId -> session?.moveOrgChild(OrgChild.Part(part.id), parentId, null) } + }, + ) + } else { + emptyList() + } + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertiesViewState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertiesViewState.kt new file mode 100644 index 0000000..4f98b49 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertiesViewState.kt @@ -0,0 +1,98 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.finiteFloatOf +import org.umamo.ui.workspace.stringArrayOrNull +import org.umamo.ui.workspace.stringListOf +import org.umamo.ui.workspace.stringOf + +/** The AreaScope.spaceState key the Properties panel parks its view state under, and its member in an area block (UMA §7.3). */ +internal const val PROPERTIES_VIEW_STATE_KEY = "properties" + +/** + * The Properties panel's per-area view state, shared between its header search box and its body (they + * render as sibling subtrees, so this lives on the hosting AreaScope via spaceState rather than a + * body-local remember). Two Properties areas each get their own instance, and the instance lives as long as + * the open document does. A saved document carries the tab, the folded sections, and the relation lists' + * heights (UMA §7.3), and not the search query. + */ +internal class PropertiesViewState : PersistentSpaceState { + /** The header search query; blank shows every section. */ + var query by mutableStateOf("") + + /** The tab the user last selected; clamped to a visible tab at render time. */ + var activeTab by mutableStateOf(PropertyTabId.Document) + + /** + * Per-section expanded state, keyed by section id. An absent entry defaults to expanded, so a fresh + * panel opens with everything unfolded; the map only records deviations the user toggled. + */ + val expandedSections = mutableStateMapOf() + + /** + * Each relation list's dragged height, keyed by the list's name ("maskedBy"). Held here rather than in the + * list because the list leaves the composition on every tab change, section fold, and selection change, and + * a height that reset each time would not be worth dragging. An absent entry is the list's default. + */ + val listHeights = mutableStateMapOf() + + /** + * The Properties panel's member of its area block. + * + * @return JsonObject The member, every known key named. + */ + override fun toJson(): JsonObject = + buildJsonObject { + put("tab", if (activeTab == PropertyTabId.Document) JsonNull else JsonPrimitive(propertyTabWireName(activeTab))) + put("collapsedSections", stringArrayOrNull(expandedSections.filterValues { open -> !open }.keys)) + // UMA §7.3: keyed by a fixed list name, not an object id, so an object is safe under the merge (UMA §7.5). + // A null for the whole member clears every height at once when none is held. + put("listHeights", if (listHeights.isEmpty()) JsonNull else buildJsonObject { listHeights.keys.sorted().forEach { listName -> put(listName, JsonPrimitive(listHeights.getValue(listName).value)) } }) + } + + /** + * Takes the Properties state a document was saved with. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + activeTab = stringOf(tree, "tab")?.let { wireName -> PropertyTabId.entries.firstOrNull { tab -> propertyTabWireName(tab) == wireName } } ?: PropertyTabId.Document + expandedSections.clear() + stringListOf(tree, "collapsedSections")?.forEach { sectionId -> expandedSections[sectionId] = false } + listHeights.clear() + (tree["listHeights"] as? JsonObject)?.forEach { (listName, height) -> + finiteFloatOf(height)?.takeIf { value -> value > 0f }?.let { value -> listHeights[listName] = value.dp } + } + } +} + +/** + * The view state of the Properties area a row is rendering in, or null outside one (previews, tests), where a row + * keeps such state to itself. + */ +internal val LocalPropertiesViewState = compositionLocalOf { null } + +/** + * A Properties tab's name in the editor entry. + * + * @param PropertyTabId tab The tab. + * @return String The wire name. + */ +internal fun propertyTabWireName(tab: PropertyTabId): String = + // UMA §7.3: properties `tab`. + when (tab) { + PropertyTabId.Document -> "document" + PropertyTabId.Object -> "object" + PropertyTabId.Data -> "data" + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyModel.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyModel.kt new file mode 100644 index 0000000..d370978 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyModel.kt @@ -0,0 +1,130 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.StringResource +import org.umamo.edit.EditorSession +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.theme.UmamoIcon + +/** + * The immutable snapshot a property tab and its sections read from. Rebuilt each recomposition from the + * composition locals ([org.umamo.ui.model.LocalPuppet] / [org.umamo.ui.model.LocalSelection]) so sections + * stay declarative - they render a function of this context rather than collecting their own flows. + * + * @property PuppetModel puppet The open document's model (never null - the space guards on it first). + * @property Selection selection The current object-mode selection. + * @property SelectionTarget? activeTarget The single active item that drives the per-item tabs, or null + * when nothing is selected or several items are (per-item tabs need one focused item). + * @property EditorSession? session The editing session an editable control writes through, or null when + * no document is open (the controls then render disabled / inert). Rebuilt from the composition local + * each recomposition alongside the read-only fields. + */ +class PropertyContext( + val puppet: PuppetModel, + val selection: Selection, + val activeTarget: SelectionTarget?, + val session: EditorSession?, +) + +/** + * The active target as a [Drawable], resolved against the model, or null when the active target is not a + * drawable (or no longer exists in the model). + * + * @return Drawable? The selected drawable, or null. + */ +fun PropertyContext.activeDrawable(): Drawable? { + val target = activeTarget as? SelectionTarget.Drawable ?: return null + return puppet.drawables.firstOrNull { drawable -> drawable.id == target.id } +} + +/** + * The active target as a [Deformer], resolved against the model, or null when the active target is not a + * deformer (or no longer exists in the model). + * + * @return Deformer? The selected deformer, or null. + */ +fun PropertyContext.activeDeformer(): Deformer? { + val target = activeTarget as? SelectionTarget.Deformer ?: return null + return puppet.deformers.firstOrNull { deformer -> deformer.id == target.id } +} + +/** + * The active target as a [Part], resolved against the model, or null when the active target is not a part + * (or no longer exists in the model). + * + * @return Part? The selected part, or null. + */ +fun PropertyContext.activePart(): Part? { + val target = activeTarget as? SelectionTarget.Part ?: return null + return puppet.parts.firstOrNull { part -> part.id == target.id } +} + +/** + * The stable identity of a property tab. Fixed slots for the first cut; the registry keying off this + * (rather than a hardcoded switch) is what lets the set grow without touching the render loop. + */ +enum class PropertyTabId { + /** Document-wide properties (canvas, runtime compatibility) - always shown. */ + Document, + + /** The active item's universal properties (transform, relations) - shown when one item is active. */ + Object, + + /** The active item's type-specific data - icon and sections resolve from the item's kind. */ + Data, +} + +/** + * One row within a section: the localized [terms] it exposes to the header search (its own label, plus + * any extra labels a stacked group folds in) and the [content] that draws it from a [PropertyContext]. + * A section is a list of these, so the header search can hide the individual non-matching rows rather + * than the whole section. A visually fused stack (a FieldStack) is one row whose terms cover every field + * in it, so the group stays intact under filtering. + * + * @property List terms The localized labels this row exposes to the header search (arg-free). + * @property Function content The composable that draws this one row. + */ +class PropertyRow( + val terms: List, + val content: @Composable (PropertyContext) -> Unit, +) + +/** + * One collapsible section within a tab: a localized [title] and the [rows] it draws from a + * [PropertyContext]. A section's [id] keys both its expanded/collapsed state and its search haystack, so + * it must be stable and unique across the whole catalog. The search index is the union of the rows' + * terms, so there is no separate term list to keep in sync with what the rows render. + * + * @property String id The stable, catalog-unique section key. + * @property StringResource title The localized section heading. + * @property Function rows The section's rows for the given context, top to bottom. + */ +class PropertySection( + val id: String, + val title: StringResource, + val rows: (PropertyContext) -> List, +) + +/** + * One tab in the left icon strip. [isVisible] gates whether it appears for the current context (Document + * is always visible; the per-item tabs require an active target), while [icon] and [sections] are + * functions of the context so the Data tab can adapt its glyph and rows to the selected item's type. + * + * @property PropertyTabId id The tab's stable identity. + * @property StringResource title The localized tab label (tooltip / accessibility name). + * @property Function icon The tab's glyph, resolved from the context (adaptive for the Data tab). + * @property Function isVisible Whether the tab appears for the given context. + * @property Function sections The tab's sections for the given context, top to bottom. + */ +class PropertyTab( + val id: PropertyTabId, + val title: StringResource, + val icon: (PropertyContext) -> UmamoIcon, + val isVisible: (PropertyContext) -> Boolean, + val sections: (PropertyContext) -> List, +) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyRows.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyRows.kt new file mode 100644 index 0000000..d9bfe63 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyRows.kt @@ -0,0 +1,159 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.model.KeyedFieldState +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography + +/* + * The shared row primitives every Properties section is built from: the label + control grid, the read-only + * line, the checkbox row, and the numeric ranges those controls clamp to. Sections live in the per-tab + * files beside this one; anything used by more than one of them belongs here. + */ + +/** + * One read-only "label: value" property line. + * + * @param String text The composed line text. + */ +@Composable +internal fun PropertyLine(text: String) { + Text(text = text, style = LocalUmamoTypography.current.bodySmall, modifier = Modifier.padding(top = 1.dp, bottom = 1.dp)) +} + +/** An unbounded float range: a numeric field that clamps nothing and draws no magnitude fill. */ +internal val UNBOUNDED_RANGE = Float.NEGATIVE_INFINITY..Float.POSITIVE_INFINITY + +/** A half-open float range (min set, no max): clamps below and draws no fill (needs both bounds). */ +internal val POSITIVE_RANGE = 1f..Float.POSITIVE_INFINITY + +/** + * The clamp for a drawable's world extent. Deliberately NOT [POSITIVE_RANGE]: a canvas is measured in + * whole pixels so a floor of 1 is meaningful there, but a drawable extent is in world units and can + * legitimately be a fraction - clamping it to 1 would silently double a typed 0.5. The floor is the + * smallest value the row's one-decimal display can actually show, which keeps the number in the field + * honest while still refusing the zero (collapse) and negative (mirror) cases. + */ +internal val DRAWABLE_EXTENT_RANGE = 0.1f..Float.POSITIVE_INFINITY + +/** + * Space the Size rows reserve at their right edge for the aspect lock that overlays it: the 20dp icon + * button plus a little breathing room. Keeping it a named constant is what ties the reservation and the + * overlaid control to the same width - if they drift, the lock either overlaps the field or floats away. + */ +internal val ASPECT_LOCK_GUTTER = 24.dp + +/** + * A labelled Properties field row, Blender-style: the right-aligned label takes the left half and the + * control fills the right half, so a column of rows aligns and every field spans a consistent width. The + * control should [Modifier.fillMaxWidth] so it fills its half. + * + * [description] is what the field does, shown as a tooltip over the LABEL HALF only. The control keeps its + * own hover: nested tooltip areas all fire at once, so one wrapping the whole row would stack a second card + * over the icon buttons a relation or color field tooltips itself, and it would pop over a field mid-scrub. + * + * [trailingGutter] reserves space at the RIGHT EDGE OF THE CONTROL for an adornment that sits outside the + * row (the Size stack's aspect lock). It shrinks the control only - the label column keeps its half of the + * full row width, so a row with a gutter still lines up with the plain rows above and below it. Reserving + * the space here rather than wrapping the whole row in a narrower box is the difference between the field + * shrinking and the entire two-column grid shifting. + * + * @param String label The localized field label. + * @param String description What the field does, as the label's tooltip; blank attaches none. + * @param Dp trailingGutter Space reserved after the control for an out-of-row adornment (0 for none). + * @param Modifier modifier The layout modifier, applied to the row. + * @param Function control The editable control (a fillMaxWidth NumberField, SelectField, etc.). + */ +@Composable +internal fun PropertyFieldRow( + label: String, + description: String = "", + trailingGutter: Dp = 0.dp, + modifier: Modifier = Modifier, + control: @Composable () -> Unit, +) { + Row(modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + // The whole left half is the hover target, not just the glyphs, so a short label is easy to find. + Tooltip(text = description, modifier = Modifier.weight(1f).padding(end = 8.dp)) { + Text( + text = label, + style = LocalUmamoTypography.current.bodySmall, + color = LocalUmamoColors.current.text, + textAlign = TextAlign.End, + modifier = Modifier.fillMaxWidth(), + ) + } + Box(modifier = Modifier.weight(1f).padding(end = trailingGutter)) { + control() + } + } +} + +/** + * A Properties checkbox row: the checkbox (box plus its own label) sits in the right half like every other + * field, with the left label column left empty - matching Blender, where a lone toggle occupies the field + * column. A group of related toggles can carry a left-column heading later. + * + * The checkbox's label is the row's label, so [description] tooltips the checkbox itself; it has no hover + * of its own to collide with. + * + * @param Boolean checked The current state. + * @param Function onCheckedChange The toggle callback. + * @param String label The checkbox's own label (drawn to the right of the box). + * @param String description What the toggle does, as the checkbox's tooltip; blank attaches none. + * @param KeyedFieldState keyState The keyform state to tint the box's border with. + */ +@Composable +internal fun PropertyCheckboxRow( + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + label: String, + description: String = "", + keyState: KeyedFieldState = KeyedFieldState.None, +) { + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Spacer(modifier = Modifier.weight(1f)) + Box(modifier = Modifier.weight(1f)) { + Tooltip(text = description) { + Checkbox(checked = checked, onCheckedChange = onCheckedChange, label = label, keyState = keyState) + } + } + } +} + +/** + * A labelled block wrapping a relation list, since a tall list does not fit the two-column field row. The + * [description] tooltips the label alone, for the reason [PropertyFieldRow] gives: the list's add, remove, + * and pick buttons carry tooltips of their own. + * + * @param String label The block's localized label. + * @param String description What the list does, as the label's tooltip; blank attaches none. + * @param Function content The list to draw beneath it. + */ +@Composable +internal fun RelationListBlock(label: String, description: String = "", content: @Composable () -> Unit) { + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Tooltip(text = description) { + Text(text = label, style = LocalUmamoTypography.current.bodySmall, color = LocalUmamoColors.current.text) + } + content() + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyTabRegistry.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyTabRegistry.kt new file mode 100644 index 0000000..900e6bb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/PropertyTabRegistry.kt @@ -0,0 +1,149 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.properties_tab_data +import org.umamo.ui.resources.properties_tab_document +import org.umamo.ui.resources.properties_tab_object +import org.umamo.ui.theme.LocalUmamoIcons + +/** + * The resolver from a [PropertyContext] to the tabs the Properties panel shows - the small registry that + * mirrors [org.umamo.ui.workspace.SpaceRegistry] one level down. Iterating a list (rather than a hardcoded + * switch) is what makes the tab set the extension point: the icon strip and the header search index both + * fall out of [visibleTabs]. + * + * @property List tabs The registered tabs, in strip order. + */ +class PropertyTabRegistry(private val tabs: List) { + /** + * The tabs to show for [context], in strip order - those whose visibility predicate holds. + * + * @param PropertyContext context The current context. + * @return List The visible tabs, top to bottom. + */ + fun visibleTabs(context: PropertyContext): List = tabs.filter { tab -> tab.isVisible(context) } + + /** + * The tab with the given [id], or null when none is registered under it. + * + * @param PropertyTabId id The tab identity to resolve. + * @return PropertyTab? The matching tab, or null. + */ + fun tab(id: PropertyTabId): PropertyTab? = tabs.firstOrNull { tab -> tab.id == id } + + /** + * A new registry with [extra] tabs layered over this one: an entry with an existing id replaces it in + * place (keeping strip position), a new id appends. The seam a vendor extension layers onto through + * [LocalPropertyTabRegistry] (the same shape [org.umamo.ui.workspace.SpaceRegistry.withOverrides] uses). + * + * @param List extra The overriding / additional tabs. + * @return PropertyTabRegistry The merged registry. + */ + fun withOverrides(extra: List): PropertyTabRegistry { + val overrideById = extra.associateBy { tab -> tab.id } + val replaced = tabs.map { tab -> overrideById[tab.id] ?: tab } + val appended = extra.filter { tab -> tabs.none { existing -> existing.id == tab.id } } + return PropertyTabRegistry(replaced + appended) + } +} + +/** + * Reports whether any string in [haystack] contains [query] (case-insensitive); a blank query matches + * everything. Pure so the header-search filter is unit-testable without Compose - the composable caller + * resolves each section's localized labels into the haystack, this decides the match. + * + * @param List haystack The already-resolved localized strings to test. + * @param String query The user's search text. + * @return Boolean True when the query is blank or any haystack entry contains it. + */ +fun matchesQuery(haystack: List, query: String): Boolean { + val trimmed = query.trim() + if (trimmed.isEmpty()) { + return true + } + return haystack.any { candidate -> candidate.contains(trimmed, ignoreCase = true) } +} + +/** + * Whether a section is shown for a query, and which of its rows to draw. A section that built no rows for + * the current context is never shown - it has nothing to say about the active item, and a header-only card + * is noise. Otherwise: a blank query shows the whole section; a query that matches the section [title] + * also shows every row (the whole section is relevant); otherwise only the rows whose terms match are + * shown, and the section is hidden entirely when none do. + * + * @property Boolean shown Whether the section appears at all. + * @property List visibleRowIndices The indices (into the section's row list) to draw, in order. + */ +class SectionVisibility(val shown: Boolean, val visibleRowIndices: List) + +/** + * Resolves per-row search visibility for one section from its already-localized [title] and [rowTerms] + * (one term list per row). Pure so the header-search filter is unit-testable without Compose - the + * composable caller resolves the strings, this decides which rows survive. + * + * @param String title The section's localized heading. + * @param List rowTerms Each row's localized search terms, in row order. + * @param String query The user's search text. + * @return SectionVisibility Whether the section shows and which rows to draw. + */ +fun sectionVisibility(title: String, rowTerms: List>, query: String): SectionVisibility { + // A section whose rows() returned nothing for this context has no content to show - and a title match + // must not resurrect it, or searching would surface an empty card. This is how a section opts out for + // an item it does not apply to (Transform against a Part or a warp deformer). + if (rowTerms.isEmpty()) { + return SectionVisibility(false, emptyList()) + } + val trimmed = query.trim() + val allRows = rowTerms.indices.toList() + if (trimmed.isEmpty() || matchesQuery(listOf(title), trimmed)) { + return SectionVisibility(true, allRows) + } + val matching = allRows.filter { index -> matchesQuery(rowTerms[index], trimmed) } + return SectionVisibility(matching.isNotEmpty(), matching) +} + +/** + * The base Properties tab set: the always-on Document tab plus the per-item Object and Data tabs. Object + * and Data occupy fixed slots; only the Data tab's icon and sections adapt to the active item's type (see + * [dataTabIcon] / [dataTabSections]). + * + * @return PropertyTabRegistry The base registry every Properties space starts from. + */ +fun defaultPropertyTabRegistry(): PropertyTabRegistry = + PropertyTabRegistry( + listOf( + PropertyTab( + id = PropertyTabId.Document, + title = Res.string.properties_tab_document, + icon = { LocalUmamoIcons.puppetRoot }, + isVisible = { true }, + sections = { listOf(CanvasSection, DisplaySection, RuntimeSection) }, + ), + PropertyTab( + id = PropertyTabId.Object, + title = Res.string.properties_tab_object, + icon = { LocalUmamoIcons.editorModeObject }, + isVisible = { context -> context.activeTarget != null }, + sections = { listOf(TransformSection, RelationsSection) }, + ), + PropertyTab( + id = PropertyTabId.Data, + title = Res.string.properties_tab_data, + icon = { context -> dataTabIcon(context) }, + isVisible = { context -> context.activeTarget != null }, + sections = { context -> dataTabSections(context) }, + ), + ), + ) + +/** + * The active [PropertyTabRegistry] for the composition. `static` - the registry is stable for the shell's + * lifetime; the Properties space reads `LocalPropertyTabRegistry.current` to build its tab strip and search + * index. The shell provides `defaultPropertyTabRegistry().withOverrides(...)`, so a vendor extension adds + * or replaces tabs without touching core (mirrors [org.umamo.ui.workspace.LocalSpaceRegistry]). + */ +val LocalPropertyTabRegistry = + staticCompositionLocalOf { + error("LocalPropertyTabRegistry not provided — wrap the shell in a PropertyTabRegistry provider") + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/RelationRows.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/RelationRows.kt new file mode 100644 index 0000000..c9a2a11 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/RelationRows.kt @@ -0,0 +1,128 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.ui.kit.RelationField +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.workspace.LocalRelationPick +import org.umamo.ui.workspace.PickKind +import org.umamo.ui.workspace.pickingFor + +/* + * The single-value relation rows - bind the active item to a part or to a deformer - plus the deformer type + * glyph they and the Data tab share. The multi-value lists live in MaskEditors.kt. + */ + +/** + * The type glyph for a deformer, matching the outliner's warp-versus-rotation split. + * + * @param Deformer deformer The deformer to glyph. + * @return UmamoIcon Its type icon. + */ +internal fun deformerIcon(deformer: Deformer): UmamoIcon = + when (deformer) { + is Deformer.Rotation -> LocalUmamoIcons.rotationDeformer + is Deformer.Warp -> LocalUmamoIcons.warpDeformer + } + +/** + * A labelled row binding the active item to an organizational part, through the shared relation picker: + * the field lists every part, and its eyedropper takes a part from a viewport click (resolved through the + * clicked drawable's owner) or an outliner row. + * + * @param StringResource labelRes The row's localized label. + * @param StringResource descriptionRes What the relation means, as the label's tooltip. + * @param PropertyContext context The context supplying the model. + * @param PartId? selectedPartId The currently bound part, or null when unbound. + * @param Function excluding Drops ineligible candidates (a part may not be nested inside itself). + * @param Any owner This field's identity, so only it lights its eyedropper. + * @param Function onSelect Applies the new binding (null clears it). + */ +@Composable +internal fun PartRelationRow( + labelRes: StringResource, + descriptionRes: StringResource, + context: PropertyContext, + selectedPartId: PartId?, + excluding: (Part) -> Boolean = { false }, + owner: Any, + onSelect: (PartId?) -> Unit, +) { + val relationPick = LocalRelationPick.current + val parts = context.puppet.parts.filterNot(excluding) + PropertyFieldRow(stringResource(labelRes), description = stringResource(descriptionRes)) { + RelationField( + selected = parts.firstOrNull { candidate -> candidate.id == selectedPartId }, + candidates = parts, + label = { candidate -> candidate.name.ifBlank { candidate.id.raw } }, + icon = { LocalUmamoIcons.part }, + onSelect = { candidate -> onSelect(candidate?.id) }, + modifier = Modifier.fillMaxWidth(), + onPick = { + relationPick.arm(setOf(PickKind.Part), owner) { target -> + (target as? SelectionTarget.Part)?.let { picked -> onSelect(picked.id) } + } + }, + picking = relationPick.pickingFor(owner), + clearDescription = stringResource(Res.string.properties_relation_clear), + pickDescription = stringResource(Res.string.properties_relation_pick), + ) + } +} + +/** + * A labelled row binding the active item to a deformer, through the shared relation picker. A viewport + * click cannot hit a deformer (the hit test is drawable-only), so this field's eyedropper resolves from + * the outliner. + * + * @param StringResource labelRes The row's localized label. + * @param StringResource descriptionRes What the relation means, as the label's tooltip. + * @param PropertyContext context The context supplying the model. + * @param DeformerId? selectedDeformerId The currently bound deformer, or null when unbound. + * @param Function excluding Drops ineligible candidates (a deformer may not parent itself). + * @param Any owner This field's identity, so only it lights its eyedropper. + * @param Function onSelect Applies the new binding (null clears it). + */ +@Composable +internal fun DeformerRelationRow( + labelRes: StringResource, + descriptionRes: StringResource, + context: PropertyContext, + selectedDeformerId: DeformerId?, + excluding: (Deformer) -> Boolean = { false }, + owner: Any, + onSelect: (DeformerId?) -> Unit, +) { + val relationPick = LocalRelationPick.current + val deformers = context.puppet.deformers.filterNot(excluding) + PropertyFieldRow(stringResource(labelRes), description = stringResource(descriptionRes)) { + RelationField( + selected = deformers.firstOrNull { candidate -> candidate.id == selectedDeformerId }, + candidates = deformers, + label = { candidate -> candidate.name.ifBlank { candidate.id.raw } }, + icon = { candidate -> deformerIcon(candidate) }, + onSelect = { candidate -> onSelect(candidate?.id) }, + modifier = Modifier.fillMaxWidth(), + onPick = { + relationPick.arm(setOf(PickKind.Deformer), owner) { target -> + (target as? SelectionTarget.Deformer)?.let { picked -> onSelect(picked.id) } + } + }, + picking = relationPick.pickingFor(owner), + clearDescription = stringResource(Res.string.properties_relation_clear), + pickDescription = stringResource(Res.string.properties_relation_pick), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/RuntimeGating.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/RuntimeGating.kt new file mode 100644 index 0000000..44f25df --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/properties/RuntimeGating.kt @@ -0,0 +1,75 @@ +package org.umamo.ui.properties + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.runtime.model.RuntimeTarget + +/* + * Pure option filters and row predicates for runtime-target gating, kept Compose-free so + * PropertyTabRegistryTest-style unit tests cover them directly. The gating contract: an option + * list filters to the supported values PLUS the current value (an unsupported stored value never + * vanishes from its own control, so nothing breaks), while whole-feature blocks hide entirely at + * their section site. + */ + +/** + * The blend-mode dropdown options under [target]: the full display order when the 5.3 blend-mode + * family is supported, else the legacy modes plus [current], preserving display-order positions. + * + * @param RuntimeTarget target The document's runtime target. + * @param BlendMode current The control's current value, kept selectable even when unsupported. + * @return List The options the dropdown should present. + */ +fun blendModeOptionsFor(target: RuntimeTarget, current: BlendMode): List { + if (target.supports(RuntimeFeature.ExtendedBlendModes)) { + return blendModeDisplayOrder() + } + return blendModeDisplayOrder().filter { mode -> mode.isLegacy || mode == current } +} + +/** + * The group-mode dropdown options under [target]: all three kinds when offscreen drawing is + * supported, else Isolated only while it is [current]. + * + * @param RuntimeTarget target The document's runtime target. + * @param PartGroupModeKind current The control's current value, kept selectable even when unsupported. + * @return List The options the dropdown should present. + */ +fun partGroupModeOptionsFor(target: RuntimeTarget, current: PartGroupModeKind): List { + if (target.supports(RuntimeFeature.PartComposite)) { + return PartGroupModeKind.entries + } + return PartGroupModeKind.entries.filter { kind -> kind != PartGroupModeKind.Isolated || kind == current } +} + +/** + * Whether the alpha-composition row shows: the blend mode must not ignore alpha, AND either the + * target supports the 5.3 blend-mode family the alpha modes belong to or [currentAlpha] already + * holds an out-of-target value - a stored value never vanishes from its own control, so the rigger + * can still see it and reset it to Over. + * + * @param RuntimeTarget target The document's runtime target. + * @param BlendMode blendMode The owning control's current blend mode. + * @param AlphaBlendMode currentAlpha The control's current alpha mode. + * @return Boolean True when the alpha row should render. + */ +fun showsAlphaBlendRow(target: RuntimeTarget, blendMode: BlendMode, currentAlpha: AlphaBlendMode): Boolean = + !blendMode.ignoresAlphaBlend && + (target.supports(RuntimeFeature.ExtendedBlendModes) || currentAlpha != AlphaBlendMode.Over) + +/** + * The alpha-composition dropdown options under [target]: the full list when the 5.3 blend-mode + * family is supported, else Over (the pre-5.3 behavior) plus [current], so an out-of-target stored + * value stays visible and the only forward move is back to Over. + * + * @param RuntimeTarget target The document's runtime target. + * @param AlphaBlendMode current The control's current value, kept selectable even when unsupported. + * @return List The options the dropdown should present. + */ +fun alphaBlendModeOptionsFor(target: RuntimeTarget, current: AlphaBlendMode): List { + if (target.supports(RuntimeFeature.ExtendedBlendModes)) { + return AlphaBlendMode.entries + } + return AlphaBlendMode.entries.filter { mode -> mode == AlphaBlendMode.Over || mode == current } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/HistorySettings.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/HistorySettings.kt new file mode 100644 index 0000000..5e9d416 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/HistorySettings.kt @@ -0,0 +1,28 @@ +package org.umamo.ui.settings + +import org.umamo.edit.DEFAULT_HISTORY_LIMIT + +/** + * The settings key, bundled default, and commit clamp for the undo-history cap. The same split as + * [org.umamo.ui.viewport.ViewportSettings]: the preferences row and the shell's session wiring both read + * these constants, so neither duplicates the key literal. + * + * The cap is applied by writing [org.umamo.edit.EditorSession.historyLimit]; :edit holds no settings + * dependency (it is the platform-neutral editing core), so the value is always pushed in from here. + */ +internal object HistorySettings { + const val HISTORY_LIMIT_KEY = "interface.historyLimit" + + /** + * The fallback for a missing or unparseable value, kept in lockstep with defaultSettings.json. Taken + * from :edit's own constant so the number itself lives in exactly one Kotlin place. + */ + const val HISTORY_LIMIT_DEFAULT = DEFAULT_HISTORY_LIMIT + + /** + * The commit clamp: at least one retained step (the stack always keeps the live state), up to 1000. + * The ceiling can be generous because snapshots structurally share their unchanged sub-trees - a step + * costs what that edit actually changed, not a copy of the document. + */ + val HISTORY_LIMIT_RANGE = 1..1000 +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/KeybindingsEditor.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/KeybindingsEditor.kt new file mode 100644 index 0000000..45a49ed --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/KeybindingsEditor.kt @@ -0,0 +1,385 @@ +package org.umamo.ui.settings + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isAltPressed +import androidx.compose.ui.input.key.isCtrlPressed +import androidx.compose.ui.input.key.isMetaPressed +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.LocalSettings +import org.umamo.ui.action.KEYMAP_PRESET_IDS +import org.umamo.ui.action.KEYMAP_PRESET_KEY +import org.umamo.ui.action.KeyChord +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.action.keyName +import org.umamo.ui.action.rebindCommand +import org.umamo.ui.action.resetKeymapOverrides +import org.umamo.ui.action.unbindCommand +import org.umamo.ui.kit.LocalKeyCapture +import org.umamo.ui.kit.SCROLLBAR_THICKNESS +import org.umamo.ui.kit.SelectField +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.kit.button.Button +import org.umamo.ui.rememberStringSetting +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.settings_keybindings_clear +import org.umamo.ui.resources.settings_keybindings_conflict +import org.umamo.ui.resources.settings_keybindings_preset +import org.umamo.ui.resources.settings_keybindings_preset_quick +import org.umamo.ui.resources.settings_keybindings_press_shortcut +import org.umamo.ui.resources.settings_keybindings_reassign +import org.umamo.ui.resources.settings_keybindings_reset +import org.umamo.ui.resources.settings_keybindings_unbound +import org.umamo.ui.resources.settings_keymap_preset_blender +import org.umamo.ui.resources.settings_keymap_preset_cubism +import org.umamo.ui.resources.settings_keymap_preset_default +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.workspace.ConfirmRequest + +/** A captured chord that collides with another command, held until its reassign prompt is raised in the shell. */ +private data class KeybindingConflict(val commandId: String, val chord: KeyChord, val existingCommandId: String) + +/** Stable chip width so the chord column lines up; the "press a shortcut" prompt is the widest label. */ +private val CHORD_CHIP_MIN_WIDTH = 148.dp + +/** + * The keymap preset row, bound write-through to input.keybinding.preset: the keybindings editor and Quick + * Setup share it. A switch keeps the user's per-command overrides, which layer on whichever preset is chosen. + * + * @param Function onSelect Called after a preset is picked, for the host's own bookkeeping. + */ +@Composable +internal fun KeymapPresetSettingRow(onSelect: () -> Unit = {}, quick: Boolean = false) { + var preset by rememberStringSetting(KEYMAP_PRESET_KEY, "default") + // Preset display names are localized chrome; the ids stay stable (see KEYMAP_PRESET_IDS). + val presetLabels = + linkedMapOf( + "default" to stringResource(Res.string.settings_keymap_preset_default), + "cubism" to stringResource(Res.string.settings_keymap_preset_cubism), + "blender" to stringResource(Res.string.settings_keymap_preset_blender), + ) + SettingRow(label = stringResource(if (quick) Res.string.settings_keybindings_preset_quick else Res.string.settings_keybindings_preset)) { + SelectField( + selected = preset, + options = KEYMAP_PRESET_IDS, + label = { presetId -> presetLabels[presetId] ?: presetId }, + onSelect = { presetId -> + preset = presetId + onSelect() + }, + ) + } +} + +/** + * The keybindings editor: pick a preset, then rebind individual commands. The preset dropdown and every + * rebind write through settings (input.keybinding.preset / .overrides) and the shell re-resolves the live + * [LocalKeymap] reactively, so a change takes effect across menus, the palette, and dispatch immediately. + * + * Only titled commands appear (an untitled command is an internal action with no user-facing label); each + * row shows the command, its current chord (or "unbound"), and a clear button. Clicking the chord captures + * the next key combination; if it is already bound elsewhere a confirm prompt offers to reassign it. Reset + * clears all user overrides back to the selected preset. + * + * キーバインド編集。プリセット選択と個別コマンドの再割り当て。変更は設定に書き込まれ、キーマップは即時反映される。 + */ +@Composable +internal fun KeybindingsEditor() { + val settings = LocalSettings.current + val commands = LocalCommands.current + val keymap = LocalKeymap.current + var capturingCommandId by remember { mutableStateOf(null) } + var pendingConflict by remember { mutableStateOf(null) } + + Box(modifier = Modifier.fillMaxSize()) { + Column(modifier = Modifier.fillMaxSize()) { + KeymapPresetSettingRow(onSelect = { capturingCommandId = null }) + Spacer(modifier = Modifier.height(SETTING_ROW_SPACING)) + Row(modifier = Modifier.fillMaxWidth()) { + Button( + label = stringResource(Res.string.settings_keybindings_reset), + onClick = { + resetKeymapOverrides(settings) + capturingCommandId = null + }, + primary = false, + ) + } + Spacer(modifier = Modifier.height(SETTING_ROW_SPACING)) + Box(modifier = Modifier.fillMaxWidth().weight(1f)) { + val scrollState = rememberScrollState() + // The scrollbar is overlaid on this column's trailing edge, so the rows reserve its width + // or the clear button on every row sits underneath the bar. + Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState).padding(end = SCROLLBAR_THICKNESS)) { + for (command in commands.all()) { + val titleResource = command.title ?: continue + KeybindingRow( + title = stringResource(titleResource), + chord = keymap.chordFor(command.id), + capturing = capturingCommandId == command.id, + onStartCapture = { capturingCommandId = command.id }, + onCancelCapture = { capturingCommandId = null }, + onClear = { + unbindCommand(settings, command.id) + capturingCommandId = null + }, + onCaptured = { captured -> + capturingCommandId = null + val existingCommandId = keymap.commandFor(captured) + if (existingCommandId != null && existingCommandId != command.id) { + pendingConflict = KeybindingConflict(command.id, captured, existingCommandId) + } else { + rebindCommand(settings, command.id, captured) + } + }, + ) + } + } + VerticalScrollbarOverlay(scrollState) + } + } + pendingConflict?.let { conflict -> + val existingTitle = + commands[conflict.existingCommandId]?.title?.let { titleResource -> stringResource(titleResource) } + ?: conflict.existingCommandId + val chordLabel = formatAccelerator(conflict.chord) + // The prompt goes through the shell's one confirm slot rather than a dialog of its own, so Enter + // reassigns and Escape cancels it: a dialog drawn here sits outside the shell's key ladder, where + // Escape falls to the Preferences overlay and closes it behind the prompt. The strings resolve + // here, where composition can read them, and the conflict clears once handed over. + LaunchedEffect(conflict) { + commands.invoke( + "document.confirm", + ConfirmRequest( + message = Res.string.settings_keybindings_conflict, + arguments = listOf(chordLabel, existingTitle), + confirmLabel = Res.string.settings_keybindings_reassign, + ) { rebindCommand(settings, conflict.commandId, conflict.chord) }, + ) + pendingConflict = null + } + } + } +} + +/** + * One command row: the command name, its chord chip, and a clear button. + * + * @param String title The command's localized display name. + * @param KeyChord? chord The currently bound chord, or null when unbound. + * @param Boolean capturing Whether this row is capturing a new chord. + * @param Function onStartCapture Begins capture for this row. + * @param Function onCancelCapture Ends capture without binding. + * @param Function onClear Unbinds the command. + * @param Function onCaptured Receives a captured chord to bind. + */ +@Composable +private fun KeybindingRow( + title: String, + chord: KeyChord?, + capturing: Boolean, + onStartCapture: () -> Unit, + onCancelCapture: () -> Unit, + onClear: () -> Unit, + onCaptured: (KeyChord) -> Unit, +) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + Row(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { + Text(text = title, style = typography.bodyMedium, color = colors.text, modifier = Modifier.weight(1f)) + ChordChip( + chord = chord, + capturing = capturing, + onStartCapture = onStartCapture, + onCancelCapture = onCancelCapture, + onCaptured = onCaptured, + ) + Spacer(modifier = Modifier.width(8.dp)) + ClearButton(enabled = chord != null && !capturing, onClick = onClear) + } +} + +/** + * The clickable chord chip: shows the current accelerator (or "unbound"), and while capturing becomes a + * focused key sink that turns the next key combination into a chord (bare Escape cancels capture). + * + * Two things keep that true inside the shell. The capture is announced on [LocalKeyCapture], because the shell's + * root handler previews every key before this chip sees it and would otherwise take Escape to close Preferences. + * And the chip keeps ONE focus node whether it is capturing or not: a focus node that left the composition when + * the capture ended would leave focus on nothing, and with nothing focused no key reaches the shell at all - the + * reassign prompt a taken chord raises would answer to neither Enter nor Escape. + * + * @param KeyChord? chord The currently bound chord, or null. + * @param Boolean capturing Whether this chip is capturing. + * @param Function onStartCapture Begins capture (chip click). + * @param Function onCancelCapture Ends capture without binding. + * @param Function onCaptured Receives a captured chord. + */ +@Composable +private fun ChordChip( + chord: KeyChord?, + capturing: Boolean, + onStartCapture: () -> Unit, + onCancelCapture: () -> Unit, + onCaptured: (KeyChord) -> Unit, +) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val shapes = LocalUmamoShapes.current + val focusRequester = remember { FocusRequester() } + LaunchedEffect(capturing) { + if (capturing) { + focusRequester.requestFocus() + } + } + val keyCapture = LocalKeyCapture.current + DisposableEffect(capturing, keyCapture) { + if (capturing) { + keyCapture.begin() + } + onDispose { + if (capturing) { + keyCapture.end() + } + } + } + val label = + when { + capturing -> stringResource(Res.string.settings_keybindings_press_shortcut) + chord != null -> formatAccelerator(chord) + else -> stringResource(Res.string.settings_keybindings_unbound) + } + val chipBase = + Modifier + .widthIn(min = CHORD_CHIP_MIN_WIDTH) + .clip(shapes.small) + // Capturing is an armed accent state, not a selection - accent is deliberate here even though + // the two tokens share a value in the dark scheme. + .background(if (capturing) colors.accent else colors.controlBackground) + .border(BorderStroke(1.dp, if (capturing) colors.accent else colors.controlBorder), shapes.small) + val chipModifier = + chipBase + .focusRequester(focusRequester) + .onPreviewKeyEvent { event -> capturing && handleCaptureKey(event, onCaptured, onCancelCapture) } + // The one focus node, present in both states so it outlives the capture. + .focusable() + .clickable(enabled = !capturing, onClick = onStartCapture) + Box(modifier = chipModifier.padding(horizontal = 10.dp, vertical = 4.dp), contentAlignment = Alignment.Center) { + Text(text = label, style = typography.labelMedium, color = if (capturing) colors.accentText else colors.text) + } +} + +/** + * Turns a key event during capture into a chord: ignores key-up and bare modifier presses (waiting for a + * real key), treats unmodified Escape as cancel, and otherwise emits the chord via [onCaptured]. The key + * naming is the shared [keyName] table, so a captured chord dispatches identically at runtime. + * + * @param KeyEvent event The key event during capture. + * @param Function onCaptured Receives the captured chord. + * @param Function onCancelCapture Cancels capture (unmodified Escape). + * @return Boolean true when the event was handled (consumed). + */ +private fun handleCaptureKey(event: KeyEvent, onCaptured: (KeyChord) -> Unit, onCancelCapture: () -> Unit): Boolean { + if (event.type != KeyEventType.KeyDown) { + return false + } + val pressedKeyName = keyName(event.key) ?: return false + val noModifiers = !event.isCtrlPressed && !event.isMetaPressed && !event.isShiftPressed && !event.isAltPressed + if (pressedKeyName == "Escape" && noModifiers) { + onCancelCapture() + return true + } + onCaptured( + KeyChord( + keyName = pressedKeyName, + primaryModifier = event.isCtrlPressed || event.isMetaPressed, + shift = event.isShiftPressed, + alt = event.isAltPressed, + ), + ) + return true +} + +/** + * A small "✕" clear button matching the kit's icon controls; dimmed and inert when there is nothing to + * clear (the command is already unbound, or the row is mid-capture). + * + * @param Boolean enabled Whether clearing is possible. + * @param Function onClick Unbinds the command. + */ +@Composable +private fun ClearButton(enabled: Boolean, onClick: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val description = stringResource(Res.string.settings_keybindings_clear) + // The label doubles as the hover text, matching the kit's icon controls: the row names the command, not + // what the ✕ beside it does. + Tooltip(text = description) { + Box( + modifier = + Modifier + .size(20.dp) + .then(if (enabled) Modifier.clickable(interactionSource = interaction, indication = null, onClick = onClick) else Modifier) + .semantics { contentDescription = description }, + contentAlignment = Alignment.Center, + ) { + Text( + text = "✕", + style = typography.labelMedium, + color = + when { + !enabled -> colors.textDisabled + hovered -> colors.text + else -> colors.textMuted + }, + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/QuickSetupDialog.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/QuickSetupDialog.kt new file mode 100644 index 0000000..7d9e4bf --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/QuickSetupDialog.kt @@ -0,0 +1,173 @@ +package org.umamo.ui.settings + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.wrapContentWidth +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.painterResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.help.ProjectInfo +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.button.Button +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.app_icon +import org.umamo.ui.resources.app_name +import org.umamo.ui.resources.quick_setup_continue +import org.umamo.ui.resources.quick_setup_title +import org.umamo.ui.resources.splash_banner +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** The banner's width-to-height ratio, near the 501x250 of Blender's splash. */ +private const val SPLASH_BANNER_ASPECT = 2f + +/** The card's widest extent; the banner art is authored at three times this width (see [SplashBanner]). */ +private val QUICK_SETUP_MAX_WIDTH = 560.dp + +/** + * The Quick Setup modal a first run opens with (and Help > Quick Setup... reopens): a banner over the few + * choices worth making before anything else - the UI language, the shortcut preset, and the theme. It is + * in the same scrim-plus-card family as the preferences window, and like it every change writes through to + * settings at once, so the app re-localizes and re-themes live behind the scrim and there is nothing to + * commit: Continue, Escape (routed here by the shell), and a scrim click all only close it. + * + * The rows are the preferences window's own, so both offer the same options under the same labels. A first + * run opens with the language already matched from the operating system (see seedFirstRunSettings). + * + * @param Function onDismiss Closes the modal. + */ +@Composable +fun QuickSetupDialog(onDismiss: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + Box( + // indication = null: the kit convention for a full-window scrim (see SettingsWindow). + modifier = + Modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Surface( + // 90% of the window, but never wider than the cap. The order matters: fillMaxWidth pins an exact width + // that a later widthIn cannot shrink, so wrapContentWidth frees it first and the cap then applies to + // what is left. The card swallows clicks (enabled = false) so a press inside it is not read as a scrim + // dismissal; the freed space beside a capped card has no handler, so a press there reaches the scrim. + modifier = + Modifier + .fillMaxWidth(0.9f) + .wrapContentWidth() + .widthIn(max = QUICK_SETUP_MAX_WIDTH) + .clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + // Scrolls only when the window is shorter than the card, so Continue stays reachable on a small screen. + Column(modifier = Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { + SplashBanner() + Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider)) + Column( + modifier = Modifier.fillMaxWidth().padding(start = 20.dp, top = 16.dp, end = 20.dp), + verticalArrangement = Arrangement.spacedBy(SETTING_ROW_SPACING), + ) { + Text(text = stringResource(Res.string.quick_setup_title), style = typography.labelMedium, color = colors.textMuted) + LanguageSettingRow() + KeymapPresetSettingRow(quick = true) + ThemeSettingRow() + } + Row(modifier = Modifier.fillMaxWidth().padding(20.dp), verticalAlignment = Alignment.CenterVertically) { + // Importing the settings of a previous version belongs at the start of this row, where Blender + // puts its "Load 3.3 Settings" button. Deferred: no installers ship yet, so there is no + // previous version to import from, and every build reads and writes the one unversioned + // /umamo/settings.json (see desktopAppStorage), so a new build already starts on the old + // file. It becomes meaningful once installed versions keep their settings side by side. + Spacer(modifier = Modifier.weight(1f)) + Button(label = stringResource(Res.string.quick_setup_continue), onClick = onDismiss, primary = true) + } + } + } + } +} + +/** + * The splash's banner: the splash artwork, with the app's name and icon in the bottom-left corner and the + * version in the top-right. + * + * The art is drawable/splash_banner.png: 2:1 at 1680x840 pixels, three times the banner's largest size + * ([QUICK_SETUP_MAX_WIDTH] wide) so it stays sharp on high-density screens. It is cropped to fill the + * banner, so art at any other ratio loses its edges rather than stretching. The name and the version are + * overlays rather than part of the art, so a version bump never means new art; the art keeps those two + * corners free of detail. They sit on the viewport's badge pill, the palette's pair for text over content + * the theme does not color, so they read on any art in either theme. + */ +@Composable +private fun SplashBanner() { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + val badgeShape = RoundedCornerShape(4.dp) + // The header fill shows only through transparent pixels in the art. + Box(modifier = Modifier.fillMaxWidth().aspectRatio(SPLASH_BANNER_ASPECT).background(colors.headerBackground)) { + // Decorative: the modal's rows and title say what it is. + Image( + painter = painterResource(Res.drawable.splash_banner), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.matchParentSize(), + ) + Row( + modifier = + Modifier + .align(Alignment.BottomStart) + .padding(12.dp) + .background(colors.viewportBadgeBackground, badgeShape) + .padding(horizontal = 8.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + // Decorative: the name beside it says what it is. + Image(painter = painterResource(Res.drawable.app_icon), contentDescription = null, modifier = Modifier.size(36.dp)) + Spacer(modifier = Modifier.width(8.dp)) + Text(text = stringResource(Res.string.app_name), style = typography.titleLarge, color = colors.viewportBadgeText) + } + // The version is data, not chrome, so it shows bare rather than through a localized "Version %s". + Text( + text = ProjectInfo.VERSION, + style = typography.bodySmall, + color = colors.viewportBadgeText, + modifier = + Modifier + .align(Alignment.TopEnd) + .padding(10.dp) + .background(colors.viewportBadgeBackground, badgeShape) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/QuickSetupState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/QuickSetupState.kt new file mode 100644 index 0000000..ec2552f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/QuickSetupState.kt @@ -0,0 +1,22 @@ +package org.umamo.ui.settings + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * Whether the Quick Setup modal is showing. Held for the application's life rather than by the shell, which + * is rebuilt for every document: a first run that opens a file while the modal is up keeps the modal. The + * app makes one - open on a first run - and provides it through [LocalQuickSetup]; the shell's overlay state + * reads and writes it like its other overlay flags. + * + * @param Boolean visible Whether the modal starts open. + */ +class QuickSetupState(visible: Boolean) { + /** Whether the modal is showing. */ + var visible: Boolean by mutableStateOf(visible) +} + +/** The app's [QuickSetupState], or null where no app provides one (the standalone shell, tests). */ +val LocalQuickSetup = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/SettingsSections.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/SettingsSections.kt new file mode 100644 index 0000000..eb9814c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/SettingsSections.kt @@ -0,0 +1,429 @@ +package org.umamo.ui.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.seed.ParameterTemplate +import org.umamo.interop.art.ArtworkAnchor +import org.umamo.reimport.WatchMode +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.HexColorField +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.SelectField +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.l10n.FALLBACK_LOCALE_TAG +import org.umamo.ui.l10n.LOCALE_SETTINGS_KEY +import org.umamo.ui.l10n.UI_LANGUAGE_ENDONYMS +import org.umamo.ui.rememberBooleanSetting +import org.umamo.ui.rememberDoubleSetting +import org.umamo.ui.rememberIntSetting +import org.umamo.ui.rememberStringSetting +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.settings_colors_active_selection_highlight +import org.umamo.ui.resources.settings_colors_group_edge +import org.umamo.ui.resources.settings_colors_group_face +import org.umamo.ui.resources.settings_colors_group_vertex +import org.umamo.ui.resources.settings_colors_mesh_edit +import org.umamo.ui.resources.settings_colors_pinned_placement +import org.umamo.ui.resources.settings_colors_role_active +import org.umamo.ui.resources.settings_colors_role_idle +import org.umamo.ui.resources.settings_colors_role_offkey +import org.umamo.ui.resources.settings_colors_role_selected +import org.umamo.ui.resources.settings_colors_selection_highlight +import org.umamo.ui.resources.settings_colors_viewport +import org.umamo.ui.resources.settings_colors_warning +import org.umamo.ui.resources.settings_import_alignment +import org.umamo.ui.resources.settings_import_delete_art_ignores_layer +import org.umamo.ui.resources.settings_import_layer_positions_from_world_axes +import org.umamo.ui.resources.settings_import_parameter_template +import org.umamo.ui.resources.settings_import_parameter_template_humanoid +import org.umamo.ui.resources.settings_import_parameter_template_none +import org.umamo.ui.resources.settings_import_watch_mode +import org.umamo.ui.resources.settings_import_watch_mode_auto +import org.umamo.ui.resources.settings_import_watch_mode_notify +import org.umamo.ui.resources.settings_import_watch_mode_off +import org.umamo.ui.resources.settings_interface_history_steps +import org.umamo.ui.resources.settings_interface_language +import org.umamo.ui.resources.settings_interface_theme +import org.umamo.ui.resources.settings_pen_coming_soon +import org.umamo.ui.resources.settings_theme_dark +import org.umamo.ui.resources.settings_theme_light +import org.umamo.ui.resources.settings_theme_system +import org.umamo.ui.resources.settings_viewport_grid_scale +import org.umamo.ui.resources.settings_viewport_grid_subdivisions +import org.umamo.ui.resources.settings_viewport_supersample +import org.umamo.ui.resources.settings_viewport_supersample_while_resizing +import org.umamo.ui.resources.settings_viewport_zoom_step +import org.umamo.ui.resources.settings_viewport_zoom_step_coarse +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.viewport.ViewportColorSettings +import org.umamo.ui.viewport.ViewportSettings +import org.umamo.ui.workspace.artworkAnchorLabel + +/** The settings key + values for the UI theme mode, kept in lockstep with org.umamo.ui.theme.Theme. */ +private const val THEME_KEY = "interface.theme" +private const val THEME_DEFAULT = "dark" + +/** + * The Interface section: theme, language, and the undo-history depth. All three are wired end-to-end - + * writing the key re-themes / re-localizes the running app and re-caps the open document's undo stack - + * so each auto-saves with immediate visible effect. + */ +@Composable +internal fun InterfaceSection() { + var historyLimit by rememberIntSetting(HistorySettings.HISTORY_LIMIT_KEY, HistorySettings.HISTORY_LIMIT_DEFAULT) + + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SETTING_ROW_SPACING)) { + ThemeSettingRow() + LanguageSettingRow() + // Lowering this trims the open document's stack on commit, but never past the live step - the + // current state and anything left to redo always survive (see EditorSession.historyLimit). + SettingRow(label = stringResource(Res.string.settings_interface_history_steps)) { + NumberField( + value = historyLimit, + onValueChange = { committed -> historyLimit = committed }, + range = HistorySettings.HISTORY_LIMIT_RANGE, + modifier = Modifier.width(80.dp), + ) + } + } +} + +/** + * The UI theme row, bound write-through to interface.theme: Preferences and Quick Setup share it, so both + * offer the same modes under the same labels. The option labels are localized chrome. + */ +@Composable +internal fun ThemeSettingRow() { + var theme by rememberStringSetting(THEME_KEY, THEME_DEFAULT) + // Resolve option labels in composition (stringResource is @Composable) into ordered maps, so the + // SelectField label lambda - which is plain (T) -> String - is a lookup, not a composable call. The + // command palette resolves its labels the same way. + val themeLabels = + linkedMapOf( + "dark" to stringResource(Res.string.settings_theme_dark), + "light" to stringResource(Res.string.settings_theme_light), + "system" to stringResource(Res.string.settings_theme_system), + ) + SettingRow(label = stringResource(Res.string.settings_interface_theme)) { + SelectField( + selected = theme, + options = themeLabels.keys.toList(), + label = { value -> themeLabels[value] ?: value }, + onSelect = { value -> theme = value }, + ) + } +} + +/** + * The UI language row, bound write-through to localization.locale: Preferences and Quick Setup share it. + * The row leads with the globe so a rigger who cannot read the current language can still find it, and the + * options are endonyms (see [UI_LANGUAGE_ENDONYMS]) for the same reason. + */ +@Composable +internal fun LanguageSettingRow() { + var locale by rememberStringSetting(LOCALE_SETTINGS_KEY, FALLBACK_LOCALE_TAG) + SettingRow(label = stringResource(Res.string.settings_interface_language), icon = LocalUmamoIcons.language) { + SelectField( + selected = locale, + options = UI_LANGUAGE_ENDONYMS.keys.toList(), + label = { value -> UI_LANGUAGE_ENDONYMS[value] ?: value }, + onSelect = { value -> locale = value }, + ) + } +} + +/** The settings key for the parameter set an artwork import seeds; the values are ParameterTemplate keys. */ +internal const val IMPORT_PARAMETER_TEMPLATE_KEY = "import.parameterTemplate" + +/** The settings key for where a later artwork file is anchored on the rig's canvas; the values are ArtworkAnchor keys. */ +internal const val IMPORT_ALIGNMENT_KEY = "import.alignment" + +/** The settings key for what a document does when a watched artwork file changes; the values are WatchMode keys. */ +internal const val IMPORT_WATCH_MODE_KEY = "import.watchMode" + +/** The settings key for whether Delete Art also marks the tile's layer ignored, so a reload does not mint the art back. */ +internal const val IMPORT_DELETE_ART_IGNORES_LAYER_KEY = "import.deleteArtIgnoresLayer" + +/** The settings key for whether the Sources layer rows measure positions from the world axes instead of the art file's top-left corner. */ +internal const val IMPORT_LAYER_POSITIONS_FROM_WORLD_AXES_KEY = "import.layerPositionsFromWorldAxes" + +/** + * The Import section: what an artwork import seeds a new model with, where a later file is anchored + * on the rig's canvas, what a document does when a watched artwork file changes, whether Delete Art + * keeps the deleted layer out of the rig, and which frame the Sources layer rows measure positions in. + * The parameter template and the anchor are stored as their keys so a later entry is one more option + * here and one more enum entry, nothing else; the import reads them at the moment it runs, so a change + * applies to the next import (and the anchor is only the default of the import's own Align row). The + * watch mode is stored as the mode's key and read live by the open document's watcher. The Delete Art + * choice is read at each dispatch. The layer-position frame is read live by the Sources space. + */ +@Composable +internal fun ImportSection() { + var templateKey by rememberStringSetting(IMPORT_PARAMETER_TEMPLATE_KEY, ParameterTemplate.Default.key) + val templateLabels = + linkedMapOf( + ParameterTemplate.Humanoid.key to stringResource(Res.string.settings_import_parameter_template_humanoid), + ParameterTemplate.None.key to stringResource(Res.string.settings_import_parameter_template_none), + ) + + var alignmentKey by rememberStringSetting(IMPORT_ALIGNMENT_KEY, ArtworkAnchor.Default.key) + val anchorLabels = ArtworkAnchor.entries.associate { anchor -> anchor.key to artworkAnchorLabel(anchor) } + + var deleteArtIgnoresLayer by rememberBooleanSetting(IMPORT_DELETE_ART_IGNORES_LAYER_KEY, false) + + var layerPositionsFromWorldAxes by rememberBooleanSetting(IMPORT_LAYER_POSITIONS_FROM_WORLD_AXES_KEY, false) + + var watchModeKey by rememberStringSetting(IMPORT_WATCH_MODE_KEY, WatchMode.Default.key) + val watchModeLabels = + linkedMapOf( + WatchMode.Auto.key to stringResource(Res.string.settings_import_watch_mode_auto), + WatchMode.Notify.key to stringResource(Res.string.settings_import_watch_mode_notify), + WatchMode.Off.key to stringResource(Res.string.settings_import_watch_mode_off), + ) + + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SETTING_ROW_SPACING)) { + SettingRow(label = stringResource(Res.string.settings_import_parameter_template)) { + SelectField( + selected = ParameterTemplate.fromKey(templateKey).key, + options = templateLabels.keys.toList(), + label = { value -> templateLabels[value] ?: value }, + onSelect = { value -> templateKey = value }, + ) + } + // The default of the import's Align row: the art programs' own canvas-resize anchors, Center + // being what both of them resize around unless told otherwise. + SettingRow(label = stringResource(Res.string.settings_import_alignment)) { + SelectField( + selected = ArtworkAnchor.fromKey(alignmentKey).key, + options = anchorLabels.keys.toList(), + label = { value -> anchorLabels[value] ?: value }, + onSelect = { value -> alignmentKey = value }, + ) + } + // Read live by the open document's watcher, so the switch applies at once. + SettingRow(label = stringResource(Res.string.settings_import_watch_mode)) { + SelectField( + selected = WatchMode.fromKey(watchModeKey).key, + options = watchModeLabels.keys.toList(), + label = { value -> watchModeLabels[value] ?: value }, + onSelect = { value -> watchModeKey = value }, + ) + } + // Off by default: a deleted drawable's layer comes back on the next reload unless the rigger asks + // otherwise here, or ignores the row by hand. + Checkbox( + checked = deleteArtIgnoresLayer, + onCheckedChange = { checked -> deleteArtIgnoresLayer = checked }, + label = stringResource(Res.string.settings_import_delete_art_ignores_layer), + ) + // Off by default: a layer row reads its position in the art file's own frame, the numbers the art + // program shows. On, it reads from the world axes like every other position in the app. + Checkbox( + checked = layerPositionsFromWorldAxes, + onCheckedChange = { checked -> layerPositionsFromWorldAxes = checked }, + label = stringResource(Res.string.settings_import_layer_positions_from_world_axes), + ) + } +} + +/** + * The Colors section: the viewport selection highlights and overlay colors (the collision warning, + * the pinned-placement highlight) plus the Edit-mode gizmo palette (viewport.meshEdit.*), grouped + * element × state. Every row is a [HexColorField] bound write-through to its settings key, so an + * edit re-colors the viewport live as it is typed - the same auto-save model as the rest of the + * window. + */ +@Composable +internal fun ColorsSection() { + val typography = LocalUmamoTypography.current + val scrollState = rememberScrollState() + Box(modifier = Modifier.fillMaxSize()) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState), verticalArrangement = Arrangement.spacedBy(SETTING_ROW_SPACING)) { + Text(text = stringResource(Res.string.settings_colors_viewport), style = typography.titleSmall) + ColorSettingRow( + stringResource(Res.string.settings_colors_selection_highlight), + ViewportColorSettings.SELECTION_HIGHLIGHT_KEY, + ViewportColorSettings.SELECTION_HIGHLIGHT_DEFAULT, + ) + ColorSettingRow( + stringResource(Res.string.settings_colors_active_selection_highlight), + ViewportColorSettings.ACTIVE_SELECTION_HIGHLIGHT_KEY, + ViewportColorSettings.ACTIVE_SELECTION_HIGHLIGHT_DEFAULT, + ) + ColorSettingRow( + stringResource(Res.string.settings_colors_warning), + ViewportColorSettings.WARNING_COLOR_KEY, + ViewportColorSettings.WARNING_COLOR_DEFAULT, + ) + ColorSettingRow( + stringResource(Res.string.settings_colors_pinned_placement), + ViewportColorSettings.PINNED_PLACEMENT_COLOR_KEY, + ViewportColorSettings.PINNED_PLACEMENT_COLOR_DEFAULT, + ) + + Text(text = stringResource(Res.string.settings_colors_mesh_edit), style = typography.titleSmall) + + ColorGroupHeading(stringResource(Res.string.settings_colors_group_vertex)) + ColorSettingRow(stringResource(Res.string.settings_colors_role_idle), ViewportColorSettings.VERTEX_IDLE_KEY, ViewportColorSettings.VERTEX_IDLE_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_selected), ViewportColorSettings.VERTEX_SELECTED_KEY, ViewportColorSettings.VERTEX_SELECTED_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_active), ViewportColorSettings.VERTEX_ACTIVE_KEY, ViewportColorSettings.VERTEX_ACTIVE_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_offkey), ViewportColorSettings.VERTEX_OFFKEY_KEY, ViewportColorSettings.VERTEX_OFFKEY_DEFAULT) + + ColorGroupHeading(stringResource(Res.string.settings_colors_group_edge)) + ColorSettingRow(stringResource(Res.string.settings_colors_role_idle), ViewportColorSettings.EDGE_IDLE_KEY, ViewportColorSettings.EDGE_IDLE_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_selected), ViewportColorSettings.EDGE_SELECTED_KEY, ViewportColorSettings.EDGE_SELECTED_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_active), ViewportColorSettings.EDGE_ACTIVE_KEY, ViewportColorSettings.EDGE_ACTIVE_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_offkey), ViewportColorSettings.EDGE_OFFKEY_KEY, ViewportColorSettings.EDGE_OFFKEY_DEFAULT) + + ColorGroupHeading(stringResource(Res.string.settings_colors_group_face)) + ColorSettingRow(stringResource(Res.string.settings_colors_role_idle), ViewportColorSettings.FACE_IDLE_KEY, ViewportColorSettings.FACE_IDLE_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_selected), ViewportColorSettings.FACE_SELECTED_KEY, ViewportColorSettings.FACE_SELECTED_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_active), ViewportColorSettings.FACE_ACTIVE_KEY, ViewportColorSettings.FACE_ACTIVE_DEFAULT) + ColorSettingRow(stringResource(Res.string.settings_colors_role_offkey), ViewportColorSettings.FACE_OFFKEY_KEY, ViewportColorSettings.FACE_OFFKEY_DEFAULT) + } + VerticalScrollbarOverlay(scrollState) + } +} + +/** + * A muted group heading within the Colors section (Vertex / Edge / Face), spaced to read as a subsection. + * + * @param String label The already-localized group label. + */ +@Composable +private fun ColorGroupHeading(label: String) { + Column { + Spacer(modifier = Modifier.height(2.dp)) + Text(text = label, style = LocalUmamoTypography.current.labelMedium, color = LocalUmamoColors.current.textMuted) + } +} + +/** + * One color row: a role label bound to a [HexColorField] editing the given settings key write-through. + * + * @param String label The already-localized role label (Idle / Selected / Active / Off-key). + * @param String key The dotted settings key the row edits. + * @param String defaultHex The bundled default used when the key is absent. + */ +@Composable +private fun ColorSettingRow(label: String, key: String, defaultHex: String) { + var hexValue by rememberStringSetting(key, defaultHex) + SettingRow(label = label) { + HexColorField(value = hexValue, onValueChange = { newValue -> hexValue = newValue }, modifier = Modifier.width(150.dp)) + } +} + +/** + * The Viewport section: pointer-interaction tuning plus the rendering performance toggles. The zoom + * steps are the percent change per wheel notch (fine) and per Shift-wheel notch (coarse); the grid + * scale is the default major-line spacing in world units for files that do not store their own + * (CMO3); the supersampling pair trades render quality for speed on weak GPUs (off = 1x everywhere; + * the resize toggle keeps 2x during panel drags). The viewport binding reads every key live, so a + * committed edit re-tunes wheel zoom / re-draws the grid / re-renders at the new quality immediately. + * Each number field commits clamped to its [ViewportSettings] range (the [NumberField] contract). + */ +@Composable +internal fun ViewportSection() { + var zoomStep by rememberDoubleSetting(ViewportSettings.ZOOM_STEP_KEY, ViewportSettings.ZOOM_STEP_DEFAULT) + var zoomStepCoarse by rememberDoubleSetting(ViewportSettings.ZOOM_STEP_COARSE_KEY, ViewportSettings.ZOOM_STEP_COARSE_DEFAULT) + var gridScale by rememberDoubleSetting(ViewportSettings.GRID_SCALE_KEY, ViewportSettings.GRID_SCALE_DEFAULT) + var gridSubdivisions by rememberIntSetting(ViewportSettings.GRID_SUBDIVISIONS_KEY, ViewportSettings.GRID_SUBDIVISIONS_DEFAULT) + var supersample by rememberBooleanSetting(ViewportSettings.SUPERSAMPLE_KEY, ViewportSettings.SUPERSAMPLE_DEFAULT) + var supersampleWhileResizing by + rememberBooleanSetting(ViewportSettings.SUPERSAMPLE_WHILE_RESIZING_KEY, ViewportSettings.SUPERSAMPLE_WHILE_RESIZING_DEFAULT) + + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SETTING_ROW_SPACING)) { + SettingRow(label = stringResource(Res.string.settings_viewport_zoom_step)) { + NumberField( + value = zoomStep.toFloat(), + onValueChange = { committed -> zoomStep = committed.toDouble() }, + range = ViewportSettings.ZOOM_STEP_RANGE, + modifier = Modifier.width(80.dp), + ) + } + SettingRow(label = stringResource(Res.string.settings_viewport_zoom_step_coarse)) { + NumberField( + value = zoomStepCoarse.toFloat(), + onValueChange = { committed -> zoomStepCoarse = committed.toDouble() }, + range = ViewportSettings.ZOOM_STEP_RANGE, + modifier = Modifier.width(80.dp), + ) + } + SettingRow(label = stringResource(Res.string.settings_viewport_grid_scale)) { + NumberField( + value = gridScale.toFloat(), + onValueChange = { committed -> gridScale = committed.toDouble() }, + range = ViewportSettings.GRID_SCALE_RANGE, + modifier = Modifier.width(80.dp), + ) + } + SettingRow(label = stringResource(Res.string.settings_viewport_grid_subdivisions)) { + NumberField( + value = gridSubdivisions, + onValueChange = { committed -> gridSubdivisions = committed }, + range = ViewportSettings.GRID_SUBDIVISIONS_RANGE, + modifier = Modifier.width(80.dp), + ) + } + Checkbox( + checked = supersample, + onCheckedChange = { checked -> supersample = checked }, + label = stringResource(Res.string.settings_viewport_supersample), + ) + // Inert with supersampling off: everything already renders at 1x, so there is no supersample + // to keep while resizing (the engine computes the same 1x either way). The stored value is + // kept, so re-enabling supersampling restores the previous choice. + Checkbox( + checked = supersampleWhileResizing, + onCheckedChange = { checked -> supersampleWhileResizing = checked }, + label = stringResource(Res.string.settings_viewport_supersample_while_resizing), + enabled = supersample, + ) + } +} + +/** + * The Keybindings section: preset selection plus the per-command rebinding editor (see [KeybindingsEditor]), + * all auto-saving to settings input.keybinding and re-resolving the live keymap. + */ +@Composable +internal fun KeybindingsSection() { + KeybindingsEditor() +} + +/** + * The Pen section: a placeholder until the pen backend (JPen / Wacom) and the radial menu land. + * + * ペン設定。ペンバックエンド実装までのプレースホルダ。 + */ +@Composable +internal fun PenSection() { + ComingSoon(stringResource(Res.string.settings_pen_coming_soon)) +} + +/** + * A muted single-line placeholder for a section whose controls are not built yet. + * + * @param String message The already-localized placeholder line. + */ +@Composable +private fun ComingSoon(message: String) { + Text(text = message, style = LocalUmamoTypography.current.bodyMedium, color = LocalUmamoColors.current.textMuted) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/SettingsWindow.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/SettingsWindow.kt new file mode 100644 index 0000000..69c7d28 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/settings/SettingsWindow.kt @@ -0,0 +1,207 @@ +package org.umamo.ui.settings + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.FIELD_ROW_LABEL_WIDTH +import org.umamo.ui.kit.FIELD_ROW_SPACING +import org.umamo.ui.kit.FieldRow +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.button.CloseButton +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.settings_category_colors +import org.umamo.ui.resources.settings_category_import +import org.umamo.ui.resources.settings_category_interface +import org.umamo.ui.resources.settings_category_keybindings +import org.umamo.ui.resources.settings_category_pen +import org.umamo.ui.resources.settings_category_viewport +import org.umamo.ui.resources.settings_close +import org.umamo.ui.resources.settings_title +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon + +/** Fixed width of the left category rail; wide enough for the longest localized category label. */ +private val CATEGORY_RAIL_WIDTH = 168.dp + +/** + * The preferences categories shown in the left rail, in display order. Each carries its localized rail + * label; the right pane switches on the selection in [SettingsWindow] (an exhaustive `when`, so adding a + * category is a compile-time prompt to give it content). + * + * 設定のカテゴリ(左レール)。各自のローカライズ済みラベルを持つ。右ペインは選択に応じて切り替わる。 + * + * @property StringResource label The rail label resource. + */ +internal enum class SettingsCategory(val label: StringResource) { + Interface(Res.string.settings_category_interface), + Colors(Res.string.settings_category_colors), + Viewport(Res.string.settings_category_viewport), + Import(Res.string.settings_category_import), + Keybindings(Res.string.settings_category_keybindings), + Pen(Res.string.settings_category_pen), +} + +/** + * The preferences window: a focus-stealing in-window overlay (a scrim over the shell with a centered + * card), styled like the kit's other modals (the command palette, the confirm dialog) so it reads as + * the same surface family rather than a host-OS window. A left category rail selects which section the + * right pane shows; sections auto-save every change (no OK/Apply), so the only chrome is dismissal. + * + * Dismissal is by Escape, a scrim click, or the header close button - the last matters on a keyboardless + * tablet, where there is no Escape key and the scrim may not read as interactive. The shell owns the + * visible state and routes Escape here (mirroring the command palette); this composable only renders. + * + * 設定ウィンドウ。シェルを覆うスクリム+中央カードのモーダル。左レールでセクションを選び、変更は即時保存。 + * Esc・スクリムのクリック・閉じるボタンで閉じる(キーボード無しのタブレット向けに閉じるボタンを用意)。 + * + * @param Function onDismiss Closes the window (Escape is routed here by the shell; also the scrim / close button). + */ +@Composable +fun SettingsWindow(onDismiss: () -> Unit) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + var category by remember { mutableStateOf(SettingsCategory.Interface) } + Box( + // indication = null: the kit's convention everywhere interactive. Without it the full-size scrim + // renders the default hover/press indication - a second dimming layer that toggles as the pointer + // enters/leaves the window or presses a dropdown, stacking on the intended scrim. + modifier = + Modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Surface( + // The card swallows clicks (enabled = false) so a press inside it is not read as a scrim dismissal, + // exactly as the confirm dialog and command palette cards do. + modifier = + Modifier + .fillMaxWidth(0.82f) + .fillMaxHeight(0.82f) + .widthIn(max = 760.dp) + .heightIn(max = 560.dp) + .clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.fillMaxSize()) { + // Header: title on the left, close button on the right. + Row( + modifier = Modifier.fillMaxWidth().background(colors.headerBackground).padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text = stringResource(Res.string.settings_title), style = typography.titleSmall, modifier = Modifier.weight(1f)) + CloseButton(onClick = onDismiss, contentDescription = stringResource(Res.string.settings_close)) + } + Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider)) + Row(modifier = Modifier.fillMaxWidth().weight(1f)) { + CategoryRail(selected = category, onSelect = { category = it }, modifier = Modifier.width(CATEGORY_RAIL_WIDTH).fillMaxHeight()) + Box(modifier = Modifier.width(1.dp).fillMaxHeight().background(colors.divider)) + Box(modifier = Modifier.weight(1f).fillMaxHeight().padding(20.dp)) { + when (category) { + SettingsCategory.Interface -> InterfaceSection() + SettingsCategory.Colors -> ColorsSection() + SettingsCategory.Viewport -> ViewportSection() + SettingsCategory.Import -> ImportSection() + SettingsCategory.Keybindings -> KeybindingsSection() + SettingsCategory.Pen -> PenSection() + } + } + } + } + } + } +} + +/** + * The left rail of category rows. The selected row is filled with the accent and its label uses the + * on-accent text color; the rest hover-highlight, matching the kit's row idiom (the command palette + * list, menu rows). + * + * @param SettingsCategory selected The currently selected category. + * @param Function onSelect Called with a category when its row is clicked. + * @param Modifier modifier Layout modifier for the rail column. + */ +@Composable +private fun CategoryRail(selected: SettingsCategory, onSelect: (SettingsCategory) -> Unit, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + Column(modifier = modifier.padding(vertical = 6.dp)) { + for (entry in SettingsCategory.entries) { + val isSelected = entry == selected + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + Row( + modifier = + Modifier + .fillMaxWidth() + .background( + when { + isSelected -> colors.selection + hovered -> colors.rowHover + else -> Color.Transparent + }, + ) + .clickable(interactionSource = interaction, indication = null) { onSelect(entry) } + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(entry.label), + style = typography.labelMedium, + color = if (isSelected) colors.selectionText else colors.text, + ) + } + } + } +} + +/** Spacer between stacked setting rows within a section (the shared kit spacing). */ +internal val SETTING_ROW_SPACING = FIELD_ROW_SPACING + +/** Fixed width of a setting row's left label column, so the controls in a section align. */ +internal val SETTING_LABEL_WIDTH = FIELD_ROW_LABEL_WIDTH + +/** + * One labelled settings row: a thin settings-side wrapper over the shared kit [FieldRow], pinning the + * settings label-column width so every section aligns. Kept as its own name so the many settings call + * sites stay a one-liner. + * + * @param String label The already-localized row label. + * @param UmamoIcon? icon A glyph before the label (the language row's globe), or null for none. + * @param Function control The control composable (a SelectField, etc.). + */ +@Composable +internal fun SettingRow(label: String, icon: UmamoIcon? = null, control: @Composable () -> Unit) { + FieldRow(label = label, labelWidth = SETTING_LABEL_WIDTH, icon = icon, control = control) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Color.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Color.kt new file mode 100644 index 0000000..7dda279 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Color.kt @@ -0,0 +1,369 @@ +package org.umamo.ui.theme + +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color + +/* + * The flat, explicit color palette for the custom design system - every role is a value we set, not a tone + * derived from a seed. A dense, Blender-ish dark scheme (flat greys + the brand purple accent) with a + * deliberately designed light scheme; re-tinting is local to this file. Kit widgets and migrated panels + * read these via [LocalUmamoColors]. + * + * The light scheme is a system, not an inversion of the dark values: + * - The surface ladder keeps the dark scheme's elevation sign (raised surfaces are lighter in both + * themes): window backdrop < tab < row stripe < panel < header < control fill. + * - One deliberate flip: transient hover washes go darker in light mode, because a lighter-than-near-white + * hover is imperceptible. Dark keeps its brighten-on-hover values. + * - The accent deepens in light mode so white on-accent text and accent-as-text stay legible. + * - Selection decouples from the accent in light mode: a soft lavender row tint with deep plum marks, so + * selected rows read as selection rather than as primary buttons. + */ + +/** + * The role palette. Lean and explicit - no seed/tonal derivation. Roles map onto the editor's surfaces, + * line-work, text, the brand accent, selection, controls, transient state washes, and the viewport overlay. + * + * @property Color windowBackground The outermost editor background and the native caption tint. + * @property Color menuBackground Menu and popup surface fill (menus, command palette, hover popups). + * @property Color panelBackground Default panel / surface / dialog fill; space-picker chip hover fill. + * @property Color panelThirdElevation A third, raised-most surface above [panelBackground] for nested + * cards within a panel (the Properties tab's Data-section blocks). + * @property Color panelThirdElevationBorder Hairline border paired with [panelThirdElevation]. + * @property Color tabBackground Unselected tabs and the space-picker chip at rest. + * @property Color headerBackground Panel headers, the status bar, the selected workspace tab, and the + * tab rename editor. + * @property Color rowHover Hover wash for rows, tabs, menu items, and secondary buttons. + * @property Color rowStripe The tint of every other row in dense lists (outliner zebra striping). + * @property Color divider The deepest structural line: splitters, hairline rules, and the Pad2D + * center crosshair. + * @property Color panelBorder Hairline border around panels, dialogs, and popups. + * @property Color panelBorderHover Border pop on hover (area chrome, select fields). + * @property Color controlBorder Inset border around controls; the Pad2D frame. + * @property Color guideLine Mid-strength drawn line-work: the Pad2D grid, slider ticks, in-menu + * dividers, and the area drag-indicator strip. + * @property Color treeGuideLine Outliner ancestry guide lines. + * @property Color text Primary text and text cursors. + * @property Color textMuted Secondary / dimmed text, placeholders, and muted glyphs. + * @property Color textDisabled Disabled text and glyphs. + * @property Color accent The brand accent fill: primary buttons, checkboxes, the slider fill, + * armed/recording states, and accent borders/marks. + * @property Color accentHover Accent hover state. + * @property Color accentPressed Accent fill while a control is held down. + * @property Color accentText Text/icon on top of accent fills. + * @property Color selection Selected-item row background. + * @property Color selectionText Text and marks on selection rows. + * @property Color controlBackground Neutral control fill (text fields, secondary buttons, segments, key + * chips). + * @property Color controlBackgroundHover Hover fill for a neutral control's background (the NumberField + * hover state). + * @property Color controlGlyph Icon glyphs on neutral control and chip fills. + * @property Color keyedOnKey Text/glyph tint for a field whose channel is keyed and the pose sits + * exactly on one of its keys (Blender-style keyframe tinting; see [org.umamo.ui.model.KeyedFieldState]). + * @property Color keyedBetween Text/glyph tint for a field whose channel is keyed but the pose is not + * sitting on one of its keys - an edit here needs an explicit key to survive. + * @property Color keyedModified Text/glyph tint for a field with an edit made and not yet keyed; it is + * showing in the viewport and dies on the next scrub. + * @property Color keyedOnKeyBackground Translucent background wash paired with [keyedOnKey]. + * @property Color keyedBetweenBackground Translucent background wash paired with [keyedBetween]. + * @property Color keyedModifiedBackground Translucent background wash paired with [keyedModified]. + * @property Color signalGood Glyph tint for a healthy state a panel reports (a layer bound by a + * stable key): the green of a traffic light, identical in both schemes. + * @property Color signalCaution Glyph tint for a state that works but will not survive a change (a + * binding by name, an unplaced tile): the amber of a traffic light. + * @property Color signalBad Glyph tint for a broken state (an unbound layer, a missing file): the + * red of a traffic light. + * @property Color buttonHover Hover fill for unselected ButtonGroup segments (stronger than + * rowHover in dark). + * @property Color buttonPressed Neutral fill while a button or segment is held down. Hover brightens + * a step from rest and a press darkens one, so the two states can never be mistaken for each other. + * @property Color sliderTrack Recessed slider track / pad groove (unfilled). + * @property Color sliderThumb Slider and 2D-pad handle. + * @property Color dropZoneFill Faint wash over a candidate area drop zone while dragging. + * @property Color dropZoneEmphasis Stronger wash over the consumed half of an area drop zone. + * @property Color dropTargetBackground Outliner nest-into drop-target row fill. + * @property Color selectionAncestorBackground Outliner ancestor-of-selection row wash. + * @property Color searchMatchBackground Outliner search-hit row band. + * @property Color scrollbarThumb Scrollbar thumb at rest. + * @property Color scrollbarThumbHover Scrollbar thumb while hovered. + * @property Color overlayScrim Dim behind modal overlays (the command palette, dialogs). + * @property Color viewportBadgeText Text on viewport overlay badges (zoom readout, edit-target badge). + * Badges overlay artwork rather than chrome, so they stay dark pills in both themes. + * @property Color viewportBadgeBackground The viewport overlay badge pill fill. + * @property Color viewportMarquee The box-select rubber-band stroke in the viewport. + * @property Color viewportMarqueeContrast The opposite-luminance tone paired with the marquee for the + * two-tone marching-ants selection affordances (crosshair guides, box, circle), so the dashed outline + * stays legible over any viewport background where a single-color dash would wash out. + * @property Color transparencyCheckerLight The lighter of the two alternating cells of the transparency + * checker drawn behind thumbnails to reveal alpha (themed so a dark scheme gets a dark checker). + * @property Color transparencyCheckerDark The darker of the two alternating transparency-checker cells. + * @property Color viewportGridBackground The flat canvas fill behind the GL viewport's world-aligned grid. + * @property Color viewportGridLineMajor The major (whole-scale) grid line color. + * @property Color viewportGridLineMinor The minor (subdivision) grid line color. + * @property Color trackRegionBackground The keyform / dope sheet's track region, behind and below the rows. + * @property Color trackRowGroup Band behind a track sheet's grouping rows. + * @property Color trackRowPrimary Band behind a track sheet's primary tracks. + * @property Color trackRowSecondary Band behind a track sheet's secondary tracks. + * @property Color trackRowAlternate Band behind a track sheet's layered-source tracks. + * @property Color outlinerObjectTint Signature tint for puppet-root / part / art-mesh outliner icons. + * @property Color outlinerDeformTint Signature tint for armature / deformer outliner icons. + * @property Color outlinerObjectTintDimmed Dimmed variant of the object tint for muted rows. + * @property Color outlinerDeformTintDimmed Dimmed variant of the deformer tint for muted rows. + */ +data class UmamoColors( + val windowBackground: Color, + val menuBackground: Color, + val panelBackground: Color, + val panelThirdElevation: Color, + val panelThirdElevationBorder: Color, + val tabBackground: Color, + val headerBackground: Color, + val rowHover: Color, + val rowStripe: Color, + val divider: Color, + val panelBorder: Color, + val panelBorderHover: Color, + val controlBorder: Color, + val guideLine: Color, + val treeGuideLine: Color, + val text: Color, + val textMuted: Color, + val textDisabled: Color, + val accent: Color, + val accentHover: Color, + val accentPressed: Color, + val accentText: Color, + val selection: Color, + val selectionText: Color, + val controlBackground: Color, + val controlBackgroundHover: Color, + val controlGlyph: Color, + val keyedOnKey: Color, + val keyedBetween: Color, + val keyedModified: Color, + val keyedOnKeyBackground: Color, + val keyedBetweenBackground: Color, + val keyedModifiedBackground: Color, + val signalGood: Color, + val signalCaution: Color, + val signalBad: Color, + val buttonHover: Color, + val buttonPressed: Color, + val sliderTrack: Color, + val sliderThumb: Color, + val dropZoneFill: Color, + val dropZoneEmphasis: Color, + val dropTargetBackground: Color, + val selectionAncestorBackground: Color, + val searchMatchBackground: Color, + val scrollbarThumb: Color, + val scrollbarThumbHover: Color, + val overlayScrim: Color, + val viewportBadgeText: Color, + val viewportBadgeBackground: Color, + val viewportMarquee: Color, + val viewportMarqueeContrast: Color, + val transparencyCheckerLight: Color, + val transparencyCheckerDark: Color, + val viewportGridBackground: Color, + val viewportGridLineMajor: Color, + val viewportGridLineMinor: Color, + val trackRegionBackground: Color, + val trackRowGroup: Color, + val trackRowPrimary: Color, + val trackRowSecondary: Color, + val trackRowAlternate: Color, + val outlinerObjectTint: Color, + val outlinerDeformTint: Color, + val outlinerObjectTintDimmed: Color, + val outlinerDeformTintDimmed: Color, +) + +// Alpha-carrying tokens below derive via .copy(alpha = ...) on these bases, never re-baked hex: values +// like 0.7f have no exact 8-bit representation, and the derivation keeps the rendered floats bit-identical +// to what the call sites historically computed inline. +private val brandPurple = Color(0xFFBF86D7) + +// Blender's keyframe colors, identical in both schemes on purpose - they are learned signals, and a +// per-scheme variant would make the light theme's "orange" mean something a user has to relearn. Shared as +// one constant, alpha included, so a per-scheme background tint could not drift them apart through the back +// door. +private val keyframeOnKey = Color(0xFFD1B727) +private val keyframeBetween = Color(0xFF5FC729) +private val keyframeModified = Color(0xFFDF8431) +private const val KEYED_BACKGROUND_ALPHA = 0.22f + +// The traffic-light signals (good / caution / bad), identical in both schemes for the same reason as the +// keyframe colors. Deliberately not the keyframe trio: keyedBetween is a keyframe state, not a health +// report, and one color must not carry two meanings across panels. +private val signalGreen = Color(0xFF58B65C) +private val signalAmber = Color(0xFFD9A62B) +private val signalRed = Color(0xFFE05252) +private val brandPurpleBright = Color(0xFFD394ED) +private val brandPurpleDim = Color(0xFFA96FC1) + +// The light scheme deepens the accent so white on-accent text reads at ~5.6:1 (the dark purple family +// value is too pale against light surfaces). +private val brandPurpleDeep = Color(0xFF8A4FA8) +private val brandPurpleDeepBright = Color(0xFF9B63B9) +private val mutedGreyDark = Color(0xFF9A9A9A) +private val mutedGreyLight = Color(0xFF6B6B6B) + +// Blender's armature object / data signature colours, per outliner node family. +private val outlinerTanDark = Color(0xFFE19658) +private val outlinerTanLight = Color(0xFFE19658) +private val outlinerTealDark = Color(0xFF00D4A3) +private val outlinerTealLight = Color(0xFF00D4A3) +private val chromeDeep = Color(0xFF181818) +private val panelEmphasis = Color(0xFF3A3A3A) +private val hoverEmphasis = Color(0xFF414141) +// Creme: FFF3EA (Text or otherwise) Muted Creme: C4B0A1 - Honestly, creme for the text looks like the weird Android Material 3 color tinting and I hate it. +// Primary Purple: BF86D7 +// Secondary Yellow: FCDD83 + +/** The dark scheme: flat greys with the brand purple accent (the default; Blender is dark-first). */ +val umamoDarkColors = + UmamoColors( + windowBackground = chromeDeep, + menuBackground = chromeDeep, + panelBackground = Color(0xFF303030), + panelThirdElevation = Color(0xFF454545), + panelThirdElevationBorder = Color(0xFF545454), + tabBackground = Color(0xFF262626), + headerBackground = panelEmphasis, + rowHover = hoverEmphasis, + rowStripe = Color(0xFF2B2B2B), + divider = chromeDeep, + panelBorder = Color(0xFF454545), + panelBorderHover = Color(0xFFA1A1A1), + controlBorder = Color(0xFF1A1A1A), + guideLine = mutedGreyDark, + treeGuideLine = mutedGreyDark.copy(alpha = 0.4f), + text = Color(0xFFE3E3E3), + textMuted = mutedGreyDark, + textDisabled = mutedGreyDark.copy(alpha = 0.3f), + accent = brandPurple, + accentHover = brandPurpleBright, + accentPressed = brandPurpleDim, + accentText = Color(0xFFFFFFFF), + selection = brandPurple, + selectionText = Color(0xFFFFFFFF), + controlBackground = Color(0xFF545454), + controlBackgroundHover = Color(0xFF696969), // The NumberField hover fill (a step lighter than the control fill). + controlGlyph = Color(0xFFFFFFFF), + keyedOnKey = keyframeOnKey, + keyedBetween = keyframeBetween, + keyedModified = keyframeModified, + keyedOnKeyBackground = keyframeOnKey.copy(alpha = KEYED_BACKGROUND_ALPHA), + keyedBetweenBackground = keyframeBetween.copy(alpha = KEYED_BACKGROUND_ALPHA), + keyedModifiedBackground = keyframeModified.copy(alpha = KEYED_BACKGROUND_ALPHA), + signalGood = signalGreen, + signalCaution = signalAmber, + signalBad = signalRed, + buttonHover = Color(0xFF656565), + buttonPressed = brandPurpleDim, + sliderTrack = Color(0xFF252525), + sliderThumb = Color(0xFFD2D2D2), + dropZoneFill = brandPurple.copy(alpha = 0.16f), + dropZoneEmphasis = brandPurple.copy(alpha = 0.28f), + dropTargetBackground = brandPurple.copy(alpha = 0.4f), + selectionAncestorBackground = brandPurple.copy(alpha = 0.5f), + searchMatchBackground = brandPurple.copy(alpha = 0.25f), + scrollbarThumb = mutedGreyDark.copy(alpha = 0.4f), + scrollbarThumbHover = mutedGreyDark.copy(alpha = 0.7f), + overlayScrim = Color(0x99000000), + viewportBadgeText = Color(0xFFE0E0E0), + viewportBadgeBackground = Color(0x99000000), + viewportMarquee = Color(0xCCFFFFFF), + // The dark tone that alternates with the white marquee so the marching-ants dash reads on light art. + viewportMarqueeContrast = Color(0xCC000000), + transparencyCheckerLight = Color(0xFF3C3C3C), + transparencyCheckerDark = Color(0xFF323232), + viewportGridBackground = Color(0xFF343434), + viewportGridLineMajor = Color(0xFF515151), + viewportGridLineMinor = Color(0xFF454545), + trackRegionBackground = Color(0xFF1F1F1F), + trackRowGroup = Color(0xFF2C4640), + trackRowPrimary = Color(0xFF39442C), + trackRowSecondary = Color(0xFF313640), + trackRowAlternate = Color(0xFF413043), + outlinerObjectTint = outlinerTanDark, + outlinerDeformTint = outlinerTealDark, + outlinerObjectTintDimmed = outlinerTanDark.copy(alpha = 0.2f), + outlinerDeformTintDimmed = outlinerTealDark.copy(alpha = 0.2f), + ) + +/** The light scheme: a designed grey ladder with the deepened purple accent (see the file comment). */ +val umamoLightColors = + UmamoColors( + windowBackground = Color(0xFFD4D4D4), + menuBackground = Color(0xFFFAFAFA), + panelBackground = Color(0xFFF4F4F4), + panelThirdElevation = Color(0xFFFFFFFF), + panelThirdElevationBorder = Color(0xFF6C6C6C), + tabBackground = Color(0xFFDDDDDD), + headerBackground = Color(0xFFFAFAFA), + rowHover = Color(0xFFE4E4E4), + rowStripe = Color(0xFFECECEC), + divider = Color(0xFFD4D4D4), + panelBorder = Color(0xFFB0B0B0), + panelBorderHover = Color(0xFF616161), + controlBorder = Color(0xFF9E9E9E), + guideLine = Color(0xFF8F8F8F), + treeGuideLine = mutedGreyLight.copy(alpha = 0.4f), + text = Color(0xFF202020), + textMuted = mutedGreyLight, + textDisabled = mutedGreyLight.copy(alpha = 0.3f), + accent = brandPurpleDeep, + accentHover = brandPurpleDeepBright, + accentPressed = brandPurpleDim, + accentText = Color(0xFFFFFFFF), + selection = Color(0xFFDCC3EA), + selectionText = Color(0xFF3B2144), + controlBackground = Color(0xFFDFDFDF), + controlBackgroundHover = Color(0xFFCECECE), // The NumberField hover fill; a subtle darken keeps dark text legible in the light theme. + controlGlyph = Color(0xFF2E2E2E), + keyedOnKey = keyframeOnKey, + keyedBetween = keyframeBetween, + keyedModified = keyframeModified, + keyedOnKeyBackground = keyframeOnKey.copy(alpha = KEYED_BACKGROUND_ALPHA), + keyedBetweenBackground = keyframeBetween.copy(alpha = KEYED_BACKGROUND_ALPHA), + keyedModifiedBackground = keyframeModified.copy(alpha = KEYED_BACKGROUND_ALPHA), + signalGood = signalGreen, + signalCaution = signalAmber, + signalBad = signalRed, + buttonHover = Color(0xFFEDEDED), + buttonPressed = brandPurpleDim, + sliderTrack = Color(0xFFDCDCDC), + sliderThumb = Color(0xFF505050), + dropZoneFill = brandPurpleDeep.copy(alpha = 0.16f), + dropZoneEmphasis = brandPurpleDeep.copy(alpha = 0.28f), + dropTargetBackground = brandPurpleDeep.copy(alpha = 0.45f), + selectionAncestorBackground = brandPurpleDeep.copy(alpha = 0.28f), + searchMatchBackground = brandPurpleDeep.copy(alpha = 0.14f), + scrollbarThumb = mutedGreyLight.copy(alpha = 0.4f), + scrollbarThumbHover = mutedGreyLight.copy(alpha = 0.7f), + overlayScrim = Color(0x55000000), + viewportBadgeText = Color(0xFFE0E0E0), + viewportBadgeBackground = Color(0x99000000), + // A white rubber band disappears on the light grid, so the marquee inverts with the theme. + viewportMarquee = Color(0xCC333333), + // The light tone that alternates with the dark marquee so the marching-ants dash reads on dark art. + viewportMarqueeContrast = Color(0xCCFFFFFF), + transparencyCheckerLight = Color(0xFFFFFFFF), + transparencyCheckerDark = Color(0xFFCCCCCC), + viewportGridBackground = Color(0xFFCFCFCF), + viewportGridLineMajor = Color(0xFFA8A8A8), + viewportGridLineMinor = Color(0xFFBEBEBE), + trackRegionBackground = Color(0xFFE8E8E8), + trackRowGroup = Color(0xFFCFE3DC), + trackRowPrimary = Color(0xFFDCE6CB), + trackRowSecondary = Color(0xFFDCE0E8), + trackRowAlternate = Color(0xFFE9D9EB), + outlinerObjectTint = outlinerTanLight, + outlinerDeformTint = outlinerTealLight, + outlinerObjectTintDimmed = outlinerTanLight.copy(alpha = 0.2f), + outlinerDeformTintDimmed = outlinerTealLight.copy(alpha = 0.2f), + ) + +/** The active palette for the composition (defaults to dark; [UmamoTheme] provides the resolved scheme). */ +val LocalUmamoColors = staticCompositionLocalOf { umamoDarkColors } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Cursor.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Cursor.kt new file mode 100644 index 0000000..926ef09 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Cursor.kt @@ -0,0 +1,1240 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Fill +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.withTransform +import androidx.compose.ui.graphics.vector.PathParser +import kotlin.math.max +import kotlin.math.min + +/** + * The stroked outline of one cursor layer: its color, line weight, and cap/join. Cursor art is drawn + * with a white body under a black outline so it stays legible over any canvas color, so a layer carries + * its own concrete colors rather than deriving them from a single caller tint the way the icon set does. + * + * @param Color color The stroke color. + * @param Float strokeWidth Line weight in the cursor's own viewport units (it scales with the art). + * @param StrokeCap cap End-cap style; round for the pen and finger-separator strokes, else butt. + * @param StrokeJoin join Corner style; round throughout the set to match the baked source art. + */ +data class CursorStroke( + val color: Color, + val strokeWidth: Float, + val cap: StrokeCap = StrokeCap.Butt, + val join: StrokeJoin = StrokeJoin.Round, +) + +/** + * One drawn element of a cursor: a vector path that may be filled, outlined, or both. The classic + * cursor silhouette is a single path filled white and then stroked black, which is why fill and stroke + * are independent and optional on the same path instead of being split across two layers. + * + * @param Path path The parsed vector outline, with its fill rule already applied. + * @param Color fill Solid fill color, or null to leave the path unfilled. + * @param CursorStroke stroke Outline description, or null to leave the path unstroked. + */ +data class CursorLayer( + val path: Path, + val fill: Color? = null, + val stroke: CursorStroke? = null, +) + +/** + * A cursor's hotspot as one point of a nine-point grid over its painted art: a horizontal anchor (left, + * center, or right) crossed with a vertical one (top, middle, or bottom). This is the point that tracks + * the pointer — the arrow's tip, a crosshair's center, an eyedropper's nib — so drawCursor places it + * exactly on the anchor the caller gives and the caller never offsets for it. The fractions address the + * art bounds, not the authored viewport, so a corner lands on the real tip. A coarse grid is a + * deliberately sensible default; a cursor that needs a pixel-exact hotspot can be refined later. + * + * @param Float fractionX Horizontal position within the art bounds (0 = left, 0.5 = center, 1 = right). + * @param Float fractionY Vertical position within the art bounds (0 = top, 0.5 = middle, 1 = bottom). + */ +enum class CursorHotspot(val fractionX: Float, val fractionY: Float) { + TopLeft(0f, 0f), + TopCenter(0.5f, 0f), + TopRight(1f, 0f), + MiddleLeft(0f, 0.5f), + MiddleCenter(0.5f, 0.5f), + MiddleRight(1f, 0.5f), + BottomLeft(0f, 1f), + BottomCenter(0.5f, 1f), + BottomRight(1f, 1f), +} + +/** + * A single themed vector cursor: its paint layers in draw order, the viewport their coordinates are + * authored in, the tight bounds of the painted art, and its hotspot. Unlike icons the viewport is not + * square (a north-south arrow is tall, an east-west arrow is wide) and the art rarely fills it to the + * edge, so the hotspot and the draw size are taken from [bounds] (the union of the layer paths) rather + * than the viewport; that way a corner hotspot lands on the real tip, not on empty authored margin. + * + * @param List layers The paint layers, drawn first to last. + * @param Float viewportWidth Width of the coordinate box the paths are authored in. + * @param Float viewportHeight Height of the coordinate box the paths are authored in. + * @param Rect bounds Tight bounding box of the painted art, in viewport units. + * @param CursorHotspot hotspot The point that tracks the pointer (see [CursorHotspot]). + */ +data class UmamoCursor( + val layers: List, + val viewportWidth: Float, + val viewportHeight: Float, + val bounds: Rect, + val hotspot: CursorHotspot = CursorHotspot.MiddleCenter, +) + +/** The bundled set of editor cursors, each a fully described [UmamoCursor]. */ +data class UmamoCursors( + val blade: UmamoCursor, + val bothHandles: UmamoCursor, + val crosshairContrast: UmamoCursor, + val crosshair: UmamoCursor, + val dot: UmamoCursor, + val eArrow: UmamoCursor, + val eraser: UmamoCursor, + val ewScroll: UmamoCursor, + val eyedropper: UmamoCursor, + val hSplit: UmamoCursor, + val hand: UmamoCursor, + val handClosed: UmamoCursor, + val handPoint: UmamoCursor, + val knife: UmamoCursor, + val leftHandle: UmamoCursor, + val mute: UmamoCursor, + val nArrow: UmamoCursor, + val nsScroll: UmamoCursor, + val nsewScroll: UmamoCursor, + val paint: UmamoCursor, + val pencil: UmamoCursor, + val pickArea: UmamoCursor, + val pointer: UmamoCursor, + val rightHandle: UmamoCursor, + val sArrow: UmamoCursor, + val slip: UmamoCursor, + val stop: UmamoCursor, + val swapArea: UmamoCursor, + val textEdit: UmamoCursor, + val vSplit: UmamoCursor, + val vertexLoop: UmamoCursor, + val wArrow: UmamoCursor, + val wait: UmamoCursor, + val xMove: UmamoCursor, + val yMove: UmamoCursor, + val zoomIn: UmamoCursor, + val zoomOut: UmamoCursor, +) + +/** + * Shorthand for an opaque 8-bit-per-channel color, used by the cursor table below for the handful of + * near-black and accent colors the source art carries alongside plain white and black. + * + * @param Int red Red channel, 0-255. + * @param Int green Green channel, 0-255. + * @param Int blue Blue channel, 0-255. + * @return Color The opaque color. + */ +private fun rgb(red: Int, green: Int, blue: Int): Color = Color(red = red, green = green, blue = blue) + +/** + * Builds one cursor layer from its SVG path data, applying the fill rule at parse time so the shape's + * holes render correctly. + * + * @param String pathData SVG "d" attribute contents; may hold several "M..." subpaths. + * @param Color fill Solid fill color, or null for an unfilled (stroke-only) path. + * @param CursorStroke stroke Outline description, or null for an unstroked (fill-only) path. + * @param Boolean evenOdd True to fill by the even-odd rule (holes); false for non-zero winding. + * @return CursorLayer The layer ready to compose into a [cursor]. + */ +private fun layer( + pathData: String, + fill: Color? = null, + stroke: CursorStroke? = null, + evenOdd: Boolean = false, +): CursorLayer { + val path = PathParser().parsePathString(pathData).toPath() + if (evenOdd) { + path.fillType = PathFillType.EvenOdd + } + return CursorLayer(path = path, fill = fill, stroke = stroke) +} + +/** + * Bundles a cursor's layers with the viewport they are authored in and its hotspot, measuring the tight + * bounds of the painted art from the layer paths so drawing can anchor to the real art, not the viewport. + * + * @param Float viewportWidth Width of the authored coordinate box. + * @param Float viewportHeight Height of the authored coordinate box. + * @param CursorLayer layers The paint layers, first to last. + * @param CursorHotspot hotspot The point that tracks the pointer; defaults to the art's center. + * @return UmamoCursor The assembled cursor. + */ +private fun cursor( + viewportWidth: Float, + viewportHeight: Float, + vararg layers: CursorLayer, + hotspot: CursorHotspot = CursorHotspot.MiddleCenter, +): UmamoCursor { + var left = Float.MAX_VALUE + var top = Float.MAX_VALUE + var right = -Float.MAX_VALUE + var bottom = -Float.MAX_VALUE + for (layer in layers) { + val layerBounds = layer.path.getBounds() + left = min(left, layerBounds.left) + top = min(top, layerBounds.top) + right = max(right, layerBounds.right) + bottom = max(bottom, layerBounds.bottom) + } + return UmamoCursor( + layers = layers.toList(), + viewportWidth = viewportWidth, + viewportHeight = viewportHeight, + bounds = Rect(left = left, top = top, right = right, bottom = bottom), + hotspot = hotspot, + ) +} + +/** + * The bundled cursor set, adapted from the Blender project's cursor art (GPL; see CREDITS.md). Like the + * icon set it is a plain top-level value referenced directly (for example LocalUmamoCursors.crosshair), + * kept so a per-theme override can layer on later without touching call sites. These feed edit mode, + * where the active tool chooses the pointer shape. + */ +val LocalUmamoCursors = + UmamoCursors( + blade = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M654.37,59.456L1538.09,943.172C1566.83,971.916 1573.3,1027.25 1538.09,1047.73C1482.75,1079.89 1440.09,1111.42 1480.24,1146.9C1500.89,1166.4 1500.89,1199.26 1480.24,1218.76L1213.45,1485.55C1193.98,1506.28 1161.06,1506.28 1141.59,1485.55C1106.47,1445.21 1079.61,1483.03 1047.45,1538.36C1026.97,1573.4 971.639,1567.11 942.894,1538.36L59.178,654.648C30.198,625.471 30.48,578.289 59.807,549.461C103.103,506.164 158.167,500.865 109.571,452.268C89.727,432.424 89.727,400.251 109.571,380.407L375.997,113.981C395.841,94.137 428.014,94.137 447.858,113.981C496.455,162.577 506.785,102.483 550.081,59.186C579.054,30.705 625.545,30.825 654.37,59.456Z", + fill = Color.White, + stroke = CursorStroke(Color.Black, 75.21f), + evenOdd = true, + ), + layer( + "M490.484,307.419C501.864,318.349 500.45,338.202 487.313,351.953L451.555,387.623C451.989,404.435 458.586,419.394 470.147,429.778C478.624,438.735 489.712,444.898 502.348,447.675C537.197,432.251 574.183,437.25 596.953,460.462C610.392,473.828 618.04,492.223 618.679,512.715C619.125,527.7 612.755,545.075 614.908,558.696C617.477,571.676 623.645,583.079 632.779,591.735C643.916,604.28 660.473,610.918 678.852,610.207L712.151,576.99C725.914,563.816 745.844,562.433 756.726,573.897C768.016,584.85 766.567,604.635 753.47,618.346L717.712,654.016C718.122,670.836 724.723,685.802 736.304,696.17C744.835,705.359 756.081,711.675 768.929,714.492C803.778,699.068 840.765,704.067 863.534,727.279C876.985,740.59 884.61,758.972 885.175,779.447C886.253,815.335 864.066,860.696 924.068,861.373L960.236,825.294C973.999,812.121 993.93,810.738 1004.81,822.201C1016.19,833.131 1014.78,852.984 1001.64,866.735L965.882,902.405C966.606,919.103 973.166,933.976 984.474,944.56C995.079,955.175 1026.11,981.527 1037.97,983.771C1072.78,968.334 1109.73,973.301 1132.49,996.474C1145.99,1009.79 1153.65,1028.21 1154.22,1048.73C1154.66,1063.71 1148.29,1081.09 1150.53,1094.79C1153.08,1107.79 1159.25,1119.19 1168.4,1127.83C1179.54,1140.38 1196.1,1147.02 1214.48,1146.3L1247.77,1113.09C1261.56,1099.98 1281.43,1098.6 1292.35,1109.99C1303.73,1120.92 1302.32,1140.78 1289.18,1154.53L1154.04,1289.34C1140.25,1302.44 1120.38,1303.82 1109.46,1292.43C1098.08,1281.5 1099.49,1261.65 1112.63,1247.9L1147.98,1212.63C1148.72,1194.27 1142.11,1177.72 1129.57,1166.57C1121.24,1157.7 1110.3,1151.61 1097.81,1148.91C1081.77,1145.75 1069.01,1153.05 1051.86,1152.87C1030.48,1152.7 1011.21,1145.05 997.263,1131.2C974.809,1107.63 970.067,1070.77 984.986,1035.78C982.657,1024.03 956.488,993.332 945.967,982.802C935.322,971.575 920.478,965.01 903.81,964.154L866.412,1001.46C852.628,1014.56 832.757,1015.94 821.838,1004.55C810.458,993.623 811.871,973.77 825.008,960.019L863.225,921.896C862.101,862.825 818.066,883.863 782.728,883.507C761.365,883.313 742.095,875.662 728.137,861.833C705.672,838.236 700.9,801.368 715.774,766.329C712.884,754.02 706.748,743.231 697.931,734.957C687.577,723.251 672.609,716.475 655.725,715.85L618.327,753.155C604.543,766.258 584.672,767.637 573.752,756.248C562.298,745.356 563.716,725.444 576.923,711.714L612.271,676.453C612.901,658.278 606.312,641.91 593.912,630.845C585.553,621.948 574.582,615.835 562.068,613.101C546.315,609.825 533.644,617.208 516.656,617.199C495.293,617.005 476.023,609.355 462.064,595.525C439.629,571.911 434.858,535.06 449.702,500.021C446.778,487.544 440.52,476.629 431.52,468.309C421.098,456.801 406.159,450.193 389.363,449.662L351.965,486.967C338.181,500.07 318.31,501.449 307.39,490.06C296.01,479.131 297.424,459.277 310.561,445.526L445.909,310.513C459.693,297.409 479.564,296.03 490.484,307.419L490.484,307.419Z", + fill = Color.Black, + evenOdd = true, + ), + ), + bothHandles = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M1238.16,465.813C1200.45,470.321 1172.07,502.298 1172.06,540.271L1172.06,1061.73C1172.07,1091.6 1189.8,1118.63 1217.21,1130.52C1244.62,1142.41 1276.48,1136.9 1298.3,1116.49L1576.97,855.764C1608.65,826.122 1608.65,775.87 1576.97,746.229L1298.3,485.504C1282.14,470.391 1260.13,463.185 1238.16,465.813Z", + fill = Color.Black, + ), + layer( + "M1247.06,540.272L1525.73,800.996L1247.06,1061.73L1247.06,540.272Z", + fill = Color.White, + ), + layer( + "M247.986,0.289C175.62,0.289 115.709,54.825 115.709,128.691L115.709,182.094C115.709,255.96 175.62,310.498 247.986,310.498L346.342,310.498C376.809,310.498 394.666,318.557 405.932,329.455C417.197,340.354 426.975,357.561 426.975,395.707L426.975,1207.33C426.975,1248.59 417.796,1266.45 409.27,1275.23C400.743,1284 385.352,1292.54 346.342,1292.54L242.586,1292.54C170.22,1292.54 115.373,1356.24 115.373,1420.94L115.373,1474.34C115.373,1512.4 132.13,1542.6 153.846,1564.37C175.561,1586.14 204.519,1602.75 242.586,1602.75L398.219,1602.75C493.192,1602.75 579.877,1568.75 640.363,1506.65C700.849,1444.55 733.187,1356.83 732.605,1260.28L732.607,1260.73L732.607,342.303C732.607,246.008 700.388,158.55 640.07,96.459C579.753,34.368 493.192,0.289 398.219,0.289L247.986,0.289Z", + fill = Color.Black, + ), + layer( + "M247.987,75.289C216.254,75.289 190.709,101.077 190.709,128.691L190.709,182.095C190.709,209.709 216.254,235.498 247.987,235.498L346.342,235.498C436.795,235.498 501.974,288.9 501.974,395.706L501.974,1207.33C501.974,1314.13 450.097,1367.54 346.342,1367.54L242.587,1367.54C210.853,1367.54 190.372,1393.33 190.372,1420.94L190.372,1474.35C190.372,1501.96 217.156,1527.75 242.587,1527.75L398.219,1527.75C553.852,1527.75 658.571,1420.94 657.607,1260.73L657.607,342.303C657.607,182.095 553.852,75.289 398.219,75.289L247.987,75.289Z", + fill = Color.White, + ), + layer( + "M362.238,465.813C340.269,463.185 318.26,470.391 302.1,485.504L23.426,746.229C-8.25,775.87 -8.251,826.121 23.424,855.764L302.1,1116.49C323.922,1136.9 355.775,1142.41 383.184,1130.52C410.594,1118.63 428.332,1091.6 428.34,1061.73L428.34,540.271C428.331,502.298 399.944,470.321 362.238,465.813Z", + fill = Color.Black, + ), + layer( + "M353.34,1061.73L74.665,800.996L353.34,540.272L353.34,1061.73Z", + fill = Color.White, + ), + layer( + "M1200.55,0.289C1105.58,0.289 1018.89,34.287 958.404,96.387C897.918,158.486 865.583,246.211 866.164,342.756L866.162,342.303L866.162,1260.73C866.162,1357.03 898.38,1444.49 958.697,1506.58C1019.01,1568.67 1105.58,1602.75 1200.55,1602.75L1350.78,1602.75C1423.15,1602.75 1483.06,1548.21 1483.06,1474.34L1483.06,1420.94C1483.06,1347.08 1423.15,1292.54 1350.78,1292.54L1252.43,1292.54C1221.96,1292.54 1204.1,1284.48 1192.84,1273.58C1181.57,1262.68 1171.8,1245.48 1171.8,1207.33L1171.8,395.707C1171.8,354.447 1180.97,336.586 1189.5,327.809C1198.02,319.032 1213.42,310.498 1252.43,310.498L1356.18,310.498C1428.55,310.498 1483.4,246.793 1483.4,182.094L1483.4,128.691C1483.4,90.636 1466.64,60.434 1444.92,38.666C1423.21,16.898 1394.25,0.289 1356.18,0.289L1200.55,0.289Z", + fill = Color.Black, + ), + layer( + "M1350.78,1527.75C1382.52,1527.75 1408.06,1501.96 1408.06,1474.35L1408.06,1420.94C1408.06,1393.33 1382.52,1367.54 1350.78,1367.54L1252.43,1367.54C1161.97,1367.54 1096.79,1314.13 1096.79,1207.33L1096.79,395.706C1096.79,288.9 1148.67,235.498 1252.43,235.498L1356.18,235.498C1387.91,235.498 1408.4,209.709 1408.4,182.095L1408.4,128.691C1408.4,101.077 1381.61,75.289 1356.18,75.289L1200.55,75.289C1044.92,75.289 940.197,182.095 941.162,342.303L941.162,1260.73C941.162,1420.94 1044.92,1527.75 1200.55,1527.75L1350.78,1527.75Z", + fill = Color.White, + ), + ), + crosshairContrast = + cursor( + viewportWidth = 1500f, + viewportHeight = 1500f, + layer( + "M679.966,499.983L820.03,499.976L820.051,630.066L679.964,630.091L679.966,499.983Z", + fill = Color.Black, + ), + layer( + "M679.973,299.992L820.02,299.985L820.042,399.968L679.97,399.992L679.973,299.992Z", + fill = Color.Black, + ), + layer( + "M679.979,100.029L820.026,100.022L820.048,200.004L679.976,200.029L679.979,100.029Z", + fill = Color.Black, + ), + layer( + "M679.982,400.013L820.029,400.006L820.051,499.989L679.979,500.013L679.982,400.013Z", + fill = Color.White, + ), + layer( + "M679.976,199.994L820.024,199.987L820.046,299.97L679.974,299.994L679.976,199.994Z", + fill = Color.White, + ), + layer( + "M679.971,-0.001L820.019,-0.008L820.041,99.976L679.968,100L679.971,-0.001Z", + fill = Color.White, + ), + layer( + "M680.059,1299.92L819.94,1299.91L819.962,1399.89L680.056,1399.92L680.059,1299.92Z", + fill = Color.Black, + ), + layer( + "M680.05,1099.93L819.931,1099.92L819.953,1199.9L680.047,1199.93L680.05,1099.93Z", + fill = Color.Black, + ), + layer( + "M680.056,870.139L819.937,870.132L819.959,999.943L680.053,999.967L680.056,870.139Z", + fill = Color.Black, + ), + layer( + "M680.034,1399.93L819.915,1399.92L819.937,1499.9L680.031,1499.93L680.034,1399.93Z", + fill = Color.White, + ), + layer( + "M680.059,1199.95L819.94,1199.94L819.962,1299.92L680.056,1299.95L680.059,1199.95Z", + fill = Color.White, + ), + layer( + "M680.053,999.932L819.935,999.922L819.957,1099.9L680.051,1099.93L680.053,999.932Z", + fill = Color.White, + ), + layer( + "M999.997,680.014L1000.01,820.062L869.917,820.084L869.893,680.012L999.997,680.014Z", + fill = Color.Black, + ), + layer( + "M1199.99,680.005L1200,820.053L1100.02,820.075L1099.99,680.003L1199.99,680.005Z", + fill = Color.Black, + ), + layer( + "M1399.95,680.011L1399.96,820.059L1299.98,820.081L1299.96,680.008L1399.95,680.011Z", + fill = Color.Black, + ), + layer( + "M1099.97,680.014L1099.98,820.062L999.994,820.084L999.97,680.012L1099.97,680.014Z", + fill = Color.White, + ), + layer( + "M1299.99,680.009L1300,820.056L1200.02,820.078L1199.99,680.006L1299.99,680.009Z", + fill = Color.White, + ), + layer( + "M1499.98,680.003L1499.99,820.051L1400.01,820.073L1399.99,680.001L1499.98,680.003Z", + fill = Color.White, + ), + layer( + "M199.951,679.964L199.961,820.012L99.979,820.034L99.955,679.962L199.951,679.964Z", + fill = Color.Black, + ), + layer( + "M399.945,679.955L399.955,820.003L299.972,820.025L299.948,679.952L399.945,679.955Z", + fill = Color.Black, + ), + layer( + "M630.016,679.961L630.026,820.008L499.936,820.03L499.912,679.958L630.016,679.961Z", + fill = Color.Black, + ), + layer( + "M99.944,679.939L99.954,819.986L-0.029,820.008L-0.053,679.936L99.944,679.939Z", + fill = Color.White, + ), + layer( + "M299.924,679.964L299.934,820.011L199.948,820.033L199.924,679.961L299.924,679.964Z", + fill = Color.White, + ), + layer( + "M499.943,679.958L499.953,820.006L399.97,820.028L399.946,679.956L499.943,679.958Z", + fill = Color.White, + ), + layer( + "M749.739,599.854C667.55,599.997 600,667.665 600,749.854C600,749.962 600,750.069 600,750.176C600.143,832.266 667.649,899.772 749.739,899.915C749.847,899.915 749.954,899.915 750.061,899.915C832.25,899.915 899.918,832.365 900.061,750.176C900.061,750.069 900.061,749.961 900.061,749.854C900.061,667.566 832.349,599.854 750.061,599.854C749.954,599.854 749.847,599.854 749.739,599.854Z", + fill = Color.White, + ), + layer( + "M749.739,677.928C708.694,678.159 675.073,712.043 675.161,753.089C675.39,793.914 708.914,827.438 749.739,827.667C790.785,827.756 824.67,794.134 824.9,753.089C824.9,753.035 824.9,752.982 824.9,752.928C824.9,711.784 791.044,677.928 749.9,677.928C749.847,677.928 749.793,677.928 749.739,677.928Z", + fill = Color.Black, + ), + ), + crosshair = + cursor( + viewportWidth = 1200f, + viewportHeight = 1200f, + layer( + "M520.001,0.002L520.002,440.002L680.004,440.003L680.004,0.003L520.001,0.002Z", + fill = Color.White, + ), + layer( + "M0.002,520.004L520.002,519.999L520,0.002L440.001,0.01L440.001,439.999L0.005,440L0.002,520.004Z", + fill = Color.Black, + ), + layer( + "M1200,520.004L759.999,520.005L759.998,680.007L1200,680.007L1200,520.004Z", + fill = Color.White, + ), + layer( + "M679.997,0.005L680.002,520.005L1200,520.003L1199.99,440.004L760,440.004L759.999,0.008L679.997,0.005Z", + fill = Color.Black, + ), + layer( + "M0.004,680.003L440.004,680.002L440.005,520L0.005,520L0.004,680.003Z", + fill = Color.White, + ), + layer( + "M520.006,1200L520.001,680.002L0.004,680.004L0.012,760.002L440.001,760.003L440.002,1200L520.006,1200Z", + fill = Color.Black, + ), + layer( + "M680.003,1199.99L680.002,759.993L520,759.992L520,1199.99L680.003,1199.99Z", + fill = Color.White, + ), + layer( + "M1200,679.991L680.002,680.001L680.004,1200L760.002,1199.99L760.003,759.999L1200,759.998L1200,679.991Z", + fill = Color.Black, + ), + ), + dot = + cursor( + viewportWidth = 300f, + viewportHeight = 300f, + layer( + "M149.933,0.164C67.744,0.307 0.193,67.975 0.193,150.164C0.193,150.271 0.193,150.378 0.194,150.486C0.337,232.576 67.842,300.082 149.933,300.225C150.04,300.225 150.147,300.225 150.254,300.225C232.443,300.225 300.111,232.675 300.254,150.486C300.255,150.378 300.255,150.271 300.255,150.164C300.255,67.876 232.542,0.163 150.254,0.163C150.147,0.163 150.04,0.164 149.933,0.164Z", + fill = Color.Black, + ), + layer( + "M149.933,78.238C108.888,78.469 75.266,112.353 75.354,153.399C75.583,194.224 109.107,227.748 149.933,227.977C190.978,228.066 224.863,194.444 225.094,153.399C225.094,153.345 225.094,153.291 225.094,153.238C225.094,112.094 191.238,78.238 150.094,78.238C150.04,78.238 149.986,78.238 149.933,78.238Z", + fill = Color.White, + ), + ), + eArrow = + cursor( + viewportWidth = 1058f, + viewportHeight = 1600f, + layer( + "M257.94,1550.45L1008.38,800.018L257.94,49.581L49.485,258.036L591.467,800.018L49.485,1342L257.94,1550.45", + fill = Color.White, + ), + layer( + "M292.654,1585.29L1043.58,834.977C1063.08,815.649 1063.08,784.134 1043.58,764.808L292.654,14.495C273.398,-4.594 242.357,-4.594 223.101,14.495L14.441,223.154C-4.646,242.41 -4.646,273.452 14.441,292.707L521.626,799.892L14.441,1307.08C-4.646,1326.33 -4.646,1357.37 14.441,1376.63L223.101,1585.29C242.356,1604.38 273.4,1604.38 292.654,1585.29ZM257.57,1480.65L119.079,1342.16L661.481,800.025L119.079,258.239L258.186,119.748L938.33,799.892L257.57,1480.65Z", + fill = Color.Black, + ), + ), + eraser = + cursor( + viewportWidth = 1600f, + viewportHeight = 1480f, + layer( + "M120.184,1120.55L120.184,1360.62L600.323,1360.62L1160.49,800.458L1480.58,480.365L1120.48,120.26L120.185,1120.55", + fill = Color.White, + stroke = CursorStroke(Color.White, 240.07f, cap = StrokeCap.Round), + ), + layer( + "M152.452,1332.56L588.349,1331.12L1022.54,894.749L704.089,576.578L150.517,1125.47L150.347,1331.86", + fill = Color.White, + stroke = CursorStroke(rgb(13, 13, 13), 100f, cap = StrokeCap.Round), + ), + layer( + "M831.277,437.279L1162.14,771.286L1453.75,481.193L1120.47,146.211L830.859,436.056", + fill = Color.Black, + stroke = CursorStroke(rgb(13, 13, 13), 80.02f, cap = StrokeCap.Round), + ), + hotspot = CursorHotspot.TopRight, + ), + ewScroll = + cursor( + viewportWidth = 1600f, + viewportHeight = 700f, + layer( + "M527.305,485.195L393.843,351.734L527.305,218.272L349.356,40.323L37.946,351.734L349.356,663.144L527.305,485.195", + fill = Color.White, + stroke = CursorStroke(Color.Black, 75f, cap = StrokeCap.Round), + ), + layer( + "M1072.56,216.576L1206.03,350.037L1072.56,483.499L1250.51,661.448L1561.92,350.037L1250.51,38.627L1072.56,216.576", + fill = Color.White, + stroke = CursorStroke(Color.Black, 75f, cap = StrokeCap.Round), + ), + ), + eyedropper = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M48.734,1555.91L48.734,1316.18L194.555,1302.18L194.555,1142.36L793.883,543.034L927.749,676.9", + fill = Color.White, + stroke = CursorStroke(Color.Black, 100f, cap = StrokeCap.Round), + ), + layer( + "M48.735,1555.91L288.467,1555.91L302.465,1410.09L462.286,1410.09L1061.62,810.766L927.749,676.9", + fill = Color.White, + stroke = CursorStroke(Color.Black, 100f, cap = StrokeCap.Round), + ), + layer( + "M448.286,1156.36L767.928,836.72", + stroke = CursorStroke(Color.Black, 100f, cap = StrokeCap.Round), + ), + layer( + "M847.838,277.346L1327.3,756.809L1167.48,916.63L688.018,437.167L847.839,277.347", + fill = Color.White, + stroke = CursorStroke(Color.Black, 100f, cap = StrokeCap.Round), + ), + layer( + "M1330.58,51.352C1269.53,50.467 1210.65,74.355 1167.48,117.528L927.748,357.259L1247.39,676.901L1487.12,437.17C1574.8,349.495 1574.8,205.203 1487.12,117.528C1445.55,75.959 1389.36,52.205 1330.58,51.352Z", + fill = Color.White, + stroke = CursorStroke(rgb(19, 19, 19), 100f, cap = StrokeCap.Round), + ), + hotspot = CursorHotspot.BottomLeft, + ), + hSplit = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M1547.91,528.922C1547.91,617.064 1473.78,688.023 1381.7,688.023L218.217,688.023C126.137,688.022 52.007,617.063 52.007,528.921", + fill = Color.White, + stroke = CursorStroke(rgb(13, 13, 13), 103.5f, cap = StrokeCap.Round), + ), + layer( + "M467.532,361.324L799.957,51.614L1132.38,361.324L966.168,520.426L799.957,369.818L633.746,520.426L463.026,361.324", + fill = Color.White, + stroke = CursorStroke(Color.Black, 103.5f, cap = StrokeCap.Round), + ), + layer( + "M1547.91,1066.19C1547.91,978.053 1473.78,907.094 1381.7,907.094L218.217,907.094C126.137,907.094 52.007,978.054 52.007,1066.2", + fill = Color.White, + stroke = CursorStroke(rgb(13, 13, 13), 103.5f, cap = StrokeCap.Round), + ), + layer( + "M467.532,1236.59L799.957,1546.3L1132.38,1236.59L966.168,1077.49L799.957,1228.1L633.746,1077.49L463.026,1236.59", + fill = Color.White, + stroke = CursorStroke(Color.Black, 103.5f, cap = StrokeCap.Round), + ), + ), + hand = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M449.761,838.543C439.916,800.95 430.072,753.626 408.976,682.937C392.2,627.087 374.62,596.814 361.761,559.312C346.19,513.693 331.323,487.023 311.934,440.902C297.971,407.916 275.368,335.827 266.025,296.523C254.071,245.49 269.34,203.88 290.537,175.607C315.953,141.617 387.177,126.478 426.857,140.414C464.126,153.448 501.597,191.749 518.876,219.421C547.807,265.543 554.739,282.788 590.903,374.027C630.381,473.488 647.563,566.33 652.282,597.709L660.784,650.008C660.91,650.754 660.784,650.787 660.784,650.025C657.262,546.856 650.369,343.747 652.577,231.854C652.779,219.221 659.006,173 661.012,160.166C668.848,110.034 691.65,79.956 728.626,62.008C770.008,41.856 821.645,40.453 869.364,60.304C911.859,77.65 932.251,115.449 938.377,162.773C939.784,173.701 947.823,261.733 947.722,273.764C946.416,376.534 948.32,438.295 949.222,491.736C949.627,514.897 949.525,654.665 950.933,639.021C957.059,573.248 960.379,319.284 985.489,243.785C999.958,200.372 1026.17,168.989 1065.26,150.642C1108.55,130.288 1177.07,143.623 1206.3,175.005C1234.93,205.585 1251.1,244.387 1254.72,290.609C1257.93,331.215 1252.81,380.544 1252.71,415.435C1252.71,502.363 1250.6,548.184 1249,628.092C1248.89,631.903 1247.49,657.972 1251.3,646.34C1260.74,618.269 1270.19,591.998 1278.02,571.648C1282.94,559.112 1302.23,510.084 1314.09,485.519C1325.54,462.058 1335.28,448.522 1355.78,416.538C1375.87,385.157 1397.47,371.621 1422.88,360.291C1477.13,336.73 1534.29,371.52 1553.58,419.546C1562.22,441.103 1554.48,491.034 1550.76,530.337C1544.64,595.206 1525.25,661.28 1515.41,695.574C1502.55,740.386 1487.88,819.399 1481.25,856.088C1474.02,895.599 1457.74,994.652 1445.18,1038.57C1436.54,1068.75 1407.92,1136.62 1379.69,1177.33C1379.69,1177.33 1271.8,1302.67 1259.94,1359.01C1248.18,1415.46 1252.1,1415.86 1249.8,1455.76C1248.09,1484.02 1254.86,1518.53 1258.98,1536.37C1260.45,1542.71 1256.17,1549.03 1249.66,1549.72C1225.43,1552.31 1170.97,1557.05 1137.98,1551.72C1098.71,1545.5 1050.09,1467.39 1037.53,1443.63C1020.25,1410.75 983.383,1417.06 969.016,1441.32C946.416,1479.73 897.795,1548.61 863.432,1552.92C798.928,1561.01 667.77,1556.33 560.894,1555.06C554.204,1554.98 549.122,1548.93 549.921,1542.34C553.341,1514.1 557.71,1446.01 525.297,1418.77C494.657,1392.7 441.918,1340.16 410.374,1312.49L326.794,1220.14C298.264,1184.05 263.606,1110.56 201.925,1021.12C166.966,970.593 98.756,912.34 72.939,862.813C50.537,820.195 39.687,767.16 53.852,729.96C76.454,670.401 121.66,640.026 190.674,646.542C242.811,651.558 275.862,667.193 315.04,700.382C337.643,719.433 372.602,753.928 390.383,775.383C406.757,794.93 410.776,803.053 428.255,826.418C451.36,857.194 458.594,872.435 449.753,838.544L449.761,838.543Z", + fill = Color.White, + evenOdd = true, + ), + layer( + "M449.761,838.543C439.916,800.95 430.072,753.626 408.976,682.937C392.2,627.087 374.62,596.814 361.761,559.312C346.19,513.693 331.323,487.023 311.934,440.902C297.971,407.916 275.368,335.827 266.025,296.523C254.071,245.49 269.34,203.88 290.537,175.607C315.953,141.617 387.177,126.478 426.857,140.414C464.126,153.448 501.597,191.749 518.876,219.421C547.807,265.543 554.739,282.788 590.903,374.027C630.381,473.488 647.563,566.33 652.282,597.709L660.784,650.008C660.91,650.754 660.784,650.787 660.784,650.025C657.262,546.856 650.369,343.747 652.577,231.854C652.779,219.221 659.006,173 661.012,160.166C668.848,110.034 691.65,79.956 728.626,62.008C770.008,41.856 821.645,40.453 869.364,60.304C911.859,77.65 932.251,115.449 938.377,162.773C939.784,173.701 947.823,261.733 947.722,273.764C946.416,376.534 948.32,438.295 949.222,491.736C949.627,514.897 949.525,654.665 950.933,639.021C957.059,573.248 960.379,319.284 985.489,243.785C999.958,200.372 1026.17,168.989 1065.26,150.642C1108.55,130.288 1177.07,143.623 1206.3,175.005C1234.93,205.585 1251.1,244.387 1254.72,290.609C1257.93,331.215 1252.81,380.544 1252.71,415.435C1252.71,502.363 1250.6,548.184 1249,628.092C1248.89,631.903 1247.49,657.972 1251.3,646.34C1260.74,618.269 1270.19,591.998 1278.02,571.648C1282.94,559.112 1302.23,510.084 1314.09,485.519C1325.54,462.058 1335.28,448.522 1355.78,416.538C1375.87,385.157 1397.47,371.621 1422.88,360.291C1477.13,336.73 1534.29,371.52 1553.58,419.546C1562.22,441.103 1554.48,491.034 1550.76,530.337C1544.64,595.206 1525.25,661.28 1515.41,695.574C1502.55,740.386 1487.88,819.399 1481.25,856.088C1474.02,895.599 1457.74,994.652 1445.18,1038.57C1436.54,1068.75 1407.92,1136.62 1379.69,1177.33C1379.69,1177.33 1271.8,1302.67 1259.94,1359.01C1248.18,1415.46 1252.1,1415.86 1249.8,1455.76C1248.09,1484.02 1254.86,1518.53 1258.98,1536.37C1260.45,1542.71 1256.17,1549.03 1249.66,1549.72C1225.43,1552.31 1170.97,1557.05 1137.98,1551.72C1098.71,1545.5 1050.09,1467.39 1037.53,1443.63C1020.25,1410.75 983.383,1417.06 969.016,1441.32C946.416,1479.73 897.795,1548.61 863.432,1552.92C798.928,1561.01 667.77,1556.33 560.894,1555.06C554.204,1554.98 549.122,1548.93 549.921,1542.34C553.341,1514.1 557.71,1446.01 525.297,1418.77C494.657,1392.7 441.918,1340.16 410.374,1312.49L326.794,1220.14C298.264,1184.05 263.606,1110.56 201.925,1021.12C166.966,970.593 98.756,912.34 72.939,862.813C50.537,820.195 39.687,767.16 53.852,729.96C76.454,670.401 121.66,640.026 190.674,646.542C242.811,651.558 275.862,667.193 315.04,700.382C337.643,719.433 372.602,753.928 390.383,775.383C406.757,794.93 410.776,803.053 428.255,826.418C451.36,857.194 458.594,872.435 449.753,838.544L449.761,838.543Z", + stroke = CursorStroke(Color.Black, 86.02f), + ), + layer( + "M1151.35,1266.32L1151.35,938.999", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + layer( + "M950.855,1266.55L950.855,939.415", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + layer( + "M751.102,939.311L751.102,1266.45", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + ), + handClosed = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M377.499,343.73C426.451,324.911 523.028,336.435 548.526,393.738C570.245,442.584 650.115,607.62 651.136,590.072C653.581,551.059 648.69,466.69 665.105,422.602C677.041,390.461 700.493,360.224 735.071,349.545C764.135,340.453 798.3,337.282 828.482,343.731C860.404,350.497 893.954,374.074 906.497,396.488C943.416,462.355 944.032,597.261 945.765,590.072C952.292,561.314 952.899,460.135 974.625,422.602C988.999,397.757 1025.31,375.554 1044.68,371.96C1074.67,366.462 1111.59,364.77 1143,371.113C1168.38,376.294 1202.76,407.483 1212.04,422.602C1234.38,458.972 1246.92,561.737 1250.68,597.895C1252.32,612.803 1258.23,556.345 1280.57,520.081C1321.97,452.523 1468.62,439.413 1474.13,587.64C1476.78,656.783 1476.17,653.616 1476.17,700.131C1476.17,754.687 1474.95,787.671 1472.09,827.213C1469.03,869.395 1460.26,965.081 1447.51,1011.39C1438.74,1043.21 1409.68,1114.79 1380.92,1157.72C1380.92,1157.72 1271.39,1289.87 1259.46,1349.29C1247.53,1408.81 1251.5,1409.23 1249.06,1451.32C1247.36,1481.74 1254.53,1519.05 1258.66,1537.48C1260.02,1543.56 1255.96,1549.6 1249.76,1550.3C1225.62,1553 1169.49,1558.18 1135.55,1552.49C1095.67,1545.93 1046.32,1463.68 1033.57,1438.52C1016.03,1403.84 978.601,1410.5 964.017,1436.09C941.173,1476.58 891.711,1549.21 856.938,1553.77C791.198,1562.32 657.574,1557.33 548.939,1556.01C542.534,1555.93 537.651,1550.17 538.42,1543.81C541.902,1514.81 546.923,1441.43 513.561,1412.3C482.457,1384.81 428.916,1329.41 396.894,1300.23L312.045,1202.85C283.184,1164.79 209.858,1104.64 185.28,992.995C163.558,894.029 165.7,845.506 189.054,805.859C212.714,765.579 257.382,743.585 276.147,739.779C297.359,735.341 346.719,735.657 365.381,746.33C388.124,759.336 397.302,763.142 415.149,787.671C438.605,820.127 446.967,835.886 436.871,800.465C429.121,772.762 404.033,737.56 392.611,697.913C381.495,659.747 290.508,515.535 292.65,453.897C293.466,430.532 303.154,372.382 377.499,343.73Z", + fill = Color.White, + evenOdd = true, + ), + layer( + "M377.499,343.73C426.451,324.911 523.028,336.435 548.526,393.738C570.245,442.584 650.115,607.62 651.136,590.072C653.581,551.059 648.69,466.69 665.105,422.602C677.041,390.461 700.493,360.224 735.071,349.545C764.135,340.453 798.3,337.282 828.482,343.731C860.404,350.497 893.954,374.074 906.497,396.488C943.416,462.355 944.032,597.261 945.765,590.072C952.292,561.314 952.899,460.135 974.625,422.602C988.999,397.757 1025.31,375.554 1044.68,371.96C1074.67,366.462 1111.59,364.77 1143,371.113C1168.38,376.294 1202.76,407.483 1212.04,422.602C1234.38,458.972 1246.92,561.737 1250.68,597.895C1252.32,612.803 1258.23,556.345 1280.57,520.081C1321.97,452.523 1468.62,439.413 1474.13,587.64C1476.78,656.783 1476.17,653.616 1476.17,700.131C1476.17,754.687 1474.95,787.671 1472.09,827.213C1469.03,869.395 1460.26,965.081 1447.51,1011.39C1438.74,1043.21 1409.68,1114.79 1380.92,1157.72C1380.92,1157.72 1271.39,1289.87 1259.46,1349.29C1247.53,1408.81 1251.5,1409.23 1249.06,1451.32C1247.36,1481.74 1254.53,1519.05 1258.66,1537.48C1260.02,1543.56 1255.96,1549.6 1249.76,1550.3C1225.62,1553 1169.49,1558.18 1135.55,1552.49C1095.67,1545.93 1046.32,1463.68 1033.57,1438.52C1016.03,1403.84 978.601,1410.5 964.017,1436.09C941.173,1476.58 891.711,1549.21 856.938,1553.77C791.198,1562.32 657.574,1557.33 548.939,1556.01C542.534,1555.93 537.651,1550.17 538.42,1543.81C541.902,1514.81 546.923,1441.43 513.561,1412.3C482.457,1384.81 428.916,1329.41 396.894,1300.23L312.045,1202.85C283.184,1164.79 209.858,1104.64 185.28,992.995C163.558,894.029 165.7,845.506 189.054,805.859C212.714,765.579 257.382,743.585 276.147,739.779C297.359,735.341 346.719,735.657 365.381,746.33C388.124,759.336 397.302,763.142 415.149,787.671C438.605,820.127 446.967,835.886 436.871,800.465C429.121,772.762 404.033,737.56 392.611,697.913C381.495,659.747 290.508,515.535 292.65,453.897C293.466,430.532 303.154,372.382 377.499,343.73Z", + stroke = CursorStroke(Color.Black, 82.92f), + ), + layer( + "M1150.13,1264.13L1150.13,936.812", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + layer( + "M949.636,1264.36L949.636,937.227", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + layer( + "M749.882,937.124L749.882,1264.26", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + ), + handPoint = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M348.563,1238.14C318.526,1203.4 282.038,1132.38 217.1,1046.16C180.294,997.392 89.02,905.563 61.839,858.921C38.254,817.696 40.792,799.22 46.398,765.059C56.34,704.29 124.451,656.976 197.111,663.358C252.001,668.105 298.537,701.293 340.42,732.646C397.368,775.154 424.689,844.157 455.044,907.561C461.539,921.128 465.488,925.874 463.099,910.602C455.632,862.874 371.413,433.107 370.467,428.283L370.414,428.018L328.711,216.301C314.043,141.845 346.303,54.111 423.395,44.939C499.827,35.847 570.41,84.792 590.579,157.338L634.826,316.479C637.976,327.814 640.516,339.138 642.493,350.724C653.407,414.832 691.107,636.639 692.457,651.584C692.227,643.565 690.965,580.031 689.854,523.39C688.742,466.73 722.675,423.936 780.72,423.936C921.886,423.936 980.293,497.324 980.293,535.912C980.293,479.924 1057.5,440.828 1107.16,440.828C1180.57,440.828 1231.39,458.115 1248.33,501.458C1265.27,544.801 1273.91,665.116 1274.8,669.422C1277.43,682.084 1283.01,604.872 1318.91,574.673C1379.24,523.934 1473.31,553.139 1485.5,643.582C1488.94,669.138 1489.72,718.563 1489.72,761.131C1489.72,811.158 1488.45,841.254 1485.5,877.448C1482.21,916.149 1473.12,1003.63 1459.9,1046.01C1450.96,1074.65 1421.65,1138.48 1392.42,1177.96C1391.44,1179.29 1390.49,1180.52 1389.5,1181.84C1377.03,1198.33 1288,1317.44 1276.49,1368.09C1264.02,1422.47 1268.14,1422.86 1265.7,1461.46C1264.02,1488.12 1270.8,1520.63 1275.13,1538.11C1276.78,1544.73 1272.23,1551.4 1265.29,1552.07C1239.64,1554.58 1182.59,1559.12 1147.99,1554.07C1106.64,1547.97 1106.22,1484.39 1093.01,1461.37C1074.81,1429.63 1022.18,1419.57 1007.06,1442.98C983.266,1480.04 932.076,1546.52 895.902,1550.68C828.011,1558.49 689.986,1554.06 577.477,1552.76C570.419,1552.67 565.072,1546.38 565.955,1539.54C569.528,1511.74 573.648,1447.21 539.901,1421.21C507.647,1396.15 469.767,1353.96 436.557,1327.26L348.563,1238.14Z", + fill = Color.White, + ), + layer( + "M980.293,535.912C980.293,497.324 921.886,423.936 780.721,423.936C722.675,423.936 688.743,466.73 689.855,523.39C691.081,586.017 692.493,657.071 692.493,652.195C692.493,644.814 653.61,416.005 642.494,350.724C640.517,339.137 637.976,327.814 634.827,316.479L590.58,157.338C570.411,84.792 499.827,35.847 423.396,44.939C346.304,54.111 314.044,141.845 328.711,216.301L370.415,428.018C370.442,428.167 370.442,428.134 370.468,428.283C371.414,433.107 455.633,862.874 463.1,910.602C465.489,925.874 461.54,921.128 455.044,907.561C424.69,844.157 397.369,775.154 340.421,732.646C298.538,701.293 252.002,668.105 197.111,663.358C124.452,656.976 56.34,704.29 46.399,765.059C40.793,799.22 38.254,817.696 61.84,858.921C89.021,905.563 180.295,997.392 217.1,1046.16C282.039,1132.38 318.527,1203.4 348.564,1238.14L436.559,1327.26C469.769,1353.96 507.649,1396.15 539.902,1421.21C573.65,1447.21 569.529,1511.75 565.956,1539.54C565.074,1546.38 570.421,1552.67 577.479,1552.76C689.988,1554.06 828.012,1558.49 895.904,1550.68C932.077,1546.52 983.267,1480.04 1007.06,1442.98C1022.19,1419.57 1074.81,1429.63 1093.01,1461.37C1106.22,1484.39 1106.64,1547.97 1147.99,1554.07C1182.59,1559.12 1239.64,1554.58 1265.29,1552.07C1272.23,1551.4 1276.78,1544.73 1275.14,1538.11C1270.8,1520.63 1264.02,1488.12 1265.7,1461.46C1268.14,1422.86 1264.02,1422.47 1276.5,1368.09C1288,1317.44 1377.03,1198.33 1389.5,1181.84C1390.5,1180.52 1391.44,1179.29 1392.42,1177.96C1421.66,1138.48 1450.96,1074.65 1459.9,1046.01C1473.12,1003.63 1482.22,916.149 1485.5,877.448C1488.45,841.254 1489.73,811.158 1489.73,761.131C1489.73,718.563 1488.94,669.138 1485.5,643.582C1473.31,553.139 1379.25,523.934 1318.91,574.673C1283.01,604.872 1277.43,682.084 1274.8,669.422C1273.91,665.116 1265.27,544.801 1248.33,501.458C1231.39,458.115 1180.57,440.828 1107.17,440.828C1057.5,440.828 980.294,479.924 980.294,535.912L980.293,535.912ZM980.293,535.912C980.293,579.626 981.476,616.372 982.702,643.582C985.164,698.553 980.293,638.534 980.293,583.511L980.293,535.912Z", + stroke = CursorStroke(Color.Black, 87.18f), + ), + layer( + "M1150.05,1263.76L1150.05,936.442", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + layer( + "M949.555,1263.99L949.555,936.858", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + layer( + "M749.802,936.754L749.802,1263.89", + stroke = CursorStroke(Color.Black, 78.11f, cap = StrokeCap.Round), + ), + hotspot = CursorHotspot.TopCenter, + ), + knife = + cursor( + viewportWidth = 1600f, + viewportHeight = 1480f, + layer( + "M49.571,1430.48L1410.07,51.267L1550.32,193.468L1122.74,626.935L1176.84,760.577L710.385,1233.45C553.823,1392.17 49.571,1430.48 49.571,1430.48", + fill = rgb(245, 245, 245), + stroke = CursorStroke(Color.Black, 100f, cap = StrokeCap.Round), + ), + hotspot = CursorHotspot.BottomLeft, + ), + leftHandle = + cursor( + viewportWidth = 1000f, + viewportHeight = 1600f, + layer( + "M333.53,465.813C311.561,463.185 289.552,470.391 273.391,485.504L24.046,746.229C-7.631,775.87 -7.632,826.121 24.044,855.764L273.391,1116.49C295.213,1136.9 327.066,1142.41 354.476,1130.52C381.885,1118.63 399.624,1091.6 399.631,1061.73L399.631,540.271C399.622,502.298 371.235,470.321 333.53,465.813Z", + fill = Color.Black, + ), + layer( + "M324.632,1061.73L75.285,800.996L324.632,540.272L324.632,1061.73Z", + fill = Color.White, + ), + layer( + "M731.374,0.289C636.401,0.289 549.716,34.287 489.229,96.387C428.743,158.486 398.925,246.211 399.506,342.756L399.504,342.303L399.504,1260.73C399.504,1357.03 429.204,1444.49 489.522,1506.58C549.84,1568.67 636.401,1602.75 731.374,1602.75L868.656,1602.75C941.022,1602.75 1000.94,1548.21 1000.94,1474.34L1000.94,1420.94C1000.94,1347.08 938.35,1292.54 865.984,1292.54L780.581,1292.54C750.113,1292.54 732.255,1284.48 720.989,1273.58C709.723,1262.68 699.946,1245.48 699.946,1207.33L699.946,395.707C699.946,354.447 709.125,336.586 717.651,327.809C726.178,319.031 741.571,310.498 780.581,310.498L868.591,310.498C940.957,310.498 998.479,246.793 998.479,182.094L998.479,128.691C998.479,90.636 981.72,60.434 960.005,38.666C938.289,16.898 909.329,0.289 871.262,0.289L731.374,0.289Z", + fill = Color.Black, + ), + layer( + "M868.657,1527.75C900.39,1527.75 925.935,1501.96 925.935,1474.35L925.935,1420.94C925.935,1393.33 900.39,1367.54 868.657,1367.54L783.252,1367.54C692.798,1367.54 627.619,1314.13 627.619,1207.33L627.619,395.706C627.619,288.9 679.496,235.498 783.252,235.498L871.263,235.498C902.997,235.498 923.478,209.709 923.478,182.095L923.478,128.691C923.478,101.077 896.694,75.289 871.263,75.289L731.374,75.289C575.741,75.289 471.021,182.095 471.986,342.303L471.986,1260.73C471.986,1420.94 575.741,1527.75 731.374,1527.75L868.657,1527.75Z", + fill = Color.White, + ), + layer( + "M872.9,1274.13C942.411,1274.13 1000.71,1215.83 1000.71,1146.31L1000.71,453.001C1000.71,383.489 942.411,325.188 872.9,325.188L826.383,325.188C756.872,325.188 698.571,383.489 698.571,453.001L698.571,1146.31C698.571,1215.83 756.872,1274.13 826.383,1274.13L872.9,1274.13Z", + fill = Color.Black, + ), + layer( + "M872.899,1199.13L827.643,1199.13C798.385,1199.13 774.83,1175.57 774.83,1146.32L774.83,453.001C774.83,423.743 798.385,400.188 827.643,400.188L872.899,400.188C902.158,400.188 925.712,423.743 925.712,453.001L925.712,1146.32C925.712,1175.57 902.158,1199.13 872.899,1199.13Z", + fill = Color.White, + ), + ), + mute = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M563.719,66.221L378.046,251.894L188.651,63.319L63.412,188.376L252.76,377.238L65.701,564.356L191.849,690.323L379.152,503.173L567.948,692.454L693.143,567.992L503.787,378.635L690.565,191.732L563.719,66.221Z", + fill = Color.White, + stroke = CursorStroke(Color.Black, 88.7f), + ), + layer( + "M949.759,450.05L949.759,750.78", + stroke = CursorStroke(Color.Black, 250f, cap = StrokeCap.Round), + ), + layer( + "M949.759,450.05L949.759,750.78", + stroke = CursorStroke(Color.White, 100f, cap = StrokeCap.Round), + ), + layer( + "M950.06,1149.8L950.06,1450.53", + stroke = CursorStroke(Color.Black, 250f, cap = StrokeCap.Round), + ), + layer( + "M950.06,1149.8L950.06,1450.53", + stroke = CursorStroke(Color.White, 100f, cap = StrokeCap.Round), + ), + layer( + "M449.219,950.532L749.949,950.532", + stroke = CursorStroke(Color.Black, 250f, cap = StrokeCap.Round), + ), + layer( + "M449.219,950.532L749.949,950.532", + stroke = CursorStroke(Color.White, 100f, cap = StrokeCap.Round), + ), + layer( + "M1148.97,950.231L1449.7,950.231", + stroke = CursorStroke(Color.Black, 250f, cap = StrokeCap.Round), + ), + layer( + "M1148.97,950.231L1449.7,950.231", + stroke = CursorStroke(Color.White, 100f, cap = StrokeCap.Round), + ), + ), + nArrow = + cursor( + viewportWidth = 1600f, + viewportHeight = 1058f, + layer( + "M1550.74,800.322L800.301,49.886L49.864,800.322L258.319,1008.78L800.301,466.795L1342.28,1008.78L1550.74,800.322", + fill = Color.White, + ), + layer( + "M1585.57,765.608L835.26,14.679C815.932,-4.819 784.417,-4.819 765.091,14.679L14.778,765.608C-4.311,784.864 -4.311,815.905 14.778,835.161L223.437,1043.82C242.692,1062.91 273.734,1062.91 292.99,1043.82L800.175,536.636L1307.36,1043.82C1326.62,1062.91 1357.66,1062.91 1376.91,1043.82L1585.57,835.161C1604.66,815.906 1604.66,784.862 1585.57,765.608ZM1480.93,800.692L1342.44,939.183L800.308,396.781L258.521,939.183L120.031,800.077L800.175,119.932L1480.93,800.692Z", + fill = Color.Black, + ), + ), + nsScroll = + cursor( + viewportWidth = 700f, + viewportHeight = 1600f, + layer( + "M217.743,527.223L351.204,393.761L484.666,527.223L662.615,349.274L351.204,37.863L39.794,349.274L217.743,527.223", + fill = Color.White, + stroke = CursorStroke(Color.Black, 75f, cap = StrokeCap.Round), + ), + layer( + "M483.602,1073.03L350.141,1206.5L216.679,1073.03L38.73,1250.98L350.141,1562.39L661.551,1250.98L483.602,1073.03", + fill = Color.White, + stroke = CursorStroke(Color.Black, 75f, cap = StrokeCap.Round), + ), + ), + nsewScroll = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M674.088,505.039L800.338,378.789L926.588,505.039L1094.92,336.706L800.338,42.123L505.755,336.706L674.088,505.039", + fill = Color.White, + stroke = CursorStroke(Color.Black, 84.17f, cap = StrokeCap.Round), + ), + layer( + "M1094.92,673.371L1221.17,799.621L1094.92,925.871L1263.25,1094.2L1557.84,799.621L1263.25,505.038L1094.92,673.371", + fill = Color.White, + stroke = CursorStroke(Color.Black, 84.17f, cap = StrokeCap.Round), + ), + layer( + "M926.489,1094.2L800.239,1220.45L673.989,1094.2L505.656,1262.54L800.239,1557.12L1094.82,1262.54L926.489,1094.2", + fill = Color.White, + stroke = CursorStroke(Color.Black, 84.17f, cap = StrokeCap.Round), + ), + layer( + "M505.755,925.871L379.506,799.621L505.755,673.372L337.423,505.039L42.84,799.621L337.423,1094.2L505.755,925.871", + fill = Color.White, + stroke = CursorStroke(Color.Black, 84.17f, cap = StrokeCap.Round), + ), + ), + paint = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M699.977,0.002L699.977,450.001L899.997,450.001L899.997,0.022L699.977,0.002Z", + fill = Color.Black, + ), + layer( + "M759.97,59.988L759.939,389.92L840.013,389.92L840.037,59.964L759.97,59.988Z", + fill = Color.White, + ), + layer( + "M699.967,700.022L699.967,900.02L899.986,900.02L899.986,700.042L699.967,700.022Z", + fill = Color.Black, + ), + layer( + "M759.96,760.007L759.928,840.086L839.954,840.037L839.977,760.032L759.96,760.007Z", + fill = Color.White, + ), + layer( + "M699.852,1149.89L699.852,1599.89L899.872,1599.89L899.872,1149.91L699.852,1149.89Z", + fill = Color.Black, + ), + layer( + "M759.845,1209.88L759.814,1539.81L839.889,1539.81L839.912,1209.86L759.845,1209.88Z", + fill = Color.White, + ), + layer( + "M0.047,900.003L450.046,900.003L450.046,699.983L0.067,699.983L0.047,900.003Z", + fill = Color.Black, + ), + layer( + "M60.033,840.01L389.965,840.041L389.965,759.966L60.009,759.943L60.033,840.01Z", + fill = Color.White, + ), + layer( + "M1149.94,900.127L1599.94,900.127L1599.94,700.108L1149.96,700.108L1149.94,900.127Z", + fill = Color.Black, + ), + layer( + "M1209.92,840.135L1539.86,840.166L1539.86,760.091L1209.9,760.068L1209.92,840.135Z", + fill = Color.White, + ), + ), + pencil = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M50.146,1551.41L150.108,1151.56L1249.7,51.96L1549.59,351.849L449.995,1451.45L50.146,1551.41Z", + fill = Color.White, + stroke = CursorStroke(Color.Black, 100f, cap = StrokeCap.Square), + ), + layer( + "M1011.87,306.849L1082.4,236.385L1365.6,518.937L1294.82,589.669L1011.87,306.849Z", + fill = Color.Black, + ), + hotspot = CursorHotspot.BottomLeft, + ), + pickArea = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M749.552,749.138L1450.47,749.186L1450.55,1450.3L749.509,1450.59L749.552,749.138Z", + stroke = CursorStroke(Color.Black, 300f), + ), + layer( + "M749.94,750.005L1450,749.592L1450.12,1449.82L750.353,1449.72L749.94,750.005Z", + stroke = CursorStroke(Color.White, 140f), + ), + layer( + "M239.883,40.228L239.873,239.557L40.062,239.894L40.099,460.065C40.099,460.065 156.665,460.214 240.099,460.084L239.959,659.64L459.918,659.846L460.101,460.25L660.131,460.02L659.869,240.009L460.058,240.009L460.067,39.899L239.883,40.228Z", + fill = Color.White, + stroke = CursorStroke(Color.Black, 80f), + ), + ), + pointer = + cursor( + viewportWidth = 1100f, + viewportHeight = 1600f, + layer( + "M51.043,122.801L50.539,1422L319.107,1160.01L474.385,1534.85L739.86,1425.8L584.91,1049.03L979.145,1049.19L51.043,122.801Z", + fill = Color.White, + stroke = CursorStroke(rgb(0, 0, 255), 77.39f), + ), + hotspot = CursorHotspot.TopLeft, + ), + rightHandle = + cursor( + viewportWidth = 1000f, + viewportHeight = 1600f, + layer( + "M666.599,465.057C628.893,469.566 600.506,501.543 600.498,539.518L600.498,1060.97C600.505,1090.85 618.243,1117.87 645.653,1129.77C673.062,1141.66 704.916,1136.15 726.738,1115.74L976.726,855.014C1008.4,825.372 1008.4,775.12 976.726,745.479L726.738,484.75C710.578,469.637 688.569,462.43 666.599,465.057Z", + fill = Color.Black, + ), + layer( + "M675.498,539.517L925.487,800.246L675.498,1060.97L675.498,539.517Z", + fill = Color.White, + ), + layer( + "M135.126,-1.504C62.76,-1.504 0.39,53.032 0.39,126.898L0.39,180.301C0.39,254.167 62.76,308.705 135.126,308.705L219.403,308.705C249.871,308.705 267.727,316.762 278.993,327.66C290.259,338.559 300.036,355.766 300.036,393.912L300.036,1205.54C300.036,1246.8 290.858,1264.66 282.331,1273.43C273.805,1282.21 258.414,1290.74 219.403,1290.74L127.941,1290.74C55.575,1290.74 0.727,1354.45 0.727,1419.15L0.727,1472.55C0.727,1510.61 17.484,1540.81 39.199,1562.58C60.915,1584.34 89.874,1600.95 127.941,1600.95L268.822,1600.95C363.795,1600.95 450.48,1566.95 510.966,1504.86C571.452,1442.76 601.331,1355.03 600.75,1258.49L600.752,1258.94L600.752,340.51C600.752,244.215 570.991,156.757 510.673,94.666C450.355,32.575 363.795,-1.504 268.822,-1.504L135.126,-1.504Z", + fill = Color.Black, + ), + layer( + "M133.076,73.495C101.343,73.495 75.799,99.283 75.799,126.898L75.799,180.301C75.799,207.916 101.343,233.704 133.076,233.704L216.944,233.704C307.398,233.704 372.577,287.107 372.577,393.913L372.577,1205.54C372.577,1312.34 320.699,1365.75 216.944,1365.75L127.941,1365.75C96.208,1365.75 75.726,1391.53 75.726,1419.15L75.726,1472.55C75.726,1500.17 102.511,1525.95 127.941,1525.95L268.822,1525.95C424.455,1525.95 529.175,1419.15 528.21,1258.94L528.21,340.51C528.21,180.301 424.455,73.495 268.822,73.495L133.076,73.495Z", + fill = Color.White, + ), + layer( + "M129.116,324.419C59.605,324.419 1.302,382.722 1.302,452.233L1.302,1147.34C1.302,1216.85 59.605,1275.15 129.116,1275.15L172.094,1275.15C241.605,1275.15 299.906,1216.85 299.906,1147.34L299.906,452.233C299.906,382.722 241.605,324.419 172.094,324.419L129.116,324.419Z", + fill = Color.Black, + ), + layer( + "M129.116,399.419L171.614,399.419C200.872,399.419 224.427,422.974 224.427,452.233L224.427,1147.34C224.427,1176.6 200.872,1200.15 171.614,1200.15L129.116,1200.15C99.857,1200.15 76.302,1176.6 76.302,1147.34L76.302,452.233C76.302,422.974 99.857,399.419 129.116,399.419Z", + fill = Color.White, + ), + ), + sArrow = + cursor( + viewportWidth = 1600f, + viewportHeight = 1058f, + layer( + "M49.615,257.827L800.051,1008.26L1550.49,257.827L1342.03,49.373L800.051,591.354L258.07,49.373L49.615,257.827", + fill = Color.White, + ), + layer( + "M14.779,292.542L765.092,1043.47C784.42,1062.97 815.935,1062.97 835.261,1043.47L1585.57,292.542C1604.66,273.286 1604.66,242.244 1585.57,222.988L1376.91,14.329C1357.66,-4.759 1326.62,-4.759 1307.36,14.329L800.177,521.513L292.993,14.329C273.737,-4.759 242.695,-4.759 223.439,14.329L14.779,222.988C-4.312,242.243 -4.312,273.287 14.779,292.542ZM119.417,257.457L257.908,118.966L800.044,661.368L1341.83,118.966L1480.32,258.073L800.177,938.217L119.417,257.457Z", + fill = Color.Black, + ), + ), + slip = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M914.707,465.813C877.183,470.3 848.614,502.48 848.605,540.271L848.605,1061.73C848.615,1102.87 882.472,1136.71 923.613,1136.71C942.631,1136.71 960.955,1129.48 974.845,1116.49L1253.52,855.764C1268.67,841.588 1277.28,821.743 1277.28,800.996C1277.28,780.249 1268.67,760.405 1253.52,746.229L974.845,485.504C958.694,470.4 936.663,463.187 914.707,465.813ZM998.605,713.148L1092.5,800.996L998.605,888.848L998.605,713.148Z", + fill = Color.Black, + ), + layer( + "M923.606,540.272L1202.28,800.996L923.606,1061.73L923.606,540.272Z", + fill = Color.White, + ), + layer( + "M1115.04,0.289C1042.67,0.289 982.764,54.825 982.764,128.691L982.764,182.094C982.764,255.96 1042.67,310.498 1115.04,310.498L1213.4,310.498C1243.86,310.498 1261.72,318.557 1272.99,329.455C1284.25,340.354 1294.03,357.561 1294.03,395.707L1294.03,1207.33C1294.03,1248.59 1284.85,1266.45 1276.32,1275.23C1267.8,1284 1252.41,1292.54 1213.4,1292.54L1109.64,1292.54C1037.28,1292.54 982.428,1356.24 982.428,1420.94L982.428,1474.34C982.428,1512.4 999.185,1542.6 1020.9,1564.37C1042.62,1586.14 1071.57,1602.75 1109.64,1602.75L1265.27,1602.75C1360.25,1602.75 1446.93,1568.75 1507.42,1506.65C1567.9,1444.55 1600.24,1356.83 1599.66,1260.28L1599.66,1260.73L1599.66,342.303C1599.66,246.008 1567.44,158.55 1507.12,96.459C1446.81,34.368 1360.25,0.289 1265.27,0.289L1115.04,0.289ZM1132.76,150.289L1265.27,150.289C1325.93,150.289 1369.07,169.613 1399.53,200.977C1430,232.34 1449.66,278.389 1449.66,342.303L1449.66,1260.73C1449.66,1260.88 1449.66,1261.03 1449.66,1261.18C1450.05,1324.85 1430.51,1370.63 1399.96,1401.99C1369.42,1433.34 1325.93,1452.75 1265.27,1452.75L1132.43,1452.75L1132.43,1442.54L1213.4,1442.54C1278.14,1442.54 1340.57,1424.37 1383.92,1379.75C1427.27,1335.12 1444.03,1272.88 1444.03,1207.33L1444.03,395.707C1444.03,327.048 1421.22,264.149 1377.28,221.645C1333.34,179.14 1273.38,160.498 1213.4,160.498L1132.76,160.498L1132.76,150.289Z", + fill = Color.Black, + ), + layer( + "M1115.04,75.289C1083.31,75.289 1057.76,101.077 1057.76,128.691L1057.76,182.095C1057.76,209.709 1083.31,235.498 1115.04,235.498L1213.4,235.498C1303.85,235.498 1369.03,288.9 1369.03,395.706L1369.03,1207.33C1369.03,1314.13 1317.15,1367.54 1213.4,1367.54L1109.64,1367.54C1077.91,1367.54 1057.43,1393.33 1057.43,1420.94L1057.43,1474.35C1057.43,1501.96 1084.21,1527.75 1109.64,1527.75L1265.27,1527.75C1420.91,1527.75 1525.63,1420.94 1524.66,1260.73L1524.66,342.303C1524.66,182.095 1420.91,75.289 1265.27,75.289L1115.04,75.289Z", + fill = Color.White, + ), + layer( + "M706.207,465.813C684.25,463.187 662.219,470.4 646.068,485.504L367.394,746.229C352.245,760.405 343.636,780.249 343.636,800.997C343.636,821.744 352.244,841.588 367.392,855.764L646.068,1116.49C659.959,1129.48 678.283,1136.71 697.301,1136.71C738.441,1136.71 772.298,1102.87 772.308,1061.73L772.308,540.271C772.299,502.48 743.731,470.3 706.207,465.813ZM622.308,713.148L622.308,888.848L528.41,800.996L622.308,713.148Z", + fill = Color.Black, + ), + layer( + "M697.308,1061.73L418.633,800.996L697.308,540.272L697.308,1061.73Z", + fill = Color.White, + ), + layer( + "M354.879,0.289C259.906,0.289 173.22,34.287 112.734,96.387C52.248,158.486 19.913,246.211 20.494,342.756L20.492,342.303L20.492,1260.73C20.492,1357.03 52.71,1444.49 113.027,1506.58C173.345,1568.67 259.906,1602.75 354.879,1602.75L505.111,1602.75C577.477,1602.75 637.389,1548.21 637.389,1474.34L637.389,1420.94C637.389,1347.08 577.477,1292.54 505.111,1292.54L406.756,1292.54C376.289,1292.54 358.434,1284.48 347.168,1273.58C335.902,1262.68 326.125,1245.48 326.125,1207.33L326.125,395.707C326.125,354.447 335.302,336.586 343.828,327.809C352.354,319.032 367.746,310.498 406.756,310.498L510.512,310.498C582.878,310.498 637.726,246.793 637.726,182.094L637.726,128.691C637.726,90.636 620.967,60.434 599.252,38.666C577.536,16.898 548.579,0.289 510.512,0.289L354.879,0.289ZM354.879,150.289L487.726,150.289L487.726,160.498L406.756,160.498C342.011,160.498 279.587,178.665 236.236,223.291C192.885,267.917 176.125,330.161 176.125,395.707L176.125,1207.33C176.125,1275.99 198.936,1338.89 242.873,1381.39C286.81,1423.89 346.769,1442.54 406.756,1442.54L487.389,1442.54L487.389,1452.75L354.879,1452.75C294.219,1452.75 251.087,1433.42 220.619,1402.06C190.151,1370.69 170.492,1324.65 170.492,1260.73L170.492,342.303C170.493,342.152 170.493,342.002 170.492,341.852C170.109,278.188 189.649,232.404 220.189,201.049C250.73,169.693 294.221,150.289 354.881,150.289L354.879,150.289Z", + fill = Color.Black, + ), + layer( + "M505.111,1527.75C536.845,1527.75 562.389,1501.96 562.389,1474.35L562.389,1420.94C562.389,1393.33 536.845,1367.54 505.111,1367.54L406.757,1367.54C316.303,1367.54 251.124,1314.13 251.124,1207.33L251.124,395.706C251.124,288.9 303.002,235.498 406.757,235.498L510.512,235.498C542.245,235.498 562.726,209.709 562.726,182.095L562.726,128.691C562.726,101.077 535.942,75.289 510.512,75.289L354.879,75.289C199.247,75.289 94.527,182.095 95.492,342.303L95.492,1260.73C95.492,1420.94 199.247,1527.75 354.879,1527.75L505.111,1527.75Z", + fill = Color.White, + ), + ), + stop = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M800.311,50.105C388.752,50.105 50.091,388.767 50.091,800.325C50.091,1211.88 388.753,1550.55 800.311,1550.55C1211.87,1550.55 1550.53,1211.88 1550.53,800.325C1550.53,388.767 1211.87,50.105 800.311,50.105ZM800.311,314.889C1066.61,314.889 1285.75,534.023 1285.75,800.325C1285.56,885.722 1262.84,969.576 1219.9,1043.39L557.248,380.739C631.06,337.793 714.914,315.076 800.311,314.889ZM380.726,557.262L1043.37,1219.91C969.562,1262.86 885.708,1285.58 800.311,1285.76C534.009,1285.76 314.875,1066.63 314.874,800.325C315.061,714.929 337.779,631.074 380.726,557.262Z", + fill = Color.White, + stroke = CursorStroke(rgb(3, 3, 3), 100f, cap = StrokeCap.Round), + ), + ), + swapArea = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M649.98,50.499L1549.72,50.406L1549.87,949.918L651.072,950.539L649.98,50.499Z", + fill = Color.Black, + ), + layer( + "M1599.71,0.4L599.92,0.504L599.964,999.793L1599.88,999.883L1599.71,0.4ZM1499.92,100.022L1499.86,899.953L699.843,899.919L699.846,100.104L1499.92,100.022Z", + fill = Color.White, + ), + layer( + "M50.05,650.471L949.974,649.805L950.254,1550.75L49.591,1550.39L50.05,650.471Z", + fill = Color.White, + ), + layer( + "M999.959,599.962L0.076,600.118L0.117,1600.37L999.994,1600.77L999.959,599.962ZM899.99,699.842L899.963,1499.9L99.617,1500.41L99.75,700.158L899.99,699.842Z", + fill = Color.Black, + ), + layer( + "M199.889,1000.27L200.224,1400.33L599.98,1400.18L199.889,1000.27Z", + fill = Color.Black, + ), + layer( + "M1399.75,200.035L1000.09,200.035L1399.78,599.763L1399.75,200.035Z", + fill = Color.White, + ), + layer( + "M1199.63,299.941L1300.1,400.604L900.315,799.858L799.825,700.264L1199.63,299.941Z", + fill = Color.White, + ), + layer( + "M300.822,1199.65L700.199,799.841L800.155,900.159L399.675,1299.96L300.822,1199.65Z", + fill = Color.Black, + ), + ), + textEdit = + cursor( + viewportWidth = 700f, + viewportHeight = 1400f, + layer( + "M349.987,127.6C308.174,93.865 224.727,51.264 85.347,50.628C65.694,50.538 49.777,67.869 49.829,86.749L50.321,263.979C127.371,279.753 230.77,257.571 230.061,339.51L230.461,1070.42C229.142,1148.87 157.691,1115.67 49.988,1137.12L49.988,1299.64C49.988,1340.97 99.869,1349.22 99.869,1349.22C244.701,1359.99 305.872,1313.47 350.316,1286.51C392.696,1315.91 453.266,1357.08 598.14,1350.04C598.14,1350.04 650.025,1351.3 649.983,1299.44L649.849,1136.49C546.304,1121.11 472.027,1148.55 470.469,1070.28L470.269,340.124C469.38,263.478 566.759,283.268 649.557,262.211C649.557,262.211 650.588,145.986 650.588,86.749C650.588,67.869 632.591,51.795 612.975,50.628C446.31,47.584 386.148,91.644 349.987,127.6Z", + fill = Color.White, + stroke = CursorStroke(rgb(0, 0, 255), 65.05f), + ), + ), + vSplit = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M529.922,51.006C618.064,51.006 689.023,125.136 689.023,217.217L689.023,1380.7C689.023,1472.78 618.063,1546.91 529.921,1546.91", + fill = Color.White, + stroke = CursorStroke(rgb(13, 13, 13), 103.5f, cap = StrokeCap.Round), + ), + layer( + "M362.324,1131.38L52.615,798.957L362.324,466.534L521.426,632.745L370.819,798.957L521.426,965.168L362.324,1135.89", + fill = Color.White, + stroke = CursorStroke(Color.Black, 103.5f, cap = StrokeCap.Round), + ), + layer( + "M1067.2,51.006C979.053,51.006 908.094,125.136 908.094,217.217L908.095,1380.7C908.095,1472.78 979.054,1546.91 1067.2,1546.91", + fill = Color.White, + stroke = CursorStroke(rgb(13, 13, 13), 103.5f, cap = StrokeCap.Round), + ), + layer( + "M1237.59,1131.38L1547.3,798.957L1237.59,466.534L1078.49,632.745L1229.1,798.957L1078.49,965.168L1237.59,1135.89", + fill = Color.White, + stroke = CursorStroke(Color.Black, 103.5f, cap = StrokeCap.Round), + ), + ), + vertexLoop = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M737.261,500.237L1259.53,500.175L1259.47,600.137L737.212,600.076L737.261,500.237Z", + fill = Color.White, + ), + layer( + "M737.737,600.109L1260.01,600.047L1259.95,700.009L737.688,699.948L737.737,600.109Z", + fill = Color.Black, + ), + layer( + "M1261.93,1499.78L739.66,1499.84L739.721,1399.88L1261.98,1399.94L1261.93,1499.78Z", + fill = Color.White, + ), + layer( + "M1261.46,1399.91L739.184,1399.97L739.245,1300.01L1261.51,1300.07L1261.46,1399.91Z", + fill = Color.Black, + ), + layer( + "M500.051,1264.39L499.99,742.119L599.951,742.18L599.89,1264.44L500.051,1264.39Z", + fill = Color.White, + ), + layer( + "M599.923,1263.92L599.862,741.643L699.823,741.704L699.762,1263.96L599.923,1263.92Z", + fill = Color.Black, + ), + layer( + "M1499.76,744.067L1499.82,1266.34L1399.86,1266.28L1399.92,744.017L1499.76,744.067Z", + fill = Color.White, + ), + layer( + "M1399.88,744.542L1399.95,1266.82L1299.98,1266.75L1300.05,744.493L1399.88,744.542Z", + fill = Color.Black, + ), + layer( + "M50.326,50.075L720.836,50.075L49.88,722.105L50.326,50.075Z", + fill = Color.White, + ), + layer( + "M0.359,0.074L-0.199,843.033L841.41,0.076L0.359,0.074ZM100.293,100.074L600.264,100.074L99.961,601.176L100.293,100.074Z", + fill = Color.Black, + ), + layer( + "M749.759,599.977C749.759,682.158 682.135,749.782 599.954,749.782C517.774,749.782 450.15,682.158 450.15,599.977C450.15,517.797 517.774,450.172 599.954,450.172C682.135,450.172 749.759,517.797 749.759,599.977Z", + fill = Color.Black, + ), + layer( + "M599.955,400.172C490.198,400.172 400.15,490.22 400.15,599.977C400.15,709.733 490.198,799.781 599.955,799.781C709.712,799.781 799.76,709.733 799.76,599.977C799.76,490.22 709.712,400.172 599.955,400.172ZM599.955,500.172C655.668,500.172 699.76,544.264 699.76,599.977C699.76,655.689 655.668,699.781 599.955,699.781C544.242,699.781 500.15,655.689 500.15,599.977C500.15,544.264 544.242,500.172 599.955,500.172Z", + fill = Color.White, + ), + layer( + "M1549.79,1400.07L1549.79,1400.07C1549.79,1482.25 1482.16,1549.87 1399.98,1549.87L1399.98,1549.87C1317.8,1549.87 1250.18,1482.25 1250.18,1400.07L1250.18,1400.07C1250.18,1317.89 1317.8,1250.26 1399.98,1250.26L1399.98,1250.26C1482.16,1250.26 1549.79,1317.89 1549.79,1400.07Z", + fill = Color.Black, + ), + layer( + "M1399.98,1200.26C1290.22,1200.26 1200.18,1290.31 1200.18,1400.07C1200.18,1509.83 1290.22,1599.87 1399.98,1599.87C1509.74,1599.87 1599.79,1509.83 1599.79,1400.07C1599.79,1290.31 1509.74,1200.26 1399.98,1200.26ZM1399.98,1300.26C1455.69,1300.26 1499.79,1344.36 1499.79,1400.07C1499.79,1455.78 1455.69,1499.87 1399.98,1499.87C1344.27,1499.87 1300.18,1455.78 1300.18,1400.07C1300.18,1344.36 1344.27,1300.26 1399.98,1300.26Z", + fill = Color.White, + ), + layer( + "M749.894,1399.9L749.894,1399.9C749.894,1482.09 682.27,1549.71 600.089,1549.71C517.909,1549.71 450.284,1482.09 450.284,1399.9L450.284,1399.9C450.284,1317.73 517.909,1250.1 600.089,1250.1C682.27,1250.1 749.894,1317.73 749.894,1399.9Z", + fill = Color.Black, + ), + layer( + "M600.09,1200.1C490.333,1200.1 400.285,1290.15 400.285,1399.9C400.285,1509.66 490.333,1599.71 600.09,1599.71C709.847,1599.71 799.895,1509.66 799.895,1399.9C799.895,1290.15 709.847,1200.1 600.09,1200.1ZM600.09,1300.1C655.803,1300.1 699.895,1344.19 699.895,1399.9C699.895,1455.62 655.803,1499.71 600.09,1499.71C544.377,1499.71 500.285,1455.62 500.285,1399.9C500.285,1344.19 544.377,1300.1 600.09,1300.1Z", + fill = Color.White, + ), + layer( + "M1549.92,600.105C1549.92,682.286 1482.3,749.91 1400.12,749.91L1400.12,749.91C1317.93,749.91 1250.31,682.286 1250.31,600.105C1250.31,517.925 1317.93,450.301 1400.12,450.3L1400.12,450.3C1482.3,450.3 1549.92,517.925 1549.92,600.105Z", + fill = Color.Black, + ), + layer( + "M1400.12,400.301C1290.36,400.301 1200.31,490.349 1200.31,600.105C1200.31,709.862 1290.36,799.91 1400.12,799.91C1509.87,799.91 1599.92,709.862 1599.92,600.105C1599.92,490.349 1509.87,400.301 1400.12,400.301ZM1400.12,500.301C1455.83,500.301 1499.92,544.393 1499.92,600.105C1499.92,655.818 1455.83,699.91 1400.12,699.91C1344.4,699.91 1300.31,655.818 1300.31,600.105C1300.31,544.393 1344.4,500.301 1400.12,500.301Z", + fill = Color.White, + ), + hotspot = CursorHotspot.TopLeft, + ), + wArrow = + cursor( + viewportWidth = 1058f, + viewportHeight = 1600f, + layer( + "M800.215,49.817L49.779,800.254L800.215,1550.69L1008.67,1342.24L466.688,800.254L1008.67,258.272L800.215,49.817", + fill = Color.White, + ), + layer( + "M765.501,14.982L14.572,765.295C-4.926,784.623 -4.926,816.138 14.572,835.464L765.501,1585.78C784.757,1604.87 815.798,1604.87 835.054,1585.78L1043.71,1377.12C1062.8,1357.86 1062.8,1326.82 1043.71,1307.56L536.529,800.379L1043.71,293.195C1062.8,273.94 1062.8,242.897 1043.71,223.641L835.054,14.982C815.799,-4.11 784.755,-4.11 765.501,14.982ZM800.585,119.619L939.076,258.11L397.17,799.998L939.076,1342.03L799.97,1480.52L119.825,800.379L800.585,119.619Z", + fill = Color.Black, + ), + ), + wait = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M359.122,149.302L1240.38,150.014C1347.51,599.35 917.595,700.434 917.932,799.929C918.273,900.188 1352.08,997.664 1240.45,1449.49L359.834,1449.49C248.896,1000.77 683.621,900.408 683.42,798.448C683.224,699.046 249.176,597.473 359.122,149.302Z", + fill = Color.White, + stroke = CursorStroke(Color.Black, 100f), + ), + layer( + "M499.798,1300.47L1100.44,1300.47C1054.48,1197.91 916.985,1043.99 800.118,1043.69C677.925,1042.68 550.813,1198.65 499.798,1300.47Z", + fill = Color.Black, + ), + layer( + "M800.252,678.689C847.529,591.408 1000.03,499.272 999.919,399.534C901.569,427.554 700.745,429.751 599.27,400.557C600.287,501.783 757.544,593.858 800.252,678.689Z", + fill = Color.Black, + ), + layer( + "M199.889,1600.28L200.279,1399.62L1399.23,1399.62L1399.62,1600.67L199.889,1600.28Z", + fill = Color.Black, + ), + layer( + "M199.889,0.39L200.279,200.279L1400.39,199.5L1400.39,-0L199.889,0.39Z", + fill = Color.Black, + ), + ), + xMove = + cursor( + viewportWidth = 1600f, + viewportHeight = 1000f, + layer( + "M1081.67,649.016L1081.42,881.922C1081.36,935.695 1133.05,968.58 1166.8,935.723L1578.15,535.305C1605.63,508.549 1607.53,488.856 1577.9,460.678L1169.75,72.55C1125.47,30.444 1081.76,53.72 1081.74,117.957L1081.68,352.176L519.899,351.977L520.722,126.146C520.845,92.23 480.353,10.825 418.223,71.105L36.229,441.724C-1.664,478.488 -16.969,503.526 33.186,552.506L415.313,925.673C483.277,992.044 519.682,914.061 519.697,875.421L519.779,649.517L1081.67,649.016Z", + fill = rgb(0, 0, 255), + evenOdd = true, + ), + layer( + "M100.119,499.652L444.444,844.491L445.012,574.628L1153.44,574.524L1152.84,843.224L1499.6,499.222L1152.82,154.98L1154.23,427.416L444.566,427.831L444.673,154.45L100.119,499.652Z", + fill = rgb(0, 255, 0), + evenOdd = true, + ), + ), + yMove = + cursor( + viewportWidth = 1000f, + viewportHeight = 1600f, + layer( + "M350.478,1082.29L117.572,1082.03C63.799,1081.97 30.914,1133.66 63.771,1167.41L464.188,1578.76C490.945,1606.25 510.638,1608.14 538.816,1578.51L926.943,1170.36C969.05,1126.08 945.774,1082.37 881.537,1082.35L647.318,1082.3L647.516,520.512L873.348,521.335C907.264,521.459 988.669,480.966 928.389,418.836L557.77,36.842C521.006,-1.051 495.967,-16.356 446.988,33.8L73.82,415.926C7.449,483.89 85.433,520.296 124.073,520.31L349.977,520.392L350.478,1082.29Z", + fill = rgb(0, 0, 255), + evenOdd = true, + ), + layer( + "M499.842,100.733L155.003,445.058L424.866,445.625L424.97,1154.05L156.27,1153.45L500.272,1500.21L844.514,1153.43L572.077,1154.84L571.663,445.18L845.044,445.287L499.842,100.733Z", + fill = rgb(0, 255, 0), + evenOdd = true, + ), + ), + zoomIn = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M956.221,755.152C903.198,755.152 852.292,776.238 814.799,813.73C777.306,851.223 756.22,902.129 756.22,955.152C756.22,1008.18 777.306,1059.08 814.799,1096.57L1258.19,1539.97C1335.78,1617.55 1463.45,1617.55 1541.04,1539.97C1578.53,1502.47 1599.61,1451.57 1599.61,1398.55C1599.61,1345.52 1578.53,1294.62 1541.04,1257.12L1097.64,813.73C1060.15,776.238 1009.24,755.153 956.221,755.152Z", + fill = Color.White, + ), + layer( + "M956.773,856.809C930.262,856.809 904.809,867.352 886.063,886.1C847.273,924.89 847.273,988.729 886.063,1027.52L1329.45,1470.91C1368.25,1509.7 1432.08,1509.7 1470.88,1470.91C1489.62,1452.17 1500.16,1426.71 1500.16,1400.2C1500.16,1373.69 1489.62,1348.24 1470.88,1329.49L1027.48,886.1C1008.74,867.353 983.285,856.809 956.773,856.809Z", + fill = Color.Black, + ), + layer( + "M950.06,549.627C950.06,769.172 769.401,949.83 549.856,949.83C330.311,949.83 149.653,769.172 149.653,549.627C149.653,330.082 330.311,149.424 549.856,149.424C769.401,149.424 950.06,330.082 950.06,549.627Z", + fill = Color.White, + ), + layer( + "M549.855,99.424C301.807,99.424 99.652,301.579 99.652,549.627C99.652,669.009 147.098,783.553 231.514,867.969C315.93,952.385 430.473,999.83 549.855,999.83C669.237,999.83 783.781,952.385 868.197,867.969C952.613,783.553 1000.06,669.009 1000.06,549.627C1000.06,430.245 952.613,315.701 868.197,231.285C783.781,146.869 669.237,99.424 549.855,99.424ZM549.855,199.424C642.754,199.424 731.799,236.307 797.488,301.996C863.178,367.685 900.061,456.728 900.061,549.627C900.061,642.526 863.178,731.568 797.488,797.258C731.799,862.947 642.754,899.83 549.855,899.83C456.957,899.83 367.914,862.947 302.225,797.258C236.535,731.568 199.652,642.526 199.652,549.627C199.652,355.623 355.851,199.424 549.855,199.424Z", + fill = Color.Black, + ), + layer( + "M549.855,1.84C404.128,1.84 264.319,59.75 161.273,162.795C58.228,265.84 0.316,405.651 0.316,551.379C0.316,697.107 58.228,836.918 161.273,939.963C264.319,1043.01 404.128,1100.92 549.855,1100.92C695.583,1100.92 835.394,1043.01 938.439,939.963C1041.49,836.918 1099.4,697.107 1099.4,551.379C1099.4,405.651 1041.49,265.84 938.439,162.795C835.394,59.75 695.583,1.84 549.855,1.84ZM549.855,101.84C669.1,101.84 783.41,149.187 867.729,233.506C952.047,317.824 999.396,432.134 999.396,551.379C999.396,670.623 952.047,784.933 867.729,869.252C783.41,953.571 669.1,1000.92 549.855,1000.92C430.611,1000.92 316.303,953.571 231.984,869.252C147.666,784.933 100.316,670.623 100.316,551.379C100.316,432.134 147.666,317.824 231.984,233.506C316.303,149.187 430.611,101.84 549.855,101.84Z", + fill = Color.White, + ), + layer( + "M550.428,300.129C522.999,300.129 500.428,322.7 500.428,350.129L500.428,500.18L350.094,500.18C322.665,500.18 300.094,522.751 300.094,550.18C300.094,577.609 322.665,600.18 350.094,600.18L500.428,600.18L500.428,750C500.428,777.429 522.999,800 550.428,800C577.857,800 600.428,777.429 600.428,750L600.428,600.18L750.248,600.18C777.677,600.18 800.248,577.609 800.248,550.18C800.248,522.751 777.677,500.18 750.248,500.18L600.428,500.18L600.428,350.129C600.428,322.7 577.857,300.129 550.428,300.129Z", + fill = Color.Black, + ), + ), + zoomOut = + cursor( + viewportWidth = 1600f, + viewportHeight = 1600f, + layer( + "M956.221,755.152C903.198,755.152 852.292,776.238 814.799,813.73C777.306,851.223 756.22,902.129 756.22,955.152C756.22,1008.18 777.306,1059.08 814.799,1096.57L1258.19,1539.97C1335.78,1617.55 1463.45,1617.55 1541.04,1539.97C1578.53,1502.47 1599.61,1451.57 1599.61,1398.55C1599.61,1345.52 1578.53,1294.62 1541.04,1257.12L1097.64,813.73C1060.15,776.238 1009.24,755.153 956.221,755.152Z", + fill = Color.White, + ), + layer( + "M956.773,856.809C930.262,856.809 904.809,867.352 886.063,886.1C847.273,924.89 847.273,988.729 886.063,1027.52L1329.45,1470.91C1368.25,1509.7 1432.08,1509.7 1470.88,1470.91C1489.62,1452.17 1500.16,1426.71 1500.16,1400.2C1500.16,1373.69 1489.62,1348.24 1470.88,1329.49L1027.48,886.1C1008.74,867.353 983.285,856.809 956.773,856.809Z", + fill = Color.Black, + ), + layer( + "M950.06,549.627C950.06,769.172 769.401,949.83 549.856,949.83C330.311,949.83 149.653,769.172 149.653,549.627C149.653,330.082 330.311,149.424 549.856,149.424C769.401,149.424 950.06,330.082 950.06,549.627Z", + fill = Color.White, + ), + layer( + "M549.855,99.424C301.807,99.424 99.652,301.579 99.652,549.627C99.652,669.009 147.098,783.553 231.514,867.969C315.93,952.385 430.473,999.83 549.855,999.83C669.237,999.83 783.781,952.385 868.197,867.969C952.613,783.553 1000.06,669.009 1000.06,549.627C1000.06,430.245 952.613,315.701 868.197,231.285C783.781,146.869 669.237,99.424 549.855,99.424ZM549.855,199.424C642.754,199.424 731.799,236.307 797.488,301.996C863.178,367.685 900.061,456.728 900.061,549.627C900.061,642.526 863.178,731.568 797.488,797.258C731.799,862.947 642.754,899.83 549.855,899.83C456.957,899.83 367.914,862.947 302.225,797.258C236.535,731.568 199.652,642.526 199.652,549.627C199.652,355.623 355.851,199.424 549.855,199.424Z", + fill = Color.Black, + ), + layer( + "M549.855,1.84C404.128,1.84 264.319,59.75 161.273,162.795C58.228,265.84 0.316,405.651 0.316,551.379C0.316,697.107 58.228,836.918 161.273,939.963C264.319,1043.01 404.128,1100.92 549.855,1100.92C695.583,1100.92 835.394,1043.01 938.439,939.963C1041.49,836.918 1099.4,697.107 1099.4,551.379C1099.4,405.651 1041.49,265.84 938.439,162.795C835.394,59.75 695.583,1.84 549.855,1.84ZM549.855,101.84C669.1,101.84 783.41,149.187 867.729,233.506C952.047,317.824 999.396,432.134 999.396,551.379C999.396,670.623 952.047,784.933 867.729,869.252C783.41,953.571 669.1,1000.92 549.855,1000.92C430.611,1000.92 316.303,953.571 231.984,869.252C147.666,784.933 100.316,670.623 100.316,551.379C100.316,432.134 147.666,317.824 231.984,233.506C316.303,149.187 430.611,101.84 549.855,101.84Z", + fill = Color.White, + ), + layer( + "M350.094,500.18C322.48,500.18 300.094,522.565 300.094,550.18C300.094,577.794 322.48,600.18 350.094,600.18L750.248,600.18C777.862,600.18 800.248,577.794 800.248,550.18C800.248,522.565 777.862,500.18 750.248,500.18L350.094,500.18Z", + fill = Color.Black, + ), + ), + ) + +/** + * Draws [cursor] with its hotspot placed exactly on [anchor] (typically the pointer position), scaled so + * the cursor's longer side spans [pixelSize]. Because the art is positioned by its hotspot the caller + * passes the pointer location and a size and never offsets for the tip or center itself. Draw into a + * surface that surrounds [anchor] (an overlay over the viewport), not a tight cursor-sized box: a + * non-corner hotspot places art on every side of [anchor]. Colors come baked into the layers, so unlike + * drawIcon there is no caller tint. + * + * @param UmamoCursor cursor The cursor to paint. + * @param Offset anchor Where the cursor's hotspot lands, in this DrawScope's coordinates. + * @param Float pixelSize Target length of the cursor's longer side, in pixels. + */ +fun DrawScope.drawCursor(cursor: UmamoCursor, anchor: Offset, pixelSize: Float = 16f) { + val bounds = cursor.bounds + // Scale so the art's longer side spans pixelSize, keeping the authored aspect ratio. + val drawScale = pixelSize / max(bounds.width, bounds.height) + // The hotspot is a point within the art bounds; shift the origin so its scaled position lands on the + // anchor, so the art draws around the anchor and the caller never offsets for the tip or center. + val hotspotX = bounds.left + cursor.hotspot.fractionX * bounds.width + val hotspotY = bounds.top + cursor.hotspot.fractionY * bounds.height + val originX = anchor.x - hotspotX * drawScale + val originY = anchor.y - hotspotY * drawScale + withTransform({ + translate(left = originX, top = originY) + scale(scaleX = drawScale, scaleY = drawScale, pivot = Offset.Zero) + }) { + for (layer in cursor.layers) { + val fillColor = layer.fill + if (fillColor != null) { + drawPath(path = layer.path, color = fillColor, style = Fill) + } + val stroke = layer.stroke + if (stroke != null) { + drawPath( + path = layer.path, + color = stroke.color, + style = Stroke(width = stroke.strokeWidth, cap = stroke.cap, join = stroke.join), + ) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Icon.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Icon.kt new file mode 100644 index 0000000..10e72b0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Icon.kt @@ -0,0 +1,475 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Fill +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.withTransform +import androidx.compose.ui.graphics.vector.PathParser + +/** + * How an icon's path is painted. Bundling this with the path lets call sites draw an icon without + * restating fill-versus-stroke or the stroke weight every time. + */ +sealed interface IconStyle { + /** Paint the path as a solid filled shape (glyph-style icons). */ + data object Filled : IconStyle + + /** + * Paint the path as a stroked outline (Tabler line icons). Caps and joins are always rounded to + * match the Tabler source, so only the line weight varies. + * + * @param Float strokeWidth Line weight in the icon's own viewport units. + */ + data class Outlined(val strokeWidth: Float = 2f) : IconStyle +} + +/** + * One paint layer of an icon: a parsed path, how it is painted, and its opacity relative to the tint + * color the caller draws with. Opacity is what carries a two-tone icon's contrast (Blender's icon set + * encodes its dark/light pairing as a full-strength layer over a muted one), so both tones derive from + * the single caller color and follow the theme automatically. A layer may instead carry its OWN + * color for genuinely multi-color art (the 2D cursor's red / blue axis stubs), overriding the caller + * tint for that layer only; theme-following icons leave it null. + * + * @param Path path The parsed vector outline. + * @param IconStyle style Fill-versus-stroke descriptor used when drawing. + * @param Float opacity The layer's opacity multiplier over the paint color (1 = full strength). + * @param Color? color The layer's own paint color, or null to take the caller's tint. + */ +data class IconLayer( + val path: Path, + val style: IconStyle = IconStyle.Outlined(), + val opacity: Float = 1f, + val color: Color? = null, +) + +/** + * A single themed vector icon: its paint layers in draw order and the square viewport their coordinates + * are authored in. Single-color icons (the Tabler set) are one layer; two-tone icons (the Blender set) + * are a muted context layer plus a full-strength highlight layer. Carrying the styles per layer keeps + * draw call sites free of stroke and scale setup. + * + * @param List layers The paint layers, drawn first to last. + * @param Float viewportSize Edge length of the square coordinate box the paths are authored in. + */ +data class UmamoIcon( + val layers: List, + val viewportSize: Float = 24f, +) + +/** The bundled set of editor icons, each a fully described [UmamoIcon]. */ +data class UmamoIcons( + val reset: UmamoIcon, + val resetAll: UmamoIcon, + val groupAdd: UmamoIcon, + val parameterAdd: UmamoIcon, + val part: UmamoIcon, + val mesh: UmamoIcon, + val warpDeformer: UmamoIcon, + val armature: UmamoIcon, + val rotationDeformer: UmamoIcon, + val search: UmamoIcon, + val close: UmamoIcon, + val plus: UmamoIcon, + val eyedropper: UmamoIcon, + val puppetRoot: UmamoIcon, + val filterUnfiltered: UmamoIcon, + val filterFiltered: UmamoIcon, + val eyeVisible: UmamoIcon, + val eyeHidden: UmamoIcon, + val linked: UmamoIcon, + val unlinked: UmamoIcon, + val locked: UmamoIcon, + val unlocked: UmamoIcon, + val selectable: UmamoIcon, + val unselectable: UmamoIcon, + val spaceViewport: UmamoIcon, + val spaceTexture: UmamoIcon, + val spaceOutliner: UmamoIcon, + val spaceHistory: UmamoIcon, + val spaceParameters: UmamoIcon, + val spaceKeyformSheet: UmamoIcon, + val spaceProperties: UmamoIcon, + val spaceTool: UmamoIcon, + val spaceAnimation: UmamoIcon, + val chevronUp: UmamoIcon, + val chevronDown: UmamoIcon, + val chevronLeft: UmamoIcon, + val chevronRight: UmamoIcon, + val dots: UmamoIcon, + val gripVertical: UmamoIcon, + val gripHorizontal: UmamoIcon, + val toolBoxSelect: UmamoIcon, + val toolCircleSelect: UmamoIcon, + val toolInsertVertex: UmamoIcon, + val toolDrawConnect: UmamoIcon, + val toolGrab: UmamoIcon, + val toolRotate: UmamoIcon, + val toolScale: UmamoIcon, + val toolMirrorH: UmamoIcon, + val toolMirrorV: UmamoIcon, + val transformPivot: UmamoIcon, + val snap: UmamoIcon, + val proportionalEdit: UmamoIcon, + val logsTerminal: UmamoIcon, + val copy: UmamoIcon, + val floppy: UmamoIcon, + val sources: UmamoIcon, + val missingFile: UmamoIcon, + val addFile: UmamoIcon, + val refresh: UmamoIcon, + val refreshAlert: UmamoIcon, + val wand: UmamoIcon, + val language: UmamoIcon, + val editorModeObject: UmamoIcon, + val editorModeEdit: UmamoIcon, + val meshSelectVertex: UmamoIcon, + val meshSelectEdge: UmamoIcon, + val meshSelectFace: UmamoIcon, + val uvSelectVertex: UmamoIcon, + val uvSelectEdge: UmamoIcon, + val uvSelectFace: UmamoIcon, + val cursor2d: UmamoIcon, +) + +/** + * Builds a stroked Tabler icon from its SVG path data. Tabler icons share a 24x24 viewport and a + * 2-unit round stroke, so this captures those defaults in one place. + * + * @param String pathData SVG "d" attribute contents; may hold several "M..." subpaths. + * @return UmamoIcon The icon ready to draw. + */ +private fun simpleIcon(pathData: String): UmamoIcon = + UmamoIcon(layers = listOf(IconLayer(path = PathParser().parsePathString(pathData).toPath()))) + +/** + * Builds one filled layer of a Blender icon from its SVG path data. Blender's icons are filled shapes + * whose two-tone contrast is encoded as fill opacity (a 1.0 highlight over a muted context, typically + * 0.6 or 0.55), which this preserves as the layer opacity. + * + * @param String pathData SVG "d" attribute contents; may hold several "M..." subpaths. + * @param Float opacity The source path's fill-opacity (1 = the highlight layer). + * @param Color? color The layer's own paint color, overriding the caller's tint; null to follow it (the + * default for every theme-following layer). + * @return IconLayer The layer ready to compose into a [compositeIcon]. + */ +private fun compositeIconLayer(pathData: String, opacity: Float = 1f, color: Color? = null): IconLayer = + IconLayer(path = PathParser().parsePathString(pathData).toPath(), style = IconStyle.Filled, opacity = opacity, color = color) + +/** + * Builds a Blender two-tone icon from its layers, given in the source SVG's paint order. A couple of + * the exports carry a 23-unit axis instead of 24 (the bake tool trimmed the viewBox), so the optional + * offsets re-center those paths in the shared 24x24 viewport at parse time. + * + * @param IconLayer layers The paint layers, first to last (see [compositeIconLayer]). + * @param Float offsetX Horizontal re-centering translation in viewport units. + * @param Float offsetY Vertical re-centering translation in viewport units. + * @return UmamoIcon The icon ready to draw. + */ +private fun compositeIcon(vararg layers: IconLayer, offsetX: Float = 0f, offsetY: Float = 0f): UmamoIcon { + if (offsetX != 0f || offsetY != 0f) { + for (layer in layers) { + layer.path.translate(Offset(offsetX, offsetY)) + } + } + return UmamoIcon(layers = layers.toList()) +} + +/** + * The bundled icon set. Despite the name there is no CompositionLocal here yet; it is a shared + * top-level value referenced directly (for example LocalUmamoIcons.reset), kept so a per-theme + * override can layer on later without touching call sites. + */ +val LocalUmamoIcons = + UmamoIcons( + // Tabler "restore", with the middle dot deleted. (viewBox 0 0 24 24, stroked) + reset = simpleIcon("M3.06 13a9 9 0 1 0 .49 -4.087 M3 4.001v5h5"), + // Tabler "restore" (viewBox 0 0 24 24, stroked). + resetAll = simpleIcon("M3.06 13a9 9 0 1 0 .49 -4.087 M3 4.001v5h5 M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"), + // Tabler "folder-plus" (viewBox 0 0 24 24, stroked). + groupAdd = simpleIcon("M12 19h-7a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2h4l3 3h7a2 2 0 0 1 2 2v3.5 M16 19h6 M19 16v6"), + // Tabler "adjustments-plus", rotated and flipped. (viewBox 0 0 24 24, stroked) + parameterAdd = simpleIcon("M10,4C11.097,4 12,4.903 12,6C12,7.097 11.097,8 10,8C8.903,8 8,7.097 8,6C8,4.903 8.903,4 10,4 M4,6L8,6 M12,6L20,6 M15.592,13.958C14.668,13.765 14,12.944 14,12C14,10.903 14.903,10 16,10C17.097,10 18,10.903 18,12 M4,12L14,12 M18,12L20,12 M7,16C8.097,16 9,16.903 9,18C9,19.097 8.097,20 7,20C5.903,20 5,19.097 5,18C5,16.903 5.903,16 7,16 M4,18L5,18 M9,18L12,18 M19,16L19,22 M16,19L22,19"), + // Tabler "yoga" (viewBox 0 0 24 24, stroked). + armature = simpleIcon("M4 20h4l1.5 -3 M17 20l-1 -5h-5l1 -7 M4 10l4 -1l4 -1l4 1.5l4 1.5 M10.007 5a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"), + // Tabler "stack-2" (viewBox 0 0 24 24, stroked). When the part is isolated as a layer + // or grouped by draw order, draw a rounded outline around this icon. + part = simpleIcon("M12 4l-8 4l8 4l8 -4l-8 -4 M4 12l8 4l8 -4 M4 16l8 4l8 -4"), + // Tabler "triangle" (viewBox 0 0 24 24, stroked). Authored already rotated 15 degrees clockwise. + mesh = simpleIcon("M14.166,3.054L2.836,14.031C2.598,14.269 2.428,14.565 2.341,14.889C2.071,15.896 2.67,16.947 3.674,17.228L19.336,21.421C20.346,21.678 21.389,21.067 21.659,20.061C21.746,19.737 21.746,19.396 21.659,19.071L17.329,3.9C17.142,3.258 16.632,2.758 15.986,2.585C15.34,2.412 14.649,2.59 14.166,3.053"), + // Tabler "mesh" (viewBox 0 0 24 24, stroked). + warpDeformer = simpleIcon("M3 9h18 M3 15h18 M8 4c.485 .445 3.5 3.312 3.5 8c0 .663 -.07 4.848 -3.5 8 M15 4a17 17 0 0 1 2.004 8c0 1.51 -.201 4.628 -2.004 8 M18.778 20h-13.556a2.22 2.22 0 0 1 -2.222 -2.222v-11.556c0 -1.227 .995 -2.222 2.222 -2.222h13.556c1.227 0 2.222 .995 2.222 2.222v11.556a2.22 2.22 0 0 1 -2.222 2.222"), + // Tabler "circle-dot" (viewBox 0 0 24 24, stroked). + rotationDeformer = simpleIcon("M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M3 12a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"), + // Tabler "search" (viewBox 0 0 24 24, stroked). + search = simpleIcon("M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0 M21 21l-6 -6"), + // Tabler "x" (viewBox 0 0 24 24, stroked). + close = simpleIcon("M18 6l-12 12 M6 6l12 12"), + // Tabler "plus" (viewBox 0 0 24 24, stroked). + plus = simpleIcon("M12 5l0 14 M5 12l14 0"), + // Tabler "color-picker" (viewBox 0 0 24 24, stroked). + eyedropper = simpleIcon("M11 7l6 6 M4 16l11.7 -11.7a1 1 0 0 1 1.4 0l2.6 2.6a1 1 0 0 1 0 1.4l-11.7 11.7h-4v-4"), + // Tabler "play-basketball" - Modified (viewBox 0 0 24 24, stroked). + puppetRoot = simpleIcon("M14.493,5C14.493,6.097 13.59,7 12.493,7C11.396,7 10.493,6.097 10.493,5C10.493,3.903 11.396,3 12.493,3C13.59,3 14.493,3.903 14.493,5 M18.5,21L15.5,18L14.75,16.5 M9.5,21L9.5,17L13.5,14L13,8 M18.5,12L17.5,9L13,8L9.5,11L5.5,10.5"), + // Tabler "filter" (viewBox 0 0 24 24, stroked). + filterUnfiltered = simpleIcon("M8 4h12v2.172a2 2 0 0 1 -.586 1.414l-3.914 3.914m-.5 3.5v4l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227 M3 3l18 18"), + // Tabler "filter-off" (viewBox 0 0 24 24, stroked). + filterFiltered = simpleIcon("M4 4h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v7l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227"), + // Tabler "eye" (viewBox 0 0 24 24, stroked). + eyeVisible = simpleIcon("M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0 M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"), + // Tabler "eye-off" (viewBox 0 0 24 24, stroked). + eyeHidden = simpleIcon("M10.585 10.587a2 2 0 0 0 2.829 2.828 M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87 M3 3l18 18"), + // Tabler "link" (viewBox 0 0 24 24, stroked). + linked = simpleIcon("M9 15l6 -6 M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464 M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463"), + // Tabler "link-off" (viewBox 0 0 24 24, stroked). + unlinked = simpleIcon("M9 15l3 -3m2 -2l1 -1 M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464 M3 3l18 18 M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463"), + // Tabler "lock" (viewBox 0 0 24 24, stroked). + locked = simpleIcon("M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6 M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0 M8 11v-4a4 4 0 1 1 8 0v4"), + // Tabler "lock-off" (viewBox 0 0 24 24, stroked). + unlocked = simpleIcon("M15 11h2a2 2 0 0 1 2 2v2m0 4a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6a2 2 0 0 1 2 -2h4 M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0 M8 11v-3m.719 -3.289a4 4 0 0 1 7.281 2.289v4 M3 3l18 18"), + // Tabler "pointer" (viewBox 0 0 24 24, stroked). + selectable = simpleIcon("M7.904 17.563a1.2 1.2 0 0 0 2.228 .308l2.09 -3.093l4.907 4.907a1.067 1.067 0 0 0 1.509 0l1.047 -1.047a1.067 1.067 0 0 0 0 -1.509l-4.907 -4.907l3.113 -2.09a1.2 1.2 0 0 0 -.309 -2.228l-13.582 -3.904l3.904 13.563"), + // Tabler "pointer-off" (viewBox 0 0 24 24, stroked). + unselectable = simpleIcon("M15.662 11.628l2.229 -1.496a1.2 1.2 0 0 0 -.309 -2.228l-8.013 -2.303m-5.569 -1.601l3.904 13.563a1.2 1.2 0 0 0 2.228 .308l2.09 -3.093l4.907 4.907a1.067 1.067 0 0 0 1.509 0l.524 -.524 M3 3l18 18"), + // Tabler "picnic-table"(It looks like Blender's 3D viewport icon and I think it's amusing.) (viewBox 0 0 24 24, stroked). + spaceViewport = simpleIcon("M16 7l2 9m-10 -9l-2 9m-1 -9h14m2 5h-18"), + // Tabler "texture" (viewBox 0 0 24 24, stroked). + spaceTexture = simpleIcon("M6 3l-3 3 M21 18l-3 3 M11 3l-8 8 M16 3l-13 13 M21 3l-18 18 M21 8l-13 13 M21 13l-8 8"), + // Tabler "list-tree" (viewBox 0 0 24 24, stroked). + spaceOutliner = simpleIcon("M9 6h11 M12 12h8 M15 18h5 M5 6v.01 M8 12v.01 M11 18v.01"), + // Tabler "history" (viewBox 0 0 24 24, stroked). + spaceHistory = simpleIcon("M12 8l0 4l2 2 M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5"), + // Tabler "adjustments-horizontal" (viewBox 0 0 24 24, stroked). + spaceParameters = simpleIcon("M12 6a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M4 6l8 0 M16 6l4 0 M6 12a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M4 12l2 0 M10 12l10 0 M15 18a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M4 18l11 0 M19 18l1 0"), + // Tabler "chart-grid-dots" (viewBox 0 0 24 24, stroked). + spaceKeyformSheet = simpleIcon("M16 6a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M4 12a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M4 18a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M16 18a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M8 18h8 M18 20v1 M18 3v1 M6 20v1 M6 10v-7 M12 3v18 M18 8v8 M8 12h13 M21 6h-1 M16 6h-13 M3 12h1 M20 18h1 M3 18h1 M6 14v2"), + // Tabler "list-details" (viewBox 0 0 24 24, stroked). + spaceProperties = simpleIcon("M13 5h8 M13 9h5 M13 15h8 M13 19h5 M3 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4 M3 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4"), + // Tabler "tools" (viewBox 0 0 24 24, stroked). + spaceTool = simpleIcon("M3 21h4l13 -13a1.5 1.5 0 0 0 -4 -4l-13 13v4 M14.5 5.5l4 4 M12 8l-5 -5l-4 4l5 5 M7 8l-1.5 1.5 M16 12l5 5l-4 4l-5 -5 M16 17l-1.5 1.5"), + // Tabler "movie" (viewBox 0 0 24 24, stroked). + spaceAnimation = simpleIcon("M4 6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2l0 -12 M8 4l0 16 M16 4l0 16 M4 8l4 0 M4 16l4 0 M4 12l16 0 M16 8l4 0 M16 16l4 0"), + // Tabler "chevron-up" (viewBox 0 0 24 24, stroked). + chevronUp = simpleIcon("M6 15l6 -6l6 6"), + // Tabler "chevron-down" (viewBox 0 0 24 24, stroked). + chevronDown = simpleIcon("M6 9l6 6l6 -6"), + // Tabler "chevron-left" (viewBox 0 0 24 24, stroked). + chevronLeft = simpleIcon("M15 6l-6 6l6 6"), + // Tabler "chevron-right" (viewBox 0 0 24 24, stroked). + chevronRight = simpleIcon("M9 6l6 6l-6 6"), + // Tabler "dots" (viewBox 0 0 24 24, stroked). + dots = simpleIcon("M4 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M18 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"), + // Tabler "grip-vertical" (viewBox 0 0 24 24, stroked). + gripVertical = simpleIcon("M8 5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M8 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M8 19a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M14 5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M14 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M14 19a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"), + // Tabler "grip-horizontal" (viewBox 0 0 24 24, stroked). + gripHorizontal = simpleIcon("M4 9a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M4 15a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M11 9a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M11 15a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M18 9a1 1 0 1 0 2 0a1 1 0 1 0 -2 0 M18 15a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"), + // Tabler "marquee-2" (viewBox 0 0 24 24, stroked) - the Box Select tool. + toolBoxSelect = simpleIcon("M4 6v-1a1 1 0 0 1 1 -1h1m5 0h2m5 0h1a1 1 0 0 1 1 1v1m0 5v2m0 5v1a1 1 0 0 1 -1 1h-1m-5 0h-2m-5 0h-1a1 1 0 0 1 -1 -1v-1m0 -5v-2"), + // Tabler "circle-dashed" (viewBox 0 0 24 24, stroked) - the Circle Select brush. + toolCircleSelect = simpleIcon("M8.56 3.69a9 9 0 0 0 -2.92 1.95 M3.69 8.56a9 9 0 0 0 -.69 3.44 M3.69 15.44a9 9 0 0 0 1.95 2.92 M8.56 20.31a9 9 0 0 0 3.44 .69 M15.44 20.31a9 9 0 0 0 2.92 -1.95 M20.31 15.44a9 9 0 0 0 .69 -3.44 M20.31 8.56a9 9 0 0 0 -1.95 -2.92 M15.44 3.69a9 9 0 0 0 -3.44 -.69"), + // Point on a diagonal edge (authored in the Tabler idiom) - the Insert Vertex tool. + toolInsertVertex = simpleIcon("M4 20l16 -16 M12 12m-1.5 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 -3 0"), + // Two vertices joined by a cut (authored in the Tabler idiom) - the Draw Connect tool. + toolDrawConnect = simpleIcon("M6 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M18 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M7.5 7.5l9 9"), + // Tabler "arrows-move" (viewBox 0 0 24 24, stroked) - the Grab (move) operator. + toolGrab = simpleIcon("M18 9l3 3l-3 3 M15 12h6 M6 9l-3 3l3 3 M3 12h6 M9 18l3 3l3 -3 M12 15v6 M9 6l3 -3l3 3 M12 3v6"), + // Tabler "rotate-clockwise" (viewBox 0 0 24 24, stroked) - the Rotate operator. + toolRotate = simpleIcon("M4.05 11a8 8 0 1 1 .5 4m-.5 5v-5h5"), + // Tabler "arrows-diagonal" (viewBox 0 0 24 24, stroked) - the Scale operator. + toolScale = simpleIcon("M16 4l4 0l0 4 M14 10l6 -6 M8 20l-4 0l0 -4 M4 20l6 -6"), + // Tabler "flip-horizontal" (viewBox 0 0 24 24, stroked) - Mirror H. + toolMirrorH = simpleIcon("M12 3l0 18 M16 7l0 10l5 0l-5 -10 M8 7l0 10l-5 0l5 -10"), + // Tabler "flip-vertical" (viewBox 0 0 24 24, stroked) - Mirror V. + toolMirrorV = simpleIcon("M3 12l18 0 M7 16l10 0l-10 5l0 -5 M7 8l10 0l-10 -5l0 5"), + // Tabler "focus-centered" (viewBox 0 0 24 24, stroked) - the transform pivot point. + transformPivot = simpleIcon("M12 12m-1.5 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 -3 0 M4 8v-2a2 2 0 0 1 2 -2h2 M4 16v2a2 2 0 0 0 2 2h2 M16 4h2a2 2 0 0 1 2 2v2 M16 20h2a2 2 0 0 0 2 -2v-2"), + // Tabler "magnet" (viewBox 0 0 24 24, stroked) - the snap operations. + snap = simpleIcon("M4 13v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a2 2 0 0 0 6 0v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a8 8 0 0 1 -16 0 M4 8l5 0 M15 8l4 0"), + // Concentric circles in the Tabler idiom (authored here) - proportional editing's influence rings. + proportionalEdit = simpleIcon("M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0 M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"), + // Tabler "terminal" (viewBox 0 0 24 24, stroked). + logsTerminal = simpleIcon("M5 7l5 5l-5 5 M12 19l7 0"), + // Tabler "copy" (viewBox 0 0 24 24, stroked). + copy = simpleIcon("M7 9.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667l0 -8.66 M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1"), + // Tabler "floppy" (viewBox 0 0 24 24, stroked). + floppy = simpleIcon("M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2 M10 14a2 2 0 1 0 4 0a2 2 0 1 0 -4 0 M14 4l0 4l-6 0l0 -4"), + // Tabler "layers-selected" (viewBox 0 0 24 24, stroked). + sources = simpleIcon("M8 10.5l6.492 -6.492 M13.496 16l6.504 -6.504l-6.504 6.504 M8.586 15.414l10.827 -10.827 M8 6a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8 M16 16v2a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h2"), + // Tabler "file-unknown" (viewBox 0 0 24 24, stroked). + missingFile = simpleIcon("M14 3v4a1 1 0 0 0 1 1h4 M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2 M12 17v.01 M12 14a1.5 1.5 0 1 0 -1.14 -2.474"), + // Tabler "file-plus" (viewBox 0 0 24 24, stroked). + addFile = simpleIcon("M14 3v4a1 1 0 0 0 1 1h4 M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2 M12 11l0 6 M9 14l6 0"), + // Tabler "refresh" (viewBox 0 0 24 24, stroked). + refresh = simpleIcon("M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4 M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"), + // Tabler "refresh-alert" (viewBox 0 0 24 24, stroked). + refreshAlert = simpleIcon("M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4 M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4 M12 9l0 3 M12 15l.01 0"), + // Tabler "wand" (viewBox 0 0 24 24, stroked). + wand = simpleIcon("M6 21l15 -15l-3 -3l-15 15l3 3 M15 6l3 3 M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2 M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"), + // Tabler "language" (viewBox 0 0 24 24, stroked). + language = simpleIcon("M9 6.371c0 4.418 -2.239 6.629 -5 6.629 M4 6.371h7 M5 9c0 2.144 2.252 3.908 6 4 M12 20l4 -9l4 9 M19.1 18h-6.2 M6.694 3l.793 .582"), + // The icons below are adapted from the Blender project's icon set (GPL-2.0-or-later, compatible + // with this project's GPL-3.0; source SVGs archived under docs/design/icons/). Each keeps + // Blender's two-tone contrast: a full-strength highlight layer over a muted context layer. + // Blender "blender_icon_object_datamode" (viewBox 0 0 24 24, baked). + editorModeObject = + compositeIcon( + compositeIconLayer( + "M2.25,1.5C1.839,1.5 1.5,1.839 1.5,2.25L1.5,7.5L3,7.5L3,3L7.5,3L7.5,1.5L2.25,1.5ZM16.5,1.5L16.5,3L21,3L21,7.5L22.5,7.5L22.5,2.25C22.5,1.839 22.161,1.5 21.75,1.5L16.5,1.5ZM1.5,16.5L1.5,21.75C1.5,22.161 1.839,22.5 2.25,22.5L7.5,22.5L7.5,21L3,21L3,16.5L1.5,16.5ZM21,16.5L21,21L16.5,21L16.5,22.5L21.75,22.5C22.161,22.5 22.5,22.161 22.5,21.75L22.5,16.5L21,16.5Z", + opacity = 0.6f, + ), + compositeIconLayer( + "M6.75,6C6.336,6 6,6.336 6,6.75L6,17.25C6,17.664 6.336,18 6.75,18L17.25,18C17.664,18 18,17.664 18,17.25L18,6.75C18,6.336 17.664,6 17.25,6L6.75,6Z", + ), + ), + // Blender "blender_icon_editmode_hlt" (viewBox 0 0 24 24, baked). + editorModeEdit = + compositeIcon( + compositeIconLayer( + "M21.75,1.5C22.164,1.5 22.5,1.836 22.5,2.25L22.5,8.25C22.5,8.664 22.164,9 21.75,9L15.75,9C15.336,9 15,8.664 15,8.25L15,2.25C15,1.836 15.336,1.5 15.75,1.5L21.75,1.5Z", + ), + compositeIconLayer( + "M21,21.75C21,22.161 20.661,22.5 20.25,22.5L15.75,22.5C15.339,22.5 15,22.161 15,21.75L15,20.988L7.5,20.988L7.5,21.75C7.5,22.161 7.161,22.5 6.75,22.5L2.25,22.5C1.839,22.5 1.5,22.161 1.5,21.75L1.5,17.25C1.5,16.839 1.839,16.5 2.25,16.5L3,16.5L3,9L2.25,9C1.839,9 1.5,8.661 1.5,8.25L1.5,3.75C1.5,3.339 1.839,3 2.25,3L6.75,3C7.161,3 7.5,3.339 7.5,3.75L7.5,4.488L12.75,4.488C12.754,4.488 12.757,4.488 12.761,4.488C13.172,4.488 13.511,4.827 13.511,5.238C13.511,5.65 13.172,5.988 12.761,5.988C12.757,5.988 12.754,5.988 12.75,5.988L7.5,5.988L7.5,8.25C7.5,8.661 7.161,9 6.75,9L4.5,9L4.5,16.5L6.75,16.5C7.161,16.5 7.5,16.839 7.5,17.25L7.5,19.488L15,19.488L15,17.25C15,16.839 15.339,16.5 15.75,16.5L18,16.5L18,11.25C18,11.246 18,11.243 18,11.239C18,10.828 18.339,10.489 18.75,10.489C19.161,10.489 19.5,10.828 19.5,11.239C19.5,11.243 19.5,11.246 19.5,11.25L19.5,16.5L20.25,16.5C20.661,16.5 21,16.839 21,17.25L21,21.75ZM19.5,21L19.5,18L16.5,18L16.5,20.121C16.513,20.201 16.513,20.282 16.5,20.361L16.5,21L19.5,21ZM6,21L6,18L3,18L3,21L6,21ZM6,7.5L6,4.5L3,4.5L3,7.5L6,7.5Z", + opacity = 0.6f, + ), + ), + // Blender "blender_icon_vertexsel" (viewBox 0 0 24 23, baked; re-centered to 24x24). + meshSelectVertex = + compositeIcon( + compositeIconLayer( + "M8.246,1.583C8.047,1.583 7.856,1.662 7.715,1.803L4.724,4.794C3.988,5.501 5.078,6.591 5.785,5.855L8.556,3.083L20.996,3.083L20.996,15.523L16.935,19.583L4.499,19.583L4.505,15.074L3.005,15.071L2.996,20.333C2.996,20.748 3.331,21.083 3.746,21.083L17.246,21.083C17.445,21.083 17.635,21.004 17.776,20.864L22.276,16.364C22.417,16.223 22.496,16.032 22.496,15.833L22.496,2.333C22.496,1.919 22.16,1.583 21.746,1.583L8.246,1.583Z", + opacity = 0.6f, + ), + compositeIconLayer( + "M2.254,7.575C1.84,7.575 1.504,7.91 1.504,8.325L1.504,12.825C1.504,13.239 1.84,13.575 2.254,13.575L6.754,13.575C7.169,13.575 7.504,13.239 7.504,12.825L7.504,8.325C7.504,7.91 7.169,7.575 6.754,7.575L2.254,7.575Z", + ), + offsetY = 0.5f, + ), + // Blender "blender_icon_edgesel" (viewBox 0 0 23 24, baked; re-centered to 24x24). + meshSelectEdge = + compositeIcon( + compositeIconLayer( + "M15.095,21.744C15.095,22.158 14.759,22.494 14.345,22.494L11.345,22.494C10.931,22.494 10.595,22.158 10.595,21.744L10.595,8.244C10.595,7.83 10.931,7.494 11.345,7.494L14.345,7.494C14.759,7.494 15.095,7.83 15.095,8.244L15.095,21.744Z", + ), + compositeIconLayer( + "M21.083,15.756C21.083,15.955 21.004,16.145 20.864,16.286L17.875,19.274C17.168,20.011 16.078,18.921 16.815,18.214L19.583,15.445L19.583,3.006L7.144,3.006L3.083,7.066L3.083,19.506L9.094,19.495L9.097,20.995L2.336,21.006C1.921,21.008 1.583,20.671 1.583,20.256L1.583,6.756C1.583,6.557 1.662,6.366 1.803,6.226L6.303,1.726C6.444,1.585 6.634,1.506 6.833,1.506L20.333,1.506C20.748,1.506 21.083,1.842 21.083,2.256L21.083,15.756Z", + opacity = 0.6f, + ), + offsetX = 0.5f, + ), + // Blender "blender_icon_facesel" (viewBox 0 0 24 24, baked). + meshSelectFace = + compositeIcon( + compositeIconLayer( + "M2.256,7.494C1.842,7.494 1.506,7.83 1.506,8.244L1.506,21.744C1.506,22.158 1.842,22.494 2.256,22.494L15.756,22.494C16.17,22.494 16.506,22.158 16.506,21.744L16.506,8.244C16.506,7.83 16.17,7.494 15.756,7.494L2.256,7.494Z", + ), + compositeIconLayer( + "M8.244,1.506C8.045,1.506 7.855,1.585 7.714,1.726L4.726,4.714C4.545,4.888 4.506,5.057 4.506,5.244L4.506,5.994L6.006,5.994L6.01,5.55L8.555,3.006L20.994,3.006L20.994,15.445L18.449,17.99L18.006,17.994L18.006,19.494L18.756,19.494C18.932,19.494 19.112,19.455 19.274,19.286L22.274,16.286C22.415,16.145 22.494,15.955 22.494,15.756L22.494,2.256C22.494,1.842 22.158,1.506 21.744,1.506L8.244,1.506Z", + opacity = 0.6f, + ), + ), + // Blender "blender_icon_uv_vertexsel" (viewBox 0 0 24 24, baked). + uvSelectVertex = + compositeIcon( + compositeIconLayer( + "M2.25,1.5C1.836,1.5 1.5,1.836 1.5,2.25L1.5,6.75C1.5,7.164 1.836,7.5 2.25,7.5L6.75,7.5C7.164,7.5 7.5,7.164 7.5,6.75L7.5,2.25C7.5,1.836 7.164,1.5 6.75,1.5L2.25,1.5Z", + ), + compositeIconLayer( + "M8.945,3L8.945,4.5L12,4.5L12,12L4.5,12L4.5,9.012L3,9.012L3,21.75C3,22.161 3.339,22.5 3.75,22.5L12.75,22.5C13.162,22.5 13.5,22.161 13.5,21.75L13.5,13.5L21.75,13.5C22.162,13.5 22.5,13.161 22.5,12.75L22.5,3.75C22.5,3.338 22.162,3 21.75,3L8.945,3ZM13.5,4.5L21,4.5L21,12L13.5,12L13.5,4.5ZM4.5,13.5L12,13.5L12,21L4.5,21L4.5,13.5Z", + opacity = 0.6f, + ), + ), + // Blender "blender_icon_uv_edgesel" (viewBox 0 0 23 24, baked; re-centered to 24x24). + uvSelectEdge = + compositeIcon( + compositeIconLayer( + "M9.088,2.25C9.088,1.836 9.424,1.5 9.838,1.5L12.838,1.5C13.253,1.5 13.588,1.836 13.588,2.25L13.588,14.25C13.588,14.664 13.253,15 12.838,15L9.838,15C9.424,15 9.088,14.664 9.088,14.25L9.088,2.25Z", + ), + compositeIconLayer( + "M1.588,3.75C1.588,3.336 1.924,3 2.338,3L7.588,3L7.588,4.5L3.088,4.5L3.088,12L7.588,12L7.588,13.5L3.088,13.5L3.088,21L10.588,21L10.588,16.5L12.088,16.5L12.088,21.75C12.088,22.164 11.753,22.5 11.338,22.5L2.338,22.5C1.924,22.5 1.588,22.164 1.588,21.75L1.588,3.75ZM15.088,3L20.328,3.007C20.742,3.007 21.078,3.343 21.078,3.757L21.078,12.757C21.078,13.17 20.744,13.506 20.331,13.507L15.081,13.51L15.078,12.01L19.578,12.01L19.578,4.51L15.091,4.5L15.088,3Z", + opacity = 0.6f, + ), + offsetX = 0.5f, + ), + // Blender "blender_icon_uv_facesel" (viewBox 0 0 24 24, baked). + uvSelectFace = + compositeIcon( + compositeIconLayer( + "M21.747,3.003L16.497,3.015L16.503,4.515L21,4.506L21,12.006L16.497,12.015L16.503,13.515L21.753,13.503C22.166,13.501 22.5,13.166 22.5,12.753L22.5,3.753C22.5,3.337 22.162,3.001 21.747,3.003L21.747,3.003ZM3,16.506L3,21.744C3,22.158 3.336,22.494 3.75,22.494L12.75,22.494C13.164,22.494 13.5,22.158 13.5,21.744L13.5,16.506L12,16.506L12,20.994L4.5,20.994L4.5,16.506L3,16.506Z", + opacity = 0.6f, + ), + compositeIconLayer( + "M2.25,1.506C1.836,1.506 1.5,1.842 1.5,2.256L1.5,14.256C1.5,14.67 1.836,15.006 2.25,15.006L14.25,15.006C14.664,15.006 15,14.67 15,14.256L15,2.256C15,1.842 14.664,1.506 14.25,1.506L2.25,1.506Z", + ), + ), + // The 2D cursor (docs/design/cursors/2DCursor.svg, authored 1600x1600, converted verbatim): + // a red/white dashed ring with axis-colored arm stubs - red X arms, blue Z arms - over + // 0.85-alpha black arm shafts. Genuinely multi-color, so every layer bakes its own paint + // (the SVG's rects are rewritten as equivalent M/h/v/z path data; PathParser reads paths only). + cursor2d = + UmamoIcon( + layers = + listOf( + // The ring's white sectors, then its red sectors. + compositeIconLayer( + "M377.065,801.822C376.711,725.254 397.337,651.256 434.776,587.043L496.976,623.308C465.915,676.582 448.771,737.966 449.064,801.489L377.065,801.822ZM801.808,377.064L801.517,449.063C771.034,448.94 740.038,452.831 709.191,461.097C678.344,469.362 649.555,481.49 623.218,496.838L586.966,434.63C618.702,416.136 653.386,401.51 690.556,391.55C727.726,381.59 765.077,376.915 801.808,377.064ZM1167.18,590.109L1104.66,625.821C1073.16,570.661 1027.62,526.074 974.08,495.468L1009.81,432.961C1074.34,469.851 1129.2,523.623 1167.18,590.109ZM1165.22,1012.96L1103.02,976.692C1134.09,923.418 1151.23,862.034 1150.94,798.511L1222.93,798.178C1223.29,874.746 1202.66,948.744 1165.22,1012.96ZM798.191,1222.94L798.482,1150.94C828.965,1151.06 859.961,1147.17 890.809,1138.9C921.656,1130.64 950.445,1118.51 976.782,1103.16L1013.03,1165.37C981.298,1183.86 946.614,1198.49 909.444,1208.45C872.273,1218.41 834.923,1223.09 798.191,1222.94ZM432.817,1009.89L495.336,974.179C526.844,1029.34 572.384,1073.93 625.92,1104.53L590.186,1167.04C525.657,1130.15 470.795,1076.38 432.817,1009.89Z", + color = Color.White, + ), + compositeIconLayer( + "M434.776,1012.96C397.337,948.745 376.712,874.747 377.065,798.18L449.064,798.512C448.771,862.036 465.915,923.419 496.976,976.693L434.776,1012.96ZM590.185,432.962L625.919,495.468C572.383,526.074 526.844,570.662 495.336,625.822L432.816,590.11C470.794,523.624 525.656,469.852 590.185,432.962ZM1013.03,434.63L976.782,496.838C950.445,481.49 921.656,469.362 890.809,461.097C859.962,452.831 828.966,448.94 798.483,449.063L798.192,377.064C834.923,376.915 872.274,381.59 909.444,391.55C946.614,401.51 981.298,416.136 1013.03,434.63ZM1222.93,801.82L1150.94,801.488C1151.23,737.964 1134.09,676.581 1103.02,623.307L1165.22,587.042C1202.66,651.255 1223.29,725.253 1222.93,801.82ZM1009.82,1167.04L974.081,1104.53C1027.62,1073.93 1073.16,1029.34 1104.66,974.178L1167.18,1009.89C1129.21,1076.38 1074.34,1130.15 1009.82,1167.04ZM586.965,1165.37L623.217,1103.16C649.555,1118.51 678.343,1130.64 709.191,1138.9C740.038,1147.17 771.034,1151.06 801.517,1150.94L801.808,1222.94C765.077,1223.09 727.726,1218.41 690.556,1208.45C653.386,1198.49 618.701,1183.86 586.965,1165.37Z", + color = Color(0xFFFF0000), + ), + // The horizontal (X) arms: 0.85-alpha black shafts with red tips. + compositeIconLayer("M120,760.609h480v80h-480z", color = Color.Black, opacity = 0.85f), + compositeIconLayer("M0,760.304h120v80h-120z", color = Color(0xFFFF0000)), + compositeIconLayer("M1000,760.304h480v80h-480z", color = Color.Black, opacity = 0.85f), + compositeIconLayer("M1480,760h120v80h-120z", color = Color(0xFFFF0000)), + // The vertical (Z) arms: 0.85-alpha black shafts with blue tips. + compositeIconLayer( + "M839.696,600.304L759.696,600.304L759.696,120.304L839.696,120.304L839.696,600.304Z", + color = Color.Black, + opacity = 0.85f, + ), + compositeIconLayer("M840,120.304L760,120.304L760,0.304L840,0.304L840,120.304Z", color = Color(0xFF0000FF)), + compositeIconLayer( + "M840,1000.3L760,1000.3L760,1480.3L840,1480.3L840,1000.3Z", + color = Color.Black, + opacity = 0.85f, + ), + compositeIconLayer("M840.304,1480.3L760.304,1480.3L760.304,1600.3L840.304,1600.3L840.304,1480.3Z", color = Color(0xFF0000FF)), + ), + viewportSize = 1600f, + ), + ) + +/** + * Draws [icon] scaled about the origin to fill the current square [DrawScope], painting its layers in + * order with each layer's style and opacity. The caller supplies one tint; a two-tone icon's muted + * layer derives from it via the layer opacity, so both tones follow the theme without a second color. + * + * @param UmamoIcon icon The icon to paint. + * @param Color color The paint color (icons are monochrome and tinted by the caller). + */ +fun DrawScope.drawIcon(icon: UmamoIcon, color: Color) { + // The paths live in a square viewport; scale it about the origin so it fills the (square) canvas. + val drawScale = size.minDimension / icon.viewportSize + withTransform({ scale(scaleX = drawScale, scaleY = drawScale, pivot = Offset.Zero) }) { + for (layer in icon.layers) { + val drawStyle = + when (val style = layer.style) { + IconStyle.Filled -> Fill + is IconStyle.Outlined -> + Stroke( + width = style.strokeWidth, + cap = StrokeCap.Round, + join = StrokeJoin.Round, + ) + } + drawPath(path = layer.path, color = layer.color ?: color, alpha = layer.opacity, style = drawStyle) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/SelectionChrome.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/SelectionChrome.kt new file mode 100644 index 0000000..27de6b9 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/SelectionChrome.kt @@ -0,0 +1,131 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.dp +import kotlin.math.abs +import kotlin.math.min + +// The on/off dash length (equal halves, so offsetting the second pass by one length makes its dashes fall in +// the first pass's gaps - the alternating "marching ants" look). +private val ANTS_DASH = 5.dp + +// The affordance line width, shared so the crosshair, box, and circle read identically. +private val ANTS_STROKE = 1.dp + +// The selection region's fill alpha: mostly transparent, just enough to read the enclosed area over busy art. +private const val SELECTION_FILL_ALPHA = 0.12f + +/** + * The two-tone "marching ants" palette for the editor's region-selection affordances (crosshair guides, + * box, and circle), read once from the theme so they share one look. The two dash tones are opposite in + * luminance (light plus dark), so the alternating outline stays legible over any viewport background - + * grid, bright art, or dark art - where a single-color dash washes out. + * + * @property Color primary The first dash tone (the theme marquee). + * @property Color secondary The contrasting dash tone that fills the primary's gaps. + * @property Color fill The mostly-transparent region fill for the box and circle (the guides use no fill). + */ +class SelectionOverlayStyle(val primary: Color, val secondary: Color, val fill: Color) + +/** + * Builds the [SelectionOverlayStyle] from the active theme colors: the marquee and its contrast tone for the + * two-tone dash, and a low-alpha marquee wash for the region fill. + * + * @param UmamoColors colors The active theme palette. + * @return SelectionOverlayStyle The shared affordance style. + */ +fun selectionOverlayStyle(colors: UmamoColors): SelectionOverlayStyle = + SelectionOverlayStyle( + primary = colors.viewportMarquee, + secondary = colors.viewportMarqueeContrast, + fill = colors.viewportMarquee.copy(alpha = SELECTION_FILL_ALPHA), + ) + +/** + * Strokes a shape twice with the marching-ants dash - once in each tone, the second offset by one dash so + * the tones alternate along the outline. The single primitive behind every selection affordance, so the + * crosshair, box, and circle cannot drift apart. + * + * @param SelectionOverlayStyle style The two-tone palette. + * @param Function drawStroke Strokes the shape with the given color and dash path effect; called twice. + */ +private inline fun strokeMarchingAnts(style: SelectionOverlayStyle, dashPx: Float, drawStroke: (Color, PathEffect) -> Unit) { + val intervals = floatArrayOf(dashPx, dashPx) + drawStroke(style.primary, PathEffect.dashPathEffect(intervals, 0f)) + drawStroke(style.secondary, PathEffect.dashPathEffect(intervals, dashPx)) +} + +/** + * Draws Blender's full-area crosshair guides for an armed region gesture (viewport Box-select and Zoom + * Region, and the keyform sheet's box select): a horizontal and a vertical marching-ants line spanning the + * area through [cursor]. The caller clips to the area bounds, so the lines stop at the area edge rather + * than bleeding across panels. + * + * @param Offset cursor The pointer position in area-local pixels. + * @param Size size The area size in pixels. + * @param SelectionOverlayStyle style The shared two-tone style. + */ +fun DrawScope.drawCrosshairGuides(cursor: Offset, size: Size, style: SelectionOverlayStyle) { + val strokeWidth = ANTS_STROKE.toPx() + strokeMarchingAnts(style, ANTS_DASH.toPx()) { color, dash -> + drawLine(color = color, start = Offset(0f, cursor.y), end = Offset(size.width, cursor.y), strokeWidth = strokeWidth, pathEffect = dash) + drawLine(color = color, start = Offset(cursor.x, 0f), end = Offset(cursor.x, size.height), strokeWidth = strokeWidth, pathEffect = dash) + } +} + +/** + * Draws a rubber-band selection / zoom box: a mostly-transparent fill plus a two-tone marching-ants border. + * The single shared style for the non-armed and armed Box-select and for the Zoom Region gesture. + * + * @param Offset topLeft The box top-left in area-local pixels. + * @param Size size The box size in pixels. + * @param SelectionOverlayStyle style The shared two-tone style. + */ +fun DrawScope.drawSelectionBox(topLeft: Offset, size: Size, style: SelectionOverlayStyle) { + drawRect(color = style.fill, topLeft = topLeft, size = size) + val strokeWidth = ANTS_STROKE.toPx() + strokeMarchingAnts(style, ANTS_DASH.toPx()) { color, dash -> + drawRect(color = color, topLeft = topLeft, size = size, style = Stroke(width = strokeWidth, pathEffect = dash)) + } +} + +/** + * Draws the Circle-select brush: a mostly-transparent fill disc plus a two-tone marching-ants outline, + * matching the box and crosshair style. + * + * @param Offset center The brush center in area-local pixels. + * @param Float radius The brush radius in pixels. + * @param SelectionOverlayStyle style The shared two-tone style. + */ +fun DrawScope.drawSelectionCircle(center: Offset, radius: Float, style: SelectionOverlayStyle) { + drawCircle(color = style.fill, radius = radius, center = center) + val strokeWidth = ANTS_STROKE.toPx() + strokeMarchingAnts(style, ANTS_DASH.toPx()) { color, dash -> + drawCircle(color = color, radius = radius, center = center, style = Stroke(width = strokeWidth, pathEffect = dash)) + } +} + +/** + * Draws a rubber band between two corners, in either drag direction, or nothing when either is null. + * + * The convenience over [drawSelectionBox] for the common case: a gesture holds its two corners as the + * points the pointer visited, and normalizing them at every call site is how one of them ends up drawing a + * zero-size box on an up-left drag. + * + * @param Offset? start The corner the drag began at, or null when no drag is in flight. + * @param Offset? end The corner the pointer is at now, or null. + * @param SelectionOverlayStyle style The shared two-tone style. + */ +fun DrawScope.drawRubberBand(start: Offset?, end: Offset?, style: SelectionOverlayStyle) { + if (start == null || end == null) { + return + } + val topLeft = Offset(min(start.x, end.x), min(start.y, end.y)) + val boxSize = Size(abs(end.x - start.x), abs(end.y - start.y)) + drawSelectionBox(topLeft, boxSize, style) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Shape.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Shape.kt new file mode 100644 index 0000000..037df09 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Shape.kt @@ -0,0 +1,39 @@ +package org.umamo.ui.theme + +import androidx.compose.foundation.shape.CornerBasedShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.unit.dp + +/* + * Compact corner rounding for a dense editor surface - tighter than the conventional defaults so panels, + * chips, and menus read as crisp tool chrome. The small radius matches the 4 dp viewport zoom chip. + * + * 密度の高いエディタ向けの小さめの角丸。 + */ + +/** + * The five corner-radius roles (same names as the conventional scale). Typed as CornerBasedShape + * rather than plain Shape so callers can derive positional variants via copy() - e.g. a ButtonGroup + * segment squaring the corners it shares with a neighbour. + */ +data class UmamoShapes( + val extraSmall: CornerBasedShape, + val small: CornerBasedShape, + val medium: CornerBasedShape, + val large: CornerBasedShape, + val extraLarge: CornerBasedShape, +) + +/** The compact shape set. */ +val umamoShapes = + UmamoShapes( + extraSmall = RoundedCornerShape(2.dp), + small = RoundedCornerShape(4.dp), + medium = RoundedCornerShape(6.dp), + large = RoundedCornerShape(10.dp), + extraLarge = RoundedCornerShape(14.dp), + ) + +/** The active shape set (defaults to [umamoShapes]; [UmamoTheme] provides it). */ +val LocalUmamoShapes = staticCompositionLocalOf { umamoShapes } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/SystemCursor.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/SystemCursor.kt new file mode 100644 index 0000000..8a852de --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/SystemCursor.kt @@ -0,0 +1,38 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.input.pointer.PointerIcon + +/* + * The seam that turns the editor's own cursor art into an OS pointer. Two mechanisms exist for showing a + * cursor, and this is the second of them: + * + * - Inside the viewport, a modal gesture HIDES the OS pointer ([hiddenPointerIcon]) and the overlay + * DRAWS the cursor itself with drawCursor, so it composites with the gizmo art. + * - Everywhere else - panel chrome, splitters, number fields - there is no overlay to draw into, so the + * art is rasterized once into a platform cursor and handed to pointerHoverIcon. + * + * Both paths therefore render the SAME UmamoCursor definitions from Cursor.kt; a control never falls back + * to a stock OS arrow, which is what kept the designed set from applying outside the viewport before. + */ + +/** + * The OS pointer for one of the editor's own [UmamoCursor] definitions, rasterized from its vector art. + * Desktop bakes a platform cursor (results cached per cursor, so a hover does not re-rasterize); touch + * platforms have no hover pointer at all and return the default. + * + * Pass a cursor from [LocalUmamoCursors] - e.g. `LocalUmamoCursors.ewScroll` for a horizontal scrub or + * drag. The cursor's own [CursorHotspot] is honored, so the caller never offsets for the tip. + * + * @param UmamoCursor cursor The cursor definition to rasterize. + * @return PointerIcon The platform pointer showing that art. + */ +expect fun umamoPointerIcon(cursor: UmamoCursor): PointerIcon + +/** + * A fully transparent pointer icon, used to hide the OS cursor during a modal transform so the overlay's + * own drawn cursor reads cleanly without the system pointer doubled on top. Desktop returns a transparent + * custom cursor; touch platforms have no cursor to hide and return the default. + * + * @return PointerIcon A transparent (invisible) cursor, or the default where none can be built. + */ +expect fun hiddenPointerIcon(): PointerIcon \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Theme.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Theme.kt new file mode 100644 index 0000000..ec85823 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Theme.kt @@ -0,0 +1,76 @@ +package org.umamo.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.ui.LocalSettings + +/** The settings key (and built-in fallback) for the UI theme mode: "dark" | "light" | "system". */ +private const val THEME_SETTING_KEY = "interface.theme" +private const val DEFAULT_THEME_MODE = "dark" + +/** + * The active theme mode ("dark" | "light" | "system") for the composition. Mirrors [LocalAppLocale]: a + * static local with a sensible default, so [UmamoTheme] is safe to use even where settings are never + * provided (a preview, or a subtree mounted outside the settings scope) - it simply renders the default + * mode there. Every app entrypoint feeds the real value in from settings via [ProvideAppThemeFromSettings]. + * + * コンポジションで有効なテーマモード。設定が無い場面でも既定値で動くよう静的ローカルにしている。 + */ +val LocalThemeMode = staticCompositionLocalOf { DEFAULT_THEME_MODE } + +/** + * The Umamo theme: resolves the palette (dark or light per [LocalThemeMode]) and provides the custom design + * tokens - [LocalUmamoColors], [LocalUmamoTypography], [LocalUmamoShapes] - to the subtree. There is no + * Material here; the kit widgets ([org.umamo.ui.kit]) read these locals directly. "system" follows the OS + * via [isSystemInDarkTheme]; any unrecognized mode falls back to dark. + * + * Umamo のテーマ。LocalThemeMode に従って配色を選び、独自トークンをコンポジションローカルで供給する。 + * + * @param Function content The UI to render under the theme. + */ +@Composable +fun UmamoTheme(content: @Composable () -> Unit) { + val useDarkScheme = + when (LocalThemeMode.current) { + "light" -> false + "system" -> isSystemInDarkTheme() + else -> true + } + CompositionLocalProvider( + LocalUmamoColors provides if (useDarkScheme) umamoDarkColors else umamoLightColors, + LocalUmamoTypography provides umamoTypography(), + LocalUmamoShapes provides umamoShapes, + content = content, + ) +} + +/** + * Resolves the theme mode from [LocalSettings] and provides it as [LocalThemeMode], reactively: the initial + * value is read once, and a collector on the settings `changes` flow updates it whenever `interface.theme` + * is written, so an in-app theme change re-themes the running app. Place this where settings are available; + * a subtree without settings simply skips it and uses the [LocalThemeMode] default. + * + * 設定からテーマモードを解決し LocalThemeMode に供給する。変更フローを購読して実行中に再配色する。 + * + * @param Function content The subtree to render under the resolved theme mode. + */ +@Composable +fun ProvideAppThemeFromSettings(content: @Composable () -> Unit) { + val settings = LocalSettings.current + var themeMode by remember { mutableStateOf(settings.getString(THEME_SETTING_KEY) ?: DEFAULT_THEME_MODE) } + LaunchedEffect(settings) { + settings.changes.collect { changedKey -> + if (changedKey == THEME_SETTING_KEY) { + themeMode = settings.getString(THEME_SETTING_KEY) ?: DEFAULT_THEME_MODE + } + } + } + CompositionLocalProvider(LocalThemeMode provides themeMode, content = content) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Type.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Type.kt new file mode 100644 index 0000000..b987f96 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/theme/Type.kt @@ -0,0 +1,112 @@ +package org.umamo.ui.theme + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp +import org.jetbrains.compose.resources.Font +import org.jetbrains.compose.resources.FontResource +import org.umamo.ui.l10n.LocalAppLocale +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.inter_regular +import org.umamo.ui.resources.noto_sans_cjk_jp_regular +import org.umamo.ui.resources.noto_sans_cjk_kr_regular + +/* + * The custom type scale. The 15 role names mirror the familiar scale (displayLarge … labelSmall) so call + * sites only swap the accessor (MaterialTheme.typography.X → LocalUmamoTypography.current.X). Inter for + * Latin, a Noto Sans CJK cut chosen by UI language for CJK; Regular only (heavier weights synthesize). + */ + +/** + * The UI font family: Inter first, then the Noto Sans CJK cut for the active UI language. Pairing them + * in one family lets the layout fall back to Noto for any glyph Inter lacks, so CJK renders from the + * bundled font rather than the platform's chance system coverage. + * + * @return FontFamily The Inter + locale-appropriate Noto family. + */ +@Composable +fun rememberUiFontFamily(): FontFamily = + FontFamily( + Font(Res.font.inter_regular, FontWeight.Normal), + Font(cjkFontFor(LocalAppLocale.current), FontWeight.Normal), + ) + +/** + * Picks the Noto Sans CJK cut for a UI language tag. Pure (no composition), so the mapping is assertable + * without a composition, the same split [umamoTypographyWith] makes for the type scale. + * + * @param String languageTag The active BCP-47 tag, bare ("ko") or regional ("ko-KR"). + * @return FontResource The cut to pair with Inter. + */ +internal fun cjkFontFor(languageTag: String): FontResource = + // Match the language subtag alone, so a regional tag resolves like the bare one. + when (languageTag.substringBefore('-').lowercase()) { + "ko" -> Res.font.noto_sans_cjk_kr_regular + else -> Res.font.noto_sans_cjk_jp_regular + } + +/** + * The role-named text styles. Same 15 roles as the familiar scale, so migrating a call site is a one-token + * change. + */ +data class UmamoTypography( + val displayLarge: TextStyle, + val displayMedium: TextStyle, + val displaySmall: TextStyle, + val headlineLarge: TextStyle, + val headlineMedium: TextStyle, + val headlineSmall: TextStyle, + val titleLarge: TextStyle, + val titleMedium: TextStyle, + val titleSmall: TextStyle, + val bodyLarge: TextStyle, + val bodyMedium: TextStyle, + val bodySmall: TextStyle, + val labelLarge: TextStyle, + val labelMedium: TextStyle, + val labelSmall: TextStyle, +) + +/** + * Builds the type scale on [family]. Pure (no composition), so it backs both the composable [umamoTypography] + * and the [LocalUmamoTypography] fallback. Sizes mirror the conventional scale; titles and labels use Medium + * (synthesized from the bundled Regular). + * + * @param FontFamily family The family to apply to every style. + * @return UmamoTypography The built scale. + */ +fun umamoTypographyWith(family: FontFamily): UmamoTypography { + fun style(sizeSp: Int, lineSp: Int, weight: FontWeight = FontWeight.Normal): TextStyle = + TextStyle(fontFamily = family, fontSize = sizeSp.sp, lineHeight = lineSp.sp, fontWeight = weight) + return UmamoTypography( + displayLarge = style(57, 64), + displayMedium = style(45, 52), + displaySmall = style(36, 44), + headlineLarge = style(32, 40), + headlineMedium = style(28, 36), + headlineSmall = style(24, 32), + titleLarge = style(22, 28), + titleMedium = style(16, 24, FontWeight.Medium), + titleSmall = style(14, 20, FontWeight.Medium), + bodyLarge = style(16, 24), + bodyMedium = style(14, 20), + bodySmall = style(12, 16), + labelLarge = style(14, 20, FontWeight.Medium), + labelMedium = style(12, 16, FontWeight.Medium), + labelSmall = style(11, 16, FontWeight.Medium), + ) +} + +/** + * The type scale bound to the bundled Inter + Noto family. + * + * @return UmamoTypography The scale [UmamoTheme] provides. + */ +@Composable +fun umamoTypography(): UmamoTypography = umamoTypographyWith(rememberUiFontFamily()) + +/** The active type scale (defaults to the system family; [UmamoTheme] provides the Inter/Noto scale). */ +val LocalUmamoTypography = staticCompositionLocalOf { umamoTypographyWith(FontFamily.Default) } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/tracks/TrackAxis.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/tracks/TrackAxis.kt new file mode 100644 index 0000000..fee140e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/tracks/TrackAxis.kt @@ -0,0 +1,363 @@ +package org.umamo.ui.tracks + +import kotlin.math.abs +import kotlin.math.floor +import kotlin.math.log10 +import kotlin.math.pow + +/* + * The track sheet's domain model, deliberately free of BOTH Compose and any Umamo concept. + * + * Nothing about parameters, keyform grids, or the puppet model may appear in this package. A track sheet + * is a list of labelled rows carrying marks along a horizontal axis, and that is all it knows - which is + * what lets the keyform sheet (marks along a parameter's min..max) and the eventual animation dope sheet + * (keys along a frame range) share it instead of growing two of everything. The constraint is easy to + * erode one convenient import at a time, so it is worth checking: `grep -r Parameter\\|Keyform\\|Puppet` + * over this package must come back empty. + */ + +/** + * The horizontal domain a track sheet maps marks onto - the ONLY place a domain appears. + * + * The keyform sheet passes a parameter's min..max; a time-based sheet would pass a frame range. + * + * @property Float start The domain value at the track region's left edge. + * @property Float end The domain value at its right edge. + */ +data class TrackAxis( + val start: Float, + val end: Float, +) { + /** The domain's extent; zero for a degenerate axis, which every mapping below guards against. */ + val span: Float get() = end - start + + /** + * Maps a domain value to its 0..1 position across the track region. + * + * A degenerate axis (min == max, which a non-animatable parameter has) maps everything to the middle + * rather than dividing by zero - the row still renders, its marks simply stack. + * + * @param Float value The domain value. + * @return Float The fraction across the region, unclamped so an out-of-range mark stays detectable. + */ + fun fractionOf(value: Float): Float = if (span == 0f) 0.5f else (value - start) / span + + /** + * Maps a 0..1 position back to its domain value - the inverse of [fractionOf], for hit-testing a click. + * + * @param Float fraction The fraction across the region. + * @return Float The domain value there. + */ + fun valueAt(fraction: Float): Float = start + span * fraction + + /** + * Evenly spaced ruler ticks at a human-readable step covering the domain. + * + * The step is the largest of 1, 2, or 5 times a power of ten that still yields at least + * [minimumTickCount] ticks, so a -30..30 axis rules at 10 and a -1..1 axis at 0.5 rather than both + * getting an arbitrary fixed count. + * + * @param Int minimumTickCount The fewest ticks the result should contain. + * @return List The tick values, ascending, within the domain. + */ + fun ticks(minimumTickCount: Int = 4): List { + val extent = abs(span) + if (extent == 0f || minimumTickCount <= 0) { + return listOf(start) + } + val roughStep = extent / minimumTickCount + val magnitude = 10f.pow(floor(log10(roughStep.toDouble())).toFloat()) + val step = + when { + roughStep / magnitude >= 5f -> 5f * magnitude + roughStep / magnitude >= 2f -> 2f * magnitude + else -> magnitude + } + if (step <= 0f) { + return listOf(start) + } + val lower = minOf(start, end) + val upper = maxOf(start, end) + val firstTick = floor(lower / step) * step + val values = ArrayList() + var tick = firstTick + // Bounded independently of the arithmetic so a pathological step can never spin here. + var guard = 0 + while (tick <= upper + step * 0.5f && guard < 1024) { + if (tick >= lower - step * 0.5f) { + values.add(tick) + } + tick += step + guard++ + } + return values + } +} + +/** + * The visible slice of a domain, as fractions of it - the zoom / pan state of a track sheet. + * + * NORMALIZED rather than in domain units so one window drives several domains at once. A keyform sheet + * showing a linked pad has two parameters with unrelated ranges (an angle over -30..30 beside an open / + * close over 0..1); a shared absolute window would overshoot the narrower one entirely, while a shared + * fraction keeps both rulers at the same screen positions and the pad's two axes reading in step. + * + * @property Float start The visible range's start, as a fraction of the full domain. + * @property Float end Its end, likewise. + */ +data class TrackWindow( + val start: Float = 0f, + val end: Float = 1f, +) { + /** The visible fraction of the whole domain; 1 when framed to everything. */ + val span: Float get() = end - start + + /** + * This window as an axis over [full], which is what the sheet actually draws against. + * + * @param TrackAxis full The whole domain. + * @return TrackAxis The visible slice of it. + */ + fun axisOver(full: TrackAxis): TrackAxis = + TrackAxis(full.start + full.span * start, full.start + full.span * end) + + /** + * This window zoomed by [factor] about [focus], a fraction of the VISIBLE width. + * + * Anchored on the pointer rather than the center, so zooming in on a cluster of keys keeps that + * cluster under the cursor instead of sliding it away. Clamped so the window can never invert, shrink + * past [MIN_SPAN] (which would divide by nothing at the pixel mapping), or grow past the full domain. + * + * @param Float factor Multiplier on the visible span; below 1 zooms in. + * @param Float focus The zoom anchor, 0..1 across the visible width. + * @return TrackWindow The new window. + */ + fun zoomedBy(factor: Float, focus: Float): TrackWindow { + val anchor = start + span * focus.coerceIn(0f, 1f) + val newSpan = (span * factor).coerceIn(MIN_SPAN, 1f) + // Hold the anchor at the same fraction of the visible width, then push the result back inside the + // domain - zooming out near an end walks the window inward rather than off the edge. + val newStart = (anchor - (anchor - start) * (newSpan / span)).coerceIn(0f, 1f - newSpan) + return TrackWindow(newStart, newStart + newSpan) + } + + /** + * This window panned by [fraction] of the FULL domain, stopping at either end. + * + * @param Float fraction The signed distance to move, as a fraction of the whole domain. + * @return TrackWindow The new window. + */ + fun pannedBy(fraction: Float): TrackWindow { + val newStart = (start + fraction).coerceIn(0f, 1f - span) + return TrackWindow(newStart, newStart + span) + } + + companion object { + /** The whole domain - what "frame all" resets to. */ + val Full: TrackWindow = TrackWindow() + + /** + * The tightest the window may zoom, as a fraction of the domain. + * + * A thousandth of a -30..30 axis is 0.06 units across the whole panel, which separates keys the + * evaluator itself treats as distinct (EPS_KEY is 0.001) by hundreds of pixels. Tighter than that + * buys nothing and starts losing float precision in the pixel mapping. + */ + const val MIN_SPAN: Float = 0.001f + } +} + +/** + * The shape a mark is drawn with, which is how a row distinguishes kinds of key at a glance. + * + * The keyform sheet uses [Circle] for a keyform-grid key and [Square] for a blend-shape key, matching the + * marks the parameter slider already draws. [Diamond] is reserved for the animation dope sheet's keys so + * the two sheets stay visually distinct when both are open. + */ +enum class TrackKeyShape { + Circle, + Square, + Diamond, +} + +/** + * One mark on a track. + * + * [keyIndex] is the mark's IDENTITY and [position] is only where it is drawn. Two marks may sit at the + * same pixel - nothing forbids keys a hair apart, and forbidding it would be the wrong cure - so anything + * that edits a key has to say which one by ordinal. Resolving "the key at this value" instead is + * ambiguous exactly when it matters, and picks the wrong key silently. + * + * A summary mark (drawn on a collapsed group) is renumbered to its ordinal within the SUMMARY, which its + * owner maps back to the whole set of child keys it stands for - so acting on one acts on all of them at + * once rather than guessing at which channel was meant. + * + * @property Int keyIndex The mark's ordinal within its row's track. + * @property Float position The mark's domain value (a parameter value, a frame, …). + * @property TrackKeyShape shape How to draw it. + * @property Boolean selected Whether it is part of the current key selection. + * @property Boolean editable Whether it may be selected, dragged, or removed; a blend-shape binding key may + * not, which is why [summarizedMarks] leaves it out of a group's summary rather than folding it in. + */ +data class TrackKeyMark( + val keyIndex: Int, + val position: Float, + val shape: TrackKeyShape = TrackKeyShape.Circle, + val selected: Boolean = false, + val editable: Boolean = true, +) + +/** + * The domain window a mark may be dragged within: the axis, end to end. + * + * Neighbours are NOT walls. A key may be dragged past another - the sheet's owner re-sorts and permutes + * to match - so clamping at a neighbour here would stop a gesture the model is happy to accept. The axis + * ends still bound it, because a key outside the domain is one the sheet cannot draw or reach again. + * + * @param TrackAxis axis The domain. + * @return ClosedFloatingPointRange The legal range, ascending. + */ +fun dragBoundsOf(axis: TrackAxis): ClosedFloatingPointRange = + minOf(axis.start, axis.end)..maxOf(axis.start, axis.end) + +/** + * A row's color band, which is how a sheet makes kinds of track separable at a glance. + * + * Abstract slots rather than colors or domain names, for the same reason [TrackAxis] is abstract: the + * theme owns what each band actually looks like, and each sheet decides which of its own kinds map onto + * which slot. The keyform sheet reads them as owner / geometry / channel / blend shape; a time-based + * sheet would read the same four as object / transform / custom property / layered action. + */ +enum class TrackRowTone { + /** A grouping row that owns the tracks nested beneath it. */ + Group, + + /** A track carrying the row's primary subject. */ + Primary, + + /** A track carrying a secondary property of the same subject. */ + Secondary, + + /** A track from a source layered on top of the primary one. */ + Alternate, +} + +/** + * One row of a track sheet: a label, the marks along it, and any rows nested beneath it. + * + * A row is a TREE node rather than a flat line with a depth number, because collapsing has to hide a + * whole subtree and a depth-tagged flat list cannot say where one ends. [flattenTrackRows] turns the + * tree back into display lines once the expansion state is known. + * + * @property String key A stable identity for the row, so Compose keeps per-row state across list changes. + * @property String label The row's primary text. + * @property String? detail Optional secondary text, shown under the label as a subtitle. + * @property TrackRowTone tone The row's color band. + * @property List marks The row's marks, in any order. + * @property List children Rows nested under this one, shown only while it is expanded. + */ +data class TrackRow( + val key: String, + val label: String, + val detail: String? = null, + val tone: TrackRowTone = TrackRowTone.Primary, + val marks: List = emptyList(), + val children: List = emptyList(), +) + +/** + * One row as it is actually displayed: the row itself plus what the tree position implies about it. + * + * @property TrackRow row The row. + * @property Int depth Its nesting level, for indentation. + * @property Boolean expandable Whether it has children at all (so a chevron is drawn). + * @property Boolean expanded Whether those children are currently shown. + */ +data class TrackRowLine( + val row: TrackRow, + val depth: Int, + val expandable: Boolean, + val expanded: Boolean, +) + +/** + * Flattens a row tree into display lines, descending only into rows whose key is in [expandedKeys]. + * + * Compose-free so the expansion rule is unit-testable and identical in every sheet on this package. + * + * @param List rows The root rows, in display order. + * @param Set expandedKeys The keys of the rows whose children are shown. + * @return List The visible lines, in display order. + */ +fun flattenTrackRows(rows: List, expandedKeys: Set): List { + val lines = ArrayList() + + fun visit(row: TrackRow, depth: Int) { + val expandable = row.children.isNotEmpty() + val expanded = expandable && row.key in expandedKeys + lines.add(TrackRowLine(row, depth, expandable, expanded)) + if (expanded) { + for (child in row.children) { + visit(child, depth + 1) + } + } + } + for (row in rows) { + visit(row, 0) + } + return lines +} + +/** + * Every mark under [row] and its whole subtree, deduplicated by position and shape. + * + * What a collapsed group row draws, so folding a subtree away still shows WHERE its keys are rather than + * hiding them entirely - the summary behaviour Blender's dope sheet has at every level. + * + * @param TrackRow row The row to summarize. + * @return List The union of its own and its descendants' marks, ascending. + */ +fun summarizedMarks(row: TrackRow): List { + val byPosition = LinkedHashMap() + + fun visit(current: TrackRow) { + for (mark in current.marks) { + // Only an EDITABLE child key can be summarized: a summary mark is a handle on the keys beneath + // it, so one standing partly on keys nothing can move would move only some of what it shows. + if (mark.editable) { + byPosition.getOrPut(mark.position) { mark } + } + } + current.children.forEach(::visit) + } + visit(row) + // Renumbered to its position in the SUMMARY. The winner's own ordinal is meaningless across the group + // (two channels keyed at one value can hold different ordinals), whereas a summary ordinal is a stable + // name the owner can map back to the whole set of keys it stands for. + return byPosition.values.sortedBy { mark -> mark.position }.mapIndexed { ordinal, mark -> + mark.copy(keyIndex = ordinal) + } +} + +/** + * The mark nearest [domainValue] within [tolerance], or null - the shared hit test for clicking a mark. + * + * Compose-free so the picking rule is unit-testable and identical in every sheet built on this package. + * + * @param List marks The row's marks. + * @param Float domainValue The clicked position in domain units. + * @param Float tolerance The pick radius in domain units. + * @return TrackKeyMark? The nearest mark in range, or null. + */ +fun nearestMark(marks: List, domainValue: Float, tolerance: Float): TrackKeyMark? { + var best: TrackKeyMark? = null + var bestDistance = tolerance + for (mark in marks) { + val distance = abs(mark.position - domainValue) + if (distance <= bestDistance) { + bestDistance = distance + best = mark + } + } + return best +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/tracks/TrackSheet.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/tracks/TrackSheet.kt new file mode 100644 index 0000000..41f9a0a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/tracks/TrackSheet.kt @@ -0,0 +1,1312 @@ +package org.umamo.ui.tracks + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.DraggableState +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.draggable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isCtrlPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.isTertiaryPressed +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChange +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.layout +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalViewConfiguration +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.AtPointPositionProvider +import org.umamo.ui.kit.DisclosureChevron +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.SCROLLBAR_CORNER_RADIUS +import org.umamo.ui.kit.SCROLLBAR_MIN_THUMB +import org.umamo.ui.kit.SCROLLBAR_THICKNESS +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.kit.contextMenuGesture +import org.umamo.ui.kit.roundToDecimals +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawCrosshairGuides +import org.umamo.ui.theme.drawCursor +import org.umamo.ui.theme.drawIcon +import org.umamo.ui.theme.drawRubberBand +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle +import org.umamo.ui.theme.umamoPointerIcon +import kotlin.math.abs + +/* + * The track sheet widget family: a label column beside a domain-mapped track region, with a ruler and a + * playhead. Domain-agnostic by construction - everything it knows about the horizontal axis arrives as a + * TrackAxis, and everything it knows about content arrives as TrackRows. + */ + +/** The label column's default width; wide enough for an item name plus its type at the panel's type size. */ +val TRACK_LABEL_COLUMN_DEFAULT_WIDTH: Dp = 180.dp + +/** How narrow and how wide the label column may be dragged. */ +val TRACK_LABEL_COLUMN_MIN_WIDTH: Dp = 80.dp + +/** The widest the label column may be dragged, so the track region can never be squeezed away entirely. */ +val TRACK_LABEL_COLUMN_MAX_WIDTH: Dp = 420.dp + +/** Row height. Two lines of text (name over its type), so taller than a single-line tree row. */ +val TRACK_ROW_HEIGHT: Dp = 32.dp + +/** The ruler strip's height. */ +val TRACK_RULER_HEIGHT: Dp = 20.dp + +/** + * The gap left between rows, showing the track region through. + * + * Small on purpose: enough to break the tone bands apart so the eye can follow one band left to right + * across a dense sheet, not enough to read as spacing between unrelated things. + */ +val TRACK_ROW_GAP: Dp = 2.dp + +/** Indent per nesting level in the label column. */ +private val INDENT_PER_DEPTH: Dp = 12.dp + +/** + * Half-extent of a drawn mark, in dp - the default for [TrackSheet]'s markRadius. + * + * It is also the amount the track region is inset at both ends, so a key at either end of the domain draws + * fully inside the lane instead of half outside it. Every axis has a key at each end, so without the + * inset every track loses two marks to the panel edge. + */ +val TRACK_MARK_RADIUS: Dp = 6.dp + +/** The chevron / icon slots in the label column. */ +private val SLOT_WIDTH: Dp = 16.dp + +/** The draggable width of the column separator; wider than the hairline it draws so it is easy to grab. */ +private val SEPARATOR_GRAB_WIDTH: Dp = 5.dp + +/** How much one wheel notch zooms; a fixed ratio, so a notch feels the same however far in you are. */ +private const val ZOOM_STEP: Float = 0.85f + +/** How far one wheel notch pans, as a fraction of the VISIBLE width. */ +private const val PAN_STEP: Float = 0.15f + +/** + * Per-row presentation the sheet cannot derive from a [TrackRow] alone. + * + * An icon is a UI concept, not a domain one, but WHICH icon a row gets is a domain decision - so it + * arrives through a provider from the sheet's owner rather than sitting on the Compose-free [TrackRow]. + * + * @property UmamoIcon? icon The glyph shown beside the row's name, or null for none. + * @property Color? iconTint The glyph's color, or null for the row's text color. + */ +data class TrackRowDecor( + val icon: UmamoIcon? = null, + val iconTint: Color? = null, +) + +/** + * Where a lane click or context-menu request landed: the row, the domain value, and the mark hit if any. + * + * @property TrackRow row The row under the pointer. + * @property Float value The domain value under the pointer. + * @property TrackKeyMark? mark The mark within pick range, or null for empty track. + */ +data class TrackLaneHit( + val row: TrackRow, + val value: Float, + val mark: TrackKeyMark?, +) + +/** + * A sheet of labelled tracks over one horizontal [axis], with a ruler, a playhead, and a resizable + * label column. + * + * Lays its rows out eagerly rather than lazily: a sheet is usually one section of a scrolling page, and a + * lazy list nested in an outer scroll fights it for the gesture. Track counts are in the tens. + * + * @param List rows The root rows; nested children appear only while their parent is expanded. + * @param TrackAxis axis The horizontal domain the marks map onto. + * @param Float? playhead The domain value to draw the playhead at, or null for none. + * @param Modifier modifier The layout modifier. + * @param Dp labelColumnWidth The label column's current width; TrackSheetSeparatorOverlay resizes it. + * @param Set expandedKeys The keys of the rows whose children are shown. + * @param Function? onToggleExpanded Invoked with a row whose chevron was clicked; null pins the tree. + * @param Function decorFor The per-row icon provider. + * @param Function formatTick Renders a ruler tick value; defaults to a trimmed decimal. + * @param Function? onMarkClick Invoked with the row, the mark nearest a click, and whether the click was + * ADDITIVE (Shift held) - the owner decides what additive means, since only it holds the selection. + * @param Function? onTrackScrub Invoked on press and on every move of a drag that missed every mark, with + * whether Shift was held when the gesture began - so a Shift+click that MISSES a mark can decline to + * clear the selection the user was building. + * @param Function? onTrackScrubEnd Invoked when such a drag is released, to commit the value it landed on. + * @param Function? onMarkDrag Invoked with the row, the dragged mark, and its live domain position on every + * move of a mark drag - what lets an owner preview a whole SELECTION following the one being dragged. + * @param Function? onMarkDragEnd Invoked with the row, the dragged mark, and its released domain position. + * @param Function selectedMarkDragDelta A domain offset drawn on every SELECTED mark while a group drag is + * in flight, so the rest of the selection travels with the one under the hand instead of jumping on + * release. In this axis's own units; the owner converts, since only it knows what the group is being + * dragged along. NULL means no group drag is in flight - distinct from 0f, which means one IS in flight + * but has been clamped to a standstill, and in that case the mark under the hand must stop with the rest + * instead of running on and snapping back. A LAMBDA, read inside the lane's draw: a plain value would + * make every pointer frame of a drag recompose the whole sheet, where a draw-scope read only redraws. + * @param Function? laneMenuItems Builds the context-menu items for a lane hit; null disables the menu. + * @param Function? labelMenuItems Builds the context-menu items for a row's LABEL cell; null disables it. + * Separate from [laneMenuItems] because the two halves of a row answer different questions - the lane is + * about a key at a position, the label is about the thing the row names. + * @param Function? onLaneHover Reports the live hit under the pointer, or null on exit, for hover-aimed commands. + * @param Function? onLaneBounds Reports each lane's window bounds, so a region gesture can resolve rows. + * @param Dp markRadius Half-extent of a drawn mark, and the inset applied at both ends of the track region. + */ +@Composable +fun TrackSheet( + rows: List, + axis: TrackAxis, + playhead: Float?, + modifier: Modifier = Modifier, + labelColumnWidth: Dp = TRACK_LABEL_COLUMN_DEFAULT_WIDTH, + expandedKeys: Set = emptySet(), + onToggleExpanded: ((TrackRow) -> Unit)? = null, + decorFor: (TrackRow) -> TrackRowDecor = { TrackRowDecor() }, + formatTick: (Float) -> String = ::defaultTickLabel, + onMarkClick: ((TrackRow, TrackKeyMark, Boolean) -> Unit)? = null, + onTrackScrub: ((TrackRow, Float, Boolean) -> Unit)? = null, + onTrackScrubEnd: ((TrackRow, Float) -> Unit)? = null, + onMarkDrag: ((TrackRow, TrackKeyMark, Float) -> Unit)? = null, + onMarkDragEnd: ((TrackRow, TrackKeyMark, Float) -> Unit)? = null, + selectedMarkDragDelta: () -> Float? = { null }, + laneMenuItems: ((TrackLaneHit) -> List)? = null, + labelMenuItems: ((TrackRow) -> List)? = null, + onLaneHover: ((TrackRow, TrackLaneHit?) -> Unit)? = null, + onLaneBounds: ((TrackRow, Rect) -> Unit)? = null, + markRadius: Dp = TRACK_MARK_RADIUS, +) { + val lines = remember(rows, expandedKeys) { flattenTrackRows(rows, expandedKeys) } + Column(modifier = modifier.fillMaxWidth()) { + TrackRuler( + axis = axis, + playhead = playhead, + labelColumnWidth = labelColumnWidth, + formatTick = formatTick, + markRadius = markRadius, + ) + for (line in lines) { + key(line.row.key) { + TrackSheetRow( + line = line, + axis = axis, + playhead = playhead, + labelColumnWidth = labelColumnWidth, + decor = decorFor(line.row), + onToggleExpanded = onToggleExpanded, + onMarkClick = onMarkClick, + onTrackScrub = onTrackScrub, + onTrackScrubEnd = onTrackScrubEnd, + onMarkDrag = onMarkDrag, + onMarkDragEnd = onMarkDragEnd, + selectedMarkDragDelta = selectedMarkDragDelta, + laneMenuItems = laneMenuItems, + labelMenuItems = labelMenuItems, + onLaneHover = onLaneHover, + onLaneBounds = onLaneBounds, + markRadius = markRadius, + ) + } + } + } +} + +/** + * The zoom / pan gestures for a whole track sheet: Ctrl+wheel zooms about the pointer, Shift+wheel pans, + * and a tertiary (middle) drag pans. + * + * Attached by the sheet's owner across its whole scrolling region, not per lane, because the window is + * shared by every track and section - the zoom belongs to the view, not to a row. + * + * PLAIN wheel is deliberately left alone: the sheet scrolls vertically through hundreds of tracks, and + * taking the unmodified wheel for zoom would cost the more common gesture to serve the rarer one. This + * matches every NLE that has real vertical overflow. + * + * @param TrackWindow window The current window. + * @param Function onWindowChange Receives the new window. + * @param Dp labelColumnWidth The label column's width, so a gesture over the labels is ignored. + * @param Function onPanningChange Reports whether a pan is in flight, so the caller can hold the cursor. + * @return Modifier The modifier carrying both gestures. + */ +@Composable +fun Modifier.trackWindowGestures( + window: TrackWindow, + onWindowChange: (TrackWindow) -> Unit, + labelColumnWidth: Dp, + onPanningChange: (Boolean) -> Unit = {}, +): Modifier { + val density = LocalDensity.current + val latestWindow by rememberUpdatedState(window) + val latestCallback by rememberUpdatedState(onWindowChange) + val latestPanning by rememberUpdatedState(onPanningChange) + val labelWidthPx = with(density) { labelColumnWidth.toPx() } + return this + .pointerInput(labelWidthPx) { + awaitPointerEventScope { + while (true) { + // The INITIAL pass, deliberately: the Main pass runs child-first, so a Main-pass handler here + // would see the wheel only after the vertical scroll container had already claimed it, and + // Ctrl+wheel would zoom and scroll at once. + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type != PointerEventType.Scroll) { + continue + } + val change = event.changes.firstOrNull() ?: continue + val laneWidth = size.width - labelWidthPx + if (change.position.x < labelWidthPx || laneWidth <= 0f) { + continue + } + val horizontal = change.scrollDelta.x + if (horizontal != 0f) { + latestCallback(latestWindow.pannedBy(horizontal * latestWindow.span * PAN_STEP)) + change.consume() + continue + } + val scroll = change.scrollDelta.y + if (scroll == 0f) { + continue + } + when { + event.keyboardModifiers.isCtrlPressed -> { + val focus = ((change.position.x - labelWidthPx) / laneWidth).coerceIn(0f, 1f) + // A notch is a fixed RATIO, so zooming feels the same however far in you are. + latestCallback(latestWindow.zoomedBy(if (scroll > 0f) 1f / ZOOM_STEP else ZOOM_STEP, focus)) + change.consume() + } + + event.keyboardModifiers.isShiftPressed -> { + latestCallback(latestWindow.pannedBy(scroll * latestWindow.span * PAN_STEP)) + change.consume() + } + + // Anything else is the vertical scroll, which belongs to the scroll container. + else -> Unit + } + } + } + } + .pointerInput(labelWidthPx) { + awaitPointerEventScope { + while (true) { + // The raw stream on the INITIAL pass, not awaitFirstDown. Two reasons, both load-bearing: + // Initial is the only pass that beats the lanes and the scroll container, which are + // children and would otherwise claim a middle press first; and awaitFirstDown does not + // resolve a down on that pass at all - it waits forever, so calling it here would silently + // hang. contextMenuGesture watches the raw stream for the same reason. + val press = awaitPointerEvent(PointerEventPass.Initial) + if (press.type != PointerEventType.Press || !press.buttons.isTertiaryPressed) { + continue + } + val down = press.changes.first() + if (down.position.x < labelWidthPx) { + continue + } + down.consume() + latestPanning(true) + val laneWidth = size.width - labelWidthPx + var lastX = down.position.x + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + val change = event.changes.firstOrNull { candidate -> candidate.id == down.id } ?: break + if (!change.pressed) { + change.consume() + break + } + if (laneWidth > 0f && change.position.x != lastX) { + // Dragging right moves the CONTENT right, so the window moves left - the direct + // manipulation a hand tool has, not a scrollbar's inverted sense. + val moved = (change.position.x - lastX) / laneWidth + latestCallback(latestWindow.pannedBy(-moved * latestWindow.span)) + lastX = change.position.x + } + change.consume() + } + latestPanning(false) + } + } + } +} + +/** + * The horizontal window indicator under a track sheet: a thumb showing which slice of the domain is on + * screen, draggable to pan. + * + * Not a scrollbar over a scroll container - there is no scrolling content to attach to - so it reads the + * window directly and reports a new one. Hidden when the whole domain is framed, since a full-width thumb + * says nothing. + * + * @param TrackWindow window The current window. + * @param Function onWindowChange Receives the new window as the thumb is dragged. + * @param Dp labelColumnWidth The label column's width, so the track starts under the tracks. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun TrackWindowScrollbar( + window: TrackWindow, + onWindowChange: (TrackWindow) -> Unit, + labelColumnWidth: Dp, + modifier: Modifier = Modifier, +) { + val colors = LocalUmamoColors.current + if (window.span >= 1f) { + return + } + val latestWindow by rememberUpdatedState(window) + val latestCallback by rememberUpdatedState(onWindowChange) + var trackWidth by remember { mutableStateOf(0) } + val dragState = + remember { + DraggableState { deltaPx -> + if (trackWidth > 0) { + latestCallback(latestWindow.pannedBy(deltaPx / trackWidth)) + } + } + } + val minimumThumbWidth = with(LocalDensity.current) { SCROLLBAR_MIN_THUMB.toPx() } + val cornerRadius = with(LocalDensity.current) { SCROLLBAR_CORNER_RADIUS.toPx() } + Row(modifier = modifier.fillMaxWidth().height(SCROLLBAR_THICKNESS)) { + Spacer(modifier = Modifier.width(labelColumnWidth + 1.dp)) + Box( + modifier = + Modifier + .weight(1f) + .fillMaxHeight() + .onSizeChanged { measured -> trackWidth = measured.width } + .draggable(state = dragState, orientation = Orientation.Horizontal), + ) { + Canvas(modifier = Modifier.fillMaxSize()) { + val thumbWidth = maxOf(size.width * latestWindow.span, minimumThumbWidth) + val thumbLeft = (size.width * latestWindow.start).coerceIn(0f, maxOf(0f, size.width - thumbWidth)) + // Full thickness, matching the panel scrollbars: a bar is a pointer target first, and one + // inset thinner than its neighbours is harder to hit for no reason the user can see. + drawRoundRect( + color = colors.scrollbarThumb, + topLeft = Offset(thumbLeft, 0f), + size = Size(thumbWidth, size.height), + cornerRadius = CornerRadius(cornerRadius), + ) + } + } + } +} + +/** + * The always-visible backdrop for a sheet region: the label column's fill beside the track region's. + * + * Drawn behind the scrolled content rather than per row, so the two columns read as columns even where + * there are no rows - below the last track, and in a section that is empty. Callers stack this under + * their scroll container. + * + * @param Dp labelColumnWidth The label column's current width, so the split lines up with the rows. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun TrackSheetBackdrop(labelColumnWidth: Dp, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + Row(modifier = modifier.fillMaxSize()) { + Box(modifier = Modifier.width(labelColumnWidth).fillMaxHeight().background(colors.panelBackground)) + Box(modifier = Modifier.width(1.dp).fillMaxHeight().background(colors.divider)) + Box(modifier = Modifier.weight(1f).fillMaxHeight().background(colors.trackRegionBackground)) + } +} + +/** + * One display line: its label cell, the column separator, and its track lane. + * + * @param TrackRowLine line The row and what its tree position implies. + * @param TrackAxis axis The domain. + * @param Float? playhead The playhead's domain value, or null. + * @param Dp labelColumnWidth The label column's width. + * @param TrackRowDecor decor The row's icon. + * @param Function? onToggleExpanded Invoked when the chevron is clicked. + * @param Function? onMarkClick Invoked when a click lands on a mark, with whether Shift was held. + * @param Function? onTrackScrub Invoked as an empty-track drag moves, with the gesture's Shift state. + * @param Function? onTrackScrubEnd Invoked when an empty-track drag is released. + * @param Function? onMarkDrag Invoked on every move of a mark drag. + * @param Function? onMarkDragEnd Invoked when a mark drag is released. + * @param Function selectedMarkDragDelta The in-flight group-drag offset drawn on selected marks; null for none. + * @param Function? laneMenuItems Builds the lane's context-menu items. + * @param Function? labelMenuItems Builds the label cell's context-menu items. + * @param Function? onLaneHover Reports the live hit under the pointer, or null on exit. + * @param Function? onLaneBounds Reports the lane's window bounds. + * @param Dp markRadius Half-extent of a drawn mark, and the track region's end inset. + */ +@Composable +private fun TrackSheetRow( + line: TrackRowLine, + axis: TrackAxis, + playhead: Float?, + labelColumnWidth: Dp, + decor: TrackRowDecor, + onToggleExpanded: ((TrackRow) -> Unit)?, + onMarkClick: ((TrackRow, TrackKeyMark, Boolean) -> Unit)?, + onTrackScrub: ((TrackRow, Float, Boolean) -> Unit)?, + onTrackScrubEnd: ((TrackRow, Float) -> Unit)?, + onMarkDrag: ((TrackRow, TrackKeyMark, Float) -> Unit)?, + onMarkDragEnd: ((TrackRow, TrackKeyMark, Float) -> Unit)?, + selectedMarkDragDelta: () -> Float?, + laneMenuItems: ((TrackLaneHit) -> List)?, + labelMenuItems: ((TrackRow) -> List)?, + onLaneHover: ((TrackRow, TrackLaneHit?) -> Unit)?, + onLaneBounds: ((TrackRow, Rect) -> Unit)?, + markRadius: Dp, +) { + val colors = LocalUmamoColors.current + val toneBackground = toneBackgroundOf(line.row.tone) + // A collapsed GROUP summarizes its whole subtree, so folding a rig away still shows where its keys are. + // Expanded, it shows only its own marks - the children are on screen carrying theirs. A leaf is + // neither: it shows its own marks, unfiltered and at their own ordinals. (Routing a leaf through the + // summary too would drop any non-editable mark it carries and renumber the rest to a summary ordinal - + // wrong for a track that owns its keys directly rather than standing in for a whole subtree's.) + val marks = + remember(line.row, line.expandable, line.expanded) { + if (line.expandable && !line.expanded) summarizedMarks(line.row) else line.row.marks + } + Row(modifier = Modifier.fillMaxWidth().height(TRACK_ROW_HEIGHT), verticalAlignment = Alignment.CenterVertically) { + TrackRowLabel( + line = line, + decor = decor, + width = labelColumnWidth, + background = toneBackground, + onToggleExpanded = onToggleExpanded, + menuItems = labelMenuItems, + ) + Box(modifier = Modifier.width(1.dp).fillMaxHeight().background(colors.divider)) + TrackLane( + row = line.row, + marks = marks, + axis = axis, + playhead = playhead, + background = toneBackground, + modifier = Modifier.weight(1f), + onMarkClick = onMarkClick, + onTrackScrub = onTrackScrub, + onTrackScrubEnd = onTrackScrubEnd, + onMarkDrag = onMarkDrag, + onMarkDragEnd = onMarkDragEnd, + selectedMarkDragDelta = selectedMarkDragDelta, + laneMenuItems = laneMenuItems, + onLaneHover = onLaneHover, + onLaneBounds = onLaneBounds, + markRadius = markRadius, + ) + } + Spacer(modifier = Modifier.fillMaxWidth().height(TRACK_ROW_GAP)) +} + +/** + * A row's label cell: chevron, icon, and the right-aligned name over its type. + * + * Right-aligned against the column separator so names of wildly different lengths still line up where the + * eye next travels - into the track region. + * + * @param TrackRowLine line The row and its tree position. + * @param TrackRowDecor decor The row's icon. + * @param Dp width The label column's width. + * @param Color background The row's tone fill. + * @param Function? onToggleExpanded Invoked when the chevron is clicked. + * @param Function? menuItems Builds this row's label context menu; null (or an empty list) shows none. + */ +@Composable +private fun TrackRowLabel( + line: TrackRowLine, + decor: TrackRowDecor, + width: Dp, + background: Color, + onToggleExpanded: ((TrackRow) -> Unit)?, + menuItems: ((TrackRow) -> List)? = null, +) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + // Only wrap a name in a tooltip when it is ACTUALLY clipped: a tooltip that repeats text already fully + // on screen is noise, and Tooltip treats a blank label as "no tooltip". + var nameTruncated by remember(line.row.key) { mutableStateOf(false) } + // Built ONCE per composition, not on the pointer event: the labels are localized through + // stringResource, which only runs while composing. An empty list means this row has nothing to + // offer, so no gesture is attached at all rather than a blank popup opening on right-click. + val items = menuItems?.invoke(line.row).orEmpty() + var menuOpen by remember(line.row.key) { mutableStateOf(false) } + var menuOffset by remember(line.row.key) { mutableStateOf(IntOffset.Zero) } + Row( + modifier = + Modifier + .width(width) + .fillMaxHeight() + .background(background) + .then( + if (items.isEmpty()) { + Modifier + } else { + Modifier.contextMenuGesture { localOffset -> + menuOffset = localOffset + menuOpen = true + } + }, + ) + .padding(start = 4.dp + INDENT_PER_DEPTH * line.depth, end = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (line.expandable && onToggleExpanded != null) { + ExpandChevron(expanded = line.expanded, onClick = { onToggleExpanded(line.row) }) + } else { + Spacer(modifier = Modifier.width(SLOT_WIDTH)) + } + Spacer(modifier = Modifier.weight(1f)) + if (decor.icon != null) { + Box(modifier = Modifier.size(SLOT_WIDTH), contentAlignment = Alignment.Center) { + Canvas(modifier = Modifier.size(SLOT_WIDTH)) { + drawIcon(decor.icon, decor.iconTint ?: colors.text) + } + } + Spacer(modifier = Modifier.width(4.dp)) + } + Tooltip(text = if (nameTruncated) line.row.label else "") { + Column(horizontalAlignment = Alignment.End) { + Text( + text = line.row.label, + style = typography.bodyMedium, + color = colors.text, + maxLines = 1, + textAlign = TextAlign.End, + overflow = TextOverflow.Ellipsis, + onTextLayout = { result -> nameTruncated = result.hasVisualOverflow }, + ) + if (line.row.detail != null) { + Text( + text = line.row.detail, + style = typography.labelSmall, + color = colors.textMuted, + maxLines = 1, + textAlign = TextAlign.End, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + if (menuOpen) { + Menu(items = items, onDismissRequest = { menuOpen = false }, positionProvider = AtPointPositionProvider(menuOffset)) + } +} + +/** + * The expand / collapse chevron, sharing the kit's [DisclosureChevron] with the outliner and parameter + * groups so the art and the accessible label stay in one place. + * + * @param Boolean expanded Whether the row's children are shown. + * @param Function onClick Invoked on click. + */ +@Composable +private fun ExpandChevron(expanded: Boolean, onClick: () -> Unit) { + val colors = LocalUmamoColors.current + // NOT focusable: a row can be disposed by the very edit its chevron is next to, and a disposed focus + // owner leaves Compose with none, killing every keyboard shortcut. + val toggleGesture = + Modifier.pointerInput(onClick) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false).consume() + onClick() + } + } + DisclosureChevron( + expanded = expanded, + tint = colors.textMuted, + modifier = toggleGesture, + glyphSize = SLOT_WIDTH, + ) +} + +/** + * The ruler strip: evenly spaced domain ticks above the track lanes, with the playhead and the draggable + * column separator. + * + * @param TrackAxis axis The domain. + * @param Float? playhead The playhead's domain value, or null. + * @param Dp labelColumnWidth The label column's width. + * @param Function formatTick Renders a tick value. + * @param Dp markRadius The track region's end inset, so ticks line up with the marks below. + */ +@Composable +private fun TrackRuler( + axis: TrackAxis, + playhead: Float?, + labelColumnWidth: Dp, + formatTick: (Float) -> String, + markRadius: Dp, +) { + val colors = LocalUmamoColors.current + val typography = LocalUmamoTypography.current + // Computed once per axis and shared by the tick lines and the labels: the canvas lambda re-executes on + // every playhead frame during a scrub, and ticks() does log10/pow work plus a list build per call. + val ticks = remember(axis) { axis.ticks() } + Row(modifier = Modifier.fillMaxWidth().height(TRACK_RULER_HEIGHT).background(colors.headerBackground)) { + Box(modifier = Modifier.width(labelColumnWidth)) + Box(modifier = Modifier.width(1.dp).fillMaxHeight().background(colors.divider)) + Box(modifier = Modifier.weight(1f).fillMaxSize().clipToBounds()) { + Canvas(modifier = Modifier.fillMaxSize()) { + val inset = markRadius.toPx() + for (tick in ticks) { + val x = laneX(axis.fractionOf(tick), size.width, inset) + drawLine(colors.panelBorder, Offset(x, size.height * 0.5f), Offset(x, size.height), strokeWidth = 1f) + } + playhead?.let { value -> drawPlayhead(value, axis, colors.accent, inset) } + } + // Tick labels ride above the canvas so they are not clipped by the lane below. Each is centered + // on the same inset laneX its tick line is drawn at - positioning by raw fraction instead would + // drift the labels up to a mark radius off their lines and push the domain-max label entirely + // past the clipped box's edge, hiding every ruler's max label. + for (tick in ticks) { + Text( + text = formatTick(tick), + style = typography.labelSmall, + color = colors.textMuted, + maxLines = 1, + modifier = Modifier.centeredAtTick(axis.fractionOf(tick), markRadius), + ) + } + } + } +} + +/** + * The box-select marquee: a rubber band over a whole scrolling sheet, reporting the region it enclosed. + * + * ARMED rather than always-on, because an unmodified drag on a lane already means something (scrub a key, + * or scrub the parameter), and a marquee that pre-empted those would cost the common gesture to serve the + * rarer one. Arming through a command means the same `B` and the same registry route the viewport's box + * select uses, so the muscle memory carries. + * + * Reports WINDOW coordinates - the same space the lanes report their bounds in - so the owner can resolve + * the region against rows that live inside a scroll it knows nothing about. + * + * While armed and before the drag begins it shows the same affordance the viewport's armed box select does: + * full-width / full-height marching-ants guides through the pointer, and the drawn crosshair standing in + * for a hidden OS cursor. Without it nothing on screen said the mode was active at all. The chrome comes + * from the theme kit ([drawCrosshairGuides] / [drawRubberBand]), shared with the viewport rather than + * reimplemented here - this package stays domain-free, but drawing primitives are not domain. + * + * @param Boolean armed Whether a marquee is awaiting its drag. + * @param Function onSelect Receives the enclosed region and whether the gesture was additive (Shift). + * @param Function onDismiss Called when the gesture ends or is abandoned, so the caller can disarm. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun TrackSheetMarqueeOverlay( + armed: Boolean, + onSelect: (Rect, Boolean) -> Unit, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + if (!armed) { + return + } + val style = selectionOverlayStyle(LocalUmamoColors.current) + val crosshairCursor = LocalUmamoCursors.crosshair + val latestSelect by rememberUpdatedState(onSelect) + val latestDismiss by rememberUpdatedState(onDismiss) + var origin by remember { mutableStateOf(null) } + var current by remember { mutableStateOf(null) } + var windowOffset by remember { mutableStateOf(Offset.Zero) } + // Null until the pointer is first seen, so an arm from the keyboard does not paint guides through the + // top-left corner before the hand has arrived. + var hoverPoint by remember { mutableStateOf(null) } + Canvas( + modifier = + modifier + .fillMaxSize() + .onGloballyPositioned { coordinates -> windowOffset = coordinates.boundsInWindow().topLeft } + // Hide the OS cursor so only the drawn crosshair shows, matching the armed viewport gesture. + .pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + // A SECOND pointerInput, on the Initial pass and consuming nothing: the gesture loop below + // blocks in awaitFirstDown and so sees no hover moves at all, which is why the guides need + // their own observer rather than a position latched inside the drag. + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Exit) { + hoverPoint = null + } else { + event.changes.lastOrNull()?.let { change -> hoverPoint = change.position } + } + } + } + } + .pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + down.consume() + val additive = currentEvent.keyboardModifiers.isShiftPressed + origin = down.position + current = down.position + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull { candidate -> candidate.id == down.id } ?: break + if (!change.pressed) { + change.consume() + break + } + current = change.position + change.consume() + } + val start = origin + val end = current + if (start != null && end != null) { + latestSelect( + Rect( + topLeft = Offset(minOf(start.x, end.x), minOf(start.y, end.y)) + windowOffset, + bottomRight = Offset(maxOf(start.x, end.x), maxOf(start.y, end.y)) + windowOffset, + ), + additive, + ) + } + origin = null + current = null + latestDismiss() + } + }, + ) { + val pointer = current ?: hoverPoint + // Guides only BEFORE the drag: once a band exists it says everything the guides did, and keeping + // both draws four lines through a box that is already outlined. + if (origin == null && pointer != null) { + drawCrosshairGuides(pointer, size, style) + } + drawRubberBand(origin, current, style) + if (pointer != null) { + drawCursor(crosshairCursor, pointer) + } + } +} + +/** + * The draggable column separator, as a full-height overlay over a whole scrolling sheet. + * + * An overlay rather than a per-row divider because the grab band has to run the WHOLE panel: a separator + * you can only catch in the 20dp ruler is a target the user has to hunt for, and with several sections + * stacked there is no single row that spans them anyway. Callers stack this in FRONT of their scroll + * container, at the same [labelColumnWidth] the sheets are drawn with. + * + * The rows still draw their own hairline at the same x, so the line is continuous where the overlay is + * merely transparent. + * + * @param Dp labelColumnWidth The current width, which the drag is applied to. + * @param Function onLabelColumnWidthChange Receives the new width, clamped to the sheet's bounds. + * @param Modifier modifier The layout modifier. + * @param Function onDraggingChange Reports whether a resize is in flight, so the caller can hold the cursor. + */ +@Composable +fun TrackSheetSeparatorOverlay( + labelColumnWidth: Dp, + onLabelColumnWidthChange: (Dp) -> Unit, + modifier: Modifier = Modifier, + onDraggingChange: (Boolean) -> Unit = {}, +) { + val density = LocalDensity.current + // The callback and the width are read at DRAG time, not captured at construction: the drag state + // outlives a recomposition, and a captured width would make every delta apply to a stale base. + val latestWidth by rememberUpdatedState(labelColumnWidth) + val latestCallback by rememberUpdatedState(onLabelColumnWidthChange) + val dragState = + remember(density) { + DraggableState { deltaPx -> + val delta = with(density) { deltaPx.toDp() } + latestCallback( + (latestWidth + delta).coerceIn(TRACK_LABEL_COLUMN_MIN_WIDTH, TRACK_LABEL_COLUMN_MAX_WIDTH), + ) + } + } + val resizeCursor = umamoPointerIcon(LocalUmamoCursors.ewScroll) + val latestDragging by rememberUpdatedState(onDraggingChange) + Row(modifier = modifier.fillMaxSize()) { + // A transparent spacer positions the grab band; it must not intercept anything, so the band is + // offset back by half its width to straddle the hairline the rows draw. + Spacer(modifier = Modifier.width(labelColumnWidth + 1.dp - SEPARATOR_GRAB_WIDTH / 2)) + Box( + modifier = + Modifier + .width(SEPARATOR_GRAB_WIDTH) + .fillMaxHeight() + .pointerHoverIcon(resizeCursor) + .draggable( + state = dragState, + orientation = Orientation.Horizontal, + onDragStarted = { latestDragging(true) }, + onDragStopped = { latestDragging(false) }, + ), + ) + } +} + +/** + * One row's track lane: its marks positioned along the axis, over the playhead. + * + * @param TrackRow row The row the lane belongs to. + * @param List marks The marks to draw (a collapsed group draws its subtree's). + * @param TrackAxis axis The domain. + * @param Float? playhead The playhead's domain value, or null. + * @param Color background The row's tone fill. + * @param Modifier modifier The layout modifier. + * @param Function? onMarkClick Invoked when a click lands on a mark, with whether Shift was held. + * @param Function? onTrackScrub Invoked as an empty-track drag moves, with the gesture's Shift state. + * @param Function? onTrackScrubEnd Invoked when an empty-track drag is released. + * @param Function? onMarkDrag Invoked on every move of a mark drag. + * @param Function? onMarkDragEnd Invoked when a mark drag is released. + * @param Function selectedMarkDragDelta The in-flight group-drag offset drawn on selected marks; null for none. + * @param Function? laneMenuItems Builds the lane's context-menu items. + * @param Function? onLaneHover Reports the live hit under the pointer, or null on exit. + * @param Function? onLaneBounds Reports the lane's window bounds. + * @param Dp markRadius Half-extent of a drawn mark, and the track region's end inset. + */ +@Composable +private fun TrackLane( + row: TrackRow, + marks: List, + axis: TrackAxis, + playhead: Float?, + background: Color, + modifier: Modifier = Modifier, + onMarkClick: ((TrackRow, TrackKeyMark, Boolean) -> Unit)?, + onTrackScrub: ((TrackRow, Float, Boolean) -> Unit)?, + onTrackScrubEnd: ((TrackRow, Float) -> Unit)?, + onMarkDrag: ((TrackRow, TrackKeyMark, Float) -> Unit)? = null, + onMarkDragEnd: ((TrackRow, TrackKeyMark, Float) -> Unit)? = null, + selectedMarkDragDelta: () -> Float? = { null }, + laneMenuItems: ((TrackLaneHit) -> List)? = null, + onLaneHover: ((TrackRow, TrackLaneHit?) -> Unit)? = null, + onLaneBounds: ((TrackRow, Rect) -> Unit)? = null, + markRadius: Dp, +) { + val colors = LocalUmamoColors.current + val density = LocalDensity.current + // The hit is reported live as the pointer MOVES, not merely on enter, because where along the lane the + // pointer sits is the whole point: a keyframe op aimed at a lane means "here", and a row-level hover + // could only say "somewhere on this row". The row rides along on the exit report too, so a receiver + // can ignore an exit for a row it is no longer holding - adjacent rows interleave, with the new row's + // enter arriving before the old row's exit. + val latestLaneHover by rememberUpdatedState(onLaneHover) + DisposableEffect(row.key) { + onDispose { latestLaneHover?.invoke(row, null) } + } + // The in-flight drag position, so the mark follows the pointer before the model is touched. The move is + // committed on release: a per-frame commit would push an undo step for every pixel of the drag. + var draggingMark by remember(row.key) { mutableStateOf(null) } + var dragDomainValue by remember(row.key) { mutableStateOf(0f) } + // The window the in-flight drag may move within: the axis, end to end. Latched at drag start for the + // same reason the number field latches its scrub base - so the bound cannot drift under the gesture. + var dragBounds by remember(row.key) { mutableStateOf(0f..0f) } + // The context menu's items depend on WHERE it was opened (over a key, or over empty track), so the + // gesture records only the anchor and the hit is resolved below, at composition time. Resolving it + // inside the gesture lambda would read whatever `marks` and `axis` were when that lambda was created - + // contextMenuGesture keys its pointerInput on Unit, so the first lambda is the one that runs forever. + var menuOpen by remember(row.key) { mutableStateOf(false) } + var menuAnchor by remember(row.key) { mutableStateOf(IntOffset.Zero) } + // The lane's measured width, so the pixel->domain mapping is available OUTSIDE a draw or pointer scope + // (the context-menu gesture reports a raw offset and has neither). + var laneWidth by remember(row.key) { mutableStateOf(0) } + val touchSlop = LocalViewConfiguration.current.touchSlop + val markRadiusPx = with(density) { markRadius.toPx() } + // The marks and the callbacks are read through latest-state holders rather than keying the gesture + // blocks below, and that is load-bearing rather than tidy: a pointerInput RESTARTS when a key changes, + // and both of these change identity the moment the SELECTION does. Keying on them would let an owner + // that clears the selection on the press (exactly what pressing empty track does) tear its own gesture + // down mid-stroke: the drag would freeze at the press point with no release ever arriving, so nothing + // would commit. Only the pixel-to-domain mapping still keys the blocks, because that genuinely + // invalidates a stroke in progress. + val editableMarks = remember(marks) { marks.filter { candidate -> candidate.editable } } + val latestEditableMarks by rememberUpdatedState(editableMarks) + val latestMarkClick by rememberUpdatedState(onMarkClick) + val latestTrackScrub by rememberUpdatedState(onTrackScrub) + val latestTrackScrubEnd by rememberUpdatedState(onTrackScrubEnd) + val latestMarkDrag by rememberUpdatedState(onMarkDrag) + val latestMarkDragEnd by rememberUpdatedState(onMarkDragEnd) + Box( + modifier = + modifier + .fillMaxHeight() + .background(background) + .clipToBounds() + // Window coordinates, so a marquee drawn over the whole scrolling sheet and a lane inside it + // are comparable without either knowing the other's scroll offset. + .onGloballyPositioned { coordinates -> onLaneBounds?.invoke(row, coordinates.boundsInWindow()) }, + ) { + Canvas( + modifier = + Modifier + .fillMaxSize() + .onSizeChanged { measured -> laneWidth = measured.width } + // Hover reporting is its own handler and consumes nothing: it has to see the pointer + // wherever it is, including mid-drag, and must never take an event from the gestures. + .pointerInput(row.key, axis, markRadiusPx) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + when (event.type) { + PointerEventType.Exit -> latestLaneHover?.invoke(row, null) + PointerEventType.Enter, PointerEventType.Move -> { + val value = domainAt(change.position.x, axis, size.width, markRadiusPx) + val mark = + nearestMark(latestEditableMarks, value, pickTolerance(axis, size.width, markRadiusPx)) + latestLaneHover?.invoke(row, TrackLaneHit(row, value, mark)) + } + + else -> Unit + } + } + } + } + .then( + if (laneMenuItems == null) { + Modifier + } else { + Modifier.contextMenuGesture { localOffset -> + menuAnchor = localOffset + menuOpen = true + } + }, + ) + // ONE gesture handler for tap AND drag. Two separate pointerInput blocks would race: a drag + // detector would consume the down before a tap detector saw it, so clicking a mark would do + // nothing and neither selection nor dragging would work. Deciding between them from a single + // stream is the only way they cannot fight. + .pointerInput(row.key, axis, markRadiusPx) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + // A secondary (right) press belongs to the context menu and a tertiary (middle) one + // to the sheet's pan. Without this guard either would also run the tap path on its + // way past: scrubbing the pose if the press missed every mark, or selecting the mark + // if it landed on one - instead of only reaching the gesture it actually means. + if (currentEvent.buttons.isSecondaryPressed || currentEvent.buttons.isTertiaryPressed) { + return@awaitEachGesture + } + // A sheet mounted with no handlers at all is read-only; it must not show drag feedback for a + // gesture that can go nowhere. Checked per gesture rather than keying the block, because the + // handlers change identity on every selection change and keying on them tears the stroke down. + if (latestMarkClick == null && latestTrackScrub == null && latestMarkDragEnd == null) { + return@awaitEachGesture + } + // Sampled at the PRESS, like the marquee's own Shift read: the modifier is part of what the + // gesture meant when it began, and a key released between press and release would otherwise + // silently change a extend-click into a replace-click. + val additive = currentEvent.keyboardModifiers.isShiftPressed + val pressedValue = domainAt(down.position.x, axis, size.width, markRadiusPx) + // Summary marks ARE addressable (summarizedMarks keeps them editable and renumbers them to a + // summary ordinal), so a press on one starts a drag like any other; it is the owner that maps + // that ordinal back to the whole set of child keys beneath it. Only a non-editable mark - a + // blend-shape binding - falls through to the scrub path. + // Sampled once at the press, so the marks a stroke hit-tests against cannot shift under + // it - the drag is manipulating the mark it started on, whatever the list does meanwhile. + val hitMark = + nearestMark(latestEditableMarks, pressedValue, pickTolerance(axis, size.width, markRadiusPx)) + var dragging = false + var releaseValue = pressedValue + // A press on empty track scrubs immediately, so the playhead lands under the + // pointer on the way down rather than only on release - the affordance a + // timeline ruler has, applied across the whole track region. + // + // CLAMPED to the axis, unlike a mark drag which clamps to its neighbours. A pose + // outside the parameter's range is not merely odd: the evaluator brackets nothing + // there, so every entity keyed on it hides. The clamp is the same one the + // pointer position is drawn with, so the playhead stops where the pointer stops. + val scrubBounds = minOf(axis.start, axis.end)..maxOf(axis.start, axis.end) + if (hitMark == null) { + latestTrackScrub?.invoke(row, pressedValue.coerceIn(scrubBounds), additive) + } + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull { candidate -> candidate.id == down.id } ?: break + if (!change.pressed) { + break + } + if (change.positionChange().x != 0f || change.positionChange().y != 0f) { + if (!dragging && abs(change.position.x - down.position.x) > touchSlop) { + dragging = true + if (hitMark != null) { + draggingMark = hitMark + dragBounds = dragBoundsOf(axis) + } + } + if (dragging) { + val pointerValue = domainAt(change.position.x, axis, size.width, markRadiusPx) + // A MARK drag is clamped as it moves rather than on release: one that + // follows the pointer past its neighbour and then snaps back reads as a + // rejected edit, where stopping at the wall reads as the wall being + // there. An empty-track scrub has no walls - it is a pose gesture. + releaseValue = + if (hitMark == null) { + pointerValue.coerceIn(scrubBounds) + } else { + pointerValue.coerceIn(dragBounds) + } + if (hitMark == null) { + latestTrackScrub?.invoke(row, releaseValue, additive) + } else { + dragDomainValue = releaseValue + // Reported every move, not only on release: an owner previewing a group drag needs + // the live value, and it is the owner - not the lane - that knows what travels with it. + latestMarkDrag?.invoke(row, hitMark, releaseValue) + } + change.consume() + } + } + } + when { + hitMark != null && dragging -> latestMarkDragEnd?.invoke(row, hitMark, releaseValue) + hitMark != null -> latestMarkClick?.invoke(row, hitMark, additive) + else -> latestTrackScrubEnd?.invoke(row, releaseValue) + } + draggingMark = null + } + }, + ) { + // A hairline baseline makes an empty track legible as a track rather than as blank panel. + drawLine( + colors.panelBorderHover, + Offset(0f, size.height * 0.5f), + Offset(size.width, size.height * 0.5f), + strokeWidth = 1f, + ) + playhead?.let { value -> drawPlayhead(value, axis, colors.accent, markRadiusPx) } + // Read HERE rather than in composition: a group drag changes it every pointer frame, and a draw + // scope read redraws the lanes without recomposing the sheet above them. + val groupDelta = selectedMarkDragDelta() + for (mark in marks) { + // A mark being dragged draws at the pointer, not at its stored position, so the gesture reads as + // direct manipulation rather than as a jump on release. A GROUP drag shifts every selected mark + // by the owner's offset instead - including the one under the hand, which is why that case is + // tested first: the group has already been clamped to its most constrained member, and letting the + // dragged mark run on past the rest would put back the snap the offset exists to remove - which is + // also why a group drag clamped to a standstill is a 0f offset and not a null one. + val drawnPosition = + when { + groupDelta != null && mark.selected -> mark.position + groupDelta + mark.keyIndex == draggingMark?.keyIndex -> dragDomainValue + else -> mark.position + } + val x = laneX(axis.fractionOf(drawnPosition), size.width, markRadiusPx) + val fill = + when { + !mark.editable -> colors.textDisabled + mark.selected -> colors.accent + else -> colors.controlGlyph + } + drawMark(mark.shape, Offset(x, size.height * 0.5f), markRadiusPx, fill, colors.panelBackground) + } + } + if (laneMenuItems != null && menuOpen && laneWidth > 0) { + val menuValue = domainAt(menuAnchor.x.toFloat(), axis, laneWidth, markRadiusPx) + val menuMark = nearestMark(marks, menuValue, pickTolerance(axis, laneWidth, markRadiusPx)) + Menu( + items = laneMenuItems(TrackLaneHit(row, menuValue, menuMark)), + onDismissRequest = { menuOpen = false }, + positionProvider = AtPointPositionProvider(menuAnchor), + focusable = true, + ) + } + } +} + +/** + * Maps a fraction across the lane to a pixel x, inset by [markRadius] at both ends. + * + * Without the inset a mark at either end of the domain draws half outside the lane and reads as clipped - + * which is exactly what a key at a parameter's min or max is, and every axis has two of those. + * + * @param Float fraction The 0..1 position across the domain. + * @param Float laneWidth The lane's pixel width. + * @param Float markRadius The half-extent of a mark, in pixels. + * @return Float The pixel x to draw at. + */ +private fun laneX(fraction: Float, laneWidth: Float, markRadius: Float): Float { + val usable = laneWidth - markRadius * 2f + return if (usable <= 0f) laneWidth * 0.5f else markRadius + fraction * usable +} + +/** + * The inverse of [laneX]: the domain value under a pixel x. + * + * @param Float x The pixel x within the lane. + * @param TrackAxis axis The domain. + * @param Int laneWidth The lane's pixel width. + * @param Float markRadius The half-extent of a mark, in pixels. + * @return Float The domain value there. + */ +private fun domainAt(x: Float, axis: TrackAxis, laneWidth: Int, markRadius: Float): Float { + val usable = laneWidth - markRadius * 2f + return if (usable <= 0f) axis.valueAt(0.5f) else axis.valueAt((x - markRadius) / usable) +} + +/** + * The pixel x a mark at [domainValue] is drawn at, within a lane [laneWidth] wide. + * + * Exposed because anything resolving a region of the sheet back to keys (a marquee) has to use the SAME + * mapping the marks were drawn with, including the end inset. Re-deriving it drifts by exactly the inset, + * which is the width of a mark - so this is the one definition, and [laneX] behind it is the one the marks + * themselves go through. + * + * @param TrackAxis axis The VISIBLE domain (a zoomed sheet passes its window's axis, not the full range). + * @param Float domainValue The mark's position. + * @param Float laneWidth The lane's pixel width. + * @param Float markRadiusPx The sheet's mark radius, which is also its end inset. + * @return Float The pixel offset within the lane. + */ +fun laneMarkOffsetX(axis: TrackAxis, domainValue: Float, laneWidth: Float, markRadiusPx: Float): Float = + laneX(axis.fractionOf(domainValue), laneWidth, markRadiusPx) + +/** + * The pick radius for a mark, in DOMAIN units, so it stays a constant number of pixels however wide the + * panel is or however large the domain is. + * + * @param TrackAxis axis The domain. + * @param Int laneWidth The lane's pixel width. + * @param Float markRadius The half-extent of a mark, in pixels. + * @return Float The tolerance, in domain units. + */ +private fun pickTolerance(axis: TrackAxis, laneWidth: Int, markRadius: Float): Float { + val usable = laneWidth - markRadius * 2f + return if (usable <= 0f) 0f else abs(axis.span) * (markRadius * 1.5f / usable) +} + +/** + * The tone-to-fill mapping, the only place a row's abstract color band becomes a real color. + * + * @param TrackRowTone tone The row's band. + * @return Color The fill to paint behind that row. + */ +@Composable +private fun toneBackgroundOf(tone: TrackRowTone): Color { + val colors = LocalUmamoColors.current + return when (tone) { + TrackRowTone.Group -> colors.trackRowGroup + TrackRowTone.Primary -> colors.trackRowPrimary + TrackRowTone.Secondary -> colors.trackRowSecondary + TrackRowTone.Alternate -> colors.trackRowAlternate + } +} + +/** Draws the playhead as a full-height vertical line at [value]'s position. */ +private fun DrawScope.drawPlayhead(value: Float, axis: TrackAxis, color: Color, inset: Float) { + val x = laneX(axis.fractionOf(value), size.width, inset) + drawLine(color, Offset(x, 0f), Offset(x, size.height), strokeWidth = 1.5f) +} + +/** + * Draws one mark centered on [center]. + * + * Every shape is filled then outlined in the panel color, so marks that land on top of each other (two + * channels keyed at the same value) stay countable instead of merging into one blob. + */ +private fun DrawScope.drawMark(shape: TrackKeyShape, center: Offset, radius: Float, fill: Color, outline: Color) { + when (shape) { + TrackKeyShape.Circle -> { + drawCircle(fill, radius, center) + drawCircle(outline, radius, center, style = Stroke(width = 1f)) + } + + TrackKeyShape.Square -> { + val topLeft = Offset(center.x - radius, center.y - radius) + val size = Size(radius * 2, radius * 2) + drawRect(fill, topLeft, size) + drawRect(outline, topLeft, size, style = Stroke(width = 1f)) + } + + TrackKeyShape.Diamond -> { + val path = + Path().apply { + moveTo(center.x, center.y - radius) + lineTo(center.x + radius, center.y) + lineTo(center.x, center.y + radius) + lineTo(center.x - radius, center.y) + close() + } + drawPath(path, fill) + drawPath(path, outline, style = Stroke(width = 1f)) + } + } +} + +/** + * Centers a composable on the ruler x of [fraction] - the same inset [laneX] mapping the tick lines use - + * clamped inward so the end labels stay fully visible inside the clipped ruler. + * + * @param Float fraction The 0..1 position across the domain. + * @param Dp markRadius The track region's end inset. + * @return Modifier The positioning modifier. + */ +private fun Modifier.centeredAtTick(fraction: Float, markRadius: Dp): Modifier = + this.layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0)) + val tickX = laneX(fraction, constraints.maxWidth.toFloat(), markRadius.toPx()) + val labelX = + (tickX - placeable.width * 0.5f) + .toInt() + .coerceIn(0, (constraints.maxWidth - placeable.width).coerceAtLeast(0)) + layout(placeable.width, placeable.height) { + placeable.placeRelative(labelX, 0) + } + } + +/** + * A tick label rounded to two decimals with a trailing ".0" trimmed, so an integral domain rules 10 / 20 + * rather than 10.0 / 20.0. + * + * Through kit's roundToDecimals, which ROUNDS: the axis generates ticks by repeated float addition, so a + * 0.2-step tick arrives as 0.59999996 - truncating it would label "0.59" beside neighbours reading 0.2 and + * 0.4, and would truncate negative ticks the other way, toward zero rather than away from it. + * + * @param Float value The tick value. + * @return String The label. + */ +fun defaultTickLabel(value: Float): String { + val rounded = roundToDecimals(value, 2) + return if (rounded == rounded.toInt().toFloat()) rounded.toInt().toString() else rounded.toString() +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/transform/DrawableWorldGeometry.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/transform/DrawableWorldGeometry.kt new file mode 100644 index 0000000..118213e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/transform/DrawableWorldGeometry.kt @@ -0,0 +1,176 @@ +package org.umamo.ui.transform + +import org.umamo.edit.Pose +import org.umamo.render.eval.DrawableSpaceMapping +import org.umamo.render.eval.drawableLocalPosed +import org.umamo.render.eval.drawableSpaceMapping +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/* + * The three spaces a drawable's geometry lives in, and the round trip between them. + * + * Every caller that transforms a whole drawable - the object gizmo's G / S / R, the Shift+S snaps, the + * Properties Transform rows - needs the same capture (base, the posed local shape, and that shape through + * the deformer chain into world) and ends with the same write-back (invert the transformed world shape to + * local, then difference it onto base). Both halves were open-coded at four sites before this file; the + * capture in particular is easy to get subtly wrong, because base is NOT the displayed shape for a + * keyformed drawable and the difference is what carries the edit across that gap. + * + * Lives in :ui rather than :edit because the mapping comes from :render's evaluator, and :edit and :render + * are siblings over :runtime - :edit cannot see it. See the plan's Context for why that layering stands. + */ + +/** + * One drawable captured in all three spaces at a fixed pose. + * + * The arrays are snapshots, not live views: a gesture captures once at the start and transforms the + * captured [world] every frame, so an in-flight preview never compounds on its own output. + * + * @property DrawableId drawableId The captured drawable. + * @property DrawableSpaceMapping mapping The local<->world mapping for the deformer chain at this pose. + * @property FloatArray base The stored rest positions (DrawableMesh.positions). + * @property FloatArray displayed The posed LOCAL shape - base plus the keyform blend; equals [base] for a + * drawable with no keyform grid. + * @property FloatArray world [displayed] projected through the deformer chain - what the viewport shows. + */ +internal class DrawableWorldGeometry( + val drawableId: DrawableId, + val mapping: DrawableSpaceMapping, + val base: FloatArray, + val displayed: FloatArray, + val world: FloatArray, +) { + /** Every vertex index of this drawable - the whole-mesh set an object-level transform moves. */ + val allIndices: Set get() = (0 until world.size / 2).toSet() + + /** + * Inverts a transformed WORLD shape back onto the base mesh - the write-back every whole-drawable + * transform ends with. + * + * Two steps, and both matter. The world shape is mapped back to local through the deformer chain + * (exact only at the neutral pose, which is why callers gate on isPoseNeutral), and the result is then + * DIFFERENCED against the captured displayed shape rather than written directly - see [movementToBase] + * for why that is what leaves the keyform grid untouched. + * + * @param FloatArray transformedWorld The reshaped world positions. + * @param Set indices The vertices the transform touched (the whole mesh for an object transform). + * @return FloatArray The new base positions (a fresh array). + */ + fun worldToBase(transformedWorld: FloatArray, indices: Set = allIndices): FloatArray { + val transformedLocal = mapping.worldToLocalLinearized(transformedWorld, displayed, world, indices) + return movementToBase(base, transformedLocal, displayed) + } + + /** + * Inverts one world-space click onto a new mesh-base position (Add Vertex free floats). + * + * Seeds the deformer inverse from the nearest existing vert when the live mesh still has verts. + * After a full wipe the live arrays are empty — pass the Edit-enter [spaceSeedBase] / projected + * [spaceSeedWorld] (same mesh kept for UV seeding) so warp Newton still starts on the art instead of + * inventing a bogus local seed that throws the rebuild off to the side. + * + * @param Float worldX Click x in viewport world space. + * @param Float worldY Click y in viewport world space. + * @param FloatArray? spaceSeedBase Pre-wipe rest positions, or null. + * @param FloatArray? spaceSeedWorld [spaceSeedBase] (or posed local) projected to world, or null. + * @return Pair The point in DrawableMesh.positions space. + */ + fun worldClickToBase( + worldX: Float, + worldY: Float, + spaceSeedBase: FloatArray? = null, + spaceSeedWorld: FloatArray? = null, + spaceSeedDisplayed: FloatArray? = null, + ): Pair { + val worldPoint = floatArrayOf(worldX, worldY) + val liveCount = base.size / 2 + val seedBase = if (liveCount > 0) base else spaceSeedBase + val seedWorld = if (liveCount > 0) world else spaceSeedWorld + val seedDisplayed = if (liveCount > 0) displayed else spaceSeedDisplayed ?: spaceSeedBase + val vertexCount = seedBase?.size?.div(2) ?: 0 + val (seedLocal, nearest) = + if (vertexCount > 0 && seedBase != null && seedWorld != null && seedWorld.size >= vertexCount * 2) { + var best = 0 + var bestDistance = Float.POSITIVE_INFINITY + for (index in 0 until vertexCount) { + val dx = seedWorld[index * 2] - worldX + val dy = seedWorld[index * 2 + 1] - worldY + val distance = dx * dx + dy * dy + if (distance < bestDistance) { + bestDistance = distance + best = index + } + } + // Newton seeds from posed local (displayed), not rest — same space worldToLocal solves in. + val localSeedX = seedDisplayed?.getOrNull(best * 2) ?: seedBase[best * 2] + val localSeedY = seedDisplayed?.getOrNull(best * 2 + 1) ?: seedBase[best * 2 + 1] + floatArrayOf(localSeedX, localSeedY) to best + } else { + // Last resort (no live verts, no Edit-enter seed): direct Y un-negation / weak Newton start. + floatArrayOf(worldX, -worldY) to -1 + } + val local = mapping.worldToLocal(worldPoint, seedLocal, setOf(0)) + if (nearest < 0 || seedBase == null || seedDisplayed == null || seedDisplayed.size < (nearest + 1) * 2) { + return local[0] to local[1] + } + val deltaX = seedDisplayed[nearest * 2] - seedBase[nearest * 2] + val deltaY = seedDisplayed[nearest * 2 + 1] - seedBase[nearest * 2 + 1] + return (local[0] - deltaX) to (local[1] - deltaY) + } + + /** + * Projects one mesh-base point into viewport world space (draft draw / hit-test). + * + * @param Float baseX Rest x. + * @param Float baseY Rest y. + * @return Pair World point. + */ + fun baseToWorld(baseX: Float, baseY: Float): Pair { + val worldPoint = mapping.localToWorld(floatArrayOf(baseX, baseY)) + return worldPoint[0] to worldPoint[1] + } +} + +/** + * Captures [drawableId] in all three spaces at [pose]. + * + * Null when the drawable carries no mesh, or when it has no world mapping at all - which happens when an + * ancestor is hidden. A caller sweeping a selection should SKIP a null rather than abort, so one hidden + * drawable does not block a gesture over the others. + * + * @param PuppetModel model The document model. + * @param Pose pose The parameter values to capture at. + * @param DrawableId drawableId The drawable to capture. + * @return DrawableWorldGeometry? The capture, or null when the drawable has no mesh or no mapping. + */ +internal fun captureDrawableWorld(model: PuppetModel, pose: Pose, drawableId: DrawableId): DrawableWorldGeometry? { + val base = model.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.mesh?.positions ?: return null + val mapping = drawableSpaceMapping(model, pose, drawableId) ?: return null + val displayed = drawableLocalPosed(model, pose, drawableId) ?: base + return DrawableWorldGeometry(drawableId, mapping, base, displayed, mapping.localToWorld(displayed)) +} + +/** + * Transfers a displayed-shape movement onto the base mesh: `newBase = base + (after - before)`. The rest + * shape a rigger sees is base + the neutral keyform blend; because the blend cancels out of the + * subtraction, the moved rest shape re-renders exactly at `after` while only DrawableMesh.positions is + * written - no keyform cell is touched, and blend-shape deltas (relative to base) follow the edit. For a + * grid-less drawable `before` equals base, so this degenerates to `newBase = after`. + * + * The one caller is [DrawableWorldGeometry.worldToBase], which owns the second half of every whole-drawable + * write-back; the overlays and the Properties panel all reach it through that method rather than directly. + * + * @param FloatArray base The rest positions captured at gesture start. + * @param FloatArray after The transformed displayed shape. + * @param FloatArray before The displayed shape captured at gesture start. + * @return FloatArray The new base positions (a fresh array). + */ +private fun movementToBase(base: FloatArray, after: FloatArray, before: FloatArray): FloatArray = + FloatArray(base.size) { coordIndex -> + if (coordIndex < after.size && coordIndex < before.size) { + base[coordIndex] + after[coordIndex] - before[coordIndex] + } else { + base[coordIndex] + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/transform/DrawableWorldTransform.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/transform/DrawableWorldTransform.kt new file mode 100644 index 0000000..35604fc --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/transform/DrawableWorldTransform.kt @@ -0,0 +1,155 @@ +package org.umamo.ui.transform + +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshBounds +import org.umamo.edit.MeshChange +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.Pose +import org.umamo.edit.isPoseNeutral +import org.umamo.edit.meshBounds +import org.umamo.edit.movedToBoundsCenter +import org.umamo.edit.resizedAboutBoundsCenter +import org.umamo.render.eval.drawableLocalPosed +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/* + * The Properties Transform panel's coordinate space. + * + * A drawable's Drawable.mesh.positions is its BASE array, and that is NOT the geometry on screen: the + * displayed shape is `base + Σ wᵢ·Δᵢ` from the keyform grid, then mapped through the parent deformer chain + * into world space. For a drawable parented to a deformer the two diverge wildly - a corpus model has an + * art mesh whose base array is 1.9 units wide while the drawable itself is 183.8 wide - so reading or + * writing the base array directly shows meaningless numbers and turns a small typed nudge into a huge + * transform. + * + * So the panel works in WORLD space, the same space the viewport and the object gizmo use, and reuses the + * gizmo's round trip: capture world, transform world, invert to local, difference back onto base. The + * inverse (worldToLocalLinearized) is exact only at the neutral pose, which is why every write here is + * gated on isPoseNeutral exactly as EditorSession.beginObjectOperator is - the panel disables its fields + * rather than writing geometry it cannot invert. + * + * Everything here stays in world space, whose zero is the canvas's top-left corner. The rigger reads + * positions from the world axes instead, so the Position rows convert at the display boundary through the + * :runtime helpers (OriginRelativeCoordinates.kt) and hand this file world coordinates. + * + * WHY THIS EDITS FROM :ui. Editing logic over EditorSession belongs in :edit; this file is the standing + * exception, and the reason is the module graph, not convenience. World space is produced by :render's + * deform eval (drawableLocalPosed below), and :edit and :render are SIBLINGS over :runtime - :edit cannot + * see :render, so an edit expressed in world space cannot live there. :ui depends on both, so it is the + * lowest module that can hold this. Do not read it as licence to put other session edits here: anything + * that does not need :render belongs in :edit (see KeyformAimEdits.kt, which was moved out of :ui for exactly + * this reason). + */ + +/** + * The world-space geometry backing one drawable's Transform rows: the bounds to display, and whether they + * can be written back. + * + * @property MeshBounds bounds The drawable's axis-aligned world bounds (x horizontal, y up = the panel's Z), which the panel shows relative to the world origin. + * @property Boolean editable Whether an edit can be inverted back onto the base mesh (see [drawableWorldTransform]). + */ +internal class DrawableWorldTransform(val bounds: MeshBounds, val editable: Boolean) + +/** + * Resolves the world bounds of drawable [id] at [pose] - what the Transform rows show. + * + * Not editable when the pose is off neutral (the deformer-chain inverse is only exact there) or when the + * drawable has no world mapping at all, which happens when an ancestor is hidden. In that second case the + * posed LOCAL geometry is reported instead so the rows still show the drawable's real proportions rather + * than the misleading base array; it is marked non-editable, so nothing can be written from it. + * + * @param PuppetModel model The document model. + * @param Pose pose The live parameter values. + * @param DrawableId id The drawable to measure. + * @return DrawableWorldTransform? The bounds and their editability, or null when the drawable has no mesh. + */ +internal fun drawableWorldTransform(model: PuppetModel, pose: Pose, id: DrawableId): DrawableWorldTransform? { + val base = model.drawables.firstOrNull { drawable -> drawable.id == id }?.mesh?.positions ?: return null + if (base.size < 2) { + return null + } + val captured = captureDrawableWorld(model, pose, id) + if (captured == null) { + // No world mapping (a hidden ancestor). The posed local shape is still worth showing, so resolve it + // directly rather than going through the capture, which requires a mapping. + val displayed = drawableLocalPosed(model, pose, id) ?: base + // No world mapping (a hidden ancestor), so fall back to the posed LOCAL geometry - but negate the + // center's y first. localToWorld flips y (world y grows upward), so reporting local y raw would make + // the Position Z row jump sign purely because an ancestor was toggled invisible. Extents are + // unsigned and carry over as-is. Not editable: without a mapping there is nothing to invert through. + // For a root drawable local space IS canvas space, so this is its true world center and the row's + // origin conversion reads it correctly. Under a deformer it is the deformer's local space, which no + // origin conversion can make meaningful; the row is read-only there, so it is shown as it is. + val local = meshBounds(displayed) + return DrawableWorldTransform( + MeshBounds(local.centerX, -local.centerY, local.width, local.height), + editable = false, + ) + } + return DrawableWorldTransform(meshBounds(captured.world), editable = isPoseNeutral(model, pose)) +} + +/** + * Applies [transformWorld] to drawable [id]'s world geometry and commits the result as one undo step. + * + * The round trip mirrors the object gizmo: project the posed local geometry to world, let the caller + * reshape it there, invert the result back to local through the deformer chain, then difference that + * against the posed local shape to recover the new BASE array (a keyformed drawable's base is not its + * displayed shape, so the delta is what carries over). Refuses off the neutral pose, on a missing mesh or + * mapping, and on a transform that returned its input unchanged - each records nothing. + * + * @param DrawableId id The drawable to transform. + * @param MeshChange change The history descriptor for the edit. + * @param Function transformWorld Reshapes the world positions; returning the same instance means no-op. + */ +private fun EditorSession.commitWorldTransform( + id: DrawableId, + change: MeshChange, + transformWorld: (FloatArray) -> FloatArray, +) { + val currentModel = model.value + val currentPose = pose.value + // The same guard beginObjectOperator applies: writing a deformed capture back through the warp inverse + // corrupts the rest mesh, so the panel refuses rather than corrupting it. + if (!isPoseNeutral(currentModel, currentPose)) { + return + } + val captured = captureDrawableWorld(currentModel, currentPose, id) ?: return + val targetWorld = transformWorld(captured.world) + if (targetWorld === captured.world) { + return + } + commitObjectPositions(change, mapOf(id to captured.worldToBase(targetWorld))) +} + +/** + * Moves drawable [id] so its world bounds center lands on ([centerX], [centerZ]) - the Transform panel's + * Position row - as one undo step. [centerZ] grows upward, like the panel's Z. Both are WORLD + * coordinates: the row converts its origin-relative value to world before calling this. + * + * @param DrawableId id The drawable to move. + * @param Float centerX The world x its bounds center should land on. + * @param Float centerZ The world z (up) its bounds center should land on. + */ +internal fun EditorSession.setDrawableWorldCenter(id: DrawableId, centerX: Float, centerZ: Float) { + commitWorldTransform(id, MeshChange.TransformDrawables(listOf(id), MeshOperatorKind.Grab)) { world -> + movedToBoundsCenter(world, centerX, centerZ) + } +} + +/** + * Scales drawable [id] about its world bounds center so its world extents become ([width], [height]) - the + * Transform panel's Size row - as one undo step. The bounds center is the pivot, so resizing leaves the + * Position row's numbers unchanged. + * + * @param DrawableId id The drawable to resize. + * @param Float width The target world x extent. + * @param Float height The target world y extent. + */ +internal fun EditorSession.setDrawableWorldSize(id: DrawableId, width: Float, height: Float) { + // Scale, though no modal operator ran: the kind names what the transform WAS, not how it was driven. + commitWorldTransform(id, MeshChange.TransformDrawables(listOf(id), MeshOperatorKind.Scale)) { world -> + resizedAboutBoundsCenter(world, width, height) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/CameraController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/CameraController.kt new file mode 100644 index 0000000..7709c09 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/CameraController.kt @@ -0,0 +1,201 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshTopology +import org.umamo.edit.eligibleTransformDrawables +import org.umamo.render.eval.drawableLocalPosed +import org.umamo.render.eval.drawableSpaceMapping + +/** + * The camera operations one editor area exposes to the shell's view commands (Fit / 1:1 / zoom / Zoom + * Region / Frame Selected). Both the 2D viewport and the UV editor host camera-bearing areas, and each + * registers one of these into the AreaCameraHub for its area's lifetime; the shell's view commands + * resolve the hovered area's controller through the hub at dispatch time. A new camera-bearing space + * reuses this by registering its own implementation - never by adding a branch to the view commands. + */ +internal interface CameraController { + /** Frames the area's content to fit. */ + fun fit() + + /** Sets true 1:1 (one content unit per screen pixel). */ + fun actualSize() + + /** + * Zooms in one step about the view center. + * + * @param Boolean coarse Use the larger (Shift) step. + */ + fun zoomIn(coarse: Boolean) + + /** + * Zooms out one step about the view center. + * + * @param Boolean coarse Use the larger (Shift) step. + */ + fun zoomOut(coarse: Boolean) + + /** + * Arms the drag-a-box-to-frame Zoom Region gesture over this area. The area's + * mounted region overlay captures the drag and frames the box on release. + */ + fun armZoomRegion() + + /** Frames the selection's covered bounds; a no-op with nothing covered. */ + fun frameSelected() +} + +/** + * A [CameraController] backed by the shared [PuppetViewportService], bound to one fixed area. The five + * navigation ops are identical across every camera-bearing space - they only differ in which area they + * target and in how Frame Selected computes its bounds - so this hoists them here against the fixed + * [areaId], leaving [frameSelected] to each concrete space. + * + * @property PuppetViewportService service The render service holding this area's per-area camera. + * @property EditorSession session The session, for the Zoom Region arming flag and Frame Selected bounds. + * @property String areaId The area this controller drives (the same id its space registered under). + */ +internal abstract class ServiceCameraController( + protected val service: PuppetViewportService, + protected val session: EditorSession, + protected val areaId: String, +) : CameraController { + override fun fit() { + service.fit(areaId) + } + + override fun actualSize() { + service.actualSize(areaId) + } + + override fun zoomIn(coarse: Boolean) { + service.zoomCentered(areaId, zoomIn = true, coarse = coarse) + } + + override fun zoomOut(coarse: Boolean) { + service.zoomCentered(areaId, zoomIn = false, coarse = coarse) + } + + override fun armZoomRegion() { + // Arms the session flag for this area; the area's top-level region overlay captures the drag and + // calls service.zoomToRegion on release. Works in Object and Edit mode alike. + session.armZoomRegion(areaId) + } +} + +/** + * The 2D viewport's camera controller for one viewport area. Frame Selected frames world-space posed + * geometry: in Edit mode the covered vertices of the session selection at the neutral pose, in Object + * mode the selected drawables' whole posed geometry at the live pose - matching what the viewport shows. + * + * @property PuppetViewportService service The render service holding this area's camera. + * @property EditorSession session The session whose selection / pose Frame Selected reads. + * @property String areaId The viewport area this controller drives. + */ +internal class ViewportSpaceCamera( + service: PuppetViewportService, + session: EditorSession, + areaId: String, +) : ServiceCameraController(service, session, areaId) { + override fun frameSelected() { + val model = session.model.value + var minX = Float.MAX_VALUE + var minY = Float.MAX_VALUE + var maxX = -Float.MAX_VALUE + var maxY = -Float.MAX_VALUE + + fun include(worldPositions: FloatArray, vertexIndices: Iterable) { + for (vertexIndex in vertexIndices) { + minX = minOf(minX, worldPositions[vertexIndex * 2]) + maxX = maxOf(maxX, worldPositions[vertexIndex * 2]) + minY = minOf(minY, worldPositions[vertexIndex * 2 + 1]) + maxY = maxOf(maxY, worldPositions[vertexIndex * 2 + 1]) + } + } + if (session.mode.value == EditorMode.Edit) { + // The covered vertices of the session selection, at the neutral pose Edit mode is pinned to. + val meshSelection = session.meshSelection.value + for (drawableId in meshSelection.drawableIds) { + val elements = meshSelection.elementsOf(drawableId) + if (elements.isEmpty()) { + continue + } + val mesh = model.drawables.firstOrNull { it.id == drawableId }?.mesh ?: continue + val covered = MeshTopology.coveredVertexIndices(elements, mesh.indices) + if (covered.isEmpty()) { + continue + } + val mapping = drawableSpaceMapping(model, emptyMap(), drawableId) ?: continue + val world = mapping.localToWorld(drawableLocalPosed(model, emptyMap(), drawableId) ?: mesh.positions) + include(world, covered) + } + } else { + // The selected drawables' whole posed geometry, at the LIVE pose - what the viewport shows. + val pose = session.pose.value + val eligibleIds = eligibleTransformDrawables(session.selection.value, model) ?: return + for (drawableId in eligibleIds) { + val mesh = model.drawables.firstOrNull { it.id == drawableId }?.mesh ?: continue + val mapping = drawableSpaceMapping(model, pose, drawableId) ?: continue + val world = mapping.localToWorld(drawableLocalPosed(model, pose, drawableId) ?: mesh.positions) + include(world, 0 until world.size / 2) + } + } + if (minX > maxX) { + return + } + service.fitWorldRect(areaId, minX, minY, maxX, maxY) + } +} + +/** + * The UV editor's camera controller for one UV-editor area. Frame Selected frames the covered UV + * bounds in the editor's display space: in Edit mode the covered vertices of the mesh selection, in + * Object mode every vertex of the shown geometries (the selected drawables). A one-texel floor keeps a + * single-vertex frame from exploding the zoom to its clamp. + * + * @property PuppetViewportService service The render service holding this area's camera. + * @property EditorSession session The session whose mode / mesh selection Frame Selected reads. + * @property String areaId The UV editor area this controller drives. + * @property Function geometries The display-space geometries Frame Selected frames, re-read on each + * call; the host's supplier narrows Object mode to the selected islands. + */ +internal class UvSpaceCamera( + service: PuppetViewportService, + session: EditorSession, + areaId: String, + private val geometries: () -> List, +) : ServiceCameraController(service, session, areaId) { + override fun frameSelected() { + // Mirror the 2D viewport's mode split (ViewportSpaceCamera.frameSelected): Edit mode frames the + // covered (selected) vertices; Object mode has no element selection, so it frames every vertex + // of the supplied geometries - the host's supplier narrows Object mode to the SELECTED islands + // (the shown list is every visible island on the surface). Without this branch Object-mode Frame + // Selected is a no-op, because meshSelection is empty there and coveredVertexIndices returns + // nothing. + val editMode = session.mode.value == EditorMode.Edit + val selection = session.meshSelection.value + var minX = Float.MAX_VALUE + var minY = Float.MAX_VALUE + var maxX = -Float.MAX_VALUE + var maxY = -Float.MAX_VALUE + for (geometry in geometries()) { + val vertexIndices: Iterable = + if (editMode) { + MeshTopology.coveredVertexIndices(selection.elementsOf(geometry.drawableId), geometry.indices) + } else { + 0 until geometry.positions.size / 2 + } + for (vertexIndex in vertexIndices) { + minX = minOf(minX, geometry.positions[vertexIndex * 2]) + maxX = maxOf(maxX, geometry.positions[vertexIndex * 2]) + minY = minOf(minY, geometry.positions[vertexIndex * 2 + 1]) + maxY = maxOf(maxY, geometry.positions[vertexIndex * 2 + 1]) + } + } + if (minX > maxX) { + return + } + // A one-texel floor keeps a single-vertex frame from exploding the zoom to its clamp. + service.fitWorldRect(areaId, minX, minY, maxOf(maxX, minX + 1f), maxOf(maxY, minY + 1f)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/Cursor2dOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/Cursor2dOverlay.kt new file mode 100644 index 0000000..efea5d9 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/Cursor2dOverlay.kt @@ -0,0 +1,120 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.inset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import org.umamo.edit.EditorSession +import org.umamo.render.ViewportCamera +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.drawIcon + +/** + * The world-space 2D cursor marker: the authored dashed-ring crosshair (LocalUmamoIcons.cursor2d, + * axis-colored arm tips) at its world position, in both modes (it anchors pivots and snaps regardless + * of mode), projected through the frame camera and drawn at a screen-constant size. + * + * The cursor is a control, not HUD chrome - the mode gizmos place it (Shift+RightClick) and the + * transform pivot and snap commands consume it - so it draws in this overlay of its own, mounted + * above the gizmo chrome and below the informational HUD. The layer itself is draw-only (no pointer + * input), and it projects through the DISPLAYED frame's camera (like every world-anchored overlay + * drawing) so it never swims against the raster. + * + * @param EditorSession session The session whose 2D cursor this overlay draws. + * @param ViewportCamera? camera The displayed frame's camera (world<->screen); null skips drawing. + * @param Int widthPx The viewport width in px. + * @param Int heightPx The viewport height in px. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +internal fun Cursor2dOverlay( + session: EditorSession, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + modifier: Modifier = Modifier, +) { + val cursor by session.cursor2d.collectAsState() + val cursorColors = LocalUmamoColors.current + val cursorToDraw = cursor + if (cursorToDraw == null || camera == null) { + return + } + Canvas(modifier = modifier.fillMaxSize()) { + drawCursorMarker( + center = worldToScreen(cursorToDraw.worldX, cursorToDraw.worldZ, camera, IntSize(widthPx, heightPx)), + tint = cursorColors.viewportBadgeText, + ) + } +} + +/** + * The UV cursor marker (the texture-space 2D cursor), the UV editor's twin of [Cursor2dOverlay]: + * the same crosshair at the cursor's display-space position, present in both modes and drawn above + * the gizmo chrome for viewport parity. Draw-only; placement stays a gizmo gesture + * (Shift+RightClick, handled by the mode's own overlay in both modes). + * + * The cursor is stored in ATLAS coordinates, so the shown surface's frame is what puts it in the + * right place: over a page that is the plain texel mapping, and over a source layer it also carries + * the drawable's placement. One cursor either way - the same point on the art, wherever it is seen. + * + * @param EditorSession session The session whose UV cursor this overlay draws. + * @param UvEditFrame frame The shown surface's texel size plus its conversion from stored coordinates. + * @param ViewportCamera? camera The displayed frame's camera; null skips drawing. + * @param Int widthPx The area width in px. + * @param Int heightPx The area height in px. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +internal fun UvCursorOverlay( + session: EditorSession, + frame: UvEditFrame, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + modifier: Modifier = Modifier, +) { + val cursor by session.uvCursor.collectAsState() + val cursorColors = LocalUmamoColors.current + val cursorToDraw = cursor + if (cursorToDraw == null || camera == null) { + return + } + val (cursorDisplayX, cursorDisplayY) = frame.displayAt(cursorToDraw.u, cursorToDraw.v) + Canvas(modifier = modifier.fillMaxSize()) { + drawCursorMarker( + center = worldToScreen(cursorDisplayX, cursorDisplayY, camera, IntSize(widthPx, heightPx)), + tint = cursorColors.viewportBadgeText, + ) + } +} + +/** + * The cursor crosshair marker (the authored dashed-ring icon) at a projected screen point, drawn at a + * screen-constant size - shared by the two cursor overlays above. + * + * @param Offset center The marker's center in area-local pixels. + * @param Color tint The icon tint. + */ +private fun DrawScope.drawCursorMarker(center: Offset, tint: Color) { + val iconSizePx = 36.dp.toPx() + // drawIcon fills the DrawScope's square, so shrink the bounds to an icon-sized box centered + // on the projected point (negative insets are fine when the cursor sits near an edge). + inset( + left = center.x - iconSizePx / 2f, + top = center.y - iconSizePx / 2f, + right = size.width - center.x - iconSizePx / 2f, + bottom = size.height - center.y - iconSizePx / 2f, + ) { + drawIcon(LocalUmamoIcons.cursor2d, tint) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/CursorWrap.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/CursorWrap.kt new file mode 100644 index 0000000..6e2ab0c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/CursorWrap.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import kotlin.math.min + +/** How close (px) to a viewport edge a modal-gesture pointer must be to trigger a Blender-style wrap. */ +internal const val WRAP_MARGIN_PX = 2f + +/** + * Where (px from the opposite edge) the wrapped cursor reappears. Must be greater than [WRAP_MARGIN_PX] + * so the teleport lands clear of the trigger zone and cannot immediately re-wrap. + */ +internal const val WRAP_INSET_PX = 4f + +/** + * The area-local point the cursor should teleport to when a modal gesture reaches a viewport edge, or null + * when [local] is not within [margin] px of (or beyond) any edge. A triggered axis wraps to the opposite + * side inset by [inset] px; the other axis is kept clamped in bounds so the target is a valid interior + * point. Because [inset] is greater than [margin] (and an axis only wraps when the viewport is wider than + * `inset + margin`), the teleport always lands clear of the trigger zone, so it cannot immediately re-wrap. + * Pure and side-effect free so the wrap geometry is unit-testable without Compose input. + * + * @param Offset local The current pointer position in area-local pixels. + * @param IntSize size The area size in pixels. + * @param Float margin The edge proximity (px) that triggers a wrap. + * @param Float inset The distance (px) from the opposite edge the wrapped cursor reappears at. + * @return Offset? The wrapped local position, or null when no edge was reached. + */ +internal fun computeCursorWrap(local: Offset, size: IntSize, margin: Float, inset: Float): Offset? { + val width = size.width.toFloat() + val height = size.height.toFloat() + var wrappedX = local.x.coerceIn(0f, width) + var wrappedY = local.y.coerceIn(0f, height) + var wrapped = false + // Only wrap an axis when the viewport is wide enough that both the near trigger zone and the far + // teleport target fit without overlap - otherwise a sliver of an area would ping-pong the cursor. + if (width > inset + margin) { + if (local.x <= margin) { + wrappedX = width - inset + wrapped = true + } else if (local.x >= width - margin) { + wrappedX = inset + wrapped = true + } + } + if (height > inset + margin) { + if (local.y <= margin) { + wrappedY = height - inset + wrapped = true + } else if (local.y >= height - margin) { + wrappedY = inset + wrapped = true + } + } + return if (wrapped) { + Offset(wrappedX, wrappedY) + } else { + null + } +} + +/** + * The cursor-wrap bookkeeping for one modal gesture, shared by the gizmo overlays: the accumulated + * wrap offset that keeps the virtual pointer continuous across teleports, the pending-landing guard + * that discards stale pre-warp events, and the fold rule that uses the ACTUAL landed position. The + * platform warp call is injected so every rule is unit-testable without Compose input or a real OS + * cursor. + * + * @param Function warpCursor Warps the OS cursor to an absolute screen position and returns where it + * actually landed, or null when the platform cannot warp; defaults to [warpViewportCursor]. + */ +internal class CursorWrapState( + private val warpCursor: (Float, Float) -> Offset? = { screenX, screenY -> warpViewportCursor(screenX, screenY) }, +) { + /** + * The sum of every cursor-wrap teleport in the current gesture. The transform is driven by a + * "virtual" pointer (raw position + this offset) that keeps moving as if the cursor had never + * wrapped, so every operator - Grab, Scale, Rotate - stays continuous across a wrap. + */ + var wrapOffset: Offset = Offset.Zero + private set + + // Where the last warp landed (viewport-local), or null when no warp is pending confirmation. + private var pendingWarpLanding: Offset? = null + + /** + * The wrap-continuous ("virtual") pointer for [rawPosition]: the raw position plus every wrap so + * far, so the transform keeps tracking as if the cursor had never teleported. This is what makes + * Scale and Rotate unbounded - the virtual pointer travels past the viewport edge freely. + * + * @param Offset rawPosition The physical pointer position in area-local pixels. + * @return Offset The virtual pointer position. + */ + fun virtualPointer(rawPosition: Offset): Offset = rawPosition + wrapOffset + + /** + * Filters one arriving Move / Exit position against a pending warp. Move events generated BEFORE + * a warp but delivered after it still carry old-edge positions; interpreting them against the + * post-warp [wrapOffset] spikes the transform and re-triggers the wrap (double-counting - the + * pointer-vs-HUD desync). The real post-warp event lands near the warp landing; anything half a + * viewport away is stale - the caller freezes its pointer at the returned landing and consumes + * the event. A fresh arrival clears the pending landing and returns null. + * + * @param Offset position The arriving pointer position in area-local pixels. + * @param IntSize size The area size in pixels. + * @return Offset? The landing to freeze the pointer at when [position] is stale, or null when the + * event is fresh and processing should continue. + */ + fun resolveArrival(position: Offset, size: IntSize): Offset? { + val expectedLanding = pendingWarpLanding + if (expectedLanding != null && (position - expectedLanding).getDistance() > min(size.width, size.height) / 2f) { + return expectedLanding + } + pendingWarpLanding = null + return null + } + + /** + * Wraps the cursor at a viewport edge (Blender-style, all operators): when [position] reaches an + * edge, teleport it to the opposite side and fold the jump into [wrapOffset] so the virtual + * pointer stays continuous. The ACTUAL landed position (read back from the OS) is folded - not + * the requested target - because mouseMove rounds, clamps, and can be platform-rescaled, and any + * request-vs-landing difference otherwise accumulates as drift across wraps. On a no-op platform + * (Android, or a Robot-less desktop) nothing folds, so the cursor just freezes at the edge rather + * than desyncing the transform. Opposite-edge (not toward-pivot) is deliberate: it is what lets + * a shrink fire wraps and reach the pivot again. + * + * @param Offset position The current pointer position in area-local pixels. + * @param IntSize size The area size in pixels. + * @param Offset? areaScreenOrigin The area's top-left in absolute screen pixels, or null before + * first layout (no wrap can happen without it). + * @return Offset? The landed area-local position (the caller's new pointer), or null when no wrap + * happened. + */ + fun maybeWrap(position: Offset, size: IntSize, areaScreenOrigin: Offset?): Offset? { + val wrapTarget = computeCursorWrap(position, size, WRAP_MARGIN_PX, WRAP_INSET_PX) ?: return null + val origin = areaScreenOrigin ?: return null + val landedScreen = warpCursor(origin.x + wrapTarget.x, origin.y + wrapTarget.y) ?: return null + val landed = Offset(landedScreen.x - origin.x, landedScreen.y - origin.y) + wrapOffset += position - landed + pendingWarpLanding = landed + return landed + } + + /** Resets the gesture bookkeeping; called when a gesture starts and when it tears down. */ + fun reset() { + wrapOffset = Offset.Zero + pendingWarpLanding = null + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/FreeTransformChrome.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/FreeTransformChrome.kt new file mode 100644 index 0000000..5de426e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/FreeTransformChrome.kt @@ -0,0 +1,100 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.AxisAlignedBounds +import org.umamo.edit.BoundsHandle +import org.umamo.render.ViewportCamera +import kotlin.math.hypot + +/** Hit radius for a free-transform handle, in viewport pixels (generous for pen / touch). */ +internal const val FREE_TRANSFORM_HANDLE_HIT_PX = 12f + +/** Half-size of the drawn handle square, in viewport pixels. */ +private const val HANDLE_HALF_PX = 4.5f + +/** + * Draws a Photoshop-style scale marquee: a dashed AABB around [bounds] plus eight filled handle + * squares at the corners and edge midpoints. + * + * @param AxisAlignedBounds bounds World-space selection bounds. + * @param ViewportCamera camera World↔screen projection. + * @param IntSize size Overlay size in pixels. + * @param Color lineColor Marquee stroke color. + * @param Color handleFill Handle square fill. + * @param Color handleStroke Handle square outline. + */ +internal fun DrawScope.drawFreeTransformBox( + bounds: AxisAlignedBounds, + camera: ViewportCamera, + size: IntSize, + lineColor: Color, + handleFill: Color = Color.White, + handleStroke: Color = Color.Black.copy(alpha = 0.75f), +) { + if (bounds.width <= 0f && bounds.height <= 0f) { + // A single point still gets handles so a collapsed selection can be scaled open. + if (bounds.minX == 0f && bounds.minY == 0f && bounds.maxX == 0f && bounds.maxY == 0f) { + return + } + } + val bottomLeft = worldToScreen(bounds.minX, bounds.minY, camera, size) + val bottomRight = worldToScreen(bounds.maxX, bounds.minY, camera, size) + val topLeft = worldToScreen(bounds.minX, bounds.maxY, camera, size) + val topRight = worldToScreen(bounds.maxX, bounds.maxY, camera, size) + val dash = floatArrayOf(5f, 4f) + val effect = PathEffect.dashPathEffect(dash) + drawLine(lineColor, bottomLeft, bottomRight, strokeWidth = 1.25f, pathEffect = effect) + drawLine(lineColor, bottomRight, topRight, strokeWidth = 1.25f, pathEffect = effect) + drawLine(lineColor, topRight, topLeft, strokeWidth = 1.25f, pathEffect = effect) + drawLine(lineColor, topLeft, bottomLeft, strokeWidth = 1.25f, pathEffect = effect) + for (handle in BoundsHandle.entries) { + val (worldX, worldY) = bounds.handleWorld(handle) + val center = worldToScreen(worldX, worldY, camera, size) + drawRect( + color = handleFill, + topLeft = Offset(center.x - HANDLE_HALF_PX, center.y - HANDLE_HALF_PX), + size = androidx.compose.ui.geometry.Size(HANDLE_HALF_PX * 2f, HANDLE_HALF_PX * 2f), + ) + drawRect( + color = handleStroke, + topLeft = Offset(center.x - HANDLE_HALF_PX, center.y - HANDLE_HALF_PX), + size = androidx.compose.ui.geometry.Size(HANDLE_HALF_PX * 2f, HANDLE_HALF_PX * 2f), + style = Stroke(width = 1f), + ) + } +} + +/** + * The free-transform handle under [screenPos], or null when the pointer is outside every handle's hit + * radius. Nearest handle wins when handles overlap (degenerate / tiny boxes). + * + * @param Offset screenPos Pointer in overlay pixels. + * @param AxisAlignedBounds bounds World-space selection bounds. + * @param ViewportCamera camera Projection. + * @param IntSize size Overlay size. + * @return BoundsHandle? The hit handle, or null. + */ +internal fun hitFreeTransformHandle( + screenPos: Offset, + bounds: AxisAlignedBounds, + camera: ViewportCamera, + size: IntSize, +): BoundsHandle? { + var best: BoundsHandle? = null + var bestDistance = FREE_TRANSFORM_HANDLE_HIT_PX + for (handle in BoundsHandle.entries) { + val (worldX, worldY) = bounds.handleWorld(handle) + val screen = worldToScreen(worldX, worldY, camera, size) + val distance = hypot(screen.x - screenPos.x, screen.y - screenPos.y) + if (distance <= bestDistance) { + bestDistance = distance + best = handle + } + } + return best +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/GizmoChrome.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/GizmoChrome.kt new file mode 100644 index 0000000..b2d90b0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/GizmoChrome.kt @@ -0,0 +1,193 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.DraftEndpoint +import org.umamo.edit.TransformAxisConstraint +import org.umamo.render.ViewportCamera +import org.umamo.render.WorldAxisColors +import org.umamo.ui.theme.SelectionOverlayStyle +import org.umamo.ui.theme.UmamoCursor +import org.umamo.ui.theme.drawCrosshairGuides +import org.umamo.ui.theme.drawCursor +import org.umamo.ui.theme.drawSelectionCircle + +// The shared gizmo chrome: the draw helpers and constants all three gizmo overlays (Edit, Object, and +// UV) render identically. Everything here is geometry-source agnostic: it takes screen-space points +// and the shared affordance style, never a session or a mesh. + +/** A primary drag shorter than this (px) is treated as a click, not a box select. */ +internal const val SELECT_DRAG_THRESHOLD_PX = 3f + +// The modal HUD's pivot-to-pointer dash pattern (on, off). +private val MODAL_DASH_ON = 6.dp +private val MODAL_DASH_OFF = 4.dp + +// The axis-lock guide colors, constructed from the world axes' own palette (WorldAxisColors.Classic) +// so the guide can never drift from the axis lines it mirrors. +private val AXIS_LOCK_X_COLOR = + Color(WorldAxisColors.Classic.xRed, WorldAxisColors.Classic.xGreen, WorldAxisColors.Classic.xBlue) +private val AXIS_LOCK_Z_COLOR = + Color(WorldAxisColors.Classic.zRed, WorldAxisColors.Classic.zGreen, WorldAxisColors.Classic.zBlue) + +/** + * Draws the modal axis-lock guide: a full-viewport line through the gesture anchor along the locked + * axis, in the matching world-axis color (red X / blue Z), so the constrained direction reads at a + * glance. Draws nothing when unconstrained. + * + * @param TransformAxisConstraint? constraint The active axis lock, or null. + * @param Offset anchorScreen The gesture anchor in screen pixels. + * @param Size viewport The viewport size in pixels. + */ +internal fun DrawScope.drawAxisConstraintLine(constraint: TransformAxisConstraint?, anchorScreen: Offset, viewport: Size) { + when (constraint) { + TransformAxisConstraint.AxisX -> + drawLine(color = AXIS_LOCK_X_COLOR, start = Offset(0f, anchorScreen.y), end = Offset(viewport.width, anchorScreen.y), strokeWidth = 1f) + + TransformAxisConstraint.AxisZ -> + drawLine(color = AXIS_LOCK_Z_COLOR, start = Offset(anchorScreen.x, 0f), end = Offset(anchorScreen.x, viewport.height), strokeWidth = 1f) + + null -> {} + } +} + +/** + * Draws the modal transform HUD shared by the gizmo overlays: the axis-lock guide, the pivot-to-pointer + * dash, the drawn stand-in cursor (the OS cursor is hidden while a modal operator is live), and the + * optional proportional-editing influence ring. + * + * @param TransformAxisConstraint? axisConstraint The active axis lock, or null. + * @param Offset pivotScreen The gesture pivot in screen pixels. + * @param Offset virtualPointer The wrapped virtual pointer position. + * @param Offset realPointer The real pointer position (for the drawn cursor). + * @param Size viewport The viewport size in pixels. + * @param Color lineColor The dash / HUD line color. + * @param UmamoCursor pointerCursor The drawn stand-in for the hidden OS cursor. + * @param Float? proportionalRadiusPx The proportional ring radius in screen px, or null when off. + */ +internal fun DrawScope.drawModalTransformHud( + axisConstraint: TransformAxisConstraint?, + pivotScreen: Offset, + virtualPointer: Offset, + realPointer: Offset, + viewport: Size, + lineColor: Color, + pointerCursor: UmamoCursor, + proportionalRadiusPx: Float? = null, +) { + drawAxisConstraintLine(axisConstraint, pivotScreen, viewport) + val dashOn = MODAL_DASH_ON.toPx() + val dashOff = MODAL_DASH_OFF.toPx() + drawLine( + color = lineColor, + start = pivotScreen, + end = virtualPointer, + strokeWidth = 1f, + pathEffect = PathEffect.dashPathEffect(floatArrayOf(dashOn, dashOff)), + ) + drawCursor(pointerCursor, realPointer) + if (proportionalRadiusPx != null && proportionalRadiusPx > 0f) { + drawCircle(color = lineColor, radius = proportionalRadiusPx, center = pivotScreen, style = Stroke(width = 1f)) + } +} + +/** + * Draws the armed select-tool affordances (Blender B / C, plus Cubism-style Add Vertex) shared by the + * gizmo overlays. The OS cursor is hidden while a select tool is armed, so the drawn one is it. + * Draws nothing with no tool armed. + * + * @param ActiveSelectTool? tool The armed select tool, or null. + * @param Offset pointer The pointer position in area-local pixels. + * @param Boolean boxDragInFlight True while a box rubber-band is being dragged (the crosshair guides + * hide during the drag - the rubber-band itself is the affordance). + * @param Size viewport The viewport size in pixels. + * @param SelectionOverlayStyle style The shared two-tone marching-ants style. + * @param UmamoCursor crosshairCursor The drawn stand-in for the hidden OS cursor. + * @param ViewportCamera? draftCamera Camera for projecting an Add Vertex draft, or null. + * @param IntSize? draftSize Area size for projecting an Add Vertex draft, or null. + * @param FloatArray? meshPositions Posed positions of the draft drawable (for Existing tip/edges), or null. + */ +internal fun DrawScope.drawSelectToolAffordances( + tool: ActiveSelectTool?, + pointer: Offset, + boxDragInFlight: Boolean, + viewport: Size, + style: SelectionOverlayStyle, + crosshairCursor: UmamoCursor, + draftCamera: ViewportCamera? = null, + draftSize: IntSize? = null, + meshPositions: FloatArray? = null, +) { + when (tool) { + is ActiveSelectTool.BoxArmed -> { + if (!boxDragInFlight) { + drawCrosshairGuides(pointer, viewport, style) + } + drawCursor(crosshairCursor, pointer) + } + + is ActiveSelectTool.Circle -> { + drawSelectionCircle(pointer, tool.radiusPx, style) + drawCursor(crosshairCursor, pointer) + } + + is ActiveSelectTool.AddVertex -> { + if (draftCamera != null && draftSize != null) { + drawAddVertexDraft(tool, pointer, style, draftCamera, draftSize, meshPositions) + } + drawCursor(crosshairCursor, pointer) + } + + null -> {} + } +} + +/** + * Draws staged Add Vertex floats, draft edges, and the tip→cursor rubber line. + */ +private fun DrawScope.drawAddVertexDraft( + tool: ActiveSelectTool.AddVertex, + pointer: Offset, + style: SelectionOverlayStyle, + camera: ViewportCamera, + size: IntSize, + meshPositions: FloatArray?, +) { + fun endpointScreen(endpoint: DraftEndpoint): Offset? = + when (endpoint) { + is DraftEndpoint.Draft -> { + val vert = tool.verts.getOrNull(endpoint.index) ?: return null + worldToScreen(vert.x, vert.y, camera, size) + } + is DraftEndpoint.Existing -> { + val positions = meshPositions ?: return null + if (endpoint.vertexIndex < 0 || endpoint.vertexIndex * 2 + 1 >= positions.size) { + return null + } + worldToScreen(positions[endpoint.vertexIndex * 2], positions[endpoint.vertexIndex * 2 + 1], camera, size) + } + } + + val dash = PathEffect.dashPathEffect(floatArrayOf(6f, 4f)) + for (edge in tool.edges) { + val start = endpointScreen(edge.a) ?: continue + val end = endpointScreen(edge.b) ?: continue + drawLine(color = style.primary, start = start, end = end, strokeWidth = 1.5f, pathEffect = dash) + } + for (vert in tool.verts) { + val screen = worldToScreen(vert.x, vert.y, camera, size) + drawCircle(color = style.primary, radius = 4f, center = screen) + drawCircle(color = style.secondary, radius = 4f, center = screen, style = Stroke(width = 1f)) + } + val tipScreen = tool.tip?.let { endpoint -> endpointScreen(endpoint) } + if (tipScreen != null) { + drawLine(color = style.primary, start = tipScreen, end = pointer, strokeWidth = 1f, pathEffect = dash) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/GizmoSelectionInput.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/GizmoSelectionInput.kt new file mode 100644 index 0000000..4fde277 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/GizmoSelectionInput.kt @@ -0,0 +1,253 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEvent +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputChange +import androidx.compose.ui.input.pointer.isCtrlPressed +import androidx.compose.ui.input.pointer.isMetaPressed +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.DraftVert +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshSelectionOps +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.parameterAlongSegment +import kotlin.math.sqrt + +/** + * The idle-state select-tool kind of an area-owned select tool, as a stable key for the + * recomposition-gated cancel backstop each overlay runs (`LaunchedEffect(selectToolKind) { marquee.cancel() }`). + * + * Keyed on the tool KIND, not the whole tool value: resizing a circle brush makes a new Circle(radius), + * which must NOT re-fire and wipe the in-flight stroke mid-paint. Updating an Add Vertex draft (new + * floats) must likewise keep kind stable so the marquee cancel does not thrash. + * + * @param ActiveSelectTool? ownedSelectTool The select tool this area owns, or null. + * @return Int A kind ordinal: 0 none, 1 armed box, 2 circle, 3 add vertex. + */ +internal fun selectToolKind(ownedSelectTool: ActiveSelectTool?): Int = + when (ownedSelectTool) { + null -> 0 + is ActiveSelectTool.BoxArmed -> 1 + is ActiveSelectTool.Circle -> 2 + is ActiveSelectTool.AddVertex -> 3 + } + +/** + * The idle mesh-element selection pointer branch shared by the Edit overlay and the UV editor: a primary + * click picks the element under the cursor per the select mode (Shift / Ctrl toggle, plain replaces), an + * empty primary drag rubber-bands a box, a sub-threshold click on empty canvas clears, and Shift+RightClick + * places the space's cursor. Only primary-driven events are consumed, so middle-drag pan and wheel zoom + * fall through to the navigation layer beneath. + * + * The one behavioral seam is [placeCursor]: the 2D viewport places its world-space cursor, the UV editor + * its texture-space one. The geometry source differs too, but that is just the caller passing its own + * projected [geometries]. Object mode is NOT a caller - its idle branch selects whole drawables with + * click-pick semantics and its own idle-box latch, the sibling machinery in [ObjectPickController]. + * + * @param PointerEvent event The full pointer event (buttons and modifiers). + * @param PointerInputChange change The event's first change (position and consumption). + * @param EditorSession session The session owning the mesh selection and the armed tool latch. + * @param List geometries The shown meshes' gizmo geometry (the hit-test domain). + * @param MarqueeSelectController marquee The box / circle machinery for the rubber-band. + * @param Boolean boxArmed True while Blender's B armed-box tool owns the pointer (always boxes, no pick). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @param Function placeCursor Places the space's cursor at a Shift+RightClick, given the world-space point. + */ +internal fun handleIdleMeshSelectionEvent( + event: PointerEvent, + change: PointerInputChange, + session: EditorSession, + geometries: List, + marquee: MarqueeSelectController, + boxArmed: Boolean, + camera: ViewportCamera, + size: IntSize, + placeCursor: (Float, Float) -> Unit, +) { + when (event.type) { + PointerEventType.Press -> + if (event.buttons.isSecondaryPressed && event.keyboardModifiers.isShiftPressed) { + // Shift+RightClick places the space's cursor at the pointer (Blender's gesture); the Cursor + // pivot mode and the snap / mirror commands anchor on it. + val (worldX, worldZ) = screenToWorld(change.position.x, change.position.y, camera, size) + placeCursor(worldX, worldZ) + change.consume() + } else if (boxArmed && event.buttons.isSecondaryPressed) { + session.clearSelectTool() + change.consume() + } else if (event.buttons.isPrimaryPressed) { + val current = session.meshSelection.value + val hit = hitTestMeshes(current.selectMode, geometries, change.position, camera, size) + // Armed Box-select ignores the hit and always boxes (Blender's B), so a press on an element + // still starts a box rather than selecting it. + if (!boxArmed && hit != null) { + val modifiers = event.keyboardModifiers + val updated = + when { + // Shift and Ctrl both toggle membership (Blender-style): a second modified click on + // a selected element deselects it. + modifiers.isShiftPressed || modifiers.isCtrlPressed || modifiers.isMetaPressed -> + MeshSelectionOps.toggle(current, hit.drawableId, hit.element) + else -> MeshSelectionOps.replace(current, hit.drawableId, hit.element) + } + session.setMeshSelection(updated) + } else { + marquee.beginBox(change.position) + } + change.consume() + } + + PointerEventType.Move -> + if (marquee.dragBox(change.position)) { + change.consume() + } + + PointerEventType.Release -> { + val boxRelease = marquee.releaseBox(change.position, event.keyboardModifiers.isShiftPressed, camera, size) + if (boxRelease != BoxRelease.None) { + if (boxRelease == BoxRelease.Click && !boxArmed && !session.meshSelection.value.isEmpty) { + // A sub-threshold click clears the selection - but not while armed, where a bare click just + // disarms the tool (below) rather than wiping the selection. + session.setMeshSelection(MeshSelectionOps.clear(session.meshSelection.value)) + } + // Armed Box-select is one-shot: disarm after the drag (or a bare click). + if (boxArmed) { + session.clearSelectTool() + } + change.consume() + } + } + + else -> {} + } +} + +/** + * The armed Add Vertex draft pointer branch: LMB stages a floating vert (or retargets onto an existing + * mesh vert) with Cubism-style auto-edges; RMB on a draft vert deletes it; RMB on an existing mesh vert + * deletes that vert from the mesh; RMB elsewhere cancels the tool. Staged floats stay document-untouched + * until Enter accepts. + * + * @param PointerEvent event The full pointer event (buttons and modifiers). + * @param PointerInputChange change The event's first change (position and consumption). + * @param EditorSession session The session owning the mesh and the armed tool latch. + * @param ActiveSelectTool.AddVertex tool The armed Add Vertex draft. + * @param List geometries The shown meshes' gizmo geometry (the hit-test domain). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ +internal fun handleAddVertexToolEvent( + event: PointerEvent, + change: PointerInputChange, + session: EditorSession, + tool: ActiveSelectTool.AddVertex, + geometries: List, + camera: ViewportCamera, + size: IntSize, +) { + if (event.type != PointerEventType.Press) { + return + } + if (event.buttons.isSecondaryPressed) { + val draftHit = hitTestDraftVert(tool.verts, change.position, camera, size) + if (draftHit != null) { + session.deleteAddVertexDraftVert(draftHit) + } else { + val geometry = geometries.firstOrNull { candidate -> candidate.drawableId == tool.drawableId } + val vertexHit = + geometry?.let { mesh -> + hitTestMeshes(MeshSelectMode.Vertex, listOf(mesh), change.position, camera, size) + } + if (vertexHit != null) { + val vertex = vertexHit.element as MeshElement.Vertex + session.deleteAddVertexExistingVert(vertex.index) + } else { + session.clearSelectTool() + } + } + change.consume() + return + } + if (!event.buttons.isPrimaryPressed) { + return + } + val geometry = geometries.firstOrNull { candidate -> candidate.drawableId == tool.drawableId } + if (geometry == null) { + change.consume() + return + } + val (worldX, worldY) = screenToWorld(change.position.x, change.position.y, camera, size) + // Prefer staged draft verts so click-back on the first float closes the loop (Cubism Add Vertex). + // Draft coords stay in this area's world / draw space so floats sit under the cursor; Accept maps + // viewport world → mesh-base via [EditorSession.addVertexWorldToBase]. + val draftHit = hitTestDraftVert(tool.verts, change.position, camera, size) + if (draftHit != null) { + session.addVertexDraftClick(worldX, worldY, draftVertIndex = draftHit) + change.consume() + return + } + val vertexHit = hitTestMeshes(MeshSelectMode.Vertex, listOf(geometry), change.position, camera, size) + if (vertexHit != null) { + val vertex = vertexHit.element as MeshElement.Vertex + session.addVertexDraftClick(worldX, worldY, existingVertexIndex = vertex.index) + change.consume() + return + } + val edgeHit = hitTestMeshes(MeshSelectMode.Edge, listOf(geometry), change.position, camera, size) + if (edgeHit != null) { + val edge = edgeHit.element as MeshElement.Edge + val t = + parameterAlongSegment( + worldX, + worldY, + geometry.positions[edge.endpointLow * 2], + geometry.positions[edge.endpointLow * 2 + 1], + geometry.positions[edge.endpointHigh * 2], + geometry.positions[edge.endpointHigh * 2 + 1], + ) + session.addVertexDraftClick(worldX, worldY, snapEdge = edge, snapT = t) + change.consume() + return + } + session.addVertexDraftClick(worldX, worldY) + change.consume() +} + +/** + * The draft vert under [pointer] within [HIT_RADIUS_PX], or null. + * + * @param List verts The staged floating verts. + * @param Offset pointer Screen position. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size. + * @return Int? The draft vert index, or null. + */ +internal fun hitTestDraftVert( + verts: List, + pointer: Offset, + camera: ViewportCamera, + size: IntSize, +): Int? { + var best = -1 + var bestDistance = HIT_RADIUS_PX + for ((index, vert) in verts.withIndex()) { + val screen = worldToScreen(vert.x, vert.y, camera, size) + val dx = screen.x - pointer.x + val dy = screen.y - pointer.y + val distance = sqrt(dx * dx + dy * dy) + if (distance <= bestDistance) { + bestDistance = distance + best = index + } + } + return if (best >= 0) best else null +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/HudOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/HudOverlay.kt new file mode 100644 index 0000000..4e516c5 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/HudOverlay.kt @@ -0,0 +1,360 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.ProportionalEditState +import org.umamo.edit.ProportionalFalloff +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TransformAxisConstraint +import org.umamo.render.ViewportCamera +import org.umamo.runtime.model.partNameByDrawable +import org.umamo.ui.kit.Text +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.workspace.LocalOperationStripInset +import kotlin.math.roundToInt + +/** + * The viewport HUD layer: informational chrome drawn over every other overlay - the modal-operator + * status badge (operator name plus the axis lock), the top-left active-mesh info chip, and the + * bottom-left zoom readout. Draw-only - it installs no pointer input, so it can sit topmost without + * stealing gestures from the gizmo overlays. The 2D cursor is a control marker, not HUD chrome, and + * draws in its own sibling overlay (Cursor2dOverlay.kt); near-cursor notices live at the shell level + * (ShellCursorOverlays.kt), where one instance escapes area bounds and follows the pointer across + * areas without duplicating. + * + * The zoom readout reads the LIVE [liveCamera]: the wheel updates it immediately, where the frame + * camera lags the raster by a few frames. Only the INITIATING area shows the badge: the operator + * latch names its area, so the gate is reactive. + * + * @param String areaId This viewport's area id (gates the badge to the initiating area). + * @param EditorSession session The session whose operator state and selections this HUD surfaces. + * @param ViewportCamera? liveCamera The area's live service camera feeding the zoom readout; null before the first fit. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +fun ViewportHudOverlay( + areaId: String, + session: EditorSession, + liveCamera: ViewportCamera?, + modifier: Modifier = Modifier, +) { + val meshOperator by session.activeMeshOperator.collectAsState() + val objectOperator by session.activeObjectOperator.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val proportionalEdit by session.proportionalEdit.collectAsState() + + // The modal status badge (top center): only the INITIATING area shows it - the latch itself names + // the area, so the gate is reactive. The proportional segment rides only for the operators that + // weight it: Edit-mode G / S / R (mesh operators), never Vertex Slide (single-vertex, + // positions-only), a suppressed latch (the duplicate / rip auto-grab), or object-mode transforms. + val liveOperator = meshOperator ?: objectOperator + if (liveOperator != null && liveOperator.areaId == areaId) { + val proportionalState = proportionalEdit + val liveMeshOperator = meshOperator + val showProportional = + proportionalState != null && + liveMeshOperator != null && + liveMeshOperator.kind != MeshOperatorKind.VertexSlide && + !session.activeMeshOperatorSuppressesProportional + ModalOperatorBadge( + operatorKind = liveOperator.kind, + axisConstraint = axisConstraint, + proportionalState = if (showProportional) proportionalState else null, + proportionalRadius = if (showProportional) proportionalState.radiusWorld.roundToInt() else null, + modifier = modifier, + ) + } + + // The area-wide info chips: the top-left active-mesh label and the bottom-left zoom readout. The + // UV editor gets the same chips through its own assembly, UvHudOverlay below. + ActiveMeshInfoLabel(session = session, modifier = modifier) + ViewportZoomBadge(camera = liveCamera, modifier = modifier) +} + +/** + * The UV editor's HUD layer, the sibling assembly of [ViewportHudOverlay]: the modal-operator status + * badge (gated on the UV operator latch), the top-left active-mesh info chip, and the bottom-left zoom + * readout. Informational chrome only - the UV cursor and every transform affordance are gesture + * controls and stay in UvEditGizmoOverlay. Draw-only: it installs no pointer input, so the host mounts it + * last and nothing below loses a gesture. + * + * The badge's proportional segment reads the UV editor's display-unit (texel) radius, not the + * session's world radius - the host owns that state and the gizmo overlay's gesture machinery writes + * it, so it is passed in rather than collected here. + * + * @param String areaId This UV editor's area id (gates the badge to the initiating area). + * @param EditorSession session The session whose operator state and selections this HUD surfaces. + * @param ViewportCamera? liveCamera The area's live service camera feeding the zoom readout; null before the first fit. + * @param Float? proportionalRadiusDisplay The proportional influence radius in display (texel) units, or null when unseeded. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +internal fun UvHudOverlay( + areaId: String, + session: EditorSession, + liveCamera: ViewportCamera?, + proportionalRadiusDisplay: Float?, + placementDragStatus: PlacementDragStatus?, + modifier: Modifier = Modifier, +) { + val uvOperator by session.activeUvOperator.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val proportionalEdit by session.proportionalEdit.collectAsState() + // The modal status badge (top center): only the INITIATING area shows it - the latch itself names + // the area, so the gate is reactive. An Object-mode latch is a placement gesture: the badge says + // so and carries the host-owned drag readout (the snapped delta, angle, or factor, and any overlap + // or off-page warning), since the Object overlay that computes it is a sibling and can only reach + // this chrome through the host. + val badgeOperator = uvOperator?.takeIf { operator -> operator.areaId == areaId } + if (badgeOperator != null) { + val badgeRadius = if (proportionalEdit != null && placementDragStatus == null) proportionalRadiusDisplay?.roundToInt() else null + ModalOperatorBadge( + operatorKind = badgeOperator.kind, + axisConstraint = axisConstraint, + proportionalState = if (badgeRadius != null) proportionalEdit else null, + proportionalRadius = badgeRadius, + detail = placementDragStatus?.let { status -> placementBadgeDetail(status) } ?: "", + modifier = modifier, + ) + } + ActiveMeshInfoLabel(session = session, modifier = modifier) + ViewportZoomBadge(camera = liveCamera, modifier = modifier) +} + +/** How wide each active-mesh info row may get before it ellipsizes, so one long name cannot cover the art. */ +private val ACTIVE_MESH_INFO_MAX_WIDTH = 260.dp + +/** + * The top-left active-mesh info chip shared by the 2D viewport and the UV editor: which drawable + * element clicks and operators land on. Row 1 is "Part | Drawable" (the part omitted, pipe and all, + * for a drawable no part owns); row 2 is the innermost parent deformer's name (the row omitted for an + * undeformed drawable). Edit mode annotates the edit-target mesh; Object mode the object selection's + * active drawable; with neither resolved the chip renders nothing, so the hosts need no gate of their + * own. Every name is user data, rendered verbatim (never localized) and capped at + * [ACTIVE_MESH_INFO_MAX_WIDTH] with an ellipsis - draw-only per the HUD contract, so no tooltip + * carries the full name. + * + * @param EditorSession session The session whose mode, selections, and model resolve the active mesh. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +private fun ActiveMeshInfoLabel( + session: EditorSession, + modifier: Modifier = Modifier, +) { + val editorMode by session.mode.collectAsState() + val meshSelection by session.meshSelection.collectAsState() + val objectSelection by session.selection.collectAsState() + val model by session.model.collectAsState() + // Both lookups walk the whole model, so they are remembered per model instance - above the + // resolution null-gates, so a selection change that toggles the chip never recomputes them. + val partNameOfDrawable = remember(model) { model.partNameByDrawable() } + val deformerNameById = remember(model) { model.deformers.associate { deformer -> deformer.id to deformer.name } } + val activeDrawableId = + when (editorMode) { + EditorMode.Edit -> meshSelection.activeDrawableId + EditorMode.Object -> (objectSelection.active as? SelectionTarget.Drawable)?.id + } ?: return + val activeDrawable = model.drawables.firstOrNull { drawable -> drawable.id == activeDrawableId } ?: return + val partName = partNameOfDrawable[activeDrawable.id] + val meshRow = if (partName != null) "$partName | ${activeDrawable.name}" else activeDrawable.name + val deformerName = activeDrawable.parentDeformerId?.let { deformerId -> deformerNameById[deformerId] } + val hudColors = LocalUmamoColors.current + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.TopStart) { + // One chip holding both rows (never two chips): one background reads as one fact about one mesh. + Column( + modifier = + Modifier + .padding(8.dp) + .background(hudColors.viewportBadgeBackground, RoundedCornerShape(4.dp)) + .padding(horizontal = 8.dp, vertical = 3.dp), + ) { + Text( + text = meshRow, + style = LocalUmamoTypography.current.labelMedium, + color = hudColors.viewportBadgeText, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = ACTIVE_MESH_INFO_MAX_WIDTH), + ) + if (deformerName != null) { + Text( + text = deformerName, + style = LocalUmamoTypography.current.labelSmall, + color = hudColors.viewportBadgeText, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = ACTIVE_MESH_INFO_MAX_WIDTH), + ) + } + } + } +} + +/** + * The bottom-left zoom readout shared by the 2D viewport and the UV editor. Reads the LIVE service + * camera, never the displayed frame's - the raster lands a few frames behind the wheel, and a readout + * lagging the gesture reads as broken. Renders nothing until the area's first fit publishes a camera. + * + * @param ViewportCamera? camera The area's live service camera, or null before the first fit. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +private fun ViewportZoomBadge( + camera: ViewportCamera?, + modifier: Modifier = Modifier, +) { + if (camera == null) { + return + } + val hudColors = LocalUmamoColors.current + // The operation settings strip owns the bottom-left while it shows; the badge lifts above it. + val stripInset = LocalOperationStripInset.current + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.BottomStart) { + Text( + text = "${(camera.zoom * 100f).roundToInt()}%", + color = hudColors.viewportBadgeText, + style = LocalUmamoTypography.current.labelSmall, + modifier = + Modifier + .padding(start = 8.dp, top = 8.dp, end = 8.dp, bottom = 8.dp + stripInset) + .background(hudColors.viewportBadgeBackground, RoundedCornerShape(4.dp)) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + } +} + +/** + * The modal status badge (top center): the operator's name, the axis lock, and optionally the + * proportional-editing segment - so the gesture's state reads without glancing at the status bar. + * Shared by the two HUD assemblies, [ViewportHudOverlay] and [UvHudOverlay]; the assembly decides + * whether the proportional segment applies and in which units the radius reads (world px in the + * viewport, texels in UV). + * + * @param MeshOperatorKind operatorKind The live operator. + * @param TransformAxisConstraint? axisConstraint The axis lock, or null when unconstrained. + * @param ProportionalEditState? proportionalState The proportional segment's state, or null to hide it. + * @param Int? proportionalRadius The rounded influence radius in the caller's units, or null to hide. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +private fun ModalOperatorBadge( + operatorKind: MeshOperatorKind, + axisConstraint: TransformAxisConstraint?, + proportionalState: ProportionalEditState?, + proportionalRadius: Int?, + detail: String = "", + modifier: Modifier = Modifier, +) { + val hudColors = LocalUmamoColors.current + val operatorLabel = + when (operatorKind) { + MeshOperatorKind.Grab -> stringResource(Res.string.status_bind_grab) + MeshOperatorKind.Scale -> stringResource(Res.string.status_bind_scale) + MeshOperatorKind.Rotate -> stringResource(Res.string.status_bind_rotate) + MeshOperatorKind.VertexSlide -> stringResource(Res.string.cmd_mesh_vertex_slide) + } + val axisSuffix = + when (axisConstraint) { + TransformAxisConstraint.AxisX -> " ${stringResource(Res.string.hud_along_x)}" + TransformAxisConstraint.AxisZ -> " ${stringResource(Res.string.hud_along_z)}" + null -> "" + } + val proportionalSuffix = + if (proportionalState != null && proportionalRadius != null) { + val connectedSuffix = if (proportionalState.connectedOnly) " ${stringResource(Res.string.hud_connected)}" else "" + " ${stringResource(Res.string.hud_proportional, falloffLabel(proportionalState.falloff), proportionalRadius)}$connectedSuffix" + } else { + "" + } + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) { + Text( + text = operatorLabel + axisSuffix + proportionalSuffix + detail, + style = LocalUmamoTypography.current.labelMedium, + color = hudColors.viewportBadgeText, + modifier = + Modifier + .padding(top = 8.dp) + .background(hudColors.viewportBadgeBackground, RoundedCornerShape(4.dp)) + .padding(horizontal = 8.dp, vertical = 3.dp), + ) + } +} + +/** + * The localized short name of a proportional falloff curve, for the modal status badge and the header's + * falloff dropdown (the palette commands carry their own longer titles). + * + * @param ProportionalFalloff falloff The falloff curve. + * @return String The localized falloff name. + */ +@Composable +internal fun falloffLabel(falloff: ProportionalFalloff): String = + when (falloff) { + ProportionalFalloff.Smooth -> stringResource(Res.string.falloff_smooth) + ProportionalFalloff.Sphere -> stringResource(Res.string.falloff_sphere) + ProportionalFalloff.Root -> stringResource(Res.string.falloff_root) + ProportionalFalloff.Sharp -> stringResource(Res.string.falloff_sharp) + ProportionalFalloff.Linear -> stringResource(Res.string.falloff_linear) + ProportionalFalloff.Constant -> stringResource(Res.string.falloff_constant) + } + +/** + * The placement gesture's badge segment: the "Placement" tag, the snapped readout for the running + * operator (pixel delta, page-space angle, or scale factor), and the overlap / off-page warning when + * the drag currently collides. Numbers are pre-formatted here because the resource formatter takes + * plain placeholders only. + * + * @param PlacementDragStatus status The drag's live readout. + * @return String The text appended to the operator badge. + */ +@Composable +private fun placementBadgeDetail(status: PlacementDragStatus): String { + val readout = + when (status.operatorKind) { + MeshOperatorKind.Grab -> stringResource(Res.string.hud_delta_px, status.deltaX, status.deltaY) + MeshOperatorKind.Rotate -> stringResource(Res.string.hud_angle_degrees, roundedTo(status.angleDegrees, 10)) + MeshOperatorKind.Scale -> + if (status.factorX == status.factorY) { + stringResource(Res.string.hud_scale_factor, roundedTo(status.factorX, 1000)) + } else { + stringResource(Res.string.hud_scale_factor, "${roundedTo(status.factorX, 1000)}, ${roundedTo(status.factorY, 1000)}") + } + MeshOperatorKind.VertexSlide -> "" + } + val warning = + when { + status.overlapCount > 0 -> " ${stringResource(Res.string.hud_overlapping)}" + status.offPage -> " ${stringResource(Res.string.hud_off_page)}" + else -> "" + } + return " ${stringResource(Res.string.hud_placement)} $readout$warning" +} + +/** + * A float rounded to a fixed number of decimal steps, rendered without platform formatting. + * + * @param Float value The value. + * @param Int stepsPerUnit 10 for one decimal, 1000 for three. + * @return String The rounded value's text. + */ +private fun roundedTo(value: Float, stepsPerUnit: Int): String = ((value * stepsPerUnit).roundToInt() / stepsPerUnit.toDouble()).toString() \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ImageFraming.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ImageFraming.kt new file mode 100644 index 0000000..2f4b4a7 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ImageFraming.kt @@ -0,0 +1,214 @@ +package org.umamo.ui.viewport + +import org.umamo.render.ContentBounds +import org.umamo.render.FrameBackdrop +import org.umamo.render.ViewportCamera +import org.umamo.ui.graphics.parseHexColor +import kotlin.math.ceil +import kotlin.math.roundToInt + +/* + * What an image captured from the puppet renderer shows and at what size: Export Image's region, scale, + * and background, resolved into the camera and pixel size the renderer draws. Pure, so the framing + * rules test without a GPU; the render itself is PuppetViewportService.renderImage. + */ + +/** + * The longest edge an image capture may have, in pixels. The GPU renders any size in tiles, so this is + * a CPU-memory bound: the stitched image is width x height x 4 bytes, a gigabyte at this edge squared. + */ +const val MAX_IMAGE_EDGE = 16384 + +/** + * The part of the world an image capture frames. + */ +enum class ImageRegion { + /** Exactly what a 2D viewport area shows, at its own framing. */ + View, + + /** The document's canvas rectangle. */ + Canvas, + + /** The shown drawables' extent at the current pose, cropped tight. */ + Content, +} + +/** + * What an image capture is drawn over. + */ +enum class ImageBackground { + /** Nothing: every pixel the puppet does not cover is fully transparent. */ + Transparent, + + /** A flat color, which may itself be translucent. */ + Solid, + + /** The themed grid and world axes, as the viewport shows them. */ + Grid, +} + +/** + * The Export Image dialog's choices. + * + * @property ImageRegion region The part of the world to frame. + * @property Float scalePercent The size relative to the region's own: the area's pixels for View, + * one pixel per world unit for Canvas and Content. 100 is 1:1. + * @property ImageBackground background What the puppet is drawn over. + * @property String solidColorHex The Solid background's color as canonical "#AARRGGBB", kept while + * another background is chosen so switching back finds it again. + */ +data class ImageExportOptions( + val region: ImageRegion, + val scalePercent: Float, + val background: ImageBackground, + val solidColorHex: String, +) { + companion object { + /** A transparent, tightly cropped capture of the posed puppet at 1:1: the image most often wanted. */ + val Default: ImageExportOptions = ImageExportOptions(ImageRegion.Content, 100f, ImageBackground.Transparent, "#FFFFFFFF") + } +} + +/** + * The renderer backdrop these options draw over. A Solid color is premultiplied here, since the + * renderer's framebuffer is; an unparseable color falls back to opaque white. + * + * @return FrameBackdrop The backdrop. + */ +fun ImageExportOptions.frameBackdrop(): FrameBackdrop = + when (background) { + ImageBackground.Transparent -> FrameBackdrop.Transparent + ImageBackground.Grid -> FrameBackdrop.Grid + ImageBackground.Solid -> { + val color = parseHexColor(solidColorHex) + if (color == null) { + FrameBackdrop.Clear(1f, 1f, 1f, 1f) + } else { + FrameBackdrop.Clear(color.red * color.alpha, color.green * color.alpha, color.blue * color.alpha, color.alpha) + } + } + } + +/** + * A resolved capture: the camera the renderer draws through and the image's size. + * + * @property ViewportCamera camera The world point at the image's center, and output pixels per world unit. + * @property Int width The image width in pixels. + * @property Int height The image height in pixels. + */ +data class ImageFrame( + val camera: ViewportCamera, + val width: Int, + val height: Int, +) + +/** + * The outcome of framing a capture: the frame, or why there is none. + */ +sealed interface ImageFrameResult { + /** + * The capture can be drawn. + * + * @property ImageFrame frame The frame to draw. + */ + data class Framed(val frame: ImageFrame) : ImageFrameResult + + /** View was asked for, but no 2D viewport has been touched. */ + data object NoViewport : ImageFrameResult + + /** Canvas was asked for, but the document has no canvas. */ + data object NoCanvas : ImageFrameResult + + /** Content was asked for, but nothing shown has any geometry. */ + data object NothingVisible : ImageFrameResult + + /** + * The image would pass [MAX_IMAGE_EDGE] on an edge. + * + * @property Int width The width it would have. + * @property Int height The height it would have. + */ + data class TooLarge(val width: Int, val height: Int) : ImageFrameResult +} + +/** + * Frames a capture of [region] at [scale]. + * + * View keeps the area's own center and scales its zoom and size together, so at 1 it is the area pixel for + * pixel. Canvas and Content center on their rectangle and draw [scale] pixels per world unit, rounding the + * size up to whole pixels so nothing at the rectangle's edge is cut. + * + * @param ImageRegion region The part of the world to frame. + * @param Float scale The size multiplier, above zero (1 is 1:1). + * @param ImageFrame? areaView The 2D viewport area's own frame, or null when none has been touched. + * @param ContentBounds? canvasBounds The canvas rectangle in world space, or null when there is none. + * @param ContentBounds? contentBounds The shown content's extent at the current pose, or null when none. + * @return ImageFrameResult The frame, or why there is none. + */ +fun resolveImageFrame( + region: ImageRegion, + scale: Float, + areaView: ImageFrame?, + canvasBounds: ContentBounds?, + contentBounds: ContentBounds?, +): ImageFrameResult { + require(scale > 0f) { "an image scale must be positive, got $scale" } + val frame = + when (region) { + ImageRegion.View -> { + val view = areaView ?: return ImageFrameResult.NoViewport + ImageFrame( + view.camera.copy(zoom = view.camera.zoom * scale), + (view.width * scale).roundToInt().coerceAtLeast(1), + (view.height * scale).roundToInt().coerceAtLeast(1), + ) + } + + ImageRegion.Canvas -> framedBounds(canvasBounds ?: return ImageFrameResult.NoCanvas, scale) + ImageRegion.Content -> framedBounds(contentBounds ?: return ImageFrameResult.NothingVisible, scale) + } + if (frame.width > MAX_IMAGE_EDGE || frame.height > MAX_IMAGE_EDGE) { + return ImageFrameResult.TooLarge(frame.width, frame.height) + } + return ImageFrameResult.Framed(frame) +} + +/** + * Frames [bounds] into an [edge] x [edge] square: its longer side fills the square and the shorter one is + * centered, the rest left to the backdrop. The shape UMA's saved thumbnail takes (docs/format/UMA.md § 5.6). + * + * @param ContentBounds bounds The world rectangle to fit. + * @param Int edge The square's edge in pixels, at least 1. + * @return ImageFrame The square frame. + */ +fun fitSquare(bounds: ContentBounds, edge: Int): ImageFrame { + require(edge > 0) { "a square frame needs a positive edge, got $edge" } + val zoom = edge / maxOf(bounds.width, bounds.height) + return ImageFrame(ViewportCamera(bounds.minX + bounds.width / 2f, bounds.minY + bounds.height / 2f, zoom), edge, edge) +} + +/** + * A world rectangle framed at [zoom] pixels per unit, centered, sized up to whole pixels. + * + * @param ContentBounds bounds The rectangle. + * @param Float zoom Output pixels per world unit. + * @return ImageFrame The frame. + */ +private fun framedBounds(bounds: ContentBounds, zoom: Float): ImageFrame = + ImageFrame( + ViewportCamera(bounds.minX + bounds.width / 2f, bounds.minY + bounds.height / 2f, zoom), + wholePixels(bounds.width * zoom), + wholePixels(bounds.height * zoom), + ) + +/** + * A pixel extent rounded up to whole pixels, forgiving the float noise that would otherwise turn an exact + * 2000 into 2001, and never below one pixel. + * + * @param Float extent The extent in pixels. + * @return Int The whole-pixel extent. + */ +private fun wholePixels(extent: Float): Int = ceil(extent - PIXEL_ROUNDING_SLACK).toInt().coerceAtLeast(1) + +/** How far past a whole pixel an extent may be and still count as that whole pixel. */ +private const val PIXEL_ROUNDING_SLACK = 1e-3f \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/LiveParams.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/LiveParams.kt new file mode 100644 index 0000000..afbd345 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/LiveParams.kt @@ -0,0 +1,122 @@ +package org.umamo.ui.viewport + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf +import org.umamo.edit.EditorSession +import org.umamo.edit.ParameterChange +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.model.LiveParamsHandle +import kotlin.concurrent.Volatile + +/** + * Thread-safe hand-off of parameter values from the Compose UI thread to the render thread. The + * value is an immutable map swapped wholesale, so a volatile reference is a safe publish; the render + * thread compares identity to detect a change. + */ +class LiveParams( + initialValues: Map, + initialChannelOverrides: Map = emptyMap(), +) { + @Volatile + private var publishedValues: Map = initialValues + + /** + * A Compose-snapshot mirror of the pose, so UI that DISPLAYS it (the keyform sheet's playhead) sees it + * move. The volatile stays the render thread's read: the renderer must never take a Compose + * dependency, and a per-frame snapshot read on the GL thread would be one. + */ + private val observedValues: MutableState> = mutableStateOf(initialValues) + + /** The current pose. Every write also publishes to the snapshot mirror behind [observed]. */ + var values: Map + get() = publishedValues + set(value) { + publishedValues = value + observedValues.value = value + } + + /** The same pose, read as Compose state - a read inside a composition recomposes when it moves. */ + val observed: Map get() = observedValues.value + + /** + * Pending unkeyed channel edits, published the same way as [values]. + * + * These are session state rather than document state, so they cannot ride the model to the renderer - + * they travel beside the pose, exactly as the pose itself travels beside the model. + */ + @Volatile + var channelOverrides: Map = initialChannelOverrides +} + +/** + * Builds the initial [LiveParams] from each parameter's default. Hosts with a headless-dump flow + * (the desktop `UMAMO_DUMP_PARAMS` override) rewrite the values afterwards — environment reads are a + * desktop dev affordance, not common code. + * + * A pose the document was saved with lays over the defaults (docs/format/UMA.md § 7.4), each value clamped to its + * parameter's range - a range can have been narrowed since the pose was saved - and an id the rig does not have + * simply never matches. The session takes these values as its initial pose, so the panel, the viewport, and the + * first undo snapshot agree from frame one. + * + * @param PuppetModel puppet The rig (for parameter defaults and ranges). + * @param Map savedPose The pose the document was saved with, by parameter id; empty for a plain open. + * @return LiveParams The starting parameter values. + */ +fun initialLiveParams(puppet: PuppetModel, savedPose: Map = emptyMap()): LiveParams = + LiveParams( + puppet.parameters.associate { parameter -> + parameter.id to (savedPose[parameter.id]?.coerceIn(minOf(parameter.min, parameter.max), maxOf(parameter.min, parameter.max)) ?: parameter.default) + }, + ) + +/** + * Adapts the [LiveParams] volatile hand-off to the platform-neutral [LiveParamsHandle] the common + * Parameters panel writes through. [preview] publishes a new immutable map (a volatile write) so the + * render thread's reference compare detects the change and re-poses — the fast per-frame scrub path, + * which does not touch undo. [commit] routes the gesture's final pose through the [EditorSession] as one + * undo step, so a whole drag is undoable in a single Ctrl+Z; the session's pose StateFlow is then mirrored + * back into this same volatile by the host, so an undo / redo re-poses the viewport. + * + * @property LiveParams liveParams The underlying render-thread hand-off (the live pose mirror). + * @property EditorSession session The session that records the committed pose as an undo step. + */ +class LiveParamsAdapter(private val liveParams: LiveParams, private val session: EditorSession) : LiveParamsHandle { + override val values: Map get() = liveParams.values + + override val observedValues: Map get() = liveParams.observed + + /** + * Previews one parameter's value toward the render thread without recording an undo step (the fast + * per-frame scrub path). + * + * Moving the pose RETIRES every pending unkeyed channel edit, on the first frame that actually moves + * rather than at the gesture's end. A pending value was chosen for one pose; carrying it across a scrub + * would apply it at every pose on the way, showing a half-typed opacity as a flat override across the + * whole range being scrubbed until release finally snapped it back to the track. The session's own + * commit already clears them on a pose move - this is the same rule applied to the preview path, which + * does not go through commit. + * + * @param ParameterId id The parameter to set. + * @param Float value The new value. + */ + override fun preview(id: ParameterId, value: Float) { + val current = liveParams.values + if (current[id] == value) { + return + } + liveParams.values = current + (id to value) + session.clearPendingChannelEdits() + } + + /** + * Records the current live pose as one undo step, ending a scrub gesture. + * + * @param Set changedIds The parameters this gesture moved (for the history-panel label). + */ + override fun commit(changedIds: Set) { + session.commitPose(ParameterChange.SetValue(changedIds.toList()), liveParams.values) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MarqueeSelectController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MarqueeSelectController.kt new file mode 100644 index 0000000..3467554 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MarqueeSelectController.kt @@ -0,0 +1,222 @@ +package org.umamo.ui.viewport + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEvent +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputChange +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.isTertiaryPressed +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.CIRCLE_RADIUS_STEP_PX +import org.umamo.render.ViewportCamera + +/** The outcome of releasing a box drag: nothing was in flight, a box applied, or a sub-threshold click. */ +internal enum class BoxRelease { + /** No box drag was in flight (the release belongs to something else). */ + None, + + /** The drag passed the click threshold and the box was applied. */ + Boxed, + + /** The drag stayed under the click threshold: the caller decides the click semantics. */ + Click, +} + +/** + * The marquee (box + circle) selection machinery shared by the gizmo overlays, generic over the + * stroke selection type: MeshSelection for the Edit overlay (and the future UV editor), the object + * Selection for the Object overlay. Owns the gesture state shared across the overlays - the + * in-flight circle stroke (with its erase flag) and the box rubber-band corners - plus + * the full circle event branch, the box begin / drag / release rules, and the cancel semantics + * (Blender-style: a circle stroke KEEPS what it painted and commits; a box rubber-band is abandoned + * with no selection change). The domain differences pass in as constructor callbacks. + * + * State is snapshot-backed so the overlay's draw pass observes the stroke and rubber-band live. + * + * @param Function seedStroke The committed selection a fresh stroke starts from. + * @param Function stampStroke Applies one brush stamp (working, erasing, center, radiusPx, camera, + * size) and returns the updated working selection. + * @param Function commitStroke Commits the finished stroke as one undo step. + * @param Function applyBox Applies a finished box drag (start, end, additive, camera, size). + * @param Function setCircleRadius Resizes the brush (the session clamps and remembers it). + * @param Function clearTool Leaves the armed select tool (a right-click inside the circle tool). + * @param Function onStrokeBegin Runs before the first stamp of a stroke (the Object overlay + * snapshots its centroid cache here); defaults to nothing. + * @param Function previewStroke Publishes the live stroke after every stamp and null when the stroke + * ends (the Object overlay's GPU tint); defaults to nothing. + */ +internal class MarqueeSelectController( + private val seedStroke: () -> StrokeSelection, + private val stampStroke: (StrokeSelection, Boolean, Offset, Float, ViewportCamera, IntSize) -> StrokeSelection, + private val commitStroke: (StrokeSelection) -> Unit, + private val applyBox: (Offset, Offset, Boolean, ViewportCamera, IntSize) -> Unit, + private val setCircleRadius: (Float) -> Unit, + private val clearTool: () -> Unit, + private val onStrokeBegin: () -> Unit = {}, + private val previewStroke: (StrokeSelection?) -> Unit = {}, +) { + /** + * The live Circle-select stroke: a working selection seeded at press, painted on move, committed + * once on release (one undo step); null when no stroke is in flight. + */ + var circleStroke: StrokeSelection? by mutableStateOf(null) + private set + + // Whether the in-flight stroke erases (a middle or Shift+primary drag) rather than adds. + private var circleErasing: Boolean = false + + /** The box rubber-band's press corner in area-local pixels, or null when no drag is in flight. */ + var boxStart: Offset? by mutableStateOf(null) + private set + + /** The box rubber-band's current corner, or null when no drag is in flight. */ + var boxCurrent: Offset? by mutableStateOf(null) + private set + + /** + * Handles one pointer event of the live Circle-select tool: a primary drag paints (adds), a middle + * or Shift+primary drag erases, the stroke accumulates into the working selection committed once on + * release, the wheel resizes the brush, and a right-click leaves the tool keeping what was painted + * (Blender parity). Every event is consumed so the tool owns the pointer. + * + * @param PointerEvent event The full pointer event (buttons and modifiers). + * @param PointerInputChange change The event's first change (position and consumption). + * @param Float radiusPx The live brush radius in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ + fun handleCircleEvent(event: PointerEvent, change: PointerInputChange, radiusPx: Float, camera: ViewportCamera, size: IntSize) { + when (event.type) { + PointerEventType.Press -> + if (event.buttons.isSecondaryPressed) { + // Right-click leaves the tool; a held stroke keeps what it painted (Blender + // parity), so commit it here before clearing rather than dropping it. + endStroke() + clearTool() + } else if (event.buttons.isPrimaryPressed) { + beginStamp(event.keyboardModifiers.isShiftPressed, change.position, radiusPx, camera, size) + } else if (event.buttons.isTertiaryPressed) { + beginStamp(erasing = true, change.position, radiusPx, camera, size) + } + + PointerEventType.Move -> { + val stroke = circleStroke + if (stroke != null) { + val painted = stampStroke(stroke, circleErasing, change.position, radiusPx, camera, size) + circleStroke = painted + previewStroke(painted) + } + } + + PointerEventType.Release -> endStroke() + + PointerEventType.Scroll -> { + val steps = change.scrollDelta.y + if (steps != 0f) { + // Wheel up (negative y) grows the brush; the session clamps the radius. + setCircleRadius(radiusPx - steps * CIRCLE_RADIUS_STEP_PX) + } + } + + else -> {} + } + change.consume() + } + + /** + * Starts a box drag at [position] (both corners collapse onto the press point). + * + * @param Offset position The press position in area-local pixels. + */ + fun beginBox(position: Offset) { + boxStart = position + boxCurrent = position + } + + /** + * Advances an in-flight box drag to [position]. + * + * @param Offset position The current pointer position in area-local pixels. + * @return Boolean True when a drag was in flight (the caller consumes the event). + */ + fun dragBox(position: Offset): Boolean { + if (boxStart == null) { + return false + } + boxCurrent = position + return true + } + + /** + * Ends an in-flight box drag: past the click threshold the box applies through the callback; under + * it nothing applies and the caller decides the click semantics (clear, pick, or just disarm). + * + * @param Offset end The release position in area-local pixels. + * @param Boolean additive True to add to the current selection (Shift held). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return BoxRelease What happened: [BoxRelease.None] with no drag in flight, else Boxed or Click. + */ + fun releaseBox(end: Offset, additive: Boolean, camera: ViewportCamera, size: IntSize): BoxRelease { + val start = boxStart ?: return BoxRelease.None + boxStart = null + boxCurrent = null + return if ((end - start).getDistance() > SELECT_DRAG_THRESHOLD_PX) { + applyBox(start, end, additive, camera, size) + BoxRelease.Boxed + } else { + BoxRelease.Click + } + } + + /** + * Resolves any in-flight gesture on an exit (Escape, right-click, a tool switch, or leaving the + * mode). The two gestures exit DIFFERENTLY, Blender-style: a circle stroke KEEPS what it painted + * (its accumulated working selection commits as one undo step - the commit callback no-ops on an + * unchanged selection, so a stroke that painted nothing adds no undo step), while a box rubber-band + * is abandoned with no selection change. Only one of the two is ever live at once, so resolving + * both arms is safe. + */ + fun cancel() { + endStroke() + boxStart = null + boxCurrent = null + } + + /** + * Begins (or continues) a stroke with one stamp: snapshots via [onStrokeBegin], records the erase + * flag, stamps from the in-flight stroke or a fresh seed, and publishes the preview. + * + * @param Boolean erasing True when this stroke removes elements. + * @param Offset center The brush center in area-local pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ + private fun beginStamp(erasing: Boolean, center: Offset, radiusPx: Float, camera: ViewportCamera, size: IntSize) { + onStrokeBegin() + circleErasing = erasing + val painted = stampStroke(circleStroke ?: seedStroke(), erasing, center, radiusPx, camera, size) + circleStroke = painted + previewStroke(painted) + } + + /** + * Ends the in-flight stroke, committing its paint (one undo step) and clearing the preview; a + * no-op with no stroke live beyond resetting the erase flag and preview. + */ + private fun endStroke() { + val stroke = circleStroke + if (stroke != null) { + commitStroke(stroke) + circleStroke = null + } + circleErasing = false + previewStroke(null) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MeshGizmoGeometry.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MeshGizmoGeometry.kt new file mode 100644 index 0000000..593fe73 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MeshGizmoGeometry.kt @@ -0,0 +1,258 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.ActiveMeshElement +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshSelectionOps +import org.umamo.edit.MeshTopology +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.distanceToSegment +import org.umamo.runtime.model.DrawableId + +/** + * One mesh's geometry as the gizmo machinery sees it: positions plus topology, agnostic of WHERE the + * positions came from. The Edit overlay feeds deformer-projected world shapes; a UV editor feeds raw + * texture coordinates mapped into its own space. The shared element queries below and the wireframe + * draw take this record, so a new editor space reuses them by constructing one - never by + * re-implementing the hit / box / circle rules. + * + * @property DrawableId drawableId The drawable the mesh belongs to (the selection key). + * @property IntArray indices The triangle vertex indices (three per triangle). + * @property List edges The unique edges, in first-encounter order. + * @property FloatArray positions The interleaved (x, y) vertex positions in the hosting space's + * world units (what the area camera projects). + */ +internal class GizmoMeshGeometry( + val drawableId: DrawableId, + val indices: IntArray, + val edges: List, + val positions: FloatArray, +) + +/** + * The nearest element of the given domain under the pointer across every mesh, or null. Each mesh's + * own hit test already picks its nearest candidate; this compares the survivors across meshes by the + * same screen-space metric each domain uses (vertex distance, point-to-segment distance, face + * centroid distance), so overlapping meshes resolve to the visually closest element. + * + * @param MeshSelectMode selectMode The element domain to pick in. + * @param List geometries The meshes' gizmo geometry. + * @param Offset pointer The cursor in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return ActiveMeshElement? The hit element with its mesh, or null. + */ +internal fun hitTestMeshes( + selectMode: MeshSelectMode, + geometries: List, + pointer: Offset, + camera: ViewportCamera, + size: IntSize, +): ActiveMeshElement? { + var best: ActiveMeshElement? = null + var bestMetric = Float.MAX_VALUE + for (geometry in geometries) { + when (selectMode) { + MeshSelectMode.Vertex -> { + val vertexIndex = hitTestVertex(geometry.positions, pointer, camera, size) ?: continue + val screen = worldToScreen(geometry.positions[vertexIndex * 2], geometry.positions[vertexIndex * 2 + 1], camera, size) + val metric = (screen - pointer).getDistance() + if (metric < bestMetric) { + bestMetric = metric + best = ActiveMeshElement(geometry.drawableId, MeshElement.Vertex(vertexIndex)) + } + } + + MeshSelectMode.Edge -> { + val edge = hitTestEdge(geometry.positions, geometry.edges, pointer, camera, size) ?: continue + val start = worldToScreen(geometry.positions[edge.endpointLow * 2], geometry.positions[edge.endpointLow * 2 + 1], camera, size) + val end = worldToScreen(geometry.positions[edge.endpointHigh * 2], geometry.positions[edge.endpointHigh * 2 + 1], camera, size) + val metric = distanceToSegment(pointer.x, pointer.y, start.x, start.y, end.x, end.y) + if (metric < bestMetric) { + bestMetric = metric + best = ActiveMeshElement(geometry.drawableId, edge) + } + } + + MeshSelectMode.Face -> { + val face = hitTestFace(geometry.positions, geometry.indices, pointer, camera, size) ?: continue + val cornerA = geometry.indices[face.triangleIndex * 3] + val cornerB = geometry.indices[face.triangleIndex * 3 + 1] + val cornerC = geometry.indices[face.triangleIndex * 3 + 2] + val screenA = worldToScreen(geometry.positions[cornerA * 2], geometry.positions[cornerA * 2 + 1], camera, size) + val screenB = worldToScreen(geometry.positions[cornerB * 2], geometry.positions[cornerB * 2 + 1], camera, size) + val screenC = worldToScreen(geometry.positions[cornerC * 2], geometry.positions[cornerC * 2 + 1], camera, size) + val centroid = Offset((screenA.x + screenB.x + screenC.x) / 3f, (screenA.y + screenB.y + screenC.y) / 3f) + val metric = (centroid - pointer).getDistance() + if (metric < bestMetric) { + bestMetric = metric + best = ActiveMeshElement(geometry.drawableId, face) + } + } + } + } + return best +} + +/** + * The elements of one mesh enclosed by a rubber-band box, in the given domain (vertex inside, edge + * both-endpoints, face centroid - the shared Blender rules). + * + * @param MeshSelectMode selectMode The element domain to enclose. + * @param GizmoMeshGeometry geometry The mesh's gizmo geometry. + * @param Offset cornerA One box corner in screen pixels. + * @param Offset cornerB The opposite box corner. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The enclosed elements. + */ +internal fun elementsInBox( + selectMode: MeshSelectMode, + geometry: GizmoMeshGeometry, + cornerA: Offset, + cornerB: Offset, + camera: ViewportCamera, + size: IntSize, +): Set = + when (selectMode) { + MeshSelectMode.Vertex -> + verticesInBox(geometry.positions, cornerA, cornerB, camera, size) + .map { vertexIndex -> MeshElement.Vertex(vertexIndex) } + .toSet() + + MeshSelectMode.Edge -> edgesInBox(geometry.positions, geometry.edges, cornerA, cornerB, camera, size) + + MeshSelectMode.Face -> facesInBox(geometry.positions, geometry.indices, cornerA, cornerB, camera, size) + } + +/** + * Computes the Circle-select result for one brush stamp: enclose the elements of [working]'s select mode + * within [radiusPx] of [center] (screen space) on EVERY mesh, and either add them (a paint stroke) or + * remove them (an erase stroke). + * + * @param MeshSelection working The stroke's accumulating selection (seeded from the committed selection). + * @param Boolean erasing True to remove the enclosed elements, false to add them. + * @param Offset center The brush center in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param List geometries The meshes' gizmo geometry. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return MeshSelection The updated working selection. + */ +internal fun circleSelection( + working: MeshSelection, + erasing: Boolean, + center: Offset, + radiusPx: Float, + geometries: List, + camera: ViewportCamera, + size: IntSize, +): MeshSelection { + val insideByDrawable = + geometries.associate { geometry -> + val inside: Set = + when (working.selectMode) { + MeshSelectMode.Vertex -> + verticesInCircle(geometry.positions, center, radiusPx, camera, size) + .map { vertexIndex -> MeshElement.Vertex(vertexIndex) } + .toSet() + + MeshSelectMode.Edge -> edgesInCircle(geometry.positions, geometry.edges, center, radiusPx, camera, size) + + MeshSelectMode.Face -> facesInCircle(geometry.positions, geometry.indices, center, radiusPx, camera, size) + } + geometry.drawableId to inside + } + return if (erasing) { + MeshSelectionOps.remove(working, insideByDrawable) + } else { + MeshSelectionOps.box(working, insideByDrawable, additive = true) + } +} + +/** + * The per-domain highlight state the wireframe draw renders: the stored selection projected onto + * vertices, edges, and faces. Only the current select mode's domain comes straight from the selection; + * the others are derived with Blender's display rules (an edge from both endpoints, a face from all of + * its own vertices or edges, a face's edges flushing down in face mode). + * + * @property Set selectedVertexIndices Vertices drawn selected (vertex mode only). + * @property Set selectedEdges Edges drawn selected (stored or derived). + * @property Set selectedFaceIndices Triangle ordinals drawn filled (stored or derived). + * @property Int? activeVertexIndex The active vertex (vertex mode), or null. + * @property MeshElement.Edge? activeEdge The active edge (edge mode), or null. + * @property Int? activeFaceIndex The active face's triangle ordinal (face mode), or null. + */ +internal class MeshHighlightSets( + val selectedVertexIndices: Set, + val selectedEdges: Set, + val selectedFaceIndices: Set, + val activeVertexIndex: Int?, + val activeEdge: MeshElement.Edge?, + val activeFaceIndex: Int?, +) + +/** + * Projects the stored selection into per-domain highlight sets for the wireframe draw, applying + * Blender's derive-up rules (vertex mode lights edges with both endpoints selected and faces with all + * vertices selected; edge mode lights faces with all three own edges selected) and flush-down display + * (face mode lights the selected faces' own edges). + * + * @param Set elements One mesh's stored elements (the current select mode's domain). + * @param MeshElement? active The active element when it lives on this mesh, or null. + * @param MeshSelectMode selectMode The current select mode. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @return MeshHighlightSets The projected highlight state for this mesh. + */ +internal fun buildHighlightSets( + elements: Set, + active: MeshElement?, + selectMode: MeshSelectMode, + triangleIndices: IntArray, +): MeshHighlightSets = + when (selectMode) { + MeshSelectMode.Vertex -> { + val vertexIndices = elements.filterIsInstance().map { it.index }.toSet() + MeshHighlightSets( + selectedVertexIndices = vertexIndices, + selectedEdges = MeshTopology.edgesWithBothEndpointsSelected(triangleIndices, vertexIndices), + selectedFaceIndices = + MeshTopology.facesWithAllVerticesSelected(triangleIndices, vertexIndices) + .map { it.triangleIndex } + .toSet(), + activeVertexIndex = (active as? MeshElement.Vertex)?.index, + activeEdge = null, + activeFaceIndex = null, + ) + } + + MeshSelectMode.Edge -> { + val selectedEdges = elements.filterIsInstance().toSet() + MeshHighlightSets( + selectedVertexIndices = emptySet(), + selectedEdges = selectedEdges, + selectedFaceIndices = + MeshTopology.facesWithAllEdgesSelected(triangleIndices, selectedEdges) + .map { it.triangleIndex } + .toSet(), + activeVertexIndex = null, + activeEdge = active as? MeshElement.Edge, + activeFaceIndex = null, + ) + } + + MeshSelectMode.Face -> { + val faceIndices = elements.filterIsInstance().map { it.triangleIndex }.toSet() + MeshHighlightSets( + selectedVertexIndices = emptySet(), + selectedEdges = faceIndices.flatMap { faceIndex -> MeshTopology.edgesOfTriangle(triangleIndices, faceIndex) }.toSet(), + selectedFaceIndices = faceIndices, + activeVertexIndex = null, + activeEdge = null, + activeFaceIndex = (active as? MeshElement.Face)?.triangleIndex, + ) + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MeshWireframeDraw.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MeshWireframeDraw.kt new file mode 100644 index 0000000..d841487 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/MeshWireframeDraw.kt @@ -0,0 +1,225 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PointMode +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshSelectMode +import org.umamo.render.ViewportCamera + +/** + * Draws one mesh's wireframe with its selection highlights - the shared gizmo mesh rendering: face + * fills first (under the wireframe), then edges, then vertex dots in vertex mode and face centroid + * dots in face mode (the click affordances, like Blender's). Geometry-source agnostic: the Edit + * overlay feeds deformer-projected world shapes, and a UV editor feeds raw texture coordinates over + * the atlas image - both through the same positions-plus-topology arguments. + * + * Every element batches by color into one path or point-set, so a mesh draws in a handful of commands + * regardless of vertex count. This matters beyond the lambda's own run cost: the window surface + * replays these recorded draw commands on every frame a sibling live viewport produces, so a per-edge + * or per-vertex command count would be re-rasterized every frame, not just on an edit. The single + * active edge, vertex, or face dot draws on its own so it layers over its batched neighbours. + * + * When [objectOverlay] is set (the UV editor's read-only Object-mode preview) the draw is the + * Blender object-overlay style regardless of [selectMode]: every face filled idle plus the edges, and + * NO click-affordance dots (neither vertex dots nor face centroid dots) - there is nothing to pick in a + * read-only preview, so the handles would only add clutter. + * + * @param FloatArray positions The interleaved (x, y) vertex positions in world units. + * @param IntArray indices The triangle vertex indices (three per triangle). + * @param List edges The unique edges to stroke. + * @param MeshHighlightSets highlight The selection highlights to render. + * @param MeshSelectMode selectMode The current select mode (gates the dot affordances and fill rules). + * @param ViewportOverlayColors colors The settings-backed overlay palette. + * @param ViewportCamera camera The area camera (world<->screen affine). + * @param IntSize size The area size in pixels. + * @param Boolean objectOverlay Draw the read-only object-overlay style (all faces filled, edges, no dots). + */ +internal fun DrawScope.drawMeshWireframe( + positions: FloatArray, + indices: IntArray, + edges: List, + highlight: MeshHighlightSets, + selectMode: MeshSelectMode, + colors: ViewportOverlayColors, + camera: ViewportCamera, + size: IntSize, + objectOverlay: Boolean = false, +) { + val vertexRadius = 3.5.dp.toPx() + val edgeWidth = 1.dp.toPx() + val faceDotRadius = 2.5.dp.toPx() + val vertexCount = positions.size / 2 + val screenPoints = + Array(vertexCount) { vertexIndex -> + worldToScreen(positions[vertexIndex * 2], positions[vertexIndex * 2 + 1], camera, size) + } + val triangleCount = indices.size / 3 + + /** + * The three screen corners of a triangle, or null when the triangle ordinal or the mesh indices + * outrun the given geometry. The highlight sets can derive from a newer mesh than the drawn one + * (right after a topology edit that appends triangles, before the async frame catches up), so they + * can name ordinals this geometry lacks; skipping self-heals next frame. + * + * @param Int triangleIndex The triangle ordinal. + * @return Triple? The three screen corners, or null when out of range. + */ + fun triangleScreenCorners(triangleIndex: Int): Triple? { + if (triangleIndex < 0 || triangleIndex * 3 + 2 >= indices.size) { + return null + } + val cornerA = indices[triangleIndex * 3] + val cornerB = indices[triangleIndex * 3 + 1] + val cornerC = indices[triangleIndex * 3 + 2] + if (cornerA >= vertexCount || cornerB >= vertexCount || cornerC >= vertexCount) { + return null + } + return Triple(screenPoints[cornerA], screenPoints[cornerB], screenPoints[cornerC]) + } + + /** + * Appends one triangle's closed outline to [target]; a no-op for an out-of-range ordinal. Disjoint + * mesh triangles never overlap, so batching many into one path and filling once matches per-face fills. + * + * @param Path target The path to append to. + * @param Int triangleIndex The triangle ordinal. + */ + fun addFace(target: Path, triangleIndex: Int) { + val corners = triangleScreenCorners(triangleIndex) ?: return + target.moveTo(corners.first.x, corners.first.y) + target.lineTo(corners.second.x, corners.second.y) + target.lineTo(corners.third.x, corners.third.y) + target.close() + } + + // Face fills first, under the wireframe. The object overlay fills every face idle (a read-only tint, + // no selection); otherwise Face mode fills every face (the face is the click target) split by + // selection, and vertex and edge modes fill only the derived-selected faces. One path per color. + val idleFaceFill = Path() + val selectedFaceFill = Path() + if (objectOverlay) { + for (triangleIndex in 0 until triangleCount) { + addFace(idleFaceFill, triangleIndex) + } + } else if (selectMode == MeshSelectMode.Face) { + for (triangleIndex in 0 until triangleCount) { + if (triangleIndex in highlight.selectedFaceIndices) { + addFace(selectedFaceFill, triangleIndex) + } else { + addFace(idleFaceFill, triangleIndex) + } + } + } else { + for (triangleIndex in highlight.selectedFaceIndices) { + addFace(selectedFaceFill, triangleIndex) + } + } + drawPath(path = idleFaceFill, color = colors.faceIdle) + drawPath(path = selectedFaceFill, color = colors.faceSelected) + + // Edges, batched by color into one path each; the single active edge draws on top of them. + val idleEdges = Path() + val selectedEdges = Path() + var activeEdgeStart: Offset? = null + var activeEdgeEnd: Offset? = null + for (edge in edges) { + if (edge.endpointLow >= vertexCount || edge.endpointHigh >= vertexCount) { + continue + } + val start = screenPoints[edge.endpointLow] + val end = screenPoints[edge.endpointHigh] + when { + edge == highlight.activeEdge -> { + activeEdgeStart = start + activeEdgeEnd = end + } + edge in highlight.selectedEdges -> { + selectedEdges.moveTo(start.x, start.y) + selectedEdges.lineTo(end.x, end.y) + } + else -> { + idleEdges.moveTo(start.x, start.y) + idleEdges.lineTo(end.x, end.y) + } + } + } + val edgeStroke = Stroke(width = edgeWidth) + drawPath(path = idleEdges, color = colors.edgeIdle, style = edgeStroke) + drawPath(path = selectedEdges, color = colors.edgeSelected, style = edgeStroke) + val resolvedActiveEdgeStart = activeEdgeStart + val resolvedActiveEdgeEnd = activeEdgeEnd + if (resolvedActiveEdgeStart != null && resolvedActiveEdgeEnd != null) { + drawLine(color = colors.edgeActive, start = resolvedActiveEdgeStart, end = resolvedActiveEdgeEnd, strokeWidth = edgeWidth) + } + + // Vertex dots only in vertex mode (Blender hides them in edge / face modes), batched by color; the + // active vertex draws on top. The read-only object overlay draws no handles at all. + if (!objectOverlay && selectMode == MeshSelectMode.Vertex) { + val idleVertices = ArrayList() + val selectedVertices = ArrayList() + for (vertexIndex in 0 until vertexCount) { + when { + vertexIndex == highlight.activeVertexIndex -> Unit + vertexIndex in highlight.selectedVertexIndices -> selectedVertices.add(screenPoints[vertexIndex]) + else -> idleVertices.add(screenPoints[vertexIndex]) + } + } + drawDots(idleVertices, colors.vertexIdle, vertexRadius) + drawDots(selectedVertices, colors.vertexSelected, vertexRadius) + val activeVertexIndex = highlight.activeVertexIndex + if (activeVertexIndex != null && activeVertexIndex < vertexCount) { + drawCircle(color = colors.vertexActive, radius = vertexRadius, center = screenPoints[activeVertexIndex]) + } + } + + // Face centroid dots only in face mode - the click affordance, like Blender's face dots. The + // alpha in the face colors is meant for fills, so dots render fully opaque. Batched by color. + // The read-only object overlay draws no handles at all. + if (!objectOverlay && selectMode == MeshSelectMode.Face) { + val idleFaceDots = ArrayList() + val selectedFaceDots = ArrayList() + var activeFaceDot: Offset? = null + for (triangleIndex in 0 until triangleCount) { + val corners = triangleScreenCorners(triangleIndex) ?: continue + val centroid = + Offset( + (corners.first.x + corners.second.x + corners.third.x) / 3f, + (corners.first.y + corners.second.y + corners.third.y) / 3f, + ) + when { + triangleIndex == highlight.activeFaceIndex -> activeFaceDot = centroid + triangleIndex in highlight.selectedFaceIndices -> selectedFaceDots.add(centroid) + else -> idleFaceDots.add(centroid) + } + } + drawDots(idleFaceDots, colors.faceIdle.copy(alpha = 1f), faceDotRadius) + drawDots(selectedFaceDots, colors.faceSelected.copy(alpha = 1f), faceDotRadius) + val resolvedActiveFaceDot = activeFaceDot + if (resolvedActiveFaceDot != null) { + drawCircle(color = colors.faceActive.copy(alpha = 1f), radius = faceDotRadius, center = resolvedActiveFaceDot) + } + } +} + +/** + * Draws a batch of same-color round dots in one drawPoints command; the round stroke cap gives each + * point the filled-circle look of an individual drawCircle of the given radius, and an empty batch is + * a no-op. + * + * @param List centers The dot centers in screen pixels. + * @param Color color The dot color. + * @param Float radius The dot radius in pixels. + */ +private fun DrawScope.drawDots(centers: List, color: Color, radius: Float) { + if (centers.isEmpty()) { + return + } + drawPoints(points = centers, pointMode = PointMode.Points, color = color, strokeWidth = radius * 2f, cap = StrokeCap.Round) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ModalGestureState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ModalGestureState.kt new file mode 100644 index 0000000..01e1935 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ModalGestureState.kt @@ -0,0 +1,85 @@ +package org.umamo.ui.viewport + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import org.umamo.edit.TransformGestureParameters +import org.umamo.runtime.model.DrawableId + +/** + * The per-area modal-gesture bookkeeping every gizmo overlay carries: the last pointer position, the frozen + * capture and its live preview, the gesture-start anchor, the area's screen origin (for cursor wrap), and + * the wrap / pointer-controller pair. The three overlays declared these as seven separate + * `remember(areaId) { mutableStateOf(...) }` locals plus the same reset boilerplate; bundling them keeps the + * begin / end lifecycle in one place and out of each overlay. + * + * State-backed fields stay observable (the draw pass and the HUD read [capture] / [preview] / [lastPointer] + * live), so the whole object is created once per area with `remember(areaId) { ModalGestureState() }` - the + * same pattern [MarqueeSelectController] uses. + * + * [TCapture] is the overlay's own capture type (each overlay holds extra per-mesh data the shared + * [org.umamo.edit.ModalTransformCapture] does not). + */ +internal class ModalGestureState { + /** The most recent pointer position in area-local pixels, tracked for the geometry-dependent effects. */ + var lastPointer by mutableStateOf(Offset.Zero) + + /** The frozen gesture capture, or null when no modal gesture is in flight. */ + var capture by mutableStateOf(null) + + /** The live preview the drive loop pushes: new positions (or UVs) per drawable, or null before the first drive. */ + var preview by mutableStateOf?>(null) + + /** The pointer position the gesture started at (the transform's origin), or null when idle. */ + var gestureStart by mutableStateOf(null) + + /** + * The parameters the most recent drive resolved from the pointer, or null before the first drive: what + * the confirm hands the operation settings strip as the rows the rigger can then edit. Plain state (no + * reader observes it), written once per pointer frame. + */ + var lastParameters: TransformGestureParameters? = null + + /** The area's top-left in absolute screen pixels, for converting a wrap target into screen space; null before first layout. */ + var areaScreenOrigin by mutableStateOf(null) + + /** The gesture's cursor-wrap bookkeeping (the virtual pointer, stale-event guard, actual-landing fold). */ + val cursorWrap = CursorWrapState() + + /** The shared pointer-side driver of the modal gesture (stale discard, drive, wrap, buttons). */ + val modalController = ModalTransformController(cursorWrap) + + /** + * Latches a fresh capture: records it, sets the gesture origin, clears any stale preview, and resets the + * cursor wrap. + * + * @param TCapture fresh The capture frozen at latch. + * @param Offset pointer The pointer position the gesture starts at. + */ + fun begin(fresh: TCapture, pointer: Offset) { + capture = fresh + gestureStart = pointer + preview = null + lastParameters = null + cursorWrap.reset() + } + + /** + * Tears the gesture down: clears the capture, preview, and origin, and resets the cursor wrap. The + * boolean return IS the resync gate every overlay's teardown repeats - true only when a gesture was + * actually in flight, so a bystander teardown (mount, another area latching) does not stomp a live + * preview. + * + * @return Boolean True when a gesture was in flight (the caller resyncs the renderer). + */ + fun end(): Boolean { + val wasActive = capture != null + capture = null + preview = null + gestureStart = null + lastParameters = null + cursorWrap.reset() + return wasActive + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ModalTransformController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ModalTransformController.kt new file mode 100644 index 0000000..629acca --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ModalTransformController.kt @@ -0,0 +1,144 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEvent +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputChange +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.EditorSession +import org.umamo.render.ViewportCamera + +/** + * The commit-side seam of a modal G / S / R gesture: what differs between the Edit overlay (per-mesh + * covered vertices folded through the deformer inverse), the Object overlay (whole drawables), and a + * future UV editor (raw texture coordinates). The pointer-side mechanics - stale-event discard, + * virtual-pointer drive, cursor wrap, confirm / cancel buttons - are identical and live in + * [ModalTransformController]; implementations supply only where the preview goes and how it commits. + */ +internal interface ModalTransformTarget { + /** + * Re-derives the live preview for the given wrap-continuous pointer and pushes it to the renderer. + * + * @param Offset virtualPointer The wrap-continuous pointer in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Boolean True when a preview was driven; false when there is nothing to drive yet (the + * gesture capture has not landed), which also skips the cursor wrap for the event. + */ + fun drivePreview(virtualPointer: Offset, camera: ViewportCamera, size: IntSize): Boolean + + /** Commits the in-flight gesture (a primary click; Enter arrives via the confirm-request bus). */ + fun confirm() + + /** Cancels the in-flight gesture (a right-click; Escape arrives via the session's operator clear). */ + fun cancel() + + /** + * Handles a modal wheel scroll. The Edit overlay resizes the proportional influence radius here; + * targets without a scroll behavior take the default no-op. + * + * @param Float steps The scroll delta in wheel steps (negative is wheel-up). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ + fun onScroll(steps: Float, camera: ViewportCamera, size: IntSize) {} +} + +/** + * Drives the pointer side of a modal transform gesture, shared by the gizmo overlays: one event + * dispatcher over a [ModalTransformTarget], wired to the gesture's [CursorWrapState]. Owning this + * here (instead of twin when-branches in every overlay) is what lets a new editor space gain the + * whole modal interaction - wrap, stale-event discard, button semantics - by implementing the target. + * + * @param CursorWrapState cursorWrap The gesture's wrap bookkeeping (also reset by the overlay's + * capture latch / teardown effect). + */ +internal class ModalTransformController( + private val cursorWrap: CursorWrapState, +) { + /** + * Feeds one pointer event of an active modal gesture to [target]: Move / Exit discard stale + * pre-warp events, drive the preview from the virtual pointer, then wrap the cursor at the + * viewport edge (Exit is handled with Move so a fast flick that clears the trigger band before its + * last in-bounds Move still wraps); a secondary press cancels, a primary press confirms; a scroll + * goes to the target. Every event is consumed - a modal gesture owns the pointer. + * + * @param PointerEvent event The full pointer event (buttons and type). + * @param PointerInputChange change The event's first change (position and consumption). + * @param ModalTransformTarget target The gesture's commit-side seam. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @param Offset? areaScreenOrigin The area's top-left in absolute screen pixels, or null before + * first layout. + * @return Offset The pointer position the overlay should record: the frozen stale landing, the + * wrap landing, or the event position. + */ + fun handleEvent( + event: PointerEvent, + change: PointerInputChange, + target: ModalTransformTarget, + camera: ViewportCamera, + size: IntSize, + areaScreenOrigin: Offset?, + ): Offset { + var pointer = change.position + when (event.type) { + PointerEventType.Move, PointerEventType.Exit -> { + // Discard stale pre-warp events, keeping the HUD anchored at the landing instead of + // flicking back to the old edge (see CursorWrapState.resolveArrival). + val staleLanding = cursorWrap.resolveArrival(change.position, size) + if (staleLanding != null) { + change.consume() + return staleLanding + } + // Drive from the virtual pointer so the transform stays continuous across wraps (what + // makes Scale / Rotate unbounded), then wrap at the viewport edge, folding the ACTUAL + // landing into the wrap offset (see CursorWrapState.maybeWrap). + if (target.drivePreview(cursorWrap.virtualPointer(change.position), camera, size)) { + val landed = cursorWrap.maybeWrap(change.position, size, areaScreenOrigin) + if (landed != null) { + pointer = landed + } + } + } + + PointerEventType.Press -> + if (event.buttons.isSecondaryPressed) { + target.cancel() + } else if (event.buttons.isPrimaryPressed) { + target.confirm() + } + + PointerEventType.Scroll -> target.onScroll(change.scrollDelta.y, camera, size) + + else -> {} + } + change.consume() + return pointer + } +} + +/** + * Collects the session's Enter-confirm requests for one overlay instance and confirms its gesture. + * Only the INITIATING area commits - every overlay instance collects this shared flow, and an + * ungated confirm would commit once per split viewport. The gate is the caller's: it checks that + * its own operator latch names this area, which is deterministic and also keeps an Edit-mode Enter + * from confirming through an idle Object overlay. + * + * @param EditorSession session The session whose confirm requests to collect. + * @param Function isGestureActiveHere True while an operator latched to this overlay's area runs. + * @param Function confirm Commits the in-flight gesture. + */ +internal suspend fun collectModalConfirmRequests( + session: EditorSession, + isGestureActiveHere: () -> Boolean, + confirm: () -> Unit, +) { + session.meshConfirmRequests.collect { + if (isGestureActiveHere()) { + confirm() + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ObjectPickController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ObjectPickController.kt new file mode 100644 index 0000000..14cd1f0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ObjectPickController.kt @@ -0,0 +1,215 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEvent +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputChange +import androidx.compose.ui.input.pointer.isAltPressed +import androidx.compose.ui.input.pointer.isCtrlPressed +import androidx.compose.ui.input.pointer.isMetaPressed +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.isTertiaryPressed +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.EditorSession +import org.umamo.edit.Selection +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.edit.selectableOf +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.DrawableId + +/** + * Resolves a primary click against the object selection: a hit with a membership modifier toggles + * (Blender-style, so a second modified click deselects), a plain hit replaces, a modified click on + * empty canvas keeps the selection, and a plain one clears it. + * + * @param Selection current The committed object selection. + * @param SelectionTarget.Drawable? target The selectable drawable under the cursor, or null on empty canvas. + * @param Boolean toggleMembership True when a membership modifier (Shift / Ctrl / Meta) is held. + * @return Selection The selection the click produces. + */ +internal fun resolveObjectClickSelection( + current: Selection, + target: SelectionTarget.Drawable?, + toggleMembership: Boolean, +): Selection = + when { + target != null && toggleMembership -> SelectionOps.toggle(current, target) + target != null -> SelectionOps.replace(target) + toggleMembership -> current + else -> SelectionOps.clear() + } + +/** The outcome of an Alt click over a candidate stack: open the overlap picker, select directly, or nothing. */ +internal sealed class AltPickResolution { + /** Two or more candidates are stacked under the cursor: the overlap picker disambiguates. */ + class ShowOverlap(val candidates: List) : AltPickResolution() + + /** Exactly one candidate: select it directly, no picker needed. */ + class SelectSingle(val id: DrawableId) : AltPickResolution() + + /** Empty canvas: the selection stays as-is (Alt is the disambiguate gesture, not a clear). */ + object None : AltPickResolution() +} + +/** + * Resolves an Alt click over the (already selectable-filtered) candidate stack under the cursor. + * + * @param List candidates The selectable candidates under the cursor, front-to-back. + * @return AltPickResolution What the click does. + */ +internal fun resolveAltOverlapPick(candidates: List): AltPickResolution = + when { + candidates.size > 1 -> AltPickResolution.ShowOverlap(candidates) + candidates.size == 1 -> AltPickResolution.SelectSingle(candidates.first().id) + else -> AltPickResolution.None + } + +/** + * The idle object-pick pointer flow shared by the drawable-selecting surfaces: a primary press starts + * a provisional rubber-band, a drag past the click threshold box-selects on release (Shift adds), a + * sub-threshold release is the click pick (plain replaces, Shift / Ctrl toggles membership, an Alt + * click resolves the overlap stack, an unmodified click on empty canvas clears), and Shift+RightClick + * places the space's cursor. Only primary-driven events are consumed, so middle-drag pan and wheel + * zoom fall through to the navigation layer beneath. + * + * The domain seams pass in as constructor callbacks, the [MarqueeSelectController] pattern: the 2D + * viewport binds the render service's raster pickers and the world 2D cursor; a UV object mode binds + * its own display-space island hit tests and the UV cursor over the SAME session selection. The + * shared parts - the selection store, the selectable filter, and the navigation-suppressing + * gesture-active flag - read the session directly, like [handleIdleMeshSelectionEvent] does for the + * mesh-element domain. + * + * @param EditorSession session The session owning the model, the object selection, and the gesture-active flag. + * @param MarqueeSelectController marquee The box machinery this flow rubber-bands through. + * @param Function pickTopmost The front-most selectable-unfiltered drawable at an area-local point, or null. + * @param Function pickStack The full candidate stack at an area-local point, front-to-back, unfiltered. + * @param Function onOverlapRequest Opens the overlap picker for an Alt click with 2+ candidates. + * @param Function placeCursor Places the space's cursor at a Shift+RightClick, given the unprojected point. + * @param Function onBoxBegin Runs at the press that starts the rubber-band (the viewport snapshots its + * centroid cache here, the [MarqueeSelectController] onStrokeBegin precedent); defaults to nothing. + */ +internal class ObjectPickController( + private val session: EditorSession, + private val marquee: MarqueeSelectController, + private val pickTopmost: (Offset) -> DrawableId?, + private val pickStack: (Offset) -> List, + private val onOverlapRequest: (Offset, List) -> Unit, + private val placeCursor: (Float, Float) -> Unit, + private val onBoxBegin: () -> Unit = {}, +) { + // Marks a box drag started from a plain primary press (the sub-threshold release of which is the + // click pick). A plain var, not snapshot state: only the pointer loop and the cancel paths read + // it, never composition, so there is no observer to notify - the rubber-band the draw pass + // observes lives in the marquee controller. + private var boxing = false + + /** + * Handles one idle pointer event: the press / move / release flow described on the class. The + * caller routes events here only while nothing is armed in its area (no modal operator, no armed + * select tool). + * + * @param PointerEvent event The full pointer event (buttons and modifiers). + * @param PointerInputChange change The event's first change (position and consumption). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ + fun handleIdleEvent(event: PointerEvent, change: PointerInputChange, camera: ViewportCamera, size: IntSize) { + when (event.type) { + PointerEventType.Press -> + if (event.buttons.isSecondaryPressed && event.keyboardModifiers.isShiftPressed && !boxing) { + // Shift+RightClick places the space's cursor at the pointer (Blender's gesture); the + // cursor overlay draws it and the Cursor pivot mode / snap menu anchor on it. + val (unprojectedX, unprojectedY) = screenToWorld(change.position.x, change.position.y, camera, size) + placeCursor(unprojectedX, unprojectedY) + change.consume() + } else if (event.buttons.isSecondaryPressed) { + if (boxing) { + cancel() + change.consume() + } + } else if (event.buttons.isPrimaryPressed && !event.buttons.isTertiaryPressed) { + onBoxBegin() + marquee.beginBox(change.position) + boxing = true + session.setViewportGestureActive(true) + change.consume() + } + + PointerEventType.Move -> + if (boxing && marquee.dragBox(change.position)) { + change.consume() + } + + PointerEventType.Release -> { + if (boxing) { + val boxRelease = marquee.releaseBox(change.position, event.keyboardModifiers.isShiftPressed, camera, size) + if (boxRelease != BoxRelease.None) { + if (boxRelease == BoxRelease.Click) { + val modifiers = event.keyboardModifiers + applyClickPick( + position = change.position, + toggleMembership = modifiers.isCtrlPressed || modifiers.isMetaPressed || modifiers.isShiftPressed, + alt = modifiers.isAltPressed, + ) + } + boxing = false + session.setViewportGestureActive(false) + change.consume() + } + } + } + + else -> {} + } + } + + /** + * Abandons an in-flight un-armed box drag, dropping the rubber-band without touching the + * selection; a no-op when none is in flight, so callers invoke it unconditionally (the Escape / + * tool-switch / inert-area paths). + */ + fun cancel() { + if (!boxing) { + return + } + marquee.cancel() + boxing = false + session.setViewportGestureActive(false) + } + + /** + * Applies the sub-threshold click: the Alt path resolves the candidate stack (2+ opens the overlap + * picker, exactly one selects directly, empty leaves the selection), the plain path picks the + * front-most drawable through the decision table. Unselectable drawables are excluded from both, + * so a click passes through them. + * + * @param Offset position The click position in area-local pixels. + * @param Boolean toggleMembership True when a membership modifier (Shift / Ctrl / Meta) is held. + * @param Boolean alt True when Alt is held (the disambiguate gesture). + */ + private fun applyClickPick(position: Offset, toggleMembership: Boolean, alt: Boolean) { + val model = session.model.value + if (alt) { + val candidates = + pickStack(position).filter { candidate -> model.selectableOf(SelectionTarget.Drawable(candidate.id)) } + when (val resolution = resolveAltOverlapPick(candidates)) { + is AltPickResolution.ShowOverlap -> onOverlapRequest(position, resolution.candidates) + is AltPickResolution.SelectSingle -> session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(resolution.id))) + AltPickResolution.None -> {} + } + return + } + val hit = pickTopmost(position)?.takeIf { drawableId -> model.selectableOf(SelectionTarget.Drawable(drawableId)) } + session.setSelection( + resolveObjectClickSelection( + current = session.selection.value, + target = hit?.let { drawableId -> SelectionTarget.Drawable(drawableId) }, + toggleMembership = toggleMembership, + ), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/OverlapState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/OverlapState.kt new file mode 100644 index 0000000..2540509 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/OverlapState.kt @@ -0,0 +1,57 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntOffset +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.DrawableId +import org.umamo.ui.model.OverlapEntry +import kotlin.math.roundToInt + +/** + * The overlap-picker popup's state: where to anchor it, the candidate rows, the pre-highlighted row, + * and the requesting surface's pick action (Object mode replaces the object selection; Edit mode's + * Alt+Q switches the edited mesh) - the popup itself is mode-agnostic. Hosted by whichever space + * mounts the popup (the 2D viewport and the UV editor each own one), area-local like the anchor. + */ +internal data class OverlapState( + val anchor: IntOffset, + val entries: List, + val defaultIndex: Int, + val pick: (DrawableId) -> Unit, +) + +/** + * Builds the overlap-popup state from a hit at [position] with [candidates] (front-to-back). The rows + * keep that front-to-back order; the pre-highlighted default is the highest-centrality candidate (the + * most unambiguously clicked one). Each row gets the drawable's layer-art thumbnail from [service] + * (cached there); an untextured drawable yields null and renders as a label-only row. The name and + * thumbnail lookups are pure model/texture reads, so any area kind may call this - a UV-editor area + * included. + * + * @param PuppetViewportService service The service that supplies the row names and (cached) thumbnails. + * @param Offset position The cursor position to anchor the popup at, in area-local pixels. + * @param List candidates The opaque candidates under the cursor, front-to-back. + * @param Function pick Applies the chosen drawable per the requesting overlay's mode. + * @return OverlapState The popup state. + */ +internal fun overlapStateFrom( + service: PuppetViewportService, + position: Offset, + candidates: List, + pick: (DrawableId) -> Unit, +): OverlapState = + OverlapState( + anchor = IntOffset(position.x.roundToInt(), position.y.roundToInt()), + entries = + candidates.map { candidate -> + // "Drawable (Part)" - what the rigger named the mesh plus the part that owns it, since that + // is what they recognize on a crowded stack. A nameless drawable falls back to its stable + // id, and a drawable with no part (or a part with no name) drops the parenthetical. + val drawableName = service.drawableNameFor(candidate.id)?.ifBlank { null } ?: candidate.id.raw + val partName = service.partNameFor(candidate.id)?.ifBlank { null } + val label = if (partName != null) "$drawableName ($partName)" else drawableName + OverlapEntry(candidate.id, label, service.thumbnailFor(candidate.id)) + }, + defaultIndex = candidates.indices.maxByOrNull { index -> candidates[index].centrality } ?: 0, + pick = pick, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/PuppetViewportBinding.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/PuppetViewportBinding.kt new file mode 100644 index 0000000..aadaccd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/PuppetViewportBinding.kt @@ -0,0 +1,742 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.input.pointer.PointerInputScope +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.isTertiaryPressed +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.GridConfig +import org.umamo.edit.NoticePlacement +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.render.DecodedImage +import org.umamo.render.GridColors +import org.umamo.render.LayerDrawPlan +import org.umamo.render.LayerRasterBatch +import org.umamo.render.SourceArtRasters +import org.umamo.render.ViewportCamera +import org.umamo.render.buildLayerDrawPlan +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.visibleDrawableIds +import org.umamo.storage.UmamoLog +import org.umamo.ui.LocalSettings +import org.umamo.ui.model.DrawableThumbnailProvider +import org.umamo.ui.model.OverlapPickerPopup +import org.umamo.ui.model.PuppetRenderSync +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.umamoPointerIcon +import org.umamo.ui.workspace.ViewportHost + +/** + * The viewport host plus its render service and preview seams, returned together so the app can inject + * the host into the editor shell and provide the service / thumbnails / render-sync into their locals. + * The per-area camera controllers are no longer carried here - each viewport / UV leaf registers its own + * into the shared AreaCameraHub, and the view commands resolve the hovered area through that hub. + * + * @property ViewportHost host The Viewport2D host injected into the editor shell. + * @property DrawableThumbnailProvider thumbnails Art-mesh previews for the Outliner hover (LocalDrawableThumbnails). + * @property PuppetRenderSync renderSync Streams transient preview models to the renderer (LocalPuppetRenderSync). + * @property PuppetViewportService service The render service itself (LocalPuppetViewportService), so the UV + * editor can register a UV-editor area and drive its camera through the same engine. + */ +class PuppetViewportBinding( + val host: ViewportHost, + val thumbnails: DrawableThumbnailProvider, + val renderSync: PuppetRenderSync, + val service: PuppetViewportService, +) + +/** How many layers one fill pass decodes before handing them over, so visible art lands early. */ +private const val SOURCE_LAYER_FILL_CHUNK = 8 + +/** + * How much of the puppet has no source artwork to display from, across a whole display-mode session. + * + * Two sources that only make sense added together: drawables the document retains no recoverable art + * for (known when the mapping is built) and drawables whose art will not decode (discovered only when + * something tries). Residency is deliberately NOT one of them - artwork the renderer left on the + * atlas for budget is still artwork the document has, and reporting that as a gap would turn a memory + * decision into a fidelity warning. + */ +private class SourceArtworkGaps { + private var plan: LayerDrawPlan = LayerDrawPlan.EMPTY + private val undecodable = HashSet() + private var reportedCount = 0 + private var reportedUnavailable = false + + /** Starts over against a new mapping. */ + fun reset(plan: LayerDrawPlan) { + this.plan = plan + undecodable.clear() + reportedCount = 0 + reportedUnavailable = false + } + + /** + * Records layers that would not decode. + * + * @param Set layerKeys The layers that failed. + * @return Boolean True when this added something not already known. + */ + fun addUndecodable(layerKeys: Set): Boolean = undecodable.addAll(layerKeys) + + /** + * Tells the rigger once per increase, so a chunked fill does not repeat itself. + * + * @param EditorSession session The session carrying the notice. + */ + fun report(session: EditorSession) { + val total = plan.unresolvedDrawableCount + plan.drawableIdsUsing(undecodable).size + if (total <= reportedCount) { + return + } + reportedCount = total + // A partly-recoverable document displays from a mix, which must not read as a clean switch. The + // count goes to the log because the notice carries no arguments; the message's job is only to stop + // the mix from being silent. + UmamoLog.warn("source-artwork display: $total drawable(s) have no usable artwork and stay on the atlas") + session.emitNotice("notice.display.partialSourceArtwork", NoticePlacement.NearCursor) + } + + /** + * Tells the rigger when the requested display mode cannot engage AT ALL, once per mapping. + * + * The renderer's own gate is all or nothing: it engages only when every displayable layer is + * resident, and displayable means the plan maps it and it decodes. So "nothing displayable" - + * an empty mapping, or every mapped layer undecodable - leaves the mode requested but silently + * never engaging, with the toggle set and the puppet unchanged. This is that condition computed + * from the producer's own state, mirroring the renderer's wanted-set test exactly. + * + * @param EditorSession session The session carrying the notice. + */ + fun reportUnavailableIfUnengaged(session: EditorSession) { + if (reportedUnavailable) { + return + } + val wanted = plan.layerByteCostByKey.keys - undecodable + if (wanted.isNotEmpty()) { + return + } + reportedUnavailable = true + UmamoLog.warn("source-artwork display: requested, but no artwork is displayable; the puppet stays on the atlas") + session.emitNotice("notice.display.sourceArtworkUnavailable", NoticePlacement.NearCursor) + } +} + +/** + * Builds a [PuppetViewportBinding] backed by a [PuppetViewportService]: the puppet renders on the + * engine's own thread and shows as a lightweight Compose `Image` with a per-area pan/zoom camera, so the + * viewport is ordinary Compose content (the zoom readout - and future gizmos - layer over it correctly). + * The service is created through [serviceFactory], owned for the life of this composition (one document), + * and disposed when it leaves; viewport areas register / resize / navigate against it by id. + * + * @param PuppetModel puppet The rig to render (the document's model at open; the service builds from it). + * @param AtlasPageBinding atlasPages The session's effective atlas pages, paired with their atlas value; + * re-published into the live service when a repack (or its undo) swaps them. + * @param SourceArtRasters artRasters The document's source artwork pixels, for the source-artwork display. + * @param LiveParams liveParams The shared parameter hand-off. + * @param EditorSession session The per-document session (its selection drives picking + tint, its model + * drives the visibility re-render). + * @param PuppetViewportServiceFactory serviceFactory Creates (and starts) the platform render service. + * @param Map initialCameras The cameras the document was saved with, by area and surface (docs/format/UMA.md § 7.3); + * read once, as the service is built. + * @return PuppetViewportBinding The host, the render service, and the preview seams the shell and app wire up. + */ +@Composable +fun rememberPuppetViewportHost( + puppet: PuppetModel, + atlasPages: AtlasPageBinding, + artRasters: SourceArtRasters, + liveParams: LiveParams, + session: EditorSession, + serviceFactory: PuppetViewportServiceFactory, + initialCameras: Map = emptyMap(), +): PuppetViewportBinding { + // The page set is deliberately NOT a key: the session swaps pages mid-document (a repack, or its + // undo), and that flows into the LIVE service below - re-keying here would tear down the whole GL + // engine and every per-area camera for what is a texture upload. + val service = + remember(puppet, liveParams) { + // Seeded here, inside the remember, so the cameras are in place before any area below registers. + serviceFactory(puppet, atlasPages.textures, liveParams).also { created -> created.seedCameras(initialCameras) } + } + DisposableEffect(service) { + onDispose { service.dispose() } + } + // The effective pages, following the session's atlas resolution. The first fire re-publishes the + // construction pair, which the renderer recognizes by identity and skips. + LaunchedEffect(service, atlasPages) { + service.setAtlasPages(atlasPages) + } + // Bridge the session's selection to the render thread: push the selected drawable ids (the only kind the + // viewport tints) plus the active (last-selected) one, so it re-renders the tint with the active drawable + // distinguished from the rest of a multi-selection. The session is the source of truth, so this also + // follows an undo/redo that changes the selection. Mirrors how settings/liveparams reach the render thread. + // + // Edit mode suppresses the tint entirely (an empty set, no active): the object selection still holds the + // drawable being edited, but the highlight is object-mode chrome that would fight the mesh gizmo overlay. + // Gated on the mode exactly like the pose override below, so entering Edit clears the tint and leaving + // restores it with no stash - session.selection is never touched. + LaunchedEffect(service, session) { + combine(session.selection, session.mode, session.previewSelection) { selection, mode, previewSelection -> + when { + mode == EditorMode.Edit -> emptySet() to null + // An in-flight object circle stroke paints a transient preview; while it is live the tint shows + // exactly what the stroke has painted (previewSelection) with no active drawable yet, so drawables + // light up plain under the brush before the stroke commits. + previewSelection != null -> previewSelection to null + // Otherwise the committed object selection's drawables tint as usual, with its active + // (last-selected) drawable tinted apart. A Part/Deformer active target yields null, so every + // selected drawable tints plain - correct, since only drawables are tinted. + else -> { + val selectedDrawableIds = + selection.targets.filterIsInstance().map { it.id }.toSet() + val activeDrawableId = (selection.active as? SelectionTarget.Drawable)?.id + selectedDrawableIds to activeDrawableId + } + } + } + .distinctUntilChanged() + .collect { (drawableIds, activeDrawableId) -> + service.setSelection(drawableIds) + service.setActiveSelection(activeDrawableId) + } + } + // Bridge the session's model to the render thread on every committed edit or undo/redo: push the whole + // model (so a layer reorder re-sorts the draw order) and the resolved Parts-panel visibility cascade (so + // an eyeball toggle hides / re-shows art). Edit mode renders the same model as Object mode — the gizmo + // overlay projects itself onto the real deformed geometry, so there is no edit-view transform here. + LaunchedEffect(service, session) { + session.model.collect { model -> + service.setModel(model) + service.setShownDrawables(model.visibleDrawableIds()) + } + } + // Cubism Mesh Edit guide image: freeze each Edit-session drawable's textured GPU mesh for the duration + // of Edit so deleting verts / faces (or grabbing verts) updates only the wireframe, never the art under + // it. Cleared on leave so the live mesh re-uploads. Independent of the model collect above — freeze + // must be keyed on mode + session mesh ids, not on every topology commit (which would re-freeze the + // already-holed mesh). + LaunchedEffect(service, session) { + combine(session.mode, session.meshSelection) { mode, meshSelection -> + if (mode == EditorMode.Edit) meshSelection.drawableIds.toSet() else emptySet() + } + .distinctUntilChanged() + .collect { frozenIds -> + service.setEditMeshFrozen(frozenIds) + } + } + // How many drawables have no usable artwork: the mapping failures the plan knows up front, plus the + // ones whose layer turned out not to decode, which only a decode can discover. Never residency - + // the renderer keeps every mapped layer or engages nothing, so there is no third case to confuse it + // with. + val artworkGaps = remember(service, artRasters) { SourceArtworkGaps() } + + // Source-artwork display, end to end: work out the mapping, then stream the pixels in behind it. + // + // The mapping is cheap (it decodes nothing) so it is built for the whole document and published + // whole, and rebuilt whenever the mode flips or the drawable set changes - a duplicate needs its own + // mapping. The pixels then follow in chunks, each handed over and released before the next is + // decoded, so the heap holds one chunk rather than the document's whole artwork; a rig whose layers + // would be a gigabyte decoded streams in a few tens of megabytes. + // + // The renderer engages nothing until the last chunk lands, so this is a fill, not a fade-in: the + // puppet shows its atlas throughout and then flips whole. That is the mode's contract - it exists + // to inspect the artwork, and a puppet drawn half from each would say nothing trustworthy about it. + // + // `delivered` is what makes a mapping rebuild cheap: the renderer keeps every layer the new plan + // still maps, so only genuinely new ones need decoding. collectLatest abandons an in-flight stream + // when the mapping changes under it. + LaunchedEffect(service, artRasters) { + val delivered = HashSet() + session.model + // The ATLAS is part of the key, not just the drawable set: a placement is model state a repack + // authors, and a plan built before it moved would keep sampling the art at its old spot. + .map { model -> Triple(model.rendersFromSourceLayers, model.atlas, model.drawables.map { drawable -> drawable.id }) } + .distinctUntilChanged() + .collectLatest { (fromSourceLayers, atlas, _) -> + if (!fromSourceLayers || atlas.tiles.isEmpty()) { + delivered.clear() + artworkGaps.reset(LayerDrawPlan.EMPTY) + service.setSourceLayerPlan(LayerDrawPlan.EMPTY) + if (fromSourceLayers) { + // Requested with nothing to show: the toggle is set and nothing on screen moves. + artworkGaps.reportUnavailableIfUnengaged(session) + } + return@collectLatest + } + val model = session.model.value + val plan = withContext(Dispatchers.Default) { buildLayerDrawPlan(model) } + artworkGaps.reset(plan) + service.setSourceLayerPlan(plan) + artworkGaps.report(session) + + delivered.retainAll(plan.layerByteCostByKey.keys) + val outstanding = plan.layerByteCostByKey.keys.filterNot { layerKey -> layerKey in delivered } + for (chunk in outstanding.chunked(SOURCE_LAYER_FILL_CHUNK)) { + val decoded = HashMap() + val undecodable = HashSet() + withContext(Dispatchers.Default) { + for (layerKey in chunk) { + val image = artRasters.decodeRaster(AtlasTileId(layerKey)) + if (image == null) { + undecodable.add(layerKey) + } else { + decoded[layerKey] = image + } + } + } + delivered.addAll(chunk) + service.deliverSourceLayerRasters(LayerRasterBatch(decoded, undecodable)) + if (artworkGaps.addUndecodable(undecodable)) { + artworkGaps.report(session) + } + } + // The fill is complete, so the displayable set is final: a mapping whose every layer + // proved undecodable (or that mapped nothing) has left the renderer unengaged for good. + artworkGaps.reportUnavailableIfUnengaged(session) + } + } + // Mirror the session's pose into the render-thread hand-off so undo / redo (and any committed scrub) + // re-poses the viewport. Mid-drag previews already take the faster direct path (the Parameters panel + // writes this same volatile through LiveParamsAdapter.preview), so this fires only at gesture + // boundaries and on undo, not per frame — and a commit re-publishes the identical map, a no-op. + // + // Edit mode overrides the DISPLAYED pose to neutral (an empty map — the renderer falls back to every + // parameter's default): Edit mode edits the neutral state of the base mesh, so the whole puppet snaps + // to rest for its duration. Display-only by construction — session.pose is never touched, so leaving + // Edit mode restores the Object-mode pose with no stash. The parameter panel is locked while in Edit + // mode, so no preview write can bypass this override. + LaunchedEffect(service, session) { + combine(session.pose, session.mode) { pose, mode -> + if (mode == EditorMode.Edit) emptyMap() else pose + }.collect { effectivePose -> liveParams.values = effectivePose } + } + // Pending unkeyed channel edits mirror the same way, and are suppressed in Edit mode for the same + // reason the pose is: Edit mode shows the neutral base, so an in-flight channel edit must not tint it. + // Publishing them into the same volatile hand-off is what makes a typed-but-unkeyed value show in the + // viewport at all - it is session state, so it can never reach the renderer inside the model. + LaunchedEffect(service, session) { + combine(session.pendingChannelEdits, session.mode) { pending, mode -> + if (mode == EditorMode.Edit) emptyMap() else pending + }.collect { effectiveOverrides -> liveParams.channelOverrides = effectiveOverrides } + } + // Feed the zoom-increment settings into the service and keep them live as settings change; the keys, + // defaults, and highlight parser are shared with the preferences window via ViewportSettings. + val settings = LocalSettings.current + LaunchedEffect(service, settings, session) { + fun applyViewportSettings() { + service.zoomStepPercent = + (settings.getDouble(ViewportSettings.ZOOM_STEP_KEY) ?: ViewportSettings.ZOOM_STEP_DEFAULT).toFloat() + service.zoomStepCoarsePercent = + ( + settings.getDouble(ViewportSettings.ZOOM_STEP_COARSE_KEY) + ?: ViewportSettings.ZOOM_STEP_COARSE_DEFAULT + ).toFloat() + service.supersampleEnabled = + settings.getBoolean(ViewportSettings.SUPERSAMPLE_KEY) ?: ViewportSettings.SUPERSAMPLE_DEFAULT + service.supersampleWhileResizing = + settings.getBoolean(ViewportSettings.SUPERSAMPLE_WHILE_RESIZING_KEY) + ?: ViewportSettings.SUPERSAMPLE_WHILE_RESIZING_DEFAULT + val (red, green, blue) = parseSelectionHighlightColor(settings.getString(ViewportColorSettings.SELECTION_HIGHLIGHT_KEY)) + service.setSelectionHighlightColor(red, green, blue) + val (activeRed, activeGreen, activeBlue) = + parseSelectionHighlightColor(settings.getString(ViewportColorSettings.ACTIVE_SELECTION_HIGHLIGHT_KEY)) + service.setActiveSelectionHighlightColor(activeRed, activeGreen, activeBlue) + // Resolve the global-default grid geometry into the session, the single source of truth the + // snap commands and the renderer both read. A grid the document saved for itself takes precedence + // (docs/format/UMA.md § 7.4); a document without one - every CMO3 and MOC3 - keeps this default. + if (session.gridFollowsApplication) { + val gridScale = + (settings.getDouble(ViewportSettings.GRID_SCALE_KEY) ?: ViewportSettings.GRID_SCALE_DEFAULT).toFloat() + val gridSubdivisions = + settings.getInt(ViewportSettings.GRID_SUBDIVISIONS_KEY) ?: ViewportSettings.GRID_SUBDIVISIONS_DEFAULT + session.setGridConfig(GridConfig(gridScale, gridSubdivisions)) + } + } + applyViewportSettings() + settings.changes.collect { key -> + if (key.startsWith("viewport.")) { + applyViewportSettings() + } + } + } + // Feed the per-document grid geometry (the session's single source of truth, resolved from settings / + // per-file) into the render service so the drawn backdrop grid matches the snap increment. + LaunchedEffect(service, session) { + session.gridConfig.collect { config -> service.gridConfig = config } + } + // Feed the themed grid-backdrop colors into the service and keep them live: LocalUmamoColors already + // resolves the active scheme (including "system"), so a theme switch recomposes with new colors and this + // effect re-pushes them, re-tinting the viewport backdrop. Compose Color components are 0..1 sRGB, exactly + // what the grid shader mixes. + val gridPalette = LocalUmamoColors.current + LaunchedEffect(service, gridPalette) { + service.gridColors = + GridColors( + backgroundRed = gridPalette.viewportGridBackground.red, + backgroundGreen = gridPalette.viewportGridBackground.green, + backgroundBlue = gridPalette.viewportGridBackground.blue, + majorRed = gridPalette.viewportGridLineMajor.red, + majorGreen = gridPalette.viewportGridLineMajor.green, + majorBlue = gridPalette.viewportGridLineMajor.blue, + minorRed = gridPalette.viewportGridLineMinor.red, + minorGreen = gridPalette.viewportGridLineMinor.green, + minorBlue = gridPalette.viewportGridLineMinor.blue, + ) + } + return remember(service, session) { + val host = + object : ViewportHost { + @Composable + override fun Viewport2D(areaId: String, modifier: Modifier) { + // Keyed on the service too: an area's registration belongs to one service instance, and + // a slot remembered across a service swap would keep collecting the disposed engine's + // flows and never register with the live one. + val imageFlow = remember(areaId, service) { service.register(areaId) } + val cameraFlow = remember(areaId, service) { service.cameraFlow(areaId) } + DisposableEffect(areaId, service) { + onDispose { service.unregister(areaId) } + } + // The area-death cleanup: a leaf can leave composition MID-GESTURE (a corner-join, a + // space switch via the header dropdown, a workspace tab switch), which cancels the + // overlay's latch effect WITHOUT running its teardown branch - stranding the renderer + // on the un-committed preview and orphaning the latch. Cancel anything this area + // initiated and resync the raster to the committed model. + DisposableEffect(areaId, session) { + onDispose { + if (session.activeMeshOperator.value?.areaId == areaId || + session.activeObjectOperator.value?.areaId == areaId + ) { + session.clearMeshOperator() + session.clearObjectOperator() + service.setModel(session.model.value) + } + if (session.activeSelectTool.value?.areaId == areaId) { + session.clearSelectTool() + } + if (session.zoomRegionArmedArea.value == areaId) { + session.disarmZoomRegion() + } + } + } + val image by imageFlow.collectAsState() + val camera by cameraFlow.collectAsState() + // Keyed on the cursor, not remembered bare: this composable recomposes per rendered frame + // (image), so the lookup is worth caching - but the cursor set is documented as gaining a + // per-theme override later, and a keyless remember would then serve stale art forever. + val panCursor = LocalUmamoCursors.nsewScroll + val grabCursor = remember(panCursor) { umamoPointerIcon(panCursor) } + var panning by remember(areaId) { mutableStateOf(false) } + var overlap by remember(areaId) { mutableStateOf(null) } + // Where the pointer last was in this area, tracked at the HOST rather than inside a gizmo + // overlay. A pointer-addressed command (Alt+Q switch-object, rip, select-linked) has to + // know where the cursor is, and the overlays that used to own that knowledge do not mount + // in the very states those commands exist to escape - Edit mode with every selected + // drawable behind a hidden ancestor, say. Tracked here, it survives them. + val areaPointer = remember(areaId) { mutableStateOf(Offset.Zero) } + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + val widthPx = constraints.maxWidth + val heightPx = constraints.maxHeight + LaunchedEffect(widthPx, heightPx) { + service.resize(areaId, widthPx, heightPx) + } + Box( + modifier = + Modifier + .fillMaxSize() + .pointerHoverIcon(if (panning) grabCursor else PointerIcon.Default) + // Watch-only: it consumes nothing, so the navigation loop below and the + // gizmo overlays above all still see every event. Initial pass so the + // position is current even while a child owns the gesture. + .pointerInput(areaId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + event.changes.lastOrNull()?.let { change -> areaPointer.value = change.position } + } + } + } + .pointerInput(areaId) { + viewportNavigation(service, areaId, session) { panning = it } + }, + ) { + image?.let { rendered -> + Image( + bitmap = rendered.bitmap, + contentDescription = null, + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.FillBounds, + ) + } + overlap?.let { state -> + OverlapPickerPopup( + anchor = state.anchor, + entries = state.entries, + defaultIndex = state.defaultIndex, + onPick = { id -> + state.pick(id) + overlap = null + }, + onDismiss = { overlap = null }, + ) + } + // Edit-mode vertex gizmos draw over the puppet image; the overlay self-gates on Edit + // mode with an active drawable, so it is inert (and passes input through) otherwise. + // Project AND pose with the DISPLAYED frame, not the live state: the raster is produced + // asynchronously and lands a few frames behind. Locking the overlay to the frame's + // camera keeps the mesh glued to the art during pan/zoom; locking its geometry to the + // frame's model keeps the wireframe glued to the art during a vertex edit (both lag the + // gesture together as one unit instead of racing ahead). camera and model come from the + // same image in one composition, so they are always the same frame. In a static view + // at rest the frame equals the live state, so there is no lag. + ViewportEditGizmoOverlay( + areaId = areaId, + service = service, + session = session, + camera = image?.camera, + frameModel = image?.model, + widthPx = widthPx, + heightPx = heightPx, + areaPointer = areaPointer, + onOverlapRequest = { position, candidates -> + // Edit mode's Alt+Q over a stack: picking a row switches the edited mesh + // (never the object selection - that follows inside switchEditDrawable). + overlap = + overlapStateFrom(service, position, candidates) { id -> + session.switchEditDrawable(id) + } + }, + ) + // The Object-mode gizmo: the mode-exclusive sibling of the Edit gizmo (each self-gates to + // its mode). It owns the whole primary-button surface in Object mode - the click pick + // (including the Alt overlap popup), the un-armed box drag, and the armed box / circle + // tools and object G / S / R. Same frame-camera projection as the Edit gizmo so the + // affordance stays glued to the art. It draws no posed mesh (only the rubber-band, + // affordances, and pivot HUD), so it needs the frame camera but no frame model. + ViewportObjectGizmoOverlay( + areaId = areaId, + service = service, + session = session, + camera = image?.camera, + widthPx = widthPx, + heightPx = heightPx, + onOverlapRequest = { position, candidates -> + overlap = + overlapStateFrom(service, position, candidates) { id -> + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(id))) + } + }, + ) + // Warp lattice CPs sit above object pick so dragging a point does not re-select a mesh. + ViewportWarpLatticeOverlay( + areaId = areaId, + service = service, + session = session, + liveParams = liveParams, + camera = image?.camera, + widthPx = widthPx, + heightPx = heightPx, + ) + // The Zoom Region overlay sits on top of the gizmo so it captures the drag in Edit mode + // too; it self-gates on the session's armed-area flag, so it is inert (and passes input + // through) in every other area and whenever Zoom Region is not armed. + ViewportRegionOverlay( + areaId = areaId, + service = service, + session = session, + camera = camera, + widthPx = widthPx, + heightPx = heightPx, + ) + // The relation-pick overlay sits above the gizmos so an armed eyedropper claims the + // click before Object mode's pick would change the selection. It self-gates on the + // shell's pick slot, so it is inert (and passes input through) whenever none is armed. + ViewportPickOverlay( + areaId = areaId, + service = service, + ) + // The 2D cursor marker: a control's world-anchored marker (not HUD chrome), so it + // draws in its own layer above the gizmo chrome and below the HUD text. Locked to + // the frame camera like every world-anchored overlay drawing. + Cursor2dOverlay( + session = session, + camera = image?.camera, + widthPx = widthPx, + heightPx = heightPx, + ) + // The HUD layer draws topmost (the modal-op status badge, the active-mesh info chip, + // and the zoom readout). It installs no pointer input, so it never steals a gesture + // from the overlays below. The zoom readout takes the LIVE camera - the wheel + // updates it immediately, where the frame camera lags the raster. The near-cursor + // notices and the radial pie menus render at the SHELL level + // (ShellCursorOverlays.kt): one instance above the whole area tree, escaping this + // viewport's clipped bounds. + ViewportHudOverlay( + areaId = areaId, + session = session, + liveCamera = camera, + ) + } + } + } + } + // The render-sync seam the UV editor's modal previews stream through: preview pushes go straight + // to the render thread (transient, like the Edit overlay's own setModel calls), and resync + // restores the session's committed model after a cancel / teardown. + // Created once per service/session with the host above, so its preview state lives as long as the + // handle every surface reads it through. + val renderSync = + object : PuppetRenderSync { + // Published to the composition as well as the render thread, so a UV area that is not the + // one being dragged in follows the gesture instead of waiting for the commit. + private val previewState = mutableStateOf(null) + + override val preview: State get() = previewState + + override fun previewModel(model: PuppetModel) { + previewState.value = model + service.setModel(model) + } + + override fun resync() { + // Cleared before the renderer is restored: a surface reading the preview must never be + // left holding one the renderer has already dropped. + previewState.value = null + service.setModel(session.model.value) + } + } + PuppetViewportBinding( + host, + service.thumbnails(), + renderSync, + service, + ) + } +} + +/** + * The viewport pointer loop: middle-mouse drag pans (grab), the wheel zooms toward the cursor (Shift + * for the coarse step), and any pointer activity marks this area active so keyboard view commands + * target it. Picking is NOT handled here - the mode's gizmo overlay above owns the primary button + * (the Object overlay's click pick / un-armed box, the Edit overlay's element picking). The right + * button stays reserved for the context menu; touch pinch is the Android host's concern. + * + * @param PuppetViewportService service The render service to drive. + * @param String areaId The area this viewport hosts. + * @param EditorSession session The session whose armed tools gate this layer. + * @param Function setPanning Reports whether a middle-mouse pan is in progress (drives the grab cursor). + * @note This loop stamps NOTHING about where the pointer is. Every workspace leaf carries that (see + * stampsHoveredSurface), and commands resolve their area from it at dispatch; a viewport-only second + * answer here would disagree with that one the moment the pointer moved to another space, so there is + * deliberately none. + */ +private suspend fun PointerInputScope.viewportNavigation( + service: PuppetViewportService, + areaId: String, + session: EditorSession, + setPanning: (Boolean) -> Unit, +) { + awaitPointerEventScope { + var panAnchor: Offset? = null + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + // THIS AREA'S modal operator (G / S / R), armed Box / Circle select tool, or armed Zoom Region + // - or an in-flight un-armed box drag (area-less: pointer capture pins its events to the + // dragging overlay) - owns the pointer: the overlay above consumes the event, but this + // navigation layer does not check isConsumed, so it must skip pan / zoom explicitly - + // otherwise a Circle MMB-erase would also pan, its wheel-resize would also zoom, and an + // object G / S / R grab would pan. A gesture latched in ANOTHER area does not block: its + // events never reach here, so this area keeps panning and zooming during it (Blender + // parity). + if (session.activeMeshOperator.value?.areaId == areaId || + session.activeObjectOperator.value?.areaId == areaId || + session.activeSelectTool.value?.areaId == areaId || + session.viewportGestureActive.value || + session.zoomRegionArmedArea.value == areaId + ) { + continue + } + when (event.type) { + PointerEventType.Scroll -> { + val shiftHeld = event.keyboardModifiers.isShiftPressed + // AWT reroutes Shift+wheel into a horizontal scroll (the delta arrives in x with y + // zero), so the coarse step's own modifier would hide the wheel motion - read the x + // delta when Shift is held. Sign convention matches y (wheel up = negative). + val scrollSteps = + if (change.scrollDelta.y != 0f) { + change.scrollDelta.y + } else if (shiftHeld) { + change.scrollDelta.x + } else { + 0f + } + if (scrollSteps != 0f) { + // One step per notch (wheel up = negative = zoom in); Shift selects the coarse step. + service.zoomAtCursor( + areaId, + zoomIn = scrollSteps < 0f, + coarse = shiftHeld, + cursorXpx = change.position.x, + cursorYpx = change.position.y, + ) + change.consume() + } + } + + else -> { + if (event.buttons.isTertiaryPressed) { + if (panAnchor == null) { + setPanning(true) + } + val anchor = panAnchor + if (anchor != null) { + val delta = change.position - anchor + if (delta != Offset.Zero) { + service.pan(areaId, delta.x, delta.y) + } + } + panAnchor = change.position + change.consume() + } else { + if (panAnchor != null) { + setPanning(false) + } + panAnchor = null + } + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/PuppetViewportService.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/PuppetViewportService.kt new file mode 100644 index 0000000..4012b76 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/PuppetViewportService.kt @@ -0,0 +1,484 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.graphics.ImageBitmap +import kotlinx.coroutines.flow.StateFlow +import org.umamo.edit.GridConfig +import org.umamo.format.raster.RasterImage +import org.umamo.render.ContentBounds +import org.umamo.render.DecodedImage +import org.umamo.render.FrameBackdrop +import org.umamo.render.GridColors +import org.umamo.render.LayerDrawPlan +import org.umamo.render.LayerRasterBatch +import org.umamo.render.PuppetTextures +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.model.DrawableThumbnailProvider + +/** + * Creates (and starts) the platform render service for one open document. Desktop supplies the + * offscreen GLFW/LWJGL engine; Android supplies its GLES sibling. Injected into + * rememberPuppetViewportHost so the whole viewport composable stack stays common. + */ +typealias PuppetViewportServiceFactory = (PuppetModel, PuppetTextures, LiveParams) -> PuppetViewportService + +/** + * A rendered puppet frame together with the camera AND the model it was rendered from. The engine + * renders asynchronously, so a frame lands a few ticks behind the live state; the overlay draws itself + * as a pure function of this frame - projecting through [camera] and posing its geometry from [model] - + * so the vector overlay stays glued to the raster along both the navigation axis (pan/zoom, the camera) + * and the edit axis (mesh geometry, the model) instead of racing ahead of it. Bundling all three in one + * immutable value keeps the publish atomic, so the bitmap, its camera, and its geometry can never tear + * apart across the frame flow. + * + * @property ImageBitmap bitmap The area's rendered pixels (already downscaled to the area size). + * @property ViewportCamera camera The camera the pixels were rendered with. + * @property PuppetModel model The model whose geometry the pixels reflect (the overlay poses from it so + * the wireframe lags with the raster during an edit instead of leading it). + */ +data class RenderedFrame(val bitmap: ImageBitmap, val camera: ViewportCamera, val model: PuppetModel) + +/** + * What a UV-editor area draws under its wireframe overlays. + * + * Two shapes rather than one nullable image because the atlas page is addressed by INDEX into the + * document's pages (the engine resolves the pixels itself, and re-uses the textures it already + * uploaded for the puppet) while a source layer arrives as pixels the engine has never seen. Keeping + * them distinct is also what lets an area switch between them without re-registering. + */ +sealed interface UvSceneContent { + /** + * One of the document's packed atlas pages. + * + * @property Int? pageIndex The page to draw, or null for none (grid only). + */ + data class AtlasPage(val pageIndex: Int?) : UvSceneContent + + /** + * A source layer's own artwork, decoded by the caller. + * + * The key is the layer's identity and the image is only its pixels: the engine remembers a view per + * layer by the key, so a re-decoded image of the same layer keeps the view it had. + * + * @property String layerKey The shown layer's key in the document's source-art store. + * @property DecodedImage? image The layer raster to draw, or null for none (grid only). + */ + data class SourceLayer(val layerKey: String, val image: DecodedImage?) : UvSceneContent +} + +/** + * A page set paired with the atlas value whose placements it renders. + * + * The pairing is what lets the engine apply a model and its pages ATOMICALLY: pages and model reach + * the render thread on independent channels, and on undo the baseline model would land frames before + * the baseline pages - repacked pixels under baseline coordinates - unless the loop can see which + * atlas a page set belongs to and hold an atlas-changing model until its pages arrive. + * + * A plain class, not a data class: it carries pixel buffers, and the engine compares bindings by + * identity and their atlases by the model's own identity-then-equality rule. + * + * @property PuppetAtlas atlas The atlas value the pages were composed for. + * @property PuppetTextures textures The page pixels and the drawable-to-page map. + */ +class AtlasPageBinding( + val atlas: PuppetAtlas, + val textures: PuppetTextures, +) + +/** + * Which surface a camera frames. The puppet's world space and a texture's pixel space share nothing, so a view of + * one means nothing over the other: an area switched from the UV editor to the 2D viewport must not inherit the + * page's pan and zoom, and each keeps its own for the day the area switches back. + */ +enum class CameraSurface { + /** The posed puppet, in world units (the 2D viewport). */ + Viewport, + + /** A flat texture surface - an atlas page or a source layer - in its own pixels (the UV editor). */ + Uv, +} + +/** + * What a remembered camera belongs to: one area, showing one kind of surface. + * + * @property String areaId The hosting leaf's area id. + * @property CameraSurface surface The surface the camera frames. + */ +data class AreaCameraKey(val areaId: String, val surface: CameraSurface) + +/** + * The platform seam between the common viewport UI and a puppet render engine. The engine owns a GPU + * context on its own thread, renders the posed puppet per registered area, and publishes each frame as + * a Compose ImageBitmap; the common `Viewport2D` composable, the navigation/pick pointer loop, and the + * Edit-mode gizmo overlay drive it exclusively through this interface. Desktop implements it with an + * offscreen GLFW/LWJGL service; Android's GLES sibling implements the same surface when it lands. + * + * Threading contract: everything here is called from the UI thread; implementations publish to their + * render thread internally (volatile swaps of immutable values). Picking is CPU-side and synchronous. + */ +interface PuppetViewportService { + /** The fine zoom increment in percentage points (one wheel notch / key press), fed from settings. */ + var zoomStepPercent: Float + + /** The coarse (Shift-held) zoom increment in percentage points, fed from settings. */ + var zoomStepCoarsePercent: Float + + /** Whether settled frames render supersampled at all, fed from settings; off is 1x everywhere. */ + var supersampleEnabled: Boolean + + /** Whether frames rendered mid-resize keep the supersample, fed from settings; off drops them to 1x. */ + var supersampleWhileResizing: Boolean + + /** The grid backdrop colors (background / major / minor), fed from the editor theme; a change forces a redraw. */ + var gridColors: GridColors + + /** The per-document grid geometry (major spacing + subdivisions), fed from the session; a change forces a redraw. */ + var gridConfig: GridConfig + + /** + * Registers a viewport area and returns the flow its rendered frames arrive on. Reference-counted + * per [areaId]: register/unregister pair across the area's composable life. + * + * @param String areaId The hosting area's stable id. + * @return StateFlow The frame flow (null until the first render lands); each frame carries the + * camera it was rendered at so the overlay can reproject it against the live camera. + */ + fun register(areaId: String): StateFlow + + /** + * Registers a UV-EDITOR area - the flat image-under-wireframe surface - rather than the posed puppet. + * Same reference-counted lifecycle and [RenderedFrame] flow as [register] (the frame's bitmap is the + * rendered image, its camera the one it was rendered at), driven by the same per-area camera surface + * ([cameraFlow] / [resize] / [pan] / [zoomAtCursor] / [zoomCentered] / [fit] / [fitWorldRect] / + * [actualSize] / [unregister]) - only the rendered content differs. The engine fits that content's + * rectangle, widened to [islandExtent], rather than the puppet content bounds. + * + * The camera is kept per SURFACE as well as per area: each page and each layer the area shows keeps the + * view it was left with for the rest of the session, and one the area has never shown is fitted. Those + * per-surface views are session state only - [cameras] reports just the view of the surface on screen, + * which is the one a save writes (docs/format/UMA.md § 7.3). + * + * Retarget it with [setUvSceneContent] as the editor's shown content changes; do NOT re-register, + * which takes a second reference-counted hold the area never releases. + * + * @param String areaId The hosting UV-editor area's stable id. + * @param UvSceneContent content What to draw (an atlas page or a source layer image). + * @param ContentBounds? islandExtent The shown meshes' display-space bounds, or null for none. + * @return StateFlow The frame flow (null until the first render lands). + */ + fun registerUvScene(areaId: String, content: UvSceneContent, islandExtent: ContentBounds?): StateFlow + + /** + * Retargets what an already-registered [registerUvScene] area draws, including switching between an + * atlas page and a source layer, and updates the mesh extent its fit covers. A switch to another + * surface brings back the view the area left that surface with, or fits one it has not shown yet. A + * no-op for an unregistered area or a puppet (2D) area. + * + * @param String areaId The UV-editor area to retarget. + * @param UvSceneContent content The new content to draw. + * @param ContentBounds? islandExtent The shown meshes' display-space bounds, or null for none. + */ + fun setUvSceneContent(areaId: String, content: UvSceneContent, islandExtent: ContentBounds?) + + /** + * Releases one registration of [areaId]; the engine drops the area's resources at zero. + * + * @param String areaId The area to release. + */ + fun unregister(areaId: String) + + /** + * The flow of [areaId]'s pan/zoom camera (null until the first fit), for readouts and overlays. + * + * @param String areaId The area whose camera to observe. + * @return StateFlow The camera flow. + */ + fun cameraFlow(areaId: String): StateFlow + + /** + * Every camera the engine remembers, by area and surface: the areas shown now and the ones a workspace tab + * switch has put away. What a save writes as each area's views (docs/format/UMA.md § 7.3). A UV editor's + * entry is the view of the page or layer it shows now; the views it keeps for the others are not here. + * + * @return Map The cameras. + */ + fun cameras(): Map + + /** + * Gives the engine the cameras a document was saved with, before any area registers: an area that has one for + * the surface it shows opens on it instead of fitting its content. A key no area ever takes costs nothing. + * + * @param Map cameras The saved cameras, by area and surface. + */ + fun seedCameras(cameras: Map) + + /** + * Reports [areaId]'s current size in pixels; the engine re-renders at the new size. + * + * @param String areaId The resized area. + * @param Int width The new width in pixels. + * @param Int height The new height in pixels. + */ + fun resize(areaId: String, width: Int, height: Int) + + /** + * Pans [areaId]'s camera by a pointer delta in viewport pixels. + * + * @param String areaId The panned area. + * @param Float deltaXpx The horizontal delta in pixels. + * @param Float deltaYpx The vertical delta in pixels. + */ + fun pan(areaId: String, deltaXpx: Float, deltaYpx: Float) + + /** + * Zooms [areaId] one step toward/away from the cursor position (the wheel gesture). + * + * @param String areaId The zoomed area. + * @param Boolean zoomIn True to zoom in, false to zoom out. + * @param Boolean coarse True for the coarse (Shift) step. + * @param Float cursorXpx The cursor x in viewport pixels (the zoom anchor). + * @param Float cursorYpx The cursor y in viewport pixels (the zoom anchor). + */ + fun zoomAtCursor(areaId: String, zoomIn: Boolean, coarse: Boolean, cursorXpx: Float, cursorYpx: Float) + + /** + * Zooms [areaId] one step about its center (the keyboard/menu gesture). + * + * @param String areaId The zoomed area. + * @param Boolean zoomIn True to zoom in, false to zoom out. + * @param Boolean coarse True for the coarse (Shift) step. + */ + fun zoomCentered(areaId: String, zoomIn: Boolean, coarse: Boolean) + + /** + * Frames a screen-pixel rectangle in [areaId], filling the viewport with the dragged box (the Zoom + * Region / Shift+B gesture). Mode-agnostic - the camera does not distinguish Object from Edit mode. + * + * @param String areaId The zoomed area. + * @param Float leftPx One horizontal box edge in viewport pixels. + * @param Float topPx One vertical box edge in viewport pixels. + * @param Float rightPx The other horizontal box edge in viewport pixels. + * @param Float bottomPx The other vertical box edge in viewport pixels. + */ + fun zoomToRegion(areaId: String, leftPx: Float, topPx: Float, rightPx: Float, bottomPx: Float) + + /** + * Sets [areaId]'s camera to 1:1 (one content unit per pixel), centerd. + * + * @param String areaId The area to reset. + */ + fun actualSize(areaId: String) + + /** + * Fits the area's content inside [areaId], centerd: the puppet's content bounds, or a UV editor's shown + * surface widened to every shown mesh that reaches past it. + * + * @param String areaId The area to fit. + */ + fun fit(areaId: String) + + /** + * Fits a world-space rectangle inside [areaId], centerd - the Frame Selected camera move (the + * caller computes the selection's world bounds; this only frames them). + * + * @param String areaId The area to frame in. + * @param Float minX The rectangle's minimum world x. + * @param Float minZ The rectangle's minimum world z (up). + * @param Float maxX The rectangle's maximum world x. + * @param Float maxZ The rectangle's maximum world z (up). + */ + fun fitWorldRect(areaId: String, minX: Float, minZ: Float, maxX: Float, maxZ: Float) + + /** + * Pushes the selected drawables; the engine re-renders their tint. + * + * @param Set ids The selected drawable ids. + */ + fun setSelection(ids: Set) + + /** + * Pushes the active (last-selected) drawable, so the engine tints it toward the active-selection color + * rather than the shared selection color and it reads apart from the rest of a multi-selection. Null + * when nothing is active (Object mode with no drawable active, an in-flight preview stroke, or Edit + * mode, whose tint is suppressed anyway). The engine re-renders on a change. + * + * @param DrawableId? id The active drawable id, or null when none is active. + */ + fun setActiveSelection(id: DrawableId?) + + /** + * Pushes which artwork every drawable would display from, or [LayerDrawPlan.EMPTY] to display from + * the packed atlas. + * + * The mapping is published whole and takes effect at once; the PIXELS follow separately and + * progressively, through [sourceLayerRequests] and [deliverSourceLayerRasters]. That split is + * deliberate: a document can reference hundreds of layers, and decoding them all to switch display + * mode is what would stall the switch - or exhaust memory before it finished. + * + * @param LayerDrawPlan plan Each drawable's mapping into the document's artwork. + */ + fun setSourceLayerPlan(plan: LayerDrawPlan) + + /** + * Hands decoded artwork to the engine, filling in the plan pushed by [setSourceLayerPlan]. + * + * Decoding must happen off both the UI and render threads, and the batch is consumed rather than + * retained, so the caller may - and should - drop its own reference as soon as this returns. That + * is what lets a document's artwork be streamed in chunks instead of held decoded all at once. + * + * @param LayerRasterBatch batch The decoded artwork. + */ + fun deliverSourceLayerRasters(batch: LayerRasterBatch) + + /** + * Pushes the drawables actually shown (the resolved Parts-panel visibility cascade). + * + * @param Set ids The shown drawable ids. + */ + fun setShownDrawables(ids: Set) + + /** + * Freezes the textured GPU mesh for the Edit-session drawables as the mesh-edit guide image (Cubism + * Mesh Edit): topology deletes and vertex moves update the wireframe only, not the image under it. + * Pass an empty set when leaving Edit so the live mesh re-uploads. + * + * @param Set ids The Edit-session drawable ids to freeze, or empty to thaw. + */ + fun setEditMeshFrozen(ids: Set) + + /** + * Pushes the latest model after a committed edit or undo/redo (draw order, mesh preview, visibility). + * + * @param PuppetModel model The current model. + */ + fun setModel(model: PuppetModel) + + /** + * Pushes the atlas page set the current model's placements render from. + * + * The session owns the effective pages now - a repack composes new ones and undo brings the old + * ones back - so the pages arrive through a seam like the model does, instead of being fixed at + * construction. The engine swaps GPU pages and re-stamps every resident's binding as one + * operation, and applies an atlas-CHANGING model only together with the binding composed for it + * (see [AtlasPageBinding]). + * + * @param AtlasPageBinding binding The pages plus the atlas value they belong to. + */ + fun setAtlasPages(binding: AtlasPageBinding) + + /** + * Sets the color selected drawables are tinted toward (0..1 sRGB components, from settings). + * + * @param Float red The red component. + * @param Float green The green component. + * @param Float blue The blue component. + */ + fun setSelectionHighlightColor(red: Float, green: Float, blue: Float) + + /** + * Sets the color the active drawable is tinted toward (0..1 sRGB components, from settings), distinct + * from the shared selection highlight so the active target of a multi-selection reads apart. + * + * @param Float red The red component. + * @param Float green The green component. + * @param Float blue The blue component. + */ + fun setActiveSelectionHighlightColor(red: Float, green: Float, blue: Float) + + /** + * Hit-tests the front-most opaque drawable under the cursor, or null on empty canvas. + * + * @param String areaId The clicked area. + * @param Float cursorXpx The cursor x in viewport pixels. + * @param Float cursorYpx The cursor y in viewport pixels. + * @return DrawableId? The hit drawable, or null. + */ + fun pickAt(areaId: String, cursorXpx: Float, cursorYpx: Float): DrawableId? + + /** + * Hit-tests every opaque drawable under the cursor, front-to-back (the overlap picker's rows). + * + * @param String areaId The clicked area. + * @param Float cursorXpx The cursor x in viewport pixels. + * @param Float cursorYpx The cursor y in viewport pixels. + * @return List The candidates, front-to-back. + */ + fun pickAllAt(areaId: String, cursorXpx: Float, cursorYpx: Float): List + + /** + * Every visible drawable's world-space geometry centroid at the current pose - the mean of its posed + * world vertices, interleaved as [x, y]. Object-mode box / circle select caches this at gesture start + * (the pose is fixed for the whole drag) and tests each drawable's centroid against the region. World + * space, so it is area-independent: the caller projects with the area's own camera. Empty until the + * first frame's geometry lands. + * + * @return Map Per-drawable [x, y] world centroid. + */ + fun drawableWorldCentroids(): Map + + /** + * Renders the posed puppet into an image: what the 2D viewport draws, through [frame]'s camera at its + * size, over [backdrop], with no selection tint, gizmos, or other editor chrome. The pose, the shown + * drawables, and the artwork are the viewport's own at the moment the render thread takes the request. + * + * @param ImageFrame frame The camera and pixel size to render. + * @param FrameBackdrop backdrop What the puppet is drawn over. + * @return RasterImage? The image, straight alpha, top row first; null when the renderer cannot render + * (its context never came up, it was disposed, or the render failed). + */ + suspend fun renderImage(frame: ImageFrame, backdrop: FrameBackdrop): RasterImage? + + /** + * What a 2D viewport area shows right now, as a frame: its camera and its size in pixels. + * + * @param String areaId The area. + * @return ImageFrame? The area's frame, or null when it is not registered or has not been sized and fitted yet. + */ + fun areaView(areaId: String): ImageFrame? + + /** + * The shown drawables' world-space extent at the current pose - what the viewport draws, measured, where + * [fit] frames the rest pose. CPU-side, on the calling thread. + * + * @return ContentBounds? The extent, or null before the first pose or when nothing shown has geometry. + */ + fun visibleContentBounds(): ContentBounds? + + /** + * A drawable's cached art thumbnail (the overlap-picker row image), or null when untextured. + * + * @param DrawableId id The drawable. + * @return ImageBitmap? The thumbnail, or null. + */ + fun thumbnailFor(id: DrawableId): ImageBitmap? + + /** + * The thumbnail provider backing [thumbnailFor], for `LocalDrawableThumbnails`. + * + * @return DrawableThumbnailProvider The provider. + */ + fun thumbnails(): DrawableThumbnailProvider + + /** + * The owning part's display name for a drawable (the overlap-picker row label), or null when partless. + * + * @param DrawableId id The drawable. + * @return String? The part name, or null. + */ + fun partNameFor(id: DrawableId): String? + + /** + * A drawable's own display name (the other half of an overlap-picker row label), or null when the + * model holds no such drawable. + * + * @param DrawableId id The drawable. + * @return String? The drawable's name, or null. + */ + fun drawableNameFor(id: DrawableId): String? + + /** Stops the engine and releases its GPU resources; the service is unusable afterwards. */ + fun dispose() +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ScaleBoxGesture.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ScaleBoxGesture.kt new file mode 100644 index 0000000..8659f3d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ScaleBoxGesture.kt @@ -0,0 +1,82 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.AxisAlignedBounds +import org.umamo.edit.BoundsHandle +import org.umamo.edit.MeshTransforms +import org.umamo.edit.handleScaleFactors +import org.umamo.edit.unionSelectionBounds + +/** + * Frozen state for a Photoshop-style Scale-box drag over one or more captured position arrays that + * share a single AABB marquee (Object drawables, Edit verts, UV islands). + * + * @property BoundsHandle handle The handle under the pointer. + * @property AxisAlignedBounds startBounds Union AABB at press. + * @property List baseWorlds Per-source world positions at press. + * @property List> indices Per-source vertex indices to scale. + */ +internal class ScaleBoxDrag( + val handle: BoundsHandle, + val startBounds: AxisAlignedBounds, + val baseWorlds: List, + val indices: List>, +) + +/** + * Builds the union AABB over [worlds] restricted to [indices] (same length lists). + * + * @param List worlds Per-source interleaved positions. + * @param List> indices Per-source cover sets. + * @return AxisAlignedBounds The union bounds. + */ +internal fun scaleBoxBounds(worlds: List, indices: List>): AxisAlignedBounds = + unionSelectionBounds(worlds.zip(indices) { positions, cover -> positions to cover }) + +/** + * Applies a handle drag to every captured source, returning new world arrays. Shared factors / pivot + * so multi-drawable Object Scale stays one marquee. + * + * @param ScaleBoxDrag drag The frozen press state. + * @param Float targetX Pointer world x. + * @param Float targetY Pointer world y. + * @param Boolean uniform Shift: keep aspect on corners. + * @param Boolean fromCenter Alt: scale about bounds center. + * @return List Transformed world arrays (same order as [ScaleBoxDrag.baseWorlds]). + */ +internal fun driveScaleBoxWorlds( + drag: ScaleBoxDrag, + targetX: Float, + targetY: Float, + uniform: Boolean, + fromCenter: Boolean, +): List { + val (factorX, factorY, pivot) = + handleScaleFactors(drag.startBounds, drag.handle, targetX, targetY, uniform, fromCenter) + if (factorX == 1f && factorY == 1f) { + return drag.baseWorlds + } + return drag.baseWorlds.mapIndexed { index, positions -> + MeshTransforms.scaleVerticesAxis( + positions, + drag.indices[index], + factorX, + factorY, + pivot.first, + pivot.second, + ) + } +} + +/** + * Live AABB of [worlds] for drawing the marquee after a drag (or a zero box when empty). + * + * @param List worlds Current world arrays. + * @param List> indices Cover sets. + * @return AxisAlignedBounds Bounds to draw. + */ +internal fun liveScaleBoxBounds(worlds: List, indices: List>): AxisAlignedBounds { + if (worlds.isEmpty()) { + return AxisAlignedBounds(0f, 0f, 0f, 0f) + } + return scaleBoxBounds(worlds, indices) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/SessionRequestHandlers.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/SessionRequestHandlers.kt new file mode 100644 index 0000000..323d6f0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/SessionRequestHandlers.kt @@ -0,0 +1,589 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshChange +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshSelectionOps +import org.umamo.edit.MeshTopology +import org.umamo.edit.MeshTopologyOps +import org.umamo.edit.MeshTransforms +import org.umamo.edit.NoticePlacement +import org.umamo.edit.SelectionTarget +import org.umamo.edit.SnapKind +import org.umamo.edit.UvCursor +import org.umamo.edit.UvSnapKind +import org.umamo.edit.eligibleTransformDrawables +import org.umamo.edit.isPoseNeutral +import org.umamo.edit.selectableOf +import org.umamo.edit.snapToGrid +import org.umamo.edit.snapToWorldGrid +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.DrawableId +import org.umamo.ui.transform.captureDrawableWorld +import kotlin.math.roundToInt + +/* + * The bodies of the session-request handlers the gizmo overlays collect: keymap commands that carry + * no pointer (Select Linked, Alt+Q switch-mesh, Rip, the Shift+S snaps) land on the session's request + * flows, and only the overlay knows the pointer position and the projected geometry to execute them + * against. Each overlay keeps a thin, area-gated collector; the work lives here as plain functions, + * testable without Compose. + */ + +/** + * Select Linked (Blender's L / Ctrl+L): flood the mesh connectivity from the element under the + * pointer (or from every selected element) and union the islands into the selection in the current + * domain, as one undo step. Takes the geometry-source-agnostic gizmo records, so the Edit overlay + * (world-posed shapes) and the UV editor (display-mapped texture coordinates) share the flood - UV + * islands ARE topology islands, since UVs share the vertex index space. + * + * @param EditorSession session The session owning the selection. + * @param List geometries The shown meshes' gizmo geometry. + * @param Boolean fromSelection True to flood from every selected element (Ctrl+L); false to flood + * from the element under the pointer (L). + * @param Offset pointer The pointer in area-local pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ +internal fun handleSelectLinkedRequest( + session: EditorSession, + geometries: List, + fromSelection: Boolean, + pointer: Offset, + camera: ViewportCamera, + size: IntSize, +) { + var selection = session.meshSelection.value + if (fromSelection) { + for (geometry in geometries) { + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(geometry.drawableId), geometry.indices) + if (covered.isEmpty()) { + continue + } + val adjacency = MeshTopology.buildVertexAdjacency(geometry.positions.size / 2, geometry.indices) + val reached = HashSet() + for (seedVertex in covered) { + if (seedVertex !in reached) { + reached.addAll(MeshTopology.connectedVertices(adjacency, seedVertex)) + } + } + selection = MeshSelectionOps.selectLinked(selection, geometry.drawableId, reached, geometry.indices) + } + } else { + val hit = hitTestMeshes(selection.selectMode, geometries, pointer, camera, size) ?: return + val geometry = geometries.firstOrNull { candidate -> candidate.drawableId == hit.drawableId } ?: return + val seedVertex = MeshTopology.coveredVertexIndices(setOf(hit.element), geometry.indices).firstOrNull() ?: return + val adjacency = MeshTopology.buildVertexAdjacency(geometry.positions.size / 2, geometry.indices) + selection = + MeshSelectionOps.selectLinked(selection, hit.drawableId, MeshTopology.connectedVertices(adjacency, seedVertex), geometry.indices) + } + session.setMeshSelection(selection) +} + +/** + * Alt+Q: switch the edited mesh to the drawable under the pointer. One candidate switches directly; + * a stack opens the overlap-picker popup (the same picker Object mode's Alt-click uses), so the + * rigger chooses by name and thumbnail instead of blind-cycling through the layers. + * + * @param EditorSession session The session owning the mesh selection. + * @param PuppetViewportService service The render service (the GPU pick). + * @param String areaId The requesting overlay's area (the pick target). + * @param Offset pointer The pointer in area-local pixels. + * @param Function onOverlapRequest Opens the overlap-picker popup for 2+ stacked candidates. + */ +internal fun handleSwitchEditDrawableRequest( + session: EditorSession, + service: PuppetViewportService, + areaId: String, + pointer: Offset, + onOverlapRequest: (Offset, List) -> Unit, +) { + val model = session.model.value + val candidates = + service.pickAllAt(areaId, pointer.x, pointer.y) + .filter { candidate -> + model.drawables.any { drawable -> drawable.id == candidate.id && drawable.mesh != null } && + model.selectableOf(SelectionTarget.Drawable(candidate.id)) + } + when { + candidates.isEmpty() -> return + // The only thing under the cursor is the mesh already being edited: switching to it + // would wipe the element selection for nothing. + candidates.size == 1 && candidates.single().id == session.meshSelection.value.activeDrawableId -> return + candidates.size == 1 -> session.switchEditDrawable(candidates.single().id) + else -> onOverlapRequest(pointer, candidates) + } +} + +/** + * Rip (Blender's V): duplicate the covered vertices and re-point the triangles on the pointer's side + * at the copies, then auto-grab so they pull away under the pointer. The side rule: a triangle + * follows the copies when its screen centroid sits nearer the pointer than the covered median does. + * + * @param EditorSession session The session owning the mesh selection and topology commits. + * @param List geometries The session meshes' live geometry. + * @param String areaId The collecting overlay's area id - the rip runs under this viewport's + * pointer, so its auto-grab latches with it as the initiating area. + * @param Offset pointer The pointer in area-local pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ +internal fun handleRipRequest( + session: EditorSession, + geometries: List, + areaId: String, + pointer: Offset, + camera: ViewportCamera, + size: IntSize, +) { + val selection = session.meshSelection.value + val ripDrawableId = selection.activeDrawableId ?: return + val geometry = geometries.firstOrNull { candidate -> candidate.drawableId == ripDrawableId } ?: return + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(ripDrawableId), geometry.mesh.indices) + if (covered.isEmpty()) { + return + } + var coveredSumX = 0f + var coveredSumY = 0f + for (vertexIndex in covered) { + coveredSumX += geometry.worldPosed[vertexIndex * 2] + coveredSumY += geometry.worldPosed[vertexIndex * 2 + 1] + } + val medianScreen = worldToScreen(coveredSumX / covered.size, coveredSumY / covered.size, camera, size) + val medianDistance = (medianScreen - pointer).getDistance() + val result = + MeshTopologyOps.ripElements(geometry.mesh, covered) { triangleIndex -> + val cornerA = geometry.mesh.indices[triangleIndex * 3] + val cornerB = geometry.mesh.indices[triangleIndex * 3 + 1] + val cornerC = geometry.mesh.indices[triangleIndex * 3 + 2] + val centroidScreen = + worldToScreen( + (geometry.worldPosed[cornerA * 2] + geometry.worldPosed[cornerB * 2] + geometry.worldPosed[cornerC * 2]) / 3f, + (geometry.worldPosed[cornerA * 2 + 1] + geometry.worldPosed[cornerB * 2 + 1] + geometry.worldPosed[cornerC * 2 + 1]) / 3f, + camera, + size, + ) + (centroidScreen - pointer).getDistance() < medianDistance + } + if (result == null) { + session.emitNotice("notice.rip.nothing", NoticePlacement.NearCursor) + return + } + session.commitMeshTopology("change.mesh.rip", ripDrawableId, result) + session.beginMeshOperator(MeshOperatorKind.Grab, areaId, suppressProportional = true) +} + +/** + * Executes the geometry-dependent Shift+S snaps for Edit mode: the cursor moves read the covered + * world median, and the selection moves ride the same movement-transfer pipeline as a finished Grab + * (one undo step). An unplaced cursor snaps from the world origin, its conceptual resting place. + * + * @param EditorSession session The session owning the selection, cursor, and commits. + * @param List geometries The session meshes' live geometry. + * @param SnapKind kind The requested snap. + */ +internal fun handleEditSnapRequest( + session: EditorSession, + geometries: List, + kind: SnapKind, +) { + val selection = session.meshSelection.value + val coveredByMesh = + geometries.mapNotNull { geometry -> + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(geometry.drawableId), geometry.mesh.indices) + if (covered.isEmpty()) null else geometry to covered + } + if (coveredByMesh.isEmpty()) { + return + } + var coveredSumX = 0f + var coveredSumY = 0f + var coveredCount = 0 + for ((geometry, covered) in coveredByMesh) { + for (vertexIndex in covered) { + coveredSumX += geometry.worldPosed[vertexIndex * 2] + coveredSumY += geometry.worldPosed[vertexIndex * 2 + 1] + coveredCount++ + } + } + val medianX = coveredSumX / coveredCount + val medianY = coveredSumY / coveredCount + // The active element's own median (its covered vertices), or null when nothing is active. + val active = selection.activeElement + val activeGeometry = active?.let { candidate -> geometries.firstOrNull { it.drawableId == candidate.drawableId } } + val activeMedian = + if (active != null && activeGeometry != null) { + val activeCovered = MeshTopology.coveredVertexIndices(setOf(active.element), activeGeometry.mesh.indices) + if (activeCovered.isNotEmpty()) MeshTransforms.medianPivot(activeGeometry.worldPosed, activeCovered) else null + } else { + null + } + val model = session.model.value + val cursor = session.cursor2dOrWorldOrigin() + when (kind) { + SnapKind.CursorToSelected -> session.setCursor2d(medianX, medianY) + SnapKind.CursorToActive -> { + // With nothing active the cursor falls back to the whole selection's median. + val target = activeMedian ?: (medianX to medianY) + session.setCursor2d(target.first, target.second) + } + else -> { + // Selection to Active with nothing active has no target: a silent no-op (Blender + // parity), never an empty history step. + if (kind == SnapKind.SelectionToActive && activeMedian == null) { + return + } + val newPositionsByDrawable = LinkedHashMap(coveredByMesh.size) + val movedIndicesByDrawable = LinkedHashMap>(coveredByMesh.size) + for ((geometry, covered) in coveredByMesh) { + val world = geometry.worldPosed + val transformedWorld = + when (kind) { + // Every covered vertex lands ON the cursor (Blender's pile-up semantics). + SnapKind.SelectionToCursor -> + MeshTransforms.collapseVertices(world, covered, cursor.worldX, cursor.worldZ) + + // A rigid translate: the covered median lands on the cursor, offsets kept. + SnapKind.SelectionToCursorOffset -> + MeshTransforms.translateVertices(world, covered, cursor.worldX - medianX, cursor.worldZ - medianY) + + // Each covered vertex rounds to its own nearest grid point (the finest subdivision). + SnapKind.SelectionToGrid -> + world.copyOf().also { positions -> + val step = session.gridConfig.value.snapStep + for (vertexIndex in covered) { + val (snappedX, snappedZ) = model.snapToWorldGrid(positions[vertexIndex * 2], positions[vertexIndex * 2 + 1], step) + positions[vertexIndex * 2] = snappedX + positions[vertexIndex * 2 + 1] = snappedZ + } + } + + // Every covered vertex lands ON the active element's median - the same + // pile-up as Selection to Cursor, not a rigid translate (Blender parity). + SnapKind.SelectionToActive -> + if (activeMedian != null) { + MeshTransforms.collapseVertices(world, covered, activeMedian.first, activeMedian.second) + } else { + world + } + + // The cursor moves were handled above; nothing else reaches here. + SnapKind.CursorToSelected, SnapKind.CursorToActive -> world + } + newPositionsByDrawable[geometry.drawableId] = geometry.worldToBase(transformedWorld, covered) + movedIndicesByDrawable[geometry.drawableId] = covered.toList() + } + // A snap relocates geometry without scaling or turning it, so it files under the move label. + session.commitMeshPositions( + MeshChange.TransformVertices(movedIndicesByDrawable, MeshOperatorKind.Grab), + newPositionsByDrawable, + ) + } + } +} + +/** + * Executes the geometry-dependent Shift+S snaps for Object mode over the selected drawables' + * centroids: the cursor moves read them, the selection moves translate whole drawables through the + * movement-transfer pipeline (one undo step). The same pose-neutral guard as a transform applies to + * the selection moves - writing a deformed capture back through the warp inverse corrupts rest meshes. + * + * @param EditorSession session The session owning the selection, cursor, and commits. + * @param SnapKind kind The requested snap. + */ +internal fun handleObjectSnapRequest(session: EditorSession, kind: SnapKind) { + val model = session.model.value + val pose = session.pose.value + val eligibleIds = org.umamo.edit.eligibleTransformDrawables(session.selection.value, model) ?: return + // Per-drawable posed geometry, the same capture a transform freezes. + // A drawable with a hidden ancestor captures as null - skip it, the rest still snap. + val geometries = eligibleIds.mapNotNull { drawableId -> captureDrawableWorld(model, pose, drawableId) } + if (geometries.isEmpty()) { + return + } + val ids = geometries.map { geometry -> geometry.drawableId } + val worldList = geometries.map { geometry -> geometry.world } + val combined = MeshTransforms.combinedCentroid(worldList) + val activeId = (session.selection.value.active as? SelectionTarget.Drawable)?.id + val activeIndex = activeId?.let { candidate -> ids.indexOf(candidate) } ?: -1 + val activeCentroid = + if (activeIndex >= 0) { + MeshTransforms.medianPivot(worldList[activeIndex], (0 until worldList[activeIndex].size / 2).toSet()) + } else { + combined + } + val cursor = session.cursor2dOrWorldOrigin() + when (kind) { + SnapKind.CursorToSelected -> session.setCursor2d(combined.first, combined.second) + SnapKind.CursorToActive -> session.setCursor2d(activeCentroid.first, activeCentroid.second) + else -> { + if (!isPoseNeutral(model, pose)) { + session.emitNotice("notice.transform.deformed", NoticePlacement.NearCursor) + return + } + val newPositionsByDrawable = LinkedHashMap(ids.size) + for (geometry in geometries) { + val world = geometry.world + val allIndices = geometry.allIndices + val ownCentroid = MeshTransforms.medianPivot(world, allIndices) + val (deltaX, deltaY) = + when (kind) { + // Each drawable's centroid lands ON the target (Blender's pile-up semantics)... + SnapKind.SelectionToCursor -> (cursor.worldX - ownCentroid.first) to (cursor.worldZ - ownCentroid.second) + SnapKind.SelectionToActive -> (activeCentroid.first - ownCentroid.first) to (activeCentroid.second - ownCentroid.second) + SnapKind.SelectionToGrid -> + model.snapToWorldGrid(ownCentroid.first, ownCentroid.second, session.gridConfig.value.snapStep).let { (snappedX, snappedZ) -> + (snappedX - ownCentroid.first) to (snappedZ - ownCentroid.second) + } + + // ...while Keep Offset translates the whole selection rigidly by one shared delta. + SnapKind.SelectionToCursorOffset -> (cursor.worldX - combined.first) to (cursor.worldZ - combined.second) + + // The cursor moves were handled above; nothing else reaches here. + SnapKind.CursorToSelected, SnapKind.CursorToActive -> 0f to 0f + } + if (deltaX == 0f && deltaY == 0f) { + continue + } + val transformedWorld = MeshTransforms.translateVertices(world, allIndices, deltaX, deltaY) + newPositionsByDrawable[geometry.drawableId] = geometry.worldToBase(transformedWorld, allIndices) + } + if (newPositionsByDrawable.isNotEmpty()) { + session.commitObjectPositions( + MeshChange.TransformDrawables(newPositionsByDrawable.keys.toList(), MeshOperatorKind.Grab), + newPositionsByDrawable, + ) + } + } + } +} + +/** + * Executes the UV editor's Shift+S snaps over the shown surface's texture coordinates: the cursor + * moves read the UV cursor or the covered median and write the UV cursor directly, and the selection + * moves transform the covered vertices in the texel display space and commit ONE TransformUvs step (the + * same commit path a finished modal UV gesture uses). All math is identity display space - no deformer + * inverse, no movement transfer - since UVs live in one flat space; only the covered vertices of the + * meshes on the shown surface participate (the overlay only shows one surface at a time, exactly as the + * modal capture scopes). + * + * The grid snaps target the drawn UV grid: its major lines fall on the shown image's tile and the minor + * lines subdivide it by the document grid subdivisions, so a grid snap rounds display coordinates to the + * surface extent / subdivisions, anchored at the image origin. The pixel snaps round to the nearest + * integer texel, which is a pixel corner in this texel-unit space - the artwork-edge-accuracy target. + * + * @param EditorSession session The session owning the selection, the UV cursor, and the commit. + * @param List geometries The shown meshes' display-space gizmo geometry. + * @param UvEditFrame frame The shown surface's texel size plus how a coordinate over it reaches the + * stored texture coordinates. Snap-to-pixel therefore targets the SHOWN surface's texel lattice - + * an atlas texel over a page, an artwork texel over a source layer - which is the right target in + * each, though a placement that scales makes them different lattices. + * @param UvSnapKind kind The requested snap. + */ +internal fun handleUvSnapRequest( + session: EditorSession, + geometries: List, + frame: UvEditFrame, + kind: UvSnapKind, +) { + val selection = session.meshSelection.value + val coveredByMesh = + geometries.mapNotNull { geometry -> + val covered = MeshTopology.coveredVertexIndices(selection.elementsOf(geometry.drawableId), geometry.indices) + if (covered.isEmpty()) null else geometry to covered + } + + // The UV grid subdivides the shown image (its major lines are the image tile, minor lines the document + // subdivisions), anchored at the image origin - so a grid snap rounds to the surface extent / + // subdivisions in display space, targeting the same lines the backdrop draws. + val subdivisions = session.gridConfig.value.subdivisions.coerceAtLeast(1) + val gridStepX = frame.displayWidth.toFloat() / subdivisions + val gridStepY = frame.displayHeight.toFloat() / subdivisions + + // The UV cursor in display space; an unplaced cursor rests at the stored origin (UV 0,0), the mesh + // snap's "an unplaced cursor snaps from its resting place" rule in this space. + val cursor = session.uvCursor.value ?: UvCursor(0f, 0f) + val (cursorDisplayX, cursorDisplayY) = frame.displayAt(cursor.u, cursor.v) + + // The covered vertices' median in display space, across the shown meshes. + var coveredSumX = 0f + var coveredSumY = 0f + var coveredCount = 0 + for ((geometry, covered) in coveredByMesh) { + for (vertexIndex in covered) { + coveredSumX += geometry.positions[vertexIndex * 2] + coveredSumY += geometry.positions[vertexIndex * 2 + 1] + coveredCount++ + } + } + + when (kind) { + UvSnapKind.CursorToPixels -> { + val (cursorU, cursorV) = + frame.storedUvAt(cursorDisplayX.roundToInt().toFloat(), cursorDisplayY.roundToInt().toFloat()) + session.setUvCursor(cursorU, cursorV) + } + + UvSnapKind.CursorToGrid -> { + val (cursorU, cursorV) = + frame.storedUvAt(snapToGrid(cursorDisplayX, 0f, gridStepX), snapToGrid(cursorDisplayY, 0f, gridStepY)) + session.setUvCursor(cursorU, cursorV) + } + + UvSnapKind.CursorToSelected -> { + // Nothing selected on the shown surface: no median to move the cursor to (a silent no-op). + if (coveredCount == 0) { + return + } + val (cursorU, cursorV) = frame.storedUvAt(coveredSumX / coveredCount, coveredSumY / coveredCount) + session.setUvCursor(cursorU, cursorV) + } + + UvSnapKind.SelectionToPixels, + UvSnapKind.SelectionToCursor, + UvSnapKind.SelectionToCursorOffset, + UvSnapKind.SelectionToGrid, + -> { + if (coveredCount == 0) { + return + } + val medianX = coveredSumX / coveredCount + val medianY = coveredSumY / coveredCount + val model = session.model.value + val newUvsByDrawable = LinkedHashMap(coveredByMesh.size) + val movedIndicesByDrawable = LinkedHashMap>(coveredByMesh.size) + for ((geometry, covered) in coveredByMesh) { + val display = geometry.positions + val transformedDisplay = + when (kind) { + // Every covered vertex lands ON the cursor (Blender's pile-up semantics). + UvSnapKind.SelectionToCursor -> + MeshTransforms.collapseVertices(display, covered, cursorDisplayX, cursorDisplayY) + + // A rigid translate: the covered median lands on the cursor, offsets kept. + UvSnapKind.SelectionToCursorOffset -> + MeshTransforms.translateVertices(display, covered, cursorDisplayX - medianX, cursorDisplayY - medianY) + + // Each covered vertex rounds to its own nearest grid line (page / subdivisions). + UvSnapKind.SelectionToGrid -> + display.copyOf().also { positions -> + for (vertexIndex in covered) { + positions[vertexIndex * 2] = snapToGrid(positions[vertexIndex * 2], 0f, gridStepX) + positions[vertexIndex * 2 + 1] = snapToGrid(positions[vertexIndex * 2 + 1], 0f, gridStepY) + } + } + + // Each covered vertex rounds to its nearest pixel corner (an integer texel boundary). + UvSnapKind.SelectionToPixels -> + display.copyOf().also { positions -> + for (vertexIndex in covered) { + positions[vertexIndex * 2] = positions[vertexIndex * 2].roundToInt().toFloat() + positions[vertexIndex * 2 + 1] = positions[vertexIndex * 2 + 1].roundToInt().toFloat() + } + } + + // The cursor moves were handled above; nothing else reaches here. + UvSnapKind.CursorToPixels, UvSnapKind.CursorToSelected, UvSnapKind.CursorToGrid -> display + } + // Only the covered vertices are written; untouched ones keep their exact stored values + // (see storedUvsWithMoved). + val currentUvs = model.drawables.firstOrNull { drawable -> drawable.id == geometry.drawableId }?.mesh?.uvs ?: continue + newUvsByDrawable[geometry.drawableId] = storedUvsWithMoved(currentUvs, covered, transformedDisplay, frame) + movedIndicesByDrawable[geometry.drawableId] = covered.toList() + } + if (newUvsByDrawable.isNotEmpty()) { + session.commitMeshUvs(MeshChange.TransformUvs(movedIndicesByDrawable, MeshOperatorKind.Grab), newUvsByDrawable) + } + } + } +} + +/** + * Reverse Positions for Edit-mode mesh selection: among each mesh's covered verts (sorted by index), + * pairwise-swap one world axis (0↔last, 1↔last-1, …), then write rest via worldToBase. + * + * @param EditorSession session The session owning selection and commits. + * @param List geometries The session meshes' live posed geometry. + * @param Boolean mirrorHorizontal True to swap x only; false to swap y only. + */ +internal fun handleEditMirrorRequest( + session: EditorSession, + geometries: List, + mirrorHorizontal: Boolean, +) { + if (session.mode.value != EditorMode.Edit) { + return + } + val selection = session.meshSelection.value + if (selection.isEmpty) { + return + } + val newPositionsByDrawable = LinkedHashMap() + val movedIndicesByDrawable = LinkedHashMap>() + for (geometry in geometries) { + val covered = + MeshTopology.coveredVertexIndices(selection.elementsOf(geometry.drawableId), geometry.mesh.indices) + if (covered.size < 2) { + continue + } + val ordered = covered.sorted() + val swappedWorld = + MeshTransforms.reverseSwapPositions(geometry.worldPosed, ordered, horizontal = mirrorHorizontal) + newPositionsByDrawable[geometry.drawableId] = geometry.worldToBase(swappedWorld, covered) + movedIndicesByDrawable[geometry.drawableId] = ordered + } + if (newPositionsByDrawable.isEmpty()) { + return + } + session.commitMeshPositions( + MeshChange.MirrorVertices(movedIndicesByDrawable, mirrorHorizontal), + newPositionsByDrawable, + ) +} + +/** + * Reverse Positions for Object-mode drawables: pairwise-swap one axis of every vertex (index order) on + * each eligible mesh. Same pose-neutral guard as G / S / R. + * + * @param EditorSession session The session owning selection and commits. + * @param Boolean mirrorHorizontal True to swap x only; false to swap y only. + * @return Boolean True when this handler owned the selection; false when a warp lattice should handle it. + */ +internal fun handleObjectMirrorRequest(session: EditorSession, mirrorHorizontal: Boolean): Boolean { + if (session.mode.value != EditorMode.Object) { + return false + } + val model = session.model.value + val pose = session.pose.value + val eligibleIds = eligibleTransformDrawables(session.selection.value, model) ?: return false + if (!isPoseNeutral(model, pose)) { + session.emitNotice("notice.transform.deformed", NoticePlacement.NearCursor) + return true + } + val geometries = eligibleIds.mapNotNull { drawableId -> captureDrawableWorld(model, pose, drawableId) } + if (geometries.isEmpty()) { + session.emitNotice("notice.transform.onlyDrawables", NoticePlacement.NearCursor) + return true + } + val newPositionsByDrawable = LinkedHashMap(geometries.size) + for (geometry in geometries) { + val ordered = (0 until geometry.world.size / 2).toList() + if (ordered.size < 2) { + continue + } + val swappedWorld = + MeshTransforms.reverseSwapPositions(geometry.world, ordered, horizontal = mirrorHorizontal) + newPositionsByDrawable[geometry.drawableId] = geometry.worldToBase(swappedWorld, geometry.allIndices) + } + if (newPositionsByDrawable.isNotEmpty()) { + session.commitObjectPositions( + MeshChange.MirrorDrawables(newPositionsByDrawable.keys.toList(), mirrorHorizontal), + newPositionsByDrawable, + ) + } + return true +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/TransformAdjustRegistration.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/TransformAdjustRegistration.kt new file mode 100644 index 0000000..6946de0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/TransformAdjustRegistration.kt @@ -0,0 +1,220 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.EditorSession +import org.umamo.edit.ModalTransformCapture +import org.umamo.edit.ProportionalEditState +import org.umamo.edit.ProportionalRows +import org.umamo.edit.TransformGestureParameters +import org.umamo.edit.TransformParameterKeys +import org.umamo.edit.TransformRowSpace +import org.umamo.edit.floatValue +import org.umamo.edit.rederiveProportionalHalos +import org.umamo.edit.slideParameters +import org.umamo.edit.transformGestureParametersOf +import org.umamo.edit.transformParameters +import org.umamo.edit.withMeshPositions +import org.umamo.edit.withMeshUvs +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.transform.DrawableWorldGeometry + +/* + * The modal transforms' registrations on the operation settings strip - the half that needs geometry. + * The rows and what they mean live in :edit (TransformAdjust.kt, next to the merge's); what stays here + * is the rerun each gesture needs, because a rerun replays the RETAINED capture through the viewport's + * frozen world geometry (DrawableWorldGeometry, which needs :render's evaluator and so cannot sit in + * :edit) or through the UV editor's frozen frame, and applies the operator math this package owns. + * Three gestures share the shape: the Edit-mode mesh transform and the Object-mode drawable transform + * in the 2D viewport, and the Edit-mode texture-coordinate transform in the UV editor. + */ + +/** + * Registers the Edit-mode mesh transform that just committed as the session's adjustable operation. + * Call it right after the commit and before the operator clears (its teardown drops the capture the + * caller still holds). An adjustment re-derives the halos on the RETAINED [transform] from its frozen + * positions under the edited proportional rows, applies the edited numbers per mesh, inverts each + * world shape back onto the base mesh through the frozen [geometryById], lands the result over the + * gesture's own step from the record's base, and hands the proportional state back to + * [onProportional] so the next gesture starts from it. Synchronous: an evaluation is the + * per-pointer-frame cost. + * + * @param EditorSession session The session the gesture committed into. + * @param String areaId The viewport the gesture ran in (where the strip shows). + * @param ModalTransformCapture transform The frozen capture. + * @param Map geometryById Each moving drawable's frozen world geometry. + * @param TransformGestureParameters parameters The numbers the gesture landed with. + * @param ProportionalRows? proportional The proportional rows, or null when the gesture took no weights. + * @param Function onProportional Receives the adjusted proportional state (null for + * off) after each landed adjustment; unused when [proportional] is null. + * @return AdjustableOperation? The record, or null when the session refused the registration or the + * operator has no rows. + */ +internal fun registerMeshTransformAdjustment( + session: EditorSession, + areaId: String, + transform: ModalTransformCapture, + geometryById: Map, + parameters: TransformGestureParameters, + proportional: ProportionalRows?, + onProportional: (ProportionalEditState?) -> Unit, +): AdjustableOperation? { + val kind = transform.operatorKind + val rows = transformParameters(kind, parameters, TransformRowSpace.World, proportional) + if (rows.isEmpty()) { + return null + } + return session.registerAdjustableOperation(session.model.value, areaId, rows) { record -> + val adjusted = transformGestureParametersOf(kind, TransformRowSpace.World, record.parameters) + val proportionalRows = rederiveProportionalHalos(transform, record.parameters) + val landed = + transform.entries.fold(record.baseSnapshot.model) { model, entry -> + val geometry = geometryById[entry.drawableId] ?: return@fold model + val world = applyOperator(kind, entry.positions, entry.groups, adjusted, entry.influence) + model.withMeshPositions(entry.drawableId, geometry.worldToBase(world, entry.movedIndices)) + } + if (session.amendLastCommit(record, landed) && proportionalRows != null) { + onProportional(proportionalRows.asState()) + } + } +} + +/** + * Registers the Vertex Slide that just committed as the session's adjustable operation, with its + * one Factor row. The rerun slides the same vertex along the same frozen edge by the row's factor + * from the record's base; the capture's other meshes stay where the base has them. + * + * @param EditorSession session The session the gesture committed into. + * @param String areaId The viewport the gesture ran in. + * @param ModalTransformCapture transform The frozen capture. + * @param Map geometryById Each moving drawable's frozen world geometry. + * @param DrawableId drawableId The mesh the sliding vertex lives in. + * @param Int vertexIndex The sliding vertex. + * @param Int neighborIndex The edge's far endpoint the slide landed toward. + * @param Float factor The landed factor. + * @return AdjustableOperation? The record, or null when the session refused the registration. + */ +internal fun registerSlideAdjustment( + session: EditorSession, + areaId: String, + transform: ModalTransformCapture, + geometryById: Map, + drawableId: DrawableId, + vertexIndex: Int, + neighborIndex: Int, + factor: Float, +): AdjustableOperation? = + session.registerAdjustableOperation(session.model.value, areaId, slideParameters(factor)) { record -> + val entry = transform.entries.firstOrNull { candidate -> candidate.drawableId == drawableId } ?: return@registerAdjustableOperation + val geometry = geometryById[drawableId] ?: return@registerAdjustableOperation + val adjustedFactor = record.parameters.floatValue(TransformParameterKeys.SLIDE_FACTOR, factor) + val world = slideVertexByFactor(entry.positions, vertexIndex, neighborIndex, adjustedFactor) + session.amendLastCommit(record, record.baseSnapshot.model.withMeshPositions(drawableId, geometry.worldToBase(world, entry.movedIndices))) + } + +/** + * Registers the Object-mode drawable transform that just committed as the session's adjustable + * operation: the mesh registration without proportional rows, each whole drawable inverted through + * its frozen geometry over every vertex. + * + * @param EditorSession session The session the gesture committed into. + * @param String areaId The viewport the gesture ran in. + * @param ModalTransformCapture transform The frozen capture. + * @param Map geometryById Each moving drawable's frozen world geometry. + * @param TransformGestureParameters parameters The numbers the gesture landed with. + * @return AdjustableOperation? The record, or null when the session refused the registration or the + * operator has no rows. + */ +internal fun registerObjectTransformAdjustment( + session: EditorSession, + areaId: String, + transform: ModalTransformCapture, + geometryById: Map, + parameters: TransformGestureParameters, +): AdjustableOperation? { + val kind = transform.operatorKind + val rows = transformParameters(kind, parameters, TransformRowSpace.World, proportional = null) + if (rows.isEmpty()) { + return null + } + return session.registerAdjustableOperation(session.model.value, areaId, rows) { record -> + val adjusted = transformGestureParametersOf(kind, TransformRowSpace.World, record.parameters) + val landed = + transform.entries.fold(record.baseSnapshot.model) { model, entry -> + val geometry = geometryById[entry.drawableId] ?: return@fold model + val world = applyOperator(kind, entry.positions, entry.groups, adjusted, emptyMap()) + model.withMeshPositions(entry.drawableId, geometry.worldToBase(world, entry.coveredIndices)) + } + session.amendLastCommit(record, landed) + } +} + +/** + * Registers the UV editor's texture-coordinate transform that just committed as the session's + * adjustable operation. The rows read in display texels; the rerun applies the edited numbers over + * the frozen display coordinates and writes only the moved vertices back through [frame] onto the + * BASE model's stored coordinates (the untouched ones stay bit-identical, as the commit keeps them). + * The proportional radius is in texels too, so [onProportional] receives it separately from the + * state for the caller to place where the editor keeps its radius. + * + * @param EditorSession session The session the gesture committed into. + * @param String areaId The UV editor the gesture ran in. + * @param ModalTransformCapture transform The frozen capture (display-space positions). + * @param UvEditFrame frame The space the gesture was authored in. + * @param TransformGestureParameters parameters The numbers the gesture landed with, in texels. + * @param ProportionalRows? proportional The proportional rows (radius in texels), or null. + * @param Function onProportional Receives the adjusted proportional state (null for + * off) and the row's texel radius after each landed adjustment; unused when [proportional] is null. + * @return AdjustableOperation? The record, or null when the session refused the registration or the + * operator has no rows. + */ +internal fun registerUvTransformAdjustment( + session: EditorSession, + areaId: String, + transform: ModalTransformCapture, + frame: UvEditFrame, + parameters: TransformGestureParameters, + proportional: ProportionalRows?, + onProportional: (ProportionalEditState?, Float) -> Unit, +): AdjustableOperation? { + val kind = transform.operatorKind + val rows = transformParameters(kind, parameters, TransformRowSpace.UvDisplay, proportional) + if (rows.isEmpty()) { + return null + } + return session.registerAdjustableOperation(session.model.value, areaId, rows) { record -> + val adjusted = transformGestureParametersOf(kind, TransformRowSpace.UvDisplay, record.parameters) + val proportionalRows = rederiveProportionalHalos(transform, record.parameters) + val landed = + transform.entries.fold(record.baseSnapshot.model) { model, entry -> + val display = applyOperator(kind, entry.positions, entry.groups, adjusted, entry.influence) + model.withMeshUvs(entry.drawableId, storedUvsForRerun(model, entry.drawableId, entry.movedIndices, display, frame)) + } + if (session.amendLastCommit(record, landed) && proportionalRows != null) { + onProportional(proportionalRows.asState(), proportionalRows.radius) + } + } +} + +/** + * The stored coordinates a rerun commits for one mesh: the base model's current values with only the + * moved vertices overwritten - the commit's own discipline (see [storedUvsWithMoved]) - or, for a + * drawable the base holds no coordinates for, the whole transformed array converted. + * + * @param PuppetModel model The base model the rerun lands over. + * @param DrawableId drawableId The mesh. + * @param Set movedIndices The vertices the rerun moved. + * @param FloatArray display The transformed display coordinates. + * @param UvEditFrame frame The space the coordinates are in. + * @return FloatArray The coordinates to commit. + */ +private fun storedUvsForRerun( + model: PuppetModel, + drawableId: DrawableId, + movedIndices: Set, + display: FloatArray, + frame: UvEditFrame, +): FloatArray { + val storedUvs = model.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.mesh?.uvs + return if (storedUvs == null) frame.storedUvs(display) else storedUvsWithMoved(storedUvs, movedIndices, display, frame) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/TransformOperators.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/TransformOperators.kt new file mode 100644 index 0000000..b580d44 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/TransformOperators.kt @@ -0,0 +1,248 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshTransforms +import org.umamo.edit.ProportionalInfluence +import org.umamo.edit.RotationAngleTracker +import org.umamo.edit.TransformAxisConstraint +import org.umamo.edit.TransformGestureParameters +import org.umamo.edit.TransformPivotGroup +import org.umamo.edit.TransformPivots +import org.umamo.render.ViewportCamera +import kotlin.math.atan2 + +/** + * One modal gesture's pointer frame: everything the operator math needs to convert the screen-space + * gesture into world-space deltas, factors, and angles. Frozen per pointer event and shared by every + * mesh in the capture (the per-mesh loop varies only the geometry and pivot groups). This is also + * where Blender-style numeric input (G X 5 Enter) later lands: a typed override slots in here once + * and feeds the Edit, Object, and UV overlays alike. + * + * @property Pair anchor The world-space anchor factors / angles measure against. + * @property Offset start The pointer position at gesture start, in screen pixels. + * @property Offset current The current (wrap-continuous virtual) pointer, in screen pixels. + * @property TransformAxisConstraint? axisConstraint The axis lock, or null when unconstrained. + * @property ViewportCamera camera The area camera (world<->screen affine). + * @property IntSize size The area size in pixels. + */ +internal class TransformGestureFrame( + val anchor: Pair, + val start: Offset, + val current: Offset, + val axisConstraint: TransformAxisConstraint?, + val camera: ViewportCamera, + val size: IntSize, +) + +/** + * Resolves [frame] into the parameters [operator] applies: a Grab's translation, a Scale's factors, + * or a Rotate's accumulated angle, the rest at identity. Call it once per pointer frame, before the + * per-mesh loop - the Rotate branch advances [rotationTracker], and one advance per frame is what the + * accumulator expects. + * + * @param MeshOperatorKind operator The active operator. + * @param TransformGestureFrame frame The gesture's pointer frame. + * @param RotationAngleTracker rotationTracker The gesture's angle accumulator (Rotate only). + * @return TransformGestureParameters The resolved parameters. + */ +internal fun gestureParameters( + operator: MeshOperatorKind, + frame: TransformGestureFrame, + rotationTracker: RotationAngleTracker, +): TransformGestureParameters = + when (operator) { + MeshOperatorKind.Grab -> { + val (deltaX, deltaY) = gestureTranslation(frame) + TransformGestureParameters(deltaX, deltaY, 1f, 1f, 0f) + } + + MeshOperatorKind.Scale -> { + val (factorX, factorY) = gestureScaleFactors(frame) + TransformGestureParameters(0f, 0f, factorX, factorY, 0f) + } + + MeshOperatorKind.Rotate -> TransformGestureParameters(0f, 0f, 1f, 1f, gestureRotationRadians(frame, rotationTracker)) + + // Vertex Slide has its own edge projection (slideFactorAlongEdge); it never applies these. + MeshOperatorKind.VertexSlide -> TransformGestureParameters.IDENTITY + } + +/** + * The translation a Grab gesture applies, in the positions' units: the pointer's screen travel over + * the zoom, with the axis lock zeroing the constrained-out component (AxisX keeps horizontal movement, + * AxisZ keeps vertical - world y, the displayed Z axis per the Y+ forward, Z+ up convention). + * + * Shared by [gestureParameters] and the placement gizmo so the two cannot drift on sign or axis. + * + * @param TransformGestureFrame frame The gesture's pointer frame. + * @return Pair The (x, y) delta. + */ +internal fun gestureTranslation(frame: TransformGestureFrame): Pair { + val deltaX = if (frame.axisConstraint == TransformAxisConstraint.AxisZ) 0f else (frame.current.x - frame.start.x) / frame.camera.zoom + val deltaY = if (frame.axisConstraint == TransformAxisConstraint.AxisX) 0f else -(frame.current.y - frame.start.y) / frame.camera.zoom + return deltaX to deltaY +} + +/** + * The per-axis factors a Scale gesture applies: the pointer's distance from the anchor over its + * distance at gesture start (Blender measures against the transform center even with Individual + * Origins), with the axis lock pinning the constrained-out axis at 1. + * + * @param TransformGestureFrame frame The gesture's pointer frame. + * @return Pair The (x, y) factors. + */ +internal fun gestureScaleFactors(frame: TransformGestureFrame): Pair { + val anchorScreen = worldToScreen(frame.anchor.first, frame.anchor.second, frame.camera, frame.size) + val startDistance = (frame.start - anchorScreen).getDistance() + val currentDistance = (frame.current - anchorScreen).getDistance() + val factor = if (startDistance > 1e-3f) currentDistance / startDistance else 1f + val factorX = if (frame.axisConstraint == TransformAxisConstraint.AxisZ) 1f else factor + val factorY = if (frame.axisConstraint == TransformAxisConstraint.AxisX) 1f else factor + return factorX to factorY +} + +/** + * The angle a Rotate gesture applies about a pivot, in the positions' units: the pointer's angle about + * the anchor accumulated through [rotationTracker], negated out of screen space into the positions' + * sense - the value [MeshTransforms.rotateVertices] takes. Rotate has no axis to lock in 2D. + * + * @param TransformGestureFrame frame The gesture's pointer frame. + * @param RotationAngleTracker rotationTracker The gesture's angle accumulator. + * @return Float The rotation in radians. + */ +internal fun gestureRotationRadians(frame: TransformGestureFrame, rotationTracker: RotationAngleTracker): Float { + val anchorScreen = worldToScreen(frame.anchor.first, frame.anchor.second, frame.camera, frame.size) + val pointerAngle = atan2(frame.current.y - anchorScreen.y, frame.current.x - anchorScreen.x) + return -rotationTracker.advance(pointerAngle) +} + +/** + * The slide factor a pointer frame means along the edge from [vertexIndex] toward [neighborIndex]: the + * pointer projects onto the edge's screen direction and the parameter clamps between the endpoints + * (Blender's Shift+V, without the unclamped and even-slide variants). A degenerate on-screen edge + * (both endpoints under the same pixel) yields 0. + * + * @param FloatArray originalWorld The captured world positions. + * @param Int vertexIndex The sliding vertex. + * @param Int neighborIndex The edge's far endpoint. + * @param TransformGestureFrame frame The gesture's pointer frame (the virtual pointer projects). + * @return Float The factor in [0, 1]: 0 leaves the vertex in place, 1 lands it on the neighbor. + */ +internal fun slideFactorAlongEdge( + originalWorld: FloatArray, + vertexIndex: Int, + neighborIndex: Int, + frame: TransformGestureFrame, +): Float { + val vertexScreen = worldToScreen(originalWorld[vertexIndex * 2], originalWorld[vertexIndex * 2 + 1], frame.camera, frame.size) + val neighborScreen = worldToScreen(originalWorld[neighborIndex * 2], originalWorld[neighborIndex * 2 + 1], frame.camera, frame.size) + val axisX = neighborScreen.x - vertexScreen.x + val axisY = neighborScreen.y - vertexScreen.y + val lengthSquared = axisX * axisX + axisY * axisY + if (lengthSquared <= 1e-3f) { + return 0f + } + return (((frame.current.x - vertexScreen.x) * axisX + (frame.current.y - vertexScreen.y) * axisY) / lengthSquared).coerceIn(0f, 1f) +} + +/** + * Slides one vertex along the edge toward [neighborIndex] by [factor] of the edge's length - the + * application half of the Vertex Slide, shared by the drag (whose factor [slideFactorAlongEdge] + * projects from the pointer) and the operation settings strip's Factor row. + * + * @param FloatArray originalWorld The captured world positions. + * @param Int vertexIndex The sliding vertex. + * @param Int neighborIndex The edge's far endpoint. + * @param Float factor How far along the edge the vertex lands, clamped to [0, 1]. + * @return FloatArray A new positions array with the vertex slid. + */ +internal fun slideVertexByFactor( + originalWorld: FloatArray, + vertexIndex: Int, + neighborIndex: Int, + factor: Float, +): FloatArray { + val t = factor.coerceIn(0f, 1f) + return originalWorld.copyOf().also { positions -> + positions[vertexIndex * 2] = originalWorld[vertexIndex * 2] + (originalWorld[neighborIndex * 2] - originalWorld[vertexIndex * 2]) * t + positions[vertexIndex * 2 + 1] = + originalWorld[vertexIndex * 2 + 1] + (originalWorld[neighborIndex * 2 + 1] - originalWorld[vertexIndex * 2 + 1]) * t + } +} + +/** + * Applies the active modal operator to [originalWorld] by the resolved [parameters], producing a new + * world-posed array: Grab translates by the delta; Scale and Rotate work about each pivot group's + * pivot by the factors and the angle. The parameters come from a pointer frame during the drag + * ([gestureParameters], which owns the screen-to-world conversion and the rotation accumulator) or from + * the operation settings strip's rows after it, so an adjustment runs the very same math. + * + * Proportional editing adds [proportionalInfluences]: after the selected vertices transform at full + * strength through their pivot groups, each influenced unselected vertex takes the SAME gesture scaled + * by its falloff weight, anchored on the pivot of the group OWNING its nearest covered vertex - so + * with Individual Origins the halo turns with its island, while the shared-pivot modes keep anchoring + * on the gesture anchor (the single group's pivot). Factors and angles are still MEASURED against + * the frame anchor (Blender measures against the transform center even with Individual Origins). + * + * @param MeshOperatorKind operator The active operator. + * @param FloatArray originalWorld The world posed positions captured at gesture start. + * @param List groups The pivot groups covering the selected vertices. + * @param TransformGestureParameters parameters The delta / factors / angle to apply - shared by every + * mesh in the capture. + * @param Map proportionalInfluences The influenced unselected vertices + * (empty when proportional editing is off). + * @return FloatArray The transformed world positions. + */ +internal fun applyOperator( + operator: MeshOperatorKind, + originalWorld: FloatArray, + groups: List, + parameters: TransformGestureParameters, + proportionalInfluences: Map, +): FloatArray = + when (operator) { + MeshOperatorKind.Grab -> { + val deltaX = parameters.deltaX + val deltaY = parameters.deltaY + val moved = + groups.fold(originalWorld) { positions, group -> + MeshTransforms.translateVertices(positions, group.vertexIndices, deltaX, deltaY) + } + // A translation has no pivot, so the halo needs no per-group partition - one weighted pass. + MeshTransforms.translateVerticesWeighted(moved, proportionalInfluences.mapValues { entry -> entry.value.weight }, deltaX, deltaY) + } + + MeshOperatorKind.Scale -> { + // The factor was measured against the gesture anchor; each group then scales about its own + // pivot, and each influenced vertex about its owning group's pivot. + val factorX = parameters.factorX + val factorY = parameters.factorY + val moved = + groups.fold(originalWorld) { positions, group -> + MeshTransforms.scaleVerticesAxis(positions, group.vertexIndices, factorX, factorY, group.pivotX, group.pivotY) + } + val partitions = TransformPivots.partitionInfluencesByGroup(proportionalInfluences, groups) + groups.foldIndexed(moved) { groupIndex, positions, group -> + MeshTransforms.scaleVerticesWeighted(positions, partitions[groupIndex], factorX, factorY, group.pivotX, group.pivotY) + } + } + + MeshOperatorKind.Rotate -> { + // The angle was measured against the gesture anchor; each group then rotates about its own + // pivot, and each influenced vertex about its owning group's pivot. + val rotation = parameters.rotationRadians + val moved = + groups.fold(originalWorld) { positions, group -> + MeshTransforms.rotateVertices(positions, group.vertexIndices, rotation, group.pivotX, group.pivotY) + } + val partitions = TransformPivots.partitionInfluencesByGroup(proportionalInfluences, groups) + groups.foldIndexed(moved) { groupIndex, positions, group -> + MeshTransforms.rotateVerticesWeighted(positions, partitions[groupIndex], rotation, group.pivotX, group.pivotY) + } + } + + // Vertex Slide never reaches here: the drive loop handles it with its own edge projection. + MeshOperatorKind.VertexSlide -> originalWorld + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvDisplayMapping.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvDisplayMapping.kt new file mode 100644 index 0000000..e9a734c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvDisplayMapping.kt @@ -0,0 +1,101 @@ +package org.umamo.ui.viewport + +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.Drawable + +/* + * The UV editor's display mapping: the space its camera, hit tests, and wireframe operate in is + * TEXEL SPACE WITH Y UP - displayX = u * pageWidth, displayY = (1 - v) * pageHeight. Stored UVs + * put v = 0 at the TOP row of the atlas image (the decoder emits top row first and the sampler + * addresses it directly), while ViewportCamera's world space grows y UPWARD - so the v axis must + * flip or the wireframe renders vertically mirrored against the drawn page. Texel units (rather + * than normalized UV) make 1:1 zoom mean one texel per screen pixel and give non-square pages + * their true aspect. The mapping is affine and involutive per axis, so the shared transform + * operators, proportional falloffs, and element queries work over display arrays unchanged; edits + * convert back per touched vertex on commit. + */ + +/** + * Maps a normalized atlas u to the display (texel) x. + * + * @param Float u The normalized atlas u coordinate. + * @param Int pageWidth The atlas page width in texels. + * @return Float The display-space x. + */ +internal fun uvToDisplayX(u: Float, pageWidth: Int): Float = u * pageWidth + +/** + * Maps a normalized atlas v to the display (texel) y, flipping into the camera's Y-up convention. + * + * @param Float v The normalized atlas v coordinate (0 at the image's top row). + * @param Int pageHeight The atlas page height in texels. + * @return Float The display-space y. + */ +internal fun uvToDisplayY(v: Float, pageHeight: Int): Float = (1f - v) * pageHeight + +/** + * Maps a display (texel) x back to the normalized atlas u - the exact inverse of [uvToDisplayX]. + * + * @param Float displayX The display-space x. + * @param Int pageWidth The atlas page width in texels. + * @return Float The normalized atlas u coordinate. + */ +internal fun displayToUvU(displayX: Float, pageWidth: Int): Float = displayX / pageWidth + +/** + * Maps a display (texel) y back to the normalized atlas v - the exact inverse of [uvToDisplayY]. + * + * @param Float displayY The display-space y. + * @param Int pageHeight The atlas page height in texels. + * @return Float The normalized atlas v coordinate. + */ +internal fun displayToUvV(displayY: Float, pageHeight: Int): Float = 1f - displayY / pageHeight + +/** + * Maps an interleaved (u, v) array into display space (see the file header for the convention). + * + * @param FloatArray uvs The interleaved normalized atlas coordinates. + * @param Int pageWidth The atlas page width in texels. + * @param Int pageHeight The atlas page height in texels. + * @return FloatArray A new interleaved display-space array. + */ +internal fun uvToDisplay(uvs: FloatArray, pageWidth: Int, pageHeight: Int): FloatArray { + val display = FloatArray(uvs.size) + val vertexCount = uvs.size / 2 + for (vertexIndex in 0 until vertexCount) { + display[vertexIndex * 2] = uvToDisplayX(uvs[vertexIndex * 2], pageWidth) + display[vertexIndex * 2 + 1] = uvToDisplayY(uvs[vertexIndex * 2 + 1], pageHeight) + } + return display +} + +/** + * Maps an interleaved display-space array back to normalized (u, v) - the inverse of [uvToDisplay], + * the commit-side conversion after a display-space transform. + * + * @param FloatArray display The interleaved display-space coordinates. + * @param Int pageWidth The atlas page width in texels. + * @param Int pageHeight The atlas page height in texels. + * @return FloatArray A new interleaved normalized uv array. + */ +internal fun displayToUv(display: FloatArray, pageWidth: Int, pageHeight: Int): FloatArray { + val uvs = FloatArray(display.size) + val vertexCount = display.size / 2 + for (vertexIndex in 0 until vertexCount) { + uvs[vertexIndex * 2] = displayToUvU(display[vertexIndex * 2], pageWidth) + uvs[vertexIndex * 2 + 1] = displayToUvV(display[vertexIndex * 2 + 1], pageHeight) + } + return uvs +} + +/** + * Resolves which atlas page a drawable samples: the mapping is keyed by the source format's ids, so + * a session-created duplicate resolves through textureSourceId - the same resolution the GPU upload + * and the thumbnailer use. + * + * @param Drawable drawable The drawable whose page to resolve. + * @param PuppetTextures textures The document's decoded atlas pages. + * @return Int? The page index into [PuppetTextures.atlases], or null when the drawable is untextured. + */ +internal fun atlasPageIndexFor(drawable: Drawable, textures: PuppetTextures): Int? = + textures.atlasIndexByDrawableId[(drawable.textureSourceId ?: drawable.id).raw] \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvEditFrame.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvEditFrame.kt new file mode 100644 index 0000000..57ffc1c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvEditFrame.kt @@ -0,0 +1,169 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.UvFrame +import org.umamo.runtime.model.DrawableLayerBinding +import org.umamo.runtime.model.identityUvAffine +import org.umamo.runtime.model.invertUvAffine +import org.umamo.runtime.model.layerUvAffineOf + +/** + * The space a UV editing gesture works in: the display surface's texel size, and how a coordinate + * over it reaches the stored texture coordinates. + * + * The UV editor authors one mapping over two surfaces. Over an atlas page the display IS the stored + * frame - the texel mapping in UvDisplayMapping.kt is the whole conversion - and [storedFromFrame] is + * null, so that path carries no conversion at all. Over a source layer the display is the artwork's own + * pixels, and the drawable's atlas placement stands between them; [storedFromFrame] carries that step + * so an edit authored on the art commits in the frame the document stores. + * + * Everything downstream of the display coordinates - the transform operators, proportional falloff, + * box and circle queries, hit tests - is space-agnostic and needs no part of this. Only the two ends + * do: reading a stored coordinate to show it, and writing an authored one back. + * + * A plain class, not a data class: it wraps an affine array whose identity-based equals would make a + * generated structural equals quietly wrong. Never key a remember or an effect on one - key on the + * dimensions and the shown surface's identity, which are the values it was built from. + * + * @property Int displayWidth The shown surface's width in texels. + * @property Int displayHeight The shown surface's height in texels. + */ +class UvEditFrame( + val displayWidth: Int, + val displayHeight: Int, + private val storedFromFrame: FloatArray?, + private val frameFromStored: FloatArray?, +) { + /** True when the display surface is the stored frame itself, so no conversion applies. */ + val isStoredFrame: Boolean get() = storedFromFrame == null + + /** + * The stored coordinate a display point authors. + * + * @param Float displayX The display x in texels. + * @param Float displayY The display y in texels. + * @return Pair The stored (u, v). + */ + fun storedUvAt(displayX: Float, displayY: Float): Pair { + val frameU = displayToUvU(displayX, displayWidth) + val frameV = displayToUvV(displayY, displayHeight) + val affine = storedFromFrame ?: return frameU to frameV + return (affine[0] * frameU + affine[1] * frameV + affine[2]) to + (affine[3] * frameU + affine[4] * frameV + affine[5]) + } + + /** + * Where a stored coordinate falls on the display surface. + * + * @param Float u The stored u. + * @param Float v The stored v. + * @return Pair The display (x, y) in texels. + */ + fun displayAt(u: Float, v: Float): Pair { + val affine = frameFromStored + val frameU = if (affine == null) u else affine[0] * u + affine[1] * v + affine[2] + val frameV = if (affine == null) v else affine[3] * u + affine[4] * v + affine[5] + return uvToDisplayX(frameU, displayWidth) to uvToDisplayY(frameV, displayHeight) + } + + /** + * Converts a whole display-space array into stored coordinates. + * + * @param FloatArray displayPositions The display coordinates, interleaved (x, y). + * @return FloatArray The stored (u, v) coordinates, a fresh array. + */ + fun storedUvs(displayPositions: FloatArray): FloatArray { + val storedUvs = FloatArray(displayPositions.size) + var componentIndex = 0 + while (componentIndex + 1 < displayPositions.size) { + val (u, v) = storedUvAt(displayPositions[componentIndex], displayPositions[componentIndex + 1]) + storedUvs[componentIndex] = u + storedUvs[componentIndex + 1] = v + componentIndex += 2 + } + return storedUvs + } + + /** + * This frame as the normalized-coordinate pair the frame-aware session operations take. + * + * @return UvFrame? The stored-to-frame pair, or null when the stored coordinates are the frame. + */ + fun asUvFrame(): UvFrame? { + val toFrame = frameFromStored ?: return null + val fromFrame = storedFromFrame ?: return null + return UvFrame(toFrame, fromFrame) + } +} + +/** + * The stored uvs a texture-coordinate edit commits: the drawable's current values with ONLY the moved + * vertices overwritten from the transformed display positions. + * + * Rebuilding from the stored array rather than converting the whole transformed one is what keeps an + * untouched vertex bit-identical. A display round trip is exact in the reals but not in floats, and + * through a source layer's placement it is one conversion further; the export's changed-uv test is a + * bitwise compare, so converting everything would report meshes as edited that the gesture never + * touched - and warn the user about re-derived mappings that were never authored. + * + * @param FloatArray storedUvs The drawable's current stored coordinates. + * @param Collection movedIndices The vertices the operation actually moved. + * @param FloatArray displayPositions The transformed display coordinates, interleaved (x, y). + * @param UvEditFrame frame The space the positions are in. + * @return FloatArray The coordinates to commit, a fresh array. + */ +fun storedUvsWithMoved( + storedUvs: FloatArray, + movedIndices: Collection, + displayPositions: FloatArray, + frame: UvEditFrame, +): FloatArray { + val committed = storedUvs.copyOf() + for (vertexIndex in movedIndices) { + val componentIndex = vertexIndex * 2 + if (componentIndex + 1 >= committed.size || componentIndex + 1 >= displayPositions.size) { + continue + } + val (u, v) = frame.storedUvAt(displayPositions[componentIndex], displayPositions[componentIndex + 1]) + committed[componentIndex] = u + committed[componentIndex + 1] = v + } + return committed +} + +/** + * The frame of a UV editor showing an atlas page: the display texels ARE the stored frame. + * + * @param Int pageWidth The shown page's width in texels. + * @param Int pageHeight The shown page's height in texels. + * @return UvEditFrame The page-view frame. + */ +fun atlasPageEditFrame(pageWidth: Int, pageHeight: Int): UvEditFrame = + UvEditFrame(pageWidth, pageHeight, storedFromFrame = null, frameFromStored = null) + +/** + * The frame of a UV editor showing a source layer, built from a drawable's recovered placement. + * + * Every drawable over one layer shares this frame - the layer view shows exactly the drawables bound + * to the shown layer - so a single conversion covers a whole edit, which is what lets the shared-pivot + * transform modes keep meaning something. + * + * Note the store's packed / unpacked test and the CMO3 export's are independently derived, and a + * document that carries an atlas while sampling per-layer rasters satisfies only one of them. That + * divergence is pre-existing and harmless here: an unpacked binding's frame is the identity, so a + * disagreement costs a conversion that would have changed nothing. + * + * @param DrawableLayerBinding binding The shown drawable's recovered binding. + * @param Int layerWidth The shown layer's width in pixels. + * @param Int layerHeight The shown layer's height in pixels. + * @return UvEditFrame? The layer-view frame, or null when the mapping cannot be formed. + */ +fun sourceLayerEditFrame(binding: DrawableLayerBinding, layerWidth: Int, layerHeight: Int): UvEditFrame? { + val frameFromStored = layerUvAffineOf(binding, layerWidth, layerHeight) ?: return null + val storedFromFrame = invertUvAffine(frameFromStored) ?: return null + // An unpacked drawable's art IS its stored frame, so it takes the page view's own null-conversion + // path rather than carrying a pair of identity matrices through every commit. + if (frameFromStored.contentEquals(identityUvAffine())) { + return atlasPageEditFrame(layerWidth, layerHeight) + } + return UvEditFrame(layerWidth, layerHeight, storedFromFrame, frameFromStored) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvEditGizmoOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvEditGizmoOverlay.kt new file mode 100644 index 0000000..c0bb30b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvEditGizmoOverlay.kt @@ -0,0 +1,647 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.DEFAULT_PROPORTIONAL_RADIUS_WORLD +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.IndividualOriginScope +import org.umamo.edit.MeshChange +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshSelectionOps +import org.umamo.edit.MeshTopology +import org.umamo.edit.MeshTransforms +import org.umamo.edit.ModalCaptureSource +import org.umamo.edit.ModalTransformCapture +import org.umamo.edit.PROPORTIONAL_RADIUS_STEP_FACTOR +import org.umamo.edit.ProportionalRows +import org.umamo.edit.buildModalTransformCapture +import org.umamo.edit.withMeshUvs +import org.umamo.render.ViewportCamera +import org.umamo.runtime.model.DrawableId +import org.umamo.ui.model.LocalPuppetRenderSync +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawRubberBand +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle +import kotlin.math.pow + +/** The smallest useful proportional influence radius in display (texel) units. */ +private const val MIN_UV_PROPORTIONAL_RADIUS_DISPLAY = 1f + +/** + * The captured state of an in-flight UV transform: the shared [ModalTransformCapture] (its entries hold each + * mesh's frozen display-space coordinates as their positions, plus the pivot groups, proportional halos, and + * moved sets) together with the frame those coordinates were mapped in. The texture-space sibling of the + * Edit gesture, minus every deformer concern: UVs live in one flat display space, so there is no deformer + * space mapping, no movement transfer, and no world/local split - the operator transforms the display + * coordinates directly and the result converts back through the frame to the stored coordinates. + * + * The frame freezes here so the display-to-uv conversion at drive and commit always matches the space the + * originals were mapped in (the shown surface can hop mid-gesture if the active drawable changes from + * another area). + * + * @property ModalTransformCapture transform The shared gesture capture (entries, groups, anchor, halos, kind). + * @property UvEditFrame frame The space the gesture is authored in (its texel size and the conversion + * back to the stored coordinates). + */ +private class UvGesture( + val transform: ModalTransformCapture, + val frame: UvEditFrame, +) + +/** + * The UV editor's gizmo overlay: the Edit-mode interaction core the UV space composes over its texture + * underlay - the atlas page or the source layer's artwork the area is showing. Self-gates to Edit mode + * with a camera - the mode-exclusive sibling of [UvObjectGizmoOverlay], so the host mounts both + * unconditionally (the viewport overlay pair's convention). + * Draws the shown meshes' UV wireframes (from the live preview during a gesture), runs the + * idle element selection (click pick with Shift/Ctrl toggle, empty-drag box, sub-threshold-click + * clear), and drives the modal G / S / R operators over raw texture coordinates through the shared + * [ModalTransformController] - the same pointer semantics as the viewport overlays (stale discard, + * virtual pointer, cursor wrap, LMB-confirm / RMB-cancel), with no deformer inverse involved: the + * transformed display arrays convert back through the shown surface's frame to the stored coordinates + * on drive and commit. + * + * Live preview streams through [LocalPuppetRenderSync]: each pointer frame folds the transformed UVs + * into an uncommitted model and pushes it to the puppet renderer, so the 2D viewport shows the art + * resampling as the mapping moves; confirm commits ONE undo step via commitMeshUvs and the session's + * model bridge republishes the committed model. Gating follows the area-ownership contract: the + * capture effect and pointer drive key on the UV latch's own areaId, bystander areas stay inert, and + * teardown resyncs the raster only when this overlay owned a gesture. + * + * @param String areaId The UV editor area this overlay covers. + * @param EditorSession session The session owning the selection and the UV operator latch. + * @param List geometries The shown meshes' display-space gizmo geometry. + * @param UvEditFrame frame The shown surface's texel size plus how a coordinate over it reaches the + * stored texture coordinates (an atlas page is the stored frame itself; a source layer is not). + * @param ViewportCamera? camera The area camera; null hides the overlay (no fit has landed yet). + * @param Int widthPx The area width in pixels. + * @param Int heightPx The area height in pixels. + * @param MutableState proportionalRadiusDisplayState The host-owned proportional radius in + * display (texel) units: this overlay's gesture machinery seeds and resizes it, and the host's + * UvHudOverlay badge reads it - sibling overlays share state only through the session or the host. + * @param Modifier modifier The layout modifier. + */ +@Composable +internal fun UvEditGizmoOverlay( + areaId: String, + session: EditorSession, + geometries: List, + frame: UvEditFrame, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + proportionalRadiusDisplayState: MutableState, + modifier: Modifier = Modifier, +) { + val mode by session.mode.collectAsState() + val meshSelection by session.meshSelection.collectAsState() + val activeOperator by session.activeUvOperator.collectAsState() + val activeSelectTool by session.activeSelectTool.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val proportionalEdit by session.proportionalEdit.collectAsState() + val renderSync = LocalPuppetRenderSync.current + val viewportOverlayColors = rememberViewportOverlayColors() + val overlayColors = LocalUmamoColors.current + if (mode != EditorMode.Edit || camera == null || geometries.isEmpty()) { + return + } + val overlayStyle = selectionOverlayStyle(overlayColors) + + // Live values the long-running pointer loop and effects read (they are keyed only on areaId, so + // they must not close over a stale camera / size / geometry / frame when those change mid-edit). + val liveCamera = rememberUpdatedState(camera) + val liveSize = rememberUpdatedState(IntSize(widthPx, heightPx)) + val liveGeometries = rememberUpdatedState(geometries) + val liveFrame = rememberUpdatedState(frame) + val liveRenderSync = rememberUpdatedState(renderSync) + + // The box-select and circle-select machinery over the shared session selection. + val marquee = + remember(areaId) { + MarqueeSelectController( + seedStroke = { session.meshSelection.value }, + stampStroke = { working, erasing, center, radiusPx, stampCamera, stampSize -> + circleSelection(working, erasing, center, radiusPx, liveGeometries.value, stampCamera, stampSize) + }, + commitStroke = { stroke -> session.setMeshSelection(stroke) }, + applyBox = { start, end, additive, boxCamera, boxSize -> + val selection = session.meshSelection.value + val insideByDrawable = + liveGeometries.value.associate { geometry -> + geometry.drawableId to elementsInBox(selection.selectMode, geometry, start, end, boxCamera, boxSize) + } + session.setMeshSelection(MeshSelectionOps.box(selection, insideByDrawable, additive = additive)) + }, + setCircleRadius = { radiusPx -> session.setCircleRadius(radiusPx) }, + clearTool = { session.clearSelectTool() }, + ) + } + + // The per-area modal-gesture bookkeeping (last pointer, capture + preview, gesture origin, area origin, + // cursor wrap, pointer controller), the Edit overlay's shape. The capture is the UV gesture (shared + // transform capture + the frozen authoring frame); preview holds each moving mesh's display-space coordinates. + val gesture = remember(areaId) { ModalGestureState() } + + // The UV editor's own proportional influence radius, in display (texel) units, delegating to the + // host's state so the sibling UvHudOverlay badge reads what the gesture machinery writes here. + var proportionalRadiusDisplay by proportionalRadiusDisplayState + + /** + * Resolves the effective proportional radius, seeding it from the shown surface's size on first use. + * + * @return Float The influence radius in display units. + */ + fun effectiveProportionalRadius(): Float { + val current = proportionalRadiusDisplay + if (current != null) { + return current + } + val seeded = + (minOf(liveFrame.value.displayWidth, liveFrame.value.displayHeight) / 8f).coerceAtLeast(MIN_UV_PROPORTIONAL_RADIUS_DISPLAY) + proportionalRadiusDisplay = seeded + return seeded + } + + // Confirms the in-flight gesture: convert each moving mesh's display preview back to normalized + // UV and commit as ONE undo step, register that step on the operation settings strip, then clear the + // operator (its teardown resyncs the renderer to the committed model the bridge republishes). A null + // preview means no movement - nothing commits. + fun confirmGesture() { + val committed = gesture.preview + val gestureData = gesture.capture + val parameters = gesture.lastParameters + if (committed != null && gestureData != null) { + val transform = gestureData.transform + val newUvsByDrawable = LinkedHashMap(transform.entries.size) + val vertexIndicesByDrawable = LinkedHashMap>(transform.entries.size) + for (entry in transform.entries) { + val transformed = committed[entry.drawableId] ?: continue + // Only the moved vertices are written; untouched ones keep their exact stored values (see + // storedUvsWithMoved). Same discipline as the snap path, and the reason a gesture over a + // wide selection does not report every mesh it covered as edited. + val storedUvs = session.model.value.drawables.firstOrNull { drawable -> drawable.id == entry.drawableId }?.mesh?.uvs + newUvsByDrawable[entry.drawableId] = + if (storedUvs == null) { + gestureData.frame.storedUvs(transformed) + } else { + storedUvsWithMoved(storedUvs, entry.movedIndices, transformed, gestureData.frame) + } + // The moved set, not just the covered set: proportional editing moves weighted + // unselected vertices too, and the change metadata must name every vertex touched. + vertexIndicesByDrawable[entry.drawableId] = entry.movedIndices.toList() + } + if (newUvsByDrawable.isNotEmpty()) { + val modelBefore = session.model.value + session.commitMeshUvs(MeshChange.TransformUvs(vertexIndicesByDrawable, transform.operatorKind), newUvsByDrawable) + // The strip's rows for the step just pushed, over the RETAINED capture and frame so an + // adjustment replays the same frozen coordinates - registered before the operator clears, + // since the teardown drops the capture. A commit that recorded nothing has no step to amend. + // The proportional radius here is the editor's own texel radius, so the write-back keeps the + // session's world radius as it was and lands the row's value where this editor keeps it. + if (parameters != null && session.model.value !== modelBefore) { + val proportional = ProportionalRows.of(session.proportionalEdit.value, effectiveProportionalRadius()) + registerUvTransformAdjustment(session, areaId, transform, gestureData.frame, parameters, proportional) { state, radiusDisplay -> + proportionalRadiusDisplay = radiusDisplay + val radiusWorld = session.proportionalEdit.value?.radiusWorld ?: DEFAULT_PROPORTIONAL_RADIUS_WORLD + session.setProportionalEdit(state?.copy(radiusWorld = radiusWorld)) + } + } + } + } + session.clearUvOperator() + } + + // Drives the modal preview for one virtual-pointer position: the shared operator math over the + // frozen display arrays (no deformer inverse), converted back to stored coordinates and folded into + // an uncommitted model for the puppet renderer. Shared by Move and the radius Scroll. False when + // the capture has not landed yet. + fun driveModalPreview(operator: MeshOperatorKind, virtualPointer: Offset, activeCamera: ViewportCamera, size: IntSize): Boolean { + val start = gesture.gestureStart ?: return false + val gestureData = gesture.capture ?: return false + val transform = gestureData.transform + // The frame resolves ONCE into the numbers every mesh applies; the confirm hands them to the + // settings strip. + val frame = TransformGestureFrame(transform.anchor, start, virtualPointer, session.axisConstraint.value, activeCamera, size) + val parameters = gestureParameters(operator, frame, transform.rotationTracker) + gesture.lastParameters = parameters + val newPreview = LinkedHashMap(transform.entries.size) + var folded = session.model.value + for (entry in transform.entries) { + val transformedDisplay = applyOperator(operator, entry.positions, entry.groups, parameters, entry.influence) + newPreview[entry.drawableId] = transformedDisplay + // The preview converts whole arrays: it is transient and never committed, so the drift the + // commit above avoids is invisible here. + folded = folded.withMeshUvs(entry.drawableId, gestureData.frame.storedUvs(transformedDisplay)) + } + gesture.preview = newPreview + liveRenderSync.value?.previewModel(folded) + return true + } + + // The modal gesture's commit-side seam over the shared pointer-side controller. + val modalTarget = + object : ModalTransformTarget { + override fun drivePreview(virtualPointer: Offset, camera: ViewportCamera, size: IntSize): Boolean { + // Defensive ownership check (the pointer loop already gates): only the initiating area drives. + val operator = session.activeUvOperator.value?.takeIf { it.areaId == areaId } ?: return false + return driveModalPreview(operator.kind, virtualPointer, camera, size) + } + + override fun confirm() { + confirmGesture() + } + + override fun cancel() { + session.clearUvOperator() + } + + override fun onScroll(steps: Float, camera: ViewportCamera, size: IntSize) { + // The wheel resizes the display-unit influence radius mid-gesture (the Edit overlay's + // behavior, in this space's units): geometric steps, weights re-derived from the frozen + // originals, preview re-driven immediately so the mapping responds without pointer motion. + val operator = session.activeUvOperator.value?.takeIf { it.areaId == areaId } ?: return + val proportional = session.proportionalEdit.value + val gestureData = gesture.capture + if (steps != 0f && proportional != null && gestureData != null) { + val maxRadius = 4f * maxOf(gestureData.frame.displayWidth, gestureData.frame.displayHeight) + val resized = + (effectiveProportionalRadius() * PROPORTIONAL_RADIUS_STEP_FACTOR.pow(-steps)) + .coerceIn(MIN_UV_PROPORTIONAL_RADIUS_DISPLAY, maxRadius) + proportionalRadiusDisplay = resized + gestureData.transform.applyProportional(proportional, resized) + driveModalPreview(operator.kind, gesture.cursorWrap.virtualPointer(gesture.lastPointer), camera, size) + } + } + } + + // A tool change - armed, cleared by Escape / right-click, or switched between box and circle - + // resolves any in-flight marquee gesture (the stroke commits, the box abandons). Keyed on the + // tool KIND derived from the AREA-OWNED tool, exactly like the Edit overlay: a brush resize makes + // a new Circle(radius) that must not wipe the stroke, and a re-arm from another area reads as + // live-to-absent here. The race-free cancel path is the request collector below; this is the + // backstop for tool switches and unmounts, where no signal is sent. + val ownedSelectTool = activeSelectTool?.takeIf { tool -> tool.areaId == areaId } + LaunchedEffect(selectToolKind(ownedSelectTool)) { + marquee.cancel() + } + + // The race-free box cancel: the shell fires this for every Edit-mode select-gesture cancel, and an + // already-suspended collector resumes before the mouse release could commit a cancelled box. + LaunchedEffect(session) { + session.meshGestureCancelRequests.collect { + marquee.cancel() + } + } + + // Mirror U / V: the executing area was resolved at dispatch into the payload, so this gate is + // deterministic. It routes through the overlay rather than straight to the session because the + // axis a mirror reflects about is a property of the SHOWN surface - reflecting a source layer's + // art about the atlas page's axis would be a different operation - and only this overlay knows + // which surface it is showing. + LaunchedEffect(session) { + session.uvMirrorRequests.collect { request -> + if (session.mode.value != EditorMode.Edit || request.areaId != areaId) { + return@collect + } + val frame = liveFrame.value.asUvFrame() + if (request.reverseSwap) { + session.reverseSwapSelectedUvs(horizontal = request.mirrorU, frame = frame) + } else { + session.mirrorSelectedUvs(request.mirrorU, frame) + } + } + } + + // Select Linked (Blender's L / Ctrl+L): the executing area was resolved at dispatch into the + // payload, so this gate is deterministic. UV islands are topology islands (UVs share the vertex + // index space), so the shared flood runs verbatim over the display geometry. + LaunchedEffect(session) { + session.selectLinkedRequests.collect { request -> + if (session.mode.value != EditorMode.Edit || request.areaId != areaId) { + return@collect + } + handleSelectLinkedRequest(session, liveGeometries.value, request.fromSelection, gesture.lastPointer, liveCamera.value, liveSize.value) + } + } + + // The UV snap pie (Shift+S over the UV editor): the executing area was resolved at dispatch into + // the payload, so this gate is deterministic. The executor owns the shown surface's frame and the + // covered display geometry, so it performs the snap over the texture coordinates here. + LaunchedEffect(session) { + session.uvSnapRequests.collect { request -> + if (session.mode.value != EditorMode.Edit || request.areaId != areaId) { + return@collect + } + handleUvSnapRequest(session, liveGeometries.value, liveFrame.value, request.kind) + } + } + + // Enter confirms the modal gesture (mirroring a primary click), gated to the INITIATING area + // through the UV latch itself - the mesh and object latches are mutually exclusive with it, so an + // Edit-overlay confirm can never double-commit with this one. + LaunchedEffect(session) { + collectModalConfirmRequests(session, { session.activeUvOperator.value?.areaId == areaId }) { + confirmGesture() + } + } + + // A proportional toggle or falloff change MID-GESTURE re-derives the capture's weights from its + // frozen originals (the keyboard-side complement of the scroll resize). + LaunchedEffect(session) { + session.proportionalEdit.collect { state -> + val gestureData = gesture.capture + if (gestureData != null && session.activeUvOperator.value != null) { + gestureData.transform.applyProportional(state, effectiveProportionalRadius()) + } + } + } + + // Start the modal gesture as a UV operator latches IN THIS AREA; tear it down (resyncing the + // renderer to the committed model) as it clears. The capture covers only the shown meshes with + // covered vertices; the anchor follows the pivot mode in display space. + LaunchedEffect(activeOperator) { + val operator = activeOperator?.takeIf { it.areaId == areaId } + if (operator != null) { + val selection = session.meshSelection.value + // Offer each shown mesh with covered vertices to the shared capture builder, its frozen + // display-space coordinates as the source positions (no deformer mapping in UV space). + val sources = ArrayList() + for (geometry in liveGeometries.value) { + val elements = selection.elementsOf(geometry.drawableId) + if (elements.isEmpty()) { + continue + } + val coveredIndices = MeshTopology.coveredVertexIndices(elements, geometry.indices) + if (coveredIndices.isEmpty()) { + continue + } + sources.add(ModalCaptureSource(geometry.drawableId, geometry.positions.copyOf(), geometry.indices, coveredIndices)) + } + // The two per-area anchors the shared builder cannot resolve itself, in display space: the + // active element's own covered median and the UV cursor. Null falls back to the shared median. + val activeAnchor = + run { + val active = selection.activeElement ?: return@run null + val activeGeometry = liveGeometries.value.firstOrNull { it.drawableId == active.drawableId } ?: return@run null + val activeCovered = MeshTopology.coveredVertexIndices(setOf(active.element), activeGeometry.indices) + if (activeCovered.isEmpty()) { + null + } else { + MeshTransforms.medianPivot(activeGeometry.positions, activeCovered) + } + } + val cursorAnchor = + session.uvCursor.value?.let { cursor -> + liveFrame.value.displayAt(cursor.u, cursor.v) + } + val transform = + buildModalTransformCapture( + sources = sources, + pivotMode = session.pivotMode.value, + // UV islands split the same as Edit mode (UVs share the vertex index space). + individualOriginScope = IndividualOriginScope.ConnectivityIsland, + operatorKind = operator.kind, + activeAnchor = activeAnchor, + cursorAnchor = cursorAnchor, + ) + if (transform == null) { + // Nothing movable on the shown surface (the selection's covered meshes live elsewhere or + // carry no editable UVs): drop the operator. + session.clearUvOperator() + } else { + transform.applyProportional(session.proportionalEdit.value, effectiveProportionalRadius()) + gesture.begin(UvGesture(transform, liveFrame.value), gesture.lastPointer) + } + } else { + // Resync the renderer only when THIS overlay owned a gesture: the else branch also runs at + // mount and when another area's operator latches, and an unguarded resync from a bystander + // would stomp the initiating area's live preview (the ownership doc's mid-gesture-split guard). + if (gesture.end()) { + liveRenderSync.value?.resync() + } + } + } + + // The unmount-mid-gesture raster guard: leaving Edit mode or closing the area disposes this + // overlay, cancelling the latch effect above WITHOUT running its else branch - so the renderer + // would strand on the un-committed preview. The latch itself is cleared by the mode-switch / + // restore teardown and the space's area-death effect; this restores the raster. + DisposableEffect(areaId, session) { + onDispose { + if (gesture.capture != null) { + liveRenderSync.value?.resync() + } + } + } + + // What the draw pass reflects: the live circle stroke while one is in flight, else the committed + // selection - so painted elements light up immediately during a Circle stroke. + val effectiveSelection = marquee.circleStroke ?: meshSelection + + // What the draw pass highlights per mesh and domain (Blender's derive-up / flush-down rules). + val highlightByDrawable = + remember(effectiveSelection, geometries) { + geometries.associate { geometry -> + geometry.drawableId to + buildHighlightSets( + elements = effectiveSelection.elementsOf(geometry.drawableId), + active = effectiveSelection.activeElement?.takeIf { activeElement -> activeElement.drawableId == geometry.drawableId }?.element, + selectMode = effectiveSelection.selectMode, + triangleIndices = geometry.indices, + ) + } + } + + // clipToBounds: Canvas drawing is not clipped to the layout bounds by default, so an off-page + // vertex would otherwise paint over the AreaHeader and neighbouring areas. + Box( + modifier = + modifier + .fillMaxSize() + .clipToBounds() + .onGloballyPositioned { coordinates -> gesture.areaScreenOrigin = coordinates.positionOnScreen() } + // While THIS AREA'S modal transform runs, hide the OS cursor so only the overlay's drawn + // cursor (double-arrow, crosshair, or brush circle) shows; a gesture owned by another + // area leaves this cursor alone. + .then( + if (activeOperator?.areaId == areaId || ownedSelectTool != null) { + Modifier.pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + } else { + Modifier + }, + ), + ) { + // Two sibling canvases, each in its OWN layer: a draw-state invalidation re-records every draw + // lambda sharing a layer, so the gesture chrome below (band, affordances, modal HUD) lives in + // a small layer of its own and the wireframes - the expensive pass - stay cached in this one. + // The chrome reads gesture.lastPointer, which updates on every pointer event (hover included), + // so its layer redraws per move; this layer re-records only when the geometry, the selection, + // or a live modal preview changes - and it composites OFFSCREEN, because a default layer + // retains a display list that every window repaint replays (re-stroking every edge), where the + // offscreen buffer rasterizes once per content change and blits per frame. + Canvas( + modifier = + Modifier + .fillMaxSize() + .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } + .pointerInput(areaId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + gesture.lastPointer = change.position + val latchedUvOperator = session.activeUvOperator.value + val latchedTool = session.activeSelectTool.value + // A gesture belongs to its initiating area, and the viewport-owned operators + // can never belong to a UV area: while any of them (or another area's UV + // operator / armed tool) is live, this overlay is fully inert - Escape and + // Enter stay global through the shell key ladder, and navigation still falls + // through to the layer below. + if (session.activeMeshOperator.value != null || + session.activeObjectOperator.value != null || + (latchedUvOperator != null && latchedUvOperator.areaId != areaId) || + (latchedTool != null && latchedTool.areaId != areaId) + ) { + continue + } + val activeCamera = liveCamera.value + val size = liveSize.value + if (latchedUvOperator != null) { + // MODAL: the shared controller drives the transform over the captured + // mapping and swallows every event. + gesture.lastPointer = gesture.modalController.handleEvent(event, change, modalTarget, activeCamera, size, gesture.areaScreenOrigin) + } else if (latchedTool is ActiveSelectTool.Circle) { + // CIRCLE SELECT: the shared controller paints / erases / commits the stroke + // and consumes every event (paired with the navigation gate so MMB / wheel + // do not also pan / zoom). + marquee.handleCircleEvent(event, change, latchedTool.radiusPx, activeCamera, size) + } else if (latchedTool is ActiveSelectTool.AddVertex) { + // ADD VERTEX: stage floating verts (document untouched) until Enter accepts. + handleAddVertexToolEvent( + event = event, + change = change, + session = session, + tool = latchedTool, + geometries = liveGeometries.value, + camera = activeCamera, + size = size, + ) + } else { + // IDLE: element selection, shared with the 2D viewport's Edit overlay. Only + // primary-driven events are consumed, so middle-drag pan and wheel zoom fall + // through; armed Box-select boxes on any press and disarms. Shift+RightClick + // places the UV cursor (the viewport's 2D-cursor gesture, in texture space). + handleIdleMeshSelectionEvent( + event = event, + change = change, + session = session, + geometries = liveGeometries.value, + marquee = marquee, + boxArmed = latchedTool is ActiveSelectTool.BoxArmed, + camera = activeCamera, + size = size, + placeCursor = { displayX, displayY -> + val (cursorU, cursorV) = liveFrame.value.storedUvAt(displayX, displayY) + session.setUvCursor( + cursorU, + cursorV, + ) + }, + ) + } + } + } + }, + ) { + // The wireframes draw from the live preview arrays during a gesture - this Canvas IS the + // display (no asynchronous raster to lag behind, unlike the viewport overlays' frame model). + // The live circle stroke drives the highlighted domain so painted elements light up mid-stroke. + val activePreview = gesture.preview.takeIf { gesture.capture != null } + for (geometry in geometries) { + val highlight = highlightByDrawable[geometry.drawableId] ?: continue + drawMeshWireframe( + positions = activePreview?.get(geometry.drawableId) ?: geometry.positions, + indices = geometry.indices, + edges = geometry.edges, + highlight = highlight, + selectMode = effectiveSelection.selectMode, + colors = viewportOverlayColors, + camera = camera, + size = IntSize(widthPx, heightPx), + ) + } + } + Canvas(modifier = Modifier.fillMaxSize().graphicsLayer()) { + drawRubberBand(marquee.boxStart, marquee.boxCurrent, overlayStyle) + + // Armed select-tool affordances (Blender B / C / Add Vertex), shared chrome with the viewport + // overlays. Only the arming area draws them - the latch is session-global, every UV area composes this. + val addVertexTool = ownedSelectTool as? ActiveSelectTool.AddVertex + val addVertexPositions = + addVertexTool?.let { tool -> + geometries.firstOrNull { entry -> entry.drawableId == tool.drawableId }?.positions + } + drawSelectToolAffordances( + tool = ownedSelectTool, + pointer = gesture.lastPointer, + boxDragInFlight = marquee.boxStart != null, + viewport = Size(widthPx.toFloat(), heightPx.toFloat()), + style = overlayStyle, + crosshairCursor = LocalUmamoCursors.crosshair, + draftCamera = camera.takeIf { addVertexTool != null }, + draftSize = IntSize(widthPx, heightPx).takeIf { addVertexTool != null }, + meshPositions = addVertexPositions, + ) + + // Modal transform HUD (axis line, pivot dash, drawn cursor, proportional ring), shared + // chrome with the viewport overlays. Only the initiating area draws it - the capture + // exists solely in the overlay whose area the operator latch names. + val hudOperator = activeOperator + val hudPivot = gesture.capture?.transform?.anchor + if (hudOperator != null && hudPivot != null) { + val ringRadiusPx = + if (proportionalEdit != null) { + (proportionalRadiusDisplay ?: 0f).takeIf { radius -> radius > 0f }?.times(camera.zoom) + } else { + null + } + drawModalTransformHud( + axisConstraint = axisConstraint, + pivotScreen = worldToScreen(hudPivot.first, hudPivot.second, camera, IntSize(widthPx, heightPx)), + virtualPointer = gesture.cursorWrap.virtualPointer(gesture.lastPointer), + realPointer = gesture.lastPointer, + viewport = Size(widthPx.toFloat(), heightPx.toFloat()), + lineColor = overlayColors.viewportMarquee, + pointerCursor = LocalUmamoCursors.nsewScroll, + proportionalRadiusPx = ringRadiusPx, + ) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvIslandPickController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvIslandPickController.kt new file mode 100644 index 0000000..ce22c17 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvIslandPickController.kt @@ -0,0 +1,213 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.render.DecodedImage +import org.umamo.render.ViewportCamera +import org.umamo.render.eval.paintOrder +import org.umamo.render.eval.renderOrder +import org.umamo.render.pick.PickCandidate +import org.umamo.render.pick.pickAllDrawables +import org.umamo.render.pick.pickDrawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel + +/** + * The static rest-pose front rank per drawable: the index of each drawable in the resolved + * back-to-front paint order (higher = drawn more in front), computed over the STATIC draw orders. + * The UV editor is a rest-space authoring view, so island stacking deliberately ignores any + * pose-blended draw-order channel - the rank a rigger sees here is the one the model rests at. + * + * The order rule mirrors the renderer's pose resolve exactly: the hierarchical group sort over + * renderRoot when the model carries a draw-order group tree, else the flat paintOrder sort over the + * parts-tree drawable order. + * + * @param PuppetModel model The model whose drawables to rank. + * @return Map The front rank per drawable (higher = more front). + */ +internal fun restFrontRank(model: PuppetModel): Map { + val drawOrderById = model.drawables.associate { drawable -> drawable.id to drawable.drawOrder } + val paintedBackToFront = + if (model.renderRoot.children.isEmpty()) { + paintOrder(model.drawables.map { drawable -> drawable.id }, drawOrderById) + } else { + renderOrder(model.renderRoot, drawOrderById) + } + return paintedBackToFront.withIndex().associate { (paintIndex, drawableId) -> drawableId to paintIndex.toFloat() } +} + +/** + * An alpha sampler over the shown surface - the atlas page or the source layer's artwork - for the + * shared pick functions: (id, u, v) -> texel alpha 0..1. v = 0 is the image's TOP row, matching the + * decoded image's top-row-first byte layout, so the sample needs no flip; out-of-range coordinates + * clamp to the edge texel. A null image (the untextured 1x1 fallback) samples 1f everywhere, so + * untextured islands stay clickable. The DrawableId parameter is unused - every shown island samples + * the one shown surface. + * + * @param DecodedImage? page The shown surface's decoded pixels, or null for the untextured fallback. + * @return Function The sampler the pick functions consume. + */ +internal fun pageAlphaSampler(page: DecodedImage?): (DrawableId, Float, Float) -> Float { + if (page == null) { + return { _, _, _ -> 1f } + } + return { _, u, v -> + val texelX = (u * page.width).toInt().coerceIn(0, page.width - 1) + val texelY = (v * page.height).toInt().coerceIn(0, page.height - 1) + // DecodedImage rgba is row-major, top row first, four bytes per texel; alpha is the fourth. + (page.rgba[(texelY * page.width + texelX) * 4 + 3].toInt() and 0xFF) / 255f + } +} + +/** + * The alpha threshold of the geometry tier. The shared pickers reject a hit whose sampled alpha is + * strictly below the threshold, and a sampler never returns less than 0, so a zero threshold admits + * every texel and the pick becomes a pure mesh-containment test. + */ +private const val GEOMETRY_TIER_ALPHA_THRESHOLD = 0f + +/** + * The UV editor's island picker: the shared point pick (pickDrawable / pickAllDrawables) bound to + * the shown surface's display-space islands, in two tiers. The opaque tier is the alpha-gated + * pick: the hit's uv is barycentric-interpolated from the mesh uvs in the SHOWN SURFACE's own frame + * (the stored coordinates over an atlas page, the layer-frame ones over a source layer), so the + * gate samples exactly the texel the click lands on, and overlapping islands resolve by the art + * actually visible there. When no island is opaque at the point, the geometry tier takes over: + * any island whose mesh contains the point is a hit, so a click on an island's transparent + * interior still selects it. In the UV editor the mesh IS the island, which is why this fallback + * is here and not in the 2D viewport's raster pick. The point is taken in display (texel) space - + * the caller unprojects a click through the area camera first. Front-most wins by [frontRankById] + * in either tier; the stack query is front-to-back with per-candidate centrality for the overlap + * popup's default row. + * + * @property Map displayPositionsById Interleaved display-space (x, y) vertices per island. + * @property Map indicesById Triangle index triples per island. + * @property Map meshUvsById The shown surface's uvs per island (the alpha-sample space). + * @property Map frontRankById The static rest-pose front rank (higher = more front). + * @property Function sampleAlpha (id, u, v) -> texel alpha over the shown surface. + * @property Function atlasSizeOf (id) -> the shown image's (width, height), or null for the untextured fallback + * (full centrality instead of ray-marching a fake 1x1 page). + */ +internal class UvIslandPickController( + val displayPositionsById: Map, + val indicesById: Map, + val meshUvsById: Map, + val frontRankById: Map, + val sampleAlpha: (DrawableId, Float, Float) -> Float, + val atlasSizeOf: (DrawableId) -> Pair?, +) { + /** + * The front-most island whose mesh contains the point and whose texel on the shown surface there is + * opaque; failing that, the front-most island whose mesh contains the point at all; null only when + * the point lies outside every island. + * + * @param Float displayX The point X in display (texel) space. + * @param Float displayY The point Y in display (texel) space. + * @return DrawableId? The front-most hit of the first tier that has one, or null. + */ + fun topmostAt(displayX: Float, displayY: Float): DrawableId? = + pickDrawable(displayX, displayY, displayPositionsById, indicesById, meshUvsById, frontRankById, sampleAlpha) + ?: pickDrawable(displayX, displayY, displayPositionsById, indicesById, meshUvsById, frontRankById, sampleAlpha, alphaThreshold = GEOMETRY_TIER_ALPHA_THRESHOLD) + + /** + * The islands under the point, front-to-back, each with its centrality - the overlap popup's + * candidate list. The tiers match [topmostAt]: the opaque islands when any is opaque at the point, + * else every island whose mesh contains it. Geometry-tier candidates carry one flat centrality + * (no ray-march - a march from a transparent hit measures nothing), so the popup's default row is + * the front-most, the island a plain click there picks. + * + * @param Float displayX The point X in display (texel) space. + * @param Float displayY The point Y in display (texel) space. + * @return List The candidates, front-to-back. + */ + fun stackAt(displayX: Float, displayY: Float): List = + pickAllDrawables(displayX, displayY, displayPositionsById, indicesById, meshUvsById, frontRankById, atlasSizeOf, sampleAlpha) + .ifEmpty { + pickAllDrawables( + displayX, + displayY, + displayPositionsById, + indicesById, + meshUvsById, + frontRankById, + atlasSizeOf = { null }, + sampleAlpha = sampleAlpha, + alphaThreshold = GEOMETRY_TIER_ALPHA_THRESHOLD, + ) + } +} + +/** + * Builds the island picker for the shown surface from what the UV space already resolves: the shown + * islands' display-space gizmo geometry, their uvs in that surface's own frame, the model's rest + * front rank, and the surface's decoded pixels. + * + * @param List geometries The islands' display-space gizmo geometry. + * @param Map frontRank The model's rest-pose front rank (restFrontRank). + * @param Map uvsById Each island's uvs in the shown surface's frame (the alpha-sample space). + * @param DecodedImage? image The shown surface's decoded pixels, or null for the untextured fallback. + * @return UvIslandPickController The picker. + */ +internal fun uvIslandPick( + geometries: List, + frontRank: Map, + uvsById: Map, + image: DecodedImage?, +): UvIslandPickController = + UvIslandPickController( + displayPositionsById = geometries.associate { geometry -> geometry.drawableId to geometry.positions }, + indicesById = geometries.associate { geometry -> geometry.drawableId to geometry.indices }, + meshUvsById = uvsById, + frontRankById = frontRank, + sampleAlpha = pageAlphaSampler(image), + atlasSizeOf = { image?.let { decodedImage -> decodedImage.width to decodedImage.height } }, + ) + +/** + * The islands a finished box drag encloses: an island is enclosed when ANY of its UV vertices falls + * inside the box (Blender's UV island box feel - a small box over an island's edge still takes it), + * tested through the shared vertex box rule. The result preserves the geometries' list order, so + * the caller's active-target choice (the last enclosed island) is deterministic. + * + * @param List geometries The islands' display-space gizmo geometry. + * @param Offset cornerA One box corner in area-local pixels. + * @param Offset cornerB The opposite box corner in area-local pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return List The enclosed islands, in geometries order. + */ +internal fun uvIslandsInBox( + geometries: List, + cornerA: Offset, + cornerB: Offset, + camera: ViewportCamera, + size: IntSize, +): List = + geometries.mapNotNull { geometry -> + geometry.drawableId.takeIf { elementsInBox(MeshSelectMode.Vertex, geometry, cornerA, cornerB, camera, size).isNotEmpty() } + } + +/** + * Resolves a finished island box drag against the object selection: additive (Shift) keeps the + * current targets and adds the enclosed islands, the last one becoming active (or the current + * active surviving when the box enclosed nothing); plain replaces the selection with the enclosed + * set. The viewport's object box rule, over islands. + * + * @param Selection current The committed object selection. + * @param List enclosed The enclosed, selectable islands in enclosure order. + * @param Boolean additive True when Shift extends the selection. + * @return Selection The selection the box produces. + */ +internal fun resolveIslandBoxSelection( + current: Selection, + enclosed: List, + additive: Boolean, +): Selection = + if (additive) { + Selection(current.targets + enclosed, enclosed.lastOrNull() ?: current.active) + } else { + Selection(enclosed.toSet(), enclosed.lastOrNull()) + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvObjectGizmoOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvObjectGizmoOverlay.kt new file mode 100644 index 0000000..f3215d0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvObjectGizmoOverlay.kt @@ -0,0 +1,714 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.FilterQuality +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.Matrix +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.withTransform +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.unit.IntSize +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.NoticePlacement +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.selectableOf +import org.umamo.edit.setAtlasPlacements +import org.umamo.format.art.AlphaContour +import org.umamo.format.art.LayerBounds +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.applyUvAffine +import org.umamo.ui.model.LocalSessionAtlasPages +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawRubberBand +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle + +/** + * One tile crop drawn at a committed placement while the page resolver is still composing the pixels + * for that commit. + * + * @property ImageBitmap crop The trim's pixels. + * @property LayerBounds trim The trim the crop covers, raster-local. + * @property AtlasPlacement placement Where the tile was committed to. + */ +private class GhostCrop( + val crop: ImageBitmap, + val trim: LayerBounds, + val placement: AtlasPlacement, +) + +/** + * A committed placement move's crops, drawn at their new spots until the resolver publishes pages for + * the committed atlas - so the islands never sit over the OLD pixels for the derivation's duration. + * + * @property PuppetAtlas atlas The atlas instance the commit published (the resolver keys by identity). + * @property Int pageHeight The page height, for the display flip. + * @property List crops The crops and where they were committed. + */ +private class PlacementGhost( + val atlas: PuppetAtlas, + val pageHeight: Int, + val crops: List, +) + +/** + * The UV editor's Object-mode gizmo overlay, the mode-exclusive sibling of [UvEditGizmoOverlay] + * (each one self-gates on the session's mode, the viewport overlay pair's convention): every + * visible island on the shown surface draws in the Blender object-overlay style - unselected islands + * dim (the idle palette), selected islands highlighted, the active island's outline emphasized - + * and the islands are click targets writing the ONE session object selection, so a selection made + * here flows out to the viewport and the outliner. + * + * The interaction vocabulary is the viewport Object gizmo's, through the same + * [ObjectPickController]: a sub-threshold primary click picks the front-most island under the + * cursor (plain replaces, Shift / Ctrl toggles membership, an unmodified click on empty canvas + * clears - under Follow Selection that may hop the shown page to the first-meshed fallback, while a + * pinned page holds), an Alt click resolves the overlap stack through the host's popup, a primary + * drag box-selects every island with a vertex inside the box (Shift adds), and Shift+RightClick + * places the UV cursor. + * Picking is CPU-side over [islandPick] - display-space point-in-face in two tiers. An island + * whose art is opaque under the cursor wins, so over overlapping islands the visible art decides; + * when none is opaque there, any island whose mesh contains the point is hit, so a click on an + * island's transparent interior still selects it and only a click outside every mesh is empty + * canvas. The same overlay serves both surfaces: over a source layer it gates on that artwork's own + * alpha and places the cursor through the layer's frame, which is the whole of the difference. + * + * Over an ATLAS PAGE the overlay also owns the placement gesture: a UV operator latched in this area + * in Object mode (G / S / R) moves the selected drawables' ART on the page - each tile's pixels and + * every drawable over it together, so the vertex-to-art mapping never changes. The capture freezes + * the movers (their placements, trims, mesh reserves, and crops), the page's bystanders, and the + * moving islands' display positions; each pointer frame evaluates the placements through the shared + * operator parameters (UvPlacementGesture.kt), previews the crops at their new spots and the islands + * translated with them, and outlines any footprint that collides or spills off the page; confirm + * commits ONE undo step through setAtlasPlacements and the session's page resolver recomposes the + * pixels. Nothing is pushed to the puppet renderer during the drag: a placement move is invisible in + * the 2D viewport by construction. Only primary-driven events are consumed while idle; pan / zoom and + * the plain right-click (the context menu) fall through, and a modal gesture owns the pointer. + * + * Posed from the FRAME camera so it lags with the GL image during pan / zoom, and unclipped to the + * image tile by design, so a mapping reaching past it stays visible - which is normal, since a mesh + * rings outside the art it samples (the hosting area still clips to its own bounds). + * + * @param String areaId The UV editor area this overlay covers (keys the pointer loop). + * @param EditorSession session The session owning the object selection, the model, and the latches. + * @param List geometries The shown islands' display-space gizmo geometry. + * @param UvIslandPickController islandPick The shown surface's island picker (point pick, stack query, front ranks). + * @param UvEditFrame frame The shown surface's texel size plus how a coordinate over it reaches the + * stored texture coordinates (an atlas page is the stored frame itself; a source layer is not). + * @param ViewportCamera? camera The displayed frame's camera; null hides the overlay (no frame yet). + * @param Int widthPx The area width in pixels. + * @param Int heightPx The area height in pixels. + * @param UvPlacementSurface? placementSurface The shown atlas page and the source-art store when the + * area shows a page, or null over a source layer (a latched placement operator is then dropped). + * @param MutableState placementDragStatusState The host-owned drag readout + * this overlay writes per pointer frame and the host's UvHudOverlay badge reads. + * @param Function onOverlapRequest Opens the host's overlap picker for an Alt click with 2+ candidates. + * @param Modifier modifier The layout modifier. + */ +@Composable +internal fun UvObjectGizmoOverlay( + areaId: String, + session: EditorSession, + geometries: List, + islandPick: UvIslandPickController, + frame: UvEditFrame, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + placementSurface: UvPlacementSurface?, + placementDragStatusState: MutableState, + onOverlapRequest: (Offset, List) -> Unit, + modifier: Modifier = Modifier, +) { + val mode by session.mode.collectAsState() + if (mode == EditorMode.Edit || camera == null) { + return + } + + val meshSelection by session.meshSelection.collectAsState() + val objectSelection by session.selection.collectAsState() + val activeOperator by session.activeUvOperator.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val committedModel by session.model.collectAsState() + val tileByDrawableId = remember(committedModel) { committedModel.drawables.mapNotNull { drawable -> drawable.atlasTileId?.let { tileId -> drawable.id to tileId } }.toMap() } + val pinnedTileIds = remember(committedModel) { committedModel.atlas.tiles.filter { tile -> tile.pinned }.mapTo(HashSet()) { tile -> tile.id } } + val sessionAtlasPages = LocalSessionAtlasPages.current + val viewportOverlayColors = rememberViewportOverlayColors() + val overlayColors = LocalUmamoColors.current + val overlayStyle = selectionOverlayStyle(overlayColors) + + // Live values the areaId-keyed pointer loop, the remembered controllers, and the latch effect + // read, so a pan / resize / shown-surface change mid-gesture is seen without re-keying. + val liveCamera = rememberUpdatedState(camera) + val liveSize = rememberUpdatedState(IntSize(widthPx, heightPx)) + val liveGeometries = rememberUpdatedState(geometries) + val liveIslandPick = rememberUpdatedState(islandPick) + val liveFrame = rememberUpdatedState(frame) + val liveSurface = rememberUpdatedState(placementSurface) + + // The per-area modal-gesture bookkeeping (the Edit overlay's shape); the capture is the placement + // gesture and the preview holds each moving island's display positions. + val gesture = remember(areaId) { ModalGestureState() } + var placementDragStatus by placementDragStatusState + + // A committed move's crops linger at their new spots until the resolver's pages catch up with the + // committed atlas; a resolver that never publishes (no page resolver at all) never gets a ghost. + var ghost by remember(areaId) { mutableStateOf(null) } + val bindingAtlas = sessionAtlasPages?.binding?.value?.atlas + val ghostData = ghost + val activeGhost = ghostData?.takeIf { pending -> pending.atlas === committedModel.atlas && bindingAtlas !== pending.atlas } + LaunchedEffect(ghostData, activeGhost) { + if (ghostData != null && activeGhost == null) { + ghost = null + } + } + + // The box machinery over whole islands. The circle callbacks are dormant: a select tool cannot + // arm over a UV area in Object mode (CommandRouting.selectToolArea keeps B / C Edit-only there), + // so they stay sanely wired only so an unforeseen arming degrades to a no-op stroke. + val marquee = + remember(areaId) { + MarqueeSelectController( + seedStroke = { session.selection.value }, + stampStroke = { working, _, _, _, _, _ -> working }, + commitStroke = { stroke -> session.setSelection(stroke) }, + applyBox = { start, end, additive, boxCamera, boxSize -> + val model = session.model.value + val enclosed = + uvIslandsInBox(liveGeometries.value, start, end, boxCamera, boxSize) + .map { drawableId -> SelectionTarget.Drawable(drawableId) } + .filter { target -> model.selectableOf(target) } + session.setSelection(resolveIslandBoxSelection(session.selection.value, enclosed, additive)) + }, + setCircleRadius = { radiusPx -> session.setCircleRadius(radiusPx) }, + clearTool = { session.clearSelectTool() }, + ) + } + + // The idle click-pick / un-armed box flow, bound to the island domain: the pick seams unproject + // the click into display space and run the CPU island picker; the cursor seam converts the + // unprojected point to normalized UV. No onBoxBegin - there is no centroid cache to snapshot, + // the box tests the live display geometry directly. + val objectPick = + remember(areaId) { + ObjectPickController( + session = session, + marquee = marquee, + pickTopmost = { position -> + val (displayX, displayY) = screenToWorld(position.x, position.y, liveCamera.value, liveSize.value) + liveIslandPick.value.topmostAt(displayX, displayY) + }, + pickStack = { position -> + val (displayX, displayY) = screenToWorld(position.x, position.y, liveCamera.value, liveSize.value) + liveIslandPick.value.stackAt(displayX, displayY) + }, + onOverlapRequest = onOverlapRequest, + placeCursor = { displayX, displayY -> + val (cursorU, cursorV) = liveFrame.value.storedUvAt(displayX, displayY) + session.setUvCursor(cursorU, cursorV) + }, + ) + } + + // What a landed evaluation shows: the crops as ghosts at their committed spots until the + // resolver's pages land, and a notice when the result collides or spills. Shared by the confirm + // and by every adjustment from the operation settings strip. + fun publishLanding(gestureData: PlacementGesture, result: PlacementDragResult) { + val crops = + gestureData.movers.mapNotNull { mover -> + val crop = mover.crop ?: return@mapNotNull null + GhostCrop(crop, mover.trim, result.placementByTile.getValue(mover.tileId)) + } + if (sessionAtlasPages != null && crops.isNotEmpty()) { + ghost = PlacementGhost(session.model.value.atlas, gestureData.pageHeight, crops) + } + if (result.overlappingTileIds.isNotEmpty()) { + session.emitNotice("notice.uv.placement.overlap", NoticePlacement.NearCursor) + } else if (result.offPageTileIds.isNotEmpty()) { + session.emitNotice("notice.uv.placement.offPage", NoticePlacement.NearCursor) + } + } + + // Confirms the in-flight placement gesture: commit every mover whose placement changed as ONE undo + // step under the operator's own label, publish the landing, register the gesture on the operation + // settings strip (an adjustment re-evaluates the same frozen gesture over that step), then clear + // the operator. No preview was ever pushed to the renderer, so there is nothing to resync. + fun confirmGesture() { + val gestureData = gesture.capture + val result = gestureData?.result + if (gestureData != null && result != null) { + val changed = changedPlacements(gestureData.movers, result) + if (changed.isNotEmpty()) { + session.setAtlasPlacements(changed, gestureData.transform.operatorKind) + publishLanding(gestureData, result) + registerPlacementAdjustment(session, areaId, gestureData, result) { landed -> publishLanding(gestureData, landed) } + } + } + session.clearUvOperator() + } + + // Drives one pointer frame: the shared operator parameters over the capture's anchor, evaluated + // into a placement per mover and a display affine per moving island. False before the capture + // has landed (it builds off-thread). + fun drivePlacementPreview(operator: MeshOperatorKind, virtualPointer: Offset, activeCamera: ViewportCamera, size: IntSize): Boolean { + val start = gesture.gestureStart ?: return false + val gestureData = gesture.capture ?: return false + val constraint = session.axisConstraint.value + val pointerFrame = TransformGestureFrame(gestureData.transform.anchor, start, virtualPointer, constraint, activeCamera, size) + val parameters = placementGestureParameters(operator, pointerFrame, gestureData.transform.rotationTracker) + val result = + evaluatePlacementDrag( + operatorKind = operator, + parameters = parameters, + movers = gestureData.movers, + bystanders = gestureData.bystanders, + occupancy = gestureData.occupancy, + pageWidth = gestureData.pageWidth, + pageHeight = gestureData.pageHeight, + extrude = gestureData.extrude, + ) + gestureData.result = result + val preview = LinkedHashMap() + for ((drawableId, frozen) in gestureData.frozenPositionsByDrawable) { + val tileId = gestureData.tileByDrawable[drawableId] ?: continue + val affine = result.displayAffineByTile[tileId] ?: continue + preview[drawableId] = applyUvAffine(frozen, affine) + } + gesture.preview = preview + placementDragStatus = result.status + return true + } + + // The modal gesture's commit-side seam over the shared pointer-side controller. + val modalTarget = + object : ModalTransformTarget { + override fun drivePreview(virtualPointer: Offset, camera: ViewportCamera, size: IntSize): Boolean { + // Defensive ownership check (the pointer loop already gates): only the initiating area drives. + val operator = session.activeUvOperator.value?.takeIf { latched -> latched.areaId == areaId } ?: return false + return drivePlacementPreview(operator.kind, virtualPointer, camera, size) + } + + override fun confirm() { + confirmGesture() + } + + override fun cancel() { + session.clearUvOperator() + } + } + + // Escape / the shell's select-gesture cancel: abandon the in-flight box without touching the + // selection. The signal carries no area id, so every mounted collector fires - both cancels are + // no-ops when nothing is in flight here. While the box is live the controller's area-less + // viewportGestureActive flag routes Escape to this signal BEFORE the shell ladder's Object-mode + // selection-clear branch, so Escape drops the box instead of wiping the selection. No tool-kind + // backstop rides here: armed tools cannot arm over a UV area in Object mode. + LaunchedEffect(session) { + session.meshGestureCancelRequests.collect { + marquee.cancel() + objectPick.cancel() + } + } + + // Enter confirms the placement gesture (mirroring a primary click), gated to the INITIATING area + // through the UV latch itself; the Edit overlay is not composed in Object mode, so no other + // collector can double-commit. + LaunchedEffect(session) { + collectModalConfirmRequests(session, { session.activeUvOperator.value?.areaId == areaId }) { + confirmGesture() + } + } + + // Start the placement gesture as a UV operator latches IN THIS AREA; tear it down as it clears. + // The capture builds off-thread (it decodes rasters and wraps crops); a latch that clears while it + // builds (Escape, a mode switch) must not begin a stale gesture, so the latch is re-checked after. + LaunchedEffect(activeOperator) { + val operator = activeOperator?.takeIf { latched -> latched.areaId == areaId } + if (operator == null) { + gesture.end() + placementDragStatus = null + return@LaunchedEffect + } + val surface = liveSurface.value + if (surface == null) { + session.emitNotice("notice.uv.placement.pageViewOnly", NoticePlacement.NearCursor) + session.clearUvOperator() + return@LaunchedEffect + } + val model = session.model.value + val selection = session.selection.value + val shownGeometries = liveGeometries.value + val pivotMode = session.pivotMode.value + val activeDrawableId = (selection.active as? SelectionTarget.Drawable)?.id + val cursorDisplay = session.uvCursor.value?.let { cursor -> liveFrame.value.displayAt(cursor.u, cursor.v) } + val build = + withContext(Dispatchers.Default) { + buildPlacementGesture(model, surface, selection, shownGeometries, pivotMode, activeDrawableId, cursorDisplay, operator.kind) + } + if (session.activeUvOperator.value != operator) { + return@LaunchedEffect + } + when (build) { + PlacementGestureBuild.NotOnPage -> { + session.emitNotice("notice.uv.placement.notOnPage", NoticePlacement.NearCursor) + session.clearUvOperator() + } + + PlacementGestureBuild.NotDerivable -> { + session.emitNotice("notice.uv.placement.notDerivable", NoticePlacement.NearCursor) + session.clearUvOperator() + } + + is PlacementGestureBuild.Ready -> gesture.begin(build.gesture, gesture.lastPointer) + } + } + + // The unmount guard: area death (corner-join, space switch, workspace tab switch) mid-gesture must + // not strand the area-less viewportGestureActive flag true or leave the host's readout showing. + // The controller's boxing latch and the gesture's end() make both no-ops otherwise. + DisposableEffect(areaId) { + onDispose { + objectPick.cancel() + if (gesture.end()) { + placementDragStatusState.value = null + } + } + } + + val ownsGesture = activeOperator?.areaId == areaId + Box( + modifier = + modifier + .fillMaxSize() + .onGloballyPositioned { coordinates -> gesture.areaScreenOrigin = coordinates.positionOnScreen() } + // While THIS AREA'S placement gesture runs, hide the OS cursor so only the overlay's + // drawn cursor shows; a gesture owned by another area leaves this cursor alone. + .then( + if (ownsGesture) { + Modifier.pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + } else { + Modifier + }, + ) + .pointerInput(areaId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + gesture.lastPointer = change.position + val latchedUvOperator = session.activeUvOperator.value + // A gesture belongs to its initiating area: another area's UV operator, or any + // viewport-owned operator or armed tool (which can never belong to a UV area in + // Object mode), leaves this overlay fully inert - dropping an in-flight box. + // Escape and Enter stay global through the shell ladder, and navigation falls + // through to the layer below. + if (session.activeMeshOperator.value != null || + session.activeObjectOperator.value != null || + (latchedUvOperator != null && latchedUvOperator.areaId != areaId) || + session.activeSelectTool.value != null + ) { + objectPick.cancel() + continue + } + val activeCamera = liveCamera.value + val size = liveSize.value + if (latchedUvOperator != null) { + // MODAL: the placement gesture owns the pointer through the shared controller + // (stale discard, virtual pointer, cursor wrap, LMB-confirm / RMB-cancel). + objectPick.cancel() + gesture.lastPointer = gesture.modalController.handleEvent(event, change, modalTarget, activeCamera, size, gesture.areaScreenOrigin) + } else { + objectPick.handleIdleEvent(event, change, activeCamera, size) + } + } + } + }, + ) { + // Two sibling canvases, each in its OWN layer: a draw-state invalidation re-records every draw + // lambda sharing a layer, so the per-move gesture chrome (the rubber band, the modal HUD) lives + // in a small layer of its own and the island wireframes plus the drag preview - the expensive + // pass - stay cached in theirs. The wireframe layer composites OFFSCREEN: a default layer + // retains a display list that every window repaint replays (re-stroking every edge), where the + // offscreen buffer rasterizes once per content change and blits per frame. + Canvas( + modifier = + Modifier.fillMaxSize().graphicsLayer { + compositingStrategy = CompositingStrategy.Offscreen + }, + ) { + val areaSize = IntSize(widthPx, heightPx) + val capture = gesture.capture + val result = capture?.result + val activePreview = gesture.preview.takeIf { capture != null } + + // The drag preview under the islands: each mover's original spot dimmed (the art is leaving + // it), its crop drawn where the placement now puts it, then a committed move's ghosts while + // the resolver composes the real pixels. + if (capture != null && result != null) { + for (mover in capture.movers) { + drawTileQuad(mover.trim, mover.placement, capture.pageHeight, camera, areaSize) { quad -> + drawPath(quad, overlayColors.overlayScrim) + } + } + for (mover in capture.movers) { + val crop = mover.crop ?: continue + val placement = result.placementByTile[mover.tileId] ?: continue + drawTileCrop(crop, mover.trim, placement, capture.pageHeight, camera, areaSize) + } + } + activeGhost?.let { pending -> + for (ghostCrop in pending.crops) { + drawTileCrop(ghostCrop.crop, ghostCrop.trim, ghostCrop.placement, pending.pageHeight, camera, areaSize) + } + } + + val selectedIds = + objectSelection.targets + .mapNotNull { target -> (target as? SelectionTarget.Drawable)?.id } + .toSet() + val activeId = (objectSelection.active as? SelectionTarget.Drawable)?.id + // The islands of every colliding tile - the triangles ARE the sampled region, so they are the + // honest thing to flag - draw their edges in the warning color, movers and bystanders alike; + // a pinned tile's islands draw theirs in the pinned color, the warning winning while a + // collision is live (a warning is transient, a pin is state). + val collidingTileIds = result?.overlappingTileIds ?: emptySet() + // Islands paint back-to-front by the rest front rank, so the front-most island's wireframe + // draws last - the painted stacking matches the pick order. Styling is per-island palette + // substitution: the idle palette IS the dim style; a selected island fills and outlines with + // the selected colors; the active island keeps the selected fill under the active-green + // outline (faceActive is deliberately never a fill - it would blank the art). During a + // placement gesture a moving island draws from the live preview. + val paintOrdered = geometries.sortedBy { geometry -> islandPick.frontRankById[geometry.drawableId] ?: 0f } + for (geometry in paintOrdered) { + val styled = + when { + geometry.drawableId == activeId -> + viewportOverlayColors.copy(faceIdle = viewportOverlayColors.faceSelected, edgeIdle = viewportOverlayColors.edgeActive) + geometry.drawableId in selectedIds -> + viewportOverlayColors.copy(faceIdle = viewportOverlayColors.faceSelected, edgeIdle = viewportOverlayColors.edgeSelected) + else -> viewportOverlayColors + } + val tileId = tileByDrawableId[geometry.drawableId] + val islandColors = + when { + collidingTileIds.isNotEmpty() && tileId in collidingTileIds -> + styled.copy(edgeIdle = viewportOverlayColors.warning, edgeSelected = viewportOverlayColors.warning, edgeActive = viewportOverlayColors.warning) + tileId in pinnedTileIds -> + styled.copy(edgeIdle = viewportOverlayColors.pinnedPlacement, edgeSelected = viewportOverlayColors.pinnedPlacement, edgeActive = viewportOverlayColors.pinnedPlacement) + else -> styled + } + drawMeshWireframe( + positions = activePreview?.get(geometry.drawableId) ?: geometry.positions, + indices = geometry.indices, + edges = geometry.edges, + highlight = buildHighlightSets(emptySet(), null, meshSelection.selectMode, geometry.indices), + selectMode = meshSelection.selectMode, + colors = islandColors, + camera = camera, + size = areaSize, + objectOverlay = true, + ) + } + + // The painter's side of a collision on top: a mover whose paint lies under another tile's + // triangles outlines its opaque region with the art's own contour (never a box), and a + // spill outlines the trim that leaves the page. A bystander painter has no contour without + // a decode; its tinted islands stand for it. + if (capture != null && result != null) { + val warningStroke = Stroke(width = 2f) + for (mover in capture.movers) { + val placement = result.placementByTile[mover.tileId] ?: continue + if (mover.tileId in result.paintingTileIds) { + drawContours(mover.contours, placement, capture.pageHeight, camera, areaSize, viewportOverlayColors.warning, warningStroke) + } + if (mover.tileId in result.offPageTileIds) { + drawTileQuad(mover.trim, placement, capture.pageHeight, camera, areaSize) { quad -> + drawPath(quad, viewportOverlayColors.warning, style = warningStroke) + } + } + } + } + } + Canvas(modifier = Modifier.fillMaxSize().graphicsLayer()) { + drawRubberBand(marquee.boxStart, marquee.boxCurrent, overlayStyle) + + // Modal transform HUD (axis line, pivot dash, drawn cursor), shared chrome with the other + // gizmo overlays. Only the initiating area draws it - the capture exists solely in the + // overlay whose area the operator latch names. + val hudPivot = gesture.capture?.transform?.anchor + if (ownsGesture && hudPivot != null) { + drawModalTransformHud( + axisConstraint = axisConstraint, + pivotScreen = worldToScreen(hudPivot.first, hudPivot.second, camera, IntSize(widthPx, heightPx)), + virtualPointer = gesture.cursorWrap.virtualPointer(gesture.lastPointer), + realPointer = gesture.lastPointer, + viewport = Size(widthPx.toFloat(), heightPx.toFloat()), + lineColor = overlayColors.viewportMarquee, + pointerCursor = LocalUmamoCursors.nsewScroll, + proportionalRadiusPx = null, + ) + } + } + } +} + +/** + * Where a tile-local point lands on screen under [placement]: through the placement into page pixels, + * through the display flip, and through the area camera. + * + * @param Float tileX The tile-local x. + * @param Float tileY The tile-local y. + * @param FloatArray tileToDisplay The tile-to-display affine (the placement's, flipped). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Offset The screen position. + */ +private fun tileToScreen(tileX: Float, tileY: Float, tileToDisplay: FloatArray, camera: ViewportCamera, size: IntSize): Offset { + val displayX = tileToDisplay[0] * tileX + tileToDisplay[1] * tileY + tileToDisplay[2] + val displayY = tileToDisplay[3] * tileX + tileToDisplay[4] * tileY + tileToDisplay[5] + return worldToScreen(displayX, displayY, camera, size) +} + +/** + * Draws a tile's trim crop where [placement] puts it: the crop's pixel grid is carried by a matrix + * fitted to three transformed trim corners, so rotation and scale come along, bilinear-filtered. + * + * @param ImageBitmap crop The trim's pixels. + * @param LayerBounds trim The trim the crop covers, raster-local. + * @param AtlasPlacement placement Where the tile sits. + * @param Int pageHeight The page height, for the display flip. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + */ +private fun DrawScope.drawTileCrop( + crop: ImageBitmap, + trim: LayerBounds, + placement: AtlasPlacement, + pageHeight: Int, + camera: ViewportCamera, + size: IntSize, +) { + val tileToDisplay = tileToDisplayAffine(placement, pageHeight) + val origin = tileToScreen(trim.left.toFloat(), trim.top.toFloat(), tileToDisplay, camera, size) + val xAxis = tileToScreen(trim.left + 1f, trim.top.toFloat(), tileToDisplay, camera, size) - origin + val yAxis = tileToScreen(trim.left.toFloat(), trim.top + 1f, tileToDisplay, camera, size) - origin + val matrix = Matrix() + matrix.values[Matrix.ScaleX] = xAxis.x + matrix.values[Matrix.SkewY] = xAxis.y + matrix.values[Matrix.SkewX] = yAxis.x + matrix.values[Matrix.ScaleY] = yAxis.y + matrix.values[Matrix.TranslateX] = origin.x + matrix.values[Matrix.TranslateY] = origin.y + withTransform({ transform(matrix) }) { + drawImage(image = crop, dstSize = IntSize(crop.width, crop.height), filterQuality = FilterQuality.Low) + } +} + +/** + * Hands [draw] the screen-space quad of a tile's trim under [placement]. + * + * @param LayerBounds trim The trim, raster-local. + * @param AtlasPlacement placement Where the tile sits. + * @param Int pageHeight The page height, for the display flip. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @param Function draw Draws the closed quad. + */ +private fun DrawScope.drawTileQuad( + trim: LayerBounds, + placement: AtlasPlacement, + pageHeight: Int, + camera: ViewportCamera, + size: IntSize, + draw: DrawScope.(Path) -> Unit, +) { + val tileToDisplay = tileToDisplayAffine(placement, pageHeight) + val left = trim.left.toFloat() + val top = trim.top.toFloat() + val right = (trim.left + trim.width).toFloat() + val bottom = (trim.top + trim.height).toFloat() + val quad = Path() + val first = tileToScreen(left, top, tileToDisplay, camera, size) + quad.moveTo(first.x, first.y) + for ((cornerX, cornerY) in listOf(right to top, right to bottom, left to bottom)) { + val corner = tileToScreen(cornerX, cornerY, tileToDisplay, camera, size) + quad.lineTo(corner.x, corner.y) + } + quad.close() + draw(quad) +} + +/** + * Strokes a tile's opaque contours on screen under [placement]: each loop's lattice corners carried + * through the placement and the camera, holes included, so the outline follows the art. + * + * @param List contours The loops, raster-local. + * @param AtlasPlacement placement Where the tile sits. + * @param Int pageHeight The page height, for the display flip. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @param Color color The stroke color. + * @param Stroke stroke The stroke style. + */ +private fun DrawScope.drawContours( + contours: List, + placement: AtlasPlacement, + pageHeight: Int, + camera: ViewportCamera, + size: IntSize, + color: Color, + stroke: Stroke, +) { + val tileToDisplay = tileToDisplayAffine(placement, pageHeight) + for (contour in contours) { + if (contour.points.size < 6) { + continue + } + val outline = Path() + var pointIndex = 0 + while (pointIndex + 1 < contour.points.size) { + val screen = tileToScreen(contour.points[pointIndex].toFloat(), contour.points[pointIndex + 1].toFloat(), tileToDisplay, camera, size) + if (pointIndex == 0) { + outline.moveTo(screen.x, screen.y) + } else { + outline.lineTo(screen.x, screen.y) + } + pointIndex += 2 + } + outline.close() + drawPath(outline, color, style = stroke) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvPlacementAdjust.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvPlacementAdjust.kt new file mode 100644 index 0000000..f6e4bfe --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvPlacementAdjust.kt @@ -0,0 +1,184 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.OperatorParameter +import org.umamo.edit.ParameterUnit +import org.umamo.edit.TRANSFORM_ANGLE_LIMIT +import org.umamo.edit.TRANSFORM_SCALE_MAX +import org.umamo.edit.TRANSFORM_SCALE_MIN +import org.umamo.edit.TRANSFORM_SCALE_STEP +import org.umamo.edit.floatValue +import org.umamo.edit.intValue +import org.umamo.edit.withAtlasPlacements +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import kotlin.math.PI + +/* + * The placement gesture's face on the operation settings strip: the numbers a Grab / Rotate / Scale + * committed as the strip's typed rows, the gesture parameters those rows mean, and the registration + * whose rerun re-evaluates the SAME frozen gesture (movers, bystanders, pivots, the page's paint) + * from the base snapshot and lands over the gesture's own history step. + * + * There is no axis-constraint row. A lock only zeroes one Grab component or pins one Scale factor + * at 1, so the per-component rows already say everything the lock said, and the evaluation reads a + * non-uniform Scale as the tile-axis scale a locked gesture produces. The rows are built from the + * drag's own readout, so the strip shows exactly the numbers the HUD showed at confirm. + */ + +/** The parameter keys the placement gesture's rows carry (the strip maps them to labels). */ +internal object PlacementParameterKeys { + const val DELTA_X = "placement.deltaX" + const val DELTA_Y = "placement.deltaY" + const val ANGLE = "placement.angle" + const val SCALE_X = "placement.scaleX" + const val SCALE_Y = "placement.scaleY" +} + +/** + * The strip's rows for the gesture [status] describes: a Grab's move in whole page pixels (y down, + * as the HUD reads it), a Rotate's page-space angle, a Scale's two factors. The angle and scale + * limits are the transform rows' (:edit's TransformAdjust.kt), so the two UV strips accept the same values. + * + * @param PlacementDragStatus status The drag's readout at confirm. + * @param Int pageWidth The page width, bounding the horizontal move. + * @param Int pageHeight The page height, bounding the vertical move. + * @return List The rows, empty for an operator that has none (a slide never reaches a placement). + */ +internal fun placementParameters(status: PlacementDragStatus, pageWidth: Int, pageHeight: Int): List = + when (status.operatorKind) { + MeshOperatorKind.Grab -> + listOf( + OperatorParameter.IntParameter(PlacementParameterKeys.DELTA_X, PlacementParameterKeys.DELTA_X, status.deltaX, -pageWidth, pageWidth, unit = ParameterUnit.Pixels), + OperatorParameter.IntParameter(PlacementParameterKeys.DELTA_Y, PlacementParameterKeys.DELTA_Y, status.deltaY, -pageHeight, pageHeight, unit = ParameterUnit.Pixels), + ) + + MeshOperatorKind.Rotate -> + listOf( + OperatorParameter.FloatParameter( + PlacementParameterKeys.ANGLE, + PlacementParameterKeys.ANGLE, + status.angleDegrees, + -TRANSFORM_ANGLE_LIMIT, + TRANSFORM_ANGLE_LIMIT, + unit = ParameterUnit.Degrees, + ), + ) + + MeshOperatorKind.Scale -> + listOf( + OperatorParameter.FloatParameter(PlacementParameterKeys.SCALE_X, PlacementParameterKeys.SCALE_X, status.factorX, TRANSFORM_SCALE_MIN, TRANSFORM_SCALE_MAX, TRANSFORM_SCALE_STEP), + OperatorParameter.FloatParameter(PlacementParameterKeys.SCALE_Y, PlacementParameterKeys.SCALE_Y, status.factorY, TRANSFORM_SCALE_MIN, TRANSFORM_SCALE_MAX, TRANSFORM_SCALE_STEP), + ) + + MeshOperatorKind.VertexSlide -> emptyList() + } + +/** + * The gesture parameters the strip's rows mean - the inverse of [placementParameters], back into + * the display-space form [evaluatePlacementDrag] takes: the move's y flips (display y runs up), and + * the angle's sign flips with it (the flip mirrors a rotation's sense). + * + * @param MeshOperatorKind kind The operator the rows belong to. + * @param List parameters The rows, possibly edited. + * @return PlacementGestureParameters The parameters to evaluate. + */ +internal fun placementGestureParametersOf(kind: MeshOperatorKind, parameters: List): PlacementGestureParameters = + when (kind) { + MeshOperatorKind.Grab -> + PlacementGestureParameters( + deltaDisplayX = parameters.intValue(PlacementParameterKeys.DELTA_X, 0).toFloat(), + deltaDisplayY = -parameters.intValue(PlacementParameterKeys.DELTA_Y, 0).toFloat(), + factorX = 1f, + factorY = 1f, + rotationRadians = 0f, + ) + + MeshOperatorKind.Rotate -> + PlacementGestureParameters( + deltaDisplayX = 0f, + deltaDisplayY = 0f, + factorX = 1f, + factorY = 1f, + rotationRadians = (-parameters.floatValue(PlacementParameterKeys.ANGLE, 0f) * PI / 180.0).toFloat(), + ) + + MeshOperatorKind.Scale -> + PlacementGestureParameters( + deltaDisplayX = 0f, + deltaDisplayY = 0f, + factorX = parameters.floatValue(PlacementParameterKeys.SCALE_X, 1f), + factorY = parameters.floatValue(PlacementParameterKeys.SCALE_Y, 1f), + rotationRadians = 0f, + ) + + MeshOperatorKind.VertexSlide -> PlacementGestureParameters(0f, 0f, 1f, 1f, 0f) + } + +/** + * The placements a gesture's evaluation actually changed: every mover whose placement under + * [result] differs from where it sat at latch - what the commit writes, and what a rerun re-writes. + * + * @param List movers The gesture's movers. + * @param PlacementDragResult result The evaluation. + * @return Map Each changed tile's new placement, in mover order. + */ +internal fun changedPlacements(movers: List, result: PlacementDragResult): Map { + val changed = LinkedHashMap() + for (mover in movers) { + val next = result.placementByTile[mover.tileId] ?: continue + if (next != mover.placement) { + changed[mover.tileId] = next + } + } + return changed +} + +/** + * Registers the placement gesture that just committed [result] as the session's adjustable + * operation. Call it right after the commit. An adjustment re-evaluates the retained [gesture] + * under the edited rows - the same movers, bystanders, pivots, and page paint the drag ran over, so + * the collision warnings stay honest - lands the placements over the gesture's own step from the + * record's base, and hands the new evaluation to [onLanded] (the overlay's ghosts and notices). + * Synchronous: an evaluation is the per-pointer-frame cost. + * + * @param EditorSession session The session the gesture committed into. + * @param String areaId The UV editor the gesture ran in (where the strip shows). + * @param PlacementGesture gesture The frozen gesture. + * @param PlacementDragResult result The evaluation the commit wrote. + * @param Function onLanded Receives each adjustment's evaluation once it has landed. + * @return AdjustableOperation? The record, or null when the session refused the registration (no + * commit was pushed) or the operator has no rows. + */ +internal fun registerPlacementAdjustment( + session: EditorSession, + areaId: String, + gesture: PlacementGesture, + result: PlacementDragResult, + onLanded: (PlacementDragResult) -> Unit, +): AdjustableOperation? { + val kind = gesture.transform.operatorKind + val parameters = placementParameters(result.status, gesture.pageWidth, gesture.pageHeight) + if (parameters.isEmpty()) { + return null + } + return session.registerAdjustableOperation(session.model.value, areaId, parameters) { record -> + val adjusted = + evaluatePlacementDrag( + operatorKind = kind, + parameters = placementGestureParametersOf(kind, record.parameters), + movers = gesture.movers, + bystanders = gesture.bystanders, + occupancy = gesture.occupancy, + pageWidth = gesture.pageWidth, + pageHeight = gesture.pageHeight, + extrude = gesture.extrude, + ) + val landed = record.baseSnapshot.model.withAtlasPlacements(changedPlacements(gesture.movers, adjusted)) + if (session.amendLastCommit(record, landed)) { + onLanded(adjusted) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvPlacementGesture.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvPlacementGesture.kt new file mode 100644 index 0000000..fffb3c2 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/UvPlacementGesture.kt @@ -0,0 +1,622 @@ +package org.umamo.ui.viewport + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.ImageBitmap +import org.umamo.edit.IndividualOriginScope +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshTransforms +import org.umamo.edit.ModalCaptureSource +import org.umamo.edit.ModalTransformCapture +import org.umamo.edit.RotationAngleTracker +import org.umamo.edit.Selection +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.buildModalTransformCapture +import org.umamo.edit.composedWith +import org.umamo.edit.localAxisScaleAboutAffine +import org.umamo.edit.placementDragTileIds +import org.umamo.edit.rotationAboutAffine +import org.umamo.edit.scaleAboutAffine +import org.umamo.edit.translationAffine +import org.umamo.format.art.AlphaContour +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.atlas.AtlasPackReserve +import org.umamo.render.DecodedImage +import org.umamo.render.PageOccupancy +import org.umamo.render.PixelRect +import org.umamo.render.PlacementFootprint +import org.umamo.render.SampledRegion +import org.umamo.render.SourceArtRasters +import org.umamo.render.TileMeshMask +import org.umamo.render.TileOpaqueMask +import org.umamo.render.meshMaskOf +import org.umamo.render.meshReserveByTile +import org.umamo.render.placementFootprint +import org.umamo.render.sampledRegionHitsMask +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.composeAffine +import org.umamo.runtime.model.placementAffine +import org.umamo.ui.graphics.RgbaAlphaType +import org.umamo.ui.graphics.rgbaToImageBitmap +import kotlin.math.PI +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.roundToInt + +/* + * The placement gesture's pointer-side bookkeeping: what a UV editor's Object overlay freezes when a + * placement operator latches, how one pointer frame's parameters turn into a placement per tile, and + * the readout the HUD shows. Everything here is plain data and pure functions; the commit is the + * session's (setAtlasPlacements) and the algebra is :edit's (composedWith and the affine builders). + * + * Two frames meet here. The overlay measures in DISPLAY space - texels with y up, what the wireframes + * and the camera speak - and a placement lives in PAGE space, y down. The two differ by the flip + * F(x, y) = (x, h - y), its own inverse, so a display affine G becomes the page affine F . G . F and a + * page affine comes back the same way. Every conversion goes through the two helpers below; nothing + * else reasons about the sign of y. + * + * A collision is a mesh sampling paint (AtlasPlacementDrag.kt), exact on both sides: each tile's + * sampled region is the rasterized coverage of its triangles, each mover's painted region is its opaque + * mask, the bystanders' paint is the shown page's own alpha with the movers' old spots read as empty, + * and every pointer frame tests the movers' triangles against that page and the bystanders' triangles + * against the movers' masks. + */ + +/** + * What a UV editor showing an ATLAS PAGE hands its Object overlay so a placement gesture can run there; + * absent over a source-layer view, where a placement has no page to move on. + * + * @property Int pageWidth The shown page's width in texels. + * @property Int pageHeight The shown page's height in texels. + * @property SourceArtRasters artRasters The document's source-art pixels (the movers' crops and masks). + * @property DecodedImage? pageImage The shown page's decoded pixels - the bystanders' paint - or + * null before the page has loaded, in which case only movers test against each other. + */ +internal class UvPlacementSurface( + val pageWidth: Int, + val pageHeight: Int, + val artRasters: SourceArtRasters, + val pageImage: DecodedImage?, +) + +/** + * The drag's live readout for the HUD badge. + * + * @property MeshOperatorKind operatorKind The running operator. + * @property Int deltaX The snapped horizontal move in page pixels (Grab). + * @property Int deltaY The snapped vertical move in page pixels, positive down (Grab). + * @property Float angleDegrees The page-space rotation applied so far (Rotate). + * @property Float factorX The factor along the tile's x axis (Scale). + * @property Float factorY The factor along the tile's y axis (Scale). + * @property Int overlapCount How many moving tiles currently collide with another tile. + * @property Boolean offPage Whether any moving tile's opaque pixels spill past the page edge. + */ +internal class PlacementDragStatus( + val operatorKind: MeshOperatorKind, + val deltaX: Int, + val deltaY: Int, + val angleDegrees: Float, + val factorX: Float, + val factorY: Float, + val overlapCount: Int, + val offPage: Boolean, +) + +/** + * One tile a placement gesture moves, frozen at latch. + * + * @property AtlasTileId tileId The tile. + * @property AtlasPlacement placement Where it sat when the gesture began. + * @property LayerBounds trim Its opaque bounds, raster-local (what the composer draws). + * @property AtlasPackReserve? reserve Its mesh reach, raster-local (the pivot's center and the spot it vacates), or null when none is measurable. + * @property TileMeshMask? meshMask The coverage of its triangles - its sampled region - or null when none is measurable. + * @property TileOpaqueMask? mask Its opaque texels - its painted region - or null when the art could not be read. + * @property List contours The outlines of its opaque region, raster-local, for the painter chrome. + * @property Float pivotDisplayX The pivot it turns and scales about, display x. + * @property Float pivotDisplayY The pivot's display y. + * @property ImageBitmap? crop Its trim's pixels for the drag preview, or null when they could not be wrapped. + */ +internal class PlacementMover( + val tileId: AtlasTileId, + val placement: AtlasPlacement, + val trim: LayerBounds, + val reserve: AtlasPackReserve?, + val meshMask: TileMeshMask?, + val mask: TileOpaqueMask?, + val contours: List, + val pivotDisplayX: Float, + val pivotDisplayY: Float, + val crop: ImageBitmap?, +) + +/** + * One placed tile on the page that is NOT moving: what the movers may collide with. + * + * @property AtlasTileId tileId The tile. + * @property AtlasPlacement placement Where it sits. + * @property SampledRegion? sampled The coverage of its triangles on the page, or null when it has no measurable mesh. + * @property PlacementFootprint paintedBounds The bounds its paint can occupy (its whole tile through + * the placement, grown by the extrusion band), for attributing a painted pixel the page reports. + */ +internal class PlacementBystander( + val tileId: AtlasTileId, + val placement: AtlasPlacement, + val sampled: SampledRegion?, + val paintedBounds: PlacementFootprint, +) + +/** + * The parameters one pointer frame yields, in display units, exactly as the shared operator math + * derives them for the mesh overlays. + * + * @property Float deltaDisplayX The Grab translation's display x. + * @property Float deltaDisplayY The Grab translation's display y (y up). + * @property Float factorX The Scale factor along display x. + * @property Float factorY The Scale factor along display y. + * @property Float rotationRadians The Rotate angle in the display frame's sense. + */ +internal class PlacementGestureParameters( + val deltaDisplayX: Float, + val deltaDisplayY: Float, + val factorX: Float, + val factorY: Float, + val rotationRadians: Float, +) + +/** + * One pointer frame's evaluation over every mover. + * + * @property Map placementByTile Each mover's placement under the gesture. + * @property Map displayAffineByTile The display-space affine each mover's islands follow. + * @property Set overlappingTileIds Every tile (mover or bystander) in a collision. + * @property Set samplingTileIds The colliding tiles whose MESH reads another tile's paint. + * @property Set paintingTileIds The colliding tiles whose PAINT lies under another tile's mesh. + * @property Set offPageTileIds Every mover whose opaque pixels spill past the page edge. + * @property PlacementDragStatus status The HUD readout. + */ +internal class PlacementDragResult( + val placementByTile: Map, + val displayAffineByTile: Map, + val overlappingTileIds: Set, + val samplingTileIds: Set, + val paintingTileIds: Set, + val offPageTileIds: Set, + val status: PlacementDragStatus, +) + +/** + * The captured state of an in-flight placement gesture. + * + * @property ModalTransformCapture transform The shared capture over the moving islands: its anchor is + * the HUD pivot and the shared-pivot modes' center, its rotation tracker keeps Rotate continuous. + * @property List movers The tiles the gesture moves. + * @property List bystanders The page's other placed tiles, for the collision test. + * @property PageOccupancy? occupancy The shown page's paint with the movers' old spots read as + * empty, or null when the page was not available (movers then test only each other). + * @property Map tileByDrawable Each moving drawable's tile. + * @property Map frozenPositionsByDrawable Each moving drawable's display positions at latch. + * @property Int pageWidth The page width in pixels. + * @property Int pageHeight The page height in pixels. + * @property Int extrude The composer's edge extrusion, the band that counts as paint around a tile. + */ +internal class PlacementGesture( + val transform: ModalTransformCapture, + val movers: List, + val bystanders: List, + val occupancy: PageOccupancy?, + val tileByDrawable: Map, + val frozenPositionsByDrawable: Map, + val pageWidth: Int, + val pageHeight: Int, + val extrude: Int, +) { + /** The latest pointer frame's evaluation, or null before the first drive. */ + var result by mutableStateOf(null) +} + +/** Why a placement gesture could not be built, or the gesture. */ +internal sealed interface PlacementGestureBuild { + /** Nothing selected is packed onto the shown page. */ + data object NotOnPage : PlacementGestureBuild + + /** The atlas cannot be recomposed from its source art, so no placement may move. */ + data object NotDerivable : PlacementGestureBuild + + /** + * The gesture is ready to drive. + * + * @property PlacementGesture gesture The frozen capture. + */ + class Ready(val gesture: PlacementGesture) : PlacementGestureBuild +} + +/** + * The page-space form of a display-space affine (and back - the flip is its own inverse). + * + * @param FloatArray affine The affine in one frame. + * @param Int pageHeight The page height, the flip's line. + * @return FloatArray The same transform in the other frame. + */ +internal fun flipAffineFrame(affine: FloatArray, pageHeight: Int): FloatArray { + val flip = floatArrayOf(1f, 0f, 0f, 0f, -1f, pageHeight.toFloat()) + return composeAffine(flip, composeAffine(affine, flip)) +} + +/** + * Where a tile's pixels land in DISPLAY space under [placement]: the placement's tile-to-page mapping + * followed by the flip. A point mapping, so the flip applies once, after the placement - unlike a + * transform, which [flipAffineFrame] conjugates (flip, transform, flip). Mixing the two draws the + * art mirrored below the page. + * + * @param AtlasPlacement placement The tile's placement. + * @param Int pageHeight The page height, the flip's line. + * @return FloatArray The tile-pixel to display-texel affine. + */ +internal fun tileToDisplayAffine(placement: AtlasPlacement, pageHeight: Int): FloatArray = + composeAffine(floatArrayOf(1f, 0f, 0f, 0f, -1f, pageHeight.toFloat()), placementAffine(placement)) + +/** + * The parameters one pointer frame yields for [operatorKind], through the same helpers the mesh + * overlays' operator math uses. + * + * @param MeshOperatorKind operatorKind The running operator. + * @param TransformGestureFrame frame The pointer frame. + * @param RotationAngleTracker rotationTracker The gesture's angle accumulator. + * @return PlacementGestureParameters The display-space parameters. + */ +internal fun placementGestureParameters( + operatorKind: MeshOperatorKind, + frame: TransformGestureFrame, + rotationTracker: RotationAngleTracker, +): PlacementGestureParameters = + when (operatorKind) { + MeshOperatorKind.Grab -> { + val (deltaX, deltaY) = gestureTranslation(frame) + PlacementGestureParameters(deltaX, deltaY, 1f, 1f, 0f) + } + + MeshOperatorKind.Scale -> { + val (factorX, factorY) = gestureScaleFactors(frame) + PlacementGestureParameters(0f, 0f, factorX, factorY, 0f) + } + + MeshOperatorKind.Rotate -> PlacementGestureParameters(0f, 0f, 1f, 1f, gestureRotationRadians(frame, rotationTracker)) + MeshOperatorKind.VertexSlide -> PlacementGestureParameters(0f, 0f, 1f, 1f, 0f) + } + +/** + * Evaluates one pointer frame: each mover's placement under the gesture, the display affine its + * islands follow, and the collisions the HUD and the chrome warn about. + * + * Grab snaps to whole page pixels (an integer placement keeps the packer's exact blit). Rotate and a + * uniform Scale turn about each mover's pivot as similarities, which every placement can express. A + * non-uniform Scale - what an axis lock produces, and what the strip's two factor rows can ask for - + * runs along the tile's OWN axes (the only expressible form for a rotated tile; the page's axes for + * an unrotated one), so its display affine is derived from the placement it produced rather than + * assumed. A product no placement can hold leaves that tile where it is. + * + * A collision is a mesh sampling paint, exact on both sides: a mover's triangles against the page's + * paint (with the movers' old spots read as empty) and against the other movers' masks, and every + * bystander's triangles against each mover's mask, the composer's extrusion band counted as paint. A + * painted pixel the page reports is attributed to the bystanders whose paint can reach it. Off-page + * is the mover's opaque bounds leaving the page; a mesh reaching past the page over transparent + * pixels is not a warning. + * + * @param MeshOperatorKind operatorKind The running operator. + * @param PlacementGestureParameters parameters This frame's parameters. + * @param List movers The moving tiles. + * @param List bystanders The page's other placed tiles. + * @param PageOccupancy? occupancy The page's paint, or null to skip the page test. + * @param Int pageWidth The page width in pixels. + * @param Int pageHeight The page height in pixels. + * @param Int extrude The composer's edge extrusion. + * @return PlacementDragResult The evaluation. + */ +internal fun evaluatePlacementDrag( + operatorKind: MeshOperatorKind, + parameters: PlacementGestureParameters, + movers: List, + bystanders: List, + occupancy: PageOccupancy?, + pageWidth: Int, + pageHeight: Int, + extrude: Int, +): PlacementDragResult { + val snappedDeltaX = parameters.deltaDisplayX.roundToInt() + val snappedDeltaY = (-parameters.deltaDisplayY).roundToInt() + val placementByTile = LinkedHashMap() + val displayAffineByTile = LinkedHashMap() + for (mover in movers) { + val pageAffine = + when (operatorKind) { + MeshOperatorKind.Grab -> translationAffine(snappedDeltaX.toFloat(), snappedDeltaY.toFloat()) + MeshOperatorKind.Rotate -> + flipAffineFrame(rotationAboutAffine(mover.pivotDisplayX, mover.pivotDisplayY, parameters.rotationRadians), pageHeight) + MeshOperatorKind.Scale -> + if (parameters.factorX == parameters.factorY) { + flipAffineFrame(scaleAboutAffine(mover.pivotDisplayX, mover.pivotDisplayY, parameters.factorX, parameters.factorY), pageHeight) + } else { + localAxisScaleAboutAffine( + mover.placement, + mover.pivotDisplayX, + pageHeight - mover.pivotDisplayY, + parameters.factorX, + parameters.factorY, + ) + } + MeshOperatorKind.VertexSlide -> translationAffine(0f, 0f) + } + val next = mover.placement.composedWith(pageAffine) + if (next == null) { + placementByTile[mover.tileId] = mover.placement + displayAffineByTile[mover.tileId] = translationAffine(0f, 0f) + } else { + placementByTile[mover.tileId] = next + displayAffineByTile[mover.tileId] = flipAffineFrame(pageAffine, pageHeight) + } + } + + val overlapping = HashSet() + val sampling = HashSet() + val painting = HashSet() + val offPage = HashSet() + for ((moverIndex, mover) in movers.withIndex()) { + val next = placementByTile.getValue(mover.tileId) + if (placementFootprint(next, mover.trim, reserve = null).exceeds(pageWidth, pageHeight)) { + offPage.add(mover.tileId) + } + val sampled = mover.meshMask?.let { coverage -> SampledRegion(next, coverage) } + // The mover's mesh over the page's paint: the pixel found is attributed to whichever bystanders + // can have painted it. + if (sampled != null && occupancy != null) { + val hit = occupancy.firstPaintedPixelIn(sampled) + if (hit != null) { + overlapping.add(mover.tileId) + sampling.add(mover.tileId) + for (bystander in bystanders) { + if (bystander.paintedBounds.overlaps(PlacementFootprint(hit.left.toFloat(), hit.top.toFloat(), hit.right.toFloat(), hit.bottom.toFloat()))) { + overlapping.add(bystander.tileId) + painting.add(bystander.tileId) + } + } + } + } + // The bystanders' meshes over the mover's paint. + val mask = mover.mask + if (mask != null) { + for (bystander in bystanders) { + val bystanderSampled = bystander.sampled ?: continue + if (sampledRegionHitsMask(bystanderSampled, next, mask, extrude)) { + overlapping.add(mover.tileId) + painting.add(mover.tileId) + overlapping.add(bystander.tileId) + sampling.add(bystander.tileId) + } + } + } + // The other movers, both ways, each at its own new placement. + for (otherIndex in movers.indices) { + if (otherIndex == moverIndex) { + continue + } + val other = movers[otherIndex] + val otherMask = other.mask ?: continue + if (sampled != null && sampledRegionHitsMask(sampled, placementByTile.getValue(other.tileId), otherMask, extrude)) { + overlapping.add(mover.tileId) + sampling.add(mover.tileId) + overlapping.add(other.tileId) + painting.add(other.tileId) + } + } + } + // The page-space angle is the display angle's mirror: the flip reverses a rotation's sense. + val status = + PlacementDragStatus( + operatorKind = operatorKind, + deltaX = snappedDeltaX, + deltaY = snappedDeltaY, + angleDegrees = (-parameters.rotationRadians * 180.0 / PI).toFloat(), + factorX = parameters.factorX, + factorY = parameters.factorY, + overlapCount = movers.count { mover -> mover.tileId in overlapping }, + offPage = offPage.isNotEmpty(), + ) + return PlacementDragResult(placementByTile, displayAffineByTile, overlapping, sampling, painting, offPage, status) +} + +/** + * The page pixels a mover's paint occupied before the gesture - its trim through its old placement, + * grown by the extrusion band and rounded out - which the page occupancy reads as empty. + * + * @param PlacementMover mover The mover. + * @param Int extrude The composer's edge extrusion. + * @return PixelRect The old spot. + */ +private fun vacatedRect(mover: PlacementMover, extrude: Int): PixelRect { + val bounds = placementFootprint(mover.placement, mover.trim, reserve = null).expanded(extrude.toFloat()) + return PixelRect(floor(bounds.left).toInt(), floor(bounds.top).toInt(), ceil(bounds.right).toInt(), ceil(bounds.bottom).toInt()) +} + +/** + * Builds the gesture a placement operator latched over: the tiles the selection moves that sit on + * the shown page, their crops, masks, and sampled regions, the page's bystanders and its paint, and + * the shared capture over the moving islands. + * + * Only the MOVERS' art is decoded (their crops, masks, and contours need it); the bystanders' paint is + * the shown page itself, whose composed alpha is what is painted there, and every tile's sampled + * region comes from the model's own meshes, so no other tile is decoded. A mover whose art will not + * decode or disagrees with its tile refuses the gesture; a bystander in that state surfaces at the + * commit as the resolver's own fault log. + * + * Decodes rasters, wraps bitmaps, and scans the page, so callers run it off the UI thread. + * + * @param PuppetModel model The session's committed model. + * @param UvPlacementSurface surface The shown page and the source-art store. + * @param Selection selection The session's object selection. + * @param List shownGeometries The shown islands' display geometry (the page's every visible island). + * @param TransformPivotMode pivotMode The session's pivot mode. + * @param DrawableId? activeDrawableId The active drawable, the Active Element pivot. + * @param Pair? cursorDisplay The UV cursor in display space, the Cursor pivot, or null when unplaced. + * @param MeshOperatorKind operatorKind The latched operator. + * @return PlacementGestureBuild The gesture, or why there is none. + */ +internal fun buildPlacementGesture( + model: PuppetModel, + surface: UvPlacementSurface, + selection: Selection, + shownGeometries: List, + pivotMode: TransformPivotMode, + activeDrawableId: DrawableId?, + cursorDisplay: Pair?, + operatorKind: MeshOperatorKind, +): PlacementGestureBuild { + val tileByDrawable = HashMap() + for (drawable in model.drawables) { + val tileId = drawable.atlasTileId ?: continue + tileByDrawable[drawable.id] = tileId + } + val shownTileIds = shownGeometries.mapNotNullTo(HashSet()) { geometry -> tileByDrawable[geometry.drawableId] } + val candidateTileIds = model.placementDragTileIds(selection).filter { tileId -> tileId in shownTileIds } + if (candidateTileIds.isEmpty()) { + return PlacementGestureBuild.NotOnPage + } + // The shown page's MODEL index is the movers' page: they were chosen from islands shown on it. A + // page whose model size disagrees with the shown surface means the two numberings diverged. + val pageIndex = model.atlas.tileById.getValue(candidateTileIds.first()).placement?.pageIndex ?: return PlacementGestureBuild.NotOnPage + val page = model.atlas.pages.getOrNull(pageIndex) ?: return PlacementGestureBuild.NotDerivable + if (page.width != surface.pageWidth || page.height != surface.pageHeight) { + return PlacementGestureBuild.NotDerivable + } + val reserveByTile = meshReserveByTile(model) + val extrude = model.atlas.composition.extrude + + val movers = ArrayList() + for (tileId in candidateTileIds) { + val tile = model.atlas.tileById.getValue(tileId) + val placement = tile.placement ?: continue + if (placement.pageIndex != pageIndex) { + continue + } + // decodeRaster rather than the cached rasterFor: this runs off the UI thread the cache is + // confined to, and a mover's art is a handful of tiles. + val raster = surface.artRasters.decodeRaster(tileId) ?: return PlacementGestureBuild.NotDerivable + if (raster.width != tile.width || raster.height != tile.height) { + return PlacementGestureBuild.NotDerivable + } + // A placed tile with nothing opaque has nothing on the page to move. + val analysis = analyzeAlpha(raster.width, raster.height, raster.rgba, model.atlas.composition.alphaThreshold) ?: continue + val trim = analysis.opaqueBounds + val reserve = reserveByTile[tileId] + val footprint = placementFootprint(placement, trim, reserve) + movers.add( + PlacementMover( + tileId = tileId, + placement = placement, + trim = trim, + reserve = reserve, + meshMask = meshMaskOf(model, tileId), + mask = TileOpaqueMask.of(raster, trim, model.atlas.composition.alphaThreshold), + contours = analysis.contours, + pivotDisplayX = (footprint.left + footprint.right) / 2f, + pivotDisplayY = surface.pageHeight - (footprint.top + footprint.bottom) / 2f, + crop = cropBitmap(raster, trim), + ), + ) + } + if (movers.isEmpty()) { + return PlacementGestureBuild.NotOnPage + } + val moverIds = movers.mapTo(HashSet()) { mover -> mover.tileId } + val bystanders = + model.atlas.tiles.mapNotNull { tile -> + val placement = tile.placement ?: return@mapNotNull null + if (placement.pageIndex != pageIndex || tile.id in moverIds) { + return@mapNotNull null + } + // The whole tile bounds its paint: known without a decode, and never narrower than the trim. + val extent = LayerBounds(0, 0, tile.width, tile.height) + PlacementBystander( + tileId = tile.id, + placement = placement, + sampled = meshMaskOf(model, tile.id)?.let { coverage -> SampledRegion(placement, coverage) }, + paintedBounds = placementFootprint(placement, extent, reserve = null).expanded(extrude.toFloat()), + ) + } + val occupancy = surface.pageImage?.let { image -> PageOccupancy.of(image, movers.map { mover -> vacatedRect(mover, extrude) }) } + + // The shared capture over the moving islands - every shown drawable over a mover, selected or not, + // because a tile carries all of them. Whole-mesh sources: a tile moves rigidly. + val movingGeometries = shownGeometries.filter { geometry -> tileByDrawable[geometry.drawableId] in moverIds } + val sources = + movingGeometries.map { geometry -> + ModalCaptureSource(geometry.drawableId, geometry.positions.copyOf(), geometry.indices, allVertexIndices(geometry.positions)) + } + val activeAnchor = + activeDrawableId + ?.let { activeId -> movingGeometries.firstOrNull { geometry -> geometry.drawableId == activeId } } + ?.let { geometry -> MeshTransforms.medianPivot(geometry.positions, allVertexIndices(geometry.positions)) } + val transform = + buildModalTransformCapture( + sources = sources, + pivotMode = pivotMode, + individualOriginScope = IndividualOriginScope.WholeMesh, + operatorKind = operatorKind, + activeAnchor = activeAnchor, + cursorAnchor = cursorDisplay, + ) ?: return PlacementGestureBuild.NotOnPage + // Individual Origins turns each TILE about its own center (the capture's per-drawable groups would + // turn two drawables sharing one tile about different pivots); every other mode shares the anchor. + val pivoted = + if (pivotMode == TransformPivotMode.IndividualOrigins) { + movers + } else { + movers.map { mover -> + PlacementMover(mover.tileId, mover.placement, mover.trim, mover.reserve, mover.meshMask, mover.mask, mover.contours, transform.anchor.first, transform.anchor.second, mover.crop) + } + } + return PlacementGestureBuild.Ready( + PlacementGesture( + transform = transform, + movers = pivoted, + bystanders = bystanders, + occupancy = occupancy, + tileByDrawable = movingGeometries.associate { geometry -> geometry.drawableId to tileByDrawable.getValue(geometry.drawableId) }, + frozenPositionsByDrawable = movingGeometries.associate { geometry -> geometry.drawableId to geometry.positions.copyOf() }, + pageWidth = surface.pageWidth, + pageHeight = surface.pageHeight, + extrude = extrude, + ), + ) +} + +/** + * Every vertex index of an interleaved positions array. + * + * @param FloatArray positions The interleaved (x, y) positions. + * @return Set The indices 0 until the vertex count. + */ +private fun allVertexIndices(positions: FloatArray): Set = (0 until positions.size / 2).toSet() + +/** + * The trim's pixels of a decoded tile as a Compose bitmap, straight alpha preserved. + * + * @param DecodedImage raster The tile's decoded art. + * @param LayerBounds trim The sub-rectangle to crop, raster-local. + * @return ImageBitmap? The crop, or null when the platform could not wrap it. + */ +private fun cropBitmap(raster: DecodedImage, trim: LayerBounds): ImageBitmap? { + if (trim.width <= 0 || trim.height <= 0) { + return null + } + val bytes = ByteArray(trim.width * trim.height * 4) + for (rowIndex in 0 until trim.height) { + val sourceOffset = ((trim.top + rowIndex) * raster.width + trim.left) * 4 + raster.rgba.copyInto(bytes, rowIndex * trim.width * 4, sourceOffset, sourceOffset + trim.width * 4) + } + return runCatching { rgbaToImageBitmap(bytes, trim.width, trim.height, RgbaAlphaType.Straight) }.getOrNull() +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportCursor.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportCursor.kt new file mode 100644 index 0000000..fc08d3c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportCursor.kt @@ -0,0 +1,24 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset + +/** + * Warps the OS pointer to an absolute screen position mid-gesture - Blender's cursor-wrap for modal + * transforms, so a Grab / Scale / Rotate is not interrupted when the pointer reaches the viewport edge. + * Desktop teleports the cursor via AWT Robot; touch platforms have no cursor and no-op. + * + * Returns where the cursor ACTUALLY landed (read back from the OS), not the requested target: the + * platform may round to integer pixels, clamp at a screen edge, or rescale the request (HiDPI), and + * any difference between request and landing must be folded into the gesture's wrap compensation or + * it accumulates as drift across wraps. Null means no warp happened (no cursor, or the platform + * denied it) - the caller leaves its gesture anchor alone and the transform freezes at the edge. + * + * ジェスチャ中に OS ポインタを画面座標へ移動する(Blender のカーソルラップ)。実際の着地点を返す。 + * デスクトップのみ実装。 + * + * @param Float screenX The requested absolute screen x in pixels. + * @param Float screenY The requested absolute screen y in pixels. + * @return Offset? The absolute screen position the cursor actually landed at, or null when no warp + * happened (platforms or configurations without warp support). + */ +expect fun warpViewportCursor(screenX: Float, screenY: Float): Offset? \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportEditGizmoOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportEditGizmoOverlay.kt new file mode 100644 index 0000000..766d9c2 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportEditGizmoOverlay.kt @@ -0,0 +1,1160 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isAltPressed +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.unit.IntSize +import kotlinx.coroutines.launch +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.DEFAULT_PROPORTIONAL_RADIUS_WORLD +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.IndividualOriginScope +import org.umamo.edit.MeshChange +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshSelectionOps +import org.umamo.edit.MeshTopology +import org.umamo.edit.MeshTransforms +import org.umamo.edit.ModalCaptureSource +import org.umamo.edit.ModalTransformCapture +import org.umamo.edit.NoticePlacement +import org.umamo.edit.PROPORTIONAL_RADIUS_STEP_FACTOR +import org.umamo.edit.ProportionalRows +import org.umamo.edit.TransformGestureParameters +import org.umamo.edit.buildModalTransformCapture +import org.umamo.edit.handleScaleFactors +import org.umamo.edit.withMeshPositions +import org.umamo.render.ViewportCamera +import org.umamo.render.eval.DrawableSpaceMapping +import org.umamo.render.eval.drawableLocalPosed +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawRubberBand +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle +import org.umamo.ui.transform.DrawableWorldGeometry +import org.umamo.ui.transform.captureDrawableWorld +import kotlin.math.pow + +/** + * One session mesh's live geometry at the neutral pose: its three-space [DrawableWorldGeometry] (base, the + * posed rest shape, and its world projection, plus the deformer-chain mapping and the world->base inverse), + * along with its mesh and derived unique edges. The Edit session spans several meshes, so the overlay + * carries one of these per drawable. + * + * The three-space geometry is the SAME primitive the object gizmo and the Properties transform panel use, so + * an Edit-mode drag inverts a transformed world shape back onto the base mesh through the shared + * [DrawableWorldGeometry.worldToBase] rather than an open-coded round trip. + * + * @property DrawableWorldGeometry worldGeometry The drawable's base / displayed / world geometry and inverse. + * @property DrawableMesh mesh The drawable's live mesh (positions, uvs, indices). + * @property List edges The mesh's unique edges, in first-encounter order. + */ +internal class EditMeshGeometry( + val worldGeometry: DrawableWorldGeometry, + val mesh: DrawableMesh, + val edges: List, +) { + /** The drawable this geometry belongs to. */ + val drawableId: DrawableId get() = worldGeometry.drawableId + + /** The local-to-world deformer-chain projection. */ + val mapping: DrawableSpaceMapping get() = worldGeometry.mapping + + /** The local rest shape the movement transfer anchors on (base + the neutral keyform blend). */ + val displayed: FloatArray get() = worldGeometry.displayed + + /** The displayed shape projected to world space. */ + val worldPosed: FloatArray get() = worldGeometry.world + + /** The geometry-source-agnostic view the shared element queries and wireframe draw take. */ + val gizmo = GizmoMeshGeometry(drawableId, mesh.indices, edges, worldGeometry.world) + + /** + * Inverts a transformed WORLD shape back onto the base mesh - the write-back a drag ends with. + * + * @param FloatArray transformedWorld The reshaped world positions. + * @param Set indices The vertices the transform touched. + * @return FloatArray The new base positions (a fresh array). + */ + fun worldToBase(transformedWorld: FloatArray, indices: Set): FloatArray = worldGeometry.worldToBase(transformedWorld, indices) +} + +/** + * One session mesh's geometry as the DISPLAYED frame rendered it, for the draw pass (the wireframe must + * lag together with the raster, not lead it). worldPosed is null when the frame could not project the + * drawable (a hidden ancestor) - the draw pass then falls back to the live shape. + * + * @property IntArray indices The frame mesh's triangle vertex indices. + * @property List edges The frame mesh's unique edges. + * @property FloatArray? worldPosed The frame's world-projected shape, or null when unprojectable. + */ +private class FrameMeshGeometry( + val indices: IntArray, + val edges: List, + val worldPosed: FloatArray?, +) + +/** + * The captured state of an in-flight Edit-mode transform: the shared [ModalTransformCapture] (entries with + * their frozen positions, pivot groups, proportional halos, and moved sets, plus the anchor, the frozen + * operator kind, and the rotation tracker) alongside the per-drawable frozen [DrawableWorldGeometry] the + * drive loop inverts each transformed world shape back through. The geometry is held in a map keyed on the + * drawable id, looked up by [org.umamo.edit.ModalCaptureEntry], so nothing stays index-aligned. + * + * The geometry frozen here is a COPY of the live geometry's arrays (base, displayed, world), so the whole + * drag transforms a fixed snapshot even though the underlying model is immutable. + * + * @property ModalTransformCapture transform The shared gesture capture (entries, groups, anchor, halos, kind). + * @property Map geometryById Each moving drawable's frozen world geometry. + */ +private class EditGesture( + val transform: ModalTransformCapture, + val geometryById: Map, +) + +/** + * The Vertex Slide gesture's frozen context: the active vertex and its incident neighbor candidates. + * Only the candidates freeze at latch - the best edge is re-picked from the live pointer every move, + * so the slide follows the pointer across the vertex's fan instead of locking to the first edge. + * + * @property DrawableId drawableId The mesh the active vertex lives in. + * @property Int activeVertex The sliding vertex's index. + * @property IntArray neighborIndices The active vertex's incident neighbors (the edge candidates). + */ +private class SlideContext( + val drawableId: DrawableId, + val activeVertex: Int, + val neighborIndices: IntArray, +) + +/** + * Where the Vertex Slide's most recent drive landed: the edge it picked and how far along it the vertex + * sits - what the confirm registers on the operation settings strip, whose Factor row re-slides the + * same frozen edge. + * + * @property Int neighborIndex The edge's far endpoint the drive picked. + * @property Float factor The landed factor in [0, 1]. + */ +private class SlideLanding( + val neighborIndex: Int, + val factor: Float, +) + +/** + * The Edit-mode gizmo overlay: a Compose layer over the offscreen puppet image that draws the active + * drawable's mesh (vertices, edges, and faces of its rest shape) and runs the modal G / S / R operators. + * It is gated on Edit mode with an active drawable; in Object mode nothing is composed, so pointer input + * flows untouched to the viewport navigation beneath. + * + * Selection follows Blender's select modes (vertex / edge / face, switched by the mesh.selectMode + * commands): only the current mode's domain is clickable and stored, while the other domains highlight by + * derivation - an edge lights up when both endpoints are selected, a face only when all three of its own + * vertices (vertex mode) or edges (edge mode) are. The gizmo palette comes from the viewport.meshEdit + * settings, so the colors follow the user's preferences live. + * + * Edit mode edits the neutral state of the base mesh, and only that - it is pinned to the neutral pose + * (the render bridge feeds the renderer neutral parameters while the mode is active, and the parameter + * panel is locked), so the session pose is never touched and blend-shape states are out of scope. The + * shape shown is the rest shape as rendered - base + the neutral keyform blend, since real rigs park + * parts elsewhere on the texture sheet and place them via those deltas - projected to world through the + * composed parent-deformer chain ([drawableSpaceMapping]), so the wireframe sits on the art for warp and + * rotation children too. A drag commits by movement transfer: `newBase = base + (displayed' - displayed)`, + * writing only DrawableMesh.positions; the neutral blend cancels out of the subtraction, so no keyform + * cell resolution is involved, and blend-shape deltas (stored relative to base) follow the edit. + * + * Interaction mirrors Blender. Idle: a primary click selects the element under the cursor per the select + * mode (Ctrl toggles, Shift adds), an empty primary drag rubber-bands a box, an empty click clears; + * middle-drag pan and wheel zoom fall through (left unconsumed) to the navigation layer. Modal (an + * operator latched on the session by a G / S / R command): pointer movement drives the transform live over + * a copy-on-write working array covering the vertices the selected elements span, pushed to the renderer; + * the wireframe itself is drawn from the model the displayed frame was rendered from ([frameModel]), so it + * lags together with the textured raster instead of leading it. A primary click or Enter confirms (one undo + * step), Esc or right-click cancels. While modal, all pointer input is swallowed. + * + * @param String areaId The viewport area this overlay covers. + * @param PuppetViewportService service The render service (for live preview pushes). + * @param EditorSession session The session owning the model, element selection, and active operator. + * @param ViewportCamera? camera The camera the displayed frame was rendered at (world<->screen affine); + * null hides the overlay. + * @param PuppetModel? frameModel The model the displayed frame's pixels reflect; the wireframe poses from + * it (not the live session model) so it stays glued to the raster during an edit. Null hides the + * overlay (no frame has landed yet - nothing to glue to). + * @param Int widthPx The area width in pixels. + * @param Int heightPx The area height in pixels. + * @param State areaPointer Where the pointer last was in this area, tracked by the HOST so the + * pointer-addressed commands still resolve while this overlay is unmounted. + * @param Function onOverlapRequest Opens the overlap-picker popup for an Alt+Q over 2+ stacked + * candidates (the pick switches the edited mesh). + * @param Modifier modifier The layout modifier. + */ +@Composable +fun ViewportEditGizmoOverlay( + areaId: String, + service: PuppetViewportService, + session: EditorSession, + camera: ViewportCamera?, + frameModel: PuppetModel?, + widthPx: Int, + heightPx: Int, + areaPointer: State, + onOverlapRequest: (Offset, List) -> Unit, + modifier: Modifier = Modifier, +) { + val mode by session.mode.collectAsState() + val meshSelection by session.meshSelection.collectAsState() + val model by session.model.collectAsState() + val activeOperator by session.activeMeshOperator.collectAsState() + val activeSelectTool by session.activeSelectTool.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val proportionalEdit by session.proportionalEdit.collectAsState() + val viewportOverlayColors = rememberViewportOverlayColors() + // Theme-level overlay chrome (the marquee) comes from the palette; the mesh gizmo colors above stay a + // separate settings-backed system. + val overlayColors = LocalUmamoColors.current + + val sessionDrawableIds = meshSelection.drawableIds + + if (mode != EditorMode.Edit || sessionDrawableIds.isEmpty() || camera == null || frameModel == null) { + return + } + // The shared two-tone marching-ants style for the box / circle / crosshair affordances. + val overlayStyle = selectionOverlayStyle(overlayColors) + + // Per-session-mesh geometry at the constant neutral pose Edit mode is pinned to. Keyed on the model + // (a commit swaps it) and the session's mesh list; NOT per rendered frame. + val liveGeometry = remember(model, sessionDrawableIds) { editMeshGeometries(model, sessionDrawableIds) } + + // Live values the long-running pointer loop, the marquee callbacks, and the request collectors read + // (they are keyed only on areaId / session, so they must not close over a stale camera / size / shape + // / topology when the model, pan, or resize change mid-edit). + val liveCamera = rememberUpdatedState(camera) + val liveSize = rememberUpdatedState(IntSize(widthPx, heightPx)) + val liveGeometryState = rememberUpdatedState(liveGeometry) + + // Capture posed space once at Edit enter (first non-empty sighting). Do NOT refresh as verts are + // deleted — wipe-and-rebuild must invert/project against the original mesh, not the last scrap. + SideEffect { + for (entry in liveGeometry) { + if (entry.mesh.vertexCount > 0 && session.addVertexSpaceSeed(entry.drawableId) == null) { + session.rememberAddVertexSpaceSeed( + entry.drawableId, + entry.worldGeometry.base, + entry.worldGeometry.displayed, + entry.worldGeometry.world, + ) + } + } + } + + // Add Vertex drafts are staged in viewport world space (so floats sit under the cursor). Accept needs + // the deformer inverse into mesh-base; install it while this Edit overlay is alive. + DisposableEffect(session, areaId) { + val converter: (DrawableId, Float, Float) -> Pair = + converter@{ drawableId, worldX, worldY -> + val geometry = + liveGeometryState.value.firstOrNull { entry -> entry.drawableId == drawableId }?.worldGeometry + ?: return@converter (worldX to worldY) + val spaceSeed = session.addVertexSpaceSeed(drawableId) + geometry.worldClickToBase( + worldX, + worldY, + spaceSeedBase = spaceSeed?.base, + spaceSeedWorld = spaceSeed?.world, + spaceSeedDisplayed = spaceSeed?.displayed, + ) + } + session.addVertexWorldToBase = converter + onDispose { + if (session.addVertexWorldToBase === converter) { + session.addVertexWorldToBase = null + } + } + } + + // The keymap-command collectors, mounted above the EMPTY-GEOMETRY guard below but still inside every + // guard above it: this overlay is Edit-mode-only and so are these commands, so there is nothing to + // gain by outliving the mode / camera / frame checks, and a second collector live in Object mode + // would only duplicate what the object overlay already runs. + // + // What they must outlive is the empty-geometry return. liveGeometry goes empty when every drawable + // in the session selection sits behind a hidden ancestor: the overlay stops drawing, and past this + // point so would the collectors, leaving a request nothing receives and therefore no feedback at all. + // Alt+Q switch-object is the sharp case - it is the command you would reach for to ESCAPE that state, + // and it needs neither geometry nor a camera to do it. + // + // The pointer comes from the HOST area rather than this overlay's gesture state, which stops being + // written once the guard below fires. + LaunchedEffect(session, areaId, service) { + // Select Linked (Blender's L / Ctrl+L). + launch { + session.selectLinkedRequests.collect { request -> + if (request.areaId != areaId) { + return@collect + } + if (liveGeometryState.value.isEmpty()) { + session.emitNotice("notice.edit.noEditableGeometry", NoticePlacement.NearCursor) + return@collect + } + handleSelectLinkedRequest( + session, + liveGeometryState.value.map { it.gizmo }, + request.fromSelection, + areaPointer.value, + liveCamera.value, + liveSize.value, + ) + } + } + // Alt+Q: switch the edited mesh to the drawable under the pointer (or the overlap picker for a + // stack). Needs no geometry and no camera, only the pointer, so it still works in the very state + // the others have to decline. + launch { + session.switchObjectRequests.collect { requestedAreaId -> + if (requestedAreaId != areaId) { + return@collect + } + handleSwitchEditDrawableRequest(session, service, areaId, areaPointer.value, onOverlapRequest) + } + } + // Rip (Blender's V): duplicate the covered vertices, re-point the pointer-side triangles, auto-grab. + launch { + session.ripRequests.collect { requestedAreaId -> + if (requestedAreaId != areaId) { + return@collect + } + if (liveGeometryState.value.isEmpty()) { + session.emitNotice("notice.edit.noEditableGeometry", NoticePlacement.NearCursor) + return@collect + } + handleRipRequest(session, liveGeometryState.value, areaId, areaPointer.value, liveCamera.value, liveSize.value) + } + } + // The geometry-dependent Shift+S snaps for Edit mode. Only the pointer's own area executes: every + // open 2D viewport composes this collector, and an ungated request would commit once per viewport. + // The handler ignores the area - a snap acts on the model - so the payload's id is purely the election. + launch { + session.snapRequests.collect { request -> + if (request.areaId != areaId) { + return@collect + } + if (liveGeometryState.value.isEmpty()) { + session.emitNotice("notice.edit.noEditableGeometry", NoticePlacement.NearCursor) + return@collect + } + handleEditSnapRequest(session, liveGeometryState.value, request.kind) + } + } + launch { + session.viewportMirrorRequests.collect { request -> + if (request.areaId != areaId || session.mode.value != EditorMode.Edit) { + return@collect + } + if (liveGeometryState.value.isEmpty()) { + session.emitNotice("notice.edit.noEditableGeometry", NoticePlacement.NearCursor) + return@collect + } + handleEditMirrorRequest(session, liveGeometryState.value, request.mirrorHorizontal) + } + } + } + + if (liveGeometry.isEmpty()) { + return + } + + // The marquee (box + circle) machinery over mesh elements: the stroke / rubber-band state and event + // rules are shared (MarqueeSelectController); the callbacks bind them to the element domain. + val marquee = + remember(areaId) { + MarqueeSelectController( + seedStroke = { session.meshSelection.value }, + stampStroke = { working, erasing, center, radiusPx, stampCamera, stampSize -> + circleSelection(working, erasing, center, radiusPx, liveGeometryState.value.map { it.gizmo }, stampCamera, stampSize) + }, + commitStroke = { stroke -> session.setMeshSelection(stroke) }, + applyBox = { start, end, additive, boxCamera, boxSize -> + val selection = session.meshSelection.value + val insideByDrawable = + liveGeometryState.value.associate { geometry -> + geometry.drawableId to elementsInBox(selection.selectMode, geometry.gizmo, start, end, boxCamera, boxSize) + } + session.setMeshSelection(MeshSelectionOps.box(selection, insideByDrawable, additive = additive)) + }, + setCircleRadius = { radiusPx -> session.setCircleRadius(radiusPx) }, + clearTool = { session.clearSelectTool() }, + ) + } + + // What the draw pass reflects: the live stroke while one is in flight, else the committed selection - so + // painted elements light up immediately during a Circle stroke. + val effectiveSelection = marquee.circleStroke ?: meshSelection + + // What the draw pass highlights per mesh and domain: the effective selection for the current select + // mode plus the cross-domain highlights derived with Blender's rules (both-endpoints for edges, + // all-own-elements for faces). Derived for display only - never stored back into the selection. + val highlightByDrawable = + remember(effectiveSelection, liveGeometry) { + liveGeometry.associate { geometry -> + geometry.drawableId to + buildHighlightSets( + elements = effectiveSelection.elementsOf(geometry.drawableId), + active = effectiveSelection.activeElement?.takeIf { it.drawableId == geometry.drawableId }?.element, + selectMode = effectiveSelection.selectMode, + triangleIndices = geometry.mesh.indices, + ) + } + } + + // The per-drawable reuse cache behind the frame-geometry derivation below: a modal drive's folded + // frame model replaces ONLY the moving meshes' drawables, so a bystander's posed world geometry + // carries over by drawable INSTANCE identity instead of re-posing every session mesh per rendered + // frame - the per-frame work during a drag is the moving meshes alone. Keyed on liveGeometry so a + // committed model swap (new mappings / topology) drops every entry. + val frameGeometryReuse = remember(liveGeometry) { HashMap>() } + // The DISPLAYED frame's geometry per session mesh - what the raster under this overlay actually + // shows. The draw pass poses the wireframes from this (not the live session shape / working arrays), + // so during a transform every mesh lags together with the raster instead of racing ahead of it. + // Recomputed per rendered frame, but ONLY the frame's changed positions are per-frame work: the + // topology (indices, edge set) and the deformer-chain mapping are invariant during a drag, so they + // are reused from liveGeometry rather than rebuilt every frame. withMeshPositions shares the indices + // array by reference, and Edit mode pins the pose so the deformers never move - rebuilding them per + // frame (a uniqueEdges plus a full buildDeformerWorlds per drawable) would make an all-vertex + // transform lag, unlike Object mode's transform, which caches. A missing member falls the draw pass + // back to the session shape (a pathological transient, e.g. a hidden ancestor). + val frameGeometryByDrawable = + remember(frameModel, liveGeometry) { + // One O(D) index of the frame's drawables, so the per-mesh lookups below are not an O(D^2) scan. + val frameDrawablesById = frameModel.drawables.associateBy { it.id } + liveGeometry.mapNotNull { liveEntry -> + val drawableId = liveEntry.drawableId + val frameDrawable = frameDrawablesById[drawableId] ?: return@mapNotNull null + val frameMesh = frameDrawable.mesh ?: return@mapNotNull null + val reused = frameGeometryReuse[drawableId] + if (reused != null && reused.first === frameDrawable) { + return@mapNotNull drawableId to reused.second + } + // Topology is unchanged during a transform (indices shared by reference), so reuse the edge set; + // recompute only across a topology edit, where the frame briefly trails on the old indices. + val edges = + if (frameMesh.indices === liveEntry.mesh.indices) { + liveEntry.edges + } else { + MeshTopology.uniqueEdges(frameMesh.indices) + } + // The deformers do not move during a mesh drag, so liveEntry.mapping (built once from the session + // model) projects the frame's changed local positions correctly - no per-frame buildDeformerWorlds. + val frameDisplayed = drawableLocalPosed(frameModel, emptyMap(), drawableId) ?: frameMesh.positions + val frameGeometry = + FrameMeshGeometry( + indices = frameMesh.indices, + edges = edges, + worldPosed = liveEntry.mapping.localToWorld(frameDisplayed), + ) + frameGeometryReuse[drawableId] = frameDrawable to frameGeometry + drawableId to frameGeometry + }.toMap() + } + + // The per-area modal-gesture bookkeeping (last pointer, capture + preview, gesture origin, area origin, + // cursor wrap, pointer controller). The capture is the Edit-mode gesture (shared transform capture + + // per-drawable frozen world geometry); preview holds each moving mesh's new BASE positions. + val gesture = remember(areaId) { ModalGestureState() } + + // The Vertex Slide edge, frozen at latch: (drawable, sliding vertex, edge's other endpoint) - the + // incident edge whose far endpoint sat nearest the pointer when the operator armed. + var slideContext by remember(areaId) { mutableStateOf(null) } + + // The Vertex Slide's most recent landing (edge + factor), written by the drive loop and read by the + // confirm's strip registration; null until the first drive of a slide. + var slideLanding by remember(areaId) { mutableStateOf(null) } + + // Photoshop-style Scale marquee (handle drag); Grab / Rotate keep the Blender distance modal. + var scaleBoxDrag by remember(areaId) { mutableStateOf(null) } + var scaleBoxPreviewWorlds by remember(areaId) { mutableStateOf?>(null) } + val liveScaleBoxDrag = rememberUpdatedState(scaleBoxDrag) + val scaleArmed = activeOperator?.areaId == areaId && activeOperator?.kind == MeshOperatorKind.Scale + + // Confirms the in-flight gesture: commit each moving mesh's new base positions as ONE undo step, + // register that step on the operation settings strip, then clear the operator (its cleanup re-syncs + // the renderer). A null preview means no movement, so nothing is committed. The preview already + // holds base positions (the drive loop inverted them via worldToBase), so confirm commits them directly. + fun confirmGesture() { + val committed = gesture.preview + val gestureData = gesture.capture + val parameters = gesture.lastParameters + if (committed != null && gestureData != null) { + val transform = gestureData.transform + val newPositionsByDrawable = LinkedHashMap(transform.entries.size) + val vertexIndicesByDrawable = LinkedHashMap>(transform.entries.size) + for (entry in transform.entries) { + val transformed = committed[entry.drawableId] ?: continue + newPositionsByDrawable[entry.drawableId] = transformed + // The moved set, not just the covered set: proportional editing moves weighted + // unselected vertices too, and the change metadata must name every vertex the edit touched. + vertexIndicesByDrawable[entry.drawableId] = entry.movedIndices.toList() + } + if (newPositionsByDrawable.isNotEmpty()) { + val modelBefore = session.model.value + session.commitMeshPositions( + MeshChange.TransformVertices(vertexIndicesByDrawable, transform.operatorKind), + newPositionsByDrawable, + ) + // The strip's rows for the step just pushed, over the RETAINED capture so an adjustment + // replays the same frozen geometry - registered before the operator clears, since the + // teardown drops the capture. A commit that recorded nothing (the geometry landed where it + // started) has no step of its own to amend, so it registers nothing. + if (session.model.value !== modelBefore) { + val slide = slideContext + val landing = slideLanding + if (transform.operatorKind == MeshOperatorKind.VertexSlide) { + if (slide != null && landing != null) { + registerSlideAdjustment(session, areaId, transform, gestureData.geometryById, slide.drawableId, slide.activeVertex, landing.neighborIndex, landing.factor) + } + } else if (parameters != null) { + // A suppressed latch (the duplicate / rip auto-grab) took no weights, so it offers no + // proportional rows; every other transform does, on or off, so the halo can be + // added after the fact the way Blender's redo panel allows. + val proportional = + if (session.activeMeshOperatorSuppressesProportional) { + null + } else { + val state = session.proportionalEdit.value + ProportionalRows.of(state, state?.radiusWorld ?: DEFAULT_PROPORTIONAL_RADIUS_WORLD) + } + registerMeshTransformAdjustment(session, areaId, transform, gestureData.geometryById, parameters, proportional) { state -> + session.setProportionalEdit(state) + } + } + } + } + } + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + session.clearMeshOperator() + } + + fun pushScaleBoxPreview(worlds: List) { + val gestureData = gesture.capture ?: return + val transform = gestureData.transform + val newPreview = LinkedHashMap(transform.entries.size) + var folded = session.model.value + for ((index, entry) in transform.entries.withIndex()) { + val geometry = gestureData.geometryById.getValue(entry.drawableId) + val newBase = geometry.worldToBase(worlds[index], entry.movedIndices) + newPreview[entry.drawableId] = newBase + folded = folded.withMeshPositions(entry.drawableId, newBase) + } + gesture.preview = newPreview + scaleBoxPreviewWorlds = worlds + service.setModel(folded) + } + + // Drives the modal preview for one virtual-pointer position: applies the operator (or the Vertex + // Slide edge projection) per captured mesh, inverts each transformed world shape back onto the base + // mesh through the shared worldToBase round trip, and pushes the folded model to the renderer. Shared + // by Move (pointer motion) and Scroll (a proportional radius change must re-derive the preview from the + // same frozen originals without waiting for the next pointer move). False when the capture has not + // landed yet. + fun driveModalPreview(operator: MeshOperatorKind, virtualPointer: Offset, activeCamera: ViewportCamera, size: IntSize): Boolean { + val start = gesture.gestureStart ?: return false + val gestureData = gesture.capture ?: return false + val transform = gestureData.transform + // One pointer frame for the whole capture; only geometry and pivots vary per mesh. The frame + // resolves ONCE into the numbers every mesh applies (the Rotate branch advances the accumulator, + // and one advance per frame is what it expects); the confirm hands them to the settings strip. + val frame = TransformGestureFrame(transform.anchor, start, virtualPointer, session.axisConstraint.value, activeCamera, size) + val parameters = gestureParameters(operator, frame, transform.rotationTracker) + gesture.lastParameters = parameters + val newPreview = LinkedHashMap(transform.entries.size) + var folded = session.model.value + for (entry in transform.entries) { + val geometry = gestureData.geometryById.getValue(entry.drawableId) + // Vertex Slide projects the pointer onto its edge (its own math); every + // other operator goes through the shared pivot-group transform. The BEST + // incident edge is re-picked from the live pointer each move (nearest + // neighbor endpoint on screen), so the slide hops between the active + // vertex's edges as the pointer travels - only the candidates are frozen. + val slide = slideContext + val transformedWorld = + if (operator == MeshOperatorKind.VertexSlide) { + if (slide != null && entry.drawableId == slide.drawableId) { + val original = entry.positions + var bestNeighbor = -1 + var bestDistance = Float.MAX_VALUE + for (neighbor in slide.neighborIndices) { + val screen = worldToScreen(original[neighbor * 2], original[neighbor * 2 + 1], activeCamera, size) + val distance = (screen - virtualPointer).getDistance() + if (distance < bestDistance) { + bestDistance = distance + bestNeighbor = neighbor + } + } + if (bestNeighbor >= 0) { + val factor = slideFactorAlongEdge(original, slide.activeVertex, bestNeighbor, frame) + slideLanding = SlideLanding(bestNeighbor, factor) + slideVertexByFactor(original, slide.activeVertex, bestNeighbor, factor) + } else { + original + } + } else { + entry.positions + } + } else { + applyOperator(operator, entry.positions, entry.groups, parameters, entry.influence) + } + val newBase = geometry.worldToBase(transformedWorld, entry.movedIndices) + newPreview[entry.drawableId] = newBase + folded = folded.withMeshPositions(entry.drawableId, newBase) + } + gesture.preview = newPreview + service.setModel(folded) + return true + } + + // The modal gesture's commit-side seam: the Edit overlay drives per-mesh previews through the + // deformer inverse, confirms via the movement transfer, cancels through the session's operator + // clear, and resizes the proportional influence radius on scroll. The pointer-side mechanics + // (stale discard, virtual pointer, wrap, button semantics) live in ModalTransformController. + val modalTarget = + object : ModalTransformTarget { + override fun drivePreview(virtualPointer: Offset, camera: ViewportCamera, size: IntSize): Boolean { + // Defensive ownership check (the pointer loop already gates): only the initiating area drives. + // Scale uses the handle marquee, not distance-from-pivot. + val operator = + session.activeMeshOperator.value?.takeIf { + it.areaId == areaId && it.kind != MeshOperatorKind.Scale + } ?: return false + return driveModalPreview(operator.kind, virtualPointer, camera, size) + } + + override fun confirm() { + confirmGesture() + } + + override fun cancel() { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + session.clearMeshOperator() + } + + override fun onScroll(steps: Float, camera: ViewportCamera, size: IntSize) { + // The wheel resizes the proportional influence radius mid-gesture (Blender's + // behavior): geometric steps, weights re-derived from the frozen originals, and + // the preview re-driven immediately so the mesh responds without a pointer move. + val operator = session.activeMeshOperator.value?.takeIf { it.areaId == areaId } ?: return + val proportional = session.proportionalEdit.value + val gestureData = gesture.capture + if (steps != 0f && + proportional != null && + gestureData != null && + operator.kind != MeshOperatorKind.VertexSlide && + !session.activeMeshOperatorSuppressesProportional + ) { + // Wheel up (negative y) grows the radius. + session.setProportionalRadius(proportional.radiusWorld * PROPORTIONAL_RADIUS_STEP_FACTOR.pow(-steps)) + val updated = session.proportionalEdit.value + gestureData.transform.applyProportional(updated, updated?.radiusWorld ?: 0f) + driveModalPreview(operator.kind, gesture.cursorWrap.virtualPointer(gesture.lastPointer), camera, size) + } + } + } + + // A tool change - armed, cleared by Escape / right-click, or switched between box and circle - resolves any + // in-flight gesture (see MarqueeSelectController.cancel: the stroke commits, the box abandons). This clears + // a cancelled circle stroke / box rubber-band that would otherwise linger as the drawn selection until the + // next stroke reseeded it. + // + // This effect is recomposition-gated (the key must change, a recomposition must run, then the effect + // relaunches), so it can lose the race to a mouse release still in flight - a cancelled armed box would + // then commit through the idle Release path before this ran. The authoritative, race-free cancel is the + // meshGestureCancelRequests signal below (fired by the shell alongside clearSelectTool); this effect is the + // backstop for tool switches and leaving Edit, where no signal is sent. + // + // Keyed on the tool KIND (none / box / circle), not the whole tool value: resizing the circle brush makes + // a new Circle(radius), which must NOT re-fire and wipe the stroke mid-paint. The kind is derived from + // the AREA-OWNED tool: re-arming the brush from another viewport keeps the raw kind unchanged, but this + // area's stroke must still resolve - to its owner the tool went from live to absent. + val ownedSelectTool = activeSelectTool?.takeIf { it.areaId == areaId } + LaunchedEffect(selectToolKind(ownedSelectTool)) { + marquee.cancel() + } + + // The race-free cancel path: an already-suspended collector that resumes before the mouse release, so the + // box rubber-band is discarded (and any held circle stroke committed) before the Release could commit it. + // The shell fires this for every Edit-mode select-gesture cancel - the non-armed box drag (which owns no + // tool state to change) and, alongside clearSelectTool, the armed box / circle tools. + LaunchedEffect(session) { + session.meshGestureCancelRequests.collect { + marquee.cancel() + } + } + + // Enter confirms the modal gesture (mirroring a primary click); the shell routes the keypress here, + // gated to the INITIATING area through the operator latch itself. + LaunchedEffect(session) { + collectModalConfirmRequests(session, { session.activeMeshOperator.value?.areaId == areaId }) { + confirmGesture() + } + } + + // A proportional toggle or falloff change MID-GESTURE (O falls through the shell ladder to the + // keymap while an operator runs - Blender allows the same) re-derives the capture's weights from + // its frozen originals; the next pointer move applies them. The scroll path recomputes inline + // (it must re-drive the preview without pointer motion), so this collector is the keyboard-side + // complement. Vertex Slide never takes weights (the latch passed null and stays null here). + LaunchedEffect(session) { + session.proportionalEdit.collect { state -> + val gestureData = gesture.capture + val liveOperator = session.activeMeshOperator.value + if (gestureData != null && + liveOperator != null && + liveOperator.kind != MeshOperatorKind.VertexSlide && + !session.activeMeshOperatorSuppressesProportional + ) { + gestureData.transform.applyProportional(state, state?.radiusWorld ?: 0f) + } + } + } + + // Start the modal gesture as an operator latches IN THIS AREA; tear it down (re-syncing the renderer + // to the committed model) as it clears. The capture covers only the session meshes with covered + // vertices (an edge or face selection moves the union of vertices its elements cover); a mesh with + // nothing selected does not move. The shared pivot is the median of every covered vertex across the + // session, so all meshes scale / rotate about one point together. + LaunchedEffect(activeOperator) { + val operator = activeOperator?.takeIf { it.areaId == areaId } + if (operator != null) { + // Freeze a COPY of each moving mesh's world geometry (base / displayed / world) so the whole drag + // transforms a fixed snapshot, and offer it to the shared capture builder as a source. A mesh with + // nothing selected does not move. + val frozenById = LinkedHashMap() + val sources = ArrayList() + for (geometry in liveGeometry) { + val elements = meshSelection.elementsOf(geometry.drawableId) + if (elements.isEmpty()) { + continue + } + val coveredIndices = MeshTopology.coveredVertexIndices(elements, geometry.mesh.indices) + if (coveredIndices.isEmpty()) { + continue + } + val frozen = + DrawableWorldGeometry( + geometry.drawableId, + geometry.mapping, + geometry.mesh.positions.copyOf(), + geometry.displayed.copyOf(), + geometry.worldPosed.copyOf(), + ) + frozenById[geometry.drawableId] = frozen + sources.add(ModalCaptureSource(geometry.drawableId, frozen.world, geometry.mesh.indices, coveredIndices)) + } + // The Active-Element anchor the builder cannot resolve itself: the active element's own covered + // median. Null falls back to the shared covered median inside the builder. + val activeAnchor = + run { + val active = meshSelection.activeElement ?: return@run null + val activeGeometry = liveGeometry.firstOrNull { it.drawableId == active.drawableId } ?: return@run null + val activeCovered = MeshTopology.coveredVertexIndices(setOf(active.element), activeGeometry.mesh.indices) + if (activeCovered.isEmpty()) { + null + } else { + MeshTransforms.medianPivot(activeGeometry.worldPosed, activeCovered) + } + } + val cursorAnchor = session.cursor2dOrWorldOrigin().let { cursor -> cursor.worldX to cursor.worldZ } + val transform = + buildModalTransformCapture( + sources = sources, + pivotMode = session.pivotMode.value, + // Edit mode's Individual Origins turns each connectivity island about its own centroid. + individualOriginScope = IndividualOriginScope.ConnectivityIsland, + operatorKind = operator.kind, + activeAnchor = activeAnchor, + cursorAnchor = cursorAnchor, + ) + if (transform == null) { + // Nothing movable (the selection emptied between latch and capture): drop the operator. + session.clearMeshOperator() + } else { + // Proportional editing weights the unselected vertices near the selection; Vertex Slide is + // positions-only single-vertex math, so it never takes weights - and a suppressed latch (the + // duplicate / rip auto-grab) opts out the same way. + val proportionalState = + if (operator.kind == MeshOperatorKind.VertexSlide || session.activeMeshOperatorSuppressesProportional) { + null + } else { + session.proportionalEdit.value + } + transform.applyProportional(proportionalState, proportionalState?.radiusWorld ?: 0f) + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + gesture.begin(EditGesture(transform, frozenById), gesture.lastPointer) + // Vertex Slide needs an active vertex with at least one incident neighbor; only the + // CANDIDATES freeze here - the best edge is re-picked from the live pointer every move + // (Blender re-picks continuously, so the slide hops between connected edges mid-drag). + // Without candidates (no active vertex, or an isolated one) the operator drops. + slideLanding = null + slideContext = + if (operator.kind == MeshOperatorKind.VertexSlide) { + val active = meshSelection.activeElement + val activeVertex = (active?.element as? MeshElement.Vertex)?.index + val activeGeometry = active?.let { candidate -> liveGeometry.firstOrNull { it.drawableId == candidate.drawableId } } + if (activeVertex != null && activeGeometry != null) { + val adjacency = MeshTopology.buildVertexAdjacency(activeGeometry.mesh.vertexCount, activeGeometry.mesh.indices) + val neighbors = adjacency.getOrElse(activeVertex) { IntArray(0) } + if (neighbors.isNotEmpty()) SlideContext(active.drawableId, activeVertex, neighbors) else null + } else { + null + } + } else { + null + } + if (operator.kind == MeshOperatorKind.VertexSlide && slideContext == null) { + session.clearMeshOperator() + } + } + } else { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + // Resync the renderer only when THIS overlay owned a gesture: the effect also runs its else + // branch at mount (and when another area's operator latches), and an unguarded setModel from + // a viewport split open mid-gesture would stomp the initiating area's live preview. + if (gesture.end()) { + service.setModel(session.model.value) + } + } + } + + // clipToBounds: Canvas drawing is not clipped to the layout bounds by default, so an off-screen vertex + // would otherwise paint over the AreaHeader and neighbouring areas. + Box( + modifier = + modifier + .fillMaxSize() + .clipToBounds() + .onGloballyPositioned { coordinates -> gesture.areaScreenOrigin = coordinates.positionOnScreen() } + // While THIS AREA'S modal transform runs or its select tool is armed, hide the OS cursor so + // only the overlay's drawn cursor (double-arrow, crosshair, or brush circle) shows; plain idle + // Edit mode adds no icon, leaving the navigation layer's cursor to show through. A gesture + // owned by another viewport leaves this area's cursor alone. + .then( + if ((activeOperator?.areaId == areaId && !scaleArmed) || ownedSelectTool != null) { + Modifier.pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + } else { + Modifier + }, + ), + ) { + // Two sibling canvases, each in its OWN layer: a draw-state invalidation re-records every draw + // lambda sharing a layer, so the gesture chrome below (band, affordances, modal HUD) lives in + // a small layer of its own and the wireframes - the expensive pass - stay cached in this one. + // The chrome reads gesture.lastPointer, which updates on every pointer event (hover included), + // so its layer redraws per move; this layer re-records only when the frame geometry, the + // selection, or a live modal preview changes - and it composites OFFSCREEN, because a default + // layer retains a display list that every window repaint replays (re-stroking every edge), + // where the offscreen buffer rasterizes once per content change and blits per frame. + Canvas( + modifier = + Modifier + .fillMaxSize() + .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } + .pointerInput(areaId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + gesture.lastPointer = change.position + val latchedOperator = session.activeMeshOperator.value + val latchedTool = session.activeSelectTool.value + // A gesture belongs to its initiating area: while another viewport's operator or tool is + // live - or a UV operator, which can never belong to a viewport area - this overlay is + // fully inert (no drive, no picks, no marquee). Escape and Enter stay global through + // the shell ladder, and navigation (pan / zoom) still falls through. + if ((latchedOperator != null && latchedOperator.areaId != areaId) || + (latchedTool != null && latchedTool.areaId != areaId) || + session.activeUvOperator.value != null + ) { + continue + } + val operator = latchedOperator + val selectTool = latchedTool + val activeCamera = liveCamera.value + val size = liveSize.value + // Zoom Region armed for this area: the top-level region overlay owns the drag. This gizmo's + // idle branch would otherwise also start a box (it does not check isConsumed), so yield. + if (session.zoomRegionArmedArea.value == areaId) { + continue + } + if (operator != null && operator.kind == MeshOperatorKind.Scale) { + val gestureData = gesture.capture + when (event.type) { + PointerEventType.Press -> { + if (event.buttons.isSecondaryPressed) { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + session.clearMeshOperator() + change.consume() + } else if (event.buttons.isPrimaryPressed && gestureData != null) { + val worlds = gestureData.transform.entries.map { it.positions } + val indices = gestureData.transform.entries.map { it.coveredIndices } + val bounds = scaleBoxBounds(worlds, indices) + val handle = hitFreeTransformHandle(change.position, bounds, activeCamera, size) + if (handle != null) { + scaleBoxDrag = ScaleBoxDrag(handle, bounds, worlds.map { it.copyOf() }, indices) + change.consume() + } else { + confirmGesture() + change.consume() + } + } + } + + PointerEventType.Move -> { + val drag = liveScaleBoxDrag.value + if (drag != null && event.buttons.isPrimaryPressed) { + val (worldX, worldY) = + screenToWorld(change.position.x, change.position.y, activeCamera, size) + val worlds = + driveScaleBoxWorlds( + drag, + worldX, + worldY, + uniform = event.keyboardModifiers.isShiftPressed, + fromCenter = event.keyboardModifiers.isAltPressed, + ) + val (fx, fy, _) = + handleScaleFactors( + drag.startBounds, + drag.handle, + worldX, + worldY, + event.keyboardModifiers.isShiftPressed, + event.keyboardModifiers.isAltPressed, + ) + gesture.lastParameters = TransformGestureParameters(0f, 0f, fx, fy, 0f) + pushScaleBoxPreview(worlds) + change.consume() + } + } + + PointerEventType.Release -> { + if (liveScaleBoxDrag.value != null) { + scaleBoxDrag = null + confirmGesture() + change.consume() + } + } + + else -> {} + } + } else if (operator != null) { + // MODAL Grab / Rotate / Vertex Slide: the shared controller drives the transform + // over the captured shape and swallows every event. + gesture.lastPointer = + gesture.modalController.handleEvent( + event, + change, + modalTarget, + activeCamera, + size, + gesture.areaScreenOrigin, + ) + } else if (selectTool is ActiveSelectTool.Circle) { + // CIRCLE SELECT: the shared controller paints / erases / commits the stroke and + // consumes every event (paired with the navigation gate so MMB / wheel do not + // also pan / zoom); see MarqueeSelectController.handleCircleEvent. + marquee.handleCircleEvent(event, change, selectTool.radiusPx, activeCamera, size) + } else if (selectTool is ActiveSelectTool.AddVertex) { + // ADD VERTEX: stage floating verts in viewport world space (under the cursor) + // until Enter accepts; Accept maps world → mesh-base via addVertexWorldToBase. + handleAddVertexToolEvent( + event = event, + change = change, + session = session, + tool = selectTool, + geometries = liveGeometryState.value.map { it.gizmo }, + camera = activeCamera, + size = size, + ) + } else { + // IDLE: element selection, shared with the UV editor (Shift+RightClick places the + // viewport's 2D cursor here). Only primary-driven events are consumed, so middle-drag + // pan and wheel zoom fall through; armed Box-select boxes on any press and disarms. + handleIdleMeshSelectionEvent( + event = event, + change = change, + session = session, + geometries = liveGeometryState.value.map { it.gizmo }, + marquee = marquee, + boxArmed = selectTool is ActiveSelectTool.BoxArmed, + camera = activeCamera, + size = size, + placeCursor = session::setCursor2d, + ) + } + } + } + }, + ) { + // Draw every session mesh from the DISPLAYED frame's geometry so the wireframes lag together with + // the raster during a transform instead of leading it (preview still feeds the commit, just not + // the draw). Fall back to the live session shape only when the frame lacks a drawable - a + // pathological transient. + // The live Circle stroke drives the highlighted domain so painted elements light up mid-stroke. + val selectMode = effectiveSelection.selectMode + for (geometry in liveGeometry) { + val highlight = highlightByDrawable[geometry.drawableId] ?: continue + val frameGeometry = frameGeometryByDrawable[geometry.drawableId] + drawMeshWireframe( + positions = frameGeometry?.worldPosed ?: geometry.worldPosed, + indices = frameGeometry?.indices ?: geometry.mesh.indices, + edges = frameGeometry?.edges ?: geometry.edges, + highlight = highlight, + selectMode = selectMode, + colors = viewportOverlayColors, + camera = camera, + size = IntSize(widthPx, heightPx), + ) + } + } + Canvas(modifier = Modifier.fillMaxSize().graphicsLayer()) { + // The rubber-band box (both plain and armed drags) shares the one selection-box style. + drawRubberBand(marquee.boxStart, marquee.boxCurrent, overlayStyle) + + // Armed select-tool affordances (Blender B / C / Add Vertex), shared chrome with the Object + // gizmo. Only the arming area draws them - the latch is session-global, every split viewport draws. + val addVertexTool = ownedSelectTool as? ActiveSelectTool.AddVertex + val addVertexPositions = + addVertexTool?.let { tool -> + liveGeometry.firstOrNull { entry -> entry.drawableId == tool.drawableId }?.worldPosed + } + drawSelectToolAffordances( + tool = ownedSelectTool, + pointer = gesture.lastPointer, + boxDragInFlight = marquee.boxStart != null, + viewport = Size(widthPx.toFloat(), heightPx.toFloat()), + style = overlayStyle, + crosshairCursor = LocalUmamoCursors.crosshair, + draftCamera = camera.takeIf { addVertexTool != null }, + draftSize = IntSize(widthPx, heightPx).takeIf { addVertexTool != null }, + meshPositions = addVertexPositions, + ) + + // Modal Grab / Rotate / Vertex Slide HUD. Scale draws the free-transform marquee instead. + val hudOperator = activeOperator?.takeIf { it.areaId == areaId } + val hudPivot = gesture.capture?.transform?.anchor + if (hudOperator != null && hudPivot != null && hudOperator.kind != MeshOperatorKind.Scale) { + // The proportional influence ring hugs the world-unit radius the weights use (scaled by the + // frame camera). Vertex Slide and a suppressed latch never take weights, so they show no ring. + val proportionalState = proportionalEdit + val ringRadiusPx = + if (proportionalState != null && + hudOperator.kind != MeshOperatorKind.VertexSlide && + !session.activeMeshOperatorSuppressesProportional + ) { + proportionalState.radiusWorld * camera.zoom + } else { + null + } + drawModalTransformHud( + axisConstraint = axisConstraint, + pivotScreen = worldToScreen(hudPivot.first, hudPivot.second, camera, IntSize(widthPx, heightPx)), + virtualPointer = gesture.cursorWrap.virtualPointer(gesture.lastPointer), + realPointer = gesture.lastPointer, + viewport = Size(widthPx.toFloat(), heightPx.toFloat()), + lineColor = overlayColors.viewportMarquee, + pointerCursor = LocalUmamoCursors.nsewScroll, + proportionalRadiusPx = ringRadiusPx, + ) + } + if (hudOperator?.kind == MeshOperatorKind.Scale) { + val captured = gesture.capture + if (captured != null) { + val worlds = + scaleBoxPreviewWorlds + ?: captured.transform.entries.map { entry -> entry.positions } + val indices = captured.transform.entries.map { entry -> entry.coveredIndices } + drawFreeTransformBox( + bounds = liveScaleBoxBounds(worlds, indices), + camera = camera, + size = IntSize(widthPx, heightPx), + lineColor = overlayColors.viewportMarquee, + ) + } + } + } + } +} + +/** + * Each session mesh's geometry at the constant neutral pose Edit mode is pinned to: its rest shape + * (displayed = base + the neutral keyform blend), its deformer-chain mapping, and its world projection. + * + * A drawable whose mapping cannot be built (a hidden ancestor) is skipped: it cannot be drawn, so it + * cannot be edited - the same three-space primitive the object gizmo and Properties use. An empty + * result is therefore a real state, not a failure, and it is exactly the state the pointer-addressed + * commands have to keep working in. + * + * @param PuppetModel model The model to project. + * @param List drawableIds The session's mesh selection. + * @return List The per-mesh geometry, skipping what cannot be projected. + */ +private fun editMeshGeometries(model: PuppetModel, drawableIds: List): List = + drawableIds.mapNotNull { drawableId -> + val mesh = model.drawables.firstOrNull { it.id == drawableId }?.mesh ?: return@mapNotNull null + // Edit mode is pinned to the neutral pose, so the three-space geometry is captured at emptyMap(). + val worldGeometry = captureDrawableWorld(model, emptyMap(), drawableId) ?: return@mapNotNull null + EditMeshGeometry( + worldGeometry = worldGeometry, + mesh = mesh, + edges = MeshTopology.uniqueEdges(mesh.indices), + ) + } + +/** + * The same geometry, resolved from the session's CURRENT state rather than from composed values. + * + * The request collectors use this so they do not have to close over state a guarded composable may + * never have produced. Rebuilding per request is cheap in context: a request is a keypress, not a + * frame. + * + * @param EditorSession session The session to read the model and mesh selection from. + * @return List The per-mesh geometry, skipping what cannot be projected. + */ +private fun editMeshGeometries(session: EditorSession): List = + editMeshGeometries(session.model.value, session.meshSelection.value.drawableIds) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportGeometryAdapters.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportGeometryAdapters.kt new file mode 100644 index 0000000..d4afe5d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportGeometryAdapters.kt @@ -0,0 +1,247 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.MeshElement +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.screenToWorldX +import org.umamo.render.pick.screenToWorldZ +import org.umamo.render.pick.worldToScreenX +import org.umamo.render.pick.worldToScreenY + +/* + * Compose-typed adapters over the pure screen-space geometry in :render's ScreenSpacePick.kt: the + * overlays speak Offset / IntSize / MeshElement, the geometry speaks plain floats and ordinals, and + * this file is the only place the two meet. Every function here is a thin projection or an + * ordinal-to-element mapping - the actual math lives (and is tested) in :render, where the UV editor + * reuses it through its own camera. + */ + +/** Pointer distance (px) within which a click selects a vertex or an edge. */ +internal const val HIT_RADIUS_PX = 10f + +/** + * Projects an evaluator world-space position into screen pixels for the given camera and area size. + * Y flips between the spaces (screen y grows downward, world y grows upward). + * + * @param Float worldX The world-space x. + * @param Float worldZ The world-space z (up). + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Offset The screen pixel position. + */ +internal fun worldToScreen(worldX: Float, worldZ: Float, camera: ViewportCamera, size: IntSize): Offset = + Offset( + worldToScreenX(worldX, camera, size.width), + worldToScreenY(worldZ, camera, size.height), + ) + +/** + * Maps a screen point back to an evaluator world-space position - the exact inverse of [worldToScreen]. + * + * @param Float screenX The screen x in pixels. + * @param Float screenY The screen y in pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Pair The (x, y) world-space position. + */ +internal fun screenToWorld(screenX: Float, screenY: Float, camera: ViewportCamera, size: IntSize): Pair = + screenToWorldX(screenX, camera, size.width) to screenToWorldZ(screenY, camera, size.height) + +/** + * Flattens an edge list into the interleaved endpoint array ScreenSpacePick consumes (two vertex + * indices per edge, in the list's order, so a returned ordinal indexes straight back into [edges]). + * + * @param List edges The mesh's unique edges. + * @return IntArray The interleaved (low, high) endpoint pairs. + */ +private fun edgeEndpointsOf(edges: List): IntArray { + val endpoints = IntArray(edges.size * 2) + for (edgeOrdinal in edges.indices) { + endpoints[edgeOrdinal * 2] = edges[edgeOrdinal].endpointLow + endpoints[edgeOrdinal * 2 + 1] = edges[edgeOrdinal].endpointHigh + } + return endpoints +} + +/** + * The vertex index under [pointer] within [HIT_RADIUS_PX], or null. Picks the nearest within the radius. + * + * @param FloatArray positions The interleaved world posed positions. + * @param Offset pointer The cursor in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Int? The hit vertex index, or null. + */ +internal fun hitTestVertex(positions: FloatArray, pointer: Offset, camera: ViewportCamera, size: IntSize): Int? = + org.umamo.render.pick.hitTestVertex(positions, pointer.x, pointer.y, HIT_RADIUS_PX, camera, size.width, size.height) + +/** + * The edge under [pointer] within [HIT_RADIUS_PX], or null. Picks the nearest by point-to-segment + * distance in screen space. + * + * @param FloatArray positions The interleaved world posed positions. + * @param List edges The mesh's unique edges. + * @param Offset pointer The cursor in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return MeshElement.Edge? The hit edge, or null. + */ +internal fun hitTestEdge( + positions: FloatArray, + edges: List, + pointer: Offset, + camera: ViewportCamera, + size: IntSize, +): MeshElement.Edge? = + org.umamo.render.pick + .hitTestEdge(positions, edgeEndpointsOf(edges), pointer.x, pointer.y, HIT_RADIUS_PX, camera, size.width, size.height) + ?.let { edgeOrdinal -> edges[edgeOrdinal] } + +/** + * The face under [pointer], or null. When a deformed mesh overlaps itself, the triangle with the + * nearest centroid wins. + * + * @param FloatArray positions The interleaved world posed positions. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Offset pointer The cursor in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return MeshElement.Face? The hit face, or null. + */ +internal fun hitTestFace( + positions: FloatArray, + triangleIndices: IntArray, + pointer: Offset, + camera: ViewportCamera, + size: IntSize, +): MeshElement.Face? = + org.umamo.render.pick + .hitTestFace(positions, triangleIndices, pointer.x, pointer.y, camera, size.width, size.height) + ?.let { triangleOrdinal -> MeshElement.Face(triangleOrdinal) } + +/** + * The set of vertices whose screen projection lies inside the rectangle spanned by [cornerA] and + * [cornerB] (a rubber-band box select). + * + * @param FloatArray positions The interleaved world posed positions. + * @param Offset cornerA One box corner in screen pixels. + * @param Offset cornerB The opposite box corner. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The enclosed vertex indices. + */ +internal fun verticesInBox(positions: FloatArray, cornerA: Offset, cornerB: Offset, camera: ViewportCamera, size: IntSize): Set = + org.umamo.render.pick.verticesInBox(positions, cornerA.x, cornerA.y, cornerB.x, cornerB.y, camera, size.width, size.height) + +/** + * The set of edges fully enclosed by the box (both endpoints inside) - Blender's edge box-select rule. + * + * @param FloatArray positions The interleaved world posed positions. + * @param List edges The mesh's unique edges. + * @param Offset cornerA One box corner in screen pixels. + * @param Offset cornerB The opposite box corner. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The enclosed edges. + */ +internal fun edgesInBox( + positions: FloatArray, + edges: List, + cornerA: Offset, + cornerB: Offset, + camera: ViewportCamera, + size: IntSize, +): Set = + org.umamo.render.pick + .edgesInBox(positions, edgeEndpointsOf(edges), cornerA.x, cornerA.y, cornerB.x, cornerB.y, camera, size.width, size.height) + .map { edgeOrdinal -> edges[edgeOrdinal] } + .toSet() + +/** + * The set of faces whose screen centroid lies inside the box - matching the centroid dot drawn as the + * face-mode click affordance. + * + * @param FloatArray positions The interleaved world posed positions. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Offset cornerA One box corner in screen pixels. + * @param Offset cornerB The opposite box corner. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The enclosed faces. + */ +internal fun facesInBox( + positions: FloatArray, + triangleIndices: IntArray, + cornerA: Offset, + cornerB: Offset, + camera: ViewportCamera, + size: IntSize, +): Set = + org.umamo.render.pick + .facesInBox(positions, triangleIndices, cornerA.x, cornerA.y, cornerB.x, cornerB.y, camera, size.width, size.height) + .map { triangleOrdinal -> MeshElement.Face(triangleOrdinal) } + .toSet() + +/** + * The set of vertices whose screen projection lies within [radiusPx] of [center] - the Circle-select + * brush. + * + * @param FloatArray positions The interleaved world posed positions. + * @param Offset center The brush center in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The enclosed vertex indices. + */ +internal fun verticesInCircle(positions: FloatArray, center: Offset, radiusPx: Float, camera: ViewportCamera, size: IntSize): Set = + org.umamo.render.pick.verticesInCircle(positions, center.x, center.y, radiusPx, camera, size.width, size.height) + +/** + * The set of edges the brush touches (the disc overlaps the segment in screen space). + * + * @param FloatArray positions The interleaved world posed positions. + * @param List edges The mesh's unique edges. + * @param Offset center The brush center in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The touched edges. + */ +internal fun edgesInCircle( + positions: FloatArray, + edges: List, + center: Offset, + radiusPx: Float, + camera: ViewportCamera, + size: IntSize, +): Set = + org.umamo.render.pick + .edgesInCircle(positions, edgeEndpointsOf(edges), center.x, center.y, radiusPx, camera, size.width, size.height) + .map { edgeOrdinal -> edges[edgeOrdinal] } + .toSet() + +/** + * The set of faces whose screen centroid lies within [radiusPx] of [center] - matching the centroid dot + * the face-mode overlay draws. + * + * @param FloatArray positions The interleaved world posed positions. + * @param IntArray triangleIndices The mesh triangle vertex indices (three per triangle). + * @param Offset center The brush center in screen pixels. + * @param Float radiusPx The brush radius in screen pixels. + * @param ViewportCamera camera The area camera. + * @param IntSize size The area size in pixels. + * @return Set The touched faces. + */ +internal fun facesInCircle( + positions: FloatArray, + triangleIndices: IntArray, + center: Offset, + radiusPx: Float, + camera: ViewportCamera, + size: IntSize, +): Set = + org.umamo.render.pick + .facesInCircle(positions, triangleIndices, center.x, center.y, radiusPx, camera, size.width, size.height) + .map { triangleOrdinal -> MeshElement.Face(triangleOrdinal) } + .toSet() \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportObjectGizmoOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportObjectGizmoOverlay.kt new file mode 100644 index 0000000..98ed372 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportObjectGizmoOverlay.kt @@ -0,0 +1,672 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isAltPressed +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.AxisAlignedBounds +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.IndividualOriginScope +import org.umamo.edit.MeshChange +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshTransforms +import org.umamo.edit.ModalCaptureSource +import org.umamo.edit.ModalTransformCapture +import org.umamo.edit.NoticePlacement +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TransformGestureParameters +import org.umamo.edit.buildModalTransformCapture +import org.umamo.edit.eligibleTransformDrawables +import org.umamo.edit.handleScaleFactors +import org.umamo.edit.selectableOf +import org.umamo.edit.selectedWarpDeformerId +import org.umamo.edit.withMeshPositions +import org.umamo.render.ViewportCamera +import org.umamo.render.pick.PickCandidate +import org.umamo.render.pick.drawablesInBox +import org.umamo.render.pick.drawablesInCircle +import org.umamo.runtime.model.DrawableId +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawRubberBand +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle +import org.umamo.ui.transform.DrawableWorldGeometry +import org.umamo.ui.transform.captureDrawableWorld +import kotlin.math.max +import kotlin.math.min + +/** + * The captured state of an in-flight Object-mode transform: the shared [ModalTransformCapture] (which owns + * the pivot groups, the anchor, the frozen operator kind, and the rotation tracker) plus the per-drawable + * [DrawableWorldGeometry] the drive loop needs to invert a transformed world shape back onto the base mesh. + * The geometry is held in a map keyed on the drawable id, looked up by [org.umamo.edit.ModalCaptureEntry], + * so nothing stays index-aligned with the capture's entry list. + * + * @property ModalTransformCapture transform The shared gesture capture (entries, groups, anchor, kind). + * @property Map geometryById Each captured drawable's world geometry. + */ +private class ObjectGesture( + val transform: ModalTransformCapture, + val geometryById: Map, +) + +/** + * The Object-mode gizmo overlay: the Object-mode counterpart to [ViewportEditGizmoOverlay], driving whole-drawable + * selection and transforms over the puppet image. Composed whenever Object mode is active with a camera. + * Gated to Object mode (returns in Edit, where [ViewportEditGizmoOverlay] owns the viewport), so the two overlays + * are mutually exclusive by mode and never both drive the pointer. Middle-drag pan and wheel zoom are + * never consumed here, so they fall through to the navigation layer beneath. + * + * Four gestures, mirroring Edit mode but over whole drawables rather than mesh elements: + * - Click pick (idle): the primary button picks the front-most drawable under the cursor on release + * (plain replaces, Shift / Ctrl toggles membership, an Alt click opens the overlap picker for stacked + * meshes, an unmodified click on empty canvas clears). + * - Box select: a primary drag rubber-bands and selects every drawable whose world centroid is enclosed + * (Shift adds to the current selection). Works un-armed (a drag from empty canvas, Blender's default + * drag) and armed (Blender's B, which skips the pick and always boxes, then disarms). Escape or a + * right-click abandons an in-flight drag. + * - Circle select (Blender's C): a brush paints drawables by centroid - a primary drag adds, a middle or + * Shift+primary drag erases; the stroke accumulates into a working selection committed once on release + * (one undo step), previewed live through the GPU tint via [EditorSession.setPreviewSelection]; the wheel + * resizes the brush; a right-click leaves the tool keeping what was painted. + * - Grab / Rotate: a modal transform of every selected drawable's whole geometry about their combined + * centroid, previewed straight to the renderer and committed as one undo step ([MeshChange.TransformDrawables]). + * A right-click or Escape cancels (the renderer re-syncs to the committed model); a primary click or Enter + * confirms. Mesh drawables transform (a selected part expands to its subtree meshes) - a selection + * with nothing transformable blocks at the session guard ([EditorSession.beginObjectOperator]) before + * an operator ever latches here. + * - Scale: a Photoshop-style AABB marquee with eight drag handles (Shift keeps aspect, Alt scales from + * center); release commits. Warp lattices use the same marquee in [ViewportWarpLatticeOverlay]. + * + * The transform math ([applyOperator], [MeshTransforms], the shared world->base round trip), the cursor-wrap + * scheme, and the screen projection ([worldToScreen] / [screenToWorld]) are shared verbatim with the Edit + * gizmo; only the capture's per-drawable geometry and the selection domain (whole drawables) differ. + * + * @param String areaId The viewport area this overlay covers. + * @param PuppetViewportService service The render service (picking, live preview pushes, centroids). + * @param EditorSession session The session owning the model, object selection, and active tool / operator. + * @param ViewportCamera? camera The area's camera (world<->screen affine); null hides the overlay. + * @param Int widthPx The area width in pixels. + * @param Int heightPx The area height in pixels. + * @param Function onOverlapRequest Opens the overlap-picker popup for an Alt-click with 2+ candidates. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun ViewportObjectGizmoOverlay( + areaId: String, + service: PuppetViewportService, + session: EditorSession, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + onOverlapRequest: (Offset, List) -> Unit, + modifier: Modifier = Modifier, +) { + val mode by session.mode.collectAsState() + val activeSelectTool by session.activeSelectTool.collectAsState() + val activeObjectOperator by session.activeObjectOperator.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val overlayColors = LocalUmamoColors.current + + if (mode != EditorMode.Object || camera == null) { + return + } + // Armed = a select tool or an object operator LATCHED IN THIS AREA owns the pointer; only then does the + // overlay hide the OS cursor. Idle is not inert: the loop still owns the click pick and the un-armed + // box, consuming only primary-driven events, so middle-drag pan and wheel zoom fall through to the + // navigation layer. A gesture owned by another viewport leaves this area idle and inert. + val ownedSelectTool = activeSelectTool?.takeIf { it.areaId == areaId } + val ownedOperator = activeObjectOperator?.takeIf { it.areaId == areaId } + val scaleArmed = ownedOperator?.kind == MeshOperatorKind.Scale + // Hide the OS cursor only for Blender-style Grab / Rotate; Scale keeps it for handle aiming. + val armed = ownedSelectTool != null || (ownedOperator != null && !scaleArmed) + val overlayStyle = selectionOverlayStyle(overlayColors) + var scaleBoxDrag by remember(areaId) { mutableStateOf(null) } + var scaleBoxPreviewWorlds by remember(areaId) { mutableStateOf?>(null) } + val liveScaleBoxDrag = rememberUpdatedState(scaleBoxDrag) + + // Live values the areaId-keyed pointer loop reads, so a pan / resize mid-gesture is seen without re-keying. + val liveCamera = rememberUpdatedState(camera) + val liveSize = rememberUpdatedState(IntSize(widthPx, heightPx)) + + // Per-drawable world centroids, snapshotted at the press that starts a select gesture (the pose is fixed for + // the whole drag, so one snapshot serves every move) and tested against the region each frame. + var cachedCentroids by remember(areaId) { mutableStateOf>(emptyMap()) } + + // The per-area modal-gesture bookkeeping (last pointer, capture + preview, gesture origin, cursor wrap, + // pointer controller); the capture is the Object-mode gesture (shared transform capture + geometry map). + val gesture = remember(areaId) { ModalGestureState() } + + // The drawable ids a working selection currently paints, for the live GPU tint preview. + fun Selection.drawableIds(): Set = + targets.mapNotNull { (it as? SelectionTarget.Drawable)?.id }.toSet() + + // One Circle-select brush stamp: enclose the drawables whose world centroid is within the brush, filter out + // locked ones, and add them to (or remove them from) the working selection. Radius is screen pixels, so it + // converts to world units by the zoom; the center unprojects to world space to match the cached centroids. + fun circleStamp(working: Selection, erasing: Boolean, screenPos: Offset, radiusPx: Float, activeCamera: ViewportCamera, size: IntSize): Selection { + val model = session.model.value + val (worldX, worldZ) = screenToWorld(screenPos.x, screenPos.y, activeCamera, size) + val worldRadius = radiusPx / activeCamera.zoom + val enclosed = + drawablesInCircle(cachedCentroids, worldX, worldZ, worldRadius) + .map { SelectionTarget.Drawable(it) } + .filter { model.selectableOf(it) } + if (enclosed.isEmpty()) { + return working + } + return if (erasing) { + val remaining = working.targets - enclosed.toSet() + Selection(remaining, working.active?.takeIf { it in remaining } ?: remaining.lastOrNull()) + } else { + Selection(working.targets + enclosed, enclosed.last()) + } + } + + // Applies a finished box drag: select every selectable drawable whose cached world centroid the box + // encloses (Shift adds to the current selection). Shared by the armed (Blender B) and un-armed paths. + fun applyBoxSelection(start: Offset, end: Offset, additive: Boolean, activeCamera: ViewportCamera, size: IntSize) { + val model = session.model.value + val (worldStartX, worldStartZ) = screenToWorld(start.x, start.y, activeCamera, size) + val (worldEndX, worldEndZ) = screenToWorld(end.x, end.y, activeCamera, size) + val enclosed = + drawablesInBox(cachedCentroids, min(worldStartX, worldEndX), min(worldStartZ, worldEndZ), max(worldStartX, worldEndX), max(worldStartZ, worldEndZ)) + .map { SelectionTarget.Drawable(it) } + .filter { model.selectableOf(it) } + val current = session.selection.value + val newSelection = + if (additive) { + Selection(current.targets + enclosed, enclosed.lastOrNull() ?: current.active) + } else { + Selection(enclosed.toSet(), enclosed.lastOrNull()) + } + session.setSelection(newSelection) + } + + // The marquee (box + circle) machinery over whole drawables: the stroke / rubber-band state and event + // rules are shared (MarqueeSelectController); the callbacks bind them to the drawable domain - the + // centroid snapshot at stroke start and the live GPU tint preview are the Object-only extras. + val marquee = + remember(areaId) { + MarqueeSelectController( + seedStroke = { session.selection.value }, + stampStroke = { working, erasing, center, radiusPx, stampCamera, stampSize -> + circleStamp(working, erasing, center, radiusPx, stampCamera, stampSize) + }, + commitStroke = { stroke -> session.setSelection(stroke) }, + applyBox = { start, end, additive, boxCamera, boxSize -> applyBoxSelection(start, end, additive, boxCamera, boxSize) }, + setCircleRadius = { radiusPx -> session.setCircleRadius(radiusPx) }, + clearTool = { session.clearSelectTool() }, + onStrokeBegin = { cachedCentroids = service.drawableWorldCentroids() }, + previewStroke = { stroke -> session.setPreviewSelection(stroke?.drawableIds()) }, + ) + } + + // The idle click-pick / un-armed box flow over whole drawables (press rubber-bands, sub-threshold + // release picks, Alt resolves the overlap stack, Shift+RightClick places the 2D cursor), bound to + // this viewport's raster pickers and centroid snapshot; see ObjectPickController. + val objectPick = + remember(areaId) { + ObjectPickController( + session = session, + marquee = marquee, + pickTopmost = { position -> service.pickAt(areaId, position.x, position.y) }, + pickStack = { position -> service.pickAllAt(areaId, position.x, position.y) }, + onOverlapRequest = onOverlapRequest, + placeCursor = session::setCursor2d, + onBoxBegin = { cachedCentroids = service.drawableWorldCentroids() }, + ) + } + + // Escape resolves the in-flight select gesture: the shell routes the key through the session's cancel + // signal (the gesture state lives in the marquee controller, which the session cannot reach directly). + // A circle stroke keeps its paint (see MarqueeSelectController.cancel); an un-armed box drag abandons. + LaunchedEffect(session) { + session.meshGestureCancelRequests.collect { + marquee.cancel() + objectPick.cancel() + } + } + + // The recomposition-gated tool-switch backstop the Edit and UV overlays already carry: an armed tool that + // is cleared or switched (box<->circle) resolves any in-flight marquee. Keyed on the tool KIND (not the + // whole value) so a circle-brush resize does not re-fire and wipe the stroke mid-paint. Object's body + // mirrors its own cancel collector above (marquee plus the idle box), since it - unlike Edit / UV - also + // carries an un-armed box drag; the pointer loop's own idle-box cancel and this one are order-independent. + LaunchedEffect(selectToolKind(ownedSelectTool)) { + marquee.cancel() + objectPick.cancel() + } + + // Confirms the in-flight object transform: commit every drawable's new base positions as one undo step (a + // null / empty preview means no movement, so nothing commits), register that step on the operation + // settings strip over the retained capture, then clear the operator - its teardown re-syncs the renderer. + fun confirmObjectGesture() { + val committed = gesture.preview + val gestureData = gesture.capture + val parameters = gesture.lastParameters + if (committed != null && gestureData != null && committed.isNotEmpty()) { + val transform = gestureData.transform + val modelBefore = session.model.value + session.commitObjectPositions(MeshChange.TransformDrawables(transform.drawableIds, transform.operatorKind), committed) + // A commit that recorded nothing (the drawables landed where they started) has no step of its + // own to amend, so it registers nothing. + if (parameters != null && session.model.value !== modelBefore) { + registerObjectTransformAdjustment(session, areaId, transform, gestureData.geometryById, parameters) + } + } + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + session.clearObjectOperator() + } + + fun pushScaleBoxPreview(worlds: List) { + val gestureData = gesture.capture ?: return + val transform = gestureData.transform + val newBaseByDrawable = LinkedHashMap(transform.entries.size) + var folded = session.model.value + for ((index, entry) in transform.entries.withIndex()) { + val geometry = gestureData.geometryById.getValue(entry.drawableId) + val newBase = geometry.worldToBase(worlds[index], entry.coveredIndices) + newBaseByDrawable[entry.drawableId] = newBase + folded = folded.withMeshPositions(entry.drawableId, newBase) + } + gesture.preview = newBaseByDrawable + scaleBoxPreviewWorlds = worlds + service.setModel(folded) + } + + // Drives the modal preview for one virtual-pointer position: applies the operator to every captured + // drawable's whole geometry about the shared pivot, maps each result back to local through the + // deformer-chain inverse, and pushes the folded model to the renderer. False when the capture has + // not landed yet. + fun driveObjectPreview(operator: MeshOperatorKind, virtualPointer: Offset, activeCamera: ViewportCamera, size: IntSize): Boolean { + val start = gesture.gestureStart ?: return false + val gestureData = gesture.capture ?: return false + val transform = gestureData.transform + // One pointer frame for the whole capture; only geometry and pivots vary per drawable. The frame + // resolves ONCE into the numbers every drawable applies; the confirm hands them to the settings strip. + val frame = TransformGestureFrame(transform.anchor, start, virtualPointer, session.axisConstraint.value, activeCamera, size) + val parameters = gestureParameters(operator, frame, transform.rotationTracker) + gesture.lastParameters = parameters + val newBaseByDrawable = LinkedHashMap(transform.entries.size) + var folded = session.model.value + for (entry in transform.entries) { + val geometry = gestureData.geometryById.getValue(entry.drawableId) + // Proportional editing is an Edit-mode feature: object mode moves whole drawables, so there + // are no unselected vertices to weight. + val transformedWorld = applyOperator(operator, entry.positions, entry.groups, parameters, emptyMap()) + val newBase = geometry.worldToBase(transformedWorld, entry.coveredIndices) + newBaseByDrawable[entry.drawableId] = newBase + folded = folded.withMeshPositions(entry.drawableId, newBase) + } + gesture.preview = newBaseByDrawable + service.setModel(folded) + return true + } + + // The modal gesture's commit-side seam: the Object overlay drives whole-drawable previews, confirms + // as one TransformDrawables undo step, and cancels through the session's operator clear. The + // pointer-side mechanics live in ModalTransformController; no scroll behavior in Object mode. + val modalTarget = + object : ModalTransformTarget { + override fun drivePreview(virtualPointer: Offset, camera: ViewportCamera, size: IntSize): Boolean { + // Defensive ownership check (the pointer loop already gates): only the initiating area drives. + // Scale uses the handle marquee, not distance-from-pivot. + val operator = + session.activeObjectOperator.value?.takeIf { + it.areaId == areaId && it.kind != MeshOperatorKind.Scale + } ?: return false + return driveObjectPreview(operator.kind, virtualPointer, camera, size) + } + + override fun confirm() { + confirmObjectGesture() + } + + override fun cancel() { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + // The teardown effect re-syncs the renderer when the operator clears. + session.clearObjectOperator() + } + } + + // Seed / tear down the transform capture as the operator latches / clears. On latch, freeze each selected + // drawable's world geometry at the current object-mode pose and hand the shared builder its sources plus + // this area's active-element / cursor anchors. On clear (confirm or cancel), re-sync the renderer to the + // committed model, discarding any throwaway preview the drive loop pushed. + LaunchedEffect(activeObjectOperator) { + val operator = activeObjectOperator?.takeIf { it.areaId == areaId } + if (operator != null) { + val model = session.model.value + val pose = session.pose.value + val eligibleIds = eligibleTransformDrawables(session.selection.value, model) + if (eligibleIds == null) { + // Warp-lattice G / S / R latches the same operator; ViewportWarpLatticeOverlay owns that path. + return@LaunchedEffect + } + // A drawable with a hidden ancestor has no world mapping and captures as null - skip it rather than + // abort the whole gesture (the others still transform). + val geometries = eligibleIds.mapNotNull { drawableId -> captureDrawableWorld(model, pose, drawableId) } + val geometryById = geometries.associateBy { geometry -> geometry.drawableId } + // Object mode moves every vertex of each drawable, so the covered set is the whole mesh. Triangle + // connectivity is unused here (WholeMesh pivots, no proportional editing), so an empty array serves. + val sources = + geometries.map { geometry -> + ModalCaptureSource(geometry.drawableId, geometry.world, IntArray(0), geometry.allIndices) + } + // The two per-area anchors the shared builder cannot resolve itself: the active drawable's own + // centroid and the 2D cursor. The builder falls back to the combined median when nothing is active; an + // unplaced cursor resolves to the world origin, like the snap commands. + val activeAnchor = + (session.selection.value.active as? SelectionTarget.Drawable)?.id + ?.let { activeId -> geometryById[activeId] } + ?.let { geometry -> MeshTransforms.medianPivot(geometry.world, geometry.allIndices) } + val cursorAnchor = session.cursor2dOrWorldOrigin().let { cursor -> cursor.worldX to cursor.worldZ } + val transform = + buildModalTransformCapture( + sources = sources, + pivotMode = session.pivotMode.value, + // Object mode's Individual Origins turns each whole drawable about its own centroid. + individualOriginScope = IndividualOriginScope.WholeMesh, + operatorKind = operator.kind, + activeAnchor = activeAnchor, + cursorAnchor = cursorAnchor, + ) + if (transform == null) { + // Nothing transformable survived (all hidden, or the selection changed): drop the operator. + session.clearObjectOperator() + } else { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + gesture.begin(ObjectGesture(transform, geometryById), gesture.lastPointer) + } + } else { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + // Resync the renderer only when THIS overlay owned a gesture: the effect also runs its else + // branch at mount (and when another area's operator latches), and an unguarded setModel from + // a viewport split open mid-gesture would stomp the initiating area's live preview. + if (gesture.end()) { + service.setModel(session.model.value) + } + } + } + + // Enter confirms the modal object gesture (mirroring a primary click); the shell routes the keypress + // here, gated to the INITIATING area through the operator latch itself. + LaunchedEffect(session) { + collectModalConfirmRequests(session, { session.activeObjectOperator.value?.areaId == areaId }) { + confirmObjectGesture() + } + } + + // The geometry-dependent Shift+S snaps for Object mode over the selected drawables' centroids. + // Only the pointer's own area executes: every open 2D viewport composes this collector, and an + // ungated request would commit once per viewport. + // The handler ignores the area - a snap acts on the model - so the payload's id is purely the election. + LaunchedEffect(session) { + session.snapRequests.collect { request -> + if (session.mode.value != EditorMode.Object || request.areaId != areaId) { + return@collect + } + handleObjectSnapRequest(session, request.kind) + } + } + + LaunchedEffect(session) { + session.viewportMirrorRequests.collect { request -> + if (session.mode.value != EditorMode.Object || request.areaId != areaId) { + return@collect + } + // Warp-lattice selections fall through so ViewportWarpLatticeOverlay can mirror CPs. + if (!handleObjectMirrorRequest(session, request.mirrorHorizontal) && + selectedWarpDeformerId(session.selection.value, session.model.value) == null + ) { + session.emitNotice("notice.transform.onlyDrawables", NoticePlacement.NearCursor) + } + } + } + + Box( + modifier = + modifier + .fillMaxSize() + .clipToBounds() + .onGloballyPositioned { coordinates -> gesture.areaScreenOrigin = coordinates.positionOnScreen() } + .then( + if (armed) { + Modifier.pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + } else { + Modifier + }, + ) + .pointerInput(areaId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + gesture.lastPointer = change.position + val latchedOperator = session.activeObjectOperator.value + val latchedTool = session.activeSelectTool.value + // A gesture belongs to its initiating area: while another viewport's operator or tool is + // live - or a UV operator, which can never belong to a viewport area - this overlay is + // fully inert (no drive, no picks, no marquee). Escape and Enter stay global through + // the shell ladder, and navigation (pan / zoom) still falls through. + if ((latchedOperator != null && latchedOperator.areaId != areaId) || + (latchedTool != null && latchedTool.areaId != areaId) || + session.activeUvOperator.value != null + ) { + objectPick.cancel() + continue + } + val operator = latchedOperator + val tool = latchedTool + val activeCamera = liveCamera.value + val size = liveSize.value + // A tool or operator armed mid-drag (via its keymap command) supersedes the un-armed box: + // drop the rubber-band so its release handler cannot fire into the armed gesture's state + // (the controller's cancel no-ops when no box is in flight). + if (operator != null || tool != null) { + objectPick.cancel() + } + if (operator != null && operator.kind == MeshOperatorKind.Scale) { + // Photoshop-style Scale marquee: drag AABB handles; release commits. + val gestureData = gesture.capture + when (event.type) { + PointerEventType.Press -> { + if (event.buttons.isSecondaryPressed) { + scaleBoxDrag = null + scaleBoxPreviewWorlds = null + session.clearObjectOperator() + change.consume() + } else if (event.buttons.isPrimaryPressed && gestureData != null) { + val worlds = gestureData.transform.entries.map { it.positions } + val indices = gestureData.transform.entries.map { it.coveredIndices } + val bounds = scaleBoxBounds(worlds, indices) + val handle = hitFreeTransformHandle(change.position, bounds, activeCamera, size) + if (handle != null) { + scaleBoxDrag = ScaleBoxDrag(handle, bounds, worlds.map { it.copyOf() }, indices) + change.consume() + } else { + confirmObjectGesture() + change.consume() + } + } + } + + PointerEventType.Move -> { + val drag = liveScaleBoxDrag.value + if (drag != null && event.buttons.isPrimaryPressed) { + val (worldX, worldY) = + screenToWorld(change.position.x, change.position.y, activeCamera, size) + val worlds = + driveScaleBoxWorlds( + drag, + worldX, + worldY, + uniform = event.keyboardModifiers.isShiftPressed, + fromCenter = event.keyboardModifiers.isAltPressed, + ) + val (fx, fy, _) = + handleScaleFactors( + drag.startBounds, + drag.handle, + worldX, + worldY, + event.keyboardModifiers.isShiftPressed, + event.keyboardModifiers.isAltPressed, + ) + gesture.lastParameters = TransformGestureParameters(0f, 0f, fx, fy, 0f) + pushScaleBoxPreview(worlds) + change.consume() + } + } + + PointerEventType.Release -> { + if (liveScaleBoxDrag.value != null) { + scaleBoxDrag = null + confirmObjectGesture() + change.consume() + } + } + + else -> {} + } + } else if (operator != null) { + // MODAL Grab / Rotate: the shared controller drives every captured drawable over the + // shared pivot and swallows every event (stale discard, virtual-pointer drive, + // cursor wrap, RMB-cancel / LMB-confirm). + gesture.lastPointer = + gesture.modalController.handleEvent( + event, + change, + modalTarget, + activeCamera, + size, + gesture.areaScreenOrigin, + ) + } else if (tool is ActiveSelectTool.Circle) { + // CIRCLE SELECT: the shared controller paints drawables by centroid, previews the + // stroke through the GPU tint, and consumes every event; see + // MarqueeSelectController.handleCircleEvent. + marquee.handleCircleEvent(event, change, tool.radiusPx, activeCamera, size) + } else if (tool is ActiveSelectTool.BoxArmed) { + // BOX SELECT (armed): a drag rubber-bands; on release every drawable whose centroid is enclosed is + // selected (Shift adds). A right-click or a sub-threshold click just disarms. One-shot: disarm after. + when (event.type) { + PointerEventType.Press -> + if (event.buttons.isSecondaryPressed) { + session.clearSelectTool() + change.consume() + } else if (event.buttons.isPrimaryPressed) { + cachedCentroids = service.drawableWorldCentroids() + marquee.beginBox(change.position) + change.consume() + } + + PointerEventType.Move -> + if (marquee.dragBox(change.position)) { + change.consume() + } + + PointerEventType.Release -> { + val boxRelease = marquee.releaseBox(change.position, event.keyboardModifiers.isShiftPressed, activeCamera, size) + if (boxRelease != BoxRelease.None) { + // Armed Box-select is one-shot: disarm after the drag (or a bare click). + session.clearSelectTool() + change.consume() + } + } + + else -> {} + } + } else { + // IDLE (nothing armed): the primary button owns picking here, through the shared + // controller - a press starts a provisional rubber-band, a drag past the threshold + // box-selects on release (Shift adds), a sub-threshold release is the click pick + // (replace / toggle / Alt overlap), Shift+RightClick places the 2D cursor, and a + // right-click or Escape abandons the drag. Only primary-driven events are + // consumed, so middle-drag pan and wheel zoom fall through to the navigation layer. + objectPick.handleIdleEvent(event, change, activeCamera, size) + } + } + } + }, + ) { + Canvas(modifier = Modifier.fillMaxSize()) { + val fullSize = Size(widthPx.toFloat(), heightPx.toFloat()) + // The box rubber-band. + drawRubberBand(marquee.boxStart, marquee.boxCurrent, overlayStyle) + + // Armed select-tool affordances (Blender B / C), shared chrome with the Edit gizmo. Only + // the arming area draws them - the latch is session-global, every split viewport draws. + drawSelectToolAffordances( + tool = ownedSelectTool, + pointer = gesture.lastPointer, + boxDragInFlight = marquee.boxStart != null, + viewport = fullSize, + style = overlayStyle, + crosshairCursor = LocalUmamoCursors.crosshair, + ) + + // Modal Grab / Rotate HUD. Scale draws the free-transform marquee instead. + val captured = gesture.capture + val operator = activeObjectOperator?.takeIf { it.areaId == areaId } + if (operator != null && captured != null && operator.kind != MeshOperatorKind.Scale) { + val anchor = captured.transform.anchor + drawModalTransformHud( + axisConstraint = axisConstraint, + pivotScreen = worldToScreen(anchor.first, anchor.second, camera, IntSize(widthPx, heightPx)), + virtualPointer = gesture.cursorWrap.virtualPointer(gesture.lastPointer), + realPointer = gesture.lastPointer, + viewport = fullSize, + lineColor = overlayColors.viewportMarquee, + pointerCursor = LocalUmamoCursors.nsewScroll, + proportionalRadiusPx = null, + ) + } + if (operator?.kind == MeshOperatorKind.Scale && captured != null) { + val worlds = + scaleBoxPreviewWorlds + ?: captured.transform.entries.map { entry -> entry.positions } + val indices = captured.transform.entries.map { entry -> entry.coveredIndices } + val bounds = liveScaleBoxBounds(worlds, indices) + if (bounds != AxisAlignedBounds(0f, 0f, 0f, 0f) || worlds.any { it.size >= 2 }) { + drawFreeTransformBox( + bounds = bounds, + camera = camera, + size = IntSize(widthPx, heightPx), + lineColor = overlayColors.viewportMarquee, + ) + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportOverlayColors.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportOverlayColors.kt new file mode 100644 index 0000000..3374833 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportOverlayColors.kt @@ -0,0 +1,171 @@ +package org.umamo.ui.viewport + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.graphics.Color +import org.umamo.ui.graphics.parseHexColor +import org.umamo.ui.rememberStringSetting + +/* + * The settings-backed colors the viewport and UV editor draw OVER the rigger's art - the Edit-mode + * element palette, the placement state colors (the collision warning, the pinned highlight), and the + * selection highlights the GL viewport tints with. User colors (Settings > Colors), never theme + * colors: no theme can know what reads against a given piece of art. One key table, one resolved + * palette, one reactive binding, so a color edited in the preferences window recomposes every overlay + * live. A new over-art color belongs here, never in UmamoColors. + */ + +/** + * The settings keys and bundled defaults for the viewport overlay colors, one #AARRGGBB hex string + * each: the Edit-mode element palette (vertex / edge / face by idle / selected / active / off-key), + * the placement state colors, and the selection highlights. The defaults here are kept in lockstep + * with defaultSettings.json (the merged-settings baseline); these constants are the Kotlin-side + * fallback for a missing or unparseable value, shared by the overlays, the GL viewport binding, and + * the preferences window so none of them duplicates a key literal. + */ +internal object ViewportColorSettings { + const val VERTEX_IDLE_KEY = "viewport.meshEdit.vertexIdle" + const val VERTEX_SELECTED_KEY = "viewport.meshEdit.vertexSelected" + const val VERTEX_ACTIVE_KEY = "viewport.meshEdit.vertexActive" + const val VERTEX_OFFKEY_KEY = "viewport.meshEdit.vertexOffKey" + const val EDGE_IDLE_KEY = "viewport.meshEdit.edgeIdle" + const val EDGE_SELECTED_KEY = "viewport.meshEdit.edgeSelected" + const val EDGE_ACTIVE_KEY = "viewport.meshEdit.edgeActive" + const val EDGE_OFFKEY_KEY = "viewport.meshEdit.edgeOffKey" + const val FACE_IDLE_KEY = "viewport.meshEdit.faceIdle" + const val FACE_SELECTED_KEY = "viewport.meshEdit.faceSelected" + const val FACE_ACTIVE_KEY = "viewport.meshEdit.faceActive" + const val FACE_OFFKEY_KEY = "viewport.meshEdit.faceOffKey" + const val WARNING_COLOR_KEY = "viewport.warningColor" + const val PINNED_PLACEMENT_COLOR_KEY = "viewport.pinnedPlacementColor" + const val SELECTION_HIGHLIGHT_KEY = "viewport.selectionHighlightColor" + const val ACTIVE_SELECTION_HIGHLIGHT_KEY = "viewport.activeSelectionHighlightColor" + + const val VERTEX_IDLE_DEFAULT = "#FFFF00EC" + const val VERTEX_SELECTED_DEFAULT = "#FFFF7A00" + const val VERTEX_ACTIVE_DEFAULT = "#FF7DE400" + const val VERTEX_OFFKEY_DEFAULT = "#66888888" + const val EDGE_IDLE_DEFAULT = "#99000000" + const val EDGE_SELECTED_DEFAULT = "#FFFF7A00" + const val EDGE_ACTIVE_DEFAULT = "#FF7DE400" + const val EDGE_OFFKEY_DEFAULT = "#44888888" + const val FACE_IDLE_DEFAULT = "#22000000" + const val FACE_SELECTED_DEFAULT = "#66FF7A00" + const val FACE_ACTIVE_DEFAULT = "#FF7DE400" + const val FACE_OFFKEY_DEFAULT = "#44888888" + const val WARNING_COLOR_DEFAULT = "#FFFF5A5A" + const val PINNED_PLACEMENT_COLOR_DEFAULT = "#FFB266FF" + const val SELECTION_HIGHLIGHT_DEFAULT = "#FF338CFF" + const val ACTIVE_SELECTION_HIGHLIGHT_DEFAULT = "#FF7DE400" +} + +/** + * The resolved overlay palette: one Compose color per role, parsed from the user's settings. Held + * as a value so an overlay's draw pass reads plain fields, and passed whole to the wireframe drawer, + * which substitutes per-island roles by copying it. + * + * @property Color vertexIdle Unselected vertex dots. + * @property Color vertexSelected Selected vertex dots. + * @property Color vertexActive The active (last-touched) vertex dot. + * @property Color vertexOffKey Vertex dots while the pose is between keys (read-only). + * @property Color edgeIdle Unselected wireframe edges. + * @property Color edgeSelected Selected (or derived-selected) edges. + * @property Color edgeActive The active edge. + * @property Color edgeOffKey Edges while the pose is between keys. + * @property Color faceIdle Unselected face fills (face mode only). + * @property Color faceSelected Selected (or derived-selected) face fills. + * @property Color faceActive The active face's centroid dot (never a fill - it would blank the art). + * @property Color faceOffKey Face fills while the pose is between keys. + * @property Color warning The stroke of a placement warning affordance - a tile overlapping a neighbor + * or spilling off its page - on every edge role while the warning stands. + * @property Color pinnedPlacement The edges of a pinned tile's islands in the UV editor, on every edge role. + * @property Color selectionHighlight The tint the GL viewport mixes over selected drawables. + * @property Color activeSelectionHighlight The tint the GL viewport mixes over the active drawable. + */ +internal data class ViewportOverlayColors( + val vertexIdle: Color, + val vertexSelected: Color, + val vertexActive: Color, + val vertexOffKey: Color, + val edgeIdle: Color, + val edgeSelected: Color, + val edgeActive: Color, + val edgeOffKey: Color, + val faceIdle: Color, + val faceSelected: Color, + val faceActive: Color, + val faceOffKey: Color, + val warning: Color, + val pinnedPlacement: Color, + val selectionHighlight: Color, + val activeSelectionHighlight: Color, +) + +/** + * Resolves the overlay palette from settings, reactively: each key is bound through + * [rememberStringSetting], so a color edited in the preferences window recomposes the overlays live. + * A missing or unparseable value falls back to the bundled default constant. + * + * @return ViewportOverlayColors The current palette. + */ +@Composable +internal fun rememberViewportOverlayColors(): ViewportOverlayColors = + ViewportOverlayColors( + vertexIdle = settingColor(ViewportColorSettings.VERTEX_IDLE_KEY, ViewportColorSettings.VERTEX_IDLE_DEFAULT), + vertexSelected = settingColor(ViewportColorSettings.VERTEX_SELECTED_KEY, ViewportColorSettings.VERTEX_SELECTED_DEFAULT), + vertexActive = settingColor(ViewportColorSettings.VERTEX_ACTIVE_KEY, ViewportColorSettings.VERTEX_ACTIVE_DEFAULT), + vertexOffKey = settingColor(ViewportColorSettings.VERTEX_OFFKEY_KEY, ViewportColorSettings.VERTEX_OFFKEY_DEFAULT), + edgeIdle = settingColor(ViewportColorSettings.EDGE_IDLE_KEY, ViewportColorSettings.EDGE_IDLE_DEFAULT), + edgeSelected = settingColor(ViewportColorSettings.EDGE_SELECTED_KEY, ViewportColorSettings.EDGE_SELECTED_DEFAULT), + edgeActive = settingColor(ViewportColorSettings.EDGE_ACTIVE_KEY, ViewportColorSettings.EDGE_ACTIVE_DEFAULT), + edgeOffKey = settingColor(ViewportColorSettings.EDGE_OFFKEY_KEY, ViewportColorSettings.EDGE_OFFKEY_DEFAULT), + faceIdle = settingColor(ViewportColorSettings.FACE_IDLE_KEY, ViewportColorSettings.FACE_IDLE_DEFAULT), + faceSelected = settingColor(ViewportColorSettings.FACE_SELECTED_KEY, ViewportColorSettings.FACE_SELECTED_DEFAULT), + faceActive = settingColor(ViewportColorSettings.FACE_ACTIVE_KEY, ViewportColorSettings.FACE_ACTIVE_DEFAULT), + faceOffKey = settingColor(ViewportColorSettings.FACE_OFFKEY_KEY, ViewportColorSettings.FACE_OFFKEY_DEFAULT), + warning = settingColor(ViewportColorSettings.WARNING_COLOR_KEY, ViewportColorSettings.WARNING_COLOR_DEFAULT), + pinnedPlacement = settingColor(ViewportColorSettings.PINNED_PLACEMENT_COLOR_KEY, ViewportColorSettings.PINNED_PLACEMENT_COLOR_DEFAULT), + selectionHighlight = settingColor(ViewportColorSettings.SELECTION_HIGHLIGHT_KEY, ViewportColorSettings.SELECTION_HIGHLIGHT_DEFAULT), + activeSelectionHighlight = settingColor(ViewportColorSettings.ACTIVE_SELECTION_HIGHLIGHT_KEY, ViewportColorSettings.ACTIVE_SELECTION_HIGHLIGHT_DEFAULT), + ) + +/** + * Binds one color setting reactively and parses it, falling back to the bundled default when the stored + * text is not a valid hex color (the default constants always parse). + * + * @param String key The dotted settings key. + * @param String defaultHex The bundled default #AARRGGBB string. + * @return Color The parsed color. + */ +@Composable +private fun settingColor(key: String, defaultHex: String): Color { + val hexText by rememberStringSetting(key, defaultHex) + return parseHexColor(hexText) ?: parseHexColor(defaultHex)!! +} + +/** + * Parses a selection-highlight hex color (#RRGGBB or #AARRGGBB, the # optional) into its three 0..1 + * sRGB components, falling back to the built-in highlight color when the string is absent or + * malformed. Both digit counts are accepted because a hand-typed or older user setting may hold + * #RRGGBB while the preferences HexColorField commits canonical #AARRGGBB; the alpha byte is + * ignored - the GL highlight mix has no alpha term. The components match what the highlight shader + * mixes (Compose-style 0..1 sRGB), so the parse divides each byte by 255. Not a Composable, because + * the viewport binding reads the setting outside composition. + * + * @param String? hex The configured hex color, or null when unset. + * @return Triple The (red, green, blue) components, each 0..1. + */ +internal fun parseSelectionHighlightColor(hex: String?): Triple { + val cleaned = (hex ?: ViewportColorSettings.SELECTION_HIGHLIGHT_DEFAULT).trim().removePrefix("#") + val packed = + when (cleaned.length) { + 6 -> cleaned.toLongOrNull(16) + 8 -> cleaned.toLongOrNull(16)?.and(0xFFFFFF) + else -> null + } ?: ViewportColorSettings.SELECTION_HIGHLIGHT_DEFAULT.removePrefix("#").toLong(16) + return Triple( + ((packed shr 16) and 0xFF) / 255f, + ((packed shr 8) and 0xFF) / 255f, + (packed and 0xFF) / 255f, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportPickOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportPickOverlay.kt new file mode 100644 index 0000000..7825bbb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportPickOverlay.kt @@ -0,0 +1,114 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.pointerInput +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.partByDrawable +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.workspace.LocalRelationPick +import org.umamo.ui.workspace.PickKind + +/** + * The relation-pick overlay: while a Properties field's eyedropper is armed, this layer covers the whole + * viewport, shows the eyedropper cursor, and turns the next click into the picked entity. Mounted ABOVE + * the Object gizmo - that overlay owns the primary button in Object mode and would otherwise change the + * selection before the pick ever saw the click. + * + * Self-gated on the shell's [org.umamo.ui.workspace.RelationPickController]: with no pick armed it composes + * nothing and installs no pointer input, so every other frame passes straight through to the gizmo and + * navigation layers beneath. Unlike the zoom-region and select-tool latches this is NOT scoped to one + * area - a pick may be resolved from any viewport or from the outliner, whichever the user clicks first. + * + * [PuppetViewportService.pickAt] hit-tests drawables only, so a Part request resolves through the picked + * drawable's owning part; a Deformer-only request has nothing to offer here and stays outliner-only. + * The selectability filter the Object gizmo applies is deliberately skipped - an eyedropper may bind an + * unselectable object, matching Blender. + * + * It also publishes what the pointer is over as it moves, which the shell's overlay names in a badge. The + * eyedropper cursor itself is drawn at the SHELL level, not here, so it is visible the instant a pick is + * armed no matter which panel the pointer happens to be over. + * + * @param String areaId The viewport area this overlay covers. + * @param PuppetViewportService service The render service (for the hit test). + * @param Modifier modifier The layout modifier. + */ +@Composable +fun ViewportPickOverlay(areaId: String, service: PuppetViewportService, modifier: Modifier = Modifier) { + val picker = LocalRelationPick.current + val request = picker.request + val puppet = LocalPuppet.current + if (request == null || puppet == null) { + return + } + // Whether a click HERE can bind anything. A deformer-only pick cannot - the hit test is drawable-only - + // but the overlay still mounts, because the alternative is worse: with no overlay the click falls through + // to the object gizmo, changes the selection, and swaps the arming field out from under the live pick. + // Same rule the outliner follows via PickClickOutcome.Swallowed - while ANY pick is armed, the viewport + // must not select. + val resolvableHere = PickKind.Drawable in request.accepts || PickKind.Part in request.accepts + + // Built once per model, not per pointer event: a Part pick calls this on every Move, and partByDrawable + // walks the whole org tree allocating a fresh map. + val partOfDrawable = remember(puppet) { puppet.partByDrawable() } + + // Resolves the entity a click at this position would bind, or null for a miss. The selectability filter + // the Object gizmo applies is deliberately skipped - an eyedropper may bind an unselectable object. + fun targetAt(x: Float, y: Float): SelectionTarget? { + if (!resolvableHere) { + return null + } + val hit = service.pickAt(areaId, x, y) ?: return null + return if (PickKind.Drawable in request.accepts) { + SelectionTarget.Drawable(hit) + } else { + partOfDrawable[hit]?.let { partId -> SelectionTarget.Part(partId) } + } + } + + Box( + modifier = + modifier + .fillMaxSize() + .clipToBounds() + .pointerInput(areaId, request) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + // Name what is under the pointer so the shell's badge can show it before the click. + // The hit test runs per move, which is affordable because this overlay only exists + // while a pick is armed - a deliberate, short-lived interaction. + when (event.type) { + PointerEventType.Move, PointerEventType.Enter -> picker.hover(targetAt(change.position.x, change.position.y)) + PointerEventType.Exit -> picker.hover(null) + else -> {} + } + if (event.type != PointerEventType.Press) { + continue + } + if (event.buttons.isSecondaryPressed) { + picker.cancel() + change.consume() + continue + } + if (!event.buttons.isPrimaryPressed) { + continue + } + // Consume every primary press, hit or miss - and also when nothing here is resolvable at + // all: the gizmo beneath must never see it, or a missed (or unresolvable) pick would + // change the selection. A miss leaves the pick armed to try again. + change.consume() + targetAt(change.position.x, change.position.y)?.let { target -> picker.resolve(target) } + } + } + }, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportPieMenus.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportPieMenus.kt new file mode 100644 index 0000000..430335f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportPieMenus.kt @@ -0,0 +1,70 @@ +package org.umamo.ui.viewport + +import org.jetbrains.compose.resources.StringResource +import org.umamo.edit.PieMenuKind +import org.umamo.ui.kit.PieMenuEntry +import org.umamo.ui.resources.* + +/** + * The entry ring for one pie kind, in Blender slot order (W, E, S, N, then the diagonals). Shared + * by the shell-level pie host's rendering (ShellCursorOverlays.kt) and the shell's 1..N digit + * shortcuts, so the picked ordinal always matches the drawn number. Icons are authored per entry; + * a null icon renders the placeholder square. + * + * @param PieMenuKind kind The open pie. + * @return List The pie's entries. + */ +fun pieMenuEntriesFor(kind: PieMenuKind): List = + when (kind) { + PieMenuKind.PivotMode -> + listOf( + PieMenuEntry("transform.pivot.median", Res.string.cmd_transform_pivot_median), + PieMenuEntry("transform.pivot.individual", Res.string.cmd_transform_pivot_individual), + PieMenuEntry("transform.pivot.active", Res.string.cmd_transform_pivot_active), + PieMenuEntry("transform.pivot.cursor", Res.string.cmd_transform_pivot_cursor), + ) + + PieMenuKind.Snap -> + listOf( + PieMenuEntry("snap.cursorToWorldOrigin", Res.string.cmd_snap_cursor_world_origin), + PieMenuEntry("snap.cursorToSelected", Res.string.cmd_snap_cursor_selected), + PieMenuEntry("snap.cursorToActive", Res.string.cmd_snap_cursor_active), + PieMenuEntry("snap.cursorToGrid", Res.string.cmd_snap_cursor_grid), + PieMenuEntry("snap.selectionToGrid", Res.string.cmd_snap_selection_grid), + PieMenuEntry("snap.selectionToCursor", Res.string.cmd_snap_selection_cursor), + PieMenuEntry("snap.selectionToCursorOffset", Res.string.cmd_snap_selection_cursor_offset), + PieMenuEntry("snap.selectionToActive", Res.string.cmd_snap_selection_active), + ) + + PieMenuKind.UvSnap -> + listOf( + PieMenuEntry("uv.snap.selectionToPixels", Res.string.cmd_uv_snap_selection_pixels), + PieMenuEntry("uv.snap.selectionToCursor", Res.string.cmd_uv_snap_selection_cursor), + PieMenuEntry("uv.snap.selectionToCursorOffset", Res.string.cmd_uv_snap_selection_cursor_offset), + PieMenuEntry("uv.snap.selectionToGrid", Res.string.cmd_uv_snap_selection_grid), + PieMenuEntry("uv.snap.cursorToPixels", Res.string.cmd_uv_snap_cursor_pixels), + PieMenuEntry("uv.snap.cursorToSelected", Res.string.cmd_uv_snap_cursor_selected), + PieMenuEntry("uv.snap.cursorToGrid", Res.string.cmd_uv_snap_cursor_grid), + ) + + PieMenuKind.MergeTarget -> + listOf( + PieMenuEntry("mesh.merge.atCenter", Res.string.cmd_mesh_merge_at_center), + PieMenuEntry("mesh.merge.atFirst", Res.string.cmd_mesh_merge_at_first), + PieMenuEntry("mesh.merge.atLast", Res.string.cmd_mesh_merge_at_last), + ) + } + +/** + * The center title for one pie kind (Blender names its pies the same way). + * + * @param PieMenuKind kind The open pie. + * @return StringResource The localized title. + */ +fun pieMenuTitleFor(kind: PieMenuKind): StringResource = + when (kind) { + PieMenuKind.PivotMode -> Res.string.pie_title_pivot + PieMenuKind.Snap -> Res.string.pie_title_snap + PieMenuKind.UvSnap -> Res.string.pie_title_uv_snap + PieMenuKind.MergeTarget -> Res.string.pie_title_merge + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportRegionOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportRegionOverlay.kt new file mode 100644 index 0000000..1a21c1d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportRegionOverlay.kt @@ -0,0 +1,142 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import org.umamo.edit.EditorSession +import org.umamo.render.ViewportCamera +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawCrosshairGuides +import org.umamo.ui.theme.drawCursor +import org.umamo.ui.theme.drawSelectionBox +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle +import kotlin.math.abs +import kotlin.math.min + +/** A drag shorter than this (px) is treated as a click (just disarm), not a region to frame. */ +private const val REGION_DRAG_THRESHOLD_PX = 3f + +/** + * The Zoom Region overlay (Blender's Shift+B): a mode-agnostic top-level layer over the puppet image that, + * while armed for this area, shows full-viewport crosshair guides and rubber-bands a box; on release it + * frames that box into the viewport ([PuppetViewportService.zoomToRegion]). Mounted above the Edit-mode + * gizmo overlay so it captures the drag in Edit mode too, and self-gated on [EditorSession.zoomRegionArmedArea] + * matching this [areaId] so only the armed area is live - every other area (and the unarmed state) composes + * nothing here and passes pointer input through to the gizmo / navigation layers beneath. + * + * The crosshair cursor and dashed guides are drawn (the OS cursor is hidden while armed), so the affordance + * matches the armed Box-select tool; the two share [drawCrosshairGuides]. + * + * @param String areaId The viewport area this overlay covers. + * @param PuppetViewportService service The render service (for the zoom-to-region call). + * @param EditorSession session The session owning the armed-area flag. + * @param ViewportCamera? camera The area's camera; null (no first fit yet) hides the overlay. + * @param Int widthPx The area width in pixels. + * @param Int heightPx The area height in pixels. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun ViewportRegionOverlay( + areaId: String, + service: PuppetViewportService, + session: EditorSession, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + modifier: Modifier = Modifier, +) { + val armedArea by session.zoomRegionArmedArea.collectAsState() + val overlayColors = LocalUmamoColors.current + if (armedArea != areaId || camera == null) { + return + } + val overlayStyle = selectionOverlayStyle(overlayColors) + + var lastPointer by remember(areaId) { mutableStateOf(Offset.Zero) } + var regionStart by remember(areaId) { mutableStateOf(null) } + var regionCurrent by remember(areaId) { mutableStateOf(null) } + + Box( + modifier = + modifier + .fillMaxSize() + .clipToBounds() + // Hide the OS cursor so only the drawn crosshair shows while the gesture is armed. + .pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + .pointerInput(areaId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + lastPointer = change.position + when (event.type) { + PointerEventType.Press -> + // Right-click cancels the armed gesture; left-click begins the region drag. + if (event.buttons.isSecondaryPressed) { + session.disarmZoomRegion() + } else if (event.buttons.isPrimaryPressed) { + regionStart = change.position + regionCurrent = change.position + change.consume() + } + + PointerEventType.Move -> + if (regionStart != null) { + regionCurrent = change.position + change.consume() + } + + PointerEventType.Release -> { + val start = regionStart + if (start != null) { + val end = change.position + // A real drag frames the box; a sub-threshold click just disarms (framing a + // point would jump to MAX_ZOOM). + if ((end - start).getDistance() > REGION_DRAG_THRESHOLD_PX) { + service.zoomToRegion(areaId, start.x, start.y, end.x, end.y) + } + regionStart = null + regionCurrent = null + session.disarmZoomRegion() + change.consume() + } + } + + else -> {} + } + } + } + }, + ) { + Canvas(modifier = Modifier.fillMaxSize()) { + val start = regionStart + val current = regionCurrent + if (regionStart == null) { + drawCrosshairGuides(lastPointer, Size(widthPx.toFloat(), heightPx.toFloat()), overlayStyle) + } + if (start != null && current != null) { + val topLeft = Offset(min(start.x, current.x), min(start.y, current.y)) + val boxSize = Size(abs(current.x - start.x), abs(current.y - start.y)) + drawSelectionBox(topLeft, boxSize, overlayStyle) + } + drawCursor(LocalUmamoCursors.crosshair, lastPointer) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportSettings.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportSettings.kt new file mode 100644 index 0000000..49bbd49 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportSettings.kt @@ -0,0 +1,43 @@ +package org.umamo.ui.viewport + +/** + * The settings keys and bundled defaults for the viewport interaction settings: the wheel-zoom + * increments, the grid, and the rendering toggles. The overlay colors live in + * [ViewportColorSettings]. The defaults are kept in lockstep with defaultSettings.json (the + * merged-settings baseline); these constants are the Kotlin-side fallback for a missing or + * unparseable value, shared by the viewport binding and the preferences window so neither duplicates + * key literals. + */ +internal object ViewportSettings { + const val ZOOM_STEP_KEY = "viewport.zoomStepPercent" + const val ZOOM_STEP_COARSE_KEY = "viewport.zoomStepCoarsePercent" + const val GRID_SCALE_KEY = "viewport.grid.scale" + const val GRID_SUBDIVISIONS_KEY = "viewport.grid.subdivisions" + const val SUPERSAMPLE_KEY = "viewport.rendering.supersample" + const val SUPERSAMPLE_WHILE_RESIZING_KEY = "viewport.rendering.supersampleWhileResizing" + + const val ZOOM_STEP_DEFAULT = 1.0 + const val ZOOM_STEP_COARSE_DEFAULT = 5.0 + + /** Supersampling on by default; off renders everything at 1x (the weak-GPU escape hatch). */ + const val SUPERSAMPLE_DEFAULT = true + + /** On by default: frames rendered while an area is actively resizing keep the supersample. */ + const val SUPERSAMPLE_WHILE_RESIZING_DEFAULT = true + + const val GRID_SCALE_DEFAULT = 100.0 + const val GRID_SUBDIVISIONS_DEFAULT = 10 + + /** + * The commit clamp for the zoom-step preference fields: 0.1 % (ultra-fine) up to 100 % (a + * doubling per wheel notch). This bounds the per-notch step only; the camera's own zoom range + * clamp is separate and still applies downstream. + */ + val ZOOM_STEP_RANGE = 0.1f..100f + + /** The commit clamp for the grid major spacing (world units): 1 up to 100000, so the grid stays finite. */ + val GRID_SCALE_RANGE = 1f..100_000f + + /** The commit clamp for the grid subdivision count: 1 (no minor lines) up to 100 per major cell. */ + val GRID_SUBDIVISIONS_RANGE = 1..100 +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportWarpLatticeOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportWarpLatticeOverlay.kt new file mode 100644 index 0000000..bf72124 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/viewport/ViewportWarpLatticeOverlay.kt @@ -0,0 +1,747 @@ +package org.umamo.ui.viewport + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isAltPressed +import androidx.compose.ui.input.pointer.isPrimaryPressed +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.AxisAlignedBounds +import org.umamo.edit.BoundsHandle +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshTransforms +import org.umamo.edit.NoticePlacement +import org.umamo.edit.RotationAngleTracker +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TransformPivotGroup +import org.umamo.edit.commitWarpLattice +import org.umamo.edit.eligibleTransformDrawables +import org.umamo.edit.scaledByHandleDrag +import org.umamo.edit.selectionBounds +import org.umamo.edit.withWarpLatticeCaptured +import org.umamo.render.ViewportCamera +import org.umamo.render.eval.DrawableSpaceMapping +import org.umamo.render.eval.warpLatticeLocalAt +import org.umamo.render.eval.warpLatticeSpaceMapping +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawRubberBand +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.theme.selectionOverlayStyle +import kotlin.math.hypot +import kotlin.math.max +import kotlin.math.min + +/** + * Object-mode warp lattice editor: marquee / click select control points, freehand drag, a Photoshop-style + * free-transform marquee (drag the eight AABB handles to scale; Shift keeps aspect, Alt scales from center), + * modal G / R about the selection centroid, and commit into the Geometry key at the live pose on the targeted + * parameter. Lattice edges draw as Catmull-Rom curves (Cubism-style bezier look) through the points. + * Scale (S) uses the same handle marquee rather than Blender's distance-from-pivot gesture - distance scale + * fights lattice editing. + * + * Samples the lattice from [liveParams] (the same pose the renderer scrubs with), not [EditorSession.pose], + * so the overlay interpolates between keys while a parameter drag is in flight - session.pose only moves + * on scrub commit. + * + * @param String areaId The viewport area. + * @param PuppetViewportService service Live model preview pushes. + * @param EditorSession session Selection, targeted parameter, modal operators, undo. + * @param LiveParams liveParams The scrub pose the viewport renders with. + * @param ViewportCamera? camera World↔screen projection. + * @param Int widthPx Area width in pixels. + * @param Int heightPx Area height in pixels. + * @param Modifier modifier Layout modifier. + */ +@Composable +fun ViewportWarpLatticeOverlay( + areaId: String, + service: PuppetViewportService, + session: EditorSession, + liveParams: LiveParams, + camera: ViewportCamera?, + widthPx: Int, + heightPx: Int, + modifier: Modifier = Modifier, +) { + val mode by session.mode.collectAsState() + val selection by session.selection.collectAsState() + val model by session.model.collectAsState() + // Live scrub pose - reading observed recomposes every preview frame, matching the mesh deformation. + val poseMap = liveParams.observed + val activeObjectOperator by session.activeObjectOperator.collectAsState() + val axisConstraint by session.axisConstraint.collectAsState() + val colors = LocalUmamoColors.current + val overlayStyle = selectionOverlayStyle(colors) + + val warpId = + when (val active = selection.active) { + is SelectionTarget.Deformer -> { + val deformer = model.deformers.firstOrNull { candidate -> candidate.id == active.id } + if (deformer is Deformer.Warp) active.id else null + } + else -> null + } + + // Draw whenever a warp is the active selection (Object or Edit): create / outliner pick must still + // show the lattice. Modal G / S / R and point drags stay Object-only below via [armed] / mode checks. + if (warpId == null || camera == null || widthPx <= 0 || heightPx <= 0) { + return + } + + val warp = model.deformers.firstOrNull { candidate -> candidate.id == warpId } as? Deformer.Warp ?: return + // Recompute every scrub frame - do not remember() on the pose map; mid-drag previews must blend. + val localPoints = warpLatticeLocalAt(model, poseMap, warpId) + val mapping = warpLatticeSpaceMapping(model, poseMap, warpId) + if (localPoints == null || mapping == null) { + return + } + + val worldPoints = mapping.localToWorld(localPoints) + val size = IntSize(widthPx, heightPx) + val pointCount = localPoints.size / 2 + val columns = warp.columns + val rows = warp.rows + + var selected by remember(warpId) { mutableStateOf(setOf()) } + var pointDrag by remember { mutableStateOf(null) } + var scaleBoxDrag by remember { mutableStateOf(null) } + var boxStart by remember { mutableStateOf(null) } + var boxCurrent by remember { mutableStateOf(null) } + val gesture = remember(areaId) { ModalGestureState() } + + val ownedOperator = activeObjectOperator?.takeIf { operator -> operator.areaId == areaId } + // Scale uses the free-transform marquee (always visible below), not the Blender distance modal. + val modalOperator = ownedOperator?.takeIf { operator -> operator.kind != MeshOperatorKind.Scale } + val scaleArmed = ownedOperator?.kind == MeshOperatorKind.Scale + val armed = modalOperator != null + + val liveCamera = rememberUpdatedState(camera) + val liveSize = rememberUpdatedState(size) + val liveWorld = rememberUpdatedState(worldPoints) + val liveLocal = rememberUpdatedState(localPoints) + val liveMapping = rememberUpdatedState(mapping) + val liveSelected = rememberUpdatedState(selected) + val livePointDrag = rememberUpdatedState(pointDrag) + val liveScaleBoxDrag = rememberUpdatedState(scaleBoxDrag) + val liveModel = rememberUpdatedState(model) + val livePose = rememberUpdatedState(poseMap) + val liveWarpId = rememberUpdatedState(warpId) + val liveAxis = rememberUpdatedState(axisConstraint) + + fun pushPreview(local: FloatArray) { + val owner = KeyformOwner.Deformer(liveWarpId.value) + val parameterId = session.parameterSelection.value.active + val parameter = + parameterId?.let { id -> liveModel.value.parameters.firstOrNull { candidate -> candidate.id == id } } + if (parameter == null) { + session.emitNotice("notice.keyform.noParameter", NoticePlacement.NearCursor) + return + } + val folded = + liveModel.value.withWarpLatticeCaptured(owner, parameter, livePose.value, WarpLatticeForm(local.copyOf())) + service.setModel(folded) + } + + fun commitLocal(local: FloatArray) { + session.commitWarpLattice( + KeyformOwner.Deformer(liveWarpId.value), + WarpLatticeForm(local.copyOf()), + livePose.value, + ) + service.setModel(session.model.value) + } + + fun driveModalPreview(kind: MeshOperatorKind, virtualPointer: Offset, activeCamera: ViewportCamera, areaSize: IntSize): Boolean { + val start = gesture.gestureStart ?: return false + val capture = gesture.capture ?: return false + val frame = TransformGestureFrame(capture.pivot, start, virtualPointer, liveAxis.value, activeCamera, areaSize) + val parameters = gestureParameters(kind, frame, capture.rotationTracker) + val group = TransformPivotGroup(capture.indices, capture.pivot.first, capture.pivot.second) + val transformedWorld = applyOperator(kind, capture.baseWorld, listOf(group), parameters, emptyMap()) + val previewLocal = capture.mapping.worldToLocal(transformedWorld, capture.baseLocal, capture.indices) + gesture.capture = capture.copy(previewWorld = transformedWorld, previewLocal = previewLocal) + pushPreview(previewLocal) + return true + } + + fun confirmModal() { + val capture = gesture.capture ?: return + commitLocal(capture.previewLocal) + session.clearObjectOperator() + } + + fun driveScaleBox( + drag: WarpLatticeScaleBoxDrag, + worldX: Float, + worldY: Float, + uniform: Boolean, + fromCenter: Boolean, + ): WarpLatticeScaleBoxDrag { + val previewWorld = + scaledByHandleDrag( + drag.baseWorld, + drag.movingIndices, + drag.startBounds, + drag.handle, + worldX, + worldY, + uniform = uniform, + fromCenter = fromCenter, + ) + val previewLocal = liveMapping.value.worldToLocal(previewWorld, drag.baseLocal, drag.movingIndices) + pushPreview(previewLocal) + return drag.copy(previewWorld = previewWorld, previewLocal = previewLocal) + } + + val modalTarget = + object : ModalTransformTarget { + override fun drivePreview(virtualPointer: Offset, camera: ViewportCamera, size: IntSize): Boolean { + val operator = + session.activeObjectOperator.value?.takeIf { + it.areaId == areaId && it.kind != MeshOperatorKind.Scale + } ?: return false + return driveModalPreview(operator.kind, virtualPointer, camera, size) + } + + override fun confirm() { + confirmModal() + } + + override fun cancel() { + session.clearObjectOperator() + } + } + + LaunchedEffect(modalOperator, selected, worldPoints, localPoints, mapping) { + val operator = modalOperator + if (operator == null) { + if (gesture.end()) { + service.setModel(session.model.value) + } + return@LaunchedEffect + } + val indices = selected.ifEmpty { (0 until pointCount).toSet() } + if (indices.isEmpty()) { + session.clearObjectOperator() + return@LaunchedEffect + } + val pivot = MeshTransforms.medianPivot(worldPoints, indices) + gesture.begin( + WarpLatticeModalCapture( + indices = indices, + baseLocal = localPoints.copyOf(), + baseWorld = worldPoints.copyOf(), + previewLocal = localPoints.copyOf(), + previewWorld = worldPoints.copyOf(), + pivot = pivot, + mapping = mapping, + rotationTracker = RotationAngleTracker(), + ), + gesture.lastPointer, + ) + } + + LaunchedEffect(session) { + collectModalConfirmRequests(session, { + val operator = session.activeObjectOperator.value + operator?.areaId == areaId && operator.kind != MeshOperatorKind.Scale + }) { + confirmModal() + } + } + + // Enter while Scale is armed (handle marquee) just clears the arming - handle drags commit on release. + LaunchedEffect(session) { + collectModalConfirmRequests(session, { + val operator = session.activeObjectOperator.value + operator?.areaId == areaId && operator.kind == MeshOperatorKind.Scale + }) { + session.clearObjectOperator() + } + } + + // Reverse Positions H/V: pairwise-swap one axis of selected lattice CPs (Object mode). + LaunchedEffect(session, areaId) { + session.viewportMirrorRequests.collect { request -> + if (request.areaId != areaId || session.mode.value != EditorMode.Object) { + return@collect + } + if (eligibleTransformDrawables(session.selection.value, session.model.value) != null) { + return@collect + } + val world = liveWorld.value + val count = world.size / 2 + val ordered = liveSelected.value.ifEmpty { (0 until count).toSet() }.sorted() + if (ordered.size < 2) { + return@collect + } + val local = liveLocal.value + val space = liveMapping.value + val swappedWorld = + MeshTransforms.reverseSwapPositions(world, ordered, horizontal = request.mirrorHorizontal) + val swappedLocal = space.worldToLocal(swappedWorld, local, ordered.toSet()) + commitLocal(swappedLocal) + } + } + + val displayWorld = scaleBoxDrag?.previewWorld ?: pointDrag?.previewWorld ?: gesture.capture?.previewWorld ?: worldPoints + val coverIndices = selected.ifEmpty { (0 until pointCount).toSet() } + val transformBounds = + scaleBoxDrag?.let { drag -> selectionBounds(drag.previewWorld, drag.movingIndices) } + ?: selectionBounds(displayWorld, coverIndices) + val latticeColor = colors.outlinerDeformTint + val selectedColor = Color(0xFFFFCC66) + + val interactive = mode == EditorMode.Object + Box( + modifier + .fillMaxSize() + .clipToBounds() + .onGloballyPositioned { coordinates -> gesture.areaScreenOrigin = coordinates.positionOnScreen() } + .then( + if (armed) { + Modifier.pointerHoverIcon(hiddenPointerIcon(), overrideDescendants = true) + } else { + Modifier + }, + ) + .drawBehind { + drawLatticeCurves(displayWorld, columns, rows, pointCount, camera, size, latticeColor) + for (index in 0 until pointCount) { + val screen = worldToScreen(displayWorld[index * 2], displayWorld[index * 2 + 1], camera, size) + val fill = if (index in selected) selectedColor else latticeColor + drawCircle(fill, radius = 5f, center = screen) + drawCircle(Color.Black.copy(alpha = 0.55f), radius = 5f, center = screen, style = Stroke(width = 1f)) + } + if (interactive) { + drawFreeTransformBox( + bounds = transformBounds, + camera = camera, + size = size, + lineColor = colors.viewportMarquee, + ) + drawRubberBand(boxStart, boxCurrent, overlayStyle) + val capture = gesture.capture + if (modalOperator != null && capture != null) { + drawModalTransformHud( + axisConstraint = axisConstraint, + pivotScreen = worldToScreen(capture.pivot.first, capture.pivot.second, camera, size), + virtualPointer = gesture.cursorWrap.virtualPointer(gesture.lastPointer), + realPointer = gesture.lastPointer, + viewport = Size(widthPx.toFloat(), heightPx.toFloat()), + lineColor = colors.viewportMarquee, + pointerCursor = LocalUmamoCursors.nsewScroll, + proportionalRadiusPx = null, + ) + } + } + } + .then( + if (!interactive) { + Modifier + } else { + modifier.pointerInput(areaId, warpId) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + gesture.lastPointer = change.position + val cameraNow = liveCamera.value + val sizeNow = liveSize.value + val latched = session.activeObjectOperator.value + if (latched != null && latched.areaId != areaId) { + continue + } + // Grab / Rotate keep the Blender distance modal; Scale uses the handle marquee below. + if (latched != null && latched.areaId == areaId && latched.kind != MeshOperatorKind.Scale) { + gesture.lastPointer = + gesture.modalController.handleEvent( + event, + change, + modalTarget, + cameraNow, + sizeNow, + gesture.areaScreenOrigin, + ) + continue + } + + val pos = change.position + when (event.type) { + PointerEventType.Press -> { + if (event.buttons.isSecondaryPressed) { + if (latched?.kind == MeshOperatorKind.Scale) { + session.clearObjectOperator() + change.consume() + } + continue + } + if (!event.buttons.isPrimaryPressed) { + continue + } + change.consume() + val cover = liveSelected.value.ifEmpty { (0 until liveWorld.value.size / 2).toSet() } + val bounds = selectionBounds(liveWorld.value, cover) + val handleHit = hitFreeTransformHandle(pos, bounds, cameraNow, sizeNow) + if (handleHit != null) { + boxStart = null + boxCurrent = null + pointDrag = null + scaleBoxDrag = + WarpLatticeScaleBoxDrag( + handle = handleHit, + movingIndices = cover, + startBounds = bounds, + baseLocal = liveLocal.value.copyOf(), + baseWorld = liveWorld.value.copyOf(), + previewWorld = liveWorld.value.copyOf(), + previewLocal = liveLocal.value.copyOf(), + ) + continue + } + val hit = nearestControlPoint(pos, liveWorld.value, cameraNow, sizeNow) + if (hit != null) { + boxStart = null + boxCurrent = null + scaleBoxDrag = null + val nextSelected = + if (event.keyboardModifiers.isShiftPressed) { + if (hit in liveSelected.value) liveSelected.value - hit else liveSelected.value + hit + } else if (hit in liveSelected.value && liveSelected.value.isNotEmpty()) { + liveSelected.value + } else { + setOf(hit) + } + selected = nextSelected + val moving = if (hit in nextSelected) nextSelected else setOf(hit) + val (worldX, worldY) = screenToWorld(pos.x, pos.y, cameraNow, sizeNow) + pointDrag = + WarpLatticeDrag( + startWorldX = worldX, + startWorldY = worldY, + movingIndices = moving, + baseLocal = liveLocal.value.copyOf(), + baseWorld = liveWorld.value.copyOf(), + previewWorld = liveWorld.value.copyOf(), + previewLocal = liveLocal.value.copyOf(), + ) + } else { + pointDrag = null + scaleBoxDrag = null + boxStart = pos + boxCurrent = pos + } + } + + PointerEventType.Move -> { + val activeScale = liveScaleBoxDrag.value + if (activeScale != null && event.buttons.isPrimaryPressed) { + change.consume() + val (worldX, worldY) = screenToWorld(pos.x, pos.y, cameraNow, sizeNow) + scaleBoxDrag = + driveScaleBox( + activeScale, + worldX, + worldY, + uniform = event.keyboardModifiers.isShiftPressed, + fromCenter = event.keyboardModifiers.isAltPressed, + ) + continue + } + val activeDrag = livePointDrag.value + if (activeDrag != null && event.buttons.isPrimaryPressed) { + change.consume() + val (worldX, worldY) = screenToWorld(pos.x, pos.y, cameraNow, sizeNow) + val deltaX = worldX - activeDrag.startWorldX + val deltaY = worldY - activeDrag.startWorldY + val previewWorld = activeDrag.baseWorld.copyOf() + for (index in activeDrag.movingIndices) { + val coord = index * 2 + if (coord + 1 >= previewWorld.size) { + continue + } + previewWorld[coord] = activeDrag.baseWorld[coord] + deltaX + previewWorld[coord + 1] = activeDrag.baseWorld[coord + 1] + deltaY + } + val previewLocal = + liveMapping.value.worldToLocal(previewWorld, activeDrag.baseLocal, activeDrag.movingIndices) + pointDrag = activeDrag.copy(previewWorld = previewWorld, previewLocal = previewLocal) + pushPreview(previewLocal) + continue + } + if (boxStart != null && event.buttons.isPrimaryPressed) { + change.consume() + boxCurrent = pos + } + } + + PointerEventType.Release -> { + val activeScale = liveScaleBoxDrag.value + if (activeScale != null) { + change.consume() + scaleBoxDrag = null + commitLocal(activeScale.previewLocal) + if (session.activeObjectOperator.value?.kind == MeshOperatorKind.Scale) { + session.clearObjectOperator() + } + continue + } + val activeDrag = livePointDrag.value + if (activeDrag != null) { + change.consume() + pointDrag = null + commitLocal(activeDrag.previewLocal) + continue + } + val start = boxStart + val end = boxCurrent ?: pos + if (start != null) { + change.consume() + boxStart = null + boxCurrent = null + if ((end - start).getDistance() > SELECT_DRAG_THRESHOLD_PX) { + val hit = + controlPointsInBox(start, end, liveWorld.value, cameraNow, sizeNow) + selected = + if (event.keyboardModifiers.isShiftPressed) { + liveSelected.value + hit + } else { + hit + } + } else if (!event.keyboardModifiers.isShiftPressed) { + selected = emptySet() + } + } + } + + else -> Unit + } + } + } + } + }, + ), + ) +} + +/** + * Modal G / S / R capture for a warp lattice selection. + * + * @property Set indices Control points covered by the gesture. + * @property FloatArray baseLocal Lattice-local points at latch. + * @property FloatArray baseWorld World points at latch. + * @property FloatArray previewLocal Live lattice-local preview. + * @property FloatArray previewWorld Live world preview. + * @property Pair pivot Selection centroid in world space. + * @property DrawableSpaceMapping mapping Parent-chain world↔local. + * @property RotationAngleTracker rotationTracker Rotate accumulator. + */ +private data class WarpLatticeModalCapture( + val indices: Set, + val baseLocal: FloatArray, + val baseWorld: FloatArray, + val previewLocal: FloatArray, + val previewWorld: FloatArray, + val pivot: Pair, + val mapping: DrawableSpaceMapping, + val rotationTracker: RotationAngleTracker, +) + +/** + * Freehand point drag (non-modal translate). + * + * @property Float startWorldX World x where the drag began. + * @property Float startWorldY World y where the drag began. + * @property Set movingIndices Control-point indices being translated. + * @property FloatArray baseLocal Lattice-local points at gesture start. + * @property FloatArray baseWorld World points at gesture start. + * @property FloatArray previewWorld Current world preview. + * @property FloatArray previewLocal Current lattice-local preview. + */ +private data class WarpLatticeDrag( + val startWorldX: Float, + val startWorldY: Float, + val movingIndices: Set, + val baseLocal: FloatArray, + val baseWorld: FloatArray, + val previewWorld: FloatArray, + val previewLocal: FloatArray, +) + +/** + * Photoshop-style free-transform scale of lattice control points via an AABB handle. + * + * @property BoundsHandle handle The handle under the pointer. + * @property Set movingIndices Control points covered by the marquee. + * @property AxisAlignedBounds startBounds Selection AABB frozen at press. + * @property FloatArray baseLocal Lattice-local points at gesture start. + * @property FloatArray baseWorld World points at gesture start. + * @property FloatArray previewWorld Current world preview. + * @property FloatArray previewLocal Current lattice-local preview. + */ +private data class WarpLatticeScaleBoxDrag( + val handle: BoundsHandle, + val movingIndices: Set, + val startBounds: AxisAlignedBounds, + val baseLocal: FloatArray, + val baseWorld: FloatArray, + val previewWorld: FloatArray, + val previewLocal: FloatArray, +) + +/** + * Draws each lattice row and column as a Catmull-Rom curve through its control points. + * + * @param FloatArray world Interleaved world control points. + * @param Int columns Warp columns (cells). + * @param Int rows Warp rows (cells). + * @param Int pointCount Number of control points. + * @param ViewportCamera camera Projection. + * @param IntSize size Overlay size. + * @param Color color Stroke color. + */ +private fun DrawScope.drawLatticeCurves( + world: FloatArray, + columns: Int, + rows: Int, + pointCount: Int, + camera: ViewportCamera, + size: IntSize, + color: Color, +) { + val cols = columns + 1 + val rowCount = rows + 1 + + fun screenPoint(index: Int): Offset? { + if (index < 0 || index >= pointCount) { + return null + } + return worldToScreen(world[index * 2], world[index * 2 + 1], camera, size) + } + for (row in 0 until rowCount) { + val points = (0 until cols).mapNotNull { col -> screenPoint(row * cols + col) } + drawCatmullRom(points, color) + } + for (col in 0 until cols) { + val points = (0 until rowCount).mapNotNull { row -> screenPoint(row * cols + col) } + drawCatmullRom(points, color) + } +} + +/** + * Strokes a Catmull-Rom spline through [points] (converted to cubic beziers). + * + * @param List points Screen-space samples along one lattice edge chain. + * @param Color color Stroke color. + */ +private fun DrawScope.drawCatmullRom(points: List, color: Color) { + when (points.size) { + 0, 1 -> return + 2 -> drawLine(color, points[0], points[1], strokeWidth = 1.5f, cap = StrokeCap.Round) + else -> { + val path = Path() + path.moveTo(points[0].x, points[0].y) + for (index in 0 until points.lastIndex) { + val p0 = points[max(index - 1, 0)] + val p1 = points[index] + val p2 = points[index + 1] + val p3 = points[min(index + 2, points.lastIndex)] + val c1 = Offset(p1.x + (p2.x - p0.x) / 6f, p1.y + (p2.y - p0.y) / 6f) + val c2 = Offset(p2.x - (p3.x - p1.x) / 6f, p2.y - (p3.y - p1.y) / 6f) + path.cubicTo(c1.x, c1.y, c2.x, c2.y, p2.x, p2.y) + } + drawPath(path, color, style = Stroke(width = 1.5f, cap = StrokeCap.Round)) + } + } +} + +/** + * Control points whose screen positions fall inside the axis-aligned box from [start] to [end]. + * + * @param Offset start Box corner. + * @param Offset end Opposite corner. + * @param FloatArray worldPoints Interleaved world control points. + * @param ViewportCamera camera Projection. + * @param IntSize size Overlay size. + * @return Set Indices inside the box. + */ +private fun controlPointsInBox( + start: Offset, + end: Offset, + worldPoints: FloatArray, + camera: ViewportCamera, + size: IntSize, +): Set { + val left = min(start.x, end.x) + val right = max(start.x, end.x) + val top = min(start.y, end.y) + val bottom = max(start.y, end.y) + val hit = LinkedHashSet() + val pointCount = worldPoints.size / 2 + for (index in 0 until pointCount) { + val screen = worldToScreen(worldPoints[index * 2], worldPoints[index * 2 + 1], camera, size) + if (screen.x in left..right && screen.y in top..bottom) { + hit.add(index) + } + } + return hit +} + +/** + * The nearest control point under [screenPos] within [HIT_RADIUS_PX], or null when none. + * + * @param Offset screenPos Pointer position in overlay pixels. + * @param FloatArray worldPoints Interleaved world control points. + * @param ViewportCamera camera Projection. + * @param IntSize size Overlay size. + * @return Int? Control-point index, or null. + */ +private fun nearestControlPoint( + screenPos: Offset, + worldPoints: FloatArray, + camera: ViewportCamera, + size: IntSize, +): Int? { + var bestIndex = -1 + var bestDistance = HIT_RADIUS_PX + val pointCount = worldPoints.size / 2 + for (index in 0 until pointCount) { + val screen = worldToScreen(worldPoints[index * 2], worldPoints[index * 2 + 1], camera, size) + val distance = hypot(screen.x - screenPos.x, screen.y - screenPos.y) + if (distance <= bestDistance) { + bestDistance = distance + bestIndex = index + } + } + return bestIndex.takeIf { it >= 0 } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaCameraHub.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaCameraHub.kt new file mode 100644 index 0000000..1d0ce7e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaCameraHub.kt @@ -0,0 +1,51 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.ui.viewport.CameraController + +/** + * The registry from a camera-bearing area id to its live [CameraController]: each 2D viewport and UV + * editor space registers its ops for its area's lifetime, and the shell's view commands resolve the + * hovered area here at dispatch time. Both surfaces drive the same per-area render camera, so one hub + * serves them uniformly - the resolver is a single opsFor(hoveredArea) lookup with no per-space branch, + * and a future camera-bearing space joins simply by registering its own controller. + * + * カメラを持つエリア id からカメラ操作への台帳。2D ビューポートと UV エディタの各空間が登録し、 + * ビューコマンドがディスパッチ時にホバー中のエリアの分を解決する。 + */ +internal class AreaCameraHub { + private val opsByArea = mutableMapOf() + + /** + * Registers one area's camera controller (replacing any prior registration for the id). + * + * @param String areaId The camera-bearing leaf's area id. + * @param CameraController ops The area's live camera controller. + */ + fun register(areaId: String, ops: CameraController) { + opsByArea[areaId] = ops + } + + /** + * Removes one area's registration (the area died or switched space). + * + * @param String areaId The camera-bearing leaf's area id. + */ + fun unregister(areaId: String) { + opsByArea.remove(areaId) + } + + /** + * The live controller for an area, or null when none is registered under the id. + * + * @param String areaId The camera-bearing leaf's area id. + * @return CameraController? The area's camera controller, or null. + */ + fun opsFor(areaId: String): CameraController? = opsByArea[areaId] +} + +/** + * The shell's area camera hub, or null outside an editor shell (previews, tests). Camera-bearing + * spaces register their areas; the view commands resolve the hovered area at dispatch. + */ +internal val LocalAreaCameraHub = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaDragController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaDragController.kt new file mode 100644 index 0000000..9b335e4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaDragController.kt @@ -0,0 +1,336 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.unit.dp +import kotlin.math.abs + +/** The drag distance a corner must travel inside its own area before a split is armed and its axis locked. */ +internal val SPLIT_ARM_DISTANCE = 24.dp + +/** Which corner of a leaf area a drag was started from. */ +enum class AreaCorner { + TopLeft, + TopRight, + BottomLeft, + BottomRight, +} + +/** + * The live state of an in-flight corner drag. All coordinates are content-local pixels (relative to + * the shell content Box, the one shared space the leaf rects and the overlay also use). Null on the + * controller means no drag is active. + * + * A drag resolves to one outcome at any moment: a valid JOIN (over a different aligned-sibling leaf), a + * valid DOCK (over a different non-aligned leaf - the source relocates to a workspace edge), a valid SPLIT + * (back inside the source area, dragged past the arm distance, axis locked), or none (a no-op on release). + * + * 進行中のコーナードラッグの状態。座標はシェル内容ボックス基準のローカルピクセル。結合・ドック・分割・無効。 + * + * @property String sourceId The leaf the drag started from (the survivor on a join, the docked/split leaf). + * @property AreaCorner startCorner The corner grabbed. + * @property Offset startPointer Where the drag began, content-local (for the split arm distance and axis). + * @property Offset pointer The current pointer position, content-local. + * @property String? targetId The leaf currently under the pointer, or null if over none. + * @property Boolean validJoin True when releasing now would perform a valid aligned-sibling join. + * @property Boolean validDock True when releasing now would dock the source to a workspace edge (non-aligned). + * @property DockEdge? dockEdge The workspace edge the source would dock to (from the cursor's zone in the target). + * @property Float dockRatio The docked strip's fraction of the perpendicular axis (keeps the source's size). + * @property SplitOrientation? splitOrientation The locked split axis once armed (persists for the drag), else null. + * @property Float splitRatio The divider fraction (original side) when splitting, following the cursor. + * @property Boolean validSplit True when releasing now would split the source area. + */ +data class AreaDragState( + val sourceId: String, + val startCorner: AreaCorner, + val startPointer: Offset, + val pointer: Offset, + val targetId: String?, + val validJoin: Boolean, + val validDock: Boolean, + val dockEdge: DockEdge?, + val dockRatio: Float, + val splitOrientation: SplitOrientation?, + val splitRatio: Float, + val validSplit: Boolean, +) + +/** The docked strip's fraction of the axis when the source's own size cannot be measured. */ +private const val DEFAULT_DOCK_FRACTION = 0.4f + +/** + * Shared, cross-area state for the corner-drag area gesture, held once per shell and exposed through + * [LocalAreaDragController]. It owns three things the gesture needs but no single leaf has: every + * leaf's on-screen rectangle (content-local), the current tree root (to test sibling-ness), and the + * in-flight [dragState] the overlay renders. It is a plain holder (not a composable); its state is + * Compose snapshot state so reads in the overlay recompose on drag moves. + * + * The gesture itself lives in the corner hotspot (Compose can't hand an in-flight gesture to the shell + * overlay): the corner calls [beginDrag] / [updateDrag] / [endDrag], and the shell applies the returned + * command. [cancelDrag] backs the Escape key. Dragging into a different aligned sibling joins; dragging + * back inside the source area (past [splitThresholdPx]) splits it. + * + * コーナードラッグによるエリア操作の共有状態。各葉の矩形・現在のツリー・進行中ドラッグを保持する。 + */ +@Stable +class AreaDragController { + // Content-local rect per leaf id; written by each AreaLeaf's onGloballyPositioned, read by the overlay. + private val bounds = mutableStateMapOf() + + // The shell content Box's coordinates (the shared space) and the current tree root, both pushed by the + // shell. Plain fields: read at gesture time, not observed for recomposition. + var contentCoords: LayoutCoordinates? = null + var currentRoot: AreaNode? = null + + // The arm distance in px (the shell sets a density-correct value); below it a split is not yet armed. + var splitThresholdPx: Float = 0f + + var dragState by mutableStateOf(null) + private set + + /** Whether a corner drag is currently in flight (used to gate the Escape-to-cancel key). */ + val isDragging: Boolean + get() = dragState != null + + /** + * Records (or clears) a leaf's content-local rectangle. Called from each leaf's layout callback. + * + * @param String areaId The leaf id. + * @param Rect rect The leaf's bounds in content-local space. + */ + fun putBounds(areaId: String, rect: Rect) { + bounds[areaId] = rect + } + + /** + * Drops a leaf's rectangle when the leaf leaves composition (e.g. it was consumed by a join). + * + * @param String areaId The leaf id to forget. + */ + fun removeBounds(areaId: String) { + bounds.remove(areaId) + } + + /** + * Returns a leaf's content-local rectangle, or null if it has not been measured. A snapshot read, + * so the overlay recomposes when the rect changes. + * + * @param String areaId The leaf id. + * @return Rect? The leaf's bounds, or null. + */ + fun boundsOf(areaId: String): Rect? = bounds[areaId] + + /** + * Begins a corner drag from [sourceId]'s [corner] at the content-local [pointer]. + * + * @param String sourceId The leaf the drag starts from. + * @param AreaCorner corner The grabbed corner. + * @param Offset pointer The starting pointer position, content-local. + */ + fun beginDrag(sourceId: String, corner: AreaCorner, pointer: Offset) { + // startPointer == pointer and no locked axis yet, so a split cannot arm until the pointer travels. + dragState = resolve(sourceId, corner, pointer, pointer, lockedOrientation = null) + } + + /** + * Updates the in-flight drag to a new pointer position, recomputing the hovered target, join validity, + * and split preview. Carries the locked split axis forward so it does not flip mid-drag. A no-op if + * no drag is active (e.g. it was cancelled by Escape). + * + * @param Offset pointer The current pointer position, content-local. + */ + fun updateDrag(pointer: Offset) { + val active = dragState ?: return + dragState = resolve(active.sourceId, active.startCorner, active.startPointer, pointer, active.splitOrientation) + } + + /** + * Ends the drag, always clearing the state. Returns the command to apply: a join when released over a + * valid aligned-sibling target, a split when released inside the armed source area, else null. + * + * @return AreaCommand? The structural edit to apply, or null. + */ + fun endDrag(): AreaCommand? { + val active = dragState + dragState = null + if (active == null) { + return null + } + val target = active.targetId + if (active.validJoin && target != null) { + return AreaCommand.JoinAreas(survivorId = active.sourceId, consumedId = target) + } + val edge = active.dockEdge + if (active.validDock && edge != null) { + return AreaCommand.DockArea(active.sourceId, edge, active.dockRatio) + } + val orientation = active.splitOrientation + if (active.validSplit && orientation != null) { + return AreaCommand.SplitArea(active.sourceId, orientation, active.splitRatio) + } + return null + } + + /** Cancels any in-flight drag without applying a command (backs the Escape key). */ + fun cancelDrag() { + dragState = null + } + + /** + * Builds a drag state for a pointer position: hit-tests the leaf rectangles, then decides whether the + * drag is a valid join (over a different sibling) or a split of the source area (back inside it, armed). + * + * @param String sourceId The drag's source leaf. + * @param AreaCorner corner The grabbed corner. + * @param Offset startPointer Where the drag began, content-local. + * @param Offset pointer The current pointer position, content-local. + * @param SplitOrientation? lockedOrientation The split axis already locked this drag, or null. + * @return AreaDragState The recomputed state. + */ + private fun resolve( + sourceId: String, + corner: AreaCorner, + startPointer: Offset, + pointer: Offset, + lockedOrientation: SplitOrientation?, + ): AreaDragState { + val targetId = bounds.entries.firstOrNull { entry -> entry.value.contains(pointer) }?.key + val overSource = targetId == sourceId + + // Split: back inside the source area. Lock the axis once the pointer has travelled the arm distance + // (from the dominant drag direction), then keep it; the divider follows the cursor along that axis. + var splitOrientation = lockedOrientation + var validSplit = false + var splitRatio = 0.5f + val sourceRect = bounds[sourceId] + if (overSource && sourceRect != null) { + if (splitOrientation == null) { + val delta = pointer - startPointer + if (delta.getDistance() >= splitThresholdPx) { + splitOrientation = + if (abs(delta.x) >= abs(delta.y)) { + SplitOrientation.Horizontal + } else { + SplitOrientation.Vertical + } + } + } + val orientation = splitOrientation + if (orientation != null) { + splitRatio = ratioWithin(sourceRect, pointer, orientation) + validSplit = true + } + } + + // Over a different leaf: an aligned sibling joins (collapse); any other leaf docks the source to a + // workspace edge (the edge is the cursor's zone within the target; the strip keeps the source's size). + val root = currentRoot + val onDifferentLeaf = !overSource && targetId != null && root != null + val aligned = onDifferentLeaf && areDirectSiblings(root, sourceId, targetId) + val validJoin = aligned + var validDock = false + var dockEdge: DockEdge? = null + var dockRatio = DEFAULT_DOCK_FRACTION + if (onDifferentLeaf && !aligned) { + val targetRect = bounds[targetId] + if (targetRect != null) { + dockEdge = edgeZoneOf(targetRect, pointer) + dockRatio = dockStripFractionOf(sourceId, dockEdge) + validDock = true + } + } + + return AreaDragState( + sourceId = sourceId, + startCorner = corner, + startPointer = startPointer, + pointer = pointer, + targetId = targetId, + validJoin = validJoin, + validDock = validDock, + dockEdge = dockEdge, + dockRatio = dockRatio, + splitOrientation = splitOrientation, + splitRatio = splitRatio, + validSplit = validSplit, + ) + } + + /** + * The workspace edge a dock targets, from where [pointer] sits within the target [rect]: the rect is + * cut into four triangles by its diagonals, and the pointer's triangle names the nearest edge. + * + * @param Rect rect The target leaf's rectangle, content-local. + * @param Offset pointer The pointer position, content-local. + * @return DockEdge The nearest edge of the target. + */ + private fun edgeZoneOf(rect: Rect, pointer: Offset): DockEdge { + val fractionX = if (rect.width > 0f) (pointer.x - rect.left) / rect.width else 0.5f + val fractionY = if (rect.height > 0f) (pointer.y - rect.top) / rect.height else 0.5f + val offsetX = fractionX - 0.5f + val offsetY = fractionY - 0.5f + return if (abs(offsetX) >= abs(offsetY)) { + if (offsetX < 0f) DockEdge.Left else DockEdge.Right + } else { + if (offsetY < 0f) DockEdge.Top else DockEdge.Bottom + } + } + + /** + * The docked strip's fraction of the perpendicular axis, taken from the source leaf's current size so + * the docked area keeps roughly its dimensions. Falls back to [DEFAULT_DOCK_FRACTION] if unmeasured. + * + * @param String sourceId The leaf being docked. + * @param DockEdge edge The edge it docks to (selects which axis the strip spans). + * @return Float The clamped strip fraction. + */ + private fun dockStripFractionOf(sourceId: String, edge: DockEdge): Float { + val sourceRect = bounds[sourceId] + val content = contentCoords?.size + if (sourceRect == null || content == null) { + return DEFAULT_DOCK_FRACTION + } + val fraction = + when (edge) { + DockEdge.Top, DockEdge.Bottom -> + if (content.height > 0) sourceRect.height / content.height.toFloat() else DEFAULT_DOCK_FRACTION + DockEdge.Left, DockEdge.Right -> + if (content.width > 0) sourceRect.width / content.width.toFloat() else DEFAULT_DOCK_FRACTION + } + return fraction.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + } + + /** + * The divider fraction (original side) for a split at [pointer] within [rect] along [orientation], + * clamped so neither side falls below [MIN_RATIO]. + * + * @param Rect rect The source area rectangle, content-local. + * @param Offset pointer The pointer position, content-local. + * @param SplitOrientation orientation The split axis. + * @return Float The clamped divider fraction. + */ + private fun ratioWithin(rect: Rect, pointer: Offset, orientation: SplitOrientation): Float { + val fraction = + when (orientation) { + SplitOrientation.Horizontal -> + if (rect.width > 0f) (pointer.x - rect.left) / rect.width else 0.5f + SplitOrientation.Vertical -> + if (rect.height > 0f) (pointer.y - rect.top) / rect.height else 0.5f + } + return fraction.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + } +} + +/** + * The active [AreaDragController] for the shell, or null where no shell provides one (e.g. an isolated + * preview). staticCompositionLocalOf - like [LocalViewportHost] / [LocalSpaceRegistry] - so the + * recursive area tree need not thread the controller through its parameter list. + */ +val LocalAreaDragController = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaDragOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaDragOverlay.kt new file mode 100644 index 0000000..a0b3b61 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaDragOverlay.kt @@ -0,0 +1,199 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import kotlin.math.max +import kotlin.math.min + +/** + * The visual-only highlight for an in-flight corner drag. Reads the shared [controller]'s drag state + * and paints one of three previews: a JOIN box spanning the source and target areas (consumed target + * tinted stronger), a DOCK strip on a workspace edge (source's slot shown vacating), or a SPLIT preview + * of the source area drawn as the two resulting areas. It draws nothing for a no-op or when idle. + * + * Highlights are rounded to the same large corner radius the areas themselves use, and the split preview + * leaves the same gap between its halves that a real [Splitter] leaves between areas, so the preview + * reads as the actual layout it will produce. + * + * No pointer input: the gesture itself lives in the corner hotspot, so this layer must never intercept + * events - it only renders. It is drawn in the shell content Box, the same content-local space the leaf + * rectangles are captured in, so the captured rects map straight to draw coordinates. + * + * コーナードラッグの進行中ハイライト(描画のみ)。結合・ドック・分割を、実際のエリアと同じ角丸と間隔で示す。 + * + * @param AreaDragController controller The shared corner-drag state. + * @param Modifier modifier The layout modifier (fill the content Box). + */ +@Composable +fun AreaDragOverlay(controller: AreaDragController, modifier: Modifier = Modifier) { + val state = controller.dragState + if (state == null) { + return + } + val colors = LocalUmamoColors.current + val accent = colors.accent + val fillWash = colors.dropZoneFill + val emphasisWash = colors.dropZoneEmphasis + val density = LocalDensity.current + val largeShape = LocalUmamoShapes.current.large + val corner = + with(density) { + val radius = if (largeShape is RoundedCornerShape) largeShape.topStart.toPx(Size.Zero, this) else 0f + CornerRadius(radius) + } + val gapPx = with(density) { SPLITTER_THICKNESS.toPx() } + val sourceRect = controller.boundsOf(state.sourceId) + if (state.validJoin && state.targetId != null) { + val targetRect = controller.boundsOf(state.targetId) + if (sourceRect != null && targetRect != null) { + Canvas(modifier = modifier) { drawJoinHighlight(sourceRect, targetRect, accent, fillWash, emphasisWash, corner) } + } + return + } + val dockEdge = state.dockEdge + if (state.validDock && dockEdge != null && sourceRect != null) { + val dockRatio = state.dockRatio + Canvas(modifier = modifier) { drawDockHighlight(sourceRect, dockEdge, dockRatio, accent, fillWash, emphasisWash, corner) } + return + } + val orientation = state.splitOrientation + if (state.validSplit && orientation != null && sourceRect != null) { + val ratio = state.splitRatio + Canvas(modifier = modifier) { drawSplitHighlight(sourceRect, orientation, ratio, accent, fillWash, emphasisWash, corner, gapPx) } + } +} + +/** + * Paints the join preview: a faint fill over the union of the two areas, a stronger fill over the + * consumed target, then a crisp outline around the union (the resulting area). + * + * @param Rect source The surviving (dragged) area. + * @param Rect target The consumed area. + * @param Color accent The accent color (the outline). + * @param Color fillWash The faint wash over the whole affected region. + * @param Color emphasisWash The stronger wash over the part that changes. + * @param CornerRadius corner The corner rounding (matches the areas). + */ +private fun DrawScope.drawJoinHighlight( + source: Rect, + target: Rect, + accent: Color, + fillWash: Color, + emphasisWash: Color, + corner: CornerRadius, +) { + val unionTopLeft = Offset(min(source.left, target.left), min(source.top, target.top)) + val unionSize = + Size( + max(source.right, target.right) - unionTopLeft.x, + max(source.bottom, target.bottom) - unionTopLeft.y, + ) + drawRoundRect(color = fillWash, topLeft = unionTopLeft, size = unionSize, cornerRadius = corner) + drawRoundRect( + color = emphasisWash, + topLeft = target.topLeft, + size = target.size, + cornerRadius = corner, + ) + drawRoundRect( + color = accent, + topLeft = unionTopLeft, + size = unionSize, + cornerRadius = corner, + style = Stroke(width = 2.dp.toPx()), + ) +} + +/** + * Paints the dock preview: a faint "vacating" wash over the source's current slot, then the destination + * strip - a full-span band on the chosen workspace [edge] taking [ratio] of the axis - with a stronger + * fill and a crisp outline. The strip is measured against the whole content area ([DrawScope.size]). + * + * @param Rect source The area being relocated (its slot is vacated). + * @param DockEdge edge The workspace edge the source docks against. + * @param Float ratio The docked strip's fraction of the perpendicular axis. + * @param Color accent The accent color (the outline). + * @param Color fillWash The faint wash over the vacated slot. + * @param Color emphasisWash The stronger wash over the destination strip. + * @param CornerRadius corner The corner rounding (matches the areas). + */ +private fun DrawScope.drawDockHighlight( + source: Rect, + edge: DockEdge, + ratio: Float, + accent: Color, + fillWash: Color, + emphasisWash: Color, + corner: CornerRadius, +) { + drawRoundRect(color = fillWash, topLeft = source.topLeft, size = source.size, cornerRadius = corner) + val width = size.width + val height = size.height + val strip = + when (edge) { + DockEdge.Top -> Rect(left = 0f, top = 0f, right = width, bottom = height * ratio) + DockEdge.Bottom -> Rect(left = 0f, top = height * (1f - ratio), right = width, bottom = height) + DockEdge.Left -> Rect(left = 0f, top = 0f, right = width * ratio, bottom = height) + DockEdge.Right -> Rect(left = width * (1f - ratio), top = 0f, right = width, bottom = height) + } + drawRoundRect(color = emphasisWash, topLeft = strip.topLeft, size = strip.size, cornerRadius = corner) + drawRoundRect(color = accent, topLeft = strip.topLeft, size = strip.size, cornerRadius = corner, style = Stroke(width = 2.dp.toPx())) +} + +/** + * Paints the split preview as the two areas it produces: the original half (faint) and the new half + * (stronger), each rounded and outlined, separated by the same [gapPx] gap a real [Splitter] leaves + * between areas - so the preview reads as the resulting layout rather than a single divided box. + * + * @param Rect source The area being split. + * @param SplitOrientation orientation The split axis. + * @param Float ratio The divider fraction (original side). + * @param Color accent The accent color (the outlines). + * @param Color fillWash The faint wash over the original half. + * @param Color emphasisWash The stronger wash over the new half. + * @param CornerRadius corner The corner rounding (matches the areas). + * @param Float gapPx The gap between the halves (the splitter thickness). + */ +private fun DrawScope.drawSplitHighlight( + source: Rect, + orientation: SplitOrientation, + ratio: Float, + accent: Color, + fillWash: Color, + emphasisWash: Color, + corner: CornerRadius, + gapPx: Float, +) { + val halfGap = gapPx / 2f + val (originalHalf, newHalf) = + when (orientation) { + SplitOrientation.Horizontal -> { + val dividerX = source.left + ratio * source.width + Rect(source.left, source.top, dividerX - halfGap, source.bottom) to + Rect(dividerX + halfGap, source.top, source.right, source.bottom) + } + SplitOrientation.Vertical -> { + val dividerY = source.top + ratio * source.height + Rect(source.left, source.top, source.right, dividerY - halfGap) to + Rect(source.left, dividerY + halfGap, source.right, source.bottom) + } + } + val stroke = 2.dp.toPx() + drawRoundRect(color = fillWash, topLeft = originalHalf.topLeft, size = originalHalf.size, cornerRadius = corner) + drawRoundRect(color = emphasisWash, topLeft = newHalf.topLeft, size = newHalf.size, cornerRadius = corner) + drawRoundRect(color = accent, topLeft = originalHalf.topLeft, size = originalHalf.size, cornerRadius = corner, style = Stroke(width = stroke)) + drawRoundRect(color = accent, topLeft = newHalf.topLeft, size = newHalf.size, cornerRadius = corner, style = Stroke(width = stroke)) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaHeader.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaHeader.kt new file mode 100644 index 0000000..50f0624 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaHeader.kt @@ -0,0 +1,114 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.OverflowRow +import org.umamo.ui.kit.Surface +import org.umamo.ui.theme.LocalUmamoColors + +/** Header bar height - compact, since every area carries one. */ +private val HEADER_HEIGHT = 28.dp + +/** + * The top strip of every leaf area: the area-type dropdown on the left (the agnostic "switch this + * area to any space" control) and the current space's optional [SpaceDescriptor.headerContent] filling + * the rest of the width. Split / close / join live in the area's right-click context menu and the + * corner-drag gesture instead (see [AreaLeaf]), not as buttons in this strip. All structural edits + * emitted from here are [AreaCommand]s through [onCommand], the single choke point the shell routes + * through the action registry - the header never mutates the tree itself. The space slot is resolved + * from the registry so the header itself stays space-agnostic; when a slot exists it OWNS the flexible + * middle region (an [OverflowRow]), so each space arranges its own controls - start-packed by default, + * or centered / end-aligned via its own flexibleSpace gaps - without the header knowing. Narrowing an + * area collapses the controls that no longer fit into the strip's trailing dropdown instead of crushing + * them, so the header stays usable down to the minimum area width. + * + * @param LeafArea area The area this header belongs to. + * @param AreaScope scope The area's stable scope, handed to the space's header content. + * @param Function onCommand Sink for structural edits; this composable itself only emits SwitchSpace. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun AreaHeader(area: LeafArea, scope: AreaScope, onCommand: (AreaCommand) -> Unit, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + Surface(modifier = modifier.fillMaxWidth(), color = colors.headerBackground) { + Row( + modifier = Modifier.fillMaxWidth().height(HEADER_HEIGHT).padding(horizontal = 15.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + AreaTypeDropdown(area = area, onCommand = onCommand) + val headerContent = LocalSpaceRegistry.current.descriptor(area.space).headerContent + if (headerContent != null) { + Spacer(modifier = Modifier.width(8.dp)) + // The slot owns the flexible middle: an OverflowRow over the whole region, so a space's own + // flexibleSpace gaps resolve against all of it (centering, right-alignment) and any control + // that will not fit collapses into the strip's trailing dropdown rather than being crushed. + // The area-type chip stays OUTSIDE it - the header's own control, never collapsible, always + // leftmost. + OverflowRow(modifier = Modifier.weight(1f)) { + headerContent(scope) + } + } else { + Spacer(modifier = Modifier.weight(1f)) + } + } + } +} + +/** + * The area-type selector, Blender-style: the button face is the current space's icon plus a chevron + * that points right while the menu is closed and down while it is open. Clicking opens a menu of every + * registered space, each row an icon plus its localized title. Choosing one emits a SwitchSpace command + * (the area keeps its id, so per-area state such as camera position survives switching away and back; + * the rendered viewport frame itself is torn down and rebuilt fresh - switching away is a genuine + * content change). The chip anatomy is the shared kit [DropdownChip]. + * + * @param LeafArea area The area whose space is being chosen. + * @param Function onCommand Sink for the SwitchSpace command. + */ +@Composable +private fun AreaTypeDropdown(area: LeafArea, onCommand: (AreaCommand) -> Unit) { + val registry = LocalSpaceRegistry.current + val current = registry.descriptor(area.space) + // Resolved in composition because the chip's semantics lambda is not composable. + val currentTitle = stringResource(current.title) + var expanded by remember { mutableStateOf(false) } + // One menu row per registered space; selecting it switches this area and the menu's own dismiss closes + // the popup (so onSelect need not toggle `expanded` itself). + val items = + registry.all.map { descriptor -> + MenuItem.Action( + label = stringResource(descriptor.title), + onSelect = { onCommand(AreaCommand.SwitchSpace(area.id, descriptor.kind)) }, + icon = descriptor.icon, + ) + } + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = currentTitle, + icon = current.icon, + ) { + Menu( + items = items, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaLeaf.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaLeaf.kt new file mode 100644 index 0000000..5b7a244 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaLeaf.kt @@ -0,0 +1,267 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.Surface +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.umamoPointerIcon + +/** The square hit size of each corner drag handle (matches Blender's small corner widget). */ +private val CORNER_HANDLE_SIZE_HEIGHT = 20.dp +private val CORNER_HANDLE_SIZE_WIDTH = 15.dp + +/** + * One leaf area: its header (editor-type dropdown + split/close) above the current space's content, + * with four corner drag handles for the Blender-style join gesture. The content is resolved from + * [LocalSpaceRegistry] by the area's [LeafArea.space]; the [AreaScope] is remembered on the stable area + * id so it (and any future per-space state) survives recomposition. A thin outline delineates the area. + * + * The leaf reports its on-screen rectangle to the shared [LocalAreaDragController] (content-local, the + * one space the drag overlay also uses) and evicts it on dispose, so a leaf consumed by a join cleans + * up after itself. + * + * 1 つの葉エリア。ヘッダ(種別ドロップダウン+分割/閉じる)の下に現在の空間の内容を表示し、四隅に結合 + * 用のドラッグハンドルを置く。自身の矩形を共有コントローラへ報告する。 + * + * @param LeafArea area The area to render. + * @param Function onCommand Sink for the header's and the corner gesture's structural edits. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun AreaLeaf(area: LeafArea, onCommand: (AreaCommand) -> Unit, modifier: Modifier = Modifier) { + val registry = LocalSpaceRegistry.current + // The open document's holder owns the scope, so a workspace tab switch - which disposes this leaf - does not + // cost the space its state; with no document (previews, tests) the leaf keeps one of its own. + val areaViewStates = LocalAreaViewStates.current + val scope = remember(area.id, areaViewStates) { areaViewStates?.scopeFor(area.id) ?: AreaScope(area.id) } + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val borderColor = + when { + hovered -> colors.panelBorderHover + else -> colors.panelBorder + } + val dragController = LocalAreaDragController.current + + // The right-click context menu mirrors the header's structural actions plus a Change Editor Type + // submenu of every registered space. Built here (in composition) so each label can be localized. + val contextItems = + listOf( + MenuItem.Action( + label = stringResource(Res.string.area_split_left_right), + onSelect = { onCommand(AreaCommand.SplitArea(area.id, SplitOrientation.Horizontal)) }, + ), + MenuItem.Action( + label = stringResource(Res.string.area_split_top_bottom), + onSelect = { onCommand(AreaCommand.SplitArea(area.id, SplitOrientation.Vertical)) }, + ), + MenuItem.Separator, + MenuItem.Submenu( + label = stringResource(Res.string.area_change_editor), + items = + registry.all.map { descriptor -> + MenuItem.Action( + label = stringResource(descriptor.title), + onSelect = { onCommand(AreaCommand.SwitchSpace(area.id, descriptor.kind)) }, + icon = descriptor.icon, + ) + }, + ), + MenuItem.Separator, + MenuItem.Action( + label = stringResource(Res.string.area_close), + onSelect = { onCommand(AreaCommand.CloseArea(area.id)) }, + ), + ) + + // Drop this leaf's captured rectangle when it leaves composition (e.g. it was consumed by a join); + // keyed on the stable id (the leaf lives under key(id) in AreaTree), like the viewport host's unregister. + if (dragController != null) { + DisposableEffect(area.id) { + onDispose { dragController.removeBounds(area.id) } + } + } + + // Release the pointer claim on the same trigger, so a closed or joined-away area stops being the + // answer to "which area does the pointer mean" - the tracker's eviction half, next to the one above. + val hoveredTracker = LocalHoveredSurfaceTracker.current + if (hoveredTracker != null) { + DisposableEffect(hoveredTracker, area.id) { + onDispose { hoveredTracker.releaseArea(area.id) } + } + // Both stamps assert the KIND the area had when touched, and a space change leaves the leaf alive + // under the same id - so the change itself settles them, without waiting for a pointer event over + // the area, which a header-dropdown switch followed by a key press or a command elsewhere never + // sends. The outgoing kind's strip-host and viewport claims are released first: a document-wide + // operation fired from a panel would otherwise be routed to this area, whose host refuses a + // non-hosting kind, and its strip would show nowhere; Export Image would frame a viewport that is + // gone. Then the area is re-stamped under the kind it hosts now, when it is + // the one the pointer last touched, so dispatch, the status bar, and the palette read the new space. + DisposableEffect(hoveredTracker, area.id, area.space) { + hoveredTracker.restampKind(area.id, area.space) + onDispose { hoveredTracker.releaseKindClaims(area.id) } + } + } + + Box( + modifier = + modifier + .fillMaxSize() + // One stamp for every space: the leaf knows its own kind, so a space cannot forget to + // report itself and a new SpaceKind is covered the day it is added. On the leaf rather + // than the body so the HEADER counts as hovering the area - the outliner's search field + // lives there, and using it has to read as "the pointer is on the outliner". + .stampsHoveredSurface(hoveredTracker, area.id, area.space) + .onGloballyPositioned { leafCoords -> + val content = dragController?.contentCoords + if (content != null && content.isAttached && leafCoords.isAttached) { + dragController.putBounds(area.id, content.localBoundingBoxOf(leafCoords)) + } + }, + ) { + ContextMenuArea(items = contextItems, modifier = Modifier.fillMaxSize()) { + Surface( + modifier = Modifier.fillMaxSize().hoverable(interaction), + border = BorderStroke(1.dp, borderColor), + shape = shapes.large, + ) { + Column(modifier = Modifier.fillMaxSize()) { + AreaHeader(area = area, scope = scope, onCommand = onCommand) + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + // The operation settings strip is hosted here, under the header and over the space body, + // so its inset reaches the space's own bottom-left chrome; the host itself shows the strip + // only in a work surface (hostsOperationStrip). + OperationStripHost(areaId = area.id, kind = area.space) { + registry.descriptor(area.space).content(scope) + } + } + } + } + } + // Corner handles last so they sit above the content for hit-testing. They only capture a real drag + // (touch-slop), so a plain tap still falls through to header controls underneath the top corners. + if (dragController != null) { + for (corner in AreaCorner.entries) { + AreaCornerHandle( + controller = dragController, + areaId = area.id, + corner = corner, + onCommand = onCommand, + ) + } + } + } +} + +/** + * One corner drag handle: a small, invisible hit target showing the move cursor on hover and, on a real + * drag, driving the shared [controller] to begin / update / end a corner join. Pointer positions are + * converted from this handle's local space into the controller's content-local space via the captured + * coordinates, so the drag is tracked correctly even after the pointer leaves the handle. + * + * 四隅のドラッグハンドル。ホバーで移動カーソル、ドラッグで結合ジェスチャを駆動する。 + * + * @param AreaDragController controller The shared corner-drag state. + * @param String areaId The owning leaf's id (the join survivor). + * @param AreaCorner corner Which corner this handle is. + * @param Function onCommand Sink for the resulting join command on release. + */ +@Composable +private fun BoxScope.AreaCornerHandle( + controller: AreaDragController, + areaId: String, + corner: AreaCorner, + onCommand: (AreaCommand) -> Unit, +) { + var handleCoords by remember { mutableStateOf(null) } + Box( + modifier = + Modifier + .align(corner.toAlignment()) + .size(width = CORNER_HANDLE_SIZE_WIDTH, height = CORNER_HANDLE_SIZE_HEIGHT) + .onGloballyPositioned { handleCoords = it } + .pointerHoverIcon(umamoPointerIcon(LocalUmamoCursors.nsewScroll)) + .pointerInput(areaId) { + detectDragGestures( + onDragStart = { startOffset -> + contentLocalOf(controller, handleCoords, startOffset)?.let { pointer -> + controller.beginDrag(areaId, corner, pointer) + } + }, + onDrag = { change, _ -> + change.consume() + contentLocalOf(controller, handleCoords, change.position)?.let { pointer -> + controller.updateDrag(pointer) + } + }, + onDragEnd = { controller.endDrag()?.let { command -> onCommand(command) } }, + onDragCancel = { controller.cancelDrag() }, + ) + }, + ) +} + +/** + * Converts a handle-local pointer [offset] into the controller's content-local space, or null when the + * coordinates are not both attached (a transient layout state). + * + * @param AreaDragController controller Holds the content-space coordinates. + * @param LayoutCoordinates? handleCoords The corner handle's coordinates. + * @param Offset offset The pointer position in handle-local space. + * @return Offset? The pointer in content-local space, or null. + */ +private fun contentLocalOf( + controller: AreaDragController, + handleCoords: LayoutCoordinates?, + offset: Offset, +): Offset? { + val content = controller.contentCoords + if (content == null || handleCoords == null || !content.isAttached || !handleCoords.isAttached) { + return null + } + return content.localPositionOf(handleCoords, offset) +} + +/** + * Maps a corner to the Box alignment that pins a handle there. + * + * @return Alignment The matching corner alignment. + */ +private fun AreaCorner.toAlignment(): Alignment = + when (this) { + AreaCorner.TopLeft -> Alignment.TopStart + AreaCorner.TopRight -> Alignment.TopEnd + AreaCorner.BottomLeft -> Alignment.BottomStart + AreaCorner.BottomRight -> Alignment.BottomEnd + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaNode.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaNode.kt new file mode 100644 index 0000000..32f39fd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaNode.kt @@ -0,0 +1,98 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * How a [SplitNode] divides its space. Horizontal lays the two children side by side (the divider is + * a vertical bar you drag left/right); Vertical stacks them top over bottom (a horizontal divider). + * Named for the axis the children occupy, and labelled in the UI by the visual result + * ("Split Left/Right" vs "Split Top/Bottom") to avoid Blender's inverse "split horizontally" wording. + * + * 分割の向き。Horizontal は左右に並べ(縦の仕切り)、Vertical は上下に積む(横の仕切り)。 + */ +@Serializable +enum class SplitOrientation { + Horizontal, + Vertical, +} + +/** + * A node in a workspace's recursive area tree - either a [SplitNode] (an internal split) or a + * [LeafArea] (a hosted editor space). A sealed interface so the layout engine and reducer match + * exhaustively (the compiler enforces both cases are handled), and `@Serializable` so the whole tree + * round-trips through the interface.layout settings key. Polymorphism uses a "type" discriminator + * with the per-subtype [SerialName] (see LayoutJson). + * + * ワークスペースの再帰的エリアツリーのノード。分割 (SplitNode) か葉 (LeafArea) のどちらか。 + */ +@Serializable +sealed interface AreaNode + +/** + * An internal split: two child nodes divided along [orientation], with [ratio] giving the first + * child's fraction of the axis (0..1). Splits nest arbitrarily, so [first]/[second] may themselves be + * SplitNodes. A SplitNode has no stable id - only leaves do - because a split is addressed + * structurally (by the leaves it contains), and ratio edits thread up through the tree, not through + * an id lookup. + * + * 内部分割ノード。orientation 方向に 2 子を ratio(最初の子の割合)で分ける。任意に入れ子可能。 + * + * @property SplitOrientation orientation The division axis. + * @property Float ratio The first child's fraction of the axis (0..1). + * @property AreaNode first The leading child (left or top). + * @property AreaNode second The trailing child (right or bottom). + */ +@Serializable +@SerialName("split") +data class SplitNode( + val orientation: SplitOrientation, + val ratio: Float, + val first: AreaNode, + val second: AreaNode, +) : AreaNode + +/** + * A leaf area hosting exactly one editor [space], identified by a stable, position-independent [id]. + * The id is the linchpin of GL viewport identity: it is minted once, never reused, and never derived + * from tree position, so a leaf keeps the same id when an unrelated area splits - which lets the + * viewport host keep the same GL surface alive (via key(id) + movableContentOf) instead of tearing it + * down and recreating it. + * + * 葉エリア。1 つのエディタ空間を表示し、安定で位置非依存の id を持つ。id は GL ビューポートの同一性の要。 + * + * @property String id The stable, never-reused area identity. + * @property SpaceKind space The editor space currently shown here. + */ +@Serializable +@SerialName("leaf") +data class LeafArea( + val id: String, + val space: SpaceKind, +) : AreaNode + +/** + * The first leaf under this node that [predicate] accepts, in tree order (a split's first child before + * its second: left before right, top before bottom), or null when none does - how a caller finds "some + * area of this kind" when the pointer has named none. + * + * @param Function predicate Whether a leaf qualifies. + * @return LeafArea? The first qualifying leaf, or null. + */ +fun AreaNode.firstLeafOrNull(predicate: (LeafArea) -> Boolean): LeafArea? = + when (this) { + is LeafArea -> if (predicate(this)) this else null + is SplitNode -> first.firstLeafOrNull(predicate) ?: second.firstLeafOrNull(predicate) + } + +/** + * Every leaf's id under this node, in tree order (a split's first child before its second) - the order a saved + * document lists a layout's areas in (docs/format/UMA.md §7.5). + * + * @return List The leaf ids. + */ +fun AreaNode.leafAreaIds(): List = + when (this) { + is LeafArea -> listOf(id) + is SplitNode -> first.leafAreaIds() + second.leafAreaIds() + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaTree.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaTree.kt new file mode 100644 index 0000000..e51d03e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaTree.kt @@ -0,0 +1,215 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity + +/** The smallest fraction either child of a split may shrink to (keeps both areas usable). */ +internal const val MIN_RATIO = 0.05f + +/** + * Renders an area tree recursively: a [LeafArea] becomes an [AreaLeaf]; a [SplitNode] becomes a + * [SplitContainer]. Two callbacks flow down: [onNodeChange] threads a rewritten subtree back up to the + * root (used by splitter ratio drags), and [onCommand] carries structural edits (split / close / + * switch) to the shell's reducer. A leaf is wrapped in `key(id)` so its composition identity follows + * the stable area id, not its position - the basis for keeping a hosted GL surface alive across + * unrelated tree mutations. + * + * エリアツリーを再帰的に描画する。葉は AreaLeaf、分割は SplitContainer。onNodeChange は書き換えた部分木を + * 上へ、onCommand は構造的編集を伝える。葉は key(id) で同一性を位置でなく安定 id に固定する。 + * + * @param AreaNode node The node to render. + * @param Function onNodeChange Receives a rewritten replacement for this node (ratio edits). + * @param Function onCommand Sink for structural edits from area headers. + * @param Modifier modifier The layout modifier. + * @param Function onSplitterDragChange Receives true when a splitter drag begins anywhere in this + * subtree and false when it ends; the persistence layer paces layout saves on it. + */ +@Composable +fun AreaTree( + node: AreaNode, + onNodeChange: (AreaNode) -> Unit, + onCommand: (AreaCommand) -> Unit, + modifier: Modifier = Modifier, + onSplitterDragChange: (Boolean) -> Unit = {}, +) { + when (node) { + is LeafArea -> + key(node.id) { + AreaLeaf(area = node, onCommand = onCommand, modifier = modifier) + } + is SplitNode -> + SplitContainer( + node = node, + onNodeChange = onNodeChange, + onCommand = onCommand, + modifier = modifier, + onSplitterDragChange = onSplitterDragChange, + ) + } +} + +/** + * Lays out a split's two children with a divider between them, weighted by the node's ratio. Each + * child recurses through [AreaTree], threading its own rewrite back into the parent via [onNodeChange] + * so an edit deep in the tree rebuilds only the path to the root. A divider drag rewrites this node's + * whole subtree through a [SplitterDragSession]: the session snapshots the node when the drag begins + * and rewrites snapshot + accumulated total per delta, so deltas arriving faster than recomposition + * commits are never lost (see the session's docblock). The ancestor onNodeChange chain + * (node.copy(first = ...)) stays value-correct under those publishes because a ratio drag never + * changes any ancestor's other fields. + * + * @param SplitNode node The split to lay out. + * @param Function onNodeChange Receives the rewritten split. + * @param Function onCommand Sink for structural edits. + * @param Modifier modifier The layout modifier. + * @param Function onSplitterDragChange Receives this split's (and its children's) drag start/end. + */ +@Composable +private fun SplitContainer( + node: SplitNode, + onNodeChange: (AreaNode) -> Unit, + onCommand: (AreaCommand) -> Unit, + modifier: Modifier, + onSplitterDragChange: (Boolean) -> Unit, +) { + val ratio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + var dragSession by remember { mutableStateOf(null) } + // Release the persistence hold if this container leaves composition MID-DRAG (a keyboard-driven + // workspace switch or area close while the bar is held): whether draggable's onDragStopped fires + // on detach is not guaranteed, and a stranded drag-active flag would silently suppress structural + // layout saves until the next completed drag. Guarded on the session so a normally-ended drag + // (session already cleared) never double-signals. rememberUpdatedState because onDispose runs + // with the closure captured at first composition, which may hold a stale callback by then. + val currentOnSplitterDragChange by rememberUpdatedState(onSplitterDragChange) + DisposableEffect(Unit) { + onDispose { + if (dragSession != null) { + currentOnSplitterDragChange(false) + } + } + } + // Park this drag's cancel where the shell's Escape precedence can reach it (see + // SplitterDragCancelController): the session below is remembered per container, so nothing outside + // this composable could otherwise abort a divider drag. Cleared by identity rather than blindly, + // because nested splits mean sibling containers run this same effect and must not blank the + // dragging one's callback. + val splitterDragCancel = LocalSplitterDragCancel.current + val activeDragSession = dragSession + DisposableEffect(activeDragSession, splitterDragCancel) { + val cancelDrag: (() -> Unit)? = + if (activeDragSession == null) { + null + } else { + { + onNodeChange(activeDragSession.cancel()) + currentOnSplitterDragChange(false) + } + } + if (cancelDrag != null) { + splitterDragCancel.cancel = cancelDrag + } + onDispose { + if (cancelDrag != null && splitterDragCancel.cancel === cancelDrag) { + splitterDragCancel.cancel = null + } + } + } + val first: @Composable () -> Unit = { + AreaTree( + node = node.first, + onNodeChange = { rewritten -> onNodeChange(node.copy(first = rewritten)) }, + onCommand = onCommand, + modifier = Modifier.fillMaxSize(), + onSplitterDragChange = onSplitterDragChange, + ) + } + val second: @Composable () -> Unit = { + AreaTree( + node = node.second, + onNodeChange = { rewritten -> onNodeChange(node.copy(second = rewritten)) }, + onCommand = onCommand, + modifier = Modifier.fillMaxSize(), + onSplitterDragChange = onSplitterDragChange, + ) + } + // BoxWithConstraints measures the parent so the splitter can convert a pixel drag into a ratio + // against the actual on-axis length (recomputed live as the window resizes). + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + val density = LocalDensity.current + val axisPx = + with(density) { + when (node.orientation) { + SplitOrientation.Horizontal -> maxWidth.toPx() + SplitOrientation.Vertical -> maxHeight.toPx() + } + } + val minPx = with(density) { MIN_AREA_DP.toPx() } + val splitterPx = with(density) { SPLITTER_THICKNESS.toPx() } + val onDragStart: () -> Unit = { + dragSession = SplitterDragSession(node, axisPx, minPx, splitterPx) + onSplitterDragChange(true) + } + val onDrag: (Float) -> Unit = { deltaPx -> + val activeSession = dragSession + // Escape already abandoned this drag and restored the starting ratio; swallow every further + // delta from the still-held pointer rather than rebasing, which would resume the drag. The + // check precedes the ownsNode test so a structural edit landing after the cancel cannot + // resurrect it either. + if (activeSession == null || !activeSession.isCancelled) { + val session = + if (activeSession != null && activeSession.ownsNode(node)) { + activeSession + } else { + // A structural edit rewrote the tree mid-drag (a keyboard command while holding + // the bar), or the start callback was missed: rebase a fresh session on the live + // node so the drag continues from the tree as it now stands. + SplitterDragSession(node, axisPx, minPx, splitterPx).also { rebased -> dragSession = rebased } + } + onNodeChange(session.accumulate(deltaPx)) + } + } + val onDragEnd: () -> Unit = { + dragSession = null + onSplitterDragChange(false) + } + when (node.orientation) { + SplitOrientation.Horizontal -> + Row(modifier = Modifier.fillMaxSize()) { + Box(modifier = Modifier.weight(ratio).fillMaxHeight()) { first() } + Splitter( + orientation = SplitOrientation.Horizontal, + onDragByPx = onDrag, + onDragStarted = onDragStart, + onDragStopped = onDragEnd, + ) + Box(modifier = Modifier.weight(1f - ratio).fillMaxHeight()) { second() } + } + SplitOrientation.Vertical -> + Column(modifier = Modifier.fillMaxSize()) { + Box(modifier = Modifier.weight(ratio).fillMaxWidth()) { first() } + Splitter( + orientation = SplitOrientation.Vertical, + onDragByPx = onDrag, + onDragStarted = onDragStart, + onDragStopped = onDragEnd, + ) + Box(modifier = Modifier.weight(1f - ratio).fillMaxWidth()) { second() } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaViewStates.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaViewStates.kt new file mode 100644 index 0000000..40eb90f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/AreaViewStates.kt @@ -0,0 +1,130 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.staticCompositionLocalOf +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.umamo.render.ViewportCamera +import org.umamo.ui.viewport.AreaCameraKey +import org.umamo.ui.viewport.CameraSurface + +/** + * Every area's view state for ONE open document: the scope each area parks its space state on, seeded from what + * the document was saved with and gathered back for its next save (docs/format/UMA.md §7.3). + * + * The scopes live here rather than in each leaf's composition so their lifetime is the document's. A workspace + * tab switch disposes the inactive tree and recomposes it on return; with the scope held by the leaf, every space + * would come back at its defaults. A new document gets a new holder, so nothing carries from one rig to the next. + * + * The area ids are the application layout's own (`interface.layout`), borrowed as opaque keys (UMA §7.3): the + * document does not own them, and a saved id the current layout lacks simply seeds nothing. + * + * @param JsonObject? restoredAreas The `areas` member the document was opened with, or null. + */ +class AreaViewStates(private val restoredAreas: JsonObject? = null) { + /** Each area's scope, created the first time the area is shown for this document. */ + private val scopesByAreaId = LinkedHashMap() + + /** + * Every leaf id of the LIVE layout, workspaces in tab order and each tree in its own order, published by the + * shell on each layout change. The live layout rather than the `interface.layout` setting, whose write is + * debounced: a save right after a split would otherwise miss the new area. + */ + var layoutAreaIds: List = emptyList() + + /** + * The cameras the document was saved with, by area and surface (UMA §7.3): a `[centerX, centerY, zoom]` with a + * zoom above zero under each surface's name. Anything else is skipped, and that area fits its content as a + * fresh one does. Kept apart by surface because a view of the puppet's world means nothing over a texture's + * pixels: an area saved as a UV editor and reopened as a 2D viewport must not take the page's pan and zoom. + * + * @return Map The saved cameras. + */ + fun restoredCameras(): Map { + val cameras = HashMap() + for ((areaId, block) in restoredAreas.orEmpty()) { + val saved = (block as? JsonObject)?.get(AREA_CAMERAS_MEMBER) as? JsonObject ?: continue + for (surface in CameraSurface.entries) { + val (centerX, centerY, zoom) = floatListOf(saved, cameraSurfaceWireName(surface), 3) ?: continue + if (zoom > 0f) { + cameras[AreaCameraKey(areaId, surface)] = ViewportCamera(centerX, centerY, zoom) + } + } + } + return cameras + } + + /** + * The scope for [areaId], created on first use over the block the document saved for that id. + * + * @param String areaId The hosting leaf's area id. + * @return AreaScope The one scope this document has for the area. + */ + fun scopeFor(areaId: String): AreaScope = scopesByAreaId.getOrPut(areaId) { AreaScope(areaId, restoredAreas?.get(areaId) as? JsonObject) } + + /** + * The `areas` member of a save's merge patch (UMA §7.5): a block for each area of the saver's layout that was + * shown in this session, and a null for every id the document held that the layout does not have - last writer + * wins, which is also what keeps another layout's tokens from piling up in the file. + * + * An area of the layout that was never shown (an inactive workspace's, say) is not named, so the block the + * file had for it survives the merge. An area that was shown and then closed is not in [layoutAreaIds], so it + * is not written either. + * + * New blocks enter the file in [layoutAreaIds]'s order. + * + * @param Map cameras Every camera the platform's render service remembers, by area and surface; empty where + * there is no render service (Android today). + * @return JsonObject The patch's `areas` member. + */ + fun gather(cameras: Map = emptyMap()): JsonObject { + val inLayout = layoutAreaIds.toHashSet() + return buildJsonObject { + for (staleAreaId in restoredAreas?.keys.orEmpty()) { + if (staleAreaId !in inLayout) { + put(staleAreaId, JsonNull) + } + } + for (areaId in layoutAreaIds) { + val spaces = scopesByAreaId[areaId]?.gather() + val views = + CameraSurface.entries.mapNotNull { surface -> + cameras[AreaCameraKey(areaId, surface)] + ?.takeIf { view -> view.centerX.isFinite() && view.centerY.isFinite() && view.zoom.isFinite() } + ?.let { view -> surface to view } + } + if (spaces == null && views.isEmpty()) { + continue + } + put( + areaId, + buildJsonObject { + // UMA §7.3: `cameras` leads the block. A surface is named only when the engine holds a view of + // it for the area, so one the area is not showing today keeps the view it was saved with. + if (views.isNotEmpty()) { + put( + AREA_CAMERAS_MEMBER, + buildJsonObject { + for ((surface, view) in views) { + put(cameraSurfaceWireName(surface), JsonArray(listOf(JsonPrimitive(view.centerX), JsonPrimitive(view.centerY), JsonPrimitive(view.zoom)))) + } + }, + ) + } + spaces?.forEach { (memberName, member) -> put(memberName, member) } + }, + ) + } + } + } +} + +/** + * The open document's area view states, or null outside a document (previews, tests), where a leaf keeps a scope + * of its own. + * + * Static because the holder is swapped whole with the document and never mutated as a value. + */ +val LocalAreaViewStates = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ChangeLabels.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ChangeLabels.kt new file mode 100644 index 0000000..990d6a3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ChangeLabels.kt @@ -0,0 +1,122 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.resources.* + +/** + * Maps a [org.umamo.edit.Change.labelKey] (or null, the seed entry) to its localized label - the + * history panel's step label and the operation settings strip's title, from ONE mapping so the two + * can never name the same change differently. The keys mirror those declared in :edit's Change + * taxonomy; an unmapped key falls back to a generic "Edit" so a newly added change kind never renders + * blank. + * + * @param String? labelKey The change's stable label key, or null for the initial-open step. + * @return String The localized step label. + */ +@Composable +internal fun changeLabel(labelKey: String?): String = + when (labelKey) { + null -> stringResource(Res.string.history_open) + "change.selection" -> stringResource(Res.string.history_selection) + "change.parameter.select" -> stringResource(Res.string.history_parameter_select) + "change.keyform.insert" -> stringResource(Res.string.history_keyform_insert) + "change.keyform.move" -> stringResource(Res.string.history_keyform_move) + "change.keyform.delete" -> stringResource(Res.string.history_keyform_remove) + "change.mode" -> stringResource(Res.string.history_mode) + "change.part.visibility" -> stringResource(Res.string.history_part_visibility) + "change.part.rename" -> stringResource(Res.string.history_part_rename) + "change.part.selectable" -> stringResource(Res.string.history_part_selectable) + "change.part.move" -> stringResource(Res.string.history_part_move) + "change.drawable.visibility" -> stringResource(Res.string.history_drawable_visibility) + "change.drawable.rename" -> stringResource(Res.string.history_drawable_rename) + "change.drawable.selectable" -> stringResource(Res.string.history_drawable_selectable) + "change.drawable.move" -> stringResource(Res.string.history_drawable_move) + "change.deformer.create" -> stringResource(Res.string.history_deformer_create) + "change.deformer.rename" -> stringResource(Res.string.history_deformer_rename) + "change.deformer.selectable" -> stringResource(Res.string.history_deformer_selectable) + "change.deformer.move" -> stringResource(Res.string.history_deformer_move) + "change.parameter.value" -> stringResource(Res.string.history_parameter_value) + "change.parameter.range" -> stringResource(Res.string.history_parameter_range) + "change.parameter.link" -> stringResource(Res.string.history_parameter_link) + "change.parameter.unlink" -> stringResource(Res.string.history_parameter_unlink) + "change.parameter.move" -> stringResource(Res.string.history_parameter_move) + "change.parameter.groupCreate" -> stringResource(Res.string.history_parameter_group_create) + "change.parameter.groupDelete" -> stringResource(Res.string.history_parameter_group_delete) + "change.parameter.groupRename" -> stringResource(Res.string.history_parameter_group_rename) + "change.parameter.create" -> stringResource(Res.string.history_parameter_create) + "change.parameter.rename" -> stringResource(Res.string.history_parameter_rename) + "change.parameter.delete" -> stringResource(Res.string.history_parameter_delete) + "change.parameter.deleteMove" -> stringResource(Res.string.history_parameter_delete_move) + "change.mesh.move" -> stringResource(Res.string.history_mesh_move) + "change.mesh.scale" -> stringResource(Res.string.history_mesh_scale) + "change.mesh.rotate" -> stringResource(Res.string.history_mesh_rotate) + "change.mesh.slide" -> stringResource(Res.string.history_mesh_slide) + "change.mesh.mirror" -> stringResource(Res.string.history_mesh_mirror) + "change.uv.move" -> stringResource(Res.string.history_uv_move) + "change.uv.scale" -> stringResource(Res.string.history_uv_scale) + "change.uv.rotate" -> stringResource(Res.string.history_uv_rotate) + "change.uv.mirror" -> stringResource(Res.string.history_uv_mirror) + "change.mesh.duplicate" -> stringResource(Res.string.history_mesh_duplicate) + "change.mesh.merge" -> stringResource(Res.string.history_mesh_merge) + "change.mesh.rip" -> stringResource(Res.string.history_mesh_rip) + "change.mesh.connect" -> stringResource(Res.string.history_mesh_connect) + "change.mesh.addVertex" -> stringResource(Res.string.history_mesh_add_vertex) + "change.mesh.deleteVertex" -> stringResource(Res.string.history_mesh_delete_vertex) + "change.drawable.duplicate" -> stringResource(Res.string.history_drawable_duplicate) + "change.object.move" -> stringResource(Res.string.history_object_move) + "change.object.scale" -> stringResource(Res.string.history_object_scale) + "change.object.rotate" -> stringResource(Res.string.history_object_rotate) + "change.object.mirror" -> stringResource(Res.string.history_object_mirror) + "change.mesh.select" -> stringResource(Res.string.history_mesh_select) + "change.keyform.select" -> stringResource(Res.string.history_keyform_select) + "change.mesh.selectMode" -> stringResource(Res.string.history_mesh_select_mode) + "change.part.delete" -> stringResource(Res.string.history_part_delete) + "change.drawable.delete" -> stringResource(Res.string.history_drawable_delete) + "change.deformer.delete" -> stringResource(Res.string.history_deformer_delete) + "change.part.sketch" -> stringResource(Res.string.history_part_sketch) + "change.part.drawOrder" -> stringResource(Res.string.history_part_draw_order) + "change.part.groupMode" -> stringResource(Res.string.history_part_group_mode) + "change.part.composite" -> stringResource(Res.string.history_part_composite) + "change.drawable.blendMode" -> stringResource(Res.string.history_drawable_blend_mode) + "change.drawable.alphaBlendMode" -> stringResource(Res.string.history_drawable_alpha_blend_mode) + "change.drawable.culling" -> stringResource(Res.string.history_drawable_culling) + "change.drawable.invertMask" -> stringResource(Res.string.history_drawable_invert_mask) + "change.drawable.parentDeformer" -> stringResource(Res.string.history_drawable_parent_deformer) + "change.drawable.maskedBy" -> stringResource(Res.string.history_drawable_masked_by) + "change.drawable.multiplyColor" -> stringResource(Res.string.history_drawable_multiply_color) + "change.drawable.screenColor" -> stringResource(Res.string.history_drawable_screen_color) + "change.drawable.opacity" -> stringResource(Res.string.history_drawable_opacity) + "change.drawable.drawOrder" -> stringResource(Res.string.history_drawable_draw_order) + "change.deformer.opacity" -> stringResource(Res.string.history_deformer_opacity) + "change.deformer.multiplyColor" -> stringResource(Res.string.history_deformer_multiply_color) + "change.deformer.screenColor" -> stringResource(Res.string.history_deformer_screen_color) + "change.deformer.flipX" -> stringResource(Res.string.history_deformer_flip_x) + "change.deformer.flipY" -> stringResource(Res.string.history_deformer_flip_y) + "change.deformer.part" -> stringResource(Res.string.history_deformer_part) + "change.deformer.baseAngle" -> stringResource(Res.string.history_deformer_base_angle) + "change.deformer.quadTransform" -> stringResource(Res.string.history_deformer_quad_transform) + "change.deformer.grid" -> stringResource(Res.string.history_deformer_grid) + "change.document.canvasSize" -> stringResource(Res.string.history_document_canvas_size) + "change.document.worldOrigin" -> stringResource(Res.string.history_document_world_origin) + "change.document.runtimeTarget" -> stringResource(Res.string.history_document_runtime_target) + "change.document.sourceLayerDisplay" -> stringResource(Res.string.history_document_source_layer_display) + "change.document.atlasPlacement" -> stringResource(Res.string.history_document_atlas_placement) + "change.document.atlasPlacement.rotate" -> stringResource(Res.string.history_document_atlas_placement_rotate) + "change.document.atlasPlacement.scale" -> stringResource(Res.string.history_document_atlas_placement_scale) + "change.document.atlasPin" -> stringResource(Res.string.history_document_atlas_pin) + "change.document.atlasUnpin" -> stringResource(Res.string.history_document_atlas_unpin) + "change.document.atlasRepack" -> stringResource(Res.string.history_document_atlas_repack) + "change.document.tileSource" -> stringResource(Res.string.history_document_tile_source) + "change.document.tileUnbind" -> stringResource(Res.string.history_document_tile_unbind) + "change.document.deleteTile" -> stringResource(Res.string.history_document_delete_tile) + "change.document.deleteTileIgnore" -> stringResource(Res.string.history_document_delete_tile_ignore) + "change.document.layerIgnore" -> stringResource(Res.string.history_document_layer_ignore) + "change.document.layerUnignore" -> stringResource(Res.string.history_document_layer_unignore) + "change.document.importArtwork" -> stringResource(Res.string.history_document_import_artwork) + "change.document.reloadArtwork" -> stringResource(Res.string.history_document_reload_artwork) + "change.document.relinkArtwork" -> stringResource(Res.string.history_document_relink_artwork) + "change.document.matchArtwork" -> stringResource(Res.string.history_document_match_artwork) + "change.document.replaceArtwork" -> stringResource(Res.string.history_document_replace_artwork) + else -> stringResource(Res.string.history_unknown) + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/DefaultSpaces.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/DefaultSpaces.kt new file mode 100644 index 0000000..94d2d17 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/DefaultSpaces.kt @@ -0,0 +1,171 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppetViewportService +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.viewport.ViewportSpaceCamera +import org.umamo.ui.workspace.spaces.HistorySpace +import org.umamo.ui.workspace.spaces.KeyformSheetSpace +import org.umamo.ui.workspace.spaces.LogsSpace +import org.umamo.ui.workspace.spaces.OutlinerSpace +import org.umamo.ui.workspace.spaces.ParametersSpace +import org.umamo.ui.workspace.spaces.PlaceholderSpace +import org.umamo.ui.workspace.spaces.PropertiesSpace +import org.umamo.ui.workspace.spaces.SourcesSpace +import org.umamo.ui.workspace.spaces.UvEditorSpace +import org.umamo.ui.workspace.spaces.ViewportSidebarDrawer +import org.umamo.ui.workspace.spaces.ViewportToolbarOverlay +import org.umamo.ui.workspace.spaces.keyformSheetHeaderControls +import org.umamo.ui.workspace.spaces.logsHeaderControls +import org.umamo.ui.workspace.spaces.outlinerHeaderControls +import org.umamo.ui.workspace.spaces.parametersHeaderControls +import org.umamo.ui.workspace.spaces.propertiesHeaderControls +import org.umamo.ui.workspace.spaces.sourcesHeaderControls +import org.umamo.ui.workspace.spaces.uvEditorHeaderControls +import org.umamo.ui.workspace.spaces.viewport2DHeaderControls + +/** + * Builds the base [SpaceRegistry] every shell starts from: a descriptor for each [SpaceKind]. The 2D + * viewport delegates to the host-injected [LocalViewportHost] (placeholder when absent); every other + * space but [SpaceKind.ToolDetails] has a real body wired directly here (UvEditor, Outliner, Parameters, + * KeyformSheet, Properties, History, Logs) - only ToolDetails still renders a [PlaceholderSpace] until + * its own panel lands. The app layers additional overrides on with [SpaceRegistry.withOverrides]. + * + * @return SpaceRegistry The base registry covering every SpaceKind. + */ +fun defaultSpaceRegistry(): SpaceRegistry { + val descriptors = + mapOf( + SpaceKind.Viewport2D to + SpaceDescriptor( + SpaceKind.Viewport2D, + Res.string.space_viewport2d, + LocalUmamoIcons.spaceViewport, + headerContent = { viewport2DHeaderControls() }, + ) { scope -> Viewport2DBody(scope) }, + SpaceKind.UvEditor to + SpaceDescriptor( + SpaceKind.UvEditor, + Res.string.space_uv, + LocalUmamoIcons.spaceTexture, + headerContent = { scope -> uvEditorHeaderControls(scope) }, + ) { scope -> UvEditorSpace(scope) }, + SpaceKind.Sources to + SpaceDescriptor( + SpaceKind.Sources, + Res.string.space_sources, + LocalUmamoIcons.sources, + headerContent = { scope -> sourcesHeaderControls(scope) }, + ) { scope -> SourcesSpace(scope) }, + SpaceKind.Outliner to + SpaceDescriptor( + SpaceKind.Outliner, + Res.string.space_outliner, + LocalUmamoIcons.spaceOutliner, + headerContent = { scope -> outlinerHeaderControls(scope) }, + ) { scope -> OutlinerSpace(scope) }, + SpaceKind.Parameters to + SpaceDescriptor( + SpaceKind.Parameters, + Res.string.space_parameters, + LocalUmamoIcons.spaceParameters, + headerContent = { scope -> parametersHeaderControls(scope) }, + ) { scope -> ParametersSpace(scope) }, + SpaceKind.KeyformSheet to + SpaceDescriptor( + SpaceKind.KeyformSheet, + Res.string.space_keyformsheet, + LocalUmamoIcons.spaceKeyformSheet, + headerContent = { scope -> keyformSheetHeaderControls(scope) }, + ) { scope -> KeyformSheetSpace(scope) }, + SpaceKind.Properties to + SpaceDescriptor( + SpaceKind.Properties, + Res.string.space_properties, + LocalUmamoIcons.spaceProperties, + headerContent = { scope -> propertiesHeaderControls(scope) }, + ) { scope -> PropertiesSpace(scope) }, + SpaceKind.ToolDetails to + SpaceDescriptor( + SpaceKind.ToolDetails, + Res.string.space_tooldetails, + LocalUmamoIcons.spaceTool, + ) { PlaceholderSpace(stringResource(Res.string.space_tooldetails)) }, + SpaceKind.History to + SpaceDescriptor( + SpaceKind.History, + Res.string.space_history, + LocalUmamoIcons.spaceHistory, + ) { HistorySpace() }, + SpaceKind.Logs to + SpaceDescriptor( + SpaceKind.Logs, + Res.string.space_logs, + LocalUmamoIcons.logsTerminal, + headerContent = { logsHeaderControls() }, + ) { LogsSpace() }, + ) + return SpaceRegistry(descriptors) +} + +/** + * The 2D viewport body: the injected [LocalViewportHost]'s rendered surface, with the floating chrome (the + * left tool toolbar and the right sidebar drawer) overlaid. + * + * The grid, the axes, and the canvas are the renderer's, drawn through its camera, for an empty document + * as for a full one - the editor always has a document, so there is no state in which this would stand + * in for them with a drawing of its own. The one case with no host is a platform that has no puppet + * renderer yet (Android until its GLES service lands); there the area is the plain viewport backdrop + * color and nothing else, because a painted grid that cannot pan or zoom would promise a work surface + * that is not there. + * + * @param AreaScope scope The hosting area context (its id keys the host's GL surface). + */ +@Composable +private fun Viewport2DBody(scope: AreaScope) { + val host = LocalViewportHost.current + val chrome = LocalViewportChrome.current + // Register this viewport area's camera controller for its lifetime, into the same per-area hub the UV + // editor registers into, so the shell's view commands (Fit / 1:1 / zoom / Frame Selected) resolve THIS + // area when the pointer last touched it. Only when a render service and session exist - with no + // viewport nothing registers, matching the hidden view commands. + val service = LocalPuppetViewportService.current + val session = LocalEditorSession.current + val areaCameraHub = LocalAreaCameraHub.current + DisposableEffect(scope.areaId, service, session, areaCameraHub) { + if (service != null && session != null && areaCameraHub != null) { + areaCameraHub.register(scope.areaId, ViewportSpaceCamera(service, session, scope.areaId)) + onDispose { areaCameraHub.unregister(scope.areaId) } + } else { + onDispose { } + } + } + Box(modifier = Modifier.fillMaxSize()) { + if (host != null) { + host.Viewport2D(scope.areaId, Modifier.fillMaxSize()) + } else { + Box(modifier = Modifier.fillMaxSize().background(LocalUmamoColors.current.viewportGridBackground)) + } + if (chrome.showToolbar) { + ViewportToolbarOverlay( + modifier = + Modifier + .align(Alignment.CenterStart) + .padding(start = 6.dp), + ) + } + ViewportSidebarDrawer(modifier = Modifier.align(Alignment.CenterEnd)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorShell.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorShell.kt new file mode 100644 index 0000000..a236e98 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorShell.kt @@ -0,0 +1,817 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.background +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.launch +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.interop.ExportFormat +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportReport +import org.umamo.ui.action.CommandPalette +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.defaultKeymap +import org.umamo.ui.action.paletteCommands +import org.umamo.ui.document.DocumentOpenError +import org.umamo.ui.help.AboutDialog +import org.umamo.ui.help.CreditsDialog +import org.umamo.ui.help.openLinkQuietly +import org.umamo.ui.kit.ConfirmDialog +import org.umamo.ui.kit.DialogChoice +import org.umamo.ui.kit.InlineEditController +import org.umamo.ui.kit.KeyCaptureController +import org.umamo.ui.kit.LocalInlineEditController +import org.umamo.ui.kit.LocalKeyCapture +import org.umamo.ui.kit.LocalMenuBarController +import org.umamo.ui.kit.MenuBar +import org.umamo.ui.kit.MenuBarController +import org.umamo.ui.kit.MessageDialog +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.TopLevelMenu +import org.umamo.ui.l10n.ProvideAppLocale +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.AtlasRepackRefusalReason +import org.umamo.ui.model.AtlasRepackReport +import org.umamo.ui.model.AtlasRepackSessionOptions +import org.umamo.ui.model.KeyableHover +import org.umamo.ui.model.KeyformHover +import org.umamo.ui.model.LocalEditorMode +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalKeyableHover +import org.umamo.ui.model.LocalPuppetTextures +import org.umamo.ui.model.LocalPuppetViewportService +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.model.LocalSessionAtlasPages +import org.umamo.ui.model.LocalSourceArtRasters +import org.umamo.ui.model.repackPageSizeOf +import org.umamo.ui.model.runAtlasRepack +import org.umamo.ui.properties.LocalPropertyTabRegistry +import org.umamo.ui.properties.PropertyTab +import org.umamo.ui.properties.defaultPropertyTabRegistry +import org.umamo.ui.properties.runtimeFeatureLabelRes +import org.umamo.ui.resources.* +import org.umamo.ui.settings.LocalQuickSetup +import org.umamo.ui.settings.QuickSetupDialog +import org.umamo.ui.settings.SettingsWindow +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.UmamoTheme +import org.umamo.ui.theme.hiddenPointerIcon +import org.umamo.ui.workspace.commands.ArtworkOperations +import org.umamo.ui.workspace.commands.CommandRouting +import org.umamo.ui.workspace.commands.SessionAvailability +import org.umamo.ui.workspace.commands.atlasCommands +import org.umamo.ui.workspace.commands.chromeCommands +import org.umamo.ui.workspace.commands.displayCommands +import org.umamo.ui.workspace.commands.documentCommands +import org.umamo.ui.workspace.commands.fileArtworkCommands +import org.umamo.ui.workspace.commands.fileImageExportCommands +import org.umamo.ui.workspace.commands.frameCommands +import org.umamo.ui.workspace.commands.historyCommands +import org.umamo.ui.workspace.commands.keyformCommands +import org.umamo.ui.workspace.commands.modeCommands +import org.umamo.ui.workspace.commands.objectCommands +import org.umamo.ui.workspace.commands.proportionalCommands +import org.umamo.ui.workspace.commands.registerAll +import org.umamo.ui.workspace.commands.selectCommands +import org.umamo.ui.workspace.commands.snapCommands +import org.umamo.ui.workspace.commands.topologyCommands +import org.umamo.ui.workspace.commands.transformCommands +import org.umamo.ui.workspace.commands.uvCommands +import org.umamo.ui.workspace.commands.viewCommands +import org.umamo.ui.workspace.commands.workspaceCommands +import org.umamo.ui.workspace.rowdrag.LocalRowDragCancel +import org.umamo.ui.workspace.rowdrag.RowDragCancelController + +/** + * The whole editor shell: workspace tabs over a recursive, switchable, splittable area tree, with the + * command palette overlaid. Self-contained so it runs standalone (defaults seed a two-workspace + * layout and a base space registry), while every collaborator is injectable so an app can supply the + * GL [viewportHost], override specific spaces, share a pre-populated [commandRegistry] (e.g. with File + * commands), drive the [languageTag] from settings, and persist via [onLayoutChange]. + * + * The shell is a thin composition over its extracted collaborators: [WorkspaceLayoutController] owns + * the layout state and its edits (structural edits route through the single [AreaCommand] choke + * point), [ShellOverlayState] holds the modal chrome flags, the command tables live in the + * org.umamo.ui.workspace.commands package (registered per group through registerAll), and the root key + * handling is the modal ladder in ModalKeyLadder.kt. The palette and keymap dispatch through the action + * registry - the input spine. + * + * @param InterfaceLayout initialLayout The starting layout (defaults to the seeded two-workspace layout). + * @param ViewportHost? viewportHost The platform GL viewport injector, or null for placeholders. + * @param Map spaceOverrides Per-kind space descriptors layered over the base registry. + * @param List propertyTabOverrides Property tabs layered over the base tab set (a vendor extension seam). + * @param CommandRegistry commandRegistry The action registry (the app may pre-register commands). + * @param List appMenu The application menu-bar contents, shown to the left of the workspace tabs; empty + * (the default) renders no bar. The app supplies it because its items close over app-specific state + * (the open document, the file picker), while the bar component itself is shared. + * @param ArtworkOperations? artwork The app's artwork orchestrations (add a file, reload the listed + * files, relink a tile, match or replace a file's bindings) over the area the command fires in, or + * null (the default) when no open document can take artwork. The shell registers the commands + * itself so the operation strip lands in the hovered work surface. + * @param Function? exportImage Export Image, handed the 2D viewport area it should frame (or null when the + * pointer last touched none), or null (the default) when nothing can be captured. The shell registers the + * command itself because only its routing knows which viewport the rigger means. + * @param String languageTag The active UI language (BCP-47). + * @param Keymap keymap The active keymap (defaults to the built-in default preset; the persistent wrapper + * injects the settings-resolved keymap so a preset change or a rebind takes effect everywhere at once). + * @param Function onLayoutChange Called with every new layout, for persistence. + * @param Function onLayoutDragChange Called with true when a splitter drag begins and false when it + * ends; the persistence wrapper holds the debounced write while the drag is live and commits + * immediately at its end. The signal carries no layout and publishes nothing, so it bypasses + * [WorkspaceLayoutController] on purpose - a controller pass-through would add API for no state. + */ +@Composable +fun EditorShell( + initialLayout: InterfaceLayout = defaultLayout(), + viewportHost: ViewportHost? = null, + spaceOverrides: Map = emptyMap(), + propertyTabOverrides: List = emptyList(), + commandRegistry: CommandRegistry = remember { CommandRegistry() }, + appMenu: List = emptyList(), + languageTag: String = "en", + keymap: Keymap = defaultKeymap(), + onLayoutChange: (InterfaceLayout) -> Unit = {}, + onLayoutDragChange: (Boolean) -> Unit = {}, + artwork: ArtworkOperations? = null, + exportImage: ((viewportAreaId: String?) -> Unit)? = null, +) { + // The layout controller outlives recompositions, so it publishes through a live reference to the + // persistence hook rather than capturing the first composition's lambda. + val currentOnLayoutChange by rememberUpdatedState(onLayoutChange) + val currentOnLayoutDragChange by rememberUpdatedState(onLayoutDragChange) + // Read at dispatch for the same reason: the command table registers once per session, and the app + // hands in a fresh collaborator per composition. + val currentArtwork by rememberUpdatedState(artwork) + val currentExportImage by rememberUpdatedState(exportImage) + val workspaces = + remember { WorkspaceLayoutController(initialLayout) { newLayout -> currentOnLayoutChange(newLayout) } } + // Quick Setup's visibility is the app's, held across the document swaps that rebuild this shell; read once, + // since the app's holder lives as long as the app and the command tables below close over these overlays. + val quickSetup = LocalQuickSetup.current + val overlays = remember { quickSetup?.let(::ShellOverlayState) ?: ShellOverlayState() } + // The localized base name new and imported workspaces are named from (deduped) - the same string the "+" + // button passes to onCreate, so the menu's New Workspace and the tab strip agree. + val newWorkspaceBaseName = stringResource(Res.string.workspace_new_name) + val spaceRegistry = remember(spaceOverrides) { defaultSpaceRegistry().withOverrides(spaceOverrides) } + val propertyTabRegistry = + remember(propertyTabOverrides) { defaultPropertyTabRegistry().withOverrides(propertyTabOverrides) } + val focusRequester = remember { FocusRequester() } + val dragController = remember { AreaDragController() } + // Shared with the menu bar so this shell's root key handler can dismiss an open menu before the keymap + // claims the same key (Escape is bound to area.dragCancel). See the onPreviewKeyEvent below. + val menuBarController = remember { MenuBarController() } + // Shared with inline editors (workspace rename) so that while one is open this shell's root key handler + // yields the keyboard to the field - routing Escape to cancel and suppressing its own shortcuts. + val inlineEditController = remember { InlineEditController() } + val keyCapture = remember { KeyCaptureController() } + // Shared with the row-dragging panels (outliner, parameters): while a row drag is in flight its cancel + // is parked here, so the root key handler can route Escape to abort the drag before the clear-selection + // branch would swallow it. One pointer means at most one in-flight drag anywhere, so one slot serves + // every panel. + val rowDragCancel = remember { RowDragCancelController() } + // Shared with the area tree: a divider drag keeps its session inside the dragged SplitContainer, so + // while one is in flight that container parks its cancel here for the root Escape precedence to + // reach - the corner-drag equivalent of what dragController already exposes directly. + val splitterDragCancel = remember { SplitterDragCancelController() } + // The one in-flight relation pick (a Properties field's eyedropper), resolved by whichever surface the + // user clicks next - the viewport pick overlay or an outliner row - and cancelled by Escape. + val relationPick = remember { RelationPickController() } + // The last-touched editor surface (area id + space kind), stamped by every workspace leaf and read by + // command handlers at dispatch time - the ONE answer to "which area does the pointer mean" (see + // HoveredSurface.kt for the dispatch-time-only contract). + val hoveredSurfaces = remember { HoveredSurfaceTracker() } + // The keyable property under the pointer, so a keyform insert needs no prior selection. + val keyableHover = remember { KeyableHover() } + val keyformSheetViews = remember { KeyformSheetViews() } + // The camera-bearing areas' per-area controllers, registered by each 2D viewport and UV space for + // its lifetime; the view commands resolve the hovered area here at dispatch time (one hub for both + // surfaces). + val areaCameras = remember { AreaCameraHub() } + // The pointer's last position in shell-root pixels (null before any pointer event), observed on the + // Initial pass below so it tracks through any gesture. Anchors the shell-level cursor overlays - + // the pie menu ring and near-cursor notices - which render above the area tree so they escape area + // bounds and exist exactly once (see ShellCursorOverlays.kt). + var shellPointerPosition by remember { mutableStateOf(null) } + // The split arm distance is in dp; convert it once to the px the controller hit-tests in. + dragController.splitThresholdPx = with(LocalDensity.current) { SPLIT_ARM_DISTANCE.toPx() } + + // The shell's command tables (the commands/ package), registered per group: each group's effect keys + // on the state its handlers close over, and registerAll returns the matching cleanup so registration + // and unregistration can never drift apart. + // + // ONE routing seam serves every group, remembered for the shell's lifetime. It closes over nothing but + // the tracker and the layout controller (both remembered for the same lifetime, and both read live at + // dispatch), so it cannot go stale across a document swap and the groups that must NOT re-register on + // one can hold it safely. + val service = LocalPuppetViewportService.current + val routing = + remember { + CommandRouting( + { hoveredSurfaces.lastTouched }, + { hoveredSurfaces.lastTouchedStripHost }, + { workspaces.layout.activeWorkspace()?.root?.firstLeafOrNull { leaf -> leaf.space.hostsOperationStrip }?.id }, + { hoveredSurfaces.lastTouchedViewport }, + ) + } + // Read at dispatch: the chrome table registers once, and the handler the platform provides is the + // composition's to change. + val currentUriHandler by rememberUpdatedState(LocalUriHandler.current) + DisposableEffect(commandRegistry, dragController) { + val cleanup = + commandRegistry.registerAll( + chromeCommands(overlays, dragController, splitterDragCancel, rowDragCancel, workspaces) { url -> currentUriHandler.openLinkQuietly(url) }, + ) + onDispose { cleanup() } + } + DisposableEffect(commandRegistry) { + val cleanup = + commandRegistry.registerAll( + workspaceCommands(workspaces, overlays, newWorkspaceBaseName) + documentCommands(overlays), + ) + onDispose { cleanup() } + } + // Viewport navigation commands dispatch to the hovered surface at invocation time: the hovered + // area's camera controller through the hub (2D viewport or UV editor), a no-op when none is + // registered. Re-registered when the render service changes (a new document / renderer), which + // flips the availability gate. + DisposableEffect(commandRegistry, service) { + val cleanup = commandRegistry.registerAll(viewCommands(areaCameras, routing, service != null)) + onDispose { cleanup() } + } + // Frame All resolves the hovered editor to the command that editor means and re-dispatches THAT, so + // it keys on the registry alone: it carries no viewport gate (a keyform sheet frames with no renderer + // at all), and re-registering it on a renderer change would only shuffle its palette position. + DisposableEffect(commandRegistry) { + val cleanup = commandRegistry.registerAll(frameCommands(commandRegistry, routing)) + onDispose { cleanup() } + } + val selection = LocalSelection.current + val editorMode = LocalEditorMode.current + DisposableEffect(commandRegistry, selection, editorMode) { + val cleanup = commandRegistry.registerAll(modeCommands(selection, editorMode)) + onDispose { cleanup() } + } + // The document-scoped groups, re-registered on a document swap so their handlers close over the + // current session. They do not key on the render service: the pointer's area resolves through the + // shared routing seam, which reads it live, so a renderer change has nothing to re-register here. + val editorSession = LocalEditorSession.current + // One tier set shared by every document-scoped group below, so the ten tables hold the same three + // availability objects rather than three apiece. Keyed on the session exactly as their effects are. + val availability = remember(editorSession) { SessionAvailability(editorSession) } + // The repack orchestration the atlas table dispatches: decode + pack off-thread, one commit, the + // refusal report routed through the shell's own modal chrome. Every collaborator here changes + // with the document - and so with the session the effect below keys on - so the closure never + // outlives what it captured. + val shellScope = rememberCoroutineScope() + val artRasters = LocalSourceArtRasters.current + val sessionAtlasPages = LocalSessionAtlasPages.current + val puppetTextures = LocalPuppetTextures.current + // The repack's session memory and the operation settings strip's disclosure state: both live as + // long as the window, across documents, which is why neither keys on the session. + val repackOptions = remember { AtlasRepackSessionOptions() } + val operationStrip = remember { OperationStripState() } + val repackAtlas: ((String?) -> Unit)? = + if (editorSession != null && artRasters != null) { + { areaId -> + val host = + AtlasRepackHost( + session = editorSession, + artRasters = artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = puppetTextures?.premultipliedAlpha ?: false, + scope = shellScope, + report = { refusalReport -> commandRegistry.invoke("document.repackReport", refusalReport) }, + rememberOptions = { options, keepPinned -> repackOptions.record(editorSession, options, keepPinned) }, + ) + val options = repackOptions.optionsFor(editorSession, repackPageSizeOf(editorSession.model.value)) + val keepPinned = repackOptions.keepPinnedFor() + shellScope.launch { runAtlasRepack(host, options, areaId, keepPinned) } + } + } else { + null + } + DisposableEffect(commandRegistry, editorSession, selection) { + val cleanup = + commandRegistry.registerAll( + historyCommands(editorSession, availability, operationStrip) + + objectCommands(editorSession, selection, availability) + + transformCommands(editorSession, routing, availability) + + selectCommands(editorSession, routing, keyformSheetViews, availability) + + snapCommands(editorSession, routing, availability) + + uvCommands(editorSession, routing, availability) + + topologyCommands(editorSession, routing, availability) + + proportionalCommands(editorSession, availability) + + displayCommands(editorSession, availability) + + atlasCommands(availability, routing, repackAtlas) + + fileArtworkCommands(routing) { currentArtwork } + + fileImageExportCommands(routing) { currentExportImage }, + ) + onDispose { cleanup() } + } + // The keyform-authoring group, its own table because it closes over the hovered KEYABLE rather than + // the session alone - the property the insert / delete write to, resolved at dispatch time. + DisposableEffect(commandRegistry, editorSession) { + val hoveredKeyable: () -> KeyformHover? = { keyableHover.hovered } + val cleanup = + commandRegistry.registerAll( + keyformCommands(editorSession, hoveredKeyable, routing, keyformSheetViews, availability), + ) + onDispose { cleanup() } + } + + // THE focus-reclaim effect. Compose leaves focus null whenever the focused node leaves composition + // (a join/split disposing the focused leaf, a closing overlay/popup/menu/inline editor taking its + // field along), and a null focus silently kills every keyboard shortcut until the next click - so the + // root must reclaim focus after each such transition. One effect keyed on every reclaim trigger: + // - structuralEditCount: area-tree edits and popup-invoked workspace CRUD; + // - selfFocusedOverlayOpen / inline edit: reclaim when the palette, preferences, Help dialogs, or an + // inline rename CLOSE (while one is open it owns focus, so the effect waits); + // - modalAlertOpen: the confirm dialog, the file-open alert, the export report, and the repack + // refusal report do NOT own focus - root focus is (re)claimed on open too, so their Escape/Enter + // route through the modal ladder while open; + // - menu-bar close: an open menu's popup holds focus and its teardown takes it along. + // The two-frame wait lets a closing popup's teardown finish stealing focus first - an immediate + // request would be nulled right back out (the menu bar demonstrably needs this; it is harmless for + // the other triggers). + val overlaySelfFocused = overlays.selfFocusedOverlayOpen || inlineEditController.cancel != null + val menuBarOpen = menuBarController.closeOpenMenu != null + LaunchedEffect(workspaces.structuralEditCount, overlaySelfFocused, overlays.modalAlertOpen, menuBarOpen) { + if (overlaySelfFocused || menuBarOpen) { + return@LaunchedEffect + } + withFrameNanos {} + withFrameNanos {} + focusRequester.requestFocus() + } + + // An OS-level focus round-trip (alt-tab away and back) restores focus to the WINDOW but to no Compose + // node - whatever was focused before the blur stays unfocused, so onPreviewKeyEvent never fires and + // every shortcut is dead until something focusable is clicked. Reclaim root focus on window-focus + // regain. Skipped while an overlay that owns its own focus is up (the reclaim effect above covers + // their close); the guard reads the live state inside the collector, never captures. + val windowInfo = LocalWindowInfo.current + LaunchedEffect(windowInfo) { + snapshotFlow { windowInfo.isWindowFocused }.collect { windowFocused -> + val overlayOwnsFocus = + inlineEditController.cancel != null || + overlays.selfFocusedOverlayOpen || + overlays.modalAlertOpen + if (windowFocused && !overlayOwnsFocus) { + focusRequester.requestFocus() + } + } + } + + ProvideAppLocale(languageTag) { + UmamoTheme { + CompositionLocalProvider( + LocalCommands provides commandRegistry, + LocalKeymap provides keymap, + LocalSpaceRegistry provides spaceRegistry, + LocalPropertyTabRegistry provides propertyTabRegistry, + LocalViewportHost provides viewportHost, + LocalAreaDragController provides dragController, + LocalMenuBarController provides menuBarController, + LocalInlineEditController provides inlineEditController, + LocalKeyCapture provides keyCapture, + LocalRowDragCancel provides rowDragCancel, + LocalSplitterDragCancel provides splitterDragCancel, + LocalKeyableHover provides keyableHover, + LocalKeyformSheetViews provides keyformSheetViews, + LocalRelationPick provides relationPick, + LocalHoveredSurfaceTracker provides hoveredSurfaces, + LocalAreaCameraHub provides areaCameras, + LocalOperationStrip provides operationStrip, + ) { + // The window-wide cursor: hidden under an armed relation pick (the shell draws the eyedropper + // itself), the editor's I-beam while text entry is live, and otherwise nothing of its own. + // Claiming it here rather than in each viewport is what makes a mode announce itself the + // instant it begins, wherever the pointer happens to be sitting. + val cursorClaim = + shellCursorClaim( + relationPickArmed = relationPick.request != null, + textEntryActive = inlineEditController.cancel != null, + ) + val claimedPointerIcon = + remember(cursorClaim) { + when (cursorClaim) { + ShellCursorClaim.Hidden -> hiddenPointerIcon() + ShellCursorClaim.TextEdit -> PointerIcon.Text + ShellCursorClaim.None -> PointerIcon.Default + } + } + Surface( + modifier = + Modifier + .fillMaxSize() + .focusRequester(focusRequester) + .focusable() + // Declared once on a node that lives the whole time, never mounted when a mode starts: a + // hover icon that appears mid-gesture is not consulted until the pointer next MOVES, and + // text entry begins with a click the hand then rests on - the I-beam would never appear. + // The unclaimed case resolves to the plain pointer, which is what an unclaimed pointer + // already resolves to, so with no mode running the descendants still decide. + .pointerHoverIcon(claimedPointerIcon, overrideDescendants = cursorClaim.overridesDescendants) + // The window-space pointer tracker for the shell cursor overlays. On the root + // surface, whose content Box shares this coordinate space, so the observer and + // the overlays agree on positions. + .pointerInput(Unit) { + observeWindowPointer { position -> shellPointerPosition = position } + } + // The press that ends text entry, so a filter cannot keep the keyboard after the pointer + // has moved on. Its own observer rather than a branch of the tracker above: that one is + // an always-on position feed, this one is a per-press state machine over the claim slot. + .pointerInput(Unit) { + observeTextEntryPresses( + beginPress = { inlineEditController.pressLandedOnTextEditor = false }, + settlePress = { + val releases = + shouldReleaseTextEntry( + textEntryActive = inlineEditController.cancel != null, + pressLandedOnTextEditor = inlineEditController.pressLandedOnTextEditor, + selfFocusedOverlayOpen = overlays.selfFocusedOverlayOpen, + ) + if (releases) { + // Take focus, never clear it: a null focus owner silently kills every + // shortcut. Moving focus still fires each control's + // onFocusChanged(hasFocus = false), and that is what commits an inline + // rename and unparks the cancel hook. + focusRequester.requestFocus() + } + }, + ) + } + // Root key handling is the modal ladder (ModalKeyLadder.kt): modal chrome and + // in-flight gestures pre-empt the keymap in stacking order; whatever the ladder + // does not consume falls through to the keymap + action registry. + .onPreviewKeyEvent { event -> + handleModalKeyLadder( + stroke = event.toShellKeyStroke(), + state = + ShellModalState( + overlays = overlays, + menuBarController = menuBarController, + inlineEditController = inlineEditController, + keyCapture = keyCapture, + editorSession = editorSession, + selection = selection, + dragController = dragController, + splitterDragCancel = splitterDragCancel, + rowDragCancel = rowDragCancel, + relationPick = relationPick, + keyformSheets = keyformSheetViews, + commandRegistry = commandRegistry, + keymap = keymap, + ), + ) + }, + color = LocalUmamoColors.current.windowBackground, + ) { + Column(modifier = Modifier.fillMaxSize()) { + // The menu bar shares the tab strip's row, sitting to its left to save vertical space; the + // tabs take the remaining width. With no menu (e.g. on Android this slice) only the tabs show. + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + if (appMenu.isNotEmpty()) { + MenuBar(menus = appMenu) + } + Box( + modifier = + Modifier + .padding(horizontal = 4.dp) + .height(14.dp).width(1.dp) + .background(LocalUmamoColors.current.guideLine), + ) + WorkspaceTabs( + workspaces = workspaces.layout.workspaces, + activeId = workspaces.layout.activeWorkspaceId, + onSelect = { workspaceId -> workspaces.setActiveWorkspace(workspaceId) }, + onCreate = { suggestedName -> workspaces.create(suggestedName) }, + onDuplicate = { sourceId, suggestedName -> + workspaces.duplicate( + sourceId, + suggestedName, + ) + }, + onDelete = { targetId -> workspaces.delete(targetId) }, + onReorder = { fromIndex, toIndex -> workspaces.reorder(fromIndex, toIndex) }, + onRename = { workspaceId, newName -> workspaces.rename(workspaceId, newName) }, + modifier = Modifier.weight(1f), + ) + } + Box( + modifier = + Modifier + .weight(1f) + .fillMaxWidth() + // The one shared space: leaf rects and the drag overlay are both resolved against this Box. + .onGloballyPositioned { coordinates -> dragController.contentCoords = coordinates }, + ) { + val active = workspaces.layout.activeWorkspace() + // The corner-drag controller needs the live root to test sibling-ness on release. + dragController.currentRoot = active?.root + if (active != null) { + AreaTree( + node = active.root, + onNodeChange = { newRoot -> workspaces.updateActiveRoot(newRoot) }, + onCommand = { command -> workspaces.applyAreaCommand(command) }, + modifier = Modifier.padding(4.dp), + onSplitterDragChange = { dragActive -> currentOnLayoutDragChange(dragActive) }, + ) + } + // Visual-only join highlight, painted last so it floats above the tree (and the offscreen viewport). + AreaDragOverlay(controller = dragController, modifier = Modifier.fillMaxSize()) + } + // The bottom status strip is the Column's last child: fixed-height chrome under the + // weight(1f) content Box, so the area tree fills the gap between the tabs and the strip. + StatusBar(modifier = Modifier.fillMaxWidth()) + } + // The shell-level cursor overlays: near-cursor notices, then the pie menu (which owns the + // pointer while open). Siblings of the Column so they float above the whole area tree - + // escaping viewport bounds - and BELOW the modal dialogs that follow. + ShellNearCursorNotice(pointerPosition = shellPointerPosition) + ShellPieMenuHost(pointerPosition = shellPointerPosition) + ShellRelationPickOverlay(pointerPosition = shellPointerPosition) + ShellParameterChoiceMenu(pointerPosition = shellPointerPosition) + // Modal overlays are siblings of the Column (Surface stacks its content in a Box), so their + // full-window scrims cover the menu bar and tab strip too: a click anywhere outside the + // overlay's card dismisses it, and the chrome behind is not interactable while it is open + // (so the palette cannot be left open under a menu-bar-launched window). Painted + // bottom-to-top: palette, preferences, the Help dialogs, Quick Setup, the export-options + // dialog, the file-open alert, the export report, the repack refusal report, then the confirm + // dialog (the topmost modal). + if (overlays.paletteVisible) { + // The space the palette was summoned over, read once per open. The palette's scrim + // keeps every leaf from stamping while it is up, so this is also the surface the + // registry resolves when the chosen command runs - the list and the dispatch cannot + // disagree about where the pointer is. + val paletteSurfaceKind = remember { hoveredSurfaces.observedKind } + // Remembered because this scope recomposes on every pointer move (it reads the shell + // pointer position), and a fresh list each time would re-query every availability and + // recompose the palette with it. The palette is modal, so nothing changes what applies + // while it is up; the revision covers the table itself. + val paletteList = + remember(commandRegistry.revision, paletteSurfaceKind) { + paletteCommands(commandRegistry.all(), paletteSurfaceKind) + } + CommandPalette( + commands = paletteList, + onDismiss = { overlays.paletteVisible = false }, + onInvoke = { command -> + overlays.paletteVisible = false + commandRegistry.invoke(command.id) + }, + ) + } + // The preferences overlay; auto-saves every change, so closing it is the only action it needs. + if (overlays.settingsVisible) { + SettingsWindow(onDismiss = { overlays.settingsVisible = false }) + } + // The Help dialogs, in the same modal family (below the confirm dialog in paint order). + if (overlays.aboutVisible) { + AboutDialog(onDismiss = { overlays.aboutVisible = false }) + } + if (overlays.creditsVisible) { + CreditsDialog(onDismiss = { overlays.creditsVisible = false }) + } + // Quick Setup, open on a first run. Above the Help dialogs, and below the alerts, so a message a + // first launch raises (a read-only document from the command line) still shows over it. + if (overlays.quickSetupVisible) { + QuickSetupDialog(onDismiss = { overlays.quickSetupVisible = false }) + } + // The export-options dialog, the last of the self-focused family (its number field owns + // focus); the modal alerts below still paint above it. The request's continuation runs + // from its own Export button, so dismissal here is unconditional. + overlays.pendingExportOptions?.let { request -> + ExportOptionsDialog( + request = request, + onDismiss = { overlays.pendingExportOptions = null }, + ) + } + // The file-open failure alert, in the same modal family (below the confirm dialog in paint order). + overlays.openFailure?.let { failure -> + MessageDialog( + message = stringResource(openFailureMessage(failure.error), failure.displayName), + onDismiss = { overlays.openFailure = null }, + ) + } + // A message the app layer raised (document.alert), in the same modal family. + overlays.pendingAlert?.let { alert -> + MessageDialog( + message = stringResource(alert.message, *alert.arguments.toTypedArray()), + onDismiss = { overlays.pendingAlert = null }, + ) + } + // The export report, in the same modal family: advisory only - the export has already + // been written when it shows. + overlays.exportReport?.let { report -> + MessageDialog( + message = exportReportMessage(report), + onDismiss = { overlays.exportReport = null }, + ) + } + // The repack refusal report, same modal family. Unlike the export report it describes + // work that did NOT happen: the repack aborted whole rather than dropping these tiles. + overlays.repackReport?.let { report -> + MessageDialog( + message = repackReportMessage(report), + onDismiss = { overlays.repackReport = null }, + ) + } + // A destructive command raised a confirm: a modal scrim over the whole shell, painted last + // so it floats above the tabs, the area tree, the palette, and the settings window. + overlays.pendingConfirm?.let { request -> + ConfirmDialog( + // Format only when the prompt takes arguments: an argument-free prompt may carry a + // literal % (a scale, a progress figure) that a formatter would choke on. + message = + if (request.arguments.isEmpty()) { + stringResource(request.message) + } else { + stringResource(request.message, *request.arguments.toTypedArray()) + }, + onConfirm = { overlays.confirmPending() }, + onCancel = { overlays.cancelPending() }, + confirmLabel = stringResource(request.confirmLabel), + cancelLabel = stringResource(request.cancelLabel), + alternative = + request.alternative?.let { alternative -> + DialogChoice(stringResource(alternative.label)) { overlays.choosePendingAlternative() } + }, + ) + } + } + } + } + } +} + +/** + * Builds the export-report alert's text: the localized header, then one line per notice. + * + * Every line is localized from the notice's structured fields - the entity category, the reason and + * whatever it carries, the affected drawable names, the missing page count, or the stripped feature + * and the entities that carried it. The only text passed through verbatim is document data: an + * entity's own id, which is format-level and must never be translated. + * + * The header names the format the export actually wrote, from the report's own discriminator - a + * notice reads identically for either format, so nothing else in the alert says which file the + * rigger is being told about. + * + * @param ExportReport report The export's advisory report. + * @return String The multiline alert text. + */ +@Composable +private fun exportReportMessage(report: ExportReport): String { + val lines = ArrayList(report.notices.size + 1) + lines.add( + stringResource( + when (report.format) { + ExportFormat.Cmo3 -> Res.string.export_report_message_cmo3 + ExportFormat.Moc3 -> Res.string.export_report_message_moc3 + }, + ), + ) + for (notice in report.notices) { + when (notice) { + is ExportNotice.UnsupportedChange -> { + val categoryLabel = stringResource(exportEntityCategoryLabelRes(notice.category)) + val reasonText = exportNoticePhraseText(exportNoticeReasonPhrase(notice.reason)) + // A document-level finding has no entity to name; its reason names the field instead. + lines.add( + if (notice.subject == null) { + "• [$categoryLabel] $reasonText" + } else { + "• [$categoryLabel] ${notice.subject}: $reasonText" + }, + ) + } + + is ExportNotice.WeldDivergence -> + lines.add("• " + stringResource(Res.string.export_weld_divergence, notice.drawableNames.joinToString())) + + is ExportNotice.MissingSourceArt -> + lines.add("• " + stringResource(Res.string.export_missing_source_art, notice.pageCount)) + + is ExportNotice.SharedAtlasSlotKept -> + lines.add("• " + stringResource(Res.string.export_shared_atlas_slot_kept, abbreviatedSubjects(notice.drawableNames))) + + is ExportNotice.FeatureStripped -> + lines.add( + "• " + + stringResource( + Res.string.export_feature_stripped, + stringResource(runtimeFeatureLabelRes(notice.feature)), + abbreviatedSubjects(notice.subjects), + ), + ) + } + } + return lines.joinToString("\n") +} + +/** + * Builds the repack refusal alert's text: the localized header, then one line per refused tile. + * + * The tile names are document data, shown verbatim; only the reasons are localized. + * + * @param AtlasRepackReport report The refusal report. + * @return String The multiline alert text. + */ +@Composable +private fun repackReportMessage(report: AtlasRepackReport): String { + val lines = ArrayList(report.refusals.size + 1) + lines.add(stringResource(Res.string.repack_report_message)) + for (refusal in report.refusals) { + val reasonText = + stringResource( + when (refusal.reason) { + AtlasRepackRefusalReason.LargerThanPage -> Res.string.repack_report_larger_than_page + AtlasRepackRefusalReason.NoOpaquePixels -> Res.string.repack_report_no_opaque_pixels + AtlasRepackRefusalReason.BelowMinimumCoverage -> Res.string.repack_report_below_minimum_coverage + AtlasRepackRefusalReason.Undecodable -> Res.string.repack_report_undecodable + AtlasRepackRefusalReason.DegeneratePlacement -> Res.string.repack_report_degenerate_placement + AtlasRepackRefusalReason.PinnedOffPage -> Res.string.repack_report_pinned_off_page + }, + ) + lines.add("• ${refusal.tileName} - $reasonText") + } + return lines.joinToString(separator = "\n") +} + +/** + * A subject list short enough for an alert: the first few names, then how many were left out. + * + * Stripping a 5.3 feature out of a large rig names every drawable that carried it - a thousand-name + * line in a dialog nobody can dismiss past. The report itself keeps the full list; only this display + * abbreviates, so a caller that wants them all (a log, a future report panel) still has them. + * + * @param List subjects The affected entities' names. + * @return String The display text. + */ +@Composable +private fun abbreviatedSubjects(subjects: List): String { + val shown = subjects.take(SUBJECTS_SHOWN) + if (shown.size == subjects.size) { + return shown.joinToString() + } + return shown.joinToString() + " " + stringResource(Res.string.export_more_subjects, subjects.size - shown.size) +} + +/** How many affected entities an export notice spells out before counting the rest. */ +private const val SUBJECTS_SHOWN: Int = 8 + +/** + * Resolves a document-open failure to its localized alert message resource. Every message takes the + * file's display name as its one format argument. + * + * @param DocumentOpenError error The failure reason reported by the document loader. + * @return StringResource The message resource for the file-open alert dialog. + */ +private fun openFailureMessage(error: DocumentOpenError): StringResource = + when (error) { + DocumentOpenError.ReadFailed -> Res.string.open_failed_read + DocumentOpenError.Unrecognized -> Res.string.open_failed_unrecognized + DocumentOpenError.NotOpenable -> Res.string.open_failed_not_openable + DocumentOpenError.ParseFailed -> Res.string.open_failed_parse + DocumentOpenError.MissingManifest -> Res.string.open_failed_missing_manifest + DocumentOpenError.MissingTexture -> Res.string.open_failed_missing_texture + DocumentOpenError.NoArtLayers -> Res.string.open_failed_no_art_layers + DocumentOpenError.NewerFormat -> Res.string.open_failed_newer_format + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorShellPersistence.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorShellPersistence.kt new file mode 100644 index 0000000..eb142a5 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorShellPersistence.kt @@ -0,0 +1,163 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.drop +import org.umamo.settings.Settings +import org.umamo.storage.FileKitFilePicker +import org.umamo.storage.FilePicker +import org.umamo.ui.LocalSettings +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.rememberLiveKeymap +import org.umamo.ui.kit.TopLevelMenu +import org.umamo.ui.l10n.rememberLocaleTag +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.commands.ArtworkOperations +import org.umamo.ui.workspace.commands.logCommands +import org.umamo.ui.workspace.commands.registerAll +import org.umamo.ui.workspace.commands.viewportChromeCommands +import org.umamo.ui.workspace.commands.workspaceFileCommands + +/** How long to coalesce rapid layout edits (structural bursts) before writing to disk. */ +private const val PERSIST_DEBOUNCE_MS = 400L + +/** + * The settings-backed [EditorShell]: loads the persisted layout at startup (seeding defaults on first + * run), drives the UI language from the localization.locale setting (reacting to changes), and + * debounce-persists layout edits back to settings. Splitter drags are paced separately through a + * [LayoutSavePacer]: no write happens while the drag is held (even across a mid-drag pause longer + * than the debounce), and the release commits exactly one write. + * + * Kept separate from [EditorShell] so the shell itself stays Settings-free and unit-testable; this is + * the thin wrapper apps mount. + * + * @param ViewportHost? viewportHost The platform GL viewport injector, or null for placeholders. + * @param Map spaceOverrides Per-kind space descriptors layered over the base registry. + * @param CommandRegistry commandRegistry The action registry (the app may pre-register commands). + * @param List appMenu The application menu-bar contents, forwarded to the shell (empty renders no bar). + * @param ArtworkOperations? artwork The app's artwork orchestrations over the hovered area, forwarded + * to the shell; null (the default) when no open document can take artwork. + * @param Function? exportImage Export Image over the 2D viewport area the shell resolves, forwarded to the + * shell; null (the default) when nothing can be captured. + * @param FilePicker filePicker The native open and save dialogs the workspace file commands and the log + * export go through; the app passes the one it already holds. + */ +@OptIn(FlowPreview::class) +@Composable +fun PersistentEditorShell( + viewportHost: ViewportHost? = null, + spaceOverrides: Map = emptyMap(), + commandRegistry: CommandRegistry = remember { CommandRegistry() }, + appMenu: List = emptyList(), + artwork: ArtworkOperations? = null, + exportImage: ((viewportAreaId: String?) -> Unit)? = null, + filePicker: FilePicker = remember { FileKitFilePicker() }, +) { + val settings = LocalSettings.current + val initialLayout = remember { loadLayout(settings) } + var latestLayout by remember { mutableStateOf(initialLayout) } + val savePacer = remember(settings) { LayoutSavePacer(initialLayout) { layout -> saveLayout(settings, layout) } } + // The open document's view states key onto this layout's area ids, so they follow it live (UMA §7.3). + val areaViewStates = LocalAreaViewStates.current + SideEffect { + areaViewStates?.layoutAreaIds = latestLayout.workspaces.flatMap { workspace -> workspace.root.leafAreaIds() } + } + + // The active locale follows the localization.locale setting and updates live when it changes. + val locale by rememberLocaleTag(settings) + + // The active keymap follows the keymap settings live, so a preset switch or a rebind in the settings + // window takes effect across menus, the palette, and live dispatch at once. + val keymap by rememberLiveKeymap(settings) + + // Persist layout edits, debounced: snapshotFlow observes the latest layout, drop(1) skips the + // initial value, and debounce coalesces a structural burst into one disk write. The pacer holds + // the write while a splitter drag is live and suppresses the duplicate after a drag-end commit. + LaunchedEffect(settings) { + snapshotFlow { latestLayout } + .drop(1) + .debounce(PERSIST_DEBOUNCE_MS) + .collect { layout -> savePacer.saveDebounced(layout) } + } + + // The viewport chrome flags follow their settings keys reactively, so the toggle commands (and any + // external write) take effect across every viewport at once. + val viewportChrome by produceState(initialValue = loadViewportChrome(settings), settings) { + settings.changes.collect { changedKey -> + if (changedKey == SHOW_TOOLBAR_SETTINGS_KEY || changedKey == SHOW_SIDEBAR_SETTINGS_KEY) { + value = loadViewportChrome(settings) + } + } + } + + // The chrome toggles are registered here rather than in EditorShell because they write settings, and + // the shell itself stays Settings-free (its documented contract); the standalone shell simply lacks + // them, the same division as the app-registered File commands. + DisposableEffect(settings, commandRegistry) { + val cleanup = commandRegistry.registerAll(viewportChromeCommands(settings)) + onDispose { cleanup() } + } + + // The workspace layout's file commands and the log export register here for the same reason: the + // exports read the persisted layout from settings. None of them needs a document, so they are live + // from launch, on every platform that mounts this shell. + val fileScope = rememberCoroutineScope() + val workspaceFiles = + remember(settings, filePicker, commandRegistry, savePacer) { + // An export commits the layout the debounce is still holding, through the pacer and so under its + // rules: nothing is written while a splitter drag is held, and nothing twice. + WorkspaceLayoutFiles(settings, filePicker, fileScope, commandRegistry) { savePacer.saveDebounced(latestLayout) } + } + DisposableEffect(workspaceFiles, commandRegistry) { + val cleanup = + commandRegistry.registerAll( + workspaceFileCommands( + onImport = workspaceFiles::importWorkspace, + onExportThis = workspaceFiles::exportThisWorkspace, + onExportAll = workspaceFiles::exportAllWorkspaces, + ) + logCommands { exportLogToFile(filePicker, fileScope) }, + ) + onDispose { cleanup() } + } + + CompositionLocalProvider(LocalViewportChrome provides viewportChrome) { + EditorShell( + initialLayout = initialLayout, + viewportHost = viewportHost, + spaceOverrides = spaceOverrides, + commandRegistry = commandRegistry, + appMenu = appMenu, + languageTag = locale, + keymap = keymap, + onLayoutChange = { layout -> latestLayout = layout }, + onLayoutDragChange = { dragActive -> savePacer.setDragActive(dragActive, latestLayout) }, + artwork = artwork, + exportImage = exportImage, + ) + } +} + +/** + * Reads the viewport chrome flags from settings (bundled defaults included), falling back to the + * standalone defaults for a missing key. + * + * @param Settings settings The merged settings tree. + * @return ViewportChromeState The current chrome visibility flags. + */ +private fun loadViewportChrome(settings: Settings): ViewportChromeState = + ViewportChromeState( + showToolbar = settings.getBoolean(SHOW_TOOLBAR_SETTINGS_KEY) ?: true, + showSidebar = settings.getBoolean(SHOW_SIDEBAR_SETTINGS_KEY) ?: false, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorStateJson.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorStateJson.kt new file mode 100644 index 0000000..f58ef34 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/EditorStateJson.kt @@ -0,0 +1,143 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.floatOrNull +import kotlinx.serialization.json.intOrNull +import org.umamo.ui.viewport.CameraSurface + +/* + * The editor entry's reading and writing kit (docs/format/UMA.md §7). The entry is a dynamic tree read + * tolerantly: every reader here answers null for a member that is absent, of the wrong JSON type, or out of + * range, and the caller keeps its default - nothing in editor state is worth refusing a file over (UMA §7.1). + * Every writer names a member whatever its state, a JSON null standing for "at the default", because the entry + * is saved as a merge patch and a merge alone could never take a deviation back out (UMA §7.5). + */ + +/** The root member holding each area's block, keyed by area id (UMA §7.2). */ +const val EDITOR_STATE_AREAS: String = "areas" + +/** An area block's cameras member: a `[centerX, centerY, zoom]` per surface the area has shown (UMA §7.3). */ +internal const val AREA_CAMERAS_MEMBER: String = "cameras" + +/** + * A camera surface's name in an area block's `cameras`. + * + * @param CameraSurface surface The surface. + * @return String The wire name. + */ +internal fun cameraSurfaceWireName(surface: CameraSurface): String = + // UMA §7.3: `cameras`. + when (surface) { + CameraSurface.Viewport -> "viewport" + CameraSurface.Uv -> "uv" + } + +/** An area block's members in the order a writer lays them down (UMA §7.3, §7.5). */ +internal val AREA_BLOCK_MEMBER_ORDER: List = listOf("cameras", "outliner", "sources", "parameters", "keyformSheet", "properties", "uv") + +/** + * The strings of the array at [memberName], or null when the member is absent or not an array. An element that + * is not a string is skipped. + * + * @param JsonObject tree The object holding the member. + * @param String memberName The member's name. + * @return List? The strings, or null. + */ +internal fun stringListOf(tree: JsonObject, memberName: String): List? = + (tree[memberName] as? JsonArray)?.mapNotNull { element -> (element as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.content } + +/** + * The string at [memberName], or null when the member is absent or not a string. + * + * @param JsonObject tree The object holding the member. + * @param String memberName The member's name. + * @return String? The string, or null. + */ +internal fun stringOf(tree: JsonObject, memberName: String): String? = (tree[memberName] as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.content + +/** + * The boolean at [memberName], or null when the member is absent or not a boolean. + * + * @param JsonObject tree The object holding the member. + * @param String memberName The member's name. + * @return Boolean? The boolean, or null. + */ +internal fun booleanOf(tree: JsonObject, memberName: String): Boolean? = (tree[memberName] as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.booleanOrNull + +/** + * The finite float [element] holds, or null when it is not a number, or is a NaN or an infinity. + * + * @param JsonElement? element The element. + * @return Float? The float, or null. + */ +internal fun finiteFloatOf(element: JsonElement?): Float? = (element as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.floatOrNull?.takeIf { value -> value.isFinite() } + +/** + * The integer [element] holds, or null when it is not one. + * + * @param JsonElement? element The element. + * @return Int? The integer, or null. + */ +internal fun intOf(element: JsonElement?): Int? = (element as? JsonPrimitive)?.takeIf { primitive -> !primitive.isString }?.intOrNull + +/** + * The array at [memberName] as exactly [size] finite floats, or null when the member is absent, not an array, of + * another length, or holds anything that is not a finite number. + * + * @param JsonObject tree The object holding the member. + * @param String memberName The member's name. + * @param Int size The length the array must have. + * @return List? The floats, or null. + */ +internal fun floatListOf(tree: JsonObject, memberName: String, size: Int): List? { + val elements = tree[memberName] as? JsonArray ?: return null + if (elements.size != size) { + return null + } + val floats = elements.mapNotNull(::finiteFloatOf) + return floats.takeIf { kept -> kept.size == size } +} + +/** + * [values] as a JSON array of strings in a stable order, or a JSON null when there are none - the form an id + * collection takes in the entry (UMA §7.1), sorted so the same state always writes the same bytes. + * + * @param Collection values The ids. + * @return JsonElement The array, or null. + */ +internal fun stringArrayOrNull(values: Collection): JsonElement = if (values.isEmpty()) JsonNull else JsonArray(values.sorted().map(::JsonPrimitive)) + +/** + * A fold map's deviations from its default rule, as the pair of arrays the entry holds: the ids opened against + * the default and the ids closed against it. An id whose recorded state equals its default is no deviation and + * is left out. + * + * @param Map states Each recorded node's open state. + * @param Function defaultOpen Whether an id is open when nothing is recorded for it. + * @return Pair The opened ids, then the closed ones, each as [stringArrayOrNull] writes them. + */ +internal fun foldDeviationsOf(states: Map, defaultOpen: (String) -> Boolean): Pair { + val opened = states.filter { (nodeId, open) -> open && !defaultOpen(nodeId) }.keys + val closed = states.filter { (nodeId, open) -> !open && defaultOpen(nodeId) }.keys + return stringArrayOrNull(opened) to stringArrayOrNull(closed) +} + +/** + * Lays a saved fold state into [states]: what was recorded goes, the opened ids are open, and the closed ids are + * closed. + * + * @param MutableMap states The fold map to fill. + * @param JsonObject tree The object holding the two arrays. + * @param String openedName The member naming the opened ids. + * @param String closedName The member naming the closed ids. + */ +internal fun restoreFoldStates(states: MutableMap, tree: JsonObject, openedName: String, closedName: String) { + states.clear() + stringListOf(tree, openedName)?.forEach { nodeId -> states[nodeId] = true } + stringListOf(tree, closedName)?.forEach { nodeId -> states[nodeId] = false } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportNoticeLabels.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportNoticeLabels.kt new file mode 100644 index 0000000..3306d5f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportNoticeLabels.kt @@ -0,0 +1,301 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.KeyformBundleRejection +import org.umamo.runtime.model.FormChannel +import org.umamo.ui.properties.formChannelLabelRes +import org.umamo.ui.resources.* + +/* + * Localized text for the export report's findings. :interop carries only the structured facts (see + * ExportNoticeReason); the sentences a rigger reads are assembled here, so the exporters stay + * presentation-free and every locale gets the same coverage. + * + * Each mapping is an exhaustive `when` with no `else`, so a new reason is a compile error here until + * it gets a sentence - the same compile-time completeness EnumLabels.kt relies on. + */ + +/** + * One localizable sentence: the resource to format, plus the arguments to format it with. + * + * A carrier rather than a bare [StringResource] because a third of the reasons take format arguments, + * and two of those arguments are themselves localized. Binding the arguments in the SAME `when` arm + * that picks the resource is what makes a mismatch unrepresentable: there is no second, `else`-bearing + * pass where a new parameterized reason could slip through and render a literal `%1$d`. + * + * @property StringResource resource The sentence template. + * @property List arguments Its format arguments, in placeholder order. + */ +class ExportNoticePhrase( + val resource: StringResource, + val arguments: List = emptyList(), +) + +/** One format argument of an [ExportNoticePhrase]. */ +sealed interface ExportNoticeArgument { + /** + * A value substituted as-is: a count, or document data (an id) that must never be translated. + * + * @property Any value The value to format. + */ + data class Literal(val value: Any) : ExportNoticeArgument + + /** + * Another phrase, resolved and substituted as text. + * + * @property ExportNoticePhrase phrase The nested sentence. + */ + data class Nested(val phrase: ExportNoticePhrase) : ExportNoticeArgument +} + +/** + * The [StringResource] naming an entity category, the bracketed prefix on a notice line. + * + * @param ExportEntityCategory category The category to label. + * @return StringResource The localized label resource. + */ +fun exportEntityCategoryLabelRes(category: ExportEntityCategory): StringResource = + when (category) { + ExportEntityCategory.Parameter -> Res.string.export_category_parameter + ExportEntityCategory.ParameterGroup -> Res.string.export_category_parameter_group + ExportEntityCategory.Part -> Res.string.export_category_part + ExportEntityCategory.Deformer -> Res.string.export_category_deformer + ExportEntityCategory.Drawable -> Res.string.export_category_drawable + ExportEntityCategory.Glue -> Res.string.export_category_glue + ExportEntityCategory.Document -> Res.string.export_category_document + ExportEntityCategory.Keyform -> Res.string.export_category_keyform + } + +/** + * The sentence explaining why one export notice fired. + * + * @param ExportNoticeReason reason The reason to phrase. + * @return ExportNoticePhrase The sentence and its arguments. + */ +fun exportNoticeReasonPhrase(reason: ExportNoticeReason): ExportNoticePhrase = + when (reason) { + // Shared by both export paths. + ExportNoticeReason.DrawableHasNoMesh -> + ExportNoticePhrase(Res.string.export_reason_drawable_has_no_mesh) + + // MOC3 lowering. + is ExportNoticeReason.ChannelDemotedToStatic -> + ExportNoticePhrase( + Res.string.export_reason_channel_demoted_to_static, + listOf(ExportNoticeArgument.Nested(channelPhrase(reason.channel))), + ) + ExportNoticeReason.SketchPartIsNotRuntimeContent -> + ExportNoticePhrase(Res.string.export_reason_sketch_part_not_runtime_content) + ExportNoticeReason.HiddenPartOmittedByExportOption -> + ExportNoticePhrase(Res.string.export_reason_hidden_part_omitted_by_option) + ExportNoticeReason.HiddenDrawableOmittedByExportOption -> + ExportNoticePhrase(Res.string.export_reason_hidden_drawable_omitted_by_option) + ExportNoticeReason.UnkeyedDrawableUnderDeformerHasNoParentGeometry -> + ExportNoticePhrase(Res.string.export_reason_unkeyed_drawable_under_deformer) + is ExportNoticeReason.RestMeshConversionSizeMismatch -> + ExportNoticePhrase( + Res.string.export_reason_rest_mesh_conversion_size_mismatch, + listOf( + ExportNoticeArgument.Literal(reason.convertedCoordinateCount), + ExportNoticeArgument.Literal(reason.expectedCoordinateCount), + ), + ) + ExportNoticeReason.NoAtlasPageBound -> + ExportNoticePhrase(Res.string.export_reason_no_atlas_page_bound) + is ExportNoticeReason.ClippingMaskNotInExport -> + ExportNoticePhrase( + Res.string.export_reason_clipping_mask_not_in_export, + listOf(ExportNoticeArgument.Literal(reason.maskDrawableIds.joinToString())), + ) + ExportNoticeReason.OffscreenMaskNotInExport -> + ExportNoticePhrase(Res.string.export_reason_offscreen_mask_not_in_export) + ExportNoticeReason.WarpDeformerHasNoLattice -> + ExportNoticePhrase(Res.string.export_reason_warp_has_no_lattice) + ExportNoticeReason.RotationDeformerHasNoPivot -> + ExportNoticePhrase(Res.string.export_reason_rotation_has_no_pivot) + ExportNoticeReason.GlueNamesAnUnknownDrawable -> + ExportNoticePhrase(Res.string.export_reason_glue_names_unknown_drawable) + is ExportNoticeReason.IdTruncated -> + ExportNoticePhrase( + Res.string.export_reason_id_truncated, + listOf( + ExportNoticeArgument.Literal(reason.recordByteWidth), + ExportNoticeArgument.Literal(reason.writtenId), + ), + ) + is ExportNoticeReason.IdTruncatedAndDisambiguated -> + ExportNoticePhrase( + Res.string.export_reason_id_truncated_disambiguated, + listOf( + ExportNoticeArgument.Literal(reason.recordByteWidth), + ExportNoticeArgument.Literal(reason.writtenId), + ), + ) + + // CMO3 reconcile. + ExportNoticeReason.NoMatchingSourceToReconcile -> + ExportNoticePhrase(Res.string.export_reason_no_matching_source) + ExportNoticeReason.ParameterKindChangeNotLowered -> + ExportNoticePhrase(Res.string.export_reason_parameter_kind_change) + ExportNoticeReason.DeformerKindChangeNotLowered -> + ExportNoticePhrase(Res.string.export_reason_deformer_kind_change) + ExportNoticeReason.DeformerEditNeedsWarpSource -> + ExportNoticePhrase(Res.string.export_reason_deformer_needs_warp_source) + ExportNoticeReason.DeformerEditNeedsRotationSource -> + ExportNoticePhrase(Res.string.export_reason_deformer_needs_rotation_source) + ExportNoticeReason.TextureSourceRebindingIsEditorOnly -> + ExportNoticePhrase(Res.string.export_reason_texture_rebinding_editor_only) + ExportNoticeReason.BaseGeometryVertexCountMismatch -> + ExportNoticePhrase(Res.string.export_reason_base_geometry_vertex_mismatch) + ExportNoticeReason.NoUvsToReconcile -> + ExportNoticePhrase(Res.string.export_reason_no_uvs_to_reconcile) + ExportNoticeReason.DeformerHasNoPartToMoveTo -> + ExportNoticePhrase(Res.string.export_reason_deformer_no_part_to_move_to) + ExportNoticeReason.StaticDrawOrderShadowedByKeyforms -> + ExportNoticePhrase(Res.string.export_reason_static_draw_order_shadowed) + ExportNoticeReason.CompositeStaticsShadowedByKeyforms -> + ExportNoticePhrase(Res.string.export_reason_composite_statics_shadowed) + ExportNoticeReason.PartMasksFlattenToDrawables -> + ExportNoticePhrase(Res.string.export_reason_part_masks_flatten) + + // CMO3 structural creation. + ExportNoticeReason.NoSourceSetToCreateInto -> + ExportNoticePhrase(Res.string.export_reason_no_source_set_to_create_into) + ExportNoticeReason.CreatedEntityHasNoSourceYet -> + ExportNoticePhrase(Res.string.export_reason_created_entity_has_no_source) + ExportNoticeReason.CreatedGroupIsNotInTheEditedTree -> + ExportNoticePhrase(Res.string.export_reason_created_group_not_in_tree) + ExportNoticeReason.CreatedDrawableHasNoTextureSource -> + ExportNoticePhrase(Res.string.export_reason_created_drawable_no_texture_source) + ExportNoticeReason.GluedDrawableHasNoSource -> + ExportNoticePhrase(Res.string.export_reason_glued_drawable_has_no_source) + + // CMO3 mesh topology and glue re-binding. + is ExportNoticeReason.VertexCountExceedsEdgeTable -> + ExportNoticePhrase( + Res.string.export_reason_vertex_count_exceeds_edge_table, + listOf( + ExportNoticeArgument.Literal(reason.vertexCount), + ExportNoticeArgument.Literal(reason.maximumVertexCount), + ), + ) + ExportNoticeReason.GluedMeshHasNoUidTable -> + ExportNoticePhrase(Res.string.export_reason_glued_mesh_no_uid_table) + ExportNoticeReason.GluePairIndexesPastUidTable -> + ExportNoticePhrase(Res.string.export_reason_glue_pair_past_uid_table) + + // CMO3 keyforms. + is ExportNoticeReason.KeyformCannotBundle -> + ExportNoticePhrase( + Res.string.export_reason_keyform_cannot_bundle, + listOf(ExportNoticeArgument.Nested(keyformBundleRejectionPhrase(reason.rejection))), + ) + is ExportNoticeReason.AxisParameterHasNoSource -> + ExportNoticePhrase( + Res.string.export_reason_axis_parameter_no_source, + listOf(ExportNoticeArgument.Literal(reason.parameterId)), + ) + is ExportNoticeReason.BlendShapeParameterHasNoSource -> + ExportNoticePhrase( + Res.string.export_reason_blend_shape_parameter_no_source, + listOf(ExportNoticeArgument.Literal(reason.parameterId)), + ) + ExportNoticeReason.KeyformsWithoutBaseMesh -> + ExportNoticePhrase(Res.string.export_reason_keyforms_without_base_mesh) + ExportNoticeReason.FractionalDrawOrderNotStorable -> + ExportNoticePhrase(Res.string.export_reason_fractional_draw_order) + ExportNoticeReason.StaticGlueIntensityWithoutKeyforms -> + ExportNoticePhrase(Res.string.export_reason_static_glue_intensity_without_keyforms) + + // CMO3 document fields. + ExportNoticeReason.NoAuthoredWorldOrigin -> + ExportNoticePhrase(Res.string.export_reason_no_authored_world_origin) + ExportNoticeReason.NoRootParameterGroup -> + ExportNoticePhrase(Res.string.export_reason_no_root_parameter_group) + ExportNoticeReason.NoRootPart -> + ExportNoticePhrase(Res.string.export_reason_no_root_part) + ExportNoticeReason.NoParameterSourceSet -> + ExportNoticePhrase(Res.string.export_reason_no_parameter_source_set) + is ExportNoticeReason.CombinedPairReordered -> + ExportNoticePhrase( + Res.string.export_reason_combined_pair_reordered, + listOf( + ExportNoticeArgument.Literal(reason.horizontalParameterId), + ExportNoticeArgument.Literal(reason.verticalParameterId), + ), + ) + ExportNoticeReason.NoCanvasToReconcile -> + ExportNoticePhrase(Res.string.export_reason_no_canvas_to_reconcile) + ExportNoticeReason.FractionalCanvasSizeNotStorable -> + ExportNoticePhrase(Res.string.export_reason_fractional_canvas_size) + ExportNoticeReason.NoTextureManagerToReconcile -> + ExportNoticePhrase(Res.string.export_reason_no_texture_manager) + ExportNoticeReason.NoTextureInputForDisplayMode -> + ExportNoticePhrase(Res.string.export_reason_no_texture_input_for_display) + ExportNoticeReason.NoAtlasEntryToReconcile -> + ExportNoticePhrase(Res.string.export_reason_no_atlas_entry) + ExportNoticeReason.AtlasPageNotRecomposed -> + ExportNoticePhrase(Res.string.export_reason_atlas_page_not_recomposed) + ExportNoticeReason.AtlasTileMetadataNotReconcilable -> + ExportNoticePhrase(Res.string.export_reason_atlas_tile_metadata) + ExportNoticeReason.AtlasTileRebindingNotLowered -> + ExportNoticePhrase(Res.string.export_reason_atlas_tile_rebinding) + } + +/** + * The sentence naming which bundling rule a keyform set broke. + * + * @param KeyformBundleRejection rejection The rejection to phrase. + * @return ExportNoticePhrase The sentence and its arguments. + */ +private fun keyformBundleRejectionPhrase(rejection: KeyformBundleRejection): ExportNoticePhrase = + when (rejection) { + KeyformBundleRejection.KeysOutsideGeometrySpan -> + ExportNoticePhrase(Res.string.export_bundle_keys_outside_geometry_span) + KeyformBundleRejection.ChannelKeysWithoutGeometry -> + ExportNoticePhrase(Res.string.export_bundle_channel_keys_without_geometry) + is KeyformBundleRejection.KeysOutsideChannelSpan -> + ExportNoticePhrase( + Res.string.export_bundle_keys_outside_channel_span, + listOf(ExportNoticeArgument.Nested(channelPhrase(rejection.channel))), + ) + } + +/** + * A channel's own label as a phrase, so it can nest as another sentence's argument. + * + * @param FormChannel channel The channel to name. + * @return ExportNoticePhrase The label, argument-free. + */ +private fun channelPhrase(channel: FormChannel): ExportNoticePhrase = + ExportNoticePhrase(formChannelLabelRes(channel)) + +/** + * Resolves a phrase and its arguments into display text. + * + * Nesting bottoms out at depth two - a reason wraps a bundle rejection or a channel label, and neither + * nests further - so the recursion needs no depth guard. + * + * @param ExportNoticePhrase phrase The phrase to resolve. + * @return String The localized sentence. + */ +@Composable +fun exportNoticePhraseText(phrase: ExportNoticePhrase): String { + if (phrase.arguments.isEmpty()) { + return stringResource(phrase.resource) + } + val resolved = ArrayList(phrase.arguments.size) + for (argument in phrase.arguments) { + resolved.add( + when (argument) { + is ExportNoticeArgument.Literal -> argument.value + is ExportNoticeArgument.Nested -> exportNoticePhraseText(argument.phrase) + }, + ) + } + return stringResource(phrase.resource, *resolved.toTypedArray()) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportOptionsDialog.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportOptionsDialog.kt new file mode 100644 index 0000000..bd8be1b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportOptionsDialog.kt @@ -0,0 +1,127 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Divider +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.button.Button +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.dialog_cancel +import org.umamo.ui.resources.export_options_export +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * The export-options dialog: format-generic chrome around a per-format option pane. + * + * Dispatches on the request's case, so a new export format gains an options pane by adding its + * [ExportOptionsRequest] case and the compiler demands an arm here - the same compile-time prompt + * the preferences window uses for its categories. Cancel and the scrim dismiss without exporting; + * the pane's Export button runs the request's continuation first. + * + * @param ExportOptionsRequest request The pending request to render. + * @param Function onDismiss Clears the pending request, with or without a confirm. + */ +@Composable +internal fun ExportOptionsDialog( + request: ExportOptionsRequest, + onDismiss: () -> Unit, +) { + when (request) { + is ExportOptionsRequest.Moc3 -> Moc3ExportOptionsPane(request, onDismiss) + is ExportOptionsRequest.Image -> ImageExportOptionsPane(request, onDismiss) + } +} + +/** + * The shared dialog chrome: scrim, centered card, title, the format's rows, and the Cancel / Export + * footer. + * + * The same scrim-and-card recipe as ConfirmDialog, one size up: the scrim click cancels, the card + * swallows clicks so a press inside it is not read as a dismissal. + * + * @param String title The already-localized dialog title. + * @param Function onCancel Called on Cancel, the scrim, or Escape's dismissal path. + * @param Function onExport Called when the rigger confirms the export. + * @param Boolean exportEnabled False while the choices can produce nothing, which disables Export. + * @param Function content The format's option rows. + */ +@Composable +internal fun ExportOptionsCard( + title: String, + onCancel: () -> Unit, + onExport: () -> Unit, + exportEnabled: Boolean = true, + content: @Composable ColumnScope.() -> Unit, +) { + val colors = LocalUmamoColors.current + Box( + // indication = null (the kit convention): a bare clickable renders the default hover/press + // indication across the whole scrim, a stray dimming layer that toggles on pointer enter/leave. + modifier = + Modifier + .fillMaxSize() + .background(colors.overlayScrim) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onCancel), + contentAlignment = Alignment.Center, + ) { + Surface( + // The card swallows clicks (enabled = false) so a press on it is not read as a scrim dismissal. + modifier = Modifier.widthIn(min = 320.dp, max = 440.dp).clickable(enabled = false, onClick = {}), + color = colors.panelBackground, + shape = LocalUmamoShapes.current.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(text = title, style = LocalUmamoTypography.current.titleSmall) + content() + Row( + modifier = Modifier.padding(top = 12.dp).align(Alignment.End), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button(label = stringResource(Res.string.dialog_cancel), onClick = onCancel, primary = false) + Button(label = stringResource(Res.string.export_options_export), onClick = onExport, primary = true, enabled = exportEnabled) + } + } + } + } +} + +/** + * A section heading within the options card: a muted label over a divider. + * + * @param String label The already-localized section name. + */ +@Composable +internal fun ExportOptionsSectionLabel(label: String) { + val colors = LocalUmamoColors.current + Column(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) { + Text( + text = label, + style = LocalUmamoTypography.current.labelMedium, + color = colors.textMuted, + modifier = Modifier.padding(bottom = 4.dp), + ) + Divider() + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportOptionsRequest.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportOptionsRequest.kt new file mode 100644 index 0000000..8dfbff1 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ExportOptionsRequest.kt @@ -0,0 +1,66 @@ +package org.umamo.ui.workspace + +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.render.ContentBounds +import org.umamo.ui.viewport.ImageExportOptions +import org.umamo.ui.viewport.ImageFrame + +/** + * A pending export-options dialog: the format's options to edit, the facts the dialog needs to + * render them, and the action to run with whatever the rigger confirms. + * + * One case per export format that HAS options - the dialog matches exhaustively, so giving a new + * format (GLTF, some day) an options pane starts by adding its case here and the compiler walks the + * rest of the way. A format with no case (CMO3) never shows the dialog, by construction rather + * than by flag. + * + * The shell holds at most one of these (see [ShellOverlayState.pendingExportOptions]) and renders + * the dialog for it; the app layer builds the request and continues the export in [onConfirm] - + * the same continuation shape as [ConfirmRequest]. + */ +internal sealed interface ExportOptionsRequest { + /** + * The MOC3 export's options. + * + * @property Moc3ExportOptions initial The options to open the dialog with (the session's sticky + * values, scale already seeded). + * @property Boolean physicsAvailable Whether a retained physics3.json exists to include; the + * toggle is disabled when there is nothing to carry. + * @property Boolean userDataAvailable Whether a retained userdata3.json exists to include. + * @property Float canvasWidth The model's canvas width in pixels, for the units readout. + * @property Float canvasHeight The model's canvas height in pixels, for the units readout. + * @property Function onConfirm Continues the export with the confirmed options. + */ + data class Moc3( + val initial: Moc3ExportOptions, + val physicsAvailable: Boolean, + val userDataAvailable: Boolean, + val canvasWidth: Float, + val canvasHeight: Float, + val onConfirm: (Moc3ExportOptions) -> Unit, + ) : ExportOptionsRequest + + /** + * Export Image's options: the region, scale, and background of a capture of the posed puppet. + * + * The three rectangles are what the dialog frames its live size readout with, and what decides which + * regions it offers: View only when a 2D viewport has been touched, Canvas only when the document has + * one. + * + * @property ImageExportOptions initial The options to open the dialog with (the session's sticky values). + * @property ImageFrame? viewFrame The framed 2D viewport's own frame (the hovered one, else the last + * touched), or null when none has been touched. + * @property ContentBounds? canvasBounds The canvas rectangle in world space, or null when there is none. + * @property ContentBounds? contentBounds The shown content's extent at the current pose, or null when none. + * @property Function onConfirm Continues the export with the confirmed options, handed with what to + * remember of them: the same options, except that a region the dialog fell back from (and the rigger never + * replaced) is remembered rather than the fallback. + */ + data class Image( + val initial: ImageExportOptions, + val viewFrame: ImageFrame?, + val canvasBounds: ContentBounds?, + val contentBounds: ContentBounds?, + val onConfirm: (exported: ImageExportOptions, remembered: ImageExportOptions) -> Unit, + ) : ExportOptionsRequest +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/HoveredSurface.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/HoveredSurface.kt new file mode 100644 index 0000000..40c836e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/HoveredSurface.kt @@ -0,0 +1,199 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput + +/** + * The editor surface the pointer last touched: an opaque workspace-leaf area id plus the space kind + * hosting it. The single answer to "which area does the pointer mean", for every space alike - the UV + * editor does not participate in the GPU service and a panel participates in nothing, yet all of them + * need that question resolved at dispatch time. + * + * @property String areaId The last-touched leaf's area id. + * @property SpaceKind kind The space kind that leaf hosts. + */ +internal data class HoveredSurface(val areaId: String, val kind: SpaceKind) + +/** + * The shell-wide holder of the last-touched editor surface. + * + * DISPATCH-TIME ONLY: command handlers read [lastTouched] inside their handler bodies at invocation + * time, never during composition - it is a non-reactive var, so a composition-time gate would go stale + * without recomposing. Composition gates key off a latch's own area id instead (ActiveOperator.areaId, + * ActiveSelectTool.areaId), and a request that must execute in one area carries the id resolved at + * dispatch in its payload rather than re-reading this at collect time. + * + * It means "the last area touched that still exists": moving off an area deliberately does NOT clear it + * (otherwise every shortcut would die whenever the pointer rested on the menu bar, the tab strip, or the + * status bar), but an area that is closed or joined away releases it via [releaseArea] - the same + * eviction-on-dispose the other per-area registries do. An area switched to another space keeps its + * stamp under its new kind through [restampKind]: the area still exists and the pointer has not moved, + * so it goes on being the answer, and a header-dropdown switch sends no pointer event over the leaf to + * wait for. Its strip-host and viewport claims assert the OLD kind, so the leaf drops them first through + * [releaseKindClaims] and the re-stamp claims each again only when the new kind makes it. + * + * Stamped by [stampsHoveredSurface], installed once on every workspace leaf, so coverage is a property + * of the area tree rather than something each space has to remember to opt into. + * + * [lastTouchedStripHost] and [lastTouchedViewport] are the two deliberate reach-backs, and neither routes + * an action. The operation settings strip exists only in a work surface (hostsOperationStrip), so a + * document-wide operation fired over a panel needs the work surface the pointer touched LAST, however long + * ago, to place its strip; it places a panel for an operation that already ran. It must never name an area + * that no longer hosts a strip: the area's host refuses a record naming a non-hosting kind, and the strip + * would show nowhere. [lastTouchedViewport] is the 2D viewport the pointer touched last, which Export + * Image READS to frame what that viewport shows - reached through the File menu, which sits over another + * area in every default workspace, so the hovered surface is almost never the viewport meant. + * + * [observedKind] is the one read composition MAY make, and it exposes the kind alone on purpose. The + * status bar suggests shortcuts for the space under the pointer, which needs a reactive read; an area + * id read reactively is what let an overlay gate itself onto "the active area" and paint in two + * viewports at once. A kind cannot do that: two viewports share one, so it names no area to gate on. + */ +internal class HoveredSurfaceTracker { + /** The surface the pointer last touched, or null before any was touched (or after that area died). */ + var lastTouched: HoveredSurface? = null + set(value) { + field = value + observedKind = value?.kind + } + + /** + * The kind of [lastTouched], as snapshot state - display chrome's reactive view of where the pointer + * is. Written only through [lastTouched], so the two cannot disagree. + */ + var observedKind: SpaceKind? by mutableStateOf(null) + private set + + /** + * The strip-hosting surface the pointer last touched, or null before any was (or after it died or + * stopped hosting a strip). + */ + var lastTouchedStripHost: HoveredSurface? = null + + /** + * The 2D viewport the pointer last touched, or null before any was (or after it died or stopped hosting + * a 2D viewport). + */ + var lastTouchedViewport: HoveredSurface? = null + + /** + * Releases [areaId]'s kind-specific claims, if it holds any - the strip host and the last viewport. The + * leaf calls this when its space changes, because each claim asserts the kind the area had when touched + * and that kind is now gone. The general stamp is untouched; the area still exists. + * + * @param String areaId The leaf whose space changed. + */ + fun releaseKindClaims(areaId: String) { + if (lastTouchedStripHost?.areaId == areaId) { + lastTouchedStripHost = null + } + if (lastTouchedViewport?.areaId == areaId) { + lastTouchedViewport = null + } + } + + /** + * Takes up the kind-specific claims [stamp]'s kind makes, as a pointer event over that area does. + * + * @param HoveredSurface stamp The surface the pointer is over. + */ + fun claimKind(stamp: HoveredSurface) { + if (stamp.kind.hostsOperationStrip) { + lastTouchedStripHost = stamp + } + if (stamp.kind == SpaceKind.Viewport2D) { + lastTouchedViewport = stamp + } + } + + /** + * Re-stamps [areaId] under [kind] when it is the last-touched surface - the leaf calls this when its + * space changes, so dispatch, the status bar, and the palette all read the space the area hosts NOW + * rather than the one it hosted when the pointer last moved over it. + * + * Does what a pointer event over the switched area would: the stamp takes the new kind, and the + * kind-specific claims follow when that kind makes them ([claimKind]). A stamp naming another area is + * left alone - a space switch says nothing about where the pointer is. + * + * @param String areaId The leaf whose space changed. + * @param SpaceKind kind The space that leaf hosts now. + */ + fun restampKind(areaId: String, kind: SpaceKind) { + val current = lastTouched + if (current == null || current.areaId != areaId || current.kind == kind) { + return + } + val stamp = HoveredSurface(areaId, kind) + lastTouched = stamp + claimKind(stamp) + } + + /** + * Releases [areaId]'s claim on the pointer, if it holds one. + * + * Guarded on the id rather than clearing unconditionally: leaves come and go while the pointer sits + * elsewhere (a workspace switch disposes a whole tree), and a dying area must not wipe a stamp that + * belongs to a surviving one. + * + * @param String areaId The disposing leaf's area id. + */ + fun releaseArea(areaId: String) { + if (lastTouched?.areaId == areaId) { + lastTouched = null + } + if (lastTouchedStripHost?.areaId == areaId) { + lastTouchedStripHost = null + } + if (lastTouchedViewport?.areaId == areaId) { + lastTouchedViewport = null + } + } +} + +/** + * Stamps [tracker] with this node's area whenever the pointer is over it. + * + * Observes the Initial pass without consuming, so it reports the pointer no matter which descendant owns + * the gesture - the same mechanism the shell's cursor overlays rely on (see observeWindowPointer). Exit + * events are ignored, keeping the tracker's "last touched" meaning. + * + * @param HoveredSurfaceTracker? tracker The shell's tracker, or null outside a shell (previews, tests). + * @param String areaId The hosting leaf's area id. + * @param SpaceKind kind The space that leaf currently hosts. + * @return Modifier This modifier with the observer attached, or unchanged when there is no tracker. + * @warning [kind] MUST stay in the pointerInput key set. Change Editor Type rewrites a leaf's kind while + * leaving its id alone, and the tree keys leaf composition on that id, so the leaf survives the change - + * an observer keyed on the id alone would keep reporting the kind the area had when it was first + * composed, forever. Keys live in here rather than at the call site so they cannot be forgotten. + */ +internal fun Modifier.stampsHoveredSurface(tracker: HoveredSurfaceTracker?, areaId: String, kind: SpaceKind): Modifier { + if (tracker == null) { + return this + } + return pointerInput(tracker, areaId, kind) { + val stamp = HoveredSurface(areaId, kind) + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + // Every pointer move over every leaf reaches here, so re-stamping an unchanged value would + // be the common case; compare first and leave the field alone when nothing moved areas. + if (event.type != PointerEventType.Exit && tracker.lastTouched != stamp) { + tracker.lastTouched = stamp + tracker.claimKind(stamp) + } + } + } + } +} + +/** + * The shell's hovered-surface tracker, or null outside an editor shell (previews, tests). Every leaf + * stamps it; the shell's command tables resolve it at dispatch through CommandRouting. + */ +internal val LocalHoveredSurfaceTracker = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ImageExportOptionsSection.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ImageExportOptionsSection.kt new file mode 100644 index 0000000..d2456d7 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ImageExportOptionsSection.kt @@ -0,0 +1,173 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.FieldRow +import org.umamo.ui.kit.HexColorField +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.SelectField +import org.umamo.ui.kit.Text +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.export_options_background_color +import org.umamo.ui.resources.export_options_background_grid +import org.umamo.ui.resources.export_options_background_solid +import org.umamo.ui.resources.export_options_background_transparent +import org.umamo.ui.resources.export_options_image_no_canvas +import org.umamo.ui.resources.export_options_image_no_viewport +import org.umamo.ui.resources.export_options_image_nothing_visible +import org.umamo.ui.resources.export_options_image_scale +import org.umamo.ui.resources.export_options_image_size +import org.umamo.ui.resources.export_options_image_too_large +import org.umamo.ui.resources.export_options_region_canvas +import org.umamo.ui.resources.export_options_region_content +import org.umamo.ui.resources.export_options_region_view +import org.umamo.ui.resources.export_options_section_background +import org.umamo.ui.resources.export_options_section_region +import org.umamo.ui.resources.export_options_title_image +import org.umamo.ui.resources.unit_percent +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.viewport.ImageBackground +import org.umamo.ui.viewport.ImageFrameResult +import org.umamo.ui.viewport.ImageRegion +import org.umamo.ui.viewport.MAX_IMAGE_EDGE +import org.umamo.ui.viewport.resolveImageFrame + +/** The smallest and largest scale the dialog accepts, in percent. */ +private val IMAGE_SCALE_PERCENT_RANGE = 1f..1600f + +/** + * Export Image's option pane: which region to capture and at what scale, and what to draw it over, with a live + * readout of the image size that the choices make. + * + * Only the regions the moment can capture are offered: View when a 2D viewport has been touched (the hovered + * one, else the last), Canvas when the document has a canvas, and Content always. A remembered region the moment cannot offer + * opens as Content, and stays remembered unless the rigger picks a region themselves: a fallback is this + * moment's, not a choice. Edits accumulate on a local copy and reach the export only through the request's + * continuation when Export is pressed; Cancel discards them. Export is disabled while the choices make no + * image; the size readout says why. + * + * @param ExportOptionsRequest.Image request The pending request: initial values, the rectangles the readout + * frames, and the continuation. + * @param Function onDismiss Clears the pending request; Export runs the continuation first. + */ +@Composable +internal fun ImageExportOptionsPane( + request: ExportOptionsRequest.Image, + onDismiss: () -> Unit, +) { + val regions = + listOfNotNull( + ImageRegion.View.takeIf { request.viewFrame != null }, + ImageRegion.Canvas.takeIf { request.canvasBounds != null }, + ImageRegion.Content, + ) + val initialRegionOffered = request.initial.region in regions + var edited by remember(request) { + mutableStateOf(if (initialRegionOffered) request.initial else request.initial.copy(region = ImageRegion.Content)) + } + var regionChosen by remember(request) { mutableStateOf(initialRegionOffered) } + val regionLabels = + mapOf( + ImageRegion.View to stringResource(Res.string.export_options_region_view), + ImageRegion.Canvas to stringResource(Res.string.export_options_region_canvas), + ImageRegion.Content to stringResource(Res.string.export_options_region_content), + ) + val backgroundLabels = + mapOf( + ImageBackground.Transparent to stringResource(Res.string.export_options_background_transparent), + ImageBackground.Solid to stringResource(Res.string.export_options_background_solid), + ImageBackground.Grid to stringResource(Res.string.export_options_background_grid), + ) + val framing = + resolveImageFrame( + edited.region, + edited.scalePercent.coerceIn(IMAGE_SCALE_PERCENT_RANGE) / 100f, + request.viewFrame, + request.canvasBounds, + request.contentBounds, + ) + ExportOptionsCard( + title = stringResource(Res.string.export_options_title_image), + onCancel = onDismiss, + onExport = { + request.onConfirm(edited, if (regionChosen) edited else edited.copy(region = request.initial.region)) + onDismiss() + }, + exportEnabled = framing is ImageFrameResult.Framed, + ) { + ExportOptionsSectionLabel(stringResource(Res.string.export_options_section_region)) + FieldRow(label = stringResource(Res.string.export_options_section_region)) { + SelectField( + selected = edited.region, + options = regions, + label = { region -> regionLabels.getValue(region) }, + onSelect = { region -> + edited = edited.copy(region = region) + regionChosen = true + }, + ) + } + FieldRow(label = stringResource(Res.string.export_options_image_scale)) { + NumberField( + value = edited.scalePercent, + onValueChange = { value -> edited = edited.copy(scalePercent = value) }, + range = IMAGE_SCALE_PERCENT_RANGE, + modifier = Modifier.width(120.dp), + decimals = 0, + unitSuffix = stringResource(Res.string.unit_percent), + showFill = false, + ) + } + ImageSizeReadout(framing) + + ExportOptionsSectionLabel(stringResource(Res.string.export_options_section_background)) + FieldRow(label = stringResource(Res.string.export_options_section_background)) { + SelectField( + selected = edited.background, + options = ImageBackground.entries, + label = { background -> backgroundLabels.getValue(background) }, + onSelect = { background -> edited = edited.copy(background = background) }, + ) + } + if (edited.background == ImageBackground.Solid) { + FieldRow(label = stringResource(Res.string.export_options_background_color)) { + HexColorField( + value = edited.solidColorHex, + onValueChange = { hex -> edited = edited.copy(solidColorHex = hex) }, + modifier = Modifier.width(150.dp), + ) + } + } + } +} + +/** + * The size the choices make, or - in the warning color - why they make no image at all. + * + * @param ImageFrameResult framing The framed choices. + */ +@Composable +private fun ImageSizeReadout(framing: ImageFrameResult) { + val colors = LocalUmamoColors.current + val text = + when (framing) { + is ImageFrameResult.Framed -> stringResource(Res.string.export_options_image_size, framing.frame.width, framing.frame.height) + ImageFrameResult.NoViewport -> stringResource(Res.string.export_options_image_no_viewport) + ImageFrameResult.NoCanvas -> stringResource(Res.string.export_options_image_no_canvas) + ImageFrameResult.NothingVisible -> stringResource(Res.string.export_options_image_nothing_visible) + is ImageFrameResult.TooLarge -> stringResource(Res.string.export_options_image_too_large, framing.width, framing.height, MAX_IMAGE_EDGE) + } + Text( + text = text, + style = LocalUmamoTypography.current.bodySmall, + color = if (framing is ImageFrameResult.Framed) colors.textMuted else colors.signalBad, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/KeyformSheetViews.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/KeyformSheetViews.kt new file mode 100644 index 0000000..b46e068 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/KeyformSheetViews.kt @@ -0,0 +1,115 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter + +/** + * What the shell's keyform-sheet commands need from one open sheet area: its current selection resolved + * to editable triples, selection maintenance, and the frame-all view op. + * + * The lambdas read the area's LIVE view state at invocation time, so a registered surface never goes + * stale between edits - the same dispatch-time-only rule as HoveredSurfaceTracker. + * + * @property Function selectedTracks The selection resolved against the area's current projection. + * @property Function hasSelection Whether the area has any selected keys. + * @property Function frameAll Resets the area's zoom window to the whole domain. + * @property Function armBoxSelect Arms the area's marquee, so the next drag selects a region of keys. + */ +internal class KeyformSheetSurface( + val selectedTracks: () -> List>, + val hasSelection: () -> Boolean, + val frameAll: () -> Unit, + val armBoxSelect: () -> Unit, + /** + * Whether this sheet's box-select marquee is armed, and how to disarm it. + * + * Exposed rather than left as private view state so the shell's Escape ladder can cancel the gesture: + * an armed marquee hides the OS cursor, so a mode with no way out strands the pointer invisible. + */ + val boxSelectArmed: () -> Boolean, + val disarmBoxSelect: () -> Unit, + /** + * Nudges the sheet's whole key selection by [Float] of each key's parameter range, as one undo step, + * and re-points the selection at where the keys landed. + * + * On the SURFACE rather than left to the command because a crossing renumbers the axis - the same + * reason the mark drag routes through the sheet. Left unhandled, a nudge that moves a key past its + * neighbour would leave the selection naming whichever key took its place, so the next press would move + * the wrong one. + */ + val nudgeSelection: (Float) -> Unit, +) + +/** + * The shell-wide registry of open keyform-sheet areas, keyed by area id. + * + * The sheet's commands (delete/nudge selected keys, frame all) are registered ONCE at shell level and + * resolve the acting sheet through this at dispatch time. Registering them per area looked simpler but + * was wrong twice over: CommandRegistry is last-write-wins per id, so a second sheet area clobbered the + * first's handlers, and disposing either area unregistered the shared ids out from under the survivor. + */ +internal class KeyformSheetViews { + private val surfacesByAreaId = LinkedHashMap() + + /** + * The one sheet with an armed box-select marquee, or null when none has one. + * + * Arming is a per-area affair but Escape is a shell-level key, so the ladder asks here rather than + * reaching into a space's private view state. First match wins: two sheets can only both be armed if + * the user armed one, moved to the other and armed that too, and cancelling either is a fine answer. + * + * @return KeyformSheetSurface? The armed sheet, or null. + */ + fun armedBoxSelect(): KeyformSheetSurface? = surfacesByAreaId.values.firstOrNull { surface -> surface.boxSelectArmed() } + + /** + * Registers [surface] as area [areaId]'s sheet. + * + * @param String areaId The hosting leaf's area id. + * @param KeyformSheetSurface surface The area's command surface. + */ + fun register(areaId: String, surface: KeyformSheetSurface) { + surfacesByAreaId[areaId] = surface + } + + /** + * Removes [surface] from [areaId], by identity - a replacement registered by a newer composition of + * the same area must not be torn down by the older one's dispose. + * + * @param String areaId The hosting leaf's area id. + * @param KeyformSheetSurface surface The surface the caller registered. + */ + fun unregister(areaId: String, surface: KeyformSheetSurface) { + if (surfacesByAreaId[areaId] === surface) { + surfacesByAreaId.remove(areaId) + } + } + + /** + * The sheet a VIEW command (frame all) acts on: the hovered sheet area when there is one, else the + * only open sheet. Two sheets with neither hovered is genuinely ambiguous, so it resolves nothing. + * + * @param String? hoveredAreaId The last-touched keyform-sheet area, or null. + * @return KeyformSheetSurface? The acting sheet, or null. + */ + fun resolve(hoveredAreaId: String?): KeyformSheetSurface? = + surfacesByAreaId[hoveredAreaId] ?: surfacesByAreaId.values.singleOrNull() + + /** + * The sheet a SELECTION command (delete, nudge) acts on: [resolve]'s answer, else the unique sheet + * that actually has keys selected - a selection is itself a statement about which sheet is meant. + * + * @param String? hoveredAreaId The last-touched keyform-sheet area, or null. + * @return KeyformSheetSurface? The acting sheet, or null. + */ + fun resolveForSelection(hoveredAreaId: String?): KeyformSheetSurface? = + resolve(hoveredAreaId) ?: surfacesByAreaId.values.singleOrNull { surface -> surface.hasSelection() } +} + +/** + * The shell's keyform-sheet registry, or null outside an editor shell (previews, tests). + * + * Static because the holder instance never changes for a shell's lifetime; only its contents do. + */ +internal val LocalKeyformSheetViews = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LayoutPersistence.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LayoutPersistence.kt new file mode 100644 index 0000000..47ab2cd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LayoutPersistence.kt @@ -0,0 +1,152 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import org.umamo.settings.Settings + +/** The settings key the whole interface layout is stored under. */ +const val INTERFACE_LAYOUT_KEY: String = "interface.layout" + +/** + * The JSON configuration for (de)serializing the area-tree layout. classDiscriminator = "type" pairs + * with each AreaNode subtype's @SerialName ("split"/"leaf") to drive the sealed-interface + * polymorphism; encodeDefaults so ratio and other defaulted fields always persist; ignoreUnknownKeys + * so a layout written by a newer build (extra fields) still loads. Held module-internal - callers go + * through the encode/decode helpers, not this directly. + * + * エリアツリー直列化用の JSON 設定。type 識別子で sealed の多態を解決し、既定値も書き出す。 + */ +internal val LayoutJson: Json = + Json { + classDiscriminator = "type" + encodeDefaults = true + ignoreUnknownKeys = true + prettyPrint = false + } + +/** + * The same scheme as [LayoutJson] but pretty-printed, used only for the human-facing workspace.json that + * Export writes (a file a user may read or hand-edit before re-importing). Import parses with [LayoutJson], + * which reads compact and pretty alike, so the two stay interchangeable. + * + * Export 用に整形して出力する点だけが [LayoutJson] と異なる。読み込みは [LayoutJson] が両方を解釈する。 + */ +internal val LayoutExportJson: Json = + Json { + classDiscriminator = "type" + encodeDefaults = true + ignoreUnknownKeys = true + prettyPrint = true + } + +/** + * Encodes an [InterfaceLayout] to a [JsonElement] for storage under the interface.layout settings key + * (Settings.set takes a JsonElement, so we stay inside its API without re-stringifying). + * + * レイアウトを JsonElement に符号化する(Settings.set が JsonElement を取るため)。 + * + * @param InterfaceLayout layout The layout to encode. + * @return JsonElement The encoded tree. + */ +fun encodeLayout(layout: InterfaceLayout): JsonElement = LayoutJson.encodeToJsonElement(InterfaceLayout.serializer(), layout) + +/** + * Decodes an [InterfaceLayout] from a [JsonElement], or null if the element is malformed or describes + * an empty layout (no workspaces) - both of which mean "fall back to the seeded defaults". Never + * throws: a corrupt stored layout must not prevent the editor from opening. + * + * JsonElement からレイアウトを復号する。不正・空なら null(既定レイアウトにフォールバック)。例外は投げない。 + * + * @param JsonElement element The stored layout element. + * @return InterfaceLayout? The decoded layout, or null to signal "use defaults". + */ +fun decodeLayout(element: JsonElement): InterfaceLayout? = + runCatching { LayoutJson.decodeFromJsonElement(InterfaceLayout.serializer(), element) } + .getOrNull() + ?.takeIf { layout -> layout.workspaces.isNotEmpty() } + +/** + * Loads the persisted layout, or seeds the defaults when none is stored (decode failure or the empty + * `interface.layout.workspaces: []` baseline). On a seed it writes the concrete default back once, so + * the stored layout is materialised on first run (mirrors how window state seeds its defaults). + * + * 保存済みレイアウトを読み込む。無ければ既定を種として書き戻す。 + * + * @param Settings settings The settings store to read/seed. + * @return InterfaceLayout The loaded or freshly-seeded layout. + */ +fun loadLayout(settings: Settings): InterfaceLayout { + val stored = settings.get(INTERFACE_LAYOUT_KEY)?.let { element -> decodeLayout(element) } + if (stored != null) { + return stored + } + val seeded = defaultLayout() + saveLayout(settings, seeded) + return seeded +} + +/** + * Persists [layout] under the interface.layout settings key as a JsonElement (staying inside the + * Settings API, which takes/returns JsonElement). Settings handles the write to the user layer, the + * re-merge over defaults, and the disk write. + * + * レイアウトを interface.layout キーに JsonElement として保存する。 + * + * @param Settings settings The settings store to write to. + * @param InterfaceLayout layout The layout to persist. + */ +fun saveLayout(settings: Settings, layout: InterfaceLayout) { + settings.set(INTERFACE_LAYOUT_KEY, encodeLayout(layout)) +} + +/** + * Parses a whole-layout workspace.json [text] into a validated [InterfaceLayout], or null if it is + * malformed or not a full layout. Wraps the same [decodeLayout] validator the persisted layout uses, so + * a single-workspace export (no `workspaces` array) returns null here - that is how Import tells the two + * file shapes apart (try this first, then [decodeWorkspaceText]). Never throws. + * + * レイアウト全体の workspace.json を検証付きで [InterfaceLayout] に復号する。不正・単一ワークスペースなら null。 + * + * @param String text The raw JSON file contents. + * @return InterfaceLayout? The decoded layout, or null when it is not a valid full layout. + */ +fun decodeLayoutText(text: String): InterfaceLayout? = + runCatching { LayoutJson.parseToJsonElement(text) }.getOrNull()?.let { element -> decodeLayout(element) } + +/** + * Parses a single-workspace workspace.json [text] into a [Workspace], or null if it is malformed or not a + * single workspace. A full-layout file (no `root`/`id` at the top level) fails to decode here, so this is + * the second branch Import tries after [decodeLayoutText]. The caller is expected to re-mint ids before + * inserting the result (see the append path) so it never collides with an existing workspace. Never throws. + * + * 単一ワークスペースの workspace.json を [Workspace] に復号する。不正・レイアウト全体なら null。 + * + * @param String text The raw JSON file contents. + * @return Workspace? The decoded workspace, or null when it is not a valid single workspace. + */ +fun decodeWorkspaceText(text: String): Workspace? = + runCatching { LayoutJson.decodeFromString(Workspace.serializer(), text) }.getOrNull() + +/** + * Renders the persisted interface layout as pretty-printed JSON for Export All Workspaces, or null when no + * layout is stored yet. Exports the saved element verbatim (just reformatted), matching "the saved JSON + * from settings.json": any forward-compatible extra keys a newer build wrote are preserved, not dropped. + * + * 保存済みのレイアウトを整形 JSON として出力する(未保存なら null)。保存された要素をそのまま整形する。 + * + * @param Settings settings The settings store to read the layout from. + * @return String? The pretty-printed layout JSON, or null when nothing is stored. + */ +fun exportLayoutText(settings: Settings): String? = + settings.get(INTERFACE_LAYOUT_KEY)?.let { element -> LayoutExportJson.encodeToString(JsonElement.serializer(), element) } + +/** + * Renders a single [workspace] as pretty-printed JSON for Export This Workspace. The result decodes back + * through [decodeWorkspaceText]; on re-import it is appended as a fresh tab (ids re-minted by the caller). + * + * 単一ワークスペースを整形 JSON として出力する(Export This Workspace 用)。 + * + * @param Workspace workspace The workspace to serialize. + * @return String The pretty-printed workspace JSON. + */ +fun exportWorkspaceText(workspace: Workspace): String = LayoutExportJson.encodeToString(Workspace.serializer(), workspace) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LayoutSavePacer.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LayoutSavePacer.kt new file mode 100644 index 0000000..340a8ee --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LayoutSavePacer.kt @@ -0,0 +1,62 @@ +package org.umamo.ui.workspace + +/** + * Paces the layout disk writes around splitter drags: while a drag is held nothing is written (a + * mid-drag pause would otherwise let the debounce fire on the UI thread mid-gesture), and the drag's + * release commits the latest layout immediately - exactly one write per drag. Structural edits + * (splits, workspace CRUD, imports) still arrive through the debounced path and write as before. + * + * Duplicate writes are suppressed by remembering the last-saved layout INSTANCE: the controller + * publishes a fresh immutable layout per edit, so reference equality is exactly "nothing changed + * since the last write" (a commit followed by the still-pending debounce of the same instance writes + * once, and a zero-movement drag writes nothing). + * + * @property InterfaceLayout initialSavedLayout The layout already persisted at startup (loaded or seeded). + * @property Function save Performs the actual write (the settings-backed saveLayout). + */ +internal class LayoutSavePacer( + initialSavedLayout: InterfaceLayout, + private val save: (InterfaceLayout) -> Unit, +) { + // A depth counter rather than a boolean: the shared shell targets touch tablets, where two + // fingers can in principle hold two splitters at once - a boolean would resume writes when the + // FIRST drag released. Clamped at zero so an unmatched release (the disposal guard's defensive + // signal) can never wedge the counter negative. + private var activeDragCount: Int = 0 + private var lastSavedLayout: InterfaceLayout = initialSavedLayout + + /** + * The debounced-path write: persists [layout] unless a drag is holding writes or this exact + * instance is already on disk. + * + * @param InterfaceLayout layout The layout the debounce settled on. + */ + fun saveDebounced(layout: InterfaceLayout) { + if (activeDragCount > 0 || layout === lastSavedLayout) { + return + } + save(layout) + lastSavedLayout = layout + } + + /** + * Tracks the splitter-drag gestures: while any is active, debounced writes are held; the release + * of the LAST one commits the latest layout immediately (skipped when nothing changed since the + * last write). + * + * @param Boolean active True at a drag start, false at a drag end. + * @param InterfaceLayout latestLayout The most recently published layout. + */ + fun setDragActive(active: Boolean, latestLayout: InterfaceLayout) { + activeDragCount = + if (active) { + activeDragCount + 1 + } else { + maxOf(0, activeDragCount - 1) + } + if (activeDragCount == 0 && latestLayout !== lastSavedLayout) { + save(latestLayout) + lastSavedLayout = latestLayout + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LogExport.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LogExport.kt new file mode 100644 index 0000000..faf2051 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/LogExport.kt @@ -0,0 +1,25 @@ +package org.umamo.ui.workspace + +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.writeString +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import org.umamo.storage.FilePicker +import org.umamo.storage.UmamoLog + +/** + * Writes the retained UmamoLog buffer to a file the person picks, as plain text with one line per entry - + * the same lines the terminal printed, for someone who launched without one. The buffer is read at write + * time, so the file captures the log as of when the save is confirmed, not when the button was pressed. + * + * @param FilePicker filePicker The native save dialog. + * @param CoroutineScope scope The scope the dialog and the write run in. + */ +internal fun exportLogToFile(filePicker: FilePicker, scope: CoroutineScope) { + scope.launch { + filePicker.saveFile("umamo-log", "txt")?.let { destination -> + destination.writeString(UmamoLog.entries.value.joinToString("\n") { entry -> entry.message }) + UmamoLog.info("exported log to ${destination.absolutePath()}") + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/MeshTotals.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/MeshTotals.kt new file mode 100644 index 0000000..a3809c1 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/MeshTotals.kt @@ -0,0 +1,87 @@ +package org.umamo.ui.workspace + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/** + * Vertex and triangle counts summed over a set of drawable meshes, for the status bar's stats zone. + * + * @property Int vertexCount The summed vertex count. + * @property Int triangleCount The summed triangle count. + */ +internal data class MeshTotals(val vertexCount: Int, val triangleCount: Int) + +/** + * The whole model's mesh totals: every drawable that carries a mesh contributes its vertex and + * triangle counts (a drawable's mesh is nullable - some drawables carry no geometry, and skipping + * them is the contract). + * + * @param PuppetModel puppet The loaded rig. + * @return MeshTotals The model-wide vertex / triangle sums. + */ +internal fun meshTotals(puppet: PuppetModel): MeshTotals { + var vertexCount = 0 + var triangleCount = 0 + for (drawable in puppet.drawables) { + val mesh = drawable.mesh ?: continue + vertexCount += mesh.vertexCount + triangleCount += mesh.triangleCount + } + return MeshTotals(vertexCount, triangleCount) +} + +/** + * The mesh totals covered by an object-mode [selection]: directly selected drawables plus every + * drawable nested under a selected part (a folder selection counts its art, recursively). Deformer + * targets contribute nothing - a deformer's influence set is a rig relationship, not containment. + * + * @param PuppetModel puppet The loaded rig. + * @param Selection selection The object-mode selection. + * @return MeshTotals The selected vertex / triangle sums. + */ +internal fun selectedMeshTotals(puppet: PuppetModel, selection: Selection): MeshTotals { + val partById = puppet.parts.associateBy { part -> part.id } + val selectedDrawableIds = HashSet() + for (target in selection.targets) { + when (target) { + is SelectionTarget.Drawable -> selectedDrawableIds.add(target.id) + is SelectionTarget.Part -> collectPartDrawableIds(target.id, partById, selectedDrawableIds) + is SelectionTarget.Deformer -> { + // Intentionally nothing: deformers influence drawables but do not contain them. + } + } + } + var vertexCount = 0 + var triangleCount = 0 + for (drawable in puppet.drawables) { + if (drawable.id !in selectedDrawableIds) { + continue + } + val mesh = drawable.mesh ?: continue + vertexCount += mesh.vertexCount + triangleCount += mesh.triangleCount + } + return MeshTotals(vertexCount, triangleCount) +} + +/** + * Recursively collects every drawable id nested under [partId] (through nested parts) into [out]. + * + * @param PartId partId The part whose subtree is collected. + * @param Map partById id -> Part, for resolving nested parts. + * @param MutableSet out The accumulating drawable id set. + */ +private fun collectPartDrawableIds(partId: PartId, partById: Map, out: MutableSet) { + val part = partById[partId] ?: return + for (child in part.children) { + when (child) { + is OrgChild.Drawable -> out.add(child.id) + is OrgChild.Part -> collectPartDrawableIds(child.id, partById, out) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Moc3ExportOptionsSection.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Moc3ExportOptionsSection.kt new file mode 100644 index 0000000..d48b8b5 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Moc3ExportOptionsSection.kt @@ -0,0 +1,139 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.FieldRow +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.Text +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.export_options_canvas_in_units +import org.umamo.ui.resources.export_options_guide_parts +import org.umamo.ui.resources.export_options_hidden_drawables +import org.umamo.ui.resources.export_options_hidden_parts +import org.umamo.ui.resources.export_options_include_displayinfo +import org.umamo.ui.resources.export_options_include_physics +import org.umamo.ui.resources.export_options_include_userdata +import org.umamo.ui.resources.export_options_pixels_per_unit +import org.umamo.ui.resources.export_options_section_content +import org.umamo.ui.resources.export_options_section_scale +import org.umamo.ui.resources.export_options_section_sidecars +import org.umamo.ui.resources.export_options_title_moc3 +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography +import kotlin.math.floor +import kotlin.math.round + +/** + * The MOC3 export's option pane: which objects the bake includes, which sidecar files ride along, + * and the bake scale. + * + * This file is the MOC3 format's whole contribution to the dialog - its option list, its layout, + * and (beside the session store) its defaults - so a future format's pane is a sibling of this + * file, not an edit to shared chrome. Edits accumulate on a local copy and reach the export only + * through the request's continuation when Export is pressed; Cancel discards them. + * + * @param ExportOptionsRequest.Moc3 request The pending request: initial values, availability facts, + * and the continuation. + * @param Function onDismiss Clears the pending request; Export runs the continuation first. + */ +@Composable +internal fun Moc3ExportOptionsPane( + request: ExportOptionsRequest.Moc3, + onDismiss: () -> Unit, +) { + var edited by remember(request) { mutableStateOf(request.initial) } + ExportOptionsCard( + title = stringResource(Res.string.export_options_title_moc3), + onCancel = onDismiss, + onExport = { + request.onConfirm(edited) + onDismiss() + }, + ) { + ExportOptionsSectionLabel(stringResource(Res.string.export_options_section_content)) + Checkbox( + checked = edited.exportHiddenParts, + onCheckedChange = { checked -> edited = edited.copy(exportHiddenParts = checked) }, + label = stringResource(Res.string.export_options_hidden_parts), + ) + Checkbox( + checked = edited.exportHiddenDrawables, + onCheckedChange = { checked -> edited = edited.copy(exportHiddenDrawables = checked) }, + label = stringResource(Res.string.export_options_hidden_drawables), + ) + Checkbox( + checked = edited.exportGuideImageParts, + onCheckedChange = { checked -> edited = edited.copy(exportGuideImageParts = checked) }, + label = stringResource(Res.string.export_options_guide_parts), + ) + + ExportOptionsSectionLabel(stringResource(Res.string.export_options_section_sidecars)) + // A pass-through sidecar can only be carried when the import retained one; with nothing to + // carry the toggle is disabled and shown clear rather than pretending a file will appear. + Checkbox( + checked = request.physicsAvailable && edited.includePhysics, + onCheckedChange = { checked -> edited = edited.copy(includePhysics = checked) }, + label = stringResource(Res.string.export_options_include_physics), + enabled = request.physicsAvailable, + ) + Checkbox( + checked = request.userDataAvailable && edited.includeUserData, + onCheckedChange = { checked -> edited = edited.copy(includeUserData = checked) }, + label = stringResource(Res.string.export_options_include_userdata), + enabled = request.userDataAvailable, + ) + Checkbox( + checked = edited.includeDisplayInfo, + onCheckedChange = { checked -> edited = edited.copy(includeDisplayInfo = checked) }, + label = stringResource(Res.string.export_options_include_displayinfo), + ) + + ExportOptionsSectionLabel(stringResource(Res.string.export_options_section_scale)) + val pixelsPerUnit = edited.pixelsPerUnitOverride ?: request.canvasWidth + FieldRow(label = stringResource(Res.string.export_options_pixels_per_unit)) { + NumberField( + value = pixelsPerUnit, + onValueChange = { value -> edited = edited.copy(pixelsPerUnitOverride = value) }, + range = 1f..1_000_000f, + modifier = Modifier.width(120.dp), + decimals = 2, + showFill = false, + ) + } + // A live sanity readout: what the canvas measures in model units at the edited scale, which + // is the number a runtime's stage works in. + Text( + text = + stringResource( + Res.string.export_options_canvas_in_units, + formatCanvasUnits(request.canvasWidth / pixelsPerUnit), + formatCanvasUnits(request.canvasHeight / pixelsPerUnit), + ), + style = LocalUmamoTypography.current.bodySmall, + color = LocalUmamoColors.current.textMuted, + ) + } +} + +/** + * Formats a canvas dimension in model units: two decimals, trimmed when whole. + * + * @param Float value The dimension in units. + * @return String The display form. + */ +private fun formatCanvasUnits(value: Float): String { + val rounded = round(value * 100f) / 100f + return if (rounded == floor(rounded)) { + rounded.toInt().toString() + } else { + rounded.toString() + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ModalKeyLadder.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ModalKeyLadder.kt new file mode 100644 index 0000000..b130fa9 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ModalKeyLadder.kt @@ -0,0 +1,305 @@ +package org.umamo.ui.workspace + +import androidx.compose.ui.input.key.Key +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.EditorMode +import org.umamo.edit.SelectionOps +import org.umamo.edit.TransformAxisConstraint +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.KeyChord +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.keyName +import org.umamo.ui.viewport.pieMenuEntriesFor + +/* + * The shell's modal key ladder: the ordered Escape/Enter (and modal-only key) precedence that runs in + * the root's onPreviewKeyEvent BEFORE the keymap. Modal chrome and in-flight gestures must pre-empt + * bound commands (Escape closes the topmost overlay, not area.dragCancel), and modal operators + * swallow keys the keymap would otherwise claim - so this is the documented exception to "all input + * dispatches through the action registry": the ladder decides WHO owns the key, and everything it + * does not consume falls through to the keymap dispatch at the bottom. Order is the contract; add + * new modal states at the precedence their UI stacking implies, and pin the new arm in + * ModalKeyLadderTest - which asserts this order arm by arm, and for the combinations where two + * modals are open at once. + */ + +/** + * Routes one key press through the shell's modal precedence, falling through to the keymap dispatch + * when no modal state owns it. + * + * @param ShellKeyStroke stroke The decoded key press. + * @param ShellModalState state Everything the precedence consults. + * @return Boolean True when the event was consumed. + */ +internal fun handleModalKeyLadder(stroke: ShellKeyStroke, state: ShellModalState): Boolean = + with(state) { + val closeOpenMenu = menuBarController.closeOpenMenu + val cancelInlineEdit = inlineEditController.cancel + val isEscapeDown = stroke.isDown && stroke.key == Key.Escape + val isEnter = stroke.key == Key.Enter || stroke.key == Key.NumPadEnter + val isEnterDown = stroke.isDown && isEnter + // Every Enter stroke is noted before any arm runs, up or down. This preview handler sees the key-down + // before the palette's own handler dispatches the command on it, so a confirm that command raises + // lands with the key already known to be held - and stays unarmed until the release. + if (isEnter) { + overlays.noteEnterStroke(stroke.isDown) + } + when { + // A confirm dialog is the topmost modal: it owns the keyboard entirely. Enter confirms (like its + // confirm button, the dialog's default) and Escape cancels (like its cancel button); every other key + // is swallowed so no shortcut fires behind it - notably Space, which would otherwise open the palette + // over the dialog now that the dialog reclaims root focus. It outranks the self-focused overlays + // below, so a confirm raised over Preferences takes its own Enter and Escape without closing them. + // An Enter still held from raising the dialog does not count: its OS auto-repeat would confirm a + // destructive action before the dialog is seen, so the arm waits for a fresh press. + overlays.pendingConfirm != null -> { + if (isEnterDown && overlays.confirmArmedForEnter) { + overlays.confirmPending() + } else if (isEscapeDown) { + overlays.cancelPending() + } + true + } + // The file-open alert is modal like the confirm dialog: Escape or Enter dismisses it + // (like its OK button); every other key is swallowed so no shortcut fires behind it. + overlays.openFailure != null -> { + if (isEscapeDown || isEnterDown) { + overlays.openFailure = null + } + true + } + // A message from the app layer (a read-only open, a failed save) dismisses the same way. + overlays.pendingAlert != null -> { + if (isEscapeDown || isEnterDown) { + overlays.pendingAlert = null + } + true + } + // The export-report alert is modal the same way: Escape or Enter dismisses it (the export + // itself already happened; this only acknowledges the notices). + overlays.exportReport != null -> { + if (isEscapeDown || isEnterDown) { + overlays.exportReport = null + } + true + } + // The repack refusal report dismisses the same way: it only acknowledges why nothing happened. + overlays.repackReport != null -> { + if (isEscapeDown || isEnterDown) { + overlays.repackReport = null + } + true + } + // An open menu owns the keyboard like the overlays below it: Escape closes it, every other key + // is inert. It has to claim the rest rather than pass them on - the bar's dropdowns open + // non-focusable so its labels keep receiving hover for the sweep-to-switch, which leaves the + // host window focused and this ladder seeing every key first, ahead of the bar's own handler + // (which claims only Escape). Passing them on fired shortcuts behind the open menu. + closeOpenMenu != null -> { + if (isEscapeDown) { + closeOpenMenu() + true + } else { + false + } + } + // A control capturing the next key press (the keybindings editor's chord chip) owns the WHOLE keyboard: + // any key may be the one being bound, and Escape cancels the capture - not the Preferences overlay the + // control sits in, which the arm below would close. The ladder previews every key before the control + // sees it, so it stands aside here and the control's own handler decides. Below the confirm and the + // alerts, which paint over everything and can arrive unasked while a capture is live. + keyCapture.active -> false + // The overlays that hold their own focus - preferences, the two Help dialogs, the palette - + // are one family: Escape closes the topmost (instead of falling through to area.dragCancel) + // and every other key yields to that overlay's own content, exactly as an open inline editor + // does. Preferences yields to its dropdown popups, which are focusable and so claim their own + // Escape before a key ever reaches here; the Help dialogs to the credits scroll and the about + // links; the palette to its search field. + overlays.selfFocusedOverlayOpen -> { + if (isEscapeDown) { + overlays.closeTopmostSelfFocused() + true + } else { + false + } + } + // An inline editor (workspace rename) owns the keyboard while open: Escape cancels it, + // and every other key falls through to the field - otherwise the shell's shortcuts + // (Space → palette, letters → file commands) would fire while the user types a name. + cancelInlineEdit != null -> { + if (isEscapeDown) { + cancelInlineEdit() + true + } else { + false + } + } + // An in-flight modal operator (G/S/R over mesh vertices, whole drawables, or texture + // coordinates) owns Escape: cancel it before any selection clear, so cancelling a grab does + // not also wipe the selection. The overlay observes its latch going null and discards its + // preview. One arm for all three families - they are mutually exclusive, and clearing + // dispatches to the family that is actually running. + isEscapeDown && editorSession?.activeOperator != null -> { + editorSession.clearActiveOperator() + true + } + // Enter confirms an in-flight modal gesture (mirroring a primary click); the driving overlay + // holds the working positions and commits on this shared signal, whichever family latched. + isEnterDown && editorSession?.activeOperator != null -> { + editorSession.requestMeshConfirm() + true + } + // An open pie menu owns the keyboard: Escape closes it, 1..N instantly picks the + // matching entry (the ordinal each chip draws - the shared entry order), and + // everything else is swallowed so shortcuts cannot fire under the ring. + editorSession?.activePieMenu?.value != null && stroke.isDown -> { + val openPie = editorSession.activePieMenu.value + if (stroke.key == Key.Escape) { + editorSession.closePieMenu() + } else if (openPie != null) { + val digit = + when (stroke.key) { + Key.One, Key.NumPad1 -> 1 + Key.Two, Key.NumPad2 -> 2 + Key.Three, Key.NumPad3 -> 3 + Key.Four, Key.NumPad4 -> 4 + Key.Five, Key.NumPad5 -> 5 + Key.Six, Key.NumPad6 -> 6 + Key.Seven, Key.NumPad7 -> 7 + Key.Eight, Key.NumPad8 -> 8 + else -> 0 + } + val entry = if (digit > 0) pieMenuEntriesFor(openPie).getOrNull(digit - 1) else null + if (entry != null && entry.enabled) { + // Invoke-then-close, matching the pointer pick's order. + commandRegistry.invoke(entry.commandId, entry.argument) + editorSession.closePieMenu() + } + } + true + } + // X / Z during a modal Grab / Scale toggle the axis lock (Blender's axis constraint). + // This has to live in the ladder: the modal operator swallows pointer input in the + // overlay and every other key here, so the keymap never sees these presses. The + // session no-ops for Rotate (one 2D rotation axis - nothing to lock). + stroke.isDown && stroke.key == Key.X && editorSession?.activeOperator != null -> { + editorSession.toggleAxisConstraint(TransformAxisConstraint.AxisX) + true + } + stroke.isDown && stroke.key == Key.Z && editorSession?.activeOperator != null -> { + editorSession.toggleAxisConstraint(TransformAxisConstraint.AxisZ) + true + } + // Add Vertex: Enter accepts the draft into the mesh; Escape discards. Both clear the tool. + isEnterDown && editorSession?.activeSelectTool?.value is ActiveSelectTool.AddVertex -> { + editorSession.acceptAddVertexDraft() + true + } + // An armed Box / Circle select tool owns Escape and Enter: both leave the tool, before the + // selection-clear branch below. Resolve any in-flight gesture on the fast cancel signal FIRST + // (a circle stroke keeps its paint, a box rubber-band is discarded), then disarm: clearSelectTool + // alone routes the cleanup through a recomposition-gated effect that can lose the race to a mouse + // release still in flight, letting a cancelled armed box commit through the idle Release path. + // Add Vertex also takes Escape here (discard without accept). + (isEscapeDown || isEnterDown) && editorSession?.activeSelectTool?.value != null -> { + editorSession.requestMeshGestureCancel() + editorSession.clearSelectTool() + true + } + // An armed keyform-sheet marquee owns Escape, before the clear-selection branch below. It hides + // the OS cursor while armed, so a mode with no way out leaves the pointer invisible over the + // sheet until the user happens to press and release somewhere. + isEscapeDown && keyformSheets.armedBoxSelect() != null -> { + keyformSheets.armedBoxSelect()?.disarmBoxSelect?.invoke() + true + } + // An armed relation pick (a Properties field's eyedropper) owns Escape: cancel the pick before the + // clear-selection branch below, so abandoning a pick never also wipes the user's selection. Like + // the zoom region this is mode-agnostic, and it resolves from the outliner as well as a viewport. + isEscapeDown && relationPick.request != null -> { + relationPick.cancel() + true + } + // An armed Zoom Region gesture owns Escape: disarm it (mode-agnostic, so it precedes the + // Object-only clear below). + isEscapeDown && editorSession?.zoomRegionArmedArea?.value != null -> { + editorSession.disarmZoomRegion() + true + } + // An in-flight panel row drag (outliner / parameters) owns Escape: cancel it (through the + // registry, mirroring area.dragCancel) before the clear-selection branch below - the press + // that started the drag already selected the row, so that branch would otherwise swallow + // Escape and deselect the dragged rows while the drag kept going. + isEscapeDown && rowDragCancel.cancel != null -> { + commandRegistry.invoke("row.dragCancel") + true + } + // An in-flight divider (splitter) drag owns Escape, before the clear-selection arm below. + // It needs its own arm because it is NOT the area corner drag the three arms below gate on: + // its session lives in the dragged SplitContainer, never touches AreaDragController, and so + // left isDragging false - Escape fell through and cleared the object selection while the user + // was only resizing a panel. Routed through the registry like the row-drag cancel. + isEscapeDown && splitterDragCancel.cancel != null -> { + commandRegistry.invoke("area.dragCancel") + true + } + // An in-flight non-armed viewport box drag owns Escape in any mode (the Object overlay + // publishes the flag): abandon the rubber-band WITHOUT falling through to the Object-mode + // clear-selection branch below, so cancelling a drag never also wipes the selection. + isEscapeDown && editorSession?.viewportGestureActive?.value == true && !dragController.isDragging -> { + editorSession.requestMeshGestureCancel() + true + } + // In Edit mode, Escape abandons an in-flight non-armed box drag (armed tools and the + // zoom region are handled above); the overlay clears its rubber-band on the signal. Gated + // off an in-flight area CORNER drag so that still yields to area.dragCancel - a divider + // (splitter) drag is a separate mechanism this gate does not see, and cannot cancel. + // Blender-parity: with nothing in flight this is a harmless no-op that consumes Escape and + // never clears selection. + isEscapeDown && editorSession?.mode?.value == EditorMode.Edit && !dragController.isDragging -> { + editorSession.requestMeshGestureCancel() + true + } + // With no modal open and no in-flight corner drag, Escape clears a non-empty OBJECT + // selection. Gated to Object mode (a null session counts as Object): in Edit mode the + // object selection holds the drawable being edited, so clearing it here would strand the + // Edit session on a drawable nothing points at. Blender's Edit mode leaves the selection + // untouched on Escape, so Edit falls through to area.dragCancel (a no-op with no drag). + // While a drag is active it yields to area.dragCancel (handled via handleShellKey below). + isEscapeDown && + editorSession?.mode?.value != EditorMode.Edit && + !dragController.isDragging && + selection?.selection?.isEmpty == false -> { + selection.set(SelectionOps.clear()) + true + } + else -> handleShellKey(stroke, keymap, commandRegistry) + } + } + +/** + * Translates a key press into a [KeyChord] and, if the keymap binds it, invokes the bound command + * through the registry - the live keybinding-lookup path. The position→name mapping is the shared + * [keyName] table, the same one the rebindings editor captures with, so any chord a user can bind there + * also dispatches here. + * + * @param ShellKeyStroke stroke The decoded key press. + * @param Keymap keymap The active keymap. + * @param CommandRegistry registry The command registry to dispatch into. + * @return Boolean true if a bound command ran (event consumed); false otherwise. + */ +private fun handleShellKey(stroke: ShellKeyStroke, keymap: Keymap, registry: CommandRegistry): Boolean { + if (!stroke.isDown) { + return false + } + val pressedKeyName = keyName(stroke.key) ?: return false + val chord = + KeyChord( + keyName = pressedKeyName, + primaryModifier = stroke.primaryModifier, + shift = stroke.shift, + alt = stroke.alt, + ) + val commandId = keymap.commandFor(chord) ?: return false + return registry.invoke(commandId) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/OperationStrip.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/OperationStrip.kt new file mode 100644 index 0000000..a550107 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/OperationStrip.kt @@ -0,0 +1,255 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.edit.AdjustableOperation +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.edit.withParameter +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.SectionHeader +import org.umamo.ui.kit.SelectField +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.properties.PropertyCheckboxRow +import org.umamo.ui.properties.PropertyFieldRow +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes + +/* + * The operation settings strip - Blender's "Adjust Last Operation" panel. A collapsed header in the + * bottom-left of the area the last operation ran in; expanded, one row per parameter, and editing a + * row re-runs the operation over its own history step. The rows are rendered from the parameter + * KINDS, never from the operation, so a new adjustable operation adds a parameter list and label + * strings, not a pane. + * + * The strip lives in that one area and nowhere else - Blender's redo panel is a region of the editor + * the operator ran in. A record naming an area outside the active workspace's tree (the rigger + * switched workspaces), an area that no longer hosts a work surface, or no area at all (the workspace + * has no 2D viewport or UV editor) shows nowhere; it shows again when its area is back on screen. + */ + +/** + * The strip's disclosure state, one per window: Blender keeps a single redo panel, and so does the + * shell. Session-remembered rather than per area or per operation, so a rigger who opened the + * strip once finds the next operation's open too. + */ +class OperationStripState { + /** Whether the strip shows its rows or only its header. */ + var expanded: Boolean by mutableStateOf(false) +} + +/** The window's strip state; the shell provides one instance. */ +val LocalOperationStrip = staticCompositionLocalOf { OperationStripState() } + +/** + * How far an area's own bottom-left chrome must lift to clear the strip: the strip's height plus its + * margin while one shows in that area, else zero. Provided by the strip host around the space + * body; the viewport's zoom badge reads it, so the two never overlap. + */ +val LocalOperationStripInset = compositionLocalOf { 0.dp } + +/** The strip's inset from the area's bottom and left edges. */ +private val STRIP_MARGIN = 8.dp + +/** + * The strip's minimum width: a narrow Properties section, so its half-and-half rows read exactly like + * the panel's while the strip stays a strip. The strip grows past it to its widest row - a Row's + * intrinsic width under equal weights is twice its most demanding half - so a long checkbox label + * widens the strip rather than wrapping inside the field column. + */ +private val STRIP_MIN_WIDTH = 300.dp + +/** + * Whether a space hosts the operation settings strip: the 2D viewport and the UV editor, the two work + * surfaces, and nothing else. A panel never shows the strip - Blender's redo panel is a region of the + * editors that have one - so a command fired over a panel places its strip in the last work surface the + * pointer touched instead (CommandRouting.operationStripArea), and a work surface switched to a panel + * after the operation stops showing it until it is switched back. + */ +internal val SpaceKind.hostsOperationStrip: Boolean + get() = this == SpaceKind.Viewport2D || this == SpaceKind.UvEditor + +/** + * Hosts the strip for one area over [content]: the space body renders under the strip's inset, and + * the strip itself draws in the bottom-left whenever the session's adjustable operation names + * [areaId] and [kind] hosts the strip. Mounted by every area leaf, so the gate lives in one place + * rather than in each space - and it is the ONLY place the strip is drawn, so a record whose area is + * not composed (another workspace is active, or the area closed) or names no area shows nowhere. + * + * @param String? areaId The hosting area's id. + * @param SpaceKind kind The space the area currently hosts. + * @param Function content The space body. + */ +@Composable +internal fun OperationStripHost(areaId: String?, kind: SpaceKind, content: @Composable () -> Unit) { + val session = LocalEditorSession.current + // Only a record naming THIS area shows here, and only while the area is a work surface; one naming + // another area, or none, is not this area's to show. + val record = + session?.adjustableOperation?.collectAsState()?.value?.takeIf { candidate -> candidate.areaId == areaId && kind.hostsOperationStrip } + var stripHeight by remember { mutableStateOf(0.dp) } + val density = LocalDensity.current + val inset: Dp = if (record != null) stripHeight + STRIP_MARGIN else 0.dp + CompositionLocalProvider(LocalOperationStripInset provides inset) { + content() + } + if (session != null && record != null) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomStart) { + OperationStrip( + record = record, + session = session, + modifier = + Modifier + .padding(start = STRIP_MARGIN, bottom = STRIP_MARGIN) + .onSizeChanged { size -> stripHeight = with(density) { size.height.toDp() } }, + ) + } + } +} + +/** + * The strip itself: the operation's label as a disclosure header, and its parameter rows when + * expanded. Editing a row publishes the whole parameter list back through + * [EditorSession.adjustLastOperation], which re-runs the operation. + * + * @param AdjustableOperation record The live record. + * @param EditorSession session The session the record belongs to. + * @param Modifier modifier The layout modifier. + */ +@Composable +internal fun OperationStrip( + record: AdjustableOperation, + session: EditorSession, + modifier: Modifier = Modifier, +) { + val strip = LocalOperationStrip.current + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + Column( + modifier = + modifier + .widthIn(min = STRIP_MIN_WIDTH) + .width(IntrinsicSize.Max) + .background(colors.tabBackground, shapes.medium) + .border(width = 1.dp, color = colors.panelBorder, shape = shapes.medium), + ) { + SectionHeader( + label = changeLabel(record.change.labelKey), + expanded = strip.expanded, + onToggle = { strip.expanded = !strip.expanded }, + ) + if (strip.expanded) { + // The Properties section body's own insets and row spacing, so a strip row and a panel row + // sit identically inside their card. + Column( + modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, top = 2.dp, bottom = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + for (parameter in record.parameters) { + key(parameter.key) { + OperationParameterRow(parameter) { updated -> + session.adjustLastOperation(record.parameters.withParameter(parameter.key, updated)) + } + } + } + } + } + } +} + +/** + * One row of the strip, rendered by the parameter's kind through the Properties panel's own row + * primitives - a right-aligned label over a control filling the right half for the numeric and + * choice kinds, a lone checkbox in the field column for a flag - so a strip row and a panel row are + * the same row, description tooltip included. The number fields commit once per edit (a scrub's + * release, a typed value), which is the one run per adjustment the design promises. + * + * @param OperatorParameter parameter The row's parameter. + * @param Function onChange Receives the parameter with its new value. + */ +@Composable +private fun OperationParameterRow( + parameter: OperatorParameter, + onChange: (OperatorParameter) -> Unit, +) { + val label = operatorParameterLabel(parameter.labelKey) + val description = operatorParameterDescription(parameter.labelKey) + when (parameter) { + is OperatorParameter.IntParameter -> { + val unitSuffix = parameterUnitSuffix(parameter.unit) + PropertyFieldRow(label, description = description) { + NumberField( + value = parameter.value, + onValueChange = { value -> onChange(parameter.copy(value = value)) }, + range = parameter.min..parameter.max, + modifier = Modifier.fillMaxWidth(), + step = parameter.step, + unitSuffix = unitSuffix, + ) + } + } + is OperatorParameter.FloatParameter -> { + val unitSuffix = parameterUnitSuffix(parameter.unit) + PropertyFieldRow(label, description = description) { + NumberField( + value = parameter.value, + onValueChange = { value -> onChange(parameter.copy(value = value)) }, + range = parameter.min..parameter.max, + modifier = Modifier.fillMaxWidth(), + decimals = 2, + step = parameter.step, + unitSuffix = unitSuffix, + ) + } + } + is OperatorParameter.BooleanParameter -> { + PropertyCheckboxRow( + checked = parameter.value, + onCheckedChange = { checked -> onChange(parameter.copy(value = checked)) }, + label = label, + description = description, + ) + } + is OperatorParameter.ChoiceParameter -> { + // Choice labels resolve here, in composable scope, because the dropdown's label lambda is not one. + val labelByKey = + parameter.choices.associate { choice -> + choice.key to (choice.labelKey?.let { labelKey -> operatorParameterLabel(labelKey) } ?: choice.key) + } + PropertyFieldRow(label, description = description) { + SelectField( + selected = parameter.value, + options = parameter.choices.map { choice -> choice.key }, + label = { key -> labelByKey[key] ?: key }, + onSelect = { key -> onChange(parameter.copy(value = key)) }, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/OperationStripLabels.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/OperationStripLabels.kt new file mode 100644 index 0000000..deca5cf --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/OperationStripLabels.kt @@ -0,0 +1,193 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.MergeParameterKeys +import org.umamo.edit.MergeTarget +import org.umamo.edit.ParameterUnit +import org.umamo.edit.ProportionalFalloff +import org.umamo.edit.TransformParameterKeys +import org.umamo.edit.choiceKey +import org.umamo.edit.parameterKey +import org.umamo.interop.art.ArtworkAnchor +import org.umamo.ui.model.ImportParameterKeys +import org.umamo.ui.model.MatchParameterKeys +import org.umamo.ui.model.RepackParameterKeys +import org.umamo.ui.resources.* +import org.umamo.ui.viewport.PlacementParameterKeys +import org.umamo.ui.viewport.falloffLabel + +/** + * Maps an [org.umamo.edit.OperatorParameter.labelKey] to its localized row label. The keys are the + * ones each adjustable operation's parameter list declares (a choice's entries carry prefixed keys, + * resolved by [choiceLabel]); an unmapped key renders verbatim so a newly added parameter never + * renders blank. + * + * @param String labelKey The parameter's stable label key. + * @return String The localized label. + */ +@Composable +internal fun operatorParameterLabel(labelKey: String): String = + when (labelKey) { + RepackParameterKeys.PAGE_SIZE -> stringResource(Res.string.repack_options_page_size) + RepackParameterKeys.GUTTER -> stringResource(Res.string.repack_options_gutter) + RepackParameterKeys.EXTRUDE -> stringResource(Res.string.repack_options_extrude) + RepackParameterKeys.ALLOW_ROTATION -> stringResource(Res.string.repack_options_allow_rotation) + RepackParameterKeys.KEEP_PINNED -> stringResource(Res.string.repack_options_keep_pinned) + RepackParameterKeys.POWER_OF_TWO -> stringResource(Res.string.repack_options_power_of_two) + RepackParameterKeys.SQUARE_PAGES -> stringResource(Res.string.repack_options_square_pages) + RepackParameterKeys.SHRINK_PAGES -> stringResource(Res.string.repack_options_shrink_pages) + RepackParameterKeys.ALPHA_THRESHOLD -> stringResource(Res.string.repack_options_alpha_threshold) + PlacementParameterKeys.DELTA_X -> stringResource(Res.string.placement_options_move_x) + PlacementParameterKeys.DELTA_Y -> stringResource(Res.string.placement_options_move_y) + PlacementParameterKeys.ANGLE -> stringResource(Res.string.placement_options_angle) + PlacementParameterKeys.SCALE_X -> stringResource(Res.string.placement_options_scale_x) + PlacementParameterKeys.SCALE_Y -> stringResource(Res.string.placement_options_scale_y) + ImportParameterKeys.ALIGN -> stringResource(Res.string.import_options_align) + ImportParameterKeys.OFFSET_X -> stringResource(Res.string.import_options_offset_x) + ImportParameterKeys.OFFSET_Z -> stringResource(Res.string.import_options_offset_z) + ImportParameterKeys.ALPHA_THRESHOLD -> stringResource(Res.string.import_options_alpha_threshold) + ImportParameterKeys.MARGIN -> stringResource(Res.string.import_options_margin) + MatchParameterKeys.THRESHOLD -> stringResource(Res.string.match_options_threshold) + // The transform rows share the placement rows' Move / Angle / Scale labels where the text is the + // same; the viewport's vertical axis is Z (Y+ forward, Z+ up), so it has labels of its own. + TransformParameterKeys.MOVE_X -> stringResource(Res.string.placement_options_move_x) + TransformParameterKeys.MOVE_Y -> stringResource(Res.string.placement_options_move_y) + TransformParameterKeys.MOVE_Z -> stringResource(Res.string.transform_options_move_z) + TransformParameterKeys.ANGLE -> stringResource(Res.string.placement_options_angle) + TransformParameterKeys.SCALE_X -> stringResource(Res.string.placement_options_scale_x) + TransformParameterKeys.SCALE_Y -> stringResource(Res.string.placement_options_scale_y) + TransformParameterKeys.SCALE_Z -> stringResource(Res.string.transform_options_scale_z) + TransformParameterKeys.PROPORTIONAL -> stringResource(Res.string.transform_options_proportional) + TransformParameterKeys.FALLOFF -> stringResource(Res.string.transform_options_falloff) + TransformParameterKeys.PROPORTIONAL_SIZE -> stringResource(Res.string.transform_options_proportional_size) + TransformParameterKeys.CONNECTED_ONLY -> stringResource(Res.string.transform_options_connected) + TransformParameterKeys.SLIDE_FACTOR -> stringResource(Res.string.transform_options_slide_factor) + MergeParameterKeys.TARGET -> stringResource(Res.string.merge_options_target) + else -> choiceLabel(labelKey) ?: labelKey + } + +/** + * Maps an [org.umamo.edit.OperatorParameter.labelKey] to the description its row shows as a tooltip over + * the label: what the parameter did to the operation it adjusts. + * + * Keyed by the parameter rather than by its label, because two operations may share a label and still mean + * different things by it: a placement's Move Y is page pixels running down the page, while a viewport + * transform's vertical move is Move Z running up. Not composable, so a test can pin that every key the + * strip can show has one. + * + * @param String labelKey The parameter's stable label key. + * @return StringResource? The description, or null for a choice entry's key or a key with none. + */ +internal fun operatorParameterDescriptionRes(labelKey: String): StringResource? = + when (labelKey) { + RepackParameterKeys.PAGE_SIZE -> Res.string.repack_options_page_size_description + RepackParameterKeys.GUTTER -> Res.string.repack_options_gutter_description + RepackParameterKeys.EXTRUDE -> Res.string.repack_options_extrude_description + RepackParameterKeys.ALLOW_ROTATION -> Res.string.repack_options_allow_rotation_description + RepackParameterKeys.KEEP_PINNED -> Res.string.repack_options_keep_pinned_description + RepackParameterKeys.POWER_OF_TWO -> Res.string.repack_options_power_of_two_description + RepackParameterKeys.SQUARE_PAGES -> Res.string.repack_options_square_pages_description + RepackParameterKeys.SHRINK_PAGES -> Res.string.repack_options_shrink_pages_description + RepackParameterKeys.ALPHA_THRESHOLD -> Res.string.repack_options_alpha_threshold_description + PlacementParameterKeys.DELTA_X -> Res.string.placement_options_move_x_description + PlacementParameterKeys.DELTA_Y -> Res.string.placement_options_move_y_description + PlacementParameterKeys.ANGLE -> Res.string.placement_options_angle_description + PlacementParameterKeys.SCALE_X -> Res.string.placement_options_scale_x_description + PlacementParameterKeys.SCALE_Y -> Res.string.placement_options_scale_y_description + ImportParameterKeys.ALIGN -> Res.string.import_options_align_description + ImportParameterKeys.OFFSET_X -> Res.string.import_options_offset_x_description + ImportParameterKeys.OFFSET_Z -> Res.string.import_options_offset_z_description + ImportParameterKeys.ALPHA_THRESHOLD -> Res.string.import_options_alpha_threshold_description + ImportParameterKeys.MARGIN -> Res.string.import_options_margin_description + MatchParameterKeys.THRESHOLD -> Res.string.match_options_threshold_description + TransformParameterKeys.MOVE_X -> Res.string.transform_options_move_x_description + TransformParameterKeys.MOVE_Y -> Res.string.transform_options_move_y_description + TransformParameterKeys.MOVE_Z -> Res.string.transform_options_move_z_description + TransformParameterKeys.ANGLE -> Res.string.transform_options_angle_description + TransformParameterKeys.SCALE_X -> Res.string.transform_options_scale_x_description + TransformParameterKeys.SCALE_Y -> Res.string.transform_options_scale_y_description + TransformParameterKeys.SCALE_Z -> Res.string.transform_options_scale_z_description + TransformParameterKeys.PROPORTIONAL -> Res.string.transform_options_proportional_description + TransformParameterKeys.FALLOFF -> Res.string.transform_options_falloff_description + TransformParameterKeys.PROPORTIONAL_SIZE -> Res.string.transform_options_proportional_size_description + TransformParameterKeys.CONNECTED_ONLY -> Res.string.transform_options_connected_description + TransformParameterKeys.SLIDE_FACTOR -> Res.string.transform_options_slide_factor_description + MergeParameterKeys.TARGET -> Res.string.merge_options_target_description + else -> null + } + +/** + * The localized description of a parameter's row, or blank when it has none (which attaches no tooltip). + * + * @param String labelKey The parameter's stable label key. + * @return String The description, or an empty string. + */ +@Composable +internal fun operatorParameterDescription(labelKey: String): String = operatorParameterDescriptionRes(labelKey)?.let { resource -> stringResource(resource) } ?: "" + +/** + * The localized label of a choice entry's prefixed key: a falloff curve's, a merge target's, or an + * import anchor's. + * + * @param String labelKey The entry's label key. + * @return String? The label, or null when the key carries none of the prefixes. + */ +@Composable +private fun choiceLabel(labelKey: String): String? { + if (labelKey.startsWith(TransformParameterKeys.FALLOFF_CHOICE_PREFIX)) { + val key = labelKey.removePrefix(TransformParameterKeys.FALLOFF_CHOICE_PREFIX) + return ProportionalFalloff.entries.firstOrNull { falloff -> falloff.choiceKey == key }?.let { falloff -> falloffLabel(falloff) } + } + if (labelKey.startsWith(ImportParameterKeys.ANCHOR_CHOICE_PREFIX)) { + val key = labelKey.removePrefix(ImportParameterKeys.ANCHOR_CHOICE_PREFIX) + return ArtworkAnchor.entries.firstOrNull { anchor -> anchor.key == key }?.let { anchor -> artworkAnchorLabel(anchor) } + } + if (labelKey.startsWith(MergeParameterKeys.TARGET_CHOICE_PREFIX)) { + val key = labelKey.removePrefix(MergeParameterKeys.TARGET_CHOICE_PREFIX) + return when (MergeTarget.entries.firstOrNull { target -> target.parameterKey == key }) { + MergeTarget.AtCenter -> stringResource(Res.string.merge_target_center) + MergeTarget.AtFirst -> stringResource(Res.string.merge_target_first) + MergeTarget.AtLast -> stringResource(Res.string.merge_target_last) + null -> null + } + } + return null +} + +/** + * The localized name of an import anchor, shared by the strip's Align row and the Import settings + * row that seeds it. + * + * @param ArtworkAnchor anchor The anchor. + * @return String The label. + */ +@Composable +internal fun artworkAnchorLabel(anchor: ArtworkAnchor): String = + when (anchor) { + ArtworkAnchor.TopLeft -> stringResource(Res.string.import_anchor_top_left) + ArtworkAnchor.Top -> stringResource(Res.string.import_anchor_top) + ArtworkAnchor.TopRight -> stringResource(Res.string.import_anchor_top_right) + ArtworkAnchor.Left -> stringResource(Res.string.import_anchor_left) + ArtworkAnchor.Center -> stringResource(Res.string.import_anchor_center) + ArtworkAnchor.Right -> stringResource(Res.string.import_anchor_right) + ArtworkAnchor.BottomLeft -> stringResource(Res.string.import_anchor_bottom_left) + ArtworkAnchor.Bottom -> stringResource(Res.string.import_anchor_bottom) + ArtworkAnchor.BottomRight -> stringResource(Res.string.import_anchor_bottom_right) + } + +/** + * The suffix a numeric row shows after its value for [unit], or null for a unitless one. + * + * @param ParameterUnit unit The parameter's display unit. + * @return String? The localized unit suffix. + */ +@Composable +internal fun parameterUnitSuffix(unit: ParameterUnit): String? = + when (unit) { + ParameterUnit.None -> null + ParameterUnit.Pixels -> stringResource(Res.string.unit_pixels) + ParameterUnit.Degrees -> stringResource(Res.string.unit_degrees) + ParameterUnit.Percent -> stringResource(Res.string.unit_percent) + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/RelationPick.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/RelationPick.kt new file mode 100644 index 0000000..9d9e7e6 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/RelationPick.kt @@ -0,0 +1,216 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import org.umamo.edit.SelectionTarget + +/** + * The kinds of rig entity a relation pick will accept, mirroring [SelectionTarget]'s taxonomy without + * carrying an id. A request names the kinds its field can bind, so the viewport overlay and the outliner + * both know which clicks to honour and which to ignore. + */ +enum class PickKind { + /** An organizational tree part. */ + Part, + + /** A textured drawable mesh. */ + Drawable, + + /** A warp or rotation deformer. */ + Deformer, +} + +/** + * The kind of [target], so a request's accepted set can be tested against a concrete pick. + * + * @return PickKind The target's kind. + */ +fun SelectionTarget.pickKind(): PickKind = + when (this) { + is SelectionTarget.Part -> PickKind.Part + is SelectionTarget.Drawable -> PickKind.Drawable + is SelectionTarget.Deformer -> PickKind.Deformer + } + +/** + * What a surface should do with a click while a relation pick may be armed. Stated once here because the + * wrong answer is subtle: letting an unaccepted click through changes the selection, which swaps the + * Properties panel - and the very field that armed the pick - out from under the user mid-interaction. + */ +enum class PickClickOutcome { + /** The click bound the entity; the pick is over. The surface should not also select. */ + Resolved, + + /** A pick is armed but this entity is not one it accepts: swallow the click and stay armed. */ + Swallowed, + + /** No pick is armed; the surface should handle the click normally (select it). */ + Ignored, +} + +/** + * One in-flight "pick a relation" interaction: which kinds the arming field accepts, an [owner] key + * identifying the field that armed it, and the callback that receives the chosen entity. [onPicked] is + * invoked at most once - the resolving surface clears the request as it fires. + * + * @property Set accepts The entity kinds this pick will honour; a click on anything else is ignored. + * @property Any? owner The arming field's identity, so only that field lights its eyedropper. + * @property Function onPicked Receives the picked entity. + */ +class RelationPickRequest( + val accepts: Set, + val owner: Any?, + val onPicked: (SelectionTarget) -> Unit, +) + +/** + * The shell slot holding the one in-flight relation pick, mirroring [org.umamo.ui.workspace.rowdrag.RowDragCancelController]. A pick is + * deliberately NOT an [org.umamo.edit.ToolLatches] latch: every latch is scoped to one viewport area, but a + * pick must also resolve from the outliner, and the latches are non-reactive vars while both resolving + * surfaces need to gate their composition on this state. Parking it here also keeps a panel concern out of + * the edit module. One pointer means at most one pick anywhere, so a single slot serves every field. + * + * Resolving a pick must NOT go through the real selection: [org.umamo.edit.EditorSession.setSelection] + * records an undo step and would swap the Properties panel out from under the field that armed the pick. + * + * @property RelationPickRequest? request The in-flight pick, or null when none is armed. + */ +class RelationPickController { + var request: RelationPickRequest? by mutableStateOf(null) + private set + + /** + * What the pointer is currently over, as the in-flight pick would resolve it, or null when it is over + * nothing pickable. Published by the resolving surfaces (the viewport's hit test, an outliner row) so + * the shell's cursor overlay can name the target before the user commits to it. + */ + var hoveredTarget: SelectionTarget? by mutableStateOf(null) + private set + + /** + * Arms a pick, replacing any already in flight. + * + * @param Set accepts The entity kinds to honour. + * @param Any? owner The arming field's identity, so only it lights its eyedropper. + * @param Function onPicked Receives the picked entity. + */ + fun arm(accepts: Set, owner: Any? = null, onPicked: (SelectionTarget) -> Unit) { + hoveredTarget = null + request = RelationPickRequest(accepts, owner, onPicked) + } + + /** + * Publishes what the pointer is over. Ignored when no pick is armed, and a target of an unaccepted kind + * reports as nothing - so a surface may report freely without gating itself. + * + * @param SelectionTarget? target The entity under the pointer, or null for nothing pickable. + */ + fun hover(target: SelectionTarget?) { + val pending = request ?: return + hoveredTarget = target?.takeIf { candidate -> candidate.pickKind() in pending.accepts } + } + + /** + * Withdraws [target] as the hover, but only when it is still the reported one - so a surface the pointer + * has left cannot clear a hover another surface has since published. + * + * @param SelectionTarget target The entity this surface last reported. + */ + fun unhover(target: SelectionTarget) { + if (hoveredTarget == target) { + hoveredTarget = null + } + } + + /** + * Whether the in-flight pick was armed by [owner] - the field's cue to light its eyedropper. + * + * @param Any? owner The field identity to test. + * @return Boolean True when a pick armed by that field is in flight. + */ + fun isPickingFor(owner: Any?): Boolean = owner != null && request?.owner == owner + + /** Cancels the in-flight pick, if any (Escape, a right-click, or the arming field going away). */ + fun cancel() { + request = null + hoveredTarget = null + } + + /** + * Cancels the in-flight pick only when [owner] armed it. Scoped rather than blanket so a field tearing + * down cannot cancel a pick some other field owns. + * + * @param Any? owner The field identity whose pick should be dropped. + */ + fun cancelFor(owner: Any?) { + if (isPickingFor(owner)) { + cancel() + } + } + + /** + * How a selecting surface (an outliner row) should treat a click on [target]. While ANY pick is armed + * the surface must not change the selection - even for an entity the pick will not accept - because + * selecting would swap the Properties panel, and the arming field with it, out from under the pick. + * + * @param SelectionTarget target The entity the user clicked. + * @return PickClickOutcome Resolved (bound it), Swallowed (armed but unaccepted), or Ignored (no pick). + */ + fun click(target: SelectionTarget): PickClickOutcome = + when { + request == null -> PickClickOutcome.Ignored + resolve(target) -> PickClickOutcome.Resolved + else -> PickClickOutcome.Swallowed + } + + /** + * Resolves the in-flight pick with [target] when its kind is accepted, clearing the request first so the + * callback cannot re-enter. A target of an unaccepted kind leaves the pick armed, so a stray click on + * the wrong kind of thing does not silently end the interaction. + * + * @param SelectionTarget target The entity the user clicked. + * @return Boolean True when the pick was resolved (the caller should consume the click). + */ + fun resolve(target: SelectionTarget): Boolean { + val pending = request ?: return false + if (target.pickKind() !in pending.accepts) { + return false + } + request = null + hoveredTarget = null + pending.onPicked(target) + return true + } +} + +/** + * Supplies the [RelationPickController] the shell shares with the picking fields and the surfaces that + * resolve them. Defaults to a standalone instance so a panel hosted without the shell still composes (its + * eyedropper simply never resolves). + */ +val LocalRelationPick = staticCompositionLocalOf { RelationPickController() } + +/** + * Whether a pick armed by [owner] is in flight, AND the guarantee that it is cancelled if that field + * leaves the composition. + * + * The two belong together: an armed pick parks a callback plus a full-window hidden cursor in shell state, + * so a field that arms one and then disappears - a Properties tab switch, a selection change, closing the + * document - would otherwise strand the editor with an invisible pointer, an eyedropper badge, and a + * callback closing over entities from a document that is gone. Reading the flag through this function + * means a call site cannot take the cue without also taking the cleanup. + * + * @param Any? owner The field identity to test. + * @return Boolean True when a pick armed by that field is in flight. + */ +@Composable +fun RelationPickController.pickingFor(owner: Any?): Boolean { + DisposableEffect(this, owner) { + onDispose { cancelFor(owner) } + } + return isPickingFor(owner) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SessionStateJson.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SessionStateJson.kt new file mode 100644 index 0000000..b0a8a19 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SessionStateJson.kt @@ -0,0 +1,254 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.umamo.edit.Cursor2d +import org.umamo.edit.DEFAULT_PROPORTIONAL_EDIT_STATE +import org.umamo.edit.EditorMode +import org.umamo.edit.GridConfig +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.ParameterSelection +import org.umamo.edit.Pose +import org.umamo.edit.ProportionalEditState +import org.umamo.edit.ProportionalFalloff +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.SessionViewState +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.UvCursor +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/* + * The editor entry's session block (docs/format/UMA.md §7.4): the pose and the session state a document was + * saved with. Read tolerantly and written with every known member named, like the area blocks (§7.1, §7.5). + * Nothing here validates an id against the model - the session does that when it opens (SessionViewState.fittedTo) + * and the loader clamps the pose - so this file stays a plain mapping between the tree and the data. + */ + +/** The root member holding the session block (UMA §7.2). */ +const val EDITOR_STATE_SESSION: String = "session" + +/** + * The session block for a save. + * + * @param SessionViewState viewState The session's state as gathered. + * @param Pose pose The session's pose as gathered. + * @param PuppetModel model The model being saved, whose parameter defaults decide which pose values deviate. + * @return JsonObject The block, every known member named. + */ +fun sessionStateJson(viewState: SessionViewState, pose: Pose, model: PuppetModel): JsonObject = + buildJsonObject { + // UMA §7.4: `pose` lists each parameter away from its default, in the model's parameter order. + val posed = + model.parameters.mapNotNull { parameter -> + val value = pose[parameter.id]?.takeIf { posedValue -> posedValue.isFinite() && posedValue != parameter.default } ?: return@mapNotNull null + buildJsonObject { + put("parameter", JsonPrimitive(parameter.id.raw)) + put("value", JsonPrimitive(value)) + } + } + put("pose", if (posed.isEmpty()) JsonNull else JsonArray(posed)) + put( + "selection", + if (viewState.selection.isEmpty) { + JsonNull + } else { + buildJsonObject { + put("targets", JsonArray(viewState.selection.targets.map { target -> JsonPrimitive(objectReferenceOf(target)) })) + put("active", viewState.selection.active?.let { active -> JsonPrimitive(objectReferenceOf(active)) } ?: JsonNull) + } + }, + ) + put( + "parameterSelection", + if (viewState.parameterSelection.isEmpty) { + JsonNull + } else { + buildJsonObject { + put("ids", JsonArray(viewState.parameterSelection.ids.map { parameterId -> JsonPrimitive(parameterId.raw) })) + put("active", viewState.parameterSelection.active?.let { active -> JsonPrimitive(active.raw) } ?: JsonNull) + } + }, + ) + put("mode", if (viewState.mode == EditorMode.Edit) JsonPrimitive("edit") else JsonNull) + put("selectMode", if (viewState.selectMode == MeshSelectMode.Vertex) JsonNull else JsonPrimitive(selectModeWireName(viewState.selectMode))) + put("cursor2d", viewState.cursor2d?.let { cursor -> floatPairOrNull(cursor.worldX, cursor.worldZ) } ?: JsonNull) + put("uvCursor", viewState.uvCursor?.let { cursor -> floatPairOrNull(cursor.u, cursor.v) } ?: JsonNull) + put("pivot", if (viewState.pivotMode == TransformPivotMode.MedianPoint) JsonNull else JsonPrimitive(pivotWireName(viewState.pivotMode))) + put( + "proportional", + viewState.proportionalSettings?.takeIf { settings -> viewState.proportionalEnabled || settings != DEFAULT_PROPORTIONAL_SETTINGS }?.let { settings -> + buildJsonObject { + put("enabled", if (viewState.proportionalEnabled) JsonPrimitive(true) else JsonNull) + put("falloff", JsonPrimitive(falloffWireName(settings.falloff))) + put("radius", JsonPrimitive(settings.radiusWorld)) + put("connectedOnly", if (settings.connectedOnly) JsonPrimitive(true) else JsonNull) + } + } ?: JsonNull, + ) + put( + "grid", + viewState.gridConfig?.let { grid -> + buildJsonObject { + put("scale", JsonPrimitive(grid.scale)) + put("subdivisions", JsonPrimitive(grid.subdivisions)) + } + } ?: JsonNull, + ) + } + +/** + * The session state a document was saved with, or null when it saved none. + * + * @param JsonObject? tree The session block as the file held it, or null. + * @return SessionViewState? The state, not yet fitted to any model. + */ +fun sessionViewStateOf(tree: JsonObject?): SessionViewState? { + if (tree == null) { + return null + } + val selection = tree["selection"] as? JsonObject + val targets = selection?.let { block -> stringListOf(block, "targets") }.orEmpty().mapNotNullTo(LinkedHashSet(), ::selectionTargetOf) + val parameterSelection = tree["parameterSelection"] as? JsonObject + val parameterIds = parameterSelection?.let { block -> stringListOf(block, "ids") }.orEmpty().mapTo(LinkedHashSet(), ::ParameterId) + val proportional = tree["proportional"] as? JsonObject + val grid = tree["grid"] as? JsonObject + return SessionViewState( + selection = Selection(targets, selection?.let { block -> stringOf(block, "active") }?.let(::selectionTargetOf)), + parameterSelection = ParameterSelection(parameterIds, parameterSelection?.let { block -> stringOf(block, "active") }?.let(::ParameterId)), + mode = if (stringOf(tree, "mode") == "edit") EditorMode.Edit else EditorMode.Object, + selectMode = stringOf(tree, "selectMode")?.let { wireName -> MeshSelectMode.entries.firstOrNull { mode -> selectModeWireName(mode) == wireName } } ?: MeshSelectMode.Vertex, + cursor2d = floatListOf(tree, "cursor2d", 2)?.let { (worldX, worldZ) -> Cursor2d(worldX, worldZ) }, + uvCursor = floatListOf(tree, "uvCursor", 2)?.let { (u, v) -> UvCursor(u, v) }, + pivotMode = stringOf(tree, "pivot")?.let { wireName -> TransformPivotMode.entries.firstOrNull { mode -> pivotWireName(mode) == wireName } } ?: TransformPivotMode.MedianPoint, + proportionalEnabled = proportional?.let { block -> booleanOf(block, "enabled") } ?: false, + proportionalSettings = + proportional?.let { block -> + ProportionalEditState( + falloff = stringOf(block, "falloff")?.let { wireName -> ProportionalFalloff.entries.firstOrNull { falloff -> falloffWireName(falloff) == wireName } } ?: DEFAULT_PROPORTIONAL_SETTINGS.falloff, + radiusWorld = finiteFloatOf(block["radius"])?.takeIf { radius -> radius > 0f } ?: DEFAULT_PROPORTIONAL_SETTINGS.radiusWorld, + connectedOnly = booleanOf(block, "connectedOnly") ?: false, + ) + }, + // UMA §7.4: a grid needs a positive scale and at least one subdivision; anything else follows the application's. + gridConfig = + grid?.let { block -> + val scale = finiteFloatOf(block["scale"])?.takeIf { value -> value > 0f } + val subdivisions = intOf(block["subdivisions"])?.takeIf { value -> value >= 1 } + if (scale != null && subdivisions != null) GridConfig(scale, subdivisions) else null + }, + ) +} + +/** + * The pose a document was saved with, by parameter id: only what the file listed, unclamped and unchecked against + * any model - the loader does both as it builds the live parameters. + * + * @param JsonObject? tree The session block as the file held it, or null. + * @return Map The saved values, empty when the file saved none. + */ +fun savedPoseOf(tree: JsonObject?): Map { + val entries = tree?.get("pose") as? JsonArray ?: return emptyMap() + val pose = LinkedHashMap() + for (entry in entries) { + val block = entry as? JsonObject ?: continue + val parameterId = stringOf(block, "parameter") ?: continue + val value = finiteFloatOf(block["value"]) ?: continue + pose[ParameterId(parameterId)] = value + } + return pose +} + +/** The proportional configuration a session starts with, which a save leaves out while proportional editing is off. */ +private val DEFAULT_PROPORTIONAL_SETTINGS: ProportionalEditState = DEFAULT_PROPORTIONAL_EDIT_STATE + +/** + * Two floats as the entry's pair form, or a JSON null when either is not finite (UMA §7.1). + * + * @param Float first The first component. + * @param Float second The second component. + * @return JsonElement The pair, or null. + */ +private fun floatPairOrNull(first: Float, second: Float): JsonElement = + if (first.isFinite() && second.isFinite()) JsonArray(listOf(JsonPrimitive(first), JsonPrimitive(second))) else JsonNull + +/** + * A selection target as an object reference (UMA §7.1): `part:`, `drawable:`, or `deformer:` plus the model's id. + * + * @param SelectionTarget target The target. + * @return String The reference. + */ +internal fun objectReferenceOf(target: SelectionTarget): String = + when (target) { + is SelectionTarget.Part -> "part:${target.id.raw}" + is SelectionTarget.Drawable -> "drawable:${target.id.raw}" + is SelectionTarget.Deformer -> "deformer:${target.id.raw}" + } + +/** + * The selection target an object reference names, or null for a reference of no known kind. + * + * @param String reference The reference. + * @return SelectionTarget? The target. + */ +internal fun selectionTargetOf(reference: String): SelectionTarget? = + when { + reference.startsWith("part:") -> SelectionTarget.Part(PartId(reference.removePrefix("part:"))) + reference.startsWith("drawable:") -> SelectionTarget.Drawable(DrawableId(reference.removePrefix("drawable:"))) + reference.startsWith("deformer:") -> SelectionTarget.Deformer(DeformerId(reference.removePrefix("deformer:"))) + else -> null + } + +/** + * A mesh select mode's name in the editor entry. + * + * @param MeshSelectMode mode The mode. + * @return String The wire name. + */ +private fun selectModeWireName(mode: MeshSelectMode): String = + // UMA §7.4: `selectMode`. + when (mode) { + MeshSelectMode.Vertex -> "vertex" + MeshSelectMode.Edge -> "edge" + MeshSelectMode.Face -> "face" + } + +/** + * A pivot mode's name in the editor entry. + * + * @param TransformPivotMode mode The mode. + * @return String The wire name. + */ +private fun pivotWireName(mode: TransformPivotMode): String = + // UMA §7.4: `pivot`. + when (mode) { + TransformPivotMode.MedianPoint -> "medianPoint" + TransformPivotMode.IndividualOrigins -> "individualOrigins" + TransformPivotMode.ActiveElement -> "activeElement" + TransformPivotMode.Cursor -> "cursor" + } + +/** + * A proportional falloff's name in the editor entry. + * + * @param ProportionalFalloff falloff The falloff. + * @return String The wire name. + */ +private fun falloffWireName(falloff: ProportionalFalloff): String = + // UMA §7.4: `proportional.falloff`. + when (falloff) { + ProportionalFalloff.Smooth -> "smooth" + ProportionalFalloff.Sphere -> "sphere" + ProportionalFalloff.Root -> "root" + ProportionalFalloff.Sharp -> "sharp" + ProportionalFalloff.Linear -> "linear" + ProportionalFalloff.Constant -> "constant" + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellCursorClaim.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellCursorClaim.kt new file mode 100644 index 0000000..8bad374 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellCursorClaim.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.workspace + +/** + * What the shell root is saying about the pointer, window-wide, over every cursor a panel or gizmo would + * otherwise choose for itself. A whole-window claim is how a mode announces itself: the pointer changes + * the moment the mode begins, wherever the hand happens to be. + */ +internal enum class ShellCursorClaim { + // No mode is running; each panel, splitter, and gizmo keeps its own cursor. + None, + + // A relation pick is armed: the OS pointer is hidden and the shell draws the eyedropper itself. + Hidden, + + // Text entry is live: the platform's own text pointer, everywhere, until the field lets go. + TextEdit, +} + +/** + * Whether this claim must beat the cursors its descendants ask for. Every real claim does - a mode that + * let a splitter edge or a scrub zone keep its own pointer would stop reading as a mode at all - and + * [ShellCursorClaim.None] must not, since with nothing claimed the descendants are the whole answer. + */ +internal val ShellCursorClaim.overridesDescendants: Boolean + get() = this != ShellCursorClaim.None + +/** + * Resolves the one cursor the shell root claims, from the modes that can be running. + * + * A pick outranks text entry because the shell DRAWS the eyedropper at the pointer: a visible I-beam + * under it would read as two cursors. The two cannot overlap in practice anyway - arming a pick is a + * click, which ends text entry - so the order is here to be stated rather than to be relied on. + * + * @param Boolean relationPickArmed Whether a relation pick is waiting for its target. + * @param Boolean textEntryActive Whether a text editor has parked its cancel hook. + * @return ShellCursorClaim The claim the root applies to the whole window. + */ +internal fun shellCursorClaim( + relationPickArmed: Boolean, + textEntryActive: Boolean, +): ShellCursorClaim = + when { + relationPickArmed -> ShellCursorClaim.Hidden + textEntryActive -> ShellCursorClaim.TextEdit + else -> ShellCursorClaim.None + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellCursorOverlays.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellCursorOverlays.kt new file mode 100644 index 0000000..86f3086 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellCursorOverlays.kt @@ -0,0 +1,286 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerInputScope +import androidx.compose.ui.layout.layout +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.delay +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.KeyformAction +import org.umamo.edit.NoticePlacement +import org.umamo.edit.SelectionTarget +import org.umamo.edit.resolveParameterChoice +import org.umamo.ui.kit.AtPointPositionProvider +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.PieMenuOverlay +import org.umamo.ui.kit.TooltipCard +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.noticeText +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.keyform_choose_parameter_insert +import org.umamo.ui.resources.keyform_choose_parameter_remove +import org.umamo.ui.resources.pick_hover_deformer +import org.umamo.ui.resources.pick_hover_drawable +import org.umamo.ui.resources.pick_hover_part +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.drawCursor +import org.umamo.ui.viewport.pieMenuEntriesFor +import org.umamo.ui.viewport.pieMenuTitleFor +import kotlin.math.roundToInt + +/** How long (ms) a near-cursor notice stays visible before it auto-dismisses. */ +private const val SHELL_NOTICE_VISIBLE_MS = 3000L + +/** Gap (dp) between the pointer and the notice badge, so the badge never sits under the cursor. */ +private val SHELL_POINTER_GAP = 14.dp + +/** + * Observes every pointer event in the Initial pass without consuming, reporting the latest position. + * Installed on the shell's root surface (an ancestor of every area), so it sees the pointer no matter + * which panel or overlay owns the gesture - consumption is advisory and never hides events from an + * Initial-pass ancestor, so this keeps tracking even while an open pie swallows input. The reported + * positions anchor the shell-level cursor overlays (the pie menu and near-cursor notices). + * + * ポインタ位置の観測。Initial パスで消費せずに監視するため、どのオーバーレイがジェスチャを + * 所有していても最新位置が得られる。シェル直上のカーソル追従オーバーレイのアンカーになる。 + * + * @param Function onPointer Receives each event's latest position in shell-root pixels. + */ +internal suspend fun PointerInputScope.observeWindowPointer(onPointer: (Offset) -> Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + event.changes.lastOrNull()?.let { change -> onPointer(change.position) } + } + } +} + +/** + * The shell-level radial pie menu host: observes the open document's pie latch and renders the entry + * ring at the window-space pointer position, frozen at open (the pie opens under the hand, + * Blender-style). Living ABOVE the area tree - not inside a viewport's clipped box - is what lets + * the ring escape area bounds, and being the only instance structurally prevents any cross-viewport + * duplication (a per-viewport copy could never be gated consistently). + * [PieMenuOverlay] clamps the center to the window so the ring never clips (Blender's + * constrain-to-screen); entries dispatch through the command registry, and opening / closing go + * through the session so the shell's key ladder routes Escape and the 1..N digits unchanged. + * + * シェル直上のパイメニューホスト。エリアツリーの上に一つだけ描画されるため、ビューポート境界を + * はみ出せて、複数ビューポートでの重複表示も構造的に起きない。中心はウィンドウ内にクランプされる。 + * + * @param Offset? pointerPosition The last pointer position in shell-root pixels, or null before any + * pointer event (a keyboard-opened pie then centers in the window). + * @param Modifier modifier The layout modifier (the shell passes a window fill). + */ +@Composable +internal fun ShellPieMenuHost(pointerPosition: Offset?, modifier: Modifier = Modifier) { + val session = LocalEditorSession.current ?: return + val activePie by session.activePieMenu.collectAsState() + val kind = activePie ?: return + val entries = pieMenuEntriesFor(kind) + if (entries.isEmpty()) { + return + } + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + // The anchor freezes at open (keyed on the pie kind): passing the live pointer would drag the + // whole ring - labels and all - around with the mouse instead of letting the pointer travel + // OVER a stationary pie to pick by direction. + val fallbackCenter = Offset(constraints.maxWidth / 2f, constraints.maxHeight / 2f) + val frozenCenter = remember(kind) { pointerPosition ?: fallbackCenter } + PieMenuOverlay( + entries = entries, + center = frozenCenter, + onDismiss = { session.closePieMenu() }, + title = pieMenuTitleFor(kind), + ) + } +} + +/** + * The shell-level near-cursor notice: transient [NoticePlacement.NearCursor] notices (Blender's + * "can't do this because" style) beside the live window-space pointer, auto-dismissed after a few + * seconds. One instance above the area tree replaces the per-viewport copies, so the badge follows + * the pointer across areas without duplicating, escapes area bounds, and appears at the true pointer + * even when it hovers a non-viewport panel (the per-area version rendered in whichever viewport the + * pointer last touched). Draw-only - installs no pointer input. + * + * @param Offset? pointerPosition The last pointer position in shell-root pixels, or null before any + * pointer event (the notice then anchors at the window's lower center). + * @param Modifier modifier The layout modifier (the shell passes a window fill). + */ +@Composable +internal fun ShellNearCursorNotice(pointerPosition: Offset?, modifier: Modifier = Modifier) { + val session = LocalEditorSession.current ?: return + val notice by session.notice.collectAsState() + val current = notice ?: return + if (current.placement != NoticePlacement.NearCursor) { + return + } + // Auto-dismiss after the visible window; keyed on the serial so a repeated notice restarts the + // timer, and clearNotice only clears if a newer notice has not replaced this one meanwhile. + LaunchedEffect(current.serial) { + delay(SHELL_NOTICE_VISIBLE_MS) + session.clearNotice(current.serial) + } + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + // Anchor beside the pointer, falling back to the lower center when no pointer has entered yet + // (a keyboard-triggered notice can arrive before any pointer event). + val anchor = pointerPosition ?: Offset(constraints.maxWidth / 2f, constraints.maxHeight * 0.75f) + TooltipCard( + text = noticeText(current.messageKey, current.arguments), + modifier = Modifier.nearPointer(anchor, SHELL_POINTER_GAP), + ) + } +} + +/** + * The shell-level "which parameter?" prompt: lists the targeted parameters at the pointer when a keyform + * edit could not tell which axis the user meant, and replays the parked edit on the one picked. + * + * Only a LINKED PAD produces this - it targets both its axes but reports only the horizontal one as active, + * so an unaimed `I` would always write there and the vertical section would keep reading as unkeyed. A + * sheet lane names its own parameter and never reaches here. + * + * Above the area tree for the same reason the pie menu is: the prompt answers a keypress made over a + * Properties row, and it must not be clipped to that panel's box. + * + * @param Offset? pointerPosition The last pointer position in shell-root pixels, or null before any + * pointer event (the prompt then opens at the window's center). + * @param Modifier modifier The layout modifier (the shell passes a window fill). + */ +@Composable +internal fun ShellParameterChoiceMenu(pointerPosition: Offset?, modifier: Modifier = Modifier) { + val session = LocalEditorSession.current ?: return + val puppet = LocalPuppet.current + val request by session.pendingParameterChoice.collectAsState() + val pending = request ?: return + val title = + stringResource( + when (pending.action) { + KeyformAction.Capture -> Res.string.keyform_choose_parameter_insert + KeyformAction.Remove -> Res.string.keyform_choose_parameter_remove + }, + ) + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + val anchor = pointerPosition ?: Offset(constraints.maxWidth / 2f, constraints.maxHeight / 2f) + val items = + // A disabled row plus a rule is the kit's only header shape; the candidates below it carry the + // parameters' own display names, which are the user's data and so are never localized. + listOf(MenuItem.Action(label = title, onSelect = {}, enabled = false), MenuItem.Separator) + + pending.candidates.map { candidateId -> + val name = + puppet?.parameters?.firstOrNull { parameter -> parameter.id == candidateId } + ?.name?.ifBlank { candidateId.raw } ?: candidateId.raw + MenuItem.Action(label = name, onSelect = { session.resolveParameterChoice(candidateId) }) + } + Menu( + items = items, + onDismissRequest = { session.cancelParameterChoice() }, + positionProvider = AtPointPositionProvider(IntOffset(anchor.x.roundToInt(), anchor.y.roundToInt())), + ) + } +} + +/** + * Places this node just below-right of [anchor], clamped fully inside the parent, while still measuring + * against the whole window. The placement every shell cursor overlay shares - a near-cursor notice and + * the relation-pick badge differ only in their gap, not in how they are pinned. + * + * @param Offset anchor The pointer position in shell-root pixels. + * @param Dp gap The offset from the pointer, clearing whatever is drawn at it. + * @return Modifier The positioning modifier. + */ +private fun Modifier.nearPointer(anchor: Offset, gap: Dp): Modifier = + layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + layout(constraints.maxWidth, constraints.maxHeight) { + val gapPx = gap.toPx() + val clampedX = (anchor.x + gapPx).roundToInt().coerceIn(0, (constraints.maxWidth - placeable.width).coerceAtLeast(0)) + val clampedY = (anchor.y + gapPx).roundToInt().coerceIn(0, (constraints.maxHeight - placeable.height).coerceAtLeast(0)) + placeable.place(clampedX, clampedY) + } + } + +/** + * The shell-level relation-pick overlay: while a Properties field's eyedropper is armed, this draws the + * eyedropper cursor at the pointer and a badge naming what a click would bind ("Drawable: Hair Front"). + * + * It lives ABOVE the area tree for the same reason the pie menu does - the cursor must be visible the + * instant the pick is armed, over panels and the outliner too, not only inside a viewport's clipped box. + * The resolving surfaces publish what is under the pointer ([RelationPickController.hover]); this only + * names it, so the badge reads identically whether the pointer is over the viewport or an outliner row. + * Installs no pointer input, so it never steals a gesture from the surfaces below. + * + * シェル直上のリレーション選択重畳。武装中はポインタ位置にスポイトカーソルと取得対象名のバッジを描く。 + * + * @param Offset? pointerPosition The last pointer position in shell-root pixels, or null before any event. + * @param Modifier modifier The layout modifier (the shell passes a window fill). + */ +@Composable +internal fun ShellRelationPickOverlay(pointerPosition: Offset?, modifier: Modifier = Modifier) { + val picker = LocalRelationPick.current + picker.request ?: return + val anchor = pointerPosition ?: return + + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + Canvas(modifier = Modifier.fillMaxSize()) { + drawCursor(LocalUmamoCursors.eyedropper, anchor) + } + // The kit's tooltip card, positioned at the cursor rather than hover-anchored to a control - the + // chrome stays owned by Tooltip.kt so this label can never drift from every other tooltip. + if (picker.hoveredTarget != null) { + TooltipCard( + text = relationPickLabel(picker.hoveredTarget), + modifier = Modifier.nearPointer(anchor, SHELL_POINTER_GAP), + ) + } + } +} + +/** + * The badge text for what a pick would bind: the entity's kind and name, or the "nothing under the pointer" + * prompt. Names come from the open document, falling back to the raw id for an unnamed entity. + * + * @param SelectionTarget? target The entity under the pointer, or null. + * @return String The localized badge label. + */ +@Composable +private fun relationPickLabel(target: SelectionTarget?): String { + val puppet = LocalPuppet.current + if (target == null || puppet == null) { + return "" + } + return when (target) { + is SelectionTarget.Drawable -> + stringResource( + Res.string.pick_hover_drawable, + puppet.drawables.firstOrNull { it.id == target.id }?.name?.ifBlank { target.id.raw } ?: target.id.raw, + ) + + is SelectionTarget.Part -> + stringResource( + Res.string.pick_hover_part, + puppet.parts.firstOrNull { it.id == target.id }?.name?.ifBlank { target.id.raw } ?: target.id.raw, + ) + + is SelectionTarget.Deformer -> + stringResource( + Res.string.pick_hover_deformer, + puppet.deformers.firstOrNull { it.id == target.id }?.name?.ifBlank { target.id.raw } ?: target.id.raw, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellKeyStroke.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellKeyStroke.kt new file mode 100644 index 0000000..0581be4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellKeyStroke.kt @@ -0,0 +1,54 @@ +package org.umamo.ui.workspace + +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isAltPressed +import androidx.compose.ui.input.key.isCtrlPressed +import androidx.compose.ui.input.key.isMetaPressed +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type + +/** + * One key press reduced to the five facts the shell's modal ladder and keymap dispatch actually read. + * + * Compose's KeyEvent is an expect class with no common constructor - it wraps the platform's native + * event - so a function taking one cannot be exercised from commonTest at all. Decoding to this value + * type at the root handler keeps the whole precedence a pure common function, which is what lets + * ModalKeyLadderTest state a modal condition and press a key without standing up a composition. + * + * [primaryModifier] folds Ctrl and Meta the way [org.umamo.ui.action.KeyChord] does, so the keymap + * fallthrough builds its chord straight from these fields rather than decoding the event a second time. + * + * @property Key key The key that moved. + * @property Boolean isDown True on key-down; the ladder's arms that test for a press read this. + * @property Boolean primaryModifier True when Ctrl (or Meta on macOS) is held. + * @property Boolean shift True when Shift is held. + * @property Boolean alt True when Alt / Option is held. + */ +internal data class ShellKeyStroke( + val key: Key, + val isDown: Boolean, + val primaryModifier: Boolean = false, + val shift: Boolean = false, + val alt: Boolean = false, +) + +/** + * Reduces a Compose key event to the [ShellKeyStroke] the shell routes on. + * + * Every accessor read here is common API on the expect class; only constructing a KeyEvent is + * platform-specific, which is why this adapter can live in commonMain while its result is what the + * tests drive. + * + * @return ShellKeyStroke The decoded stroke. + */ +internal fun KeyEvent.toShellKeyStroke(): ShellKeyStroke = + ShellKeyStroke( + key = key, + isDown = type == KeyEventType.KeyDown, + primaryModifier = isCtrlPressed || isMetaPressed, + shift = isShiftPressed, + alt = isAltPressed, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellModalState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellModalState.kt new file mode 100644 index 0000000..8ab7255 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellModalState.kt @@ -0,0 +1,50 @@ +package org.umamo.ui.workspace + +import org.umamo.edit.EditorSession +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.Keymap +import org.umamo.ui.kit.InlineEditController +import org.umamo.ui.kit.KeyCaptureController +import org.umamo.ui.kit.MenuBarController +import org.umamo.ui.model.SelectionHandle +import org.umamo.ui.workspace.rowdrag.RowDragCancelController + +/** + * Everything the shell's modal key ladder consults, in one aggregate. + * + * The ladder reads a dozen collaborators to decide who owns a key, and threading them as a dozen + * parameters is what kept it untested: a test for one arm had to name all twelve. Every field defaults + * to an inert instance, so a test states only the modal it exercises and the rest stay quiet - the + * shell, which holds live instances of all of them, passes each one explicitly. + * + * This is a plain holder, not a controller: it owns no state of its own and adds no behavior. + * + * @property ShellOverlayState overlays The modal chrome flags (confirm, alerts, palette, preferences, Help). + * @property MenuBarController menuBarController The menu-bar seam; an open menu claims Escape. + * @property InlineEditController inlineEditController The inline-editor seam; an open field claims the keyboard. + * @property KeyCaptureController keyCapture The key-capture seam; a control binding the next key press owns every key. + * @property EditorSession? editorSession The open document's session, or null with no document. + * @property SelectionHandle? selection The object-selection handle, or null with no document. + * @property AreaDragController dragController The area corner-drag state; an in-flight drag defers Escape to area.dragCancel. + * @property SplitterDragCancelController splitterDragCancel The divider-drag seam; an in-flight divider drag claims Escape. + * @property RowDragCancelController rowDragCancel The panel row-drag seam; an in-flight row drag claims Escape. + * @property RelationPickController relationPick The relation-pick seam; an armed eyedropper claims Escape. + * @property KeyformSheetViews keyformSheets The open keyform sheets; an armed marquee claims Escape. + * @property CommandRegistry commandRegistry The registry pie picks and the fallthrough dispatch into. + * @property Keymap keymap The active keymap for the fallthrough dispatch. + */ +internal class ShellModalState( + val overlays: ShellOverlayState = ShellOverlayState(), + val menuBarController: MenuBarController = MenuBarController(), + val inlineEditController: InlineEditController = InlineEditController(), + val keyCapture: KeyCaptureController = KeyCaptureController(), + val editorSession: EditorSession? = null, + val selection: SelectionHandle? = null, + val dragController: AreaDragController = AreaDragController(), + val splitterDragCancel: SplitterDragCancelController = SplitterDragCancelController(), + val rowDragCancel: RowDragCancelController = RowDragCancelController(), + val relationPick: RelationPickController = RelationPickController(), + val keyformSheets: KeyformSheetViews = KeyformSheetViews(), + val commandRegistry: CommandRegistry = CommandRegistry(), + val keymap: Keymap = Keymap(emptyMap()), +) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellOverlayState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellOverlayState.kt new file mode 100644 index 0000000..ff5d71f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellOverlayState.kt @@ -0,0 +1,240 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import org.jetbrains.compose.resources.StringResource +import org.umamo.interop.ExportReport +import org.umamo.ui.document.DocumentOpenFailure +import org.umamo.ui.model.AtlasRepackReport +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.dialog_cancel +import org.umamo.ui.resources.dialog_confirm +import org.umamo.ui.settings.QuickSetupState + +/** + * A confirmation's third choice beside Cancel and Confirm - "Don't Save" beside "Save". + * + * @property StringResource label The button's label. + * @property Function onSelect The action to run when picked. + */ +internal data class ConfirmAlternative( + val label: StringResource, + val onSelect: () -> Unit, +) + +/** + * A modal message with nothing to decide - a document that opened read-only, a save that failed - shown + * until acknowledged. + * + * @property StringResource message The message resource. + * @property List arguments The format arguments, in placeholder order: document data (file + * names, entry paths), never translated. + */ +internal data class AlertRequest( + val message: StringResource, + val arguments: List = emptyList(), +) + +/** + * A pending confirmation: the localized prompt to show, the buttons it names, and the action to run if the + * user confirms. The shell holds at most one of these (like its palette-visible flag) and renders a + * ConfirmDialog for it, so a destructive command (reset, import-overwrite, export-overwrite) sets one instead + * of acting immediately. + * + * @property StringResource message The localized prompt shown in the dialog. + * @property List arguments The prompt's format arguments, in placeholder order; empty for + * an argument-free prompt. Plain values (counts, file names) - + * document data is never translated. + * @property StringResource confirmLabel The confirm button's label, naming the action it takes. + * @property StringResource cancelLabel The cancel button's label. + * @property ConfirmAlternative? alternative A third choice, or null for a two-button dialog. + * @property Function onConfirm The action to run when confirmed. + */ +internal data class ConfirmRequest( + val message: StringResource, + val arguments: List = emptyList(), + val confirmLabel: StringResource = Res.string.dialog_confirm, + val cancelLabel: StringResource = Res.string.dialog_cancel, + val alternative: ConfirmAlternative? = null, + val onConfirm: () -> Unit, +) + +/** + * The shell's transient overlay flags in one place: which modal chrome (palette, preferences, Quick + * Setup, Help dialogs, confirm dialog, file-open alert, export report, repack refusal report) is + * currently up. The command handlers toggle these, the modal key ladder routes Escape/Enter by them, + * the focus-reclaim effect watches their aggregate, and the shell renders the matching overlay for each - + * one holder instead of eight loose vars, so the pieces that must agree read the same state. + * + * @param QuickSetupState quickSetup The Quick Setup modal's visibility, which the app holds for its whole + * life because this state is rebuilt with the shell on every document swap; a standalone shell has its own. + */ +internal class ShellOverlayState( + private val quickSetup: QuickSetupState = QuickSetupState(visible = false), +) { + /** The command palette's visible flag - toggled by palette.toggle. */ + var paletteVisible: Boolean by mutableStateOf(false) + + /** The preferences overlay's visible flag - toggled by the edit.preferences command. */ + var settingsVisible: Boolean by mutableStateOf(false) + + /** The Quick Setup modal's visible flag - open on a first run, toggled by the help.quickSetup command. */ + var quickSetupVisible: Boolean + get() = quickSetup.visible + set(value) { + quickSetup.visible = value + } + + /** The About dialog's visible flag - toggled by the help.about command. */ + var aboutVisible: Boolean by mutableStateOf(false) + + /** The Credits dialog's visible flag - toggled by the help.credits command. */ + var creditsVisible: Boolean by mutableStateOf(false) + + private val pendingConfirmState = mutableStateOf(null) + + /** + * A destructive command (reset, import-overwrite) sets this instead of acting; the rendered + * ConfirmDialog runs the action on confirm. At most one is pending at a time. + * + * Raising a request also decides whether Enter may confirm it yet - see [confirmArmedForEnter]. + */ + var pendingConfirm: ConfirmRequest? + get() = pendingConfirmState.value + set(value) { + if (value != null) { + confirmArmedForEnter = !enterHeld + } + pendingConfirmState.value = value + } + + /** + * Whether Enter is physically down, as the key ladder last saw it. Compose's key-down carries no + * repeat flag, so this is the one honest signal for "the Enter that raised a dialog is still held". + */ + private var enterHeld: Boolean = false + + /** + * Whether Enter may confirm the pending request. + * + * False while the Enter that raised the request is still held: the palette runs its command on Enter's + * key-down, so the request lands under a held key whose OS auto-repeat would otherwise reach the confirm + * arm and run a destructive action before the dialog is even seen. The release arms it. A request + * raised with Enter up - a menu row, a button - is armed at once, and the first Enter confirms it. + */ + var confirmArmedForEnter: Boolean = true + private set + + /** + * Records an Enter stroke the ladder saw, so a request raised under a held Enter waits for its release. + * + * @param Boolean isDown True for the key-down, false for the release. + */ + fun noteEnterStroke(isDown: Boolean) { + enterHeld = isDown + if (!isDown && pendingConfirm != null) { + confirmArmedForEnter = true + } + } + + /** + * Runs the pending confirmation's action - what its confirm button and Enter both do. + * + * The slot clears before the action runs, so an action that raises a confirmation of its own leaves that one + * pending instead of having it cleared out from under it. The key ladder and the rendered dialog both come + * through here, so the two cannot disagree about what confirming means. + */ + fun confirmPending() { + val request = pendingConfirm ?: return + pendingConfirm = null + request.onConfirm() + } + + /** + * Dismisses the pending confirmation without acting - what its cancel button, the scrim, and Escape do. + */ + fun cancelPending() { + pendingConfirm = null + } + + /** + * Runs the pending confirmation's third choice, when it has one, clearing the slot first as [confirmPending] + * does. + */ + fun choosePendingAlternative() { + val alternative = pendingConfirm?.alternative ?: return + pendingConfirm = null + alternative.onSelect() + } + + /** + * A message the app layer asks the shell to show modally - set by the document.alert command, cleared + * by its OK button, the scrim, Escape, or Enter. Null while none shows. + */ + var pendingAlert: AlertRequest? by mutableStateOf(null) + + /** + * The file-open failure alert's payload - set by the document.openFailed command (dispatched by + * the app's document layer), cleared by its OK button, the scrim, Escape, or Enter. Null while + * none shows. + */ + var openFailure: DocumentOpenFailure? by mutableStateOf(null) + + /** + * The export report alert's payload - set by the document.exportReport command when a CMO3 or MOC3 + * export finished with advisory notices (edits the target format could not carry, features stripped + * for an older runtime target, weld divergence), cleared like the open-failure alert. Null while + * none shows. Non-blocking: the export has already been written when this shows. + */ + var exportReport: ExportReport? by mutableStateOf(null) + + /** + * The repack refusal report's payload - set by the document.repackReport command when a repack + * aborted over tiles it could not carry, cleared like the open-failure alert. Null while none + * shows. Unlike the export report this one is about work that did NOT happen: nothing was + * applied when it shows. + */ + var repackReport: AtlasRepackReport? by mutableStateOf(null) + + /** + * The export-options dialog's payload - set by the document.exportOptions command when an + * export with options begins, cleared by Cancel, the scrim, Escape, or the Export button (which + * first runs the request's continuation). Null while none shows. + */ + var pendingExportOptions: ExportOptionsRequest? by mutableStateOf(null) + + /** + * True while an overlay that holds its own focus is open (the palette's search field, the + * preferences window's and Quick Setup's popups, the Help dialogs, the export-options dialog's + * fields). While one is up the shell must NOT steal focus; it reclaims when this flips false. + */ + val selfFocusedOverlayOpen: Boolean + get() = paletteVisible || settingsVisible || quickSetupVisible || aboutVisible || creditsVisible || pendingExportOptions != null + + /** + * Closes the topmost open self-focused overlay, if any - what Escape does to this family. + * + * The order is the overlays' stacking order. It lives here rather than as consecutive + * modal-ladder arms, so the flags and the precedence over them cannot drift apart. It only matters + * when two are somehow open at once; with one open, any order closes it. + */ + fun closeTopmostSelfFocused() { + when { + pendingExportOptions != null -> pendingExportOptions = null + quickSetupVisible -> quickSetupVisible = false + settingsVisible -> settingsVisible = false + aboutVisible -> aboutVisible = false + creditsVisible -> creditsVisible = false + paletteVisible -> paletteVisible = false + } + } + + /** + * True while a modal alert (confirm dialog, file-open failure, export report, repack refusal + * report) is up. These do NOT hold their own focus - the shell keeps root focus so their + * Escape/Enter route through the modal key ladder. + */ + val modalAlertOpen: Boolean + get() = pendingConfirm != null || openFailure != null || exportReport != null || repackReport != null +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellTextEntry.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellTextEntry.kt new file mode 100644 index 0000000..e8c1b88 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ShellTextEntry.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.workspace + +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputScope + +/** + * Whether a press that has finished dispatching should end text entry and hand the keyboard back to the + * shell root. + * + * @param Boolean textEntryActive Whether a text editor has parked its cancel hook. + * @param Boolean pressLandedOnTextEditor Whether the press landed on a text editor's own surface. + * @param Boolean selfFocusedOverlayOpen Whether an overlay that owns its own focus is open. + * @return Boolean True when the shell should take focus back. + */ +internal fun shouldReleaseTextEntry( + textEntryActive: Boolean, + pressLandedOnTextEditor: Boolean, + selfFocusedOverlayOpen: Boolean, +): Boolean = textEntryActive && !pressLandedOnTextEditor && !selfFocusedOverlayOpen + +/** + * Watches one node for the presses that end text entry, reporting each press twice: [beginPress] on the + * Initial pass, before any descendant has seen it, and [settlePress] on the Final pass, once every + * descendant has handled it. Installed on the shell root, whose two calls clear and then read the + * editor's press claim. Consumes nothing. + * + * @param Function beginPress Runs on each press's Initial pass, before any descendant sees it. + * @param Function settlePress Runs on the same press's Final pass, after every descendant has seen it. + */ +internal suspend fun PointerInputScope.observeTextEntryPresses( + beginPress: () -> Unit, + settlePress: () -> Unit, +) { + awaitPointerEventScope { + while (true) { + if (awaitPointerEvent(PointerEventPass.Initial).type != PointerEventType.Press) { + continue + } + beginPress() + // The same press again, now that it has reached whatever it landed on. + awaitPointerEvent(PointerEventPass.Final) + settlePress() + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SpaceKind.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SpaceKind.kt new file mode 100644 index 0000000..d578de9 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SpaceKind.kt @@ -0,0 +1,104 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +/** + * The closed inventory of editor space types an area can host. This is the Blender "editor type": + * any area can be switched to any of these via its header dropdown, so the set is agnostic, not tied + * to a fixed dock position. + * + * Each entry carries a stable string [key] used for serialization - we serialize by key, not by + * ordinal or enum name, so reordering or renaming an entry never corrupts a saved layout. + * + * エリアが表示できるエディタ種別の閉じた集合(Blender のエディタタイプ相当)。各エリアはヘッダの + * ドロップダウンで任意の種別へ切替可能。直列化は安定した key 文字列で行う。 + * + * @property String key The stable serialization token (never reorder-sensitive). + */ +@Serializable(with = SpaceKindSerializer::class) +enum class SpaceKind(val key: String) { + /** The 2D modelling viewport (the GL work surface: mesh + deformers). */ + Viewport2D("viewport2d"), + + /** The UV / texture-atlas editor. */ + UvEditor("uv"), + + /** + * The source-art linking table: each artwork file, its layers, the tiles bound to them, and the + * drawables over each tile - where art is added to a document, reloaded, relinked, and matched. + */ + Sources("sources"), + + /** The parts + deformer hierarchy (Blender's Outliner equivalent). */ + Outliner("outliner"), + + /** The parameter cockpit: sliders and the multi-key 2D pad. */ + Parameters("parameters"), + + /** + * The keyform sheet: per-(item, channel) tracks over the targeted parameter's range. + * + * Named for what it shows rather than "dope sheet", which is left free for the time-based animation + * editor - both will exist, and a serialized key cannot be renamed without resetting saved layouts. + */ + KeyformSheet("keyformsheet"), + + /** A tabbed mega-panel (Document / Object / Data) of the document and the selected item. */ + Properties("properties"), + + /** Settings for the active tool. */ + ToolDetails("tooldetails"), + + /** The undo-history stack: every step, the live one highlighted, click to jump. */ + History("history"), + + /** The diagnostic log console. */ + Logs("logs"), + ; + + companion object { + /** + * Resolves a serialized [key] back to its [SpaceKind], or null when unknown. + * + * @param String key The stored key token. + * @return SpaceKind? The matching kind, or null. + */ + fun fromKey(key: String): SpaceKind? = entries.firstOrNull { kind -> kind.key == key } + } +} + +/** + * Serializes [SpaceKind] as its stable [SpaceKind.key] string. An unknown key (a layout written by a + * newer build that has a space this build lacks) decodes to a neutral [SpaceKind.Outliner] rather + * than failing the whole layout - a forward-compatible, non-destructive fallback that also avoids + * spinning up a GL viewport for an unknown kind. + * + * SpaceKind を安定キー文字列として直列化する。未知のキーは中立な Outliner にフォールバックする。 + */ +object SpaceKindSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("org.umamo.ui.workspace.SpaceKind", PrimitiveKind.STRING) + + /** + * Writes the kind's stable key. + * + * @param Encoder encoder The output encoder. + * @param SpaceKind value The kind to write. + */ + override fun serialize(encoder: Encoder, value: SpaceKind) { + encoder.encodeString(value.key) + } + + /** + * Reads a key and resolves it, falling back to [SpaceKind.Outliner] for an unrecognised key. + * + * @param Decoder decoder The input decoder. + * @return SpaceKind The resolved kind. + */ + override fun deserialize(decoder: Decoder): SpaceKind = SpaceKind.fromKey(decoder.decodeString()) ?: SpaceKind.Outliner +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SpaceRegistry.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SpaceRegistry.kt new file mode 100644 index 0000000..f0d8e7a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SpaceRegistry.kt @@ -0,0 +1,160 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.staticCompositionLocalOf +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import org.jetbrains.compose.resources.StringResource +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.theme.UmamoIcon + +/** + * A space's view state that a saved document carries (docs/format/UMA.md §7.3): it writes itself as one member of + * its area's block and takes that member back when the document reopens. + * + * Nothing here marks a document dirty. The state rides on a real save and is otherwise left alone (UMA §7). + */ +interface PersistentSpaceState { + /** + * This state as its area block's member. Every member this state knows is named: its value when it deviates + * from the default, a JSON null when it does not - a merge alone could never take a deviation back out of the + * file (UMA §7.5). + * + * @return JsonObject The member's content. + */ + fun toJson(): JsonObject + + /** + * Takes the state a document was saved with. Tolerant by contract: a member of the wrong type, an unknown + * name, or an id that names nothing is skipped, never thrown over (UMA §7.1). + * + * @param JsonObject tree The member as the file held it. + */ + fun restore(tree: JsonObject) +} + +/** + * The per-area context handed to a space's content factory and its header slot. Carries the hosting + * area's stable id (which the 2D viewport needs to key its GL surface) and the per-space state bag - + * the header slot and the body render as sibling subtrees sharing only this scope, so [spaceState] is + * the one channel a space's header controls and its body can share state through (a CompositionLocal + * provided inside the body never reaches the header). + * + * @property String areaId The id of the leaf hosting this space. + * @property JsonObject? restored This area's block as the open document held it (UMA §7.3), or null. + */ +class AreaScope( + val areaId: String, + private val restored: JsonObject? = null, +) { + /** Per-space parked state, keyed by a space-chosen string. */ + private val spaceStates = mutableMapOf() + + /** + * Returns the state object parked under [stateKey], creating it via [factory] on first use. The + * instance lives as long as this scope, so it survives switching the space away and back. A key is + * the space's member name in its area block ("outliner", "keyformSheet"), which is why it carries no + * dot; a cross-space key collision is a programming error, hence the unchecked cast. + * + * A [PersistentSpaceState] takes the document's saved member the moment it is created, before any + * composable reads it, so a space never renders its defaults first and the restored state second. + * + * @param String stateKey The space-unique key naming the parked state. + * @param Function factory Creates the state on first request. + * @return StateT The one instance for this area. + */ + @Suppress("UNCHECKED_CAST") + fun spaceState(stateKey: String, factory: () -> StateT): StateT = + spaceStates.getOrPut(stateKey) { + factory().also { created -> + if (created is PersistentSpaceState) { + (restored?.get(stateKey) as? JsonObject)?.let(created::restore) + } + } + } as StateT + + /** + * This area's block for a save: one member per persistent state the area has shown, in the spec's order + * (UMA §7.5). A space the area never showed has no state here and so is not named, which leaves its member + * as the file had it. + * + * @return JsonObject The block's members. + */ + fun gather(): JsonObject = + buildJsonObject { + for (stateKey in spaceStates.keys.sortedWith(compareBy({ key -> AREA_BLOCK_MEMBER_ORDER.indexOf(key).takeIf { index -> index >= 0 } ?: Int.MAX_VALUE }, { key -> key }))) { + (spaceStates[stateKey] as? PersistentSpaceState)?.let { state -> put(stateKey, state.toJson()) } + } + } +} + +/** + * Describes one editor space: its [kind], the localized [title] shown in the dropdown menu, the [icon] + * shown in the area header and beside the title in the dropdown, and the [content] factory that renders + * it given its [AreaScope]. Keeping content a `@Composable (AreaScope) -> Unit` lambda lets the app + * override specific kinds (notably the GL viewport) without `:ui` depending on any platform code. + * + * [headerContent] is the optional space-specific header strip, rendered by the (otherwise + * space-agnostic) area header after the editor-type dropdown - the 2D viewport mounts its mode dropdown + * and select-mode buttons here, and the UV editor is the intended second consumer. Declared before + * [content] so the existing trailing-lambda construction sites stay valid. + * + * The slot declares ITEMS into an overflow-aware strip rather than emitting composables into a Row: a + * control that does not fit collapses into the strip's trailing dropdown instead of being squeezed to + * nothing. Because the builder is not itself composable, a CompositionLocal may only be read inside an + * item's body - see [org.umamo.ui.kit.OverflowRowScope]. + * + * @property SpaceKind kind The space type this describes. + * @property StringResource title The localized dropdown label. + * @property UmamoIcon icon The glyph shown in the area header and the dropdown rows. + * @property Function? headerContent Optional space-specific header controls, or null for none. + * @property Function content The composable that renders the space body. + */ +class SpaceDescriptor( + val kind: SpaceKind, + val title: StringResource, + val icon: UmamoIcon, + val headerContent: (OverflowRowScope.(AreaScope) -> Unit)? = null, + val content: @Composable (AreaScope) -> Unit, +) + +/** + * The resolver from [SpaceKind] to its [SpaceDescriptor] - the agnostic-area machinery. An area asks + * the registry for its current kind's descriptor to render content, and lists [all] descriptors to + * populate the editor-type dropdown. The app augments the base registry with [withOverrides] (e.g. to + * swap the placeholder viewport for the real GL one). + */ +class SpaceRegistry(private val descriptorsByKind: Map) { + /** + * The descriptor for [kind]. Throws if a kind is unregistered - every kind must have a descriptor + * (the base registry covers all of them), so a miss is a programming error, not a runtime branch. + * + * @param SpaceKind kind The kind to resolve. + * @return SpaceDescriptor The descriptor for that kind. + */ + fun descriptor(kind: SpaceKind): SpaceDescriptor = + descriptorsByKind[kind] ?: error("no SpaceDescriptor registered for $kind") + + /** Every descriptor, in SpaceKind declaration order - the source for the editor-type dropdown. */ + val all: List get() = SpaceKind.entries.mapNotNull { kind -> descriptorsByKind[kind] } + + /** + * Returns a new registry with [extra] descriptors layered over this one (same-kind entries win), + * so the app can replace specific spaces without rebuilding the whole map. + * + * @param Map extra The overriding descriptors, keyed by kind. + * @return SpaceRegistry The merged registry. + */ + fun withOverrides(extra: Map): SpaceRegistry = SpaceRegistry(descriptorsByKind + extra) +} + +/** + * The active [SpaceRegistry] for the composition. `static` - the registry is stable for the shell's + * lifetime; areas read `LocalSpaceRegistry.current` to render and to build their dropdown. + * + * コンポジションで有効な SpaceRegistry。 + */ +val LocalSpaceRegistry = + staticCompositionLocalOf { + error("LocalSpaceRegistry not provided — wrap the shell in a SpaceRegistry provider") + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Splitter.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Splitter.kt new file mode 100644 index 0000000..9d46181 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Splitter.kt @@ -0,0 +1,271 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.DraggableState +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.draggable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.UmamoCursor +import org.umamo.ui.theme.umamoPointerIcon +import kotlin.math.max +import kotlin.math.min + +/** The draggable thickness of a splitter bar. */ +internal val SPLITTER_THICKNESS = 4.dp + +/** The minimum on-axis size either child of a split may shrink to under a drag. */ +internal val MIN_AREA_DP = 48.dp + +/** + * The cursor art for a splitter of the given orientation - the east-west arrows for a Horizontal split + * (children side by side, dragged left/right) and the north-south arrows for a Vertical split. + * + * @param SplitOrientation orientation The split's orientation. + * @return UmamoCursor The editor's own arrows for that drag axis. + */ +private fun splitterCursor(orientation: SplitOrientation): UmamoCursor = + when (orientation) { + SplitOrientation.Horizontal -> LocalUmamoCursors.ewScroll + SplitOrientation.Vertical -> LocalUmamoCursors.nsScroll + } + +/** + * Which end of a subtree touches the divider being dragged: the divider sits after a Trailing-edge + * subtree (the dragged split's first child) and before a Leading-edge one (its second child). + */ +internal enum class SpineEdge { + Trailing, + Leading, +} + +/** + * Rewrites a split's subtree after a pointer drag on its own divider so that ONLY the two panels + * adjacent to the divider resize - every other panel keeps its pixel extent. A plain drag would just + * move this node's ratio, which rescales an entire child subtree as a unit (dragging the divider next + * to a three-column group visibly moves the far column); instead the drag delta telescopes down each + * child's divider-adjacent spine of same-orientation splits, counter-adjusting every ratio along it + * (see resizeEdgePanel). Pure (no Compose) so the pixels↔ratio math and the clamping are unit-tested + * directly - this is the fiddliest bit of the layout math. + * + * The drag is clamped BEFORE rewriting (boundaryDragBounds) so no adjacent panel shrinks below + * [minPx] and no stored ratio leaves the render clamp band [MIN_RATIO, 1 - MIN_RATIO] - a stored + * ratio outside the band would be silently re-clamped at render time and break the pixel invariance. + * A non-positive [axisPx] (first frame, not yet measured), an empty clamp interval (degenerate + * geometry), or a fully clamped-away drag returns the node unchanged. + * + * 仕切りドラッグ後の部分木を、仕切りに隣接する 2 パネルだけが伸縮するよう書き換える純粋関数。 + * 差分は同方向スプリットの背骨に沿って各比を補正しながら隣接パネルまで伝わる。 + * + * @param SplitNode node The split whose divider was dragged. + * @param Float dragPx The drag delta along the split axis, in pixels (positive grows the first child). + * @param Float axisPx The node's measured length along the split axis, in pixels. + * @param Float minPx The minimum size the divider-adjacent panels may shrink to, in pixels. + * @param Float splitterPx The divider bar's own thickness, in pixels (a fixed sibling of the two + * weighted children, so each split distributes axisPx minus splitterPx). + * @return SplitNode The rewritten split, or the same instance when the drag is a no-op. + */ +fun dragSplitBoundary(node: SplitNode, dragPx: Float, axisPx: Float, minPx: Float, splitterPx: Float): SplitNode { + val usablePx = axisPx - splitterPx + if (axisPx <= 0f || usablePx <= 0f) { + return node + } + val dragBounds = boundaryDragBounds(node, axisPx, minPx, splitterPx) + if (dragBounds.isEmpty()) { + return node + } + val clampedDragPx = dragPx.coerceIn(dragBounds.start, dragBounds.endInclusive) + if (clampedDragPx == 0f) { + return node + } + val clampedRatio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + val firstExtentPx = clampedRatio * usablePx + val secondExtentPx = usablePx - firstExtentPx + return node.copy( + ratio = (firstExtentPx + clampedDragPx) / usablePx, + first = resizeEdgePanel(node.first, node.orientation, firstExtentPx, clampedDragPx, splitterPx, SpineEdge.Trailing), + second = resizeEdgePanel(node.second, node.orientation, secondExtentPx, -clampedDragPx, splitterPx, SpineEdge.Leading), + ) +} + +/** + * The pixel extent of the divider-adjacent terminal panel inside [node]. Walks the [edge] spine of + * same-orientation splits (Trailing follows second children, Leading follows first children); a leaf + * or a cross-orientation split terminates the walk, because a cross-axis subtree resizes as one unit + * along the drag axis (its children fill the drag axis) and so absorbs the delta exactly like a leaf. + * + * @param AreaNode node The subtree on one side of the dragged divider. + * @param SplitOrientation orientation The dragged split's orientation (the drag axis). + * @param Float axisPx The subtree's current extent along the drag axis, in pixels. + * @param Float splitterPx The divider bar thickness, in pixels. + * @param SpineEdge edge Which end of the subtree touches the dragged divider. + * @return Float The adjacent terminal panel's extent along the drag axis, in pixels. + */ +internal fun edgePanelSizePx(node: AreaNode, orientation: SplitOrientation, axisPx: Float, splitterPx: Float, edge: SpineEdge): Float { + if (node !is SplitNode || node.orientation != orientation) { + return axisPx + } + val clampedRatio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + val usablePx = axisPx - splitterPx + return when (edge) { + SpineEdge.Trailing -> edgePanelSizePx(node.second, orientation, (1f - clampedRatio) * usablePx, splitterPx, edge) + SpineEdge.Leading -> edgePanelSizePx(node.first, orientation, clampedRatio * usablePx, splitterPx, edge) + } +} + +/** + * The allowed drag interval for [node]'s divider: the intersection of the adjacent terminal panels' + * [minPx] bounds with, for the node itself and every spine split the compensation will rewrite, the + * bound keeping its new ratio inside the render clamp band [MIN_RATIO, 1 - MIN_RATIO]. Only these + * nodes' ratios change, so only they constrain the drag; interior panels are pixel-invariant by + * construction. May be empty when the geometry is degenerate (extents already below the minimums). + * + * @param SplitNode node The split whose divider is being dragged. + * @param Float axisPx The node's measured length along the split axis, in pixels. + * @param Float minPx The minimum size the divider-adjacent panels may shrink to, in pixels. + * @param Float splitterPx The divider bar thickness, in pixels. + * @return ClosedFloatingPointRange The inclusive drag bounds, in pixels. + */ +internal fun boundaryDragBounds(node: SplitNode, axisPx: Float, minPx: Float, splitterPx: Float): ClosedFloatingPointRange { + val usablePx = axisPx - splitterPx + val clampedRatio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + val firstExtentPx = clampedRatio * usablePx + val secondExtentPx = usablePx - firstExtentPx + // The dragged node's own new ratio (firstExtentPx + drag) / usablePx must stay in the band. + var lowerBoundPx = MIN_RATIO * usablePx - firstExtentPx + var upperBoundPx = (1f - MIN_RATIO) * usablePx - firstExtentPx + // The divider-adjacent terminal panels must keep at least minPx. + lowerBoundPx = max(lowerBoundPx, minPx - edgePanelSizePx(node.first, node.orientation, firstExtentPx, splitterPx, SpineEdge.Trailing)) + upperBoundPx = min(upperBoundPx, edgePanelSizePx(node.second, node.orientation, secondExtentPx, splitterPx, SpineEdge.Leading) - minPx) + // First-side spine: each node's extent grows by the drag, its new ratio is s*u / (u + drag). + var spineNode: AreaNode = node.first + var spineExtentPx = firstExtentPx + while (spineNode is SplitNode && spineNode.orientation == node.orientation) { + val spineUsablePx = spineExtentPx - splitterPx + val spineRatio = spineNode.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + lowerBoundPx = max(lowerBoundPx, spineRatio * spineUsablePx / (1f - MIN_RATIO) - spineUsablePx) + upperBoundPx = min(upperBoundPx, spineRatio * spineUsablePx / MIN_RATIO - spineUsablePx) + spineExtentPx = (1f - spineRatio) * spineUsablePx + spineNode = spineNode.second + } + // Second-side spine: each node's extent shrinks by the drag, its new ratio is + // (s*u - drag) / (u - drag). + spineNode = node.second + spineExtentPx = secondExtentPx + while (spineNode is SplitNode && spineNode.orientation == node.orientation) { + val spineUsablePx = spineExtentPx - splitterPx + val spineRatio = spineNode.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + lowerBoundPx = max(lowerBoundPx, spineUsablePx * (spineRatio - (1f - MIN_RATIO)) / MIN_RATIO) + upperBoundPx = min(upperBoundPx, spineUsablePx * (spineRatio - MIN_RATIO) / (1f - MIN_RATIO)) + spineExtentPx = spineRatio * spineUsablePx + spineNode = spineNode.first + } + return lowerBoundPx..upperBoundPx +} + +/** + * Rewrites the ratios along [node]'s [edge] spine so that only the divider-adjacent terminal panel + * absorbs [deltaPx] while every other panel in the subtree keeps its pixel extent. At each spine + * split the far child's extent is held invariant - new ratio times new usable equals old extent + * exactly - so the delta telescopes down to the terminal. A leaf or a cross-orientation split ends + * the recursion unchanged (it absorbs the delta as a unit). + * + * @param AreaNode node The subtree on one side of the dragged divider. + * @param SplitOrientation orientation The dragged split's orientation (the drag axis). + * @param Float axisPx The subtree's current extent along the drag axis, in pixels. + * @param Float deltaPx This subtree's own extent change, in pixels (the clamped drag, sign-adjusted + * by the caller: positive on the growing side, negative on the shrinking side). + * @param Float splitterPx The divider bar thickness, in pixels. + * @param SpineEdge edge Which end of the subtree touches the dragged divider. + * @return AreaNode The rewritten subtree, or the same instance when nothing inside changes. + */ +private fun resizeEdgePanel(node: AreaNode, orientation: SplitOrientation, axisPx: Float, deltaPx: Float, splitterPx: Float, edge: SpineEdge): AreaNode { + if (node !is SplitNode || node.orientation != orientation) { + return node + } + val usablePx = axisPx - splitterPx + val newUsablePx = usablePx + deltaPx + val clampedRatio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + val firstExtentPx = clampedRatio * usablePx + return when (edge) { + SpineEdge.Trailing -> + node.copy( + ratio = firstExtentPx / newUsablePx, + second = resizeEdgePanel(node.second, orientation, usablePx - firstExtentPx, deltaPx, splitterPx, edge), + ) + SpineEdge.Leading -> + node.copy( + ratio = (firstExtentPx + deltaPx) / newUsablePx, + first = resizeEdgePanel(node.first, orientation, firstExtentPx, deltaPx, splitterPx, edge), + ) + } +} + +/** + * The draggable divider between a split's two children. Dragging it reports the pixel delta along the + * split axis via [onDragByPx], bracketed by [onDragStarted] / [onDragStopped]; the parent + * (SplitContainer) accumulates the deltas in a [SplitterDragSession] and rewrites its subtree with + * [dragSplitBoundary]. Orientation picks both the bar's long axis and the drag axis: a Horizontal + * split (children side by side) gets a vertical bar dragged horizontally; a Vertical split gets a + * horizontal bar dragged vertically. + * + * All three callbacks are wrapped in rememberUpdatedState so the pointer path always invokes the + * latest composition's closures even though the DraggableState itself is remembered once. Per-delta + * staleness of the captured node is neutralized by the caller's drag session, which rewrites from a + * drag-start snapshot rather than the composed node. + * + * @param SplitOrientation orientation The parent split's orientation. + * @param Function onDragByPx Receives the drag delta in pixels along the split axis. + * @param Modifier modifier The layout modifier. + * @param Function onDragStarted Called when a drag gesture begins, before the first delta. + * @param Function onDragStopped Called when the drag gesture ends or is cancelled. + */ +@Composable +fun Splitter( + orientation: SplitOrientation, + onDragByPx: (Float) -> Unit, + modifier: Modifier = Modifier, + onDragStarted: () -> Unit = {}, + onDragStopped: () -> Unit = {}, +) { + val latestOnDrag by rememberUpdatedState(onDragByPx) + val latestOnDragStarted by rememberUpdatedState(onDragStarted) + val latestOnDragStopped by rememberUpdatedState(onDragStopped) + val dragState = remember { DraggableState { deltaPx -> latestOnDrag(deltaPx) } } + val colors = LocalUmamoColors.current + val bar = + when (orientation) { + SplitOrientation.Horizontal -> Modifier.width(SPLITTER_THICKNESS).fillMaxHeight() + SplitOrientation.Vertical -> Modifier.height(SPLITTER_THICKNESS).fillMaxWidth() + } + val dragOrientation = + when (orientation) { + SplitOrientation.Horizontal -> Orientation.Horizontal + SplitOrientation.Vertical -> Orientation.Vertical + } + Box( + modifier = + modifier + .then(bar) + .pointerHoverIcon(umamoPointerIcon(splitterCursor(orientation))) + .draggable( + state = dragState, + orientation = dragOrientation, + onDragStarted = { latestOnDragStarted() }, + onDragStopped = { latestOnDragStopped() }, + ) + .background(colors.divider), + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SplitterDragCancel.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SplitterDragCancel.kt new file mode 100644 index 0000000..d27f7f3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SplitterDragCancel.kt @@ -0,0 +1,34 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * A coordination seam between an in-flight divider (splitter) drag and the editor shell's Escape + * precedence, mirroring [org.umamo.ui.workspace.rowdrag.RowDragCancelController]. + * + * A divider drag keeps its [SplitterDragSession] in the dragged SplitContainer's own remembered state, + * which the shell cannot see - unlike an area CORNER drag, whose state lives in the shell-level + * [AreaDragController] and which `area.dragCancel` has always been able to abort. Without this seam + * Escape mid-drag fell past every arm of the modal ladder to the bottom, which in Object mode CLEARED + * THE SELECTION while the user was merely resizing a panel. + * + * Nested splits mean many SplitContainers may be composed at once, but one pointer means at most one + * drag in flight, so a single shared slot serves them all. Unlike the row-drag seam the owner clears + * it by identity, because a sibling container recomposing must not blank the dragging one's callback. + * Holds null whenever no divider drag is in flight. + * + * @property Function cancel Cancels the in-flight divider drag, or null when none is in flight. + */ +class SplitterDragCancelController { + var cancel: (() -> Unit)? by mutableStateOf(null) +} + +/** + * Supplies the [SplitterDragCancelController] the shell shares with the area tree beneath it. Defaults + * to a standalone instance so an area tree hosted without the shell still composes (its divider drags + * simply cannot be cancelled from the keyboard). + */ +val LocalSplitterDragCancel = staticCompositionLocalOf { SplitterDragCancelController() } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SplitterDragSession.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SplitterDragSession.kt new file mode 100644 index 0000000..c0f722b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/SplitterDragSession.kt @@ -0,0 +1,100 @@ +package org.umamo.ui.workspace + +/** + * Accumulates one splitter drag against a snapshot of the dragged split taken when the drag began. + * Every delta rewrites from that snapshot with the RUNNING TOTAL of drag pixels, never from the + * currently composed node: pointer deltas can arrive faster than recomposition commits, and a + * per-delta rewrite of the composed node would apply each of them to the same stale tree, silently + * discarding all but the last delta per frame (the divider then crawls behind the pointer on a slow + * machine until the pointer walks off the bar). Rewriting snapshot + total also makes the clamp + * exact: dragging past the minimum and back retraces to the starting extents, which incremental + * application cannot do once a delta has been clamped away. + * + * The geometry inputs (axis length, minimum panel size, splitter thickness) are frozen at drag + * start on purpose: only an OS-driven window resize can change them mid-hold, and the next drag + * re-measures. + * + * @property SplitNode startNode The dragged split as it was when the drag began. + * @property Float axisPx The split's measured length along the drag axis, in pixels. + * @property Float minPx The minimum size the divider-adjacent panels may shrink to, in pixels. + * @property Float splitterPx The divider bar's own thickness, in pixels. + */ +internal class SplitterDragSession( + private val startNode: SplitNode, + private val axisPx: Float, + private val minPx: Float, + private val splitterPx: Float, +) { + private var totalDragPx: Float = 0f + + /** + * True once Escape has abandoned this drag. The pointer is very likely still held at that moment, + * so the session stays in place and inert rather than being discarded: clearing it would let the + * next delta rebase a fresh session on the live node and silently resume the drag the user just + * cancelled. + */ + var isCancelled: Boolean = false + private set + + // Every node this session has published, oldest first. Recomposition can lag several publishes + // behind the pointer, so the composed node handed back to ownsNode may legitimately be ANY + // instance this session ever produced, not just the latest. + private val publishedNodes = ArrayList() + + /** + * Folds one drag delta into the running total and rewrites the snapshot with it. The returned + * node is recorded so [ownsNode] can later recognize it as this session's own publish. + * + * @param Float deltaPx The pointer delta along the split axis, in pixels. + * @return SplitNode The snapshot rewritten by the accumulated drag. + */ + fun accumulate(deltaPx: Float): SplitNode { + totalDragPx += deltaPx + val rewritten = dragSplitBoundary(startNode, totalDragPx, axisPx, minPx, splitterPx) + publishedNodes.add(rewritten) + return rewritten + } + + /** + * Abandons the drag and returns the split as it stood when the drag began, for the caller to + * publish - Escape's undo of an in-flight divider drag. + * + * Rewinding to the snapshot is exact rather than approximate: [accumulate] always rewrites from + * that same snapshot, so no incremental state has to be unwound. The session marks itself + * [isCancelled] and stays alive so the deltas still arriving from the held pointer are ignored. + * + * @return SplitNode The drag-start snapshot to restore. + */ + fun cancel(): SplitNode { + isCancelled = true + totalDragPx = 0f + // The restored snapshot is a publish like any other, so ownsNode keeps recognizing this split + // as ours while the pointer is still down. + publishedNodes.add(startNode) + return startNode + } + + /** + * Whether [composedNode] is this session's own work: the drag-start snapshot or any node this + * session has published. A false answer means something else rewrote the tree mid-drag (a + * keyboard structural edit) and the caller must rebase a fresh session on the live node. + * Compares by identity - the publishes are the exact instances handed to onNodeChange. On a + * match, every older publish is pruned (composition has moved past them; they cannot reappear). + * + * @param AreaNode composedNode The node the composition currently holds for this split. + * @return Boolean True when the composed node originated from this session. + */ + fun ownsNode(composedNode: AreaNode): Boolean { + if (composedNode === startNode) { + return true + } + val matchIndex = publishedNodes.indexOfFirst { published -> published === composedNode } + if (matchIndex < 0) { + return false + } + if (matchIndex > 0) { + publishedNodes.subList(0, matchIndex).clear() + } + return true + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/StatusBar.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/StatusBar.kt new file mode 100644 index 0000000..6df314b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/StatusBar.kt @@ -0,0 +1,328 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.delay +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.MeshTopology +import org.umamo.edit.NoticePlacement +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.kit.Text +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.model.noticeText +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography + +// The strip reads better a touch shorter than the area header (HEADER_HEIGHT = 28.dp in AreaHeader); +// it is fixed-height chrome, so the area tree above takes the remaining height. +private val STATUS_BAR_HEIGHT = 24.dp + +// Separates the inline entries within a zone; a middot-style bar keeps the run-on counts grouped. +private const val STAT_SEPARATOR = " | " + +/** + * The bottom status strip: thin, always-present window chrome below the area tree, laid out as four + * conceptual zones left to right - the current context's input binds, a blank flexible middle, the + * selected item, and the model stats. Lives in commonMain so the strip is shared chrome on desktop + * and Android. + * + * @param Modifier modifier The layout modifier (the shell passes fillMaxWidth). + */ +@Composable +fun StatusBar(modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + Column(modifier = modifier) { + // A hairline above the strip separates it from the area tree (and the offscreen GL viewport). + Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider)) + Row( + modifier = + Modifier + .fillMaxWidth() + .height(STATUS_BAR_HEIGHT) + .background(colors.headerBackground) + .padding(horizontal = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + // Weighted, and emitted even when it holds nothing: a weighted child is measured after the + // selected item and the stats, so a long hint run is cut before it can squeeze them, and a slot + // that is always there keeps the notice beside it from moving as the hints change. + Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.CenterStart) { + ContextBindsZone() + } + // The flexible middle doubles as the transient-notice slot: a blank gap normally, a brief message + // when the session emits one (e.g. an Object-mode transform blocked by a part / deformer selection). + Box(modifier = Modifier.weight(1f).padding(horizontal = 12.dp), contentAlignment = Alignment.Center) { + StatusNotice() + } + SelectedItemZone() + Spacer(modifier = Modifier.width(16.dp)) + ModelStats() + } + } +} + +/** How long (ms) a transient status notice stays visible before it auto-dismisses. */ +private const val NOTICE_VISIBLE_MS = 4000L + +/** + * The transient-notice slot: shows the session's most recent status-bar-placed notice for a few seconds, + * then clears itself. A notice is momentary feedback explaining why an action did nothing, so it lives + * outside the undo history and the change bus. Notices placed [NoticePlacement.NearCursor] are the + * viewport HUD overlay's to draw, not this slot's. Renders nothing when no notice is active or no + * document is open. + */ +@Composable +private fun StatusNotice() { + val session = LocalEditorSession.current ?: return + val notice by session.notice.collectAsState() + val current = notice ?: return + if (current.placement != NoticePlacement.StatusBar) { + return + } + // Auto-dismiss this notice after the visible window; keyed on the serial so a repeat of the same text + // restarts the timer, and clearNotice only clears if a newer notice has not replaced it meanwhile. + LaunchedEffect(current.serial) { + delay(NOTICE_VISIBLE_MS) + session.clearNotice(current.serial) + } + Text( + text = noticeText(current.messageKey, current.arguments), + style = LocalUmamoTypography.current.labelMedium, + color = LocalUmamoColors.current.text, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) +} + +/** + * The context-binds zone: the shortcuts worth suggesting for the space under the pointer, derived from + * what each command declares about itself (its spaces, its availability, its short hint label) rather + * than listed here - see [statusHintsFor]. Moving the pointer from a viewport to a keyform sheet + * changes the suggestions, and a command that gains a hint appears with no edit to this zone. + * + * An active modal transform operator - from any of the three families, since G / S / R latch the mesh, + * the object, or the UV operator depending on the mode and the surface - overrides the list with its + * confirm / cancel pair. Those two are literal strings because the inputs live in the overlay's own + * pointer loop and the shell's hardcoded modal branches, not in the keymap - there is nothing rebindable + * to resolve, and no command to derive them from. + */ +@Composable +private fun ContextBindsZone() { + val keymap = LocalKeymap.current + val commands = LocalCommands.current + val hoveredKind = LocalHoveredSurfaceTracker.current?.observedKind + val session = LocalEditorSession.current + val editorMode = session?.mode?.collectAsState()?.value + // The three latches are separate flows and at most one is live; the session's own activeOperator is + // an instantaneous read, so composition collects each (as the viewport HUD does). + val meshOperator = session?.activeMeshOperator?.collectAsState()?.value + val objectOperator = session?.activeObjectOperator?.collectAsState()?.value + val uvOperator = session?.activeUvOperator?.collectAsState()?.value + val operatorActive = meshOperator != null || objectOperator != null || uvOperator != null + // The table is a plain map, so the revision is what re-reads it: a document swap lands its commands + // from effects AFTER the composition the swap caused, and only the bump brings this zone back. + val registered = remember(commands.revision) { commands.all() } + // Availability is a live query the snapshot system cannot see, so these keys ARE the contract: a + // hinted command's availability and its hint's suggestedWhen may depend on the registered table (and + // so the document), the mode, and nothing else - which is what CommandHint asks of them. + val hints = remember(registered, keymap, hoveredKind, editorMode) { statusHintsFor(registered, keymap, hoveredKind) } + val entries = + if (operatorActive) { + listOf(stringResource(Res.string.status_bind_confirm), stringResource(Res.string.status_bind_cancel)) + } else { + hints.map { hint -> + val chordRun = hint.chords.joinToString(separator = "/") { chord -> formatAccelerator(chord) } + "$chordRun ${stringResource(hint.label)}" + } + } + if (entries.isEmpty()) { + return + } + Text( + text = entries.joinToString(separator = STAT_SEPARATOR), + style = LocalUmamoTypography.current.labelMedium, + color = LocalUmamoColors.current.textMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) +} + +/** + * The selected-item zone: in Object mode the active target's display name (or a "%d selected" count + * for a multi-selection); in Edit mode the selected element count over the edited drawable's domain + * total ("3/120 vertices"). Renders nothing when nothing is selected or no document is open. + * + * 選択項目区画。オブジェクトモードではアクティブ対象の表示名(複数選択時は件数)、編集モードでは + * 選択要素数/総数を表示する。 + */ +@Composable +private fun SelectedItemZone() { + val puppet = LocalPuppet.current + val session = LocalEditorSession.current + if (puppet == null || session == null) { + return + } + val editorMode by session.mode.collectAsState() + val text: String? + if (editorMode == EditorMode.Edit) { + // The denominators sum over EVERY session mesh (multi-mesh edit), so "3/240 vertices" reads + // against everything the session can select. + val meshSelection by session.meshSelection.collectAsState() + val drawableById = remember(puppet) { puppet.drawables.associateBy { drawable -> drawable.id } } + val sessionMeshes = + remember(puppet, meshSelection.drawableIds) { + meshSelection.drawableIds.mapNotNull { drawableId -> drawableById[drawableId]?.mesh } + } + text = + if (sessionMeshes.isEmpty() || meshSelection.isEmpty) { + null + } else { + when (meshSelection.selectMode) { + MeshSelectMode.Vertex -> + stringResource(Res.string.status_mesh_vertices, meshSelection.size, sessionMeshes.sumOf { mesh -> mesh.vertexCount }) + MeshSelectMode.Edge -> { + val totalEdges = remember(sessionMeshes) { sessionMeshes.sumOf { mesh -> MeshTopology.uniqueEdges(mesh.indices).size } } + stringResource(Res.string.status_mesh_edges, meshSelection.size, totalEdges) + } + MeshSelectMode.Face -> + stringResource(Res.string.status_mesh_faces, meshSelection.size, sessionMeshes.sumOf { mesh -> mesh.triangleCount }) + } + } + } else { + val selection = LocalSelection.current?.selection + text = + if (selection == null || selection.isEmpty) { + null + } else if (selection.size > 1) { + stringResource(Res.string.status_multi_selected, selection.size) + } else { + val target = selection.active ?: selection.targets.first() + when (target) { + is SelectionTarget.Part -> remember(puppet) { puppet.parts.associateBy { part -> part.id } }[target.id]?.name + is SelectionTarget.Drawable -> remember(puppet) { puppet.drawables.associateBy { drawable -> drawable.id } }[target.id]?.name + is SelectionTarget.Deformer -> remember(puppet) { puppet.deformers.associateBy { deformer -> deformer.id } }[target.id]?.name + } + } + } + if (text == null) { + return + } + Text( + text = text, + style = LocalUmamoTypography.current.labelMedium, + color = LocalUmamoColors.current.textMuted, + ) +} + +/** + * The model-stats zone: an inline summary of the open model's element counts (parts, drawables, + * parameters, deformers, glues) plus its mesh vertex / triangle totals. While a selection exists the + * mesh numbers turn selection-relative ("Verts: 12/3400") - in Object mode over the selected + * drawables (a selected part counts its nested art), in Edit mode over the selected elements' covered + * vertices and fully-covered faces. Reads the open document's [LocalPuppet] and renders nothing when + * no model is open. + * + * モデル統計区画。各種件数と頂点・三角形の合計を表示し、選択があるあいだは選択分/合計の形になる。 + * 未読込時は何も描かない。 + */ +@Composable +private fun ModelStats() { + val puppet = LocalPuppet.current ?: return + val session = LocalEditorSession.current + var selectedTotals: MeshTotals? = null + // The session meshes Edit mode scopes to (paired with their ids for per-mesh element lookups), or + // null in Object mode / no session; drives the denominator below. + var editedMeshes: List>? = null + if (session != null) { + val editorMode by session.mode.collectAsState() + if (editorMode == EditorMode.Edit) { + val meshSelection by session.meshSelection.collectAsState() + val drawableById = remember(puppet) { puppet.drawables.associateBy { drawable -> drawable.id } } + val sessionMeshes = + remember(puppet, meshSelection.drawableIds) { + meshSelection.drawableIds.mapNotNull { drawableId -> drawableById[drawableId]?.mesh?.let { mesh -> drawableId to mesh } } + } + editedMeshes = sessionMeshes.takeIf { pairs -> pairs.isNotEmpty() } + if (sessionMeshes.isNotEmpty() && !meshSelection.isEmpty) { + selectedTotals = + remember(meshSelection, sessionMeshes) { + var coveredVertexTotal = 0 + var coveredFaceTotal = 0 + for ((drawableId, mesh) in sessionMeshes) { + val coveredVertexIndices = MeshTopology.coveredVertexIndices(meshSelection.elementsOf(drawableId), mesh.indices) + coveredVertexTotal += coveredVertexIndices.size + coveredFaceTotal += MeshTopology.facesWithAllVerticesSelected(mesh.indices, coveredVertexIndices).size + } + MeshTotals(vertexCount = coveredVertexTotal, triangleCount = coveredFaceTotal) + } + } + } else { + val selection = LocalSelection.current?.selection + if (selection != null && !selection.isEmpty) { + selectedTotals = remember(puppet, selection) { selectedMeshTotals(puppet, selection) } + } + } + } + // The stats denominator: in Edit mode the session meshes' own totals (so "3/240" reads against the + // meshes being edited, matching the selected-item zone), else the whole model's totals. A val for + // the smart-cast to survive into the remember lambda. + val editedMeshesForTotals = editedMeshes + val totals = + if (editedMeshesForTotals != null) { + remember(editedMeshesForTotals) { + MeshTotals( + vertexCount = editedMeshesForTotals.sumOf { (_, mesh) -> mesh.vertexCount }, + triangleCount = editedMeshesForTotals.sumOf { (_, mesh) -> mesh.triangleCount }, + ) + } + } else { + remember(puppet) { meshTotals(puppet) } + } + val vertsEntry = + selectedTotals?.let { selected -> stringResource(Res.string.status_verts_selected, selected.vertexCount, totals.vertexCount) } + ?: stringResource(Res.string.status_verts_selected, "0", totals.vertexCount) + val trisEntry = + selectedTotals?.let { selected -> stringResource(Res.string.status_tris_selected, selected.triangleCount, totals.triangleCount) } + ?: stringResource(Res.string.status_tris_selected, "0", totals.triangleCount) + val line = + listOf( + stringResource(Res.string.status_parts, puppet.parts.size), + stringResource(Res.string.status_drawables, puppet.drawables.size), + stringResource(Res.string.status_parameters, puppet.parameters.size), + stringResource(Res.string.status_deformers, puppet.deformers.size), + stringResource(Res.string.status_glues, puppet.glues.size), + vertsEntry, + trisEntry, + ).joinToString(separator = STAT_SEPARATOR) + Text( + text = line, + style = LocalUmamoTypography.current.labelMedium, + color = LocalUmamoColors.current.textMuted, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/StatusHints.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/StatusHints.kt new file mode 100644 index 0000000..7acf10b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/StatusHints.kt @@ -0,0 +1,81 @@ +package org.umamo.ui.workspace + +import org.jetbrains.compose.resources.StringResource +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.action.KeyChord +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.isOfferedIn + +/** + * The most suggestions the status bar shows at once. The strip is one line shared with the transient + * notice, the selected item, and the model stats, so the list is cut rather than left to crowd them out. + */ +internal const val STATUS_HINT_LIMIT = 6 + +/** + * One status bar suggestion: the chords that reach it, and the short label it reads under. + * + * @property List chords The canonical chord of each command suggested under [label], in + * registration order - one for a lone command, several for commands sharing a label ("1/2/3"). + * @property StringResource label The short localized label. + */ +internal data class StatusHint(val chords: List, val label: StringResource) + +/** + * Resolves the shortcuts worth suggesting for the space under the pointer, from the same declarations + * the command palette filters on. + * + * A command is suggested when it carries a [Command.hint], is offered over [hoveredKind] (the palette's + * own rule, [isOfferedIn]), and its hint's suggestedWhen holds. Commands scoped to particular spaces + * come first - they are what is specific to where the pointer is - followed by the ones that belong + * everywhere, each in registration order. + * + * Commands sharing one label are suggested as one entry carrying every member's chord. Such a group is + * shown only when EVERY member is bound: a partial run ("1/3 Select Mode") would misread as the full set. + * For a lone command that is simply the rule that an unbound command is never advertised. Chords come + * from the live keymap, so a rebind shows here at once. + * + * The list is then cut at [STATUS_HINT_LIMIT], keeping the leading entries - see [everyStatusHintFor] + * for the list before the cut. + * + * @param List commands The registered commands, in registration order. + * @param Keymap keymap The active keymap. + * @param SpaceKind? hoveredKind The space the pointer last touched, or null before it touched any. + * @return List The suggestions to show, at most [STATUS_HINT_LIMIT]. + */ +internal fun statusHintsFor(commands: List, keymap: Keymap, hoveredKind: SpaceKind?): List = + everyStatusHintFor(commands, keymap, hoveredKind).take(STATUS_HINT_LIMIT) + +/** + * Every suggestion [statusHintsFor] would make, before it cuts the list to fit the strip. + * + * Separate so that the cut can be seen: it drops the trailing suggestions without a trace, and only the + * uncut list says whether a space has more to suggest than the strip can show. + * + * @param List commands The registered commands, in registration order. + * @param Keymap keymap The active keymap. + * @param SpaceKind? hoveredKind The space the pointer last touched, or null before it touched any. + * @return List Every suggestion, in the order the strip shows them. + */ +internal fun everyStatusHintFor(commands: List, keymap: Keymap, hoveredKind: SpaceKind?): List { + // Each suggested command paired with the label it reads under, so the hint is resolved once. + val suggested = + commands.mapNotNull { command -> + command.hint + ?.takeIf { hint -> command.isOfferedIn(hoveredKind) && hint.suggestedWhen.isAvailable() } + ?.let { hint -> hint.label to command } + } + // A stable sort, so each tier keeps registration order. + val tiered = suggested.sortedBy { (_, command) -> if (command.spaces is CommandSpaces.Everywhere) 1 else 0 } + // groupBy keeps first-occurrence order (a LinkedHashMap), so a group sits where its first member does. + val membersByLabel = tiered.groupBy({ (label, _) -> label }, { (_, command) -> command }) + val hints = mutableListOf() + for ((label, members) in membersByLabel) { + val chords = members.mapNotNull { member -> keymap.chordFor(member.id) } + if (chords.size == members.size) { + hints.add(StatusHint(chords, label)) + } + } + return hints +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ViewportChrome.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ViewportChrome.kt new file mode 100644 index 0000000..6940c5c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ViewportChrome.kt @@ -0,0 +1,33 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.compositionLocalOf + +/* The 2D viewport's floating chrome state: whether the left tool toolbar and the right sidebar drawer + * are shown. The state itself lives in settings (interface.viewport.showToolbar / showSidebar) and is + * provided by the settings-backed shell wrapper; the plain EditorShell stays Settings-free (its + * documented contract), so the default here is what a standalone shell renders. */ + +/** The settings key backing the left tool toolbar's visibility. */ +const val SHOW_TOOLBAR_SETTINGS_KEY = "interface.viewport.showToolbar" + +/** The settings key backing the right sidebar drawer's visibility. */ +const val SHOW_SIDEBAR_SETTINGS_KEY = "interface.viewport.showSidebar" + +/** + * The viewport chrome visibility flags, resolved from settings by the persistent shell wrapper (or the + * defaults below in a standalone shell). The view.toggleToolbar / view.toggleSidebar commands and the + * sidebar's pull tab flip the backing settings; this state follows reactively. + * + * @property Boolean showToolbar Whether the left tool toolbar overlay is shown. + * @property Boolean showSidebar Whether the right sidebar drawer is open. + */ +data class ViewportChromeState( + val showToolbar: Boolean = true, + val showSidebar: Boolean = false, +) + +/** + * The active [ViewportChromeState]. Non-static: the persistent shell swaps the value on every settings + * change, and readers (the viewport body) must recompose with it. + */ +val LocalViewportChrome = compositionLocalOf { ViewportChromeState() } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ViewportHost.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ViewportHost.kt new file mode 100644 index 0000000..d40c2fd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/ViewportHost.kt @@ -0,0 +1,29 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier + +/** + * The seam through which an app injects the platform GL viewport into the common `:ui` shell. The 2D + * viewport (desktop renders offscreen via GLFW into a Compose Image; Android will drive a GLSurfaceView) + * lives in the app's platform source set - `:ui` can't reference it - so a Viewport2D area asks the host + * to render itself. The [areaId] lets the host cache one GL surface per area (via movableContentOf), so + * the surface moves rather than tears down when an unrelated area splits. + */ +fun interface ViewportHost { + /** + * Renders the 2D GL viewport for the given area. + * + * @param String areaId The hosting area's stable id (used to key the GL surface). + * @param Modifier modifier The layout modifier for the viewport (typically fillMaxSize). + */ + @Composable + fun Viewport2D(areaId: String, modifier: Modifier) +} + +/** + * The active [ViewportHost], or null when no GL viewport is available (e.g. before a model is open, or + * on a platform without the viewport wired). A Viewport2D area shows a placeholder when this is null. + */ +val LocalViewportHost = staticCompositionLocalOf { null } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Workspace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Workspace.kt new file mode 100644 index 0000000..0fcabdf --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/Workspace.kt @@ -0,0 +1,170 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.Serializable + +/** + * One workspace: a named, top-level tab holding an independent area tree. The [id] is a stable, + * locale-free identity - built-in workspaces use known ids ("modelling", "texture") that the tab + * strip resolves to a localized title, so the persisted layout never bakes in a display language. + * (User-created/renamed workspaces, when added, will carry a literal user name - user data, not + * localized, like part names.) + * + * 1 つのワークスペース(最上位タブ)。独立したエリアツリーを持つ。id はロケール非依存の安定識別子。 + * + * @property String id The stable workspace identity (also the title-resolution key for built-ins). + * @property AreaNode root The root of this workspace's area tree. + * @property String? name The user-supplied display name, or null for a built-in whose title is + * resolved from [id] (so a built-in's tab label stays localized). User-created and duplicated + * workspaces carry a literal name here - user data, shown verbatim, never localized. + */ +@Serializable +data class Workspace( + val id: String, + val root: AreaNode, + val name: String? = null, +) + +/** + * The whole persisted interface layout: which workspace is active and the ordered set of workspaces. + * Serialized as one object under the interface.layout settings key. An empty [workspaces] list is the + * "no layout yet - seed defaults" signal (matches defaultSettings.json's `interface.layout.workspaces: []`). + * + * 永続化されるインターフェイスレイアウト全体。interface.layout キーに 1 オブジェクトとして保存する。 + * + * @property String activeWorkspaceId The id of the workspace currently shown. + * @property List workspaces The workspaces, in tab order. + */ +@Serializable +data class InterfaceLayout( + val activeWorkspaceId: String, + val workspaces: List, +) { + /** + * The active workspace, or the first one if the active id no longer resolves (defensive against a + * stale id), or null only when there are no workspaces at all. + * + * @return Workspace? The workspace to display. + */ + fun activeWorkspace(): Workspace? = workspaces.firstOrNull { workspace -> workspace.id == activeWorkspaceId } ?: workspaces.firstOrNull() + + /** + * Returns a copy with the active workspace's root replaced - the update path for tree edits (ratio + * drags, splits, closes) that the shell applies after the area tree produces a new root. + * + * @param AreaNode newRoot The replacement root for the active workspace. + * @return InterfaceLayout The updated layout (unchanged if there is no active workspace). + */ + fun withActiveRoot(newRoot: AreaNode): InterfaceLayout { + val active = activeWorkspace() ?: return this + return copy(workspaces = workspaces.map { workspace -> if (workspace.id == active.id) workspace.copy(root = newRoot) else workspace }) + } + + /** + * The index of the active workspace in tab order, or 0 if its id no longer resolves - the same + * defensive fallback as [activeWorkspace], so navigation and tab highlighting agree. + * + * @return Int The active workspace's index (0 when empty or the id is stale). + */ + fun activeIndex(): Int = workspaces.indexOfFirst { workspace -> workspace.id == activeWorkspaceId }.coerceAtLeast(0) + + /** + * Moves the active selection [delta] tabs along the strip, wrapping around either end (so Next from + * the last tab lands on the first). A no-op when there are no workspaces. + * + * アクティブ選択を delta 個ずらす(端で巻き戻る)。ワークスペースが無ければ何もしない。 + * + * @param Int delta How many tabs to move (negative is leftward / previous). + * @return InterfaceLayout The layout with the active id shifted. + */ + fun withActiveShiftedBy(delta: Int): InterfaceLayout { + if (workspaces.isEmpty()) { + return this + } + val count = workspaces.size + // Kotlin's % can yield a negative result for a leftward delta; the extra + count and second % fold it back. + val shiftedIndex = ((activeIndex() + delta) % count + count) % count + return copy(activeWorkspaceId = workspaces[shiftedIndex].id) + } + + /** + * Inserts [workspace] at [atIndex] (clamped into range), optionally making it the active tab. The + * insertion path for new and duplicated workspaces. + * + * workspace を atIndex に挿入し、必要ならアクティブにする(新規・複製の挿入経路)。 + * + * @param Workspace workspace The workspace to insert. + * @param Int atIndex The target index (clamped to 0..size). + * @param Boolean activate Whether to switch the active tab to the inserted workspace. + * @return InterfaceLayout The layout with the workspace inserted. + */ + fun withWorkspaceInserted(workspace: Workspace, atIndex: Int, activate: Boolean): InterfaceLayout { + val updated = workspaces.toMutableList() + updated.add(atIndex.coerceIn(0, updated.size), workspace) + return copy( + workspaces = updated, + activeWorkspaceId = if (activate) workspace.id else activeWorkspaceId, + ) + } + + /** + * Removes the workspace with [id]. Refuses to remove the last workspace (the strip never goes + * empty), and if the removed workspace was active, moves the active selection to the tab that slides + * into its slot (or the new last tab). + * + * id のワークスペースを削除する。最後の 1 つは削除を拒否し、アクティブを隣のタブへ移す。 + * + * @param String id The workspace id to remove. + * @return InterfaceLayout The layout with the workspace removed (unchanged if it was the last or absent). + */ + fun withWorkspaceRemoved(id: String): InterfaceLayout { + if (workspaces.size <= 1) { + return this + } + val removedIndex = workspaces.indexOfFirst { workspace -> workspace.id == id } + if (removedIndex < 0) { + return this + } + val remaining = workspaces.filterNot { workspace -> workspace.id == id } + val nextActiveId = + if (activeWorkspaceId == id) { + remaining[removedIndex.coerceAtMost(remaining.size - 1)].id + } else { + activeWorkspaceId + } + return copy(workspaces = remaining, activeWorkspaceId = nextActiveId) + } + + /** + * Moves the workspace at [fromIndex] so it ends up at [toIndex] in tab order, leaving the active + * selection unchanged (reordering re-arranges tabs, it does not switch which one is shown). + * + * fromIndex のワークスペースを toIndex の位置へ移動する(アクティブ選択は変えない)。 + * + * @param Int fromIndex The current index of the workspace to move. + * @param Int toIndex The destination index in the final ordering. + * @return InterfaceLayout The reordered layout (unchanged if fromIndex is out of range). + */ + fun withWorkspacesReordered(fromIndex: Int, toIndex: Int): InterfaceLayout { + if (fromIndex !in workspaces.indices) { + return this + } + val updated = workspaces.toMutableList() + val moved = updated.removeAt(fromIndex) + updated.add(toIndex.coerceIn(0, updated.size), moved) + return copy(workspaces = updated) + } + + /** + * Sets the display [name] of the workspace with [id] (user data, shown verbatim, overriding any + * built-in localized title). A no-op if no workspace has that id. The caller is responsible for + * rejecting a blank name; this method stores whatever it is given. + * + * id のワークスペースの表示名を name に設定する(ユーザーデータ。組み込みの既定タイトルを上書きする)。 + * + * @param String id The workspace id to rename. + * @param String name The new display name. + * @return InterfaceLayout The layout with the workspace renamed. + */ + fun withWorkspaceRenamed(id: String, name: String): InterfaceLayout = + copy(workspaces = workspaces.map { workspace -> if (workspace.id == id) workspace.copy(name = name) else workspace }) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceDefaults.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceDefaults.kt new file mode 100644 index 0000000..95c2ead --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceDefaults.kt @@ -0,0 +1,149 @@ +package org.umamo.ui.workspace + +import kotlin.random.Random + +/** + * Mints a fresh, unique area id. Uses a random token rather than a global counter so there is no + * shared mutable state to make tests order-dependent or to reset across runs; uniqueness within a + * single layout (the only scope that matters) is overwhelmingly assured. Never reused once a leaf is + * closed, so it is safe as a stable Compose key. + * + * @return String A new area id. + */ +fun newAreaId(): String = "area-" + Random.nextLong().toULong().toString(16) + +/** + * Mints a fresh, unique workspace id. Like [newAreaId] it uses a random token rather than a counter so + * there is no shared mutable state, and like an area id it is locale-free and never reused - the + * persisted layout keys on it, and a user-created workspace's display name lives separately in + * [Workspace.name] so the id never bakes in a language. + * + * @return String A new workspace id. + */ +fun newWorkspaceId(): String = "ws-" + Random.nextLong().toULong().toString(16) + +/** + * Deep-copies an area tree, minting a fresh id for every leaf. Duplicating a workspace must not reuse + * the source's leaf ids: those ids are stable Compose keys and the handles the GL-identity machinery + * keeps a per-area surface alive by, so two workspaces sharing a leaf id would collide. The space kind + * and split orientation/ratio are preserved so the copy looks identical. + * + * @param AreaNode node The tree to clone. + * @return AreaNode A structurally identical tree with all-fresh leaf ids. + */ +fun cloneAreaTree(node: AreaNode): AreaNode = + when (node) { + is LeafArea -> LeafArea(newAreaId(), node.space) + is SplitNode -> node.copy(first = cloneAreaTree(node.first), second = cloneAreaTree(node.second)) + } + +/** + * Resolves a unique display name from [base] given the [existing] workspaces: returns [base] unchanged + * when no other workspace already uses it, otherwise appends the lowest free " N" suffix ("Workspace", + * "Workspace 2", "Workspace 3", …). Only user names ([Workspace.name]) are considered taken; built-ins + * resolve their title from id and never collide with a stored name. + * + * @param String base The desired base name. + * @param List existing The current workspaces to avoid colliding with. + * @return String A name not already used by any existing workspace. + */ +fun uniqueWorkspaceName(base: String, existing: List): String { + val takenNames = existing.mapNotNull { workspace -> workspace.name }.toSet() + if (base !in takenNames) { + return base + } + var candidateSuffix = 2 + while ("$base $candidateSuffix" in takenNames) { + candidateSuffix++ + } + return "$base $candidateSuffix" +} + +/** + * The seeded default layout used when no saved layout exists. Three workspaces: + * + * - "Modelling" puts the Parameters panel on the left, the 2D viewport over the keyform sheet in the + * middle, and the Outliner over Properties on the right. + * - "Texture" stacks two UV editors on the left, then the 2D viewport, then a right column of the + * Sources table over the Outliner over Properties. + * - "Physics" is a single 2D viewport. + * + * Modelling is active. Each built-in seeds name = null so its tab stays localized. + * + * @return InterfaceLayout The default three-workspace layout. + */ +fun defaultLayout(): InterfaceLayout { + val modelling = + Workspace( + id = "modelling", + root = + SplitNode( + orientation = SplitOrientation.Horizontal, + ratio = 0.75f, + first = + SplitNode( + orientation = SplitOrientation.Horizontal, + ratio = 0.2f, + first = LeafArea(newAreaId(), SpaceKind.Parameters), + second = + SplitNode( + orientation = SplitOrientation.Vertical, + ratio = 0.6f, + first = LeafArea(newAreaId(), SpaceKind.Viewport2D), + second = LeafArea(newAreaId(), SpaceKind.KeyformSheet), + ), + ), + second = + SplitNode( + orientation = SplitOrientation.Vertical, + ratio = 0.5f, + first = LeafArea(newAreaId(), SpaceKind.Outliner), + second = LeafArea(newAreaId(), SpaceKind.Properties), + ), + ), + ) + val texture = + Workspace( + id = "texture", + root = + SplitNode( + orientation = SplitOrientation.Horizontal, + ratio = 0.35f, + first = + SplitNode( + orientation = SplitOrientation.Vertical, + ratio = 0.5f, + first = LeafArea(newAreaId(), SpaceKind.UvEditor), + second = LeafArea(newAreaId(), SpaceKind.UvEditor), + ), + second = + SplitNode( + orientation = SplitOrientation.Horizontal, + ratio = 0.65f, + first = LeafArea(newAreaId(), SpaceKind.Viewport2D), + second = + SplitNode( + orientation = SplitOrientation.Vertical, + ratio = 0.65f, + first = + SplitNode( + orientation = SplitOrientation.Vertical, + ratio = 0.65f, + first = LeafArea(newAreaId(), SpaceKind.Sources), + second = LeafArea(newAreaId(), SpaceKind.Outliner), + ), + second = LeafArea(newAreaId(), SpaceKind.Properties), + ), + ), + ), + ) + val physics = + Workspace( + id = "physics", + root = LeafArea(newAreaId(), SpaceKind.Viewport2D), + ) + return InterfaceLayout( + activeWorkspaceId = "modelling", + workspaces = listOf(modelling, texture, physics), + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceLayoutController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceLayoutController.kt new file mode 100644 index 0000000..7ac68bf --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceLayoutController.kt @@ -0,0 +1,188 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +/** + * Owns the shell's workspace layout state and every operation that rewrites it: the area-tree + * structural edits, the workspace CRUD behind the tab strip and its context menu, and the import + * paths. Each write publishes the new layout through [onLayoutChange] (the persistence hook), and a + * write that disposes or re-homes the focused area subtree also bumps [structuralEditCount], which + * the shell's focus-reclaim effect watches - a join/split (or a workspace switch/delete invoked from + * a focusable popup) would otherwise leave focus null and silently kill all keyboard shortcuts until + * the next click. (Reorder and rename are exempt: a reorder is a pointer drag that never holds + * focus, and a rename ends in the inline editor's own close-time reclaim.) + * + * シェルのワークスペース配置状態と、それを書き換える全操作(エリアツリー編集・タブの CRUD・ + * インポート)を持つ。書き込みは onLayoutChange で永続化され、フォーカスを壊しうる編集は + * structuralEditCount を進めてシェルの再フォーカス処理を起こす。 + */ +internal class WorkspaceLayoutController( + initialLayout: InterfaceLayout, + private val onLayoutChange: (InterfaceLayout) -> Unit, +) { + /** The live layout every shell chrome piece renders from. */ + var layout: InterfaceLayout by mutableStateOf(initialLayout) + private set + + /** Bumped on every focus-hazardous edit; the shell's refocus effect keys on it. */ + var structuralEditCount: Int by mutableStateOf(0) + private set + + /** + * Publishes [newLayout]: swaps the live state, notifies the persistence hook, and bumps the + * structural counter when the edit can strand focus. + * + * @param InterfaceLayout newLayout The layout to publish. + * @param Boolean structural Whether the edit may have disposed the focused subtree. + */ + private fun publish(newLayout: InterfaceLayout, structural: Boolean) { + layout = newLayout + onLayoutChange(newLayout) + if (structural) { + structuralEditCount++ + } + } + + /** + * Applies a structural edit to the active workspace's area tree and republishes the layout. + * + * @param AreaCommand command The structural edit. + */ + fun applyAreaCommand(command: AreaCommand) { + val root = layout.activeWorkspace()?.root ?: return + publish(layout.withActiveRoot(reduce(root, command)), structural = true) + } + + /** + * Replaces the active workspace's root from a ratio drag (the tree's onNodeChange path). + * + * @param AreaNode newRoot The updated tree. + */ + fun updateActiveRoot(newRoot: AreaNode) { + publish(layout.withActiveRoot(newRoot), structural = false) + } + + /** + * Activates the workspace [workspaceId] (a tab click; focus stays where it is). + * + * @param String workspaceId The workspace to activate. + */ + fun setActiveWorkspace(workspaceId: String) { + publish(layout.copy(activeWorkspaceId = workspaceId), structural = false) + } + + /** + * Moves the active selection [delta] tabs along the strip (wrapping), backing workspace.prev/next. + * + * @param Int delta Tabs to move by (negative = left). + */ + fun switchBy(delta: Int) { + publish(layout.withActiveShiftedBy(delta), structural = true) + } + + /** + * Appends a new single-viewport workspace named from [suggestedName] (deduped) and activates it. + * + * @param String suggestedName The localized base name to dedupe from. + */ + fun create(suggestedName: String) { + val workspace = + Workspace( + id = newWorkspaceId(), + root = LeafArea(newAreaId(), SpaceKind.Viewport2D), + name = uniqueWorkspaceName(suggestedName, layout.workspaces), + ) + publish(layout.withWorkspaceInserted(workspace, layout.workspaces.size, activate = true), structural = true) + } + + /** + * Inserts a copy of [sourceId] (fresh ids via [cloneAreaTree], deduped [suggestedName]) after it. + * + * @param String sourceId The workspace to copy. + * @param String suggestedName The name to dedupe from. + */ + fun duplicate(sourceId: String, suggestedName: String) { + val sourceIndex = layout.workspaces.indexOfFirst { workspace -> workspace.id == sourceId } + if (sourceIndex < 0) { + return + } + val source = layout.workspaces[sourceIndex] + val copy = + Workspace( + id = newWorkspaceId(), + root = cloneAreaTree(source.root), + name = uniqueWorkspaceName(suggestedName, layout.workspaces), + ) + publish(layout.withWorkspaceInserted(copy, sourceIndex + 1, activate = true), structural = true) + } + + /** + * Removes [targetId] (refused when it is the last workspace) and republishes the layout. + * + * @param String targetId The workspace to remove. + */ + fun delete(targetId: String) { + publish(layout.withWorkspaceRemoved(targetId), structural = true) + } + + /** + * Moves the workspace at [fromIndex] to [toIndex] in tab order and republishes the layout. + * + * @param Int fromIndex The dragged tab's index. + * @param Int toIndex The destination index. + */ + fun reorder(fromIndex: Int, toIndex: Int) { + publish(layout.withWorkspacesReordered(fromIndex, toIndex), structural = false) + } + + /** + * Sets the display name of [workspaceId] from an inline rename and republishes the layout. + * + * @param String workspaceId The workspace to rename. + * @param String newName The new display name. + */ + fun rename(workspaceId: String, newName: String) { + publish(layout.withWorkspaceRenamed(workspaceId, newName), structural = false) + } + + /** + * Resets the active workspace's area tree to its default: a built-in id ("modelling"/"texture"/ + * "physics") goes back to its seeded tree, while a user-created workspace collapses to a single 2D + * viewport. Only the active workspace is touched; the others keep their layouts. Gated behind a + * confirm by its command. + */ + fun resetActive() { + val active = layout.activeWorkspace() ?: return + // defaultLayout() mints fresh area ids on every call, so the built-in root is already collision-free. + val builtinRoot = defaultLayout().workspaces.firstOrNull { workspace -> workspace.id == active.id }?.root + val resetRoot = builtinRoot ?: LeafArea(newAreaId(), SpaceKind.Viewport2D) + publish(layout.withActiveRoot(resetRoot), structural = true) + } + + /** + * Appends [imported] as a fresh tab (re-minted ids, deduped name) and activates it; the import path. + * + * @param Workspace imported The parsed workspace to append. + * @param String fallbackName The localized base name used when the import carries none. + */ + fun appendImported(imported: Workspace, fallbackName: String) { + val copy = + Workspace( + id = newWorkspaceId(), + root = cloneAreaTree(imported.root), + name = uniqueWorkspaceName(imported.name ?: fallbackName, layout.workspaces), + ) + publish(layout.withWorkspaceInserted(copy, layout.workspaces.size, activate = true), structural = true) + } + + /** + * Replaces the whole layout with [imported] (import-overwrite); gated behind a confirm by its command. + * + * @param InterfaceLayout imported The parsed layout to apply. + */ + fun applyImported(imported: InterfaceLayout) { + publish(imported, structural = true) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceLayoutFiles.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceLayoutFiles.kt new file mode 100644 index 0000000..157933c --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceLayoutFiles.kt @@ -0,0 +1,108 @@ +package org.umamo.ui.workspace + +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.readString +import io.github.vinceglb.filekit.writeString +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import org.umamo.settings.Settings +import org.umamo.storage.FilePicker +import org.umamo.storage.UmamoLog +import org.umamo.ui.action.CommandRegistry + +/** + * The workspace layout's trips to and from a file: export the active workspace, export the whole layout, + * and import either. None of it touches a document, so it sits with the layout it moves rather than with + * the app's document flows. + * + * An export writes the PERSISTED layout - the saved JSON from settings, which is what a rigger means by + * "my layout" and what another install will load. The saved element goes out verbatim, so any key a newer + * build wrote that this one does not know survives the trip. Layout edits reach settings through a + * debounce, though, so an export first commits whatever the debounce is still holding: the file is the + * layout on screen, never the one from a moment before the last split. + * + * An import never edits the layout itself: it parses the file and dispatches workspace.applyLayout or + * workspace.appendWorkspace, so the shell's live layout state stays the single source of truth and a + * whole-layout replace goes through the one confirm. + * + * @property Settings settings The settings the persisted layout is read from. + * @property FilePicker filePicker The native open and save dialogs. + * @property CoroutineScope scope The scope the dialogs and the file IO run in. + * @property CommandRegistry commandRegistry The registry an imported layout or workspace is applied through. + * @property Function commitPendingLayout Writes the live layout to settings now if the debounce has yet + * to; the owner of that debounce supplies it, and keeps its own rules (nothing is written mid-drag). + */ +internal class WorkspaceLayoutFiles( + private val settings: Settings, + private val filePicker: FilePicker, + private val scope: CoroutineScope, + private val commandRegistry: CommandRegistry, + private val commitPendingLayout: () -> Unit, +) { + /** + * The text Export All Workspaces writes: the whole persisted layout, pretty-printed, as of now. + * + * @return String? The layout JSON, or null when no layout has been saved yet. + */ + internal fun allWorkspacesText(): String? { + commitPendingLayout() + return exportLayoutText(settings) + } + + /** + * The workspace Export This Workspace writes: the persisted layout's active one, as of now. + * + * @return Workspace? The active workspace, or null when no layout has been saved yet. + */ + internal fun activeWorkspaceToExport(): Workspace? { + commitPendingLayout() + return settings.get(INTERFACE_LAYOUT_KEY)?.let { element -> decodeLayout(element) }?.activeWorkspace() + } + + /** Exports the whole interface.layout, pretty-printed, to a file; does nothing when no layout has been saved yet. */ + fun exportAllWorkspaces() { + val text = allWorkspacesText() ?: return + scope.launch { + filePicker.saveFile("workspaces", "json")?.let { destination -> + destination.writeString(text) + UmamoLog.info("exported all workspaces to ${destination.absolutePath()}") + } + } + } + + /** Exports the active workspace of the persisted layout to a file; its display name (or id) seeds the suggested filename. */ + fun exportThisWorkspace() { + val active = activeWorkspaceToExport() ?: return + val text = exportWorkspaceText(active) + scope.launch { + filePicker.saveFile(active.name ?: active.id, "json")?.let { destination -> + destination.writeString(text) + UmamoLog.info("exported workspace to ${destination.absolutePath()}") + } + } + } + + /** + * Imports a layout or workspace file, detected by shape: a whole layout overwrites every workspace (the + * shell confirms first), a single workspace is appended as a new tab, and anything else is rejected with + * a log line and the current layout untouched. + */ + fun importWorkspace() { + scope.launch { + filePicker.openFile(listOf("json"))?.let { picked -> + val text = picked.readString() + val importedLayout = decodeLayoutText(text) + if (importedLayout != null) { + commandRegistry.invoke("workspace.applyLayout", importedLayout) + } else { + val importedWorkspace = decodeWorkspaceText(text) + if (importedWorkspace != null) { + commandRegistry.invoke("workspace.appendWorkspace", importedWorkspace) + } else { + UmamoLog.warn("invalid workspace file: ${picked.absolutePath()}") + } + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceReducer.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceReducer.kt new file mode 100644 index 0000000..08356bd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceReducer.kt @@ -0,0 +1,261 @@ +package org.umamo.ui.workspace + +/** + * A structural edit to an area tree, addressed by the target leaf's id. These are the named commands + * the area header (and a future keymap/palette) issue; keeping them as data objects routed through + * one pure [reduce] choke point means the mutation logic is centralized and unit-testable, and the + * action registry can drive them by name without the header touching the tree directly. + * + * Ratio drags are deliberately NOT here: a splitter rewrites its own subtree (dragSplitBoundary) and + * threads the result up via the layout callback, so it never needs an id lookup. + * + * エリアツリーへの構造的編集(対象は葉の id)。ヘッダ等が発行する名前付きコマンド。純粋な reduce に集約。 + * + * @property String areaId The leaf the command targets. + */ +sealed interface AreaCommand { + val areaId: String + + /** + * Split the target leaf in two along [orientation] at [ratio] (the original side's fraction of the + * axis, 0..1, defaulting to an even 50/50 split); the new sibling inherits the leaf's space. + */ + data class SplitArea( + override val areaId: String, + val orientation: SplitOrientation, + val ratio: Float = 0.5f, + ) : AreaCommand + + /** Close the target leaf, collapsing its parent split into the surviving sibling. */ + data class CloseArea(override val areaId: String) : AreaCommand + + /** Switch the target leaf to a different editor [kind], keeping its id. */ + data class SwitchSpace(override val areaId: String, val kind: SpaceKind) : AreaCommand + + /** + * Join two direct-sibling leaves: [survivorId] consumes its sibling [consumedId], collapsing their + * shared parent split into the survivor. A no-op unless the two are direct sibling leaves. The + * command targets the surviving leaf, so [areaId] is [survivorId]. + */ + data class JoinAreas(val survivorId: String, val consumedId: String) : AreaCommand { + override val areaId: String get() = survivorId + } + + /** + * Dock a leaf as a full-span strip on one [edge] of the whole workspace: the leaf is lifted out of its + * current slot (which heals - its parent split collapses into the sibling) and re-inserted spanning the + * given edge of the root, taking [ratio] of the perpendicular axis. Area count is preserved (the leaf + * moves, nothing is consumed); a no-op if the leaf is the workspace's sole area. Used for the + * non-aligned drop, where a clean sibling join is impossible. + */ + data class DockArea(val sourceId: String, val edge: DockEdge, val ratio: Float) : AreaCommand { + override val areaId: String get() = sourceId + } +} + +/** + * Which edge of the workspace a [AreaCommand.DockArea] docks its leaf against. Bottom/Top dock a + * full-width strip; Left/Right dock a full-height one. + * + * ドック先のワークスペース端。Bottom/Top は横幅いっぱい、Left/Right は縦高いっぱいの帯。 + */ +enum class DockEdge { + Top, + Bottom, + Left, + Right, +} + +/** + * Applies a structural [command] to [root], returning the new tree (the input is never mutated - + * data classes + copy). Unknown ids are no-ops (the tree returns unchanged), so a stale command from + * a closed area fails safely. + * + * 構造的コマンドを root に適用し、新しいツリーを返す(入力は不変)。未知の id は無操作。 + * + * @param AreaNode root The tree to edit. + * @param AreaCommand command The structural edit to apply. + * @return AreaNode The resulting tree. + */ +fun reduce(root: AreaNode, command: AreaCommand): AreaNode = + when (command) { + is AreaCommand.SplitArea -> + mapLeaf(root, command.areaId) { leaf -> + SplitNode( + orientation = command.orientation, + ratio = command.ratio, + first = leaf, + second = LeafArea(newAreaId(), leaf.space), + ) + } + is AreaCommand.SwitchSpace -> + mapLeaf(root, command.areaId) { leaf -> leaf.copy(space = command.kind) } + is AreaCommand.CloseArea -> closeArea(root, command.areaId) + is AreaCommand.JoinAreas -> + // removeLeaf collapses a split to its OTHER child, so removing the consumed sibling promotes + // the survivor - but only valid when the two really are direct siblings, else a no-op. + if (command.survivorId != command.consumedId && + areDirectSiblings(root, command.survivorId, command.consumedId) + ) { + removeLeaf(root, command.consumedId) ?: root + } else { + root + } + is AreaCommand.DockArea -> dockArea(root, command.sourceId, command.edge, command.ratio) + } + +/** + * Lifts the leaf [sourceId] out of its slot (its parent split collapses into the sibling) and re-inserts + * it as a full-span strip on [edge] of the whole workspace, the strip taking [ratio] of the perpendicular + * axis. A no-op when the leaf is missing or is the workspace's sole area (nothing to dock against). + * + * 葉を現在の位置から外し(親分割は兄弟に畳む)、ワークスペース端の帯として再挿入する。 + * + * @param AreaNode root The tree to edit. + * @param String sourceId The leaf to dock. + * @param DockEdge edge The workspace edge to dock against. + * @param Float ratio The docked strip's fraction of the perpendicular axis. + * @return AreaNode The restructured tree, or [root] unchanged on a no-op. + */ +private fun dockArea(root: AreaNode, sourceId: String, edge: DockEdge, ratio: Float): AreaNode { + val sourceLeaf = findLeaf(root, sourceId) + val remainder = removeLeaf(root, sourceId) + if (sourceLeaf == null || remainder == null) { + return root + } + val stripRatio = ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + return when (edge) { + // The strip is the first child for Top/Left and the second for Bottom/Right, so the ratio (always + // the leading child's fraction) is the strip's share where it leads and the complement otherwise. + DockEdge.Top -> SplitNode(SplitOrientation.Vertical, stripRatio, sourceLeaf, remainder) + DockEdge.Bottom -> SplitNode(SplitOrientation.Vertical, 1f - stripRatio, remainder, sourceLeaf) + DockEdge.Left -> SplitNode(SplitOrientation.Horizontal, stripRatio, sourceLeaf, remainder) + DockEdge.Right -> SplitNode(SplitOrientation.Horizontal, 1f - stripRatio, remainder, sourceLeaf) + } +} + +/** + * Finds the leaf with id [areaId] anywhere in [node], or null if absent. + * + * @param AreaNode node The subtree to search. + * @param String areaId The leaf id to find. + * @return LeafArea? The matching leaf, or null. + */ +private fun findLeaf(node: AreaNode, areaId: String): LeafArea? = + when (node) { + is LeafArea -> if (node.id == areaId) node else null + is SplitNode -> findLeaf(node.first, areaId) ?: findLeaf(node.second, areaId) + } + +/** + * Reports whether [firstId] and [secondId] are both leaves and the two direct children of one + * [SplitNode] - i.e. they share a full edge and can be joined by collapsing their parent split. + * Recurses the whole tree looking for such a parent. + * + * firstId と secondId が同一 SplitNode の 2 つの直接の子(葉)かどうかを返す。 + * + * @param AreaNode node The subtree to search. + * @param String firstId One leaf id. + * @param String secondId The other leaf id. + * @return Boolean True when the two are direct sibling leaves somewhere in [node]. + */ +internal fun areDirectSiblings(node: AreaNode, firstId: String, secondId: String): Boolean = + when (node) { + is LeafArea -> false + is SplitNode -> { + val firstChild = node.first + val secondChild = node.second + val matchedHere = + firstChild is LeafArea && + secondChild is LeafArea && + ( + (firstChild.id == firstId && secondChild.id == secondId) || + (firstChild.id == secondId && secondChild.id == firstId) + ) + matchedHere || + areDirectSiblings(firstChild, firstId, secondId) || + areDirectSiblings(secondChild, firstId, secondId) + } + } + +/** + * Returns a copy of [node] with the leaf whose id is [areaId] replaced by [transform]'s result; + * recurses into splits. Leaves that don't match (and the whole tree, if none matches) come back + * structurally unchanged. + * + * id 一致の葉を transform で置換したコピーを返す。分割は再帰。一致が無ければ不変。 + * + * @param AreaNode node The subtree to walk. + * @param String areaId The leaf id to replace. + * @param Function transform Maps the matched leaf to its replacement node. + * @return AreaNode The rewritten subtree. + */ +private fun mapLeaf(node: AreaNode, areaId: String, transform: (LeafArea) -> AreaNode): AreaNode = + when (node) { + is LeafArea -> + if (node.id == areaId) { + transform(node) + } else { + node + } + is SplitNode -> + node.copy( + first = mapLeaf(node.first, areaId, transform), + second = mapLeaf(node.second, areaId, transform), + ) + } + +/** + * Closes the leaf [areaId] by collapsing its parent split into the surviving sibling. Closing the + * sole leaf of a workspace is refused (returns the tree unchanged) - a workspace must always have at + * least one area. + * + * 親分割を生き残る兄弟に畳んで葉を閉じる。ワークスペース唯一の葉は閉じない(不変を返す)。 + * + * @param AreaNode root The tree to edit. + * @param String areaId The leaf id to close. + * @return AreaNode The tree with the leaf removed (or unchanged if it is the sole area / not found). + */ +private fun closeArea(root: AreaNode, areaId: String): AreaNode { + if (root is LeafArea) { + return root + } + return removeLeaf(root, areaId) ?: root +} + +/** + * Recursively removes the leaf [areaId] from a subtree, returning the rewritten subtree, or null when + * the leaf is not in this subtree (the caller uses null to mean "keep looking / not here"). When a + * split's direct child is the target, the split collapses to its other child. + * + * 部分木から葉を再帰的に取り除き、書き換えた部分木を返す。ここに無ければ null。 + * + * @param node The subtree to search. + * @param areaId The leaf id to remove. + * @return AreaNode? The rewritten subtree, or null if the leaf was not found here. + */ +private fun removeLeaf(node: AreaNode, areaId: String): AreaNode? = + when (node) { + is LeafArea -> null + is SplitNode -> { + val firstChild = node.first + val secondChild = node.second + when { + firstChild is LeafArea && firstChild.id == areaId -> secondChild + secondChild is LeafArea && secondChild.id == areaId -> firstChild + else -> { + val rewrittenFirst = removeLeaf(firstChild, areaId) + if (rewrittenFirst != null) { + node.copy(first = rewrittenFirst) + } else { + val rewrittenSecond = removeLeaf(secondChild, areaId) + if (rewrittenSecond != null) { + node.copy(second = rewrittenSecond) + } else { + null + } + } + } + } + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceTabs.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceTabs.kt new file mode 100644 index 0000000..15847fd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/WorkspaceTabs.kt @@ -0,0 +1,416 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.isTertiaryPressed +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChange +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import androidx.compose.ui.zIndex +import kotlinx.coroutines.withTimeoutOrNull +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.DoubleClickTracker +import org.umamo.ui.kit.InlineRenameField +import org.umamo.ui.kit.LocalInlineEditController +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.Tab +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.drawIcon + +/** + * How long the pointer must rest on a tab before a drag reorders it. Below this, a press is a tap + * (select) or a quick flick, never a reorder - without the gate a fast click that nudges a few pixels + * would silently reshuffle the tab order. + */ +private const val REORDER_HOLD_MILLIS = 100L + +/** + * The browser-style top tab strip: one tab per workspace (the active one selected), a trailing "+" + * button that creates a new workspace, a right-click context menu per tab (Duplicate, Delete, and the + * Previous/Next navigation commands), and drag-to-reorder. The strip is a thin view: every mutation is + * reported to the shell, which owns the layout - selecting reports an id, create/duplicate/delete/reorder + * report the requested edit, and Previous/Next dispatch through the action registry (so the same keyboard + * shortcut and this menu drive one code path). + * + * 最上部のタブ帯。ワークスペースごとに 1 タブ+末尾の「+」で新規作成、右クリックで複製・削除・前後移動、 + * ドラッグで並べ替え。状態は持たず、すべての変更をシェルに通知する。 + * + * @param List workspaces The workspaces in tab order. + * @param String activeId The currently active workspace id. + * @param Function onSelect Reports the chosen workspace id. + * @param Function onCreate Requests a new workspace, given a suggested (already-localized) base name. + * @param Function onDuplicate Requests a copy of the workspace id, given a suggested name for the copy. + * @param Function onDelete Requests deletion of the workspace id. + * @param Function onReorder Requests moving the workspace at fromIndex to toIndex in tab order. + * @param Function onRename Requests setting the workspace id's display name (from an inline edit). + * @param Modifier modifier The layout modifier. + */ +@Composable +fun WorkspaceTabs( + workspaces: List, + activeId: String, + onSelect: (String) -> Unit, + onCreate: (suggestedName: String) -> Unit, + onDuplicate: (workspaceId: String, suggestedName: String) -> Unit, + onDelete: (workspaceId: String) -> Unit, + onReorder: (fromIndex: Int, toIndex: Int) -> Unit, + onRename: (workspaceId: String, newName: String) -> Unit, + modifier: Modifier = Modifier, +) { + val typography = LocalUmamoTypography.current + val commands = LocalCommands.current + val keymap = LocalKeymap.current + val activeIndex = workspaces.indexOfFirst { workspace -> workspace.id == activeId }.coerceAtLeast(0) + + // Drag-to-reorder state. The dragged tab translates with the pointer while its layout slot stays put; + // on release the projected center decides the destination index. Tab centers are measured in root + // space (a common frame for all tabs) so the projected-center comparison is consistent. + var draggingIndex by remember { mutableStateOf(null) } + var dragDeltaX by remember { mutableStateOf(0f) } + val tabCenters = remember { mutableStateMapOf() } + // Bumped when a drag finishes, to force-rebuild each tab's hover interaction source (see the key below): + // a reorder shifts tabs under a stationary pointer, which Compose does not see as a hover change, so a + // tab hovered during the drag would otherwise stay highlighted until the pointer re-enters it. + var reorderGeneration by remember { mutableStateOf(0) } + // The workspace whose tab is being renamed in place (double-click or the context-menu Rename), or null. + var editingWorkspaceId by remember { mutableStateOf(null) } + + // Localized chrome resolved once here: the context-menu onSelect lambdas run on a pointer event, not + // in composition, so they cannot call stringResource themselves - they capture these instead. + val newWorkspaceName = stringResource(Res.string.workspace_new_name) + val newWorkspaceLabel = stringResource(Res.string.workspace_new) + val copySuffix = stringResource(Res.string.workspace_copy_suffix) + val renameLabel = stringResource(Res.string.workspace_rename) + val duplicateLabel = stringResource(Res.string.workspace_duplicate) + val deleteLabel = stringResource(Res.string.workspace_delete) + val previousLabel = stringResource(Res.string.cmd_workspace_prev) + val nextLabel = stringResource(Res.string.cmd_workspace_next) + val previousShortcut = keymap.chordFor("workspace.prev")?.let { chord -> formatAccelerator(chord) } + val nextShortcut = keymap.chordFor("workspace.next")?.let { chord -> formatAccelerator(chord) } + + // height(IntrinsicSize.Min) makes the strip exactly as tall as a Tab's font-metric-driven line + // box, so fillMaxHeight children (the "+" button) match the tabs to the pixel — a fixed dp size + // cannot track a fractional text metric and always lands one pixel off at some density. + Row(modifier = modifier.height(IntrinsicSize.Min), verticalAlignment = Alignment.CenterVertically) { + workspaces.forEachIndexed { index, workspace -> + // A workspace with a name shows it verbatim (user data, never translated); otherwise the title + // resolves from the id, which localizes built-ins (and is the id itself for anything else). So + // an unnamed built-in relabels on a runtime language switch, while renaming one promotes it to a + // custom-named tab that keeps its literal name. A legacy layout that baked a name onto a built-in + // is cleared to null on load (see migrateLayout), so those tabs localize again rather than sticking. + val title = workspace.name ?: workspaceTitle(workspace.id) + if (editingWorkspaceId == workspace.id) { + // The tab turns into an inline editor in place of its label. + WorkspaceTabEditor( + initialName = title, + onCommit = { newName -> + editingWorkspaceId = null + onRename(workspace.id, newName) + }, + onCancel = { editingWorkspaceId = null }, + ) + } else { + val isDragging = draggingIndex == index + val contextItems = + listOf( + MenuItem.Action(renameLabel, onSelect = { editingWorkspaceId = workspace.id }), + MenuItem.Action(duplicateLabel, onSelect = { onDuplicate(workspace.id, "$title $copySuffix") }), + // The strip never goes empty, so deleting the last workspace is offered as a disabled row. + MenuItem.Action( + deleteLabel, + onSelect = { onDelete(workspace.id) }, + enabled = workspaces.size > 1, + ), + MenuItem.Separator, + MenuItem.Action( + previousLabel, + onSelect = { commands.invoke("workspace.prev") }, + shortcut = previousShortcut, + ), + MenuItem.Action( + nextLabel, + onSelect = { commands.invoke("workspace.next") }, + shortcut = nextShortcut, + ), + ) + Box( + modifier = + Modifier + // Measured on the static slot (the Box), not the translated Tab, so the slot center is + // stable while the tab visual is dragged across it. The center is resolved in the parent + // (Row) space - a frame shared by every tab - so the drag's projected-center comparison is + // consistent across tabs. + .onGloballyPositioned { coordinates -> + val parent = coordinates.parentLayoutCoordinates + if (parent != null) { + tabCenters[index] = + parent.localPositionOf(coordinates, Offset(coordinates.size.width / 2f, 0f)).x + } + } + // Raise the dragged tab above its neighbors so it draws (and is hit-tested) on top. + .then(if (isDragging) Modifier.zIndex(1f) else Modifier) + // Keyed on the workspace as well as the slot: the gesture reads workspace.id, and a reorder + // can hand a slot a different workspace without changing its index or the tab count. + .pointerInput(workspace.id, index, workspaces.size) { + // One tracker per tab, so a press on one tab never pairs with a press on another. + val clickTracker = DoubleClickTracker() + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + // A secondary/tertiary press belongs to the context-menu gesture, never to a tab drag + // or a rename tap - leave it for ContextMenuArea. (Touch reports neither, so it passes.) + if (currentEvent.buttons.isSecondaryPressed || currentEvent.buttons.isTertiaryPressed) { + return@awaitEachGesture + } + // Double-click is detected on the press, not the release: the tab's clickable consumes + // the up when it fires its click, so the up is an unreliable signal, but the down always + // reaches us. Selection stays on that clickable, which is why this gesture uses the + // shared timing core rather than the singleOrDoubleClick modifier: the clickable consumes + // the press before a parent modifier would see it. + if (clickTracker.registerPress(down.uptimeMillis)) { + editingWorkspaceId = workspace.id + return@awaitEachGesture + } + // Hold gate: wait out the window watching the raw pressed state (read from the event, + // not waitForUpOrCancellation, whose result the clickable's up-consumption would defeat). + // A lift within the window is a click: the clickable handled selection, nothing to do here. + val liftedWithinWindow = + withTimeoutOrNull(REORDER_HOLD_MILLIS) { + var pointerUp = false + while (!pointerUp) { + val event = awaitPointerEvent() + val change = + event.changes.firstOrNull { pointer -> pointer.id == down.id } + if (change == null || !change.pressed) { + pointerUp = true + } + } + true + } + if (liftedWithinWindow != null) { + return@awaitEachGesture + } + // Held past the window: arm the reorder, engaging once the pointer actually moves. + var engaged = false + while (true) { + val event = awaitPointerEvent() + val change = + event.changes.firstOrNull { pointer -> pointer.id == down.id } ?: break + if (!change.pressed) { + break + } + if (!engaged && change.positionChange().getDistanceSquared() > 0f) { + engaged = true + draggingIndex = index + dragDeltaX = 0f + } + if (engaged) { + dragDeltaX += change.positionChange().x + change.consume() + } + } + if (engaged) { + val fromIndex = draggingIndex + if (fromIndex != null) { + val centers = + (0 until workspaces.size).map { tabIndex -> tabCenters[tabIndex] } + val toIndex = reorderTargetIndex(fromIndex, dragDeltaX, centers) + if (toIndex != fromIndex) { + onReorder(fromIndex, toIndex) + } + } + draggingIndex = null + dragDeltaX = 0f + // A drag's press must not pair with a later click as a double-click. + clickTracker.reset() + // Rebuild the tab visuals so no tab keeps a hover left stale by the layout shift. + reorderGeneration++ + } + } + }, + ) { + // Keyed on reorderGeneration so a completed reorder rebuilds the tab (and its hover + // interaction source) from scratch - clearing any hover the layout shift left stale. + key(reorderGeneration) { + ContextMenuArea(items = contextItems) { + Tab( + selected = index == activeIndex, + onClick = { onSelect(workspace.id) }, + modifier = + Modifier.graphicsLayer { + translationX = if (isDragging) dragDeltaX else 0f + alpha = if (isDragging) 0.85f else 1f + }, + label = { Text(title, style = typography.labelMedium) }, + ) + } + } + } + } + } + NewWorkspaceButton(contentDescription = newWorkspaceLabel, onClick = { onCreate(newWorkspaceName) }) + } +} + +/** + * The in-place rename editor shown over a tab's slot. Styled to match a selected [Tab] (panel fill, same + * padding) so it reads as the tab itself turning editable. The whole name starts selected so typing + * replaces it; it commits on Enter or when focus leaves (clicking away), and cancels on Escape - the last + * routed in by the shell via [LocalInlineEditController], because the shell's root key handler previews + * Escape (and every shortcut) before this field could see it. A blank name commits as a cancel, so the + * tab keeps its old title. + * + * タブ位置に重ねるインライン名前編集。Enter/フォーカス喪失で確定、Escape で取消(シェル経由)。空名は取消扱い。 + * + * @param String initialName The current title, pre-selected for replacement. + * @param Function onCommit Called with the trimmed new name when the edit is confirmed. + * @param Function onCancel Called when the edit is abandoned (Escape or a blank name). + */ +@Composable +private fun WorkspaceTabEditor(initialName: String, onCommit: (String) -> Unit, onCancel: () -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val typography = LocalUmamoTypography.current + Box( + modifier = + Modifier + .padding(horizontal = 2.dp) + .background(colors.headerBackground, shape = shapes.medium) + .padding(horizontal = 10.dp, vertical = 4.dp), + contentAlignment = Alignment.Center, + ) { + InlineRenameField( + initialName = initialName, + textStyle = typography.labelMedium.copy(color = colors.text), + cursorColor = colors.text, + onCommit = onCommit, + onCancel = onCancel, + modifier = Modifier.widthIn(min = 48.dp), + ) + } +} + +/** + * The trailing "+" affordance that creates a new workspace. Styled to match a [Tab] at rest (transparent + * until hovered) so it reads as part of the strip rather than a heavy button; the localized + * [contentDescription] gives it an accessible label since its face is only a glyph. + * + * タブ帯末尾の「+」。新規ワークスペースを作成する。グリフのみのため content description を付ける。 + * + * @param String contentDescription The accessible label (the localized "New Workspace"). + * @param Function onClick Invoked to create a new workspace. + */ +@Composable +private fun NewWorkspaceButton(contentDescription: String, onClick: () -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + // fillMaxHeight (against the strip's IntrinsicSize.Min row) keeps this button exactly as tall as + // the text-metric-sized tabs beside it; no vertical padding, the icon centers in the full height. + // The label doubles as the hover text, matching the kit's icon controls; the wrapper carries the + // fillMaxHeight so the button still measures against the strip row. + Tooltip(text = contentDescription, modifier = Modifier.fillMaxHeight()) { + Box( + modifier = + Modifier + .padding(horizontal = 2.dp) + .fillMaxHeight() + .clip(shapes.medium) + .clickable(interactionSource = interaction, indication = null, onClick = onClick) + .background(if (hovered) colors.rowHover else Color.Transparent, shape = shapes.medium) + .semantics { this.contentDescription = contentDescription } + .padding(horizontal = 3.dp), + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.size(16.dp)) { + drawIcon(LocalUmamoIcons.plus, colors.textMuted) + } + } + } +} + +/** + * The destination index for a drag-reordered tab: the number of other tabs whose center lies left of the + * dragged tab's projected center (its measured center plus the accumulated drag). Because the dragged + * tab is removed before re-insertion, this count is exactly its final index - moving right past one + * neighbor yields the neighbor's old index, moving fully left yields 0. Tabs with an unmeasured center + * (null, only on the first frame) are ignored, and a missing dragged center is a no-op (returns + * [fromIndex]). Pure so the off-by-one-prone index math is unit-tested directly. + * + * ドラッグ並べ替えの着地インデックス。投影中心より左にある他タブの数(=除去後の最終位置)。 + * + * @param Int fromIndex The dragged tab's current index. + * @param Float dragDeltaX The accumulated horizontal drag in pixels. + * @param List centers The per-index measured tab centers (null where not yet measured). + * @return Int The destination index (equal to fromIndex when it should not move). + */ +internal fun reorderTargetIndex(fromIndex: Int, dragDeltaX: Float, centers: List): Int { + val fromCenter = centers.getOrNull(fromIndex) ?: return fromIndex + val projectedCenter = fromCenter + dragDeltaX + var targetIndex = 0 + centers.forEachIndexed { otherIndex, center -> + if (otherIndex != fromIndex && center != null && center < projectedCenter) { + targetIndex++ + } + } + return targetIndex +} + +/** + * Resolves a workspace id to its display title. Built-in ids map to localized strings; any other id + * (a user-created/renamed workspace whose name is user data, not chrome) shows verbatim. + * + * ワークスペース id を表示タイトルに解決する。組み込み id はローカライズ、それ以外はそのまま。 + * + * @param String workspaceId The workspace id. + * @return String The localized or literal title. + */ +@Composable +fun workspaceTitle(workspaceId: String): String = + when (workspaceId) { + "modelling" -> stringResource(Res.string.workspace_modelling) + "texture" -> stringResource(Res.string.workspace_texture) + "physics" -> stringResource(Res.string.workspace_physics) + else -> workspaceId + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/AtlasCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/AtlasCommands.kt new file mode 100644 index 0000000..d1b7d12 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/AtlasCommands.kt @@ -0,0 +1,36 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* + +/** + * The document's atlas commands: operations on the packed texture pages themselves. + * + * The repack handler is a nullable collaborator resolved at DISPATCH time, like every table + * collaborator: the table declares the command, the shell supplies the orchestration closure, and a + * null handler (no document, or a platform without one) makes the dispatch a no-op behind the + * availability gate. The handler receives the area its operation settings strip shows in: the hovered + * work surface, else the last one the pointer touched, else the workspace's first (routing.operationStripArea + * - the repack is document-wide, so it can fire from anywhere, but the strip exists only in a 2D viewport + * or UV editor); null when the workspace has neither, and the strip then shows nowhere. + * + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @param CommandRouting routing The hovered-area resolver, read at dispatch. + * @param Function? repack Launches the repack orchestration over the given area, or null + * when the shell has none to offer. + * @return List The commands to register. + */ +internal fun atlasCommands( + availability: SessionAvailability, + routing: CommandRouting, + repack: ((String?) -> Unit)?, +): List = + listOf( + Command( + "document.repackAtlas", + title = Res.string.cmd_document_repack_atlas, + availability = availability.canRepackAtlas, + ) { + repack?.invoke(routing.operationStripArea()) + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ChromeCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ChromeCommands.kt new file mode 100644 index 0000000..95df80f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ChromeCommands.kt @@ -0,0 +1,66 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.Command +import org.umamo.ui.help.ProjectInfo +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.AreaDragController +import org.umamo.ui.workspace.ShellOverlayState +import org.umamo.ui.workspace.SplitterDragCancelController +import org.umamo.ui.workspace.WorkspaceLayoutController +import org.umamo.ui.workspace.rowdrag.RowDragCancelController + +/** + * The shell-chrome commands: overlay toggles (palette, preferences, Help), the project links, the drag + * cancels, and workspace tab navigation. All are real registry commands so a key binding (or a menu) + * drives them through the one dispatch point - no key handling hardcoded in the shell. + * + * @param ShellOverlayState overlays The overlay flags the toggles flip. + * @param AreaDragController dragController The area CORNER drag state area.dragCancel aborts. + * @param SplitterDragCancelController splitterDragCancel The divider-drag seam area.dragCancel also aborts; + * that drag's session lives in SplitContainer's own state, so it can only be reached through this. + * @param RowDragCancelController rowDragCancel The panel row-drag seam row.dragCancel invokes. + * @param WorkspaceLayoutController workspaces The layout state workspace.prev/next shift. + * @param Function openLink Opens a project URL through the platform's handler. + * @return List The commands to register. + */ +internal fun chromeCommands( + overlays: ShellOverlayState, + dragController: AreaDragController, + splitterDragCancel: SplitterDragCancelController, + rowDragCancel: RowDragCancelController, + workspaces: WorkspaceLayoutController, + openLink: (url: String) -> Unit, +): List = + listOf( + Command("palette.toggle", title = null) { overlays.paletteVisible = !overlays.paletteVisible }, + // Cancels whichever kind of area drag is in flight - the two are separate mechanisms (a corner + // drag splits/joins, a divider drag re-ratios) and only ever one is live, so both are addressed + // here rather than splitting the one Escape-bound command in two. + Command("area.dragCancel", title = null) { + dragController.cancelDrag() + splitterDragCancel.cancel?.invoke() + }, + // The panel row-drag cancel (outliner / parameters rows), dispatched from the shell's Escape + // precedence (mirroring area.dragCancel). + Command("row.dragCancel", title = null) { rowDragCancel.cancel?.invoke() }, + // The preferences window opens through the registry like everything else, so the Edit menu, the + // Ctrl/Cmd+, binding, and the command palette all reach it through the one dispatch point. Titled, + // so it surfaces in the palette ("Settings") for free. + Command("edit.preferences", title = Res.string.cmd_preferences) { overlays.settingsVisible = !overlays.settingsVisible }, + // The Help dialogs open through the registry too, so the Help menu and the palette (both titled, + // so they surface there for free) reach them through the one dispatch point. + Command("help.about", title = Res.string.menu_about) { overlays.aboutVisible = !overlays.aboutVisible }, + Command("help.credits", title = Res.string.menu_credits) { overlays.creditsVisible = !overlays.creditsVisible }, + // Quick Setup opens by itself on a first run; this reopens it (the Help menu and the palette). + Command("help.quickSetup", title = Res.string.menu_quick_setup) { overlays.quickSetupVisible = !overlays.quickSetupVisible }, + // The project links are commands as well, so the Help menu's rows dispatch like every other row and + // the palette finds the documentation by name. The URLs come from ProjectInfo, the same source the + // About dialog shows. + Command("help.sourceCode", title = Res.string.menu_source_code) { openLink(ProjectInfo.SOURCE_CODE_URL) }, + Command("help.webSite", title = Res.string.menu_web_site) { openLink(ProjectInfo.WEB_SITE_URL) }, + Command("help.documentation", title = Res.string.menu_documentation) { openLink(ProjectInfo.DOCUMENTATION_URL) }, + // Workspace navigation: titled so they surface in the palette and resolve a shortcut hint in the tab + // context menu. The tab strip's Previous/Next rows dispatch the same ids, so menu and key share a path. + Command("workspace.prev", title = Res.string.cmd_workspace_prev) { workspaces.switchBy(-1) }, + Command("workspace.next", title = Res.string.cmd_workspace_next) { workspaces.switchBy(1) }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/CommandRegistration.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/CommandRegistration.kt new file mode 100644 index 0000000..a8d5baf --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/CommandRegistration.kt @@ -0,0 +1,78 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.action.CommandRegistry + +/* + * The machinery every command table in this package shares: how a group gets registered, and the + * availability tiers the document-scoped groups all query. + * + * A table is a plain List built by a function that closes over the state its handlers need. + * The shell registers each through registerAll inside a DisposableEffect keyed on exactly that state, + * so a document swap or a renderer change re-registers the groups whose handlers went stale and leaves + * the rest alone. + */ + +/** + * Registers every command in [commands] and returns the matching cleanup, so a DisposableEffect's + * onDispose can never fall out of sync with what was registered. + * + * The hand-mirrored unregister list this replaced rotted the moment a command was added to one list and + * not the other, which fails silently: the command simply outlives its handler's state. + * + * @param List commands The commands to register. + * @return Function The cleanup unregistering exactly those commands. + * @warning Registration is insertion-ordered and re-registering MOVES a group to the tail. Two things + * read that order verbatim: the command palette, for a blank query, and the status bar, which lists + * each tier's hints in it and cuts the list at STATUS_HINT_LIMIT - so the order also decides WHICH + * hint falls off. Harmless today because no group's effect key flips while a document stays open; + * adding an independently-flipping key to one of those effects would make the palette reorder itself, + * and the status bar swap its last suggestion, at runtime. + */ +internal fun CommandRegistry.registerAll(commands: List): () -> Unit { + commands.forEach { command -> register(command) } + return { commands.forEach { command -> unregister(command.id) } } +} + +/** + * The availability tiers the document-scoped command groups share. + * + * One instance per registration pass, so the eleven session groups hold the same four + * [CommandAvailability] objects rather than eleven copies apiece. Each lambda reads live session state + * at query time, so the palette's filter and the keymap's dispatch guard always see the current + * context - the tiers are computed fresh per query, never sampled at registration. + * + * @param EditorSession? session The open document's session, or null when none is open. + */ +internal class SessionAvailability(session: EditorSession?) { + /** Applies whenever a document is open - the tier most session commands sit in. */ + val hasDocument = CommandAvailability { session != null } + + /** Applies only in Edit mode, where there is a mesh-element domain to act on. */ + val inEditMode = CommandAvailability { session?.mode?.value == EditorMode.Edit } + + /** Applies only in Object mode, where whole drawables - and the art placements under them - are the domain. */ + val inObjectMode = CommandAvailability { session?.mode?.value == EditorMode.Object } + + /** Applies only while a Circle-select brush is live, since the radius steps have nothing to resize otherwise. */ + val circleToolLive = CommandAvailability { session?.activeSelectTool?.value is ActiveSelectTool.Circle } + + /** + * Applies when the document's atlas is repackable: it has tiles to pack, and its stored + * coordinates address the pages (a fully layer-addressed document has no page mapping to + * re-derive, and flipping one to page addressing is a bigger change than a repack). A MOC3-origin + * document has no tiles at all, so this also keeps the command off the packed endpoint. + */ + val canRepackAtlas = + CommandAvailability { + val atlas = session?.model?.value?.atlas + atlas != null && atlas.tiles.isNotEmpty() && atlas.storedUvsAddressPages + } + + /** Applies while an operation may still be adjusted - the strip's F9 has something to open. */ + val hasAdjustableOperation = CommandAvailability { session?.adjustableOperation?.value != null } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/CommandRouting.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/CommandRouting.kt new file mode 100644 index 0000000..5675fdb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/CommandRouting.kt @@ -0,0 +1,206 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.ui.workspace.HoveredSurface +import org.umamo.ui.workspace.SpaceKind +import org.umamo.ui.workspace.hostsOperationStrip + +/* + * The ONE place a command asks "which area does the pointer mean". + * + * Blender's hovered-area routing - the key acts where the pointer is - needs the same question answered + * by a dozen commands, and answering it inline gave a dozen slightly different answers. Every rule that + * reads the pointer's surface lives here, so a change to the routing model is a change to this file + * rather than an archaeology exercise across the command tables. + * + * ONE resolver backs it: the hovered surface (area id + space kind), stamped by every workspace leaf, so + * it answers "what is the pointer on" for all nine space kinds. Exactly one, deliberately: a second + * resolver scoped to 2D viewports could only mean "the last viewport touched, however long ago" rather + * than "the one under the pointer", and the two would disagree the moment the pointer moved to another + * space. Every command resolves a surface the user is actually pointing at, or none at all. + * + * A command that needs a viewport and finds none does NOTHING; it does not reach back to a viewport the + * pointer has left. That is Blender's rule and it is the whole point of the seam. + * + * The one read that does reach back is [CommandRouting.operationStripArea], and it routes no action: it + * places the settings strip of a document-wide operation that already ran, and the strip exists only + * in a work surface (2D viewport or UV editor), so a command fired over a panel shows it in the last + * work surface touched - or, when the pointer has touched none since the shell opened, in the first + * work surface of the active workspace. A workspace with no work surface at all yields null, and the + * strip shows nowhere. + * + * Every answer is resolved at DISPATCH time, inside a handler body, never latched at registration - the + * same contract HoveredSurfaceTracker carries. The backing read is a non-reactive var, so a value + * captured during composition goes stale without recomposing. + */ + +/** + * Where a modal transform (Grab / Scale / Rotate) runs: the pointer's UV editor, or its 2D viewport. + * + * A sealed pair rather than a bare area id because the two cases dispatch to different session + * operators over different data - texture coordinates versus geometry - and a `when` over this makes the + * compiler enforce that a caller handled both. + * + * @property String areaId The area the gesture belongs to; only that area's overlay drives it. + */ +internal sealed interface TransformTarget { + val areaId: String + + /** A hovered UV editor: the gesture transforms texture coordinates. */ + data class Uv(override val areaId: String) : TransformTarget + + /** The pointer's 2D viewport: the gesture transforms geometry, in whichever mode is active. */ + data class Viewport(override val areaId: String) : TransformTarget +} + +/** + * A dispatching command's view of where the pointer is. + * + * Holds nothing but its one resolver on purpose. Folding the per-area registries (the camera hub, the + * open keyform sheets) in here would look tidier and would be wrong: their lookups carry fallbacks that + * are correct for some commands and actively harmful for others, and a shared helper cannot express + * that. Commands needing a registry take it directly and pick their own lookup, keyed off an area id + * resolved here. + * + * @param Function hoveredSurface Resolves the last-touched editor surface (area id + space kind). + * @param Function lastTouchedStripHost Resolves the last-touched strip-hosting surface (a 2D viewport or + * UV editor), read only by [operationStripArea]. + * @param Function defaultStripHost Resolves the active workspace's first strip-hosting area in tree + * order, or null when it has none; read only by [operationStripArea], and only when the pointer has + * touched no work surface since the shell opened. + * @param Function lastTouchedViewport Resolves the 2D viewport the pointer last touched, read only by + * [framedViewportArea]. + * @warning Every resolver must read LIVE state, not a value captured when the instance was built - one + * instance serves the whole shell for its lifetime, across document swaps, workspace switches, and + * area-tree edits, so a snapshot would answer with wherever the pointer was at first composition forever. + */ +internal class CommandRouting( + private val hoveredSurface: () -> HoveredSurface?, + private val lastTouchedStripHost: () -> HoveredSurface?, + private val defaultStripHost: () -> String? = { null }, + private val lastTouchedViewport: () -> HoveredSurface? = { null }, +) { + /** + * A routing that remembers no work surface and knows no workspace: the strip placement yields null, + * and the strip shows nowhere. The trailing-lambda form the tables' tests build with, kept as a + * constructor so that lambda stays the hovered resolver rather than silently binding to the last parameter. + * + * @param Function hoveredSurface Resolves the last-touched editor surface. + */ + constructor(hoveredSurface: () -> HoveredSurface?) : this(hoveredSurface, { null }, { null }) + + /** + * Where a document-wide operation's settings strip shows: the hovered area when it is a work surface + * (2D viewport or UV editor), else the last work surface the pointer touched, else the workspace's + * first work surface, else null - which only a workspace with no work surface at all reaches, and + * then the strip shows nowhere. The strip exists only in those two spaces, so a command fired from + * a panel (the Sources header's Add Artwork, the palette over the outliner) still lands it somewhere + * the rigger will find it, including on a freshly opened document whose viewports the pointer has + * not crossed yet. + * + * @return String? The area to show the strip in, or null. + */ + fun operationStripArea(): String? { + val hovered = hoveredSurface() + if (hovered != null && hovered.kind.hostsOperationStrip) { + return hovered.areaId + } + return lastTouchedStripHost()?.areaId ?: defaultStripHost() + } + + /** + * The editor surface the pointer last touched, or null before any was touched. + * + * @return HoveredSurface? The last-touched surface, or null. + */ + fun hovered(): HoveredSurface? = hoveredSurface() + + /** + * Whether the pointer last touched a surface of [kind]. + * + * @param SpaceKind kind The space kind to test for. + * @return Boolean True when the last-touched surface hosts that kind. + */ + fun isHovering(kind: SpaceKind): Boolean = hoveredSurface()?.kind == kind + + /** + * The hovered area's id, but only when that area hosts [kind] - the "is the pointer over one of + * these, and if so which one" question. + * + * @param SpaceKind kind The space kind the caller acts on. + * @return String? The hovered area's id when it hosts [kind], else null. + */ + fun areaOf(kind: SpaceKind): String? = hoveredSurface()?.takeIf { surface -> surface.kind == kind }?.areaId + + /** + * The hovered area's id whatever space it hosts. + * + * @return String? The last-touched area's id, or null before any surface was touched. + * @warning Kind-agnostic BY DESIGN, and narrowing it to one kind is a behavior change disguised as a + * cleanup. Its callers put the id into a session request payload whose collectors gate on their + * own area id, so an id naming the "wrong" kind of surface simply matches no collector and the + * request no-ops - while Select Linked genuinely executes in a viewport AND in a UV editor. + */ + fun hoveredAreaIdAnyKind(): String? = hoveredSurface()?.areaId + + /** + * The 2D viewport under the pointer, or null when the pointer is on anything else. + * + * @return String? The hovered viewport's area id, or null. + * @note There is deliberately no "last viewport touched" fallback. A command that needs a viewport and + * gets null here must do nothing - acting in a viewport the pointer has left is precisely the failure + * a single hovered-surface resolver exists to rule out. + */ + fun viewportArea(): String? = areaOf(SpaceKind.Viewport2D) + + /** + * The 2D viewport whose framing a capture reads: the hovered one, else the last one the pointer touched. + * + * @return String? The viewport's area id, or null when no viewport has been touched. + * @note The fallback [viewportArea] rules out is right here, because nothing ACTS in this viewport: the + * caller only reads what it shows. And it is needed, since Export Image is reached through the File + * menu, and the way there crosses another area in every default workspace. + */ + fun framedViewportArea(): String? = viewportArea() ?: lastTouchedViewport()?.areaId + + /** + * Where a modal Grab / Scale / Rotate runs. + * + * @return TransformTarget? The hovered surface when it can host a transform, else null - the pointer is + * on a panel, or on nothing, and there is nowhere to run the gesture. + * @warning Neither branch falls back to the other. A hovered UV editor resolves to [TransformTarget.Uv] + * even outside Edit mode (the session refuses it there), and a hovered panel resolves to nothing at + * all; either fallback would start a gesture in an area the pointer is not over, which is precisely + * the bug hovered-area routing exists to prevent. + */ + fun transformTarget(): TransformTarget? { + val hovered = hoveredSurface() ?: return null + return when (hovered.kind) { + SpaceKind.UvEditor -> TransformTarget.Uv(hovered.areaId) + SpaceKind.Viewport2D -> TransformTarget.Viewport(hovered.areaId) + else -> null + } + } + + /** + * Where a Box / Circle select tool arms: the hovered 2D viewport, or the hovered UV editor in Edit mode. + * Anything else - a panel, a UV editor in Object mode, nothing at all - arms nowhere. + * + * @param EditorSession? session The active session, or null when no document is open. + * @return String? The arming area's id, or null when no surface can host the tool. + * @note The Edit-mode gate on the UV branch is load-bearing, unlike [transformTarget]'s missing one: + * EditorSession.beginBoxSelect / beginCircleSelect are mode-agnostic and arm unconditionally in + * Object mode, while the UV editor's overlay only composes in Edit mode. Arming there in Object + * mode would latch a tool nothing can drive or cancel by pointer. Read the session's mode HERE, + * inside the resolver, so it is sampled at dispatch. + */ + fun selectToolArea(session: EditorSession?): String? { + val hovered = hoveredSurface() ?: return null + return when (hovered.kind) { + SpaceKind.Viewport2D -> hovered.areaId + SpaceKind.UvEditor -> hovered.areaId.takeIf { session?.mode?.value == EditorMode.Edit } + else -> null + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/DisplayCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/DisplayCommands.kt new file mode 100644 index 0000000..160e195 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/DisplayCommands.kt @@ -0,0 +1,34 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorSession +import org.umamo.edit.setSourceLayerDisplay +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* + +/** + * The document's display commands: how the puppet is shown, as opposed to what it is. + * + * Document content rather than app chrome - the source formats author it, so it is one undo step and + * it round-trips - which is why these edit the session rather than writing settings the way the + * toolbar / sidebar toggles do. + * + * The toggle records authored INTENT and is available whenever a document is open, even one whose + * artwork the renderer cannot display from. Honoring it is best-effort per drawable, and intent that + * cannot be honored today still round-trips and still applies once the artwork is there. + * + * @param EditorSession? editorSession The open document's session, or null (the command then no-ops). + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun displayCommands(editorSession: EditorSession?, availability: SessionAvailability): List = + listOf( + Command( + "document.toggleSourceArtworkDisplay", + title = Res.string.cmd_document_toggle_source_artwork, + availability = availability.hasDocument, + ) { + editorSession?.let { session -> + session.setSourceLayerDisplay(!session.model.value.rendersFromSourceLayers) + } + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/DocumentCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/DocumentCommands.kt new file mode 100644 index 0000000..6e16954 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/DocumentCommands.kt @@ -0,0 +1,106 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.interop.ExportReport +import org.umamo.ui.action.Command +import org.umamo.ui.document.DocumentOpenFailure +import org.umamo.ui.model.AtlasRepackReport +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.AlertRequest +import org.umamo.ui.workspace.ConfirmAlternative +import org.umamo.ui.workspace.ConfirmRequest +import org.umamo.ui.workspace.ExportOptionsRequest +import org.umamo.ui.workspace.ShellOverlayState + +/** + * What a dirty document's replace and quit prompts can do: discard the unsaved edits and go on, or save + * them and go on once the save has landed. + * + * @property Function discard Goes on without saving. + * @property Function? save Saves, then goes on when the save succeeds; null when the document cannot be + * saved (it opened read-only), which leaves the prompt with the discard alone. + */ +class DirtyDocumentPrompt( + val discard: () -> Unit, + val save: (() -> Unit)?, +) + +/** + * The confirm a dirty document's prompt raises: Save (the default) / Don't Save / Cancel when a save is + * possible, else the plain discard-or-cancel pair, worded for a replace or for quitting. + * + * @param DirtyDocumentPrompt prompt The actions. + * @param Boolean quitting True for the quit guard's wording, false for a document replace. + * @return ConfirmRequest The request. + */ +private fun dirtyDocumentRequest(prompt: DirtyDocumentPrompt, quitting: Boolean): ConfirmRequest { + val save = prompt.save + return if (save != null) { + ConfirmRequest( + message = if (quitting) Res.string.confirm_save_before_quit else Res.string.confirm_save_before_replace, + confirmLabel = Res.string.dialog_save, + alternative = ConfirmAlternative(Res.string.dialog_dont_save) { prompt.discard() }, + onConfirm = save, + ) + } else { + ConfirmRequest( + message = if (quitting) Res.string.confirm_quit_unsaved else Res.string.confirm_discard_unsaved, + confirmLabel = if (quitting) Res.string.dialog_quit_without_saving else Res.string.dialog_discard, + onConfirm = prompt.discard, + ) + } +} + +/** + * The document-report commands the app's document layer dispatches into. + * + * The reporting lives here rather than in the app because the shell owns the modal chrome: routing a + * failure or a confirm through a command means Escape, Enter, the scrim, and focus reclamation behave + * exactly as they do for every other overlay, instead of each alert re-implementing them. All of them + * are argument-only and untitled, so they never surface in the palette - there is nothing to invoke + * without a payload. + * + * @param ShellOverlayState overlays The overlay state the confirms and the alerts go through. + * @return List The commands to register. + */ +internal fun documentCommands(overlays: ShellOverlayState): List = + listOf( + Command("document.openFailed", title = null) { argument -> + (argument as? DocumentOpenFailure)?.let { failure -> overlays.openFailure = failure } + }, + // The document layer asks before replacing a dirty document (an open or an import discards its + // unsaved edits); the shell owns the confirm dialog so Escape/Enter route like every other overlay. + // Save is the default when the document can be saved, with Don't Save as the third choice. + Command("document.confirmReplace", title = null) { argument -> + (argument as? DirtyDocumentPrompt)?.let { prompt -> overlays.pendingConfirm = dirtyDocumentRequest(prompt, quitting = false) } + }, + // The app asks before quitting over a dirty document - from File > Exit, the window's close button, the + // OS's quit, or Android's back gesture - with the same Save / Don't Save / Cancel shape. + Command("document.confirmExit", title = null) { argument -> + (argument as? DirtyDocumentPrompt)?.let { prompt -> overlays.pendingConfirm = dirtyDocumentRequest(prompt, quitting = true) } + }, + // A CMO3 or MOC3 export finished with advisory notices; the shell shows them in a modal alert. + Command("document.exportReport", title = null) { argument -> + (argument as? ExportReport)?.let { report -> overlays.exportReport = report } + }, + // A repack refused; the shell shows which tiles kept it from running. Modal like the export + // report - a tile the pack cannot carry must not be a four-second toast. + Command("document.repackReport", title = null) { argument -> + (argument as? AtlasRepackReport)?.let { report -> overlays.repackReport = report } + }, + // An export with options is starting; the shell shows the options dialog and the request's + // continuation carries the export on from whatever the rigger confirms. One command for every + // format: the dialog picks its pane by the request's type. + Command("document.exportOptions", title = null) { argument -> + (argument as? ExportOptionsRequest)?.let { request -> overlays.pendingExportOptions = request } + }, + // A ready-built confirm from the app layer (the export-overwrite warning). Unlike + // document.confirmReplace, whose prompt is fixed here, the caller owns the prompt and its + // arguments - the command only routes it into the shell's one pending-confirm slot. + Command("document.confirm", title = null) { argument -> + (argument as? ConfirmRequest)?.let { request -> overlays.pendingConfirm = request } + }, + // A ready-built message from the app layer with nothing to decide - a read-only open, a failed save. + Command("document.alert", title = null) { argument -> + (argument as? AlertRequest)?.let { request -> overlays.pendingAlert = request } + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/FileCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/FileCommands.kt new file mode 100644 index 0000000..4a88ca8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/FileCommands.kt @@ -0,0 +1,319 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.resources.* + +/* + * The document import / export commands. + * + * These are the one group the app registers rather than the shell, because their work needs the document + * loader and the CMO3 codec, which sit above the shell (and, for the codec, off commonMain entirely). The + * file picker alone is no reason: the workspace layout's file commands and the log export need one too, + * and the shell registers those, since nothing about them is a document. Only the TABLE lives here: each + * builder takes the action as a plain lambda, + * so the ids, titles, and availability tiers sit with every other command table while the app keeps the + * document logic. Registering them here instead would drag the whole document layer into the shell's + * package and invert the dependency. The artwork table ([fileArtworkCommands]) is the exception: the + * shell registers it (with the app's closures injected) because its operation strip needs the hovered + * area at dispatch. + * + * Open / Save mean the native UMA document and nothing else; CMO3 and MOC3 are interop boundaries, so they + * come and go through Import / Export. + */ + +/** + * The commands that make, open, save, or replace the whole document - New, Open, Save, Save As, one import + * per interop format, and a file opened by its path - and the one that ends the session altogether, Exit. + * What they share is the unsaved-changes gate: each would discard the editing session. + * + * Split from [fileExportCommands] because the two register on different triggers: these handlers read + * the document live through the app's holders, while export closes over the open document. The artwork + * import is NOT here - it adds to the open document rather than replacing it, so it registers with the + * other artwork operations ([fileArtworkCommands]). + * + * @param Function onNew Starts a new, empty document (dirty-confirm first). + * @param Function onOpen Opens a `.uma` (picker, dirty-confirm, load). + * @param Function onSave Saves to the document's `.uma`, asking where on the first save. + * @param Function onSaveAs Asks where to save. + * @param Function canSave Whether the open document can be saved, queried live (gates Save and Save As). + * @param Function onImportCmo3 Runs the CMO3 import (picker, dirty-confirm, load). + * @param Function onImportMoc3 Runs the MOC3 import. + * @param Function onOpenPath Opens the file at a stored path or uri, by what the file is (dirty-confirm, load). + * @param Function onExit Closes the application (dirty-confirm first). + * @return List The commands to register. + */ +internal fun fileCommands( + onNew: () -> Unit, + onOpen: () -> Unit, + onSave: () -> Unit, + onSaveAs: () -> Unit, + canSave: () -> Boolean, + onImportCmo3: () -> Unit, + onImportMoc3: () -> Unit, + onOpenPath: (path: String) -> Unit, + onExit: () -> Unit, +): List = + listOf( + Command("file.new", title = Res.string.cmd_file_new) { onNew() }, + Command("file.open", title = Res.string.cmd_file_open) { onOpen() }, + Command("file.save", title = Res.string.cmd_file_save, availability = CommandAvailability { canSave() }) { onSave() }, + Command("file.saveAs", title = Res.string.cmd_file_save_as, availability = CommandAvailability { canSave() }) { onSaveAs() }, + Command("file.importCmo3", title = Res.string.cmd_import_cmo3) { onImportCmo3() }, + // MOC3 comes in through its own row rather than one merged "import" filter, keeping the + // source-project / baked-runtime distinction visible in the UI. + Command("file.importMoc3", title = Res.string.cmd_import_moc3) { onImportMoc3() }, + // No title, like the other argument-only commands: the Open Recent rows supply the path, and the + // palette has nothing to offer without one. Anything that opens a file it was handed belongs on this + // id, since the way in is what carries the unsaved-changes gate. + Command("file.openPath", title = null) { argument -> + val path = argument as? String ?: return@Command + onOpenPath(path) + }, + // No default chord: the platform's own quit gesture (the window's close button, Cmd+Q, Android's back) + // reaches the same gate through the host's exit guard, and a chord is one rebind away. + Command("file.exit", title = Res.string.menu_exit) { onExit() }, + ) + +/** + * A request to rebind one or more tiles to one layer, the payload of the sources.relink command: one + * tile from the tile chip or a drop, every tile bound to a lost key from a review row, so those land + * as one step. + * + * @property List tileIds The tiles. + * @property SourceLayerRef? ref The binding they take, or null to unbind. + * @property List retire The tiles bound to the target layer that go with the move, as the + * accepted proposal named them (a fresh drawable a reload minted for the layer); empty otherwise. + */ +class RelinkRequest( + val tileIds: List, + val ref: SourceLayerRef?, + val retire: List = emptyList(), +) { + /** + * The one-tile form. + * + * @param AtlasTileId tileId The tile. + * @param SourceLayerRef? ref The binding it takes, or null to unbind. + */ + constructor(tileId: AtlasTileId, ref: SourceLayerRef?) : this(listOf(tileId), ref) +} + +/** + * A request to add named artwork files to the open document, the optional payload of the + * file.importArtwork command: the files a drop handed over, in the order they were dropped. Invoked + * without one, the command asks for a file instead. + * + * @property List paths The artwork files' stored paths. + */ +class ImportArtworkRequest( + val paths: List, +) + +/** + * A request to remove one piece of source art from the atlas, the payload of the sources.deleteArt + * command: a tile no drawable samples, which otherwise lingers on a page and in the Sources table. + * + * @property AtlasTileId tileId The tile to remove. + */ +class DeleteArtRequest( + val tileId: AtlasTileId, +) + +/** + * A request to repoint one artwork record at another file, the payload of the sources.replaceArtwork + * command; the app picks the file. + * + * @property ArtSourceId sourceId The record to repoint. + */ +class ReplaceRequest( + val sourceId: ArtSourceId, +) + +/** + * A request to mark or clear the ignore on one layer of a listed artwork file, the payload of the + * sources.ignoreLayer command: while marked, a reload leaves the layer out of the rig. + * + * @property SourceLayerRef ref The file and layer key. + * @property Boolean ignored True to mark, false to clear. + */ +class IgnoreLayerRequest( + val ref: SourceLayerRef, + val ignored: Boolean, +) + +/** + * Which listed files a reload covers, the optional payload of the document.reloadArtwork command: the + * watcher names the files that changed, so the rest are not re-read; a press of Reload passes none + * and covers every present file. + * + * @property Set sourceIds The files to re-read. + */ +class ReloadScope( + val sourceIds: Set, +) + +/** + * The app's artwork orchestrations the shell's table dispatches to: each reads files the way only the + * app can (the picker, a path on the platform's file system) and lands the result on the session. + * Every one takes the area its operation strip shows in, resolved by the shell at dispatch. + * + * @property Function importArtwork Adds the named artwork files to the open document, or picks one when + * handed no request. + * @property Function reloadArtwork Re-reads the listed files that are present - those the scope names, + * or every one when it is null - and reloads the document from them. + * @property Function relinkArtwork Rebinds a tile, pulling the layer's art in when its file can be read. + * @property Function matchArtwork Reads every file it can and rebinds the unresolved bindings the matcher is confident about. + * @property Function replaceArtwork Picks a file and repoints the named record at it. + * @property Function deleteArt Removes a tile no drawable samples from the atlas (and, under the import + * setting, marks its layer ignored with it). + * @property Function ignoreLayer Marks or clears the ignore on one layer, so a reload leaves it out or mints it again. + * @property Function canReload Whether any listed file could be re-read, queried live. + */ +class ArtworkOperations( + val importArtwork: (request: ImportArtworkRequest?, areaId: String?) -> Unit, + val reloadArtwork: (areaId: String?, scope: ReloadScope?) -> Unit, + val relinkArtwork: (request: RelinkRequest, areaId: String?) -> Unit, + val matchArtwork: (areaId: String?) -> Unit, + val replaceArtwork: (request: ReplaceRequest, areaId: String?) -> Unit, + val deleteArt: (request: DeleteArtRequest) -> Unit, + val ignoreLayer: (request: IgnoreLayerRequest) -> Unit, + val canReload: () -> Boolean, +) + +/** + * The artwork commands over the OPEN document: Import Artwork (a file's layers join the document), Reload + * (every present file is re-read and the changed layers land), the Sources space's relink (a tile + * rebound, with the layer's art pulled in), Match Automatically (the bindings the files no longer + * resolve rebound to their confident matches), Replace Artwork (one record repointed at another file), + * and the Sources row's Delete Art and ignore toggle. Each is an undoable edit; the file-reading ones + * land on the operation settings strip. + * + * Unlike the other file commands these are registered by the SHELL, not the app, with the app's + * file-reading closures injected as a collaborator: the strip's area (the hovered work surface, else + * the last one the pointer touched - the Sources header is the usual origin, and a panel hosts no + * strip) is a question only the shell's routing can answer. An app-registered handler would have no + * area to give and the strip would show nowhere. The collaborator is read at dispatch, so the table + * survives a document swap without re-registration, and a null one (no puppet document) hides the + * commands. + * + * @param CommandRouting routing The hovered-area resolver, read at dispatch. + * @param Function artwork Supplies the current orchestrations, or null when no document can take artwork. + * @return List The commands to register. + */ +internal fun fileArtworkCommands(routing: CommandRouting, artwork: () -> ArtworkOperations?): List = + listOf( + // The one way artwork enters a document, from the File menu's Import row, the Sources space, and a + // drop on the window alike: a file's layers are ADDED to the open document as one undoable edit, the + // way importing an object into a Blender scene adds to it rather than replacing the scene. With no + // payload it asks for a file; with one it takes the files it was handed, which is how a drop arrives on + // the same id - and so under the same availability gate and the same operation strip. + Command( + "file.importArtwork", + title = Res.string.cmd_import_artwork, + availability = CommandAvailability { artwork() != null }, + ) { argument -> artwork()?.importArtwork?.invoke(argument as? ImportArtworkRequest, routing.operationStripArea()) }, + Command( + "document.reloadArtwork", + title = Res.string.cmd_document_reload_artwork, + availability = CommandAvailability { artwork()?.canReload?.invoke() == true }, + ) { argument -> artwork()?.reloadArtwork?.invoke(routing.operationStripArea(), argument as? ReloadScope) }, + Command( + "sources.relink", + title = Res.string.cmd_sources_relink, + availability = CommandAvailability { artwork() != null }, + ) { argument -> + val request = argument as? RelinkRequest ?: return@Command + artwork()?.relinkArtwork?.invoke(request, routing.operationStripArea()) + }, + Command( + "sources.matchAutomatically", + title = Res.string.cmd_sources_match_automatically, + availability = CommandAvailability { artwork() != null }, + ) { artwork()?.matchArtwork?.invoke(routing.operationStripArea()) }, + Command( + "sources.replaceArtwork", + title = Res.string.cmd_sources_replace_artwork, + availability = CommandAvailability { artwork() != null }, + ) { argument -> + val request = argument as? ReplaceRequest ?: return@Command + artwork()?.replaceArtwork?.invoke(request, routing.operationStripArea()) + }, + Command( + "sources.deleteArt", + title = Res.string.cmd_sources_delete_art, + availability = CommandAvailability { artwork() != null }, + ) { argument -> + val request = argument as? DeleteArtRequest ?: return@Command + artwork()?.deleteArt?.invoke(request) + }, + // No title, like the other argument-only commands: a row supplies the layer, and the palette has + // nothing to offer without one. + Command( + "sources.ignoreLayer", + title = null, + availability = CommandAvailability { artwork() != null }, + ) { argument -> + val request = argument as? IgnoreLayerRequest ?: return@Command + artwork()?.ignoreLayer?.invoke(request) + }, + ) + +/** + * Export Image: a capture of the posed puppet, straight from the viewport renderer, saved as a PNG. + * + * Registered by the SHELL for the same reason the artwork commands are: the capture can frame exactly what a + * 2D viewport shows, and which viewport the rigger means is a question only the shell's routing answers - the + * hovered one, else the last 2D viewport the pointer touched, and none at all before any was (the dialog then + * offers only the regions that need no viewport). The collaborator is read at dispatch, and + * a null one - no puppet document, or no puppet renderer on this platform - hides the command. + * + * @param CommandRouting routing The hovered-area resolver, read at dispatch. + * @param Function exportImage Supplies the export, handed the 2D viewport area to frame (or null), or + * null when nothing can be captured. + * @return List The commands to register. + */ +internal fun fileImageExportCommands(routing: CommandRouting, exportImage: () -> ((viewportAreaId: String?) -> Unit)?): List = + listOf( + Command( + "file.exportImage", + title = Res.string.cmd_export_image, + availability = CommandAvailability { exportImage() != null }, + ) { exportImage()?.invoke(routing.framedViewportArea()) }, + ) + +/** + * The export commands, one per target format, available only while a puppet document is open. + * + * Neither carries a default chord. With two formats there is no honest meaning for one "export" + * accelerator, and the pair is one keystroke away in the palette and one row apart in the File menu - + * a shortcut that silently favours whichever format was implemented first is worse than none. + * + * @param Function canExport Whether the open document can be exported, queried live. + * @param Function onExportCmo3 Runs the CMO3 export (picker, reconcile, write, report). + * @param Function onExportMoc3 Runs the MOC3 export (picker, lower, write the family, report). + * @return List The commands to register. + * @note Registered in its own effect keyed on the document AND the session, so the handler always closes + * over the pair the export reconciles from - a mismatched pair would write one model's rig onto + * another's atlas pages. + */ +internal fun fileExportCommands( + canExport: () -> Boolean, + onExportCmo3: () -> Unit, + onExportMoc3: () -> Unit, +): List = + listOf( + Command( + "file.exportCmo3", + title = Res.string.cmd_export_cmo3, + availability = CommandAvailability { canExport() }, + ) { onExportCmo3() }, + Command( + "file.exportMoc3", + title = Res.string.cmd_export_moc3, + availability = CommandAvailability { canExport() }, + ) { onExportMoc3() }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/HistoryCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/HistoryCommands.kt new file mode 100644 index 0000000..9183415 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/HistoryCommands.kt @@ -0,0 +1,32 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorSession +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.OperationStripState + +/** + * The undo-history commands. All three walk the session's snapshot stack or its adjustable record, + * which is why they need no routing: history is per document, not per area, so where the pointer + * is has no bearing on what they undo. + * + * Adjust Last Operation (Blender's F9) toggles the operation settings strip open: the strip already + * sits where the last operation ran, so opening it is all the command has to do. + * + * @param EditorSession? editorSession The open document's session, or null (the commands then no-op). + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @param OperationStripState operationStrip The window's strip state the adjust command opens. + * @return List The commands to register. + */ +internal fun historyCommands( + editorSession: EditorSession?, + availability: SessionAvailability, + operationStrip: OperationStripState, +): List = + listOf( + Command("edit.undo", title = Res.string.cmd_undo, availability = availability.hasDocument) { editorSession?.undo() }, + Command("edit.redo", title = Res.string.cmd_redo, availability = availability.hasDocument) { editorSession?.redo() }, + Command("edit.adjustLastOperation", title = Res.string.cmd_adjust_last_operation, availability = availability.hasAdjustableOperation) { + operationStrip.expanded = !operationStrip.expanded + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/KeyformCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/KeyformCommands.kt new file mode 100644 index 0000000..91a6f2e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/KeyformCommands.kt @@ -0,0 +1,165 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorSession +import org.umamo.edit.NoticePlacement +import org.umamo.edit.SelectionTarget +import org.umamo.edit.captureKeyOnTrack +import org.umamo.edit.removeKeyOnTrack +import org.umamo.edit.removeTrackKeys +import org.umamo.edit.removingKeys +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandHint +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.model.KeyformHover +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.KeyformSheetViews +import org.umamo.ui.workspace.SpaceKind + +/* + * The keyform-authoring command table: insert / delete on the hovered keyable property, and the keyform + * sheet's own selection and view operations. + * + * What is here is POINTER bookkeeping, not authoring rules. A command resolves what the pointer is over, + * refuses when that is nothing, and hands the plain description of it - track, parameter, aim - to the + * matching op in :edit (KeyformAimEdits.kt), which owns every decision about what the edit means. Deciding + * here instead would put authoring rules where only a running composition could exercise them, and would + * let the sheet, a panel row, and a lane menu drift into meaning different things by the same gesture. + * + * Every target resolves at DISPATCH time (the hovered keyable, the hovered sheet), never latched at + * registration - the same rule the viewport commands follow, and what lets `I` work with no prior + * selection: point at Opacity and press it. + */ + +/** + * The keyform-authoring commands: insert / delete a key on the hovered keyable, and the keyform sheet's + * delete-selected / nudge / frame-all. + * + * The sheet commands are registered ONCE here rather than per sheet area: CommandRegistry is + * last-write-wins per id, so per-area registration made two open sheets clobber each other's handlers and + * closing either area unregistered the shared ids out from under the survivor. The acting sheet resolves + * through [keyformSheets] at dispatch time - the hovered sheet, else the only open one, else (for the + * selection ops) the unique one with keys selected. + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param Function hoveredKeyable Resolves the hovered keyable property (a sheet lane or a Properties row) + * at dispatch time; null when the pointer is over nothing keyable. + * @param CommandRouting routing Resolves which area the pointer means, naming the acting sheet when the + * last-touched surface is one. + * @param KeyformSheetViews keyformSheets The shell's open-sheet registry the sheet commands act through. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun keyformCommands( + editorSession: EditorSession?, + hoveredKeyable: () -> KeyformHover?, + routing: CommandRouting, + keyformSheets: KeyformSheetViews, + availability: SessionAvailability, +): List { + /** + * The last-touched keyform-sheet area, or null when the pointer's surface is not a sheet. Both sheet + * lookups below take this rather than an unconditional area id, so a pointer parked over a viewport + * reads as "no sheet named" and leaves their own fallbacks to decide. + * + * @return String? The hovered sheet's area id, or null. + */ + fun hoveredSheetArea(): String? = routing.areaOf(SpaceKind.KeyformSheet) + return listOf( + Command( + "keyform.insert", + title = Res.string.cmd_keyform_insert, + availability = availability.hasDocument, + spaces = CommandSpaces.KeyableSurfaces, + hint = CommandHint(Res.string.status_bind_insert_key), + ) { + editorSession?.let { session -> + aimedKeyable(session, hoveredKeyable() ?: geometryHoverFromSelection(session))?.let { hover -> + // The hovered row goes with it, so the insert shifts the sheet's key selection past the key + // it adds instead of handing that key the selected mark's ordinal. + session.captureKeyOnTrack(hover.track, hover.parameterId, hover.aim, hover.rowKey) + } + } + }, + Command( + "keyform.delete", + title = Res.string.cmd_keyform_delete, + availability = availability.hasDocument, + spaces = CommandSpaces.KeyableSurfaces, + hint = CommandHint(Res.string.status_bind_delete_key), + ) { + editorSession?.let { session -> + aimedKeyable(session, hoveredKeyable() ?: geometryHoverFromSelection(session))?.let { hover -> + // The hovered row goes with it, so the removal re-points the sheet's key selection at what + // survives instead of leaving it on the ordinal the removal frees - the neighbouring key. + session.removeKeyOnTrack(hover.track, hover.parameterId, hover.aim, hover.rowKey) + } + } + }, + Command("keyform.deleteSelectedKeys", title = Res.string.cmd_keyform_delete_keys, availability = availability.hasDocument) { + val sheet = keyformSheets.resolveForSelection(hoveredSheetArea()) + val removals = sheet?.selectedTracks().orEmpty() + if (editorSession != null && sheet != null && removals.isNotEmpty()) { + // Everything selected is what is going, so the reconciliation lands on an empty selection - + // through the same helper as every other removal, which folds the selection update into the + // removal's own undo step rather than recording it as a separate one. + editorSession.removingKeys(editorSession.keySelection.value) { + editorSession.removeTrackKeys(removals) + } + } + }, + Command("keyform.nudgeKeyLeft", title = Res.string.cmd_keyform_nudge_left, availability = availability.hasDocument) { + keyformSheets.resolveForSelection(hoveredSheetArea())?.nudgeSelection(-KEYFORM_NUDGE_FRACTION) + }, + Command("keyform.nudgeKeyRight", title = Res.string.cmd_keyform_nudge_right, availability = availability.hasDocument) { + keyformSheets.resolveForSelection(hoveredSheetArea())?.nudgeSelection(KEYFORM_NUDGE_FRACTION) + }, + Command("keyform.frameAll", title = Res.string.cmd_keyform_frame_all, availability = availability.hasDocument) { + keyformSheets.resolve(hoveredSheetArea())?.frameAll?.invoke() + }, + ) +} + +/** + * The keyable an authoring command acts on, or null after refusing with a notice. + * + * Refusing here rather than in :edit because "the pointer is over nothing" is a fact about the pointer, not + * about the rig - the authoring ops take a track and so can never be in this state. + * + * @param EditorSession session The session that shows the notice. + * @param KeyformHover? hover What the pointer is over, or null. + * @return KeyformHover? The hover to act on, or null when there is none. + */ +private fun aimedKeyable(session: EditorSession, hover: KeyformHover?): KeyformHover? { + if (hover == null) { + session.emitNotice("notice.keyform.noTarget", NoticePlacement.NearCursor) + } + return hover +} + +/** + * When the pointer is not over a keyable row, fall back to the active selection's geometry track so + * selecting a warp / rotation / drawable, targeting any parameter, and pressing `I` still binds it. + * + * @param EditorSession session The open document. + * @return KeyformHover? A pose-aimed geometry hover, or null when the selection has no geometry owner. + */ +private fun geometryHoverFromSelection(session: EditorSession): KeyformHover? { + val owner = + when (val target = session.selection.value.active) { + is SelectionTarget.Deformer -> KeyformOwner.Deformer(target.id) + is SelectionTarget.Drawable -> KeyformOwner.Drawable(target.id) + else -> return null + } + return KeyformHover(KeyformTrackRef.Geometry(owner)) +} + +/** + * How far one arrow-key press moves a sheet key, as a fraction of its parameter's range. + * + * Relative rather than absolute because ranges differ by orders of magnitude across a rig - an angle + * spans 60, an open/close spans 1 - so one absolute step would be invisible on the first and wild on the + * second. A hundredth puts a full sweep at a hundred presses, which reads as fine adjustment. + */ +private const val KEYFORM_NUDGE_FRACTION = 0.01f \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/LogCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/LogCommands.kt new file mode 100644 index 0000000..e696d09 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/LogCommands.kt @@ -0,0 +1,18 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* + +/** + * The diagnostic-log commands. + * + * Registered by the settings-backed shell, beside the workspace layout's file commands: the log exists + * from startup whatever document is open, so the export is live from launch. The Logs panel's Export + * button dispatches the id instead of holding a handler, so the panel needs no picker of its own - and the + * command palette reaches the same operation for free. + * + * @param Function onExportLog Writes the retained log buffer to a picked file. + * @return List The commands to register. + */ +internal fun logCommands(onExportLog: () -> Unit): List = + listOf(Command("logs.export", title = Res.string.logs_export) { onExportLog() }) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ModeCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ModeCommands.kt new file mode 100644 index 0000000..c069bd1 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ModeCommands.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.SelectionOps +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.action.CommandHint +import org.umamo.ui.model.EditorModeHandle +import org.umamo.ui.model.SelectionHandle +import org.umamo.ui.resources.* + +/** + * The selection-clear and editor-mode commands. Escape-to-clear is handled in the modal key ladder + * (so it yields to an in-flight drag's area.dragCancel), not bound here; mode.toggleEdit is bound to + * Tab in the default and Blender presets (the Cubism preset leaves it unbound). + * + * Its own table rather than part of the session groups because it closes over the shell's selection and + * mode handles instead of the session itself, so it re-registers on a different trigger. + * + * @param SelectionHandle? selection The selection handle, or null with no document. + * @param EditorModeHandle? editorMode The mode handle, or null with no document. + * @return List The commands to register. + */ +internal fun modeCommands(selection: SelectionHandle?, editorMode: EditorModeHandle?): List { + // Selection and mode commands need an open document (its selection / mode holders exist). + val hasSelection = CommandAvailability { selection != null } + val hasMode = CommandAvailability { editorMode != null } + // The toggle runs from either mode, and is suggested only on the way IN: the label reads "Edit Mode", + // which from inside Edit mode names where the user already is. + val inObjectMode = CommandAvailability { editorMode?.mode == EditorMode.Object } + return listOf( + Command("select.clear", title = Res.string.cmd_select_clear, availability = hasSelection) { selection?.set(SelectionOps.clear()) }, + Command( + "mode.toggleEdit", + title = Res.string.cmd_mode_toggle_edit, + availability = hasMode, + hint = CommandHint(Res.string.status_bind_edit_mode, suggestedWhen = inObjectMode), + ) { + editorMode?.let { it.set(if (it.mode == EditorMode.Object) EditorMode.Edit else EditorMode.Object) } + }, + // Explicit set-mode commands for the viewport header's mode dropdown (and the palette). setMode + // no-ops when already in the requested mode, so re-selecting the current row records no undo step. + Command("mode.object", title = Res.string.cmd_mode_object, availability = hasMode) { editorMode?.set(EditorMode.Object) }, + Command("mode.edit", title = Res.string.cmd_mode_edit, availability = hasMode) { editorMode?.set(EditorMode.Edit) }, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ObjectCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ObjectCommands.kt new file mode 100644 index 0000000..74bff28 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ObjectCommands.kt @@ -0,0 +1,81 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.DrawableChange +import org.umamo.edit.EditorSession +import org.umamo.edit.PartChange +import org.umamo.edit.Selection +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.edit.createWarpDeformerForSelection +import org.umamo.edit.visibilityOf +import org.umamo.edit.withSelectionVisibility +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandHint +import org.umamo.ui.model.SelectionHandle +import org.umamo.ui.resources.* + +/** + * The commands acting on the object selection itself: the visibility toggle, the outliner's + * select-hierarchy, and create-warp (wrap selected meshes in a new armature warp). All work off the + * selection rather than the pointer, so they need no routing - a selection is already a statement about + * what is meant, wherever the pointer happens to sit. + * + * @param EditorSession? editorSession The open document's session, or null (commands then no-op). + * @param SelectionHandle? selection The object-selection handle, or null with no document. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun objectCommands( + editorSession: EditorSession?, + selection: SelectionHandle?, + availability: SessionAvailability, +): List = + listOf( + // The first real model mutation: flips the selected parts'/drawables' eyeball as one undo step. + // Suggested in Object mode alone: in Edit mode the key hides the very drawable being edited, which + // runs but is not worth advertising beside the mesh tools. + Command( + "object.toggleVisibility", + title = Res.string.cmd_toggle_visibility, + availability = availability.hasDocument, + hint = CommandHint(Res.string.status_bind_visibility, suggestedWhen = availability.inObjectMode), + ) { + val current = selection?.selection + val active = current?.active + if (editorSession != null && active != null && !current.isEmpty) { + // Flip relative to the active target's current state, applied to the whole selection, so a + // mixed selection toggles consistently rather than each entity independently. + val newVisible = !editorSession.model.value.visibilityOf(active) + val change = + when (active) { + is SelectionTarget.Part -> PartChange.SetVisibility(active.id, newVisible) + is SelectionTarget.Drawable -> DrawableChange.SetVisibility(active.id, newVisible) + // A deformer has no visibility flag; nothing to toggle. + is SelectionTarget.Deformer -> null + } + if (change != null) { + editorSession.mutate(change) { model -> model.withSelectionVisibility(current.targets, newVisible) } + } + } + }, + // Select Hierarchy: with a target argument (the outliner context menu passes its row) the row's + // subtree replaces the selection; without one (the palette) the current selection expands in place. + Command("outliner.selectHierarchy", title = Res.string.cmd_outliner_select_hierarchy, availability = availability.hasDocument) { argument -> + val live = editorSession + if (live != null) { + val seed = (argument as? SelectionTarget)?.let { target -> Selection(setOf(target), target) } ?: live.selection.value + live.setSelection(SelectionOps.selectHierarchy(seed, live.model.value)) + } + }, + // Create Warp Deformer: wrap the selected meshes (a part expands to its subtree) in a new warp + // fitted to their rest bounds, inserted under their shared parent. Suggested in Object mode - that + // is where the lattice overlay lives. + Command( + "deformer.createWarp", + title = Res.string.cmd_deformer_create_warp, + availability = availability.hasDocument, + hint = CommandHint(Res.string.status_bind_create_warp, suggestedWhen = availability.inObjectMode), + ) { argument -> + editorSession?.createWarpDeformerForSelection(argument as? String ?: "Warp Deformer") + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ProportionalCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ProportionalCommands.kt new file mode 100644 index 0000000..76768ac --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ProportionalCommands.kt @@ -0,0 +1,50 @@ +package org.umamo.ui.workspace.commands + +import org.jetbrains.compose.resources.StringResource +import org.umamo.edit.EditorSession +import org.umamo.edit.ProportionalFalloff +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* + +/** The localized palette title for each proportional-editing falloff curve. */ +private val FALLOFF_TITLES: Map = + mapOf( + ProportionalFalloff.Smooth to Res.string.cmd_mesh_proportional_falloff_smooth, + ProportionalFalloff.Sphere to Res.string.cmd_mesh_proportional_falloff_sphere, + ProportionalFalloff.Root to Res.string.cmd_mesh_proportional_falloff_root, + ProportionalFalloff.Sharp to Res.string.cmd_mesh_proportional_falloff_sharp, + ProportionalFalloff.Linear to Res.string.cmd_mesh_proportional_falloff_linear, + ProportionalFalloff.Constant to Res.string.cmd_mesh_proportional_falloff_constant, + ) + +/** + * Proportional editing (Blender's O): the toggle flips it, the falloff commands select the curve + * (enabling it if off). The Edit overlay reads the state when an operator latches and the wheel resizes + * the radius mid-gesture, so nothing here needs to know which area the gesture will run in. + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun proportionalCommands(editorSession: EditorSession?, availability: SessionAvailability): List = + listOf( + Command("mesh.proportional.toggle", title = Res.string.cmd_mesh_proportional_toggle, availability = availability.inEditMode) { + editorSession?.toggleProportionalEdit() + }, + Command( + "mesh.proportional.connectedToggle", + title = Res.string.cmd_mesh_proportional_connected, + availability = availability.inEditMode, + ) { + editorSession?.toggleProportionalConnected() + }, + ) + + // One falloff command per curve, looped over the enum so a new falloff cannot be forgotten here - + // getValue throws on a curve with no title rather than silently registering an unlabelled command. + ProportionalFalloff.entries.map { falloff -> + Command( + "mesh.proportional.falloff.${falloff.name.lowercase()}", + title = FALLOFF_TITLES.getValue(falloff), + availability = availability.inEditMode, + ) { editorSession?.setProportionalFalloff(falloff) } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/SelectCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/SelectCommands.kt new file mode 100644 index 0000000..6223e96 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/SelectCommands.kt @@ -0,0 +1,127 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshSelectMode +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandHint +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.KeyformSheetViews +import org.umamo.ui.workspace.SpaceKind + +/** + * The selection commands: the Edit-mode element domains, select all / invert, the Box and Circle marquee + * tools, and the pointer-driven Select Linked pair. + * + * Several of these dispatch by mode so one binding serves both - mesh elements in Edit mode, whole + * entities in Object mode - and the session methods no-op in the wrong mode, so the keymap binds them + * context-free. + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param CommandRouting routing Resolves which area the pointer means at dispatch time. + * @param KeyformSheetViews keyformSheets The shell's open-sheet registry; Box Select arms the hovered + * sheet's own marquee through it instead of the viewport's tool. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun selectCommands( + editorSession: EditorSession?, + routing: CommandRouting, + keyformSheets: KeyformSheetViews, + availability: SessionAvailability, +): List = + listOf( + // Edit-mode select modes (Blender 1 / 2 / 3). The session guards them to no-op outside Edit mode, + // so the keymap can bind bare digits context-free; the availability tier additionally hides them + // from the palette in Object mode (there is no element domain to switch there). + Command( + "mesh.selectMode.vertex", + title = Res.string.cmd_mesh_select_mode_vertex, + availability = availability.inEditMode, + hint = CommandHint(Res.string.status_select_mode), + ) { + editorSession?.setMeshSelectMode(MeshSelectMode.Vertex) + }, + Command( + "mesh.selectMode.edge", + title = Res.string.cmd_mesh_select_mode_edge, + availability = availability.inEditMode, + hint = CommandHint(Res.string.status_select_mode), + ) { + editorSession?.setMeshSelectMode(MeshSelectMode.Edge) + }, + Command( + "mesh.selectMode.face", + title = Res.string.cmd_mesh_select_mode_face, + availability = availability.inEditMode, + hint = CommandHint(Res.string.status_select_mode), + ) { + editorSession?.setMeshSelectMode(MeshSelectMode.Face) + }, + // Select All / Invert dispatch by mode so one binding (A / Ctrl+I) serves both: mesh elements in Edit + // mode, whole selectable entities in Object mode. Each session method no-ops in the wrong mode. + Command("select.all", title = Res.string.cmd_select_all, availability = availability.hasDocument) { + if (editorSession?.mode?.value == EditorMode.Edit) { + editorSession.selectAllMeshElements() + } else { + editorSession?.selectAllObjects() + } + }, + Command("select.invert", title = Res.string.cmd_select_invert, availability = availability.hasDocument) { + if (editorSession?.mode?.value == EditorMode.Edit) { + editorSession.invertMeshSelection() + } else { + editorSession?.invertObjectSelection() + } + }, + // Box (Blender B) and Circle (Blender C) select tools latch on the session; the arming surface's + // overlay drives the gesture (both modes in the viewport; Edit mode in the UV editor, whose + // overlay only composes there). The circle grow / shrink commands (numpad +/-) apply only + // while a Circle brush is live, so they hide from the palette otherwise. + // ONE Box Select that acts on whatever is under the pointer, rather than a second command fighting + // for the same chord: a hovered keyform sheet arms its own marquee, a hovered viewport (or UV + // editor in Edit mode) arms the session's tool, and anything else arms nothing. Resolved at + // dispatch time like every other hovered-surface command. + Command( + "mesh.boxSelect", + title = Res.string.cmd_mesh_box_select, + availability = availability.hasDocument, + spaces = CommandSpaces.WorkSurfacesAndSheet, + ) { + // Only reach for a sheet when the pointer actually names one. The registry's lookup falls back + // to the lone open sheet when handed no area, so asking it unconditionally would hijack B in the + // viewport for any layout that happens to have a keyform sheet open. + val hoveredSheetArea = routing.areaOf(SpaceKind.KeyformSheet) + if (hoveredSheetArea != null) { + keyformSheets.resolve(hoveredSheetArea)?.armBoxSelect?.invoke() + } else { + routing.selectToolArea(editorSession)?.let { areaId -> editorSession?.beginBoxSelect(areaId) } + } + }, + // No sheet branch here, unlike Box Select: the keyform sheet has no circle brush to arm, so C over a + // sheet arms nothing at all - selectToolArea answers only for a viewport or an Edit-mode UV editor, + // and arming a viewport the pointer has left is worse than doing nothing. + Command("mesh.circleSelect", title = Res.string.cmd_mesh_circle_select, availability = availability.hasDocument, spaces = CommandSpaces.WorkSurfaces) { + routing.selectToolArea(editorSession)?.let { areaId -> editorSession?.beginCircleSelect(areaId) } + }, + Command("mesh.circleSelect.grow", title = Res.string.cmd_mesh_circle_grow, availability = availability.circleToolLive) { + editorSession?.growCircleRadius() + }, + Command("mesh.circleSelect.shrink", title = Res.string.cmd_mesh_circle_shrink, availability = availability.circleToolLive) { + editorSession?.shrinkCircleRadius() + }, + // Select Linked (Blender's L / Ctrl+L) and the Alt+Q edited-mesh switch: the pointer position and + // the projected geometry live in the overlays, so these fire session request flows they collect. + // The executing area resolves HERE, at dispatch, into the request payload (the hovered surface - + // viewport or UV editor alike), so the collectors gate deterministically on their own area id. + Command("mesh.selectLinkedAtCursor", title = Res.string.cmd_mesh_select_linked_cursor, availability = availability.inEditMode, spaces = CommandSpaces.WorkSurfaces) { + editorSession?.requestSelectLinked(fromSelection = false, areaId = routing.hoveredAreaIdAnyKind()) + }, + Command("mesh.selectLinked", title = Res.string.cmd_mesh_select_linked, availability = availability.inEditMode, spaces = CommandSpaces.WorkSurfaces) { + editorSession?.requestSelectLinked(fromSelection = true, areaId = routing.hoveredAreaIdAnyKind()) + }, + Command("edit.switchObjectUnderCursor", title = Res.string.cmd_switch_object_under_cursor, availability = availability.inEditMode, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSwitchObjectUnderCursor(routing.viewportArea()) + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/SnapCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/SnapCommands.kt new file mode 100644 index 0000000..c25bb3e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/SnapCommands.kt @@ -0,0 +1,103 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.PieMenuKind +import org.umamo.edit.SnapKind +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.snapToWorldGrid +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.SpaceKind + +/** + * The transform pivot modes (the Period pie / the palette) and the Shift+S snap operations over world + * space. + * + * The pivot setters and the arithmetical cursor snaps run right here; the geometry-dependent snaps go + * through the session's request flow to the active mode's overlay, which owns the world projections. + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param CommandRouting routing Resolves which area the pointer means at dispatch time. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun snapCommands( + editorSession: EditorSession?, + routing: CommandRouting, + availability: SessionAvailability, +): List = + listOf( + Command("transform.pivotPie", title = Res.string.cmd_transform_pivot_pie, availability = availability.hasDocument) { + editorSession?.openPieMenu(PieMenuKind.PivotMode) + }, + Command("transform.pivot.median", title = Res.string.cmd_transform_pivot_median, availability = availability.hasDocument) { + editorSession?.setPivotMode(TransformPivotMode.MedianPoint) + editorSession?.closePieMenu() + }, + Command("transform.pivot.individual", title = Res.string.cmd_transform_pivot_individual, availability = availability.hasDocument) { + editorSession?.setPivotMode(TransformPivotMode.IndividualOrigins) + editorSession?.closePieMenu() + }, + Command("transform.pivot.active", title = Res.string.cmd_transform_pivot_active, availability = availability.hasDocument) { + editorSession?.setPivotMode(TransformPivotMode.ActiveElement) + editorSession?.closePieMenu() + }, + Command("transform.pivot.cursor", title = Res.string.cmd_transform_pivot_cursor, availability = availability.hasDocument) { + editorSession?.setPivotMode(TransformPivotMode.Cursor) + editorSession?.closePieMenu() + }, + Command("snap.pie", title = Res.string.cmd_snap_pie, availability = availability.hasDocument) { + // Blender's hovered-area routing (the key acts where the pointer is): over the UV editor in + // Edit mode this opens the UV snap pie, whose entries snap texture coordinates; everywhere + // else the world snap pie - mirroring how mesh.grab / scale / rotate route to beginUvOperator. + editorSession?.let { live -> + if (live.mode.value == EditorMode.Edit && routing.isHovering(SpaceKind.UvEditor)) { + live.openPieMenu(PieMenuKind.UvSnap) + } else { + live.openPieMenu(PieMenuKind.Snap) + } + } + }, + Command("snap.cursorToWorldOrigin", title = Res.string.cmd_snap_cursor_world_origin, availability = availability.hasDocument) { + editorSession?.let { live -> + live.setCursor2d(live.model.value.worldOriginX, live.model.value.worldOriginZ) + live.closePieMenu() + } + }, + Command("snap.cursorToGrid", title = Res.string.cmd_snap_cursor_grid, availability = availability.hasDocument) { + editorSession?.let { live -> + // An unplaced cursor snaps from the world origin (its resting place). The world grid is anchored + // on the origin, so the snap targets the same lines the backdrop draws. + val cursor = live.cursor2dOrWorldOrigin() + val (snappedX, snappedZ) = live.model.value.snapToWorldGrid(cursor.worldX, cursor.worldZ, live.gridConfig.value.snapStep) + live.setCursor2d(snappedX, snappedZ) + live.closePieMenu() + } + }, + Command("snap.cursorToSelected", title = Res.string.cmd_snap_cursor_selected, availability = availability.hasDocument, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSnap(SnapKind.CursorToSelected, routing.viewportArea()) + editorSession?.closePieMenu() + }, + Command("snap.cursorToActive", title = Res.string.cmd_snap_cursor_active, availability = availability.hasDocument, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSnap(SnapKind.CursorToActive, routing.viewportArea()) + editorSession?.closePieMenu() + }, + Command("snap.selectionToGrid", title = Res.string.cmd_snap_selection_grid, availability = availability.hasDocument, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSnap(SnapKind.SelectionToGrid, routing.viewportArea()) + editorSession?.closePieMenu() + }, + Command("snap.selectionToCursor", title = Res.string.cmd_snap_selection_cursor, availability = availability.hasDocument, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSnap(SnapKind.SelectionToCursor, routing.viewportArea()) + editorSession?.closePieMenu() + }, + Command("snap.selectionToCursorOffset", title = Res.string.cmd_snap_selection_cursor_offset, availability = availability.hasDocument, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSnap(SnapKind.SelectionToCursorOffset, routing.viewportArea()) + editorSession?.closePieMenu() + }, + Command("snap.selectionToActive", title = Res.string.cmd_snap_selection_active, availability = availability.hasDocument, spaces = CommandSpaces.Viewport2D) { + editorSession?.requestSnap(SnapKind.SelectionToActive, routing.viewportArea()) + editorSession?.closePieMenu() + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/TopologyCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/TopologyCommands.kt new file mode 100644 index 0000000..dcc7e95 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/TopologyCommands.kt @@ -0,0 +1,99 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MergeTarget +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.PieMenuKind +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.resources.* + +/** + * The topology operators (Blender's Shift+D / M / V / J, plus Cubism-style Add Vertex). Duplicate + * dispatches by mode like G / S / R and auto-grabs the copies; merge opens its target pie; rip needs the + * pointer side, so it flows to the Edit overlay; connect cuts between the two selected vertices in place; + * Add Vertex latches a staged draft on the hovered work surface (Enter accepts, Esc discards). + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param CommandRouting routing Resolves which area the pointer means at dispatch time. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun topologyCommands( + editorSession: EditorSession?, + routing: CommandRouting, + availability: SessionAvailability, +): List = + listOf( + Command("mesh.duplicate", title = Res.string.cmd_mesh_duplicate, availability = availability.hasDocument) { + val live = editorSession + if (live != null) { + // The duplicate itself needs no area - it is a model edit - so it runs wherever the pointer + // is. Only the auto-grab needs a viewport, and it simply does not happen when the pointer + // is on a UV editor or a panel: starting a grab in an area the user is not pointing at is + // worse than leaving the copies where they landed for an explicit one. Both modes read the + // same rule from viewportArea(), which is null off a viewport. + if (live.mode.value == EditorMode.Edit) { + live.duplicateSelectedElements() + // Proportional weights would drag the ORIGINAL vertices along with the fresh copies, so + // the auto-grab latch opts out of them (Blender parity). + routing.viewportArea()?.let { areaId -> + live.beginMeshOperator(MeshOperatorKind.Grab, areaId, suppressProportional = true) + } + } else if (live.duplicateSelectedDrawables().isNotEmpty()) { + routing.viewportArea()?.let { areaId -> live.beginObjectOperator(MeshOperatorKind.Grab, areaId) } + } + } + }, + Command("mesh.merge", title = Res.string.cmd_mesh_merge, availability = availability.inEditMode) { + editorSession?.openPieMenu(PieMenuKind.MergeTarget) + }, + // The merge is a model edit that needs no area to run; the area it takes is where its operation + // settings strip shows (the hovered work surface, else the last one touched), since the merge pie + // or the palette may have been opened over a panel. + Command("mesh.merge.atCenter", title = Res.string.cmd_mesh_merge_at_center, availability = availability.inEditMode) { + editorSession?.mergeSelectedVertices(MergeTarget.AtCenter, routing.operationStripArea()) + editorSession?.closePieMenu() + }, + Command("mesh.merge.atFirst", title = Res.string.cmd_mesh_merge_at_first, availability = availability.inEditMode) { + editorSession?.mergeSelectedVertices(MergeTarget.AtFirst, routing.operationStripArea()) + editorSession?.closePieMenu() + }, + Command("mesh.merge.atLast", title = Res.string.cmd_mesh_merge_at_last, availability = availability.inEditMode) { + editorSession?.mergeSelectedVertices(MergeTarget.AtLast, routing.operationStripArea()) + editorSession?.closePieMenu() + }, + Command( + "mesh.rip", + title = Res.string.cmd_mesh_rip, + availability = + CommandAvailability { + editorSession?.mode?.value == EditorMode.Edit && editorSession.meshSelection.value.selectMode != MeshSelectMode.Face + }, + spaces = CommandSpaces.Viewport2D, + ) { editorSession?.requestRip(routing.viewportArea()) }, + Command("mesh.connect", title = Res.string.cmd_mesh_connect, availability = availability.inEditMode) { + editorSession?.connectSelectedVertices() + }, + // Add Vertex latches like Box / Circle: the arming work surface's overlay stages floats until + // Enter accepts (Esc / empty RMB discard; RMB on a float deletes it). + Command("mesh.insertVertex", title = Res.string.cmd_mesh_insert_vertex, availability = availability.inEditMode, spaces = CommandSpaces.WorkSurfaces) { + routing.selectToolArea(editorSession)?.let { areaId -> editorSession?.beginAddVertex(areaId) } + }, + Command( + "mesh.vertexSlide", + title = Res.string.cmd_mesh_vertex_slide, + availability = + CommandAvailability { + editorSession?.mode?.value == EditorMode.Edit && + editorSession.meshSelection.value.activeElement?.element is MeshElement.Vertex + }, + spaces = CommandSpaces.Viewport2D, + ) { + routing.viewportArea()?.let { areaId -> editorSession?.beginMeshOperator(MeshOperatorKind.VertexSlide, areaId) } + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/TransformCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/TransformCommands.kt new file mode 100644 index 0000000..edd7993 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/TransformCommands.kt @@ -0,0 +1,140 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.UvMirrorRequest +import org.umamo.edit.ViewportMirrorRequest +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandHint +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.resources.* + +/** + * The modal transform commands (Blender G / S / R), one-shot Mirror H / V, and modal cancel. + * + * One binding serves every surface and mode: the operator dispatches by where the pointer is and which + * mode is active, so the keymap binds a bare letter with no context of its own. Each session method + * guards its own preconditions, so an out-of-mode or ineligible press is a safe no-op. + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param CommandRouting routing Resolves which area the pointer means at dispatch time. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun transformCommands( + editorSession: EditorSession?, + routing: CommandRouting, + availability: SessionAvailability, +): List = + listOf( + Command( + "mesh.grab", + title = Res.string.cmd_mesh_grab, + availability = availability.hasDocument, + spaces = CommandSpaces.WorkSurfaces, + hint = CommandHint(Res.string.status_bind_grab), + ) { + beginTransform(editorSession, MeshOperatorKind.Grab, routing) + }, + Command( + "mesh.scale", + title = Res.string.cmd_mesh_scale, + availability = availability.hasDocument, + spaces = CommandSpaces.WorkSurfaces, + hint = CommandHint(Res.string.status_bind_scale), + ) { + beginTransform(editorSession, MeshOperatorKind.Scale, routing) + }, + Command( + "mesh.rotate", + title = Res.string.cmd_mesh_rotate, + availability = availability.hasDocument, + spaces = CommandSpaces.WorkSurfaces, + hint = CommandHint(Res.string.status_bind_rotate), + ) { + beginTransform(editorSession, MeshOperatorKind.Rotate, routing) + }, + // Reverse Positions H/V: pairwise-swap one axis among selected verts / CPs (not pivot reflection). + Command( + "mesh.mirrorH", + title = Res.string.cmd_mesh_mirror_h, + availability = availability.hasDocument, + spaces = CommandSpaces.WorkSurfaces, + ) { + beginReversePositions(editorSession, horizontal = true, routing) + }, + Command( + "mesh.mirrorV", + title = Res.string.cmd_mesh_mirror_v, + availability = availability.hasDocument, + spaces = CommandSpaces.WorkSurfaces, + ) { + beginReversePositions(editorSession, horizontal = false, routing) + }, + // Untitled and ungated: the ladder and the overlays dispatch it as a cleanup signal, and exactly + // one of the three latches can be live, so clearing all three unconditionally is the whole job. + Command("mesh.modalCancel", title = null) { + editorSession?.clearMeshOperator() + editorSession?.clearObjectOperator() + editorSession?.clearUvOperator() + }, + ) + +/** + * Begins a modal transform on [session] for the surface the pointer last touched: a UV operator over + * texture coordinates in a hovered UV editor (Blender's hovered-area routing - the key acts where the + * pointer is), else an Edit-mode mesh operator over the selected vertices or an Object-mode operator over + * the selected drawables' whole geometry. + * + * @param EditorSession? session The active session, or null when no document is open. + * @param MeshOperatorKind kind The operator to begin (Grab / Scale / Rotate). + * @param CommandRouting routing Resolves the target surface at dispatch time. + * @note The UV branch does not fall back to a viewport when the session declines it (beginUvOperator + * refuses an Edit-mode selection with no editable UVs and an Object-mode selection with no packed + * art to place). Refusing outright is the point: the alternative would grab geometry in an area the + * pointer is nowhere near. + */ +private fun beginTransform(session: EditorSession?, kind: MeshOperatorKind, routing: CommandRouting) { + if (session == null) { + return + } + when (val target = routing.transformTarget()) { + is TransformTarget.Uv -> session.beginUvOperator(kind, target.areaId) + is TransformTarget.Viewport -> + if (session.mode.value == EditorMode.Edit) { + session.beginMeshOperator(kind, target.areaId) + } else { + session.beginObjectOperator(kind, target.areaId) + } + // The pointer has never touched a viewport and is not over a UV editor: nowhere to run it. + null -> Unit + } +} + +/** + * One-shot Reverse Positions H/V: pairwise-swap one axis among selected verts / drawables / warp CPs, + * or UV coords when the pointer is over a UV editor. + * + * @param EditorSession? session The active session, or null when no document is open. + * @param Boolean horizontal True to swap x/u only; false to swap y/v only. + * @param CommandRouting routing Resolves the target surface at dispatch time. + */ +private fun beginReversePositions(session: EditorSession?, horizontal: Boolean, routing: CommandRouting) { + if (session == null) { + return + } + when (val target = routing.transformTarget()) { + is TransformTarget.Uv -> + session.requestUvMirror( + UvMirrorRequest(mirrorU = horizontal, areaId = target.areaId, reverseSwap = true), + ) + is TransformTarget.Viewport -> + session.requestViewportMirror(ViewportMirrorRequest(mirrorHorizontal = horizontal, areaId = target.areaId)) + // Toolbar sits on the viewport chrome; if hover was lost mid-click, frame the last viewport. + null -> + routing.framedViewportArea()?.let { areaId -> + session.requestViewportMirror(ViewportMirrorRequest(mirrorHorizontal = horizontal, areaId = areaId)) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/UvCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/UvCommands.kt new file mode 100644 index 0000000..55bcbdd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/UvCommands.kt @@ -0,0 +1,148 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorSession +import org.umamo.edit.NoticePlacement +import org.umamo.edit.UvMirrorRequest +import org.umamo.edit.UvPageKind +import org.umamo.edit.UvPageRequest +import org.umamo.edit.UvSnapKind +import org.umamo.edit.UvSnapRequest +import org.umamo.edit.placementSelectedTileIds +import org.umamo.edit.setAtlasPins +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandHint +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.SpaceKind + +/** + * The texture-coordinate commands: the axis mirrors, the UV editor's own snap pie, the texture + * page switches, and the placement pins. + * + * Every snap entry runs through the session's UV snap request flow to the hovered UV editor's overlay, + * which owns the shown surface's dimensions and display geometry. The area is resolved HERE, at dispatch, + * into the payload (like Select Linked), so the collector gates deterministically on its own area id. + * + * Every command here is scoped to the UV editor: each one is collected by that editor's overlay or + * space alone, so fired anywhere else it matches no collector and does nothing. + * + * @param EditorSession? editorSession The open document's session, or null (every command then no-ops). + * @param CommandRouting routing Resolves which area the pointer means at dispatch time. + * @param SessionAvailability availability The shared document-scoped availability tiers. + * @return List The commands to register. + */ +internal fun uvCommands( + editorSession: EditorSession?, + routing: CommandRouting, + availability: SessionAvailability, +): List { + /** + * Fires one UV snap request at the hovered area. + * + * @param UvSnapKind kind The snap to perform. + */ + fun requestUvSnap(kind: UvSnapKind) { + editorSession?.requestUvSnap(UvSnapRequest(kind, routing.hoveredAreaIdAnyKind())) + editorSession?.closePieMenu() + } + + /** + * Fires one mirror request at the hovered UV editor, which supplies the frame it is authoring in. + * + * @param Boolean mirrorU True to mirror horizontally, false vertically. + */ + fun requestUvMirror(mirrorU: Boolean) { + editorSession?.requestUvMirror(UvMirrorRequest(mirrorU, routing.areaOf(SpaceKind.UvEditor))) + } + + /** + * Fires one page-switch request at the hovered UV editor. The kind-checked resolver hands a + * pointer that is NOT on a UV editor a null area, which matches no collector - the Blender + * hovered-area rule, resolved one step earlier than the snap helper's any-kind id. + * + * @param UvPageKind kind The page operation to perform. + */ + fun requestUvPage(kind: UvPageKind) { + editorSession?.requestUvPage(UvPageRequest(kind, routing.areaOf(SpaceKind.UvEditor))) + } + + /** + * Pins or unpins the placed tiles under the object selection, pinned or not (Unpin must find the + * pinned ones, which a placement gesture no longer moves), so a repack keeps (or may move) them. + * From a hovered UV editor only: a pin is set while looking at the page, and the key means + * nothing over a viewport. + * + * @param Boolean pinned True to pin, false to unpin. + */ + fun setPins(pinned: Boolean) { + val session = editorSession ?: return + if (routing.areaOf(SpaceKind.UvEditor) == null) { + return + } + val tileIds = session.model.value.placementSelectedTileIds(session.selection.value) + if (tileIds.isEmpty()) { + session.emitNotice("notice.uv.placement.noPlacedArt", NoticePlacement.NearCursor) + return + } + session.setAtlasPins(tileIds, pinned) + } + return listOf( + // Mirror UVs (the duplicated-and-flipped texture regions workflow, e.g. both eyes sampling one + // eye texture): axis-aligned reflections about the transform pivot, palette-discoverable and + // unbound by default - an interactive flip is already S + axis + drag through the pivot. + Command("uv.mirrorU", title = Res.string.cmd_uv_mirror_u, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvMirror(mirrorU = true) + }, + Command("uv.mirrorV", title = Res.string.cmd_uv_mirror_v, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvMirror(mirrorU = false) + }, + Command("uv.snap.selectionToPixels", title = Res.string.cmd_uv_snap_selection_pixels, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.SelectionToPixels) + }, + Command("uv.snap.selectionToCursor", title = Res.string.cmd_uv_snap_selection_cursor, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.SelectionToCursor) + }, + Command("uv.snap.selectionToCursorOffset", title = Res.string.cmd_uv_snap_selection_cursor_offset, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.SelectionToCursorOffset) + }, + Command("uv.snap.selectionToGrid", title = Res.string.cmd_uv_snap_selection_grid, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.SelectionToGrid) + }, + Command("uv.snap.cursorToPixels", title = Res.string.cmd_uv_snap_cursor_pixels, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.CursorToPixels) + }, + Command("uv.snap.cursorToSelected", title = Res.string.cmd_uv_snap_cursor_selected, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.CursorToSelected) + }, + Command("uv.snap.cursorToGrid", title = Res.string.cmd_uv_snap_cursor_grid, availability = availability.inEditMode, spaces = CommandSpaces.UvEditor) { + requestUvSnap(UvSnapKind.CursorToGrid) + }, + // Texture page switching (the header selector's palette path): retargets the hovered UV + // editor's per-area texture selection - cycling pins with wrap-around, follow clears the pin. + // Mode-agnostic (reviewing pages is not an Edit-mode operation), palette-discoverable, and + // unbound by default like the rest of the table. + Command("uv.page.next", title = Res.string.cmd_uv_page_next, availability = availability.hasDocument, spaces = CommandSpaces.UvEditor) { + requestUvPage(UvPageKind.NextPage) + }, + Command("uv.page.previous", title = Res.string.cmd_uv_page_previous, availability = availability.hasDocument, spaces = CommandSpaces.UvEditor) { + requestUvPage(UvPageKind.PreviousPage) + }, + Command("uv.page.followSelection", title = Res.string.cmd_uv_page_follow, availability = availability.hasDocument, spaces = CommandSpaces.UvEditor) { + requestUvPage(UvPageKind.FollowSelection) + }, + // Placement pins (Blender's P / Alt+P in the UV editor): Object mode, where the selection names + // whole drawables and so the tiles under them. + Command( + "uv.pinPlacement", + title = Res.string.cmd_uv_pin_placement, + availability = availability.inObjectMode, + spaces = CommandSpaces.UvEditor, + hint = CommandHint(Res.string.status_bind_pin), + ) { + setPins(pinned = true) + }, + Command("uv.unpinPlacement", title = Res.string.cmd_uv_unpin_placement, availability = availability.inObjectMode, spaces = CommandSpaces.UvEditor) { + setPins(pinned = false) + }, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ViewCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ViewCommands.kt new file mode 100644 index 0000000..beaa83a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ViewCommands.kt @@ -0,0 +1,94 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.resources.* +import org.umamo.ui.viewport.CameraController +import org.umamo.ui.workspace.AreaCameraHub +import org.umamo.ui.workspace.SpaceKind + +/** + * The viewport navigation commands, dispatching to the surface the pointer last touched: each 2D + * viewport and UV editor registers a per-area camera controller into the shared hub, and every command + * resolves the hovered area's controller through it (Blender's hovered-area routing, the same rule as + * the transforms) - one lookup, no per-space branch. They apply whenever a viewport is present (a + * document open on a platform with a renderer); without one they hide from the palette instead of + * registering as no-ops. + * + * @param AreaCameraHub cameras The camera-bearing areas' per-area controller registry. + * @param CommandRouting routing Resolves which area the pointer means at dispatch time. + * @param Boolean viewportPresent Whether a viewport / render service exists (gates availability). + * @return List The commands to register. + */ +internal fun viewCommands(cameras: AreaCameraHub, routing: CommandRouting, viewportPresent: Boolean): List { + val hasViewport = CommandAvailability { viewportPresent } + + /** + * The camera controller of the area the pointer last touched, or null when none is registered under + * it - then the command is a no-op. + * + * @return CameraController? The hovered area's camera controller, or null. + * @note Deliberately kind-agnostic: the hub's contract is that a future camera-bearing space joins by + * registering a controller, with no per-space branch to update here. Hovering a space that has no + * camera (a keyform sheet, an outliner) simply resolves nothing. The one thing such a space does + * add is itself to CommandSpaces.WorkSurfaces, or the palette keeps hiding these commands over it. + */ + fun hoveredCamera(): CameraController? = routing.hovered()?.areaId?.let { areaId -> cameras.opsFor(areaId) } + return listOf( + Command("view.fit", title = Res.string.cmd_view_fit, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.fit() + }, + Command("view.zoomActualSize", title = Res.string.cmd_view_actual_size, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.actualSize() + }, + Command("view.zoomIn", title = Res.string.cmd_view_zoom_in, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.zoomIn(coarse = false) + }, + Command("view.zoomOut", title = Res.string.cmd_view_zoom_out, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.zoomOut(coarse = false) + }, + // Coarse (Shift) variants take a larger zoom step - they are titled so they also surface in the palette. + Command("view.zoomInCoarse", title = Res.string.cmd_view_zoom_in_coarse, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.zoomIn(coarse = true) + }, + Command("view.zoomOutCoarse", title = Res.string.cmd_view_zoom_out_coarse, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.zoomOut(coarse = true) + }, + // Zoom Region (Blender's Shift+B): arms a drag-a-box-to-frame gesture on the hovered surface. + Command("view.zoomRegion", title = Res.string.cmd_view_zoom_region, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.armZoomRegion() + }, + // Frame Selected (Blender's numpad-period): fit the camera to the selection's bounds - world + // bounds in the viewport, covered UV bounds in a hovered UV editor. + Command("view.frameSelected", title = Res.string.cmd_view_frame_selected, availability = hasViewport, spaces = CommandSpaces.WorkSurfaces) { + hoveredCamera()?.frameSelected() + }, + ) +} + +/** + * The context-aware frame command - Blender's Home: Frame All in WHICHEVER editor the pointer is over. + * + * Its own table rather than part of [viewCommands] because it is a re-dispatcher, not an operation: it + * resolves the hovered surface to the command that surface means and invokes THAT through the registry, + * so each editor keeps owning its own framing. Ungated on purpose - the camera commands it forwards to + * carry their own viewport gate, while the keyform sheet needs no renderer at all, so gating this one + * would kill Home over a sheet on a platform with no render service. + * + * @param CommandRegistry commandRegistry The registry the resolved command is invoked through. + * @param CommandRouting routing Resolves which editor the pointer means at dispatch time. + * @return List The commands to register. + */ +internal fun frameCommands(commandRegistry: CommandRegistry, routing: CommandRouting): List = + listOf( + Command( + "frame.all", + title = Res.string.cmd_frame_all, + spaces = CommandSpaces.WorkSurfacesAndSheet, + ) { + val target = if (routing.isHovering(SpaceKind.KeyformSheet)) "keyform.frameAll" else "view.fit" + commandRegistry.invoke(target) + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ViewportChromeCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ViewportChromeCommands.kt new file mode 100644 index 0000000..0872c7d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/ViewportChromeCommands.kt @@ -0,0 +1,28 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.settings.Settings +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.SHOW_SIDEBAR_SETTINGS_KEY +import org.umamo.ui.workspace.SHOW_TOOLBAR_SETTINGS_KEY + +/** + * The viewport chrome toggles. They write settings rather than session or layout state, so the chrome + * follows its keys reactively and a toggle takes effect across every open viewport at once. + * + * Registered by the settings-backed shell wrapper, not by EditorShell itself: the shell's contract is to + * stay Settings-free so it remains standalone-runnable and unit-testable, which is the same division the + * app-registered File commands follow. A shell mounted without settings simply lacks these two. + * + * @param Settings settings The merged settings tree the toggles read and write. + * @return List The commands to register. + */ +internal fun viewportChromeCommands(settings: Settings): List = + listOf( + Command("view.toggleToolbar", title = Res.string.cmd_view_toggle_toolbar) { + settings.setBoolean(SHOW_TOOLBAR_SETTINGS_KEY, !(settings.getBoolean(SHOW_TOOLBAR_SETTINGS_KEY) ?: true)) + }, + Command("view.toggleSidebar", title = Res.string.cmd_view_toggle_sidebar) { + settings.setBoolean(SHOW_SIDEBAR_SETTINGS_KEY, !(settings.getBoolean(SHOW_SIDEBAR_SETTINGS_KEY) ?: false)) + }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/WorkspaceCommands.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/WorkspaceCommands.kt new file mode 100644 index 0000000..eabbe4f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/commands/WorkspaceCommands.kt @@ -0,0 +1,69 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.Command +import org.umamo.ui.resources.* +import org.umamo.ui.workspace.ConfirmRequest +import org.umamo.ui.workspace.InterfaceLayout +import org.umamo.ui.workspace.ShellOverlayState +import org.umamo.ui.workspace.Workspace +import org.umamo.ui.workspace.WorkspaceLayoutController + +/** + * The workspace-management commands. New mirrors the "+" create path; Reset and Apply-Layout are + * destructive, so they raise a confirm dialog rather than acting at once; Append-Workspace adds an + * imported tab (a non-destructive add). The file handling is its own table ([workspaceFileCommands]), + * whose import parses a file and invokes applyLayout / appendWorkspace here with the result - keeping the + * live layout state the single source of truth. + * + * @param WorkspaceLayoutController workspaces The layout state the commands rewrite. + * @param ShellOverlayState overlays The overlay state the confirms go through. + * @param String newWorkspaceBaseName The localized base name new workspaces are named from (deduped). + * @return List The commands to register. + */ +internal fun workspaceCommands( + workspaces: WorkspaceLayoutController, + overlays: ShellOverlayState, + newWorkspaceBaseName: String, +): List = + listOf( + Command("workspace.new", title = Res.string.workspace_new) { workspaces.create(newWorkspaceBaseName) }, + Command("workspace.reset", title = Res.string.cmd_workspace_reset) { + overlays.pendingConfirm = ConfirmRequest(Res.string.confirm_reset_workspace, confirmLabel = Res.string.dialog_reset) { workspaces.resetActive() } + }, + Command("workspace.applyLayout", title = null) { argument -> + (argument as? InterfaceLayout)?.let { imported -> + overlays.pendingConfirm = ConfirmRequest(Res.string.confirm_import_replace, confirmLabel = Res.string.dialog_replace) { workspaces.applyImported(imported) } + } + }, + Command("workspace.appendWorkspace", title = null) { argument -> + (argument as? Workspace)?.let { imported -> workspaces.appendImported(imported, newWorkspaceBaseName) } + }, + ) + +/** + * The workspace layout's file commands: import a layout or workspace file, export the active workspace, + * export the whole layout - in the Workspace menu's order, which is the order the palette lists them in. + * + * A table of its own rather than more rows on [workspaceCommands] because the two register in different + * places: these read the persisted layout from settings and open a file dialog, so the settings-backed + * shell registers them, while the shell proper stays Settings-free. The actions arrive as plain lambdas, + * like every other table's, so the table builds with no picker and no settings. + * + * None carries a default chord: they are occasional operations, reachable from the menu and the palette + * and bindable in Preferences. + * + * @param Function onImport Picks a layout or workspace file and applies it. + * @param Function onExportThis Exports the active workspace to a file. + * @param Function onExportAll Exports the whole layout to a file. + * @return List The commands to register. + */ +internal fun workspaceFileCommands( + onImport: () -> Unit, + onExportThis: () -> Unit, + onExportAll: () -> Unit, +): List = + listOf( + Command("workspace.import", title = Res.string.menu_workspace_import) { onImport() }, + Command("workspace.exportThis", title = Res.string.menu_workspace_export_this) { onExportThis() }, + Command("workspace.exportAll", title = Res.string.menu_workspace_export_all) { onExportAll() }, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragCancel.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragCancel.kt new file mode 100644 index 0000000..4271cc4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragCancel.kt @@ -0,0 +1,52 @@ +package org.umamo.ui.workspace.rowdrag + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf + +/** + * A coordination seam between an in-flight panel row drag and the editor shell's Escape precedence, + * mirroring [org.umamo.ui.kit.InlineEditController]. A panel's drag state is remembered per panel + * instance and invisible to the shell, yet Escape must reach it: a row drag almost always coexists + * with a non-empty selection (the press that starts the drag already selected the row), so without + * this seam the shell's clear-selection Escape branch fires instead of cancelling the drag. While a + * drag is in flight the owning panel parks its cancel callback here; the shell checks it before + * clearing the selection. Several row-dragging panels (outliner, parameters, sources) across several + * areas may exist, but one pointer means at most one in-flight drag anywhere, so a single shared slot + * suffices for all of them. Holds null whenever no row drag is in flight. Only the dragging panel + * should write it. + * + * @property Function cancel Cancels the in-flight row drag, or null when none is in flight. + */ +class RowDragCancelController { + var cancel: (() -> Unit)? by mutableStateOf(null) +} + +/** + * Supplies the [RowDragCancelController] the shell shares with the row-dragging panels under it. + * Defaults to a standalone instance so a panel hosted without the shell still composes (its drags + * simply cannot be cancelled from the keyboard). + */ +val LocalRowDragCancel = staticCompositionLocalOf { RowDragCancelController() } + +/** + * Parks this controller's cancel on the shell's seam for as long as a drag is in flight, so Escape + * aborts the drag instead of falling through to the shell's clear-selection branch. [RowDragController.isDragging] + * is snapshot state, so the effect re-keys on drag start and end; disposal also covers the space + * closing mid-drag. Every row-dragging space calls this once beside its controller. + */ +@Composable +fun RowDragController<*>.parkCancelOnSeam() { + val seam = LocalRowDragCancel.current + DisposableEffect(isDragging) { + if (isDragging) { + seam.cancel = { cancel() } + } + onDispose { + seam.cancel = null + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragController.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragController.kt new file mode 100644 index 0000000..9f10379 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragController.kt @@ -0,0 +1,161 @@ +package org.umamo.ui.workspace.rowdrag + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.LayoutCoordinates + +/* + * Row drag-and-drop, shared by every space that drags rows (the outliner, the parameters panel, the + * Sources table): the transient drag state and hit-test here, the Escape seam in RowDragCancel.kt, the + * long-press pickup in RowDragGesture.kt, the cursor chip in RowDragLabel.kt, and the drop-target ring + * in RowDropHighlight.kt. What a drag MEANS - which rows may take a drop, and what a release does - + * stays with each space and its :edit rules; nothing here knows a payload's kind. + */ + +/** + * A panel's row drag-and-drop state, shared by every row so the rows stay thin: each reports its + * window bounds and its drag gestures here, and the space reads the current drag / drop target to + * draw the indicator and to dispatch the move on release. Window coordinates throughout, so a + * pointer that has left the dragged row still hit-tests against every visible row. Rows are + * identified by a stable string key (the outliner's node id, the parameters panel's rowKey); what a + * drag relocates is the panel-specific [Payload] (its kind decides the legal drop bands). + * + * Holds only transient interaction state (never document state), so it is remembered per panel + * instance and discarded with it. + */ +class RowDragController { + /** The row key currently being dragged, or null when no drag is in progress. */ + var draggingKey: String? by mutableStateOf(null) + private set + + /** What the drag relocates (its kind decides the legal drop bands), or null when no drag is in progress. */ + var draggedPayload: Payload? by mutableStateOf(null) + private set + + /** The drag pointer's current X in window coordinates (for the floating drag label that follows the cursor). */ + var dragWindowX: Float by mutableStateOf(0f) + private set + + /** The drag pointer's current Y in window coordinates (meaningful only while [draggingKey] is set). */ + var dragWindowY: Float by mutableStateOf(0f) + private set + + // Each visible row's window bounds, by row key, for hit-testing the drop target. A SnapshotStateMap so + // the drop-indicator overlay recomposes as rows lay out / the pointer moves. + private val rowBounds = mutableStateMapOf() + + /** + * Records a row's current window bounds (called from its onGloballyPositioned). + * + * @param String rowKey The row's stable key. + * @param Rect bounds The row's bounds in window coordinates. + */ + fun reportBounds(rowKey: String, bounds: Rect) { + rowBounds[rowKey] = bounds + } + + /** + * Drops a row's bounds when it leaves composition (scrolled off), so the hit-test never targets a row + * that is no longer visible. + * + * @param String rowKey The row's stable key. + */ + fun clearBounds(rowKey: String) { + rowBounds.remove(rowKey) + } + + /** + * Begins a drag of [rowKey]. Seeds the pointer position with the press point so the drop target + * starts on the dragged row itself (i.e. no target) rather than wherever the previous drag ended - + * so a fresh grab never shows a stale drop, and a release without moving is a no-op. + * + * @param String rowKey The row being picked up. + * @param Payload payload What the drag relocates. + * @param Float windowX The press X in window coordinates. + * @param Float windowY The press Y in window coordinates. + */ + fun start(rowKey: String, payload: Payload, windowX: Float, windowY: Float) { + draggingKey = rowKey + draggedPayload = payload + dragWindowX = windowX + dragWindowY = windowY + } + + /** + * Updates the drag pointer's window position. + * + * @param Float windowX The pointer X in window coordinates. + * @param Float windowY The pointer Y in window coordinates. + */ + fun drag(windowX: Float, windowY: Float) { + dragWindowX = windowX + dragWindowY = windowY + } + + /** Ends the current drag (clears the drag state); the caller reads the target / fraction first. */ + fun end() { + draggingKey = null + draggedPayload = null + } + + /** + * Aborts the in-flight drag without dropping. Compose's drag gestures cannot be aborted from + * outside mid-stream, so cancelling resets the controller state instead: with [draggingKey] null + * the remaining onDrag updates and the release's drop dispatch become no-ops ([dropTargetKey] + * returns null, so the drop application early-returns), and the floating drag label and drop + * indicators - all keyed off [isDragging] - disappear at once. + */ + fun cancel() { + end() + } + + /** True while a drag is in progress. */ + val isDragging: Boolean get() = draggingKey != null + + /** + * The row key the drag pointer is currently over (excluding the dragged row itself), or null when + * over empty space. Uses a half-open band [top, bottom) so a pointer exactly on a shared row edge + * belongs to the lower row only - one unambiguous target, never two. + * + * @return String? The hovered row's key, or null. + */ + val dropTargetKey: String? + get() { + val dragged = draggingKey ?: return null + return rowBounds.entries + .firstOrNull { (rowKey, bounds) -> rowKey != dragged && dragWindowY >= bounds.top && dragWindowY < bounds.bottom } + ?.key + } + + /** + * The pointer's vertical position within the drop-target row, 0 (top edge) .. 1 (bottom edge), or null + * when there is no target. The space reads this to decide before / into / after on release, and a row + * reads its own band to draw the matching insertion edge. + * + * @return Float? The 0..1 fraction down the target row, or null. + */ + val dropTargetFraction: Float? + get() { + val target = dropTargetKey ?: return null + val bounds = rowBounds[target] ?: return null + val height = bounds.bottom - bounds.top + if (height <= 0f) { + return 0.5f + } + return ((dragWindowY - bounds.top) / height).coerceIn(0f, 1f) + } +} + +/** + * A plain, non-snapshot holder for a row's latest layout coordinates. Writing it from + * onGloballyPositioned does not invalidate the composition (unlike Compose state), so the per-frame + * layout callbacks during a scroll cost nothing; the drag gesture reads the live window bounds from it + * to convert a press into window coordinates, and a hover effect to anchor a preview. + */ +class RowCoordinatesHolder { + /** The row's most recent layout coordinates, or null before the first layout pass. */ + var coordinates: LayoutCoordinates? = null +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragGesture.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragGesture.kt new file mode 100644 index 0000000..a2edf35 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragGesture.kt @@ -0,0 +1,50 @@ +package org.umamo.ui.workspace.rowdrag + +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInWindow + +/** + * Picks the row up on a long press and drags it: the press point is converted into window + * coordinates through [holder] and seeds the drag there, so the initial target is the row itself + * (i.e. none) and never a stale target left over from the previous drag; every move is converted + * the same way; a release runs [onDrop] (the space reads the controller's target and applies the + * move); a cancelled gesture ends the drag without dropping. The long press keeps the gesture + * distinct from a tap-to-select handler on the same row, so a press still selects first and only a + * hold begins the drag. + * + * @param RowDragController controller The space's drag state. + * @param String rowKey The row's stable key. + * @param Payload? payload What a drag of this row relocates, or null for a row that + * cannot be picked up (a heading, a lost binding) - the modifier is then a no-op. + * @param RowCoordinatesHolder holder The row's latest layout coordinates, for the window conversion. + * @param Function onDrop Runs on release; read the controller's target inside it. Pass + * a lambda over updated state, since the gesture re-keys only on the controller, key, and payload. + * @return Modifier This modifier with the gesture attached, or unchanged when the row cannot be dragged. + */ +fun Modifier.dragRowOnLongPress( + controller: RowDragController, + rowKey: String, + payload: Payload?, + holder: RowCoordinatesHolder, + onDrop: () -> Unit, +): Modifier { + if (payload == null) { + return this + } + return pointerInput(controller, rowKey, payload) { + detectDragGesturesAfterLongPress( + onDragStart = { offset -> + val bounds = holder.coordinates?.boundsInWindow() + controller.start(rowKey, payload, (bounds?.left ?: 0f) + offset.x, (bounds?.top ?: 0f) + offset.y) + }, + onDrag = { change, _ -> + val bounds = holder.coordinates?.boundsInWindow() + controller.drag((bounds?.left ?: 0f) + change.position.x, (bounds?.top ?: 0f) + change.position.y) + }, + onDragEnd = { onDrop() }, + onDragCancel = { controller.end() }, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragLabel.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragLabel.kt new file mode 100644 index 0000000..95d35e0 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDragLabel.kt @@ -0,0 +1,68 @@ +package org.umamo.ui.workspace.rowdrag + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import kotlin.math.roundToInt + +/** Places a popup at a fixed window point (the drag cursor), nudged down-right so it clears the pointer. */ +private class CursorPopupPositionProvider(private val cursorX: Float, private val cursorY: Float) : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset = IntOffset((cursorX + 14f).roundToInt(), (cursorY + 8f).roundToInt()) +} + +/** + * The little name chip that follows the cursor while a row is being dragged, so there is something + * obviously "in hand" beyond the faded source row. Non-focusable and mounted at the space root, + * positioned in window coordinates at the drag pointer - the one chip every row-dragging space shows. + * + * @param String label The dragged row's display name. + * @param Float cursorX The drag pointer X, in window pixels. + * @param Float cursorY The drag pointer Y, in window pixels. + */ +@Composable +fun RowDragLabel(label: String, cursorX: Float, cursorY: Float) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val typography = LocalUmamoTypography.current + Popup( + popupPositionProvider = CursorPopupPositionProvider(cursorX, cursorY), + properties = PopupProperties(focusable = false, clippingEnabled = false), + ) { + Surface( + color = colors.menuBackground, + shape = shapes.small, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 6.dp, + ) { + Text( + text = label, + style = typography.labelSmall, + color = colors.text, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 220.dp).padding(horizontal = 8.dp, vertical = 3.dp), + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDropHighlight.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDropHighlight.kt new file mode 100644 index 0000000..7b33f24 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/rowdrag/RowDropHighlight.kt @@ -0,0 +1,43 @@ +package org.umamo.ui.workspace.rowdrag + +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.drawOutline +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.inset +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoColors + +/** How far the ring's outer edge sits inside the row, so it never lands on an edge a flush neighbour shares. */ +private val RING_INSET = 1.dp + +/** The ring's stroke, weighted like the insertion lines the row drags draw (2.5 dp) rather than a hairline. */ +private val RING_STROKE = 2.dp + +/** + * The drop-target treatment every row drag shares: while [active], the drop-target fill in [shape] + * with a 2 dp accent ring inset 1 dp inside the row, drawn behind the row's content. Inset and + * weighted on purpose - a 1 dp border on the row's own edge sits on the line a flush neighbour and the + * zebra band already occupy, and in the same hue as the fill it outlines it reads as the fill's + * antialiased edge rather than as a ring. Applied by the outliner, the parameters panel, and the + * Sources table, so the three read alike. + * + * @param Boolean active Whether this row is the drop target right now. + * @param Shape shape The row's shape, so the fill and the ring follow its corners. + * @param UmamoColors colors The palette the fill and the ring come from. + * @return Modifier This modifier with the highlight behind it, or unchanged when inactive. + */ +fun Modifier.rowDropHighlight(active: Boolean, shape: Shape, colors: UmamoColors): Modifier { + if (!active) { + return this + } + return drawBehind { + drawOutline(shape.createOutline(size, layoutDirection, this), colors.dropTargetBackground) + val stroke = RING_STROKE.toPx() + // The stroke is centred on the inset outline, so its outer edge sits RING_INSET inside the row. + inset(RING_INSET.toPx() + stroke / 2f) { + drawOutline(shape.createOutline(size, layoutDirection, this), colors.accent, style = Stroke(width = stroke)) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/EditHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/EditHeaderControls.kt new file mode 100644 index 0000000..5cddc4d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/EditHeaderControls.kt @@ -0,0 +1,190 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.ProportionalFalloff +import org.umamo.edit.TransformPivotMode +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.button.ButtonGroup +import org.umamo.ui.kit.button.ButtonGroupItem +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.viewport.falloffLabel + +/* + * The Edit-mode header controls shared by the editor surfaces that host element editing - the 2D + * viewport and the UV editor mount the same select-mode buttons, pivot dropdown, and proportional + * controls, so the two headers stay one behavior (and one look) by construction. Every control + * mutates only by dispatching registry commands, per the everything-through-the-action-registry rule. + */ + +/** + * The vertex / edge / face select-mode buttons: a three-segment radio ButtonGroup whose lit segment is + * the selection's current mode. Each segment dispatches its mesh.selectMode command; the session + * no-ops a same-mode set, so re-clicking the lit segment records nothing. Renders nothing outside Edit + * mode, so the commands' outside-Edit self-guard is belt-and-braces here but load-bearing for the bare + * 1 / 2 / 3 key bindings. + */ +@Composable +internal fun MeshSelectModeButtons() { + val commands = LocalCommands.current + val session = LocalEditorSession.current ?: return + val editorMode by session.mode.collectAsState() + val meshSelection by session.meshSelection.collectAsState() + if (editorMode != EditorMode.Edit) { + return + } + val selectMode = meshSelection.selectMode + ButtonGroup( + items = + listOf( + ButtonGroupItem( + icon = LocalUmamoIcons.meshSelectVertex, + selected = selectMode == MeshSelectMode.Vertex, + onClick = { commands.invoke("mesh.selectMode.vertex") }, + contentDescription = stringResource(Res.string.cmd_mesh_select_mode_vertex), + ), + ButtonGroupItem( + icon = LocalUmamoIcons.meshSelectEdge, + selected = selectMode == MeshSelectMode.Edge, + onClick = { commands.invoke("mesh.selectMode.edge") }, + contentDescription = stringResource(Res.string.cmd_mesh_select_mode_edge), + ), + ButtonGroupItem( + icon = LocalUmamoIcons.meshSelectFace, + selected = selectMode == MeshSelectMode.Face, + onClick = { commands.invoke("mesh.selectMode.face") }, + contentDescription = stringResource(Res.string.cmd_mesh_select_mode_face), + ), + ), + ) +} + +/** + * The transform pivot selector (Blender's pivot point dropdown, the header face of the Period pie): + * the chip shows the current pivot's name; each row dispatches its transform.pivot command, so the + * pie, the palette, and this dropdown stay one behavior. + */ +@Composable +internal fun PivotModeDropdown() { + val commands = LocalCommands.current + val session = LocalEditorSession.current + val enabled = session != null + val pivotMode = session?.pivotMode?.collectAsState()?.value ?: TransformPivotMode.MedianPoint + var expanded by remember { mutableStateOf(false) } + val currentLabel = + when (pivotMode) { + TransformPivotMode.MedianPoint -> stringResource(Res.string.cmd_transform_pivot_median) + TransformPivotMode.IndividualOrigins -> stringResource(Res.string.cmd_transform_pivot_individual) + TransformPivotMode.ActiveElement -> stringResource(Res.string.cmd_transform_pivot_active) + TransformPivotMode.Cursor -> stringResource(Res.string.cmd_transform_pivot_cursor) + } + val items = + listOf( + MenuItem.Action(label = stringResource(Res.string.cmd_transform_pivot_median), onSelect = { commands.invoke("transform.pivot.median") }), + MenuItem.Action(label = stringResource(Res.string.cmd_transform_pivot_individual), onSelect = { commands.invoke("transform.pivot.individual") }), + MenuItem.Action(label = stringResource(Res.string.cmd_transform_pivot_active), onSelect = { commands.invoke("transform.pivot.active") }), + MenuItem.Action(label = stringResource(Res.string.cmd_transform_pivot_cursor), onSelect = { commands.invoke("transform.pivot.cursor") }), + ) + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = stringResource(Res.string.cmd_transform_pivot_pie), + icon = LocalUmamoIcons.transformPivot, + label = currentLabel, + enabled = enabled, + ) { + Menu( + items = items, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} + +/** + * The proportional-editing header controls (Edit mode): a concentric-rings toggle lit while + * proportional editing is on (dispatching mesh.proportional.toggle, the same command O binds to), and + * while on, a falloff dropdown whose rows dispatch the mesh.proportional.falloff commands plus the + * Connected Only toggle. + * + * The three ride one Row so the strip treats them as an indivisible group: the falloff chip and the + * connected-only toggle exist only while the enable toggle is lit, so collapsing the toggle away while + * leaving them behind would be incoherent. Renders nothing outside Edit mode. + */ +@Composable +internal fun ProportionalEditControls() { + val commands = LocalCommands.current + val shapes = LocalUmamoShapes.current + val session = LocalEditorSession.current ?: return + val editorMode by session.mode.collectAsState() + val proportionalEdit by session.proportionalEdit.collectAsState() + if (editorMode != EditorMode.Edit) { + return + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + IconButton( + icon = LocalUmamoIcons.proportionalEdit, + onClick = { commands.invoke("mesh.proportional.toggle") }, + contentDescription = stringResource(Res.string.cmd_mesh_proportional_toggle), + appearance = IconButtonAppearance.Filled(shapes.small), + size = DpSize(26.dp, 20.dp), + active = proportionalEdit != null, + ) + val activeProportionalEdit = proportionalEdit + if (activeProportionalEdit != null) { + var expanded by remember { mutableStateOf(false) } + val items = + listOf( + MenuItem.Action(label = falloffLabel(ProportionalFalloff.Smooth), onSelect = { commands.invoke("mesh.proportional.falloff.smooth") }), + MenuItem.Action(label = falloffLabel(ProportionalFalloff.Sphere), onSelect = { commands.invoke("mesh.proportional.falloff.sphere") }), + MenuItem.Action(label = falloffLabel(ProportionalFalloff.Root), onSelect = { commands.invoke("mesh.proportional.falloff.root") }), + MenuItem.Action(label = falloffLabel(ProportionalFalloff.Sharp), onSelect = { commands.invoke("mesh.proportional.falloff.sharp") }), + MenuItem.Action(label = falloffLabel(ProportionalFalloff.Linear), onSelect = { commands.invoke("mesh.proportional.falloff.linear") }), + MenuItem.Action(label = falloffLabel(ProportionalFalloff.Constant), onSelect = { commands.invoke("mesh.proportional.falloff.constant") }), + ) + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = stringResource(Res.string.header_proportional_falloff), + label = falloffLabel(activeProportionalEdit.falloff), + ) { + Menu( + items = items, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } + // Connected Only (Blender's Alt+O): influence spreads along mesh edges instead of leaping + // straight-line gaps. Lit while on; same size family as the proportional toggle. + IconButton( + icon = LocalUmamoIcons.linked, + onClick = { commands.invoke("mesh.proportional.connectedToggle") }, + contentDescription = stringResource(Res.string.cmd_mesh_proportional_connected), + appearance = IconButtonAppearance.Filled(shapes.small), + size = DpSize(26.dp, 20.dp), + active = activeProportionalEdit.connectedOnly, + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/HistorySpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/HistorySpace.kt new file mode 100644 index 0000000..2628f5d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/HistorySpace.kt @@ -0,0 +1,156 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.workspace.changeLabel + +/** + * The history space: the session's undo stack as a clickable list, oldest at the top and the live step + * highlighted (Blender's Undo History / Photoshop's History panel). Clicking a row jumps the session + * straight to that step — undoing or redoing several levels at once — and the steps ahead of the cursor + * (the redo branch) are dimmed. A trailing dot marks the last-saved step. The whole list is a projection + * the session republishes ([org.umamo.edit.EditorSession.historyView]), so it tracks edits made anywhere. + * + * @param Modifier modifier The layout modifier. + */ +@Composable +fun HistorySpace(modifier: Modifier = Modifier) { + val session = LocalEditorSession.current + if (session == null) { + Box(modifier = modifier.fillMaxSize().zebraFill(rememberLazyListState(), ROW_HEIGHT, LocalUmamoColors.current.rowStripe)) + return + } + val view by session.historyView.collectAsState() + val listState = rememberLazyListState() + // Keep the live step on screen as the cursor moves (a row click, an undo / redo from the keyboard), + // but only scroll when it has actually left the viewport so manual scrolling is never fought. + LaunchedEffect(view.cursor, view.steps.size) { + val visible = listState.layoutInfo.visibleItemsInfo + val firstVisible = visible.firstOrNull()?.index ?: 0 + val lastVisible = visible.lastOrNull()?.index ?: 0 + if (view.steps.isNotEmpty() && (view.cursor < firstVisible || view.cursor > lastVisible)) { + listState.animateScrollToItem(view.cursor) + } + } + val stripeColor = LocalUmamoColors.current.rowStripe + Box(modifier = modifier.fillMaxSize().zebraFill(listState, ROW_HEIGHT, stripeColor)) { + LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { + itemsIndexed(view.steps) { index, step -> + HistoryStepRow( + label = changeLabel(step.labelKey), + isCurrent = index == view.cursor, + isFuture = index > view.cursor, + saved = step.saved, + onClick = { session.jumpTo(index) }, + ) + } + } + VerticalScrollbarOverlay(listState) + } +} + +/** + * One step row: its [label], styled by where it sits relative to the cursor (current is the accent band, + * a step ahead of the cursor is dimmed as a pending redo), with a hover highlight and an optional saved + * dot. Clicking jumps the session to this step. + * + * @param String label The localized step label. + * @param Boolean isCurrent Whether this is the live step (the highlighted row). + * @param Boolean isFuture Whether this step is ahead of the cursor (a dimmed redo step). + * @param Boolean saved Whether this is the last-saved step (draws the trailing dot). + * @param Function onClick Jumps the session to this step. + */ +@Composable +private fun HistoryStepRow( + label: String, + isCurrent: Boolean, + isFuture: Boolean, + saved: Boolean, + onClick: () -> Unit, +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val typography = LocalUmamoTypography.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val background = + when { + isCurrent -> colors.selection + hovered -> colors.rowHover + else -> Color.Transparent + } + val labelColor = + when { + isCurrent -> colors.selectionText + isFuture -> colors.textMuted + else -> colors.text + } + Row( + modifier = + Modifier.fillMaxWidth() + .height(ROW_HEIGHT) + .background(background, shape = shapes.medium) + // NOT focusable: jumping to an entry can truncate the stack, disposing the very row that + // holds focus, and Compose leaves focus null when that happens - every keyboard shortcut + // then dies until something focusable is clicked again. + .focusProperties { canFocus = false } + .clickable(interactionSource = interaction, indication = null, onClick = onClick) + .padding(horizontal = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = label, + style = typography.bodySmall, + color = labelColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + // Fixed trailing slot so labels align whether or not the dot is present; the dot marks the saved step. + Box(modifier = Modifier.size(SAVED_DOT_SLOT), contentAlignment = Alignment.Center) { + if (saved) { + Box(modifier = Modifier.size(SAVED_DOT).background(if (isCurrent) colors.selectionText else colors.accent, CircleShape)) + } + } + } +} + +/** The fixed height of one history step row. */ +private val ROW_HEIGHT = 22.dp + +/** The diameter of the saved-step dot. */ +private val SAVED_DOT = 6.dp + +/** The fixed width reserved at the row's trailing edge for the saved dot, so labels align regardless. */ +private val SAVED_DOT_SLOT = 14.dp \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetHeaderControls.kt new file mode 100644 index 0000000..7366f48 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetHeaderControls.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.workspace.spaces + +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.FilterPopupChip +import org.umamo.ui.kit.FilterSectionLabel +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.workspace.AreaScope + +/** + * The keyform sheet's area-header controls: the track-kind filter. + * + * A sibling subtree of the sheet body rather than part of it, so both read the same [AreaScope] view state + * - which is why that state lives in its own file at internal visibility rather than private to the body. + * + * @param AreaScope scope The hosting area's scope. + */ +internal fun OverflowRowScope.keyformSheetHeaderControls(scope: AreaScope) { + val viewState = scope.spaceState(KEYFORM_SHEET_VIEW_STATE_KEY) { KeyformSheetViewState() } + flexibleSpace() + item("filter") { + FilterPopupChip( + contentDescription = stringResource(Res.string.common_filters), + icon = if (viewState.isUnfiltered) LocalUmamoIcons.filterUnfiltered else LocalUmamoIcons.filterFiltered, + ) { + FilterSectionLabel(stringResource(Res.string.common_filters)) + Checkbox( + checked = viewState.showGeometry, + onCheckedChange = { checked -> viewState.showGeometry = checked }, + label = stringResource(Res.string.keyform_sheet_filter_geometry), + ) + Checkbox( + checked = viewState.showChannels, + onCheckedChange = { checked -> viewState.showChannels = checked }, + label = stringResource(Res.string.keyform_sheet_filter_channels), + ) + Checkbox( + checked = viewState.showBlendShapes, + onCheckedChange = { checked -> viewState.showBlendShapes = checked }, + label = stringResource(Res.string.keyform_sheet_filter_blend_shapes), + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetRows.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetRows.kt new file mode 100644 index 0000000..9efa7c3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetRows.kt @@ -0,0 +1,420 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.TrackKeyRef +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.tracks.TrackKeyMark +import org.umamo.ui.tracks.TrackKeyShape +import org.umamo.ui.tracks.TrackRow +import org.umamo.ui.tracks.TrackRowTone +import org.umamo.ui.tracks.summarizedMarks + +/* + * The PuppetModel -> track rows projection: everything the keyform sheet knows about the document. + * + * This is the ONLY place the sheet touches the model. org.umamo.ui.tracks stays domain-agnostic so the + * eventual time-based animation dope sheet can reuse the same widgets, which means the mapping from + * "keyform grids on a parameter" to "rows of marks" has to live on this side of the boundary. + * + * Compose-free so the projection is unit-testable without a composition. + */ + +/** + * The kinds of thing that can own keyform tracks, which is what decides a group row's icon and its type + * subtitle. + * + * Coarser than the model's own type hierarchy on purpose: the sheet only needs enough to pick an icon, + * and every one of these already has art in the icon set. + */ +enum class KeyformOwnerKind { + Drawable, + WarpDeformer, + RotationDeformer, + Part, + Glue, +} + +/** + * Which kinds of track the sheet lists. + * + * Applied while BUILDING the projection rather than while drawing, so a filtered-out track is absent from + * the row tree entirely - an owner left with nothing loses its group row too, and a summary mark never + * stands for a key the user cannot see. + * + * @property Boolean geometry Whether geometry (deformation) tracks are listed. + * @property Boolean channels Whether channel (property) tracks are listed. + * @property Boolean blendShapes Whether blend-shape tracks are listed. + */ +class KeyformTrackFilter( + val geometry: Boolean = true, + val channels: Boolean = true, + val blendShapes: Boolean = true, +) { + companion object { + /** Everything shown - the default, and what an unfiltered sheet uses. */ + val All: KeyformTrackFilter = KeyformTrackFilter() + } +} + +/** + * The labels the projection needs, resolved by the caller from string resources. + * + * Injected rather than looked up here so the projection stays Compose-free AND localized: these are Umamo + * chrome, and the guardrail is that no UI string is hardcoded. Item names are NOT here - those are the + * user's own document data and are never translated. + * + * @property Function channelName A channel's short display label. + * @property String geometry The label for a geometry track. + * @property String blendShape The label for a blend-shape track. + * @property Function ownerKindName An owner kind's display label, shown as a group row's subtitle. + */ +class KeyformTrackLabels( + val channelName: (FormChannel) -> String, + val geometry: String, + val blendShape: String, + val ownerKindName: (KeyformOwnerKind) -> String, +) + +/** + * The sheet's projection of a rig: rows to draw, and what each row edits. + * + * The targets and owner kinds ride alongside rather than inside [TrackRow] because a row is a + * domain-agnostic widget input - org.umamo.ui.tracks must never learn what a keyform channel is - so the + * mapping back to the model stays on this side of the boundary, keyed by the row's own identity. + * + * @property List rows The group rows, each carrying its tracks as children. + * @property Map tracksByRowKey What each track row edits. A GROUP row has no entry (it names the owner, + * not a track) and neither does a blend-shape row (a blend binding is not a keyform grid, so the sheet's + * grid ops cannot touch it) - so a null lookup is the sheet's "this row is read-only" signal. + * @property Map ownerKindByRowKey The owner kind behind each GROUP row, for its icon. + * @property Map ownerByRowKey The model reference behind each GROUP row, so the row's own menu can act on + * the thing it names rather than on a track. + * @property Set groupRowKeys Every group row's key, so a caller can seed "expand all". + * @property Map summaryMembersByRowKey What each GROUP row's summary marks stand for, indexed by the + * summary ordinal the collapsed row draws them under. + * @property Boolean hiddenByFilter Whether the filter dropped at least one row that would otherwise be + * listed - what lets an empty sheet say "hidden by filters" instead of "nothing is keyed here", which + * are opposite diagnoses and only one of them is the user's own doing. + */ +class KeyformSheetProjection( + val rows: List, + val tracksByRowKey: Map, + val ownerKindByRowKey: Map, + val ownerByRowKey: Map, + val groupRowKeys: Set, + val summaryMembersByRowKey: Map>>, + val hiddenByFilter: Boolean = false, +) { + /** + * The child keys a summary mark stands for, or null when the row is not a collapsed group's. + * + * Null is the caller's signal that the mark is an ordinary one addressing a single key, so a summary + * and a plain mark never have to be told apart by anything but this lookup. + * + * @param String rowKey The row the mark was drawn on. + * @param Int summaryIndex The mark's ordinal within that row's summary. + * @return List? The keys it stands for, or null. + */ + fun summaryMembers(rowKey: String, summaryIndex: Int): List? = + summaryMembersByRowKey[rowKey]?.getOrNull(summaryIndex) +} + +/** + * The per-(item, channel) tracks keyed on [parameterId], in outliner order, grouped under their owner. + * + * One row per channel rather than one per item, because that is what the split made possible: an item can + * key opacity on a parameter its geometry never touches, and collapsing those into one row would hide + * exactly the thing the sheet exists to show. An item contributes a GEOMETRY track when its geometry grid + * keys on the parameter, one track per channel grid that does, and one per blend-shape binding driven by + * it (drawn with square marks, matching the parameter slider's own key marks). + * + * Those tracks hang under a per-owner group row so a rig with hundreds of deformers can be folded down to + * the handful being worked on. A collapsed group still shows its subtree's key positions - see + * `summarizedMarks` - so folding hides the detail, never the fact that keys are there. + * + * @param PuppetModel puppet The rig. + * @param ParameterId parameterId The parameter whose tracks to list. + * @param KeyformTrackLabels labels The localized chrome labels. + * @param KeyformTrackFilter filter Which kinds of track to list. + * @return KeyformSheetProjection The rows and their model bindings; empty when nothing keys on it. + */ +fun keyformSheetRows( + puppet: PuppetModel, + parameterId: ParameterId, + labels: KeyformTrackLabels, + filter: KeyformTrackFilter = KeyformTrackFilter.All, +): KeyformSheetProjection { + val builder = ProjectionBuilder(labels, parameterId, filter) + for (part in puppet.parts) { + builder.addOwner( + ownerKey = "part:${part.id.raw}", + ownerName = part.name, + ownerKind = KeyformOwnerKind.Part, + owner = KeyformOwner.Part(part.id), + geometryMarks = null, + channelGrids = part.channelGrids, + blendShapeMarks = emptyList(), + parameterId = parameterId, + ) + } + for (deformer in puppet.deformers) { + val geometry = + when (deformer) { + is Deformer.Warp -> deformer.geometryGrid + is Deformer.Rotation -> deformer.geometryGrid + } + val blendShapes = + when (deformer) { + is Deformer.Warp -> deformer.blendShapes + is Deformer.Rotation -> deformer.blendShapes + } + builder.addOwner( + ownerKey = "deformer:${deformer.id.raw}", + ownerName = deformer.name, + ownerKind = + when (deformer) { + is Deformer.Warp -> KeyformOwnerKind.WarpDeformer + is Deformer.Rotation -> KeyformOwnerKind.RotationDeformer + }, + owner = KeyformOwner.Deformer(deformer.id), + // Empty marks when the grid exists but is not yet keyed on THIS parameter - so the sheet still + // offers a Geometry lane to bind any targeted parameter (Angle X, Angle Y, Breath, …). + geometryMarks = marksOf(geometry, parameterId, TrackKeyShape.Circle) ?: geometry?.let { emptyList() }, + channelGrids = deformer.channelGrids, + blendShapeMarks = blendShapeMarksOf(blendShapes.map { it.parameterId to it.keys }, parameterId), + parameterId = parameterId, + ) + } + for (drawable in puppet.drawables) { + builder.addOwner( + ownerKey = "drawable:${drawable.id.raw}", + ownerName = drawable.name, + ownerKind = KeyformOwnerKind.Drawable, + owner = KeyformOwner.Drawable(drawable.id), + geometryMarks = + marksOf(drawable.geometryGrid, parameterId, TrackKeyShape.Circle) + ?: drawable.geometryGrid?.let { emptyList() } + ?: drawable.mesh?.let { emptyList() }, + channelGrids = drawable.channelGrids, + blendShapeMarks = blendShapeMarksOf(drawable.blendShapes.map { it.parameterId to it.keys }, parameterId), + parameterId = parameterId, + ) + } + val drawableNameById = puppet.drawables.associate { drawable -> drawable.id to drawable.name } + for (glue in puppet.glues) { + // Keyed by the MESH PAIR, the same stable identity KeyformOwner.Glue encodes - a list ordinal + // renumbers every later glue when one is removed, silently migrating selection and collapse state + // (and so a Delete) onto a different glue's rows. Labeled with display names, not raw ids. + builder.addOwner( + ownerKey = "glue:${glue.meshA.raw}:${glue.meshB.raw}", + ownerName = "${drawableNameById[glue.meshA] ?: glue.meshA.raw} ↔ ${drawableNameById[glue.meshB] ?: glue.meshB.raw}", + ownerKind = KeyformOwnerKind.Glue, + owner = KeyformOwner.Glue(glue.meshA, glue.meshB), + geometryMarks = null, + channelGrids = glue.channelGrids, + blendShapeMarks = emptyList(), + parameterId = parameterId, + ) + } + return builder.build() +} + +/** + * Accumulates one owner at a time into the group rows, targets, and kind map that make up a projection. + * + * A builder rather than three separate passes because the row key is the join between all three maps, and + * deriving it twice in two places is exactly how they drifted apart before. + * + * @property KeyformTrackLabels labels The localized chrome labels. + * @property ParameterId parameterId The parameter being listed, which is part of a key ref's identity. + * @property KeyformTrackFilter filter Which kinds of track to list. + */ +private class ProjectionBuilder( + private val labels: KeyformTrackLabels, + private val parameterId: ParameterId, + private val filter: KeyformTrackFilter, +) { + private val rows = ArrayList() + private val tracks = HashMap() + private val ownerKinds = HashMap() + private val owners = HashMap() + private var hiddenByFilter = false + + /** + * Adds one owner's group row and its tracks, or nothing at all when it keys nothing on the parameter. + * + * @param String ownerKey The owner's stable row-key prefix. + * @param String ownerName The owner's display name (user data - never translated). + * @param KeyformOwnerKind ownerKind What the owner is, for its icon and subtitle. + * @param KeyformOwner owner The model reference the tracks edit. + * @param List? geometryMarks Its geometry track's marks, or null when it has none. + * @param ChannelGrids channelGrids Its channel tracks. + * @param List blendShapeMarks Its blend-shape tracks' marks, one list per binding. + * @param ParameterId parameterId The parameter being listed. + */ + fun addOwner( + ownerKey: String, + ownerName: String, + ownerKind: KeyformOwnerKind, + owner: KeyformOwner, + geometryMarks: List?, + channelGrids: ChannelGrids, + blendShapeMarks: List>, + parameterId: ParameterId, + ) { + val children = ArrayList() + // Recorded per DROPPED row rather than per enabled flag: a flag that is off but hides nothing on this + // rig must not make an empty sheet blame the filter for a rig that simply keys nothing here. + if (geometryMarks != null && !filter.geometry) { + hiddenByFilter = true + } + if (geometryMarks != null && filter.geometry) { + val rowKey = "$ownerKey/geometry" + children.add( + TrackRow( + key = rowKey, + label = labels.geometry, + tone = TrackRowTone.Primary, + marks = geometryMarks, + ), + ) + // A geometry row is editable: its key POSITIONS are ordinary grid algebra even though authoring + // the forms themselves is deferred. Leaving it unaddressable made the sheet silently swallow + // every gesture on what is, after compaction, nearly every row a corpus rig shows. + tracks[rowKey] = KeyformTrackRef.Geometry(owner) + } + for ((channel, track) in channelGrids.gridsByChannel) { + val marks = marksOf(track, parameterId, TrackKeyShape.Circle) ?: continue + if (!filter.channels) { + hiddenByFilter = true + continue + } + val rowKey = "$ownerKey/${channel.name}" + children.add( + TrackRow( + key = rowKey, + label = labels.channelName(channel), + tone = TrackRowTone.Secondary, + marks = marks, + ), + ) + tracks[rowKey] = KeyformTrackRef.Channel(KeyableTarget(owner, channel)) + } + // A blend-shape binding is not a keyform grid, so it gets a row but no track ref: the sheet's ops + // would have nothing to apply, and offering a drag that reverts is worse than offering none. + if (blendShapeMarks.isNotEmpty() && !filter.blendShapes) { + hiddenByFilter = true + } + for ((bindingIndex, marks) in (if (filter.blendShapes) blendShapeMarks else emptyList()).withIndex()) { + children.add( + TrackRow( + key = "$ownerKey/blend$bindingIndex", + label = labels.blendShape, + tone = TrackRowTone.Alternate, + marks = marks, + ), + ) + } + if (children.isEmpty()) { + return + } + rows.add( + TrackRow( + key = ownerKey, + label = ownerName, + detail = labels.ownerKindName(ownerKind), + tone = TrackRowTone.Group, + children = children, + ), + ) + ownerKinds[ownerKey] = ownerKind + owners[ownerKey] = owner + } + + /** + * The keys each group row's summary marks stand for. + * + * Built from the same `summarizedMarks` the collapsed row draws with, so the ordinals line up by + * construction rather than by two implementations agreeing. A child key with no track ref (a + * blend-shape binding) is excluded at source - `summarizedMarks` only summarizes editable marks - so a + * summary mark never promises to move something that cannot move. + * + * @param TrackRow groupRow The group row to resolve. + * @return List The member keys per summary ordinal. + */ + private fun summaryMembersOf(groupRow: TrackRow): List> = + summarizedMarks(groupRow).map { summaryMark -> + groupRow.children.flatMap { child -> + child.marks + .filter { mark -> mark.editable && mark.position == summaryMark.position } + .map { mark -> TrackKeyRef(parameterId, child.key, mark.keyIndex) } + } + } + + /** The accumulated projection. */ + fun build(): KeyformSheetProjection = + KeyformSheetProjection( + rows = rows, + tracksByRowKey = tracks, + ownerKindByRowKey = ownerKinds, + ownerByRowKey = owners, + groupRowKeys = rows.map { row -> row.key }.toSet(), + summaryMembersByRowKey = rows.associate { row -> row.key to summaryMembersOf(row) }, + hiddenByFilter = hiddenByFilter, + ) +} + +/** + * The marks for one grid's axis on [parameterId], or null when the grid does not key on it. + * + * @param KeyformGrid? grid The grid to read. + * @param ParameterId parameterId The parameter to look for. + * @param TrackKeyShape shape The mark shape to emit. + * @return List? The marks, or null when the grid has no such axis. + */ +private fun marksOf(grid: KeyformGrid<*>?, parameterId: ParameterId, shape: TrackKeyShape): List? { + val axis = grid?.axes?.firstOrNull { axis -> axis.parameterId == parameterId } ?: return null + return axis.keys.mapIndexed { keyIndex, keyValue -> TrackKeyMark(keyIndex, keyValue, shape) } +} + +/** + * The marks for each blend-shape binding driven by [parameterId], drawn as squares. + * + * Squares rather than circles because a blend-shape key is not a keyform-grid key and cannot be moved or + * removed by the sheet's ops - the shape is the affordance saying so, and matches the parameter slider. + * + * @param List bindings Each binding's driving parameter and its key positions. + * @param ParameterId parameterId The parameter being listed. + * @return List The marks per matching binding, in binding order. + */ +private fun blendShapeMarksOf( + bindings: List>, + parameterId: ParameterId, +): List> = + bindings + .filter { (bindingParameter, _) -> bindingParameter == parameterId } + .map { (_, keys) -> + keys.mapIndexed { keyIndex, keyValue -> + // NOT editable: a blend row has no track ref, so none of the sheet's ops can apply - an + // editable mark would accept a drag that snaps back and a selection Delete cannot resolve. + TrackKeyMark(keyIndex, keyValue, TrackKeyShape.Square, editable = false) + } + } + +/** + * The axis domain for [parameter] - its authored range, which is what the sheet rules against. + * + * @param Parameter parameter The parameter. + * @return Pair The domain start and end. + */ +fun parameterDomain(parameter: Parameter): Pair = parameter.min to parameter.max \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetSpace.kt new file mode 100644 index 0000000..754bcca --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetSpace.kt @@ -0,0 +1,1017 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.flow.MutableStateFlow +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.ParameterSelection +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TrackKeyRef +import org.umamo.edit.dragTrackKeys +import org.umamo.edit.limitedDragFraction +import org.umamo.edit.moveTrackKey +import org.umamo.edit.moveTrackKeys +import org.umamo.edit.removeTrackKeys +import org.umamo.edit.removingKeys +import org.umamo.edit.trackKeyDragLandings +import org.umamo.edit.trackKeyIndexAfterMove +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.kit.DisclosureChevron +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.SCROLLBAR_THICKNESS +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.model.KeyformHover +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalKeyableHover +import org.umamo.ui.model.LocalLiveParams +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.properties.formChannelLabelRes +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoCursors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.umamoPointerIcon +import org.umamo.ui.tracks.TRACK_MARK_RADIUS +import org.umamo.ui.tracks.TrackAxis +import org.umamo.ui.tracks.TrackKeyMark +import org.umamo.ui.tracks.TrackRow +import org.umamo.ui.tracks.TrackRowDecor +import org.umamo.ui.tracks.TrackSheet +import org.umamo.ui.tracks.TrackSheetBackdrop +import org.umamo.ui.tracks.TrackSheetMarqueeOverlay +import org.umamo.ui.tracks.TrackSheetSeparatorOverlay +import org.umamo.ui.tracks.TrackWindow +import org.umamo.ui.tracks.TrackWindowScrollbar +import org.umamo.ui.tracks.flattenTrackRows +import org.umamo.ui.tracks.laneMarkOffsetX +import org.umamo.ui.tracks.trackWindowGestures +import org.umamo.ui.workspace.AreaScope +import org.umamo.ui.workspace.KeyformSheetSurface +import org.umamo.ui.workspace.LocalKeyformSheetViews + +/** + * The keyform sheet: for each parameter targeted in the Parameters panel, one track per (item, channel) + * keyed on it, with the marks laid out across that parameter's authored range. + * + * One SECTION per targeted parameter, stacked under a single scroll. A linked pad targets both of its + * axes at once, so a single-section sheet would show only half of what the panel says is selected. + * + * Within a section, tracks hang under a collapsible per-owner group row - one track per CHANNEL rather + * than per item, because that is the thing the per-channel split made possible and the thing this sheet + * exists to make visible: an item can key opacity on a parameter its geometry never touches. A collapsed + * group still shows its subtree's key positions, so folding hides detail, never the presence of keys. + * + * Clicking a mark scrubs the parameter onto it and selects it; dragging a mark moves the key (clamped at + * its neighbours); Delete removes the selection as one undo step; right-clicking a lane inserts a key + * there or removes the one under the pointer; Box Select (B) arms a marquee that adds the keys it + * encloses to the selection. + * + * @param AreaScope scope The hosting area's scope. + */ +@Composable +internal fun KeyformSheetSpace(scope: AreaScope) { + val colors = LocalUmamoColors.current + val puppet = LocalPuppet.current + val session = LocalEditorSession.current + val viewState = scope.spaceState(KEYFORM_SHEET_VIEW_STATE_KEY) { KeyformSheetViewState() } + + val parameterSelection by remember(session) { + session?.parameterSelection ?: MutableStateFlow(ParameterSelection()) + }.collectAsState() + + // The key selection lives on the SESSION, not on this area's view state: it is snapshotted, and undo can + // only restore what the session holds. Two open sheets therefore share one selection - the same trade + // the parameter target already makes. A sheet with no session (previews, tests) simply has none. + val selectedKeys by remember(session) { + session?.keySelection ?: MutableStateFlow(emptySet()) + }.collectAsState() + // Recording a selection as its own undo step, versus folding it into the step a following commit is + // about to record. See EditorSession.stageKeySelection for which is correct where. + val setSelectedKeys: (Set) -> Unit = { keys -> session?.setKeySelection(keys) } + val stageSelectedKeys: (Set) -> Unit = { keys -> session?.stageKeySelection(keys) } + + // Channel and track labels are Umamo chrome, so they resolve from resources here and are injected into + // the Compose-free projection. Item names are the user's own data and are never translated. + // Resolved EAGERLY into maps rather than looked up inside the injected lambdas: stringResource is + // itself composable, so a lambda the projection calls later cannot reach it. + val channelLabels = channelLabels() + val ownerKindLabels = ownerKindLabels() + val geometryLabel = stringResource(Res.string.track_geometry) + val blendShapeLabel = stringResource(Res.string.track_blend_shape) + val labels = + remember(channelLabels, ownerKindLabels, geometryLabel, blendShapeLabel) { + KeyformTrackLabels( + channelName = { channel -> channelLabels.getValue(channel) }, + geometry = geometryLabel, + blendShape = blendShapeLabel, + ownerKindName = { kind -> ownerKindLabels.getValue(kind) }, + ) + } + + // EVERY targeted parameter gets a section, not just the active one: clicking a linked pad targets both + // of its axes, and showing only one of them makes half the pad's keys invisible. Ordered by the model + // so the sections read in the same order as the panel's rows, not in selection order. + val targetedParameters = + remember(puppet, parameterSelection) { + puppet?.parameters?.filter { parameter -> parameter.id in parameterSelection.ids }.orEmpty() + } + // The backdrop is drawn whatever the sheet has to show, so an empty sheet still reads as a track region + // beside a label column rather than as blank panel. + // Either horizontal drag - panning the tracks, or resizing the label column - holds the resize cursor + // for the whole gesture. Tracked here rather than inside each gesture because the cursor has to be + // declared ONCE, on a node that exists the whole time: a pointerHoverIcon that only appears mid-drag + // is not re-resolved until the pointer next crosses a node boundary, which mid-drag it may never do. + var panningTracks by remember { mutableStateOf(false) } + var resizingColumn by remember { mutableStateOf(false) } + val horizontalDrag = panningTracks || resizingColumn + // A Column, not a Box with the window indicator layered on: as an overlay the indicator painted over the + // bottom 8dp of the last row and - because it is draggable - swallowed the pointer there, so marks in + // that strip were unclickable whenever the sheet was zoomed. As a sibling it cannot reach the rows. + val scrollState = rememberScrollState() + val markRadiusPx = with(LocalDensity.current) { TRACK_MARK_RADIUS.toPx() } + Column( + modifier = + Modifier + .fillMaxSize() + .background(colors.panelBackground) + .pointerHoverIcon( + icon = if (horizontalDrag) umamoPointerIcon(LocalUmamoCursors.ewScroll) else PointerIcon.Default, + // Only while a drag is live: otherwise the label column's own hover cursors, and the + // separator band's, must keep winning over this. + overrideDescendants = horizontalDrag, + ) + .trackWindowGestures( + window = viewState.window, + onWindowChange = { window -> viewState.window = window }, + labelColumnWidth = viewState.labelColumnWidth, + onPanningChange = { panning -> panningTracks = panning }, + ), + ) { + // The window indicator is composed AFTER this box, so it needs the weight; the box takes the rest. + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + // The track region stops short of the vertical bar, so a mark at the domain maximum is never + // underneath it. The backdrop is inset to match, or the two columns would stop lining up. + TrackSheetBackdrop( + labelColumnWidth = viewState.labelColumnWidth, + modifier = Modifier.padding(end = SCROLLBAR_THICKNESS), + ) + if (puppet == null || targetedParameters.isEmpty()) { + return@Box + } + // The filter is a projection INPUT, not a draw-time skip: a filtered-out track has to be absent + // from the row tree so an owner left with nothing loses its group row too, and so a summary mark + // never stands for a key the sheet is not showing. + val filter = + remember(viewState.showGeometry, viewState.showChannels, viewState.showBlendShapes) { + KeyformTrackFilter(viewState.showGeometry, viewState.showChannels, viewState.showBlendShapes) + } + val projections = + remember(puppet, targetedParameters, labels, filter) { + targetedParameters.map { parameter -> + parameter to keyformSheetRows(puppet, parameter.id, labels, filter) + } + } + if (!viewState.seeded) { + // In a SideEffect so it runs only for APPLIED compositions: an abandoned composition rolls back + // the snapshot write to expandedKeys but not the plain seeded gate, which would strand the sheet + // all-collapsed forever - indistinguishable from a rig with nothing keyed. + val seedKeys = projections.flatMap { (_, projection) -> projection.groupRowKeys }.toSet() + SideEffect { + if (!viewState.seeded) { + viewState.seeded = true + viewState.expandedKeys = seedKeys + } + } + } + if (projections.all { (_, projection) -> projection.rows.isEmpty() }) { + // "Nothing is keyed" and "you hid it" are opposite diagnoses, and only one of them is the + // user's own doing - saying the first while a filter is eating the rows sends them looking for + // a rig problem that is not there. + val everythingFiltered = projections.any { (_, projection) -> projection.hiddenByFilter } + EmptySheetNotice( + stringResource( + if (everythingFiltered) Res.string.keyform_sheet_all_filtered else Res.string.keyform_sheet_no_tracks, + ), + ) + return@Box + } + // The sheet's commands (delete/nudge selected keys, frame all) live at SHELL level - per-area + // registration made two open sheets clobber each other in the last-write-wins registry. The area + // only registers its command surface here; the lambdas read the live view state and the CURRENT + // projections at dispatch time, so the effect never needs to re-run on an edit or a selection + // change. A ref whose row is gone simply drops out of selectedTracks, which is what makes a stale + // selection harmless rather than dangerous. + val keyformSheetViews = LocalKeyformSheetViews.current + val currentProjections = rememberUpdatedState(projections) + // Dragging one mark of a multi-key selection drags the whole selection, which means resolving refs + // from EVERY section: a linked pad shows two, and one box select can enclose keys in both. The + // section that owns the gesture sees only its own projection, so the resolution lives here and it + // is handed down as an action. + // + // PREVIEW then COMMIT, through the same clamp: while the pointer moves, the fraction is only + // recorded (the marks draw shifted by it and the model is untouched); on release it is applied as + // one undo step. A per-move commit would push an undo entry per pixel, and a preview at the + // unclamped fraction would show the group travelling past the wall it is about to stop at. + // Reads the live projections holder rather than the composition's own `projections`, because the + // surface registered below captures this lambda once and must not go stale on the next edit. + val dragSelectedKeys: (Float, Boolean) -> Unit = { fraction, commit -> + val plan = + session?.keySelection?.value.orEmpty().mapNotNull { keyRef -> + val entry = projections.firstOrNull { (parameter, _) -> parameter.id == keyRef.parameterId } + entry?.second?.tracksByRowKey?.get(keyRef.rowKey)?.let { track -> + keyRef to Triple(track, entry.first, keyRef.keyIndex) + } + } + if (session == null || plan.isEmpty()) { + viewState.dragPreviewFraction = null + } else if (commit) { + viewState.dragPreviewFraction = null + val dragged = plan.map { (_, key) -> key } + // Asked BEFORE the drag, so the re-pointed selection can be staged into the drag's own + // snapshot: a crossing renumbers its axis, and staging afterwards left every recorded step + // holding the pre-drag ordinals for redo to restore. + val landed = session.model.value.trackKeyDragLandings(dragged, fraction) + val landedSelection = + plan.mapIndexed { position, (keyRef, _) -> keyRef.copy(keyIndex = landed.getOrElse(position) { keyRef.keyIndex }) } + .toSet() + // STAGE, EDIT, CONFIRM - see EditorSession.stageKeySelection. The confirm is what records + // the re-pointing when the drag itself declined to (clamped against a range wall). + session.stageKeySelection(landedSelection) + session.dragTrackKeys(dragged, fraction) + session.setKeySelection(landedSelection) + } else { + viewState.dragPreviewFraction = session.model.value.limitedDragFraction(plan.map { (_, key) -> key }, fraction) + } + } + val currentDragSelectedKeys = rememberUpdatedState(dragSelectedKeys) + DisposableEffect(keyformSheetViews, scope.areaId) { + if (keyformSheetViews == null) { + onDispose {} + } else { + fun selectedTracks(): List> = + session?.keySelection?.value.orEmpty().mapNotNull { keyRef -> + val entry = + currentProjections.value.firstOrNull { (parameter, _) -> parameter.id == keyRef.parameterId } + entry?.second?.tracksByRowKey?.get(keyRef.rowKey)?.let { track -> + Triple(track, entry.first, keyRef.keyIndex) + } + } + + val surface = + KeyformSheetSurface( + selectedTracks = ::selectedTracks, + hasSelection = { session?.keySelection?.value?.isNotEmpty() == true }, + frameAll = { viewState.window = TrackWindow.Full }, + armBoxSelect = { viewState.boxSelectArmed = true }, + boxSelectArmed = { viewState.boxSelectArmed }, + disarmBoxSelect = { viewState.boxSelectArmed = false }, + // The same path a mark drag commits through, so a nudge and a drag cannot disagree about + // clamping or about where the selection points afterwards. + nudgeSelection = { fraction -> currentDragSelectedKeys.value(fraction, true) }, + ) + keyformSheetViews.register(scope.areaId, surface) + onDispose { keyformSheetViews.unregister(scope.areaId, surface) } + } + } + // ONE outer scroll over all the sections; each TrackSheet lays its rows out eagerly for exactly this + // reason (a lazy list nested in a scroll fights it for the gesture). + Column( + modifier = + Modifier + .fillMaxSize() + .padding(end = SCROLLBAR_THICKNESS) + .verticalScroll(scrollState), + ) { + for ((parameter, projection) in projections) { + key(parameter.id) { + val collapsed = parameter.id in viewState.collapsedParameters + // The section header names which parameter the ruler below belongs to, and folds it + // away. Shown even for a single section: without it the sheet is a set of numbers with + // no stated domain. + SectionHeader( + name = parameter.name, + collapsed = collapsed, + onToggle = { + viewState.collapsedParameters = + if (collapsed) { + viewState.collapsedParameters - parameter.id + } else { + viewState.collapsedParameters + parameter.id + } + }, + ) + if (collapsed) { + // Folded: the header alone, so a linked pad's other axis is one click away. + } else if (projection.rows.isEmpty()) { + Box( + modifier = Modifier.fillMaxWidth().padding(12.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = + stringResource( + if (projection.hiddenByFilter) { + Res.string.keyform_sheet_all_filtered + } else { + Res.string.keyform_sheet_no_tracks + }, + ), + style = LocalUmamoTypography.current.bodyMedium, + color = colors.textMuted, + ) + } + } else { + KeyformSheetSection( + parameter = parameter, + projection = projection, + selectedKeys = selectedKeys, + window = viewState.window, + labelColumnWidth = viewState.labelColumnWidth, + expandedKeys = viewState.expandedKeys, + onToggleExpanded = { row -> + viewState.expandedKeys = + if (row.key in viewState.expandedKeys) { + viewState.expandedKeys - row.key + } else { + viewState.expandedKeys + row.key + } + }, + onSelectedKeysChange = setSelectedKeys, + onStageSelectedKeys = stageSelectedKeys, + onDragSelectedKeys = dragSelectedKeys, + // The preview fraction is of the parameter's RANGE; a lane draws in its own domain units, so + // each section converts with its own span - which is what keeps a linked pad's two axes moving + // together on screen despite unrelated ranges. + selectedMarkDragDelta = { + viewState.dragPreviewFraction?.times( + maxOf(parameter.max, parameter.min) - minOf(parameter.max, parameter.min), + ) + }, + onLaneBounds = { row, bounds -> viewState.laneBounds[row.key] = bounds }, + ) + } + } + } + } + TrackSheetSeparatorOverlay( + labelColumnWidth = viewState.labelColumnWidth, + onLabelColumnWidthChange = { width -> viewState.labelColumnWidth = width }, + onDraggingChange = { dragging -> resizingColumn = dragging }, + ) + // Above the separator, so while armed the marquee takes the drag rather than the column resize. + TrackSheetMarqueeOverlay( + armed = viewState.boxSelectArmed, + onSelect = { region, additive -> + val enclosed = + keysWithin( + region, + projections, + viewState.laneBounds, + markRadiusPx, + viewState.window, + viewState.expandedKeys, + viewState.collapsedParameters, + ) + setSelectedKeys(if (additive) selectedKeys + enclosed else enclosed) + }, + onDismiss = { viewState.boxSelectArmed = false }, + ) + VerticalScrollbarOverlay(scrollState) + } + // Beneath the scroll region rather than over it: it describes the HORIZONTAL view, and it hides + // itself entirely when the whole domain is framed. + TrackWindowScrollbar( + window = viewState.window, + onWindowChange = { window -> viewState.window = window }, + labelColumnWidth = viewState.labelColumnWidth, + modifier = Modifier.padding(end = SCROLLBAR_THICKNESS), + ) + } +} + +/** + * A parameter section's header: its name and the chevron that folds the section away. + * + * @param String name The parameter's display name (user data - never translated). + * @param Boolean collapsed Whether the section is folded. + * @param Function onToggle Invoked when the header is clicked. + */ +@Composable +private fun SectionHeader(name: String, collapsed: Boolean, onToggle: () -> Unit) { + val colors = LocalUmamoColors.current + Row( + modifier = + Modifier + .fillMaxWidth() + .background(colors.tabBackground) + // NOT focusable: a clickable takes focus, and a row that can be disposed by the very edit + // beside it leaves Compose with no focus owner, which kills every keyboard shortcut. + .focusProperties { canFocus = false } + .clickable(onClick = onToggle) + .padding(horizontal = 6.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + DisclosureChevron(expanded = !collapsed, tint = colors.textMuted, glyphSize = 14.dp) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = name, style = LocalUmamoTypography.current.labelMedium, color = colors.textMuted) + } +} + +/** + * One parameter's ruler and tracks. + * + * Split out from [KeyformSheetSpace] so each section's marks recompose against their own projection and + * playhead rather than the whole sheet's. + * + * @param Parameter parameter The parameter this section's domain comes from. + * @param KeyformSheetProjection projection Its tracks and their owning targets. + * @param Set selectedKeys The sheet-wide key selection (shared across sections). + * @param TrackWindow window The visible slice of the parameter's range, shared by every section. + * @param Dp labelColumnWidth The label column's width, shared by every section. + * @param Set expandedKeys The open group rows, shared by every section. + * @param Function onToggleExpanded Publishes a chevron click. + * @param Function onSelectedKeysChange Publishes a new selection, recording it as its own undo step. + * @param Function onStageSelectedKeys Publishes a new selection WITHOUT a step of its own, for a gesture + * that commits one immediately afterwards (or has just committed one) - see EditorSession.stageKeySelection. + * @param Function onDragSelectedKeys Previews (commit = false) or applies (commit = true) a drag of the + * WHOLE selection by a fraction of each key's parameter range. Only the sheet can do this - the + * selection spans sections and a section sees only its own projection. + * @param Function selectedMarkDragDelta The in-flight group drag in THIS section's domain units, drawn on + * its selected marks so they travel with the one under the hand. A lambda so the per-frame read lands in + * the lane's draw scope rather than recomposing the sheet. + * @param Function onLaneBounds Reports each lane's window bounds, for the box-select marquee. + */ +@Composable +private fun KeyformSheetSection( + parameter: Parameter, + projection: KeyformSheetProjection, + selectedKeys: Set, + window: TrackWindow, + labelColumnWidth: Dp, + expandedKeys: Set, + onToggleExpanded: (TrackRow) -> Unit, + onSelectedKeysChange: (Set) -> Unit, + onStageSelectedKeys: (Set) -> Unit, + onDragSelectedKeys: (Float, Boolean) -> Unit, + selectedMarkDragDelta: () -> Float?, + onLaneBounds: (TrackRow, Rect) -> Unit, +) { + val session = LocalEditorSession.current + val liveParams = LocalLiveParams.current + val keyableHover = LocalKeyableHover.current + val commands = LocalCommands.current + val colors = LocalUmamoColors.current + val icons = LocalUmamoIcons + val keymap = LocalKeymap.current + val insertLabel = stringResource(Res.string.cmd_keyform_insert) + // Resolved in COMPOSITION, not in the menu lambda: stringResource only runs while composing, and + // the lambda fires on a pointer event. + val selectOwnerLabels = + ownerKindLabels().mapValues { (_, kindLabel) -> + stringResource( + Res.string.keyform_sheet_select_owner, + kindLabel, + ) + } + val deleteLabel = stringResource(Res.string.cmd_keyform_delete) + // The playhead follows the live scrub through snapshotFlow rather than a composition read: + // observedValues is one whole-map state replaced on every preview move of ANY parameter, so reading + // it while composing invalidated the entire sheet per pointer move (ParametersSpace documents the + // same rule). The initial read is deliberately unobserved; the flow delivers every later change to + // this section's own state alone. + var playhead by remember(parameter.id) { + mutableStateOf( + Snapshot.withoutReadObservation { liveParams?.observedValues?.get(parameter.id) } ?: parameter.default, + ) + } + LaunchedEffect(liveParams, parameter.id) { + snapshotFlow { liveParams?.observedValues?.get(parameter.id) ?: parameter.default } + .collect { value -> playhead = value } + } + val rows = + remember(projection, selectedKeys, parameter.id) { + projection.rows.map { row -> row.withSelection(parameter.id, selectedKeys) } + } + val (domainStart, domainEnd) = parameterDomain(parameter) + // The section draws the VISIBLE slice of its parameter, which is what makes one normalized window + // drive two axes with unrelated ranges at the same screen positions. + val axis = window.axisOver(TrackAxis(domainStart, domainEnd)) + TrackSheet( + rows = rows, + axis = axis, + // The playhead is the live scrub value, so the sheet reads as a view OF the current pose rather + // than a static list beside it. + playhead = playhead, + modifier = Modifier.fillMaxWidth(), + labelColumnWidth = labelColumnWidth, + expandedKeys = expandedKeys, + onToggleExpanded = onToggleExpanded, + decorFor = { row -> + // Only group rows carry an icon: they are the rows that name a thing in the rig. A channel + // track names a property, and several of those (opacity, draw order) have no icon in the set - + // giving some of them art and not others would read as a missing glyph rather than a category. + when (projection.ownerKindByRowKey[row.key]) { + KeyformOwnerKind.Drawable -> TrackRowDecor(icons.mesh, colors.outlinerObjectTint) + KeyformOwnerKind.Part -> TrackRowDecor(icons.part, colors.outlinerObjectTint) + KeyformOwnerKind.WarpDeformer -> TrackRowDecor(icons.warpDeformer, colors.outlinerDeformTint) + KeyformOwnerKind.RotationDeformer -> TrackRowDecor(icons.rotationDeformer, colors.outlinerDeformTint) + KeyformOwnerKind.Glue -> TrackRowDecor(icons.linked, colors.outlinerDeformTint) + null -> TrackRowDecor() + } + }, + // Clicking a mark selects it AND scrubs to it: selection is what Delete acts on, and scrubbing is + // how you land the pose exactly on a key without hunting with the slider. The two never conflict, + // so doing both is strictly more useful than choosing. + // + // SHIFT+click is the exception on both counts: it TOGGLES rather than replaces (toggle, not + // add-only, because it is the only gesture that can take a single mark back OUT of a selection + // without starting over), and it does NOT scrub - building a multi-key selection is a selection + // act, and having the pose jump to each mark on the way would fight the very comparison the + // selection is being built for. The marquee stays add-only, which is the convention for a + // region gesture; a click is where toggling belongs. + onMarkClick = { row, mark, additive -> + // A summary mark stands for every child key stacked at that value, so clicking it selects all + // of them - which is what makes Delete and the arrow nudges work on a folded group too. + val clicked = + projection.summaryMembers(row.key, mark.keyIndex)?.toSet() + ?: setOf(TrackKeyRef(parameter.id, row.key, mark.keyIndex)) + if (additive) { + // Nothing follows a shift-click, so it records a step of its own. + onSelectedKeysChange(selectionAfterAdditiveClick(selectedKeys, clicked)) + } else if (session != null && liveParams != null) { + // ONE undo step for the whole click, named for the selection rather than for the scrub it + // implies: the user clicked a keyframe, and the pose landing on it is the consequence. + // Recorded through the session rather than staged behind liveParams.commit because a click on + // the key the pose ALREADY sits on moves nothing - the pose commit would short-circuit and the + // selection would never reach history at all. + liveParams.preview(parameter.id, mark.position) + session.selectKeysAtPose(clicked, liveParams.values) + } else { + onSelectedKeysChange(clicked) + } + }, + // Pressing or dragging empty track scrubs the parameter, so the whole track region works like the + // ruler of a timeline rather than only the marks being live. The press also drops the key + // selection, matching every other list in the editor. + onTrackScrub = { _, value, additive -> + // A SHIFT press keeps the selection: shift-clicking is how a multi-key selection is built, and a + // near-miss on a mark should not wipe the work rather than merely failing to add to it. + if (!additive) { + // Staged: onTrackScrubEnd commits the scrub, and the clear belongs to that same step. + // It confirms the clear there too - the commit records nothing when the press lands on the + // value the playhead already holds, and a selection lost that way has no undo. + onStageSelectedKeys(emptySet()) + } + // Clamped again at the model boundary, not only in the lane: the lane clamps to the VISIBLE + // window, which is a subrange, but this is the call that reaches the evaluator - and a pose + // outside the parameter's range brackets nothing, so every entity keyed on it disappears. + // The minOf/maxOf form tolerates a reversed (min > max) range from a malformed import, like + // every sibling clamp in this feature - a plain coerceIn throws on one mid-gesture. + liveParams?.preview( + parameter.id, + value.coerceIn(minOf(parameter.min, parameter.max), maxOf(parameter.min, parameter.max)), + ) + }, + // One undo step per gesture, at its end - the same contract a slider drag has. + onTrackScrubEnd = { _, _ -> + liveParams?.commit(setOf(parameter.id)) + // CONFIRM the selection the press staged (see EditorSession.stageKeySelection): a no-op when the + // commit above folded it into the scrub's step, and a step of its own when the commit declined + // because the pose never moved. Read live rather than from `selectedKeys`, which is this + // composition's snapshot of a selection the press has since changed. + session?.setKeySelection(session.keySelection.value) + }, + // The whole selection follows the mark under the hand rather than snapping to it on release, + // which is what makes a group drag read as moving keys instead of as a deferred command. The + // model is untouched until the release; only what is DRAWN moves. + onMarkDrag = { row, mark, at -> + val dragged = TrackKeyRef(parameter.id, row.key, mark.keyIndex) + groupDragFraction(parameter, selectedKeys, dragged, mark, at)?.let { fraction -> + onDragSelectedKeys(fraction, false) + } + }, + selectedMarkDragDelta = selectedMarkDragDelta, + onMarkDragEnd = { row, mark, releasedAt -> + val members = projection.summaryMembers(row.key, mark.keyIndex) + val track = projection.tracksByRowKey[row.key] + if (session != null && members != null) { + // Every member's ordinal may have changed on its own track, so the safe answer is to drop the + // selection rather than guess - and to drop it BEFORE the move, so the move's own snapshot + // records the cleared selection instead of a second step having to. + onStageSelectedKeys(emptySet()) + // Dragging a summary moves everything it stands for, to one destination, as one undo step - + // they were stacked at a value and stay stacked. + session.moveTrackKeys( + members.mapNotNull { member -> + projection.tracksByRowKey[member.rowKey]?.let { memberTrack -> + Triple(memberTrack, parameter, member.keyIndex) + } + }, + releasedAt, + ) + // CONFIRM: the move records nothing when the summary is released where it was picked up, + // and the clear above would then vanish with it. + session.setKeySelection(emptySet()) + } else if (session != null && track != null) { + val dragged = TrackKeyRef(parameter.id, row.key, mark.keyIndex) + val groupFraction = groupDragFraction(parameter, selectedKeys, dragged, mark, releasedAt) + if (groupFraction != null) { + onDragSelectedKeys(groupFraction, true) + } else { + // A key may cross its neighbours, which renumbers the axis - so the selection is + // re-pointed at the ordinal the key lands on. Keeping the old ordinal would silently + // leave the selection on whichever key took its place. + if (dragged in selectedKeys) { + // Asked BEFORE the move so the re-pointing can be STAGED into the move's own snapshot; + // staging afterwards left every recorded step holding the pre-move ordinal, which redo + // then restored onto the wrong key. CONFIRMED after, for a release that moved nothing. + val landedIndex = + session.model.value.trackKeyIndexAfterMove(track, parameter, mark.keyIndex, releasedAt) + val landedSelection = + selectedKeys - dragged + TrackKeyRef(parameter.id, row.key, landedIndex) + onStageSelectedKeys(landedSelection) + session.moveTrackKey(track, parameter, mark.keyIndex, releasedAt) + session.setKeySelection(landedSelection) + } else { + session.moveTrackKey(track, parameter, mark.keyIndex, releasedAt) + } + } + } + }, + // Publishing the hovered row is what lets `I` / `Alt+I` aim at a track the way they already aim at a + // Properties row: point at it and press. The projection maps the row back to what it edits; a row + // with no track ref (a group header, a blend-shape binding) publishes nothing, so the shortcut + // falls through to its notice rather than acting on something it cannot address. The hover carries + // THIS section's parameter - the selection's active member can be the other axis of a linked pad. + onLaneBounds = { row, bounds -> onLaneBounds(row, bounds) }, + onLaneHover = { row, hit -> + projection.tracksByRowKey[row.key]?.let { track -> + if (hit == null) { + keyableHover?.exit(track) + } else { + keyableHover?.enter(KeyformHover(track, hit.value, hit.mark?.keyIndex, parameter.id, row.key)) + } + } + }, + // The LABEL half of a row answers a different question from the lane: the lane is about a key at a + // position, the label is about the thing the row names. Only a GROUP row names a rig entity, and + // only a selectable one - a glue has no SelectionTarget - so every other row gets an empty list and + // no gesture at all. + labelMenuItems = { row -> + val target = projection.ownerByRowKey[row.key]?.let(::selectionTargetOf) + val ownerKind = projection.ownerKindByRowKey[row.key] + if (session == null || target == null || ownerKind == null) { + emptyList() + } else { + listOf( + MenuItem.Action( + label = selectOwnerLabels.getValue(ownerKind), + onSelect = { session.setSelection(Selection(setOf(target), target)) }, + ), + ) + } + }, + laneMenuItems = { hit -> + // A group row names the owner rather than a track, and a blend-shape row is not a keyform grid - + // neither has a track ref, so both get an empty menu rather than actions that silently do nothing. + // Each item dispatches THROUGH the registry rather than calling the session, so the menu can + // never drift from the shortcut it advertises. The popup owns the pointer by the time an item + // fires and the live lane hover is gone, so the clicked spot is re-published for the command's + // dispatch-time read and cleared right after. + val track = projection.tracksByRowKey[hit.row.key] + val hitMark = hit.mark + val summaryMembers = hitMark?.let { mark -> projection.summaryMembers(hit.row.key, mark.keyIndex) } + when { + // A summary mark stands for several keys, so its menu removes them all in one step. There + // is no Insert counterpart: a folded group cannot say which of its tracks a new key belongs + // on, and picking one would be a guess. + session != null && summaryMembers != null -> + listOf( + MenuItem.Action( + label = deleteLabel, + onSelect = { + // Reconciled rather than blanket-cleared: dropping the whole selection here + // deselected the user's marks for deleting an unrelated one. + val removed = + summaryMembers + .map { member -> TrackKeyRef(parameter.id, member.rowKey, member.keyIndex) } + .toSet() + session.removingKeys(removed) { + session.removeTrackKeys( + summaryMembers.mapNotNull { member -> + projection.tracksByRowKey[member.rowKey]?.let { memberTrack -> + Triple(memberTrack, parameter, member.keyIndex) + } + }, + ) + } + }, + ), + ) + + session == null || track == null -> emptyList() + hitMark != null -> + listOf( + MenuItem.Action( + label = deleteLabel, + onSelect = { + // The row key rides the hover, so the removal reconciles the key selection itself - + // see EditorSession.removeKeyOnTrack. Without it, deleting a selected mark would leave + // its ref on the ordinal the removal freed, which is the neighbour: the mark to the + // right would light up as selected and the next Delete would take it. + keyableHover?.enter( + KeyformHover(track, hit.value, hitMark.keyIndex, parameter.id, hit.row.key), + ) + commands.invoke("keyform.delete") + keyableHover?.exit(track) + }, + shortcut = keymap.chordFor("keyform.delete")?.let { chord -> formatAccelerator(chord) }, + ), + ) + + else -> + listOf( + MenuItem.Action( + label = insertLabel, + onSelect = { + keyableHover?.enter( + KeyformHover( + track, + hit.value, + keyIndex = null, + parameterId = parameter.id, + rowKey = hit.row.key, + ), + ) + commands.invoke("keyform.insert") + keyableHover?.exit(track) + }, + shortcut = keymap.chordFor("keyform.insert")?.let { chord -> formatAccelerator(chord) }, + ), + ) + } + }, + ) +} + +/** + * The fraction of [parameter]'s range a drag of [mark] to [at] represents, or null when it is not a GROUP + * drag at all. + * + * Null - meaning "handle this as an ordinary single-key move" - whenever the dragged mark is not itself + * selected, or is the only thing selected, or the parameter has no range to take a fraction of. + * + * A fraction rather than an absolute delta because a selection can span two parameters (a linked pad shows + * both axes at once) whose ranges differ by orders of magnitude. Within ONE parameter a fraction of its + * range IS the distance the hand moved. + * + * Shared by the live preview and the release so the two cannot disagree about which gesture this is - the + * failure mode being a drag that previews as a group and commits as a single key, or the reverse. + * + * @param Parameter parameter The section's parameter. + * @param Set selectedKeys The sheet-wide key selection. + * @param TrackKeyRef dragged The key under the hand. + * @param TrackKeyMark mark Its mark, for the position the drag started from. + * @param Float at The pointer's current (or released) domain position. + * @return Float? The signed fraction, or null when this is not a group drag. + */ +private fun groupDragFraction( + parameter: Parameter, + selectedKeys: Set, + dragged: TrackKeyRef, + mark: TrackKeyMark, + at: Float, +): Float? { + if (dragged !in selectedKeys || selectedKeys.size < 2) { + return null + } + val span = maxOf(parameter.max, parameter.min) - minOf(parameter.max, parameter.min) + return if (span > 0f) (at - mark.position) / span else null +} + +/** + * [current] with [clicked] toggled in or out - what a Shift+click on a mark leaves behind. + * + * TOGGLE rather than add-only because a click is the only gesture that can take a single mark back OUT of + * a selection without starting over; the marquee stays add-only, which is the convention for a region + * gesture. + * + * A summary mark's whole membership toggles as ONE unit - all of them or none - so a folded group cannot + * end up half-selected by a gesture that showed the user a single mark. Partly-selected therefore counts + * as "not selected" and the click completes it, which is the reading that lets a second click undo the + * first. + * + * Internal rather than private so the rule can be pinned without a composition: the UI test can only + * reach as far as "Shift arrived", and what the sheet then DOES with it is the part worth stating. + * + * @param Set current The selection before the click. + * @param Set clicked The keys the clicked mark stands for - one, or a summary's whole membership. + * @return Set The selection after it. + */ +internal fun selectionAfterAdditiveClick(current: Set, clicked: Set): Set = + if (clicked.isNotEmpty() && clicked.all { key -> key in current }) current - clicked else current + clicked + +/** + * The selection target a keyform owner names, or null when it names nothing selectable. + * + * Glue is the null case, and deliberately so: it has no SelectionTarget, no outliner entry, and is + * addressed by a mesh pair rather than an id, so there is nothing for a "select this" to put in the + * selection. See TODO.md's Claude Note on glue having no editable home. + * + * @param KeyformOwner owner The row's owner. + * @return SelectionTarget? What to select, or null. + */ +private fun selectionTargetOf(owner: KeyformOwner): SelectionTarget? = + when (owner) { + is KeyformOwner.Drawable -> SelectionTarget.Drawable(owner.id) + is KeyformOwner.Part -> SelectionTarget.Part(owner.id) + is KeyformOwner.Deformer -> SelectionTarget.Deformer(owner.id) + is KeyformOwner.Glue -> null + } + +/** + * This row and its whole subtree with each mark's selected flag resolved against [selectedKeys]. + * + * Recursive because selection is per-track but the tree is what gets rendered, and a child's marks have to + * carry the flag whether or not its parent happens to be expanded. + * + * @param ParameterId parameterId The section's parameter, which is part of a key's identity. + * @param Set selectedKeys The current selection. + * @return TrackRow The row with selection applied. + */ +private fun TrackRow.withSelection(parameterId: ParameterId, selectedKeys: Set): TrackRow = + copy( + marks = + marks.map { mark -> + mark.copy( + selected = + TrackKeyRef( + parameterId, + key, + mark.keyIndex, + ) in selectedKeys, + ) + }, + children = children.map { child -> child.withSelection(parameterId, selectedKeys) }, + ) + +/** + * Every key the window-space [region] encloses, across every section. + * + * Resolved against the lanes' own reported bounds rather than computed from row heights: sections fold, + * groups collapse, and the sheet scrolls, so the only reliable answer to "where is this row" is the one + * the row gave during layout. A mark counts when its lane overlaps the region vertically AND its drawn + * position falls inside it horizontally. + * + * Two things have to match what is ON SCREEN rather than what is in the model, or the marquee selects keys + * the user cannot see: + * + * - The rows walked are the FLATTENED, currently-visible ones ([flattenTrackRows] with the sheet's own + * expand state, skipping folded sections), not the whole tree. laneBounds is never pruned - a lane + * that leaves composition simply stops reporting - so a collapsed group's children keep their last + * rectangles forever, and walking the tree blind would keep hitting them. + * - The axis is the WINDOWED one, so a zoomed sheet maps a mark to the pixel it is actually drawn at. + * The full-range axis put every mark at the wrong x the moment the sheet was not framed to the whole + * domain. + * + * Internal rather than private so the resolution can be tested without a composition: it is pure over plain + * data, and a wrong answer here - an un-windowed axis, or a walk that reaches collapsed rows - is a + * silently wrong selection, not a crash, so a direct test is the only way to catch it. + * + * @param Rect region The marquee, in window coordinates. + * @param List projections Each targeted parameter and its tracks. + * @param Map laneBounds Each row key's last reported window bounds. + * @param Float markRadiusPx The sheet's mark radius, which is also its lane end inset. + * @param TrackWindow window The visible slice of each parameter's range, shared by every section. + * @param Set expandedKeys The open group rows, which decide which lanes exist. + * @param Set collapsedParameters The folded sections, whose rows are not on screen at all. + * @return Set The enclosed keys. + */ +internal fun keysWithin( + region: Rect, + projections: List>, + laneBounds: Map, + markRadiusPx: Float, + window: TrackWindow, + expandedKeys: Set, + collapsedParameters: Set, +): Set { + val enclosed = mutableSetOf() + for ((parameter, projection) in projections) { + if (parameter.id in collapsedParameters) { + continue + } + val (domainStart, domainEnd) = parameterDomain(parameter) + val axis = window.axisOver(TrackAxis(domainStart, domainEnd)) + for (line in flattenTrackRows(projection.rows, expandedKeys)) { + // Only rows with a track ref: a group header names an owner and a blend-shape row is not a + // keyform grid, so neither has keys a selection could act on. + val row = line.row + val bounds = laneBounds[row.key] ?: continue + if (!projection.tracksByRowKey.containsKey(row.key) || !bounds.overlapsVertically(region)) { + continue + } + for (mark in row.marks) { + // The same mapping the marks were drawn with, from the same function - re-deriving the end + // inset here is how a marquee drifts by exactly one mark width. + val drawnX = bounds.left + laneMarkOffsetX(axis, mark.position, bounds.width, markRadiusPx) + if (drawnX in region.left..region.right) { + enclosed.add(TrackKeyRef(parameter.id, row.key, mark.keyIndex)) + } + } + } + } + return enclosed +} + +/** + * Whether two rectangles share any vertical extent - the marquee's row test. + * + * @param Rect other The rectangle to test against. + * @return Boolean True when their vertical extents overlap. + */ +private fun Rect.overlapsVertically(other: Rect): Boolean = top < other.bottom && bottom > other.top + +/** The centered muted notice shown when the sheet has nothing to draw. */ +@Composable +private fun EmptySheetNotice(message: String) { + Box(modifier = Modifier.fillMaxSize().padding(12.dp), contentAlignment = Alignment.Center) { + Text( + text = message, + style = LocalUmamoTypography.current.bodyMedium, + color = LocalUmamoColors.current.textMuted, + ) + } +} + +/** + * Every channel's localized short label, resolved in one pass. + * + * A map rather than a function because the projection is Compose-free and calls its label lookup from + * ordinary code, where stringResource is unreachable. The labels themselves come from + * [formChannelLabelRes], shared with the export report so a channel reads the same in both. + * + * @return Map The label per channel. + */ +@Composable +private fun channelLabels(): Map = + FormChannel.entries.associateWith { channel -> stringResource(formChannelLabelRes(channel)) } + +/** + * Every owner kind's localized label, resolved in one pass - the subtitle under a group row's name. + * + * @return Map The label per owner kind. + */ +@Composable +private fun ownerKindLabels(): Map = + KeyformOwnerKind.entries.associateWith { kind -> + when (kind) { + KeyformOwnerKind.Drawable -> stringResource(Res.string.owner_kind_drawable) + KeyformOwnerKind.WarpDeformer -> stringResource(Res.string.owner_kind_warp_deformer) + KeyformOwnerKind.RotationDeformer -> stringResource(Res.string.owner_kind_rotation_deformer) + KeyformOwnerKind.Part -> stringResource(Res.string.owner_kind_part) + KeyformOwnerKind.Glue -> stringResource(Res.string.owner_kind_glue) + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetViewState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetViewState.kt new file mode 100644 index 0000000..4365626 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetViewState.kt @@ -0,0 +1,148 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.umamo.runtime.model.ParameterId +import org.umamo.ui.tracks.TRACK_LABEL_COLUMN_DEFAULT_WIDTH +import org.umamo.ui.tracks.TRACK_LABEL_COLUMN_MAX_WIDTH +import org.umamo.ui.tracks.TRACK_LABEL_COLUMN_MIN_WIDTH +import org.umamo.ui.tracks.TrackWindow +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.finiteFloatOf +import org.umamo.ui.workspace.floatListOf +import org.umamo.ui.workspace.stringArrayOrNull +import org.umamo.ui.workspace.stringListOf + +/** The key this space's view state is stored under on its hosting area, and its member in an area block (UMA §7.3). */ +internal const val KEYFORM_SHEET_VIEW_STATE_KEY = "keyformSheet" + +/** + * The keyform sheet's per-area view state: the label column's width, which groups are open, the zoom window. + * + * On the AreaScope rather than the session because these are how one area is LOOKING at the rig, not what + * the rig is - two sheets side by side may reasonably be folded differently, and none of it belongs in undo. + * + * The SELECTED KEYS used to live here on that reasoning and no longer do: undo restores session state, so a + * selection that undo is meant to bring back has to be session state, and that outranks letting two sheets + * disagree about what is selected. It is EditorSession.keySelection now, alongside the object, mesh, and + * parameter selections, which all made the same trade. + */ +internal class KeyformSheetViewState : PersistentSpaceState { + /** The label column's width, dragged on the separator. */ + var labelColumnWidth: Dp by mutableStateOf(TRACK_LABEL_COLUMN_DEFAULT_WIDTH) + + /** The group rows whose tracks are shown. */ + var expandedKeys: Set by mutableStateOf(emptySet()) + + /** + * Whether [expandedKeys] has been seeded yet. + * + * A fresh sheet opens with every group expanded (an all-collapsed sheet looks identical to one with + * nothing keyed), but "collapse everything" has to stay reachable - so the seed happens ONCE rather + * than whenever the set is empty. + */ + var seeded: Boolean = false + + /** + * The parameter sections folded away. + * + * COLLAPSED rather than expanded, so a section that appears later (targeting a second parameter) opens + * rather than arriving invisible. Sections matter for a linked pad, where one parameter's tracks can + * bury the other's. + */ + var collapsedParameters: Set by mutableStateOf(emptySet()) + + /** + * The visible slice of every section's domain. + * + * ONE window for the whole area, normalized, so zooming works like a timeline's: every track and both + * of a linked pad's sections move together. Per-track zoom has no precedent in any editor with tracks + * and would make comparing two rows - the reason the sheet exists - impossible. + */ + var window: TrackWindow by mutableStateOf(TrackWindow.Full) + + /** Whether a box-select marquee is awaiting its drag. */ + var boxSelectArmed: Boolean by mutableStateOf(false) + + /** + * The in-flight group drag, as a signed fraction of each dragged key's parameter range, or NULL when + * no group drag is in flight. + * + * Null rather than 0f for "none", because 0f is a real state: a group whose most constrained member is + * already at its parameter's end clamps the whole drag to a standstill, and the mark under the hand + * has to stop with the rest rather than run on to the pointer and snap back on release. + * + * Held on the SHEET rather than in the lane that owns the gesture because the selection it previews + * spans rows and sections, and a lane knows only its own marks. Already clamped to the group's most + * constrained member (`limitedDragFraction`), so what is drawn is what the release will commit. + */ + var dragPreviewFraction: Float? by mutableStateOf(null) + + /** + * Where each lane sits, in WINDOW coordinates, so a marquee drawn over the whole scrolling sheet can + * say which rows it crossed without either side knowing the other's scroll offset. + * + * A plain map rather than snapshot state: it is written during layout and only ever read when a + * marquee is released, so observing it would recompose the sheet on every scroll for nothing. + */ + val laneBounds: MutableMap = mutableMapOf() + + /** Whether GEOMETRY tracks are listed. */ + var showGeometry: Boolean by mutableStateOf(true) + + /** Whether CHANNEL tracks (opacity, draw order, the colours, the flips) are listed. */ + var showChannels: Boolean by mutableStateOf(true) + + /** Whether BLEND-SHAPE tracks are listed. */ + var showBlendShapes: Boolean by mutableStateOf(true) + + /** Whether every track kind is shown - what the header's funnel glyph reports. */ + val isUnfiltered: Boolean get() = showGeometry && showChannels && showBlendShapes + + /** + * The keyform sheet's member of its area block. The marquee arm, the drag preview, and the lane bounds are a + * gesture in flight and layout bookkeeping, so they are not written. + * + * @return JsonObject The member, every known key named. + */ + override fun toJson(): JsonObject = + buildJsonObject { + // UMA §7.3: `expanded` is exactly the group rows shown, and is absent until the sheet has seeded itself + // with every group open - an unseeded sheet has no fold state of its own to save. + put("expanded", if (seeded) JsonArray(expandedKeys.sorted().map(::JsonPrimitive)) else JsonNull) + put("collapsedParameters", stringArrayOrNull(collapsedParameters.map { parameterId -> parameterId.raw })) + put("hidden", stringArrayOrNull(listOfNotNull("geometry".takeUnless { showGeometry }, "channels".takeUnless { showChannels }, "blendShapes".takeUnless { showBlendShapes }))) + put("window", if (window == TrackWindow.Full) JsonNull else JsonArray(listOf(JsonPrimitive(window.start), JsonPrimitive(window.end)))) + put("labelColumnWidth", if (labelColumnWidth == TRACK_LABEL_COLUMN_DEFAULT_WIDTH) JsonNull else JsonPrimitive(labelColumnWidth.value)) + } + + /** + * Takes the keyform sheet state a document was saved with. A saved fold state counts as the seed, so the + * open-everything pass a fresh sheet runs does not overwrite it. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + stringListOf(tree, "expanded")?.let { groupKeys -> + expandedKeys = groupKeys.toSet() + seeded = true + } + collapsedParameters = stringListOf(tree, "collapsedParameters").orEmpty().map(::ParameterId).toSet() + val hidden = stringListOf(tree, "hidden").orEmpty() + showGeometry = "geometry" !in hidden + showChannels = "channels" !in hidden + showBlendShapes = "blendShapes" !in hidden + // UMA §7.3: `window` is [start, end] with 0 <= start < end <= 1; anything else keeps the whole domain. + window = floatListOf(tree, "window", 2)?.takeIf { (start, end) -> start >= 0f && end <= 1f && start < end }?.let { (start, end) -> TrackWindow(start, end) } ?: TrackWindow.Full + labelColumnWidth = finiteFloatOf(tree["labelColumnWidth"])?.dp?.coerceIn(TRACK_LABEL_COLUMN_MIN_WIDTH, TRACK_LABEL_COLUMN_MAX_WIDTH) ?: TRACK_LABEL_COLUMN_DEFAULT_WIDTH + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/LogsHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/LogsHeaderControls.kt new file mode 100644 index 0000000..105c6b4 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/LogsHeaderControls.kt @@ -0,0 +1,60 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.ui.Alignment +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.storage.UmamoLog +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes + +/** + * The logs panel's area-header controls (mounted via SpaceDescriptor.headerContent): a flexible gap + * then two trailing buttons - Copy the whole log to the clipboard, and Export it to a file. Unlike the + * parameter/outliner headers this never early-returns on a missing document: the log exists from startup, + * independent of any open puppet, so its controls are always live. + * + * Copy stays an inline handler (the clipboard is a composition-local reachable here) rather than a + * registry command - the same direct-manipulation rationale parametersHeaderControls documents, since no + * shortcut or menu needs to reach it. Export is the registry command logs.export instead: the shell that + * mounts this header holds the FilePicker the write goes through, and dispatching the command reaches it + * without the header taking a picker of its own - and puts the export in the palette. + * + * Copy and Export ride one item so the pair collapses together: they are the same "do something with + * this log" affordance, and splitting them across the strip and the overflow panel would read as noise. + */ +internal fun OverflowRowScope.logsHeaderControls() { + flexibleSpace() + item("logTools") { + // LocalClipboardManager / setText are deprecated in favour of the suspend LocalClipboard, but the + // replacement needs a platform-built ClipEntry and a coroutine scope - overkill for a one-shot button. + @Suppress("DEPRECATION") + val clipboard = LocalClipboardManager.current + val commands = LocalCommands.current + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + IconButton( + icon = LocalUmamoIcons.copy, + onClick = { + @Suppress("DEPRECATION") + clipboard.setText(AnnotatedString(UmamoLog.entries.value.joinToString("\n") { entry -> entry.message })) + }, + contentDescription = stringResource(Res.string.logs_copy), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + IconButton( + icon = LocalUmamoIcons.floppy, + onClick = { commands.invoke("logs.export") }, + contentDescription = stringResource(Res.string.logs_export), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/LogsSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/LogsSpace.kt new file mode 100644 index 0000000..a0f1c8a --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/LogsSpace.kt @@ -0,0 +1,91 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.storage.LogEntry +import org.umamo.storage.LogLevel +import org.umamo.storage.UmamoLog +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * The logs space: the retained UmamoLog output as a scrolling console, so a user who launched without a + * terminal (a desktop shortcut, or Android) can still read the diagnostics. Each line is tinted by + * severity - routine info is de-emphasised, a warning reads at full weight, and an error is accented - + * escalating with the flat palette's existing tokens rather than introducing semantic colours. + * + * The list follows the tail as new lines arrive, but only while the user is already at the bottom, so + * scrolling up to read history is never fought (the same restraint HistorySpace uses for its cursor). + * It reads no document state - logs exist from startup, before and independent of any open puppet. + * + * @param Modifier modifier The layout modifier. + */ +@Composable +fun LogsSpace(modifier: Modifier = Modifier) { + val entries by UmamoLog.entries.collectAsState() + if (entries.isEmpty()) { + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text(text = stringResource(Res.string.logs_empty), color = LocalUmamoColors.current.textMuted) + } + return + } + val listState = rememberLazyListState() + // Follow the tail only when the user is already viewing the bottom: if the previously-last line was + // visible when this new line arrived, jump to the new last line; otherwise leave the scroll alone. + LaunchedEffect(entries.size) { + val lastVisibleIndex = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1 + val previousLastIndex = entries.size - 2 + if (lastVisibleIndex >= previousLastIndex) { + listState.scrollToItem(entries.lastIndex) + } + } + Box(modifier = modifier.fillMaxSize()) { + LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { + items(entries) { entry -> + LogLineRow(entry) + } + } + VerticalScrollbarOverlay(listState) + } +} + +/** + * One log line, tinted by its [LogEntry.level] and left free to wrap so a long message stays fully + * readable rather than truncating. + * + * @param LogEntry entry The line to render. + */ +@Composable +private fun LogLineRow(entry: LogEntry) { + val colors = LocalUmamoColors.current + val lineColor = + when (entry.level) { + LogLevel.Info -> colors.textMuted + LogLevel.Warn -> colors.text + LogLevel.Error -> colors.accent + } + Text( + text = entry.message, + style = LocalUmamoTypography.current.bodySmall, + color = lineColor, + modifier = + Modifier.fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 1.dp), + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerHeaderControls.kt new file mode 100644 index 0000000..c56c758 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerHeaderControls.kt @@ -0,0 +1,107 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.FilterPopupChip +import org.umamo.ui.kit.FilterSectionLabel +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.kit.SEARCH_FIELD_MIN_WIDTH +import org.umamo.ui.kit.SearchField +import org.umamo.ui.kit.button.ButtonGroup +import org.umamo.ui.kit.button.ButtonGroupItem +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.workspace.AreaScope + +/** + * The outliner's area-header controls (mounted via SpaceDescriptor.headerContent): the name search + * field centered in the header's flexible middle and the filter dropdown chip right-aligned at its + * end. Reads and writes the area's shared OutlinerViewState so the body's tree filtering reacts + * live; renders nothing without an open document (unlike viewport2DHeaderControls, which renders its + * chips disabled rather than vanishing). Keeping a large rig (hundreds of deformers) navigable is the + * role Cubism's per-panel search served before the panels were unified here. + * + * アウトライナーのエリアヘッダ内容。中央に名前検索フィールド、右端に絞り込みチップ。エリア共有の + * OutlinerViewState を読み書きし、本体のツリーが即座に反応する。ドキュメント未オープン時は何も + * 描画しない。 + * + * @param AreaScope scope The hosting area's scope carrying the shared view state. + */ +internal fun OverflowRowScope.outlinerHeaderControls(scope: AreaScope) { + val viewState = scope.spaceState(OUTLINER_VIEW_STATE_KEY) { OutlinerViewState() } + // Flexible gaps on both sides center the search field in the slot region; the filter chip after the + // second gap right-aligns. The center sits left of true center by half the chip's width - accepted, + // since exact centering would need the strip to weight against the placed items too. + flexibleSpace() + item("search", minWidth = SEARCH_FIELD_MIN_WIDTH) { + // Each item gates itself on the document: an item that renders nothing measures zero, so the + // whole strip disappears without the builder needing a CompositionLocal it cannot read. + if (LocalPuppet.current != null) { + SearchField(value = viewState.query, onValueChange = { newQuery -> viewState.query = newQuery }) + } + } + flexibleSpace() + item("filter") { + if (LocalPuppet.current != null) { + FilterDropdownButton(viewState) + } + } +} + +/** + * The outliner's filter dropdown: the shared [FilterPopupChip] holding this panel's kind toggles plus + * the restriction toggles - a Blender-style row of icon buttons controlling whether the pointer / eye + * indicator columns render on the rows (lit = shown). Mutates the shared [viewState] directly. + * + * @param OutlinerViewState viewState The area's shared search / filter state. + */ +@Composable +private fun FilterDropdownButton(viewState: OutlinerViewState) { + FilterPopupChip( + contentDescription = stringResource(Res.string.common_filters), + icon = if (viewState.isUnfiltered) LocalUmamoIcons.filterUnfiltered else LocalUmamoIcons.filterFiltered, + ) { + FilterSectionLabel(stringResource(Res.string.outliner_restriction_toggles)) + // Blender's restriction-toggle row: one butted segment per indicator column, lit while + // the column is shown. + ButtonGroup( + items = + listOf( + ButtonGroupItem( + icon = LocalUmamoIcons.selectable, + selected = viewState.showSelectableColumn, + onClick = { viewState.showSelectableColumn = !viewState.showSelectableColumn }, + contentDescription = stringResource(Res.string.outliner_column_selectable), + ), + ButtonGroupItem( + icon = LocalUmamoIcons.eyeVisible, + selected = viewState.showVisibilityColumn, + onClick = { viewState.showVisibilityColumn = !viewState.showVisibilityColumn }, + contentDescription = stringResource(Res.string.outliner_column_visibility), + ), + ), + modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), + ) + FilterSectionLabel(stringResource(Res.string.common_filters)) + Checkbox( + checked = viewState.showParts, + onCheckedChange = { checked -> viewState.showParts = checked }, + label = stringResource(Res.string.outliner_filter_parts), + ) + Checkbox( + checked = viewState.showDrawables, + onCheckedChange = { checked -> viewState.showDrawables = checked }, + label = stringResource(Res.string.outliner_filter_drawables), + ) + Checkbox( + checked = viewState.showDeformers, + onCheckedChange = { checked -> viewState.showDeformers = checked }, + label = stringResource(Res.string.outliner_filter_deformers), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerSpace.kt new file mode 100644 index 0000000..1c98cdb --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerSpace.kt @@ -0,0 +1,1218 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isCtrlPressed +import androidx.compose.ui.input.pointer.isMetaPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextMeasurer +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorSession +import org.umamo.edit.OutlinerDropTarget +import org.umamo.edit.RowDropBand +import org.umamo.edit.Selection +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.edit.applyOutlinerDrop +import org.umamo.edit.deleteTarget +import org.umamo.edit.outlinerDropBandFor +import org.umamo.edit.rename +import org.umamo.edit.resolveOutlinerDrop +import org.umamo.edit.toggleSelectable +import org.umamo.edit.toggleSelectableSubtree +import org.umamo.edit.toggleVisibility +import org.umamo.edit.toggleVisibilitySubtree +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.InlineRenameField +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.kit.button.IconSlot +import org.umamo.ui.kit.singleOrDoubleClick +import org.umamo.ui.model.LocalDrawableThumbnails +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.drawIcon +import org.umamo.ui.workspace.AreaScope +import org.umamo.ui.workspace.LocalRelationPick +import org.umamo.ui.workspace.PickClickOutcome +import org.umamo.ui.workspace.rowdrag.RowCoordinatesHolder +import org.umamo.ui.workspace.rowdrag.RowDragController +import org.umamo.ui.workspace.rowdrag.RowDragLabel +import org.umamo.ui.workspace.rowdrag.dragRowOnLongPress +import org.umamo.ui.workspace.rowdrag.parkCancelOnSeam +import org.umamo.ui.workspace.rowdrag.rowDropHighlight + +/** Per-depth indentation, matching the Parameters space's folder indent. */ +private val INDENT_PER_DEPTH = 12.dp + +/** Fixed width of the disclosure-chevron slot (kept in sync with the math for the click region). */ +private val CHEVRON_WIDTH = 14.dp + +/** Fixed width of the type-icon slot. */ +private val ICON_WIDTH = 16.dp + +/** Row height, shared by every outliner row. */ +private val ROW_HEIGHT = 22.dp + +/** Fixed width of the trailing restriction indicator slot. */ +private val RESTRICTION_SLOT_WIDTH = 16.dp + +/** One outliner node paired with its tree depth, the unit a [LazyColumn] item renders. */ +private data class FlatRow(val node: OutlinerNode, val depth: Int) + +/** + * The outliner space: the unified Blender-style tree that folds Cubism's split Part and Deformer panels + * into one. A single puppet root holds the Armature deformer hierarchy followed by the parts, each part + * listing its drawables then its sub-parts. Reads the open document's puppet from [LocalPuppet] (empty + * state when nothing is loaded). Branches start collapsed (only the root is open); rows dim when hidden + * or sketch and select through [LocalSelection] (plain click replaces, Ctrl / Cmd toggles, Shift adds). + * A selection made elsewhere (a viewport pick) reveals its row - ancestors expand and the list scrolls + * to it - but a click inside the outliner never scrolls the list. Clearing the search reveals the active + * selection the same way, so a row picked out of the results is not stranded behind a branch that closes + * again. The AREA header carries the name search and the filter dropdown (outlinerHeaderControls, + * sharing this body's OutlinerViewState through [scope]); names never wrap, so a horizontal scroll + * reaches long ones. + * + * @param AreaScope scope The hosting area's scope carrying the shared view state. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun OutlinerSpace(scope: AreaScope, modifier: Modifier = Modifier) { + val stripeColor = LocalUmamoColors.current.rowStripe + val puppet = LocalPuppet.current + if (puppet == null) { + Box(modifier = modifier.fillMaxSize().zebraFill(rememberLazyListState(), ROW_HEIGHT, stripeColor)) + return + } + val selectionHandle = LocalSelection.current + // An armed relation pick (a Properties eyedropper) resolves from an outliner row as well as from a + // viewport, so rows check it before selecting. + val relationPick = LocalRelationPick.current + val selection = selectionHandle?.selection ?: Selection() + // The open document's session drives the per-row edits (eye toggle, inline rename); null when no + // document is open, in which case those affordances no-op. + val editorSession = LocalEditorSession.current + // The node id whose label is being renamed in place (double-click opens it), or null when none is. + // Not keyed on the puppet (see the expand-state note): a rename commit changes the model, which must + // not yank the editor's own id state out from under it mid-edit. + var renamingNodeId by remember { mutableStateOf(null) } + // Drag-and-drop state: long-press a row to pick it up, drop onto another to reparent. Transient, so + // remembered per outliner instance (never keyed on the puppet). + val dragController = remember { RowDragController() } + // While a drag is in flight its cancel is parked with the shell, so Escape aborts the drag instead of + // falling through to the shell's clear-selection branch. + dragController.parkCancelOnSeam() + val rootLabel = stringResource(Res.string.outliner_root) + val armatureLabel = stringResource(Res.string.outliner_armature) + val tree = remember(puppet, rootLabel, armatureLabel) { buildOutlinerTree(puppet, rootLabel, armatureLabel) } + // Search / filter state shared with the area-header controls (outlinerHeaderControls) through the + // hosting AreaScope - the header slot is a sibling subtree, so a body-local remember cannot reach it. + val viewState = scope.spaceState(OUTLINER_VIEW_STATE_KEY) { OutlinerViewState() } + // Expand state keyed by stable node id, on the view state so a saved document carries it (UMA §7.3). + // Default collapsed - only the root opens. + val expanded = viewState.expanded + val query = viewState.query + // Set when a click inside the outliner changes the selection, so the reveal effect can skip the scroll. + var suppressReveal by remember { mutableStateOf(false) } + val filteredTree = + remember(tree, query, viewState.showParts, viewState.showDrawables, viewState.showDeformers) { + filterOutliner(tree, query, viewState.showParts, viewState.showDrawables, viewState.showDeformers) + } + // During an active search every branch opens so matches are not hidden behind the collapsed default. + val searching = query.isNotBlank() + val trimmedQuery = query.trim() + val isOpen: (String) -> Boolean = { id -> searching || viewState.isOpen(id) } + // Memoise the visible rows on what actually changes them, so the width measurement below is stable + // across recompositions (and unaffected by vertical scrolling). + val rows = remember(filteredTree, expanded.toMap(), searching) { flattenOutliner(filteredTree, isOpen) } + val listState = rememberLazyListState() + val horizontalScroll = rememberScrollState() + val density = LocalDensity.current + val textMeasurer = rememberTextMeasurer() + val typography = LocalUmamoTypography.current + // Part folders that contain (anywhere below) a selected node, so a collapsed parent still signals the + // selection lives inside it. Keyed by node id; computed from each selected target's path to the root. + val ancestorParts = + remember(filteredTree, selection) { + buildSet { + for (target in selection.targets) { + val path = pathTo(filteredTree, target) ?: continue + path.dropLast(1).forEach { ancestorId -> if (ancestorId.startsWith("part:")) add(ancestorId) } + } + } + } + + // Hover art preview: the host's thumbnail provider (null on a platform / document without one, which + // disables the preview), and the shared rest-delayed state the rows report into (RowHoverPreview.kt). + val thumbnails = LocalDrawableThumbnails.current + val hoverPreview = rememberRowHoverPreviewState() + + // The one reveal body both paths below share: open every ancestor of the target, then bring its row + // into view. Shared so the two entry points cannot drift into revealing a row differently. + suspend fun revealTarget(target: SelectionTarget) { + val path = pathTo(filteredTree, target) ?: return + path.dropLast(1).forEach { ancestorId -> expanded[ancestorId] = true } + val index = flattenOutliner(filteredTree, isOpen).indexOfFirst { row -> row.node.id == path.last() } + if (index >= 0) { + listState.animateScrollToItem(index) + } + } + + // Reveal-on-select: a selection from elsewhere (a viewport pick) opens the target's ancestors and + // scrolls to it; a selection made by clicking inside the outliner suppresses the scroll so the list + // does not jump under the user's cursor. + LaunchedEffect(selection.active) { + val wasLocalClick = suppressReveal + suppressReveal = false + if (wasLocalClick) { + return@LaunchedEffect + } + val active = selection.active ?: return@LaunchedEffect + revealTarget(active) + } + + // Reveal-on-search-cleared: a search opens every branch, so a row clicked out of the results sits in a + // branch that closes again the moment the query goes away. Revealing the active selection on that edge + // keeps it in view. Strictly the searching -> not-searching edge: doing it on every query change would + // pull the list to the selection on each keystroke, and expand the ancestors of whatever the shifting + // matches happen to be, which is nearly every branch. + var wasSearching by remember { mutableStateOf(searching) } + LaunchedEffect(searching) { + val searchCleared = wasSearching && !searching + wasSearching = searching + if (!searchCleared) { + return@LaunchedEffect + } + val active = selection.active ?: return@LaunchedEffect + revealTarget(active) + } + + Column(modifier = modifier.fillMaxSize()) { + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + BoxWithConstraints(modifier = Modifier.fillMaxSize().zebraFill(listState, ROW_HEIGHT, stripeColor)) { + val viewportWidth = maxWidth + val contentWidth = + remember(rows, viewportWidth, density, typography, viewState.showSelectableColumn, viewState.showVisibilityColumn) { + outlinerContentWidth( + rows, + textMeasurer, + density, + viewportWidth, + typography.bodySmall, + typography.labelSmall, + viewState.showSelectableColumn, + viewState.showVisibilityColumn, + ) + } + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize().horizontalScroll(horizontalScroll), + ) { + itemsIndexed( + rows, + key = { _, row -> row.node.id }, + contentType = { _, row -> row.node.icon }, + ) { index, row -> + OutlinerRowView( + row = row, + rowIndex = index, + rowWidth = contentWidth, + puppet = puppet, + selected = row.node.target != null && row.node.target in selection, + ancestorOfSelection = row.node.id in ancestorParts, + matched = searching && row.node.label.contains(trimmedQuery, ignoreCase = true), + expanded = isOpen(row.node.id), + onToggle = { + expanded[row.node.id] = !viewState.isOpen(row.node.id) + }, + onSelect = { toggle, extend -> + val target = row.node.target + val handle = selectionHandle + // An armed relation pick (a Properties eyedropper) claims the click. It claims a + // row it will NOT accept too - selecting would record an undo step and swap the + // Properties panel, and the arming field with it, out from under the pick. + val pickOutcome = target?.let { relationPick.click(it) } ?: PickClickOutcome.Ignored + if (pickOutcome == PickClickOutcome.Resolved) { + suppressReveal = true + } else if (pickOutcome == PickClickOutcome.Ignored && target != null && handle != null) { + // Selectability gates only viewport picking; the outliner always selects. + suppressReveal = true + handle.set( + selectionAfterClick( + rows, + handle.selection, + index, + target, + toggle, + extend, + ), + ) + } + }, + renaming = row.node.id == renamingNodeId, + onStartRename = { + // Only real rows rename; the editor needs a session to commit through. + if (row.node.target != null && editorSession != null) { + renamingNodeId = row.node.id + } + }, + onCommitRename = { newName -> + row.node.target?.let { target -> editorSession?.rename(target, newName) } + renamingNodeId = null + }, + onCancelRename = { renamingNodeId = null }, + onToggleVisibility = { shiftHeld -> + row.node.target?.let { target -> + // Blender parity: Shift sets the clicked node and its whole subtree to one uniform value. + if (shiftHeld) { + editorSession?.toggleVisibilitySubtree(target) + } else { + editorSession?.toggleVisibility(target) + } + } + }, + onToggleSelectable = { shiftHeld -> + row.node.target?.let { target -> + if (shiftHeld) { + editorSession?.toggleSelectableSubtree(target) + } else { + editorSession?.toggleSelectable(target) + } + } + }, + showSelectableColumn = viewState.showSelectableColumn, + showVisibilityColumn = viewState.showVisibilityColumn, + onRequestDelete = { cascade -> + // No confirmation: history / undo makes an accidental delete cheap to recover, and the + // rows are hard to hit by accident - so this applies immediately (the chosen behaviour). + row.node.target?.let { target -> editorSession?.deleteTarget(target, cascade) } + }, + dragController = dragController, + onDrop = { + performOutlinerDrop( + dragController, + rows, + puppet, + editorSession, + ) { nodeId -> expanded[nodeId] = true } + }, + hoverPreviewsEnabled = thumbnails != null, + hoverPreview = hoverPreview, + ) + } + } + } + VerticalScrollbarOverlay(listState) + } + // One art preview for the whole space, anchored beside the rested-on row. Gated on a provider being + // present and the entity actually having art (untextured drawables / art-less parts pop nothing): a + // drawable shows its own crop, a part shows the combined preview of every art mesh under it. + val preview = hoverPreview.shown + val previewBitmap = + preview?.let { shown -> + when (val target = shown.key) { + is SelectionTarget.Drawable -> thumbnails?.thumbnailFor(target.id) + is SelectionTarget.Part -> thumbnails?.partThumbnailFor(target.id) + is SelectionTarget.Deformer -> null + } + } + if (preview != null && previewBitmap != null) { + RowThumbnailPreview(name = preview.name, thumbnail = previewBitmap, anchorRect = preview.rowBounds) + } + // A name chip follows the cursor while dragging, so there is something clearly "in hand". + val draggingLabel = + dragController.draggingKey?.let { id -> rows.firstOrNull { it.node.id == id }?.node?.label } + if (dragController.isDragging && draggingLabel != null) { + RowDragLabel( + label = draggingLabel, + cursorX = dragController.dragWindowX, + cursorY = dragController.dragWindowY, + ) + } + } +} + +/** + * Applies the drop at the end of a drag: reads the drag state, resolves the move through :edit's + * [resolveOutlinerDrop] (the same band rules the row indicator drew, so what the user saw is what + * happens), dispatches it as one undo step, and expands the destination on a nest-inside drop so the + * user sees the moved item land. Drops with no valid target, onto itself, or across the org / + * armature boundary do nothing; cycles are refused inside the move. + * + * @param RowDragController controller The drag state (read for the dragged + target + band, then ended). + * @param List rows The visible rows, to resolve a node id to its selection target. + * @param PuppetModel puppet The model, to resolve the target's parent and siblings. + * @param EditorSession? session The session the move is dispatched through (null = no document, no-op). + * @param Function expand Opens the given node id (the destination is expanded on a nest-inside drop so the + * user sees the moved item land, rather than fearing it vanished into a collapsed branch). + */ +private fun performOutlinerDrop( + controller: RowDragController, + rows: List, + puppet: PuppetModel, + session: EditorSession?, + expand: (String) -> Unit, +) { + val targetId = controller.dropTargetKey + val fraction = controller.dropTargetFraction ?: 0.5f + val dragged = controller.draggedPayload + controller.end() + if (targetId == null || session == null || dragged == null) { + return + } + val targetNode = rows.firstOrNull { it.node.id == targetId }?.node ?: return + val target = outlinerDropTargetOf(targetNode) ?: return + val drop = puppet.resolveOutlinerDrop(dragged, target, fraction) ?: return + session.applyOutlinerDrop(drop) + if (drop.expandTarget) { + expand(targetNode.id) + } +} + +/** + * Maps an outliner node to the drop-target the :edit rules understand: real rows by their selection + * target, the synthetic puppet root / Armature by name. Null when the row cannot accept a drop (there + * are none today - both synthetics and every real row are named). + * + * @param OutlinerNode node The row under the pointer. + * @return OutlinerDropTarget? The drop target, or null. + */ +private fun outlinerDropTargetOf(node: OutlinerNode): OutlinerDropTarget? = + when { + node.id == OUTLINER_ROOT_ID -> OutlinerDropTarget.PuppetRoot + node.id == OUTLINER_ARMATURE_ID -> OutlinerDropTarget.Armature + node.target != null -> OutlinerDropTarget.Entity(node.target) + else -> null + } + +/** + * One tree row with its context menu attached. A right-click (desktop) or long-press (touch) on a real + * row opens [outlinerRowMenuItems]; the synthetic root rows (no target) have no menu and pass straight + * through to the bare [OutlinerRowBody]. The menu reuses the very callbacks the eye / pointer / rename + * affordances already drive, plus [onRequestDelete] for the destructive entries, so a menu action and its + * inline affordance always do the same thing. + * + * @param FlatRow row The node and its depth. + * @param Int rowIndex The visible-row index, for the ancestry-guide dash phase. + * @param Dp rowWidth The fixed width shared by every row. + * @param PuppetModel puppet The model, for drop-band resolution (cycle checks need the tree). + * @param Boolean selected Whether the node is in the current selection. + * @param Boolean ancestorOfSelection Whether this part folder contains the selection. + * @param Boolean matched Whether the node matches the active search. + * @param Boolean expanded Whether the node is expanded. + * @param Function onToggle Flips this node's expand state. + * @param Function onSelect Applies a selection gesture for a real node. + * @param Boolean renaming Whether this row's label is the inline rename editor. + * @param Function onStartRename Opens this row's inline rename. + * @param Function onCommitRename Commits the inline rename. + * @param Function onCancelRename Abandons the inline rename. + * @param Function onToggleVisibility Flips this row's entity visibility; with Shift held, its whole subtree. + * @param Function onToggleSelectable Flips this row's entity selectability; with Shift held, its whole subtree. + * @param Boolean showSelectableColumn Whether the pointer restriction column renders on the rows. + * @param Boolean showVisibilityColumn Whether the eye restriction column renders on the rows. + * @param Function onRequestDelete Requests a delete of this row's entity (true = cascade, false = ungroup). + * @param RowDragController dragController Shared drag state. + * @param Function onDrop Applies the move when a drag started on this row ends. + * @param Boolean hoverPreviewsEnabled Whether a hovered drawable / part row reports an art preview. + * @param RowHoverPreviewState hoverPreview The space's hover preview state the row reports into. + */ +@Composable +private fun OutlinerRowView( + row: FlatRow, + rowIndex: Int, + rowWidth: Dp, + puppet: PuppetModel, + selected: Boolean, + ancestorOfSelection: Boolean, + matched: Boolean, + expanded: Boolean, + onToggle: () -> Unit, + onSelect: (toggle: Boolean, extend: Boolean) -> Unit, + renaming: Boolean, + onStartRename: () -> Unit, + onCommitRename: (String) -> Unit, + onCancelRename: () -> Unit, + onToggleVisibility: (shiftHeld: Boolean) -> Unit, + onToggleSelectable: (shiftHeld: Boolean) -> Unit, + showSelectableColumn: Boolean, + showVisibilityColumn: Boolean, + onRequestDelete: (cascade: Boolean) -> Unit, + dragController: RowDragController, + onDrop: () -> Unit, + hoverPreviewsEnabled: Boolean, + hoverPreview: RowHoverPreviewState, +) { + val body = + @Composable { + OutlinerRowBody( + row = row, + rowIndex = rowIndex, + rowWidth = rowWidth, + puppet = puppet, + selected = selected, + ancestorOfSelection = ancestorOfSelection, + matched = matched, + expanded = expanded, + onToggle = onToggle, + onSelect = onSelect, + renaming = renaming, + onStartRename = onStartRename, + onCommitRename = onCommitRename, + onCancelRename = onCancelRename, + onToggleVisibility = onToggleVisibility, + onToggleSelectable = onToggleSelectable, + showSelectableColumn = showSelectableColumn, + showVisibilityColumn = showVisibilityColumn, + dragController = dragController, + onDrop = onDrop, + hoverPreviewsEnabled = hoverPreviewsEnabled, + hoverPreview = hoverPreview, + ) + } + val target = row.node.target + if (target == null) { + body() + } else { + ContextMenuArea( + items = + outlinerRowMenuItems( + target, + // A menu action has no Shift context, so it is always the plain single-entity toggle. + { onToggleVisibility(false) }, + { onToggleSelectable(false) }, + onStartRename, + onRequestDelete, + ), + content = body, + ) + } +} + +/** + * Builds the context-menu entries for a real outliner row, by entity kind: parts and drawables get a + * visibility toggle (deformers have none); every kind gets selectability, rename, and delete. A part's + * "Delete" ungroups (keeps the contents, splicing them into its parent) and a second "Delete Hierarchy" + * cascades (removes the whole subtree); a drawable or deformer has the single delete. Selectability + * gates only viewport picking, so every entry stays enabled on an unselectable row. + * + * @param SelectionTarget target The row's entity. + * @param Function onToggleVisibility Flips the entity's visibility. + * @param Function onToggleSelectable Flips the entity's selectability. + * @param Function onStartRename Opens the inline rename. + * @param Function onRequestDelete Requests a delete (true = cascade / the sole delete, false = ungroup). + * @return List The menu entries. + */ +@Composable +private fun outlinerRowMenuItems( + target: SelectionTarget, + onToggleVisibility: () -> Unit, + onToggleSelectable: () -> Unit, + onStartRename: () -> Unit, + onRequestDelete: (cascade: Boolean) -> Unit, +): List = + buildList { + // Select Hierarchy replaces the selection with this row's whole subtree (dispatched through the + // registry with the row's target as the argument, so the palette and a future binding share it). + val commands = LocalCommands.current + add( + MenuItem.Action( + stringResource(Res.string.outliner_menu_select_hierarchy), + onSelect = { commands.invoke("outliner.selectHierarchy", target) }, + ), + ) + add(MenuItem.Separator) + if (target is SelectionTarget.Part || target is SelectionTarget.Drawable) { + add(MenuItem.Action(stringResource(Res.string.outliner_menu_visibility), onSelect = onToggleVisibility)) + } + add(MenuItem.Action(stringResource(Res.string.outliner_menu_selectable), onSelect = onToggleSelectable)) + add(MenuItem.Action(stringResource(Res.string.outliner_menu_rename), onSelect = onStartRename)) + if (target is SelectionTarget.Part || target is SelectionTarget.Drawable) { + add(MenuItem.Separator) + // Create Warp uses the current selection (the row is usually already selected from the + // right-click), wrapping its meshes in a new armature lattice. + val warpName = stringResource(Res.string.deformer_default_warp_name) + add( + MenuItem.Action( + stringResource(Res.string.outliner_menu_create_warp), + onSelect = { commands.invoke("deformer.createWarp", warpName) }, + ), + ) + } + add(MenuItem.Separator) + // "Delete" removes just this item (a part keeps its contents, which rise to the parent); "Delete + // Hierarchy" removes a part's whole subtree. A drawable / deformer has no hierarchy, so just "Delete". + add(MenuItem.Action(stringResource(Res.string.outliner_menu_delete), onSelect = { onRequestDelete(false) })) + if (target is SelectionTarget.Part) { + add( + MenuItem.Action( + stringResource(Res.string.outliner_menu_delete_hierarchy), + onSelect = { onRequestDelete(true) }, + ), + ) + } + } + +/** + * Renders one tree row: indent, a disclosure chevron (only when the node has children), a placeholder + * type icon, the single-line label (or its inline rename editor while [renaming]), and - for parts / + * drawables - a clickable visibility eye pinned to the right. Every row is fixed to [rowWidth] so the + * selection / hover / search-match backgrounds span the full width and the horizontal scroll range stays + * put; a name longer than the viewport grows [rowWidth] and is reached by scrolling rather than wrapping. + * A single click selects a real node or toggles a synthetic one; a double-click on a real node opens its + * inline rename ([onStartRename]); the chevron and the eye consume their own press (only toggling + * expansion / visibility). A part folder whose subtree holds the selection is tinted + * ([ancestorOfSelection]); a search hit is tinted too, so found rows stand out along the path the filter + * kept. + * + * @param FlatRow row The node and its depth. + * @param Int rowIndex The visible-row index, for the ancestry-guide dash phase. + * @param Dp rowWidth The fixed width shared by every row (the wider of the viewport and the longest row). + * @param PuppetModel puppet The model, for drop-band resolution (cycle checks need the tree). + * @param Boolean selected Whether the node is in the current selection. + * @param Boolean ancestorOfSelection Whether this part folder contains the selection (tinted to signal it). + * @param Boolean matched Whether the node's name matches the active search (tinted to stand out). + * @param Boolean expanded Whether the node is expanded. + * @param Function onToggle Flips this node's expand state. + * @param Function onSelect Applies a selection gesture (toggle / extend modifiers) for a real node. + * @param Boolean renaming Whether this row's label is currently the inline rename editor. + * @param Function onStartRename Opens this row's inline rename (a double-click on a real node). + * @param Function onCommitRename Commits the inline rename with the new name. + * @param Function onCancelRename Abandons the inline rename. + * @param Function onToggleVisibility Flips this row's entity visibility (the eye click); Shift = subtree. + * @param Function onToggleSelectable Flips this row's entity selectability (the pointer click); Shift = subtree. + * @param Boolean showSelectableColumn Whether the pointer restriction column renders (the filter dropdown's toggle). + * @param Boolean showVisibilityColumn Whether the eye restriction column renders (the filter dropdown's toggle). + * @param RowDragController dragController Shared drag state; the row reports its bounds and gestures here. + * @param Function onDrop Applies the move when a drag started on this row ends. + * @param Boolean hoverPreviewsEnabled Whether a hovered drawable / part row should report an art preview. + * @param RowHoverPreviewState hoverPreview The space's hover preview state this drawable / part row reports into. + */ +@Composable +private fun OutlinerRowBody( + row: FlatRow, + rowIndex: Int, + rowWidth: Dp, + puppet: PuppetModel, + selected: Boolean, + ancestorOfSelection: Boolean, + matched: Boolean, + expanded: Boolean, + onToggle: () -> Unit, + onSelect: (toggle: Boolean, extend: Boolean) -> Unit, + renaming: Boolean, + onStartRename: () -> Unit, + onCommitRename: (String) -> Unit, + onCancelRename: () -> Unit, + onToggleVisibility: (shiftHeld: Boolean) -> Unit, + onToggleSelectable: (shiftHeld: Boolean) -> Unit, + showSelectableColumn: Boolean, + showVisibilityColumn: Boolean, + dragController: RowDragController, + onDrop: () -> Unit, + hoverPreviewsEnabled: Boolean, + hoverPreview: RowHoverPreviewState, +) { + val node = row.node + // The long-press drag runs in a long-lived pointerInput coroutine that only re-captures its closures + // when its keys change, and onDrop closes over live state; this keeps the drag's release pointed at the + // latest callback. + val currentOnDrop by rememberUpdatedState(onDrop) + // Drag feedback: this row is the one being dragged (faded), or the row the pointer is over (a drop + // target). Real rows and the synthetic puppet root / Armature all accept drops when the pairing is legal. + val isDragged = dragController.draggingKey == node.id + val dropTarget = outlinerDropTargetOf(node) + val isDropTarget = + dragController.isDragging && !isDragged && dropTarget != null && dragController.dropTargetKey == node.id + // The drop band for THIS row, resolved by the same band rules the dispatch uses (so the indicator always + // matches the move): an insertion line above (before) or below (after), or a whole-row fill (nest into). + val draggedPayload = dragController.draggedPayload + val dropBand = + when { + !isDropTarget || draggedPayload == null || dropTarget == null -> null + else -> puppet.outlinerDropBandFor(draggedPayload, dropTarget, dragController.dropTargetFraction ?: 0.5f) + } + val dropAbove = dropBand == RowDropBand.Before + val dropBelow = dropBand == RowDropBand.After + val isIntoTarget = dropBand == RowDropBand.Into + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + // Plain (non-snapshot) holder for the row's layout coordinates so onGloballyPositioned never forces a + // recompose; the hover effect reads the live window bounds from it on demand to anchor the preview. + val boundsHolder = remember { RowCoordinatesHolder() } + // While a relation pick is armed, report this row as what a click here would bind, so the shell's badge + // names it exactly as it does for a viewport hover. Withdrawn on leaving, and only if still ours. + val relationPick = LocalRelationPick.current + LaunchedEffect(hovered, node.target) { + val target = node.target ?: return@LaunchedEffect + if (hovered) { + relationPick.hover(target) + } else { + relationPick.unhover(target) + } + } + // Report this row's hover so the space can pop (after its rest delay) an art preview beside it: a + // drawable previews its own art mesh, a part the combined art of everything under it; deformers have no + // art, and the synthetic root rows have no entity to report. A row's target is fixed for its list key, + // so the branch never flips under a live row. + val hoverTarget = node.target + if (hoverTarget != null) { + ReportRowHover( + state = hoverPreview, + key = hoverTarget, + name = node.label, + hovered = hovered, + enabled = hoverPreviewsEnabled && (hoverTarget is SelectionTarget.Drawable || hoverTarget is SelectionTarget.Part), + boundsHolder = boundsHolder, + ) + } + // Drop this row's drag-hit-test bounds when it scrolls off, so a drop never targets an off-screen row. + DisposableEffect(node.id) { + onDispose { dragController.clearBounds(node.id) } + } + // A "nest inside" drop draws the shared drop ring over whatever fill the row has; before / after draw + // an edge line instead (below). + val background = + when { + selected -> colors.selection + hovered -> colors.rowHover + ancestorOfSelection -> colors.selectionAncestorBackground + matched -> colors.searchMatchBackground + else -> Color.Transparent + } + val borderColor = + when { + selected -> colors.selection + hovered -> colors.rowHover + ancestorOfSelection -> colors.accent + matched -> colors.accent + else -> Color.Transparent + } + val labelColor = + when { + selected -> colors.selectionText + node.dimmed -> colors.textMuted + else -> colors.text + } + // Subtle dashed ancestry guides: muted so they stay subordinate to the labels in both themes. + val guideLineColor = colors.treeGuideLine + val hasChildren = node.children.isNotEmpty() + val showEye = node.target is SelectionTarget.Part || node.target is SelectionTarget.Drawable + Row( + modifier = + Modifier.width(rowWidth) + .height(ROW_HEIGHT) + // The dragged row fades while it is in flight - the whole row, fill and ring included, so the + // alpha layer wraps everything painted below it. + .alpha(if (isDragged) 0.4f else 1f) + // Background and border paint on the full row, before padding insets the content - otherwise the + // selection / hover band is drawn inside the 2dp vertical padding, so the highlighted rows read + // as having extra vertical padding while the plain rows (no visible band) do not. + .background(background, shape = shapes.medium) + .border(BorderStroke(1.dp, borderColor), shapes.medium) + .rowDropHighlight(isIntoTarget, shapes.medium, colors) + // Dashed vertical guide lines, one per ancestor indent column, so deep branches line up + // visually (Blender's outliner ancestry lines). Painted over the zebra fill but behind the + // content; depth 0 (the root) draws none. The dash phase is offset by the row's stacked height + // so the dashes stay continuous from one row to the next instead of resetting every row. + .drawBehind { + if (row.depth == 0) { + return@drawBehind + } + val leftEdgePx = + 4.dp.toPx() + 4.dp.toPx() // the row's horizontal padding plus the Spacer's base inset + val indentPx = INDENT_PER_DEPTH.toPx() + val chevronHalfPx = CHEVRON_WIDTH.toPx() / 2f + val dashOnPx = 2.dp.toPx() + val dashOffPx = 3.dp.toPx() + val dashPeriodPx = dashOnPx + dashOffPx + val dashEffect = + PathEffect.dashPathEffect( + floatArrayOf(dashOnPx, dashOffPx), + (rowIndex * size.height) % dashPeriodPx, + ) + var ancestorLevel = 0 + while (ancestorLevel < row.depth) { + val lineX = leftEdgePx + indentPx * ancestorLevel + chevronHalfPx + drawLine( + color = guideLineColor, + start = Offset(lineX, 0f), + end = Offset(lineX, size.height), + strokeWidth = 1.dp.toPx(), + pathEffect = dashEffect, + ) + ancestorLevel += 1 + } + } + // The drop insertion line: above for a "before" drop, below for "after"; an "into" drop (a part's + // middle band) shows the whole-row fill instead. The line starts at this row's indent level, so + // it visually reads as landing at the same nesting as the target (the dropped sibling's level). + .drawBehind { + // Inset the line by half its stroke so the full 2.5dp stays inside the row - drawing it at the + // very edge (y == 0) clips the top half against the row bound, which made the "before" line on + // the first row nearly invisible. + val strokeWidth = 2.5.dp.toPx() + val edgeY = + when { + dropAbove -> strokeWidth / 2f + dropBelow -> size.height - strokeWidth / 2f + else -> return@drawBehind + } + val startX = 4.dp.toPx() + 4.dp.toPx() + INDENT_PER_DEPTH.toPx() * row.depth + drawLine( + color = colors.accent, + start = Offset(startX, edgeY), + end = Offset(size.width, edgeY), + strokeWidth = strokeWidth, + ) + } + .hoverable(interaction) + .onGloballyPositioned { coordinates -> + boundsHolder.coordinates = coordinates + // Publish the window bounds so a drag can hit-test the drop target against every visible row. + dragController.reportBounds(node.id, coordinates.boundsInWindow()) + } + // Long-press then drag to reparent: distinct from the tap-to-select gesture below, so a press still + // selects first, then a hold begins the drag. Only real rows (a target) pick up; the drop is + // applied on release by the space, which reads the controller's target. + .dragRowOnLongPress(dragController, node.id, node.target, boundsHolder) { currentOnDrop() } + // Selection covers the whole row (indent, icon, label, blank space) so clicking anywhere but the + // chevron or eye selects; those consume their own press, which the gesture skips. A right press + // falls through to the wrapping ContextMenuArea. A double click on a real node opens the inline + // rename; a synthetic node toggles on every press. While renaming the editor owns the row, so + // the gesture stands down. + .singleOrDoubleClick( + enabled = !renaming, + onSingle = { modifiers -> + if (node.target == null) { + onToggle() + } else { + onSelect(modifiers.isCtrlPressed || modifiers.isMetaPressed, modifiers.isShiftPressed) + } + }, + onDouble = { + if (node.target == null) { + onToggle() + } else { + onStartRename() + } + }, + ) + .padding(horizontal = 4.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Spacer(modifier = Modifier.width(4.dp + INDENT_PER_DEPTH * row.depth)) + ChevronSlot(visible = hasChildren, expanded = expanded, onToggle = onToggle, tint = colors.textMuted) + OutlinerIconSlot(icon = node.icon, dimmed = node.dimmed) + Spacer(modifier = Modifier.width(4.dp)) + val labelStyle = + if (node.target is SelectionTarget.Drawable) LocalUmamoTypography.current.labelSmall else LocalUmamoTypography.current.bodySmall + Box(modifier = Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.CenterStart) { + if (renaming) { + InlineRenameField( + initialName = node.label, + textStyle = labelStyle.copy(color = colors.text), + cursorColor = colors.text, + onCommit = onCommitRename, + onCancel = onCancelRename, + modifier = Modifier.fillMaxWidth(), + ) + } else { + Text( + text = node.label, + style = labelStyle, + color = labelColor, + maxLines = 1, + overflow = TextOverflow.Clip, + ) + } + } + // Selectability applies to any real entity (deformers included), so its column covers every real + // row; the eye only parts / drawables. The filter dropdown's restriction toggles gate each column + // wholesale - a hidden column composes nothing, so its slot vanishes and a click there selects the + // row like any other blank space (outlinerContentWidth mirrors this same math). + if (showSelectableColumn && node.target != null) { + SelectableIndicator( + selectable = node.selectable, + tint = colors.textMuted, + onToggle = onToggleSelectable, + ) + } + if (showVisibilityColumn && showEye) { + VisibilityIndicator( + hidden = node.dimmed, + tint = colors.textMuted, + onToggle = onToggleVisibility, + ) + } + if (node.target != null) { + Spacer(modifier = Modifier.width(6.dp)) + } + } +} + +/** + * The disclosure chevron slot - a fixed-width box drawing a right (collapsed) or down (expanded) + * triangle, the whole slot toggling expansion. Always occupies its width even when [visible] is false, + * so leaf and parent rows align. + * + * The accessible name is the action a click performs, because the row's own name never says whether the + * node is open - the chevron is the only place that state is exposed. It carries no tooltip for the + * matching reason [org.umamo.ui.kit.DisclosureChevron] carries none: the row label sits right beside it. + * + * @param Boolean visible Whether to draw the chevron (false for a childless node). + * @param Boolean expanded Whether the node is expanded. + * @param Function onToggle Toggle callback. + * @param Color tint The chevron color. + */ +@Composable +private fun ChevronSlot(visible: Boolean, expanded: Boolean, onToggle: () -> Unit, tint: Color) { + val base = Modifier.size(CHEVRON_WIDTH) + // Consume the press so the row's whole-row selection handler skips it (the chevron only toggles). + val slot = + if (visible) { + val toggleLabel = stringResource(if (expanded) Res.string.common_collapse else Res.string.common_expand) + base + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if (event.type == PointerEventType.Press) { + event.changes.forEach { change -> change.consume() } + onToggle() + } + } + } + } + .semantics { contentDescription = toggleLabel } + } else { + base + } + Box(modifier = slot, contentAlignment = Alignment.Center) { + if (visible) { + Canvas(modifier = Modifier.size(9.dp)) { + val chevron = Path() + if (expanded) { + chevron.moveTo(size.width * 0.15f, size.height * 0.35f) + chevron.lineTo(size.width * 0.85f, size.height * 0.35f) + chevron.lineTo(size.width * 0.50f, size.height * 0.72f) + } else { + chevron.moveTo(size.width * 0.35f, size.height * 0.15f) + chevron.lineTo(size.width * 0.72f, size.height * 0.50f) + chevron.lineTo(size.width * 0.35f, size.height * 0.85f) + } + chevron.close() + drawPath(chevron, color = tint) + } + } + } +} + +/** + * The type-icon slot: a fixed-width box drawing the themed vector icon for [OutlinerIcon] (from the + * shared UmamoIcons set), distinct enough to tell the kinds apart at a glance. Each node family carries + * a signature palette tint ([UmamoColors.outlinerObjectTint] / [UmamoColors.outlinerDeformTint], after + * Blender's armature object / data colours) - only this function maps an [OutlinerIcon] to its art, so + * the row layout never changes when an icon does. + * + * @param OutlinerIcon icon The icon kind. + * @param Boolean dimmed Whether the row is muted (the glyph fades to match). + */ +@Composable +private fun OutlinerIconSlot(icon: OutlinerIcon, dimmed: Boolean) { + val colors = LocalUmamoColors.current + val tint = + when (icon) { + OutlinerIcon.PuppetRoot, OutlinerIcon.Part, OutlinerIcon.Drawable -> + if (dimmed) colors.outlinerObjectTintDimmed else colors.outlinerObjectTint + OutlinerIcon.Armature, OutlinerIcon.WarpDeformer, OutlinerIcon.RotationDeformer -> + if (dimmed) colors.outlinerDeformTintDimmed else colors.outlinerDeformTint + } + Box(modifier = Modifier.size(ICON_WIDTH), contentAlignment = Alignment.Center) { + Canvas(modifier = Modifier.size(20.dp)) { + val width = size.width + val height = size.height + val stroke = Stroke(width = width * 0.12f) + when (icon) { + OutlinerIcon.PuppetRoot -> drawIcon(LocalUmamoIcons.puppetRoot, tint) + OutlinerIcon.Armature -> drawIcon(LocalUmamoIcons.armature, tint) + OutlinerIcon.Part -> drawIcon(LocalUmamoIcons.part, tint) + OutlinerIcon.Drawable -> drawIcon(LocalUmamoIcons.mesh, tint) + OutlinerIcon.WarpDeformer -> drawIcon(LocalUmamoIcons.warpDeformer, tint) + OutlinerIcon.RotationDeformer -> drawIcon(LocalUmamoIcons.rotationDeformer, tint) + } + } + } +} + +/** + * The clickable visibility eye: open while the row's entity is shown, struck-through while hidden. + * Clicking flips the entity's visibility; with Shift held it flips the whole subtree to one uniform value + * (Blender parity). The slot consumes its own press so the whole-row selection handler skips it, + * mirroring the chevron. + * + * Unlike the chevron this one does take a tooltip: the eye is genuinely icon-only, and nothing else in the + * row says what it does. It reuses the context menu's own label so the two routes to the same edit read + * identically. + * + * @param Boolean hidden Whether the row is dimmed (hidden or sketch). + * @param Color tint The indicator color. + * @param Function onToggle Flips the visibility; the argument reports whether Shift was held (subtree). + */ +@Composable +private fun VisibilityIndicator(hidden: Boolean, tint: Color, onToggle: (shiftHeld: Boolean) -> Unit) { + /* pointerInput(Unit) never re-captures its closures, so route through rememberUpdatedState to keep the + long-lived loop pointed at the latest callback (the row body's own convention). */ + val currentOnToggle by rememberUpdatedState(onToggle) + // Consume the press so the row's whole-row selection handler skips it (the eye only toggles visibility), + // mirroring the chevron's own consume. + val toggleGesture = + Modifier.pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if (event.type == PointerEventType.Press) { + event.changes.forEach { change -> change.consume() } + currentOnToggle(event.keyboardModifiers.isShiftPressed) + } + } + } + } + IconSlot( + icon = if (hidden) LocalUmamoIcons.eyeHidden else LocalUmamoIcons.eyeVisible, + contentDescription = stringResource(Res.string.outliner_menu_visibility), + tint = tint, + modifier = toggleGesture, + slotSize = DpSize(RESTRICTION_SLOT_WIDTH, RESTRICTION_SLOT_WIDTH), + glyphSize = 16.dp, + ) +} + +/** + * The trailing selectable toggle: a small pointer the user clicks to flip whether the row's entity can be + * picked in the viewport; with Shift held it flips the whole subtree to one uniform value (Blender + * parity). An unselectable entity shows the struck-through pointer; a selectable one the plain pointer. + * The slot consumes its own press so the whole-row selection handler skips it, mirroring the chevron and + * the eye. + * + * Labelled and tooltipped from the context menu's own string, for the reason [VisibilityIndicator] is. + * + * @param Boolean selectable Whether the entity is viewport-selectable (plain vs struck-through pointer). + * @param Color tint The base glyph color. + * @param Function onToggle Flips the selectability; the argument reports whether Shift was held (subtree). + */ +@Composable +private fun SelectableIndicator(selectable: Boolean, tint: Color, onToggle: (shiftHeld: Boolean) -> Unit) { + /* pointerInput(Unit) never re-captures its closures, so route through rememberUpdatedState to keep the + long-lived loop pointed at the latest callback (the row body's own convention). */ + val currentOnToggle by rememberUpdatedState(onToggle) + IconSlot( + icon = if (selectable) LocalUmamoIcons.selectable else LocalUmamoIcons.unselectable, + contentDescription = stringResource(Res.string.outliner_menu_selectable), + tint = tint, + modifier = + Modifier.pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if (event.type == PointerEventType.Press) { + event.changes.forEach { change -> change.consume() } + currentOnToggle(event.keyboardModifiers.isShiftPressed) + } + } + } + }, + slotSize = DpSize(RESTRICTION_SLOT_WIDTH, RESTRICTION_SLOT_WIDTH), + glyphSize = 16.dp, + ) +} + +/** + * Computes the selection after a row click given the held modifiers: plain replaces, Ctrl / Cmd + * ([toggle]) toggles the one target, and Shift ([extend]) range-selects from the active row to the + * clicked one over the currently visible [rows], adding that contiguous run to the existing selection + * (a mass-select). With no active anchor the range is just the clicked row. + * + * @param List rows The currently visible rows, in display order (the range runs over these). + * @param Selection current The selection before the click. + * @param Int clickedIndex The clicked row's index in [rows]. + * @param SelectionTarget target The clicked row's target (becomes active). + * @param Boolean toggle Whether Ctrl / Cmd was held. + * @param Boolean extend Whether Shift was held (range select). + * @return Selection The resulting selection. + */ +private fun selectionAfterClick( + rows: List, + current: Selection, + clickedIndex: Int, + target: SelectionTarget, + toggle: Boolean, + extend: Boolean, +): Selection = + when { + extend -> outlinerRangeSelection(rows.map { it.node.target }, current, clickedIndex, target) + toggle -> SelectionOps.toggle(current, target) + else -> SelectionOps.replace(target) + } + +/** + * Measures the single width every row is fixed to: the wider of the viewport and the longest row (its + * indent + chevron + icon + gap + the measured label + the trailing restriction slots its row kind and + * the active restriction toggles compose). Fixing all rows to one width is what keeps the selection / + * hover backgrounds full-width and the horizontal scroll range constant as rows scroll in and out. + * Run once per visible-row set (memoised by the caller), not per frame. + * + * @param List rows The visible rows. + * @param TextMeasurer measurer Measures label widths. + * @param Density density For dp <-> px conversion. + * @param Dp viewportWidth The available width - the floor for the result. + * @param TextStyle bodyStyle The label style for non-drawable rows. + * @param TextStyle drawableStyle The label style for drawable rows. + * @param Boolean showSelectableColumn Whether the pointer restriction column renders. + * @param Boolean showVisibilityColumn Whether the eye restriction column renders. + * @return Dp The shared row width. + */ +private fun outlinerContentWidth( + rows: List, + measurer: TextMeasurer, + density: Density, + viewportWidth: Dp, + bodyStyle: TextStyle, + drawableStyle: TextStyle, + showSelectableColumn: Boolean, + showVisibilityColumn: Boolean, +): Dp = + with(density) { + val basePx = 4.dp.toPx() + val perDepthPx = INDENT_PER_DEPTH.toPx() + val fixedPx = CHEVRON_WIDTH.toPx() + ICON_WIDTH.toPx() + 4.dp.toPx() + val restrictionSlotPx = RESTRICTION_SLOT_WIDTH.toPx() + val trailingSpacerPx = 6.dp.toPx() + val trailingPx = 8.dp.toPx() + var maxPx = viewportWidth.toPx() + for (row in rows) { + val style = if (row.node.target is SelectionTarget.Drawable) drawableStyle else bodyStyle + val labelPx = measurer.measure(row.node.label, style).size.width.toFloat() + val hasTarget = row.node.target != null + val showEye = row.node.target is SelectionTarget.Part || row.node.target is SelectionTarget.Drawable + // Must mirror the row body's trailing slots exactly: a selectable slot for every real row when + // that column is on, an eye slot for parts / drawables when that column is on, and the trailing + // spacer every real row keeps regardless. + val trailingSlotsPx = + (if (showSelectableColumn && hasTarget) restrictionSlotPx else 0f) + + (if (showVisibilityColumn && showEye) restrictionSlotPx else 0f) + + (if (hasTarget) trailingSpacerPx else 0f) + val rowPx = basePx + perDepthPx * row.depth + fixedPx + labelPx + trailingSlotsPx + trailingPx + if (rowPx > maxPx) { + maxPx = rowPx + } + } + maxPx.toDp() + } + +/** + * Flattens the tree into the visible rows for the [LazyColumn], descending into a node's children only + * when [isOpen] reports it expanded. Pure given the predicate, so the reveal effect can recompute the + * same index the body renders. + * + * @param OutlinerNode root The tree root. + * @param Function isOpen Reports whether a node id is expanded. + * @return List the visible rows, each with its depth. + */ +private fun flattenOutliner(root: OutlinerNode, isOpen: (String) -> Boolean): List { + val rows = mutableListOf() + + fun visit(node: OutlinerNode, depth: Int) { + rows += FlatRow(node, depth) + if (isOpen(node.id)) { + node.children.forEach { child -> visit(child, depth + 1) } + } + } + + visit(root, 0) + return rows +} + +/** + * Finds the id path from [root] to the node carrying [target], inclusive, or null if absent. Used by + * reveal-on-select to expand a found node's ancestors before scrolling to it. + * + * @param OutlinerNode root The tree (sub)root to search. + * @param SelectionTarget target The selection target to locate. + * @return List the node ids from root to the match, or null. + */ +private fun pathTo(root: OutlinerNode, target: SelectionTarget): List? { + if (root.target == target) { + return listOf(root.id) + } + for (child in root.children) { + val sub = pathTo(child, target) + if (sub != null) { + return listOf(root.id) + sub + } + } + return null +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerTree.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerTree.kt new file mode 100644 index 0000000..ca4cd9b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerTree.kt @@ -0,0 +1,272 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PuppetModel + +/** The stable node id of the synthetic puppet root - the one row open by default in the outliner. */ +const val OUTLINER_ROOT_ID = "root" + +/** The stable node id of the synthetic Armature deformer-hierarchy row. */ +const val OUTLINER_ARMATURE_ID = "armature" + +/** + * The icon a row carries, drawn as themed vector art from the shared UmamoIcons set inside a reserved + * fixed-width slot (see OutlinerIconSlot). The two synthetic roots mirror Blender's armature object / + * armature data icons. + */ +enum class OutlinerIcon { + /** The puppet root (Blender's orange armature-object icon). */ + PuppetRoot, + + /** The deformer-hierarchy group node (Blender's green armature-data icon). */ + Armature, + + /** An organizational part / folder. */ + Part, + + /** A drawable art mesh. */ + Drawable, + + /** A warp (FFD lattice) deformer. */ + WarpDeformer, + + /** A rotation (pivot) deformer. */ + RotationDeformer, +} + +/** + * One node in the unified outliner tree: the Blender-style single tree that folds Cubism's split Part + * and Deformer panels into one. A node is a part, a drawable, a deformer, or one of the two synthetic + * grouping rows (the puppet root and the Armature deformer-hierarchy node). Synthetic rows carry a null + * [target] - they only expand / collapse, they do not select. + * + * @property String id A stable, unique key for expand-state and reveal lookup (never reused). + * @property String label The display text (already localised for synthetic rows; raw document name otherwise). + * @property OutlinerIcon icon The placeholder icon kind. + * @property Boolean dimmed Whether the row renders muted (hidden / sketch). + * @property SelectionTarget? target What the row selects when clicked, or null for a synthetic row. + * @property List children The child rows, in display order (drawables before sub-parts within a part). + * @property Boolean selectable Whether the row's entity is viewport-selectable (synthetic rows true). + */ +data class OutlinerNode( + val id: String, + val label: String, + val icon: OutlinerIcon, + val dimmed: Boolean, + val target: SelectionTarget?, + val children: List, + val selectable: Boolean = true, +) + +/** + * Builds the unified outliner tree from a puppet: one root holding the Armature deformer hierarchy + * (all warp / rotation deformers nested by [Deformer.parent], roots being the parentless ones) followed + * by the top-level parts, each part listing its drawables then its sub-parts. This is a pure function + * over [PuppetModel] so it unit-tests without Compose. Cross-links (which deformer deforms a drawable, + * which part owns a deformer) are deliberately absent - they belong in the Properties panel, not + * duplicated into the tree, which is exactly what makes Cubism's twin-panel layout confusing. + * + * @param PuppetModel puppet The rig to walk. + * @param String rootLabel The localised label for the puppet root row. + * @param String armatureLabel The localised label for the deformer-hierarchy row. + * @return OutlinerNode The root node of the unified tree. + */ +fun buildOutlinerTree(puppet: PuppetModel, rootLabel: String = "Armature", armatureLabel: String = "Armature"): OutlinerNode { + val armature = buildArmatureNode(puppet, armatureLabel) + + val partsById = puppet.parts.associateBy { part -> part.id } + val drawablesById = puppet.drawables.associateBy { drawable -> drawable.id } + + fun drawableNode(drawable: Drawable): OutlinerNode = + OutlinerNode( + id = "drawable:${drawable.id.raw}", + label = drawable.name, + icon = OutlinerIcon.Drawable, + dimmed = !drawable.isVisible, + target = SelectionTarget.Drawable(drawable.id), + children = emptyList(), + selectable = drawable.isSelectable, + ) + + // The org tree is already a single interleaved order of sub-parts and drawables per level, so the + // outliner just reads it - no separate merge. A node that does not resolve (a dangling id) is dropped. + // childNodes and partNode are mutually recursive (a part's children may be parts), so childNodes is a + // var the part builder closes over and that is assigned the real body once partNode exists. + var childNodes: (List) -> List = { emptyList() } + + fun partNode(part: Part): OutlinerNode = + OutlinerNode( + id = "part:${part.id.raw}", + label = part.name, + icon = OutlinerIcon.Part, + dimmed = !part.isVisible || part.isSketch, + target = SelectionTarget.Part(part.id), + children = childNodes(part.children), + selectable = part.isSelectable, + ) + + childNodes = { children -> + children.mapNotNull { child -> + when (child) { + is OrgChild.Drawable -> drawablesById[child.id]?.let { drawableNode(it) } + is OrgChild.Part -> partsById[child.id]?.let { partNode(it) } + } + } + } + + return OutlinerNode( + id = OUTLINER_ROOT_ID, + label = rootLabel, + icon = OutlinerIcon.PuppetRoot, + dimmed = false, + target = null, + children = listOf(armature) + childNodes(puppet.rootChildren), + ) +} + +/** + * Prunes the tree for the outliner header's search box and kind toggles, returning a new root. Runs two + * passes: first the kind toggles ([showParts] / [showDrawables] / [showDeformers]) drop whole kinds - + * turning Parts off hoists their drawables up rather than hiding them, so the meshes flatten instead of + * vanishing - then the [query] keeps only rows whose name (or a descendant's) matches (case-insensitive + * substring; blank matches everything). A name match keeps its whole kind-filtered subtree so a matched + * part still shows its contents; ancestors of a deeper match are retained as the path to it. The puppet + * root always survives so the panel never goes fully blank. + * + * @param OutlinerNode root The full tree. + * @param String query The case-insensitive name filter (blank = no name filter). + * @param Boolean showParts Whether to keep part / folder rows (false hoists their drawables up). + * @param Boolean showDrawables Whether to keep drawable rows. + * @param Boolean showDeformers Whether to keep the Armature deformer hierarchy. + * @return OutlinerNode The pruned root. + */ +fun filterOutliner(root: OutlinerNode, query: String, showParts: Boolean, showDrawables: Boolean, showDeformers: Boolean): OutlinerNode { + val kindRoot = kindFiltered(root, showParts, showDrawables, showDeformers).firstOrNull() ?: root.copy(children = emptyList()) + return queryPruned(kindRoot, query.trim()) ?: kindRoot.copy(children = emptyList()) +} + +/** + * Computes a Shift-click range selection over the outliner's visible rows: the contiguous run of targets + * from the active anchor to the clicked row (inclusive, in either direction) is added to the existing + * selection, and the clicked target becomes active. With no current anchor the range is just the clicked + * row. Pure over the ordered target list (the row order the user sees), so it unit-tests without Compose; + * the visible-row order encodes the range, which is why this takes [orderedTargets] rather than the tree. + * + * @param List orderedTargets The visible rows' targets in display order (null for non-selectable rows). + * @param Selection current The selection before the click. + * @param Int clickedIndex The clicked row's index in [orderedTargets]. + * @param SelectionTarget clickedTarget The clicked row's target (becomes active). + * @return Selection The selection after the range add. + */ +fun outlinerRangeSelection(orderedTargets: List, current: Selection, clickedIndex: Int, clickedTarget: SelectionTarget): Selection { + val anchorIndex = current.active?.let { active -> orderedTargets.indexOfFirst { it == active } }?.takeIf { it >= 0 } ?: clickedIndex + val low = minOf(anchorIndex, clickedIndex) + val high = maxOf(anchorIndex, clickedIndex) + val rangeTargets = orderedTargets.subList(low, high + 1).filterNotNull() + return Selection(current.targets + rangeTargets, clickedTarget) +} + +/** + * The kind-toggle pass: returns the node (with kind-filtered children) as a one-element list, an empty + * list when its whole kind is hidden, or - for a hidden part - just its kept children, hoisting the + * drawables up so they flatten under the part's parent instead of disappearing. Returns a list (not a + * nullable node) precisely so a dropped part can splice multiple children into its parent. + * + * @param OutlinerNode node The node to filter. + * @param Boolean showParts Whether part rows are kept. + * @param Boolean showDrawables Whether drawable rows are kept. + * @param Boolean showDeformers Whether the deformer hierarchy is kept. + * @return List the node (possibly hoisted away), as a list. + */ +private fun kindFiltered(node: OutlinerNode, showParts: Boolean, showDrawables: Boolean, showDeformers: Boolean): List { + val isDeformerKind = node.icon == OutlinerIcon.Armature || node.icon == OutlinerIcon.WarpDeformer || node.icon == OutlinerIcon.RotationDeformer + if (!showDeformers && isDeformerKind) { + return emptyList() + } + if (!showDrawables && node.icon == OutlinerIcon.Drawable) { + return emptyList() + } + val keptChildren = node.children.flatMap { child -> kindFiltered(child, showParts, showDrawables, showDeformers) } + return if (!showParts && node.icon == OutlinerIcon.Part) { + keptChildren + } else { + listOf(node.copy(children = keptChildren)) + } +} + +/** + * The name-search pass over an already kind-filtered tree: a node survives when it matches [query] or any + * descendant does, but only the path down to each match is kept - a matched node keeps just its matching + * descendants, not its whole subtree, so searching "bag" shows the branches down to the bag rows and not + * every unrelated child under them. A blank query keeps the tree unchanged; the puppet root survives even + * with no match so the panel never goes blank. + * + * @param OutlinerNode node The kind-filtered node. + * @param String query The trimmed, case-insensitive name filter (empty matches everything). + * @return OutlinerNode? The pruned node, or null when neither it nor any descendant matches. + */ +private fun queryPruned(node: OutlinerNode, query: String): OutlinerNode? { + if (query.isEmpty()) { + return node + } + val selfMatches = node.label.contains(query, ignoreCase = true) + val keptChildren = node.children.mapNotNull { child -> queryPruned(child, query) } + return when { + selfMatches || keptChildren.isNotEmpty() -> node.copy(children = keptChildren) + node.icon == OutlinerIcon.PuppetRoot -> node.copy(children = emptyList()) + else -> null + } +} + +/** + * Builds the Armature node: every deformer nested by [Deformer.parent] (parentless deformers are the + * roots), preserving the model's list order among siblings. Always present even when the rig has no + * deformers, so the tree's structure is stable. A [visited] guard tolerates a malformed cyclic parent + * reference, mirroring the parts / parameter-tree walks in the importer. + * + * @param PuppetModel puppet The rig whose deformers populate the node. + * @param String armatureLabel The localised label for the node. + * @return OutlinerNode The Armature deformer-hierarchy node. + */ +private fun buildArmatureNode(puppet: PuppetModel, armatureLabel: String): OutlinerNode { + val childrenByParent = puppet.deformers.groupBy { deformer -> deformer.parent } + val visited = HashSet() + + fun deformerNode(deformer: Deformer): OutlinerNode { + val icon = + when (deformer) { + is Deformer.Warp -> OutlinerIcon.WarpDeformer + is Deformer.Rotation -> OutlinerIcon.RotationDeformer + } + val children = + if (visited.add(deformer.id.raw)) { + childrenByParent[deformer.id].orEmpty().map { child -> deformerNode(child) } + } else { + emptyList() + } + return OutlinerNode( + id = "deformer:${deformer.id.raw}", + label = deformer.name, + icon = icon, + dimmed = false, + target = SelectionTarget.Deformer(deformer.id), + children = children, + selectable = deformer.isSelectable, + ) + } + + val roots = childrenByParent[null].orEmpty().map { deformer -> deformerNode(deformer) } + return OutlinerNode( + id = OUTLINER_ARMATURE_ID, + label = armatureLabel, + icon = OutlinerIcon.Armature, + dimmed = false, + target = null, + children = roots, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerViewState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerViewState.kt new file mode 100644 index 0000000..a863404 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/OutlinerViewState.kt @@ -0,0 +1,100 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.foldDeviationsOf +import org.umamo.ui.workspace.restoreFoldStates +import org.umamo.ui.workspace.stringArrayOrNull +import org.umamo.ui.workspace.stringListOf + +/** The AreaScope.spaceState key the outliner parks its view state under, and its member in an area block (UMA §7.3). */ +internal const val OUTLINER_VIEW_STATE_KEY = "outliner" + +/** + * The outliner's search, filter, and open-branch state, shared between its area-header controls and its body + * (they render as sibling subtrees, so this lives on the hosting AreaScope via spaceState rather than in a + * body-local remember). Two outliner areas each get their own instance, and the instance lives as long as the + * open document does. A saved document carries everything here but the search query (UMA §7.3): a file + * that reopened to last week's filtered list would read as a broken panel. + */ +internal class OutlinerViewState : PersistentSpaceState { + /** The name-search query; blank shows the whole tree. */ + var query by mutableStateOf("") + + /** + * Each branch's open state by stable node id; an absent id follows [outlinerOpensByDefault]. Not keyed on + * the puppet: the model changes identity on every edit and undo, and a rename must not fold the tree. + */ + val expanded = mutableStateMapOf() + + /** Whether part rows are shown. */ + var showParts by mutableStateOf(true) + + /** Whether drawable rows are shown. */ + var showDrawables by mutableStateOf(true) + + /** Whether the Armature deformer hierarchy is shown. */ + var showDeformers by mutableStateOf(true) + + /** Whether the pointer restriction indicator column renders on the rows. */ + var showSelectableColumn by mutableStateOf(true) + + /** Whether the eye restriction indicator column renders on the rows. */ + var showVisibilityColumn by mutableStateOf(true) + + val isUnfiltered: Boolean get() = showParts && showDrawables && showDeformers + + /** + * Whether the branch [nodeId] is open. + * + * @param String nodeId The outliner node id. + * @return Boolean True when open. + */ + fun isOpen(nodeId: String): Boolean = expanded[nodeId] ?: outlinerOpensByDefault(nodeId) + + /** + * The outliner's member of its area block. + * + * @return JsonObject The member, every known key named. + */ + override fun toJson(): JsonObject { + // UMA §7.3: the fold state is two arrays of node ids, the deviations from "only the root is open". + val (opened, closed) = foldDeviationsOf(expanded, ::outlinerOpensByDefault) + return buildJsonObject { + put("expanded", opened) + put("collapsed", closed) + // UMA §7.3: `hidden` names the row kinds filtered out, `hiddenColumns` the restriction columns switched off. + put("hidden", stringArrayOrNull(listOfNotNull("parts".takeUnless { showParts }, "drawables".takeUnless { showDrawables }, "deformers".takeUnless { showDeformers }))) + put("hiddenColumns", stringArrayOrNull(listOfNotNull("selectable".takeUnless { showSelectableColumn }, "visibility".takeUnless { showVisibilityColumn }))) + } + } + + /** + * Takes the outliner state a document was saved with. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + restoreFoldStates(expanded, tree, "expanded", "collapsed") + val hidden = stringListOf(tree, "hidden").orEmpty() + showParts = "parts" !in hidden + showDrawables = "drawables" !in hidden + showDeformers = "deformers" !in hidden + val hiddenColumns = stringListOf(tree, "hiddenColumns").orEmpty() + showSelectableColumn = "selectable" !in hiddenColumns + showVisibilityColumn = "visibility" !in hiddenColumns + } +} + +/** + * Whether an outliner branch is open when nothing is recorded for it: only the root is. + * + * @param String nodeId The outliner node id. + * @return Boolean True for the root. + */ +internal fun outlinerOpensByDefault(nodeId: String): Boolean = nodeId == OUTLINER_ROOT_ID \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParameterObjectBinding.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParameterObjectBinding.kt new file mode 100644 index 0000000..ecd82c3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParameterObjectBinding.kt @@ -0,0 +1,214 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.eval.allAxes +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel + +/* + * The object -> parameters relation behind the "show only the selected object's parameters" filter. A + * parameter affects an object when it is an axis of a keyform grid that deforms it. Because a drawable is + * usually deformed by its parent deformer chain rather than keyed directly, the EFFECTIVE set unions the + * object's own axes with every ancestor deformer's axes (and, for a part, its member drawables' effective + * sets). Compose-free so it can be unit-tested; every axis references one parameter by KeyformAxis.parameterId. + * + * 選択オブジェクトに影響するパラメータ集合(自身のキーフォーム軸+親デフォーマ連鎖の軸)。 + */ + +/** + * The set of parameter ids that effectively drive [selection] in [puppet]: for each selected target, the + * union of the object's own keyform-grid axes and, following the deformer chain, its ancestor deformers' + * axes. A selected part contributes its own channel-track axes (draw order and, while isolated, its + * composite opacity / color tracks) plus the effective set of every drawable it contains. Empty when the + * selection is empty. + * + * @param PuppetModel puppet The loaded rig. + * @param Selection selection The current selection (drawables / deformers / parts). + * @return Set Every parameter that affects any selected object. + */ +internal fun effectiveParameterIds(puppet: PuppetModel, selection: Selection): Set { + if (selection.isEmpty) { + return emptySet() + } + val deformerById = puppet.deformers.associateBy { deformer -> deformer.id } + val drawableById = puppet.drawables.associateBy { drawable -> drawable.id } + val partById = puppet.parts.associateBy { part -> part.id } + val gluesByMesh = puppet.gluesByMesh() + val result = HashSet() + + // Walks the deformer nesting from [startDeformerId] up through parents, adding each deformer's axes + // and blend-shape drivers. A visited guard defends against a malformed cyclic parent chain. + fun addDeformerChainAxes(startDeformerId: DeformerId?) { + val visited = HashSet() + var current = startDeformerId + while (current != null && visited.add(current)) { + val deformer = deformerById[current] ?: break + deformer.keyformAxes().forEach { axis -> result.add(axis.parameterId) } + deformer.blendShapeDrivers().forEach { parameterId -> result.add(parameterId) } + current = deformer.parent + } + } + + // A drawable's effective set: its own mesh keyform axes and blend-shape drivers, its whole parent + // deformer chain's axes, and the intensity tracks of every glue welding it - a weld visibly moves + // the drawable's vertices, so its driving parameter affects the drawable. + fun addDrawableEffective(drawable: Drawable) { + // Geometry AND channel tracks, so an opacity-only track still reports the parameter driving it. + drawable.geometryGrid?.axes?.forEach { axis -> result.add(axis.parameterId) } + drawable.channelGrids.allAxes().forEach { axis -> result.add(axis.parameterId) } + drawable.blendShapes.forEach { binding -> result.add(binding.parameterId) } + gluesByMesh[drawable.id]?.forEach { glue -> + glue.channelGrids.allAxes().forEach { axis -> result.add(axis.parameterId) } + } + addDeformerChainAxes(drawable.parentDeformerId) + } + + for (target in selection.targets) { + when (target) { + is SelectionTarget.Drawable -> drawableById[target.id]?.let { drawable -> addDrawableEffective(drawable) } + // Start at the deformer itself so its own axes join its ancestors'. + is SelectionTarget.Deformer -> addDeformerChainAxes(target.id) + is SelectionTarget.Part -> + partById[target.id]?.let { part -> + part.channelGrids.allAxes().forEach { axis -> result.add(axis.parameterId) } + collectPartDrawables(part, partById).forEach { drawableId -> + drawableById[drawableId]?.let { drawable -> addDrawableEffective(drawable) } + } + } + } + } + return result +} + +/** Every glue keyed by the meshes it welds, so a drawable's welds resolve without a per-drawable scan. */ +private fun PuppetModel.gluesByMesh(): Map> { + val byMesh = HashMap>() + for (glue in glues) { + byMesh.getOrPut(glue.meshA) { ArrayList() }.add(glue) + byMesh.getOrPut(glue.meshB) { ArrayList() }.add(glue) + } + return byMesh +} + +/** + * A parameter's key marks: the parameter values it is keyed at, split by source. Grid keys come from + * keyform-grid axes (rendered as circle points); blend keys come from blend-shape bindings (square + * points). Each list is sorted ascending and deduplicated. A parameter with neither has no map entry. + * + * @property List gridKeys The keyform-grid axis key values (circle points), sorted ascending. + * @property List blendKeys The blend-shape binding key values (square points), sorted ascending. + */ +internal data class ParameterKeyMarks( + val gridKeys: List, + val blendKeys: List, +) + +/** + * The per-parameter key marks for this rig: for each parameter id keyed by any object, the sorted, + * deduplicated union of the parameter values it is keyed at, split into keyform-grid keys and + * blend-shape keys. One pass over every drawable, deformer, and part (the same objects + * [effectiveParameterIds] walks); a parameter absent from the result has no keys yet. Compose-free so + * the panel can compute it once per model and unit-test it. + * + * @return Map Each keyed parameter's grid + blend key marks. + */ +internal fun PuppetModel.parameterKeyMarks(): Map { + val gridKeysByParameter = HashMap>() + val blendKeysByParameter = HashMap>() + + fun addGridKeys(parameterId: ParameterId, keys: FloatArray) { + val values = gridKeysByParameter.getOrPut(parameterId) { sortedSetOf() } + keys.forEach { keyValue -> values.add(keyValue) } + } + + fun addBlendKeys(parameterId: ParameterId, keys: FloatArray) { + val values = blendKeysByParameter.getOrPut(parameterId) { sortedSetOf() } + keys.forEach { keyValue -> values.add(keyValue) } + } + + for (drawable in drawables) { + drawable.geometryGrid?.axes?.forEach { axis -> addGridKeys(axis.parameterId, axis.keys) } + drawable.channelGrids.allAxes().forEach { axis -> addGridKeys(axis.parameterId, axis.keys) } + drawable.blendShapes.forEach { binding -> addBlendKeys(binding.parameterId, binding.keys) } + } + for (deformer in deformers) { + deformer.keyformAxes().forEach { axis -> addGridKeys(axis.parameterId, axis.keys) } + deformer.blendShapeBindingKeys().forEach { (parameterId, keys) -> addBlendKeys(parameterId, keys) } + } + for (part in parts) { + part.channelGrids.allAxes().forEach { axis -> addGridKeys(axis.parameterId, axis.keys) } + } + // Glue intensity tracks key parameters like every other channel; without this walk a glue-only-keyed + // parameter would show marks in the keyform sheet but none on its Parameters-panel slider. + for (glue in glues) { + glue.channelGrids.allAxes().forEach { axis -> addGridKeys(axis.parameterId, axis.keys) } + } + + val keyedParameters = gridKeysByParameter.keys + blendKeysByParameter.keys + return keyedParameters.associateWith { parameterId -> + ParameterKeyMarks( + gridKeys = gridKeysByParameter[parameterId]?.toList() ?: emptyList(), + blendKeys = blendKeysByParameter[parameterId]?.toList() ?: emptyList(), + ) + } +} + +/** + * This deformer's keyform axes (empty when it is unkeyed), regardless of kind. + * + * Unions the geometry grid's axes with every channel track's, so a deformer keyed only on opacity still + * reports the parameter that drives it - otherwise an opacity-only track would be invisible to the + * parameter panel and the keyform sheet. + */ +private fun Deformer.keyformAxes(): List { + val geometryAxes = + when (this) { + is Deformer.Warp -> geometryGrid?.axes ?: emptyList() + is Deformer.Rotation -> geometryGrid?.axes ?: emptyList() + } + return geometryAxes + channelGrids.allAxes() +} + +/** This deformer's blend-shape bindings as (driving parameter, key values) pairs (empty when none). */ +private fun Deformer.blendShapeBindingKeys(): List> = + when (this) { + is Deformer.Warp -> blendShapes.map { binding -> binding.parameterId to binding.keys } + is Deformer.Rotation -> blendShapes.map { binding -> binding.parameterId to binding.keys } + } + +/** + * The parameters driving this deformer's blend-shape bindings (empty when it has none). Limit-curve + * constraint parameters deliberately do NOT count as edges - a limit gates a binding's weight but + * does not key the object itself. + */ +private fun Deformer.blendShapeDrivers(): List = + when (this) { + is Deformer.Warp -> blendShapes.map { binding -> binding.parameterId } + is Deformer.Rotation -> blendShapes.map { binding -> binding.parameterId } + } + +/** Every drawable id under [part]'s organizational subtree, descending into sub-parts. */ +private fun collectPartDrawables(part: Part, partById: Map): List { + val result = ArrayList() + + fun walk(children: List) { + for (child in children) { + when (child) { + is OrgChild.Drawable -> result.add(child.id) + is OrgChild.Part -> partById[child.id]?.let { subPart -> walk(subPart.children) } + } + } + } + walk(part.children) + return result +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParameterRows.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParameterRows.kt new file mode 100644 index 0000000..f4de07e --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParameterRows.kt @@ -0,0 +1,294 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel + +/** + * One row of the Parameters panel: a group header, a single 1D slider, or a 2D pad for a LINKED pair. + * [depth] is the group nesting level, used to indent the control. Compose-free on purpose - the whole + * row model lives in this file so commonTest can pin the folding and link-candidate rules. + */ +internal sealed interface ParameterRow { + val depth: Int + + /** A collapsible group header (Cubism's CParameterGroup). */ + data class GroupHeader( + val groupId: ParameterGroupId, + val name: String, + override val depth: Int, + val expanded: Boolean, + ) : ParameterRow + + /** + * A standalone parameter rendered as a horizontal slider. [linkCandidateId] is the parameter this + * one may be linked with (the immediately-next parameter in the same run - CMO3's "next parameter + * in document order", never across a group boundary), or null when no valid partner exists: the + * next parameter is absent (last in its run), not animatable, or either side already belongs to a + * link. + */ + data class Single(val parameter: Parameter, override val depth: Int, val linkCandidateId: ParameterId? = null) : ParameterRow + + /** A linked pair rendered as one 2D pad ([horizontal] = X axis, [vertical] = Y axis). */ + data class Pair2D(val horizontal: Parameter, val vertical: Parameter, override val depth: Int) : ParameterRow +} + +/** + * A stable LazyColumn key for a row, unique across all row kinds (parameter and group ids are unique, and + * a link's consumed vertical member is never also emitted as a Single). Keeps each row's slot identity - + * and its remembered state - bound to its data across group expand/collapse. + * + * @param ParameterRow row The row to key. + * @return String A stable, unique key. + */ +internal fun rowKey(row: ParameterRow): String = + when (row) { + is ParameterRow.GroupHeader -> "group:${row.groupId.raw}" + is ParameterRow.Single -> "param:${row.parameter.id.raw}" + is ParameterRow.Pair2D -> "pair:${row.horizontal.id.raw}" + } + +/** + * The animatable-parameter set plus the resolved LINKED-pair lookups, computed once per puppet. + * [linkMemberIds] holds every member of every raw link, including pairs whose partner is not + * animatable: a degenerate link still occupies its members, and offering a second link over one + * would corrupt the model. + */ +internal data class LinkInfo( + val animatableIds: Set, + val verticalByHorizontal: Map, + val verticalMembers: Set, + val linkMemberIds: Set, +) + +/** + * Indexes the puppet's animatable parameters and its LINKED pairs (keeping only pairs whose both members + * are animatable for the pad folding, but ALL link members for the occupied set) for the row builder to + * consult. + * + * @param PuppetModel puppet The loaded rig. + * @return LinkInfo The animatable id set and the link lookups. + */ +internal fun buildLinkInfo(puppet: PuppetModel): LinkInfo { + val animatableIds = puppet.parameters.filter { parameter -> parameter.max > parameter.min }.map { it.id }.toSet() + val verticalByHorizontal = HashMap() + val verticalMembers = HashSet() + val linkMemberIds = HashSet() + for (link in puppet.parameterLinks) { + linkMemberIds.add(link.horizontal) + linkMemberIds.add(link.vertical) + if (link.horizontal in animatableIds && link.vertical in animatableIds) { + verticalByHorizontal[link.horizontal] = link.vertical + verticalMembers.add(link.vertical) + } + } + return LinkInfo(animatableIds, verticalByHorizontal, verticalMembers, linkMemberIds) +} + +/** + * The parameters whose name or id contains [query], case-insensitively - the header search's filter set, + * shaped to feed [buildParameterRows]'s visibleParamIds. The id matches as well as the displayed name + * because a rigger migrating from Cubism knows the axis as ParamAngleX however the row was renamed; ids + * are format-level identifiers and are never localized, so matching them needs no locale handling. + * + * @param PuppetModel puppet The loaded rig. + * @param String query The search text; the caller skips a blank one, which would match everything. + * @return Set The matching parameter ids. + */ +internal fun parameterIdsMatching(puppet: PuppetModel, query: String): Set = + puppet.parameters + .filter { parameter -> + parameter.name.contains(query, ignoreCase = true) || parameter.id.raw.contains(query, ignoreCase = true) + } + .mapTo(HashSet()) { parameter -> parameter.id } + +/** + * Flattens the parameter-panel group tree into an ordered list of render rows. Each group emits a + * [ParameterRow.GroupHeader] and, when expanded, recurses its children one level deeper; each run of + * consecutive parameter siblings is paired into [ParameterRow.Single] / [ParameterRow.Pair2D]. Falls + * back to a single flat run when the model carries no groups. + * + * @param PuppetModel puppet The loaded rig. + * @param LinkInfo linkInfo Animatable + link lookups from [buildLinkInfo]. + * @param Map parameterById id -> Parameter, for resolving tree leaves and link partners. + * @param Map expanded Live group expand state (group id -> open); absent => initiallyOpen. + * @param Set? visibleParamIds When non-null, only parameters in this set are emitted (the "affects + * the selected object" filter and the header search), and a group with + * no surviving rows is dropped; null means no filter (every parameter + * is shown). + * @param Boolean forceExpanded When true every group renders open whatever [expanded] says - what a + * search does, so a match cannot hide inside a collapsed group. The + * rigger's own fold state is read again the moment it is false. + * @return List The rows in panel order. + */ +internal fun buildParameterRows( + puppet: PuppetModel, + linkInfo: LinkInfo, + parameterById: Map, + expanded: Map, + visibleParamIds: Set? = null, + forceExpanded: Boolean = false, +): List { + val rows = ArrayList() + if (puppet.parameterTree.isEmpty()) { + rows += pairRun(puppet.parameters, depth = 0, linkInfo = linkInfo, parameterById = parameterById, visibleParamIds = visibleParamIds) + return rows + } + walkParameterNodes( + puppet.parameterTree, + depth = 0, + linkInfo = linkInfo, + parameterById = parameterById, + expanded = expanded, + visibleParamIds = visibleParamIds, + forceExpanded = forceExpanded, + out = rows, + ) + return rows +} + +/** + * Recursively appends rows for [nodes] at [depth]: parameter leaves accumulate into a run (flushed + * through [pairRun] at each group boundary and at the end), and a group emits its header then, if + * expanded, recurses. + * + * @param List nodes The sibling nodes to walk. + * @param Int depth The current group nesting level. + * @param LinkInfo linkInfo Animatable + link lookups. + * @param Map parameterById id -> Parameter. + * @param Map expanded Live group expand state. + * @param Set? visibleParamIds The filter set, or null for no filter (see [buildParameterRows]). + * @param Boolean forceExpanded Whether every group renders open (see [buildParameterRows]). + * @param MutableList out The accumulating row list. + */ +private fun walkParameterNodes( + nodes: List, + depth: Int, + linkInfo: LinkInfo, + parameterById: Map, + expanded: Map, + visibleParamIds: Set?, + forceExpanded: Boolean, + out: MutableList, +) { + val run = ArrayList() + for (node in nodes) { + when (node) { + is ParameterNode.Param -> { + parameterById[node.id]?.let { run.add(it) } + } + + is ParameterNode.Group -> { + if (run.isNotEmpty()) { + out += pairRun(run, depth, linkInfo, parameterById, visibleParamIds) + run.clear() + } + // While filtering, drop a group whose subtree holds no visible parameter (no empty headers) - + // checked independent of expansion, since a collapsed group must still vanish when it is empty. + if (visibleParamIds != null && !groupHasVisibleParam(node, linkInfo, visibleParamIds)) { + continue + } + val isExpanded = forceExpanded || (expanded[node.id] ?: node.initiallyOpen) + out += ParameterRow.GroupHeader(node.id, node.name, depth, isExpanded) + if (isExpanded) { + walkParameterNodes(node.children, depth + 1, linkInfo, parameterById, expanded, visibleParamIds, forceExpanded, out) + } + } + } + } + if (run.isNotEmpty()) { + out += pairRun(run, depth, linkInfo, parameterById, visibleParamIds) + } +} + +/** + * Whether [group]'s subtree holds at least one animatable parameter in [visible] - the test that keeps a + * group header (and lets it survive the filter) only when it has something to show, recursing into nested + * groups. + * + * @param ParameterNode.Group group The group to test. + * @param LinkInfo linkInfo Animatable lookups. + * @param Set visible The filter set (parameter ids to keep). + * @return Boolean True when any animatable leaf under the group is in [visible]. + */ +private fun groupHasVisibleParam(group: ParameterNode.Group, linkInfo: LinkInfo, visible: Set): Boolean { + for (child in group.children) { + when (child) { + is ParameterNode.Param -> + if (child.id in visible && child.id in linkInfo.animatableIds) { + return true + } + + is ParameterNode.Group -> + if (groupHasVisibleParam(child, linkInfo, visible)) { + return true + } + } + } + return false +} + +/** + * Converts a run of sibling parameters into slider / pad rows: a non-animatable parameter is skipped, a + * LINKED pair's vertical member is folded into its horizontal's pad (and skipped on its own), and every + * other animatable parameter becomes a slider. All emitted rows carry [depth] for indentation. + * + * Each slider row also carries its link candidate - the parameter a link click would pair it with. + * The candidate is the run's immediately-next parameter (CMO3's "next parameter in document order", + * scoped to the run so a link never crosses a group boundary - [walkParameterNodes] flushes runs at + * every group) when that next parameter is animatable and NEITHER side already belongs to any link; + * otherwise null and the row offers no link affordance. + * // CMO3: CParameterSource.combined - first member flags the pair, partner is the next parameter in + * // document order (see Cmo3Import's link derivation). + * + * @param List params The parameter run, in panel order. + * @param Int depth The group nesting level for the emitted rows. + * @param LinkInfo linkInfo Animatable + link lookups. + * @param Map parameterById id -> Parameter, for resolving a link's vertical partner. + * @param Set? visibleParamIds The filter set, or null for no filter. A slider survives when its id is + * in the set; a pad survives when EITHER member is (it is one control). + * @return List The slider / pad rows for the run. + */ +private fun pairRun( + params: List, + depth: Int, + linkInfo: LinkInfo, + parameterById: Map, + visibleParamIds: Set?, +): List = + buildList { + for ((runIndex, parameter) in params.withIndex()) { + if (parameter.id !in linkInfo.animatableIds) { + continue + } + if (parameter.id in linkInfo.verticalMembers) { + continue + } + val verticalId = linkInfo.verticalByHorizontal[parameter.id] + val vertical = verticalId?.let { parameterById[it] } + if (vertical != null) { + // A pad is one control over two axes, so it survives the filter if either axis is visible. + if (visibleParamIds == null || parameter.id in visibleParamIds || vertical.id in visibleParamIds) { + add(ParameterRow.Pair2D(parameter, vertical, depth)) + } + } else { + if (visibleParamIds == null || parameter.id in visibleParamIds) { + val nextParameter = params.getOrNull(runIndex + 1) + val linkCandidateId = + if ( + nextParameter != null && + nextParameter.id in linkInfo.animatableIds && + parameter.id !in linkInfo.linkMemberIds && + nextParameter.id !in linkInfo.linkMemberIds + ) { + nextParameter.id + } else { + null + } + add(ParameterRow.Single(parameter, depth, linkCandidateId)) + } + } + } + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersDropRules.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersDropRules.kt new file mode 100644 index 0000000..11455f3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersDropRules.kt @@ -0,0 +1,154 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.ParameterMoveSubject +import org.umamo.edit.ParameterNodeRef +import org.umamo.edit.RowDropBand +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel + +// Above / below these fractions a group-header drop reads as reorder (before / after) rather than nest. +private const val GROUP_NEST_LOW_FRACTION = 0.33f +private const val GROUP_NEST_HIGH_FRACTION = 0.66f + +/** + * The band a drop resolves to, or null when the pairing is illegal - one level of groups only. Parameters + * never nest, so a slider / pad target only takes Before / After. A group header takes Into (a parameter + * nesting inside it) plus Before / After (a root sibling), but only for a dragged parameter run - a + * dragged group never nests, so against a group header it takes only Before / After. A dragged group may + * reorder only among root nodes, so a non-root target refuses it. Used by both the indicator and the + * dispatch, so the line the user sees matches the move that happens. + * + * @param ParameterMoveSubject dragged The subject being dragged. + * @param ParameterRow targetRow The row under the pointer. + * @param Boolean targetAtRoot Whether the target sits at the tree root (depth 0). + * @param Float fraction The pointer's 0..1 position down the target row. + * @return RowDropBand? The resolved band, or null when the drop is illegal. + */ +internal fun parameterDropBandFor( + dragged: ParameterMoveSubject, + targetRow: ParameterRow, + targetAtRoot: Boolean, + fraction: Float, +): RowDropBand? { + val draggingGroup = dragged is ParameterMoveSubject.Group + return when (targetRow) { + is ParameterRow.GroupHeader -> { + if (draggingGroup) { + beforeOrAfter(fraction) + } else { + when { + fraction < GROUP_NEST_LOW_FRACTION -> RowDropBand.Before + fraction > GROUP_NEST_HIGH_FRACTION -> RowDropBand.After + else -> RowDropBand.Into + } + } + } + is ParameterRow.Single, is ParameterRow.Pair2D -> { + // A dragged group can only live at the root, so a target inside a group refuses it. + if (draggingGroup && !targetAtRoot) { + null + } else { + beforeOrAfter(fraction) + } + } + } +} + +/** Before above the row's midline, After below it. */ +private fun beforeOrAfter(fraction: Float): RowDropBand = + if (fraction >= 0.5f) { + RowDropBand.After + } else { + RowDropBand.Before + } + +/** + * The subject a drag of [row] relocates: a slider is one leaf, a linked pad is its two leaves in order + * (kept contiguous for combined-export adjacency), a group header is the whole group. + * + * @param ParameterRow row The row being dragged. + * @return ParameterMoveSubject What the drag moves. + */ +internal fun parameterMoveSubjectOf(row: ParameterRow): ParameterMoveSubject = + when (row) { + is ParameterRow.Single -> ParameterMoveSubject.Leaves(listOf(row.parameter.id)) + is ParameterRow.Pair2D -> ParameterMoveSubject.Leaves(listOf(row.horizontal.id, row.vertical.id)) + is ParameterRow.GroupHeader -> ParameterMoveSubject.Group(row.groupId) + } + +/** + * The destination parent group and the insert-before anchor for dropping onto [targetRow] with [band], + * resolved against the model's tree (a group-less model is treated as a flat root of leaves). Into + * appends inside the group; Before anchors on the target's leading node; After anchors on the node past + * the target's span (a pad spans its two leaves), or null (append) when the target is last in its + * siblings. + * + * @param PuppetModel puppet The model whose tree is walked. + * @param ParameterRow targetRow The row under the pointer. + * @param RowDropBand band The resolved band. + * @return Pair The destination parent (null = root) and the anchor. + */ +internal fun parameterDropAnchor( + puppet: PuppetModel, + targetRow: ParameterRow, + band: RowDropBand, +): Pair { + if (band == RowDropBand.Into && targetRow is ParameterRow.GroupHeader) { + return targetRow.groupId to null + } + val tree = puppet.parameterTree.ifEmpty { puppet.parameters.map { parameter -> ParameterNode.Param(parameter.id) } } + val primaryRef = primaryRefOf(targetRow) + val location = locate(tree, primaryRef) ?: return null to null + val (parentGroupId, siblings, index) = location + return when (band) { + RowDropBand.Before -> parentGroupId to primaryRef + RowDropBand.After -> { + val span = if (targetRow is ParameterRow.Pair2D) 2 else 1 + val afterIndex = index + span + val anchor = siblings.getOrNull(afterIndex)?.let { node -> refOf(node) } + parentGroupId to anchor + } + RowDropBand.Into -> parentGroupId to primaryRef // a non-group Into never reaches here. + } +} + +/** The node ref that anchors [targetRow]: a group by its id, a slider / pad by its leading leaf. */ +private fun primaryRefOf(targetRow: ParameterRow): ParameterNodeRef = + when (targetRow) { + is ParameterRow.GroupHeader -> ParameterNodeRef.Group(targetRow.groupId) + is ParameterRow.Single -> ParameterNodeRef.Leaf(targetRow.parameter.id) + is ParameterRow.Pair2D -> ParameterNodeRef.Leaf(targetRow.horizontal.id) + } + +/** The ref naming a tree node. */ +private fun refOf(node: ParameterNode): ParameterNodeRef = + when (node) { + is ParameterNode.Param -> ParameterNodeRef.Leaf(node.id) + is ParameterNode.Group -> ParameterNodeRef.Group(node.id) + } + +/** True when [node] is the one [ref] names. */ +private fun ParameterNode.matches(ref: ParameterNodeRef): Boolean = + when { + this is ParameterNode.Param && ref is ParameterNodeRef.Leaf -> id == ref.id + this is ParameterNode.Group && ref is ParameterNodeRef.Group -> id == ref.id + else -> false + } + +/** The sibling list and index of the node [ref] names, with its parent group id (null at root). */ +private fun locate(tree: List, ref: ParameterNodeRef): Triple, Int>? { + val rootIndex = tree.indexOfFirst { node -> node.matches(ref) } + if (rootIndex >= 0) { + return Triple(null, tree, rootIndex) + } + for (node in tree) { + if (node is ParameterNode.Group) { + val childIndex = node.children.indexOfFirst { child -> child.matches(ref) } + if (childIndex >= 0) { + return Triple(node.id, node.children, childIndex) + } + } + } + return null +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersHeaderControls.kt new file mode 100644 index 0000000..5aaa8cc --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersHeaderControls.kt @@ -0,0 +1,206 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import kotlinx.coroutines.flow.MutableStateFlow +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.createParameter +import org.umamo.edit.createParameterGroup +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.FilterPopupChip +import org.umamo.ui.kit.FilterSectionLabel +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.kit.SEARCH_FIELD_MIN_WIDTH +import org.umamo.ui.kit.SearchField +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalLiveParams +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.workspace.AreaScope + +/** + * The parameters panel's area-header controls (mounted via SpaceDescriptor.headerContent): the leading + * Add Parameter dropdown and New Group button, the name / id search field centered in the flexible + * middle, then Reset All and the filter chip at the header's end - so the panel body keeps its full + * height for the parameter list. Renders nothing without an open document, matching the other header + * controls. + * + * These stay inline handlers rather than registry commands on purpose - adding a parameter, creating a + * group, and resetting the pose are direct manipulation like the sliders themselves; a command becomes + * warranted only when a shortcut or menu needs to reach it. Creating either opens it for inline rename + * immediately, so the new id is parked on the shared [scope] view state (the header and body are + * sibling subtrees). + * + * @param AreaScope scope The hosting area's scope carrying the panel's view state. + */ +internal fun OverflowRowScope.parametersHeaderControls(scope: AreaScope) { + val viewState = scope.spaceState(PARAMETERS_VIEW_STATE_KEY) { ParametersViewState() } + // Add Parameter and New Group ride one item: both create, they were always 4.dp apart rather than the + // strip's 8.dp, and splitting a create pair across the strip and the overflow panel would read as noise. + // I know this looks like duplicate `LocalPuppet.current != null`, but it is not. They are still added, but only show if a document is open. + item("add") { + if (LocalPuppet.current != null) { + AddParameterChip(viewState) + } + } + item("new") { + if (LocalPuppet.current != null) { + NewParameterGroupButton(viewState) + } + } + flexibleSpace() + item("search", minWidth = SEARCH_FIELD_MIN_WIDTH) { + if (LocalPuppet.current != null) { + SearchField(value = viewState.query, onValueChange = { newQuery -> viewState.query = newQuery }) + } + } + flexibleSpace() + item("resetAll") { + if (LocalPuppet.current != null) { + ResetAllParametersButton() + } + } + item("filter") { + if (LocalPuppet.current != null) { + ParametersFilterChip(viewState) + } + } +} + +/** + * The Add Parameter dropdown: the rigger picks the kind up front - a key-form (circle) or a blend-shape + * (square) parameter. Either creates a document edit and opens the new row for inline rename. The full + * add-ticks / keyform-capture workflow is not built yet. + * + * @param ParametersViewState viewState The panel's shared view state, which parks the id to rename. + */ +@Composable +private fun AddParameterChip(viewState: ParametersViewState) { + val puppet = LocalPuppet.current ?: return + val session = LocalEditorSession.current + val defaultParameterName = stringResource(Res.string.parameter_default_name) + var addMenuExpanded by remember { mutableStateOf(false) } + val addKeyFormLabel = stringResource(Res.string.parameter_menu_add_keyform) + val addBlendShapeLabel = stringResource(Res.string.parameter_menu_add_blendshape) + DropdownChip( + expanded = addMenuExpanded, + onExpandRequest = { addMenuExpanded = true }, + contentDescription = stringResource(Res.string.parameter_menu_add), + icon = LocalUmamoIcons.parameterAdd, + enabled = session != null, + ) { + Menu( + items = + listOfNotNull( + MenuItem.Action( + label = addKeyFormLabel, + onSelect = { + session?.let { + viewState.renamingParameterId = it.createParameter(defaultParameterName, ParameterKind.NORMAL) + } + }, + enabled = session != null, + ), + // Blend-shape parameters are a 4.2 feature; under an older runtime target the creation + // entry disappears (existing blend-shape parameters keep working and rendering). + if (!puppet.runtimeTarget.supports(RuntimeFeature.BlendShapeParameters)) { + null + } else { + MenuItem.Action( + label = addBlendShapeLabel, + onSelect = { + session?.let { + viewState.renamingParameterId = it.createParameter(defaultParameterName, ParameterKind.BLEND_SHAPE) + } + }, + enabled = session != null, + ) + }, + ), + onDismissRequest = { addMenuExpanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} + +/** + * The New Group button: creates an empty parameter group and opens it for inline rename. + * + * @param ParametersViewState viewState The panel's shared view state, which parks the id to rename. + */ +@Composable +private fun NewParameterGroupButton(viewState: ParametersViewState) { + val session = LocalEditorSession.current + val defaultGroupName = stringResource(Res.string.parameter_group_default_name) + IconButton( + icon = LocalUmamoIcons.groupAdd, + onClick = { session?.let { viewState.renamingGroupId = it.createParameterGroup(defaultGroupName) } }, + contentDescription = stringResource(Res.string.parameter_new_group), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) +} + +/** + * Reset All: returns every parameter to its default in one undo step. + * + * The panel body gates every pose write on Edit mode (Edit mode is pinned to the neutral pose), and this + * must replicate that lock or a locked panel becomes writable from the header. Group create / delete / + * rename are document edits rather than pose writes, so they are NOT gated. + */ +@Composable +private fun ResetAllParametersButton() { + val puppet = LocalPuppet.current ?: return + val liveParams = LocalLiveParams.current + val session = LocalEditorSession.current + val editorMode by remember(session) { session?.mode ?: MutableStateFlow(EditorMode.Object) }.collectAsState() + IconButton( + icon = LocalUmamoIcons.resetAll, + onClick = { + if (editorMode != EditorMode.Edit) { + // The same two-phase shape as the panel's sliders: preview every default, then one + // commit so the whole reset is a single undo step. + puppet.parameters.forEach { parameter -> liveParams?.preview(parameter.id, parameter.default) } + liveParams?.commit(puppet.parameters.map { it.id }.toSet()) + } + }, + contentDescription = stringResource(Res.string.parameter_reset_all), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) +} + +/** + * The panel's view filters. The same stay-open filter panel the outliner uses, rather than a bare toggle + * button: this panel grows more view toggles as the keyform tracks land, and a shared chip keeps the two + * headers from drifting apart. The funnel glyph still reports the filtered / unfiltered state at a glance. + * + * @param ParametersViewState viewState The panel's shared view state. + */ +@Composable +private fun ParametersFilterChip(viewState: ParametersViewState) { + FilterPopupChip( + contentDescription = stringResource(Res.string.common_filters), + icon = if (viewState.showOnlySelected) LocalUmamoIcons.filterFiltered else LocalUmamoIcons.filterUnfiltered, + ) { + FilterSectionLabel(stringResource(Res.string.common_filters)) + Checkbox( + checked = viewState.showOnlySelected, + onCheckedChange = { checked -> viewState.showOnlySelected = checked }, + label = stringResource(Res.string.parameter_filter_selected), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersSpace.kt new file mode 100644 index 0000000..9370bd1 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersSpace.kt @@ -0,0 +1,1548 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.input.pointer.pointerHoverIcon +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalViewConfiguration +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.ParameterMoveSubject +import org.umamo.edit.ParameterSelection +import org.umamo.edit.RowDropBand +import org.umamo.edit.Selection +import org.umamo.edit.createParameter +import org.umamo.edit.createParameterGroup +import org.umamo.edit.deleteParameterGroup +import org.umamo.edit.moveParameterRow +import org.umamo.edit.renameParameter +import org.umamo.edit.renameParameterGroup +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterKind +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeFeature +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.DisclosureChevron +import org.umamo.ui.kit.FieldStack +import org.umamo.ui.kit.InlineRenameField +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.Pad2D +import org.umamo.ui.kit.Slider +import org.umamo.ui.kit.SliderKeyMark +import org.umamo.ui.kit.SliderKeyShape +import org.umamo.ui.kit.StackPosition +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.kit.singleOrDoubleClick +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalLiveParams +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.drawIcon +import org.umamo.ui.workspace.AreaScope +import org.umamo.ui.workspace.rowdrag.RowCoordinatesHolder +import org.umamo.ui.workspace.rowdrag.RowDragController +import org.umamo.ui.workspace.rowdrag.RowDragLabel +import org.umamo.ui.workspace.rowdrag.parkCancelOnSeam +import org.umamo.ui.workspace.rowdrag.rowDropHighlight +import kotlin.math.abs + +/** A value within this of a parameter's default counts as "at default" - no reset glyph, no drift. */ +private const val RESET_EPSILON = 1e-4f + +/** Indentation applied per group nesting level, matching the outliner's indent idiom. */ +private val INDENT_PER_DEPTH = 12.dp + +/** + * A generous clamp for the range-editor numeric fields. The three fields (min / default / max) are + * interdependent, so each is clamped only to this wide sanity bound and the session normalizes the + * triple (min <= max, default within range); a tight per-field clamp would block typing a default beyond + * the not-yet-committed max. + */ +private val RANGE_FIELD_LIMIT = -1_000_000f..1_000_000f + +/** + * The parameter cockpit: one control per animatable parameter, organised into the model's collapsible + * groups (Cubism's CParameterGroup tree). A LINKED ("combined") pair renders as one 2D pad; every other + * animatable parameter is a slider. Each parameter sits in its own rounded island (the visual + * separation); group headers render as recessed rounded rails between them. Each row carries a numeric + * entry field and, when its value is off its default, a reset glyph; a "Reset All" button returns the + * whole rig to its neutral pose. + * + * Scrubbing is undoable: a slider / pad drag streams transient preview frames straight to the renderer + * (via [LocalLiveParams]) and commits one undo step on release, so a whole gesture is a single Ctrl+Z and + * an undo re-poses the viewport (the session's pose drives both the renderer and these sliders). Clicking + * a parameter's name (or its leading chevron) opens the range editor inside that island - minimum / + * default / maximum, the document-level edit, distinct from scrubbing the live value - and any number of + * islands can be open at once. The open set lives on the hosting [AreaScope], so it survives switching + * the space away and back. Models without groups fall back to a flat list. The header's search field + * filters the list by parameter name or id, opening every group for as long as it has text in it. + * + * @param AreaScope scope The hosting area's scope carrying the panel's view state. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun ParametersSpace(scope: AreaScope, modifier: Modifier = Modifier) { + val puppet = LocalPuppet.current + val liveParams = LocalLiveParams.current + val session = LocalEditorSession.current + if (puppet == null) { + // No document: the bare panel fill is the empty state (no load hint). + return + } + val viewState = scope.spaceState(PARAMETERS_VIEW_STATE_KEY) { ParametersViewState() } + // Local control state seeded from the live values (or defaults); writes publish to the renderer. + // + // Keyed on WHICH parameters exist, not on the model instance. Every document edit publishes a new + // PuppetModel - moving a keyform key, recolouring a drawable - and keying this map to that threw it + // away and rebuilt it on each one. That is churn by itself, and worse: the effects below capture the + // map, so a replacement silently orphaned their writes and the sliders stopped following a live scrub + // until something else forced them to re-run. The set of parameters is what this map is actually + // about, and it survives an ordinary edit. + val parameterIds = remember(puppet) { puppet.parameters.map { parameter -> parameter.id } } + val values = + remember(parameterIds) { + mutableStateMapOf().apply { + puppet.parameters.forEach { parameter -> + put(parameter.id, liveParams?.values?.get(parameter.id) ?: parameter.default) + } + } + } + // Reseed the sliders from the session pose when it changes out from under us - an undo / redo restores + // a prior pose, and these controls must follow it. Mid-drag previews update [values] directly (the + // session pose does not move until commit), so this never fights a live scrub; the guard skips + // unchanged entries so a commit (pose == values already) triggers no writes. An empty fallback flow + // keeps the collect unconditional when no session is present. + val pose by remember(session) { session?.pose ?: MutableStateFlow(emptyMap()) }.collectAsState() + LaunchedEffect(pose, values) { + pose.forEach { (id, value) -> + if (values[id] != value) { + values[id] = value + } + } + } + // And follow PREVIEWS made from elsewhere - the keyform sheet scrubs the same pose by dragging its + // track region. A preview deliberately never touches session.pose (that is what keeps a whole drag to + // one undo step), so the effect above only caught up on release and the sliders sat still meanwhile. + // + // Through snapshotFlow rather than a composition read: the scrub path writes on every pointer move, and + // reading it in composition would recompose this whole panel per frame instead of only the sliders + // whose value actually moved. Edit mode publishes an EMPTY pose, which writes nothing and so cannot + // disturb the locked panel's displayed values. + LaunchedEffect(liveParams, values) { + snapshotFlow { liveParams?.observedValues.orEmpty() }.collect { livePose -> + livePose.forEach { (id, value) -> + if (values[id] != value) { + values[id] = value + } + } + } + } + + // Group expand/collapse state, keyed by group id; absent entries fall back to the group's saved + // initiallyOpen. Parked on [viewState] rather than remember(puppet) so it survives every model edit - + // keying it to the puppet would reset the map, and so collapse every group, on any edit at all, + // including a link write inside the group itself. + val expandedGroups = viewState.expandedGroups + + // Puppet-derived facts reused every rebuild: which parameters are animatable, and the link pairing. + val linkInfo = remember(puppet) { buildLinkInfo(puppet) } + val parameterById = remember(puppet) { puppet.parameters.associateBy { it.id } } + // Per-parameter key marks (circle grid keys / square blend keys) for the sliders; one graph pass, + // recomputed only when the model changes. + val keyMarksByParameter = remember(puppet) { puppet.parameterKeyMarks() } + + // Parameters are LOCKED while in Edit mode: Edit mode edits the neutral state of the base mesh and is + // pinned to the neutral pose (the viewport shows rest via a display-only override), so no scrub may + // move the session pose out from under it. The lock gates every write path below; the sliders keep + // displaying the untouched Object-mode pose, which returns to the viewport on exit. + val editorMode by remember(session) { session?.mode ?: MutableStateFlow(EditorMode.Object) }.collectAsState() + val parametersLocked = editorMode == EditorMode.Edit + + /** Previews a value: updates local state and streams it to the renderer, recording no undo step. */ + fun previewValue(id: ParameterId, newValue: Float) { + if (parametersLocked) { + return + } + values[id] = newValue + liveParams?.preview(id, newValue) + } + + /** Commits the current pose as one undo step, ending a scrub gesture over [ids]. */ + fun commitGesture(ids: Set) { + if (parametersLocked) { + return + } + liveParams?.commit(ids) + } + + /** A discrete value edit (a typed field, a reset): preview then commit it as one step. */ + fun commitValue(id: ParameterId, newValue: Float) { + previewValue(id, newValue) + commitGesture(setOf(id)) + } + + // The "affects the selected object" filter: when it is on and something is selected, restrict the panel + // to the parameters that drive the selection (effective, through the deformer chain). Inert with no + // selection, so the panel is never mysteriously blank. Recomputed only on a puppet / selection / flag / + // query change. + val selection = LocalSelection.current?.selection ?: Selection() + // The keyform-authoring target, shared across areas via the session - a keyform sheet in another area + // follows whatever is picked here. + val parameterSelection by remember(session) { session?.parameterSelection ?: MutableStateFlow(ParameterSelection()) }.collectAsState() + // The header search's text, applied as a second filter over the same set. Trimmed once here so the + // memo key and the match both read the same string. + val searchQuery = viewState.query.trim() + val visibleParamIds = + remember(puppet, selection, viewState.showOnlySelected, searchQuery) { + val selectedFilter = + if (viewState.showOnlySelected && !selection.isEmpty) { + effectiveParameterIds(puppet, selection) + } else { + null + } + val queryFilter = if (searchQuery.isEmpty()) null else parameterIdsMatching(puppet, searchQuery) + // Both filters restrict, so with both on a parameter must satisfy each of them. + when { + selectedFilter == null -> queryFilter + queryFilter == null -> selectedFilter + else -> selectedFilter intersect queryFilter + } + } + + // Built each recomposition so a group toggle (or a value change) reflects immediately; reading + // [expandedGroups] / [values] here registers the snapshot reads that drive the rebuild. While a + // search is running every group renders open, so a match inside a collapsed one is still reachable. + val rows = buildParameterRows(puppet, linkInfo, parameterById, expandedGroups, visibleParamIds, forceExpanded = searchQuery.isNotEmpty()) + val resetLabel = stringResource(Res.string.parameter_reset) + val rangeToggleLabel = stringResource(Res.string.parameter_range_section) + val linkLabel = stringResource(Res.string.parameter_link) + val unlinkLabel = stringResource(Res.string.parameter_unlink) + val newGroupLabel = stringResource(Res.string.parameter_new_group) + val renameLabel = stringResource(Res.string.parameter_menu_rename) + val deleteGroupLabel = stringResource(Res.string.parameter_menu_delete_group) + val addKeyFormParamLabel = stringResource(Res.string.parameter_menu_add_keyform) + val addBlendShapeParamLabel = stringResource(Res.string.parameter_menu_add_blendshape) + val deleteParamLabel = stringResource(Res.string.parameter_menu_delete) + val deleteDiscardLabel = stringResource(Res.string.parameter_menu_delete_discard) + val deleteMoveKeysLabel = stringResource(Res.string.parameter_menu_delete_move_keys) + val defaultGroupName = stringResource(Res.string.parameter_group_default_name) + val defaultParameterName = stringResource(Res.string.parameter_default_name) + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val listState = rememberLazyListState() + val reorderLabel = stringResource(Res.string.parameter_reorder_handle) + + // A newly created group or parameter is prepended at the top and immediately opened for inline rename; + // scroll its row into view when it is not already visible (the created item can otherwise land just + // above the viewport when the list was scrolled down). Mirrors the reveal-on-select effect in the + // outliner / history spaces; the visibility guard keeps renaming an already-visible item from jumping. + // The row is AWAITED through snapshotFlow rather than looked up once: a created parameter reaches this + // composition through the model StateFlow's collector, which can land a recomposition after the + // renaming id was set - a one-shot look at the captured rows missed it and, with the effect's keys + // unchanged, never ran again. The prepended row also sits above a scrolled-down viewport, where its + // lazy item cannot even open the rename field until this scroll composes it. + val currentRows = rememberUpdatedState(rows) + LaunchedEffect(viewState.renamingGroupId, viewState.renamingParameterId) { + val renamingGroupId = viewState.renamingGroupId + val renamingParameterId = viewState.renamingParameterId + if (renamingGroupId == null && renamingParameterId == null) { + return@LaunchedEffect + } + val index = + snapshotFlow { + currentRows.value.indexOfFirst { row -> + when (row) { + is ParameterRow.GroupHeader -> row.groupId == renamingGroupId + is ParameterRow.Single -> row.parameter.id == renamingParameterId + is ParameterRow.Pair2D -> row.horizontal.id == renamingParameterId || row.vertical.id == renamingParameterId + } + } + }.first { candidate -> candidate >= 0 } + if (listState.layoutInfo.visibleItemsInfo.none { visible -> visible.index == index }) { + listState.animateScrollToItem(index) + } + } + + // Transient drag-and-drop state, per panel instance. While a drag is in flight the panel parks its + // cancel on the shell's seam so Escape aborts the drag (the grip is pointerInput, never focusable, + // so it does not reintroduce the link-icon focus bug). + val dragController = remember { RowDragController() } + dragController.parkCancelOnSeam() + + // The "add" items every parameter menu ends with: Add Key Form / Add Blend Shape parameter, and New + // Group. Each creates a document edit and opens the created item for inline rename. Shared by the + // panel-background menu (so the first parameter / group can be made with no row to right-click) and + // each row's context menu. The two parameter kinds mirror the header's Add Parameter dropdown, + // including its runtime-target gate - a second creation path must not bypass what the header hides. + val createMenuItems = + listOfNotNull( + MenuItem.Action( + label = addKeyFormParamLabel, + onSelect = { + session?.let { + viewState.renamingParameterId = it.createParameter(defaultParameterName, ParameterKind.NORMAL) + } + }, + enabled = session != null, + ), + if (!puppet.runtimeTarget.supports(RuntimeFeature.BlendShapeParameters)) { + null + } else { + MenuItem.Action( + label = addBlendShapeParamLabel, + onSelect = { + session?.let { + viewState.renamingParameterId = it.createParameter(defaultParameterName, ParameterKind.BLEND_SHAPE) + } + }, + enabled = session != null, + ) + }, + MenuItem.Action( + label = newGroupLabel, + onSelect = { session?.let { viewState.renamingGroupId = it.createParameterGroup(defaultGroupName) } }, + enabled = session != null, + ), + ) + + // A right-click anywhere on the panel body (empty space or a row) offers Add Parameter / New Group, so + // the first parameter or group can be made without a row to right-click; ContextMenuArea supplies the + // body Box. + ContextMenuArea( + items = createMenuItems, + modifier = modifier.fillMaxSize(), + ) { + Column(modifier = Modifier.fillMaxSize()) { + // The list scrolls under an overlay scrollbar; the Box carries the column weight so the bar + // spans the scrolling region. Reset All lives in the area header (parametersHeaderControls). + Box(modifier = Modifier.fillMaxWidth().weight(1f)) { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize().padding(start = 8.dp, end = 8.dp, top = 8.dp, bottom = 8.dp), + // The gap between islands is the row separation (no dividers). + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + // Stable per-row keys: expanding/collapsing a group mutates the row list, so without keys + // Compose would reuse slots by position and a row's remembered state (a slider's gesture + // detector, a field's text/focus) would bind to the wrong parameter. + items(rows, key = { row -> rowKey(row) }, contentType = { row -> row::class }) { row -> + val key = rowKey(row) + // Drop this row's window bounds when it scrolls off, so the drop hit-test never + // targets an invisible row. + DisposableEffect(key) { + onDispose { dragController.clearBounds(key) } + } + // The band this row would receive if a drop landed now (null unless it is the drag + // target), read from snapshot state so the indicator tracks the moving pointer. + val dropBand: RowDropBand? = + if (dragController.isDragging && dragController.dropTargetKey == key) { + dragController.draggedPayload?.let { subject -> + parameterDropBandFor( + subject, + row, + row.depth == 0, + dragController.dropTargetFraction ?: 0.5f, + ) + } + } else { + null + } + val isDragged = dragController.draggingKey == key + Row( + // Report the OUTER row's bounds (not the inner island's) so the drop band math + // measures the whole row. The group-depth indent sits here, beside the grip. + modifier = + Modifier + .fillMaxWidth() + .onGloballyPositioned { coordinates -> + dragController.reportBounds( + key, + coordinates.boundsInWindow(), + ) + } + .parameterDropLine(dropBand, colors.accent) + .alpha(if (isDragged) 0.4f else 1f) + .padding(start = INDENT_PER_DEPTH * row.depth), + verticalAlignment = Alignment.CenterVertically, + ) { + ParameterGripHandle( + gripLabel = reorderLabel, + subject = parameterMoveSubjectOf(row), + rowKey = key, + dragController = dragController, + onDrop = { + performParameterDrop(dragController, rows, puppet, session) { groupId -> + expandedGroups[groupId] = true + } + }, + // Clicking the handle targets the row's parameters. The island itself is + // crowded - slider, pad, name, numeric field, reset glyph all consume their + // own pointer input - so the handle is the one reliably empty place to click, + // and it already means "this row" for the drag. A group header selects + // nothing: it owns no parameter to key on. + onSelect = { + parameterSelectionOf(row)?.let { selection -> + session?.setParameterSelection(selection) + } + }, + ) + when (row) { + is ParameterRow.GroupHeader -> { + val nesting = dropBand == RowDropBand.Into + val renaming = viewState.renamingGroupId == row.groupId + ContextMenuArea( + items = + listOf( + MenuItem.Action( + label = newGroupLabel, + onSelect = { + session?.let { + viewState.renamingGroupId = + it.createParameterGroup(defaultGroupName) + } + }, + enabled = session != null, + ), + MenuItem.Action( + label = renameLabel, + onSelect = { viewState.renamingGroupId = row.groupId }, + enabled = session != null, + ), + MenuItem.Separator, + MenuItem.Action( + label = deleteGroupLabel, + onSelect = { session?.deleteParameterGroup(row.groupId) }, + enabled = session != null, + ), + ), + modifier = Modifier.weight(1f), + ) { + if (renaming) { + ParameterGroupRenameField( + initialName = row.name, + onCommit = { newName -> + session?.renameParameterGroup(row.groupId, newName) + viewState.renamingGroupId = null + }, + onCancel = { viewState.renamingGroupId = null }, + ) + } else { + // A recessed rounded rail (tabBackground) so groups read as chrome under the + // raised islands; a nest-into drop tints and outlines it. Double-click the + // header to rename it (pointerInput, so it stays keyboard-focus-safe). + ParameterGroupHeaderBody( + name = row.name, + expanded = row.expanded, + nesting = nesting, + onToggle = { expandedGroups[row.groupId] = !(expandedGroups[row.groupId] ?: row.expanded) }, + onStartRename = { + // The double-click's first press already fired the immediate single-click + // toggle; flip the group back so renaming does not also open / close it. + // Flip the LIVE map value, not the captured row's - the capture can be a + // recomposition stale under a fast double click, and flipping a stale + // value re-applies the first toggle instead of undoing it. + expandedGroups[row.groupId] = !(expandedGroups[row.groupId] ?: row.expanded) + viewState.renamingGroupId = row.groupId + }, + ) + } + } + } + + is ParameterRow.Single -> { + val parameter = row.parameter + val linkCandidateId = row.linkCandidateId + val rangeOpen = viewState.openRangeEditors[parameter.id] == true + ContextMenuArea( + items = + listOf( + MenuItem.Action( + label = renameLabel, + onSelect = { viewState.renamingParameterId = parameter.id }, + enabled = session != null, + ), + MenuItem.Submenu( + label = deleteParamLabel, + items = + deleteParameterMenuItems( + session = session, + parameterId = parameter.id, + destinations = puppet.parameters, + discardLabel = deleteDiscardLabel, + moveKeysLabel = deleteMoveKeysLabel, + ), + enabled = session != null, + ), + MenuItem.Separator, + ) + createMenuItems, + modifier = Modifier.weight(1f), + ) { + ParameterIsland( + modifier = Modifier.fillMaxWidth(), + selected = parameter.id in parameterSelection, + // Through parameterSelectionOf, the ONE place the targeting policy lives - + // the grip handle uses the same function, so click and grab cannot drift. + onSelect = { parameterSelectionOf(row)?.let { target -> session?.setParameterSelection(target) } }, + ) { + ParameterSlider( + parameter = parameter, + keyMarks = keyMarksByParameter[parameter.id], + value = values[parameter.id] ?: parameter.default, + resetLabel = resetLabel, + rangeToggleLabel = rangeToggleLabel, + rangeOpen = rangeOpen, + onToggleRange = { + viewState.openRangeEditors[parameter.id] = !rangeOpen + }, + renaming = viewState.renamingParameterId == parameter.id, + onStartRename = { viewState.renamingParameterId = parameter.id }, + onCommitRename = { newName -> + session?.renameParameter(parameter.id, newName) + viewState.renamingParameterId = null + }, + onCancelRename = { viewState.renamingParameterId = null }, + onPreview = { newValue -> previewValue(parameter.id, newValue) }, + onCommitGesture = { commitGesture(setOf(parameter.id)) }, + onCommitValue = { newValue -> commitValue(parameter.id, newValue) }, + // Link editing is a document edit, not a pose write, so it deliberately + // bypasses the Edit-mode parameter lock (the same policy as range edits). + linkIcon = if (linkCandidateId != null && session != null) LocalUmamoIcons.unlinked else null, + linkContentDescription = linkLabel, + onLinkClick = + if (linkCandidateId != null && session != null) { + { + session.setParameterLink( + parameter.id, + linkCandidateId, + linked = true, + ) + } + } else { + null + }, + ) + if (rangeOpen) { + RangeFieldsRow( + parameter = parameter, + onSetRange = { min, default, max -> + session?.setParameterRange( + parameter.id, + min, + default, + max, + ) + }, + ) + } + } + } + } + + is ParameterRow.Pair2D -> { + // The pad island keys its open state on the horizontal (upper) member. + val rangeOpen = viewState.openRangeEditors[row.horizontal.id] == true + ContextMenuArea( + items = + listOf( + // A pad holds two axes, so rename / delete open per-axis submenus + // (the axis names are user data); double-clicking a name renames it too. + MenuItem.Submenu( + label = renameLabel, + items = + listOf( + MenuItem.Action( + row.horizontal.name, + onSelect = { + viewState.renamingParameterId = row.horizontal.id + }, + enabled = session != null, + ), + MenuItem.Action( + row.vertical.name, + onSelect = { + viewState.renamingParameterId = row.vertical.id + }, + enabled = session != null, + ), + ), + enabled = session != null, + ), + MenuItem.Submenu( + label = deleteParamLabel, + items = + listOf( + MenuItem.Submenu( + label = row.horizontal.name, + items = + deleteParameterMenuItems( + session = session, + parameterId = row.horizontal.id, + destinations = puppet.parameters, + discardLabel = deleteDiscardLabel, + moveKeysLabel = deleteMoveKeysLabel, + ), + enabled = session != null, + ), + MenuItem.Submenu( + label = row.vertical.name, + items = + deleteParameterMenuItems( + session = session, + parameterId = row.vertical.id, + destinations = puppet.parameters, + discardLabel = deleteDiscardLabel, + moveKeysLabel = deleteMoveKeysLabel, + ), + enabled = session != null, + ), + ), + enabled = session != null, + ), + MenuItem.Separator, + ) + createMenuItems, + modifier = Modifier.weight(1f), + ) { + ParameterIsland( + modifier = Modifier.fillMaxWidth(), + selected = row.horizontal.id in parameterSelection || row.vertical.id in parameterSelection, + // A pad targets BOTH its axes - through parameterSelectionOf, the ONE place + // the policy lives, shared with the grip handle and the single island. + onSelect = { parameterSelectionOf(row)?.let { target -> session?.setParameterSelection(target) } }, + ) { + ParameterPad2D( + horizontal = row.horizontal, + vertical = row.vertical, + xValue = values[row.horizontal.id] ?: row.horizontal.default, + yValue = values[row.vertical.id] ?: row.vertical.default, + resetLabel = resetLabel, + rangeToggleLabel = rangeToggleLabel, + rangeOpen = rangeOpen, + onToggleRange = { + viewState.openRangeEditors[row.horizontal.id] = !rangeOpen + }, + renamingParameterId = viewState.renamingParameterId, + onStartRename = { id -> viewState.renamingParameterId = id }, + onCommitRename = { id, newName -> + session?.renameParameter(id, newName) + viewState.renamingParameterId = null + }, + onCancelRename = { viewState.renamingParameterId = null }, + onPreview = { id, newValue -> previewValue(id, newValue) }, + onCommitGesture = { ids -> commitGesture(ids) }, + onCommitValue = { id, newValue -> commitValue(id, newValue) }, + // Unlink splits the pad back into two sliders; a document edit, allowed + // in Edit mode like range edits. + linkIcon = if (session != null) LocalUmamoIcons.linked else null, + linkContentDescription = unlinkLabel, + onLinkClick = + if (session != null) { + { + session.setParameterLink( + row.horizontal.id, + row.vertical.id, + linked = false, + ) + } + } else { + null + }, + ) + if (rangeOpen) { + // One range row per axis, each captioned with its axis name (user + // data, never localized). + RangeAxisLabel(row.horizontal.name) + RangeFieldsRow( + parameter = row.horizontal, + onSetRange = { min, default, max -> + session?.setParameterRange(row.horizontal.id, min, default, max) + }, + ) + RangeAxisLabel(row.vertical.name) + RangeFieldsRow( + parameter = row.vertical, + onSetRange = { min, default, max -> + session?.setParameterRange(row.vertical.id, min, default, max) + }, + ) + } + } + } + } + } + } + } + } + VerticalScrollbarOverlay(listState) + } + } + // The floating drag ghost follows the cursor over everything. + if (dragController.isDragging) { + RowDragLabel( + label = draggedRowLabel(rows, dragController.draggingKey), + cursorX = dragController.dragWindowX, + cursorY = dragController.dragWindowY, + ) + } + } +} + +/** + * The rounded elevation island wrapping one parameter (slider or pad) and, while open, its range + * editor. One visual step raised from the panel fill (headerBackground sits exactly one elevation + * step above panelBackground in both schemes), rounded with the kit's medium shape. The group-depth + * indent lives on the caller's row (beside the drag grip), so the island only carries [modifier]. + * + * @param Modifier modifier The layout modifier (the caller supplies the row weight). + * @param Boolean selected Whether this island's parameter(s) are the current keyform-authoring target. + * @param Function? onSelect Called when the island's own surface is clicked, or null to disable selection. + * @param Function content The island's rows. + */ +@Composable +private fun ParameterIsland( + modifier: Modifier = Modifier, + selected: Boolean = false, + onSelect: (() -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit, +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + Column( + modifier = + modifier + .clip(shapes.medium) + .let { base -> + // The slider, pad, and name each consume their own pointer input first, so this only fires on + // the island's own surface. Scrubbing therefore does NOT retarget: a scrub is a pose gesture, + // and making it push a selection undo step would bury the history under drag noise. + // + // NOT FOCUSABLE, and that is load-bearing: a clickable takes focus, and deleting the row that + // holds focus leaves Compose's focus null, which silently kills every keyboard shortcut until + // the next click. The range-editor chevron below guards itself the same way. + if (onSelect != null) { + base + .focusProperties { canFocus = false } + .clickable(indication = null, interactionSource = null, onClick = onSelect) + } else { + base + } + } + .background(colors.headerBackground, shape = shapes.medium) + .border( + width = if (selected) 2.dp else 1.dp, + color = if (selected) colors.accent else colors.panelBorder, + shape = shapes.medium, + ) + .padding(horizontal = 6.dp, vertical = 6.dp), + content = content, + ) +} + +/** + * One labelled slider for a parameter, clamped to its range, with a numeric entry field and (when the + * value is off its default) a reset glyph. The slider drag previews live and commits one step on release; + * the field / reset commit one step each. + * + * @param Parameter parameter The parameter to scrub. + * @param ParameterKeyMarks? keyMarks The parameter's grid / blend key marks to draw on the slider, or null. + * @param Float value The current value. + * @param String resetLabel The localized accessible label for the reset glyph. + * @param String rangeToggleLabel The localized accessible label for the range chevron. + * @param Boolean rangeOpen Whether this island's range editor is open (highlights the name). + * @param Function onToggleRange Called when the name / chevron is clicked (toggles the range editor). + * @param Boolean renaming Whether this parameter's name is being edited in place. + * @param Function onStartRename Called on a double-click of the name to begin inline rename. + * @param Function onCommitRename Called with the new name when the inline rename commits. + * @param Function onCancelRename Called when the inline rename is abandoned. + * @param Function onPreview Called per drag frame with the new value (transient, no undo step). + * @param Function onCommitGesture Called on slider release / tap to commit the gesture as one step. + * @param Function onCommitValue Called by the numeric field / reset with a discrete value to commit. + * @param UmamoIcon linkIcon The trailing link glyph, or null when the row offers no link edit. + * @param String linkContentDescription The localized accessible label for the link glyph, read only + * when [linkIcon] shows one. Non-null so the glyph can never appear unnamed and untooltipped. + * @param Function onLinkClick Called when the link glyph is clicked, or null when hidden. + */ +@Composable +private fun ParameterSlider( + parameter: Parameter, + keyMarks: ParameterKeyMarks?, + value: Float, + resetLabel: String, + rangeToggleLabel: String, + rangeOpen: Boolean, + onToggleRange: () -> Unit, + renaming: Boolean, + onStartRename: () -> Unit, + onCommitRename: (String) -> Unit, + onCancelRename: () -> Unit, + onPreview: (Float) -> Unit, + onCommitGesture: () -> Unit, + onCommitValue: (Float) -> Unit, + linkIcon: UmamoIcon?, + linkContentDescription: String, + onLinkClick: (() -> Unit)?, +) { + ParameterValueRow( + name = parameter.name, + value = value, + default = parameter.default, + range = parameter.min..parameter.max, + resetLabel = resetLabel, + rangeToggleLabel = rangeToggleLabel, + showRangeToggle = true, + showLeadingSlot = true, + rangeOpen = rangeOpen, + onToggleRange = onToggleRange, + renaming = renaming, + onStartRename = onStartRename, + onCommitRename = onCommitRename, + onCancelRename = onCancelRename, + onCommitValue = onCommitValue, + linkIcon = linkIcon, + linkContentDescription = linkContentDescription, + onLinkClick = onLinkClick, + ) + // Circle marks for grid keys, square marks for blend-shape keys; the thumb takes the parameter's own + // kind (a blend-shape parameter reads as a square knob even before it has any keys). + val sliderKeyMarks = + remember(keyMarks) { + buildList { + keyMarks?.gridKeys?.forEach { keyValue -> add(SliderKeyMark(keyValue, SliderKeyShape.Circle)) } + keyMarks?.blendKeys?.forEach { keyValue -> add(SliderKeyMark(keyValue, SliderKeyShape.Square)) } + } + } + Slider( + value = value, + onValueChange = onPreview, + onValueChangeFinished = onCommitGesture, + valueRange = parameter.min..parameter.max, + keyMarks = sliderKeyMarks, + thumbShape = if (parameter.kind == ParameterKind.BLEND_SHAPE) SliderKeyShape.Square else SliderKeyShape.Circle, + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), + ) +} + +/** + * One 2D pad for a LINKED parameter pair: a labelled numeric/reset row per axis above a [Pad2D] that + * scrubs both at once. [horizontal] is the X axis, [vertical] the Y axis. The pad drag previews both live + * and commits one step (covering both parameters) on release. The range chevron sits on the horizontal + * (upper) axis row; clicking either axis name toggles the island's shared range editor. + * + * @param Parameter horizontal The X-axis parameter. + * @param Parameter vertical The Y-axis parameter. + * @param Float xValue The current X value. + * @param Float yValue The current Y value. + * @param String resetLabel The localized accessible label for the reset glyphs. + * @param String rangeToggleLabel The localized accessible label for the range chevron. + * @param Boolean rangeOpen Whether this island's range editor is open. + * @param Function onToggleRange Called when an axis name / the chevron is clicked. + * @param ParameterId? renamingParameterId The axis id currently being renamed in place, or null. + * @param Function onStartRename Called with an axis id on a double-click of that axis name. + * @param Function onCommitRename Called with (axis id, new name) when an inline rename commits. + * @param Function onCancelRename Called when an inline rename is abandoned. + * @param Function onPreview Called per drag frame with (id, value) for each axis (transient). + * @param Function onCommitGesture Called on pad release to commit both axes as one step. + * @param Function onCommitValue Called by an axis field / reset with (id, value) to commit one step. + * @param UmamoIcon linkIcon The unlink glyph shown on the horizontal (upper) axis row - the + * link "points at the parameter below" so it sits on the upper member. + * @param String linkContentDescription The localized accessible label for the unlink glyph, read only + * on the horizontal row (the vertical one shows no glyph). + * @param Function onLinkClick Called when the unlink glyph is clicked, or null when hidden. + */ +@Composable +private fun ParameterPad2D( + horizontal: Parameter, + vertical: Parameter, + xValue: Float, + yValue: Float, + resetLabel: String, + rangeToggleLabel: String, + rangeOpen: Boolean, + onToggleRange: () -> Unit, + renamingParameterId: ParameterId?, + onStartRename: (ParameterId) -> Unit, + onCommitRename: (ParameterId, String) -> Unit, + onCancelRename: () -> Unit, + onPreview: (ParameterId, Float) -> Unit, + onCommitGesture: (Set) -> Unit, + onCommitValue: (ParameterId, Float) -> Unit, + linkIcon: UmamoIcon?, + linkContentDescription: String, + onLinkClick: (() -> Unit)?, +) { + val colors = LocalUmamoColors.current + // Both axis names toggle the SAME island range editor, so the disclosure chevron is shared and + // vertically centerd across the two axis rows rather than pinned to the first. It is pulled out of the + // per-row leading slot (both rows pass showLeadingSlot = false, supplying the indent from here) and + // kept keyboard-focus-safe like the slider's inline toggle. + // IntrinsicSize.Min gives the row the height of its tallest child (the two-axis Column), so the shared + // chevron can fillMaxHeight to span both names top-to-bottom - a tall, wide hit target rather than a + // 12.dp dot pinned to the first row. + Row(modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = + Modifier + .fillMaxHeight() + .width(24.dp) + .focusProperties { canFocus = false } + .clickable(onClick = onToggleRange), + contentAlignment = Alignment.Center, + ) { + // Named for what it discloses rather than the generic expand / collapse, and deliberately without a + // tooltip: the axis names it opens sit immediately to its right. + DisclosureChevron(expanded = rangeOpen, tint = colors.text, contentDescription = rangeToggleLabel) + } + // The two axis rows butt into one stacked field group (First / Last, hairline seam between) so a linked + // pair reads as a single joined control, matching the Canvas dimension stack. + FieldStack( + modifier = Modifier.weight(1f), + rows = + listOf( + { position -> + ParameterValueRow( + name = horizontal.name, + value = xValue, + default = horizontal.default, + range = horizontal.min..horizontal.max, + resetLabel = resetLabel, + rangeToggleLabel = rangeToggleLabel, + showRangeToggle = false, + showLeadingSlot = false, + rangeOpen = rangeOpen, + onToggleRange = onToggleRange, + renaming = renamingParameterId == horizontal.id, + onStartRename = { onStartRename(horizontal.id) }, + onCommitRename = { newName -> onCommitRename(horizontal.id, newName) }, + onCancelRename = onCancelRename, + onCommitValue = { newX -> onCommitValue(horizontal.id, newX) }, + linkIcon = linkIcon, + linkContentDescription = linkContentDescription, + onLinkClick = onLinkClick, + stackPosition = position, + ) + }, + { position -> + ParameterValueRow( + name = vertical.name, + value = yValue, + default = vertical.default, + range = vertical.min..vertical.max, + resetLabel = resetLabel, + rangeToggleLabel = rangeToggleLabel, + showRangeToggle = false, + showLeadingSlot = false, + rangeOpen = rangeOpen, + onToggleRange = onToggleRange, + renaming = renamingParameterId == vertical.id, + onStartRename = { onStartRename(vertical.id) }, + onCommitRename = { newName -> onCommitRename(vertical.id, newName) }, + onCancelRename = onCancelRename, + onCommitValue = { newY -> onCommitValue(vertical.id, newY) }, + linkIcon = null, + linkContentDescription = linkContentDescription, + onLinkClick = null, + stackPosition = position, + ) + }, + ), + ) + } + Pad2D( + xValue = xValue, + yValue = yValue, + onChange = { newX, newY -> + onPreview(horizontal.id, newX) + onPreview(vertical.id, newY) + }, + onChangeFinished = { onCommitGesture(setOf(horizontal.id, vertical.id)) }, + xRange = horizontal.min..horizontal.max, + yRange = vertical.min..vertical.max, + modifier = Modifier.padding(10.dp).fillMaxWidth(), + ) +} + +/** + * The shared label row above a slider or pad axis: a leading range chevron (on the island's toggle + * row), the clickable parameter name (name and chevron both toggle the island's range editor, the name + * highlighted while it is open), an optional reset glyph (shown only when [value] is off [default]), + * and a numeric entry field clamped to [range]. + * + * @param String name The parameter display name. + * @param Float value The current value. + * @param Float default The parameter's default (neutral) value. + * @param ClosedFloatingPointRange range The value range the numeric field clamps to. + * @param String resetLabel The localized accessible label for the reset glyph. + * @param String rangeToggleLabel The localized accessible label for the range chevron. + * @param Boolean showRangeToggle Whether this row's leading slot draws the island's chevron (versus a + * matching spacer); only consulted when [showLeadingSlot] is true. + * @param Boolean showLeadingSlot Whether this row renders its own leading chevron / spacer slot. A + * linked pad shares one external chevron centerd across both axis rows, + * so its rows pass false and let that chevron supply the indent. + * @param Boolean rangeOpen Whether the island's range editor is open. + * @param Function onToggleRange Called when the name / chevron is clicked. + * @param Boolean renaming Whether this parameter's name is being edited in place. + * @param Function onStartRename Called on a double-click of the name to begin inline rename. + * @param Function onCommitRename Called with the new name when the inline rename commits. + * @param Function onCancelRename Called when the inline rename is abandoned. + * @param Function onCommitValue Called with the new value (a discrete edit committed as one step). + * @param UmamoIcon linkIcon The trailing link / unlink glyph, or null for an empty slot. + * @param String linkContentDescription The localized accessible label for the link glyph, read only when + * [linkIcon] and [onLinkClick] are both present. + * @param Function onLinkClick Called when the link glyph is clicked, or null when hidden. + * @param StackPosition stackPosition This field's position in a vertical stack: a linked pair's two axis + * rows butt into one stacked group (First / Last), while a standalone + * slider row stays Single (a self-contained, fully-rounded field). + */ +@Composable +private fun ParameterValueRow( + name: String, + value: Float, + default: Float, + range: ClosedFloatingPointRange, + resetLabel: String, + rangeToggleLabel: String, + showRangeToggle: Boolean, + showLeadingSlot: Boolean, + rangeOpen: Boolean, + onToggleRange: () -> Unit, + renaming: Boolean, + onStartRename: () -> Unit, + onCommitRename: (String) -> Unit, + onCancelRename: () -> Unit, + onCommitValue: (Float) -> Unit, + linkIcon: UmamoIcon?, + linkContentDescription: String, + onLinkClick: (() -> Unit)?, + stackPosition: StackPosition = StackPosition.Single, +) { + val colors = LocalUmamoColors.current + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Row( + // A single click toggles the range editor; a double click begins inline rename. singleOrDoubleClick + // uses raw pointerInput (never requests focus, so keyboard dispatch stays on the shell root) and + // fires the single click immediately - no double-tap wait. While renaming, the field below consumes + // its own presses, so this gesture does not fight it. + modifier = Modifier.weight(1f).singleOrDoubleClick(onSingle = { onToggleRange() }, onDouble = onStartRename), + verticalAlignment = Alignment.CenterVertically, + ) { + if (showLeadingSlot) { + if (showRangeToggle) { + // Named for what it discloses, tooltip-free: the parameter name sits immediately to its right. + DisclosureChevron(expanded = rangeOpen, tint = colors.text, contentDescription = rangeToggleLabel) + } else { + Spacer(modifier = Modifier.width(12.dp)) + } + } + if (renaming) { + InlineRenameField( + initialName = name, + textStyle = LocalUmamoTypography.current.labelSmall.copy(color = colors.text), + cursorColor = colors.text, + onCommit = onCommitRename, + onCancel = onCancelRename, + modifier = Modifier.weight(1f).padding(start = 4.dp), + ) + } else { + Text( + text = name, + style = LocalUmamoTypography.current.labelSmall, + color = if (rangeOpen) colors.accent else colors.text, + modifier = Modifier.padding(start = 4.dp), + ) + } + } + if (abs(value - default) > RESET_EPSILON) { + IconButton( + icon = LocalUmamoIcons.reset, + onClick = { onCommitValue(default) }, + contentDescription = resetLabel, + size = DpSize(20.dp, 20.dp), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + Spacer(modifier = Modifier.width(4.dp)) + } + NumberField( + value = value, + onValueChange = onCommitValue, + range = range, + modifier = Modifier.width(64.dp), + stackPosition = stackPosition, + ) + // A fixed-width trailing slot whether or not this row offers a link edit, so the number + // fields stay column-aligned across all rows. + Spacer(modifier = Modifier.width(4.dp)) + Box(modifier = Modifier.size(20.dp), contentAlignment = Alignment.Center) { + if (linkIcon != null && onLinkClick != null) { + IconButton( + icon = linkIcon, + onClick = onLinkClick, + contentDescription = linkContentDescription, + size = DpSize(20.dp, 20.dp), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + suppressFocus = true, + ) + } + } + } +} + +/** + * The axis-name caption above a pad axis's range fields (user data, never localized). + * + * @param String name The axis parameter's display name. + */ +@Composable +private fun RangeAxisLabel(name: String) { + Text( + text = name, + style = LocalUmamoTypography.current.labelSmall, + color = LocalUmamoColors.current.textMuted, + modifier = Modifier.padding(start = 8.dp, top = 4.dp), + ) +} + +/** + * The min / default / max fields for one parameter's range, rendered inside its island while the range + * editor is open. Editing any field commits one undo step through the session (which normalizes + * min <= max, clamps the default into the range, and re-clamps the live pose); the model then refreshes + * the fields. Any number of islands can hold an open range editor at once. + * + * @param Parameter parameter The parameter whose range is edited. + * @param Function onSetRange Called with (min, default, max) to commit a range edit. + */ +@Composable +private fun RangeFieldsRow(parameter: Parameter, onSetRange: (Float, Float, Float) -> Unit) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp), + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + RangeField( + label = stringResource(Res.string.parameter_range_min), + value = parameter.min, + modifier = Modifier.weight(1f), + onCommit = { newMin -> onSetRange(newMin, parameter.default, parameter.max) }, + ) + RangeField( + label = stringResource(Res.string.parameter_range_default), + value = parameter.default, + modifier = Modifier.weight(1f), + onCommit = { newDefault -> onSetRange(parameter.min, newDefault, parameter.max) }, + ) + RangeField( + label = stringResource(Res.string.parameter_range_max), + value = parameter.max, + modifier = Modifier.weight(1f), + onCommit = { newMax -> onSetRange(parameter.min, parameter.default, newMax) }, + ) + } +} + +/** + * One labelled numeric field of the range editor (min / default / max). The field clamps only to a wide + * sanity bound; the session normalizes the resulting triple. + * + * @param String label The field's caption. + * @param Float value The current value. + * @param Modifier modifier The layout modifier (the caller supplies the row weight). + * @param Function onCommit Called with the typed value when the field commits. + */ +@Composable +private fun RangeField( + label: String, + value: Float, + modifier: Modifier = Modifier, + onCommit: (Float) -> Unit, +) { + Column(modifier = modifier) { + Text( + text = label, + style = LocalUmamoTypography.current.labelSmall, + color = LocalUmamoColors.current.textMuted, + modifier = Modifier.padding(start = 2.dp, bottom = 2.dp), + ) + NumberField( + value = value, + onValueChange = onCommit, + range = RANGE_FIELD_LIMIT, + modifier = Modifier.fillMaxWidth(), + // The limit is a wide sanity clamp, not a display range, so the magnitude fill would be meaningless. + showFill = false, + ) + } +} + +/** + * The leading drag handle of a parameter row (a slider, a pad, or a group header). Dragging it reorders + * the row or moves it into / out of a group. Uses raw pointerInput (immediate drag on a dedicated grip, + * since the row body carries sliders and pads), which also never requests focus - so it does not + * reintroduce the link-icon focus bug. + * + * @param String gripLabel The localized accessible label for the handle. + * @param ParameterMoveSubject subject What a drag of this row relocates. + * @param String rowKey The row's stable key (the drag / drop identity). + * @param RowDragController dragController The shared drag state. + * @param Function onDrop Invoked on release to apply the move. + * @param Function onSelect Invoked when the handle is clicked rather than dragged. + */ +@Composable +private fun ParameterGripHandle( + gripLabel: String, + subject: ParameterMoveSubject, + rowKey: String, + dragController: RowDragController, + onDrop: () -> Unit, + onSelect: () -> Unit, +) { + val colors = LocalUmamoColors.current + val gripCoordinates = remember { RowCoordinatesHolder() } + val touchSlop = LocalViewConfiguration.current.touchSlop + // Read at gesture time, not keyed into pointerInput: the callbacks are rebuilt on every recomposition + // of the panel, and keying the gesture to them would cancel an in-flight drag the moment anything + // upstream recomposed - which a drag, by moving the drop indicator, does constantly. + val latestSelect by rememberUpdatedState(onSelect) + val latestDrop by rememberUpdatedState(onDrop) + // Tooltipped as well as named, unlike the disclosure chevrons: a grip's two jobs (drag to reorder, click + // to target the row) are not something the parameter name beside it conveys. The wrapper only wraps - + // the drag's onGloballyPositioned stays on the fixed-size face, so grip coordinates are unchanged. + Tooltip(text = gripLabel) { + Box( + modifier = + Modifier + .size(width = 18.dp, height = 24.dp) + // A hand cursor on hover signals the row is grabbable here (desktop only; touch has no hover). + .pointerHoverIcon(PointerIcon.Hand) + .onGloballyPositioned { coordinates -> gripCoordinates.coordinates = coordinates } + // ONE handler resolving tap versus drag off a single stream. A separate tap detector beside + // detectDragGestures loses the race - the drag detector consumes the press first - which is + // the same trap the keyform sheet's lanes fell into. + .pointerInput(rowKey) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + val origin = gripCoordinates.coordinates?.boundsInWindow() + var dragging = false + // Only a REAL release completes the gesture. Everything else - the coroutine + // cancelled mid-drag (the row scrolled out of composition), the pointer id lost, a + // change consumed by another handler - must cancel a live drag rather than drop it, + // and must never turn a press into a click. The finally is what runs the cancel on + // cancellation, which awaitEachGesture itself gives no hook for. + var released = false + try { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull { candidate -> candidate.id == down.id } ?: break + if (change.isConsumed) { + break + } + if (!change.pressed) { + released = true + break + } + if (!dragging && (change.position - down.position).getDistance() > touchSlop) { + dragging = true + dragController.start( + rowKey, + subject, + (origin?.left ?: 0f) + down.position.x, + (origin?.top ?: 0f) + down.position.y, + ) + } + if (dragging) { + dragController.drag( + (origin?.left ?: 0f) + change.position.x, + (origin?.top ?: 0f) + change.position.y, + ) + change.consume() + } + } + } finally { + when { + dragging && released -> latestDrop() + dragging -> dragController.end() + released -> latestSelect() + // A lost pointer id or a consumed press ends the gesture with no action. + else -> Unit + } + } + } + } + .semantics { contentDescription = gripLabel }, + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.size(14.dp)) { + drawIcon(LocalUmamoIcons.gripVertical, colors.textMuted) + } + } + } +} + +/** + * Context-menu rows for deleting [parameterId]: discard its keys, or move them onto another parameter + * picked from [destinations] (every axis except itself). + */ +private fun deleteParameterMenuItems( + session: EditorSession?, + parameterId: ParameterId, + destinations: List, + discardLabel: String, + moveKeysLabel: String, +): List { + val others = destinations.filter { parameter -> parameter.id != parameterId } + return listOf( + MenuItem.Action( + label = discardLabel, + onSelect = { session?.deleteParameter(parameterId) }, + enabled = session != null, + ), + MenuItem.Submenu( + label = moveKeysLabel, + items = + others.map { destination -> + MenuItem.Action( + label = destination.name, + onSelect = { session?.deleteParameter(parameterId, destination.id) }, + enabled = session != null, + ) + }, + enabled = session != null && others.isNotEmpty(), + ), + ) +} + +/** + * What clicking [row]'s grab handle should target, or null when the row owns no parameter. + * + * A pad selects BOTH its axes with the horizontal one active, matching what clicking the pad itself does - + * the keyform sheet then shows a section per axis, which is the point of targeting a pad at all. + * + * @param ParameterRow row The row whose handle was clicked. + * @return ParameterSelection? The selection to apply, or null for a group header. + */ +private fun parameterSelectionOf(row: ParameterRow): ParameterSelection? = + when (row) { + is ParameterRow.Single -> ParameterSelection.of(row.parameter.id) + is ParameterRow.Pair2D -> + ParameterSelection(setOf(row.horizontal.id, row.vertical.id), row.horizontal.id) + + is ParameterRow.GroupHeader -> null + } + +/** + * Draws the before / after insertion line for a drop-target row. Into is drawn by the group header's own + * fill, so this only handles the reorder bands; a null band or an Into draws nothing. + * + * Drawn OVER the row's content, not behind it: the line sits on the row's top / bottom edge, and the + * ParameterIsland inside fills that same edge with an opaque elevation color, so a drawBehind line is + * completely hidden by its own child. + * + * @param RowDropBand band The row's current drop band, or null when it is not the target. + * @param Color accentColor The insertion-line color. + * @return Modifier The modifier drawing the line over the row. + */ +private fun Modifier.parameterDropLine(band: RowDropBand?, accentColor: Color): Modifier = + this.drawWithContent { + drawContent() + if (band == RowDropBand.Before || band == RowDropBand.After) { + val strokeWidth = 2.5.dp.toPx() + val lineY = + if (band == RowDropBand.Before) { + strokeWidth / 2f + } else { + size.height - strokeWidth / 2f + } + drawLine(accentColor, Offset(0f, lineY), Offset(size.width, lineY), strokeWidth) + } + } + +/** + * The display name of the row currently being dragged (a parameter name, a pad's horizontal axis name, + * or a group name), for the floating drag ghost. + * + * @param List rows The current render rows. + * @param String? draggingKey The dragged row's key, or null. + * @return String The dragged row's display name, or empty when none. + */ +private fun draggedRowLabel(rows: List, draggingKey: String?): String { + val row = rows.firstOrNull { candidate -> rowKey(candidate) == draggingKey } ?: return "" + return when (row) { + is ParameterRow.Single -> row.parameter.name + is ParameterRow.Pair2D -> row.horizontal.name + is ParameterRow.GroupHeader -> row.name + } +} + +/** + * Applies a parameter-row drag drop: resolves the target row and band, then dispatches the tree move. + * Ends the controller first (after capturing its state), so a no-op / illegal drop simply clears the + * drag. An Into drop expands the destination group. + * + * @param RowDragController dragController The drag state (read then cleared). + * @param List rows The current render rows. + * @param PuppetModel puppet The open model (its tree resolves the drop anchor). + * @param EditorSession? session The session the move dispatches through. + * @param Function onExpandGroup Expands a group id (for an Into drop). + */ +private fun performParameterDrop( + dragController: RowDragController, + rows: List, + puppet: PuppetModel, + session: EditorSession?, + onExpandGroup: (ParameterGroupId) -> Unit, +) { + val targetKey = dragController.dropTargetKey + val subject = dragController.draggedPayload + val fraction = dragController.dropTargetFraction ?: 0.5f + dragController.end() + if (targetKey == null || subject == null || session == null) { + return + } + val targetRow = rows.firstOrNull { candidate -> rowKey(candidate) == targetKey } ?: return + val band = parameterDropBandFor(subject, targetRow, targetRow.depth == 0, fraction) ?: return + val (newParentGroupId, before) = parameterDropAnchor(puppet, targetRow, band) + session.moveParameterRow(subject, newParentGroupId, before) + if (band == RowDropBand.Into && targetRow is ParameterRow.GroupHeader) { + onExpandGroup(targetRow.groupId) + } +} + +/** The shared height of a group header row (matches the kit SectionHeader it replaced). */ +private val GROUP_HEADER_HEIGHT = 22.dp + +/** + * A parameter group's header rail: a recessed rounded row with a disclosure chevron and the group name. + * A single tap toggles the group; a double tap opens inline rename. Both go through [singleOrDoubleClick], + * whose raw pointerInput - unlike a clickable - never requests focus (keeping keyboard dispatch on the + * shell root) and, unlike detectTapGestures, fires the toggle immediately instead of waiting out the + * double-tap window. A nest-into drop tints and outlines it. + * + * @param String name The group's display name. + * @param Boolean expanded Whether the group is open (chevron points down). + * @param Boolean nesting Whether a drag is hovering to nest into this group (drop highlight). + * @param Function onToggle Called on a single tap to expand / collapse. + * @param Function onStartRename Called on a double tap to begin inline rename. + */ +@Composable +private fun ParameterGroupHeaderBody( + name: String, + expanded: Boolean, + nesting: Boolean, + onToggle: () -> Unit, + onStartRename: () -> Unit, +) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + Row( + modifier = + Modifier + .fillMaxWidth() + .height(GROUP_HEADER_HEIGHT) + .clip(shapes.small) + .background(colors.tabBackground, shape = shapes.small) + // A "nest into" drop rings the island the way every row drag rings its target. + .rowDropHighlight(nesting, shapes.small, colors) + // A single tap toggles the group immediately (no double-tap wait, so it never feels laggy); + // a double tap opens inline rename. + .singleOrDoubleClick(onSingle = { onToggle() }, onDouble = onStartRename) + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + DisclosureChevron(expanded = expanded, tint = colors.text, glyphSize = 10.dp) + Spacer(modifier = Modifier.width(5.dp)) + Text(text = name, style = LocalUmamoTypography.current.labelMedium) + } +} + +/** + * The inline rename field for a group header, styled as the recessed rail it replaces while editing. + * Commits on Enter or focus loss, cancels on Escape (routed by the shell through LocalInlineEditController). + * + * @param String initialName The current group name, pre-selected for replacement. + * @param Function onCommit Called with the trimmed new name. + * @param Function onCancel Called when the edit is abandoned. + */ +@Composable +private fun ParameterGroupRenameField(initialName: String, onCommit: (String) -> Unit, onCancel: () -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + Box( + modifier = + Modifier + .fillMaxWidth() + .height(GROUP_HEADER_HEIGHT) + .clip(shapes.small) + .background(colors.tabBackground, shape = shapes.small) + .padding(horizontal = 4.dp), + contentAlignment = Alignment.CenterStart, + ) { + InlineRenameField( + initialName = initialName, + textStyle = LocalUmamoTypography.current.labelMedium.copy(color = colors.text), + cursorColor = colors.text, + onCommit = onCommit, + onCancel = onCancel, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersViewState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersViewState.kt new file mode 100644 index 0000000..03d6d52 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ParametersViewState.kt @@ -0,0 +1,102 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.booleanOf +import org.umamo.ui.workspace.stringArrayOrNull +import org.umamo.ui.workspace.stringListOf + +/** The AreaScope.spaceState key the parameters panel parks its view state under, and its member in an area block (UMA §7.3). */ +internal const val PARAMETERS_VIEW_STATE_KEY = "parameters" + +/** + * The parameters panel's view state, parked on the hosting AreaScope via spaceState. Two parameters areas + * each get their own instance, and the instance lives as long as the open document does. A saved document + * carries the group folds, the open range editors, and the selection filter (UMA §7.3); the search query + * and the two in-place rename slots are gestures in flight and are not. + */ +internal class ParametersViewState : PersistentSpaceState { + /** + * The name / id search query; blank shows every parameter the other filters leave. Deliberately not + * carried by a saved document, for the reason [OutlinerViewState.query] is not: a file that reopened + * to last week's filtered list reads as a broken panel. + */ + var query by mutableStateOf("") + + /** + * Parameter islands whose range editor is open, keyed by the island's primary parameter id (a pad + * keys on its horizontal member, so the state survives the param <-> pair row-identity change on + * link / unlink). Multiple islands may be open at once, so range editors on different parameters + * never contend for one shared slot. + */ + val openRangeEditors = mutableStateMapOf() + + /** + * Which parameter groups are expanded, keyed by group id; an absent entry falls back to the group's + * imported initiallyOpen. Parked here rather than in a remember(puppet) so it survives every model + * edit - a link, an undo, a rename each mint a new PuppetModel instance that would otherwise reset it + * and collapse an open group. A newly created group has no entry and is minted initiallyOpen = true, + * so it defaults open. + */ + val expandedGroups = mutableStateMapOf() + + /** + * The group whose header is being renamed in place, or null. Parked here (not remember(puppet), not + * body-local) because the New Group header button - a sibling subtree - opens rename on the group it + * just created, and a rename commit mints a new PuppetModel that must not yank this out mid-edit. + */ + var renamingGroupId: ParameterGroupId? by mutableStateOf(null) + + /** + * The parameter whose name is being renamed in place, or null. Parked here for the same reasons as + * [renamingGroupId]: the Add Parameter header button (a sibling subtree) opens rename on the parameter + * it just created, and every rename / create commit mints a new PuppetModel that must not yank the + * in-place editor out mid-edit. At most one of this and [renamingGroupId] is non-null at a time. + */ + var renamingParameterId: ParameterId? by mutableStateOf(null) + + /** + * When true, the panel shows only the parameters that affect the current selection (a drawable's own + * keyform axes plus every parent deformer up its chain; a deformer's own plus its ancestors'; a part's + * draw-order axes plus its member drawables' effective sets). Off by default. With nothing selected the + * filter is inert (the whole list shows), so the panel is never mysteriously empty. + */ + var showOnlySelected: Boolean by mutableStateOf(false) + + /** + * The parameters panel's member of its area block. + * + * @return JsonObject The member, every known key named. + */ + override fun toJson(): JsonObject = + buildJsonObject { + // UMA §7.3: a group the rigger opened or closed; any other group follows its initiallyOpen (UMA §4.3). + put("expandedGroups", stringArrayOrNull(expandedGroups.filterValues { open -> open }.keys.map { groupId -> groupId.raw })) + put("collapsedGroups", stringArrayOrNull(expandedGroups.filterValues { open -> !open }.keys.map { groupId -> groupId.raw })) + put("openRangeEditors", stringArrayOrNull(openRangeEditors.filterValues { open -> open }.keys.map { parameterId -> parameterId.raw })) + put("onlySelected", if (showOnlySelected) JsonPrimitive(true) else JsonNull) + } + + /** + * Takes the parameters state a document was saved with. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + expandedGroups.clear() + stringListOf(tree, "expandedGroups")?.forEach { raw -> expandedGroups[ParameterGroupId(raw)] = true } + stringListOf(tree, "collapsedGroups")?.forEach { raw -> expandedGroups[ParameterGroupId(raw)] = false } + openRangeEditors.clear() + stringListOf(tree, "openRangeEditors")?.forEach { raw -> openRangeEditors[ParameterId(raw)] = true } + showOnlySelected = booleanOf(tree, "onlySelected") ?: false + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PlaceholderSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PlaceholderSpace.kt new file mode 100644 index 0000000..34ae999 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PlaceholderSpace.kt @@ -0,0 +1,35 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import org.umamo.ui.kit.Text +import org.umamo.ui.theme.LocalUmamoTypography + +/** + * A generic centered-label space body, used for spaces not yet built out (and as the viewport's + * unavailable state). Deliberately tiny so any space can fall back to it during the staged build. + * + * 未実装の空間や、ビューポート不可状態に使う中央ラベルのプレースホルダ。 + * + * @param String label The text to show centered. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun PlaceholderSpace(label: String, modifier: Modifier = Modifier) { + Box( + modifier = modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + style = LocalUmamoTypography.current.titleSmall, + textAlign = TextAlign.Center, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PropertiesHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PropertiesHeaderControls.kt new file mode 100644 index 0000000..11cb212 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PropertiesHeaderControls.kt @@ -0,0 +1,31 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.kit.SEARCH_FIELD_MIN_WIDTH +import org.umamo.ui.kit.SearchField +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.properties.PROPERTIES_VIEW_STATE_KEY +import org.umamo.ui.properties.PropertiesViewState +import org.umamo.ui.workspace.AreaScope + +/** + * The Properties panel's area-header controls (mounted via SpaceDescriptor.headerContent): the property + * search field, centered in the header's flexible middle. Reads and writes the area's shared + * [PropertiesViewState] so the body filters live and auto-switches to a tab with matches; renders nothing + * without an open document, matching the other header controls. + * + * @param AreaScope scope The hosting area's scope carrying the shared view state. + */ +internal fun OverflowRowScope.propertiesHeaderControls(scope: AreaScope) { + val viewState = scope.spaceState(PROPERTIES_VIEW_STATE_KEY) { PropertiesViewState() } + // Flexible gaps on both sides center the search field within the header slot. + flexibleSpace() + item("search", minWidth = SEARCH_FIELD_MIN_WIDTH) { + // The item gates itself on the document: an item that renders nothing measures zero, so the strip + // empties without the builder needing a CompositionLocal it cannot read. + if (LocalPuppet.current != null) { + SearchField(value = viewState.query, onValueChange = { newQuery -> viewState.query = newQuery }) + } + } + flexibleSpace() +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PropertiesSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PropertiesSpace.kt new file mode 100644 index 0000000..49edeaa --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/PropertiesSpace.kt @@ -0,0 +1,315 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CornerSize +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.key +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.Selection +import org.umamo.ui.kit.SectionHeader +import org.umamo.ui.kit.VerticalScrollbarOverlay +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.properties.LocalPropertiesViewState +import org.umamo.ui.properties.LocalPropertyTabRegistry +import org.umamo.ui.properties.PROPERTIES_VIEW_STATE_KEY +import org.umamo.ui.properties.PropertiesViewState +import org.umamo.ui.properties.PropertyContext +import org.umamo.ui.properties.PropertyRow +import org.umamo.ui.properties.PropertySection +import org.umamo.ui.properties.PropertyTab +import org.umamo.ui.properties.PropertyTabId +import org.umamo.ui.properties.sectionVisibility +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.workspace.AreaScope + +/** The width of the left icon tab strip (Blender's property-tab rail): the 28.dp button plus a 2.dp far-edge margin. */ +private val TAB_STRIP_WIDTH = 32.dp + +/** + * The Properties space: a Blender-style tabbed property editor. A left icon strip switches between the + * always-on Document tab and the per-item Object / Data tabs (visible only with one item active); the body + * renders the active tab's collapsible sections. The header's search box (mounted separately via + * [propertiesHeaderControls]) filters sections and auto-switches to a tab that has matches. + * + * Reads [LocalPuppet] for the document + object graph, [LocalSelection] for the active item, and + * [LocalEditorSession] for the session an editable row writes its change through. Its search / + * active-tab / expanded state lives on the area's [PropertiesViewState], shared with the header + * controls, so it survives switching the space away and back. + * + * @param AreaScope scope The hosting area's scope carrying the shared view state. + * @param Modifier modifier The layout modifier. + */ +@Composable +fun PropertiesSpace(scope: AreaScope, modifier: Modifier = Modifier) { + val puppet = LocalPuppet.current + if (puppet == null) { + return + } + val selection = LocalSelection.current?.selection ?: Selection() + // Per-item tabs need one focused item; a multi-selection or empty selection leaves only Document. + val activeTarget = + if (selection.size == 1) { + selection.active ?: selection.targets.firstOrNull() + } else { + null + } + val context = + PropertyContext( + puppet, + selection, + activeTarget, + LocalEditorSession.current, + ) + val viewState = scope.spaceState(PROPERTIES_VIEW_STATE_KEY) { PropertiesViewState() } + val registry = LocalPropertyTabRegistry.current + val colors = LocalUmamoColors.current + val scrollState = rememberScrollState() + + val query = viewState.query.trim() + val searching = query.isNotEmpty() + val visibleTabs = registry.visibleTabs(context) + // Resolve per-row search visibility once for every visible tab; the strip filter and the body both read + // it. Each section's rows are built once here and reused when rendering, so a section's row-building + // (and its label lookups) runs a single time per recomposition. + val visibilityByTab = buildVisibilityIndex(visibleTabs, context, query) + // While searching, the strip shows only tabs that still have a visible section (the "auto-switch tabs" cue). + val stripTabs = + if (searching) { + visibleTabs.filter { tab -> visibilityByTab[tab.id]?.isNotEmpty() == true } + } else { + visibleTabs + } + val activeTabId = resolveActiveTab(searching, stripTabs, visibleTabs, viewState.activeTab) + val bodySections = visibilityByTab[activeTabId].orEmpty() + + Row(modifier = modifier.fillMaxSize()) { + Column( + modifier = + Modifier.fillMaxHeight().width(TAB_STRIP_WIDTH).background(colors.tabBackground) + .padding(start = 4.dp, top = 4.dp, bottom = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + for (tab in stripTabs) { + key(tab.id) { + PropertyTabButton( + tab = tab, + context = context, + active = tab.id == activeTabId, + onClick = { viewState.activeTab = tab.id }, + ) + } + } + } + Box(modifier = Modifier.weight(1f).fillMaxHeight().background(colors.headerBackground)) { + if (bodySections.isEmpty()) { + if (searching) { + PlaceholderSpace(stringResource(Res.string.properties_no_matches)) + } + } else { + Column( + modifier = + Modifier.fillMaxSize().verticalScroll(scrollState) + .padding(horizontal = 6.dp, vertical = 6.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + for (visible in bodySections) { + val section = visible.section + key(section.id) { + // A search forces its matching sections open; otherwise the user's fold state wins, + // defaulting to open for an untouched section. + val expanded = if (searching) true else viewState.expandedSections[section.id] ?: true + PropertySectionIsland { + SectionHeader( + label = stringResource(section.title), + expanded = expanded, + onToggle = { + viewState.expandedSections[section.id] = + !(viewState.expandedSections[section.id] ?: true) + }, + ) + if (expanded) { + Column( + modifier = + Modifier.fillMaxWidth() + .padding(start = 12.dp, end = 8.dp, top = 2.dp, bottom = 8.dp), + // Breathing room between separate rows so filled controls do not touch; a + // FieldStack's own 1.dp seam is internal, so stacked groups stay tight. + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + // Only the rows that survived the search (every row when not searching). + for (rowIndex in visible.visibleRowIndices) { + key(rowIndex) { + // A row that keeps per-area state (a relation list's dragged height) reaches it here. + CompositionLocalProvider(LocalPropertiesViewState provides viewState) { + visible.rows[rowIndex].content(context) + } + } + } + } + } + } + } + } + } + VerticalScrollbarOverlay(scrollState) + } + } + } +} + +/** + * One section that survived the header-search filter: the [section] itself, its already-resolved [rows] + * (built once so rendering reuses them), and the [visibleRowIndices] to draw - every row when not + * searching or when the section title matched, else just the matching rows. + * + * @property PropertySection section The surviving section. + * @property List rows The section's rows for the current context, resolved once. + * @property List visibleRowIndices The indices into [rows] to draw, in order. + */ +private class VisibleSection( + val section: PropertySection, + val rows: List, + val visibleRowIndices: List, +) + +/** + * Resolves, for every visible tab, which of its sections and rows survive the current [query]. Resolving + * the localized section titles and row terms needs Compose, so this runs in the composition and the pure + * [sectionVisibility] decides the match. A tab maps to its surviving sections in order (empty when none + * match), which both the strip filter and the body read. + * + * @param List visibleTabs The tabs visible for the context, in strip order. + * @param PropertyContext context The current context the sections read from. + * @param String query The trimmed search text. + * @return Map The surviving sections per tab id. + */ +@Composable +private fun buildVisibilityIndex( + visibleTabs: List, + context: PropertyContext, + query: String, +): Map> { + val index = LinkedHashMap>(visibleTabs.size) + for (tab in visibleTabs) { + val survivors = ArrayList() + for (section in tab.sections(context)) { + val rows = section.rows(context) + val rowTerms = rows.map { row -> row.terms.map { term -> stringResource(term) } } + val visibility = sectionVisibility(stringResource(section.title), rowTerms, query) + if (visibility.shown) { + survivors.add(VisibleSection(section, rows, visibility.visibleRowIndices)) + } + } + index[tab.id] = survivors + } + return index +} + +/** + * A raised section card: one elevation step above the panel body (headerBackground over panelBackground, + * the kit's standard two-tone step), rounded with the medium shape and outlined, mirroring the Parameters + * panel's ParameterIsland. It holds the section's disclosure header and, while open, its rows. The header + * spans the card (its hover fill is clipped to the rounded corners), so the island adds no inner padding of + * its own - the header and body manage their own insets. + * + * @param Function content The card's contents (the SectionHeader and the open section body). + */ +@Composable +private fun PropertySectionIsland(content: @Composable ColumnScope.() -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + Column( + modifier = + Modifier.fillMaxWidth() + .clip(shapes.medium) + .background(colors.panelThirdElevation, shape = shapes.medium) + .border(width = 1.dp, color = colors.panelThirdElevationBorder, shape = shapes.medium), + content = content, + ) +} + +/** + * One icon-strip tab button. The active tab's cell is filled to the area-header color and rounded on its + * outer (left) edge, square on the body-facing (right) edge, so it reads as a tab pulled out of the rail + * toward its content - the fill is the active cue, in place of an accent glyph. + * + * @param PropertyTab tab The tab this button switches to. + * @param PropertyContext context The current context (resolves the adaptive Data-tab glyph). + * @param Boolean active Whether this is the active tab. + * @param Function onClick Selects this tab. + */ +@Composable +private fun PropertyTabButton(tab: PropertyTab, context: PropertyContext, active: Boolean, onClick: () -> Unit) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val cellModifier = + Modifier.fillMaxWidth().background( + color = if (active) colors.headerBackground else colors.panelBackground, + shape = + RoundedCornerShape( + topStart = shapes.small.topStart, + topEnd = CornerSize(0.dp), + bottomEnd = CornerSize(0.dp), + bottomStart = shapes.small.bottomStart, + ), + ) + Box(modifier = cellModifier, contentAlignment = Alignment.Center) { + IconButton( + icon = tab.icon(context), + onClick = onClick, + contentDescription = stringResource(tab.title), + size = DpSize(28.dp, 28.dp), + glyphSize = 18.dp, + ) + } +} + +/** + * The tab to render, clamping the stored choice to a visible tab. While searching this follows the search: + * it keeps the stored tab only if it still has matches, else falls to the first matching tab. With no + * candidate it lands on Document, which is always visible. + * + * @param Boolean searching Whether a search is active. + * @param List stripTabs The tabs shown in the strip (the matching ones while searching). + * @param List visibleTabs Every visible tab for the context. + * @param PropertyTabId stored The tab the user last selected. + * @return PropertyTabId The tab to show. + */ +private fun resolveActiveTab( + searching: Boolean, + stripTabs: List, + visibleTabs: List, + stored: PropertyTabId, +): PropertyTabId { + if (searching) { + val keepStored = stripTabs.firstOrNull { tab -> tab.id == stored } + return (keepStored ?: stripTabs.firstOrNull())?.id ?: PropertyTabId.Document + } + return if (visibleTabs.any { tab -> tab.id == stored }) stored else PropertyTabId.Document +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/RowHoverPreview.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/RowHoverPreview.kt new file mode 100644 index 0000000..aee4773 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/RowHoverPreview.kt @@ -0,0 +1,131 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.boundsInWindow +import kotlinx.coroutines.delay +import org.umamo.ui.workspace.rowdrag.RowCoordinatesHolder + +/* + * The hover art preview a list space pops beside a rested-on row, shared by the Outliner and the Sources + * space so both keep one rest delay and one ownership rule. A space holds one state, each row reports + * its own hover into it, and the space draws the one preview the state shows beside its row + * (RowThumbnailPreview). What a row previews is the space's business: the state carries only the row's + * key, which the space resolves back to its art. + */ + +/** Pause the pointer must rest on a row before its art preview pops, so a sweep down the list does not flicker. */ +private const val ROW_HOVER_PREVIEW_DELAY_MILLIS = 10L + +/** + * A pending art preview: which row is hovered, the name shown under its art, and the row's window bounds + * the preview anchors beside. + * + * @property Key key The hovered row's identity, which the space resolves back to its art. + * @property String name The row's display name (document data, not localized). + * @property Rect rowBounds The hovered row's bounds in window pixels. + */ +internal data class RowHoverPreview(val key: Key, val name: String, val rowBounds: Rect) + +/** + * One list space's hover preview: the row under the pointer the moment it is hovered, and the row whose + * preview shows, which lags it by the rest delay. + * + * Only the row that owns the current preview may clear it. Moving onto the next row reports that row + * first, so the old row's exit, arriving after, must not undo it. + */ +@Stable +internal class RowHoverPreviewState { + /** The row under the pointer, or null when none reports one. */ + var hovered: RowHoverPreview? by mutableStateOf(null) + private set + + /** The row whose preview shows: [hovered] once the pointer has rested on it, or null. */ + var shown: RowHoverPreview? by mutableStateOf(null) + internal set + + /** + * Reports a row the pointer is over, replacing whichever row was. + * + * @param RowHoverPreview preview The hovered row. + */ + fun report(preview: RowHoverPreview) { + hovered = preview + } + + /** + * Withdraws the row [key] reported, when it still owns the preview. + * + * @param Key key The row leaving. + */ + fun clear(key: Key) { + if (hovered?.key == key) { + hovered = null + } + } +} + +/** + * The space's hover preview state, with the rest delay running: [RowHoverPreviewState.shown] follows + * [RowHoverPreviewState.hovered] only once the hovered row has held for the delay. The delay re-arms on + * every change of row, so only a rested pointer surfaces a preview. + * + * @return RowHoverPreviewState The state. + */ +@Composable +internal fun rememberRowHoverPreviewState(): RowHoverPreviewState { + val state = remember { RowHoverPreviewState() } + LaunchedEffect(state.hovered) { + val pending = state.hovered + if (pending == null) { + state.shown = null + } else { + delay(ROW_HOVER_PREVIEW_DELAY_MILLIS) + state.shown = pending + } + } + return state +} + +/** + * Reports one row's hover into [state]: the row's preview while it is hovered, withdrawn when the pointer + * leaves, when the row stops having art to preview, or when the row leaves the list (scrolled away or + * filtered out), so a row that is gone never leaves its preview standing. + * + * Keyed on the row's identity, so a row slot that comes to hold another item reports the new one. + * + * @param RowHoverPreviewState state The space's hover preview state. + * @param Key key The row's identity. + * @param String name The row's display name, shown under its art. + * @param Boolean hovered Whether the pointer is over the row. + * @param Boolean enabled Whether the row has art to preview. + * @param RowCoordinatesHolder boundsHolder The row's coordinates, read for its window bounds. + */ +@Composable +internal fun ReportRowHover( + state: RowHoverPreviewState, + key: Key, + name: String, + hovered: Boolean, + enabled: Boolean, + boundsHolder: RowCoordinatesHolder, +) { + LaunchedEffect(hovered, enabled, key) { + if (hovered && enabled) { + val bounds = boundsHolder.coordinates?.boundsInWindow() ?: return@LaunchedEffect + state.report(RowHoverPreview(key, name, bounds)) + } else { + state.clear(key) + } + } + DisposableEffect(state, key) { + onDispose { state.clear(key) } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/RowThumbnailPopup.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/RowThumbnailPopup.kt new file mode 100644 index 0000000..a1c2a9f --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/RowThumbnailPopup.kt @@ -0,0 +1,113 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties +import org.umamo.ui.kit.Surface +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.ThumbnailSlot +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import kotlin.math.max +import kotlin.math.roundToInt + +/** The square edge of a row's hover preview - bigger than the picker slot so the art is easy to read. */ +private val ROW_PREVIEW_SIZE = 120.dp + +/** + * Positions a row's hover preview just to the right of the hovered row (anchored by its window + * bounds), flipping to the left when it would overflow the window's right edge and clamping to the window + * on both axes. Unlike the menu providers this ignores the Popup's own anchor layout - the preview is + * mounted at the space root, so the row's absolute window rectangle [anchorRect] is the real anchor. + * + * @property Rect anchorRect The hovered row's bounds, in window pixels. + * @property Int gapPx The horizontal gap between the row and the preview, in pixels. + */ +private class RowSidePopupPositionProvider( + private val anchorRect: Rect, + private val gapPx: Int, +) : PopupPositionProvider { + /** + * Computes the preview's top-left in window coordinates. + * + * @param IntRect anchorBounds The Popup's anchor layout bounds (unused - the row rect is the anchor). + * @param IntSize windowSize The host window size. + * @param LayoutDirection layoutDirection The layout direction (unused; the preview is LTR-neutral). + * @param IntSize popupContentSize The measured preview size. + * @return IntOffset The preview's top-left, clamped into the window. + */ + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val rightOfRow = anchorRect.right.roundToInt() + gapPx + val leftOfRow = anchorRect.left.roundToInt() - gapPx - popupContentSize.width + // Prefer the right of the row; flip to the left when the preview would overflow the window edge. + val preferredX = if (rightOfRow + popupContentSize.width <= windowSize.width) rightOfRow else leftOfRow + val x = preferredX.coerceIn(0, max(0, windowSize.width - popupContentSize.width)) + val y = anchorRect.top.roundToInt().coerceIn(0, max(0, windowSize.height - popupContentSize.height)) + return IntOffset(x, y) + } +} + +/** + * A passive hover preview for a list row with art - an Outliner drawable or part, a Sources layer, tile, + * or drawable: the thumbnail over the themed checker (so a transparent layer reads as a silhouette) with + * the row's name beneath, in a small floating card anchored beside the hovered row. Non-focusable - it never steals input or the selection; the caller + * shows and hides it purely by composing or not composing it (no dismiss handling needed). + * + * @param String name The row's display name (document data, not localized). + * @param ImageBitmap thumbnail The cropped art preview. + * @param Rect anchorRect The hovered row's bounds, in window pixels, the card is placed beside. + */ +@Composable +fun RowThumbnailPreview(name: String, thumbnail: ImageBitmap, anchorRect: Rect) { + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val typography = LocalUmamoTypography.current + val gapPx = with(LocalDensity.current) { 8.dp.roundToPx() } + Popup( + popupPositionProvider = RowSidePopupPositionProvider(anchorRect, gapPx), + properties = PopupProperties(focusable = false), + ) { + Surface( + color = colors.menuBackground, + shape = shapes.medium, + border = BorderStroke(1.dp, colors.panelBorder), + shadowElevation = 8.dp, + ) { + Column(modifier = Modifier.padding(6.dp)) { + ThumbnailSlot(thumbnail = thumbnail, size = ROW_PREVIEW_SIZE) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = name, + style = typography.bodySmall, + color = colors.text, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = ROW_PREVIEW_SIZE), + ) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesHeaderControls.kt new file mode 100644 index 0000000..cd31179 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesHeaderControls.kt @@ -0,0 +1,118 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.Checkbox +import org.umamo.ui.kit.FilterPopupChip +import org.umamo.ui.kit.FilterSectionLabel +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.kit.SEARCH_FIELD_MIN_WIDTH +import org.umamo.ui.kit.SearchField +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalSourceWatch +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.workspace.AreaScope + +/** + * The Sources space's area-header controls: Import Artwork… (the file.importArtwork command, so the palette + * and the button share one path), the name search centered in the flexible middle, Match + * Automatically (sources.matchAutomatically), Reload (which also re-probes whether each file is still + * on disk), and the filter chip. Reads and writes the area's shared SourcesViewState; renders nothing + * without an open document. + * + * @param AreaScope scope The hosting area's scope carrying the shared view state. + */ +internal fun OverflowRowScope.sourcesHeaderControls(scope: AreaScope) { + val viewState = scope.spaceState(SOURCES_VIEW_STATE_KEY) { SourcesViewState() } + item("add") { + if (LocalPuppet.current != null) { + val commands = LocalCommands.current + IconButton( + icon = LocalUmamoIcons.addFile, + onClick = { commands.invoke("file.importArtwork") }, + contentDescription = stringResource(Res.string.cmd_import_artwork), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + } + } + flexibleSpace() + item("search", minWidth = SEARCH_FIELD_MIN_WIDTH) { + if (LocalPuppet.current != null) { + SearchField(value = viewState.query, onValueChange = { newQuery -> viewState.query = newQuery }) + } + } + flexibleSpace() + item("match") { + if (LocalPuppet.current != null) { + // Every file is read and the bindings the files no longer resolve move to their confident + // matches as one step; the rest keep their proposals on the rows that need review. + val commands = LocalCommands.current + IconButton( + icon = LocalUmamoIcons.wand, + onClick = { commands.invoke("sources.matchAutomatically") }, + contentDescription = stringResource(Res.string.sources_match_automatically), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + } + } + item("reload") { + if (LocalPuppet.current != null) { + // One button: re-probe every file's presence, then reload the present ones as one undo step + // (the command itself says when nothing changed). The alert glyph is the watcher's: files + // changed on disk and await this press (notify mode, or a file edited while the document was closed). + val commands = LocalCommands.current + val pending = LocalSourceWatch.current?.pending?.collectAsState()?.value.orEmpty() + IconButton( + icon = if (pending.isEmpty()) LocalUmamoIcons.refresh else LocalUmamoIcons.refreshAlert, + onClick = { + viewState.refreshSerial++ + commands.invoke("document.reloadArtwork") + }, + contentDescription = stringResource(if (pending.isEmpty()) Res.string.sources_reload else Res.string.sources_reload_pending), + appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small), + ) + } + } + item("filter") { + if (LocalPuppet.current != null) { + FilterDropdownButton(viewState) + } + } +} + +/** + * The filter chip: one checkbox per kind of row, each toggled on its own like the outliner's, in the + * shared [FilterPopupChip]. + * + * @param SourcesViewState viewState The area's shared view state. + */ +@Composable +private fun FilterDropdownButton(viewState: SourcesViewState) { + FilterPopupChip( + contentDescription = stringResource(Res.string.common_filters), + icon = if (viewState.isUnfiltered) LocalUmamoIcons.filterUnfiltered else LocalUmamoIcons.filterFiltered, + ) { + FilterSectionLabel(stringResource(Res.string.common_filters)) + for (filter in SourcesFilter.entries) { + Checkbox( + checked = filter in viewState.filters, + onCheckedChange = { checked -> viewState.setShown(filter, checked) }, + label = + stringResource( + when (filter) { + SourcesFilter.Bound -> Res.string.sources_filter_bound + SourcesFilter.Unbound -> Res.string.sources_filter_unbound + SourcesFilter.Missing -> Res.string.sources_filter_missing + SourcesFilter.NeedsReview -> Res.string.sources_filter_needs_review + }, + ), + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesSpace.kt new file mode 100644 index 0000000..c2dbeff --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesSpace.kt @@ -0,0 +1,951 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.Selection +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.reimport.LayerMatch +import org.umamo.reimport.suggestionsFor +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.drawableIdsByAtlasTile +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.DisclosureChevron +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.DropdownChipStyle +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.button.IconSlot +import org.umamo.ui.kit.formatDecimals +import org.umamo.ui.model.LocalDrawableThumbnails +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.model.LocalSourceArtRasters +import org.umamo.ui.model.LocalSourceFilePresence +import org.umamo.ui.model.LocalSourceSuggestions +import org.umamo.ui.model.LocalSourceWatch +import org.umamo.ui.model.SourceTileThumbnails +import org.umamo.ui.model.percentOf +import org.umamo.ui.rememberBooleanSetting +import org.umamo.ui.resources.* +import org.umamo.ui.settings.IMPORT_LAYER_POSITIONS_FROM_WORLD_AXES_KEY +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.UmamoColors +import org.umamo.ui.theme.UmamoIcon +import org.umamo.ui.theme.UmamoIcons +import org.umamo.ui.workspace.AreaScope +import org.umamo.ui.workspace.commands.DeleteArtRequest +import org.umamo.ui.workspace.commands.IgnoreLayerRequest +import org.umamo.ui.workspace.commands.RelinkRequest +import org.umamo.ui.workspace.commands.ReloadScope +import org.umamo.ui.workspace.commands.ReplaceRequest +import org.umamo.ui.workspace.rowdrag.RowCoordinatesHolder +import org.umamo.ui.workspace.rowdrag.RowDragController +import org.umamo.ui.workspace.rowdrag.RowDragLabel +import org.umamo.ui.workspace.rowdrag.dragRowOnLongPress +import org.umamo.ui.workspace.rowdrag.parkCancelOnSeam +import org.umamo.ui.workspace.rowdrag.rowDropHighlight + +/* + * The Sources space: the linking table between the document's artwork files and its art. File -> + * layer -> tile -> drawables, each with a status; a layer row dragged onto a tile row (or the reverse) + * rebinds the tile, a tile row's chip picks a layer or unbinds, a row that needs review carries the + * matcher's proposal to accept or a relink by hand, an unbound layer row's chip (or its context menu) + * ignores the layer so a reload never mints it, and a file row's chip (or its context menu) replaces + * or reloads that one file. Drawable rows select, so the table is also a way into the rig by the art + * it came from. + */ + +private val SOURCES_ROW_HEIGHT = 22.dp +private val SOURCES_INDENT_PER_DEPTH = 12.dp +private val SOURCES_CHEVRON_WIDTH = 14.dp +private val SOURCES_ICON_WIDTH = 16.dp + +/** The relink menu's width, which its search box fixes so the rows stay put as the search narrows them. */ +private val RELINK_PANEL_WIDTH = 320.dp + +/** What a dragged row carries: the binding a layer row stands for, or the tile a tile row stands for. */ +internal sealed interface SourcesDragPayload { + data class Layer(val ref: SourceLayerRef) : SourcesDragPayload + + data class Tile(val tileId: AtlasTileId) : SourcesDragPayload +} + +/** The art a row previews on hover: a tile's source art, or a drawable's crop of the atlas. */ +internal sealed interface SourcesPreviewSubject { + data class Tile(val tileId: AtlasTileId) : SourcesPreviewSubject + + data class Drawable(val drawableId: DrawableId) : SourcesPreviewSubject +} + +/** + * The Sources space body. + * + * @param AreaScope scope The hosting area's scope (view state, per-area state). + * @param Modifier modifier The layout modifier. + */ +@Composable +fun SourcesSpace(scope: AreaScope, modifier: Modifier = Modifier) { + val colors = LocalUmamoColors.current + val listState = rememberLazyListState() + val puppet = LocalPuppet.current + if (puppet == null) { + Box(modifier = modifier.fillMaxSize().zebraFill(listState, SOURCES_ROW_HEIGHT, colors.rowStripe)) + return + } + val session = LocalEditorSession.current + val selection = LocalSelection.current?.selection ?: Selection() + val presenceProbe = LocalSourceFilePresence.current + val viewState = scope.spaceState(SOURCES_VIEW_STATE_KEY) { SourcesViewState() } + // The watcher's presence serial: a file deleted or returned re-probes without a click. + val watchSerial = LocalSourceWatch.current?.serial?.collectAsState()?.value ?: 0 + + // The presence probe runs once per source per refresh, off the row composition: a file check per + // recompose would hit the disk every time the pointer moves. + val presenceBySource = + remember(puppet.sources, viewState.refreshSerial, watchSerial, presenceProbe) { + puppet.sources.associate { source -> + val path = source.path + val present = if (path == null || presenceProbe == null) null else presenceProbe(path) + source.id to + when (present) { + null -> SourcePresence.Unknown + true -> SourcePresence.Present + false -> SourcePresence.Missing + } + } + } + val unboundGroupLabel = stringResource(Res.string.sources_unbound_art) + // Two tiers of proposal for a binding the file no longer resolves: the one the last operation that + // read the file scored with pixels, else the one the model's own inventory ranks (names, folders, + // bounds, hashes) - so the chips show something even before any file is read. + val published = LocalSourceSuggestions.current?.suggestions?.collectAsState()?.value.orEmpty() + // Keyed on what the ranking reads - the files and the tile bindings - not the whole model: a + // vertex drag mints a model per frame, and the name-distance pass over every lost layer and every + // candidate must not run on each of them. + val modelSuggestions = + remember(puppet.sources, puppet.atlas.tiles) { + puppet.sources.associate { source -> source.id to suggestionsFor(puppet, source.id) } + } + val suggestionCandidates: (ArtSourceId, String) -> List = + { sourceId, key -> listOfNotNull(published[sourceId to key], modelSuggestions[sourceId]?.get(key)) } + // Read live, so flipping the preference re-measures the layer rows at once. + val layerPositionsFromWorldAxes by rememberBooleanSetting(IMPORT_LAYER_POSITIONS_FROM_WORLD_AXES_KEY, false) + val tree = + remember(puppet, presenceBySource, unboundGroupLabel, published, layerPositionsFromWorldAxes) { + buildSourcesTree( + puppet, + { source: ArtSource -> presenceBySource[source.id] ?: SourcePresence.Unknown }, + unboundGroupLabel, + layerPositionsFromWorldAxes = layerPositionsFromWorldAxes, + suggestionsFor = suggestionCandidates, + ) + } + val query = viewState.query + val filtered = remember(tree, query, viewState.filters) { filterSourcesTree(tree, query, viewState.filters) } + // Expand state by node id, on the view state so a saved document carries it (UMA §7.3). Files and the + // unbound group open by default; layers and tiles close. + val expanded = viewState.expanded + val searching = query.isNotBlank() + val isOpen: (String) -> Boolean = { id -> searching || viewState.isOpen(id) } + val rows = remember(filtered, expanded.toMap(), searching) { flattenSources(filtered, isOpen) } + val nodeById = remember(rows) { rows.associate { row -> row.node.id to row.node } } + + // Drag-and-drop: long-press a layer or tile row, drop it on the other kind to rebind. Transient, + // per space instance; Escape cancels through the shell's shared seam like the outliner. + val dragController = remember { RowDragController() } + dragController.parkCancelOnSeam() + // A relink is a command, not a session edit from here: the app reads the layer's file and pulls its + // art in (a binding-only change when it cannot), and the shell resolves where the strip shows. + val commands = LocalCommands.current + val relink: (List, SourceLayerRef?, List) -> Unit = { tileIds, ref, retire -> commands.invoke("sources.relink", RelinkRequest(tileIds, ref, retire)) } + val performDrop: () -> Unit = { + val payload = dragController.draggedPayload + val target = dragController.dropTargetKey?.let { key -> nodeById[key] } + if (session != null && payload != null && target != null) { + relinkFor(payload, target)?.let { (tileId, ref) -> relink(listOf(tileId), ref, emptyList()) } + } + dragController.end() + } + + // Hover art preview: a layer or tile row shows its source art from the document's raster store, a + // drawable row the atlas crop the outliner shows. Either provider may be absent, which previews nothing. + val artRasters = LocalSourceArtRasters.current + val tileThumbnails = remember(artRasters) { artRasters?.let { store -> SourceTileThumbnails(store) } } + val drawableThumbnails = LocalDrawableThumbnails.current + val hoverPreview = rememberRowHoverPreviewState() + + if (tree.isEmpty()) { + Box(modifier = modifier.fillMaxSize().zebraFill(listState, SOURCES_ROW_HEIGHT, colors.rowStripe)) + return + } + LazyColumn( + state = listState, + modifier = modifier.fillMaxSize().zebraFill(listState, SOURCES_ROW_HEIGHT, colors.rowStripe), + ) { + items(rows, key = { row -> row.node.id }) { row -> + SourcesRowView( + row = row, + puppet = puppet, + expanded = isOpen(row.node.id), + selected = row.node.kind.let { kind -> kind is SourcesNodeKind.Drawable && SelectionTarget.Drawable(kind.drawableId) in selection.targets }, + onToggle = { expanded[row.node.id] = !isOpen(row.node.id) }, + onSelect = { targets -> + if (session != null && targets.isNotEmpty()) { + session.setSelection(targets.drop(1).fold(SelectionOps.replace(targets.first())) { acc, target -> SelectionOps.add(acc, target) }) + } + }, + onRelink = relink, + dragController = dragController, + onDrop = performDrop, + hoverPreview = hoverPreview, + ) + } + } + // One art preview for the whole space, beside the rested-on row, once its art resolves. + val preview = hoverPreview.shown + val previewBitmap = + preview?.let { shown -> nodeById[shown.key]?.let(::sourcesPreviewSubject) }?.let { subject -> + when (subject) { + is SourcesPreviewSubject.Tile -> tileThumbnails?.thumbnailFor(subject.tileId) + is SourcesPreviewSubject.Drawable -> drawableThumbnails?.thumbnailFor(subject.drawableId) + } + } + if (preview != null && previewBitmap != null) { + RowThumbnailPreview(name = preview.name, thumbnail = previewBitmap, anchorRect = preview.rowBounds) + } + // A name chip follows the cursor while dragging, so there is something clearly "in hand" beyond the + // faded row: the row being dragged (a layer or a tile). + val draggingLabel = dragController.draggingKey?.let { id -> nodeById[id]?.label } + if (dragController.isDragging && draggingLabel != null) { + RowDragLabel(label = draggingLabel, cursorX = dragController.dragWindowX, cursorY = dragController.dragWindowY) + } +} + +/** + * The rebind a drop means: a layer onto a tile, or a tile onto a layer; anything else is no drop. A + * layer row under review (lost, erased, or lost to a replacement) is no target either - it stands for + * a review, not for art a tile could take, and a binding to it would read as needing review the moment + * it landed - and neither is an ignored row, which the rigger keeps out of the rig. + * + * @param SourcesDragPayload payload The dragged row. + * @param SourcesNode target The row it was dropped on. + * @return Pair? The tile to rebind and its new binding, or null. + */ +internal fun relinkFor(payload: SourcesDragPayload, target: SourcesNode): Pair? { + val kind = target.kind + return when { + payload is SourcesDragPayload.Layer && kind is SourcesNodeKind.Tile -> kind.tileId to payload.ref + payload is SourcesDragPayload.Tile && kind is SourcesNodeKind.Layer && !target.status.isReview && target.status != SourcesStatus.Ignored -> payload.tileId to kind.ref + else -> null + } +} + +/** + * The art a row previews on hover: a tile row its tile, a layer row the first tile bound to it, and a + * drawable row its drawable. A layer under review still binds its old tile, so its row previews the art + * the review is about. A file row, the unbound group, and a layer no tile binds preview nothing - an + * unbound layer's pixels live in its file, not in the document. + * + * @param SourcesNode node The hovered row. + * @return SourcesPreviewSubject? What the row previews, or null for nothing. + */ +internal fun sourcesPreviewSubject(node: SourcesNode): SourcesPreviewSubject? = + when (val kind = node.kind) { + is SourcesNodeKind.Tile -> SourcesPreviewSubject.Tile(kind.tileId) + is SourcesNodeKind.Layer -> node.children.firstNotNullOfOrNull { child -> (child.kind as? SourcesNodeKind.Tile)?.let { tile -> SourcesPreviewSubject.Tile(tile.tileId) } } + is SourcesNodeKind.Drawable -> SourcesPreviewSubject.Drawable(kind.drawableId) + is SourcesNodeKind.Source, SourcesNodeKind.UnboundGroup -> null + } + +/** + * The drawables a row's click selects: a drawable row itself, a tile row every drawable over it, a + * layer row every drawable over its bound tiles; files and the unbound group select nothing. + * + * @param SourcesNode node The clicked row. + * @param PuppetModel puppet The rig. + * @return List The targets, possibly empty. + */ +private fun selectionTargetsOf(node: SourcesNode, puppet: PuppetModel): List { + fun drawablesOver(tileId: AtlasTileId): List = puppet.drawableIdsByAtlasTile()[tileId].orEmpty() + return when (val kind = node.kind) { + is SourcesNodeKind.Drawable -> listOf(SelectionTarget.Drawable(kind.drawableId)) + is SourcesNodeKind.Tile -> drawablesOver(kind.tileId).map { drawableId -> SelectionTarget.Drawable(drawableId) } + is SourcesNodeKind.Layer -> + node.children.flatMap { child -> (child.kind as? SourcesNodeKind.Tile)?.let { tile -> drawablesOver(tile.tileId) }.orEmpty() } + .map { drawableId -> SelectionTarget.Drawable(drawableId) } + is SourcesNodeKind.Source, SourcesNodeKind.UnboundGroup -> emptyList() + } +} + +/** + * One row: indent, chevron, icon, label, detail, status, and the trailing chip its kind carries - a + * tile row's relink chip, a review row's proposal chip, an unbound layer row's ignore chip, a file + * row's actions chip (the last two mirrored in the row's context menu). + * + * @param SourcesRow row The row. + * @param PuppetModel puppet The rig, for the relink chip's candidates and the click's targets. + * @param Boolean expanded Whether the row's children are shown. + * @param Boolean selected Whether the row's drawable is in the session selection. + * @param Function onToggle Flips the expand state. + * @param Function onSelect Selects the given targets. + * @param Function onRelink Rebinds tiles to one layer (null unbinds), retiring the tiles the accepted proposal named. + * @param RowDragController dragController The space's drag state. + * @param Function onDrop Applies the drop on release. + * @param RowHoverPreviewState hoverPreview The space's hover preview state the row reports into. + */ +@Composable +private fun SourcesRowView( + row: SourcesRow, + puppet: PuppetModel, + expanded: Boolean, + selected: Boolean, + onToggle: () -> Unit, + onSelect: (List) -> Unit, + onRelink: (List, SourceLayerRef?, List) -> Unit, + dragController: RowDragController, + onDrop: () -> Unit, + hoverPreview: RowHoverPreviewState, +) { + val node = row.node + val colors = LocalUmamoColors.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val boundsHolder = remember { RowCoordinatesHolder() } + ReportRowHover( + state = hoverPreview, + key = node.id, + name = node.label, + hovered = hovered, + enabled = sourcesPreviewSubject(node) != null, + boundsHolder = boundsHolder, + ) + val currentOnDrop by rememberUpdatedState(onDrop) + // A layer under review drags nowhere: its binding is what is under review, not a layer to offer; an + // ignored layer stays out of the rig until its row says otherwise. + val payload: SourcesDragPayload? = + when (val kind = node.kind) { + is SourcesNodeKind.Layer -> if (node.status.isReview || node.status == SourcesStatus.Ignored) null else SourcesDragPayload.Layer(kind.ref) + is SourcesNodeKind.Tile -> SourcesDragPayload.Tile(kind.tileId) + else -> null + } + val isDragged = dragController.draggingKey == node.id + val isDropTarget = + dragController.isDragging && + !isDragged && + dragController.dropTargetKey == node.id && + dragController.draggedPayload?.let { dragged -> relinkFor(dragged, node) } != null + DisposableEffect(node.id) { + onDispose { dragController.clearBounds(node.id) } + } + // A valid target (a layer under a dragged tile, a tile under a dragged layer) takes the shared drop ring; + // anything else under the pointer shows nothing, so the rigger sees where a release would bind. + val background = + when { + selected -> colors.accent.copy(alpha = 0.25f) + hovered -> colors.rowHover + else -> Color.Transparent + } + val sourceKind = node.kind as? SourcesNodeKind.Source + val layerKind = node.kind as? SourcesNodeKind.Layer + val commands = LocalCommands.current + val body: @Composable () -> Unit = { + SourcesRowBody( + row = row, + puppet = puppet, + expanded = expanded, + background = background, + isDropTarget = isDropTarget, + isDragged = isDragged, + interaction = interaction, + boundsHolder = boundsHolder, + payload = payload, + onToggle = onToggle, + onSelect = onSelect, + onRelink = onRelink, + dragController = dragController, + onDropNow = { currentOnDrop() }, + ) + } + // A secondary press falls through the row's clickable to the menu; the items are the row's own + // chip's, so a mouse and a pen reach the same actions. + when { + sourceKind != null -> ContextMenuArea(items = sourceFileMenuItems(sourceKind.sourceId, commands), content = body) + layerKind != null && ignorable(node.status) -> + ContextMenuArea(items = layerMenuItems(layerKind.ref, ignored = node.status == SourcesStatus.Ignored, commands = commands), content = body) + else -> body() + } +} + +/** + * The file row's two actions, as the chip and the context menu both list them: Replace Artwork… + * (`sources.replaceArtwork`) and Reload This File (`document.reloadArtwork` scoped to the file). + * + * @param ArtSourceId sourceId The file. + * @param org.umamo.ui.action.CommandRegistry commands The registry to dispatch through. + * @return List The items. + */ +@Composable +private fun sourceFileMenuItems(sourceId: ArtSourceId, commands: org.umamo.ui.action.CommandRegistry): List = + listOf( + MenuItem.Action(stringResource(Res.string.sources_file_menu_replace), onSelect = { commands.invoke("sources.replaceArtwork", ReplaceRequest(sourceId)) }), + MenuItem.Action(stringResource(Res.string.sources_file_menu_reload), onSelect = { commands.invoke("document.reloadArtwork", ReloadScope(setOf(sourceId))) }), + ) + +/** + * Whether a layer row carries the ignore toggle: an unbound present layer, or one already ignored. A + * bound row is matched by key and needs no mark; a review row has a binding to settle first. + * + * @param SourcesStatus status The row's status. + * @return Boolean True when the row may be ignored or un-ignored. + */ +private fun ignorable(status: SourcesStatus): Boolean = status == SourcesStatus.Unbound || status == SourcesStatus.Ignored + +/** + * An unbound layer row's one action, as the chip and the context menu both list it: Ignore Layer + * (`sources.ignoreLayer`, so a reload never mints a drawable for it) while the row is plain unbound, + * Stop Ignoring once it is. + * + * @param SourceLayerRef ref The layer. + * @param Boolean ignored Whether the row is ignored now. + * @param org.umamo.ui.action.CommandRegistry commands The registry to dispatch through. + * @return List The item. + */ +@Composable +private fun layerMenuItems(ref: SourceLayerRef, ignored: Boolean, commands: org.umamo.ui.action.CommandRegistry): List = + listOf( + MenuItem.Action( + stringResource(if (ignored) Res.string.sources_layer_menu_unignore else Res.string.sources_layer_menu_ignore), + onSelect = { commands.invoke("sources.ignoreLayer", IgnoreLayerRequest(ref, ignored = !ignored)) }, + ), + ) + +/** + * The row itself, laid out inside whatever wraps it. + * + * @param SourcesRow row The row. + * @param PuppetModel puppet The rig. + * @param Boolean expanded Whether the row's children are shown. + * @param Color background The row's fill for its hover or selection state. + * @param Boolean isDropTarget Whether a release would bind onto this row, which draws the drop ring. + * @param Boolean isDragged Whether the row is the one being dragged. + * @param MutableInteractionSource interaction The row's hover source. + * @param RowCoordinatesHolder boundsHolder The row's coordinates holder. + * @param SourcesDragPayload? payload What a drag from the row carries, or null when it cannot be dragged. + * @param Function onToggle Flips the expand state. + * @param Function onSelect Selects the given targets. + * @param Function onRelink Rebinds tiles to one layer (null unbinds), retiring the tiles the accepted proposal named. + * @param RowDragController dragController The space's drag state. + * @param Function onDropNow Applies the drop on release. + */ +@Composable +private fun SourcesRowBody( + row: SourcesRow, + puppet: PuppetModel, + expanded: Boolean, + background: Color, + isDropTarget: Boolean, + isDragged: Boolean, + interaction: MutableInteractionSource, + boundsHolder: RowCoordinatesHolder, + payload: SourcesDragPayload?, + onToggle: () -> Unit, + onSelect: (List) -> Unit, + onRelink: (List, SourceLayerRef?, List) -> Unit, + dragController: RowDragController, + onDropNow: () -> Unit, +) { + val node = row.node + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val icons = LocalUmamoIcons + val commands = LocalCommands.current + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + Modifier + .fillMaxWidth() + .height(SOURCES_ROW_HEIGHT) + // The dragged row fades whole, fill and ring included, so the alpha layer wraps what follows. + .alpha(if (isDragged) 0.4f else 1f) + .background(background, shape = shapes.small) + .rowDropHighlight(isDropTarget, shapes.small, colors) + .onGloballyPositioned { coordinates -> + boundsHolder.coordinates = coordinates + dragController.reportBounds(node.id, coordinates.boundsInWindow()) + } + .hoverable(interaction) + .focusProperties { canFocus = false } + .clickable(interactionSource = interaction, indication = null) { + val targets = selectionTargetsOf(node, puppet) + if (targets.isEmpty()) { + onToggle() + } else { + onSelect(targets) + } + } + // Long-press to pick a layer or tile row up; a file or drawable row (no payload) never lifts. + .dragRowOnLongPress(dragController, node.id, payload, boundsHolder, onDropNow) + .padding(start = SOURCES_INDENT_PER_DEPTH * row.depth + 4.dp, end = 6.dp), + ) { + Box(modifier = Modifier.width(SOURCES_CHEVRON_WIDTH), contentAlignment = Alignment.Center) { + if (node.children.isNotEmpty()) { + DisclosureChevron( + expanded = expanded, + tint = colors.textMuted, + modifier = Modifier.focusProperties { canFocus = false }.clickable(onClick = onToggle), + ) + } + } + // The status is the icon: its glyph and traffic-light tint say bound / bound by name / unbound and + // present / missing, and the word survives as the glyph's tooltip rather than as row text. + val visual = sourcesRowVisual(node, icons, colors) + val statusLabel = visual.statusLabel?.let { label -> stringResource(label) } ?: "" + Box(modifier = Modifier.width(SOURCES_ICON_WIDTH), contentAlignment = Alignment.Center) { + IconSlot(icon = visual.icon, contentDescription = statusLabel, tint = visual.tint, glyphSize = 14.dp) + } + Spacer(modifier = Modifier.width(4.dp)) + // The label and detail share ONE weighted slot, so the label's unused share is slack inside it and + // the trailing chip lands flush right on every row; a second weighted child in the outer row would + // leave that slack at the row's end instead. + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) { + Text(text = node.label, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + val detail = detailText(node.detail) + if (detail != null) { + Spacer(modifier = Modifier.width(8.dp)) + Text(text = detail, color = colors.textMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + when (val kind = node.kind) { + is SourcesNodeKind.Tile -> { + Spacer(modifier = Modifier.width(6.dp)) + RelinkChip( + tileId = kind.tileId, + puppet = puppet, + onRelink = onRelink, + // Only a tile nothing samples may leave the atlas; a sampled one would strand its drawables. + canDelete = puppet.drawables.none { drawable -> drawable.atlasTileId == kind.tileId }, + onDelete = { commands.invoke("sources.deleteArt", DeleteArtRequest(kind.tileId)) }, + ) + } + is SourcesNodeKind.Layer -> + if (node.status.isReview) { + Spacer(modifier = Modifier.width(6.dp)) + ReviewChip(node = node, ref = kind.ref, puppet = puppet, onRelink = onRelink) + } else if (ignorable(node.status)) { + Spacer(modifier = Modifier.width(6.dp)) + LayerChip(ref = kind.ref, ignored = node.status == SourcesStatus.Ignored, commands = commands) + } + is SourcesNodeKind.Source -> { + Spacer(modifier = Modifier.width(6.dp)) + SourceFileChip(sourceId = kind.sourceId, commands = commands) + } + is SourcesNodeKind.Drawable, SourcesNodeKind.UnboundGroup -> Unit + } + } +} + +/** + * A file row's actions chip: Replace Artwork… and Reload This File, the same two the row's context + * menu offers, drawn as the kit [Menu] so the chip and the context menu are one menu in two places. + * + * @param ArtSourceId sourceId The file. + * @param org.umamo.ui.action.CommandRegistry commands The registry to dispatch through. + */ +@Composable +private fun SourceFileChip(sourceId: ArtSourceId, commands: org.umamo.ui.action.CommandRegistry) { + val icons = LocalUmamoIcons + var open by remember { mutableStateOf(false) } + val items = sourceFileMenuItems(sourceId, commands) + DropdownChip( + expanded = open, + onExpandRequest = { open = true }, + contentDescription = stringResource(Res.string.sources_file_menu), + icon = icons.dots, + style = DropdownChipStyle.Compact, + ) { + Menu(items = items, onDismissRequest = { open = false }, positionProvider = BelowAnchorPositionProvider) + } +} + +/** + * An unbound layer row's actions chip: Ignore Layer, or Stop Ignoring once it is, the same item the + * row's context menu offers, drawn as the kit [Menu] so the chip and the menu are one menu in two places. + * + * @param SourceLayerRef ref The layer. + * @param Boolean ignored Whether the row is ignored now. + * @param org.umamo.ui.action.CommandRegistry commands The registry to dispatch through. + */ +@Composable +private fun LayerChip(ref: SourceLayerRef, ignored: Boolean, commands: org.umamo.ui.action.CommandRegistry) { + val icons = LocalUmamoIcons + var open by remember { mutableStateOf(false) } + val items = layerMenuItems(ref, ignored, commands) + DropdownChip( + expanded = open, + onExpandRequest = { open = true }, + contentDescription = stringResource(Res.string.sources_layer_menu), + icon = icons.dots, + style = DropdownChipStyle.Compact, + ) { + Menu(items = items, onDismissRequest = { open = false }, positionProvider = BelowAnchorPositionProvider) + } +} + +/** + * A review row's chip: the matcher's proposal to accept (the candidate's name and confidence, and + * whether a fresh drawable over the candidate goes with it), a relink by hand through the same list a + * tile row's chip shows, or leave the binding as it is. Accepting is one relink of every tile bound to + * the lost key, so the art is pulled exactly as a manual relink pulls it and the tiles move together as + * one step, naming the tiles the proposal retires; the planner re-checks those for rig work before any + * leaves. A relink by hand names none. + * + * @param SourcesNode node The review row, carrying its suggestion when there is one. + * @param SourceLayerRef ref The lost binding the row stands for. + * @param PuppetModel puppet The rig, for the relink list. + * @param Function onRelink Rebinds the tiles as one step (null unbinds), with the tiles the proposal retires. + */ +@Composable +private fun ReviewChip(node: SourcesNode, ref: SourceLayerRef, puppet: PuppetModel, onRelink: (List, SourceLayerRef?, List) -> Unit) { + val colors = LocalUmamoColors.current + val icons = LocalUmamoIcons + var open by remember { mutableStateOf(false) } + var byHand by remember { mutableStateOf(false) } + var query by remember { mutableStateOf("") } + // The tiles under review are the row's own children: the tree lists them by (file, key), which is + // the binding as the tile carries it, whereas the row's ref re-derives the key's strength and can + // disagree with a reader-minted one (a flat raster's) - an equality on the ref would find nothing. + val boundTiles = remember(node) { node.children.mapNotNull { child -> (child.kind as? SourcesNodeKind.Tile)?.tileId } } + val suggestion = node.suggestion + val relinkAll: (SourceLayerRef?, List) -> Unit = { target, retire -> + if (boundTiles.isNotEmpty()) { + onRelink(boundTiles, target, retire) + } + } + // The proposal page is a kit Menu, like every other menu in the application; picking Relink by + // hand… flips the SAME open chip to the stay-open list panel (the menu row runs its action before + // the root dismiss, so the dismiss sees the flag and keeps the chip open). + val menuItems = + buildList { + if (suggestion != null) { + val acceptLabel = + if (suggestion.retires.isEmpty()) { + stringResource(Res.string.sources_suggestion_accept, suggestion.candidateName, percentOf(suggestion.score)) + } else { + stringResource(Res.string.sources_suggestion_accept_merge, suggestion.candidateName, percentOf(suggestion.score)) + } + add( + MenuItem.Action( + label = acceptLabel, + onSelect = { relinkAll(SourceLayerRef(ref.sourceId, suggestion.candidateKey, stableKey = layerKeyLooksStable(suggestion.candidateKey)), suggestion.retires) }, + ), + ) + } + add(MenuItem.Action(label = stringResource(Res.string.sources_suggestion_relink), onSelect = { byHand = true })) + add(MenuItem.Action(label = stringResource(Res.string.sources_suggestion_leave), onSelect = {})) + } + DropdownChip( + expanded = open, + onExpandRequest = { + open = true + byHand = false + }, + contentDescription = stringResource(Res.string.sources_suggestion_title), + icon = icons.linked, + style = DropdownChipStyle.Compact, + iconTint = colors.signalCaution, + ) { + if (byHand) { + Menu( + items = relinkMenuItems(puppet, ref, query, { updated -> query = updated }, showUnbind = false) { target -> relinkAll(target, emptyList()) }, + onDismissRequest = { + open = false + byHand = false + }, + positionProvider = BelowAnchorPositionProvider, + ) + } else { + Menu( + items = menuItems, + onDismissRequest = { + if (!byHand) { + open = false + } + }, + positionProvider = BelowAnchorPositionProvider, + ) + } + } +} + +/** + * How a row's leading icon reads: the glyph, its tint, and the status word the glyph's tooltip carries. + * + * @property UmamoIcon icon The glyph. + * @property Color tint The glyph's color. + * @property StringResource? statusLabel The row's status as a tooltip, or null for a row with none. + */ +internal class SourcesRowVisual( + val icon: UmamoIcon, + val tint: Color, + val statusLabel: StringResource?, +) + +/** + * The icon a row draws with, carrying the row's status the way a traffic light does: green for a + * layer bound by a stable key, amber for one bound by name (a binding that holds only while the + * layer keeps its name and place), a tile on no page, or a binding whose layer the file lost, red for + * an unbound layer, a missing file, or the unbound-art group, and the muted text color for a layer the + * rigger ignored. The glyph itself already says what the + * row is - a file, a link, a tile, a mesh - and a missing file swaps to the missing-file glyph, so the + * status word is a tooltip, never row text. Pure, so the mapping is testable without a composition. + * + * @param SourcesNode node The row. + * @param UmamoIcons icons The icon set. + * @param UmamoColors colors The palette. + * @return SourcesRowVisual The glyph, tint, and tooltip. + */ +internal fun sourcesRowVisual(node: SourcesNode, icons: UmamoIcons, colors: UmamoColors): SourcesRowVisual = + when (node.kind) { + is SourcesNodeKind.Source -> + when (node.status) { + SourcesStatus.Missing -> SourcesRowVisual(icons.missingFile, colors.signalBad, Res.string.sources_status_missing) + SourcesStatus.Unknown -> SourcesRowVisual(icons.sources, colors.text, Res.string.sources_status_unknown) + else -> SourcesRowVisual(icons.sources, colors.text, Res.string.sources_status_present) + } + is SourcesNodeKind.Layer -> + when (node.status) { + SourcesStatus.Unbound -> SourcesRowVisual(icons.unlinked, colors.signalBad, Res.string.sources_status_unbound) + SourcesStatus.BoundByName -> SourcesRowVisual(icons.linked, colors.signalCaution, Res.string.sources_status_bound_unstable) + // The tile is bound, but to a layer its file no longer lists: linked to nothing, waiting on a decision. + SourcesStatus.NeedsReview -> SourcesRowVisual(icons.unlinked, colors.signalCaution, Res.string.sources_status_needs_review) + // Bound to a layer the file still has but erased: the same wait, with a different reason on the tooltip. + SourcesStatus.Emptied -> SourcesRowVisual(icons.unlinked, colors.signalCaution, Res.string.sources_status_emptied) + // Bound to a key the replacement file does not mint: the same wait again, and the tooltip says so. + SourcesStatus.SourceReplaced -> SourcesRowVisual(icons.unlinked, colors.signalCaution, Res.string.sources_status_replaced) + // Kept out of the rig on purpose: no signal color, since the row is settled rather than waiting. + SourcesStatus.Ignored -> SourcesRowVisual(icons.unlinked, colors.textMuted, Res.string.sources_status_ignored) + else -> SourcesRowVisual(icons.linked, colors.signalGood, Res.string.sources_status_bound) + } + is SourcesNodeKind.Tile -> + if (node.status == SourcesStatus.Unplaced) { + SourcesRowVisual(icons.spaceTexture, colors.signalCaution, Res.string.sources_status_unplaced) + } else { + SourcesRowVisual(icons.spaceTexture, colors.text, null) + } + is SourcesNodeKind.Drawable -> SourcesRowVisual(icons.mesh, colors.outlinerObjectTint, null) + // Every tile under the group is unbound; the one red marker at the heading is the group's status. + SourcesNodeKind.UnboundGroup -> SourcesRowVisual(icons.unlinked, colors.signalBad, Res.string.sources_status_unbound) + } + +/** + * The localized secondary text of a row, or null when it has none. + * + * @param SourcesDetail detail The row's detail. + * @return String? The text. + */ +@Composable +private fun detailText(detail: SourcesDetail): String? = + when (detail) { + is SourcesDetail.Source -> { + val summary = stringResource(Res.string.sources_source_detail, detail.format.uppercase(), detail.layerCount) + if (detail.hasPath) summary else "$summary · ${stringResource(Res.string.sources_source_no_path)}" + } + is SourcesDetail.Layer -> stringResource(Res.string.sources_layer_detail, detail.width, detail.height, detail.left, detail.top) + // One decimal, like the Properties Position rows: a half-pixel origin (an odd canvas) is real. + is SourcesDetail.LayerOnAxes -> + stringResource(Res.string.sources_layer_detail_axes, detail.width, detail.height, formatDecimals(detail.x, 1), formatDecimals(detail.z, 1)) + is SourcesDetail.TilePage -> stringResource(Res.string.sources_tile_page, detail.pageNumber) + SourcesDetail.None -> null + } + +/** + * One artwork file's rows in the relink list: the file as a heading, the layers beneath it. + * + * @property ArtSource source The file. + * @property List layers The layers to list under it, in inventory order. + */ +internal class RelinkGroup( + val source: ArtSource, + val layers: List, +) + +/** + * The relink list for [query]: every file with every layer when the query is blank; otherwise a layer + * survives when its name matches, a whole file survives when the FILE name matches, and a file with + * nothing left under it is dropped. Grouped by file so the file name is read once as a heading and + * a long one can never push the layer names out of a row. + * + * @param List sources The document's artwork files. + * @param String query The search text, matched case-insensitively after trimming. + * @return List The files and their surviving layers, in document order. + */ +internal fun relinkGroups(sources: List, query: String): List { + val trimmed = query.trim() + return sources.mapNotNull { source -> + // A row the file lost is kept for the review, never offered as a target; a layer erased to nothing + // has no art to give; an ignored layer is kept out of the rig until its row says otherwise. + val present = source.layers.filter { layer -> layer.present && !layer.empty && !layer.ignored } + val layers = + if (trimmed.isEmpty() || source.name.contains(trimmed, ignoreCase = true)) { + present + } else { + present.filter { layer -> layer.name.contains(trimmed, ignoreCase = true) } + } + if (layers.isEmpty()) null else RelinkGroup(source, layers) + } +} + +/** + * A tile row's relink chip: a searchable menu of every listed file's layers, grouped under the file, + * plus Unbind while the tile is bound. Picking closes the menu and rebinds as one undo step. + * + * @param AtlasTileId tileId The tile the chip rebinds. + * @param PuppetModel puppet The rig, for the candidates and the current binding. + * @param Function onRelink Rebinds tiles to one layer (null unbinds); a chip relink retires nothing. + */ +@Composable +private fun RelinkChip( + tileId: AtlasTileId, + puppet: PuppetModel, + onRelink: (List, SourceLayerRef?, List) -> Unit, + canDelete: Boolean, + onDelete: () -> Unit, +) { + val icons = LocalUmamoIcons + var open by remember { mutableStateOf(false) } + var query by remember { mutableStateOf("") } + val current = puppet.atlas.tileById[tileId]?.source + DropdownChip( + expanded = open, + onExpandRequest = { open = true }, + contentDescription = stringResource(Res.string.sources_relink_title), + icon = if (current != null) icons.linked else icons.unlinked, + // The row is 22.dp; the Header face would overflow it. + style = DropdownChipStyle.Compact, + ) { + Menu( + items = + relinkMenuItems(puppet, current, query, { updated -> query = updated }, showUnbind = current != null, onDelete = onDelete.takeIf { canDelete }) { target -> + onRelink(listOf(tileId), target, emptyList()) + }, + onDismissRequest = { open = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} + +/** + * The searchable relink menu: every listed file's present layers under the file's name, with the + * search box on top and Unbind leading when asked - the tile chip's menu and the review chip's by-hand + * page, as one kit [Menu] like every other menu. The current binding reads dimmed and does nothing; + * a query that matches nothing leaves one dimmed line saying so. + * + * @param PuppetModel puppet The rig, for the candidates and the strength of a key some tile already binds. + * @param SourceLayerRef? current The binding the picker starts from, shown dimmed, or null. + * @param String query The search text. + * @param Function onQueryChange Takes the edited search text. + * @param Boolean showUnbind Whether the Unbind row leads the list. + * @param Function? onDelete Removes the tile from the atlas, offered as a Delete Art row when + * non-null (a tile no drawable samples); null hides the row. + * @param Function onPick Takes the chosen binding, or null for Unbind; the menu dismisses itself. + * @return List The menu, search box first. + */ +@Composable +private fun relinkMenuItems( + puppet: PuppetModel, + current: SourceLayerRef?, + query: String, + onQueryChange: (String) -> Unit, + showUnbind: Boolean, + onDelete: (() -> Unit)? = null, + onPick: (SourceLayerRef?) -> Unit, +): List { + val groups = remember(puppet.sources, query) { relinkGroups(puppet.sources, query) } + val unbindLabel = stringResource(Res.string.sources_relink_clear) + val deleteLabel = stringResource(Res.string.sources_relink_delete) + val noMatchesLabel = stringResource(Res.string.sources_relink_no_matches) + return buildList { + add(MenuItem.Search(value = query, onValueChange = onQueryChange, width = RELINK_PANEL_WIDTH)) + if (showUnbind) { + add(MenuItem.Action(label = unbindLabel, onSelect = { onPick(null) })) + } + if (onDelete != null) { + add(MenuItem.Action(label = deleteLabel, onSelect = onDelete)) + } + if (showUnbind || onDelete != null) { + add(MenuItem.Separator) + } + if (groups.isEmpty()) { + add(MenuItem.Action(label = noMatchesLabel, onSelect = {}, enabled = false)) + } + for (group in groups) { + val source = group.source + add(MenuItem.Heading(source.name)) + for (layer in group.layers) { + val key = layer.key + val bound = current?.sourceId == source.id && current.layerKey == key + add( + MenuItem.Action( + label = layer.name, + enabled = !bound, + onSelect = { + // A layer some tile already binds says how strong its key is; otherwise the key's shape does. + val stable = + puppet.atlas.tiles + .mapNotNull { tile -> tile.source } + .firstOrNull { ref -> ref.sourceId == source.id && ref.layerKey == key } + ?.stableKey + onPick(SourceLayerRef(source.id, key, stableKey = stable ?: layerKeyLooksStable(key))) + }, + ), + ) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesTree.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesTree.kt new file mode 100644 index 0000000..199d833 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesTree.kt @@ -0,0 +1,427 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.reimport.LayerMatch +import org.umamo.reimport.tileCarriesNoRigWork +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.runtime.model.drawableIdsByAtlasTile +import org.umamo.runtime.model.originRelativeX +import org.umamo.runtime.model.originRelativeZ + +/* + * The Sources table as a tree: artwork file -> its layers (the inventory as of the last read) -> the + * tiles bound to each layer -> the drawables over each tile, plus a trailing group for art bound to + * no layer. A pure function over the model so it unit-tests without Compose; the space renders it. + */ + +/** Whether an artwork file is still where the document last read it. */ +enum class SourcePresence { + Present, + Missing, + Unknown, +} + +/** + * The kinds of row the Sources space can show or hide, each toggled on its own: the table shows the + * rows of every enabled kind, with their descendants and the ancestors that give them context. With + * every kind enabled nothing is hidden at all. + */ +enum class SourcesFilter { + /** Layers some tile is bound to, by a stable key or by name. */ + Bound, + + /** Layers no tile is bound to (the ignored ones among them), and tiles bound to no layer. */ + Unbound, + + /** Artwork files that are no longer where the document read them, with everything under them. */ + Missing, + + /** Bindings a reload could not resolve: tiles bound to a layer their file no longer lists, has erased to nothing, or a replacement file lacks. */ + NeedsReview, +} + +/** The status a row shows at its right edge. */ +enum class SourcesStatus { + Present, + Missing, + Unknown, + + /** A layer some tile is bound to through a format-minted key. */ + Bound, + + /** A layer some tile is bound to through a name-and-order key, which only holds while the layer keeps its name and place. */ + BoundByName, + + /** A layer no tile is bound to, or a tile bound to no layer. */ + Unbound, + + /** A tile that is in the document but on no page. */ + Unplaced, + + /** A binding to a layer its file no longer lists: the tile keeps its art until a person decides. */ + NeedsReview, + + /** A binding to a layer the file still has but erased to nothing: the tile keeps its art until a person decides. */ + Emptied, + + /** A binding to a layer the replacement file has no key for (Replace Artwork repointed the record): the same wait, with its own reason. */ + SourceReplaced, + + /** A present layer no tile binds that the rigger keeps out of the rig: a reload never mints it. */ + Ignored, + + /** A row with no status of its own. */ + None, + ; + + /** Whether the row stands for a binding waiting on a person: a layer lost, erased, or lost to a replacement. */ + val isReview: Boolean + get() = this == NeedsReview || this == Emptied || this == SourceReplaced +} + +/** What a row stands for, and the identity a click or a drop acts on. */ +sealed interface SourcesNodeKind { + /** An artwork file the document lists. */ + data class Source(val sourceId: ArtSourceId) : SourcesNodeKind + + /** One layer of a file, as the binding a tile would carry to it. */ + data class Layer(val ref: SourceLayerRef) : SourcesNodeKind + + /** One piece of art in the document's atlas. */ + data class Tile(val tileId: AtlasTileId) : SourcesNodeKind + + /** A drawable sampling a tile. */ + data class Drawable(val drawableId: DrawableId) : SourcesNodeKind + + /** The synthetic group holding every tile bound to no layer. */ + data object UnboundGroup : SourcesNodeKind +} + +/** The secondary text a row shows after its label, as data so the space localizes it. */ +sealed interface SourcesDetail { + /** A file's format and inventory size, and whether a path is recorded. */ + data class Source(val format: String, val layerCount: Int, val hasPath: Boolean) : SourcesDetail + + /** + * A layer's size and position at the last read, in the FILE's own canvas (the row's document position + * with the source's offset taken back out: x subtracted, z - which is up - added), so the numbers match + * what the art program shows. The one absolute position the rigger reads that does not start from the + * world axes, on purpose: the default, since it is the artist's own frame. + */ + data class Layer(val width: Int, val height: Int, val left: Int, val top: Int) : SourcesDetail + + /** + * A layer's size and the position of its top-left corner measured from the world axes, x right and z up - + * [Layer]'s alternative under the `import.layerPositionsFromWorldAxes` setting, for a rigger who places art + * by the rig's coordinates rather than the art program's. + */ + data class LayerOnAxes(val width: Int, val height: Int, val x: Float, val z: Float) : SourcesDetail + + /** The 1-based page a placed tile sits on. */ + data class TilePage(val pageNumber: Int) : SourcesDetail + + /** No secondary text. */ + data object None : SourcesDetail +} + +/** + * What the document proposes for a binding its file no longer resolves: the layer it would move to, + * how sure the matcher is, and the tiles that go with the move. + * + * @property String candidateKey The proposed layer's key. + * @property String candidateName The proposed layer's name, for the chip. + * @property Float score The confidence, 0..1. + * @property List retires The tiles bound to the proposed layer that accepting retires + * with their drawables - a fresh, untouched drawable a reload minted for the layer - so the chip can + * say so; empty when the layer is unbound. + */ +data class LayerSuggestion( + val candidateKey: String, + val candidateName: String, + val score: Float, + val retires: List = emptyList(), +) + +/** + * One row of the Sources tree. + * + * @property String id A stable, unique key for expand state and drop hit-testing. + * @property String label The display text (a document name, never localized chrome, except the unbound group's). + * @property SourcesDetail detail The secondary text. + * @property SourcesNodeKind kind What the row stands for. + * @property SourcesStatus status The status chip. + * @property List children The child rows, in display order. + * @property LayerSuggestion? suggestion The proposed relink on a row that needs review, or null. + */ +data class SourcesNode( + val id: String, + val label: String, + val detail: SourcesDetail, + val kind: SourcesNodeKind, + val status: SourcesStatus, + val children: List, + val suggestion: LayerSuggestion? = null, +) + +/** One visible row after flattening: the node and its depth. */ +data class SourcesRow(val node: SourcesNode, val depth: Int) + +/** The id of the synthetic unbound-art group row. */ +const val SOURCES_UNBOUND_GROUP_ID: String = "unbound" + +/** + * Builds the Sources tree from a puppet: one node per artwork file in document order, each holding + * its inventory layers in the file's order with the tiles bound to each - a layer the file lost but a + * tile still binds reads as needing review, named and sized as the inventory last saw it, with the + * proposed relink when there is one and its own status when a replacement lost it; an unbound layer + * the rigger ignored reads as ignored - then any tile bound to a key the inventory never listed, the + * drawables over each tile, and last the unbound group when any tile has no binding. + * + * @param PuppetModel puppet The rig to walk. + * @param Function presenceOf Whether each file is still on disk. + * @param String unboundGroupLabel The localized label of the unbound-art group. + * @param Boolean layerPositionsFromWorldAxes Whether layer rows read their position from the world axes + * ([SourcesDetail.LayerOnAxes]) instead of the file's own top-left corner ([SourcesDetail.Layer]). + * @param Function suggestionsFor The proposals for a lost binding by file and key, best first + * (the pixel-scored one an operation published, then the one the inventory alone ranks); the row + * takes the first that still holds - one naming a layer the file no longer has, or a layer bound to a + * tile with rig work over it, is passed over, so a stale published proposal never hides a live one + * behind it; a layer bound only to fresh, untouched drawables stands, and the proposal names the + * tiles accepting it retires. + * @return List The top-level rows. + */ +fun buildSourcesTree( + puppet: PuppetModel, + presenceOf: (ArtSource) -> SourcePresence, + unboundGroupLabel: String, + layerPositionsFromWorldAxes: Boolean = false, + suggestionsFor: (ArtSourceId, String) -> List = { _, _ -> emptyList() }, +): List { + val drawableIdsByTile = puppet.drawableIdsByAtlasTile() + val drawableNameById = puppet.drawables.associate { drawable -> drawable.id to drawable.name } + val tilesByBinding = puppet.atlas.tiles.filter { tile -> tile.source != null }.groupBy { tile -> tile.source!!.sourceId to tile.source!!.layerKey } + + fun tileNode(tileId: AtlasTileId): SourcesNode { + val tile = puppet.atlas.tileById.getValue(tileId) + val placement = tile.placement + return SourcesNode( + id = "tile:${tile.id.raw}", + label = tile.name, + detail = if (placement != null) SourcesDetail.TilePage(placement.pageIndex + 1) else SourcesDetail.None, + kind = SourcesNodeKind.Tile(tile.id), + status = if (placement == null) SourcesStatus.Unplaced else SourcesStatus.None, + children = + drawableIdsByTile[tile.id].orEmpty().map { drawableId -> + SourcesNode( + id = "drawable:${drawableId.raw}", + label = drawableNameById[drawableId] ?: drawableId.raw, + detail = SourcesDetail.None, + kind = SourcesNodeKind.Drawable(drawableId), + status = SourcesStatus.None, + children = emptyList(), + ) + }, + ) + } + + fun layerNode( + source: ArtSource, + key: String, + label: String, + detail: SourcesDetail, + listed: Boolean = true, + emptied: Boolean = false, + replaced: Boolean = false, + ignored: Boolean = false, + ): SourcesNode { + val sourceId = source.id + val bound = tilesByBinding[sourceId to key].orEmpty() + val stable = bound.any { tile -> tile.source?.stableKey == true } + val status = + when { + !listed && replaced -> SourcesStatus.SourceReplaced + !listed -> SourcesStatus.NeedsReview + // The ignore mark means nothing for a bound layer, so a bound row reads bound whatever it says. + bound.isEmpty() && ignored -> SourcesStatus.Ignored + bound.isEmpty() -> SourcesStatus.Unbound + emptied -> SourcesStatus.Emptied + stable -> SourcesStatus.Bound + else -> SourcesStatus.BoundByName + } + val suggestion = + if (status.isReview) { + suggestionsFor(sourceId, key).firstNotNullOfOrNull { match -> + val candidate = source.layers.firstOrNull { layer -> layer.key == match.key && layer.present && !layer.empty } + val boundToCandidate = tilesByBinding[sourceId to match.key].orEmpty() + when { + candidate == null -> null + boundToCandidate.any { tile -> !puppet.tileCarriesNoRigWork(tile.id, candidate) } -> null + else -> LayerSuggestion(match.key, candidate.name, match.score, boundToCandidate.map { tile -> tile.id }) + } + } + } else { + null + } + return SourcesNode( + id = "layer:${sourceId.raw}/$key", + label = label, + detail = detail, + kind = SourcesNodeKind.Layer(SourceLayerRef(sourceId, key, stableKey = stable || layerKeyLooksStable(key))), + status = status, + children = bound.map { tile -> tileNode(tile.id) }, + suggestion = suggestion, + ) + } + + val sourceNodes = + puppet.sources.map { source -> + val inventoryKeys = source.layers.mapTo(HashSet()) { layer -> layer.key } + // A reader mints one key per layer, so a repeated key can only come from a foreign or broken + // file. The guard keeps every row id unique (the list keys its rows on them) and lets the first + // row own the binding, so no tile is listed twice. + val rowCountByKey = HashMap() + val inventoryRows = + source.layers.mapNotNull { layer -> + // A row the file lost is kept only while a tile binds it - its whole purpose is the + // review of those tiles. Once the last one is unbound or relinked away the row would + // review nothing, so it leaves the table ahead of the refresh that prunes it. + if (!layer.present && !tilesByBinding.containsKey(source.id to layer.key)) { + return@mapNotNull null + } + val detail = + if (layerPositionsFromWorldAxes) { + // The inventory sits on the document canvas (canvas x, y down), and world z is the + // negated canvas y, so the corner converts through the origin like any position. + SourcesDetail.LayerOnAxes(layer.width, layer.height, puppet.originRelativeX(layer.left.toFloat()), puppet.originRelativeZ(-layer.top.toFloat())) + } else { + SourcesDetail.Layer(layer.width, layer.height, layer.left - source.offsetX, layer.top + source.offsetZ) + } + val node = + layerNode( + source, + layer.key, + layer.name, + detail, + listed = layer.present, + emptied = layer.empty, + replaced = layer.replaced, + ignored = layer.ignored, + ) + val ordinal = (rowCountByKey[layer.key] ?: 0) + 1 + rowCountByKey[layer.key] = ordinal + if (ordinal == 1) node else node.copy(id = "${node.id}~$ordinal", status = SourcesStatus.Unbound, children = emptyList(), suggestion = null) + } + // Tiles bound to this file under a key its inventory never listed (a CMO3 whose walk found no such + // layer, or a document from before the inventory kept lost rows): shown so the binding is never invisible. + val strayRows = + tilesByBinding.keys + .filter { (sourceId, key) -> sourceId == source.id && key !in inventoryKeys } + .sortedBy { (_, key) -> key } + .map { (_, key) -> layerNode(source, key, key.removePrefix("name:"), SourcesDetail.None, listed = false) } + SourcesNode( + id = "source:${source.id.raw}", + label = source.name, + detail = SourcesDetail.Source(source.format, source.layers.size, hasPath = source.path != null), + kind = SourcesNodeKind.Source(source.id), + status = + when (presenceOf(source)) { + SourcePresence.Present -> SourcesStatus.Present + SourcePresence.Missing -> SourcesStatus.Missing + SourcePresence.Unknown -> SourcesStatus.Unknown + }, + children = inventoryRows + strayRows, + ) + } + val unboundTiles = puppet.atlas.tiles.filter { tile -> tile.source == null } + if (unboundTiles.isEmpty()) { + return sourceNodes + } + return sourceNodes + + SourcesNode( + id = SOURCES_UNBOUND_GROUP_ID, + label = unboundGroupLabel, + detail = SourcesDetail.None, + kind = SourcesNodeKind.UnboundGroup, + status = SourcesStatus.None, + children = unboundTiles.map { tile -> tileNode(tile.id) }, + ) +} + +/** + * Whether a layer key reads as format-minted: the PSD name-and-order fallback (`name:` or a `#` order + * suffix) is the one weak shape the readers produce; everything else (a lyid, a CLIP or Krita uuid) + * survives a rename. Used only to type a relink to a layer no tile was bound to before - a bound + * layer's own ref says what it is. + * + * @param String key The reader's layer key. + * @return Boolean True when the key looks stable. + */ +fun layerKeyLooksStable(key: String): Boolean = !key.startsWith("name:") && !key.contains('#') + +/** + * Prunes the tree to [filters] and [query]: a row survives when it is of an enabled kind (or sits + * under one that is) and its label matches the query, or when any descendant survives. Ancestors + * of a surviving row are kept for context, exactly as the outliner's search does. With every kind + * enabled only the query prunes, so a file with no layers still lists; with none enabled nothing does. + * + * @param List nodes The top-level rows. + * @param String query The name search; blank matches everything. + * @param Set filters The kinds of row to show. + * @return List The surviving rows. + */ +fun filterSourcesTree(nodes: List, query: String, filters: Set): List { + val trimmed = query.trim() + val unfiltered = filters.size == SourcesFilter.entries.size + + fun matchesFilter(node: SourcesNode): Boolean = + unfiltered || + filters.any { filter -> + when (filter) { + SourcesFilter.Bound -> node.status == SourcesStatus.Bound || node.status == SourcesStatus.BoundByName + SourcesFilter.Unbound -> node.status == SourcesStatus.Unbound || node.status == SourcesStatus.Ignored || node.kind == SourcesNodeKind.UnboundGroup + SourcesFilter.Missing -> node.kind is SourcesNodeKind.Source && node.status == SourcesStatus.Missing + SourcesFilter.NeedsReview -> node.status.isReview + } + } + + fun prune(node: SourcesNode, satisfiedAbove: Boolean): SourcesNode? { + val satisfied = satisfiedAbove || matchesFilter(node) + val children = node.children.mapNotNull { child -> prune(child, satisfied) } + val labelMatches = trimmed.isEmpty() || node.label.contains(trimmed, ignoreCase = true) + return when { + children.isNotEmpty() -> node.copy(children = children) + satisfied && labelMatches -> node + else -> null + } + } + return nodes.mapNotNull { node -> prune(node, satisfiedAbove = false) } +} + +/** + * Flattens the tree into the visible rows: a node's children follow it when [isOpen] says its row + * is expanded. + * + * @param List nodes The top-level rows. + * @param Function isOpen Whether the row with the given id is expanded. + * @return List The rows top to bottom, each with its depth. + */ +fun flattenSources(nodes: List, isOpen: (String) -> Boolean): List { + val rows = ArrayList() + + fun visit(node: SourcesNode, depth: Int) { + rows.add(SourcesRow(node, depth)) + if (node.children.isNotEmpty() && isOpen(node.id)) { + for (child in node.children) { + visit(child, depth + 1) + } + } + } + for (node in nodes) { + visit(node, 0) + } + return rows +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesViewState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesViewState.kt new file mode 100644 index 0000000..85f8804 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/SourcesViewState.kt @@ -0,0 +1,106 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.foldDeviationsOf +import org.umamo.ui.workspace.restoreFoldStates +import org.umamo.ui.workspace.stringArrayOrNull +import org.umamo.ui.workspace.stringListOf + +/** The AreaScope.spaceState key the Sources space parks its view state under, and its member in an area block (UMA §7.3). */ +internal const val SOURCES_VIEW_STATE_KEY = "sources" + +/** + * The Sources space's search, filter, open-row, and refresh state, shared between its area-header controls and + * its body (sibling subtrees, so it lives on the hosting AreaScope via spaceState). It lives as long as the open + * document does, like the outliner's, and a saved document carries its filters and open rows (UMA §7.3). + */ +internal class SourcesViewState : PersistentSpaceState { + /** The name-search query; blank shows the whole table. */ + var query by mutableStateOf("") + + /** Each row's open state by node id; an absent id follows [sourcesOpensByDefault]. */ + val expanded = mutableStateMapOf() + + /** The kinds of row the table shows, each toggled on its own; every kind by default. */ + var filters by mutableStateOf(SourcesFilter.entries.toSet()) + + /** Whether every kind is shown, so the filter chip reads as unfiltered. */ + val isUnfiltered: Boolean get() = filters.size == SourcesFilter.entries.size + + /** + * Shows or hides one kind of row. + * + * @param SourcesFilter filter The kind. + * @param Boolean shown Whether to show it. + */ + fun setShown(filter: SourcesFilter, shown: Boolean) { + filters = if (shown) filters + filter else filters - filter + } + + /** Bumped by the header's Refresh, so the file-presence probe runs again over every source. */ + var refreshSerial by mutableStateOf(0) + + /** + * Whether the row [nodeId] is open. + * + * @param String nodeId The Sources node id. + * @return Boolean True when open. + */ + fun isOpen(nodeId: String): Boolean = expanded[nodeId] ?: sourcesOpensByDefault(nodeId) + + /** + * The Sources space's member of its area block. + * + * @return JsonObject The member, every known key named. + */ + override fun toJson(): JsonObject { + val (opened, closed) = foldDeviationsOf(expanded, ::sourcesOpensByDefault) + return buildJsonObject { + put("expanded", opened) + put("collapsed", closed) + // UMA §7.3: `hidden` names the row kinds filtered out. + put("hidden", stringArrayOrNull(SourcesFilter.entries.filter { filter -> filter !in filters }.map(::sourcesFilterWireName))) + } + } + + /** + * Takes the Sources state a document was saved with. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + restoreFoldStates(expanded, tree, "expanded", "collapsed") + val hidden = stringListOf(tree, "hidden").orEmpty() + filters = SourcesFilter.entries.filter { filter -> sourcesFilterWireName(filter) !in hidden }.toSet() + } +} + +/** + * Whether a Sources row is open when nothing is recorded for it: files and the unbound group are, layers and + * tiles are not. + * + * @param String nodeId The Sources node id. + * @return Boolean True when open by default. + */ +internal fun sourcesOpensByDefault(nodeId: String): Boolean = nodeId.startsWith("source:") || nodeId == SOURCES_UNBOUND_GROUP_ID + +/** + * A row-kind filter's name in the editor entry. + * + * @param SourcesFilter filter The filter. + * @return String The wire name. + */ +internal fun sourcesFilterWireName(filter: SourcesFilter): String = + // UMA §7.3: sources `hidden`. + when (filter) { + SourcesFilter.Bound -> "bound" + SourcesFilter.Unbound -> "unbound" + SourcesFilter.Missing -> "missing" + SourcesFilter.NeedsReview -> "needsReview" + } \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorHeaderControls.kt new file mode 100644 index 0000000..3559364 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorHeaderControls.kt @@ -0,0 +1,152 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalPuppetTextures +import org.umamo.ui.resources.* +import org.umamo.ui.viewport.atlasPageIndexFor +import org.umamo.ui.workspace.AreaScope + +/** + * The UV editor's space-specific header strip (mounted via SpaceDescriptor.headerContent): the + * texture selector naming what the space shows (follow the selection, a pinned atlas page, or the + * source-layer view) and the layer picker that finds a drawable by its artwork, then the vertex / + * edge / face select-mode buttons, the transform pivot dropdown, and the proportional-editing + * controls - the shared EditHeaderControls.kt composables the 2D viewport's header also mounts, so + * the two surfaces stay one behavior. The shared controls drive the SHARED session state (the + * selection and its select mode are one, Blender's UV sync selection): switching to face mode here + * switches the viewport too, by design. The texture selector instead reads and writes the area's own + * UvEditorViewState, so two UV editors pin independently. Each control gates itself, and one that + * renders nothing measures zero and costs the strip nothing. + * + * @param AreaScope scope The hosting area's scope carrying the shared view state. + */ +internal fun OverflowRowScope.uvEditorHeaderControls(scope: AreaScope) { + val viewState = scope.spaceState(UV_EDITOR_VIEW_STATE_KEY) { UvEditorViewState() } + item("textureSelector") { + // The vanish gate: without a document there are no pages to choose, and the space body is a + // placeholder anyway - an item that renders nothing measures zero. + if (LocalPuppet.current != null) { + UvTextureSelectorDropdown(viewState) + } + } + item("layerPicker") { + // Only worth offering when the document retains artwork to search. + if (LocalPuppet.current?.atlas?.tiles?.isNotEmpty() == true) { + UvLayerPickerChip() + } + } + item("selectMode") { MeshSelectModeButtons() } + item("pivot") { PivotModeDropdown() } + item("proportional") { ProportionalEditControls() } +} + +/** + * The texture selector: a label chip naming what the space shows, opening a menu of Follow Selection, + * the source-layer row when this document retains artwork, and one row per atlas page (number, texel + * dimensions, meshed-drawable count - the page inventory). Choosing a row mutates the area's + * [UvEditorViewState] directly - a per-area view choice, not a session operation, so no registry + * dispatch (the uv.page.* palette commands are the separate, hovered-area-routed path onto the same + * state). + * + * The chip face labels the EFFECTIVE selection: a pin the current textures cannot satisfy, or a layer + * view a document with no retained artwork cannot serve, reads as Follow Selection - matching what the + * body resolves - without clearing what is stored. + * + * @param UvEditorViewState viewState The area's shared texture-selection state. + */ +@Composable +private fun UvTextureSelectorDropdown(viewState: UvEditorViewState) { + val model = LocalPuppet.current ?: return + val textures = LocalPuppetTextures.current + val atlases = textures?.atlases.orEmpty() + val hasSourceArt = model.atlas.tiles.isNotEmpty() + val storedSelection = viewState.textureSelection + // The face names what the body actually resolves: a pin the current textures cannot satisfy, or a + // layer view this document has no artwork for, both fall back to following the selection. + val effectiveSelection = + when { + storedSelection is UvTextureSelection.PinnedPage && storedSelection.pageIndex in atlases.indices -> storedSelection + storedSelection is UvTextureSelection.SourceLayer && hasSourceArt -> storedSelection + else -> UvTextureSelection.FollowSelection + } + val currentLabel = + when (effectiveSelection) { + is UvTextureSelection.PinnedPage -> stringResource(Res.string.uv_texture_selector_page, effectiveSelection.pageIndex + 1) + UvTextureSelection.SourceLayer -> stringResource(Res.string.uv_texture_selector_layer) + UvTextureSelection.FollowSelection -> stringResource(Res.string.uv_texture_selector_follow) + } + // The inventory rows' meshed-drawable counts. Each drawable resolves its page through + // atlasPageIndexFor (the textureSourceId indirection); inverting the raw-id atlas map instead + // would miss session-created duplicates sharing a source. + val meshedCountByPage = + remember(model, textures) { + val counts = IntArray(atlases.size) + if (textures != null) { + for (drawable in model.drawables) { + if (drawable.mesh != null) { + val pageIndex = atlasPageIndexFor(drawable, textures) + if (pageIndex != null && pageIndex in counts.indices) { + counts[pageIndex] = counts[pageIndex] + 1 + } + } + } + } + counts + } + var expanded by remember { mutableStateOf(false) } + // Follow Selection first, then the source-layer row when there is artwork behind it, then one row + // per page; with neither the menu is the Follow row alone. The menu's own dismiss closes the popup, + // so onSelect need not toggle `expanded`. + val followRow = + MenuItem.Action( + label = stringResource(Res.string.uv_texture_selector_follow), + onSelect = { viewState.textureSelection = UvTextureSelection.FollowSelection }, + ) + val pageRows = + atlases.mapIndexed { pageIndex, page -> + MenuItem.Action( + label = + stringResource( + Res.string.uv_texture_selector_page_row, + pageIndex + 1, + page.width, + page.height, + meshedCountByPage[pageIndex], + ), + onSelect = { viewState.textureSelection = UvTextureSelection.PinnedPage(pageIndex) }, + ) + } + // Offered only when the document retains source artwork; a MOC3 origin has none. + val layerRow = + if (hasSourceArt) { + MenuItem.Action( + label = stringResource(Res.string.uv_texture_selector_layer), + onSelect = { viewState.textureSelection = UvTextureSelection.SourceLayer }, + ) + } else { + null + } + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = currentLabel, + label = currentLabel, + ) { + Menu( + items = listOfNotNull(followRow, layerRow) + pageRows, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorSpace.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorSpace.kt new file mode 100644 index 0000000..26b60c3 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorSpace.kt @@ -0,0 +1,575 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.PointerInputScope +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.isTertiaryPressed +import androidx.compose.ui.input.pointer.pointerInput +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.atlasBindingForTile +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.ContextMenuArea +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalPuppetRenderSync +import org.umamo.ui.model.LocalPuppetTextures +import org.umamo.ui.model.LocalPuppetViewportService +import org.umamo.ui.model.LocalSourceArtRasters +import org.umamo.ui.model.OverlapPickerPopup +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.menu_uv_mirror_x +import org.umamo.ui.resources.menu_uv_mirror_y +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.viewport.OverlapState +import org.umamo.ui.viewport.PlacementDragStatus +import org.umamo.ui.viewport.PuppetViewportService +import org.umamo.ui.viewport.UvCursorOverlay +import org.umamo.ui.viewport.UvEditGizmoOverlay +import org.umamo.ui.viewport.UvHudOverlay +import org.umamo.ui.viewport.UvObjectGizmoOverlay +import org.umamo.ui.viewport.UvPlacementSurface +import org.umamo.ui.viewport.UvSceneContent +import org.umamo.ui.viewport.UvSpaceCamera +import org.umamo.ui.viewport.ViewportRegionOverlay +import org.umamo.ui.viewport.atlasPageEditFrame +import org.umamo.ui.viewport.overlapStateFrom +import org.umamo.ui.viewport.restFrontRank +import org.umamo.ui.viewport.sourceLayerEditFrame +import org.umamo.ui.viewport.uvIslandPick +import org.umamo.ui.workspace.AreaScope +import org.umamo.ui.workspace.LocalAreaCameraHub + +/** + * The UV editor space: the shown surface - an atlas page, or the source layer the art was authored on - + * drawn under its UV islands, with the session's selections shared 1:1 (Blender's UV sync selection, + * always on - Umamo UVs are strictly per-vertex, so the viewport and the UV editor agree by + * construction). In Edit mode the composed [UvEditGizmoOverlay] owns the interactions: element picking + * and box select over the shared mesh selection, and the modal G / S / R operators over the texture + * coordinates with live GPU preview. In Object mode [UvObjectGizmoOverlay] draws every visible island + * on the shown surface and owns island selection - click, box, and the Alt overlap stack, writing the + * session's object selection, so a selection made here flows out to the viewport and the outliner. + * Middle-drag pans and the wheel zooms in both modes, through this space's own navigation loop. + * + * FULL VIEWPORT-SERVICE PARITY: the underlay is rendered by the SAME offscreen GL engine the 2D viewport + * uses (a per-area UV render scene, whose content is either an atlas page or a source layer's raster), + * blitted here by [UvPageUnderlay]; the UV camera is owned by that service, and the Compose wireframe / + * gizmo overlays lock to the frame camera so they stay glued to the (asynchronously produced) raster + * during pan / zoom. With no service present (Android until the GLES engine lands) the space shows the + * grid placeholder, exactly like the 2D viewport - there is no CPU underlay fallback. + * + * The working space is the display mapping of UvDisplayMapping.kt: texel units with Y up (v = 0 is the + * image's TOP row, so the axis flips - see that file's header). + * + * @param AreaScope scope The hosting area context (its id keys the render registration and gesture latches). + */ +@Composable +internal fun UvEditorSpace(scope: AreaScope) { + val committedModel = LocalPuppet.current + // The document as it looks RIGHT NOW: the uncommitted model while any area drags a modal gesture, + // else the committed one. Read here rather than only in the area that owns the gesture, because a + // second UV editor showing the atlas page has to follow a drag happening over the source artwork + // live, the way the 2D viewport beside it does, rather than wait for the gesture to confirm. + // + // Never session state: the preview carries no undo step and never marks the document dirty, so the + // surfaces that want the document as SAVED keep reading LocalPuppet. + val model = LocalPuppetRenderSync.current?.preview?.value ?: committedModel + val session = LocalEditorSession.current + val textures = LocalPuppetTextures.current + val service = LocalPuppetViewportService.current + + // STRICT PARITY: the UV editor renders its surface through the GL engine, exactly like the 2D viewport. + // With no service (Android until the GLES engine lands) show the grid placeholder - no underlay, no + // editing camera - mirroring Viewport2DBody's null-host branch. + if (model == null || session == null || service == null) { + PlaceholderSpace("") + return + } + val mode by session.mode.collectAsState() + val meshSelection by session.meshSelection.collectAsState() + val objectSelection by session.selection.collectAsState() + + // The area's texture selection, shared with the header's selector through the hosting AreaScope + // (header and body are sibling subtrees - spaceState is their one channel). + val viewState = scope.spaceState(UV_EDITOR_VIEW_STATE_KEY) { UvEditorViewState() } + + // The source-layer view, when the selector asks for one AND this document retains the artwork to + // serve it: the active drawable's own art with its mapping recovered onto it. Null falls the space + // back to its page view, so choosing the mode never blanks the editor and a document with no source + // art (a MOC3 origin) simply keeps showing pages. + val artRasters = LocalSourceArtRasters.current + val layerView = + if (viewState.textureSelection is UvTextureSelection.SourceLayer) { + resolveUvEditorLayer(model, meshSelection, objectSelection) + } else { + null + } + + // The shown page: a pinned page the textures can satisfy wins page-first, else the page follows + // the session's active drawable, falling back to the first meshed drawable so the space is never + // blank; the precedence chain and the untextured 1x1 fallback live in resolveUvEditorPage + // (UvEditorViewState.kt). + val resolvedPage = resolveUvEditorPage(model, meshSelection, objectSelection, textures, viewState.textureSelection) + + // The palette's page-switch requests (uv.page.*): the executing area was resolved at dispatch + // into the payload, so this gate is deterministic. Mode-agnostic on purpose - reviewing pages is + // not an Edit-mode operation. Collected ABOVE the placeholder early-return so a document with + // textures but nothing meshed (placeholder showing) can still pin a page into view. + val liveEffectivePageIndex = rememberUpdatedState(resolvedPage?.pageIndex) + val livePageCount = rememberUpdatedState(textures?.atlases?.size ?: 0) + LaunchedEffect(session, scope.areaId) { + session.uvPageRequests.collect { request -> + if (request.areaId != scope.areaId) { + return@collect + } + viewState.textureSelection = + uvPageSelectionAfter(request.kind, viewState.textureSelection, liveEffectivePageIndex.value, livePageCount.value) + } + } + // The display space both views share: texels of whatever is shown, with the v-flip (UvDisplayMapping). + // One of the two resolutions must have produced a surface or there is nothing to show at all. + val pageIndex = resolvedPage?.pageIndex + val displayWidth = layerView?.width ?: resolvedPage?.pageWidth + val displayHeight = layerView?.height ?: resolvedPage?.pageHeight + if (displayWidth == null || displayHeight == null) { + return + } + + // The meshes drawn over the shown surface and their display-space projection: over a layer, every + // drawable bound to it with its stored coordinates recovered into the layer's frame; over a page, + // the Edit / Object candidate rules and the page filter (shownUvDrawables). Remembered so + // selection churn - which changes styling, never membership - rebuilds nothing here. + val shownDrawables = + remember(model, textures, layerView, pageIndex, mode, meshSelection.drawableIds) { + if (layerView != null) { + shownLayerDrawables(model, mode, meshSelection, layerView.layerKey) + } else { + shownUvDrawables(model, mode, meshSelection, textures, pageIndex) + } + } + // Each shown mapping in the SHOWN surface's own frame - stored coordinates over a page, recovered + // ones over a layer. One derivation feeds both the display projection and the pick's alpha gate, + // so the wireframe and the hit test can never disagree about where a mesh is. + val shownUvs = + remember(shownDrawables, model, layerView) { + shownSurfaceUvs(shownDrawables, model, layerView) + } + val geometries = + remember(shownDrawables, shownUvs, displayWidth, displayHeight) { + uvGizmoGeometries(shownDrawables, shownUvs, displayWidth, displayHeight) + } + val liveGeometries = rememberUpdatedState(geometries) + + // The space an edit here is authored in. Over a page the display texels ARE the stored frame; over + // a layer the drawable's placement stands between them. Every drawable over one layer shares that + // placement, so the frame comes from the LAYER rather than from whichever drawables are currently + // shown - it must not shift when Edit mode narrows the shown set to the session's meshes. One + // conversion therefore covers a whole edit and the shared-pivot transform modes keep meaning + // something. A layer whose mapping will not invert falls back to treating its own texels as the + // frame rather than editing blind. + val editFrame = + remember(layerView, model.atlas, displayWidth, displayHeight) { + val layerBinding = + if (layerView != null) { + model.atlasBindingForTile(AtlasTileId(layerView.layerKey)) + } else { + null + } + val layerFrame = + if (layerView != null && layerBinding != null) { + sourceLayerEditFrame(layerBinding, layerView.width, layerView.height) + } else { + null + } + layerFrame ?: atlasPageEditFrame(displayWidth, displayHeight) + } + + // The Object-mode island pick surface: the model's rest-pose front rank plus the CPU pick adapters + // over the shown islands and the shown image's decoded pixels (UvIslandPickController.kt). The + // image is the atlas page or the source layer's artwork, and the alpha gate follows it - over + // overlapping islands, the one with opaque art under the click on the surface actually being + // looked at wins, and a click where no island is opaque falls back to the mesh itself. + val frontRank = remember(model) { restFrontRank(model) } + val shownImage = + if (layerView != null) { + artRasters?.rasterFor(AtlasTileId(layerView.layerKey)) + } else { + pageIndex?.let { resolvedIndex -> textures?.atlases?.getOrNull(resolvedIndex) } + } + val islandPick = + remember(geometries, frontRank, shownUvs, shownImage) { + uvIslandPick(geometries = geometries, frontRank = frontRank, uvsById = shownUvs, image = shownImage) + } + + // Register this area as a UV scene on the shared GL engine and follow the frame it publishes; the + // content tracks the resolved texture selection via setUvSceneContent, which is also how the area + // switches between a page and a layer WITHOUT re-registering (a second register would take a + // reference-counted hold this area never releases). The camera is owned by the service (pan / zoom / + // fit below drive it), and the frame carries the camera it was rendered at for the overlay glue. The + // service keeps this area's view of each page and layer apart, so following the selection onto another + // one - or picking one - brings back the view it was left with, or fits it the first time. + // + // Resolving the raster here is what triggers its decode, on first sight only - the store caches + // thereafter, including its failures. + val sceneContent = + if (layerView != null) { + UvSceneContent.SourceLayer(layerView.layerKey, shownImage) + } else { + UvSceneContent.AtlasPage(pageIndex) + } + // The extent a fit of this area takes in beside the surface: every shown mesh, so art moved past the + // page edge is framed with the page. Handed over with the content, which is what lets the engine fit a + // surface it switches to against that surface's own meshes. + val islandExtent = remember(geometries) { shownIslandExtent(geometries) } + // Keyed on the service too, like the 2D viewport's registration: a slot remembered across a + // service swap would keep collecting the disposed engine's flows and never register with the live one. + val imageFlow = remember(scope.areaId, service) { service.registerUvScene(scope.areaId, sceneContent, islandExtent) } + // The live service camera feeds the zoom readout: the wheel updates it immediately, where the + // frame's camera (image?.camera) lags the raster by a few frames. + val cameraFlow = remember(scope.areaId, service) { service.cameraFlow(scope.areaId) } + LaunchedEffect(scope.areaId, sceneContent, islandExtent) { service.setUvSceneContent(scope.areaId, sceneContent, islandExtent) } + DisposableEffect(scope.areaId, service) { + onDispose { service.unregister(scope.areaId) } + } + val image by imageFlow.collectAsState() + val liveCamera by cameraFlow.collectAsState() + // The UV editor's proportional influence radius, in display (texel) units. The session's + // radiusWorld is scaled for the puppet canvas and means nothing on a texture surface, so only the + // falloff curve and Connected Only are shared; the radius seeds from the shown surface's size on + // first use and survives across gestures (the circle-select remembered-radius pattern). Owned here, + // by the overlay stack's host, because two sibling overlays need it: UvEditGizmoOverlay's gesture + // machinery seeds and resizes it, UvHudOverlay's status badge reads it. + // + // Kept PER SURFACE, not per area: a radius seeded on an 8192-texel page means something else + // entirely on a 576-texel layer, so carrying one into the other would arrive absurdly large or + // vanishingly small. Each surface seeds its own from what it is actually showing. + val proportionalRadiusDisplay = + remember(scope.areaId, displayWidth, displayHeight, layerView?.layerKey) { mutableStateOf(null) } + + // The overlap-picker popup's host state (the 2D viewport's pattern): the Object overlay's Alt + // pick requests it through overlapStateFrom, the popup mounted in the content stack resolves or + // dismisses it. Area-local, like the anchor it carries. + var overlap by remember(scope.areaId) { mutableStateOf(null) } + + // The placement gesture's page: Object-mode G / S / R over the shown page's placements needs the + // page's texel size and the source art the pages recompose from. Null over a source layer (a + // placement has no page to move on there) and while the document retains no art; the Object + // overlay then drops a latch with its own notice. + val placementSurface = + remember(layerView, pageIndex, displayWidth, displayHeight, artRasters, shownImage) { + if (layerView == null && pageIndex != null && artRasters != null) { + UvPlacementSurface(displayWidth, displayHeight, artRasters, shownImage) + } else { + null + } + } + // The drag's live readout, host-owned because two sibling overlays meet on it: the Object overlay + // writes it per pointer frame and UvHudOverlay's badge reads it. + val placementDragStatus = remember(scope.areaId) { mutableStateOf(null) } + + // Area-death guard: a gesture latched from this area must not outlive it (corner-join, space + // switch, workspace tab switch), or the latch strands with no overlay to drive or confirm it. + // The overlay's own dispose effect resyncs the renderer when a capture was live. Zoom Region + // disarms too - an armed flag naming a dead area would never resolve (the 2D viewport's guard). + DisposableEffect(scope.areaId, session) { + onDispose { + if (session.activeUvOperator.value?.areaId == scope.areaId) { + session.clearUvOperator() + } + if (session.activeSelectTool.value?.areaId == scope.areaId) { + session.clearSelectTool() + } + if (session.zoomRegionArmedArea.value == scope.areaId) { + session.disarmZoomRegion() + } + } + } + + // The view commands' seam: register this area's camera ops for its lifetime, so view.fit / 1:1 / + // zoom / frame-selected target this UV editor when the pointer last touched it. The ops drive the + // SERVICE camera (the same per-area camera the pan / zoom / fit machinery the 2D viewport uses), so the + // zoom steps honor the same viewport.zoomStep settings fed into the service. + val areaCameraHub = LocalAreaCameraHub.current + DisposableEffect(scope.areaId, areaCameraHub, session, service) { + // The UV camera reads the supplier lazily each Frame Selected, so it always frames the current + // shown geometries without re-registering on every mesh change. Object mode narrows to the + // SELECTED islands - the shown list is every visible island on the surface, and framing all of + // them would just frame the surface; an empty selection yields an empty list, keeping Frame + // Selected a no-op then. + val ops = + UvSpaceCamera(service, session, scope.areaId) { + if (session.mode.value == EditorMode.Edit) { + liveGeometries.value + } else { + val selectedIds = + session.selection.value.targets + .mapNotNull { target -> (target as? SelectionTarget.Drawable)?.id } + .toSet() + liveGeometries.value.filter { geometry -> geometry.drawableId in selectedIds } + } + } + areaCameraHub?.register(scope.areaId, ops) + onDispose { areaCameraHub?.unregister(scope.areaId) } + } + + // The UV viewport's own contextual menu: right-click anywhere in the viewport for UV operations. A + // context menu is contextual - this holds ONLY UV ops, not area actions. Nested in the content below, + // it overrides the AreaLeaf area menu within the viewport (the same precedence the outliner's row menu + // has over the area menu); the area context stays on the header. Mirror X / Mirror Y dispatch the + // existing uv.mirror* commands through the registry (never a hardcoded handler); rebuilt on mode change + // (mode is observed above), so the rows enable and disable with Edit / Object mode. + val commands = LocalCommands.current + val mirrorEnabled = mode == EditorMode.Edit + val uvContextItems = + listOf( + MenuItem.Action( + label = stringResource(Res.string.menu_uv_mirror_x), + onSelect = { commands.invoke("uv.mirrorU") }, + enabled = mirrorEnabled, + ), + MenuItem.Action( + label = stringResource(Res.string.menu_uv_mirror_y), + onSelect = { commands.invoke("uv.mirrorV") }, + enabled = mirrorEnabled, + ), + ) + + val uiColors = LocalUmamoColors.current + BoxWithConstraints(modifier = Modifier.fillMaxSize()) { + val widthPx = constraints.maxWidth + val heightPx = constraints.maxHeight + LaunchedEffect(widthPx, heightPx) { + service.resize(scope.areaId, widthPx, heightPx) + } + ContextMenuArea(items = uvContextItems, modifier = Modifier.fillMaxSize()) { + Box( + modifier = + Modifier + .fillMaxSize() + .background(uiColors.panelBackground) + // Cache boundary: promote the UV editor's overlay drawing to its own layer so a sibling + // repaint - the 2D viewport's own pan / zoom, a parameter scrub - composites this cached + // content instead of re-rasterizing the wireframe. Only a real UV change re-records it. + .graphicsLayer() + .clipToBounds() + // Navigation lives on the PARENT box, not the drawing canvas. In Edit mode the gizmo + // overlay is a child on top; as the parent, this loop sees the Main pass after the overlay, + // so pan / zoom work in both modes - the 2D viewport's setup. + .pointerInput(session, scope.areaId) { + uvEditorNavigation(session = session, service = service, areaId = scope.areaId) + }, + ) { + // The underlay: the GL-rendered surface - atlas page or source layer - clipped to its + // on-screen tile with the 1.dp frame around it, or the grid placeholder before the first + // frame (UvPageUnderlay.kt). + UvPageUnderlay( + rendered = image, + pageWidth = displayWidth, + pageHeight = displayHeight, + widthPx = widthPx, + heightPx = heightPx, + ) + // The overlap picker for an ambiguous Alt click over stacked islands (the popup is its + // own window; the anchor stays area-local). + overlap?.let { state -> + OverlapPickerPopup( + anchor = state.anchor, + entries = state.entries, + defaultIndex = state.defaultIndex, + onPick = { pickedId -> + state.pick(pickedId) + overlap = null + }, + onDismiss = { overlap = null }, + ) + } + // The mode-exclusive sibling overlays, each self-gated on the session's mode (the + // viewport pair's convention, so both mount unconditionally): Object mode's island + // selection surface (every island drawn, click / box / Alt-stack picking and + // Shift+RightClick cursor placement over the session's object selection), then Edit + // mode's interaction core (element selection, box select, and the modal G / S / R + // operators with live GPU preview). Both are locked to the frame camera + // (image?.camera) for the same pan / zoom glue as the 2D viewport's overlays; + // unconsumed input falls through to the navigation loop and the context menu. + // + // The SAME pair serves a page and a source layer. What differs between the two views is + // carried entirely by the frame and the pick they are handed - the surface's texel size, + // the conversion back to the stored coordinates, and which image the alpha gate reads - + // so neither overlay knows which surface it is drawing over. + UvObjectGizmoOverlay( + areaId = scope.areaId, + session = session, + geometries = geometries, + islandPick = islandPick, + frame = editFrame, + camera = image?.camera, + widthPx = widthPx, + heightPx = heightPx, + placementSurface = placementSurface, + placementDragStatusState = placementDragStatus, + onOverlapRequest = { position, candidates -> + // The Object-mode Alt pick over a stack: picking a row replaces the object selection. + overlap = + overlapStateFrom(service, position, candidates) { pickedId -> + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(pickedId))) + } + }, + ) + UvEditGizmoOverlay( + areaId = scope.areaId, + session = session, + geometries = geometries, + frame = editFrame, + camera = image?.camera, + widthPx = widthPx, + heightPx = heightPx, + proportionalRadiusDisplayState = proportionalRadiusDisplay, + ) + // Zoom Region (Shift+B): mode-agnostic and self-gated on the armed area, so it composes nothing + // until armed. Mounted above the gizmo overlays so an armed drag is captured over them; on + // release it calls the area-generic service.zoomToRegion for this UV editor area. Takes + // the LIVE camera like the 2D viewport's mount - the overlay reads it only as its + // area-initialized gate, never for projection. + ViewportRegionOverlay( + areaId = scope.areaId, + service = service, + session = session, + camera = liveCamera, + widthPx = widthPx, + heightPx = heightPx, + ) + // The UV cursor marker: a control's texture-space marker (not HUD chrome), present in + // both modes like the viewport's 2D cursor, drawn above the gizmo chrome and below the + // HUD text. Locked to the frame camera for the same pan / zoom glue as the wireframes. + // Present in the layer view too: the cursor is stored in ATLAS coordinates, so it converts + // through the shown surface's frame to be drawn and converts back when placed - one shared + // control seen in whichever space the user is working in, rather than two cursors to keep + // in sync. + UvCursorOverlay( + session = session, + frame = editFrame, + camera = image?.camera, + widthPx = widthPx, + heightPx = heightPx, + ) + // The HUD layer draws topmost, informational chrome only (draw-only, no pointer input, so + // nothing below loses a gesture): the modal-op status badge, the active-mesh info chip, + // and the zoom readout. The chip uses the SAME mode-dependent resolution as the 2D + // viewport - deliberately not this space's first-meshed page fallback - so the two + // surfaces annotate the same mesh and the chip stays absent while nothing is selected. + // Under a pinned page that mesh may live on ANOTHER page: the chip still names it, on + // purpose - it annotates the session's active mesh, not this page's contents. + UvHudOverlay( + areaId = scope.areaId, + session = session, + liveCamera = liveCamera, + proportionalRadiusDisplay = proportionalRadiusDisplay.value, + placementDragStatus = placementDragStatus.value, + ) + } + } + } +} + +/** + * The UV editor's navigation pointer loop: middle-mouse drag pans and the wheel zooms toward the cursor + * (Shift for the coarse step). Pan and zoom drive the SERVICE camera (same as the 2D viewport) and are + * skipped while this area owns a modal UV operator or an armed select tool - the overlay's controller owns + * the pointer then (a wheel scroll resizes the proportional radius, not the zoom) - and while an un-armed + * box drag is live (viewportGestureActive, area-less by design: pointer capture pins the drag's events to + * the dragging overlay, and zooming under a live rubber-band would desync the box from the camera used at + * release) or Zoom Region is armed here (its overlay owns the drag above). The four-term gate is the 2D + * viewport loop's. A gesture latched in ANOTHER area does not block: its events never reach here, so this + * area keeps panning and zooming during it (Blender parity). + * + * This loop stamps nothing about where the pointer is: the hovered surface is stamped by the hosting + * leaf, for every space alike (see stampsHoveredSurface). + * + * @param EditorSession session The session whose latches gate this layer. + * @param PuppetViewportService service The render service whose per-area camera this drives. + * @param String areaId The UV editor area this loop serves. + */ +private suspend fun PointerInputScope.uvEditorNavigation( + session: EditorSession, + service: PuppetViewportService, + areaId: String, +) { + awaitPointerEventScope { + var panAnchor: Offset? = null + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull() ?: continue + if (session.activeUvOperator.value?.areaId == areaId || + session.activeSelectTool.value?.areaId == areaId || + session.viewportGestureActive.value || + session.zoomRegionArmedArea.value == areaId + ) { + continue + } + when (event.type) { + PointerEventType.Scroll -> { + val shiftHeld = event.keyboardModifiers.isShiftPressed + // AWT reroutes Shift+wheel into a horizontal scroll (delta arrives in x with y zero), so + // read the x delta when Shift is held. Sign convention matches y (wheel up = negative). + val scrollSteps = + if (change.scrollDelta.y != 0f) { + change.scrollDelta.y + } else if (shiftHeld) { + change.scrollDelta.x + } else { + 0f + } + if (scrollSteps != 0f) { + // One step per notch (wheel up = negative = zoom in); Shift selects the coarse step. + service.zoomAtCursor( + areaId, + zoomIn = scrollSteps < 0f, + coarse = shiftHeld, + cursorXpx = change.position.x, + cursorYpx = change.position.y, + ) + change.consume() + } + } + + else -> { + if (event.buttons.isTertiaryPressed) { + val anchor = panAnchor + if (anchor != null) { + val delta = change.position - anchor + if (delta != Offset.Zero) { + service.pan(areaId, delta.x, delta.y) + } + } + panAnchor = change.position + change.consume() + } else { + panAnchor = null + } + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorViewState.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorViewState.kt new file mode 100644 index 0000000..d6587dd --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvEditorViewState.kt @@ -0,0 +1,450 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.umamo.edit.EditorMode +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshTopology +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.UvPageKind +import org.umamo.render.ContentBounds +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.atlasBindingFor +import org.umamo.runtime.model.layerUvsFromAtlasUvs +import org.umamo.runtime.model.visibleDrawableIds +import org.umamo.ui.viewport.GizmoMeshGeometry +import org.umamo.ui.viewport.atlasPageIndexFor +import org.umamo.ui.viewport.uvToDisplay +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.intOf +import org.umamo.ui.workspace.stringOf + +/** The AreaScope.spaceState key the UV editor parks its view state under, and its member in an area block (UMA §7.3). */ +internal const val UV_EDITOR_VIEW_STATE_KEY = "uv" + +/** + * What the UV editor area is showing: the auto-follow default, one atlas page pinned regardless of the + * selection, or the active drawable's own source artwork. Sealed so a further surface joins as another + * case rather than by widening the existing ones. + */ +internal sealed class UvTextureSelection { + /** The auto-follow default: the shown page tracks the session's active drawable. */ + data object FollowSelection : UvTextureSelection() + + /** The space keeps showing atlas page [pageIndex] regardless of the selection. */ + data class PinnedPage(val pageIndex: Int) : UvTextureSelection() + + /** + * The space shows the active drawable's own source artwork instead of a packed page - the mapping + * over the art it was authored against. Follow-active like [FollowSelection] and for the same + * reason: which layer to show is a restatement of which drawable is selected, so carrying a layer + * id here would be a second selection to keep in sync with the first. + */ + data object SourceLayer : UvTextureSelection() +} + +/** + * The UV editor's per-area view state, shared between its area-header controls and its body (they + * render as sibling subtrees, so this lives on the hosting AreaScope via spaceState rather than in a + * body-local remember). Two UV editors each get their own instance, and the instance lives as long as the open + * document does; a saved document carries it (UMA §7.3). + * + * A pin can name a page the document does not have - a repack that shrank the atlas, a file saved by another + * version. Resolution treats such a pin as Follow Selection (resolveUvEditorPage) without clearing what is + * stored here, so a later repack that brings the page back finds the pin still set. + */ +internal class UvEditorViewState : PersistentSpaceState { + /** The area's texture selection: follow the session, a pinned atlas page, or the source-layer view. */ + var textureSelection by mutableStateOf(UvTextureSelection.FollowSelection) + + /** + * The UV editor's member of its area block. + * + * @return JsonObject The member, every known key named. + */ + override fun toJson(): JsonObject = + buildJsonObject { + // UMA §7.3: `texture` is "follow" (the default, so absent), "sourceLayer", or { "page": N }. + put( + "texture", + when (val selection = textureSelection) { + UvTextureSelection.FollowSelection -> JsonNull + UvTextureSelection.SourceLayer -> JsonPrimitive("sourceLayer") + is UvTextureSelection.PinnedPage -> buildJsonObject { put("page", JsonPrimitive(selection.pageIndex)) } + }, + ) + } + + /** + * Takes the UV editor state a document was saved with. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + val pinnedPage = (tree["texture"] as? JsonObject)?.let { pin -> intOf(pin["page"]) }?.takeIf { pageIndex -> pageIndex >= 0 } + textureSelection = + when { + pinnedPage != null -> UvTextureSelection.PinnedPage(pinnedPage) + stringOf(tree, "texture") == "sourceLayer" -> UvTextureSelection.SourceLayer + else -> UvTextureSelection.FollowSelection + } + } +} + +/** + * The UV editor's resolved page context: the shown page and its texel dimensions. + * + * @property Int? pageIndex The shown atlas page's index, or null for an untextured drawable or absent textures. + * @property Int pageWidth The page width in texels (1 for the untextured fallback). + * @property Int pageHeight The page height in texels (1 for the untextured fallback). + */ +internal data class UvEditorPage( + val pageIndex: Int?, + val pageWidth: Int, + val pageHeight: Int, +) + +/** + * Resolves which atlas page the UV editor shows. A pinned page the textures can satisfy wins + * outright - page-first, with no meshed-drawable requirement, so an empty page is still reviewable. + * Otherwise (following the selection, or a pin the current document cannot satisfy) the page follows + * the session's active drawable (Edit-mode active mesh first, then the object selection's active + * drawable), falling back to the first meshed drawable so the space is never blank. Null when no + * meshed drawable resolves in follow mode (the space shows its placeholder). + * + * Untextured fallback: a 1x1 "page" turns the display mapping into the flipped unit square, so the + * wireframe still shows (over the grid) for a drawable with no atlas entry. Must equal the + * service's pageContentBounds dimensions so the Compose wireframe and the GL page frame at the same + * camera align. + * + * @param PuppetModel model The session's committed model. + * @param MeshSelection meshSelection The mesh-element selection (its active drawable wins). + * @param Selection objectSelection The object selection (its active drawable is the second choice). + * @param PuppetTextures? textures The decoded atlas pages, or null before textures load. + * @param UvTextureSelection textureSelection The area's texture selection (a valid pin wins the chain). + * @return UvEditorPage? The resolved page context, or null with no meshed drawable to show. + */ +internal fun resolveUvEditorPage( + model: PuppetModel, + meshSelection: MeshSelection, + objectSelection: Selection, + textures: PuppetTextures?, + textureSelection: UvTextureSelection = UvTextureSelection.FollowSelection, +): UvEditorPage? { + if (textureSelection is UvTextureSelection.PinnedPage) { + val pinnedPage = textures?.atlases?.getOrNull(textureSelection.pageIndex) + if (pinnedPage != null) { + return UvEditorPage( + pageIndex = textureSelection.pageIndex, + pageWidth = pinnedPage.width, + pageHeight = pinnedPage.height, + ) + } + } + + // The selection may still name a drawable the model no longer has (the one just deleted): that is + // no selection, and the first meshed drawable stands in, so the space never goes blank over a + // document that has art to show. + val selectedDrawableId = meshSelection.activeDrawableId ?: (objectSelection.active as? SelectionTarget.Drawable)?.id + val activeDrawable = + selectedDrawableId?.let { drawableId -> model.drawables.firstOrNull { drawable -> drawable.id == drawableId } } + ?: model.drawables.firstOrNull { drawable -> drawable.mesh != null } + + if (activeDrawable?.mesh == null) { + return null + } + + val pageIndex = textures?.let { puppetTextures -> atlasPageIndexFor(activeDrawable, puppetTextures) } + val page = if (textures != null && pageIndex != null) textures.atlases.getOrNull(pageIndex) else null + + return UvEditorPage( + pageIndex = pageIndex, + pageWidth = page?.width ?: 1, + pageHeight = page?.height ?: 1, + ) +} + +/** + * The UV editor's resolved source-layer context: which layer the space shows and its pixel size. + * + * @property String layerKey The shown layer's key in the document's source-art store. + * @property Int width The layer image's width in pixels. + * @property Int height The layer image's height in pixels. + */ +internal data class UvEditorLayer( + val layerKey: String, + val width: Int, + val height: Int, +) + +/** + * Resolves which source layer the UV editor shows: the one the active drawable was authored against, + * following the same precedence the page chain uses (Edit-mode active mesh, then the object + * selection's active drawable, then the first meshed drawable). + * + * Null when nothing resolves a layer - an empty atlas, no active drawable, or a drawable with no + * tile of its own. The space falls back to its page view then, so choosing the layer mode never + * blanks the editor. + * + * @param PuppetModel model The session's committed model. + * @param MeshSelection meshSelection The mesh-element selection (its active drawable wins). + * @param Selection objectSelection The object selection (its active drawable is the second choice). + * @return UvEditorLayer? The resolved layer context, or null with no layer to show. + */ +internal fun resolveUvEditorLayer( + model: PuppetModel, + meshSelection: MeshSelection, + objectSelection: Selection, +): UvEditorLayer? { + if (model.atlas.tiles.isEmpty()) { + return null + } + val activeDrawable = activeUvDrawable(model, meshSelection, objectSelection) ?: return null + // The tile the drawable itself names: a session-created duplicate copies the field along with the + // rest of the drawable, so it finds its art natively rather than through its source. + val entry = activeDrawable.atlasTileId?.let { tileId -> model.atlas.tileById[tileId] } ?: return null + if (entry.width <= 0 || entry.height <= 0) { + return null + } + return UvEditorLayer(entry.id.raw, entry.width, entry.height) +} + +/** + * The drawable the UV editor's view follows: the Edit-mode active mesh, else the object selection's + * active drawable, else the first meshed drawable so the space is never blank. + * + * @param PuppetModel model The session's committed model. + * @param MeshSelection meshSelection The mesh-element selection. + * @param Selection objectSelection The object selection. + * @return Drawable? The followed drawable, or null when the model has no meshed drawable at all. + */ +private fun activeUvDrawable(model: PuppetModel, meshSelection: MeshSelection, objectSelection: Selection): Drawable? { + val activeDrawableId = + meshSelection.activeDrawableId + ?: (objectSelection.active as? SelectionTarget.Drawable)?.id + ?: model.drawables.firstOrNull { drawable -> drawable.mesh != null }?.id + return model.drawables.firstOrNull { drawable -> drawable.id == activeDrawableId }?.takeIf { it.mesh != null } +} + +/** + * The meshes drawn over a shown source layer, under the same Edit / Object rule the page view uses: + * the session's edited meshes while editing, every visible mesh while selecting. + * + * Duplicated art shares a layer, so several drawables can draw over one image at once - which is why + * Object mode shows them all (they are the click targets) and Edit mode does not (only the meshes the + * session is editing can actually be moved). + * + * @param PuppetModel model The session's committed model. + * @param EditorMode mode The session mode selecting the Edit / Object candidate rule. + * @param MeshSelection meshSelection The mesh-element selection (Edit mode's candidate set). + * @param String layerKey The shown layer. + * @return List The drawables whose mappings draw over the layer, in model order. + */ +internal fun shownLayerDrawables( + model: PuppetModel, + mode: EditorMode, + meshSelection: MeshSelection, + layerKey: String, +): List = + shownSurfaceDrawables(model, mode, meshSelection) { drawable -> drawable.atlasTileId?.raw == layerKey } + +/** + * Each shown drawable's mapping IN THE SHOWN SURFACE'S OWN FRAME - the coordinates that address the + * image the editor is drawing over. + * + * Over a page those are the stored coordinates verbatim; over a source layer they are the stored ones + * recovered through the drawable's placement. One map serves both of the things that need them: the + * display projection the overlays draw, and the alpha gate the island pick samples the shown image + * with. Deriving them once is what keeps those two from disagreeing about where a mesh is. + * + * A drawable whose recovery is degenerate is absent rather than mapped to a wrong place. + * + * @param List shownDrawables The drawables drawn over the shown surface. + * @param PuppetModel model The puppet, for the atlas the layer mapping derives from. + * @param UvEditorLayer? layerView The shown layer, or null when a page is shown. + * @return Map Each drawable's mapping in the shown surface's frame. + */ +internal fun shownSurfaceUvs( + shownDrawables: List, + model: PuppetModel, + layerView: UvEditorLayer?, +): Map = + shownDrawables + .mapNotNull { drawable -> + val mesh = drawable.mesh ?: return@mapNotNull null + if (layerView == null) { + return@mapNotNull drawable.id to mesh.uvs + } + val binding = model.atlasBindingFor(drawable) ?: return@mapNotNull null + val layerUvs = layerUvsFromAtlasUvs(mesh.uvs, binding, layerView.width, layerView.height) ?: return@mapNotNull null + drawable.id to layerUvs + } + .toMap() + +/** + * The texture-selection transition for one page-switch request: cycling pins the page adjacent to + * the EFFECTIVE page (what the area is actually showing, pin or follow) with wrap-around, and + * FollowSelection clears the pin. From the untextured fallback (a null effective page) NextPage + * pins the first page and PreviousPage the last, so cycling always lands somewhere real. With no + * pages at all there is nothing to pin and cycling keeps the selection unchanged. + * + * @param UvPageKind kind The requested page operation. + * @param UvTextureSelection currentSelection The area's stored texture selection. + * @param Int? effectivePageIndex The shown page's index, or null for the untextured fallback. + * @param Int pageCount The document's atlas page count. + * @return UvTextureSelection The texture selection after the request. + */ +internal fun uvPageSelectionAfter( + kind: UvPageKind, + currentSelection: UvTextureSelection, + effectivePageIndex: Int?, + pageCount: Int, +): UvTextureSelection = + when (kind) { + UvPageKind.FollowSelection -> UvTextureSelection.FollowSelection + UvPageKind.NextPage -> + if (pageCount <= 0) { + currentSelection + } else { + UvTextureSelection.PinnedPage(((effectivePageIndex ?: -1) + 1).mod(pageCount)) + } + UvPageKind.PreviousPage -> + if (pageCount <= 0) { + currentSelection + } else { + UvTextureSelection.PinnedPage(((effectivePageIndex ?: 0) - 1 + pageCount).mod(pageCount)) + } + } + +/** + * The meshes drawn over the shown page: in Edit mode every session mesh sampling this page (the + * active one is emphasized via the highlight sets), in Object mode EVERY visible meshed drawable + * mapped to the page, in model (parts-tree) order - the islands are the click targets, so all of + * them show, selection styling the difference. Visibility follows the Parts-panel eyeball cascade + * (visibleDrawableIds), matching what the viewport can render and therefore pick; a hidden island + * neither draws nor picks. Meshes without an editable UV array (empty or malformed) and meshes + * mapped to another page are excluded everywhere. + * + * @param PuppetModel model The session's committed model. + * @param EditorMode mode The session mode selecting the Edit / Object candidate rule. + * @param MeshSelection meshSelection The mesh-element selection (Edit mode's candidate set). + * @param PuppetTextures? textures The decoded atlas pages, or null before textures load. + * @param Int? pageIndex The shown page's index (the page filter), or null for the untextured fallback. + * @return List The drawables whose mappings draw over the page. + */ +internal fun shownUvDrawables( + model: PuppetModel, + mode: EditorMode, + meshSelection: MeshSelection, + textures: PuppetTextures?, + pageIndex: Int?, +): List = + shownSurfaceDrawables(model, mode, meshSelection) { drawable -> + textures == null || atlasPageIndexFor(drawable, textures) == pageIndex + } + +/** + * The meshes drawn over whichever surface the UV editor is showing. + * + * The Edit / Object split is the whole rule and it belongs to the EDITOR, not to the surface: Edit + * mode shows the session's edited meshes, because those are the ones an operator can act on - showing + * more would offer the user vertices that refuse to move - and Object mode shows every visible mesh, + * because those are the click targets. Only [drawsOverSurface] differs between a page and a source + * layer, which is what keeps the two views from drifting apart on the rule they share. + * + * Meshes without an editable UV array (empty or malformed) are excluded everywhere. Visibility + * follows the Parts-panel eyeball cascade in Object mode, matching what the viewport can render and + * therefore pick; a hidden island neither draws nor picks. + * + * @param PuppetModel model The session's committed model. + * @param EditorMode mode The session mode selecting the Edit / Object candidate rule. + * @param MeshSelection meshSelection The mesh-element selection (Edit mode's candidate set). + * @param Function drawsOverSurface Whether a drawable's mapping addresses the shown surface. + * @return List The drawables whose mappings draw over it, in model order. + */ +internal fun shownSurfaceDrawables( + model: PuppetModel, + mode: EditorMode, + meshSelection: MeshSelection, + drawsOverSurface: (Drawable) -> Boolean, +): List { + val candidates = + if (mode == EditorMode.Edit) { + meshSelection.drawableIds.mapNotNull { drawableId -> model.drawables.firstOrNull { drawable -> drawable.id == drawableId } } + } else { + val shownIds = model.visibleDrawableIds() + model.drawables.filter { drawable -> drawable.id in shownIds } + } + return candidates.filter { drawable -> + val mesh = drawable.mesh + mesh != null && mesh.uvs.isNotEmpty() && mesh.uvs.size == mesh.positions.size && drawsOverSurface(drawable) + } +} + +/** + * Projects the shown drawables' mappings into display-space gizmo geometry: texel units with the + * v-axis flip (see UvDisplayMapping.kt), edges derived from the triangle indices. + * + * Takes the mappings rather than reading them off the drawables, because which frame they are in is + * the caller's business (see [shownSurfaceUvs]) - which is what lets one projection serve the page + * view and the layer view alike, and every overlay downstream stay unaware of the difference. + * + * @param List shownDrawables The drawables drawn over the shown surface. + * @param Map uvsById Each drawable's mapping in the shown surface's frame. + * @param Int displayWidth The shown surface's width in texels (the display mapping's scale). + * @param Int displayHeight The shown surface's height in texels. + * @return List One geometry per drawable with a mapping. + */ +internal fun uvGizmoGeometries( + shownDrawables: List, + uvsById: Map, + displayWidth: Int, + displayHeight: Int, +): List = + shownDrawables.mapNotNull { drawable -> + val mesh = drawable.mesh ?: return@mapNotNull null + val uvs = uvsById[drawable.id] ?: return@mapNotNull null + GizmoMeshGeometry(drawable.id, mesh.indices, MeshTopology.uniqueEdges(mesh.indices), uvToDisplay(uvs, displayWidth, displayHeight)) + } + +/** + * The display-space rectangle every shown mesh covers - what a fit of the UV editor widens the shown + * surface to take in, so a placement moved past the page edge is still framed along with the page. + * + * @param List geometries The shown meshes in display space. + * @return ContentBounds? Their bounds, or null when no mesh has a vertex. + */ +internal fun shownIslandExtent(geometries: List): ContentBounds? { + var minX = Float.POSITIVE_INFINITY + var minY = Float.POSITIVE_INFINITY + var maxX = Float.NEGATIVE_INFINITY + var maxY = Float.NEGATIVE_INFINITY + for (geometry in geometries) { + val positions = geometry.positions + for (vertexIndex in 0 until positions.size / 2) { + val x = positions[vertexIndex * 2] + val y = positions[vertexIndex * 2 + 1] + // A mapping that is not a number frames nothing, and would poison every bound it touched. + if (!x.isFinite() || !y.isFinite()) { + continue + } + minX = minOf(minX, x) + minY = minOf(minY, y) + maxX = maxOf(maxX, x) + maxY = maxOf(maxY, y) + } + } + if (minX > maxX) { + return null + } + return ContentBounds(minX, minY, maxX - minX, maxY - minY) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvLayerPickerChip.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvLayerPickerChip.kt new file mode 100644 index 0000000..ed5bbc8 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvLayerPickerChip.kt @@ -0,0 +1,113 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.drawableIdsByAtlasTile +import org.umamo.ui.action.rankCommandMatches +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons + +/** The layer menu's width, which its search box fixes so the rows stay put as the search narrows them. */ +private val LAYER_PICKER_WIDTH = 320.dp + +/** + * Find a drawable by its artwork: a searchable list of the document's source layers whose rows select + * the drawable that samples them. + * + * This is navigation, not a second selection. The layer view follows the active drawable, so pointing + * it at a particular piece of art means selecting the object that uses that art - which is exactly what + * a row does, writing the ONE session selection. Naming a layer here would otherwise be a second + * pointer to keep in sync with the first. + * + * Ranked with the command palette's own matcher, so "eye" finds the eye layers by the same rules that + * find the eye commands. Rows name the layer, its pixel size, and how many drawables share it - + * duplicated art is common, and a row selecting one of several is worth seeing before it happens. + * A kit [Menu] with a search box, so it looks like every other menu and closes on a pick. + */ +@Composable +internal fun UvLayerPickerChip() { + val puppet = LocalPuppet.current + val session = LocalEditorSession.current + var query by remember { mutableStateOf("") } + val entries = puppet?.atlas?.tiles.orEmpty() + // The tile -> drawables inverse, remembered with the model: a row says how many drawables share its + // art and selects one of them, and rebuilding that per row would walk the whole drawable list each time. + val drawableIdsByTile = remember(puppet) { puppet?.drawableIdsByAtlasTile().orEmpty() } + // Remembered on both inputs: ranking scores and sorts the document's whole layer inventory, which + // runs to hundreds of rows, and this chip recomposes for header state that has nothing to do with + // either of them. + val filtered = + remember(entries, query) { + if (query.isBlank()) { + entries + } else { + rankCommandMatches(entries, query, labelOf = { entry -> entry.name }, idOf = { entry -> entry.id.raw }) + } + } + var open by remember { mutableStateOf(false) } + val emptyLabel = stringResource(if (entries.isEmpty()) Res.string.uv_layer_picker_empty else Res.string.uv_layer_picker_no_matches) + // One row per ranked layer; a layer no drawable uses is listed dimmed, since it selects nothing. + // The menu's search box fixes the width, so the rows stay put as the search narrows them. + val rows = + filtered.map { entry -> + val users = drawableIdsByTile[entry.id].orEmpty() + MenuItem.Action( + label = layerRowLabel(entry, users.size), + enabled = users.isNotEmpty(), + onSelect = { + // The first drawable using this art: with duplicates any of them shows the same + // layer, and picking deterministically beats picking arbitrarily. + users.firstOrNull()?.let { drawableId -> + session?.setSelection(SelectionOps.replace(SelectionTarget.Drawable(drawableId))) + } + }, + ) + } + val items = + buildList { + add(MenuItem.Search(value = query, onValueChange = { updated -> query = updated }, width = LAYER_PICKER_WIDTH)) + if (rows.isEmpty()) { + add(MenuItem.Action(label = emptyLabel, onSelect = {}, enabled = false)) + } + addAll(rows) + } + DropdownChip( + expanded = open, + onExpandRequest = { open = true }, + contentDescription = stringResource(Res.string.uv_layer_picker_title), + icon = LocalUmamoIcons.search, + ) { + Menu(items = items, onDismissRequest = { open = false }, positionProvider = BelowAnchorPositionProvider) + } +} + +/** + * One layer row's text: its name, its pixel size, and how many drawables sample it. + * + * @param AtlasTile entry The tile to describe. + * @param Int userCount How many drawables sample it. + * @return String The row label. + */ +@Composable +private fun layerRowLabel(entry: AtlasTile, userCount: Int): String = + stringResource( + Res.string.uv_layer_picker_row, + entry.name, + entry.width, + entry.height, + userCount, + ) \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvPageUnderlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvPageUnderlay.kt new file mode 100644 index 0000000..ec9dbac --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/UvPageUnderlay.kt @@ -0,0 +1,85 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.viewport.RenderedFrame +import org.umamo.ui.viewport.worldToScreen + +/** + * The UV editor's underlay: the shown surface - an atlas page or a source layer's artwork - rendered + * by the GL engine (upright, correctly sampled, sharing the puppet's texture), clipped to its + * on-screen rectangle with a 1.dp frame drawn around it - or the plain viewport backdrop color for the + * moment before the first GL frame lands. + * + * The rectangle is the full UV tile (display space [0, 0]-[pageWidth, pageHeight]) projected + * through the FRAME's camera, so it tracks pan / zoom glued to the rendered texture. The grid + + * texture raster is clipped to it so the grid does not spill past the texture onto the panel + * elevation; the wireframe overlays above are deliberately unclipped, so UVs outside the tile stay + * visible. + * + * @param RenderedFrame? rendered The displayed GL frame, or null before the first frame. + * @param Int pageWidth The shown surface's width in texels. + * @param Int pageHeight The shown surface's height in texels. + * @param Int widthPx The area width in pixels. + * @param Int heightPx The area height in pixels. + * @param Modifier modifier The layout modifier (the host passes a stack fill). + */ +@Composable +internal fun UvPageUnderlay( + rendered: RenderedFrame?, + pageWidth: Int, + pageHeight: Int, + widthPx: Int, + heightPx: Int, + modifier: Modifier = Modifier, +) { + val uiColors = LocalUmamoColors.current + if (rendered == null) { + // Before the first frame there is no camera to draw anything through, so the area is just the + // backdrop color the frame will arrive over - no grid of its own to swap out a moment later. + Box(modifier = modifier.fillMaxSize().background(uiColors.viewportGridBackground)) + return + } + val cornerLowerLeft = worldToScreen(0f, 0f, rendered.camera, IntSize(widthPx, heightPx)) + val cornerUpperRight = worldToScreen(pageWidth.toFloat(), pageHeight.toFloat(), rendered.camera, IntSize(widthPx, heightPx)) + val textureRect = + Rect( + left = minOf(cornerLowerLeft.x, cornerUpperRight.x), + top = minOf(cornerLowerLeft.y, cornerUpperRight.y), + right = maxOf(cornerLowerLeft.x, cornerUpperRight.x), + bottom = maxOf(cornerLowerLeft.y, cornerUpperRight.y), + ) + Image( + bitmap = rendered.bitmap, + contentDescription = null, + modifier = + modifier.fillMaxSize().drawWithContent { + clipRect(textureRect.left, textureRect.top, textureRect.right, textureRect.bottom) { this@drawWithContent.drawContent() } + }, + contentScale = ContentScale.FillBounds, + ) + // The 1.dp frame around the texture (the page-elevation border of the diagram). + Canvas(modifier = modifier.fillMaxSize()) { + drawRect( + color = uiColors.panelBorder, + topLeft = Offset(textureRect.left, textureRect.top), + size = Size(textureRect.width, textureRect.height), + style = Stroke(width = 1.dp.toPx()), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/Viewport2DHeaderControls.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/Viewport2DHeaderControls.kt new file mode 100644 index 0000000..bb9a506 --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/Viewport2DHeaderControls.kt @@ -0,0 +1,141 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.formatAccelerator +import org.umamo.ui.kit.BelowAnchorPositionProvider +import org.umamo.ui.kit.DropdownChip +import org.umamo.ui.kit.Menu +import org.umamo.ui.kit.MenuItem +import org.umamo.ui.kit.OverflowRowScope +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons + +/** + * The 2D viewport's space-specific header strip (mounted via SpaceDescriptor.headerContent): the + * Object / Edit mode dropdown, the vertex / edge / face select-mode buttons (Edit mode), the transform + * pivot dropdown, the snap menu, and the proportional-editing toggle with its falloff dropdown (Edit + * mode). With no open document the chips render disabled rather than vanishing, so the viewport + * chrome reads the same before the first file opens. + * + * Every control observes the session's own flows and mutates only by dispatching registry commands, + * per the everything-through-the-action-registry rule - a rebind or palette invocation stays + * consistent with these controls for free. The Edit-mode pieces (select modes, pivot, proportional) + * are the shared EditHeaderControls.kt composables the UV editor's header mounts too, and each gates + * itself on the session's mode: an item that renders nothing measures zero and costs the strip nothing. + * + * The widest strip in the app, so it is the one that most needs the overflow behavior. Only the mode + * dropdown is pinned - it is the control the whole viewport header is about, and a header that hides its + * own subject is worse than one that clips. + */ +fun OverflowRowScope.viewport2DHeaderControls() { + item("editorMode") { EditorModeDropdown() } + item("selectMode") { MeshSelectModeButtons() } + item("pivot") { PivotModeDropdown() } + item("snap") { SnapDropdown() } + item("proportional") { ProportionalEditControls() } +} + +/** + * The editor-mode selector, Blender-style: the button face is the current mode's icon plus its label + * plus a chevron that points right while the menu is closed and down while it is open. Clicking opens + * a two-row menu (Object Mode / Edit Mode, each icon + label + bound-shortcut hint); choosing a row + * dispatches the matching set-mode command. The chip anatomy is the shared kit [DropdownChip], the + * same face as the area header's AreaTypeDropdown so the header chips read as one family. + */ +@Composable +private fun EditorModeDropdown() { + val commands = LocalCommands.current + val keymap = LocalKeymap.current + val session = LocalEditorSession.current + val enabled = session != null + val editorMode = session?.mode?.collectAsState()?.value ?: EditorMode.Object + val modeIcon = + when (editorMode) { + EditorMode.Object -> LocalUmamoIcons.editorModeObject + EditorMode.Edit -> LocalUmamoIcons.editorModeEdit + } + // Resolved in composition because the chip's semantics lambda is not composable. + val currentLabel = + when (editorMode) { + EditorMode.Object -> stringResource(Res.string.cmd_mode_object) + EditorMode.Edit -> stringResource(Res.string.cmd_mode_edit) + } + var expanded by remember { mutableStateOf(false) } + // One row per mode; the menu's own dismiss closes the popup, so onSelect need not toggle `expanded`. + // Each row shows its own command's bound chord (none by default - a hint appears if the user binds one). + val items = + listOf( + MenuItem.Action( + label = stringResource(Res.string.cmd_mode_object), + onSelect = { commands.invoke("mode.object") }, + shortcut = keymap.chordFor("mode.object")?.let { chord -> formatAccelerator(chord) }, + icon = LocalUmamoIcons.editorModeObject, + ), + MenuItem.Action( + label = stringResource(Res.string.cmd_mode_edit), + onSelect = { commands.invoke("mode.edit") }, + shortcut = keymap.chordFor("mode.edit")?.let { chord -> formatAccelerator(chord) }, + icon = LocalUmamoIcons.editorModeEdit, + ), + ) + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = currentLabel, + icon = modeIcon, + label = currentLabel, + enabled = enabled, + ) { + Menu( + items = items, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} + +/** + * The snap menu (Blender's Shift+S, as a header dropdown): an icon-only magnet chip whose rows + * dispatch the eight snap commands - the cursor moves and the selection moves - so the pie and this + * menu stay one behavior. + */ +@Composable +private fun SnapDropdown() { + val commands = LocalCommands.current + val enabled = LocalEditorSession.current != null + var expanded by remember { mutableStateOf(false) } + val items = + listOf( + MenuItem.Action(label = stringResource(Res.string.cmd_snap_cursor_world_origin), onSelect = { commands.invoke("snap.cursorToWorldOrigin") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_cursor_grid), onSelect = { commands.invoke("snap.cursorToGrid") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_cursor_selected), onSelect = { commands.invoke("snap.cursorToSelected") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_cursor_active), onSelect = { commands.invoke("snap.cursorToActive") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_selection_grid), onSelect = { commands.invoke("snap.selectionToGrid") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_selection_cursor), onSelect = { commands.invoke("snap.selectionToCursor") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_selection_cursor_offset), onSelect = { commands.invoke("snap.selectionToCursorOffset") }), + MenuItem.Action(label = stringResource(Res.string.cmd_snap_selection_active), onSelect = { commands.invoke("snap.selectionToActive") }), + ) + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = stringResource(Res.string.cmd_snap_pie), + icon = LocalUmamoIcons.snap, + enabled = enabled, + ) { + Menu( + items = items, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ViewportSidebarDrawer.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ViewportSidebarDrawer.kt new file mode 100644 index 0000000..da3d76d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ViewportSidebarDrawer.kt @@ -0,0 +1,128 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.ZeroCornerSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.Text +import org.umamo.ui.kit.Tooltip +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.LocalUmamoTypography +import org.umamo.ui.theme.drawIcon +import org.umamo.ui.workspace.LocalViewportChrome + +/** The open drawer panel's width. */ +private val SIDEBAR_PANEL_WIDTH = 200.dp + +/** The pull tab's width (its height is [SIDEBAR_TAB_HEIGHT]). */ +private val SIDEBAR_TAB_WIDTH = 14.dp + +/** The pull tab's height. */ +private val SIDEBAR_TAB_HEIGHT = 48.dp + +/** + * The viewport's right sidebar drawer (Blender's N panel, as chrome): a collapsible panel hugging the + * viewport's right edge with a pull tab riding its outer border. The tab's chevron points into the + * viewport ("<") while closed and back out (">") while open; clicking it dispatches view.toggleSidebar + * (bound to N), the same command the keymap and palette use, which flips the settings-backed + * [LocalViewportChrome] flag. The panel body is currently an empty shell; it does not yet host the + * tool/item tabs. + * + * ビューポート右側のサイドバー(Blender の N パネル)。プルタブで開閉し、view.toggleSidebar コマンドを + * 発行する。中身は今のところ骨組みのみ。 + * + * @param Modifier modifier The layout modifier (the caller aligns it to the viewport's right edge). + */ +@Composable +internal fun ViewportSidebarDrawer(modifier: Modifier = Modifier) { + val chrome = LocalViewportChrome.current + val colors = LocalUmamoColors.current + Row(modifier = modifier.fillMaxHeight()) { + Box(modifier = Modifier.fillMaxHeight(), contentAlignment = Alignment.Center) { + SidebarPullTab(open = chrome.showSidebar) + } + if (chrome.showSidebar) { + Column( + modifier = + Modifier + .fillMaxHeight() + .width(SIDEBAR_PANEL_WIDTH) + .background(colors.panelBackground) + .border(width = 1.dp, color = colors.panelBorder) + .padding(8.dp), + ) { + Text( + text = stringResource(Res.string.sidebar_title), + style = LocalUmamoTypography.current.labelMedium, + color = colors.text, + ) + Text( + text = stringResource(Res.string.sidebar_empty_hint), + style = LocalUmamoTypography.current.labelSmall, + color = colors.textMuted, + modifier = Modifier.padding(top = 6.dp), + ) + } + } + } +} + +/** + * The drawer's pull tab: a slim rounded-start chip on the panel's outer edge whose chevron points the + * way the drawer will move. Dispatches view.toggleSidebar through the registry. + * + * @param Boolean open Whether the drawer is currently open (flips the chevron). + */ +@Composable +private fun SidebarPullTab(open: Boolean) { + val commands = LocalCommands.current + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val interaction = remember { MutableInteractionSource() } + val hovered by interaction.collectIsHoveredAsState() + val label = stringResource(Res.string.cmd_view_toggle_sidebar) + // Rounded on the viewport side only; the panel side sits flush against the drawer (or the area edge). + val tabShape = shapes.small.copy(topEnd = ZeroCornerSize, bottomEnd = ZeroCornerSize) + Tooltip(text = label) { + Box( + modifier = + Modifier + .size(width = SIDEBAR_TAB_WIDTH, height = SIDEBAR_TAB_HEIGHT) + .clip(tabShape) + .background(if (hovered) colors.buttonHover else colors.panelBackground) + .border(width = 1.dp, color = if (hovered) colors.panelBorderHover else colors.panelBorder, shape = tabShape) + .clickable(interactionSource = interaction, indication = null) { commands.invoke("view.toggleSidebar") } + .semantics { contentDescription = label }, + contentAlignment = Alignment.Center, + ) { + val chevron = if (open) LocalUmamoIcons.chevronRight else LocalUmamoIcons.chevronLeft + Canvas(modifier = Modifier.size(12.dp)) { + drawIcon(chevron, colors.controlGlyph) + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ViewportToolbarOverlay.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ViewportToolbarOverlay.kt new file mode 100644 index 0000000..1ecae4b --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ViewportToolbarOverlay.kt @@ -0,0 +1,150 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.EditorMode +import org.umamo.edit.MeshOperatorKind +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.kit.button.IconButton +import org.umamo.ui.kit.button.IconButtonAppearance +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoColors +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.LocalUmamoShapes +import org.umamo.ui.theme.UmamoIcon + +/** The square size of one toolbar button (generous for pen and touch). */ +private val TOOLBAR_BUTTON_SIZE = 28.dp + +/** The glyph size inside a toolbar button. */ +private val TOOLBAR_GLYPH_SIZE = 18.dp + +/** + * The viewport's floating left tool toolbar (Blender's toolbar, reduced to a strip): the select tools + * (Box, Circle), the Edit-mode Add Vertex draft tool, the modal transforms (Grab, Rotate), Photoshop-style + * Scale (AABB handle marquee), and one-shot Mirror H / V, each dispatching its registry command so the + * buttons, shortcuts, pies, and palette all share one behavior. The armed / in-flight state lights the + * matching button. With no open document the strip still renders, disabled, so the viewport chrome + * reads the same before the first file opens. + * + * Visibility is [org.umamo.ui.workspace.LocalViewportChrome] (settings-backed, toggled by + * view.toggleToolbar / T) - the caller gates on it, keeping this composable a pure strip. + * + * @param Modifier modifier The layout modifier (the caller aligns it to the viewport's left edge). + */ +@Composable +internal fun ViewportToolbarOverlay(modifier: Modifier = Modifier) { + val session = LocalEditorSession.current + val colors = LocalUmamoColors.current + val shapes = LocalUmamoShapes.current + val enabled = session != null + val selectTool = session?.activeSelectTool?.collectAsState()?.value + val meshOperator = session?.activeMeshOperator?.collectAsState()?.value + val objectOperator = session?.activeObjectOperator?.collectAsState()?.value + val liveOperator = meshOperator ?: objectOperator + val inEditMode = session?.mode?.collectAsState()?.value == EditorMode.Edit + Column( + modifier = + modifier + .background(colors.panelBackground, shapes.small) + .border(width = 1.dp, color = colors.panelBorder, shape = shapes.small) + .padding(3.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + ToolbarButton( + commandId = "mesh.boxSelect", + icon = LocalUmamoIcons.toolBoxSelect, + label = stringResource(Res.string.cmd_mesh_box_select), + active = selectTool is ActiveSelectTool.BoxArmed, + enabled = enabled, + ) + ToolbarButton( + commandId = "mesh.circleSelect", + icon = LocalUmamoIcons.toolCircleSelect, + label = stringResource(Res.string.cmd_mesh_circle_select), + active = selectTool is ActiveSelectTool.Circle, + enabled = enabled, + ) + ToolbarButton( + commandId = "mesh.insertVertex", + icon = LocalUmamoIcons.toolInsertVertex, + label = stringResource(Res.string.cmd_mesh_insert_vertex), + active = selectTool is ActiveSelectTool.AddVertex, + enabled = enabled && inEditMode, + ) + ToolbarButton( + commandId = "mesh.grab", + icon = LocalUmamoIcons.toolGrab, + label = stringResource(Res.string.cmd_mesh_grab), + active = liveOperator?.kind == MeshOperatorKind.Grab, + enabled = enabled, + ) + ToolbarButton( + commandId = "mesh.rotate", + icon = LocalUmamoIcons.toolRotate, + label = stringResource(Res.string.cmd_mesh_rotate), + active = liveOperator?.kind == MeshOperatorKind.Rotate, + enabled = enabled, + ) + ToolbarButton( + commandId = "mesh.scale", + icon = LocalUmamoIcons.toolScale, + label = stringResource(Res.string.cmd_mesh_scale), + active = liveOperator?.kind == MeshOperatorKind.Scale, + enabled = enabled, + ) + ToolbarButton( + commandId = "mesh.mirrorH", + icon = LocalUmamoIcons.toolMirrorH, + label = stringResource(Res.string.cmd_mesh_mirror_h), + active = false, + enabled = enabled, + ) + ToolbarButton( + commandId = "mesh.mirrorV", + icon = LocalUmamoIcons.toolMirrorV, + label = stringResource(Res.string.cmd_mesh_mirror_v), + active = false, + enabled = enabled, + ) + } +} + +/** + * One toolbar button: a filled kit [IconButton] whose click dispatches [commandId] through the registry + * (an unavailable command no-ops there, the same guard every entry point shares). + * + * @param String commandId The registry command the button dispatches. + * @param UmamoIcon icon The button glyph. + * @param String label The localized tooltip / accessibility label. + * @param Boolean active Whether the tool is armed / in flight (lights the fill). + * @param Boolean enabled Whether a document is open (disabled chrome otherwise). + */ +@Composable +private fun ToolbarButton(commandId: String, icon: UmamoIcon, label: String, active: Boolean, enabled: Boolean) { + val commands = LocalCommands.current + val shapes = LocalUmamoShapes.current + IconButton( + icon = icon, + onClick = { commands.invoke(commandId) }, + contentDescription = label, + appearance = IconButtonAppearance.Filled(shapes.small), + size = DpSize(TOOLBAR_BUTTON_SIZE, TOOLBAR_BUTTON_SIZE), + glyphSize = TOOLBAR_GLYPH_SIZE, + active = active, + enabled = enabled, + ) +} \ No newline at end of file diff --git a/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ZebraBackground.kt b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ZebraBackground.kt new file mode 100644 index 0000000..409e70d --- /dev/null +++ b/module/ui/src/commonMain/kotlin/org/umamo/ui/workspace/spaces/ZebraBackground.kt @@ -0,0 +1,61 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.unit.Dp +import kotlin.math.floor + +/** + * Paints an alternating "zebra" stripe pattern across the whole drawing area, filling it top to bottom + * regardless of how many list rows are present, so a short or empty list still reads as a prepared panel + * rather than a list that runs out partway down. The stripe grid is anchored to the first visible row + * (read from [listState]) and steps in [rowHeight] bands, so the painted stripes stay locked to the rows + * as the list scrolls; odd-indexed bands take [stripeColor] and even bands are left clear. Rows draw only + * their selection / hover / match overlays on top - the base stripe lives here, behind them. + * + * The caller must draw the list flush at the area's top edge with no leading vertical inset (row index 0 + * at y = 0) and rows of uniform [rowHeight]; otherwise the bands and rows drift apart. + * + * @param LazyListState listState The list whose scroll position anchors the stripe grid. + * @param Dp rowHeight The uniform row height, which is also the stripe band height. + * @param Color stripeColor The fill for the odd (striped) bands. + * @return Modifier The modifier drawing the zebra fill behind its content. + */ +internal fun Modifier.zebraFill(listState: LazyListState, rowHeight: Dp, stripeColor: Color): Modifier = + this.drawBehind { + val rowHeightPx = rowHeight.toPx() + if (rowHeightPx <= 0f) { + return@drawBehind + } + // Anchor the band grid to the first visible row so bands track the rows while scrolling; an empty + // list has no visible row, so fall back to band 0 flush at the area's top edge. + val firstVisible = listState.layoutInfo.visibleItemsInfo.firstOrNull() + val anchorTop = firstVisible?.offset?.toFloat() ?: 0f + val anchorIndex = firstVisible?.index ?: 0 + // Step back to the band covering the top edge (its top is the greatest band top <= 0), then stripe + // downward past the last row to the area's foot so a short or empty list still reads as filled. + var bandIndex = anchorIndex + floor(-anchorTop / rowHeightPx).toInt() + var bandTop = anchorTop + (bandIndex - anchorIndex) * rowHeightPx + // Clip to the drawing area: drawBehind does not clip, and the first / last bands overhang the top and + // bottom edges (the top band belongs to the partially scrolled-off first row) - unclipped they would + // paint over the neighbouring chrome, e.g. the area header sitting directly above this body. + clipRect(left = 0f, top = 0f, right = size.width, bottom = size.height) { + while (bandTop < size.height) { + // mod (not %) so the parity stays correct even if a band index ever goes negative. + if (bandIndex.mod(2) == 1) { + drawRect( + color = stripeColor, + topLeft = Offset(0f, bandTop), + size = Size(size.width, rowHeightPx), + ) + } + bandTop += rowHeightPx + bandIndex += 1 + } + } + } \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/FirstRunSettingsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/FirstRunSettingsTest.kt new file mode 100644 index 0000000..cb5f2a0 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/FirstRunSettingsTest.kt @@ -0,0 +1,79 @@ +package org.umamo.ui + +import okio.Path +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.settings.Settings +import org.umamo.storage.OkioAppStorage +import org.umamo.ui.l10n.LOCALE_SETTINGS_KEY +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** What a first run - no user settings file at load - seeds before anything is shown. */ +class FirstRunSettingsTest { + private val configDir: Path = "/config".toPath() + + private val defaultJson = """{"localization":{"locale":"en"}}""" + + /** + * An in-memory storage rooted at /config, with the user settings file seeded when [userJson] is given. + * + * @param String? userJson The user settings file's contents, or null for none. + * @return Pair The filesystem and a storage over it. + */ + private fun storageWith(userJson: String? = null): Pair { + val fileSystem = FakeFileSystem() + fileSystem.createDirectories(configDir) + if (userJson != null) { + fileSystem.write(configDir / "settings.json") { writeUtf8(userJson) } + } + return fileSystem to OkioAppStorage(fileSystem, configDir, "/data".toPath()) + } + + @Test + fun aFirstRunSeedsTheSystemLanguageAndCreatesTheFile() { + val (fileSystem, storage) = storageWith() + val settings = Settings.load(storage, defaultJson) + + seedFirstRunSettings(settings, systemTags = listOf("ja-JP")) + + assertEquals("ja", settings.getString(LOCALE_SETTINGS_KEY)) + assertTrue(fileSystem.exists(configDir / "settings.json"), "the seed creates the user file") + assertTrue(Settings.load(storage, defaultJson).foundUserFile, "so the next launch is not a first run") + } + + @Test + fun aFirstRunWithNoCatalogForTheSystemLanguageStillPinsEnglish() { + val (fileSystem, storage) = storageWith() + val settings = Settings.load(storage, defaultJson) + + seedFirstRunSettings(settings, systemTags = listOf("fr-FR")) + + assertEquals("en", settings.getString(LOCALE_SETTINGS_KEY)) + assertTrue(fileSystem.exists(configDir / "settings.json"), "written even when it matches the default") + } + + @Test + fun existingSettingsAreNeverReseeded() { + val (_, storage) = storageWith(userJson = """{"localization":{"locale":"ko"}}""") + val settings = Settings.load(storage, defaultJson) + + seedFirstRunSettings(settings, systemTags = listOf("ja-JP")) + + assertEquals("ko", settings.getString(LOCALE_SETTINGS_KEY), "the rigger's own choice stands") + } + + @Test + fun existingSettingsWithoutALanguageAreNotSeededEither() { + // Only a first run detects: a settings file that never chose a language keeps the default. + val (fileSystem, storage) = storageWith(userJson = """{"interface":{"theme":"light"}}""") + val settings = Settings.load(storage, defaultJson) + + seedFirstRunSettings(settings, systemTags = listOf("ja-JP")) + + assertEquals("en", settings.getString(LOCALE_SETTINGS_KEY)) + assertFalse(fileSystem.read(configDir / "settings.json") { readUtf8() }.contains("locale"), "nothing was written") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/action/AcceleratorTextTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/AcceleratorTextTest.kt new file mode 100644 index 0000000..3c5e19e --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/AcceleratorTextTest.kt @@ -0,0 +1,59 @@ +package org.umamo.ui.action + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Verifies accelerator-hint formatting: key-token to glyph mapping, modifier ordering, and the + * "+"-joined assembly. The pure overload that takes an explicit primary-modifier label is tested + * (rather than the platform one) so the assertions are host-independent. + */ +class AcceleratorTextTest { + /** + * A "Key" token becomes its bare letter and a "Digit" token its bare digit; the named keys map to + * their short symbols. + */ + @Test + fun keyGlyphMapsTokensToDisplayForms() { + assertEquals("O", keyGlyph("KeyO")) + assertEquals("0", keyGlyph("Digit0")) + assertEquals("=", keyGlyph("Equals")) + assertEquals("−", keyGlyph("Minus")) + assertEquals("Esc", keyGlyph("Escape")) + assertEquals("Space", keyGlyph("Space")) + } + + /** + * An unrecognized token falls back to itself, so a newly bound key still shows something readable. + */ + @Test + fun keyGlyphFallsBackToTheTokenItself() { + assertEquals("F13", keyGlyph("F13")) + } + + /** + * The primary modifier prefixes the key with the supplied platform label. + */ + @Test + fun formatsPrimaryModifierWithSuppliedLabel() { + assertEquals("Ctrl+O", formatAccelerator(KeyChord(keyName = "KeyO", primaryModifier = true), "Ctrl")) + assertEquals("⌘+O", formatAccelerator(KeyChord(keyName = "KeyO", primaryModifier = true), "⌘")) + } + + /** + * Modifiers render in the order primary, Alt, Shift, ahead of the key glyph. + */ + @Test + fun ordersModifiersPrimaryAltShiftThenKey() { + val chord = KeyChord(keyName = "KeyP", primaryModifier = true, shift = true, alt = true) + assertEquals("Ctrl+Alt+Shift+P", formatAccelerator(chord, "Ctrl")) + } + + /** + * A bare key with no modifiers formats as just its glyph. + */ + @Test + fun formatsBareKey() { + assertEquals("Esc", formatAccelerator(KeyChord(keyName = "Escape"), "Ctrl")) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandRegistryTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandRegistryTest.kt new file mode 100644 index 0000000..b5e1e4b --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandRegistryTest.kt @@ -0,0 +1,137 @@ +package org.umamo.ui.action + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the action-registry dispatch contract: registered commands run with the forwarded + * argument, unknown ids fail quietly (no throw), listing is in registration order, and an + * unavailable command neither runs nor consumes its trigger. + */ +class CommandRegistryTest { + /** + * Invoking a registered command runs its handler and forwards the argument. + */ + @Test + fun invokesRegisteredCommandWithArgument() { + val registry = CommandRegistry() + var receivedArgument: Any? = "unset" + registry.register(Command("test.echo", title = null, handler = { argument -> receivedArgument = argument })) + + val found = registry.invoke("test.echo", "hello") + + assertTrue(found, "a registered command should be found") + assertEquals("hello", receivedArgument) + } + + /** + * Invoking an unknown id returns false and never throws - a stray key chord must not crash. + */ + @Test + fun unknownCommandReturnsFalse() { + val registry = CommandRegistry() + assertFalse(registry.invoke("does.not.exist")) + } + + /** + * Re-registering an id replaces the handler (last write wins). + */ + @Test + fun reRegisteringReplacesHandler() { + val registry = CommandRegistry() + var ran = "none" + registry.register(Command("test.x", title = null, handler = { ran = "first" })) + registry.register(Command("test.x", title = null, handler = { ran = "second" })) + + registry.invoke("test.x") + + assertEquals("second", ran) + } + + /** + * An unavailable command is not run and invoke() returns false, so the bound chord falls through + * unconsumed; the availability lambda is re-read on every invoke, so live context flips apply. + */ + @Test + fun unavailableCommandDoesNotRunAndReadsLiveContext() { + val registry = CommandRegistry() + var applicable = false + var runCount = 0 + registry.register( + Command("test.gated", title = null, availability = { applicable }, handler = { runCount++ }), + ) + + assertFalse(registry.invoke("test.gated"), "an unavailable command reports false") + assertEquals(0, runCount, "the handler never ran") + + applicable = true + assertTrue(registry.invoke("test.gated"), "the same registration applies once the context allows it") + assertEquals(1, runCount) + } + + /** + * all() lists commands in registration order; get() and unregister() behave. + */ + @Test + fun listsInRegistrationOrderAndUnregisters() { + val registry = CommandRegistry() + registry.register(Command("a", title = null, handler = {})) + registry.register(Command("b", title = null, handler = {})) + registry.register(Command("c", title = null, handler = {})) + + assertEquals(listOf("a", "b", "c"), registry.all().map { command -> command.id }) + + registry.unregister("b") + + assertEquals(listOf("a", "c"), registry.all().map { command -> command.id }) + assertNull(registry["b"]) + } + + /** + * The revision moves on every change to the table and on nothing else - it is what a composable + * listing all() subscribes to, since the table itself is a plain map. + */ + @Test + fun theRevisionMovesWithTheTable() { + val registry = CommandRegistry() + val initial = registry.revision + var runCount = 0 + + registry.register(Command("a", title = null, handler = { runCount++ })) + val afterRegister = registry.revision + assertTrue(afterRegister != initial, "registering moves it") + + // Invoked while registered, so the handler really runs: an invoke that found nothing returns before + // any bookkeeping a run could bump the revision from. + assertTrue(registry.invoke("a")) + assertEquals(1, runCount, "the invoke must reach the handler for this to mean anything") + assertEquals(afterRegister, registry.revision, "running a command does not change the table") + + registry.unregister("a") + val afterUnregister = registry.revision + assertTrue(afterUnregister != afterRegister, "unregistering moves it") + + registry.unregister("a") + assertEquals(afterUnregister, registry.revision, "unregistering an id that is not there changes nothing") + + registry.invoke("a") + assertEquals(afterUnregister, registry.revision, "and neither does invoking one") + } + + /** + * A command's spaces never gate dispatch. They filter the palette and the status bar; a chord still + * reaches the handler wherever the pointer is, and the handler decides what that press means. + */ + @Test + fun spacesNeverGateDispatch() { + val registry = CommandRegistry() + var runCount = 0 + registry.register(Command("test.scoped", title = null, spaces = CommandSpaces.UvEditor, handler = { runCount++ })) + + assertTrue(registry.invoke("test.scoped"), "the registry knows nothing about where the pointer is") + assertEquals(1, runCount) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandSearchTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandSearchTest.kt new file mode 100644 index 0000000..f73e913 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandSearchTest.kt @@ -0,0 +1,78 @@ +package org.umamo.ui.action + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * The palette ranking: label prefix > label word start > label substring > id-only substring, ties + * alphabetical, non-matches dropped. The "ac" case pins the property that matters most for usability: + * "Actual Size" must outrank the workspace commands that merely contain "ac". + */ +class CommandSearchTest { + private data class Entry(val id: String, val label: String) + + private fun rank(entries: List, query: String): List = + rankCommandMatches(entries, query, labelOf = { entry -> entry.label }, idOf = { entry -> entry.id }) + .map { entry -> entry.label } + + @Test + fun labelPrefixOutranksSubstringMatches() { + val entries = + listOf( + Entry("workspace.prev", "Previous Workspace"), + Entry("workspace.next", "Next Workspace"), + Entry("view.zoomActualSize", "Actual Size"), + ) + assertEquals( + listOf("Actual Size", "Next Workspace", "Previous Workspace"), + rank(entries, "ac"), + "the prefix match leads; the substring matches follow alphabetically", + ) + } + + @Test + fun wordStartOutranksMidWordSubstring() { + val entries = + listOf( + Entry("a", "Reincarnate"), // "in" mid-word + Entry("b", "Zoom In"), // "in" starts the second word + Entry("c", "Invert"), // "in" starts the label + ) + assertEquals(listOf("Invert", "Zoom In", "Reincarnate"), rank(entries, "in")) + } + + @Test + fun idOnlyMatchesRankLastAndPowerUserIdSearchWorks() { + val entries = + listOf( + Entry("view.zoomIn", "Zoom In"), + Entry("view.fit", "Fit View"), + ) + assertEquals(listOf("Fit View", "Zoom In"), rank(entries, "view."), "both match only by id; alphabetical") + assertEquals(listOf("Zoom In"), rank(entries, "zoomin"), "camelCase id substring hits") + } + + @Test + fun matchingIsCaseInsensitive() { + val entries = listOf(Entry("view.zoomActualSize", "Actual Size")) + assertEquals(listOf("Actual Size"), rank(entries, "ACTUAL")) + assertEquals(listOf("Actual Size"), rank(entries, "actual size")) + } + + @Test + fun nonMatchesAreDropped() { + val entries = listOf(Entry("view.fit", "Fit View"), Entry("edit.undo", "Undo")) + assertEquals(listOf("Undo"), rank(entries, "und")) + assertEquals(emptyList(), rank(entries, "xyzzy")) + } + + @Test + fun scoreTiersAreStable() { + assertEquals(0, commandMatchScore("Actual Size", "view.zoomActualSize", "ac")) + assertEquals(1, commandMatchScore("Zoom In", "view.zoomIn", "in")) + assertEquals(2, commandMatchScore("Previous Workspace", "workspace.prev", "ac")) + assertEquals(3, commandMatchScore("Fit View", "view.fit", "view.")) + assertNull(commandMatchScore("Fit View", "view.fit", "xyzzy")) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandSpacesTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandSpacesTest.kt new file mode 100644 index 0000000..c695794 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/CommandSpacesTest.kt @@ -0,0 +1,58 @@ +package org.umamo.ui.action + +import org.umamo.ui.workspace.SpaceKind +import kotlin.test.Test +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** Pins what each [CommandSpaces] shape answers, including for a pointer that has touched nothing yet. */ +class CommandSpacesTest { + /** Everywhere applies to every space, and also before the pointer has touched any. */ + @Test + fun everywhereAppliesToEverySpaceAndToNone() { + for (kind in SpaceKind.entries) { + assertTrue(CommandSpaces.Everywhere.appliesIn(kind), "Everywhere must cover $kind") + } + assertTrue(CommandSpaces.Everywhere.appliesIn(null), "a command that routes by nothing needs no surface") + } + + /** A scoped command applies in exactly its listed spaces. */ + @Test + fun aScopedCommandAppliesOnlyInItsSpaces() { + val spaces = CommandSpaces.of(SpaceKind.Viewport2D, SpaceKind.KeyformSheet) + for (kind in SpaceKind.entries) { + val expected = kind == SpaceKind.Viewport2D || kind == SpaceKind.KeyformSheet + assertTrue(spaces.appliesIn(kind) == expected, "$kind should ${if (expected) "" else "not "}be covered") + } + } + + /** + * Before the pointer touches any surface a scoped command applies nowhere - its handler would resolve + * no area to act in, so listing it would offer a guaranteed no-op. + */ + @Test + fun aScopedCommandAppliesNowhereBeforeAnySurfaceIsTouched() { + assertFalse(CommandSpaces.UvEditor.appliesIn(null)) + assertFalse(CommandSpaces.WorkSurfaces.appliesIn(null)) + } + + /** The named sets cover what their names say. */ + @Test + fun theNamedSetsCoverWhatTheyName() { + assertTrue(CommandSpaces.Viewport2D.appliesIn(SpaceKind.Viewport2D)) + assertFalse(CommandSpaces.Viewport2D.appliesIn(SpaceKind.UvEditor)) + assertTrue(CommandSpaces.UvEditor.appliesIn(SpaceKind.UvEditor)) + assertFalse(CommandSpaces.UvEditor.appliesIn(SpaceKind.Viewport2D)) + assertTrue(CommandSpaces.WorkSurfaces.appliesIn(SpaceKind.Viewport2D)) + assertTrue(CommandSpaces.WorkSurfaces.appliesIn(SpaceKind.UvEditor)) + assertFalse(CommandSpaces.WorkSurfaces.appliesIn(SpaceKind.Outliner)) + } + + /** A scope over no space is unrepresentable: it could never be shown, which is never what was meant. */ + @Test + fun aScopeOverNoSpaceIsRejected() { + assertFailsWith { CommandSpaces.Only(emptySet()) } + assertFailsWith { CommandSpaces.of() } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/action/KeymapPersistenceTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/KeymapPersistenceTest.kt new file mode 100644 index 0000000..3a57586 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/KeymapPersistenceTest.kt @@ -0,0 +1,116 @@ +package org.umamo.ui.action + +import okio.Path +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.settings.Settings +import org.umamo.storage.OkioAppStorage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Verifies settings-backed keymap resolution and mutation over an in-memory filesystem: preset selection, + * rebinding (move + conflict reassign), unbinding, and reset, each persisting across a fresh Settings load. + */ +class KeymapPersistenceTest { + private val configDir: Path = "/config".toPath() + + /** Defaults with the input.keybinding subtree the persistence reads/writes. */ + private val defaultJson = """{"input":{"keybinding":{"preset":"default","overrides":{}}}}""" + + /** A fresh in-memory storage rooted at /config + /data. */ + private fun storage(): OkioAppStorage { + val fileSystem = FakeFileSystem() + fileSystem.createDirectories(configDir) + return OkioAppStorage(fileSystem, configDir, "/data".toPath()) + } + + /** + * With no overrides, the resolved keymap is exactly the selected preset's bindings. + */ + @Test + fun resolvesSelectedPreset() { + val settings = Settings.load(storage(), defaultJson) + val keymap = loadKeymap(settings) + assertEquals("palette.toggle", keymap.commandFor(parseKeyChord("primary+KeyP")!!)) + assertEquals(parseKeyChord("primary+Digit0"), keymap.chordFor("view.fit")) + } + + /** + * Selecting a preset changes the base bindings (Blender frames all on Home - the context-aware + * frame.all, which resolves per hovered editor - and searches on F3). + */ + @Test + fun presetSelectionSwitchesBase() { + val storage = storage() + val settings = Settings.load(storage, defaultJson) + setKeymapPreset(settings, "blender") + + val keymap = loadKeymap(Settings.load(storage, defaultJson)) + assertEquals(parseKeyChord("Home"), keymap.chordFor("frame.all")) + assertEquals("palette.toggle", keymap.commandFor(parseKeyChord("F3")!!)) + } + + /** + * Rebinding moves a command to a new chord (releasing its preset chord) and survives a reload. + */ + @Test + fun rebindMovesBindingAndPersists() { + val storage = storage() + val settings = Settings.load(storage, defaultJson) + rebindCommand(settings, "view.fit", parseKeyChord("F5")!!) + + val keymap = loadKeymap(Settings.load(storage, defaultJson)) + assertEquals("view.fit", keymap.commandFor(parseKeyChord("F5")!!)) + // The preset chord it used to hold is now unbound (masked), so view.fit no longer answers to it. + assertNull(keymap.commandFor(parseKeyChord("primary+Digit0")!!)) + assertEquals(parseKeyChord("F5"), keymap.chordFor("view.fit")) + } + + /** + * Rebinding a command onto a chord another command holds reassigns it: the new command wins, the old + * one loses that chord. + */ + @Test + fun rebindOntoOccupiedChordReassigns() { + val storage = storage() + val settings = Settings.load(storage, defaultJson) + // primary+Digit0 is view.fit in the default preset; give it to view.zoomIn instead. + rebindCommand(settings, "view.zoomIn", parseKeyChord("primary+Digit0")!!) + + val keymap = loadKeymap(Settings.load(storage, defaultJson)) + assertEquals("view.zoomIn", keymap.commandFor(parseKeyChord("primary+Digit0")!!)) + } + + /** + * Unbinding clears a command's chord and persists, leaving other bindings intact. + */ + @Test + fun unbindClearsAndPersists() { + val storage = storage() + val settings = Settings.load(storage, defaultJson) + unbindCommand(settings, "view.fit") + + val keymap = loadKeymap(Settings.load(storage, defaultJson)) + assertNull(keymap.chordFor("view.fit")) + assertNull(keymap.commandFor(parseKeyChord("primary+Digit0")!!)) + // An untouched binding is still present. + assertEquals("file.open", keymap.commandFor(parseKeyChord("primary+KeyO")!!)) + } + + /** + * Reset clears all overrides, restoring the selected preset's bindings (preset choice unchanged). + */ + @Test + fun resetRestoresPreset() { + val storage = storage() + val settings = Settings.load(storage, defaultJson) + rebindCommand(settings, "view.fit", parseKeyChord("F5")!!) + resetKeymapOverrides(settings) + + val keymap = loadKeymap(Settings.load(storage, defaultJson)) + assertEquals(parseKeyChord("primary+Digit0"), keymap.chordFor("view.fit")) + assertNull(keymap.commandFor(parseKeyChord("F5")!!)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/action/KeymapTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/KeymapTest.kt new file mode 100644 index 0000000..9212b02 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/action/KeymapTest.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.action + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull + +/** + * Verifies chord parsing (logical primary modifier, position-based key, malformed rejection) and + * keymap lookup. + */ +class KeymapTest { + /** + * A full modifier+key spec parses into the expected chord, case- and whitespace-insensitive on modifiers. + */ + @Test + fun parsesModifiersAndKey() { + assertEquals( + KeyChord(keyName = "KeyP", primaryModifier = true, shift = true, alt = false), + parseKeyChord(" primary + Shift + KeyP "), + ) + } + + /** + * "cmd"/"ctrl"/"control" all map to the single logical primary modifier. + */ + @Test + fun primaryModifierAliasesUnify() { + val viaCmd = parseKeyChord("cmd+KeyA") + val viaCtrl = parseKeyChord("ctrl+KeyA") + assertEquals(viaCmd, viaCtrl) + assertEquals(KeyChord(keyName = "KeyA", primaryModifier = true), viaCmd) + } + + /** + * A bare key with no modifiers parses; an unknown modifier or empty spec is rejected. + */ + @Test + fun bareKeyParsesAndMalformedIsRejected() { + assertEquals(KeyChord(keyName = "KeyF"), parseKeyChord("KeyF")) + assertNull(parseKeyChord("hyper+KeyF")) + assertNull(parseKeyChord("")) + assertNull(parseKeyChord("+")) + } + + /** + * A keymap built from specs resolves a bound chord to its command id and an unbound chord to null. + */ + @Test + fun keymapLooksUpBoundChord() { + val keymap = Keymap.fromSpecs(mapOf("primary+KeyP" to "palette.toggle")) + assertEquals("palette.toggle", keymap.commandFor(parseKeyChord("primary+KeyP")!!)) + assertNull(keymap.commandFor(parseKeyChord("primary+KeyQ")!!)) + } + + /** + * Every built-in preset builds without duplicate chords (presetSpecs refuses them at construction, so + * merely reading each preset asserts it), and Home resolves to the context-aware frame command in the + * presets that bind it. mapOf's silent last-wins once left the Blender preset with two Home entries + * and keyform.frameAll unbound, invisible even to the keybindings editor's conflict detection. + */ + @Test + fun presetsHaveNoDuplicateChordsAndHomeFramesContextually() { + for (presetId in listOf("default", "cubism", "blender")) { + val specs = keymapPresetSpecs(presetId) + assertEquals(specs.size, specs.keys.distinct().size, "$presetId: chords are unique") + } + assertEquals("frame.all", keymapPresetSpecs("default")["Home"], "default Home is the context-aware frame") + assertEquals("frame.all", keymapPresetSpecs("blender")["Home"], "blender Home is the context-aware frame") + } + + /** + * Every preset reaches the document commands a rigger starts from, under the accelerators every other + * application uses for them: New, Open, Save, and Save As on their usual keys, the artwork import + * - which ADDS to the open document - keeping the chord it has always had so a rebind saved against that + * id still resolves, and Import CMO3 with no chord at all, since an import is not an open. + */ + @Test + fun everyPresetBindsTheDocumentCommands() { + for (presetId in listOf("default", "cubism", "blender")) { + val specs = keymapPresetSpecs(presetId) + assertEquals("file.new", specs["primary+KeyN"], "$presetId: Ctrl+N starts a new document") + assertEquals("file.open", specs["primary+KeyO"], "$presetId: Ctrl+O opens a document") + assertEquals("file.save", specs["primary+KeyS"], "$presetId: Ctrl+S saves") + assertEquals("file.saveAs", specs["primary+shift+KeyS"], "$presetId: Ctrl+Shift+S saves as") + assertEquals("file.importArtwork", specs["primary+shift+KeyO"], "$presetId: Ctrl+Shift+O imports artwork") + assertFalse(specs.containsValue("file.importCmo3"), "$presetId: Import CMO3 has no chord") + } + } + + /** + * A malformed spec is dropped from the keymap rather than shadowing valid bindings. + */ + @Test + fun malformedSpecIsDropped() { + // "hyper+KeyF" has an unrecognised modifier, so parseKeyChord rejects it and it is dropped. + val keymap = Keymap.fromSpecs(mapOf("primary+KeyP" to "palette.toggle", "hyper+KeyF" to "nope")) + assertEquals(1, keymap.size()) + } + + /** + * The reverse lookup resolves a command id to its bound chord, and an unbound id to null. + */ + @Test + fun chordForResolvesBoundCommand() { + val keymap = Keymap.fromSpecs(mapOf("primary+KeyO" to "file.open")) + assertEquals(KeyChord(keyName = "KeyO", primaryModifier = true), keymap.chordFor("file.open")) + assertNull(keymap.chordFor("file.close")) + } + + /** + * When several chords bind one command, the reverse lookup returns the first in insertion order, so a + * menu shows the canonical accelerator (primary+KeyP) rather than the secondary (Space). + */ + @Test + fun chordForReturnsFirstBindingWhenSeveral() { + val keymap = Keymap.fromSpecs(mapOf("primary+KeyP" to "palette.toggle", "Space" to "palette.toggle")) + assertEquals(KeyChord(keyName = "KeyP", primaryModifier = true), keymap.chordFor("palette.toggle")) + } + + /** + * The default keymap opens the palette on both Space (the Blender-style headline default) and the + * primary modifier + P (the familiar accelerator), and resolves primary+P as the canonical chord the + * palette / menu shows as the hint. Guards the Space-default requirement and the keybind-hint feature. + */ + @Test + fun defaultKeymapBindsPaletteToggleToSpaceAndPrimaryP() { + val keymap = defaultKeymap() + assertEquals("palette.toggle", keymap.commandFor(KeyChord(keyName = "Space"))) + assertEquals("palette.toggle", keymap.commandFor(KeyChord(keyName = "KeyP", primaryModifier = true))) + assertEquals(KeyChord(keyName = "KeyP", primaryModifier = true), keymap.chordFor("palette.toggle")) + } + + /** + * Bare 1 / 2 / 3 switch the Edit-mode select modes (Blender's convention) in the default and blender + * presets, and stay unbound in the cubism preset (which carries no Blender edit-mode family). + */ + @Test + fun selectModeDigitsBindInDefaultAndBlenderButNotCubism() { + for (presetId in listOf("default", "blender")) { + val keymap = Keymap.fromSpecs(keymapPresetSpecs(presetId)) + assertEquals("mesh.selectMode.vertex", keymap.commandFor(KeyChord(keyName = "Digit1")), "Digit1 in $presetId") + assertEquals("mesh.selectMode.edge", keymap.commandFor(KeyChord(keyName = "Digit2")), "Digit2 in $presetId") + assertEquals("mesh.selectMode.face", keymap.commandFor(KeyChord(keyName = "Digit3")), "Digit3 in $presetId") + } + val cubism = Keymap.fromSpecs(keymapPresetSpecs("cubism")) + assertNull(cubism.commandFor(KeyChord(keyName = "Digit1"))) + assertNull(cubism.commandFor(KeyChord(keyName = "Digit2"))) + assertNull(cubism.commandFor(KeyChord(keyName = "Digit3"))) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/app/ExitGuardTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/app/ExitGuardTest.kt new file mode 100644 index 0000000..882ef8c --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/app/ExitGuardTest.kt @@ -0,0 +1,70 @@ +package org.umamo.ui.app + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +/** + * Pins the host-side half of the quit guard: who decides, and what happens when nobody does. + * + * Both failure modes are silent and bad in opposite directions. A guard that is never consulted means + * the window's close button drops unsaved work without asking; a request that goes nowhere when no + * guard is installed means the close button stops closing the app at all. + */ +class ExitGuardTest { + @Test + fun withNoGuardInstalledTheExitRunsAtOnce() { + val guard = ExitGuard() + var exitCount = 0 + + guard.request { exitCount++ } + + assertEquals(1, exitCount) + } + + @Test + fun anInstalledGuardReceivesTheExitAndDecidesWhenItRuns() { + val guard = ExitGuard() + var exitCount = 0 + var held: (() -> Unit)? = null + guard.install { exit -> held = exit } + + guard.request { exitCount++ } + + assertEquals(0, exitCount, "the guard holds the exit while it asks") + assertNotNull(held, "and keeps it to run later") + held.invoke() + assertEquals(1, exitCount) + } + + @Test + fun uninstallingRestoresTheDirectExit() { + val guard = ExitGuard() + var guardedCount = 0 + var exitCount = 0 + val cleanup = guard.install { guardedCount++ } + + cleanup() + guard.request { exitCount++ } + + assertEquals(0, guardedCount) + assertEquals(1, exitCount) + } + + @Test + fun aStaleCleanupLeavesAReplacementGuardInPlace() { + // The shell re-installs before a disposed composition's cleanup runs; a cleanup that cleared the + // slot blindly would leave the app unguarded from then on. + val guard = ExitGuard() + var replacementCount = 0 + var exitCount = 0 + val staleCleanup = guard.install { } + guard.install { replacementCount++ } + + staleCleanup() + guard.request { exitCount++ } + + assertEquals(1, replacementCount) + assertEquals(0, exitCount) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/graphics/ColorRgbBridgeTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/graphics/ColorRgbBridgeTest.kt new file mode 100644 index 0000000..b325887 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/graphics/ColorRgbBridgeTest.kt @@ -0,0 +1,39 @@ +package org.umamo.ui.graphics + +import androidx.compose.ui.graphics.Color +import org.umamo.runtime.model.ColorRgb +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the [ColorRgb] <-> Compose [Color] bridge the composite color pickers ride on: the identities map + * to opaque white / black (and their canonical hex), an arbitrary color round-trips within float + * tolerance, and the Color -> ColorRgb direction drops alpha. + */ +class ColorRgbBridgeTest { + @Test + fun identitiesMapToOpaqueWhiteAndBlack() { + assertEquals(Color(1f, 1f, 1f, 1f), ColorRgb.MultiplyIdentity.toComposeColor()) + assertEquals(Color(0f, 0f, 0f, 1f), ColorRgb.ScreenIdentity.toComposeColor()) + // Via the existing hex helpers - the canonical #AARRGGBB the field displays. + assertEquals("#FFFFFFFF", formatHexColor(ColorRgb.MultiplyIdentity.toComposeColor())) + assertEquals("#FF000000", formatHexColor(ColorRgb.ScreenIdentity.toComposeColor())) + } + + @Test + fun composeColorDropsAlphaBackToColorRgb() { + // A half-transparent red still yields the opaque-channel ColorRgb (alpha is not modeled). + assertEquals(ColorRgb(1f, 0f, 0f), Color(1f, 0f, 0f, 0.5f).toColorRgb()) + // Parsed hex round-trips exactly at 8-bit boundaries. + assertEquals(ColorRgb(1f, 0f, 0f), parseHexColor("#FF0000")!!.toColorRgb()) + } + + @Test + fun arbitraryColorRoundTripsWithinTolerance() { + val original = ColorRgb(0.25f, 0.5f, 0.75f) + val roundTripped = original.toComposeColor().toColorRgb() + assertEquals(original.red, roundTripped.red, 0.005f) + assertEquals(original.green, roundTripped.green, 0.005f) + assertEquals(original.blue, roundTripped.blue, 0.005f) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/graphics/HexColorTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/graphics/HexColorTest.kt new file mode 100644 index 0000000..9769928 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/graphics/HexColorTest.kt @@ -0,0 +1,48 @@ +package org.umamo.ui.graphics + +import androidx.compose.ui.graphics.Color +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Verifies hex color parsing (8-digit AARRGGBB, 6-digit opaque RRGGBB, tolerant of '#' and whitespace, + * strict against everything else) and that formatting round-trips to the canonical form. + */ +class HexColorTest { + /** An 8-digit string parses as AARRGGBB, with or without the leading '#'. */ + @Test + fun parsesEightDigitArgb() { + assertEquals(Color(0xCCFF9800), parseHexColor("#CCFF9800")) + assertEquals(Color(0xCCFF9800), parseHexColor("CCFF9800")) + assertEquals(Color(0xCCFF9800), parseHexColor(" #ccff9800 "), "case- and whitespace-insensitive") + } + + /** A 6-digit string parses as opaque RRGGBB. */ + @Test + fun parsesSixDigitRgbAsOpaque() { + assertEquals(Color(0xFF2962FF), parseHexColor("#2962FF")) + assertEquals(Color(0xFF2962FF), parseHexColor("2962ff")) + } + + /** Wrong lengths, non-hex characters, signs, and empty input are rejected. */ + @Test + fun rejectsInvalidInput() { + assertNull(parseHexColor("")) + assertNull(parseHexColor("#")) + assertNull(parseHexColor("#12345"), "five digits") + assertNull(parseHexColor("#1234567"), "seven digits") + assertNull(parseHexColor("#123456789"), "nine digits") + assertNull(parseHexColor("#GGHHIIJJ"), "non-hex characters") + assertNull(parseHexColor("-2962FF0"), "a sign is not a hex digit") + assertNull(parseHexColor("#2962 FF"), "interior whitespace") + } + + /** Formatting produces the canonical uppercase "#AARRGGBB", and a parse-format cycle round-trips. */ + @Test + fun formatsCanonicallyAndRoundTrips() { + assertEquals("#CCFF9800", formatHexColor(Color(0xCCFF9800))) + assertEquals("#FF2962FF", formatHexColor(parseHexColor("2962ff")!!)) + assertEquals("#66888888", formatHexColor(parseHexColor("#66888888")!!)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/DoubleClickTrackerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/DoubleClickTrackerTest.kt new file mode 100644 index 0000000..d55615c --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/DoubleClickTrackerTest.kt @@ -0,0 +1,80 @@ +package org.umamo.ui.kit + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The press-to-press timing every double-click in the editor shares: the outliner rows, the parameter + * names and group headers, and the workspace tabs. + */ +class DoubleClickTrackerTest { + /** A press inside the window after an unmodified press completes a double click; the edge counts. */ + @Test + fun aSecondPressInsideTheWindowPairs() { + val tracker = DoubleClickTracker(windowMillis = 300L) + assertFalse(tracker.registerPress(10_000L), "the first press only arms") + assertTrue(tracker.registerPress(10_120L), "a press 120ms later is the second half") + + val edgeTracker = DoubleClickTracker(windowMillis = 300L) + edgeTracker.registerPress(10_000L) + assertTrue(edgeTracker.registerPress(10_300L), "the window is inclusive") + } + + /** A press past the window does not pair, and arms in its own right. */ + @Test + fun aLatePressArmsAgain() { + val tracker = DoubleClickTracker(windowMillis = 300L) + tracker.registerPress(10_000L) + assertFalse(tracker.registerPress(10_301L), "one millisecond late is a new single") + assertTrue(tracker.registerPress(10_400L), "and that single arms the next double") + } + + /** A completed double clears the pending press, so a third quick press is a fresh single. */ + @Test + fun aThirdQuickPressStartsFresh() { + val tracker = DoubleClickTracker(windowMillis = 300L) + tracker.registerPress(10_000L) + assertTrue(tracker.registerPress(10_100L)) + assertFalse(tracker.registerPress(10_200L), "a triple click is a double, then a single") + } + + /** + * A modified press never takes part in a double click, on either side of the pair. Ctrl-clicking a row + * twice toggles it in and out, and a plain click right after a Ctrl-click selects rather than renames. + */ + @Test + fun aModifiedPressNeverPairs() { + val secondModified = DoubleClickTracker(windowMillis = 300L) + secondModified.registerPress(10_000L) + assertFalse(secondModified.registerPress(10_100L, modified = true), "a modified second press") + + val firstModified = DoubleClickTracker(windowMillis = 300L) + firstModified.registerPress(10_000L, modified = true) + assertFalse(firstModified.registerPress(10_100L), "a plain press right after a modified one") + assertTrue(firstModified.registerPress(10_200L), "which arms normally itself") + + val bothModified = DoubleClickTracker(windowMillis = 300L) + bothModified.registerPress(10_000L, modified = true) + assertFalse(bothModified.registerPress(10_100L, modified = true), "two modified presses") + } + + /** Reset forgets the pending press. */ + @Test + fun resetForgetsThePendingPress() { + val tracker = DoubleClickTracker(windowMillis = 300L) + tracker.registerPress(10_000L) + tracker.reset() + assertFalse(tracker.registerPress(10_100L)) + } + + /** The very first press is never a double, however early in the clock it lands. */ + @Test + fun anEarlyFirstPressIsNotADouble() { + val tracker = DoubleClickTracker(windowMillis = 300L) + assertFalse(tracker.registerPress(0L)) + + val nearZero = DoubleClickTracker(windowMillis = 300L) + assertFalse(nearZero.registerPress(100L)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/MenuPositionTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/MenuPositionTest.kt new file mode 100644 index 0000000..ea8ceac --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/MenuPositionTest.kt @@ -0,0 +1,49 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the dropdown placement geometry: a menu drops below its anchor when it fits, flips above when it + * would overflow the window bottom, and clamps when it fits neither way. This is the regression the long + * Masked By list exposed - the provider used to return the anchor's bottom unconditionally, so a tall menu + * ran off screen and its tail was unreachable. + */ +class MenuPositionTest { + private val window = IntSize(1000, 800) + + private fun positionOf(anchor: IntRect, popup: IntSize): IntOffset = + BelowAnchorPositionProvider.calculatePosition(anchor, window, LayoutDirection.Ltr, popup) + + @Test + fun dropsBelowTheAnchorWhenItFits() { + // Anchor near the top; a short menu fits underneath, so it opens at the anchor's bottom-left. + assertEquals(IntOffset(120, 60), positionOf(IntRect(120, 40, 300, 60), IntSize(180, 200))) + } + + @Test + fun flipsAboveWhenItWouldOverflowTheBottom() { + // Anchor near the bottom (bottom edge 760) with a 300-tall menu: 760 + 300 > 800, and there is room + // above (700 - 300 = 400 >= 0), so it opens upward ending at the anchor's top. + assertEquals(IntOffset(120, 400), positionOf(IntRect(120, 700, 300, 760), IntSize(180, 300))) + } + + @Test + fun clampsWhenItFitsNeitherAboveNorBelow() { + // A 700-tall menu on an anchor mid-window fits neither way, so it is pushed up to sit fully on screen. + assertEquals(IntOffset(0, 100), positionOf(IntRect(0, 400, 180, 440), IntSize(180, 700))) + // Taller than the whole window: start at the top edge and let it scroll. + assertEquals(IntOffset(0, 0), positionOf(IntRect(0, 400, 180, 440), IntSize(180, 900))) + } + + @Test + fun clampsTheLeftEdgeIntoTheWindow() { + // An anchor near the right edge would push a wide menu past it; the left is pulled back so the whole + // menu stays on screen. + assertEquals(IntOffset(700, 60), positionOf(IntRect(950, 40, 990, 60), IntSize(300, 100))) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/NumberFieldMathTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/NumberFieldMathTest.kt new file mode 100644 index 0000000..60b3e2e --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/NumberFieldMathTest.kt @@ -0,0 +1,119 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.shape.ZeroCornerSize +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.ui.unit.dp +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the pure numeric-field math and the stacked-corner helper: the min-max fill fraction (bounded vs + * unbounded), display / storage rounding, fixed-decimal formatting, the drag-scrub value mapping, and the + * stack-position corner shaping the vertical numeric-field stack and horizontal ButtonGroup share. + */ +class NumberFieldMathTest { + @Test + fun fillFractionIsThePositionInABoundedRangeElseNull() { + assertEquals(0.5f, numberFieldFillFraction(5f, 0f, 10f)) + assertEquals(0f, numberFieldFillFraction(-3f, 0f, 10f)) + assertEquals(1f, numberFieldFillFraction(99f, 0f, 10f)) + // Unbounded (infinite endpoint) or a degenerate range draws no fill. + assertNull(numberFieldFillFraction(5f, 0f, Float.POSITIVE_INFINITY)) + assertNull(numberFieldFillFraction(5f, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY)) + assertNull(numberFieldFillFraction(5f, 10f, 10f)) + } + + @Test + fun roundToDecimalsRoundsAndCaps() { + assertEquals(2f, roundToDecimals(1.6f, 0)) + assertEquals(1.5f, roundToDecimals(1.49f, 1)) + assertEquals(1.23f, roundToDecimals(1.2345f, 2)) + // Beyond the Float storage cap the extra places are dropped (no more than NUMBER_FIELD_STORAGE_DECIMALS). + val capped = roundToDecimals(1.123456789f, 12) + assertEquals(roundToDecimals(1.123456789f, NUMBER_FIELD_STORAGE_DECIMALS), capped) + } + + @Test + fun formatDecimalsPadsToFixedWidth() { + assertEquals("1920", formatDecimals(1920f, 0)) + assertEquals("0.50", formatDecimals(0.5f, 2)) + assertEquals("1.20", formatDecimals(1.2f, 2)) + assertEquals("-3.5", formatDecimals(-3.5f, 1)) + assertEquals("0.000", formatDecimals(0f, 3)) + } + + @Test + fun scrubValueMapsDeltaToStepsAndClamps() { + // One step per NUMBER_FIELD_SCRUB_PIXELS_PER_STEP pixels; rightward increases. + val tenNotches = NUMBER_FIELD_SCRUB_PIXELS_PER_STEP * 10f + assertEquals(10f, scrubValue(0f, tenNotches, 1f, -100f..100f)) + assertEquals(-10f, scrubValue(0f, -tenNotches, 1f, -100f..100f)) + // Clamped to the range. + assertEquals(5f, scrubValue(0f, tenNotches * 100f, 1f, 0f..5f)) + } + + @Test + fun stackPositionResolvesFromIndexAndCount() { + assertEquals(StackPosition.Single, stackPositionOf(0, 1)) + assertEquals(StackPosition.First, stackPositionOf(0, 3)) + assertEquals(StackPosition.Middle, stackPositionOf(1, 3)) + assertEquals(StackPosition.Last, stackPositionOf(2, 3)) + } + + @Test + fun stackedShapeSquaresTheSharedEdges() { + val group = RoundedCornerShape(4.dp) + + // A standalone control keeps the full rounding; a middle control is fully square. + assertSame(group, stackedShape(group, StackPosition.Single, StackAxis.Vertical)) + assertSame(RectangleShape, stackedShape(group, StackPosition.Middle, StackAxis.Vertical)) + + // A vertical run squares the bottom of the first item and the top of the last. + assertEquals( + group.copy(bottomStart = ZeroCornerSize, bottomEnd = ZeroCornerSize), + stackedShape(group, StackPosition.First, StackAxis.Vertical), + ) + assertEquals( + group.copy(topStart = ZeroCornerSize, topEnd = ZeroCornerSize), + stackedShape(group, StackPosition.Last, StackAxis.Vertical), + ) + + // A horizontal run squares the trailing edge of the first item instead. + assertEquals( + group.copy(topEnd = ZeroCornerSize, bottomEnd = ZeroCornerSize), + stackedShape(group, StackPosition.First, StackAxis.Horizontal), + ) + + // The First and Last shapes genuinely differ from the standalone rounding. + assertTrue(stackedShape(group, StackPosition.First, StackAxis.Vertical) != group) + } + + /** + * A scrub maps the TOTAL pointer delta onto a FIXED base, so the caller must latch the value the drag + * started from rather than re-reading the live one. + * + * This is the contract `NumberFieldCore` has to honour, and honouring it stopped being automatic once + * fields gained a live preview: the property rows feed each previewed value straight back in, so the + * live value moves during the drag. Passing that moving value as the base compounds the movement - + * the scrub accelerates, and reversing direction spends its first stretch unwinding the drift. + */ + @Test + fun scrubbingIsLinearInTheTotalDeltaFromAFixedBase() { + val range = 0f..1000f + val base = 100f + // Six pixels per step, so 60px of total travel is ten steps whatever route the pointer took. + assertEquals(110f, scrubValue(base, 60f, step = 1f, range = range), 1e-4f) + assertEquals(120f, scrubValue(base, 120f, step = 1f, range = range), 1e-4f) + // Returning the pointer to where it started returns the value to where it started. + assertEquals(base, scrubValue(base, 0f, step = 1f, range = range), 1e-4f) + + // Feeding each result back in as the next base is what the bug did: the same 120px of travel, + // reported in two frames, lands somewhere else entirely. + val compounded = scrubValue(scrubValue(base, 60f, step = 1f, range = range), 120f, step = 1f, range = range) + assertEquals(130f, compounded, 1e-4f, "a drifting base overshoots - which is why the base is latched") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/OverflowRowPackingTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/OverflowRowPackingTest.kt new file mode 100644 index 0000000..a75603d --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/OverflowRowPackingTest.kt @@ -0,0 +1,367 @@ +package org.umamo.ui.kit + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the pure strip-packing math: which controls fit, where they land, how the flexible gaps + * split the leftover, and - the properties the whole design rests on - that a collapsed control is + * never measured, and that a control once collapsed never pops back as the strip keeps narrowing. + */ +class OverflowRowPackingTest { + private val collapsible = OverflowSlotSpec(OverflowSlotKind.Collapsible) + private val pinned = OverflowSlotSpec(OverflowSlotKind.Pinned) + + /** + * A flexible gap of the given weight. + * + * @param Float weight The gap's share of the leftover. + * @return OverflowSlotSpec The gap spec. + */ + private fun flexible(weight: Float = 1f): OverflowSlotSpec = OverflowSlotSpec(OverflowSlotKind.Flexible, weight) + + /** + * Packs [slots] against a fixed-width strip, measuring every slot at the matching entry of [widths]. + * + * @param List slots The declared slots. + * @param List widths Each slot's natural width; a Flexible slot's entry is ignored. + * @param Int availableWidthPx The strip's width. + * @param Int spacingPx The gap between adjacent placed slots. + * @param Int overflowButtonWidthPx The overflow chip's width. + * @return OverflowRowPacking The resolved strip. + */ + private fun pack( + slots: List, + widths: List, + availableWidthPx: Int, + spacingPx: Int = 10, + overflowButtonWidthPx: Int = 20, + ): OverflowRowPacking = + packOverflowRow( + slots = slots, + availableWidthPx = availableWidthPx, + boundedWidth = true, + spacingPx = spacingPx, + overflowButtonWidthPx = overflowButtonWidthPx, + slotWidthPx = { slotIndex, _ -> widths[slotIndex] }, + ) + + /** + * Packs [slots] with a measure that honors the offered maximum, the way a real control does - a + * Modifier.width caps at the incoming constraint, so a compressible slot reports the smaller of its + * natural width and the room it was handed. + * + * @param List slots The declared slots. + * @param List naturalWidths Each slot's unconstrained width. + * @param Int availableWidthPx The strip's width. + * @return OverflowRowPacking The resolved strip. + */ + private fun packWithMeasure( + slots: List, + naturalWidths: List, + availableWidthPx: Int, + ): OverflowRowPacking = + packOverflowRow( + slots = slots, + availableWidthPx = availableWidthPx, + boundedWidth = true, + spacingPx = 10, + overflowButtonWidthPx = 20, + slotWidthPx = { slotIndex, maxWidthPx -> minOf(naturalWidths[slotIndex], maxWidthPx) }, + ) + + /** With room to spare every slot is placed and the chip is measured but never positioned. */ + @Test + fun everythingFitsPlacesEverySlotAndHidesTheChip() { + val packing = pack(slots = listOf(collapsible, collapsible, collapsible), widths = listOf(30, 30, 30), availableWidthPx = 500) + assertEquals(listOf(0, 1, 2), packing.placements.map { it.slotIndex }) + assertEquals(listOf(0, 40, 80), packing.placements.map { it.xPx }) + assertTrue(packing.collapsedSlotIndices.isEmpty()) + assertNull(packing.overflowButtonXPx) + } + + /** The first slot that will not fit takes every later collapsible slot down with it. */ + @Test + fun theFirstMissFlushesEveryLaterCollapsibleSlot() { + // Budget is 100 - 20 = 80. Slots 0 and 1 use 30 + 10 + 30 = 70; slot 2 would need 110. + val packing = pack(slots = listOf(collapsible, collapsible, collapsible), widths = listOf(30, 30, 30), availableWidthPx = 100) + assertEquals(listOf(0, 1), packing.placements.map { it.slotIndex }) + assertEquals(listOf(2), packing.collapsedSlotIndices) + assertEquals(80, packing.overflowButtonXPx) + } + + /** A later collapsible slot does NOT sneak in behind an earlier one that missed. */ + @Test + fun aNarrowSlotAfterTheCollapsePointStillCollapses() { + val packing = pack(slots = listOf(collapsible, collapsible, collapsible), widths = listOf(60, 60, 1), availableWidthPx = 100) + assertEquals(listOf(0), packing.placements.map { it.slotIndex }) + assertEquals(listOf(1, 2), packing.collapsedSlotIndices) + } + + /** A pinned slot is always placed, and its width is reserved before an earlier slot is admitted. */ + @Test + fun aTrailingPinnedSlotIsReservedForAndAlwaysPlaced() { + // Reserving the trailing pinned 50 (+10 spacing) leaves 10, so the leading 30 cannot fit. + val packing = pack(slots = listOf(collapsible, pinned), widths = listOf(30, 50), availableWidthPx = 70) + assertEquals(listOf(1), packing.placements.map { it.slotIndex }) + assertEquals(listOf(0), packing.collapsedSlotIndices) + } + + /** + * A strip whose controls all fit at the full width is not charged for a chip it will not show. + * + * The regression: the chip's width used to come off the budget on every decision, so the last control + * collapsed roughly a chip early - visibly so, with slack still sitting in the flexible gaps. + */ + @Test + fun nothingIsChargedForTheChipWhenEverythingFits() { + // 30 + 10 + 50 = 90, which fits 100 exactly - but not 100 minus a 20-wide chip. + val packing = pack(slots = listOf(collapsible, collapsible), widths = listOf(30, 50), availableWidthPx = 100) + assertEquals(listOf(0, 1), packing.placements.map { it.slotIndex }) + assertTrue(packing.collapsedSlotIndices.isEmpty()) + assertNull(packing.overflowButtonXPx) + } + + /** Once something genuinely misses, the chip is real and the second walk charges for it. */ + @Test + fun theChipIsChargedForOnceSomethingMisses() { + // 30 + 10 + 90 = 130 misses 100 outright, so the chip exists and the budget drops to 80. + val packing = pack(slots = listOf(collapsible, collapsible), widths = listOf(30, 90), availableWidthPx = 100) + assertEquals(listOf(0), packing.placements.map { it.slotIndex }) + assertEquals(listOf(1), packing.collapsedSlotIndices) + assertEquals(80, packing.overflowButtonXPx) + } + + /** A pinned slot is placed even when it alone overruns the strip - clipped, never hidden. */ + @Test + fun aPinnedSlotOverrunsRatherThanDisappearing() { + val packing = pack(slots = listOf(pinned, pinned), widths = listOf(40, 40), availableWidthPx = 30) + assertEquals(listOf(0, 1), packing.placements.map { it.slotIndex }) + assertEquals(listOf(0, 50), packing.placements.map { it.xPx }) + assertTrue(packing.placements.all { it.widthPx > 0 }) + } + + /** Leftover width goes to the flexible gaps, split by weight and summing exactly. */ + @Test + fun flexibleGapsSplitTheLeftoverByWeight() { + val packing = + pack( + slots = listOf(flexible(1f), collapsible, flexible(3f)), + widths = listOf(0, 40, 0), + availableWidthPx = 140, + ) + val gapWidths = packing.placements.filter { it.slotIndex != 1 }.map { it.widthPx } + assertEquals(100, gapWidths.sum()) + assertEquals(listOf(25, 75), gapWidths) + } + + /** The rounding remainder is handed out so the gaps sum to exactly the leftover, never one pixel short. */ + @Test + fun theRoundingRemainderIsDistributedNotDropped() { + val packing = + pack( + slots = listOf(flexible(1f), flexible(1f), flexible(1f)), + widths = listOf(0, 0, 0), + availableWidthPx = 100, + ) + assertEquals(100, packing.placements.sumOf { it.widthPx }) + } + + /** A flexible gap IS the separation, so it adds no spacing of its own on either side. */ + @Test + fun aFlexibleGapSuppressesSpacingOnBothSides() { + // 200 wide, two 30-wide controls either side of one gap: the gap absorbs 140 and no 10px spacing + // is inserted anywhere, so the trailing control's left edge is exactly 30 + 140. + val packing = + pack( + slots = listOf(collapsible, flexible(), collapsible), + widths = listOf(30, 0, 30), + availableWidthPx = 200, + ) + assertEquals(listOf(0, 30, 170), packing.placements.map { it.xPx }) + assertEquals(140, packing.placements[1].widthPx) + } + + /** A slot that measures zero is dropped whole: no spacing, not placed, absent from the dropdown. */ + @Test + fun aZeroWidthSlotCostsNothing() { + val packing = pack(slots = listOf(collapsible, collapsible, collapsible), widths = listOf(30, 0, 30), availableWidthPx = 500) + assertEquals(listOf(0, 2), packing.placements.map { it.slotIndex }) + // 30 + one 10px gap - the dropped slot contributes no spacing of its own. + assertEquals(listOf(0, 40), packing.placements.map { it.xPx }) + assertTrue(packing.collapsedSlotIndices.isEmpty()) + } + + /** The chip's width is reserved while packing, then handed back to the gaps when nothing collapsed. */ + @Test + fun theReservedChipWidthReturnsToTheGapsWhenNothingCollapses() { + val packing = pack(slots = listOf(collapsible, flexible()), widths = listOf(30, 0), availableWidthPx = 200) + assertNull(packing.overflowButtonXPx) + // The full 170 is shared out, not 170 minus the 20 the packer reserved while deciding. + assertEquals(170, packing.placements.first { it.slotIndex == 1 }.widthPx) + } + + /** A collapsed slot is never measured - composing a control only to hide it is the cost this avoids. */ + @Test + fun collapsedSlotsAreNeverMeasured() { + val measuredIndices = mutableListOf() + val widths = listOf(20, 60, 60, 40) + val packing = + packOverflowRow( + slots = listOf(collapsible, collapsible, collapsible, pinned), + availableWidthPx = 100, + boundedWidth = true, + spacingPx = 10, + overflowButtonWidthPx = 20, + slotWidthPx = { slotIndex, _ -> + measuredIndices.add(slotIndex) + widths[slotIndex] + }, + ) + assertEquals(listOf(1, 2), packing.collapsedSlotIndices) + assertEquals(listOf(0, 3), packing.placements.map { it.slotIndex }) + // The pinned slot is always measured (its width is reserved for) and slot 1 is the miss that + // latches collapsing, but slot 2 is behind the latch and is never composed at all. A slot CAN be + // asked twice, once per walk - the caller composes once and re-measures, so that costs no composition. + assertTrue(3 in measuredIndices) + assertTrue(2 !in measuredIndices) + } + + /** Narrowing the strip only ever collapses more - the unconditional chip reserve rules out oscillation. */ + @Test + fun collapsingIsMonotoneAsTheStripNarrows() { + val widths = listOf(40, 40, 40, 40) + val slots = listOf(collapsible, collapsible, collapsible, collapsible) + var previousCollapsed = emptySet() + for (availableWidthPx in 300 downTo 0 step 1) { + val collapsed = pack(slots = slots, widths = widths, availableWidthPx = availableWidthPx).collapsedSlotIndices.toSet() + assertTrue( + previousCollapsed.all { slotIndex -> slotIndex in collapsed }, + "width $availableWidthPx un-collapsed ${previousCollapsed - collapsed}", + ) + previousCollapsed = collapsed + } + } + + /** + * A compressible slot gives up width to keep the controls behind it on the strip. + * + * The regression: a fixed 160-wide search box took its natural width and pushed the filter chip beside + * it into the dropdown, which read as the filter collapsing for no reason while the box sat full-size. + */ + @Test + fun aCompressibleSlotYieldsToTheControlsBehindIt() { + val packing = + packWithMeasure( + slots = listOf(OverflowSlotSpec(OverflowSlotKind.Collapsible, minWidthPx = 40), collapsible), + naturalWidths = listOf(160, 30), + availableWidthPx = 120, + ) + // Both placed: the box took 120 - 30 - 10 = 80 instead of its natural 160. + assertEquals(listOf(0, 1), packing.placements.map { it.slotIndex }) + assertTrue(packing.collapsedSlotIndices.isEmpty()) + assertEquals(80, packing.placements.first().widthPx) + } + + /** It keeps its natural width whenever there is room for it. */ + @Test + fun aCompressibleSlotKeepsItsNaturalWidthWhenItFits() { + val packing = + packWithMeasure( + slots = listOf(OverflowSlotSpec(OverflowSlotKind.Collapsible, minWidthPx = 40), collapsible), + naturalWidths = listOf(160, 30), + availableWidthPx = 400, + ) + assertEquals(160, packing.placements.first().widthPx) + } + + /** It never squeezes past its floor - below that it collapses like anything else. */ + @Test + fun aCompressibleSlotCollapsesBelowItsFloor() { + val packing = + packWithMeasure( + slots = listOf(OverflowSlotSpec(OverflowSlotKind.Collapsible, minWidthPx = 40), collapsible), + naturalWidths = listOf(160, 30), + availableWidthPx = 45, + ) + assertEquals(listOf(0, 1), packing.collapsedSlotIndices) + } + + /** Squeezed to its floor rather than collapsed when the tail alone would push it under. */ + @Test + fun aCompressibleSlotStopsAtItsFloorRatherThanYieldingFurther() { + val packing = + packWithMeasure( + slots = listOf(OverflowSlotSpec(OverflowSlotKind.Collapsible, minWidthPx = 40), collapsible), + naturalWidths = listOf(160, 60), + availableWidthPx = 90, + ) + // Leaving the 60-wide tail its room would need the box at 20; it stops at 40 and the tail collapses. + assertEquals(40, packing.placements.first().widthPx) + assertEquals(listOf(1), packing.collapsedSlotIndices) + } + + /** + * A starved flexible gap keeps its floor instead of closing, so the controls either side never touch. + * + * The regression: the walk placed every gap at zero and the leftover was written OVER that, so once the + * leftover ran out the two buttons around the gap butted together and read as a rendering fault. + */ + @Test + fun aStarvedFlexibleGapKeepsItsFloor() { + val gapWithFloor = OverflowSlotSpec(OverflowSlotKind.Flexible, weight = 1f, minWidthPx = 8) + // 30 + 8 + 30 = 68 against 68: nothing left over, so the gap is down to exactly its floor. + val packing = pack(slots = listOf(collapsible, gapWithFloor, collapsible), widths = listOf(30, 0, 30), availableWidthPx = 68) + assertEquals(listOf(0, 1, 2), packing.placements.map { it.slotIndex }) + assertEquals(8, packing.placements[1].widthPx) + assertEquals(listOf(0, 30, 38), packing.placements.map { it.xPx }) + } + + /** The floor is reserved before its neighbours are admitted, not shared out of what they leave. */ + @Test + fun aFlexibleGapsFloorIsChargedAgainstItsNeighbours() { + val gapWithFloor = OverflowSlotSpec(OverflowSlotKind.Flexible, weight = 1f, minWidthPx = 8) + // 30 + 8 + 30 needs 68; at 60 the trailing control cannot have its width AND leave the gap its floor. + val packing = pack(slots = listOf(collapsible, gapWithFloor, collapsible), widths = listOf(30, 0, 30), availableWidthPx = 60) + assertEquals(listOf(2), packing.collapsedSlotIndices) + } + + /** Leftover is added to the floor rather than replacing it, so a roomy gap is floor plus its share. */ + @Test + fun aFlexibleGapAddsItsLeftoverShareToItsFloor() { + val gapWithFloor = OverflowSlotSpec(OverflowSlotKind.Flexible, weight = 1f, minWidthPx = 8) + val packing = pack(slots = listOf(collapsible, gapWithFloor, collapsible), widths = listOf(30, 0, 30), availableWidthPx = 200) + // 200 - 30 - 8 - 30 = 132 free, on top of the 8 the gap already holds. + assertEquals(140, packing.placements[1].widthPx) + } + + /** An unbounded strip has no width to run out of: nothing collapses and the gaps resolve to zero. */ + @Test + fun anUnboundedStripNeverCollapsesAndHasNoLeftover() { + val widths = listOf(40, 0, 40) + val packing = + packOverflowRow( + slots = listOf(collapsible, flexible(), collapsible), + availableWidthPx = 0, + boundedWidth = false, + spacingPx = 10, + overflowButtonWidthPx = 20, + slotWidthPx = { slotIndex, _ -> widths[slotIndex] }, + ) + assertTrue(packing.collapsedSlotIndices.isEmpty()) + assertNull(packing.overflowButtonXPx) + assertEquals(0, packing.placements.first { it.slotIndex == 1 }.widthPx) + assertEquals(80, packing.contentWidthPx) + } + + /** The reported extent covers the chip when one is placed, so the strip does not under-report its width. */ + @Test + fun theContentExtentIncludesThePlacedChip() { + val packing = pack(slots = listOf(collapsible, collapsible), widths = listOf(30, 300), availableWidthPx = 100) + assertNotNull(packing.overflowButtonXPx) + assertEquals(100, packing.contentWidthPx) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/TextEditSelectionTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/TextEditSelectionTest.kt new file mode 100644 index 0000000..4c99434 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/kit/TextEditSelectionTest.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The selection arithmetic behind Cut and Paste. + * + * Small, but the caret placement is exactly the kind of off-by-one that only shows up as "pasting twice puts + * the second one in the wrong place" - a bug reported as flakiness rather than as arithmetic. + */ +class TextEditSelectionTest { + /** Cut and Copy act on the selected span, in text order whichever way the user dragged. */ + @Test + fun theSelectedTextIsTheSpanInTextOrder() { + assertEquals("bcd", TextFieldValue("abcde", TextRange(1, 4)).selectedText()) + assertEquals("bcd", TextFieldValue("abcde", TextRange(4, 1)).selectedText(), "a backwards selection") + assertEquals("", TextFieldValue("abcde", TextRange(2)).selectedText(), "a bare caret selects nothing") + } + + /** Pasting over a selection replaces it and leaves the caret AFTER the inserted text, ready to keep typing. */ + @Test + fun replacingASelectionLeavesTheCaretAfterTheInsertion() { + val pasted = TextFieldValue("abcde", TextRange(1, 4)).withSelectionReplaced("XY") + assertEquals("aXYe", pasted.text) + assertEquals(TextRange(3), pasted.selection) + } + + /** Pasting at a bare caret inserts without deleting anything. */ + @Test + fun replacingABareCaretInserts() { + val pasted = TextFieldValue("abc", TextRange(3)).withSelectionReplaced("!") + assertEquals("abc!", pasted.text) + assertEquals(TextRange(4), pasted.selection) + } + + /** Cutting is the same op with an empty replacement, so the caret lands where the removed text began. */ + @Test + fun cuttingLeavesTheCaretWhereTheTextWas() { + val cut = TextFieldValue("abcde", TextRange(1, 4)).withSelectionReplaced("") + assertEquals("ae", cut.text) + assertEquals(TextRange(1), cut.selection) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/l10n/UiLanguageMatchTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/l10n/UiLanguageMatchTest.kt new file mode 100644 index 0000000..3875318 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/l10n/UiLanguageMatchTest.kt @@ -0,0 +1,54 @@ +package org.umamo.ui.l10n + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The operating-system-language to UI-catalog match a first run seeds localization.locale from. */ +class UiLanguageMatchTest { + private val shipped = UI_LANGUAGE_ENDONYMS.keys + + @Test + fun aRegionTagMatchesItsLanguageCatalog() { + assertEquals("ja", matchUiLanguage(listOf("ja-JP"), shipped)) + assertEquals("ko", matchUiLanguage(listOf("ko-KR"), shipped)) + } + + @Test + fun theJvmUnderscoreSpellingAndCaseDoNotMatter() { + assertEquals("ja", matchUiLanguage(listOf("ja_JP"), shipped)) + assertEquals("ko", matchUiLanguage(listOf("KO"), shipped)) + } + + @Test + fun theFirstPreferredLanguageWithACatalogWins() { + // French has no catalog, so the next preference is taken rather than falling back to English. + assertEquals("ko", matchUiLanguage(listOf("fr-FR", "ko-KR", "ja-JP"), shipped)) + } + + @Test + fun noCatalogFallsBackToEnglish() { + assertEquals("en", matchUiLanguage(listOf("zh-TW"), shipped)) + assertEquals("en", matchUiLanguage(listOf("fr-FR", "de"), shipped)) + } + + @Test + fun noSystemLanguageFallsBackToEnglish() { + assertEquals("en", matchUiLanguage(emptyList(), shipped)) + assertEquals("en", matchUiLanguage(listOf(""), shipped)) + } + + @Test + fun aRegionCatalogOutranksTheBareLanguage() { + val withRegions = listOf("en", "zh", "zh-CN", "zh-TW") + assertEquals("zh-CN", matchUiLanguage(listOf("zh-CN"), withRegions)) + // A script between the language and the region still finds the region catalog. + assertEquals("zh-TW", matchUiLanguage(listOf("zh-Hant-TW"), withRegions)) + // A region with no catalog of its own takes the bare language. + assertEquals("zh", matchUiLanguage(listOf("zh-SG"), withRegions)) + } + + @Test + fun theMatchIsReturnedAsTheCatalogSpellsIt() { + assertEquals("zh-CN", matchUiLanguage(listOf("zh_cn"), listOf("en", "zh-CN"))) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/model/AtlasRepackFlowTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/AtlasRepackFlowTest.kt new file mode 100644 index 0000000..c09be3a --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/AtlasRepackFlowTest.kt @@ -0,0 +1,153 @@ +package org.umamo.ui.model + +import org.umamo.format.atlas.AtlasPackFixed +import org.umamo.format.atlas.AtlasPackItem +import org.umamo.format.atlas.AtlasPackSkip +import org.umamo.format.atlas.AtlasPackSkipReason +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the repack's abort rule: a BOUND tile the pack cannot carry refuses the whole repack - a + * skipped tile, undecodable art, a degenerate placement, or a placement naming a missing page - while + * an unbound tile never refuses (nothing samples it, so nothing can be stranded). + */ +class AtlasRepackFlowTest { + private val boundId = AtlasTileId("bound") + private val freeId = AtlasTileId("free") + + private fun placement(pageIndex: Int = 0, scaleX: Float = 1f): AtlasPlacement = + AtlasPlacement(pageIndex, 4f, 4f, scaleX = scaleX, scaleY = 1f, rotationDegrees = 0f) + + private fun modelWith(boundTile: AtlasTile, freeTile: AtlasTile): PuppetModel { + val drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + atlasTileId = boundId, + ) + return PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = 50f, + atlas = PuppetAtlas(pages = listOf(AtlasPage(64, 64)), tiles = listOf(boundTile, freeTile)), + ) + } + + @Test + fun anUnboundTileNeverRefusesAndABoundSkipDoes() { + val model = + modelWith( + AtlasTile(boundId, "Bound Art", 16, 16, placement()), + AtlasTile(freeId, "Free Art", 16, 16, placement()), + ) + + val cleanRefusals = repackRefusals(model, emptyList(), emptySet()) + assertTrue(cleanRefusals.isEmpty(), "a healthy pack refuses nothing") + + val freeSkipped = repackRefusals(model, listOf(AtlasPackSkip(freeId.raw, AtlasPackSkipReason.NoOpaquePixels)), emptySet()) + assertTrue(freeSkipped.isEmpty(), "an unbound tile skips freely") + + val boundSkipped = repackRefusals(model, listOf(AtlasPackSkip(boundId.raw, AtlasPackSkipReason.LargerThanPage)), emptySet()) + assertEquals(1, boundSkipped.size) + assertEquals("Bound Art", boundSkipped.single().tileName, "the report names the tile verbatim") + assertEquals(AtlasRepackRefusalReason.LargerThanPage, boundSkipped.single().reason) + } + + @Test + fun undecodableArtRefusesOnlyWhenBound() { + val model = + modelWith( + AtlasTile(boundId, "Bound Art", 16, 16, placement()), + AtlasTile(freeId, "Free Art", 16, 16, placement()), + ) + + assertTrue(repackRefusals(model, emptyList(), setOf(freeId)).isEmpty()) + assertEquals( + AtlasRepackRefusalReason.Undecodable, + repackRefusals(model, emptyList(), setOf(boundId)).single().reason, + ) + } + + @Test + fun aDegenerateOrDanglingPlacementRefusesTheRederivation() { + val zeroScaled = + modelWith( + AtlasTile(boundId, "Bound Art", 16, 16, placement(scaleX = 0f)), + AtlasTile(freeId, "Free Art", 16, 16, placement()), + ) + assertEquals( + AtlasRepackRefusalReason.DegeneratePlacement, + repackRefusals(zeroScaled, emptyList(), emptySet()).single().reason, + ) + + val danglingPage = + modelWith( + AtlasTile(boundId, "Bound Art", 16, 16, placement(pageIndex = 7)), + AtlasTile(freeId, "Free Art", 16, 16, placement()), + ) + assertEquals( + AtlasRepackRefusalReason.DegeneratePlacement, + repackRefusals(danglingPage, emptyList(), emptySet()).single().reason, + ) + + // A bound but UNPLACED tile has an identity mapping, which always inverts. + val unplaced = + modelWith( + AtlasTile(boundId, "Bound Art", 16, 16, placement = null), + AtlasTile(freeId, "Free Art", 16, 16, placement()), + ) + assertTrue(repackRefusals(unplaced, emptyList(), emptySet()).isEmpty()) + } + + /** + * The three ways one decoded input is handed to the packer: every tile free, the pinned tiles + * fixed, or EVERY placed tile fixed (art added to an open document packs into the gaps). The + * fixed forms are the packer's, keyed by tile, and a free item stays the same instance. + */ + @Test + fun theInputHandsThePackerFreePinnedOrEveryPlacedTileFixed() { + val pinnedForm = AtlasPackFixed(0, floatArrayOf(1f, 0f, 4f, 0f, 1f, 4f)) + val placedForm = AtlasPackFixed(0, floatArrayOf(1f, 0f, 20f, 0f, 1f, 20f)) + val pinned = AtlasPackItem("pinned", 1, 1, ByteArray(4)) + val placed = AtlasPackItem("placed", 1, 1, ByteArray(4)) + val fresh = AtlasPackItem("fresh", 1, 1, ByteArray(4)) + val input = + RepackPackInput( + items = listOf(pinned, placed, fresh), + fixedByKey = mapOf("pinned" to pinnedForm), + placedByKey = mapOf("pinned" to pinnedForm, "placed" to placedForm), + undecodableTileIds = emptySet(), + reserveByTile = emptyMap(), + ) + + assertTrue(input.itemsFor(keepPinned = false).all { item -> item.fixed == null }, "pins ignored: every tile free") + val keepingPins = input.itemsFor(keepPinned = true) + assertEquals(listOf(pinnedForm, null, null), keepingPins.map { item -> item.fixed }, "pins kept: only the pinned tile is fixed") + val fixingPlaced = input.itemsFor(keepPinned = true, fixPlaced = true) + assertEquals(listOf(pinnedForm, placedForm, null), fixingPlaced.map { item -> item.fixed }, "placed fixed: every placed tile stays, the fresh one packs") + assertTrue(fixingPlaced[2] === fresh, "a free item is the same instance") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/model/DrawableThumbnailerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/DrawableThumbnailerTest.kt new file mode 100644 index 0000000..7fade69 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/DrawableThumbnailerTest.kt @@ -0,0 +1,285 @@ +package org.umamo.ui.model + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.graphics.toPixelMap +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Unit-tests [DrawableThumbnailer], the shared crop-and-downsample used by both the overlap picker and the + * Outliner hover preview. Corpus-free: a hand-built 4x4 atlas with distinct corner pixels and a drawable + * whose UVs cover the left half, so the cropped thumbnail is a known 2x4 1:1 copy whose pixels can be + * asserted exactly. No GL - the bitmap is read back via toPixelMap (common Compose API). If the ui android target ever + * enables host tests, the Bitmap-backed rgbaToImageBitmap actual will need Robolectric. + */ +class DrawableThumbnailerTest { + /** Packs an opaque RGBA pixel into a 4x4 atlas buffer at (x, y), top row first. */ + private fun setPixel(rgba: ByteArray, width: Int, x: Int, y: Int, color: Color) { + val offset = (y * width + x) * 4 + rgba[offset] = (color.red * 255f).toInt().toByte() + rgba[offset + 1] = (color.green * 255f).toInt().toByte() + rgba[offset + 2] = (color.blue * 255f).toInt().toByte() + rgba[offset + 3] = 255.toByte() + } + + private fun atlas4x4(): DecodedImage { + val width = 4 + val height = 4 + val rgba = ByteArray(width * height * 4) + // Black fill, then four distinct corners within the left-half crop (columns 0..1). + for (offset in 3 until rgba.size step 4) { + rgba[offset] = 255.toByte() // opaque + } + setPixel(rgba, width, 0, 0, Color.Red) + setPixel(rgba, width, 1, 0, Color.Green) + setPixel(rgba, width, 0, 3, Color.Blue) + setPixel(rgba, width, 1, 3, Color.Yellow) + return DecodedImage(rgba, width, height) + } + + private fun drawable(id: String, uvs: FloatArray, positions: FloatArray = floatArrayOf()): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(positions = positions, uvs = uvs, indices = intArrayOf()), + geometryGrid = null, + ) + + /** A flat model: every [drawables] entry sits at the organizational root (no owning part). */ + private fun flatModel(drawables: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { OrgChild.Drawable(it.id) }, + rootPartId = null, + ) + + /** A one-part model: [part] owns every [drawables] entry (membership lives in the org tree). */ + private fun partModel(partId: String, drawables: List): PuppetModel { + val part = Part(PartId(partId), partId.uppercase(), drawables.map { OrgChild.Drawable(it.id) }) + return PuppetModel( + parameters = emptyList(), + parts = listOf(part), + deformers = emptyList(), + drawables = drawables, + rootChildren = listOf(OrgChild.Part(part.id)), + rootPartId = null, + ) + } + + /** A 4x4 atlas: the left two columns red, the right two green, so a left-UV crop reads red and a right-UV crop green. */ + private fun atlasLeftRedRightGreen(): DecodedImage { + val width = 4 + val height = 4 + val rgba = ByteArray(width * height * 4) + for (y in 0 until height) { + for (x in 0 until width) { + setPixel(rgba, width, x, y, if (x < 2) Color.Red else Color.Green) + } + } + return DecodedImage(rgba, width, height) + } + + @Test + fun cropsTheUvBoundingBoxAtOneToOneWhenSmallerThanTheThumbnailBox() { + // UVs over the left half: u in [0, 0.5], v in [0, 1] → crop columns 0..1, rows 0..3 (a 2x4 region). + val leftHalf = floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f) + val puppet = flatModel(listOf(drawable("mesh", leftHalf))) + val textures = PuppetTextures(listOf(atlas4x4()), mapOf("mesh" to 0), premultipliedAlpha = false) + + val thumbnail = DrawableThumbnailer(puppet, textures).thumbnailFor(DrawableId("mesh")) + assertEquals(true, thumbnail != null, "a textured, meshed drawable yields a thumbnail") + val pixels = thumbnail!!.toPixelMap() + + // 96px box never upscales a 2x4 region, so the crop is copied 1:1. + assertEquals(2, pixels.width) + assertEquals(4, pixels.height) + // Nearest-neighbor is the identity over the left two columns, so the corners survive verbatim. + assertEquals(Color.Red.toArgb(), pixels[0, 0].toArgb()) + assertEquals(Color.Green.toArgb(), pixels[1, 0].toArgb()) + assertEquals(Color.Blue.toArgb(), pixels[0, 3].toArgb()) + assertEquals(Color.Yellow.toArgb(), pixels[1, 3].toArgb()) + } + + @Test + fun duplicateResolvesItsAtlasThroughItsSourceAfterUpdateModel() { + // The atlas map knows only the source-format id "mesh"; the duplicate carries a fresh id and + // textureSourceId = mesh, with its own UVs over the right (green) half. + val source = drawable("mesh", floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f)) + val copy = + drawable("mesh.001", floatArrayOf(0.5f, 0f, 1f, 0f, 1f, 1f, 0.5f, 1f)) + .copy(textureSourceId = DrawableId("mesh")) + val textures = PuppetTextures(listOf(atlasLeftRedRightGreen()), mapOf("mesh" to 0), premultipliedAlpha = false) + val thumbnailer = DrawableThumbnailer(flatModel(listOf(source)), textures) + + // Before the refresh the id is unknown - the session has not pushed the duplicating edit yet. + assertNull(thumbnailer.thumbnailFor(DrawableId("mesh.001"))) + + thumbnailer.updateModel(flatModel(listOf(source, copy))) + val thumbnail = thumbnailer.thumbnailFor(DrawableId("mesh.001")) + assertNotNull(thumbnail, "a session-created duplicate previews through its source's atlas page") + val pixels = thumbnail.toPixelMap() + assertEquals(Color.Green.toArgb(), pixels[0, 0].toArgb(), "the crop follows the COPY's own UVs (the green half)") + } + + @Test + fun remeshEvictsTheStaleCropOnUpdateModel() { + // Same id, new UV array (a remesh copy-on-writes uvs): the cached red-half crop must not survive. + val before = drawable("mesh", floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f)) + val after = drawable("mesh", floatArrayOf(0.5f, 0f, 1f, 0f, 1f, 1f, 0.5f, 1f)) + val textures = PuppetTextures(listOf(atlasLeftRedRightGreen()), mapOf("mesh" to 0), premultipliedAlpha = false) + val thumbnailer = DrawableThumbnailer(flatModel(listOf(before)), textures) + assertEquals(Color.Red.toArgb(), thumbnailer.thumbnailFor(DrawableId("mesh"))!!.toPixelMap()[0, 0].toArgb()) + + thumbnailer.updateModel(flatModel(listOf(after))) + assertEquals( + Color.Green.toArgb(), + thumbnailer.thumbnailFor(DrawableId("mesh"))!!.toPixelMap()[0, 0].toArgb(), + "the remeshed UVs re-crop instead of serving the stale cached thumbnail", + ) + } + + @Test + fun setTexturesEvictsEveryServedCrop() { + // Same drawable, same UVs; only the PIXELS move (a repack recomposes the page). A served crop + // must not survive the swap. + val meshed = drawable("mesh", floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f)) + val redLeft = PuppetTextures(listOf(atlasLeftRedRightGreen()), mapOf("mesh" to 0), premultipliedAlpha = false) + val thumbnailer = DrawableThumbnailer(flatModel(listOf(meshed)), redLeft) + assertEquals(Color.Red.toArgb(), thumbnailer.thumbnailFor(DrawableId("mesh"))!!.toPixelMap()[0, 0].toArgb()) + + val greenEverywhere = ByteArray(4 * 4 * 4) + for (y in 0 until 4) { + for (x in 0 until 4) { + setPixel(greenEverywhere, 4, x, y, Color.Green) + } + } + thumbnailer.setTextures( + PuppetTextures(listOf(DecodedImage(greenEverywhere, 4, 4)), mapOf("mesh" to 0), premultipliedAlpha = false), + ) + assertEquals( + Color.Green.toArgb(), + thumbnailer.thumbnailFor(DrawableId("mesh"))!!.toPixelMap()[0, 0].toArgb(), + "a page swap re-crops from the new pixels instead of serving the stale cached thumbnail", + ) + } + + @Test + fun returnsNullForAnUntexturedDrawable() { + // A drawable with mesh UVs but no atlas page mapping is untextured → no preview. + val uvs = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f) + val puppet = flatModel(listOf(drawable("flat", uvs))) + val textures = PuppetTextures(listOf(atlas4x4()), emptyMap(), premultipliedAlpha = false) + + assertNull(DrawableThumbnailer(puppet, textures).thumbnailFor(DrawableId("flat"))) + } + + @Test + fun combinesPartMembersInModelSpaceLeftToRight() { + // Two opaque, non-overlapping layers under one part: 'a' on the model-space left (red atlas region), + // 'b' on the right (green). Their union is 20x10 model units → a 128x64 composite split down the middle. + val left = + drawable( + id = "a", + uvs = floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f), + positions = floatArrayOf(0f, 0f, 10f, 0f, 10f, 10f, 0f, 10f), + ) + val right = + drawable( + id = "b", + uvs = floatArrayOf(0.5f, 0f, 1f, 0f, 1f, 1f, 0.5f, 1f), + positions = floatArrayOf(10f, 0f, 20f, 0f, 20f, 10f, 10f, 10f), + ) + val puppet = partModel("p", listOf(left, right)) + val textures = PuppetTextures(listOf(atlasLeftRedRightGreen()), mapOf("a" to 0, "b" to 0), premultipliedAlpha = false) + + val composite = DrawableThumbnailer(puppet, textures).partThumbnailFor(PartId("p")) + assertNotNull(composite, "a part with textured members yields a composite") + val pixels = composite.toPixelMap() + + // 128px long edge over the 20x10 union → 128x64; left half is 'a' (red), right half is 'b' (green). + assertEquals(128, pixels.width) + assertEquals(64, pixels.height) + assertEquals(Color.Red.toArgb(), pixels[16, 32].toArgb()) + assertEquals(Color.Green.toArgb(), pixels[112, 32].toArgb()) + } + + @Test + fun stacksPartMembersTopToBottomByModelY() { + // Two stacked layers under one part: 'upper' at the smaller model Y (red), 'lower' below it (green). + // Rest-pose Y is top-down, so the smaller-Y layer must land at the TOP of the composite (no Y flip). + val upper = + drawable( + id = "a", + uvs = floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f), + positions = floatArrayOf(0f, 0f, 10f, 0f, 10f, 10f, 0f, 10f), + ) + val lower = + drawable( + id = "b", + uvs = floatArrayOf(0.5f, 0f, 1f, 0f, 1f, 1f, 0.5f, 1f), + positions = floatArrayOf(0f, 10f, 10f, 10f, 10f, 20f, 0f, 20f), + ) + val puppet = partModel("p", listOf(upper, lower)) + val textures = PuppetTextures(listOf(atlasLeftRedRightGreen()), mapOf("a" to 0, "b" to 0), premultipliedAlpha = false) + + val composite = DrawableThumbnailer(puppet, textures).partThumbnailFor(PartId("p")) + assertNotNull(composite) + val pixels = composite.toPixelMap() + + // 128px long edge over the 10x20 union → 64x128; the smaller-Y layer is the top half (red). + assertEquals(64, pixels.width) + assertEquals(128, pixels.height) + assertEquals(Color.Red.toArgb(), pixels[32, 16].toArgb()) + assertEquals(Color.Green.toArgb(), pixels[32, 100].toArgb()) + } + + @Test + fun partWithNoTexturedMembersHasNoComposite() { + val flat = drawable("a", floatArrayOf(0f, 0f, 1f, 1f), floatArrayOf(0f, 0f, 10f, 10f)) + val puppet = partModel("empty", listOf(flat)) + // No atlas mapping → the member is untextured → no crop → null composite. + val textures = PuppetTextures(listOf(atlasLeftRedRightGreen()), emptyMap(), premultipliedAlpha = false) + + assertNull(DrawableThumbnailer(puppet, textures).partThumbnailFor(PartId("empty"))) + } + + @Test + fun modelRasterCompositesEveryVisibleDrawableRootLevelIncluded() { + // Two root-level drawables side by side in model space: the left one samples the red half of the + // atlas, the right one the green half, so the composite reads red on the left and green on the right. + val left = drawable("left", floatArrayOf(0f, 0f, 0.5f, 0f, 0.5f, 1f, 0f, 1f), floatArrayOf(0f, 0f, 2f, 0f, 2f, 2f, 0f, 2f)) + val right = drawable("right", floatArrayOf(0.5f, 0f, 1f, 0f, 1f, 1f, 0.5f, 1f), floatArrayOf(2f, 0f, 4f, 0f, 4f, 2f, 2f, 2f)) + val textures = PuppetTextures(listOf(atlasLeftRedRightGreen()), mapOf("left" to 0, "right" to 0), premultipliedAlpha = false) + val composite = assertNotNull(DrawableThumbnailer(flatModel(listOf(left, right)), textures).modelRasterFor(), "a textured model composites") + assertEquals(128, composite.width, "the union's longer edge fills the composite box") + assertEquals(64, composite.height) + + fun channel(x: Int, y: Int, channel: Int): Int = composite.rgba[(y * composite.width + x) * 4 + channel].toInt() and 0xFF + assertEquals(listOf(255, 0, 0, 255), (0 until 4).map { channel -> channel(8, 32, channel) }, "the left half is red") + assertEquals(listOf(0, 255, 0, 255), (0 until 4).map { channel -> channel(120, 32, channel) }, "the right half is green") + + // A hidden drawable stays out of the model thumbnail, as it stays out of the viewport. + val withHiddenRight = DrawableThumbnailer(flatModel(listOf(left, right.copy(isVisible = false))), textures).modelRasterFor() + assertEquals(128 to 128, assertNotNull(withHiddenRight).let { raster -> raster.width to raster.height }, "only the left square remains") + assertNull(DrawableThumbnailer(flatModel(listOf(drawable("flat", floatArrayOf()))), textures).modelRasterFor(), "an untextured model has no thumbnail") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/model/KeyedFieldStateTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/KeyedFieldStateTest.kt new file mode 100644 index 0000000..cea71be --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/KeyedFieldStateTest.kt @@ -0,0 +1,202 @@ +package org.umamo.ui.model + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the keyed-field tint states. + * + * These are what stop manual keying from silently discarding work: BetweenKeys warns that an edit here + * needs an explicit key, and ModifiedUnkeyed says that has already happened. A Cubism migrant has never + * needed either signal - Cubism auto-keys - so getting them wrong is precisely the friction they hit. + */ +class KeyedFieldStateTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val drawableId = DrawableId("d") + private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.OPACITY) + + private fun opacityTrack(): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))), + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(0f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(0.5f)), + KeyformCell(intArrayOf(2), ChannelValue.Scalar(1f)), + ), + ) + + /** Opacity keyed on BOTH parameters, keys at -30 / 0 / 30 on each - a linked pad's shape. */ + private fun twoAxisOpacityTrack(): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f)), KeyformAxis(angleY, floatArrayOf(-30f, 0f, 30f))), + (0..2).flatMap { yIndex -> + (0..2).map { xIndex -> + KeyformCell(intArrayOf(xIndex, yIndex), ChannelValue.Scalar(0.5f)) + } + }, + ) + + private fun model(channelGrids: ChannelGrids): PuppetModel = + PuppetModel( + parameters = + listOf( + Parameter(angleX, angleX.raw, min = -30f, max = 30f, default = 0f), + Parameter(angleY, angleY.raw, min = -30f, max = 30f, default = 0f), + ), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + channelGrids = channelGrids, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + private fun stateAt( + channelGrids: ChannelGrids, + pose: Map, + pending: Map = emptyMap(), + ): KeyedFieldState = + keyedFieldStateOf( + puppet = model(channelGrids), + target = target, + pose = pose, + pendingEdits = pending, + ) + + /** An untracked channel is not keyed, so the field looks ordinary. */ + @Test + fun anUntrackedChannelIsNone() { + assertEquals(KeyedFieldState.None, stateAt(ChannelGrids.Empty, mapOf(angleX to 0f))) + } + + /** + * The state follows the TRACK's own axes, not whatever parameter is targeted. + * + * This is the difference between the tint answering "is the value under this field stored" and answering + * "is it stored on the axis you happen to have clicked". A rigger reads it as the first; the second + * would paint a keyed opacity as unstored whenever the target was the other half of a linked pad. The + * targeted parameter is not even an input here, so a pose sitting on a key reads as on-key regardless. + */ + @Test + fun theStateFollowsTheTracksOwnAxes() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack())) + assertEquals(KeyedFieldState.OnKey, stateAt(grids, mapOf(angleX to 0f)), "on a key of its own axis") + assertEquals( + KeyedFieldState.OnKey, + stateAt(grids, mapOf(angleX to 0f, angleY to 17f)), + "an unrelated parameter's value is irrelevant", + ) + } + + /** Exactly on a key: editing here writes that key. */ + @Test + fun onAKeyIsOnKey() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack())) + assertEquals(KeyedFieldState.OnKey, stateAt(grids, mapOf(angleX to 0f))) + assertEquals(KeyedFieldState.OnKey, stateAt(grids, mapOf(angleX to 30f))) + } + + /** + * A parameter absent from the pose resolves at its DEFAULT, which is what the evaluator does too. + * + * A pose map need not list every parameter, and treating a missing one as zero would report a state for + * a pose the viewport is not showing. + */ + @Test + fun aMissingPoseValueResolvesAtTheParameterDefault() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack())) + assertEquals(KeyedFieldState.OnKey, stateAt(grids, emptyMap()), "the default, 0, is a key") + } + + /** + * A MULTI-axis track is on-key only when the pose sits on a key of every axis. + * + * That is exactly when a capture overwrites the cell it lands on rather than inserting a slice, so it is + * the only reading under which OnKey's promise - "editing writes that key" - is true. + */ + @Test + fun aMultiAxisTrackNeedsEveryAxisOnAKey() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to twoAxisOpacityTrack())) + assertEquals(KeyedFieldState.OnKey, stateAt(grids, mapOf(angleX to 0f, angleY to 30f))) + assertEquals( + KeyedFieldState.BetweenKeys, + stateAt(grids, mapOf(angleX to 0f, angleY to 15f)), + "between keys on the second axis is still between keys", + ) + } + + /** + * Within the evaluator's snap tolerance still counts as on-key. + * + * An exact compare would flicker to "between" a hair either side of a key, disagreeing with the key the + * pose actually resolved to - the tint has to match what is being rendered, not a stricter idea of it. + */ + @Test + fun withinTheSnapToleranceIsStillOnKey() { + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack())) + assertEquals(KeyedFieldState.OnKey, stateAt(grids, mapOf(angleX to 0.0005f))) + } + + /** Between keys: an edit here is lost unless explicitly keyed. */ + @Test + fun betweenKeysIsBetweenKeys() { + assertEquals( + KeyedFieldState.BetweenKeys, + stateAt(ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack())), mapOf(angleX to 15f)), + ) + } + + /** A pending edit outranks every other state - it is the one carrying a warning. */ + @Test + fun aPendingEditWinsOverEveryOtherState() { + val pending = mapOf(target to ChannelValue.Scalar(0.9f)) + val grids = ChannelGrids(mapOf(FormChannel.OPACITY to opacityTrack())) + assertEquals( + KeyedFieldState.ModifiedUnkeyed, + stateAt(grids, mapOf(angleX to 0f), pending), + "even sitting on a key", + ) + assertEquals(KeyedFieldState.ModifiedUnkeyed, stateAt(grids, mapOf(angleX to 15f), pending), "and between keys") + } + + /** + * An UNTRACKED channel is never tinted, pending edit or not. + * + * A field being scrubbed writes the pending buffer on every frame regardless of whether the channel is + * keyed (that is what makes the viewport follow the pointer), so reading the pending map before checking + * for a track would paint the orange "edited and not keyed" warning across every ordinary drag. Nothing is + * uncommitted here: the release writes the owner's static as a plain undoable edit. + */ + @Test + fun anUntrackedChannelIsNeverTintedEvenMidScrub() { + val pending = mapOf(target to ChannelValue.Scalar(0.9f)) + assertEquals(KeyedFieldState.None, stateAt(ChannelGrids.Empty, mapOf(angleX to 0f), pending)) + assertEquals(KeyedFieldState.None, stateAt(ChannelGrids.Empty, emptyMap(), pending), "and at any pose") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/model/LoggedSourceFilePresenceTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/LoggedSourceFilePresenceTest.kt new file mode 100644 index 0000000..1287566 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/LoggedSourceFilePresenceTest.kt @@ -0,0 +1,38 @@ +package org.umamo.ui.model + +import org.umamo.storage.LogLevel +import org.umamo.storage.UmamoLog +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The presence probe's log: one line the first time a path is asked about, one more whenever the + * answer changes, and nothing for the same answer again - the Sources space and the watcher ask + * constantly, and a diagnosis needs the path once, not once a second. + */ +class LoggedSourceFilePresenceTest { + @Test + fun aPathIsLoggedOnItsFirstAnswerAndOnEveryChange() { + val path = "/art/presence-${kotlin.random.Random.nextInt()}.psd" + val uri = "content://art/presence-${kotlin.random.Random.nextInt()}" + var onDisk: Boolean? = true + val logged = LoggedSourceFilePresence { probed -> if (probed == path) onDisk else null } + + fun lines(): List> = UmamoLog.entries.value.filter { entry -> path in entry.message || uri in entry.message }.map { entry -> entry.level to entry.message } + + assertEquals(true, logged.probe(path)) + assertEquals(true, logged.probe(path)) + assertEquals(listOf(LogLevel.Info to "source artwork: found at $path"), lines(), "the same answer again earns no line") + onDisk = false + assertEquals(false, logged.probe(path)) + assertEquals(false, logged.probe(path)) + assertEquals(LogLevel.Warn to "source artwork: missing at $path", lines().last(), "a change earns one line, at warn for a missing file") + assertEquals(2, lines().size) + onDisk = true + logged.probe(path) + assertEquals(3, lines().size, "and coming back earns another") + assertEquals(null, logged.probe(uri)) + logged.probe(uri) + assertEquals(listOf(LogLevel.Info to "source artwork: presence unknown at $uri (not a file path this platform can probe)"), lines().filter { (_, message) -> uri in message }) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/model/SourceTileThumbnailsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/SourceTileThumbnailsTest.kt new file mode 100644 index 0000000..8fac4be --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/model/SourceTileThumbnailsTest.kt @@ -0,0 +1,84 @@ +package org.umamo.ui.model + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.graphics.toPixelMap +import org.umamo.render.DecodedImage +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.AtlasTileId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * The Sources space's tile previews: fitted into their square, cached per tile, and refitted when the + * store's pixels for a tile change under the same id. + */ +class SourceTileThumbnailsTest { + private val tile = AtlasTileId("tile") + + /** + * A raster of one opaque color. + * + * @param Int width The raster width. + * @param Int height The raster height. + * @param Color color The fill. + * @return DecodedImage The raster. + */ + private fun solid(width: Int, height: Int, color: Color): DecodedImage { + val rgba = ByteArray(width * height * 4) + val argb = color.toArgb() + for (pixelIndex in 0 until width * height) { + rgba[pixelIndex * 4] = (argb shr 16).toByte() + rgba[pixelIndex * 4 + 1] = (argb shr 8).toByte() + rgba[pixelIndex * 4 + 2] = argb.toByte() + rgba[pixelIndex * 4 + 3] = (argb ushr 24).toByte() + } + return DecodedImage(rgba, width, height) + } + + /** A tile the store cannot decode previews nothing. */ + @Test + fun aTileWithNoPixelsHasNoPreview() { + val thumbnails = SourceTileThumbnails(SourceArtRasters { null }) + assertNull(thumbnails.thumbnailFor(tile)) + } + + /** A wide layer fills the square's width, centered, with transparent bands above and below. */ + @Test + fun aPreviewIsFittedIntoItsSquare() { + val thumbnails = SourceTileThumbnails(SourceArtRasters { solid(300, 150, Color.Red) }) + val preview = assertNotNull(thumbnails.thumbnailFor(tile)) + assertEquals(128, preview.width) + assertEquals(128, preview.height) + val pixels = preview.toPixelMap() + assertEquals(Color.Red.toArgb(), pixels[64, 64].toArgb(), "the art sits in the middle") + assertEquals(0f, pixels[64, 0].alpha, "a wide layer leaves the top band transparent") + } + + /** Asking again for an unchanged tile hands back the same bitmap rather than fitting it twice. */ + @Test + fun aRepeatRequestReusesThePreview() { + val thumbnails = SourceTileThumbnails(SourceArtRasters { solid(8, 8, Color.Red) }) + assertSame(thumbnails.thumbnailFor(tile), thumbnails.thumbnailFor(tile)) + } + + /** + * A reload, its undo, and a second reload mint one tile id twice with different pixels, and the store + * hands out the second. The preview has to follow it rather than keep the first reload's art. + */ + @Test + fun aReplacedRasterIsRefitted() { + val rasters = SourceArtRasters { solid(8, 8, Color.Red) } + val thumbnails = SourceTileThumbnails(rasters) + val first = assertNotNull(thumbnails.thumbnailFor(tile)) + rasters.addDecoded(mapOf(tile to solid(8, 8, Color.Blue))) + val second = assertNotNull(thumbnails.thumbnailFor(tile)) + assertNotSame(first, second) + assertEquals(Color.Blue.toArgb(), second.toPixelMap()[64, 64].toArgb()) + assertSame(second, thumbnails.thumbnailFor(tile), "the refitted preview is cached in turn") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/BlendModeDisplayOrderTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/BlendModeDisplayOrderTest.kt new file mode 100644 index 0000000..bf206e2 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/BlendModeDisplayOrderTest.kt @@ -0,0 +1,30 @@ +package org.umamo.ui.properties + +import org.umamo.runtime.model.BlendMode +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The blend-mode picker order: every mode present exactly once, Normal first, the two "(Legacy)" + * premultiplied modes sunk to the bottom, and the 5.3 modes keeping their canonical order ahead of + * them. Guards against the enum/format order (BlendMode.entries) leaking into the UI unchanged. + */ +class BlendModeDisplayOrderTest { + @Test + fun displayOrderSinksLegacyModesToTheBottomWithoutDroppingAny() { + val order = blendModeDisplayOrder() + assertEquals(BlendMode.entries.size, order.size, "no drops or duplicates") + assertEquals(BlendMode.entries.toSet(), order.toSet(), "every mode present exactly once") + assertEquals(BlendMode.Normal, order.first(), "Normal stays first") + assertEquals( + listOf(BlendMode.AdditivePremultiplied, BlendMode.MultiplyPremultiplied), + order.takeLast(2), + "the two (Legacy) premultiplied modes are last", + ) + assertEquals( + BlendMode.entries.filterNot { it.ignoresAlphaBlend }, + order.dropLast(2), + "the 5.3 modes keep their canonical order ahead of the legacy pair", + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/EnumLabelsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/EnumLabelsTest.kt new file mode 100644 index 0000000..2ac8155 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/EnumLabelsTest.kt @@ -0,0 +1,53 @@ +package org.umamo.ui.properties + +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.RuntimeFeature +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the enum-label coverage and the part group-mode projection. The label resolvers are exhaustive + * `when`s (a missing entry would not compile), so this asserts each enum maps to a distinct resource per + * entry, and that the three-way group-mode projection round-trips while preserving an Isolated composite. + */ +class EnumLabelsTest { + @Test + fun everyEnumEntryMapsToADistinctLabelResource() { + val blendResources = BlendMode.entries.map { mode -> blendModeLabelRes(mode) } + assertEquals(BlendMode.entries.size, blendResources.toSet().size) + + val alphaResources = AlphaBlendMode.entries.map { mode -> alphaBlendModeLabelRes(mode) } + assertEquals(AlphaBlendMode.entries.size, alphaResources.toSet().size) + + val groupResources = PartGroupModeKind.entries.map { kind -> partGroupModeLabelRes(kind) } + assertEquals(PartGroupModeKind.entries.size, groupResources.toSet().size) + + val featureResources = RuntimeFeature.entries.map { feature -> runtimeFeatureLabelRes(feature) } + assertEquals(RuntimeFeature.entries.size, featureResources.toSet().size) + + val channelResources = FormChannel.entries.map { channel -> formChannelLabelRes(channel) } + assertEquals(FormChannel.entries.size, channelResources.toSet().size) + } + + @Test + fun groupModeKindProjectsEveryCase() { + assertEquals(PartGroupModeKind.PassThrough, PartGroupMode.PassThrough.kind()) + assertEquals(PartGroupModeKind.Grouped, PartGroupMode.Grouped.kind()) + assertEquals(PartGroupModeKind.Isolated, PartGroupMode.Isolated.kind()) + } + + @Test + fun partGroupModeOfProjectsEveryKind() { + // The modes are payload-free (the composite lives latently on the part), so this is a plain + // projection: each kind maps to its mode and round-trips through kind(). + assertEquals(PartGroupMode.PassThrough, partGroupModeOf(PartGroupModeKind.PassThrough)) + assertEquals(PartGroupMode.Grouped, partGroupModeOf(PartGroupModeKind.Grouped)) + assertEquals(PartGroupMode.Isolated, partGroupModeOf(PartGroupModeKind.Isolated)) + for (kind in PartGroupModeKind.entries) { + assertEquals(kind, partGroupModeOf(kind).kind()) + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/MaskCandidatesTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/MaskCandidatesTest.kt new file mode 100644 index 0000000..86cb1f8 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/MaskCandidatesTest.kt @@ -0,0 +1,37 @@ +package org.umamo.ui.properties + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the pure candidate set behind the composite mask editor's add menu: the drawables not already + * masking, in model order, with the empty-current and empty-model edges. + */ +class MaskCandidatesTest { + private fun drawable(id: String): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + @Test + fun excludesAlreadyAppliedMasksPreservingOrder() { + val candidates = maskCandidates(listOf(drawable("a"), drawable("b"), drawable("c")), listOf(DrawableId("b"))) + assertEquals(listOf(DrawableId("a"), DrawableId("c")), candidates.map { it.id }) + } + + @Test + fun emptyCurrentReturnsAllAndEmptyModelReturnsNone() { + assertEquals(listOf(DrawableId("a")), maskCandidates(listOf(drawable("a")), emptyList()).map { it.id }) + assertTrue(maskCandidates(emptyList(), listOf(DrawableId("a"))).isEmpty()) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/PropertyTabRegistryTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/PropertyTabRegistryTest.kt new file mode 100644 index 0000000..4093c50 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/PropertyTabRegistryTest.kt @@ -0,0 +1,158 @@ +package org.umamo.ui.properties + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.properties_tab_document +import org.umamo.ui.resources.properties_tab_object +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Covers the two pure behaviors that carry the Properties data design: which tabs are visible for a given + * selection ([PropertyTabRegistry.visibleTabs]) and the header-search match predicate ([matchesQuery]). + * Both are Compose-free, so they exercise the design without a UI harness. + */ +class PropertyTabRegistryTest { + /** A minimal, empty model - enough to build a [PropertyContext] (the visibility predicates read only the target). */ + private fun emptyPuppet(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** + * Builds a single-target selection context. + * + * @param SelectionTarget target The lone active target. + * @return PropertyContext The context with that target active. + */ + private fun contextFor(target: SelectionTarget): PropertyContext = PropertyContext(emptyPuppet(), Selection(setOf(target), target), target, session = null) + + /** With nothing selected, only the always-on Document tab is visible. */ + @Test + fun documentTabIsTheOnlyTabWithNoSelection() { + val visible = defaultPropertyTabRegistry().visibleTabs(PropertyContext(emptyPuppet(), Selection(), null, session = null)).map { tab -> tab.id } + assertEquals(listOf(PropertyTabId.Document), visible) + } + + /** A single active item exposes the per-item Object and Data tabs alongside Document, in fixed order. */ + @Test + fun perItemTabsAppearForEachSelectionKind() { + val registry = defaultPropertyTabRegistry() + val expected = listOf(PropertyTabId.Document, PropertyTabId.Object, PropertyTabId.Data) + assertEquals(expected, registry.visibleTabs(contextFor(SelectionTarget.Drawable(DrawableId("d1")))).map { it.id }) + assertEquals(expected, registry.visibleTabs(contextFor(SelectionTarget.Deformer(DeformerId("w1")))).map { it.id }) + assertEquals(expected, registry.visibleTabs(contextFor(SelectionTarget.Part(PartId("p1")))).map { it.id }) + } + + /** The Data tab adapts its sections to the active item's type. */ + @Test + fun dataTabSectionsResolvePerType() { + assertEquals( + listOf(MeshSection.id, TextureSection.id, BlendSection.id), + dataTabSections(contextFor(SelectionTarget.Drawable(DrawableId("d1")))).map { it.id }, + ) + assertEquals(listOf(DeformerSection.id), dataTabSections(contextFor(SelectionTarget.Deformer(DeformerId("w1")))).map { it.id }) + assertEquals(listOf(PartSection.id), dataTabSections(contextFor(SelectionTarget.Part(PartId("p1")))).map { it.id }) + } + + /** The match predicate is case-insensitive, and a blank query matches everything. */ + @Test + fun matchesQueryIsCaseInsensitiveAndBlankMatchesAll() { + val haystack = listOf("Canvas", "Size: %1\$s × %2\$s") + assertTrue(matchesQuery(haystack, "")) + assertTrue(matchesQuery(haystack, " ")) + assertTrue(matchesQuery(haystack, "can")) + assertTrue(matchesQuery(haystack, "SIZE")) + assertFalse(matchesQuery(haystack, "runtime")) + assertFalse(matchesQuery(emptyList(), "x")) + } + + /** + * Per-row visibility: a blank query or a section-title match shows every row; a field query keeps only + * the matching rows; and a stacked row (several terms) survives when any of its terms match. + */ + @Test + fun sectionVisibilityHidesNonMatchingRows() { + val rows = listOf(listOf("Opacity"), listOf("Blend Mode"), listOf("Invert Mask")) + + // Blank query: the whole section, every row. + sectionVisibility("Compositing", rows, "").let { result -> + assertTrue(result.shown) + assertEquals(listOf(0, 1, 2), result.visibleRowIndices) + } + // A field-name query keeps only the matching row. + sectionVisibility("Compositing", rows, "blend").let { result -> + assertTrue(result.shown) + assertEquals(listOf(1), result.visibleRowIndices) + } + // A section-title match shows every row (the whole section is relevant), even when no row matches. + sectionVisibility("Compositing", rows, "compos").let { result -> + assertTrue(result.shown) + assertEquals(listOf(0, 1, 2), result.visibleRowIndices) + } + // No match anywhere hides the section outright. + sectionVisibility("Compositing", rows, "zzz").let { result -> + assertFalse(result.shown) + assertTrue(result.visibleRowIndices.isEmpty()) + } + // A stacked row (canvas width + height) matches on any of its terms. + sectionVisibility("Canvas", listOf(listOf("Width", "Height")), "height").let { result -> + assertTrue(result.shown) + assertEquals(listOf(0), result.visibleRowIndices) + } + } + + /** + * A section that built no rows for the current context never shows - not on a blank query, and not on a + * title match either. This is how Transform opts out for an item with no transform (a Part, a warp + * deformer) instead of drawing an empty card, so a title match must not resurrect it. + */ + @Test + fun sectionVisibilityHidesASectionThatBuiltNoRows() { + val noRows = emptyList>() + + sectionVisibility("Transform", noRows, "").let { result -> + assertFalse(result.shown, "an empty section is not shown on a blank query") + assertTrue(result.visibleRowIndices.isEmpty()) + } + sectionVisibility("Transform", noRows, "transf").let { result -> + assertFalse(result.shown, "a title match must not resurrect an empty section") + assertTrue(result.visibleRowIndices.isEmpty()) + } + sectionVisibility("Transform", noRows, "zzz").let { result -> + assertFalse(result.shown) + assertTrue(result.visibleRowIndices.isEmpty()) + } + } + + /** A same-id override replaces its tab in place (keeping strip position); a new id appends after. */ + @Test + fun withOverridesReplacesInPlaceAndAppends() { + val original = PropertyTab(PropertyTabId.Document, Res.string.properties_tab_document, { error("icon unused") }, { true }, { emptyList() }) + val base = PropertyTabRegistry(listOf(original)) + val replacement = PropertyTab(PropertyTabId.Document, Res.string.properties_tab_document, { error("icon unused") }, { true }, { emptyList() }) + val appended = PropertyTab(PropertyTabId.Object, Res.string.properties_tab_object, { error("icon unused") }, { true }, { emptyList() }) + + val merged = base.withOverrides(listOf(replacement, appended)) + + val visibleContext = PropertyContext(emptyPuppet(), Selection(), null, session = null) + assertEquals(listOf(PropertyTabId.Document, PropertyTabId.Object), merged.visibleTabs(visibleContext).map { it.id }) + assertSame(replacement, merged.tab(PropertyTabId.Document)) + assertSame(appended, merged.tab(PropertyTabId.Object)) + // The base registry is untouched - withOverrides returns a new registry. + assertSame(original, base.tab(PropertyTabId.Document)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/RuntimeGatingTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/RuntimeGatingTest.kt new file mode 100644 index 0000000..84115c4 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/properties/RuntimeGatingTest.kt @@ -0,0 +1,219 @@ +package org.umamo.ui.properties + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.AlphaBlendMode +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartGroupMode +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RuntimeTarget +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.properties_field_alpha_mode +import org.umamo.ui.resources.properties_field_invert_mask +import org.umamo.ui.resources.properties_field_masked_by +import org.umamo.ui.resources.properties_field_multiply_color +import org.umamo.ui.resources.properties_field_opacity +import org.umamo.ui.resources.properties_field_quad_transform +import org.umamo.ui.resources.properties_field_runtime_target +import org.umamo.ui.resources.properties_field_screen_color +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins the runtime-target gating: the pure option filters (supported values plus the current one), + * and the section shapes - which rows each Data-tab section builds under a restrictive target. + * Compose-free like PropertyTabRegistryTest: `rows(context)` is a pure call and row terms identify + * the rows without composing them. + */ +class RuntimeGatingTest { + private val drawableId = DrawableId("drawable") + private val partId = PartId("part") + + private fun drawable( + blendMode: BlendMode = BlendMode.Normal, + alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over, + ): Drawable = + Drawable( + id = drawableId, + name = drawableId.raw, + parentDeformerId = null, + blendMode = blendMode, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + alphaBlendMode = alphaBlendMode, + ) + + private fun puppetWith(target: RuntimeTarget, drawables: List = emptyList(), parts: List = emptyList()): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = parts, + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { entry -> OrgChild.Drawable(entry.id) } + parts.map { entry -> OrgChild.Part(entry.id) }, + rootPartId = null, + runtimeTarget = target, + ) + + private fun drawableContext( + target: RuntimeTarget, + blendMode: BlendMode = BlendMode.Normal, + alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over, + ): PropertyContext { + val selected = SelectionTarget.Drawable(drawableId) + return PropertyContext( + puppetWith(target, drawables = listOf(drawable(blendMode, alphaBlendMode))), + Selection(setOf(selected), selected), + selected, + session = null, + ) + } + + private fun isolatedPartContext(target: RuntimeTarget): PropertyContext { + val selected = SelectionTarget.Part(partId) + val isolated = Part(partId, "part", children = emptyList(), groupMode = PartGroupMode.Isolated) + return PropertyContext( + puppetWith(target, parts = listOf(isolated)), + Selection(setOf(selected), selected), + selected, + session = null, + ) + } + + @Test + fun blendModeOptionsFilterToLegacyPlusCurrent() { + val legacyOnly = blendModeDisplayOrder().filter { mode -> mode.isLegacy } + assertEquals(legacyOnly, blendModeOptionsFor(RuntimeTarget.Cubism50, BlendMode.Normal)) + assertEquals(legacyOnly, blendModeOptionsFor(RuntimeTarget.Ayagami, BlendMode.Normal), "Ayagami is 5.0-level") + + // An unsupported stored value stays selectable, in its display-order position. + val withCurrent = blendModeDisplayOrder().filter { mode -> mode.isLegacy || mode == BlendMode.Overlay } + assertEquals(withCurrent, blendModeOptionsFor(RuntimeTarget.Cubism50, BlendMode.Overlay)) + + assertEquals(blendModeDisplayOrder(), blendModeOptionsFor(RuntimeTarget.NoTarget, BlendMode.Normal)) + assertEquals(blendModeDisplayOrder(), blendModeOptionsFor(RuntimeTarget.Cubism53, BlendMode.Normal)) + } + + @Test + fun partGroupModeOptionsExcludeIsolatedUnlessCurrent() { + assertEquals( + listOf(PartGroupModeKind.PassThrough, PartGroupModeKind.Grouped), + partGroupModeOptionsFor(RuntimeTarget.Cubism50, PartGroupModeKind.Grouped), + ) + assertEquals( + PartGroupModeKind.entries.toList(), + partGroupModeOptionsFor(RuntimeTarget.Cubism50, PartGroupModeKind.Isolated), + "an already-isolated part keeps its mode selectable", + ) + assertEquals(PartGroupModeKind.entries.toList(), partGroupModeOptionsFor(RuntimeTarget.Cubism53, PartGroupModeKind.Grouped)) + } + + @Test + fun alphaBlendRowNeedsTheModeAndTheTargetOrAStoredValue() { + assertTrue(showsAlphaBlendRow(RuntimeTarget.Cubism53, BlendMode.Normal, AlphaBlendMode.Over)) + assertTrue(showsAlphaBlendRow(RuntimeTarget.NoTarget, BlendMode.Normal, AlphaBlendMode.Over)) + assertFalse( + showsAlphaBlendRow(RuntimeTarget.Cubism50, BlendMode.Normal, AlphaBlendMode.Over), + "alpha modes are part of the 5.3 blend feature", + ) + assertTrue( + showsAlphaBlendRow(RuntimeTarget.Cubism50, BlendMode.Normal, AlphaBlendMode.Atop), + "a stored out-of-target value never vanishes from its own control", + ) + assertFalse( + showsAlphaBlendRow(RuntimeTarget.Cubism53, BlendMode.AdditivePremultiplied, AlphaBlendMode.Over), + "premultiplied modes ignore alpha", + ) + } + + @Test + fun alphaBlendModeOptionsFilterToOverPlusCurrent() { + assertEquals( + listOf(AlphaBlendMode.Over, AlphaBlendMode.Atop), + alphaBlendModeOptionsFor(RuntimeTarget.Cubism50, AlphaBlendMode.Atop), + "the stored value stays, and Over is the only forward move", + ) + assertEquals(AlphaBlendMode.entries.toList(), alphaBlendModeOptionsFor(RuntimeTarget.Cubism53, AlphaBlendMode.Over)) + } + + @Test + fun blendSectionRowsGateColorsAlphaAndReversedMaskByTier() { + val cubism40Terms = BlendSection.rows(drawableContext(RuntimeTarget.Cubism40)).flatMap { row -> row.terms } + assertFalse(Res.string.properties_field_multiply_color in cubism40Terms, "multiply color is 4.2+") + assertFalse(Res.string.properties_field_screen_color in cubism40Terms, "screen color is 4.2+") + assertFalse(Res.string.properties_field_alpha_mode in cubism40Terms, "alpha modes are 5.3+") + assertTrue(Res.string.properties_field_invert_mask in cubism40Terms, "reversed mask is supported at 4.0") + + val cubism33Terms = BlendSection.rows(drawableContext(RuntimeTarget.Cubism33)).flatMap { row -> row.terms } + assertFalse(Res.string.properties_field_invert_mask in cubism33Terms, "reversed mask is 4.0+") + + val noTargetTerms = BlendSection.rows(drawableContext(RuntimeTarget.NoTarget)).flatMap { row -> row.terms } + assertTrue(Res.string.properties_field_multiply_color in noTargetTerms) + assertTrue(Res.string.properties_field_alpha_mode in noTargetTerms) + assertTrue(Res.string.properties_field_invert_mask in noTargetTerms) + } + + @Test + fun partSectionHidesTheCompositeBlockBelowFiveThree() { + val gatedTerms = PartSection.rows(isolatedPartContext(RuntimeTarget.Cubism50)).flatMap { row -> row.terms } + assertFalse(Res.string.properties_field_opacity in gatedTerms, "the composite block hides as one unit") + assertFalse(Res.string.properties_field_masked_by in gatedTerms) + + val fullTerms = PartSection.rows(isolatedPartContext(RuntimeTarget.Cubism53)).flatMap { row -> row.terms } + assertTrue(Res.string.properties_field_opacity in fullTerms, "5.3 keeps the composite editable") + assertTrue(Res.string.properties_field_masked_by in fullTerms) + } + + @Test + fun deformerSectionGatesTheQuadTransformRow() { + val warp = + Deformer.Warp( + id = DeformerId("warp"), + name = "warp", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = false, + geometryGrid = null, + ) + val selected = SelectionTarget.Deformer(warp.id) + + fun contextFor(target: RuntimeTarget): PropertyContext { + val puppet = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = listOf(warp), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + runtimeTarget = target, + ) + return PropertyContext(puppet, Selection(setOf(selected), selected), selected, session = null) + } + + val cubism30Terms = DeformerSection.rows(contextFor(RuntimeTarget.Cubism30)).flatMap { row -> row.terms } + assertFalse(Res.string.properties_field_quad_transform in cubism30Terms, "the new warp method is 3.3+") + assertFalse(Res.string.properties_field_multiply_color in cubism30Terms, "deformer tints are 4.2+") + + val cubism33Terms = DeformerSection.rows(contextFor(RuntimeTarget.Cubism33)).flatMap { row -> row.terms } + assertTrue(Res.string.properties_field_quad_transform in cubism33Terms) + } + + @Test + fun runtimeSectionBuildsTheSelectorAndTheListRow() { + val rows = RuntimeSection.rows(drawableContext(RuntimeTarget.Cubism50)) + assertEquals(2, rows.size) + assertTrue(Res.string.properties_field_runtime_target in rows.first().terms) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/CjkFontSelectionTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/CjkFontSelectionTest.kt new file mode 100644 index 0000000..0faa811 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/CjkFontSelectionTest.kt @@ -0,0 +1,47 @@ +package org.umamo.ui.theme + +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.noto_sans_cjk_jp_regular +import org.umamo.ui.resources.noto_sans_cjk_kr_regular +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the UI-language to Noto Sans CJK cut mapping. + * + * The cut has to be selected rather than appended to the family: every language-specific Noto Sans CJK + * cut carries the same codepoints, so a second cut listed after the first is unreachable - fallback + * fires on a missing glyph, and nothing is missing. A refactor that "adds Korean support" by appending + * the KR face instead of selecting it renders identically to having no KR face at all, which no visual + * check would catch. This test fails that refactor. + */ +class CjkFontSelectionTest { + /** + * Korean takes the KR cut; every other UI language falls to JP. + */ + @Test + fun koreanTakesTheKoreanCut() { + assertEquals(Res.font.noto_sans_cjk_kr_regular, cjkFontFor("ko"), "ko") + assertEquals(Res.font.noto_sans_cjk_jp_regular, cjkFontFor("ja"), "ja") + assertEquals(Res.font.noto_sans_cjk_jp_regular, cjkFontFor("en"), "en") + } + + /** + * A regional or oddly-cased tag resolves like its bare lowercase language subtag. + */ + @Test + fun regionalAndCasedTagsResolveLikeTheBareLanguage() { + assertEquals(Res.font.noto_sans_cjk_kr_regular, cjkFontFor("ko-KR"), "ko-KR") + assertEquals(Res.font.noto_sans_cjk_kr_regular, cjkFontFor("KO"), "KO") + assertEquals(Res.font.noto_sans_cjk_jp_regular, cjkFontFor("en-US"), "en-US") + } + + /** + * An unknown or empty tag falls back to JP rather than throwing. + */ + @Test + fun unknownTagsFallBackToJapanese() { + assertEquals(Res.font.noto_sans_cjk_jp_regular, cjkFontFor("de"), "de") + assertEquals(Res.font.noto_sans_cjk_jp_regular, cjkFontFor(""), "empty") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/CursorTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/CursorTest.kt new file mode 100644 index 0000000..9749a82 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/CursorTest.kt @@ -0,0 +1,180 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Canvas +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.drawscope.CanvasDrawScope +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.LayoutDirection +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Verifies the bundled cursor set parses (accessing [LocalUmamoCursors] forces every path through the SVG + * path parser) and that each cursor is drawable: a positive viewport, at least one layer, and every layer + * carrying real geometry that is actually painted. A second group rasterizes drawCursor to confirm the + * hotspot lands on the caller's anchor. + */ +class CursorTest { + private val cursors = LocalUmamoCursors + + /** Every cursor in the set, so the assertions below cover all of them rather than a sample. */ + private val allCursors: List> = + listOf( + "blade" to cursors.blade, + "bothHandles" to cursors.bothHandles, + "crosshairContrast" to cursors.crosshairContrast, + "crosshair" to cursors.crosshair, + "dot" to cursors.dot, + "eArrow" to cursors.eArrow, + "eraser" to cursors.eraser, + "ewScroll" to cursors.ewScroll, + "eyedropper" to cursors.eyedropper, + "hSplit" to cursors.hSplit, + "hand" to cursors.hand, + "handClosed" to cursors.handClosed, + "handPoint" to cursors.handPoint, + "knife" to cursors.knife, + "leftHandle" to cursors.leftHandle, + "mute" to cursors.mute, + "nArrow" to cursors.nArrow, + "nsScroll" to cursors.nsScroll, + "nsewScroll" to cursors.nsewScroll, + "paint" to cursors.paint, + "pencil" to cursors.pencil, + "pickArea" to cursors.pickArea, + "pointer" to cursors.pointer, + "rightHandle" to cursors.rightHandle, + "sArrow" to cursors.sArrow, + "slip" to cursors.slip, + "stop" to cursors.stop, + "swapArea" to cursors.swapArea, + "textEdit" to cursors.textEdit, + "vSplit" to cursors.vSplit, + "vertexLoop" to cursors.vertexLoop, + "wArrow" to cursors.wArrow, + "wait" to cursors.wait, + "xMove" to cursors.xMove, + "yMove" to cursors.yMove, + "zoomIn" to cursors.zoomIn, + "zoomOut" to cursors.zoomOut, + ) + + /** The list above must hold the entire set, so no cursor slips past the per-cursor checks. */ + @Test + fun everyCursorIsCovered() { + assertTrue(allCursors.size == 37, "expected all 37 cursors, listed ${allCursors.size}") + } + + /** Every cursor parses to a positive viewport and bounds with at least one non-empty, painted layer. */ + @Test + fun bundledCursorSetParses() { + for ((name, cursor) in allCursors) { + assertTrue(cursor.viewportWidth > 0f && cursor.viewportHeight > 0f, "$name has a positive viewport") + assertTrue(cursor.bounds.width > 0f && cursor.bounds.height > 0f, "$name has positive art bounds") + assertTrue(cursor.layers.isNotEmpty(), "$name has at least one layer") + assertTrue(cursor.layers.all { layer -> !layer.path.isEmpty }, "$name layers carry geometry") + assertTrue( + cursor.layers.all { layer -> layer.fill != null || layer.stroke != null }, + "$name layers are all painted (a fill, a stroke, or both)", + ) + } + } + + /** A few hotspots are pinned so a bad edit to the map is caught. */ + @Test + fun keyHotspotsAreLocked() { + assertEquals(CursorHotspot.TopLeft, cursors.pointer.hotspot, "pointer tip is top-left") + assertEquals(CursorHotspot.BottomLeft, cursors.eyedropper.hotspot, "eyedropper nib is bottom-left") + assertEquals(CursorHotspot.TopRight, cursors.eraser.hotspot, "eraser head is top-right") + assertEquals(CursorHotspot.TopCenter, cursors.handPoint.hotspot, "pointing fingertip is top-center") + assertEquals(CursorHotspot.MiddleCenter, cursors.crosshair.hotspot, "crosshair is centered") + // pick_area is a lone +; its hotspot is the center of its own bounds, i.e. the default. + assertEquals(CursorHotspot.MiddleCenter, cursors.pickArea.hotspot, "pick_area + is centered") + } + + /** Shifting the anchor shifts the painted art by the same vector (stroke expansion cancels out). */ + @Test + fun drawCursorTracksTheAnchor() { + val first = paintedBounds(cursors.pointer, Offset(60f, 55f), 100f) + val second = paintedBounds(cursors.pointer, Offset(100f, 80f), 100f) + assertNotNull(first, "pointer rendered at the first anchor") + assertNotNull(second, "pointer rendered at the second anchor") + // Anchor moved by (40, 25); every edge of the painted box must move with it. + assertTrue(abs((second.left - first.left) - 40) <= 1, "minX tracks anchor dx") + assertTrue(abs((second.top - first.top) - 25) <= 1, "minY tracks anchor dy") + assertTrue(abs((second.right - first.right) - 40) <= 1, "maxX tracks anchor dx") + assertTrue(abs((second.bottom - first.bottom) - 25) <= 1, "maxY tracks anchor dy") + } + + /** A MiddleCenter hotspot centers the painted art on the anchor; a corner hotspot offsets it. */ + @Test + fun hotspotPlacesArtRelativeToAnchor() { + val anchor = Offset(110f, 100f) + // crosshair is centered: the painted box straddles the anchor evenly (symmetric stroke keeps the + // center exact even though it widens the box). + val centered = paintedBounds(cursors.crosshair, anchor, 80f) + assertNotNull(centered, "crosshair rendered") + assertTrue(abs((centered.left + centered.right) / 2f - anchor.x) <= 2f, "crosshair center x on anchor") + assertTrue(abs((centered.top + centered.bottom) / 2f - anchor.y) <= 2f, "crosshair center y on anchor") + + // pointer is TopLeft: the arrow tip sits on the anchor and the body lies down-right of it. + val corner = paintedBounds(cursors.pointer, anchor, 100f) + assertNotNull(corner, "pointer rendered") + assertTrue(abs(corner.left - anchor.x) <= 8f, "pointer tip x near anchor (within stroke half-width)") + assertTrue(abs(corner.top - anchor.y) <= 8f, "pointer tip y near anchor (within stroke half-width)") + assertTrue((corner.left + corner.right) / 2f > anchor.x + 10f, "pointer body is right of the anchor") + assertTrue((corner.top + corner.bottom) / 2f > anchor.y + 10f, "pointer body is below the anchor") + } + + /** Bounding box, in pixels, of everything drawCursor painted over a sentinel background. */ + private data class PaintedBox(val left: Int, val top: Int, val right: Int, val bottom: Int) + + /** + * Rasterizes [cursor] at [anchor]/[pixelSize] onto a sentinel-filled bitmap and returns the tight box + * of the painted (non-sentinel) pixels, or null if nothing was drawn. + */ + private fun paintedBounds(cursor: UmamoCursor, anchor: Offset, pixelSize: Float, dimension: Int = 220): PaintedBox? { + // Magenta is used by none of the cursors (white / black / blue / green), so it reads as "unpainted". + val sentinel = Color(1f, 0f, 1f, 1f) + val bitmap = ImageBitmap(dimension, dimension) + CanvasDrawScope().draw( + Density(1f), + LayoutDirection.Ltr, + Canvas(bitmap), + Size(dimension.toFloat(), dimension.toFloat()), + ) { + drawRect(color = sentinel) + drawCursor(cursor, anchor, pixelSize) + } + val pixels = bitmap.toPixelMap() + var minX = dimension + var minY = dimension + var maxX = -1 + var maxY = -1 + for (y in 0 until dimension) { + for (x in 0 until dimension) { + val pixel = pixels[x, y] + val delta = abs(pixel.red - sentinel.red) + abs(pixel.green - sentinel.green) + abs(pixel.blue - sentinel.blue) + if (delta > 0.2f) { + minX = min(minX, x) + minY = min(minY, y) + maxX = max(maxX, x) + maxY = max(maxY, y) + } + } + } + if (maxX < 0) { + return null + } + return PaintedBox(minX, minY, maxX, maxY) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/IconTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/IconTest.kt new file mode 100644 index 0000000..4275e84 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/IconTest.kt @@ -0,0 +1,48 @@ +package org.umamo.ui.theme + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Verifies the bundled icon set parses (accessing [LocalUmamoIcons] forces every path through the SVG + * path parser) and that the Blender-derived icons keep their two-tone structure: two non-empty layers, + * exactly one of them the full-strength highlight. + */ +class IconTest { + /** Every bundled icon parses to at least one non-empty layer. */ + @Test + fun bundledIconSetParses() { + val icons = LocalUmamoIcons + // A representative sample across both icon families; parsing already happened for the whole set + // the moment LocalUmamoIcons initialized. + for (icon in listOf(icons.reset, icons.search, icons.editorModeObject, icons.uvSelectFace)) { + assertTrue(icon.layers.isNotEmpty()) + assertTrue(icon.layers.all { layer -> !layer.path.isEmpty }) + } + } + + /** The Blender two-tone icons carry a muted context layer plus exactly one full-strength highlight. */ + @Test + fun compositeIconsAreTwoTone() { + val icons = LocalUmamoIcons + val compositeIcons = + mapOf( + "editorModeObject" to icons.editorModeObject, + "editorModeEdit" to icons.editorModeEdit, + "meshSelectVertex" to icons.meshSelectVertex, + "meshSelectEdge" to icons.meshSelectEdge, + "meshSelectFace" to icons.meshSelectFace, + "uvSelectVertex" to icons.uvSelectVertex, + "uvSelectEdge" to icons.uvSelectEdge, + "uvSelectFace" to icons.uvSelectFace, + ) + for ((name, icon) in compositeIcons) { + assertEquals(2, icon.layers.size, "$name has two layers") + assertTrue(icon.layers.all { layer -> !layer.path.isEmpty }, "$name layers are non-empty") + assertTrue(icon.layers.all { layer -> layer.style == IconStyle.Filled }, "$name layers are filled") + assertEquals(1, icon.layers.count { layer -> layer.opacity == 1f }, "$name has one highlight layer") + assertEquals(1, icon.layers.count { layer -> layer.opacity < 1f }, "$name has one muted layer") + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/ThemeColorsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/ThemeColorsTest.kt new file mode 100644 index 0000000..2862a73 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/theme/ThemeColorsTest.kt @@ -0,0 +1,74 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.graphics.Color +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins every umamoDarkColors value to its expected constant. The dark scheme is the shipped look and its + * rendered pixels are a contract: this test keeps a later refactor of the color table from silently + * shifting any token's value. Alpha-carrying tokens are asserted via .copy(alpha = ...) on the same base + * value for float bit-identity (values like 0.7f have no exact 8-bit hex form). + */ +class ThemeColorsTest { + /** + * Asserts every dark-scheme token against its pinned constant. + */ + @Test + fun darkSchemeValuesArePinned() { + val brandPurple = Color(0xFFBF86D7) + val mutedGrey = Color(0xFF9A9A9A) + val outlinerTan = Color(0xFFE19658) + val outlinerTeal = Color(0xFF00D4A3) + val colors = umamoDarkColors + assertEquals(Color(0xFF181818), colors.windowBackground, "windowBackground") + assertEquals(Color(0xFF181818), colors.menuBackground, "menuBackground") + assertEquals(Color(0xFF303030), colors.panelBackground, "panelBackground") + assertEquals(Color(0xFF262626), colors.tabBackground, "tabBackground") + assertEquals(Color(0xFF3A3A3A), colors.headerBackground, "headerBackground") + assertEquals(Color(0xFF414141), colors.rowHover, "rowHover") + assertEquals(Color(0xFF2B2B2B), colors.rowStripe, "rowStripe") + assertEquals(Color(0xFF181818), colors.divider, "divider") + assertEquals(Color(0xFF454545), colors.panelBorder, "panelBorder") + assertEquals(Color(0xFFA1A1A1), colors.panelBorderHover, "panelBorderHover") + assertEquals(Color(0xFF1A1A1A), colors.controlBorder, "controlBorder") + assertEquals(mutedGrey, colors.guideLine, "guideLine") + assertEquals(mutedGrey.copy(alpha = 0.4f), colors.treeGuideLine, "treeGuideLine") + assertEquals(Color(0xFFE3E3E3), colors.text, "text") + assertEquals(mutedGrey, colors.textMuted, "textMuted") + assertEquals(mutedGrey.copy(alpha = 0.3f), colors.textDisabled, "textDisabled") + assertEquals(brandPurple, colors.accent, "accent") + assertEquals(Color(0xFFD394ED), colors.accentHover, "accentHover") + assertEquals(Color(0xFFA96FC1), colors.accentPressed, "accentPressed") + assertEquals(Color(0xFFFFFFFF), colors.accentText, "accentText") + assertEquals(brandPurple, colors.selection, "selection") + assertEquals(Color(0xFFFFFFFF), colors.selectionText, "selectionText") + assertEquals(Color(0xFF545454), colors.controlBackground, "controlBackground") + assertEquals(Color(0xFFFFFFFF), colors.controlGlyph, "controlGlyph") + assertEquals(Color(0xFF656565), colors.buttonHover, "buttonHover") + assertEquals(Color(0xFFA96FC1), colors.buttonPressed, "buttonPressed") + assertEquals(Color(0xFF252525), colors.sliderTrack, "sliderTrack") + assertEquals(Color(0xFFD2D2D2), colors.sliderThumb, "sliderThumb") + assertEquals(brandPurple.copy(alpha = 0.16f), colors.dropZoneFill, "dropZoneFill") + assertEquals(brandPurple.copy(alpha = 0.28f), colors.dropZoneEmphasis, "dropZoneEmphasis") + assertEquals(brandPurple.copy(alpha = 0.4f), colors.dropTargetBackground, "dropTargetBackground") + assertEquals(brandPurple.copy(alpha = 0.5f), colors.selectionAncestorBackground, "selectionAncestorBackground") + assertEquals(brandPurple.copy(alpha = 0.25f), colors.searchMatchBackground, "searchMatchBackground") + assertEquals(mutedGrey.copy(alpha = 0.4f), colors.scrollbarThumb, "scrollbarThumb") + assertEquals(mutedGrey.copy(alpha = 0.7f), colors.scrollbarThumbHover, "scrollbarThumbHover") + assertEquals(Color(0x99000000), colors.overlayScrim, "overlayScrim") + assertEquals(Color(0xFFE0E0E0), colors.viewportBadgeText, "viewportBadgeText") + assertEquals(Color(0x99000000), colors.viewportBadgeBackground, "viewportBadgeBackground") + assertEquals(Color(0xCCFFFFFF), colors.viewportMarquee, "viewportMarquee") + assertEquals(Color(0xCC000000), colors.viewportMarqueeContrast, "viewportMarqueeContrast") + assertEquals(Color(0xFF3C3C3C), colors.transparencyCheckerLight, "transparencyCheckerLight") + assertEquals(Color(0xFF323232), colors.transparencyCheckerDark, "transparencyCheckerDark") + assertEquals(Color(0xFF343434), colors.viewportGridBackground, "viewportGridBackground") + assertEquals(Color(0xFF515151), colors.viewportGridLineMajor, "viewportGridLineMajor") + assertEquals(Color(0xFF454545), colors.viewportGridLineMinor, "viewportGridLineMinor") + assertEquals(outlinerTan, colors.outlinerObjectTint, "outlinerObjectTint") + assertEquals(outlinerTeal, colors.outlinerDeformTint, "outlinerDeformTint") + assertEquals(outlinerTan.copy(alpha = 0.2f), colors.outlinerObjectTintDimmed, "outlinerObjectTintDimmed") + assertEquals(outlinerTeal.copy(alpha = 0.2f), colors.outlinerDeformTintDimmed, "outlinerDeformTintDimmed") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/tracks/TrackAxisTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/tracks/TrackAxisTest.kt new file mode 100644 index 0000000..df843dc --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/tracks/TrackAxisTest.kt @@ -0,0 +1,291 @@ +package org.umamo.ui.tracks + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the track sheet's domain model - the one place a horizontal domain appears, and therefore the whole + * reason the keyform sheet and a future time-based dope sheet can share the same widgets. + */ +class TrackAxisTest { + /** A value maps to its proportional position, and the mapping inverts. */ + @Test + fun mapsAndInvertsAcrossTheDomain() { + val axis = TrackAxis(-30f, 30f) + assertEquals(0f, axis.fractionOf(-30f)) + assertEquals(0.5f, axis.fractionOf(0f)) + assertEquals(1f, axis.fractionOf(30f)) + assertEquals(0f, axis.valueAt(0.5f)) + assertEquals(-30f, axis.valueAt(0f)) + } + + /** + * A degenerate axis maps everything to the middle rather than dividing by zero. + * + * A parameter whose min equals its max is not animatable but still renders a row, and a NaN sweeping + * through the layout would take the whole panel with it. + */ + @Test + fun aDegenerateAxisDoesNotDivideByZero() { + val axis = TrackAxis(5f, 5f) + assertEquals(0.5f, axis.fractionOf(5f)) + assertEquals(0.5f, axis.fractionOf(999f)) + assertTrue(axis.fractionOf(0f).isFinite()) + } + + /** An out-of-range value maps outside 0..1 rather than being clamped, so it stays detectable. */ + @Test + fun outOfRangeStaysOutOfRange() { + val axis = TrackAxis(0f, 10f) + assertTrue(axis.fractionOf(-5f) < 0f) + assertTrue(axis.fractionOf(15f) > 1f) + } + + /** Ticks land on human-readable steps that scale with the domain, not a fixed count. */ + @Test + fun ticksUseAReadableStep() { + assertEquals(listOf(-30f, -20f, -10f, 0f, 10f, 20f, 30f), TrackAxis(-30f, 30f).ticks()) + assertEquals(listOf(-1f, -0.5f, 0f, 0.5f, 1f), TrackAxis(-1f, 1f).ticks()) + } + + /** A degenerate axis yields one tick instead of spinning. */ + @Test + fun degenerateTicksTerminate() { + assertEquals(listOf(5f), TrackAxis(5f, 5f).ticks()) + } + + /** The nearest mark within tolerance wins; nothing outside it is picked. */ + @Test + fun picksTheNearestMarkInRange() { + val marks = listOf(TrackKeyMark(0, 0f), TrackKeyMark(1, 10f), TrackKeyMark(2, 20f)) + assertEquals(10f, assertNotNull(nearestMark(marks, 11f, tolerance = 2f)).position) + assertNull(nearestMark(marks, 15f, tolerance = 2f), "a click between marks picks nothing") + assertEquals(20f, assertNotNull(nearestMark(marks, 100f, tolerance = 1000f)).position, "a wide tolerance still picks the nearest") + } + + /** A collapsed subtree is not walked; expanding one parent reveals only its own children. */ + @Test + fun flatteningDescendsOnlyIntoExpandedRows() { + val tree = + listOf( + TrackRow( + key = "owner", + label = "Owner", + children = + listOf( + TrackRow(key = "owner/a", label = "A"), + TrackRow(key = "owner/b", label = "B", children = listOf(TrackRow(key = "owner/b/1", label = "B1"))), + ), + ), + TrackRow(key = "other", label = "Other"), + ) + assertEquals(listOf("owner", "other"), flattenTrackRows(tree, emptySet()).map { line -> line.row.key }) + assertEquals( + listOf("owner", "owner/a", "owner/b", "other"), + flattenTrackRows(tree, setOf("owner")).map { line -> line.row.key }, + "expanding a parent must not expand its children too", + ) + assertEquals( + listOf("owner", "owner/a", "owner/b", "owner/b/1", "other"), + flattenTrackRows(tree, setOf("owner", "owner/b")).map { line -> line.row.key }, + ) + } + + /** Depth and the chevron flags come from the tree, not from the caller. */ + @Test + fun flatteningReportsDepthAndExpandability() { + val tree = listOf(TrackRow(key = "owner", label = "Owner", children = listOf(TrackRow(key = "leaf", label = "Leaf")))) + val collapsed = flattenTrackRows(tree, emptySet()).single() + assertEquals(0, collapsed.depth) + assertTrue(collapsed.expandable, "a row with children is expandable") + assertTrue(!collapsed.expanded) + val expanded = flattenTrackRows(tree, setOf("owner")) + assertEquals(1, expanded[1].depth) + assertTrue(!expanded[1].expandable, "a leaf has no chevron") + } + + /** A collapsed group still shows where its subtree's keys are, deduplicated and ordered. */ + @Test + fun summaryUnionsTheSubtreeMarks() { + val row = + TrackRow( + key = "owner", + label = "Owner", + marks = listOf(TrackKeyMark(0, 30f)), + children = + listOf( + TrackRow(key = "a", label = "A", marks = listOf(TrackKeyMark(0, 0f), TrackKeyMark(1, 30f))), + TrackRow(key = "b", label = "B", marks = listOf(TrackKeyMark(0, -30f), TrackKeyMark(1, 0f))), + ), + ) + assertEquals(listOf(-30f, 0f, 30f), summarizedMarks(row).map { mark -> mark.position }) + } + + /** + * Summary marks are renumbered to their ordinal within the summary. + * + * The winner's own ordinal is meaningless across the group - two channels keyed at one value can hold + * different ordinals - whereas a summary ordinal is a stable name the owner maps back to the whole set + * of keys the mark stands for. + */ + @Test + fun summaryMarksAreRenumberedByPosition() { + val row = + TrackRow( + key = "owner", + label = "Owner", + children = + listOf( + TrackRow(key = "a", label = "A", marks = listOf(TrackKeyMark(0, 30f), TrackKeyMark(1, 0f))), + TrackRow(key = "b", label = "B", marks = listOf(TrackKeyMark(5, 30f))), + ), + ) + val summary = summarizedMarks(row) + assertEquals(listOf(0f, 30f), summary.map { mark -> mark.position }, "ascending by position") + assertEquals(listOf(0, 1), summary.map { mark -> mark.keyIndex }, "and renumbered to that order") + assertTrue(summary.all { mark -> mark.editable }, "a summary is a handle on the keys beneath it") + } + + /** A key nothing can move is left out of the summary, so a summary mark never half-moves. */ + @Test + fun summarySkipsUneditableKeys() { + val row = + TrackRow( + key = "owner", + label = "Owner", + children = + listOf( + TrackRow(key = "blend", label = "Blend", marks = listOf(TrackKeyMark(0, 12f, editable = false))), + TrackRow(key = "a", label = "A", marks = listOf(TrackKeyMark(0, 30f))), + ), + ) + assertEquals(listOf(30f), summarizedMarks(row).map { mark -> mark.position }) + } + + /** A mark's shape survives the summary, so a blend-shape key still reads as a square when folded. */ + @Test + fun summaryKeepsTheFirstMarkShape() { + val row = + TrackRow( + key = "owner", + label = "Owner", + children = listOf(TrackRow(key = "a", label = "A", marks = listOf(TrackKeyMark(0, 0f, TrackKeyShape.Square)))), + ) + assertEquals(TrackKeyShape.Square, summarizedMarks(row).single().shape) + } + + /** + * A drag is bounded by the AXIS, not by neighbouring marks. + * + * Neighbours stopped being walls when keys gained the ability to cross: the grid re-sorts and permutes + * its cells to match, so clamping here would refuse a gesture the model accepts. + */ + @Test + fun dragBoundsSpanTheAxis() { + assertEquals(-30f..30f, dragBoundsOf(TrackAxis(-30f, 30f))) + assertEquals(0f..1f, dragBoundsOf(TrackAxis(0f, 1f))) + } + + /** A reversed axis still yields an ascending range, so coerceIn cannot throw on it. */ + @Test + fun dragBoundsAscendOnAReversedAxis() { + assertEquals(-30f..30f, dragBoundsOf(TrackAxis(30f, -30f))) + } + + /** A window maps onto a domain as a proportional slice of it. */ + @Test + fun aWindowSlicesItsDomainProportionally() { + val full = TrackAxis(-30f, 30f) + assertEquals(TrackAxis(-30f, 30f), TrackWindow.Full.axisOver(full)) + assertEquals(TrackAxis(-15f, 15f), TrackWindow(0.25f, 0.75f).axisOver(full)) + } + + /** + * The same window over two unrelated ranges lands at the same SCREEN positions. + * + * The reason the window is normalized: a linked pad shows two parameters at once, and a shared + * absolute window would overshoot the narrower one entirely. + */ + @Test + fun oneWindowKeepsTwoDomainsInStep() { + val window = TrackWindow(0.25f, 0.75f) + val wide = window.axisOver(TrackAxis(-30f, 30f)) + val narrow = window.axisOver(TrackAxis(0f, 1f)) + assertEquals(-15f, wide.start) + assertEquals(0.25f, narrow.start) + assertEquals(wide.fractionOf(0f), narrow.fractionOf(0.5f), 1e-5f, "both sit at the same screen x") + } + + /** Zooming holds the anchor under the pointer rather than drifting toward the center. */ + @Test + fun zoomingHoldsItsAnchor() { + val zoomed = TrackWindow.Full.zoomedBy(0.5f, focus = 0.25f) + assertEquals(0.5f, zoomed.span, 1e-5f) + assertEquals(0.25f, zoomed.start + zoomed.span * 0.25f, 1e-5f, "the anchored domain point stays put") + } + + /** Zooming out near an end walks the window inward instead of running off the domain. */ + @Test + fun zoomingOutStaysInsideTheDomain() { + val atEnd = TrackWindow(0.9f, 1f) + val zoomedOut = atEnd.zoomedBy(4f, focus = 1f) + assertTrue(zoomedOut.start >= 0f && zoomedOut.end <= 1f, "got $zoomedOut") + assertEquals(0.4f, zoomedOut.span, 1e-5f) + } + + /** Zoom is bounded at both ends: never past the whole domain, never below the pixel-mapping floor. */ + @Test + fun zoomIsBoundedBothWays() { + assertEquals(1f, TrackWindow.Full.zoomedBy(10f, focus = 0.5f).span, 1e-5f) + assertEquals(TrackWindow.MIN_SPAN, TrackWindow.Full.zoomedBy(1e-9f, focus = 0.5f).span, 1e-6f) + } + + /** + * Panning keeps the span and stops at either end of the domain. + * + * Compared with a tolerance rather than by value: the window is carried as two floats, so re-anchoring + * it lands an ULP off by construction. Asserting equality here would be asserting that float addition + * is exact, which is a different (and false) claim than the one this test is about. + */ + @Test + fun panningKeepsTheSpanAndStopsAtTheEnds() { + val window = TrackWindow(0.4f, 0.6f) + assertWindow(expectedStart = 0.5f, expectedEnd = 0.7f, actual = window.pannedBy(0.1f)) + assertWindow(0f, 0.2f, window.pannedBy(-9f), "panning past the start stops at it") + assertWindow(0.8f, 1f, window.pannedBy(9f), "panning past the end stops at it") + } + + /** + * Tick labels ROUND to two decimals rather than truncate: the axis generates ticks by repeated float + * addition, so a 0.2-step tick arrives as 0.59999996 - truncation labeled it "0.59" beside 0.2 and + * 0.4, and negative ticks truncated the other way. + */ + @Test + fun tickLabelsRoundInsteadOfTruncating() { + assertEquals("0.6", defaultTickLabel(0.59999996f), "accumulated float error rounds up to the meant tick") + assertEquals("-0.2", defaultTickLabel(-0.19999998f), "negative ticks round away from zero, not toward it") + assertEquals("10", defaultTickLabel(10.0f), "an integral tick drops its .0") + assertEquals("0.25", defaultTickLabel(0.25f), "an exact fraction is untouched") + } + + /** + * Asserts a window's bounds within float tolerance. + * + * @param Float expectedStart The expected visible start. + * @param Float expectedEnd The expected visible end. + * @param TrackWindow actual The window to check. + * @param String message A label for the failure. + */ + private fun assertWindow( + expectedStart: Float, + expectedEnd: Float, + actual: TrackWindow, + message: String = "window", + ) { + assertEquals(expectedStart, actual.start, 1e-5f, "$message: start") + assertEquals(expectedEnd, actual.end, 1e-5f, "$message: end") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/transform/DrawableWorldTransformTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/transform/DrawableWorldTransformTest.kt new file mode 100644 index 0000000..e692852 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/transform/DrawableWorldTransformTest.kt @@ -0,0 +1,191 @@ +package org.umamo.ui.transform + +import org.umamo.edit.EditorSession +import org.umamo.edit.meshBounds +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.originRelativeX +import org.umamo.runtime.model.originRelativeZ +import org.umamo.runtime.model.worldXFromOriginRelative +import org.umamo.runtime.model.worldZFromOriginRelative +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins the Properties Transform panel to the space the user actually sees. + * + * The bug this guards against: Drawable.mesh.positions is the BASE array, and a keyformed drawable's base + * is not its displayed shape (`displayed = base + Σ wᵢ·Δᵢ`). Reading or writing base directly showed + * numbers unrelated to the drawable - on a corpus model, a base array 1.9 units wide for a drawable 183.8 + * wide - so a small typed nudge became an enormous transform. These tests assert the rows measure and + * write the DISPLAYED geometry instead, and that the write is refused off the neutral pose (where the + * deformer-chain inverse is not exact). + */ +class DrawableWorldTransformTest { + private val drawableId = DrawableId("d") + private val parameterId = ParameterId("Param") + + /** A 10 x 10 base quad that the keyform grid then displaces and inflates to 100 x 100 at the default. */ + private val basePositions = floatArrayOf(0f, 0f, 10f, 0f, 10f, 10f, 0f, 10f) + + /** Deltas taking the 10 x 10 base to a 100 x 100 square at local (500, 500) - the "base is not what you see" case. */ + private val neutralDeltas = + floatArrayOf( + 450f, + 450f, + 540f, + 450f, + 540f, + 540f, + 450f, + 540f, + ) + + /** + * The one-drawable model every test measures. + * + * @param Float canvasSize The square canvas's side, with the world origin at its center; 0 leaves both at + * their (0, 0) defaults, where world and origin-relative readings coincide. + * @return PuppetModel The model. + */ + private fun model(canvasSize: Float = 0f): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(parameterId, "Param", min = -1f, max = 1f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(basePositions.copyOf(), FloatArray(basePositions.size), intArrayOf(0, 1, 2)), + geometryGrid = + KeyformGrid( + axes = listOf(KeyformAxis(parameterId, floatArrayOf(-1f, 0f, 1f))), + cells = + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(neutralDeltas.copyOf())), + KeyformCell(intArrayOf(1), MeshDeltaForm(neutralDeltas.copyOf())), + KeyformCell(intArrayOf(2), MeshDeltaForm(neutralDeltas.copyOf())), + ), + ), + ), + ), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = canvasSize, + canvasHeight = canvasSize, + worldOriginX = canvasSize / 2f, + worldOriginZ = -(canvasSize / 2f), + ) + + @Test + fun boundsReportTheDisplayedGeometryNotTheBaseArray() { + val puppet = model() + val neutral = puppet.parameters.associate { it.id to it.default } + + // The base array is a 10 x 10 quad at the origin; reading it would be the bug. + val baseBounds = meshBounds(puppet.drawables.first().mesh!!.positions) + assertEquals(10f, baseBounds.width, "precondition: the base array is small") + + val transform = drawableWorldTransform(puppet, neutral, drawableId)!! + assertEquals(100f, transform.bounds.width, "the row shows the displayed size, not the base size") + assertEquals(100f, transform.bounds.height) + assertTrue(transform.editable, "a neutral pose is editable") + } + + @Test + fun editingIsRefusedWhileTheRigIsPosed() { + val puppet = model() + val posed = mapOf(parameterId to 1f) + + val transform = drawableWorldTransform(puppet, posed, drawableId)!! + assertFalse(transform.editable, "the deformer-chain inverse is only exact at the neutral pose") + + // And the write path refuses too, so a stale enabled flag still cannot corrupt the mesh. + val session = EditorSession(puppet, initialPose = posed) + session.setDrawableWorldCenter(drawableId, 0f, 0f) + session.setDrawableWorldSize(drawableId, 1f, 1f) + assertFalse(session.canUndo.value, "a posed edit records nothing") + assertFalse(session.dirty.value) + } + + @Test + fun movingLandsTheDisplayedCenterOnTheRequestedPoint() { + val session = EditorSession(model()) + + session.setDrawableWorldCenter(drawableId, 0f, 0f) + + val moved = drawableWorldTransform(session.model.value, session.pose.value, drawableId)!! + assertEquals(0f, moved.bounds.centerX, "what you type is what the readout becomes") + assertEquals(0f, moved.bounds.centerY) + assertEquals(100f, moved.bounds.width, "a move does not resize") + assertTrue(session.canUndo.value, "one undo step") + + session.undo() + val restored = drawableWorldTransform(session.model.value, session.pose.value, drawableId)!! + assertEquals(500f, restored.bounds.centerX) + } + + @Test + fun resizingLandsTheDisplayedExtentsAndHoldsThePositionStill() { + val session = EditorSession(model()) + + session.setDrawableWorldSize(drawableId, 50f, 25f) + + val resized = drawableWorldTransform(session.model.value, session.pose.value, drawableId)!! + assertEquals(50f, resized.bounds.width) + assertEquals(25f, resized.bounds.height) + // The bounds center is the pivot, so the Position row does not move when Size is edited. Z is + // negated against the art's local y because world y grows UPWARD - the Z+ up convention the panel + // labels its rows with - so art sitting at local y 500 reads as Z -500. + assertEquals(500f, resized.bounds.centerX) + assertEquals(-500f, resized.bounds.centerY) + } + + @Test + fun positionReadsFromTheWorldAxes() { + // A 1000 canvas puts the origin at world (500, -500) - exactly where the displayed square is centered. + val session = EditorSession(model(canvasSize = 1000f)) + val puppet = session.model.value + val centered = drawableWorldTransform(puppet, session.pose.value, drawableId)!! + assertEquals(0f, puppet.originRelativeX(centered.bounds.centerX), "a mesh centered on the axes reads X 0") + assertEquals(0f, puppet.originRelativeZ(centered.bounds.centerY), "and Z 0, not the -500 world y") + + // Typing (10, 20) goes through the same conversions the Position rows use, one axis at a time. + session.setDrawableWorldCenter(drawableId, puppet.worldXFromOriginRelative(10f), puppet.worldZFromOriginRelative(20f)) + + val moved = drawableWorldTransform(session.model.value, session.pose.value, drawableId)!! + assertEquals(10f, session.model.value.originRelativeX(moved.bounds.centerX), "what you type is what the readout becomes") + assertEquals(20f, session.model.value.originRelativeZ(moved.bounds.centerY), "Z counts up from the red line") + assertEquals(510f, moved.bounds.centerX, "the world position is the typed value plus the origin") + assertEquals(-480f, moved.bounds.centerY) + assertTrue(session.canUndo.value, "one undo step") + } + + @Test + fun aNoOpEditRecordsNothing() { + val session = EditorSession(model()) + val current = drawableWorldTransform(session.model.value, session.pose.value, drawableId)!! + + session.setDrawableWorldCenter(drawableId, current.bounds.centerX, current.bounds.centerY) + session.setDrawableWorldSize(drawableId, current.bounds.width, current.bounds.height) + + assertFalse(session.canUndo.value) + assertFalse(session.dirty.value) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/CursorWrapStateTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/CursorWrapStateTest.kt new file mode 100644 index 0000000..901d7f7 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/CursorWrapStateTest.kt @@ -0,0 +1,95 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * The wrap-gesture bookkeeping rules (CursorWrapState) with the platform warp injected: the virtual + * pointer stays continuous across a teleport, the ACTUAL landing is folded (not the requested target), + * stale pre-warp events resolve to the landing, and a warp-less platform folds nothing. + */ +class CursorWrapStateTest { + private val size = IntSize(400, 300) + private val origin = Offset(1000f, 500f) + + /** A warp that lands exactly where asked - the ideal platform. */ + private fun exactWarp(): (Float, Float) -> Offset? = { screenX, screenY -> Offset(screenX, screenY) } + + @Test + fun virtualPointerIsRawBeforeAnyWrap() { + val state = CursorWrapState(exactWarp()) + assertEquals(Offset(120f, 80f), state.virtualPointer(Offset(120f, 80f))) + } + + @Test + fun interiorPointerNeverWraps() { + val state = CursorWrapState(exactWarp()) + assertNull(state.maybeWrap(Offset(200f, 150f), size, origin)) + assertEquals(Offset.Zero, state.wrapOffset) + } + + @Test + fun wrapKeepsTheVirtualPointerContinuous() { + val state = CursorWrapState(exactWarp()) + // The pointer reaches the right edge; the cursor teleports to the left interior. + val edgePosition = Offset(399f, 150f) + val landed = state.maybeWrap(edgePosition, size, origin) + assertNotNull(landed) + assertEquals(WRAP_INSET_PX, landed.x) + // The virtual pointer at the landing equals the pre-wrap position: the transform sees no jump. + assertEquals(edgePosition, state.virtualPointer(landed)) + } + + @Test + fun foldUsesTheActualLandingNotTheRequestedTarget() { + // A platform that rounds/rescales: it lands 3px right of every requested target. + val state = CursorWrapState({ screenX, screenY -> Offset(screenX + 3f, screenY) }) + val edgePosition = Offset(399f, 150f) + val landed = state.maybeWrap(edgePosition, size, origin) + assertNotNull(landed) + assertEquals(WRAP_INSET_PX + 3f, landed.x) + // Continuity still holds against the ACTUAL landing, so the offset absorbed the platform skew. + assertEquals(edgePosition, state.virtualPointer(landed)) + } + + @Test + fun warplessPlatformFoldsNothing() { + val state = CursorWrapState({ _, _ -> null }) + assertNull(state.maybeWrap(Offset(399f, 150f), size, origin)) + assertEquals(Offset.Zero, state.wrapOffset) + } + + @Test + fun missingAreaOriginFoldsNothing() { + val state = CursorWrapState(exactWarp()) + assertNull(state.maybeWrap(Offset(399f, 150f), size, areaScreenOrigin = null)) + assertEquals(Offset.Zero, state.wrapOffset) + } + + @Test + fun staleOldEdgeEventResolvesToTheLandingUntilAFreshOneArrives() { + val state = CursorWrapState(exactWarp()) + val landed = state.maybeWrap(Offset(399f, 150f), size, origin) + assertNotNull(landed) + // A queued pre-warp event still at the old edge (half a viewport from the landing) is stale. + assertEquals(landed, state.resolveArrival(Offset(398f, 150f), size)) + // The real post-warp event lands near the landing: fresh, and it clears the pending landing. + assertNull(state.resolveArrival(landed + Offset(1f, 0f), size)) + // With the landing confirmed, even a far position is a legitimate move, not a stale one. + assertNull(state.resolveArrival(Offset(398f, 150f), size)) + } + + @Test + fun resetClearsTheGestureBookkeeping() { + val state = CursorWrapState(exactWarp()) + state.maybeWrap(Offset(399f, 150f), size, origin) + state.reset() + assertEquals(Offset.Zero, state.wrapOffset) + // No pending landing survives the reset: nothing resolves as stale. + assertNull(state.resolveArrival(Offset(398f, 150f), size)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/CursorWrapTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/CursorWrapTest.kt new file mode 100644 index 0000000..d2064b4 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/CursorWrapTest.kt @@ -0,0 +1,70 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The cursor-wrap geometry that keeps a modal G / S / R gesture alive at the viewport edge: a pointer that + * reaches an edge teleports to the opposite side, and an interior pointer is left alone. Pure math, so it + * is tested without Compose input; the anchor-compensation and Robot call are exercised interactively. + */ +class CursorWrapTest { + private val size = IntSize(400, 300) + private val margin = 8f + private val inset = 32f + + @Test + fun interiorPointerDoesNotWrap() { + assertNull(computeCursorWrap(Offset(200f, 150f), size, margin, inset)) + } + + @Test + fun leftEdgeWrapsToTheRightInterior() { + assertEquals(Offset(400f - inset, 150f), computeCursorWrap(Offset(4f, 150f), size, margin, inset)) + } + + @Test + fun rightEdgeWrapsToTheLeftInterior() { + assertEquals(Offset(inset, 150f), computeCursorWrap(Offset(398f, 150f), size, margin, inset)) + } + + @Test + fun topEdgeWrapsToTheBottomInterior() { + assertEquals(Offset(200f, 300f - inset), computeCursorWrap(Offset(200f, 5f), size, margin, inset)) + } + + @Test + fun bottomEdgeWrapsToTheTopInterior() { + assertEquals(Offset(200f, inset), computeCursorWrap(Offset(200f, 297f), size, margin, inset)) + } + + @Test + fun cornerWrapsBothAxes() { + assertEquals(Offset(400f - inset, 300f - inset), computeCursorWrap(Offset(2f, 2f), size, margin, inset)) + } + + @Test + fun outOfBoundsStillWrapsAndClampsTheOtherAxis() { + // A move that already left the area on x still wraps; the untouched y stays clamped in bounds. + assertEquals(Offset(400f - inset, 150f), computeCursorWrap(Offset(-10f, 150f), size, margin, inset)) + } + + @Test + fun tooSmallAnAxisDoesNotWrap() { + // Width 30 <= inset + margin (40): wrapping would land back in the trigger zone, so it is skipped. + val sliver = IntSize(30, 300) + assertNull(computeCursorWrap(Offset(2f, 150f), sliver, margin, inset)) + } + + @Test + fun wrapTargetLandsClearOfTheTriggerZone() { + // The teleport point must not itself be within margin of an edge, or it would re-wrap forever. + val wrapped = computeCursorWrap(Offset(1f, 1f), size, margin, inset)!! + assertTrue(wrapped.x > margin && wrapped.x < size.width - margin) + assertTrue(wrapped.y > margin && wrapped.y < size.height - margin) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ImageFramingTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ImageFramingTest.kt new file mode 100644 index 0000000..6bd3ae1 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ImageFramingTest.kt @@ -0,0 +1,96 @@ +package org.umamo.ui.viewport + +import org.umamo.render.ContentBounds +import org.umamo.render.FrameBackdrop +import org.umamo.render.ViewportCamera +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs + +/** + * Export Image's framing rules: what each region captures, how the scale sizes it, and the refusals when a + * region has nothing to frame or would be too large. + */ +class ImageFramingTest { + private val areaView = ImageFrame(ViewportCamera(40f, -25f, 0.5f), 800, 600) + + // A 2000 x 3000 canvas, placed the way world space holds it: x in [0, 2000], z in [-3000, 0]. + private val canvas = ContentBounds(0f, -3000f, 2000f, 3000f) + private val content = ContentBounds(100f, -900f, 300.5f, 600f) + + /** + * Frames with the fixture rectangles, unwrapping a successful frame. + * + * @param ImageRegion region The region. + * @param Float scale The size multiplier. + * @return ImageFrame The frame. + */ + private fun framed(region: ImageRegion, scale: Float): ImageFrame = assertIs(resolveImageFrame(region, scale, areaView, canvas, content)).frame + + /** View at 100% is the area's own frame, pixel for pixel. */ + @Test + fun viewAtOneIsTheAreaPixelForPixel() { + assertEquals(areaView, framed(ImageRegion.View, 1f)) + } + + /** View's scale grows the zoom and the size together and keeps the area's center. */ + @Test + fun viewScalesItsZoomAndSizeTogetherAroundTheSameCenter() { + assertEquals(ImageFrame(ViewportCamera(40f, -25f, 1f), 1600, 1200), framed(ImageRegion.View, 2f)) + } + + /** Canvas at 100% draws one pixel per canvas pixel, centered on the canvas. */ + @Test + fun canvasAtOneIsOnePixelPerCanvasPixelCenteredOnTheCanvas() { + assertEquals(ImageFrame(ViewportCamera(1000f, -1500f, 1f), 2000, 3000), framed(ImageRegion.Canvas, 1f)) + } + + /** Content rounds a fractional size up to whole pixels, so nothing at its edge is cut. */ + @Test + fun contentRoundsUpToWholePixelsSoItsEdgesAreNotCut() { + val frame = framed(ImageRegion.Content, 0.5f) + // 300.5 x 0.5 = 150.25 rounds up to 151; 600 x 0.5 is exactly 300. + assertEquals(151 to 300, frame.width to frame.height) + assertEquals(ViewportCamera(250.25f, -600f, 0.5f), frame.camera) + } + + /** Each region names what it lacks when it has nothing to frame. */ + @Test + fun eachRegionRefusesWhenItHasNothingToFrame() { + assertEquals(ImageFrameResult.NoViewport, resolveImageFrame(ImageRegion.View, 1f, null, canvas, content)) + assertEquals(ImageFrameResult.NoCanvas, resolveImageFrame(ImageRegion.Canvas, 1f, areaView, null, content)) + assertEquals(ImageFrameResult.NothingVisible, resolveImageFrame(ImageRegion.Content, 1f, areaView, canvas, null)) + } + + /** An image past the edge limit is refused, carrying the size it would have had. */ + @Test + fun anImagePastTheEdgeLimitIsRefusedWithItsSize() { + assertEquals(ImageFrameResult.TooLarge(12000, 18000), resolveImageFrame(ImageRegion.Canvas, 6f, areaView, canvas, content)) + } + + /** The thumbnail square is filled by the longer side, with the shorter one centered. */ + @Test + fun aSquareFitFillsTheLongerSideAndCentersTheShorter() { + val frame = fitSquare(content, 256) + assertEquals(256 to 256, frame.width to frame.height) + // The 600-unit height is the longer side, so it spans the 256 pixels. + assertEquals(ViewportCamera(250.25f, -600f, 256f / 600f), frame.camera) + } + + /** Each background choice maps onto the renderer backdrop it draws over. */ + @Test + fun backgroundsMapToTheRendererBackdrop() { + val options = ImageExportOptions.Default + assertEquals(FrameBackdrop.Transparent, options.copy(background = ImageBackground.Transparent).frameBackdrop()) + assertEquals(FrameBackdrop.Grid, options.copy(background = ImageBackground.Grid).frameBackdrop()) + assertEquals(FrameBackdrop.Clear(1f, 0f, 0f, 1f), options.copy(background = ImageBackground.Solid, solidColorHex = "#FFFF0000").frameBackdrop()) + } + + /** A translucent solid color reaches the renderer premultiplied, as its framebuffer is. */ + @Test + fun aTranslucentSolidColorIsPremultiplied() { + val backdrop = assertIs(ImageExportOptions.Default.copy(background = ImageBackground.Solid, solidColorHex = "#80FFFFFF").frameBackdrop()) + assertEquals(backdrop.alpha, backdrop.red, 1e-6f) + assertEquals(128f / 255f, backdrop.alpha, 1e-6f) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/LiveParamsAdapterTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/LiveParamsAdapterTest.kt new file mode 100644 index 0000000..00a3320 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/LiveParamsAdapterTest.kt @@ -0,0 +1,75 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.EditorSession +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * What a live parameter preview does to a pending unkeyed channel edit. + * + * A pending value is chosen FOR one pose, and the session already discards them when a pose COMMIT moves. + * The preview path does not go through commit, so without its own discard a scrub would carry the pending + * value across every pose it passes through: a half-typed opacity would show as a flat override over the + * whole range being scrubbed, snapping back to the track only on release. + */ +class LiveParamsAdapterTest { + private val angleX = ParameterId("ParamAngleX") + private val target = KeyableTarget(KeyformOwner.Drawable(DrawableId("d")), FormChannel.OPACITY) + + private fun session(): EditorSession = + EditorSession( + PuppetModel( + parameters = listOf(Parameter(angleX, angleX.raw, min = -30f, max = 30f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + + private fun adapter(editorSession: EditorSession): Pair { + val liveParams = LiveParams(mapOf(angleX to 0f)) + return liveParams to LiveParamsAdapter(liveParams, editorSession) + } + + /** The first frame that actually moves the pose retires the pending edits - not the release. */ + @Test + fun aPreviewThatMovesThePoseRetiresPendingEdits() { + val editorSession = session() + val (liveParams, live) = adapter(editorSession) + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.5f)) + + live.preview(angleX, 15f) + + assertTrue(editorSession.pendingChannelEdits.value.isEmpty(), "retired on the way, not on release") + assertEquals(15f, liveParams.values[angleX], "and the preview still reached the render hand-off") + } + + /** + * A preview that does not move the pose leaves them alone. + * + * The parameter panel republishes the current value on every frame of a gesture that has not moved yet, + * and a typed-then-not-yet-keyed value must survive that - it is only invalidated by actually going + * somewhere else. + */ + @Test + fun aPreviewAtTheSameValueLeavesPendingEditsAlone() { + val editorSession = session() + val (_, live) = adapter(editorSession) + editorSession.setPendingChannelEdit(target, ChannelValue.Scalar(0.5f)) + + live.preview(angleX, 0f) + + assertEquals(ChannelValue.Scalar(0.5f), editorSession.pendingChannelEdits.value[target]) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/MeshGizmoGeometryTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/MeshGizmoGeometryTest.kt new file mode 100644 index 0000000..82099ec --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/MeshGizmoGeometryTest.kt @@ -0,0 +1,106 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshTopology +import org.umamo.render.ViewportCamera +import org.umamo.runtime.model.DrawableId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The shared gizmo element queries over synthetic GizmoMeshGeometry - the geometry-source-agnostic + * record the Edit overlay (deformer-projected world shapes) and the future UV editor (raw texture + * coordinates) both feed. Camera at origin with zoom 1 over a 200x200 area, so world (x, y) lands at + * screen (x + 100, 100 - y). + */ +class MeshGizmoGeometryTest { + private val camera = ViewportCamera(centerX = 0f, centerY = 0f, zoom = 1f) + private val size = IntSize(200, 200) + + // A two-triangle quad: v0 (0,0), v1 (20,0), v2 (0,20), v3 (20,20). + private val quadIndices = intArrayOf(0, 1, 2, 1, 3, 2) + private val quadPositions = floatArrayOf(0f, 0f, 20f, 0f, 0f, 20f, 20f, 20f) + + /** + * Builds the standard test quad as one gizmo geometry. + * + * @param String id The drawable id. + * @param FloatArray positions The interleaved positions; defaults to the standard quad. + * @return GizmoMeshGeometry The geometry under test. + */ + private fun quad(id: String, positions: FloatArray = quadPositions): GizmoMeshGeometry = + GizmoMeshGeometry(DrawableId(id), quadIndices, MeshTopology.uniqueEdges(quadIndices), positions) + + @Test + fun hitTestPicksTheVertexUnderThePointer() { + // v1 (20, 0) is at screen (120, 100); a pointer 1px off still hits within HIT_RADIUS_PX. + val hit = hitTestMeshes(MeshSelectMode.Vertex, listOf(quad("a")), Offset(121f, 101f), camera, size) + assertNotNull(hit) + assertEquals(DrawableId("a"), hit.drawableId) + assertEquals(MeshElement.Vertex(1), hit.element) + } + + @Test + fun hitTestMissesFarFromEveryVertex() { + assertNull(hitTestMeshes(MeshSelectMode.Vertex, listOf(quad("a")), Offset(160f, 160f), camera, size)) + } + + @Test + fun hitTestResolvesOverlappingMeshesToTheNearestElement() { + // Mesh b is the same quad shifted +2 world x, so its v0 sits at screen (102, 100). A pointer at + // (103, 100) is within radius of both meshes' v0; the visually closest (mesh b) must win. + val shifted = FloatArray(quadPositions.size) { index -> if (index % 2 == 0) quadPositions[index] + 2f else quadPositions[index] } + val hit = hitTestMeshes(MeshSelectMode.Vertex, listOf(quad("a"), quad("b", shifted)), Offset(103f, 100f), camera, size) + assertNotNull(hit) + assertEquals(DrawableId("b"), hit.drawableId) + assertEquals(MeshElement.Vertex(0), hit.element) + } + + @Test + fun boxEnclosesVerticesByScreenPosition() { + // A screen box over the quad's bottom edge (v0, v1 at screen y=100; v2, v3 sit higher at y=80). + val inside = elementsInBox(MeshSelectMode.Vertex, quad("a"), Offset(95f, 95f), Offset(125f, 105f), camera, size) + assertEquals(setOf(MeshElement.Vertex(0), MeshElement.Vertex(1)), inside) + } + + @Test + fun boxEnclosesOnlyEdgesWithBothEndpointsInside() { + val inside = elementsInBox(MeshSelectMode.Edge, quad("a"), Offset(95f, 95f), Offset(125f, 105f), camera, size) + assertEquals(setOf(MeshElement.Edge(0, 1)), inside) + } + + @Test + fun circleStampAddsThenErasesElements() { + val geometry = quad("a") + val seed = MeshSelection.editing(listOf(DrawableId("a"))) + // v3 (20, 20) is at screen (120, 80): a small brush there selects only it. + val painted = circleSelection(seed, erasing = false, Offset(120f, 80f), 5f, listOf(geometry), camera, size) + assertEquals(setOf(MeshElement.Vertex(3)), painted.elementsOf(DrawableId("a"))) + // The erase stamp over the same spot removes it again. + val erased = circleSelection(painted, erasing = true, Offset(120f, 80f), 5f, listOf(geometry), camera, size) + assertTrue(erased.elementsOf(DrawableId("a")).isEmpty()) + } + + @Test + fun highlightSetsDeriveUpFromSelectedVertices() { + // All three vertices of the first triangle selected: its edges and the face light up derived. + val highlight = + buildHighlightSets( + elements = setOf(MeshElement.Vertex(0), MeshElement.Vertex(1), MeshElement.Vertex(2)), + active = MeshElement.Vertex(2), + selectMode = MeshSelectMode.Vertex, + triangleIndices = quadIndices, + ) + assertEquals(setOf(0, 1, 2), highlight.selectedVertexIndices) + assertEquals(2, highlight.activeVertexIndex) + assertTrue(MeshElement.Edge(0, 1) in highlight.selectedEdges) + assertEquals(setOf(0), highlight.selectedFaceIndices) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ObjectPickControllerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ObjectPickControllerTest.kt new file mode 100644 index 0000000..9385293 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ObjectPickControllerTest.kt @@ -0,0 +1,89 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.render.pick.PickCandidate +import org.umamo.runtime.model.DrawableId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the object-pick decision tables ([resolveObjectClickSelection], [resolveAltOverlapPick]): the + * Blender click semantics the 2D viewport and the UV editor's Object mode both ship verbatim, since + * both feed the SAME session selection. + */ +class ObjectPickControllerTest { + private val drawableA = SelectionTarget.Drawable(DrawableId("a")) + private val drawableB = SelectionTarget.Drawable(DrawableId("b")) + + /** A plain click on a drawable replaces the whole selection with it. */ + @Test + fun plainClickOnADrawableReplacesTheSelection() { + val result = resolveObjectClickSelection(Selection(setOf(drawableA), drawableA), drawableB, toggleMembership = false) + assertEquals(setOf(drawableB), result.targets, "the hit replaces the previous selection") + assertEquals(drawableB, result.active, "the hit becomes active") + } + + /** A modified click on an unselected drawable toggles it into the selection and makes it active. */ + @Test + fun modifiedClickTogglesAnUnselectedDrawableIn() { + val result = resolveObjectClickSelection(Selection(setOf(drawableA), drawableA), drawableB, toggleMembership = true) + assertEquals(setOf(drawableA, drawableB), result.targets, "the hit joins the selection") + assertEquals(drawableB, result.active, "the newly added target becomes active") + } + + /** A second modified click on a selected drawable toggles it back out (Blender parity). */ + @Test + fun modifiedClickTogglesASelectedDrawableOut() { + val result = + resolveObjectClickSelection(Selection(setOf(drawableA, drawableB), drawableB), drawableB, toggleMembership = true) + assertEquals(setOf(drawableA), result.targets, "the hit leaves the selection") + assertEquals(drawableA, result.active, "the active target falls back to a remaining member") + } + + /** A plain click on empty canvas clears the selection. */ + @Test + fun plainClickOnEmptyCanvasClears() { + val result = resolveObjectClickSelection(Selection(setOf(drawableA), drawableA), target = null, toggleMembership = false) + assertTrue(result.isEmpty, "a plain empty-canvas click clears") + assertNull(result.active, "no active target survives a clear") + } + + /** A modified click on empty canvas keeps the selection untouched, active target included. */ + @Test + fun modifiedClickOnEmptyCanvasKeepsTheSelection() { + val current = Selection(setOf(drawableA, drawableB), drawableB) + val result = resolveObjectClickSelection(current, target = null, toggleMembership = true) + assertEquals(current, result, "a modified empty-canvas click changes nothing") + } + + /** An Alt click over empty canvas resolves to nothing - the selection stays as-is. */ + @Test + fun altPickOverEmptyCanvasResolvesToNone() { + assertIs(resolveAltOverlapPick(emptyList()), "no candidates means no action") + } + + /** An Alt click over exactly one candidate selects it directly, no picker involved. */ + @Test + fun altPickOverOneCandidateSelectsDirectly() { + val resolution = resolveAltOverlapPick(listOf(PickCandidate(DrawableId("a"), frontRank = 1f, centrality = 0.5f))) + val direct = assertIs(resolution, "a single candidate skips the picker") + assertEquals(DrawableId("a"), direct.id, "the sole candidate is the pick") + } + + /** An Alt click over a stack opens the overlap picker with the candidates in their given order. */ + @Test + fun altPickOverAStackShowsTheOverlapPickerInOrder() { + val candidates = + listOf( + PickCandidate(DrawableId("front"), frontRank = 2f, centrality = 0.2f), + PickCandidate(DrawableId("back"), frontRank = 1f, centrality = 0.9f), + ) + val resolution = resolveAltOverlapPick(candidates) + val overlap = assertIs(resolution, "two candidates need the picker") + assertEquals(candidates, overlap.candidates, "the front-to-back order is preserved") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/TransformAdjustRegistrationTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/TransformAdjustRegistrationTest.kt new file mode 100644 index 0000000..ba20930 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/TransformAdjustRegistrationTest.kt @@ -0,0 +1,114 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.EditorSession +import org.umamo.edit.IndividualOriginScope +import org.umamo.edit.MeshChange +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.ModalCaptureSource +import org.umamo.edit.OperatorParameter +import org.umamo.edit.ProportionalEditState +import org.umamo.edit.ProportionalRows +import org.umamo.edit.TransformGestureParameters +import org.umamo.edit.TransformParameterKeys +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.buildModalTransformCapture +import org.umamo.edit.withParameter +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.transform.captureDrawableWorld +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Pins the geometry-bound half of the transform gestures' strip registration: the slide factor + * clamps to its edge, and a registered Grab re-lands the base mesh from the record's base when its + * Move row is edited (the rows themselves are pinned in :edit's TransformAdjustTest). + */ +class TransformAdjustRegistrationTest { + private val drawableId = DrawableId("a") + + @Test + fun theSlideFactorClampsToTheEdge() { + val world = floatArrayOf(0f, 0f, 10f, 0f) + val slid = slideVertexByFactor(world, vertexIndex = 0, neighborIndex = 1, factor = 1.5f) + assertEquals(10f, slid[0], "past the far endpoint clamps onto it") + assertEquals(10f, slid[2], "the neighbor itself never moves") + val stayed = slideVertexByFactor(world, vertexIndex = 0, neighborIndex = 1, factor = -1f) + assertEquals(0f, stayed[0], "before the start clamps to the vertex") + } + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "a", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f), FloatArray(6), intArrayOf(0, 1, 2)), + geometryGrid = null, + ), + ), + rootChildren = listOf(OrgChild.Drawable(drawableId)), + rootPartId = null, + ) + + /** + * A registered Grab of the whole triangle, committed the way the Edit overlay commits it: the + * frozen capture, the moved world shape inverted onto the base, one step, then the registration. + */ + @Test + fun aRegisteredGrabReLandsFromTheBaseWhenItsMoveRowIsEdited() { + val session = EditorSession(model()) + val geometry = assertNotNull(captureDrawableWorld(session.model.value, emptyMap(), drawableId), "a direct drawable captures") + val transform = + assertNotNull( + buildModalTransformCapture( + sources = listOf(ModalCaptureSource(drawableId, geometry.world.copyOf(), intArrayOf(0, 1, 2), setOf(0, 1, 2))), + pivotMode = TransformPivotMode.MedianPoint, + individualOriginScope = IndividualOriginScope.ConnectivityIsland, + operatorKind = MeshOperatorKind.Grab, + activeAnchor = null, + cursorAnchor = null, + ), + ) + val landed = TransformGestureParameters(10f, 0f, 1f, 1f, 0f) + val entry = transform.entries.single() + val world = applyOperator(MeshOperatorKind.Grab, entry.positions, entry.groups, landed, emptyMap()) + session.commitMeshPositions(MeshChange.TransformVertices(mapOf(drawableId to listOf(0, 1, 2)), MeshOperatorKind.Grab), mapOf(drawableId to geometry.worldToBase(world, entry.movedIndices))) + assertEquals(10f, session.model.value.drawables.single().mesh!!.positions[0], "the grab landed") + var writtenBack: ProportionalEditState? = null + var writeBacks = 0 + val record = + assertNotNull( + registerMeshTransformAdjustment(session, "area-1", transform, mapOf(drawableId to geometry), landed, ProportionalRows.of(null, 200f)) { state -> + writtenBack = state + writeBacks++ + }, + ) + val stepsBefore = session.historyView.value.steps.size + + session.adjustLastOperation(record.parameters.withParameter(TransformParameterKeys.MOVE_X, OperatorParameter.FloatParameter(TransformParameterKeys.MOVE_X, TransformParameterKeys.MOVE_X, 25f, -100f, 100f))) + + val positions = session.model.value.drawables.single().mesh!!.positions + assertEquals(25f, positions[0], "the rerun moved from the BASE by the new delta, not from the landed shape") + assertEquals(35f, positions[2]) + assertEquals(10f, positions[5], "y is untouched") + assertEquals(stepsBefore, session.historyView.value.steps.size, "the step was amended in place") + assertEquals(1, writeBacks, "the proportional rows were written back once") + assertNull(writtenBack, "and they said off") + session.undo() + assertEquals(0f, session.model.value.drawables.single().mesh!!.positions[0], "one undo returns to the base") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvDisplayMappingTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvDisplayMappingTest.kt new file mode 100644 index 0000000..d76a168 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvDisplayMappingTest.kt @@ -0,0 +1,40 @@ +package org.umamo.ui.viewport + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Locks the UV editor's display mapping: texel units with the V axis flipped into the camera's Y-up + * convention. The orientation assertion is the load-bearing one - stored v = 0 is the TOP row of the + * atlas image, so it must land at display y = pageHeight (the top in a Y-up world), or the wireframe + * renders vertically mirrored against the drawn page. + */ +class UvDisplayMappingTest { + /** v = 0 (the image's top row) maps to y = pageHeight; v = 1 (the bottom row) maps to y = 0. */ + @Test + fun orientationLock() { + assertEquals(512f, uvToDisplayY(0f, 512), 1e-4f, "the top row lands at the Y-up top") + assertEquals(0f, uvToDisplayY(1f, 512), 1e-4f, "the bottom row lands at the Y-up bottom") + assertEquals(0f, uvToDisplayX(0f, 1024), 1e-4f) + assertEquals(1024f, uvToDisplayX(1f, 1024), 1e-4f) + } + + /** Round-tripping an array through display space and back is the identity (within float noise). */ + @Test + fun roundTripIdentity() { + val uvs = floatArrayOf(0f, 0f, 1f, 1f, 0.25f, 0.75f, 0.6f, 0.1f) + val roundTripped = displayToUv(uvToDisplay(uvs, 2048, 1024), 2048, 1024) + assertEquals(uvs.size, roundTripped.size) + for (componentIndex in uvs.indices) { + assertEquals(uvs[componentIndex], roundTripped[componentIndex], 1e-5f, "component $componentIndex round-trips") + } + } + + /** Non-square pages scale each axis by its own texel extent, so aspect is preserved on screen. */ + @Test + fun nonSquarePageAspect() { + val display = uvToDisplay(floatArrayOf(0.5f, 0.5f), 2048, 512) + assertEquals(1024f, display[0], 1e-3f, "u scales by the page width") + assertEquals(256f, display[1], 1e-3f, "v scales by the page height") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvEditFrameTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvEditFrameTest.kt new file mode 100644 index 0000000..4643095 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvEditFrameTest.kt @@ -0,0 +1,117 @@ +package org.umamo.ui.viewport + +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.DrawableLayerBinding +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Pins the UV editor's frame conversions - the two ends of an edit, reading a stored coordinate to + * show it and writing an authored one back - plus the commit discipline that keeps a vertex the user + * never moved bit-identical to what the document stores. + * + * The page-view frame is the load-bearing case for "changed nothing": it must be exactly the bare + * texel mapping in UvDisplayMapping.kt, or every page-view edit shifts. + */ +class UvEditFrameTest { + private fun packedBinding( + positionX: Float = 128f, + positionY: Float = 256f, + scaleX: Float = 1f, + scaleY: Float = 1f, + rotationDegrees: Float = 0f, + ): DrawableLayerBinding = + DrawableLayerBinding( + layerKey = "layer", + placement = AtlasPlacement(0, positionX, positionY, scaleX, scaleY, rotationDegrees), + pageWidth = 2048, + pageHeight = 1024, + ) + + /** A page frame is the plain texel mapping - no conversion, and it says so. */ + @Test + fun pageFrameIsTheStoredFrame() { + val frame = atlasPageEditFrame(pageWidth = 64, pageHeight = 32) + assertTrue(frame.isStoredFrame, "the page display IS the stored frame") + val (u, v) = frame.storedUvAt(16f, 16f) + assertEquals(displayToUvU(16f, 64), u, 0f, "u matches the bare display mapping exactly") + assertEquals(displayToUvV(16f, 32), v, 0f, "v matches the bare display mapping exactly") + val (displayX, displayY) = frame.displayAt(0.25f, 0.5f) + assertEquals(uvToDisplayX(0.25f, 64), displayX, 0f, "and back out exactly") + assertEquals(uvToDisplayY(0.5f, 32), displayY, 0f, "and back out exactly") + assertEquals(null, frame.asUvFrame(), "a page frame carries no normalized conversion") + } + + /** A layer frame round-trips a display point through the stored coordinates and back. */ + @Test + fun layerFrameRoundTripsThroughTheStoredCoordinates() { + val frame = sourceLayerEditFrame(packedBinding(rotationDegrees = 37.5f, scaleX = 0.86f, scaleY = 0.86f), 576, 646) + assertNotNull(frame, "a well-formed placement yields a frame") + assertFalse(frame.isStoredFrame, "a placed layer is not the stored frame") + for ((displayX, displayY) in listOf(0f to 0f, 137f to 251f, 575f to 645f)) { + val (u, v) = frame.storedUvAt(displayX, displayY) + val (backX, backY) = frame.displayAt(u, v) + assertEquals(displayX, backX, 1e-2f, "display x survives the round trip") + assertEquals(displayY, backY, 1e-2f, "display y survives the round trip") + } + } + + /** An unpacked drawable's art is its stored frame, so it takes the page view's own no-conversion path. */ + @Test + fun unpackedLayerFrameIsTheStoredFrame() { + val unpacked = DrawableLayerBinding("layer", placement = null, pageWidth = 0, pageHeight = 0) + val frame = sourceLayerEditFrame(unpacked, 64, 32) + assertNotNull(frame, "an unpacked binding still yields a frame") + assertTrue(frame.isStoredFrame, "with no placement the art IS the stored frame") + assertEquals(64, frame.displayWidth, "sized by the layer") + assertEquals(null, frame.asUvFrame(), "and carries no normalized conversion") + } + + /** A placement that cannot be inverted yields no frame rather than a wrong one. */ + @Test + fun degeneratePlacementYieldsNoFrame() { + assertEquals(null, sourceLayerEditFrame(packedBinding(scaleX = 0f), 64, 32), "a collapsed axis has no frame") + assertEquals(null, sourceLayerEditFrame(packedBinding(), layerWidth = 0, layerHeight = 32), "a zero-width layer has no frame") + } + + /** + * The commit discipline's load-bearing guarantee, over both frames: a commit leaves every vertex the + * operation did not move bit-identical. Converting whole arrays instead would mark untouched meshes + * as edited, warning the user on CMO3 export about mappings they never authored. + */ + @Test + fun commitLeavesUnmovedVerticesBitIdentical() { + val storedUvs = floatArrayOf(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f) + val frames = + listOf( + "page" to atlasPageEditFrame(2048, 1024), + "layer" to sourceLayerEditFrame(packedBinding(rotationDegrees = 37.5f, scaleX = 0.86f, scaleY = 0.86f), 576, 646)!!, + ) + for ((label, frame) in frames) { + // Display positions for every vertex, as a real gesture supplies - but only vertex 1 moved. + val displayPositions = FloatArray(storedUvs.size) { componentIndex -> 7f * (componentIndex + 1) } + val committed = storedUvsWithMoved(storedUvs, listOf(1), displayPositions, frame) + assertEquals(storedUvs[0].toRawBits(), committed[0].toRawBits(), "$label: vertex 0 u is untouched") + assertEquals(storedUvs[1].toRawBits(), committed[1].toRawBits(), "$label: vertex 0 v is untouched") + assertEquals(storedUvs[4].toRawBits(), committed[4].toRawBits(), "$label: vertex 2 u is untouched") + assertEquals(storedUvs[5].toRawBits(), committed[5].toRawBits(), "$label: vertex 2 v is untouched") + val (movedU, movedV) = frame.storedUvAt(displayPositions[2], displayPositions[3]) + assertEquals(movedU, committed[2], 0f, "$label: the moved vertex takes its authored u") + assertEquals(movedV, committed[3], 0f, "$label: the moved vertex takes its authored v") + } + } + + /** A moved index past either array's end is skipped rather than throwing. */ + @Test + fun commitIgnoresOutOfRangeMovedIndices() { + val storedUvs = floatArrayOf(0.1f, 0.2f) + val committed = storedUvsWithMoved(storedUvs, listOf(0, 9), floatArrayOf(4f, 8f), atlasPageEditFrame(64, 32)) + assertEquals(2, committed.size, "the result matches the stored array") + val (movedU, movedV) = atlasPageEditFrame(64, 32).storedUvAt(4f, 8f) + assertEquals(movedU, committed[0], 0f, "the in-range vertex is written") + assertEquals(movedV, committed[1], 0f, "the in-range vertex is written") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvIslandPickControllerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvIslandPickControllerTest.kt new file mode 100644 index 0000000..f64b5f0 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvIslandPickControllerTest.kt @@ -0,0 +1,312 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.unit.IntSize +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.render.DecodedImage +import org.umamo.render.ViewportCamera +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.RenderDrawable +import org.umamo.runtime.model.RenderGroup +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the UV editor's island-pick adapters (UvIslandPickController.kt): the static rest-pose front + * rank, the page alpha sampler, the two-tier front-most / stack picks over display-space islands + * (an island opaque at the click first, any island whose mesh contains it when none is), the + * any-vertex box rule, and the box-selection decision table. The shared pick internals + * (pickDrawable / pickAllDrawables) are :render-tested; these tests cover OUR bindings of them. + * + * The pick scene: two islands sharing one display-space triangle (0,4)-(4,4)-(0,0) on a 4x4 page + * whose texels are all opaque except (1, 1). The islands differ only in their stored uvs, so the + * alpha gate samples a different texel per island at the same click. + */ +class UvIslandPickControllerTest { + private val frontId = DrawableId("front") + private val backId = DrawableId("back") + + /** The shared display triangle: one island's on-page footprint. */ + private val displayTriangle = floatArrayOf(0f, 4f, 4f, 4f, 0f, 0f) + + /** Uvs whose barycentric blend at display (1, 3) lands on texel (1, 1) - the transparent one. */ + private val uvsHittingTransparentTexel = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f) + + /** Uvs pinned to uv (0, 0) - texel (0, 0), opaque - regardless of where the click lands. */ + private val uvsHittingOpaqueTexel = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f) + + /** A 4x4 page, fully opaque except texel (1, 1). */ + private fun fourByFourPage(): DecodedImage { + val rgba = ByteArray(4 * 4 * 4) { byteIndex -> if (byteIndex % 4 == 3) 0xFF.toByte() else 0 } + rgba[(1 * 4 + 1) * 4 + 3] = 0 + return DecodedImage(rgba, 4, 4) + } + + private fun stackedIslandsPick(frontUvs: FloatArray, backUvs: FloatArray): UvIslandPickController = + UvIslandPickController( + displayPositionsById = mapOf(frontId to displayTriangle, backId to displayTriangle), + indicesById = mapOf(frontId to intArrayOf(0, 1, 2), backId to intArrayOf(0, 1, 2)), + meshUvsById = mapOf(frontId to frontUvs, backId to backUvs), + frontRankById = mapOf(frontId to 1f, backId to 0f), + sampleAlpha = pageAlphaSampler(fourByFourPage()), + atlasSizeOf = { 4 to 4 }, + ) + + private fun rankDrawable(rawId: String, drawOrder: Float): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + drawOrder = drawOrder, + ) + + /** A grouped model ranks by the render-order group sort: the higher draw order ranks more front. */ + @Test + fun restFrontRankFollowsTheGroupedRenderOrder() { + val higher = rankDrawable("higher", drawOrder = 600f) + val lower = rankDrawable("lower", drawOrder = 400f) + val model = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(higher, lower), + rootChildren = emptyList(), + rootPartId = null, + renderRoot = RenderGroup(null, 500, listOf(RenderDrawable(higher.id), RenderDrawable(lower.id))), + ) + val rank = restFrontRank(model) + assertEquals(0f, rank[lower.id], "the lower draw order paints first (back)") + assertEquals(1f, rank[higher.id], "the higher draw order paints last (front)") + } + + /** A renderRoot-less model takes the flat paintOrder fallback; ties keep model order. */ + @Test + fun restFrontRankFallsBackToPaintOrderWithoutAGroupTree() { + val front = rankDrawable("front", drawOrder = 600f) + val backFirst = rankDrawable("backFirst", drawOrder = 500f) + val backSecond = rankDrawable("backSecond", drawOrder = 500f) + val model = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(front, backFirst, backSecond), + rootChildren = emptyList(), + rootPartId = null, + ) + val rank = restFrontRank(model) + assertEquals(2f, rank[front.id], "the higher draw order ranks most front") + assertEquals(0f, rank[backFirst.id], "tied draw orders keep model order") + assertEquals(1f, rank[backSecond.id], "tied draw orders keep model order") + } + + /** The sampler reads the alpha byte at the uv's texel; out-of-range coordinates clamp to the edge. */ + @Test + fun pageAlphaSamplerReadsTexelsAndClamps() { + // A 2x1 page: texel (0, 0) opaque, texel (1, 0) transparent. + val rgba = byteArrayOf(0, 0, 0, 0xFF.toByte(), 0, 0, 0, 0) + val sampler = pageAlphaSampler(DecodedImage(rgba, 2, 1)) + assertEquals(1f, sampler(frontId, 0.25f, 0.5f), "the opaque texel samples 1") + assertEquals(0f, sampler(frontId, 0.75f, 0.5f), "the transparent texel samples 0") + assertEquals(0f, sampler(frontId, 1.5f, 0.5f), "past the right edge clamps to the edge texel") + assertEquals(1f, sampler(frontId, -0.5f, 0.5f), "past the left edge clamps to the edge texel") + } + + /** A null page (the untextured 1x1 fallback) samples fully opaque, so untextured islands stay clickable. */ + @Test + fun pageAlphaSamplerTreatsANullPageAsOpaque() { + assertEquals(1f, pageAlphaSampler(null)(frontId, 0.5f, 0.5f), "no page means no alpha gate") + } + + /** With both islands opaque at the click, the higher front rank wins. */ + @Test + fun topmostPickResolvesByFrontRank() { + val pick = stackedIslandsPick(frontUvs = uvsHittingOpaqueTexel, backUvs = uvsHittingOpaqueTexel) + assertEquals(frontId, pick.topmostAt(1f, 3f), "the front island takes the click") + } + + /** + * A click on the front island's transparent texel falls through to the island beneath that is + * opaque there: the opaque tier outranks the front island's mesh, so overlapping islands resolve + * by the visible art. + */ + @Test + fun transparentOverhangFallsThroughToTheIslandBeneath() { + val pick = stackedIslandsPick(frontUvs = uvsHittingTransparentTexel, backUvs = uvsHittingOpaqueTexel) + assertEquals(backId, pick.topmostAt(1f, 3f), "the alpha gate rejects the front island") + } + + /** A click outside every island misses in both tiers. */ + @Test + fun topmostPickMissesOutsideEveryIsland() { + val pick = stackedIslandsPick(frontUvs = uvsHittingOpaqueTexel, backUvs = uvsHittingOpaqueTexel) + assertNull(pick.topmostAt(3.5f, 0.5f), "below the hypotenuse nothing is hit") + } + + /** + * The stack query lists every opaque island under the click, front-to-back; while any island is + * opaque there, one that is transparent there stays out of the stack. + */ + @Test + fun stackListsOpaqueIslandsFrontToBack() { + val bothOpaque = stackedIslandsPick(frontUvs = uvsHittingOpaqueTexel, backUvs = uvsHittingOpaqueTexel) + assertEquals(listOf(frontId, backId), bothOpaque.stackAt(1f, 3f).map { candidate -> candidate.id }, "front first") + val frontTransparent = stackedIslandsPick(frontUvs = uvsHittingTransparentTexel, backUvs = uvsHittingOpaqueTexel) + assertEquals(listOf(backId), frontTransparent.stackAt(1f, 3f).map { candidate -> candidate.id }, "the alpha gate filters the stack too") + } + + /** With no island opaque at the click, the geometry tier picks the front-most mesh containing it. */ + @Test + fun transparentClickFallsBackToTheFrontMostMesh() { + val pick = stackedIslandsPick(frontUvs = uvsHittingTransparentTexel, backUvs = uvsHittingTransparentTexel) + assertEquals(frontId, pick.topmostAt(1f, 3f), "the front island's mesh takes the click over its transparent texel") + } + + /** A lone island is clickable anywhere inside its mesh, including over a transparent texel. */ + @Test + fun loneIslandIsClickableOverATransparentTexel() { + val pick = + UvIslandPickController( + displayPositionsById = mapOf(backId to displayTriangle), + indicesById = mapOf(backId to intArrayOf(0, 1, 2)), + meshUvsById = mapOf(backId to uvsHittingTransparentTexel), + frontRankById = mapOf(backId to 0f), + sampleAlpha = pageAlphaSampler(fourByFourPage()), + atlasSizeOf = { 4 to 4 }, + ) + assertEquals(backId, pick.topmostAt(1f, 3f), "the mesh is the island, whatever the texel's alpha") + } + + /** + * With no island opaque at the click, the stack lists every mesh containing it, front-to-back, and + * their centralities tie - so the overlap popup's highest-centrality default resolves to the first + * row, the island a plain click there picks. + */ + @Test + fun stackFallsBackToGeometryWhenNothingIsOpaque() { + val pick = stackedIslandsPick(frontUvs = uvsHittingTransparentTexel, backUvs = uvsHittingTransparentTexel) + val candidates = pick.stackAt(1f, 3f) + assertEquals(listOf(frontId, backId), candidates.map { candidate -> candidate.id }, "front first") + assertEquals(1, candidates.map { candidate -> candidate.centrality }.distinct().size, "geometry-tier centralities tie") + } + + /** A stack query outside every island is empty in both tiers. */ + @Test + fun stackIsEmptyOutsideEveryIsland() { + val pick = stackedIslandsPick(frontUvs = uvsHittingTransparentTexel, backUvs = uvsHittingTransparentTexel) + assertTrue(pick.stackAt(3.5f, 0.5f).isEmpty(), "below the hypotenuse nothing is hit") + } + + /** An island is box-enclosed when ANY of its vertices falls inside; result keeps geometries order. */ + @Test + fun boxEnclosesIslandsByAnyVertex() { + val camera = ViewportCamera(centerX = 0f, centerY = 0f, zoom = 1f) + val size = IntSize(200, 200) + val nearIsland = GizmoMeshGeometry(DrawableId("near"), intArrayOf(0, 1, 2), emptyList(), floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f)) + val farIsland = GizmoMeshGeometry(DrawableId("far"), intArrayOf(0, 1, 2), emptyList(), floatArrayOf(80f, 80f, 90f, 80f, 80f, 90f)) + // A box around the near island's (0, 10) vertex alone: one enclosed vertex takes the island. + val cornerA = worldToScreen(-1f, 11f, camera, size) + val cornerB = worldToScreen(1f, 9f, camera, size) + assertEquals( + listOf(DrawableId("near")), + uvIslandsInBox(listOf(farIsland, nearIsland), cornerA, cornerB, camera, size), + "one enclosed vertex selects the island; the far island stays out", + ) + // A box around everything keeps the geometries' list order. + val allCornerA = worldToScreen(-5f, 95f, camera, size) + val allCornerB = worldToScreen(95f, -5f, camera, size) + assertEquals( + listOf(DrawableId("far"), DrawableId("near")), + uvIslandsInBox(listOf(farIsland, nearIsland), allCornerA, allCornerB, camera, size), + "the result preserves geometries order", + ) + } + + /** Plain box replaces; additive extends with the last enclosed island active. */ + @Test + fun boxSelectionReplacesOrExtends() { + val islandA = SelectionTarget.Drawable(DrawableId("a")) + val islandB = SelectionTarget.Drawable(DrawableId("b")) + val replaced = resolveIslandBoxSelection(Selection(setOf(islandA), islandA), listOf(islandB), additive = false) + assertEquals(setOf(islandB), replaced.targets, "a plain box replaces the selection") + assertEquals(islandB, replaced.active, "the last enclosed island becomes active") + val extended = resolveIslandBoxSelection(Selection(setOf(islandA), islandA), listOf(islandB), additive = true) + assertEquals(setOf(islandA, islandB), extended.targets, "an additive box keeps the current targets") + assertEquals(islandB, extended.active, "the last enclosed island becomes active") + } + + /** An additive box that enclosed nothing keeps the selection AND its active target. */ + @Test + fun emptyAdditiveBoxKeepsTheSelection() { + val islandA = SelectionTarget.Drawable(DrawableId("a")) + val current = Selection(setOf(islandA), islandA) + val result = resolveIslandBoxSelection(current, emptyList(), additive = true) + assertEquals(current, result, "nothing enclosed changes nothing") + } + + /** A plain box that enclosed nothing clears (the viewport's box rule). */ + @Test + fun emptyPlainBoxClears() { + val islandA = SelectionTarget.Drawable(DrawableId("a")) + val result = resolveIslandBoxSelection(Selection(setOf(islandA), islandA), emptyList(), additive = false) + assertTrue(result.isEmpty, "an empty plain box clears the selection") + assertNull(result.active, "no active target survives") + } + + /** + * The builder serves BOTH surfaces from one construction: it gates on whichever image the editor is + * showing, indexed by whichever mapping addresses it. This is what lets one Object overlay cover + * the page view and the source-layer view - the alpha gate follows the surface, so a click through + * transparent art falls through on the artwork exactly as it does on the page. + */ + @Test + fun builderGatesOnWhicheverImageIsShown() { + val geometries = + listOf( + GizmoMeshGeometry(frontId, intArrayOf(0, 1, 2), emptyList(), displayTriangle), + GizmoMeshGeometry(backId, intArrayOf(0, 1, 2), emptyList(), displayTriangle), + ) + val frontRank = mapOf(frontId to 1f, backId to 0f) + + // Front island mapped onto the transparent texel, back island onto an opaque one: the gate must + // reject the front and fall through, whatever the image happens to be. + val gated = + uvIslandPick( + geometries = geometries, + frontRank = frontRank, + uvsById = mapOf(frontId to uvsHittingTransparentTexel, backId to uvsHittingOpaqueTexel), + image = fourByFourPage(), + ) + assertEquals(backId, gated.topmostAt(1f, 3f), "the shown image's alpha decides the pick") + + // The SAME geometry with both mapped onto opaque art: front rank decides instead. + val ungated = + uvIslandPick( + geometries = geometries, + frontRank = frontRank, + uvsById = mapOf(frontId to uvsHittingOpaqueTexel, backId to uvsHittingOpaqueTexel), + image = fourByFourPage(), + ) + assertEquals(frontId, ungated.topmostAt(1f, 3f), "with no alpha rejection the front island wins") + + // No image at all (an untextured surface): everything reads opaque, so islands stay clickable. + val imageless = + uvIslandPick( + geometries = geometries, + frontRank = frontRank, + uvsById = mapOf(frontId to uvsHittingTransparentTexel, backId to uvsHittingOpaqueTexel), + image = null, + ) + assertEquals(frontId, imageless.topmostAt(1f, 3f), "with no image there is nothing to gate on") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvPlacementAdjustTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvPlacementAdjustTest.kt new file mode 100644 index 0000000..5c38707 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvPlacementAdjustTest.kt @@ -0,0 +1,227 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.EditorSession +import org.umamo.edit.IndividualOriginScope +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.ModalCaptureSource +import org.umamo.edit.OperatorParameter +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.buildModalTransformCapture +import org.umamo.edit.intValue +import org.umamo.edit.setAtlasPlacements +import org.umamo.edit.withParameter +import org.umamo.format.art.LayerBounds +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.atlasPixelOf +import org.umamo.runtime.model.layerPixelOf +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the placement gesture as an operation settings strip client: a confirmed Grab / Rotate / + * Scale registers its numbers as rows, an adjustment re-evaluates the SAME frozen gesture from the + * base snapshot (the pivot it turns about is the one frozen at latch) and rewrites the gesture's own + * step, the landing callback sees each adjustment, one undo returns to the base, and any other push + * ends the record. + */ +class UvPlacementAdjustTest { + private val tileId = AtlasTileId("a") + private val drawableId = DrawableId("dA") + private val pageSide = 64 + private val original = AtlasPlacement(pageIndex = 0, positionX = 4f, positionY = 4f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f) + private val trim = LayerBounds(0, 0, 10, 10) + + /** The island's display positions: the tile's 10x10 art at page (4, 4), display y up. */ + private val positions = floatArrayOf(4f, 60f, 14f, 60f, 4f, 50f, 14f, 50f) + private val indices = intArrayOf(0, 1, 2, 1, 3, 2) + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "dA", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = + DrawableMesh( + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), + floatArrayOf(4f / 64, 4f / 64, 14f / 64, 4f / 64, 4f / 64, 14f / 64, 14f / 64, 14f / 64), + indices, + ), + geometryGrid = null, + atlasTileId = tileId, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = 50f, + atlas = PuppetAtlas(pages = listOf(AtlasPage(pageSide, pageSide)), tiles = listOf(AtlasTile(tileId, "a", 10, 10, original))), + ) + + /** + * A frozen gesture over the one island, the way the overlay builds it at latch: the shared + * capture's median anchor is the tile's pivot. + * + * @param MeshOperatorKind kind The latched operator. + * @return PlacementGesture The gesture. + */ + private fun gesture(kind: MeshOperatorKind): PlacementGesture { + val transform = + assertNotNull( + buildModalTransformCapture( + sources = listOf(ModalCaptureSource(drawableId, positions.copyOf(), indices, setOf(0, 1, 2, 3))), + pivotMode = TransformPivotMode.MedianPoint, + individualOriginScope = IndividualOriginScope.WholeMesh, + operatorKind = kind, + activeAnchor = null, + cursorAnchor = null, + ), + ) + val mover = PlacementMover(tileId, original, trim, null, null, null, emptyList(), transform.anchor.first, transform.anchor.second, crop = null) + return PlacementGesture( + transform = transform, + movers = listOf(mover), + bystanders = emptyList(), + occupancy = null, + tileByDrawable = mapOf(drawableId to tileId), + frozenPositionsByDrawable = mapOf(drawableId to positions.copyOf()), + pageWidth = pageSide, + pageHeight = pageSide, + extrude = 2, + ) + } + + private fun evaluate(gesture: PlacementGesture, parameters: PlacementGestureParameters): PlacementDragResult = + evaluatePlacementDrag(gesture.transform.operatorKind, parameters, gesture.movers, gesture.bystanders, gesture.occupancy, gesture.pageWidth, gesture.pageHeight, gesture.extrude) + + /** + * Runs a gesture to its confirm: evaluates, commits the placements under the operator's label, and + * registers the record. + * + * @param EditorSession session The session. + * @param PlacementGesture gesture The frozen gesture. + * @param PlacementGestureParameters parameters The drag's parameters at confirm. + * @param Function onLanded Receives each adjustment's evaluation. + * @return PlacementDragResult The drag's evaluation. + */ + private fun confirm(session: EditorSession, gesture: PlacementGesture, parameters: PlacementGestureParameters, onLanded: (PlacementDragResult) -> Unit): PlacementDragResult { + val dragged = evaluate(gesture, parameters) + session.setAtlasPlacements(changedPlacements(gesture.movers, dragged), gesture.transform.operatorKind) + assertNotNull(registerPlacementAdjustment(session, "uv-1", gesture, dragged, onLanded), "the gesture registers") + return dragged + } + + private fun placementOf(session: EditorSession): AtlasPlacement = assertNotNull(session.model.value.atlas.tileById.getValue(tileId).placement) + + private fun assertClose(expected: Float, actual: Float, message: String) { + assertTrue(abs(expected - actual) < 1e-3f, "$message: expected $expected, was $actual") + } + + @Test + fun aGrabRegistersItsMoveAndAnAdjustmentRewritesTheStepFromTheBase() { + val session = EditorSession(model()) + val gesture = gesture(MeshOperatorKind.Grab) + val landed = ArrayList() + + confirm(session, gesture, PlacementGestureParameters(7f, -5f, 1f, 1f, 0f)) { result -> landed.add(result) } + + val record = assertNotNull(session.adjustableOperation.value) + assertEquals("uv-1", record.areaId) + assertEquals("change.document.atlasPlacement", record.change.labelKey) + assertEquals(7, record.parameters.intValue(PlacementParameterKeys.DELTA_X, -1)) + assertEquals(5, record.parameters.intValue(PlacementParameterKeys.DELTA_Y, -1), "display y up 5 is page y down 5") + assertEquals(original.copy(positionX = 11f, positionY = 9f), placementOf(session)) + val steps = session.historyView.value.steps.size + + session.adjustLastOperation( + record.parameters.withParameter( + PlacementParameterKeys.DELTA_X, + OperatorParameter.IntParameter(PlacementParameterKeys.DELTA_X, PlacementParameterKeys.DELTA_X, 20, -pageSide, pageSide), + ), + ) + + assertEquals(original.copy(positionX = 24f, positionY = 9f), placementOf(session), "the rerun moved the tile from the BASE by the new delta") + assertEquals(steps, session.historyView.value.steps.size, "the step was rewritten, not added") + assertEquals(20, landed.single().status.deltaX, "the landing callback saw the adjustment") + session.undo() + assertEquals(original, placementOf(session), "one undo returns to the base") + assertNull(session.adjustableOperation.value, "undo ends the record") + } + + @Test + fun aRotateAdjustsAboutTheFrozenPivotAndAScaleItsFactors() { + val session = EditorSession(model()) + val rotate = gesture(MeshOperatorKind.Rotate) + confirm(session, rotate, PlacementGestureParameters(0f, 0f, 1f, 1f, 0.5f)) {} + val rotateRecord = assertNotNull(session.adjustableOperation.value) + assertEquals("change.document.atlasPlacement.rotate", rotateRecord.change.labelKey) + + session.adjustLastOperation( + rotateRecord.parameters.withParameter( + PlacementParameterKeys.ANGLE, + OperatorParameter.FloatParameter(PlacementParameterKeys.ANGLE, PlacementParameterKeys.ANGLE, 90f, -360f, 360f), + ), + ) + + val turned = placementOf(session) + assertClose(90f, turned.rotationDegrees, "the page-space angle is the row's") + // The pivot frozen at latch - the island's center, page (9, 9) - is a fixed point of the turn. + val pivotInTile = assertNotNull(layerPixelOf(original, 9f, 9f)) + val pivotAfter = atlasPixelOf(turned, pivotInTile[0], pivotInTile[1]) + assertClose(9f, pivotAfter[0], "pivot x fixed") + assertClose(9f, pivotAfter[1], "pivot y fixed") + + session.undo() + val scale = gesture(MeshOperatorKind.Scale) + confirm(session, scale, PlacementGestureParameters(0f, 0f, 1.5f, 1.5f, 0f)) {} + val scaleRecord = assertNotNull(session.adjustableOperation.value) + assertEquals("change.document.atlasPlacement.scale", scaleRecord.change.labelKey) + + session.adjustLastOperation( + scaleRecord.parameters.withParameter( + PlacementParameterKeys.SCALE_X, + OperatorParameter.FloatParameter(PlacementParameterKeys.SCALE_X, PlacementParameterKeys.SCALE_X, 2f, 0.01f, 100f), + ), + ) + + val scaled = placementOf(session) + assertClose(2f, scaled.scaleX, "one factor edited alone scales that tile axis") + assertClose(1.5f, scaled.scaleY, "the other keeps the drag's factor") + assertClose(0f, scaled.rotationDegrees, "no shear") + } + + @Test + fun anyOtherPushEndsTheRecord() { + val session = EditorSession(model()) + confirm(session, gesture(MeshOperatorKind.Grab), PlacementGestureParameters(3f, 0f, 1f, 1f, 0f)) {} + assertNotNull(session.adjustableOperation.value) + + session.setSelection(Selection(setOf(SelectionTarget.Drawable(drawableId)), SelectionTarget.Drawable(drawableId))) + + assertNull(session.adjustableOperation.value, "a selection push is a push") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvPlacementGestureTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvPlacementGestureTest.kt new file mode 100644 index 0000000..5faa4d8 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvPlacementGestureTest.kt @@ -0,0 +1,313 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.OperatorParameter +import org.umamo.format.art.LayerBounds +import org.umamo.format.atlas.AtlasPackReserve +import org.umamo.render.DecodedImage +import org.umamo.render.PageOccupancy +import org.umamo.render.PixelRect +import org.umamo.render.SampledRegion +import org.umamo.render.TileMeshMask +import org.umamo.render.TileOpaqueMask +import org.umamo.render.placementFootprint +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.applyUvAffine +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.roundToInt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the placement drag's evaluation: Grab snaps to whole page pixels with the display flip + * applied, Rotate and uniform Scale turn about the pivot and land on the placement's own TRS + * components, a non-uniform Scale on a rotated tile scales the tile's own axis, the islands' display + * affine agrees with the placement (the pivot stays put), collisions with bystanders, other movers, + * and the page edge are reported, and the operation settings strip's rows round-trip every operator + * back to the placements the drag wrote. + */ +class UvPlacementGestureTest { + private val pageWidth = 100 + private val pageHeight = 80 + private val trim = LayerBounds(0, 0, 10, 10) + + /** A fully opaque 10x10 tile whose mesh covers exactly its art (plus the mask's one-pixel margin). */ + private val solidMask = TileOpaqueMask.of(opaqueRaster(10, 10), trim, alphaThreshold = 1) + private val solidReserve = AtlasPackReserve(0, 0, 10, 10) + private val solidMesh = quadMesh(0f, 0f, 10f, 10f) + + /** A mesh covering the rectangle [left, right) by [top, bottom) with two triangles. */ + private fun quadMesh(left: Float, top: Float, right: Float, bottom: Float): TileMeshMask = + TileMeshMask.of( + listOf(floatArrayOf(left, top, right, top, right, bottom), floatArrayOf(left, top, right, bottom, left, bottom)), + )!! + + private fun opaqueRaster(width: Int, height: Int): DecodedImage { + val rgba = ByteArray(width * height * 4) + for (pixelIndex in 0 until width * height) { + rgba[pixelIndex * 4 + 3] = 0xFF.toByte() + } + return DecodedImage(rgba, width, height) + } + + private fun mover( + id: String, + placement: AtlasPlacement, + pivotDisplayX: Float, + pivotDisplayY: Float, + reserve: AtlasPackReserve? = solidReserve, + meshMask: TileMeshMask? = solidMesh, + mask: TileOpaqueMask? = solidMask, + ): PlacementMover = PlacementMover(AtlasTileId(id), placement, trim, reserve, meshMask, mask, emptyList(), pivotDisplayX, pivotDisplayY, crop = null) + + /** A page painted opaque inside [painted] only. */ + private fun pageWith(painted: PixelRect, excluded: List): PageOccupancy { + val rgba = ByteArray(pageWidth * pageHeight * 4) + for (y in painted.top until painted.bottom) { + for (x in painted.left until painted.right) { + rgba[(y * pageWidth + x) * 4 + 3] = 0xFF.toByte() + } + } + return PageOccupancy.of(DecodedImage(rgba, pageWidth, pageHeight), excluded) + } + + private fun bystander(id: String, placement: AtlasPlacement, meshMask: TileMeshMask?): PlacementBystander = + PlacementBystander( + AtlasTileId(id), + placement, + meshMask?.let { coverage -> SampledRegion(placement, coverage) }, + placementFootprint(placement, trim, reserve = null).expanded(2f), + ) + + private fun placement(x: Float, y: Float, rotationDegrees: Float = 0f, scale: Float = 1f): AtlasPlacement = + AtlasPlacement(0, x, y, scale, scale, rotationDegrees) + + private fun parameters( + deltaX: Float = 0f, + deltaY: Float = 0f, + factorX: Float = 1f, + factorY: Float = 1f, + rotationRadians: Float = 0f, + ): PlacementGestureParameters = PlacementGestureParameters(deltaX, deltaY, factorX, factorY, rotationRadians) + + private fun evaluate( + kind: MeshOperatorKind, + parameters: PlacementGestureParameters, + movers: List, + bystanders: List = emptyList(), + occupancy: PageOccupancy? = null, + ): PlacementDragResult = evaluatePlacementDrag(kind, parameters, movers, bystanders, occupancy, pageWidth, pageHeight, extrude = 2) + + private fun assertPlacementClose(expected: AtlasPlacement, actual: AtlasPlacement, message: String) { + assertEquals(expected.pageIndex, actual.pageIndex, "$message: page") + assertClose(expected.positionX, actual.positionX, "$message: position x") + assertClose(expected.positionY, actual.positionY, "$message: position y") + assertClose(expected.scaleX, actual.scaleX, "$message: scale x") + assertClose(expected.scaleY, actual.scaleY, "$message: scale y") + assertClose(expected.rotationDegrees, actual.rotationDegrees, "$message: rotation") + } + + private fun assertClose(expected: Float, actual: Float, message: String) { + assertTrue(abs(expected - actual) < 1e-3f, "$message: expected $expected, was $actual") + } + + @Test + fun grabSnapsToWholePagePixelsThroughTheFlip() { + val mover = mover("a", placement(20f, 30f), 25f, 45f) + val result = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 2.6f, deltaY = -3.4f), listOf(mover)) + + val moved = result.placementByTile.getValue(mover.tileId) + assertClose(23f, moved.positionX, "x snapped to 3") + assertClose(33f, moved.positionY, "display y up 3.4 is page y down 3") + assertEquals(3, result.status.deltaX) + assertEquals(3, result.status.deltaY) + // The islands follow the same move in display space. + val displayed = applyUvAffine(floatArrayOf(25f, 45f), result.displayAffineByTile.getValue(mover.tileId)) + assertClose(28f, displayed[0], "island x") + assertClose(42f, displayed[1], "island y (display y up)") + } + + @Test + fun rotateTurnsAboutThePivotAndTheIslandsAgree() { + val original = placement(20f, 30f, rotationDegrees = 10f) + val mover = mover("a", original, 40f, 40f) + val quarterTurn = (PI / 2).toFloat() + val result = evaluate(MeshOperatorKind.Rotate, parameters(rotationRadians = quarterTurn), listOf(mover)) + + val turned = result.placementByTile.getValue(mover.tileId) + assertClose(1f, turned.scaleX, "scale untouched") + assertClose(1f, turned.scaleY, "scale untouched") + // A display-space turn is the page-space turn mirrored: the placement's angle moves by -90. + assertClose(-80f, turned.rotationDegrees, "the page angle mirrors the display angle") + assertClose(-90f, result.status.angleDegrees, "the readout shows the page-space angle") + // The pivot is a fixed point of the islands' affine. + val pivot = applyUvAffine(floatArrayOf(40f, 40f), result.displayAffineByTile.getValue(mover.tileId)) + assertClose(40f, pivot[0], "pivot x fixed") + assertClose(40f, pivot[1], "pivot y fixed") + } + + @Test + fun uniformScaleMultipliesBothAxesAboutThePivot() { + val mover = mover("a", placement(20f, 30f, rotationDegrees = 45f), 40f, 40f) + val result = evaluate(MeshOperatorKind.Scale, parameters(factorX = 2f, factorY = 2f), listOf(mover)) + + val scaled = result.placementByTile.getValue(mover.tileId) + assertClose(2f, scaled.scaleX, "scale x doubled") + assertClose(2f, scaled.scaleY, "scale y doubled") + assertClose(45f, scaled.rotationDegrees, "rotation untouched") + val pivot = applyUvAffine(floatArrayOf(40f, 40f), result.displayAffineByTile.getValue(mover.tileId)) + assertClose(40f, pivot[0], "pivot x fixed") + assertClose(40f, pivot[1], "pivot y fixed") + } + + @Test + fun aNonUniformScaleOnARotatedTileScalesItsOwnAxes() { + // What an axis lock produces (one factor pinned at 1) and what the strip's two rows can ask for: + // no constraint is needed to say so, the factors themselves do. + val mover = mover("a", placement(20f, 30f, rotationDegrees = 30f), 40f, 40f) + val result = evaluate(MeshOperatorKind.Scale, parameters(factorX = 2f, factorY = 1f), listOf(mover)) + + val scaled = result.placementByTile.getValue(mover.tileId) + assertClose(2f, scaled.scaleX, "the tile's own x axis scaled") + assertClose(1f, scaled.scaleY, "the tile's own y axis untouched") + assertClose(30f, scaled.rotationDegrees, "rotation untouched - no shear was written") + + val both = evaluate(MeshOperatorKind.Scale, parameters(factorX = 2f, factorY = 1.5f), listOf(mover)).placementByTile.getValue(mover.tileId) + assertClose(2f, both.scaleX, "two different factors scale both tile axes") + assertClose(1.5f, both.scaleY, "two different factors scale both tile axes") + assertClose(30f, both.rotationDegrees, "still no shear") + } + + @Test + fun theStripRowsRoundTripEachOperator() { + val cases = + listOf( + Triple(MeshOperatorKind.Grab, parameters(deltaX = 7.3f, deltaY = -5.2f), "grab"), + Triple(MeshOperatorKind.Rotate, parameters(rotationRadians = 0.4f), "rotate"), + Triple(MeshOperatorKind.Scale, parameters(factorX = 1.5f, factorY = 1.5f), "uniform scale"), + Triple(MeshOperatorKind.Scale, parameters(factorX = 1.5f, factorY = 1f), "tile-axis scale"), + ) + for ((kind, dragParameters, name) in cases) { + val movers = listOf(mover("a", placement(20f, 30f, rotationDegrees = 30f), 40f, 40f), mover("b", placement(50f, 20f), 55f, 55f)) + val dragged = evaluate(kind, dragParameters, movers) + + val rows = placementParameters(dragged.status, pageWidth, pageHeight) + val replayed = evaluate(kind, placementGestureParametersOf(kind, rows), movers) + + assertTrue(rows.isNotEmpty(), "$name has rows") + for (mover in movers) { + assertPlacementClose(dragged.placementByTile.getValue(mover.tileId), replayed.placementByTile.getValue(mover.tileId), "$name '${mover.tileId.raw}'") + } + } + // The rows show the HUD's numbers: the snapped move, the page-space angle, the factors. + val grabRows = placementParameters(evaluate(MeshOperatorKind.Grab, parameters(deltaX = 7.3f, deltaY = -5.2f), listOf(mover("a", placement(20f, 30f), 25f, 45f))).status, pageWidth, pageHeight) + assertEquals(7, (grabRows[0] as OperatorParameter.IntParameter).value) + assertEquals(5, (grabRows[1] as OperatorParameter.IntParameter).value, "display y up 5.2 is page y down 5") + val rotateRows = placementParameters(evaluate(MeshOperatorKind.Rotate, parameters(rotationRadians = (PI / 2).toFloat()), listOf(mover("a", placement(20f, 30f), 25f, 45f))).status, pageWidth, pageHeight) + assertEquals(-90, (rotateRows.single() as OperatorParameter.FloatParameter).value.roundToInt(), "the angle row is the page-space angle") + } + + @Test + fun aMeshOverAnotherTilesPaintCollidesAndPaintNobodySamplesDoesNot() { + // Mover A: opaque 10x10 at page (20, 30), mesh over exactly its art. Bystander C paints page + // pixels x 33..43, y 30..40 and its mesh covers only the right half of that paint (x 38..43). + val moverA = mover("a", placement(20f, 30f), 25f, 45f) + val painted = PixelRect(33, 30, 43, 40) + val bystanderC = bystander("c", placement(33f, 30f), quadMesh(5f, 0f, 10f, 10f)) + val occupancy = pageWith(painted, excluded = listOf(PixelRect(18, 28, 32, 42))) + + // A moves right by 2: its mesh (with its margin) ends at x 32, one pixel short of C's paint, and + // C's mesh starts at x 37, past A's paint and its band - nothing samples anything. + val clear = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 2f), listOf(moverA), listOf(bystanderC), occupancy = occupancy) + assertTrue(clear.overlappingTileIds.isEmpty(), "adjacent paint with no mesh over it is not a collision, was ${clear.overlappingTileIds}") + + // A moves right by 5: A's mesh (x 24..36) now reads C's paint at x 33..35. + val samplesPaint = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 5f), listOf(moverA), listOf(bystanderC), occupancy = occupancy) + assertEquals(setOf(AtlasTileId("a"), AtlasTileId("c")), samplesPaint.overlappingTileIds) + assertEquals(setOf(AtlasTileId("a")), samplesPaint.samplingTileIds, "A is the sampler") + assertEquals(setOf(AtlasTileId("c")), samplesPaint.paintingTileIds, "C is the painter") + assertEquals(1, samplesPaint.status.overlapCount) + + // A moves right by 16: A's paint (x 36..46) lands under C's mesh (x 37..44) while A's own mesh + // sits over C's paint too - both directions report. + val underMesh = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 16f), listOf(moverA), listOf(bystanderC), occupancy = occupancy) + assertTrue(AtlasTileId("a") in underMesh.paintingTileIds, "A's paint is under C's mesh") + assertTrue(AtlasTileId("c") in underMesh.samplingTileIds, "C samples A") + + // A moves right by 24: A's paint (x 44..54) sits past C's paint, and only C's mesh (to x 44) + // reaches it - C samples A, A samples nothing. + val reached = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 24f), listOf(moverA), listOf(bystanderC), occupancy = occupancy) + assertEquals(setOf(AtlasTileId("c")), reached.samplingTileIds, "only C's mesh reaches A's paint") + assertTrue(reached.overlappingTileIds.containsAll(setOf(AtlasTileId("a"), AtlasTileId("c")))) + + // Paint nobody samples: a mover with no mesh over C's paint, when C's mesh is elsewhere. + val meshless = mover("m", placement(20f, 30f), 25f, 45f, meshMask = null) + val ignored = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 5f), listOf(meshless), listOf(bystanderC), occupancy = occupancy) + assertTrue(ignored.overlappingTileIds.isEmpty(), "overlapping paint with no mesh reading it is allowed, was ${ignored.overlappingTileIds}") + } + + @Test + fun overlappingBoxesWithDisjointTrianglesAndPixelsDoNotWarn() { + // The screenshot: mover A's mesh overhangs its art on the right by ten pixels but only along a + // thin diagonal; bystander C's paint sits inside A's mesh BOX yet off that diagonal, and C's + // own mesh is a sliver that never reaches A's pixels. + val overhang = TileMeshMask.of(listOf(floatArrayOf(0f, 0f, 10f, 10f, 20f, 2f), floatArrayOf(0f, 0f, 20f, 2f, 0f, 2f)))!! + val moverA = mover("a", placement(20f, 30f), 25f, 45f, meshMask = overhang) + // C paints a dot at page (36, 38): inside A's mesh box (x 20..40, y 30..40) after the move, but + // far from the diagonal sliver. + // No vacated spot to exclude: the synthetic page holds nothing but the dot. + val occupancy = pageWith(PixelRect(36, 38, 37, 39), excluded = emptyList()) + val bystanderC = bystander("c", placement(30f, 34f), quadMesh(4f, 2f, 8f, 6f)) + val result = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 0f), listOf(moverA), listOf(bystanderC), occupancy = occupancy) + assertTrue(result.overlappingTileIds.isEmpty(), "boxes overlap, triangles and pixels do not: no warning, was ${result.overlappingTileIds}") + // Move the dot under the sliver's start and it warns. + val touching = pageWith(PixelRect(24, 31, 25, 32), excluded = emptyList()) + val hit = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 0f), listOf(moverA), listOf(bystanderC), occupancy = touching) + assertEquals(setOf(AtlasTileId("a")), hit.samplingTileIds, "the sliver over the dot samples it") + } + + @Test + fun theEdgeAndOtherMoversAreReported() { + val moverA = mover("a", placement(20f, 30f), 25f, 45f) + val moverB = mover("b", placement(60f, 30f), 65f, 45f) + + // Both slide left by 25: A's opaque bounds cross the page's left edge. + val spilled = evaluate(MeshOperatorKind.Grab, parameters(deltaX = -25f), listOf(moverA, moverB)) + assertEquals(setOf(AtlasTileId("a")), spilled.offPageTileIds) + assertTrue(spilled.status.offPage) + + // A mesh reaching past the page over transparent pixels is not a spill: mover with a wide mesh. + val wideMesh = mover("w", placement(2f, 30f), 7f, 45f, meshMask = quadMesh(-5f, 0f, 10f, 10f)) + val reaching = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 0f), listOf(wideMesh)) + assertTrue(reaching.offPageTileIds.isEmpty(), "the reserve alone does not spill") + + // Movers collide with each other: B stacked onto A samples A's paint and A samples B's. + val stacked = evaluate(MeshOperatorKind.Grab, parameters(deltaX = 0f), listOf(moverA, mover("b", placement(28f, 30f), 33f, 45f))) + assertEquals(setOf(AtlasTileId("a"), AtlasTileId("b")), stacked.overlappingTileIds) + assertEquals(setOf(AtlasTileId("a"), AtlasTileId("b")), stacked.samplingTileIds) + } + + @Test + fun theTileToDisplayMappingFlipsOnceAfterThePlacement() { + // A tile at page (20, 30): its origin shows at display (20, h - 30) and its rows run DOWN the + // page, so the next row sits one texel lower in display space - not mirrored below the page. + val mapping = tileToDisplayAffine(placement(20f, 30f), pageHeight) + val origin = applyUvAffine(floatArrayOf(0f, 0f), mapping) + val nextRow = applyUvAffine(floatArrayOf(0f, 1f), mapping) + assertClose(20f, origin[0], "origin x") + assertClose((pageHeight - 30).toFloat(), origin[1], "origin y") + assertClose((pageHeight - 31).toFloat(), nextRow[1], "the next row is one texel lower") + } + + @Test + fun theFlipIsItsOwnInverse() { + val affine = floatArrayOf(0.5f, -0.25f, 7f, 0.25f, 0.5f, -3f) + val roundTrip = flipAffineFrame(flipAffineFrame(affine, pageHeight), pageHeight) + for (componentIndex in affine.indices) { + assertClose(affine[componentIndex], roundTrip[componentIndex], "component $componentIndex") + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvSnapTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvSnapTest.kt new file mode 100644 index 0000000..eb36ec6 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/UvSnapTest.kt @@ -0,0 +1,177 @@ +package org.umamo.ui.viewport + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.GridConfig +import org.umamo.edit.MeshElement +import org.umamo.edit.MeshSelectionOps +import org.umamo.edit.UvCursor +import org.umamo.edit.UvSnapKind +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * Verifies the UV snap executor ([handleUvSnapRequest]) end to end at the model level: each of the + * seven operations transforms the selected texture coordinates (or moves the UV cursor) as the UV snap + * pie promises, over the texel display space the UV editor works in. A 100x100 page with a + * 10-subdivision grid is used throughout, so the display coordinate of a uv is u * 100 across and + * (1 - v) * 100 down (the v-flip), the pixel step is one texel, and the grid step is ten. + * + * The single triangle's three vertices sit at display (12.3, 45.7), (34.6, 45.7), (12.3, 78.2) - chosen + * so no round lands on a tie and every expected target is exact to four decimals. + */ +class UvSnapTest { + private val pageWidth = 100 + private val pageHeight = 100 + + /** The triangle's stored uvs, the display positions above run back through the display mapping. */ + private val startUvs = floatArrayOf(0.123f, 0.543f, 0.346f, 0.543f, 0.123f, 0.218f) + + private fun snapModel(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = DrawableId("a"), + name = "a", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), startUvs.copyOf(), intArrayOf(0, 1, 2)), + geometryGrid = null, + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** An Edit-mode session with the whole triangle selected and a 100-unit / 10-subdivision grid. */ + private fun snapSession(select: Boolean = true): EditorSession { + val session = EditorSession(snapModel()) + session.setMode(EditorMode.Edit) + session.setGridConfig(GridConfig(scale = 100f, subdivisions = 10)) + if (select) { + var selection = session.meshSelection.value + for (vertexIndex in 0..2) { + selection = MeshSelectionOps.add(selection, DrawableId("a"), MeshElement.Vertex(vertexIndex)) + } + session.setMeshSelection(selection) + } + return session + } + + /** The shown mesh's gizmo geometry, its positions the stored uvs projected into display space. */ + private fun geometriesOf(session: EditorSession): List = + session.model.value.drawables.mapNotNull { drawable -> + val mesh = drawable.mesh ?: return@mapNotNull null + GizmoMeshGeometry(drawable.id, mesh.indices, emptyList(), uvToDisplay(mesh.uvs, pageWidth, pageHeight)) + } + + private fun snap(session: EditorSession, kind: UvSnapKind) { + handleUvSnapRequest(session, geometriesOf(session), atlasPageEditFrame(pageWidth, pageHeight), kind) + } + + private fun currentUvs(session: EditorSession): FloatArray = session.model.value.drawables[0].mesh!!.uvs + + private fun assertUvsEqual(expected: List, actual: FloatArray, message: String) { + assertEquals(expected.size, actual.size, message) + for (componentIndex in expected.indices) { + assertEquals(expected[componentIndex], actual[componentIndex], 1e-4f, "$message (component $componentIndex)") + } + } + + /** Selection to Pixels rounds each covered vertex to its nearest integer texel (a pixel corner). */ + @Test + fun selectionToPixelsRoundsToTexelCorners() { + val session = snapSession() + snap(session, UvSnapKind.SelectionToPixels) + // (12.3,45.7)->(12,46) (34.6,45.7)->(35,46) (12.3,78.2)->(12,78), back through the display mapping. + assertUvsEqual(listOf(0.12f, 0.54f, 0.35f, 0.54f, 0.12f, 0.22f), currentUvs(session), "each vertex snaps to a pixel corner") + assertEquals("change.uv.move", session.historyView.value.steps.last().labelKey, "one TransformUvs undo step") + } + + /** Selection to Grid rounds each covered vertex to the page / subdivisions grid (step 10 here). */ + @Test + fun selectionToGridRoundsToTheDrawnGrid() { + val session = snapSession() + snap(session, UvSnapKind.SelectionToGrid) + // (12.3,45.7)->(10,50) (34.6,45.7)->(30,50) (12.3,78.2)->(10,80). + assertUvsEqual(listOf(0.10f, 0.50f, 0.30f, 0.50f, 0.10f, 0.20f), currentUvs(session), "each vertex snaps to a grid line") + } + + /** Selection to Cursor piles every covered vertex onto the UV cursor (Blender parity). */ + @Test + fun selectionToCursorCollapsesOntoTheCursor() { + val session = snapSession() + session.setUvCursor(0.5f, 0.5f) + snap(session, UvSnapKind.SelectionToCursor) + assertUvsEqual(listOf(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f), currentUvs(session), "every vertex lands on the cursor") + } + + /** Selection to Cursor (Offset) rigidly translates so the covered median lands on the cursor. */ + @Test + fun selectionToCursorOffsetTranslatesKeepingShape() { + val session = snapSession() + session.setUvCursor(0.5f, 0.5f) + snap(session, UvSnapKind.SelectionToCursorOffset) + // Median display (19.7333, 56.5333) -> cursor (50, 50): a shared delta of (30.2667, -6.5333). + assertUvsEqual( + listOf(0.42567f, 0.60833f, 0.64867f, 0.60833f, 0.42567f, 0.28333f), + currentUvs(session), + "the selection translates rigidly, its median on the cursor", + ) + } + + /** Cursor to Pixels snaps the UV cursor to its nearest pixel corner. */ + @Test + fun cursorToPixelsRoundsTheCursor() { + val session = snapSession(select = false) + session.setUvCursor(0.123f, 0.543f) + snap(session, UvSnapKind.CursorToPixels) + val cursor = session.uvCursor.value!! + assertEquals(0.12f, cursor.u, 1e-4f, "cursor u snaps to a texel corner") + assertEquals(0.54f, cursor.v, 1e-4f, "cursor v snaps to a texel corner") + } + + /** Cursor to Grid snaps the UV cursor to the page / subdivisions grid. */ + @Test + fun cursorToGridSnapsTheCursor() { + val session = snapSession(select = false) + session.setUvCursor(0.123f, 0.543f) + snap(session, UvSnapKind.CursorToGrid) + assertEquals(UvCursor(0.10f, 0.50f), session.uvCursor.value, "cursor snaps to a grid line") + } + + /** Cursor to Selected moves the UV cursor to the covered vertices' median. */ + @Test + fun cursorToSelectedMovesToTheMedian() { + val session = snapSession() + snap(session, UvSnapKind.CursorToSelected) + val cursor = session.uvCursor.value!! + // Median display (19.7333, 56.5333) -> uv (0.19733, 0.43467). + assertEquals(0.19733f, cursor.u, 1e-4f, "cursor u lands on the covered median") + assertEquals(0.43467f, cursor.v, 1e-4f, "cursor v lands on the covered median") + } + + /** With nothing selected the selection snaps commit nothing and Cursor to Selected no-ops. */ + @Test + fun emptySelectionIsANoOp() { + val session = snapSession(select = false) + val modelBefore = session.model.value + snap(session, UvSnapKind.SelectionToPixels) + snap(session, UvSnapKind.SelectionToGrid) + assertSame(modelBefore, session.model.value, "no covered vertices commit nothing") + snap(session, UvSnapKind.CursorToSelected) + assertNull(session.uvCursor.value, "no covered median leaves the cursor unplaced") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ViewportSettingsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ViewportSettingsTest.kt new file mode 100644 index 0000000..85b6af3 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/viewport/ViewportSettingsTest.kt @@ -0,0 +1,44 @@ +package org.umamo.ui.viewport + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The selection-highlight parser: both hex widths must land on the same RGB because a hand-typed or + * older user setting may hold #RRGGBB while the preferences HexColorField commits canonical + * #AARRGGBB - a 6-digit-only parser would silently ignore every edit made in the window. + */ +class ViewportSettingsTest { + private val defaultComponents = parseSelectionHighlightColor(ViewportColorSettings.SELECTION_HIGHLIGHT_DEFAULT) + + @Test + fun sixDigitHexParses() { + val (red, green, blue) = parseSelectionHighlightColor("#00FF00") + assertEquals(0f, red) + assertEquals(1f, green) + assertEquals(0f, blue) + } + + @Test + fun eightDigitHexParsesWithAlphaIgnored() { + assertEquals( + parseSelectionHighlightColor("#00FF00"), + parseSelectionHighlightColor("#8000FF00"), + "the alpha byte is masked off", + ) + assertEquals(defaultComponents, parseSelectionHighlightColor("#FF338CFF"), "the canonical form of the default") + } + + @Test + fun leadingHashIsOptional() { + assertEquals(parseSelectionHighlightColor("#00FF00"), parseSelectionHighlightColor("00FF00")) + } + + @Test + fun malformedOrAbsentValuesFallBackToTheDefault() { + assertEquals(defaultComponents, parseSelectionHighlightColor(null)) + assertEquals(defaultComponents, parseSelectionHighlightColor("")) + assertEquals(defaultComponents, parseSelectionHighlightColor("#12345"), "wrong digit count") + assertEquals(defaultComponents, parseSelectionHighlightColor("#GGGGGG"), "non-hex digits") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/AreaScopeTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/AreaScopeTest.kt new file mode 100644 index 0000000..3105ea7 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/AreaScopeTest.kt @@ -0,0 +1,51 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotSame +import kotlin.test.assertSame + +/** + * Pins the AreaScope.spaceState contract: one instance per key per scope (the header slot and the + * body must observe the same object), created lazily, and independent across scopes (two areas + * hosting the same space never share state). + */ +class AreaScopeTest { + /** Repeated requests under one key return the same instance; the factory runs once. */ + @Test + fun sameKeyReturnsSameInstance() { + val scope = AreaScope(areaId = "area-1") + var factoryRuns = 0 + val firstRequest = + scope.spaceState("outliner.view") { + factoryRuns++ + Any() + } + val secondRequest = + scope.spaceState("outliner.view") { + factoryRuns++ + Any() + } + assertSame(firstRequest, secondRequest) + assertEquals(1, factoryRuns) + } + + /** Different keys park different objects. */ + @Test + fun differentKeysAreIndependent() { + val scope = AreaScope(areaId = "area-1") + val outlinerState = scope.spaceState("outliner.view") { Any() } + val otherState = scope.spaceState("uv.view") { Any() } + assertNotSame(outlinerState, otherState) + } + + /** Two scopes (two areas) never share state under the same key. */ + @Test + fun scopesAreIndependent() { + val firstScope = AreaScope(areaId = "area-1") + val secondScope = AreaScope(areaId = "area-2") + val firstState = firstScope.spaceState("outliner.view") { Any() } + val secondState = secondScope.spaceState("outliner.view") { Any() } + assertNotSame(firstState, secondState) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/AreaViewStatesTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/AreaViewStatesTest.kt new file mode 100644 index 0000000..b537068 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/AreaViewStatesTest.kt @@ -0,0 +1,194 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import org.umamo.render.ViewportCamera +import org.umamo.ui.viewport.AreaCameraKey +import org.umamo.ui.viewport.CameraSurface +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotSame +import kotlin.test.assertSame + +/** + * Pins the per-document holder of area view state (docs/format/UMA.md §7.3, §7.5): scopes live as long as + * the holder rather than a leaf, a saved block seeds only the area whose id it carries, and a gather writes the + * saver's layout and takes every other id out of the file. + */ +class AreaViewStatesTest { + /** A stand-in for a space's view state holding one list. */ + private class ListState : PersistentSpaceState { + var values: List = emptyList() + + /** + * The state's member of its area block. + * + * @return JsonObject The member. + */ + override fun toJson(): JsonObject = buildJsonObject { put("values", stringArrayOrNull(values)) } + + /** + * Takes the saved member. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + values = stringListOf(tree, "values").orEmpty() + } + } + + /** + * A saved `areas` member holding one list per area id. + * + * @param Map valuesByAreaId Each area's list. + * @return JsonObject The member. + */ + private fun savedAreas(valuesByAreaId: Map>): JsonObject = + buildJsonObject { + for ((areaId, values) in valuesByAreaId) { + put(areaId, buildJsonObject { put("outliner", buildJsonObject { put("values", JsonArray(values.map(::JsonPrimitive))) }) }) + } + } + + /** The scope outlives the leaf that asked for it: asking again, as a recomposed leaf does, finds the same state. */ + @Test + fun aScopeLivesAsLongAsTheHolder() { + val holder = AreaViewStates() + val firstMount = holder.scopeFor("area-1").spaceState("outliner") { ListState() } + firstMount.values = listOf("part:1") + + val afterATabSwitch = holder.scopeFor("area-1").spaceState("outliner") { ListState() } + + assertSame(firstMount, afterATabSwitch) + assertEquals(listOf("part:1"), afterATabSwitch.values) + assertNotSame(firstMount, AreaViewStates().scopeFor("area-1").spaceState("outliner") { ListState() }, "another document starts over") + } + + /** A saved block seeds the area whose id it carries, and only that one. */ + @Test + fun aSavedBlockSeedsOnlyItsOwnArea() { + val holder = AreaViewStates(savedAreas(mapOf("area-1" to listOf("part:1")))) + + assertEquals(listOf("part:1"), holder.scopeFor("area-1").spaceState("outliner") { ListState() }.values) + assertEquals(emptyList(), holder.scopeFor("area-2").spaceState("outliner") { ListState() }.values, "an id the file does not have starts at its defaults") + } + + /** A state that is not persistent is parked like any other and never written. */ + @Test + fun aPlainStateIsNeverWritten() { + val holder = AreaViewStates() + holder.layoutAreaIds = listOf("area-1") + holder.scopeFor("area-1").spaceState("logs") { Any() } + + assertEquals(JsonObject(emptyMap()), holder.gather()["area-1"]) + } + + /** + * A gather writes the shown areas of the layout in layout order, leaves an area it never showed unnamed so + * the file's block survives, and nulls every id the layout lacks. + */ + @Test + fun aGatherWritesTheLayoutAndDropsTheRest() { + val holder = AreaViewStates(savedAreas(mapOf("area-stale" to listOf("part:9"), "area-unshown" to listOf("part:7")))) + holder.layoutAreaIds = listOf("area-2", "area-unshown", "area-1") + holder.scopeFor("area-1").spaceState("outliner") { ListState() }.values = listOf("part:1") + holder.scopeFor("area-2").spaceState("outliner") { ListState() }.values = listOf("part:2") + holder.scopeFor("area-closed").spaceState("outliner") { ListState() }.values = listOf("part:3") + + val gathered = holder.gather() + + assertEquals(listOf("area-stale", "area-2", "area-1"), gathered.keys.toList(), "the removal first, then the layout's order") + assertEquals(JsonNull, gathered["area-stale"], "an id the layout lacks leaves the file") + assertEquals(null, gathered["area-unshown"], "an area never shown keeps the block the file had") + assertEquals(null, gathered["area-closed"], "an area closed in the session is not written") + assertEquals(savedAreas(mapOf("area-1" to listOf("part:1")))["area-1"], gathered["area-1"]!!.jsonObject) + } + + /** A state back at its default names its member as a null, which is what takes the deviation out of the file. */ + @Test + fun aStateAtItsDefaultWritesANull() { + val holder = AreaViewStates(savedAreas(mapOf("area-1" to listOf("part:1")))) + holder.layoutAreaIds = listOf("area-1") + holder.scopeFor("area-1").spaceState("outliner") { ListState() }.values = emptyList() + + assertEquals(JsonNull, holder.gather()["area-1"]!!.jsonObject["outliner"]!!.jsonObject["values"]) + } + + /** + * A camera view as the entry writes it. + * + * @param Float centerX The view's center x. + * @param Float centerY The view's center y. + * @param Float zoom The view's zoom. + * @return JsonArray The `[centerX, centerY, zoom]` triple. + */ + private fun viewJson(centerX: Float, centerY: Float, zoom: Float): JsonArray = JsonArray(listOf(JsonPrimitive(centerX), JsonPrimitive(centerY), JsonPrimitive(zoom))) + + /** + * Each area's cameras go out to seed the render service and come back from it at a save, leading the block. They + * are kept apart by surface: a view of the puppet's world means nothing over a texture's pixels, so an area saved + * as a UV editor and reopened as a 2D viewport must not take the page's pan and zoom. + */ + @Test + fun camerasAreRestoredAndGatheredByAreaAndSurface() { + val saved = + buildJsonObject { + put( + "area-both", + buildJsonObject { + put( + "cameras", + buildJsonObject { + put("viewport", viewJson(10f, -20f, 1.5f)) + put("uv", viewJson(512f, 512f, 0.25f)) + }, + ) + }, + ) + put("area-flat", buildJsonObject { put("cameras", buildJsonObject { put("viewport", viewJson(0f, 0f, 0f)) }) }) + put("area-junk", buildJsonObject { put("cameras", JsonPrimitive("wide")) }) + } + val holder = AreaViewStates(saved) + assertEquals( + mapOf( + AreaCameraKey("area-both", CameraSurface.Viewport) to ViewportCamera(10f, -20f, 1.5f), + AreaCameraKey("area-both", CameraSurface.Uv) to ViewportCamera(512f, 512f, 0.25f), + ), + holder.restoredCameras(), + "a zoom of zero and a member of the wrong shape are skipped", + ) + + holder.layoutAreaIds = listOf("area-view", "area-both", "area-panel") + holder.scopeFor("area-both").spaceState("outliner") { ListState() }.values = listOf("part:1") + holder.scopeFor("area-panel").spaceState("outliner") { ListState() } + val cameras = + mapOf( + AreaCameraKey("area-view", CameraSurface.Viewport) to ViewportCamera(1f, 2f, 3f), + AreaCameraKey("area-both", CameraSurface.Uv) to ViewportCamera(4f, 5f, 6f), + AreaCameraKey("area-closed", CameraSurface.Viewport) to ViewportCamera(7f, 8f, 9f), + ) + + val gathered = holder.gather(cameras) + + assertEquals(buildJsonObject { put("viewport", viewJson(1f, 2f, 3f)) }, gathered["area-view"]!!.jsonObject["cameras"]) + assertEquals(listOf("cameras", "outliner"), gathered["area-both"]!!.jsonObject.keys.toList(), "the cameras lead the block") + assertEquals(setOf("uv"), gathered["area-both"]!!.jsonObject["cameras"]!!.jsonObject.keys, "only a surface the engine holds is named, so the saved viewport view survives the merge") + assertEquals(listOf("outliner"), gathered["area-panel"]!!.jsonObject.keys.toList(), "an area with no camera names none") + assertEquals(null, gathered["area-closed"], "a camera for an area the layout lacks is not written") + } + + /** An area block's members come out in the spec's order whatever order the spaces were shown in. */ + @Test + fun aBlockOrdersItsMembersByTheSpec() { + val scope = AreaScope("area-1") + scope.spaceState("uv") { ListState() } + scope.spaceState("outliner") { ListState() } + scope.spaceState("keyformSheet") { ListState() } + + assertEquals(listOf("outliner", "keyformSheet", "uv"), scope.gather().keys.toList()) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/HoveredSurfaceTrackerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/HoveredSurfaceTrackerTest.kt new file mode 100644 index 0000000..a9c6520 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/HoveredSurfaceTrackerTest.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pins the tracker's observable kind to its last-touched surface. The status bar reads the kind and the + * command handlers read the surface, so the two disagreeing would suggest shortcuts for one space while + * a press acts in another. + */ +class HoveredSurfaceTrackerTest { + /** Nothing is observed before the pointer touches a surface. */ + @Test + fun nothingIsObservedBeforeAnySurfaceIsTouched() { + assertNull(HoveredSurfaceTracker().observedKind) + } + + /** The observed kind follows every stamp, including a move between two areas of different kinds. */ + @Test + fun theObservedKindFollowsTheLastTouchedSurface() { + val tracker = HoveredSurfaceTracker() + + tracker.lastTouched = HoveredSurface("viewport-1", SpaceKind.Viewport2D) + assertEquals(SpaceKind.Viewport2D, tracker.observedKind) + + tracker.lastTouched = HoveredSurface("sheet-1", SpaceKind.KeyformSheet) + assertEquals(SpaceKind.KeyformSheet, tracker.observedKind) + } + + /** An area that is closed or joined away takes its kind with it. */ + @Test + fun releasingTheTouchedAreaClearsTheObservedKind() { + val tracker = HoveredSurfaceTracker() + tracker.lastTouched = HoveredSurface("uv-1", SpaceKind.UvEditor) + + tracker.releaseArea("uv-1") + + assertNull(tracker.lastTouched) + assertNull(tracker.observedKind) + } + + /** A dying area that does not hold the stamp leaves the survivor's kind alone. */ + @Test + fun releasingAnotherAreaLeavesTheObservedKindAlone() { + val tracker = HoveredSurfaceTracker() + tracker.lastTouched = HoveredSurface("uv-1", SpaceKind.UvEditor) + + tracker.releaseArea("outliner-1") + + assertEquals(SpaceKind.UvEditor, tracker.observedKind) + } + + /** + * Switching the touched area to another space re-stamps it at once. A header-dropdown switch sends + * no pointer event over the leaf, so waiting for one would leave dispatch, the status bar, and the + * palette all reading the space the area used to host. + */ + @Test + fun switchingTheTouchedAreasSpaceRestampsItsKind() { + val tracker = HoveredSurfaceTracker() + tracker.lastTouched = HoveredSurface("area-1", SpaceKind.Viewport2D) + + tracker.restampKind("area-1", SpaceKind.Outliner) + + assertEquals(HoveredSurface("area-1", SpaceKind.Outliner), tracker.lastTouched) + assertEquals(SpaceKind.Outliner, tracker.observedKind) + } + + /** + * The strip-host claim follows the re-stamp the way it follows a pointer event: taken when the new + * kind hosts a strip, and left released when it does not. + */ + @Test + fun theStripHostClaimFollowsTheRestampedKind() { + val tracker = HoveredSurfaceTracker() + tracker.lastTouched = HoveredSurface("area-1", SpaceKind.Outliner) + + tracker.restampKind("area-1", SpaceKind.UvEditor) + assertEquals(HoveredSurface("area-1", SpaceKind.UvEditor), tracker.lastTouchedStripHost) + + // The leaf releases the outgoing kind's claim before it re-stamps, as AreaLeaf's effect does. + tracker.releaseKindClaims("area-1") + tracker.restampKind("area-1", SpaceKind.Outliner) + assertNull(tracker.lastTouchedStripHost, "a panel hosts no strip, so nothing claims the slot back") + } + + /** A space switch says nothing about where the pointer is: a stamp naming another area is left alone. */ + @Test + fun switchingAnotherAreasSpaceLeavesTheStampAlone() { + val tracker = HoveredSurfaceTracker() + val touched = HoveredSurface("viewport-1", SpaceKind.Viewport2D) + tracker.lastTouched = touched + tracker.lastTouchedStripHost = touched + + tracker.restampKind("outliner-1", SpaceKind.UvEditor) + + assertEquals(touched, tracker.lastTouched) + assertEquals(touched, tracker.lastTouchedStripHost) + assertEquals(SpaceKind.Viewport2D, tracker.observedKind) + } + + /** Before the pointer has touched anything there is no stamp to move, so a switch leaves none behind. */ + @Test + fun switchingASpaceBeforeAnyTouchStampsNothing() { + val tracker = HoveredSurfaceTracker() + + tracker.restampKind("area-1", SpaceKind.UvEditor) + + assertNull(tracker.lastTouched) + assertNull(tracker.lastTouchedStripHost) + } + + /** + * The last viewport survives the pointer moving on to a panel, as a trip to the File menu over the + * Parameters panel does, and a UV editor touched meanwhile does not take it: only a 2D viewport claims it. + */ + @Test + fun theLastViewportOutlivesPanelsAndUvEditorsTouchedAfterIt() { + val tracker = HoveredSurfaceTracker() + val viewport = HoveredSurface("viewport-1", SpaceKind.Viewport2D) + tracker.lastTouched = viewport + tracker.claimKind(viewport) + + for (later in listOf(HoveredSurface("uv-1", SpaceKind.UvEditor), HoveredSurface("parameters-1", SpaceKind.Parameters))) { + tracker.lastTouched = later + tracker.claimKind(later) + } + + assertEquals(viewport, tracker.lastTouchedViewport) + assertEquals(HoveredSurface("uv-1", SpaceKind.UvEditor), tracker.lastTouchedStripHost) + } + + /** A viewport that is closed, or switched to another space, is no longer the last viewport. */ + @Test + fun theLastViewportGoesWithItsAreaOrItsKind() { + val tracker = HoveredSurfaceTracker() + tracker.claimKind(HoveredSurface("viewport-1", SpaceKind.Viewport2D)) + tracker.releaseArea("viewport-1") + assertNull(tracker.lastTouchedViewport, "a closed area") + + tracker.lastTouched = HoveredSurface("viewport-2", SpaceKind.Viewport2D) + tracker.claimKind(HoveredSurface("viewport-2", SpaceKind.Viewport2D)) + tracker.releaseKindClaims("viewport-2") + tracker.restampKind("viewport-2", SpaceKind.Outliner) + assertNull(tracker.lastTouchedViewport, "an area switched to a panel") + + tracker.restampKind("viewport-2", SpaceKind.Viewport2D) + assertEquals(HoveredSurface("viewport-2", SpaceKind.Viewport2D), tracker.lastTouchedViewport, "and switched back") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/KeyformSheetViewsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/KeyformSheetViewsTest.kt new file mode 100644 index 0000000..a644227 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/KeyformSheetViewsTest.kt @@ -0,0 +1,93 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * Pins the shell-level sheet registry's dispatch-time resolution: the hovered sheet wins, a lone sheet + * resolves without hover, two un-hovered sheets are ambiguous for view ops but a unique selection + * disambiguates the selection ops, and unregistration is by identity so a replacement registration + * cannot be torn down by the older composition's dispose. + */ +class KeyformSheetViewsTest { + private fun surface(hasSelection: Boolean = false, boxSelectArmed: Boolean = false): KeyformSheetSurface = + KeyformSheetSurface( + selectedTracks = { emptyList() }, + hasSelection = { hasSelection }, + frameAll = {}, + armBoxSelect = {}, + boxSelectArmed = { boxSelectArmed }, + disarmBoxSelect = {}, + nudgeSelection = {}, + ) + + /** Escape has to find the armed sheet wherever it is, since arming is per area but the key is global. */ + @Test + fun theArmedSheetIsFoundWhicheverAreaHoldsIt() { + val views = KeyformSheetViews() + views.register("a", surface()) + val armed = surface(boxSelectArmed = true) + views.register("b", armed) + assertSame(armed, views.armedBoxSelect()) + + val quiet = KeyformSheetViews() + quiet.register("a", surface()) + assertNull(quiet.armedBoxSelect(), "with nothing armed, Escape falls through to the branches below it") + } + + /** The hovered sheet area always wins, regardless of how many are open. */ + @Test + fun hoveredAreaWins() { + val views = KeyformSheetViews() + val sheetA = surface() + val sheetB = surface() + views.register("a", sheetA) + views.register("b", sheetB) + assertSame(sheetB, views.resolve("b")) + assertSame(sheetA, views.resolve("a")) + } + + /** A lone open sheet resolves with no hover at all - the single-sheet case must keep working. */ + @Test + fun aLoneSheetResolvesWithoutHover() { + val views = KeyformSheetViews() + val sheet = surface() + views.register("a", sheet) + assertSame(sheet, views.resolve(null)) + assertSame(sheet, views.resolveForSelection(null)) + } + + /** Two un-hovered sheets are genuinely ambiguous for a view op, so nothing resolves. */ + @Test + fun twoUnhoveredSheetsAreAmbiguousForViewOps() { + val views = KeyformSheetViews() + views.register("a", surface()) + views.register("b", surface()) + assertNull(views.resolve(null)) + } + + /** A unique selection is itself a statement about which sheet is meant, so selection ops resolve it. */ + @Test + fun aUniqueSelectionDisambiguatesSelectionOps() { + val views = KeyformSheetViews() + val selected = surface(hasSelection = true) + views.register("a", surface(hasSelection = false)) + views.register("b", selected) + assertSame(selected, views.resolveForSelection(null)) + } + + /** Unregistration is by identity: a stale dispose must not tear down a newer registration. */ + @Test + fun unregisterIsByIdentity() { + val views = KeyformSheetViews() + val older = surface() + val newer = surface() + views.register("a", older) + views.register("a", newer) + views.unregister("a", older) + assertSame(newer, views.resolve("a"), "the stale dispose left the replacement registered") + views.unregister("a", newer) + assertNull(views.resolve("a")) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/LayoutPersistenceTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/LayoutPersistenceTest.kt new file mode 100644 index 0000000..06a19f0 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/LayoutPersistenceTest.kt @@ -0,0 +1,137 @@ +package org.umamo.ui.workspace + +import okio.Path +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.settings.Settings +import org.umamo.storage.OkioAppStorage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Verifies layout persistence over an in-memory filesystem: first run seeds + writes back the + * defaults, and a later edit survives a reload (ids and all). + */ +class LayoutPersistenceTest { + private val configDir: Path = "/config".toPath() + + /** Minimal defaults: the empty interface.layout baseline that should trigger seeding. */ + private val defaultJson = """{"interface":{"layout":{"workspaces":[]}},"localization":{"locale":"en"}}""" + + /** A fresh in-memory storage rooted at /config + /data. */ + private fun storage(): OkioAppStorage { + val fileSystem = FakeFileSystem() + fileSystem.createDirectories(configDir) + return OkioAppStorage(fileSystem, configDir, "/data".toPath()) + } + + /** + * The first leaf of a tree, reached down the leading children, so an edit can target a real area + * whatever shape the seeded workspace takes. + * + * @param AreaNode node The tree to descend. + * @return LeafArea The first leaf. + */ + private fun firstLeaf(node: AreaNode): LeafArea = + when (node) { + is LeafArea -> node + is SplitNode -> firstLeaf(node.first) + } + + /** + * loadLayout over an empty layout seeds the default workspaces and writes them back, so a fresh + * Settings over the same disk reads the identical seeded layout (proving the write-back). + */ + @Test + fun seedsDefaultsAndWritesBack() { + val storage = storage() + val seeded = loadLayout(Settings.load(storage, defaultJson)) + assertEquals(listOf("modelling", "texture", "physics"), seeded.workspaces.map { workspace -> workspace.id }) + + val reloaded = loadLayout(Settings.load(storage, defaultJson)) + assertEquals(seeded, reloaded, "the seeded layout must persist (including minted area ids)") + } + + /** + * An edited layout (a split + active-workspace change) saved through saveLayout reloads intact. + */ + @Test + fun editedLayoutSurvivesReload() { + val storage = storage() + val settings = Settings.load(storage, defaultJson) + val seeded = loadLayout(settings) + + val modellingRoot = seeded.workspaces.first { workspace -> workspace.id == "modelling" }.root + val splitRoot = reduce(modellingRoot, AreaCommand.SplitArea(firstLeaf(modellingRoot).id, SplitOrientation.Vertical)) + assertNotEquals(modellingRoot, splitRoot, "the split must change the tree") + val edited = + seeded + .copy(activeWorkspaceId = "texture") + .copy(workspaces = seeded.workspaces.map { workspace -> if (workspace.id == "modelling") workspace.copy(root = splitRoot) else workspace }) + saveLayout(settings, edited) + + val reloaded = loadLayout(Settings.load(storage, defaultJson)) + assertEquals(edited, reloaded) + } + + /** + * Export then import round-trips the whole layout: exportLayoutText pretty-prints the persisted layout + * and decodeLayoutText reads it back to an equal InterfaceLayout (minted ids and all). + */ + @Test + fun layoutExportRoundTrips() { + val settings = Settings.load(storage(), defaultJson) + val seeded = loadLayout(settings) + val text = assertNotNull(exportLayoutText(settings), "a seeded layout must export") + assertEquals(seeded, decodeLayoutText(text)) + } + + /** + * Export then import round-trips a single workspace through exportWorkspaceText / decodeWorkspaceText. + */ + @Test + fun workspaceExportRoundTrips() { + val seeded = loadLayout(Settings.load(storage(), defaultJson)) + val workspace = seeded.workspaces.first() + assertEquals(workspace, decodeWorkspaceText(exportWorkspaceText(workspace))) + } + + /** + * The two import shapes are unambiguous: a whole-layout file does not decode as a single workspace and a + * single-workspace file does not decode as a layout, so Import can try layout first, then workspace. + */ + @Test + fun importShapesAreDistinct() { + val settings = Settings.load(storage(), defaultJson) + val seeded = loadLayout(settings) + val layoutText = assertNotNull(exportLayoutText(settings)) + val workspaceText = exportWorkspaceText(seeded.workspaces.first()) + + assertNull(decodeWorkspaceText(layoutText), "a full layout must not decode as a single workspace") + assertNull(decodeLayoutText(workspaceText), "a single workspace must not decode as a full layout") + } + + /** + * Malformed text never throws and yields null from both decoders (Import then reports an invalid file). + */ + @Test + fun malformedTextDecodesToNull() { + assertNull(decodeLayoutText("not json at all")) + assertNull(decodeWorkspaceText("not json at all")) + } + + /** + * A space key this build no longer knows (here "deformerlog", a removed space) degrades to a neutral + * Outliner leaf instead of failing the layout - the serializer's forward-compatible fallback, which is + * also what keeps saved layouts from older builds opening after a space is deleted. + */ + @Test + fun unknownSpaceKeyDegradesToOutliner() { + val workspaceText = """{"id":"legacy","root":{"type":"leaf","id":"a","space":"deformerlog"}}""" + val workspace = assertNotNull(decodeWorkspaceText(workspaceText), "an unknown space key must not fail the decode") + assertEquals(LeafArea("a", SpaceKind.Outliner), workspace.root) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/LayoutSavePacerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/LayoutSavePacerTest.kt new file mode 100644 index 0000000..baf07b4 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/LayoutSavePacerTest.kt @@ -0,0 +1,95 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** + * Verifies the layout save pacing: debounced writes persist and deduplicate by instance, a held + * splitter drag blocks every debounced write, the drag's release commits exactly once, and a + * zero-movement drag writes nothing. Instances are distinguished by identity (data-class copies are + * value-equal but distinct), matching the controller's fresh-instance-per-edit publishing. + */ +class LayoutSavePacerTest { + /** A minimal single-workspace layout; copies of it model successive published edits. */ + private fun layout(): InterfaceLayout = + InterfaceLayout( + activeWorkspaceId = "workspace", + workspaces = listOf(Workspace(id = "workspace", root = LeafArea("area", SpaceKind.Viewport2D))), + ) + + @Test + fun debouncedSavePersistsOnceAndDeduplicates() { + val saved = ArrayList() + val initial = layout() + val pacer = LayoutSavePacer(initial) { persisted -> saved.add(persisted) } + val edited = initial.copy() + pacer.saveDebounced(edited) + pacer.saveDebounced(edited) + assertEquals(1, saved.size) + assertSame(edited, saved.single()) + } + + @Test + fun heldDragBlocksDebouncedWritesAndCommitsOnRelease() { + val saved = ArrayList() + val initial = layout() + val pacer = LayoutSavePacer(initial) { persisted -> saved.add(persisted) } + pacer.setDragActive(true, initial) + val midDrag = initial.copy() + // A mid-drag pause longer than the debounce would deliver this; the held drag suppresses it. + pacer.saveDebounced(midDrag) + assertEquals(0, saved.size) + val released = midDrag.copy() + pacer.setDragActive(false, released) + assertEquals(1, saved.size) + assertSame(released, saved.single()) + // The still-pending debounce of the committed instance is a duplicate - suppressed. + pacer.saveDebounced(released) + assertEquals(1, saved.size) + } + + @Test + fun zeroMovementDragWritesNothing() { + val saved = ArrayList() + val initial = layout() + val pacer = LayoutSavePacer(initial) { persisted -> saved.add(persisted) } + pacer.setDragActive(true, initial) + pacer.setDragActive(false, initial) + assertEquals(0, saved.size) + } + + @Test + fun overlappingDragsCommitOnlyWhenTheLastReleases() { + val saved = ArrayList() + val initial = layout() + val pacer = LayoutSavePacer(initial) { persisted -> saved.add(persisted) } + // Two fingers on two splitters (the touch-tablet shape): the first release must NOT resume + // writes while the second drag is still held. + pacer.setDragActive(true, initial) + pacer.setDragActive(true, initial) + val firstReleased = initial.copy() + pacer.setDragActive(false, firstReleased) + assertEquals(0, saved.size) + pacer.saveDebounced(firstReleased) + assertEquals(0, saved.size) + val secondReleased = firstReleased.copy() + pacer.setDragActive(false, secondReleased) + assertEquals(1, saved.size) + assertSame(secondReleased, saved.single()) + } + + @Test + fun savesResumeAfterCommit() { + val saved = ArrayList() + val initial = layout() + val pacer = LayoutSavePacer(initial) { persisted -> saved.add(persisted) } + val committed = initial.copy() + pacer.setDragActive(true, initial) + pacer.setDragActive(false, committed) + val laterEdit = committed.copy() + pacer.saveDebounced(laterEdit) + assertEquals(2, saved.size) + assertSame(laterEdit, saved.last()) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/ModalKeyLadderTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/ModalKeyLadderTest.kt new file mode 100644 index 0000000..0389bc0 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/ModalKeyLadderTest.kt @@ -0,0 +1,1023 @@ +package org.umamo.ui.workspace + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.PieMenuKind +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TransformAxisConstraint +import org.umamo.interop.ExportFormat +import org.umamo.interop.ExportReport +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.KeyChord +import org.umamo.ui.action.Keymap +import org.umamo.ui.document.DocumentOpenError +import org.umamo.ui.document.DocumentOpenFailure +import org.umamo.ui.kit.InlineEditController +import org.umamo.ui.kit.KeyCaptureController +import org.umamo.ui.kit.MenuBarController +import org.umamo.ui.model.SelectionHandle +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.cmd_mesh_grab +import org.umamo.ui.settings.QuickSetupState +import org.umamo.ui.viewport.pieMenuEntriesFor +import org.umamo.ui.workspace.rowdrag.RowDragCancelController +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the shell's modal key precedence - the order in which modal chrome and in-flight gestures claim a + * key before the keymap ever sees it. + * + * The ladder's own header says "Order is the contract", and until this suite existed nothing enforced + * it: every arm was reachable only through a live composition, so a reordering merged silently. Two + * halves here, and the second is the one that matters. The per-arm tests prove each state claims its + * key at all; the precedence tests open two or three modals at once and assert which one wins, which is + * the only way a mis-ordered arm actually shows up. + * + * Several arms exist because of a specific past bug - Escape during an area drag must reach + * area.dragCancel, Escape on a row drag must not deselect the dragged rows, Edit mode must never clear + * the object selection - so those are pinned against the behavior their comments describe. + */ +class ModalKeyLadderTest { + private val areaId = "viewport-1" + + private fun meshDrawable(id: String): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = + DrawableMesh( + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), + intArrayOf(0, 1, 2), + ), + geometryGrid = null, + ) + + /** + * A session in [mode] with one drawable selected and every mesh element selected, so an operator or + * tool actually latches rather than refusing on an empty selection. + * + * @param EditorMode mode The mode to leave the session in. + * @return EditorSession The session. + */ + private fun session(mode: EditorMode = EditorMode.Object): EditorSession { + val session = + EditorSession( + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(meshDrawable("a")), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + val drawable = SelectionTarget.Drawable(DrawableId("a")) + session.setSelection(Selection(setOf(drawable), drawable)) + session.setMode(mode) + if (mode == EditorMode.Edit) { + session.selectAllMeshElements() + } + return session + } + + /** + * One session per operator family, each already latched, in the mode that family requires - Object + * refuses outside Object mode and UV outside Edit mode. + * + * Each entry asserts its OWN latch, because a fixture that quietly fails to arm would make every + * ladder assertion below it pass for the wrong reason. + * + * @return List> The family name and its latched session. + */ + private fun latchedOperatorFamilies(): List> = + listOf( + "mesh" to session(EditorMode.Edit).apply { beginMeshOperator(MeshOperatorKind.Grab, areaId) }, + "object" to session(EditorMode.Object).apply { beginObjectOperator(MeshOperatorKind.Grab, areaId) }, + "uv" to session(EditorMode.Edit).apply { beginUvOperator(MeshOperatorKind.Grab, areaId) }, + ).onEach { (family, session) -> + assertNotNull(session.activeOperator, "the $family fixture must actually latch") + } + + /** A selection handle over a mutable slot, so the clear-selection arm's effect is observable. */ + private class RecordingSelection(initial: Selection) : SelectionHandle { + override var selection: Selection = initial + private set + + override fun set(selection: Selection) { + this.selection = selection + } + } + + private fun nonEmptySelection(): RecordingSelection { + val drawable = SelectionTarget.Drawable(DrawableId("a")) + return RecordingSelection(Selection(setOf(drawable), drawable)) + } + + /** A menu-bar seam whose close was recorded, so "the menu claimed it" is an assertion and not an absence. */ + private class RecordingMenuBar { + var closed = false + val controller = MenuBarController().apply { closeOpenMenu = { closed = true } } + } + + private class RecordingInlineEdit { + var cancelled = false + val controller = InlineEditController().apply { cancel = { cancelled = true } } + } + + private class RecordingRowDrag { + var cancelled = false + val controller = RowDragCancelController().apply { cancel = { cancelled = true } } + } + + /** A sheet surface with an armed marquee, recording the disarm the ladder is expected to call. */ + private class RecordingSheet(armedInitially: Boolean) { + var armed = armedInitially + + val surface: KeyformSheetSurface = + KeyformSheetSurface( + selectedTracks = { emptyList() }, + hasSelection = { false }, + frameAll = {}, + armBoxSelect = { armed = true }, + boxSelectArmed = { armed }, + disarmBoxSelect = { armed = false }, + nudgeSelection = {}, + ) + } + + private fun sheetViews(armed: Boolean): Pair { + val sheet = RecordingSheet(armed) + val views = KeyformSheetViews() + views.register("sheet-1", sheet.surface) + return views to sheet + } + + /** A controller reporting an in-flight corner drag, which several arms gate off. */ + private fun draggingController(): AreaDragController = + AreaDragController().apply { beginDrag("a", AreaCorner.TopLeft, Offset.Zero) } + + /** A minimal pending MOC3 export-options request, for the self-focused overlay arms. */ + private fun exportOptionsRequest(): ExportOptionsRequest = + ExportOptionsRequest.Moc3( + initial = Moc3ExportOptions(), + physicsAvailable = false, + userDataAvailable = false, + canvasWidth = 100f, + canvasHeight = 100f, + onConfirm = {}, + ) + + /** A registry with one recording command, for the arms that dispatch by id. */ + private class RecordingRegistry(commandId: String) { + var invoked = false + val registry = + CommandRegistry().apply { + register(Command(commandId, title = Res.string.cmd_mesh_grab) { invoked = true }) + } + } + + private fun press( + key: Key, + state: ShellModalState, + isDown: Boolean = true, + primaryModifier: Boolean = false, + shift: Boolean = false, + alt: Boolean = false, + ): Boolean = handleModalKeyLadder(ShellKeyStroke(key, isDown, primaryModifier, shift, alt), state) + + private fun escape(state: ShellModalState): Boolean = press(Key.Escape, state) + + private fun enter(state: ShellModalState): Boolean = press(Key.Enter, state) + + // --------------------------------------------------------------------------------------------- + // Arm 1-3: the modal alerts, which swallow every key so nothing fires behind them. + // --------------------------------------------------------------------------------------------- + + @Test + fun aConfirmDialogTakesEnterOrEscapeAndSwallowsEverythingElse() { + var confirmCount = 0 + val overlays = ShellOverlayState().apply { pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { confirmCount++ } } + val state = ShellModalState(overlays = overlays) + + assertTrue(press(Key.Spacebar, state), "every key is swallowed so no shortcut fires behind the dialog") + assertNotNull(overlays.pendingConfirm, "but only Enter or Escape dismisses it") + + assertTrue(escape(state)) + assertNull(overlays.pendingConfirm) + assertEquals(0, confirmCount, "Escape cancels without running the confirm") + + for (confirmKey in listOf(Key.Enter, Key.NumPadEnter)) { + val before = confirmCount + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { confirmCount++ } + + assertTrue(press(confirmKey, state)) + assertNull(overlays.pendingConfirm, "$confirmKey dismisses the dialog") + assertEquals(before + 1, confirmCount, "$confirmKey runs the confirm exactly once") + // Released like a real key: a request raised while a confirming Enter is still down waits for + // the release, so the next press would otherwise count as that Enter's repeat. + press(confirmKey, state, isDown = false) + } + } + + @Test + fun aConfirmThatRaisesAnotherConfirmLeavesTheSecondPending() { + val overlays = ShellOverlayState() + val followUp = ConfirmRequest(Res.string.cmd_mesh_grab) {} + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { overlays.pendingConfirm = followUp } + val state = ShellModalState(overlays = overlays) + + assertTrue(enter(state)) + + assertEquals(followUp, overlays.pendingConfirm, "the slot clears before the action runs, so the follow-up survives") + } + + /** + * The palette runs its command on Enter's key-down, so a confirm that command raises lands under a + * still-held Enter. The OS repeats a held key; without this rule the repeat would confirm a destructive + * action before the dialog is seen. Compose's key-down has no repeat flag, so the ladder tracks the + * key itself: the confirm stays unarmed until that Enter is released, and only a fresh press confirms. + */ + @Test + fun aConfirmRaisedUnderAHeldEnterWaitsForItsRelease() { + var confirmCount = 0 + val overlays = ShellOverlayState() + val state = ShellModalState(overlays = overlays) + // The ladder previews the key-down first; the command then raises the confirm under the held key. + press(Key.Enter, state) + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { confirmCount++ } + + assertTrue(press(Key.Enter, state), "the auto-repeat of the same Enter is swallowed") + assertNotNull(overlays.pendingConfirm, "and confirms nothing") + assertTrue(press(Key.Enter, state, isDown = false), "the release is swallowed too") + assertNotNull(overlays.pendingConfirm, "and confirms nothing either") + assertEquals(0, confirmCount) + + assertTrue(enter(state)) + assertNull(overlays.pendingConfirm, "a fresh press confirms") + assertEquals(1, confirmCount, "exactly once") + } + + @Test + fun aHeldNumPadEnterIsHeldEnterToo() { + var confirmCount = 0 + val overlays = ShellOverlayState() + val state = ShellModalState(overlays = overlays) + press(Key.NumPadEnter, state) + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { confirmCount++ } + + assertTrue(press(Key.NumPadEnter, state)) + assertNotNull(overlays.pendingConfirm, "the repeated NumPadEnter confirms nothing") + press(Key.NumPadEnter, state, isDown = false) + + assertTrue(press(Key.NumPadEnter, state)) + assertNull(overlays.pendingConfirm, "and a fresh press confirms") + assertEquals(1, confirmCount) + } + + @Test + fun escapeCancelsAConfirmThatEnterCannotYetConfirm() { + var confirmCount = 0 + val overlays = ShellOverlayState() + val state = ShellModalState(overlays = overlays) + press(Key.Enter, state) + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { confirmCount++ } + + assertTrue(escape(state)) + + assertNull(overlays.pendingConfirm, "the arming gates Enter alone; Escape cancels as always") + assertEquals(0, confirmCount) + } + + @Test + fun anAppAlertTakesEscapeOrEnterAndSwallowsEverythingElse() { + val overlays = ShellOverlayState().apply { pendingAlert = AlertRequest(Res.string.cmd_mesh_grab) } + val state = ShellModalState(overlays = overlays) + + assertTrue(press(Key.Spacebar, state)) + assertNotNull(overlays.pendingAlert, "every other key is swallowed") + assertTrue(enter(state)) + assertNull(overlays.pendingAlert, "Enter acknowledges it") + + overlays.pendingAlert = AlertRequest(Res.string.cmd_mesh_grab) + assertTrue(escape(state)) + assertNull(overlays.pendingAlert, "and so does Escape") + } + + @Test + fun theOpenFailureAlertTakesEscapeOrEnter() { + val overlays = + ShellOverlayState().apply { openFailure = DocumentOpenFailure(DocumentOpenError.ReadFailed, "model.cmo3") } + val state = ShellModalState(overlays = overlays) + + assertTrue(press(Key.Spacebar, state)) + assertNotNull(overlays.openFailure) + + assertTrue(enter(state), "Enter acknowledges it like its OK button") + assertNull(overlays.openFailure) + } + + @Test + fun theExportReportAlertTakesEscapeOrEnter() { + val overlays = ShellOverlayState().apply { exportReport = ExportReport(ExportFormat.Cmo3, emptyList()) } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertNull(overlays.exportReport) + } + + // --------------------------------------------------------------------------------------------- + // Arm 4-6: the chrome that claims Escape but yields other keys to its own content. + // --------------------------------------------------------------------------------------------- + + @Test + fun anOpenMenuTakesEscape() { + val menu = RecordingMenuBar() + val state = ShellModalState(menuBarController = menu.controller) + + assertTrue(escape(state)) + assertTrue(menu.closed) + } + + @Test + fun anOpenMenuSwallowsOtherKeysInsteadOfFiringShortcutsBehindIt() { + // The bar's dropdowns open non-focusable so the labels keep receiving hover, which leaves the host + // window focused and this root ladder seeing every key first. The bar's own handler claims ONLY + // Escape, so before this arm covered the rest, G with the File menu open dispatched mesh.grab and + // left the menu hanging open over the moving geometry. + val menu = RecordingMenuBar() + val registry = RecordingRegistry("mesh.grab") + val keymap = Keymap(mapOf(KeyChord("KeyG") to "mesh.grab")) + val state = + ShellModalState( + menuBarController = menu.controller, + commandRegistry = registry.registry, + keymap = keymap, + ) + + assertFalse(press(Key.G, state), "the key is inert; the menu has no keyboard content to yield to") + + assertFalse(registry.invoked, "no shortcut may fire while a menu is open") + assertFalse(menu.closed, "and an unrelated key does not dismiss the menu either") + } + + /** + * A control capturing the next key press (the keybindings editor's chord chip) owns the whole keyboard, Escape + * included: the ladder previews every key before the control does, so it has to stand aside or the overlay arm + * closes Preferences behind the capture. A confirm still outranks it - it paints over everything and can + * arrive unasked while a capture is live. + */ + @Test + fun aLiveKeyCaptureOwnsEveryKeyOverAnOpenOverlay() { + val overlays = ShellOverlayState().apply { settingsVisible = true } + val keyCapture = KeyCaptureController() + val state = ShellModalState(overlays = overlays, keyCapture = keyCapture) + + keyCapture.begin() + assertFalse(escape(state), "Escape is left to the capturing control, which cancels its capture") + assertTrue(overlays.settingsVisible, "and Preferences stays open") + assertFalse(press(Key.Spacebar, state), "as is every other key - any of them may be the one being bound") + + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) {} + assertTrue(escape(state), "a confirm raised over the capture takes its own Escape") + assertNull(overlays.pendingConfirm) + assertTrue(overlays.settingsVisible) + + keyCapture.end() + assertTrue(escape(state), "with the capture over, Escape is the overlay's again") + assertFalse(overlays.settingsVisible) + } + + /** Two captures overlapping - one chip ending as another begins - never read as no capture at all. */ + @Test + fun overlappingKeyCapturesStayLiveUntilTheLastEnds() { + val keyCapture = KeyCaptureController() + + keyCapture.begin() + keyCapture.begin() + keyCapture.end() + assertTrue(keyCapture.active) + keyCapture.end() + assertFalse(keyCapture.active) + keyCapture.end() + assertFalse(keyCapture.active, "an unpaired end is harmless") + } + + @Test + fun theSelfFocusedOverlaysTakeEscapeAndYieldOtherKeys() { + // Preferences, Quick Setup, the two Help dialogs, the palette, and the export-options dialog are one + // family: Escape closes, anything else falls through to the overlay's own content (its search field, + // its scroll, its links, its number field's type-in). + val cases = + listOf Boolean>>( + Triple("preferences", ShellOverlayState().apply { settingsVisible = true }, { it.settingsVisible }), + Triple("quick setup", ShellOverlayState().apply { quickSetupVisible = true }, { it.quickSetupVisible }), + Triple("about", ShellOverlayState().apply { aboutVisible = true }, { it.aboutVisible }), + Triple("credits", ShellOverlayState().apply { creditsVisible = true }, { it.creditsVisible }), + Triple("palette", ShellOverlayState().apply { paletteVisible = true }, { it.paletteVisible }), + Triple( + "export options", + ShellOverlayState().apply { pendingExportOptions = exportOptionsRequest() }, + { it.pendingExportOptions != null }, + ), + ) + for ((name, overlays, isOpen) in cases) { + val state = ShellModalState(overlays = overlays) + + assertFalse(press(Key.A, state), "$name yields non-Escape keys to its own content") + assertTrue(isOpen(overlays), "$name stays open") + + assertTrue(escape(state), "$name claims Escape") + assertFalse(isOpen(overlays), "$name closed") + } + } + + @Test + fun escapeClosesOnlyTheTopmostSelfFocusedOverlay() { + // The four share ONE ladder arm, so their relative order lives in closeTopmostSelfFocused rather + // than in the ladder; this is what pins the two together: one Escape closes exactly one overlay, + // the topmost, leaving the one beneath it up. + val overlays = + ShellOverlayState().apply { + settingsVisible = true + aboutVisible = true + } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertFalse(overlays.settingsVisible, "preferences sits above the Help dialogs") + assertTrue(overlays.aboutVisible, "and the dialog beneath it survives the first Escape") + + assertTrue(escape(state)) + assertFalse(overlays.aboutVisible, "a second Escape takes the next one down") + } + + @Test + fun quickSetupSitsAbovePreferences() { + val overlays = + ShellOverlayState().apply { + settingsVisible = true + quickSetupVisible = true + } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertFalse(overlays.quickSetupVisible, "Quick Setup closes before preferences") + assertTrue(overlays.settingsVisible, "which survives the first Escape") + } + + @Test + fun quickSetupLivesInTheAppsHolderNotTheShell() { + // The shell's overlay state is rebuilt on every document swap; Quick Setup's visibility is the app's, + // so a new shell over the same holder opens with it still up, and closing it closes it for the app. + val quickSetup = QuickSetupState(visible = true) + assertTrue(ShellOverlayState(quickSetup).quickSetupVisible, "open in the first shell") + + val rebuilt = ShellOverlayState(quickSetup) + assertTrue(rebuilt.quickSetupVisible, "and still open in the shell a document swap rebuilds") + + assertTrue(escape(ShellModalState(overlays = rebuilt))) + assertFalse(quickSetup.visible, "Escape in the new shell closes it in the app's holder") + } + + @Test + fun aConfirmOverQuickSetupTakesEscapeWhileQuickSetupStaysOpen() { + // A first launch can raise an alert or a confirm under Quick Setup; the alert arms sit above the + // self-focused arm, so their keys never reach Quick Setup's Escape-to-close. + val overlays = + ShellOverlayState().apply { + quickSetupVisible = true + pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) {} + } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertNull(overlays.pendingConfirm, "Escape cancels the confirm") + assertTrue(overlays.quickSetupVisible, "and Quick Setup stays open") + } + + @Test + fun theExportOptionsDialogSitsAtopTheSelfFocusedFamily() { + val overlays = + ShellOverlayState().apply { + pendingExportOptions = exportOptionsRequest() + settingsVisible = true + } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertNull(overlays.pendingExportOptions, "the export dialog closes before preferences") + assertTrue(overlays.settingsVisible, "which survives the first Escape") + + assertTrue(escape(state)) + assertFalse(overlays.settingsVisible) + } + + @Test + fun aConfirmDialogOutranksTheExportOptionsDialog() { + // The confirm is a modal alert, the export dialog a self-focused overlay; the alert arm sits + // higher in the ladder, so Escape reaches the confirm first. + val overlays = + ShellOverlayState().apply { + pendingExportOptions = exportOptionsRequest() + pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) {} + } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertNull(overlays.pendingConfirm, "the confirm took it") + assertNotNull(overlays.pendingExportOptions, "and the export dialog beneath it stays up") + } + + @Test + fun aConfirmOverPreferencesTakesEnterAndEscapeWhilePreferencesStaysOpen() { + // The keybinding conflict prompt raises its confirm from inside Preferences; the confirm arm sits + // above the self-focused arm, so its keys never reach Preferences' Escape-to-close. + var reassignCount = 0 + val overlays = + ShellOverlayState().apply { + settingsVisible = true + pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { reassignCount++ } + } + val state = ShellModalState(overlays = overlays) + + assertTrue(escape(state)) + assertNull(overlays.pendingConfirm, "Escape cancels the prompt") + assertTrue(overlays.settingsVisible, "and Preferences stays open") + assertEquals(0, reassignCount) + + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) { reassignCount++ } + assertTrue(enter(state)) + assertNull(overlays.pendingConfirm, "Enter confirms the prompt") + assertTrue(overlays.settingsVisible, "and Preferences still stays open") + assertEquals(1, reassignCount) + } + + @Test + fun anInlineEditorTakesEscapeAndYieldsOtherKeysToTheField() { + val inline = RecordingInlineEdit() + val state = ShellModalState(inlineEditController = inline.controller) + + assertFalse(press(Key.A, state), "letters must reach the field, not fire file commands") + assertFalse(inline.cancelled) + + assertTrue(escape(state)) + assertTrue(inline.cancelled) + } + + // --------------------------------------------------------------------------------------------- + // Arm 7-8: the modal operator latches - one Escape arm and one Enter arm, shared by all three families. + // --------------------------------------------------------------------------------------------- + + @Test + fun escapeCancelsAnyModalOperator() { + for ((family, session) in latchedOperatorFamilies()) { + assertTrue(escape(ShellModalState(editorSession = session)), family) + + assertNull(session.activeMeshOperator.value, family) + assertNull(session.activeObjectOperator.value, family) + assertNull(session.activeUvOperator.value, family) + } + } + + @Test + fun escapeOnAMeshOperatorDoesNotAlsoClearTheVertexSelection() { + // The arm sits above the clear-selection arm precisely so cancelling a grab keeps the selection. + val session = session(EditorMode.Edit) + session.beginMeshOperator(MeshOperatorKind.Grab, areaId) + assertNotNull(session.activeMeshOperator.value, "fixture: the grab must be running") + val before = session.meshSelection.value + + assertTrue(escape(ShellModalState(editorSession = session))) + + assertNull(session.activeMeshOperator.value) + assertEquals(before, session.meshSelection.value, "the grab was cancelled, not the selection") + } + + @Test + fun enterConfirmsAnyModalOperator() = + runTest { + for ((family, session) in latchedOperatorFamilies()) { + var confirms = 0 + val collector = launch { session.meshConfirmRequests.collect { confirms++ } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + assertTrue(enter(ShellModalState(editorSession = session))) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + assertEquals(1, confirms, "$family: Enter mirrors a primary click through the shared confirm signal") + collector.cancel() + } + } + + // --------------------------------------------------------------------------------------------- + // Arm 9: the pie menu, which owns the keyboard while its ring is up. + // --------------------------------------------------------------------------------------------- + + @Test + fun anOpenPieMenuTakesEscapeAndSwallowsUnhandledKeys() { + val session = session(EditorMode.Object) + session.openPieMenu(PieMenuKind.PivotMode) + val state = ShellModalState(editorSession = session) + + assertTrue(press(Key.A, state), "shortcuts must not fire under the ring") + assertNotNull(session.activePieMenu.value, "an unmapped key leaves the ring up") + + assertTrue(escape(state)) + assertNull(session.activePieMenu.value) + } + + @Test + fun aPieMenuDigitPicksItsEntryAndClosesTheRing() { + val session = session(EditorMode.Object) + session.openPieMenu(PieMenuKind.PivotMode) + val first = pieMenuEntriesFor(PieMenuKind.PivotMode).first() + val registry = RecordingRegistry(first.commandId) + val state = ShellModalState(editorSession = session, commandRegistry = registry.registry) + + assertTrue(press(Key.One, state)) + + assertTrue(registry.invoked, "digit 1 picks the first chip, matching the ordinal it draws") + assertNull(session.activePieMenu.value, "and the ring closes behind the pick") + } + + @Test + fun aPieMenuIgnoresKeyUp() { + // The arm gates on isDown, so a key-up under the ring falls past it - the ring stays open. + val session = session(EditorMode.Object) + session.openPieMenu(PieMenuKind.PivotMode) + + press(Key.Escape, ShellModalState(editorSession = session), isDown = false) + + assertNotNull(session.activePieMenu.value) + } + + // --------------------------------------------------------------------------------------------- + // Arm 10-11: the axis lock, which only the ladder can deliver while an operator swallows input. + // --------------------------------------------------------------------------------------------- + + @Test + fun xAndZToggleTheAxisLockUnderEveryOperatorFamily() { + for ((family, session) in latchedOperatorFamilies()) { + val state = ShellModalState(editorSession = session) + + assertTrue(press(Key.X, state), family) + assertEquals(TransformAxisConstraint.AxisX, session.axisConstraint.value, family) + + assertTrue(press(Key.Z, state), family) + assertEquals(TransformAxisConstraint.AxisZ, session.axisConstraint.value, family) + } + } + + @Test + fun xIsNotClaimedWithNoOperatorRunning() { + // Without a live operator X must reach the keymap, or the axis arm would eat a bindable key. + val session = session(EditorMode.Object) + + assertFalse(press(Key.X, ShellModalState(editorSession = session))) + assertNull(session.axisConstraint.value) + } + + // --------------------------------------------------------------------------------------------- + // Arm 12-17: the armed tools and in-flight panel gestures. + // --------------------------------------------------------------------------------------------- + + @Test + fun anArmedSelectToolTakesEscapeAndEnterAndCancelsBeforeDisarming() = + runTest { + for (key in listOf(Key.Escape, Key.Enter)) { + val session = session(EditorMode.Object) + session.beginBoxSelect(areaId) + assertNotNull(session.activeSelectTool.value, "fixture: the tool must be armed") + var cancels = 0 + val collector = launch { session.meshGestureCancelRequests.collect { cancels++ } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + assertTrue(press(key, ShellModalState(editorSession = session))) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + // The cancel must fire as well as the disarm: clearSelectTool alone routes cleanup through a + // recomposition-gated effect that can lose the race to a mouse release still in flight. + assertEquals(1, cancels, "$key resolves the in-flight gesture") + assertNull(session.activeSelectTool.value, "$key disarms the tool") + collector.cancel() + } + } + + @Test + fun anArmedSheetMarqueeTakesEscape() { + val (views, sheet) = sheetViews(armed = true) + + assertTrue(escape(ShellModalState(keyformSheets = views))) + + assertFalse(sheet.armed, "an armed marquee hides the cursor, so it must always have a way out") + } + + @Test + fun anArmedRelationPickTakesEscape() { + val relationPick = RelationPickController() + relationPick.arm(accepts = emptySet()) {} + val selection = nonEmptySelection() + val state = ShellModalState(selection = selection, relationPick = relationPick) + + assertTrue(escape(state)) + + assertNull(relationPick.request) + assertFalse(selection.selection.isEmpty, "abandoning a pick must never also wipe the selection") + } + + @Test + fun anArmedZoomRegionTakesEscape() { + val session = session(EditorMode.Object) + session.armZoomRegion(areaId) + assertNotNull(session.zoomRegionArmedArea.value, "fixture: the region must be armed") + + assertTrue(escape(ShellModalState(editorSession = session))) + + assertNull(session.zoomRegionArmedArea.value) + } + + @Test + fun anInFlightRowDragTakesEscapeWithoutDeselectingTheDraggedRows() { + // The press that started the drag already selected the row, so the clear-selection arm below would + // otherwise deselect the rows mid-drag. + val rowDrag = RecordingRowDrag() + val registry = RecordingRegistry("row.dragCancel") + val selection = nonEmptySelection() + val state = + ShellModalState( + selection = selection, + rowDragCancel = rowDrag.controller, + commandRegistry = registry.registry, + ) + + assertTrue(escape(state)) + + assertTrue(registry.invoked, "the cancel routes through the registry, mirroring area.dragCancel") + assertFalse(selection.selection.isEmpty, "and the dragged rows keep their selection") + } + + @Test + fun anInFlightDividerDragTakesEscapeWithoutClearingTheSelection() { + // A divider drag keeps its session inside the dragged SplitContainer and never touches + // AreaDragController, so isDragging stays false and the corner-drag gates below do not cover it. + // Before this arm existed, Escape while resizing a panel fell all the way through and wiped the + // object selection. + val splitterDragCancel = SplitterDragCancelController() + var cancelled = false + splitterDragCancel.cancel = { cancelled = true } + val registry = RecordingRegistry("area.dragCancel") + val selection = nonEmptySelection() + val state = + ShellModalState( + editorSession = session(EditorMode.Object), + selection = selection, + splitterDragCancel = splitterDragCancel, + commandRegistry = registry.registry, + ) + + assertTrue(escape(state)) + + assertTrue(registry.invoked, "the cancel routes through area.dragCancel like the corner drag") + assertFalse(selection.selection.isEmpty, "and resizing a panel never touches the selection") + assertFalse(cancelled, "the recording seam is only reached through the real command, not directly") + } + + @Test + fun noDividerDragLeavesEscapeToTheArmsBelow() { + // Guards the arm against widening to "the area tree exists": with no drag parked, Escape must + // still reach the clear-selection arm. + val selection = nonEmptySelection() + + assertTrue(escape(ShellModalState(selection = selection, splitterDragCancel = SplitterDragCancelController()))) + + assertTrue(selection.selection.isEmpty) + } + + // --------------------------------------------------------------------------------------------- + // Arm 18-19: the viewport gestures and the final clear-selection, the last arms before the + // else that falls through to the shell keymap. + // --------------------------------------------------------------------------------------------- + + @Test + fun anInFlightViewportDragTakesEscapeWithoutClearingTheSelection() = + runTest { + val session = session(EditorMode.Object) + session.setViewportGestureActive(true) + val selection = nonEmptySelection() + var cancels = 0 + val collector = launch { session.meshGestureCancelRequests.collect { cancels++ } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + assertTrue(escape(ShellModalState(editorSession = session, selection = selection))) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + assertEquals(1, cancels) + assertFalse(selection.selection.isEmpty, "cancelling a drag never also wipes the selection") + collector.cancel() + } + + @Test + fun editModeConsumesEscapeAndNeverClearsTheObjectSelection() { + // Blender parity: Edit mode leaves the selection alone. Clearing it here would strand the Edit + // session on a drawable nothing points at, since the object selection holds the edited drawable. + val session = session(EditorMode.Edit) + val selection = nonEmptySelection() + + assertTrue(escape(ShellModalState(editorSession = session, selection = selection))) + + assertFalse(selection.selection.isEmpty) + } + + @Test + fun objectModeEscapeClearsANonEmptySelection() { + val session = session(EditorMode.Object) + val selection = nonEmptySelection() + + assertTrue(escape(ShellModalState(editorSession = session, selection = selection))) + + assertTrue(selection.selection.isEmpty) + } + + @Test + fun aNullSessionCountsAsObjectModeForTheClear() { + val selection = nonEmptySelection() + + assertTrue(escape(ShellModalState(selection = selection))) + + assertTrue(selection.selection.isEmpty) + } + + // --------------------------------------------------------------------------------------------- + // The fallthrough. + // --------------------------------------------------------------------------------------------- + + @Test + fun anUnclaimedKeyReachesTheKeymap() { + val registry = RecordingRegistry("mesh.grab") + val keymap = Keymap(mapOf(KeyChord("KeyG") to "mesh.grab")) + val state = ShellModalState(commandRegistry = registry.registry, keymap = keymap) + + assertTrue(press(Key.G, state)) + assertTrue(registry.invoked) + } + + @Test + fun anUnclaimedKeyUpReachesNothing() { + val registry = RecordingRegistry("mesh.grab") + val keymap = Keymap(mapOf(KeyChord("KeyG") to "mesh.grab")) + val state = ShellModalState(commandRegistry = registry.registry, keymap = keymap) + + assertFalse(press(Key.G, state, isDown = false)) + assertFalse(registry.invoked, "only key-down dispatches") + } + + @Test + fun theKeymapSeesTheStrokesModifiers() { + val registry = RecordingRegistry("mesh.grab") + val keymap = Keymap(mapOf(KeyChord("KeyG", primaryModifier = true, shift = true) to "mesh.grab")) + val state = ShellModalState(commandRegistry = registry.registry, keymap = keymap) + + assertFalse(press(Key.G, state), "the bare chord is unbound") + assertTrue(press(Key.G, state, primaryModifier = true, shift = true)) + assertTrue(registry.invoked) + } + + // --------------------------------------------------------------------------------------------- + // Precedence: two or more modals live at once. A per-arm sweep passes regardless of order, so + // these are what actually enforce the contract. + // --------------------------------------------------------------------------------------------- + + @Test + fun aConfirmDialogOutranksEverythingBelowIt() { + val session = session(EditorMode.Edit) + session.beginMeshOperator(MeshOperatorKind.Grab, areaId) + val overlays = ShellOverlayState().apply { pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) {} } + val menu = RecordingMenuBar() + val selection = nonEmptySelection() + + assertTrue( + escape( + ShellModalState( + overlays = overlays, + menuBarController = menu.controller, + editorSession = session, + selection = selection, + ), + ), + ) + + assertNull(overlays.pendingConfirm, "the dialog took it") + assertFalse(menu.closed, "and nothing below it ran") + assertNotNull(session.activeMeshOperator.value) + assertFalse(selection.selection.isEmpty) + + overlays.pendingConfirm = ConfirmRequest(Res.string.cmd_mesh_grab) {} + assertTrue(enter(ShellModalState(overlays = overlays, menuBarController = menu.controller, editorSession = session, selection = selection))) + + assertNull(overlays.pendingConfirm, "Enter goes to the dialog too") + assertNotNull(session.activeMeshOperator.value, "rather than confirming the operator beneath it") + } + + @Test + fun anOpenMenuOutranksAModalOperator() { + val session = session(EditorMode.Edit) + session.beginMeshOperator(MeshOperatorKind.Grab, areaId) + val menu = RecordingMenuBar() + + assertTrue(escape(ShellModalState(menuBarController = menu.controller, editorSession = session))) + + assertTrue(menu.closed) + assertNotNull(session.activeMeshOperator.value, "the grab survives closing the menu") + } + + @Test + fun aModalOperatorOutranksAnArmedSelectTool() { + // beginBoxSelect then beginMeshOperator leaves only the operator latched (they are mutually + // exclusive), so this pins the ordering with the operator arm reached first. + val session = session(EditorMode.Edit) + session.beginBoxSelect(areaId) + session.beginMeshOperator(MeshOperatorKind.Grab, areaId) + assertNotNull(session.activeMeshOperator.value, "fixture: the grab must be running") + assertNull(session.activeSelectTool.value, "the latches are mutually exclusive") + + assertTrue(escape(ShellModalState(editorSession = session))) + + assertNull(session.activeMeshOperator.value) + } + + @Test + fun anAreaDragDefersEscapeToTheDragCancelCommand() { + // The three lowest arms all gate off !isDragging so an in-flight area CORNER drag reaches + // area.dragCancel through the keymap; without that gate it would clear the selection instead of + // cancelling. Note this covers the corner drag ONLY - a divider (splitter) drag keeps its session + // in SplitContainer's own state, never sets isDragging, and so has no Escape cancel at all. + val session = session(EditorMode.Object) + val selection = nonEmptySelection() + val registry = RecordingRegistry("area.dragCancel") + val keymap = Keymap(mapOf(KeyChord("Escape") to "area.dragCancel")) + val state = + ShellModalState( + editorSession = session, + selection = selection, + dragController = draggingController(), + commandRegistry = registry.registry, + keymap = keymap, + ) + + assertTrue(escape(state)) + + assertTrue(registry.invoked, "Escape reached area.dragCancel") + assertFalse(selection.selection.isEmpty, "and did not clear the selection on the way") + } + + @Test + fun anArmedSheetMarqueeOutranksTheClearSelection() { + val (views, sheet) = sheetViews(armed = true) + val selection = nonEmptySelection() + + assertTrue(escape(ShellModalState(selection = selection, keyformSheets = views))) + + assertFalse(sheet.armed) + assertFalse(selection.selection.isEmpty, "disarming a marquee is not a deselect") + } + + @Test + fun anUnarmedSheetLeavesEscapeToTheArmsBelow() { + // Guards the arm against widening to "a sheet is open" - it must key on ARMED. + val (views, _) = sheetViews(armed = false) + val selection = nonEmptySelection() + + assertTrue(escape(ShellModalState(selection = selection, keyformSheets = views))) + + assertTrue(selection.selection.isEmpty, "with nothing armed the clear-selection arm runs") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/OperationStripLabelsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/OperationStripLabelsTest.kt new file mode 100644 index 0000000..66bdf53 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/OperationStripLabelsTest.kt @@ -0,0 +1,93 @@ +package org.umamo.ui.workspace + +import org.umamo.edit.MergeTarget +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.OperatorParameter +import org.umamo.edit.ProportionalFalloff +import org.umamo.edit.ProportionalRows +import org.umamo.edit.TransformGestureParameters +import org.umamo.edit.TransformRowSpace +import org.umamo.edit.mergeParameters +import org.umamo.edit.slideParameters +import org.umamo.edit.transformParameters +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.ui.model.addArtworkParameters +import org.umamo.ui.model.matchArtworkParameters +import org.umamo.ui.model.repackParameters +import org.umamo.ui.viewport.PlacementDragStatus +import org.umamo.ui.viewport.placementParameters +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the operation strip's row descriptions: every row the strip can show has one, no two rows share + * one by accident, and a choice entry's key never picks one up. + * + * The rows come from the operations' own row builders rather than from a hand-kept key list, so an + * operation that grows a row fails here until the row has a description to show. + */ +class OperationStripLabelsTest { + /** + * Every row every adjustable operation registers: the repack, the three placement gestures, adding and + * matching artwork, each modal transform in both of its spaces with the proportional rows on, the + * vertex slide, and the merge. + */ + private val everyRow: List = + buildList { + addAll(repackParameters(AtlasPackOptions())) + for (kind in listOf(MeshOperatorKind.Grab, MeshOperatorKind.Rotate, MeshOperatorKind.Scale)) { + addAll(placementParameters(PlacementDragStatus(kind, 0, 0, 0f, 1f, 1f, 0, false), 1024, 1024)) + for (space in TransformRowSpace.entries) { + addAll(transformParameters(kind, TransformGestureParameters.IDENTITY, space, ProportionalRows(true, ProportionalFalloff.Smooth, 50f, false))) + } + } + addAll(addArtworkParameters(SourceArtImportOptions(), placed = true)) + addAll(matchArtworkParameters(0.8f, SourceArtImportOptions())) + addAll(slideParameters(0.5f)) + addAll(mergeParameters(MergeTarget.AtCenter)) + } + + /** The distinct label keys of [everyRow], the unit a description is looked up by. */ + private val everyLabelKey: List = everyRow.map { row -> row.labelKey }.distinct() + + /** A row with no description would show its label and nothing to explain it. */ + @Test + fun everyRowHasADescription() { + for (labelKey in everyLabelKey) { + assertNotNull(operatorParameterDescriptionRes(labelKey), "the strip row $labelKey has no description") + } + } + + /** + * Two rows mapped to one description is a copy-paste slip: the keys are distinct precisely because the + * rows mean different things, even where two share a label (a placement's Move Y and a transform's). + */ + @Test + fun noTwoRowsShareADescription() { + val descriptions = everyLabelKey.mapNotNull { labelKey -> operatorParameterDescriptionRes(labelKey) } + assertEquals(descriptions.size, descriptions.distinct().size, "two strip rows share one description") + } + + /** + * A choice entry's key names one option in a dropdown, not a row, so it describes nothing; resolving + * one would mean a prefixed key collided with a row's. + */ + @Test + fun choiceEntriesHaveNoDescription() { + val entryKeys = everyRow.filterIsInstance().flatMap { row -> row.choices.mapNotNull { choice -> choice.labelKey } } + assertTrue(entryKeys.isNotEmpty(), "the strip has choice rows whose entries carry label keys") + for (entryKey in entryKeys) { + assertNull(operatorParameterDescriptionRes(entryKey), "the choice entry $entryKey resolved a row description") + } + } + + /** An unknown key describes nothing rather than borrowing another row's text. */ + @Test + fun anUnknownKeyHasNoDescription() { + assertNull(operatorParameterDescriptionRes("not.a.row")) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/RelationPickTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/RelationPickTest.kt new file mode 100644 index 0000000..dd1b0ea --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/RelationPickTest.kt @@ -0,0 +1,155 @@ +package org.umamo.ui.workspace + +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.PartId +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the relation-pick slot's resolve contract: only an accepted kind resolves (and does so exactly + * once, clearing the request first), a click on the wrong kind leaves the pick armed rather than silently + * ending it, and cancelling clears without firing. + */ +class RelationPickTest { + private val drawable = SelectionTarget.Drawable(DrawableId("d1")) + private val part = SelectionTarget.Part(PartId("p1")) + private val deformer = SelectionTarget.Deformer(DeformerId("w1")) + + @Test + fun kindsMapFromTargets() { + assertEquals(PickKind.Drawable, drawable.pickKind()) + assertEquals(PickKind.Part, part.pickKind()) + assertEquals(PickKind.Deformer, deformer.pickKind()) + } + + @Test + fun resolvesAnAcceptedKindOnceAndClears() { + val controller = RelationPickController() + val picked = mutableListOf() + controller.arm(setOf(PickKind.Drawable)) { target -> picked.add(target) } + + assertTrue(controller.resolve(drawable)) + assertEquals(listOf(drawable), picked) + assertNull(controller.request, "the request clears as it fires") + + // A second click has nothing to resolve and must not re-fire the callback. + assertFalse(controller.resolve(drawable)) + assertEquals(listOf(drawable), picked) + } + + @Test + fun anUnacceptedKindLeavesThePickArmed() { + val controller = RelationPickController() + val picked = mutableListOf() + controller.arm(setOf(PickKind.Part)) { target -> picked.add(target) } + + assertFalse(controller.resolve(drawable), "a drawable is not accepted") + assertTrue(picked.isEmpty()) + assertTrue(controller.request != null, "a stray click on the wrong kind does not end the pick") + + assertTrue(controller.resolve(part)) + assertEquals(listOf(part), picked) + } + + @Test + fun hoverReportsOnlyAcceptedKindsAndClearsWithThePick() { + val controller = RelationPickController() + controller.arm(setOf(PickKind.Drawable)) { } + + controller.hover(drawable) + assertEquals(drawable, controller.hoveredTarget) + + // A surface may report freely; an unaccepted kind simply reads as nothing to pick. + controller.hover(part) + assertNull(controller.hoveredTarget) + + // Resolving clears the hover along with the request, so no stale label survives the pick. + controller.hover(drawable) + controller.resolve(drawable) + assertNull(controller.hoveredTarget) + + // With nothing armed a report is ignored outright. + controller.hover(drawable) + assertNull(controller.hoveredTarget) + } + + @Test + fun unhoverOnlyClearsTheSurfaceStillReported() { + val controller = RelationPickController() + controller.arm(setOf(PickKind.Drawable, PickKind.Part)) { } + + controller.hover(drawable) + // A surface the pointer already left must not clear a hover another surface has since published. + controller.unhover(part) + assertEquals(drawable, controller.hoveredTarget) + + controller.unhover(drawable) + assertNull(controller.hoveredTarget) + } + + @Test + fun anArmedPickSwallowsClicksItWillNotAccept() { + val controller = RelationPickController() + val picked = mutableListOf() + + // With nothing armed a surface handles its own clicks as usual. + assertEquals(PickClickOutcome.Ignored, controller.click(part)) + + controller.arm(setOf(PickKind.Drawable)) { target -> picked.add(target) } + + // The regression: a part clicked during a drawable-only pick must NOT fall through to selection - + // selecting would swap the Properties panel, and the arming field with it, out from under the pick. + assertEquals(PickClickOutcome.Swallowed, controller.click(part)) + assertTrue(picked.isEmpty()) + assertTrue(controller.request != null, "the pick survives so the user can click a valid target") + + assertEquals(PickClickOutcome.Resolved, controller.click(drawable)) + assertEquals(listOf(drawable), picked) + // The pick is over, so the surface owns its clicks again. + assertEquals(PickClickOutcome.Ignored, controller.click(part)) + } + + @Test + fun cancelClearsWithoutFiring() { + val controller = RelationPickController() + var fired = false + controller.arm(setOf(PickKind.Drawable, PickKind.Part)) { fired = true } + + controller.hover(drawable) + controller.cancel() + + assertNull(controller.request) + assertNull(controller.hoveredTarget) + assertFalse(fired) + assertFalse(controller.resolve(drawable)) + } + + /** + * cancelFor is what the arming field's teardown calls, so it MUST be scoped: an armed pick parks a + * callback and a full-window hidden cursor in shell state, and a blanket cancel from an unrelated field + * disposing would silently kill a pick the user is still in the middle of. + */ + @Test + fun cancelForOnlyCancelsThePickItsOwnerArmed() { + val controller = RelationPickController() + controller.arm(setOf(PickKind.Drawable), owner = "field.a") {} + + // Another field going away must not touch this pick. + controller.cancelFor("field.b") + assertNotNull(controller.request, "a different owner cannot cancel it") + assertTrue(controller.isPickingFor("field.a")) + + // A null owner never matches, so an unowned teardown cannot cancel either. + controller.cancelFor(null) + assertNotNull(controller.request) + + controller.cancelFor("field.a") + assertNull(controller.request, "the arming field's teardown does cancel it") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SessionStateJsonTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SessionStateJsonTest.kt new file mode 100644 index 0000000..e4a08dd --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SessionStateJsonTest.kt @@ -0,0 +1,160 @@ +package org.umamo.ui.workspace + +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.umamo.edit.Cursor2d +import org.umamo.edit.DEFAULT_PROPORTIONAL_EDIT_STATE +import org.umamo.edit.EditorMode +import org.umamo.edit.GridConfig +import org.umamo.edit.MeshSelectMode +import org.umamo.edit.ParameterSelection +import org.umamo.edit.ProportionalEditState +import org.umamo.edit.ProportionalFalloff +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.SessionViewState +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.UvCursor +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.viewport.initialLiveParams +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the editor entry's session block (docs/format/UMA.md §7.4): what a session saves comes back, a session at + * its defaults writes nothing but nulls, the pose lists only the parameters away from their defaults and is + * clamped as it loads, and a member of the wrong shape is skipped rather than thrown over. + */ +class SessionStateJsonTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val model = + PuppetModel( + parameters = listOf(Parameter(angleX, "Angle X", -30f, 30f, 0f), Parameter(angleY, "Angle Y", -30f, 30f, 5f)), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ) + private val defaultPose = mapOf(angleX to 0f, angleY to 5f) + + @Test + fun aSessionAtItsDefaultsWritesOnlyNulls() { + val tree = sessionStateJson(SessionViewState(proportionalSettings = DEFAULT_PROPORTIONAL_EDIT_STATE), defaultPose, model) + + assertTrue(tree.values.all { value -> value is JsonNull }, "nothing deviates: $tree") + assertEquals(SessionViewState(), sessionViewStateOf(JsonObject(emptyMap())), "and an empty block reads as the defaults") + assertNull(sessionViewStateOf(null), "while no block at all is no saved state") + } + + @Test + fun everyMemberRoundTrips() { + val saved = + SessionViewState( + selection = + Selection( + linkedSetOf(SelectionTarget.Drawable(DrawableId("ArtMesh12")), SelectionTarget.Part(PartId("face")), SelectionTarget.Deformer(DeformerId("warp:1"))), + SelectionTarget.Part(PartId("face")), + ), + parameterSelection = ParameterSelection(linkedSetOf(angleX, angleY), angleY), + mode = EditorMode.Edit, + selectMode = MeshSelectMode.Edge, + cursor2d = Cursor2d(12.5f, -8f), + uvCursor = UvCursor(0.25f, 0.75f), + pivotMode = TransformPivotMode.IndividualOrigins, + proportionalEnabled = true, + proportionalSettings = ProportionalEditState(ProportionalFalloff.Linear, 64f, connectedOnly = true), + gridConfig = GridConfig(50f, 4), + ) + + val reopened = sessionViewStateOf(sessionStateJson(saved, defaultPose, model)) + + assertEquals(saved, reopened) + } + + /** An id holding a colon survives: the reference splits on its FIRST colon only. */ + @Test + fun anObjectReferenceKeepsAnIdWithAColon() { + val target = SelectionTarget.Deformer(DeformerId("art-0/lyid:12~1")) + + assertEquals(target, selectionTargetOf(objectReferenceOf(target))) + assertNull(selectionTargetOf("glue:3"), "a reference of no known kind names nothing") + } + + /** A disabled proportional configuration away from the default is still saved: a toggle brings it back. */ + @Test + fun aDisabledProportionalConfigurationIsSaved() { + val saved = SessionViewState(proportionalSettings = ProportionalEditState(ProportionalFalloff.Root, 48f)) + + val reopened = sessionViewStateOf(sessionStateJson(saved, defaultPose, model)) + + assertEquals(saved, reopened) + } + + @Test + fun thePoseListsOnlyDeviationsAndLoadsClamped() { + val tree = sessionStateJson(SessionViewState(), mapOf(angleX to 12.5f, angleY to 5f), model) + assertEquals(mapOf(angleX to 12.5f), savedPoseOf(tree), "a parameter at its default is not listed") + + val live = initialLiveParams(model, mapOf(angleX to 99f, ParameterId("ParamGone") to 1f)) + assertEquals(mapOf(angleX to 30f, angleY to 5f), live.values, "a saved value is clamped to its range, and an unknown id never matches") + assertEquals(defaultPose, initialLiveParams(model).values, "a plain open is every default") + } + + /** Every member the wrong shape: nothing throws, and the state is the defaults (UMA §7.1). */ + @Test + fun membersOfTheWrongShapeAreSkipped() { + val junk = + buildJsonObject { + put( + "pose", + buildJsonArray { + add(JsonPrimitive("ParamAngleX")) + add( + buildJsonObject { + put("parameter", 7) + put("value", "far") + }, + ) + }, + ) + put("selection", "everything") + put("parameterSelection", buildJsonObject { put("ids", 3) }) + put("mode", "sculpt") + put("selectMode", 2) + put("cursor2d", buildJsonArray { add(JsonPrimitive(1)) }) + put("uvCursor", "center") + put("pivot", "origin") + put( + "proportional", + buildJsonObject { + put("enabled", "yes") + put("falloff", "gaussian") + put("radius", -4) + }, + ) + put( + "grid", + buildJsonObject { + put("scale", 0) + put("subdivisions", 0) + }, + ) + } + + assertEquals(SessionViewState(proportionalSettings = DEFAULT_PROPORTIONAL_EDIT_STATE), sessionViewStateOf(junk)) + assertEquals(emptyMap(), savedPoseOf(junk)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/ShellCursorClaimTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/ShellCursorClaimTest.kt new file mode 100644 index 0000000..a6f02c9 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/ShellCursorClaimTest.kt @@ -0,0 +1,54 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The shell root's one window-wide cursor claim: which running mode the pointer shows, and which claims + * have to beat the cursors their descendants ask for. + * + * The resolver is the whole of the decision on purpose - the root then carries ONE permanent hover icon + * rather than mounting a modifier when a mode starts, because a hover icon that appears mid-gesture is + * not consulted until the pointer next moves, and text entry starts with a click the hand rests on. + */ +class ShellCursorClaimTest { + /** With nothing running the shell claims nothing, so every panel, splitter, and gizmo still decides. */ + @Test + fun withNoModeRunningTheShellClaimsNothing() { + val claim = shellCursorClaim(relationPickArmed = false, textEntryActive = false) + assertEquals(ShellCursorClaim.None, claim) + assertFalse(claim.overridesDescendants, "an empty claim must leave the descendants' cursors alone") + } + + /** An armed relation pick hides the OS pointer, because the shell draws the eyedropper itself. */ + @Test + fun anArmedRelationPickHidesThePointer() { + assertEquals(ShellCursorClaim.Hidden, shellCursorClaim(relationPickArmed = true, textEntryActive = false)) + } + + /** Live text entry shows the editor's I-beam, which is what makes the mode visible window-wide. */ + @Test + fun liveTextEntryShowsTheTextCursor() { + assertEquals(ShellCursorClaim.TextEdit, shellCursorClaim(relationPickArmed = false, textEntryActive = true)) + } + + /** + * A pick outranks text entry: the shell draws the eyedropper at the pointer, so an I-beam under it + * would read as two cursors at once. + */ + @Test + fun aPickOutranksTextEntry() { + assertEquals(ShellCursorClaim.Hidden, shellCursorClaim(relationPickArmed = true, textEntryActive = true)) + } + + /** Every real claim overrides its descendants - a mode a splitter edge could break is not a mode. */ + @Test + fun everyRealClaimOverridesItsDescendants() { + val claimed = ShellCursorClaim.entries.filter { claim -> claim != ShellCursorClaim.None } + claimed.forEach { claim -> + assertTrue(claim.overridesDescendants, "$claim must beat the cursors its descendants ask for") + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SplitterDragSessionTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SplitterDragSessionTest.kt new file mode 100644 index 0000000..7d73bc6 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SplitterDragSessionTest.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Verifies the drag-session accumulation over the pure boundary-drag math: deltas fold into one + * running total applied to the drag-start snapshot (so deltas arriving faster than recomposition can + * never be lost), overshoot past the clamp retraces exactly, and ownership tracking tells the + * session's own publishes apart from a foreign mid-drag rewrite. + */ +class SplitterDragSessionTest { + private val tolerance = 1e-3f + + /** A leaf hosting an arbitrary space; the id names the panel in assertions. */ + private fun leaf(id: String): LeafArea = LeafArea(id = id, space = SpaceKind.Outliner) + + /** A horizontal split (children side by side, the drag axis for every test tree). */ + private fun hsplit(ratio: Float, first: AreaNode, second: AreaNode): SplitNode = + SplitNode(SplitOrientation.Horizontal, ratio, first, second) + + /** + * The pixel extent of the named leaf inside [node], resolving nested weights against [axisPx] + * exactly the way SplitContainer's weighted Row does. Null when the leaf is not in the subtree. + * + * @param AreaNode node The subtree to search. + * @param String leafId The leaf whose on-axis extent is wanted. + * @param Float axisPx The subtree's extent along the drag axis, in pixels. + * @param Float splitterPx The divider bar thickness, in pixels. + * @return Float? The leaf's extent, or null when absent. + */ + private fun leafExtentPx(node: AreaNode, leafId: String, axisPx: Float, splitterPx: Float): Float? = + when (node) { + is LeafArea -> if (node.id == leafId) axisPx else null + is SplitNode -> { + val clampedRatio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + val usablePx = axisPx - splitterPx + leafExtentPx(node.first, leafId, clampedRatio * usablePx, splitterPx) + ?: leafExtentPx(node.second, leafId, (1f - clampedRatio) * usablePx, splitterPx) + } + } + + /** Three accumulated deltas land on the same tree as one dragSplitBoundary call with their sum. */ + @Test + fun accumulationMatchesSingleTotalDrag() { + val start = hsplit(0.5f, leaf("a"), leaf("b")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 50f, splitterPx = 0f) + session.accumulate(10f) + session.accumulate(10f) + val accumulated = session.accumulate(10f) + val direct = dragSplitBoundary(start, dragPx = 30f, axisPx = 1000f, minPx = 50f, splitterPx = 0f) + assertEquals(direct.ratio, accumulated.ratio, tolerance) + } + + /** + * Dragging far past the min clamp and then all the way back restores the starting extents - the + * property incremental per-delta application loses (a clamped-away delta would never be paid back). + */ + @Test + fun overshootRetracesExactly() { + val start = hsplit(0.5f, leaf("a"), leaf("b")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 100f, splitterPx = 0f) + val overshot = session.accumulate(1000f) + assertEquals(0.9f, overshot.ratio, tolerance) + val retraced = session.accumulate(-1000f) + assertEquals(start.ratio, retraced.ratio, tolerance) + assertEquals(500f, leafExtentPx(retraced, "a", 1000f, 0f)!!, tolerance) + assertEquals(500f, leafExtentPx(retraced, "b", 1000f, 0f)!!, tolerance) + } + + /** + * The session recognizes the snapshot and EVERY node it has published - recomposition may lag + * several publishes behind the pointer, so any of them can be the currently composed node. + */ + @Test + fun ownsNodeAcceptsSnapshotAndEveryPublish() { + val start = hsplit(0.5f, leaf("a"), leaf("b")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 50f, splitterPx = 0f) + val firstPublish = session.accumulate(10f) + val secondPublish = session.accumulate(10f) + assertTrue(session.ownsNode(start)) + assertTrue(session.ownsNode(firstPublish)) + assertTrue(session.ownsNode(secondPublish)) + } + + /** + * A structurally identical but distinct instance is NOT owned - it means something else rewrote + * the tree mid-drag and the caller must rebase. Ownership is identity, not equality, because the + * publishes are the exact instances handed to onNodeChange. + */ + @Test + fun ownsNodeRejectsForeignRewrite() { + val start = hsplit(0.5f, leaf("a"), leaf("b")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 50f, splitterPx = 0f) + session.accumulate(10f) + val foreign = start.copy() + assertFalse(session.ownsNode(foreign)) + } + + /** + * Cancelling rewinds to the drag-start snapshot exactly, however far the drag had travelled - the + * same snapshot-relative property [overshootRetracesExactly] relies on, so no state has to unwind. + */ + @Test + fun cancelRestoresTheStartingSplitExactly() { + val start = hsplit(0.5f, leaf("a"), leaf("b")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 100f, splitterPx = 0f) + session.accumulate(200f) + + val restored = session.cancel() + + assertEquals(start.ratio, restored.ratio, tolerance) + assertEquals(500f, leafExtentPx(restored, "a", 1000f, 0f)!!, tolerance) + assertTrue(session.isCancelled) + } + + /** + * The cancelled session still claims the restored snapshot as its own. It has to: the pointer is + * usually still down, and a session that disowned its own publish would let SplitContainer rebase a + * fresh one and silently resume the drag Escape just abandoned. + */ + @Test + fun aCancelledSessionStillOwnsTheRestoredNode() { + val start = hsplit(0.5f, leaf("a"), leaf("b")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 100f, splitterPx = 0f) + session.accumulate(200f) + + val restored = session.cancel() + + assertTrue(session.ownsNode(restored)) + } + + /** + * Accumulated deltas on the deep spine (((a | b) | c) | d) land exactly where one direct drag of + * the total does: far panels stay pixel-invariant and only the adjacent panel absorbs. + */ + @Test + fun deepSpineAccumulation() { + val start = hsplit(0.5f, hsplit(0.5f, hsplit(0.5f, leaf("a"), leaf("b")), leaf("c")), leaf("d")) + val session = SplitterDragSession(start, axisPx = 1000f, minPx = 48f, splitterPx = 0f) + session.accumulate(40f) + session.accumulate(35f) + val accumulated = session.accumulate(25f) + assertEquals(125f, leafExtentPx(accumulated, "a", 1000f, 0f)!!, tolerance) + assertEquals(125f, leafExtentPx(accumulated, "b", 1000f, 0f)!!, tolerance) + assertEquals(350f, leafExtentPx(accumulated, "c", 1000f, 0f)!!, tolerance) + assertEquals(400f, leafExtentPx(accumulated, "d", 1000f, 0f)!!, tolerance) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SplitterTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SplitterTest.kt new file mode 100644 index 0000000..edcae13 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/SplitterTest.kt @@ -0,0 +1,176 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** + * Verifies the pure boundary-drag math: a divider drag resizes ONLY its two adjacent panels (far + * panels are pixel-invariant through the spine compensation), the min-size and render-ratio clamps, + * and the no-op guards (unmeasured axis, degenerate geometry). Most cases use splitterPx = 0 for + * readable round numbers; one case proves exactness with the real 4px bar. + */ +class SplitterTest { + private val tolerance = 1e-3f + + /** A leaf hosting an arbitrary space; the id names the panel in assertions. */ + private fun leaf(id: String): LeafArea = LeafArea(id = id, space = SpaceKind.Outliner) + + /** A horizontal split (children side by side, the drag axis for every test tree). */ + private fun hsplit(ratio: Float, first: AreaNode, second: AreaNode): SplitNode = + SplitNode(SplitOrientation.Horizontal, ratio, first, second) + + /** + * The pixel extent of the named leaf inside [node], resolving nested weights against [axisPx] + * exactly the way SplitContainer's weighted Row does (each split distributes its extent minus + * splitterPx between the two ratio-weighted children). Null when the leaf is not in the subtree. + * + * @param AreaNode node The subtree to search. + * @param String leafId The leaf whose on-axis extent is wanted. + * @param Float axisPx The subtree's extent along the drag axis, in pixels. + * @param Float splitterPx The divider bar thickness, in pixels. + * @return Float? The leaf's extent, or null when absent. + */ + private fun leafExtentPx(node: AreaNode, leafId: String, axisPx: Float, splitterPx: Float): Float? = + when (node) { + is LeafArea -> if (node.id == leafId) axisPx else null + is SplitNode -> { + val clampedRatio = node.ratio.coerceIn(MIN_RATIO, 1f - MIN_RATIO) + val usablePx = axisPx - splitterPx + leafExtentPx(node.first, leafId, clampedRatio * usablePx, splitterPx) + ?: leafExtentPx(node.second, leafId, (1f - clampedRatio) * usablePx, splitterPx) + } + } + + /** + * A drag of +100px on a 1000px leaf-pair axis moves the ratio by +0.1 - the spine walk terminates + * immediately at the leaves, so a lone split behaves like a simple proportional ratio move. + */ + @Test + fun leafPairDragMovesRatioProportionally() { + val node = hsplit(0.5f, leaf("a"), leaf("b")) + val dragged = dragSplitBoundary(node, dragPx = 100f, axisPx = 1000f, minPx = 50f, splitterPx = 0f) + assertEquals(0.6f, dragged.ratio, tolerance) + } + + /** An overshooting drag pins the adjacent leaf at minPx on either side. */ + @Test + fun leafPairClampsToMinOnBothSides() { + val node = hsplit(0.5f, leaf("a"), leaf("b")) + // minPx 100 of 1000px usable: the first leaf pins at 100px (ratio 0.1) and 900px (ratio 0.9). + assertEquals(0.1f, dragSplitBoundary(node, -1000f, 1000f, 100f, 0f).ratio, tolerance) + assertEquals(0.9f, dragSplitBoundary(node, 1000f, 1000f, 100f, 0f).ratio, tolerance) + } + + /** Before the parent is measured (axisPx == 0) the node is returned untouched - no divide-by-zero. */ + @Test + fun zeroAxisIsNoOp() { + val node = hsplit(0.42f, leaf("a"), leaf("b")) + assertSame(node, dragSplitBoundary(node, 50f, 0f, 10f, 0f)) + } + + /** + * When the minimums cannot be satisfied at all (minPx over half the axis) the drag interval is + * empty and the node is returned untouched rather than snapped somewhere arbitrary. + */ + @Test + fun degenerateMinIsNoOp() { + val node = hsplit(0.3f, leaf("a"), leaf("b")) + assertSame(node, dragSplitBoundary(node, -200f, 1000f, 800f, 0f)) + } + + /** + * The reported bug shape: in ((left | center) | right) dragging the OUTER divider (between center + * and right) must not move the left column - the inner ratio counter-adjusts so center absorbs + * the full delta. + */ + @Test + fun outerDragKeepsFarLeftColumnFixed() { + val node = hsplit(0.5f, hsplit(0.5f, leaf("left"), leaf("center")), leaf("right")) + val dragged = dragSplitBoundary(node, dragPx = 100f, axisPx = 1000f, minPx = 48f, splitterPx = 0f) + assertEquals(0.6f, dragged.ratio, tolerance) + assertEquals(250f, leafExtentPx(dragged, "left", 1000f, 0f)!!, tolerance) + assertEquals(350f, leafExtentPx(dragged, "center", 1000f, 0f)!!, tolerance) + assertEquals(400f, leafExtentPx(dragged, "right", 1000f, 0f)!!, tolerance) + } + + /** The mirrored nesting (left | (center | right)): the outer drag must not move the right column. */ + @Test + fun outerDragKeepsFarRightColumnFixed() { + val node = hsplit(0.5f, leaf("left"), hsplit(0.5f, leaf("center"), leaf("right"))) + val dragged = dragSplitBoundary(node, dragPx = 100f, axisPx = 1000f, minPx = 48f, splitterPx = 0f) + assertEquals(0.6f, dragged.ratio, tolerance) + val innerSplit = dragged.second as SplitNode + assertEquals(0.375f, innerSplit.ratio, tolerance) + assertEquals(600f, leafExtentPx(dragged, "left", 1000f, 0f)!!, tolerance) + assertEquals(150f, leafExtentPx(dragged, "center", 1000f, 0f)!!, tolerance) + assertEquals(250f, leafExtentPx(dragged, "right", 1000f, 0f)!!, tolerance) + } + + /** + * Three same-axis levels (((a | b) | c) | d): dragging the outermost divider compensates every + * spine level, so both a and b keep their pixels and only c (the adjacent panel) absorbs. + */ + @Test + fun deepSpineCompensatesEveryLevel() { + val node = hsplit(0.5f, hsplit(0.5f, hsplit(0.5f, leaf("a"), leaf("b")), leaf("c")), leaf("d")) + val dragged = dragSplitBoundary(node, dragPx = 100f, axisPx = 1000f, minPx = 48f, splitterPx = 0f) + assertEquals(125f, leafExtentPx(dragged, "a", 1000f, 0f)!!, tolerance) + assertEquals(125f, leafExtentPx(dragged, "b", 1000f, 0f)!!, tolerance) + assertEquals(350f, leafExtentPx(dragged, "c", 1000f, 0f)!!, tolerance) + assertEquals(400f, leafExtentPx(dragged, "d", 1000f, 0f)!!, tolerance) + } + + /** + * A cross-orientation subtree beside the divider ends the spine walk: it scales as one unit along + * the drag axis (its children fill that axis), so it is returned as the SAME instance and only the + * dragged node's own ratio changes. + */ + @Test + fun crossOrientationSubtreeScalesAsUnit() { + val verticalStack = SplitNode(SplitOrientation.Vertical, 0.3f, leaf("top"), leaf("bottom")) + val node = hsplit(0.5f, verticalStack, leaf("right")) + val dragged = dragSplitBoundary(node, dragPx = 100f, axisPx = 1000f, minPx = 48f, splitterPx = 0f) + assertEquals(0.6f, dragged.ratio, tolerance) + assertSame(verticalStack, dragged.first) + } + + /** + * The min clamp binds on the ADJACENT panel (the inner center leaf), not on the dragged node's + * whole child subtree - and the far column stays pixel-invariant even at the clamp. + */ + @Test + fun clampRespectsAdjacentLeafMin() { + val node = hsplit(0.5f, hsplit(0.5f, leaf("left"), leaf("center")), leaf("right")) + // center is 250px; dragging left by 500px is clamped to -202px so center pins at minPx 48. + val dragged = dragSplitBoundary(node, dragPx = -500f, axisPx = 1000f, minPx = 48f, splitterPx = 0f) + assertEquals(48f, leafExtentPx(dragged, "center", 1000f, 0f)!!, tolerance) + assertEquals(250f, leafExtentPx(dragged, "left", 1000f, 0f)!!, tolerance) + } + + /** + * On a wide axis the pixel min alone would let a stored ratio fall below MIN_RATIO; the render + * clamp would then silently re-clamp it and break the invariance, so the drag bound keeps every + * stored ratio inside [MIN_RATIO, 1 - MIN_RATIO]. + */ + @Test + fun clampRespectsRenderMinRatio() { + val node = hsplit(0.5f, leaf("a"), leaf("b")) + // minPx 48 of 10000px would allow ratio 0.0048; the band clamp stops at MIN_RATIO instead. + val dragged = dragSplitBoundary(node, dragPx = -6000f, axisPx = 10000f, minPx = 48f, splitterPx = 0f) + assertEquals(MIN_RATIO, dragged.ratio, tolerance) + } + + /** + * With the real 4px divider bar each split distributes axisPx - 4 between its children; the + * compensation must use that usable extent or the far column drifts by a few pixels per drag. + */ + @Test + fun splitterThicknessIsExact() { + val splitterPx = 4f + val node = hsplit(0.5f, hsplit(0.5f, leaf("left"), leaf("center")), leaf("right")) + val leftBeforePx = leafExtentPx(node, "left", 1000f, splitterPx)!! + val dragged = dragSplitBoundary(node, dragPx = 100f, axisPx = 1000f, minPx = 48f, splitterPx = splitterPx) + assertEquals(leftBeforePx, leafExtentPx(dragged, "left", 1000f, splitterPx)!!, tolerance) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/StatusBarStatsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/StatusBarStatsTest.kt new file mode 100644 index 0000000..26323d9 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/StatusBarStatsTest.kt @@ -0,0 +1,110 @@ +package org.umamo.ui.workspace + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the status bar's pure mesh-stat derivations: whole-model totals skip meshless drawables, and + * selection totals count directly selected drawables, expand selected parts to their nested + * descendants, and ignore deformer targets. + */ +class StatusBarStatsTest { + /** + * A drawable with a mesh of [triangleCount] triangle-fan triangles ([triangleCount] + 2 vertices), + * or no mesh at all when [triangleCount] is null. + * + * @param String id The drawable id (doubles as its name). + * @param Int? triangleCount The triangle count, or null for a meshless drawable. + * @return Drawable The fixture drawable. + */ + private fun drawable(id: String, triangleCount: Int?): Drawable { + val mesh = + triangleCount?.let { count -> + val vertexCount = count + 2 + DrawableMesh( + positions = FloatArray(vertexCount * 2), + uvs = FloatArray(vertexCount * 2), + indices = IntArray(count * 3) { indexSlot -> indexSlot % vertexCount }, + ) + } + return Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = mesh, + geometryGrid = null, + ) + } + + /** + * A model with [drawables] at the root plus one part ("bag") nesting a sub-part ("bagInner") that + * owns the "nested" drawable - the shape the part-expansion walk must traverse. + * + * @param List drawables The root drawables. + * @return PuppetModel The fixture model. + */ + private fun model(drawables: List): PuppetModel { + val nested = drawable("nested", triangleCount = 4) + val innerPart = Part(PartId("bagInner"), "Bag Inner", listOf(OrgChild.Drawable(nested.id))) + val outerPart = Part(PartId("bag"), "Bag", listOf(OrgChild.Part(innerPart.id))) + return PuppetModel( + parameters = emptyList(), + parts = listOf(outerPart, innerPart), + deformers = emptyList(), + drawables = drawables + nested, + rootChildren = drawables.map { rootDrawable -> OrgChild.Drawable(rootDrawable.id) } + OrgChild.Part(outerPart.id), + rootPartId = null, + ) + } + + /** Whole-model totals sum every mesh and skip meshless drawables. */ + @Test + fun meshTotalsSkipMeshlessDrawables() { + val puppet = model(listOf(drawable("face", triangleCount = 10), drawable("anchor", triangleCount = null))) + // face: 10 tris / 12 verts; anchor: no mesh; nested: 4 tris / 6 verts. + assertEquals(MeshTotals(vertexCount = 18, triangleCount = 14), meshTotals(puppet)) + } + + /** A directly selected drawable contributes exactly its own mesh. */ + @Test + fun selectedTotalsCountDirectDrawable() { + val puppet = model(listOf(drawable("face", triangleCount = 10))) + val selection = Selection(targets = setOf(SelectionTarget.Drawable(DrawableId("face")))) + assertEquals(MeshTotals(vertexCount = 12, triangleCount = 10), selectedMeshTotals(puppet, selection)) + } + + /** A selected part expands to its nested descendants (through sub-parts). */ + @Test + fun selectedTotalsExpandPartToNestedDescendants() { + val puppet = model(listOf(drawable("face", triangleCount = 10))) + val selection = Selection(targets = setOf(SelectionTarget.Part(PartId("bag")))) + assertEquals(MeshTotals(vertexCount = 6, triangleCount = 4), selectedMeshTotals(puppet, selection)) + } + + /** Deformer targets contribute nothing (influence is not containment). */ + @Test + fun selectedTotalsIgnoreDeformerTargets() { + val puppet = model(listOf(drawable("face", triangleCount = 10))) + val selection = + Selection( + targets = + setOf( + SelectionTarget.Deformer(org.umamo.runtime.model.DeformerId("warp1")), + SelectionTarget.Drawable(DrawableId("face")), + ), + ) + assertEquals(MeshTotals(vertexCount = 12, triangleCount = 10), selectedMeshTotals(puppet, selection)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/StatusHintsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/StatusHintsTest.kt new file mode 100644 index 0000000..bd6b944 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/StatusHintsTest.kt @@ -0,0 +1,196 @@ +package org.umamo.ui.workspace + +import org.jetbrains.compose.resources.StringResource +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.action.CommandHint +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.parseKeyChord +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.status_bind_delete_key +import org.umamo.ui.resources.status_bind_edit_mode +import org.umamo.ui.resources.status_bind_grab +import org.umamo.ui.resources.status_bind_insert_key +import org.umamo.ui.resources.status_bind_pin +import org.umamo.ui.resources.status_bind_scale +import org.umamo.ui.resources.status_bind_visibility +import org.umamo.ui.resources.status_select_mode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins how the status bar's suggestions are derived from the command declarations: which commands are + * suggested over which space, in what order, and how commands sharing a label become one entry. + */ +class StatusHintsTest { + /** + * A hinted command that does nothing. + * + * @param String id The command id. + * @param StringResource? hint The status label, or null for a command that is never suggested. + * @param CommandSpaces spaces The spaces it belongs to. + * @param Boolean available Whether it currently applies. + * @param Boolean suggested Whether its hint is worth suggesting right now, on top of being available. + * @return Command The command. + */ + private fun command( + id: String, + hint: StringResource?, + spaces: CommandSpaces = CommandSpaces.Everywhere, + available: Boolean = true, + suggested: Boolean = true, + ): Command = + Command( + id, + title = null, + availability = CommandAvailability { available }, + spaces = spaces, + hint = hint?.let { label -> CommandHint(label, suggestedWhen = CommandAvailability { suggested }) }, + handler = {}, + ) + + /** + * A keymap over chord-spec to command-id pairs. + * + * @param Pair bindings Each chord spec ("KeyG") with the command id it reaches. + * @return Keymap The keymap holding exactly those bindings. + */ + private fun keymap(vararg bindings: Pair): Keymap = Keymap.fromSpecs(bindings.toMap()) + + /** + * The labels of these suggestions, in order - what most cases below compare. + * + * @return List The suggestion labels. + */ + private fun List.labels(): List = map { hint -> hint.label } + + /** Only a command carrying a hint is ever suggested. */ + @Test + fun aCommandWithoutAHintIsNeverSuggested() { + val commands = listOf(command("test.plain", hint = null), command("test.hinted", hint = Res.string.status_bind_grab)) + val hints = statusHintsFor(commands, keymap("KeyA" to "test.plain", "KeyG" to "test.hinted"), SpaceKind.Viewport2D) + + assertEquals(listOf(Res.string.status_bind_grab), hints.labels()) + } + + /** A scoped command is suggested inside its spaces and nowhere else - the point of deriving from the hovered space. */ + @Test + fun aScopedCommandIsSuggestedOnlyInItsSpaces() { + val commands = listOf(command("test.pin", hint = Res.string.status_bind_pin, spaces = CommandSpaces.UvEditor)) + val bindings = keymap("KeyP" to "test.pin") + + assertEquals(listOf(Res.string.status_bind_pin), statusHintsFor(commands, bindings, SpaceKind.UvEditor).labels()) + assertTrue(statusHintsFor(commands, bindings, SpaceKind.Viewport2D).isEmpty()) + assertTrue(statusHintsFor(commands, bindings, null).isEmpty(), "and not before the pointer has touched a surface") + } + + /** An unavailable command is not suggested, whatever space it belongs to. */ + @Test + fun anUnavailableCommandIsNotSuggested() { + val commands = listOf(command("test.grab", hint = Res.string.status_bind_grab, available = false)) + + assertTrue(statusHintsFor(commands, keymap("KeyG" to "test.grab"), SpaceKind.Viewport2D).isEmpty()) + } + + /** + * An available command whose hint is not worth suggesting right now stays off the bar - how Tab is + * bound and runs in Edit mode while the bar suggests it only from Object mode. + */ + @Test + fun anAvailableCommandWhoseHintIsNotSuggestedStaysOffTheBar() { + val commands = listOf(command("test.editMode", hint = Res.string.status_bind_edit_mode, suggested = false)) + + assertTrue(statusHintsFor(commands, keymap("Tab" to "test.editMode"), SpaceKind.Viewport2D).isEmpty()) + } + + /** An unbound command is omitted, so the strip never advertises a key that does nothing. */ + @Test + fun anUnboundCommandIsNotSuggested() { + val commands = listOf(command("test.grab", hint = Res.string.status_bind_grab)) + + assertTrue(statusHintsFor(commands, keymap(), SpaceKind.Viewport2D).isEmpty()) + } + + /** + * What is specific to the hovered space leads, then what belongs everywhere - each tier in + * registration order, even when the global command was registered first. + */ + @Test + fun scopedSuggestionsLeadAndEachTierKeepsRegistrationOrder() { + val commands = + listOf( + command("test.editMode", hint = Res.string.status_bind_edit_mode), + command("test.grab", hint = Res.string.status_bind_grab, spaces = CommandSpaces.WorkSurfaces), + command("test.visibility", hint = Res.string.status_bind_visibility), + command("test.scale", hint = Res.string.status_bind_scale, spaces = CommandSpaces.WorkSurfaces), + ) + val bindings = keymap("Tab" to "test.editMode", "KeyG" to "test.grab", "KeyH" to "test.visibility", "KeyS" to "test.scale") + + assertEquals( + listOf(Res.string.status_bind_grab, Res.string.status_bind_scale, Res.string.status_bind_edit_mode, Res.string.status_bind_visibility), + statusHintsFor(commands, bindings, SpaceKind.Viewport2D).labels(), + ) + } + + /** Commands sharing one label are one entry carrying every chord, in registration order ("1/2/3 Select Mode"). */ + @Test + fun commandsSharingALabelMergeIntoOneEntry() { + val commands = + listOf( + command("test.vertex", hint = Res.string.status_select_mode), + command("test.edge", hint = Res.string.status_select_mode), + command("test.face", hint = Res.string.status_select_mode), + ) + val hints = statusHintsFor(commands, keymap("Digit1" to "test.vertex", "Digit2" to "test.edge", "Digit3" to "test.face"), SpaceKind.Viewport2D) + + assertEquals(1, hints.size) + assertEquals(listOf(parseKeyChord("Digit1"), parseKeyChord("Digit2"), parseKeyChord("Digit3")), hints.single().chords) + } + + /** A group with any member unbound is dropped whole: "1/3 Select Mode" would misread as the full set. */ + @Test + fun aPartiallyBoundGroupIsDroppedWhole() { + val commands = + listOf( + command("test.vertex", hint = Res.string.status_select_mode), + command("test.edge", hint = Res.string.status_select_mode), + command("test.face", hint = Res.string.status_select_mode), + ) + + assertTrue(statusHintsFor(commands, keymap("Digit1" to "test.vertex", "Digit3" to "test.face"), SpaceKind.Viewport2D).isEmpty()) + } + + /** The chord always comes from the keymap handed in, so a rebind is reflected with no other change. */ + @Test + fun aRebindIsReflected() { + val commands = listOf(command("test.grab", hint = Res.string.status_bind_grab)) + + assertEquals(listOf(parseKeyChord("KeyG")), statusHintsFor(commands, keymap("KeyG" to "test.grab"), SpaceKind.Viewport2D).single().chords) + assertEquals(listOf(parseKeyChord("KeyM")), statusHintsFor(commands, keymap("KeyM" to "test.grab"), SpaceKind.Viewport2D).single().chords) + } + + /** The list is cut at the limit, keeping the leading entries - the space-specific ones. */ + @Test + fun theListIsCutAtTheLimitKeepingTheLeadingEntries() { + val labels = + listOf( + Res.string.status_bind_grab, + Res.string.status_bind_scale, + Res.string.status_bind_pin, + Res.string.status_bind_edit_mode, + Res.string.status_bind_visibility, + Res.string.status_select_mode, + Res.string.status_bind_insert_key, + Res.string.status_bind_delete_key, + ) + val commands = labels.mapIndexed { labelIndex, label -> command("test.command$labelIndex", hint = label) } + val bindings = Keymap.fromSpecs(labels.indices.associate { labelIndex -> "F${labelIndex + 1}" to "test.command$labelIndex" }) + + val hints = statusHintsFor(commands, bindings, SpaceKind.Viewport2D) + + assertEquals(STATUS_HINT_LIMIT, hints.size) + assertEquals(labels.take(STATUS_HINT_LIMIT), hints.labels()) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/TextEntryReleaseTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/TextEntryReleaseTest.kt new file mode 100644 index 0000000..af03821 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/TextEntryReleaseTest.kt @@ -0,0 +1,68 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * When a finished press ends text entry and hands the keyboard back to the shell root. + * + * The bug behind the rule: a header filter kept focus for as long as the document stayed open, so undo + * and every other shortcut went quietly dead the moment someone typed in one. + */ +class TextEntryReleaseTest { + /** With no editor live there is nothing to release, wherever the press landed. */ + @Test + fun noEditorLiveReleasesNothing() { + listOf(true, false).forEach { onEditor -> + assertFalse( + shouldReleaseTextEntry( + textEntryActive = false, + pressLandedOnTextEditor = onEditor, + selfFocusedOverlayOpen = false, + ), + "no text entry is live, so a press (onEditor=$onEditor) has nothing to end", + ) + } + } + + /** A press on the field itself is a caret move, not a way out of it. */ + @Test + fun aPressOnTheEditorItselfKeepsTextEntry() { + assertFalse( + shouldReleaseTextEntry( + textEntryActive = true, + pressLandedOnTextEditor = true, + selfFocusedOverlayOpen = false, + ), + ) + } + + /** A press anywhere else ends text entry - Blender's rule, and the whole point of the session. */ + @Test + fun aPressElsewhereReleases() { + assertTrue( + shouldReleaseTextEntry( + textEntryActive = true, + pressLandedOnTextEditor = false, + selfFocusedOverlayOpen = false, + ), + ) + } + + /** + * An overlay that owns its own focus keeps it. The modal ladder has already stood the root's + * shortcuts down while one is open, so a release would hand the keyboard to a root that refuses to + * use it - and the command palette keeps its list navigation on an ancestor of its own search field. + */ + @Test + fun aSelfFocusedOverlayNeverReleases() { + assertFalse( + shouldReleaseTextEntry( + textEntryActive = true, + pressLandedOnTextEditor = false, + selfFocusedOverlayOpen = true, + ), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceLayoutFilesTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceLayoutFilesTest.kt new file mode 100644 index 0000000..de2aaad --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceLayoutFilesTest.kt @@ -0,0 +1,118 @@ +package org.umamo.ui.workspace + +import io.github.vinceglb.filekit.PlatformFile +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.settings.Settings +import org.umamo.storage.FilePicker +import org.umamo.storage.OkioAppStorage +import org.umamo.ui.action.CommandRegistry +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull + +/** + * Pins what a workspace export writes when the layout on screen is newer than the one in settings. + * + * Layout edits reach settings through a debounce, so for a moment after a split the saved layout is the + * one from before it. An export pressed in that moment must still write the layout the rigger is looking + * at - and must get there through the debounce's own pacer, so its rules hold: nothing is written while a + * splitter drag is held. + */ +class WorkspaceLayoutFilesTest { + /** Minimal defaults: the empty interface.layout baseline that triggers seeding. */ + private val defaultJson = """{"interface":{"layout":{"workspaces":[]}},"localization":{"locale":"en"}}""" + + /** + * The shell's wiring in miniature: settings, the live layout, the pacer that writes it, and the file + * commands' collaborator committing through that pacer. + */ + private class Fixture(defaultJson: String) { + val settings: Settings + + /** The layout on screen, which the debounce has not necessarily written yet. */ + var latestLayout: InterfaceLayout + + val pacer: LayoutSavePacer + + val files: WorkspaceLayoutFiles + + init { + val fileSystem = FakeFileSystem() + val configDirectory = "/config".toPath() + fileSystem.createDirectories(configDirectory) + settings = Settings.load(OkioAppStorage(fileSystem, configDirectory, "/data".toPath()), defaultJson) + latestLayout = loadLayout(settings) + pacer = LayoutSavePacer(latestLayout) { layout -> saveLayout(settings, layout) } + files = WorkspaceLayoutFiles(settings, CancelledFilePicker, CoroutineScope(Job()), CommandRegistry()) { pacer.saveDebounced(latestLayout) } + } + + /** + * Splits the active workspace's first area on screen, without the debounce having fired. + * + * @return InterfaceLayout The layout now on screen. + */ + fun splitOnScreen(): InterfaceLayout { + val root = assertNotNull(latestLayout.activeWorkspace()).root + val split = latestLayout.withActiveRoot(reduce(root, AreaCommand.SplitArea(firstLeaf(root).id, SplitOrientation.Vertical))) + assertNotEquals(latestLayout, split, "the split must change the tree") + latestLayout = split + return split + } + + /** + * The first leaf of a tree, reached down the leading children. + * + * @param AreaNode node The tree to descend. + * @return LeafArea The first leaf. + */ + private fun firstLeaf(node: AreaNode): LeafArea = + when (node) { + is LeafArea -> node + is SplitNode -> firstLeaf(node.first) + } + } + + @Test + fun anExportWritesTheLayoutOnScreenNotTheOneTheDebounceHasYetToSave() { + val fixture = Fixture(defaultJson) + val seeded = fixture.latestLayout + val split = fixture.splitOnScreen() + assertEquals(seeded, decodeLayoutText(assertNotNull(exportLayoutText(fixture.settings))), "settings still hold the layout from before the split") + + val exported = decodeLayoutText(assertNotNull(fixture.files.allWorkspacesText())) + + assertEquals(split, exported, "the file is the layout on screen") + assertEquals(split, loadLayout(fixture.settings), "because the export committed it, which the debounce was about to do anyway") + } + + @Test + fun exportingOneWorkspaceWritesItAsItIsOnScreenToo() { + val fixture = Fixture(defaultJson) + val split = fixture.splitOnScreen() + + assertEquals(split.activeWorkspace(), fixture.files.activeWorkspaceToExport()) + } + + @Test + fun anExportNeverWritesALayoutHeldByASplitterDrag() { + val fixture = Fixture(defaultJson) + val seeded = fixture.latestLayout + fixture.pacer.setDragActive(true, seeded) + fixture.splitOnScreen() + + val exported = decodeLayoutText(assertNotNull(fixture.files.allWorkspacesText())) + + assertEquals(seeded, exported, "a drag in flight holds every write, an export's included; its release commits the layout") + } +} + +/** A picker whose every dialog is cancelled: these cases stop before a file. */ +private object CancelledFilePicker : FilePicker { + override suspend fun openFile(extensions: List): PlatformFile? = null + + override suspend fun saveFile(suggestedName: String, extension: String): PlatformFile? = null +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceListTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceListTest.kt new file mode 100644 index 0000000..e015bce --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceListTest.kt @@ -0,0 +1,160 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertSame + +/** + * Verifies the workspace-list operations behind the tab strip's create / duplicate / delete / reorder / + * navigate features: the pure [InterfaceLayout] transforms (shift, insert, remove, reorder), the + * fresh-id clone and unique-name helpers, and the drag-reorder index math. These are the off-by-one and + * edge-case prone bits (wraparound, refusing the last workspace, active reassignment), kept pure so they + * are tested without a composition. + */ +class WorkspaceListTest { + /** A workspace with a single viewport leaf, for terse fixtures. */ + private fun workspace(id: String, name: String? = null): Workspace = + Workspace(id = id, root = LeafArea("leaf-$id", SpaceKind.Viewport2D), name = name) + + /** A three-workspace layout (a, b, c) with [activeId] active. */ + private fun threeWorkspaces(activeId: String): InterfaceLayout = + InterfaceLayout( + activeWorkspaceId = activeId, + workspaces = listOf(workspace("a"), workspace("b"), workspace("c")), + ) + + @Test + fun shiftActiveWrapsBothWays() { + val layout = threeWorkspaces("a") + assertEquals("b", layout.withActiveShiftedBy(1).activeWorkspaceId) + // Previous from the first tab wraps to the last. + assertEquals("c", layout.withActiveShiftedBy(-1).activeWorkspaceId) + // Next from the last tab wraps to the first. + assertEquals("a", threeWorkspaces("c").withActiveShiftedBy(1).activeWorkspaceId) + } + + @Test + fun shiftActiveOnEmptyIsNoOp() { + val empty = InterfaceLayout(activeWorkspaceId = "x", workspaces = emptyList()) + assertSame(empty, empty.withActiveShiftedBy(1)) + } + + @Test + fun insertPlacesAndActivates() { + val layout = threeWorkspaces("a") + val inserted = layout.withWorkspaceInserted(workspace("z"), atIndex = 1, activate = true) + assertEquals(listOf("a", "z", "b", "c"), inserted.workspaces.map { workspace -> workspace.id }) + assertEquals("z", inserted.activeWorkspaceId) + } + + @Test + fun insertWithoutActivateKeepsActive() { + val layout = threeWorkspaces("a") + val inserted = layout.withWorkspaceInserted(workspace("z"), atIndex = 99, activate = false) + // Index is clamped to the end, and the active selection is untouched. + assertEquals(listOf("a", "b", "c", "z"), inserted.workspaces.map { workspace -> workspace.id }) + assertEquals("a", inserted.activeWorkspaceId) + } + + @Test + fun removeActiveReassignsToSlot() { + // Removing the active middle tab moves active to the tab that slides into its slot. + val removed = threeWorkspaces("b").withWorkspaceRemoved("b") + assertEquals(listOf("a", "c"), removed.workspaces.map { workspace -> workspace.id }) + assertEquals("c", removed.activeWorkspaceId) + } + + @Test + fun removeActiveLastReassignsToNewLast() { + val removed = threeWorkspaces("c").withWorkspaceRemoved("c") + assertEquals("b", removed.activeWorkspaceId) + } + + @Test + fun removeNonActiveKeepsActive() { + val removed = threeWorkspaces("a").withWorkspaceRemoved("c") + assertEquals("a", removed.activeWorkspaceId) + assertEquals(listOf("a", "b"), removed.workspaces.map { workspace -> workspace.id }) + } + + @Test + fun removeLastWorkspaceIsRefused() { + val single = InterfaceLayout(activeWorkspaceId = "a", workspaces = listOf(workspace("a"))) + assertSame(single, single.withWorkspaceRemoved("a")) + } + + @Test + fun reorderMovesItemAndKeepsActive() { + val layout = threeWorkspaces("a") + assertEquals(listOf("b", "a", "c"), layout.withWorkspacesReordered(0, 1).workspaces.map { workspace -> workspace.id }) + assertEquals(listOf("b", "c", "a"), layout.withWorkspacesReordered(0, 2).workspaces.map { workspace -> workspace.id }) + assertEquals(listOf("c", "a", "b"), layout.withWorkspacesReordered(2, 0).workspaces.map { workspace -> workspace.id }) + // Reordering never changes which workspace is active. + assertEquals("a", layout.withWorkspacesReordered(0, 2).activeWorkspaceId) + } + + @Test + fun reorderOutOfRangeIsNoOp() { + val layout = threeWorkspaces("a") + assertSame(layout, layout.withWorkspacesReordered(5, 0)) + } + + @Test + fun renameSetsOnlyTargetName() { + val renamed = threeWorkspaces("a").withWorkspaceRenamed("b", "Faces") + assertEquals("Faces", renamed.workspaces.first { workspace -> workspace.id == "b" }.name) + assertNull(renamed.workspaces.first { workspace -> workspace.id == "a" }.name, "other names are untouched") + } + + @Test + fun renameUnknownIdIsNoOp() { + val layout = threeWorkspaces("a") + assertEquals(layout, layout.withWorkspaceRenamed("zzz", "Nope")) + } + + @Test + fun cloneAreaTreeMintsFreshLeafIdsAndPreservesShape() { + val original = + SplitNode( + orientation = SplitOrientation.Horizontal, + ratio = 0.4f, + first = LeafArea("a", SpaceKind.UvEditor), + second = LeafArea("b", SpaceKind.Viewport2D), + ) + val clone = cloneAreaTree(original) as SplitNode + + assertEquals(original.orientation, clone.orientation) + assertEquals(original.ratio, clone.ratio) + val originalFirst = original.first as LeafArea + val cloneFirst = clone.first as LeafArea + assertEquals(originalFirst.space, cloneFirst.space, "the space kind is preserved") + assertNotEquals(originalFirst.id, cloneFirst.id, "the leaf id is freshly minted, never shared") + assertNotEquals((original.second as LeafArea).id, (clone.second as LeafArea).id) + } + + @Test + fun uniqueWorkspaceNameAppendsLowestFreeSuffix() { + val existing = listOf(workspace("a", name = "Workspace"), workspace("b", name = "Workspace 2")) + assertEquals("Workspace 3", uniqueWorkspaceName("Workspace", existing)) + assertEquals("Texture", uniqueWorkspaceName("Texture", existing), "a free name is returned unchanged") + } + + @Test + fun reorderTargetIndexCountsNeighborsLeftOfProjectedCenter() { + // Three tabs centered at 50, 150, 250 (width 100). Drag the first far enough right to pass tab b. + val centers = listOf(50f, 150f, 250f) + assertEquals(0, reorderTargetIndex(fromIndex = 0, dragDeltaX = 0f, centers = centers)) + assertEquals(1, reorderTargetIndex(fromIndex = 0, dragDeltaX = 120f, centers = centers)) + assertEquals(2, reorderTargetIndex(fromIndex = 0, dragDeltaX = 220f, centers = centers)) + // Drag the last tab left past both neighbors. + assertEquals(0, reorderTargetIndex(fromIndex = 2, dragDeltaX = -220f, centers = centers)) + } + + @Test + fun reorderTargetIndexWithUnmeasuredCenterIsNoOp() { + val centers = listOf(null, null) + assertEquals(0, reorderTargetIndex(fromIndex = 0, dragDeltaX = 500f, centers = centers)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceModelTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceModelTest.kt new file mode 100644 index 0000000..de2dc8f --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/WorkspaceModelTest.kt @@ -0,0 +1,371 @@ +package org.umamo.ui.workspace + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Verifies the area-tree data model: recursive sealed-tree serialization round-trips (the trickiest + * serialization risk), and the reducer's structural edits (split keeps id, switch keeps id, close + * collapses, sole-leaf close is refused). + */ +class WorkspaceModelTest { + /** + * The seeded default layout encodes to JSON and decodes back equal - proves the polymorphic + * SplitNode/LeafArea discriminator + SpaceKind-by-key serialization round-trip. + */ + @Test + fun defaultLayoutRoundTrips() { + val layout = defaultLayout() + val decoded = decodeLayout(encodeLayout(layout)) + assertEquals(layout, decoded) + } + + /** + * A deliberately deep (3-level) nested tree round-trips structurally, exercising recursion on both + * split children. + */ + @Test + fun deepNestedTreeRoundTrips() { + val deep = + InterfaceLayout( + activeWorkspaceId = "w", + workspaces = + listOf( + Workspace( + id = "w", + root = + SplitNode( + SplitOrientation.Horizontal, + 0.4f, + LeafArea("a", SpaceKind.Outliner), + SplitNode( + SplitOrientation.Vertical, + 0.7f, + LeafArea("b", SpaceKind.Viewport2D), + SplitNode( + SplitOrientation.Horizontal, + 0.25f, + LeafArea("c", SpaceKind.Parameters), + LeafArea("d", SpaceKind.Properties), + ), + ), + ), + ), + ), + ) + assertEquals(deep, decodeLayout(encodeLayout(deep))) + } + + /** + * An unknown space key decodes to the neutral Outliner fallback rather than failing the layout. + */ + @Test + fun unknownSpaceKeyFallsBackToOutliner() { + val json = """{"activeWorkspaceId":"w","workspaces":[{"id":"w","root":{"type":"leaf","id":"a","space":"hologram"}}]}""" + val decoded = decodeLayout(LayoutJson.parseToJsonElement(json))!! + val leaf = decoded.workspaces.single().root as LeafArea + assertEquals(SpaceKind.Outliner, leaf.space) + } + + /** + * An empty workspace list decodes to null - the "seed defaults" signal. + */ + @Test + fun emptyLayoutDecodesToNull() { + val json = """{"activeWorkspaceId":"x","workspaces":[]}""" + assertNull(decodeLayout(LayoutJson.parseToJsonElement(json))) + } + + /** + * Splitting a leaf keeps that leaf's id on one side and mints a different id for the new sibling, + * which inherits the original space. + */ + @Test + fun splitKeepsIdAndInheritsSpace() { + val root = LeafArea("a", SpaceKind.Viewport2D) + val result = reduce(root, AreaCommand.SplitArea("a", SplitOrientation.Vertical)) as SplitNode + + val original = result.first as LeafArea + val created = result.second as LeafArea + assertEquals("a", original.id, "the original leaf keeps its id") + assertNotEquals("a", created.id, "the new sibling gets a fresh id") + assertEquals(SpaceKind.Viewport2D, created.space, "the new sibling inherits the space") + assertEquals(SplitOrientation.Vertical, result.orientation) + } + + /** + * Splitting with an explicit ratio places the divider at that fraction (a corner-drag split lands the + * divider under the cursor rather than at the 50/50 default). + */ + @Test + fun splitHonoursExplicitRatio() { + val root = LeafArea("a", SpaceKind.Viewport2D) + val result = reduce(root, AreaCommand.SplitArea("a", SplitOrientation.Horizontal, 0.3f)) as SplitNode + assertEquals(0.3f, result.ratio) + assertEquals("a", (result.first as LeafArea).id, "the original keeps its id on the first side") + } + + /** + * Switching a leaf's space keeps its id. + */ + @Test + fun switchSpaceKeepsId() { + val root = LeafArea("a", SpaceKind.Viewport2D) + val result = reduce(root, AreaCommand.SwitchSpace("a", SpaceKind.Properties)) as LeafArea + assertEquals("a", result.id) + assertEquals(SpaceKind.Properties, result.space) + } + + /** + * Closing a leaf collapses its parent split into the surviving sibling, preserving nesting elsewhere. + */ + @Test + fun closeCollapsesParentSplit() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("a", SpaceKind.Outliner), + SplitNode( + SplitOrientation.Vertical, + 0.5f, + LeafArea("b", SpaceKind.Viewport2D), + LeafArea("c", SpaceKind.Parameters), + ), + ) + // Close "b": its parent (the inner vertical split) collapses to "c". + val result = reduce(root, AreaCommand.CloseArea("b")) as SplitNode + assertEquals(LeafArea("a", SpaceKind.Outliner), result.first) + assertEquals(LeafArea("c", SpaceKind.Parameters), result.second) + } + + /** + * Closing the sole leaf of a workspace is refused (a workspace must keep at least one area). + */ + @Test + fun closingSoleLeafIsNoOp() { + val root = LeafArea("a", SpaceKind.Viewport2D) + assertEquals(root, reduce(root, AreaCommand.CloseArea("a"))) + } + + /** + * Joining two direct-sibling leaves collapses their parent split to the survivor, keeping its id and + * space and discarding the consumed sibling. + */ + @Test + fun joinDirectSiblingsCollapsesToSurvivor() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("a", SpaceKind.Viewport2D), + LeafArea("b", SpaceKind.Properties), + ) + // "a" survives and consumes its sibling "b": the split collapses to just "a". + assertEquals(LeafArea("a", SpaceKind.Viewport2D), reduce(root, AreaCommand.JoinAreas("a", "b"))) + } + + /** + * The survivor - not the first/second position - decides who remains: joining with "b" as survivor + * keeps "b". + */ + @Test + fun joinHonoursSurvivorRegardlessOfPosition() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("a", SpaceKind.Viewport2D), + LeafArea("b", SpaceKind.Properties), + ) + assertEquals(LeafArea("b", SpaceKind.Properties), reduce(root, AreaCommand.JoinAreas("b", "a"))) + } + + /** + * Joining a nested pair collapses only their split and preserves unrelated nesting around it. + */ + @Test + fun joinPreservesUnrelatedNesting() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("a", SpaceKind.Outliner), + SplitNode( + SplitOrientation.Vertical, + 0.5f, + LeafArea("b", SpaceKind.Viewport2D), + LeafArea("c", SpaceKind.Parameters), + ), + ) + // Join "b"+"c": the inner split collapses to "b"; the outer split and "a" are untouched. + val result = reduce(root, AreaCommand.JoinAreas("b", "c")) as SplitNode + assertEquals(LeafArea("a", SpaceKind.Outliner), result.first) + assertEquals(LeafArea("b", SpaceKind.Viewport2D), result.second) + } + + /** + * Joining two leaves that are not direct siblings (different parents) is a no-op. + */ + @Test + fun joinNonSiblingsIsNoOp() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("a", SpaceKind.Outliner), + SplitNode( + SplitOrientation.Vertical, + 0.5f, + LeafArea("b", SpaceKind.Viewport2D), + LeafArea("c", SpaceKind.Parameters), + ), + ) + // "a" and "b" are not direct siblings (a's sibling is the inner split, not b). + assertEquals(root, reduce(root, AreaCommand.JoinAreas("a", "b"))) + } + + /** + * Joining a leaf with itself is a no-op (no self-consume). + */ + @Test + fun joinSameIdIsNoOp() { + val root = SplitNode(SplitOrientation.Horizontal, 0.5f, LeafArea("a", SpaceKind.Outliner), LeafArea("b", SpaceKind.Properties)) + assertEquals(root, reduce(root, AreaCommand.JoinAreas("a", "a"))) + } + + /** + * Joining against an unknown id leaves the tree unchanged. + */ + @Test + fun joinUnknownIdIsNoOp() { + val root = SplitNode(SplitOrientation.Horizontal, 0.5f, LeafArea("a", SpaceKind.Outliner), LeafArea("b", SpaceKind.Properties)) + assertEquals(root, reduce(root, AreaCommand.JoinAreas("a", "zzz"))) + } + + /** + * Docking a leaf to the bottom edge lifts it out (its column heals to the sibling) and re-inserts it as + * a full-width bottom strip, with the remainder leading and the area count preserved. + */ + @Test + fun dockToBottomRelocatesAsFullStrip() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("v", SpaceKind.Viewport2D), + SplitNode( + SplitOrientation.Vertical, + 0.5f, + LeafArea("o", SpaceKind.Outliner), + LeafArea("p", SpaceKind.Properties), + ), + ) + // Dock "p" to the bottom: "p"'s column collapses to "o", and "p" becomes a full-width bottom row. + val result = reduce(root, AreaCommand.DockArea("p", DockEdge.Bottom, 0.3f)) as SplitNode + assertEquals(SplitOrientation.Vertical, result.orientation) + assertEquals(0.7f, result.ratio, 0.0001f, "the remainder leads and takes 1 - strip fraction") + assertEquals(LeafArea("p", SpaceKind.Properties), result.second, "the docked leaf keeps its id and space") + val topRow = result.first as SplitNode + assertEquals(SplitOrientation.Horizontal, topRow.orientation) + assertEquals(LeafArea("v", SpaceKind.Viewport2D), topRow.first) + assertEquals(LeafArea("o", SpaceKind.Outliner), topRow.second, "the source column healed to its sibling") + } + + /** + * Docking to the top edge places the docked leaf as the leading child (so the strip leads), mirroring + * the bottom case. + */ + @Test + fun dockToTopPlacesStripFirst() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + LeafArea("v", SpaceKind.Viewport2D), + LeafArea("p", SpaceKind.Properties), + ) + val result = reduce(root, AreaCommand.DockArea("p", DockEdge.Top, 0.3f)) as SplitNode + assertEquals(SplitOrientation.Vertical, result.orientation) + assertEquals(0.3f, result.ratio, 0.0001f, "the strip leads and takes the strip fraction") + assertEquals(LeafArea("p", SpaceKind.Properties), result.first) + assertEquals(LeafArea("v", SpaceKind.Viewport2D), result.second, "the remainder is the lone sibling") + } + + /** + * Docking the workspace's sole area is a no-op (nothing to dock against). + */ + @Test + fun dockingSoleLeafIsNoOp() { + val root = LeafArea("a", SpaceKind.Viewport2D) + assertEquals(root, reduce(root, AreaCommand.DockArea("a", DockEdge.Right, 0.3f))) + } + + /** + * A command targeting a missing id leaves the tree unchanged. + */ + @Test + fun unknownTargetIsNoOp() { + val root = SplitNode(SplitOrientation.Horizontal, 0.5f, LeafArea("a", SpaceKind.Outliner), LeafArea("b", SpaceKind.Properties)) + assertEquals(root, reduce(root, AreaCommand.SwitchSpace("zzz", SpaceKind.Parameters))) + } + + /** + * withActiveRoot swaps only the active workspace's tree and leaves the others intact. + */ + @Test + fun withActiveRootReplacesOnlyActive() { + val layout = defaultLayout() + val replacement = LeafArea("new", SpaceKind.History) + val updated = layout.withActiveRoot(replacement) + + assertEquals(replacement, updated.activeWorkspace()!!.root) + val texture = updated.workspaces.first { workspace -> workspace.id == "texture" } + assertTrue(texture.root is SplitNode, "the inactive workspace is untouched") + } + + /** + * The Texture workspace seeds two stacked UV editors on the left, the viewport in the middle, and a + * right column of the Sources table over the Outliner over Properties. + */ + @Test + fun theDefaultTextureWorkspaceLeadsWithUvEditors() { + val texture = defaultLayout().workspaces.first { workspace -> workspace.id == "texture" } + val root = assertIs(texture.root) + val uvColumn = assertIs(root.first) + assertEquals(SplitOrientation.Vertical, uvColumn.orientation, "the left column stacks its UV editors") + assertEquals(SpaceKind.UvEditor, assertIs(uvColumn.first).space) + assertEquals(SpaceKind.UvEditor, assertIs(uvColumn.second).space) + val rest = assertIs(root.second) + assertEquals(SpaceKind.Viewport2D, assertIs(rest.first).space) + val sideColumn = assertIs(rest.second) + val sourcesOverOutliner = assertIs(sideColumn.first) + assertEquals(SpaceKind.Sources, assertIs(sourcesOverOutliner.first).space) + assertEquals(SpaceKind.Outliner, assertIs(sourcesOverOutliner.second).space) + assertEquals(SpaceKind.Properties, assertIs(sideColumn.second).space) + } + + /** + * The first leaf in tree order is the workspace's default strip host: a split's first child before its + * second, however deep, and null when no leaf qualifies. + */ + @Test + fun theFirstQualifyingLeafFollowsTreeOrder() { + val root = + SplitNode( + SplitOrientation.Horizontal, + 0.5f, + SplitNode(SplitOrientation.Vertical, 0.5f, LeafArea("sources", SpaceKind.Sources), LeafArea("uv", SpaceKind.UvEditor)), + LeafArea("view", SpaceKind.Viewport2D), + ) + assertEquals("uv", root.firstLeafOrNull { leaf -> leaf.space.hostsOperationStrip }?.id, "the first work surface, reading the tree first-child first") + assertEquals("view", root.firstLeafOrNull { leaf -> leaf.space == SpaceKind.Viewport2D }?.id) + assertNull(root.firstLeafOrNull { leaf -> leaf.space == SpaceKind.Logs }) + val panelsOnly = SplitNode(SplitOrientation.Vertical, 0.5f, LeafArea("outliner", SpaceKind.Outliner), LeafArea("logs", SpaceKind.Logs)) + assertNull(panelsOnly.firstLeafOrNull { leaf -> leaf.space.hostsOperationStrip }, "a workspace of panels alone has no strip host") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandDispatchTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandDispatchTest.kt new file mode 100644 index 0000000..efcf6a3 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandDispatchTest.kt @@ -0,0 +1,410 @@ +package org.umamo.ui.workspace.commands + +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.umamo.edit.ActiveSelectTool +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshOperatorKind +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.SnapKind +import org.umamo.edit.SnapRequest +import org.umamo.edit.UvMirrorRequest +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.action.Command +import org.umamo.ui.viewport.CameraController +import org.umamo.ui.workspace.AreaCameraHub +import org.umamo.ui.workspace.HoveredSurface +import org.umamo.ui.workspace.KeyformSheetSurface +import org.umamo.ui.workspace.KeyformSheetViews +import org.umamo.ui.workspace.SpaceKind +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Runs the command handlers themselves against a real session, one test per routing rule whose failure + * mode is silent. + * + * Every case here is a rule that looks wrong on first reading and is not: a hovered UV editor that + * refuses a transform outright rather than falling back, a duplicate that still copies over a UV editor + * but declines to auto-grab there, a Box Select that must not reach for a keyform sheet the pointer is + * nowhere near. Each would break invisibly - a key that quietly does nothing, or acts in an area the + * user is not looking at - so each is pinned rather than left to review. + */ +class CommandDispatchTest { + private val viewportArea = "viewport-1" + private val uvArea = "uv-1" + private val sheetArea = "sheet-1" + + private fun meshDrawable(id: String): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2)), + geometryGrid = null, + ) + + /** + * A session in [mode] with one mesh drawable selected. + * + * @param EditorMode mode The mode to leave the session in. + * @return EditorSession The session. + */ + private fun session(mode: EditorMode): EditorSession { + val session = + EditorSession( + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(meshDrawable("a")), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + val drawable = SelectionTarget.Drawable(DrawableId("a")) + session.setSelection(Selection(setOf(drawable), drawable)) + session.setMode(mode) + return session + } + + private fun routing(hovered: HoveredSurface?): CommandRouting = CommandRouting { hovered } + + private fun List.run(id: String) { + first { command -> command.id == id }.handler.run(null) + } + + /** + * A sheet surface recording whether its marquee was armed, so a Box Select that reaches the wrong + * surface is visible rather than merely absent from the session. + */ + private class RecordingSheet { + var armed = false + + val surface: KeyformSheetSurface = + KeyformSheetSurface( + selectedTracks = { emptyList() }, + hasSelection = { false }, + frameAll = {}, + armBoxSelect = { armed = true }, + boxSelectArmed = { armed }, + disarmBoxSelect = { armed = false }, + nudgeSelection = {}, + ) + } + + /** + * G over a UV editor in Object mode latches NOTHING. The UV operator refuses outside Edit mode and + * the routing deliberately offers no viewport fallback, so the press is a no-op - grabbing the + * pointer's last viewport instead would move geometry the user is not looking at. + */ + @Test + fun grabOverAUvEditorInObjectModeLatchesNothing() { + val session = session(EditorMode.Object) + val commands = transformCommands(session, routing(HoveredSurface(uvArea, SpaceKind.UvEditor)), SessionAvailability(session)) + + commands.run("mesh.grab") + + assertNull(session.activeUvOperator.value, "the UV operator refuses outside Edit mode") + assertNull(session.activeMeshOperator.value) + assertNull(session.activeObjectOperator.value, "and it must not fall back to the pointer's viewport") + } + + /** The same press in Edit mode does reach the UV operator, so the test above is not vacuous. */ + @Test + fun grabOverAUvEditorInEditModeLatchesTheUvOperator() { + val session = session(EditorMode.Edit) + session.selectAllMeshElements() + val commands = transformCommands(session, routing(HoveredSurface(uvArea, SpaceKind.UvEditor)), SessionAvailability(session)) + + commands.run("mesh.grab") + + assertEquals(uvArea, session.activeUvOperator.value?.areaId) + } + + /** + * B over a viewport arms the VIEWPORT's box select even with a keyform sheet open elsewhere. + * + * The sheet registry resolves a lone open sheet when handed no area, which is right for the sheet's + * own commands and catastrophic here: asking it unconditionally would hijack B in every viewport for + * any layout that happens to include a keyform sheet. + */ + @Test + fun boxSelectOverAViewportIgnoresALoneOpenSheet() { + val session = session(EditorMode.Edit) + val sheets = KeyformSheetViews() + val sheet = RecordingSheet() + sheets.register(sheetArea, sheet.surface) + val commands = + selectCommands(session, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)), sheets, SessionAvailability(session)) + + commands.run("mesh.boxSelect") + + assertFalse(sheet.armed, "the sheet is open but the pointer is not over it") + assertEquals(viewportArea, (session.activeSelectTool.value as? ActiveSelectTool.BoxArmed)?.areaId) + } + + /** B over the sheet itself arms the sheet's marquee and leaves the session's tool alone. */ + @Test + fun boxSelectOverASheetArmsThatSheet() { + val session = session(EditorMode.Edit) + val sheets = KeyformSheetViews() + val sheet = RecordingSheet() + sheets.register(sheetArea, sheet.surface) + val commands = + selectCommands(session, routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)), sheets, SessionAvailability(session)) + + commands.run("mesh.boxSelect") + + assertTrue(sheet.armed) + assertNull(session.activeSelectTool.value, "the viewport's box select stays unarmed") + } + + /** + * C over a keyform sheet arms NOTHING. A sheet has no circle brush, and there is no longer a + * last-viewport to fall back to - arming one the pointer is not over is the failure the single resolver + * exists to remove. + */ + @Test + fun circleSelectOverASheetArmsNothing() { + val session = session(EditorMode.Edit) + val commands = + selectCommands(session, routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)), KeyformSheetViews(), SessionAvailability(session)) + + commands.run("mesh.circleSelect") + + assertNull(session.activeSelectTool.value, "a sheet hosts no brush and hands the gesture to no one") + } + + /** The same press over a viewport does arm, so the refusal above is the routing talking, not a dead command. */ + @Test + fun circleSelectOverAViewportArmsThere() { + val session = session(EditorMode.Edit) + val commands = + selectCommands(session, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)), KeyformSheetViews(), SessionAvailability(session)) + + commands.run("mesh.circleSelect") + + assertEquals(viewportArea, (session.activeSelectTool.value as? ActiveSelectTool.Circle)?.areaId) + } + + /** + * Shift+D in Object mode duplicates wherever the pointer is, but only auto-grabs when the pointer is on + * a viewport. + * + * The duplicate itself needs no area - it is a model edit - so it still runs over a UV editor or a + * panel. The auto-grab is a viewport gesture, so it is simply skipped rather than started somewhere + * the user is not pointing. + */ + @Test + fun objectDuplicateSkipsTheAutoGrabOffAViewport() { + val session = session(EditorMode.Object) + val commands = topologyCommands(session, routing(HoveredSurface(uvArea, SpaceKind.UvEditor)), SessionAvailability(session)) + + commands.run("mesh.duplicate") + + assertEquals(2, session.model.value.drawables.size, "the duplicate itself still happened") + assertNull(session.activeObjectOperator.value, "but nothing was grabbed in a viewport the pointer left") + } + + /** Over a viewport it does auto-grab, so the skip above is the routing talking. */ + @Test + fun objectDuplicateAutoGrabsInTheHoveredViewport() { + val session = session(EditorMode.Object) + val commands = topologyCommands(session, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)), SessionAvailability(session)) + + commands.run("mesh.duplicate") + + assertEquals(MeshOperatorKind.Grab, session.activeObjectOperator.value?.kind) + assertEquals(viewportArea, session.activeObjectOperator.value?.areaId) + } + + /** + * G with the pointer on a PANEL latches nothing at all. + * + * This is the whole point of retiring the second resolver: there used to be a "last viewport touched" + * to fall back on, so a transform started in a viewport the user had walked away from. The fixture + * has a live mesh selection, so the refusal is the routing talking and not an ineligible session. + */ + @Test + fun grabOverAPanelLatchesNothing() { + val session = session(EditorMode.Edit) + session.selectAllMeshElements() + val commands = + transformCommands(session, routing(HoveredSurface("outliner-1", SpaceKind.Outliner)), SessionAvailability(session)) + + commands.run("mesh.grab") + + assertNull(session.activeMeshOperator.value, "no viewport is hovered, so there is nowhere to grab") + assertNull(session.activeObjectOperator.value) + assertNull(session.activeUvOperator.value) + } + + /** The same press over a viewport does latch, so the refusal above is not a dead command. */ + @Test + fun grabOverAViewportLatchesThere() { + val session = session(EditorMode.Edit) + session.selectAllMeshElements() + val commands = + transformCommands(session, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)), SessionAvailability(session)) + + commands.run("mesh.grab") + + assertEquals(viewportArea, session.activeMeshOperator.value?.areaId) + } + + /** Box Select over a panel arms nothing either - same rule, different tool. */ + @Test + fun boxSelectOverAPanelArmsNothing() { + val session = session(EditorMode.Edit) + val commands = + selectCommands( + session, + routing(HoveredSurface("properties-1", SpaceKind.Properties)), + KeyformSheetViews(), + SessionAvailability(session), + ) + + commands.run("mesh.boxSelect") + + assertNull(session.activeSelectTool.value) + } + + /** + * A world snap fired over a panel reaches no overlay. + * + * The request still goes out - the session has no idea where the pointer is - but it carries a null + * area, and every collector gates on its own id, so nothing executes. Pinned at the payload because + * the collectors themselves live in composables this test cannot reach. + */ + @Test + fun aWorldSnapOverAPanelCarriesNoArea() = + runTest { + val session = session(EditorMode.Edit) + val commands = + snapCommands(session, routing(HoveredSurface("logs-1", SpaceKind.Logs)), SessionAvailability(session)) + val received = mutableListOf() + val collector = launch { session.snapRequests.collect { request -> received += request } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + commands.run("snap.selectionToCursor") + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + collector.cancel() + + assertEquals(1, received.size, "the request is still emitted") + assertNull(received.single().areaId, "but it names no area, so no overlay collector matches") + assertEquals(SnapKind.SelectionToCursor, received.single().kind) + } + + /** Over a viewport the same snap carries that viewport, electing exactly one overlay. */ + @Test + fun aWorldSnapOverAViewportCarriesIt() = + runTest { + val session = session(EditorMode.Edit) + val commands = + snapCommands(session, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)), SessionAvailability(session)) + val received = mutableListOf() + val collector = launch { session.snapRequests.collect { request -> received += request } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + commands.run("snap.selectionToCursor") + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + collector.cancel() + + assertEquals(viewportArea, received.single().areaId) + } + + /** + * Mirror UVs fired over a 2D viewport still runs its handler - a command's spaces hide it from the + * palette there, they do not gate the dispatch - and the request it emits names no area, so no UV + * editor's collector matches. That no-op is what makes hiding it safe: nothing that worked is lost. + */ + @Test + fun aUvMirrorOverAViewportStillDispatchesAndCarriesNoArea() = + runTest { + val session = session(EditorMode.Edit) + val commands = + uvCommands(session, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)), SessionAvailability(session)) + val received = mutableListOf() + val collector = launch { session.uvMirrorRequests.collect { request -> received += request } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + commands.run("uv.mirrorU") + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + collector.cancel() + + assertEquals(1, received.size, "the handler ran: spaces are not a dispatch guard") + assertNull(received.single().areaId, "but it names no area, so no UV editor acts on it") + } + + /** Over a UV editor the same mirror carries that editor, electing exactly one overlay. */ + @Test + fun aUvMirrorOverAUvEditorCarriesIt() = + runTest { + val session = session(EditorMode.Edit) + val commands = + uvCommands(session, routing(HoveredSurface(uvArea, SpaceKind.UvEditor)), SessionAvailability(session)) + val received = mutableListOf() + val collector = launch { session.uvMirrorRequests.collect { request -> received += request } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + + commands.run("uv.mirrorU") + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + runCurrent() + collector.cancel() + + assertEquals(uvArea, received.single().areaId) + } + + /** + * The camera lookup is kind-agnostic: it resolves whatever controller the hovered area registered, + * with no per-space branch. Pinned against a rewrite that "tidies" it into a Viewport2D/UvEditor + * check, which would silently lock out any camera-bearing space added later. + */ + @Test + fun viewCommandsResolveWhicheverAreaRegisteredACamera() { + var fitCount = 0 + val camera = + object : CameraController { + override fun fit() { + fitCount++ + } + + override fun actualSize() = Unit + + override fun zoomIn(coarse: Boolean) = Unit + + override fun zoomOut(coarse: Boolean) = Unit + + override fun armZoomRegion() = Unit + + override fun frameSelected() = Unit + } + val cameras = AreaCameraHub() + cameras.register(sheetArea, camera) + val commands = viewCommands(cameras, routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)), viewportPresent = true) + + commands.run("view.fit") + + assertEquals(1, fitCount, "the hovered area's controller resolved on its area id alone") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandRoutingTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandRoutingTest.kt new file mode 100644 index 0000000..093c93b --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandRoutingTest.kt @@ -0,0 +1,266 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.workspace.HoveredSurface +import org.umamo.ui.workspace.SpaceKind +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pins the one place a command asks "which area does the pointer mean". + * + * The rules these cover were previously five separate private helpers and a scatter of inline SpaceKind + * comparisons, none of which any test could reach - they only ran inside a live composition. Several + * are asymmetric in ways that read like bugs and are not, so the asymmetries are asserted deliberately: + * a hovered UV editor blocks a select tool outside Edit mode but still claims a transform, and the + * kind-agnostic lookups stay kind-agnostic. + */ +class CommandRoutingTest { + private val viewportArea = "viewport-1" + private val uvArea = "uv-1" + private val sheetArea = "sheet-1" + + private fun routing(hovered: HoveredSurface?): CommandRouting = CommandRouting { hovered } + + /** + * The strip placement rule: a hovered work surface wins, a hovered panel yields to the last work + * surface touched, an untouched shell yields to the workspace's first work surface, and with none of + * those the strip has no area (it shows nowhere). + */ + @Test + fun theOperationStripGoesToAWorkSurfaceOrNowhere() { + val lastWorkSurface = HoveredSurface(uvArea, SpaceKind.UvEditor) + assertEquals(viewportArea, CommandRouting({ HoveredSurface(viewportArea, SpaceKind.Viewport2D) }, { lastWorkSurface }).operationStripArea()) + assertEquals(uvArea, CommandRouting({ HoveredSurface(uvArea, SpaceKind.UvEditor) }, { lastWorkSurface }).operationStripArea()) + assertEquals(uvArea, CommandRouting({ HoveredSurface(sheetArea, SpaceKind.KeyformSheet) }, { lastWorkSurface }).operationStripArea(), "a panel yields to the last work surface") + assertEquals(uvArea, CommandRouting({ null }, { lastWorkSurface }).operationStripArea(), "no pointer at all still finds the last work surface") + assertNull(CommandRouting({ HoveredSurface(sheetArea, SpaceKind.KeyformSheet) }, { null }).operationStripArea(), "never a panel") + assertNull(routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)).operationStripArea(), "the default remembers no work surface and knows no workspace") + + // A fresh shell: the pointer went straight from the file picker to a panel, so no work surface was + // ever touched, and the workspace's first one takes the strip - a hovered or remembered one still wins. + val untouched = CommandRouting({ HoveredSurface(sheetArea, SpaceKind.KeyformSheet) }, { null }, { viewportArea }) + assertEquals(viewportArea, untouched.operationStripArea(), "an untouched shell yields to the workspace's first work surface") + assertEquals(uvArea, CommandRouting({ null }, { lastWorkSurface }, { viewportArea }).operationStripArea(), "the last touched still outranks the workspace default") + assertEquals(uvArea, CommandRouting({ HoveredSurface(uvArea, SpaceKind.UvEditor) }, { null }, { viewportArea }).operationStripArea(), "and so does the hovered one") + assertNull(CommandRouting({ null }, { null }, { null }).operationStripArea(), "a workspace of panels alone shows the strip nowhere") + var workspaceDefault: String? = null + val live = CommandRouting({ null }, { null }, { workspaceDefault }) + assertNull(live.operationStripArea()) + workspaceDefault = viewportArea + assertEquals(viewportArea, live.operationStripArea(), "the workspace default is read per call, so a workspace switch is seen") + } + + /** + * The viewport a capture frames: the hovered one wins, a panel crossed on the way to the File menu yields + * to the last viewport touched, and with none touched there is none. The acting lookup keeps refusing the + * fallback, since a command that acts must act where the pointer is. + */ + @Test + fun aCaptureFramesTheHoveredViewportElseTheLastOneTouched() { + val lastViewport = HoveredSurface("viewport-2", SpaceKind.Viewport2D) + val overViewport = CommandRouting({ HoveredSurface(viewportArea, SpaceKind.Viewport2D) }, { null }, { null }, { lastViewport }) + assertEquals(viewportArea, overViewport.framedViewportArea(), "the hovered viewport wins") + + val overPanel = CommandRouting({ HoveredSurface(sheetArea, SpaceKind.KeyformSheet) }, { null }, { null }, { lastViewport }) + assertEquals("viewport-2", overPanel.framedViewportArea(), "a panel yields to the last viewport") + assertNull(overPanel.viewportArea(), "while an acting command still finds no viewport") + + assertNull(CommandRouting({ HoveredSurface(uvArea, SpaceKind.UvEditor) }, { null }, { null }, { null }).framedViewportArea(), "no viewport touched yet") + } + + private fun meshDrawable(): Drawable = + Drawable( + id = DrawableId("a"), + name = "a", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2)), + geometryGrid = null, + ) + + /** + * A session in [mode], with the one mesh drawable selected so Edit mode has something to edit. + * + * @param EditorMode mode The mode to leave the session in. + * @return EditorSession The session. + */ + private fun session(mode: EditorMode): EditorSession { + val session = + EditorSession( + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(meshDrawable()), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + val drawable = SelectionTarget.Drawable(DrawableId("a")) + session.setSelection(Selection(setOf(drawable), drawable)) + session.setMode(mode) + return session + } + + /** areaOf names the hovered area only when that area hosts the asked-for kind. */ + @Test + fun areaOfMatchesOnlyItsKind() { + val overUv = routing(HoveredSurface(uvArea, SpaceKind.UvEditor)) + assertEquals(uvArea, overUv.areaOf(SpaceKind.UvEditor)) + assertNull(overUv.areaOf(SpaceKind.KeyformSheet), "a UV editor is not a sheet, even though both are hovered surfaces") + assertNull(overUv.areaOf(SpaceKind.Viewport2D)) + assertNull(routing(null).areaOf(SpaceKind.UvEditor), "nothing hovered names no area") + } + + /** + * hoveredAreaIdAnyKind stays kind-agnostic. Narrowing it to one kind would look like a cleanup and + * would silently change Select Linked, which genuinely executes in a viewport AND in a UV editor. + */ + @Test + fun hoveredAreaIdIsKindAgnostic() { + assertEquals(uvArea, routing(HoveredSurface(uvArea, SpaceKind.UvEditor)).hoveredAreaIdAnyKind()) + assertEquals(sheetArea, routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)).hoveredAreaIdAnyKind()) + assertEquals("outliner-1", routing(HoveredSurface("outliner-1", SpaceKind.Outliner)).hoveredAreaIdAnyKind()) + assertNull(routing(null).hoveredAreaIdAnyKind()) + } + + /** + * Every space kind resolves, not just the three that happen to stamp the tracker today. + * + * Swept over [SpaceKind.entries] rather than a hand-picked sample so a tenth kind cannot be added + * without deciding what routing does with it: every kind names its own area and only its own, and + * exactly two - the 2D viewport and the UV editor - can host a transform. The remaining seven resolve + * nothing, which is what makes a key pressed over a panel do nothing instead of acting elsewhere. + */ + @Test + fun everySpaceKindResolves() { + for (kind in SpaceKind.entries) { + val areaId = "area-${kind.key}" + val routing = routing(HoveredSurface(areaId, kind)) + + assertEquals(areaId, routing.areaOf(kind), "${kind.name} names its own area") + assertEquals(areaId, routing.hoveredAreaIdAnyKind(), "${kind.name} is reported kind-agnostically") + for (other in SpaceKind.entries.filter { candidate -> candidate != kind }) { + assertNull(routing.areaOf(other), "a hovered ${kind.name} must not answer as ${other.name}") + } + + // Exactly two kinds can host a transform, and each hosts it in ITS OWN area; the other seven + // resolve nothing rather than reaching back to a viewport the pointer has left. + val expectedTarget = + when (kind) { + SpaceKind.UvEditor -> TransformTarget.Uv(areaId) + SpaceKind.Viewport2D -> TransformTarget.Viewport(areaId) + else -> null + } + assertEquals(expectedTarget, routing.transformTarget(), "${kind.name} transform target") + } + } + + /** + * A hovered space with no camera registered resolves no camera, so the view commands no-op rather than + * reaching into whichever viewport the pointer last visited. + * + * The lookup itself lives in ViewCommands (it needs the hub); what is pinned here is the input to it - + * that a panel hover reports the PANEL's area id, which no camera is registered under. + */ + @Test + fun aPanelHoverNamesAnAreaThatOwnsNoCamera() { + val overOutliner = routing(HoveredSurface("outliner-1", SpaceKind.Outliner)) + assertEquals("outliner-1", overOutliner.hovered()?.areaId) + assertNull(overOutliner.areaOf(SpaceKind.Viewport2D), "the pointer is on a panel, not on a viewport") + assertNull(overOutliner.areaOf(SpaceKind.KeyformSheet)) + } + + /** A hovered UV editor in Edit mode arms the select tool in itself, not in the pointer's old viewport. */ + @Test + fun selectToolArmsInAHoveredUvEditorInEditMode() { + assertEquals(uvArea, routing(HoveredSurface(uvArea, SpaceKind.UvEditor)).selectToolArea(session(EditorMode.Edit))) + } + + /** + * In Object mode a hovered UV editor arms NOTHING - it must not fall back to the viewport. The UV + * overlay only composes in Edit mode, and the session's arm is mode-agnostic, so a fallback would + * latch a tool on an area with nothing to drive or cancel it. + */ + @Test + fun selectToolRefusesAHoveredUvEditorOutsideEditMode() { + val routing = routing(HoveredSurface(uvArea, SpaceKind.UvEditor)) + assertNull(routing.selectToolArea(session(EditorMode.Object)), "Object mode over a UV editor arms nothing") + assertNull(routing.selectToolArea(null), "no document arms nothing") + // Not vacuous: the same routing DOES arm in Edit mode, so the nulls above are the mode gate talking. + assertEquals(uvArea, routing.selectToolArea(session(EditorMode.Edit))) + } + + /** + * A select tool arms in the hovered VIEWPORT and nowhere else. + * + * There is no "last viewport" fallback: a marquee is a pointer gesture, so arming one in an area the + * pointer is not over would latch a tool the user cannot drive, exactly as it would in a UV editor + * outside Edit mode. + */ + @Test + fun selectToolArmsOnlyInAHoveredViewport() { + val editing = session(EditorMode.Edit) + assertEquals(viewportArea, routing(HoveredSurface(viewportArea, SpaceKind.Viewport2D)).selectToolArea(editing)) + assertNull(routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)).selectToolArea(editing)) + assertNull(routing(HoveredSurface("outliner-1", SpaceKind.Outliner)).selectToolArea(editing)) + assertNull(routing(null).selectToolArea(editing), "nothing hovered arms nothing") + } + + /** + * A transform over a hovered UV editor targets the UV editor in EITHER mode: routing is session-blind + * here, and beginUvOperator does its own Edit-mode refusal. The asymmetry with selectToolArea above + * is deliberate - both end in a refusal outside Edit mode, just at different layers. + */ + @Test + fun transformTargetsAHoveredUvEditorInEitherMode() { + assertEquals(TransformTarget.Uv(uvArea), routing(HoveredSurface(uvArea, SpaceKind.UvEditor)).transformTarget()) + } + + /** + * A transform runs in the hovered viewport, and in no viewport at all when the pointer is elsewhere. + * + * The hovered viewport's OWN id is what comes back - the property the retired second resolver could not + * guarantee, since it remembered the last viewport touched rather than the one under the pointer. + */ + @Test + fun transformRunsOnlyWhereThePointerIs() { + val secondViewport = "viewport-2" + assertEquals( + TransformTarget.Viewport(secondViewport), + routing(HoveredSurface(secondViewport, SpaceKind.Viewport2D)).transformTarget(), + "the hovered viewport, not whichever one was touched first", + ) + assertNull( + routing(HoveredSurface(sheetArea, SpaceKind.KeyformSheet)).transformTarget(), + "a keyform sheet hosts no transform, and must not hand the gesture to a viewport", + ) + assertNull(routing(HoveredSurface("logs-1", SpaceKind.Logs)).transformTarget()) + assertNull(routing(null).transformTarget(), "nothing hovered is nowhere to run it") + } + + /** + * The resolver is read on every call, never sampled once. A routing instance outlives the document + * swaps and area edits that move the pointer, so a captured answer would go permanently stale. + */ + @Test + fun theResolverIsReadPerCall() { + var hovered: HoveredSurface? = HoveredSurface(uvArea, SpaceKind.UvEditor) + val routing = CommandRouting { hovered } + assertEquals(TransformTarget.Uv(uvArea), routing.transformTarget()) + + hovered = HoveredSurface(viewportArea, SpaceKind.Viewport2D) + assertEquals(TransformTarget.Viewport(viewportArea), routing.transformTarget(), "the second call saw the new pointer state") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandSpacesTableTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandSpacesTableTest.kt new file mode 100644 index 0000000..e2e515f --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandSpacesTableTest.kt @@ -0,0 +1,106 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.CommandSpaces +import org.umamo.ui.workspace.SpaceKind +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins which commands are scoped to a space, and to which. + * + * A scope is read off what a handler's routing does, which no test can derive - so the table is pinned + * whole instead. A command that gains or loses a scope must change this map, which is the moment to + * check the handler really is a no-op everywhere else: a scope narrower than its handler hides a + * command that would have run, and the palette is the only place that shows. + */ +class CommandSpacesTableTest { + /** The scoped commands, each with the spaces its handler acts in; every other command is Everywhere. */ + @Test + fun theScopedCommandsAreExactlyThese() { + val viewport = setOf(SpaceKind.Viewport2D) + val uvEditor = setOf(SpaceKind.UvEditor) + val workSurfaces = setOf(SpaceKind.Viewport2D, SpaceKind.UvEditor) + val workSurfacesAndSheet = setOf(SpaceKind.Viewport2D, SpaceKind.UvEditor, SpaceKind.KeyformSheet) + val keyableSurfaces = setOf(SpaceKind.KeyformSheet, SpaceKind.Properties) + val expected = + mapOf( + "view.fit" to workSurfaces, + "view.zoomActualSize" to workSurfaces, + "view.zoomIn" to workSurfaces, + "view.zoomOut" to workSurfaces, + "view.zoomInCoarse" to workSurfaces, + "view.zoomOutCoarse" to workSurfaces, + "view.zoomRegion" to workSurfaces, + "view.frameSelected" to workSurfaces, + "frame.all" to workSurfacesAndSheet, + "mesh.grab" to workSurfaces, + "mesh.scale" to workSurfaces, + "mesh.rotate" to workSurfaces, + "mesh.mirrorH" to workSurfaces, + "mesh.mirrorV" to workSurfaces, + "mesh.boxSelect" to workSurfacesAndSheet, + "mesh.circleSelect" to workSurfaces, + "mesh.selectLinkedAtCursor" to workSurfaces, + "mesh.selectLinked" to workSurfaces, + "edit.switchObjectUnderCursor" to viewport, + "snap.cursorToSelected" to viewport, + "snap.cursorToActive" to viewport, + "snap.selectionToGrid" to viewport, + "snap.selectionToCursor" to viewport, + "snap.selectionToCursorOffset" to viewport, + "snap.selectionToActive" to viewport, + "uv.mirrorU" to uvEditor, + "uv.mirrorV" to uvEditor, + "uv.snap.selectionToPixels" to uvEditor, + "uv.snap.selectionToCursor" to uvEditor, + "uv.snap.selectionToCursorOffset" to uvEditor, + "uv.snap.selectionToGrid" to uvEditor, + "uv.snap.cursorToPixels" to uvEditor, + "uv.snap.cursorToSelected" to uvEditor, + "uv.snap.cursorToGrid" to uvEditor, + "uv.page.next" to uvEditor, + "uv.page.previous" to uvEditor, + "uv.page.followSelection" to uvEditor, + "uv.pinPlacement" to uvEditor, + "uv.unpinPlacement" to uvEditor, + "mesh.rip" to viewport, + "mesh.insertVertex" to workSurfaces, + "mesh.vertexSlide" to viewport, + "keyform.insert" to keyableSurfaces, + "keyform.delete" to keyableSurfaces, + ) + val actual = + everyCommandTable() + .mapNotNull { command -> (command.spaces as? CommandSpaces.Only)?.let { scoped -> command.id to scoped.kinds } } + .toMap() + assertEquals(expected, actual) + } + + /** + * Every texture-coordinate command is scoped. The one leak this dimension exists to close is a uv.* + * command listed over a 2D viewport, so a new one that forgets its scope fails here by name rather + * than waiting to be noticed in the palette. + */ + @Test + fun everyUvCommandIsScoped() { + val uvCommands = everyCommandTable().filter { command -> command.id.startsWith("uv.") } + assertTrue(uvCommands.isNotEmpty(), "the table must actually hold uv commands for this to mean anything") + for (command in uvCommands) { + assertEquals(CommandSpaces.UvEditor, command.spaces, "${command.id} must be scoped to the UV editor") + } + } + + /** + * The keyform sheet's own commands stay Everywhere on purpose: their sheet lookup falls back to the + * lone open sheet, so they run from the palette over a viewport, and scoping them to the sheet would + * hide commands that work. + */ + @Test + fun theSheetCommandsWithAFallbackStayEverywhere() { + val byId = everyCommandTable().associateBy { command -> command.id } + for (id in listOf("keyform.deleteSelectedKeys", "keyform.nudgeKeyLeft", "keyform.nudgeKeyRight", "keyform.frameAll")) { + assertEquals(CommandSpaces.Everywhere, byId.getValue(id).spaces, "$id reaches the lone open sheet from anywhere") + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandTableFixture.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandTableFixture.kt new file mode 100644 index 0000000..fbbc6a3 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandTableFixture.kt @@ -0,0 +1,157 @@ +package org.umamo.ui.workspace.commands + +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetModel +import org.umamo.settings.Settings +import org.umamo.storage.OkioAppStorage +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.model.EditorModeHandle +import org.umamo.ui.model.SelectionHandle +import org.umamo.ui.workspace.AreaCameraHub +import org.umamo.ui.workspace.AreaDragController +import org.umamo.ui.workspace.KeyformSheetViews +import org.umamo.ui.workspace.OperationStripState +import org.umamo.ui.workspace.ShellOverlayState +import org.umamo.ui.workspace.SplitterDragCancelController +import org.umamo.ui.workspace.WorkspaceLayoutController +import org.umamo.ui.workspace.defaultLayout +import org.umamo.ui.workspace.rowdrag.RowDragCancelController +import kotlin.test.assertEquals + +/* + * The fixtures the command-table tests share: a session parked in a given mode, and the whole command + * table the way the shell, the settings-backed shell, and the app register it. + * + * Registration happens inside composables, so no test can read the list the shell really registers. + * Holding the test-side copy once at least keeps every table-wide assertion looking at the same set. + */ + +/** + * A session in [mode] with one mesh drawable selected - Edit mode is refused with nothing to edit. + * + * @param EditorMode mode The mode to leave the session in. + * @return EditorSession The session, verified to be in [mode]. + */ +internal fun commandFixtureSession(mode: EditorMode): EditorSession { + val drawable = + Drawable( + id = DrawableId("a"), + name = "a", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f), intArrayOf(0, 1, 2)), + geometryGrid = null, + ) + val session = + EditorSession( + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = listOf(drawable), + rootChildren = emptyList(), + rootPartId = null, + ), + ) + val target = SelectionTarget.Drawable(DrawableId("a")) + session.setSelection(Selection(setOf(target), target)) + session.setMode(mode) + // A case reading the mode through a command's availability would pass its "is hidden" half against a + // fixture that quietly stayed in Object mode, while testing nothing. + assertEquals(mode, session.mode.value, "the fixture must really be in the mode the case names") + return session +} + +/** + * The selection and mode handles over [session], reading the session directly where the app's handle + * reads a Compose mirror of it. + * + * @property EditorSession session The session both handles read and write. + */ +private class SessionHandles(private val session: EditorSession) : SelectionHandle, EditorModeHandle { + override val selection: Selection get() = session.selection.value + + /** + * Routes a selection to the session. + * + * @param Selection selection The new selection. + */ + override fun set(selection: Selection) { + session.setSelection(selection) + } + + override val mode: EditorMode get() = session.mode.value + + /** + * Routes a mode change to the session. + * + * @param EditorMode mode The new mode. + */ + override fun set(mode: EditorMode) { + session.setMode(mode) + } +} + +/** + * Settings over an in-memory filesystem, for the tables that write a key. + * + * @return Settings Empty settings that persist nowhere real. + */ +internal fun inMemorySettings(): Settings { + val configDirectory = "/config".toPath() + val fileSystem = FakeFileSystem() + fileSystem.createDirectories(configDirectory) + return Settings.load(OkioAppStorage(fileSystem, configDirectory, "/data".toPath()), "{}") +} + +/** + * Every command table the shell, the settings-backed shell, and the app register, in the shell's + * registration order. + * + * @param EditorSession? session The session the document-scoped tables close over, or null for the + * no-document tables (every availability then answers for a closed document). + * @return List Every command. + */ +internal fun everyCommandTable(session: EditorSession? = null): List { + val overlays = ShellOverlayState() + val workspaces = WorkspaceLayoutController(defaultLayout()) {} + val routing = CommandRouting { null } + val availability = SessionAvailability(session) + val sheets = KeyformSheetViews() + val handles = session?.let { live -> SessionHandles(live) } + return chromeCommands(overlays, AreaDragController(), SplitterDragCancelController(), RowDragCancelController(), workspaces) {} + + workspaceCommands(workspaces, overlays, "Workspace") + + documentCommands(overlays) + + viewCommands(AreaCameraHub(), routing, viewportPresent = false) + + frameCommands(CommandRegistry(), routing) + + modeCommands(handles, handles) + + historyCommands(session, availability, OperationStripState()) + + objectCommands(session, handles, availability) + + transformCommands(session, routing, availability) + + selectCommands(session, routing, sheets, availability) + + snapCommands(session, routing, availability) + + uvCommands(session, routing, availability) + + topologyCommands(session, routing, availability) + + proportionalCommands(session, availability) + + displayCommands(session, availability) + + atlasCommands(availability, routing, null) + + fileArtworkCommands(routing) { null } + + fileImageExportCommands(routing) { null } + + keyformCommands(session, { null }, routing, sheets, availability) + + viewportChromeCommands(inMemorySettings()) + + workspaceFileCommands({}, {}, {}) + + logCommands {} + + fileCommands({}, {}, {}, {}, { true }, {}, {}, {}, {}) + + fileExportCommands({ true }, {}, {}) +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandTableOrderTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandTableOrderTest.kt new file mode 100644 index 0000000..4ac6651 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/CommandTableOrderTest.kt @@ -0,0 +1,457 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.help.ProjectInfo +import org.umamo.ui.workspace.AreaCameraHub +import org.umamo.ui.workspace.AreaDragController +import org.umamo.ui.workspace.HoveredSurface +import org.umamo.ui.workspace.KeyformSheetViews +import org.umamo.ui.workspace.OperationStripState +import org.umamo.ui.workspace.ShellOverlayState +import org.umamo.ui.workspace.SpaceKind +import org.umamo.ui.workspace.SplitterDragCancelController +import org.umamo.ui.workspace.WorkspaceLayoutController +import org.umamo.ui.workspace.defaultLayout +import org.umamo.ui.workspace.rowdrag.RowDragCancelController +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins every command table's contents AND the order the shell registers them in. + * + * Two things ride on this. A command silently dropped by a refactor is otherwise invisible until a user + * reaches for it - a menu row, a palette entry, or a chord that does nothing at all - because nothing else + * in the tree enumerates the tables. And [CommandRegistry] is insertion-ordered, which the command palette + * shows verbatim for a blank query, so the order here IS the order the user reads; a regrouping that + * shuffles it should be a deliberate edit to these lists, not a surprise. + * + * Every builder takes its collaborators as plain values and resolves the rest at dispatch time, so a + * table builds with no document, no renderer, and no composition - which is what makes this test + * possible at all. + */ +class CommandTableOrderTest { + private fun overlays(): ShellOverlayState = ShellOverlayState() + + private fun workspaces(): WorkspaceLayoutController = WorkspaceLayoutController(defaultLayout()) {} + + private fun routing(): CommandRouting = CommandRouting { null } + + /** The shell-chrome table: overlay toggles, the project links, the drag cancels, workspace tab navigation. */ + @Test + fun chromeTableIsComplete() { + val commands = + chromeCommands( + overlays(), + AreaDragController(), + SplitterDragCancelController(), + RowDragCancelController(), + workspaces(), + ) {} + assertEquals( + listOf( + "palette.toggle", + "area.dragCancel", + "row.dragCancel", + "edit.preferences", + "help.about", + "help.credits", + "help.quickSetup", + "help.sourceCode", + "help.webSite", + "help.documentation", + "workspace.prev", + "workspace.next", + ), + commands.map { command -> command.id }, + ) + } + + /** The workspace-management and document-report tables, in the order the shell concatenates them. */ + @Test + fun workspaceAndDocumentTablesAreComplete() { + val commands = workspaceCommands(workspaces(), overlays(), "Workspace") + documentCommands(overlays()) + assertEquals( + listOf( + "workspace.new", + "workspace.reset", + "workspace.applyLayout", + "workspace.appendWorkspace", + "document.openFailed", + "document.confirmReplace", + "document.confirmExit", + "document.exportReport", + "document.repackReport", + "document.exportOptions", + "document.confirm", + "document.alert", + ), + commands.map { command -> command.id }, + ) + } + + /** + * The viewport navigation table and the context-aware frame command. Built with no render service, + * which only flips the availability gate - the tables themselves are the same either way. + */ + @Test + fun viewTablesAreComplete() { + val commands = viewCommands(AreaCameraHub(), routing(), viewportPresent = false) + assertEquals( + listOf( + "view.fit", + "view.zoomActualSize", + "view.zoomIn", + "view.zoomOut", + "view.zoomInCoarse", + "view.zoomOutCoarse", + "view.zoomRegion", + "view.frameSelected", + ), + commands.map { command -> command.id }, + ) + assertEquals(listOf("frame.all"), frameCommands(CommandRegistry(), routing()).map { command -> command.id }) + } + + /** The selection-clear and editor-mode table. */ + @Test + fun modeTableIsComplete() { + assertEquals( + listOf("select.clear", "mode.toggleEdit", "mode.object", "mode.edit"), + modeCommands(null, null).map { command -> command.id }, + ) + } + + /** + * The document-scoped groups in the order the shell concatenates them - by far the largest set, and + * the one a split most easily loses a command from. The six proportional-falloff commands are + * appended by a loop over the enum, so they trail their group's hand-written pair. + */ + @Test + fun sessionTablesAreComplete() { + val availability = SessionAvailability(null) + val routing = routing() + val sheets = KeyformSheetViews() + val commands = + historyCommands(null, availability, OperationStripState()) + + objectCommands(null, null, availability) + + transformCommands(null, routing, availability) + + selectCommands(null, routing, sheets, availability) + + snapCommands(null, routing, availability) + + uvCommands(null, routing, availability) + + topologyCommands(null, routing, availability) + + proportionalCommands(null, availability) + + displayCommands(null, availability) + + atlasCommands(availability, routing, null) + assertEquals( + listOf( + "edit.undo", + "edit.redo", + "edit.adjustLastOperation", + "object.toggleVisibility", + "outliner.selectHierarchy", + "deformer.createWarp", + "mesh.grab", + "mesh.scale", + "mesh.rotate", + "mesh.mirrorH", + "mesh.mirrorV", + "mesh.modalCancel", + "mesh.selectMode.vertex", + "mesh.selectMode.edge", + "mesh.selectMode.face", + "select.all", + "select.invert", + "mesh.boxSelect", + "mesh.circleSelect", + "mesh.circleSelect.grow", + "mesh.circleSelect.shrink", + "mesh.selectLinkedAtCursor", + "mesh.selectLinked", + "edit.switchObjectUnderCursor", + "transform.pivotPie", + "transform.pivot.median", + "transform.pivot.individual", + "transform.pivot.active", + "transform.pivot.cursor", + "snap.pie", + "snap.cursorToWorldOrigin", + "snap.cursorToGrid", + "snap.cursorToSelected", + "snap.cursorToActive", + "snap.selectionToGrid", + "snap.selectionToCursor", + "snap.selectionToCursorOffset", + "snap.selectionToActive", + "uv.mirrorU", + "uv.mirrorV", + "uv.snap.selectionToPixels", + "uv.snap.selectionToCursor", + "uv.snap.selectionToCursorOffset", + "uv.snap.selectionToGrid", + "uv.snap.cursorToPixels", + "uv.snap.cursorToSelected", + "uv.snap.cursorToGrid", + "uv.page.next", + "uv.page.previous", + "uv.page.followSelection", + "uv.pinPlacement", + "uv.unpinPlacement", + "mesh.duplicate", + "mesh.merge", + "mesh.merge.atCenter", + "mesh.merge.atFirst", + "mesh.merge.atLast", + "mesh.rip", + "mesh.connect", + "mesh.insertVertex", + "mesh.vertexSlide", + "mesh.proportional.toggle", + "mesh.proportional.connectedToggle", + "mesh.proportional.falloff.smooth", + "mesh.proportional.falloff.sphere", + "mesh.proportional.falloff.root", + "mesh.proportional.falloff.sharp", + "mesh.proportional.falloff.linear", + "mesh.proportional.falloff.constant", + "document.toggleSourceArtworkDisplay", + "document.repackAtlas", + ), + commands.map { command -> command.id }, + ) + } + + /** + * The workspace layout's file table and the log table, in the order the settings-backed shell + * concatenates them. Their actions are plain lambdas, so the tables build with no picker and no settings. + */ + @Test + fun workspaceFileAndLogTablesAreComplete() { + val commands = workspaceFileCommands({}, {}, {}) + logCommands {} + assertEquals(listOf("workspace.import", "workspace.exportThis", "workspace.exportAll", "logs.export"), commands.map { command -> command.id }) + } + + /** The viewport chrome toggles the settings-backed shell registers; they write settings, so they build over an in-memory tree. */ + @Test + fun viewportChromeTableIsComplete() { + assertEquals( + listOf("view.toggleToolbar", "view.toggleSidebar"), + viewportChromeCommands(inMemorySettings()).map { command -> command.id }, + ) + } + + /** + * The app-registered file tables. Their actions are plain lambdas, which is what lets a commonMain test + * build them at all - the document layer they actually call into is jvmAndroidMain. + */ + @Test + fun fileTablesAreComplete() { + val commands = fileCommands({}, {}, {}, {}, { true }, {}, {}, {}, {}) + assertEquals( + listOf("file.new", "file.open", "file.save", "file.saveAs", "file.importCmo3", "file.importMoc3", "file.openPath", "file.exit"), + commands.map { command -> command.id }, + ) + assertEquals( + listOf("file.exportCmo3", "file.exportMoc3"), + fileExportCommands({ true }, {}, {}).map { command -> command.id }, + ) + assertEquals( + listOf("file.importArtwork", "document.reloadArtwork", "sources.relink", "sources.matchAutomatically", "sources.replaceArtwork", "sources.deleteArt", "sources.ignoreLayer"), + fileArtworkCommands(routing()) { null }.map { command -> command.id }, + ) + assertEquals(listOf("file.exportImage"), fileImageExportCommands(routing()) { null }.map { command -> command.id }) + } + + /** + * Export Image hides itself while nothing can be captured (the collaborator is null) and asks LIVE; fired, it + * hands the export the 2D viewport the pointer last touched, and no area at all when that surface was + * anything else - never a viewport the pointer has left. + */ + @Test + fun imageExportFollowsTheCollaboratorAndTheHoveredViewport() { + var exportImage: ((String?) -> Unit)? = null + var hovered = HoveredSurface("viewport-3", SpaceKind.Viewport2D) + val command = fileImageExportCommands(CommandRouting { hovered }) { exportImage }.single() + assertFalse(command.availability.isAvailable(), "nothing to capture with no renderer or document") + + val framedAreas = ArrayList() + exportImage = { areaId -> framedAreas.add(areaId) } + assertTrue(command.availability.isAvailable(), "the collaborator is queried per call, not sampled at registration") + command.handler.run(null) + hovered = HoveredSurface("outliner-1", SpaceKind.Outliner) + command.handler.run(null) + + assertEquals(listOf("viewport-3", null), framedAreas) + } + + /** + * Export hides itself when no puppet document is open, and asks LIVE rather than at registration - the + * palette must not offer an export that would no-op. + */ + @Test + fun exportAvailabilityFollowsTheOpenDocument() { + var exportable = false + val export = fileExportCommands({ exportable }, {}, {}).first() + assertFalse(export.availability.isAvailable(), "nothing to export with no document open") + exportable = true + assertTrue(export.availability.isAvailable(), "the tier is queried per call, not sampled at registration") + } + + /** + * Opening a file by its path is argument-only: a recent file's row supplies the path, so the command + * has no title for the palette, passes a path through untouched, and ignores anything that is not one + * rather than opening a file nobody named. + */ + @Test + fun openingByPathTakesThePathAsItsArgument() { + val openedPaths = ArrayList() + val openPath = fileCommands({}, {}, {}, {}, { true }, {}, {}, { path -> openedPaths.add(path) }, {}).first { command -> command.id == "file.openPath" } + + assertNull(openPath.title, "nothing for the palette to offer without a path") + openPath.handler.run("/rigs/hero.uma") + openPath.handler.run(null) + openPath.handler.run(42) + + assertEquals(listOf("/rigs/hero.uma"), openedPaths) + } + + /** Each Help link command opens its own project URL, and nothing else, through the shell's opener. */ + @Test + fun theHelpLinksOpenTheProjectUrls() { + val openedUrls = ArrayList() + val commands = + chromeCommands(overlays(), AreaDragController(), SplitterDragCancelController(), RowDragCancelController(), workspaces()) { url -> openedUrls.add(url) } + + for (commandId in listOf("help.sourceCode", "help.webSite", "help.documentation")) { + commands.first { command -> command.id == commandId }.handler.run(null) + } + + assertEquals(listOf(ProjectInfo.SOURCE_CODE_URL, ProjectInfo.WEB_SITE_URL, ProjectInfo.DOCUMENTATION_URL), openedUrls) + } + + /** + * The artwork commands hide themselves while no document can take artwork (the collaborator is + * null), ask LIVE, and hand the handler the area its operation strip shows in - fired over the + * Sources panel, that is the last work surface the pointer touched, never the panel. Reload also + * asks the collaborator whether any file can be read; relink, delete, and ignore carry their requests + * through, and ignore is argument-only, so it has no title for the palette. + * + * The import carries an optional one: with no payload it means "ask for a file", and with one it means + * "add these" - the way a drop reaches the same id. + */ + @Test + fun artworkCommandsFollowTheCollaboratorAndTheStripArea() { + var operations: ArtworkOperations? = null + val routing = CommandRouting({ HoveredSurface("sources-1", SpaceKind.Sources) }, { HoveredSurface("area-7", SpaceKind.UvEditor) }) + val commands = fileArtworkCommands(routing) { operations } + val add = commands.first { command -> command.id == "file.importArtwork" } + val reload = commands.first { command -> command.id == "document.reloadArtwork" } + val relink = commands.first { command -> command.id == "sources.relink" } + val match = commands.first { command -> command.id == "sources.matchAutomatically" } + val replace = commands.first { command -> command.id == "sources.replaceArtwork" } + assertFalse(add.availability.isAvailable(), "no document to import artwork into") + assertFalse(reload.availability.isAvailable()) + assertFalse(relink.availability.isAvailable()) + assertFalse(match.availability.isAvailable()) + assertFalse(replace.availability.isAvailable()) + var landedArea: String? = "untouched" + var landedImport: ImportArtworkRequest? = null + var landedRequest: RelinkRequest? = null + var landedScope: ReloadScope? = null + var landedReplace: ReplaceRequest? = null + var deleted: DeleteArtRequest? = null + var ignored: IgnoreLayerRequest? = null + var matched = 0 + var canReload = false + operations = + ArtworkOperations( + importArtwork = { request, areaId -> + landedImport = request + landedArea = areaId + }, + reloadArtwork = { areaId, reloadScope -> + landedArea = areaId + landedScope = reloadScope + }, + relinkArtwork = { request, areaId -> + landedRequest = request + landedArea = areaId + }, + matchArtwork = { areaId -> + matched++ + landedArea = areaId + }, + replaceArtwork = { request, areaId -> + landedReplace = request + landedArea = areaId + }, + deleteArt = { request -> deleted = request }, + ignoreLayer = { request -> ignored = request }, + canReload = { canReload }, + ) + assertTrue(add.availability.isAvailable(), "the collaborator is queried per call") + assertFalse(reload.availability.isAvailable(), "a reload needs a file it can read") + canReload = true + assertTrue(reload.availability.isAvailable()) + add.handler.run(null) + assertEquals("area-7", landedArea, "the strip area reaches the orchestration") + assertEquals(null, landedImport, "no payload means ask for a file") + val dropped = ImportArtworkRequest(listOf("/art/face.psd", "/art/hair.psd")) + add.handler.run(dropped) + assertSame(dropped, landedImport, "the dropped files reach the orchestration") + assertEquals("area-7", landedArea) + add.handler.run("not a request") + assertEquals(null, landedImport, "a payload of the wrong shape asks for a file rather than adding nothing") + landedArea = "untouched" + reload.handler.run(null) + assertEquals("area-7", landedArea) + assertEquals(null, landedScope, "a plain Reload covers every file") + val scoped = ReloadScope(setOf(ArtSourceId("art-0"))) + reload.handler.run(scoped) + assertSame(scoped, landedScope, "the watcher's scope reaches the operation") + val request = RelinkRequest(AtlasTileId("t1"), null) + relink.handler.run(request) + assertSame(request, landedRequest, "the relink carries its request") + assertEquals("area-7", landedArea) + landedArea = "untouched" + match.handler.run(null) + assertEquals(1, matched) + assertEquals("area-7", landedArea, "the match lands its strip in the work surface too") + val replaceRequest = ReplaceRequest(ArtSourceId("art-0")) + replace.handler.run(replaceRequest) + assertSame(replaceRequest, landedReplace, "the replace carries its file") + replace.handler.run("not a request") + assertSame(replaceRequest, landedReplace, "a payload of the wrong shape is ignored") + val deleteRequest = DeleteArtRequest(AtlasTileId("t9")) + commands.first { command -> command.id == "sources.deleteArt" }.handler.run(deleteRequest) + assertSame(deleteRequest, deleted, "the delete carries its tile") + val ignore = commands.first { command -> command.id == "sources.ignoreLayer" } + val ignoreRequest = IgnoreLayerRequest(SourceLayerRef(ArtSourceId("art-0"), "lyid:1", stableKey = true), ignored = true) + ignore.handler.run(ignoreRequest) + assertSame(ignoreRequest, ignored, "the ignore carries its layer") + assertNull(ignore.title, "argument-only, so not a palette entry") + } + + /** The keyform-authoring table. */ + @Test + fun keyformTableIsComplete() { + val commands = keyformCommands(null, { null }, routing(), KeyformSheetViews(), SessionAvailability(null)) + assertEquals( + listOf( + "keyform.insert", + "keyform.delete", + "keyform.deleteSelectedKeys", + "keyform.nudgeKeyLeft", + "keyform.nudgeKeyRight", + "keyform.frameAll", + ), + commands.map { command -> command.id }, + ) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/DocumentConfirmTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/DocumentConfirmTest.kt new file mode 100644 index 0000000..caf69cf --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/DocumentConfirmTest.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.confirm_quit_unsaved +import org.umamo.ui.resources.confirm_save_before_quit +import org.umamo.ui.resources.confirm_save_before_replace +import org.umamo.ui.resources.dialog_discard +import org.umamo.ui.resources.dialog_dont_save +import org.umamo.ui.resources.dialog_quit_without_saving +import org.umamo.ui.resources.dialog_save +import org.umamo.ui.workspace.AlertRequest +import org.umamo.ui.workspace.ConfirmAlternative +import org.umamo.ui.workspace.ConfirmRequest +import org.umamo.ui.workspace.ShellOverlayState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins what the destructive confirms ask and what answering them runs. + * + * The prompts guard work that cannot be recovered - a replaced document's unsaved edits, a quit over + * them - so two things matter beyond the dialog appearing at all. The button has to name the + * destructive verb rather than a generic Confirm, since that label is the whole warning once the + * message has been skimmed; and the action has to run on confirm and only on confirm, which nothing + * else in the tree checks without a composition. + */ +class DocumentConfirmTest { + /** + * A registry carrying the document table, over the given overlay state. + * + * @param ShellOverlayState overlays The state the commands raise their requests into. + * @return CommandRegistry The registry to dispatch through. + */ + private fun registry(overlays: ShellOverlayState): CommandRegistry = + CommandRegistry().also { registry -> registry.registerAll(documentCommands(overlays)) } + + @Test + fun confirmExitAsksBeforeQuittingAndRunsTheExitOnConfirm() { + val overlays = ShellOverlayState() + var exitCount = 0 + + assertTrue(registry(overlays).invoke("document.confirmExit", DirtyDocumentPrompt(discard = { exitCount++ }, save = null))) + + val request = overlays.pendingConfirm + assertEquals(Res.string.confirm_quit_unsaved, request?.message) + assertEquals(Res.string.dialog_quit_without_saving, request?.confirmLabel, "with no save possible, the button names what quitting costs") + assertNull(request?.alternative, "and there is no third choice") + assertEquals(0, exitCount, "raising the prompt must not quit") + + overlays.confirmPending() + + assertNull(overlays.pendingConfirm) + assertEquals(1, exitCount) + } + + @Test + fun cancellingTheExitPromptLeavesTheAppRunning() { + val overlays = ShellOverlayState() + var exitCount = 0 + registry(overlays).invoke("document.confirmExit", DirtyDocumentPrompt(discard = { exitCount++ }, save = null)) + + overlays.cancelPending() + + assertNull(overlays.pendingConfirm) + assertEquals(0, exitCount) + } + + @Test + fun confirmReplaceNamesTheDiscard() { + val overlays = ShellOverlayState() + var proceedCount = 0 + registry(overlays).invoke("document.confirmReplace", DirtyDocumentPrompt(discard = { proceedCount++ }, save = null)) + + assertEquals(Res.string.dialog_discard, overlays.pendingConfirm?.confirmLabel) + + overlays.confirmPending() + + assertEquals(1, proceedCount) + } + + /** + * When the document can be saved, both prompts lead with Save: Enter and the primary button save and go on, + * the third choice goes on without saving, and Cancel stays put. The wording says which act follows. + */ + @Test + fun aSaveablePromptLeadsWithSaveAndOffersDontSave() { + val overlays = ShellOverlayState() + var saveCount = 0 + var discardCount = 0 + val prompt = DirtyDocumentPrompt(discard = { discardCount++ }, save = { saveCount++ }) + + registry(overlays).invoke("document.confirmExit", prompt) + val quitRequest = assertNotNull(overlays.pendingConfirm) + assertEquals(Res.string.confirm_save_before_quit, quitRequest.message) + assertEquals(Res.string.dialog_save, quitRequest.confirmLabel, "Save is the default") + assertEquals(Res.string.dialog_dont_save, quitRequest.alternative?.label, "Don't Save is the third choice") + overlays.confirmPending() + assertEquals(1, saveCount, "confirming saves") + assertEquals(0, discardCount) + + registry(overlays).invoke("document.confirmReplace", prompt) + assertEquals(Res.string.confirm_save_before_replace, overlays.pendingConfirm?.message, "the replace prompt is worded for a replace") + overlays.choosePendingAlternative() + assertEquals(1, discardCount, "the third choice goes on without saving") + assertEquals(1, saveCount) + } + + @Test + fun anAlertRoutesIntoTheAlertSlot() { + val overlays = ShellOverlayState() + val alert = AlertRequest(Res.string.confirm_quit_unsaved) + + registry(overlays).invoke("document.alert", alert) + + assertSame(alert, overlays.pendingAlert) + } + + @Test + fun aReadyBuiltConfirmRoutesIntoTheOneSlotUnchanged() { + val overlays = ShellOverlayState() + val request = ConfirmRequest(Res.string.confirm_quit_unsaved) {} + + registry(overlays).invoke("document.confirm", request) + + assertSame(request, overlays.pendingConfirm) + } + + @Test + fun theAlternativeRunsAloneAndClearsTheSlot() { + val overlays = ShellOverlayState() + var confirmCount = 0 + var alternativeCount = 0 + overlays.pendingConfirm = + ConfirmRequest( + message = Res.string.confirm_quit_unsaved, + alternative = ConfirmAlternative(Res.string.dialog_discard) { alternativeCount++ }, + onConfirm = { confirmCount++ }, + ) + + overlays.choosePendingAlternative() + + assertNull(overlays.pendingConfirm) + assertEquals(1, alternativeCount) + assertEquals(0, confirmCount, "the third choice is not the confirm") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/PaletteCommandsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/PaletteCommandsTest.kt new file mode 100644 index 0000000..985702f --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/PaletteCommandsTest.kt @@ -0,0 +1,107 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandAvailability +import org.umamo.ui.action.CommandHint +import org.umamo.ui.action.paletteCommands +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.cmd_select_all +import org.umamo.ui.workspace.SpaceKind +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins what the command palette lists over each kind of surface, against the real command tables. + * + * The case that matters is the one the space dimension exists for: Mirror UVs is an Edit-mode command, + * so availability alone lists it while a mesh is being edited in the 2D viewport, where it does nothing. + */ +class PaletteCommandsTest { + /** + * The transform and texture-coordinate tables over [session] - one work-surface group and the UV-only group. + * + * @param EditorSession session The session the tables close over. + * @return List The two tables, concatenated. + */ + private fun tables(session: EditorSession): List { + val routing = CommandRouting { null } + val availability = SessionAvailability(session) + return transformCommands(session, routing, availability) + uvCommands(session, routing, availability) + } + + /** + * The ids of these commands, in order - what every case below compares. + * + * @return List The command ids. + */ + private fun List.ids(): List = map { command -> command.id } + + /** Editing a mesh in the 2D viewport, the palette offers the transforms and no texture-coordinate command. */ + @Test + fun overAViewportInEditModeNoUvCommandIsListed() { + val listed = paletteCommands(tables(commandFixtureSession(EditorMode.Edit)), SpaceKind.Viewport2D).ids() + + assertTrue("mesh.grab" in listed, "the transforms belong to the viewport") + assertTrue(listed.none { id -> id.startsWith("uv.") }, "no uv command belongs there, but got $listed") + } + + /** Over the UV editor the same session lists them, so the case above is the scope at work and not the mode. */ + @Test + fun overAUvEditorInEditModeTheUvCommandsAreListed() { + val listed = paletteCommands(tables(commandFixtureSession(EditorMode.Edit)), SpaceKind.UvEditor).ids() + + assertTrue("uv.mirrorU" in listed) + assertTrue("uv.mirrorV" in listed) + assertTrue("mesh.grab" in listed, "the transforms belong to the UV editor too") + } + + /** The space does not override the mode: over the UV editor in Object mode, Mirror UVs is still hidden. */ + @Test + fun availabilityStillHidesACommandInsideItsSpace() { + val listed = paletteCommands(tables(commandFixtureSession(EditorMode.Object)), SpaceKind.UvEditor).ids() + + assertFalse("uv.mirrorU" in listed, "Mirror UVs is an Edit-mode command") + assertTrue("uv.pinPlacement" in listed, "while the Object-mode pin is listed") + } + + /** Over a panel neither group is listed: nothing in them acts there. */ + @Test + fun overAPanelNoWorkSurfaceCommandIsListed() { + assertEquals(emptyList(), paletteCommands(tables(commandFixtureSession(EditorMode.Edit)), SpaceKind.Outliner).ids()) + } + + /** Before the pointer has touched any surface, only commands that belong everywhere are listed. */ + @Test + fun beforeAnySurfaceIsTouchedOnlyUnscopedCommandsAreListed() { + val everywhere = Command("test.everywhere", title = Res.string.cmd_select_all, handler = {}) + val listed = paletteCommands(tables(commandFixtureSession(EditorMode.Edit)) + everywhere, null).ids() + + assertEquals(listOf("test.everywhere"), listed) + } + + /** An untitled command is never a palette entry, and an unavailable one is hidden - the two rules the filter kept. */ + @Test + fun untitledAndUnavailableCommandsStayHidden() { + val commands = + listOf( + Command("test.untitled", title = null, handler = {}), + Command("test.unavailable", title = Res.string.cmd_select_all, availability = CommandAvailability { false }, handler = {}), + Command("test.listed", title = Res.string.cmd_select_all, handler = {}), + ) + + assertEquals(listOf("test.listed"), paletteCommands(commands, SpaceKind.Viewport2D).ids()) + } + + /** A hint's suggestedWhen narrows the status bar alone: the palette lists the command regardless. */ + @Test + fun aHintNeverHidesAPaletteEntry() { + val neverSuggested = CommandHint(Res.string.cmd_select_all, suggestedWhen = CommandAvailability { false }) + val commands = listOf(Command("test.hinted", title = Res.string.cmd_select_all, hint = neverSuggested, handler = {})) + + assertEquals(listOf("test.hinted"), paletteCommands(commands, SpaceKind.Viewport2D).ids()) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/StatusHintTableTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/StatusHintTableTest.kt new file mode 100644 index 0000000..16d4e9e --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/commands/StatusHintTableTest.kt @@ -0,0 +1,118 @@ +package org.umamo.ui.workspace.commands + +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.ui.action.defaultKeymap +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.status_bind_edit_mode +import org.umamo.ui.resources.status_bind_grab +import org.umamo.ui.resources.status_bind_rotate +import org.umamo.ui.resources.status_bind_scale +import org.umamo.ui.resources.status_bind_visibility +import org.umamo.ui.resources.status_select_mode +import org.umamo.ui.workspace.STATUS_HINT_LIMIT +import org.umamo.ui.workspace.SpaceKind +import org.umamo.ui.workspace.everyStatusHintFor +import org.umamo.ui.workspace.statusHintsFor +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins which commands the status bar may suggest, and in which document states. + * + * The status bar recomputes its suggestions when the registered table (and so the document), the editor + * mode, the hovered space, or the keymap changes - and on nothing else, because a command's availability + * is a live query the composition cannot observe. So a hinted command's availability, and its hint's + * suggestedWhen, may depend on the document and the mode ALONE. One that also read the selection, an + * armed tool, or the atlas would leave its suggestion standing (or missing) until the pointer next + * crossed into another space. + * + * What a predicate reads is nothing a test can derive, so the hinted table is pinned whole instead. A + * command that gains a hint must change this map, which is the moment to check that both of its + * predicates answer from the document and the mode and nothing more. + */ +class StatusHintTableTest { + /** + * When a hinted command is suggested, across the three states the status bar recomputes on. + * + * @property Boolean noDocument Whether it is suggested with no document open. + * @property Boolean objectMode Whether it is suggested in Object mode. + * @property Boolean editMode Whether it is suggested in Edit mode. + */ + private data class SuggestedIn(val noDocument: Boolean, val objectMode: Boolean, val editMode: Boolean) + + /** + * Whether each hinted command is suggested over [session], by id: available, and its hint worth + * suggesting. The space is left out on purpose - CommandSpacesTableTest pins that dimension. + * + * @param EditorSession? session The session the tables close over, or null for no document. + * @return Map Every hinted command's id with whether it is suggested. + */ + private fun suggestedById(session: EditorSession?): Map = + everyCommandTable(session) + .mapNotNull { command -> + command.hint?.let { hint -> command.id to (command.availability.isAvailable() && hint.suggestedWhen.isAvailable()) } + }.toMap() + + /** The hinted commands, each with the states it is suggested in; every other command carries no hint. */ + @Test + fun theHintedCommandsAreExactlyThese() { + val inObjectModeOnly = SuggestedIn(noDocument = false, objectMode = true, editMode = false) + val inEditModeOnly = SuggestedIn(noDocument = false, objectMode = false, editMode = true) + val withADocument = SuggestedIn(noDocument = false, objectMode = true, editMode = true) + val expected = + mapOf( + "mode.toggleEdit" to inObjectModeOnly, + "object.toggleVisibility" to inObjectModeOnly, + "mesh.grab" to withADocument, + "mesh.scale" to withADocument, + "mesh.rotate" to withADocument, + "mesh.selectMode.vertex" to inEditModeOnly, + "mesh.selectMode.edge" to inEditModeOnly, + "mesh.selectMode.face" to inEditModeOnly, + "uv.pinPlacement" to inObjectModeOnly, + "keyform.insert" to withADocument, + "keyform.delete" to withADocument, + ) + val noDocument = suggestedById(null) + val objectMode = suggestedById(commandFixtureSession(EditorMode.Object)) + val editMode = suggestedById(commandFixtureSession(EditorMode.Edit)) + val actual = + noDocument.keys.associateWith { id -> + SuggestedIn(noDocument = noDocument.getValue(id), objectMode = objectMode.getValue(id), editMode = editMode.getValue(id)) + } + + assertEquals(expected, actual) + } + + /** + * Over a viewport under the default keymap, each mode reads as its own short list: the way into Edit + * mode and the visibility toggle from Object mode, the element domains from Edit mode. + */ + @Test + fun eachModeSuggestsItsOwnListOverAViewport() { + val transforms = listOf(Res.string.status_bind_grab, Res.string.status_bind_scale, Res.string.status_bind_rotate) + val objectHints = statusHintsFor(everyCommandTable(commandFixtureSession(EditorMode.Object)), defaultKeymap(), SpaceKind.Viewport2D) + val editHints = statusHintsFor(everyCommandTable(commandFixtureSession(EditorMode.Edit)), defaultKeymap(), SpaceKind.Viewport2D) + + assertEquals(transforms + Res.string.status_bind_edit_mode + Res.string.status_bind_visibility, objectHints.map { hint -> hint.label }) + assertEquals(transforms + Res.string.status_select_mode, editHints.map { hint -> hint.label }) + } + + /** + * Under the default keymap no space, in either mode, has more to suggest than the strip shows. The + * cut drops the trailing suggestions without a trace, so a hint that pushes a list past the limit + * fails here by name instead of quietly taking another off the bar. + */ + @Test + fun noSuggestionIsCutUnderTheDefaultKeymap() { + for (mode in EditorMode.entries) { + val commands = everyCommandTable(commandFixtureSession(mode)) + for (kind in SpaceKind.entries) { + val uncut = everyStatusHintFor(commands, defaultKeymap(), kind) + assertTrue(uncut.size <= STATUS_HINT_LIMIT, "$kind in $mode mode has ${uncut.size} suggestions, and the strip shows $STATUS_HINT_LIMIT") + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/rowdrag/RowDragControllerTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/rowdrag/RowDragControllerTest.kt new file mode 100644 index 0000000..84de678 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/rowdrag/RowDragControllerTest.kt @@ -0,0 +1,69 @@ +package org.umamo.ui.workspace.rowdrag + +import androidx.compose.ui.geometry.Rect +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The shared row drag state's hit-test: the target is whatever visible row the pointer's Y is over + * except the dragged row, a shared edge belongs to the lower row only, empty space is no target, a + * fresh grab starts with none, and cancelling clears everything at once. + */ +class RowDragControllerTest { + private fun controllerOverThreeRows(): RowDragController = + RowDragController().apply { + reportBounds("a", Rect(0f, 0f, 100f, 20f)) + reportBounds("b", Rect(0f, 20f, 100f, 40f)) + reportBounds("c", Rect(0f, 40f, 100f, 60f)) + } + + @Test + fun theTargetIsTheRowUnderThePointerNeverTheDraggedOne() { + val controller = controllerOverThreeRows() + assertNull(controller.dropTargetKey, "nothing is dragged") + controller.start("a", "payload-a", windowX = 10f, windowY = 5f) + assertTrue(controller.isDragging) + assertEquals("payload-a", controller.draggedPayload) + assertNull(controller.dropTargetKey, "a fresh grab sits on its own row, which is no target") + controller.drag(10f, 30f) + assertEquals("b", controller.dropTargetKey) + assertEquals(0.5f, controller.dropTargetFraction) + controller.drag(10f, 5f) + assertNull(controller.dropTargetKey, "back over the dragged row is no target again") + controller.drag(10f, 95f) + assertNull(controller.dropTargetKey, "empty space below every row") + assertNull(controller.dropTargetFraction) + } + + @Test + fun aSharedEdgeBelongsToTheLowerRowOnly() { + val controller = controllerOverThreeRows() + controller.start("a", "payload-a", 10f, 5f) + controller.drag(10f, 40f) + assertEquals("c", controller.dropTargetKey, "y == 40 is c's top edge, not b's bottom") + assertEquals(0f, controller.dropTargetFraction) + controller.drag(10f, 39.5f) + assertEquals("b", controller.dropTargetKey) + } + + @Test + fun cancelClearsTheDragAndScrolledOffRowsStopBeingTargets() { + val controller = controllerOverThreeRows() + controller.start("a", "payload-a", 10f, 5f) + controller.drag(10f, 50f) + assertEquals("c", controller.dropTargetKey) + controller.clearBounds("c") + assertNull(controller.dropTargetKey, "a row that left composition cannot take a drop") + controller.drag(10f, 30f) + controller.cancel() + assertFalse(controller.isDragging) + assertNull(controller.draggingKey) + assertNull(controller.draggedPayload) + assertNull(controller.dropTargetKey, "no drag, no target, however the pointer moves") + controller.drag(10f, 30f) + assertNull(controller.dropTargetKey) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetClickSelectionTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetClickSelectionTest.kt new file mode 100644 index 0000000..32b6b2b --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetClickSelectionTest.kt @@ -0,0 +1,60 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.TrackKeyRef +import org.umamo.runtime.model.ParameterId +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * What a Shift+click does to the keyform sheet's selection. + * + * The UI test can only reach as far as "Shift arrived at the callback"; the rule the sheet applies after + * that is the part with a decision in it, so it is pinned here where no composition is needed. + */ +class KeyformSheetClickSelectionTest { + private val angleX = ParameterId("ParamAngleX") + + /** A key on the geometry row at [ordinal]. */ + private fun key(ordinal: Int): TrackKeyRef = TrackKeyRef(angleX, "drawable:d/geometry", ordinal) + + /** Shift+click ADDS an unselected mark, leaving everything already selected alone. */ + @Test + fun anUnselectedMarkIsAdded() { + assertEquals(setOf(key(0), key(2)), selectionAfterAdditiveClick(setOf(key(0)), setOf(key(2)))) + assertEquals(setOf(key(1)), selectionAfterAdditiveClick(emptySet(), setOf(key(1))), "from nothing selected") + } + + /** + * Shift+click REMOVES an already-selected mark. + * + * Toggle rather than add-only: this is the only gesture that can take one mark back out of a selection + * without starting over, and without it a mis-click is unrecoverable except by rebuilding the whole set. + */ + @Test + fun anAlreadySelectedMarkIsRemoved() { + assertEquals(setOf(key(0)), selectionAfterAdditiveClick(setOf(key(0), key(2)), setOf(key(2)))) + assertEquals(emptySet(), selectionAfterAdditiveClick(setOf(key(2)), setOf(key(2))), "down to nothing") + } + + /** + * A summary mark toggles as ONE unit, and a partly-selected one COMPLETES rather than clearing. + * + * A collapsed group shows the user a single mark standing for several keys; removing only some of them + * would leave a selection whose state the mark cannot express. Treating partly-selected as "not + * selected" is what lets a second Shift+click undo the first. + */ + @Test + fun aSummaryTogglesAsOneUnit() { + val members = setOf(key(0), key(1), key(2)) + assertEquals(members, selectionAfterAdditiveClick(emptySet(), members), "none selected -> all") + assertEquals(members, selectionAfterAdditiveClick(setOf(key(1)), members), "partly selected -> all") + assertEquals(emptySet(), selectionAfterAdditiveClick(members, members), "all selected -> none") + } + + /** A mark standing for nothing leaves the selection exactly as it was, rather than clearing it. */ + @Test + fun anEmptyClickChangesNothing() { + val selection = setOf(key(0), key(1)) + assertEquals(selection, selectionAfterAdditiveClick(selection, emptySet())) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetMarqueeTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetMarqueeTest.kt new file mode 100644 index 0000000..9279a94 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetMarqueeTest.kt @@ -0,0 +1,128 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.ui.geometry.Rect +import org.umamo.edit.TrackKeyRef +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.tracks.TrackWindow +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The box-select marquee's region -> keys resolution. + * + * Worth its own suite because the mapping has to agree with what is DRAWN, not with the model: a marquee + * that reads the full parameter domain while the lanes draw a zoomed window selects the wrong keys, and one + * that walks the whole row tree selects keys inside groups the user has folded away. Neither is visible + * from outside the function, and neither shows up as a crash. + */ +class KeyformSheetMarqueeTest { + private val angleX = ParameterId("ParamAngleX") + private val parameter = Parameter(angleX, "ParamAngleX", min = -10f, max = 10f, default = 0f) + + /** Chrome-free labels: the projection is Compose-free, so tests inject plain strings. */ + private fun labels(): KeyformTrackLabels = + KeyformTrackLabels( + channelName = { channel -> channel.name }, + geometry = "Geometry", + blendShape = "Blend Shape", + ownerKindName = { kind -> kind.name }, + ) + + /** A glue with one intensity track keyed at -10, 0 and 10 - three marks spread across the domain. */ + private fun model(): PuppetModel = + PuppetModel( + parameters = listOf(parameter), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + glues = + listOf( + Glue( + DrawableId("a"), + DrawableId("b"), + emptyList(), + ChannelGrids( + mapOf( + FormChannel.GLUE_INTENSITY to + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-10f, 0f, 10f))), + listOf>( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(0f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(0.5f)), + KeyformCell(intArrayOf(2), ChannelValue.Scalar(1f)), + ), + ), + ), + ), + ), + ), + ) + + private val trackRowKey = "glue:a:b/GLUE_INTENSITY" + private val groupRowKey = "glue:a:b" + + /** A 100px-wide lane at the window origin, the shape the marquee resolves against. */ + private val laneRect = Rect(0f, 0f, 100f, 20f) + + /** + * A zoomed sheet resolves marks against the WINDOW, not the full range. + * + * The lanes draw `window.axisOver(fullAxis)`, so reading the full domain here put every mark at the x + * it would have had unzoomed - selecting a different key, or none. + */ + @Test + fun aZoomedSheetResolvesAgainstTheVisibleWindow() { + val projection = keyformSheetRows(model(), angleX, labels()) + val bounds = mapOf(trackRowKey to laneRect) + // The right half of -10..10, so the visible domain is 0..10 and the key at 0 sits at the far LEFT. + val zoomed = TrackWindow(start = 0.5f, end = 1f) + val leftEdge = Rect(0f, 0f, 20f, 20f) + + val enclosed = + keysWithin(leftEdge, listOf(parameter to projection), bounds, markRadiusPx = 4f, window = zoomed, expandedKeys = setOf(groupRowKey), collapsedParameters = emptySet()) + assertEquals(setOf(TrackKeyRef(angleX, trackRowKey, 1)), enclosed, "the key at 0 is what the left edge shows when zoomed right") + + val unzoomed = + keysWithin(leftEdge, listOf(parameter to projection), bounds, markRadiusPx = 4f, window = TrackWindow.Full, expandedKeys = setOf(groupRowKey), collapsedParameters = emptySet()) + assertEquals(setOf(TrackKeyRef(angleX, trackRowKey, 0)), unzoomed, "unzoomed the same band shows the key at -10") + } + + /** + * A collapsed group's child keys are NOT selectable, even though their lane bounds are still on record. + * + * laneBounds is never pruned - a lane that leaves composition simply stops reporting - so a collapsed + * group's children keep their last rectangles forever. Walking the tree blind kept hitting them, and a + * following Delete then edited tracks the user could not see. + */ + @Test + fun collapsedRowsAreNotSelectable() { + val projection = keyformSheetRows(model(), angleX, labels()) + val bounds = mapOf(trackRowKey to laneRect) + val wholeLane = Rect(0f, 0f, 100f, 20f) + + val expanded = + keysWithin(wholeLane, listOf(parameter to projection), bounds, markRadiusPx = 4f, window = TrackWindow.Full, expandedKeys = setOf(groupRowKey), collapsedParameters = emptySet()) + assertTrue(expanded.isNotEmpty(), "expanded, the track's keys are in reach") + + val collapsed = + keysWithin(wholeLane, listOf(parameter to projection), bounds, markRadiusPx = 4f, window = TrackWindow.Full, expandedKeys = emptySet(), collapsedParameters = emptySet()) + assertTrue(collapsed.isEmpty(), "collapsed, its stale lane bounds must not put hidden keys in the selection") + + val foldedSection = + keysWithin(wholeLane, listOf(parameter to projection), bounds, markRadiusPx = 4f, window = TrackWindow.Full, expandedKeys = setOf(groupRowKey), collapsedParameters = setOf(angleX)) + assertTrue(foldedSection.isEmpty(), "a folded section is not on screen at all") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetRowsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetRowsTest.kt new file mode 100644 index 0000000..807d466 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/KeyformSheetRowsTest.kt @@ -0,0 +1,309 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.Glue +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.KeyformTrackRef +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpLatticeForm +import org.umamo.ui.tracks.TrackRow +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Pins the sheet projection's row identities and mark flags: glue rows are keyed by the mesh PAIR (the + * stable identity KeyformOwner.Glue itself encodes), and blend-shape marks are not editable (they have + * no track ref, so none of the sheet's ops can apply to them). + */ +class KeyformSheetRowsTest { + private val angleX = ParameterId("ParamAngleX") + + /** Chrome-free labels: the projection is Compose-free, so tests inject plain strings. */ + private fun labels(): KeyformTrackLabels = + KeyformTrackLabels( + channelName = { channel -> channel.name }, + geometry = "Geometry", + blendShape = "Blend Shape", + ownerKindName = { kind -> kind.name }, + ) + + /** A single-axis intensity track on angleX, so a glue owner has rows to project. */ + private fun intensityTrack(): KeyformGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf>( + KeyformCell(intArrayOf(0), ChannelValue.Scalar(0.5f)), + KeyformCell(intArrayOf(1), ChannelValue.Scalar(1f)), + ), + ) + + /** A glue welding [meshA] and [meshB] with a keyed intensity track. */ + private fun glue(meshA: String, meshB: String): Glue = + Glue(DrawableId(meshA), DrawableId(meshB), emptyList(), ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to intensityTrack()))) + + private val angleY = ParameterId("ParamAngleY") + + /** A model holding [glues], [drawables], and [deformers] under the listed [parameters]. */ + private fun model( + glues: List = emptyList(), + drawables: List = emptyList(), + deformers: List = emptyList(), + parameters: List = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)), + ): PuppetModel = + PuppetModel( + parameters = parameters, + parts = emptyList(), + deformers = deformers, + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + glues = glues, + ) + + /** Every row in the tree, flattened. */ + private fun allRows(rows: List): List = rows.flatMap { row -> listOf(row) + allRows(row.children) } + + /** + * Removing an earlier glue must not migrate a later glue's row keys: selection and collapse state key + * off the rowKey, and an ordinal key handed one glue's state to the next after a removal. + */ + @Test + fun glueRowKeysSurviveAnEarlierRemoval() { + val glueAB = glue("a", "b") + val glueCD = glue("c", "d") + val bothProjection = keyformSheetRows(model(glues = listOf(glueAB, glueCD)), angleX, labels()) + val cdOnlyProjection = keyformSheetRows(model(glues = listOf(glueCD)), angleX, labels()) + + val cdKeysBefore = bothProjection.tracksByRowKey.keys.filter { key -> key.startsWith("glue:c:d") } + val cdKeysAfter = cdOnlyProjection.tracksByRowKey.keys.filter { key -> key.startsWith("glue:c:d") } + assertTrue(cdKeysBefore.isNotEmpty(), "the glue's track rows are keyed by its mesh pair") + assertEquals(cdKeysBefore, cdKeysAfter, "removing another glue leaves this glue's row keys untouched") + } + + /** Glue group rows are labeled with the meshes' display names, not their raw ids. */ + @Test + fun glueRowsAreLabeledWithDisplayNames() { + val eyeLeft = + Drawable( + id = DrawableId("a"), + name = "Eye L", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + val eyeRight = eyeLeft.copy(id = DrawableId("b"), name = "Eye R") + val projection = keyformSheetRows(model(glues = listOf(glue("a", "b")), drawables = listOf(eyeLeft, eyeRight)), angleX, labels()) + + val glueGroupRow = allRows(projection.rows).first { row -> row.key == "glue:a:b" } + assertEquals("Eye L ↔ Eye R", glueGroupRow.label) + } + + /** A drawable carrying all three track kinds at once, so a filter has something of each to drop. */ + private fun drawableWithEveryTrackKind(): Drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf( + KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))), + KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(1f, 0f))), + ), + ), + channelGrids = ChannelGrids(mapOf(FormChannel.OPACITY to intensityTrack())), + blendShapes = + listOf( + BlendShapeBinding( + parameterId = angleX, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, MeshForm(floatArrayOf(0f, 0f))), + ), + ), + ) + + /** + * Each filter flag drops exactly its own kind of child row and leaves the other two alone. + * + * Gated while BUILDING the projection rather than while drawing, so a hidden track is absent from the + * tree entirely - which is what keeps a summary mark from standing for a key the sheet is not showing. + */ + @Test + fun eachFilterFlagDropsOnlyItsOwnRows() { + val puppet = model(drawables = listOf(drawableWithEveryTrackKind())) + val unfiltered = allRows(keyformSheetRows(puppet, angleX, labels()).rows) + assertTrue(unfiltered.any { row -> row.key.endsWith("/geometry") }, "the unfiltered sheet lists geometry") + assertTrue(unfiltered.any { row -> row.key.endsWith("/OPACITY") }, "and the channel track") + assertTrue(unfiltered.any { row -> row.key.contains("/blend") }, "and the blend shape") + + val withoutGeometry = allRows(keyformSheetRows(puppet, angleX, labels(), KeyformTrackFilter(geometry = false)).rows) + assertFalse(withoutGeometry.any { row -> row.key.endsWith("/geometry") }, "the geometry row is gone") + assertTrue(withoutGeometry.any { row -> row.key.endsWith("/OPACITY") }, "the channel row is untouched") + assertTrue(withoutGeometry.any { row -> row.key.contains("/blend") }, "so is the blend row") + + val withoutChannels = allRows(keyformSheetRows(puppet, angleX, labels(), KeyformTrackFilter(channels = false)).rows) + assertFalse(withoutChannels.any { row -> row.key.endsWith("/OPACITY") }, "the channel row is gone") + assertTrue(withoutChannels.any { row -> row.key.endsWith("/geometry") }, "the geometry row is untouched") + + val withoutBlends = allRows(keyformSheetRows(puppet, angleX, labels(), KeyformTrackFilter(blendShapes = false)).rows) + assertFalse(withoutBlends.any { row -> row.key.contains("/blend") }, "the blend row is gone") + assertTrue(withoutBlends.any { row -> row.key.endsWith("/geometry") }, "the geometry row is untouched") + } + + /** + * An owner filtered down to nothing loses its group row too, rather than sitting there empty. + * + * The group row is a disclosure for its children; an expandable row that expands into nothing reads as + * a bug, and its summary marks would stand for keys the sheet is deliberately not showing. + */ + @Test + fun anOwnerWithEveryTrackFilteredOutLosesItsGroupRow() { + val puppet = model(glues = listOf(glue("a", "b"))) + assertTrue( + allRows(keyformSheetRows(puppet, angleX, labels()).rows).any { row -> row.key == "glue:a:b" }, + "the glue's only tracks are channels, so unfiltered it has a group row", + ) + val filtered = keyformSheetRows(puppet, angleX, labels(), KeyformTrackFilter(channels = false)) + assertTrue(filtered.rows.isEmpty(), "with channels hidden the glue has no children left, so no group row either") + } + + /** + * The projection reports whether a filter actually DROPPED something, not merely that one is off. + * + * "Nothing is keyed here" and "you hid it" are opposite diagnoses; a flag that is off but hides nothing + * on this rig must not make an empty sheet blame the filter for a rig that simply keys nothing. + */ + @Test + fun theProjectionReportsWhetherTheFilterDroppedAnything() { + val puppet = model(drawables = listOf(drawableWithEveryTrackKind())) + assertFalse(keyformSheetRows(puppet, angleX, labels()).hiddenByFilter, "nothing is filtered by default") + assertTrue( + keyformSheetRows(puppet, angleX, labels(), KeyformTrackFilter(geometry = false)).hiddenByFilter, + "the drawable has a geometry track, so hiding geometry hid something", + ) + + // A rig with only channel tracks: hiding GEOMETRY takes nothing away from it, so the sheet must not + // claim a filter is responsible for what it shows. + val glueOnly = model(glues = listOf(glue("a", "b"))) + assertFalse( + keyformSheetRows(glueOnly, angleX, labels(), KeyformTrackFilter(geometry = false)).hiddenByFilter, + "a glue has no geometry track, so the geometry filter dropped nothing", + ) + assertTrue(keyformSheetRows(glueOnly, angleX, labels(), KeyformTrackFilter(channels = false)).hiddenByFilter) + } + + /** Every group row carries the owner it names, so its own menu can act on the thing rather than a track. */ + @Test + fun groupRowsCarryTheirOwner() { + val puppet = model(drawables = listOf(drawableWithEveryTrackKind()), glues = listOf(glue("a", "b"))) + val projection = keyformSheetRows(puppet, angleX, labels()) + assertEquals(KeyformOwner.Drawable(DrawableId("d")), projection.ownerByRowKey["drawable:d"]) + assertEquals(KeyformOwner.Glue(DrawableId("a"), DrawableId("b")), projection.ownerByRowKey["glue:a:b"]) + assertEquals( + projection.ownerKindByRowKey.keys, + projection.ownerByRowKey.keys, + "the two group-row maps are keyed alike - a row with an icon but no owner would show a dead menu", + ) + } + + /** + * A warp keyed on Angle X still gets an empty Geometry lane under Angle Y (or any other parameter), + * so the sheet can bind that owner without hovering a different section first. + */ + @Test + fun aWarpOffersGeometryOnAParameterItDoesNotYetKey() { + val warp = + Deformer.Warp( + id = DeformerId("w"), + name = "Head", + parent = null, + partId = null, + rows = 2, + columns = 2, + isQuadTransform = true, + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf( + KeyformCell(intArrayOf(0), WarpLatticeForm(FloatArray(8))), + KeyformCell(intArrayOf(1), WarpLatticeForm(FloatArray(8))), + ), + ), + ) + val puppet = + model( + deformers = listOf(warp), + parameters = + listOf( + Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f), + Parameter(angleY, angleY.raw, min = -1f, max = 1f, default = 0f), + ), + ) + val onAngleX = keyformSheetRows(puppet, angleX, labels()) + val geometryOnX = assertNotNull(allRows(onAngleX.rows).firstOrNull { row -> row.key == "deformer:w/geometry" }) + assertEquals(2, geometryOnX.marks.size, "Angle X already has keys") + + val onAngleY = keyformSheetRows(puppet, angleY, labels()) + val geometryOnY = assertNotNull(allRows(onAngleY.rows).firstOrNull { row -> row.key == "deformer:w/geometry" }) + assertTrue(geometryOnY.marks.isEmpty(), "Angle Y shows an empty Geometry lane ready to bind") + assertEquals(KeyformTrackRef.Geometry(KeyformOwner.Deformer(DeformerId("w"))), onAngleY.tracksByRowKey["deformer:w/geometry"]) + } + + /** + * Blend-shape marks are NOT editable: the row has no track ref, so an editable mark would accept a + * drag that silently reverts and a selection that Delete can never resolve. + */ + @Test + fun blendShapeMarksAreNotEditable() { + val binding = + BlendShapeBinding( + parameterId = angleX, + keys = floatArrayOf(0f, 1f), + neutralIndex = 0, + forms = listOf(null, MeshForm(floatArrayOf(0f, 0f))), + ) + val drawable = + Drawable( + id = DrawableId("d"), + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + blendShapes = listOf(binding), + ) + val projection = keyformSheetRows(model(drawables = listOf(drawable)), angleX, labels()) + + val blendRows = allRows(projection.rows).filter { row -> row.key.contains("/blend") } + assertTrue(blendRows.isNotEmpty(), "the binding projects a blend row") + val blendMarks = blendRows.flatMap { row -> row.marks } + assertTrue(blendMarks.isNotEmpty(), "the blend row carries its key marks") + assertTrue(blendMarks.none { mark -> mark.editable }, "no blend mark may accept a drag or a selection") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/OutlinerTreeTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/OutlinerTreeTest.kt new file mode 100644 index 0000000..5b19955 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/OutlinerTreeTest.kt @@ -0,0 +1,256 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Unit-tests [buildOutlinerTree]: the unified Blender-style tree (root → Armature deformer hierarchy + + * the org tree's interleaved parts / drawables). Corpus-free - a hand-built rig exercises deformer + * nesting, the interleaved child order read straight off the org tree, the dim rules, and the synthetic + * rows' null selection targets. + */ +class OutlinerTreeTest { + private fun part(id: String, name: String, children: List = emptyList(), visible: Boolean = true, sketch: Boolean = false) = + Part(PartId(id), name, children, isVisible = visible, isSketch = sketch) + + private fun drawable(id: String, name: String, visible: Boolean = true) = + Drawable(DrawableId(id), name, null, BlendMode.Normal, emptyList(), null, null, isVisible = visible) + + private fun warp(id: String, name: String, parent: String?) = + Deformer.Warp(DeformerId(id), name, parent?.let(::DeformerId), null, 1, 1, true, null) + + private fun rotation(id: String, name: String, parent: String?) = + Deformer.Rotation(DeformerId(id), name, parent?.let(::DeformerId), null, 0f, null) + + private fun model(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + part("front_hair", "Front Hair", listOf(OrgChild.Drawable(DrawableId("mesh_fh")))), + part("head", "Head", listOf(OrgChild.Drawable(DrawableId("mesh_head")), OrgChild.Part(PartId("hair_inner")))), + part("hair_inner", "Hair Inner", visible = false), // child of head, hidden -> dimmed + part("guide", "[Guide Image]", sketch = true), // root, sketch -> dimmed + ), + deformers = + listOf( + warp("w_root", "Root Warp", parent = null), + rotation("r_child", "Child Rotation", parent = "w_root"), + ), + drawables = + listOf( + drawable("mesh_fh", "Front Hair Mesh"), + drawable("mesh_head", "Head Mesh", visible = false), // own eyeball off -> dimmed + ), + rootChildren = listOf(OrgChild.Part(PartId("front_hair")), OrgChild.Part(PartId("head")), OrgChild.Part(PartId("guide"))), + rootPartId = null, + ) + + @Test + fun rootHoldsArmatureThenTopLevelPartsInOrder() { + val root = buildOutlinerTree(model(), rootLabel = "Puppet", armatureLabel = "Armature") + + assertEquals("Puppet", root.label) + assertEquals(OutlinerIcon.PuppetRoot, root.icon) + assertNull(root.target, "the puppet root only expands, it does not select") + + // First child is the Armature node; the rest are the root org children in their tree order. + assertEquals( + listOf("armature", "part:front_hair", "part:head", "part:guide"), + root.children.map { it.id }, + ) + } + + @Test + fun rootReadsInterleavedPartsAndDrawablesFromTree() { + // Cubism panel order: part a, a loose root mesh, part b - read straight off rootChildren. + val puppet = + PuppetModel( + parameters = emptyList(), + parts = listOf(part("a", "A"), part("b", "B")), + deformers = emptyList(), + drawables = listOf(drawable("loose", "Loose")), + rootChildren = listOf(OrgChild.Part(PartId("a")), OrgChild.Drawable(DrawableId("loose")), OrgChild.Part(PartId("b"))), + rootPartId = null, + ) + val root = buildOutlinerTree(puppet, rootLabel = "Puppet", armatureLabel = "Armature") + + assertEquals(listOf("armature", "part:a", "drawable:loose", "part:b"), root.children.map { it.id }) + } + + @Test + fun partReadsInterleavedChildOrderFromTree() { + // Inside "Head": drawable d1, sub-part Inner, drawable d2 - the sub-part sits between the meshes. + val puppet = + PuppetModel( + parameters = emptyList(), + parts = + listOf( + part( + "head", + "Head", + listOf(OrgChild.Drawable(DrawableId("d1")), OrgChild.Part(PartId("inner")), OrgChild.Drawable(DrawableId("d2"))), + ), + part("inner", "Inner"), + ), + deformers = emptyList(), + drawables = listOf(drawable("d1", "D1"), drawable("d2", "D2")), + rootChildren = listOf(OrgChild.Part(PartId("head"))), + rootPartId = null, + ) + val head = buildOutlinerTree(puppet).children.first { it.id == "part:head" } + + assertEquals(listOf("drawable:d1", "part:inner", "drawable:d2"), head.children.map { it.id }) + } + + @Test + fun armatureNestsDeformersByParent() { + val armature = buildOutlinerTree(model()).children.first { it.id == "armature" } + + assertEquals(OutlinerIcon.Armature, armature.icon) + assertNull(armature.target) + assertEquals(listOf("deformer:w_root"), armature.children.map { it.id }) + + val warpNode = armature.children.single() + assertEquals("Root Warp", warpNode.label) + assertEquals(OutlinerIcon.WarpDeformer, warpNode.icon) + + val rotationNode = warpNode.children.single() + assertEquals(OutlinerIcon.RotationDeformer, rotationNode.icon) + assertEquals(SelectionTarget.Deformer(DeformerId("r_child")), rotationNode.target) + } + + @Test + fun partListsItsChildrenInTreeOrderAndUsesNames() { + val head = buildOutlinerTree(model()).children.first { it.id == "part:head" } + + assertEquals(SelectionTarget.Part(PartId("head")), head.target) + // The org tree puts the drawable before the sub-part here. + assertEquals(listOf("drawable:mesh_head", "part:hair_inner"), head.children.map { it.id }) + assertEquals("Head Mesh", head.children.first().label) + } + + @Test + fun dimsHiddenAndSketchRows() { + val root = buildOutlinerTree(model()) + val guide = root.children.first { it.id == "part:guide" } + val head = root.children.first { it.id == "part:head" } + val hiddenDrawable = head.children.first { it.id == "drawable:mesh_head" } + val hiddenChildPart = head.children.first { it.id == "part:hair_inner" } + val visibleDrawable = root.children.first { it.id == "part:front_hair" }.children.single() + + assertTrue(guide.dimmed, "sketch part is dimmed") + assertTrue(hiddenDrawable.dimmed, "hidden drawable is dimmed") + assertTrue(hiddenChildPart.dimmed, "hidden part is dimmed") + assertTrue(!visibleDrawable.dimmed, "a visible drawable is not dimmed") + } + + @Test + fun filterHidesArmatureWhenDeformersToggledOff() { + val filtered = filterOutliner(buildOutlinerTree(model()), query = "", showParts = true, showDrawables = true, showDeformers = false) + + assertTrue(filtered.children.none { it.id == "armature" }, "the Armature subtree is removed") + assertTrue(filtered.children.any { it.id == "part:front_hair" }, "parts remain") + } + + @Test + fun filterHidesDrawableRowsWhenDrawablesToggledOff() { + val filtered = filterOutliner(buildOutlinerTree(model()), query = "", showParts = true, showDrawables = false, showDeformers = true) + + val frontHair = filtered.children.first { it.id == "part:front_hair" } + assertTrue(frontHair.children.isEmpty(), "drawables under the part are removed") + assertTrue(filtered.children.any { it.id == "armature" }, "the Armature subtree remains") + } + + @Test + fun filterHoistsDrawablesWhenPartsToggledOff() { + val filtered = filterOutliner(buildOutlinerTree(model()), query = "", showParts = false, showDrawables = true, showDeformers = true) + + // No part / folder rows survive; their drawables flatten up under the root next to the Armature. + assertTrue(filtered.children.none { it.id.startsWith("part:") }, "part rows are removed") + assertEquals(listOf("armature", "drawable:mesh_fh", "drawable:mesh_head"), filtered.children.map { it.id }) + } + + @Test + fun searchKeepsOnlyThePathToMatchesAndDropsUnrelatedChildren() { + val filtered = filterOutliner(buildOutlinerTree(model()), query = "head", showParts = true, showDrawables = true, showDeformers = true) + + // Only the matching part survives at the top level; Armature / Front Hair / Guide are dropped. + assertEquals(listOf("part:head"), filtered.children.map { it.id }) + // A matched part keeps only its matching descendant ("Head Mesh"); the unrelated sub-part is dropped. + assertEquals(listOf("drawable:mesh_head"), filtered.children.single().children.map { it.id }) + } + + @Test + fun searchKeepsNonMatchingAncestorsAsThePathToADeepMatch() { + // "Child Rotation" is nested under "Root Warp" under Armature; only that path survives. + val filtered = filterOutliner(buildOutlinerTree(model()), query = "child", showParts = true, showDrawables = true, showDeformers = true) + + assertEquals(listOf("armature"), filtered.children.map { it.id }) + val warp = filtered.children.single().children.single() + assertEquals("deformer:w_root", warp.id) // kept as an ancestor though "Root Warp" does not match + assertEquals(listOf("deformer:r_child"), warp.children.map { it.id }) + } + + @Test + fun armatureNodePresentEvenWithNoDeformers() { + val empty = PuppetModel(emptyList(), emptyList(), emptyList(), emptyList(), emptyList(), null) + val root = buildOutlinerTree(empty) + + val armature = root.children.single() + assertEquals("armature", armature.id) + assertTrue(armature.children.isEmpty()) + } + + private val partA = SelectionTarget.Part(PartId("a")) + private val meshB = SelectionTarget.Drawable(DrawableId("b")) + private val meshC = SelectionTarget.Drawable(DrawableId("c")) + private val partD = SelectionTarget.Part(PartId("d")) + + @Test + fun rangeSelectAddsTheRunFromAnchorToClickInEitherDirection() { + // index: 0 1 2 3 4 + val ordered = listOf(null, partA, meshB, meshC, partD) + + val forward = outlinerRangeSelection(ordered, Selection(setOf(partA), partA), clickedIndex = 3, clickedTarget = meshC) + assertEquals(setOf(partA, meshB, meshC), forward.targets) + assertEquals(meshC, forward.active, "the clicked row becomes active") + + // Anchored at the clicked-from row, clicking upward selects the same run. + val backward = outlinerRangeSelection(ordered, Selection(setOf(meshC), meshC), clickedIndex = 1, clickedTarget = partA) + assertEquals(setOf(partA, meshB, meshC), backward.targets) + assertEquals(partA, backward.active) + } + + @Test + fun rangeSelectUnionsWithExistingSelectionAndSkipsNullRows() { + // A prior pick (partD) stays; the new range adds partA..meshB, skipping the synthetic null row. + val ordered = listOf(partA, null, meshB, partD) + val result = outlinerRangeSelection(ordered, Selection(setOf(partD, partA), partA), clickedIndex = 2, clickedTarget = meshB) + + assertEquals(setOf(partA, meshB, partD), result.targets) + assertEquals(meshB, result.active) + } + + @Test + fun rangeSelectWithNoAnchorSelectsOnlyTheClickedRow() { + val ordered = listOf(partA, meshB, meshC) + val result = outlinerRangeSelection(ordered, Selection(), clickedIndex = 1, clickedTarget = meshB) + + assertEquals(setOf(meshB), result.targets) + assertEquals(meshB, result.active) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterKeyMarksTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterKeyMarksTest.kt new file mode 100644 index 0000000..724488a --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterKeyMarksTest.kt @@ -0,0 +1,136 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pins the per-parameter key-mark index feeding the sliders: keyform-grid axis keys become circle + * marks and blend-shape binding keys become square marks; each parameter's list is the sorted, + * deduplicated union across every object, and an unkeyed parameter has no entry. + */ +class ParameterKeyMarksTest { + private val angleX = ParameterId("ParamAngleX") + private val shrink = ParameterId("ParamShrink") + private val unused = ParameterId("ParamUnused") + + /** A drawable keyed on [paramId]'s grid at [keys] (a single-axis grid, one cell per key). */ + private fun drawableGrid(id: String, paramId: ParameterId, keys: FloatArray): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = + KeyformGrid( + listOf(KeyformAxis(paramId, keys)), + keys.indices.map { keyIndex -> KeyformCell(intArrayOf(keyIndex), MeshDeltaForm(floatArrayOf(0f, 0f))) }, + ), + ) + + /** A bare drawable carrying [bindings] as its blend shapes (no grid). */ + private fun drawableBlend(id: String, bindings: List>): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ).copy(blendShapes = bindings) + + /** A warp deformer carrying [bindings] as its blend shapes (no grid). */ + private fun warpBlend(id: String, bindings: List>): Deformer.Warp = + Deformer.Warp( + id = DeformerId(id), + name = id, + parent = null, + partId = null, + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = null, + ).copy(blendShapes = bindings) + + private fun meshBinding(parameterId: ParameterId, keys: FloatArray, neutralIndex: Int): BlendShapeBinding = + BlendShapeBinding( + parameterId = parameterId, + keys = keys, + neutralIndex = neutralIndex, + forms = keys.indices.map { if (it == neutralIndex) null else MeshForm(floatArrayOf(0f, 0f)) }, + ) + + private fun warpBinding(parameterId: ParameterId, keys: FloatArray, neutralIndex: Int): BlendShapeBinding = + BlendShapeBinding( + parameterId = parameterId, + keys = keys, + neutralIndex = neutralIndex, + forms = keys.indices.map { if (it == neutralIndex) null else WarpForm(floatArrayOf(0f, 0f)) }, + ) + + private fun model(drawables: List, deformers: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = deformers, + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + ) + + /** Grid axes on the same parameter across objects union into one sorted, deduplicated circle list. */ + @Test + fun gridKeysUnionSortedAndDeduped() { + val puppet = + model( + drawables = + listOf( + drawableGrid("d1", angleX, floatArrayOf(0f, 1f)), + drawableGrid("d2", angleX, floatArrayOf(-1f, 0f, 1f)), + ), + deformers = emptyList(), + ) + + val marks = puppet.parameterKeyMarks() + assertEquals(listOf(-1f, 0f, 1f), marks[angleX]?.gridKeys, "grid keys are the sorted union across objects") + assertEquals(emptyList(), marks[angleX]?.blendKeys, "a key-form parameter has no square keys") + } + + /** Blend bindings on the same parameter across a drawable and a deformer union into one square list. */ + @Test + fun blendKeysGatherFromDrawablesAndDeformers() { + val puppet = + model( + drawables = listOf(drawableBlend("d", listOf(meshBinding(shrink, floatArrayOf(-1f, 0f), neutralIndex = 1)))), + deformers = listOf(warpBlend("w", listOf(warpBinding(shrink, floatArrayOf(0f, 1f), neutralIndex = 0)))), + ) + + val marks = puppet.parameterKeyMarks() + assertEquals(listOf(-1f, 0f, 1f), marks[shrink]?.blendKeys, "blend keys union drawable + deformer bindings (incl. neutral)") + assertEquals(emptyList(), marks[shrink]?.gridKeys, "a blend-shape parameter has no circle keys") + } + + /** A parameter no object keys is absent from the index. */ + @Test + fun unkeyedParameterHasNoEntry() { + val puppet = model(listOf(drawableGrid("d", angleX, floatArrayOf(0f))), emptyList()) + assertNull(puppet.parameterKeyMarks()[unused], "an unkeyed parameter contributes no marks") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterObjectBindingTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterObjectBindingTest.kt new file mode 100644 index 0000000..56d1392 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterObjectBindingTest.kt @@ -0,0 +1,182 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.BlendShapeBinding +import org.umamo.runtime.model.BlendWeightLimit +import org.umamo.runtime.model.BlendWeightLimitPoint +import org.umamo.runtime.model.Deformer +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.MeshDeltaForm +import org.umamo.runtime.model.MeshForm +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.WarpForm +import org.umamo.runtime.model.WarpLatticeForm +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the effective object -> parameters relation behind the filter: a drawable's set unions its own + * keyform axes with its whole parent deformer chain's, a deformer's unions its ancestors', and an empty + * selection yields nothing. + */ +class ParameterObjectBindingTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val angleZ = ParameterId("ParamAngleZ") + + /** A warp deformer keyed on [paramId] (a 1x1 grid), nesting under [parent]. */ + private fun warp(id: String, parent: DeformerId?, paramId: ParameterId): Deformer.Warp = + Deformer.Warp( + id = DeformerId(id), + name = id, + parent = parent, + partId = null, + rows = 1, + columns = 1, + isQuadTransform = true, + geometryGrid = KeyformGrid(listOf(KeyformAxis(paramId, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), WarpLatticeForm(floatArrayOf(0f, 0f))))), + ) + + /** A drawable under [parentDeformerId], keyed on [ownParamId] when non-null. */ + private fun drawable(id: String, parentDeformerId: DeformerId?, ownParamId: ParameterId?): Drawable = + Drawable( + id = DrawableId(id), + name = id, + parentDeformerId = parentDeformerId, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = + ownParamId?.let { + KeyformGrid(listOf(KeyformAxis(it, floatArrayOf(0f))), listOf(KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))))) + }, + ) + + /** A model holding [drawables] and [deformers]. */ + private fun model(drawables: List, deformers: List): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = deformers, + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + ) + + /** A selected drawable's set unions its own axis with every parent deformer's up the chain. */ + @Test + fun drawableInheritsParentDeformerChainAxes() { + // Chain: warp1 (angleX) <- warp2 (angleY); drawable keyed on angleZ, deformed by warp2. + val warp1 = warp("w1", parent = null, paramId = angleX) + val warp2 = warp("w2", parent = warp1.id, paramId = angleY) + val art = drawable("d", parentDeformerId = warp2.id, ownParamId = angleZ) + val puppet = model(listOf(art), listOf(warp1, warp2)) + + val result = effectiveParameterIds(puppet, Selection(setOf(SelectionTarget.Drawable(art.id)))) + assertEquals(setOf(angleX, angleY, angleZ), result) + } + + /** A selected deformer's set unions its own axis with its ancestors'. */ + @Test + fun deformerUnionsAncestors() { + val warp1 = warp("w1", parent = null, paramId = angleX) + val warp2 = warp("w2", parent = warp1.id, paramId = angleY) + val puppet = model(emptyList(), listOf(warp1, warp2)) + + val result = effectiveParameterIds(puppet, Selection(setOf(SelectionTarget.Deformer(warp2.id)))) + assertEquals(setOf(angleX, angleY), result, "the deformer contributes its own axis plus its parent's") + } + + /** An empty selection affects no parameters. */ + @Test + fun emptySelectionIsEmpty() { + val puppet = model(listOf(drawable("d", parentDeformerId = null, ownParamId = angleX)), emptyList()) + assertTrue(effectiveParameterIds(puppet, Selection()).isEmpty()) + } + + /** + * A blend-shape binding is an object -> parameter edge like a keyform axis: an object whose ONLY + * link to a parameter is a blend shape still lists it. Limit-curve constraint parameters are NOT + * edges - a limit gates the binding's weight, it does not key the object. + */ + @Test + fun blendShapeBindingsAreEdgesButLimitConstraintsAreNot() { + val shrink = ParameterId("ParamShrink") + val binding = + BlendShapeBinding( + parameterId = shrink, + keys = floatArrayOf(-1f, 0f), + neutralIndex = 1, + forms = listOf(WarpForm(floatArrayOf(0f, 0f)), null), + limits = listOf(BlendWeightLimit(angleX, listOf(BlendWeightLimitPoint(0f, 1f)))), + ) + val warpWithBlendShape = + warp("w1", parent = null, paramId = angleY).copy(blendShapes = listOf(binding)) + val meshBinding = + BlendShapeBinding( + parameterId = shrink, + keys = floatArrayOf(-1f, 0f), + neutralIndex = 1, + forms = listOf(MeshForm(floatArrayOf(0f, 0f)), null), + ) + val art = + drawable("d", parentDeformerId = warpWithBlendShape.id, ownParamId = null) + .copy(blendShapes = listOf(meshBinding)) + val puppet = model(listOf(art), listOf(warpWithBlendShape)) + + val drawableResult = effectiveParameterIds(puppet, Selection(setOf(SelectionTarget.Drawable(art.id)))) + assertEquals( + setOf(shrink, angleY), + drawableResult, + "drawable: own blend driver + chain's grid axis + chain's blend driver; limit param angleX excluded", + ) + val deformerResult = effectiveParameterIds(puppet, Selection(setOf(SelectionTarget.Deformer(warpWithBlendShape.id)))) + assertEquals(setOf(shrink, angleY), deformerResult, "deformer: own axis + own blend driver; limit param excluded") + } + + /** + * A glue's intensity track affects the drawables it welds: scrubbing its parameter visibly moves + * their vertices, so selecting either welded mesh must keep that parameter in the filtered list. + * Glues were the one owner this walk missed. + */ + @Test + fun glueIntensityCountsForItsWeldedDrawables() { + val meshA = drawable("a", parentDeformerId = null, ownParamId = null) + val meshB = drawable("b", parentDeformerId = null, ownParamId = angleZ) + val weld = + org.umamo.runtime.model.Glue( + meshA = meshA.id, + meshB = meshB.id, + pairs = emptyList(), + channelGrids = + org.umamo.runtime.model.ChannelGrids( + mapOf( + org.umamo.runtime.model.FormChannel.GLUE_INTENSITY to + KeyformGrid( + listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))), + listOf( + KeyformCell(intArrayOf(0), org.umamo.runtime.model.ChannelValue.Scalar(0.5f)), + KeyformCell(intArrayOf(1), org.umamo.runtime.model.ChannelValue.Scalar(1f)), + ), + ), + ), + ), + ) + val puppet = model(listOf(meshA, meshB), emptyList()).copy(glues = listOf(weld)) + + val result = effectiveParameterIds(puppet, Selection(setOf(SelectionTarget.Drawable(meshA.id)))) + assertEquals(setOf(angleX), result, "the weld's driving parameter counts for a welded drawable") + + val marks = puppet.parameterKeyMarks() + assertEquals(listOf(-1f, 1f), marks[angleX]?.gridKeys, "the glue's keys show as slider marks") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterRowsTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterRowsTest.kt new file mode 100644 index 0000000..90bcbae --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParameterRowsTest.kt @@ -0,0 +1,283 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterLink +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the pure Parameters-panel row model: link pairs fold into 2D pads (the vertical member is + * never emitted on its own), group boundaries flush runs, and the link-candidate rules - the + * candidate is the run's immediately-next parameter, refused when it is absent, not animatable, or + * when either side already belongs to any link (including a degenerate one). + */ +class ParameterRowsTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val angleZ = ParameterId("ParamAngleZ") + private val breath = ParameterId("ParamBreath") + + /** + * An animatable parameter over -1..1 (or a fixed one when [animatable] is false). + * + * @param ParameterId id The parameter id. + * @param Boolean animatable Whether the range is non-degenerate. + * @return Parameter The fixture parameter. + */ + private fun parameter(id: ParameterId, animatable: Boolean = true): Parameter = + Parameter(id, id.raw, min = if (animatable) -1f else 0f, max = if (animatable) 1f else 0f, default = 0f) + + /** + * An animatable parameter whose display name differs from its id - what the search tests need to tell + * a name match from an id match. + * + * @param ParameterId id The parameter id. + * @param String name The display name. + * @return Parameter The fixture parameter. + */ + private fun named(id: ParameterId, name: String): Parameter = Parameter(id, name, min = -1f, max = 1f, default = 0f) + + /** + * A drawable-less model holding just [parameters], [links], and an optional group [tree]. + * + * @param List parameters The parameters in document order. + * @param List links The parameter links. + * @param List tree The group tree (empty = the flat fallback). + * @return PuppetModel The fixture model. + */ + private fun model( + parameters: List, + links: List = emptyList(), + tree: List = emptyList(), + ): PuppetModel = + PuppetModel( + parameters = parameters, + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + parameterLinks = links, + parameterTree = tree, + ) + + /** + * The rows the panel would render for [puppet] with every group expanded as saved. + * + * @param PuppetModel puppet The fixture model. + * @return List The built rows. + */ + private fun rowsOf(puppet: PuppetModel): List = + buildParameterRows(puppet, buildLinkInfo(puppet), puppet.parameters.associateBy { it.id }, expanded = emptyMap()) + + /** + * The rows the panel would render for [puppet] under the "affects selection" filter set [visible]. + * + * @param PuppetModel puppet The fixture model. + * @param Set visible The visible-parameter filter set. + * @return List The filtered rows. + */ + private fun filteredRowsOf(puppet: PuppetModel, visible: Set): List = + buildParameterRows(puppet, buildLinkInfo(puppet), puppet.parameters.associateBy { it.id }, expanded = emptyMap(), visibleParamIds = visible) + + /** A linked pair folds into one Pair2D and its vertical member is never emitted as a Single. */ + @Test + fun linkedPairFoldsIntoPad() { + val puppet = + model( + parameters = listOf(parameter(angleX), parameter(angleY), parameter(breath)), + links = listOf(ParameterLink(angleX, angleY)), + ) + val rows = rowsOf(puppet) + assertEquals(2, rows.size) + val pad = rows[0] as ParameterRow.Pair2D + assertEquals(angleX, pad.horizontal.id) + assertEquals(angleY, pad.vertical.id) + assertTrue(rows.none { row -> row is ParameterRow.Single && row.parameter.id == angleY }) + } + + /** In the flat fallback, adjacent unlinked animatable parameters are link candidates of each other. */ + @Test + fun adjacentUnlinkedParametersAreCandidates() { + val puppet = model(parameters = listOf(parameter(angleX), parameter(angleY))) + val rows = rowsOf(puppet) + assertEquals(angleY, (rows[0] as ParameterRow.Single).linkCandidateId) + assertNull((rows[1] as ParameterRow.Single).linkCandidateId, "the last parameter has nothing below to link") + } + + /** A non-animatable next parameter is not a candidate (it is not even rendered). */ + @Test + fun nonAnimatableNextIsNoCandidate() { + val puppet = model(parameters = listOf(parameter(angleX), parameter(angleY, animatable = false))) + val rows = rowsOf(puppet) + assertEquals(1, rows.size, "the fixed parameter renders no row") + assertNull((rows[0] as ParameterRow.Single).linkCandidateId) + } + + /** A parameter whose next neighbour already belongs to a link gets no candidate. */ + @Test + fun nextAlreadyLinkedIsNoCandidate() { + val puppet = + model( + parameters = listOf(parameter(breath), parameter(angleX), parameter(angleY)), + links = listOf(ParameterLink(angleX, angleY)), + ) + val rows = rowsOf(puppet) + assertNull((rows[0] as ParameterRow.Single).linkCandidateId, "the neighbour is a link's horizontal member") + } + + /** + * A degenerate link (its partner not animatable) still renders its animatable member as a Single, + * but that member is occupied - it must offer no second link, and its neighbour must not offer to + * link with it. + */ + @Test + fun degenerateLinkMemberIsOccupied() { + val puppet = + model( + parameters = listOf(parameter(breath), parameter(angleX), parameter(angleY, animatable = false)), + links = listOf(ParameterLink(angleX, angleY)), + ) + val rows = rowsOf(puppet) + assertEquals(2, rows.size) + assertNull((rows[0] as ParameterRow.Single).linkCandidateId, "the neighbour is occupied by the degenerate link") + assertNull((rows[1] as ParameterRow.Single).linkCandidateId, "the occupied member offers no second link") + } + + /** A group boundary flushes the run: candidacy never crosses groups, and the header row lands between. */ + @Test + fun groupBoundaryBreaksCandidacy() { + val groupId = ParameterGroupId("group1") + val puppet = + model( + parameters = listOf(parameter(angleX), parameter(angleY)), + tree = + listOf( + ParameterNode.Param(angleX), + ParameterNode.Group(groupId, "Group", initiallyOpen = true, children = listOf(ParameterNode.Param(angleY))), + ), + ) + val rows = rowsOf(puppet) + assertEquals(3, rows.size) + assertNull((rows[0] as ParameterRow.Single).linkCandidateId, "the next parameter sits across a group boundary") + assertEquals("group:group1", rowKey(rows[1])) + assertEquals(1, (rows[2] as ParameterRow.Single).depth) + } + + /** Row keys are unique across a mixed list of groups, sliders, and pads. */ + @Test + fun rowKeysAreUniqueAcrossKinds() { + val groupId = ParameterGroupId("group1") + val puppet = + model( + parameters = listOf(parameter(angleX), parameter(angleY), parameter(angleZ), parameter(breath)), + links = listOf(ParameterLink(angleX, angleY)), + tree = + listOf( + ParameterNode.Param(angleX), + ParameterNode.Param(angleY), + ParameterNode.Param(angleZ), + ParameterNode.Group(groupId, "Group", initiallyOpen = true, children = listOf(ParameterNode.Param(breath))), + ), + ) + val rows = rowsOf(puppet) + val keys = rows.map { row -> rowKey(row) } + assertEquals(keys.size, keys.toSet().size, "every row key must be unique") + } + + /** The filter keeps only the sliders whose parameter is in the visible set. */ + @Test + fun filterKeepsOnlyVisibleSingles() { + val puppet = model(parameters = listOf(parameter(angleX), parameter(angleY), parameter(angleZ))) + val rows = filteredRowsOf(puppet, setOf(angleY)) + assertEquals(1, rows.size) + assertEquals(angleY, (rows[0] as ParameterRow.Single).parameter.id) + } + + /** A pad survives the filter when EITHER of its axes is visible (it is one control). */ + @Test + fun filterKeepsPadWhenEitherMemberVisible() { + val puppet = + model( + parameters = listOf(parameter(angleX), parameter(angleY), parameter(breath)), + links = listOf(ParameterLink(angleX, angleY)), + ) + // Only the vertical member (angleY) is visible; the pad still shows, and the unrelated breath drops. + val rows = filteredRowsOf(puppet, setOf(angleY)) + assertEquals(1, rows.size) + assertEquals(angleX, (rows[0] as ParameterRow.Pair2D).horizontal.id) + } + + /** A group whose every child is filtered out is dropped - no empty header. */ + @Test + fun filterDropsEmptyGroup() { + val groupId = ParameterGroupId("group1") + val puppet = + model( + parameters = listOf(parameter(angleX), parameter(angleY)), + tree = + listOf( + ParameterNode.Param(angleX), + ParameterNode.Group(groupId, "Group", initiallyOpen = true, children = listOf(ParameterNode.Param(angleY))), + ), + ) + // Only angleX is visible; the group holds only angleY, so it vanishes rather than showing empty. + val rows = filteredRowsOf(puppet, setOf(angleX)) + assertEquals(1, rows.size) + assertEquals(angleX, (rows[0] as ParameterRow.Single).parameter.id) + assertTrue(rows.none { row -> row is ParameterRow.GroupHeader }) + } + + /** The header search matches a parameter's display name, case-insensitively. */ + @Test + fun searchMatchesDisplayName() { + val puppet = model(parameters = listOf(named(angleX, "Head Turn"), named(breath, "Breathing"))) + assertEquals(setOf(angleX), parameterIdsMatching(puppet, "head")) + } + + /** It matches the parameter id too, so a renamed row is still reachable by the axis a rigger knows. */ + @Test + fun searchMatchesParameterId() { + val puppet = model(parameters = listOf(named(angleX, "Head Turn"), named(breath, "Breathing"))) + assertEquals(setOf(angleX), parameterIdsMatching(puppet, "anglex")) + } + + /** A query matching neither field yields an empty set, which filters the panel down to nothing. */ + @Test + fun searchMissMatchesNothing() { + val puppet = model(parameters = listOf(named(angleX, "Head Turn"), named(breath, "Breathing"))) + assertTrue(parameterIdsMatching(puppet, "eyelid").isEmpty()) + } + + /** + * A search renders a collapsed group open, so a match inside it is reachable - without touching the + * fold state the rigger set (the same map still says closed). + */ + @Test + fun forceExpandedOpensACollapsedGroup() { + val groupId = ParameterGroupId("group1") + val puppet = + model( + parameters = listOf(parameter(angleX), parameter(angleY)), + tree = + listOf( + ParameterNode.Param(angleX), + ParameterNode.Group(groupId, "Group", initiallyOpen = false, children = listOf(ParameterNode.Param(angleY))), + ), + ) + val folded = mapOf(groupId to false) + val closedRows = buildParameterRows(puppet, buildLinkInfo(puppet), puppet.parameters.associateBy { it.id }, expanded = folded) + assertTrue(closedRows.none { row -> row is ParameterRow.Single && row.parameter.id == angleY }, "the group is closed") + val searchingRows = + buildParameterRows(puppet, buildLinkInfo(puppet), puppet.parameters.associateBy { it.id }, expanded = folded, forceExpanded = true) + assertTrue(searchingRows.any { row -> row is ParameterRow.Single && row.parameter.id == angleY }, "the search opens it") + assertTrue((searchingRows.first { row -> row is ParameterRow.GroupHeader } as ParameterRow.GroupHeader).expanded) + assertEquals(false, folded[groupId], "the rigger's own fold state is untouched") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParametersDropRulesTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParametersDropRulesTest.kt new file mode 100644 index 0000000..0e111bb --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/ParametersDropRulesTest.kt @@ -0,0 +1,97 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.ParameterMoveSubject +import org.umamo.edit.ParameterNodeRef +import org.umamo.edit.RowDropBand +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.ParameterNode +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pins the pure parameter drop rules under the one-level constraint: which (dragged, target, band) + * combinations are legal, and how a legal band resolves to a destination parent and insert-before anchor + * (a pad's "after" skips its vertical partner). + */ +class ParametersDropRulesTest { + private val angleX = ParameterId("ParamAngleX") + private val angleY = ParameterId("ParamAngleY") + private val angleZ = ParameterId("ParamAngleZ") + private val breath = ParameterId("ParamBreath") + private val groupA = ParameterGroupId("ParamGroup") + + private fun parameter(id: ParameterId): Parameter = Parameter(id, id.raw, min = -1f, max = 1f, default = 0f) + + private fun single(id: ParameterId, depth: Int = 0): ParameterRow.Single = ParameterRow.Single(parameter(id), depth) + + private fun pad(depth: Int = 0): ParameterRow.Pair2D = ParameterRow.Pair2D(parameter(angleY), parameter(angleZ), depth) + + private fun header(depth: Int = 0): ParameterRow.GroupHeader = ParameterRow.GroupHeader(groupA, "Group", depth, expanded = true) + + private val draggedLeaf = ParameterMoveSubject.Leaves(listOf(breath)) + private val draggedGroup = ParameterMoveSubject.Group(ParameterGroupId("ParamGroupOther")) + + /** A leaf target takes Before above the midline, After below; a dragged group only if the target is at root. */ + @Test + fun leafTargetBands() { + assertEquals(RowDropBand.Before, parameterDropBandFor(draggedLeaf, single(angleX), targetAtRoot = true, fraction = 0.2f)) + assertEquals(RowDropBand.After, parameterDropBandFor(draggedLeaf, single(angleX), targetAtRoot = true, fraction = 0.8f)) + // A dragged group onto a root leaf reorders among root nodes. + assertEquals(RowDropBand.After, parameterDropBandFor(draggedGroup, single(angleX), targetAtRoot = true, fraction = 0.8f)) + // A dragged group onto an in-group leaf is illegal (a group can't live inside a group). + assertNull(parameterDropBandFor(draggedGroup, single(angleX, depth = 1), targetAtRoot = false, fraction = 0.8f)) + } + + /** A group header nests a dragged leaf in its middle band and reorders at its edges; a dragged group never nests. */ + @Test + fun groupHeaderBands() { + assertEquals(RowDropBand.Before, parameterDropBandFor(draggedLeaf, header(), targetAtRoot = true, fraction = 0.1f)) + assertEquals(RowDropBand.Into, parameterDropBandFor(draggedLeaf, header(), targetAtRoot = true, fraction = 0.5f)) + assertEquals(RowDropBand.After, parameterDropBandFor(draggedLeaf, header(), targetAtRoot = true, fraction = 0.9f)) + // A dragged group onto a group header only reorders - never Into (even in the middle band). + assertEquals(RowDropBand.Before, parameterDropBandFor(draggedGroup, header(), targetAtRoot = true, fraction = 0.4f)) + assertEquals(RowDropBand.After, parameterDropBandFor(draggedGroup, header(), targetAtRoot = true, fraction = 0.6f)) + } + + private fun model(parameters: List, tree: List): PuppetModel = + PuppetModel( + parameters = parameters, + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + parameterTree = tree, + ) + + /** Before anchors on the target's leading node; Into a group appends inside it. */ + @Test + fun anchorBeforeAndInto() { + val tree = listOf(ParameterNode.Param(angleX), header().let { ParameterNode.Group(groupA, "Group", true, emptyList()) }) + val puppet = model(listOf(parameter(angleX)), tree) + assertEquals(null to ParameterNodeRef.Leaf(angleX), parameterDropAnchor(puppet, single(angleX), RowDropBand.Before)) + assertEquals(groupA to null, parameterDropAnchor(puppet, header(), RowDropBand.Into)) + } + + /** After a root leaf anchors on the next root node; after the last node appends (null). */ + @Test + fun anchorAfterRootLeaf() { + val tree = listOf(ParameterNode.Param(angleX), ParameterNode.Param(breath)) + val puppet = model(listOf(parameter(angleX), parameter(breath)), tree) + assertEquals(null to ParameterNodeRef.Leaf(breath), parameterDropAnchor(puppet, single(angleX), RowDropBand.After)) + assertEquals(null to null, parameterDropAnchor(puppet, single(breath), RowDropBand.After)) + } + + /** After a pad skips its vertical partner and anchors on the node past both leaves. */ + @Test + fun anchorAfterPadSkipsVertical() { + // Tree: [padHorizontal(angleY), padVertical(angleZ), breath]; after the pad should anchor on breath. + val tree = listOf(ParameterNode.Param(angleY), ParameterNode.Param(angleZ), ParameterNode.Param(breath)) + val puppet = model(listOf(parameter(angleY), parameter(angleZ), parameter(breath)), tree) + assertEquals(null to ParameterNodeRef.Leaf(breath), parameterDropAnchor(puppet, pad(), RowDropBand.After)) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/PersistentViewStatesTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/PersistentViewStatesTest.kt new file mode 100644 index 0000000..0116dfe --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/PersistentViewStatesTest.kt @@ -0,0 +1,204 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.ui.unit.dp +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.umamo.runtime.model.ParameterGroupId +import org.umamo.runtime.model.ParameterId +import org.umamo.ui.properties.PropertiesViewState +import org.umamo.ui.properties.PropertyTabId +import org.umamo.ui.tracks.TRACK_LABEL_COLUMN_DEFAULT_WIDTH +import org.umamo.ui.tracks.TRACK_LABEL_COLUMN_MAX_WIDTH +import org.umamo.ui.tracks.TrackWindow +import org.umamo.ui.workspace.PersistentSpaceState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Pins each space's saved view state (docs/format/UMA.md §7.3): what it writes comes back, a state at its + * defaults writes nothing but nulls, and a member that is the wrong shape is skipped rather than thrown over. + */ +class PersistentViewStatesTest { + /** + * Whether [state] names every member as a null, which is what an untouched space writes. + * + * @param PersistentSpaceState state The state. + * @return Boolean True when nothing deviates. + */ + private fun writesOnlyNulls(state: PersistentSpaceState): Boolean = state.toJson().values.all { value -> value is JsonNull } + + @Test + fun theOutlinerRoundTripsItsFoldsFiltersAndColumns() { + val saved = OutlinerViewState() + assertTrue(writesOnlyNulls(saved), "an untouched outliner has nothing to save") + saved.query = "arm" + saved.expanded["part:12"] = true + saved.expanded["part:13"] = false + saved.expanded[OUTLINER_ROOT_ID] = false + saved.showDeformers = false + saved.showVisibilityColumn = false + + val tree = saved.toJson() + val reopened = OutlinerViewState().also { state -> state.restore(tree) } + + assertEquals("", reopened.query, "a search query is not saved") + assertTrue(reopened.isOpen("part:12")) + assertFalse(reopened.isOpen(OUTLINER_ROOT_ID), "a closed root is a deviation and is saved") + assertFalse("part:13" in reopened.expanded, "a branch closed at its default is no deviation") + assertFalse(reopened.showDeformers) + assertTrue(reopened.showParts && reopened.showDrawables && reopened.showSelectableColumn) + assertFalse(reopened.showVisibilityColumn) + assertEquals(tree, reopened.toJson(), "and the restored state writes the same member") + } + + @Test + fun theSourcesSpaceRoundTripsItsFoldsAndFilters() { + val saved = SourcesViewState() + assertTrue(writesOnlyNulls(saved)) + saved.expanded["source:art-0"] = false + saved.expanded["layer:art-0/lyid:4"] = true + saved.setShown(SourcesFilter.Bound, false) + saved.setShown(SourcesFilter.NeedsReview, false) + + val reopened = SourcesViewState().also { state -> state.restore(saved.toJson()) } + + assertFalse(reopened.isOpen("source:art-0")) + assertTrue(reopened.isOpen("layer:art-0/lyid:4")) + assertTrue(reopened.isOpen("source:art-1"), "an unrecorded file is open by default") + assertEquals(setOf(SourcesFilter.Unbound, SourcesFilter.Missing), reopened.filters) + } + + @Test + fun theParametersPanelRoundTripsItsGroupsEditorsAndFilter() { + val saved = ParametersViewState() + assertTrue(writesOnlyNulls(saved)) + saved.expandedGroups[ParameterGroupId("face")] = true + saved.expandedGroups[ParameterGroupId("body")] = false + saved.openRangeEditors[ParameterId("ParamAngleX")] = true + saved.openRangeEditors[ParameterId("ParamAngleY")] = false + saved.showOnlySelected = true + saved.renamingParameterId = ParameterId("ParamAngleX") + + val reopened = ParametersViewState().also { state -> state.restore(saved.toJson()) } + + assertEquals(mapOf(ParameterGroupId("face") to true, ParameterGroupId("body") to false), reopened.expandedGroups.toMap()) + assertEquals(mapOf(ParameterId("ParamAngleX") to true), reopened.openRangeEditors.toMap(), "a closed range editor is the default") + assertTrue(reopened.showOnlySelected) + assertEquals(null, reopened.renamingParameterId, "a rename in flight is not saved") + } + + @Test + fun theKeyformSheetRoundTripsItsFoldsFiltersWindowAndWidth() { + val unseeded = KeyformSheetViewState() + assertTrue(writesOnlyNulls(unseeded), "a sheet that never seeded has no fold state of its own") + + val saved = KeyformSheetViewState() + saved.seeded = true + saved.expandedKeys = setOf("part:3") + saved.collapsedParameters = setOf(ParameterId("ParamAngleX")) + saved.showBlendShapes = false + saved.window = TrackWindow(0.25f, 0.75f) + saved.labelColumnWidth = 240.dp + saved.boxSelectArmed = true + + val reopened = KeyformSheetViewState().also { state -> state.restore(saved.toJson()) } + + assertTrue(reopened.seeded, "a saved fold state counts as the seed") + assertEquals(setOf("part:3"), reopened.expandedKeys) + assertEquals(setOf(ParameterId("ParamAngleX")), reopened.collapsedParameters) + assertTrue(reopened.showGeometry && reopened.showChannels) + assertFalse(reopened.showBlendShapes) + assertEquals(TrackWindow(0.25f, 0.75f), reopened.window) + assertEquals(240.dp, reopened.labelColumnWidth) + assertFalse(reopened.boxSelectArmed, "a gesture in flight is not saved") + } + + @Test + fun aSeededSheetWithEveryGroupClosedSavesAnEmptyList() { + val saved = KeyformSheetViewState() + saved.seeded = true + + val reopened = KeyformSheetViewState().also { state -> state.restore(saved.toJson()) } + + assertTrue(reopened.seeded, "collapse-everything survives: the reopened sheet does not seed itself open") + assertEquals(emptySet(), reopened.expandedKeys) + } + + @Test + fun thePropertiesPanelRoundTripsItsTabSectionsAndListHeights() { + val saved = PropertiesViewState() + assertTrue(writesOnlyNulls(saved)) + saved.query = "mask" + saved.activeTab = PropertyTabId.Data + saved.expandedSections["data.mesh"] = false + saved.expandedSections["data.blend"] = true + saved.listHeights["maskedBy"] = 220.dp + + val reopened = PropertiesViewState().also { state -> state.restore(saved.toJson()) } + + assertEquals("", reopened.query) + assertEquals(PropertyTabId.Data, reopened.activeTab) + assertEquals(mapOf("data.mesh" to false), reopened.expandedSections.toMap(), "an open section is the default") + assertEquals(mapOf("maskedBy" to 220.dp), reopened.listHeights.toMap()) + } + + @Test + fun theUvEditorRoundTripsEachTextureSelection() { + assertTrue(writesOnlyNulls(UvEditorViewState()), "following the selection is the default") + for (selection in listOf(UvTextureSelection.PinnedPage(2), UvTextureSelection.SourceLayer, UvTextureSelection.FollowSelection)) { + val saved = UvEditorViewState().also { state -> state.textureSelection = selection } + val reopened = UvEditorViewState().also { state -> state.restore(saved.toJson()) } + assertEquals(selection, reopened.textureSelection) + } + } + + /** Every member the wrong shape: nothing throws, and every state keeps its defaults (UMA §7.1). */ + @Test + fun membersOfTheWrongShapeAreSkipped() { + val junk = + buildJsonObject { + for (memberName in listOf("expanded", "collapsed", "hidden", "hiddenColumns", "expandedGroups", "collapsedGroups", "openRangeEditors", "collapsedParameters", "collapsedSections")) { + put(memberName, "not an array") + } + put("onlySelected", "yes") + put("tab", 7) + put("texture", buildJsonObject { put("page", "two") }) + put( + "window", + buildJsonArray { + add(JsonPrimitive(0.9f)) + add(JsonPrimitive(0.1f)) + }, + ) + put("labelColumnWidth", 99999) + put( + "listHeights", + buildJsonObject { + put("maskedBy", -4) + put("other", "tall") + }, + ) + } + + val outliner = OutlinerViewState().also { state -> state.restore(junk) } + val sources = SourcesViewState().also { state -> state.restore(junk) } + val parameters = ParametersViewState().also { state -> state.restore(junk) } + val sheet = KeyformSheetViewState().also { state -> state.restore(junk) } + val properties = PropertiesViewState().also { state -> state.restore(junk) } + val uvEditor = UvEditorViewState().also { state -> state.restore(junk) } + + assertTrue(writesOnlyNulls(outliner) && writesOnlyNulls(sources) && writesOnlyNulls(parameters) && writesOnlyNulls(uvEditor)) + assertFalse(sheet.seeded) + assertEquals(TrackWindow.Full, sheet.window, "a window that runs backwards keeps the whole domain") + assertEquals(TRACK_LABEL_COLUMN_MAX_WIDTH, sheet.labelColumnWidth, "a width past the sheet's limit is clamped to it") + assertEquals(PropertyTabId.Document, properties.activeTab) + assertEquals(emptyMap(), properties.listHeights.toMap()) + assertEquals(TRACK_LABEL_COLUMN_DEFAULT_WIDTH, KeyformSheetViewState().also { state -> state.restore(JsonObject(emptyMap())) }.labelColumnWidth) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/RowHoverPreviewStateTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/RowHoverPreviewStateTest.kt new file mode 100644 index 0000000..cc547d3 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/RowHoverPreviewStateTest.kt @@ -0,0 +1,46 @@ +package org.umamo.ui.workspace.spaces + +import androidx.compose.ui.geometry.Rect +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * The hover preview's ownership rule: only the row that owns the preview may withdraw it. + * + * The order the rule exists for is the everyday one. Moving the pointer down the list reports the next + * row before the previous row's exit arrives, so an exit that cleared unconditionally would blank the + * preview of the row the pointer is now on. + */ +class RowHoverPreviewStateTest { + private fun preview(key: String): RowHoverPreview = RowHoverPreview(key, "Row $key", Rect(0f, 0f, 100f, 20f)) + + /** The next row's report arriving before the old row's exit keeps the next row. */ + @Test + fun anOldRowsExitDoesNotClearTheNextRow() { + val state = RowHoverPreviewState() + state.report(preview("a")) + state.report(preview("b")) + state.clear("a") + assertEquals("b", state.hovered?.key) + } + + /** The owning row's exit withdraws the preview. */ + @Test + fun theOwningRowsExitClearsIt() { + val state = RowHoverPreviewState() + state.report(preview("a")) + state.clear("a") + assertNull(state.hovered) + } + + /** A report replaces whichever row was hovered, name and bounds included. */ + @Test + fun aReportReplacesTheHoveredRow() { + val state = RowHoverPreviewState() + state.report(preview("a")) + val next = RowHoverPreview("b", "Renamed", Rect(0f, 20f, 100f, 40f)) + state.report(next) + assertEquals(next, state.hovered) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/SourcesSpaceTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/SourcesSpaceTest.kt new file mode 100644 index 0000000..41da397 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/SourcesSpaceTest.kt @@ -0,0 +1,195 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.ui.model.percentOf +import org.umamo.ui.resources.* +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.umamoDarkColors +import org.umamo.ui.theme.umamoLightColors +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Unit-tests the Sources space's pure pieces: the row visual (which glyph and traffic-light tint a + * status reads as, and which word rides the tooltip) and the relink list's grouping by file. Neither + * needs a composition. + */ +class SourcesSpaceTest { + private val icons = LocalUmamoIcons + private val colors = umamoDarkColors + private val artA = ArtSourceId("art-0") + + private fun node(kind: SourcesNodeKind, status: SourcesStatus): SourcesNode = SourcesNode("row", "Row", SourcesDetail.None, kind, status, emptyList()) + + private fun layer(key: String, name: String): ArtSourceLayer = ArtSourceLayer(key, name, "", 0, 0, 4, 4, true) + + /** A file's presence swaps the glyph and tints only when the file is missing. */ + @Test + fun fileRowsReadPresenceThroughTheGlyph() { + val source = SourcesNodeKind.Source(artA) + val missing = sourcesRowVisual(node(source, SourcesStatus.Missing), icons, colors) + assertSame(icons.missingFile, missing.icon) + assertEquals(colors.signalBad, missing.tint) + assertSame(Res.string.sources_status_missing, missing.statusLabel) + val present = sourcesRowVisual(node(source, SourcesStatus.Present), icons, colors) + assertSame(icons.sources, present.icon) + assertEquals(colors.text, present.tint) + assertSame(Res.string.sources_status_present, present.statusLabel) + val unknown = sourcesRowVisual(node(source, SourcesStatus.Unknown), icons, colors) + assertSame(icons.sources, unknown.icon) + assertEquals(colors.text, unknown.tint, "an unprobed file is not a missing one") + assertSame(Res.string.sources_status_unknown, unknown.statusLabel) + } + + /** Layer rows are the traffic light: green bound, amber bound by name, red unbound. */ + @Test + fun layerRowsAreTheTrafficLight() { + val layer = SourcesNodeKind.Layer(SourceLayerRef(artA, "lyid:1", true)) + val bound = sourcesRowVisual(node(layer, SourcesStatus.Bound), icons, colors) + assertSame(icons.linked, bound.icon) + assertEquals(colors.signalGood, bound.tint) + assertSame(Res.string.sources_status_bound, bound.statusLabel) + val byName = sourcesRowVisual(node(layer, SourcesStatus.BoundByName), icons, colors) + assertSame(icons.linked, byName.icon) + assertEquals(colors.signalCaution, byName.tint) + assertSame(Res.string.sources_status_bound_unstable, byName.statusLabel) + val unbound = sourcesRowVisual(node(layer, SourcesStatus.Unbound), icons, colors) + assertSame(icons.unlinked, unbound.icon) + assertEquals(colors.signalBad, unbound.tint) + assertSame(Res.string.sources_status_unbound, unbound.statusLabel) + val review = sourcesRowVisual(node(layer, SourcesStatus.NeedsReview), icons, colors) + assertSame(icons.unlinked, review.icon) + assertEquals(colors.signalCaution, review.tint, "a binding the file lost is caution, not broken: the tile keeps its art") + assertSame(Res.string.sources_status_needs_review, review.statusLabel) + val emptied = sourcesRowVisual(node(layer, SourcesStatus.Emptied), icons, colors) + assertSame(icons.unlinked, emptied.icon) + assertEquals(colors.signalCaution, emptied.tint) + assertSame(Res.string.sources_status_emptied, emptied.statusLabel, "the same wait, its own reason") + val replaced = sourcesRowVisual(node(layer, SourcesStatus.SourceReplaced), icons, colors) + assertSame(icons.unlinked, replaced.icon) + assertEquals(colors.signalCaution, replaced.tint) + assertSame(Res.string.sources_status_replaced, replaced.statusLabel, "lost to a replacement: the same wait again, its own reason") + val ignored = sourcesRowVisual(node(layer, SourcesStatus.Ignored), icons, colors) + assertSame(icons.unlinked, ignored.icon) + assertEquals(colors.textMuted, ignored.tint, "settled by the rigger, so no signal color") + assertSame(Res.string.sources_status_ignored, ignored.statusLabel) + } + + /** A tile on no page reads caution; a placed tile and a drawable carry no status at all. */ + @Test + fun tilesAndDrawablesCarryAStatusOnlyWhenUnplaced() { + val tile = SourcesNodeKind.Tile(AtlasTileId("t1")) + val unplaced = sourcesRowVisual(node(tile, SourcesStatus.Unplaced), icons, colors) + assertSame(icons.spaceTexture, unplaced.icon) + assertEquals(colors.signalCaution, unplaced.tint) + assertSame(Res.string.sources_status_unplaced, unplaced.statusLabel) + val placed = sourcesRowVisual(node(tile, SourcesStatus.None), icons, colors) + assertEquals(colors.text, placed.tint) + assertNull(placed.statusLabel, "a placed tile shows no tooltip") + val drawable = sourcesRowVisual(node(SourcesNodeKind.Drawable(DrawableId("a")), SourcesStatus.None), icons, colors) + assertSame(icons.mesh, drawable.icon) + assertNull(drawable.statusLabel) + val group = sourcesRowVisual(node(SourcesNodeKind.UnboundGroup, SourcesStatus.None), icons, colors) + assertSame(icons.unlinked, group.icon) + assertEquals(colors.signalBad, group.tint, "the heading carries the group's status") + } + + /** The signals are learned colors: identical in both schemes, and none of them is a keyframe color. */ + @Test + fun signalColorsAreSharedAcrossSchemesAndDistinctFromKeyframes() { + assertEquals(umamoDarkColors.signalGood, umamoLightColors.signalGood) + assertEquals(umamoDarkColors.signalCaution, umamoLightColors.signalCaution) + assertEquals(umamoDarkColors.signalBad, umamoLightColors.signalBad) + val signals = setOf(colors.signalGood, colors.signalCaution, colors.signalBad) + assertEquals(3, signals.size, "three distinct signals") + val keyframes = setOf(colors.keyedOnKey, colors.keyedBetween, colors.keyedModified) + assertTrue(signals.none { signal -> signal in keyframes }, "a signal never doubles as a keyframe state") + } + + /** The relink list groups by file; the query keeps a layer by name or a whole file by its name. */ + @Test + fun relinkGroupsByFileAndFiltersByLayerOrFileName() { + val sources = + listOf( + ArtSource(artA, "Erica Tamamo.psd", null, "psd", listOf(layer("lyid:1", "Hair front"), layer("lyid:2", "Eye L"), layer("lyid:3", "Hair back"))), + ArtSource(ArtSourceId("art-1"), "Extra parts.psd", null, "psd", listOf(layer("lyid:7", "Background"))), + ArtSource(ArtSourceId("art-2"), "Empty.psd", null, "psd", emptyList()), + ) + val all = relinkGroups(sources, " ") + assertEquals(listOf("Erica Tamamo.psd", "Extra parts.psd"), all.map { group -> group.source.name }, "a blank query lists every file that has layers") + assertEquals(listOf("Hair front", "Eye L", "Hair back"), all[0].layers.map { layer -> layer.name }) + val byLayer = relinkGroups(sources, "hair") + assertEquals(listOf("Erica Tamamo.psd"), byLayer.map { group -> group.source.name }, "a file with no matching layer is dropped") + assertEquals(listOf("Hair front", "Hair back"), byLayer[0].layers.map { layer -> layer.name }, "only the matching layers survive, in order") + val byFile = relinkGroups(sources, "EXTRA") + assertEquals(listOf("Extra parts.psd"), byFile.map { group -> group.source.name }) + assertEquals(listOf("Background"), byFile[0].layers.map { layer -> layer.name }, "a file-name match keeps every layer of that file") + assertTrue(relinkGroups(sources, "nothing here").isEmpty()) + } + + /** A row the file lost is kept for review, never offered as a relink target; nor is an erased or an ignored layer. */ + @Test + fun lostRowsAreNeverRelinkTargets() { + val sources = + listOf( + ArtSource( + artA, + "a.psd", + null, + "psd", + listOf(layer("lyid:1", "Hair"), layer("lyid:2", "Old hair").copy(present = false), layer("lyid:3", "Blank").copy(empty = true), layer("lyid:4", "Sketch").copy(ignored = true)), + ), + ) + assertEquals(listOf("Hair"), relinkGroups(sources, "").single().layers.map { layer -> layer.name }, "neither a lost row, an erased one, nor an ignored one is a target") + assertTrue(relinkGroups(sources, "old").isEmpty()) + assertTrue(relinkGroups(sources, "sketch").isEmpty()) + } + + /** The chip's confidence is a whole percentage, rounded, never past the ends. */ + @Test + fun suggestionScoresReadAsWholePercentages() { + assertEquals(92, percentOf(0.924f)) + assertEquals(93, percentOf(0.925f)) + assertEquals(100, percentOf(1.2f)) + assertEquals(0, percentOf(-0.1f)) + } + + /** A tile row and a drawable row preview themselves. */ + @Test + fun tileAndDrawableRowsPreviewThemselves() { + val tileId = AtlasTileId("tile") + assertEquals(SourcesPreviewSubject.Tile(tileId), sourcesPreviewSubject(node(SourcesNodeKind.Tile(tileId), SourcesStatus.Bound))) + val drawableId = DrawableId("mesh") + assertEquals(SourcesPreviewSubject.Drawable(drawableId), sourcesPreviewSubject(node(SourcesNodeKind.Drawable(drawableId), SourcesStatus.Bound))) + } + + /** + * A layer row previews the first tile bound to it, and a layer under review still does: its binding is + * what the review is about, so its old art is exactly what the rigger needs to see. + */ + @Test + fun aLayerRowPreviewsItsFirstBoundTile() { + val layerKind = SourcesNodeKind.Layer(SourceLayerRef(artA, "lyid:1", true)) + val tiles = listOf(node(SourcesNodeKind.Tile(AtlasTileId("first")), SourcesStatus.Bound), node(SourcesNodeKind.Tile(AtlasTileId("second")), SourcesStatus.Bound)) + val bound = node(layerKind, SourcesStatus.Bound).copy(children = tiles) + assertEquals(SourcesPreviewSubject.Tile(AtlasTileId("first")), sourcesPreviewSubject(bound)) + val underReview = node(layerKind, SourcesStatus.NeedsReview).copy(children = tiles) + assertEquals(SourcesPreviewSubject.Tile(AtlasTileId("first")), sourcesPreviewSubject(underReview)) + } + + /** An unbound layer's pixels live in its file, not the document, and a file or the unbound group is no single piece of art. */ + @Test + fun rowsWithNoArtOfTheirOwnPreviewNothing() { + assertNull(sourcesPreviewSubject(node(SourcesNodeKind.Layer(SourceLayerRef(artA, "lyid:1", true)), SourcesStatus.Unbound))) + assertNull(sourcesPreviewSubject(node(SourcesNodeKind.Source(artA), SourcesStatus.Present))) + assertNull(sourcesPreviewSubject(node(SourcesNodeKind.UnboundGroup, SourcesStatus.Unknown))) + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/SourcesTreeTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/SourcesTreeTest.kt new file mode 100644 index 0000000..ca9e5d4 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/SourcesTreeTest.kt @@ -0,0 +1,409 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.reimport.LayerMatch +import org.umamo.reimport.MatchSignals +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.ArtSourceLayer +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.DeformerId +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.SourceLayerRef +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Unit-tests the Sources tree: files with their presence, inventory layers with their binding status, + * tiles under the layers they are bound to (and strays under keys the inventory lacks), drawables + * under tiles, the unbound-art group, the four filters, and the flatten. Hand-built rig, no Compose. + */ +class SourcesTreeTest { + private val artA = ArtSourceId("art-0") + private val artB = ArtSourceId("art-1") + + private fun drawable(id: String, tileId: String): Drawable = + Drawable(DrawableId(id), id, null, BlendMode.Normal, emptyList(), null, null, atlasTileId = AtlasTileId(tileId)) + + private fun model(): PuppetModel { + val drawables = listOf(drawable("a", "tA1"), drawable("b", "tA1"), drawable("c", "tA3"), drawable("d", "tLoose")) + return PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + atlas = + PuppetAtlas( + pages = listOf(AtlasPage(64, 64)), + tiles = + listOf( + AtlasTile(AtlasTileId("tA1"), "Eye", 4, 4, placement = AtlasPlacement(0, 1f, 1f, 1f, 1f, 0f), source = SourceLayerRef(artA, "lyid:1", true)), + AtlasTile(AtlasTileId("tA3"), "Hair", 4, 4, source = SourceLayerRef(artA, "name:Stray", false)), + AtlasTile(AtlasTileId("tLoose"), "Loose", 4, 4), + ), + ), + sources = + listOf( + ArtSource( + artA, + "a.psd", + "/art/a.psd", + "psd", + listOf( + ArtSourceLayer("lyid:1", "Eye", "Head", 10, 20, 4, 4, true), + ArtSourceLayer("lyid:2", "Unused", "Head", 0, 0, 2, 2, false), + ), + ), + ArtSource(artB, "b.clip", null, "clip", listOf(ArtSourceLayer("uuid-9", "Wing", "", 0, 0, 8, 8, true))), + ), + ) + } + + private fun presence(source: ArtSource): SourcePresence = if (source.id == artA) SourcePresence.Missing else SourcePresence.Unknown + + @Test + fun layerPositionsReadFromTheFileOrTheWorldAxes() { + // A 64 x 64 canvas with the origin at its center, world (32, -32); file A placed 5 right and 3 down. + val base = model() + val puppet = + base.copy( + canvasWidth = 64f, + canvasHeight = 64f, + worldOriginX = 32f, + worldOriginZ = -32f, + sources = base.sources.map { source -> if (source.id == artA) source.copy(offsetX = 5, offsetZ = -3) else source }, + ) + + // The Eye layer sits at document (10, 20), top-left, y down. + val fileFrame = buildSourcesTree(puppet, ::presence, "Unbound art")[0].children[0].detail + assertEquals(SourcesDetail.Layer(4, 4, 5, 17), fileFrame, "the default takes the placement back out, so the numbers match the art file") + + val worldAxes = buildSourcesTree(puppet, ::presence, "Unbound art", layerPositionsFromWorldAxes = true)[0].children[0].detail + assertEquals(SourcesDetail.LayerOnAxes(4, 4, -22f, 12f), worldAxes, "the same corner, 22 left of and 12 above the axes") + } + + @Test + fun theTreeReadsFileLayerTileDrawable() { + val tree = buildSourcesTree(model(), ::presence, "Unbound art") + + assertEquals(listOf("source:art-0", "source:art-1", SOURCES_UNBOUND_GROUP_ID), tree.map { node -> node.id }) + val fileA = tree[0] + assertEquals(SourcesStatus.Missing, fileA.status) + assertEquals(SourcesDetail.Source("psd", 2, hasPath = true), fileA.detail) + assertEquals(listOf("layer:art-0/lyid:1", "layer:art-0/lyid:2", "layer:art-0/name:Stray"), fileA.children.map { node -> node.id }, "inventory rows, then the stray binding") + val eye = fileA.children[0] + assertEquals(SourcesStatus.Bound, eye.status) + assertEquals(SourcesDetail.Layer(4, 4, 10, 20), eye.detail) + assertEquals(listOf("tile:tA1"), eye.children.map { node -> node.id }) + assertEquals(SourcesDetail.TilePage(1), eye.children[0].detail) + assertEquals(listOf("drawable:a", "drawable:b"), eye.children[0].children.map { node -> node.id }) + assertEquals(SourcesStatus.Unbound, fileA.children[1].status, "a layer no tile binds") + val stray = fileA.children[2] + assertEquals("Stray", stray.label, "a name key shows as the name") + assertEquals(SourcesStatus.NeedsReview, stray.status, "a binding to a layer the file no longer lists waits on a decision") + assertEquals(SourcesStatus.Unplaced, stray.children.single().status) + assertEquals(SourcesStatus.Unknown, tree[1].status, "no path, no verdict") + assertEquals(SourcesDetail.Source("clip", 1, hasPath = false), tree[1].detail) + val unbound = tree[2] + assertEquals(SourcesNodeKind.UnboundGroup, unbound.kind) + assertEquals(listOf("tile:tLoose"), unbound.children.map { node -> node.id }) + } + + /** + * Each kind of row is its own toggle: the table shows the rows of every enabled kind with their + * descendants and the ancestors that give them context, kinds combine by union, every kind on + * hides nothing, and none on shows nothing. + */ + @Test + fun theFiltersKeepWhatTheyNameAndTheirAncestorsAndCombine() { + val tree = buildSourcesTree(model(), ::presence, "Unbound art") + val everything = SourcesFilter.entries.toSet() + + val unbound = filterSourcesTree(tree, "", setOf(SourcesFilter.Unbound)) + assertEquals(listOf("source:art-0", "source:art-1", SOURCES_UNBOUND_GROUP_ID), unbound.map { node -> node.id }) + assertEquals(listOf("layer:art-0/lyid:2"), unbound[0].children.map { node -> node.id }, "only the unbound layer survives under the file") + assertEquals(listOf("layer:art-1/uuid-9"), unbound[1].children.map { node -> node.id }) + assertEquals(listOf("tile:tLoose"), unbound[2].children.map { node -> node.id }, "the unbound group keeps its tiles") + + val bound = filterSourcesTree(tree, "", setOf(SourcesFilter.Bound)) + assertEquals(listOf("source:art-0"), bound.map { node -> node.id }, "only the file with a bound layer") + assertEquals(listOf("layer:art-0/lyid:1"), bound[0].children.map { node -> node.id }) + assertEquals(listOf("tile:tA1"), bound[0].children[0].children.map { node -> node.id }, "with its tile and drawables beneath") + + val missing = filterSourcesTree(tree, "", setOf(SourcesFilter.Missing)) + assertEquals(listOf("source:art-0"), missing.map { node -> node.id }) + assertEquals(3, missing[0].children.size, "a missing file keeps its whole subtree") + + val review = filterSourcesTree(tree, "", setOf(SourcesFilter.NeedsReview)) + assertEquals(listOf("source:art-0"), review.map { node -> node.id }) + assertEquals(listOf("layer:art-0/name:Stray"), review[0].children.map { node -> node.id }, "only the stray binding needs review") + + val both = filterSourcesTree(tree, "", setOf(SourcesFilter.Unbound, SourcesFilter.NeedsReview)) + assertEquals(listOf("layer:art-0/lyid:2", "layer:art-0/name:Stray"), both[0].children.map { node -> node.id }, "two kinds combine by union") + assertEquals(3, both.size, "the unbound group still shows") + + assertEquals(tree, filterSourcesTree(tree, "", everything), "every kind on hides nothing") + assertTrue(filterSourcesTree(tree, "", emptySet()).isEmpty(), "no kind on shows nothing") + + val searched = filterSourcesTree(tree, "wing", everything) + assertEquals(listOf("source:art-1"), searched.map { node -> node.id }, "a search keeps the matching row's ancestors") + assertEquals(listOf("layer:art-1/uuid-9"), searched[0].children.map { node -> node.id }) + assertTrue(filterSourcesTree(tree, "wing", setOf(SourcesFilter.Bound)).isEmpty(), "a search narrows within the enabled kinds") + } + + @Test + fun flattenFollowsTheOpenRows() { + val tree = buildSourcesTree(model(), ::presence, "Unbound art") + val closed = flattenSources(tree) { id -> id.startsWith("source:") } + assertEquals( + listOf("source:art-0", "layer:art-0/lyid:1", "layer:art-0/lyid:2", "layer:art-0/name:Stray", "source:art-1", "layer:art-1/uuid-9", SOURCES_UNBOUND_GROUP_ID), + closed.map { row -> row.node.id }, + ) + assertEquals(listOf(0, 1, 1, 1, 0, 1, 0), closed.map { row -> row.depth }) + val open = flattenSources(tree) { true } + assertTrue(open.any { row -> row.node.id == "drawable:b" && row.depth == 3 }, "an open tile lists its drawables three deep") + } + + /** + * A layer the file lost but a tile still binds keeps its row - named and sized as the inventory last + * saw it, reading as needing review - and carries the proposal the matcher made for it, unless the + * proposal names a layer the file no longer has or one some tile already binds. A binding the + * inventory never listed still falls back to its raw key. + */ + @Test + fun lostRowsReadTheirNameAndCarryAValidSuggestion() { + val base = model() + val puppet = + base.copy( + atlas = + base.atlas.copy( + tiles = + base.atlas.tiles + AtlasTile(AtlasTileId("tA9"), "Old brow", 4, 4, source = SourceLayerRef(artA, "lyid:9", true)), + ), + sources = + base.sources.map { source -> + if (source.id != artA) { + source + } else { + source.copy( + layers = + source.layers + + ArtSourceLayer("lyid:5", "Brow", "Head", 12, 22, 4, 4, true) + + ArtSourceLayer("lyid:9", "Brow (old)", "Head", 12, 22, 4, 4, true, present = false), + ) + } + }, + ) + + fun match(key: String, score: Float): LayerMatch = LayerMatch(key, score, MatchSignals(1f, 1f, 1f, 1f, null, hashEqual = false)) + val tree = buildSourcesTree(puppet, ::presence, "Unbound art") { sourceId, key -> if (sourceId == artA && key == "lyid:9") listOf(match("lyid:5", 0.92f)) else emptyList() } + val fileA = tree[0] + assertEquals(listOf("layer:art-0/lyid:1", "layer:art-0/lyid:2", "layer:art-0/lyid:5", "layer:art-0/lyid:9", "layer:art-0/name:Stray"), fileA.children.map { node -> node.id }) + val lost = fileA.children[3] + assertEquals("Brow (old)", lost.label, "the lost row keeps the name the inventory last saw") + assertEquals(SourcesDetail.Layer(4, 4, 12, 22), lost.detail) + assertEquals(SourcesStatus.NeedsReview, lost.status) + assertEquals(listOf("tile:tA9"), lost.children.map { node -> node.id }) + assertEquals(LayerSuggestion("lyid:5", "Brow", 0.92f), lost.suggestion) + assertNull(fileA.children[2].suggestion, "a present row proposes nothing") + val stray = fileA.children[4] + assertEquals("Stray", stray.label, "a binding the inventory never listed still shows by its key") + assertEquals(SourcesStatus.NeedsReview, stray.status) + + val boundElsewhere = buildSourcesTree(puppet, ::presence, "Unbound art") { _, _ -> listOf(match("lyid:1", 0.9f)) } + assertNull(boundElsewhere[0].children[3].suggestion, "a proposal naming a layer some tile binds is dropped") + val goneCandidate = buildSourcesTree(puppet, ::presence, "Unbound art") { _, _ -> listOf(match("lyid:77", 0.9f)) } + assertNull(goneCandidate[0].children[3].suggestion, "a proposal naming a layer the file lacks is dropped") + // A stale published proposal ahead of a live one: the row takes the live one rather than nothing. + val staleFirst = buildSourcesTree(puppet, ::presence, "Unbound art") { _, _ -> listOf(match("lyid:1", 0.95f), match("lyid:5", 0.6f)) } + assertEquals(LayerSuggestion("lyid:5", "Brow", 0.6f), staleFirst[0].children[3].suggestion, "a dropped proposal does not hide the next one") + val review = filterSourcesTree(tree, "", setOf(SourcesFilter.NeedsReview)) + assertEquals(listOf("layer:art-0/lyid:9", "layer:art-0/name:Stray"), review[0].children.map { node -> node.id }) + + // Unbind the lost row's one tile: the row reviews nothing now, so it leaves the table at once + // rather than waiting for the refresh that prunes it from the inventory. + val unbound = puppet.copy(atlas = puppet.atlas.copy(tiles = puppet.atlas.tiles.map { tile -> if (tile.id == AtlasTileId("tA9")) tile.copy(source = null) else tile })) + val afterUnbind = buildSourcesTree(unbound, ::presence, "Unbound art") + assertEquals(listOf("layer:art-0/lyid:1", "layer:art-0/lyid:2", "layer:art-0/lyid:5", "layer:art-0/name:Stray"), afterUnbind[0].children.map { node -> node.id }) + assertTrue(filterSourcesTree(afterUnbind, "", setOf(SourcesFilter.NeedsReview))[0].children.none { node -> node.id == "layer:art-0/lyid:9" }) + } + + /** A bound layer erased to nothing reads as its own review state and joins the review filter; an unbound one is simply unbound. */ + @Test + fun anErasedBoundLayerReadsAsEmptiedAndJoinsTheReviewFilter() { + val base = model() + val puppet = + base.copy( + sources = + base.sources.map { source -> + if (source.id != artA) source else source.copy(layers = source.layers.map { layer -> layer.copy(empty = true) }) + }, + ) + val tree = buildSourcesTree(puppet, ::presence, "Unbound art") + val fileA = tree[0] + assertEquals(SourcesStatus.Emptied, fileA.children[0].status, "bound and erased") + assertEquals(SourcesStatus.Unbound, fileA.children[1].status, "unbound and erased is just unbound") + val review = filterSourcesTree(tree, "", setOf(SourcesFilter.NeedsReview)) + assertEquals(listOf("layer:art-0/lyid:1", "layer:art-0/name:Stray"), review[0].children.map { node -> node.id }, "the emptied row reviews beside the stray") + } + + /** + * A lost row says how it was lost - the file no longer has the layer, or a replacement file lacks its + * key - and an unbound layer the rigger ignored reads as ignored, under the Unbound filter and not the + * review one; a bound layer reads bound whatever its mark says. + */ + @Test + fun replacedAndIgnoredRowsReadTheirOwnStatus() { + val base = model() + val puppet = + base.copy( + atlas = base.atlas.copy(tiles = base.atlas.tiles + AtlasTile(AtlasTileId("tA9"), "Old brow", 4, 4, source = SourceLayerRef(artA, "lyid:9", true))), + sources = + base.sources.map { source -> + if (source.id != artA) { + source + } else { + source.copy( + layers = + listOf( + source.layers[0].copy(ignored = true), + source.layers[1].copy(ignored = true), + ArtSourceLayer("lyid:9", "Brow (old)", "Head", 12, 22, 4, 4, true, present = false, replaced = true), + ), + ) + } + }, + ) + val tree = buildSourcesTree(puppet, ::presence, "Unbound art") + val fileA = tree[0] + assertEquals(listOf("layer:art-0/lyid:1", "layer:art-0/lyid:2", "layer:art-0/lyid:9", "layer:art-0/name:Stray"), fileA.children.map { node -> node.id }) + assertEquals(SourcesStatus.Bound, fileA.children[0].status, "a bound row reads bound whatever its mark says") + assertEquals(SourcesStatus.Ignored, fileA.children[1].status) + assertEquals(SourcesStatus.SourceReplaced, fileA.children[2].status) + assertTrue(fileA.children[2].status.isReview) + assertTrue(!fileA.children[1].status.isReview, "ignored is settled, not under review") + assertEquals(listOf("layer:art-0/lyid:2"), filterSourcesTree(tree, "", setOf(SourcesFilter.Unbound))[0].children.map { node -> node.id }, "the ignored row shows under Unbound") + assertEquals(listOf("layer:art-0/lyid:9", "layer:art-0/name:Stray"), filterSourcesTree(tree, "", setOf(SourcesFilter.NeedsReview))[0].children.map { node -> node.id }, "the replaced row reviews beside the stray") + } + + @Test + fun keyShapesSayWhatTheyAre() { + assertTrue(layerKeyLooksStable("lyid:12")) + assertTrue(layerKeyLooksStable("3f2a-uuid")) + assertTrue(!layerKeyLooksStable("name:Eye")) + assertTrue(!layerKeyLooksStable("Eye#4")) + } + + @Test + fun aDropRebindsOnlyAcrossTheTwoKindsAndNeverOntoALostRow() { + val ref = SourceLayerRef(artA, "lyid:1", true) + + fun node(kind: SourcesNodeKind, status: SourcesStatus = SourcesStatus.None): SourcesNode = SourcesNode("row", "Row", SourcesDetail.None, kind, status, emptyList()) + + assertEquals(AtlasTileId("t") to ref, relinkFor(SourcesDragPayload.Layer(ref), node(SourcesNodeKind.Tile(AtlasTileId("t"))))) + assertEquals(AtlasTileId("t") to ref, relinkFor(SourcesDragPayload.Tile(AtlasTileId("t")), node(SourcesNodeKind.Layer(ref), SourcesStatus.Bound))) + assertEquals(null, relinkFor(SourcesDragPayload.Tile(AtlasTileId("t")), node(SourcesNodeKind.Tile(AtlasTileId("u"))))) + assertEquals(null, relinkFor(SourcesDragPayload.Layer(ref), node(SourcesNodeKind.Source(artA)))) + assertEquals(null, relinkFor(SourcesDragPayload.Tile(AtlasTileId("t")), node(SourcesNodeKind.Layer(ref), SourcesStatus.NeedsReview)), "a lost row is no target") + assertEquals(null, relinkFor(SourcesDragPayload.Tile(AtlasTileId("t")), node(SourcesNodeKind.Layer(ref), SourcesStatus.Emptied)), "nor an erased one") + assertEquals(null, relinkFor(SourcesDragPayload.Tile(AtlasTileId("t")), node(SourcesNodeKind.Layer(ref), SourcesStatus.SourceReplaced)), "nor one a replacement lost") + assertEquals(null, relinkFor(SourcesDragPayload.Tile(AtlasTileId("t")), node(SourcesNodeKind.Layer(ref), SourcesStatus.Ignored)), "nor an ignored one") + } + + /** + * A repeated inventory key (a foreign or broken file) still yields unique row ids - the list keys + * on them - and the bound tile lists once, under the first row. + */ + @Test + fun repeatedInventoryKeysKeepRowIdsUniqueAndListTilesOnce() { + val drawables = listOf(drawable("a", "t1")) + val puppet = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + atlas = PuppetAtlas(pages = emptyList(), tiles = listOf(AtlasTile(AtlasTileId("t1"), "One", 4, 4, source = SourceLayerRef(artA, "name:1", false)))), + sources = + listOf( + ArtSource( + artA, + "a.psd", + null, + "psd", + listOf( + ArtSourceLayer("name:1", "1", "", 0, 0, 4, 4, true), + ArtSourceLayer("name:1", "1", "Folder", 0, 0, 4, 4, true), + ArtSourceLayer("name:1", "1", "Folder/Deeper", 0, 0, 4, 4, true), + ), + ), + ), + ) + val file = buildSourcesTree(puppet, { SourcePresence.Unknown }, "Unbound").single() + assertEquals(listOf("layer:art-0/name:1", "layer:art-0/name:1~2", "layer:art-0/name:1~3"), file.children.map { node -> node.id }) + assertEquals(listOf("tile:t1"), file.children[0].children.map { node -> node.id }, "the first row owns the binding") + assertTrue(file.children.drop(1).all { node -> node.children.isEmpty() && node.status == SourcesStatus.Unbound }, "later rows list nothing") + + fun ids(nodes: List): List = nodes.flatMap { node -> listOf(node.id) + ids(node.children) } + val allIds = ids(listOf(file)) + assertEquals(allIds.size, allIds.toSet().size, "no row id repeats anywhere in the tree") + } + + /** + * A proposal naming a layer some tile binds stands when only a fresh, untouched drawable sits over + * that tile (a reload minted it for the re-created layer before the match could take it), and names + * the tile accepting it retires; the same layer under rig work is passed over. + */ + @Test + fun aProposalNamingALayerUnderAFreshDrawableStandsAndSaysWhatItRetires() { + val base = model() + val freshQuad = DrawableMesh(floatArrayOf(12f, 22f, 16f, 22f, 16f, 26f, 12f, 26f), floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f), intArrayOf(0, 1, 2, 0, 2, 3)) + val fresh = drawable("e", "tA5").copy(mesh = freshQuad) + val puppet = + base.copy( + drawables = base.drawables + fresh, + atlas = + base.atlas.copy( + tiles = + base.atlas.tiles + + AtlasTile(AtlasTileId("tA5"), "Brow", 4, 4, source = SourceLayerRef(artA, "lyid:5", true)) + + AtlasTile(AtlasTileId("tA9"), "Old brow", 4, 4, source = SourceLayerRef(artA, "lyid:9", true)), + ), + sources = + base.sources.map { source -> + if (source.id != artA) { + source + } else { + source.copy( + layers = + source.layers + + ArtSourceLayer("lyid:5", "Brow", "Head", 12, 22, 4, 4, true) + + ArtSourceLayer("lyid:9", "Brow (old)", "Head", 12, 22, 4, 4, true, present = false), + ) + } + }, + ) + + fun match(key: String, score: Float): LayerMatch = LayerMatch(key, score, MatchSignals(1f, 1f, 1f, 1f, null, hashEqual = false)) + val proposals: (ArtSourceId, String) -> List = { sourceId, key -> if (sourceId == artA && key == "lyid:9") listOf(match("lyid:5", 0.6f)) else emptyList() } + val lost = buildSourcesTree(puppet, ::presence, "Unbound art", suggestionsFor = proposals)[0].children.first { node -> node.id == "layer:art-0/lyid:9" } + assertEquals(LayerSuggestion("lyid:5", "Brow", 0.6f, retires = listOf(AtlasTileId("tA5"))), lost.suggestion) + val rigged = puppet.copy(drawables = puppet.drawables.map { drawable -> if (drawable.id.raw == "e") drawable.copy(parentDeformerId = DeformerId("warp")) else drawable }) + val riggedLost = buildSourcesTree(rigged, ::presence, "Unbound art", suggestionsFor = proposals)[0].children.first { node -> node.id == "layer:art-0/lyid:9" } + assertNull(riggedLost.suggestion, "under rig work the layer is passed over") + } +} \ No newline at end of file diff --git a/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/UvEditorViewStateTest.kt b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/UvEditorViewStateTest.kt new file mode 100644 index 0000000..5f8f465 --- /dev/null +++ b/module/ui/src/commonTest/kotlin/org/umamo/ui/workspace/spaces/UvEditorViewStateTest.kt @@ -0,0 +1,630 @@ +package org.umamo.ui.workspace.spaces + +import org.umamo.edit.EditorMode +import org.umamo.edit.MeshSelection +import org.umamo.edit.MeshTopology +import org.umamo.edit.Selection +import org.umamo.edit.SelectionTarget +import org.umamo.edit.UvPageKind +import org.umamo.render.ContentBounds +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.Part +import org.umamo.runtime.model.PartId +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.atlasBindingForTile +import org.umamo.ui.viewport.GizmoMeshGeometry +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the UV editor's pure view-state derivations ([resolveUvEditorPage], [resolveUvEditorLayer], + * [uvPageSelectionAfter], [shownUvDrawables], [shownLayerDrawables], [shownSurfaceUvs], + * [uvGizmoGeometries]): the pin-first page resolution with its follow-chain fallback, the + * active-drawable precedence chain both surfaces share, the untextured 1x1 fallback, the page-cycle + * transition (including out of the layer view), the Edit / Object candidate rules with the + * malformed-mesh, visibility, page, and layer filters, and the display-space projection (texel units, + * v-flip) over a page and over a layer alike. + * + * Two atlas pages are used throughout: page 0 is 64x32 (drawables "a" and "a2"), page 1 is 16x16 + * (drawable "b"); drawable "c" is unmeshed. The layer fixture is one 64x32 layer, "layer0". + */ +class UvEditorViewStateTest { + /** The default triangle's uvs: display (16, 16), (48, 16), (16, 24) on the 64x32 page. */ + private val triangleUvs = floatArrayOf(0.25f, 0.5f, 0.75f, 0.5f, 0.25f, 0.25f) + + private fun meshedDrawable( + rawId: String, + uvs: FloatArray = triangleUvs.copyOf(), + isVisible: Boolean = true, + tileId: String? = null, + ): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = DrawableMesh(floatArrayOf(0f, 0f, 2f, 0f, 0f, 2f), uvs, intArrayOf(0, 1, 2)), + geometryGrid = null, + isVisible = isVisible, + atlasTileId = tileId?.let { raw -> AtlasTileId(raw) }, + ) + + private fun bareDrawable(rawId: String): Drawable = + Drawable( + id = DrawableId(rawId), + name = rawId, + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + ) + + // Every drawable gets a root org-tree entry: visibleDrawableIds walks rootChildren, so a drawable + // absent from the tree would read as hidden. + private fun modelOf(vararg drawables: Drawable, atlas: PuppetAtlas = PuppetAtlas.Empty): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables.toList(), + rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) }, + rootPartId = null, + atlas = atlas, + ) + + /** An atlas fixture: one tile, sized, unpacked unless a placement is given. */ + private fun atlasOf( + tileId: String = "layer0", + width: Int = 64, + height: Int = 32, + placement: AtlasPlacement? = null, + ): PuppetAtlas = + PuppetAtlas( + pages = listOf(AtlasPage(128, 128)), + tiles = listOf(AtlasTile(AtlasTileId(tileId), "Art", width, height, placement)), + ) + + private fun twoPageTextures(): PuppetTextures = + PuppetTextures( + atlases = listOf(DecodedImage(ByteArray(64 * 32 * 4), 64, 32), DecodedImage(ByteArray(16 * 16 * 4), 16, 16)), + atlasIndexByDrawableId = mapOf("a" to 0, "a2" to 0, "b" to 1), + premultipliedAlpha = false, + ) + + /** The mesh selection's active drawable outranks the object selection's. */ + @Test + fun meshSelectionActiveDrawableWins() { + val model = modelOf(meshedDrawable("a"), meshedDrawable("b")) + val resolved = + resolveUvEditorPage( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("b")), activeDrawableId = DrawableId("b")), + objectSelection = Selection(setOf(SelectionTarget.Drawable(DrawableId("a"))), SelectionTarget.Drawable(DrawableId("a"))), + textures = twoPageTextures(), + ) + assertNotNull(resolved, "a meshed active drawable resolves a page") + assertEquals(1, resolved.pageIndex, "the page follows the Edit-mode active mesh") + assertEquals(16, resolved.pageWidth, "page 1's width") + assertEquals(16, resolved.pageHeight, "page 1's height") + } + + /** With no mesh-selection active drawable, the object selection's active drawable drives the page. */ + @Test + fun objectSelectionActiveDrawableIsSecond() { + val model = modelOf(meshedDrawable("a"), meshedDrawable("b")) + val resolved = + resolveUvEditorPage( + model = model, + meshSelection = MeshSelection(), + objectSelection = Selection(setOf(SelectionTarget.Drawable(DrawableId("b"))), SelectionTarget.Drawable(DrawableId("b"))), + textures = twoPageTextures(), + ) + assertNotNull(resolved, "an object-selected meshed drawable resolves a page") + assertEquals(1, resolved.pageIndex, "the object selection's active drawable is the second choice") + } + + /** With nothing selected at all, the first MESHED drawable drives the page (unmeshed ones skipped). */ + @Test + fun fallsBackToTheFirstMeshedDrawable() { + val model = modelOf(bareDrawable("c"), meshedDrawable("a"), meshedDrawable("b")) + val resolved = + resolveUvEditorPage(model = model, meshSelection = MeshSelection(), objectSelection = Selection(), textures = twoPageTextures()) + assertNotNull(resolved, "the fallback keeps the space non-blank") + assertEquals(0, resolved.pageIndex, "the first meshed drawable's page is the fallback") + } + + /** A selection naming a drawable the model no longer has (just deleted) is no selection: the first meshed drawable stands in. */ + @Test + fun aSelectionOfADeletedDrawableFallsBackToTheFirstMeshedOne() { + val model = modelOf(meshedDrawable("b")) + val page = + resolveUvEditorPage( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("gone")), activeDrawableId = DrawableId("gone")), + objectSelection = Selection(), + textures = twoPageTextures(), + ) + assertEquals(1, page?.pageIndex, "the kept drawable's page, not the placeholder") + val viaObject = + resolveUvEditorPage( + model = model, + meshSelection = MeshSelection(), + objectSelection = Selection(setOf(SelectionTarget.Drawable(DrawableId("gone"))), SelectionTarget.Drawable(DrawableId("gone"))), + textures = twoPageTextures(), + ) + assertEquals(1, viaObject?.pageIndex) + } + + /** With no meshed drawable anywhere the resolution is null (the space shows its placeholder). */ + @Test + fun resolvesNullWithNothingMeshed() { + assertNull( + resolveUvEditorPage(model = modelOf(bareDrawable("c")), meshSelection = MeshSelection(), objectSelection = Selection(), textures = twoPageTextures()), + "no meshed drawable means no page", + ) + } + + /** A meshed drawable absent from the atlas map resolves the untextured 1x1 fallback page. */ + @Test + fun untexturedDrawableGetsTheUnitPage() { + val model = modelOf(meshedDrawable("loose")) + val resolved = + resolveUvEditorPage(model = model, meshSelection = MeshSelection(), objectSelection = Selection(), textures = twoPageTextures()) + assertNotNull(resolved, "an untextured drawable still resolves") + assertNull(resolved.pageIndex, "no atlas entry means no page index") + assertEquals(1, resolved.pageWidth, "the 1x1 fallback turns the display mapping into the unit square") + assertEquals(1, resolved.pageHeight, "the 1x1 fallback turns the display mapping into the unit square") + } + + /** A pin the textures can satisfy beats the whole follow chain. */ + @Test + fun validPinShowsThePinnedPageFirst() { + val model = modelOf(meshedDrawable("a"), meshedDrawable("b")) + val resolved = + resolveUvEditorPage( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("a")), activeDrawableId = DrawableId("a")), + objectSelection = Selection(), + textures = twoPageTextures(), + textureSelection = UvTextureSelection.PinnedPage(1), + ) + assertNotNull(resolved, "a valid pin resolves a page") + assertEquals(1, resolved.pageIndex, "the pin beats the active drawable's page 0") + assertEquals(16, resolved.pageWidth, "the pinned page's width") + assertEquals(16, resolved.pageHeight, "the pinned page's height") + } + + /** A valid pin needs no meshed drawable: the empty page is still reviewable. */ + @Test + fun pinnedPageResolvesWithNoMeshedDrawable() { + val resolved = + resolveUvEditorPage( + model = modelOf(bareDrawable("c")), + meshSelection = MeshSelection(), + objectSelection = Selection(), + textures = twoPageTextures(), + textureSelection = UvTextureSelection.PinnedPage(0), + ) + assertNotNull(resolved, "the pinned page shows even with nothing meshed (contrast resolvesNullWithNothingMeshed)") + assertEquals(0, resolved.pageIndex, "the pinned page shows") + assertEquals(64, resolved.pageWidth, "the pinned page's width") + } + + /** A pin the textures cannot satisfy falls back to the follow chain without clearing anything. */ + @Test + fun outOfRangePinFallsBackToFollow() { + val model = modelOf(meshedDrawable("a"), meshedDrawable("b")) + val resolved = + resolveUvEditorPage( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("a")), activeDrawableId = DrawableId("a")), + objectSelection = Selection(), + textures = twoPageTextures(), + textureSelection = UvTextureSelection.PinnedPage(7), + ) + assertNotNull(resolved, "the follow chain still resolves") + assertEquals(0, resolved.pageIndex, "the stale pin defers to the active drawable's page") + } + + /** With no textures a pin cannot resolve: the follow chain runs, untextured fallback included. */ + @Test + fun pinWithNoTexturesFallsBackToFollow() { + val resolved = + resolveUvEditorPage( + model = modelOf(meshedDrawable("a")), + meshSelection = MeshSelection(), + objectSelection = Selection(), + textures = null, + textureSelection = UvTextureSelection.PinnedPage(0), + ) + assertNotNull(resolved, "the follow chain still resolves") + assertNull(resolved.pageIndex, "no textures means the untextured fallback, pin or not") + assertEquals(1, resolved.pageWidth, "the 1x1 fallback") + assertNull( + resolveUvEditorPage( + model = modelOf(bareDrawable("c")), + meshSelection = MeshSelection(), + objectSelection = Selection(), + textures = null, + textureSelection = UvTextureSelection.PinnedPage(0), + ), + "no textures and nothing meshed still resolves null (the placeholder)", + ) + } + + /** Next pins the following page, wrapping past the last back to the first. */ + @Test + fun nextPinsTheFollowingPageWithWrap() { + assertEquals( + UvTextureSelection.PinnedPage(1), + uvPageSelectionAfter(UvPageKind.NextPage, UvTextureSelection.FollowSelection, effectivePageIndex = 0, pageCount = 2), + "next from page 0 pins page 1", + ) + assertEquals( + UvTextureSelection.PinnedPage(0), + uvPageSelectionAfter(UvPageKind.NextPage, UvTextureSelection.PinnedPage(1), effectivePageIndex = 1, pageCount = 2), + "next from the last page wraps to the first", + ) + } + + /** Previous pins the preceding page, wrapping past the first back to the last. */ + @Test + fun previousPinsThePrecedingPageWithWrap() { + assertEquals( + UvTextureSelection.PinnedPage(1), + uvPageSelectionAfter(UvPageKind.PreviousPage, UvTextureSelection.FollowSelection, effectivePageIndex = 0, pageCount = 2), + "previous from page 0 wraps to the last", + ) + assertEquals( + UvTextureSelection.PinnedPage(0), + uvPageSelectionAfter(UvPageKind.PreviousPage, UvTextureSelection.PinnedPage(1), effectivePageIndex = 1, pageCount = 2), + "previous from page 1 pins page 0", + ) + } + + /** From the untextured fallback (null effective page) cycling lands on an end page. */ + @Test + fun cycleFromTheUntexturedFallbackPinsAnEndPage() { + assertEquals( + UvTextureSelection.PinnedPage(0), + uvPageSelectionAfter(UvPageKind.NextPage, UvTextureSelection.FollowSelection, effectivePageIndex = null, pageCount = 2), + "next from the fallback pins the first page", + ) + assertEquals( + UvTextureSelection.PinnedPage(1), + uvPageSelectionAfter(UvPageKind.PreviousPage, UvTextureSelection.FollowSelection, effectivePageIndex = null, pageCount = 2), + "previous from the fallback pins the last page", + ) + } + + /** With no pages there is nothing to pin: cycling keeps the selection unchanged from either state. */ + @Test + fun cycleNoOpsWithNoPages() { + assertEquals( + UvTextureSelection.FollowSelection, + uvPageSelectionAfter(UvPageKind.NextPage, UvTextureSelection.FollowSelection, effectivePageIndex = null, pageCount = 0), + "next with no pages keeps following", + ) + assertEquals( + UvTextureSelection.PinnedPage(3), + uvPageSelectionAfter(UvPageKind.PreviousPage, UvTextureSelection.PinnedPage(3), effectivePageIndex = null, pageCount = 0), + "previous with no pages keeps the stored (stale) pin", + ) + } + + /** The FollowSelection kind clears any pin. */ + @Test + fun followSelectionClearsThePin() { + assertEquals( + UvTextureSelection.FollowSelection, + uvPageSelectionAfter(UvPageKind.FollowSelection, UvTextureSelection.PinnedPage(1), effectivePageIndex = 1, pageCount = 2), + "follow clears the pin", + ) + } + + /** The layer view follows the active drawable, exactly as the page chain does. */ + @Test + fun layerViewFollowsTheActiveDrawable() { + val model = modelOf(meshedDrawable("a", tileId = "layer0"), meshedDrawable("b"), atlas = atlasOf()) + val resolved = + resolveUvEditorLayer( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("a")), activeDrawableId = DrawableId("a")), + objectSelection = Selection(), + ) + assertNotNull(resolved, "the active drawable's layer resolves") + assertEquals("layer0", resolved.layerKey, "the bound layer shows") + assertEquals(64, resolved.width, "the layer's own width") + assertEquals(32, resolved.height, "the layer's own height") + } + + /** + * A session-created duplicate reaches the same layer as the drawable it was copied from. + * + * The tile is a field on the drawable, so a copy carries it like every other field - unlike the atlas + * PAGE, which still resolves through textureSourceId because that map is keyed by the source format's + * own drawable ids and a fresh duplicate has no entry in it. + */ + @Test + fun layerViewFollowsADuplicateThroughItsOwnTile() { + val duplicate = meshedDrawable("a copy", tileId = "layer0").copy(textureSourceId = DrawableId("a")) + val model = modelOf(meshedDrawable("a", tileId = "layer0"), duplicate, atlas = atlasOf()) + val resolved = + resolveUvEditorLayer( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(duplicate.id), activeDrawableId = duplicate.id), + objectSelection = Selection(), + ) + assertNotNull(resolved, "the duplicate resolves its own tile") + assertEquals("layer0", resolved.layerKey, "the same layer the original shows") + } + + /** A drawable this document retains no artwork for resolves nothing, so the space keeps its page view. */ + @Test + fun layerViewResolvesNothingWithoutABinding() { + val model = modelOf(meshedDrawable("a", tileId = "layer0"), meshedDrawable("b"), atlas = atlasOf()) + assertNull( + resolveUvEditorLayer( + model = model, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("b")), activeDrawableId = DrawableId("b")), + objectSelection = Selection(), + ), + "a drawable with no tile has no layer to show", + ) + assertNull( + resolveUvEditorLayer(modelOf(meshedDrawable("a")), MeshSelection(), Selection()), + "an empty atlas means no layer view", + ) + } + + /** In OBJECT mode every drawable sharing one piece of art draws over it together; unbound ones do not. */ + @Test + fun objectModeListsEverySharerOfTheArt() { + val model = + modelOf( + meshedDrawable("a", tileId = "layer0"), + meshedDrawable("b"), + meshedDrawable("a2", tileId = "layer0"), + atlas = atlasOf(), + ) + val shown = shownLayerDrawables(model, EditorMode.Object, MeshSelection(), "layer0") + assertEquals( + listOf(DrawableId("a"), DrawableId("a2")), + shown.map { drawable -> drawable.id }, + "both users of the art are click targets, in model order", + ) + } + + /** + * In EDIT mode a layer shows only the meshes the SESSION is editing, exactly as a page does. + * + * Duplicated art means several drawables draw over one layer, but an operator can only move the + * ones the session has under edit - drawing the rest as though they were editable offers vertices + * that refuse to move and answers a drag with "no editable UVs". + */ + @Test + fun editModeListsOnlyTheSessionMeshesOverTheLayer() { + val model = + modelOf(meshedDrawable("a", tileId = "layer0"), meshedDrawable("a2", tileId = "layer0"), atlas = atlasOf()) + val shown = + shownLayerDrawables( + model, + EditorMode.Edit, + MeshSelection(drawableIds = listOf(DrawableId("a")), activeDrawableId = DrawableId("a")), + "layer0", + ) + assertEquals(listOf(DrawableId("a")), shown.map { drawable -> drawable.id }, "only the edited mesh is shown") + + val none = shownLayerDrawables(model, EditorMode.Edit, MeshSelection(), "layer0") + assertTrue(none.isEmpty(), "editing nothing shows nothing over the layer") + } + + /** The layer's frame comes from the TILE, so narrowing the shown set in Edit mode cannot shift it. */ + @Test + fun layerBindingResolvesFromTheTileNotTheShownSet() { + val model = + modelOf(meshedDrawable("a", tileId = "layer0"), meshedDrawable("a2", tileId = "layer0"), atlas = atlasOf()) + val binding = model.atlasBindingForTile(AtlasTileId("layer0")) + assertNotNull(binding, "a tile resolves a binding without being asked which drawable") + assertEquals("layer0", binding.layerKey, "and it is that tile's") + assertNull(model.atlasBindingForTile(AtlasTileId("missing")), "an unknown tile resolves nothing") + } + + /** + * The layer projection is the same texel display mapping the page view uses, over the LAYER's own + * size - an unpacked binding passes its uvs straight through, so the mapping is uv times layer size + * with the v-flip. One projection serves both views; only the uvs handed to it differ. + */ + @Test + fun layerGeometriesProjectIntoTheLayerFrame() { + val model = modelOf(meshedDrawable("a", tileId = "layer0"), atlas = atlasOf(width = 64, height = 32)) + val shown = shownLayerDrawables(model, EditorMode.Object, MeshSelection(), "layer0") + val layerView = UvEditorLayer("layer0", 64, 32) + val geometries = uvGizmoGeometries(shown, shownSurfaceUvs(shown, model, layerView), 64, 32) + assertEquals(1, geometries.size, "one geometry per bound drawable") + // The same triangleUvs the page test uses: (0.25, 0.5) -> (16, 16) on a 64x32 frame, v flipped. + val expectedPositions = floatArrayOf(16f, 16f, 48f, 16f, 16f, 24f) + for (componentIndex in expectedPositions.indices) { + assertEquals(expectedPositions[componentIndex], geometries.first().positions[componentIndex], 1e-4f, "component $componentIndex") + } + } + + /** Cycling pages from the layer view leaves it, and asking to follow returns to following. */ + @Test + fun pageCyclingLeavesTheLayerView() { + assertEquals( + UvTextureSelection.PinnedPage(0), + uvPageSelectionAfter(UvPageKind.NextPage, UvTextureSelection.SourceLayer, effectivePageIndex = null, pageCount = 2), + "next from the layer view pins a page, leaving it", + ) + assertEquals( + UvTextureSelection.FollowSelection, + uvPageSelectionAfter(UvPageKind.FollowSelection, UvTextureSelection.SourceLayer, effectivePageIndex = null, pageCount = 2), + "follow returns to following the selection", + ) + assertEquals( + UvTextureSelection.SourceLayer, + uvPageSelectionAfter(UvPageKind.NextPage, UvTextureSelection.SourceLayer, effectivePageIndex = null, pageCount = 0), + "with no pages to cycle to, the layer view holds", + ) + } + + /** Edit mode lists the session's meshes mapped to the shown page; other pages' meshes are excluded. */ + @Test + fun editModeListsTheSessionMeshesOnThePage() { + val model = modelOf(meshedDrawable("a"), meshedDrawable("b")) + val shown = + shownUvDrawables( + model = model, + mode = EditorMode.Edit, + meshSelection = MeshSelection(drawableIds = listOf(DrawableId("a"), DrawableId("b")), activeDrawableId = DrawableId("a")), + textures = twoPageTextures(), + pageIndex = 0, + ) + assertEquals(listOf(DrawableId("a")), shown.map { drawable -> drawable.id }, "only the shown page's meshes draw") + } + + /** Object mode lists EVERY visible meshed drawable mapped to the shown page, in model order. */ + @Test + fun objectModeListsEveryVisibleMeshOnThePage() { + val model = modelOf(meshedDrawable("a"), meshedDrawable("b"), meshedDrawable("a2")) + val shown = + shownUvDrawables( + model = model, + mode = EditorMode.Object, + meshSelection = MeshSelection(), + textures = twoPageTextures(), + pageIndex = 0, + ) + assertEquals( + listOf(DrawableId("a"), DrawableId("a2")), + shown.map { drawable -> drawable.id }, + "every visible page-0 mesh draws, in model order, selection playing no part", + ) + } + + /** Object mode excludes hidden islands: the drawable's own eyeball and a hidden ancestor part alike. */ + @Test + fun objectModeExcludesHiddenIslands() { + val visible = meshedDrawable("a") + val hiddenSelf = meshedDrawable("hiddenSelf", isVisible = false) + val underHiddenPart = meshedDrawable("underHiddenPart") + val hiddenPart = + Part( + id = PartId("hiddenPart"), + name = "hiddenPart", + children = listOf(OrgChild.Drawable(underHiddenPart.id)), + isVisible = false, + ) + val model = + PuppetModel( + parameters = emptyList(), + parts = listOf(hiddenPart), + deformers = emptyList(), + drawables = listOf(visible, hiddenSelf, underHiddenPart), + rootChildren = + listOf( + OrgChild.Drawable(visible.id), + OrgChild.Drawable(hiddenSelf.id), + OrgChild.Part(hiddenPart.id), + ), + rootPartId = null, + ) + val shown = + shownUvDrawables( + model = model, + mode = EditorMode.Object, + meshSelection = MeshSelection(), + // Null textures reduce the filter to visibility alone (no page filter). + textures = null, + pageIndex = null, + ) + assertEquals(listOf(DrawableId("a")), shown.map { drawable -> drawable.id }, "hidden islands neither draw nor pick") + } + + /** Meshes with an empty or size-mismatched UV array are excluded everywhere. */ + @Test + fun excludesMalformedMeshes() { + val emptyUvs = meshedDrawable("emptyUvs", uvs = FloatArray(0)) + val mismatched = meshedDrawable("mismatched", uvs = floatArrayOf(0.1f, 0.2f, 0.3f, 0.4f)) + val model = modelOf(emptyUvs, mismatched, meshedDrawable("a")) + val shown = + shownUvDrawables( + model = model, + mode = EditorMode.Edit, + meshSelection = + MeshSelection( + drawableIds = listOf(DrawableId("emptyUvs"), DrawableId("mismatched"), DrawableId("a")), + activeDrawableId = DrawableId("a"), + ), + // Null textures reduce the filter to the UV-shape checks alone (no page filter). + textures = null, + pageIndex = null, + ) + assertEquals(listOf(DrawableId("a")), shown.map { drawable -> drawable.id }, "only the well-formed mesh survives") + } + + /** The projection is the texel display mapping with the v-flip; indices and edges carry over. */ + @Test + fun projectsUvsIntoDisplaySpace() { + val drawable = meshedDrawable("a") + val geometries = + uvGizmoGeometries( + listOf(drawable), + shownSurfaceUvs(listOf(drawable), modelOf(drawable), layerView = null), + displayWidth = 64, + displayHeight = 32, + ) + assertEquals(1, geometries.size, "one geometry per meshed drawable") + val geometry = geometries.first() + assertEquals(DrawableId("a"), geometry.drawableId, "the geometry names its drawable") + // uv (0.25, 0.5) -> (16, 16), (0.75, 0.5) -> (48, 16), (0.25, 0.25) -> (16, 24): u scales by the + // width, v flips then scales by the height. + val expectedPositions = floatArrayOf(16f, 16f, 48f, 16f, 16f, 24f) + for (componentIndex in expectedPositions.indices) { + assertEquals(expectedPositions[componentIndex], geometry.positions[componentIndex], 1e-4f, "display component $componentIndex") + } + assertEquals(MeshTopology.uniqueEdges(intArrayOf(0, 1, 2)), geometry.edges, "edges derive from the triangle indices") + } + + /** Unmeshed drawables project no geometry. */ + @Test + fun skipsUnmeshedDrawables() { + val bare = listOf(bareDrawable("c")) + assertTrue( + uvGizmoGeometries(bare, shownSurfaceUvs(bare, modelOf(*bare.toTypedArray()), layerView = null), 64, 32).isEmpty(), + "a drawable with no mesh yields no geometry", + ) + } + + /** + * The extent a fit takes in beside the surface covers every shown mesh, past the surface's edge + * included - a placement moved off the page carries its islands there. A vertex that is not a number + * frames nothing, and no mesh at all yields no extent. + */ + @Test + fun islandExtentCoversEveryShownMesh() { + val onPage = GizmoMeshGeometry(DrawableId("a"), intArrayOf(0, 1, 2), emptyList(), floatArrayOf(16f, 16f, 48f, 16f, 16f, 24f)) + val pastTheEdge = GizmoMeshGeometry(DrawableId("b"), intArrayOf(0, 1, 2), emptyList(), floatArrayOf(60f, -8f, 90f, -8f, Float.NaN, 5f)) + + assertEquals(ContentBounds(16f, 16f, 32f, 8f), shownIslandExtent(listOf(onPage))) + assertEquals(ContentBounds(16f, -8f, 74f, 32f), shownIslandExtent(listOf(onPage, pastTheEdge))) + assertNull(shownIslandExtent(emptyList()), "no mesh, no extent") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/ArtworkController.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/ArtworkController.kt new file mode 100644 index 0000000..d90a846 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/ArtworkController.kt @@ -0,0 +1,350 @@ +package org.umamo.ui.app + +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.name +import io.github.vinceglb.filekit.readBytes +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import org.umamo.edit.NoticePlacement +import org.umamo.edit.deleteTile +import org.umamo.edit.setLayerIgnored +import org.umamo.edit.setTileSources +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.placedFor +import org.umamo.reimport.InventoryLayerMatcher +import org.umamo.reimport.WatchedReloadResult +import org.umamo.runtime.model.ArtSourceId +import org.umamo.storage.UmamoLog +import org.umamo.ui.document.DocumentOpenError +import org.umamo.ui.document.DocumentOpenFailure +import org.umamo.ui.document.ReadArtwork +import org.umamo.ui.document.artworkImportExtensions +import org.umamo.ui.document.artworkImportOptions +import org.umamo.ui.document.fileDisplayName +import org.umamo.ui.document.fileModifiedAtMillis +import org.umamo.ui.document.isFileSystemPath +import org.umamo.ui.document.readArtwork +import org.umamo.ui.document.readArtworkAt +import org.umamo.ui.document.readListedArtworkAt +import org.umamo.ui.document.readSourceArt +import org.umamo.ui.document.systemSourceFilePresence +import org.umamo.ui.model.AddArtworkRequest +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.MatchArtworkRequest +import org.umamo.ui.model.RelinkArtworkRequest +import org.umamo.ui.model.ReloadArtworkRequest +import org.umamo.ui.model.ReloadArtworkResult +import org.umamo.ui.model.ReloadEntry +import org.umamo.ui.model.ReplaceArtworkRequest +import org.umamo.ui.model.SourceSuggestionState +import org.umamo.ui.model.SourceSuggestions +import org.umamo.ui.model.runAddArtwork +import org.umamo.ui.model.runMatchArtwork +import org.umamo.ui.model.runRelinkArtwork +import org.umamo.ui.model.runReloadArtwork +import org.umamo.ui.model.runReplaceArtwork +import org.umamo.ui.model.scoreSourceSuggestions +import org.umamo.ui.settings.IMPORT_DELETE_ART_IGNORES_LAYER_KEY +import org.umamo.ui.workspace.commands.ArtworkOperations +import org.umamo.ui.workspace.commands.ImportArtworkRequest +import org.umamo.ui.workspace.commands.RelinkRequest +import org.umamo.ui.workspace.commands.ReloadScope +import org.umamo.ui.workspace.commands.ReplaceRequest + +/** + * An artwork file as picked and read for an add or a replace. + * + * @property ReadArtwork read The parsed art, its format, and its content hash. + * @property ArtSourceDescriptor descriptor The file's name, path, format, and hash as the document records them. + */ +private class PickedArtwork( + val read: ReadArtwork, + val descriptor: ArtSourceDescriptor, +) + +/** + * The artwork operations over ONE open puppet document: Import Artwork, Reload, the Sources space's relink, + * Match Automatically, Replace Artwork, Delete Art, and the layer ignore. Each reads files the way only + * the app can - the picker, a path on the platform's file system - and lands the result on the session as + * one undoable edit. None of them swaps the document or asks over unsaved changes: artwork is ADDED to + * the open document, the way importing an object into a Blender scene adds to it. + * + * Made per document and holding its [OpenPuppet], so every operation lands on the session its files + * belong to. The shell registers the commands (see fileArtworkCommands) and reads [operations] at + * dispatch, because the area an operation's strip shows in is a question only the shell's routing answers. + * + * @property EditorAppServices services The app's shared collaborators. + * @property OpenPuppet puppet The open puppet document with its session and pages. + * @property DocumentWatch? watch The document's artwork watcher, told how each reload ended, or null. + */ +internal class ArtworkController( + private val services: EditorAppServices, + private val puppet: OpenPuppet, + private val watch: DocumentWatch?, +) { + /** + * The suggestions the last operation that read a file scored for its unresolved bindings, for the + * Sources space's review chips. An operation replaces what stands for the files it read and leaves the + * rest; a new document starts empty, since it gets a new controller. + */ + private val suggestions = MutableStateFlow(emptyMap()) + + /** The published suggestions as the Sources space reads them: one instance for the controller's life. */ + val suggestionState: SourceSuggestionState = SourceSuggestionState(suggestions) + + /** + * The host every artwork operation over the open document lands through: the same one the repack + * builds, so an add, a reload, and a relink share its report route and its resolver pre-warm. + */ + private val host: AtlasRepackHost = + AtlasRepackHost( + session = puppet.session, + artRasters = puppet.document.artRasters, + sessionAtlasPages = puppet.atlasPages, + premultipliedAlpha = puppet.document.textures.premultipliedAlpha, + scope = services.scope, + report = { report -> services.commandRegistry.invoke("document.repackReport", report) }, + rememberOptions = { _, _ -> }, + ) + + /** + * The operations as the shell's artwork command table takes them. A reload has something to read when + * any listed file has a real path - checked without touching the disk, since the palette asks on every + * listing; a missing file is found out by the reload. + */ + val operations: ArtworkOperations = + ArtworkOperations( + importArtwork = { request, areaId -> importArtwork(request, areaId) }, + reloadArtwork = { areaId, reloadScope -> reloadArtworkFromDisk(areaId, reloadScope) }, + relinkArtwork = { request, areaId -> relinkArtwork(request, areaId) }, + matchArtwork = { areaId -> matchArtwork(areaId) }, + replaceArtwork = { request, areaId -> replaceArtwork(request, areaId) }, + deleteArt = { request -> puppet.session.deleteTile(request.tileId, ignoreLayer = services.settings.getBoolean(IMPORT_DELETE_ART_IGNORES_LAYER_KEY) == true) }, + ignoreLayer = { request -> puppet.session.setLayerIgnored(request.ref, request.ignored) }, + canReload = { puppet.session.model.value.sources.any { source -> source.path?.let(::isFileSystemPath) == true } }, + ) + + /** + * Publishes what one operation scored: the files it read take its proposals (an empty map for a file it + * read and found nothing for), and every other file keeps whatever was published last. + * + * @param Set covered The files the operation read. + * @param SourceSuggestions published What it scored for them. + */ + private fun publishSuggestions(covered: Set, published: SourceSuggestions) { + suggestions.value = suggestions.value.filterKeys { (sourceId, _) -> sourceId !in covered } + published + } + + /** + * Picks an artwork file and reads it, describing it the way the document records a file. A file that + * will not read raises the same alert an open would. + * + * @return PickedArtwork? The read file, or null for a cancelled picker or a file that would not read. + */ + private suspend fun pickArtwork(): PickedArtwork? { + val picked = services.filePicker.openFile(artworkImportExtensions) ?: return null + val bytes = + runCatching { picked.readBytes() }.getOrElse { failure -> + UmamoLog.error("failed to read ${picked.name}", failure) + services.commandRegistry.invoke("document.openFailed", DocumentOpenFailure(DocumentOpenError.ReadFailed, picked.name)) + return null + } + val read = + readArtwork(bytes, picked.name) ?: run { + services.commandRegistry.invoke("document.openFailed", DocumentOpenFailure(DocumentOpenError.Unrecognized, picked.name)) + return null + } + val path = picked.absolutePath() + return PickedArtwork(read, ArtSourceDescriptor(picked.name, path, read.kind.extension, read.contentHash, path.let(::fileModifiedAtMillis))) + } + + /** + * The artwork import: each file's layers join the open document as one undoable edit. Every layered and + * flat-raster format the registry reads comes in through this one path, from the File menu's Import row, + * the Sources space, and a drop on the window alike. The options carry the parameter template, which + * seeds only when the document has no parameters of its own - a rig's first artwork. + * + * With no [request] it asks for a file. With one it adds the files it was handed, one after another and + * each awaited: an add packs against the model as it stood when it began, so two running at once would + * each pack as though the other had not happened. A file that will not read is reported and the rest + * still land. + * + * @param ImportArtworkRequest? request The files to add, or null to ask for one. + * @param String? areaId The area the command fired over, resolved by the shell before the + * picker opens; it is where the operation strip shows once the import lands. + */ + private fun importArtwork(request: ImportArtworkRequest?, areaId: String?) { + services.scope.launch { + if (request == null) { + val picked = pickArtwork() ?: return@launch + addArtwork(picked, areaId) + return@launch + } + for (path in request.paths) { + addArtwork(readArtworkForPath(path) ?: continue, areaId) + } + } + } + + /** + * Reads the artwork file at [path], describing it the way the document records a file. + * + * A file that yields no art raises the unrecognized-file alert an open would, so a dropped file that + * turns out not to be artwork is named rather than silently skipped. The reasons are not told apart - + * a file gone since the drop, one the reader refuses, and one that is simply not art all reach the same + * row - because the reader reports them as one absence and the distinction would not change what the + * rigger does about it. + * + * @param String path The file's stored path. + * @return PickedArtwork? The read file, or null when no art came out of it. + */ + private suspend fun readArtworkForPath(path: String): PickedArtwork? { + val name = fileDisplayName(path) + val read = + readArtworkAt(path) ?: run { + services.commandRegistry.invoke("document.openFailed", DocumentOpenFailure(DocumentOpenError.Unrecognized, name)) + return null + } + return PickedArtwork(read, ArtSourceDescriptor(name, path, read.kind.extension, read.contentHash, read.lastModified)) + } + + /** + * Adds one read file's layers to the open document as one undoable edit. + * + * @param PickedArtwork artwork The read file and how the document records it. + * @param String? areaId The area the operation strip shows in. + */ + private suspend fun addArtwork(artwork: PickedArtwork, areaId: String?) { + runAddArtwork( + host, + AddArtworkRequest(artwork.read.art, artwork.descriptor, services.configuredArtworkImportOptions()), + areaId, + ) + } + + /** + * Reloads the listed artwork files that are present on disk - those the scope names, or every one - as + * one undo step; a file that cannot be read is logged and skipped. Each read is placed by its record's + * offset, so the planner compares the file against the inventory in one frame. Real file-system paths + * only: a platform uri has no reader here, so a document opened through one reloads nothing. The + * watcher hears how it ended, so it knows whether to wait for the model's new hashes, try again, or let go. + * + * @param String? areaId The area the operation strip shows in. + * @param ReloadScope? reloadScope The files to re-read, or null for every present file. + */ + private fun reloadArtworkFromDisk(areaId: String?, reloadScope: ReloadScope?) { + services.scope.launch { + val entries = ArrayList() + val covered = LinkedHashSet() + for (source in puppet.session.model.value.sources) { + if (reloadScope != null && source.id !in reloadScope.sourceIds) { + continue + } + val path = source.path ?: continue + if (systemSourceFilePresence(path) != true) { + continue + } + covered.add(source.id) + val read = readListedArtworkAt(source, path) + if (read == null) { + UmamoLog.warn("reload artwork: '${source.name}' at $path could not be read; skipped") + continue + } + entries.add(ReloadEntry(source.id, read.art, read.contentHash, read.lastModified)) + } + if (entries.isEmpty()) { + puppet.session.emitNotice("notice.reload.noFiles", NoticePlacement.StatusBar) + watch?.coordinator?.reloadFinished(covered, WatchedReloadResult.Abandoned) + return@launch + } + // A reload that lands publishes what its matcher left under the bar (scored before it minted); + // one that found nothing changed re-scores the files as they stand. + val result = runReloadArtwork(host, ReloadArtworkRequest(entries, artworkImportOptions(), InventoryLayerMatcher.DEFAULT_THRESHOLD), areaId) { scored -> publishSuggestions(covered, scored) } + if (result == ReloadArtworkResult.NothingChanged) { + publishSuggestions(covered, scoreSourceSuggestions(host, entries)) + } + watch?.coordinator?.reloadFinished( + entries.mapTo(LinkedHashSet()) { entry -> entry.sourceId }, + when (result) { + ReloadArtworkResult.Applied -> WatchedReloadResult.Applied + ReloadArtworkResult.NothingChanged -> WatchedReloadResult.NothingChanged + ReloadArtworkResult.Superseded -> WatchedReloadResult.Superseded + ReloadArtworkResult.Refused -> WatchedReloadResult.Abandoned + }, + ) + } + } + + /** + * Rebinds one or more tiles as one step. An unbind is the plain binding edit; a binding to a layer + * pulls the layer's art in when its file is on disk - or, for a CMO3-origin document whose file is not, + * from the layer PNGs the official editor decomposed into the CMO3 at import - and changes the bindings + * alone when neither can be read. + * + * @param RelinkRequest request The tiles and the binding they take. + * @param String? areaId The area the operation strip shows in. + */ + private fun relinkArtwork(request: RelinkRequest, areaId: String?) { + val ref = request.ref + if (ref == null) { + puppet.session.setTileSources(request.tileIds, null) + return + } + services.scope.launch { + val source = puppet.session.model.value.sources.firstOrNull { candidate -> candidate.id == ref.sourceId } + val read = source?.let { listed -> readSourceArt(puppet.document, listed) } + if (read?.fromCmo3 == true) { + UmamoLog.info("relink artwork: '${ref.layerKey}' read from the CMO3's own decomposed layer image, since its file could not be read on this machine") + } + runRelinkArtwork(host, RelinkArtworkRequest(request.tileIds, ref, read?.art, artworkImportOptions(), request.retire), areaId) + } + } + + /** + * Reads every listed file it can and rebinds the bindings the files no longer resolve to the layers the + * matcher is confident about, as one undo step with the threshold on the strip; what it is not sure + * about it publishes as suggestions for the rows that need review. + * + * @param String? areaId The area the operation strip shows in. + */ + private fun matchArtwork(areaId: String?) { + services.scope.launch { + val entries = ArrayList() + for (source in puppet.session.model.value.sources) { + val read = readSourceArt(puppet.document, source) ?: continue + entries.add(ReloadEntry(source.id, read.art, read.contentHash, read.lastModified)) + } + if (entries.isEmpty()) { + puppet.session.emitNotice("notice.reload.noFiles", NoticePlacement.StatusBar) + return@launch + } + val covered = entries.mapTo(HashSet()) { entry -> entry.sourceId } + runMatchArtwork( + host, + MatchArtworkRequest(entries, InventoryLayerMatcher.DEFAULT_THRESHOLD, artworkImportOptions(), standing = suggestions.value), + areaId, + ) { scored -> publishSuggestions(covered, scored) } + } + } + + /** + * Repoints one listed file at another the rigger picks: what the new file resolves by key reloads, what + * the matcher is confident about rebinds, and the rest is flagged for review with suggestions scored + * against the new file's layers. The replacement keeps the record's frame: the new file is placed by + * the offset the record already carries, since it stands in for the same art. + * + * @param ReplaceRequest request The record to repoint. + * @param String? areaId The area the operation strip shows in. + */ + private fun replaceArtwork(request: ReplaceRequest, areaId: String?) { + services.scope.launch { + val source = puppet.session.model.value.sources.firstOrNull { candidate -> candidate.id == request.sourceId } ?: return@launch + val picked = pickArtwork() ?: return@launch + runReplaceArtwork( + host, + ReplaceArtworkRequest(request.sourceId, picked.read.art.placedFor(source), picked.descriptor, picked.read.contentHash, artworkImportOptions(), InventoryLayerMatcher.DEFAULT_THRESHOLD), + areaId, + ) { scored -> publishSuggestions(setOf(request.sourceId), scored) } + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentExportController.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentExportController.kt new file mode 100644 index 0000000..dfdf97f --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentExportController.kt @@ -0,0 +1,177 @@ +package org.umamo.ui.app + +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.name +import io.github.vinceglb.filekit.write +import kotlinx.coroutines.launch +import org.umamo.format.FileKind +import org.umamo.format.cmo3.Cmo3 +import org.umamo.interop.ExportReport +import org.umamo.interop.describeExportNotice +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.storage.UmamoLog +import org.umamo.ui.document.DocumentFile +import org.umamo.ui.document.Moc3Document +import org.umamo.ui.document.Moc3ExportSessionOptions +import org.umamo.ui.document.existingBundleFiles +import org.umamo.ui.document.exportedModelFor +import org.umamo.ui.document.prepareCmo3Export +import org.umamo.ui.document.prepareMoc3Export +import org.umamo.ui.document.writeMoc3Bundle +import org.umamo.ui.model.DrawableThumbnailer +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.confirm_export_overwrite +import org.umamo.ui.resources.dialog_overwrite +import org.umamo.ui.workspace.ConfirmRequest +import org.umamo.ui.workspace.ExportOptionsRequest +import kotlin.random.Random +import kotlin.time.Clock + +/** + * The CMO3 and MOC3 exports of ONE open document. Both puppet document kinds export to either format: + * Export CMO3 reconciles onto a CMO3-origin document's retained graph and synthesizes a fresh one + * otherwise, while Export MOC3 bakes fresh from the model whatever the origin. + * + * Made per document and holding its [OpenPuppet], so the document, the session, and the page set an export + * reconciles from are the same three for the controller's whole life - a mismatched set would write one + * model's rig onto another's atlas pages. The export commands re-register whenever it is remade. + * + * @property EditorAppServices services The app's shared collaborators. + * @property OpenPuppet? puppet The open puppet document with its session and pages, or null. + * @property DocumentFile? file Where the document saves, which names the exports; null with + * no document. + * @property Moc3ExportSessionOptions moc3ExportOptions The MOC3 export dialog's session memory, sticky for the + * application's life and never persisted, so it outlives this controller. + */ +internal class DocumentExportController( + private val services: EditorAppServices, + private val puppet: OpenPuppet?, + private val file: DocumentFile?, + private val moc3ExportOptions: Moc3ExportSessionOptions, +) { + /** Whether there is a puppet document to export. */ + val canExport: Boolean = puppet != null + + /** + * Exports the open document to a `.cmo3` the rigger picks. An export is not a save: the dirty baseline + * stays put, since only a save marks the session saved, and only for the `.uma` it wrote. + */ + fun exportCmo3() { + val exported = puppet ?: return + val puppetDocument = exported.document + services.scope.launch { + val suggestedName = file?.exportBaseName ?: services.untitledName() + services.filePicker.saveFile(suggestedName, FileKind.Cmo3.extension)?.let { destination -> + val edited = exportedModelFor(puppetDocument, exported.session) + // The session's resolved page set: the document's own instance until a repack + // composed a new one, which is exactly the gate the archive patch keys on. + val effectiveTextures = exported.pageBinding().textures + // Named in the log because both outcomes are otherwise silent: an unedited model exports + // the graph as-is with an empty report, and the document's own pages mean no page patch. + UmamoLog.info( + "export: model ${if (edited === puppetDocument.puppet) "is the unedited import" else "carries session edits"}" + + " (atlas ${if (edited.atlas === puppetDocument.puppet.atlas) "unchanged" else "repacked"});" + + " pages ${if (effectiveTextures === puppetDocument.textures) "are the document's own" else "are the session's (${effectiveTextures.atlases.size})"}", + ) + // The model's own icons come from the outliner's rest-pose composite, over the same + // pages the export writes - pure CPU, so the Android shell writes them too. + val modelThumbnail = DrawableThumbnailer(edited, effectiveTextures).modelRasterFor() + val prepared = + prepareCmo3Export( + document = puppetDocument, + edited = edited, + effectiveTextures = effectiveTextures, + modelName = suggestedName, + nowMillis = Clock.System.now().toEpochMilliseconds(), + obfuscateKey = Random.nextInt(), + modelThumbnail = modelThumbnail, + ) + destination.write(Cmo3.write(prepared.model)) + reportExport(prepared.report) + UmamoLog.info("exported ${destination.absolutePath()}") + } + } + } + + /** + * Exports the open document's moc family. Options first, destination second: the choices do not depend + * on where the family lands, and recording them on confirm - before the picker - keeps them sticky + * through a cancelled picker. + */ + fun exportMoc3() { + val exported = puppet ?: return + val puppetDocument = exported.document + val moc3Document = puppetDocument as? Moc3Document + val seedModel = exportedModelFor(puppetDocument, exported.session) + services.commandRegistry.invoke( + "document.exportOptions", + ExportOptionsRequest.Moc3( + initial = moc3ExportOptions.dialogOptionsFor(puppetDocument.path, seedModel), + physicsAvailable = moc3Document?.sidecars?.any { sidecar -> sidecar.kind == Moc3Sidecars.SidecarKind.Physics } == true, + userDataAvailable = moc3Document?.sidecars?.any { sidecar -> sidecar.kind == Moc3Sidecars.SidecarKind.UserData } == true, + canvasWidth = seedModel.canvasWidth, + canvasHeight = seedModel.canvasHeight, + onConfirm = { options -> + moc3ExportOptions.recordConfirmed(puppetDocument.path, options) + services.scope.launch { + services.filePicker.saveFile(file?.exportBaseName ?: services.untitledName(), FileKind.Moc3.extension)?.let { destination -> + val bundle = + prepareMoc3Export( + document = puppetDocument, + // Re-resolved at write time: the dialog is modeless enough that the + // session could undo between confirm and the picker closing. + edited = exportedModelFor(puppetDocument, exported.session), + effectiveTextures = exported.pageBinding().textures, + // FileKit appends the extension, so the picked handle's own name is authoritative. + destinationName = destination.name, + options = options, + ) + + fun writeAndReport() { + services.scope.launch { + val written = writeMoc3Bundle(destination, bundle) + reportExport(bundle.report) + UmamoLog.info("exported $written file(s) as ${destination.absolutePath()}") + } + } + // The native save dialog confirmed the picked file only; the rest of the family + // (manifest, cdi3, textures, sidecars) lands beside it unannounced, so anything + // already there gets one warning naming what an OK would replace. + val existing = existingBundleFiles(destination, bundle) + if (existing.isEmpty()) { + writeAndReport() + } else { + services.commandRegistry.invoke( + "document.confirm", + ConfirmRequest( + message = Res.string.confirm_export_overwrite, + // File names are document data, listed in full - the dialog wraps, and a + // name the warning omitted is a file the rigger did not agree to lose. + arguments = listOf(existing.size, existing.joinToString()), + confirmLabel = Res.string.dialog_overwrite, + onConfirm = ::writeAndReport, + ), + ) + } + } + } + }, + ), + ) + } + + /** + * Surfaces an export's report: every notice to the log, and the report itself to the alert the shell + * shows. Both exports end this way - anything unrepresentable is stated, never dropped. + * + * @param ExportReport report The export's report. + */ + private fun reportExport(report: ExportReport) { + for (notice in report.notices) { + UmamoLog.warn("export: ${describeExportNotice(notice)}") + } + if (!report.isEmpty) { + services.commandRegistry.invoke("document.exportReport", report) + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentOpenController.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentOpenController.kt new file mode 100644 index 0000000..4e0fff5 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentOpenController.kt @@ -0,0 +1,131 @@ +package org.umamo.ui.app + +import kotlinx.coroutines.launch +import org.umamo.format.FileKind +import org.umamo.storage.UmamoLog +import org.umamo.storage.platformFileFromSavedPath +import org.umamo.ui.document.DocumentLoad +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.UmaDocument +import org.umamo.ui.document.addRecentFile +import org.umamo.ui.document.loadDocument +import org.umamo.ui.document.newBlankDocument +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.alert_document_read_only +import org.umamo.ui.workspace.AlertRequest + +/** + * Everything that REPLACES the open document: New, Open, the CMO3 and MOC3 imports, and a file opened by + * its stored path (Open Recent, or a file the operating system hands the running editor). Each goes + * through the unsaved-changes gate first, since a replace discards the session. + * + * Lives for the application's life, like the save controller whose gate it borrows. An artwork import is + * NOT here: it adds to the open document rather than replacing it (see ArtworkController). + * + * @property EditorAppServices services The app's shared collaborators. + * @property DocumentSaveController save The owner of the unsaved-changes gate. + */ +internal class DocumentOpenController( + private val services: EditorAppServices, + private val save: DocumentSaveController, +) { + /** + * Lands the result of a load: success records the recent file and swaps the document in, and a failure + * raises the shell's modal alert (document.openFailed) so the rigger sees why nothing opened. + * + * @param DocumentLoad load The load's result. + */ + fun applyDocumentLoad(load: DocumentLoad) { + when (load) { + is DocumentLoad.Loaded -> { + val opened = load.document + // Only a document that came from a file is recordable; a loaded one always did, but the read + // is null-safe because the type it arrives as covers the new, unsaved document too. + opened.path?.let { path -> services.settings.addRecentFile(path) } + // What the document says about its artwork files, before anything probes them: the recorded + // path is what a reload, the watcher, and the Sources space will all go by. + for (source in (opened as? PuppetDocument)?.puppet?.sources.orEmpty()) { + val recorded = source.path + if (recorded == null) { + UmamoLog.info("source artwork: '${source.name}' (${source.format}, ${source.layers.size} layer(s)) has no recorded path") + } else { + UmamoLog.info("source artwork: '${source.name}' (${source.format}, ${source.layers.size} layer(s)) recorded at $recorded") + } + } + services.onOpen(opened) + // A file that opened read-only says so once, up front: Save is greyed for the document's life, and a + // rigger who edits it for an hour before finding that out has been misled. + if (opened is UmaDocument && opened.isReadOnly) { + val entries = opened.readOnlyReasons.joinToString { reason -> "${reason.path} (${reason.kind})" } + services.commandRegistry.invoke("document.alert", AlertRequest(Res.string.alert_document_read_only, listOf(opened.displayName, entries))) + } + } + is DocumentLoad.Failed -> services.commandRegistry.invoke("document.openFailed", load.failure) + } + } + + /** + * File > New: an empty document, which replaces the open one like any other document swap - so a dirty + * document asks first. + */ + fun newDocument() { + save.confirmIfDirty { services.onOpen(newBlankDocument()) } + } + + /** + * File > Open: the native document, read whole - the one thing Open means. A dirty document asks first, + * with Save on offer, like every other document replace. + */ + fun openViaPicker() { + pickAndLoad(FileKind.Uma) + } + + /** + * File > Import > CMO3. The filter is CMO3 alone: artwork comes in through Import Artwork, which adds to + * the open document rather than replacing it, and MOC3 through its own row, which keeps the distinction + * between a source project and a baked runtime visible in the UI. Open and Save are reserved for the + * native UMA format. + */ + fun importCmo3ViaPicker() { + pickAndLoad(FileKind.Cmo3) + } + + /** + * File > Import > MOC3. The picked `.moc3` routes through loadDocument's file-level MOC3 branch, which + * discovers the model3.json manifest, the cdi3 display info, and the atlas pages beside the file. + */ + fun importMoc3ViaPicker() { + pickAndLoad(FileKind.Moc3) + } + + /** + * Opens the file at a stored path the way a recent file opens, unsaved-changes check included. The + * configured artwork import options ride along because a stored path may name an artwork file, which + * opens as a rig born from it. + * + * @param String path The stored path or uri. + */ + fun openStoredPath(path: String) { + save.confirmIfDirty { + services.scope.launch { + applyDocumentLoad(loadDocument(platformFileFromSavedPath(path), services.configuredArtworkImportOptions())) + } + } + } + + /** + * Asks for one file of [kind] and loads it over the open document, behind the unsaved-changes gate. + * FileKit's native dialog supplies its own (OS-localized) title, so none is passed. + * + * @param FileKind kind The one format the picker offers. + */ + private fun pickAndLoad(kind: FileKind) { + save.confirmIfDirty { + services.scope.launch { + services.filePicker.openFile(listOf(kind.extension))?.let { picked -> + applyDocumentLoad(loadDocument(picked)) + } + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentSaveController.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentSaveController.kt new file mode 100644 index 0000000..63f8d4d --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentSaveController.kt @@ -0,0 +1,251 @@ +package org.umamo.ui.app + +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.name +import kotlinx.coroutines.async +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.buildJsonObject +import org.umamo.edit.NoticePlacement +import org.umamo.format.FileKind +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.UmaModel +import org.umamo.render.FrameBackdrop +import org.umamo.storage.UmamoLog +import org.umamo.storage.platformFileFromSavedPath +import org.umamo.ui.document.Cmo3Document +import org.umamo.ui.document.Moc3Document +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.UMA_THUMBNAIL_SIZE +import org.umamo.ui.document.UmaWriteOutcome +import org.umamo.ui.document.addRecentFile +import org.umamo.ui.document.fileDisplayName +import org.umamo.ui.document.umamoWriterInfo +import org.umamo.ui.document.writeUmaDocument +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.alert_save_failed +import org.umamo.ui.viewport.fitSquare +import org.umamo.ui.workspace.AlertRequest +import org.umamo.ui.workspace.EDITOR_STATE_AREAS +import org.umamo.ui.workspace.EDITOR_STATE_SESSION +import org.umamo.ui.workspace.commands.DirtyDocumentPrompt +import org.umamo.ui.workspace.sessionStateJson + +/** + * How long a save waits for the renderer to draw its thumbnail before compositing one itself. A capture + * this small takes a frame or two; the wait only matters when the render thread is stuck. + */ +private const val THUMBNAIL_RENDER_TIMEOUT_MILLIS = 5_000L + +/** + * Save and Save As, and the two gates that stand in front of anything that would discard the session: + * replacing the document and quitting. + * + * Lives for the application's life and reads the open document through [EditorAppServices.current] at + * each call. The file commands register once and the exit guard installs once, so a controller that held + * a document would keep asking about whichever one was open when it was made. + * + * @property EditorAppServices services The app's shared collaborators. + */ +internal class DocumentSaveController( + private val services: EditorAppServices, +) { + /** + * Whether Save can write now: a puppet document that did not open read-only. + * + * @return Boolean True when a save is possible. + */ + fun canSaveNow(): Boolean { + val context = services.current() + return context.document is PuppetDocument && context.file?.canSave == true + } + + /** + * Saves the open document, or asks where first. The first save of a document that did not come from a + * `.uma` is a Save As suggesting the origin's name; after that a plain Save writes the same file + * without asking. + * + * The document's whole context is taken ONCE, here, and everything the save gathers comes from it - so a + * document swapped in while the save dialog is up cannot lend its pages or its area state to this + * document's file. The model and the atlas pages are snapshotted on the calling (UI) thread and the + * writer runs off it, so the editor stays usable while a large document encodes; the session is marked + * saved with that same snapshot, so an edit made meanwhile keeps the document dirty. + * + * @param Boolean saveAs True to ask where to save even when the document already has a file. + * @param Function onSaved Called once the file has landed; not called for a cancelled or failed save. + */ + fun save(saveAs: Boolean, onSaved: () -> Unit = {}) { + val context = services.current() + val puppet = context.puppet ?: return + val file = context.file ?: return + val activeSession = puppet.session + if (!file.canSave) { + return + } + if (file.saving) { + activeSession.emitNotice("notice.document.saveBusy", NoticePlacement.StatusBar) + return + } + // Kept on the holder as the save in flight, so a quit or a document replace asked for meanwhile waits + // for it instead of racing it (afterPendingSave below); it completes true only when the file landed. + file.saveJob = + services.scope.async { + val knownPath = file.umaPath + val destination = + if (!saveAs && knownPath != null) { + platformFileFromSavedPath(knownPath) + } else { + // The native save dialog owns the overwrite prompt: a .uma is one file, unlike the MOC3 family. + services.filePicker.saveFile(file.suggestedBaseName ?: services.untitledName(), FileKind.Uma.extension) ?: return@async false + } + val snapshot = activeSession.model.value + val binding = puppet.pageBinding() + // Editor state is gathered with the model, on this thread, and rides the save without ever counting as a + // change to the document (UMA §7). + val editorState = + buildJsonObject { + put(EDITOR_STATE_AREAS, context.areaViewStates.gather(context.viewport.service?.cameras().orEmpty())) + put(EDITOR_STATE_SESSION, sessionStateJson(activeSession.viewState(), activeSession.pose.value, snapshot)) + } + val base = file.base ?: UmaModel.create(umamoWriterInfo()) + file.saving = true + activeSession.emitNotice("notice.document.saving", NoticePlacement.StatusBar) + val outcome = + try { + writeUmaDocument(puppet.document, base, snapshot, binding, editorState, destination, renderedThumbnail(context.viewport)) + } finally { + file.saving = false + } + when (outcome) { + is UmaWriteOutcome.Written -> { + activeSession.markSaved(snapshot) + val path = destination.absolutePath() + file.umaPath = path + file.base = outcome.uma + services.settings.addRecentFile(path) + UmamoLog.info("saved $path") + activeSession.emitNotice("notice.document.saved", NoticePlacement.StatusBar, listOf(fileDisplayName(path))) + // Once per document, what a .uma of this origin does not carry: shown after + // the saved notice, so it is the one left on screen. + if (!file.lossNoticeShown) { + file.lossNoticeShown = true + // Logged as well as shown: a status notice is gone in seconds, and this is the one place the + // rigger is told what the new file leaves behind. + when (puppet.document) { + is Cmo3Document -> { + UmamoLog.info("saved $path from a CMO3: the CMO3 structure Umamo does not model is not in the .uma; exports from this session still reconcile onto the original") + activeSession.emitNotice("notice.document.cmo3Loss", NoticePlacement.StatusBar) + } + is Moc3Document -> { + UmamoLog.info("saved $path from a MOC3: physics, motions, expressions, user data, and pose are not in the .uma") + activeSession.emitNotice("notice.document.moc3Loss", NoticePlacement.StatusBar) + } + else -> Unit + } + } + onSaved() + true + } + is UmaWriteOutcome.Failed -> { + services.commandRegistry.invoke("document.alert", AlertRequest(Res.string.alert_save_failed, listOf(destination.name, outcome.reason))) + false + } + } + } + } + + /** + * The saved thumbnail as the viewport renderer draws it (UMA §5.6): the pose on screen, the drawables the + * editor shows, blended, masked, and colored as the viewport has them, fitted into the square over + * transparency. + * + * The render thread draws its own latest model, which can trail the snapshot this save writes by a frame; a + * thumbnail is a picture of the document, and a frame's lag does not change what it shows. + * + * @param DocumentViewportSlot viewport Where the document's render service is. + * @return RasterImage? The thumbnail, or null when there is no renderer, nothing is shown, or the render did + * not come back in time - the writer then composites one itself. + */ + private suspend fun renderedThumbnail(viewport: DocumentViewportSlot): RasterImage? { + val service = viewport.service ?: return null + val bounds = service.visibleContentBounds() ?: return null + val thumbnail = + withTimeoutOrNull(THUMBNAIL_RENDER_TIMEOUT_MILLIS) { + service.renderImage(fitSquare(bounds, UMA_THUMBNAIL_SIZE), FrameBackdrop.Transparent) + } + if (thumbnail == null) { + UmamoLog.warn("save: the renderer did not draw the thumbnail; compositing it instead") + } + return thumbnail + } + + /** + * Runs [action] once no save is being written. A save still in flight settles before anything that + * would end the process or replace the document: the write runs on a thread the process does not wait + * for, so a quit that went ahead mid-save would kill it - and a clean document (an import never edited) + * has nothing unsaved to stop the quit with. Waiting also keeps the unsaved-changes prompt from + * appearing over a running save, where its Save button could only answer that one is in progress. + * + * @param Function action What to do once nothing is being written. + */ + private fun afterPendingSave(action: () -> Unit) { + val context = services.current() + val file = context.file + if (file == null) { + action() + return + } + file.afterPendingSave( + services.scope, + onWaiting = { context.session?.emitNotice("notice.document.waitingForSave", NoticePlacement.StatusBar) }, + action = action, + ) + } + + /** + * The choices a dirty document's prompt offers: go on without saving, or save first and go on once the + * save has landed - the latter only when the document can be saved at all. + * + * @param Function proceed What the prompt stands in front of. + * @return DirtyDocumentPrompt The prompt's choices. + */ + private fun dirtyDocumentPrompt(proceed: () -> Unit): DirtyDocumentPrompt = + DirtyDocumentPrompt( + discard = proceed, + save = if (canSaveNow()) ({ save(saveAs = false, onSaved = proceed) }) else null, + ) + + /** + * Runs [proceed] - something that replaces the document - asking first when the document is dirty. + * Replacing the document discards its session, the undo history and any unsaved edits with it. The + * shell owns the confirm dialog (document.confirmReplace), keeping its Escape and Enter routing with + * every other overlay. + * + * @param Function proceed Replaces the document. + */ + fun confirmIfDirty(proceed: () -> Unit) { + afterPendingSave { + if (services.current().session?.dirty?.value == true) { + services.commandRegistry.invoke("document.confirmReplace", dirtyDocumentPrompt(proceed)) + } else { + proceed() + } + } + } + + /** + * Runs [exit], asking first when the document is dirty (document.confirmExit): quitting discards the + * session the same way a replace does. File > Exit calls this directly; the host's window close, OS + * quit, and back gesture reach it through the exit guard. + * + * @param Function exit Closes the application. + */ + fun confirmExit(exit: () -> Unit) { + afterPendingSave { + if (services.current().session?.dirty?.value == true) { + services.commandRegistry.invoke("document.confirmExit", dirtyDocumentPrompt(exit)) + } else { + exit() + } + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentViewport.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentViewport.kt new file mode 100644 index 0000000..f500a46 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentViewport.kt @@ -0,0 +1,179 @@ +package org.umamo.ui.app + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.remember +import org.umamo.edit.EditorSession +import org.umamo.storage.FilePicker +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.document.Document +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.systemSourceFilePresence +import org.umamo.ui.kit.TopLevelMenu +import org.umamo.ui.model.DrawableThumbnailer +import org.umamo.ui.model.LocalDrawableThumbnails +import org.umamo.ui.model.LocalEditorMode +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalLiveParams +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.LocalPuppetRenderSync +import org.umamo.ui.model.LocalPuppetTextures +import org.umamo.ui.model.LocalPuppetViewportService +import org.umamo.ui.model.LocalSelection +import org.umamo.ui.model.LocalSessionAtlasPages +import org.umamo.ui.model.LocalSourceArtRasters +import org.umamo.ui.model.LocalSourceFilePresence +import org.umamo.ui.model.LocalSourceSuggestions +import org.umamo.ui.model.LocalSourceWatch +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.SourceSuggestionState +import org.umamo.ui.model.SourceWatchState +import org.umamo.ui.model.rememberSessionEditorState +import org.umamo.ui.rememberIntSetting +import org.umamo.ui.settings.HistorySettings +import org.umamo.ui.viewport.AtlasPageBinding +import org.umamo.ui.viewport.LiveParamsAdapter +import org.umamo.ui.viewport.PuppetViewportServiceFactory +import org.umamo.ui.viewport.rememberPuppetViewportHost +import org.umamo.ui.workspace.LocalAreaViewStates +import org.umamo.ui.workspace.PersistentEditorShell +import org.umamo.ui.workspace.commands.ArtworkOperations + +/** + * Renders the open document inside the editor shell. For a puppet document, a per-area viewport host + * is injected (when the platform supplies a render-service factory) and the runtime model + live + * params are provided to the panels; with no document, the shell shows placeholders. + * With a null factory the model locals still mount - the outliner, parameters, and thumbnails all + * work - only the viewport areas render placeholders. The shell's workspace layout + locale are + * persisted via settings regardless of the open document. + * + * @param Document? document The open document, or null. + * @param EditorSession? session The open document's editing session (non-null for a puppet document). + * @param SessionAtlasPages? sessionAtlasPages The session's resolved atlas page set (repack/undo + * aware); null with no puppet document, in which case the document's own decoded textures are used. + * @param CommandRegistry commandRegistry The registry the file commands are registered in (drives the keymap). + * @param List appMenu The menu-bar contents, mounted by each shell. + * @param PuppetViewportServiceFactory? viewportServiceFactory Creates the platform render service, or null. + * @param FilePicker filePicker The app's native dialogs, forwarded to the shell for its own file commands. + * @param ArtworkOperations? artwork The app's artwork orchestrations over the hovered area, handed to + * the shell for a puppet document only (the shell registers the commands; see fileArtworkCommands); null + * with no puppet document, which hides them. + * @param SourceWatchState? sourceWatch The document's artwork watcher's state for the Sources space, or null. + * @param SourceSuggestionState? sourceSuggestions The published relink suggestions for the Sources space's review chips, or null. + * @param DocumentViewportSlot? viewportSlot Where the render service is handed to the operations that use it outside an + * area (a save's cameras and thumbnail, Export Image) while it lives; null when nothing asks. + * @param Function? exportImage Export Image over a 2D viewport area, handed to the shell for a puppet document on a + * platform with a renderer (the shell registers the command); null otherwise, which hides it. + */ +@Composable +internal fun DocumentViewport( + document: Document?, + session: EditorSession?, + sessionAtlasPages: SessionAtlasPages?, + commandRegistry: CommandRegistry, + appMenu: List, + viewportServiceFactory: PuppetViewportServiceFactory?, + filePicker: FilePicker, + artwork: ArtworkOperations?, + sourceWatch: SourceWatchState?, + sourceSuggestions: SourceSuggestionState?, + viewportSlot: DocumentViewportSlot? = null, + exportImage: ((viewportAreaId: String?) -> Unit)? = null, +) { + when (document) { + is PuppetDocument -> + key(document) { + // The session is created per-document by the host and is non-null for a puppet document; + // the fallback only guards a desync. Panels read LocalPuppet (a live projection of the session + // model) and drive edits through LocalEditorSession / the session-backed selection handle. + val activeSession = session ?: remember(document) { EditorSession(document.puppet, document.liveParams.values) } + // The undo cap is a preference, not a construction-time constant, so it is applied here rather + // than passed to the constructor: the desktop host builds the session outside the settings + // provider, and a committed change has to reach the stack of the document already open. Keying + // the session's own remember on the value would instead discard the stack on every change. + val historyLimit by rememberIntSetting(HistorySettings.HISTORY_LIMIT_KEY, HistorySettings.HISTORY_LIMIT_DEFAULT) + LaunchedEffect(activeSession, historyLimit) { + activeSession.historyLimit = historyLimit + } + val editorState = rememberSessionEditorState(activeSession) + // The session's resolved page set - the pixels the model's atlas value denotes. The + // fallback pair only guards the same desync the session fallback above does. + val atlasPages = + sessionAtlasPages?.binding?.value + ?: remember(document) { AtlasPageBinding(document.puppet.atlas, document.textures) } + // The factory is fixed for the app's lifetime (a platform capability, not state), so the + // conditional composable call is stable across recompositions. + val areaViewStates = LocalAreaViewStates.current + val viewport = + if (viewportServiceFactory != null) { + rememberPuppetViewportHost( + document.puppet, + atlasPages, + document.artRasters, + document.liveParams, + activeSession, + viewportServiceFactory, + // Each area reopens on the view it was saved with (UMA §7.3); read once, as the service is built. + initialCameras = remember(areaViewStates) { areaViewStates?.restoredCameras().orEmpty() }, + ) + } else { + null + } + // The render service is handed to what uses it outside an area - a save's cameras and thumbnail, + // Export Image - while it lives, and taken back when it goes, so nothing asks a disposed engine. A + // slot already refilled by a newer service is left alone. + val viewportService = viewport?.service + DisposableEffect(viewportSlot, viewportService) { + viewportSlot?.service = viewportService + onDispose { + if (viewportSlot?.service === viewportService) { + viewportSlot?.service = null + } + } + } + val liveParamsHandle = remember(document, activeSession) { LiveParamsAdapter(document.liveParams, activeSession) } + // Without a viewport the thumbnails come straight from the shared thumbnailer, so the + // outliner's hover previews work before a platform puppet renderer exists. Keyed on the + // page set: a repack stales every crop, and the live path gets the same eviction through + // the picker's setTextures. + val thumbnails = + viewport?.thumbnails + ?: remember(document, atlasPages) { DrawableThumbnailer(document.puppet, atlasPages.textures) } + val model by activeSession.model.collectAsState() + CompositionLocalProvider( + LocalPuppet provides model, + LocalEditorSession provides activeSession, + LocalLiveParams provides liveParamsHandle, + LocalDrawableThumbnails provides thumbnails, + LocalPuppetTextures provides atlasPages.textures, + LocalSessionAtlasPages provides sessionAtlasPages, + LocalSourceArtRasters provides document.artRasters, + LocalSourceFilePresence provides systemSourceFilePresence, + LocalSourceWatch provides sourceWatch, + LocalSourceSuggestions provides sourceSuggestions, + LocalPuppetRenderSync provides viewport?.renderSync, + LocalPuppetViewportService provides viewport?.service, + LocalSelection provides editorState, + LocalEditorMode provides editorState, + ) { + PersistentEditorShell( + viewportHost = viewport?.host, + commandRegistry = commandRegistry, + appMenu = appMenu, + // Registered by the shell (see fileArtworkCommands): the strip shows in the hovered work surface. + artwork = artwork, + exportImage = exportImage, + filePicker = filePicker, + ) + } + } + null -> + // No document open: the shell renders with placeholder viewport areas (no host injected). + PersistentEditorShell(commandRegistry = commandRegistry, appMenu = appMenu, filePicker = filePicker) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentWatch.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentWatch.kt new file mode 100644 index 0000000..401a6d5 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/DocumentWatch.kt @@ -0,0 +1,141 @@ +package org.umamo.ui.app + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okio.FileSystem +import okio.Path.Companion.toPath +import org.umamo.edit.EditorSession +import org.umamo.edit.NoticePlacement +import org.umamo.reimport.PollingSourceWatcher +import org.umamo.reimport.SourceWatchCoordinator +import org.umamo.reimport.SourceWatchEvent +import org.umamo.reimport.WatchMode +import org.umamo.reimport.WatchedSource +import org.umamo.settings.Settings +import org.umamo.storage.UmamoLog +import org.umamo.storage.contentHashOfFile +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.document.Document +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.fileModifiedAtMillis +import org.umamo.ui.document.isFileSystemPath +import org.umamo.ui.document.systemSourceFilePresence +import org.umamo.ui.model.SourceWatchState +import org.umamo.ui.settings.IMPORT_WATCH_MODE_KEY +import org.umamo.ui.workspace.commands.ReloadScope + +/** + * One open document's artwork watcher: the platform watcher and the policy over it, closed together. + * + * @property PollingSourceWatcher watcher The file poller. + * @property SourceWatchCoordinator coordinator The settle-hash-idle policy the app's events come from. + */ +internal class DocumentWatch( + val watcher: PollingSourceWatcher, + val coordinator: SourceWatchCoordinator, +) { + /** + * What the watcher tells the Sources space, as ONE instance for the watcher's life: it is handed to a + * static composition local, where a fresh wrapper per recomposition would invalidate the whole shell. + */ + val state: SourceWatchState = SourceWatchState(coordinator.pending, coordinator.serial) + + /** Stops the policy and the watcher. */ + fun close() { + coordinator.close() + watcher.close() + } +} + +/** + * The open document's artwork watcher, with its whole life: one per open puppet document, closed when + * the document goes, following the model's source list and landing its events on the session. + * + * The watcher runs over the CALLER's scope rather than one of its own, because that scope's dispatcher + * is what confines the coordinator's state. The watch mode is read live from settings at every + * decision, so the Import setting applies at once. A due reload goes THROUGH the command registry, so + * the operation strip shows in the last work surface exactly as a pressed Reload does; the rest are + * notices. Real file-system paths only: a platform uri has nothing to poll. + * + * @param Document? document The open document, or null. + * @param EditorSession? session The open document's session, or null. + * @param CoroutineScope scope The app composable's scope the watcher and the coordinator run in. + * @param Settings settings The settings the watch mode is read from. + * @param CommandRegistry commandRegistry The registry a due reload dispatches through. + * @return DocumentWatch? The watcher, or null with no puppet document open. + */ +@Composable +internal fun rememberDocumentWatch( + document: Document?, + session: EditorSession?, + scope: CoroutineScope, + settings: Settings, + commandRegistry: CommandRegistry, +): DocumentWatch? { + val documentWatch: DocumentWatch? = + remember(document, session) { + val activeSession = session + if (document is PuppetDocument && activeSession != null) { + val watcher = PollingSourceWatcher(scope, FileSystem.SYSTEM, statContext = Dispatchers.IO) + DocumentWatch( + watcher, + SourceWatchCoordinator( + scope = scope, + watcher = watcher, + hashOf = { path -> withContext(Dispatchers.IO) { contentHashOfFile(FileSystem.SYSTEM, path.toPath()) } }, + exists = { path -> systemSourceFilePresence(path) }, + modifiedAtOf = { path -> withContext(Dispatchers.IO) { fileModifiedAtMillis(path) } }, + isIdle = { activeSession.isQuiescent }, + mode = { WatchMode.fromKey(settings.getString(IMPORT_WATCH_MODE_KEY)) }, + ), + ) + } else { + null + } + } + DisposableEffect(documentWatch) { + onDispose { documentWatch?.close() } + } + LaunchedEffect(documentWatch, session) { + val watch = documentWatch ?: return@LaunchedEffect + val activeSession = session ?: return@LaunchedEffect + + fun trackCurrentSources() { + watch.coordinator.track( + activeSession.model.value.sources.mapNotNull { source -> + val path = source.path?.takeIf { candidate -> isFileSystemPath(candidate) } ?: return@mapNotNull null + WatchedSource(source.id, path, source.contentHash, source.lastModified) + }, + ) + } + launch { activeSession.model.collect { trackCurrentSources() } } + launch { + settings.changes.collect { changedKey -> + if (changedKey == IMPORT_WATCH_MODE_KEY) { + trackCurrentSources() + } + } + } + watch.coordinator.events.collect { event -> + when (event) { + is SourceWatchEvent.ReloadDue -> commandRegistry.invoke("document.reloadArtwork", ReloadScope(event.sourceIds)) + is SourceWatchEvent.ChangedOnDisk -> + activeSession.emitNotice("notice.watch.changed", NoticePlacement.StatusBar, listOf(event.sourceIds.size.toString())) + is SourceWatchEvent.StaleAtOpen -> + activeSession.emitNotice("notice.watch.staleAtOpen", NoticePlacement.StatusBar, listOf(event.sourceIds.size.toString())) + is SourceWatchEvent.Missing -> { + val name = activeSession.model.value.sources.firstOrNull { source -> source.id == event.sourceId }?.name ?: event.sourceId.raw + UmamoLog.warn("watch artwork: '$name' is no longer where the document read it") + activeSession.emitNotice("notice.watch.missing", NoticePlacement.StatusBar, listOf(name)) + } + } + } + } + return documentWatch +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/EditorApp.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/EditorApp.kt new file mode 100644 index 0000000..951aad0 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/EditorApp.kt @@ -0,0 +1,278 @@ +package org.umamo.ui.app + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import kotlinx.serialization.json.JsonObject +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorSession +import org.umamo.storage.FileKitFilePicker +import org.umamo.ui.LocalSettings +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.document.ArtDocument +import org.umamo.ui.document.Document +import org.umamo.ui.document.DocumentFile +import org.umamo.ui.document.ImageExportSessionOptions +import org.umamo.ui.document.Moc3ExportSessionOptions +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.UmaDocument +import org.umamo.ui.document.openDroppedFiles +import org.umamo.ui.kit.FileDropTarget +import org.umamo.ui.menu.buildAppMenu +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.title_untitled_document +import org.umamo.ui.settings.LocalQuickSetup +import org.umamo.ui.settings.QuickSetupState +import org.umamo.ui.viewport.PuppetViewportServiceFactory +import org.umamo.ui.workspace.AreaViewStates +import org.umamo.ui.workspace.EDITOR_STATE_AREAS +import org.umamo.ui.workspace.EDITOR_STATE_SESSION +import org.umamo.ui.workspace.LocalAreaViewStates +import org.umamo.ui.workspace.commands.fileCommands +import org.umamo.ui.workspace.commands.fileExportCommands +import org.umamo.ui.workspace.commands.registerAll +import org.umamo.ui.workspace.sessionViewStateOf + +/** + * The one editing session per open puppet document (the undo history + dirty state live here), + * recreated when the document swaps; null for no document. Owned at the host level so both the host's + * own chrome (e.g. the desktop title's unsaved marker) and [EditorApp] share the one session. + * + * A `.uma` opens on the session state it was saved with (docs/format/UMA.md § 7.4): the selection, the mode, the + * cursors, and the tool settings are laid into the session's FIRST snapshot, so none of it is an undo step. The + * pose arrives the same way every document's does, through its live parameters. + * + * @param Document? document The open document, or null. + * @return EditorSession? The document's session, or null with no puppet document open. + */ +@Composable +fun rememberEditorSessionFor(document: Document?): EditorSession? = + remember(document) { + (document as? PuppetDocument)?.let { puppetDocument -> + val savedState = (puppetDocument as? UmaDocument)?.uma?.editorState?.get(EDITOR_STATE_SESSION) as? JsonObject + EditorSession(puppetDocument.puppet, puppetDocument.liveParams.values, initialViewState = sessionViewStateOf(savedState)) + } + } + +/** + * Where the open document saves - one [DocumentFile] per document, keyed on the same identity as the session + * and owned at the host level for the same reason: the desktop title shows the `.uma` name the holder carries. + * + * @param Document? document The open document, or null. + * @return DocumentFile? The document's save target, or null with no document. + */ +@Composable +fun rememberDocumentFileFor(document: Document?): DocumentFile? = remember(document) { document?.let { DocumentFile(it) } } + +/** + * The shared editor shell: a custom in-window menu bar (File / Edit / Workspace / Help, drawn with the + * kit menu system) over the document viewport. The Import/Export dialogs come from FileKit; [document] is + * owned by the caller (so host chrome like the window title tracks it); [onOpen] swaps it; [onExit] + * closes. Both apps mount this one composable - desktop supplies the GL [viewportServiceFactory], + * Android passes null until its GLES renderer lands (viewport areas show placeholders, everything else + * is identical). + * + * The menu bar is drawn in-window (not a host-OS menu strip) so it looks and behaves identically on + * every platform and can sit on the workspace tab row to save vertical space - the Blender-style + * choice. The trade-off is deliberate: there is no macOS system menu strip. + * + * @param Document? document The open document, or null. + * @param EditorSession? session The open document's editing session (non-null for a puppet document); drives + * undo/redo, the Edit-menu enabled state, and the saved marker. + * @param DocumentFile? documentFile Where the document saves (the `.uma` path and the model the next save lays + * over), remembered by the host beside the session; null with no document. + * @param Function onOpen Called with a newly-opened document. + * @param Function onExit Closes the application; File > Exit runs it through the unsaved-changes guard. + * @param ExitGuard exitGuard The host's route into the same guard, for the exits the host owns (the window's + * close button, the OS's quit, Android's back gesture); the shell installs its guard here while composed. + * @param PuppetViewportServiceFactory? viewportServiceFactory Creates the platform render service, or + * null on a platform without a puppet renderer yet (viewport areas render placeholders). + * @param HostOpenRequests? openRequests Files the operating system asks the running editor to open, or null for + * a host that receives none. + */ +@Composable +fun EditorApp( + document: Document?, + session: EditorSession?, + documentFile: DocumentFile?, + onOpen: (Document) -> Unit, + onExit: () -> Unit, + exitGuard: ExitGuard, + viewportServiceFactory: PuppetViewportServiceFactory?, + openRequests: HostOpenRequests? = null, +) { + val settings = LocalSettings.current + val scope = rememberCoroutineScope() + val filePicker = remember { FileKitFilePicker() } + val commandRegistry = remember { CommandRegistry() } + // The MOC3 export dialog's session memory: sticky for the application's life, never persisted. + // Held here rather than in the shell because it must survive document swaps (nothing in this + // remember block is keyed on the document), which is also why it outlives the export controller. + val moc3ExportOptions = remember { Moc3ExportSessionOptions() } + // Export Image's session memory, held here for the same reason. + val imageExportOptions = remember { ImageExportSessionOptions() } + // Quick Setup opens on a first run - no user settings file when the app loaded - and is held here for the + // same reason: a file opened while it is up swaps the document and rebuilds the shell, which must not close it. + val quickSetup = remember { QuickSetupState(visible = !settings.foundUserFile) } + // The session's effective atlas pages: a repack swaps them and undo swaps them back, driven by the + // model through the resolver's collector. Created up here rather than in the viewport wiring so + // a save and an export read the same page set the viewport shows. + val sessionAtlasPages = + remember(document, session) { + if (document is PuppetDocument && session != null) { + SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + } else { + null + } + } + LaunchedEffect(sessionAtlasPages) { + sessionAtlasPages?.follow() + } + // An artwork import that could not carry everything as drawn says so once, on the status bar; the + // detail is already in the log. Keyed on the session as well, so the notice lands on the session + // that owns the new document rather than the one being torn down. + LaunchedEffect(document, session) { + if (document is ArtDocument && session != null && document.importNotices.isNotEmpty()) { + session.emitNotice("notice.import.artworkNotes") + } + } + // Every area's view state for this document, seeded from the editor state the file was saved with (UMA §7.3). + // Remembered here, beside the document read, so it is never paired with another document's areas. + val areaViewStates = remember(document) { AreaViewStates((document as? UmaDocument)?.uma?.editorState?.get(EDITOR_STATE_AREAS) as? JsonObject) } + // Where this document's render service is handed to a save's cameras and thumbnail and Export Image, filled + // by the viewport wiring while the service lives. + val viewportSlot = remember(document) { DocumentViewportSlot() } + + // Everything derived from the open document, as one value built beside the document read. The + // controllers made per document hold it; the ones that outlive documents read it through the holder + // below. They register their commands once (Ctrl+O and the palette dispatch through the registry) and + // the exit guard installs once, so a controller that held a document would keep asking about whichever + // one was open when it was made - none at all on a normal launch, which is a silent skip of the whole + // unsaved-changes prompt. The holder always reads the context of the composition that is live now. + val context = + remember(document, session, documentFile, sessionAtlasPages, areaViewStates, viewportSlot) { + OpenDocumentContext(document, session, documentFile, sessionAtlasPages, areaViewStates, viewportSlot) + } + val currentContext by rememberUpdatedState(context) + val currentOnOpen by rememberUpdatedState(onOpen) + val currentOnExit by rememberUpdatedState(onExit) + val currentUntitledName by rememberUpdatedState(stringResource(Res.string.title_untitled_document)) + val services = + remember { + EditorAppServices( + settings = settings, + scope = scope, + filePicker = filePicker, + commandRegistry = commandRegistry, + current = { currentContext }, + onOpen = { opened -> currentOnOpen(opened) }, + untitledName = { currentUntitledName }, + ) + } + val save = remember { DocumentSaveController(services) } + val open = remember { DocumentOpenController(services, save) } + + // A file the operating system hands the running editor - a double-clicked document on macOS, a VIEW intent + // on Android - opens the way a recent file does, unsaved-changes check included. + LaunchedEffect(openRequests) { + openRequests?.requests?.collect { requestedPath -> open.openStoredPath(requestedPath) } + } + + // The document's artwork watcher with its whole life (see rememberDocumentWatch): it follows the + // model's source list and the watch-mode setting, and lands its events on the session. + val documentWatch = rememberDocumentWatch(document, session, scope, settings, commandRegistry) + // The per-document controllers, remade with the context so each works from one consistent document, + // session, and page set. Artwork exists only for a puppet document; without one the shell hides its commands. + val artwork = remember(context, documentWatch) { context.puppet?.let { puppet -> ArtworkController(services, puppet, documentWatch) } } + val export = remember(context) { DocumentExportController(services, context.puppet, context.file, moc3ExportOptions) } + // Export Image draws through the puppet renderer, so it exists only for a puppet document on a platform + // that has one; without it the shell hides the command and the menu disables its row. + val imageExport = + remember(context) { + context.puppet?.takeIf { viewportServiceFactory != null }?.let { puppet -> + ImageExportController(services, puppet, context.file, context.viewport, imageExportOptions) + } + } + val exportImage = remember(imageExport) { imageExport?.let { controller -> { viewportAreaId: String? -> controller.exportImage(viewportAreaId) } } } + + // The host's exits pass through the same guard as File > Exit. Installed once per guard: the gate reads + // the live document, so the closure's own age does not matter. + DisposableEffect(exitGuard) { + val cleanup = exitGuard.install { exit -> save.confirmExit(exit) } + onDispose { cleanup() } + } + + // Register the document operations as real commands so the keymap and the palette drive them (Ctrl+O + // dispatches through the shell's registry). The tables themselves live with every other command table + // in org.umamo.ui.workspace.commands; only the actions are supplied here, where the document loader is. + DisposableEffect(commandRegistry) { + val cleanup = + commandRegistry.registerAll( + fileCommands( + onNew = { open.newDocument() }, + onOpen = { open.openViaPicker() }, + onSave = { save.save(saveAs = false) }, + onSaveAs = { save.save(saveAs = true) }, + canSave = { save.canSaveNow() }, + onImportCmo3 = { open.importCmo3ViaPicker() }, + onImportMoc3 = { open.importMoc3ViaPicker() }, + onOpenPath = { path -> open.openStoredPath(path) }, + onExit = { save.confirmExit { currentOnExit() } }, + ), + ) + onDispose { cleanup() } + } + // Keyed on the export controller, which is remade with the document and the session: the handlers + // always reach the pair the export reconciles from, consistent by construction. + DisposableEffect(commandRegistry, export) { + val cleanup = + commandRegistry.registerAll( + fileExportCommands( + canExport = { export.canExport }, + onExportCmo3 = { export.exportCmo3() }, + onExportMoc3 = { export.exportMoc3() }, + ), + ) + onDispose { cleanup() } + } + + // The menu bar, kept live by its own assembly (keymap, recent files, undo state, locale). Every row + // stands for a command, so the registry is all it is handed. + val appMenu = + buildAppMenu( + settings = settings, + session = session, + canSave = save.canSaveNow(), + canExport = export.canExport, + canExportImage = imageExport != null, + dispatch = { commandId, argument -> commandRegistry.invoke(commandId, argument) }, + ) + // A file dropped on the window takes the same way in as one chosen from a dialog: a document replaces + // what is open (through the unsaved-changes gate file.openPath carries), artwork is added to it. Both + // go through the registry rather than straight to a controller - that is what gives the add the hovered + // area its operation strip shows in, and what keeps a drop under the same availability gate as the menu. + FileDropTarget(onDrop = { paths -> openDroppedFiles(paths, commandRegistry) }) { + CompositionLocalProvider(LocalAreaViewStates provides areaViewStates, LocalQuickSetup provides quickSetup) { + DocumentViewport( + document = document, + session = session, + sessionAtlasPages = sessionAtlasPages, + commandRegistry = commandRegistry, + appMenu = appMenu, + viewportServiceFactory = viewportServiceFactory, + filePicker = filePicker, + artwork = artwork?.operations, + sourceWatch = documentWatch?.state, + sourceSuggestions = artwork?.suggestionState, + viewportSlot = viewportSlot, + exportImage = exportImage, + ) + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/HostOpenRequests.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/HostOpenRequests.kt new file mode 100644 index 0000000..478a93c --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/HostOpenRequests.kt @@ -0,0 +1,33 @@ +package org.umamo.ui.app + +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.receiveAsFlow + +/** + * Files the operating system asks the running editor to open: a double-clicked document macOS delivers as an + * open-file event, a document an Android file manager hands over as a VIEW intent. The host forwards each here, + * and the shell opens it the way File > Open Recent opens a stored path - through the unsaved-changes check. + * + * Buffered without limit on purpose. A cold launch's request arrives before the first composition exists to + * collect it (macOS raises the event as the process starts, Android's intent is in hand in onCreate), so a request + * has to wait for its collector rather than be dropped on the floor. The volume is a rigger's double-clicks. + * + * A path here is what the recent-files list stores: a file-system path on desktop, a `content://` uri string on + * Android. + */ +class HostOpenRequests { + private val pending = Channel(Channel.UNLIMITED) + + /** Each requested path, in the order the host asked, held until a collector takes it. */ + val requests: Flow = pending.receiveAsFlow() + + /** + * Asks the shell to open [path]. Safe from any thread, and before the shell exists. + * + * @param String path The stored path or uri string of the file to open. + */ + fun request(path: String) { + pending.trySend(path) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/ImageExportController.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/ImageExportController.kt new file mode 100644 index 0000000..0708ff9 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/ImageExportController.kt @@ -0,0 +1,150 @@ +package org.umamo.ui.app + +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.name +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okio.IOException +import org.jetbrains.compose.resources.getString +import org.umamo.edit.NoticePlacement +import org.umamo.format.FileKind +import org.umamo.format.png.PngCodec +import org.umamo.render.puppet.canvasBoundsOf +import org.umamo.storage.UmamoLog +import org.umamo.storage.writeReplacing +import org.umamo.ui.document.DocumentFile +import org.umamo.ui.document.ImageExportSessionOptions +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.alert_export_image_failed +import org.umamo.ui.resources.export_image_failed_memory +import org.umamo.ui.resources.export_image_failed_renderer +import org.umamo.ui.resources.export_options_image_no_canvas +import org.umamo.ui.resources.export_options_image_no_viewport +import org.umamo.ui.resources.export_options_image_nothing_visible +import org.umamo.ui.resources.export_options_image_too_large +import org.umamo.ui.viewport.ImageExportOptions +import org.umamo.ui.viewport.ImageFrameResult +import org.umamo.ui.viewport.MAX_IMAGE_EDGE +import org.umamo.ui.viewport.frameBackdrop +import org.umamo.ui.viewport.resolveImageFrame +import org.umamo.ui.workspace.AlertRequest +import org.umamo.ui.workspace.ExportOptionsRequest + +/** + * Export Image for ONE open document: the options dialog, the destination, a capture straight from the viewport + * renderer, and the PNG on disk. + * + * Made per document like the format exports, holding its [OpenPuppet] and the slot its render service arrives + * in. An export is not a save: nothing here touches the dirty state. + * + * @property EditorAppServices services The app's shared collaborators. + * @property OpenPuppet puppet The open puppet document with its session. + * @property DocumentFile? file Where the document saves, which names the image. + * @property DocumentViewportSlot viewport Where the document's render service is while it lives. + * @property ImageExportSessionOptions sessionOptions The dialog's session memory, which outlives this controller. + */ +internal class ImageExportController( + private val services: EditorAppServices, + private val puppet: OpenPuppet, + private val file: DocumentFile?, + private val viewport: DocumentViewportSlot, + private val sessionOptions: ImageExportSessionOptions, +) { + /** + * Opens the Export Image dialog, framed around what there is to capture right now: the 2D viewport area the + * command resolved (none when no 2D viewport has been touched), the canvas, and the shown content at the + * current pose. Confirming records what the dialog says to remember - the options, keeping a region it only + * fell back from - and continues to the destination and the render. + * + * @param String? viewportAreaId The 2D viewport area the View region frames, or null for none. + */ + fun exportImage(viewportAreaId: String?) { + val service = viewport.service ?: return + services.commandRegistry.invoke( + "document.exportOptions", + ExportOptionsRequest.Image( + initial = sessionOptions.dialogOptions(), + viewFrame = viewportAreaId?.let { areaId -> service.areaView(areaId) }, + canvasBounds = canvasBoundsOf(puppet.session.model.value), + contentBounds = service.visibleContentBounds(), + onConfirm = { options, remembered -> + sessionOptions.recordConfirmed(remembered) + services.scope.launch { export(options, viewportAreaId) } + }, + ), + ) + } + + /** + * Asks where, renders, encodes, and writes. The frame is resolved again after the picker closes rather + * than taken from the dialog, so the image is of what the viewport shows when it is drawn. + * + * @param ImageExportOptions options The confirmed options. + * @param String? viewportAreaId The 2D viewport area the View region frames, or null for none. + */ + private suspend fun export(options: ImageExportOptions, viewportAreaId: String?) { + val destination = services.filePicker.saveFile(file?.exportBaseName ?: services.untitledName(), FileKind.Png.extension) ?: return + val service = viewport.service + if (service == null) { + alert(destination, getString(Res.string.export_image_failed_renderer)) + return + } + val framing = + resolveImageFrame( + options.region, + options.scalePercent / 100f, + viewportAreaId?.let { areaId -> service.areaView(areaId) }, + canvasBoundsOf(puppet.session.model.value), + service.visibleContentBounds(), + ) + val frame = + when (framing) { + is ImageFrameResult.Framed -> framing.frame + ImageFrameResult.NoViewport -> return alert(destination, getString(Res.string.export_options_image_no_viewport)) + ImageFrameResult.NoCanvas -> return alert(destination, getString(Res.string.export_options_image_no_canvas)) + ImageFrameResult.NothingVisible -> return alert(destination, getString(Res.string.export_options_image_nothing_visible)) + is ImageFrameResult.TooLarge -> + return alert(destination, getString(Res.string.export_options_image_too_large, framing.width, framing.height, MAX_IMAGE_EDGE)) + } + puppet.session.emitNotice("notice.document.exportingImage", NoticePlacement.StatusBar) + val bytes = + try { + val image = service.renderImage(frame, options.frameBackdrop()) + if (image == null) { + alert(destination, getString(Res.string.export_image_failed_renderer)) + return + } + withContext(Dispatchers.Default) { PngCodec.write(image) } + } catch (failure: OutOfMemoryError) { + // The image and its encoding are the large allocations here, up to a gigabyte each at the edge + // limit; running short costs this export, not the editor and the rig's unsaved work. + UmamoLog.error("export image: ran out of memory at ${frame.width}x${frame.height}", failure) + alert(destination, getString(Res.string.export_image_failed_memory, frame.width, frame.height)) + return + } + try { + // Once the bytes exist they land, as with a save: a torn-down composition must not leave half a file. + withContext(NonCancellable) { destination.writeReplacing(bytes) } + } catch (failure: IOException) { + UmamoLog.error("export image: could not write ${destination.name}", failure) + alert(destination, failure.message ?: destination.name) + return + } + UmamoLog.info("exported image ${destination.absolutePath()} (${frame.width}x${frame.height})") + puppet.session.emitNotice("notice.document.exportedImage", NoticePlacement.StatusBar, listOf(destination.name)) + } + + /** + * Tells the rigger the image was not exported, and why. + * + * @param PlatformFile destination The file that was not written. + * @param String reason The already-localized reason. + */ + private fun alert(destination: PlatformFile, reason: String) { + UmamoLog.warn("export image: ${destination.name} not written: $reason") + services.commandRegistry.invoke("document.alert", AlertRequest(Res.string.alert_export_image_failed, listOf(destination.name, reason))) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/OpenDocumentContext.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/OpenDocumentContext.kt new file mode 100644 index 0000000..3df9294 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/app/OpenDocumentContext.kt @@ -0,0 +1,123 @@ +package org.umamo.ui.app + +import kotlinx.coroutines.CoroutineScope +import org.umamo.edit.EditorSession +import org.umamo.edit.seed.ParameterTemplate +import org.umamo.interop.art.ArtworkAnchor +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.settings.Settings +import org.umamo.storage.FilePicker +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.document.Document +import org.umamo.ui.document.DocumentFile +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.document.artworkImportOptions +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.settings.IMPORT_ALIGNMENT_KEY +import org.umamo.ui.settings.IMPORT_PARAMETER_TEMPLATE_KEY +import org.umamo.ui.viewport.AtlasPageBinding +import org.umamo.ui.viewport.PuppetViewportService +import org.umamo.ui.workspace.AreaViewStates + +/** + * An open puppet document with the session that edits it and the page set that session resolves to: the + * three an edit-bearing operation needs TOGETHER. Holding them as one value is what keeps a save or an + * export from pairing one document's rig with another's atlas pages. + * + * @property PuppetDocument document The open puppet document. + * @property EditorSession session Its editing session. + * @property SessionAtlasPages? atlasPages The session's resolved atlas pages (repack and undo aware), or null. + */ +internal class OpenPuppet( + val document: PuppetDocument, + val session: EditorSession, + val atlasPages: SessionAtlasPages?, +) { + /** + * The page set the session resolves to right now: the document's own pages until a repack composed a new + * set, which is the identity gate a CMO3 export's page patch and a save's stored pages both key on. Read + * at the moment of the call, since a repack or an undo swaps it. + * + * @return AtlasPageBinding The atlas value and the page pixels it denotes. + */ + fun pageBinding(): AtlasPageBinding = atlasPages?.binding?.value ?: AtlasPageBinding(document.puppet.atlas, document.textures) +} + +/** + * Everything the app derives from the open document, as one immutable value built where the document is + * read. A controller that lives for one document holds the value it was made with; a controller that + * outlives documents asks for the current one at each call and then works from that single answer, so no + * operation ever mixes one document's parts with another's. + * + * @property Document? document The open document, or null. + * @property EditorSession? session The open document's editing session (non-null for a puppet document). + * @property DocumentFile? file Where the document saves, or null with no document. + * @property SessionAtlasPages? atlasPages The session's resolved atlas pages, or null with no puppet document. + * @property AreaViewStates areaViewStates Every area's view state for this document. + * @property DocumentViewportSlot viewport The document's render service while one is live. + */ +internal class OpenDocumentContext( + val document: Document?, + val session: EditorSession?, + val file: DocumentFile?, + val atlasPages: SessionAtlasPages?, + val areaViewStates: AreaViewStates, + val viewport: DocumentViewportSlot = DocumentViewportSlot(), +) { + /** The puppet document with its session and pages, or null unless a puppet document is open with its session. */ + val puppet: OpenPuppet? = + if (document is PuppetDocument && session != null) { + OpenPuppet(document, session, atlasPages) + } else { + null + } +} + +/** + * Where the operations that use the renderer outside a viewport area - a save's cameras and thumbnail, Export + * Image - find the open document's render service. + * + * The service is built inside the document's composition, after the context that the controllers hold, so it + * is handed over here rather than through the constructor: the viewport wiring fills the slot while the + * service lives and clears it when the service goes, so nothing ever asks a disposed engine. Empty on a + * platform without a puppet renderer, where those operations fall back or hide. + */ +internal class DocumentViewportSlot { + /** The live render service, or null while there is none. */ + var service: PuppetViewportService? = null +} + +/** + * The collaborators every app controller shares, for the application's life. + * + * @property Settings settings The settings store. + * @property CoroutineScope scope The app composable's scope the controllers' work runs in. + * @property FilePicker filePicker The native open and save dialogs. + * @property CommandRegistry commandRegistry The registry the shell's dialogs and alerts are raised through. + * @property Function current The open document's context as of the call. A controller registered once + * reads the document through this rather than holding one, which is what keeps a handler registered at + * launch from asking about whichever document was open then - none at all, on a normal launch. + * @property Function onOpen Swaps a newly opened document in. + * @property Function untitledName The localized name a never-saved document's Save As suggests. + */ +internal class EditorAppServices( + val settings: Settings, + val scope: CoroutineScope, + val filePicker: FilePicker, + val commandRegistry: CommandRegistry, + val current: () -> OpenDocumentContext, + val onOpen: (Document) -> Unit, + val untitledName: () -> String, +) { + /** + * What an artwork import seeds with and where it places a later file, read at the moment the import + * runs so the preferences rows apply to the next import without a restart. + * + * @return SourceArtImportOptions The import options under the configured parameter template and anchor. + */ + fun configuredArtworkImportOptions(): SourceArtImportOptions = + artworkImportOptions( + ParameterTemplate.fromKey(settings.getString(IMPORT_PARAMETER_TEMPLATE_KEY)), + ArtworkAnchor.fromKey(settings.getString(IMPORT_ALIGNMENT_KEY)), + ) +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/ArtDocumentLoader.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/ArtDocumentLoader.kt new file mode 100644 index 0000000..a568d7a --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/ArtDocumentLoader.kt @@ -0,0 +1,238 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okio.FileSystem +import okio.Path.Companion.toPath +import org.umamo.edit.seed.ParameterTemplate +import org.umamo.format.FileKind +import org.umamo.format.FileRole +import org.umamo.format.FormatCodec +import org.umamo.format.FormatRegistry +import org.umamo.format.art.SourceArt +import org.umamo.format.binary.contentHashOf +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.rasterToSourceArt +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.ArtworkAnchor +import org.umamo.interop.art.SourceArtImport +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.ui.model.AtlasRepackRefusalReason +import org.umamo.ui.model.LoggedSourceFilePresence +import org.umamo.ui.model.SourceFilePresence +import org.umamo.ui.model.describeImportNotice +import org.umamo.ui.model.packModelAtOpen +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.initialLiveParams + +/** + * A rig born from an artwork file - a layered PSD / CLIP / KRA, or a flat raster wrapped as one layer. + * + * Nothing format-specific is retained: the reader's layer tree became the model's source inventory, + * the layers' pixels became the raster store, and the pack that ran at open became the model's atlas + * and these pages. Export has no retained graph to reconcile onto, so a CMO3 export synthesizes a + * fresh one the way a MOC3-origin document's does. + * + * @property List importNotices Everything the import could not carry as drawn - already logged, kept + * so the shell can say once that there are notes to read. + */ +class ArtDocument( + override val path: String, + override val puppet: PuppetModel, + override val textures: PuppetTextures, + override val artRasters: SourceArtRasters, + override val liveParams: LiveParams, + val importNotices: List, +) : PuppetDocument + +/** + * The options an artwork import runs with under [template] and [anchor]. The bridge takes the + * resolved parameter list and knows nothing about templates, so the template-to-parameters step + * happens once here for every caller: the shell resolves the preferences into it, and the loaders + * default through it so a caller with no setting to read still seeds the configured defaults. The + * anchor only matters to an import into a rig that already has art; a reload or a relink reads the + * options for their threshold and margin alone. + * + * @param ParameterTemplate template The parameter set to seed. + * @param ArtworkAnchor anchor Where a later file is anchored on the rig's canvas. + * @return SourceArtImportOptions The import options. + */ +fun artworkImportOptions(template: ParameterTemplate = ParameterTemplate.Default, anchor: ArtworkAnchor = ArtworkAnchor.Default): SourceArtImportOptions = + SourceArtImportOptions(parameters = template.parameters, anchor = anchor) + +/** + * A layered artwork file, or a flat raster wrapped as one layer, read for the artwork paths: the + * document open and Add Artwork into an open document. + * + * @property SourceArt art The parsed source art. + * @property FileKind kind The format it was read from. + * @property String contentHash The whole-file content hash of the bytes it was read from. + * @property Long? lastModified The file's modification time (epoch milliseconds) when read, or null + * when the bytes came without a file the platform can stat. + */ +class ReadArtwork( + val art: SourceArt, + val kind: FileKind, + val contentHash: String, + val lastModified: Long? = null, +) + +/** + * The modification time of the file at [path], or null when there is no such file or the string is + * not a path the platform can stat (a content uri). + * + * @param String path The stored path. + * @return Long? The time in epoch milliseconds, or null. + */ +fun fileModifiedAtMillis(path: String): Long? { + if (!isFileSystemPath(path)) { + return null + } + return runCatching { FileSystem.SYSTEM.metadataOrNull(path.toPath())?.lastModifiedAtMillis }.getOrNull() +} + +/** + * The file-presence probe the Sources space, the artwork operations, and the watcher all read: an okio + * existence check over a real path. A uri and a path the file system refuses both read as unknown + * rather than missing - the space must never accuse a file it could not check. One logged instance + * for the app's life, so a path is named in the log once and again only when its answer changes. + */ +internal val systemSourceFilePresence: SourceFilePresence = + LoggedSourceFilePresence { path -> + if (isFileSystemPath(path)) runCatching { FileSystem.SYSTEM.exists(path.toPath()) }.getOrNull() else null + }::probe + +/** + * The picker filter for File > Import > Artwork: every layered and flat-raster format the registry reads, + * its `.jpeg` and `.tif` aliases included. Derived from the registry rather than listed here, so a new art + * format reaches the picker by being registered. + */ +internal val artworkImportExtensions: List = FormatRegistry.extensionsFor(FileRole.Artwork) + +/** + * Reads [bytes] as artwork when they are one of the art formats the registry knows (PSD / CLIP / KRA, + * or PNG / BMP / JPEG / WebP / TIFF as a one-layer document), and null for anything else - a model + * format, an unrecognized file, or a file that fails to parse, which is logged. + * + * @param ByteArray bytes The file contents. + * @param String name The file name (the extension fallback for detection; the log's name). + * @return ReadArtwork? The art and its format, or null. + */ +fun readArtwork(bytes: ByteArray, name: String): ReadArtwork? { + val codec = FormatRegistry.detect(bytes, name) ?: return null + return runCatching { artworkOf(codec, bytes, name)?.let { art -> ReadArtwork(art, codec.kind, contentHashOf(bytes)) } } + .getOrElse { failure -> + UmamoLog.error("failed to read artwork $name", failure) + null + } +} + +/** + * Reads the artwork file at [path] - a real file-system path recorded on a source at import - off the + * calling thread, and null when it cannot: a platform uri (Android's SAF handles have no path to + * read), a missing or unreadable file, or bytes that are not artwork. Every failure is logged, so the + * reload that asked can say which file it skipped. + * + * @param String path The recorded path. + * @return ReadArtwork? The art and its format, or null. + */ +suspend fun readArtworkAt(path: String): ReadArtwork? { + if (!isFileSystemPath(path)) { + return null + } + val bytes = + withContext(Dispatchers.IO) { + runCatching { FileSystem.SYSTEM.read(path.toPath()) { readByteArray() } } + .getOrElse { failure -> + UmamoLog.error("failed to read artwork at $path", failure) + null + } + } ?: return null + val name = path.toPath().name + val lastModified = withContext(Dispatchers.IO) { fileModifiedAtMillis(path) } + val read = withContext(Dispatchers.Default) { readArtwork(bytes, name) } ?: return null + return ReadArtwork(read.art, read.kind, read.contentHash, lastModified) +} + +/** + * The source art [codec] reads out of [bytes]: a layered reader's document as it is, a flat raster + * wrapped as one layer, or null for a kind that is not artwork at all. + * + * @param FormatCodec codec The detected codec. + * @param ByteArray bytes The file contents. + * @param String name The file name (a flat raster's one layer is named after it). + * @return SourceArt? The art, or null for a non-art kind. + */ +internal fun artworkOf(codec: FormatCodec<*>, bytes: ByteArray, name: String): SourceArt? = + // detect returns a star-projected FormatCodec<*>; each kind's read result is cast to the model + // type that kind's codec is known to produce. + when (codec.kind) { + FileKind.Psd, FileKind.Clip, FileKind.Kra -> codec.read(bytes) as SourceArt + FileKind.Png, FileKind.Bmp, FileKind.Jpeg, FileKind.WebP, FileKind.Tiff -> rasterToSourceArt(codec.read(bytes) as RasterImage, name) + FileKind.Cmo3, FileKind.Moc3, FileKind.Json, FileKind.Uma -> null + } + +/** + * Assembles an [ArtDocument] from parsed source art: the bridge builds the unpacked model, the pack + * at open moves it onto pages, and the rasters the reader decoded become the document's pixel store. + * + * Every raster is wrapped into ONE decoded image up front, so the store's cached and uncached reads + * hand out the same instance for a tile - the identity the renderer's texture cache and the + * viewport's freshness test compare by. + * + * Throws nothing of its own - the byte-level [loadDocument] wraps this call, so a reader result that + * trips the bridge or the pack surfaces as ParseFailed there. + * + * @param SourceArt art The parsed source art. + * @param FileKind kind The format it was read from, recorded on the model's source list. + * @param String name The file name (the failure display name, the source's name). + * @param String path The stored path or URI string recorded on the document. + * @param SourceArtImportOptions options The seed parameters, threshold, and margin the import runs with. + * @param String? contentHash The whole-file content hash of the bytes the art was read from, recorded on its source. + * @param Long? lastModified The file's modification time when read, recorded on its source; null when unknown. + * @return DocumentLoad The loaded document, or NoArtLayers when nothing in the file can be rigged. + */ +internal fun buildArtDocument( + art: SourceArt, + kind: FileKind, + name: String, + path: String, + options: SourceArtImportOptions, + contentHash: String? = null, + lastModified: Long? = null, +): DocumentLoad { + val imported = SourceArtImport.fromSourceArt(art, ArtSourceDescriptor(name, path.takeIf { stored -> stored.isNotEmpty() }, kind.extension, contentHash, lastModified), options) + if (imported.puppet.drawables.isEmpty()) { + for (notice in imported.notices) { + UmamoLog.warn("import: ${describeImportNotice(notice)}") + } + UmamoLog.error("failed to import $path: no layer has pixels to rig") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.NoArtLayers, name)) + } + val decodedByTile = imported.rasterByTile.mapValues { (_, raster) -> DecodedImage(raster.rgba, raster.width, raster.height) } + val decodeRaster: (org.umamo.runtime.model.AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] } + val packed = packModelAtOpen(imported.puppet, decodeRaster) + val notices = + imported.notices + + packed.refusals.map { refusal -> + when (refusal.reason) { + AtlasRepackRefusalReason.LargerThanPage -> SourceArtImportNotice.LayerLargerThanPage(refusal.tileName) + else -> SourceArtImportNotice.LayerNotPacked(refusal.tileName, refusal.reason.name) + } + } + for (notice in notices) { + UmamoLog.warn("import: ${describeImportNotice(notice)}") + } + val puppet = packed.model + UmamoLog.info( + "import: $name -> ${puppet.drawables.size} drawable(s), ${puppet.parts.size} part(s), ${puppet.atlas.pages.size} page(s)," + + " ${puppet.parameters.size} parameter(s); ${notices.size} note(s)", + ) + return DocumentLoad.Loaded(ArtDocument(path, puppet, packed.textures, SourceArtRasters(decodeRaster), initialLiveParams(puppet), notices)) +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/BlankDocument.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/BlankDocument.kt new file mode 100644 index 0000000..8a85886 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/BlankDocument.kt @@ -0,0 +1,69 @@ +package org.umamo.ui.document + +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.canvasCenterWorldOriginX +import org.umamo.runtime.model.canvasCenterWorldOriginZ +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.initialLiveParams + +/** The canvas a new document starts with, in canvas pixels, until artwork brings a size of its own. */ +const val BLANK_DOCUMENT_CANVAS_SIZE = 1200f + +/** + * A rig that came from no file: what the editor opens into, and what File > New makes. + * + * Empty in every list, so there is nothing to render but the canvas - the rigger starts by bringing + * artwork in, which lands through the ordinary import (an add onto the open document) and carries the + * canvas and the parameter template with it. A document that has never been written has no [path], and + * nothing about it is special beyond that: the session, the viewport, and every panel treat it as the + * puppet document it is. + */ +class BlankDocument( + override val puppet: PuppetModel, + override val textures: PuppetTextures, + override val artRasters: SourceArtRasters, + override val liveParams: LiveParams, +) : PuppetDocument { + override val path: String? = null +} + +/** + * A new, empty document. + * + * The model is empty rather than seeded: a rigger who made a document by hand has made no parameters + * yet, and the template belongs to the artwork import that follows (`import.parameterTemplate`, seeded + * by the first art to land in a rig that has none). The canvas is the one thing a blank rig cannot do + * without - the viewport, the properties panel, and an export all read it - so it starts square at + * [BLANK_DOCUMENT_CANVAS_SIZE] with the world origin at its center, the same centering every import + * applies, and the first artwork replaces both with its own. + * + * @return BlankDocument The new document. + */ +fun newBlankDocument(): BlankDocument { + val puppet = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = BLANK_DOCUMENT_CANVAS_SIZE, + canvasHeight = BLANK_DOCUMENT_CANVAS_SIZE, + // The canvas center, the same default origin every importer derives. + worldOriginX = canvasCenterWorldOriginX(BLANK_DOCUMENT_CANVAS_SIZE), + worldOriginZ = canvasCenterWorldOriginZ(BLANK_DOCUMENT_CANVAS_SIZE), + ) + return BlankDocument( + puppet = puppet, + // No pages, and the convention a pack at open writes (premultipliedAlpha = false), so the first + // artwork to land composes its pages the way an artwork-opened document's were. + textures = PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), + // Its OWN store, never the shared SourceArtRasters.EMPTY: added artwork decodes into the store it + // is handed, so a shared one would carry this document's art into the next. + artRasters = SourceArtRasters { null }, + liveParams = initialLiveParams(puppet), + ) +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Cmo3DocumentLoader.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Cmo3DocumentLoader.kt new file mode 100644 index 0000000..43afdf9 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Cmo3DocumentLoader.kt @@ -0,0 +1,87 @@ +package org.umamo.ui.document + +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.AtlasPageSet +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasPages +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.render.UndecodablePagePolicy +import org.umamo.render.buildPuppetTextures +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.initialLiveParams + +/** + * A loaded `.cmo3`: the format model (the retained graph Export CMO3 reconciles the session's edits + * onto - Cmo3Export.apply), the runtime puppet + atlas textures + source artwork (for render), live + * params. + */ +class Cmo3Document( + override val path: String, + val cmo3: Cmo3Model, + override val puppet: PuppetModel, + override val textures: PuppetTextures, + override val artRasters: SourceArtRasters, + override val liveParams: LiveParams, + /** + * The atlas pages as the CMO3 embedded them, kept from the open so a save can store those exact bytes + * while the atlas sits at its imported baseline, whatever a later export rewrote in the graph. A document + * assembled by hand (a test probe) has none, and a save of it derives its pages instead. + */ + val pageSet: AtlasPageSet = AtlasPageSet.EMPTY, + /** + * A tile's layer PNG as the CMO3 embedded it, or null for a tile the graph has no image for - the same + * lookup the raster store decodes through, exposed so a save can copy the bytes without a decode. + */ + val tilePng: (AtlasTileId) -> ByteArray? = { null }, +) : PuppetDocument + +/** + * Assembles a [Cmo3Document] from an already-parsed CMO3. Unlike the MOC3 loader this needs no + * sibling files at all: a `.cmo3` carries its own pixels, so the whole document comes out of the one + * parsed graph. + * + * Throws nothing of its own - the byte-level [loadDocument] wraps this call, so a malformed-but- + * parseable graph that trips the import or the atlas walk surfaces as ParseFailed there. + * + * @param Cmo3Model cmo3 The parsed CMO3. + * @param String name The file name (the failure display name). + * @param String path The stored path or URI string recorded on the document. + * @return DocumentLoad The loaded document, or the failure reason. + */ +internal fun buildCmo3Document(cmo3: Cmo3Model, name: String, path: String): DocumentLoad { + val root = cmo3.root as? CModelSource + if (root == null) { + UmamoLog.error("failed to open $path: the CMO3 has no model source") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.ParseFailed, name)) + } + val imported = Cmo3Import.importModelSource(root) + val puppet = imported.puppet + // The atlas walk takes the root plus a pixel lookup rather than the Cmo3Model itself, which is what + // keeps it in :interop's commonMain; the archive-backed lookup is the only JVM-bound half and it is + // supplied from here. Decoding is the renderer's, and a CMO3 skips a page that will not decode + // rather than refusing the document: its pixels are embedded in the model file, so one corrupt + // resource inside an otherwise editable rig must not cost the rigger everything else. Skip never + // returns null, so the fallback is unreachable - the shared builder's return type is nullable only + // to serve the Fail policy. + val pageSet = cmo3AtlasPages(root, imported.atlasIngest, cmo3::extractLayerPng) + val textures = + buildPuppetTextures( + pageSet.pageBytes, + pageSet.atlasIndexByDrawableId, + pageSet.premultipliedAlpha, + UndecodablePagePolicy.Skip, + ) ?: PuppetTextures(emptyList(), emptyMap(), pageSet.premultipliedAlpha) + // The source artwork's PIXELS. Its inventory and placements are model state, read by the import + // above (whose one atlas walk also yields the per-tile resources); this is only the lazy byte + // supplier, which defers every raster to first request so opening a model with hundreds of layers + // costs no more than opening one without. + val tileResources = imported.atlasIngest.imageResourceByTile + val tilePng: (AtlasTileId) -> ByteArray? = { tileId -> tileResources[tileId]?.let(cmo3::extractLayerPng) } + val artRasters = SourceArtRasters.fromPng(tilePng) + return DocumentLoad.Loaded(Cmo3Document(path, cmo3, puppet, textures, artRasters, initialLiveParams(puppet), pageSet, tilePng)) +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Cmo3ExportPolicy.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Cmo3ExportPolicy.kt new file mode 100644 index 0000000..89032cc --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Cmo3ExportPolicy.kt @@ -0,0 +1,151 @@ +package org.umamo.ui.document + +import org.umamo.format.raster.RasterImage +import org.umamo.interop.cmo3.Cmo3Conversion +import org.umamo.interop.cmo3.Cmo3Export +import org.umamo.render.PuppetTextures +import org.umamo.render.encodeAtlasPng +import org.umamo.runtime.model.PuppetModel + +/* + * Decides WHAT a CMO3 export writes; the app layer picks the destination and writes the bytes. + * + * The counterpart to Moc3ExportPolicy, and pure for the same reason: the origin branch below is the + * difference between reconciling onto a retained graph and synthesizing a fresh one, which is the + * single most consequential choice the export makes and so is the one that most needs a test. + */ + +/** + * Lowers [edited] into a CMO3 for [document], by whichever route the document's origin allows. + * + * A CMO3-origin document reconciles onto the graph it retained from import, which is what keeps its + * real layered art and its byte-identity gates intact. A MOC3-origin or artwork-origin document has + * no retained graph, so a fresh one is synthesized from the blank skeleton plus its atlas pages and + * then reconciled onto in exactly the same way. + * + * The clock and the container key are PARAMETERS, not calls: [Cmo3Conversion.freshCmo3] is + * deterministic given them, and that determinism is only reachable if the seam extends to the app + * boundary. The caller is the one place that reads a wall clock or mints a key. + * + * @param PuppetDocument document The document being exported. + * @param PuppetModel edited The model to write; see [exportedModelFor]. + * @param PuppetTextures effectiveTextures The SESSION's page set; recomposed pages reach the + * archive through it, and the document's own instance means + * the archive is left untouched. + * @param String modelName The display name a synthesized skeleton records. + * @param Long nowMillis The timestamp a synthesized image chain, or a layer minted into a + * retained graph, records. + * @param Int obfuscateKey The container XOR key; the editor mints one per save. + * @param RasterImage? modelThumbnail The model's rest-pose thumbnail the file's model icons take, + * or null to leave them (blank on a fresh graph, the import's on a + * retained one). + * @return PreparedCmo3Export The model to serialize plus its report. + */ +fun prepareCmo3Export( + document: PuppetDocument, + edited: PuppetModel, + effectiveTextures: PuppetTextures, + modelName: String, + nowMillis: Long, + obfuscateKey: Int, + modelThumbnail: RasterImage? = null, +): PreparedCmo3Export = + when (document) { + // A CMO3-origin document reconciles onto its retained graph. The page patch is gated by + // INSTANCE identity: the session's resolver republishes the document's own textures whenever + // the atlas sits at its imported baseline (an unedited document, or a repack undone), so + // passing pages here happens exactly when the session composed new ones - the strict gate the + // byte-identity contract needs. + is Cmo3Document -> { + val recomposedPages = + if (effectiveTextures !== document.textures) { + effectiveTextures.atlases.map { page -> + Cmo3Conversion.AtlasPage(encodeAtlasPng(page), page.width, page.height) + } + } else { + emptyList() + } + // The document's own rasters ride along so a reloaded tile rewrites its retained layer and + // an added tile mints one; the reconcile reads them only for tiles the graph must change. + val report = + Cmo3Export.apply( + edited, + document.cmo3, + recomposedPages = recomposedPages, + tileRasters = { tileId -> document.artRasters.decodeRaster(tileId)?.let { decoded -> RasterImage(decoded.width, decoded.height, decoded.rgba) } }, + nowMillis = nowMillis, + modelThumbnail = modelThumbnail, + ) + PreparedCmo3Export(document.cmo3, report) + } + // An artwork-origin document has no retained graph either: the pages it packed at open, or the + // session's repack of them, are re-encoded and synthesized into a fresh graph the same way, + // with the document's own rasters handed over so every tile writes its real layer rather than + // a slice of a page. A new document that was never saved is the same case - whatever artwork + // was brought into it is in its own store, and an untouched one synthesizes an empty rig. + is ArtDocument, is BlankDocument -> { + val result = + Cmo3Conversion.freshCmo3( + puppet = edited, + pages = effectiveTextures.atlases.map { page -> Cmo3Conversion.AtlasPage(encodeAtlasPng(page), page.width, page.height) }, + pageIndexByDrawableId = effectiveTextures.atlasIndexByDrawableId, + modelName = modelName, + nowMillis = nowMillis, + obfuscateKey = obfuscateKey, + tileRasters = { tileId -> document.artRasters.decodeRaster(tileId)?.let { decoded -> RasterImage(decoded.width, decoded.height, decoded.rgba) } }, + modelThumbnail = modelThumbnail, + ) + PreparedCmo3Export(result.model, result.report) + } + // A UMA document has no retained graph either: a fresh graph is synthesized as for an artwork + // document, with the file's stored render pages as the image chain while the atlas is at the + // document's baseline (the same identity gate as the CMO3 branch), and a re-encode of the effective + // pages otherwise. The document's own rasters ride along so every tile writes its real layer. + is UmaDocument -> { + val stored = document.storedPages?.takeIf { pageSet -> effectiveTextures === document.textures && pageSet.pageBytes.size == effectiveTextures.atlases.size } + val pages = + effectiveTextures.atlases.mapIndexed { pageIndex, page -> + Cmo3Conversion.AtlasPage(stored?.pageBytes?.get(pageIndex) ?: encodeAtlasPng(page), page.width, page.height) + } + val result = + Cmo3Conversion.freshCmo3( + puppet = edited, + pages = pages, + pageIndexByDrawableId = effectiveTextures.atlasIndexByDrawableId, + modelName = modelName, + nowMillis = nowMillis, + obfuscateKey = obfuscateKey, + tileRasters = { tileId -> document.artRasters.decodeRaster(tileId)?.let { decoded -> RasterImage(decoded.width, decoded.height, decoded.rgba) } }, + modelThumbnail = modelThumbnail, + ) + PreparedCmo3Export(result.model, result.report) + } + // A MOC3-origin document has no retained graph: synthesize a fresh one from the blank skeleton + // + the retained atlas pages, then reconcile onto it. + is Moc3Document -> { + val result = + Cmo3Conversion.freshCmo3( + puppet = edited, + pages = conversionPagesFor(document), + pageIndexByDrawableId = document.textures.atlasIndexByDrawableId, + modelName = modelName, + nowMillis = nowMillis, + obfuscateKey = obfuscateKey, + modelThumbnail = modelThumbnail, + ) + PreparedCmo3Export(result.model, result.report) + } + } + +/** + * The atlas pages a fresh-graph synthesis builds its image chain from: the document's page PNGs + * ([Moc3Document.pagePngs], which says why the decoded set is the list) with each decoded page's size. + * + * @param Moc3Document document The MOC3-origin document being converted. + * @return List The pages, in decoded page order. + */ +private fun conversionPagesFor(document: Moc3Document): List = + document.pagePngs().mapIndexed { pageIndex, pngBytes -> + val decoded = document.textures.atlases[pageIndex] + Cmo3Conversion.AtlasPage(pngBytes = pngBytes, width = decoded.width, height = decoded.height) + } \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Document.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Document.kt new file mode 100644 index 0000000..15cf950 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Document.kt @@ -0,0 +1,181 @@ +package org.umamo.ui.document + +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.name +import io.github.vinceglb.filekit.readBytes +import org.umamo.edit.EditorSession +import org.umamo.format.FileKind +import org.umamo.format.FormatRegistry +import org.umamo.format.binary.contentHashOf +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.ui.viewport.LiveParams + +/** + * An open editor document - a parsed source file the viewport renders. Lives in jvmAndroidMain (not + * commonMain) because loading goes through :format's FormatRegistry / CMO3 codec, which is JVM-only + * API shared by the desktop-JVM and Android targets. + */ +sealed interface Document { + /** + * The stored path or URI string this document was read from (the recent-files key + window title + * source), or null for a document that was never on disk - a new, unsaved one. + * + * Nullable rather than a placeholder string: a stand-in path would be recorded in recent files and + * offered as a save target, both of which name a file that does not exist. + */ + val path: String? + + /** + * File name for titles/menus, falling back to [UNTITLED_DOCUMENT_NAME] for a document with no file. + * + * Deliberately not localized - this also reaches the log and an export's suggested file name, which + * are stable-text surfaces. The window title localizes the unsaved case itself. + */ + val displayName: String get() = path?.let(::fileDisplayName) ?: UNTITLED_DOCUMENT_NAME +} + +/** What a document with no file is called wherever a plain string is needed (the log, an export's name). */ +const val UNTITLED_DOCUMENT_NAME = "Untitled" + +/** + * A document the editor shell runs a full puppet session over - the shared face of every format that + * imports to a [PuppetModel]. The session, viewport, and panels consume only this surface, so a new + * puppet-producing format plugs in by adding a subtype; format-specific state (the CMO3 model kept for + * export reconcile, the MOC3 container kept for a future re-bake) stays on the concrete type. + * + * Each subtype lives with its loader rather than here - `Cmo3Document` in Cmo3DocumentLoader.kt, + * `Moc3Document` in Moc3DocumentLoader.kt - so this file holds only what every format shares. + */ +sealed interface PuppetDocument : Document { + /** The imported runtime puppet the session edits and the viewport renders. */ + val puppet: PuppetModel + + /** The decoded atlas pages + per-drawable page index backing the puppet's preview. */ + val textures: PuppetTextures + + /** + * The source artwork's pixels the puppet was authored against, keyed by atlas tile. Each + * drawable's link to its source tile lives in the model now (`PuppetModel.atlas`), not here - this + * is only the lazy byte supplier. + * + * A document that retains no source art still supplies a store of its own, empty to begin with: a + * CMO3 keeps every layer's pixels in its graph, a MOC3 is the packed endpoint of that pipeline and + * has none, and artwork brought into either afterwards decodes into whichever store it was handed. + * That is why there is no shared empty instance to fall back on - one document's added art would + * read back out of the next document's store. A surface that shows source art therefore checks for + * emptiness rather than assuming. + */ + val artRasters: SourceArtRasters + + /** The live parameter values driving the preview pose. */ + val liveParams: LiveParams +} + +/** + * The model an export should write for [document]: the session's edited model when [session] belongs + * to this document, else the document's own unedited puppet. + * + * A session left over from a previously opened document would export the WRONG puppet if trusted + * blindly, so a mismatch is logged as an error and the document's own unedited puppet is exported + * instead - giving logged proof if a desync like that ever recurs. + * + * @param PuppetDocument document The document being exported. + * @param EditorSession? session The shell's current session, if any. + * @return PuppetModel The model to export. + */ +fun exportedModelFor(document: PuppetDocument, session: EditorSession?): PuppetModel { + val documentSession = session?.takeIf { candidate -> candidate.baselineModel === document.puppet } + if (session != null && documentSession == null) { + UmamoLog.error("export: session does not belong to ${document.displayName}; exporting the unedited document") + } + return documentSession?.model?.value ?: document.puppet +} + +/** + * The outcome of loading a file into a [Document]: the document, or the reason there is none. + * Failures carry a [DocumentOpenFailure] so the caller can surface a localized alert (the shell's + * document.openFailed command) instead of failing silently to the log. + */ +sealed interface DocumentLoad { + /** Loaded successfully; [document] is ready to open. */ + class Loaded(val document: Document) : DocumentLoad + + /** Failed to load; [failure] says why and names the file. */ + class Failed(val failure: DocumentOpenFailure) : DocumentLoad +} + +/** + * Loads a picked/stored file into a [Document] via [loadDocument]'s byte core, reading through + * FileKit's common API so desktop paths and Android SAF URIs take the same route. A `.moc3` is the + * one format routed to the sidecar-discovering loader instead: its manifest, display info, and atlas + * pages live in sibling files, so it can only open from a file with a resolvable directory - which is + * also why the byte-level overload keeps reporting it NotOpenable. + * + * @param PlatformFile file The picked or reconstructed file handle. + * @param SourceArtImportOptions importOptions What an artwork import seeds and trims with; ignored by + * the model formats. + * @return DocumentLoad The loaded document, or the failure reason (missing, unrecognized, or failed to parse). + */ +suspend fun loadDocument(file: PlatformFile, importOptions: SourceArtImportOptions = artworkImportOptions()): DocumentLoad { + val bytes = + runCatching { file.readBytes() }.getOrElse { + UmamoLog.error("failed to read ${file.name}", it) + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.ReadFailed, file.name)) + } + if (FormatRegistry.detect(bytes, file.name)?.kind == FileKind.Moc3) { + return loadMoc3Document(file, bytes) + } + return loadDocument(bytes, file.name, file.absolutePath(), importOptions) +} + +/** + * Loads [bytes] into a [Document] by detecting the format from the contents - magic bytes via + * [FormatRegistry], with a file-extension fallback on [name] - then building the matching document: + * a `.cmo3` imports as the puppet it holds, a layered artwork file (PSD / CLIP / KRA) or a flat + * raster (PNG / BMP / JPEG / WebP / TIFF) becomes a fresh rig through the artwork import, packed at + * open. Returns a [DocumentLoad.Failed] if the content is unrecognized, not openable in the editor + * shell, or fails to parse - failures are logged, never thrown, so the UI keeps the document it had. + * + * @param ByteArray bytes The file contents. + * @param String name The file name (the extension fallback for detection; the failure display name). + * @param String path The stored path or URI string recorded on the document. + * @param SourceArtImportOptions importOptions What an artwork import seeds and trims with. + * @return DocumentLoad The loaded document, or the failure reason. + */ +fun loadDocument( + bytes: ByteArray, + name: String, + path: String, + importOptions: SourceArtImportOptions = artworkImportOptions(), +): DocumentLoad = + runCatching { + val codec = FormatRegistry.detect(bytes, name) + if (codec == null) { + UmamoLog.warn("$path is not a format that Umamo recognizes") + return@runCatching DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.Unrecognized, name)) + } + // The native document: read whole, never imported. + if (codec.kind == FileKind.Uma) { + return@runCatching buildUmaDocument(bytes, name, path) + } + if (codec.kind == FileKind.Cmo3) { + // detect returns a star-projected FormatCodec<*>; each kind's read result is cast to the model + // type that kind's codec is known to produce. + return@runCatching buildCmo3Document(codec.read(bytes) as Cmo3Model, name, path) + } + val artwork = artworkOf(codec, bytes, name) + if (artwork == null) { + UmamoLog.warn("$path is a .${codec.kind.extension} file, which the editor shell can't open") + return@runCatching DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.NotOpenable, name)) + } + buildArtDocument(artwork, codec.kind, name, path, importOptions, contentHashOf(bytes), fileModifiedAtMillis(path)) + }.getOrElse { + UmamoLog.error("failed to open $path", it) + DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.ParseFailed, name)) + } \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/DocumentFile.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/DocumentFile.kt new file mode 100644 index 0000000..efb3c8c --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/DocumentFile.kt @@ -0,0 +1,96 @@ +package org.umamo.ui.document + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.launch +import org.umamo.format.uma.UmaModel + +/** + * Where a document saves, held apart from the document itself. + * + * A [Document] is the identity the editing session keys on, so a save must not replace it: a CMO3-origin + * document stays a Cmo3Document after its first save, and its exports keep reconciling onto the graph it + * retained. Everything a save changes lives here instead - the `.uma` the document now lives in and the + * [UmaModel] the next save lays over - one holder per open document, remembered by the host beside the + * session. A document with no file yet (a new one, or an import that was never saved) has no path until + * its first Save As, which is what makes that first Save a Save As. + */ +class DocumentFile(origin: Document) { + /** + * The `.uma` a plain Save writes without asking: the file the document was opened from, or the one its + * first Save As wrote; null until then. The window title follows it. + */ + var umaPath: String? by mutableStateOf((origin as? UmaDocument)?.path) + + /** + * The document the next save lays over, so every key this version does not know and every tile the + * file already holds survive in place: the file as opened, then each save's result; null until the first + * save mints an empty one. + */ + var base: UmaModel? = (origin as? UmaDocument)?.uma + + /** Whether the document opened read-only - it holds a required entry this version cannot interpret. */ + val readOnly: Boolean = (origin as? UmaDocument)?.isReadOnly == true + + /** Whether a save can be written at all: a puppet document that did not open read-only. */ + val canSave: Boolean = origin is PuppetDocument && !readOnly + + /** True while a save is running; a second save asked meanwhile is refused with a notice. */ + var saving: Boolean by mutableStateOf(false) + + /** + * The save in flight, completing true when the file landed and false when it did not (a cancelled + * dialog, a refused or failed write); null before the first save. Kept so that whatever would end the + * process or replace the document can wait for it ([afterPendingSave]). + */ + var saveJob: Deferred? = null + + /** + * Runs [action] once no save is being written: at once when none is in flight, else when the one in + * flight lands - and not at all when it fails. + * + * Quitting is what makes this necessary. The write runs on a background thread the process does not + * wait for, so an exit that went ahead mid-save would kill it, leaving a partial temporary on disk and + * no file - even for a document that reads as clean, since an import that was never edited has nothing + * unsaved to stop the quit with. A failed save abandons the action because the rigger asked for a file + * and did not get one; the failure alert says why, and quitting is theirs to ask for again. + * + * @param CoroutineScope scope The scope the wait runs in. + * @param Function onWaiting Called when there is a save to wait for, before the wait. + * @param Function action What to do once nothing is being written. + */ + fun afterPendingSave(scope: CoroutineScope, onWaiting: () -> Unit = {}, action: () -> Unit) { + val pending = saveJob + if (pending == null || pending.isCompleted) { + action() + return + } + onWaiting() + scope.launch { + if (pending.await()) { + action() + } + } + } + + /** Whether the once-per-document loss notice of a CMO3- or MOC3-origin document has been posted. */ + var lossNoticeShown: Boolean = false + + /** + * The name a Save As suggests: the origin's file name minus its extension, so `Erica.cmo3` suggests + * `Erica`; null for a document with no file, which the caller names the localized untitled name. + */ + val suggestedBaseName: String? = origin.path?.let { saveSuggestedName(origin.displayName) } + + /** + * The name an export suggests: the `.uma` the document saves to, else the file it came from, minus the + * extension - so a document saved as `hero.uma` exports as `hero`, and one opened from `hero.psd` as `hero`, + * not `hero.psd`. Read live, so it follows a Save As; null for a document with neither, which the caller + * names the localized untitled name. + */ + val exportBaseName: String? + get() = umaPath?.let { path -> saveSuggestedName(fileDisplayName(path)) } ?: suggestedBaseName +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/DropRoute.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/DropRoute.kt new file mode 100644 index 0000000..a3ec83c --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/DropRoute.kt @@ -0,0 +1,88 @@ +package org.umamo.ui.document + +import org.umamo.format.FileRole +import org.umamo.format.FormatRegistry +import org.umamo.storage.UmamoLog +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.workspace.commands.ImportArtworkRequest + +/** + * What a set of dropped files means: which way in the gesture takes, and which of its files that way + * leaves behind. + * + * A drop is one gesture, so it gets one meaning. The FIRST file decides which - a rigger dragging a + * document in and a rigger dragging artwork in are doing two different things, and there is no honest + * reading of a gesture that does both at once. Whatever the chosen way cannot use is reported as + * [ignored] rather than silently dropped, so a rigger who grabbed more than they meant to can see it. + * + * Classified by extension alone, deliberately. The extension is enough to pick the route, and the route's + * own loader then detects the real format from the bytes - so a mislabelled file still ends up refused by a + * reader rather than accepted by a router. That is the same division the command line already uses for a + * path handed over by the operating system. + */ +internal sealed interface DropRoute { + /** The files the chosen way in cannot use, in the order they were dropped. */ + val ignored: List + + /** + * Open [path] as the whole document, replacing what is open. + * + * Also where a file of no recognized kind lands: the loader is what tells a rigger their file is not + * one Umamo reads, and it already does that with a named alert. + * + * @property String path The file to open. + * @property List ignored The rest of the drop - only one document can be open. + */ + class OpenDocument(val path: String, override val ignored: List) : DropRoute + + /** + * Add [paths] to the open document as source artwork. + * + * @property List paths The artwork files to add, in the order they were dropped. + * @property List ignored Everything in the drop that was not artwork. + */ + class AddArtwork(val paths: List, override val ignored: List) : DropRoute + + /** Nothing to do - the drop carried no files. */ + data object None : DropRoute { + override val ignored: List = emptyList() + } +} + +/** + * Reads what a drop of [paths] means (see [DropRoute] for why the first file decides). + * + * @param List paths The dropped files' stored paths, in the order the platform reported them. + * @return DropRoute The way in, and what it leaves behind. + */ +internal fun dropRouteFor(paths: List): DropRoute { + val first = paths.firstOrNull() ?: return DropRoute.None + if (FormatRegistry.kindForFileName(first)?.role == FileRole.Artwork) { + val artwork = paths.filter { path -> FormatRegistry.kindForFileName(path)?.role == FileRole.Artwork } + return DropRoute.AddArtwork(artwork, paths - artwork.toSet()) + } + return DropRoute.OpenDocument(first, paths.drop(1)) +} + +/** + * Opens what was dropped on the editor, by dispatching the command its [DropRoute] calls for. + * + * Through the registry rather than into a controller, for two reasons: the artwork add needs the hovered + * area its operation strip shows in, which only the shell's routing can answer at dispatch, and a document + * open needs the unsaved-changes gate that `file.openPath` is defined to carry. Both are already what + * those ids do, so a drop is one more way in to them and not a path of its own. + * + * @param List paths The dropped files' stored paths, in the order the platform reported them. + * @param CommandRegistry commands The registry the two file commands are registered in. + */ +internal fun openDroppedFiles(paths: List, commands: CommandRegistry) { + val route = dropRouteFor(paths) + if (route.ignored.isNotEmpty()) { + UmamoLog.info("drag and drop: ${route.ignored.size} dropped file(s) were not used - ${route.ignored.joinToString()}") + } + when (route) { + is DropRoute.OpenDocument -> commands.invoke("file.openPath", route.path) + is DropRoute.AddArtwork -> commands.invoke("file.importArtwork", ImportArtworkRequest(route.paths)) + DropRoute.None -> Unit + } +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/ExportOptionsSession.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/ExportOptionsSession.kt new file mode 100644 index 0000000..107bee0 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/ExportOptionsSession.kt @@ -0,0 +1,109 @@ +package org.umamo.ui.document + +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.viewport.ImageExportOptions + +/** + * The MOC3 export dialog's session memory: what the rigger last confirmed, held for the life of the + * application and deliberately NEVER persisted to settings. + * + * Two lifetimes live in one object. The toggles are sticky across documents - a rigger who exports + * without hidden parts wants that for the next model too. The scale is sticky only per document: + * pixels per unit is a property of one rig's bake (its default is the canvas width), so carrying a + * confirmed scale onto a DIFFERENT document would silently bake it at the previous model's size - + * on a document change it re-seeds from the model instead. + * + * A plain class rather than Compose state on purpose: the dialog copies the returned value into its + * own editing state, so nothing observes this between exports and it stays unit-testable. + */ +class Moc3ExportSessionOptions { + private var confirmed: Moc3ExportOptions? = null + private var confirmedDocumentPath: String? = null + + /** + * The options the export dialog should open with for the document at [documentPath]. + * + * First open of the session returns the dialog defaults, which match the official editor's bake + * (hidden objects and guides dropped) rather than [Moc3ExportOptions.Default]'s carry-everything + * API contract. After a confirm, returns the confirmed toggles, with the scale re-seeded from + * [puppet] whenever [documentPath] is not the document the confirm happened on. + * + * @param String? documentPath The current document's identity, or null for one with no file, which + * has no identity to be the same document twice - its scale re-seeds from the model every time. + * @param PuppetModel puppet The model the scale seeds from on a document change. + * @return Moc3ExportOptions The options to open the dialog with. + */ + fun dialogOptionsFor(documentPath: String?, puppet: PuppetModel): Moc3ExportOptions { + val remembered = confirmed ?: moc3ExportDialogDefaults() + val seededScale = + if (documentPath != null && confirmedDocumentPath == documentPath) { + remembered.pixelsPerUnitOverride ?: Moc3Export.mocPixelsPerUnitFor(puppet) + } else { + Moc3Export.mocPixelsPerUnitFor(puppet) + } + return remembered.copy(pixelsPerUnitOverride = seededScale) + } + + /** + * Records what the rigger confirmed, making it the seed for the next dialog open. + * + * Called on dialog confirm rather than after the write, so the choices survive a cancelled file + * picker: deciding the options and choosing a destination are separate steps. + * + * @param String? documentPath The document the confirm happened on, or null for one with no file. + * @param Moc3ExportOptions options The confirmed options. + */ + fun recordConfirmed(documentPath: String?, options: Moc3ExportOptions) { + confirmed = options + confirmedDocumentPath = documentPath + } +} + +/** + * The Export Image dialog's session memory: what the rigger last confirmed, held for the life of the + * application and never persisted, like the MOC3 dialog's. + * + * Every choice is sticky across documents: a region, a scale, and a background say how the rigger wants + * their images, not anything about one rig. A region the next document cannot offer (no canvas, no + * viewport touched) is the dialog's to fall back from, not this store's. + */ +class ImageExportSessionOptions { + private var confirmed: ImageExportOptions? = null + + /** + * The options the Export Image dialog should open with: the last confirmed, or the defaults before any. + * + * @return ImageExportOptions The options to open the dialog with. + */ + fun dialogOptions(): ImageExportOptions = confirmed ?: ImageExportOptions.Default + + /** + * Records what the rigger confirmed, on the dialog's confirm rather than after the write, so the choices + * survive a cancelled file picker. + * + * @param ImageExportOptions options The confirmed options. + */ + fun recordConfirmed(options: ImageExportOptions) { + confirmed = options + } +} + +/** + * The export dialog's first-launch defaults, matching the official editor's bake: hidden objects + * and guides are DROPPED unless ticked, every sidecar is included, and the scale seeds from the + * model. + * + * Deliberately not [Moc3ExportOptions.Default]: that value is the API's compatibility contract for + * options-less calls (carry everything, exactly as the lowering behaved before options existed), + * while this is what a rigger who never touched the dialog gets - the editor-matching bake. + * + * @return Moc3ExportOptions The dialog defaults. + */ +fun moc3ExportDialogDefaults(): Moc3ExportOptions = + Moc3ExportOptions( + exportHiddenParts = false, + exportHiddenDrawables = false, + exportGuideImageParts = false, + ) \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3DocumentLoader.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3DocumentLoader.kt new file mode 100644 index 0000000..23e1cb1 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3DocumentLoader.kt @@ -0,0 +1,316 @@ +package org.umamo.ui.document + +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.name +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okio.FileSystem +import okio.Path.Companion.toPath +import org.umamo.format.moc3.Moc3 +import org.umamo.format.moc3.json.Cdi3Json +import org.umamo.format.moc3.json.Model3Json +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.interop.moc3.import.moc3AtlasPages +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.render.UndecodablePagePolicy +import org.umamo.render.buildPuppetTextures +import org.umamo.render.encodeAtlasPng +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.initialLiveParams + +/** + * A `.moc3` imported together with its JSON sidecars and external atlas pages. None of the file's + * undigested form is retained, because the MOC3 export bakes every section fresh from the model with + * no reference container involved (docs/format/MOC3.md § 8) - which is why this class has no + * counterpart to [Cmo3Document]'s retained graph. That one IS load-bearing: the CMO3 export + * reconciles onto it. The original atlas page PNGs are the one thing kept ([atlasPages], in model3 + * texture order): both exports prefer those exact bytes over re-encoding the decoded RGBA, Export CMO3 + * embedding them in the synthesized graph's image chain and Export MOC3 writing them beside the moc. + * Each export falls back to a re-encode for any decoded page this list does not reach, so the page + * numbering the drawables address stays intact either way. + */ +class Moc3Document( + override val path: String, + override val puppet: PuppetModel, + override val textures: PuppetTextures, + override val liveParams: LiveParams, + val atlasPages: List, + /** The parsed manifest, whose texture names and non-file sections a MOC3 export re-emits. */ + val manifest: Model3Json, + /** + * Every sidecar the manifest referenced and the loader could read, each carrying the manifest + * section it came from and its manifest-relative name (`Erica.physics3.json`, + * `motion/idle.motion3.json`). + * + * Retained as TEXT, unparsed: Umamo models none of these, so a MOC3 export re-emits them verbatim + * rather than rebuilding them from a model that never held them. Reading them at import is what + * makes that possible at all - a picker-driven export has no access to the source directory. + * + * The KIND travels with the text because only the manifest knows it. A rigger is free to name the + * physics file anything, and re-deriving the kind from the file name later would drop such a file + * into the motion catch-all - written beside the moc, but no longer wired into the manifest. + */ + val sidecars: List, +) : PuppetDocument { + /** + * Its own store, empty at open: a baked model retains no source art, but artwork added afterwards + * decodes into whatever store the document hands the add - so this document needs one of its own + * rather than a shared empty instance, whose contents would follow the next document. + */ + override val artRasters: SourceArtRasters = SourceArtRasters { null } + + /** + * The page PNGs in DECODED page order: the retained bytes where the family had them, a re-encode of the + * decoded page where it did not. + * + * The decoded set is the list, because that is what the drawables' page indices were resolved against; + * the retained bytes are only the preferred payload for each of those pages. Re-encoding rather than + * skipping a page the family lacks keeps every later page's number under the drawables that reference it. + * Both the CMO3 export's image chain and a UMA save's stored render pages read this. + * + * @return List One PNG per decoded page. + */ + fun pagePngs(): List = textures.atlases.mapIndexed { pageIndex, decoded -> atlasPages.getOrNull(pageIndex) ?: encodeAtlasPng(decoded) } +} + +/** + * Loads a picked `.moc3` plus its sidecars into a [Moc3Document]. A baked model is a file family, + * not a single file: the `.model3.json` manifest next to the moc names the atlas PNGs (and + * the optional cdi3/physics3/... sidecars), all resolved relative to the moc's directory. + * + * The whole pipeline runs on Dispatchers.IO: the sibling reads are blocking okio IO, and the decode + * plus import that interleave them are seconds of CPU on a real model (a single 8192 atlas page is + * 256MB of RGBA) - none of which may run on the caller's dispatcher, which is the Compose Main + * thread for every interactive open. + * + * Desktop-first: sibling discovery needs a real directory, so an Android SAF `content://` handle + * (which has no resolvable parent) fails cleanly as MissingManifest until a folder-picker flow exists. + * + * @param PlatformFile file The picked or reconstructed `.moc3` handle. + * @param ByteArray mocBytes The moc's already-read contents. + * @return DocumentLoad The loaded document, or the failure reason. + */ +suspend fun loadMoc3Document(file: PlatformFile, mocBytes: ByteArray): DocumentLoad = + withContext(Dispatchers.IO) { + val path = file.absolutePath() + val directory = runCatching { path.toPath().parent }.getOrNull() + buildMoc3Document( + path = path, + name = file.name, + mocBytes = mocBytes, + readRelative = { reference -> + directory?.let { baseDirectory -> + runCatching { FileSystem.SYSTEM.read(baseDirectory / reference) { readByteArray() } }.getOrNull() + } + }, + ) + } + +/** + * Assembles a [Moc3Document] from a moc's bytes and its sidecars, every sibling read injected via + * [readRelative] so the discovery/failure rules unit-test without a filesystem. The rules: + * + * - `.model3.json` is REQUIRED - absent fails as MissingManifest; present but + * unparseable fails as ParseFailed (the file exists, so "not found" would mislead). + * - Every texture the manifest lists is REQUIRED, and every mesh's textureIndex must land inside + * that list - an empty list, a missing file, an undecodable page, or an out-of-range index + * fails as MissingTexture: a puppet without its atlas wiring is broken, not degraded. + * - cdi3 (display names) is OPTIONAL - the manifest's DisplayInfo reference first, then the + * basename fallback; absent or unparseable degrades to raw format ids. + * - physics3/pose3/userdata3/exp3/motion3 are read as TEXT and retained for a MOC3 export to + * re-emit; each is optional, and a missing one degrades that export rather than the open. + * - No failure escapes as an exception: like the byte-level CMO3 loader, anything thrown by the + * import/assembly is caught and reported as ParseFailed, never propagated to the caller. + * + * @param String path The stored path recorded on the document (the recent-files key). + * @param String name The moc file name (`Erica.moc3`; sidecars derive from its basename). + * @param ByteArray mocBytes The moc's contents. + * @param Function readRelative Reads a manifest-directory-relative reference, or null when missing. + * @return DocumentLoad The loaded document, or the failure reason. + */ +internal fun buildMoc3Document( + path: String, + name: String, + mocBytes: ByteArray, + readRelative: (String) -> ByteArray?, +): DocumentLoad { + // Shared with the export so import and re-export agree on the family's shape. + val basename = Moc3Sidecars.basenameFor(name) + + // model3.json: the manifest that joins the family together. Hard requirement; a manifest that + // exists but does not parse is a ParseFailed, not a MissingManifest - the alert must not claim + // a file is absent when it is sitting right there. + val manifestName = "$basename.model3.json" + val manifestBytes = readRelative(manifestName) + if (manifestBytes == null) { + UmamoLog.warn("cannot import $path: no $manifestName next to it") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.MissingManifest, name)) + } + val manifest = + runCatching { Moc3.readModel3(manifestBytes.decodeToString()) }.getOrElse { failure -> + UmamoLog.error("cannot import $path: $manifestName failed to parse", failure) + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.ParseFailed, name)) + } + if (manifest.fileReferences.moc.substringAfterLast('/') != name) { + // The manifest names a different moc (a renamed file); the picked bytes stay authoritative. + UmamoLog.warn("$manifestName references ${manifest.fileReferences.moc}, not $name; importing the picked file") + } + + val mocDocument = + runCatching { Moc3.read(mocBytes) }.getOrElse { failure -> + UmamoLog.error("failed to decode $path", failure) + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.ParseFailed, name)) + } + + // Atlas pages, in manifest order (a mesh's textureIndex indexes this list). Hard requirement. + // model3: FileReferences.Textures - the ordered atlas page paths, manifest-relative. + val textureReferences = manifest.fileReferences.textures + if (textureReferences.isEmpty()) { + UmamoLog.warn("cannot import $path: $manifestName lists no textures") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.MissingTexture, name)) + } + // Validate the moc's page indices against the manifest BEFORE decoding megabytes of PNG. The + // texture build rejects an out-of-range index too, so this is not the correctness guard - it is + // what keeps a stale or foreign manifest from costing a full atlas decode first, and what names + // the offending mesh and page count instead of the build's generic decode failure. + for (artMesh in mocDocument.artMeshes) { + if (artMesh.textureIndex !in textureReferences.indices) { + UmamoLog.warn( + "cannot import $path: ${artMesh.id} references texture page ${artMesh.textureIndex}, " + + "but $manifestName lists ${textureReferences.size} page(s)", + ) + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.MissingTexture, name)) + } + } + val pageBytes = + textureReferences.map { textureReference -> + readRelative(textureReference) ?: run { + UmamoLog.warn("cannot import $path: texture $textureReference is missing") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.MissingTexture, name)) + } + } + // A MOC3's pages are sibling files named by the manifest, so one that will not decode means the + // family on disk is incomplete or mismatched - an import error to surface, not a puppet to render + // half of. Hence Fail here where the CMO3 loader passes Skip. + val pageSet = moc3AtlasPages(mocDocument, pageBytes) + val textures = + buildPuppetTextures( + pageSet.pageBytes, + pageSet.atlasIndexByDrawableId, + pageSet.premultipliedAlpha, + UndecodablePagePolicy.Fail, + ) + ?: run { + UmamoLog.warn("cannot import $path: an atlas page failed to decode") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.MissingTexture, name)) + } + + // Pass-through sidecars: read now, re-emitted verbatim by a MOC3 export. Every one is optional - + // an unreadable physics file degrades the export's fidelity, never the open. + val sidecars = readPassThroughSidecars(manifest, readRelative) + + // cdi3: optional display info; a parse failure degrades (cosmetics never block a working model). + val displayInfo = readDisplayInfo(manifest.fileReferences.displayInfo, basename, readRelative) + + // The import leaves warp/rotation-parented rest meshes in parent-deformer space (all a moc stores); + // the post-pass evaluates the default pose to rewrite them into the editor's canvas-space convention. + // Guarded like the byte-level CMO3 loader's whole body: a malformed-but-decodable moc that throws + // inside the import or the evaluator must surface the ParseFailed alert, not crash the app. + return runCatching { + val puppet = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(mocDocument, displayInfo)) + DocumentLoad.Loaded( + Moc3Document( + path = path, + puppet = puppet, + textures = textures, + liveParams = initialLiveParams(puppet), + atlasPages = pageBytes, + manifest = manifest, + sidecars = sidecars, + ), + ) + }.getOrElse { failure -> + UmamoLog.error("failed to import $path", failure) + DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.ParseFailed, name)) + } +} + +/** + * Reads every sidecar the manifest references, as text, tagged with the section it came from. + * + * The kind is taken from WHICH manifest field named the file, which is the only place it is stated: + * the names themselves are the rigger's to choose, so a physics file called `custom.json` is + * indistinguishable from a motion by its name alone. Classifying here rather than at export time is + * what keeps such a file wired into the manifest the export writes. + * + * The cdi3 is deliberately NOT among them: it is the one sidecar the export synthesizes from the + * model (display names are model data), so carrying the imported one through would overwrite the + * names the rigger has since changed. + * + * @param Model3Json manifest The parsed manifest. + * @param Function readRelative Reads a manifest-directory-relative reference, or null when missing. + * @return List Each readable sidecar, with its kind and relative name. + */ +private fun readPassThroughSidecars( + manifest: Model3Json, + readRelative: (String) -> ByteArray?, +): List { + val references = LinkedHashMap() + manifest.fileReferences.physics?.let { reference -> + references[reference] = Moc3Sidecars.SidecarKind.Physics + } + manifest.fileReferences.pose?.let { reference -> references[reference] = Moc3Sidecars.SidecarKind.Pose } + manifest.fileReferences.userData?.let { reference -> + references[reference] = Moc3Sidecars.SidecarKind.UserData + } + manifest.fileReferences.expressions?.forEach { expression -> + references[expression.file] = Moc3Sidecars.SidecarKind.Expression + } + manifest.fileReferences.motions?.values?.forEach { motions -> + motions.forEach { motion -> references[motion.file] = Moc3Sidecars.SidecarKind.Motion } + } + val sidecars = ArrayList(references.size) + for ((reference, kind) in references) { + val bytes = readRelative(reference) + if (bytes == null) { + UmamoLog.warn("sidecar $reference is missing; a MOC3 export will not carry it") + continue + } + sidecars.add(Moc3Sidecars.PassThroughSidecar(kind, reference, bytes.decodeToString())) + } + return sidecars +} + +/** + * Reads the optional cdi3 display info: the manifest's DisplayInfo reference first, then the + * `.cdi3.json` sibling fallback; null (raw-id degradation) when neither reads or parses. + * + * @param String? manifestReference The manifest's FileReferences.DisplayInfo, or null. + * @param String basename The moc's basename for the sibling fallback. + * @param Function readRelative Reads a manifest-directory-relative reference. + * @return Cdi3Json? The parsed display info, or null. + */ +private fun readDisplayInfo( + manifestReference: String?, + basename: String, + readRelative: (String) -> ByteArray?, +): Cdi3Json? { + val candidates = listOfNotNull(manifestReference, "$basename.cdi3.json").distinct() + for (candidate in candidates) { + val bytes = readRelative(candidate) ?: continue + val parsed = + runCatching { Moc3.readCdi3(bytes.decodeToString()) } + .onFailure { failure -> UmamoLog.warn("ignoring unparseable $candidate: ${failure.message}") } + .getOrNull() + if (parsed != null) { + return parsed + } + } + return null +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3DocumentWriter.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3DocumentWriter.kt new file mode 100644 index 0000000..143afd6 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3DocumentWriter.kt @@ -0,0 +1,96 @@ +package org.umamo.ui.document + +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.absolutePath +import io.github.vinceglb.filekit.write +import okio.FileSystem +import okio.Path.Companion.toPath +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.storage.UmamoLog + +/* + * Writes an exported moc family to disk, and classifies the sidecars an import retained. + * + * The picker hands back ONE destination - a `.moc3` - but a baked model is a family, so everything + * else lands beside it under the manifest-relative names the bundle assigned. That mirrors the + * import, which discovers the same family by reading siblings of the picked moc, and it inherits the + * same platform limit: an Android SAF `content://` handle has no resolvable parent directory, so the + * family cannot be written there yet (the MOC3 itself still is, through the picker's own handle). + */ + +/** + * The bundle files that already exist at [destination], under the names the bundle would write. + * + * The safety check behind the pre-export overwrite warning: the native save dialog confirms + * replacing the PICKED file only, while the family lands a manifest, a cdi3, atlas pages (in their + * subfolder), and sidecars beside it that the dialog never mentioned. Every bundle name is + * checked - the moc included, since a picked NEW name can still collide with an existing family's + * moc when only the extension's case differs. On a platform whose handle has no resolvable parent + * (Android SAF) nothing beside the moc will be written anyway, so there is nothing to warn about. + * + * @param PlatformFile destination The picked `.moc3` handle. + * @param Bundle bundle The family that would be written. + * @return List The relative names that already exist, in the bundle's own order. + */ +fun existingBundleFiles(destination: PlatformFile, bundle: Moc3Sidecars.Bundle): List { + val directory = runCatching { destination.absolutePath().toPath().parent }.getOrNull() ?: return emptyList() + return bundle.files + .map { file -> file.name } + .filter { name -> FileSystem.SYSTEM.exists(directory / name) } +} + +/** + * Writes every file of [bundle] beside [destination]. + * + * The moc goes through the picker's own handle - that is the one path the user actually chose, and on + * a sandboxed platform the only one the app is permitted to write. The rest resolve against its + * parent directory, creating subdirectories (`motion/`) as the source layout requires. + * + * @param PlatformFile destination The picked `.moc3` handle. + * @param Bundle bundle The family to write. + * @return Int How many files were written, including the moc. + */ +suspend fun writeMoc3Bundle(destination: PlatformFile, bundle: Moc3Sidecars.Bundle): Int { + // The bundle names its own moc rather than being matched against the picked file's name. Matching + // by name silently degrades to "whatever is first" the moment the two disagree - which they do as + // soon as the picked extension differs in case from the one the bundle generated. + val mocFile = bundle.files.first { file -> file.name == bundle.mocFileName } + destination.write(mocFile.bytes) + + val directory = runCatching { destination.absolutePath().toPath().parent }.getOrNull() + if (directory == null) { + // The moc is written; the family is not. Loud, because the result is a file no runtime can + // open on its own - and silent partial success is exactly what a rigger would not check for. + UmamoLog.error("exported ${destination.absolutePath()} alone: its directory is not writable from here") + return 1 + } + var written = 1 + for (file in bundle.files) { + if (file === mocFile) { + continue + } + val target = directory / file.name + runCatching { + target.parent?.let { parent -> FileSystem.SYSTEM.createDirectories(parent) } + FileSystem.SYSTEM.write(target) { write(file.bytes) } + written++ + }.onFailure { failure -> + UmamoLog.error("could not write ${file.name} beside the exported moc", failure) + } + } + return written +} + +/** + * The pass-through sidecars of [document], already classified by the manifest section that named + * them (see `Moc3Document.sidecars`). + * + * Nothing is re-derived here. Classifying by file name instead would drop any sidecar the rigger + * named off-convention into the motion catch-all, and the export's manifest would stop pointing at + * it - the file copied beside the moc, but silently unwired from the rig. + * + * @param Moc3Document? document The imported document, or null for a non-MOC3 origin. + * @return List The sidecars to re-emit, empty when there are none. + */ +fun passThroughSidecars(document: Moc3Document?): List = + document?.sidecars.orEmpty() \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3ExportPolicy.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3ExportPolicy.kt new file mode 100644 index 0000000..dad8905 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/Moc3ExportPolicy.kt @@ -0,0 +1,144 @@ +package org.umamo.ui.document + +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.render.PuppetTextures +import org.umamo.render.canvasToParentSpaceFor +import org.umamo.render.encodeAtlasPng +import org.umamo.render.withTexturePagesFrom +import org.umamo.runtime.model.PuppetModel + +/* + * Decides WHAT a MOC3 export writes; Moc3DocumentWriter decides where the bytes land. + * + * The split is what makes the rules testable: everything here is pure, so the page naming, the + * verbatim-vs-re-encode choice, and the family's shape can be exercised from a hand-built document + * without a picker or a filesystem. The app layer keeps only the picker call, the write, and the + * report. + */ + +/** + * Builds the exported MOC3 family for [document] at the picked file name. + * + * @param PuppetDocument document The document being exported (for a MOC3 origin, its source + * manifest and page bytes). + * @param PuppetModel edited The model to write; see [exportedModelFor]. + * @param PuppetTextures effectiveTextures The SESSION's page set - the document's own for an + * unedited atlas, the recomposed set after a repack - so the + * written pages match what the viewport shows. + * @param String destinationName The picked file's own name, which the family is named after. + * @param Moc3ExportOptions options What the rigger chose to include; the default is the + * options-less behavior. + * @return Bundle The named byte arrays to write, plus the report of anything unrepresentable. + */ +fun prepareMoc3Export( + document: PuppetDocument, + edited: PuppetModel, + effectiveTextures: PuppetTextures, + destinationName: String, + options: Moc3ExportOptions = Moc3ExportOptions.Default, +): Moc3Sidecars.Bundle { + // The page binding comes from the decoded atlas set, not the model: a CMO3-origin document has no + // page index of its own (see withTexturePagesFrom). + val bound = withTexturePagesFrom(edited, effectiveTextures) + // FileKit appends the extension, so the destination's own name is the family's base name. + val basename = Moc3Sidecars.basenameFor(destinationName) + val moc3Document = document as? Moc3Document + return Moc3Sidecars.bundle( + puppet = bound, + basename = basename, + pages = atlasPagesFor(effectiveTextures, moc3Document, basename), + sidecars = exportedSidecarsFor(passThroughSidecars(moc3Document), options), + source = moc3Document?.manifest, + canvasToParentSpace = canvasToParentSpaceFor(bound), + options = options, + ) +} + +/** + * The pass-through sidecars an export carries under [options]. + * + * Physics and user data are the two a rigger can opt out of; every other kind always rides along. + * Filtered HERE, before the bundle, because the manifest derives its physics/userData references + * from the sidecar list it is handed - dropping a sidecar upstream drops its reference with it, + * so the two cannot disagree. + * + * @param List sidecars The retained pass-through sidecars. + * @param Moc3ExportOptions options What the rigger chose to include. + * @return List The sidecars to bundle. + */ +internal fun exportedSidecarsFor( + sidecars: List, + options: Moc3ExportOptions, +): List = + sidecars.filter { sidecar -> + when (sidecar.kind) { + Moc3Sidecars.SidecarKind.Physics -> options.includePhysics + Moc3Sidecars.SidecarKind.UserData -> options.includeUserData + Moc3Sidecars.SidecarKind.Pose, + Moc3Sidecars.SidecarKind.Expression, + Moc3Sidecars.SidecarKind.Motion, + -> true + } + } + +/** + * The atlas pages the family writes, in the decoded set's page order. + * + * Page names come from the SOURCE manifest when there is one, so a re-export lands the family in the + * shape (and the subdirectory) the model already used. A CMO3-origin document has no manifest, so + * its pages are named the way the official editor's bake names them - a `Basename.Resolution/` + * subfolder holding `texture_NN.png` files (two-digit minimum, underscore separated); every corpus + * manifest follows exactly this shape, and runtimes' tooling expects it. Bytes are the source PNGs + * verbatim when the document retains them - both faster and lossless - and a re-encode of the + * decoded RGBA only when it does not. + * + * Driven by the DECODED set rather than the retained bytes: that set is what the model's page indices + * were resolved against, so a source whose manifest lists more pages than decoded cannot silently + * emit a page nothing samples. + * + * @param PuppetTextures textures The document's decoded atlas set, which drives the page list. + * @param Moc3Document? moc3Document The document when it came from a moc, else null (a CMO3 origin, + * which has neither source names nor source bytes). + * @param String basename The family base name, for synthesized page names. + * @return List The pages to write. + */ +internal fun atlasPagesFor( + textures: PuppetTextures, + moc3Document: Moc3Document?, + basename: String, +): List { + val textureFolder = "$basename.${atlasResolutionFor(textures)}" + return textures.atlases.mapIndexed { pageIndex, atlas -> + val sourceName = moc3Document?.manifest?.fileReferences?.textures?.getOrNull(pageIndex) + Moc3Sidecars.AtlasPage( + fileName = sourceName ?: "$textureFolder/texture_${paddedPageIndex(pageIndex)}.png", + // The verbatim-bytes preference is only reachable for a MOC3-origin document, which the + // repack's availability gate excludes (no atlas tiles) - so a recomposed effective set can + // never be shadowed by stale retained bytes here. + bytes = moc3Document?.atlasPages?.getOrNull(pageIndex) ?: encodeAtlasPng(atlas), + ) + } +} + +/** + * The single per-project resolution the texture subfolder is named with. + * + * The official layout carries ONE resolution for the whole family (`Azxiana.4096/`, + * `modelF.16384/`), so a set whose pages differ still has to pick one number - the largest + * dimension across every page, which is the size the export target actually needed. + * + * @param PuppetTextures textures The decoded atlas set. + * @return Int The folder resolution; 0 only for a set with no pages, which names no files. + */ +private fun atlasResolutionFor(textures: PuppetTextures): Int = + textures.atlases.maxOfOrNull { atlas -> maxOf(atlas.width, atlas.height) } ?: 0 + +/** + * A page index in the official texture file naming: at least two digits, so page 3 is + * `texture_03.png` while page 100 keeps all its digits. + * + * @param Int pageIndex The page's index in the decoded set. + * @return String The padded index. + */ +private fun paddedPageIndex(pageIndex: Int): String = pageIndex.toString().padStart(2, '0') \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/PreparedCmo3Export.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/PreparedCmo3Export.kt new file mode 100644 index 0000000..d2a68a5 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/PreparedCmo3Export.kt @@ -0,0 +1,16 @@ +package org.umamo.ui.document + +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.interop.ExportReport + +/** + * A CMO3 export ready to write: the model to serialize plus what the lowering could not carry. + * + * The two origins produce this the same way but mean different things by [model] - a CMO3-origin + * document's is its own retained graph, reconciled in place, while a MOC3-origin document's is a graph + * synthesized for the occasion. The writer does not care which, which is the point of the type. + * + * @property Cmo3Model model The model to serialize. + * @property ExportReport report Everything unrepresentable; surfaced to the rigger, never swallowed. + */ +class PreparedCmo3Export(val model: Cmo3Model, val report: ExportReport) \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/SourceRead.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/SourceRead.kt new file mode 100644 index 0000000..763caf2 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/SourceRead.kt @@ -0,0 +1,79 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.umamo.format.art.SourceArt +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.art.placedFor +import org.umamo.interop.cmo3.cmo3SourceArtOf +import org.umamo.runtime.model.ArtSource +import org.umamo.storage.UmamoLog +import org.umamo.ui.model.SourceFilePresence + +/** + * One listed file's art as an operation read it. + * + * @property SourceArt art The art. + * @property String? contentHash The whole-file hash of the bytes it came from, or null when it came from a CMO3's own layers. + * @property Long? lastModified The file's modification time when read, or null when it came from a CMO3's own layers. + * @property Boolean fromCmo3 Whether it was read from the CMO3's decomposed layer images rather than the file. + */ +internal class SourceRead( + val art: SourceArt, + val contentHash: String?, + val lastModified: Long?, + val fromCmo3: Boolean, +) + +/** + * A listed file read from [path] and placed on the document canvas by its record's offset - the ONE + * way a listed file's disk read reaches an operation, so the reload, the relink, and the match all see + * its layers in the frame the drawables and the inventory share. A file that shares the document's + * frame (offset zero) comes back as read. + * + * @param ArtSource source The listed file, for its offset. + * @param String path The path to read. + * @return ReadArtwork? The placed read, or null when the file yields no art. + */ +internal suspend fun readListedArtworkAt(source: ArtSource, path: String): ReadArtwork? { + val read = readArtworkAt(path) ?: return null + return ReadArtwork(read.art.placedFor(source), read.kind, read.contentHash, read.lastModified) +} + +/** + * One listed file's art the way every operation over it reads it: from disk when the file is there + * and reads, placed by the record's offset, else - for a CMO3-origin document - from the layer PNGs + * the official editor decomposed into the CMO3 at import, whether the file is gone or is one our + * reader refuses; null when neither can be read. The CMO3's own layers already sit on the document + * canvas, so that fallback is never placed. Each step is logged, so a relink or a match that fell + * back says which file it could not reach and why. + * + * @param PuppetDocument puppetDocument The open document the file is listed on. + * @param ArtSource source The listed file. + * @param SourceFilePresence presence The file-presence probe; the app's logged okio probe by default. + * @return SourceRead? The art and where it came from, or null when nothing could be read. + */ +internal suspend fun readSourceArt( + puppetDocument: PuppetDocument, + source: ArtSource, + presence: SourceFilePresence = systemSourceFilePresence, +): SourceRead? { + val path = source.path + if (path == null) { + UmamoLog.info("read artwork: '${source.name}' has no recorded path; falling back to what the document holds") + } else if (presence(path) != true) { + UmamoLog.info("read artwork: '${source.name}' is not at $path; falling back to what the document holds") + } else { + val read = readListedArtworkAt(source, path) + if (read != null) { + UmamoLog.info("read artwork: '${source.name}' read from $path") + return SourceRead(read.art, read.contentHash, read.lastModified, fromCmo3 = false) + } + UmamoLog.warn("read artwork: '${source.name}' at $path could not be read; falling back to what the document holds") + } + val cmo3Document = puppetDocument as? Cmo3Document ?: return null + // CMO3: CModelSource is the graph root the decomposed CLayeredImage tree hangs off. + val root = cmo3Document.cmo3.root as? CModelSource ?: return null + val art = withContext(Dispatchers.Default) { cmo3SourceArtOf(root, source.id) { resource -> cmo3Document.cmo3.extractLayerPng(resource) } } ?: return null + return SourceRead(art, contentHash = null, lastModified = null, fromCmo3 = true) +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaDocumentLoader.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaDocumentLoader.kt new file mode 100644 index 0000000..b585cf6 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaDocumentLoader.kt @@ -0,0 +1,133 @@ +package org.umamo.ui.document + +import kotlinx.serialization.json.JsonObject +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaFormatException +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaReadFailure +import org.umamo.format.uma.UmaReadOnlyReason +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.interop.AtlasPageSet +import org.umamo.interop.uma.UmaDocumentBridge +import org.umamo.render.PuppetTextures +import org.umamo.render.SourceArtRasters +import org.umamo.render.UndecodablePagePolicy +import org.umamo.render.buildPuppetTextures +import org.umamo.render.deriveAtlasTextures +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.ui.help.ProjectInfo +import org.umamo.ui.viewport.LiveParams +import org.umamo.ui.viewport.initialLiveParams +import org.umamo.ui.workspace.EDITOR_STATE_SESSION +import org.umamo.ui.workspace.savedPoseOf + +/** + * A rig opened from Umamo's own `.uma` file - the one format the editor opens and saves rather than + * imports and exports. + * + * The opened [uma] is kept whole: a save lays the session's model over it, so every key this version + * does not know survives in place and every tile the file already holds is copied byte for byte + * (docs/format/UMA.md § 3.3). A file that carries a required entry this version cannot interpret opens + * read-only ([isReadOnly]): edits are allowed, but no save can be written that would keep the file + * honest, so Save is unavailable and the shell says why. + * + * @property UmaModel uma The file as read, the base the next save lays over. + * @property AtlasPageSet? storedPages The render pages the file stores, in page order, or null when it + * stores none and the pages derive from the tiles at open. + */ +class UmaDocument( + override val path: String, + val uma: UmaModel, + override val puppet: PuppetModel, + override val textures: PuppetTextures, + override val artRasters: SourceArtRasters, + override val liveParams: LiveParams, + val storedPages: AtlasPageSet?, +) : PuppetDocument { + /** Each required entry this version cannot interpret; empty for a document that can be saved. */ + val readOnlyReasons: List + get() = uma.readOnlyReasons + + /** True when the file holds something this version must not write over, so Save is unavailable. */ + val isReadOnly: Boolean + get() = uma.isReadOnly +} + +/** + * The writer record this application stamps into every `.uma` it saves: the manifest's `writer` names + * the app and the version, which is what a later reader shows for "made by a newer Umamo". + * Do NOT attempt to localize the "Umamo" application name or pull in the app_name string. + * + * @return UmaWriterInfo The record. + */ +fun umamoWriterInfo(): UmaWriterInfo = UmaWriterInfo("Umamo", ProjectInfo.VERSION) + +/** + * Assembles a [UmaDocument] from a file's bytes: the codec reads the container, the bridge rebuilds the + * puppet with its atlas and sources, and the pages come from the file when it stores them or derive + * from the tiles when it does not. + * + * Failures map to the open errors the shell shows: a file that is not a UMA at all, a container or a + * puppet entry newer than this reader, and a damaged or malformed file each get their own. Any OTHER + * required entry this version cannot interpret is not a failure - the codec opens the file read-only and + * the document says so; only the puppet is needed to have a rig to show at all. + * + * @param ByteArray bytes The file's contents. + * @param String name The file name, for the failure alert. + * @param String path The stored path or uri string recorded on the document. + * @return DocumentLoad The document, or the failure reason. + */ +internal fun buildUmaDocument(bytes: ByteArray, name: String, path: String): DocumentLoad { + val uma = + try { + Uma.read(bytes) + } catch (failure: UmaFormatException) { + UmamoLog.error("failed to open $path: ${failure.message}", failure) + return DocumentLoad.Failed(DocumentOpenFailure(openErrorOf(failure.failure), name)) + } + // A puppet entry newer than this version reads is a file from a newer Umamo, not a damaged one: the + // codec keeps it byte for byte and reads nothing from it, so there is no rig to open, and saying "the + // file may be damaged" about a healthy file sends the rigger looking for the wrong problem. + if (uma.holdsTooNewEntry(UmaEntryKind.Puppet)) { + UmamoLog.warn("cannot open $path: its puppet entry needs a newer version of Umamo") + return DocumentLoad.Failed(DocumentOpenFailure(DocumentOpenError.NewerFormat, name)) + } + // A puppet entry the file lacks fails here as a parse failure, through the caller's catch. + val puppet = UmaDocumentBridge.modelOf(uma) + val pages = UmaDocumentBridge.pagesOf(uma) + // The document's own store, over the file's tile PNGs: artwork brought in later decodes into it. + val artRasters = SourceArtRasters.fromPng { tileId -> pages.tilePng(tileId) } + val stored = pages.pageSet + // Stored pages decode with the Skip policy, as a CMO3's do: one page that will not decode must not + // cost the rigger the rest of an editable rig. Without stored pages the atlas composes from the + // tiles, the way an artwork document's does after its pack. + val textures = + stored?.let { pageSet -> buildPuppetTextures(pageSet.pageBytes, pageSet.atlasIndexByDrawableId, pageSet.premultipliedAlpha, UndecodablePagePolicy.Skip) } + ?: deriveAtlasTextures(puppet, artRasters, premultipliedAlpha = false) + ?: PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false) + if (uma.isReadOnly) { + UmamoLog.warn("opened $path read-only: " + uma.readOnlyReasons.joinToString { reason -> "'${reason.path}' (${reason.kind}): ${reason.cause}" }) + } + // The pose the document was saved with is editor state, read tolerantly and never an input to the model (UMA §7.4). + val savedPose = savedPoseOf(uma.editorState?.get(EDITOR_STATE_SESSION) as? JsonObject) + return DocumentLoad.Loaded(UmaDocument(path, uma, puppet, textures, artRasters, initialLiveParams(puppet, savedPose), stored)) +} + +/** + * The open error a codec read failure reports. + * + * @param UmaReadFailure failure Why the codec refused the file. + * @return DocumentOpenError The reason the shell shows. + */ +private fun openErrorOf(failure: UmaReadFailure): DocumentOpenError = + when (failure) { + is UmaReadFailure.NotUma -> DocumentOpenError.Unrecognized + is UmaReadFailure.UnsupportedContainerVersion -> DocumentOpenError.NewerFormat + is UmaReadFailure.CorruptContainer, + is UmaReadFailure.MalformedManifest, + is UmaReadFailure.MissingEntry, + is UmaReadFailure.MalformedEntry, + -> DocumentOpenError.ParseFailed + } \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaDocumentWriter.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaDocumentWriter.kt new file mode 100644 index 0000000..f5cb4ec --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaDocumentWriter.kt @@ -0,0 +1,156 @@ +package org.umamo.ui.document + +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.name +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonObject +import okio.IOException +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.fittedInto +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaEntryKind +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriteException +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.interop.uma.UmaDocumentBridge +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.storage.UmamoLog +import org.umamo.storage.writeReplacing +import org.umamo.ui.model.DrawableThumbnailer +import org.umamo.ui.viewport.AtlasPageBinding + +/** The size the saved thumbnail is fitted into (UMA §5.6). */ +const val UMA_THUMBNAIL_SIZE = 256 + +/** + * Writes [model] as a `.uma` at [destination], laid over [base]. + * + * Pure given its inputs, which is what lets a gate test drive the real save with no picker: the caller + * snapshots the session's model, the atlas page binding, and the editor state on the UI thread and hands them in, and this + * runs the rest off it - the pixel gathering and the encode on the default dispatcher, the write on the + * platform's own file-system route. Nothing here marks the session saved; the caller does that with the + * same snapshot once the file is on disk. + * + * What the file gets for pixels (docs/format/UMA.md § 5): + * - A tile the base already holds is copied by the codec and never asked for. Every other tile takes + * its PNG from the document's own bytes where it has them (a CMO3's embedded layer, a `.uma`'s stored + * entry) and is encoded from its decoded raster otherwise. + * - The render pages are stored as the file or the origin had them while the atlas is at the document's + * baseline - the same identity gate the CMO3 export uses - and derive from the tiles after any repack (UMA §5.5). + * - The thumbnail is [thumbnail] when the caller rendered one - the pose on screen as the viewport draws it - + * and otherwise the rest pose composited on the CPU, fitted into [UMA_THUMBNAIL_SIZE] pixels (UMA §5.6). + * + * Editor state rides on the save as a merge patch over what the base holds (docs/format/UMA.md § 7.5) and is never + * a reason to refuse one: an editor entry too new for this version to merge into is carried as it is. + * + * @param PuppetDocument document The open document, for the pixels only it can supply. + * @param UmaModel base The document the save lays over. + * @param PuppetModel model The session's model as snapshotted. + * @param AtlasPageBinding binding The session's atlas pages as snapshotted. + * @param JsonObject editorState The editor entry's merge patch as gathered; empty when there is none to write. + * @param PlatformFile destination Where to write. + * @param RasterImage? thumbnail The thumbnail as rendered, [UMA_THUMBNAIL_SIZE] square, or null to composite one here. + * @return UmaWriteOutcome The written document, or why nothing complete was written. + */ +suspend fun writeUmaDocument( + document: PuppetDocument, + base: UmaModel, + model: PuppetModel, + binding: AtlasPageBinding, + editorState: JsonObject, + destination: PlatformFile, + thumbnail: RasterImage? = null, +): UmaWriteOutcome { + val encoded = + withContext(Dispatchers.Default) { + try { + val modelDocument = UmaDocumentBridge.documentOf(base, model, pixelSourceFor(document, base, model, binding, thumbnail)) + // UMA §7.5: the patch is laid over the entry the base holds, unless that entry is one this version cannot read. + val written = if (modelDocument.holdsTooNewEntry(UmaEntryKind.Editor)) modelDocument else modelDocument.withEditorState(editorState) + UmaWriteOutcome.Written(written) to Uma.write(written) + } catch (failure: UmaWriteException) { + UmamoLog.error("save: ${destination.name} refused", failure) + return@withContext UmaWriteOutcome.Failed(failure.message ?: failure.detail) to null + } catch (failure: IllegalStateException) { + // The codec's own refusal of a read-only document; the app gates that earlier, so reaching it is a bug + // worth a log line, not a crash. + UmamoLog.error("save: ${destination.name} refused", failure) + return@withContext UmaWriteOutcome.Failed(failure.message.orEmpty()) to null + } + } + val (outcome, bytes) = encoded + if (bytes == null) { + return outcome + } + return try { + // Not cancellable: a composition torn down mid-save (Android's back, a closing window) cancels the + // scope this runs in, and a write interrupted there leaves a partial file - in place on Android, + // where there is no temporary to discard. Once the bytes exist, they land. + withContext(NonCancellable) { destination.writeReplacing(bytes) } + outcome + } catch (failure: IOException) { + UmamoLog.error("save: could not write ${destination.name}", failure) + UmaWriteOutcome.Failed(failure.message ?: "the file could not be written") + } +} + +/** + * The pixels a save hands the bridge: each tile the base lacks, the render pages' mode, and the thumbnail. + * + * The tile PNGs are gathered up front rather than inside the source's lambda, so the layout - which asks + * for them one by one - never runs a decode or an encode of its own. + * + * The thumbnail is the rendered one when the caller had a renderer to draw it. Otherwise it is the rest + * pose composited on the CPU, which knows the art and the visible drawables but none of the blending, + * masks, or colors the renderer applies; a platform without a puppet renderer still saves a thumbnail. + * + * @param PuppetDocument document The open document. + * @param UmaModel base The document the save lays over. + * @param PuppetModel model The model being written. + * @param AtlasPageBinding binding The atlas pages as snapshotted. + * @param RasterImage? thumbnail The rendered thumbnail, or null to composite one. + * @return UmaPixelSource The pixels. + */ +private fun pixelSourceFor(document: PuppetDocument, base: UmaModel, model: PuppetModel, binding: AtlasPageBinding, thumbnail: RasterImage?): UmaPixelSource { + val heldByBase = base.textures?.tiles.orEmpty().mapNotNull { tile -> tile.path?.let { tile.id } }.toHashSet() + val tilePngs = HashMap() + for (tile in model.atlas.tiles) { + if (tile.id.raw !in heldByBase) { + tilePngs[tile.id.raw] = tilePngFor(document, tile.id) + } + } + val atBaseline = binding.textures === document.textures + val renderPages: UmaRenderPagePixels = + when { + !atBaseline -> UmaRenderPagePixels.Derived + document is UmaDocument -> if (document.storedPages != null) UmaRenderPagePixels.Retained else UmaRenderPagePixels.Derived + document is Cmo3Document && document.pageSet.pageBytes.isNotEmpty() -> UmaRenderPagePixels.Stored(document.pageSet.pageBytes, document.pageSet.atlasIndexByDrawableId) + document is Moc3Document -> UmaRenderPagePixels.Stored(document.pagePngs(), document.textures.atlasIndexByDrawableId) + else -> UmaRenderPagePixels.Derived + } + val thumbnailRaster = thumbnail ?: DrawableThumbnailer(model, binding.textures).modelRasterFor()?.fittedInto(UMA_THUMBNAIL_SIZE) + return UmaPixelSource({ tileId -> tilePngs[tileId] }, renderPages, thumbnailRaster?.let(PngCodec::write)) +} + +/** + * A tile's PNG for a file that does not hold it yet: the document's own bytes where it has them, else an + * encode of the decoded raster; null when the document has no pixels for the tile at all, which the + * bridge refuses the save over. + * + * @param PuppetDocument document The open document. + * @param AtlasTileId tileId The tile. + * @return ByteArray? The PNG, or null. + */ +private fun tilePngFor(document: PuppetDocument, tileId: AtlasTileId): ByteArray? { + val embedded = (document as? Cmo3Document)?.tilePng?.invoke(tileId) + if (embedded != null) { + return embedded + } + val decoded = document.artRasters.decodeRaster(tileId) ?: return null + return PngCodec.write(RasterImage(decoded.width, decoded.height, decoded.rgba)) +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaWriteOutcome.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaWriteOutcome.kt new file mode 100644 index 0000000..5aac03a --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/document/UmaWriteOutcome.kt @@ -0,0 +1,20 @@ +package org.umamo.ui.document + +import org.umamo.format.uma.UmaModel + +/** What writing a document produced. */ +sealed interface UmaWriteOutcome { + /** + * The file was written; [uma] is the document as written, the base the next save lays over. + * + * @property UmaModel uma The written document. + */ + class Written(val uma: UmaModel) : UmaWriteOutcome + + /** + * Nothing was written, or nothing complete; the target is whatever it was. + * + * @property String reason Why, in the codec's or the file system's words. + */ + class Failed(val reason: String) : UmaWriteOutcome +} \ No newline at end of file diff --git a/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/l10n/AppLocale.jvmAndroid.kt b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/l10n/AppLocale.jvmAndroid.kt new file mode 100644 index 0000000..17544b9 --- /dev/null +++ b/module/ui/src/jvmAndroidMain/kotlin/org/umamo/ui/l10n/AppLocale.jvmAndroid.kt @@ -0,0 +1,17 @@ +package org.umamo.ui.l10n + +import java.util.Locale + +/** + * Shared JVM/Android actual: sets the JVM default locale, which Compose Multiplatform's resource + * environment reads when resolving string catalogs. Combined with the key()-driven recomposition in + * ProvideAppLocale, switching localization.locale re-resolves stringResource() to the new catalog. + * On Android the configuration locale also matters for platform resource resolution; for v1 the JVM + * default is the lever we control, and a per-Activity configuration override can layer on when the + * Android UX is hardened. + * + * @param String languageTag The BCP-47 language tag to apply. + */ +actual fun applyAppLocale(languageTag: String) { + Locale.setDefault(Locale.forLanguageTag(languageTag)) +} \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/action/AcceleratorText.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/action/AcceleratorText.jvm.kt new file mode 100644 index 0000000..fbca61d --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/action/AcceleratorText.jvm.kt @@ -0,0 +1,16 @@ +package org.umamo.ui.action + +/** + * Desktop primary-modifier label: the Apple Command glyph on macOS, "Ctrl" on Windows and Linux. The + * OS is read from the "os.name" system property, the standard JVM way to branch on the host platform. + * + * デスクトップの主修飾ラベル。macOS は "⌘"、Windows / Linux は "Ctrl"。 + * + * @return String The primary modifier label. + */ +actual fun primaryModifierLabel(): String = + if (System.getProperty("os.name").orEmpty().startsWith("Mac")) { + "⌘" + } else { + "Ctrl" + } \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/action/KeyName.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/action/KeyName.jvm.kt new file mode 100644 index 0000000..93ee6c2 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/action/KeyName.jvm.kt @@ -0,0 +1,49 @@ +package org.umamo.ui.action + +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.nativeKeyCode +import androidx.compose.ui.input.key.nativeKeyLocation +import java.awt.event.KeyEvent + +/* + * The AWT virtual-key codes that only exist on the numeric keypad and whose Compose constants use the + * same code (NumPad0..9, the four operators). An event key with one of these codes but a non-NUMPAD + * reported location can be re-located without ambiguity - no main-row key shares these codes. + */ +private val numpadOnlyKeyCodes = + setOf( + KeyEvent.VK_NUMPAD0, + KeyEvent.VK_NUMPAD1, + KeyEvent.VK_NUMPAD2, + KeyEvent.VK_NUMPAD3, + KeyEvent.VK_NUMPAD4, + KeyEvent.VK_NUMPAD5, + KeyEvent.VK_NUMPAD6, + KeyEvent.VK_NUMPAD7, + KeyEvent.VK_NUMPAD8, + KeyEvent.VK_NUMPAD9, + KeyEvent.VK_ADD, + KeyEvent.VK_SUBTRACT, + KeyEvent.VK_MULTIPLY, + KeyEvent.VK_DIVIDE, + ) + +/** + * Remaps the numpad key codes AWT actually delivers onto the codes Compose's located constants are + * built from. Compose desktop defines Key.NumPadDot as Key(VK_PERIOD, NUMPAD) and Key.NumPadComma as + * Key(VK_COMMA, NUMPAD), but AWT reports the physical keys as VK_DECIMAL / VK_SEPARATOR - so without + * this remap the raw event key can never equal the constant and every NumpadDecimal binding is dead. + * The remaining numpad-only codes match their constants code-for-code and only need the defensive + * re-location for X stacks that under-report the key location. + * + * @param Key key The key from a key event. + * @return Key The key to match the named constants against. + */ +internal actual fun normalizeKeyPosition(key: Key): Key = + when { + key.nativeKeyCode == KeyEvent.VK_DECIMAL -> Key(KeyEvent.VK_PERIOD, KeyEvent.KEY_LOCATION_NUMPAD) + key.nativeKeyCode == KeyEvent.VK_SEPARATOR -> Key(KeyEvent.VK_COMMA, KeyEvent.KEY_LOCATION_NUMPAD) + key.nativeKeyCode in numpadOnlyKeyCodes && key.nativeKeyLocation != KeyEvent.KEY_LOCATION_NUMPAD -> + Key(key.nativeKeyCode, KeyEvent.KEY_LOCATION_NUMPAD) + else -> key + } \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.jvm.kt new file mode 100644 index 0000000..ebdebe8 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/graphics/ImageBitmaps.jvm.kt @@ -0,0 +1,27 @@ +package org.umamo.ui.graphics + +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.toComposeImageBitmap +import org.jetbrains.skia.ColorAlphaType +import org.jetbrains.skia.ColorType +import org.jetbrains.skia.Image +import org.jetbrains.skia.ImageInfo + +/** + * Desktop actual: wraps the RGBA bytes as a Skia raster image and bridges it to Compose. + * + * @param ByteArray rgba The pixel bytes, 4 per texel, top row first. + * @param Int width The image width in texels. + * @param Int height The image height in texels. + * @param RgbaAlphaType alphaType How the alpha channel is interpreted. + * @return ImageBitmap The wrapped Compose bitmap. + */ +actual fun rgbaToImageBitmap(rgba: ByteArray, width: Int, height: Int, alphaType: RgbaAlphaType): ImageBitmap { + val skiaAlphaType = + when (alphaType) { + RgbaAlphaType.Opaque -> ColorAlphaType.OPAQUE + RgbaAlphaType.Straight -> ColorAlphaType.UNPREMUL + } + val info = ImageInfo(width, height, ColorType.RGBA_8888, skiaAlphaType) + return Image.makeRaster(info, rgba, width * 4).toComposeImageBitmap() +} \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/ContextMenu.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/ContextMenu.jvm.kt new file mode 100644 index 0000000..29ae58a --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/ContextMenu.jvm.kt @@ -0,0 +1,61 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.IntOffset + +/** + * Desktop context-menu trigger: a secondary (right) mouse-button press. Watches the raw pointer stream + * and fires on the press whose button state has the secondary button down, consuming it so it does not + * also reach the content beneath. + * + * An already-consumed press is skipped, so a nested context menu wins over an enclosing one: the inner + * area consumes the press in the main pass before the outer area sees it, and the outer area then skips + * it instead of opening a second menu on top (e.g. a row's menu suppresses the whole panel's area menu). + * + * デスクトップのトリガーは右ボタン押下。生のポインタ列を監視し、押下時に通知して消費する。既に消費済みの + * 押下は無視するので、内側のコンテキストメニューが外側より優先される。 + * + * @param Function onContextMenu Called with the press point in local coordinates. + * @return Modifier The modifier with the secondary-click detector attached. + */ +internal actual fun Modifier.contextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier = + secondaryClickGesture(PointerEventPass.Main, onContextMenu) + +/** + * Desktop text-field context-menu trigger: the same secondary-click detector on the INITIAL pass. + * + * The initial pass runs outermost-first, which is the whole point: the text-field primitive's own menu + * handler sits on an inner node and watches the main pass, so watching a pass earlier and consuming there is + * what lets the kit's menu replace it rather than lose to it. Consuming a secondary press costs the field + * nothing - it uses the primary button for caret placement and selection. + * + * @param Function onContextMenu Called with the press point in local coordinates. + * @return Modifier The modifier with the detector attached. + */ +internal actual fun Modifier.textEditContextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier = + secondaryClickGesture(PointerEventPass.Initial, onContextMenu) + +/** + * A secondary-press detector on [pass], reporting the press point and consuming it. + * + * @param PointerEventPass pass The pointer pass to watch. + * @param Function onContextMenu Called with the press point in local coordinates. + * @return Modifier The modifier with the detector attached. + */ +private fun Modifier.secondaryClickGesture(pass: PointerEventPass, onContextMenu: (IntOffset) -> Unit): Modifier = + this.pointerInput(pass) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(pass) + val change = event.changes.first() + if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed && !change.isConsumed) { + change.consume() + onContextMenu(change.position.toIntOffset()) + } + } + } + } \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/FileDropTarget.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/FileDropTarget.jvm.kt new file mode 100644 index 0000000..8e64da6 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/FileDropTarget.jvm.kt @@ -0,0 +1,44 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.draganddrop.DragAndDropEvent +import androidx.compose.ui.draganddrop.awtTransferable +import org.umamo.storage.UmamoLog +import java.awt.datatransfer.DataFlavor +import java.io.File + +/** + * Whether the AWT drag carries a file list. + * + * Asks the transferable which flavors it offers, never for the data: a drag still in flight may not be + * able to produce its contents yet, but it always says what it holds. A drag Compose routed here from + * something other than AWT has no transferable at all, which is not an error - it is a drag this target + * does not want. + * + * @return Boolean True when the drag offers a file list. + */ +@OptIn(ExperimentalComposeUiApi::class) +actual fun DragAndDropEvent.carriesFiles(): Boolean = + runCatching { awtTransferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor) }.getOrDefault(false) + +/** + * The absolute paths of the files an AWT drop carries. + * + * Reads [DataFlavor.javaFileListFlavor] directly rather than going through Compose's `dragData()`, which + * hands back percent-encoded `file:` uris that would then have to be decoded - a step that gets non-ASCII + * names wrong, and there is no reason to take it when AWT already offers the files themselves. + * + * Directories are dropped here rather than passed on: a caller would read one as a file, fail, and report + * an unreadable file for something the rigger never claimed was one. + * + * @return List The dropped files' absolute paths, in the order AWT reported them. + */ +@OptIn(ExperimentalComposeUiApi::class) +actual fun DragAndDropEvent.droppedFilePaths(): List = + runCatching { + val transferred = awtTransferable.getTransferData(DataFlavor.javaFileListFlavor) as List<*> + transferred.filterIsInstance().filter { dropped -> dropped.isFile }.map { dropped -> dropped.absolutePath } + }.getOrElse { failure -> + UmamoLog.warn("drag and drop: the dropped file list could not be read (${failure.message})") + emptyList() + } \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/Scrollbar.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/Scrollbar.jvm.kt new file mode 100644 index 0000000..079f925 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/Scrollbar.jvm.kt @@ -0,0 +1,71 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.ScrollbarStyle +import androidx.compose.foundation.VerticalScrollbar +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.rememberScrollbarAdapter +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import org.umamo.ui.theme.LocalUmamoColors + +/** + * The flat, palette-keyed scrollbar style shared by every overlay below: a thin rounded thumb tinted + * from [LocalUmamoColors].scrollbarThumb that brightens on hover. Foundation's ScrollbarStyle (not + * Material), so it stays within the project's no-Material design system while reusing the well-tested + * bar widget. + * + * @return ScrollbarStyle The themed style for the active color scheme. + */ +@Composable +private fun umamoScrollbarStyle(): ScrollbarStyle { + val colors = LocalUmamoColors.current + return ScrollbarStyle( + minimalHeight = SCROLLBAR_MIN_THUMB, + thickness = SCROLLBAR_THICKNESS, + shape = RoundedCornerShape(SCROLLBAR_CORNER_RADIUS), + hoverDurationMillis = 300, + unhoverColor = colors.scrollbarThumb, + hoverColor = colors.scrollbarThumbHover, + ) +} + +/** + * Desktop actual: Foundation's draggable VerticalScrollbar, gated on the content overflowing. + * + * デスクトップ実装:内容がはみ出すときのみ Foundation のスクロールバーを描画する。 + * + * @param ScrollState scrollState The scroll state of the verticalScroll content to drive and gate on. + */ +@Composable +actual fun BoxScope.VerticalScrollbarOverlay(scrollState: ScrollState) { + if (scrollState.maxValue > 0) { + VerticalScrollbar( + adapter = rememberScrollbarAdapter(scrollState), + style = umamoScrollbarStyle(), + modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), + ) + } +} + +/** + * Desktop actual: Foundation's draggable VerticalScrollbar for a LazyColumn, gated on it being scrollable. + * + * デスクトップ実装:LazyColumn がスクロール可能なときのみバーを描画する。 + * + * @param LazyListState listState The LazyColumn's state to drive and gate on. + */ +@Composable +actual fun BoxScope.VerticalScrollbarOverlay(listState: LazyListState) { + if (listState.canScrollForward || listState.canScrollBackward) { + VerticalScrollbar( + adapter = rememberScrollbarAdapter(listState), + style = umamoScrollbarStyle(), + modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), + ) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/Tooltip.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/Tooltip.jvm.kt new file mode 100644 index 0000000..bc16a6b --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/kit/Tooltip.jvm.kt @@ -0,0 +1,44 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.TooltipArea +import androidx.compose.foundation.TooltipPlacement +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.DpOffset +import androidx.compose.ui.unit.dp + +/** How long the pointer must dwell over the content before the tooltip appears. */ +private const val TOOLTIP_DELAY_MILLIS = 500 + +/** + * Desktop tooltip: [TooltipArea] reveals the label after a mouse-dwell over the content, placed just + * below the cursor. A blank label attaches nothing (the content is wrapped only to carry [modifier]), + * so callers can pass an unconditional description. + * + * デスクトップのツールチップ。マウス静止後にカーソル下へラベルを表示する。空ラベルは何も表示しない。 + * + * @param String text The tooltip label; blank attaches no tooltip. + * @param Modifier modifier The layout modifier, applied to the wrapper. + * @param Function content The control the tooltip describes. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +actual fun Tooltip(text: String, modifier: Modifier, content: @Composable () -> Unit) { + if (text.isBlank()) { + Box(modifier = modifier) { + content() + } + return + } + TooltipArea( + tooltip = { TooltipCard(text) }, + modifier = modifier, + delayMillis = TOOLTIP_DELAY_MILLIS, + // Follow the cursor rather than anchoring the component, matching the Blender-style pointer focus; + // the downward offset keeps the card clear of the pointer itself. + tooltipPlacement = TooltipPlacement.CursorPoint(offset = DpOffset(0.dp, 16.dp)), + content = content, + ) +} \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/l10n/SystemLanguage.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/l10n/SystemLanguage.jvm.kt new file mode 100644 index 0000000..2aaa9c2 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/l10n/SystemLanguage.jvm.kt @@ -0,0 +1,25 @@ +package org.umamo.ui.l10n + +/** + * The desktop JVM's system language, read from the user.* system properties the JVM fills from the operating + * system at startup. Locale.setDefault - what applyAppLocale calls - never rewrites these properties, so the + * answer does not depend on whether the app has applied its own language yet. The display variants win where + * the JVM sets them (the platforms whose display and format locales can differ), since the UI language is the + * display one. The JVM reports a single language, not the operating system's whole preference list. + * + * @return List The system language tag, or empty when the JVM reports none. + */ +actual fun systemLanguageTags(): List { + val language = systemProperty("user.language.display") ?: systemProperty("user.language") ?: return emptyList() + val script = systemProperty("user.script.display") ?: systemProperty("user.script") + val region = systemProperty("user.country.display") ?: systemProperty("user.country") ?: systemProperty("user.region") + return listOf(listOfNotNull(language, script, region).joinToString("-")) +} + +/** + * Reads one system property, treating a blank value as unset. + * + * @param String name The property name. + * @return String? The value, or null when it is unset or blank. + */ +private fun systemProperty(name: String): String? = System.getProperty(name)?.takeIf { value -> value.isNotBlank() } \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/theme/SystemCursor.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/theme/SystemCursor.jvm.kt new file mode 100644 index 0000000..5feca34 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/theme/SystemCursor.jvm.kt @@ -0,0 +1,122 @@ +package org.umamo.ui.theme + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Canvas +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.drawscope.CanvasDrawScope +import androidx.compose.ui.graphics.toAwtImage +import androidx.compose.ui.input.pointer.PointerIcon +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.LayoutDirection +import java.awt.Dimension +import java.awt.Point +import java.awt.Toolkit +import java.awt.image.BufferedImage +import java.util.concurrent.ConcurrentHashMap +import kotlin.math.max +import kotlin.math.roundToInt + +/** + * The fallback cursor box used when the toolkit reports no preferred size. 32x32 is the near-universal + * native cursor size, so this is only a guard against a toolkit that answers 0. + */ +private const val FALLBACK_CURSOR_SIZE = 32 + +/** + * The fraction of the cursor box the art spans. Kept under 1 so a hotspot that sits on the art's edge + * still has a pixel of margin inside the bitmap and the outline is not clipped by the box. + */ +private const val CURSOR_ART_FRACTION = 0.9f + +/** + * Baked cursors, keyed by the cursor definition. Without this every hover frame would rasterize a fresh + * bitmap and ask the toolkit for a new native cursor, since the icon is resolved during composition. The + * bundled cursors are a single top-level value, so the same key instance comes back each time. Concurrent + * because composition is not pledged to one thread, and a torn HashMap would be a genuine crash. + */ +private val bakedCursors = ConcurrentHashMap() + +/** + * A single cached transparent AWT cursor; falls back to the default pointer if the toolkit cannot build a + * custom cursor (a locked-down or headless environment). + */ +private val hiddenCursorIcon: PointerIcon by lazy { + try { + val transparent = BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB) + val cursor = Toolkit.getDefaultToolkit().createCustomCursor(transparent, Point(0, 0), "umamo-hidden") + PointerIcon(cursor) + } catch (error: Exception) { + // HeadlessException, IndexOutOfBoundsException (bad hotspot), or a toolkit failure - fall back. + PointerIcon.Default + } +} + +/** + * Rasterizes [cursor] into an AWT custom cursor at the toolkit's preferred cursor size. + * + * The art is scaled to [CURSOR_ART_FRACTION] of the box and centered, then the cursor's own hotspot + * fraction is resolved against the PAINTED bounds (not the authored viewport) to a pixel, mirroring what + * drawCursor does on the overlay path - so the same art tracks the pointer identically whether the OS or + * the viewport overlay is drawing it. + * + * @param UmamoCursor cursor The cursor definition to bake. + * @return PointerIcon The AWT-backed cursor, or the default if the toolkit refuses one. + */ +private fun bakeCursor(cursor: UmamoCursor): PointerIcon = + try { + val toolkit = Toolkit.getDefaultToolkit() + val preferred: Dimension? = toolkit.getBestCursorSize(FALLBACK_CURSOR_SIZE, FALLBACK_CURSOR_SIZE) + val boxSize = max(preferred?.width ?: 0, preferred?.height ?: 0).takeIf { it > 0 } ?: FALLBACK_CURSOR_SIZE + val artSpan = boxSize * CURSOR_ART_FRACTION + + // Match drawCursor: scale so the art's LONGER side spans artSpan, keeping the authored aspect. + val bounds = cursor.bounds + val drawScale = artSpan / max(bounds.width, bounds.height) + val artWidth = bounds.width * drawScale + val artHeight = bounds.height * drawScale + // Center the art in the box, then resolve the hotspot inside it. + val hotspotX = (boxSize - artWidth) / 2f + cursor.hotspot.fractionX * artWidth + val hotspotY = (boxSize - artHeight) / 2f + cursor.hotspot.fractionY * artHeight + + val bitmap = ImageBitmap(boxSize, boxSize) + CanvasDrawScope().draw( + density = Density(1f), + layoutDirection = LayoutDirection.Ltr, + canvas = Canvas(bitmap), + size = Size(boxSize.toFloat(), boxSize.toFloat()), + ) { + // drawCursor places the hotspot exactly on the anchor, so anchoring at the resolved hotspot + // lands the art where the centering math intends. + drawCursor(cursor, Offset(hotspotX, hotspotY), pixelSize = artSpan) + } + + val awtHotspot = + Point( + hotspotX.roundToInt().coerceIn(0, boxSize - 1), + hotspotY.roundToInt().coerceIn(0, boxSize - 1), + ) + PointerIcon(toolkit.createCustomCursor(bitmap.toAwtImage(), awtHotspot, "umamo-cursor")) + } catch (error: Exception) { + // HeadlessException, an unsupported cursor size, or a raster failure - a stock pointer still works. + PointerIcon.Default + } + +/** + * Desktop actual: bakes the vector cursor into an AWT custom cursor once and reuses it thereafter. + * + * デスクトップ実装:ベクターカーソルを AWT カーソルに一度だけ焼き込み、以降は再利用する。 + * + * @param UmamoCursor cursor The cursor definition to rasterize. + * @return PointerIcon The AWT-backed cursor showing that art. + */ +actual fun umamoPointerIcon(cursor: UmamoCursor): PointerIcon = bakedCursors.getOrPut(cursor) { bakeCursor(cursor) } + +/** + * Desktop actual: an invisible cursor built from a fully transparent 16x16 image. + * + * デスクトップ実装:透明画像から作った不可視カーソルを返す。 + * + * @return PointerIcon The transparent cursor, or the default where none can be built. + */ +actual fun hiddenPointerIcon(): PointerIcon = hiddenCursorIcon \ No newline at end of file diff --git a/module/ui/src/jvmMain/kotlin/org/umamo/ui/viewport/ViewportCursor.jvm.kt b/module/ui/src/jvmMain/kotlin/org/umamo/ui/viewport/ViewportCursor.jvm.kt new file mode 100644 index 0000000..b74c270 --- /dev/null +++ b/module/ui/src/jvmMain/kotlin/org/umamo/ui/viewport/ViewportCursor.jvm.kt @@ -0,0 +1,42 @@ +package org.umamo.ui.viewport + +import androidx.compose.ui.geometry.Offset +import java.awt.MouseInfo +import java.awt.Robot +import kotlin.math.roundToInt + +/** + * A single shared AWT Robot used to warp the cursor. It is null when the platform denies low-level input + * control - a headless environment (Robot's constructor throws there) or a locked-down SecurityManager - + * in which case cursor warps degrade to no-ops rather than crashing. + */ +private val cursorWarpRobot: Robot? by lazy { + try { + Robot() + } catch (error: Exception) { + // AWTException (incl. headless), SecurityException, or HeadlessException - warp is unavailable. + null + } +} + +/** + * Desktop actual: teleport the OS cursor to the given screen pixel via AWT Robot, then read back where + * it actually landed via MouseInfo. The read-back (rather than trusting the request) is what keeps the + * wrap compensation exact when mouseMove rounds, clamps at a screen edge, or is rescaled by the platform + * (HiDPI / WSLg). A no-op returning null when no Robot is available (headless / denied), so the caller + * leaves its gesture anchor alone. + * + * デスクトップ実装:AWT Robot でカーソルを画面座標へ移動し、実際の着地点を MouseInfo で読み返す。 + * + * @param Float screenX The requested absolute screen x in pixels. + * @param Float screenY The requested absolute screen y in pixels. + * @return Offset? The absolute screen position the cursor landed at, or null when no Robot is available. + */ +actual fun warpViewportCursor(screenX: Float, screenY: Float): Offset? { + val robot = cursorWarpRobot ?: return null + robot.mouseMove(screenX.roundToInt(), screenY.roundToInt()) + // MouseInfo can be unavailable (headless edge cases): fall back to the rounded request, the best + // available estimate of where the cursor landed. + val landed = MouseInfo.getPointerInfo()?.location ?: return Offset(screenX.roundToInt().toFloat(), screenY.roundToInt().toFloat()) + return Offset(landed.x.toFloat(), landed.y.toFloat()) +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/action/KeyNameJvmTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/action/KeyNameJvmTest.kt new file mode 100644 index 0000000..b551b4f --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/action/KeyNameJvmTest.kt @@ -0,0 +1,37 @@ +package org.umamo.ui.action + +import androidx.compose.ui.input.key.Key +import java.awt.event.KeyEvent +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the desktop numpad normalization: AWT delivers the physical numpad keys as codes that differ + * from (or arrive located differently than) the codes Compose's Key.NumPad* constants are built from, + * and without [normalizeKeyPosition] those bindings silently never fire. + */ +class KeyNameJvmTest { + @Test + fun numpadDecimalAsDeliveredByAwtResolves() { + // AWT reports the numpad period as VK_DECIMAL at the NUMPAD location; Compose's constant is + // Key(VK_PERIOD, NUMPAD), so the raw key only names through the remap. + assertEquals("NumpadDecimal", keyName(Key(KeyEvent.VK_DECIMAL, KeyEvent.KEY_LOCATION_NUMPAD))) + assertEquals("NumpadDecimal", keyName(Key.NumPadDot), "the constant itself keeps naming") + } + + @Test + fun numpadOperatorsResolveEvenWithAMisreportedLocation() { + assertEquals("NumpadAdd", keyName(Key(KeyEvent.VK_ADD, KeyEvent.KEY_LOCATION_NUMPAD))) + // Some X stacks under-report the location; numpad-only codes re-locate defensively. + assertEquals("NumpadAdd", keyName(Key(KeyEvent.VK_ADD, KeyEvent.KEY_LOCATION_STANDARD))) + assertEquals("Numpad7", keyName(Key(KeyEvent.VK_NUMPAD7, KeyEvent.KEY_LOCATION_STANDARD))) + } + + @Test + fun mainRowKeysAreUntouchedByTheNormalization() { + // The main-row period shares the VK code the NumPadDot constant is built from; it must keep + // resolving to Period (the pivot pie's binding), never remap into a numpad key. + assertEquals("Period", keyName(Key(KeyEvent.VK_PERIOD, KeyEvent.KEY_LOCATION_STANDARD))) + assertEquals("KeyG", keyName(Key.G)) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/AppControllerFixture.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/AppControllerFixture.kt new file mode 100644 index 0000000..29d4160 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/AppControllerFixture.kt @@ -0,0 +1,113 @@ +package org.umamo.ui.app + +import io.github.vinceglb.filekit.PlatformFile +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.job +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.edit.EditorSession +import org.umamo.settings.Settings +import org.umamo.storage.FilePicker +import org.umamo.storage.OkioAppStorage +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.document.Document +import org.umamo.ui.document.DocumentFile +import org.umamo.ui.document.PuppetDocument +import org.umamo.ui.workspace.AreaViewStates + +/** + * The app controllers' collaborators for a test, with no composition and no dialogs: in-memory settings, + * a picker that is always cancelled, and a registry whose shell commands record what they were asked + * instead of raising an overlay. + * + * The open document is a plain variable the controllers read through [EditorAppServices.current], the way + * the app's holder hands them the live composition's context - so a test swaps the document by assigning + * [context], exactly as opening one does. + * + * @param CoroutineScope scope The scope the controllers' work runs in (a test's own scope). + */ +internal class AppControllerFixture( + private val scope: CoroutineScope, +) { + /** Every command the controllers dispatched, in order, with its argument. */ + val invocations = ArrayList>() + + /** Every document the controllers swapped in, in order. */ + val opened = ArrayList() + + /** The settings the controllers write recent files to. */ + val settings: Settings + + /** The registry, holding a recorder for each shell command a controller raises. */ + val registry = CommandRegistry() + + /** The open document's context as the controllers see it; starts with no document, like a launch. */ + var context: OpenDocumentContext = contextFor(null) + + /** The collaborators the controllers under test are built over. */ + val services: EditorAppServices + + init { + val fileSystem = FakeFileSystem() + val configDirectory = "/config".toPath() + fileSystem.createDirectories(configDirectory) + settings = Settings.load(OkioAppStorage(fileSystem, configDirectory, "/data".toPath()), "{}") + for (commandId in listOf("document.confirmReplace", "document.confirmExit", "document.openFailed", "document.alert")) { + registry.register(Command(commandId, title = null) { argument -> invocations.add(commandId to argument) }) + } + services = + EditorAppServices( + settings = settings, + scope = scope, + filePicker = CancelledFilePicker, + commandRegistry = registry, + current = { context }, + onOpen = { document -> opened.add(document) }, + untitledName = { "Untitled" }, + ) + } + + /** + * Waits for the work the controllers launched to finish. + * + * A controller does its file reading in a coroutine on the shared scope, and the read itself runs on a + * real IO dispatcher - so the test scheduler's own idle point says nothing about whether it is done. + * Joining the scope's children waits for the real thing. The caller's own job is excluded, since a + * test body waiting on itself never returns. + */ + suspend fun settle() { + val caller = currentCoroutineContext().job + scope.coroutineContext.job.children.filter { child -> child !== caller }.forEach { child -> child.join() } + } + + /** + * The arguments [commandId] was dispatched with, in order. + * + * @param String commandId The command. + * @return List Its arguments, one per dispatch. + */ + fun argumentsOf(commandId: String): List = invocations.filter { (id, _) -> id == commandId }.map { (_, argument) -> argument } + + companion object { + /** + * The context the app would build for [document]: its session and its save target, no resolved pages + * (the fallback is the document's own), and empty area state. + * + * @param Document? document The open document, or null. + * @return OpenDocumentContext The context. + */ + fun contextFor(document: Document?): OpenDocumentContext { + val session = (document as? PuppetDocument)?.let { puppetDocument -> EditorSession(puppetDocument.puppet, puppetDocument.liveParams.values) } + return OpenDocumentContext(document, session, document?.let { origin -> DocumentFile(origin) }, atlasPages = null, areaViewStates = AreaViewStates(null)) + } + } +} + +/** A picker whose every dialog is cancelled: the tests here never reach a file. */ +private object CancelledFilePicker : FilePicker { + override suspend fun openFile(extensions: List): PlatformFile? = null + + override suspend fun saveFile(suggestedName: String, extension: String): PlatformFile? = null +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/DocumentOpenControllerTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/DocumentOpenControllerTest.kt new file mode 100644 index 0000000..8555c8e --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/DocumentOpenControllerTest.kt @@ -0,0 +1,117 @@ +package org.umamo.ui.app + +import kotlinx.coroutines.test.runTest +import org.umamo.edit.setCanvasSize +import org.umamo.ui.document.BlankDocument +import org.umamo.ui.document.DocumentLoad +import org.umamo.ui.document.DocumentOpenError +import org.umamo.ui.document.DocumentOpenFailure +import org.umamo.ui.document.emptyDocumentBytes +import org.umamo.ui.document.loadDocument +import org.umamo.ui.document.newBlankDocument +import org.umamo.ui.document.recentFiles +import org.umamo.ui.document.umaBytesWithUnknownRequiredEntry +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.alert_document_read_only +import org.umamo.ui.workspace.AlertRequest +import org.umamo.ui.workspace.commands.DirtyDocumentPrompt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins what landing a load does, and that replacing the document goes through the unsaved-changes gate. + * A failure must reach the rigger as an alert and open nothing; a success is recorded and swapped in; a + * file that opened read-only says so once, up front, since Save is greyed for the document's life. + */ +class DocumentOpenControllerTest { + /** + * The open controller over [fixture], with the save controller whose gate it borrows. + * + * @param AppControllerFixture fixture The collaborators. + * @return DocumentOpenController The controller. + */ + private fun controllerOver(fixture: AppControllerFixture): DocumentOpenController = DocumentOpenController(fixture.services, DocumentSaveController(fixture.services)) + + @Test + fun aFailedLoadRaisesTheAlertAndOpensNothing() = + runTest { + val fixture = AppControllerFixture(this) + val failure = DocumentOpenFailure(DocumentOpenError.Unrecognized, "notes.bin") + + controllerOver(fixture).applyDocumentLoad(DocumentLoad.Failed(failure)) + + assertSame(failure, fixture.argumentsOf("document.openFailed").single(), "the rigger is told why nothing opened") + assertTrue(fixture.opened.isEmpty(), "and the open document is left alone") + assertTrue(fixture.settings.recentFiles().isEmpty(), "a file that would not open is not a recent file") + } + + @Test + fun aLoadedFileIsRecordedAndSwappedIn() = + runTest { + val fixture = AppControllerFixture(this) + val load = assertIs(loadDocument(emptyDocumentBytes(), "rig.uma", "/rigs/rig.uma")) + + controllerOver(fixture).applyDocumentLoad(load) + + assertSame(load.document, fixture.opened.single()) + assertEquals(listOf("/rigs/rig.uma"), fixture.settings.recentFiles()) + assertTrue(fixture.invocations.isEmpty(), "a document that can be saved opens without an alert") + } + + @Test + fun aReadOnlyDocumentSaysSoOnceAsItOpens() = + runTest { + val fixture = AppControllerFixture(this) + val load = assertIs(loadDocument(umaBytesWithUnknownRequiredEntry(), "rig.uma", "/rigs/rig.uma")) + + controllerOver(fixture).applyDocumentLoad(load) + + assertSame(load.document, fixture.opened.single(), "it still opens: it can be viewed, edited, and exported") + val alert = assertIs(fixture.argumentsOf("document.alert").single()) + assertEquals(Res.string.alert_document_read_only, alert.message) + assertEquals(listOf("rig.uma", "future/thing.json (mystery)"), alert.arguments, "naming the file and every entry that blocks saving") + } + + /** + * Opening a stored path is the one entry every file the editor is HANDED comes through - Open Recent, a + * document the operating system passes over, a file dropped on the window - so the unsaved-changes gate + * has to sit on it and not on each of those callers. + */ + @Test + fun openingAStoredPathOverADirtyDocumentAsksFirst() = + runTest { + val fixture = AppControllerFixture(this) + val open = controllerOver(fixture) + fixture.context = AppControllerFixture.contextFor(newBlankDocument()) + val session = assertNotNull(fixture.context.session) + session.setCanvasSize(session.model.value.canvasWidth + 64f, session.model.value.canvasHeight) + + open.openStoredPath("/rigs/missing.uma") + + assertTrue(fixture.opened.isEmpty(), "nothing is read until the prompt is answered") + assertIs(fixture.argumentsOf("document.confirmReplace").single()).discard() + fixture.settle() + // The path does not exist, so the load fails - which is the proof it was attempted at all. + assertEquals(1, fixture.argumentsOf("document.openFailed").size, "and then the load runs") + } + + @Test + fun aNewDocumentOverADirtyOneAsksFirst() = + runTest { + val fixture = AppControllerFixture(this) + val open = controllerOver(fixture) + fixture.context = AppControllerFixture.contextFor(newBlankDocument()) + val session = assertNotNull(fixture.context.session) + session.setCanvasSize(session.model.value.canvasWidth + 64f, session.model.value.canvasHeight) + + open.newDocument() + + assertTrue(fixture.opened.isEmpty(), "File > New never discards unsaved edits on its own") + assertIs(fixture.argumentsOf("document.confirmReplace").single()).discard() + assertIs(fixture.opened.single(), "choosing not to save goes on to the empty document") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/DocumentSaveControllerTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/DocumentSaveControllerTest.kt new file mode 100644 index 0000000..239eb9c --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/DocumentSaveControllerTest.kt @@ -0,0 +1,131 @@ +package org.umamo.ui.app + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.umamo.edit.setCanvasSize +import org.umamo.ui.document.DocumentLoad +import org.umamo.ui.document.UmaDocument +import org.umamo.ui.document.loadDocument +import org.umamo.ui.document.newBlankDocument +import org.umamo.ui.document.umaBytesWithUnknownRequiredEntry +import org.umamo.ui.workspace.commands.DirtyDocumentPrompt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins the unsaved-changes gate in front of a document replace and a quit. + * + * The case that matters most is the first. The file commands register once and the exit guard installs + * once, at launch, when no document is open - so a gate that remembered the document it was made with + * would find nothing to ask about for the rest of the run, and Ctrl+O would replace a dirty document with + * no prompt at all while the File menu's own row asked correctly. The controller reads the document that + * is open NOW, and that is what these hold it to. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DocumentSaveControllerTest { + /** + * Opens a new document in [fixture] and edits it, so it has changes to lose. + * + * @param AppControllerFixture fixture The fixture whose open document is replaced. + */ + private fun openADirtyDocument(fixture: AppControllerFixture) { + fixture.context = AppControllerFixture.contextFor(newBlankDocument()) + val session = assertNotNull(fixture.context.session) + session.setCanvasSize(session.model.value.canvasWidth + 64f, session.model.value.canvasHeight) + assertTrue(session.dirty.value, "the edit dirtied the document") + } + + @Test + fun aGateMadeAtLaunchAsksAboutTheDocumentOpenNow() = + runTest { + val fixture = AppControllerFixture(this) + // Made with no document open, as the app makes it at launch. + val save = DocumentSaveController(fixture.services) + var proceeded = 0 + + openADirtyDocument(fixture) + save.confirmIfDirty { proceeded++ } + + assertEquals(0, proceeded, "a dirty document is never replaced without asking") + val prompt = assertIs(fixture.argumentsOf("document.confirmReplace").single()) + prompt.discard() + assertEquals(1, proceeded, "choosing not to save goes on with the replace") + } + + @Test + fun quittingAsksAboutTheDocumentOpenNowToo() = + runTest { + val fixture = AppControllerFixture(this) + val save = DocumentSaveController(fixture.services) + var exited = 0 + + openADirtyDocument(fixture) + save.confirmExit { exited++ } + + assertEquals(0, exited, "a dirty document is never quit without asking") + assertEquals(1, fixture.argumentsOf("document.confirmExit").size) + assertTrue(fixture.argumentsOf("document.confirmReplace").isEmpty(), "the quit prompt is its own, worded for quitting") + } + + @Test + fun aCleanDocumentIsReplacedWithoutAsking() = + runTest { + val fixture = AppControllerFixture(this) + val save = DocumentSaveController(fixture.services) + fixture.context = AppControllerFixture.contextFor(newBlankDocument()) + var proceeded = 0 + + save.confirmIfDirty { proceeded++ } + + assertEquals(1, proceeded) + assertTrue(fixture.invocations.isEmpty(), "with nothing to lose, nothing is asked") + } + + @Test + fun thePromptOffersSaveOnlyWhenTheDocumentCanBeSaved() = + runTest { + val fixture = AppControllerFixture(this) + val save = DocumentSaveController(fixture.services) + + openADirtyDocument(fixture) + assertTrue(save.canSaveNow()) + save.confirmIfDirty {} + assertNotNull(assertIs(fixture.argumentsOf("document.confirmReplace").single()).save, "a saveable document offers Save") + + // A document that opened read-only can be edited but never saved, so its prompt is discard-or-cancel. + val load = loadDocument(umaBytesWithUnknownRequiredEntry(), "rig.uma", "/rigs/rig.uma") + val readOnly = assertIs(assertIs(load).document) + fixture.context = AppControllerFixture.contextFor(readOnly) + val session = assertNotNull(fixture.context.session) + session.setCanvasSize(session.model.value.canvasWidth + 64f, session.model.value.canvasHeight) + + assertEquals(false, save.canSaveNow()) + save.confirmIfDirty {} + assertNull(assertIs(fixture.argumentsOf("document.confirmReplace").last()).save, "a read-only document has no Save to offer") + } + + @Test + fun theGateWaitsForASaveStillBeingWritten() = + runTest { + val fixture = AppControllerFixture(this) + val save = DocumentSaveController(fixture.services) + fixture.context = AppControllerFixture.contextFor(newBlankDocument()) + val writing = CompletableDeferred() + assertNotNull(fixture.context.file).saveJob = writing + var exited = 0 + + save.confirmExit { exited++ } + runCurrent() + assertEquals(0, exited, "nothing ends the process while the file is being written") + + writing.complete(true) + runCurrent() + assertEquals(1, exited, "the file landed, so the quit goes on") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/HostOpenRequestsTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/HostOpenRequestsTest.kt new file mode 100644 index 0000000..57a0d1c --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/app/HostOpenRequestsTest.kt @@ -0,0 +1,56 @@ +package org.umamo.ui.app + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins the one property the host-to-shell open seam exists for: a request made before anything collects - a cold + * launch's double-clicked file, which the OS delivers before the first composition - is held, not dropped. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class HostOpenRequestsTest { + /** Requests made before the shell exists reach it, in order, once it starts collecting. */ + @Test + fun requestsMadeBeforeACollectorAreHeldInOrder() = + runTest { + val openRequests = HostOpenRequests() + openRequests.request("/rigs/first.uma") + openRequests.request("content://documents/second.uma") + val opened = mutableListOf() + + val collector = launch { openRequests.requests.collect { requestedPath -> opened += requestedPath } } + runCurrent() + + assertEquals(listOf("/rigs/first.uma", "content://documents/second.uma"), opened) + collector.cancelAndJoin() + } + + /** + * A collector that went away - the shell recomposed under another document - does not take the seam with it: + * the next collector receives what is asked afterwards, and nothing is delivered twice. + */ + @Test + fun aLaterCollectorReceivesLaterRequests() = + runTest { + val openRequests = HostOpenRequests() + val openedByFirst = mutableListOf() + val first = launch { openRequests.requests.collect { requestedPath -> openedByFirst += requestedPath } } + openRequests.request("/rigs/first.uma") + runCurrent() + first.cancelAndJoin() + + val openedBySecond = mutableListOf() + val second = launch { openRequests.requests.collect { requestedPath -> openedBySecond += requestedPath } } + openRequests.request("/rigs/second.uma") + runCurrent() + + assertEquals(listOf("/rigs/first.uma"), openedByFirst) + assertEquals(listOf("/rigs/second.uma"), openedBySecond) + second.cancelAndJoin() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddArtworkFlowTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddArtworkFlowTest.kt new file mode 100644 index 0000000..29b7a9f --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddArtworkFlowTest.kt @@ -0,0 +1,198 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.edit.seed.ParameterTemplate +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.render.deriveAtlasTextures +import org.umamo.runtime.model.ParameterNode +import org.umamo.ui.model.AddArtworkRequest +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.ImportParameterKeys +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.runAddArtwork +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Add Artwork into an open document, driven the way the shell drives it: a second PSD read through + * [readArtwork], appended and packed by [runAddArtwork] over a live session with its page resolver + * following, then undone, then adjusted through the operation record. + * + * What only a real pair of files proves: the added art packs into the gaps without moving a single + * existing placement, the pages the session publishes equal their derivation, the step is one undo, + * and an adjustment of the margin re-lands the same step with wider quads. Gated on `psd.sample` + * with the sibling `EricaVisibilityTest.psd` as the second file; self-skips without either. + */ +class AddArtworkFlowTest { + private val sample: File? = System.getProperty("psd.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aSecondPsdJoinsTheOpenDocumentBesideItsArt() = + runBlocking { + val first = sample + val second = first?.let { file -> File(file.parentFile, "EricaVisibilityTest.psd") }?.takeIf { it.isFile } + if (first == null || second == null) { + println("psd.sample (and its EricaVisibilityTest.psd sibling) not present; skipping the add-artwork flow gate") + return@runBlocking + } + val load = loadDocument(first.readBytes(), first.name, first.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the add must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val read = assertNotNull(readArtwork(second.readBytes(), second.name), "the second file reads as artwork") + val request = AddArtworkRequest(read.art, ArtSourceDescriptor(second.name, second.path, read.kind.extension), SourceArtImportOptions()) + val before = session.model.value + val placementsBefore = before.atlas.tiles.associate { tile -> tile.id to tile.placement } + + assertTrue(runAddArtwork(host, request, areaId = null), "the artwork is added") + val grown = session.model.value + assertEquals(2, grown.sources.size, "the document lists both files") + assertEquals(before.drawables.size * 2, grown.drawables.size, "the twin PSD adds one drawable per layer") + for ((tileId, placement) in placementsBefore) { + assertEquals(placement, grown.atlas.tileById.getValue(tileId).placement, "existing tile '${tileId.raw}' did not move") + } + val addedTiles = grown.atlas.tiles.filter { tile -> tile.id !in placementsBefore } + assertTrue(addedTiles.isNotEmpty() && addedTiles.all { tile -> tile.placement != null }, "every added tile is placed") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== grown.atlas) { + yield() + } + } + val published = sessionAtlasPages.binding.value.textures + val derived = assertNotNull(deriveAtlasTextures(grown, document.artRasters, premultipliedAlpha = false), "the grown model derives") + assertEquals(derived.atlases.size, published.atlases.size, "page count") + for ((pageIndex, page) in published.atlases.withIndex()) { + assertTrue(page.rgba.contentEquals(derived.atlases[pageIndex].rgba), "published page $pageIndex equals its derivation") + } + + // An adjustment re-lands the SAME step: wider birth quads, same source. It has to come before + // any undo, which retires the record by design. + val record = assertNotNull(session.adjustableOperation.value, "the add registered on the strip") + val addedDrawable = grown.drawables.first { drawable -> drawable.atlasTileId in addedTiles.map { tile -> tile.id }.toSet() } + val quadBefore = assertNotNull(addedDrawable.mesh).positions.copyOf() + val widened = record.parameters.map { parameter -> if (parameter.key == ImportParameterKeys.MARGIN && parameter is OperatorParameter.IntParameter) parameter.copy(value = parameter.value + 6) else parameter } + session.adjustLastOperation(widened) + withTimeout(120_000) { + while (session.model.value.drawables.first { drawable -> drawable.id == addedDrawable.id }.mesh?.positions?.contentEquals(quadBefore) != false) { + yield() + } + } + val quadAfter = assertNotNull(session.model.value.drawables.first { drawable -> drawable.id == addedDrawable.id }.mesh).positions + assertEquals(quadBefore[0] - 6f, quadAfter[0], 1e-3f, "the quad's left edge moved out by the margin change") + assertEquals(2, session.model.value.sources.size, "the adjusted step still holds one added file") + + // The whole add is one step: undo removes the file, its tiles, and its drawables together. + session.undo() + assertEquals(1, session.model.value.sources.size, "undo removes the added file") + assertEquals(before.drawables.size, session.model.value.drawables.size) + session.redo() + assertEquals(2, session.model.value.sources.size, "redo brings it back") + assertTrue(assertNotNull(session.model.value.drawables.first { drawable -> drawable.id == addedDrawable.id }.mesh).positions.contentEquals(quadAfter), "and the adjusted quad with it") + follower.cancel() + println("add-artwork gate: ${addedTiles.size} tiles added onto ${grown.atlas.pages.size} page(s)") + } + + /** + * The first artwork imported into a NEW document gives the rig its frame and its axes, and a second + * file leaves both alone. + * + * This is the path every rig starts on - a new document opens empty and artwork is imported into + * it - so the first import is what seeds the rig: the file's canvas over the placeholder one, the + * world origin at its center, the parameter template, and the flat parameter tree the CMO3 export + * reads. + */ + @Test + fun theFirstImportIntoANewDocumentSeedsItsCanvasAndParameters() = + runBlocking { + val first = sample + val second = first?.let { file -> File(file.parentFile, "EricaVisibilityTest.psd") }?.takeIf { it.isFile } + if (first == null || second == null) { + println("psd.sample (and its EricaVisibilityTest.psd sibling) not present; skipping the new-document import gate") + return@runBlocking + } + val document = newBlankDocument() + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the import must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val options = artworkImportOptions(ParameterTemplate.Humanoid) + val read = assertNotNull(readArtwork(first.readBytes(), first.name), "the file reads as artwork") + + assertTrue( + runAddArtwork(host, AddArtworkRequest(read.art, ArtSourceDescriptor(first.name, first.path, read.kind.extension), options), areaId = null), + "the artwork is imported", + ) + + val seeded = session.model.value + assertTrue(seeded.drawables.isNotEmpty(), "the layers landed as drawables") + assertEquals(read.art.widthPx.toFloat(), seeded.canvasWidth, "the canvas is the file's") + assertEquals(read.art.heightPx.toFloat(), seeded.canvasHeight, "the canvas is the file's") + assertEquals(seeded.canvasWidth / 2f, seeded.worldOriginX, "the world origin is the canvas center") + assertEquals(-(seeded.canvasHeight / 2f), seeded.worldOriginZ, "the world origin is the canvas center") + assertEquals( + ParameterTemplate.Humanoid.parameters.map { parameter -> parameter.id }, + seeded.parameters.map { parameter -> parameter.id }, + "the template seeded the axes", + ) + assertEquals( + seeded.parameters.map { parameter -> parameter.id }, + seeded.parameterTree.map { node -> assertIs(node).id }, + "and the tree is materialized flat, which the CMO3 export reads", + ) + + // A second file is placed within the frame the first one set: it redefines neither the canvas + // nor the axes, template in hand or not. + val secondRead = assertNotNull(readArtwork(second.readBytes(), second.name), "the second file reads as artwork") + assertTrue( + runAddArtwork( + host, + AddArtworkRequest(secondRead.art, ArtSourceDescriptor(second.name, second.path, secondRead.kind.extension), options), + areaId = null, + ), + "the second artwork is imported", + ) + + val grown = session.model.value + assertEquals(seeded.canvasWidth, grown.canvasWidth, "the canvas is unchanged") + assertEquals(seeded.canvasHeight, grown.canvasHeight, "the canvas is unchanged") + assertEquals(seeded.worldOriginX, grown.worldOriginX, "the world origin is unchanged") + assertEquals( + seeded.parameters.map { parameter -> parameter.id }, + grown.parameters.map { parameter -> parameter.id }, + "the axes are neither replaced nor duplicated", + ) + assertEquals(2, grown.sources.size, "and both files are listed") + follower.cancel() + println("new-document import gate: ${grown.drawables.size} drawables over ${grown.atlas.pages.size} page(s)") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddVertexWipeGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddVertexWipeGateTest.kt new file mode 100644 index 0000000..f39d4be --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddVertexWipeGateTest.kt @@ -0,0 +1,127 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.runBlocking +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.MeshTopologyOps +import org.umamo.edit.MeshUvField +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.runtime.model.DrawableId +import org.umamo.ui.transform.captureDrawableWorld +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Wipe-and-rebuild Add Vertex on Bear_.uma: after deleting every vert, Accept must land a textured + * triangle on the art (posed-space seed + auto-close), not off to the side. + */ +class AddVertexWipeGateTest { + private val bear = File("/home/litruv/Desktop/Bear_.uma").takeIf { it.isFile } + + @Test + fun wipeRebuildAcceptsTexturedTriangle() = + runBlocking { + val file = bear + if (file == null) { + println("Bear_.uma missing; skip") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet) + val drawableId = DrawableId("Jumper") + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(drawableId))) + session.setMode(EditorMode.Edit) + val before = assertNotNull(session.model.value.drawables.first { it.id == drawableId }.mesh) + assertTrue(before.vertexCount > 0 && before.triangleCount > 0, "jumper starts with a mesh") + val seedUMin = before.uvs.filterIndexed { i, _ -> i % 2 == 0 }.min() + val seedUMax = before.uvs.filterIndexed { i, _ -> i % 2 == 0 }.max() + val seedVMin = before.uvs.filterIndexed { i, _ -> i % 2 == 1 }.min() + val seedVMax = before.uvs.filterIndexed { i, _ -> i % 2 == 1 }.max() + + // Capture posed space while verts still exist (what the Edit overlay SideEffect does). + val geomBefore = assertNotNull(captureDrawableWorld(session.model.value, emptyMap(), drawableId)) + session.rememberAddVertexSpaceSeed( + drawableId, + geomBefore.base, + geomBefore.displayed, + geomBefore.world, + ) + + val enterVertCount = before.vertexCount + var mesh = before + while (mesh.vertexCount > 0) { + val result = MeshTopologyOps.deleteVertices(mesh, listOf(0))!! + assertTrue(session.commitMeshTopology("change.mesh.deleteVertex", drawableId, result)) + mesh = assertNotNull(session.model.value.drawables.first { it.id == drawableId }.mesh) + } + assertTrue(mesh.vertexCount == 0 && mesh.triangleCount == 0) + // Deletes must not shrink the UV seed — projection needs the Edit-enter mesh. + assertEquals( + enterVertCount, + assertNotNull(session.addVertexUvSeed(drawableId)).vertexCount, + "UV seed must stay the Edit-enter mesh through wipe", + ) + + val spaceSeed = assertNotNull(session.addVertexSpaceSeed(drawableId)) + val emptyGeom = assertNotNull(captureDrawableWorld(session.model.value, emptyMap(), drawableId)) + val worldA = floatArrayOf(spaceSeed.world[0], spaceSeed.world[1]) + val worldB = floatArrayOf(spaceSeed.world[2], spaceSeed.world[3]) + val worldC = floatArrayOf(spaceSeed.world[4], spaceSeed.world[5]) + val (baseAx, baseAy) = + emptyGeom.worldClickToBase( + worldA[0], + worldA[1], + spaceSeed.base, + spaceSeed.world, + spaceSeed.displayed, + ) + val restAx = spaceSeed.base[0] + val restAy = spaceSeed.base[1] + println("converted A=($baseAx,$baseAy) vs rest ($restAx,$restAy) err=${abs(baseAx - restAx) + abs(baseAy - restAy)}") + assertTrue( + abs(baseAx - restAx) + abs(baseAy - restAy) < 2f, + "wipe space seed must round-trip corner A", + ) + + session.addVertexWorldToBase = { id, x, y -> + val geom = captureDrawableWorld(session.model.value, emptyMap(), id)!! + val seed = session.addVertexSpaceSeed(id)!! + geom.worldClickToBase(x, y, seed.base, seed.world, seed.displayed) + } + session.beginAddVertex("gate") + session.addVertexDraftClick(worldA[0], worldA[1]) + session.addVertexDraftClick(worldB[0], worldB[1]) + session.addVertexDraftClick(worldC[0], worldC[1]) + session.acceptAddVertexDraft() + + val after = assertNotNull(session.model.value.drawables.first { it.id == drawableId }.mesh) + println("after verts=${after.vertexCount} tris=${after.triangleCount} uvs=${after.uvs.toList()}") + assertTrue(after.triangleCount >= 1, "Accept must create at least one face, got tris=${after.triangleCount}") + assertTrue(after.vertexCount >= 3, "Accept must keep the three floats") + // Edit-enter UV field: same rest position → same stored UV (texture locked to the seed mesh). + val uvSeed = assertNotNull(session.addVertexUvSeed(drawableId)) + val field = MeshUvField(uvSeed) + for (i in 0 until after.vertexCount) { + val x = after.positions[i * 2] + val y = after.positions[i * 2 + 1] + val (expectU, expectV) = field.uvAt(x, y) + assertTrue(abs(after.uvs[i * 2] - expectU) < 1e-3f, "u field-locked at vert $i") + assertTrue(abs(after.uvs[i * 2 + 1] - expectV) < 1e-3f, "v field-locked at vert $i") + assertTrue(after.uvs[i * 2] in (seedUMin - 0.05f)..(seedUMax + 0.05f), "u outside seed range") + assertTrue(after.uvs[i * 2 + 1] in (seedVMin - 0.05f)..(seedVMax + 0.05f), "v outside seed range") + } + // Corners of the original first triangle must keep their original seed UVs. + for (corner in 0 until 3) { + val (u, v) = field.uvAt(spaceSeed.base[corner * 2], spaceSeed.base[corner * 2 + 1]) + assertTrue(abs(u - before.uvs[corner * 2]) < 1e-3f, "original corner $corner u") + assertTrue(abs(v - before.uvs[corner * 2 + 1]) < 1e-3f, "original corner $corner v") + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddedArtCmo3ExportGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddedArtCmo3ExportGateTest.kt new file mode 100644 index 0000000..6e3033a --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/AddedArtCmo3ExportGateTest.kt @@ -0,0 +1,172 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.format.art.LayerBounds +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.caff.CaffArchive +import org.umamo.format.cmo3.caff.CaffCodec +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.png.PngCodec +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasIngest +import org.umamo.interop.cmo3.cmo3SourceArtOf +import org.umamo.ui.model.AddArtworkRequest +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.runAddArtwork +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertTrue + +/** + * A CMO3-origin document with a file added through Add Artwork exports it: the retained graph gains + * a layered image for the file with a layer per tile, a model image and an entry per tile, and the + * created drawables over them bind through the minted web. Read back, the file lists its layers + * under their keys with their pixels, the drawables re-import verbatim, and a reopened export is a + * byte-identical no-op - the same gate an unedited corpus file passes. + * + * Skips without the corpus sample. + */ +class AddedArtCmo3ExportGateTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun addedArtworkExportsAsALayeredImageAndReopensBoundByKey() = + runBlocking { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the added-art export gate") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the add must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + // Two opaque layers keyed the way a PSD keys them, so the export writes Photoshop ids and the + // reopened file keys them stably. + val layerA = InMemoryLayer("lyid:9001", "Added A", 0, LayerBounds(10, 20, 24, 16), solidRaster(24, 16, 0x5A)) + val layerB = InMemoryLayer("lyid:9002", "Added B", 1, LayerBounds(40, 60, 12, 12), solidRaster(12, 12, 0x3C)) + val art = InMemoryArt(listOf(layerA, layerB), before.canvasWidth.toInt(), before.canvasHeight.toInt()) + val request = AddArtworkRequest(art, ArtSourceDescriptor("added.psd", "/art/added.psd", "psd"), SourceArtImportOptions()) + assertTrue(runAddArtwork(host, request, areaId = null), "the artwork is added") + val grown = session.model.value + val added = grown.sources.first { source -> source.name == "added.psd" } + val addedTiles = grown.atlas.tiles.filter { tile -> tile.source?.sourceId == added.id } + assertEquals(2, addedTiles.size) + val addedDrawables = grown.drawables.filter { drawable -> drawable.atlasTileId in addedTiles.map { tile -> tile.id }.toSet() } + assertEquals(2, addedDrawables.size, "one drawable per added layer") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== grown.atlas) { + yield() + } + } + val effective = sessionAtlasPages.binding.value.textures + assertNotSame(document.textures, effective, "the resolver published the add's pages") + + val prepared = + prepareCmo3Export( + document = document, + edited = exportedModelFor(document, session), + effectiveTextures = effective, + modelName = "gate", + nowMillis = 0L, + obfuscateKey = 0, + ) + follower.cancel() + println("export report: ${prepared.report}") + for (reason in listOf(ExportNoticeReason.AtlasPageNotRecomposed, ExportNoticeReason.CreatedDrawableHasNoTextureSource, ExportNoticeReason.AtlasTileMetadataNotReconcilable)) { + assertTrue(prepared.report.notices.none { notice -> notice is ExportNotice.UnsupportedChange && notice.reason == reason }, "the added art reconciled without $reason") + } + val exportedBytes = Cmo3.write(prepared.model) + + // Read back: the file, its layers under their keys with their rects and pixels, the tiles, + // and the drawables. + val reread = Cmo3.read(exportedBytes) + val rereadRoot = reread.root as CModelSource + val ingest = cmo3AtlasIngest(rereadRoot) + val rereadAdded = assertNotNull(ingest.sources.firstOrNull { source -> source.name == "added.psd" }, "the added file is a layered image: ${ingest.sources.map { source -> source.name }}") + assertEquals("/art/added.psd", rereadAdded.path) + assertEquals(listOf("lyid:9001", "lyid:9002"), rereadAdded.layers.map { layer -> layer.key }) + assertEquals(listOf(10, 20, 24, 16), rereadAdded.layers[0].let { layer -> listOf(layer.left, layer.top, layer.width, layer.height) }) + val rereadTiles = ingest.atlas.tiles.filter { tile -> tile.source?.sourceId == rereadAdded.id } + assertEquals(2, rereadTiles.size, "one tile per added layer") + assertTrue(rereadTiles.all { tile -> tile.placement != null && tile.source?.stableKey == true }, "both tiles are placed and keyed stably") + val rereadArt = assertNotNull(cmo3SourceArtOf(rereadRoot, rereadAdded.id) { resource -> reread.extractLayerPng(resource) }) + assertContentEquals(layerA.raster.rgba, assertNotNull(rereadArt.layers.firstOrNull { layer -> layer.id.raw == "lyid:9001" }).raster.rgba, "the first layer's pixels read back") + assertContentEquals(layerB.raster.rgba, assertNotNull(rereadArt.layers.firstOrNull { layer -> layer.id.raw == "lyid:9002" }).raster.rgba) + // The added drawables carry thumbnails of their art, one 32px and one 16px entry each. + val rereadMeshes = graphElements((rereadRoot.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + for (drawable in addedDrawables) { + val mesh = assertNotNull(rereadMeshes.firstOrNull { candidate -> (candidate.id as? Id)?.idstr == drawable.id.raw }, "${drawable.name} is written") + for ((icon, size) in listOf(mesh.icon32 to 32, mesh.icon16 to 16)) { + val path = assertNotNull(((icon as? CImageIcon)?.image as? CWritableImage)?.image?.archivePath, "${drawable.name} has a ${size}px icon") + val decoded = PngCodec.read(assertNotNull(reread.archive.byPath(path), "icon '$path' is embedded").content) + assertEquals(size to size, decoded.width to decoded.height) + assertTrue((0 until decoded.width * decoded.height).any { pixel -> (decoded.rgba[pixel * 4 + 3].toInt() and 0xFF) == 255 }, "${drawable.name}'s ${size}px icon shows its opaque art") + } + } + val reimported = Cmo3Import.fromModelSource(rereadRoot) + for (drawable in addedDrawables) { + val back = assertNotNull(reimported.drawables.firstOrNull { candidate -> candidate.id == drawable.id }, "${drawable.name} re-imports") + assertContentEquals(drawable.mesh?.uvs, back.mesh?.uvs, "${drawable.name} uvs are verbatim") + val key = grown.atlas.tileById.getValue(assertNotNull(drawable.atlasTileId)).source?.layerKey + val boundTile = assertNotNull(ingest.tileIdByDrawableId[drawable.id.raw]?.let { tileId -> ingest.atlas.tileById[tileId] }, "${drawable.name} binds to a tile") + assertEquals(key, boundTile.source?.layerKey, "${drawable.name} binds to its layer's tile") + } + + // Reopened through the loader, an unedited re-export is the byte-identical no-op every + // unedited CMO3 passes. + val reopenedLoad = loadDocument(exportedBytes, "gate.cmo3", "/art/gate.cmo3") + val reopened = assertIs(assertIs(reopenedLoad).document) + assertTrue(reopened.puppet.atlas.tiles.filter { tile -> tile.source?.sourceId?.raw == rereadAdded.id.raw }.all { tile -> tile.source?.stableKey == true }, "the added tiles reopen bound by key") + val identity = prepareCmo3Export(reopened, reopened.puppet, reopened.textures, "gate", 0L, 0) + assertTrue(identity.report.isEmpty, "an unedited re-export owes nothing: ${identity.report.notices}") + val sourceMainXml = CaffCodec.read(exportedBytes).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + val reemittedMainXml = CaffCodec.read(Cmo3.write(identity.model)).firstByTag(CaffArchive.TAG_MAIN_XML)!!.content + assertContentEquals(sourceMainXml, reemittedMainXml, "main.xml survives the reopen byte-identical") + } + + /** + * A CMO3 collection field as its elements, whichever container shape the serializer used. + * + * @param Any? collection The raw field. + * @return List The elements. + */ + private fun graphElements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ArtDocumentLoadTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ArtDocumentLoadTest.kt new file mode 100644 index 0000000..9d60dda --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ArtDocumentLoadTest.kt @@ -0,0 +1,229 @@ +package org.umamo.ui.document + +import org.umamo.edit.seed.HumanoidParameters +import org.umamo.format.binary.contentHashOf +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.gen.KeyformGridSource +import org.umamo.format.png.PngCodec +import org.umamo.interop.ExportNotice +import org.umamo.interop.art.SourceArtImportNotice +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasIngest +import org.umamo.interop.cmo3.cmo3SourceArtOf +import org.umamo.render.deriveAtlasTextures +import org.umamo.runtime.model.ParameterNode +import org.umamo.ui.model.DrawableThumbnailer +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * End-to-end open of a real layered PSD through [loadDocument] into [buildArtDocument]: the bridge, + * the pack at open, and the document's page set, then the CMO3 export the shell would run on it. + * + * Two things only a real file proves. The pages the pack composed at open must equal the pages + * [deriveAtlasTextures] composes from the packed model - the derivation is what undo and the resolver + * rebuild from, so a difference there is a viewport that changes when nothing was edited. And the + * fresh-graph export must re-import to the same rig, which is the promise that an artwork-origin + * document is shippable from the moment it opens. + * + * Reads `psd.sample` (defaulted to the local corpus by the build) and self-skips without it. + */ +class ArtDocumentLoadTest { + private val sample: File? = System.getProperty("psd.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aCorpusPsdOpensPackedAndExportsToARigThatReimports() { + val file = sample + if (file == null) { + println("psd.sample not present; skipping the artwork document gate") + return + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val puppet = document.puppet + for (notice in document.importNotices) { + println("import note: $notice") + } + + assertTrue(puppet.drawables.isNotEmpty(), "the PSD has layers to rig") + assertEquals(contentHashOf(file.readBytes()), puppet.sources.single().contentHash, "the source records the whole-file hash the watcher compares against") + assertEquals(HumanoidParameters.list, puppet.parameters, "the default template seeds the humanoid set") + assertTrue(puppet.rendersFromSourceLayers, "a fresh import shows the layers as drawn") + assertTrue(puppet.atlas.pages.isNotEmpty(), "the pack at open produced pages") + assertEquals(puppet.atlas.pages.size, document.textures.atlases.size, "one composed page per model page") + + // Every bound tile is either on a page or named in the notes - never silently unpacked. + val notedUnpacked = + document.importNotices.mapNotNull { notice -> + when (notice) { + is SourceArtImportNotice.LayerLargerThanPage -> notice.layerName + is SourceArtImportNotice.LayerNotPacked -> notice.layerName + else -> null + } + }.toSet() + for (drawable in puppet.drawables) { + val tile = assertNotNull(puppet.atlas.tileById[assertNotNull(drawable.atlasTileId)]) + val placement = tile.placement + if (placement == null) { + assertTrue(tile.name in notedUnpacked, "unpacked tile '${tile.name}' is named in the import notes") + } else { + assertTrue(placement.pageIndex in puppet.atlas.pages.indices, "tile '${tile.name}' sits on a page the model has") + assertEquals(placement.pageIndex, document.textures.atlasIndexByDrawableId[drawable.id.raw], "the renderer's page map agrees") + } + assertNotNull(document.artRasters.rasterFor(tile.id), "tile '${tile.name}' has its pixels") + } + + // The pack's pages ARE the derivation's pages, byte for byte. + val derived = assertNotNull(deriveAtlasTextures(puppet, document.artRasters, premultipliedAlpha = false), "the packed model derives") + assertEquals(document.textures.atlases.size, derived.atlases.size, "derived page count") + for ((pageIndex, page) in document.textures.atlases.withIndex()) { + val derivedPage = derived.atlases[pageIndex] + assertEquals(page.width, derivedPage.width, "page $pageIndex width") + assertEquals(page.height, derivedPage.height, "page $pageIndex height") + assertTrue(page.rgba.contentEquals(derivedPage.rgba), "page $pageIndex composed at open differs from its derivation") + } + + // The fresh-graph export re-imports to the same rig. + val modelThumbnail = assertNotNull(DrawableThumbnailer(puppet, document.textures).modelRasterFor(), "the outliner composite exists for the model icon") + val prepared = + prepareCmo3Export( + document = document, + edited = puppet, + effectiveTextures = document.textures, + modelName = "gate", + nowMillis = 0L, + obfuscateKey = 0, + modelThumbnail = modelThumbnail, + ) + assertTrue(prepared.report.notices.none { notice -> notice is ExportNotice.MissingSourceArt }, "the export writes the real source art: ${prepared.report.notices}") + val exportedBytes = Cmo3.write(prepared.model) + val reread = Cmo3.read(exportedBytes) + val rereadRoot = reread.root as CModelSource + + // Every exported art mesh carries a keyform grid with its default cell. The official editor + // refuses a mesh without one (setKeyformGridSource rejects null, getDefaultKeyForm throws "no + // KeyForms"), and every drawable born from artwork is unkeyed - so this is the line between a + // file that opens in Cubism and one that fills its log and crashes. + val artMeshes = graphElements((rereadRoot.drawableSourceSet as? CDrawableSourceSet)?._sources).filterIsInstance() + assertEquals(puppet.drawables.size, artMeshes.size, "one art mesh per drawable in the written graph") + for (artMesh in artMeshes) { + val gridSource = assertNotNull(artMesh.keyformGridSource as? KeyformGridSource, "art mesh '${artMesh.localName}' has a keyform grid") + assertTrue(graphElements(gridSource.keyformsOnGrid).isNotEmpty(), "art mesh '${artMesh.localName}' grid has its default cell") + assertTrue(graphElements(artMesh.keyforms).isNotEmpty(), "art mesh '${artMesh.localName}' has a default form") + } + + // The model's own icon is the rest-pose composite: not blank, and shaped like the drawn model + // (the union of the visible drawables' rest bounds), which the layered-image frame is not. + val modelIconPath = assertNotNull(((rereadRoot._icon64 as? CImageIcon)?.image as? CWritableImage)?.image?.archivePath, "the model has a 64px icon") + val modelIcon = PngCodec.read(assertNotNull(reread.archive.byPath(modelIconPath), "the model icon is embedded").content) + assertEquals(64 to 64, modelIcon.width to modelIcon.height) + var iconMinX = 64 + var iconMaxX = -1 + var iconMinY = 64 + var iconMaxY = -1 + for (y in 0 until 64) { + for (x in 0 until 64) { + if ((modelIcon.rgba[(y * 64 + x) * 4 + 3].toInt() and 0xFF) > 0) { + iconMinX = minOf(iconMinX, x) + iconMaxX = maxOf(iconMaxX, x) + iconMinY = minOf(iconMinY, y) + iconMaxY = maxOf(iconMaxY, y) + } + } + } + assertTrue(iconMaxX >= 0, "the model icon is not blank") + val iconAspect = (iconMaxX - iconMinX + 1).toFloat() / (iconMaxY - iconMinY + 1) + val thumbnailAspect = modelThumbnail.width.toFloat() / modelThumbnail.height + assertTrue(abs(iconAspect - thumbnailAspect) <= thumbnailAspect * 0.1f, "the icon is shaped like the rest-pose composite: $iconAspect vs $thumbnailAspect") + val reimported = Cmo3Import.fromModelSource(rereadRoot) + // Compared by id, not by list position: a CMO3's storage order is not the panel order (the org + // tree is), and the ids are what the export writes and the re-import reads back. + val rereadById = reimported.drawables.associateBy { drawable -> drawable.id } + assertEquals(puppet.drawables.map { drawable -> drawable.id }.toSet(), rereadById.keys, "the same drawables come back") + assertEquals( + puppet.parts.associate { part -> part.id to part.name }, + reimported.parts.associate { part -> part.id to part.name }, + "the same parts come back, named the same", + ) + assertEquals(puppet.rootChildren, reimported.rootChildren, "the org tree's root keeps its order") + assertEquals(puppet.parameters.map { parameter -> parameter.id }, reimported.parameters.map { parameter -> parameter.id }, "the seeded parameters") + // Every parameter sits in the written group hierarchy: the editor logs a recovery for each one it + // finds outside it, and the re-import builds this tree from that hierarchy alone. + assertEquals( + puppet.parameters.map { parameter -> ParameterNode.Param(parameter.id) }, + reimported.parameterTree, + "every seeded parameter is in the root parameter group, in order", + ) + assertEquals(puppet.atlas.pages, reimported.atlas.pages, "the page inventory") + for (drawable in puppet.drawables) { + val expected = assertNotNull(drawable.mesh) + val reread = assertNotNull(rereadById[drawable.id], "${drawable.name} re-imports") + assertEquals(drawable.name, reread.name, "${drawable.id.raw} keeps its name") + val actual = assertNotNull(reread.mesh, "${drawable.name} keeps its mesh") + assertEquals(expected.vertexCount, actual.vertexCount, "${drawable.name} vertex count") + for (componentIndex in expected.uvs.indices) { + assertEquals(expected.uvs[componentIndex], actual.uvs[componentIndex], 1e-4f, "${drawable.name} uv component $componentIndex") + assertEquals(expected.positions[componentIndex], actual.positions[componentIndex], 1e-2f, "${drawable.name} position component $componentIndex") + } + } + // The written web is the real art: the file's record, every layer under its key with its canvas + // rect, every tile's placement, and every layer's pixels. + val ingest = cmo3AtlasIngest(rereadRoot) + val source = puppet.sources.single() + val rereadSource = ingest.sources.single() + assertEquals(source.name, rereadSource.name, "the layered image is the file") + assertEquals(source.path, rereadSource.path, "with its path") + assertEquals(source.lastModified, rereadSource.lastModified, "and its modification time") + val rowsByKey = source.layers.associateBy { row -> row.key } + assertTrue(rereadSource.layers.isNotEmpty(), "the layers came back") + for (row in rereadSource.layers) { + val original = assertNotNull(rowsByKey[row.key], "layer '${row.name}' comes back under its key") + assertEquals(listOf(original.left, original.top, original.width, original.height), listOf(row.left, row.top, row.width, row.height), "'${row.name}' keeps its canvas rect") + } + val rereadTileByKey = ingest.atlas.tiles.associateBy { tile -> tile.source?.layerKey } + for (tile in puppet.atlas.tiles) { + val key = assertNotNull(tile.source?.layerKey) + val rereadTile = assertNotNull(rereadTileByKey[key], "tile '${tile.name}' comes back bound to its layer") + assertEquals(tile.placement, rereadTile.placement, "'${tile.name}' keeps its placement") + assertEquals(tile.width to tile.height, rereadTile.width to rereadTile.height, "'${tile.name}' keeps its size") + } + val rereadArt = assertNotNull(cmo3SourceArtOf(rereadRoot, rereadSource.id) { resource -> reread.extractLayerPng(resource) }, "the layers read back as source art") + for (tile in puppet.atlas.tiles) { + val layer = rereadArt.layers.first { layer -> layer.id.raw == tile.source?.layerKey } + val original = assertNotNull(document.artRasters.rasterFor(tile.id)) + assertEquals(original.width to original.height, layer.raster.width to layer.raster.height, "'${tile.name}' pixels are the tile's") + assertTrue(original.rgba.contentEquals(layer.raster.rgba), "'${tile.name}' pixels round-trip byte for byte") + } + + // The export reopens as a CMO3-origin document whose bindings are the stable keys the PSD + // reader mints, so a reload against the PSD lands by key - the reopen-then-refresh promise. + val reopened = assertIs(assertIs(loadDocument(exportedBytes, "gate.cmo3", "/art/gate.cmo3")).document) + assertEquals(puppet.atlas.tiles.size, reopened.puppet.atlas.tiles.size, "one tile per layer on reopen") + assertTrue(reopened.puppet.atlas.tiles.all { tile -> tile.source?.stableKey == true }, "every reopened binding is a stable key") + println("artwork gate: ${puppet.drawables.size} drawables, ${puppet.parts.size} parts, ${puppet.atlas.pages.size} page(s), ${document.importNotices.size} note(s)") + } + + /** + * A CMO3 collection field as its elements, whichever container shape the serializer used. + * + * @param Any? collection The raw field. + * @return List The elements. + */ + private fun graphElements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/BlankDocumentTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/BlankDocumentTest.kt new file mode 100644 index 0000000..13402e8 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/BlankDocumentTest.kt @@ -0,0 +1,68 @@ +package org.umamo.ui.document + +import org.umamo.edit.EditorSession +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * What the editor opens into, and what File > New makes. + * + * Three of these pin decisions that are invisible until they are wrong. A new document must be CLEAN, + * or the quit guard asks about work nobody did and the first Ctrl+N of a session prompts for nothing. + * It must carry a canvas, because the viewport, the properties panel, and an export all read one and a + * 0x0 rig has no frame to draw. And its raster store must be its own: artwork decodes into whatever + * store the document hands the import, so a shared one would carry this document's art into the next. + */ +class BlankDocumentTest { + @Test + fun aNewDocumentIsEmptyInEveryList() { + val document = newBlankDocument() + + assertNull(document.path, "a document that was never saved has no file") + assertEquals(UNTITLED_DOCUMENT_NAME, document.displayName) + val puppet = document.puppet + assertTrue(puppet.drawables.isEmpty(), "no drawables") + assertTrue(puppet.parts.isEmpty(), "no parts") + assertTrue(puppet.deformers.isEmpty(), "no deformers") + assertTrue(puppet.rootChildren.isEmpty(), "nothing in the organizational tree") + assertTrue(puppet.atlas.tiles.isEmpty(), "no art on the atlas") + assertTrue(puppet.sources.isEmpty(), "no artwork files behind it") + assertTrue( + puppet.parameters.isEmpty(), + "and no parameters - the template seeds on the first artwork imported, not on the empty document", + ) + assertTrue(document.textures.atlases.isEmpty(), "no atlas pages") + } + + @Test + fun aNewDocumentHasACanvasWithTheOriginAtItsCenter() { + val puppet = newBlankDocument().puppet + + assertEquals(BLANK_DOCUMENT_CANVAS_SIZE, puppet.canvasWidth) + assertEquals(BLANK_DOCUMENT_CANVAS_SIZE, puppet.canvasHeight) + // World space negates canvas y, so the center sits at (w/2, -h/2) - what every import computes. + assertEquals(BLANK_DOCUMENT_CANVAS_SIZE / 2f, puppet.worldOriginX) + assertEquals(-(BLANK_DOCUMENT_CANVAS_SIZE / 2f), puppet.worldOriginZ) + } + + @Test + fun aNewDocumentStartsClean() { + val document = newBlankDocument() + + val session = EditorSession(document.puppet, document.liveParams.values) + + assertFalse(session.dirty.value, "nothing has been edited yet, so quitting must not ask") + } + + @Test + fun eachNewDocumentBringsItsOwnRasterStore() { + val first = newBlankDocument() + val second = newBlankDocument() + + assertNotSame(first.artRasters, second.artRasters, "two documents never share the store artwork decodes into") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Cmo3DocumentLoadTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Cmo3DocumentLoadTest.kt new file mode 100644 index 0000000..6e5061c --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Cmo3DocumentLoadTest.kt @@ -0,0 +1,48 @@ +package org.umamo.ui.document + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * End-to-end load of a real `.cmo3` through [loadDocument] into [buildCmo3Document], the counterpart + * to [Moc3DocumentLoadTest]'s family check. The failure paths are covered synthetically in + * [DocumentLoadTest]; what this adds is the one thing fake bytes cannot prove - that a genuine + * corpus model comes out with its embedded atlas decoded and bound to real drawables. + * + * That binding is what the atlas walk exists to produce, and a real model is the only thing that can + * exercise it: synthetic bytes carry no embedded pages to decode. Reads the corpus sample + * (`-Dcmo3.sample`, defaulted to the local corpus by the build) and self-skips without it, so CI + * stays green on a fresh clone. + */ +class Cmo3DocumentLoadTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aCorpusModelLoadsWithItsEmbeddedAtlasBound() { + val file = sample ?: return + val load = loadDocument(file.readBytes(), file.name, file.path) + + val document = assertIs(assertIs(load).document) + assertTrue(document.puppet.drawables.isNotEmpty(), "the corpus model has drawables") + + // A CMO3 embeds its pixels, so a successful open must yield at least one decoded page - an empty + // atlas list here is the silent failure mode (every drawable would render in fallback color, and + // nothing else in the load path would complain). + val textures = document.textures + assertTrue(textures.atlases.isNotEmpty(), "at least one atlas page decoded") + for (page in textures.atlases) { + assertTrue(page.width > 0 && page.height > 0, "page has real dimensions") + assertEquals(page.width * page.height * 4, page.rgba.size, "RGBA8888, tightly packed") + } + + // Every mapped drawable must resolve to a page the renderer can actually index: PuppetRenderer + // looks pages up by direct list indexing, so a stale index is a first-frame crash. + assertTrue(textures.atlasIndexByDrawableId.isNotEmpty(), "drawables are bound to pages") + for ((drawableId, pageIndex) in textures.atlasIndexByDrawableId) { + assertTrue(pageIndex in textures.atlases.indices, "$drawableId points at a decoded page") + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ConvertedRepackGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ConvertedRepackGateTest.kt new file mode 100644 index 0000000..814e5a8 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ConvertedRepackGateTest.kt @@ -0,0 +1,321 @@ +package org.umamo.ui.document + +import org.umamo.edit.withAtlasRepack +import org.umamo.format.art.analyzeAlpha +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.packAtlas +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.Cmo3Model +import org.umamo.format.cmo3.model.custom.CModelImage +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.gen.CArtMeshSource +import org.umamo.format.cmo3.model.gen.CDrawableSourceSet +import org.umamo.format.cmo3.model.gen.CModelImageGroup +import org.umamo.format.cmo3.model.gen.CTextureAtlas +import org.umamo.format.cmo3.model.gen.CTextureInputExtension +import org.umamo.format.cmo3.model.gen.CTextureInput_ModelImage +import org.umamo.format.cmo3.model.gen.CTextureInput_TextureAtlasRegion +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.GTexture2D +import org.umamo.format.cmo3.model.gen.ModelImageEntry +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.cmo3.model.identity.Id +import org.umamo.format.cmo3.model.type.CAffine +import org.umamo.format.png.PngCodec +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasIngest +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import org.umamo.render.atlasPlacementFromPack +import org.umamo.render.generatedPuppetTextures +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import org.umamo.runtime.model.atlasPixelOf +import org.umamo.ui.model.buildRepackPackInput +import org.umamo.ui.model.repackRefusals +import org.umamo.ui.viewport.initialLiveParams +import java.io.File +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The converted-repack export gate, end to end on the modelG corpus fixture: a MOC3-origin + * conversion with five pages repacks (consolidating pages, moving most tiles across them) and + * exports through the SHIPPED policy; the re-read file must be exactly as consistent as the + * original import. + * + * This is the modelG bug's regression net: before the atlas-web reconcile, this pipeline wrote new + * placements and coordinates against old page membership and old images, and the reimport showed a + * quarter of the drawables displaced. The saved artifact recording that state lives OUTSIDE the + * golden glob (test/corpus/cmo3/invalid/), because it fails the corpus invariants by nature. + * + * Skips without the fixture. + */ +class ConvertedRepackGateTest { + private val sample: File? = System.getProperty("cmo3.repackSample")?.let(::File)?.takeIf { it.isFile } + + private class JumbleStats( + val displacedDrawables: Int, + val checkedDrawables: Int, + ) + + /** How many bound drawables' uv bboxes miss their own tile's trim rect on the page. */ + private fun jumbleStats(model: PuppetModel, decodeRaster: (AtlasTileId) -> DecodedImage?): JumbleStats { + val tileById = model.atlas.tiles.associateBy { tile -> tile.id } + val trimByTile = HashMap() + var displaced = 0 + var checked = 0 + for (drawable in model.drawables) { + val tileId = drawable.atlasTileId ?: continue + val tile = tileById[tileId] ?: continue + val placement = tile.placement ?: continue + val page = model.atlas.pages.getOrNull(placement.pageIndex) ?: continue + val uvs = drawable.mesh?.uvs ?: continue + if (uvs.size < 2) { + continue + } + val trim = + trimByTile.getOrPut(tileId) { + decodeRaster(tileId)?.let { raster -> + analyzeAlpha(raster.width, raster.height, raster.rgba)?.opaqueBounds?.let { bounds -> + floatArrayOf( + placement.positionX + bounds.left, + placement.positionY + bounds.top, + placement.positionX + bounds.left + bounds.width, + placement.positionY + bounds.top + bounds.height, + ) + } + } + } ?: continue + var minU = Float.MAX_VALUE + var maxU = -Float.MAX_VALUE + var minV = Float.MAX_VALUE + var maxV = -Float.MAX_VALUE + var componentIndex = 0 + while (componentIndex + 1 < uvs.size) { + minU = min(minU, uvs[componentIndex]) + maxU = max(maxU, uvs[componentIndex]) + minV = min(minV, uvs[componentIndex + 1]) + maxV = max(maxV, uvs[componentIndex + 1]) + componentIndex += 2 + } + checked++ + val left = minU * page.width + val top = minV * page.height + val right = maxU * page.width + val bottom = maxV * page.height + val intersectWidth = min(right, trim[2]) - max(left, trim[0]) + val intersectHeight = min(bottom, trim[3]) - max(top, trim[1]) + val bboxArea = max(1f, (right - left) * (bottom - top)) + val overlap = + if (intersectWidth > 0f && intersectHeight > 0f) intersectWidth * intersectHeight / bboxArea else 0f + if (overlap < 0.25f) { + displaced++ + } + } + return JumbleStats(displaced, checked) + } + + /** Flattens a CMO3 collection field, held as `Any?` by the serializer. */ + private fun elementsOf(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + private fun decodeRasterOf(cmo3: Cmo3Model): (AtlasTileId) -> DecodedImage? { + val ingest = cmo3AtlasIngest(cmo3.root as CModelSource) + return { tileId -> + ingest.imageResourceByTile[tileId]?.let(cmo3::extractLayerPng)?.let { bytes -> + val image = PngCodec.read(bytes) + DecodedImage(image.rgba, image.width, image.height) + } + } + } + + @Test + fun aConvertedRepackExportRoundTripsConsistently() { + val file = sample + if (file == null) { + println("cmo3.repackSample not present; skipping the converted-repack export gate") + return + } + val cmo3 = Cmo3.read(file.readBytes()) + val imported = Cmo3Import.fromModelSource(cmo3.root as CModelSource) + assertTrue(imported.atlas.storedUvsAddressPages, "the fixture is page-addressed") + val baselineDecode = decodeRasterOf(cmo3) + val baselineJumble = jumbleStats(imported, baselineDecode) + + // The SHIPPED repack input, packed at the document's own page size. + val packInput = buildRepackPackInput(imported) { tileId -> baselineDecode(tileId) } + val options = + AtlasPackOptions(maxPageSize = imported.atlas.pages.maxOf { page -> max(page.width, page.height) }) + val packResult = packAtlas(packInput.items, options) + assertTrue( + repackRefusals(imported, packResult.skipped, packInput.undecodableTileIds).isEmpty(), + "the fixture must repack cleanly", + ) + val packedByKey = packResult.placements.associateBy { placement -> placement.key } + val placements = HashMap() + for (tile in imported.atlas.tiles) { + placements[tile.id] = packedByKey[tile.id.raw]?.let { packed -> atlasPlacementFromPack(packed) } + } + val repacked = + imported.withAtlasRepack(packResult.pages.map { page -> AtlasPage(page.width, page.height) }, placements) + assertTrue( + repacked.atlas.pages.size < imported.atlas.pages.size, + "the fixture's repack consolidates pages (the page-delete arm)", + ) + + // The SHIPPED export policy: the effective page set is the repack's own. + val effective = generatedPuppetTextures(packResult.pages, repacked, premultipliedAlpha = false) + val probeDocument = + Cmo3Document( + path = file.path, + cmo3 = cmo3, + puppet = imported, + textures = PuppetTextures(emptyList(), emptyMap(), premultipliedAlpha = false), + artRasters = org.umamo.render.SourceArtRasters { null }, + liveParams = initialLiveParams(imported), + ) + val prepared = prepareCmo3Export(probeDocument, repacked, effective, "modelG", 0L, 0x5A17E5) + assertFalse( + prepared.report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && + ( + notice.reason == ExportNoticeReason.AtlasPageNotRecomposed || + notice.reason == ExportNoticeReason.NoAtlasEntryToReconcile + ) + }, + "the full reconcile owes no atlas notice: ${prepared.report.notices}", + ) + val exportedBytes = Cmo3.write(prepared.model) + File("build/modelG-repacked-export.cmo3").apply { parentFile?.mkdirs() }.writeBytes(exportedBytes) + val rereadCmo3 = Cmo3.read(exportedBytes) + val rereadSource = rereadCmo3.root as CModelSource + val reimported = Cmo3Import.fromModelSource(rereadSource) + + // The reimport reads the repack's own page set and every placement, and stays page-addressed. + assertEquals(repacked.atlas.pages, reimported.atlas.pages, "the page set follows the repack") + assertTrue(reimported.atlas.storedUvsAddressPages) + var placementMismatches = 0 + for (tile in repacked.atlas.tiles) { + val reread = reimported.atlas.tiles.firstOrNull { candidate -> candidate.id == tile.id } + if (reread?.placement != tile.placement) { + placementMismatches++ + } + } + assertEquals(0, placementMismatches, "every placement round-trips") + + // The jumble metric is back at the baseline: the export is exactly as consistent as the import. + val rereadJumble = jumbleStats(reimported, decodeRasterOf(rereadCmo3)) + assertEquals(baselineJumble.checkedDrawables, rereadJumble.checkedDrawables, "every mapping still checks") + assertEquals( + baselineJumble.displacedDrawables, + rereadJumble.displacedDrawables, + "the reimport shows no displacement beyond the import's own baseline", + ) + + // The composition invariant holds for EVERY re-read entry, non-pure canvas affines included. + // CMO3: CModelSource field textureManager -> CTextureManager fields _textureAtlases / + // _modelImageGroups. + val textureManager = rereadSource.textureManager as CTextureManager + val canvasByGuid = HashMap() + for (group in elementsOf(textureManager._modelImageGroups).filterIsInstance()) { + for (modelImage in elementsOf(group._modelImages).filterIsInstance()) { + val uuid = (modelImage.guid as? Guid)?.uuid ?: continue + (modelImage._materialLocalToCanvasTransform as? CAffine)?.let { canvas -> canvasByGuid[uuid] = canvas } + } + } + val atlases = elementsOf(textureManager._textureAtlases).filterIsInstance() + val placementByTileId = + reimported.atlas.tiles.associateBy({ tile -> tile.id.raw }, { tile -> tile.placement }) + var compositionChecks = 0 + for (atlas in atlases) { + for (entry in elementsOf(atlas.modelImages).filterIsInstance()) { + val uuid = (entry.modelImageGuid as? Guid)?.uuid ?: continue + val placement = placementByTileId[uuid] ?: continue + val canvas = canvasByGuid[uuid] ?: continue + val entryHalf = entry.atlasLocalToCanvasTransform as? CAffine ?: continue + for ((probeX, probeY) in listOf(0f to 0f, 137f to 0f, 0f to 251f)) { + val onPage = atlasPixelOf(placement, probeX, probeY) + val composedX = entryHalf.m00 * onPage[0] + entryHalf.m01 * onPage[1] + entryHalf.m02 + val composedY = entryHalf.m10 * onPage[0] + entryHalf.m11 * onPage[1] + entryHalf.m12 + val declaredX = canvas.m00 * probeX + canvas.m01 * probeY + canvas.m02 + val declaredY = canvas.m10 * probeX + canvas.m11 * probeY + canvas.m12 + assertTrue( + abs(composedX - declaredX) < 1e-1f && abs(composedY - declaredY) < 1e-1f, + "entry $uuid: composition ($composedX, $composedY) vs canvas ($declaredX, $declaredY)" + + " at ($probeX, $probeY)", + ) + } + compositionChecks++ + } + } + assertTrue(compositionChecks > 100, "the composition invariant actually ran ($compositionChecks entries)") + + // Drawable page-consistency, zero disagreements: the sampled resource, the region's atlas + // guid, and the entry's membership all name the same page. + val atlasIndexByGuidUuid = HashMap() + val atlasIndexByResource = java.util.IdentityHashMap() + val atlasIndexByEntryGuid = HashMap() + for ((atlasIndex, atlas) in atlases.withIndex()) { + (atlas.guid as? Guid)?.uuid?.let { uuid -> atlasIndexByGuidUuid[uuid] = atlasIndex } + atlas.cachedAtlasImage?.let { resource -> atlasIndexByResource[resource] = atlasIndex } + for (entry in elementsOf(atlas.modelImages).filterIsInstance()) { + (entry.modelImageGuid as? Guid)?.uuid?.let { uuid -> atlasIndexByEntryGuid[uuid] = atlasIndex } + } + } + var consistencyChecks = 0 + var disagreements = 0 + val artMeshes = + elementsOf((rereadSource.drawableSourceSet as? CDrawableSourceSet)?._sources) + .filterIsInstance() + for (mesh in artMeshes) { + val extension = + elementsOf(mesh._extensions).filterIsInstance().firstOrNull() ?: continue + val region = + elementsOf(extension._textureInputs) + .filterIsInstance() + .firstOrNull() ?: continue + val tileUuid = + ( + elementsOf(extension._textureInputs) + .filterIsInstance() + .firstOrNull() + ?._modelImageGuid as? Guid + )?.uuid ?: continue + val entryPage = atlasIndexByEntryGuid[tileUuid] ?: continue + val guidPage = (region.textureAtlasGuid as? Guid)?.uuid?.let(atlasIndexByGuidUuid::get) + val resourcePage = (mesh.texture as? GTexture2D)?.srcImageResource?.let(atlasIndexByResource::get) + consistencyChecks++ + if (guidPage != entryPage || resourcePage != entryPage) { + disagreements++ + if (disagreements <= 5) { + println( + "[repack-gate] '${(mesh.id as? Id)?.idstr}' pages disagree:" + + " entry=$entryPage guid=$guidPage resource=$resourcePage", + ) + } + } + } + println( + "[repack-gate] ${reimported.atlas.pages.size} page(s), jumble ${rereadJumble.displacedDrawables}/" + + "${rereadJumble.checkedDrawables} (baseline ${baselineJumble.displacedDrawables}), " + + "$compositionChecks compositions, $consistencyChecks drawables page-checked", + ) + assertTrue(consistencyChecks > 100, "the page-consistency walk actually ran") + assertEquals(0, disagreements, "every drawable's three page references agree") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentFileTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentFileTest.kt new file mode 100644 index 0000000..dffd779 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentFileTest.kt @@ -0,0 +1,121 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pins what a quit or a document replace does about a save that is still being written: it waits. + * + * The write runs on a background thread the process does not wait for, so an exit that goes ahead + * mid-save kills it - the file never lands and a partial temporary is left on disk. Nothing about the + * document stops that on its own, because an import that was never edited is clean, with nothing unsaved + * to ask about. So the wait is the guard, and these are its four outcomes. + * + * Also pins the name an export suggests, which follows where the document saves. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DocumentFileTest { + @Test + fun withNoSaveInFlightTheActionRunsAtOnce() = + runTest { + val file = DocumentFile(newBlankDocument()) + var waitCount = 0 + var actionCount = 0 + + file.afterPendingSave(this, onWaiting = { waitCount++ }, action = { actionCount++ }) + + assertEquals(1, actionCount) + assertEquals(0, waitCount, "with nothing to wait for, nobody is told to wait") + } + + @Test + fun anActionWaitsForTheSaveInFlightAndRunsOnceItLands() = + runTest { + val file = DocumentFile(newBlankDocument()) + val save = CompletableDeferred() + file.saveJob = save + var waitCount = 0 + var actionCount = 0 + + file.afterPendingSave(this, onWaiting = { waitCount++ }, action = { actionCount++ }) + runCurrent() + + assertEquals(1, waitCount, "the rigger is told the quit is waiting") + assertEquals(0, actionCount, "and nothing ends the process while the file is being written") + + save.complete(true) + runCurrent() + + assertEquals(1, actionCount, "the file landed, so the action goes on") + } + + @Test + fun aSaveThatFailsAbandonsTheActionThatWaitedOnIt() = + runTest { + val file = DocumentFile(newBlankDocument()) + val save = CompletableDeferred() + file.saveJob = save + var actionCount = 0 + + file.afterPendingSave(this, action = { actionCount++ }) + save.complete(false) + runCurrent() + + assertEquals(0, actionCount, "the rigger asked for a file and did not get one; quitting is theirs to ask for again") + } + + @Test + fun aSaveThatAlreadyEndedHoldsNothingBack() = + runTest { + val file = DocumentFile(newBlankDocument()) + file.saveJob = CompletableDeferred(false) + var actionCount = 0 + + file.afterPendingSave(this, action = { actionCount++ }) + + assertEquals(1, actionCount, "a save that failed a while ago is not a save in flight") + } + + /** + * A document born from a file of [path], for the export-name cases: an artwork document over the blank + * document's empty rig, since only the path matters here. + * + * @param String path The origin file's path. + * @return DocumentFile The document's file holder. + */ + private fun fileFrom(path: String): DocumentFile { + val blank = newBlankDocument() + return DocumentFile(ArtDocument(path, blank.puppet, blank.textures, blank.artRasters, blank.liveParams, emptyList())) + } + + /** An export names itself after the file the document came from, minus whatever extension that carries. */ + @Test + fun anExportIsNamedAfterTheOriginFileWithoutItsExtension() { + assertEquals("hero", fileFrom("/art/hero.psd").exportBaseName, "never hero.psd.png") + assertEquals("Model", fileFrom("/rigs/Model.cmo3").exportBaseName) + assertEquals("Model", fileFrom("C:\\rigs\\Model.MOC3").exportBaseName) + assertEquals("v1.2 sketch", fileFrom("/art/v1.2 sketch").exportBaseName, "a dot inside the name is not an extension") + } + + /** Once the document saves to a `.uma`, an export is named after that file instead. */ + @Test + fun anExportFollowsTheFileTheDocumentSavesTo() { + val file = fileFrom("/art/hero.psd") + file.umaPath = "/rigs/hero final.uma" + assertEquals("hero final", file.exportBaseName) + } + + /** A document never saved and born from no file has no name to suggest; the caller supplies the untitled one. */ + @Test + fun aNewDocumentHasNoExportName() { + val file = DocumentFile(newBlankDocument()) + assertNull(file.exportBaseName) + file.umaPath = "/rigs/hero.uma" + assertEquals("hero", file.exportBaseName, "its first Save As names it") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentLoadTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentLoadTest.kt new file mode 100644 index 0000000..e9a5c99 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentLoadTest.kt @@ -0,0 +1,73 @@ +package org.umamo.ui.document + +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull + +/** + * Failure classification of the byte-core document loader: each rejection path must report the + * matching [DocumentOpenError] (the shell's alert message key) instead of a bare null, so a failed + * open is always explainable to the user - plus the one success path synthetic bytes CAN prove, a + * flat raster opening as a rig. No corpus dependency. + */ +class DocumentLoadTest { + private fun pngOf(width: Int, height: Int, alpha: Int): ByteArray { + val rgba = ByteArray(width * height * 4) { index -> if (index % 4 == 3) alpha.toByte() else 0x40 } + return PngCodec.write(RasterImage(width, height, rgba)) + } + + /** A flat raster is a one-layer artwork: it opens as a rig with one drawable, packed at open. */ + @Test + fun aFlatRasterOpensAsAOneDrawableRig() { + val load = loadDocument(pngOf(4, 4, alpha = 0xFF), "hero.png", "hero.png") + val document = assertIs(assertIs(load).document) + val drawable = document.puppet.drawables.single() + assertEquals("hero.png", drawable.name, "the one drawable is named after the file") + assertNotNull(document.puppet.atlas.tiles.single().placement, "the pack at open placed the one tile") + assertEquals(1, document.textures.atlases.size, "and composed the page it sits on") + assertEquals("png", document.puppet.sources.single().format, "the source list records where it came from") + assertNotNull(document.artRasters.rasterFor(drawable.atlasTileId!!), "the layer's pixels are the document's art") + } + + /** A raster with no pixel over the threshold has nothing to rig; the open says so rather than opening blank. */ + @Test + fun aFullyTransparentRasterFailsAsNoArtLayers() { + val load = loadDocument(pngOf(4, 4, alpha = 0), "blank.png", "blank.png") + val failed = assertIs(load) + assertEquals(DocumentOpenError.NoArtLayers, failed.failure.error) + assertEquals("blank.png", failed.failure.displayName) + } + + @Test + fun unrecognizedBytesFailAsUnrecognized() { + val load = loadDocument(byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8), "mystery.bin", "mystery.bin") + val failed = assertIs(load) + assertEquals(DocumentOpenError.Unrecognized, failed.failure.error) + assertEquals("mystery.bin", failed.failure.displayName) + } + + @Test + fun recognizedNonEditorFormatFailsAsNotOpenable() { + // MOC3 header: magic "MOC3" @ +0x00. The BYTE-level loader keeps reporting MOC3 NotOpenable by + // design: sidecar discovery needs a directory, so only the file-level loadDocument(PlatformFile) + // routes a .moc3 to the sidecar loader (see Moc3DocumentLoadTest for that path). + val bytes = ByteArray(64) + "MOC3".encodeToByteArray().copyInto(bytes) + val load = loadDocument(bytes, "puppet.moc3", "puppet.moc3") + val failed = assertIs(load) + assertEquals(DocumentOpenError.NotOpenable, failed.failure.error) + } + + @Test + fun corruptCmo3FailsAsParseFailed() { + // CAFF magic @ +0x00 makes detection pick the CMO3 codec; the garbage tail makes its read throw. + val bytes = ByteArray(64) + "CAFF".encodeToByteArray().copyInto(bytes) + val load = loadDocument(bytes, "broken.cmo3", "broken.cmo3") + val failed = assertIs(load) + assertEquals(DocumentOpenError.ParseFailed, failed.failure.error) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentSwapRetentionTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentSwapRetentionTest.kt new file mode 100644 index 0000000..ecb98db --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DocumentSwapRetentionTest.kt @@ -0,0 +1,120 @@ +package org.umamo.ui.document + +import org.umamo.edit.EditorSession +import org.umamo.edit.ParameterChange +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.ui.model.DrawableThumbnailer +import org.umamo.ui.model.SessionAtlasPages +import java.io.File +import java.lang.ref.WeakReference +import kotlin.test.Test +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** How long to keep prodding the collector before declaring a reference leaked. */ +private const val GC_WAIT_MILLIS = 10_000L + +/** The pause between collection prods, so the poll loop is not a busy spin. */ +private const val GC_POLL_MILLIS = 50L + +/** + * A replaced document must become garbage: opening a new file drops the previous [Cmo3Document] + * (its retained CMO3 graph with every embedded PNG, the runtime puppet, the decoded atlas pages) + * and its [EditorSession] (the undo history) on the floor, and nothing static may keep any of it + * reachable. A single strongly-held reference here - a companion cache, a registry, a listener - + * pins tens to hundreds of megabytes per document swap, so this test IS the leak detector for the + * whole load-and-session layer. + * + * The shell's swap is mirrored without composition: the outgoing document gets the session, the + * undo step, the selection, the atlas page resolver, and the no-viewport thumbnailer a real open + * creates, then every strong reference is released while the incoming document stays held - exactly + * what EditorApp's onOpen does. Reads the corpus sample (`-Dcmo3.sample`, defaulted to the local + * corpus by the build) and self-skips without it, so CI stays green on a fresh clone. + */ +class DocumentSwapRetentionTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aReplacedDocumentAndItsSessionBecomeUnreachable() { + val file = sample ?: return + val replacedReferences = openUseAndRelease(file) + // The incoming document is held strongly across the whole check, as the shell holds its + // current document while the previous one is discarded. + val currentDocument = loadCmo3Document(file) + awaitCollection(replacedReferences) + for ((label, reference) in replacedReferences) { + assertNull(reference.get(), "$label is still strongly reachable after the document swap") + } + assertTrue(currentDocument.puppet.drawables.isNotEmpty(), "the replacement document stays live") + } + + /** + * Opens the corpus file, exercises it the way an open document is exercised, and returns ONLY weak + * references to its pieces. A separate method on purpose: the strong references live in this + * frame, which is popped on return, so the caller's GC poll observes true reachability rather than + * a stale stack slot. + * + * @param File file The corpus `.cmo3` to open. + * @return List>> A labeled weak reference per document piece. + */ + private fun openUseAndRelease(file: File): List>> { + val document = loadCmo3Document(file) + val session = EditorSession(document.puppet, document.liveParams.values) + val thumbnails = DrawableThumbnailer(document.puppet, document.textures) + // The session's page resolver holds the baseline pages plus one derived page set - the largest + // thing a repack leaves behind - so it has to go with the session it follows. + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val firstDrawable = document.puppet.drawables.first() + session.setSelection(SelectionOps.replace(SelectionTarget.Drawable(firstDrawable.id))) + // One committed pose puts a real step on the undo history, so the history stack is part of + // what must become unreachable. + val firstParameter = document.puppet.parameters.first() + session.commitPose( + ParameterChange.SetValue(listOf(firstParameter.id)), + mapOf(firstParameter.id to firstParameter.default + 1f), + ) + val references = + mutableListOf( + "Cmo3Document" to WeakReference(document), + "Cmo3Model (retained graph)" to WeakReference(document.cmo3), + "PuppetModel" to WeakReference(document.puppet), + "PuppetTextures" to WeakReference(document.textures), + "EditorSession" to WeakReference(session), + "DrawableThumbnailer" to WeakReference(thumbnails), + "SessionAtlasPages" to WeakReference(sessionAtlasPages), + ) + // Every document builds its own raster store, so this one is always the document's to release. + references.add("SourceArtRasters" to WeakReference(document.artRasters)) + return references + } + + /** + * Loads [file] through the same byte-core path the shell uses and asserts it opens as a CMO3. + * + * @param File file The corpus `.cmo3` to load. + * @return Cmo3Document The loaded document. + */ + private fun loadCmo3Document(file: File): Cmo3Document { + val load = loadDocument(file.readBytes(), file.name, file.path) + return assertIs(assertIs(load).document) + } + + /** + * Prods the collector until every reference clears or the deadline passes. Returning without all + * of them cleared is not itself a failure - the caller's assertions name the survivors. + * + * @param List>> references The references to wait on. + */ + private fun awaitCollection(references: List>>) { + val deadlineNanos = System.nanoTime() + GC_WAIT_MILLIS * 1_000_000L + while (System.nanoTime() < deadlineNanos) { + System.gc() + if (references.all { (_, reference) -> reference.get() == null }) { + return + } + Thread.sleep(GC_POLL_MILLIS) + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DropRouteTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DropRouteTest.kt new file mode 100644 index 0000000..10dafd4 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/DropRouteTest.kt @@ -0,0 +1,62 @@ +package org.umamo.ui.document + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertSame + +/** + * Pins what a drop MEANS, which is the whole of the decision a drop makes before any file is read: a + * document replaces the open one, artwork is added to it, and the first file settles which of the two the + * gesture was. Everything the chosen way cannot use has to come back as ignored rather than disappear - + * a rigger who grabbed one file too many should be able to find out. + */ +class DropRouteTest { + @Test + fun aDropOfNothingMeansNothing() { + assertSame(DropRoute.None, dropRouteFor(emptyList())) + } + + @Test + fun aDocumentOpensAndTakesNothingElseWithIt() { + val route = assertIs(dropRouteFor(listOf("/rigs/Erica.uma", "/rigs/Other.cmo3"))) + + assertEquals("/rigs/Erica.uma", route.path) + assertEquals(listOf("/rigs/Other.cmo3"), route.ignored, "only one document can be open") + } + + @Test + fun everyImportedModelFormatOpens() { + assertIs(dropRouteFor(listOf("/rigs/Erica.cmo3"))) + assertIs(dropRouteFor(listOf("/rigs/Erica.moc3"))) + } + + @Test + fun artworkFirstAddsEveryArtworkFileInTheDrop() { + val route = assertIs(dropRouteFor(listOf("/art/face.psd", "/art/hair.clip", "/art/eyes.PNG"))) + + assertEquals(listOf("/art/face.psd", "/art/hair.clip", "/art/eyes.PNG"), route.paths, "in the order they were dropped") + assertEquals(emptyList(), route.ignored) + } + + @Test + fun artworkFirstLeavesADocumentInTheSameDropBehind() { + val route = assertIs(dropRouteFor(listOf("/art/face.psd", "/rigs/Erica.uma", "/art/hair.psd"))) + + assertEquals(listOf("/art/face.psd", "/art/hair.psd"), route.paths) + assertEquals(listOf("/rigs/Erica.uma"), route.ignored, "the gesture was an add; the document is not quietly opened instead") + } + + /** + * A file of no kind the registry claims still routes to the open, which is what puts it in front of the + * loader - and the loader is what tells the rigger their file is not one Umamo reads. Routing it to the + * add would swallow it into a reader that has no alert of its own for "this is not artwork". + */ + @Test + fun anUnrecognizedFileRoutesToTheOpenSoItsFailureIsReported() { + val route = assertIs(dropRouteFor(listOf("/downloads/notes.txt", "/art/face.psd"))) + + assertEquals("/downloads/notes.txt", route.path) + assertEquals(listOf("/art/face.psd"), route.ignored) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ExportOptionsSessionTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ExportOptionsSessionTest.kt new file mode 100644 index 0000000..c5fc071 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ExportOptionsSessionTest.kt @@ -0,0 +1,79 @@ +package org.umamo.ui.document + +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The export dialog's session memory: what it opens with, what sticks across documents, and what + * deliberately does not. + * + * The two-lifetime rule under test: toggles are sticky for the whole session while the scale is + * sticky only per document, re-seeding from the model on a document change - a confirmed bake + * scale is a property of one rig, not of the rigger. + */ +class ExportOptionsSessionTest { + /** + * A rig with only the fields the scale seed reads. + * + * @param Float canvasWidth The canvas width the heuristic falls back to. + * @param Float? pixelsPerUnit The recorded bake scale, or null for a CMO3-origin document. + * @return PuppetModel The rig. + */ + private fun puppetOf(canvasWidth: Float, pixelsPerUnit: Float? = null): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = canvasWidth, + canvasHeight = canvasWidth, + pixelsPerUnit = pixelsPerUnit, + ) + + @Test + fun theFirstOpenGetsTheEditorMatchingDefaults() { + val opened = Moc3ExportSessionOptions().dialogOptionsFor("/models/a.cmo3", puppetOf(canvasWidth = 100f)) + + // The dialog defaults drop hidden objects and guides, like the official bake - deliberately + // NOT Moc3ExportOptions.Default, which is the options-less API's carry-everything contract. + assertFalse(opened.exportHiddenParts) + assertFalse(opened.exportHiddenDrawables) + assertFalse(opened.exportGuideImageParts) + assertTrue(opened.includePhysics) + assertTrue(opened.includeUserData) + assertTrue(opened.includeDisplayInfo) + assertEquals(100f, opened.pixelsPerUnitOverride, "the scale seeds from the canvas width heuristic") + } + + @Test + fun aRecordedScaleSeedsFromTheModelInsteadOfTheHeuristic() { + val opened = Moc3ExportSessionOptions().dialogOptionsFor("/models/a.moc3", puppetOf(100f, pixelsPerUnit = 250f)) + + assertEquals(250f, opened.pixelsPerUnitOverride, "a MOC3-origin document keeps its own bake scale") + } + + @Test + fun confirmedTogglesStickAcrossDocumentsButTheScaleDoesNot() { + val session = Moc3ExportSessionOptions() + session.recordConfirmed( + "/models/a.cmo3", + Moc3ExportOptions(exportHiddenParts = true, includeDisplayInfo = false, pixelsPerUnitOverride = 512f), + ) + + val reopened = session.dialogOptionsFor("/models/a.cmo3", puppetOf(100f)) + assertTrue(reopened.exportHiddenParts, "a confirmed toggle sticks") + assertFalse(reopened.includeDisplayInfo) + assertEquals(512f, reopened.pixelsPerUnitOverride, "the same document keeps the confirmed scale") + + val otherDocument = session.dialogOptionsFor("/models/b.cmo3", puppetOf(300f)) + assertTrue(otherDocument.exportHiddenParts, "toggles stick across documents") + assertFalse(otherDocument.includeDisplayInfo) + assertEquals(300f, otherDocument.pixelsPerUnitOverride, "the scale re-seeds on a document change") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/InMemoryArt.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/InMemoryArt.kt new file mode 100644 index 0000000..cfe2b57 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/InMemoryArt.kt @@ -0,0 +1,50 @@ +package org.umamo.ui.document + +import org.umamo.format.art.LayerBlend +import org.umamo.format.art.LayerBounds +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer + +/** An in-memory source layer of one opaque color at a canvas position, keyed the way a reader keys it. */ +internal class InMemoryLayer( + id: String, + override val name: String, + override val order: Int, + override val bounds: LayerBounds, + override val raster: LayerRaster, + override val visible: Boolean = true, +) : SourceLayer { + override val id: LayerId = LayerId(id) + override val groupPath: String = "" + override val opacity: Float = 1f + override val clipped: Boolean = false + override val blend: LayerBlend = LayerBlend.Normal +} + +/** An in-memory source document, so a flow test needs no file. */ +internal class InMemoryArt( + override val layers: List, + override val widthPx: Int = 64, + override val heightPx: Int = 64, +) : SourceArt + +/** + * A raster filled with one opaque color. + * + * @param Int width The width in pixels. + * @param Int height The height in pixels. + * @param Byte value The byte every color channel takes. + * @return LayerRaster The raster. + */ +internal fun solidRaster(width: Int, height: Int, value: Byte): LayerRaster { + val rgba = ByteArray(width * height * 4) + for (pixel in 0 until width * height) { + rgba[pixel * 4] = value + rgba[pixel * 4 + 1] = value + rgba[pixel * 4 + 2] = value + rgba[pixel * 4 + 3] = 0xFF.toByte() + } + return LayerRaster(width, height, rgba) +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/LivePlacementMoveGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/LivePlacementMoveGateTest.kt new file mode 100644 index 0000000..9f225bc --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/LivePlacementMoveGateTest.kt @@ -0,0 +1,183 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.edit.setAtlasPlacements +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasPages +import org.umamo.render.DecodedImage +import org.umamo.render.derivedTileTrim +import org.umamo.render.encodeAtlasPng +import org.umamo.render.placementFootprint +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.applyUvAffine +import org.umamo.runtime.model.storedToArtAffineForTile +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.AtlasRepackReport +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.repackPageSizeOf +import org.umamo.ui.model.runAtlasRepack +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The live placement-move gate, driven the way the gizmo drives it: a repack (so the atlas is a + * generated one whose numbering the resolver and the export share), then one tile moved by whole + * pixels and another turned and reduced through the session's placement commit, the page resolver + * recomposing, and the export writing what the resolver shows. Proves the pieces agree: the moved + * tile's pixels sit at the new spot verbatim, its vertices still sample the same art pixels, and the + * file reads back with the placements, coordinates, and pages the session holds. + * + * Skips without the corpus sample. + */ +class LivePlacementMoveGateTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private fun pixelBytes(image: DecodedImage, x: Int, y: Int): ByteArray { + val offset = (y * image.width + x) * 4 + return image.rgba.copyOfRange(offset, offset + 4) + } + + private fun assertPlacementClose(expected: AtlasPlacement, actual: AtlasPlacement?, name: String) { + assertNotNull(actual, "'$name' reimports placed") + assertEquals(expected.pageIndex, actual.pageIndex, "'$name' page") + assertEquals(expected.positionX, actual.positionX, 1e-2f, "'$name' position x") + assertEquals(expected.positionY, actual.positionY, 1e-2f, "'$name' position y") + assertEquals(expected.scaleX, actual.scaleX, 1e-3f, "'$name' scale x") + assertEquals(expected.scaleY, actual.scaleY, 1e-3f, "'$name' scale y") + assertEquals(expected.rotationDegrees, actual.rotationDegrees, 1e-2f, "'$name' rotation") + } + + @Test + fun aLivePlacementMoveExportsTheMovedArrangement() = + runBlocking { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the live placement move gate") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + var refusal: AtlasRepackReport? = null + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> refusal = report }, + rememberOptions = { _, _ -> }, + ) + runAtlasRepack(host, AtlasPackOptions(maxPageSize = repackPageSizeOf(document.puppet)), areaId = null) + assertNull(refusal?.refusals?.joinToString { "${it.tileName}: ${it.reason}" }, "the repack refused") + val repacked = session.model.value + withTimeout(30_000) { + while (sessionAtlasPages.binding.value.atlas !== repacked.atlas) { + yield() + } + } + + // Two bound, placed tiles with art: one to move by whole pixels, one to turn and reduce. + val boundTileIds = repacked.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId } + val candidates = + repacked.atlas.tiles.filter { tile -> + tile.placement != null && tile.id in boundTileIds && document.artRasters.rasterFor(tile.id) != null + } + assertTrue(candidates.size >= 2, "the sample packs at least two bound tiles with art") + val mover = candidates[0] + val turner = candidates[1] + val moverPlacement = assertNotNull(mover.placement) + val moverRaster = assertNotNull(document.artRasters.rasterFor(mover.id)) + val moverTrim = assertNotNull(derivedTileTrim(moverRaster, repacked.atlas.composition.alphaThreshold)) + val page = repacked.atlas.pages[moverPlacement.pageIndex] + val footprint = placementFootprint(moverPlacement, moverTrim, reserve = null) + val deltaX = if (footprint.right + 9 <= page.width) 7 else -7 + val deltaY = if (footprint.bottom + 7 <= page.height) 5 else -5 + val movedPlacement = moverPlacement.copy(positionX = moverPlacement.positionX + deltaX, positionY = moverPlacement.positionY + deltaY) + val turnedPlacement = assertNotNull(turner.placement).copy(rotationDegrees = 30f, scaleX = 0.75f, scaleY = 0.75f) + val moverDrawable = repacked.drawables.first { drawable -> drawable.atlasTileId == mover.id && (drawable.mesh?.uvs?.size ?: 0) >= 2 } + val artUvsBefore = + applyUvAffine(assertNotNull(moverDrawable.mesh).uvs, assertNotNull(repacked.atlas.storedToArtAffineForTile(mover.id))) + + session.setAtlasPlacements(mapOf(mover.id to movedPlacement, turner.id to turnedPlacement)) + + val moved = session.model.value + assertNotSame(repacked.atlas, moved.atlas, "the move committed a new atlas") + assertEquals(movedPlacement, moved.atlas.tileById.getValue(mover.id).placement) + assertEquals(turnedPlacement, moved.atlas.tileById.getValue(turner.id).placement) + val artUvsAfter = + applyUvAffine( + assertNotNull(moved.drawables.first { drawable -> drawable.id == moverDrawable.id }.mesh).uvs, + assertNotNull(moved.atlas.storedToArtAffineForTile(mover.id)), + ) + for (componentIndex in artUvsBefore.indices) { + assertTrue( + abs(artUvsBefore[componentIndex] - artUvsAfter[componentIndex]) < 1e-4f, + "'${moverDrawable.name}' samples the same art pixel after the move (component $componentIndex)", + ) + } + + withTimeout(60_000) { + while (sessionAtlasPages.binding.value.atlas !== moved.atlas) { + yield() + } + } + val effective = sessionAtlasPages.binding.value.textures + val composedPage = effective.atlases[movedPlacement.pageIndex] + assertContentEquals( + pixelBytes(moverRaster, moverTrim.left + 1, moverTrim.top + 1), + pixelBytes(composedPage, movedPlacement.positionX.toInt() + moverTrim.left + 1, movedPlacement.positionY.toInt() + moverTrim.top + 1), + "the moved tile's pixels sit at the new spot verbatim", + ) + + val prepared = + prepareCmo3Export( + document = document, + edited = exportedModelFor(document, session), + effectiveTextures = effective, + modelName = "gate", + nowMillis = 0L, + obfuscateKey = 0, + ) + follower.cancel() + println("export report: ${prepared.report}") + val reread = Cmo3.read(Cmo3.write(prepared.model)) + val reimported = Cmo3Import.fromModelSource(reread.root as CModelSource) + assertEquals(moved.atlas.pages, reimported.atlas.pages, "page inventory") + assertPlacementClose(movedPlacement, reimported.atlas.tileById[mover.id]?.placement, mover.name) + assertPlacementClose(turnedPlacement, reimported.atlas.tileById[turner.id]?.placement, turner.name) + val editedUvs = moved.drawables.associate { drawable -> drawable.id to drawable.mesh?.uvs } + var uvMismatches = 0 + for (drawable in reimported.drawables) { + val expected = editedUvs[drawable.id] ?: continue + if (!expected.contentEquals(drawable.mesh?.uvs)) { + uvMismatches++ + } + } + assertEquals(0, uvMismatches, "drawables whose exported uvs differ from the session's") + val exportedPages = cmo3AtlasPages(reread.root as CModelSource) { resource -> reread.extractLayerPng(resource) }.pageBytes + val expectedPages = effective.atlases.map { pageImage -> encodeAtlasPng(pageImage) } + assertEquals(expectedPages.size, exportedPages.size, "exported page count") + for ((pageIndex, bytes) in exportedPages.withIndex()) { + assertTrue(expectedPages.any { expected -> expected.contentEquals(bytes) }, "exported page $pageIndex is not one of the resolver's pages") + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/LiveRepackExportGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/LiveRepackExportGateTest.kt new file mode 100644 index 0000000..5160561 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/LiveRepackExportGateTest.kt @@ -0,0 +1,115 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasPages +import org.umamo.render.encodeAtlasPng +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.AtlasRepackReport +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.repackPageSizeOf +import org.umamo.ui.model.runAtlasRepack +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The live repack-then-export gate, driven the way the shell drives it: the session's repack command, + * the page resolver following the model, the export policy reading the resolver's pages, the bytes + * written and re-read. Every unit gate below this exercises one stage in isolation; this is the one + * that proves the stages agree, so an exported file carries the arrangement the viewport shows. + * + * Skips without the corpus sample. + */ +class LiveRepackExportGateTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aLiveRepackExportsTheRepackedArrangement() = + runBlocking { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the live repack export gate") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + var refusal: AtlasRepackReport? = null + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> refusal = report }, + rememberOptions = { _, _ -> }, + ) + runAtlasRepack(host, AtlasPackOptions(maxPageSize = repackPageSizeOf(document.puppet)), areaId = null) + assertNull(refusal?.refusals?.joinToString { "${it.tileName}: ${it.reason}" }, "the repack refused") + val repacked = session.model.value + assertNotSame(document.puppet.atlas, repacked.atlas, "the repack committed a new atlas") + withTimeout(10_000) { + while (sessionAtlasPages.binding.value.atlas !== repacked.atlas) { + yield() + } + } + val effective = sessionAtlasPages.binding.value.textures + assertNotSame(document.textures, effective, "the resolver published the repack's own pages") + val prepared = + prepareCmo3Export( + document = document, + edited = exportedModelFor(document, session), + effectiveTextures = effective, + modelName = "gate", + nowMillis = 0L, + obfuscateKey = 0, + ) + follower.cancel() + println("export report: ${prepared.report}") + val reread = Cmo3.read(Cmo3.write(prepared.model)) + val reimported = Cmo3Import.fromModelSource(reread.root as CModelSource) + assertEquals(repacked.atlas.pages, reimported.atlas.pages, "page inventory") + var mismatches = 0 + for (tile in repacked.atlas.tiles) { + val reread = reimported.atlas.tileById[tile.id]?.placement + if (reread != tile.placement) { + mismatches++ + if (mismatches <= 5) { + println("placement mismatch '${tile.name}': session=${tile.placement} file=$reread") + } + } + } + assertEquals(0, mismatches, "tiles whose exported placement differs from the session's") + val editedUvs = repacked.drawables.associate { it.id to it.mesh?.uvs } + var uvMismatches = 0 + for (drawable in reimported.drawables) { + val expected = editedUvs[drawable.id] ?: continue + if (!expected.contentEquals(drawable.mesh?.uvs)) { + uvMismatches++ + } + } + assertEquals(0, uvMismatches, "drawables whose exported uvs differ from the session's") + // The page BYTES the file carries must be the resolver's pages, not the imported originals. + val exportedPages = cmo3AtlasPages(reread.root as CModelSource) { resource -> reread.extractLayerPng(resource) }.pageBytes + val expectedPages = effective.atlases.map { page -> encodeAtlasPng(page) } + assertEquals(expectedPages.size, exportedPages.size, "exported page count") + for ((pageIndex, bytes) in exportedPages.withIndex()) { + assertTrue(expectedPages.any { expected -> expected.contentEquals(bytes) }, "exported page $pageIndex is not one of the repack's pages") + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/MatchArtworkFlowTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/MatchArtworkFlowTest.kt new file mode 100644 index 0000000..00520a3 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/MatchArtworkFlowTest.kt @@ -0,0 +1,341 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.format.FileKind +import org.umamo.format.art.LayerBounds +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.MatchArtworkRequest +import org.umamo.ui.model.MatchParameterKeys +import org.umamo.ui.model.ReloadArtworkRequest +import org.umamo.ui.model.ReloadArtworkResult +import org.umamo.ui.model.ReloadEntry +import org.umamo.ui.model.ReplaceArtworkRequest +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.SourceSuggestions +import org.umamo.ui.model.runMatchArtwork +import org.umamo.ui.model.runReloadArtwork +import org.umamo.ui.model.runReplaceArtwork +import org.umamo.ui.model.scoreSourceSuggestions +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Match Automatically and Replace Artwork driven the way the shell drives them, over a document built + * from in-memory art: a file whose layers came back under new keys, one recognizable by its pixels + * and one only weakly, matched at the default bar as one step with the weak one left as a suggestion; + * the strip's threshold re-landing the step with both; undo restoring; a same-format twin replacing + * the record by key; a cross-format twin rebinding every binding by its pixels inside the replace + * step; and a Match after a reload merging the fresh drawable the reload minted into the rigged tile. + */ +class MatchArtworkFlowTest { + /** + * The label key of the history step the session stands on. + * + * @param EditorSession session The session. + * @return String? The current step's label key, or null on the seed. + */ + private fun currentStepLabel(session: EditorSession): String? = session.historyView.value.let { view -> view.steps[view.cursor].labelKey } + + private val options = SourceArtImportOptions(alphaThreshold = 1, birthMeshMargin = 2) + private val sourceId = ArtSourceId("art-0") + + private val hair = InMemoryLayer("lyid:1", "Hair Front", 0, LayerBounds(10, 10, 8, 8), solidRaster(8, 8, 1)) + private val eye = InMemoryLayer("lyid:2", "Eye L", 1, LayerBounds(40, 40, 8, 8), solidRaster(8, 8, 2)) + + /** Hair under a new key with the same pixels; the eye under a new key, renamed, moved, and repainted. */ + private val hairRenamed = InMemoryLayer("lyid:5", "Hair Front 2", 0, LayerBounds(10, 10, 8, 8), hair.raster) + private val eyeMoved = InMemoryLayer("lyid:6", "Eye", 1, LayerBounds(100, 100, 8, 8), solidRaster(8, 8, 0xF0.toByte())) + + @Test + fun matchAppliesTheConfidentRenameAndTheThresholdRowTakesTheRest() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(hair, eye)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the match must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + val tileHair = AtlasTileId("art-0/lyid:1") + val tileEye = AtlasTileId("art-0/lyid:2") + var published: SourceSuggestions = emptyMap() + + val renamedArt = InMemoryArt(listOf(hairRenamed, eyeMoved)) + val request = MatchArtworkRequest(listOf(ReloadEntry(sourceId, renamedArt, contentHash = "hash-v2")), threshold = 0.7f, options) + assertTrue(runMatchArtwork(host, request, areaId = null) { suggestions -> published = suggestions }, "the confident rename lands") + val matched = session.model.value + val hairTile = matched.atlas.tiles.first { tile -> tile.replaces == tileHair } + assertEquals("lyid:5", hairTile.source?.layerKey, "the hair tile moved to the layer with its pixels") + assertEquals("lyid:2", matched.atlas.tileById.getValue(tileEye).source?.layerKey, "the eye binding is left for a person") + assertEquals(listOf("lyid:5", "lyid:6", "lyid:2"), matched.sources.single().layers.map { layer -> layer.key }) + assertEquals(listOf(true, true, false), matched.sources.single().layers.map { layer -> layer.present }) + val eyeSuggestion = assertNotNull(published[sourceId to "lyid:2"], "the weak match is published as a suggestion") + assertEquals("lyid:6", eyeSuggestion.key) + assertTrue(eyeSuggestion.score < 0.7f, "below the bar: ${eyeSuggestion.score}") + assertTrue(eyeSuggestion.score >= 0.5f, "but not hopeless: ${eyeSuggestion.score}") + assertNotNull(eyeSuggestion.signals.pixels, "the pixels were compared") + assertEquals("change.document.matchArtwork", currentStepLabel(session), "one step, labeled as a match") + + // The strip's threshold row: lowering the bar re-lands the same step with both. + val record = assertNotNull(session.adjustableOperation.value, "the match registered on the strip") + val lowered = record.parameters.map { parameter -> if (parameter.key == MatchParameterKeys.THRESHOLD && parameter is OperatorParameter.FloatParameter) parameter.copy(value = 50f) else parameter } + session.adjustLastOperation(lowered) + withTimeout(120_000) { + while (session.model.value.atlas.tiles.any { tile -> tile.source?.layerKey == "lyid:2" }) { + yield() + } + } + val both = session.model.value + assertEquals(setOf("lyid:5", "lyid:6"), both.atlas.tiles.mapNotNull { tile -> tile.source?.layerKey }.toSet(), "both bindings moved") + assertEquals(listOf("lyid:5", "lyid:6"), both.sources.single().layers.map { layer -> layer.key }, "no lost row remains") + assertTrue(published.isEmpty(), "nothing is left to suggest") + assertEquals(2, both.drawables.size, "no drawable was added or lost") + + // One step: undo restores the document as imported. + session.undo() + assertSame(before, session.model.value) + session.redo() + assertEquals(setOf("lyid:5", "lyid:6"), session.model.value.atlas.tiles.mapNotNull { tile -> tile.source?.layerKey }.toSet()) + follower.cancel() + } + + @Test + fun raisingTheThresholdPastTheMatchAmendsTheStepBackToTheBase() = + runBlocking { + // A rename at the same place with repainted pixels scores just under certain, so the strip's + // threshold can be raised past it. Doing so must take the rebinding with it - the step amends + // back to the base and the proposal is published - so the strip and the document agree; a + // certain (hash-equal) match scores exactly 1 and survives any bar, which is right. + val repainted = InMemoryLayer("lyid:5", "Hair Front", 0, LayerBounds(10, 10, 8, 8), solidRaster(8, 8, 3)) + val load = buildArtDocument(InMemoryArt(listOf(hair)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the match must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + var published: SourceSuggestions = emptyMap() + + val request = MatchArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(repainted)), contentHash = "hash-v2")), threshold = 0.7f, options) + assertTrue(runMatchArtwork(host, request, areaId = null) { suggestions -> published = suggestions }) + assertEquals(listOf("lyid:5"), session.model.value.atlas.tiles.mapNotNull { tile -> tile.source?.layerKey }) + assertTrue(published.isEmpty()) + val record = assertNotNull(session.adjustableOperation.value) + + val raised = record.parameters.map { parameter -> if (parameter.key == MatchParameterKeys.THRESHOLD && parameter is OperatorParameter.FloatParameter) parameter.copy(value = 100f) else parameter } + session.adjustLastOperation(raised) + withTimeout(120_000) { + while (session.model.value !== before) { + yield() + } + } + assertEquals(listOf("lyid:1"), session.model.value.atlas.tiles.mapNotNull { tile -> tile.source?.layerKey }, "the rebinding went with the bar") + val proposal = assertNotNull(published[sourceId to "lyid:1"], "the proposal is published for the review row") + assertEquals("lyid:5", proposal.key) + assertTrue(proposal.score < 1f && proposal.score >= 0.7f, "near certain, not certain: ${proposal.score}") + assertTrue(session.canUndo.value, "the step still stands, holding the base") + assertEquals("change.document.matchArtwork", currentStepLabel(session)) + + // And back down: the same record re-lands the rebinding. + val lowered = record.parameters.map { parameter -> if (parameter.key == MatchParameterKeys.THRESHOLD && parameter is OperatorParameter.FloatParameter) parameter.copy(value = 70f) else parameter } + session.adjustLastOperation(lowered) + withTimeout(120_000) { + while (session.model.value.atlas.tiles.any { tile -> tile.source?.layerKey == "lyid:1" }) { + yield() + } + } + assertTrue(published.isEmpty()) + session.undo() + assertSame(before, session.model.value) + follower.cancel() + } + + @Test + fun twoLostLayersPreferringOneCandidateSettleOnTheMoreConfidentAndKeepTheOther() = + runBlocking { + // Two layers with the same pixels come back as ONE layer under a new key: both hash-match it. + // One takes it; the other must stay a suggestion, counted as remaining, not vanish because its + // candidate was spoken for. + val front = InMemoryLayer("lyid:1", "Hair Front", 0, LayerBounds(10, 10, 8, 8), solidRaster(8, 8, 1)) + val back = InMemoryLayer("lyid:2", "Hair Back", 1, LayerBounds(10, 30, 8, 8), front.raster) + val merged = InMemoryLayer("lyid:5", "Hair", 0, LayerBounds(10, 10, 8, 8), front.raster) + val load = buildArtDocument(InMemoryArt(listOf(front, back)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the match must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + var published: SourceSuggestions = emptyMap() + + val request = MatchArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(merged)), contentHash = "hash-v2")), threshold = 0.7f, options) + assertTrue(runMatchArtwork(host, request, areaId = null) { suggestions -> published = suggestions }) + val matched = session.model.value + assertEquals(setOf("lyid:5", "lyid:2"), matched.atlas.tiles.mapNotNull { tile -> tile.source?.layerKey }.toSet(), "one moved, one stayed") + val notice = assertNotNull(session.notice.value) + assertEquals("notice.match.done", notice.messageKey) + assertEquals(listOf("1", "1"), notice.arguments, "one matched, one remaining") + val leftover = assertNotNull(published[sourceId to "lyid:2"], "the loser keeps its proposal") + assertEquals("lyid:5", leftover.key) + assertTrue(leftover.signals.hashEqual) + follower.cancel() + } + + @Test + fun replaceReloadsByKeyForATwinAndReboundsEverythingForACrossFormatOne() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(hair, eye)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the replace must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + var published: SourceSuggestions = emptyMap() + + // A same-format twin: the keys resolve, the record is repointed, no tile changes. + val twin = ArtSourceDescriptor("b.psd", "/art/b.psd", "psd", "hash-b") + val twinRequest = ReplaceArtworkRequest(sourceId, InMemoryArt(listOf(hair, eye)), twin, contentHash = "hash-b", options) + assertTrue(runReplaceArtwork(host, twinRequest, areaId = null) { suggestions -> published = suggestions }) + val repointed = session.model.value + assertEquals("b.psd", repointed.sources.single().name) + assertEquals("/art/b.psd", repointed.sources.single().path) + assertEquals("hash-b", repointed.sources.single().contentHash) + assertEquals(listOf(AtlasTileId("art-0/lyid:1"), AtlasTileId("art-0/lyid:2")), repointed.atlas.tiles.map { tile -> tile.id }, "nothing replaced") + assertEquals("change.document.replaceArtwork", currentStepLabel(session)) + assertTrue(published.isEmpty()) + + // A cross-format twin: the same art under other keys. Every binding is rebound by its pixels + // inside the replace step, nothing minted, no lost row, nothing left to suggest. + val clipHair = InMemoryLayer("clip:a", "Hair Front", 0, LayerBounds(10, 10, 8, 8), hair.raster) + val clipEye = InMemoryLayer("clip:b", "Eye L", 1, LayerBounds(40, 40, 8, 8), eye.raster) + val clip = ArtSourceDescriptor("a.clip", "/art/a.clip", "clip", "hash-c") + val clipArt = InMemoryArt(listOf(clipHair, clipEye)) + assertTrue(runReplaceArtwork(host, ReplaceArtworkRequest(sourceId, clipArt, clip, contentHash = "hash-c", options), areaId = null) { suggestions -> published = suggestions }) + val replaced = session.model.value + assertEquals("clip", replaced.sources.single().format) + assertEquals(listOf("clip:a", "clip:b"), replaced.sources.single().layers.map { layer -> layer.key }, "no lost row remains") + assertEquals(setOf("clip:a", "clip:b"), replaced.atlas.tiles.mapNotNull { tile -> tile.source?.layerKey }.toSet(), "both bindings moved") + assertEquals(setOf(AtlasTileId("art-0/lyid:1"), AtlasTileId("art-0/lyid:2")), replaced.atlas.tiles.mapNotNull { tile -> tile.replaces }.toSet(), "the two tiles were replaced") + assertEquals(2, replaced.atlas.tiles.size, "and none minted") + assertEquals(2, replaced.drawables.size) + assertEquals("change.document.replaceArtwork", currentStepLabel(session)) + val notice = assertNotNull(session.notice.value) + assertEquals("notice.replace.done", notice.messageKey) + assertEquals(listOf("0", "2", "0"), notice.arguments, "none by key, two matched, none for review") + assertTrue(published.isEmpty(), "nothing is left to suggest") + val record = assertNotNull(session.adjustableOperation.value) + assertEquals(MatchParameterKeys.THRESHOLD, record.parameters.first().key, "the replace strip leads with the bar") + + // Nothing left to match: no step, the model untouched, and the notice says why. + val matchRequest = MatchArtworkRequest(listOf(ReloadEntry(sourceId, clipArt, contentHash = "hash-c")), threshold = 0.7f, options) + assertFalse(runMatchArtwork(host, matchRequest, areaId = null) { suggestions -> published = suggestions }) + assertSame(replaced, session.model.value) + assertEquals("notice.match.noCandidates", assertNotNull(session.notice.value).messageKey) + follower.cancel() + } + + /** + * A reload whose lost layer's best candidate scores under the bar mints the candidate as a fresh + * drawable; the lost row then proposes that layer all the same, since only a fresh, untouched + * drawable sits over it, and a Match at a lower bar moves the rigged tile onto the layer and + * retires the fresh drawable with its tile - one step, no doubled art. + */ + @Test + fun aMatchAfterAReloadMergesTheFreshDrawableIntoTheRiggedTile() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(hair, eye)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the pass must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val tileHair = AtlasTileId("art-0/lyid:1") + val fringe = InMemoryLayer("lyid:5", "Fringe", 0, LayerBounds(100, 100, 8, 8), solidRaster(8, 8, 0xF0.toByte())) + val reloadEntry = ReloadEntry(sourceId, InMemoryArt(listOf(fringe, eye)), contentHash = "hash-v2") + var published: SourceSuggestions = emptyMap() + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(reloadEntry), options), areaId = null) { suggestions -> published = suggestions }) + val minted = session.model.value + assertEquals(3, minted.drawables.size, "under the bar, the stranger is minted") + val freshTile = AtlasTileId("art-0/lyid:5") + assertNotNull(minted.atlas.tileById[freshTile]) + assertNotNull(minted.atlas.tileById[tileHair], "the lost binding's tile stands") + val proposal = assertNotNull(published[sourceId to "lyid:1"], "the reload publishes the proposal it scored before minting") + assertEquals("lyid:5", proposal.key) + assertTrue(proposal.score < 0.7f, "under the bar: ${proposal.score}") + assertTrue(scoreSourceSuggestions(host, listOf(reloadEntry)).isEmpty(), "re-scored on the model alone, the bound layer is no candidate") + + var afterMatch: SourceSuggestions = emptyMap() + assertTrue(runMatchArtwork(host, MatchArtworkRequest(listOf(reloadEntry), threshold = 0.1f, options, standing = published), areaId = null) { suggestions -> afterMatch = suggestions }) + val merged = session.model.value + assertEquals(2, merged.drawables.size, "the fresh drawable is gone") + assertNull(merged.atlas.tileById[freshTile], "with its tile") + val rebound = merged.atlas.tiles.first { tile -> tile.replaces == tileHair } + assertEquals("lyid:5", rebound.source?.layerKey, "the rigged tile took the layer") + assertNotNull(rebound.placement) + assertEquals(listOf("lyid:5", "lyid:2"), merged.sources.single().layers.map { layer -> layer.key }) + assertTrue(afterMatch.isEmpty()) + assertEquals("change.document.matchArtwork", currentStepLabel(session)) + session.undo() + assertSame(minted, session.model.value, "one step") + follower.cancel() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3DocumentLoadTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3DocumentLoadTest.kt new file mode 100644 index 0000000..fc4bd5a --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3DocumentLoadTest.kt @@ -0,0 +1,157 @@ +package org.umamo.ui.document + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * Discovery and failure classification of the MOC3 sidecar loader ([buildMoc3Document]): every + * rejection path must report the matching [DocumentOpenError], and the optional-cdi3 degradation + * must keep the import working on raw ids. All file IO is injected, so the rules run against fake + * readers; the moc-dependent paths read the corpus sample (`-Dmoc3.sample`, defaulted to the local + * corpus by the build) and self-skip without it. + */ +class Moc3DocumentLoadTest { + private val sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + + /** A minimal parseable manifest whose moc/texture references the tests override per case. */ + private val minimalManifestText = """{"Version":3,"FileReferences":{"Moc":"puppet.moc3","Textures":["missing.png"]}}""" + + @Test + fun missingManifestFailsAsMissingManifest() { + val load = buildMoc3Document("puppet.moc3", "puppet.moc3", ByteArray(64)) { _ -> null } + val failed = assertIs(load) + assertEquals(DocumentOpenError.MissingManifest, failed.failure.error) + assertEquals("puppet.moc3", failed.failure.displayName) + } + + @Test + fun unparseableManifestFailsAsParseFailed() { + // The manifest EXISTS but is not JSON: that is a parse failure, not a missing file - the + // alert must not claim a file is absent when it sits right next to the moc. + val load = + buildMoc3Document("puppet.moc3", "puppet.moc3", ByteArray(64)) { reference -> + if (reference == "puppet.model3.json") "not json".encodeToByteArray() else null + } + val failed = assertIs(load) + assertEquals(DocumentOpenError.ParseFailed, failed.failure.error) + } + + @Test + fun manifestWithUnknownKeysStillParses() { + // Newer Cubism exports add manifest keys the schema does not model (e.g. MotionSync); the + // reader must tolerate them. The unknown-keyed manifest parses, so the load proceeds past + // the manifest gate and fails later on the unresolvable texture instead. + val manifestWithExtras = + """{"Version":3,"MotionSync":"puppet.motionsync3.json","FileReferences":{"Moc":"puppet.moc3","MotionSync":"x.json","Textures":["missing.png"]}}""" + val load = + buildMoc3Document("puppet.moc3", "puppet.moc3", ByteArray(64)) { reference -> + if (reference == "puppet.model3.json") manifestWithExtras.encodeToByteArray() else null + } + val failed = assertIs(load) + assertEquals(DocumentOpenError.ParseFailed, failed.failure.error, "moc bytes are garbage, so decode fails AFTER the manifest gate") + } + + @Test + fun uppercaseExtensionDerivesTheLowercaseFamilyBasename() { + // Every route here matches the extension case-insensitively, so "PUPPET.MOC3" must look for + // "PUPPET.model3.json", not "PUPPET.MOC3.model3.json". + var requestedManifest: String? = null + buildMoc3Document("PUPPET.MOC3", "PUPPET.MOC3", ByteArray(64)) { reference -> + if (reference.endsWith(".model3.json")) { + requestedManifest = reference + } + null + } + assertEquals("PUPPET.model3.json", requestedManifest) + } + + @Test + fun corruptMocFailsAsParseFailed() { + // A parseable manifest next to garbage moc bytes: the manifest gate passes, the decode throws. + val load = + buildMoc3Document("puppet.moc3", "puppet.moc3", ByteArray(64)) { reference -> + if (reference == "puppet.model3.json") minimalManifestText.encodeToByteArray() else null + } + val failed = assertIs(load) + assertEquals(DocumentOpenError.ParseFailed, failed.failure.error) + } + + @Test + fun missingTextureFailsAsMissingTexture() { + val mocFile = sample + if (mocFile == null) { + println("moc3.sample not present; skipping missing-texture test") + return + } + // A real decodable moc whose manifest lists a texture the reader cannot resolve. + val load = + buildMoc3Document(mocFile.path, mocFile.name, mocFile.readBytes()) { reference -> + if (reference.endsWith(".model3.json")) minimalManifestText.encodeToByteArray() else null + } + val failed = assertIs(load) + assertEquals(DocumentOpenError.MissingTexture, failed.failure.error) + } + + @Test + fun undecodableTextureFailsAsMissingTexture() { + val mocFile = sample + if (mocFile == null) { + println("moc3.sample not present; skipping undecodable-texture test") + return + } + val load = + buildMoc3Document(mocFile.path, mocFile.name, mocFile.readBytes()) { reference -> + when { + reference.endsWith(".model3.json") -> minimalManifestText.encodeToByteArray() + reference == "missing.png" -> "not a png".encodeToByteArray() + else -> null + } + } + val failed = assertIs(load) + assertEquals(DocumentOpenError.MissingTexture, failed.failure.error) + } + + @Test + fun loadsCorpusFamilyAndDegradesWithoutCdi3() { + val mocFile = sample + if (mocFile == null) { + println("moc3.sample not present; skipping corpus load test") + return + } + val directory = mocFile.parentFile + + fun readRelative(reference: String): ByteArray? = directory.resolve(reference).takeIf { it.isFile }?.readBytes() + + // Full family: manifest + textures + cdi3 resolve from the corpus directory. + val load = buildMoc3Document(mocFile.path, mocFile.name, mocFile.readBytes(), ::readRelative) + val loaded = assertIs(load) + val document = assertIs(loaded.document) + assertTrue(document.puppet.drawables.isNotEmpty(), "expected drawables") + assertTrue(document.textures.atlases.isNotEmpty(), "expected decoded atlas pages") + assertEquals( + document.puppet.drawables.size, + document.textures.atlasIndexByDrawableId.size, + "every drawable resolves an atlas page", + ) + assertTrue( + document.puppet.parameters.any { parameter -> parameter.id.raw != parameter.name }, + "cdi3 display names applied", + ) + + // cdi3 withheld: the import still succeeds and every name degrades to the raw format id. + val withoutCdi3 = + buildMoc3Document(mocFile.path, mocFile.name, mocFile.readBytes()) { reference -> + if (reference.endsWith(".cdi3.json")) null else readRelative(reference) + } + val degraded = assertIs(assertIs(withoutCdi3).document) + assertTrue( + degraded.puppet.parameters.all { parameter -> parameter.id.raw == parameter.name }, + "raw-id parameter names without cdi3", + ) + assertTrue(degraded.puppet.parameterTree.isEmpty(), "no parameter tree without cdi3") + assertTrue(degraded.puppet.parameterLinks.isEmpty(), "no parameter links without cdi3") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3DocumentWriterTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3DocumentWriterTest.kt new file mode 100644 index 0000000..3671942 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3DocumentWriterTest.kt @@ -0,0 +1,75 @@ +package org.umamo.ui.document + +import org.umamo.interop.ExportFormat +import org.umamo.interop.ExportReport +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.storage.platformFileFromSavedPath +import java.nio.file.Files +import kotlin.io.path.createDirectories +import kotlin.io.path.writeBytes +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The pre-export overwrite check: which of the family's files already sit at the destination. + * + * On a real (temporary) directory rather than a fake filesystem, because the function under test + * resolves the picked handle's parent through the same path FileKit hands the writer - the platform + * seam is the thing being exercised. + */ +class Moc3DocumentWriterTest { + /** + * A bundle whose family is a moc, a manifest, and one subfoldered texture page. + * + * @param String basename The family base name. + * @return Bundle The bundle; contents are placeholders, only the names matter here. + */ + private fun bundleOf(basename: String): Moc3Sidecars.Bundle { + val mocFileName = "$basename.moc3" + return Moc3Sidecars.Bundle( + files = + listOf( + Moc3Sidecars.BundleFile(mocFileName, byteArrayOf(1)), + Moc3Sidecars.BundleFile("$basename.model3.json", byteArrayOf(2)), + Moc3Sidecars.BundleFile("$basename.2048/texture_00.png", byteArrayOf(3)), + ), + mocFileName = mocFileName, + report = ExportReport(ExportFormat.Moc3, emptyList()), + ) + } + + @Test + fun anEmptyDestinationReportsNothingToOverwrite() { + val directory = Files.createTempDirectory("umamo-export") + val destination = platformFileFromSavedPath(directory.resolve("Model.moc3").toString()) + + assertEquals(emptyList(), existingBundleFiles(destination, bundleOf("Model"))) + } + + @Test + fun everyExistingFamilyFileIsReported() { + // A prior export's family, the subfoldered texture included - the case the native save dialog + // cannot warn about, because the rigger only picked the moc. + val directory = Files.createTempDirectory("umamo-export") + directory.resolve("Model.moc3").writeBytes(byteArrayOf(9)) + directory.resolve("Model.model3.json").writeBytes(byteArrayOf(9)) + directory.resolve("Model.2048").createDirectories() + directory.resolve("Model.2048/texture_00.png").writeBytes(byteArrayOf(9)) + val destination = platformFileFromSavedPath(directory.resolve("Model.moc3").toString()) + + assertEquals( + listOf("Model.moc3", "Model.model3.json", "Model.2048/texture_00.png"), + existingBundleFiles(destination, bundleOf("Model")), + "every colliding family member is named, in bundle order", + ) + } + + @Test + fun anUnrelatedNeighborIsNotReported() { + val directory = Files.createTempDirectory("umamo-export") + directory.resolve("Other.model3.json").writeBytes(byteArrayOf(9)) + val destination = platformFileFromSavedPath(directory.resolve("Model.moc3").toString()) + + assertEquals(emptyList(), existingBundleFiles(destination, bundleOf("Model"))) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3ExportPolicyTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3ExportPolicyTest.kt new file mode 100644 index 0000000..e1148ac --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3ExportPolicyTest.kt @@ -0,0 +1,136 @@ +package org.umamo.ui.document + +import org.umamo.format.png.PngCodec +import org.umamo.interop.moc3.Moc3ExportOptions +import org.umamo.interop.moc3.Moc3Sidecars +import org.umamo.render.DecodedImage +import org.umamo.render.PuppetTextures +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The MOC3 export's naming and page-payload rules, on hand-built inputs. + * + * Deliberately NOT sample-gated: these are the branches the corpus round trip cannot reach. A corpus + * document always has a manifest and always has source page bytes, so that test only ever exercises the + * "source name, verbatim bytes" side of both decisions. The CMO3-origin side has neither, and is + * covered here or nowhere. + */ +class Moc3ExportPolicyTest { + /** + * A solid-color decoded page. + * + * @param Int width Page width. + * @param Int height Page height. + * @return DecodedImage The page. + */ + private fun decodedPage(width: Int, height: Int): DecodedImage = + DecodedImage(ByteArray(width * height * 4) { 0x7F }, width, height) + + /** + * A texture set over [pages] with no drawable bindings. + * + * @param List pages The decoded pages. + * @return PuppetTextures The set. + */ + private fun texturesOf(vararg pages: DecodedImage): PuppetTextures = + PuppetTextures(pages.toList(), emptyMap(), premultipliedAlpha = false) + + @Test + fun aCmo3OriginPageIsNamedInTheOfficialTextureLayout() { + // Basename.Resolution/texture_NN.png, exactly as every corpus manifest lays the family out. + // The resolution is per PROJECT, so the smaller second page still lives in the same folder. + val pages = atlasPagesFor(texturesOf(decodedPage(4, 4), decodedPage(2, 2)), moc3Document = null, basename = "Model") + assertEquals(listOf("Model.4/texture_00.png", "Model.4/texture_01.png"), pages.map { page -> page.fileName }) + } + + @Test + fun theTextureFolderResolutionIsTheLargestPageDimension() { + // A non-square page still needs one number for the folder; the largest dimension is the size + // the export actually required. + val pages = atlasPagesFor(texturesOf(decodedPage(6, 3)), moc3Document = null, basename = "Model") + assertEquals(listOf("Model.6/texture_00.png"), pages.map { page -> page.fileName }) + } + + @Test + fun thePageIndexKeepsAllItsDigitsPastTwo() { + val pages = + atlasPagesFor( + texturesOf(*Array(101) { decodedPage(1, 1) }), + moc3Document = null, + basename = "Model", + ) + assertEquals("Model.1/texture_00.png", pages.first().fileName) + assertEquals("Model.1/texture_100.png", pages.last().fileName, "a third digit is kept, not truncated") + } + + @Test + fun aCmo3OriginPageIsReEncodedFromTheDecodedPixels() { + // The one path that produces bytes rather than passing them through: a CMO3-origin document has + // no source PNG at all, so a page that did not re-encode would be written empty. + val pages = atlasPagesFor(texturesOf(decodedPage(6, 3)), moc3Document = null, basename = "Model") + val decoded = PngCodec.read(pages.single().bytes) + assertEquals(6, decoded.width, "re-encoded page width") + assertEquals(3, decoded.height, "re-encoded page height") + } + + @Test + fun everyDecodedPageIsWritten() { + // Driven by the decoded set, so the page a drawable's index refers to always exists. Dropping + // one would renumber every later page out from under the drawables referencing it. + val pages = atlasPagesFor(texturesOf(decodedPage(1, 1), decodedPage(1, 1), decodedPage(1, 1)), null, "Model") + assertEquals(3, pages.size) + assertTrue(pages.all { page -> page.bytes.isNotEmpty() }, "no page may be written empty") + } + + @Test + fun theBasenameStripIgnoresExtensionCase() { + // A destination spelled `.MOC3` that kept its extension would name every sibling - the manifest + // included - after an `X.MOC3.moc3` that no write ever produces. + assertEquals("Model", Moc3Sidecars.basenameFor("Model.MOC3")) + assertEquals("Model", Moc3Sidecars.basenameFor("Model.moc3")) + assertEquals("Model", Moc3Sidecars.basenameFor("Model.Moc3")) + } + + @Test + fun aNameWithoutTheExtensionIsItsOwnBasename() { + assertEquals("Model", Moc3Sidecars.basenameFor("Model")) + // Only a TRAILING `.moc3` is an extension; an interior one is part of the name. + assertEquals("Model.moc3.backup", Moc3Sidecars.basenameFor("Model.moc3.backup")) + } + + /** + * One retained sidecar of [kind]. + * + * @param SidecarKind kind The sidecar's kind. + * @param String fileName Its relative file name. + * @return PassThroughSidecar The sidecar. + */ + private fun sidecarOf(kind: Moc3Sidecars.SidecarKind, fileName: String): Moc3Sidecars.PassThroughSidecar = + Moc3Sidecars.PassThroughSidecar(kind, fileName, text = "{}") + + private fun retainedSidecars(): List = + listOf( + sidecarOf(Moc3Sidecars.SidecarKind.Physics, "Model.physics3.json"), + sidecarOf(Moc3Sidecars.SidecarKind.UserData, "Model.userdata3.json"), + sidecarOf(Moc3Sidecars.SidecarKind.Pose, "Model.pose3.json"), + ) + + @Test + fun defaultOptionsCarryEveryRetainedSidecar() { + val exported = exportedSidecarsFor(retainedSidecars(), Moc3ExportOptions.Default) + assertEquals(retainedSidecars().map { sidecar -> sidecar.fileName }, exported.map { sidecar -> sidecar.fileName }) + } + + @Test + fun optingOutDropsExactlyTheOptedOutSidecarKinds() { + val exported = + exportedSidecarsFor( + retainedSidecars(), + Moc3ExportOptions(includePhysics = false, includeUserData = false), + ) + // The pose sidecar has no toggle, so opting the other two out must never take it along. + assertEquals(listOf("Model.pose3.json"), exported.map { sidecar -> sidecar.fileName }) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3FamilyExportTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3FamilyExportTest.kt new file mode 100644 index 0000000..d183140 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3FamilyExportTest.kt @@ -0,0 +1,143 @@ +package org.umamo.ui.document + +import org.umamo.format.moc3.Moc3 +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContains +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * The exported moc FAMILY loads back through the importer that reads a Cubism-baked one. + * + * The MOC3's own fidelity is gated far more sharply elsewhere (against the official core); what this + * covers is everything AROUND it - that the manifest names files that exist, that the atlas pages are + * where the manifest says, that the cdi3 carries the display names a moc cannot, and that the + * sidecars an import retained come back out. Those are exactly the parts a runtime needs and the moc + * itself says nothing about. + * + * The round trip runs entirely in memory once the sample is read: the bundle is a list of named byte + * arrays, so the loader's injected `readRelative` reads it directly and no temporary directory is + * involved. + * + * Gated on `-Dmoc3.sample` (defaulted to the local corpus by the build); self-skips without it. + */ +class Moc3FamilyExportTest { + private val sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + + /** + * Imports the sample, exports its family, and re-imports that. + * + * @param String basename The base name to export under. + * @return Pair The source document and the re-imported one, or null when the sample is absent. + */ + private fun roundTrip(basename: String): Pair? { + val sampleFile = sample ?: return null + val directory = sampleFile.parentFile + val sourceName = sampleFile.name + val source = + buildMoc3Document(sampleFile.path, sourceName, sampleFile.readBytes()) { reference -> + File(directory, reference).takeIf { it.isFile }?.readBytes() + } + val loaded = assertIs(source).document as Moc3Document + + // Through the SHIPPED policy, not a copy of it: the page naming, the verbatim-vs-re-encode + // choice, and the basename strip are the rules under test, so re-deriving them here would only + // ever assert that the test agrees with itself. + val bundle = prepareMoc3Export(loaded, loaded.puppet, loaded.textures, "$basename.moc3") + val byName = bundle.files.associate { file -> file.name to file.bytes } + val reimported = + buildMoc3Document("$basename.moc3", "$basename.moc3", byName.getValue("$basename.moc3")) { reference -> + byName[reference] + } + return loaded to (assertIs(reimported).document as Moc3Document) + } + + @Test + fun theExportedFamilyReimports() { + val (source, reimported) = roundTrip("Exported") ?: return + assertEquals(source.puppet.drawables.size, reimported.puppet.drawables.size, "drawable count") + assertEquals(source.puppet.parts.size, reimported.puppet.parts.size, "part count") + assertEquals(source.puppet.deformers.size, reimported.puppet.deformers.size, "deformer count") + assertEquals(source.puppet.parameters.size, reimported.puppet.parameters.size, "parameter count") + assertEquals(source.atlasPages.size, reimported.atlasPages.size, "atlas page count") + } + + @Test + fun displayNamesSurviveTheFamily() { + val (source, reimported) = roundTrip("Exported") ?: return + // Compared BY ID: the export re-derives its own object ordering (parts pre-order, deformers + // parent-first), so a positional comparison would report every name as wrong on any model whose + // authored order differs from that walk. + assertEquals( + source.puppet.drawables.associate { it.id to it.name }, + reimported.puppet.drawables.associate { it.id to it.name }, + "art-mesh display names - the Umamo cdi3 extension is the only thing carrying these", + ) + assertEquals( + source.puppet.parts.associate { it.id to it.name }, + reimported.puppet.parts.associate { it.id to it.name }, + "part names", + ) + assertEquals( + source.puppet.parameters.associate { it.id to it.name }, + reimported.puppet.parameters.associate { it.id to it.name }, + "parameter names", + ) + assertEquals( + source.puppet.parameterLinks, + reimported.puppet.parameterLinks, + "combined-parameter pairs", + ) + } + + @Test + fun retainedSidecarsAreReemittedVerbatim() { + val (source, reimported) = roundTrip("Exported") ?: return + // Keyed by (kind, name) rather than compared directly: PassThroughSidecar has no value equality, + // and the KIND is half of what this asserts. A sidecar that returns with the right bytes filed + // under the wrong manifest section is written beside the moc but no longer wired to the rig. + assertEquals( + source.sidecars.associate { sidecar -> (sidecar.kind to sidecar.fileName) to sidecar.text }, + reimported.sidecars.associate { sidecar -> (sidecar.kind to sidecar.fileName) to sidecar.text }, + "the sidecars must come back byte-identical, under the same manifest sections", + ) + } + + @Test + fun theManifestNamesOnlyFilesTheBundleContains() { + val sampleFile = sample ?: return + val directory = sampleFile.parentFile + val loaded = + assertIs( + buildMoc3Document(sampleFile.path, sampleFile.name, sampleFile.readBytes()) { reference -> + File(directory, reference).takeIf { it.isFile }?.readBytes() + }, + ).document as Moc3Document + val bundle = prepareMoc3Export(loaded, loaded.puppet, loaded.textures, "Exported.moc3") + val names = bundle.files.map { file -> file.name }.toSet() + val manifest = Moc3.readModel3(bundle.files.first { it.name == "Exported.model3.json" }.bytes.decodeToString()) + val references = + buildList { + add(manifest.fileReferences.moc) + addAll(manifest.fileReferences.textures) + manifest.fileReferences.pose?.let(::add) + manifest.fileReferences.physics?.let(::add) + manifest.fileReferences.userData?.let(::add) + manifest.fileReferences.displayInfo?.let(::add) + manifest.fileReferences.expressions?.forEach { expression -> add(expression.file) } + manifest.fileReferences.motions?.values?.forEach { motions -> + motions.forEach { motion -> add(motion.file) } + } + } + assertTrue(references.isNotEmpty(), "the manifest must reference something") + for (reference in references) { + assertContains(names, reference, "the manifest names $reference, which the bundle does not contain") + } + // The non-file sections are user data with no home in PuppetModel; losing them on a round trip + // would silently delete a rigger's eye-blink wiring. + assertEquals(loaded.manifest.groups, manifest.groups, "auto-wiring groups") + assertEquals(loaded.manifest.hitAreas, manifest.hitAreas, "hit areas") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3UnkeyedDrawableExportTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3UnkeyedDrawableExportTest.kt new file mode 100644 index 0000000..325749e --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/Moc3UnkeyedDrawableExportTest.kt @@ -0,0 +1,125 @@ +package org.umamo.ui.document + +import org.umamo.interop.ExportNotice +import org.umamo.interop.moc3.export.Moc3Export +import org.umamo.interop.moc3.import.Moc3Import +import org.umamo.render.canvasToParentSpaceFor +import org.umamo.render.restMeshesToCanvasSpace +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.abs +import kotlin.math.max +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * An UNKEYED drawable under a deformer survives the export, through the injected space seam. + * + * This is the one geometry case a moc export cannot solve on its own. A keyed drawable stores + * parent-local values that base + delta reconstructs; an unkeyed one has only its rest mesh. After + * [org.umamo.render.restMeshesToCanvasSpace] that rest is canvas-space, so writing it verbatim under + * a warp would store canvas coordinates where the runtime expects lattice UVs. Inverting the chain + * needs `:render`'s warp inverse, which `:interop` cannot reach, hence the seam. (UMA / CMO3 rests + * that are already parent-local are a separate case the seam must leave alone - see + * [org.umamo.render.Moc3HiddenDrawableSpaceTest].) + * + * Both halves are pinned: with the seam the drawable is written and comes back where it started, and + * WITHOUT it the drawable is dropped with a notice rather than written wrong. The second half is the + * one that would rot quietly - a future refactor that silently wrote the canvas-space mesh would look + * fine in every count-based test. + * + * Gated on `-Dmoc3.sample`; self-skips without it. + */ +class Moc3UnkeyedDrawableExportTest { + private val sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + + /** + * The sample rig with one deformer-parented drawable's keyform grid removed. + * + * @return Pair The rig and the un-keyed drawable, or null when the sample is absent or has none. + */ + private fun rigWithAnUnkeyedChild(): Pair? { + val sampleFile = sample ?: return null + val directory = sampleFile.parentFile + val loaded = + assertIs( + buildMoc3Document(sampleFile.path, sampleFile.name, sampleFile.readBytes()) { reference -> + File(directory, reference).takeIf { it.isFile }?.readBytes() + }, + ).document as Moc3Document + // A warp child specifically: the rotation inverse is closed-form, so the warp's damped Newton is + // the half worth exercising. + val warpIds = loaded.puppet.deformers.filterIsInstance().map { it.id } + val target = + loaded.puppet.drawables.firstOrNull { drawable -> + drawable.parentDeformerId in warpIds && drawable.geometryGrid != null && drawable.mesh != null + } ?: return null + val unkeyed = target.copy(geometryGrid = null) + val rig = + loaded.puppet.copy( + drawables = loaded.puppet.drawables.map { drawable -> if (drawable.id == target.id) unkeyed else drawable }, + ) + return rig to unkeyed + } + + @Test + fun theSeamKeepsTheDrawableAndItsPlace() { + val (rig, unkeyed) = rigWithAnUnkeyedChild() ?: return + val lowered = Moc3Export.toMocDocument(rig, canvasToParentSpace = canvasToParentSpaceFor(rig)) + assertTrue( + lowered.document.artMeshes.any { mesh -> mesh.id == unkeyed.id.raw }, + "the unkeyed drawable must be written, not dropped", + ) + assertTrue( + lowered.report.notices.none { notice -> + notice is ExportNotice.UnsupportedChange && notice.subject == unkeyed.id.raw + }, + "nothing about the drawable should be unsupported once the seam is supplied", + ) + + // Re-import and put the rest meshes back into canvas space - the same pass the loader runs - so + // the comparison is against the geometry the editor started with. + val reimported = restMeshesToCanvasSpace(Moc3Import.fromMocDocument(lowered.document, displayInfo = null)) + val original = assertNotNull(unkeyed.mesh).positions + val roundTripped = assertNotNull(reimported.drawables.first { it.id == unkeyed.id }.mesh).positions + assertEquals(original.size, roundTripped.size, "vertex count") + var worstIndex = 0 + var worstError = 0f + for (coordinate in original.indices) { + // RELATIVE: a canvas coordinate is a model unit and runs into the thousands, so an absolute + // bound would be a precision test on the magnitude rather than on the inverse. The warp + // inverse is iterative, so this is a convergence bound, not an equality - and a wrong SPACE + // would miss by the whole deformer transform, orders of magnitude past it. + val error = abs(original[coordinate] - roundTripped[coordinate]) / max(1f, abs(original[coordinate])) + if (error > worstError) { + worstError = error + worstIndex = coordinate + } + } + assertTrue( + worstError < 1e-4f, + "the rest mesh moved: worst relative error = $worstError at coordinate $worstIndex " + + "(${original[worstIndex]} -> ${roundTripped[worstIndex]})", + ) + } + + @Test + fun withoutTheSeamTheDrawableIsDroppedRatherThanWrittenWrong() { + val (rig, unkeyed) = rigWithAnUnkeyedChild() ?: return + val lowered = Moc3Export.toMocDocument(rig) + assertTrue( + lowered.document.artMeshes.none { mesh -> mesh.id == unkeyed.id.raw }, + "without the inverse the drawable must not be written at all", + ) + assertTrue( + lowered.report.notices.any { notice -> + notice is ExportNotice.UnsupportedChange && notice.subject == unkeyed.id.raw + }, + "and the drop must be reported", + ) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/PlacedArtworkFlowTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/PlacedArtworkFlowTest.kt new file mode 100644 index 0000000..9708a52 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/PlacedArtworkFlowTest.kt @@ -0,0 +1,142 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.format.art.LayerBounds +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.art.ArtworkAnchor +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.interop.art.placedFor +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasTileId +import org.umamo.ui.model.AddArtworkRequest +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.ImportParameterKeys +import org.umamo.ui.model.ReloadArtworkRequest +import org.umamo.ui.model.ReloadArtworkResult +import org.umamo.ui.model.ReloadEntry +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.runAddArtwork +import org.umamo.ui.model.runReloadArtwork +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * A later artwork file placed on the rig's canvas, driven the way the shell drives it over in-memory + * art: the first file sets the canvas and carries no placement rows; a smaller second file lands + * centered with its record keeping the offset; the strip's Align and Offset rows re-land the step; + * a reload of the placed file finds nothing changed and re-borns a repainted layer at the placed + * position; and undo restores the model. + */ +class PlacedArtworkFlowTest { + private val options = SourceArtImportOptions(alphaThreshold = 1, birthMeshMargin = 2) + + /** The first file: the whole 64 x 64 canvas, one layer at (10, 10). */ + private val hostLayer = InMemoryLayer("lyid:1", "Host", 0, LayerBounds(10, 10, 8, 8), solidRaster(8, 8, 1)) + + /** The second file: a 16 x 16 canvas with one 4 x 4 layer at (2, 2) in its own frame. */ + private val patchLayer = InMemoryLayer("lyid:9", "Patch", 0, LayerBounds(2, 2, 4, 4), solidRaster(4, 4, 5)) + private val patchArt = InMemoryArt(listOf(patchLayer), widthPx = 16, heightPx = 16) + + @Test + fun aSecondFileLandsCenteredAndStaysPlacedThroughAdjustmentsAndReloads() = + runBlocking { + val document = newBlankDocument() + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the import must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + + // The first file defines the canvas: no placement, and no Align / Offset rows on its strip. + assertTrue(runAddArtwork(host, AddArtworkRequest(InMemoryArt(listOf(hostLayer)), ArtSourceDescriptor("host.psd", "/art/host.psd", "psd"), options), areaId = null)) + val framed = session.model.value + assertEquals(64f to 64f, framed.canvasWidth to framed.canvasHeight) + assertEquals(0 to 0, framed.sources.single().let { source -> source.offsetX to source.offsetZ }) + val firstRecord = assertNotNull(session.adjustableOperation.value) + assertTrue(firstRecord.parameters.none { parameter -> parameter.key == ImportParameterKeys.ALIGN }, "a first artwork has nothing to align") + assertContentEquals(floatArrayOf(8f, 8f, 20f, 8f, 20f, 20f, 8f, 20f), assertNotNull(framed.drawables.single().mesh).positions) + + // The second file is centered: (64 - 16) / 2 = 24 to the right and 24 down, which is z = -24. + assertTrue(runAddArtwork(host, AddArtworkRequest(patchArt, ArtSourceDescriptor("patch.png", "/art/patch.png", "png"), options), areaId = null)) + val placed = session.model.value + val patchSource = placed.sources.first { source -> source.name == "patch.png" } + assertEquals(ArtSourceId("art-1"), patchSource.id) + assertEquals(24 to -24, patchSource.offsetX to patchSource.offsetZ, "the record keeps the centered offset") + assertEquals(26 to 26, patchSource.layers.single().let { row -> row.left to row.top }, "the inventory row is in the document frame") + val patchTile = AtlasTileId("art-1/lyid:9") + val patchDrawable = placed.drawables.first { drawable -> drawable.atlasTileId == patchTile } + assertContentEquals(floatArrayOf(24f, 24f, 32f, 24f, 32f, 32f, 24f, 32f), assertNotNull(patchDrawable.mesh).positions, "the birth quad sits at the placed position") + assertEquals(64f to 64f, placed.canvasWidth to placed.canvasHeight, "the canvas is the first file's still") + + // Align to the top-left with a 3 px nudge along x and 5 px UP along Z re-lands the SAME step at + // offset (3, 5): z is up, so the quad's canvas y drops by 5. + val record = assertNotNull(session.adjustableOperation.value, "the add registered on the strip") + assertEquals(listOf(ImportParameterKeys.ALIGN, ImportParameterKeys.OFFSET_X, ImportParameterKeys.OFFSET_Z, ImportParameterKeys.ALPHA_THRESHOLD, ImportParameterKeys.MARGIN), record.parameters.map { parameter -> parameter.key }) + val adjusted = + record.parameters.map { parameter -> + when { + parameter.key == ImportParameterKeys.ALIGN && parameter is OperatorParameter.ChoiceParameter -> parameter.copy(value = ArtworkAnchor.TopLeft.key) + parameter.key == ImportParameterKeys.OFFSET_X && parameter is OperatorParameter.IntParameter -> parameter.copy(value = 3) + parameter.key == ImportParameterKeys.OFFSET_Z && parameter is OperatorParameter.IntParameter -> parameter.copy(value = 5) + else -> parameter + } + } + session.adjustLastOperation(adjusted) + withTimeout(120_000) { + while (session.model.value.sources.first { source -> source.name == "patch.png" }.offsetX != 3) { + yield() + } + } + val realigned = session.model.value + val realignedSource = realigned.sources.first { source -> source.name == "patch.png" } + assertEquals(3 to 5, realignedSource.offsetX to realignedSource.offsetZ, "the anchor's placement plus the nudge, in the world axes") + assertContentEquals(floatArrayOf(3f, -5f, 11f, -5f, 11f, 3f, 3f, 3f), assertNotNull(realigned.drawables.first { drawable -> drawable.atlasTileId == patchTile }.mesh).positions) + val shownRows = assertNotNull(session.adjustableOperation.value).parameters + assertEquals(5, (shownRows.first { parameter -> parameter.key == ImportParameterKeys.OFFSET_Z } as OperatorParameter.IntParameter).value, "the row still reads as the Z the rigger typed") + assertEquals(placed.drawables.size, realigned.drawables.size, "re-landed, not added twice") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== realigned.atlas) { + yield() + } + } + + // The file read again and placed by its record: nothing changed, nothing pushed. + val reread = ReloadArtworkRequest(listOf(ReloadEntry(realignedSource.id, patchArt.placedFor(realignedSource), contentHash = "same")), options) + assertEquals(ReloadArtworkResult.NothingChanged, runReloadArtwork(host, reread, areaId = null), "a placed read matches the placed inventory") + assertSame(realigned, session.model.value) + + // Repainted in its own frame, it re-borns at the PLACED position and the record keeps the offset. + val repainted = InMemoryArt(listOf(InMemoryLayer("lyid:9", "Patch", 0, LayerBounds(2, 2, 6, 6), solidRaster(6, 6, 7))), widthPx = 16, heightPx = 16) + val reload = ReloadArtworkRequest(listOf(ReloadEntry(realignedSource.id, repainted.placedFor(realignedSource), contentHash = "v2")), options) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, reload, areaId = null)) + val reloaded = session.model.value + val reloadedSource = reloaded.sources.first { source -> source.name == "patch.png" } + assertEquals(3 to 5, reloadedSource.offsetX to reloadedSource.offsetZ, "the reload keeps the record's offset") + assertEquals(5 to -3, reloadedSource.layers.single().let { row -> row.left to row.top }) + assertNull(reloaded.atlas.tileById[patchTile], "the changed tile is replaced") + val reborn = reloaded.drawables.first { drawable -> drawable.atlasTileId == AtlasTileId("art-1/lyid:9~1") } + assertContentEquals(floatArrayOf(3f, -5f, 13f, -5f, 13f, 5f, 3f, 5f), assertNotNull(reborn.mesh).positions, "re-born over the wider art, still placed") + + session.undo() + assertSame(realigned, session.model.value, "undo restores the placed model") + follower.cancel() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ReloadArtworkFlowTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ReloadArtworkFlowTest.kt new file mode 100644 index 0000000..5e4d593 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ReloadArtworkFlowTest.kt @@ -0,0 +1,460 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.DocumentChange +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.edit.commitArtworkReloaded +import org.umamo.edit.withAtlasRepack +import org.umamo.format.FileKind +import org.umamo.format.art.LayerBounds +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.render.deriveAtlasTextures +import org.umamo.runtime.model.ArtSourceId +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.OrgChild +import org.umamo.runtime.model.SourceLayerRef +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.ImportParameterKeys +import org.umamo.ui.model.MatchParameterKeys +import org.umamo.ui.model.RelinkArtworkRequest +import org.umamo.ui.model.ReloadArtworkRequest +import org.umamo.ui.model.ReloadArtworkResult +import org.umamo.ui.model.ReloadEntry +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.runRelinkArtwork +import org.umamo.ui.model.runReloadArtwork +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Reload and relink driven the way the shell drives them, over a document built from in-memory art + * so no corpus is needed: a repainted and grown layer, an unchanged one, and a new one land as one + * step; the pages the session publishes equal their derivation; undo shows the old pixels again by + * pure snapshot; an adjustment re-lands the step; a reload with nothing changed pushes nothing; a + * relink pulls the target layer's art when its file is read and changes the binding alone when not; + * and a layer re-created under a new key is rebound in the reload at the strip's bar. + */ +class ReloadArtworkFlowTest { + private val options = SourceArtImportOptions(alphaThreshold = 1, birthMeshMargin = 2) + private val sourceId = ArtSourceId("art-0") + + private val layerA = InMemoryLayer("lyid:1", "A", 0, LayerBounds(10, 10, 8, 8), solidRaster(8, 8, 1)) + private val layerB = InMemoryLayer("lyid:2", "B", 1, LayerBounds(40, 40, 8, 8), solidRaster(8, 8, 2)) + private val layerARepainted = InMemoryLayer("lyid:1", "A", 0, LayerBounds(10, 10, 12, 12), solidRaster(12, 12, 9)) + + /** Inserted at the TOP of the file (above A and B), the way an artist adds a layer in Photoshop. */ + private val layerC = InMemoryLayer("lyid:3", "C", -1, LayerBounds(5, 50, 6, 6), solidRaster(6, 6, 3)) + + /** + * A layer the file lost leaves its tile exactly as it was: same placement, same pages, same + * coordinates - a reload with nothing to pack touches no page. Exercised with the added layer on a + * SECOND page, the way a full first page forces it, since that is where a re-pack that dropped or + * re-indexed pages would strand the tile. + */ + @Test + fun aRemovedLayerLeavesItsTileAndThePagesUntouched() = + runBlocking { + // Two layers that fill the first page's width, so a third that fits a page but not the gaps + // takes a second page. + val wide = InMemoryLayer("lyid:1", "Wide", 0, LayerBounds(0, 0, 110, 110), solidRaster(110, 110, 1)) + val corner = InMemoryLayer("lyid:2", "Corner", 1, LayerBounds(114, 0, 8, 8), solidRaster(8, 8, 2)) + val load = buildArtDocument(InMemoryArt(listOf(wide, corner)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the reload must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val big = InMemoryLayer("lyid:9", "Big", 2, LayerBounds(0, 120, 30, 30), solidRaster(30, 30, 7)) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(wide, corner, big)), contentHash = "v2")), options), areaId = null)) + val packedOnce = session.model.value + val bigTile = packedOnce.atlas.tiles.first { tile -> tile.source?.layerKey == "lyid:9" } + assertNotNull(bigTile.placement, "the added layer was packed") + // A page that shrinks to a power of two always leaves a hole, so the second page is made by + // hand: the tile moved there through the repack edit (its coordinates re-derived with it). + val movedPlacement = AtlasPlacement(1, 2f, 2f, 1f, 1f, 0f) + val placements = packedOnce.atlas.tiles.associate { tile -> tile.id to (if (tile.id == bigTile.id) movedPlacement else tile.placement) } + val withBig = session.commitArtworkReloaded(DocumentChange.ReloadArtwork(1, 0, 0, 0, 0), packedOnce.withAtlasRepack(packedOnce.atlas.pages + AtlasPage(256, 256), placements, packedOnce.atlas.composition)) + val bigPlacement = assertNotNull(withBig.atlas.tileById.getValue(bigTile.id).placement) + assertEquals(2, withBig.atlas.pages.size, "onto a second page") + assertEquals(1, bigPlacement.pageIndex) + val bigDrawable = withBig.drawables.first { drawable -> drawable.atlasTileId == bigTile.id } + val uvsBefore = assertNotNull(bigDrawable.mesh).uvs.copyOf() + val uvWidth = (0 until uvsBefore.size / 2).let { vertices -> vertices.maxOf { vertex -> uvsBefore[vertex * 2] } - vertices.minOf { vertex -> uvsBefore[vertex * 2] } } + assertEquals(34f / 256f, uvWidth, 1e-3f, "the coordinates span the birth quad (the tile plus its 2 px margin) on its 256 page") + + // The layer is deleted in the file: its tile, page, and coordinates must all stand. + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(wide, corner)), contentHash = "v3")), options), areaId = null)) + val withoutBig = session.model.value + assertEquals(withBig.atlas.pages, withoutBig.atlas.pages, "no page appeared, vanished, or resized") + val keptTile = assertNotNull(withoutBig.atlas.tileById[bigTile.id], "the tile is kept, not replaced") + assertEquals(bigPlacement, keptTile.placement, "and stays where it was") + assertEquals(withBig.atlas.tiles.map { tile -> tile.id to tile.placement }, withoutBig.atlas.tiles.map { tile -> tile.id to tile.placement }, "every placement stands") + assertContentEquals(uvsBefore, assertNotNull(withoutBig.drawables.first { drawable -> drawable.atlasTileId == bigTile.id }.mesh).uvs, "the coordinates stand") + assertEquals(false, withoutBig.sources.single().layers.first { layer -> layer.key == "lyid:9" }.present, "the row is kept for review") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== withoutBig.atlas) { + yield() + } + } + val published = sessionAtlasPages.binding.value.textures + val derived = assertNotNull(deriveAtlasTextures(withoutBig, document.artRasters, premultipliedAlpha = false)) + assertEquals(2, published.atlases.size) + for ((pageIndex, page) in published.atlases.withIndex()) { + assertTrue(page.rgba.contentEquals(derived.atlases[pageIndex].rgba), "published page $pageIndex equals its derivation") + } + follower.cancel() + } + + @Test + fun aReloadLandsTheChangedLayersAsOneStepAndUndoShowsTheOldArt() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(layerA, layerB)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the reload must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + val tileA = AtlasTileId("art-0/lyid:1") + val tileB = AtlasTileId("art-0/lyid:2") + val placementB = assertNotNull(before.atlas.tileById.getValue(tileB).placement) + val drawableA = before.drawables.first { drawable -> drawable.atlasTileId == tileA } + + val request = ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(layerARepainted, layerB, layerC)), contentHash = "hash-v2")), options) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, request, areaId = null), "the reload lands") + val reloaded = session.model.value + val tileA1 = AtlasTileId("art-0/lyid:1~1") + assertEquals(listOf(tileB, tileA1, AtlasTileId("art-0/lyid:3")), reloaded.atlas.tiles.map { tile -> tile.id }, "the changed tile is replaced, the new layer appended") + assertEquals(placementB, reloaded.atlas.tileById.getValue(tileB).placement, "the unchanged tile did not move") + assertNotNull(reloaded.atlas.tileById.getValue(tileA1).placement, "the replacement is placed") + assertEquals(tileA, reloaded.atlas.tileById.getValue(tileA1).replaces) + assertEquals(12, reloaded.atlas.tileById.getValue(tileA1).width) + val carriedA = reloaded.drawables.first { drawable -> drawable.id == drawableA.id } + assertEquals(tileA1, carriedA.atlasTileId, "the drawable moved onto the replacement") + assertEquals(3, reloaded.drawables.size, "the new layer became a drawable") + assertEquals(OrgChild.Drawable(DrawableId("ArtMesh3")), reloaded.rootChildren.first(), "placed first, where the file put it, so it draws in front") + assertEquals(listOf("lyid:3", "lyid:1", "lyid:2"), reloaded.sources.single().layers.map { layer -> layer.key }, "the inventory reads in the file's order, the new top layer first") + assertEquals("hash-v2", reloaded.sources.single().contentHash, "the record carries the hash the reload read") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== reloaded.atlas) { + yield() + } + } + val published = sessionAtlasPages.binding.value.textures + val derived = assertNotNull(deriveAtlasTextures(reloaded, document.artRasters, premultipliedAlpha = false), "the reloaded model derives") + for ((pageIndex, page) in published.atlases.withIndex()) { + assertTrue(page.rgba.contentEquals(derived.atlases[pageIndex].rgba), "published page $pageIndex equals its derivation") + } + assertTrue(published.atlases.any { page -> page.rgba.any { byte -> byte == 9.toByte() } }, "the pages carry the repainted pixels") + + // An adjustment re-lands the SAME step with wider re-born quads. Before any undo, which + // retires the record. + val record = assertNotNull(session.adjustableOperation.value, "the reload registered on the strip") + val quadBefore = assertNotNull(carriedA.mesh).positions.copyOf() + val widened = record.parameters.map { parameter -> if (parameter.key == ImportParameterKeys.MARGIN && parameter is OperatorParameter.IntParameter) parameter.copy(value = parameter.value + 6) else parameter } + session.adjustLastOperation(widened) + withTimeout(120_000) { + while (session.model.value.drawables.first { drawable -> drawable.id == drawableA.id }.mesh?.positions?.contentEquals(quadBefore) != false) { + yield() + } + } + val quadAfter = assertNotNull(session.model.value.drawables.first { drawable -> drawable.id == drawableA.id }.mesh).positions + assertEquals(quadBefore[0] - 6f, quadAfter[0], 1e-3f, "the re-born quad's left edge moved out by the margin change") + + // One step: undo restores the whole model, and the resolver shows the pages as imported again. + session.undo() + assertSame(before, session.model.value, "undo restores the model as it was") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== before.atlas) { + yield() + } + } + assertSame(document.textures, sessionAtlasPages.binding.value.textures, "the old pixels come back with the baseline pages") + session.redo() + assertEquals(3, session.model.value.drawables.size, "redo brings the reload back") + + // Nothing changed since: no step, the model untouched. + val settled = session.model.value + assertEquals( + ReloadArtworkResult.NothingChanged, + runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(layerARepainted, layerB, layerC)), contentHash = "hash-v3")), options), areaId = null), + "a save that changed bytes but no layer plans nothing", + ) + assertSame(settled, session.model.value) + assertEquals("hash-v2", session.model.value.sources.single().contentHash, "and the record keeps the hash of the reload that landed") + + // A relink to another layer of the read file pulls that layer's art; without the file it + // changes the binding alone. + val tileC = AtlasTileId("art-0/lyid:3") + val refB = SourceLayerRef(sourceId, "lyid:2", true) + assertTrue(runRelinkArtwork(host, RelinkArtworkRequest(tileC, refB, InMemoryArt(listOf(layerARepainted, layerB, layerC)), options), areaId = null)) + val relinked = session.model.value + assertNull(relinked.atlas.tileById[tileC], "the relinked tile was replaced") + val pulled = relinked.atlas.tiles.first { tile -> tile.replaces == tileC } + assertEquals(refB, pulled.source) + assertEquals(8, pulled.width, "with the target layer's art") + val refA = SourceLayerRef(sourceId, "lyid:1", true) + assertFalse(runRelinkArtwork(host, RelinkArtworkRequest(pulled.id, refA, art = null, options), areaId = null), "no file, no art") + assertEquals(refA, session.model.value.atlas.tileById.getValue(pulled.id).source, "but the binding changed") + follower.cancel() + } + + /** + * A layer's eye toggle in the file follows into the drawable over it while that drawable still shows + * the state the file last had - a step of its own, with no tile replaced and nothing packed - and + * follows back when the layer is shown again. + */ + @Test + fun aLayerEyeToggleFollowsIntoTheDrawableAndBack() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(layerA, layerB)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = null, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the reload must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + val tileB = AtlasTileId("art-0/lyid:2") + val drawableB = before.drawables.first { drawable -> drawable.atlasTileId == tileB } + assertTrue(drawableB.isVisible) + + val layerBHidden = InMemoryLayer("lyid:2", "B", 1, LayerBounds(40, 40, 8, 8), solidRaster(8, 8, 2), visible = false) + val hide = ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(layerA, layerBHidden)), contentHash = "hash-hidden")), options) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, hide, areaId = null), "an eye toggle alone is a step") + val hidden = session.model.value + assertFalse(hidden.drawables.first { drawable -> drawable.id == drawableB.id }.isVisible, "the untouched drawable followed the file") + assertEquals(before.atlas.tiles.map { tile -> tile.id }, hidden.atlas.tiles.map { tile -> tile.id }, "no tile changed") + assertEquals(false, hidden.sources.single().layers.first { layer -> layer.key == "lyid:2" }.visible, "the inventory records the new state") + + val show = ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(layerA, layerB)), contentHash = "hash-shown")), options) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, show, areaId = null)) + assertTrue(session.model.value.drawables.first { drawable -> drawable.id == drawableB.id }.isVisible, "shown again in the file, it follows back") + session.undo() + session.undo() + assertSame(before, session.model.value, "two steps, both undone") + } + + @Test + fun aReloadAfterAnUndoReusesTheReplacementIdAndTheStoreServesTheNewPixels() = + runBlocking { + // The replacement id is minted past the ids the model holds, so reload, undo, reload mints + // `~1` twice. The raster store is document-lifetime and its cached read (the UV editor's pick + // surface) may have answered `~1` after the first reload; it must answer the second's pixels now. + val load = buildArtDocument(InMemoryArt(listOf(layerA, layerB)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the reload must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + val tileA1 = AtlasTileId("art-0/lyid:1~1") + + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(layerARepainted, layerB)), "hash-v2")), options), areaId = null)) + assertTrue(session.model.value.atlas.tileById.containsKey(tileA1)) + val firstPixels = assertNotNull(document.artRasters.rasterFor(tileA1), "the cached read answers the first reload") + assertEquals(9.toByte(), firstPixels.rgba[0]) + session.undo() + assertSame(before, session.model.value) + + val repaintedAgain = InMemoryLayer("lyid:1", "A", 0, LayerBounds(10, 10, 10, 10), solidRaster(10, 10, 7)) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(repaintedAgain, layerB)), "hash-v3")), options), areaId = null)) + assertTrue(session.model.value.atlas.tileById.containsKey(tileA1), "the replacement id is minted again") + assertEquals(10, session.model.value.atlas.tileById.getValue(tileA1).width) + val secondPixels = assertNotNull(document.artRasters.rasterFor(tileA1), "the cached read answers the second reload") + assertEquals(7.toByte(), secondPixels.rgba[0], "with the second reload's pixels, not the cached first") + assertEquals(10, secondPixels.width) + assertSame(secondPixels, document.artRasters.decodeRaster(tileA1), "one instance from both reads") + follower.cancel() + } + + @Test + fun tilesBoundToOneLostKeyRelinkTogetherAsOneStep() = + runBlocking { + // Two tiles under one binding, the shape a review row's Accept acts on: relinked in one request + // they land as one step (a request per tile would race, each superseding the next), with the + // file and without it. + val load = buildArtDocument(InMemoryArt(listOf(layerA, layerB)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the relink must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val tileA = AtlasTileId("art-0/lyid:1") + val tileB = AtlasTileId("art-0/lyid:2") + val refC = SourceLayerRef(sourceId, "lyid:3", true) + val before = session.model.value + + assertTrue(runRelinkArtwork(host, RelinkArtworkRequest(listOf(tileA, tileB), refC, InMemoryArt(listOf(layerA, layerB, layerC)), options), areaId = null)) + val relinked = session.model.value + assertEquals(listOf(tileA, tileB), relinked.atlas.tiles.mapNotNull { tile -> tile.replaces }, "both tiles were replaced") + assertTrue(relinked.atlas.tiles.all { tile -> tile.source == refC }, "both carry the new binding") + assertTrue(relinked.atlas.tiles.all { tile -> tile.width == 6 }, "both took the target layer's art") + session.undo() + assertSame(before, session.model.value, "one step for both") + assertFalse(session.canUndo.value) + + // Without the file only the bindings change, still as one step. + assertFalse(runRelinkArtwork(host, RelinkArtworkRequest(listOf(tileA, tileB), refC, art = null, options), areaId = null)) + assertTrue(session.model.value.atlas.tiles.all { tile -> tile.source == refC }) + session.undo() + assertSame(before, session.model.value) + assertFalse(session.canUndo.value) + follower.cancel() + } + + /** + * A layer deleted and re-created under a new key with its pixels and place - Photoshop's duplicate, + * delete the original, rename - reloads as one step that rebinds the rigged tile instead of minting + * a fresh drawable beside it, and the strip leads with the Match Threshold row that decided it. + */ + @Test + fun aReCreatedLayerReloadsAsARebindingWithTheThresholdRowFirst() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(layerA, layerB)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the reload must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val tileA = AtlasTileId("art-0/lyid:1") + val recreatedA = InMemoryLayer("lyid:3", "A", 0, LayerBounds(10, 10, 8, 8), layerA.raster) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(recreatedA, layerB)), contentHash = "v2")), options), areaId = null)) + val reloaded = session.model.value + assertEquals(2, reloaded.drawables.size, "nothing was minted") + val rebound = reloaded.atlas.tiles.first { tile -> tile.replaces == tileA } + assertEquals("lyid:3", rebound.source?.layerKey, "the rigged tile follows the re-created layer") + assertNotNull(rebound.placement, "and is packed") + assertEquals(listOf("lyid:3", "lyid:2"), reloaded.sources.single().layers.map { layer -> layer.key }, "no lost row") + assertTrue(reloaded.sources.single().layers.all { layer -> layer.present }) + val notice = assertNotNull(session.notice.value) + assertEquals("notice.reload.done", notice.messageKey) + assertEquals(listOf("1", "0", "1", "0"), notice.arguments, "one updated, none added, one matched, none missing") + val record = assertNotNull(session.adjustableOperation.value, "the reload registered on the strip") + assertEquals(MatchParameterKeys.THRESHOLD, record.parameters.first().key, "the strip leads with the bar") + assertEquals("change.document.reloadArtwork", session.historyView.value.let { view -> view.steps[view.cursor].labelKey }) + follower.cancel() + } + + /** + * A re-created layer repainted at the same place scores under certain: raising the reload's bar to + * 100% re-lands the same step with the layer minted and the binding left for review, and lowering + * it rebinds again - the strip and the document always agree. + */ + @Test + fun raisingTheReloadThresholdReLandsTheStepWithTheLayerMintedInstead() = + runBlocking { + val load = buildArtDocument(InMemoryArt(listOf(layerA, layerB)), FileKind.Psd, "a.psd", "/art/a.psd", options) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the reload must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + val tileA = AtlasTileId("art-0/lyid:1") + val repaintedA = InMemoryLayer("lyid:3", "A", 0, LayerBounds(10, 10, 8, 8), solidRaster(8, 8, 3)) + assertEquals(ReloadArtworkResult.Applied, runReloadArtwork(host, ReloadArtworkRequest(listOf(ReloadEntry(sourceId, InMemoryArt(listOf(repaintedA, layerB)), contentHash = "v2")), options), areaId = null)) + assertEquals(2, session.model.value.drawables.size, "rebound at the default bar") + assertTrue(session.model.value.atlas.tiles.any { tile -> tile.replaces == tileA }) + val record = assertNotNull(session.adjustableOperation.value) + + val raised = record.parameters.map { parameter -> if (parameter.key == MatchParameterKeys.THRESHOLD && parameter is OperatorParameter.FloatParameter) parameter.copy(value = 100f) else parameter } + session.adjustLastOperation(raised) + withTimeout(120_000) { + while (session.model.value.drawables.size != 3) { + yield() + } + } + val minted = session.model.value + assertNotNull(minted.atlas.tileById[tileA], "the old tile stands, unreplaced") + assertNotNull(minted.atlas.tileById[AtlasTileId("art-0/lyid:3")], "the layer was minted") + assertEquals(false, minted.sources.single().layers.first { layer -> layer.key == "lyid:1" }.present, "the binding waits for review") + assertEquals("change.document.reloadArtwork", session.historyView.value.let { view -> view.steps[view.cursor].labelKey }) + + val lowered = record.parameters.map { parameter -> if (parameter.key == MatchParameterKeys.THRESHOLD && parameter is OperatorParameter.FloatParameter) parameter.copy(value = 70f) else parameter } + session.adjustLastOperation(lowered) + withTimeout(120_000) { + while (session.model.value.drawables.size != 2) { + yield() + } + } + assertTrue(session.model.value.atlas.tiles.any { tile -> tile.replaces == tileA }, "rebound again") + session.undo() + assertSame(before, session.model.value, "one step throughout") + follower.cancel() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ReloadedCmo3ExportGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ReloadedCmo3ExportGateTest.kt new file mode 100644 index 0000000..85a7930 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/ReloadedCmo3ExportGateTest.kt @@ -0,0 +1,247 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import org.umamo.edit.EditorSession +import org.umamo.format.art.LayerBounds +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CLayer +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.cmo3.model.custom.CWritableImage +import org.umamo.format.cmo3.model.gen.ACLayerGroup +import org.umamo.format.cmo3.model.gen.CImageIcon +import org.umamo.format.cmo3.model.gen.CLayeredImage +import org.umamo.format.cmo3.model.gen.CTextureManager +import org.umamo.format.cmo3.model.gen.LayeredImageWrapper +import org.umamo.format.cmo3.model.identity.Guid +import org.umamo.format.png.PngCodec +import org.umamo.interop.ExportNotice +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.art.SourceArtImportOptions +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasPages +import org.umamo.interop.cmo3.cmo3SourceArtOf +import org.umamo.render.encodeAtlasPng +import org.umamo.runtime.model.lineageRoot +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.RelinkArtworkRequest +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.runRelinkArtwork +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertTrue + +/** + * A CMO3-origin document with a reloaded tile still exports through its retained graph: the + * reloaded tile is a NEW tile in the model, and the atlas web has to read it as the entry its lineage + * root imported from - moved to the replacement's placement - rather than as a pack-in with no model + * image, which would decline the whole reconcile. The pages carry the new pixels, and so does the + * retained layer the root's model image composites, so the official editor's layered view shows the + * reloaded art. + * + * Skips without the corpus sample. + */ +class ReloadedCmo3ExportGateTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aReloadedTileExportsAsItsLineageRootMoving() = + runBlocking { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the reloaded export gate") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the relink must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + // A placed tile bound by a stable key with a drawable over it: the art the reload replaces. + val tile = + before.atlas.tiles.first { candidate -> + candidate.placement != null && candidate.source?.stableKey == true && before.drawables.any { drawable -> drawable.atlasTileId == candidate.id } + } + val ref = assertNotNull(tile.source) + val row = before.sources.first { source -> source.id == ref.sourceId }.layers.first { layer -> layer.key == ref.layerKey } + // The same layer, the same size, repainted: only the pixels differ, so the graph reconcile + // owes nothing but the page patch. + val repainted = InMemoryLayer(ref.layerKey, row.name, 0, LayerBounds(row.left, row.top, tile.width, tile.height), solidRaster(tile.width, tile.height, 0x5A)) + val request = RelinkArtworkRequest(tile.id, ref, InMemoryArt(listOf(repainted), before.canvasWidth.toInt(), before.canvasHeight.toInt()), SourceArtImportOptions()) + assertTrue(runRelinkArtwork(host, request, areaId = null), "the reload pulls the repainted art") + val reloaded = session.model.value + val replacement = reloaded.atlas.tiles.first { candidate -> candidate.replaces == tile.id } + assertEquals(tile.id, replacement.id.lineageRoot) + val newPlacement = assertNotNull(replacement.placement, "the replacement is placed") + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== reloaded.atlas) { + yield() + } + } + val effective = sessionAtlasPages.binding.value.textures + assertNotSame(document.textures, effective, "the resolver published the reload's pages") + + val prepared = + prepareCmo3Export( + document = document, + edited = exportedModelFor(document, session), + effectiveTextures = effective, + modelName = "gate", + nowMillis = 0L, + obfuscateKey = 0, + ) + follower.cancel() + println("export report: ${prepared.report}") + assertTrue( + prepared.report.notices.none { notice -> notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.AtlasPageNotRecomposed }, + "the atlas web reconciled the reloaded tile rather than declining", + ) + assertTrue( + prepared.report.notices.none { notice -> notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.AtlasTileRebindingNotLowered }, + "the drawables over the replacement are not rebindings as far as the graph knows", + ) + assertTrue( + prepared.report.notices.none { notice -> notice is ExportNotice.UnsupportedChange && notice.reason == ExportNoticeReason.AtlasTileMetadataNotReconcilable }, + "the reloaded tile's metadata is reconciled by the layer rewrite", + ) + + val reread = Cmo3.read(Cmo3.write(prepared.model)) + val reimported = Cmo3Import.fromModelSource(reread.root as CModelSource) + assertEquals(newPlacement, reimported.atlas.tileById.getValue(tile.id).placement, "the root's entry moved to the replacement's placement") + // The retained layer holds the repainted pixels: the layered-art reader decodes them back + // out of the root's own layer, keyed as the reload keyed it. + val rereadArt = assertNotNull(cmo3SourceArtOf(reread.root as CModelSource, ref.sourceId) { resource -> reread.extractLayerPng(resource) }, "the file reads back") + val rereadLayer = assertNotNull(rereadArt.layers.firstOrNull { layer -> layer.id.raw == ref.layerKey }, "the reloaded layer is listed under its key") + assertEquals(tile.width to tile.height, rereadLayer.raster.width to rereadLayer.raster.height) + assertTrue(rereadLayer.raster.rgba.contentEquals(repainted.raster.rgba), "the layer's pixels are the repainted ones") + // So is the layer's icon: every opaque pixel of the 64px thumbnail is the repainted gray. + val rereadImage = + assertNotNull( + graphElements((reread.root as CModelSource).textureManager.let { manager -> (manager as CTextureManager)._rawImages }) + .mapNotNull { wrapper -> (wrapper as? LayeredImageWrapper)?.image as? CLayeredImage } + .firstOrNull { image -> (image.guid as? Guid)?.uuid == ref.sourceId.raw }, + "the file's layered image reads back", + ) + val rereadCLayer = assertNotNull(layersOf(rereadImage).firstOrNull { layer -> layer.name == row.name }, "the reloaded layer is in the tree") + val iconPath = assertNotNull(((rereadCLayer.icon64 as? CImageIcon)?.image as? CWritableImage)?.image?.archivePath, "the layer has a 64px icon") + val icon = PngCodec.read(assertNotNull(reread.archive.byPath(iconPath), "the icon is embedded").content) + var opaquePixels = 0 + for (pixel in 0 until icon.width * icon.height) { + if ((icon.rgba[pixel * 4 + 3].toInt() and 0xFF) == 255) { + opaquePixels += 1 + assertEquals(listOf(0x5A, 0x5A, 0x5A), (0 until 3).map { channel -> icon.rgba[pixel * 4 + channel].toInt() and 0xFF }, "icon pixel $pixel is the repainted gray") + } + } + assertTrue(opaquePixels > 0, "the icon shows the repainted art") + val exportedPages = cmo3AtlasPages(reread.root as CModelSource) { resource -> reread.extractLayerPng(resource) }.pageBytes + val expectedPages = effective.atlases.map { page -> encodeAtlasPng(page) } + assertEquals(expectedPages.size, exportedPages.size, "exported page count") + for ((pageIndex, bytes) in exportedPages.withIndex()) { + assertTrue(expectedPages.any { expected -> expected.contentEquals(bytes) }, "exported page $pageIndex is not one of the reload's pages") + } + } + + /** + * Every image layer under a layered image's root, depth first. + * + * @param CLayeredImage image The layered image. + * @return List The layers. + */ + private fun layersOf(image: CLayeredImage): List { + val layers = ArrayList() + + fun walk(group: ACLayerGroup) { + for (entry in graphElements(group._children)) { + when (entry) { + is ACLayerGroup -> walk(entry) + is CLayer -> layers.add(entry) + } + } + } + (image._rootLayer as? ACLayerGroup)?.let(::walk) + return layers + } + + /** + * A CMO3 collection field as its elements, whichever container shape the serializer used. + * + * @param Any? collection The raw field. + * @return List The elements. + */ + private fun graphElements(collection: Any?): List = + when (collection) { + is Map<*, *> -> collection.values.toList() + is Iterable<*> -> collection.toList() + is Array<*> -> collection.toList() + else -> emptyList() + } + + /** + * A relink on a CMO3-origin document whose file is not on this machine reads the target layer + * from the CMO3's own decomposed layer image: the tile is replaced with that layer's pixels at + * the layer's size, not merely rebound. + */ + @Test + fun aRelinkReadsTheDecomposedLayerWhenTheFileIsMissing() = + runBlocking { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the decomposed relink gate") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = + AtlasRepackHost( + session = session, + artRasters = document.artRasters, + sessionAtlasPages = sessionAtlasPages, + premultipliedAlpha = document.textures.premultipliedAlpha, + scope = this, + report = { report -> error("the relink must not refuse: ${report.refusals.joinToString { "${it.tileName}: ${it.reason}" }}") }, + rememberOptions = { _, _ -> }, + ) + val before = session.model.value + // Two placed, stably bound tiles of one file: the first is rebound to the second's layer. + val bound = before.atlas.tiles.filter { tile -> tile.placement != null && tile.source?.stableKey == true } + val tile = bound.first() + val target = bound.first { candidate -> candidate.source?.sourceId == tile.source?.sourceId && candidate.source?.layerKey != tile.source?.layerKey } + val targetRef = assertNotNull(target.source) + // Read the way the app's relink reads it: the artist's file is not on this machine, so the read + // falls back to the layers the official editor decomposed into the CMO3. + val listed = before.sources.first { source -> source.id == targetRef.sourceId } + val read = assertNotNull(readSourceArt(document, listed) { false }, "the file reads back from the CMO3") + assertTrue(read.fromCmo3) + val art = read.art + assertTrue(runRelinkArtwork(host, RelinkArtworkRequest(tile.id, targetRef, art, SourceArtImportOptions()), areaId = null), "the relink pulls the decomposed layer") + val relinked = session.model.value + val replacement = relinked.atlas.tiles.first { candidate -> candidate.replaces == tile.id } + assertEquals(targetRef, replacement.source) + val targetLayer = art.layers.first { layer -> layer.id.raw == targetRef.layerKey } + assertEquals(targetLayer.raster.width, replacement.width, "the replacement is the target layer's size") + assertEquals(targetLayer.raster.height, replacement.height) + val pulled = assertNotNull(document.artRasters.decodeRaster(replacement.id), "the target layer's pixels joined the store") + assertTrue(pulled.rgba.contentEquals(targetLayer.raster.rgba), "with the decomposed layer's own bytes") + follower.cancel() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/SourceReadTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/SourceReadTest.kt new file mode 100644 index 0000000..8d53adc --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/SourceReadTest.kt @@ -0,0 +1,94 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.runBlocking +import org.umamo.format.art.LayerBounds +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.runtime.model.ArtSource +import org.umamo.runtime.model.ArtSourceId +import java.io.File +import kotlin.io.path.createTempDirectory +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Pins where an artwork operation reads a listed file's art from when the file itself is out of reach. + * + * A CMO3 carries the layers the official editor decomposed out of the artist's file, so a relink or a + * Match Automatically on a CMO3-origin document still has the art to work with on a machine that never + * had the PSD. Any other origin has nothing to fall back to, and must say so with a null rather than + * guess. A file that is there is placed by its record's offset. The CMO3 case skips without the + * corpus sample. + */ +class SourceReadTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + @Test + fun aMissingFileOnACmo3DocumentReadsTheDecomposedLayers() = + runBlocking { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the decomposed source read gate") + return@runBlocking + } + val load = loadDocument(file.readBytes(), file.name, file.path) + val document = assertIs(assertIs(load).document) + val source = assertNotNull(document.puppet.sources.firstOrNull(), "the sample lists the artwork file it was rigged from") + // The artist's file is recorded at a path from the machine it was rigged on; here it reads as missing. + val probed = ArrayList() + + val read = + readSourceArt(document, source) { path -> + probed.add(path) + false + } + + val fromDocument = assertNotNull(read, "the CMO3's own layers stand in for the file") + assertTrue(fromDocument.fromCmo3) + assertTrue(fromDocument.art.layers.isNotEmpty(), "with the layers the official editor decomposed") + assertNull(fromDocument.contentHash, "no file was read, so there is no file hash to record") + assertNull(fromDocument.lastModified) + assertTrue(source.path == null || probed == listOf(source.path), "the recorded path is asked about once, and nothing else is") + } + + /** + * A listed file read from disk is placed by its record's offset before any operation sees it, so its + * layers sit where the document's inventory says they do; a record at offset zero reads as-is. + */ + @Test + fun aFileOnDiskIsPlacedByItsRecord() = + runBlocking { + val folder = createTempDirectory("umamo-source-read").toFile() + try { + val file = File(folder, "patch.png") + val rgba = ByteArray(4 * 3 * 4) { index -> if (index % 4 == 3) 0xFF.toByte() else 0x40 } + file.writeBytes(PngCodec.write(RasterImage(4, 3, rgba))) + val placed = ArtSource(ArtSourceId("art-1"), name = "patch.png", path = file.path, format = "png", offsetX = 30, offsetZ = 5) + + val read = assertNotNull(readSourceArt(newBlankDocument(), placed)) + assertTrue(!read.fromCmo3) + assertEquals(LayerBounds(30, -5, 4, 3), read.art.layers.single().bounds, "the flat raster's one layer sits at the record's offset, 5 px UP being canvas y -5") + assertNotNull(read.contentHash, "a disk read records its hash") + + val unplaced = assertNotNull(readSourceArt(newBlankDocument(), placed.copy(offsetX = 0, offsetZ = 0))) + assertEquals(LayerBounds(0, 0, 4, 3), unplaced.art.layers.single().bounds) + } finally { + folder.deleteRecursively() + } + } + + @Test + fun aMissingFileOnAnyOtherDocumentReadsNothing() = + runBlocking { + val document = newBlankDocument() + val source = ArtSource(ArtSourceId("hero"), name = "hero.psd", path = "/art/hero.psd", format = "psd") + + val read = readSourceArt(document, source) { false } + + assertNull(read, "only a CMO3 holds a copy of its artwork's layers") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaArtDocumentGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaArtDocumentGateTest.kt new file mode 100644 index 0000000..e86a184 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaArtDocumentGateTest.kt @@ -0,0 +1,240 @@ +package org.umamo.ui.document + +import org.umamo.format.art.LayerId +import org.umamo.format.art.LayerRaster +import org.umamo.format.art.SourceArt +import org.umamo.format.art.SourceLayer +import org.umamo.format.art.SourceLayerKind +import org.umamo.format.binary.contentHashOf +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.raster.fittedInto +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.UmaWriterInfo +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.interop.uma.UmaDocumentBridge +import org.umamo.reimport.ArtworkReloadPlanner +import org.umamo.reimport.ReconcileResult +import org.umamo.reimport.ReloadPlan +import org.umamo.render.SourceArtRasters +import org.umamo.render.deriveAtlasTextures +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.ui.model.DrawableThumbnailer +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The native format's promise for artwork documents, end to end through the app's own open (docs/format/UMA.md §5, + * §6): each corpus PSD, CLIP, and KRA opened packed, saved as UMA with its tiles and a thumbnail, and reopened comes + * back with the same atlas and source records; the pages composed from the reopened tiles are byte for byte the + * pages the open composed; and a reload of changed art planned before the save and one planned after the reopen are + * the same plan. + * + * Corpus-gated: the PSD / CLIP / KRA files under test/corpus found by walking up from the working directory, + * self-skipping with a printed line when none exist. + */ +class UmaArtDocumentGateTest { + private val writer = UmaWriterInfo("Umamo", "gate-test") + + /** + * A layer the artist repainted: the same layer with every color channel inverted. + * + * @property SourceLayer original The layer as it was. + */ + private class RepaintedLayer(private val original: SourceLayer) : SourceLayer by original { + override val raster: LayerRaster = + LayerRaster( + original.raster.width, + original.raster.height, + original.raster.rgba.copyOf().also { rgba -> + for (channelIndex in rgba.indices) { + if (channelIndex % 4 != 3) { + rgba[channelIndex] = (255 - (rgba[channelIndex].toInt() and 0xFF)).toByte() + } + } + }, + ) + } + + /** + * Art with its layers replaced. + * + * @property SourceArt original The art as it was. + * @property List layers The new layers. + */ + private class EditedArt(private val original: SourceArt, override val layers: List) : SourceArt by original + + /** + * A reload plan reduced to text that is equal exactly when the plans are: meshes by their arrays, rasters by their + * content hash, and everything else by its data-class form. + * + * @param ReloadPlan? plan The plan, or null when there is nothing to do. + * @return List The lines. + */ + private fun fingerprintOf(plan: ReloadPlan?): List { + if (plan == null) { + return listOf("no plan") + } + + /** + * A mesh as text. + * + * @param DrawableMesh? mesh The mesh. + * @return String The text. + */ + fun meshText(mesh: DrawableMesh?): String = mesh?.let { present -> "${present.positions.contentToString()} ${present.uvs.contentToString()} ${present.indices.contentToString()}" } ?: "none" + val reload = plan.reload + val lines = ArrayList() + lines += "source ${reload.source}" + reload.replacedTiles.forEach { replaced -> lines += "replaced ${replaced.oldId.raw} with ${replaced.tile}" } + reload.drawableMeshes.entries.sortedBy { (drawableId, _) -> drawableId.raw }.forEach { (drawableId, mesh) -> lines += "mesh ${drawableId.raw} ${meshText(mesh)}" } + reload.additions?.let { additions -> + lines += "added source ${additions.source}" + additions.tiles.forEach { tile -> lines += "added tile $tile" } + additions.drawables.forEach { drawable -> lines += "added drawable ${drawable.copy(mesh = null)} ${meshText(drawable.mesh)}" } + additions.parts.forEach { part -> lines += "added part $part" } + lines += "added root ${additions.rootChildren} insertions ${additions.insertions}" + } + lines += "outgrown ${reload.outgrown} retired ${reload.retiredTiles} visibility ${reload.drawableVisibility}" + plan.rasterByTile.entries.sortedBy { (tileId, _) -> tileId.raw }.forEach { (tileId, raster) -> lines += "raster ${tileId.raw} ${raster.width}x${raster.height} ${contentHashOf(raster.rgba)}" } + lines += "report ${plan.report.results}" + lines += "notices ${plan.notices}" + lines += "leftovers ${plan.leftovers}" + return lines + } + + /** + * Every PSD, CLIP, and KRA under test/corpus, found by walking up from the working directory. + * + * @return List The samples, empty when there is no corpus. + */ + private fun locateArtworkSamples(): List { + var directory: File? = File(System.getProperty("user.dir")) + while (directory != null) { + val corpus = File(directory, "test/corpus") + if (corpus.isDirectory) { + return listOf("psd", "clip", "krita") + .flatMap { folder -> File(corpus, folder).listFiles { file -> file.isFile }.orEmpty().toList() } + .filter { file -> file.extension.lowercase() in setOf("psd", "clip", "kra") } + .sortedBy { file -> file.name } + } + directory = directory.parentFile + } + return emptyList() + } + + /** + * Every corpus artwork file opens, saves, reopens, derives, and reloads as the promise says. + */ + @Test + fun artworkDocumentsReopenAndReloadAsSaved() { + val samples = locateArtworkSamples() + if (samples.isEmpty()) { + println("no test/corpus artwork samples; skipping the UMA artwork document gate") + return + } + val failures = ArrayList() + var openedSamples = 0 + var reloadedSamples = 0 + for (sample in samples) { + try { + when (checkSample(sample)) { + SampleOutcome.NotOpenable -> println("[Umamo][uma] ${sample.name}: the app does not open it as a document, so there is nothing to save") + SampleOutcome.Reopened -> openedSamples++ + SampleOutcome.Reloaded -> { + openedSamples++ + reloadedSamples++ + } + } + } catch (failure: AssertionError) { + failures += "${sample.name}: ${failure.message?.take(600)}" + } + } + assertTrue(failures.isEmpty(), "${failures.size} samples failed:\n${failures.joinToString("\n")}") + assertTrue(openedSamples > 0 && reloadedSamples > 0, "the gate saved $openedSamples documents and reloaded $reloadedSamples, so it compared nothing") + println("[Umamo][uma] $openedSamples artwork documents reopen as saved; $reloadedSamples reload identically after the reopen") + } + + /** How far one sample got. */ + private enum class SampleOutcome { + /** The app refuses to open the file as a document (it has no layer with pixels). */ + NotOpenable, + + /** The document saved, reopened, and derived as it should. */ + Reopened, + + /** And a reload planned after the reopen matched one planned before the save. */ + Reloaded, + } + + /** + * One sample's open, save, reopen, derivation, and reload. The file is parsed once and the document built from + * that parse, as the app's open does, so the reload leg reuses the same layers rather than holding a second copy. + * + * @param File sample The artwork file. + * @return SampleOutcome How far the sample got. + */ + private fun checkSample(sample: File): SampleOutcome { + val bytes = sample.readBytes() + val read = assertNotNull(readArtwork(bytes, sample.name), "${sample.name}: read") + val load = buildArtDocument(read.art, read.kind, sample.name, sample.path, artworkImportOptions(), read.contentHash) + if (load is DocumentLoad.Failed) { + return SampleOutcome.NotOpenable + } + val document = assertIs(assertIs(load).document) + val puppet = document.puppet + val tilePngs = puppet.atlas.tiles.associate { tile -> tile.id.raw to document.artRasters.rasterFor(tile.id)?.let { raster -> PngCodec.write(RasterImage(raster.width, raster.height, raster.rgba)) } } + val thumbnail = DrawableThumbnailer(puppet, document.textures).modelRasterFor()?.fittedInto(256)?.let(PngCodec::write) + val saved = UmaDocumentBridge.documentOf(UmaModel.create(writer), puppet, UmaPixelSource({ tileId -> tilePngs[tileId] }, UmaRenderPagePixels.Derived, thumbnail)) + val uma = Uma.read(Uma.write(saved)) + val reopened = UmaDocumentBridge.modelOf(uma) + assertEquals(puppet.atlas, reopened.atlas, "${sample.name}: the atlas") + assertEquals(puppet.sources, reopened.sources, "${sample.name}: the sources") + if (thumbnail != null) { + assertEquals(256, assertNotNull(uma.textures?.thumbnail, "${sample.name}: the thumbnail").width) + } + + val pages = UmaDocumentBridge.pagesOf(uma) + assertEquals(null, pages.pageSet, "${sample.name}: a packed artwork document's pages derive") + val reopenedRasters = SourceArtRasters.fromPng(pages.tilePng) + val derived = assertNotNull(deriveAtlasTextures(reopened, reopenedRasters, premultipliedAlpha = false), "${sample.name}: the reopened pages derive") + assertEquals(document.textures.atlases.size, derived.atlases.size, "${sample.name}: page count") + for ((pageIndex, page) in document.textures.atlases.withIndex()) { + val reopenedPage = derived.atlases[pageIndex] + assertTrue(page.width == reopenedPage.width && page.height == reopenedPage.height && page.rgba.contentEquals(reopenedPage.rgba), "${sample.name}: page $pageIndex composes from the reopened tiles byte for byte") + } + assertEquals(document.textures.atlasIndexByDrawableId, derived.atlasIndexByDrawableId, "${sample.name}: each drawable's page") + + // The reload leg: the art as the artist might save it next - the first layer repainted, the second deleted, + // and a copy of the third added under a new key. + val art = read.art + val rasterLayers = art.layers.filter { layer -> layer.kind == SourceLayerKind.Raster && puppet.atlas.tiles.any { tile -> tile.source?.layerKey == layer.id.raw } } + if (rasterLayers.size < 3) { + return SampleOutcome.Reopened + } + val added = + object : SourceLayer by rasterLayers[2] { + override val id: LayerId = LayerId("umamo-gate-added") + override val name: String = "Added by the gate" + } + val editedLayers = art.layers.mapNotNull { layer -> if (layer === rasterLayers[0]) RepaintedLayer(layer) else layer.takeIf { candidate -> candidate !== rasterLayers[1] } } + added + val editedArt = EditedArt(art, editedLayers) + val sourceId = puppet.sources.single().id + val options = artworkImportOptions() + val newHash = contentHashOf("${sample.name} saved again".encodeToByteArray()) + val before = ArtworkReloadPlanner.plan(puppet, sourceId, editedArt, options, { tileId -> document.artRasters.rasterFor(tileId)?.let { raster -> LayerRaster(raster.width, raster.height, raster.rgba) } }, newHash) + val after = ArtworkReloadPlanner.plan(reopened, sourceId, editedArt, options, { tileId: AtlasTileId -> reopenedRasters.decodeRaster(tileId)?.let { raster -> LayerRaster(raster.width, raster.height, raster.rgba) } }, newHash) + val plan = assertNotNull(before, "${sample.name}: the edited art plans a reload") + assertTrue(plan.reload.replacedTiles.isNotEmpty(), "${sample.name}: the repainted layer supersedes its tile") + assertTrue(plan.report.results.any { result -> result !is ReconcileResult.Matched }, "${sample.name}: the deleted and added layers are more than matches") + assertEquals(fingerprintOf(before), fingerprintOf(after), "${sample.name}: the reload after the reopen") + return SampleOutcome.Reloaded + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaDocumentLoadTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaDocumentLoadTest.kt new file mode 100644 index 0000000..5b2a406 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaDocumentLoadTest.kt @@ -0,0 +1,87 @@ +package org.umamo.ui.document + +import org.umamo.format.uma.Uma +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * How a `.uma` opens through the same byte-level loader every other document uses: as a UmaDocument, with + * the file kept whole for the next save; read-only when the file holds a required entry this version + * cannot interpret; and with a typed reason when it cannot open at all. Synthetic files throughout - a + * document the codec wrote from an empty rig, then rewritten by hand where a case needs a manifest this + * writer would never produce. + */ +class UmaDocumentLoadTest { + @Test + fun aUmaOpensAsAUmaDocumentKeptWholeForTheNextSave() { + val bytes = emptyDocumentBytes() + + val load = loadDocument(bytes, "rig.uma", "/rigs/rig.uma") + + val document = assertIs(assertIs(load).document) + assertEquals("/rigs/rig.uma", document.path) + assertFalse(document.isReadOnly) + assertTrue(document.puppet.drawables.isEmpty(), "the empty rig came back empty") + assertEquals(newBlankDocument().puppet.canvasWidth, document.puppet.canvasWidth, "with its canvas") + assertTrue(document.storedPages == null, "a file with no render pages derives them") + assertEquals(bytes.size, Uma.write(document.uma).size, "the file is kept whole: rewriting it costs nothing new") + } + + @Test + fun aRequiredEntryThisVersionCannotReadOpensReadOnly() { + val bytes = umaBytesWithUnknownRequiredEntry() + + val document = assertIs(assertIs(loadDocument(bytes, "rig.uma", "/rigs/rig.uma")).document) + + assertTrue(document.isReadOnly, "an unknown required entry blocks saving") + assertEquals(listOf("future/thing.json"), document.readOnlyReasons.map { reason -> reason.path }) + assertFalse(DocumentFile(document).canSave, "and the save target says so") + } + + @Test + fun aNewerContainerReportsANewerFormat() { + val bytes = + rewritten(emptyDocumentBytes()) { manifest -> + val patched = manifest.replaceFirst(Regex("\"containerVersion\":\\s*1"), "\"containerVersion\": 99") + check(patched != manifest) { "the container version was not found: $manifest" } + patched + } + + val failure = assertIs(loadDocument(bytes, "rig.uma", "/rigs/rig.uma")).failure + + assertEquals(DocumentOpenError.NewerFormat, failure.error) + assertEquals("rig.uma", failure.displayName) + } + + /** + * A puppet entry this version cannot read is a file from a newer Umamo too: there is no rig to show, and + * the message must not call a healthy file damaged. + */ + @Test + fun aNewerPuppetEntryReportsANewerFormat() { + val bytes = + rewritten(emptyDocumentBytes()) { manifest -> + // The puppet's record is the first entry: raise its version and the floor a reader must meet. + val patched = manifest.replaceFirst(Regex("\"version\":\\s*1"), "\"version\": 2").replaceFirst(Regex("\"minVersion\":\\s*1"), "\"minVersion\": 2") + check(patched != manifest) { "the puppet record was not found: $manifest" } + patched + } + + val failure = assertIs(loadDocument(bytes, "rig.uma", "/rigs/rig.uma")).failure + + assertEquals(DocumentOpenError.NewerFormat, failure.error) + } + + @Test + fun aDamagedUmaReportsAParseFailure() { + val bytes = emptyDocumentBytes() + val truncated = bytes.copyOf(bytes.size - 40) + + val failure = assertIs(loadDocument(truncated, "rig.uma", "/rigs/rig.uma")).failure + + assertEquals(DocumentOpenError.ParseFailed, failure.error) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaSaveGateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaSaveGateTest.kt new file mode 100644 index 0000000..6ac3696 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaSaveGateTest.kt @@ -0,0 +1,412 @@ +package org.umamo.ui.document + +import io.github.vinceglb.filekit.PlatformFile +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.umamo.edit.Cursor2d +import org.umamo.edit.EditorSession +import org.umamo.edit.ParameterChange +import org.umamo.edit.PartChange +import org.umamo.edit.Selection +import org.umamo.edit.SelectionOps +import org.umamo.edit.SelectionTarget +import org.umamo.edit.TransformPivotMode +import org.umamo.edit.withPartVisibility +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.png.PngCodec +import org.umamo.format.raster.RasterImage +import org.umamo.format.uma.UmaModel +import org.umamo.interop.art.ArtSourceDescriptor +import org.umamo.interop.diffPuppetModels +import org.umamo.render.ViewportCamera +import org.umamo.runtime.model.PartId +import org.umamo.ui.model.AddArtworkRequest +import org.umamo.ui.model.AtlasRepackHost +import org.umamo.ui.model.SessionAtlasPages +import org.umamo.ui.model.repackPageSizeOf +import org.umamo.ui.model.runAddArtwork +import org.umamo.ui.model.runAtlasRepack +import org.umamo.ui.viewport.AreaCameraKey +import org.umamo.ui.viewport.AtlasPageBinding +import org.umamo.ui.viewport.CameraSurface +import org.umamo.ui.workspace.AreaViewStates +import org.umamo.ui.workspace.EDITOR_STATE_AREAS +import org.umamo.ui.workspace.EDITOR_STATE_SESSION +import org.umamo.ui.workspace.PersistentSpaceState +import org.umamo.ui.workspace.sessionStateJson +import org.umamo.ui.workspace.sessionViewStateOf +import java.io.File +import java.util.zip.ZipFile +import kotlin.io.path.createTempDirectory +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The save the app runs, driven end to end on real documents: open, edit through a session, write the + * `.uma` with the same writer File > Save uses, mark the session saved with the same snapshot, reopen + * through the same loader, and find the edit there. Every origin the editor can hold takes the trip - a + * CMO3, a MOC3 family, an artwork file, and a new document with art imported into it - plus the two rules + * the design pins: a save after a repack derives its pages (UMA §5.5), and a save of an unedited reopen writes + * the same bytes (UMA §3.5). Gated on the corpus samples; each case self-skips without its file. + */ +class UmaSaveGateTest { + private val cmo3Sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + private val moc3Sample: File? = System.getProperty("moc3.sample")?.let(::File)?.takeIf { it.isFile } + private val psdSample: File? = System.getProperty("psd.sample")?.let(::File)?.takeIf { it.isFile } + + /** A fresh directory for one case's files. */ + private fun temporaryDirectory(): File = createTempDirectory("uma-save-gate").toFile() + + /** + * Opens [file] the way the shell does. + * + * @param File file The sample. + * @return PuppetDocument The document. + */ + private suspend fun open(file: File): PuppetDocument = assertIs(assertIs(loadDocument(PlatformFile(file))).document) + + /** + * The one edit every case makes: the first part hidden, which the puppet entry carries. + * + * @param EditorSession session The session. + * @return PartId The part hidden. + */ + private fun hideFirstPart(session: EditorSession): PartId { + val partId = assertNotNull(session.model.value.parts.firstOrNull()?.id, "the sample has a part to edit") + session.mutate(PartChange.SetVisibility(partId, false)) { model -> model.withPartVisibility(partId, false) } + assertTrue(session.dirty.value, "the edit dirtied the document") + return partId + } + + /** + * Saves [document]'s session to a `.uma` in [directory] and reopens it. + * + * @param PuppetDocument document The open document. + * @param EditorSession session Its session. + * @param AtlasPageBinding binding Its atlas pages. + * @param UmaModel base The document the save lays over. + * @param File directory Where to write. + * @param String name The file name. + * @param JsonObject editorState The editor entry's merge patch; empty for a save with no UI behind it. + * @return Triple The written model, the file, and the reopened document. + */ + private suspend fun saveAndReopen( + document: PuppetDocument, + session: EditorSession, + binding: AtlasPageBinding, + base: UmaModel, + directory: File, + name: String = "saved.uma", + editorState: JsonObject = JsonObject(emptyMap()), + ): Triple { + val target = File(directory, name) + val snapshot = session.model.value + val outcome = writeUmaDocument(document, base, snapshot, binding, editorState, PlatformFile(target)) + val written = assertIs(outcome, "the save succeeds: ${(outcome as? UmaWriteOutcome.Failed)?.reason}") + session.markSaved(snapshot) + assertFalse(session.dirty.value, "the save clears the dirty marker") + assertFalse(directory.listFiles().orEmpty().any { file -> file.name.contains(".tmp-") }, "no temporary is left behind") + val reopened = assertIs(assertIs(loadDocument(target.readBytes(), target.name, target.path)).document) + return Triple(written.uma, target, reopened) + } + + /** + * The whole trip for a loaded document: edit, save, reopen with the edit, and a second save of the + * reopen writing the same bytes. + * + * @param PuppetDocument document The open document. + * @param String label The case, for the summary line. + */ + private suspend fun roundTrip(document: PuppetDocument, label: String) { + val directory = temporaryDirectory() + val session = EditorSession(document.puppet, document.liveParams.values) + val hidden = hideFirstPart(session) + val binding = AtlasPageBinding(document.puppet.atlas, document.textures) + + val (_, file, reopened) = saveAndReopen(document, session, binding, UmaModel.create(umamoWriterInfo()), directory) + + assertFalse(reopened.puppet.partById.getValue(hidden).isVisible, "the edit is in the file") + assertEquals(session.model.value.drawables.size, reopened.puppet.drawables.size, "every drawable came back") + assertEquals(session.model.value.atlas.tiles.size, reopened.puppet.atlas.tiles.size, "and every tile") + + // A save of the unedited reopen writes the same bytes (UMA §3.5): nothing about a document depends on how it got here. + val reopenedSession = EditorSession(reopened.puppet, reopened.liveParams.values) + val (_, second, _) = saveAndReopen(reopened, reopenedSession, AtlasPageBinding(reopened.puppet.atlas, reopened.textures), reopened.uma, directory, "again.uma") + assertContentEquals(file.readBytes(), second.readBytes(), "an unedited reopen saves byte for byte") + println("uma save gate: $label -> ${file.length()} bytes, ${reopened.puppet.drawables.size} drawables") + } + + @Test + fun aCmo3DocumentSavesAndReopensWithItsEdit() = + runBlocking { + val file = cmo3Sample ?: return@runBlocking println("cmo3.sample not present; skipping the CMO3 save gate") + roundTrip(open(file), "cmo3") + } + + @Test + fun aMoc3DocumentSavesAndReopensWithItsEdit() = + runBlocking { + val file = moc3Sample ?: return@runBlocking println("moc3.sample not present; skipping the MOC3 save gate") + roundTrip(open(file), "moc3") + } + + @Test + fun anArtworkDocumentSavesAndReopensWithItsEdit() = + runBlocking { + val file = psdSample ?: return@runBlocking println("psd.sample not present; skipping the artwork save gate") + roundTrip(open(file), "psd") + } + + /** + * Editor state rides a save and comes back in its own area (UMA §7.3), never dirties, and is never an + * input to the model (UMA §7): the same document saved with and without it loads the same puppet. + */ + @Test + fun editorStateSurvivesASaveAndNeverTouchesTheModel() = + runBlocking { + val file = psdSample ?: return@runBlocking println("psd.sample not present; skipping the editor-state save gate") + val document = open(file) + val directory = temporaryDirectory() + val session = EditorSession(document.puppet, document.liveParams.values) + val binding = AtlasPageBinding(document.puppet.atlas, document.textures) + + // One area folds a branch open the way the outliner does, through the scope its leaf would be handed. + val areaViewStates = AreaViewStates() + areaViewStates.layoutAreaIds = listOf("area-test") + val folds = areaViewStates.scopeFor("area-test").spaceState("outliner") { FoldProbe() } + folds.opened = listOf("part:probe") + assertFalse(session.dirty.value, "a view toggle is not an edit") + + val editorState = buildJsonObject { put(EDITOR_STATE_AREAS, areaViewStates.gather()) } + val (_, _, withState) = saveAndReopen(document, session, binding, UmaModel.create(umamoWriterInfo()), directory, "with-state.uma", editorState) + val (_, _, withoutState) = saveAndReopen(document, session, binding, UmaModel.create(umamoWriterInfo()), directory, "without-state.uma") + + val restoredAreas = assertNotNull(withState.uma.editorState)[EDITOR_STATE_AREAS]!!.jsonObject + val reopenedFolds = AreaViewStates(restoredAreas).scopeFor("area-test").spaceState("outliner") { FoldProbe() } + assertEquals(listOf("part:probe"), reopenedFolds.opened, "the area gets its own state back") + assertEquals(emptyList(), AreaViewStates(restoredAreas).scopeFor("area-other").spaceState("outliner") { FoldProbe() }.opened, "and no other area does") + + assertEquals(null, withoutState.uma.editorState, "an untouched UI mints no entry") + assertTrue(diffPuppetModels(withoutState.puppet, withState.puppet).isEmpty, "the editor entry is no input to the puppet") + assertEquals(withoutState.puppet.atlas, withState.puppet.atlas) + assertEquals(withoutState.puppet.sources, withState.puppet.sources) + } + + /** + * The session half of editor state (UMA §7.4) and each area's camera (§7.3) through the real save and the real + * loader: a document reopens to the pose, the selection, the cursor, and the view it was saved with, none of it + * an undo step or a dirty mark, and none of it an input to the model. + */ + @Test + fun aDocumentReopensToThePoseSelectionAndViewItWasSavedWith() = + runBlocking { + val file = psdSample ?: return@runBlocking println("psd.sample not present; skipping the session-state save gate") + val document = open(file) + val directory = temporaryDirectory() + val session = EditorSession(document.puppet, document.liveParams.values) + val binding = AtlasPageBinding(document.puppet.atlas, document.textures) + + // Work the way a rigger does: select a drawable, scrub a parameter, place the cursor, switch the pivot. + val selected = SelectionTarget.Drawable(document.puppet.drawables.first().id) + session.setSelection(SelectionOps.replace(selected)) + val scrubbed = assertNotNull(document.puppet.parameters.firstOrNull { parameter -> parameter.max > parameter.default }, "the sample has a parameter with room to move") + session.commitPose(ParameterChange.SetValue(listOf(scrubbed.id)), mapOf(scrubbed.id to scrubbed.max)) + session.setCursor2d(12f, -8f) + session.setPivotMode(TransformPivotMode.Cursor) + assertFalse(session.dirty.value, "none of that is a change to the document") + + val areaViewStates = AreaViewStates() + areaViewStates.layoutAreaIds = listOf("area-view") + val savedView = AreaCameraKey("area-view", CameraSurface.Viewport) + val editorState = + buildJsonObject { + put(EDITOR_STATE_AREAS, areaViewStates.gather(mapOf(savedView to ViewportCamera(120f, -340f, 2.5f)))) + put(EDITOR_STATE_SESSION, sessionStateJson(session.viewState(), session.pose.value, session.model.value)) + } + val (_, _, reopened) = saveAndReopen(document, session, binding, UmaModel.create(umamoWriterInfo()), directory, "session.uma", editorState) + val (_, _, bare) = saveAndReopen(document, session, binding, UmaModel.create(umamoWriterInfo()), directory, "bare.uma") + + // The loader lays the saved pose into the live parameters, and the session opens on the rest. + assertEquals(scrubbed.max, reopened.liveParams.values.getValue(scrubbed.id), "the pose came back through the loader") + val savedState = assertNotNull(reopened.uma.editorState) + val reopenedSession = EditorSession(reopened.puppet, reopened.liveParams.values, initialViewState = sessionViewStateOf(savedState[EDITOR_STATE_SESSION]!!.jsonObject)) + assertEquals(scrubbed.max, reopenedSession.pose.value.getValue(scrubbed.id)) + assertEquals(Selection(setOf(selected), selected), reopenedSession.selection.value) + assertEquals(Cursor2d(12f, -8f), reopenedSession.cursor2d.value) + assertEquals(TransformPivotMode.Cursor, reopenedSession.pivotMode.value) + assertFalse(reopenedSession.canUndo.value, "what a document reopens to is where its history starts") + assertFalse(reopenedSession.dirty.value) + assertEquals(mapOf(savedView to ViewportCamera(120f, -340f, 2.5f)), AreaViewStates(savedState[EDITOR_STATE_AREAS]!!.jsonObject).restoredCameras()) + + assertEquals(scrubbed.default, bare.liveParams.values.getValue(scrubbed.id), "a file with no editor state opens at the default pose") + assertTrue(diffPuppetModels(bare.puppet, reopened.puppet).isEmpty, "and the session block is no input to the puppet") + } + + /** + * The path every rig starts on now: a new document, artwork imported into it, saved. The document has no + * file of its own and no base, so every tile is encoded from its raster. + */ + @Test + fun aNewDocumentWithImportedArtSavesAndReopens() = + runBlocking { + val file = psdSample ?: return@runBlocking println("psd.sample not present; skipping the new-document save gate") + val document = newBlankDocument() + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = AtlasRepackHost(session, document.artRasters, sessionAtlasPages, document.textures.premultipliedAlpha, this, { report -> error("refused: ${report.refusals}") }, { _, _ -> }) + val read = assertNotNull(readArtwork(file.readBytes(), file.name)) + assertTrue(runAddArtwork(host, AddArtworkRequest(read.art, ArtSourceDescriptor(file.name, file.path, read.kind.extension), artworkImportOptions()), areaId = null)) + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== session.model.value.atlas) { + yield() + } + } + val hidden = hideFirstPart(session) + + val (_, _, reopened) = saveAndReopen(document, session, sessionAtlasPages.binding.value, UmaModel.create(umamoWriterInfo()), temporaryDirectory()) + + follower.cancel() + assertFalse(reopened.puppet.partById.getValue(hidden).isVisible, "the edit is in the file") + assertEquals(session.model.value.drawables.size, reopened.puppet.drawables.size, "every imported drawable came back") + assertEquals(session.model.value.sources.size, reopened.puppet.sources.size, "with its artwork file listed") + assertTrue(reopened.storedPages == null, "a packed document derives its pages") + } + + /** + * A repack moves the atlas off the document's baseline, so the save derives its pages rather than + * storing the origin's (UMA §5.5); the reopened document composes the same pages the session showed. + */ + @Test + fun aSaveAfterARepackDerivesItsPages() = + runBlocking { + val file = cmo3Sample ?: return@runBlocking println("cmo3.sample not present; skipping the repack save gate") + val document = assertIs(open(file)) + val session = EditorSession(document.puppet, document.liveParams.values) + val sessionAtlasPages = SessionAtlasPages(session, document.puppet.atlas, document.textures, document.artRasters) + val follower = launch { sessionAtlasPages.follow() } + val host = AtlasRepackHost(session, document.artRasters, sessionAtlasPages, document.textures.premultipliedAlpha, this, { report -> error("refused: ${report.refusals}") }, { _, _ -> }) + runAtlasRepack(host, AtlasPackOptions(maxPageSize = repackPageSizeOf(document.puppet)), areaId = null) + withTimeout(120_000) { + while (sessionAtlasPages.binding.value.atlas !== session.model.value.atlas) { + yield() + } + } + val binding = sessionAtlasPages.binding.value + assertTrue(binding.textures !== document.textures, "the repack moved the pages off the baseline") + + val (_, _, reopened) = saveAndReopen(document, session, binding, UmaModel.create(umamoWriterInfo()), temporaryDirectory()) + + follower.cancel() + assertTrue(reopened.storedPages == null, "a repacked atlas stores no render pages") + assertEquals(binding.textures.atlases.size, reopened.textures.atlases.size, "the reopened document composes the same page count") + for ((pageIndex, page) in reopened.textures.atlases.withIndex()) { + assertTrue(page.rgba.contentEquals(binding.textures.atlases[pageIndex].rgba), "page $pageIndex composes as the session showed it") + } + } + + /** + * A thumbnail the viewport renderer drew is the one the file stores, pixel for pixel - the writer only + * composites its own when it is handed none. The supplied image is one no composite of the sample could + * produce, so finding it in the file proves which of the two landed. + */ + @Test + fun aRenderedThumbnailIsTheOneTheFileStores() = + runBlocking { + val file = cmo3Sample ?: return@runBlocking println("cmo3.sample not present; skipping the rendered-thumbnail save gate") + val document = open(file) + val session = EditorSession(document.puppet, document.liveParams.values) + // A flat color over an alpha ramp across each row, never fully transparent. + val rendered = + RasterImage( + UMA_THUMBNAIL_SIZE, + UMA_THUMBNAIL_SIZE, + ByteArray(UMA_THUMBNAIL_SIZE * UMA_THUMBNAIL_SIZE * 4) { byteIndex -> + when (byteIndex % 4) { + 0 -> 0x40 + 1 -> 0x80 + 2 -> 0xC0 + else -> 1 + (byteIndex / 4) % UMA_THUMBNAIL_SIZE % 255 + }.toByte() + }, + ) + val target = File(temporaryDirectory(), "rendered-thumbnail.uma") + + val outcome = + writeUmaDocument( + document, + UmaModel.create(umamoWriterInfo()), + session.model.value, + AtlasPageBinding(document.puppet.atlas, document.textures), + JsonObject(emptyMap()), + PlatformFile(target), + thumbnail = rendered, + ) + + val written = assertIs(outcome, "the save succeeds: ${(outcome as? UmaWriteOutcome.Failed)?.reason}") + val thumbnail = assertNotNull(written.uma.textures?.thumbnail, "the file records a thumbnail") + assertEquals(UMA_THUMBNAIL_SIZE to UMA_THUMBNAIL_SIZE, thumbnail.width to thumbnail.height) + val stored = ZipFile(target).use { archive -> archive.getInputStream(assertNotNull(archive.getEntry(thumbnail.path))).readBytes() } + assertContentEquals(rendered.rgba, PngCodec.read(stored).rgba, "the stored thumbnail is the rendered one") + } + + /** + * A save snapshots the model before writing; an edit that lands meanwhile is not on disk, so the document + * stays dirty once the save is marked. + */ + @Test + fun anEditDuringASaveStaysDirty() = + runBlocking { + val file = cmo3Sample ?: return@runBlocking println("cmo3.sample not present; skipping the dirty-during-save gate") + val document = open(file) + val session = EditorSession(document.puppet, document.liveParams.values) + val hidden = hideFirstPart(session) + val snapshot = session.model.value + val target = File(temporaryDirectory(), "saved.uma") + + val outcome = writeUmaDocument(document, UmaModel.create(umamoWriterInfo()), snapshot, AtlasPageBinding(document.puppet.atlas, document.textures), JsonObject(emptyMap()), PlatformFile(target)) + assertIs(outcome) + // The edit that lands while the file is being written. + session.mutate(PartChange.SetVisibility(hidden, true)) { model -> model.withPartVisibility(hidden, true) } + session.markSaved(snapshot) + + assertTrue(session.dirty.value, "what is on screen is not what is on disk") + session.undo() + assertFalse(session.dirty.value, "undoing back to the saved instance is clean") + } +} + +/** A stand-in for a space's view state: one fold list, written and restored the way the real ones are. */ +private class FoldProbe : PersistentSpaceState { + var opened: List = emptyList() + + /** + * The probe's member of its area block. + * + * @return JsonObject The member. + */ + override fun toJson(): JsonObject = buildJsonObject { put("expanded", JsonArray(opened.map(::JsonPrimitive))) } + + /** + * Takes the saved member. + * + * @param JsonObject tree The member as the file held it. + */ + override fun restore(tree: JsonObject) { + opened = tree["expanded"]?.jsonArray?.map { element -> element.jsonPrimitive.content }.orEmpty() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaTestFiles.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaTestFiles.kt new file mode 100644 index 0000000..1a825d0 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UmaTestFiles.kt @@ -0,0 +1,87 @@ +package org.umamo.ui.document + +import org.umamo.format.uma.Uma +import org.umamo.format.uma.UmaModel +import org.umamo.format.uma.textures.UmaPixelSource +import org.umamo.format.uma.textures.UmaRenderPagePixels +import org.umamo.interop.uma.UmaDocumentBridge +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.util.zip.CRC32 +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream + +/* + * Synthetic `.uma` files for the tests in this package: a document the codec wrote from an empty rig, and + * the same file rewritten by hand where a case needs a manifest this writer would never produce. + */ + +/** + * A `.uma` the codec wrote from a new document's empty puppet. + * + * @return ByteArray The file. + */ +internal fun emptyDocumentBytes(): ByteArray { + val puppet = newBlankDocument().puppet + val written = UmaDocumentBridge.documentOf(UmaModel.create(umamoWriterInfo()), puppet, UmaPixelSource({ null }, UmaRenderPagePixels.Derived, null)) + return Uma.write(written) +} + +/** + * [bytes] re-zipped with its manifest text passed through [rewrite] and [extraEntries] appended, keeping + * the stored mimetype first as the format requires. + * + * @param ByteArray bytes A UMA file. + * @param List extraEntries Entries to append, path to contents. + * @param Function rewrite The manifest's new text given its old one. + * @return ByteArray The rewritten file. + */ +internal fun rewritten(bytes: ByteArray, extraEntries: List> = emptyList(), rewrite: (String) -> String): ByteArray { + val output = ByteArrayOutputStream() + ZipOutputStream(output).use { zip -> + ZipInputStream(ByteArrayInputStream(bytes)).use { input -> + generateSequence { input.nextEntry }.forEach { entry -> + val contents = input.readBytes() + if (entry.name == "mimetype") { + zip.putNextEntry( + ZipEntry(entry.name).apply { + method = ZipEntry.STORED + size = contents.size.toLong() + compressedSize = contents.size.toLong() + crc = CRC32().apply { update(contents) }.value + }, + ) + zip.write(contents) + } else { + zip.putNextEntry(ZipEntry(entry.name)) + zip.write(if (entry.name == "manifest.json") rewrite(contents.decodeToString()).encodeToByteArray() else contents) + } + zip.closeEntry() + } + } + for ((path, contents) in extraEntries) { + zip.putNextEntry(ZipEntry(path)) + zip.write(contents) + zip.closeEntry() + } + } + return output.toByteArray() +} + +/** + * A `.uma` holding a REQUIRED entry of a kind this version does not know (`future/thing.json`), which is + * what opens a document read-only. + * + * @return ByteArray The file. + */ +internal fun umaBytesWithUnknownRequiredEntry(): ByteArray = + rewritten( + emptyDocumentBytes(), + extraEntries = listOf("future/thing.json" to "{}".encodeToByteArray()), + ) { manifest -> + val record = """{ "path": "future/thing.json", "kind": "mystery", "version": 1, "minVersion": 1, "required": true }""" + val patched = manifest.replaceFirst("\"entries\": [", "\"entries\": [ $record,") + check(patched != manifest) { "the manifest's entries array was not found: $manifest" } + patched + } \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UvProbeTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UvProbeTest.kt new file mode 100644 index 0000000..5d43b57 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/document/UvProbeTest.kt @@ -0,0 +1,47 @@ +package org.umamo.ui.document + +import kotlinx.coroutines.runBlocking +import org.umamo.edit.freeVertUvContextOf +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.storedToArtAffineForTile +import java.io.File +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +class UvProbeTest { + @Test + fun probeJumperUvContext() = + runBlocking { + val file = File("/home/litruv/Desktop/Bear_.uma") + val load = loadDocument(file.readBytes(), file.name, file.path) + val doc = assertIs(assertIs(load).document) + val model = doc.puppet + val id = DrawableId("Jumper") + val d = model.drawables.first { it.id == id } + val mesh = assertNotNull(d.mesh) + val tileId = assertNotNull(d.atlasTileId) + val tile = assertNotNull(model.atlas.tileById[tileId]) + println("sources=${model.sources.size} tiles=${model.atlas.tileById.size}") + println("tile source=${tile.source} name=${tile.name} placement=${tile.placement}") + val storedToArt = model.atlas.storedToArtAffineForTile(tileId) + println("storedToArt=${storedToArt?.toList()}") + val ctx = freeVertUvContextOf(model, id) + println("ctx=$ctx origin=${ctx?.layerLeft},${ctx?.layerTop} tile=${ctx?.tileWidth}x${ctx?.tileHeight} frame=${ctx?.frame != null}") + assertNotNull(ctx) + var maxErr = 0f + for (i in 0 until mesh.vertexCount) { + val x = mesh.positions[i * 2] + val y = mesh.positions[i * 2 + 1] + val (u, v) = ctx.storedUvAt(x, y) + val eu = abs(u - mesh.uvs[i * 2]) + val ev = abs(v - mesh.uvs[i * 2 + 1]) + maxErr = maxOf(maxErr, eu + ev) + if (i < 5) println("v$i pos=($x,$y) got=($u,$v) want=(${mesh.uvs[i * 2]},${mesh.uvs[i * 2 + 1]}) err=${eu + ev}") + } + println("maxErr=$maxErr") + assertTrue(maxErr < 1e-2f, "art projector must match original UVs, maxErr=$maxErr") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/ConfirmDialogTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/ConfirmDialogTest.kt new file mode 100644 index 0000000..a8196c0 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/ConfirmDialogTest.kt @@ -0,0 +1,84 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.v2.runComposeUiTest +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Pins which buttons a confirm dialog shows and which action each one runs. + * + * The dialog is the last thing between a rigger and losing work, so the mapping from a named button to + * its action is the part worth pinning: a three-way dialog whose "Don't Save" ran the save, or whose + * cancel ran the destructive action, would read as correct in the source and be wrong on screen. A + * two-button dialog must also stay two buttons - the third choice is opt-in. + */ +class ConfirmDialogTest { + private val message = "Discard the unsaved changes?" + + @OptIn(ExperimentalTestApi::class) + @Test + fun aDialogWithoutAnAlternativeShowsItsTwoNamedButtons() { + runComposeUiTest { + setContent { + UmamoTheme { + ConfirmDialog( + message = message, + onConfirm = {}, + onCancel = {}, + confirmLabel = "Discard", + cancelLabel = "Keep Editing", + ) + } + } + + onNodeWithText(message).assertIsDisplayed() + onNodeWithText("Discard").assertIsDisplayed() + onNodeWithText("Keep Editing").assertIsDisplayed() + // The third choice is opt-in: nothing takes its place in a two-button dialog. + onAllNodesWithText("Don't Save").assertCountEquals(0) + } + } + + @OptIn(ExperimentalTestApi::class) + @Test + fun eachButtonRunsOnlyItsOwnAction() { + var confirmCount = 0 + var cancelCount = 0 + var alternativeCount = 0 + runComposeUiTest { + setContent { + UmamoTheme { + ConfirmDialog( + message = message, + onConfirm = { confirmCount++ }, + onCancel = { cancelCount++ }, + confirmLabel = "Save", + cancelLabel = "Cancel", + alternative = DialogChoice("Don't Save") { alternativeCount++ }, + ) + } + } + + onNodeWithText("Don't Save").performClick() + assertEquals(1, alternativeCount) + assertEquals(0, confirmCount) + assertEquals(0, cancelCount) + + onNodeWithText("Cancel").performClick() + assertEquals(1, cancelCount) + assertEquals(0, confirmCount) + + onNodeWithText("Save").performClick() + assertEquals(1, confirmCount) + assertEquals(1, cancelCount, "and no button runs another's action") + assertEquals(1, alternativeCount) + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/DropdownChipSizingTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/DropdownChipSizingTest.kt new file mode 100644 index 0000000..e5fde7c --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/DropdownChipSizingTest.kt @@ -0,0 +1,79 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.width +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A Header chip holds its size when its parent runs out of room. + * + * The failure this guards is silent on screen and was live: Modifier.size coerces to the incoming + * constraints, so a starved parent measured the chip's 16.dp glyph and 12.dp chevron at zero and the chip + * rendered as an empty padding box - present, clickable, and completely unreadable. Being pushed off the + * edge is legible; shrinking to nothing is not. + */ +class DropdownChipSizingTest { + /** A chip in a roomy parent and one in a 24.dp parent measure the same. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aHeaderChipKeepsItsWidthInAStarvedParent() { + assertEquals(chipWidth(parentWidth = 400.dp), chipWidth(parentWidth = 24.dp)) + } + + /** The squeeze also has to survive a parent with literally no room at all. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aHeaderChipKeepsItsWidthWithNoRoomAtAll() { + assertEquals(chipWidth(parentWidth = 400.dp), chipWidth(parentWidth = 0.dp)) + } + + /** + * Composes one labelled Header chip inside a fixed-width parent and returns the width of its painted + * face. + * + * Read off the chip's semantics node, which rides the same modifier chain as its border and fill - + * that is the node whose width IS what the user sees. The chip's outer anchor box reports the + * parent's clamp instead, which is the very measurement the fix stops the face from inheriting. + * + * @param Dp parentWidth The width of the box the chip is squeezed into. + * @return Dp The chip face's measured width. + */ + @OptIn(ExperimentalTestApi::class) + private fun chipWidth(parentWidth: Dp): Dp { + var measured = 0.dp + runComposeUiTest { + setContent { + UmamoTheme { + Box(modifier = Modifier.width(parentWidth)) { + DropdownChip( + expanded = false, + onExpandRequest = {}, + contentDescription = CHIP_LABEL, + icon = LocalUmamoIcons.transformPivot, + label = "Median Point", + ) {} + } + } + } + waitForIdle() + measured = onNodeWithContentDescription(CHIP_LABEL, useUnmergedTree = true).getUnclippedBoundsInRoot().width + } + return measured + } + + private companion object { + /** The chip's accessible name, which is also how the test addresses its painted face. */ + const val CHIP_LABEL = "Pivot" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/HexColorFieldMirrorTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/HexColorFieldMirrorTest.kt new file mode 100644 index 0000000..f8be9a1 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/HexColorFieldMirrorTest.kt @@ -0,0 +1,129 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextClearance +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextInputSelection +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.unit.dp +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * That a hex field follows its external value even while it holds focus. + * + * This field is not the only writer of what it shows - its own swatch picker, a parameter scrub moving a + * keyed channel, and undo all change the value underneath it. It used to skip the mirror whenever it was + * focused, and since nothing ever takes focus back off it, one click into the field froze it permanently: + * a keyed multiply color sat on its first key while the viewport went on blending. + */ +class HexColorFieldMirrorTest { + private val green = "#FF3DFF00" + private val magenta = "#FFFF00FF" + + /** An external change lands in the field even though the field is focused. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun anExternalChangeReachesAFocusedField() = + runComposeUiTest { + var value by mutableStateOf(green) + setContent { + Box(modifier = Modifier.width(240.dp)) { + HexColorField( + value = value, + onValueChange = { hex -> value = hex }, + ) + } + } + // Focus it the way a user would, then change the value from somewhere else entirely. + field().performClick() + waitForIdle() + value = magenta + waitForIdle() + field().assertTextEquals(magenta) + } + + /** Typing is not fought: the user's own edit round-trips and the field keeps what they typed. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun typingIsNotClobberedByItsOwnRoundTrip() = + runComposeUiTest { + var value by mutableStateOf(green) + setContent { + Box(modifier = Modifier.width(240.dp)) { + HexColorField( + value = value, + onValueChange = { hex -> value = hex }, + ) + } + } + field().performClick() + field().performTextClearance() + field().performTextInput(magenta) + waitForIdle() + field().assertTextEquals(magenta) + assertEquals(magenta, value, "a parseable edit commits out through onValueChange") + } + + /** + * Moving the selection is not an edit, so it must not persist anything. + * + * The field holds a TextFieldValue so its context menu can act on a selection, and BasicTextField's + * TextFieldValue overload reports caret and selection moves through the same callback as typing. + * Persisting those re-committed the stored color for merely clicking into the field or dragging a + * selection across it - and on a KEYED channel that is an undo step plus the orange uncommitted-edit + * tint, for a value that never changed. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun movingTheSelectionPersistsNothing() = + runComposeUiTest { + var value by mutableStateOf(green) + var commits = 0 + setContent { + Box(modifier = Modifier.width(240.dp)) { + HexColorField( + value = value, + onValueChange = { hex -> + commits++ + value = hex + }, + ) + } + } + field().performClick() + waitForIdle() + // Counted from here: the click itself places a caret, which is the very thing under test. + val commitsBeforeSelecting = commits + + field().performTextInputSelection(TextRange(0, value.length)) + waitForIdle() + assertEquals(commitsBeforeSelecting, commits, "selecting the text is not an edit of it") + + field().performTextClearance() + field().performTextInput(magenta) + waitForIdle() + assertEquals(magenta, value, "but a real edit still persists") + } + + /** + * The editable node inside the field. + * + * Selected by its set-text action rather than a tag: the caller's modifier lands on the field's outer + * row, whose subtree also holds the swatch, so a tag there is not the node text assertions act on. + * + * @return SemanticsNodeInteraction The text node. + */ + @OptIn(ExperimentalTestApi::class) + private fun androidx.compose.ui.test.ComposeUiTest.field() = onNode(hasSetTextAction()) +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/IconSlotSemanticsTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/IconSlotSemanticsTest.kt new file mode 100644 index 0000000..6499601 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/IconSlotSemanticsTest.kt @@ -0,0 +1,152 @@ +package org.umamo.ui.kit + +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.v2.runComposeUiTest +import org.umamo.ui.kit.button.IconSlot +import org.umamo.ui.theme.LocalUmamoIcons +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** + * The kit's label contract for the slots whose gesture the caller owns: every one of them publishes an + * accessible name, and a disclosure chevron publishes WHICH WAY it would move. + * + * These are the two places that invariant now lives, so they are the two worth pinning. The failure they + * guard against is silent by nature - a glyph-only control with no name looks perfectly fine on screen and + * is simply absent to a screen reader - and it is exactly what the hand-rolled slots these replaced did. + */ +class IconSlotSemanticsTest { + /** A slot publishes the name it was given. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aSlotPublishesItsContentDescription() { + assertEquals("Toggle Visibility", slotDescription(hoverLabel = "Toggle Visibility")) + } + + /** + * Suppressing the tooltip must not cost the accessible name. + * + * The blank hoverLabel is the escape hatch for a slot sitting beside its own visible text, and the whole + * point of separating it from contentDescription is that only the hover card goes away. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aBlankHoverLabelKeepsTheAccessibleName() { + assertEquals("Toggle Visibility", slotDescription(hoverLabel = "")) + } + + /** + * A chevron's default name distinguishes its two states. + * + * This is the reason a disclosure chevron is labelled at all: the row's own text names the section but + * never says whether it is open, so a name that read the same either way would carry nothing. Asserted + * as a difference rather than against the English wording, which is free to change. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aChevronNamesTheDirectionItWouldMove() { + val collapsed = chevronDescription(expanded = false) + val expanded = chevronDescription(expanded = true) + + assertTrue(collapsed.isNotBlank(), "a collapsed chevron must publish a name") + assertTrue(expanded.isNotBlank(), "an expanded chevron must publish a name") + assertNotEquals(collapsed, expanded, "the name must say which way the chevron would move") + } + + /** A caller with a more specific name than "expand" / "collapse" keeps it. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun anExplicitChevronNameWins() { + assertEquals("Range", chevronDescription(expanded = false, contentDescription = "Range")) + } + + /** + * Composes one [IconSlot] and returns the accessible name it published. + * + * @param String hoverLabel The tooltip text to pass; blank attaches no tooltip. + * @return String The published content description. + */ + @OptIn(ExperimentalTestApi::class) + private fun slotDescription(hoverLabel: String): String { + var description = "" + runComposeUiTest { + setContent { + UmamoTheme { + IconSlot( + icon = LocalUmamoIcons.eyeVisible, + contentDescription = "Toggle Visibility", + tint = Color.White, + modifier = Modifier.testTag(SLOT_TAG), + hoverLabel = hoverLabel, + ) + } + } + description = publishedDescription() + } + return description + } + + /** + * Composes one [DisclosureChevron] and returns the accessible name it published. + * + * @param Boolean expanded Whether the chevron reads as open. + * @param String? contentDescription An explicit name, or null to take the default. + * @return String The published content description. + */ + @OptIn(ExperimentalTestApi::class) + private fun chevronDescription(expanded: Boolean, contentDescription: String? = null): String { + var description = "" + runComposeUiTest { + setContent { + UmamoTheme { + if (contentDescription == null) { + DisclosureChevron( + expanded = expanded, + tint = Color.White, + modifier = Modifier.testTag(SLOT_TAG), + ) + } else { + DisclosureChevron( + expanded = expanded, + tint = Color.White, + modifier = Modifier.testTag(SLOT_TAG), + contentDescription = contentDescription, + ) + } + } + } + description = publishedDescription() + } + return description + } + + /** + * Reads the tagged node's content description off the unmerged tree. + * + * Unmerged because the tag and the description ride the same modifier chain - the slot's face - and a + * merged read would answer for whatever ancestor absorbed them. + * + * @return String The single published description, or "" when the node published none. + */ + @OptIn(ExperimentalTestApi::class) + private fun ComposeUiTest.publishedDescription(): String { + waitForIdle() + val node = onNodeWithTag(SLOT_TAG, useUnmergedTree = true).fetchSemanticsNode() + return node.config.getOrNull(SemanticsProperties.ContentDescription)?.firstOrNull().orEmpty() + } + + private companion object { + /** The tag both helpers hang on the slot's face, so the description is read off that exact node. */ + const val SLOT_TAG = "slot" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/MenuSearchAndHeadingTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/MenuSearchAndHeadingTest.kt new file mode 100644 index 0000000..7655ec1 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/MenuSearchAndHeadingTest.kt @@ -0,0 +1,155 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.assertWidthIsEqualTo +import androidx.compose.ui.test.getBoundsInRoot +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.height +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * A menu with a search box and section headings: the box is pinned, focused on open, and fixes the + * menu's width; the caller filters the rows through the query it hands back; a heading is inert; an + * action still dismisses. The shape the Sources relink menu and the UV layer picker are built on. + */ +class MenuSearchAndHeadingTest { + @OptIn(ExperimentalTestApi::class) + @Test + fun aSearchMenuFiltersThroughItsCallerAndKeepsItsWidth() { + var picked: String? = null + var dismissed = 0 + runComposeUiTest { + setContent { + UmamoTheme { + var expanded by remember { mutableStateOf(true) } + var query by remember { mutableStateOf("") } + val names = ALL_ROWS.filter { name -> name.contains(query, ignoreCase = true) } + Box(modifier = Modifier.size(400.dp, 300.dp)) { + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = CHIP_LABEL, + label = CHIP_LABEL, + ) { + Menu( + items = + buildList { + add(MenuItem.Search(value = query, onValueChange = { updated -> query = updated }, width = MENU_WIDTH, placeholder = HINT)) + add(MenuItem.Heading(HEADING)) + for (name in names) { + add(MenuItem.Action(label = name, onSelect = { picked = name })) + } + }, + onDismissRequest = { + expanded = false + dismissed++ + }, + positionProvider = BelowAnchorPositionProvider, + modifier = Modifier.testTag(ROWS_TAG), + ) + } + } + } + } + waitForIdle() + onNodeWithText(HEADING, useUnmergedTree = true).assertExists() + onNode(hasSetTextAction(), useUnmergedTree = true).assertIsFocused() + onNodeWithTag(ROWS_TAG, useUnmergedTree = true).assertWidthIsEqualTo(MENU_WIDTH) + + // Typing reaches the caller, which rebuilds the rows; the menu stays open at the same width even + // though the longest row is gone. + onNode(hasSetTextAction(), useUnmergedTree = true).performTextInput("eye") + waitForIdle() + onNodeWithText(ALL_ROWS[0], useUnmergedTree = true).assertDoesNotExist() + onNodeWithText(ALL_ROWS[2], useUnmergedTree = true).assertDoesNotExist() + onNodeWithText(ALL_ROWS[1], useUnmergedTree = true).assertExists() + assertEquals(0, dismissed, "typing does not dismiss") + onNodeWithTag(ROWS_TAG, useUnmergedTree = true).assertWidthIsEqualTo(MENU_WIDTH) + + // A heading is inert. + onNodeWithText(HEADING, useUnmergedTree = true).performClick() + waitForIdle() + assertEquals(0, dismissed, "a heading does not dismiss") + assertNull(picked, "a heading selects nothing") + + // An action picks and dismisses as ever. + onNodeWithText(ALL_ROWS[1], useUnmergedTree = true).performClick() + waitForIdle() + assertEquals(ALL_ROWS[1], picked) + assertEquals(1, dismissed) + } + } + + /** + * A search menu over a long list stays under its chip: its rows cap well below the window and scroll, + * instead of standing as tall as the window and being clamped to the window's bottom edge - which + * opened the layer pickers far from their chip until a search shrank them back. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aSearchMenuOverALongListStaysAnchoredUnderItsChip() { + runComposeUiTest { + setContent { + UmamoTheme { + var expanded by remember { mutableStateOf(true) } + Box(modifier = Modifier.size(400.dp, 700.dp)) { + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = CHIP_LABEL, + label = CHIP_LABEL, + modifier = Modifier.testTag(CHIP_TAG), + ) { + Menu( + items = + buildList { + add(MenuItem.Search(value = "", onValueChange = {}, width = MENU_WIDTH)) + for (index in 0 until 80) { + add(MenuItem.Action(label = "Layer $index", onSelect = {})) + } + }, + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + modifier = Modifier.testTag(ROWS_TAG), + ) + } + } + } + } + waitForIdle() + val chip = onNodeWithTag(CHIP_TAG, useUnmergedTree = true).getBoundsInRoot() + val rows = onNodeWithTag(ROWS_TAG, useUnmergedTree = true).getBoundsInRoot() + assertTrue(rows.height <= MENU_SEARCH_ROWS_MAX_HEIGHT, "rows are capped at ${MENU_SEARCH_ROWS_MAX_HEIGHT}, got ${rows.height}") + assertTrue(rows.top >= chip.bottom, "the menu hangs under the chip (rows top ${rows.top}, chip bottom ${chip.bottom})") + } + } + + private companion object { + const val CHIP_TAG = "chip" + const val CHIP_LABEL = "Relink" + const val HEADING = "erica.psd" + const val HINT = "Filter layers" + const val ROWS_TAG = "rows" + val MENU_WIDTH = 240.dp + val ALL_ROWS = listOf("Hair Front", "Eye L", "A layer whose name runs well past the width of the menu") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/NumberFieldKeyStateTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/NumberFieldKeyStateTest.kt new file mode 100644 index 0000000..1d507af --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/NumberFieldKeyStateTest.kt @@ -0,0 +1,93 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import org.umamo.ui.model.KeyedFieldState +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * That a keyed field state actually TINTS an enabled number field. + * + * A pixel test on purpose: the state once reached only the disabled-plain display branch, so every real + * (enabled) numeric field silently dropped the work-loss warning the tint exists to carry - a wiring gap + * no assertion over the state enum could see. The tint is a background fill rather than an outline now, + * which does not change what this checks: that the state reaches the pixels at all. + */ +class NumberFieldKeyStateTest { + /** The keyed tint changes the enabled resting face's pixels; None leaves them untouched. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theKeyedTintRendersOnTheEnabledRestingFace() { + val none = renderedPixels(KeyedFieldState.None) + val onKey = renderedPixels(KeyedFieldState.OnKey) + val modified = renderedPixels(KeyedFieldState.ModifiedUnkeyed) + + assertTrue(differing(none, onKey) > 0, "the OnKey tint must change the enabled face") + assertTrue(differing(none, modified) > 0, "the ModifiedUnkeyed warning tint must change the enabled face") + } + + /** + * A fill covers far more of the field than the outline did, so the tint must survive the field's own + * fills rather than being painted under them. + * + * Guards the ordering: the magnitude fill and the resting background are both drawn by the same control, + * and a tint layered beneath either of them is invisible in exactly the half of the field the value + * occupies - which reads as "the tint is broken for some values" rather than as a stacking mistake. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theTintCoversTheFieldRatherThanItsEdge() { + val none = renderedPixels(KeyedFieldState.None) + val onKey = renderedPixels(KeyedFieldState.OnKey) + + // A 1px outline on a 150x30 field is under 10% of it; a fill is nearly all of it. + assertTrue(differing(none, onKey) > none.size / 2, "the tint must fill the field, not outline it") + } + + /** The type-in face carries the same tint, so clicking a keyed field to type does not flash it away. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun thePlainTypeInFaceIsTintedToo() { + val none = renderedPixels(KeyedFieldState.None, plain = true) + val onKey = renderedPixels(KeyedFieldState.OnKey, plain = true) + + assertTrue(differing(none, onKey) > 0, "the type-in face must carry the keyed tint as well") + } + + /** Renders one enabled number field with [keyState] and returns its pixels. */ + @OptIn(ExperimentalTestApi::class) + private fun renderedPixels(keyState: KeyedFieldState, plain: Boolean = false): IntArray { + var pixels: IntArray? = null + runComposeUiTest { + setContent { + Box(modifier = Modifier.size(width = 160.dp, height = 40.dp).testTag("field")) { + NumberField( + value = 0.5f, + onValueChange = {}, + range = 0f..1f, + modifier = Modifier.size(width = 150.dp, height = 30.dp), + keyState = keyState, + plain = plain, + ) + } + } + val image = onNodeWithTag("field").captureToImage() + val captured = IntArray(image.width * image.height) + image.readPixels(captured) + pixels = captured + } + return requireNotNull(pixels) + } + + /** The number of pixels two same-size renders differ in. */ + private fun differing(left: IntArray, right: IntArray): Int = + left.indices.count { pixelIndex -> left[pixelIndex] != right[pixelIndex] } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/OverflowPopupNestedMenuTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/OverflowPopupNestedMenuTest.kt new file mode 100644 index 0000000..606f037 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/OverflowPopupNestedMenuTest.kt @@ -0,0 +1,112 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * A dropdown collapsed into the overflow panel is still usable from inside it. + * + * This is the nested-popup hazard the kit's own Menu docblock names: only one popup in a tree may be + * focusable, or they fight over the dismiss and the inner press reads as "outside" to the outer popup, + * tearing the inner one down mid-click. LocalPopupDismissOwned is what makes the inner menu yield, and + * this is the test that would catch it regressing. + */ +class OverflowPopupNestedMenuTest { + /** A menu opened from inside the overflow panel survives long enough to be clicked. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aMenuInsideTheOverflowPanelCanBeDriven() { + var selected = false + runComposeUiTest { + setContent { + UmamoTheme { + Box(modifier = Modifier.width(80.dp)) { + OverflowRow { + pinnedItem("pin") { Box(modifier = Modifier.size(40.dp).testTag("pin")) } + item("chip") { + var expanded by remember { mutableStateOf(false) } + DropdownChip( + expanded = expanded, + onExpandRequest = { expanded = true }, + contentDescription = CHIP_LABEL, + label = CHIP_LABEL, + ) { + Menu( + items = listOf(MenuItem.Action(label = ROW_LABEL, onSelect = { selected = true })), + onDismissRequest = { expanded = false }, + positionProvider = BelowAnchorPositionProvider, + ) + } + } + } + } + } + } + waitForIdle() + // The chip did not fit, so it lives in the panel rather than on the strip. + onNodeWithContentDescription(CHIP_LABEL, useUnmergedTree = true).assertDoesNotExist() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + onNodeWithContentDescription(CHIP_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + onNodeWithText(ROW_LABEL, useUnmergedTree = true).assertExists() + onNodeWithText(ROW_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + } + assertTrue(selected, "the row inside the nested menu never fired") + } + + /** Widening the strip past the collapse point cannot leave the panel open with no anchor. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun wideningTheStripClosesAnOpenPanel() { + runComposeUiTest { + var stripWidth by mutableStateOf(80.dp) + setContent { + UmamoTheme { + Box(modifier = Modifier.width(stripWidth)) { + OverflowRow { + pinnedItem("pin") { Box(modifier = Modifier.size(40.dp).testTag("pin")) } + item("wide") { Box(modifier = Modifier.size(40.dp).testTag("wide")) } + } + } + } + } + waitForIdle() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + onNodeWithTag("wide").assertExists() + + stripWidth = 400.dp + waitForIdle() + // Back on the strip and no longer in a panel: the chip itself is gone, so nothing is orphaned. + onNodeWithTag("wide").assertExists() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).assertDoesNotExist() + } + } + + private companion object { + /** The overflow chip's English name; it doubles as its accessible label. */ + const val MORE_LABEL = "More" + + const val CHIP_LABEL = "Pivot" + const val ROW_LABEL = "Median Point" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/OverflowRowTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/OverflowRowTest.kt new file mode 100644 index 0000000..39997d3 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/OverflowRowTest.kt @@ -0,0 +1,168 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertWidthIsEqualTo +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test + +/** + * The strip collapses instead of crushing: controls that no longer fit stop being composed at all and + * reappear inside the overflow chip's panel, while a pinned control survives every width. + * + * assertDoesNotExist rather than a visibility check is the point of several of these - a collapsed + * control must be genuinely uncomposed, not merely unplaced, or its state and its own popups would live + * on invisibly. + */ +class OverflowRowTest { + /** With room to spare every control is present and the chip is not. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aRoomyStripShowsEverythingAndNoChip() { + runComposeUiTest { + setStrip(stripWidth = 400.dp) + onNodeWithTag("a").assertExists() + onNodeWithTag("b").assertExists() + onNodeWithTag("c").assertExists() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).assertDoesNotExist() + } + } + + /** A narrow strip drops the trailing controls entirely and raises the chip. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aNarrowStripCollapsesTheTrailingControls() { + runComposeUiTest { + setStrip(stripWidth = 120.dp) + onNodeWithTag("a").assertExists() + onNodeWithTag("c").assertDoesNotExist() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).assertExists() + } + } + + /** Opening the chip brings the collapsed controls back, inside its panel. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theChipPanelHoldsTheCollapsedControls() { + runComposeUiTest { + setStrip(stripWidth = 120.dp) + onNodeWithTag("c").assertDoesNotExist() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + onNodeWithTag("c").assertExists() + } + } + + /** A pinned control is placed at every width, however little room is left. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aPinnedControlSurvivesEveryWidth() { + runComposeUiTest { + setStrip(stripWidth = 10.dp) + onNodeWithTag("a").assertExists() + } + } + + /** An item that renders nothing is dropped rather than collapsed - it never reaches the panel. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun anEmptyItemIsDroppedNotCollapsed() { + runComposeUiTest { + setContent { + UmamoTheme { + Box(modifier = Modifier.width(400.dp)) { + OverflowRow { + item("present") { Box(modifier = Modifier.size(40.dp).testTag("present")) } + item("empty") { } + } + } + } + } + waitForIdle() + onNodeWithTag("present").assertExists() + // Nothing collapsed, so no chip: an item with no content costs the strip nothing at all. + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).assertDoesNotExist() + } + } + + /** + * Shrinking a strip with a compressible control past its overflow point, twice: the first pass learns + * the chip's width, so the second packs in two walks that offer the search box two different bounds. + * A strip that measured the box on each walk would measure one Measurable twice in a pass, which + * Compose refuses; the strip must instead settle with the box squeezed and the trailing control in + * the chip. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun shrinkingPastTheOverflowPointSqueezesRatherThanCrashing() { + runComposeUiTest { + var stripWidth by mutableStateOf(400.dp) + setContent { + UmamoTheme { + Box(modifier = Modifier.width(stripWidth)) { + OverflowRow { + pinnedItem("a") { Box(modifier = Modifier.size(40.dp).testTag("a")) } + item("search", minWidth = 40.dp) { Box(modifier = Modifier.width(120.dp).height(20.dp).testTag("search")) } + item("b") { Box(modifier = Modifier.size(40.dp).testTag("b")) } + item("c") { Box(modifier = Modifier.size(40.dp).testTag("c")) } + } + } + } + } + waitForIdle() + onNodeWithTag("search").assertWidthIsEqualTo(120.dp) + // Past the point where c no longer fits: the chip appears and the box gives up width for b. + stripWidth = 180.dp + waitForIdle() + onNodeWithContentDescription(MORE_LABEL).assertExists() + // Narrower again, now with the chip's width known: the second-walk bound differs from the first. + stripWidth = 150.dp + waitForIdle() + onNodeWithTag("a").assertExists() + onNodeWithTag("search").assertExists() + onNodeWithContentDescription(MORE_LABEL).assertExists() + } + } + + /** + * Composes the standard three-control strip inside a fixed-width box: one pinned 40.dp control + * followed by two collapsible 40.dp controls. + * + * @param Dp stripWidth The width the strip is given. + */ + @OptIn(ExperimentalTestApi::class) + private fun ComposeUiTest.setStrip(stripWidth: Dp) { + setContent { + UmamoTheme { + Box(modifier = Modifier.width(stripWidth)) { + OverflowRow { + pinnedItem("a") { Box(modifier = Modifier.size(40.dp).testTag("a")) } + item("b") { Box(modifier = Modifier.size(40.dp).testTag("b")) } + item("c") { Box(modifier = Modifier.size(40.dp).testTag("c")) } + } + } + } + } + waitForIdle() + } + + private companion object { + /** The overflow chip's English name; it doubles as its accessible label. */ + const val MORE_LABEL = "More" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/SearchFieldTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/SearchFieldTest.kt new file mode 100644 index 0000000..05f98cf --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/SearchFieldTest.kt @@ -0,0 +1,170 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.width +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The clear affordance takes its width out of the text's rather than sitting on top of it. + * + * The bug this pins had the X overlaid at the field's trailing edge, so a long enough value ran straight + * underneath the glyph - and because a single-line BasicTextField scrolls the caret into view, the caret + * went under it too, leaving the user typing blind at the end of a long query. The fix is a reserved + * trailing slot in the decoration Row, so the assertion is on the geometry the reservation produces. + */ +class SearchFieldTest { + /** + * A trailing control shrinks the text viewport by at least its own width. + * + * Measured off the placeholder, which is the one node that fills the text viewport and is addressable + * from a test. An overlaid control would leave the viewport untouched, which is exactly the bug. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aTrailingControlReservesItsWidthFromTheText() { + val withoutTrailing = placeholderWidth(trailingSize = null) + val withTrailing = placeholderWidth(trailingSize = TRAILING_SIZE) + assertTrue( + withoutTrailing - withTrailing >= TRAILING_SIZE, + "the trailing slot must take its width out of the text viewport ($withoutTrailing -> $withTrailing)", + ) + } + + /** An empty field shows no clear affordance at all. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun anEmptyFieldShowsNoClearButton() { + runComposeUiTest { + setContent { + UmamoTheme { + SearchField(value = "", onValueChange = {}) + } + } + waitForIdle() + onNodeWithContentDescription(CLEAR_LABEL, useUnmergedTree = true).assertDoesNotExist() + } + } + + /** Clicking the X empties the query and takes the button away with it. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun clickingClearEmptiesTheQuery() { + runComposeUiTest { + setContent { + UmamoTheme { + var query by remember { mutableStateOf(LONG_QUERY) } + SearchField(value = query, onValueChange = { edited -> query = edited }) + } + } + waitForIdle() + onNodeWithContentDescription(CLEAR_LABEL, useUnmergedTree = true).assertIsDisplayed() + onNodeWithContentDescription(CLEAR_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + onNodeWithContentDescription(CLEAR_LABEL, useUnmergedTree = true).assertDoesNotExist() + } + } + + /** The clear button stays inside the field it belongs to. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theClearButtonSitsInsideTheField() { + runComposeUiTest { + setContent { + UmamoTheme { + Box(modifier = Modifier.testTag(FIELD_TAG)) { + SearchField(value = LONG_QUERY, onValueChange = {}) + } + } + } + waitForIdle() + val fieldBounds = onNodeWithTag(FIELD_TAG, useUnmergedTree = true).getUnclippedBoundsInRoot() + val clearBounds = onNodeWithContentDescription(CLEAR_LABEL, useUnmergedTree = true).getUnclippedBoundsInRoot() + assertTrue(clearBounds.left >= fieldBounds.left, "the clear button escaped the field's left edge") + assertTrue(clearBounds.right <= fieldBounds.right, "the clear button escaped the field's right edge") + } + } + + /** The field keeps the kit's standard header width unless a caller overrides it. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theFieldTakesTheStandardHeaderWidth() { + runComposeUiTest { + setContent { + UmamoTheme { + Box(modifier = Modifier.testTag(FIELD_TAG)) { + SearchField(value = "", onValueChange = {}) + } + } + } + waitForIdle() + assertEquals(SEARCH_FIELD_WIDTH, onNodeWithTag(FIELD_TAG, useUnmergedTree = true).getUnclippedBoundsInRoot().width) + } + } + + /** + * Composes one fixed-width [TextField] and returns how wide its placeholder was allowed to be - the + * width of the text viewport, since the placeholder fills the weighted box the editable text uses. + * + * @param Dp? trailingSize The trailing control's square size, or null for no trailing slot. + * @return Dp The placeholder's measured width. + */ + @OptIn(ExperimentalTestApi::class) + private fun placeholderWidth(trailingSize: Dp?): Dp { + var measured = 0.dp + runComposeUiTest { + setContent { + UmamoTheme { + TextField( + value = "", + onValueChange = {}, + modifier = Modifier.size(width = SEARCH_FIELD_WIDTH, height = 24.dp), + // A single unbroken run, so it cannot wrap at a space and the line fills the viewport. + placeholder = LONG_QUERY, + trailing = + if (trailingSize == null) { + null + } else { + { Box(modifier = Modifier.size(trailingSize)) } + }, + ) + } + } + waitForIdle() + measured = onNodeWithText(LONG_QUERY, useUnmergedTree = true).getUnclippedBoundsInRoot().width + } + return measured + } + + private companion object { + /** Longer than the 160.dp field, so the value genuinely reaches the trailing edge. */ + const val LONG_QUERY = "asdasdasdasdasdasdasdasdasdasdasd" + + /** The clear button's English name; it doubles as its accessible label. */ + const val CLEAR_LABEL = "Clear search" + + const val FIELD_TAG = "search" + + /** Wide enough that the reservation is unmistakable against layout rounding. */ + val TRAILING_SIZE = 40.dp + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/SingleOrDoubleClickTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/SingleOrDoubleClickTest.kt new file mode 100644 index 0000000..09bf6d7 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/SingleOrDoubleClickTest.kt @@ -0,0 +1,182 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isCtrlPressed +import androidx.compose.ui.input.pointer.isShiftPressed +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.MouseButton +import androidx.compose.ui.test.click +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The press-timing modifier under real pointer input: what reaches the single action, what reaches the + * double action, and what reaches neither. + */ +@OptIn(ExperimentalTestApi::class) +class SingleOrDoubleClickTest { + /** What the modifier dispatched, in order: "single", "single+ctrl", "single+shift", or "double". */ + private val dispatched = mutableListOf() + + /** + * Mounts a 200 x 100 target carrying the modifier, with a 40 x 40 child in its top-left corner that + * consumes its own presses the way the outliner's chevron and eye do. + * + * @param ComposeUiTest test The running UI test. + * @param Function enabled Reads whether the modifier is enabled. + */ + private fun mount(test: ComposeUiTest, enabled: () -> Boolean = { true }) { + test.setContent { + Box( + modifier = + Modifier + .size(width = 200.dp, height = 100.dp) + .testTag(TARGET_TAG) + .singleOrDoubleClick( + enabled = enabled(), + onSingle = { modifiers -> + dispatched += + when { + modifiers.isCtrlPressed -> "single+ctrl" + modifiers.isShiftPressed -> "single+shift" + else -> "single" + } + }, + onDouble = { dispatched += "double" }, + ), + ) { + Box( + modifier = + Modifier + .align(Alignment.TopStart) + .size(40.dp) + .pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + if (event.type == PointerEventType.Press) { + event.changes.forEach { change -> change.consume() } + } + } + } + }, + ) + } + } + } + + /** The single action fires on the press itself, before the release. */ + @Test + fun theSingleActionFiresOnPress() = + runComposeUiTest { + mount(this) + onNodeWithTag(TARGET_TAG).performMouseInput { + moveTo(Offset(150f, 50f)) + press() + } + waitForIdle() + assertEquals(listOf("single"), dispatched, "dispatched before any release") + onNodeWithTag(TARGET_TAG).performMouseInput { release() } + } + + /** A second press inside the window runs the double action after the single one. */ + @Test + fun twoQuickClicksRunSingleThenDouble() = + runComposeUiTest { + mount(this) + onNodeWithTag(TARGET_TAG).performMouseInput { + click(Offset(150f, 50f)) + advanceEventTime(100L) + click(Offset(150f, 50f)) + } + waitForIdle() + assertEquals(listOf("single", "double"), dispatched) + } + + /** A right press is the context-menu gesture and a child's consumed press is the child's own. */ + @Test + fun secondaryAndConsumedPressesAreIgnored() = + runComposeUiTest { + mount(this) + onNodeWithTag(TARGET_TAG).performMouseInput { + moveTo(Offset(150f, 50f)) + press(MouseButton.Secondary) + release(MouseButton.Secondary) + advanceEventTime(500L) + click(Offset(20f, 20f)) + } + waitForIdle() + assertEquals(emptyList(), dispatched) + } + + /** A disabled modifier handles nothing, and turning it back on starts with no pending press. */ + @Test + fun aDisabledModifierHandlesNothing() = + runComposeUiTest { + var enabled by mutableStateOf(false) + mount(this) { enabled } + onNodeWithTag(TARGET_TAG).performMouseInput { click(Offset(150f, 50f)) } + waitForIdle() + assertEquals(emptyList(), dispatched, "nothing while disabled") + + enabled = true + waitForIdle() + onNodeWithTag(TARGET_TAG).performMouseInput { click(Offset(150f, 50f)) } + waitForIdle() + assertEquals(listOf("single"), dispatched, "the first press after enabling is a single") + } + + /** + * A press holding a selection modifier reaches the single action with that modifier, and never takes + * part in a double click on either side. + */ + @Test + fun aModifiedPressIsAlwaysASingle() = + runComposeUiTest { + mount(this) + onNodeWithTag(TARGET_TAG).performKeyInput { keyDown(Key.CtrlLeft) } + onNodeWithTag(TARGET_TAG).performMouseInput { + click(Offset(150f, 50f)) + advanceEventTime(100L) + click(Offset(150f, 50f)) + } + onNodeWithTag(TARGET_TAG).performKeyInput { keyUp(Key.CtrlLeft) } + onNodeWithTag(TARGET_TAG).performMouseInput { + advanceEventTime(100L) + click(Offset(150f, 50f)) + } + onNodeWithTag(TARGET_TAG).performKeyInput { keyDown(Key.ShiftLeft) } + onNodeWithTag(TARGET_TAG).performMouseInput { + advanceEventTime(100L) + click(Offset(150f, 50f)) + } + onNodeWithTag(TARGET_TAG).performKeyInput { keyUp(Key.ShiftLeft) } + waitForIdle() + assertEquals( + listOf("single+ctrl", "single+ctrl", "single", "single+shift"), + dispatched, + "Ctrl twice toggles twice, a plain click after Ctrl selects, and Shift never completes a double", + ) + } + + private companion object { + const val TARGET_TAG = "target" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/TextEditContextMenuTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/TextEditContextMenuTest.kt new file mode 100644 index 0000000..6eb44cb --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/kit/TextEditContextMenuTest.kt @@ -0,0 +1,109 @@ +package org.umamo.ui.kit + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.MouseButton +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The kit's text-field context menu, driven with real pointer input against a real composition. + * + * This is not a paranoid test. The whole mechanism turns on one fact that cannot be checked by reading our + * own code: whether an initial-pass secondary-click detector really does outrank the handler Compose + * installs INSIDE its text field. If a Compose upgrade moves that handler earlier, the built-in menu + * silently takes the right-click back and the keyframe entries become unreachable again - the exact bug this + * replaced, returning with no compile error to announce it. + */ +class TextEditContextMenuTest { + /** A text field inside a context-menu area, which is how every real one is mounted. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aTextFieldsMenuCarriesTheEnclosingItemsThenTheClipboardOnes() = + runComposeUiTest { + setContent { + UmamoTheme { + ContextMenuArea(items = listOf(MenuItem.Action(label = "Insert Keyframe", onSelect = {}))) { + Box(modifier = Modifier.size(width = 200.dp, height = 40.dp).testTag("field")) { + TextField(value = "abc", onValueChange = {}) + } + } + } + } + onNodeWithTag("field").performMouseInput { + moveTo(Offset(20f, 10f)) + press(MouseButton.Secondary) + release(MouseButton.Secondary) + } + waitForIdle() + // The enclosing area's entry proves ours won the click; the clipboard entry proves we replaced + // rather than merely suppressed Compose's menu. + onNodeWithText("Insert Keyframe").assertExists() + onNodeWithText("Paste").assertExists() + } + + /** + * A focus requester in the caller's modifier still reaches the FIELD, not the menu's wrapper. + * + * The command palette opens with its search box already focused, and it asks for that with a + * focusRequester passed in the modifier. Wrapping the field in a box and giving the box that modifier + * compiles, renders identically, and silently stops the palette from being typed into. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aCallersFocusRequesterStillReachesTheField() = + runComposeUiTest { + val focus = FocusRequester() + var typed = "" + setContent { + UmamoTheme { + TextField( + value = typed, + onValueChange = { edited -> typed = edited }, + modifier = Modifier.fillMaxWidth().focusRequester(focus).testTag("field"), + ) + } + LaunchedEffect(Unit) { focus.requestFocus() } + } + waitForIdle() + onNodeWithTag("field").performTextInput("hi") + waitForIdle() + assertEquals("hi", typed, "the field must have taken focus and received the keystrokes") + } + + /** With no enclosing area the menu is the clipboard entries alone - and no leading separator. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aBareTextFieldStillGetsTheClipboardMenu() = + runComposeUiTest { + setContent { + UmamoTheme { + Box(modifier = Modifier.size(width = 200.dp, height = 40.dp).testTag("field")) { + TextField(value = "abc", onValueChange = {}) + } + } + } + onNodeWithTag("field").performMouseInput { + moveTo(Offset(20f, 10f)) + press(MouseButton.Secondary) + release(MouseButton.Secondary) + } + waitForIdle() + onNodeWithText("Select All").assertExists() + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/model/AtlasRepackAdjustTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/model/AtlasRepackAdjustTest.kt new file mode 100644 index 0000000..1576767 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/model/AtlasRepackAdjustTest.kt @@ -0,0 +1,275 @@ +package org.umamo.ui.model + +import kotlinx.coroutines.job +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.runBlocking +import org.umamo.edit.EditorSession +import org.umamo.edit.OperatorParameter +import org.umamo.edit.withAtlasPins +import org.umamo.edit.withAtlasPlacements +import org.umamo.edit.withParameter +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.packAtlas +import org.umamo.render.DecodedImage +import org.umamo.render.SourceArtRasters +import org.umamo.render.atlasCompositionOf +import org.umamo.render.atlasPlacementFromPack +import org.umamo.render.deriveAtlasTextures +import org.umamo.render.encodeAtlasPng +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTile +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.DrawableMesh +import org.umamo.runtime.model.PuppetAtlas +import org.umamo.runtime.model.PuppetModel +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Pins the repack as the operation settings strip's first client: the first run registers itself + * with its options as rows, an adjustment re-packs the same decoded input under the edited options + * from the model the repack ran on and rewrites the repack's own history step (the stack does not + * grow, one undo returns to the base), the result equals a fresh pack under those options and + * derives byte-identically under the composition it recorded, a refused adjustment leaves the + * previous result standing with the record still live, and a pinned tile keeps its placement + * through a repack until the Keep Pinned Tiles row is turned off. + */ +class AtlasRepackAdjustTest { + private val tileIds = listOf(AtlasTileId("t0"), AtlasTileId("t1"), AtlasTileId("t2")) + + private fun tileRaster(width: Int, height: Int, margin: Int, red: Int): DecodedImage { + val rgba = ByteArray(width * height * 4) + for (rowIndex in margin until height - margin) { + for (columnIndex in margin until width - margin) { + val offset = (rowIndex * width + columnIndex) * 4 + rgba[offset] = red.toByte() + rgba[offset + 1] = (rowIndex * 16 + columnIndex).toByte() + rgba[offset + 2] = 0x40 + rgba[offset + 3] = 0xFF.toByte() + } + } + return DecodedImage(rgba, width, height) + } + + private class Fixture(val model: PuppetModel, val store: SourceArtRasters) + + /** + * Three unpacked tiles, each sampled by one quad-meshed drawable over its whole art, with a store + * serving their pixels - a document the repack packs from scratch. + * + * @return Fixture The model and its store. + */ + private fun unpackedFixture(): Fixture { + val rasters = + listOf( + tileRaster(12, 10, 2, 0x10), + tileRaster(8, 16, 1, 0x20), + tileRaster(10, 10, 0, 0x30), + ) + val tiles = tileIds.mapIndexed { tileIndex, tileId -> AtlasTile(tileId, tileId.raw, rasters[tileIndex].width, rasters[tileIndex].height) } + val drawables = + tileIds.mapIndexed { tileIndex, tileId -> + Drawable( + id = DrawableId("d$tileIndex"), + name = "d$tileIndex", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = + DrawableMesh( + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), + floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f), + intArrayOf(0, 1, 2, 1, 3, 2), + ), + geometryGrid = null, + atlasTileId = tileId, + ) + } + val model = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = drawables, + rootChildren = emptyList(), + rootPartId = null, + canvasWidth = 100f, + canvasHeight = 100f, + worldOriginX = 50f, + worldOriginZ = 50f, + atlas = PuppetAtlas(pages = emptyList(), tiles = tiles), + ) + val pngByTile = tileIds.withIndex().associate { (tileIndex, tileId) -> tileId to encodeAtlasPng(rasters[tileIndex]) } + return Fixture(model, SourceArtRasters.fromPng { tileId -> pngByTile[tileId] }) + } + + @Test + fun anAdjustmentRepacksFromTheBaseAndRewritesTheRepackStep() = + runBlocking { + val fixture = unpackedFixture() + val session = EditorSession(fixture.model) + var remembered: AtlasPackOptions? = null + var reports = 0 + val host = + AtlasRepackHost( + session = session, + artRasters = fixture.store, + sessionAtlasPages = null, + premultipliedAlpha = false, + scope = this, + report = { reports++ }, + rememberOptions = { options, _ -> remembered = options }, + ) + val initial = AtlasPackOptions(maxPageSize = 64) + + runAtlasRepack(host, initial, areaId = "uv-1") + + val record = assertNotNull(session.adjustableOperation.value, "the repack registers itself as adjustable") + assertEquals("uv-1", record.areaId) + assertEquals(initial, remembered, "the options the pack ran with are remembered") + assertSame(fixture.model, record.baseSnapshot.model, "the base is the model the repack ran on") + val stepsAfterRepack = session.historyView.value.steps.size + assertEquals(2, stepsAfterRepack, "seed plus one repack step") + + val adjustedParameters = + record.parameters + .withParameter(RepackParameterKeys.GUTTER, OperatorParameter.IntParameter(RepackParameterKeys.GUTTER, RepackParameterKeys.GUTTER, 8, 0, REPACK_MAX_GUTTER)) + .withParameter(RepackParameterKeys.ALLOW_ROTATION, OperatorParameter.BooleanParameter(RepackParameterKeys.ALLOW_ROTATION, RepackParameterKeys.ALLOW_ROTATION, true)) + session.adjustLastOperation(adjustedParameters) + coroutineContext.job.children.toList().joinAll() + + val expectedOptions = initial.copy(gutter = 8, allowRotation = true) + assertEquals(expectedOptions, remembered, "the adjusted options are what the re-pack ran with") + assertEquals(0, reports, "nothing refused") + assertEquals(stepsAfterRepack, session.historyView.value.steps.size, "the adjustment rewrote the step rather than adding one") + assertNotNull(session.adjustableOperation.value, "the record stays live for the next adjustment") + + // The result is exactly a fresh pack of the same input under those options, from the base. + val packInput = buildRepackPackInput(fixture.model) { tileId -> fixture.store.decodeRaster(tileId) } + val fresh = packAtlas(packInput.items, expectedOptions) + val freshByKey = fresh.placements.associateBy { placement -> placement.key } + val adjustedAtlas = session.model.value.atlas + assertEquals(fresh.pages.map { page -> AtlasPage(page.width, page.height) }, adjustedAtlas.pages) + for (tile in adjustedAtlas.tiles) { + assertEquals(freshByKey[tile.id.raw]?.let(::atlasPlacementFromPack), tile.placement, "tile ${tile.id.raw} sits where the fresh pack put it") + } + assertEquals(atlasCompositionOf(expectedOptions), adjustedAtlas.composition, "the composition follows the adjusted options") + val derived = assertNotNull(deriveAtlasTextures(session.model.value, fixture.store, false)) + for (pageIndex in fresh.pages.indices) { + assertContentEquals(fresh.pages[pageIndex].rgba, derived.atlases[pageIndex].rgba, "page $pageIndex derives byte-identically under the recorded composition") + } + + session.undo() + assertSame(fixture.model, session.model.value, "one undo returns to the model the repack ran on") + assertNull(session.adjustableOperation.value, "undo ends the adjustable operation") + } + + @Test + fun aPinnedTileKeepsItsPlacementThroughARepackAndMovesWhenTheRowIsOff() = + runBlocking { + val fixture = unpackedFixture() + // Tile 1 hand-placed through the placement edit - turned, reduced, at (30, 30) on a 64 page, its + // coordinates re-mapped so its mesh still reaches its own art - and pinned; the others unpacked. + val kept = AtlasPlacement(pageIndex = 0, positionX = 30f, positionY = 30f, scaleX = 0.75f, scaleY = 0.75f, rotationDegrees = 30f) + val pinnedTileId = tileIds[1] + val pinnedModel = + fixture.model + .copy(atlas = fixture.model.atlas.copy(pages = listOf(AtlasPage(64, 64)))) + .withAtlasPlacements(mapOf(pinnedTileId to kept)) + .withAtlasPins(listOf(pinnedTileId), pinned = true) + assertTrue(pinnedModel.atlas.tileById.getValue(pinnedTileId).pinned, "the fixture pinned its tile") + val session = EditorSession(pinnedModel) + var rememberedKeepPinned: Boolean? = null + val reports = ArrayList() + val host = + AtlasRepackHost( + session = session, + artRasters = fixture.store, + sessionAtlasPages = null, + premultipliedAlpha = false, + scope = this, + report = { report -> reports.add(report) }, + rememberOptions = { _, keepPinned -> rememberedKeepPinned = keepPinned }, + ) + val options = AtlasPackOptions(maxPageSize = 64) + val uvsBefore = pinnedModel.drawables.first { drawable -> drawable.atlasTileId == pinnedTileId }.mesh!!.uvs + + runAtlasRepack(host, options, areaId = null) + + val refusalText = reports.flatMap { report -> report.refusals }.joinToString { refusal -> "${refusal.tileName}: ${refusal.reason}" } + val record = assertNotNull(session.adjustableOperation.value, "the repack registered (refusals: $refusalText)") + assertEquals(true, rememberedKeepPinned) + assertTrue(repackKeepPinnedOf(record.parameters), "the row shows the pins kept") + val repacked = session.model.value + val keptTile = repacked.atlas.tileById.getValue(pinnedTileId) + assertEquals(kept, keptTile.placement, "the pinned tile stayed exactly where it was") + assertTrue(keptTile.pinned, "and stays pinned") + assertSame(uvsBefore, repacked.drawables.first { drawable -> drawable.atlasTileId == pinnedTileId }.mesh!!.uvs, "its coordinates did not move") + for (tile in repacked.atlas.tiles) { + if (tile.id != pinnedTileId) { + assertNotNull(tile.placement, "tile ${tile.id.raw} packed around the pin") + } + } + // The pages the pack composed (what the resolver is pre-warmed with) are what the model derives. + val packInput = buildRepackPackInput(pinnedModel) { tileId -> fixture.store.decodeRaster(tileId) } + val fresh = packAtlas(packInput.itemsFor(keepPinned = true), options) + assertEquals(pinnedTileId.raw, fresh.fixed.single().key) + val derived = assertNotNull(deriveAtlasTextures(repacked, fixture.store, false)) + for (pageIndex in fresh.pages.indices) { + assertContentEquals(fresh.pages[pageIndex].rgba, derived.atlases[pageIndex].rgba, "page $pageIndex derives byte-identically, pinned tile included") + } + val stepsAfterRepack = session.historyView.value.steps.size + + // Keep Pinned Tiles off: the same decoded input re-packs with the pinned tile free. + session.adjustLastOperation( + record.parameters.withParameter(RepackParameterKeys.KEEP_PINNED, OperatorParameter.BooleanParameter(RepackParameterKeys.KEEP_PINNED, RepackParameterKeys.KEEP_PINNED, false)), + ) + coroutineContext.job.children.toList().joinAll() + + assertEquals(false, rememberedKeepPinned) + assertEquals(stepsAfterRepack, session.historyView.value.steps.size, "the adjustment rewrote the step") + val freed = session.model.value.atlas.tileById.getValue(pinnedTileId) + val freedPlacement = assertNotNull(freed.placement) + assertTrue(freedPlacement != kept && freedPlacement.rotationDegrees == 0f && freedPlacement.scaleX == 1f, "the tile packed like any other") + assertTrue(freed.pinned, "the pin itself survives the pack that ignored it") + } + + @Test + fun aRefusedAdjustmentLeavesThePreviousResultStanding() = + runBlocking { + val fixture = unpackedFixture() + val session = EditorSession(fixture.model) + var reports = 0 + val host = + AtlasRepackHost( + session = session, + artRasters = fixture.store, + sessionAtlasPages = null, + premultipliedAlpha = false, + scope = this, + report = { reports++ }, + rememberOptions = { _, _ -> }, + ) + runAtlasRepack(host, AtlasPackOptions(maxPageSize = 64), areaId = null) + val record = assertNotNull(session.adjustableOperation.value) + val repacked = session.model.value + + // A page too small for any tile: every bound tile refuses. + val tooSmall = record.parameters.withParameter(RepackParameterKeys.PAGE_SIZE, OperatorParameter.ChoiceParameter(RepackParameterKeys.PAGE_SIZE, RepackParameterKeys.PAGE_SIZE, "4", emptyList())) + session.adjustLastOperation(tooSmall) + coroutineContext.job.children.toList().joinAll() + + assertEquals(1, reports, "the refusal reports through the same surface as a first run's") + assertSame(repacked, session.model.value, "the previous result stands") + assertTrue(session.adjustableOperation.value != null, "the record stays live so the rigger can pick another size") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/model/AtlasRepackMeshDisjointTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/model/AtlasRepackMeshDisjointTest.kt new file mode 100644 index 0000000..d911d67 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/model/AtlasRepackMeshDisjointTest.kt @@ -0,0 +1,154 @@ +package org.umamo.ui.model + +import org.umamo.edit.withAtlasRepack +import org.umamo.format.atlas.AtlasPackOptions +import org.umamo.format.atlas.packAtlas +import org.umamo.format.cmo3.Cmo3 +import org.umamo.format.cmo3.model.custom.CModelSource +import org.umamo.format.png.PngCodec +import org.umamo.interop.cmo3.Cmo3Import +import org.umamo.interop.cmo3.cmo3AtlasIngest +import org.umamo.render.DecodedImage +import org.umamo.render.atlasPlacementFromPack +import org.umamo.runtime.model.AtlasPage +import org.umamo.runtime.model.AtlasPlacement +import org.umamo.runtime.model.AtlasTileId +import org.umamo.runtime.model.PuppetModel +import java.io.File +import kotlin.math.max +import kotlin.math.min +import kotlin.test.Test +import kotlin.test.assertTrue + +/** + * The repack's mesh-disjointness gate: after a repack, no two tiles' MESH footprints may intersect + * on a page, and every footprint stays on its page. + * + * Pixel trims alone cannot guarantee this - a mesh rings outside its art's opaque region (Erica: up + * to 58px past the trim, and 127 of 128 meshes past the raster itself), so a pack spaced by trims + * put 308 tile pairs over each other and hung meshes off the page edge. The official editor's own + * packing keeps mesh footprints disjoint (its only overlaps are deliberate duplicate-art sharing), + * which is the behavior the mesh reserve reproduces. This drives the SHIPPED input path + * (buildRepackPackInput), so what it proves disjoint is exactly what the command packs. + */ +class AtlasRepackMeshDisjointTest { + private val sample: File? = System.getProperty("cmo3.sample")?.let(::File)?.takeIf { it.isFile } + + private class Rect(val left: Float, val top: Float, val right: Float, val bottom: Float) { + fun intersectionArea(other: Rect): Float { + val width = min(right, other.right) - max(left, other.left) + val height = min(bottom, other.bottom) - max(top, other.top) + return if (width > 0f && height > 0f) width * height else 0f + } + + fun union(other: Rect): Rect = + Rect(min(left, other.left), min(top, other.top), max(right, other.right), max(bottom, other.bottom)) + + override fun toString(): String = "[%.1f,%.1f %.0fx%.0f]".format(left, top, right - left, bottom - top) + } + + /** Per placed+bound tile: the union of its drawables' mesh bboxes in PAGE pixels, keyed by page. */ + private fun meshFootprintsByTile(model: PuppetModel): Map> { + val tileById = model.atlas.tiles.associateBy { tile -> tile.id } + val footprints = HashMap>() + for (drawable in model.drawables) { + val tileId = drawable.atlasTileId ?: continue + val placement = tileById[tileId]?.placement ?: continue + val page = model.atlas.pages.getOrNull(placement.pageIndex) ?: continue + val uvs = drawable.mesh?.uvs ?: continue + if (uvs.size < 2) { + continue + } + var minU = Float.MAX_VALUE + var maxU = -Float.MAX_VALUE + var minV = Float.MAX_VALUE + var maxV = -Float.MAX_VALUE + var componentIndex = 0 + while (componentIndex + 1 < uvs.size) { + minU = min(minU, uvs[componentIndex]) + maxU = max(maxU, uvs[componentIndex]) + minV = min(minV, uvs[componentIndex + 1]) + maxV = max(maxV, uvs[componentIndex + 1]) + componentIndex += 2 + } + val bounds = Rect(minU * page.width, minV * page.height, maxU * page.width, maxV * page.height) + val existing = footprints[tileId] + footprints[tileId] = placement.pageIndex to (existing?.second?.union(bounds) ?: bounds) + } + return footprints + } + + @Test + fun repackedMeshFootprintsAreDisjointAndOnThePage() { + val file = sample + if (file == null) { + println("cmo3.sample not present; skipping the repack mesh-disjointness gate") + return + } + val cmo3 = Cmo3.read(file.readBytes()) + val root = cmo3.root as? CModelSource ?: error("root is not a CModelSource") + val imported = Cmo3Import.fromModelSource(root) + if (imported.atlas.tiles.isEmpty() || !imported.atlas.storedUvsAddressPages) { + println("${file.name} is not repackable; skipping the mesh-disjointness gate") + return + } + val ingest = cmo3AtlasIngest(root) + val decodeRaster = { tileId: AtlasTileId -> + ingest.imageResourceByTile[tileId]?.let(cmo3::extractLayerPng)?.let { bytes -> + val image = PngCodec.read(bytes) + DecodedImage(image.rgba, image.width, image.height) + } + } + + // The SHIPPED pack input (pixels + mesh reserves), packed at the document's own page size. + val packInput = buildRepackPackInput(imported, decodeRaster) + val options = + AtlasPackOptions(maxPageSize = imported.atlas.pages.maxOf { page -> max(page.width, page.height) }) + val packResult = packAtlas(packInput.items, options) + assertTrue( + repackRefusals(imported, packResult.skipped, packInput.undecodableTileIds).isEmpty(), + "the corpus sample must repack cleanly", + ) + val packedByKey = packResult.placements.associateBy { placement -> placement.key } + val placements = HashMap() + for (tile in imported.atlas.tiles) { + placements[tile.id] = packedByKey[tile.id.raw]?.let { packed -> atlasPlacementFromPack(packed) } + } + val repacked = + imported.withAtlasRepack(packResult.pages.map { page -> AtlasPage(page.width, page.height) }, placements) + + val tileNames = imported.atlas.tiles.associateBy({ tile -> tile.id }, { tile -> tile.name }) + val footprints = meshFootprintsByTile(repacked).entries.toList() + val overlaps = ArrayList() + for (firstIndex in footprints.indices) { + for (secondIndex in firstIndex + 1 until footprints.size) { + val (firstPage, firstRect) = footprints[firstIndex].value + val (secondPage, secondRect) = footprints[secondIndex].value + if (firstPage != secondPage) { + continue + } + val area = firstRect.intersectionArea(secondRect) + if (area > 0f) { + overlaps.add( + "'${tileNames[footprints[firstIndex].key]}' x '${tileNames[footprints[secondIndex].key]}'" + + " ${"%.0f".format(area)}px2 $firstRect vs $secondRect", + ) + } + } + } + val offPage = ArrayList() + for ((tileId, footprint) in footprints.map { entry -> entry.key to entry.value }) { + val (pageIndex, rect) = footprint + val page = repacked.atlas.pages[pageIndex] + if (rect.left < 0f || rect.top < 0f || rect.right > page.width || rect.bottom > page.height) { + offPage.add("'${tileNames[tileId]}' $rect off the ${page.width}x${page.height} page") + } + } + println( + "[repack-gate] ${footprints.size} mesh footprints on ${packResult.pages.size} page(s), " + + "${overlaps.size} overlap(s), ${offPage.size} off-page", + ) + assertTrue(overlaps.isEmpty(), "mesh footprints overlap after repack:\n" + overlaps.take(10).joinToString("\n")) + assertTrue(offPage.isEmpty(), "mesh footprints leave the page after repack:\n" + offPage.take(10).joinToString("\n")) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/properties/DisplayedChannelValueTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/properties/DisplayedChannelValueTest.kt new file mode 100644 index 0000000..da87e1e --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/properties/DisplayedChannelValueTest.kt @@ -0,0 +1,112 @@ +package org.umamo.ui.properties + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.v2.runComposeUiTest +import org.umamo.edit.EditorSession +import org.umamo.runtime.model.BlendMode +import org.umamo.runtime.model.ChannelGrids +import org.umamo.runtime.model.ChannelValue +import org.umamo.runtime.model.ColorRgb +import org.umamo.runtime.model.Drawable +import org.umamo.runtime.model.DrawableId +import org.umamo.runtime.model.FormChannel +import org.umamo.runtime.model.KeyableTarget +import org.umamo.runtime.model.KeyformAxis +import org.umamo.runtime.model.KeyformCell +import org.umamo.runtime.model.KeyformGrid +import org.umamo.runtime.model.KeyformOwner +import org.umamo.runtime.model.Parameter +import org.umamo.runtime.model.ParameterId +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * What a keyable properties row DISPLAYS: the pending unkeyed edit, else the track at the pose, else the + * static. + * + * Driven through a real composition because the resolver reads the session's flows, and the bug it exists + * to prevent - a keyed color field stuck on the shadowed static, so typing a new value looked rejected - + * is invisible to any test that does not actually recompose on those flows. + */ +class DisplayedChannelValueTest { + private val angleX = ParameterId("ParamAngleX") + private val drawableId = DrawableId("d") + private val target = KeyableTarget(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR) + + private val staticColor = ColorRgb(1f, 1f, 1f) + private val keyedAtDefault = ColorRgb(0.25f, 1f, 0f) + private val pendingColor = ColorRgb(1f, 0f, 1f) + + /** A drawable whose multiply color is keyed over ParamAngleX, holding [keyedAtDefault] at the default. */ + private fun model(): PuppetModel = + PuppetModel( + parameters = listOf(Parameter(angleX, "ParamAngleX", min = -30f, max = 30f, default = 0f)), + parts = emptyList(), + deformers = emptyList(), + drawables = + listOf( + Drawable( + id = drawableId, + name = "d", + parentDeformerId = null, + blendMode = BlendMode.Normal, + maskedBy = emptyList(), + mesh = null, + geometryGrid = null, + multiplyColor = staticColor, + channelGrids = + ChannelGrids( + mapOf( + FormChannel.MULTIPLY_COLOR to + KeyformGrid( + axes = listOf(KeyformAxis(angleX, floatArrayOf(-30f, 0f, 30f))), + cells = + listOf( + KeyformCell(intArrayOf(0), ChannelValue.Color(keyedAtDefault)), + KeyformCell(intArrayOf(1), ChannelValue.Color(keyedAtDefault)), + KeyformCell(intArrayOf(2), ChannelValue.Color(keyedAtDefault)), + ), + ), + ), + ), + ), + ), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** + * A keyed channel shows the TRACK's value, not the static it shadows - and a pending unkeyed edit wins + * over both, so a typed value stays on screen instead of snapping back. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun pendingEditWinsOverTrackWhichWinsOverStatic() = + runComposeUiTest { + val session = EditorSession(model()) + var shown: ColorRgb? = null + setContent { + CompositionLocalProvider( + LocalPuppet provides model(), + LocalEditorSession provides session, + ) { + shown = + displayedChannelColor(KeyformOwner.Drawable(drawableId), FormChannel.MULTIPLY_COLOR, staticColor) + } + } + waitForIdle() + assertEquals(keyedAtDefault, shown, "a keyed channel must show the track, not the shadowed static") + + session.setPendingChannelEdit(target, ChannelValue.Color(pendingColor)) + waitForIdle() + assertEquals(pendingColor, shown, "a pending unkeyed edit must win over the stored track") + + session.clearPendingChannelEdits() + waitForIdle() + assertEquals(keyedAtDefault, shown, "discarding the pending edit returns the field to the track") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/properties/PropertyRowTooltipTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/properties/PropertyRowTooltipTest.kt new file mode 100644 index 0000000..d6f8d45 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/properties/PropertyRowTooltipTest.kt @@ -0,0 +1,130 @@ +package org.umamo.ui.properties + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.isPopup +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test + +/** + * The row description under real pointer input: it shows over a row's label, never over its control, and + * a blank one shows nothing. + * + * The control half is the case worth pinning. A tooltip wrapping the whole row compiles, looks right on a + * plain row, and stacks a second card over every relation and color field's own button tooltips, because + * nested tooltip areas all fire at once. + */ +@OptIn(ExperimentalTestApi::class) +class PropertyRowTooltipTest { + /** Hovering the label half shows the description once the pointer has rested. */ + @Test + fun aFieldRowsLabelShowsItsDescription() = + runComposeUiTest { + mountFieldRow(this, DESCRIPTION) + hoverAt(this, LABEL_HALF) + onNodeWithText(DESCRIPTION, useUnmergedTree = true).assertExists() + } + + /** Hovering the control half leaves the control's own hover alone. */ + @Test + fun aFieldRowsControlDoesNotShowTheDescription() = + runComposeUiTest { + mountFieldRow(this, DESCRIPTION) + hoverAt(this, CONTROL_HALF) + onNodeWithText(DESCRIPTION, useUnmergedTree = true).assertDoesNotExist() + onAllNodes(isPopup()).assertCountEquals(0) + } + + /** A row with nothing to say pops nothing, so a caller can pass an unconditional description. */ + @Test + fun aBlankDescriptionAttachesNoTooltip() = + runComposeUiTest { + mountFieldRow(this, "") + hoverAt(this, LABEL_HALF) + onAllNodes(isPopup()).assertCountEquals(0) + } + + /** A checkbox row's label sits beside its box in the right half, so the box is what the description tooltips. */ + @Test + fun aCheckboxRowShowsItsDescriptionOverTheBox() = + runComposeUiTest { + mount(this) { + PropertyCheckboxRow(checked = false, onCheckedChange = {}, label = LABEL, description = DESCRIPTION) + } + hoverAt(this, CONTROL_HALF) + onNodeWithText(DESCRIPTION, useUnmergedTree = true).assertExists() + } + + /** + * Mounts a field row whose control is a plain box filling its half. + * + * @param ComposeUiTest test The running UI test. + * @param String description The row's description. + */ + private fun mountFieldRow(test: ComposeUiTest, description: String) { + mount(test) { + PropertyFieldRow(LABEL, description = description) { + Box(modifier = Modifier.fillMaxWidth().height(20.dp)) + } + } + } + + /** + * Mounts [row] in a fixed-size themed box tagged for the pointer to find. + * + * @param ComposeUiTest test The running UI test. + * @param Function row The row under test. + */ + private fun mount(test: ComposeUiTest, row: @Composable () -> Unit) { + test.setContent { + UmamoTheme { + Box(modifier = Modifier.size(width = 400.dp, height = 30.dp).testTag(ROW_TAG)) { + row() + } + } + } + } + + /** + * Rests the pointer at [fractionX] of the row's width, halfway down, and lets the tooltip delay run out. + * + * @param ComposeUiTest test The running UI test. + * @param Float fractionX Where across the row to rest, 0 at the left edge and 1 at the right. + */ + private fun hoverAt(test: ComposeUiTest, fractionX: Float) { + test.onNodeWithTag(ROW_TAG).performMouseInput { + moveTo(Offset(width * fractionX, height / 2f)) + } + test.mainClock.advanceTimeBy(TOOLTIP_WAIT_MILLIS) + test.waitForIdle() + } + + private companion object { + const val ROW_TAG = "row" + const val LABEL = "Opacity" + const val DESCRIPTION = "How opaque the mesh draws." + + /** A point in the label half of a field row. */ + const val LABEL_HALF = 0.25f + + /** A point in the control half, where a checkbox row's box and label sit. */ + const val CONTROL_HALF = 0.6f + + /** Comfortably past the tooltip's dwell delay. */ + const val TOOLTIP_WAIT_MILLIS = 1_000L + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/settings/KeybindingReassignKeysTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/settings/KeybindingReassignKeysTest.kt new file mode 100644 index 0000000..ae6cd37 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/settings/KeybindingReassignKeysTest.kt @@ -0,0 +1,221 @@ +package org.umamo.ui.settings + +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.v2.runComposeUiTest +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.umamo.settings.Settings +import org.umamo.storage.OkioAppStorage +import org.umamo.ui.LocalSettings +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.loadKeymap +import org.umamo.ui.action.parseKeyChord +import org.umamo.ui.kit.ConfirmDialog +import org.umamo.ui.kit.KeyCaptureController +import org.umamo.ui.kit.LocalKeyCapture +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.cmd_mesh_grab +import org.umamo.ui.resources.cmd_preferences +import org.umamo.ui.theme.UmamoTheme +import org.umamo.ui.workspace.ConfirmRequest +import org.umamo.ui.workspace.ShellModalState +import org.umamo.ui.workspace.ShellOverlayState +import org.umamo.ui.workspace.commands.registerAll +import org.umamo.ui.workspace.handleModalKeyLadder +import org.umamo.ui.workspace.toShellKeyStroke +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Drives the keybindings editor with real key events under the shell's real modal ladder, the way it sits inside + * Preferences: the ladder is the root's preview handler, so it sees every key before the editor does. + */ +@OptIn(ExperimentalTestApi::class) +class KeybindingReassignKeysTest { + private val defaultJson = """{"input":{"keybinding":{"preset":"default","overrides":{}}}}""" + + /** + * Mounts the editor under a root that routes keys through the modal ladder, with Preferences marked open. + * + * @param ComposeUiTest test The running UI test. + * @param ShellOverlayState overlays The shell's overlay state. + * @param MutableList strokes Receives each key stroke the root sees, for the failure message. + * @return Settings The settings the editor writes its rebinds into. + */ + private fun mount(test: ComposeUiTest, overlays: ShellOverlayState, strokes: MutableList): Settings { + val fileSystem = FakeFileSystem() + fileSystem.createDirectories("/config".toPath()) + val settings = Settings.load(OkioAppStorage(fileSystem, "/config".toPath(), "/data".toPath()), defaultJson) + val registry = CommandRegistry() + registry.registerAll( + listOf( + Command("test.bound", title = Res.string.cmd_mesh_grab) {}, + Command("test.unbound", title = Res.string.cmd_preferences) {}, + Command("document.confirm", title = null) { argument -> (argument as? ConfirmRequest)?.let { request -> overlays.pendingConfirm = request } }, + ), + ) + val keymap = Keymap(mapOf(parseKeyChord("primary+KeyS")!! to "test.bound")) + val rootFocus = FocusRequester() + // One controller shared by the ladder and the editor, as the shell wires it. + val keyCapture = KeyCaptureController() + test.setContent { + UmamoTheme { + CompositionLocalProvider(LocalSettings provides settings, LocalCommands provides registry, LocalKeymap provides keymap, LocalKeyCapture provides keyCapture) { + Box( + modifier = + Modifier + .fillMaxSize() + .testTag("root") + .focusRequester(rootFocus) + .focusable() + .onPreviewKeyEvent { event -> + val stroke = event.toShellKeyStroke() + strokes += "${stroke.key} down=${stroke.isDown} confirm=${overlays.pendingConfirm != null}" + handleModalKeyLadder(stroke, ShellModalState(overlays = overlays, keyCapture = keyCapture, commandRegistry = registry, keymap = keymap)) + }, + ) { + if (overlays.settingsVisible) { + KeybindingsEditor() + } + overlays.pendingConfirm?.let { + ConfirmDialog( + message = "reassign?", + onConfirm = { overlays.confirmPending() }, + onCancel = { overlays.cancelPending() }, + confirmLabel = "Reassign", + cancelLabel = "Cancel", + ) + } + } + } + } + } + return settings + } + + /** + * Arms the unbound command's chip and presses Ctrl+S, which the other command already holds, so the reassign + * prompt is up. + * + * @param ComposeUiTest test The running UI test. + * @param ShellOverlayState overlays The shell's overlay state. + * @param List strokes The strokes seen so far, for the failure message. + */ + private fun raiseTheReassignPrompt(test: ComposeUiTest, overlays: ShellOverlayState, strokes: List) { + test.onNodeWithText("Unbound").performClick() + test.waitForIdle() + test.onNodeWithTag("root").performKeyInput { + keyDown(Key.CtrlLeft) + keyDown(Key.S) + keyUp(Key.S) + keyUp(Key.CtrlLeft) + } + test.waitForIdle() + assertNotNull(overlays.pendingConfirm, "the taken chord raises the reassign prompt; strokes: $strokes") + } + + /** + * Enter on the reassign prompt reassigns the chord and leaves Preferences open. The prompt only hears Enter + * at all because the chip keeps its focus node once the capture ends: with focus on nothing, no key reaches + * the shell. + */ + @Test + fun enterOnTheReassignPromptReassignsAndLeavesPreferencesOpen() { + runComposeUiTest { + val overlays = ShellOverlayState().apply { settingsVisible = true } + val strokes = mutableListOf() + val settings = mount(this, overlays, strokes) + raiseTheReassignPrompt(this, overlays, strokes) + + onNodeWithTag("root").performKeyInput { + keyDown(Key.Enter) + keyUp(Key.Enter) + } + waitForIdle() + + assertNull(overlays.pendingConfirm, "Enter answers the prompt; strokes: $strokes") + assertTrue(overlays.settingsVisible, "and Preferences stays open; strokes: $strokes") + assertEquals("test.unbound", loadKeymap(settings).commandFor(parseKeyChord("primary+KeyS")!!), "with the chord reassigned") + } + } + + /** Escape on the reassign prompt cancels the prompt alone: the confirm outranks the overlay it was raised over. */ + @Test + fun escapeOnTheReassignPromptCancelsItAndLeavesPreferencesOpen() { + runComposeUiTest { + val overlays = ShellOverlayState().apply { settingsVisible = true } + val strokes = mutableListOf() + val settings = mount(this, overlays, strokes) + raiseTheReassignPrompt(this, overlays, strokes) + + onNodeWithTag("root").performKeyInput { + keyDown(Key.Escape) + keyUp(Key.Escape) + } + waitForIdle() + + assertNull(overlays.pendingConfirm, "Escape cancels the prompt; strokes: $strokes") + assertTrue(overlays.settingsVisible, "and Preferences stays open; strokes: $strokes") + assertNotEquals("test.unbound", loadKeymap(settings).commandFor(parseKeyChord("primary+KeyS")!!), "with nothing rebound: no override was written") + } + } + + /** + * Escape while the chip is waiting for a key cancels the capture, not Preferences. The shell's root handler + * previews every key before the chip does, so without the capture announced to it the overlay arm takes the + * Escape and closes Preferences behind the chip. + */ + @Test + fun escapeWhileCapturingCancelsTheCaptureAndLeavesPreferencesOpen() { + runComposeUiTest { + val overlays = ShellOverlayState().apply { settingsVisible = true } + val strokes = mutableListOf() + mount(this, overlays, strokes) + + onNodeWithText("Unbound").performClick() + waitForIdle() + onNodeWithText("Press a shortcut…").assertExists() + onNodeWithTag("root").performKeyInput { + keyDown(Key.Escape) + keyUp(Key.Escape) + } + waitForIdle() + + assertTrue(overlays.settingsVisible, "Escape cancels the capture, not Preferences; strokes: $strokes") + onNodeWithText("Unbound").assertExists() + onNodeWithText("Press a shortcut…").assertDoesNotExist() + + // With the capture over, Escape is the overlay's again. + onNodeWithTag("root").performKeyInput { + keyDown(Key.Escape) + keyUp(Key.Escape) + } + waitForIdle() + assertFalse(overlays.settingsVisible, "a second Escape closes Preferences; strokes: $strokes") + } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/settings/QuickSetupDialogTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/settings/QuickSetupDialogTest.kt new file mode 100644 index 0000000..f09f60d --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/settings/QuickSetupDialogTest.kt @@ -0,0 +1,156 @@ +package org.umamo.ui.settings + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.click +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onFirst +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import org.jetbrains.compose.resources.stringResource +import org.umamo.settings.Settings +import org.umamo.storage.OkioAppStorage +import org.umamo.ui.LocalSettings +import org.umamo.ui.l10n.LOCALE_SETTINGS_KEY +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.quick_setup_continue +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The Quick Setup modal under real pointer input: its choices write through to settings as they are picked, + * and it closes from Continue or the scrim - never from a press on its own card. + */ +@OptIn(ExperimentalTestApi::class) +class QuickSetupDialogTest { + private val defaultJson = """{"localization":{"locale":"en"},"interface":{"theme":"dark"},"input":{"keybinding":{"preset":"default","overrides":{}}}}""" + + /** Picking a language from the row's dropdown writes it to settings at once, with nothing to commit. */ + @Test + fun pickingALanguageWritesItThrough() = + runComposeUiTest { + val settings = freshSettings() + mount(this, settings) {} + onAllNodesWithText("English", useUnmergedTree = true).onFirst().performClick() + onNodeWithText("日本語", useUnmergedTree = true).performClick() + waitForIdle() + assertEquals("ja", settings.getString(LOCALE_SETTINGS_KEY)) + } + + /** Continue closes the modal. */ + @Test + fun continueDismisses() = + runComposeUiTest { + var dismissCount = 0 + var continueLabel = "" + mount(this, freshSettings(), onContinueLabel = { label -> continueLabel = label }) { dismissCount++ } + onNodeWithText(continueLabel).performClick() + waitForIdle() + assertEquals(1, dismissCount) + } + + /** A press on the scrim closes it; a press on the card does not. */ + @Test + fun onlyTheScrimDismisses() = + runComposeUiTest { + var dismissCount = 0 + mount(this, freshSettings()) { dismissCount++ } + // The card is centered at no more than 560dp wide, so the window's middle is card and its corner is scrim. + onNodeWithTag(HOST_TAG).performMouseInput { click(center) } + waitForIdle() + assertEquals(0, dismissCount, "a press on the card is not a dismissal") + onNodeWithTag(HOST_TAG).performMouseInput { click(Offset(4f, 4f)) } + waitForIdle() + assertEquals(1, dismissCount, "a press on the scrim is") + } + + /** + * A wide window caps the card at 560dp: the space beside it inside the 90% band is scrim, not card. The cap + * is the case worth pinning - with the width modifiers in the wrong order the card silently fills 90%. + */ + @Test + fun aWideWindowCapsTheCard() = + runComposeUiTest { + var dismissCount = 0 + mount(this, freshSettings(), hostWidth = 900.dp) { dismissCount++ } + // The 900dp host's 90% band starts at 45dp; the capped 560dp card starts at 170dp. + onNodeWithTag(HOST_TAG).performMouseInput { click(Offset(200.dp.toPx(), centerY)) } + waitForIdle() + assertEquals(0, dismissCount, "inside the capped card") + onNodeWithTag(HOST_TAG).performMouseInput { click(Offset(100.dp.toPx(), centerY)) } + waitForIdle() + assertEquals(1, dismissCount, "beside the capped card, still inside the 90% band, is scrim") + } + + /** A narrow window gives the card 90% of its width, under the cap. */ + @Test + fun aNarrowWindowGivesTheCardNinetyPercent() = + runComposeUiTest { + var dismissCount = 0 + mount(this, freshSettings(), hostWidth = 400.dp) { dismissCount++ } + // The 400dp host's card spans 20dp to 380dp. + onNodeWithTag(HOST_TAG).performMouseInput { click(Offset(30.dp.toPx(), centerY)) } + waitForIdle() + assertEquals(0, dismissCount, "the card reaches past the 5% margin") + onNodeWithTag(HOST_TAG).performMouseInput { click(Offset(10.dp.toPx(), centerY)) } + waitForIdle() + assertEquals(1, dismissCount, "and the margin is scrim") + } + + /** + * Settings over an empty in-memory config directory - a first run's. + * + * @return Settings The loaded settings. + */ + private fun freshSettings(): Settings { + val fileSystem = FakeFileSystem() + fileSystem.createDirectories("/config".toPath()) + return Settings.load(OkioAppStorage(fileSystem, "/config".toPath(), "/data".toPath()), defaultJson) + } + + /** + * Mounts the modal over [settings] in a window-sized themed box. + * + * @param ComposeUiTest test The running UI test. + * @param Settings settings The settings the rows write through to. + * @param Dp hostWidth The stand-in window's width. + * @param Function onContinueLabel Receives the localized Continue label, resolved in composition. + * @param Function onDismiss The modal's dismissal. + */ + private fun mount( + test: ComposeUiTest, + settings: Settings, + hostWidth: Dp = 900.dp, + onContinueLabel: (String) -> Unit = {}, + onDismiss: () -> Unit, + ) { + test.setContent { + onContinueLabel(stringResource(Res.string.quick_setup_continue)) + UmamoTheme { + CompositionLocalProvider(LocalSettings provides settings) { + Box(modifier = Modifier.size(width = hostWidth, height = 700.dp).testTag(HOST_TAG)) { + QuickSetupDialog(onDismiss = onDismiss) + } + } + } + } + } + + private companion object { + const val HOST_TAG = "host" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackLaneInteractionTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackLaneInteractionTest.kt new file mode 100644 index 0000000..0362192 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackLaneInteractionTest.kt @@ -0,0 +1,724 @@ +package org.umamo.ui.tracks + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.MouseButton +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The lane's tap-versus-drag resolution, driven with real pointer input against a real composition. + * + * These paths are not reachable from a pure-function test: the lane decides between a click and a drag by + * reading one raw pointer stream, and every interaction bug reported against the keyform sheet so far has + * been in that decision or in the state it writes to - never in the pure projection the unit tests cover. + */ +class TrackLaneInteractionTest { + /** A sheet 400px wide over a -30..30 domain with marks at both ends and the middle. */ + private val axis = TrackAxis(-30f, 30f) + + private val rows = + listOf( + TrackRow( + key = "owner", + label = "Owner", + tone = TrackRowTone.Group, + children = + listOf( + TrackRow( + key = "owner/opacity", + label = "Opacity", + marks = listOf(TrackKeyMark(0, -30f), TrackKeyMark(1, 0f), TrackKeyMark(2, 30f)), + ), + ), + ), + ) + + /** + * A scrub survives its own side effects changing the marks underneath it. + * + * Pressing empty track drops the key selection, and a selection change rebuilds every mark (the flag + * lives on the mark). While the lane's gesture was KEYED on the marks, that press tore its own handler + * down mid-stroke: the drag froze at the press point and the release never arrived, so the scrub was + * never committed. This drives exactly that shape - the scrub callback mutates state the marks are + * built from - and asserts the stroke still finishes. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aScrubSurvivesItsOwnCallbackRebuildingTheMarks() = + runComposeUiTest { + var scrubEndedAt: Float? = null + var moves = 0 + setContent { + // Stands in for the key selection: the scrub clears it, and clearing it rebuilds the marks. + var selectedKeyIndex by remember { mutableStateOf(2) } + val liveRows = + listOf( + TrackRow( + key = "owner", + label = "Owner", + tone = TrackRowTone.Group, + children = + listOf( + TrackRow( + key = "owner/opacity", + label = "Opacity", + marks = + listOf(-30f, 0f, 30f).mapIndexed { keyIndex, position -> + TrackKeyMark(keyIndex, position, selected = keyIndex == selectedKeyIndex) + }, + ), + ), + ), + ) + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = liveRows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkClick = { _, _, _ -> }, + onTrackScrub = { _, _, _ -> + moves++ + selectedKeyIndex = null + }, + onTrackScrubEnd = { _, released -> scrubEndedAt = released }, + onMarkDragEnd = { _, _, _ -> }, + ) + } + } + // Press on empty track (a quarter across, clear of every mark), drag right, release. + onNodeWithTag("sheet").performMouseInput { + val laneStart = labelColumnEdge() + moveTo(Offset(laneStart + (width - laneStart) * 0.4f, childRowCenterY())) + press() + moveTo(Offset(laneStart + (width - laneStart) * 0.6f, childRowCenterY())) + moveTo(Offset(laneStart + (width - laneStart) * 0.7f, childRowCenterY())) + release() + } + waitForIdle() + assertTrue(moves > 1, "the drag must keep reporting after the press rebuilt the marks") + assertNotNull(scrubEndedAt, "and the release must still commit the scrub") + } + + /** A press-and-release on a mark reports it as a CLICK, not as a zero-length drag. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun pressingAMarkReportsAClick() = + runComposeUiTest { + var clicked: TrackKeyMark? = null + var trackClicked = false + var dragEnded: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkClick = { _, mark, _ -> clicked = mark }, + onTrackScrub = { _, _, _ -> trackClicked = true }, + onMarkDragEnd = { _, _, released -> dragEnded = released }, + ) + } + } + // The child row sits under the ruler and the group row; click the middle mark on it. + onNodeWithTag("sheet").performMouseInput { + val laneCenterX = (width + labelColumnEdge()) / 2f + moveTo(Offset(laneCenterX, childRowCenterY())) + press() + release() + } + waitForIdle() + assertNotNull(clicked, "a press on a mark must report a mark click") + assertEquals(0f, assertNotNull(clicked).position) + assertTrue(!trackClicked, "a mark click must not also read as an empty-track click") + assertNull(dragEnded, "a click is not a drag") + } + + /** + * A click reports whether SHIFT was held, on a mark and on empty track alike. + * + * The lane decides nothing about what additive means - only the owner holds a selection - so all that + * has to hold here is that the modifier survives the trip. It is sampled at the PRESS, so a Shift + * released before the button comes up still reads as an extend. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aClickReportsWhetherShiftWasHeld() = + runComposeUiTest { + val markAdditive = mutableListOf() + val trackAdditive = mutableListOf() + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkClick = { _, _, additive -> markAdditive.add(additive) }, + onTrackScrub = { _, _, additive -> trackAdditive.add(additive) }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + // The middle mark, at domain 0 - the same target the plain-click test uses. + moveTo(Offset((width + labelColumnEdge()) / 2f, childRowCenterY())) + press() + release() + } + waitForIdle() + assertEquals(listOf(false), markAdditive, "a plain click is not additive") + + onNodeWithTag("sheet").performKeyInput { keyDown(Key.ShiftLeft) } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset((width + labelColumnEdge()) / 2f, childRowCenterY())) + press() + release() + } + onNodeWithTag("sheet").performKeyInput { keyUp(Key.ShiftLeft) } + waitForIdle() + assertEquals(listOf(false, true), markAdditive, "a Shift+click is") + + // And the same on empty track, which is what lets a Shift+click that MISSES a mark decline to + // wipe the selection the user was building. + onNodeWithTag("sheet").performKeyInput { keyDown(Key.ShiftLeft) } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset(labelColumnEdge() + 20f, childRowCenterY())) + press() + release() + } + onNodeWithTag("sheet").performKeyInput { keyUp(Key.ShiftLeft) } + waitForIdle() + assertTrue(trackAdditive.isNotEmpty() && trackAdditive.all { additive -> additive }, "empty track too") + } + + /** A press on empty track reports an empty-track click carrying the domain value under the pointer. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun pressingEmptyTrackReportsTheDomainValue() = + runComposeUiTest { + var clicked: TrackKeyMark? = null + var trackValue: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkClick = { _, mark, _ -> clicked = mark }, + onTrackScrubEnd = { _, value -> trackValue = value }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + // A quarter of the way along the lane: nowhere near a mark at -30 / 0 / 30. + val laneStart = labelColumnEdge() + moveTo(Offset(laneStart + (width - laneStart) * 0.25f, childRowCenterY())) + press() + release() + } + waitForIdle() + assertNull(clicked, "a click away from every mark must not report a mark") + assertNotNull(trackValue, "an empty-track click must report where it landed") + } + + /** Dragging a mark reports the release position, so the caller can commit the move. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun draggingAMarkReportsItsReleasePosition() = + runComposeUiTest { + var draggedMark: TrackKeyMark? = null + var releasedAt: Float? = null + var clicked: TrackKeyMark? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkClick = { _, mark, _ -> clicked = mark }, + onMarkDragEnd = { _, mark, released -> + draggedMark = mark + releasedAt = released + }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + val laneCenterX = (width + labelColumnEdge()) / 2f + val rowY = childRowCenterY() + moveTo(Offset(laneCenterX, rowY)) + press() + moveTo(Offset(laneCenterX + 60f, rowY)) + moveTo(Offset(laneCenterX + 120f, rowY)) + release() + } + waitForIdle() + assertEquals(0f, assertNotNull(draggedMark).position, "the mark under the press is the one dragged") + assertNull(clicked, "a drag must not also report a click") + assertTrue(assertNotNull(releasedAt) > 0f, "releasing to the right must report a larger domain value") + } + + /** A secondary click over a mark resolves to THAT mark, so the menu can offer to remove it. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun rightClickingAMarkResolvesToIt() = + runComposeUiTest { + var hit: TrackLaneHit? = null + var markClicked = false + var trackClicked = false + setContent { + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .verticalScroll(rememberScrollState()), + ) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxWidth(), + expandedKeys = setOf("owner"), + // The tap handlers are live, as they are in the sheet: two pointer-input modifiers on + // one node is exactly what a secondary press has to survive. + onMarkClick = { _, _, _ -> markClicked = true }, + onTrackScrub = { _, _, _ -> trackClicked = true }, + onMarkDragEnd = { _, _, _ -> }, + laneMenuItems = { laneHit -> + hit = laneHit + emptyList() + }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + val laneCenterX = (width + labelColumnEdge()) / 2f + moveTo(Offset(laneCenterX, childRowCenterY())) + press(MouseButton.Secondary) + release(MouseButton.Secondary) + } + waitForIdle() + val resolved = assertNotNull(hit, "a secondary click must reach the lane's menu hook") + assertEquals(0f, assertNotNull(resolved.mark).position, "it must resolve to the mark under the pointer") + assertTrue(!markClicked, "a secondary press must not also scrub onto the mark") + } + + /** A secondary click away from every mark resolves to empty track, so the menu offers to insert. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun rightClickingEmptyTrackResolvesToNoMark() = + runComposeUiTest { + var hit: TrackLaneHit? = null + var markClicked = false + var trackClicked = false + setContent { + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .verticalScroll(rememberScrollState()), + ) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxWidth(), + expandedKeys = setOf("owner"), + // The tap handlers are live, as they are in the sheet: two pointer-input modifiers on + // one node is exactly what a secondary press has to survive. + onMarkClick = { _, _, _ -> markClicked = true }, + onTrackScrub = { _, _, _ -> trackClicked = true }, + onMarkDragEnd = { _, _, _ -> }, + laneMenuItems = { laneHit -> + hit = laneHit + emptyList() + }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + val laneStart = labelColumnEdge() + moveTo(Offset(laneStart + (width - laneStart) * 0.25f, childRowCenterY())) + press(MouseButton.Secondary) + release(MouseButton.Secondary) + } + waitForIdle() + assertNull(assertNotNull(hit, "a secondary click must reach the menu hook").mark) + assertTrue(!trackClicked, "a secondary press must not also clear the selection") + } + + /** A drag stops at the mark's neighbour instead of running past it and snapping back on release. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aDragIsClampedAtItsNeighbour() = + runComposeUiTest { + var releasedAt: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkDragEnd = { _, _, released -> releasedAt = released }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + // Grab the middle mark (at 0) and haul it far past the one at 30. + val laneCenterX = (width + labelColumnEdge()) / 2f + val rowY = childRowCenterY() + moveTo(Offset(laneCenterX, rowY)) + press() + moveTo(Offset(width + 500f, rowY)) + release() + } + waitForIdle() + assertEquals(30f, assertNotNull(releasedAt), "the drag must stop at the neighbour, not run past it") + } + + /** An endpoint drag stops at the axis end rather than leaving the track. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aDragIsClampedAtTheAxisEnd() = + runComposeUiTest { + var releasedAt: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onMarkDragEnd = { _, _, released -> releasedAt = released }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + // Grab the LAST mark (at 30, hard against the right edge) and haul it further right. + val rowY = childRowCenterY() + moveTo(Offset(width - 6f, rowY)) + press() + moveTo(Offset(width + 500f, rowY)) + release() + } + waitForIdle() + assertEquals(30f, assertNotNull(releasedAt), "an endpoint must stop at the axis end") + } + + /** Pressing empty track scrubs immediately, dragging keeps scrubbing, and releasing commits. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun draggingEmptyTrackScrubsContinuously() = + runComposeUiTest { + val scrubbed = mutableListOf() + var committedAt: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onTrackScrub = { _, value, _ -> scrubbed.add(value) }, + onTrackScrubEnd = { _, value -> committedAt = value }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + // Start a quarter along - nowhere near the marks at -30 / 0 / 30 - and drag right. + val laneStart = labelColumnEdge() + val startX = laneStart + (width - laneStart) * 0.25f + val rowY = childRowCenterY() + moveTo(Offset(startX, rowY)) + press() + moveTo(Offset(startX + 40f, rowY)) + moveTo(Offset(startX + 90f, rowY)) + release() + } + waitForIdle() + assertTrue(scrubbed.size >= 3, "the press and each move must scrub (got ${scrubbed.size})") + assertTrue(scrubbed.last() > scrubbed.first(), "dragging right must raise the scrubbed value") + assertEquals(scrubbed.last(), assertNotNull(committedAt), "the commit lands where the drag ended") + } + + /** + * A COLLAPSED group's summary mark is draggable, and reports its SUMMARY ordinal. + * + * That ordinal is the name its owner maps back to every child key stacked at that value, so one drag + * moves the whole stack instead of guessing at which channel was meant. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun summaryMarksAreDraggable() = + runComposeUiTest { + var draggedMark: TrackKeyMark? = null + var releasedAt: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + // COLLAPSED, so the group row draws its subtree's summary marks. + expandedKeys = emptySet(), + onMarkDragEnd = { _, mark, released -> + draggedMark = mark + releasedAt = released + }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + // The group row is the first line under the ruler, and its middle summary mark sits at 0. + val laneCenterX = (width + labelColumnEdge()) / 2f + val groupRowY = 20f + 16f + moveTo(Offset(laneCenterX, groupRowY)) + press() + moveTo(Offset(laneCenterX + 120f, groupRowY)) + release() + } + waitForIdle() + assertEquals(1, assertNotNull(draggedMark).keyIndex, "the middle of three summary marks") + assertTrue(assertNotNull(releasedAt) > 0f, "dragging right raises the destination") + } + + /** A scrub is clamped to the axis: dragging off the end of the track cannot push the pose out of range. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun anEmptyTrackScrubIsClampedToTheAxis() = + runComposeUiTest { + val scrubbed = mutableListOf() + var committedAt: Float? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onTrackScrub = { _, value, _ -> scrubbed.add(value) }, + onTrackScrubEnd = { _, value -> committedAt = value }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + val laneStart = labelColumnEdge() + val rowY = childRowCenterY() + // A quarter along, clear of the marks at -30 / 0 / 30, so this reads as a scrub. + moveTo(Offset(laneStart + (width - laneStart) * 0.25f, rowY)) + press() + // Far past the right edge of the lane, and then far past the left. + moveTo(Offset(width + 400f, rowY)) + moveTo(Offset(laneStart - 400f, rowY)) + release() + } + waitForIdle() + assertTrue(scrubbed.all { value -> value in -30f..30f }, "out of range: ${scrubbed.filter { it !in -30f..30f }}") + assertTrue(assertNotNull(committedAt) in -30f..30f, "the commit is in range too") + } + + /** + * Hover reports WHERE on the lane the pointer is, and which mark it is on, live as it moves. + * + * This is what `I` / `Alt+I` aim with over a track: pointing at a spot is a statement about which + * spot, so a row-level "the pointer is somewhere on this row" would not be enough to act on. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun hoverReportsThePositionAndMarkUnderThePointer() = + runComposeUiTest { + val hits = mutableListOf() + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onLaneHover = { _, hit -> hits.add(hit) }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + val laneStart = labelColumnEdge() + val rowY = childRowCenterY() + // A quarter along - clear of every mark - then onto the middle mark at 0. + moveTo(Offset(laneStart + (width - laneStart) * 0.25f, rowY)) + moveTo(Offset((width + laneStart) / 2f, rowY)) + } + waitForIdle() + val reported = hits.filterNotNull() + assertTrue(reported.size >= 2, "hover must report as the pointer moves, not once on enter") + assertNull(reported.first().mark, "a quarter along is clear of every mark") + assertEquals(0f, assertNotNull(reported.last().mark).position, "the middle mark is at 0") + assertTrue(reported.last().value > reported.first().value, "and the reported value follows the pointer") + } + + /** Leaving the lane reports null, so a stale target cannot outlive the pointer. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun leavingTheLaneClearsTheHover() = + runComposeUiTest { + val hits = mutableListOf() + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onLaneHover = { _, hit -> hits.add(hit) }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset((width + labelColumnEdge()) / 2f, childRowCenterY())) + // Up into the ruler, off every lane. + moveTo(Offset((width + labelColumnEdge()) / 2f, 4f)) + } + waitForIdle() + assertNull(hits.last(), "leaving the lane must clear what it reported") + } + + /** An armed marquee reports the region it enclosed, in window coordinates, and then disarms. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun anArmedMarqueeReportsItsRegion() = + runComposeUiTest { + var region: Rect? = null + var additive: Boolean? = null + var dismissed = false + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheetMarqueeOverlay( + armed = true, + onSelect = { enclosed, wasAdditive -> + region = enclosed + additive = wasAdditive + }, + onDismiss = { dismissed = true }, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset(100f, 40f)) + press() + moveTo(Offset(300f, 120f)) + release() + } + waitForIdle() + val enclosed = assertNotNull(region, "a drag must report its region") + assertEquals(200f, enclosed.width, "the region spans the drag horizontally") + assertEquals(80f, enclosed.height, "and vertically") + assertEquals(false, additive, "an unmodified drag replaces the selection") + assertTrue(dismissed, "and the marquee disarms itself afterwards") + } + + /** A marquee dragged up-and-left still reports an ascending rectangle. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aMarqueeNormalizesItsRegion() = + runComposeUiTest { + var region: Rect? = null + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheetMarqueeOverlay( + armed = true, + onSelect = { enclosed, _ -> region = enclosed }, + onDismiss = {}, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset(300f, 120f)) + press() + moveTo(Offset(100f, 40f)) + release() + } + waitForIdle() + val enclosed = assertNotNull(region) + assertTrue(enclosed.left < enclosed.right && enclosed.top < enclosed.bottom, "got $enclosed") + } + + /** A disarmed marquee is not in the way at all - it composes nothing and takes no pointer input. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aDisarmedMarqueeTakesNoInput() = + runComposeUiTest { + var region: Rect? = null + var trackScrubbed = false + setContent { + Box(modifier = Modifier.size(width = 600.dp, height = 200.dp).testTag("sheet")) { + TrackSheet( + rows = rows, + axis = axis, + playhead = null, + modifier = Modifier.fillMaxSize(), + expandedKeys = setOf("owner"), + onTrackScrub = { _, _, _ -> trackScrubbed = true }, + ) + TrackSheetMarqueeOverlay( + armed = false, + onSelect = { enclosed, _ -> region = enclosed }, + onDismiss = {}, + ) + } + } + onNodeWithTag("sheet").performMouseInput { + val laneStart = labelColumnEdge() + moveTo(Offset(laneStart + (width - laneStart) * 0.25f, childRowCenterY())) + press() + release() + } + waitForIdle() + assertNull(region, "a disarmed marquee reports nothing") + assertTrue(trackScrubbed, "and the lane underneath still gets its gesture") + } +} + +/** The x just right of the label column and its separator, in pixels. */ +private fun androidx.compose.ui.test.MouseInjectionScope.labelColumnEdge(): Float = 190f + +/** The y at the middle of the single child row: ruler, then the group row, then half a row. */ +private fun androidx.compose.ui.test.MouseInjectionScope.childRowCenterY(): Float = 20f + 32f + 16f \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackMarkSizeTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackMarkSizeTest.kt new file mode 100644 index 0000000..aecb180 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackMarkSizeTest.kt @@ -0,0 +1,114 @@ +package org.umamo.ui.tracks + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * That the drawn marks actually track the sheet's mark radius. + * + * A pixel test rather than a logic one, because the question it answers is exactly "does changing the + * radius change what is on screen" - a rendering fact no assertion over the geometry helpers alone can + * settle. + */ +class TrackMarkSizeTest { + /** A single track with one mark in the middle of its domain. */ + private val rows = + listOf(TrackRow(key = "track", label = "Track", marks = listOf(TrackKeyMark(0, 0f)))) + + /** Doubling the radius makes the drawn mark cover materially more pixels. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theDrawnMarkScalesWithTheRadius() { + val smallArea = markPixelCount(4.dp) + val largeArea = markPixelCount(12.dp) + assertTrue(smallArea > 0, "the small mark must draw at all (got $smallArea px)") + assertTrue( + largeArea > smallArea * 2, + "tripling the radius must grow the mark's area well past double (small=$smallArea large=$largeArea)", + ) + } + + /** + * The default render is exactly the [TRACK_MARK_RADIUS] render, and changing that constant changes it. + * + * Pins the whole chain the sheet actually uses - the constant, through TrackSheet's default argument + * and the lane's markRadiusPx, into drawMark - rather than only the explicit-argument path: a break + * anywhere in that chain would show only when the constant itself changes, not when a radius is passed + * explicitly, so the default path needs its own assertion rather than riding on the explicit one. + */ + @Test + fun theDefaultIsTheConstant() { + assertEquals( + markPixelCount(TRACK_MARK_RADIUS), + markPixelCount(null), + "omitting markRadius must draw exactly what TRACK_MARK_RADIUS draws", + ) + assertTrue( + markPixelCount(TRACK_MARK_RADIUS * 2f) > markPixelCount(null), + "doubling the constant must grow the drawn mark", + ) + } + + /** + * Renders one sheet at [markRadius] and counts the pixels the mark differs from the bare lane in. + * + * Differenced against a mark-less render rather than thresholded absolutely, so the count isolates the + * mark from the lane's tone band and baseline whatever the theme resolves those to. + * + * @param Dp? markRadius The radius to render at, or null to exercise the sheet's own default. + * @return Int The number of pixels the mark covers. + */ + @OptIn(ExperimentalTestApi::class) + private fun markPixelCount(markRadius: Dp?): Int { + var withMark: IntArray? = null + var without: IntArray? = null + for (drawMark in listOf(true, false)) { + runComposeUiTest { + setContent { + Box(modifier = Modifier.size(width = 400.dp, height = 60.dp).testTag("sheet")) { + val sheetRows = if (drawMark) rows else listOf(rows.single().copy(marks = emptyList())) + if (markRadius == null) { + TrackSheet( + rows = sheetRows, + axis = TrackAxis(-30f, 30f), + playhead = null, + modifier = Modifier.fillMaxSize(), + ) + } else { + TrackSheet( + rows = sheetRows, + axis = TrackAxis(-30f, 30f), + playhead = null, + modifier = Modifier.fillMaxSize(), + markRadius = markRadius, + ) + } + } + } + val image = onNodeWithTag("sheet").captureToImage() + val pixels = IntArray(image.width * image.height) + image.readPixels(pixels) + if (drawMark) { + withMark = pixels + } else { + without = pixels + } + } + } + val marked = requireNotNull(withMark) + val bare = requireNotNull(without) + return marked.indices.count { pixelIndex -> marked[pixelIndex] != bare[pixelIndex] } + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackWindowGestureTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackWindowGestureTest.kt new file mode 100644 index 0000000..5a41545 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/tracks/TrackWindowGestureTest.kt @@ -0,0 +1,208 @@ +package org.umamo.ui.tracks + +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.MouseButton +import androidx.compose.ui.test.ScrollWheel +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The sheet-wide zoom / pan gestures, driven with real pointer input over a real scroll container. + * + * The scroll container is the point: these gestures live on an ancestor of it, and the pass they claim + * events on is what decides whether the wheel zooms or merely scrolls, and whether a middle press reaches + * the pan at all or is eaten by the lanes underneath. None of that is visible without the ancestor + * relationship in place. + */ +class TrackWindowGestureTest { + /** A middle-button drag over the track region pans the window. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun middleDragPansTheWindow() = + runComposeUiTest { + var window by mutableStateOf(TrackWindow(0.4f, 0.6f)) + setContent { + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .trackWindowGestures( + window = window, + onWindowChange = { updated -> window = updated }, + labelColumnWidth = 100.dp, + ), + ) { + // A scrolling child, exactly as the sheet has: the gestures must beat it to the event. + Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())) { + Box(modifier = Modifier.size(width = 600.dp, height = 800.dp)) + } + } + } + onNodeWithTag("sheet").performMouseInput { + // Well right of the 100dp label column, then drag left, which moves the window right. + moveTo(Offset(400f, 100f)) + press(MouseButton.Tertiary) + moveTo(Offset(340f, 100f)) + moveTo(Offset(280f, 100f)) + release(MouseButton.Tertiary) + } + waitForIdle() + assertTrue(window.start > 0.4f, "dragging left must move the window right (got $window)") + assertTrue(window.span in 0.19f..0.21f, "a pan keeps the span (got ${window.span})") + } + + /** A middle-button drag over the LABEL column is not a pan - that region is not the track. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun middleDragOverTheLabelsDoesNothing() = + runComposeUiTest { + var window by mutableStateOf(TrackWindow(0.4f, 0.6f)) + setContent { + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .trackWindowGestures( + window = window, + onWindowChange = { updated -> window = updated }, + labelColumnWidth = 100.dp, + ), + ) { + Box(modifier = Modifier.fillMaxSize().height(200.dp)) + } + } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset(40f, 100f)) + press(MouseButton.Tertiary) + moveTo(Offset(20f, 100f)) + release(MouseButton.Tertiary) + } + waitForIdle() + assertTrue(window == TrackWindow(0.4f, 0.6f), "the label column does not pan (got $window)") + } + + /** Ctrl+wheel zooms in about the pointer, and takes the event so the sheet underneath does not scroll. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun ctrlWheelZoomsWithoutScrolling() = + runComposeUiTest { + var window by mutableStateOf(TrackWindow.Full) + lateinit var scrollState: ScrollState + setContent { + scrollState = rememberScrollState() + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .trackWindowGestures( + window = window, + onWindowChange = { updated -> window = updated }, + labelColumnWidth = 100.dp, + ), + ) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) { + Box(modifier = Modifier.size(width = 600.dp, height = 800.dp)) + } + } + } + onNodeWithTag("sheet").performMouseInput { moveTo(Offset(400f, 100f)) } + onNodeWithTag("sheet").performKeyInput { keyDown(Key.CtrlLeft) } + // Negative is wheel-UP, which zooms in; positive zooms out, and from a fully framed window + // that is correctly a no-op. + onNodeWithTag("sheet").performMouseInput { scroll(-1f) } + onNodeWithTag("sheet").performKeyInput { keyUp(Key.CtrlLeft) } + waitForIdle() + assertTrue(window.span < 1f, "Ctrl+wheel must zoom in (got $window)") + assertEquals(0, scrollState.value, "and must not also scroll the sheet") + } + + /** A plain wheel is left alone, so the sheet still scrolls vertically through its tracks. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun plainWheelStillScrolls() = + runComposeUiTest { + var window by mutableStateOf(TrackWindow.Full) + lateinit var scrollState: ScrollState + setContent { + scrollState = rememberScrollState() + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .trackWindowGestures( + window = window, + onWindowChange = { updated -> window = updated }, + labelColumnWidth = 100.dp, + ), + ) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) { + Box(modifier = Modifier.size(width = 600.dp, height = 800.dp)) + } + } + } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset(400f, 100f)) + scroll(1f) + } + waitForIdle() + assertEquals(TrackWindow.Full, window, "an unmodified wheel must not zoom") + assertTrue(scrollState.value > 0, "it scrolls the sheet instead") + } + + /** A horizontal wheel pans the tracks, with no modifier needed - nothing else uses that axis here. */ + @OptIn(ExperimentalTestApi::class) + @Test + fun horizontalWheelPansTheTracks() = + runComposeUiTest { + var window by mutableStateOf(TrackWindow(0.4f, 0.6f)) + setContent { + Box( + modifier = + Modifier + .size(width = 600.dp, height = 200.dp) + .testTag("sheet") + .trackWindowGestures( + window = window, + onWindowChange = { updated -> window = updated }, + labelColumnWidth = 100.dp, + ), + ) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())) { + Box(modifier = Modifier.size(width = 600.dp, height = 800.dp)) + } + } + } + onNodeWithTag("sheet").performMouseInput { + moveTo(Offset(400f, 100f)) + scroll(1f, ScrollWheel.Horizontal) + } + waitForIdle() + assertTrue(window.start > 0.4f, "a horizontal wheel must pan the window (got $window)") + assertTrue(window.span in 0.19f..0.21f, "and keep its span (got ${window.span})") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/AreaHeaderOverflowTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/AreaHeaderOverflowTest.kt new file mode 100644 index 0000000..aa382c5 --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/AreaHeaderOverflowTest.kt @@ -0,0 +1,158 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.umamo.runtime.model.PuppetModel +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.defaultKeymap +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test + +/** + * Every space's real header strip composes and lays out through the overflow row, at a comfortable width + * and at the narrowest an area can be dragged to. + * + * The kit tests drive OverflowRow with synthetic fixed-size items; this drives it with the actual + * headerContent builders through the actual registry, which is where the integration can break in ways a + * synthetic strip cannot show - a builder reading a CompositionLocal outside an item body, a duplicate + * slot key, or an intrinsic measurement the SubcomposeLayout cannot answer under the header's fixed + * height. All of those throw rather than look wrong, so composing at all is the assertion. + */ +class AreaHeaderOverflowTest { + /** Every space's header composes at a width no area can be dragged below. */ + @Test + fun everySpaceHeaderComposesAtTheMinimumAreaWidth() { + for (kind in SpaceKind.entries) { + composeHeader(kind = kind, headerWidth = MIN_AREA_WIDTH) + } + } + + /** Every space's header composes with room to spare, where nothing should collapse. */ + @Test + fun everySpaceHeaderComposesAtAComfortableWidth() { + for (kind in SpaceKind.entries) { + composeHeader(kind = kind, headerWidth = 900.dp) + } + } + + /** + * The 2D viewport's strip - the widest in the app - collapses into a usable panel when squeezed. + * + * Opening the panel is the part worth driving: it composes the collapsed builders a second time, in a + * popup, which is where a control that only works inside a Row would surface. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theViewportHeaderCollapsesIntoAnOpenablePanel() { + runComposeUiTest { + setHeader(kind = SpaceKind.Viewport2D, headerWidth = MIN_AREA_WIDTH) + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).assertExists() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + // The mode chip is pinned, so it is the one control that must still be on the strip itself. + onNodeWithContentDescription(OBJECT_MODE_LABEL, useUnmergedTree = true).assertExists() + } + } + + /** + * The Outliner keeps its search box AND its filter chip on the strip well before the area gets tight. + * + * Two regressions meet here. The chip's width used to be charged against every admission even when no + * chip would be shown, and the search box was a fixed 160.dp that took its natural width and pushed the + * filter into the dropdown - so the filter turned into an overflow chip with obvious slack still on the + * strip. 260.dp is comfortably tighter than a default panel and must still show both. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theOutlinerKeepsItsSearchAndFilterOnATightStrip() { + runComposeUiTest { + setHeader(kind = SpaceKind.Outliner, headerWidth = 260.dp, puppet = emptyPuppet()) + onNodeWithContentDescription(FILTERS_LABEL, useUnmergedTree = true).assertExists() + onNodeWithContentDescription(MORE_LABEL, useUnmergedTree = true).assertDoesNotExist() + } + } + + /** + * A document with no content - enough to satisfy the headers' open-document gate, which is all these + * layout assertions need. + * + * @return PuppetModel The empty document. + */ + private fun emptyPuppet(): PuppetModel = + PuppetModel( + parameters = emptyList(), + parts = emptyList(), + deformers = emptyList(), + drawables = emptyList(), + rootChildren = emptyList(), + rootPartId = null, + ) + + /** + * Composes one space's real header inside a fixed-width box and settles it. + * + * @param SpaceKind kind The space whose header strip to mount. + * @param Dp headerWidth The width the header is given. + */ + @OptIn(ExperimentalTestApi::class) + private fun composeHeader(kind: SpaceKind, headerWidth: Dp) { + runComposeUiTest { + setHeader(kind = kind, headerWidth = headerWidth) + } + } + + /** + * Mounts one space's real header, with the command registry and keymap its controls read. + * + * No puppet and no session are provided, which is the no-document state every header already handles - + * the viewport chips render disabled and the panel headers render nothing. + * + * @param SpaceKind kind The space whose header strip to mount. + * @param Dp headerWidth The width the header is given. + * @param PuppetModel? puppet The open document, or null for the no-document state. + */ + @OptIn(ExperimentalTestApi::class) + private fun ComposeUiTest.setHeader(kind: SpaceKind, headerWidth: Dp, puppet: PuppetModel? = null) { + setContent { + UmamoTheme { + CompositionLocalProvider( + LocalSpaceRegistry provides defaultSpaceRegistry(), + LocalCommands provides CommandRegistry(), + LocalKeymap provides defaultKeymap(), + LocalPuppet provides puppet, + ) { + Box(modifier = Modifier.width(headerWidth)) { + AreaHeader(area = LeafArea("area-1", kind), scope = AreaScope("area-1"), onCommand = {}) + } + } + } + } + waitForIdle() + } + + private companion object { + /** The narrowest an area tree lets a leaf become, so the tightest strip the shell can actually produce. */ + val MIN_AREA_WIDTH = 48.dp + + /** The overflow chip's English name; it doubles as its accessible label. */ + const val MORE_LABEL = "More" + + /** The pinned mode chip's English name, taken from its current mode with no document open. */ + const val OBJECT_MODE_LABEL = "Object Mode" + + /** The filter chip's English name; it doubles as its accessible label. */ + const val FILTERS_LABEL = "Filters" + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/AreaHoverStampTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/AreaHoverStampTest.kt new file mode 100644 index 0000000..5398efa --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/AreaHoverStampTest.kt @@ -0,0 +1,328 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.MouseInjectionScope +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.dp +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * The area tree's hovered-surface stamping, driven with real pointer input against a real composition. + * + * None of this is reachable from a pure test: the stamp is a pointer-input node, and every property that + * makes it trustworthy - that it covers every kind, that it follows a Change Editor Type, that a drag does + * not stamp the area it passes over, that a dying area stops claiming the pointer - is a property of + * Compose's dispatch rather than of any function we wrote. The routing tests in commonTest assert what + * the shell does with an answer; these assert the answer is right. + */ +class AreaHoverStampTest { + /** + * A registry with every real kind's title and icon but an empty body, so a leaf composes with no + * puppet, no renderer, and no space state. The stamp is on the leaf, not the space, so the real + * bodies are irrelevant to what is being measured here. + * + * @return SpaceRegistry The stub registry. + */ + private fun stubRegistry(): SpaceRegistry = + SpaceRegistry( + defaultSpaceRegistry().all.associate { descriptor -> + descriptor.kind to + SpaceDescriptor( + kind = descriptor.kind, + title = descriptor.title, + icon = descriptor.icon, + content = { Box(modifier = Modifier.fillMaxSize()) }, + ) + }, + ) + + /** + * Composes one leaf of [kind] under a tracker, drives [interact] against it, and returns what the + * tracker ended up holding. + * + * @param SpaceKind kind The space the leaf hosts. + * @param Function read Which stamp to report; the last-touched surface by default. + * @param Function interact The pointer input to drive. + * @return HoveredSurface? The stamped surface, or null if nothing stamped. + */ + @OptIn(ExperimentalTestApi::class) + private fun stampAfter( + kind: SpaceKind, + read: (HoveredSurfaceTracker) -> HoveredSurface? = { tracker -> tracker.lastTouched }, + interact: MouseInjectionScope.() -> Unit, + ): HoveredSurface? { + var result: HoveredSurface? = null + runComposeUiTest { + val tracker = HoveredSurfaceTracker() + setContent { + UmamoTheme { + CompositionLocalProvider( + LocalSpaceRegistry provides stubRegistry(), + LocalHoveredSurfaceTracker provides tracker, + ) { + Box(modifier = Modifier.size(400.dp, 300.dp).testTag("leaf")) { + AreaLeaf(area = LeafArea("area-1", kind), onCommand = {}) + } + } + } + } + onNodeWithTag("leaf").performMouseInput(interact) + result = read(tracker) + } + return result + } + + /** + * Only a work surface stamps the strip host: the operation settings strip exists in the 2D viewport + * and the UV editor alone, so a panel touched last must never become where a strip appears. Swept + * over the enum like the stamp itself, so a kind added later is classified by construction. + */ + @Test + fun onlyWorkSurfacesStampTheStripHost() { + for (kind in SpaceKind.entries) { + val expected = if (kind.hostsOperationStrip) HoveredSurface("area-1", kind) else null + assertEquals( + expected, + stampAfter(kind, { tracker -> tracker.lastTouchedStripHost }) { moveTo(Offset(200f, 200f)) }, + "${kind.name} stamped the strip host wrongly", + ) + } + } + + /** + * Every space kind stamps, not just the three editor surfaces that used to carry their own stamp. + * + * Swept over the whole enum because the point of moving the stamp to the leaf is that coverage stops + * being something a space author has to remember - a kind added later is covered by construction, and + * this fails if that ever stops being true. + */ + @Test + fun everySpaceKindStampsItsOwnArea() { + for (kind in SpaceKind.entries) { + assertEquals( + HoveredSurface("area-1", kind), + stampAfter(kind) { moveTo(Offset(200f, 200f)) }, + "${kind.name} did not stamp the hovered surface", + ) + } + } + + /** + * The area HEADER stamps too, which the per-space stamps never did. + * + * This is the case the whole change exists for: the outliner's search field lives in its header, so + * using it has to read as "the pointer is on the outliner" - otherwise the tracker keeps naming + * whichever viewport the pointer visited before, and a key pressed afterwards acts there. + */ + @Test + fun theHeaderStampsAsWellAsTheBody() { + // The header band is the leaf's top 28dp; 8px in is inside it and clear of the body. + assertEquals( + HoveredSurface("area-1", SpaceKind.Outliner), + stampAfter(SpaceKind.Outliner) { moveTo(Offset(200f, 8f)) }, + "hovering the header must claim the area", + ) + } + + /** Leaving an area does not clear the stamp - it means "last touched", which keeps shortcuts alive over chrome. */ + @Test + fun leavingAnAreaKeepsTheStamp() { + assertEquals( + HoveredSurface("area-1", SpaceKind.Properties), + stampAfter(SpaceKind.Properties) { + moveTo(Offset(200f, 200f)) + moveTo(Offset(-50f, -50f)) + }, + "an Exit must not clear the stamp", + ) + } + + /** + * The stamp follows a Change Editor Type. + * + * SwitchSpace rewrites the leaf's kind while leaving its id alone, and the tree keys leaf composition + * on that id - so the leaf survives the change. A pointer-input block keyed on the id alone would + * capture the original kind and keep reporting it forever; this is that bug's regression test. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theStampFollowsASpaceChange() = + runComposeUiTest { + val tracker = HoveredSurfaceTracker() + var switchToLogs: (() -> Unit)? = null + setContent { + var space by remember { mutableStateOf(SpaceKind.Outliner) } + switchToLogs = { space = SpaceKind.Logs } + UmamoTheme { + CompositionLocalProvider( + LocalSpaceRegistry provides stubRegistry(), + LocalHoveredSurfaceTracker provides tracker, + ) { + Box(modifier = Modifier.size(400.dp, 300.dp).testTag("leaf")) { + AreaLeaf(area = LeafArea("area-1", space), onCommand = {}) + } + } + } + } + onNodeWithTag("leaf").performMouseInput { moveTo(Offset(200f, 200f)) } + assertEquals(HoveredSurface("area-1", SpaceKind.Outliner), tracker.lastTouched) + + switchToLogs?.invoke() + waitForIdle() + onNodeWithTag("leaf").performMouseInput { moveTo(Offset(210f, 200f)) } + assertEquals( + HoveredSurface("area-1", SpaceKind.Logs), + tracker.lastTouched, + "the leaf kept its id across the switch, so a stamp keyed only on the id would still say Outliner", + ) + } + + /** + * Switching a work surface to a panel releases its strip-host claim at once, with no pointer event + * over the area: a document-wide command fired elsewhere right after the switch would otherwise be + * routed to an area whose host refuses a non-hosting kind, and its strip would show nowhere. The + * general stamp stays, since the area still exists, and takes the new kind on the same switch - a + * key pressed before the pointer moves acts in the space the area hosts now, and the status bar and + * the palette read that space too. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aSpaceChangeReleasesTheStripHostWithoutAPointerEvent() = + runComposeUiTest { + val tracker = HoveredSurfaceTracker() + var switchToLogs: (() -> Unit)? = null + setContent { + var space by remember { mutableStateOf(SpaceKind.Viewport2D) } + switchToLogs = { space = SpaceKind.Logs } + UmamoTheme { + CompositionLocalProvider( + LocalSpaceRegistry provides stubRegistry(), + LocalHoveredSurfaceTracker provides tracker, + ) { + Box(modifier = Modifier.size(400.dp, 300.dp).testTag("leaf")) { + AreaLeaf(area = LeafArea("area-1", space), onCommand = {}) + } + } + } + } + onNodeWithTag("leaf").performMouseInput { moveTo(Offset(200f, 200f)) } + assertEquals(HoveredSurface("area-1", SpaceKind.Viewport2D), tracker.lastTouchedStripHost) + + switchToLogs?.invoke() + waitForIdle() + assertNull(tracker.lastTouchedStripHost, "the strip-host claim is released by the switch itself") + assertEquals(HoveredSurface("area-1", SpaceKind.Logs), tracker.lastTouched, "the general stamp takes the new kind with no pointer event") + assertEquals(SpaceKind.Logs, tracker.observedKind, "and display chrome observes it") + + onNodeWithTag("leaf").performMouseInput { moveTo(Offset(210f, 200f)) } + assertEquals(HoveredSurface("area-1", SpaceKind.Logs), tracker.lastTouched) + assertNull(tracker.lastTouchedStripHost, "a panel never re-claims the strip host") + } + + /** + * A drag that starts in one area and crosses into another does not restamp. + * + * Compose hit-tests only unpressed pointers; a pressed one keeps the path captured at press. The whole + * design leans on that - an area-join drag or a modal transform crossing a neighbour must not hand the + * neighbour the pointer - and it would fail silently, so it is pinned rather than assumed. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aDragDoesNotStampTheAreaItCrossesInto() = + runComposeUiTest { + val tracker = HoveredSurfaceTracker() + setContent { + UmamoTheme { + CompositionLocalProvider( + LocalSpaceRegistry provides stubRegistry(), + LocalHoveredSurfaceTracker provides tracker, + ) { + Row(modifier = Modifier.size(400.dp, 300.dp).testTag("pair")) { + Box(modifier = Modifier.size(200.dp, 300.dp)) { + AreaLeaf(area = LeafArea("left", SpaceKind.Outliner), onCommand = {}) + } + Box(modifier = Modifier.size(200.dp, 300.dp)) { + AreaLeaf(area = LeafArea("right", SpaceKind.Logs), onCommand = {}) + } + } + } + } + } + // 300f is squarely inside the RIGHT leaf (the pair is 400px wide, split at 200f), so the drag + // genuinely crosses the boundary rather than wandering off the pair entirely. + onNodeWithTag("pair").performMouseInput { + moveTo(Offset(100f, 200f)) + press() + moveTo(Offset(300f, 200f)) + } + assertEquals( + HoveredSurface("left", SpaceKind.Outliner), + tracker.lastTouched, + "a pressed pointer keeps its captured path, so the right leaf must not claim it", + ) + + onNodeWithTag("pair").performMouseInput { + release() + moveTo(Offset(310f, 200f)) + } + assertEquals( + HoveredSurface("right", SpaceKind.Logs), + tracker.lastTouched, + "once released, an ordinary move stamps normally", + ) + } + + /** + * A disposed area stops claiming the pointer. + * + * Unlike leaving an area, a closed or joined one is gone - keeping its id would leave every downstream + * lookup resolving against something that no longer exists. The other per-area registries all evict on + * dispose; this one does too. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun aDisposedAreaReleasesTheStamp() = + runComposeUiTest { + val tracker = HoveredSurfaceTracker() + var closeArea: (() -> Unit)? = null + setContent { + var present by remember { mutableStateOf(true) } + closeArea = { present = false } + UmamoTheme { + CompositionLocalProvider( + LocalSpaceRegistry provides stubRegistry(), + LocalHoveredSurfaceTracker provides tracker, + ) { + Box(modifier = Modifier.size(400.dp, 300.dp).testTag("host")) { + if (present) { + AreaLeaf(area = LeafArea("area-1", SpaceKind.History), onCommand = {}) + } + } + } + } + } + onNodeWithTag("host").performMouseInput { moveTo(Offset(200f, 200f)) } + assertEquals(HoveredSurface("area-1", SpaceKind.History), tracker.lastTouched) + + closeArea?.invoke() + waitForIdle() + assertNull(tracker.lastTouched, "a closed area must not keep claiming the pointer") + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/ExportNoticeLabelsTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/ExportNoticeLabelsTest.kt new file mode 100644 index 0000000..a9daefb --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/ExportNoticeLabelsTest.kt @@ -0,0 +1,160 @@ +package org.umamo.ui.workspace + +import org.umamo.interop.ExportEntityCategory +import org.umamo.interop.ExportNoticeReason +import org.umamo.interop.KeyformBundleRejection +import org.umamo.runtime.model.FormChannel +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Pins the export report's localization coverage. + * + * The phrase mappings are exhaustive `when`s, so a reason with no sentence does not compile. What the + * compiler cannot catch is the two failure modes this covers: a reason whose sentence is a copy of + * another's (so the dialog explains the wrong thing), and a phrase whose argument count disagrees with + * its template's placeholders (so the dialog prints a literal %1$d). + * + * The sample list below is the forcing function for the first: a sealed interface has no `entries`, so + * coverage is checked against the reflected subclass list and a new case fails here until it is added. + */ +class ExportNoticeLabelsTest { + /** + * One instance of every [ExportNoticeReason] case. Field values are arbitrary - only the case + * identity and the argument count matter here. + */ + private val sampleReasons: List = + listOf( + ExportNoticeReason.DrawableHasNoMesh, + ExportNoticeReason.ChannelDemotedToStatic(FormChannel.OPACITY), + ExportNoticeReason.SketchPartIsNotRuntimeContent, + ExportNoticeReason.HiddenPartOmittedByExportOption, + ExportNoticeReason.HiddenDrawableOmittedByExportOption, + ExportNoticeReason.UnkeyedDrawableUnderDeformerHasNoParentGeometry, + ExportNoticeReason.RestMeshConversionSizeMismatch(6, 8), + ExportNoticeReason.NoAtlasPageBound, + ExportNoticeReason.ClippingMaskNotInExport(listOf("Mask01")), + ExportNoticeReason.OffscreenMaskNotInExport, + ExportNoticeReason.WarpDeformerHasNoLattice, + ExportNoticeReason.RotationDeformerHasNoPivot, + ExportNoticeReason.GlueNamesAnUnknownDrawable, + ExportNoticeReason.IdTruncated(64, "Param01"), + ExportNoticeReason.IdTruncatedAndDisambiguated(64, "Param01-2"), + ExportNoticeReason.NoMatchingSourceToReconcile, + ExportNoticeReason.ParameterKindChangeNotLowered, + ExportNoticeReason.DeformerKindChangeNotLowered, + ExportNoticeReason.DeformerEditNeedsWarpSource, + ExportNoticeReason.DeformerEditNeedsRotationSource, + ExportNoticeReason.TextureSourceRebindingIsEditorOnly, + ExportNoticeReason.BaseGeometryVertexCountMismatch, + ExportNoticeReason.NoUvsToReconcile, + ExportNoticeReason.DeformerHasNoPartToMoveTo, + ExportNoticeReason.StaticDrawOrderShadowedByKeyforms, + ExportNoticeReason.CompositeStaticsShadowedByKeyforms, + ExportNoticeReason.PartMasksFlattenToDrawables, + ExportNoticeReason.NoSourceSetToCreateInto, + ExportNoticeReason.CreatedEntityHasNoSourceYet, + ExportNoticeReason.CreatedGroupIsNotInTheEditedTree, + ExportNoticeReason.CreatedDrawableHasNoTextureSource, + ExportNoticeReason.GluedDrawableHasNoSource, + ExportNoticeReason.VertexCountExceedsEdgeTable(40000, 32767), + ExportNoticeReason.GluedMeshHasNoUidTable, + ExportNoticeReason.GluePairIndexesPastUidTable, + ExportNoticeReason.KeyformCannotBundle(KeyformBundleRejection.KeysOutsideGeometrySpan), + ExportNoticeReason.AxisParameterHasNoSource("ParamAngleX"), + ExportNoticeReason.BlendShapeParameterHasNoSource("ParamSmile"), + ExportNoticeReason.KeyformsWithoutBaseMesh, + ExportNoticeReason.FractionalDrawOrderNotStorable, + ExportNoticeReason.StaticGlueIntensityWithoutKeyforms, + ExportNoticeReason.NoAuthoredWorldOrigin, + ExportNoticeReason.NoRootParameterGroup, + ExportNoticeReason.NoRootPart, + ExportNoticeReason.NoParameterSourceSet, + ExportNoticeReason.CombinedPairReordered("ParamAngleX", "ParamAngleY"), + ExportNoticeReason.NoCanvasToReconcile, + ExportNoticeReason.FractionalCanvasSizeNotStorable, + ExportNoticeReason.NoTextureManagerToReconcile, + ExportNoticeReason.NoTextureInputForDisplayMode, + ExportNoticeReason.NoAtlasEntryToReconcile, + ExportNoticeReason.AtlasPageNotRecomposed, + ExportNoticeReason.AtlasTileMetadataNotReconcilable, + ExportNoticeReason.AtlasTileRebindingNotLowered, + ) + + private val sampleRejections: List = + listOf( + KeyformBundleRejection.KeysOutsideGeometrySpan, + KeyformBundleRejection.ChannelKeysWithoutGeometry, + KeyformBundleRejection.KeysOutsideChannelSpan(FormChannel.OPACITY), + ) + + @Test + fun everySampleCoversItsSealedHierarchy() { + val declaredReasons = ExportNoticeReason::class.sealedSubclasses.map { it.simpleName }.toSet() + val declaredRejections = KeyformBundleRejection::class.sealedSubclasses.map { it.simpleName }.toSet() + // Reflection over a sealed hierarchy yields an empty list when kotlin-reflect is off the test + // classpath, which would turn both assertions below into tautologies. Fail loudly instead. + assertTrue(declaredReasons.isNotEmpty(), "sealedSubclasses is empty; is kotlin-reflect missing?") + assertTrue(declaredRejections.isNotEmpty(), "sealedSubclasses is empty; is kotlin-reflect missing?") + + assertEquals( + declaredReasons, + sampleReasons.map { reason -> reason::class.simpleName }.toSet(), + "add the new ExportNoticeReason case to sampleReasons", + ) + assertEquals( + declaredRejections, + sampleRejections.map { rejection -> rejection::class.simpleName }.toSet(), + "add the new KeyformBundleRejection case to sampleRejections", + ) + } + + @Test + fun everyReasonMapsToADistinctSentence() { + val resources = sampleReasons.map { reason -> exportNoticeReasonPhrase(reason).resource } + assertEquals(sampleReasons.size, resources.toSet().size, "two reasons share one sentence") + + val categoryResources = + ExportEntityCategory.entries.map { category -> exportEntityCategoryLabelRes(category) } + assertEquals(ExportEntityCategory.entries.size, categoryResources.toSet().size) + } + + @Test + fun everyPhraseSuppliesExactlyThePlaceholdersItsTemplateHas() { + val placeholderCounts = placeholderCountsByKey() + for (reason in sampleReasons) { + val phrase = exportNoticeReasonPhrase(reason) + val key = phrase.resource.key + assertEquals( + placeholderCounts[key], + phrase.arguments.size, + "$key: template placeholders disagree with the arguments ${reason::class.simpleName} supplies", + ) + } + } + + /** + * The distinct `%N$` placeholder count of every string in the default catalog. + * + * Read from the source XML rather than the packed resource because the test needs the template + * text, which the runtime accessor only exposes through a Compose environment. + * + * @return Map The placeholder count per resource key. + */ + private fun placeholderCountsByKey(): Map { + val catalog = File("src/commonMain/composeResources/values/strings.xml") + assertTrue(catalog.isFile, "the default string catalog is missing at ${catalog.absolutePath}") + val text = catalog.readText() + val counts = HashMap() + val stringPattern = Regex("""(.*?)""", RegexOption.DOT_MATCHES_ALL) + val placeholderPattern = Regex("""%(\d+)\$""") + for (match in stringPattern.findAll(text)) { + val key = match.groupValues[1] + val body = match.groupValues[2] + counts[key] = placeholderPattern.findAll(body).map { it.groupValues[1] }.toSet().size + } + return counts + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/StatusBarLayoutTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/StatusBarLayoutTest.kt new file mode 100644 index 0000000..257749e --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/StatusBarLayoutTest.kt @@ -0,0 +1,173 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpRect +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.height +import androidx.compose.ui.unit.width +import org.jetbrains.compose.resources.stringResource +import org.umamo.edit.EditorMode +import org.umamo.edit.EditorSession +import org.umamo.edit.NoticePlacement +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.action.defaultKeymap +import org.umamo.ui.model.LocalEditorSession +import org.umamo.ui.model.LocalPuppet +import org.umamo.ui.model.noticeText +import org.umamo.ui.resources.Res +import org.umamo.ui.resources.status_bind_grab +import org.umamo.ui.resources.status_parts +import org.umamo.ui.theme.UmamoTheme +import org.umamo.ui.workspace.commands.commandFixtureSession +import org.umamo.ui.workspace.commands.everyCommandTable +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The status strip's layout under pressure, against a real composition. + * + * The hints are the one zone whose length follows the pointer, and the longest list the default keymap + * produces - six entries over a UV editor in Object mode - is wider than everything else on the strip. + * What is measured here is who gives way when the window cannot hold it all, which is a property of how + * the Row measures its children and so of nothing a pure test can reach. + */ +class StatusBarLayoutTest { + /** The notice every case shows, chosen only for being a status-bar notice with no arguments. */ + private val noticeKey = "notice.transform.onlyDrawables" + + /** + * What a composed strip resolved its localized text to, so the cases find their nodes by the strings + * the strip really shows rather than by an English literal. + * + * @property String hintFragment A label only the hint zone shows. + * @property String statsFragment An entry only the model stats show. + * @property String notice The transient notice's text. + */ + private class StripText(val hintFragment: String, val statsFragment: String, val notice: String) + + /** + * Composes the strip at a width the case controls, over an Object-mode session with the whole command + * table registered and the pointer on a UV editor - the longest hint list there is. + * + * @param ComposeUiTest test The running compose test. + * @param EditorSession session The session the strip reads. + * @param HoveredSurfaceTracker tracker The tracker the hint zone observes. + * @param Function barWidth Reads the width to lay the strip out at, as snapshot state. + * @return StripText The localized strings the strip shows, for finding its nodes. + */ + @OptIn(ExperimentalTestApi::class) + private fun composeStrip(test: ComposeUiTest, session: EditorSession, tracker: HoveredSurfaceTracker, barWidth: () -> Dp): StripText { + val registry = CommandRegistry() + everyCommandTable(session).forEach { command -> registry.register(command) } + var hintFragment = "" + var statsFragment = "" + var notice = "" + test.setContent { + hintFragment = stringResource(Res.string.status_bind_grab) + statsFragment = stringResource(Res.string.status_parts, 0) + notice = noticeText(noticeKey) + UmamoTheme { + CompositionLocalProvider( + LocalCommands provides registry, + LocalKeymap provides defaultKeymap(), + LocalHoveredSurfaceTracker provides tracker, + LocalEditorSession provides session, + LocalPuppet provides session.model.value, + ) { + Box(modifier = Modifier.width(barWidth())) { + StatusBar(modifier = Modifier.fillMaxWidth()) + } + } + } + } + test.waitForIdle() + return StripText(hintFragment, statsFragment, notice) + } + + /** + * The bounds of the one text node containing [fragment]. + * + * @param ComposeUiTest test The running compose test. + * @param String fragment Text only that node shows. + * @return DpRect The node's bounds in the root, unclipped. + */ + @OptIn(ExperimentalTestApi::class) + private fun boundsOf(test: ComposeUiTest, fragment: String): DpRect = + test.onNodeWithText(fragment, substring = true, useUnmergedTree = true).getUnclippedBoundsInRoot() + + /** + * When the window cannot hold the full hint list, the hints are cut and the model stats keep their + * whole width: a suggestion is worth less than a count the user is reading. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theHintsGiveWayBeforeTheStats() = + runComposeUiTest { + var barWidth by mutableStateOf(3000.dp) + val tracker = HoveredSurfaceTracker() + tracker.lastTouched = HoveredSurface("uv-1", SpaceKind.UvEditor) + val text = composeStrip(this, commandFixtureSession(EditorMode.Object), tracker) { barWidth } + + val roomyHints = boundsOf(this, text.hintFragment) + val roomyStats = boundsOf(this, text.statsFragment) + + // Room for the stats and about a third of the hints: the hints cannot fit, the stats can. + barWidth = roomyStats.width + roomyHints.width / 3 + waitForIdle() + val tightHints = boundsOf(this, text.hintFragment) + val tightStats = boundsOf(this, text.statsFragment) + + assertEquals(roomyStats.width, tightStats.width, "the stats keep their whole width") + assertEquals(roomyStats.height, tightStats.height, "and stay on one line") + assertTrue(tightHints.width < roomyHints.width, "the hints are what gets cut") + assertEquals(roomyHints.height, tightHints.height, "cut on one line, not wrapped inside the fixed-height strip") + assertTrue(tightHints.right <= tightStats.left, "and end before the stats begin") + assertTrue(tightStats.right <= barWidth, "with the stats still inside the window") + } + + /** + * The transient notice holds its place as the pointer crosses between spaces. The hint list under it + * changes length with every crossing, and a notice that slid sideways each time would read as a new + * message. + */ + @OptIn(ExperimentalTestApi::class) + @Test + fun theNoticeHoldsItsPlaceAsTheHintsChange() = + runComposeUiTest { + // The notice dismisses itself after a few seconds of the test clock, so the clock is stepped by + // hand and never that far. + mainClock.autoAdvance = false + val session = commandFixtureSession(EditorMode.Object) + val tracker = HoveredSurfaceTracker() + tracker.lastTouched = HoveredSurface("uv-1", SpaceKind.UvEditor) + val text = composeStrip(this, session, tracker) { 1600.dp } + session.emitNotice(noticeKey, NoticePlacement.StatusBar) + mainClock.advanceTimeBy(64L) + val overTheUvEditor = boundsOf(this, text.notice) + + // An outliner is offered only the two hints that belong everywhere: a much shorter list. + tracker.lastTouched = HoveredSurface("outliner-1", SpaceKind.Outliner) + mainClock.advanceTimeBy(64L) + val grabHints = onAllNodesWithText(text.hintFragment, substring = true, useUnmergedTree = true).fetchSemanticsNodes() + assertTrue(grabHints.isEmpty(), "the hint list must really have changed for this to mean anything") + + assertEquals(overTheUvEditor, boundsOf(this, text.notice)) + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/TextEntryReleaseInteractionTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/TextEntryReleaseInteractionTest.kt new file mode 100644 index 0000000..7523b0c --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/TextEntryReleaseInteractionTest.kt @@ -0,0 +1,339 @@ +package org.umamo.ui.workspace + +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.dp +import org.umamo.ui.action.Command +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.parseKeyChord +import org.umamo.ui.kit.InlineEditController +import org.umamo.ui.kit.InlineRenameField +import org.umamo.ui.kit.LocalInlineEditController +import org.umamo.ui.kit.NumberField +import org.umamo.ui.kit.SearchField +import org.umamo.ui.theme.UmamoTheme +import org.umamo.ui.workspace.commands.registerAll +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Drives the release under a miniature shell: a focusable root carrying the real modal ladder and the two + * pointer observers the shell installs, with real presses and real key events. + * + * The bug this pins let a header filter keep the keyboard for the rest of the session - undo and every + * other shortcut went quietly dead the moment someone typed in one, because nothing in the tree ever took + * focus back off a text field. + */ +@OptIn(ExperimentalTestApi::class) +class TextEntryReleaseInteractionTest { + /** The shell state one case shares between its composition and its assertions. */ + private class Harness { + val overlays = ShellOverlayState() + val controller = InlineEditController() + val registry = CommandRegistry() + val keymap = Keymap(mapOf(parseKeyChord("primary+KeyS")!! to SHORTCUT_COMMAND)) + val rootFocus = FocusRequester() + + /** How many times the bound chord reached the keymap, which is what "shortcuts work" means here. */ + var shortcutRuns = 0 + + /** Whether the root itself holds focus, so a release can be told from a focus left null. */ + var rootFocused by mutableStateOf(false) + + /** The filter query, hoisted so a case can assert the text outlived the release. */ + var query by mutableStateOf("") + + /** The value a number field committed, or null until it commits one. */ + var committedNumber: Float? = null + + /** The name an inline rename committed, and whether it cancelled instead. */ + var committedName: String? = null + var renameCancelled = false + } + + /** + * Mounts [content] under a root that behaves like the shell: the modal ladder previews every key, and + * the press observer hands focus back when a press lands away from a live text editor. An "elsewhere" + * target sits below the content, standing in for the panel a user clicks into next. + * + * @param ComposeUiTest test The running UI test. + * @param Harness harness The state this case shares with its composition. + * @param Function content The text entry under test. + */ + private fun mount(test: ComposeUiTest, harness: Harness, content: @Composable () -> Unit) { + harness.registry.registerAll(listOf(Command(SHORTCUT_COMMAND, title = null) { harness.shortcutRuns += 1 })) + test.setContent { + UmamoTheme { + CompositionLocalProvider(LocalInlineEditController provides harness.controller) { + Box( + modifier = + Modifier + .fillMaxSize() + .testTag(ROOT_TAG) + // Before the focus target it observes: after focusable() it reports whichever + // DESCENDANT holds focus, which would make every root-focus assertion here pass. + .onFocusChanged { focusState -> harness.rootFocused = focusState.isFocused } + .focusRequester(harness.rootFocus) + .focusable() + .pointerInput(Unit) { + observeTextEntryPresses( + beginPress = { harness.controller.pressLandedOnTextEditor = false }, + settlePress = { + val releases = + shouldReleaseTextEntry( + textEntryActive = harness.controller.cancel != null, + pressLandedOnTextEditor = harness.controller.pressLandedOnTextEditor, + selfFocusedOverlayOpen = harness.overlays.selfFocusedOverlayOpen, + ) + if (releases) { + harness.rootFocus.requestFocus() + } + }, + ) + } + .onPreviewKeyEvent { event -> + handleModalKeyLadder( + event.toShellKeyStroke(), + ShellModalState( + overlays = harness.overlays, + inlineEditController = harness.controller, + commandRegistry = harness.registry, + keymap = harness.keymap, + ), + ) + }, + ) { + Column { + content() + Box(modifier = Modifier.testTag(ELSEWHERE_TAG).size(ELSEWHERE_SIZE)) + } + } + } + } + } + } + + /** + * Mounts a header filter and types into it, leaving text entry live. + * + * @param ComposeUiTest test The running UI test. + * @param Harness harness The state this case shares with its composition. + */ + private fun typeInTheFilter(test: ComposeUiTest, harness: Harness) { + mount(test, harness) { + SearchField( + value = harness.query, + onValueChange = { edited -> harness.query = edited }, + modifier = Modifier.testTag(FIELD_TAG), + ) + } + test.onNodeWithTag(FIELD_TAG).performClick() + test.waitForIdle() + test.onNodeWithTag(FIELD_TAG).performTextInput(QUERY) + test.waitForIdle() + assertNotNull(harness.controller.cancel, "typing in the filter has to leave text entry live") + } + + /** The bug: after typing in a filter and pressing elsewhere, the shortcuts work again. */ + @Test + fun pressingElsewhereAfterTypingInAFilterRevivesTheShortcuts() { + runComposeUiTest { + val harness = Harness() + typeInTheFilter(this, harness) + onNodeWithTag(ROOT_TAG).performKeyInput { + keyDown(Key.CtrlLeft) + keyDown(Key.S) + keyUp(Key.S) + keyUp(Key.CtrlLeft) + } + waitForIdle() + assertEquals(0, harness.shortcutRuns, "a live text editor keeps the chord for itself") + + onNodeWithTag(ELSEWHERE_TAG).performClick() + waitForIdle() + assertNull(harness.controller.cancel, "a press away from the field has to end text entry") + + onNodeWithTag(ROOT_TAG).performKeyInput { + keyDown(Key.CtrlLeft) + keyDown(Key.S) + keyUp(Key.S) + keyUp(Key.CtrlLeft) + } + waitForIdle() + assertEquals(1, harness.shortcutRuns, "the chord has to reach the keymap once the field lets go") + } + } + + /** The release takes the keyboard, never the text: the filter still holds what was typed into it. */ + @Test + fun theFilterTextSurvivesTheRelease() { + runComposeUiTest { + val harness = Harness() + typeInTheFilter(this, harness) + onNodeWithTag(ELSEWHERE_TAG).performClick() + waitForIdle() + assertEquals(QUERY, harness.query, "the release must not touch what the field holds") + } + } + + /** A press on the field itself is a caret move: text entry survives it. */ + @Test + fun aPressInsideTheFieldKeepsTextEntryLive() { + runComposeUiTest { + val harness = Harness() + typeInTheFilter(this, harness) + onNodeWithTag(FIELD_TAG).performClick() + waitForIdle() + assertNotNull(harness.controller.cancel, "pressing the field you are typing in must not end text entry") + } + } + + /** The clear affordance rides inside the field, so pressing it clears the query and keeps the keyboard. */ + @Test + fun pressingTheClearAffordanceKeepsTextEntryLive() { + runComposeUiTest { + val harness = Harness() + typeInTheFilter(this, harness) + onNodeWithContentDescription(CLEAR_LABEL, useUnmergedTree = true).performClick() + waitForIdle() + assertEquals("", harness.query) + assertNotNull(harness.controller.cancel, "the clear button is part of the field, not somewhere else") + } + } + + /** After a release the root holds focus - a focus left null would kill the shortcuts just as dead. */ + @Test + fun aReleasedShellHasFocusRatherThanNull() { + runComposeUiTest { + val harness = Harness() + typeInTheFilter(this, harness) + assertFalse(harness.rootFocused, "the field owns the keyboard while it is being typed in") + onNodeWithTag(ELSEWHERE_TAG).performClick() + waitForIdle() + assertTrue(harness.rootFocused, "the release has to hand focus to the root, not clear it") + } + } + + /** Clicking away from an inline rename commits it, the way renaming a file in an explorer does. */ + @Test + fun anOutsidePressCommitsAnInlineRename() { + runComposeUiTest { + val harness = Harness() + mount(this, harness) { + InlineRenameField( + initialName = OLD_NAME, + textStyle = TextStyle.Default, + cursorColor = Color.Black, + onCommit = { committed -> harness.committedName = committed }, + onCancel = { harness.renameCancelled = true }, + modifier = Modifier.testTag(FIELD_TAG), + ) + } + waitForIdle() + onNodeWithTag(FIELD_TAG).performTextInput(NEW_NAME) + waitForIdle() + + onNodeWithTag(ELSEWHERE_TAG).performClick() + waitForIdle() + assertEquals(NEW_NAME, harness.committedName, "clicking away commits the typed name") + assertFalse(harness.renameCancelled, "clicking away must never run the cancel the shell parks for Escape") + } + } + + /** A number field commits its typed value on the way out, the same as the rename beside it. */ + @Test + fun anOutsidePressCommitsAHalfTypedNumber() { + runComposeUiTest { + val harness = Harness() + mount(this, harness) { + NumberField( + value = 0f, + onValueChange = { committed -> harness.committedNumber = committed }, + range = 0f..100f, + modifier = Modifier.testTag(FIELD_TAG), + plain = true, + ) + } + onNodeWithTag(FIELD_TAG).performClick() + waitForIdle() + // The tag rides the field's box; the typing action is on the text node inside it. Replacement, + // not insertion: typing into the value already shown would read as a number nobody typed. + onNode(hasSetTextAction()).performTextReplacement(TYPED_NUMBER) + waitForIdle() + + onNodeWithTag(ELSEWHERE_TAG).performClick() + waitForIdle() + assertEquals(TYPED_NUMBER.toFloat(), harness.committedNumber) + } + } + + /** + * An overlay that owns its own focus keeps it. The command palette parks the same hook from its own + * search box, and its list navigation lives on an ancestor of that box - releasing would take the + * arrows off the focus path while the palette is still open. + */ + @Test + fun aPressWhileASelfFocusedOverlayIsOpenKeepsItsFocus() { + runComposeUiTest { + val harness = Harness() + harness.overlays.paletteVisible = true + typeInTheFilter(this, harness) + onNodeWithTag(ELSEWHERE_TAG).performClick() + waitForIdle() + assertNotNull(harness.controller.cancel, "an open self-focused overlay keeps its own text entry") + } + } + + private companion object { + const val ROOT_TAG = "root" + const val FIELD_TAG = "field" + const val ELSEWHERE_TAG = "elsewhere" + + /** The command the bound chord runs, standing in for undo and the rest of the keymap. */ + const val SHORTCUT_COMMAND = "test.shortcut" + + const val QUERY = "hip" + const val OLD_NAME = "Old" + const val NEW_NAME = "New" + const val TYPED_NUMBER = "42" + + /** The clear button's English name; it doubles as its accessible label. */ + const val CLEAR_LABEL = "Clear search" + + /** Big enough to press without landing on the field above it. */ + val ELSEWHERE_SIZE = 40.dp + } +} \ No newline at end of file diff --git a/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/WorkspaceTabsInteractionTest.kt b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/WorkspaceTabsInteractionTest.kt new file mode 100644 index 0000000..56b354c --- /dev/null +++ b/module/ui/src/jvmTest/kotlin/org/umamo/ui/workspace/WorkspaceTabsInteractionTest.kt @@ -0,0 +1,158 @@ +package org.umamo.ui.workspace + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.click +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.v2.runComposeUiTest +import org.umamo.ui.action.CommandRegistry +import org.umamo.ui.action.Keymap +import org.umamo.ui.action.LocalCommands +import org.umamo.ui.action.LocalKeymap +import org.umamo.ui.theme.UmamoTheme +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The tab strip's press handling, driven with real pointer input: the double-click that opens the inline + * rename editor, and the reorder drag that shares its gesture. + * + * The strip's gesture is a long-lived pointerInput coroutine per tab slot, so what these pin is which + * workspace a slot's gesture believes it belongs to after the list underneath it has changed. + */ +@OptIn(ExperimentalTestApi::class) +class WorkspaceTabsInteractionTest { + /** The strip's state, shared between a case's composition and its assertions. */ + private class Harness { + var workspaces by mutableStateOf( + listOf(workspace("alpha", "Alpha"), workspace("bravo", "Bravo"), workspace("charlie", "Charlie")), + ) + var activeId by mutableStateOf("alpha") + } + + /** + * Mounts the tab strip over [harness], wired the way the shell wires it: selection and reorder write + * back to the harness state, and the context menu's commands resolve against an empty registry. + * + * @param ComposeUiTest test The running UI test. + * @param Harness harness The state this case shares with its composition. + */ + private fun mount(test: ComposeUiTest, harness: Harness) { + test.setContent { + UmamoTheme { + CompositionLocalProvider( + LocalCommands provides CommandRegistry(), + LocalKeymap provides Keymap(emptyMap()), + ) { + WorkspaceTabs( + workspaces = harness.workspaces, + activeId = harness.activeId, + onSelect = { workspaceId -> harness.activeId = workspaceId }, + onCreate = {}, + onDuplicate = { _, _ -> }, + onDelete = {}, + onReorder = { fromIndex, toIndex -> + val reordered = harness.workspaces.toMutableList() + reordered.add(toIndex, reordered.removeAt(fromIndex)) + harness.workspaces = reordered + }, + onRename = { _, _ -> }, + ) + } + } + } + } + + /** + * The names of every tab currently showing the inline rename editor. + * + * @param ComposeUiTest test The running UI test. + * @return List The editor's text for each open editor (empty when none is open). + */ + private fun openEditors(test: ComposeUiTest): List = + listOf("Alpha", "Bravo", "Charlie").filter { name -> + test.onAllNodes(hasSetTextAction() and hasText(name)).fetchSemanticsNodes().isNotEmpty() + } + + /** Two quick presses on a tab open that tab's rename editor. */ + @Test + fun doubleClickOpensTheClickedTabsEditor() = + runComposeUiTest { + val harness = Harness() + mount(this, harness) + onNodeWithText("Bravo").performMouseInput { + click() + advanceEventTime(100L) + click() + } + waitForIdle() + assertEquals(listOf("Bravo"), openEditors(this)) + } + + /** + * After the order changes underneath a slot, a double-click there renames the workspace the slot now + * shows. The slot's gesture outlives the change (same index, same tab count), so a gesture that captured + * its workspace when it started would open the editor on the tab that used to sit there. + */ + @Test + fun doubleClickAfterAReorderRenamesTheTabNowInThatSlot() = + runComposeUiTest { + val harness = Harness() + mount(this, harness) + // A first click starts slot 0's gesture while it still holds Alpha. + onNodeWithText("Alpha").performMouseInput { click() } + waitForIdle() + mainClock.advanceTimeBy(1_000L) + harness.workspaces = listOf(harness.workspaces[1], harness.workspaces[0], harness.workspaces[2]) + waitForIdle() + onNodeWithText("Bravo").performMouseInput { + click() + advanceEventTime(100L) + click() + } + waitForIdle() + assertEquals(listOf("Bravo"), openEditors(this), "the editor opens on the tab that was double-clicked") + } + + /** A press that became a reorder drag never pairs with the click after it as a double-click. */ + @Test + fun aClickRightAfterADragIsNotADoubleClick() = + runComposeUiTest { + val harness = Harness() + mount(this, harness) + onNodeWithText("Alpha").performMouseInput { + press() + // Past the reorder hold gate, then a nudge too small to change the order. + advanceEventTime(150L) + moveBy(Offset(2f, 0f)) + release() + advanceEventTime(50L) + click() + } + waitForIdle() + assertEquals(emptyList(), openEditors(this), "no rename editor opens") + assertEquals(1, onAllNodesWithText("Alpha").fetchSemanticsNodes().size) + } + + private companion object { + /** + * A named workspace over a single viewport leaf; the name keeps the label user data, so the tab shows + * it verbatim instead of resolving a localized title. + * + * @param String id The workspace id. + * @param String name The display name. + * @return Workspace The workspace. + */ + fun workspace(id: String, name: String): Workspace = + Workspace(id = id, root = LeafArea("leaf-$id", SpaceKind.Viewport2D), name = name) + } +} \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..a7a872e --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,51 @@ +// Settings script — the FIRST thing Gradle evaluates. Declares where plugins and +// dependencies are fetched from, and which subprojects make up the build. + +rootProject.name = "umamo" + +// `pluginManagement` controls plugin resolution. google() is required for the +// Android Gradle Plugin; gradlePluginPortal() for community plugins (ktlint). +pluginManagement { + // Umamo's own convention plugins (umamo.kmp-jvmandroid, umamo.kmp-ios-gate, umamo.test-corpus), + // as an included build rather than buildSrc: a buildSrc change invalidates the whole build's + // configuration cache, which is on for this project (see gradle.properties). + includeBuild("gradle/build-logic") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +// `dependencyResolutionManagement` centralises repositories for ALL modules, so no +// module declares its own — keeps the dependency supply chain auditable in one place. +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + } +} + +// Library modules live under module/, applications under app/. A module's Gradle PATH (e.g. +// ":format") is kept flat and deliberately independent of its DIRECTORY, so dependency +// declarations stay terse — project(":format"), not project(":module:format") — while the +// folder tree stays tidy. Path ≠ directory ≠ package: three separate things. +// (settings.gradle.kts is just Kotlin, so a local helper removes the repetition.) +fun includeAt(path: String, dir: String) { + include(path) + project(path).projectDir = file(dir) +} + +includeAt(":format", "module/format") +includeAt(":reimport", "module/reimport") +includeAt(":storage", "module/storage") +includeAt(":settings", "module/settings") +includeAt(":render", "module/render") +includeAt(":runtime", "module/runtime") +includeAt(":interop", "module/interop") +includeAt(":edit", "module/edit") +includeAt(":ui", "module/ui") +includeAt(":desktop", "app/desktop") +includeAt(":android", "app/android") +includeAt(":cli", "app/cli") \ No newline at end of file diff --git a/test/ret.psd b/test/ret.psd new file mode 100644 index 0000000..2bdee9e Binary files /dev/null and b/test/ret.psd differ